]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Accept destructuring form in catch clause
[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 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defvar js2-emacs22 (>= emacs-major-version 22))
176
177 (defcustom js2-highlight-level 2
178 "Amount of syntax highlighting to perform.
179 0 or a negative value means do no highlighting.
180 1 adds basic syntax highlighting.
181 2 adds highlighting of some Ecma built-in properties.
182 3 adds highlighting of many Ecma built-in functions."
183 :group 'js2-mode
184 :type '(choice (const :tag "None" 0)
185 (const :tag "Basic" 1)
186 (const :tag "Include Properties" 2)
187 (const :tag "Include Functions" 3)))
188
189 (defvar js2-mode-dev-mode-p nil
190 "Non-nil if running in development mode. Normally nil.")
191
192 (defgroup js2-mode nil
193 "An improved JavaScript mode."
194 :group 'languages)
195
196 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
197 (numberp c-basic-offset))
198 c-basic-offset
199 4)
200 "Number of spaces to indent nested statements.
201 Similar to `c-basic-offset'."
202 :group 'js2-mode
203 :type 'integer)
204 (make-variable-buffer-local 'js2-basic-offset)
205
206 ;; TODO(stevey): move this code into a separate minor mode.
207 (defcustom js2-mirror-mode nil
208 "Non-nil to insert closing brackets, parens, etc. automatically."
209 :group 'js2-mode
210 :type 'boolean)
211
212 (defcustom js2-auto-indent-p nil
213 "Automatic indentation with punctuation characters.
214 If non-nil, the current line is indented when certain punctuations
215 are inserted."
216 :group 'js2-mode
217 :type 'boolean)
218
219 (defcustom js2-bounce-indent-p nil
220 "Non-nil to have indent-line function choose among alternatives.
221 If nil, the indent-line function will indent to a predetermined column
222 based on heuristic guessing. If non-nil, then if the current line is
223 already indented to that predetermined column, indenting will choose
224 another likely column and indent to that spot. Repeated invocation of
225 the indent-line function will cycle among the computed alternatives.
226 See the function `js2-bounce-indent' for details."
227 :type 'boolean
228 :group 'js2-mode)
229
230 (defcustom js2-consistent-level-indent-inner-bracket-p t
231 "Non-nil to make indentation level inner bracket consistent,
232 regardless of the beginning bracket position."
233 :group 'js2-mode
234 :type 'boolean)
235
236 (defcustom js2-use-ast-for-indentation-p nil
237 "Non-nil to use AST for indentation and make it more robust."
238 :group 'js2-mode
239 :type 'boolean)
240
241 (defcustom js2-indent-on-enter-key nil
242 "Non-nil to have Enter/Return key indent the 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-enter-indents-newline nil
248 "Non-nil to have Enter/Return key indent the newly-inserted line.
249 This is unusual for Emacs modes but common in IDEs like Eclipse."
250 :type 'boolean
251 :group 'js2-mode)
252
253 (defcustom js2-rebind-eol-bol-keys t
254 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
255 If non-nil, bounce between bol/eol and first/last non-whitespace char."
256 :group 'js2-mode
257 :type 'boolean)
258
259 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
260 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
261 Each value in the list is passed to `define-key'."
262 :type 'list
263 :group 'js2-mode)
264
265 (defcustom js2-idle-timer-delay 0.2
266 "Delay in secs before re-parsing after user makes changes.
267 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
268 :type 'number
269 :group 'js2-mode)
270 (make-variable-buffer-local 'js2-idle-timer-delay)
271
272 (defcustom js2-dynamic-idle-timer-adjust 0
273 "Positive to adjust `js2-idle-timer-delay' based on file size.
274 The idea is that for short files, parsing is faster so we can be
275 more responsive to user edits without interfering with editing.
276 The buffer length in characters (typically bytes) is divided by
277 this value and used to multiply `js2-idle-timer-delay' for the
278 buffer. For example, a 21k file and 10k adjust yields 21k/10k
279 == 2, so js2-idle-timer-delay is multiplied by 2.
280 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
281 `js2-idle-timer-delay' is not dependent on the file size."
282 :type 'number
283 :group 'js2-mode)
284
285 (defcustom js2-mode-escape-quotes t
286 "Non-nil to disable automatic quote-escaping inside strings."
287 :type 'boolean
288 :group 'js2-mode)
289
290 (defcustom js2-mode-squeeze-spaces t
291 "Non-nil to normalize whitespace when filling in comments.
292 Multiple runs of spaces are converted to a single space."
293 :type 'boolean
294 :group 'js2-mode)
295
296 (defcustom js2-mode-show-parse-errors t
297 "True to highlight parse errors."
298 :type 'boolean
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-strict-warnings t
302 "Non-nil to emit Ecma strict-mode warnings.
303 Some of the warnings can be individually disabled by other flags,
304 even if this flag is non-nil."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-strict-trailing-comma-warning t
309 "Non-nil to warn about trailing commas in array literals.
310 Ecma-262 forbids them, but many browsers permit them. IE is the
311 big exception, and can produce bugs if you have trailing commas."
312 :type 'boolean
313 :group 'js2-mode)
314
315 (defcustom js2-strict-missing-semi-warning t
316 "Non-nil to warn about semicolon auto-insertion after statement.
317 Technically this is legal per Ecma-262, but some style guides disallow
318 depending on it."
319 :type 'boolean
320 :group 'js2-mode)
321
322 (defcustom js2-missing-semi-one-line-override nil
323 "Non-nil to permit missing semicolons in one-line functions.
324 In one-liner functions such as `function identity(x) {return x}'
325 people often omit the semicolon for a cleaner look. If you are
326 such a person, you can suppress the missing-semicolon warning
327 by setting this variable to t."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-inconsistent-return-warning t
332 "Non-nil to warn about mixing returns with value-returns.
333 It's perfectly legal to have a `return' and a `return foo' in the
334 same function, but it's often an indicator of a bug, and it also
335 interferes with type inference (in systems that support it.)"
336 :type 'boolean
337 :group 'js2-mode)
338
339 (defcustom js2-strict-cond-assign-warning t
340 "Non-nil to warn about expressions like if (a = b).
341 This often should have been '==' instead of '='. If the warning
342 is enabled, you can suppress it on a per-expression basis by
343 parenthesizing the expression, e.g. if ((a = b)) ..."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-cond-assign-warning t
348 "Non-nil to warn about expressions like if (a = b).
349 This often should have been '==' instead of '='. If the warning
350 is enabled, you can suppress it on a per-expression basis by
351 parenthesizing the expression, e.g. if ((a = b)) ..."
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-var-redeclaration-warning t
356 "Non-nil to warn about redeclaring variables in a script or function."
357 :type 'boolean
358 :group 'js2-mode)
359
360 (defcustom js2-strict-var-hides-function-arg-warning t
361 "Non-nil to warn about a var decl hiding a function argument."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-skip-preprocessor-directives nil
366 "Non-nil to treat lines beginning with # as comments.
367 Useful for viewing Mozilla JavaScript source code."
368 :type 'boolean
369 :group 'js2-mode)
370
371 (defcustom js2-language-version 180
372 "Configures what JavaScript language version to recognize.
373 Currently versions 150, 160, 170 and 180 are supported, corresponding
374 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
375 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
376 and 1.8 adds function closures."
377 :type 'integer
378 :group 'js2-mode)
379
380 (defcustom js2-allow-keywords-as-property-names t
381 "If non-nil, you can use JavaScript keywords as object property names.
382 Examples:
383
384 var foo = {int: 5, while: 6, continue: 7};
385 foo.return = 8;
386
387 Ecma-262 forbids this syntax, but many browsers support it."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-instanceof-has-side-effects nil
392 "If non-nil, treats the instanceof operator as having side effects.
393 This is useful for xulrunner apps."
394 :type 'boolean
395 :group 'js2-mode)
396
397 (defcustom js2-cleanup-whitespace nil
398 "Non-nil to invoke `delete-trailing-whitespace' before saves."
399 :type 'boolean
400 :group 'js2-mode)
401
402 (defcustom js2-move-point-on-right-click t
403 "Non-nil to move insertion point when you right-click.
404 This makes right-click context menu behavior a bit more intuitive,
405 since menu operations generally apply to the point. The exception
406 is if there is a region selection, in which case the point does -not-
407 move, so cut/copy/paste etc. can work properly.
408
409 Note that IntelliJ moves the point, and Eclipse leaves it alone,
410 so this behavior is customizable."
411 :group 'js2-mode
412 :type 'boolean)
413
414 (defcustom js2-allow-rhino-new-expr-initializer t
415 "Non-nil to support a Rhino's experimental syntactic construct.
416
417 Rhino supports the ability to follow a `new' expression with an object
418 literal, which is used to set additional properties on the new object
419 after calling its constructor. Syntax:
420
421 new <expr> [ ( arglist ) ] [initializer]
422
423 Hence, this expression:
424
425 new Object {a: 1, b: 2}
426
427 results in an Object with properties a=1 and b=2. This syntax is
428 apparently not configurable in Rhino - it's currently always enabled,
429 as of Rhino version 1.7R2."
430 :type 'boolean
431 :group 'js2-mode)
432
433 (defcustom js2-allow-member-expr-as-function-name nil
434 "Non-nil to support experimental Rhino syntax for function names.
435
436 Rhino supports an experimental syntax configured via the Rhino Context
437 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
438
439 function <member-expr> ( [ arg-list ] ) { <body> }
440
441 Where member-expr is a non-parenthesized 'member expression', which
442 is anything at the grammar level of a new-expression or lower, meaning
443 any expression that does not involve infix or unary operators.
444
445 When <member-expr> is not a simple identifier, then it is syntactic
446 sugar for assigning the anonymous function to the <member-expr>. Hence,
447 this code:
448
449 function a.b().c[2] (x, y) { ... }
450
451 is rewritten as:
452
453 a.b().c[2] = function(x, y) {...}
454
455 which doesn't seem particularly useful, but Rhino permits it."
456 :type 'boolean
457 :group 'js2-mode)
458
459 (defvar js2-mode-version 20101228
460 "Release number for `js2-mode'.")
461
462 ;; scanner variables
463
464 (defmacro js2-deflocal (name value &optional comment)
465 "Define a buffer-local variable NAME with VALUE and COMMENT."
466 `(progn
467 (defvar ,name ,value ,comment)
468 (make-variable-buffer-local ',name)))
469
470 ;; We record the start and end position of each token.
471 (js2-deflocal js2-token-beg 1)
472 (js2-deflocal js2-token-end -1)
473
474 (defvar js2-EOF_CHAR -1
475 "Represents end of stream. Distinct from js2-EOF token type.")
476
477 ;; I originally used symbols to represent tokens, but Rhino uses
478 ;; ints and then sets various flag bits in them, so ints it is.
479 ;; The upshot is that we need a `js2-' prefix in front of each name.
480 (defvar js2-ERROR -1)
481 (defvar js2-EOF 0)
482 (defvar js2-EOL 1)
483 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
484 (defvar js2-LEAVEWITH 3)
485 (defvar js2-RETURN 4)
486 (defvar js2-GOTO 5)
487 (defvar js2-IFEQ 6)
488 (defvar js2-IFNE 7)
489 (defvar js2-SETNAME 8)
490 (defvar js2-BITOR 9)
491 (defvar js2-BITXOR 10)
492 (defvar js2-BITAND 11)
493 (defvar js2-EQ 12)
494 (defvar js2-NE 13)
495 (defvar js2-LT 14)
496 (defvar js2-LE 15)
497 (defvar js2-GT 16)
498 (defvar js2-GE 17)
499 (defvar js2-LSH 18)
500 (defvar js2-RSH 19)
501 (defvar js2-URSH 20)
502 (defvar js2-ADD 21) ; infix plus
503 (defvar js2-SUB 22) ; infix minus
504 (defvar js2-MUL 23)
505 (defvar js2-DIV 24)
506 (defvar js2-MOD 25)
507 (defvar js2-NOT 26)
508 (defvar js2-BITNOT 27)
509 (defvar js2-POS 28) ; unary plus
510 (defvar js2-NEG 29) ; unary minus
511 (defvar js2-NEW 30)
512 (defvar js2-DELPROP 31)
513 (defvar js2-TYPEOF 32)
514 (defvar js2-GETPROP 33)
515 (defvar js2-GETPROPNOWARN 34)
516 (defvar js2-SETPROP 35)
517 (defvar js2-GETELEM 36)
518 (defvar js2-SETELEM 37)
519 (defvar js2-CALL 38)
520 (defvar js2-NAME 39) ; an identifier
521 (defvar js2-NUMBER 40)
522 (defvar js2-STRING 41)
523 (defvar js2-NULL 42)
524 (defvar js2-THIS 43)
525 (defvar js2-FALSE 44)
526 (defvar js2-TRUE 45)
527 (defvar js2-SHEQ 46) ; shallow equality (===)
528 (defvar js2-SHNE 47) ; shallow inequality (!==)
529 (defvar js2-REGEXP 48)
530 (defvar js2-BINDNAME 49)
531 (defvar js2-THROW 50)
532 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
533 (defvar js2-IN 52)
534 (defvar js2-INSTANCEOF 53)
535 (defvar js2-LOCAL_LOAD 54)
536 (defvar js2-GETVAR 55)
537 (defvar js2-SETVAR 56)
538 (defvar js2-CATCH_SCOPE 57)
539 (defvar js2-ENUM_INIT_KEYS 58)
540 (defvar js2-ENUM_INIT_VALUES 59)
541 (defvar js2-ENUM_INIT_ARRAY 60)
542 (defvar js2-ENUM_NEXT 61)
543 (defvar js2-ENUM_ID 62)
544 (defvar js2-THISFN 63)
545 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
546 (defvar js2-ARRAYLIT 65) ; array literal
547 (defvar js2-OBJECTLIT 66) ; object literal
548 (defvar js2-GET_REF 67) ; *reference
549 (defvar js2-SET_REF 68) ; *reference = something
550 (defvar js2-DEL_REF 69) ; delete reference
551 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
552 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
553 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
554
555 ;; XML support
556 (defvar js2-DEFAULTNAMESPACE 73)
557 (defvar js2-ESCXMLATTR 74)
558 (defvar js2-ESCXMLTEXT 75)
559 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
560 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
561 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
562 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
563
564 (defvar js2-first-bytecode js2-ENTERWITH)
565 (defvar js2-last-bytecode js2-REF_NS_NAME)
566
567 (defvar js2-TRY 80)
568 (defvar js2-SEMI 81) ; semicolon
569 (defvar js2-LB 82) ; left and right brackets
570 (defvar js2-RB 83)
571 (defvar js2-LC 84) ; left and right curly-braces
572 (defvar js2-RC 85)
573 (defvar js2-LP 86) ; left and right parens
574 (defvar js2-RP 87)
575 (defvar js2-COMMA 88) ; comma operator
576
577 (defvar js2-ASSIGN 89) ; simple assignment (=)
578 (defvar js2-ASSIGN_BITOR 90) ; |=
579 (defvar js2-ASSIGN_BITXOR 91) ; ^=
580 (defvar js2-ASSIGN_BITAND 92) ; &=
581 (defvar js2-ASSIGN_LSH 93) ; <<=
582 (defvar js2-ASSIGN_RSH 94) ; >>=
583 (defvar js2-ASSIGN_URSH 95) ; >>>=
584 (defvar js2-ASSIGN_ADD 96) ; +=
585 (defvar js2-ASSIGN_SUB 97) ; -=
586 (defvar js2-ASSIGN_MUL 98) ; *=
587 (defvar js2-ASSIGN_DIV 99) ; /=
588 (defvar js2-ASSIGN_MOD 100) ; %=
589
590 (defvar js2-first-assign js2-ASSIGN)
591 (defvar js2-last-assign js2-ASSIGN_MOD)
592
593 (defvar js2-HOOK 101) ; conditional (?:)
594 (defvar js2-COLON 102)
595 (defvar js2-OR 103) ; logical or (||)
596 (defvar js2-AND 104) ; logical and (&&)
597 (defvar js2-INC 105) ; increment/decrement (++ --)
598 (defvar js2-DEC 106)
599 (defvar js2-DOT 107) ; member operator (.)
600 (defvar js2-FUNCTION 108) ; function keyword
601 (defvar js2-EXPORT 109) ; export keyword
602 (defvar js2-IMPORT 110) ; import keyword
603 (defvar js2-IF 111) ; if keyword
604 (defvar js2-ELSE 112) ; else keyword
605 (defvar js2-SWITCH 113) ; switch keyword
606 (defvar js2-CASE 114) ; case keyword
607 (defvar js2-DEFAULT 115) ; default keyword
608 (defvar js2-WHILE 116) ; while keyword
609 (defvar js2-DO 117) ; do keyword
610 (defvar js2-FOR 118) ; for keyword
611 (defvar js2-BREAK 119) ; break keyword
612 (defvar js2-CONTINUE 120) ; continue keyword
613 (defvar js2-VAR 121) ; var keyword
614 (defvar js2-WITH 122) ; with keyword
615 (defvar js2-CATCH 123) ; catch keyword
616 (defvar js2-FINALLY 124) ; finally keyword
617 (defvar js2-VOID 125) ; void keyword
618 (defvar js2-RESERVED 126) ; reserved keywords
619
620 (defvar js2-EMPTY 127)
621
622 ;; Types used for the parse tree - never returned by scanner.
623
624 (defvar js2-BLOCK 128) ; statement block
625 (defvar js2-LABEL 129) ; label
626 (defvar js2-TARGET 130)
627 (defvar js2-LOOP 131)
628 (defvar js2-EXPR_VOID 132) ; expression statement in functions
629 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
630 (defvar js2-JSR 134)
631 (defvar js2-SCRIPT 135) ; top-level node for entire script
632 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
633 (defvar js2-USE_STACK 137)
634 (defvar js2-SETPROP_OP 138) ; x.y op= something
635 (defvar js2-SETELEM_OP 139) ; x[y] op= something
636 (defvar js2-LOCAL_BLOCK 140)
637 (defvar js2-SET_REF_OP 141) ; *reference op= something
638
639 ;; For XML support:
640 (defvar js2-DOTDOT 142) ; member operator (..)
641 (defvar js2-COLONCOLON 143) ; namespace::name
642 (defvar js2-XML 144) ; XML type
643 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
644 (defvar js2-XMLATTR 146) ; @
645 (defvar js2-XMLEND 147)
646
647 ;; Optimizer-only tokens
648 (defvar js2-TO_OBJECT 148)
649 (defvar js2-TO_DOUBLE 149)
650
651 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
652 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
653 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
654 (defvar js2-CONST 153)
655 (defvar js2-SETCONST 154)
656 (defvar js2-SETCONSTVAR 155)
657 (defvar js2-ARRAYCOMP 156)
658 (defvar js2-LETEXPR 157)
659 (defvar js2-WITHEXPR 158)
660 (defvar js2-DEBUGGER 159)
661
662 (defvar js2-COMMENT 160)
663 (defvar js2-ENUM 161) ; for "enum" reserved word
664
665 (defconst js2-num-tokens (1+ js2-ENUM))
666
667 (defconst js2-debug-print-trees nil)
668
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
672 ;; scanning them.
673
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
676
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
680
681 (js2-deflocal js2-ts-regexp-flags nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-string ""
685 "Token stream buffer-local variable.
686 Last string scanned.")
687
688 (js2-deflocal js2-ts-number nil
689 "Token stream buffer-local variable.
690 Last literal number scanned.")
691
692 (js2-deflocal js2-ts-hit-eof nil
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-line-start 0
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-lineno 1
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-line-end-char -1
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
705 "Token stream buffer-local variable.
706 Current scan position.")
707
708 (js2-deflocal js2-ts-is-xml-attribute nil
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-xml-is-tag-content nil
712 "Token stream buffer-local variable.")
713
714 (js2-deflocal js2-ts-xml-open-tags-count 0
715 "Token stream buffer-local variable.")
716
717 (js2-deflocal js2-ts-string-buffer nil
718 "Token stream buffer-local variable.
719 List of chars built up while scanning various tokens.")
720
721 (js2-deflocal js2-ts-comment-type nil
722 "Token stream buffer-local variable.")
723
724 ;;; Parser variables
725
726 (js2-deflocal js2-parsed-errors nil
727 "List of errors produced during scanning/parsing.")
728
729 (js2-deflocal js2-parsed-warnings nil
730 "List of warnings produced during scanning/parsing.")
731
732 (js2-deflocal js2-recover-from-parse-errors t
733 "Non-nil to continue parsing after a syntax error.
734
735 In recovery mode, the AST will be built in full, and any error
736 nodes will be flagged with appropriate error information. If
737 this flag is nil, a syntax error will result in an error being
738 signaled.
739
740 The variable is automatically buffer-local, because different
741 modes that use the parser will need different settings.")
742
743 (js2-deflocal js2-parse-hook nil
744 "List of callbacks for receiving parsing progress.")
745
746 (defvar js2-parse-finished-hook nil
747 "List of callbacks to notify when parsing finishes.
748 Not called if parsing was interrupted.")
749
750 (js2-deflocal js2-is-eval-code nil
751 "True if we're evaluating code in a string.
752 If non-nil, the tokenizer will record the token text, and the AST nodes
753 will record their source text. Off by default for IDE modes, since the
754 text is available in the buffer.")
755
756 (defvar js2-parse-ide-mode t
757 "Non-nil if the parser is being used for `js2-mode'.
758 If non-nil, the parser will set text properties for fontification
759 and the syntax table. The value should be nil when using the
760 parser as a frontend to an interpreter or byte compiler.")
761
762 ;;; Parser instance variables (buffer-local vars for js2-parse)
763
764 (defconst js2-clear-ti-mask #xFFFF
765 "Mask to clear token information bits.")
766
767 (defconst js2-ti-after-eol (lsh 1 16)
768 "Flag: first token of the source line.")
769
770 (defconst js2-ti-check-label (lsh 1 17)
771 "Flag: indicates to check for label.")
772
773 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
774
775 (js2-deflocal js2-compiler-generate-debug-info t)
776 (js2-deflocal js2-compiler-use-dynamic-scope nil)
777 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
778 (js2-deflocal js2-compiler-xml-available t)
779 (js2-deflocal js2-compiler-optimization-level 0)
780 (js2-deflocal js2-compiler-generating-source t)
781 (js2-deflocal js2-compiler-strict-mode nil)
782 (js2-deflocal js2-compiler-report-warning-as-error nil)
783 (js2-deflocal js2-compiler-generate-observer-count nil)
784 (js2-deflocal js2-compiler-activation-names nil)
785
786 ;; SKIP: sourceURI
787
788 ;; There's a compileFunction method in Context.java - may need it.
789 (js2-deflocal js2-called-by-compile-function nil
790 "True if `js2-parse' was called by `js2-compile-function'.
791 Will only be used when we finish implementing the interpreter.")
792
793 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
794
795 (js2-deflocal js2-current-flagged-token js2-EOF)
796 (js2-deflocal js2-current-token js2-EOF)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (defmacro js2-in-lhs (body)
807 `(let ((js2-is-in-lhs t))
808 ,body))
809
810 (defmacro js2-in-rhs (body)
811 `(let ((js2-is-in-lhs nil))
812 ,body))
813
814 (js2-deflocal js2-is-in-lhs nil
815 "True while parsing lhs statement")
816
817 (defcustom js2-global-externs nil
818 "A list of any extern names you'd like to consider always declared.
819 This list is global and is used by all js2-mode files.
820 You can create buffer-local externs list using `js2-additional-externs'.
821
822 There is also a buffer-local variable `js2-default-externs',
823 which is initialized by default to include the Ecma-262 externs
824 and the standard browser externs. The three lists are all
825 checked during highlighting."
826 :type 'list
827 :group 'js2-mode)
828
829 (js2-deflocal js2-default-externs nil
830 "Default external declarations.
831
832 These are currently only used for highlighting undeclared variables,
833 which only worries about top-level (unqualified) references.
834 As js2-mode's processing improves, we will flesh out this list.
835
836 The initial value is set to `js2-ecma-262-externs', unless you
837 have set `js2-include-browser-externs', in which case the browser
838 externs are also included.
839
840 See `js2-additional-externs' for more information.")
841
842 (defcustom js2-include-browser-externs t
843 "Non-nil to include browser externs in the master externs list.
844 If you work on JavaScript files that are not intended for browsers,
845 such as Mozilla Rhino server-side JavaScript, set this to nil.
846 You can always include them on a per-file basis by calling
847 `js2-add-browser-externs' from a function on `js2-mode-hook'.
848
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-rhino-externs t
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (defcustom js2-include-gears-externs t
860 "Non-nil to include Google Gears externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
862 :type 'boolean
863 :group 'js2-mode)
864
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
869
870 Each entry is a lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
873
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
878
879 Next, you can add a function to `js2-mode-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
882
883 Finally, you can add a function to `js2-post-parse-callbacks',
884 which is called after parsing completes, and `root' is bound to
885 the root of the parse tree. At this stage you can set up an AST
886 node visitor using `js2-visit-ast' and examine the parse tree
887 for specific import patterns that may imply the existence of
888 other externs, possibly tied to your build system. These should also
889 be added to `js2-additional-externs'.
890
891 Your post-parse callback may of course also use the simpler and
892 faster (but perhaps less robust) approach of simply scanning the
893 buffer text for your imports, using regular expressions.")
894
895 ;; SKIP: decompiler
896 ;; SKIP: encoded-source
897
898 ;;; The following variables are per-function and should be saved/restored
899 ;;; during function parsing...
900
901 (js2-deflocal js2-current-script-or-fn nil)
902 (js2-deflocal js2-current-scope nil)
903 (js2-deflocal js2-nesting-of-with 0)
904 (js2-deflocal js2-label-set nil
905 "An alist mapping label names to nodes.")
906
907 (js2-deflocal js2-loop-set nil)
908 (js2-deflocal js2-loop-and-switch-set nil)
909 (js2-deflocal js2-has-return-value nil)
910 (js2-deflocal js2-end-flags 0)
911
912 ;;; ...end of per function variables
913
914 ;; Without 2-token lookahead, labels are a problem.
915 ;; These vars store the token info of the last matched name,
916 ;; iff it wasn't the last matched token. Only valid in some contexts.
917 (defvar js2-prev-name-token-start nil)
918 (defvar js2-prev-name-token-string nil)
919
920 (defsubst js2-save-name-token-data (pos name)
921 (setq js2-prev-name-token-start pos
922 js2-prev-name-token-string name))
923
924 ;; These flags enumerate the possible ways a statement/function can
925 ;; terminate. These flags are used by endCheck() and by the Parser to
926 ;; detect inconsistent return usage.
927 ;;
928 ;; END_UNREACHED is reserved for code paths that are assumed to always be
929 ;; able to execute (example: throw, continue)
930 ;;
931 ;; END_DROPS_OFF indicates if the statement can transfer control to the
932 ;; next one. Statement such as return dont. A compound statement may have
933 ;; some branch that drops off control to the next statement.
934 ;;
935 ;; END_RETURNS indicates that the statement can return (without arguments)
936 ;; END_RETURNS_VALUE indicates that the statement can return a value.
937 ;;
938 ;; A compound statement such as
939 ;; if (condition) {
940 ;; return value;
941 ;; }
942 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
943
944 (defconst js2-end-unreached #x0)
945 (defconst js2-end-drops-off #x1)
946 (defconst js2-end-returns #x2)
947 (defconst js2-end-returns-value #x4)
948 (defconst js2-end-yields #x8)
949
950 ;; Rhino awkwardly passes a statementLabel parameter to the
951 ;; statementHelper() function, the main statement parser, which
952 ;; is then used by quite a few of the sub-parsers. We just make
953 ;; it a buffer-local variable and make sure it's cleaned up properly.
954 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
955
956 ;; Similarly, Rhino passes an inForInit boolean through about half
957 ;; the expression parsers. We use a dynamically-scoped variable,
958 ;; which makes it easier to funcall the parsers individually without
959 ;; worrying about whether they take the parameter or not.
960 (js2-deflocal js2-in-for-init nil)
961 (js2-deflocal js2-temp-name-counter 0)
962 (js2-deflocal js2-parse-stmt-count 0)
963
964 (defsubst js2-get-next-temp-name ()
965 (format "$%d" (incf js2-temp-name-counter)))
966
967 (defvar js2-parse-interruptable-p t
968 "Set this to nil to force parse to continue until finished.
969 This will mostly be useful for interpreters.")
970
971 (defvar js2-statements-per-pause 50
972 "Pause after this many statements to check for user input.
973 If user input is pending, stop the parse and discard the tree.
974 This makes for a smoother user experience for large files.
975 You may have to wait a second or two before the highlighting
976 and error-reporting appear, but you can always type ahead if
977 you wish. This appears to be more or less how Eclipse, IntelliJ
978 and other editors work.")
979
980 (js2-deflocal js2-record-comments t
981 "Instructs the scanner to record comments in `js2-scanned-comments'.")
982
983 (js2-deflocal js2-scanned-comments nil
984 "List of all comments from the current parse.")
985
986 (defcustom js2-mode-indent-inhibit-undo nil
987 "Non-nil to disable collection of Undo information when indenting lines.
988 Some users have requested this behavior. It's nil by default because
989 other Emacs modes don't work this way."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defcustom js2-mode-indent-ignore-first-tab nil
994 "If non-nil, ignore first TAB keypress if we look indented properly.
995 It's fairly common for users to navigate to an already-indented line
996 and press TAB for reassurance that it's been indented. For this class
997 of users, we want the first TAB press on a line to be ignored if the
998 line is already indented to one of the precomputed alternatives.
999
1000 This behavior is only partly implemented. If you TAB-indent a line,
1001 navigate to another line, and then navigate back, it fails to clear
1002 the last-indented variable, so it thinks you've already hit TAB once,
1003 and performs the indent. A full solution would involve getting on the
1004 point-motion hooks for the entire buffer. If we come across another
1005 use cases that requires watching point motion, I'll consider doing it.
1006
1007 If you set this variable to nil, then the TAB key will always change
1008 the indentation of the current line, if more than one alternative
1009 indentation spot exists."
1010 :type 'boolean
1011 :group 'js2-mode)
1012
1013 (defvar js2-indent-hook nil
1014 "A hook for user-defined indentation rules.
1015
1016 Functions on this hook should expect two arguments: (LIST INDEX)
1017 The LIST argument is the list of computed indentation points for
1018 the current line. INDEX is the list index of the indentation point
1019 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1020 indent function is not going to change the current line indentation.
1021
1022 If a hook function on this list returns a non-nil value, then
1023 `js2-bounce-indent' assumes the hook function has performed its own
1024 indentation, and will do nothing. If all hook functions on the list
1025 return nil, then `js2-bounce-indent' will use its computed indentation
1026 and reindent the line.
1027
1028 When hook functions on this hook list are called, the variable
1029 `js2-mode-ast' may or may not be set, depending on whether the
1030 parse tree is available. If the variable is nil, you can pass a
1031 callback to `js2-mode-wait-for-parse', and your callback will be
1032 called after the new parse tree is built. This can take some time
1033 in large files.")
1034
1035 (defface js2-warning-face
1036 `((((class color) (background light))
1037 (:underline "orange"))
1038 (((class color) (background dark))
1039 (:underline "orange"))
1040 (t (:underline t)))
1041 "Face for JavaScript warnings."
1042 :group 'js2-mode)
1043
1044 (defface js2-error-face
1045 `((((class color) (background light))
1046 (:foreground "red"))
1047 (((class color) (background dark))
1048 (:foreground "red"))
1049 (t (:foreground "red")))
1050 "Face for JavaScript errors."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-tag-face
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1056 :group 'js2-mode)
1057
1058 (defface js2-jsdoc-type-face
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-value-face
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1066 :group 'js2-mode)
1067
1068 (defface js2-function-param-face
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1071 :group 'js2-mode)
1072
1073 (defface js2-instance-member-face
1074 '((t :foreground "DarkOrchid"))
1075 "Face used to highlight instance variables in javascript.
1076 Not currently used."
1077 :group 'js2-mode)
1078
1079 (defface js2-private-member-face
1080 '((t :foreground "PeachPuff3"))
1081 "Face used to highlight calls to private methods in javascript.
1082 Not currently used."
1083 :group 'js2-mode)
1084
1085 (defface js2-private-function-call-face
1086 '((t :foreground "goldenrod"))
1087 "Face used to highlight calls to private functions in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-jsdoc-html-tag-name-face
1092 (if js2-emacs22
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "rosybrown"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "yellow"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "magenta")))
1099 '((((type tty pc) (class color) (background light))
1100 (:foreground "magenta"))
1101 (((type tty pc) (class color) (background dark))
1102 (:foreground "yellow"))
1103 (t (:foreground "RosyBrown"))))
1104 "Face used to highlight jsdoc html tag names"
1105 :group 'js2-mode)
1106
1107 (defface js2-jsdoc-html-tag-delimiter-face
1108 (if js2-emacs22
1109 '((((class color) (min-colors 88) (background light))
1110 (:foreground "dark khaki"))
1111 (((class color) (min-colors 8) (background dark))
1112 (:foreground "green"))
1113 (((class color) (min-colors 8) (background light))
1114 (:foreground "green")))
1115 '((((type tty pc) (class color) (background light))
1116 (:foreground "green"))
1117 (((type tty pc) (class color) (background dark))
1118 (:foreground "green"))
1119 (t (:foreground "dark khaki"))))
1120 "Face used to highlight brackets in jsdoc html tags."
1121 :group 'js2-mode)
1122
1123 (defface js2-magic-paren-face
1124 '((t :underline t))
1125 "Face used to color parens that will be auto-overwritten."
1126 :group 'js2-mode)
1127
1128 (defcustom js2-post-parse-callbacks nil
1129 "A list of callback functions invoked after parsing finishes.
1130 Currently, the main use for this function is to add synthetic
1131 declarations to `js2-recorded-identifiers', which see."
1132 :type 'list
1133 :group 'js2-mode)
1134
1135 (defface js2-external-variable-face
1136 '((t :foreground "orange"))
1137 "Face used to highlight undeclared variable identifiers.
1138 An undeclared variable is any variable not declared with var or let
1139 in the current scope or any lexically enclosing scope. If you use
1140 such a variable, then you are either expecting it to originate from
1141 another file, or you've got a potential bug."
1142 :group 'js2-mode)
1143
1144 (defcustom js2-highlight-external-variables t
1145 "Non-nil to highlight undeclared variable identifiers."
1146 :type 'boolean
1147 :group 'js2-mode)
1148
1149 (defcustom js2-auto-insert-catch-block t
1150 "Non-nil to insert matching catch block on open-curly after `try'."
1151 :type 'boolean
1152 :group 'js2-mode)
1153
1154 (defvar js2-mode-map
1155 (let ((map (make-sparse-keymap))
1156 keys)
1157 (define-key map [mouse-1] #'js2-mode-show-node)
1158 (define-key map (kbd "C-m") #'js2-enter-key)
1159 (when js2-rebind-eol-bol-keys
1160 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1161 (define-key map (kbd "C-e") #'js2-end-of-line))
1162 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1163 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1164 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1165 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1166 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1167 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1168 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1169 (define-key map (kbd "C-c C-`") #'js2-next-error)
1170 ;; also define user's preference for next-error, if available
1171 (if (setq keys (where-is-internal #'next-error))
1172 (define-key map (car keys) #'js2-next-error))
1173 (define-key map (or (car (where-is-internal #'mark-defun))
1174 (kbd "M-C-h"))
1175 #'js2-mark-defun)
1176 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1177 (kbd "C-x nd"))
1178 #'js2-narrow-to-defun)
1179 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1180 (when js2-auto-indent-p
1181 (mapc (lambda (key)
1182 (define-key map key #'js2-insert-and-indent))
1183 js2-electric-keys))
1184
1185 (define-key map [menu-bar javascript]
1186 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1187
1188 (define-key map [menu-bar javascript customize-js2-mode]
1189 '(menu-item "Customize js2-mode" js2-mode-customize
1190 :help "Customize the behavior of this mode"))
1191
1192 (define-key map [menu-bar javascript js2-force-refresh]
1193 '(menu-item "Force buffer refresh" js2-mode-reset
1194 :help "Re-parse the buffer from scratch"))
1195
1196 (define-key map [menu-bar javascript separator-2]
1197 '("--"))
1198
1199 (define-key map [menu-bar javascript next-error]
1200 '(menu-item "Next warning or error" js2-next-error
1201 :enabled (and js2-mode-ast
1202 (or (js2-ast-root-errors js2-mode-ast)
1203 (js2-ast-root-warnings js2-mode-ast)))
1204 :help "Move to next warning or error"))
1205
1206 (define-key map [menu-bar javascript display-errors]
1207 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1208 :visible (not js2-mode-show-parse-errors)
1209 :help "Turn on display of warnings and errors"))
1210
1211 (define-key map [menu-bar javascript hide-errors]
1212 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1213 :visible js2-mode-show-parse-errors
1214 :help "Turn off display of warnings and errors"))
1215
1216 (define-key map [menu-bar javascript separator-1]
1217 '("--"))
1218
1219 (define-key map [menu-bar javascript js2-toggle-function]
1220 '(menu-item "Show/collapse element" js2-mode-toggle-element
1221 :help "Hide or show function body or comment"))
1222
1223 (define-key map [menu-bar javascript show-comments]
1224 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1225 :visible js2-mode-comments-hidden
1226 :help "Expand all hidden block comments"))
1227
1228 (define-key map [menu-bar javascript hide-comments]
1229 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1230 :visible (not js2-mode-comments-hidden)
1231 :help "Show block comments as /*...*/"))
1232
1233 (define-key map [menu-bar javascript show-all-functions]
1234 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1235 :visible js2-mode-functions-hidden
1236 :help "Expand all hidden function bodies"))
1237
1238 (define-key map [menu-bar javascript hide-all-functions]
1239 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1240 :visible (not js2-mode-functions-hidden)
1241 :help "Show {...} for all top-level function bodies"))
1242
1243 map)
1244 "Keymap used in `js2-mode' buffers.")
1245
1246 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1247
1248 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1249 "Matches a //-comment line. Must be first non-whitespace on line.
1250 First match-group is the leading whitespace.")
1251
1252 (defvar js2-mode-hook nil)
1253
1254 (js2-deflocal js2-mode-ast nil "Private variable.")
1255 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1256 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1257 (js2-deflocal js2-mode-parsing nil "Private variable.")
1258 (js2-deflocal js2-mode-node-overlay nil)
1259
1260 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1261 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1262
1263 (js2-deflocal js2-mode-fontifications nil "Private variable")
1264 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1265 (js2-deflocal js2-imenu-recorder nil "Private variable")
1266 (js2-deflocal js2-imenu-function-map nil "Private variable")
1267 (js2-deflocal js2-imenu-fn-type-map nil "Private variable")
1268
1269 (defvar js2-paragraph-start
1270 "\\(@[a-zA-Z]+\\>\\|$\\)")
1271
1272 ;; Note that we also set a 'c-in-sws text property in html comments,
1273 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1274 (defvar js2-syntactic-ws-start
1275 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1276
1277 (defvar js2-syntactic-ws-end
1278 "\\s \\|[\n\r/]\\|\\s!")
1279
1280 (defvar js2-syntactic-eol
1281 (concat "\\s *\\(/\\*[^*\n\r]*"
1282 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1283 "\\*+/\\s *\\)*"
1284 "\\(//\\|/\\*[^*\n\r]*"
1285 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1286 "\\|\\\\$\\|$\\)")
1287 "Copied from `java-mode'. Needed for some cc-engine functions.")
1288
1289 (defvar js2-comment-prefix-regexp
1290 "//+\\|\\**")
1291
1292 (defvar js2-comment-start-skip
1293 "\\(//+\\|/\\*+\\)\\s *")
1294
1295 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1296 "Non-nil to emit status messages during parsing.")
1297
1298 (defvar js2-mode-functions-hidden nil "private variable")
1299 (defvar js2-mode-comments-hidden nil "private variable")
1300
1301 (defvar js2-mode-syntax-table
1302 (let ((table (make-syntax-table)))
1303 (c-populate-syntax-table table)
1304 table)
1305 "Syntax table used in js2-mode buffers.")
1306
1307 (defvar js2-mode-abbrev-table nil
1308 "Abbrev table in use in `js2-mode' buffers.")
1309 (define-abbrev-table 'js2-mode-abbrev-table ())
1310
1311 (defvar js2-mode-pending-parse-callbacks nil
1312 "List of functions waiting to be notified that parse is finished.")
1313
1314 (defvar js2-mode-last-indented-line -1)
1315
1316 ;;; Localizable error and warning messages
1317
1318 ;; Messages are copied from Rhino's Messages.properties.
1319 ;; Many of the Java-specific messages have been elided.
1320 ;; Add any js2-specific ones at the end, so we can keep
1321 ;; this file synced with changes to Rhino's.
1322
1323 (defvar js2-message-table
1324 (make-hash-table :test 'equal :size 250)
1325 "Contains localized messages for js2-mode.")
1326
1327 ;; TODO(stevey): construct this table at compile-time.
1328 (defmacro js2-msg (key &rest strings)
1329 `(puthash ,key (funcall #'concat ,@strings)
1330 js2-message-table))
1331
1332 (defun js2-get-msg (msg-key)
1333 "Look up a localized message.
1334 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1335 the correct number of ARGS must be provided."
1336 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1337 (args (if (listp msg-key) (cdr msg-key)))
1338 (msg (gethash key js2-message-table)))
1339 (if msg
1340 (apply #'format msg args)
1341 key))) ; default to showing the key
1342
1343 (js2-msg "msg.dup.parms"
1344 "Duplicate parameter name '%s'.")
1345
1346 (js2-msg "msg.too.big.jump"
1347 "Program too complex: jump offset too big.")
1348
1349 (js2-msg "msg.too.big.index"
1350 "Program too complex: internal index exceeds 64K limit.")
1351
1352 (js2-msg "msg.while.compiling.fn"
1353 "Encountered code generation error while compiling function '%s': %s")
1354
1355 (js2-msg "msg.while.compiling.script"
1356 "Encountered code generation error while compiling script: %s")
1357
1358 ;; Context
1359 (js2-msg "msg.ctor.not.found"
1360 "Constructor for '%s' not found.")
1361
1362 (js2-msg "msg.not.ctor"
1363 "'%s' is not a constructor.")
1364
1365 ;; FunctionObject
1366 (js2-msg "msg.varargs.ctor"
1367 "Method or constructor '%s' must be static "
1368 "with the signature (Context cx, Object[] args, "
1369 "Function ctorObj, boolean inNewExpr) "
1370 "to define a variable arguments constructor.")
1371
1372 (js2-msg "msg.varargs.fun"
1373 "Method '%s' must be static with the signature "
1374 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1375 "to define a variable arguments function.")
1376
1377 (js2-msg "msg.incompat.call"
1378 "Method '%s' called on incompatible object.")
1379
1380 (js2-msg "msg.bad.parms"
1381 "Unsupported parameter type '%s' in method '%s'.")
1382
1383 (js2-msg "msg.bad.method.return"
1384 "Unsupported return type '%s' in method '%s'.")
1385
1386 (js2-msg "msg.bad.ctor.return"
1387 "Construction of objects of type '%s' is not supported.")
1388
1389 (js2-msg "msg.no.overload"
1390 "Method '%s' occurs multiple times in class '%s'.")
1391
1392 (js2-msg "msg.method.not.found"
1393 "Method '%s' not found in '%s'.")
1394
1395 ;; IRFactory
1396
1397 (js2-msg "msg.bad.for.in.lhs"
1398 "Invalid left-hand side of for..in loop.")
1399
1400 (js2-msg "msg.mult.index"
1401 "Only one variable allowed in for..in loop.")
1402
1403 (js2-msg "msg.bad.for.in.destruct"
1404 "Left hand side of for..in loop must be an array of "
1405 "length 2 to accept key/value pair.")
1406
1407 (js2-msg "msg.cant.convert"
1408 "Can't convert to type '%s'.")
1409
1410 (js2-msg "msg.bad.assign.left"
1411 "Invalid assignment left-hand side.")
1412
1413 (js2-msg "msg.bad.decr"
1414 "Invalid decerement operand.")
1415
1416 (js2-msg "msg.bad.incr"
1417 "Invalid increment operand.")
1418
1419 (js2-msg "msg.bad.yield"
1420 "yield must be in a function.")
1421
1422 (js2-msg "msg.yield.parenthesized"
1423 "yield expression must be parenthesized.")
1424
1425 ;; NativeGlobal
1426 (js2-msg "msg.cant.call.indirect"
1427 "Function '%s' must be called directly, and not by way of a "
1428 "function of another name.")
1429
1430 (js2-msg "msg.eval.nonstring"
1431 "Calling eval() with anything other than a primitive "
1432 "string value will simply return the value. "
1433 "Is this what you intended?")
1434
1435 (js2-msg "msg.eval.nonstring.strict"
1436 "Calling eval() with anything other than a primitive "
1437 "string value is not allowed in strict mode.")
1438
1439 (js2-msg "msg.bad.destruct.op"
1440 "Invalid destructuring assignment operator")
1441
1442 ;; NativeCall
1443 (js2-msg "msg.only.from.new"
1444 "'%s' may only be invoked from a `new' expression.")
1445
1446 (js2-msg "msg.deprec.ctor"
1447 "The '%s' constructor is deprecated.")
1448
1449 ;; NativeFunction
1450 (js2-msg "msg.no.function.ref.found"
1451 "no source found to decompile function reference %s")
1452
1453 (js2-msg "msg.arg.isnt.array"
1454 "second argument to Function.prototype.apply must be an array")
1455
1456 ;; NativeGlobal
1457 (js2-msg "msg.bad.esc.mask"
1458 "invalid string escape mask")
1459
1460 ;; NativeRegExp
1461 (js2-msg "msg.bad.quant"
1462 "Invalid quantifier %s")
1463
1464 (js2-msg "msg.overlarge.backref"
1465 "Overly large back reference %s")
1466
1467 (js2-msg "msg.overlarge.min"
1468 "Overly large minimum %s")
1469
1470 (js2-msg "msg.overlarge.max"
1471 "Overly large maximum %s")
1472
1473 (js2-msg "msg.zero.quant"
1474 "Zero quantifier %s")
1475
1476 (js2-msg "msg.max.lt.min"
1477 "Maximum %s less than minimum")
1478
1479 (js2-msg "msg.unterm.quant"
1480 "Unterminated quantifier %s")
1481
1482 (js2-msg "msg.unterm.paren"
1483 "Unterminated parenthetical %s")
1484
1485 (js2-msg "msg.unterm.class"
1486 "Unterminated character class %s")
1487
1488 (js2-msg "msg.bad.range"
1489 "Invalid range in character class.")
1490
1491 (js2-msg "msg.trail.backslash"
1492 "Trailing \\ in regular expression.")
1493
1494 (js2-msg "msg.re.unmatched.right.paren"
1495 "unmatched ) in regular expression.")
1496
1497 (js2-msg "msg.no.regexp"
1498 "Regular expressions are not available.")
1499
1500 (js2-msg "msg.bad.backref"
1501 "back-reference exceeds number of capturing parentheses.")
1502
1503 (js2-msg "msg.bad.regexp.compile"
1504 "Only one argument may be specified if the first "
1505 "argument to RegExp.prototype.compile is a RegExp object.")
1506
1507 ;; Parser
1508 (js2-msg "msg.got.syntax.errors"
1509 "Compilation produced %s syntax errors.")
1510
1511 (js2-msg "msg.var.redecl"
1512 "TypeError: redeclaration of var %s.")
1513
1514 (js2-msg "msg.const.redecl"
1515 "TypeError: redeclaration of const %s.")
1516
1517 (js2-msg "msg.let.redecl"
1518 "TypeError: redeclaration of variable %s.")
1519
1520 (js2-msg "msg.parm.redecl"
1521 "TypeError: redeclaration of formal parameter %s.")
1522
1523 (js2-msg "msg.fn.redecl"
1524 "TypeError: redeclaration of function %s.")
1525
1526 (js2-msg "msg.let.decl.not.in.block"
1527 "SyntaxError: let declaration not directly within block")
1528
1529 ;; NodeTransformer
1530 (js2-msg "msg.dup.label"
1531 "duplicated label")
1532
1533 (js2-msg "msg.undef.label"
1534 "undefined label")
1535
1536 (js2-msg "msg.bad.break"
1537 "unlabelled break must be inside loop or switch")
1538
1539 (js2-msg "msg.continue.outside"
1540 "continue must be inside loop")
1541
1542 (js2-msg "msg.continue.nonloop"
1543 "continue can only use labels of iteration statements")
1544
1545 (js2-msg "msg.bad.throw.eol"
1546 "Line terminator is not allowed between the throw "
1547 "keyword and throw expression.")
1548
1549 (js2-msg "msg.no.paren.parms"
1550 "missing ( before function parameters.")
1551
1552 (js2-msg "msg.no.parm"
1553 "missing formal parameter")
1554
1555 (js2-msg "msg.no.paren.after.parms"
1556 "missing ) after formal parameters")
1557
1558 (js2-msg "msg.no.brace.body"
1559 "missing '{' before function body")
1560
1561 (js2-msg "msg.no.brace.after.body"
1562 "missing } after function body")
1563
1564 (js2-msg "msg.no.paren.cond"
1565 "missing ( before condition")
1566
1567 (js2-msg "msg.no.paren.after.cond"
1568 "missing ) after condition")
1569
1570 (js2-msg "msg.no.semi.stmt"
1571 "missing ; before statement")
1572
1573 (js2-msg "msg.missing.semi"
1574 "missing ; after statement")
1575
1576 (js2-msg "msg.no.name.after.dot"
1577 "missing name after . operator")
1578
1579 (js2-msg "msg.no.name.after.coloncolon"
1580 "missing name after :: operator")
1581
1582 (js2-msg "msg.no.name.after.dotdot"
1583 "missing name after .. operator")
1584
1585 (js2-msg "msg.no.name.after.xmlAttr"
1586 "missing name after .@")
1587
1588 (js2-msg "msg.no.bracket.index"
1589 "missing ] in index expression")
1590
1591 (js2-msg "msg.no.paren.switch"
1592 "missing ( before switch expression")
1593
1594 (js2-msg "msg.no.paren.after.switch"
1595 "missing ) after switch expression")
1596
1597 (js2-msg "msg.no.brace.switch"
1598 "missing '{' before switch body")
1599
1600 (js2-msg "msg.bad.switch"
1601 "invalid switch statement")
1602
1603 (js2-msg "msg.no.colon.case"
1604 "missing : after case expression")
1605
1606 (js2-msg "msg.double.switch.default"
1607 "double default label in the switch statement")
1608
1609 (js2-msg "msg.no.while.do"
1610 "missing while after do-loop body")
1611
1612 (js2-msg "msg.no.paren.for"
1613 "missing ( after for")
1614
1615 (js2-msg "msg.no.semi.for"
1616 "missing ; after for-loop initializer")
1617
1618 (js2-msg "msg.no.semi.for.cond"
1619 "missing ; after for-loop condition")
1620
1621 (js2-msg "msg.in.after.for.name"
1622 "missing in after for")
1623
1624 (js2-msg "msg.no.paren.for.ctrl"
1625 "missing ) after for-loop control")
1626
1627 (js2-msg "msg.no.paren.with"
1628 "missing ( before with-statement object")
1629
1630 (js2-msg "msg.no.paren.after.with"
1631 "missing ) after with-statement object")
1632
1633 (js2-msg "msg.no.paren.after.let"
1634 "missing ( after let")
1635
1636 (js2-msg "msg.no.paren.let"
1637 "missing ) after variable list")
1638
1639 (js2-msg "msg.no.curly.let"
1640 "missing } after let statement")
1641
1642 (js2-msg "msg.bad.return"
1643 "invalid return")
1644
1645 (js2-msg "msg.no.brace.block"
1646 "missing } in compound statement")
1647
1648 (js2-msg "msg.bad.label"
1649 "invalid label")
1650
1651 (js2-msg "msg.bad.var"
1652 "missing variable name")
1653
1654 (js2-msg "msg.bad.var.init"
1655 "invalid variable initialization")
1656
1657 (js2-msg "msg.no.colon.cond"
1658 "missing : in conditional expression")
1659
1660 (js2-msg "msg.no.paren.arg"
1661 "missing ) after argument list")
1662
1663 (js2-msg "msg.no.bracket.arg"
1664 "missing ] after element list")
1665
1666 (js2-msg "msg.bad.prop"
1667 "invalid property id")
1668
1669 (js2-msg "msg.no.colon.prop"
1670 "missing : after property id")
1671
1672 (js2-msg "msg.no.brace.prop"
1673 "missing } after property list")
1674
1675 (js2-msg "msg.no.paren"
1676 "missing ) in parenthetical")
1677
1678 (js2-msg "msg.reserved.id"
1679 "identifier is a reserved word")
1680
1681 (js2-msg "msg.no.paren.catch"
1682 "missing ( before catch-block condition")
1683
1684 (js2-msg "msg.bad.catchcond"
1685 "invalid catch block condition")
1686
1687 (js2-msg "msg.catch.unreachable"
1688 "any catch clauses following an unqualified catch are unreachable")
1689
1690 (js2-msg "msg.no.brace.try"
1691 "missing '{' before try block")
1692
1693 (js2-msg "msg.no.brace.catchblock"
1694 "missing '{' before catch-block body")
1695
1696 (js2-msg "msg.try.no.catchfinally"
1697 "'try' without 'catch' or 'finally'")
1698
1699 (js2-msg "msg.no.return.value"
1700 "function %s does not always return a value")
1701
1702 (js2-msg "msg.anon.no.return.value"
1703 "anonymous function does not always return a value")
1704
1705 (js2-msg "msg.return.inconsistent"
1706 "return statement is inconsistent with previous usage")
1707
1708 (js2-msg "msg.generator.returns"
1709 "TypeError: generator function '%s' returns a value")
1710
1711 (js2-msg "msg.anon.generator.returns"
1712 "TypeError: anonymous generator function returns a value")
1713
1714 (js2-msg "msg.syntax"
1715 "syntax error")
1716
1717 (js2-msg "msg.unexpected.eof"
1718 "Unexpected end of file")
1719
1720 (js2-msg "msg.XML.bad.form"
1721 "illegally formed XML syntax")
1722
1723 (js2-msg "msg.XML.not.available"
1724 "XML runtime not available")
1725
1726 (js2-msg "msg.too.deep.parser.recursion"
1727 "Too deep recursion while parsing")
1728
1729 (js2-msg "msg.no.side.effects"
1730 "Code has no side effects")
1731
1732 (js2-msg "msg.extra.trailing.comma"
1733 "Trailing comma is not legal in an ECMA-262 object initializer")
1734
1735 (js2-msg "msg.array.trailing.comma"
1736 "Trailing comma yields different behavior across browsers")
1737
1738 (js2-msg "msg.equal.as.assign"
1739 (concat "Test for equality (==) mistyped as assignment (=)?"
1740 " (parenthesize to suppress warning)"))
1741
1742 (js2-msg "msg.var.hides.arg"
1743 "Variable %s hides argument")
1744
1745 (js2-msg "msg.destruct.assign.no.init"
1746 "Missing = in destructuring declaration")
1747
1748 ;; ScriptRuntime
1749 (js2-msg "msg.no.properties"
1750 "%s has no properties.")
1751
1752 (js2-msg "msg.invalid.iterator"
1753 "Invalid iterator value")
1754
1755 (js2-msg "msg.iterator.primitive"
1756 "__iterator__ returned a primitive value")
1757
1758 (js2-msg "msg.assn.create.strict"
1759 "Assignment to undeclared variable %s")
1760
1761 (js2-msg "msg.ref.undefined.prop"
1762 "Reference to undefined property '%s'")
1763
1764 (js2-msg "msg.prop.not.found"
1765 "Property %s not found.")
1766
1767 (js2-msg "msg.invalid.type"
1768 "Invalid JavaScript value of type %s")
1769
1770 (js2-msg "msg.primitive.expected"
1771 "Primitive type expected (had %s instead)")
1772
1773 (js2-msg "msg.namespace.expected"
1774 "Namespace object expected to left of :: (found %s instead)")
1775
1776 (js2-msg "msg.null.to.object"
1777 "Cannot convert null to an object.")
1778
1779 (js2-msg "msg.undef.to.object"
1780 "Cannot convert undefined to an object.")
1781
1782 (js2-msg "msg.cyclic.value"
1783 "Cyclic %s value not allowed.")
1784
1785 (js2-msg "msg.is.not.defined"
1786 "'%s' is not defined.")
1787
1788 (js2-msg "msg.undef.prop.read"
1789 "Cannot read property '%s' from %s")
1790
1791 (js2-msg "msg.undef.prop.write"
1792 "Cannot set property '%s' of %s to '%s'")
1793
1794 (js2-msg "msg.undef.prop.delete"
1795 "Cannot delete property '%s' of %s")
1796
1797 (js2-msg "msg.undef.method.call"
1798 "Cannot call method '%s' of %s")
1799
1800 (js2-msg "msg.undef.with"
1801 "Cannot apply 'with' to %s")
1802
1803 (js2-msg "msg.isnt.function"
1804 "%s is not a function, it is %s.")
1805
1806 (js2-msg "msg.isnt.function.in"
1807 "Cannot call property %s in object %s. "
1808 "It is not a function, it is '%s'.")
1809
1810 (js2-msg "msg.function.not.found"
1811 "Cannot find function %s.")
1812
1813 (js2-msg "msg.function.not.found.in"
1814 "Cannot find function %s in object %s.")
1815
1816 (js2-msg "msg.isnt.xml.object"
1817 "%s is not an xml object.")
1818
1819 (js2-msg "msg.no.ref.to.get"
1820 "%s is not a reference to read reference value.")
1821
1822 (js2-msg "msg.no.ref.to.set"
1823 "%s is not a reference to set reference value to %s.")
1824
1825 (js2-msg "msg.no.ref.from.function"
1826 "Function %s can not be used as the left-hand "
1827 "side of assignment or as an operand of ++ or -- operator.")
1828
1829 (js2-msg "msg.bad.default.value"
1830 "Object's getDefaultValue() method returned an object.")
1831
1832 (js2-msg "msg.instanceof.not.object"
1833 "Can't use instanceof on a non-object.")
1834
1835 (js2-msg "msg.instanceof.bad.prototype"
1836 "'prototype' property of %s is not an object.")
1837
1838 (js2-msg "msg.bad.radix"
1839 "illegal radix %s.")
1840
1841 ;; ScriptableObject
1842 (js2-msg "msg.default.value"
1843 "Cannot find default value for object.")
1844
1845 (js2-msg "msg.zero.arg.ctor"
1846 "Cannot load class '%s' which has no zero-parameter constructor.")
1847
1848 (js2-msg "msg.ctor.multiple.parms"
1849 "Can't define constructor or class %s since more than "
1850 "one constructor has multiple parameters.")
1851
1852 (js2-msg "msg.extend.scriptable"
1853 "%s must extend ScriptableObject in order to define property %s.")
1854
1855 (js2-msg "msg.bad.getter.parms"
1856 "In order to define a property, getter %s must have zero "
1857 "parameters or a single ScriptableObject parameter.")
1858
1859 (js2-msg "msg.obj.getter.parms"
1860 "Expected static or delegated getter %s to take "
1861 "a ScriptableObject parameter.")
1862
1863 (js2-msg "msg.getter.static"
1864 "Getter and setter must both be static or neither be static.")
1865
1866 (js2-msg "msg.setter.return"
1867 "Setter must have void return type: %s")
1868
1869 (js2-msg "msg.setter2.parms"
1870 "Two-parameter setter must take a ScriptableObject as "
1871 "its first parameter.")
1872
1873 (js2-msg "msg.setter1.parms"
1874 "Expected single parameter setter for %s")
1875
1876 (js2-msg "msg.setter2.expected"
1877 "Expected static or delegated setter %s to take two parameters.")
1878
1879 (js2-msg "msg.setter.parms"
1880 "Expected either one or two parameters for setter.")
1881
1882 (js2-msg "msg.setter.bad.type"
1883 "Unsupported parameter type '%s' in setter '%s'.")
1884
1885 (js2-msg "msg.add.sealed"
1886 "Cannot add a property to a sealed object: %s.")
1887
1888 (js2-msg "msg.remove.sealed"
1889 "Cannot remove a property from a sealed object: %s.")
1890
1891 (js2-msg "msg.modify.sealed"
1892 "Cannot modify a property of a sealed object: %s.")
1893
1894 (js2-msg "msg.modify.readonly"
1895 "Cannot modify readonly property: %s.")
1896
1897 ;; TokenStream
1898 (js2-msg "msg.missing.exponent"
1899 "missing exponent")
1900
1901 (js2-msg "msg.caught.nfe"
1902 "number format error")
1903
1904 (js2-msg "msg.unterminated.string.lit"
1905 "unterminated string literal")
1906
1907 (js2-msg "msg.unterminated.comment"
1908 "unterminated comment")
1909
1910 (js2-msg "msg.unterminated.re.lit"
1911 "unterminated regular expression literal")
1912
1913 (js2-msg "msg.invalid.re.flag"
1914 "invalid flag after regular expression")
1915
1916 (js2-msg "msg.no.re.input.for"
1917 "no input for %s")
1918
1919 (js2-msg "msg.illegal.character"
1920 "illegal character")
1921
1922 (js2-msg "msg.invalid.escape"
1923 "invalid Unicode escape sequence")
1924
1925 (js2-msg "msg.bad.namespace"
1926 "not a valid default namespace statement. "
1927 "Syntax is: default xml namespace = EXPRESSION;")
1928
1929 ;; TokensStream warnings
1930 (js2-msg "msg.bad.octal.literal"
1931 "illegal octal literal digit %s; "
1932 "interpreting it as a decimal digit")
1933
1934 (js2-msg "msg.reserved.keyword"
1935 "illegal usage of future reserved keyword %s; "
1936 "interpreting it as ordinary identifier")
1937
1938 (js2-msg "msg.script.is.not.constructor"
1939 "Script objects are not constructors.")
1940
1941 ;; Arrays
1942 (js2-msg "msg.arraylength.bad"
1943 "Inappropriate array length.")
1944
1945 ;; Arrays
1946 (js2-msg "msg.arraylength.too.big"
1947 "Array length %s exceeds supported capacity limit.")
1948
1949 ;; URI
1950 (js2-msg "msg.bad.uri"
1951 "Malformed URI sequence.")
1952
1953 ;; Number
1954 (js2-msg "msg.bad.precision"
1955 "Precision %s out of range.")
1956
1957 ;; NativeGenerator
1958 (js2-msg "msg.send.newborn"
1959 "Attempt to send value to newborn generator")
1960
1961 (js2-msg "msg.already.exec.gen"
1962 "Already executing generator")
1963
1964 (js2-msg "msg.StopIteration.invalid"
1965 "StopIteration may not be changed to an arbitrary object.")
1966
1967 ;; Interpreter
1968 (js2-msg "msg.yield.closing"
1969 "Yield from closing generator")
1970
1971 ;;; Utilities
1972
1973 (defun js2-delete-if (predicate list)
1974 "Remove all items satisfying PREDICATE in LIST."
1975 (loop for item in list
1976 if (not (funcall predicate item))
1977 collect item))
1978
1979 (defun js2-position (element list)
1980 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1981 Returns nil if element is not found in the list."
1982 (let ((count 0)
1983 found)
1984 (while (and list (not found))
1985 (if (eq element (car list))
1986 (setq found t)
1987 (setq count (1+ count)
1988 list (cdr list))))
1989 (if found count)))
1990
1991 (defun js2-find-if (predicate list)
1992 "Find first item satisfying PREDICATE in LIST."
1993 (let (result)
1994 (while (and list (not result))
1995 (if (funcall predicate (car list))
1996 (setq result (car list)))
1997 (setq list (cdr list)))
1998 result))
1999
2000 (defmacro js2-time (form)
2001 "Evaluate FORM, discard result, and return elapsed time in sec"
2002 (declare (debug t))
2003 (let ((beg (make-symbol "--js2-time-beg--"))
2004 (delta (make-symbol "--js2-time-end--")))
2005 `(let ((,beg (current-time))
2006 ,delta)
2007 ,form
2008 (/ (truncate (* (- (float-time (current-time))
2009 (float-time ,beg))
2010 10000))
2011 10000.0))))
2012
2013 (defsubst js2-same-line (pos)
2014 "Return t if POS is on the same line as current point."
2015 (and (>= pos (point-at-bol))
2016 (<= pos (point-at-eol))))
2017
2018 (defsubst js2-same-line-2 (p1 p2)
2019 "Return t if p1 is on the same line as p2."
2020 (save-excursion
2021 (goto-char p1)
2022 (js2-same-line p2)))
2023
2024 (defun js2-code-bug ()
2025 "Signal an error when we encounter an unexpected code path."
2026 (error "failed assertion"))
2027
2028 (defsubst js2-record-text-property (beg end prop value)
2029 "Record a text property to set when parsing finishes."
2030 (push (list beg end prop value) js2-mode-deferred-properties))
2031
2032 ;; I'd like to associate errors with nodes, but for now the
2033 ;; easiest thing to do is get the context info from the last token.
2034 (defsubst js2-record-parse-error (msg &optional arg pos len)
2035 (push (list (list msg arg)
2036 (or pos js2-token-beg)
2037 (or len (- js2-token-end js2-token-beg)))
2038 js2-parsed-errors))
2039
2040 (defsubst js2-report-error (msg &optional msg-arg pos len)
2041 "Signal a syntax error or record a parse error."
2042 (if js2-recover-from-parse-errors
2043 (js2-record-parse-error msg msg-arg pos len)
2044 (signal 'js2-syntax-error
2045 (list msg
2046 js2-ts-lineno
2047 (save-excursion
2048 (goto-char js2-ts-cursor)
2049 (current-column))
2050 js2-ts-hit-eof))))
2051
2052 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2053 (if js2-compiler-report-warning-as-error
2054 (js2-report-error msg msg-arg pos len)
2055 (push (list (list msg msg-arg)
2056 (or pos js2-token-beg)
2057 (or len (- js2-token-end js2-token-beg)))
2058 js2-parsed-warnings)))
2059
2060 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2061 (if js2-compiler-strict-mode
2062 (js2-report-warning msg-id msg-arg beg
2063 (and beg end (- end beg)))))
2064
2065 (put 'js2-syntax-error 'error-conditions
2066 '(error syntax-error js2-syntax-error))
2067 (put 'js2-syntax-error 'error-message "Syntax error")
2068
2069 (put 'js2-parse-error 'error-conditions
2070 '(error parse-error js2-parse-error))
2071 (put 'js2-parse-error 'error-message "Parse error")
2072
2073 (defmacro js2-clear-flag (flags flag)
2074 `(setq ,flags (logand ,flags (lognot ,flag))))
2075
2076 (defmacro js2-set-flag (flags flag)
2077 "Logical-or FLAG into FLAGS."
2078 `(setq ,flags (logior ,flags ,flag)))
2079
2080 (defsubst js2-flag-set-p (flags flag)
2081 (/= 0 (logand flags flag)))
2082
2083 (defsubst js2-flag-not-set-p (flags flag)
2084 (zerop (logand flags flag)))
2085
2086 ;; Stolen shamelessly from James Clark's nxml-mode.
2087 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2088 "Evaluate BODY without any text property changes modifying the buffer.
2089 Any text properties changes happen as usual but the changes are not treated as
2090 modifications to the buffer."
2091 (declare (indent 0) (debug t))
2092 (let ((modified (make-symbol "modified")))
2093 `(let ((,modified (buffer-modified-p))
2094 (inhibit-read-only t)
2095 (inhibit-modification-hooks t)
2096 (buffer-undo-list t)
2097 (deactivate-mark nil)
2098 ;; Apparently these avoid file locking problems.
2099 (buffer-file-name nil)
2100 (buffer-file-truename nil))
2101 (unwind-protect
2102 (progn ,@body)
2103 (unless ,modified
2104 (restore-buffer-modified-p nil))))))
2105
2106 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2107 "Evaluate BODY with the _ character set to be word-syntax."
2108 (declare (indent 0) (debug t))
2109 (let ((old-syntax (make-symbol "old-syntax")))
2110 `(let ((,old-syntax (string (char-syntax ?_))))
2111 (unwind-protect
2112 (progn
2113 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2114 ,@body)
2115 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2116
2117 (defsubst js2-char-uppercase-p (c)
2118 "Return t if C is an uppercase character.
2119 Handles unicode and latin chars properly."
2120 (/= c (downcase c)))
2121
2122 (defsubst js2-char-lowercase-p (c)
2123 "Return t if C is an uppercase character.
2124 Handles unicode and latin chars properly."
2125 (/= c (upcase c)))
2126
2127 ;;; AST struct and function definitions
2128
2129 ;; flags for ast node property 'member-type (used for e4x operators)
2130 (defvar js2-property-flag #x1 "property access: element is valid name")
2131 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2132 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2133
2134 (defsubst js2-relpos (pos anchor)
2135 "Convert POS to be relative to ANCHOR.
2136 If POS is nil, returns nil."
2137 (and pos (- pos anchor)))
2138
2139 (defsubst js2-make-pad (indent)
2140 (if (zerop indent)
2141 ""
2142 (make-string (* indent js2-basic-offset) ? )))
2143
2144 (defsubst js2-visit-ast (node callback)
2145 "Visit every node in ast NODE with visitor CALLBACK.
2146
2147 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2148 called twice: once to visit the node, and again after all the node's
2149 children have been processed. The END-P argument is nil on the first
2150 call and non-nil on the second call. The return value of the callback
2151 affects the traversal: if non-nil, the children of NODE are processed.
2152 If the callback returns nil, or if the node has no children, then the
2153 callback is called immediately with a non-nil END-P argument.
2154
2155 The node traversal is approximately lexical-order, although there
2156 are currently no guarantees around this."
2157 (if node
2158 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2159 ;; visit the node
2160 (when (funcall callback node nil)
2161 ;; visit the kids
2162 (cond
2163 ((eq vfunc 'js2-visit-none)
2164 nil) ; don't even bother calling it
2165 ;; Each AST node type has to define a `js2-visitor' function
2166 ;; that takes a node and a callback, and calls `js2-visit-ast'
2167 ;; on each child of the node.
2168 (vfunc
2169 (funcall vfunc node callback))
2170 (t
2171 (error "%s does not define a visitor-traversal function"
2172 (aref node 0)))))
2173 ;; call the end-visit
2174 (funcall callback node t))))
2175
2176 (defstruct (js2-node
2177 (:constructor nil)) ; abstract
2178 "Base AST node type."
2179 (type -1) ; token type
2180 (pos -1) ; start position of this AST node in parsed input
2181 (len 1) ; num characters spanned by the node
2182 props ; optional node property list (an alist)
2183 parent) ; link to parent node; null for root
2184
2185 (defsubst js2-node-get-prop (node prop &optional default)
2186 (or (cadr (assoc prop (js2-node-props node))) default))
2187
2188 (defsubst js2-node-set-prop (node prop value)
2189 (setf (js2-node-props node)
2190 (cons (list prop value) (js2-node-props node))))
2191
2192 (defsubst js2-fixup-starts (n nodes)
2193 "Adjust the start positions of NODES to be relative to N.
2194 Any node in the list may be nil, for convenience."
2195 (dolist (node nodes)
2196 (when node
2197 (setf (js2-node-pos node) (- (js2-node-pos node)
2198 (js2-node-pos n))))))
2199
2200 (defsubst js2-node-add-children (parent &rest nodes)
2201 "Set parent node of NODES to PARENT, and return PARENT.
2202 Does nothing if we're not recording parent links.
2203 If any given node in NODES is nil, doesn't record that link."
2204 (js2-fixup-starts parent nodes)
2205 (dolist (node nodes)
2206 (and node
2207 (setf (js2-node-parent node) parent))))
2208
2209 ;; Non-recursive since it's called a frightening number of times.
2210 (defsubst js2-node-abs-pos (n)
2211 (let ((pos (js2-node-pos n)))
2212 (while (setq n (js2-node-parent n))
2213 (setq pos (+ pos (js2-node-pos n))))
2214 pos))
2215
2216 (defsubst js2-node-abs-end (n)
2217 "Return absolute buffer position of end of N."
2218 (+ (js2-node-abs-pos n) (js2-node-len n)))
2219
2220 ;; It's important to make sure block nodes have a lisp list for the
2221 ;; child nodes, to limit printing recursion depth in an AST that
2222 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2223 ;; a sufficiently large vector tree.
2224
2225 (defstruct (js2-block-node
2226 (:include js2-node)
2227 (:constructor nil)
2228 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2229 (pos js2-token-beg)
2230 len
2231 props
2232 kids)))
2233 "A block of statements."
2234 kids) ; a lisp list of the child statement nodes
2235
2236 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2237 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2238
2239 (defsubst js2-visit-block (ast callback)
2240 "Visit the `js2-block-node' children of AST."
2241 (dolist (kid (js2-block-node-kids ast))
2242 (js2-visit-ast kid callback)))
2243
2244 (defun js2-print-block (n i)
2245 (let ((pad (js2-make-pad i)))
2246 (insert pad "{\n")
2247 (dolist (kid (js2-block-node-kids n))
2248 (js2-print-ast kid (1+ i)))
2249 (insert pad "}")))
2250
2251 (defstruct (js2-scope
2252 (:include js2-block-node)
2253 (:constructor nil)
2254 (:constructor make-js2-scope (&key (type js2-BLOCK)
2255 (pos js2-token-beg)
2256 len
2257 kids)))
2258 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2259 ;; I don't have one of those handy, so I'll use an alist for now.
2260 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2261 ;; and is much lighter-weight to construct (both CPU and mem).
2262 ;; The keys are interned strings (symbols) for faster lookup.
2263 ;; Should switch to hybrid alist/hashtable eventually.
2264 symbol-table ; an alist of (symbol . js2-symbol)
2265 parent-scope ; a `js2-scope'
2266 top) ; top-level `js2-scope' (script/function)
2267
2268 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2269 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2270
2271 (defun js2-scope-set-parent-scope (scope parent)
2272 (setf (js2-scope-parent-scope scope) parent
2273 (js2-scope-top scope) (if (null parent)
2274 scope
2275 (js2-scope-top parent))))
2276
2277 (defun js2-node-get-enclosing-scope (node)
2278 "Return the innermost `js2-scope' node surrounding NODE.
2279 Returns nil if there is no enclosing scope node."
2280 (let ((parent (js2-node-parent node)))
2281 (while (not (js2-scope-p parent))
2282 (setq parent (js2-node-parent parent)))
2283 parent))
2284
2285 (defun js2-get-defining-scope (scope name)
2286 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2287 Returns `js2-scope' in which NAME is defined, or nil if not found."
2288 (let ((sym (if (symbolp name)
2289 name
2290 (intern name)))
2291 table
2292 result
2293 (continue t))
2294 (while (and scope continue)
2295 (if (and (setq table (js2-scope-symbol-table scope))
2296 (assq sym table))
2297 (setq continue nil
2298 result scope)
2299 (setq scope (js2-scope-parent-scope scope))))
2300 result))
2301
2302 (defsubst js2-scope-get-symbol (scope name)
2303 "Return symbol table entry for NAME in SCOPE.
2304 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2305 (and (js2-scope-symbol-table scope)
2306 (cdr (assq (if (symbolp name)
2307 name
2308 (intern name))
2309 (js2-scope-symbol-table scope)))))
2310
2311 (defsubst js2-scope-put-symbol (scope name symbol)
2312 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2313 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2314 (let* ((table (js2-scope-symbol-table scope))
2315 (sym (if (symbolp name) name (intern name)))
2316 (entry (assq sym table)))
2317 (if entry
2318 (setcdr entry symbol)
2319 (push (cons sym symbol)
2320 (js2-scope-symbol-table scope)))))
2321
2322 (defstruct (js2-symbol
2323 (:constructor nil)
2324 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2325 "A symbol table entry."
2326 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2327 ;; js2-LET, or js2-CONST
2328 decl-type
2329 name ; string
2330 ast-node) ; a `js2-node'
2331
2332 (defstruct (js2-error-node
2333 (:include js2-node)
2334 (:constructor nil) ; silence emacs21 byte-compiler
2335 (:constructor make-js2-error-node (&key (type js2-ERROR)
2336 (pos js2-token-beg)
2337 len)))
2338 "AST node representing a parse error.")
2339
2340 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2341 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2342
2343 (defstruct (js2-script-node
2344 (:include js2-scope)
2345 (:constructor nil)
2346 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2347 (pos js2-token-beg)
2348 len
2349 var-decls
2350 fun-decls)))
2351 functions ; lisp list of nested functions
2352 regexps ; lisp list of (string . flags)
2353 symbols ; alist (every symbol gets unique index)
2354 (param-count 0)
2355 var-names ; vector of string names
2356 consts ; bool-vector matching var-decls
2357 (temp-number 0)) ; for generating temp variables
2358
2359 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2360 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2361
2362 (defun js2-print-script (node indent)
2363 (dolist (kid (js2-block-node-kids node))
2364 (js2-print-ast kid indent)))
2365
2366 (defstruct (js2-ast-root
2367 (:include js2-script-node)
2368 (:constructor nil)
2369 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2370 (pos js2-token-beg)
2371 len
2372 buffer)))
2373 "The root node of a js2 AST."
2374 buffer ; the source buffer from which the code was parsed
2375 comments ; a lisp list of comments, ordered by start position
2376 errors ; a lisp list of errors found during parsing
2377 warnings ; a lisp list of warnings found during parsing
2378 node-count) ; number of nodes in the tree, including the root
2379
2380 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2381 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2382
2383 (defun js2-visit-ast-root (ast callback)
2384 (dolist (kid (js2-ast-root-kids ast))
2385 (js2-visit-ast kid callback))
2386 (dolist (comment (js2-ast-root-comments ast))
2387 (js2-visit-ast comment callback)))
2388
2389 (defstruct (js2-comment-node
2390 (:include js2-node)
2391 (:constructor nil)
2392 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2393 (pos js2-token-beg)
2394 len
2395 (format js2-ts-comment-type))))
2396 format) ; 'line, 'block, 'jsdoc or 'html
2397
2398 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2399 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2400
2401 (defun js2-print-comment (n i)
2402 ;; We really ought to link end-of-line comments to their nodes.
2403 ;; Or maybe we could add a new comment type, 'endline.
2404 (insert (js2-make-pad i)
2405 (js2-node-string n)))
2406
2407 (defstruct (js2-expr-stmt-node
2408 (:include js2-node)
2409 (:constructor nil)
2410 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2411 (pos js2-ts-cursor)
2412 len
2413 expr)))
2414 "An expression statement."
2415 expr)
2416
2417 (defsubst js2-expr-stmt-node-set-has-result (node)
2418 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2419 (setf (js2-node-type node) js2-EXPR_RESULT))
2420
2421 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2422 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2423
2424 (defun js2-visit-expr-stmt-node (n v)
2425 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2426
2427 (defun js2-print-expr-stmt-node (n indent)
2428 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2429 (insert ";\n"))
2430
2431 (defstruct (js2-loop-node
2432 (:include js2-scope)
2433 (:constructor nil))
2434 "Abstract supertype of loop nodes."
2435 body ; a `js2-block-node'
2436 lp ; position of left-paren, nil if omitted
2437 rp) ; position of right-paren, nil if omitted
2438
2439 (defstruct (js2-do-node
2440 (:include js2-loop-node)
2441 (:constructor nil)
2442 (:constructor make-js2-do-node (&key (type js2-DO)
2443 (pos js2-token-beg)
2444 len
2445 body
2446 condition
2447 while-pos
2448 lp
2449 rp)))
2450 "AST node for do-loop."
2451 condition ; while (expression)
2452 while-pos) ; buffer position of 'while' keyword
2453
2454 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2455 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2456
2457 (defun js2-visit-do-node (n v)
2458 (js2-visit-ast (js2-do-node-body n) v)
2459 (js2-visit-ast (js2-do-node-condition n) v))
2460
2461 (defun js2-print-do-node (n i)
2462 (let ((pad (js2-make-pad i)))
2463 (insert pad "do {\n")
2464 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2465 (js2-print-ast kid (1+ i)))
2466 (insert pad "} while (")
2467 (js2-print-ast (js2-do-node-condition n) 0)
2468 (insert ");\n")))
2469
2470 (defstruct (js2-while-node
2471 (:include js2-loop-node)
2472 (:constructor nil)
2473 (:constructor make-js2-while-node (&key (type js2-WHILE)
2474 (pos js2-token-beg)
2475 len
2476 body
2477 condition
2478 lp
2479 rp)))
2480 "AST node for while-loop."
2481 condition) ; while-condition
2482
2483 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2484 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2485
2486 (defun js2-visit-while-node (n v)
2487 (js2-visit-ast (js2-while-node-condition n) v)
2488 (js2-visit-ast (js2-while-node-body n) v))
2489
2490 (defun js2-print-while-node (n i)
2491 (let ((pad (js2-make-pad i)))
2492 (insert pad "while (")
2493 (js2-print-ast (js2-while-node-condition n) 0)
2494 (insert ") {\n")
2495 (js2-print-body (js2-while-node-body n) (1+ i))
2496 (insert pad "}\n")))
2497
2498 (defstruct (js2-for-node
2499 (:include js2-loop-node)
2500 (:constructor nil)
2501 (:constructor make-js2-for-node (&key (type js2-FOR)
2502 (pos js2-ts-cursor)
2503 len
2504 body
2505 init
2506 condition
2507 update
2508 lp
2509 rp)))
2510 "AST node for a C-style for-loop."
2511 init ; initialization expression
2512 condition ; loop condition
2513 update) ; update clause
2514
2515 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2516 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2517
2518 (defun js2-visit-for-node (n v)
2519 (js2-visit-ast (js2-for-node-init n) v)
2520 (js2-visit-ast (js2-for-node-condition n) v)
2521 (js2-visit-ast (js2-for-node-update n) v)
2522 (js2-visit-ast (js2-for-node-body n) v))
2523
2524 (defun js2-print-for-node (n i)
2525 (let ((pad (js2-make-pad i)))
2526 (insert pad "for (")
2527 (js2-print-ast (js2-for-node-init n) 0)
2528 (insert "; ")
2529 (js2-print-ast (js2-for-node-condition n) 0)
2530 (insert "; ")
2531 (js2-print-ast (js2-for-node-update n) 0)
2532 (insert ") {\n")
2533 (js2-print-body (js2-for-node-body n) (1+ i))
2534 (insert pad "}\n")))
2535
2536 (defstruct (js2-for-in-node
2537 (:include js2-loop-node)
2538 (:constructor nil)
2539 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2540 (pos js2-ts-cursor)
2541 len
2542 body
2543 iterator
2544 object
2545 in-pos
2546 each-pos
2547 foreach-p
2548 lp
2549 rp)))
2550 "AST node for a for..in loop."
2551 iterator ; [var] foo in ...
2552 object ; object over which we're iterating
2553 in-pos ; buffer position of 'in' keyword
2554 each-pos ; buffer position of 'each' keyword, if foreach-p
2555 foreach-p) ; t if it's a for-each loop
2556
2557 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2558 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2559
2560 (defun js2-visit-for-in-node (n v)
2561 (js2-visit-ast (js2-for-in-node-iterator n) v)
2562 (js2-visit-ast (js2-for-in-node-object n) v)
2563 (js2-visit-ast (js2-for-in-node-body n) v))
2564
2565 (defun js2-print-for-in-node (n i)
2566 (let ((pad (js2-make-pad i))
2567 (foreach (js2-for-in-node-foreach-p n)))
2568 (insert pad "for ")
2569 (if foreach
2570 (insert "each "))
2571 (insert "(")
2572 (js2-print-ast (js2-for-in-node-iterator n) 0)
2573 (insert " in ")
2574 (js2-print-ast (js2-for-in-node-object n) 0)
2575 (insert ") {\n")
2576 (js2-print-body (js2-for-in-node-body n) (1+ i))
2577 (insert pad "}\n")))
2578
2579 (defstruct (js2-return-node
2580 (:include js2-node)
2581 (:constructor nil)
2582 (:constructor make-js2-return-node (&key (type js2-RETURN)
2583 (pos js2-ts-cursor)
2584 len
2585 retval)))
2586 "AST node for a return statement."
2587 retval) ; expression to return, or 'undefined
2588
2589 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2590 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2591
2592 (defun js2-visit-return-node (n v)
2593 (js2-visit-ast (js2-return-node-retval n) v))
2594
2595 (defun js2-print-return-node (n i)
2596 (insert (js2-make-pad i) "return")
2597 (when (js2-return-node-retval n)
2598 (insert " ")
2599 (js2-print-ast (js2-return-node-retval n) 0))
2600 (insert ";\n"))
2601
2602 (defstruct (js2-if-node
2603 (:include js2-node)
2604 (:constructor nil)
2605 (:constructor make-js2-if-node (&key (type js2-IF)
2606 (pos js2-ts-cursor)
2607 len
2608 condition
2609 then-part
2610 else-pos
2611 else-part
2612 lp
2613 rp)))
2614 "AST node for an if-statement."
2615 condition ; expression
2616 then-part ; statement or block
2617 else-pos ; optional buffer position of 'else' keyword
2618 else-part ; optional statement or block
2619 lp ; position of left-paren, nil if omitted
2620 rp) ; position of right-paren, nil if omitted
2621
2622 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2623 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2624
2625 (defun js2-visit-if-node (n v)
2626 (js2-visit-ast (js2-if-node-condition n) v)
2627 (js2-visit-ast (js2-if-node-then-part n) v)
2628 (js2-visit-ast (js2-if-node-else-part n) v))
2629
2630 (defun js2-print-if-node (n i)
2631 (let ((pad (js2-make-pad i))
2632 (then-part (js2-if-node-then-part n))
2633 (else-part (js2-if-node-else-part n)))
2634 (insert pad "if (")
2635 (js2-print-ast (js2-if-node-condition n) 0)
2636 (insert ") {\n")
2637 (js2-print-body then-part (1+ i))
2638 (insert pad "}")
2639 (cond
2640 ((not else-part)
2641 (insert "\n"))
2642 ((js2-if-node-p else-part)
2643 (insert " else ")
2644 (js2-print-body else-part i))
2645 (t
2646 (insert " else {\n")
2647 (js2-print-body else-part (1+ i))
2648 (insert pad "}\n")))))
2649
2650 (defstruct (js2-try-node
2651 (:include js2-node)
2652 (:constructor nil)
2653 (:constructor make-js2-try-node (&key (type js2-TRY)
2654 (pos js2-ts-cursor)
2655 len
2656 try-block
2657 catch-clauses
2658 finally-block)))
2659 "AST node for a try-statement."
2660 try-block
2661 catch-clauses ; a lisp list of `js2-catch-node'
2662 finally-block) ; a `js2-finally-node'
2663
2664 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2665 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2666
2667 (defun js2-visit-try-node (n v)
2668 (js2-visit-ast (js2-try-node-try-block n) v)
2669 (dolist (clause (js2-try-node-catch-clauses n))
2670 (js2-visit-ast clause v))
2671 (js2-visit-ast (js2-try-node-finally-block n) v))
2672
2673 (defun js2-print-try-node (n i)
2674 (let ((pad (js2-make-pad i))
2675 (catches (js2-try-node-catch-clauses n))
2676 (finally (js2-try-node-finally-block n)))
2677 (insert pad "try {\n")
2678 (js2-print-body (js2-try-node-try-block n) (1+ i))
2679 (insert pad "}")
2680 (when catches
2681 (dolist (catch catches)
2682 (js2-print-ast catch i)))
2683 (if finally
2684 (js2-print-ast finally i)
2685 (insert "\n"))))
2686
2687 (defstruct (js2-catch-node
2688 (:include js2-node)
2689 (:constructor nil)
2690 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2691 (pos js2-ts-cursor)
2692 len
2693 param
2694 guard-kwd
2695 guard-expr
2696 block
2697 lp
2698 rp)))
2699 "AST node for a catch clause."
2700 param ; destructuring form or simple name node
2701 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2702 guard-expr ; catch condition, a `js2-node'
2703 block ; statements, a `js2-block-node'
2704 lp ; buffer position of left-paren, nil if omitted
2705 rp) ; buffer position of right-paren, nil if omitted
2706
2707 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2708 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2709
2710 (defun js2-visit-catch-node (n v)
2711 (js2-visit-ast (js2-catch-node-param n) v)
2712 (when (js2-catch-node-guard-kwd n)
2713 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2714 (js2-visit-ast (js2-catch-node-block n) v))
2715
2716 (defun js2-print-catch-node (n i)
2717 (let ((pad (js2-make-pad i))
2718 (guard-kwd (js2-catch-node-guard-kwd n))
2719 (guard-expr (js2-catch-node-guard-expr n)))
2720 (insert " catch (")
2721 (js2-print-ast (js2-catch-node-var-name n) 0)
2722 (when guard-kwd
2723 (insert " if ")
2724 (js2-print-ast guard-expr 0))
2725 (insert ") {\n")
2726 (js2-print-body (js2-catch-node-block n) (1+ i))
2727 (insert pad "}")))
2728
2729 (defstruct (js2-finally-node
2730 (:include js2-node)
2731 (:constructor nil)
2732 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2733 (pos js2-ts-cursor)
2734 len
2735 body)))
2736 "AST node for a finally clause."
2737 body) ; a `js2-node', often but not always a block node
2738
2739 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2740 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2741
2742 (defun js2-visit-finally-node (n v)
2743 (js2-visit-ast (js2-finally-node-body n) v))
2744
2745 (defun js2-print-finally-node (n i)
2746 (let ((pad (js2-make-pad i)))
2747 (insert " finally {\n")
2748 (js2-print-body (js2-finally-node-body n) (1+ i))
2749 (insert pad "}\n")))
2750
2751 (defstruct (js2-switch-node
2752 (:include js2-node)
2753 (:constructor nil)
2754 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2755 (pos js2-ts-cursor)
2756 len
2757 discriminant
2758 cases
2759 lp
2760 rp)))
2761 "AST node for a switch statement."
2762 discriminant ; a `js2-node' (switch expression)
2763 cases ; a lisp list of `js2-case-node'
2764 lp ; position of open-paren for discriminant, nil if omitted
2765 rp) ; position of close-paren for discriminant, nil if omitted
2766
2767 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2768 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2769
2770 (defun js2-visit-switch-node (n v)
2771 (js2-visit-ast (js2-switch-node-discriminant n) v)
2772 (dolist (c (js2-switch-node-cases n))
2773 (js2-visit-ast c v)))
2774
2775 (defun js2-print-switch-node (n i)
2776 (let ((pad (js2-make-pad i))
2777 (cases (js2-switch-node-cases n)))
2778 (insert pad "switch (")
2779 (js2-print-ast (js2-switch-node-discriminant n) 0)
2780 (insert ") {\n")
2781 (dolist (case cases)
2782 (js2-print-ast case i))
2783 (insert pad "}\n")))
2784
2785 (defstruct (js2-case-node
2786 (:include js2-block-node)
2787 (:constructor nil)
2788 (:constructor make-js2-case-node (&key (type js2-CASE)
2789 (pos js2-ts-cursor)
2790 len
2791 kids
2792 expr)))
2793 "AST node for a case clause of a switch statement."
2794 expr) ; the case expression (nil for default)
2795
2796 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2797 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2798
2799 (defun js2-visit-case-node (n v)
2800 (js2-visit-ast (js2-case-node-expr n) v)
2801 (js2-visit-block n v))
2802
2803 (defun js2-print-case-node (n i)
2804 (let ((pad (js2-make-pad i))
2805 (expr (js2-case-node-expr n)))
2806 (insert pad)
2807 (if (null expr)
2808 (insert "default:\n")
2809 (insert "case ")
2810 (js2-print-ast expr 0)
2811 (insert ":\n"))
2812 (dolist (kid (js2-case-node-kids n))
2813 (js2-print-ast kid (1+ i)))))
2814
2815 (defstruct (js2-throw-node
2816 (:include js2-node)
2817 (:constructor nil)
2818 (:constructor make-js2-throw-node (&key (type js2-THROW)
2819 (pos js2-ts-cursor)
2820 len
2821 expr)))
2822 "AST node for a throw statement."
2823 expr) ; the expression to throw
2824
2825 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2826 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2827
2828 (defun js2-visit-throw-node (n v)
2829 (js2-visit-ast (js2-throw-node-expr n) v))
2830
2831 (defun js2-print-throw-node (n i)
2832 (insert (js2-make-pad i) "throw ")
2833 (js2-print-ast (js2-throw-node-expr n) 0)
2834 (insert ";\n"))
2835
2836 (defstruct (js2-with-node
2837 (:include js2-node)
2838 (:constructor nil)
2839 (:constructor make-js2-with-node (&key (type js2-WITH)
2840 (pos js2-ts-cursor)
2841 len
2842 object
2843 body
2844 lp
2845 rp)))
2846 "AST node for a with-statement."
2847 object
2848 body
2849 lp ; buffer position of left-paren around object, nil if omitted
2850 rp) ; buffer position of right-paren around object, nil if omitted
2851
2852 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2853 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2854
2855 (defun js2-visit-with-node (n v)
2856 (js2-visit-ast (js2-with-node-object n) v)
2857 (js2-visit-ast (js2-with-node-body n) v))
2858
2859 (defun js2-print-with-node (n i)
2860 (let ((pad (js2-make-pad i)))
2861 (insert pad "with (")
2862 (js2-print-ast (js2-with-node-object n) 0)
2863 (insert ") {\n")
2864 (js2-print-body (js2-with-node-body n) (1+ i))
2865 (insert pad "}\n")))
2866
2867 (defstruct (js2-label-node
2868 (:include js2-node)
2869 (:constructor nil)
2870 (:constructor make-js2-label-node (&key (type js2-LABEL)
2871 (pos js2-ts-cursor)
2872 len
2873 name)))
2874 "AST node for a statement label or case label."
2875 name ; a string
2876 loop) ; for validating and code-generating continue-to-label
2877
2878 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2879 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2880
2881 (defun js2-print-label (n i)
2882 (insert (js2-make-pad i)
2883 (js2-label-node-name n)
2884 ":\n"))
2885
2886 (defstruct (js2-labeled-stmt-node
2887 (:include js2-node)
2888 (:constructor nil)
2889 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2890 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2891 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2892 (pos js2-ts-cursor)
2893 len
2894 labels
2895 stmt)))
2896 "AST node for a statement with one or more labels.
2897 Multiple labels for a statement are collapsed into the labels field."
2898 labels ; lisp list of `js2-label-node'
2899 stmt) ; the statement these labels are for
2900
2901 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2902 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2903
2904 (defun js2-get-label-by-name (lbl-stmt name)
2905 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2906 Returns nil if no such label is in the list."
2907 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2908 result)
2909 (while (and label-list (not result))
2910 (if (string= (js2-label-node-name (car label-list)) name)
2911 (setq result (car label-list))
2912 (setq label-list (cdr label-list))))
2913 result))
2914
2915 (defun js2-visit-labeled-stmt (n v)
2916 (dolist (label (js2-labeled-stmt-node-labels n))
2917 (js2-visit-ast label v))
2918 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2919
2920 (defun js2-print-labeled-stmt (n i)
2921 (dolist (label (js2-labeled-stmt-node-labels n))
2922 (js2-print-ast label i))
2923 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2924
2925 (defun js2-labeled-stmt-node-contains (node label)
2926 "Return t if NODE contains LABEL in its label set.
2927 NODE is a `js2-labels-node'. LABEL is an identifier."
2928 (loop for nl in (js2-labeled-stmt-node-labels node)
2929 if (string= label (js2-label-node-name nl))
2930 return t
2931 finally return nil))
2932
2933 (defsubst js2-labeled-stmt-node-add-label (node label)
2934 "Add a `js2-label-node' to the label set for this statement."
2935 (setf (js2-labeled-stmt-node-labels node)
2936 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2937
2938 (defstruct (js2-jump-node
2939 (:include js2-node)
2940 (:constructor nil))
2941 "Abstract supertype of break and continue nodes."
2942 label ; `js2-name-node' for location of label identifier, if present
2943 target) ; target js2-labels-node or loop/switch statement
2944
2945 (defun js2-visit-jump-node (n v)
2946 (js2-visit-ast (js2-jump-node-label n) v))
2947
2948 (defstruct (js2-break-node
2949 (:include js2-jump-node)
2950 (:constructor nil)
2951 (:constructor make-js2-break-node (&key (type js2-BREAK)
2952 (pos js2-ts-cursor)
2953 len
2954 label
2955 target)))
2956 "AST node for a break statement.
2957 The label field is a `js2-name-node', possibly nil, for the named label
2958 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2959 is the target of the break - a label node or enclosing loop/switch statement.")
2960
2961 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2962 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2963
2964 (defun js2-print-break-node (n i)
2965 (insert (js2-make-pad i) "break")
2966 (when (js2-break-node-label n)
2967 (insert " ")
2968 (js2-print-ast (js2-break-node-label n) 0))
2969 (insert ";\n"))
2970
2971 (defstruct (js2-continue-node
2972 (:include js2-jump-node)
2973 (:constructor nil)
2974 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2975 (pos js2-ts-cursor)
2976 len
2977 label
2978 target)))
2979 "AST node for a continue statement.
2980 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2981 It is nil if continue specifies no label. The target field is the jump target:
2982 a `js2-label-node' or the innermost enclosing loop.")
2983
2984 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2985 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2986
2987 (defun js2-print-continue-node (n i)
2988 (insert (js2-make-pad i) "continue")
2989 (when (js2-continue-node-label n)
2990 (insert " ")
2991 (js2-print-ast (js2-continue-node-label n) 0))
2992 (insert ";\n"))
2993
2994 (defstruct (js2-function-node
2995 (:include js2-script-node)
2996 (:constructor nil)
2997 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2998 (pos js2-ts-cursor)
2999 len
3000 (ftype 'FUNCTION)
3001 (form 'FUNCTION_STATEMENT)
3002 (name "")
3003 params
3004 body
3005 lp
3006 rp)))
3007 "AST node for a function declaration.
3008 The `params' field is a lisp list of nodes. Each node is either a simple
3009 `js2-name-node', or if it's a destructuring-assignment parameter, a
3010 `js2-array-node' or `js2-object-node'."
3011 ftype ; FUNCTION, GETTER or SETTER
3012 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3013 name ; function name (a `js2-name-node', or nil if anonymous)
3014 params ; a lisp list of destructuring forms or simple name nodes
3015 body ; a `js2-block-node' or expression node (1.8 only)
3016 lp ; position of arg-list open-paren, or nil if omitted
3017 rp ; position of arg-list close-paren, or nil if omitted
3018 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3019 needs-activation ; t if we need an activation object for this frame
3020 is-generator ; t if this function contains a yield
3021 member-expr) ; nonstandard Ecma extension from Rhino
3022
3023 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3024 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3025
3026 (defun js2-visit-function-node (n v)
3027 (js2-visit-ast (js2-function-node-name n) v)
3028 (dolist (p (js2-function-node-params n))
3029 (js2-visit-ast p v))
3030 (js2-visit-ast (js2-function-node-body n) v))
3031
3032 (defun js2-print-function-node (n i)
3033 (let ((pad (js2-make-pad i))
3034 (getter (js2-node-get-prop n 'GETTER_SETTER))
3035 (name (js2-function-node-name n))
3036 (params (js2-function-node-params n))
3037 (body (js2-function-node-body n))
3038 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3039 (unless getter
3040 (insert pad "function"))
3041 (when name
3042 (insert " ")
3043 (js2-print-ast name 0))
3044 (insert "(")
3045 (loop with len = (length params)
3046 for param in params
3047 for count from 1
3048 do
3049 (js2-print-ast param 0)
3050 (if (< count len)
3051 (insert ", ")))
3052 (insert ") {")
3053 (unless expr
3054 (insert "\n"))
3055 ;; TODO: fix this to be smarter about indenting, etc.
3056 (js2-print-body body (1+ i))
3057 (insert pad "}")
3058 (unless expr
3059 (insert "\n"))))
3060
3061 (defsubst js2-function-name (node)
3062 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3063 (and (js2-function-node-name node)
3064 (js2-name-node-name (js2-function-node-name node))))
3065
3066 ;; Having this be an expression node makes it more flexible.
3067 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3068 ;; that work better if you assume it's an expression. Whenever we have
3069 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3070 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3071 (defstruct (js2-var-decl-node
3072 (:include js2-node)
3073 (:constructor nil)
3074 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3075 (pos js2-token-beg)
3076 len
3077 kids
3078 decl-type)))
3079 "AST node for a variable declaration list (VAR, CONST or LET).
3080 The node bounds differ depending on the declaration type. For VAR or
3081 CONST declarations, the bounds include the var/const keyword. For LET
3082 declarations, the node begins at the position of the first child."
3083 kids ; a lisp list of `js2-var-init-node' structs.
3084 decl-type) ; js2-VAR, js2-CONST or js2-LET
3085
3086 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3087 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3088
3089 (defun js2-visit-var-decl (n v)
3090 (dolist (kid (js2-var-decl-node-kids n))
3091 (js2-visit-ast kid v)))
3092
3093 (defun js2-print-var-decl (n i)
3094 (let ((pad (js2-make-pad i))
3095 (tt (js2-var-decl-node-decl-type n)))
3096 (insert pad)
3097 (insert (cond
3098 ((= tt js2-VAR) "var ")
3099 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3100 ((= tt js2-CONST) "const ")
3101 (t
3102 (error "malformed var-decl node"))))
3103 (loop with kids = (js2-var-decl-node-kids n)
3104 with len = (length kids)
3105 for kid in kids
3106 for count from 1
3107 do
3108 (js2-print-ast kid 0)
3109 (if (< count len)
3110 (insert ", ")))))
3111
3112 (defstruct (js2-var-init-node
3113 (:include js2-node)
3114 (:constructor nil)
3115 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3116 (pos js2-ts-cursor)
3117 len
3118 target
3119 initializer)))
3120 "AST node for a variable declaration.
3121 The type field will be js2-CONST for a const decl."
3122 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3123 initializer) ; initializer expression, a `js2-node'
3124
3125 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3126 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3127
3128 (defun js2-visit-var-init-node (n v)
3129 (js2-visit-ast (js2-var-init-node-target n) v)
3130 (js2-visit-ast (js2-var-init-node-initializer n) v))
3131
3132 (defun js2-print-var-init-node (n i)
3133 (let ((pad (js2-make-pad i))
3134 (name (js2-var-init-node-target n))
3135 (init (js2-var-init-node-initializer n)))
3136 (insert pad)
3137 (js2-print-ast name 0)
3138 (when init
3139 (insert " = ")
3140 (js2-print-ast init 0))))
3141
3142 (defstruct (js2-cond-node
3143 (:include js2-node)
3144 (:constructor nil)
3145 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3146 (pos js2-ts-cursor)
3147 len
3148 test-expr
3149 true-expr
3150 false-expr
3151 q-pos
3152 c-pos)))
3153 "AST node for the ternary operator"
3154 test-expr
3155 true-expr
3156 false-expr
3157 q-pos ; buffer position of ?
3158 c-pos) ; buffer position of :
3159
3160 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3161 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3162
3163 (defun js2-visit-cond-node (n v)
3164 (js2-visit-ast (js2-cond-node-test-expr n) v)
3165 (js2-visit-ast (js2-cond-node-true-expr n) v)
3166 (js2-visit-ast (js2-cond-node-false-expr n) v))
3167
3168 (defun js2-print-cond-node (n i)
3169 (let ((pad (js2-make-pad i)))
3170 (insert pad)
3171 (js2-print-ast (js2-cond-node-test-expr n) 0)
3172 (insert " ? ")
3173 (js2-print-ast (js2-cond-node-true-expr n) 0)
3174 (insert " : ")
3175 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3176
3177 (defstruct (js2-infix-node
3178 (:include js2-node)
3179 (:constructor nil)
3180 (:constructor make-js2-infix-node (&key type
3181 (pos js2-ts-cursor)
3182 len
3183 op-pos
3184 left
3185 right)))
3186 "Represents infix expressions.
3187 Includes assignment ops like `|=', and the comma operator.
3188 The type field inherited from `js2-node' holds the operator."
3189 op-pos ; buffer position where operator begins
3190 left ; any `js2-node'
3191 right) ; any `js2-node'
3192
3193 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3194 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3195
3196 (defun js2-visit-infix-node (n v)
3197 (js2-visit-ast (js2-infix-node-left n) v)
3198 (js2-visit-ast (js2-infix-node-right n) v))
3199
3200 (defconst js2-operator-tokens
3201 (let ((table (make-hash-table :test 'eq))
3202 (tokens
3203 (list (cons js2-IN "in")
3204 (cons js2-TYPEOF "typeof")
3205 (cons js2-INSTANCEOF "instanceof")
3206 (cons js2-DELPROP "delete")
3207 (cons js2-COMMA ",")
3208 (cons js2-COLON ":")
3209 (cons js2-OR "||")
3210 (cons js2-AND "&&")
3211 (cons js2-INC "++")
3212 (cons js2-DEC "--")
3213 (cons js2-BITOR "|")
3214 (cons js2-BITXOR "^")
3215 (cons js2-BITAND "&")
3216 (cons js2-EQ "==")
3217 (cons js2-NE "!=")
3218 (cons js2-LT "<")
3219 (cons js2-LE "<=")
3220 (cons js2-GT ">")
3221 (cons js2-GE ">=")
3222 (cons js2-LSH "<<")
3223 (cons js2-RSH ">>")
3224 (cons js2-URSH ">>>")
3225 (cons js2-ADD "+") ; infix plus
3226 (cons js2-SUB "-") ; infix minus
3227 (cons js2-MUL "*")
3228 (cons js2-DIV "/")
3229 (cons js2-MOD "%")
3230 (cons js2-NOT "!")
3231 (cons js2-BITNOT "~")
3232 (cons js2-POS "+") ; unary plus
3233 (cons js2-NEG "-") ; unary minus
3234 (cons js2-SHEQ "===") ; shallow equality
3235 (cons js2-SHNE "!==") ; shallow inequality
3236 (cons js2-ASSIGN "=")
3237 (cons js2-ASSIGN_BITOR "|=")
3238 (cons js2-ASSIGN_BITXOR "^=")
3239 (cons js2-ASSIGN_BITAND "&=")
3240 (cons js2-ASSIGN_LSH "<<=")
3241 (cons js2-ASSIGN_RSH ">>=")
3242 (cons js2-ASSIGN_URSH ">>>=")
3243 (cons js2-ASSIGN_ADD "+=")
3244 (cons js2-ASSIGN_SUB "-=")
3245 (cons js2-ASSIGN_MUL "*=")
3246 (cons js2-ASSIGN_DIV "/=")
3247 (cons js2-ASSIGN_MOD "%="))))
3248 (loop for (k . v) in tokens do
3249 (puthash k v table))
3250 table))
3251
3252 (defun js2-print-infix-node (n i)
3253 (let* ((tt (js2-node-type n))
3254 (op (gethash tt js2-operator-tokens)))
3255 (unless op
3256 (error "unrecognized infix operator %s" (js2-node-type n)))
3257 (insert (js2-make-pad i))
3258 (js2-print-ast (js2-infix-node-left n) 0)
3259 (unless (= tt js2-COMMA)
3260 (insert " "))
3261 (insert op)
3262 (insert " ")
3263 (js2-print-ast (js2-infix-node-right n) 0)))
3264
3265 (defstruct (js2-assign-node
3266 (:include js2-infix-node)
3267 (:constructor nil)
3268 (:constructor make-js2-assign-node (&key type
3269 (pos js2-ts-cursor)
3270 len
3271 op-pos
3272 left
3273 right)))
3274 "Represents any assignment.
3275 The type field holds the actual assignment operator.")
3276
3277 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3278 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3279
3280 (defstruct (js2-unary-node
3281 (:include js2-node)
3282 (:constructor nil)
3283 (:constructor make-js2-unary-node (&key type ; required
3284 (pos js2-ts-cursor)
3285 len
3286 operand)))
3287 "AST node type for unary operator nodes.
3288 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3289 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3290 property is added if the operator follows the operand."
3291 operand) ; a `js2-node' expression
3292
3293 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3294 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3295
3296 (defun js2-visit-unary-node (n v)
3297 (js2-visit-ast (js2-unary-node-operand n) v))
3298
3299 (defun js2-print-unary-node (n i)
3300 (let* ((tt (js2-node-type n))
3301 (op (gethash tt js2-operator-tokens))
3302 (postfix (js2-node-get-prop n 'postfix)))
3303 (unless op
3304 (error "unrecognized unary operator %s" tt))
3305 (insert (js2-make-pad i))
3306 (unless postfix
3307 (insert op))
3308 (if (or (= tt js2-TYPEOF)
3309 (= tt js2-DELPROP))
3310 (insert " "))
3311 (js2-print-ast (js2-unary-node-operand n) 0)
3312 (when postfix
3313 (insert op))))
3314
3315 (defstruct (js2-let-node
3316 (:include js2-scope)
3317 (:constructor nil)
3318 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3319 (pos js2-token-beg)
3320 len
3321 vars
3322 body
3323 lp
3324 rp)))
3325 "AST node for a let expression or a let statement.
3326 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3327 vars ; a `js2-var-decl-node'
3328 body ; a `js2-node' representing the expression or body block
3329 lp
3330 rp)
3331
3332 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3333 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3334
3335 (defun js2-visit-let-node (n v)
3336 (js2-visit-ast (js2-let-node-vars n) v)
3337 (js2-visit-ast (js2-let-node-body n) v))
3338
3339 (defun js2-print-let-node (n i)
3340 (insert (js2-make-pad i) "let (")
3341 (js2-print-ast (js2-let-node-vars n) 0)
3342 (insert ") ")
3343 (js2-print-ast (js2-let-node-body n) i))
3344
3345 (defstruct (js2-keyword-node
3346 (:include js2-node)
3347 (:constructor nil)
3348 (:constructor make-js2-keyword-node (&key type
3349 (pos js2-token-beg)
3350 (len (- js2-ts-cursor pos)))))
3351 "AST node representing a literal keyword such as `null'.
3352 Used for `null', `this', `true', `false' and `debugger'.
3353 The node type is set to js2-NULL, js2-THIS, etc.")
3354
3355 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3356 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3357
3358 (defun js2-print-keyword-node (n i)
3359 (insert (js2-make-pad i)
3360 (let ((tt (js2-node-type n)))
3361 (cond
3362 ((= tt js2-THIS) "this")
3363 ((= tt js2-NULL) "null")
3364 ((= tt js2-TRUE) "true")
3365 ((= tt js2-FALSE) "false")
3366 ((= tt js2-DEBUGGER) "debugger")
3367 (t (error "Invalid keyword literal type: %d" tt))))))
3368
3369 (defsubst js2-this-node-p (node)
3370 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3371 (eq (js2-node-type node) js2-THIS))
3372
3373 (defstruct (js2-new-node
3374 (:include js2-node)
3375 (:constructor nil)
3376 (:constructor make-js2-new-node (&key (type js2-NEW)
3377 (pos js2-token-beg)
3378 len
3379 target
3380 args
3381 initializer
3382 lp
3383 rp)))
3384 "AST node for new-expression such as new Foo()."
3385 target ; an identifier or reference
3386 args ; a lisp list of argument nodes
3387 lp ; position of left-paren, nil if omitted
3388 rp ; position of right-paren, nil if omitted
3389 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3390
3391 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3392 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3393
3394 (defun js2-visit-new-node (n v)
3395 (js2-visit-ast (js2-new-node-target n) v)
3396 (dolist (arg (js2-new-node-args n))
3397 (js2-visit-ast arg v))
3398 (js2-visit-ast (js2-new-node-initializer n) v))
3399
3400 (defun js2-print-new-node (n i)
3401 (insert (js2-make-pad i) "new ")
3402 (js2-print-ast (js2-new-node-target n))
3403 (insert "(")
3404 (js2-print-list (js2-new-node-args n))
3405 (insert ")")
3406 (when (js2-new-node-initializer n)
3407 (insert " ")
3408 (js2-print-ast (js2-new-node-initializer n))))
3409
3410 (defstruct (js2-name-node
3411 (:include js2-node)
3412 (:constructor nil)
3413 (:constructor make-js2-name-node (&key (type js2-NAME)
3414 (pos js2-token-beg)
3415 (len (- js2-ts-cursor
3416 js2-token-beg))
3417 (name js2-ts-string))))
3418 "AST node for a JavaScript identifier"
3419 name ; a string
3420 scope) ; a `js2-scope' (optional, used for codegen)
3421
3422 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3423 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3424
3425 (defun js2-print-name-node (n i)
3426 (insert (js2-make-pad i)
3427 (js2-name-node-name n)))
3428
3429 (defsubst js2-name-node-length (node)
3430 "Return identifier length of NODE, a `js2-name-node'.
3431 Returns 0 if NODE is nil or its identifier field is nil."
3432 (if node
3433 (length (js2-name-node-name node))
3434 0))
3435
3436 (defstruct (js2-number-node
3437 (:include js2-node)
3438 (:constructor nil)
3439 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3440 (pos js2-token-beg)
3441 (len (- js2-ts-cursor
3442 js2-token-beg))
3443 (value js2-ts-string)
3444 (num-value js2-ts-number))))
3445 "AST node for a number literal."
3446 value ; the original string, e.g. "6.02e23"
3447 num-value) ; the parsed number value
3448
3449 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3450 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3451
3452 (defun js2-print-number-node (n i)
3453 (insert (js2-make-pad i)
3454 (number-to-string (js2-number-node-num-value n))))
3455
3456 (defstruct (js2-regexp-node
3457 (:include js2-node)
3458 (:constructor nil)
3459 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3460 (pos js2-token-beg)
3461 (len (- js2-ts-cursor
3462 js2-token-beg))
3463 value
3464 flags)))
3465 "AST node for a regular expression literal."
3466 value ; the regexp string, without // delimiters
3467 flags) ; a string of flags, e.g. `mi'.
3468
3469 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3470 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3471
3472 (defun js2-print-regexp (n i)
3473 (insert (js2-make-pad i)
3474 "/"
3475 (js2-regexp-node-value n)
3476 "/")
3477 (if (js2-regexp-node-flags n)
3478 (insert (js2-regexp-node-flags n))))
3479
3480 (defstruct (js2-string-node
3481 (:include js2-node)
3482 (:constructor nil)
3483 (:constructor make-js2-string-node (&key (type js2-STRING)
3484 (pos js2-token-beg)
3485 (len (- js2-ts-cursor
3486 js2-token-beg))
3487 (value js2-ts-string))))
3488 "String literal.
3489 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3490 You can tell the quote type by looking at the first character."
3491 value) ; the characters of the string, including the quotes
3492
3493 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3494 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3495
3496 (defun js2-print-string-node (n i)
3497 (insert (js2-make-pad i)
3498 (js2-node-string n)))
3499
3500 (defstruct (js2-array-node
3501 (:include js2-node)
3502 (:constructor nil)
3503 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3504 (pos js2-ts-cursor)
3505 len
3506 elems)))
3507 "AST node for an array literal."
3508 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3509
3510 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3511 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3512
3513 (defun js2-visit-array-node (n v)
3514 (dolist (e (js2-array-node-elems n))
3515 (js2-visit-ast e v)))
3516
3517 (defun js2-print-array-node (n i)
3518 (insert (js2-make-pad i) "[")
3519 (js2-print-list (js2-array-node-elems n))
3520 (insert "]"))
3521
3522 (defstruct (js2-object-node
3523 (:include js2-node)
3524 (:constructor nil)
3525 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3526 (pos js2-ts-cursor)
3527 len
3528 elems)))
3529 "AST node for an object literal expression.
3530 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3531 the latter represents abbreviation in destructuring expressions."
3532 elems)
3533
3534 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3535 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3536
3537 (defun js2-visit-object-node (n v)
3538 (dolist (e (js2-object-node-elems n))
3539 (js2-visit-ast e v)))
3540
3541 (defun js2-print-object-node (n i)
3542 (insert (js2-make-pad i) "{")
3543 (js2-print-list (js2-object-node-elems n))
3544 (insert "}"))
3545
3546 (defstruct (js2-object-prop-node
3547 (:include js2-infix-node)
3548 (:constructor nil)
3549 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3550 (pos js2-ts-cursor)
3551 len
3552 left
3553 right
3554 op-pos)))
3555 "AST node for an object literal prop:value entry.
3556 The `left' field is the property: a name node, string node or number node.
3557 The `right' field is a `js2-node' representing the initializer value.")
3558
3559 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3560 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3561
3562 (defun js2-print-object-prop-node (n i)
3563 (insert (js2-make-pad i))
3564 (js2-print-ast (js2-object-prop-node-left n) 0)
3565 (insert ":")
3566 (js2-print-ast (js2-object-prop-node-right n) 0))
3567
3568 (defstruct (js2-getter-setter-node
3569 (:include js2-infix-node)
3570 (:constructor nil)
3571 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3572 (pos js2-ts-cursor)
3573 len
3574 left
3575 right)))
3576 "AST node for a getter/setter property in an object literal.
3577 The `left' field is the `js2-name-node' naming the getter/setter prop.
3578 The `right' field is always an anonymous `js2-function-node' with a node
3579 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3580
3581 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3582 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3583
3584 (defun js2-print-getter-setter (n i)
3585 (let ((pad (js2-make-pad i))
3586 (left (js2-getter-setter-node-left n))
3587 (right (js2-getter-setter-node-right n)))
3588 (insert pad)
3589 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3590 (js2-print-ast left 0)
3591 (js2-print-ast right 0)))
3592
3593 (defstruct (js2-prop-get-node
3594 (:include js2-infix-node)
3595 (:constructor nil)
3596 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3597 (pos js2-ts-cursor)
3598 len
3599 left
3600 right)))
3601 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3602
3603 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3604 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3605
3606 (defun js2-visit-prop-get-node (n v)
3607 (js2-visit-ast (js2-prop-get-node-left n) v)
3608 (js2-visit-ast (js2-prop-get-node-right n) v))
3609
3610 (defun js2-print-prop-get-node (n i)
3611 (insert (js2-make-pad i))
3612 (js2-print-ast (js2-prop-get-node-left n) 0)
3613 (insert ".")
3614 (js2-print-ast (js2-prop-get-node-right n) 0))
3615
3616 (defstruct (js2-elem-get-node
3617 (:include js2-node)
3618 (:constructor nil)
3619 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3620 (pos js2-ts-cursor)
3621 len
3622 target
3623 element
3624 lb
3625 rb)))
3626 "AST node for an array index expression such as foo[bar]."
3627 target ; a `js2-node' - the expression preceding the "."
3628 element ; a `js2-node' - the expression in brackets
3629 lb ; position of left-bracket, nil if omitted
3630 rb) ; position of right-bracket, nil if omitted
3631
3632 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3633 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3634
3635 (defun js2-visit-elem-get-node (n v)
3636 (js2-visit-ast (js2-elem-get-node-target n) v)
3637 (js2-visit-ast (js2-elem-get-node-element n) v))
3638
3639 (defun js2-print-elem-get-node (n i)
3640 (insert (js2-make-pad i))
3641 (js2-print-ast (js2-elem-get-node-target n) 0)
3642 (insert "[")
3643 (js2-print-ast (js2-elem-get-node-element n) 0)
3644 (insert "]"))
3645
3646 (defstruct (js2-call-node
3647 (:include js2-node)
3648 (:constructor nil)
3649 (:constructor make-js2-call-node (&key (type js2-CALL)
3650 (pos js2-ts-cursor)
3651 len
3652 target
3653 args
3654 lp
3655 rp)))
3656 "AST node for a JavaScript function call."
3657 target ; a `js2-node' evaluating to the function to call
3658 args ; a lisp list of `js2-node' arguments
3659 lp ; position of open-paren, or nil if missing
3660 rp) ; position of close-paren, or nil if missing
3661
3662 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3663 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3664
3665 (defun js2-visit-call-node (n v)
3666 (js2-visit-ast (js2-call-node-target n) v)
3667 (dolist (arg (js2-call-node-args n))
3668 (js2-visit-ast arg v)))
3669
3670 (defun js2-print-call-node (n i)
3671 (insert (js2-make-pad i))
3672 (js2-print-ast (js2-call-node-target n) 0)
3673 (insert "(")
3674 (js2-print-list (js2-call-node-args n))
3675 (insert ")"))
3676
3677 (defstruct (js2-yield-node
3678 (:include js2-node)
3679 (:constructor nil)
3680 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3681 (pos js2-ts-cursor)
3682 len
3683 value)))
3684 "AST node for yield statement or expression."
3685 value) ; optional: value to be yielded
3686
3687 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3688 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3689
3690 (defun js2-visit-yield-node (n v)
3691 (js2-visit-ast (js2-yield-node-value n) v))
3692
3693 (defun js2-print-yield-node (n i)
3694 (insert (js2-make-pad i))
3695 (insert "yield")
3696 (when (js2-yield-node-value n)
3697 (insert " ")
3698 (js2-print-ast (js2-yield-node-value n) 0)))
3699
3700 (defstruct (js2-paren-node
3701 (:include js2-node)
3702 (:constructor nil)
3703 (:constructor make-js2-paren-node (&key (type js2-LP)
3704 (pos js2-ts-cursor)
3705 len
3706 expr)))
3707 "AST node for a parenthesized expression.
3708 In particular, used when the parens are syntactically optional,
3709 as opposed to required parens such as those enclosing an if-conditional."
3710 expr) ; `js2-node'
3711
3712 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3713 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3714
3715 (defun js2-visit-paren-node (n v)
3716 (js2-visit-ast (js2-paren-node-expr n) v))
3717
3718 (defun js2-print-paren-node (n i)
3719 (insert (js2-make-pad i))
3720 (insert "(")
3721 (js2-print-ast (js2-paren-node-expr n) 0)
3722 (insert ")"))
3723
3724 (defstruct (js2-array-comp-node
3725 (:include js2-scope)
3726 (:constructor nil)
3727 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3728 (pos js2-ts-cursor)
3729 len
3730 result
3731 loops
3732 filter
3733 if-pos
3734 lp
3735 rp)))
3736 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3737 result ; result expression (just after left-bracket)
3738 loops ; a lisp list of `js2-array-comp-loop-node'
3739 filter ; guard/filter expression
3740 if-pos ; buffer pos of 'if' keyword, if present, else nil
3741 lp ; buffer position of if-guard left-paren, or nil if not present
3742 rp) ; buffer position of if-guard right-paren, or nil if not present
3743
3744 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3745 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3746
3747 (defun js2-visit-array-comp-node (n v)
3748 (js2-visit-ast (js2-array-comp-node-result n) v)
3749 (dolist (l (js2-array-comp-node-loops n))
3750 (js2-visit-ast l v))
3751 (js2-visit-ast (js2-array-comp-node-filter n) v))
3752
3753 (defun js2-print-array-comp-node (n i)
3754 (let ((pad (js2-make-pad i))
3755 (result (js2-array-comp-node-result n))
3756 (loops (js2-array-comp-node-loops n))
3757 (filter (js2-array-comp-node-filter n)))
3758 (insert pad "[")
3759 (js2-print-ast result 0)
3760 (dolist (l loops)
3761 (insert " ")
3762 (js2-print-ast l 0))
3763 (when filter
3764 (insert " if (")
3765 (js2-print-ast filter 0))
3766 (insert ")]")))
3767
3768 (defstruct (js2-array-comp-loop-node
3769 (:include js2-for-in-node)
3770 (:constructor nil)
3771 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3772 (pos js2-ts-cursor)
3773 len
3774 iterator
3775 object
3776 in-pos
3777 foreach-p
3778 each-pos
3779 lp
3780 rp)))
3781 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3782
3783 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3784 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3785
3786 (defun js2-visit-array-comp-loop (n v)
3787 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3788 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3789
3790 (defun js2-print-array-comp-loop (n i)
3791 (insert "for (")
3792 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3793 (insert " in ")
3794 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3795 (insert ")"))
3796
3797 (defstruct (js2-empty-expr-node
3798 (:include js2-node)
3799 (:constructor nil)
3800 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3801 (pos js2-token-beg)
3802 len)))
3803 "AST node for an empty expression.")
3804
3805 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3806 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3807
3808 (defstruct (js2-xml-node
3809 (:include js2-block-node)
3810 (:constructor nil)
3811 (:constructor make-js2-xml-node (&key (type js2-XML)
3812 (pos js2-token-beg)
3813 len
3814 kids)))
3815 "AST node for initial parse of E4X literals.
3816 The kids field is a list of XML fragments, each a `js2-string-node' or
3817 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3818
3819 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3820 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3821
3822 (defun js2-print-xml-node (n i)
3823 (dolist (kid (js2-xml-node-kids n))
3824 (js2-print-ast kid i)))
3825
3826 (defstruct (js2-xml-js-expr-node
3827 (:include js2-xml-node)
3828 (:constructor nil)
3829 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3830 (pos js2-ts-cursor)
3831 len
3832 expr)))
3833 "AST node for an embedded JavaScript {expression} in an E4X literal.
3834 The start and end fields correspond to the curly-braces."
3835 expr) ; a `js2-expr-node' of some sort
3836
3837 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3838 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3839
3840 (defun js2-visit-xml-js-expr (n v)
3841 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3842
3843 (defun js2-print-xml-js-expr (n i)
3844 (insert (js2-make-pad i))
3845 (insert "{")
3846 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3847 (insert "}"))
3848
3849 (defstruct (js2-xml-dot-query-node
3850 (:include js2-infix-node)
3851 (:constructor nil)
3852 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3853 (pos js2-ts-cursor)
3854 op-pos
3855 len
3856 left
3857 right
3858 rp)))
3859 "AST node for an E4X foo.(bar) filter expression.
3860 Note that the left-paren is automatically the character immediately
3861 following the dot (.) in the operator. No whitespace is permitted
3862 between the dot and the lp by the scanner."
3863 rp)
3864
3865 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3866 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3867
3868 (defun js2-print-xml-dot-query (n i)
3869 (insert (js2-make-pad i))
3870 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3871 (insert ".(")
3872 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3873 (insert ")"))
3874
3875 (defstruct (js2-xml-ref-node
3876 (:include js2-node)
3877 (:constructor nil)) ; abstract
3878 "Base type for E4X XML attribute-access or property-get expressions.
3879 Such expressions can take a variety of forms. The general syntax has
3880 three parts:
3881
3882 - (optional) an @ (specifying an attribute access)
3883 - (optional) a namespace (a `js2-name-node') and double-colon
3884 - (required) either a `js2-name-node' or a bracketed [expression]
3885
3886 The property-name expressions (examples: ns::name, @name) are
3887 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3888 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3889
3890 This node type (or more specifically, its subclasses) will sometimes
3891 be the right-hand child of a `js2-prop-get-node' or a
3892 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3893 The `js2-xml-ref-node' may also be a standalone primary expression with
3894 no explicit target, which is valid in certain expression contexts such as
3895
3896 company..employee.(@id < 100)
3897
3898 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3899 expression whose parent is a `js2-xml-dot-query-node'."
3900 namespace
3901 at-pos
3902 colon-pos)
3903
3904 (defsubst js2-xml-ref-node-attr-access-p (node)
3905 "Return non-nil if this expression began with an @-token."
3906 (and (numberp (js2-xml-ref-node-at-pos node))
3907 (plusp (js2-xml-ref-node-at-pos node))))
3908
3909 (defstruct (js2-xml-prop-ref-node
3910 (:include js2-xml-ref-node)
3911 (:constructor nil)
3912 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3913 (pos js2-token-beg)
3914 len
3915 propname
3916 namespace
3917 at-pos
3918 colon-pos)))
3919 "AST node for an E4X XML [expr] property-ref expression.
3920 The JavaScript syntax is an optional @, an optional ns::, and a name.
3921
3922 [ '@' ] [ name '::' ] name
3923
3924 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3925 @ns::*, @*::attr, @*::*, and @*.
3926
3927 The node starts at the @ token, if present. Otherwise it starts at the
3928 namespace name. The node bounds extend through the closing right-bracket,
3929 or if it is missing due to a syntax error, through the end of the index
3930 expression."
3931 propname)
3932
3933 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3934 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3935
3936 (defun js2-visit-xml-prop-ref-node (n v)
3937 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3938 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3939
3940 (defun js2-print-xml-prop-ref-node (n i)
3941 (insert (js2-make-pad i))
3942 (if (js2-xml-ref-node-attr-access-p n)
3943 (insert "@"))
3944 (when (js2-xml-prop-ref-node-namespace n)
3945 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3946 (insert "::"))
3947 (if (js2-xml-prop-ref-node-propname n)
3948 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3949
3950 (defstruct (js2-xml-elem-ref-node
3951 (:include js2-xml-ref-node)
3952 (:constructor nil)
3953 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3954 (pos js2-token-beg)
3955 len
3956 expr
3957 lb
3958 rb
3959 namespace
3960 at-pos
3961 colon-pos)))
3962 "AST node for an E4X XML [expr] member-ref expression.
3963 Syntax:
3964
3965 [ '@' ] [ name '::' ] '[' expr ']'
3966
3967 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3968
3969 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3970 is not a legal E4X XML element-ref expression, since it's already used
3971 for standard JavaScript element-get array indexing. Hence, a
3972 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3973 non-nil namespace node, or both.
3974
3975 The node starts at the @ token, if present. Otherwise it starts
3976 at the namespace name. The node bounds extend through the closing
3977 right-bracket, or if it is missing due to a syntax error, through the
3978 end of the index expression."
3979 expr ; the bracketed index expression
3980 lb
3981 rb)
3982
3983 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3984 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3985
3986 (defun js2-visit-xml-elem-ref-node (n v)
3987 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3988 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3989
3990 (defun js2-print-xml-elem-ref-node (n i)
3991 (insert (js2-make-pad i))
3992 (if (js2-xml-ref-node-attr-access-p n)
3993 (insert "@"))
3994 (when (js2-xml-elem-ref-node-namespace n)
3995 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3996 (insert "::"))
3997 (insert "[")
3998 (if (js2-xml-elem-ref-node-expr n)
3999 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4000 (insert "]"))
4001
4002 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4003
4004 (defstruct (js2-xml-start-tag-node
4005 (:include js2-xml-node)
4006 (:constructor nil)
4007 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4008 (pos js2-ts-cursor)
4009 len
4010 name
4011 attrs
4012 kids
4013 empty-p)))
4014 "AST node for an XML start-tag. Not currently used.
4015 The `kids' field is a lisp list of child content nodes."
4016 name ; a `js2-xml-name-node'
4017 attrs ; a lisp list of `js2-xml-attr-node'
4018 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4019
4020 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4021 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4022
4023 (defun js2-visit-xml-start-tag (n v)
4024 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4025 (dolist (attr (js2-xml-start-tag-node-attrs n))
4026 (js2-visit-ast attr v))
4027 (js2-visit-block n v))
4028
4029 (defun js2-print-xml-start-tag (n i)
4030 (insert (js2-make-pad i) "<")
4031 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4032 (when (js2-xml-start-tag-node-attrs n)
4033 (insert " ")
4034 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4035 (insert ">"))
4036
4037 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4038 ;; and add the end-tag to the kids list of the parent as well.
4039 (defstruct (js2-xml-end-tag-node
4040 (:include js2-xml-node)
4041 (:constructor nil)
4042 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4043 (pos js2-ts-cursor)
4044 len
4045 name)))
4046 "AST node for an XML end-tag. Not currently used."
4047 name) ; a `js2-xml-name-node'
4048
4049 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4050 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4051
4052 (defun js2-visit-xml-end-tag (n v)
4053 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4054
4055 (defun js2-print-xml-end-tag (n i)
4056 (insert (js2-make-pad i))
4057 (insert "</")
4058 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4059 (insert ">"))
4060
4061 (defstruct (js2-xml-name-node
4062 (:include js2-xml-node)
4063 (:constructor nil)
4064 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4065 (pos js2-ts-cursor)
4066 len
4067 namespace
4068 kids)))
4069 "AST node for an E4X XML name. Not currently used.
4070 Any XML name can be qualified with a namespace, hence the namespace field.
4071 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4072 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4073 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4074 namespace) ; a `js2-string-node'
4075
4076 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4077 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4078
4079 (defun js2-visit-xml-name-node (n v)
4080 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4081
4082 (defun js2-print-xml-name-node (n i)
4083 (insert (js2-make-pad i))
4084 (when (js2-xml-name-node-namespace n)
4085 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4086 (insert "::"))
4087 (dolist (kid (js2-xml-name-node-kids n))
4088 (js2-print-ast kid 0)))
4089
4090 (defstruct (js2-xml-pi-node
4091 (:include js2-xml-node)
4092 (:constructor nil)
4093 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4094 (pos js2-ts-cursor)
4095 len
4096 name
4097 attrs)))
4098 "AST node for an E4X XML processing instruction. Not currently used."
4099 name ; a `js2-xml-name-node'
4100 attrs) ; a list of `js2-xml-attr-node'
4101
4102 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4103 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4104
4105 (defun js2-visit-xml-pi-node (n v)
4106 (js2-visit-ast (js2-xml-pi-node-name n) v)
4107 (dolist (attr (js2-xml-pi-node-attrs n))
4108 (js2-visit-ast attr v)))
4109
4110 (defun js2-print-xml-pi-node (n i)
4111 (insert (js2-make-pad i) "<?")
4112 (js2-print-ast (js2-xml-pi-node-name n))
4113 (when (js2-xml-pi-node-attrs n)
4114 (insert " ")
4115 (js2-print-list (js2-xml-pi-node-attrs n)))
4116 (insert "?>"))
4117
4118 (defstruct (js2-xml-cdata-node
4119 (:include js2-xml-node)
4120 (:constructor nil)
4121 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4122 (pos js2-ts-cursor)
4123 len
4124 content)))
4125 "AST node for a CDATA escape section. Not currently used."
4126 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4127
4128 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4129 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4130
4131 (defun js2-visit-xml-cdata-node (n v)
4132 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4133
4134 (defun js2-print-xml-cdata-node (n i)
4135 (insert (js2-make-pad i))
4136 (js2-print-ast (js2-xml-cdata-node-content n)))
4137
4138 (defstruct (js2-xml-attr-node
4139 (:include js2-xml-node)
4140 (:constructor nil)
4141 (:constructor make-js2-attr-node (&key (type js2-XML)
4142 (pos js2-ts-cursor)
4143 len
4144 name
4145 value
4146 eq-pos
4147 quote-type)))
4148 "AST node representing a foo='bar' XML attribute value. Not yet used."
4149 name ; a `js2-xml-name-node'
4150 value ; a `js2-xml-name-node'
4151 eq-pos ; buffer position of "=" sign
4152 quote-type) ; 'single or 'double
4153
4154 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4155 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4156
4157 (defun js2-visit-xml-attr-node (n v)
4158 (js2-visit-ast (js2-xml-attr-node-name n) v)
4159 (js2-visit-ast (js2-xml-attr-node-value n) v))
4160
4161 (defun js2-print-xml-attr-node (n i)
4162 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4163 "'"
4164 "\"")))
4165 (insert (js2-make-pad i))
4166 (js2-print-ast (js2-xml-attr-node-name n) 0)
4167 (insert "=" quote)
4168 (js2-print-ast (js2-xml-attr-node-value n) 0)
4169 (insert quote)))
4170
4171 (defstruct (js2-xml-text-node
4172 (:include js2-xml-node)
4173 (:constructor nil)
4174 (:constructor make-js2-text-node (&key (type js2-XML)
4175 (pos js2-ts-cursor)
4176 len
4177 content)))
4178 "AST node for an E4X XML text node. Not currently used."
4179 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4180
4181 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4182 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4183
4184 (defun js2-visit-xml-text-node (n v)
4185 (js2-visit-ast (js2-xml-text-node-content n) v))
4186
4187 (defun js2-print-xml-text-node (n i)
4188 (insert (js2-make-pad i))
4189 (dolist (kid (js2-xml-text-node-content n))
4190 (js2-print-ast kid)))
4191
4192 (defstruct (js2-xml-comment-node
4193 (:include js2-xml-node)
4194 (:constructor nil)
4195 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4196 (pos js2-ts-cursor)
4197 len)))
4198 "AST node for E4X XML comment. Not currently used.")
4199
4200 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4201 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4202
4203 (defun js2-print-xml-comment (n i)
4204 (insert (js2-make-pad i)
4205 (js2-node-string n)))
4206
4207 ;;; Node utilities
4208
4209 (defsubst js2-node-line (n)
4210 "Fetch the source line number at the start of node N.
4211 This is O(n) in the length of the source buffer; use prudently."
4212 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4213
4214 (defsubst js2-block-node-kid (n i)
4215 "Return child I of node N, or nil if there aren't that many."
4216 (nth i (js2-block-node-kids n)))
4217
4218 (defsubst js2-block-node-first (n)
4219 "Return first child of block node N, or nil if there is none."
4220 (first (js2-block-node-kids n)))
4221
4222 (defun js2-node-root (n)
4223 "Return the root of the AST containing N.
4224 If N has no parent pointer, returns N."
4225 (let ((parent (js2-node-parent n)))
4226 (if parent
4227 (js2-node-root parent)
4228 n)))
4229
4230 (defun js2-node-position-in-parent (node &optional parent)
4231 "Return the position of NODE in parent's block-kids list.
4232 PARENT can be supplied if known. Positioned returned is zero-indexed.
4233 Returns 0 if NODE is not a child of a block statement, or if NODE
4234 is not a statement node."
4235 (let ((p (or parent (js2-node-parent node)))
4236 (i 0))
4237 (if (not (js2-block-node-p p))
4238 i
4239 (or (js2-position node (js2-block-node-kids p))
4240 0))))
4241
4242 (defsubst js2-node-short-name (n)
4243 "Return the short name of node N as a string, e.g. `js2-if-node'."
4244 (substring (symbol-name (aref n 0))
4245 (length "cl-struct-")))
4246
4247 (defsubst js2-node-child-list (node)
4248 "Return the child list for NODE, a lisp list of nodes.
4249 Works for block nodes, array nodes, obj literals, funarg lists,
4250 var decls and try nodes (for catch clauses). Note that you should call
4251 `js2-block-node-kids' on the function body for the body statements.
4252 Returns nil for zero-length child lists or unsupported nodes."
4253 (cond
4254 ((js2-function-node-p node)
4255 (js2-function-node-params node))
4256 ((js2-block-node-p node)
4257 (js2-block-node-kids node))
4258 ((js2-try-node-p node)
4259 (js2-try-node-catch-clauses node))
4260 ((js2-array-node-p node)
4261 (js2-array-node-elems node))
4262 ((js2-object-node-p node)
4263 (js2-object-node-elems node))
4264 ((js2-call-node-p node)
4265 (js2-call-node-args node))
4266 ((js2-new-node-p node)
4267 (js2-new-node-args node))
4268 ((js2-var-decl-node-p node)
4269 (js2-var-decl-node-kids node))
4270 (t
4271 nil)))
4272
4273 (defsubst js2-node-set-child-list (node kids)
4274 "Set the child list for NODE to KIDS."
4275 (cond
4276 ((js2-function-node-p node)
4277 (setf (js2-function-node-params node) kids))
4278 ((js2-block-node-p node)
4279 (setf (js2-block-node-kids node) kids))
4280 ((js2-try-node-p node)
4281 (setf (js2-try-node-catch-clauses node) kids))
4282 ((js2-array-node-p node)
4283 (setf (js2-array-node-elems node) kids))
4284 ((js2-object-node-p node)
4285 (setf (js2-object-node-elems node) kids))
4286 ((js2-call-node-p node)
4287 (setf (js2-call-node-args node) kids))
4288 ((js2-new-node-p node)
4289 (setf (js2-new-node-args node) kids))
4290 ((js2-var-decl-node-p node)
4291 (setf (js2-var-decl-node-kids node) kids))
4292 (t
4293 (error "Unsupported node type: %s" (js2-node-short-name node))))
4294 kids)
4295
4296 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4297 (defconst js2-paren-expr-nodes
4298 '(cl-struct-js2-array-comp-loop-node
4299 cl-struct-js2-array-comp-node
4300 cl-struct-js2-call-node
4301 cl-struct-js2-catch-node
4302 cl-struct-js2-do-node
4303 cl-struct-js2-elem-get-node
4304 cl-struct-js2-for-in-node
4305 cl-struct-js2-for-node
4306 cl-struct-js2-function-node
4307 cl-struct-js2-if-node
4308 cl-struct-js2-let-node
4309 cl-struct-js2-new-node
4310 cl-struct-js2-paren-node
4311 cl-struct-js2-switch-node
4312 cl-struct-js2-while-node
4313 cl-struct-js2-with-node
4314 cl-struct-js2-xml-dot-query-node)
4315 "Node types that can have a parenthesized child expression.
4316 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4317
4318 (defsubst js2-paren-expr-node-p (node)
4319 "Return t for nodes that typically have a parenthesized child expression.
4320 Useful for computing the indentation anchors for arg-lists and conditions.
4321 Note that it may return a false positive, for instance when NODE is
4322 a `js2-new-node' and there are no arguments or parentheses."
4323 (memq (aref node 0) js2-paren-expr-nodes))
4324
4325 ;; Fake polymorphism... yech.
4326 (defsubst js2-node-lp (node)
4327 "Return relative left-paren position for NODE, if applicable.
4328 For `js2-elem-get-node' structs, returns left-bracket position.
4329 Note that the position may be nil in the case of a parse error."
4330 (cond
4331 ((js2-elem-get-node-p node)
4332 (js2-elem-get-node-lb node))
4333 ((js2-loop-node-p node)
4334 (js2-loop-node-lp node))
4335 ((js2-function-node-p node)
4336 (js2-function-node-lp node))
4337 ((js2-if-node-p node)
4338 (js2-if-node-lp node))
4339 ((js2-new-node-p node)
4340 (js2-new-node-lp node))
4341 ((js2-call-node-p node)
4342 (js2-call-node-lp node))
4343 ((js2-paren-node-p node)
4344 (js2-node-pos node))
4345 ((js2-switch-node-p node)
4346 (js2-switch-node-lp node))
4347 ((js2-catch-node-p node)
4348 (js2-catch-node-lp node))
4349 ((js2-let-node-p node)
4350 (js2-let-node-lp node))
4351 ((js2-array-comp-node-p node)
4352 (js2-array-comp-node-lp node))
4353 ((js2-with-node-p node)
4354 (js2-with-node-lp node))
4355 ((js2-xml-dot-query-node-p node)
4356 (1+ (js2-infix-node-op-pos node)))
4357 (t
4358 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4359
4360 ;; Fake polymorphism... blech.
4361 (defsubst js2-node-rp (node)
4362 "Return relative right-paren position for NODE, if applicable.
4363 For `js2-elem-get-node' structs, returns right-bracket position.
4364 Note that the position may be nil in the case of a parse error."
4365 (cond
4366 ((js2-elem-get-node-p node)
4367 (js2-elem-get-node-lb node))
4368 ((js2-loop-node-p node)
4369 (js2-loop-node-rp node))
4370 ((js2-function-node-p node)
4371 (js2-function-node-rp node))
4372 ((js2-if-node-p node)
4373 (js2-if-node-rp node))
4374 ((js2-new-node-p node)
4375 (js2-new-node-rp node))
4376 ((js2-call-node-p node)
4377 (js2-call-node-rp node))
4378 ((js2-paren-node-p node)
4379 (+ (js2-node-pos node) (js2-node-len node)))
4380 ((js2-switch-node-p node)
4381 (js2-switch-node-rp node))
4382 ((js2-catch-node-p node)
4383 (js2-catch-node-rp node))
4384 ((js2-let-node-p node)
4385 (js2-let-node-rp node))
4386 ((js2-array-comp-node-p node)
4387 (js2-array-comp-node-rp node))
4388 ((js2-with-node-p node)
4389 (js2-with-node-rp node))
4390 ((js2-xml-dot-query-node-p node)
4391 (1+ (js2-xml-dot-query-node-rp node)))
4392 (t
4393 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4394
4395 (defsubst js2-node-first-child (node)
4396 "Returns the first element of `js2-node-child-list' for NODE."
4397 (car (js2-node-child-list node)))
4398
4399 (defsubst js2-node-last-child (node)
4400 "Returns the last element of `js2-node-last-child' for NODE."
4401 (car (last (js2-node-child-list node))))
4402
4403 (defun js2-node-prev-sibling (node)
4404 "Return the previous statement in parent.
4405 Works for parents supported by `js2-node-child-list'.
4406 Returns nil if NODE is not in the parent, or PARENT is
4407 not a supported node, or if NODE is the first child."
4408 (let* ((p (js2-node-parent node))
4409 (kids (js2-node-child-list p))
4410 (sib (car kids)))
4411 (while (and kids
4412 (not (eq node (cadr kids))))
4413 (setq kids (cdr kids)
4414 sib (car kids)))
4415 sib))
4416
4417 (defun js2-node-next-sibling (node)
4418 "Return the next statement in parent block.
4419 Returns nil if NODE is not in the block, or PARENT is not
4420 a block node, or if NODE is the last statement."
4421 (let* ((p (js2-node-parent node))
4422 (kids (js2-node-child-list p)))
4423 (while (and kids
4424 (not (eq node (car kids))))
4425 (setq kids (cdr kids)))
4426 (cadr kids)))
4427
4428 (defun js2-node-find-child-before (pos parent &optional after)
4429 "Find the last child that starts before POS in parent.
4430 If AFTER is non-nil, returns first child starting after POS.
4431 POS is an absolute buffer position. PARENT is any node
4432 supported by `js2-node-child-list'.
4433 Returns nil if no applicable child is found."
4434 (let ((kids (if (js2-function-node-p parent)
4435 (js2-block-node-kids (js2-function-node-body parent))
4436 (js2-node-child-list parent)))
4437 (beg (if (js2-function-node-p parent)
4438 (js2-node-abs-pos (js2-function-node-body parent))
4439 (js2-node-abs-pos parent)))
4440 kid
4441 result
4442 fn
4443 (continue t))
4444 (setq fn (if after '> '<))
4445 (while (and kids continue)
4446 (setq kid (car kids))
4447 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4448 (setq result kid
4449 continue (if after nil t))
4450 (setq continue (if after t nil)))
4451 (setq kids (cdr kids)))
4452 result))
4453
4454 (defun js2-node-find-child-after (pos parent)
4455 "Find first child that starts after POS in parent.
4456 POS is an absolute buffer position. PARENT is any node
4457 supported by `js2-node-child-list'.
4458 Returns nil if no applicable child is found."
4459 (js2-node-find-child-before pos parent 'after))
4460
4461 (defun js2-node-replace-child (pos parent new-node)
4462 "Replace node at index POS in PARENT with NEW-NODE.
4463 Only works for parents supported by `js2-node-child-list'."
4464 (let ((kids (js2-node-child-list parent))
4465 (i 0))
4466 (while (< i pos)
4467 (setq kids (cdr kids)
4468 i (1+ i)))
4469 (setcar kids new-node)
4470 (js2-node-add-children parent new-node)))
4471
4472 (defun js2-node-buffer (n)
4473 "Return the buffer associated with AST N.
4474 Returns nil if the buffer is not set as a property on the root
4475 node, or if parent links were not recorded during parsing."
4476 (let ((root (js2-node-root n)))
4477 (and root
4478 (js2-ast-root-p root)
4479 (js2-ast-root-buffer root))))
4480
4481 (defsubst js2-block-node-push (n kid)
4482 "Push js2-node KID onto the end of js2-block-node N's child list.
4483 KID is always added to the -end- of the kids list.
4484 Function also calls `js2-node-add-children' to add the parent link."
4485 (let ((kids (js2-node-child-list n)))
4486 (if kids
4487 (setcdr kids (nconc (cdr kids) (list kid)))
4488 (js2-node-set-child-list n (list kid)))
4489 (js2-node-add-children n kid)))
4490
4491 (defun js2-node-string (node)
4492 (let ((buf (js2-node-buffer node))
4493 pos)
4494 (unless buf
4495 (error "No buffer available for node %s" node))
4496 (save-excursion
4497 (set-buffer buf)
4498 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4499 (+ pos (js2-node-len node))))))
4500
4501 ;; Container for storing the node we're looking for in a traversal.
4502 (js2-deflocal js2-discovered-node nil)
4503
4504 ;; Keep track of absolute node position during traversals.
4505 (js2-deflocal js2-visitor-offset nil)
4506
4507 (js2-deflocal js2-node-search-point nil)
4508
4509 (when js2-mode-dev-mode-p
4510 (defun js2-find-node-at-point ()
4511 (interactive)
4512 (let ((node (js2-node-at-point)))
4513 (message "%s" (or node "No node found at point"))))
4514 (defun js2-node-name-at-point ()
4515 (interactive)
4516 (let ((node (js2-node-at-point)))
4517 (message "%s" (if node
4518 (js2-node-short-name node)
4519 "No node found at point.")))))
4520
4521 (defun js2-node-at-point (&optional pos skip-comments)
4522 "Return AST node at POS, a buffer position, defaulting to current point.
4523 The `js2-mode-ast' variable must be set to the current parse tree.
4524 Signals an error if the AST (`js2-mode-ast') is nil.
4525 Always returns a node - if it can't find one, it returns the root.
4526 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4527 (let ((ast js2-mode-ast)
4528 result)
4529 (unless ast
4530 (error "No JavaScript AST available"))
4531 ;; Look through comments first, since they may be inside nodes that
4532 ;; would otherwise report a match.
4533 (setq pos (or pos (point))
4534 result (if (> pos (js2-node-abs-end ast))
4535 ast
4536 (if (not skip-comments)
4537 (js2-comment-at-point pos))))
4538 (unless result
4539 (setq js2-discovered-node nil
4540 js2-visitor-offset 0
4541 js2-node-search-point pos)
4542 (unwind-protect
4543 (catch 'js2-visit-done
4544 (js2-visit-ast ast #'js2-node-at-point-visitor))
4545 (setq js2-visitor-offset nil
4546 js2-node-search-point nil))
4547 (setq result js2-discovered-node))
4548 ;; may have found a comment beyond end of last child node,
4549 ;; since visiting the ast-root looks at the comment-list last.
4550 (if (and skip-comments
4551 (js2-comment-node-p result))
4552 (setq result nil))
4553 (or result js2-mode-ast)))
4554
4555 (defun js2-node-at-point-visitor (node end-p)
4556 (let ((rel-pos (js2-node-pos node))
4557 abs-pos
4558 abs-end
4559 (point js2-node-search-point))
4560 (cond
4561 (end-p
4562 ;; this evaluates to a non-nil return value, even if it's zero
4563 (decf js2-visitor-offset rel-pos))
4564 ;; we already looked for comments before visiting, and don't want them now
4565 ((js2-comment-node-p node)
4566 nil)
4567 (t
4568 (setq abs-pos (incf js2-visitor-offset rel-pos)
4569 ;; we only want to use the node if the point is before
4570 ;; the last character position in the node, so we decrement
4571 ;; the absolute end by 1.
4572 abs-end (+ abs-pos (js2-node-len node) -1))
4573 (cond
4574 ;; If this node starts after search-point, stop the search.
4575 ((> abs-pos point)
4576 (throw 'js2-visit-done nil))
4577 ;; If this node ends before the search-point, don't check kids.
4578 ((> point abs-end)
4579 nil)
4580 (t
4581 ;; Otherwise point is within this node, possibly in a child.
4582 (setq js2-discovered-node node)
4583 t)))))) ; keep processing kids to look for more specific match
4584
4585 (defsubst js2-block-comment-p (node)
4586 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4587 (and (js2-comment-node-p node)
4588 (memq (js2-comment-node-format node) '(jsdoc block))))
4589
4590 ;; TODO: put the comments in a vector and binary-search them instead
4591 (defun js2-comment-at-point (&optional pos)
4592 "Look through scanned comment nodes for one containing POS.
4593 POS is a buffer position that defaults to current point.
4594 Function returns nil if POS was not in any comment node."
4595 (let ((ast js2-mode-ast)
4596 (x (or pos (point)))
4597 beg
4598 end)
4599 (unless ast
4600 (error "No JavaScript AST available"))
4601 (catch 'done
4602 ;; Comments are stored in lexical order.
4603 (dolist (comment (js2-ast-root-comments ast) nil)
4604 (setq beg (js2-node-abs-pos comment)
4605 end (+ beg (js2-node-len comment)))
4606 (if (and (>= x beg)
4607 (<= x end))
4608 (throw 'done comment))))))
4609
4610 (defun js2-mode-find-parent-fn (node)
4611 "Find function enclosing NODE.
4612 Returns nil if NODE is not inside a function."
4613 (setq node (js2-node-parent node))
4614 (while (and node (not (js2-function-node-p node)))
4615 (setq node (js2-node-parent node)))
4616 (and (js2-function-node-p node) node))
4617
4618 (defun js2-mode-find-enclosing-fn (node)
4619 "Find function or root enclosing NODE."
4620 (if (js2-ast-root-p node)
4621 node
4622 (setq node (js2-node-parent node))
4623 (while (not (or (js2-ast-root-p node)
4624 (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 node))
4627
4628 (defun js2-mode-find-enclosing-node (beg end)
4629 "Find script or function fully enclosing BEG and END."
4630 (let ((node (js2-node-at-point beg))
4631 pos
4632 (continue t))
4633 (while continue
4634 (if (or (js2-ast-root-p node)
4635 (and (js2-function-node-p node)
4636 (<= (setq pos (js2-node-abs-pos node)) beg)
4637 (>= (+ pos (js2-node-len node)) end)))
4638 (setq continue nil)
4639 (setq node (js2-node-parent node))))
4640 node))
4641
4642 (defun js2-node-parent-script-or-fn (node)
4643 "Find script or function immediately enclosing NODE.
4644 If NODE is the ast-root, returns nil."
4645 (if (js2-ast-root-p node)
4646 nil
4647 (setq node (js2-node-parent node))
4648 (while (and node (not (or (js2-function-node-p node)
4649 (js2-script-node-p node))))
4650 (setq node (js2-node-parent node)))
4651 node))
4652
4653 (defsubst js2-nested-function-p (node)
4654 "Return t if NODE is a nested function, or is inside a nested function."
4655 (unless (js2-ast-root-p node)
4656 (js2-function-node-p (if (js2-function-node-p node)
4657 (js2-node-parent-script-or-fn node)
4658 (js2-node-parent-script-or-fn
4659 (js2-node-parent-script-or-fn node))))))
4660
4661 (defsubst js2-function-param-node-p (node)
4662 "Return non-nil if NODE is a param node of a `js2-function-node'."
4663 (let ((parent (js2-node-parent node)))
4664 (and parent
4665 (js2-function-node-p parent)
4666 (memq node (js2-function-node-params parent)))))
4667
4668 (defsubst js2-mode-shift-kids (kids start offset)
4669 (dolist (kid kids)
4670 (if (> (js2-node-pos kid) start)
4671 (incf (js2-node-pos kid) offset))))
4672
4673 (defsubst js2-mode-shift-children (parent start offset)
4674 "Update start-positions of all children of PARENT beyond START."
4675 (let ((root (js2-node-root parent)))
4676 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4677 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4678
4679 (defsubst js2-node-is-descendant (node ancestor)
4680 "Return t if NODE is a descendant of ANCESTOR."
4681 (while (and node
4682 (not (eq node ancestor)))
4683 (setq node (js2-node-parent node)))
4684 node)
4685
4686 ;;; visitor infrastructure
4687
4688 (defun js2-visit-none (node callback)
4689 "Visitor for AST node that have no node children."
4690 nil)
4691
4692 (defun js2-print-none (node indent)
4693 "Visitor for AST node with no printed representation.")
4694
4695 (defun js2-print-body (node indent)
4696 "Print a statement, or a block without braces."
4697 (if (js2-block-node-p node)
4698 (dolist (kid (js2-block-node-kids node))
4699 (js2-print-ast kid indent))
4700 (js2-print-ast node indent)))
4701
4702 (defun js2-print-list (args &optional delimiter)
4703 (loop with len = (length args)
4704 for arg in args
4705 for count from 1
4706 do
4707 (js2-print-ast arg 0)
4708 (if (< count len)
4709 (insert (or delimiter ", ")))))
4710
4711 (defun js2-print-tree (ast)
4712 "Prints an AST to the current buffer.
4713 Makes `js2-ast-parent-nodes' available to the printer functions."
4714 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4715 (js2-print-ast ast)))
4716
4717 (defun js2-print-ast (node &optional indent)
4718 "Helper function for printing AST nodes.
4719 Requires `js2-ast-parent-nodes' to be non-nil.
4720 You should use `js2-print-tree' instead of this function."
4721 (let ((printer (get (aref node 0) 'js2-printer))
4722 (i (or indent 0))
4723 (pos (js2-node-abs-pos node)))
4724 ;; TODO: wedge comments in here somewhere
4725 (if printer
4726 (funcall printer node i))))
4727
4728 (defconst js2-side-effecting-tokens
4729 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4730 (dolist (tt (list js2-ASSIGN
4731 js2-ASSIGN_ADD
4732 js2-ASSIGN_BITAND
4733 js2-ASSIGN_BITOR
4734 js2-ASSIGN_BITXOR
4735 js2-ASSIGN_DIV
4736 js2-ASSIGN_LSH
4737 js2-ASSIGN_MOD
4738 js2-ASSIGN_MUL
4739 js2-ASSIGN_RSH
4740 js2-ASSIGN_SUB
4741 js2-ASSIGN_URSH
4742 js2-BLOCK
4743 js2-BREAK
4744 js2-CALL
4745 js2-CATCH
4746 js2-CATCH_SCOPE
4747 js2-CONST
4748 js2-CONTINUE
4749 js2-DEBUGGER
4750 js2-DEC
4751 js2-DELPROP
4752 js2-DEL_REF
4753 js2-DO
4754 js2-ELSE
4755 js2-EMPTY
4756 js2-ENTERWITH
4757 js2-EXPORT
4758 js2-EXPR_RESULT
4759 js2-FINALLY
4760 js2-FOR
4761 js2-FUNCTION
4762 js2-GOTO
4763 js2-IF
4764 js2-IFEQ
4765 js2-IFNE
4766 js2-IMPORT
4767 js2-INC
4768 js2-JSR
4769 js2-LABEL
4770 js2-LEAVEWITH
4771 js2-LET
4772 js2-LETEXPR
4773 js2-LOCAL_BLOCK
4774 js2-LOOP
4775 js2-NEW
4776 js2-REF_CALL
4777 js2-RETHROW
4778 js2-RETURN
4779 js2-RETURN_RESULT
4780 js2-SEMI
4781 js2-SETELEM
4782 js2-SETELEM_OP
4783 js2-SETNAME
4784 js2-SETPROP
4785 js2-SETPROP_OP
4786 js2-SETVAR
4787 js2-SET_REF
4788 js2-SET_REF_OP
4789 js2-SWITCH
4790 js2-TARGET
4791 js2-THROW
4792 js2-TRY
4793 js2-VAR
4794 js2-WHILE
4795 js2-WITH
4796 js2-WITHEXPR
4797 js2-YIELD))
4798 (aset tokens tt t))
4799 (if js2-instanceof-has-side-effects
4800 (aset tokens js2-INSTANCEOF t))
4801 tokens))
4802
4803 (defun js2-node-has-side-effects (node)
4804 "Return t if NODE has side effects."
4805 (when node ; makes it easier to handle malformed expressions
4806 (let ((tt (js2-node-type node)))
4807 (cond
4808 ;; This doubtless needs some work, since EXPR_VOID is used
4809 ;; in several ways in Rhino, and I may not have caught them all.
4810 ;; I'll wait for people to notice incorrect warnings.
4811 ((and (= tt js2-EXPR_VOID)
4812 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4813 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4814 ((= tt js2-COMMA)
4815 (js2-node-has-side-effects (js2-infix-node-right node)))
4816 ((or (= tt js2-AND)
4817 (= tt js2-OR))
4818 (or (js2-node-has-side-effects (js2-infix-node-right node))
4819 (js2-node-has-side-effects (js2-infix-node-left node))))
4820 ((= tt js2-HOOK)
4821 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4822 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4823 ((js2-paren-node-p node)
4824 (js2-node-has-side-effects (js2-paren-node-expr node)))
4825 ((= tt js2-ERROR) ; avoid cascaded error messages
4826 nil)
4827 (t
4828 (aref js2-side-effecting-tokens tt))))))
4829
4830 (defun js2-member-expr-leftmost-name (node)
4831 "For an expr such as foo.bar.baz, return leftmost node foo.
4832 NODE is any `js2-node' object. If it represents a member expression,
4833 which is any sequence of property gets, element-gets, function calls,
4834 or xml descendants/filter operators, then we look at the lexically
4835 leftmost (first) node in the chain. If it is a name-node we return it.
4836 Note that NODE can be a raw name-node and it will be returned as well.
4837 If NODE is not a name-node or member expression, or if it is a member
4838 expression whose leftmost target is not a name node, returns nil."
4839 (let ((continue t)
4840 result)
4841 (while (and continue (not result))
4842 (cond
4843 ((js2-name-node-p node)
4844 (setq result node))
4845 ((js2-prop-get-node-p node)
4846 (setq node (js2-prop-get-node-left node)))
4847 ;; TODO: handle call-nodes, xml-nodes, others?
4848 (t
4849 (setq continue nil))))
4850 result))
4851
4852 (defconst js2-stmt-node-types
4853 (list js2-BLOCK
4854 js2-BREAK
4855 js2-CONTINUE
4856 js2-DEFAULT ; e4x "default xml namespace" statement
4857 js2-DO
4858 js2-EXPR_RESULT
4859 js2-EXPR_VOID
4860 js2-FOR
4861 js2-IF
4862 js2-RETURN
4863 js2-SWITCH
4864 js2-THROW
4865 js2-TRY
4866 js2-WHILE
4867 js2-WITH)
4868 "Node types that only appear in statement contexts.
4869 The list does not include nodes that always appear as the child
4870 of another specific statement type, such as switch-cases,
4871 catch and finally blocks, and else-clauses. The list also excludes
4872 nodes like yield, let and var, which may appear in either expression
4873 or statement context, and in the latter context always have a
4874 `js2-expr-stmt-node' parent. Finally, the list does not include
4875 functions or scripts, which are treated separately from statements
4876 by the JavaScript parser and runtime.")
4877
4878 (defun js2-stmt-node-p (node)
4879 "Heuristic for figuring out if NODE is a statement.
4880 Some node types can appear in either an expression context or a
4881 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4882 For these node types in a statement context, the parent will be a
4883 `js2-expr-stmt-node'.
4884 Functions aren't included in the check."
4885 (memq (js2-node-type node) js2-stmt-node-types))
4886
4887 (defsubst js2-mode-find-first-stmt (node)
4888 "Search upward starting from NODE looking for a statement.
4889 For purposes of this function, a `js2-function-node' counts."
4890 (while (not (or (js2-stmt-node-p node)
4891 (js2-function-node-p node)))
4892 (setq node (js2-node-parent node)))
4893 node)
4894
4895 (defun js2-node-parent-stmt (node)
4896 "Return the node's first ancestor that is a statement.
4897 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4898 appearing in a statement context will have a parent that is a
4899 `js2-expr-stmt-node' that will be returned by this function."
4900 (let ((parent (js2-node-parent node)))
4901 (if (or (null parent)
4902 (js2-stmt-node-p parent)
4903 (and (js2-function-node-p parent)
4904 (not (eq (js2-function-node-form parent)
4905 'FUNCTION_EXPRESSION))))
4906 parent
4907 (js2-node-parent-stmt parent))))
4908
4909 ;; In the Mozilla Rhino sources, Roshan James writes:
4910 ;; Does consistent-return analysis on the function body when strict mode is
4911 ;; enabled.
4912 ;;
4913 ;; function (x) { return (x+1) }
4914 ;;
4915 ;; is ok, but
4916 ;;
4917 ;; function (x) { if (x < 0) return (x+1); }
4918 ;;
4919 ;; is not because the function can potentially return a value when the
4920 ;; condition is satisfied and if not, the function does not explicitly
4921 ;; return a value.
4922 ;;
4923 ;; This extends to checking mismatches such as "return" and "return <value>"
4924 ;; used in the same function. Warnings are not emitted if inconsistent
4925 ;; returns exist in code that can be statically shown to be unreachable.
4926 ;; Ex.
4927 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4928 ;;
4929 ;; emits no warning. However if the loop had a break statement, then a
4930 ;; warning would be emitted.
4931 ;;
4932 ;; The consistency analysis looks at control structures such as loops, ifs,
4933 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4934 ;; warns the user about an inconsistent set of termination possibilities.
4935 ;;
4936 ;; These flags enumerate the possible ways a statement/function can
4937 ;; terminate. These flags are used by endCheck() and by the Parser to
4938 ;; detect inconsistent return usage.
4939 ;;
4940 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4941 ;; able to execute (example: throw, continue)
4942 ;;
4943 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4944 ;; next one. Statement such as return dont. A compound statement may have
4945 ;; some branch that drops off control to the next statement.
4946 ;;
4947 ;; END_RETURNS indicates that the statement can return with no value.
4948 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4949 ;;
4950 ;; A compound statement such as
4951 ;; if (condition) {
4952 ;; return value;
4953 ;; }
4954 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4955
4956 (defconst js2-END_UNREACHED 0)
4957 (defconst js2-END_DROPS_OFF 1)
4958 (defconst js2-END_RETURNS 2)
4959 (defconst js2-END_RETURNS_VALUE 4)
4960 (defconst js2-END_YIELDS 8)
4961
4962 (defun js2-has-consistent-return-usage (node)
4963 "Check that every return usage in a function body is consistent.
4964 Returns t if the function satisfies strict mode requirement."
4965 (let ((n (js2-end-check node)))
4966 ;; either it doesn't return a value in any branch...
4967 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4968 ;; or it returns a value (or is unreached) at every branch
4969 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4970 js2-END_RETURNS
4971 js2-END_YIELDS)))))
4972
4973 (defun js2-end-check-if (node)
4974 "Returns in the then and else blocks must be consistent with each other.
4975 If there is no else block, then the return statement can fall through.
4976 Returns logical OR of END_* flags"
4977 (let ((th (js2-if-node-then-part node))
4978 (el (js2-if-node-else-part node)))
4979 (if (null th)
4980 js2-END_UNREACHED
4981 (logior (js2-end-check th) (if el
4982 (js2-end-check el)
4983 js2-END_DROPS_OFF)))))
4984
4985 (defun js2-end-check-switch (node)
4986 "Consistency of return statements is checked between the case statements.
4987 If there is no default, then the switch can fall through. If there is a
4988 default, we check to see if all code paths in the default return or if
4989 there is a code path that can fall through.
4990 Returns logical OR of END_* flags."
4991 (let ((rv js2-END_UNREACHED)
4992 default-case)
4993 ;; examine the cases
4994 (catch 'break
4995 (dolist (c (js2-switch-node-cases node))
4996 (if (js2-case-node-expr c)
4997 (js2-set-flag rv (js2-end-check-block c))
4998 (setq default-case c)
4999 (throw 'break nil))))
5000 ;; we don't care how the cases drop into each other
5001 (js2-clear-flag rv js2-END_DROPS_OFF)
5002 ;; examine the default
5003 (js2-set-flag rv (if default-case
5004 (js2-end-check default-case)
5005 js2-END_DROPS_OFF))
5006 rv))
5007
5008 (defun js2-end-check-try (node)
5009 "If the block has a finally, return consistency is checked in the
5010 finally block. If all code paths in the finally return, then the
5011 returns in the try-catch blocks don't matter. If there is a code path
5012 that does not return or if there is no finally block, the returns
5013 of the try and catch blocks are checked for mismatch.
5014 Returns logical OR of END_* flags."
5015 (let ((finally (js2-try-node-finally-block node))
5016 rv)
5017 ;; check the finally if it exists
5018 (setq rv (if finally
5019 (js2-end-check (js2-finally-node-body finally))
5020 js2-END_DROPS_OFF))
5021 ;; If the finally block always returns, then none of the returns
5022 ;; in the try or catch blocks matter.
5023 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5024 (js2-clear-flag rv js2-END_DROPS_OFF)
5025 ;; examine the try block
5026 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5027 ;; check each catch block
5028 (dolist (cb (js2-try-node-catch-clauses node))
5029 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5030 rv))
5031
5032 (defun js2-end-check-loop (node)
5033 "Return statement in the loop body must be consistent. The default
5034 assumption for any kind of a loop is that it will eventually terminate.
5035 The only exception is a loop with a constant true condition. Code that
5036 follows such a loop is examined only if one can statically determine
5037 that there is a break out of the loop.
5038
5039 for(... ; ... ; ...) {}
5040 for(... in ... ) {}
5041 while(...) { }
5042 do { } while(...)
5043
5044 Returns logical OR of END_* flags."
5045 (let ((rv (js2-end-check (js2-loop-node-body node)))
5046 (condition (cond
5047 ((js2-while-node-p node)
5048 (js2-while-node-condition node))
5049 ((js2-do-node-p node)
5050 (js2-do-node-condition node))
5051 ((js2-for-node-p node)
5052 (js2-for-node-condition node)))))
5053
5054 ;; check to see if the loop condition is always true
5055 (if (and condition
5056 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5057 (js2-clear-flag rv js2-END_DROPS_OFF))
5058
5059 ;; look for effect of breaks
5060 (js2-set-flag rv (js2-node-get-prop node
5061 'CONTROL_BLOCK_PROP
5062 js2-END_UNREACHED))
5063 rv))
5064
5065 (defun js2-end-check-block (node)
5066 "A general block of code is examined statement by statement.
5067 If any statement (even a compound one) returns in all branches, then
5068 subsequent statements are not examined.
5069 Returns logical OR of END_* flags."
5070 (let* ((rv js2-END_DROPS_OFF)
5071 (kids (js2-block-node-kids node))
5072 (n (car kids)))
5073 ;; Check each statment. If the statement can continue onto the next
5074 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5075 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5076 (js2-clear-flag rv js2-END_DROPS_OFF)
5077 (js2-set-flag rv (js2-end-check n))
5078 (setq kids (cdr kids)
5079 n (car kids)))
5080 rv))
5081
5082 (defun js2-end-check-label (node)
5083 "A labeled statement implies that there may be a break to the label.
5084 The function processes the labeled statement and then checks the
5085 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5086 particular label.
5087 Returns logical OR of END_* flags."
5088 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5089 (logior rv (js2-node-get-prop node
5090 'CONTROL_BLOCK_PROP
5091 js2-END_UNREACHED))))
5092
5093 (defun js2-end-check-break (node)
5094 "When a break is encountered annotate the statement being broken
5095 out of by setting its CONTROL_BLOCK_PROP property.
5096 Returns logical OR of END_* flags."
5097 (and (js2-break-node-target node)
5098 (js2-node-set-prop (js2-break-node-target node)
5099 'CONTROL_BLOCK_PROP
5100 js2-END_DROPS_OFF))
5101 js2-END_UNREACHED)
5102
5103 (defun js2-end-check (node)
5104 "Examine the body of a function, doing a basic reachability analysis.
5105 Returns a combination of flags END_* flags that indicate
5106 how the function execution can terminate. These constitute only the
5107 pessimistic set of termination conditions. It is possible that at
5108 runtime certain code paths will never be actually taken. Hence this
5109 analysis will flag errors in cases where there may not be errors.
5110 Returns logical OR of END_* flags"
5111 (let (kid)
5112 (cond
5113 ((js2-break-node-p node)
5114 (js2-end-check-break node))
5115 ((js2-expr-stmt-node-p node)
5116 (if (setq kid (js2-expr-stmt-node-expr node))
5117 (js2-end-check kid)
5118 js2-END_DROPS_OFF))
5119 ((or (js2-continue-node-p node)
5120 (js2-throw-node-p node))
5121 js2-END_UNREACHED)
5122 ((js2-return-node-p node)
5123 (if (setq kid (js2-return-node-retval node))
5124 js2-END_RETURNS_VALUE
5125 js2-END_RETURNS))
5126 ((js2-loop-node-p node)
5127 (js2-end-check-loop node))
5128 ((js2-switch-node-p node)
5129 (js2-end-check-switch node))
5130 ((js2-labeled-stmt-node-p node)
5131 (js2-end-check-label node))
5132 ((js2-if-node-p node)
5133 (js2-end-check-if node))
5134 ((js2-try-node-p node)
5135 (js2-end-check-try node))
5136 ((js2-block-node-p node)
5137 (if (null (js2-block-node-kids node))
5138 js2-END_DROPS_OFF
5139 (js2-end-check-block node)))
5140 ((js2-yield-node-p node)
5141 js2-END_YIELDS)
5142 (t
5143 js2-END_DROPS_OFF))))
5144
5145 (defun js2-always-defined-boolean-p (node)
5146 "Check if NODE always evaluates to true or false in boolean context.
5147 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5148 nor always false."
5149 (let ((tt (js2-node-type node))
5150 num)
5151 (cond
5152 ((or (= tt js2-FALSE) (= tt js2-NULL))
5153 'ALWAYS_FALSE)
5154 ((= tt js2-TRUE)
5155 'ALWAYS_TRUE)
5156 ((= tt js2-NUMBER)
5157 (setq num (js2-number-node-num-value node))
5158 (if (and (not (eq num 0.0e+NaN))
5159 (not (zerop num)))
5160 'ALWAYS_TRUE
5161 'ALWAYS_FALSE))
5162 (t
5163 nil))))
5164
5165 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5166 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5167
5168 (defvar js2-tokens nil
5169 "List of all defined token names.") ; initialized in `js2-token-names'
5170
5171 (defconst js2-token-names
5172 (let* ((names (make-vector js2-num-tokens -1))
5173 (case-fold-search nil) ; only match js2-UPPER_CASE
5174 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5175 (loop for sym in syms
5176 for i from 0
5177 do
5178 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5179 (not (boundp sym)))
5180 (aset names (symbol-value sym) ; code, e.g. 152
5181 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5182 (push sym js2-tokens)))
5183 names)
5184 "Vector mapping int values to token string names, sans `js2-' prefix.")
5185
5186 (defun js2-token-name (tok)
5187 "Return a string name for TOK, a token symbol or code.
5188 Signals an error if it's not a recognized token."
5189 (let ((code tok))
5190 (if (symbolp tok)
5191 (setq code (symbol-value tok)))
5192 (if (eq code -1)
5193 "ERROR"
5194 (if (and (numberp code)
5195 (not (minusp code))
5196 (< code js2-num-tokens))
5197 (aref js2-token-names code)
5198 (error "Invalid token: %s" code)))))
5199
5200 (defsubst js2-token-sym (tok)
5201 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5202 (intern (js2-token-name tok)))
5203
5204 (defconst js2-token-codes
5205 (let ((table (make-hash-table :test 'eq :size 256)))
5206 (loop for name across js2-token-names
5207 for sym = (intern (concat "js2-" name))
5208 do
5209 (puthash sym (symbol-value sym) table))
5210 ;; clean up a few that are "wrong" in Rhino's token codes
5211 (puthash 'js2-DELETE js2-DELPROP table)
5212 table)
5213 "Hashtable mapping token symbols to their bytecodes.")
5214
5215 (defsubst js2-token-code (sym)
5216 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5217 (or (gethash sym js2-token-codes)
5218 (error "Invalid token symbol: %s " sym))) ; signal code bug
5219
5220 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5221 (setq js2-token-end js2-ts-cursor)
5222 (js2-report-error msg nil
5223 (or beg js2-token-beg)
5224 (or len (- js2-token-end js2-token-beg)))
5225 (unless no-throw
5226 (throw 'return js2-ERROR)))
5227
5228 (defsubst js2-get-string-from-buffer ()
5229 "Reverse the char accumulator and return it as a string."
5230 (setq js2-token-end js2-ts-cursor)
5231 (if js2-ts-string-buffer
5232 (apply #'string (nreverse js2-ts-string-buffer))
5233 ""))
5234
5235 ;; TODO: could potentially avoid a lot of consing by allocating a
5236 ;; char buffer the way Rhino does.
5237 (defsubst js2-add-to-string (c)
5238 (push c js2-ts-string-buffer))
5239
5240 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5241 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5242 ;; any other character: when it's not part of the current token, we
5243 ;; unget it, allowing it to be read again by the following call.
5244 (defsubst js2-unget-char ()
5245 (decf js2-ts-cursor))
5246
5247 ;; Rhino distinguishes \r and \n line endings. We don't need to
5248 ;; because we only scan from Emacs buffers, which always use \n.
5249 (defsubst js2-get-char ()
5250 "Read and return the next character from the input buffer.
5251 Increments `js2-ts-lineno' if the return value is a newline char.
5252 Updates `js2-ts-cursor' to the point after the returned char.
5253 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5254 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5255 (let (c)
5256 ;; check for end of buffer
5257 (if (>= js2-ts-cursor (point-max))
5258 (setq js2-ts-hit-eof t
5259 js2-ts-cursor (1+ js2-ts-cursor)
5260 c js2-EOF_CHAR) ; return value
5261 ;; otherwise read next char
5262 (setq c (char-before (incf js2-ts-cursor)))
5263 ;; if we read a newline, update counters
5264 (if (= c ?\n)
5265 (setq js2-ts-line-start js2-ts-cursor
5266 js2-ts-lineno (1+ js2-ts-lineno)))
5267 ;; TODO: skip over format characters
5268 c)))
5269
5270 (defsubst js2-read-unicode-escape ()
5271 "Read a \\uNNNN sequence from the input.
5272 Assumes the ?\ and ?u have already been read.
5273 Returns the unicode character, or nil if it wasn't a valid character.
5274 Doesn't change the values of any scanner variables."
5275 ;; I really wish I knew a better way to do this, but I can't
5276 ;; find the Emacs function that takes a 16-bit int and converts
5277 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5278 ;; Have to first check that it's 4 hex characters or it may stop
5279 ;; the read early.
5280 (ignore-errors
5281 (let ((s (buffer-substring-no-properties js2-ts-cursor
5282 (+ 4 js2-ts-cursor))))
5283 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5284 (read (concat "?\\u" s))))))
5285
5286 (defsubst js2-match-char (test)
5287 "Consume and return next character if it matches TEST, a character.
5288 Returns nil and consumes nothing if TEST is not the next character."
5289 (let ((c (js2-get-char)))
5290 (if (eq c test)
5291 t
5292 (js2-unget-char)
5293 nil)))
5294
5295 (defsubst js2-peek-char ()
5296 (prog1
5297 (js2-get-char)
5298 (js2-unget-char)))
5299
5300 (defsubst js2-java-identifier-start-p (c)
5301 (or
5302 (memq c '(?$ ?_))
5303 (js2-char-uppercase-p c)
5304 (js2-char-lowercase-p c)))
5305
5306 (defsubst js2-java-identifier-part-p (c)
5307 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5308 ;; TODO: make me Unicode-friendly. See comments above.
5309 (or
5310 (memq c '(?$ ?_))
5311 (js2-char-uppercase-p c)
5312 (js2-char-lowercase-p c)
5313 (and (>= c ?0) (<= c ?9))))
5314
5315 (defsubst js2-alpha-p (c)
5316 (cond ((and (<= ?A c) (<= c ?Z)) t)
5317 ((and (<= ?a c) (<= c ?z)) t)
5318 (t nil)))
5319
5320 (defsubst js2-digit-p (c)
5321 (and (<= ?0 c) (<= c ?9)))
5322
5323 (defsubst js2-js-space-p (c)
5324 (if (<= c 127)
5325 (memq c '(#x20 #x9 #xB #xC #xD))
5326 (or
5327 (eq c #xA0)
5328 ;; TODO: change this nil to check for Unicode space character
5329 nil)))
5330
5331 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5332
5333 (defsubst js2-skip-line ()
5334 "Skip to end of line"
5335 (let (c)
5336 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5337 (js2-unget-char)
5338 (setq js2-token-end js2-ts-cursor)))
5339
5340 (defun js2-init-scanner (&optional buf line)
5341 "Create token stream for BUF starting on LINE.
5342 BUF defaults to current-buffer and line defaults to 1.
5343
5344 A buffer can only have one scanner active at a time, which yields
5345 dramatically simpler code than using a defstruct. If you need to
5346 have simultaneous scanners in a buffer, copy the regions to scan
5347 into temp buffers."
5348 (save-excursion
5349 (when buf
5350 (set-buffer buf))
5351 (setq js2-ts-dirty-line nil
5352 js2-ts-regexp-flags nil
5353 js2-ts-string ""
5354 js2-ts-number nil
5355 js2-ts-hit-eof nil
5356 js2-ts-line-start 0
5357 js2-ts-lineno (or line 1)
5358 js2-ts-line-end-char -1
5359 js2-ts-cursor (point-min)
5360 js2-ts-is-xml-attribute nil
5361 js2-ts-xml-is-tag-content nil
5362 js2-ts-xml-open-tags-count 0
5363 js2-ts-string-buffer nil)))
5364
5365 ;; This function uses the cached op, string and number fields in
5366 ;; TokenStream; if getToken has been called since the passed token
5367 ;; was scanned, the op or string printed may be incorrect.
5368 (defun js2-token-to-string (token)
5369 ;; Not sure where this function is used in Rhino. Not tested.
5370 (if (not js2-debug-print-trees)
5371 ""
5372 (let ((name (js2-token-name token)))
5373 (cond
5374 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5375 (concat name " `" js2-ts-string "'"))
5376 ((eq token js2-NUMBER)
5377 (format "NUMBER %g" js2-ts-number))
5378 (t
5379 name)))))
5380
5381 (defconst js2-keywords
5382 '(break
5383 case catch const continue
5384 debugger default delete do
5385 else enum
5386 false finally for function
5387 if in instanceof import
5388 let
5389 new null
5390 return
5391 switch
5392 this throw true try typeof
5393 var void
5394 while with
5395 yield))
5396
5397 ;; Token names aren't exactly the same as the keywords, unfortunately.
5398 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5399 (defconst js2-kwd-tokens
5400 (let ((table (make-vector js2-num-tokens nil))
5401 (tokens
5402 (list js2-BREAK
5403 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5404 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5405 js2-ELSE
5406 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5407 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5408 js2-LET
5409 js2-NEW js2-NULL
5410 js2-RETURN
5411 js2-SWITCH
5412 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5413 js2-VAR
5414 js2-WHILE js2-WITH
5415 js2-YIELD)))
5416 (dolist (i tokens)
5417 (aset table i 'font-lock-keyword-face))
5418 (aset table js2-STRING 'font-lock-string-face)
5419 (aset table js2-REGEXP 'font-lock-string-face)
5420 (aset table js2-COMMENT 'font-lock-comment-face)
5421 (aset table js2-THIS 'font-lock-builtin-face)
5422 (aset table js2-VOID 'font-lock-constant-face)
5423 (aset table js2-NULL 'font-lock-constant-face)
5424 (aset table js2-TRUE 'font-lock-constant-face)
5425 (aset table js2-FALSE 'font-lock-constant-face)
5426 table)
5427 "Vector whose values are non-nil for tokens that are keywords.
5428 The values are default faces to use for highlighting the keywords.")
5429
5430 (defconst js2-reserved-words
5431 '(abstract
5432 boolean byte
5433 char class
5434 double
5435 enum export extends
5436 final float
5437 goto
5438 implements import int interface
5439 long
5440 native
5441 package private protected public
5442 short static super synchronized
5443 throws transient
5444 volatile))
5445
5446 (defconst js2-keyword-names
5447 (let ((table (make-hash-table :test 'equal)))
5448 (loop for k in js2-keywords
5449 do (puthash
5450 (symbol-name k) ; instanceof
5451 (intern (concat "js2-"
5452 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5453 table))
5454 table)
5455 "JavaScript keywords by name, mapped to their symbols.")
5456
5457 (defconst js2-reserved-word-names
5458 (let ((table (make-hash-table :test 'equal)))
5459 (loop for k in js2-reserved-words
5460 do
5461 (puthash (symbol-name k) 'js2-RESERVED table))
5462 table)
5463 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5464
5465 (defsubst js2-collect-string (buf)
5466 "Convert BUF, a list of chars, to a string.
5467 Reverses BUF before converting."
5468 (cond
5469 ((stringp buf)
5470 buf)
5471 ((null buf) ; for emacs21 compat
5472 "")
5473 (t
5474 (if buf
5475 (apply #'string (nreverse buf))
5476 ""))))
5477
5478 (defun js2-string-to-keyword (s)
5479 "Return token for S, a string, if S is a keyword or reserved word.
5480 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5481 (or (gethash s js2-keyword-names)
5482 (gethash s js2-reserved-word-names)))
5483
5484 (defsubst js2-ts-set-char-token-bounds ()
5485 "Used when next token is one character."
5486 (setq js2-token-beg (1- js2-ts-cursor)
5487 js2-token-end js2-ts-cursor))
5488
5489 (defsubst js2-ts-return (token)
5490 "Return an N-character TOKEN from `js2-get-token'.
5491 Updates `js2-token-end' accordingly."
5492 (setq js2-token-end js2-ts-cursor)
5493 (throw 'return token))
5494
5495 (defsubst js2-x-digit-to-int (c accumulator)
5496 "Build up a hex number.
5497 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5498 corresponding number. Otherwise return -1."
5499 (catch 'return
5500 (catch 'check
5501 ;; Use 0..9 < A..Z < a..z
5502 (cond
5503 ((<= c ?9)
5504 (decf c ?0)
5505 (if (<= 0 c)
5506 (throw 'check nil)))
5507 ((<= c ?F)
5508 (when (<= ?A c)
5509 (decf c (- ?A 10))
5510 (throw 'check nil)))
5511 ((<= c ?f)
5512 (when (<= ?a c)
5513 (decf c (- ?a 10))
5514 (throw 'check nil))))
5515 (throw 'return -1))
5516 (logior c (lsh accumulator 4))))
5517
5518 (defun js2-get-token ()
5519 "Return next JavaScript token, an int such as js2-RETURN."
5520 (let (c
5521 c1
5522 identifier-start
5523 is-unicode-escape-start
5524 contains-escape
5525 escape-val
5526 escape-start
5527 str
5528 result
5529 base
5530 is-integer
5531 quote-char
5532 val
5533 look-for-slash
5534 continue)
5535 (catch 'return
5536 (while t
5537 ;; Eat whitespace, possibly sensitive to newlines.
5538 (setq continue t)
5539 (while continue
5540 (setq c (js2-get-char))
5541 (cond
5542 ((eq c js2-EOF_CHAR)
5543 (js2-ts-set-char-token-bounds)
5544 (throw 'return js2-EOF))
5545 ((eq c ?\n)
5546 (js2-ts-set-char-token-bounds)
5547 (setq js2-ts-dirty-line nil)
5548 (throw 'return js2-EOL))
5549 ((not (js2-js-space-p c))
5550 (if (/= c ?-) ; in case end of HTML comment
5551 (setq js2-ts-dirty-line t))
5552 (setq continue nil))))
5553 ;; Assume the token will be 1 char - fixed up below.
5554 (js2-ts-set-char-token-bounds)
5555 (when (eq c ?@)
5556 (throw 'return js2-XMLATTR))
5557 ;; identifier/keyword/instanceof?
5558 ;; watch out for starting with a <backslash>
5559 (cond
5560 ((eq c ?\\)
5561 (setq c (js2-get-char))
5562 (if (eq c ?u)
5563 (setq identifier-start t
5564 is-unicode-escape-start t
5565 js2-ts-string-buffer nil)
5566 (setq identifier-start nil)
5567 (js2-unget-char)
5568 (setq c ?\\)))
5569 (t
5570 (when (setq identifier-start (js2-java-identifier-start-p c))
5571 (setq js2-ts-string-buffer nil)
5572 (js2-add-to-string c))))
5573 (when identifier-start
5574 (setq contains-escape is-unicode-escape-start)
5575 (catch 'break
5576 (while t
5577 (if is-unicode-escape-start
5578 ;; strictly speaking we should probably push-back
5579 ;; all the bad characters if the <backslash>uXXXX
5580 ;; sequence is malformed. But since there isn't a
5581 ;; correct context(is there?) for a bad Unicode
5582 ;; escape sequence in an identifier, we can report
5583 ;; an error here.
5584 (progn
5585 (setq escape-val 0)
5586 (dotimes (i 4)
5587 (setq c (js2-get-char)
5588 escape-val (js2-x-digit-to-int c escape-val))
5589 ;; Next check takes care of c < 0 and bad escape
5590 (if (minusp escape-val)
5591 (throw 'break nil)))
5592 (if (minusp escape-val)
5593 (js2-report-scan-error "msg.invalid.escape" t))
5594 (js2-add-to-string escape-val)
5595 (setq is-unicode-escape-start nil))
5596 (setq c (js2-get-char))
5597 (cond
5598 ((eq c ?\\)
5599 (setq c (js2-get-char))
5600 (if (eq c ?u)
5601 (setq is-unicode-escape-start t
5602 contains-escape t)
5603 (js2-report-scan-error "msg.illegal.character" t)))
5604 (t
5605 (if (or (eq c js2-EOF_CHAR)
5606 (not (js2-java-identifier-part-p c)))
5607 (throw 'break nil))
5608 (js2-add-to-string c))))))
5609 (js2-unget-char)
5610 (setq str (js2-get-string-from-buffer))
5611 (unless contains-escape
5612 ;; OPT we shouldn't have to make a string (object!) to
5613 ;; check if it's a keyword.
5614 ;; Return the corresponding token if it's a keyword
5615 (when (setq result (js2-string-to-keyword str))
5616 (if (and (< js2-language-version 170)
5617 (memq result '(js2-LET js2-YIELD)))
5618 ;; LET and YIELD are tokens only in 1.7 and later
5619 (setq result 'js2-NAME))
5620 (if (not (eq result 'js2-RESERVED))
5621 (throw 'return (js2-token-code result)))
5622 (js2-report-warning "msg.reserved.keyword" str)))
5623 ;; If we want to intern these as Rhino does, just use (intern str)
5624 (setq js2-ts-string str)
5625 (throw 'return js2-NAME)) ; end identifier/kwd check
5626 ;; is it a number?
5627 (when (or (js2-digit-p c)
5628 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5629 (setq js2-ts-string-buffer nil
5630 base 10)
5631 (when (eq c ?0)
5632 (setq c (js2-get-char))
5633 (cond
5634 ((or (eq c ?x) (eq c ?X))
5635 (setq base 16)
5636 (setq c (js2-get-char)))
5637 ((js2-digit-p c)
5638 (setq base 8))
5639 (t
5640 (js2-add-to-string ?0))))
5641 (if (eq base 16)
5642 (while (<= 0 (js2-x-digit-to-int c 0))
5643 (js2-add-to-string c)
5644 (setq c (js2-get-char)))
5645 (while (and (<= ?0 c) (<= c ?9))
5646 ;; We permit 08 and 09 as decimal numbers, which
5647 ;; makes our behavior a superset of the ECMA
5648 ;; numeric grammar. We might not always be so
5649 ;; permissive, so we warn about it.
5650 (when (and (eq base 8) (>= c ?8))
5651 (js2-report-warning "msg.bad.octal.literal"
5652 (if (eq c ?8) "8" "9"))
5653 (setq base 10))
5654 (js2-add-to-string c)
5655 (setq c (js2-get-char))))
5656 (setq is-integer t)
5657 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5658 (setq is-integer nil)
5659 (when (eq c ?.)
5660 (loop do
5661 (js2-add-to-string c)
5662 (setq c (js2-get-char))
5663 while (js2-digit-p c)))
5664 (when (memq c '(?e ?E))
5665 (js2-add-to-string c)
5666 (setq c (js2-get-char))
5667 (when (memq c '(?+ ?-))
5668 (js2-add-to-string c)
5669 (setq c (js2-get-char)))
5670 (unless (js2-digit-p c)
5671 (js2-report-scan-error "msg.missing.exponent" t))
5672 (loop do
5673 (js2-add-to-string c)
5674 (setq c (js2-get-char))
5675 while (js2-digit-p c))))
5676 (js2-unget-char)
5677 (setq js2-ts-string (js2-get-string-from-buffer)
5678 js2-ts-number
5679 (if (and (eq base 10) (not is-integer))
5680 (string-to-number js2-ts-string)
5681 ;; TODO: call runtime number-parser. Some of it is in
5682 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5683 (string-to-number js2-ts-string)))
5684 (throw 'return js2-NUMBER))
5685 ;; is it a string?
5686 (when (memq c '(?\" ?\'))
5687 ;; We attempt to accumulate a string the fast way, by
5688 ;; building it directly out of the reader. But if there
5689 ;; are any escaped characters in the string, we revert to
5690 ;; building it out of a string buffer.
5691 (setq quote-char c
5692 js2-ts-string-buffer nil
5693 c (js2-get-char))
5694 (catch 'break
5695 (while (/= c quote-char)
5696 (catch 'continue
5697 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5698 (js2-unget-char)
5699 (setq js2-token-end js2-ts-cursor)
5700 (js2-report-error "msg.unterminated.string.lit")
5701 (throw 'return js2-STRING))
5702 (when (eq c ?\\)
5703 ;; We've hit an escaped character
5704 (setq c (js2-get-char))
5705 (case c
5706 (?b (setq c ?\b))
5707 (?f (setq c ?\f))
5708 (?n (setq c ?\n))
5709 (?r (setq c ?\r))
5710 (?t (setq c ?\t))
5711 (?v (setq c ?\v))
5712 (?u
5713 (setq c1 (js2-read-unicode-escape))
5714 (if js2-parse-ide-mode
5715 (if c1
5716 (progn
5717 ;; just copy the string in IDE-mode
5718 (js2-add-to-string ?\\)
5719 (js2-add-to-string ?u)
5720 (dotimes (i 3)
5721 (js2-add-to-string (js2-get-char)))
5722 (setq c (js2-get-char))) ; added at end of loop
5723 ;; flag it as an invalid escape
5724 (js2-report-warning "msg.invalid.escape"
5725 nil (- js2-ts-cursor 2) 6))
5726 ;; Get 4 hex digits; if the u escape is not
5727 ;; followed by 4 hex digits, use 'u' + the
5728 ;; literal character sequence that follows.
5729 (js2-add-to-string ?u)
5730 (setq escape-val 0)
5731 (dotimes (i 4)
5732 (setq c (js2-get-char)
5733 escape-val (js2-x-digit-to-int c escape-val))
5734 (if (minusp escape-val)
5735 (throw 'continue nil))
5736 (js2-add-to-string c))
5737 ;; prepare for replace of stored 'u' sequence by escape value
5738 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5739 c escape-val)))
5740 (?x
5741 ;; Get 2 hex digits, defaulting to 'x'+literal
5742 ;; sequence, as above.
5743 (setq c (js2-get-char)
5744 escape-val (js2-x-digit-to-int c 0))
5745 (if (minusp escape-val)
5746 (progn
5747 (js2-add-to-string ?x)
5748 (throw 'continue nil))
5749 (setq c1 c
5750 c (js2-get-char)
5751 escape-val (js2-x-digit-to-int c escape-val))
5752 (if (minusp escape-val)
5753 (progn
5754 (js2-add-to-string ?x)
5755 (js2-add-to-string c1)
5756 (throw 'continue nil))
5757 ;; got 2 hex digits
5758 (setq c escape-val))))
5759 (?\n
5760 ;; Remove line terminator after escape to follow
5761 ;; SpiderMonkey and C/C++
5762 (setq c (js2-get-char))
5763 (throw 'continue nil))
5764 (t
5765 (when (and (<= ?0 c) (< c ?8))
5766 (setq val (- c ?0)
5767 c (js2-get-char))
5768 (when (and (<= ?0 c) (< c ?8))
5769 (setq val (- (+ (* 8 val) c) ?0)
5770 c (js2-get-char))
5771 (when (and (<= ?0 c)
5772 (< c ?8)
5773 (< val #o37))
5774 ;; c is 3rd char of octal sequence only
5775 ;; if the resulting val <= 0377
5776 (setq val (- (+ (* 8 val) c) ?0)
5777 c (js2-get-char))))
5778 (js2-unget-char)
5779 (setq c val)))))
5780 (js2-add-to-string c)
5781 (setq c (js2-get-char)))))
5782 (setq js2-ts-string (js2-get-string-from-buffer))
5783 (throw 'return js2-STRING))
5784 (case c
5785 (?\;
5786 (throw 'return js2-SEMI))
5787 (?\[
5788 (throw 'return js2-LB))
5789 (?\]
5790 (throw 'return js2-RB))
5791 (?{
5792 (throw 'return js2-LC))
5793 (?}
5794 (throw 'return js2-RC))
5795 (?\(
5796 (throw 'return js2-LP))
5797 (?\)
5798 (throw 'return js2-RP))
5799 (?,
5800 (throw 'return js2-COMMA))
5801 (??
5802 (throw 'return js2-HOOK))
5803 (?:
5804 (if (js2-match-char ?:)
5805 (js2-ts-return js2-COLONCOLON)
5806 (throw 'return js2-COLON)))
5807 (?.
5808 (if (js2-match-char ?.)
5809 (js2-ts-return js2-DOTDOT)
5810 (if (js2-match-char ?\()
5811 (js2-ts-return js2-DOTQUERY)
5812 (throw 'return js2-DOT))))
5813 (?|
5814 (if (js2-match-char ?|)
5815 (throw 'return js2-OR)
5816 (if (js2-match-char ?=)
5817 (js2-ts-return js2-ASSIGN_BITOR)
5818 (throw 'return js2-BITOR))))
5819 (?^
5820 (if (js2-match-char ?=)
5821 (js2-ts-return js2-ASSIGN_BITOR)
5822 (throw 'return js2-BITXOR)))
5823 (?&
5824 (if (js2-match-char ?&)
5825 (throw 'return js2-AND)
5826 (if (js2-match-char ?=)
5827 (js2-ts-return js2-ASSIGN_BITAND)
5828 (throw 'return js2-BITAND))))
5829 (?=
5830 (if (js2-match-char ?=)
5831 (if (js2-match-char ?=)
5832 (js2-ts-return js2-SHEQ)
5833 (throw 'return js2-EQ))
5834 (throw 'return js2-ASSIGN)))
5835 (?!
5836 (if (js2-match-char ?=)
5837 (if (js2-match-char ?=)
5838 (js2-ts-return js2-SHNE)
5839 (js2-ts-return js2-NE))
5840 (throw 'return js2-NOT)))
5841 (?<
5842 ;; NB:treat HTML begin-comment as comment-till-eol
5843 (when (js2-match-char ?!)
5844 (when (js2-match-char ?-)
5845 (when (js2-match-char ?-)
5846 (js2-skip-line)
5847 (setq js2-ts-comment-type 'html)
5848 (throw 'return js2-COMMENT)))
5849 (js2-unget-char))
5850 (if (js2-match-char ?<)
5851 (if (js2-match-char ?=)
5852 (js2-ts-return js2-ASSIGN_LSH)
5853 (js2-ts-return js2-LSH))
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-LE)
5856 (throw 'return js2-LT))))
5857 (?>
5858 (if (js2-match-char ?>)
5859 (if (js2-match-char ?>)
5860 (if (js2-match-char ?=)
5861 (js2-ts-return js2-ASSIGN_URSH)
5862 (js2-ts-return js2-URSH))
5863 (if (js2-match-char ?=)
5864 (js2-ts-return js2-ASSIGN_RSH)
5865 (js2-ts-return js2-RSH)))
5866 (if (js2-match-char ?=)
5867 (js2-ts-return js2-GE)
5868 (throw 'return js2-GT))))
5869 (?*
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-ASSIGN_MUL)
5872 (throw 'return js2-MUL)))
5873 (?/
5874 ;; is it a // comment?
5875 (when (js2-match-char ?/)
5876 (setq js2-token-beg (- js2-ts-cursor 2))
5877 (js2-skip-line)
5878 (setq js2-ts-comment-type 'line)
5879 ;; include newline so highlighting goes to end of window
5880 (incf js2-token-end)
5881 (throw 'return js2-COMMENT))
5882 ;; is it a /* comment?
5883 (when (js2-match-char ?*)
5884 (setq look-for-slash nil
5885 js2-token-beg (- js2-ts-cursor 2)
5886 js2-ts-comment-type
5887 (if (js2-match-char ?*)
5888 (progn
5889 (setq look-for-slash t)
5890 'jsdoc)
5891 'block))
5892 (while t
5893 (setq c (js2-get-char))
5894 (cond
5895 ((eq c js2-EOF_CHAR)
5896 (setq js2-token-end (1- js2-ts-cursor))
5897 (js2-report-error "msg.unterminated.comment")
5898 (throw 'return js2-COMMENT))
5899 ((eq c ?*)
5900 (setq look-for-slash t))
5901 ((eq c ?/)
5902 (if look-for-slash
5903 (js2-ts-return js2-COMMENT)))
5904 (t
5905 (setq look-for-slash nil
5906 js2-token-end js2-ts-cursor)))))
5907 (if (js2-match-char ?=)
5908 (js2-ts-return js2-ASSIGN_DIV)
5909 (throw 'return js2-DIV)))
5910 (?#
5911 (when js2-skip-preprocessor-directives
5912 (js2-skip-line)
5913 (setq js2-ts-comment-type 'preprocessor
5914 js2-token-end js2-ts-cursor)
5915 (throw 'return js2-COMMENT))
5916 (throw 'return js2-ERROR))
5917 (?%
5918 (if (js2-match-char ?=)
5919 (js2-ts-return js2-ASSIGN_MOD)
5920 (throw 'return js2-MOD)))
5921 (?~
5922 (throw 'return js2-BITNOT))
5923 (?+
5924 (if (js2-match-char ?=)
5925 (js2-ts-return js2-ASSIGN_ADD)
5926 (if (js2-match-char ?+)
5927 (js2-ts-return js2-INC)
5928 (throw 'return js2-ADD))))
5929 (?-
5930 (cond
5931 ((js2-match-char ?=)
5932 (setq c js2-ASSIGN_SUB))
5933 ((js2-match-char ?-)
5934 (unless js2-ts-dirty-line
5935 ;; treat HTML end-comment after possible whitespace
5936 ;; after line start as comment-until-eol
5937 (when (js2-match-char ?>)
5938 (js2-skip-line)
5939 (setq js2-ts-comment-type 'html)
5940 (throw 'return js2-COMMENT)))
5941 (setq c js2-DEC))
5942 (t
5943 (setq c js2-SUB)))
5944 (setq js2-ts-dirty-line t)
5945 (js2-ts-return c))
5946 (otherwise
5947 (js2-report-scan-error "msg.illegal.character")))))))
5948
5949 (defun js2-read-regexp (start-token)
5950 "Called by parser when it gets / or /= in literal context."
5951 (let (c
5952 err
5953 in-class ; inside a '[' .. ']' character-class
5954 flags
5955 (continue t))
5956 (setq js2-token-beg js2-ts-cursor
5957 js2-ts-string-buffer nil
5958 js2-ts-regexp-flags nil)
5959 (if (eq start-token js2-ASSIGN_DIV)
5960 ;; mis-scanned /=
5961 (js2-add-to-string ?=)
5962 (if (not (eq start-token js2-DIV))
5963 (error "failed assertion")))
5964 (while (and (not err)
5965 (or (/= (setq c (js2-get-char)) ?/)
5966 in-class))
5967 (cond
5968 ((or (= c ?\n)
5969 (= c js2-EOF_CHAR))
5970 (setq js2-token-end (1- js2-ts-cursor)
5971 err t
5972 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5973 (js2-report-error "msg.unterminated.re.lit"))
5974 (t (cond
5975 ((= c ?\\)
5976 (js2-add-to-string c)
5977 (setq c (js2-get-char)))
5978 ((= c ?\[)
5979 (setq in-class t))
5980 ((= c ?\])
5981 (setq in-class nil)))
5982 (js2-add-to-string c))))
5983 (unless err
5984 (while continue
5985 (cond
5986 ((js2-match-char ?g)
5987 (push ?g flags))
5988 ((js2-match-char ?i)
5989 (push ?i flags))
5990 ((js2-match-char ?m)
5991 (push ?m flags))
5992 (t
5993 (setq continue nil))))
5994 (if (js2-alpha-p (js2-peek-char))
5995 (js2-report-scan-error "msg.invalid.re.flag" t
5996 js2-ts-cursor 1))
5997 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5998 js2-ts-regexp-flags (js2-collect-string flags)
5999 js2-token-end js2-ts-cursor)
6000 ;; tell `parse-partial-sexp' to ignore this range of chars
6001 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6002
6003 (defun js2-get-first-xml-token ()
6004 (setq js2-ts-xml-open-tags-count 0
6005 js2-ts-is-xml-attribute nil
6006 js2-ts-xml-is-tag-content nil)
6007 (js2-unget-char)
6008 (js2-get-next-xml-token))
6009
6010 (defsubst js2-xml-discard-string ()
6011 "Throw away the string in progress and flag an XML parse error."
6012 (setq js2-ts-string-buffer nil
6013 js2-ts-string nil)
6014 (js2-report-scan-error "msg.XML.bad.form" t))
6015
6016 (defun js2-get-next-xml-token ()
6017 (setq js2-ts-string-buffer nil ; for recording the XML
6018 js2-token-beg js2-ts-cursor)
6019 (let (c result)
6020 (setq result
6021 (catch 'return
6022 (while t
6023 (setq c (js2-get-char))
6024 (cond
6025 ((= c js2-EOF_CHAR)
6026 (throw 'return js2-ERROR))
6027 (js2-ts-xml-is-tag-content
6028 (case c
6029 (?>
6030 (js2-add-to-string c)
6031 (setq js2-ts-xml-is-tag-content nil
6032 js2-ts-is-xml-attribute nil))
6033 (?/
6034 (js2-add-to-string c)
6035 (when (eq ?> (js2-peek-char))
6036 (setq c (js2-get-char))
6037 (js2-add-to-string c)
6038 (setq js2-ts-xml-is-tag-content nil)
6039 (decf js2-ts-xml-open-tags-count)))
6040 (?{
6041 (js2-unget-char)
6042 (setq js2-ts-string (js2-get-string-from-buffer))
6043 (throw 'return js2-XML))
6044 ((?\' ?\")
6045 (js2-add-to-string c)
6046 (unless (js2-read-quoted-string c)
6047 (throw 'return js2-ERROR)))
6048 (?=
6049 (js2-add-to-string c)
6050 (setq js2-ts-is-xml-attribute t))
6051 ((? ?\t ?\r ?\n)
6052 (js2-add-to-string c))
6053 (t
6054 (js2-add-to-string c)
6055 (setq js2-ts-is-xml-attribute nil)))
6056 (when (and (not js2-ts-xml-is-tag-content)
6057 (zerop js2-ts-xml-open-tags-count))
6058 (setq js2-ts-string (js2-get-string-from-buffer))
6059 (throw 'return js2-XMLEND)))
6060 (t
6061 ;; else not tag content
6062 (case c
6063 (?<
6064 (js2-add-to-string c)
6065 (setq c (js2-peek-char))
6066 (case c
6067 (?!
6068 (setq c (js2-get-char)) ;; skip !
6069 (js2-add-to-string c)
6070 (setq c (js2-peek-char))
6071 (case c
6072 (?-
6073 (setq c (js2-get-char)) ;; skip -
6074 (js2-add-to-string c)
6075 (if (eq c ?-)
6076 (progn
6077 (js2-add-to-string c)
6078 (unless (js2-read-xml-comment)
6079 (throw 'return js2-ERROR)))
6080 (js2-xml-discard-string)
6081 (throw 'return js2-ERROR)))
6082 (?\[
6083 (setq c (js2-get-char)) ;; skip [
6084 (js2-add-to-string c)
6085 (if (and (= (js2-get-char) ?C)
6086 (= (js2-get-char) ?D)
6087 (= (js2-get-char) ?A)
6088 (= (js2-get-char) ?T)
6089 (= (js2-get-char) ?A)
6090 (= (js2-get-char) ?\[))
6091 (progn
6092 (js2-add-to-string ?C)
6093 (js2-add-to-string ?D)
6094 (js2-add-to-string ?A)
6095 (js2-add-to-string ?T)
6096 (js2-add-to-string ?A)
6097 (js2-add-to-string ?\[)
6098 (unless (js2-read-cdata)
6099 (throw 'return js2-ERROR)))
6100 (js2-xml-discard-string)
6101 (throw 'return js2-ERROR)))
6102 (t
6103 (unless (js2-read-entity)
6104 (throw 'return js2-ERROR)))))
6105 (??
6106 (setq c (js2-get-char)) ;; skip ?
6107 (js2-add-to-string c)
6108 (unless (js2-read-PI)
6109 (throw 'return js2-ERROR)))
6110 (?/
6111 ;; end tag
6112 (setq c (js2-get-char)) ;; skip /
6113 (js2-add-to-string c)
6114 (when (zerop js2-ts-xml-open-tags-count)
6115 (js2-xml-discard-string)
6116 (throw 'return js2-ERROR))
6117 (setq js2-ts-xml-is-tag-content t)
6118 (decf js2-ts-xml-open-tags-count))
6119 (t
6120 ;; start tag
6121 (setq js2-ts-xml-is-tag-content t)
6122 (incf js2-ts-xml-open-tags-count))))
6123 (?{
6124 (js2-unget-char)
6125 (setq js2-ts-string (js2-get-string-from-buffer))
6126 (throw 'return js2-XML))
6127 (t
6128 (js2-add-to-string c))))))))
6129 (setq js2-token-end js2-ts-cursor)
6130 result))
6131
6132 (defun js2-read-quoted-string (quote)
6133 (let (c)
6134 (catch 'return
6135 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6136 (js2-add-to-string c)
6137 (if (eq c quote)
6138 (throw 'return t)))
6139 (js2-xml-discard-string) ;; throw away string in progress
6140 nil)))
6141
6142 (defun js2-read-xml-comment ()
6143 (let ((c (js2-get-char)))
6144 (catch 'return
6145 (while (/= c js2-EOF_CHAR)
6146 (catch 'continue
6147 (js2-add-to-string c)
6148 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6149 (setq c (js2-get-char))
6150 (js2-add-to-string c)
6151 (if (eq (js2-peek-char) ?>)
6152 (progn
6153 (setq c (js2-get-char)) ;; skip >
6154 (js2-add-to-string c)
6155 (throw 'return t))
6156 (throw 'continue nil)))
6157 (setq c (js2-get-char))))
6158 (js2-xml-discard-string)
6159 nil)))
6160
6161 (defun js2-read-cdata ()
6162 (let ((c (js2-get-char)))
6163 (catch 'return
6164 (while (/= c js2-EOF_CHAR)
6165 (catch 'continue
6166 (js2-add-to-string c)
6167 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6168 (setq c (js2-get-char))
6169 (js2-add-to-string c)
6170 (if (eq (js2-peek-char) ?>)
6171 (progn
6172 (setq c (js2-get-char)) ;; Skip >
6173 (js2-add-to-string c)
6174 (throw 'return t))
6175 (throw 'continue nil)))
6176 (setq c (js2-get-char))))
6177 (js2-xml-discard-string)
6178 nil)))
6179
6180 (defun js2-read-entity ()
6181 (let ((decl-tags 1)
6182 c)
6183 (catch 'return
6184 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6185 (js2-add-to-string c)
6186 (case c
6187 (?<
6188 (incf decl-tags))
6189 (?>
6190 (decf decl-tags)
6191 (if (zerop decl-tags)
6192 (throw 'return t)))))
6193 (js2-xml-discard-string)
6194 nil)))
6195
6196 (defun js2-read-PI ()
6197 "Scan an XML processing instruction."
6198 (let (c)
6199 (catch 'return
6200 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6201 (js2-add-to-string c)
6202 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6203 (setq c (js2-get-char)) ;; Skip >
6204 (js2-add-to-string c)
6205 (throw 'return t)))
6206 (js2-xml-discard-string)
6207 nil)))
6208
6209 (defun js2-scanner-get-line ()
6210 "Return the text of the current scan line."
6211 (buffer-substring (point-at-bol) (point-at-eol)))
6212
6213 ;;; Highlighting
6214
6215 (defsubst js2-set-face (beg end face &optional record)
6216 "Fontify a region. If RECORD is non-nil, record for later."
6217 (when (plusp js2-highlight-level)
6218 (setq beg (min (point-max) beg)
6219 beg (max (point-min) beg)
6220 end (min (point-max) end)
6221 end (max (point-min) end))
6222 (if record
6223 (push (list beg end face) js2-mode-fontifications)
6224 (put-text-property beg end 'face face))))
6225
6226 (defsubst js2-set-kid-face (pos kid len face)
6227 "Set-face on a child node.
6228 POS is absolute buffer position of parent.
6229 KID is the child node.
6230 LEN is the length to fontify.
6231 FACE is the face to fontify with."
6232 (js2-set-face (+ pos (js2-node-pos kid))
6233 (+ pos (js2-node-pos kid) (js2-node-len kid))
6234 face))
6235
6236 (defsubst js2-fontify-kwd (start length)
6237 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6238
6239 (defsubst js2-clear-face (beg end)
6240 (remove-text-properties beg end '(face nil
6241 help-echo nil
6242 point-entered nil
6243 c-in-sws nil)))
6244
6245 (defconst js2-ecma-global-props
6246 (concat "^"
6247 (regexp-opt
6248 '("Infinity" "NaN" "undefined" "arguments") t)
6249 "$")
6250 "Value properties of the Ecma-262 Global Object.
6251 Shown at or above `js2-highlight-level' 2.")
6252
6253 ;; might want to add the name "arguments" to this list?
6254 (defconst js2-ecma-object-props
6255 (concat "^"
6256 (regexp-opt
6257 '("prototype" "__proto__" "__parent__") t)
6258 "$")
6259 "Value properties of the Ecma-262 Object constructor.
6260 Shown at or above `js2-highlight-level' 2.")
6261
6262 (defconst js2-ecma-global-funcs
6263 (concat
6264 "^"
6265 (regexp-opt
6266 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6267 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6268 "$")
6269 "Function properties of the Ecma-262 Global object.
6270 Shown at or above `js2-highlight-level' 2.")
6271
6272 (defconst js2-ecma-number-props
6273 (concat "^"
6274 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6275 "NEGATIVE_INFINITY"
6276 "POSITIVE_INFINITY") t)
6277 "$")
6278 "Properties of the Ecma-262 Number constructor.
6279 Shown at or above `js2-highlight-level' 2.")
6280
6281 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6282 "Properties of the Ecma-262 Date constructor.
6283 Shown at or above `js2-highlight-level' 2.")
6284
6285 (defconst js2-ecma-math-props
6286 (concat "^"
6287 (regexp-opt
6288 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6289 t)
6290 "$")
6291 "Properties of the Ecma-262 Math object.
6292 Shown at or above `js2-highlight-level' 2.")
6293
6294 (defconst js2-ecma-math-funcs
6295 (concat "^"
6296 (regexp-opt
6297 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6298 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6299 "$")
6300 "Function properties of the Ecma-262 Math object.
6301 Shown at or above `js2-highlight-level' 2.")
6302
6303 (defconst js2-ecma-function-props
6304 (concat
6305 "^"
6306 (regexp-opt
6307 '(;; properties of the Object prototype object
6308 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6309 "toLocaleString" "toString" "valueOf"
6310 ;; properties of the Function prototype object
6311 "apply" "call"
6312 ;; properties of the Array prototype object
6313 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6314 "splice" "unshift"
6315 ;; properties of the String prototype object
6316 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6317 "localeCompare" "match" "replace" "search" "split" "substring"
6318 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6319 "toUpperCase"
6320 ;; properties of the Number prototype object
6321 "toExponential" "toFixed" "toPrecision"
6322 ;; properties of the Date prototype object
6323 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6324 "getMinutes" "getMonth" "getSeconds" "getTime"
6325 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6326 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6327 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6328 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6329 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6330 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6331 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6332 "toTimeString" "toUTCString"
6333 ;; properties of the RegExp prototype object
6334 "exec" "test"
6335 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6336 "toSource" "__defineGetter__" "__defineSetter__"
6337 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6338 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6339 t)
6340 "$")
6341 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6342 Shown at or above `js2-highlight-level' 3.")
6343
6344 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6345 (let ((target-name (and target
6346 (js2-name-node-p target)
6347 (js2-name-node-name target)))
6348 (prop-name (if prop (js2-name-node-name prop)))
6349 (level1 (>= js2-highlight-level 1))
6350 (level2 (>= js2-highlight-level 2))
6351 (level3 (>= js2-highlight-level 3))
6352 pos
6353 face)
6354 (when level2
6355 (if call-p
6356 (cond
6357 ((and target prop)
6358 (cond
6359 ((and level3 (string-match js2-ecma-function-props prop-name))
6360 (setq face 'font-lock-builtin-face))
6361 ((and target-name prop)
6362 (cond
6363 ((string= target-name "Date")
6364 (if (string-match js2-ecma-date-props prop-name)
6365 (setq face 'font-lock-builtin-face)))
6366 ((string= target-name "Math")
6367 (if (string-match js2-ecma-math-funcs prop-name)
6368 (setq face 'font-lock-builtin-face)))))))
6369 (prop
6370 (if (string-match js2-ecma-global-funcs prop-name)
6371 (setq face 'font-lock-builtin-face))))
6372 (cond
6373 ((and target prop)
6374 (cond
6375 ((string= target-name "Number")
6376 (if (string-match js2-ecma-number-props prop-name)
6377 (setq face 'font-lock-constant-face)))
6378 ((string= target-name "Math")
6379 (if (string-match js2-ecma-math-props prop-name)
6380 (setq face 'font-lock-constant-face)))))
6381 (prop
6382 (if (string-match js2-ecma-object-props prop-name)
6383 (setq face 'font-lock-constant-face)))))
6384 (when face
6385 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6386 (js2-node-pos prop))) ; relative
6387 (+ pos (js2-node-len prop))
6388 face)))))
6389
6390 (defun js2-parse-highlight-member-expr-node (node)
6391 "Perform syntax highlighting of EcmaScript built-in properties.
6392 The variable `js2-highlight-level' governs this highighting."
6393 (let (face target prop name pos end parent call-p callee)
6394 (cond
6395 ;; case 1: simple name, e.g. foo
6396 ((js2-name-node-p node)
6397 (setq name (js2-name-node-name node))
6398 ;; possible for name to be nil in rare cases - saw it when
6399 ;; running js2-mode on an elisp buffer. Might as well try to
6400 ;; make it so js2-mode never barfs.
6401 (when name
6402 (setq face (if (string-match js2-ecma-global-props name)
6403 'font-lock-constant-face))
6404 (when face
6405 (setq pos (js2-node-pos node)
6406 end (+ pos (js2-node-len node)))
6407 (js2-set-face pos end face))))
6408 ;; case 2: property access or function call
6409 ((or (js2-prop-get-node-p node)
6410 ;; highlight function call if expr is a prop-get node
6411 ;; or a plain name (i.e. unqualified function call)
6412 (and (setq call-p (js2-call-node-p node))
6413 (setq callee (js2-call-node-target node)) ; separate setq!
6414 (or (js2-prop-get-node-p callee)
6415 (js2-name-node-p callee))))
6416 (setq parent node
6417 node (if call-p callee node))
6418 (if (and call-p (js2-name-node-p callee))
6419 (setq prop callee)
6420 (setq target (js2-prop-get-node-left node)
6421 prop (js2-prop-get-node-right node)))
6422 (cond
6423 ((js2-name-node-p target)
6424 (if (js2-name-node-p prop)
6425 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6426 (js2-parse-highlight-prop-get parent target prop call-p)
6427 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6428 (js2-parse-highlight-prop-get parent target nil call-p)))
6429 ((js2-name-node-p prop)
6430 ;; case 2c: complex target, simple name, e.g. x[y].bar
6431 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6432
6433 (defun js2-parse-highlight-member-expr-fn-name (expr)
6434 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6435 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6436 We currently only handle the case where the last component is a prop-get
6437 of a simple name. Called before EXPR has a parent node."
6438 (let (pos
6439 (name (and (js2-prop-get-node-p expr)
6440 (js2-prop-get-node-right expr))))
6441 (when (js2-name-node-p name)
6442 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6443 (js2-node-pos name)))
6444 (+ pos (js2-node-len name))
6445 'font-lock-function-name-face
6446 'record))))
6447
6448 ;; source: http://jsdoc.sourceforge.net/
6449 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6450 ;; allows type specifications, and needs work before entering the wild.
6451
6452 (defconst js2-jsdoc-param-tag-regexp
6453 (concat "^\\s-*\\*+\\s-*\\(@"
6454 "\\(?:param\\|argument\\)"
6455 "\\)"
6456 "\\s-*\\({[^}]+}\\)?" ; optional type
6457 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6458 "\\>")
6459 "Matches jsdoc tags with optional type and optional param name.")
6460
6461 (defconst js2-jsdoc-typed-tag-regexp
6462 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6463 (regexp-opt
6464 '("enum"
6465 "extends"
6466 "field"
6467 "id"
6468 "implements"
6469 "lends"
6470 "mods"
6471 "requires"
6472 "return"
6473 "returns"
6474 "throw"
6475 "throws"))
6476 "\\)\\)\\s-*\\({[^}]+}\\)?")
6477 "Matches jsdoc tags with optional type.")
6478
6479 (defconst js2-jsdoc-arg-tag-regexp
6480 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6481 (regexp-opt
6482 '("alias"
6483 "augments"
6484 "borrows"
6485 "bug"
6486 "base"
6487 "config"
6488 "default"
6489 "define"
6490 "exception"
6491 "function"
6492 "member"
6493 "memberOf"
6494 "name"
6495 "namespace"
6496 "property"
6497 "since"
6498 "suppress"
6499 "this"
6500 "throws"
6501 "type"
6502 "version"))
6503 "\\)\\)\\s-+\\([^ \t]+\\)")
6504 "Matches jsdoc tags with a single argument.")
6505
6506 (defconst js2-jsdoc-empty-tag-regexp
6507 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6508 (regexp-opt
6509 '("addon"
6510 "author"
6511 "class"
6512 "const"
6513 "constant"
6514 "constructor"
6515 "constructs"
6516 "deprecated"
6517 "desc"
6518 "description"
6519 "event"
6520 "example"
6521 "exec"
6522 "export"
6523 "fileoverview"
6524 "final"
6525 "function"
6526 "hidden"
6527 "ignore"
6528 "implicitCast"
6529 "inheritDoc"
6530 "inner"
6531 "interface"
6532 "license"
6533 "noalias"
6534 "noshadow"
6535 "notypecheck"
6536 "override"
6537 "owner"
6538 "preserve"
6539 "preserveTry"
6540 "private"
6541 "protected"
6542 "public"
6543 "static"
6544 "supported"
6545 ))
6546 "\\)\\)\\s-*")
6547 "Matches empty jsdoc tags.")
6548
6549 (defconst js2-jsdoc-link-tag-regexp
6550 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6551 "Matches a jsdoc link or code tag.")
6552
6553 (defconst js2-jsdoc-see-tag-regexp
6554 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6555 "Matches a jsdoc @see tag.")
6556
6557 (defconst js2-jsdoc-html-tag-regexp
6558 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6559 "Matches a simple (no attributes) html start- or end-tag.")
6560
6561 (defsubst js2-jsdoc-highlight-helper ()
6562 (js2-set-face (match-beginning 1)
6563 (match-end 1)
6564 'js2-jsdoc-tag-face)
6565 (if (match-beginning 2)
6566 (if (save-excursion
6567 (goto-char (match-beginning 2))
6568 (= (char-after) ?{))
6569 (js2-set-face (1+ (match-beginning 2))
6570 (1- (match-end 2))
6571 'js2-jsdoc-type-face)
6572 (js2-set-face (match-beginning 2)
6573 (match-end 2)
6574 'js2-jsdoc-value-face)))
6575 (if (match-beginning 3)
6576 (js2-set-face (match-beginning 3)
6577 (match-end 3)
6578 'js2-jsdoc-value-face)))
6579
6580 (defun js2-highlight-jsdoc (ast)
6581 "Highlight doc comment tags."
6582 (let ((comments (js2-ast-root-comments ast))
6583 beg end)
6584 (save-excursion
6585 (dolist (node comments)
6586 (when (eq (js2-comment-node-format node) 'jsdoc)
6587 (setq beg (js2-node-abs-pos node)
6588 end (+ beg (js2-node-len node)))
6589 (save-restriction
6590 (narrow-to-region beg end)
6591 (dolist (re (list js2-jsdoc-param-tag-regexp
6592 js2-jsdoc-typed-tag-regexp
6593 js2-jsdoc-arg-tag-regexp
6594 js2-jsdoc-link-tag-regexp
6595 js2-jsdoc-see-tag-regexp
6596 js2-jsdoc-empty-tag-regexp))
6597 (goto-char beg)
6598 (while (re-search-forward re nil t)
6599 (js2-jsdoc-highlight-helper)))
6600 ;; simple highlighting for html tags
6601 (goto-char beg)
6602 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6603 (js2-set-face (match-beginning 1)
6604 (match-end 1)
6605 'js2-jsdoc-html-tag-delimiter-face)
6606 (js2-set-face (match-beginning 2)
6607 (match-end 2)
6608 'js2-jsdoc-html-tag-name-face)
6609 (js2-set-face (match-beginning 3)
6610 (match-end 3)
6611 'js2-jsdoc-html-tag-delimiter-face))))))))
6612
6613 (defun js2-highlight-assign-targets (node left right)
6614 "Highlight function properties and external variables."
6615 (let (leftpos end name)
6616 ;; highlight vars and props assigned function values
6617 (when (js2-function-node-p right)
6618 (cond
6619 ;; var foo = function() {...}
6620 ((js2-name-node-p left)
6621 (setq name left))
6622 ;; foo.bar.baz = function() {...}
6623 ((and (js2-prop-get-node-p left)
6624 (js2-name-node-p (js2-prop-get-node-right left)))
6625 (setq name (js2-prop-get-node-right left))))
6626 (when name
6627 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6628 (+ leftpos (js2-node-len name))
6629 'font-lock-function-name-face
6630 'record)))))
6631
6632 (defun js2-record-name-node (node)
6633 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6634 later. NODE must be a name node."
6635 (let (leftpos end)
6636 (push (list node js2-current-scope
6637 (setq leftpos (js2-node-abs-pos node))
6638 (setq end (+ leftpos (js2-node-len node))))
6639 js2-recorded-identifiers)))
6640
6641 (defun js2-highlight-undeclared-vars ()
6642 "After entire parse is finished, look for undeclared variable references.
6643 We have to wait until entire buffer is parsed, since JavaScript permits var
6644 decls to occur after they're used.
6645
6646 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6647 it is considered declared."
6648 (let (name)
6649 (dolist (entry js2-recorded-identifiers)
6650 (destructuring-bind (name-node scope pos end) entry
6651 (setq name (js2-name-node-name name-node))
6652 (unless (or (member name js2-global-externs)
6653 (member name js2-default-externs)
6654 (member name js2-additional-externs)
6655 (js2-get-defining-scope scope name))
6656 (js2-set-face pos end 'js2-external-variable-face 'record)
6657 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6658 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6659 (setq js2-recorded-identifiers nil)))
6660
6661 ;;; IMenu support
6662
6663 ;; We currently only support imenu, but eventually should support speedbar and
6664 ;; possibly other browsing mechanisms.
6665
6666 ;; The basic strategy is to identify function assignment targets of the form
6667 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6668 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6669 ;; for imenu after parsing is finished.
6670
6671 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6672 ;; JavaScript, and the general problem is undecidable. However, several forms
6673 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6674 ;; include:
6675
6676 ;; function foo() -- function declaration
6677 ;; foo = function() -- function expression assigned to variable
6678 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6679 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6680 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6681 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6682 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6683 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6684 ;; function foo() {function bar() {...}} -- nested function
6685 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6686
6687 ;; This list boils down to a few forms that can be combined recursively.
6688 ;; Top-level named function declarations include both the left-hand (name)
6689 ;; and the right-hand (function value) expressions needed to produce an imenu
6690 ;; entry. The other "right-hand" forms we need to look for are:
6691 ;; - functions declared as props/getters/setters in object literals
6692 ;; - nested named function declarations
6693 ;; The "left-hand" expressions that functions can be assigned to include:
6694 ;; - local/global variables
6695 ;; - nested property-get expressions like a.b.c.d
6696 ;; - element gets like foo[10] or foo['bar'] where the index
6697 ;; expression can be trivially converted to a property name. They
6698 ;; effectively then become property gets.
6699
6700 ;; All the different definition types are canonicalized into the form
6701 ;; foo.bar.baz = position-of-function-keyword
6702
6703 ;; We need to build a trie-like structure for imenu. As an example,
6704 ;; consider the following JavaScript code:
6705
6706 ;; a = function() {...} // function at position 5
6707 ;; b = function() {...} // function at position 25
6708 ;; foo = function() {...} // function at position 100
6709 ;; foo.bar = function() {...} // function at position 200
6710 ;; foo.bar.baz = function() {...} // function at position 300
6711 ;; foo.bar.zab = function() {...} // function at position 400
6712
6713 ;; During parsing we accumulate an entry for each definition in
6714 ;; the variable `js2-imenu-recorder', like so:
6715
6716 ;; '((a 5)
6717 ;; (b 25)
6718 ;; (foo 100)
6719 ;; (foo bar 200)
6720 ;; (foo bar baz 300)
6721 ;; (foo bar zab 400))
6722
6723 ;; After parsing these entries are merged into this alist-trie:
6724
6725 ;; '((a . 1)
6726 ;; (b . 2)
6727 ;; (foo (<definition> . 3)
6728 ;; (bar (<definition> . 6)
6729 ;; (baz . 100)
6730 ;; (zab . 200))))
6731
6732 ;; Note the wacky need for a <definition> name. The token can be anything
6733 ;; that isn't a valid JavaScript identifier, because you might make foo
6734 ;; a function and then start setting properties on it that are also functions.
6735
6736 (defsubst js2-prop-node-name (node)
6737 "Return the name of a node that may be a property-get/property-name.
6738 If NODE is not a valid name-node, string-node or integral number-node,
6739 returns nil. Otherwise returns the string name/value of the node."
6740 (cond
6741 ((js2-name-node-p node)
6742 (js2-name-node-name node))
6743 ((js2-string-node-p node)
6744 (js2-string-node-value node))
6745 ((and (js2-number-node-p node)
6746 (string-match "^[0-9]+$" (js2-number-node-value node)))
6747 (js2-number-node-value node))
6748 ((js2-this-node-p node)
6749 "this")))
6750
6751 (defsubst js2-node-qname-component (node)
6752 "Test function: return the name of this node, if it contributes to a qname.
6753 Returns nil if the node doesn't contribute."
6754 (copy-sequence
6755 (or (js2-prop-node-name node)
6756 (if (and (js2-function-node-p node)
6757 (js2-function-node-name node))
6758 (js2-name-node-name (js2-function-node-name node))))))
6759
6760 (defsubst js2-record-function-qname (fn-node qname)
6761 "Associate FN-NODE with its QNAME for later lookup.
6762 This is used in postprocessing the chain list. When we find a chain
6763 whose first element is a js2-THIS keyword node, we look up the parent
6764 function and see (using this map) whether it is the tail of a chain.
6765 If so, we replace the this-node with a copy of the parent's qname."
6766 (unless js2-imenu-function-map
6767 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6768 (puthash fn-node qname js2-imenu-function-map))
6769
6770 (defun js2-record-imenu-functions (node &optional var)
6771 "Record function definitions for imenu.
6772 NODE is a function node or an object literal.
6773 VAR, if non-nil, is the expression that NODE is being assigned to."
6774 (when js2-parse-ide-mode
6775 (let ((fun-p (js2-function-node-p node))
6776 qname left fname-node pos)
6777 (cond
6778 ;; non-anonymous function declaration?
6779 ((and fun-p
6780 (not var)
6781 (setq fname-node (js2-function-node-name node)))
6782 (push (setq qname (list fname-node (js2-node-pos node)))
6783 js2-imenu-recorder)
6784 (js2-record-function-qname node qname))
6785 ;; for remaining forms, compute left-side tree branch first
6786 ((and var (setq qname (js2-compute-nested-prop-get var)))
6787 (cond
6788 ;; foo.bar.baz = function
6789 (fun-p
6790 (push (nconc qname (list (js2-node-pos node)))
6791 js2-imenu-recorder)
6792 (js2-record-function-qname node qname))
6793 ;; foo.bar.baz = object-literal
6794 ;; look for nested functions: {a: {b: function() {...} }}
6795 ((js2-object-node-p node)
6796 ;; Node position here is still absolute, since the parser
6797 ;; passes the assignment target and value expressions
6798 ;; to us before they are added as children of the assignment node.
6799 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6800
6801 (defun js2-compute-nested-prop-get (node)
6802 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6803 component nodes as a list. Otherwise return nil. Element-gets are treated
6804 as property-gets if the index expression is a string, or a positive integer."
6805 (let (left right head)
6806 (cond
6807 ((or (js2-name-node-p node)
6808 (js2-this-node-p node))
6809 (list node))
6810 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6811 ((js2-prop-get-node-p node) ; foo.bar
6812 (setq left (js2-prop-get-node-left node)
6813 right (js2-prop-get-node-right node))
6814 (if (setq head (js2-compute-nested-prop-get left))
6815 (nconc head (list right))))
6816 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6817 (setq left (js2-elem-get-node-target node)
6818 right (js2-elem-get-node-element node))
6819 (if (or (js2-string-node-p right) ; ['bar']
6820 (and (js2-number-node-p right) ; [10]
6821 (string-match "^[0-9]+$"
6822 (js2-number-node-value right))))
6823 (if (setq head (js2-compute-nested-prop-get left))
6824 (nconc head (list right))))))))
6825
6826 (defun js2-record-object-literal (node qname pos)
6827 "Recursively process an object literal looking for functions.
6828 NODE is an object literal that is the right-hand child of an assignment
6829 expression. QNAME is a list of nodes representing the assignment target,
6830 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6831 POS is the absolute position of the node.
6832 We do a depth-first traversal of NODE. Any functions we find are prefixed
6833 with QNAME plus the property name of the function and appended to the
6834 variable `js2-imenu-recorder'."
6835 (let (left right)
6836 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6837 (let ((left (js2-infix-node-left e))
6838 ;; Element positions are relative to the parent position.
6839 (pos (+ pos (js2-node-pos e))))
6840 (cond
6841 ;; foo: function() {...}
6842 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6843 (when (js2-prop-node-name left)
6844 ;; As a policy decision, we record the position of the property,
6845 ;; not the position of the `function' keyword, since the property
6846 ;; is effectively the name of the function.
6847 (push (append qname (list left pos))
6848 js2-imenu-recorder)
6849 (js2-record-function-qname right qname)))
6850 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6851 ((js2-object-node-p right)
6852 (js2-record-object-literal right
6853 (append qname (list (js2-infix-node-left e)))
6854 (+ pos (js2-node-pos right)))))))))
6855
6856 (defsubst js2-node-top-level-decl-p (node)
6857 "Return t if NODE's name is defined in the top-level scope.
6858 Also returns t if NODE's name is not defined in any scope, since it implies
6859 that it's an external variable, which must also be in the top-level scope."
6860 (let* ((name (js2-prop-node-name node))
6861 (this-scope (js2-node-get-enclosing-scope node))
6862 defining-scope)
6863 (cond
6864 ((js2-this-node-p node)
6865 nil)
6866 ((null this-scope)
6867 t)
6868 ((setq defining-scope (js2-get-defining-scope this-scope name))
6869 (js2-ast-root-p defining-scope))
6870 (t t))))
6871
6872 (defsubst js2-anonymous-wrapper-fn-p (node)
6873 "Returns t if NODE is an anonymous function that's invoked immediately.
6874 NODE must be `js2-function-node'."
6875 (let ((parent (js2-node-parent node)))
6876 (and (js2-paren-node-p parent)
6877 ;; (function(){...})();
6878 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6879 ;; (function(){...}).call(this);
6880 (and (js2-prop-get-node-p parent)
6881 (member (js2-name-node-name (js2-prop-get-node-right parent))
6882 '("call" "apply"))
6883 (js2-call-node-p (js2-node-parent parent)))))))
6884
6885 (defun js2-browse-postprocess-chains (chains)
6886 "Modify function-declaration name chains after parsing finishes.
6887 Some of the information is only available after the parse tree is complete.
6888 For instance, following a 'this' reference requires a parent function node."
6889 (let (result head fn fn-type parent-chain p elem parent)
6890 (dolist (chain chains)
6891 ;; examine the head of each node to get its defining scope
6892 (setq head (car chain))
6893 ;; if top-level/external, keep as-is
6894 (if (js2-node-top-level-decl-p head)
6895 (push chain result)
6896 (cond
6897 ;; starts with this-reference
6898 ((js2-this-node-p head)
6899 (setq fn (js2-node-parent-script-or-fn head)
6900 chain (cdr chain))) ; discard this-node
6901 ;; nested named function
6902 ((js2-function-node-p (setq parent (js2-node-parent head)))
6903 (setq fn (js2-node-parent-script-or-fn parent)))
6904 ;; variable assigned a function expression
6905 (t (setq fn (js2-node-parent-script-or-fn head))))
6906 (when fn
6907 (if js2-imenu-fn-type-map
6908 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6909 (setq js2-imenu-fn-type-map (make-hash-table :test 'eq)))
6910 (unless fn-type
6911 (setq fn-type
6912 (cond ((js2-nested-function-p fn) 'skip)
6913 ((setq parent-chain
6914 (gethash fn js2-imenu-function-map))
6915 'named)
6916 ((js2-anonymous-wrapper-fn-p fn) 'anon)
6917 (t 'skip)))
6918 (puthash fn fn-type js2-imenu-fn-type-map))
6919 (case fn-type
6920 ('anon (push chain result)) ; anonymous top-level wrapper
6921 ('named ; top-level named function
6922 ;; prefix parent fn qname, which is
6923 ;; parent-chain sans last elem, to this chain.
6924 (push (append (butlast parent-chain) chain) result))))))
6925 ;; finally replace each node in each chain with its name.
6926 (dolist (chain result)
6927 (setq p chain)
6928 (while p
6929 (if (js2-node-p (setq elem (car p)))
6930 (setcar p (js2-node-qname-component elem)))
6931 (setq p (cdr p))))
6932 result))
6933
6934 ;; Merge name chains into a trie-like tree structure of nested lists.
6935 ;; To simplify construction of the trie, we first build it out using the rule
6936 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6937 ;; [key, num-or-list]. The second element can be a number; if so, this key
6938 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6939 ;; associated with the key at this level.) Otherwise the second element is
6940 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6941 ;; a simple recursive formulation.
6942 ;;
6943 ;; js2-mode is building the data structure for imenu. The imenu documentation
6944 ;; claims that it's the structure above, but in practice it wants the children
6945 ;; at the same list level as the key for that level, which is how I've drawn
6946 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6947 ;; list wrapper around the children at each level.
6948 ;;
6949 ;; A completed nested imenu-alist entry looks like this:
6950 ;; '(("foo"
6951 ;; ("<definition>" . 7)
6952 ;; ("bar"
6953 ;; ("a" . 40)
6954 ;; ("b" . 60))))
6955 ;;
6956 ;; In particular, the documentation for `imenu--index-alist' says that
6957 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6958 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6959
6960 (defsubst js2-treeify (lst)
6961 "Convert (a b c d) to (a ((b ((c d)))))"
6962 (if (null (cddr lst)) ; list length <= 2
6963 lst
6964 (list (car lst) (list (js2-treeify (cdr lst))))))
6965
6966 (defun js2-build-alist-trie (chains trie)
6967 "Merge declaration name chains into a trie-like alist structure for imenu.
6968 CHAINS is the qname chain list produced during parsing. TRIE is a
6969 list of elements built up so far."
6970 (let (head tail pos branch kids)
6971 (dolist (chain chains)
6972 (setq head (car chain)
6973 tail (cdr chain)
6974 pos (if (numberp (car tail)) (car tail))
6975 branch (js2-find-if (lambda (n)
6976 (string= (car n) head))
6977 trie)
6978 kids (second branch))
6979 (cond
6980 ;; case 1: this key isn't in the trie yet
6981 ((null branch)
6982 (if trie
6983 (setcdr (last trie) (list (js2-treeify chain)))
6984 (setq trie (list (js2-treeify chain)))))
6985 ;; case 2: key is present with a single number entry: replace w/ list
6986 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6987 ;; ("<definition>" 20)))
6988 ((numberp kids)
6989 (setcar (cdr branch)
6990 (list (list "<definition-1>" kids)
6991 (if pos
6992 (list "<definition-2>" pos)
6993 (js2-treeify tail)))))
6994 ;; case 3: key is there (with kids), and we're a number entry
6995 (pos
6996 (setcdr (last kids)
6997 (list
6998 (list (format "<definition-%d>"
6999 (1+ (loop for kid in kids
7000 count (eq ?< (aref (car kid) 0)))))
7001 pos))))
7002 ;; case 4: key is there with kids, need to merge in our chain
7003 (t
7004 (js2-build-alist-trie (list tail) kids))))
7005 trie))
7006
7007 (defun js2-flatten-trie (trie)
7008 "Convert TRIE to imenu-format.
7009 Recurses through nodes, and for each one whose second element is a list,
7010 appends the list's flattened elements to the current element. Also
7011 changes the tails into conses. For instance, this pre-flattened trie
7012
7013 '(a ((b 20)
7014 (c ((d 30)
7015 (e 40)))))
7016
7017 becomes
7018
7019 '(a (b . 20)
7020 (c (d . 30)
7021 (e . 40)))
7022
7023 Note that the root of the trie has no key, just a list of chains.
7024 This is also true for the value of any key with multiple children,
7025 e.g. key 'c' in the example above."
7026 (cond
7027 ((listp (car trie))
7028 (mapcar #'js2-flatten-trie trie))
7029 (t
7030 (if (numberp (second trie))
7031 (cons (car trie) (second trie))
7032 ;; else pop list and append its kids
7033 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7034
7035 (defun js2-build-imenu-index ()
7036 "Turn `js2-imenu-recorder' into an imenu data structure."
7037 (unless (eq js2-imenu-recorder 'empty)
7038 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7039 (result (js2-build-alist-trie chains nil)))
7040 (js2-flatten-trie result))))
7041
7042 (defun js2-test-print-chains (chains)
7043 "Print a list of qname chains.
7044 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7045 i.e. one or more nodes, and an integer position as the list tail."
7046 (mapconcat (lambda (chain)
7047 (concat "("
7048 (mapconcat (lambda (elem)
7049 (if (js2-node-p elem)
7050 (or (js2-node-qname-component elem)
7051 "nil")
7052 (number-to-string elem)))
7053 chain
7054 " ")
7055 ")"))
7056 chains
7057 "\n"))
7058
7059 ;;; Parser
7060
7061 (defconst js2-version "1.8.0"
7062 "Version of JavaScript supported, plus minor js2 version.")
7063
7064 (defmacro js2-record-face (face)
7065 "Record a style run of FACE for the current token."
7066 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7067
7068 (defsubst js2-node-end (n)
7069 "Computes the absolute end of node N.
7070 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7071 is only true until the node is added to its parent; i.e., while parsing."
7072 (+ (js2-node-pos n)
7073 (js2-node-len n)))
7074
7075 (defsubst js2-record-comment ()
7076 "Record a comment in `js2-scanned-comments'."
7077 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7078 :format js2-ts-comment-type)
7079 js2-scanned-comments)
7080 (when js2-parse-ide-mode
7081 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7082 'font-lock-doc-face
7083 'font-lock-comment-face))
7084 (when (memq js2-ts-comment-type '(html preprocessor))
7085 ;; Tell cc-engine the bounds of the comment.
7086 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7087
7088 ;; This function is called depressingly often, so it should be fast.
7089 ;; Most of the time it's looking at the same token it peeked before.
7090 (defsubst js2-peek-token ()
7091 "Returns the next token without consuming it.
7092 If previous token was consumed, calls scanner to get new token.
7093 If previous token was -not- consumed, returns it (idempotent).
7094
7095 This function will not return a newline (js2-EOL) - instead, it
7096 gobbles newlines until it finds a non-newline token, and flags
7097 that token as appearing just after a newline.
7098
7099 This function will also not return a js2-COMMENT. Instead, it
7100 records comments found in `js2-scanned-comments'. If the token
7101 returned by this function immediately follows a jsdoc comment,
7102 the token is flagged as such.
7103
7104 Note that this function always returned the un-flagged token!
7105 The flags, if any, are saved in `js2-current-flagged-token'."
7106 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7107 js2-current-token ; most common case - return already-peeked token
7108 (let ((tt (js2-get-token)) ; call scanner
7109 saw-eol
7110 face)
7111 ;; process comments and whitespace
7112 (while (or (= tt js2-EOL)
7113 (= tt js2-COMMENT))
7114 (if (= tt js2-EOL)
7115 (setq saw-eol t)
7116 (setq saw-eol nil)
7117 (if js2-record-comments
7118 (js2-record-comment)))
7119 (setq tt (js2-get-token))) ; call scanner
7120 (setq js2-current-token tt
7121 js2-current-flagged-token (if saw-eol
7122 (logior tt js2-ti-after-eol)
7123 tt))
7124 ;; perform lexical fontification as soon as token is scanned
7125 (when js2-parse-ide-mode
7126 (cond
7127 ((minusp tt)
7128 (js2-record-face 'js2-error-face))
7129 ((setq face (aref js2-kwd-tokens tt))
7130 (js2-record-face face))
7131 ((and (= tt js2-NAME)
7132 (equal js2-ts-string "undefined"))
7133 (js2-record-face 'font-lock-constant-face))))
7134 tt))) ; return unflagged token
7135
7136 (defsubst js2-peek-flagged-token ()
7137 "Returns the current token along with any flags set for it."
7138 (js2-peek-token)
7139 js2-current-flagged-token)
7140
7141 (defsubst js2-consume-token ()
7142 (setq js2-current-flagged-token js2-EOF))
7143
7144 (defsubst js2-next-token ()
7145 (prog1
7146 (js2-peek-token)
7147 (js2-consume-token)))
7148
7149 (defsubst js2-next-flagged-token ()
7150 (js2-peek-token)
7151 (prog1 js2-current-flagged-token
7152 (js2-consume-token)))
7153
7154 (defsubst js2-match-token (match)
7155 "Consume and return t if next token matches MATCH, a bytecode.
7156 Returns nil and consumes nothing if MATCH is not the next token."
7157 (if (/= (js2-peek-token) match)
7158 nil
7159 (js2-consume-token)
7160 t))
7161
7162 (defsubst js2-valid-prop-name-token (tt)
7163 (or (= tt js2-NAME)
7164 (and js2-allow-keywords-as-property-names
7165 (plusp tt)
7166 (aref js2-kwd-tokens tt))))
7167
7168 (defsubst js2-match-prop-name ()
7169 "Consume token and return t if next token is a valid property name.
7170 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7171 is non-nil and it's a keyword token."
7172 (if (js2-valid-prop-name-token (js2-peek-token))
7173 (progn
7174 (js2-consume-token)
7175 t)
7176 nil))
7177
7178 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7179 (if (js2-match-prop-name)
7180 t
7181 (js2-report-error msg-id nil pos len)
7182 nil))
7183
7184 (defsubst js2-peek-token-or-eol ()
7185 "Return js2-EOL if the current token immediately follows a newline.
7186 Else returns the current token. Used in situations where we don't
7187 consider certain token types valid if they are preceded by a newline.
7188 One example is the postfix ++ or -- operator, which has to be on the
7189 same line as its operand."
7190 (let ((tt (js2-peek-token)))
7191 ;; Check for last peeked token flags
7192 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7193 js2-EOL
7194 tt)))
7195
7196 (defsubst js2-set-check-for-label ()
7197 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7198 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7199
7200 (defsubst js2-must-match (token msg-id &optional pos len)
7201 "Match next token to token code TOKEN, or record a syntax error.
7202 MSG-ID is the error message to report if the match fails.
7203 Returns t on match, nil if no match."
7204 (if (js2-match-token token)
7205 t
7206 (js2-report-error msg-id nil pos len)
7207 nil))
7208
7209 (defsubst js2-inside-function ()
7210 (plusp js2-nesting-of-function))
7211
7212 (defsubst js2-set-requires-activation ()
7213 (if (js2-function-node-p js2-current-script-or-fn)
7214 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7215
7216 (defsubst js2-check-activation-name (name token)
7217 (when (js2-inside-function)
7218 ;; skip language-version 1.2 check from Rhino
7219 (if (or (string= "arguments" name)
7220 (and js2-compiler-activation-names ; only used in codegen
7221 (gethash name js2-compiler-activation-names)))
7222 (js2-set-requires-activation))))
7223
7224 (defsubst js2-set-is-generator ()
7225 (if (js2-function-node-p js2-current-script-or-fn)
7226 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7227
7228 (defsubst js2-must-have-xml ()
7229 (unless js2-compiler-xml-available
7230 (js2-report-error "msg.XML.not.available")))
7231
7232 (defsubst js2-push-scope (scope)
7233 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7234 (assert (js2-scope-p scope))
7235 (assert (null (js2-scope-parent-scope scope)))
7236 (assert (not (eq js2-current-scope scope)))
7237 (setf (js2-scope-parent-scope scope) js2-current-scope
7238 js2-current-scope scope))
7239
7240 (defsubst js2-pop-scope ()
7241 (setq js2-current-scope
7242 (js2-scope-parent-scope js2-current-scope)))
7243
7244 (defsubst js2-enter-loop (loop-node)
7245 (push loop-node js2-loop-set)
7246 (push loop-node js2-loop-and-switch-set)
7247 (js2-push-scope loop-node)
7248 ;; Tell the current labeled statement (if any) its statement,
7249 ;; and set the jump target of the first label to the loop.
7250 ;; These are used in `js2-parse-continue' to verify that the
7251 ;; continue target is an actual labeled loop. (And for codegen.)
7252 (when js2-labeled-stmt
7253 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7254 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7255 js2-labeled-stmt))) loop-node)))
7256
7257 (defsubst js2-exit-loop ()
7258 (pop js2-loop-set)
7259 (pop js2-loop-and-switch-set)
7260 (js2-pop-scope))
7261
7262 (defsubst js2-enter-switch (switch-node)
7263 (push switch-node js2-loop-and-switch-set))
7264
7265 (defsubst js2-exit-switch ()
7266 (pop js2-loop-and-switch-set))
7267
7268 (defun js2-parse (&optional buf cb)
7269 "Tells the js2 parser to parse a region of JavaScript.
7270
7271 BUF is a buffer or buffer name containing the code to parse.
7272 Call `narrow-to-region' first to parse only part of the buffer.
7273
7274 The returned AST root node is given some additional properties:
7275 `node-count' - total number of nodes in the AST
7276 `buffer' - BUF. The buffer it refers to may change or be killed,
7277 so the value is not necessarily reliable.
7278
7279 An optional callback CB can be specified to report parsing
7280 progress. If `(functionp CB)' returns t, it will be called with
7281 the current line number once before parsing begins, then again
7282 each time the lexer reaches a new line number.
7283
7284 CB can also be a list of the form `(symbol cb ...)' to specify
7285 multiple callbacks with different criteria. Each symbol is a
7286 criterion keyword, and the following element is the callback to
7287 call
7288
7289 :line - called whenever the line number changes
7290 :token - called for each new token consumed
7291
7292 The list of criteria could be extended to include entering or
7293 leaving a statement, an expression, or a function definition."
7294 (if (and cb (not (functionp cb)))
7295 (error "criteria callbacks not yet implemented"))
7296 (let ((inhibit-point-motion-hooks t)
7297 (js2-compiler-xml-available (>= js2-language-version 160))
7298 ;; This is a recursive-descent parser, so give it a big stack.
7299 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7300 (max-specpdl-size (max max-specpdl-size 3000))
7301 (case-fold-search nil)
7302 ast)
7303 (or buf (setq buf (current-buffer)))
7304 (message nil) ; clear any error message from previous parse
7305 (save-excursion
7306 (set-buffer buf)
7307 (setq js2-scanned-comments nil
7308 js2-parsed-errors nil
7309 js2-parsed-warnings nil
7310 js2-imenu-recorder nil
7311 js2-imenu-function-map nil
7312 js2-imenu-fn-type-map nil
7313 js2-label-set nil)
7314 (js2-init-scanner)
7315 (setq ast (js2-with-unmodifying-text-property-changes
7316 (js2-do-parse)))
7317 (unless js2-ts-hit-eof
7318 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7319 (setf (js2-ast-root-errors ast) js2-parsed-errors
7320 (js2-ast-root-warnings ast) js2-parsed-warnings)
7321 ;; if we didn't find any declarations, put a dummy in this list so we
7322 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7323 (unless js2-imenu-recorder
7324 (setq js2-imenu-recorder 'empty))
7325 (run-hooks 'js2-parse-finished-hook)
7326 ast)))
7327
7328 ;; Corresponds to Rhino's Parser.parse() method.
7329 (defun js2-do-parse ()
7330 "Parse current buffer starting from current point.
7331 Scanner should be initialized."
7332 (let ((pos js2-ts-cursor)
7333 (end js2-ts-cursor) ; in case file is empty
7334 root n tt)
7335 ;; initialize buffer-local parsing vars
7336 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7337 js2-current-script-or-fn root
7338 js2-current-scope root
7339 js2-current-flagged-token js2-EOF
7340 js2-nesting-of-function 0
7341 js2-labeled-stmt nil
7342 js2-recorded-identifiers nil) ; for js2-highlight
7343 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7344 (if (= tt js2-FUNCTION)
7345 (progn
7346 (js2-consume-token)
7347 (setq n (js2-parse-function (if js2-called-by-compile-function
7348 'FUNCTION_EXPRESSION
7349 'FUNCTION_STATEMENT))))
7350 ;; not a function - parse a statement
7351 (setq n (js2-parse-statement)))
7352 ;; add function or statement to script
7353 (setq end (js2-node-end n))
7354 (js2-block-node-push root n))
7355 ;; add comments to root in lexical order
7356 (when js2-scanned-comments
7357 ;; if we find a comment beyond end of normal kids, use its end
7358 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7359 (dolist (comment js2-scanned-comments)
7360 (push comment (js2-ast-root-comments root))
7361 (js2-node-add-children root comment)))
7362 (setf (js2-node-len root) (- end pos))
7363 ;; Give extensions a chance to muck with things before highlighting starts.
7364 (dolist (callback js2-post-parse-callbacks)
7365 (funcall callback))
7366 (js2-highlight-undeclared-vars)
7367 root))
7368
7369 (defun js2-function-parser ()
7370 (js2-consume-token)
7371 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7372
7373 (defun js2-parse-function-closure-body (fn-node)
7374 "Parse a JavaScript 1.8 function closure body."
7375 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7376 (if js2-ts-hit-eof
7377 (js2-report-error "msg.no.brace.body" nil
7378 (js2-node-pos fn-node)
7379 (- js2-ts-cursor (js2-node-pos fn-node)))
7380 (js2-node-add-children fn-node
7381 (setf (js2-function-node-body fn-node)
7382 (js2-parse-expr t))))))
7383
7384 (defun js2-parse-function-body (fn-node)
7385 (js2-must-match js2-LC "msg.no.brace.body"
7386 (js2-node-pos fn-node)
7387 (- js2-ts-cursor (js2-node-pos fn-node)))
7388 (let ((pos js2-token-beg) ; LC position
7389 (pn (make-js2-block-node)) ; starts at LC position
7390 tt
7391 end)
7392 (incf js2-nesting-of-function)
7393 (unwind-protect
7394 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7395 (= tt js2-EOF)
7396 (= tt js2-RC)))
7397 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7398 (js2-parse-statement)
7399 (js2-consume-token)
7400 (js2-parse-function 'FUNCTION_STATEMENT))))
7401 (decf js2-nesting-of-function))
7402 (setq end js2-token-end) ; assume no curly and leave at current token
7403 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7404 (setq end js2-token-end))
7405 (setf (js2-node-pos pn) pos
7406 (js2-node-len pn) (- end pos))
7407 (setf (js2-function-node-body fn-node) pn)
7408 (js2-node-add-children fn-node pn)
7409 pn))
7410
7411 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7412 "Declare and fontify destructuring parameters inside NODE.
7413 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7414 (cond
7415 ((js2-name-node-p node)
7416 (let (leftpos)
7417 (js2-define-symbol decl-type (js2-name-node-name node)
7418 node ignore-not-in-block)
7419 (when face
7420 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7421 (+ leftpos (js2-node-len node))
7422 face 'record))))
7423 ((js2-object-node-p node)
7424 (dolist (elem (js2-object-node-elems node))
7425 (js2-define-destruct-symbols
7426 (if (js2-object-prop-node-p elem)
7427 (js2-object-prop-node-right elem)
7428 ;; abbreviated destructuring {a, b}
7429 elem)
7430 decl-type face ignore-not-in-block)))
7431 ((js2-array-node-p node)
7432 (dolist (elem (js2-array-node-elems node))
7433 (when elem
7434 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7435 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7436 (js2-node-len node)))))
7437
7438 (defun js2-parse-function-params (fn-node pos)
7439 (if (js2-match-token js2-RP)
7440 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7441 (let (params len param)
7442 (loop for tt = (js2-peek-token)
7443 do
7444 (cond
7445 ;; destructuring param
7446 ((or (= tt js2-LB) (= tt js2-LC))
7447 (setq param (js2-parse-primary-expr-lhs))
7448 (js2-define-destruct-symbols param
7449 js2-LP
7450 'js2-function-param-face)
7451 (push param params))
7452 ;; simple name
7453 (t
7454 (js2-must-match js2-NAME "msg.no.parm")
7455 (js2-record-face 'js2-function-param-face)
7456 (setq param (js2-create-name-node))
7457 (js2-define-symbol js2-LP js2-ts-string param)
7458 (push param params)))
7459 while
7460 (js2-match-token js2-COMMA))
7461 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7462 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7463 (dolist (p params)
7464 (js2-node-add-children fn-node p)
7465 (push p (js2-function-node-params fn-node))))))
7466
7467 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7468 "Possibly show inconsistent-return warning.
7469 Last token scanned is the close-curly for the function body."
7470 (when (and js2-mode-show-strict-warnings
7471 js2-strict-inconsistent-return-warning
7472 (not (js2-has-consistent-return-usage
7473 (js2-function-node-body fn-node))))
7474 ;; Have it extend from close-curly to bol or beginning of block.
7475 (let ((pos (save-excursion
7476 (goto-char js2-token-end)
7477 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7478 (point-at-bol))))
7479 (end js2-token-end))
7480 (if (plusp (js2-name-node-length name))
7481 (js2-add-strict-warning "msg.no.return.value"
7482 (js2-name-node-name name) pos end)
7483 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7484
7485 (defun js2-parse-function (function-type)
7486 "Function parser. FUNCTION-TYPE is a symbol."
7487 (let ((pos js2-token-beg) ; start of 'function' keyword
7488 name
7489 name-beg
7490 name-end
7491 fn-node
7492 lp
7493 (synthetic-type function-type)
7494 member-expr-node)
7495 ;; parse function name, expression, or non-name (anonymous)
7496 (cond
7497 ;; function foo(...)
7498 ((js2-match-token js2-NAME)
7499 (setq name (js2-create-name-node t)
7500 name-beg js2-token-beg
7501 name-end js2-token-end)
7502 (unless (js2-match-token js2-LP)
7503 (when js2-allow-member-expr-as-function-name
7504 ;; function foo.bar(...)
7505 (setq member-expr-node name
7506 name nil
7507 member-expr-node (js2-parse-member-expr-tail
7508 nil member-expr-node)))
7509 (js2-must-match js2-LP "msg.no.paren.parms")))
7510 ((js2-match-token js2-LP)
7511 nil) ; anonymous function: leave name as null
7512 (t
7513 ;; function random-member-expr(...)
7514 (when js2-allow-member-expr-as-function-name
7515 ;; Note that memberExpr can not start with '(' like
7516 ;; in function (1+2).toString(), because 'function (' already
7517 ;; processed as anonymous function
7518 (setq member-expr-node (js2-parse-member-expr)))
7519 (js2-must-match js2-LP "msg.no.paren.parms")))
7520 (if (= js2-current-token js2-LP) ; eventually matched LP?
7521 (setq lp js2-token-beg))
7522 (if member-expr-node
7523 (progn
7524 (setq synthetic-type 'FUNCTION_EXPRESSION)
7525 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7526 (if name
7527 (js2-set-face name-beg name-end
7528 'font-lock-function-name-face 'record)))
7529 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7530 (plusp (js2-name-node-length name)))
7531 ;; Function statements define a symbol in the enclosing scope
7532 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7533 (setf fn-node (make-js2-function-node :pos pos
7534 :name name
7535 :form function-type
7536 :lp (if lp (- lp pos))))
7537 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7538 ;; 1. Nested functions are not affected by the dynamic scope flag
7539 ;; as dynamic scope is already a parent of their scope.
7540 ;; 2. Functions defined under the with statement also immune to
7541 ;; this setup, in which case dynamic scope is ignored in favor
7542 ;; of the with object.
7543 (setf (js2-function-node-ignore-dynamic fn-node) t))
7544 ;; dynamically bind all the per-function variables
7545 (let ((js2-current-script-or-fn fn-node)
7546 (js2-current-scope fn-node)
7547 (js2-nesting-of-with 0)
7548 (js2-end-flags 0)
7549 js2-label-set
7550 js2-loop-set
7551 js2-loop-and-switch-set)
7552 (js2-parse-function-params fn-node pos)
7553 (if (and (>= js2-language-version 180)
7554 (/= (js2-peek-token) js2-LC))
7555 (js2-parse-function-closure-body fn-node)
7556 (js2-parse-function-body fn-node))
7557 (if name
7558 (js2-node-add-children fn-node name))
7559 (js2-check-inconsistent-return-warning fn-node name)
7560 ;; Function expressions define a name only in the body of the
7561 ;; function, and only if not hidden by a parameter name
7562 (if (and name
7563 (eq synthetic-type 'FUNCTION_EXPRESSION)
7564 (null (js2-scope-get-symbol js2-current-scope
7565 (js2-name-node-name name))))
7566 (js2-define-symbol js2-FUNCTION
7567 (js2-name-node-name name)
7568 fn-node))
7569 (if (and name
7570 (not (eq function-type 'FUNCTION_EXPRESSION)))
7571 (js2-record-imenu-functions fn-node)))
7572 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7573 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7574 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7575 ;; We wait until after parsing the function to set its parent scope,
7576 ;; since `js2-define-symbol' needs the defining-scope check to stop
7577 ;; at the function boundary when checking for redeclarations.
7578 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7579 fn-node))
7580
7581 (defun js2-parse-statements (&optional parent)
7582 "Parse a statement list. Last token consumed must be js2-LC.
7583
7584 PARENT can be a `js2-block-node', in which case the statements are
7585 appended to PARENT. Otherwise a new `js2-block-node' is created
7586 and returned.
7587
7588 This function does not match the closing js2-RC: the caller
7589 matches the RC so it can provide a suitable error message if not
7590 matched. This means it's up to the caller to set the length of
7591 the node to include the closing RC. The node start pos is set to
7592 the absolute buffer start position, and the caller should fix it
7593 up to be relative to the parent node. All children of this block
7594 node are given relative start positions and correct lengths."
7595 (let ((pn (or parent (make-js2-block-node)))
7596 tt)
7597 (setf (js2-node-pos pn) js2-token-beg)
7598 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7599 (/= tt js2-RC))
7600 (js2-block-node-push pn (js2-parse-statement)))
7601 pn))
7602
7603 (defun js2-parse-statement ()
7604 (let (tt pn beg end)
7605 ;; coarse-grained user-interrupt check - needs work
7606 (and js2-parse-interruptable-p
7607 (zerop (% (incf js2-parse-stmt-count)
7608 js2-statements-per-pause))
7609 (input-pending-p)
7610 (throw 'interrupted t))
7611 (setq pn (js2-statement-helper))
7612 ;; no-side-effects warning check
7613 (unless (js2-node-has-side-effects pn)
7614 (setq end (js2-node-end pn))
7615 (save-excursion
7616 (goto-char end)
7617 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7618 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7619 pn))
7620
7621 ;; These correspond to the switch cases in Parser.statementHelper
7622 (defconst js2-parsers
7623 (let ((parsers (make-vector js2-num-tokens
7624 #'js2-parse-expr-stmt)))
7625 (aset parsers js2-BREAK #'js2-parse-break)
7626 (aset parsers js2-CONST #'js2-parse-const-var)
7627 (aset parsers js2-CONTINUE #'js2-parse-continue)
7628 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7629 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7630 (aset parsers js2-DO #'js2-parse-do)
7631 (aset parsers js2-FOR #'js2-parse-for)
7632 (aset parsers js2-FUNCTION #'js2-function-parser)
7633 (aset parsers js2-IF #'js2-parse-if)
7634 (aset parsers js2-LC #'js2-parse-block)
7635 (aset parsers js2-LET #'js2-parse-let-stmt)
7636 (aset parsers js2-NAME #'js2-parse-name-or-label)
7637 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7638 (aset parsers js2-SEMI #'js2-parse-semi)
7639 (aset parsers js2-SWITCH #'js2-parse-switch)
7640 (aset parsers js2-THROW #'js2-parse-throw)
7641 (aset parsers js2-TRY #'js2-parse-try)
7642 (aset parsers js2-VAR #'js2-parse-const-var)
7643 (aset parsers js2-WHILE #'js2-parse-while)
7644 (aset parsers js2-WITH #'js2-parse-with)
7645 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7646 parsers)
7647 "A vector mapping token types to parser functions.")
7648
7649 (defsubst js2-parse-warn-missing-semi (beg end)
7650 (and js2-mode-show-strict-warnings
7651 js2-strict-missing-semi-warning
7652 (js2-add-strict-warning
7653 "msg.missing.semi" nil
7654 ;; back up to beginning of statement or line
7655 (max beg (save-excursion
7656 (goto-char end)
7657 (point-at-bol)))
7658 end)))
7659
7660 (defconst js2-no-semi-insertion
7661 (list js2-IF
7662 js2-SWITCH
7663 js2-WHILE
7664 js2-DO
7665 js2-FOR
7666 js2-TRY
7667 js2-WITH
7668 js2-LC
7669 js2-ERROR
7670 js2-SEMI
7671 js2-FUNCTION)
7672 "List of tokens that don't do automatic semicolon insertion.")
7673
7674 (defconst js2-autoinsert-semi-and-warn
7675 (list js2-ERROR js2-EOF js2-RC))
7676
7677 (defun js2-statement-helper ()
7678 (let* ((tt (js2-peek-token))
7679 (first-tt tt)
7680 (beg js2-token-beg)
7681 (parser (if (= tt js2-ERROR)
7682 #'js2-parse-semi
7683 (aref js2-parsers tt)))
7684 pn
7685 tt-flagged)
7686 ;; If the statement is set, then it's been told its label by now.
7687 (and js2-labeled-stmt
7688 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7689 (setq js2-labeled-stmt nil))
7690 (setq pn (funcall parser))
7691 ;; Don't do auto semi insertion for certain statement types.
7692 (unless (or (memq first-tt js2-no-semi-insertion)
7693 (js2-labeled-stmt-node-p pn))
7694 (js2-auto-insert-semicolon pn))
7695 pn))
7696
7697 (defun js2-auto-insert-semicolon (pn)
7698 (let* ((tt-flagged (js2-peek-flagged-token))
7699 (tt (logand tt-flagged js2-clear-ti-mask))
7700 (pos (js2-node-pos pn)))
7701 (cond
7702 ((= tt js2-SEMI)
7703 ;; Consume ';' as a part of expression
7704 (js2-consume-token)
7705 ;; extend the node bounds to include the semicolon.
7706 (setf (js2-node-len pn) (- js2-token-end pos)))
7707 ((memq tt js2-autoinsert-semi-and-warn)
7708 ;; Autoinsert ;
7709 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7710 (t
7711 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7712 ;; Report error if no EOL or autoinsert ';' otherwise
7713 (js2-report-error "msg.no.semi.stmt")
7714 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7715
7716 (defun js2-parse-condition ()
7717 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7718 The parens are discarded and the expression node is returned.
7719 The `pos' field of the return value is set to an absolute position
7720 that must be fixed up by the caller.
7721 Return value is a list (EXPR LP RP), with absolute paren positions."
7722 (let (pn lp rp)
7723 (if (js2-must-match js2-LP "msg.no.paren.cond")
7724 (setq lp js2-token-beg))
7725 (setq pn (js2-parse-expr))
7726 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7727 (setq rp js2-token-beg))
7728 ;; Report strict warning on code like "if (a = 7) ..."
7729 (if (and js2-strict-cond-assign-warning
7730 (js2-assign-node-p pn))
7731 (js2-add-strict-warning "msg.equal.as.assign" nil
7732 (js2-node-pos pn)
7733 (+ (js2-node-pos pn)
7734 (js2-node-len pn))))
7735 (list pn lp rp)))
7736
7737 (defun js2-parse-if ()
7738 "Parser for if-statement. Last matched token must be js2-IF."
7739 (let ((pos js2-token-beg)
7740 cond
7741 if-true
7742 if-false
7743 else-pos
7744 end
7745 pn)
7746 (js2-consume-token)
7747 (setq cond (js2-parse-condition)
7748 if-true (js2-parse-statement)
7749 if-false (if (js2-match-token js2-ELSE)
7750 (progn
7751 (setq else-pos (- js2-token-beg pos))
7752 (js2-parse-statement)))
7753 end (js2-node-end (or if-false if-true))
7754 pn (make-js2-if-node :pos pos
7755 :len (- end pos)
7756 :condition (car cond)
7757 :then-part if-true
7758 :else-part if-false
7759 :else-pos else-pos
7760 :lp (js2-relpos (second cond) pos)
7761 :rp (js2-relpos (third cond) pos)))
7762 (js2-node-add-children pn (car cond) if-true if-false)
7763 pn))
7764
7765 (defun js2-parse-switch ()
7766 "Parser for if-statement. Last matched token must be js2-SWITCH."
7767 (let ((pos js2-token-beg)
7768 tt
7769 pn
7770 discriminant
7771 has-default
7772 case-expr
7773 case-node
7774 case-pos
7775 cases
7776 stmt
7777 lp
7778 rp)
7779 (js2-consume-token)
7780 (if (js2-must-match js2-LP "msg.no.paren.switch")
7781 (setq lp js2-token-beg))
7782 (setq discriminant (js2-parse-expr)
7783 pn (make-js2-switch-node :discriminant discriminant
7784 :pos pos
7785 :lp (js2-relpos lp pos)))
7786 (js2-node-add-children pn discriminant)
7787 (js2-enter-switch pn)
7788 (unwind-protect
7789 (progn
7790 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7791 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7792 (js2-must-match js2-LC "msg.no.brace.switch")
7793 (catch 'break
7794 (while t
7795 (setq tt (js2-next-token)
7796 case-pos js2-token-beg)
7797 (cond
7798 ((= tt js2-RC)
7799 (setf (js2-node-len pn) (- js2-token-end pos))
7800 (throw 'break nil)) ; done
7801 ((= tt js2-CASE)
7802 (setq case-expr (js2-parse-expr))
7803 (js2-must-match js2-COLON "msg.no.colon.case"))
7804 ((= tt js2-DEFAULT)
7805 (if has-default
7806 (js2-report-error "msg.double.switch.default"))
7807 (setq has-default t
7808 case-expr nil)
7809 (js2-must-match js2-COLON "msg.no.colon.case"))
7810 (t
7811 (js2-report-error "msg.bad.switch")
7812 (throw 'break nil)))
7813 (setq case-node (make-js2-case-node :pos case-pos
7814 :len (- js2-token-end case-pos)
7815 :expr case-expr))
7816 (js2-node-add-children case-node case-expr)
7817 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7818 (/= tt js2-CASE)
7819 (/= tt js2-DEFAULT)
7820 (/= tt js2-EOF))
7821 (setf stmt (js2-parse-statement)
7822 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7823 (js2-block-node-push case-node stmt))
7824 (push case-node cases)))
7825 ;; add cases last, as pushing reverses the order to be correct
7826 (dolist (kid cases)
7827 (js2-node-add-children pn kid)
7828 (push kid (js2-switch-node-cases pn)))
7829 pn) ; return value
7830 (js2-exit-switch))))
7831
7832 (defun js2-parse-while ()
7833 "Parser for while-statement. Last matched token must be js2-WHILE."
7834 (let ((pos js2-token-beg)
7835 (pn (make-js2-while-node))
7836 cond
7837 body)
7838 (js2-consume-token)
7839 (js2-enter-loop pn)
7840 (unwind-protect
7841 (progn
7842 (setf cond (js2-parse-condition)
7843 (js2-while-node-condition pn) (car cond)
7844 body (js2-parse-statement)
7845 (js2-while-node-body pn) body
7846 (js2-node-len pn) (- (js2-node-end body) pos)
7847 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7848 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7849 (js2-node-add-children pn body (car cond)))
7850 (js2-exit-loop))
7851 pn))
7852
7853 (defun js2-parse-do ()
7854 "Parser for do-statement. Last matched token must be js2-DO."
7855 (let ((pos js2-token-beg)
7856 (pn (make-js2-do-node))
7857 cond
7858 body
7859 end)
7860 (js2-consume-token)
7861 (js2-enter-loop pn)
7862 (unwind-protect
7863 (progn
7864 (setq body (js2-parse-statement))
7865 (js2-must-match js2-WHILE "msg.no.while.do")
7866 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7867 cond (js2-parse-condition)
7868 (js2-do-node-condition pn) (car cond)
7869 (js2-do-node-body pn) body
7870 end js2-ts-cursor
7871 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7872 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7873 (js2-node-add-children pn (car cond) body))
7874 (js2-exit-loop))
7875 ;; Always auto-insert semicolon to follow SpiderMonkey:
7876 ;; It is required by ECMAScript but is ignored by the rest of
7877 ;; world; see bug 238945
7878 (if (js2-match-token js2-SEMI)
7879 (setq end js2-ts-cursor))
7880 (setf (js2-node-len pn) (- end pos))
7881 pn))
7882
7883 (defun js2-parse-for ()
7884 "Parser for for-statement. Last matched token must be js2-FOR.
7885 Parses for, for-in, and for each-in statements."
7886 (let ((for-pos js2-token-beg)
7887 pn
7888 is-for-each
7889 is-for-in
7890 in-pos
7891 each-pos
7892 tmp-pos
7893 init ; Node init is also foo in 'foo in object'
7894 cond ; Node cond is also object in 'foo in object'
7895 incr ; 3rd section of for-loop initializer
7896 body
7897 tt
7898 lp
7899 rp)
7900 (js2-consume-token)
7901 ;; See if this is a for each () instead of just a for ()
7902 (when (js2-match-token js2-NAME)
7903 (if (string= "each" js2-ts-string)
7904 (progn
7905 (setq is-for-each t
7906 each-pos (- js2-token-beg for-pos)) ; relative
7907 (js2-record-face 'font-lock-keyword-face))
7908 (js2-report-error "msg.no.paren.for")))
7909 (if (js2-must-match js2-LP "msg.no.paren.for")
7910 (setq lp (- js2-token-beg for-pos)))
7911 (setq tt (js2-peek-token))
7912 ;; parse init clause
7913 (let ((js2-in-for-init t)) ; set as dynamic variable
7914 (cond
7915 ((= tt js2-SEMI)
7916 (setq init (make-js2-empty-expr-node)))
7917 ((or (= tt js2-VAR) (= tt js2-LET))
7918 (js2-consume-token)
7919 (setq init (js2-parse-variables tt js2-token-beg)))
7920 (t
7921 (setq init (js2-parse-expr)))))
7922 (if (js2-match-token js2-IN)
7923 (setq is-for-in t
7924 in-pos (- js2-token-beg for-pos)
7925 cond (js2-parse-expr)) ; object over which we're iterating
7926 ;; else ordinary for loop - parse cond and incr
7927 (js2-must-match js2-SEMI "msg.no.semi.for")
7928 (setq cond (if (= (js2-peek-token) js2-SEMI)
7929 (make-js2-empty-expr-node) ; no loop condition
7930 (js2-parse-expr)))
7931 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7932 (setq tmp-pos js2-token-end
7933 incr (if (= (js2-peek-token) js2-RP)
7934 (make-js2-empty-expr-node :pos tmp-pos)
7935 (js2-parse-expr))))
7936 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7937 (setq rp (- js2-token-beg for-pos)))
7938 (if (not is-for-in)
7939 (setq pn (make-js2-for-node :init init
7940 :condition cond
7941 :update incr
7942 :lp lp
7943 :rp rp))
7944 ;; cond could be null if 'in obj' got eaten by the init node.
7945 (if (js2-infix-node-p init)
7946 ;; it was (foo in bar) instead of (var foo in bar)
7947 (setq cond (js2-infix-node-right init)
7948 init (js2-infix-node-left init))
7949 (if (and (js2-var-decl-node-p init)
7950 (> (length (js2-var-decl-node-kids init)) 1))
7951 (js2-report-error "msg.mult.index")))
7952 (setq pn (make-js2-for-in-node :iterator init
7953 :object cond
7954 :in-pos in-pos
7955 :foreach-p is-for-each
7956 :each-pos each-pos
7957 :lp lp
7958 :rp rp)))
7959 (unwind-protect
7960 (progn
7961 (js2-enter-loop pn)
7962 ;; We have to parse the body -after- creating the loop node,
7963 ;; so that the loop node appears in the js2-loop-set, allowing
7964 ;; break/continue statements to find the enclosing loop.
7965 (setf body (js2-parse-statement)
7966 (js2-loop-node-body pn) body
7967 (js2-node-pos pn) for-pos
7968 (js2-node-len pn) (- (js2-node-end body) for-pos))
7969 (js2-node-add-children pn init cond incr body))
7970 ;; finally
7971 (js2-exit-loop))
7972 pn))
7973
7974 (defun js2-parse-try ()
7975 "Parser for try-statement. Last matched token must be js2-TRY."
7976 (let ((try-pos js2-token-beg)
7977 try-end
7978 try-block
7979 catch-blocks
7980 finally-block
7981 saw-default-catch
7982 peek
7983 param
7984 catch-cond
7985 catch-node
7986 guard-kwd
7987 catch-pos
7988 finally-pos
7989 pn
7990 block
7991 lp
7992 rp)
7993 (js2-consume-token)
7994 (if (/= (js2-peek-token) js2-LC)
7995 (js2-report-error "msg.no.brace.try"))
7996 (setq try-block (js2-parse-statement)
7997 try-end (js2-node-end try-block)
7998 peek (js2-peek-token))
7999 (cond
8000 ((= peek js2-CATCH)
8001 (while (js2-match-token js2-CATCH)
8002 (setq catch-pos js2-token-beg
8003 guard-kwd nil
8004 catch-cond nil
8005 lp nil
8006 rp nil)
8007 (if saw-default-catch
8008 (js2-report-error "msg.catch.unreachable"))
8009 (if (js2-must-match js2-LP "msg.no.paren.catch")
8010 (setq lp (- js2-token-beg catch-pos)))
8011 (js2-push-scope (make-js2-scope))
8012 (let ((tt (js2-peek-token)))
8013 (cond
8014 ;; destructuring pattern
8015 ;; catch ({ message, file }) { ... }
8016 ((or (= tt js2-LB) (= tt js2-LC))
8017 (setq param
8018 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8019 js2-LET nil)))
8020 ;; simple name
8021 (t
8022 (js2-must-match js2-NAME "msg.bad.catchcond")
8023 (setq param (js2-create-name-node))
8024 (js2-define-symbol js2-LET js2-ts-string param))))
8025 ;; pattern guard
8026 (if (js2-match-token js2-IF)
8027 (setq guard-kwd (- js2-token-beg catch-pos)
8028 catch-cond (js2-parse-expr))
8029 (setq saw-default-catch t))
8030 (if (js2-must-match js2-RP "msg.bad.catchcond")
8031 (setq rp (- js2-token-beg catch-pos)))
8032 (js2-must-match js2-LC "msg.no.brace.catchblock")
8033 (setq block (js2-parse-statements)
8034 try-end (js2-node-end block)
8035 catch-node (make-js2-catch-node :pos catch-pos
8036 :param param
8037 :guard-expr catch-cond
8038 :guard-kwd guard-kwd
8039 :block block
8040 :lp lp
8041 :rp rp))
8042 (js2-pop-scope)
8043 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8044 (setq try-end js2-token-beg))
8045 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8046 (js2-node-len catch-node) (- try-end catch-pos))
8047 (js2-node-add-children catch-node param catch-cond block)
8048 (push catch-node catch-blocks)))
8049 ((/= peek js2-FINALLY)
8050 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8051 (js2-node-pos try-block)
8052 (- (setq try-end (js2-node-end try-block))
8053 (js2-node-pos try-block)))))
8054 (when (js2-match-token js2-FINALLY)
8055 (setq finally-pos js2-token-beg
8056 block (js2-parse-statement)
8057 try-end (js2-node-end block)
8058 finally-block (make-js2-finally-node :pos finally-pos
8059 :len (- try-end finally-pos)
8060 :body block))
8061 (js2-node-add-children finally-block block))
8062 (setq pn (make-js2-try-node :pos try-pos
8063 :len (- try-end try-pos)
8064 :try-block try-block
8065 :finally-block finally-block))
8066 (js2-node-add-children pn try-block finally-block)
8067 ;; push them onto the try-node, which reverses and corrects their order
8068 (dolist (cb catch-blocks)
8069 (js2-node-add-children pn cb)
8070 (push cb (js2-try-node-catch-clauses pn)))
8071 pn))
8072
8073 (defun js2-parse-throw ()
8074 "Parser for throw-statement. Last matched token must be js2-THROW."
8075 (let ((pos js2-token-beg)
8076 expr
8077 pn)
8078 (js2-consume-token)
8079 (if (= (js2-peek-token-or-eol) js2-EOL)
8080 ;; ECMAScript does not allow new lines before throw expression,
8081 ;; see bug 256617
8082 (js2-report-error "msg.bad.throw.eol"))
8083 (setq expr (js2-parse-expr)
8084 pn (make-js2-throw-node :pos pos
8085 :len (- (js2-node-end expr) pos)
8086 :expr expr))
8087 (js2-node-add-children pn expr)
8088 pn))
8089
8090 (defsubst js2-match-jump-label-name (label-name)
8091 "If break/continue specified a label, return that label's labeled stmt.
8092 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8093 does not match an existing label, reports an error and returns nil."
8094 (let ((bundle (cdr (assoc label-name js2-label-set))))
8095 (if (null bundle)
8096 (js2-report-error "msg.undef.label"))
8097 bundle))
8098
8099 (defun js2-parse-break ()
8100 "Parser for break-statement. Last matched token must be js2-BREAK."
8101 (let ((pos js2-token-beg)
8102 (end js2-token-end)
8103 break-target ; statement to break from
8104 break-label ; in "break foo", name-node representing the foo
8105 labels ; matching labeled statement to break to
8106 pn)
8107 (js2-consume-token) ; `break'
8108 (when (eq (js2-peek-token-or-eol) js2-NAME)
8109 (js2-consume-token)
8110 (setq break-label (js2-create-name-node)
8111 end (js2-node-end break-label)
8112 ;; matchJumpLabelName only matches if there is one
8113 labels (js2-match-jump-label-name js2-ts-string)
8114 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8115 (unless (or break-target break-label)
8116 ;; no break target specified - try for innermost enclosing loop/switch
8117 (if (null js2-loop-and-switch-set)
8118 (unless break-label
8119 (js2-report-error "msg.bad.break" nil pos (length "break")))
8120 (setq break-target (car js2-loop-and-switch-set))))
8121 (setq pn (make-js2-break-node :pos pos
8122 :len (- end pos)
8123 :label break-label
8124 :target break-target))
8125 (js2-node-add-children pn break-label) ; but not break-target
8126 pn))
8127
8128 (defun js2-parse-continue ()
8129 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8130 (let ((pos js2-token-beg)
8131 (end js2-token-end)
8132 label ; optional user-specified label, a `js2-name-node'
8133 labels ; current matching labeled stmt, if any
8134 target ; the `js2-loop-node' target of this continue stmt
8135 pn)
8136 (js2-consume-token) ; `continue'
8137 (when (= (js2-peek-token-or-eol) js2-NAME)
8138 (js2-consume-token)
8139 (setq label (js2-create-name-node)
8140 end (js2-node-end label)
8141 ;; matchJumpLabelName only matches if there is one
8142 labels (js2-match-jump-label-name js2-ts-string)))
8143 (cond
8144 ((null labels) ; no current label to go to
8145 (if (null js2-loop-set) ; no loop to continue to
8146 (js2-report-error "msg.continue.outside" nil pos
8147 (length "continue"))
8148 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8149 (t
8150 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8151 (setq target (js2-labeled-stmt-node-stmt labels))
8152 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8153 (setq pn (make-js2-continue-node :pos pos
8154 :len (- end pos)
8155 :label label
8156 :target target))
8157 (js2-node-add-children pn label) ; but not target - it's not our child
8158 pn))
8159
8160 (defun js2-parse-with ()
8161 "Parser for with-statement. Last matched token must be js2-WITH."
8162 (js2-consume-token)
8163 (let ((pos js2-token-beg)
8164 obj body pn lp rp)
8165 (if (js2-must-match js2-LP "msg.no.paren.with")
8166 (setq lp js2-token-beg))
8167 (setq obj (js2-parse-expr))
8168 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8169 (setq rp js2-token-beg))
8170 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8171 (setq body (js2-parse-statement)))
8172 (setq pn (make-js2-with-node :pos pos
8173 :len (- (js2-node-end body) pos)
8174 :object obj
8175 :body body
8176 :lp (js2-relpos lp pos)
8177 :rp (js2-relpos rp pos)))
8178 (js2-node-add-children pn obj body)
8179 pn))
8180
8181 (defun js2-parse-const-var ()
8182 "Parser for var- or const-statement.
8183 Last matched token must be js2-CONST or js2-VAR."
8184 (let ((tt (js2-peek-token))
8185 (pos js2-token-beg)
8186 expr
8187 pn)
8188 (js2-consume-token)
8189 (setq expr (js2-parse-variables tt js2-token-beg)
8190 pn (make-js2-expr-stmt-node :pos pos
8191 :len (- (js2-node-end expr) pos)
8192 :expr expr))
8193 (js2-node-add-children pn expr)
8194 pn))
8195
8196 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8197 (let ((pn (make-js2-expr-stmt-node :pos pos
8198 :len (js2-node-len expr)
8199 :type (if (js2-inside-function)
8200 js2-EXPR_VOID
8201 js2-EXPR_RESULT)
8202 :expr expr)))
8203 (if add-child
8204 (js2-node-add-children pn expr))
8205 pn))
8206
8207 (defun js2-parse-let-stmt ()
8208 "Parser for let-statement. Last matched token must be js2-LET."
8209 (js2-consume-token)
8210 (let ((pos js2-token-beg)
8211 expr
8212 pn)
8213 (if (= (js2-peek-token) js2-LP)
8214 ;; let expression in statement context
8215 (setq expr (js2-parse-let pos 'statement)
8216 pn (js2-wrap-with-expr-stmt pos expr t))
8217 ;; else we're looking at a statement like let x=6, y=7;
8218 (setf expr (js2-parse-variables js2-LET pos)
8219 pn (js2-wrap-with-expr-stmt pos expr t)
8220 (js2-node-type pn) js2-EXPR_RESULT))
8221 pn))
8222
8223 (defun js2-parse-ret-yield ()
8224 (js2-parse-return-or-yield (js2-peek-token) nil))
8225
8226 (defconst js2-parse-return-stmt-enders
8227 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8228
8229 (defsubst js2-now-all-set (before after mask)
8230 "Return whether or not the bits in the mask have changed to all set.
8231 BEFORE is bits before change, AFTER is bits after change, and MASK is
8232 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8233 but not BEFORE."
8234 (and (/= (logand before mask) mask)
8235 (= (logand after mask) mask)))
8236
8237 (defun js2-parse-return-or-yield (tt expr-context)
8238 (let ((pos js2-token-beg)
8239 (end js2-token-end)
8240 (before js2-end-flags)
8241 (inside-function (js2-inside-function))
8242 e
8243 ret
8244 name)
8245 (unless inside-function
8246 (js2-report-error (if (eq tt js2-RETURN)
8247 "msg.bad.return"
8248 "msg.bad.yield")))
8249 (js2-consume-token)
8250 ;; This is ugly, but we don't want to require a semicolon.
8251 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8252 (setq e (js2-parse-expr)
8253 end (js2-node-end e)))
8254 (cond
8255 ((eq tt js2-RETURN)
8256 (js2-set-flag js2-end-flags (if (null e)
8257 js2-end-returns
8258 js2-end-returns-value))
8259 (setq ret (make-js2-return-node :pos pos
8260 :len (- end pos)
8261 :retval e))
8262 (js2-node-add-children ret e)
8263 ;; See if we need a strict mode warning.
8264 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8265 ;; more thorough and accurate than this before/after flag check.
8266 ;; E.g. if there's a finally-block that always returns, we shouldn't
8267 ;; show a warning generated by inconsistent returns in the catch blocks.
8268 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8269 ;; so we know which returns/yields to highlight, and we should get rid of
8270 ;; all the checking in `js2-parse-return-or-yield'.
8271 (if (and js2-strict-inconsistent-return-warning
8272 (js2-now-all-set before js2-end-flags
8273 (logior js2-end-returns js2-end-returns-value)))
8274 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8275 (t
8276 (unless (js2-inside-function)
8277 (js2-report-error "msg.bad.yield"))
8278 (js2-set-flag js2-end-flags js2-end-yields)
8279 (setq ret (make-js2-yield-node :pos pos
8280 :len (- end pos)
8281 :value e))
8282 (js2-node-add-children ret e)
8283 (unless expr-context
8284 (setq e ret
8285 ret (js2-wrap-with-expr-stmt pos e t))
8286 (js2-set-requires-activation)
8287 (js2-set-is-generator))))
8288 ;; see if we are mixing yields and value returns.
8289 (when (and inside-function
8290 (js2-now-all-set before js2-end-flags
8291 (logior js2-end-yields js2-end-returns-value)))
8292 (setq name (js2-function-name js2-current-script-or-fn))
8293 (if (zerop (length name))
8294 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8295 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8296 ret))
8297
8298 (defun js2-parse-debugger ()
8299 (js2-consume-token)
8300 (make-js2-keyword-node :type js2-DEBUGGER))
8301
8302 (defun js2-parse-block ()
8303 "Parser for a curly-delimited statement block.
8304 Last token matched must be js2-LC."
8305 (let ((pos js2-token-beg)
8306 (pn (make-js2-scope)))
8307 (js2-consume-token)
8308 (js2-push-scope pn)
8309 (unwind-protect
8310 (progn
8311 (js2-parse-statements pn)
8312 (js2-must-match js2-RC "msg.no.brace.block")
8313 (setf (js2-node-len pn) (- js2-token-end pos)))
8314 (js2-pop-scope))
8315 pn))
8316
8317 ;; for js2-ERROR too, to have a node for error recovery to work on
8318 (defun js2-parse-semi ()
8319 "Parse a statement or handle an error.
8320 Last matched token is js-SEMI or js-ERROR."
8321 (let ((tt (js2-peek-token)) pos len)
8322 (js2-consume-token)
8323 (if (eq tt js2-SEMI)
8324 (make-js2-empty-expr-node :len 1)
8325 (setq pos js2-token-beg
8326 len (- js2-token-beg pos))
8327 (js2-report-error "msg.syntax" nil pos len)
8328 (make-js2-error-node :pos pos :len len))))
8329
8330 (defun js2-parse-default-xml-namespace ()
8331 "Parse a `default xml namespace = <expr>' e4x statement."
8332 (let ((pos js2-token-beg)
8333 end len expr unary es)
8334 (js2-consume-token)
8335 (js2-must-have-xml)
8336 (js2-set-requires-activation)
8337 (setq len (- js2-ts-cursor pos))
8338 (unless (and (js2-match-token js2-NAME)
8339 (string= js2-ts-string "xml"))
8340 (js2-report-error "msg.bad.namespace" nil pos len))
8341 (unless (and (js2-match-token js2-NAME)
8342 (string= js2-ts-string "namespace"))
8343 (js2-report-error "msg.bad.namespace" nil pos len))
8344 (unless (js2-match-token js2-ASSIGN)
8345 (js2-report-error "msg.bad.namespace" nil pos len))
8346 (setq expr (js2-parse-expr)
8347 end (js2-node-end expr)
8348 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8349 :pos pos
8350 :len (- end pos)
8351 :operand expr))
8352 (js2-node-add-children unary expr)
8353 (make-js2-expr-stmt-node :pos pos
8354 :len (- end pos)
8355 :expr unary)))
8356
8357 (defun js2-record-label (label bundle)
8358 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8359 (js2-consume-token)
8360 (let ((name (js2-label-node-name label))
8361 labeled-stmt
8362 dup)
8363 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8364 ;; flag both labels if possible when used in editing mode
8365 (if (and js2-parse-ide-mode
8366 (setq dup (js2-get-label-by-name labeled-stmt name)))
8367 (js2-report-error "msg.dup.label" nil
8368 (js2-node-abs-pos dup) (js2-node-len dup)))
8369 (js2-report-error "msg.dup.label" nil
8370 (js2-node-pos label) (js2-node-len label)))
8371 (js2-labeled-stmt-node-add-label bundle label)
8372 (js2-node-add-children bundle label)
8373 ;; Add one reference to the bundle per label in `js2-label-set'
8374 (push (cons name bundle) js2-label-set)))
8375
8376 (defun js2-parse-name-or-label ()
8377 "Parser for identifier or label. Last token matched must be js2-NAME.
8378 Called when we found a name in a statement context. If it's a label, we gather
8379 up any following labels and the next non-label statement into a
8380 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8381 expression and return it wrapped in a `js2-expr-stmt-node'."
8382 (let ((pos js2-token-beg)
8383 (end js2-token-end)
8384 expr
8385 stmt
8386 pn
8387 bundle
8388 (continue t))
8389 ;; set check for label and call down to `js2-parse-primary-expr'
8390 (js2-set-check-for-label)
8391 (setq expr (js2-parse-expr))
8392 (if (/= (js2-node-type expr) js2-LABEL)
8393 ;; Parsed non-label expression - wrap with expression stmt.
8394 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8395 ;; else parsed a label
8396 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8397 (js2-record-label expr bundle)
8398 ;; look for more labels
8399 (while (and continue (= (js2-peek-token) js2-NAME))
8400 (js2-set-check-for-label)
8401 (setq expr (js2-parse-expr))
8402 (if (/= (js2-node-type expr) js2-LABEL)
8403 (progn
8404 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8405 continue nil)
8406 (js2-auto-insert-semicolon stmt))
8407 (js2-record-label expr bundle)))
8408 ;; no more labels; now parse the labeled statement
8409 (unwind-protect
8410 (unless stmt
8411 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8412 (setq stmt (js2-statement-helper))))
8413 ;; remove the labels for this statement from the global set
8414 (dolist (label (js2-labeled-stmt-node-labels bundle))
8415 (setq js2-label-set (remove label js2-label-set))))
8416 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8417 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8418 (js2-node-add-children bundle stmt)
8419 bundle)))
8420
8421 (defun js2-parse-expr-stmt ()
8422 "Default parser in statement context, if no recognized statement found."
8423 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8424
8425 (defun js2-parse-variables (decl-type pos)
8426 "Parse a comma-separated list of variable declarations.
8427 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8428
8429 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8430 For 'var' or 'const', the keyword should be the token last scanned.
8431
8432 POS is the position where the node should start. It's sometimes the
8433 var/const/let keyword, and other times the beginning of the first token
8434 in the first variable declaration.
8435
8436 Returns the parsed `js2-var-decl-node' expression node."
8437 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8438 :pos pos))
8439 destructuring
8440 kid-pos
8441 tt
8442 init
8443 name
8444 end
8445 nbeg nend
8446 vi
8447 (continue t))
8448 ;; Example:
8449 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8450 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8451 ;; var {a, b} = baz;
8452 (while continue
8453 (setq destructuring nil
8454 name nil
8455 tt (js2-peek-token)
8456 kid-pos js2-token-beg
8457 end js2-token-end
8458 init nil)
8459 (if (or (= tt js2-LB) (= tt js2-LC))
8460 ;; Destructuring assignment, e.g., var [a, b] = ...
8461 (setq destructuring (js2-parse-primary-expr-lhs)
8462 end (js2-node-end destructuring))
8463 ;; Simple variable name
8464 (when (js2-must-match js2-NAME "msg.bad.var")
8465 (setq name (js2-create-name-node)
8466 nbeg js2-token-beg
8467 nend js2-token-end
8468 end nend)
8469 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8470 (when (js2-match-token js2-ASSIGN)
8471 (setq init (js2-parse-assign-expr)
8472 end (js2-node-end init))
8473 (if (and js2-parse-ide-mode
8474 (or (js2-object-node-p init)
8475 (js2-function-node-p init)))
8476 (js2-record-imenu-functions init name)))
8477 (when name
8478 (js2-set-face nbeg nend (if (js2-function-node-p init)
8479 'font-lock-function-name-face
8480 'font-lock-variable-name-face)
8481 'record))
8482 (setq vi (make-js2-var-init-node :pos kid-pos
8483 :len (- end kid-pos)
8484 :type decl-type))
8485 (if destructuring
8486 (progn
8487 (if (and (null init) (not js2-in-for-init))
8488 (js2-report-error "msg.destruct.assign.no.init"))
8489 (js2-define-destruct-symbols destructuring
8490 decl-type
8491 'font-lock-variable-name-face)
8492 (setf (js2-var-init-node-target vi) destructuring))
8493 (setf (js2-var-init-node-target vi) name))
8494 (setf (js2-var-init-node-initializer vi) init)
8495 (js2-node-add-children vi name destructuring init)
8496 (js2-block-node-push result vi)
8497 (unless (js2-match-token js2-COMMA)
8498 (setq continue nil)))
8499 (setf (js2-node-len result) (- end pos))
8500 result))
8501
8502 (defun js2-parse-let (pos &optional stmt-p)
8503 "Parse a let expression or statement.
8504 A let-expression is of the form `let (vars) expr'.
8505 A let-statment is of the form `let (vars) {statements}'.
8506 The third form of let is a variable declaration list, handled
8507 by `js2-parse-variables'."
8508 (let ((pn (make-js2-let-node :pos pos))
8509 beg vars body)
8510 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8511 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8512 (js2-push-scope pn)
8513 (unwind-protect
8514 (progn
8515 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8516 (if (js2-must-match js2-RP "msg.no.paren.let")
8517 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8518 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8519 ;; let statement
8520 (progn
8521 (js2-consume-token)
8522 (setf beg js2-token-beg ; position stmt at LC
8523 body (js2-parse-statements))
8524 (js2-must-match js2-RC "msg.no.curly.let")
8525 (setf (js2-node-len body) (- js2-token-end beg)
8526 (js2-node-len pn) (- js2-token-end pos)
8527 (js2-let-node-body pn) body
8528 (js2-node-type pn) js2-LET))
8529 ;; let expression
8530 (setf body (js2-parse-expr)
8531 (js2-node-len pn) (- (js2-node-end body) pos)
8532 (js2-let-node-body pn) body))
8533 (js2-node-add-children pn vars body))
8534 (js2-pop-scope))
8535 pn))
8536
8537 (defsubst js2-define-new-symbol (decl-type name node)
8538 (js2-scope-put-symbol js2-current-scope
8539 name
8540 (make-js2-symbol decl-type name node)))
8541
8542 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8543 "Define a symbol in the current scope.
8544 If NODE is non-nil, it is the AST node associated with the symbol."
8545 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8546 (symbol (if defining-scope
8547 (js2-scope-get-symbol defining-scope name)))
8548 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8549 (cond
8550 ((and symbol ; already defined
8551 (or (= sdt js2-CONST) ; old version is const
8552 (= decl-type js2-CONST) ; new version is const
8553 ;; two let-bound vars in this block have same name
8554 (and (= sdt js2-LET)
8555 (eq defining-scope js2-current-scope))))
8556 (js2-report-error
8557 (cond
8558 ((= sdt js2-CONST) "msg.const.redecl")
8559 ((= sdt js2-LET) "msg.let.redecl")
8560 ((= sdt js2-VAR) "msg.var.redecl")
8561 ((= sdt js2-FUNCTION) "msg.function.redecl")
8562 (t "msg.parm.redecl"))
8563 name))
8564 ((= decl-type js2-LET)
8565 (if (and (not ignore-not-in-block)
8566 (or (= (js2-node-type js2-current-scope) js2-IF)
8567 (js2-loop-node-p js2-current-scope)))
8568 (js2-report-error "msg.let.decl.not.in.block")
8569 (js2-define-new-symbol decl-type name node)))
8570 ((or (= decl-type js2-VAR)
8571 (= decl-type js2-CONST)
8572 (= decl-type js2-FUNCTION))
8573 (if symbol
8574 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8575 (js2-add-strict-warning "msg.var.redecl" name)
8576 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8577 (js2-add-strict-warning "msg.var.hides.arg" name)))
8578 (js2-define-new-symbol decl-type name node)))
8579 ((= decl-type js2-LP)
8580 (if symbol
8581 ;; must be duplicate parameter. Second parameter hides the
8582 ;; first, so go ahead and add the second pararameter
8583 (js2-report-warning "msg.dup.parms" name))
8584 (js2-define-new-symbol decl-type name node))
8585 (t (js2-code-bug)))))
8586
8587 (defun js2-parse-expr (&optional oneshot)
8588 (let* ((pn (js2-parse-assign-expr))
8589 (pos (js2-node-pos pn))
8590 left
8591 right
8592 op-pos)
8593 (while (and (not oneshot)
8594 (js2-match-token js2-COMMA))
8595 (setq op-pos (- js2-token-beg pos)) ; relative
8596 (if (= (js2-peek-token) js2-YIELD)
8597 (js2-report-error "msg.yield.parenthesized"))
8598 (setq right (js2-parse-assign-expr)
8599 left pn
8600 pn (make-js2-infix-node :type js2-COMMA
8601 :pos pos
8602 :len (- js2-ts-cursor pos)
8603 :op-pos op-pos
8604 :left left
8605 :right right))
8606 (js2-node-add-children pn left right))
8607 pn))
8608
8609 (defun js2-parse-assign-expr ()
8610 (let ((tt (js2-peek-token))
8611 (pos js2-token-beg)
8612 pn
8613 left
8614 right
8615 op-pos)
8616 (if (= tt js2-YIELD)
8617 (js2-parse-return-or-yield tt t)
8618 ;; not yield - parse assignment expression
8619 (setq pn (js2-parse-cond-expr)
8620 tt (js2-peek-token))
8621 (when (and (<= js2-first-assign tt)
8622 (<= tt js2-last-assign))
8623 ;; tt express assignment (=, |=, ^=, ..., %=)
8624 (js2-consume-token)
8625 (setq op-pos (- js2-token-beg pos) ; relative
8626 left pn
8627 right (js2-parse-assign-expr)
8628 pn (make-js2-assign-node :type tt
8629 :pos pos
8630 :len (- (js2-node-end right) pos)
8631 :op-pos op-pos
8632 :left left
8633 :right right))
8634 (when js2-parse-ide-mode
8635 (js2-highlight-assign-targets pn left right)
8636 (if (or (js2-function-node-p right)
8637 (js2-object-node-p right))
8638 (js2-record-imenu-functions right left)))
8639 ;; do this last so ide checks above can use absolute positions
8640 (js2-node-add-children pn left right))
8641 pn)))
8642
8643 (defun js2-parse-cond-expr ()
8644 (let ((pos js2-token-beg)
8645 (pn (js2-parse-or-expr))
8646 test-expr
8647 if-true
8648 if-false
8649 q-pos
8650 c-pos)
8651 (when (js2-match-token js2-HOOK)
8652 (setq q-pos (- js2-token-beg pos)
8653 if-true (js2-parse-assign-expr))
8654 (js2-must-match js2-COLON "msg.no.colon.cond")
8655 (setq c-pos (- js2-token-beg pos)
8656 if-false (js2-parse-assign-expr)
8657 test-expr pn
8658 pn (make-js2-cond-node :pos pos
8659 :len (- (js2-node-end if-false) pos)
8660 :test-expr test-expr
8661 :true-expr if-true
8662 :false-expr if-false
8663 :q-pos q-pos
8664 :c-pos c-pos))
8665 (js2-node-add-children pn test-expr if-true if-false))
8666 pn))
8667
8668 (defun js2-make-binary (type left parser)
8669 "Helper for constructing a binary-operator AST node.
8670 LEFT is the left-side-expression, already parsed, and the
8671 binary operator should have just been matched.
8672 PARSER is a function to call to parse the right operand,
8673 or a `js2-node' struct if it has already been parsed."
8674 (let* ((pos (js2-node-pos left))
8675 (op-pos (- js2-token-beg pos))
8676 (right (if (js2-node-p parser)
8677 parser
8678 (funcall parser)))
8679 (pn (make-js2-infix-node :type type
8680 :pos pos
8681 :len (- (js2-node-end right) pos)
8682 :op-pos op-pos
8683 :left left
8684 :right right)))
8685 (js2-node-add-children pn left right)
8686 pn))
8687
8688 (defun js2-parse-or-expr ()
8689 (let ((pn (js2-parse-and-expr)))
8690 (when (js2-match-token js2-OR)
8691 (setq pn (js2-make-binary js2-OR
8692 pn
8693 'js2-parse-or-expr)))
8694 pn))
8695
8696 (defun js2-parse-and-expr ()
8697 (let ((pn (js2-parse-bit-or-expr)))
8698 (when (js2-match-token js2-AND)
8699 (setq pn (js2-make-binary js2-AND
8700 pn
8701 'js2-parse-and-expr)))
8702 pn))
8703
8704 (defun js2-parse-bit-or-expr ()
8705 (let ((pn (js2-parse-bit-xor-expr)))
8706 (while (js2-match-token js2-BITOR)
8707 (setq pn (js2-make-binary js2-BITOR
8708 pn
8709 'js2-parse-bit-xor-expr)))
8710 pn))
8711
8712 (defun js2-parse-bit-xor-expr ()
8713 (let ((pn (js2-parse-bit-and-expr)))
8714 (while (js2-match-token js2-BITXOR)
8715 (setq pn (js2-make-binary js2-BITXOR
8716 pn
8717 'js2-parse-bit-and-expr)))
8718 pn))
8719
8720 (defun js2-parse-bit-and-expr ()
8721 (let ((pn (js2-parse-eq-expr)))
8722 (while (js2-match-token js2-BITAND)
8723 (setq pn (js2-make-binary js2-BITAND
8724 pn
8725 'js2-parse-eq-expr)))
8726 pn))
8727
8728 (defconst js2-parse-eq-ops
8729 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8730
8731 (defun js2-parse-eq-expr ()
8732 (let ((pn (js2-parse-rel-expr))
8733 tt)
8734 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8735 (js2-consume-token)
8736 (setq pn (js2-make-binary tt
8737 pn
8738 'js2-parse-rel-expr)))
8739 pn))
8740
8741 (defconst js2-parse-rel-ops
8742 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8743
8744 (defun js2-parse-rel-expr ()
8745 (let ((pn (js2-parse-shift-expr))
8746 (continue t)
8747 tt)
8748 (while continue
8749 (setq tt (js2-peek-token))
8750 (cond
8751 ((and js2-in-for-init (= tt js2-IN))
8752 (setq continue nil))
8753 ((memq tt js2-parse-rel-ops)
8754 (js2-consume-token)
8755 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8756 (t
8757 (setq continue nil))))
8758 pn))
8759
8760 (defconst js2-parse-shift-ops
8761 (list js2-LSH js2-URSH js2-RSH))
8762
8763 (defun js2-parse-shift-expr ()
8764 (let ((pn (js2-parse-add-expr))
8765 tt
8766 (continue t))
8767 (while continue
8768 (setq tt (js2-peek-token))
8769 (if (memq tt js2-parse-shift-ops)
8770 (progn
8771 (js2-consume-token)
8772 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8773 (setq continue nil)))
8774 pn))
8775
8776 (defun js2-parse-add-expr ()
8777 (let ((pn (js2-parse-mul-expr))
8778 tt
8779 (continue t))
8780 (while continue
8781 (setq tt (js2-peek-token))
8782 (if (or (= tt js2-ADD) (= tt js2-SUB))
8783 (progn
8784 (js2-consume-token)
8785 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8786 (setq continue nil)))
8787 pn))
8788
8789 (defconst js2-parse-mul-ops
8790 (list js2-MUL js2-DIV js2-MOD))
8791
8792 (defun js2-parse-mul-expr ()
8793 (let ((pn (js2-parse-unary-expr))
8794 tt
8795 (continue t))
8796 (while continue
8797 (setq tt (js2-peek-token))
8798 (if (memq tt js2-parse-mul-ops)
8799 (progn
8800 (js2-consume-token)
8801 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8802 (setq continue nil)))
8803 pn))
8804
8805 (defsubst js2-make-unary (type parser &rest args)
8806 "Make a unary node of type TYPE.
8807 PARSER is either a node (for postfix operators) or a function to call
8808 to parse the operand (for prefix operators)."
8809 (let* ((pos js2-token-beg)
8810 (postfix (js2-node-p parser))
8811 (expr (if postfix
8812 parser
8813 (apply parser args)))
8814 end
8815 pn)
8816 (if postfix ; e.g. i++
8817 (setq pos (js2-node-pos expr)
8818 end js2-token-end)
8819 (setq end (js2-node-end expr)))
8820 (setq pn (make-js2-unary-node :type type
8821 :pos pos
8822 :len (- end pos)
8823 :operand expr))
8824 (js2-node-add-children pn expr)
8825 pn))
8826
8827 (defconst js2-incrementable-node-types
8828 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8829 "Node types that can be the operand of a ++ or -- operator.")
8830
8831 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8832 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8833 js2-incrementable-node-types)
8834 (js2-report-error (if (= tt js2-INC)
8835 "msg.bad.incr"
8836 "msg.bad.decr")
8837 nil beg (- end beg))))
8838
8839 (defun js2-parse-unary-expr ()
8840 (let ((tt (js2-peek-token))
8841 pn expr beg end)
8842 (cond
8843 ((or (= tt js2-VOID)
8844 (= tt js2-NOT)
8845 (= tt js2-BITNOT)
8846 (= tt js2-TYPEOF))
8847 (js2-consume-token)
8848 (js2-make-unary tt 'js2-parse-unary-expr))
8849 ((= tt js2-ADD)
8850 (js2-consume-token)
8851 ;; Convert to special POS token in decompiler and parse tree
8852 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8853 ((= tt js2-SUB)
8854 (js2-consume-token)
8855 ;; Convert to special NEG token in decompiler and parse tree
8856 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8857 ((or (= tt js2-INC)
8858 (= tt js2-DEC))
8859 (js2-consume-token)
8860 (prog1
8861 (setq beg js2-token-beg
8862 end js2-token-end
8863 expr (js2-make-unary tt 'js2-parse-member-expr t))
8864 (js2-check-bad-inc-dec tt beg end expr)))
8865 ((= tt js2-DELPROP)
8866 (js2-consume-token)
8867 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8868 ((= tt js2-ERROR)
8869 (js2-consume-token)
8870 (make-js2-error-node)) ; try to continue
8871 ((and (= tt js2-LT)
8872 js2-compiler-xml-available)
8873 ;; XML stream encountered in expression.
8874 (js2-consume-token)
8875 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8876 (t
8877 (setq pn (js2-parse-member-expr t)
8878 ;; Don't look across a newline boundary for a postfix incop.
8879 tt (js2-peek-token-or-eol))
8880 (when (or (= tt js2-INC) (= tt js2-DEC))
8881 (js2-consume-token)
8882 (setf expr pn
8883 pn (js2-make-unary tt expr))
8884 (js2-node-set-prop pn 'postfix t)
8885 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8886 pn))))
8887
8888 (defun js2-parse-xml-initializer ()
8889 "Parse an E4X XML initializer.
8890 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8891 Then I'll postprocess the result, depending on whether we're in IDE
8892 mode or codegen mode, and generate the appropriate rewritten AST.
8893 IDE mode uses a rich AST that models the XML structure. Codegen mode
8894 just concatenates everything and makes a new XML or XMLList out of it."
8895 (let ((tt (js2-get-first-xml-token))
8896 pn-xml
8897 pn
8898 expr
8899 kids
8900 expr-pos
8901 (continue t)
8902 (first-token t))
8903 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8904 (js2-report-error "msg.syntax"))
8905 (setq pn-xml (make-js2-xml-node))
8906 (while continue
8907 (if first-token
8908 (setq first-token nil)
8909 (setq tt (js2-get-next-xml-token)))
8910 (cond
8911 ;; js2-XML means we found a {expr} in the XML stream.
8912 ;; The js2-ts-string is the XML up to the left-curly.
8913 ((= tt js2-XML)
8914 (push (make-js2-string-node :pos js2-token-beg
8915 :len (- js2-ts-cursor js2-token-beg))
8916 kids)
8917 (js2-must-match js2-LC "msg.syntax")
8918 (setq expr-pos js2-ts-cursor
8919 expr (if (eq (js2-peek-token) js2-RC)
8920 (make-js2-empty-expr-node :pos expr-pos)
8921 (js2-parse-expr)))
8922 (js2-must-match js2-RC "msg.syntax")
8923 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8924 :len (js2-node-len expr)
8925 :expr expr))
8926 (js2-node-add-children pn expr)
8927 (push pn kids))
8928 ;; a js2-XMLEND token means we hit the final close-tag.
8929 ((= tt js2-XMLEND)
8930 (push (make-js2-string-node :pos js2-token-beg
8931 :len (- js2-ts-cursor js2-token-beg))
8932 kids)
8933 (dolist (kid (nreverse kids))
8934 (js2-block-node-push pn-xml kid))
8935 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8936 (js2-node-pos pn-xml))
8937 continue nil))
8938 (t
8939 (js2-report-error "msg.syntax")
8940 (setq continue nil))))
8941 pn-xml))
8942
8943
8944 (defun js2-parse-argument-list ()
8945 "Parse an argument list and return it as a lisp list of nodes.
8946 Returns the list in reverse order. Consumes the right-paren token."
8947 (let (result)
8948 (unless (js2-match-token js2-RP)
8949 (loop do
8950 (if (= (js2-peek-token) js2-YIELD)
8951 (js2-report-error "msg.yield.parenthesized"))
8952 (push (js2-parse-assign-expr) result)
8953 while
8954 (js2-match-token js2-COMMA))
8955 (js2-must-match js2-RP "msg.no.paren.arg")
8956 result)))
8957
8958 (defun js2-parse-member-expr (&optional allow-call-syntax)
8959 (let ((tt (js2-peek-token))
8960 pn
8961 pos
8962 target
8963 args
8964 beg
8965 end
8966 init
8967 tail)
8968 (if (/= tt js2-NEW)
8969 (setq pn (js2-parse-primary-expr))
8970 ;; parse a 'new' expression
8971 (js2-consume-token)
8972 (setq pos js2-token-beg
8973 beg pos
8974 target (js2-parse-member-expr)
8975 end (js2-node-end target)
8976 pn (make-js2-new-node :pos pos
8977 :target target
8978 :len (- end pos)))
8979 (js2-node-add-children pn target)
8980 (when (js2-match-token js2-LP)
8981 ;; Add the arguments to pn, if any are supplied.
8982 (setf beg pos ; start of "new" keyword
8983 pos js2-token-beg
8984 args (nreverse (js2-parse-argument-list))
8985 (js2-new-node-args pn) args
8986 end js2-token-end
8987 (js2-new-node-lp pn) (- pos beg)
8988 (js2-new-node-rp pn) (- end 1 beg))
8989 (apply #'js2-node-add-children pn args))
8990 (when (and js2-allow-rhino-new-expr-initializer
8991 (js2-match-token js2-LC))
8992 (setf init (js2-parse-object-literal)
8993 end (js2-node-end init)
8994 (js2-new-node-initializer pn) init)
8995 (js2-node-add-children pn init))
8996 (setf (js2-node-len pn) (- end beg))) ; end outer if
8997 (js2-parse-member-expr-tail allow-call-syntax pn)))
8998
8999 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9000 "Parse a chain of property/array accesses or function calls.
9001 Includes parsing for E4X operators like `..' and `.@'.
9002 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9003 Returns an expression tree that includes PN, the parent node."
9004 (let ((beg (js2-node-pos pn))
9005 tt
9006 (continue t))
9007 (while continue
9008 (setq tt (js2-peek-token))
9009 (cond
9010 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9011 (setq pn (js2-parse-property-access tt pn)))
9012 ((= tt js2-DOTQUERY)
9013 (setq pn (js2-parse-dot-query pn)))
9014 ((= tt js2-LB)
9015 (setq pn (js2-parse-element-get pn)))
9016 ((= tt js2-LP)
9017 (if allow-call-syntax
9018 (setq pn (js2-parse-function-call pn))
9019 (setq continue nil)))
9020 (t
9021 (setq continue nil))))
9022 (if (>= js2-highlight-level 2)
9023 (js2-parse-highlight-member-expr-node pn))
9024 pn))
9025
9026 (defun js2-parse-dot-query (pn)
9027 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9028 Last token parsed must be `js2-DOTQUERY'."
9029 (let ((pos (js2-node-pos pn))
9030 op-pos
9031 expr
9032 end)
9033 (js2-consume-token)
9034 (js2-must-have-xml)
9035 (js2-set-requires-activation)
9036 (setq op-pos js2-token-beg
9037 expr (js2-parse-expr)
9038 end (js2-node-end expr)
9039 pn (make-js2-xml-dot-query-node :left pn
9040 :pos pos
9041 :op-pos op-pos
9042 :right expr))
9043 (js2-node-add-children pn
9044 (js2-xml-dot-query-node-left pn)
9045 (js2-xml-dot-query-node-right pn))
9046 (if (js2-must-match js2-RP "msg.no.paren")
9047 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9048 end js2-token-end))
9049 (setf (js2-node-len pn) (- end pos))
9050 pn))
9051
9052 (defun js2-parse-element-get (pn)
9053 "Parse an element-get expression, e.g. foo[bar].
9054 Last token parsed must be `js2-RB'."
9055 (let ((lb js2-token-beg)
9056 (pos (js2-node-pos pn))
9057 rb
9058 expr)
9059 (js2-consume-token)
9060 (setq expr (js2-parse-expr))
9061 (if (js2-must-match js2-RB "msg.no.bracket.index")
9062 (setq rb js2-token-beg))
9063 (setq pn (make-js2-elem-get-node :target pn
9064 :pos pos
9065 :element expr
9066 :lb (js2-relpos lb pos)
9067 :rb (js2-relpos rb pos)
9068 :len (- js2-token-end pos)))
9069 (js2-node-add-children pn
9070 (js2-elem-get-node-target pn)
9071 (js2-elem-get-node-element pn))
9072 pn))
9073
9074 (defun js2-parse-function-call (pn)
9075 (let (args
9076 (pos (js2-node-pos pn)))
9077 (js2-consume-token)
9078 (setq pn (make-js2-call-node :pos pos
9079 :target pn
9080 :lp (- js2-token-beg pos)))
9081 (js2-node-add-children pn (js2-call-node-target pn))
9082 ;; Add the arguments to pn, if any are supplied.
9083 (setf args (nreverse (js2-parse-argument-list))
9084 (js2-call-node-rp pn) (- js2-token-beg pos)
9085 (js2-call-node-args pn) args)
9086 (apply #'js2-node-add-children pn args)
9087 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9088 pn))
9089
9090 (defun js2-parse-property-access (tt pn)
9091 "Parse a property access, XML descendants access, or XML attr access."
9092 (let ((member-type-flags 0)
9093 (dot-pos js2-token-beg)
9094 (dot-len (if (= tt js2-DOTDOT) 2 1))
9095 name
9096 ref ; right side of . or .. operator
9097 result)
9098 (js2-consume-token)
9099 (when (= tt js2-DOTDOT)
9100 (js2-must-have-xml)
9101 (setq member-type-flags js2-descendants-flag))
9102 (if (not js2-compiler-xml-available)
9103 (progn
9104 (js2-must-match-prop-name "msg.no.name.after.dot")
9105 (setq name (js2-create-name-node t js2-GETPROP)
9106 result (make-js2-prop-get-node :left pn
9107 :pos js2-token-beg
9108 :right name
9109 :len (- js2-token-end
9110 js2-token-beg)))
9111 (js2-node-add-children result pn name)
9112 result)
9113 ;; otherwise look for XML operators
9114 (setf result (if (= tt js2-DOT)
9115 (make-js2-prop-get-node)
9116 (make-js2-infix-node :type js2-DOTDOT))
9117 (js2-node-pos result) (js2-node-pos pn)
9118 (js2-infix-node-op-pos result) dot-pos
9119 (js2-infix-node-left result) pn ; do this after setting position
9120 tt (js2-next-token))
9121 (cond
9122 ;; needed for generator.throw()
9123 ((= tt js2-THROW)
9124 (js2-save-name-token-data js2-token-beg "throw")
9125 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9126 ;; handles: name, ns::name, ns::*, ns::[expr]
9127 ((js2-valid-prop-name-token tt)
9128 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9129 ;; handles: *, *::name, *::*, *::[expr]
9130 ((= tt js2-MUL)
9131 (js2-save-name-token-data js2-token-beg "*")
9132 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9133 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9134 ((= tt js2-XMLATTR)
9135 (setq result (js2-parse-attribute-access)))
9136 (t
9137 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9138 (if ref
9139 (setf (js2-node-len result) (- (js2-node-end ref)
9140 (js2-node-pos result))
9141 (js2-infix-node-right result) ref))
9142 (if (js2-infix-node-p result)
9143 (js2-node-add-children result
9144 (js2-infix-node-left result)
9145 (js2-infix-node-right result)))
9146 result)))
9147
9148 (defun js2-parse-attribute-access ()
9149 "Parse an E4X XML attribute expression.
9150 This includes expressions of the forms:
9151
9152 @attr @ns::attr @ns::*
9153 @* @*::attr @*::*
9154 @[expr] @*::[expr] @ns::[expr]
9155
9156 Called if we peeked an '@' token."
9157 (let ((tt (js2-next-token))
9158 (at-pos js2-token-beg))
9159 (cond
9160 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9161 ((js2-valid-prop-name-token tt)
9162 (js2-parse-property-name at-pos js2-ts-string 0))
9163 ;; handles: @*, @*::name, @*::*, @*::[expr]
9164 ((= tt js2-MUL)
9165 (js2-save-name-token-data js2-token-beg "*")
9166 (js2-parse-property-name js2-token-beg "*" 0))
9167 ;; handles @[expr]
9168 ((= tt js2-LB)
9169 (js2-parse-xml-elem-ref at-pos))
9170 (t
9171 (js2-report-error "msg.no.name.after.xmlAttr")
9172 ;; Avoid cascaded errors that happen if we make an error node here.
9173 (js2-save-name-token-data js2-token-beg "")
9174 (js2-parse-property-name js2-token-beg "" 0)))))
9175
9176 (defun js2-parse-property-name (at-pos s member-type-flags)
9177 "Check if :: follows name in which case it becomes qualified name.
9178
9179 AT-POS is a natural number if we just read an '@' token, else nil.
9180 S is the name or string that was matched: an identifier, 'throw' or '*'.
9181 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9182
9183 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9184 operator, or the name is followed by ::. For a plain name, returns a
9185 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9186 (let ((pos (or at-pos js2-token-beg))
9187 colon-pos
9188 (name (js2-create-name-node t js2-current-token))
9189 ns
9190 tt
9191 ref
9192 pn)
9193 (catch 'return
9194 (when (js2-match-token js2-COLONCOLON)
9195 (setq ns name
9196 colon-pos js2-token-beg
9197 tt (js2-next-token))
9198 (cond
9199 ;; handles name::name
9200 ((js2-valid-prop-name-token tt)
9201 (setq name (js2-create-name-node)))
9202 ;; handles name::*
9203 ((= tt js2-MUL)
9204 (js2-save-name-token-data js2-token-beg "*")
9205 (setq name (js2-create-name-node)))
9206 ;; handles name::[expr]
9207 ((= tt js2-LB)
9208 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9209 (t
9210 (js2-report-error "msg.no.name.after.coloncolon"))))
9211 (if (and (null ns) (zerop member-type-flags))
9212 name
9213 (prog1
9214 (setq pn
9215 (make-js2-xml-prop-ref-node :pos pos
9216 :len (- (js2-node-end name) pos)
9217 :at-pos at-pos
9218 :colon-pos colon-pos
9219 :propname name))
9220 (js2-node-add-children pn name))))))
9221
9222 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9223 "Parse the [expr] portion of an xml element reference.
9224 For instance, @[expr], @*::[expr], or ns::[expr]."
9225 (let* ((lb js2-token-beg)
9226 (pos (or at-pos lb))
9227 rb
9228 (expr (js2-parse-expr))
9229 (end (js2-node-end expr))
9230 pn)
9231 (if (js2-must-match js2-RB "msg.no.bracket.index")
9232 (setq rb js2-token-beg
9233 end js2-token-end))
9234 (prog1
9235 (setq pn
9236 (make-js2-xml-elem-ref-node :pos pos
9237 :len (- end pos)
9238 :namespace namespace
9239 :colon-pos colon-pos
9240 :at-pos at-pos
9241 :expr expr
9242 :lb (js2-relpos lb pos)
9243 :rb (js2-relpos rb pos)))
9244 (js2-node-add-children pn namespace expr))))
9245
9246 (defsubst js2-parse-primary-expr-lhs ()
9247 (let ((js2-is-in-lhs t))
9248 (js2-parse-primary-expr)))
9249
9250 (defun js2-parse-primary-expr ()
9251 "Parses a literal (leaf) expression of some sort.
9252 Includes complex literals such as functions, object-literals,
9253 array-literals, array comprehensions and regular expressions."
9254 (let ((tt-flagged (js2-next-flagged-token))
9255 pn ; parent node (usually return value)
9256 tt
9257 px-pos ; paren-expr pos
9258 len
9259 flags ; regexp flags
9260 expr)
9261 (setq tt js2-current-token)
9262 (cond
9263 ((= tt js2-FUNCTION)
9264 (js2-parse-function 'FUNCTION_EXPRESSION))
9265 ((= tt js2-LB)
9266 (js2-parse-array-literal))
9267 ((= tt js2-LC)
9268 (js2-parse-object-literal))
9269 ((= tt js2-LET)
9270 (js2-parse-let js2-token-beg))
9271 ((= tt js2-LP)
9272 (setq px-pos js2-token-beg
9273 expr (js2-parse-expr))
9274 (js2-must-match js2-RP "msg.no.paren")
9275 (setq pn (make-js2-paren-node :pos px-pos
9276 :expr expr
9277 :len (- js2-token-end px-pos)))
9278 (js2-node-add-children pn (js2-paren-node-expr pn))
9279 pn)
9280 ((= tt js2-XMLATTR)
9281 (js2-must-have-xml)
9282 (js2-parse-attribute-access))
9283 ((= tt js2-NAME)
9284 (js2-parse-name tt-flagged tt))
9285 ((= tt js2-NUMBER)
9286 (make-js2-number-node))
9287 ((= tt js2-STRING)
9288 (prog1
9289 (make-js2-string-node)
9290 (js2-record-face 'font-lock-string-face)))
9291 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9292 ;; Got / or /= which in this context means a regexp literal
9293 (setq px-pos js2-token-beg)
9294 (js2-read-regexp tt)
9295 (setq flags js2-ts-regexp-flags
9296 js2-ts-regexp-flags nil)
9297 (prog1
9298 (make-js2-regexp-node :pos px-pos
9299 :len (- js2-ts-cursor px-pos)
9300 :value js2-ts-string
9301 :flags flags)
9302 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9303 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9304 ((or (= tt js2-NULL)
9305 (= tt js2-THIS)
9306 (= tt js2-FALSE)
9307 (= tt js2-TRUE))
9308 (make-js2-keyword-node :type tt))
9309 ((= tt js2-RESERVED)
9310 (js2-report-error "msg.reserved.id")
9311 (make-js2-name-node))
9312 ((= tt js2-ERROR)
9313 ;; the scanner or one of its subroutines reported the error.
9314 (make-js2-error-node))
9315 ((= tt js2-EOF)
9316 (setq px-pos (point-at-bol)
9317 len (- js2-ts-cursor px-pos))
9318 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9319 (make-js2-error-node :pos px-pos :len len))
9320 (t
9321 (js2-report-error "msg.syntax")
9322 (make-js2-error-node)))))
9323
9324 (defun js2-parse-name (tt-flagged tt)
9325 (let ((name js2-ts-string)
9326 (name-pos js2-token-beg)
9327 node)
9328 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9329 (= (js2-peek-token) js2-COLON))
9330 (prog1
9331 ;; Do not consume colon, it is used as unwind indicator
9332 ;; to return to statementHelper.
9333 (make-js2-label-node :pos name-pos
9334 :len (- js2-token-end name-pos)
9335 :name name)
9336 (js2-set-face name-pos
9337 js2-token-end
9338 'font-lock-variable-name-face 'record))
9339 ;; Otherwise not a label, just a name. Unfortunately peeking
9340 ;; the next token to check for a colon has biffed js2-token-beg
9341 ;; and js2-token-end. We store the name's bounds in buffer vars
9342 ;; and `js2-create-name-node' uses them.
9343 (js2-save-name-token-data name-pos name)
9344 (setq node (if js2-compiler-xml-available
9345 (js2-parse-property-name nil name 0)
9346 (js2-create-name-node 'check-activation)))
9347 (if js2-highlight-external-variables
9348 (js2-record-name-node node))
9349 node)))
9350
9351 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9352 (js2-add-strict-warning
9353 msg nil
9354 ;; back up from comma to beginning of line or array/objlit
9355 (max (if elems
9356 (js2-node-pos (car elems))
9357 pos)
9358 (save-excursion
9359 (goto-char comma-pos)
9360 (back-to-indentation)
9361 (point)))
9362 comma-pos))
9363
9364 (defun js2-parse-array-literal ()
9365 (let ((pos js2-token-beg)
9366 (end js2-token-end)
9367 (after-lb-or-comma t)
9368 after-comma
9369 tt
9370 elems
9371 pn
9372 (continue t))
9373 (unless js2-is-in-lhs
9374 (js2-push-scope (make-js2-scope))) ; for array comp
9375 (while continue
9376 (setq tt (js2-peek-token))
9377 (cond
9378 ;; comma
9379 ((= tt js2-COMMA)
9380 (js2-consume-token)
9381 (setq after-comma js2-token-end)
9382 (if (not after-lb-or-comma)
9383 (setq after-lb-or-comma t)
9384 (push nil elems)))
9385 ;; end of array
9386 ((or (= tt js2-RB)
9387 (= tt js2-EOF)) ; prevent infinite loop
9388 (if (= tt js2-EOF)
9389 (js2-report-error "msg.no.bracket.arg" nil pos)
9390 (js2-consume-token))
9391 (setq continue nil
9392 end js2-token-end
9393 pn (make-js2-array-node :pos pos
9394 :len (- js2-ts-cursor pos)
9395 :elems (nreverse elems)))
9396 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9397 (when after-comma
9398 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9399 pos elems after-comma)))
9400 ;; destructuring binding
9401 (js2-is-in-lhs
9402 (push (if (or (= tt js2-LC)
9403 (= tt js2-LB)
9404 (= tt js2-NAME))
9405 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9406 (js2-parse-primary-expr-lhs)
9407 ;; invalid pattern
9408 (js2-consume-token)
9409 (js2-report-error "msg.bad.var")
9410 (make-js2-error-node))
9411 elems)
9412 (setq after-lb-or-comma nil
9413 after-comma nil))
9414 ;; array comp
9415 ((and (>= js2-language-version 170)
9416 (= tt js2-FOR) ; check for array comprehension
9417 (not after-lb-or-comma) ; "for" can't follow a comma
9418 elems ; must have at least 1 element
9419 (not (cdr elems))) ; but no 2nd element
9420 (setf continue nil
9421 pn (js2-parse-array-comprehension (car elems) pos)))
9422
9423 ;; another element
9424 (t
9425 (unless after-lb-or-comma
9426 (js2-report-error "msg.no.bracket.arg"))
9427 (push (js2-parse-assign-expr) elems)
9428 (setq after-lb-or-comma nil
9429 after-comma nil))))
9430 (unless js2-is-in-lhs
9431 (js2-pop-scope))
9432 pn))
9433
9434 (defun js2-parse-array-comprehension (expr pos)
9435 "Parse a JavaScript 1.7 Array Comprehension.
9436 EXPR is the first expression after the opening left-bracket.
9437 POS is the beginning of the LB token preceding EXPR.
9438 We should have just parsed the 'for' keyword before calling this function."
9439 (let (loops
9440 loop
9441 first
9442 prev
9443 filter
9444 if-pos
9445 result)
9446 (while (= (js2-peek-token) js2-FOR)
9447 (let ((prev (car loops))) ; rearrange scope chain
9448 (push (setq loop (js2-parse-array-comp-loop)) loops)
9449 (if prev ; each loop is parent scope to the next one
9450 (setf (js2-scope-parent-scope loop) prev)
9451 ; first loop takes expr scope's parent
9452 (setf (js2-scope-parent-scope (setq first loop))
9453 (js2-scope-parent-scope js2-current-scope)))))
9454 ;; set expr scope's parent to the last loop
9455 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9456 (when (= (js2-peek-token) js2-IF)
9457 (js2-consume-token)
9458 (setq if-pos (- js2-token-beg pos) ; relative
9459 filter (js2-parse-condition)))
9460 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9461 (setq result (make-js2-array-comp-node :pos pos
9462 :len (- js2-ts-cursor pos)
9463 :result expr
9464 :loops (nreverse loops)
9465 :filter (car filter)
9466 :lp (js2-relpos (second filter) pos)
9467 :rp (js2-relpos (third filter) pos)
9468 :if-pos if-pos))
9469 (apply #'js2-node-add-children result expr (car filter)
9470 (js2-array-comp-node-loops result))
9471 (setq js2-current-scope first) ; pop to the first loop
9472 result))
9473
9474 (defun js2-parse-array-comp-loop ()
9475 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9476 Last token peeked should be the initial FOR."
9477 (let ((pos js2-token-beg)
9478 (pn (make-js2-array-comp-loop-node))
9479 tt
9480 iter
9481 obj
9482 foreach-p
9483 in-pos
9484 each-pos
9485 lp
9486 rp)
9487 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9488 (js2-push-scope pn)
9489 (unwind-protect
9490 (progn
9491 (when (js2-match-token js2-NAME)
9492 (if (string= js2-ts-string "each")
9493 (progn
9494 (setq foreach-p t
9495 each-pos (- js2-token-beg pos)) ; relative
9496 (js2-record-face 'font-lock-keyword-face))
9497 (js2-report-error "msg.no.paren.for")))
9498 (if (js2-must-match js2-LP "msg.no.paren.for")
9499 (setq lp (- js2-token-beg pos)))
9500 (setq tt (js2-peek-token))
9501 (cond
9502 ((or (= tt js2-LB)
9503 (= tt js2-LC))
9504 ;; handle destructuring assignment
9505 (setq iter (js2-parse-primary-expr-lhs))
9506 (js2-define-destruct-symbols iter js2-LET
9507 'font-lock-variable-name-face t))
9508 ((js2-valid-prop-name-token tt)
9509 (js2-consume-token)
9510 (setq iter (js2-create-name-node)))
9511 (t
9512 (js2-report-error "msg.bad.var")))
9513 ;; Define as a let since we want the scope of the variable to
9514 ;; be restricted to the array comprehension
9515 (if (js2-name-node-p iter)
9516 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9517 (if (js2-must-match js2-IN "msg.in.after.for.name")
9518 (setq in-pos (- js2-token-beg pos)))
9519 (setq obj (js2-parse-expr))
9520 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9521 (setq rp (- js2-token-beg pos)))
9522 (setf (js2-node-pos pn) pos
9523 (js2-node-len pn) (- js2-ts-cursor pos)
9524 (js2-array-comp-loop-node-iterator pn) iter
9525 (js2-array-comp-loop-node-object pn) obj
9526 (js2-array-comp-loop-node-in-pos pn) in-pos
9527 (js2-array-comp-loop-node-each-pos pn) each-pos
9528 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9529 (js2-array-comp-loop-node-lp pn) lp
9530 (js2-array-comp-loop-node-rp pn) rp)
9531 (js2-node-add-children pn iter obj))
9532 (js2-pop-scope))
9533 pn))
9534
9535 (defun js2-parse-object-literal ()
9536 (let ((pos js2-token-beg)
9537 tt
9538 elems
9539 result
9540 after-comma
9541 (continue t))
9542 (while continue
9543 (setq tt (js2-peek-token))
9544 (cond
9545 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9546 ((or (js2-valid-prop-name-token tt)
9547 (= tt js2-STRING))
9548 (setq after-comma nil
9549 result (js2-parse-named-prop tt))
9550 (if (and (null result)
9551 (not js2-recover-from-parse-errors))
9552 (setq continue nil)
9553 (push result elems)))
9554 ;; {12: x} or {10.7: x}
9555 ((= tt js2-NUMBER)
9556 (js2-consume-token)
9557 (setq after-comma nil)
9558 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9559 ;; trailing comma
9560 ((= tt js2-RC)
9561 (setq continue nil)
9562 (if after-comma
9563 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9564 pos elems after-comma)))
9565 (t
9566 (js2-report-error "msg.bad.prop")
9567 (unless js2-recover-from-parse-errors
9568 (setq continue nil)))) ; end switch
9569 (if (js2-match-token js2-COMMA)
9570 (setq after-comma js2-token-end)
9571 (setq continue nil))) ; end loop
9572 (js2-must-match js2-RC "msg.no.brace.prop")
9573 (setq result (make-js2-object-node :pos pos
9574 :len (- js2-ts-cursor pos)
9575 :elems (nreverse elems)))
9576 (apply #'js2-node-add-children result (js2-object-node-elems result))
9577 result))
9578
9579 (defun js2-parse-named-prop (tt)
9580 "Parse a name, string, or getter/setter object property.
9581 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9582 (js2-consume-token)
9583 (let ((string-prop (and (= tt js2-STRING)
9584 (make-js2-string-node)))
9585 expr
9586 (ppos js2-token-beg)
9587 (pend js2-token-end)
9588 (name (js2-create-name-node))
9589 (prop js2-ts-string))
9590 (cond
9591 ;; getter/setter prop
9592 ((and (= tt js2-NAME)
9593 (= (js2-peek-token) js2-NAME)
9594 (or (string= prop "get")
9595 (string= prop "set")))
9596 (js2-consume-token)
9597 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9598 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9599 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9600 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9601 ;; abbreviated destructuring bind e.g., {a, b} = c;
9602 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9603 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9604 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9605 ;; assignment but it's difficult because it requires looking ahead of expression.
9606 ((and js2-is-in-lhs
9607 (= tt js2-NAME)
9608 (let ((ctk (js2-peek-token)))
9609 (or (= ctk js2-COMMA)
9610 (= ctk js2-RC)
9611 (js2-valid-prop-name-token ctk))))
9612 name)
9613 ;; regular prop
9614 (t
9615 (prog1
9616 (setq expr (js2-parse-plain-property (or string-prop name)))
9617 (js2-set-face ppos pend
9618 (if (js2-function-node-p
9619 (js2-object-prop-node-right expr))
9620 'font-lock-function-name-face
9621 'font-lock-variable-name-face)
9622 'record))))))
9623
9624 (defun js2-parse-plain-property (prop)
9625 "Parse a non-getter/setter property in an object literal.
9626 PROP is the node representing the property: a number, name or string."
9627 (js2-must-match js2-COLON "msg.no.colon.prop")
9628 (let* ((pos (js2-node-pos prop))
9629 (colon (- js2-token-beg pos))
9630 (expr (js2-parse-assign-expr))
9631 (result (make-js2-object-prop-node
9632 :pos pos
9633 ;; don't include last consumed token in length
9634 :len (- (+ (js2-node-pos expr)
9635 (js2-node-len expr))
9636 pos)
9637 :left prop
9638 :right expr
9639 :op-pos colon)))
9640 (js2-node-add-children result prop expr)
9641 result))
9642
9643 (defun js2-parse-getter-setter-prop (pos prop get-p)
9644 "Parse getter or setter property in an object literal.
9645 JavaScript syntax is:
9646
9647 { get foo() {...}, set foo(x) {...} }
9648
9649 and expression closure style is also supported
9650
9651 { get foo() x, set foo(x) _x = x }
9652
9653 POS is the start position of the `get' or `set' keyword.
9654 PROP is the `js2-name-node' representing the property name.
9655 GET-P is non-nil if the keyword was `get'."
9656 (let ((type (if get-p js2-GET js2-SET))
9657 result
9658 end
9659 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9660 ;; it has to be an anonymous function, as we already parsed the name
9661 (if (/= (js2-node-type fn) js2-FUNCTION)
9662 (js2-report-error "msg.bad.prop")
9663 (if (plusp (length (js2-function-name fn)))
9664 (js2-report-error "msg.bad.prop")))
9665 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9666 (setq end (js2-node-end fn)
9667 result (make-js2-getter-setter-node :type type
9668 :pos pos
9669 :len (- end pos)
9670 :left prop
9671 :right fn))
9672 (js2-node-add-children result prop fn)
9673 result))
9674
9675 (defun js2-create-name-node (&optional check-activation-p token)
9676 "Create a name node using the token info from last scanned name.
9677 In some cases we need to either synthesize a name node, or we lost
9678 the name token information by peeking. If the TOKEN parameter is
9679 not `js2-NAME', then we use the token info saved in instance vars."
9680 (let ((beg js2-token-beg)
9681 (s js2-ts-string)
9682 name)
9683 (when (/= js2-current-token js2-NAME)
9684 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9685 s js2-prev-name-token-string
9686 js2-prev-name-token-start nil
9687 js2-prev-name-token-string nil))
9688 (setq name (make-js2-name-node :pos beg
9689 :name s
9690 :len (length s)))
9691 (if check-activation-p
9692 (js2-check-activation-name s (or token js2-NAME)))
9693 name))
9694
9695 ;;; Indentation support
9696
9697 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9698 ;; Karl cleverly deduces that the desired indentation level is often a
9699 ;; function of paren/bracket/brace nesting depth, which can be determined
9700 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9701 ;; then does some equally clever checks to see if we're in the context of a
9702 ;; substatement of a possibly braceless statement keyword such as if, while,
9703 ;; or finally. This approach yields pretty good results.
9704
9705 ;; The indenter is often "wrong", however, and needs to be overridden.
9706 ;; The right long-term solution is probably to emulate (or integrate
9707 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9708 ;; parse tree from `js2-parse' is present, which is not true at the
9709 ;; moment the user is typing, computing indentation is still thousands
9710 ;; of lines of code to handle every possible syntactic edge case.
9711
9712 ;; In the meantime, the compromise solution is that we offer a "bounce
9713 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9714 ;; current line indent among various likely guess points. This approach
9715 ;; is far from perfect, but should at least make it slightly easier to
9716 ;; move the line towards its desired indentation when manually
9717 ;; overriding Karl's heuristic nesting guesser.
9718
9719 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9720 ;; extensions such as `let' and Array comprehensions. Major kudos to
9721 ;; Karl for coming up with the initial approach, which packs a lot of
9722 ;; punch for so little code.
9723
9724 (defconst js-possibly-braceless-keyword-re
9725 (regexp-opt
9726 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9727 'words)
9728 "Regular expression matching keywords that are optionally
9729 followed by an opening brace.")
9730
9731 (defconst js-possibly-braceless-keywords-re
9732 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9733 "Regular expression which matches the keywords which are consist of more than 2 words
9734 like 'if else' and 'for each', and optionally followed by an opening brace.")
9735
9736 (defconst js-indent-operator-re
9737 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9738 (regexp-opt '("in" "instanceof") 'words))
9739 "Regular expression matching operators that affect indentation
9740 of continued expressions.")
9741
9742 ;; This function has horrible results if you're typing an array
9743 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9744 ;; in conjunction with electric-indent, so just disabling it.
9745 (defsubst js2-code-at-bol-p ()
9746 "Return t if the first character on line is non-whitespace."
9747 nil)
9748
9749 (defun js2-insert-and-indent (key)
9750 "Run command bound to key and indent current line. Runs the command
9751 bound to KEY in the global keymap and indents the current line."
9752 (interactive (list (this-command-keys)))
9753 (let ((cmd (lookup-key (current-global-map) key)))
9754 (if (commandp cmd)
9755 (call-interactively cmd)))
9756 ;; don't do the electric keys inside comments or strings,
9757 ;; and don't do bounce-indent with them.
9758 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9759 (js2-bounce-indent-p (js2-code-at-bol-p)))
9760 (unless (or (nth 3 parse-state)
9761 (nth 4 parse-state))
9762 (indent-according-to-mode))))
9763
9764 (defun js-re-search-forward-inner (regexp &optional bound count)
9765 "Auxiliary function for `js-re-search-forward'."
9766 (let ((parse)
9767 (saved-point (point-min)))
9768 (while (> count 0)
9769 (re-search-forward regexp bound)
9770 (setq parse (parse-partial-sexp saved-point (point)))
9771 (cond ((nth 3 parse)
9772 (re-search-forward
9773 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9774 (save-excursion (end-of-line) (point)) t))
9775 ((nth 7 parse)
9776 (forward-line))
9777 ((or (nth 4 parse)
9778 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9779 (re-search-forward "\\*/"))
9780 (t
9781 (setq count (1- count))))
9782 (setq saved-point (point))))
9783 (point))
9784
9785 (defun js-re-search-forward (regexp &optional bound noerror count)
9786 "Search forward but ignore strings and comments. Invokes
9787 `re-search-forward' but treats the buffer as if strings and
9788 comments have been removed."
9789 (let ((saved-point (point))
9790 (search-expr
9791 (cond ((null count)
9792 '(js-re-search-forward-inner regexp bound 1))
9793 ((< count 0)
9794 '(js-re-search-backward-inner regexp bound (- count)))
9795 ((> count 0)
9796 '(js-re-search-forward-inner regexp bound count)))))
9797 (condition-case err
9798 (eval search-expr)
9799 (search-failed
9800 (goto-char saved-point)
9801 (unless noerror
9802 (error (error-message-string err)))))))
9803
9804 (defun js-re-search-backward-inner (regexp &optional bound count)
9805 "Auxiliary function for `js-re-search-backward'."
9806 (let ((parse)
9807 (saved-point (point-min)))
9808 (while (> count 0)
9809 (re-search-backward regexp bound)
9810 (setq parse (parse-partial-sexp saved-point (point)))
9811 (cond ((nth 3 parse)
9812 (re-search-backward
9813 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9814 (save-excursion (beginning-of-line) (point)) t))
9815 ((nth 7 parse)
9816 (goto-char (nth 8 parse)))
9817 ((or (nth 4 parse)
9818 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9819 (re-search-backward "/\\*"))
9820 (t
9821 (setq count (1- count))))))
9822 (point))
9823
9824 (defun js-re-search-backward (regexp &optional bound noerror count)
9825 "Search backward but ignore strings and comments. Invokes
9826 `re-search-backward' but treats the buffer as if strings and
9827 comments have been removed."
9828 (let ((saved-point (point))
9829 (search-expr
9830 (cond ((null count)
9831 '(js-re-search-backward-inner regexp bound 1))
9832 ((< count 0)
9833 '(js-re-search-forward-inner regexp bound (- count)))
9834 ((> count 0)
9835 '(js-re-search-backward-inner regexp bound count)))))
9836 (condition-case err
9837 (eval search-expr)
9838 (search-failed
9839 (goto-char saved-point)
9840 (unless noerror
9841 (error (error-message-string err)))))))
9842
9843 (defun js-looking-at-operator-p ()
9844 "Return non-nil if text after point is an operator (that is not
9845 a comma)."
9846 (save-match-data
9847 (and (looking-at js-indent-operator-re)
9848 (or (not (looking-at ":"))
9849 (save-excursion
9850 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9851 (looking-at "?")))))))
9852
9853 (defun js-continued-expression-p ()
9854 "Returns non-nil if the current line continues an expression."
9855 (save-excursion
9856 (back-to-indentation)
9857 (or (js-looking-at-operator-p)
9858 ;; comment
9859 (and (js-re-search-backward "\n" nil t)
9860 (progn
9861 (skip-chars-backward " \t")
9862 (backward-char)
9863 (and (js-looking-at-operator-p)
9864 (and (progn (backward-char)
9865 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9866
9867 (defun js-end-of-do-while-loop-p ()
9868 "Returns non-nil if word after point is `while' of a do-while
9869 statement, else returns nil. A braceless do-while statement
9870 spanning several lines requires that the start of the loop is
9871 indented to the same column as the current line."
9872 (interactive)
9873 (save-excursion
9874 (save-match-data
9875 (when (looking-at "\\s-*\\<while\\>")
9876 (if (save-excursion
9877 (skip-chars-backward "[ \t\n]*}")
9878 (looking-at "[ \t\n]*}"))
9879 (save-excursion
9880 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9881 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9882 (or (looking-at "\\<do\\>")
9883 (let ((saved-indent (current-indentation)))
9884 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9885 (/= (current-indentation) saved-indent)))
9886 (and (looking-at "[ \t]*\\<do\\>")
9887 (not (js-re-search-forward
9888 "\\<while\\>" (point-at-eol) t))
9889 (= (current-indentation) saved-indent)))))))))
9890
9891 (defun js-get-multiline-declaration-offset ()
9892 "Returns offset (> 0) if the current line is part of
9893 multi-line variable declaration like below example, and
9894 returns 0 otherwise.
9895
9896 var a = 10,
9897 b = 20,
9898 c = 30;
9899
9900 "
9901 (let* ((node (js2-node-at-point))
9902 (pnode (and node (js2-node-parent node)))
9903 (pnode-type (and pnode (js2-node-type pnode))))
9904 (if (and node
9905 (= js2-NAME (js2-node-type node))
9906 (or
9907 (= js2-VAR pnode-type)
9908 (= js2-LET pnode-type)
9909 (= js2-CONST pnode-type)))
9910 (if (= js2-CONST pnode-type)
9911 6
9912 4)
9913 0)))
9914
9915 (defun js-ctrl-statement-indentation ()
9916 "Returns the proper indentation of the current line if it
9917 starts the body of a control statement without braces, else
9918 returns nil."
9919 (let (forward-sexp-function) ; temporarily unbind it
9920 (save-excursion
9921 (back-to-indentation)
9922 (when (save-excursion
9923 (and (not (js2-same-line (point-min)))
9924 (not (looking-at "{"))
9925 (js-re-search-backward "[[:graph:]]" nil t)
9926 (not (looking-at "[{([]"))
9927 (progn
9928 (forward-char)
9929 ;; scan-sexps sometimes throws an error
9930 (ignore-errors (backward-sexp))
9931 (when (looking-at "(") (backward-word 1))
9932 (and (save-excursion
9933 (skip-chars-backward " \t}" (point-at-bol))
9934 (or (bolp)
9935 (and (backward-word 1)
9936 (skip-chars-backward " \t}" (point-at-bol))
9937 (bolp)
9938 (looking-at js-possibly-braceless-keywords-re))))
9939 (looking-at js-possibly-braceless-keyword-re)
9940 (not (js-end-of-do-while-loop-p))))))
9941 (save-excursion
9942 (goto-char (match-beginning 0))
9943 (+ (current-indentation) js2-basic-offset))))))
9944
9945 (defun js2-indent-in-array-comp (parse-status)
9946 "Return non-nil if we think we're in an array comprehension.
9947 In particular, return the buffer position of the first `for' kwd."
9948 (let ((end (point)))
9949 (when (nth 1 parse-status)
9950 (save-excursion
9951 (goto-char (nth 1 parse-status))
9952 (when (looking-at "\\[")
9953 (forward-char 1)
9954 (js2-forward-sws)
9955 (if (looking-at "[[{]")
9956 (let (forward-sexp-function) ; use lisp version
9957 (forward-sexp) ; skip destructuring form
9958 (js2-forward-sws)
9959 (if (and (/= (char-after) ?,) ; regular array
9960 (looking-at "for"))
9961 (match-beginning 0)))
9962 ;; to skip arbitrary expressions we need the parser,
9963 ;; so we'll just guess at it.
9964 (if (re-search-forward "[^,]* \\(for\\) " end t)
9965 (match-beginning 1))))))))
9966
9967 (defun js2-array-comp-indentation (parse-status for-kwd)
9968 (if (js2-same-line for-kwd)
9969 ;; first continuation line
9970 (save-excursion
9971 (goto-char (nth 1 parse-status))
9972 (forward-char 1)
9973 (skip-chars-forward " \t")
9974 (current-column))
9975 (save-excursion
9976 (goto-char for-kwd)
9977 (current-column))))
9978
9979 (defun js-proper-indentation (parse-status)
9980 "Return the proper indentation for the current line."
9981 (save-excursion
9982 (back-to-indentation)
9983 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9984 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9985 (continued-expr-p (js-continued-expression-p))
9986 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9987 (js-get-multiline-declaration-offset))
9988 0))
9989 (bracket (nth 1 parse-status))
9990 beg)
9991 (cond
9992 ;; indent array comprehension continuation lines specially
9993 ((and bracket
9994 (not (js2-same-line bracket))
9995 (setq beg (js2-indent-in-array-comp parse-status))
9996 (>= (point) (save-excursion
9997 (goto-char beg)
9998 (point-at-bol)))) ; at or after first loop?
9999 (js2-array-comp-indentation parse-status beg))
10000
10001 (ctrl-stmt-indent)
10002
10003 (bracket
10004 (goto-char bracket)
10005 (cond
10006 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10007 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10008 (when (save-excursion (skip-chars-backward " \t)")
10009 (looking-at ")"))
10010 (backward-list))
10011 (if (and (nth 1 p)
10012 (not js2-consistent-level-indent-inner-bracket-p))
10013 (progn (goto-char (1+ (nth 1 p)))
10014 (skip-chars-forward " \t"))
10015 (back-to-indentation))
10016 (cond (same-indent-p
10017 (current-column))
10018 (continued-expr-p
10019 (+ (current-column) (* 2 js2-basic-offset)))
10020 ((> multiline-declaration-offset 0)
10021 (+ (current-column) js2-basic-offset multiline-declaration-offset))
10022 (t
10023 (+ (current-column) js2-basic-offset)))))
10024 (t
10025 (unless same-indent-p
10026 (forward-char)
10027 (skip-chars-forward " \t"))
10028 (current-column))))
10029
10030 (continued-expr-p js2-basic-offset)
10031
10032 ((> multiline-declaration-offset 0)
10033 (+ multiline-declaration-offset))
10034
10035 (t 0)))))
10036
10037 (defun js2-lineup-comment (parse-status)
10038 "Indent a multi-line block comment continuation line."
10039 (let* ((beg (nth 8 parse-status))
10040 (first-line (js2-same-line beg))
10041 (offset (save-excursion
10042 (goto-char beg)
10043 (if (looking-at "/\\*")
10044 (+ 1 (current-column))
10045 0))))
10046 (unless first-line
10047 (indent-line-to offset))))
10048
10049 (defun js2-backward-sws ()
10050 "Move backward through whitespace and comments."
10051 (interactive)
10052 (while (forward-comment -1)))
10053
10054 (defun js2-forward-sws ()
10055 "Move forward through whitespace and comments."
10056 (interactive)
10057 (while (forward-comment 1)))
10058
10059 (defsubst js2-current-indent (&optional pos)
10060 "Return column of indentation on current line.
10061 If POS is non-nil, go to that point and return indentation for that line."
10062 (save-excursion
10063 (if pos
10064 (goto-char pos))
10065 (back-to-indentation)
10066 (current-column)))
10067
10068 (defsubst js2-arglist-close ()
10069 "Return non-nil if we're on a line beginning with a close-paren/brace."
10070 (save-match-data
10071 (save-excursion
10072 (goto-char (point-at-bol))
10073 (js2-forward-sws)
10074 (looking-at "[])}]"))))
10075
10076 (defsubst js2-indent-looks-like-label-p ()
10077 (goto-char (point-at-bol))
10078 (js2-forward-sws)
10079 (looking-at (concat js2-mode-identifier-re ":")))
10080
10081 (defun js2-indent-in-objlit-p (parse-status)
10082 "Return non-nil if this looks like an object-literal entry."
10083 (let ((start (nth 1 parse-status)))
10084 (and
10085 start
10086 (save-excursion
10087 (and (zerop (forward-line -1))
10088 (not (< (point) start)) ; crossed a {} boundary
10089 (js2-indent-looks-like-label-p)))
10090 (save-excursion
10091 (js2-indent-looks-like-label-p)))))
10092
10093 ;; if prev line looks like foobar({ then we're passing an object
10094 ;; literal to a function call, and people pretty much always want to
10095 ;; de-dent back to the previous line, so move the 'basic-offset'
10096 ;; position to the front.
10097 (defsubst js2-indent-objlit-arg-p (parse-status)
10098 (save-excursion
10099 (back-to-indentation)
10100 (js2-backward-sws)
10101 (and (eq (1- (point)) (nth 1 parse-status))
10102 (eq (char-before) ?{)
10103 (progn
10104 (forward-char -1)
10105 (skip-chars-backward " \t")
10106 (eq (char-before) ?\()))))
10107
10108 (defsubst js2-indent-case-block-p ()
10109 (save-excursion
10110 (back-to-indentation)
10111 (js2-backward-sws)
10112 (goto-char (point-at-bol))
10113 (skip-chars-forward " \t")
10114 (save-match-data
10115 (looking-at "case\\s-.+:"))))
10116
10117 (defsubst js2-syntax-bol ()
10118 "Return the point at the first non-whitespace char on the line.
10119 Returns `point-at-bol' if the line is empty."
10120 (save-excursion
10121 (beginning-of-line)
10122 (skip-chars-forward " \t")
10123 (point)))
10124
10125 (defun js2-bounce-indent (normal-col parse-status)
10126 "Cycle among alternate computed indentation positions.
10127 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10128 of the buffer to the current point. NORMAL-COL is the indentation
10129 column computed by the heuristic guesser based on current paren,
10130 bracket, brace and statement nesting."
10131 (let ((cur-indent (js2-current-indent))
10132 (old-buffer-undo-list buffer-undo-list)
10133 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10134 (current-line (save-excursion
10135 (forward-line 0) ; move to bol
10136 (1+ (count-lines (point-min) (point)))))
10137 positions
10138 pos
10139 anchor
10140 arglist-cont
10141 same-indent
10142 prev-line-col
10143 basic-offset
10144 computed-pos)
10145 ;; temporarily don't record undo info, if user requested this
10146 (if js2-mode-indent-inhibit-undo
10147 (setq buffer-undo-list t))
10148 (unwind-protect
10149 (progn
10150 ;; first likely point: indent from beginning of previous code line
10151 (push (setq basic-offset
10152 (+ (save-excursion
10153 (back-to-indentation)
10154 (js2-backward-sws)
10155 (back-to-indentation)
10156 (setq prev-line-col (current-column)))
10157 js2-basic-offset))
10158 positions)
10159
10160 ;; (first + epsilon) likely point: indent 2x from beginning of
10161 ;; previous code line. Some companies like this approach. Ahem.
10162 ;; Seriously, though -- 4-space indent for expression continuation
10163 ;; lines isn't a bad idea. We should eventually implement it
10164 ;; that way.
10165 (push (setq basic-offset
10166 (+ (save-excursion
10167 (back-to-indentation)
10168 (js2-backward-sws)
10169 (back-to-indentation)
10170 (setq prev-line-col (current-column)))
10171 (* 2 js2-basic-offset)))
10172 positions)
10173
10174 ;; second likely point: indent from assign-expr RHS. This
10175 ;; is just a crude guess based on finding " = " on the previous
10176 ;; line containing actual code.
10177 (setq pos (save-excursion
10178 (save-match-data
10179 (forward-line -1)
10180 (goto-char (point-at-bol))
10181 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10182 (point-at-eol) t)
10183 (goto-char (match-end 1))
10184 (skip-chars-forward " \t\r\n")
10185 (current-column)))))
10186 (when pos
10187 (incf pos js2-basic-offset)
10188 (unless (member pos positions)
10189 (push pos positions)))
10190
10191 ;; third likely point: same indent as previous line of code.
10192 ;; Make it the first likely point if we're not on an
10193 ;; arglist-close line and previous line ends in a comma, or
10194 ;; both this line and prev line look like object-literal
10195 ;; elements.
10196 (setq pos (save-excursion
10197 (goto-char (point-at-bol))
10198 (js2-backward-sws)
10199 (back-to-indentation)
10200 (prog1
10201 (current-column)
10202 ;; while we're here, look for trailing comma
10203 (if (save-excursion
10204 (goto-char (point-at-eol))
10205 (js2-backward-sws)
10206 (eq (char-before) ?,))
10207 (setq arglist-cont (1- (point)))))))
10208 (when pos
10209 (if (and (or arglist-cont
10210 (js2-indent-in-objlit-p parse-status))
10211 (not (js2-arglist-close)))
10212 (setq same-indent pos))
10213 (unless (member pos positions)
10214 (push pos positions)))
10215
10216 ;; fourth likely point: first preceding code with less indentation
10217 ;; than the immediately preceding code line.
10218 (setq pos (save-excursion
10219 (js2-backward-sws)
10220 (back-to-indentation)
10221 (setq anchor (current-column))
10222 (while (and (zerop (forward-line -1))
10223 (>= (progn
10224 (back-to-indentation)
10225 (current-column))
10226 anchor)))
10227 (setq pos (current-column))))
10228 (unless (member pos positions)
10229 (push pos positions))
10230
10231 ;; put nesting-heuristic position first in list, sort rest
10232 (setq positions (nreverse (sort positions '<)))
10233 (setq positions (cons normal-col (delete normal-col positions)))
10234
10235 ;; comma-list continuation lines: prev line indent takes precedence
10236 (if same-indent
10237 (setq positions
10238 (cons same-indent
10239 (sort (delete same-indent positions) '<))))
10240
10241 ;; common special cases where we want to indent in from previous line
10242 (if (or (js2-indent-case-block-p)
10243 (js2-indent-objlit-arg-p parse-status))
10244 (setq positions
10245 (cons basic-offset
10246 (delete basic-offset positions))))
10247
10248 ;; record whether we're already sitting on one of the alternatives
10249 (setq pos (member cur-indent positions))
10250 (cond
10251 ;; case 0: we're one one of the alternatives and this is the
10252 ;; first time they've pressed TAB on this line (best-guess).
10253 ((and js2-mode-indent-ignore-first-tab
10254 pos
10255 ;; first time pressing TAB on this line?
10256 (not (eq js2-mode-last-indented-line current-line)))
10257 ;; do nothing
10258 (setq computed-pos nil))
10259 ;; case 1: only one computed position => use it
10260 ((null (cdr positions))
10261 (setq computed-pos 0))
10262 ;; case 2: not on any of the computed spots => use main spot
10263 ((not pos)
10264 (setq computed-pos 0))
10265 ;; case 3: on last position: cycle to first position
10266 ((null (cdr pos))
10267 (setq computed-pos 0))
10268 ;; case 4: on intermediate position: cycle to next position
10269 (t
10270 (setq computed-pos (js2-position (second pos) positions))))
10271
10272 ;; see if any hooks want to indent; otherwise we do it
10273 (loop with result = nil
10274 for hook in js2-indent-hook
10275 while (null result)
10276 do
10277 (setq result (funcall hook positions computed-pos))
10278 finally do
10279 (unless (or result (null computed-pos))
10280 (indent-line-to (nth computed-pos positions)))))
10281
10282 ;; finally
10283 (if js2-mode-indent-inhibit-undo
10284 (setq buffer-undo-list old-buffer-undo-list))
10285 ;; see commentary for `js2-mode-last-indented-line'
10286 (setq js2-mode-last-indented-line current-line))))
10287
10288 (defsubst js2-1-line-comment-continuation-p ()
10289 "Return t if we're in a 1-line comment continuation.
10290 If so, we don't ever want to use bounce-indent."
10291 (save-excursion
10292 (save-match-data
10293 (and (progn
10294 (forward-line 0)
10295 (looking-at "\\s-*//"))
10296 (progn
10297 (forward-line -1)
10298 (forward-line 0)
10299 (when (looking-at "\\s-*$")
10300 (js2-backward-sws)
10301 (forward-line 0))
10302 (looking-at "\\s-*//"))))))
10303
10304 (defun js2-indent-line ()
10305 "Indent the current line as JavaScript source text."
10306 (interactive)
10307 (when js2-use-ast-for-indentation-p
10308 (js2-reparse))
10309 (let (parse-status
10310 current-indent
10311 offset
10312 indent-col
10313 moved
10314 ;; don't whine about errors/warnings when we're indenting.
10315 ;; This has to be set before calling parse-partial-sexp below.
10316 (inhibit-point-motion-hooks t))
10317 (setq parse-status (save-excursion
10318 (parse-partial-sexp (point-min)
10319 (point-at-bol)))
10320 offset (- (point) (save-excursion
10321 (back-to-indentation)
10322 (setq current-indent (current-column))
10323 (point))))
10324 (js2-with-underscore-as-word-syntax
10325 (if (nth 4 parse-status)
10326 (js2-lineup-comment parse-status)
10327 (setq indent-col (js-proper-indentation parse-status))
10328 ;; see comments below about js2-mode-last-indented-line
10329 (when
10330 (cond
10331 ;; bounce-indenting is disabled during electric-key indent.
10332 ;; It doesn't work well on first line of buffer.
10333 ((and js2-bounce-indent-p
10334 (not (js2-same-line (point-min)))
10335 (not (js2-1-line-comment-continuation-p)))
10336 (js2-bounce-indent indent-col parse-status)
10337 (setq moved t))
10338 ;; just indent to the guesser's likely spot
10339 ((/= current-indent indent-col)
10340 (indent-line-to indent-col)
10341 (setq moved t)))
10342 (when (and moved (plusp offset))
10343 (forward-char offset)))))))
10344
10345 (defun js2-indent-region (start end)
10346 "Indent the region, but don't use bounce indenting."
10347 (let ((js2-bounce-indent-p nil)
10348 (indent-region-function nil))
10349 (indent-region start end nil))) ; nil for byte-compiler
10350
10351 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10352
10353 ;;;###autoload
10354 (defun js2-mode ()
10355 "Major mode for editing JavaScript code."
10356 (interactive)
10357 (kill-all-local-variables)
10358 (set-syntax-table js2-mode-syntax-table)
10359 (use-local-map js2-mode-map)
10360 (setq major-mode 'js2-mode
10361 mode-name "JavaScript-IDE"
10362 comment-start "//" ; used by comment-region; don't change it
10363 comment-end "")
10364 (setq local-abbrev-table js2-mode-abbrev-table)
10365 (set (make-local-variable 'max-lisp-eval-depth)
10366 (max max-lisp-eval-depth 3000))
10367 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10368 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10369
10370 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10371 ;; on most platforms other than the one I originally wrote it on. So it's
10372 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10373 ;; with our binding of the RET key inside comments: short lines stay short.
10374 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10375
10376 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10377 (set (make-local-variable 'next-error-function) #'js2-next-error)
10378 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10379 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10380 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10381 ;; for characters inside regexp literals.
10382 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10383 ;; this is necessary to make `show-paren-function' work properly
10384 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10385 ;; needed for M-x rgrep, among other things
10386 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10387
10388 ;; some variables needed by cc-engine for paragraph-fill, etc.
10389 (setq c-buffer-is-cc-mode t
10390 c-comment-prefix-regexp js2-comment-prefix-regexp
10391 c-comment-start-regexp "/[*/]\\|\\s|"
10392 c-paragraph-start js2-paragraph-start
10393 c-paragraph-separate "$"
10394 comment-start-skip js2-comment-start-skip
10395 c-syntactic-ws-start js2-syntactic-ws-start
10396 c-syntactic-ws-end js2-syntactic-ws-end
10397 c-syntactic-eol js2-syntactic-eol)
10398
10399 (setq js2-default-externs
10400 (append js2-ecma-262-externs
10401 (if js2-include-browser-externs
10402 js2-browser-externs)
10403 (if js2-include-gears-externs
10404 js2-gears-externs)
10405 (if js2-include-rhino-externs
10406 js2-rhino-externs)))
10407
10408 ;; We do our own syntax highlighting based on the parse tree.
10409 ;; However, we want minor modes that add keywords to highlight properly
10410 ;; (examples: doxymacs, column-marker). We do this by not letting
10411 ;; font-lock unfontify anything, and telling it to fontify after we
10412 ;; re-parse and re-highlight the buffer. (We currently don't do any
10413 ;; work with regions other than the whole buffer.)
10414 (dolist (var '(font-lock-unfontify-buffer-function
10415 font-lock-unfontify-region-function))
10416 (set (make-local-variable var) (lambda (&rest args) t)))
10417
10418 ;; Don't let font-lock do syntactic (string/comment) fontification.
10419 (set (make-local-variable #'font-lock-syntactic-face-function)
10420 (lambda (state) nil))
10421
10422 ;; Experiment: make reparse-delay longer for longer files.
10423 (if (plusp js2-dynamic-idle-timer-adjust)
10424 (setq js2-idle-timer-delay
10425 (* js2-idle-timer-delay
10426 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10427
10428 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10429 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10430 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10431 (imenu-add-to-menubar (concat "IM-" mode-name))
10432 (when js2-mirror-mode
10433 (js2-enter-mirror-mode))
10434 (add-to-invisibility-spec '(js2-outline . t))
10435 (set (make-local-variable 'line-move-ignore-invisible) t)
10436 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10437 (setq js2-mode-functions-hidden nil
10438 js2-mode-comments-hidden nil
10439 js2-mode-buffer-dirty-p t
10440 js2-mode-parsing nil)
10441 (js2-reparse)
10442 (run-hooks 'js2-mode-hook))
10443
10444 (defun js2-mode-exit ()
10445 "Exit `js2-mode' and clean up."
10446 (interactive)
10447 (when js2-mode-node-overlay
10448 (delete-overlay js2-mode-node-overlay)
10449 (setq js2-mode-node-overlay nil))
10450 (js2-remove-overlays)
10451 (setq js2-mode-ast nil)
10452 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10453 (remove-from-invisibility-spec '(js2-outline . t))
10454 (js2-mode-show-all)
10455 (js2-with-unmodifying-text-property-changes
10456 (js2-clear-face (point-min) (point-max))))
10457
10458 (defun js2-before-save ()
10459 "Clean up whitespace before saving file.
10460 You can disable this by customizing `js2-cleanup-whitespace'."
10461 (when js2-cleanup-whitespace
10462 (let ((col (current-column)))
10463 (delete-trailing-whitespace)
10464 ;; don't change trailing whitespace on current line
10465 (unless (eq (current-column) col)
10466 (indent-to col)))))
10467
10468 (defsubst js2-mode-reset-timer ()
10469 "Cancel any existing parse timer and schedule a new one."
10470 (if js2-mode-parse-timer
10471 (cancel-timer js2-mode-parse-timer))
10472 (setq js2-mode-parsing nil)
10473 (setq js2-mode-parse-timer
10474 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10475
10476 (defun js2-mode-edit (beg end len)
10477 "Schedule a new parse after buffer is edited.
10478 Buffer edit spans from BEG to END and is of length LEN.
10479 Also clears the `js2-magic' bit on autoinserted parens/brackets
10480 if the edit occurred on a line different from the magic paren."
10481 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10482 (line (if magic-pos (line-number-at-pos magic-pos))))
10483 (and line
10484 (or (/= (line-number-at-pos beg) line)
10485 (and (> 0 len)
10486 (/= (line-number-at-pos end) line)))
10487 (js2-mode-mundanify-parens)))
10488 (setq js2-mode-buffer-dirty-p t)
10489 (js2-mode-hide-overlay)
10490 (js2-mode-reset-timer))
10491
10492 (defun js2-mode-run-font-lock ()
10493 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10494 This is intended to allow modes that install their own font-lock keywords
10495 to work with js2-mode. In practice it never seems to work for long.
10496 Hopefully the Emacs maintainers can help figure out a way to make it work."
10497 (when (and (boundp 'font-lock-keywords)
10498 font-lock-keywords
10499 (boundp 'font-lock-mode)
10500 font-lock-mode)
10501 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10502 ;; play nicely with js2-mode. They go out of their way to fail to
10503 ;; provide any option for saying "look, fontify the farging buffer
10504 ;; with just the keywords already". Argh.
10505 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10506 (let (font-lock-verbose)
10507 (font-lock-fontify-buffer))))
10508
10509 (defun js2-reparse (&optional force)
10510 "Re-parse current buffer after user finishes some data entry.
10511 If we get any user input while parsing, including cursor motion,
10512 we discard the parse and reschedule it. If FORCE is nil, then the
10513 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10514 (let (time
10515 interrupted-p
10516 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10517 (unless js2-mode-parsing
10518 (setq js2-mode-parsing t)
10519 (unwind-protect
10520 (when (or js2-mode-buffer-dirty-p force)
10521 (js2-remove-overlays)
10522 (js2-with-unmodifying-text-property-changes
10523 (setq js2-mode-buffer-dirty-p nil
10524 js2-mode-fontifications nil
10525 js2-mode-deferred-properties nil
10526 js2-additional-externs nil)
10527 (if js2-mode-verbose-parse-p
10528 (message "parsing..."))
10529 (setq time
10530 (js2-time
10531 (setq interrupted-p
10532 (catch 'interrupted
10533 (setq js2-mode-ast (js2-parse))
10534 ;; if parsing is interrupted, comments and regex
10535 ;; literals stay ignored by `parse-partial-sexp'
10536 (remove-text-properties (point-min) (point-max)
10537 '(syntax-table))
10538 (js2-mode-apply-deferred-properties)
10539 (js2-mode-remove-suppressed-warnings)
10540 (js2-mode-show-warnings)
10541 (js2-mode-show-errors)
10542 (js2-mode-run-font-lock) ; note: doesn't work
10543 (js2-mode-highlight-magic-parens)
10544 (if (>= js2-highlight-level 1)
10545 (js2-highlight-jsdoc js2-mode-ast))
10546 nil))))
10547 (if interrupted-p
10548 (progn
10549 ;; unfinished parse => try again
10550 (setq js2-mode-buffer-dirty-p t)
10551 (js2-mode-reset-timer))
10552 (if js2-mode-verbose-parse-p
10553 (message "Parse time: %s" time)))))
10554 (setq js2-mode-parsing nil)
10555 (unless interrupted-p
10556 (setq js2-mode-parse-timer nil))))))
10557
10558 (defun js2-mode-show-node ()
10559 "Debugging aid: highlight selected AST node on mouse click."
10560 (interactive)
10561 (let ((node (js2-node-at-point))
10562 beg
10563 end)
10564 (when js2-mode-show-overlay
10565 (if (null node)
10566 (message "No node found at location %s" (point))
10567 (setq beg (js2-node-abs-pos node)
10568 end (+ beg (js2-node-len node)))
10569 (if js2-mode-node-overlay
10570 (move-overlay js2-mode-node-overlay beg end)
10571 (setq js2-mode-node-overlay (make-overlay beg end))
10572 (overlay-put js2-mode-node-overlay 'face 'highlight))
10573 (js2-with-unmodifying-text-property-changes
10574 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10575 (message "%s, parent: %s"
10576 (js2-node-short-name node)
10577 (if (js2-node-parent node)
10578 (js2-node-short-name (js2-node-parent node))
10579 "nil"))))))
10580
10581 (defun js2-mode-hide-overlay (&optional p1 p2)
10582 "Remove the debugging overlay when the point moves.
10583 P1 and P2 are the old and new values of point, respectively."
10584 (when js2-mode-node-overlay
10585 (let ((beg (overlay-start js2-mode-node-overlay))
10586 (end (overlay-end js2-mode-node-overlay)))
10587 ;; Sometimes we're called spuriously.
10588 (unless (and p2
10589 (>= p2 beg)
10590 (<= p2 end))
10591 (js2-with-unmodifying-text-property-changes
10592 (remove-text-properties beg end '(point-left nil)))
10593 (delete-overlay js2-mode-node-overlay)
10594 (setq js2-mode-node-overlay nil)))))
10595
10596 (defun js2-mode-reset ()
10597 "Debugging helper: reset everything."
10598 (interactive)
10599 (js2-mode-exit)
10600 (js2-mode))
10601
10602 (defsubst js2-mode-show-warn-or-err (e face)
10603 "Highlight a warning or error E with FACE.
10604 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10605 (let* ((key (first e))
10606 (beg (second e))
10607 (end (+ beg (third e)))
10608 ;; Don't inadvertently go out of bounds.
10609 (beg (max (point-min) (min beg (point-max))))
10610 (end (max (point-min) (min end (point-max))))
10611 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10612 (ovl (make-overlay beg end)))
10613 (overlay-put ovl 'face face)
10614 (overlay-put ovl 'js2-error t)
10615 (put-text-property beg end 'help-echo (js2-get-msg key))
10616 (put-text-property beg end 'point-entered #'js2-echo-error)))
10617
10618 (defun js2-remove-overlays ()
10619 "Remove overlays from buffer that have a `js2-error' property."
10620 (let ((beg (point-min))
10621 (end (point-max)))
10622 (save-excursion
10623 (dolist (o (overlays-in beg end))
10624 (when (overlay-get o 'js2-error)
10625 (delete-overlay o))))))
10626
10627 (defun js2-error-at-point (&optional pos)
10628 "Return non-nil if there's an error overlay at POS.
10629 Defaults to point."
10630 (loop with pos = (or pos (point))
10631 for o in (overlays-at pos)
10632 thereis (overlay-get o 'js2-error)))
10633
10634 (defun js2-mode-apply-deferred-properties ()
10635 "Apply fontifications and other text properties recorded during parsing."
10636 (when (plusp js2-highlight-level)
10637 ;; We defer clearing faces as long as possible to eliminate flashing.
10638 (js2-clear-face (point-min) (point-max))
10639 ;; Have to reverse the recorded fontifications list so that errors
10640 ;; and warnings overwrite the normal fontifications.
10641 (dolist (f (nreverse js2-mode-fontifications))
10642 (put-text-property (first f) (second f) 'face (third f)))
10643 (setq js2-mode-fontifications nil))
10644 (dolist (p js2-mode-deferred-properties)
10645 (apply #'put-text-property p))
10646 (setq js2-mode-deferred-properties nil))
10647
10648 (defun js2-mode-show-errors ()
10649 "Highlight syntax errors."
10650 (when js2-mode-show-parse-errors
10651 (dolist (e (js2-ast-root-errors js2-mode-ast))
10652 (js2-mode-show-warn-or-err e 'js2-error-face))))
10653
10654 (defun js2-mode-remove-suppressed-warnings ()
10655 "Take suppressed warnings out of the AST warnings list.
10656 This ensures that the counts and `next-error' are correct."
10657 (setf (js2-ast-root-warnings js2-mode-ast)
10658 (js2-delete-if
10659 (lambda (e)
10660 (let ((key (caar e)))
10661 (or
10662 (and (not js2-strict-trailing-comma-warning)
10663 (string-match "trailing\\.comma" key))
10664 (and (not js2-strict-cond-assign-warning)
10665 (string= key "msg.equal.as.assign"))
10666 (and js2-missing-semi-one-line-override
10667 (string= key "msg.missing.semi")
10668 (let* ((beg (second e))
10669 (node (js2-node-at-point beg))
10670 (fn (js2-mode-find-parent-fn node))
10671 (body (and fn (js2-function-node-body fn)))
10672 (lc (and body (js2-node-abs-pos body)))
10673 (rc (and lc (+ lc (js2-node-len body)))))
10674 (and fn
10675 (or (null body)
10676 (save-excursion
10677 (goto-char beg)
10678 (and (js2-same-line lc)
10679 (js2-same-line rc))))))))))
10680 (js2-ast-root-warnings js2-mode-ast))))
10681
10682 (defun js2-mode-show-warnings ()
10683 "Highlight strict-mode warnings."
10684 (when js2-mode-show-strict-warnings
10685 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10686 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10687
10688 (defun js2-echo-error (old-point new-point)
10689 "Called by point-motion hooks."
10690 (let ((msg (get-text-property new-point 'help-echo)))
10691 (if msg
10692 (message msg))))
10693
10694 (defalias #'js2-echo-help #'js2-echo-error)
10695
10696 (defun js2-enter-key ()
10697 "Handle user pressing the Enter key."
10698 (interactive)
10699 (let ((parse-status (save-excursion
10700 (parse-partial-sexp (point-min) (point)))))
10701 (cond
10702 ;; check if we're inside a string
10703 ((nth 3 parse-status)
10704 (js2-mode-split-string parse-status))
10705 ;; check if inside a block comment
10706 ((nth 4 parse-status)
10707 (js2-mode-extend-comment))
10708 (t
10709 ;; should probably figure out what the mode-map says we should do
10710 (if js2-indent-on-enter-key
10711 (let ((js2-bounce-indent-p nil))
10712 (js2-indent-line)))
10713 (insert "\n")
10714 (if js2-enter-indents-newline
10715 (let ((js2-bounce-indent-p nil))
10716 (js2-indent-line)))))))
10717
10718 (defun js2-mode-split-string (parse-status)
10719 "Turn a newline in mid-string into a string concatenation.
10720 PARSE-STATUS is as documented in `parse-partial-sexp'."
10721 (let* ((col (current-column))
10722 (quote-char (nth 3 parse-status))
10723 (quote-string (string quote-char))
10724 (string-beg (nth 8 parse-status))
10725 (indent (save-match-data
10726 (or
10727 (save-excursion
10728 (back-to-indentation)
10729 (if (looking-at "\\+")
10730 (current-column)))
10731 (save-excursion
10732 (goto-char string-beg)
10733 (if (looking-back "\\+\\s-+")
10734 (goto-char (match-beginning 0)))
10735 (current-column))))))
10736 (insert quote-char "\n")
10737 (indent-to indent)
10738 (insert "+ " quote-string)
10739 (when (eolp)
10740 (insert quote-string)
10741 (backward-char 1))))
10742
10743 (defun js2-mode-extend-comment ()
10744 "When inside a comment block, add comment prefix."
10745 (let (star single col first-line needs-close)
10746 (save-excursion
10747 (back-to-indentation)
10748 (cond
10749 ((looking-at "\\*[^/]")
10750 (setq star t
10751 col (current-column)))
10752 ((looking-at "/\\*")
10753 (setq star t
10754 first-line t
10755 col (1+ (current-column))))
10756 ((looking-at "//")
10757 (setq single t
10758 col (current-column)))))
10759 ;; Heuristic for whether we need to close the comment:
10760 ;; if we've got a parse error here, assume it's an unterminated
10761 ;; comment.
10762 (setq needs-close
10763 (or
10764 (eq (get-text-property (1- (point)) 'point-entered)
10765 'js2-echo-error)
10766 ;; The heuristic above doesn't work well when we're
10767 ;; creating a comment and there's another one downstream,
10768 ;; as our parser thinks this one ends at the end of the
10769 ;; next one. (You can have a /* inside a js block comment.)
10770 ;; So just close it if the next non-ws char isn't a *.
10771 (and first-line
10772 (eolp)
10773 (save-excursion
10774 (skip-chars-forward " \t\r\n")
10775 (not (eq (char-after) ?*))))))
10776 (insert "\n")
10777 (cond
10778 (star
10779 (indent-to col)
10780 (insert "* ")
10781 (if (and first-line needs-close)
10782 (save-excursion
10783 (insert "\n")
10784 (indent-to col)
10785 (insert "*/"))))
10786 (single
10787 (when (save-excursion
10788 (and (zerop (forward-line 1))
10789 (looking-at "\\s-*//")))
10790 (indent-to col)
10791 (insert "// "))))))
10792
10793 (defun js2-beginning-of-line ()
10794 "Toggles point between bol and first non-whitespace char in line.
10795 Also moves past comment delimiters when inside comments."
10796 (interactive)
10797 (let (node beg)
10798 (cond
10799 ((bolp)
10800 (back-to-indentation))
10801 ((looking-at "//")
10802 (skip-chars-forward "/ \t"))
10803 ((and (eq (char-after) ?*)
10804 (setq node (js2-comment-at-point))
10805 (memq (js2-comment-node-format node) '(jsdoc block))
10806 (save-excursion
10807 (skip-chars-backward " \t")
10808 (bolp)))
10809 (skip-chars-forward "\* \t"))
10810 (t
10811 (goto-char (point-at-bol))))))
10812
10813 (defun js2-end-of-line ()
10814 "Toggles point between eol and last non-whitespace char in line."
10815 (interactive)
10816 (if (eolp)
10817 (skip-chars-backward " \t")
10818 (goto-char (point-at-eol))))
10819
10820 (defun js2-enter-mirror-mode()
10821 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10822 on insertion."
10823 (interactive)
10824 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10825 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10826 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10827 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10828 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10829 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10830 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10831 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10832
10833 (defun js2-leave-mirror-mode()
10834 "Turns off mirror mode."
10835 (interactive)
10836 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10837 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10838
10839 (defsubst js2-mode-inside-string ()
10840 "Return non-nil if inside a string.
10841 Actually returns the quote character that begins the string."
10842 (let ((parse-state (save-excursion
10843 (parse-partial-sexp (point-min) (point)))))
10844 (nth 3 parse-state)))
10845
10846 (defsubst js2-mode-inside-comment-or-string ()
10847 "Return non-nil if inside a comment or string."
10848 (or
10849 (let ((comment-start
10850 (save-excursion
10851 (goto-char (point-at-bol))
10852 (if (re-search-forward "//" (point-at-eol) t)
10853 (match-beginning 0)))))
10854 (and comment-start
10855 (<= comment-start (point))))
10856 (let ((parse-state (save-excursion
10857 (parse-partial-sexp (point-min) (point)))))
10858 (or (nth 3 parse-state)
10859 (nth 4 parse-state)))))
10860
10861 (defsubst js2-make-magic-delimiter (delim &optional pos)
10862 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10863 Sets value of `js2-magic' text property to line number at POS."
10864 (propertize delim
10865 'js2-magic (line-number-at-pos pos)
10866 'face 'js2-magic-paren-face))
10867
10868 (defun js2-mode-match-delimiter (open close)
10869 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10870 The rule we use, which as far as we can tell is how Eclipse works,
10871 is that we insert the match if we're not in a comment or string,
10872 and the next non-whitespace character is either punctuation or
10873 occurs on another line."
10874 (insert open)
10875 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10876 (not (js2-mode-inside-comment-or-string)))
10877 (save-excursion
10878 (insert (js2-make-magic-delimiter close)))
10879 (when js2-auto-indent-p
10880 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10881 (js2-indent-line)))))
10882
10883 (defun js2-mode-match-bracket ()
10884 "Insert matching bracket."
10885 (interactive)
10886 (js2-mode-match-delimiter "[" "]"))
10887
10888 (defun js2-mode-match-paren ()
10889 "Insert matching paren unless already inserted."
10890 (interactive)
10891 (js2-mode-match-delimiter "(" ")"))
10892
10893 (defun js2-mode-match-curly (arg)
10894 "Insert matching curly-brace.
10895 With prefix arg, no formatting or indentation will occur -- the close-brace
10896 is simply inserted directly at the point."
10897 (interactive "p")
10898 (let (try-pos)
10899 (cond
10900 (current-prefix-arg
10901 (js2-mode-match-delimiter "{" "}"))
10902 ((and js2-auto-insert-catch-block
10903 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10904 (point-at-bol))
10905 (match-beginning 1))))
10906 (js2-insert-catch-skel try-pos))
10907 (t
10908 ;; Otherwise try to do something smarter.
10909 (insert "{")
10910 (unless (or (not (looking-at "\\s-*$"))
10911 (save-excursion
10912 (skip-chars-forward " \t\r\n")
10913 (and (looking-at "}")
10914 (js2-error-at-point)))
10915 (js2-mode-inside-comment-or-string))
10916 (undo-boundary)
10917 ;; absolutely mystifying bug: when inserting the next "\n",
10918 ;; the buffer-undo-list is given two new entries: the inserted range,
10919 ;; and the incorrect position of the point. It's recorded incorrectly
10920 ;; as being before the opening "{", not after it. But it's recorded
10921 ;; as the correct value if you're debugging `js2-mode-match-curly'
10922 ;; in edebug. I have no idea why it's doing this, but incrementing
10923 ;; the inserted position fixes the problem, so that the undo takes us
10924 ;; back to just after the user-inserted "{".
10925 (insert "\n")
10926 (ignore-errors
10927 (incf (cadr buffer-undo-list)))
10928 (js2-indent-line)
10929 (save-excursion
10930 (insert "\n}")
10931 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10932 (js2-indent-line))))))))
10933
10934 (defun js2-insert-catch-skel (try-pos)
10935 "Complete a try/catch block after inserting a { following a try keyword.
10936 Rationale is that a try always needs a catch or a finally, and the catch is
10937 the more likely of the two.
10938
10939 TRY-POS is the buffer position of the try keyword. The open-curly should
10940 already have been inserted."
10941 (insert "{")
10942 (let ((try-col (save-excursion
10943 (goto-char try-pos)
10944 (current-column))))
10945 (insert "\n")
10946 (undo-boundary)
10947 (js2-indent-line) ;; indent the blank line where cursor will end up
10948 (save-excursion
10949 (insert "\n")
10950 (indent-to try-col)
10951 (insert "} catch (x) {\n\n")
10952 (indent-to try-col)
10953 (insert "}"))))
10954
10955 (defun js2-mode-highlight-magic-parens ()
10956 "Re-highlight magic parens after parsing nukes the 'face prop."
10957 (let ((beg (point-min))
10958 end)
10959 (while (setq beg (next-single-property-change beg 'js2-magic))
10960 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10961 (if (get-text-property beg 'js2-magic)
10962 (js2-with-unmodifying-text-property-changes
10963 (put-text-property beg (or end (1+ beg))
10964 'face 'js2-magic-paren-face))))))
10965
10966 (defun js2-mode-mundanify-parens ()
10967 "Clear all magic parens and brackets."
10968 (let ((beg (point-min))
10969 end)
10970 (while (setq beg (next-single-property-change beg 'js2-magic))
10971 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10972 (remove-text-properties beg (or end (1+ beg))
10973 '(js2-magic face)))))
10974
10975 (defsubst js2-match-quote (quote-string)
10976 (let ((start-quote (js2-mode-inside-string)))
10977 (cond
10978 ;; inside a comment - don't do quote-matching, since we can't
10979 ;; reliably figure out if we're in a string inside the comment
10980 ((js2-comment-at-point)
10981 (insert quote-string))
10982 ((not start-quote)
10983 ;; not in string => insert matched quotes
10984 (insert quote-string)
10985 ;; exception: if we're just before a word, don't double it.
10986 (unless (looking-at "[^ \t\r\n]")
10987 (save-excursion
10988 (insert quote-string))))
10989 ((looking-at quote-string)
10990 (if (looking-back "[^\\]\\\\")
10991 (insert quote-string)
10992 (forward-char 1)))
10993 ((and js2-mode-escape-quotes
10994 (save-excursion
10995 (save-match-data
10996 (re-search-forward quote-string (point-at-eol) t))))
10997 ;; inside terminated string, escape quote (unless already escaped)
10998 (insert (if (looking-back "[^\\]\\\\")
10999 quote-string
11000 (concat "\\" quote-string))))
11001 (t
11002 (insert quote-string))))) ; else terminate the string
11003
11004 (defun js2-mode-match-single-quote ()
11005 "Insert matching single-quote."
11006 (interactive)
11007 (let ((parse-status (parse-partial-sexp (point-min) (point))))
11008 ;; don't match inside comments, since apostrophe is more common
11009 (if (nth 4 parse-status)
11010 (insert "'")
11011 (js2-match-quote "'"))))
11012
11013 (defun js2-mode-match-double-quote ()
11014 "Insert matching double-quote."
11015 (interactive)
11016 (js2-match-quote "\""))
11017
11018 ;; Eclipse works as follows:
11019 ;; * type an open-paren and it auto-inserts close-paren
11020 ;; - auto-inserted paren gets a green bracket
11021 ;; - green bracket means typing close-paren there will skip it
11022 ;; * if you insert any text on a different line, it turns off
11023 (defun js2-mode-magic-close-paren ()
11024 "Skip over close-paren rather than inserting, where appropriate."
11025 (interactive)
11026 (let* ((here (point))
11027 (parse-status (parse-partial-sexp (point-min) here))
11028 (open-pos (nth 1 parse-status))
11029 (close last-input-event)
11030 (open (cond
11031 ((eq close ?\))
11032 ?\()
11033 ((eq close ?\])
11034 ?\[)
11035 ((eq close ?})
11036 ?{)
11037 (t nil))))
11038 (if (and (eq (char-after) close)
11039 (eq open (char-after open-pos))
11040 (js2-same-line open-pos)
11041 (get-text-property here 'js2-magic))
11042 (progn
11043 (remove-text-properties here (1+ here) '(js2-magic face))
11044 (forward-char 1))
11045 (insert-char close 1))
11046 (blink-matching-open)))
11047
11048 (defun js2-mode-wait-for-parse (callback)
11049 "Invoke CALLBACK when parsing is finished.
11050 If parsing is already finished, calls CALLBACK immediately."
11051 (if (not js2-mode-buffer-dirty-p)
11052 (funcall callback)
11053 (push callback js2-mode-pending-parse-callbacks)
11054 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11055
11056 (defun js2-mode-parse-finished ()
11057 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11058 ;; We can't let errors propagate up, since it prevents the
11059 ;; `js2-parse' method from completing normally and returning
11060 ;; the ast, which makes things mysteriously not work right.
11061 (unwind-protect
11062 (dolist (cb js2-mode-pending-parse-callbacks)
11063 (condition-case err
11064 (funcall cb)
11065 (error (message "%s" err))))
11066 (setq js2-mode-pending-parse-callbacks nil)))
11067
11068 (defun js2-mode-flag-region (from to flag)
11069 "Hide or show text from FROM to TO, according to FLAG.
11070 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11071 Returns the created overlay if FLAG is non-nil."
11072 (remove-overlays from to 'invisible 'js2-outline)
11073 (when flag
11074 (let ((o (make-overlay from to)))
11075 (overlay-put o 'invisible 'js2-outline)
11076 (overlay-put o 'isearch-open-invisible
11077 'js2-isearch-open-invisible)
11078 o)))
11079
11080 ;; Function to be set as an outline-isearch-open-invisible' property
11081 ;; to the overlay that makes the outline invisible (see
11082 ;; `js2-mode-flag-region').
11083 (defun js2-isearch-open-invisible (overlay)
11084 ;; We rely on the fact that isearch places point on the matched text.
11085 (js2-mode-show-element))
11086
11087 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11088 "Return cons cell of bounds of folding overlay at POS.
11089 Returns nil if not found."
11090 (let ((overlays (overlays-at (or pos (point))))
11091 o)
11092 (while (and overlays
11093 (not o))
11094 (if (overlay-get (car overlays) 'invisible)
11095 (setq o (car overlays))
11096 (setq overlays (cdr overlays))))
11097 (if o
11098 (cons (overlay-start o) (overlay-end o)))))
11099
11100 (defun js2-mode-function-at-point (&optional pos)
11101 "Return the innermost function node enclosing current point.
11102 Returns nil if point is not in a function."
11103 (let ((node (js2-node-at-point pos)))
11104 (while (and node (not (js2-function-node-p node)))
11105 (setq node (js2-node-parent node)))
11106 (if (js2-function-node-p node)
11107 node)))
11108
11109 (defun js2-mode-toggle-element ()
11110 "Hide or show the foldable element at the point."
11111 (interactive)
11112 (let (comment fn pos)
11113 (save-excursion
11114 (save-match-data
11115 (cond
11116 ;; /* ... */ comment?
11117 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11118 (if (js2-mode-invisible-overlay-bounds
11119 (setq pos (+ 3 (js2-node-abs-pos comment))))
11120 (progn
11121 (goto-char pos)
11122 (js2-mode-show-element))
11123 (js2-mode-hide-element)))
11124 ;; //-comment?
11125 ((save-excursion
11126 (back-to-indentation)
11127 (looking-at js2-mode-//-comment-re))
11128 (js2-mode-toggle-//-comment))
11129 ;; function?
11130 ((setq fn (js2-mode-function-at-point))
11131 (setq pos (and (js2-function-node-body fn)
11132 (js2-node-abs-pos (js2-function-node-body fn))))
11133 (goto-char (1+ pos))
11134 (if (js2-mode-invisible-overlay-bounds)
11135 (js2-mode-show-element)
11136 (js2-mode-hide-element)))
11137 (t
11138 (message "Nothing at point to hide or show")))))))
11139
11140 (defun js2-mode-hide-element ()
11141 "Fold/hide contents of a block, showing ellipses.
11142 Show the hidden text with \\[js2-mode-show-element]."
11143 (interactive)
11144 (if js2-mode-buffer-dirty-p
11145 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11146 (let (node body beg end)
11147 (cond
11148 ((js2-mode-invisible-overlay-bounds)
11149 (message "already hidden"))
11150 (t
11151 (setq node (js2-node-at-point))
11152 (cond
11153 ((js2-block-comment-p node)
11154 (js2-mode-hide-comment node))
11155 (t
11156 (while (and node (not (js2-function-node-p node)))
11157 (setq node (js2-node-parent node)))
11158 (if (and node
11159 (setq body (js2-function-node-body node)))
11160 (progn
11161 (setq beg (js2-node-abs-pos body)
11162 end (+ beg (js2-node-len body)))
11163 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11164 (message "No collapsable element found at point"))))))))
11165
11166 (defun js2-mode-show-element ()
11167 "Show the hidden element at current point."
11168 (interactive)
11169 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11170 (if bounds
11171 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11172 (message "Nothing to un-hide"))))
11173
11174 (defun js2-mode-show-all ()
11175 "Show all of the text in the buffer."
11176 (interactive)
11177 (js2-mode-flag-region (point-min) (point-max) nil))
11178
11179 (defun js2-mode-toggle-hide-functions ()
11180 (interactive)
11181 (if js2-mode-functions-hidden
11182 (js2-mode-show-functions)
11183 (js2-mode-hide-functions)))
11184
11185 (defun js2-mode-hide-functions ()
11186 "Hides all non-nested function bodies in the buffer.
11187 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11188 to open an individual entry."
11189 (interactive)
11190 (if js2-mode-buffer-dirty-p
11191 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11192 (if (null js2-mode-ast)
11193 (message "Oops - parsing failed")
11194 (setq js2-mode-functions-hidden t)
11195 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11196
11197 (defun js2-mode-function-hider (n endp)
11198 (when (not endp)
11199 (let ((tt (js2-node-type n))
11200 body beg end)
11201 (cond
11202 ((and (= tt js2-FUNCTION)
11203 (setq body (js2-function-node-body n)))
11204 (setq beg (js2-node-abs-pos body)
11205 end (+ beg (js2-node-len body)))
11206 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11207 nil) ; don't process children of function
11208 (t
11209 t))))) ; keep processing other AST nodes
11210
11211 (defun js2-mode-show-functions ()
11212 "Un-hide any folded function bodies in the buffer."
11213 (interactive)
11214 (setq js2-mode-functions-hidden nil)
11215 (save-excursion
11216 (goto-char (point-min))
11217 (while (/= (goto-char (next-overlay-change (point)))
11218 (point-max))
11219 (dolist (o (overlays-at (point)))
11220 (when (and (overlay-get o 'invisible)
11221 (not (overlay-get o 'comment)))
11222 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11223
11224 (defun js2-mode-hide-comment (n)
11225 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11226 3 ; /**
11227 2)) ; /*
11228 (beg (+ (js2-node-abs-pos n) head))
11229 (end (- (+ beg (js2-node-len n)) head 2))
11230 (o (js2-mode-flag-region beg end 'hide)))
11231 (overlay-put o 'comment t)))
11232
11233 (defun js2-mode-toggle-hide-comments ()
11234 "Folds all block comments in the buffer.
11235 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11236 to open an individual entry."
11237 (interactive)
11238 (if js2-mode-comments-hidden
11239 (js2-mode-show-comments)
11240 (js2-mode-hide-comments)))
11241
11242 (defun js2-mode-hide-comments ()
11243 (interactive)
11244 (if js2-mode-buffer-dirty-p
11245 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11246 (if (null js2-mode-ast)
11247 (message "Oops - parsing failed")
11248 (setq js2-mode-comments-hidden t)
11249 (dolist (n (js2-ast-root-comments js2-mode-ast))
11250 (let ((format (js2-comment-node-format n)))
11251 (when (js2-block-comment-p n)
11252 (js2-mode-hide-comment n))))
11253 (js2-mode-hide-//-comments)))
11254
11255 (defsubst js2-mode-extend-//-comment (direction)
11256 "Find start or end of a block of similar //-comment lines.
11257 DIRECTION is -1 to look back, 1 to look forward.
11258 INDENT is the indentation level to match.
11259 Returns the end-of-line position of the furthest adjacent
11260 //-comment line with the same indentation as the current line.
11261 If there is no such matching line, returns current end of line."
11262 (let ((pos (point-at-eol))
11263 (indent (current-indentation)))
11264 (save-excursion
11265 (save-match-data
11266 (while (and (zerop (forward-line direction))
11267 (looking-at js2-mode-//-comment-re)
11268 (eq indent (length (match-string 1))))
11269 (setq pos (point-at-eol)))
11270 pos))))
11271
11272 (defun js2-mode-hide-//-comments ()
11273 "Fold adjacent 1-line comments, showing only snippet of first one."
11274 (let (beg end)
11275 (save-excursion
11276 (save-match-data
11277 (goto-char (point-min))
11278 (while (re-search-forward js2-mode-//-comment-re nil t)
11279 (setq beg (point)
11280 end (js2-mode-extend-//-comment 1))
11281 (unless (eq beg end)
11282 (overlay-put (js2-mode-flag-region beg end 'hide)
11283 'comment t))
11284 (goto-char end)
11285 (forward-char 1))))))
11286
11287 (defun js2-mode-toggle-//-comment ()
11288 "Fold or un-fold any multi-line //-comment at point.
11289 Caller should have determined that this line starts with a //-comment."
11290 (let* ((beg (point-at-eol))
11291 (end beg))
11292 (save-excursion
11293 (goto-char end)
11294 (if (js2-mode-invisible-overlay-bounds)
11295 (js2-mode-show-element)
11296 ;; else hide the comment
11297 (setq beg (js2-mode-extend-//-comment -1)
11298 end (js2-mode-extend-//-comment 1))
11299 (unless (eq beg end)
11300 (overlay-put (js2-mode-flag-region beg end 'hide)
11301 'comment t))))))
11302
11303 (defun js2-mode-show-comments ()
11304 "Un-hide any hidden comments, leaving other hidden elements alone."
11305 (interactive)
11306 (setq js2-mode-comments-hidden nil)
11307 (save-excursion
11308 (goto-char (point-min))
11309 (while (/= (goto-char (next-overlay-change (point)))
11310 (point-max))
11311 (dolist (o (overlays-at (point)))
11312 (when (overlay-get o 'comment)
11313 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11314
11315 (defun js2-mode-display-warnings-and-errors ()
11316 "Turn on display of warnings and errors."
11317 (interactive)
11318 (setq js2-mode-show-parse-errors t
11319 js2-mode-show-strict-warnings t)
11320 (js2-reparse 'force))
11321
11322 (defun js2-mode-hide-warnings-and-errors ()
11323 "Turn off display of warnings and errors."
11324 (interactive)
11325 (setq js2-mode-show-parse-errors nil
11326 js2-mode-show-strict-warnings nil)
11327 (js2-reparse 'force))
11328
11329 (defun js2-mode-toggle-warnings-and-errors ()
11330 "Toggle the display of warnings and errors.
11331 Some users don't like having warnings/errors reported while they type."
11332 (interactive)
11333 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11334 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11335 (if (interactive-p)
11336 (message "warnings and errors %s"
11337 (if js2-mode-show-parse-errors
11338 "enabled"
11339 "disabled")))
11340 (js2-reparse 'force))
11341
11342 (defun js2-mode-customize ()
11343 (interactive)
11344 (customize-group 'js2-mode))
11345
11346 (defun js2-mode-forward-sexp (&optional arg)
11347 "Move forward across one statement or balanced expression.
11348 With ARG, do it that many times. Negative arg -N means
11349 move backward across N balanced expressions."
11350 (interactive "p")
11351 (setq arg (or arg 1))
11352 (if js2-mode-buffer-dirty-p
11353 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11354 (let (node end (start (point)))
11355 (cond
11356 ;; backward-sexp
11357 ;; could probably make this better for some cases:
11358 ;; - if in statement block (e.g. function body), go to parent
11359 ;; - infix exprs like (foo in bar) - maybe go to beginning
11360 ;; of infix expr if in the right-side expression?
11361 ((and arg (minusp arg))
11362 (dotimes (i (- arg))
11363 (js2-backward-sws)
11364 (forward-char -1) ; enter the node we backed up to
11365 (setq node (js2-node-at-point (point) t))
11366 (goto-char (if node
11367 (js2-node-abs-pos node)
11368 (point-min)))))
11369 (t
11370 ;; forward-sexp
11371 (js2-forward-sws)
11372 (dotimes (i arg)
11373 (js2-forward-sws)
11374 (setq node (js2-node-at-point (point) t)
11375 end (if node (+ (js2-node-abs-pos node)
11376 (js2-node-len node))))
11377 (goto-char (or end (point-max))))))))
11378
11379 (defun js2-next-error (&optional arg reset)
11380 "Move to next parse error.
11381 Typically invoked via \\[next-error].
11382 ARG is the number of errors, forward or backward, to move.
11383 RESET means start over from the beginning."
11384 (interactive "p")
11385 (if (or (null js2-mode-ast)
11386 (and (null (js2-ast-root-errors js2-mode-ast))
11387 (null (js2-ast-root-warnings js2-mode-ast))))
11388 (message "No errors")
11389 (when reset
11390 (goto-char (point-min)))
11391 (let* ((errs (copy-sequence
11392 (append (js2-ast-root-errors js2-mode-ast)
11393 (js2-ast-root-warnings js2-mode-ast))))
11394 (continue t)
11395 (start (point))
11396 (count (or arg 1))
11397 (backward (minusp count))
11398 (sorter (if backward '> '<))
11399 (stopper (if backward '< '>))
11400 (count (abs count))
11401 all-errs
11402 err)
11403 ;; sort by start position
11404 (setq errs (sort errs (lambda (e1 e2)
11405 (funcall sorter (second e1) (second e2))))
11406 all-errs errs)
11407 ;; find nth error with pos > start
11408 (while (and errs continue)
11409 (when (funcall stopper (cadar errs) start)
11410 (setq err (car errs))
11411 (if (zerop (decf count))
11412 (setq continue nil)))
11413 (setq errs (cdr errs)))
11414 (if err
11415 (goto-char (second err))
11416 ;; wrap around to first error
11417 (goto-char (second (car all-errs)))
11418 ;; if we were already on it, echo msg again
11419 (if (= (point) start)
11420 (js2-echo-error (point) (point)))))))
11421
11422 (defun js2-down-mouse-3 ()
11423 "Make right-click move the point to the click location.
11424 This makes right-click context menu operations a bit more intuitive.
11425 The point will not move if the region is active, however, to avoid
11426 destroying the region selection."
11427 (interactive)
11428 (when (and js2-move-point-on-right-click
11429 (not mark-active))
11430 (let ((e last-input-event))
11431 (ignore-errors
11432 (goto-char (cadadr e))))))
11433
11434 (defun js2-mode-create-imenu-index ()
11435 "Return an alist for `imenu--index-alist'."
11436 ;; This is built up in `js2-parse-record-imenu' during parsing.
11437 (when js2-mode-ast
11438 ;; if we have an ast but no recorder, they're requesting a rescan
11439 (unless js2-imenu-recorder
11440 (js2-reparse 'force))
11441 (prog1
11442 (js2-build-imenu-index)
11443 (setq js2-imenu-recorder nil
11444 js2-imenu-function-map nil
11445 js2-imenu-fn-type-map nil))))
11446
11447 (defun js2-mode-find-tag ()
11448 "Replacement for `find-tag-default'.
11449 `find-tag-default' returns a ridiculous answer inside comments."
11450 (let (beg end)
11451 (js2-with-underscore-as-word-syntax
11452 (save-excursion
11453 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11454 (looking-back "[A-Za-z0-9_$]"))
11455 (setq beg (progn (forward-word -1) (point))
11456 end (progn (forward-word 1) (point)))
11457 (setq beg (progn (forward-word 1) (point))
11458 end (progn (forward-word -1) (point))))
11459 (replace-regexp-in-string
11460 "[\"']" ""
11461 (buffer-substring-no-properties beg end))))))
11462
11463 (defun js2-mode-forward-sibling ()
11464 "Move to the end of the sibling following point in parent.
11465 Returns non-nil if successful, or nil if there was no following sibling."
11466 (let* ((node (js2-node-at-point))
11467 (parent (js2-mode-find-enclosing-fn node))
11468 sib)
11469 (when (setq sib (js2-node-find-child-after (point) parent))
11470 (goto-char (+ (js2-node-abs-pos sib)
11471 (js2-node-len sib))))))
11472
11473 (defun js2-mode-backward-sibling ()
11474 "Move to the beginning of the sibling node preceding point in parent.
11475 Parent is defined as the enclosing script or function."
11476 (let* ((node (js2-node-at-point))
11477 (parent (js2-mode-find-enclosing-fn node))
11478 sib)
11479 (when (setq sib (js2-node-find-child-before (point) parent))
11480 (goto-char (js2-node-abs-pos sib)))))
11481
11482 (defun js2-beginning-of-defun ()
11483 "Go to line on which current function starts, and return non-nil.
11484 If we're not in a function, go to beginning of previous script-level element."
11485 (interactive)
11486 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11487 pos sib)
11488 (cond
11489 ((and (js2-function-node-p parent)
11490 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11491 (goto-char pos))
11492 (t
11493 (js2-mode-backward-sibling)))))
11494
11495 (defun js2-end-of-defun ()
11496 "Go to the char after the last position of the current function.
11497 If we're not in a function, skips over the next script-level element."
11498 (interactive)
11499 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11500 (if (not (js2-function-node-p parent))
11501 ;; punt: skip over next script-level element beyond point
11502 (js2-mode-forward-sibling)
11503 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11504 (js2-node-len parent)))))))
11505
11506 (defun js2-mark-defun (&optional allow-extend)
11507 "Put mark at end of this function, point at beginning.
11508 The function marked is the one that contains point.
11509
11510 Interactively, if this command is repeated,
11511 or (in Transient Mark mode) if the mark is active,
11512 it marks the next defun after the ones already marked."
11513 (interactive "p")
11514 (let (extended)
11515 (when (and allow-extend
11516 (or (and (eq last-command this-command) (mark t))
11517 (and transient-mark-mode mark-active)))
11518 (let ((sib (save-excursion
11519 (goto-char (mark))
11520 (if (js2-mode-forward-sibling)
11521 (point))))
11522 node)
11523 (if sib
11524 (progn
11525 (set-mark sib)
11526 (setq extended t))
11527 ;; no more siblings - try extending to enclosing node
11528 (goto-char (mark t)))))
11529 (when (not extended)
11530 (let ((node (js2-node-at-point (point) t)) ; skip comments
11531 ast fn stmt parent beg end)
11532 (when (js2-ast-root-p node)
11533 (setq ast node
11534 node (or (js2-node-find-child-after (point) node)
11535 (js2-node-find-child-before (point) node))))
11536 ;; only mark whole buffer if we can't find any children
11537 (if (null node)
11538 (setq node ast))
11539 (if (js2-function-node-p node)
11540 (setq parent node)
11541 (setq fn (js2-mode-find-enclosing-fn node)
11542 stmt (if (or (null fn)
11543 (js2-ast-root-p fn))
11544 (js2-mode-find-first-stmt node))
11545 parent (or stmt fn)))
11546 (setq beg (js2-node-abs-pos parent)
11547 end (+ beg (js2-node-len parent)))
11548 (push-mark beg)
11549 (goto-char end)
11550 (exchange-point-and-mark)))))
11551
11552 (defun js2-narrow-to-defun ()
11553 "Narrow to the function enclosing point."
11554 (interactive)
11555 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11556 (fn (if (js2-script-node-p node)
11557 node
11558 (js2-mode-find-enclosing-fn node)))
11559 (beg (js2-node-abs-pos fn)))
11560 (unless (js2-ast-root-p fn)
11561 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11562
11563 (provide 'js2-mode)
11564
11565 ;;; js2-mode.el ends here