]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Revert "don't use inner scope of `for` for iteration target."
[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 (when js2-bounce-indent-p
1185 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1186
1187 (define-key map [menu-bar javascript]
1188 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1189
1190 (define-key map [menu-bar javascript customize-js2-mode]
1191 '(menu-item "Customize js2-mode" js2-mode-customize
1192 :help "Customize the behavior of this mode"))
1193
1194 (define-key map [menu-bar javascript js2-force-refresh]
1195 '(menu-item "Force buffer refresh" js2-mode-reset
1196 :help "Re-parse the buffer from scratch"))
1197
1198 (define-key map [menu-bar javascript separator-2]
1199 '("--"))
1200
1201 (define-key map [menu-bar javascript next-error]
1202 '(menu-item "Next warning or error" js2-next-error
1203 :enabled (and js2-mode-ast
1204 (or (js2-ast-root-errors js2-mode-ast)
1205 (js2-ast-root-warnings js2-mode-ast)))
1206 :help "Move to next warning or error"))
1207
1208 (define-key map [menu-bar javascript display-errors]
1209 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1210 :visible (not js2-mode-show-parse-errors)
1211 :help "Turn on display of warnings and errors"))
1212
1213 (define-key map [menu-bar javascript hide-errors]
1214 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1215 :visible js2-mode-show-parse-errors
1216 :help "Turn off display of warnings and errors"))
1217
1218 (define-key map [menu-bar javascript separator-1]
1219 '("--"))
1220
1221 (define-key map [menu-bar javascript js2-toggle-function]
1222 '(menu-item "Show/collapse element" js2-mode-toggle-element
1223 :help "Hide or show function body or comment"))
1224
1225 (define-key map [menu-bar javascript show-comments]
1226 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1227 :visible js2-mode-comments-hidden
1228 :help "Expand all hidden block comments"))
1229
1230 (define-key map [menu-bar javascript hide-comments]
1231 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1232 :visible (not js2-mode-comments-hidden)
1233 :help "Show block comments as /*...*/"))
1234
1235 (define-key map [menu-bar javascript show-all-functions]
1236 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1237 :visible js2-mode-functions-hidden
1238 :help "Expand all hidden function bodies"))
1239
1240 (define-key map [menu-bar javascript hide-all-functions]
1241 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1242 :visible (not js2-mode-functions-hidden)
1243 :help "Show {...} for all top-level function bodies"))
1244
1245 map)
1246 "Keymap used in `js2-mode' buffers.")
1247
1248 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1249
1250 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1251 "Matches a //-comment line. Must be first non-whitespace on line.
1252 First match-group is the leading whitespace.")
1253
1254 (defvar js2-mode-hook nil)
1255
1256 (js2-deflocal js2-mode-ast nil "Private variable.")
1257 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1258 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1259 (js2-deflocal js2-mode-parsing nil "Private variable.")
1260 (js2-deflocal js2-mode-node-overlay nil)
1261
1262 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1263 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1264
1265 (js2-deflocal js2-mode-fontifications nil "Private variable")
1266 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1267 (js2-deflocal js2-imenu-recorder nil "Private variable")
1268 (js2-deflocal js2-imenu-function-map nil "Private variable")
1269
1270 (defvar js2-paragraph-start
1271 "\\(@[a-zA-Z]+\\>\\|$\\)")
1272
1273 ;; Note that we also set a 'c-in-sws text property in html comments,
1274 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1275 (defvar js2-syntactic-ws-start
1276 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1277
1278 (defvar js2-syntactic-ws-end
1279 "\\s \\|[\n\r/]\\|\\s!")
1280
1281 (defvar js2-syntactic-eol
1282 (concat "\\s *\\(/\\*[^*\n\r]*"
1283 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1284 "\\*+/\\s *\\)*"
1285 "\\(//\\|/\\*[^*\n\r]*"
1286 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1287 "\\|\\\\$\\|$\\)")
1288 "Copied from `java-mode'. Needed for some cc-engine functions.")
1289
1290 (defvar js2-comment-prefix-regexp
1291 "//+\\|\\**")
1292
1293 (defvar js2-comment-start-skip
1294 "\\(//+\\|/\\*+\\)\\s *")
1295
1296 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1297 "Non-nil to emit status messages during parsing.")
1298
1299 (defvar js2-mode-functions-hidden nil "private variable")
1300 (defvar js2-mode-comments-hidden nil "private variable")
1301
1302 (defvar js2-mode-syntax-table
1303 (let ((table (make-syntax-table)))
1304 (c-populate-syntax-table table)
1305 table)
1306 "Syntax table used in js2-mode buffers.")
1307
1308 (defvar js2-mode-abbrev-table nil
1309 "Abbrev table in use in `js2-mode' buffers.")
1310 (define-abbrev-table 'js2-mode-abbrev-table ())
1311
1312 (defvar js2-mode-pending-parse-callbacks nil
1313 "List of functions waiting to be notified that parse is finished.")
1314
1315 (defvar js2-mode-last-indented-line -1)
1316
1317 ;;; Localizable error and warning messages
1318
1319 ;; Messages are copied from Rhino's Messages.properties.
1320 ;; Many of the Java-specific messages have been elided.
1321 ;; Add any js2-specific ones at the end, so we can keep
1322 ;; this file synced with changes to Rhino's.
1323
1324 (defvar js2-message-table
1325 (make-hash-table :test 'equal :size 250)
1326 "Contains localized messages for js2-mode.")
1327
1328 ;; TODO(stevey): construct this table at compile-time.
1329 (defmacro js2-msg (key &rest strings)
1330 `(puthash ,key (funcall #'concat ,@strings)
1331 js2-message-table))
1332
1333 (defun js2-get-msg (msg-key)
1334 "Look up a localized message.
1335 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1336 the correct number of ARGS must be provided."
1337 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1338 (args (if (listp msg-key) (cdr msg-key)))
1339 (msg (gethash key js2-message-table)))
1340 (if msg
1341 (apply #'format msg args)
1342 key))) ; default to showing the key
1343
1344 (js2-msg "msg.dup.parms"
1345 "Duplicate parameter name '%s'.")
1346
1347 (js2-msg "msg.too.big.jump"
1348 "Program too complex: jump offset too big.")
1349
1350 (js2-msg "msg.too.big.index"
1351 "Program too complex: internal index exceeds 64K limit.")
1352
1353 (js2-msg "msg.while.compiling.fn"
1354 "Encountered code generation error while compiling function '%s': %s")
1355
1356 (js2-msg "msg.while.compiling.script"
1357 "Encountered code generation error while compiling script: %s")
1358
1359 ;; Context
1360 (js2-msg "msg.ctor.not.found"
1361 "Constructor for '%s' not found.")
1362
1363 (js2-msg "msg.not.ctor"
1364 "'%s' is not a constructor.")
1365
1366 ;; FunctionObject
1367 (js2-msg "msg.varargs.ctor"
1368 "Method or constructor '%s' must be static "
1369 "with the signature (Context cx, Object[] args, "
1370 "Function ctorObj, boolean inNewExpr) "
1371 "to define a variable arguments constructor.")
1372
1373 (js2-msg "msg.varargs.fun"
1374 "Method '%s' must be static with the signature "
1375 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1376 "to define a variable arguments function.")
1377
1378 (js2-msg "msg.incompat.call"
1379 "Method '%s' called on incompatible object.")
1380
1381 (js2-msg "msg.bad.parms"
1382 "Unsupported parameter type '%s' in method '%s'.")
1383
1384 (js2-msg "msg.bad.method.return"
1385 "Unsupported return type '%s' in method '%s'.")
1386
1387 (js2-msg "msg.bad.ctor.return"
1388 "Construction of objects of type '%s' is not supported.")
1389
1390 (js2-msg "msg.no.overload"
1391 "Method '%s' occurs multiple times in class '%s'.")
1392
1393 (js2-msg "msg.method.not.found"
1394 "Method '%s' not found in '%s'.")
1395
1396 ;; IRFactory
1397
1398 (js2-msg "msg.bad.for.in.lhs"
1399 "Invalid left-hand side of for..in loop.")
1400
1401 (js2-msg "msg.mult.index"
1402 "Only one variable allowed in for..in loop.")
1403
1404 (js2-msg "msg.bad.for.in.destruct"
1405 "Left hand side of for..in loop must be an array of "
1406 "length 2 to accept key/value pair.")
1407
1408 (js2-msg "msg.cant.convert"
1409 "Can't convert to type '%s'.")
1410
1411 (js2-msg "msg.bad.assign.left"
1412 "Invalid assignment left-hand side.")
1413
1414 (js2-msg "msg.bad.decr"
1415 "Invalid decerement operand.")
1416
1417 (js2-msg "msg.bad.incr"
1418 "Invalid increment operand.")
1419
1420 (js2-msg "msg.bad.yield"
1421 "yield must be in a function.")
1422
1423 (js2-msg "msg.yield.parenthesized"
1424 "yield expression must be parenthesized.")
1425
1426 ;; NativeGlobal
1427 (js2-msg "msg.cant.call.indirect"
1428 "Function '%s' must be called directly, and not by way of a "
1429 "function of another name.")
1430
1431 (js2-msg "msg.eval.nonstring"
1432 "Calling eval() with anything other than a primitive "
1433 "string value will simply return the value. "
1434 "Is this what you intended?")
1435
1436 (js2-msg "msg.eval.nonstring.strict"
1437 "Calling eval() with anything other than a primitive "
1438 "string value is not allowed in strict mode.")
1439
1440 (js2-msg "msg.bad.destruct.op"
1441 "Invalid destructuring assignment operator")
1442
1443 ;; NativeCall
1444 (js2-msg "msg.only.from.new"
1445 "'%s' may only be invoked from a `new' expression.")
1446
1447 (js2-msg "msg.deprec.ctor"
1448 "The '%s' constructor is deprecated.")
1449
1450 ;; NativeFunction
1451 (js2-msg "msg.no.function.ref.found"
1452 "no source found to decompile function reference %s")
1453
1454 (js2-msg "msg.arg.isnt.array"
1455 "second argument to Function.prototype.apply must be an array")
1456
1457 ;; NativeGlobal
1458 (js2-msg "msg.bad.esc.mask"
1459 "invalid string escape mask")
1460
1461 ;; NativeRegExp
1462 (js2-msg "msg.bad.quant"
1463 "Invalid quantifier %s")
1464
1465 (js2-msg "msg.overlarge.backref"
1466 "Overly large back reference %s")
1467
1468 (js2-msg "msg.overlarge.min"
1469 "Overly large minimum %s")
1470
1471 (js2-msg "msg.overlarge.max"
1472 "Overly large maximum %s")
1473
1474 (js2-msg "msg.zero.quant"
1475 "Zero quantifier %s")
1476
1477 (js2-msg "msg.max.lt.min"
1478 "Maximum %s less than minimum")
1479
1480 (js2-msg "msg.unterm.quant"
1481 "Unterminated quantifier %s")
1482
1483 (js2-msg "msg.unterm.paren"
1484 "Unterminated parenthetical %s")
1485
1486 (js2-msg "msg.unterm.class"
1487 "Unterminated character class %s")
1488
1489 (js2-msg "msg.bad.range"
1490 "Invalid range in character class.")
1491
1492 (js2-msg "msg.trail.backslash"
1493 "Trailing \\ in regular expression.")
1494
1495 (js2-msg "msg.re.unmatched.right.paren"
1496 "unmatched ) in regular expression.")
1497
1498 (js2-msg "msg.no.regexp"
1499 "Regular expressions are not available.")
1500
1501 (js2-msg "msg.bad.backref"
1502 "back-reference exceeds number of capturing parentheses.")
1503
1504 (js2-msg "msg.bad.regexp.compile"
1505 "Only one argument may be specified if the first "
1506 "argument to RegExp.prototype.compile is a RegExp object.")
1507
1508 ;; Parser
1509 (js2-msg "msg.got.syntax.errors"
1510 "Compilation produced %s syntax errors.")
1511
1512 (js2-msg "msg.var.redecl"
1513 "TypeError: redeclaration of var %s.")
1514
1515 (js2-msg "msg.const.redecl"
1516 "TypeError: redeclaration of const %s.")
1517
1518 (js2-msg "msg.let.redecl"
1519 "TypeError: redeclaration of variable %s.")
1520
1521 (js2-msg "msg.parm.redecl"
1522 "TypeError: redeclaration of formal parameter %s.")
1523
1524 (js2-msg "msg.fn.redecl"
1525 "TypeError: redeclaration of function %s.")
1526
1527 (js2-msg "msg.let.decl.not.in.block"
1528 "SyntaxError: let declaration not directly within block")
1529
1530 ;; NodeTransformer
1531 (js2-msg "msg.dup.label"
1532 "duplicated label")
1533
1534 (js2-msg "msg.undef.label"
1535 "undefined label")
1536
1537 (js2-msg "msg.bad.break"
1538 "unlabelled break must be inside loop or switch")
1539
1540 (js2-msg "msg.continue.outside"
1541 "continue must be inside loop")
1542
1543 (js2-msg "msg.continue.nonloop"
1544 "continue can only use labels of iteration statements")
1545
1546 (js2-msg "msg.bad.throw.eol"
1547 "Line terminator is not allowed between the throw "
1548 "keyword and throw expression.")
1549
1550 (js2-msg "msg.no.paren.parms"
1551 "missing ( before function parameters.")
1552
1553 (js2-msg "msg.no.parm"
1554 "missing formal parameter")
1555
1556 (js2-msg "msg.no.paren.after.parms"
1557 "missing ) after formal parameters")
1558
1559 (js2-msg "msg.no.brace.body"
1560 "missing '{' before function body")
1561
1562 (js2-msg "msg.no.brace.after.body"
1563 "missing } after function body")
1564
1565 (js2-msg "msg.no.paren.cond"
1566 "missing ( before condition")
1567
1568 (js2-msg "msg.no.paren.after.cond"
1569 "missing ) after condition")
1570
1571 (js2-msg "msg.no.semi.stmt"
1572 "missing ; before statement")
1573
1574 (js2-msg "msg.missing.semi"
1575 "missing ; after statement")
1576
1577 (js2-msg "msg.no.name.after.dot"
1578 "missing name after . operator")
1579
1580 (js2-msg "msg.no.name.after.coloncolon"
1581 "missing name after :: operator")
1582
1583 (js2-msg "msg.no.name.after.dotdot"
1584 "missing name after .. operator")
1585
1586 (js2-msg "msg.no.name.after.xmlAttr"
1587 "missing name after .@")
1588
1589 (js2-msg "msg.no.bracket.index"
1590 "missing ] in index expression")
1591
1592 (js2-msg "msg.no.paren.switch"
1593 "missing ( before switch expression")
1594
1595 (js2-msg "msg.no.paren.after.switch"
1596 "missing ) after switch expression")
1597
1598 (js2-msg "msg.no.brace.switch"
1599 "missing '{' before switch body")
1600
1601 (js2-msg "msg.bad.switch"
1602 "invalid switch statement")
1603
1604 (js2-msg "msg.no.colon.case"
1605 "missing : after case expression")
1606
1607 (js2-msg "msg.double.switch.default"
1608 "double default label in the switch statement")
1609
1610 (js2-msg "msg.no.while.do"
1611 "missing while after do-loop body")
1612
1613 (js2-msg "msg.no.paren.for"
1614 "missing ( after for")
1615
1616 (js2-msg "msg.no.semi.for"
1617 "missing ; after for-loop initializer")
1618
1619 (js2-msg "msg.no.semi.for.cond"
1620 "missing ; after for-loop condition")
1621
1622 (js2-msg "msg.in.after.for.name"
1623 "missing in after for")
1624
1625 (js2-msg "msg.no.paren.for.ctrl"
1626 "missing ) after for-loop control")
1627
1628 (js2-msg "msg.no.paren.with"
1629 "missing ( before with-statement object")
1630
1631 (js2-msg "msg.no.paren.after.with"
1632 "missing ) after with-statement object")
1633
1634 (js2-msg "msg.no.paren.after.let"
1635 "missing ( after let")
1636
1637 (js2-msg "msg.no.paren.let"
1638 "missing ) after variable list")
1639
1640 (js2-msg "msg.no.curly.let"
1641 "missing } after let statement")
1642
1643 (js2-msg "msg.bad.return"
1644 "invalid return")
1645
1646 (js2-msg "msg.no.brace.block"
1647 "missing } in compound statement")
1648
1649 (js2-msg "msg.bad.label"
1650 "invalid label")
1651
1652 (js2-msg "msg.bad.var"
1653 "missing variable name")
1654
1655 (js2-msg "msg.bad.var.init"
1656 "invalid variable initialization")
1657
1658 (js2-msg "msg.no.colon.cond"
1659 "missing : in conditional expression")
1660
1661 (js2-msg "msg.no.paren.arg"
1662 "missing ) after argument list")
1663
1664 (js2-msg "msg.no.bracket.arg"
1665 "missing ] after element list")
1666
1667 (js2-msg "msg.bad.prop"
1668 "invalid property id")
1669
1670 (js2-msg "msg.no.colon.prop"
1671 "missing : after property id")
1672
1673 (js2-msg "msg.no.brace.prop"
1674 "missing } after property list")
1675
1676 (js2-msg "msg.no.paren"
1677 "missing ) in parenthetical")
1678
1679 (js2-msg "msg.reserved.id"
1680 "identifier is a reserved word")
1681
1682 (js2-msg "msg.no.paren.catch"
1683 "missing ( before catch-block condition")
1684
1685 (js2-msg "msg.bad.catchcond"
1686 "invalid catch block condition")
1687
1688 (js2-msg "msg.catch.unreachable"
1689 "any catch clauses following an unqualified catch are unreachable")
1690
1691 (js2-msg "msg.no.brace.try"
1692 "missing '{' before try block")
1693
1694 (js2-msg "msg.no.brace.catchblock"
1695 "missing '{' before catch-block body")
1696
1697 (js2-msg "msg.try.no.catchfinally"
1698 "'try' without 'catch' or 'finally'")
1699
1700 (js2-msg "msg.no.return.value"
1701 "function %s does not always return a value")
1702
1703 (js2-msg "msg.anon.no.return.value"
1704 "anonymous function does not always return a value")
1705
1706 (js2-msg "msg.return.inconsistent"
1707 "return statement is inconsistent with previous usage")
1708
1709 (js2-msg "msg.generator.returns"
1710 "TypeError: generator function '%s' returns a value")
1711
1712 (js2-msg "msg.anon.generator.returns"
1713 "TypeError: anonymous generator function returns a value")
1714
1715 (js2-msg "msg.syntax"
1716 "syntax error")
1717
1718 (js2-msg "msg.unexpected.eof"
1719 "Unexpected end of file")
1720
1721 (js2-msg "msg.XML.bad.form"
1722 "illegally formed XML syntax")
1723
1724 (js2-msg "msg.XML.not.available"
1725 "XML runtime not available")
1726
1727 (js2-msg "msg.too.deep.parser.recursion"
1728 "Too deep recursion while parsing")
1729
1730 (js2-msg "msg.no.side.effects"
1731 "Code has no side effects")
1732
1733 (js2-msg "msg.extra.trailing.comma"
1734 "Trailing comma is not legal in an ECMA-262 object initializer")
1735
1736 (js2-msg "msg.array.trailing.comma"
1737 "Trailing comma yields different behavior across browsers")
1738
1739 (js2-msg "msg.equal.as.assign"
1740 (concat "Test for equality (==) mistyped as assignment (=)?"
1741 " (parenthesize to suppress warning)"))
1742
1743 (js2-msg "msg.var.hides.arg"
1744 "Variable %s hides argument")
1745
1746 (js2-msg "msg.destruct.assign.no.init"
1747 "Missing = in destructuring declaration")
1748
1749 ;; ScriptRuntime
1750 (js2-msg "msg.no.properties"
1751 "%s has no properties.")
1752
1753 (js2-msg "msg.invalid.iterator"
1754 "Invalid iterator value")
1755
1756 (js2-msg "msg.iterator.primitive"
1757 "__iterator__ returned a primitive value")
1758
1759 (js2-msg "msg.assn.create.strict"
1760 "Assignment to undeclared variable %s")
1761
1762 (js2-msg "msg.ref.undefined.prop"
1763 "Reference to undefined property '%s'")
1764
1765 (js2-msg "msg.prop.not.found"
1766 "Property %s not found.")
1767
1768 (js2-msg "msg.invalid.type"
1769 "Invalid JavaScript value of type %s")
1770
1771 (js2-msg "msg.primitive.expected"
1772 "Primitive type expected (had %s instead)")
1773
1774 (js2-msg "msg.namespace.expected"
1775 "Namespace object expected to left of :: (found %s instead)")
1776
1777 (js2-msg "msg.null.to.object"
1778 "Cannot convert null to an object.")
1779
1780 (js2-msg "msg.undef.to.object"
1781 "Cannot convert undefined to an object.")
1782
1783 (js2-msg "msg.cyclic.value"
1784 "Cyclic %s value not allowed.")
1785
1786 (js2-msg "msg.is.not.defined"
1787 "'%s' is not defined.")
1788
1789 (js2-msg "msg.undef.prop.read"
1790 "Cannot read property '%s' from %s")
1791
1792 (js2-msg "msg.undef.prop.write"
1793 "Cannot set property '%s' of %s to '%s'")
1794
1795 (js2-msg "msg.undef.prop.delete"
1796 "Cannot delete property '%s' of %s")
1797
1798 (js2-msg "msg.undef.method.call"
1799 "Cannot call method '%s' of %s")
1800
1801 (js2-msg "msg.undef.with"
1802 "Cannot apply 'with' to %s")
1803
1804 (js2-msg "msg.isnt.function"
1805 "%s is not a function, it is %s.")
1806
1807 (js2-msg "msg.isnt.function.in"
1808 "Cannot call property %s in object %s. "
1809 "It is not a function, it is '%s'.")
1810
1811 (js2-msg "msg.function.not.found"
1812 "Cannot find function %s.")
1813
1814 (js2-msg "msg.function.not.found.in"
1815 "Cannot find function %s in object %s.")
1816
1817 (js2-msg "msg.isnt.xml.object"
1818 "%s is not an xml object.")
1819
1820 (js2-msg "msg.no.ref.to.get"
1821 "%s is not a reference to read reference value.")
1822
1823 (js2-msg "msg.no.ref.to.set"
1824 "%s is not a reference to set reference value to %s.")
1825
1826 (js2-msg "msg.no.ref.from.function"
1827 "Function %s can not be used as the left-hand "
1828 "side of assignment or as an operand of ++ or -- operator.")
1829
1830 (js2-msg "msg.bad.default.value"
1831 "Object's getDefaultValue() method returned an object.")
1832
1833 (js2-msg "msg.instanceof.not.object"
1834 "Can't use instanceof on a non-object.")
1835
1836 (js2-msg "msg.instanceof.bad.prototype"
1837 "'prototype' property of %s is not an object.")
1838
1839 (js2-msg "msg.bad.radix"
1840 "illegal radix %s.")
1841
1842 ;; ScriptableObject
1843 (js2-msg "msg.default.value"
1844 "Cannot find default value for object.")
1845
1846 (js2-msg "msg.zero.arg.ctor"
1847 "Cannot load class '%s' which has no zero-parameter constructor.")
1848
1849 (js2-msg "msg.ctor.multiple.parms"
1850 "Can't define constructor or class %s since more than "
1851 "one constructor has multiple parameters.")
1852
1853 (js2-msg "msg.extend.scriptable"
1854 "%s must extend ScriptableObject in order to define property %s.")
1855
1856 (js2-msg "msg.bad.getter.parms"
1857 "In order to define a property, getter %s must have zero "
1858 "parameters or a single ScriptableObject parameter.")
1859
1860 (js2-msg "msg.obj.getter.parms"
1861 "Expected static or delegated getter %s to take "
1862 "a ScriptableObject parameter.")
1863
1864 (js2-msg "msg.getter.static"
1865 "Getter and setter must both be static or neither be static.")
1866
1867 (js2-msg "msg.setter.return"
1868 "Setter must have void return type: %s")
1869
1870 (js2-msg "msg.setter2.parms"
1871 "Two-parameter setter must take a ScriptableObject as "
1872 "its first parameter.")
1873
1874 (js2-msg "msg.setter1.parms"
1875 "Expected single parameter setter for %s")
1876
1877 (js2-msg "msg.setter2.expected"
1878 "Expected static or delegated setter %s to take two parameters.")
1879
1880 (js2-msg "msg.setter.parms"
1881 "Expected either one or two parameters for setter.")
1882
1883 (js2-msg "msg.setter.bad.type"
1884 "Unsupported parameter type '%s' in setter '%s'.")
1885
1886 (js2-msg "msg.add.sealed"
1887 "Cannot add a property to a sealed object: %s.")
1888
1889 (js2-msg "msg.remove.sealed"
1890 "Cannot remove a property from a sealed object: %s.")
1891
1892 (js2-msg "msg.modify.sealed"
1893 "Cannot modify a property of a sealed object: %s.")
1894
1895 (js2-msg "msg.modify.readonly"
1896 "Cannot modify readonly property: %s.")
1897
1898 ;; TokenStream
1899 (js2-msg "msg.missing.exponent"
1900 "missing exponent")
1901
1902 (js2-msg "msg.caught.nfe"
1903 "number format error")
1904
1905 (js2-msg "msg.unterminated.string.lit"
1906 "unterminated string literal")
1907
1908 (js2-msg "msg.unterminated.comment"
1909 "unterminated comment")
1910
1911 (js2-msg "msg.unterminated.re.lit"
1912 "unterminated regular expression literal")
1913
1914 (js2-msg "msg.invalid.re.flag"
1915 "invalid flag after regular expression")
1916
1917 (js2-msg "msg.no.re.input.for"
1918 "no input for %s")
1919
1920 (js2-msg "msg.illegal.character"
1921 "illegal character")
1922
1923 (js2-msg "msg.invalid.escape"
1924 "invalid Unicode escape sequence")
1925
1926 (js2-msg "msg.bad.namespace"
1927 "not a valid default namespace statement. "
1928 "Syntax is: default xml namespace = EXPRESSION;")
1929
1930 ;; TokensStream warnings
1931 (js2-msg "msg.bad.octal.literal"
1932 "illegal octal literal digit %s; "
1933 "interpreting it as a decimal digit")
1934
1935 (js2-msg "msg.reserved.keyword"
1936 "illegal usage of future reserved keyword %s; "
1937 "interpreting it as ordinary identifier")
1938
1939 (js2-msg "msg.script.is.not.constructor"
1940 "Script objects are not constructors.")
1941
1942 ;; Arrays
1943 (js2-msg "msg.arraylength.bad"
1944 "Inappropriate array length.")
1945
1946 ;; Arrays
1947 (js2-msg "msg.arraylength.too.big"
1948 "Array length %s exceeds supported capacity limit.")
1949
1950 ;; URI
1951 (js2-msg "msg.bad.uri"
1952 "Malformed URI sequence.")
1953
1954 ;; Number
1955 (js2-msg "msg.bad.precision"
1956 "Precision %s out of range.")
1957
1958 ;; NativeGenerator
1959 (js2-msg "msg.send.newborn"
1960 "Attempt to send value to newborn generator")
1961
1962 (js2-msg "msg.already.exec.gen"
1963 "Already executing generator")
1964
1965 (js2-msg "msg.StopIteration.invalid"
1966 "StopIteration may not be changed to an arbitrary object.")
1967
1968 ;; Interpreter
1969 (js2-msg "msg.yield.closing"
1970 "Yield from closing generator")
1971
1972 ;;; Utilities
1973
1974 (defun js2-delete-if (predicate list)
1975 "Remove all items satisfying PREDICATE in LIST."
1976 (loop for item in list
1977 if (not (funcall predicate item))
1978 collect item))
1979
1980 (defun js2-position (element list)
1981 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1982 Returns nil if element is not found in the list."
1983 (let ((count 0)
1984 found)
1985 (while (and list (not found))
1986 (if (eq element (car list))
1987 (setq found t)
1988 (setq count (1+ count)
1989 list (cdr list))))
1990 (if found count)))
1991
1992 (defun js2-find-if (predicate list)
1993 "Find first item satisfying PREDICATE in LIST."
1994 (let (result)
1995 (while (and list (not result))
1996 (if (funcall predicate (car list))
1997 (setq result (car list)))
1998 (setq list (cdr list)))
1999 result))
2000
2001 (defmacro js2-time (form)
2002 "Evaluate FORM, discard result, and return elapsed time in sec"
2003 (declare (debug t))
2004 (let ((beg (make-symbol "--js2-time-beg--"))
2005 (delta (make-symbol "--js2-time-end--")))
2006 `(let ((,beg (current-time))
2007 ,delta)
2008 ,form
2009 (/ (truncate (* (- (float-time (current-time))
2010 (float-time ,beg))
2011 10000))
2012 10000.0))))
2013
2014 (defsubst js2-same-line (pos)
2015 "Return t if POS is on the same line as current point."
2016 (and (>= pos (point-at-bol))
2017 (<= pos (point-at-eol))))
2018
2019 (defsubst js2-same-line-2 (p1 p2)
2020 "Return t if p1 is on the same line as p2."
2021 (save-excursion
2022 (goto-char p1)
2023 (js2-same-line p2)))
2024
2025 (defun js2-code-bug ()
2026 "Signal an error when we encounter an unexpected code path."
2027 (error "failed assertion"))
2028
2029 (defsubst js2-record-text-property (beg end prop value)
2030 "Record a text property to set when parsing finishes."
2031 (push (list beg end prop value) js2-mode-deferred-properties))
2032
2033 ;; I'd like to associate errors with nodes, but for now the
2034 ;; easiest thing to do is get the context info from the last token.
2035 (defsubst js2-record-parse-error (msg &optional arg pos len)
2036 (push (list (list msg arg)
2037 (or pos js2-token-beg)
2038 (or len (- js2-token-end js2-token-beg)))
2039 js2-parsed-errors))
2040
2041 (defsubst js2-report-error (msg &optional msg-arg pos len)
2042 "Signal a syntax error or record a parse error."
2043 (if js2-recover-from-parse-errors
2044 (js2-record-parse-error msg msg-arg pos len)
2045 (signal 'js2-syntax-error
2046 (list msg
2047 js2-ts-lineno
2048 (save-excursion
2049 (goto-char js2-ts-cursor)
2050 (current-column))
2051 js2-ts-hit-eof))))
2052
2053 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2054 (if js2-compiler-report-warning-as-error
2055 (js2-report-error msg msg-arg pos len)
2056 (push (list (list msg msg-arg)
2057 (or pos js2-token-beg)
2058 (or len (- js2-token-end js2-token-beg)))
2059 js2-parsed-warnings)))
2060
2061 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2062 (if js2-compiler-strict-mode
2063 (js2-report-warning msg-id msg-arg beg
2064 (and beg end (- end beg)))))
2065
2066 (put 'js2-syntax-error 'error-conditions
2067 '(error syntax-error js2-syntax-error))
2068 (put 'js2-syntax-error 'error-message "Syntax error")
2069
2070 (put 'js2-parse-error 'error-conditions
2071 '(error parse-error js2-parse-error))
2072 (put 'js2-parse-error 'error-message "Parse error")
2073
2074 (defmacro js2-clear-flag (flags flag)
2075 `(setq ,flags (logand ,flags (lognot ,flag))))
2076
2077 (defmacro js2-set-flag (flags flag)
2078 "Logical-or FLAG into FLAGS."
2079 `(setq ,flags (logior ,flags ,flag)))
2080
2081 (defsubst js2-flag-set-p (flags flag)
2082 (/= 0 (logand flags flag)))
2083
2084 (defsubst js2-flag-not-set-p (flags flag)
2085 (zerop (logand flags flag)))
2086
2087 ;; Stolen shamelessly from James Clark's nxml-mode.
2088 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2089 "Evaluate BODY without any text property changes modifying the buffer.
2090 Any text properties changes happen as usual but the changes are not treated as
2091 modifications to the buffer."
2092 (declare (indent 0) (debug t))
2093 (let ((modified (make-symbol "modified")))
2094 `(let ((,modified (buffer-modified-p))
2095 (inhibit-read-only t)
2096 (inhibit-modification-hooks t)
2097 (buffer-undo-list t)
2098 (deactivate-mark nil)
2099 ;; Apparently these avoid file locking problems.
2100 (buffer-file-name nil)
2101 (buffer-file-truename nil))
2102 (unwind-protect
2103 (progn ,@body)
2104 (unless ,modified
2105 (restore-buffer-modified-p nil))))))
2106
2107 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2108 "Evaluate BODY with the _ character set to be word-syntax."
2109 (declare (indent 0) (debug t))
2110 (let ((old-syntax (make-symbol "old-syntax")))
2111 `(let ((,old-syntax (string (char-syntax ?_))))
2112 (unwind-protect
2113 (progn
2114 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2115 ,@body)
2116 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2117
2118 (defsubst js2-char-uppercase-p (c)
2119 "Return t if C is an uppercase character.
2120 Handles unicode and latin chars properly."
2121 (/= c (downcase c)))
2122
2123 (defsubst js2-char-lowercase-p (c)
2124 "Return t if C is an uppercase character.
2125 Handles unicode and latin chars properly."
2126 (/= c (upcase c)))
2127
2128 ;;; AST struct and function definitions
2129
2130 ;; flags for ast node property 'member-type (used for e4x operators)
2131 (defvar js2-property-flag #x1 "property access: element is valid name")
2132 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2133 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2134
2135 (defsubst js2-relpos (pos anchor)
2136 "Convert POS to be relative to ANCHOR.
2137 If POS is nil, returns nil."
2138 (and pos (- pos anchor)))
2139
2140 (defsubst js2-make-pad (indent)
2141 (if (zerop indent)
2142 ""
2143 (make-string (* indent js2-basic-offset) ? )))
2144
2145 (defsubst js2-visit-ast (node callback)
2146 "Visit every node in ast NODE with visitor CALLBACK.
2147
2148 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2149 called twice: once to visit the node, and again after all the node's
2150 children have been processed. The END-P argument is nil on the first
2151 call and non-nil on the second call. The return value of the callback
2152 affects the traversal: if non-nil, the children of NODE are processed.
2153 If the callback returns nil, or if the node has no children, then the
2154 callback is called immediately with a non-nil END-P argument.
2155
2156 The node traversal is approximately lexical-order, although there
2157 are currently no guarantees around this."
2158 (if node
2159 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2160 ;; visit the node
2161 (when (funcall callback node nil)
2162 ;; visit the kids
2163 (cond
2164 ((eq vfunc 'js2-visit-none)
2165 nil) ; don't even bother calling it
2166 ;; Each AST node type has to define a `js2-visitor' function
2167 ;; that takes a node and a callback, and calls `js2-visit-ast'
2168 ;; on each child of the node.
2169 (vfunc
2170 (funcall vfunc node callback))
2171 (t
2172 (error "%s does not define a visitor-traversal function"
2173 (aref node 0)))))
2174 ;; call the end-visit
2175 (funcall callback node t))))
2176
2177 (defstruct (js2-node
2178 (:constructor nil)) ; abstract
2179 "Base AST node type."
2180 (type -1) ; token type
2181 (pos -1) ; start position of this AST node in parsed input
2182 (len 1) ; num characters spanned by the node
2183 props ; optional node property list (an alist)
2184 parent) ; link to parent node; null for root
2185
2186 (defsubst js2-node-get-prop (node prop &optional default)
2187 (or (cadr (assoc prop (js2-node-props node))) default))
2188
2189 (defsubst js2-node-set-prop (node prop value)
2190 (setf (js2-node-props node)
2191 (cons (list prop value) (js2-node-props node))))
2192
2193 (defsubst js2-fixup-starts (n nodes)
2194 "Adjust the start positions of NODES to be relative to N.
2195 Any node in the list may be nil, for convenience."
2196 (dolist (node nodes)
2197 (when node
2198 (setf (js2-node-pos node) (- (js2-node-pos node)
2199 (js2-node-pos n))))))
2200
2201 (defsubst js2-node-add-children (parent &rest nodes)
2202 "Set parent node of NODES to PARENT, and return PARENT.
2203 Does nothing if we're not recording parent links.
2204 If any given node in NODES is nil, doesn't record that link."
2205 (js2-fixup-starts parent nodes)
2206 (dolist (node nodes)
2207 (and node
2208 (setf (js2-node-parent node) parent))))
2209
2210 ;; Non-recursive since it's called a frightening number of times.
2211 (defsubst js2-node-abs-pos (n)
2212 (let ((pos (js2-node-pos n)))
2213 (while (setq n (js2-node-parent n))
2214 (setq pos (+ pos (js2-node-pos n))))
2215 pos))
2216
2217 (defsubst js2-node-abs-end (n)
2218 "Return absolute buffer position of end of N."
2219 (+ (js2-node-abs-pos n) (js2-node-len n)))
2220
2221 ;; It's important to make sure block nodes have a lisp list for the
2222 ;; child nodes, to limit printing recursion depth in an AST that
2223 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2224 ;; a sufficiently large vector tree.
2225
2226 (defstruct (js2-block-node
2227 (:include js2-node)
2228 (:constructor nil)
2229 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2230 (pos js2-token-beg)
2231 len
2232 props
2233 kids)))
2234 "A block of statements."
2235 kids) ; a lisp list of the child statement nodes
2236
2237 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2238 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2239
2240 (defsubst js2-visit-block (ast callback)
2241 "Visit the `js2-block-node' children of AST."
2242 (dolist (kid (js2-block-node-kids ast))
2243 (js2-visit-ast kid callback)))
2244
2245 (defun js2-print-block (n i)
2246 (let ((pad (js2-make-pad i)))
2247 (insert pad "{\n")
2248 (dolist (kid (js2-block-node-kids n))
2249 (js2-print-ast kid (1+ i)))
2250 (insert pad "}")))
2251
2252 (defstruct (js2-scope
2253 (:include js2-block-node)
2254 (:constructor nil)
2255 (:constructor make-js2-scope (&key (type js2-BLOCK)
2256 (pos js2-token-beg)
2257 len
2258 kids)))
2259 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2260 ;; I don't have one of those handy, so I'll use an alist for now.
2261 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2262 ;; and is much lighter-weight to construct (both CPU and mem).
2263 ;; The keys are interned strings (symbols) for faster lookup.
2264 ;; Should switch to hybrid alist/hashtable eventually.
2265 symbol-table ; an alist of (symbol . js2-symbol)
2266 parent-scope ; a `js2-scope'
2267 top) ; top-level `js2-scope' (script/function)
2268
2269 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2270 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2271
2272 (defun js2-scope-set-parent-scope (scope parent)
2273 (setf (js2-scope-parent-scope scope) parent
2274 (js2-scope-top scope) (if (null parent)
2275 scope
2276 (js2-scope-top parent))))
2277
2278 (defun js2-node-get-enclosing-scope (node)
2279 "Return the innermost `js2-scope' node surrounding NODE.
2280 Returns nil if there is no enclosing scope node."
2281 (let ((parent (js2-node-parent node)))
2282 (while (not (js2-scope-p parent))
2283 (setq parent (js2-node-parent parent)))
2284 parent))
2285
2286 (defun js2-get-defining-scope (scope name)
2287 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2288 Returns `js2-scope' in which NAME is defined, or nil if not found."
2289 (let ((sym (if (symbolp name)
2290 name
2291 (intern name)))
2292 table
2293 result
2294 (continue t))
2295 (while (and scope continue)
2296 (if (and (setq table (js2-scope-symbol-table scope))
2297 (assq sym table))
2298 (setq continue nil
2299 result scope)
2300 (setq scope (js2-scope-parent-scope scope))))
2301 result))
2302
2303 (defsubst js2-scope-get-symbol (scope name)
2304 "Return symbol table entry for NAME in SCOPE.
2305 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2306 (and (js2-scope-symbol-table scope)
2307 (cdr (assq (if (symbolp name)
2308 name
2309 (intern name))
2310 (js2-scope-symbol-table scope)))))
2311
2312 (defsubst js2-scope-put-symbol (scope name symbol)
2313 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2314 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2315 (let* ((table (js2-scope-symbol-table scope))
2316 (sym (if (symbolp name) name (intern name)))
2317 (entry (assq sym table)))
2318 (if entry
2319 (setcdr entry symbol)
2320 (push (cons sym symbol)
2321 (js2-scope-symbol-table scope)))))
2322
2323 (defstruct (js2-symbol
2324 (:constructor nil)
2325 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2326 "A symbol table entry."
2327 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2328 ;; js2-LET, or js2-CONST
2329 decl-type
2330 name ; string
2331 ast-node) ; a `js2-node'
2332
2333 (defstruct (js2-error-node
2334 (:include js2-node)
2335 (:constructor nil) ; silence emacs21 byte-compiler
2336 (:constructor make-js2-error-node (&key (type js2-ERROR)
2337 (pos js2-token-beg)
2338 len)))
2339 "AST node representing a parse error.")
2340
2341 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2342 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2343
2344 (defstruct (js2-script-node
2345 (:include js2-scope)
2346 (:constructor nil)
2347 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2348 (pos js2-token-beg)
2349 len
2350 var-decls
2351 fun-decls)))
2352 functions ; lisp list of nested functions
2353 regexps ; lisp list of (string . flags)
2354 symbols ; alist (every symbol gets unique index)
2355 (param-count 0)
2356 var-names ; vector of string names
2357 consts ; bool-vector matching var-decls
2358 (temp-number 0)) ; for generating temp variables
2359
2360 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2361 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2362
2363 (defun js2-print-script (node indent)
2364 (dolist (kid (js2-block-node-kids node))
2365 (js2-print-ast kid indent)))
2366
2367 (defstruct (js2-ast-root
2368 (:include js2-script-node)
2369 (:constructor nil)
2370 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2371 (pos js2-token-beg)
2372 len
2373 buffer)))
2374 "The root node of a js2 AST."
2375 buffer ; the source buffer from which the code was parsed
2376 comments ; a lisp list of comments, ordered by start position
2377 errors ; a lisp list of errors found during parsing
2378 warnings ; a lisp list of warnings found during parsing
2379 node-count) ; number of nodes in the tree, including the root
2380
2381 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2382 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2383
2384 (defun js2-visit-ast-root (ast callback)
2385 (dolist (kid (js2-ast-root-kids ast))
2386 (js2-visit-ast kid callback))
2387 (dolist (comment (js2-ast-root-comments ast))
2388 (js2-visit-ast comment callback)))
2389
2390 (defstruct (js2-comment-node
2391 (:include js2-node)
2392 (:constructor nil)
2393 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2394 (pos js2-token-beg)
2395 len
2396 (format js2-ts-comment-type))))
2397 format) ; 'line, 'block, 'jsdoc or 'html
2398
2399 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2400 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2401
2402 (defun js2-print-comment (n i)
2403 ;; We really ought to link end-of-line comments to their nodes.
2404 ;; Or maybe we could add a new comment type, 'endline.
2405 (insert (js2-make-pad i)
2406 (js2-node-string n)))
2407
2408 (defstruct (js2-expr-stmt-node
2409 (:include js2-node)
2410 (:constructor nil)
2411 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2412 (pos js2-ts-cursor)
2413 len
2414 expr)))
2415 "An expression statement."
2416 expr)
2417
2418 (defsubst js2-expr-stmt-node-set-has-result (node)
2419 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2420 (setf (js2-node-type node) js2-EXPR_RESULT))
2421
2422 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2423 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2424
2425 (defun js2-visit-expr-stmt-node (n v)
2426 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2427
2428 (defun js2-print-expr-stmt-node (n indent)
2429 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2430 (insert ";\n"))
2431
2432 (defstruct (js2-loop-node
2433 (:include js2-scope)
2434 (:constructor nil))
2435 "Abstract supertype of loop nodes."
2436 body ; a `js2-block-node'
2437 lp ; position of left-paren, nil if omitted
2438 rp) ; position of right-paren, nil if omitted
2439
2440 (defstruct (js2-do-node
2441 (:include js2-loop-node)
2442 (:constructor nil)
2443 (:constructor make-js2-do-node (&key (type js2-DO)
2444 (pos js2-token-beg)
2445 len
2446 body
2447 condition
2448 while-pos
2449 lp
2450 rp)))
2451 "AST node for do-loop."
2452 condition ; while (expression)
2453 while-pos) ; buffer position of 'while' keyword
2454
2455 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2456 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2457
2458 (defun js2-visit-do-node (n v)
2459 (js2-visit-ast (js2-do-node-body n) v)
2460 (js2-visit-ast (js2-do-node-condition n) v))
2461
2462 (defun js2-print-do-node (n i)
2463 (let ((pad (js2-make-pad i)))
2464 (insert pad "do {\n")
2465 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2466 (js2-print-ast kid (1+ i)))
2467 (insert pad "} while (")
2468 (js2-print-ast (js2-do-node-condition n) 0)
2469 (insert ");\n")))
2470
2471 (defstruct (js2-while-node
2472 (:include js2-loop-node)
2473 (:constructor nil)
2474 (:constructor make-js2-while-node (&key (type js2-WHILE)
2475 (pos js2-token-beg)
2476 len
2477 body
2478 condition
2479 lp
2480 rp)))
2481 "AST node for while-loop."
2482 condition) ; while-condition
2483
2484 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2485 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2486
2487 (defun js2-visit-while-node (n v)
2488 (js2-visit-ast (js2-while-node-condition n) v)
2489 (js2-visit-ast (js2-while-node-body n) v))
2490
2491 (defun js2-print-while-node (n i)
2492 (let ((pad (js2-make-pad i)))
2493 (insert pad "while (")
2494 (js2-print-ast (js2-while-node-condition n) 0)
2495 (insert ") {\n")
2496 (js2-print-body (js2-while-node-body n) (1+ i))
2497 (insert pad "}\n")))
2498
2499 (defstruct (js2-for-node
2500 (:include js2-loop-node)
2501 (:constructor nil)
2502 (:constructor make-js2-for-node (&key (type js2-FOR)
2503 (pos js2-ts-cursor)
2504 len
2505 body
2506 init
2507 condition
2508 update
2509 lp
2510 rp)))
2511 "AST node for a C-style for-loop."
2512 init ; initialization expression
2513 condition ; loop condition
2514 update) ; update clause
2515
2516 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2517 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2518
2519 (defun js2-visit-for-node (n v)
2520 (js2-visit-ast (js2-for-node-init n) v)
2521 (js2-visit-ast (js2-for-node-condition n) v)
2522 (js2-visit-ast (js2-for-node-update n) v)
2523 (js2-visit-ast (js2-for-node-body n) v))
2524
2525 (defun js2-print-for-node (n i)
2526 (let ((pad (js2-make-pad i)))
2527 (insert pad "for (")
2528 (js2-print-ast (js2-for-node-init n) 0)
2529 (insert "; ")
2530 (js2-print-ast (js2-for-node-condition n) 0)
2531 (insert "; ")
2532 (js2-print-ast (js2-for-node-update n) 0)
2533 (insert ") {\n")
2534 (js2-print-body (js2-for-node-body n) (1+ i))
2535 (insert pad "}\n")))
2536
2537 (defstruct (js2-for-in-node
2538 (:include js2-loop-node)
2539 (:constructor nil)
2540 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2541 (pos js2-ts-cursor)
2542 len
2543 body
2544 iterator
2545 object
2546 in-pos
2547 each-pos
2548 foreach-p
2549 lp
2550 rp)))
2551 "AST node for a for..in loop."
2552 iterator ; [var] foo in ...
2553 object ; object over which we're iterating
2554 in-pos ; buffer position of 'in' keyword
2555 each-pos ; buffer position of 'each' keyword, if foreach-p
2556 foreach-p) ; t if it's a for-each loop
2557
2558 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2559 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2560
2561 (defun js2-visit-for-in-node (n v)
2562 (js2-visit-ast (js2-for-in-node-iterator n) v)
2563 (js2-visit-ast (js2-for-in-node-object n) v)
2564 (js2-visit-ast (js2-for-in-node-body n) v))
2565
2566 (defun js2-print-for-in-node (n i)
2567 (let ((pad (js2-make-pad i))
2568 (foreach (js2-for-in-node-foreach-p n)))
2569 (insert pad "for ")
2570 (if foreach
2571 (insert "each "))
2572 (insert "(")
2573 (js2-print-ast (js2-for-in-node-iterator n) 0)
2574 (insert " in ")
2575 (js2-print-ast (js2-for-in-node-object n) 0)
2576 (insert ") {\n")
2577 (js2-print-body (js2-for-in-node-body n) (1+ i))
2578 (insert pad "}\n")))
2579
2580 (defstruct (js2-return-node
2581 (:include js2-node)
2582 (:constructor nil)
2583 (:constructor make-js2-return-node (&key (type js2-RETURN)
2584 (pos js2-ts-cursor)
2585 len
2586 retval)))
2587 "AST node for a return statement."
2588 retval) ; expression to return, or 'undefined
2589
2590 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2591 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2592
2593 (defun js2-visit-return-node (n v)
2594 (js2-visit-ast (js2-return-node-retval n) v))
2595
2596 (defun js2-print-return-node (n i)
2597 (insert (js2-make-pad i) "return")
2598 (when (js2-return-node-retval n)
2599 (insert " ")
2600 (js2-print-ast (js2-return-node-retval n) 0))
2601 (insert ";\n"))
2602
2603 (defstruct (js2-if-node
2604 (:include js2-node)
2605 (:constructor nil)
2606 (:constructor make-js2-if-node (&key (type js2-IF)
2607 (pos js2-ts-cursor)
2608 len
2609 condition
2610 then-part
2611 else-pos
2612 else-part
2613 lp
2614 rp)))
2615 "AST node for an if-statement."
2616 condition ; expression
2617 then-part ; statement or block
2618 else-pos ; optional buffer position of 'else' keyword
2619 else-part ; optional statement or block
2620 lp ; position of left-paren, nil if omitted
2621 rp) ; position of right-paren, nil if omitted
2622
2623 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2624 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2625
2626 (defun js2-visit-if-node (n v)
2627 (js2-visit-ast (js2-if-node-condition n) v)
2628 (js2-visit-ast (js2-if-node-then-part n) v)
2629 (js2-visit-ast (js2-if-node-else-part n) v))
2630
2631 (defun js2-print-if-node (n i)
2632 (let ((pad (js2-make-pad i))
2633 (then-part (js2-if-node-then-part n))
2634 (else-part (js2-if-node-else-part n)))
2635 (insert pad "if (")
2636 (js2-print-ast (js2-if-node-condition n) 0)
2637 (insert ") {\n")
2638 (js2-print-body then-part (1+ i))
2639 (insert pad "}")
2640 (cond
2641 ((not else-part)
2642 (insert "\n"))
2643 ((js2-if-node-p else-part)
2644 (insert " else ")
2645 (js2-print-body else-part i))
2646 (t
2647 (insert " else {\n")
2648 (js2-print-body else-part (1+ i))
2649 (insert pad "}\n")))))
2650
2651 (defstruct (js2-try-node
2652 (:include js2-node)
2653 (:constructor nil)
2654 (:constructor make-js2-try-node (&key (type js2-TRY)
2655 (pos js2-ts-cursor)
2656 len
2657 try-block
2658 catch-clauses
2659 finally-block)))
2660 "AST node for a try-statement."
2661 try-block
2662 catch-clauses ; a lisp list of `js2-catch-node'
2663 finally-block) ; a `js2-finally-node'
2664
2665 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2666 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2667
2668 (defun js2-visit-try-node (n v)
2669 (js2-visit-ast (js2-try-node-try-block n) v)
2670 (dolist (clause (js2-try-node-catch-clauses n))
2671 (js2-visit-ast clause v))
2672 (js2-visit-ast (js2-try-node-finally-block n) v))
2673
2674 (defun js2-print-try-node (n i)
2675 (let ((pad (js2-make-pad i))
2676 (catches (js2-try-node-catch-clauses n))
2677 (finally (js2-try-node-finally-block n)))
2678 (insert pad "try {\n")
2679 (js2-print-body (js2-try-node-try-block n) (1+ i))
2680 (insert pad "}")
2681 (when catches
2682 (dolist (catch catches)
2683 (js2-print-ast catch i)))
2684 (if finally
2685 (js2-print-ast finally i)
2686 (insert "\n"))))
2687
2688 (defstruct (js2-catch-node
2689 (:include js2-node)
2690 (:constructor nil)
2691 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2692 (pos js2-ts-cursor)
2693 len
2694 param
2695 guard-kwd
2696 guard-expr
2697 block
2698 lp
2699 rp)))
2700 "AST node for a catch clause."
2701 param ; destructuring form or simple name node
2702 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2703 guard-expr ; catch condition, a `js2-node'
2704 block ; statements, a `js2-block-node'
2705 lp ; buffer position of left-paren, nil if omitted
2706 rp) ; buffer position of right-paren, nil if omitted
2707
2708 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2709 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2710
2711 (defun js2-visit-catch-node (n v)
2712 (js2-visit-ast (js2-catch-node-param n) v)
2713 (when (js2-catch-node-guard-kwd n)
2714 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2715 (js2-visit-ast (js2-catch-node-block n) v))
2716
2717 (defun js2-print-catch-node (n i)
2718 (let ((pad (js2-make-pad i))
2719 (guard-kwd (js2-catch-node-guard-kwd n))
2720 (guard-expr (js2-catch-node-guard-expr n)))
2721 (insert " catch (")
2722 (js2-print-ast (js2-catch-node-param n) 0)
2723 (when guard-kwd
2724 (insert " if ")
2725 (js2-print-ast guard-expr 0))
2726 (insert ") {\n")
2727 (js2-print-body (js2-catch-node-block n) (1+ i))
2728 (insert pad "}")))
2729
2730 (defstruct (js2-finally-node
2731 (:include js2-node)
2732 (:constructor nil)
2733 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2734 (pos js2-ts-cursor)
2735 len
2736 body)))
2737 "AST node for a finally clause."
2738 body) ; a `js2-node', often but not always a block node
2739
2740 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2741 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2742
2743 (defun js2-visit-finally-node (n v)
2744 (js2-visit-ast (js2-finally-node-body n) v))
2745
2746 (defun js2-print-finally-node (n i)
2747 (let ((pad (js2-make-pad i)))
2748 (insert " finally {\n")
2749 (js2-print-body (js2-finally-node-body n) (1+ i))
2750 (insert pad "}\n")))
2751
2752 (defstruct (js2-switch-node
2753 (:include js2-node)
2754 (:constructor nil)
2755 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2756 (pos js2-ts-cursor)
2757 len
2758 discriminant
2759 cases
2760 lp
2761 rp)))
2762 "AST node for a switch statement."
2763 discriminant ; a `js2-node' (switch expression)
2764 cases ; a lisp list of `js2-case-node'
2765 lp ; position of open-paren for discriminant, nil if omitted
2766 rp) ; position of close-paren for discriminant, nil if omitted
2767
2768 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2769 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2770
2771 (defun js2-visit-switch-node (n v)
2772 (js2-visit-ast (js2-switch-node-discriminant n) v)
2773 (dolist (c (js2-switch-node-cases n))
2774 (js2-visit-ast c v)))
2775
2776 (defun js2-print-switch-node (n i)
2777 (let ((pad (js2-make-pad i))
2778 (cases (js2-switch-node-cases n)))
2779 (insert pad "switch (")
2780 (js2-print-ast (js2-switch-node-discriminant n) 0)
2781 (insert ") {\n")
2782 (dolist (case cases)
2783 (js2-print-ast case i))
2784 (insert pad "}\n")))
2785
2786 (defstruct (js2-case-node
2787 (:include js2-block-node)
2788 (:constructor nil)
2789 (:constructor make-js2-case-node (&key (type js2-CASE)
2790 (pos js2-ts-cursor)
2791 len
2792 kids
2793 expr)))
2794 "AST node for a case clause of a switch statement."
2795 expr) ; the case expression (nil for default)
2796
2797 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2798 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2799
2800 (defun js2-visit-case-node (n v)
2801 (js2-visit-ast (js2-case-node-expr n) v)
2802 (js2-visit-block n v))
2803
2804 (defun js2-print-case-node (n i)
2805 (let ((pad (js2-make-pad i))
2806 (expr (js2-case-node-expr n)))
2807 (insert pad)
2808 (if (null expr)
2809 (insert "default:\n")
2810 (insert "case ")
2811 (js2-print-ast expr 0)
2812 (insert ":\n"))
2813 (dolist (kid (js2-case-node-kids n))
2814 (js2-print-ast kid (1+ i)))))
2815
2816 (defstruct (js2-throw-node
2817 (:include js2-node)
2818 (:constructor nil)
2819 (:constructor make-js2-throw-node (&key (type js2-THROW)
2820 (pos js2-ts-cursor)
2821 len
2822 expr)))
2823 "AST node for a throw statement."
2824 expr) ; the expression to throw
2825
2826 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2827 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2828
2829 (defun js2-visit-throw-node (n v)
2830 (js2-visit-ast (js2-throw-node-expr n) v))
2831
2832 (defun js2-print-throw-node (n i)
2833 (insert (js2-make-pad i) "throw ")
2834 (js2-print-ast (js2-throw-node-expr n) 0)
2835 (insert ";\n"))
2836
2837 (defstruct (js2-with-node
2838 (:include js2-node)
2839 (:constructor nil)
2840 (:constructor make-js2-with-node (&key (type js2-WITH)
2841 (pos js2-ts-cursor)
2842 len
2843 object
2844 body
2845 lp
2846 rp)))
2847 "AST node for a with-statement."
2848 object
2849 body
2850 lp ; buffer position of left-paren around object, nil if omitted
2851 rp) ; buffer position of right-paren around object, nil if omitted
2852
2853 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2854 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2855
2856 (defun js2-visit-with-node (n v)
2857 (js2-visit-ast (js2-with-node-object n) v)
2858 (js2-visit-ast (js2-with-node-body n) v))
2859
2860 (defun js2-print-with-node (n i)
2861 (let ((pad (js2-make-pad i)))
2862 (insert pad "with (")
2863 (js2-print-ast (js2-with-node-object n) 0)
2864 (insert ") {\n")
2865 (js2-print-body (js2-with-node-body n) (1+ i))
2866 (insert pad "}\n")))
2867
2868 (defstruct (js2-label-node
2869 (:include js2-node)
2870 (:constructor nil)
2871 (:constructor make-js2-label-node (&key (type js2-LABEL)
2872 (pos js2-ts-cursor)
2873 len
2874 name)))
2875 "AST node for a statement label or case label."
2876 name ; a string
2877 loop) ; for validating and code-generating continue-to-label
2878
2879 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2880 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2881
2882 (defun js2-print-label (n i)
2883 (insert (js2-make-pad i)
2884 (js2-label-node-name n)
2885 ":\n"))
2886
2887 (defstruct (js2-labeled-stmt-node
2888 (:include js2-node)
2889 (:constructor nil)
2890 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2891 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2892 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2893 (pos js2-ts-cursor)
2894 len
2895 labels
2896 stmt)))
2897 "AST node for a statement with one or more labels.
2898 Multiple labels for a statement are collapsed into the labels field."
2899 labels ; lisp list of `js2-label-node'
2900 stmt) ; the statement these labels are for
2901
2902 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2903 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2904
2905 (defun js2-get-label-by-name (lbl-stmt name)
2906 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2907 Returns nil if no such label is in the list."
2908 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2909 result)
2910 (while (and label-list (not result))
2911 (if (string= (js2-label-node-name (car label-list)) name)
2912 (setq result (car label-list))
2913 (setq label-list (cdr label-list))))
2914 result))
2915
2916 (defun js2-visit-labeled-stmt (n v)
2917 (dolist (label (js2-labeled-stmt-node-labels n))
2918 (js2-visit-ast label v))
2919 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2920
2921 (defun js2-print-labeled-stmt (n i)
2922 (dolist (label (js2-labeled-stmt-node-labels n))
2923 (js2-print-ast label i))
2924 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2925
2926 (defun js2-labeled-stmt-node-contains (node label)
2927 "Return t if NODE contains LABEL in its label set.
2928 NODE is a `js2-labels-node'. LABEL is an identifier."
2929 (loop for nl in (js2-labeled-stmt-node-labels node)
2930 if (string= label (js2-label-node-name nl))
2931 return t
2932 finally return nil))
2933
2934 (defsubst js2-labeled-stmt-node-add-label (node label)
2935 "Add a `js2-label-node' to the label set for this statement."
2936 (setf (js2-labeled-stmt-node-labels node)
2937 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2938
2939 (defstruct (js2-jump-node
2940 (:include js2-node)
2941 (:constructor nil))
2942 "Abstract supertype of break and continue nodes."
2943 label ; `js2-name-node' for location of label identifier, if present
2944 target) ; target js2-labels-node or loop/switch statement
2945
2946 (defun js2-visit-jump-node (n v)
2947 (js2-visit-ast (js2-jump-node-label n) v))
2948
2949 (defstruct (js2-break-node
2950 (:include js2-jump-node)
2951 (:constructor nil)
2952 (:constructor make-js2-break-node (&key (type js2-BREAK)
2953 (pos js2-ts-cursor)
2954 len
2955 label
2956 target)))
2957 "AST node for a break statement.
2958 The label field is a `js2-name-node', possibly nil, for the named label
2959 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2960 is the target of the break - a label node or enclosing loop/switch statement.")
2961
2962 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2963 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2964
2965 (defun js2-print-break-node (n i)
2966 (insert (js2-make-pad i) "break")
2967 (when (js2-break-node-label n)
2968 (insert " ")
2969 (js2-print-ast (js2-break-node-label n) 0))
2970 (insert ";\n"))
2971
2972 (defstruct (js2-continue-node
2973 (:include js2-jump-node)
2974 (:constructor nil)
2975 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2976 (pos js2-ts-cursor)
2977 len
2978 label
2979 target)))
2980 "AST node for a continue statement.
2981 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2982 It is nil if continue specifies no label. The target field is the jump target:
2983 a `js2-label-node' or the innermost enclosing loop.")
2984
2985 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2986 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2987
2988 (defun js2-print-continue-node (n i)
2989 (insert (js2-make-pad i) "continue")
2990 (when (js2-continue-node-label n)
2991 (insert " ")
2992 (js2-print-ast (js2-continue-node-label n) 0))
2993 (insert ";\n"))
2994
2995 (defstruct (js2-function-node
2996 (:include js2-script-node)
2997 (:constructor nil)
2998 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2999 (pos js2-ts-cursor)
3000 len
3001 (ftype 'FUNCTION)
3002 (form 'FUNCTION_STATEMENT)
3003 (name "")
3004 params
3005 body
3006 lp
3007 rp)))
3008 "AST node for a function declaration.
3009 The `params' field is a lisp list of nodes. Each node is either a simple
3010 `js2-name-node', or if it's a destructuring-assignment parameter, a
3011 `js2-array-node' or `js2-object-node'."
3012 ftype ; FUNCTION, GETTER or SETTER
3013 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3014 name ; function name (a `js2-name-node', or nil if anonymous)
3015 params ; a lisp list of destructuring forms or simple name nodes
3016 body ; a `js2-block-node' or expression node (1.8 only)
3017 lp ; position of arg-list open-paren, or nil if omitted
3018 rp ; position of arg-list close-paren, or nil if omitted
3019 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3020 needs-activation ; t if we need an activation object for this frame
3021 is-generator ; t if this function contains a yield
3022 member-expr) ; nonstandard Ecma extension from Rhino
3023
3024 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3025 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3026
3027 (defun js2-visit-function-node (n v)
3028 (js2-visit-ast (js2-function-node-name n) v)
3029 (dolist (p (js2-function-node-params n))
3030 (js2-visit-ast p v))
3031 (js2-visit-ast (js2-function-node-body n) v))
3032
3033 (defun js2-print-function-node (n i)
3034 (let ((pad (js2-make-pad i))
3035 (getter (js2-node-get-prop n 'GETTER_SETTER))
3036 (name (js2-function-node-name n))
3037 (params (js2-function-node-params n))
3038 (body (js2-function-node-body n))
3039 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3040 (unless getter
3041 (insert pad "function"))
3042 (when name
3043 (insert " ")
3044 (js2-print-ast name 0))
3045 (insert "(")
3046 (loop with len = (length params)
3047 for param in params
3048 for count from 1
3049 do
3050 (js2-print-ast param 0)
3051 (if (< count len)
3052 (insert ", ")))
3053 (insert ") {")
3054 (unless expr
3055 (insert "\n"))
3056 ;; TODO: fix this to be smarter about indenting, etc.
3057 (js2-print-body body (1+ i))
3058 (insert pad "}")
3059 (unless expr
3060 (insert "\n"))))
3061
3062 (defsubst js2-function-name (node)
3063 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3064 (and (js2-function-node-name node)
3065 (js2-name-node-name (js2-function-node-name node))))
3066
3067 ;; Having this be an expression node makes it more flexible.
3068 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3069 ;; that work better if you assume it's an expression. Whenever we have
3070 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3071 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3072 (defstruct (js2-var-decl-node
3073 (:include js2-node)
3074 (:constructor nil)
3075 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3076 (pos js2-token-beg)
3077 len
3078 kids
3079 decl-type)))
3080 "AST node for a variable declaration list (VAR, CONST or LET).
3081 The node bounds differ depending on the declaration type. For VAR or
3082 CONST declarations, the bounds include the var/const keyword. For LET
3083 declarations, the node begins at the position of the first child."
3084 kids ; a lisp list of `js2-var-init-node' structs.
3085 decl-type) ; js2-VAR, js2-CONST or js2-LET
3086
3087 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3088 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3089
3090 (defun js2-visit-var-decl (n v)
3091 (dolist (kid (js2-var-decl-node-kids n))
3092 (js2-visit-ast kid v)))
3093
3094 (defun js2-print-var-decl (n i)
3095 (let ((pad (js2-make-pad i))
3096 (tt (js2-var-decl-node-decl-type n)))
3097 (insert pad)
3098 (insert (cond
3099 ((= tt js2-VAR) "var ")
3100 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3101 ((= tt js2-CONST) "const ")
3102 (t
3103 (error "malformed var-decl node"))))
3104 (loop with kids = (js2-var-decl-node-kids n)
3105 with len = (length kids)
3106 for kid in kids
3107 for count from 1
3108 do
3109 (js2-print-ast kid 0)
3110 (if (< count len)
3111 (insert ", ")))))
3112
3113 (defstruct (js2-var-init-node
3114 (:include js2-node)
3115 (:constructor nil)
3116 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3117 (pos js2-ts-cursor)
3118 len
3119 target
3120 initializer)))
3121 "AST node for a variable declaration.
3122 The type field will be js2-CONST for a const decl."
3123 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3124 initializer) ; initializer expression, a `js2-node'
3125
3126 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3127 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3128
3129 (defun js2-visit-var-init-node (n v)
3130 (js2-visit-ast (js2-var-init-node-target n) v)
3131 (js2-visit-ast (js2-var-init-node-initializer n) v))
3132
3133 (defun js2-print-var-init-node (n i)
3134 (let ((pad (js2-make-pad i))
3135 (name (js2-var-init-node-target n))
3136 (init (js2-var-init-node-initializer n)))
3137 (insert pad)
3138 (js2-print-ast name 0)
3139 (when init
3140 (insert " = ")
3141 (js2-print-ast init 0))))
3142
3143 (defstruct (js2-cond-node
3144 (:include js2-node)
3145 (:constructor nil)
3146 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3147 (pos js2-ts-cursor)
3148 len
3149 test-expr
3150 true-expr
3151 false-expr
3152 q-pos
3153 c-pos)))
3154 "AST node for the ternary operator"
3155 test-expr
3156 true-expr
3157 false-expr
3158 q-pos ; buffer position of ?
3159 c-pos) ; buffer position of :
3160
3161 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3162 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3163
3164 (defun js2-visit-cond-node (n v)
3165 (js2-visit-ast (js2-cond-node-test-expr n) v)
3166 (js2-visit-ast (js2-cond-node-true-expr n) v)
3167 (js2-visit-ast (js2-cond-node-false-expr n) v))
3168
3169 (defun js2-print-cond-node (n i)
3170 (let ((pad (js2-make-pad i)))
3171 (insert pad)
3172 (js2-print-ast (js2-cond-node-test-expr n) 0)
3173 (insert " ? ")
3174 (js2-print-ast (js2-cond-node-true-expr n) 0)
3175 (insert " : ")
3176 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3177
3178 (defstruct (js2-infix-node
3179 (:include js2-node)
3180 (:constructor nil)
3181 (:constructor make-js2-infix-node (&key type
3182 (pos js2-ts-cursor)
3183 len
3184 op-pos
3185 left
3186 right)))
3187 "Represents infix expressions.
3188 Includes assignment ops like `|=', and the comma operator.
3189 The type field inherited from `js2-node' holds the operator."
3190 op-pos ; buffer position where operator begins
3191 left ; any `js2-node'
3192 right) ; any `js2-node'
3193
3194 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3195 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3196
3197 (defun js2-visit-infix-node (n v)
3198 (js2-visit-ast (js2-infix-node-left n) v)
3199 (js2-visit-ast (js2-infix-node-right n) v))
3200
3201 (defconst js2-operator-tokens
3202 (let ((table (make-hash-table :test 'eq))
3203 (tokens
3204 (list (cons js2-IN "in")
3205 (cons js2-TYPEOF "typeof")
3206 (cons js2-INSTANCEOF "instanceof")
3207 (cons js2-DELPROP "delete")
3208 (cons js2-COMMA ",")
3209 (cons js2-COLON ":")
3210 (cons js2-OR "||")
3211 (cons js2-AND "&&")
3212 (cons js2-INC "++")
3213 (cons js2-DEC "--")
3214 (cons js2-BITOR "|")
3215 (cons js2-BITXOR "^")
3216 (cons js2-BITAND "&")
3217 (cons js2-EQ "==")
3218 (cons js2-NE "!=")
3219 (cons js2-LT "<")
3220 (cons js2-LE "<=")
3221 (cons js2-GT ">")
3222 (cons js2-GE ">=")
3223 (cons js2-LSH "<<")
3224 (cons js2-RSH ">>")
3225 (cons js2-URSH ">>>")
3226 (cons js2-ADD "+") ; infix plus
3227 (cons js2-SUB "-") ; infix minus
3228 (cons js2-MUL "*")
3229 (cons js2-DIV "/")
3230 (cons js2-MOD "%")
3231 (cons js2-NOT "!")
3232 (cons js2-BITNOT "~")
3233 (cons js2-POS "+") ; unary plus
3234 (cons js2-NEG "-") ; unary minus
3235 (cons js2-SHEQ "===") ; shallow equality
3236 (cons js2-SHNE "!==") ; shallow inequality
3237 (cons js2-ASSIGN "=")
3238 (cons js2-ASSIGN_BITOR "|=")
3239 (cons js2-ASSIGN_BITXOR "^=")
3240 (cons js2-ASSIGN_BITAND "&=")
3241 (cons js2-ASSIGN_LSH "<<=")
3242 (cons js2-ASSIGN_RSH ">>=")
3243 (cons js2-ASSIGN_URSH ">>>=")
3244 (cons js2-ASSIGN_ADD "+=")
3245 (cons js2-ASSIGN_SUB "-=")
3246 (cons js2-ASSIGN_MUL "*=")
3247 (cons js2-ASSIGN_DIV "/=")
3248 (cons js2-ASSIGN_MOD "%="))))
3249 (loop for (k . v) in tokens do
3250 (puthash k v table))
3251 table))
3252
3253 (defun js2-print-infix-node (n i)
3254 (let* ((tt (js2-node-type n))
3255 (op (gethash tt js2-operator-tokens)))
3256 (unless op
3257 (error "unrecognized infix operator %s" (js2-node-type n)))
3258 (insert (js2-make-pad i))
3259 (js2-print-ast (js2-infix-node-left n) 0)
3260 (unless (= tt js2-COMMA)
3261 (insert " "))
3262 (insert op)
3263 (insert " ")
3264 (js2-print-ast (js2-infix-node-right n) 0)))
3265
3266 (defstruct (js2-assign-node
3267 (:include js2-infix-node)
3268 (:constructor nil)
3269 (:constructor make-js2-assign-node (&key type
3270 (pos js2-ts-cursor)
3271 len
3272 op-pos
3273 left
3274 right)))
3275 "Represents any assignment.
3276 The type field holds the actual assignment operator.")
3277
3278 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3279 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3280
3281 (defstruct (js2-unary-node
3282 (:include js2-node)
3283 (:constructor nil)
3284 (:constructor make-js2-unary-node (&key type ; required
3285 (pos js2-ts-cursor)
3286 len
3287 operand)))
3288 "AST node type for unary operator nodes.
3289 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3290 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3291 property is added if the operator follows the operand."
3292 operand) ; a `js2-node' expression
3293
3294 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3295 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3296
3297 (defun js2-visit-unary-node (n v)
3298 (js2-visit-ast (js2-unary-node-operand n) v))
3299
3300 (defun js2-print-unary-node (n i)
3301 (let* ((tt (js2-node-type n))
3302 (op (gethash tt js2-operator-tokens))
3303 (postfix (js2-node-get-prop n 'postfix)))
3304 (unless op
3305 (error "unrecognized unary operator %s" tt))
3306 (insert (js2-make-pad i))
3307 (unless postfix
3308 (insert op))
3309 (if (or (= tt js2-TYPEOF)
3310 (= tt js2-DELPROP))
3311 (insert " "))
3312 (js2-print-ast (js2-unary-node-operand n) 0)
3313 (when postfix
3314 (insert op))))
3315
3316 (defstruct (js2-let-node
3317 (:include js2-scope)
3318 (:constructor nil)
3319 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3320 (pos js2-token-beg)
3321 len
3322 vars
3323 body
3324 lp
3325 rp)))
3326 "AST node for a let expression or a let statement.
3327 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3328 vars ; a `js2-var-decl-node'
3329 body ; a `js2-node' representing the expression or body block
3330 lp
3331 rp)
3332
3333 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3334 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3335
3336 (defun js2-visit-let-node (n v)
3337 (js2-visit-ast (js2-let-node-vars n) v)
3338 (js2-visit-ast (js2-let-node-body n) v))
3339
3340 (defun js2-print-let-node (n i)
3341 (insert (js2-make-pad i) "let (")
3342 (js2-print-ast (js2-let-node-vars n) 0)
3343 (insert ") ")
3344 (js2-print-ast (js2-let-node-body n) i))
3345
3346 (defstruct (js2-keyword-node
3347 (:include js2-node)
3348 (:constructor nil)
3349 (:constructor make-js2-keyword-node (&key type
3350 (pos js2-token-beg)
3351 (len (- js2-ts-cursor pos)))))
3352 "AST node representing a literal keyword such as `null'.
3353 Used for `null', `this', `true', `false' and `debugger'.
3354 The node type is set to js2-NULL, js2-THIS, etc.")
3355
3356 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3357 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3358
3359 (defun js2-print-keyword-node (n i)
3360 (insert (js2-make-pad i)
3361 (let ((tt (js2-node-type n)))
3362 (cond
3363 ((= tt js2-THIS) "this")
3364 ((= tt js2-NULL) "null")
3365 ((= tt js2-TRUE) "true")
3366 ((= tt js2-FALSE) "false")
3367 ((= tt js2-DEBUGGER) "debugger")
3368 (t (error "Invalid keyword literal type: %d" tt))))))
3369
3370 (defsubst js2-this-node-p (node)
3371 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3372 (eq (js2-node-type node) js2-THIS))
3373
3374 (defstruct (js2-new-node
3375 (:include js2-node)
3376 (:constructor nil)
3377 (:constructor make-js2-new-node (&key (type js2-NEW)
3378 (pos js2-token-beg)
3379 len
3380 target
3381 args
3382 initializer
3383 lp
3384 rp)))
3385 "AST node for new-expression such as new Foo()."
3386 target ; an identifier or reference
3387 args ; a lisp list of argument nodes
3388 lp ; position of left-paren, nil if omitted
3389 rp ; position of right-paren, nil if omitted
3390 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3391
3392 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3393 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3394
3395 (defun js2-visit-new-node (n v)
3396 (js2-visit-ast (js2-new-node-target n) v)
3397 (dolist (arg (js2-new-node-args n))
3398 (js2-visit-ast arg v))
3399 (js2-visit-ast (js2-new-node-initializer n) v))
3400
3401 (defun js2-print-new-node (n i)
3402 (insert (js2-make-pad i) "new ")
3403 (js2-print-ast (js2-new-node-target n))
3404 (insert "(")
3405 (js2-print-list (js2-new-node-args n))
3406 (insert ")")
3407 (when (js2-new-node-initializer n)
3408 (insert " ")
3409 (js2-print-ast (js2-new-node-initializer n))))
3410
3411 (defstruct (js2-name-node
3412 (:include js2-node)
3413 (:constructor nil)
3414 (:constructor make-js2-name-node (&key (type js2-NAME)
3415 (pos js2-token-beg)
3416 (len (- js2-ts-cursor
3417 js2-token-beg))
3418 (name js2-ts-string))))
3419 "AST node for a JavaScript identifier"
3420 name ; a string
3421 scope) ; a `js2-scope' (optional, used for codegen)
3422
3423 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3424 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3425
3426 (defun js2-print-name-node (n i)
3427 (insert (js2-make-pad i)
3428 (js2-name-node-name n)))
3429
3430 (defsubst js2-name-node-length (node)
3431 "Return identifier length of NODE, a `js2-name-node'.
3432 Returns 0 if NODE is nil or its identifier field is nil."
3433 (if node
3434 (length (js2-name-node-name node))
3435 0))
3436
3437 (defstruct (js2-number-node
3438 (:include js2-node)
3439 (:constructor nil)
3440 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3441 (pos js2-token-beg)
3442 (len (- js2-ts-cursor
3443 js2-token-beg))
3444 (value js2-ts-string)
3445 (num-value js2-ts-number))))
3446 "AST node for a number literal."
3447 value ; the original string, e.g. "6.02e23"
3448 num-value) ; the parsed number value
3449
3450 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3451 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3452
3453 (defun js2-print-number-node (n i)
3454 (insert (js2-make-pad i)
3455 (number-to-string (js2-number-node-num-value n))))
3456
3457 (defstruct (js2-regexp-node
3458 (:include js2-node)
3459 (:constructor nil)
3460 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3461 (pos js2-token-beg)
3462 (len (- js2-ts-cursor
3463 js2-token-beg))
3464 value
3465 flags)))
3466 "AST node for a regular expression literal."
3467 value ; the regexp string, without // delimiters
3468 flags) ; a string of flags, e.g. `mi'.
3469
3470 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3471 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3472
3473 (defun js2-print-regexp (n i)
3474 (insert (js2-make-pad i)
3475 "/"
3476 (js2-regexp-node-value n)
3477 "/")
3478 (if (js2-regexp-node-flags n)
3479 (insert (js2-regexp-node-flags n))))
3480
3481 (defstruct (js2-string-node
3482 (:include js2-node)
3483 (:constructor nil)
3484 (:constructor make-js2-string-node (&key (type js2-STRING)
3485 (pos js2-token-beg)
3486 (len (- js2-ts-cursor
3487 js2-token-beg))
3488 (value js2-ts-string))))
3489 "String literal.
3490 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3491 You can tell the quote type by looking at the first character."
3492 value) ; the characters of the string, including the quotes
3493
3494 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3495 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3496
3497 (defun js2-print-string-node (n i)
3498 (insert (js2-make-pad i)
3499 (js2-node-string n)))
3500
3501 (defstruct (js2-array-node
3502 (:include js2-node)
3503 (:constructor nil)
3504 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3505 (pos js2-ts-cursor)
3506 len
3507 elems)))
3508 "AST node for an array literal."
3509 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3510
3511 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3512 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3513
3514 (defun js2-visit-array-node (n v)
3515 (dolist (e (js2-array-node-elems n))
3516 (js2-visit-ast e v)))
3517
3518 (defun js2-print-array-node (n i)
3519 (insert (js2-make-pad i) "[")
3520 (js2-print-list (js2-array-node-elems n))
3521 (insert "]"))
3522
3523 (defstruct (js2-object-node
3524 (:include js2-node)
3525 (:constructor nil)
3526 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3527 (pos js2-ts-cursor)
3528 len
3529 elems)))
3530 "AST node for an object literal expression.
3531 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3532 the latter represents abbreviation in destructuring expressions."
3533 elems)
3534
3535 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3536 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3537
3538 (defun js2-visit-object-node (n v)
3539 (dolist (e (js2-object-node-elems n))
3540 (js2-visit-ast e v)))
3541
3542 (defun js2-print-object-node (n i)
3543 (insert (js2-make-pad i) "{")
3544 (js2-print-list (js2-object-node-elems n))
3545 (insert "}"))
3546
3547 (defstruct (js2-object-prop-node
3548 (:include js2-infix-node)
3549 (:constructor nil)
3550 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3551 (pos js2-ts-cursor)
3552 len
3553 left
3554 right
3555 op-pos)))
3556 "AST node for an object literal prop:value entry.
3557 The `left' field is the property: a name node, string node or number node.
3558 The `right' field is a `js2-node' representing the initializer value.")
3559
3560 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3561 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3562
3563 (defun js2-print-object-prop-node (n i)
3564 (insert (js2-make-pad i))
3565 (js2-print-ast (js2-object-prop-node-left n) 0)
3566 (insert ":")
3567 (js2-print-ast (js2-object-prop-node-right n) 0))
3568
3569 (defstruct (js2-getter-setter-node
3570 (:include js2-infix-node)
3571 (:constructor nil)
3572 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3573 (pos js2-ts-cursor)
3574 len
3575 left
3576 right)))
3577 "AST node for a getter/setter property in an object literal.
3578 The `left' field is the `js2-name-node' naming the getter/setter prop.
3579 The `right' field is always an anonymous `js2-function-node' with a node
3580 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3581
3582 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3583 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3584
3585 (defun js2-print-getter-setter (n i)
3586 (let ((pad (js2-make-pad i))
3587 (left (js2-getter-setter-node-left n))
3588 (right (js2-getter-setter-node-right n)))
3589 (insert pad)
3590 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3591 (js2-print-ast left 0)
3592 (js2-print-ast right 0)))
3593
3594 (defstruct (js2-prop-get-node
3595 (:include js2-infix-node)
3596 (:constructor nil)
3597 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3598 (pos js2-ts-cursor)
3599 len
3600 left
3601 right)))
3602 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3603
3604 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3605 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3606
3607 (defun js2-visit-prop-get-node (n v)
3608 (js2-visit-ast (js2-prop-get-node-left n) v)
3609 (js2-visit-ast (js2-prop-get-node-right n) v))
3610
3611 (defun js2-print-prop-get-node (n i)
3612 (insert (js2-make-pad i))
3613 (js2-print-ast (js2-prop-get-node-left n) 0)
3614 (insert ".")
3615 (js2-print-ast (js2-prop-get-node-right n) 0))
3616
3617 (defstruct (js2-elem-get-node
3618 (:include js2-node)
3619 (:constructor nil)
3620 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3621 (pos js2-ts-cursor)
3622 len
3623 target
3624 element
3625 lb
3626 rb)))
3627 "AST node for an array index expression such as foo[bar]."
3628 target ; a `js2-node' - the expression preceding the "."
3629 element ; a `js2-node' - the expression in brackets
3630 lb ; position of left-bracket, nil if omitted
3631 rb) ; position of right-bracket, nil if omitted
3632
3633 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3634 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3635
3636 (defun js2-visit-elem-get-node (n v)
3637 (js2-visit-ast (js2-elem-get-node-target n) v)
3638 (js2-visit-ast (js2-elem-get-node-element n) v))
3639
3640 (defun js2-print-elem-get-node (n i)
3641 (insert (js2-make-pad i))
3642 (js2-print-ast (js2-elem-get-node-target n) 0)
3643 (insert "[")
3644 (js2-print-ast (js2-elem-get-node-element n) 0)
3645 (insert "]"))
3646
3647 (defstruct (js2-call-node
3648 (:include js2-node)
3649 (:constructor nil)
3650 (:constructor make-js2-call-node (&key (type js2-CALL)
3651 (pos js2-ts-cursor)
3652 len
3653 target
3654 args
3655 lp
3656 rp)))
3657 "AST node for a JavaScript function call."
3658 target ; a `js2-node' evaluating to the function to call
3659 args ; a lisp list of `js2-node' arguments
3660 lp ; position of open-paren, or nil if missing
3661 rp) ; position of close-paren, or nil if missing
3662
3663 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3664 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3665
3666 (defun js2-visit-call-node (n v)
3667 (js2-visit-ast (js2-call-node-target n) v)
3668 (dolist (arg (js2-call-node-args n))
3669 (js2-visit-ast arg v)))
3670
3671 (defun js2-print-call-node (n i)
3672 (insert (js2-make-pad i))
3673 (js2-print-ast (js2-call-node-target n) 0)
3674 (insert "(")
3675 (js2-print-list (js2-call-node-args n))
3676 (insert ")"))
3677
3678 (defstruct (js2-yield-node
3679 (:include js2-node)
3680 (:constructor nil)
3681 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3682 (pos js2-ts-cursor)
3683 len
3684 value)))
3685 "AST node for yield statement or expression."
3686 value) ; optional: value to be yielded
3687
3688 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3689 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3690
3691 (defun js2-visit-yield-node (n v)
3692 (js2-visit-ast (js2-yield-node-value n) v))
3693
3694 (defun js2-print-yield-node (n i)
3695 (insert (js2-make-pad i))
3696 (insert "yield")
3697 (when (js2-yield-node-value n)
3698 (insert " ")
3699 (js2-print-ast (js2-yield-node-value n) 0)))
3700
3701 (defstruct (js2-paren-node
3702 (:include js2-node)
3703 (:constructor nil)
3704 (:constructor make-js2-paren-node (&key (type js2-LP)
3705 (pos js2-ts-cursor)
3706 len
3707 expr)))
3708 "AST node for a parenthesized expression.
3709 In particular, used when the parens are syntactically optional,
3710 as opposed to required parens such as those enclosing an if-conditional."
3711 expr) ; `js2-node'
3712
3713 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3714 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3715
3716 (defun js2-visit-paren-node (n v)
3717 (js2-visit-ast (js2-paren-node-expr n) v))
3718
3719 (defun js2-print-paren-node (n i)
3720 (insert (js2-make-pad i))
3721 (insert "(")
3722 (js2-print-ast (js2-paren-node-expr n) 0)
3723 (insert ")"))
3724
3725 (defstruct (js2-array-comp-node
3726 (:include js2-scope)
3727 (:constructor nil)
3728 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3729 (pos js2-ts-cursor)
3730 len
3731 result
3732 loops
3733 filter
3734 if-pos
3735 lp
3736 rp)))
3737 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3738 result ; result expression (just after left-bracket)
3739 loops ; a lisp list of `js2-array-comp-loop-node'
3740 filter ; guard/filter expression
3741 if-pos ; buffer pos of 'if' keyword, if present, else nil
3742 lp ; buffer position of if-guard left-paren, or nil if not present
3743 rp) ; buffer position of if-guard right-paren, or nil if not present
3744
3745 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3746 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3747
3748 (defun js2-visit-array-comp-node (n v)
3749 (js2-visit-ast (js2-array-comp-node-result n) v)
3750 (dolist (l (js2-array-comp-node-loops n))
3751 (js2-visit-ast l v))
3752 (js2-visit-ast (js2-array-comp-node-filter n) v))
3753
3754 (defun js2-print-array-comp-node (n i)
3755 (let ((pad (js2-make-pad i))
3756 (result (js2-array-comp-node-result n))
3757 (loops (js2-array-comp-node-loops n))
3758 (filter (js2-array-comp-node-filter n)))
3759 (insert pad "[")
3760 (js2-print-ast result 0)
3761 (dolist (l loops)
3762 (insert " ")
3763 (js2-print-ast l 0))
3764 (when filter
3765 (insert " if (")
3766 (js2-print-ast filter 0))
3767 (insert ")]")))
3768
3769 (defstruct (js2-array-comp-loop-node
3770 (:include js2-for-in-node)
3771 (:constructor nil)
3772 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3773 (pos js2-ts-cursor)
3774 len
3775 iterator
3776 object
3777 in-pos
3778 foreach-p
3779 each-pos
3780 lp
3781 rp)))
3782 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3783
3784 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3785 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3786
3787 (defun js2-visit-array-comp-loop (n v)
3788 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3789 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3790
3791 (defun js2-print-array-comp-loop (n i)
3792 (insert "for (")
3793 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3794 (insert " in ")
3795 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3796 (insert ")"))
3797
3798 (defstruct (js2-empty-expr-node
3799 (:include js2-node)
3800 (:constructor nil)
3801 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3802 (pos js2-token-beg)
3803 len)))
3804 "AST node for an empty expression.")
3805
3806 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3807 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3808
3809 (defstruct (js2-xml-node
3810 (:include js2-block-node)
3811 (:constructor nil)
3812 (:constructor make-js2-xml-node (&key (type js2-XML)
3813 (pos js2-token-beg)
3814 len
3815 kids)))
3816 "AST node for initial parse of E4X literals.
3817 The kids field is a list of XML fragments, each a `js2-string-node' or
3818 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3819
3820 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3821 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3822
3823 (defun js2-print-xml-node (n i)
3824 (dolist (kid (js2-xml-node-kids n))
3825 (js2-print-ast kid i)))
3826
3827 (defstruct (js2-xml-js-expr-node
3828 (:include js2-xml-node)
3829 (:constructor nil)
3830 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3831 (pos js2-ts-cursor)
3832 len
3833 expr)))
3834 "AST node for an embedded JavaScript {expression} in an E4X literal.
3835 The start and end fields correspond to the curly-braces."
3836 expr) ; a `js2-expr-node' of some sort
3837
3838 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3839 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3840
3841 (defun js2-visit-xml-js-expr (n v)
3842 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3843
3844 (defun js2-print-xml-js-expr (n i)
3845 (insert (js2-make-pad i))
3846 (insert "{")
3847 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3848 (insert "}"))
3849
3850 (defstruct (js2-xml-dot-query-node
3851 (:include js2-infix-node)
3852 (:constructor nil)
3853 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3854 (pos js2-ts-cursor)
3855 op-pos
3856 len
3857 left
3858 right
3859 rp)))
3860 "AST node for an E4X foo.(bar) filter expression.
3861 Note that the left-paren is automatically the character immediately
3862 following the dot (.) in the operator. No whitespace is permitted
3863 between the dot and the lp by the scanner."
3864 rp)
3865
3866 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3867 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3868
3869 (defun js2-print-xml-dot-query (n i)
3870 (insert (js2-make-pad i))
3871 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3872 (insert ".(")
3873 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3874 (insert ")"))
3875
3876 (defstruct (js2-xml-ref-node
3877 (:include js2-node)
3878 (:constructor nil)) ; abstract
3879 "Base type for E4X XML attribute-access or property-get expressions.
3880 Such expressions can take a variety of forms. The general syntax has
3881 three parts:
3882
3883 - (optional) an @ (specifying an attribute access)
3884 - (optional) a namespace (a `js2-name-node') and double-colon
3885 - (required) either a `js2-name-node' or a bracketed [expression]
3886
3887 The property-name expressions (examples: ns::name, @name) are
3888 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3889 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3890
3891 This node type (or more specifically, its subclasses) will sometimes
3892 be the right-hand child of a `js2-prop-get-node' or a
3893 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3894 The `js2-xml-ref-node' may also be a standalone primary expression with
3895 no explicit target, which is valid in certain expression contexts such as
3896
3897 company..employee.(@id < 100)
3898
3899 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3900 expression whose parent is a `js2-xml-dot-query-node'."
3901 namespace
3902 at-pos
3903 colon-pos)
3904
3905 (defsubst js2-xml-ref-node-attr-access-p (node)
3906 "Return non-nil if this expression began with an @-token."
3907 (and (numberp (js2-xml-ref-node-at-pos node))
3908 (plusp (js2-xml-ref-node-at-pos node))))
3909
3910 (defstruct (js2-xml-prop-ref-node
3911 (:include js2-xml-ref-node)
3912 (:constructor nil)
3913 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3914 (pos js2-token-beg)
3915 len
3916 propname
3917 namespace
3918 at-pos
3919 colon-pos)))
3920 "AST node for an E4X XML [expr] property-ref expression.
3921 The JavaScript syntax is an optional @, an optional ns::, and a name.
3922
3923 [ '@' ] [ name '::' ] name
3924
3925 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3926 @ns::*, @*::attr, @*::*, and @*.
3927
3928 The node starts at the @ token, if present. Otherwise it starts at the
3929 namespace name. The node bounds extend through the closing right-bracket,
3930 or if it is missing due to a syntax error, through the end of the index
3931 expression."
3932 propname)
3933
3934 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3935 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3936
3937 (defun js2-visit-xml-prop-ref-node (n v)
3938 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3939 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3940
3941 (defun js2-print-xml-prop-ref-node (n i)
3942 (insert (js2-make-pad i))
3943 (if (js2-xml-ref-node-attr-access-p n)
3944 (insert "@"))
3945 (when (js2-xml-prop-ref-node-namespace n)
3946 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3947 (insert "::"))
3948 (if (js2-xml-prop-ref-node-propname n)
3949 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3950
3951 (defstruct (js2-xml-elem-ref-node
3952 (:include js2-xml-ref-node)
3953 (:constructor nil)
3954 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3955 (pos js2-token-beg)
3956 len
3957 expr
3958 lb
3959 rb
3960 namespace
3961 at-pos
3962 colon-pos)))
3963 "AST node for an E4X XML [expr] member-ref expression.
3964 Syntax:
3965
3966 [ '@' ] [ name '::' ] '[' expr ']'
3967
3968 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3969
3970 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3971 is not a legal E4X XML element-ref expression, since it's already used
3972 for standard JavaScript element-get array indexing. Hence, a
3973 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3974 non-nil namespace node, or both.
3975
3976 The node starts at the @ token, if present. Otherwise it starts
3977 at the namespace name. The node bounds extend through the closing
3978 right-bracket, or if it is missing due to a syntax error, through the
3979 end of the index expression."
3980 expr ; the bracketed index expression
3981 lb
3982 rb)
3983
3984 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3985 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3986
3987 (defun js2-visit-xml-elem-ref-node (n v)
3988 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3989 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3990
3991 (defun js2-print-xml-elem-ref-node (n i)
3992 (insert (js2-make-pad i))
3993 (if (js2-xml-ref-node-attr-access-p n)
3994 (insert "@"))
3995 (when (js2-xml-elem-ref-node-namespace n)
3996 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3997 (insert "::"))
3998 (insert "[")
3999 (if (js2-xml-elem-ref-node-expr n)
4000 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4001 (insert "]"))
4002
4003 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4004
4005 (defstruct (js2-xml-start-tag-node
4006 (:include js2-xml-node)
4007 (:constructor nil)
4008 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4009 (pos js2-ts-cursor)
4010 len
4011 name
4012 attrs
4013 kids
4014 empty-p)))
4015 "AST node for an XML start-tag. Not currently used.
4016 The `kids' field is a lisp list of child content nodes."
4017 name ; a `js2-xml-name-node'
4018 attrs ; a lisp list of `js2-xml-attr-node'
4019 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4020
4021 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4022 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4023
4024 (defun js2-visit-xml-start-tag (n v)
4025 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4026 (dolist (attr (js2-xml-start-tag-node-attrs n))
4027 (js2-visit-ast attr v))
4028 (js2-visit-block n v))
4029
4030 (defun js2-print-xml-start-tag (n i)
4031 (insert (js2-make-pad i) "<")
4032 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4033 (when (js2-xml-start-tag-node-attrs n)
4034 (insert " ")
4035 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4036 (insert ">"))
4037
4038 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4039 ;; and add the end-tag to the kids list of the parent as well.
4040 (defstruct (js2-xml-end-tag-node
4041 (:include js2-xml-node)
4042 (:constructor nil)
4043 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4044 (pos js2-ts-cursor)
4045 len
4046 name)))
4047 "AST node for an XML end-tag. Not currently used."
4048 name) ; a `js2-xml-name-node'
4049
4050 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4051 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4052
4053 (defun js2-visit-xml-end-tag (n v)
4054 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4055
4056 (defun js2-print-xml-end-tag (n i)
4057 (insert (js2-make-pad i))
4058 (insert "</")
4059 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4060 (insert ">"))
4061
4062 (defstruct (js2-xml-name-node
4063 (:include js2-xml-node)
4064 (:constructor nil)
4065 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4066 (pos js2-ts-cursor)
4067 len
4068 namespace
4069 kids)))
4070 "AST node for an E4X XML name. Not currently used.
4071 Any XML name can be qualified with a namespace, hence the namespace field.
4072 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4073 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4074 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4075 namespace) ; a `js2-string-node'
4076
4077 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4078 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4079
4080 (defun js2-visit-xml-name-node (n v)
4081 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4082
4083 (defun js2-print-xml-name-node (n i)
4084 (insert (js2-make-pad i))
4085 (when (js2-xml-name-node-namespace n)
4086 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4087 (insert "::"))
4088 (dolist (kid (js2-xml-name-node-kids n))
4089 (js2-print-ast kid 0)))
4090
4091 (defstruct (js2-xml-pi-node
4092 (:include js2-xml-node)
4093 (:constructor nil)
4094 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4095 (pos js2-ts-cursor)
4096 len
4097 name
4098 attrs)))
4099 "AST node for an E4X XML processing instruction. Not currently used."
4100 name ; a `js2-xml-name-node'
4101 attrs) ; a list of `js2-xml-attr-node'
4102
4103 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4104 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4105
4106 (defun js2-visit-xml-pi-node (n v)
4107 (js2-visit-ast (js2-xml-pi-node-name n) v)
4108 (dolist (attr (js2-xml-pi-node-attrs n))
4109 (js2-visit-ast attr v)))
4110
4111 (defun js2-print-xml-pi-node (n i)
4112 (insert (js2-make-pad i) "<?")
4113 (js2-print-ast (js2-xml-pi-node-name n))
4114 (when (js2-xml-pi-node-attrs n)
4115 (insert " ")
4116 (js2-print-list (js2-xml-pi-node-attrs n)))
4117 (insert "?>"))
4118
4119 (defstruct (js2-xml-cdata-node
4120 (:include js2-xml-node)
4121 (:constructor nil)
4122 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4123 (pos js2-ts-cursor)
4124 len
4125 content)))
4126 "AST node for a CDATA escape section. Not currently used."
4127 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4128
4129 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4130 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4131
4132 (defun js2-visit-xml-cdata-node (n v)
4133 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4134
4135 (defun js2-print-xml-cdata-node (n i)
4136 (insert (js2-make-pad i))
4137 (js2-print-ast (js2-xml-cdata-node-content n)))
4138
4139 (defstruct (js2-xml-attr-node
4140 (:include js2-xml-node)
4141 (:constructor nil)
4142 (:constructor make-js2-attr-node (&key (type js2-XML)
4143 (pos js2-ts-cursor)
4144 len
4145 name
4146 value
4147 eq-pos
4148 quote-type)))
4149 "AST node representing a foo='bar' XML attribute value. Not yet used."
4150 name ; a `js2-xml-name-node'
4151 value ; a `js2-xml-name-node'
4152 eq-pos ; buffer position of "=" sign
4153 quote-type) ; 'single or 'double
4154
4155 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4156 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4157
4158 (defun js2-visit-xml-attr-node (n v)
4159 (js2-visit-ast (js2-xml-attr-node-name n) v)
4160 (js2-visit-ast (js2-xml-attr-node-value n) v))
4161
4162 (defun js2-print-xml-attr-node (n i)
4163 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4164 "'"
4165 "\"")))
4166 (insert (js2-make-pad i))
4167 (js2-print-ast (js2-xml-attr-node-name n) 0)
4168 (insert "=" quote)
4169 (js2-print-ast (js2-xml-attr-node-value n) 0)
4170 (insert quote)))
4171
4172 (defstruct (js2-xml-text-node
4173 (:include js2-xml-node)
4174 (:constructor nil)
4175 (:constructor make-js2-text-node (&key (type js2-XML)
4176 (pos js2-ts-cursor)
4177 len
4178 content)))
4179 "AST node for an E4X XML text node. Not currently used."
4180 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4181
4182 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4183 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4184
4185 (defun js2-visit-xml-text-node (n v)
4186 (js2-visit-ast (js2-xml-text-node-content n) v))
4187
4188 (defun js2-print-xml-text-node (n i)
4189 (insert (js2-make-pad i))
4190 (dolist (kid (js2-xml-text-node-content n))
4191 (js2-print-ast kid)))
4192
4193 (defstruct (js2-xml-comment-node
4194 (:include js2-xml-node)
4195 (:constructor nil)
4196 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4197 (pos js2-ts-cursor)
4198 len)))
4199 "AST node for E4X XML comment. Not currently used.")
4200
4201 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4202 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4203
4204 (defun js2-print-xml-comment (n i)
4205 (insert (js2-make-pad i)
4206 (js2-node-string n)))
4207
4208 ;;; Node utilities
4209
4210 (defsubst js2-node-line (n)
4211 "Fetch the source line number at the start of node N.
4212 This is O(n) in the length of the source buffer; use prudently."
4213 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4214
4215 (defsubst js2-block-node-kid (n i)
4216 "Return child I of node N, or nil if there aren't that many."
4217 (nth i (js2-block-node-kids n)))
4218
4219 (defsubst js2-block-node-first (n)
4220 "Return first child of block node N, or nil if there is none."
4221 (first (js2-block-node-kids n)))
4222
4223 (defun js2-node-root (n)
4224 "Return the root of the AST containing N.
4225 If N has no parent pointer, returns N."
4226 (let ((parent (js2-node-parent n)))
4227 (if parent
4228 (js2-node-root parent)
4229 n)))
4230
4231 (defun js2-node-position-in-parent (node &optional parent)
4232 "Return the position of NODE in parent's block-kids list.
4233 PARENT can be supplied if known. Positioned returned is zero-indexed.
4234 Returns 0 if NODE is not a child of a block statement, or if NODE
4235 is not a statement node."
4236 (let ((p (or parent (js2-node-parent node)))
4237 (i 0))
4238 (if (not (js2-block-node-p p))
4239 i
4240 (or (js2-position node (js2-block-node-kids p))
4241 0))))
4242
4243 (defsubst js2-node-short-name (n)
4244 "Return the short name of node N as a string, e.g. `js2-if-node'."
4245 (substring (symbol-name (aref n 0))
4246 (length "cl-struct-")))
4247
4248 (defsubst js2-node-child-list (node)
4249 "Return the child list for NODE, a lisp list of nodes.
4250 Works for block nodes, array nodes, obj literals, funarg lists,
4251 var decls and try nodes (for catch clauses). Note that you should call
4252 `js2-block-node-kids' on the function body for the body statements.
4253 Returns nil for zero-length child lists or unsupported nodes."
4254 (cond
4255 ((js2-function-node-p node)
4256 (js2-function-node-params node))
4257 ((js2-block-node-p node)
4258 (js2-block-node-kids node))
4259 ((js2-try-node-p node)
4260 (js2-try-node-catch-clauses node))
4261 ((js2-array-node-p node)
4262 (js2-array-node-elems node))
4263 ((js2-object-node-p node)
4264 (js2-object-node-elems node))
4265 ((js2-call-node-p node)
4266 (js2-call-node-args node))
4267 ((js2-new-node-p node)
4268 (js2-new-node-args node))
4269 ((js2-var-decl-node-p node)
4270 (js2-var-decl-node-kids node))
4271 (t
4272 nil)))
4273
4274 (defsubst js2-node-set-child-list (node kids)
4275 "Set the child list for NODE to KIDS."
4276 (cond
4277 ((js2-function-node-p node)
4278 (setf (js2-function-node-params node) kids))
4279 ((js2-block-node-p node)
4280 (setf (js2-block-node-kids node) kids))
4281 ((js2-try-node-p node)
4282 (setf (js2-try-node-catch-clauses node) kids))
4283 ((js2-array-node-p node)
4284 (setf (js2-array-node-elems node) kids))
4285 ((js2-object-node-p node)
4286 (setf (js2-object-node-elems node) kids))
4287 ((js2-call-node-p node)
4288 (setf (js2-call-node-args node) kids))
4289 ((js2-new-node-p node)
4290 (setf (js2-new-node-args node) kids))
4291 ((js2-var-decl-node-p node)
4292 (setf (js2-var-decl-node-kids node) kids))
4293 (t
4294 (error "Unsupported node type: %s" (js2-node-short-name node))))
4295 kids)
4296
4297 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4298 (defconst js2-paren-expr-nodes
4299 '(cl-struct-js2-array-comp-loop-node
4300 cl-struct-js2-array-comp-node
4301 cl-struct-js2-call-node
4302 cl-struct-js2-catch-node
4303 cl-struct-js2-do-node
4304 cl-struct-js2-elem-get-node
4305 cl-struct-js2-for-in-node
4306 cl-struct-js2-for-node
4307 cl-struct-js2-function-node
4308 cl-struct-js2-if-node
4309 cl-struct-js2-let-node
4310 cl-struct-js2-new-node
4311 cl-struct-js2-paren-node
4312 cl-struct-js2-switch-node
4313 cl-struct-js2-while-node
4314 cl-struct-js2-with-node
4315 cl-struct-js2-xml-dot-query-node)
4316 "Node types that can have a parenthesized child expression.
4317 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4318
4319 (defsubst js2-paren-expr-node-p (node)
4320 "Return t for nodes that typically have a parenthesized child expression.
4321 Useful for computing the indentation anchors for arg-lists and conditions.
4322 Note that it may return a false positive, for instance when NODE is
4323 a `js2-new-node' and there are no arguments or parentheses."
4324 (memq (aref node 0) js2-paren-expr-nodes))
4325
4326 ;; Fake polymorphism... yech.
4327 (defsubst js2-node-lp (node)
4328 "Return relative left-paren position for NODE, if applicable.
4329 For `js2-elem-get-node' structs, returns left-bracket position.
4330 Note that the position may be nil in the case of a parse error."
4331 (cond
4332 ((js2-elem-get-node-p node)
4333 (js2-elem-get-node-lb node))
4334 ((js2-loop-node-p node)
4335 (js2-loop-node-lp node))
4336 ((js2-function-node-p node)
4337 (js2-function-node-lp node))
4338 ((js2-if-node-p node)
4339 (js2-if-node-lp node))
4340 ((js2-new-node-p node)
4341 (js2-new-node-lp node))
4342 ((js2-call-node-p node)
4343 (js2-call-node-lp node))
4344 ((js2-paren-node-p node)
4345 (js2-node-pos node))
4346 ((js2-switch-node-p node)
4347 (js2-switch-node-lp node))
4348 ((js2-catch-node-p node)
4349 (js2-catch-node-lp node))
4350 ((js2-let-node-p node)
4351 (js2-let-node-lp node))
4352 ((js2-array-comp-node-p node)
4353 (js2-array-comp-node-lp node))
4354 ((js2-with-node-p node)
4355 (js2-with-node-lp node))
4356 ((js2-xml-dot-query-node-p node)
4357 (1+ (js2-infix-node-op-pos node)))
4358 (t
4359 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4360
4361 ;; Fake polymorphism... blech.
4362 (defsubst js2-node-rp (node)
4363 "Return relative right-paren position for NODE, if applicable.
4364 For `js2-elem-get-node' structs, returns right-bracket position.
4365 Note that the position may be nil in the case of a parse error."
4366 (cond
4367 ((js2-elem-get-node-p node)
4368 (js2-elem-get-node-lb node))
4369 ((js2-loop-node-p node)
4370 (js2-loop-node-rp node))
4371 ((js2-function-node-p node)
4372 (js2-function-node-rp node))
4373 ((js2-if-node-p node)
4374 (js2-if-node-rp node))
4375 ((js2-new-node-p node)
4376 (js2-new-node-rp node))
4377 ((js2-call-node-p node)
4378 (js2-call-node-rp node))
4379 ((js2-paren-node-p node)
4380 (+ (js2-node-pos node) (js2-node-len node)))
4381 ((js2-switch-node-p node)
4382 (js2-switch-node-rp node))
4383 ((js2-catch-node-p node)
4384 (js2-catch-node-rp node))
4385 ((js2-let-node-p node)
4386 (js2-let-node-rp node))
4387 ((js2-array-comp-node-p node)
4388 (js2-array-comp-node-rp node))
4389 ((js2-with-node-p node)
4390 (js2-with-node-rp node))
4391 ((js2-xml-dot-query-node-p node)
4392 (1+ (js2-xml-dot-query-node-rp node)))
4393 (t
4394 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4395
4396 (defsubst js2-node-first-child (node)
4397 "Returns the first element of `js2-node-child-list' for NODE."
4398 (car (js2-node-child-list node)))
4399
4400 (defsubst js2-node-last-child (node)
4401 "Returns the last element of `js2-node-last-child' for NODE."
4402 (car (last (js2-node-child-list node))))
4403
4404 (defun js2-node-prev-sibling (node)
4405 "Return the previous statement in parent.
4406 Works for parents supported by `js2-node-child-list'.
4407 Returns nil if NODE is not in the parent, or PARENT is
4408 not a supported node, or if NODE is the first child."
4409 (let* ((p (js2-node-parent node))
4410 (kids (js2-node-child-list p))
4411 (sib (car kids)))
4412 (while (and kids
4413 (not (eq node (cadr kids))))
4414 (setq kids (cdr kids)
4415 sib (car kids)))
4416 sib))
4417
4418 (defun js2-node-next-sibling (node)
4419 "Return the next statement in parent block.
4420 Returns nil if NODE is not in the block, or PARENT is not
4421 a block node, or if NODE is the last statement."
4422 (let* ((p (js2-node-parent node))
4423 (kids (js2-node-child-list p)))
4424 (while (and kids
4425 (not (eq node (car kids))))
4426 (setq kids (cdr kids)))
4427 (cadr kids)))
4428
4429 (defun js2-node-find-child-before (pos parent &optional after)
4430 "Find the last child that starts before POS in parent.
4431 If AFTER is non-nil, returns first child starting after POS.
4432 POS is an absolute buffer position. PARENT is any node
4433 supported by `js2-node-child-list'.
4434 Returns nil if no applicable child is found."
4435 (let ((kids (if (js2-function-node-p parent)
4436 (js2-block-node-kids (js2-function-node-body parent))
4437 (js2-node-child-list parent)))
4438 (beg (if (js2-function-node-p parent)
4439 (js2-node-abs-pos (js2-function-node-body parent))
4440 (js2-node-abs-pos parent)))
4441 kid
4442 result
4443 fn
4444 (continue t))
4445 (setq fn (if after '> '<))
4446 (while (and kids continue)
4447 (setq kid (car kids))
4448 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4449 (setq result kid
4450 continue (if after nil t))
4451 (setq continue (if after t nil)))
4452 (setq kids (cdr kids)))
4453 result))
4454
4455 (defun js2-node-find-child-after (pos parent)
4456 "Find first child that starts after POS in parent.
4457 POS is an absolute buffer position. PARENT is any node
4458 supported by `js2-node-child-list'.
4459 Returns nil if no applicable child is found."
4460 (js2-node-find-child-before pos parent 'after))
4461
4462 (defun js2-node-replace-child (pos parent new-node)
4463 "Replace node at index POS in PARENT with NEW-NODE.
4464 Only works for parents supported by `js2-node-child-list'."
4465 (let ((kids (js2-node-child-list parent))
4466 (i 0))
4467 (while (< i pos)
4468 (setq kids (cdr kids)
4469 i (1+ i)))
4470 (setcar kids new-node)
4471 (js2-node-add-children parent new-node)))
4472
4473 (defun js2-node-buffer (n)
4474 "Return the buffer associated with AST N.
4475 Returns nil if the buffer is not set as a property on the root
4476 node, or if parent links were not recorded during parsing."
4477 (let ((root (js2-node-root n)))
4478 (and root
4479 (js2-ast-root-p root)
4480 (js2-ast-root-buffer root))))
4481
4482 (defsubst js2-block-node-push (n kid)
4483 "Push js2-node KID onto the end of js2-block-node N's child list.
4484 KID is always added to the -end- of the kids list.
4485 Function also calls `js2-node-add-children' to add the parent link."
4486 (let ((kids (js2-node-child-list n)))
4487 (if kids
4488 (setcdr kids (nconc (cdr kids) (list kid)))
4489 (js2-node-set-child-list n (list kid)))
4490 (js2-node-add-children n kid)))
4491
4492 (defun js2-node-string (node)
4493 (let ((buf (js2-node-buffer node))
4494 pos)
4495 (unless buf
4496 (error "No buffer available for node %s" node))
4497 (save-excursion
4498 (set-buffer buf)
4499 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4500 (+ pos (js2-node-len node))))))
4501
4502 ;; Container for storing the node we're looking for in a traversal.
4503 (js2-deflocal js2-discovered-node nil)
4504
4505 ;; Keep track of absolute node position during traversals.
4506 (js2-deflocal js2-visitor-offset nil)
4507
4508 (js2-deflocal js2-node-search-point nil)
4509
4510 (when js2-mode-dev-mode-p
4511 (defun js2-find-node-at-point ()
4512 (interactive)
4513 (let ((node (js2-node-at-point)))
4514 (message "%s" (or node "No node found at point"))))
4515 (defun js2-node-name-at-point ()
4516 (interactive)
4517 (let ((node (js2-node-at-point)))
4518 (message "%s" (if node
4519 (js2-node-short-name node)
4520 "No node found at point.")))))
4521
4522 (defun js2-node-at-point (&optional pos skip-comments)
4523 "Return AST node at POS, a buffer position, defaulting to current point.
4524 The `js2-mode-ast' variable must be set to the current parse tree.
4525 Signals an error if the AST (`js2-mode-ast') is nil.
4526 Always returns a node - if it can't find one, it returns the root.
4527 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4528 (let ((ast js2-mode-ast)
4529 result)
4530 (unless ast
4531 (error "No JavaScript AST available"))
4532 ;; Look through comments first, since they may be inside nodes that
4533 ;; would otherwise report a match.
4534 (setq pos (or pos (point))
4535 result (if (> pos (js2-node-abs-end ast))
4536 ast
4537 (if (not skip-comments)
4538 (js2-comment-at-point pos))))
4539 (unless result
4540 (setq js2-discovered-node nil
4541 js2-visitor-offset 0
4542 js2-node-search-point pos)
4543 (unwind-protect
4544 (catch 'js2-visit-done
4545 (js2-visit-ast ast #'js2-node-at-point-visitor))
4546 (setq js2-visitor-offset nil
4547 js2-node-search-point nil))
4548 (setq result js2-discovered-node))
4549 ;; may have found a comment beyond end of last child node,
4550 ;; since visiting the ast-root looks at the comment-list last.
4551 (if (and skip-comments
4552 (js2-comment-node-p result))
4553 (setq result nil))
4554 (or result js2-mode-ast)))
4555
4556 (defun js2-node-at-point-visitor (node end-p)
4557 (let ((rel-pos (js2-node-pos node))
4558 abs-pos
4559 abs-end
4560 (point js2-node-search-point))
4561 (cond
4562 (end-p
4563 ;; this evaluates to a non-nil return value, even if it's zero
4564 (decf js2-visitor-offset rel-pos))
4565 ;; we already looked for comments before visiting, and don't want them now
4566 ((js2-comment-node-p node)
4567 nil)
4568 (t
4569 (setq abs-pos (incf js2-visitor-offset rel-pos)
4570 ;; we only want to use the node if the point is before
4571 ;; the last character position in the node, so we decrement
4572 ;; the absolute end by 1.
4573 abs-end (+ abs-pos (js2-node-len node) -1))
4574 (cond
4575 ;; If this node starts after search-point, stop the search.
4576 ((> abs-pos point)
4577 (throw 'js2-visit-done nil))
4578 ;; If this node ends before the search-point, don't check kids.
4579 ((> point abs-end)
4580 nil)
4581 (t
4582 ;; Otherwise point is within this node, possibly in a child.
4583 (setq js2-discovered-node node)
4584 t)))))) ; keep processing kids to look for more specific match
4585
4586 (defsubst js2-block-comment-p (node)
4587 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4588 (and (js2-comment-node-p node)
4589 (memq (js2-comment-node-format node) '(jsdoc block))))
4590
4591 ;; TODO: put the comments in a vector and binary-search them instead
4592 (defun js2-comment-at-point (&optional pos)
4593 "Look through scanned comment nodes for one containing POS.
4594 POS is a buffer position that defaults to current point.
4595 Function returns nil if POS was not in any comment node."
4596 (let ((ast js2-mode-ast)
4597 (x (or pos (point)))
4598 beg
4599 end)
4600 (unless ast
4601 (error "No JavaScript AST available"))
4602 (catch 'done
4603 ;; Comments are stored in lexical order.
4604 (dolist (comment (js2-ast-root-comments ast) nil)
4605 (setq beg (js2-node-abs-pos comment)
4606 end (+ beg (js2-node-len comment)))
4607 (if (and (>= x beg)
4608 (<= x end))
4609 (throw 'done comment))))))
4610
4611 (defun js2-mode-find-parent-fn (node)
4612 "Find function enclosing NODE.
4613 Returns nil if NODE is not inside a function."
4614 (setq node (js2-node-parent node))
4615 (while (and node (not (js2-function-node-p node)))
4616 (setq node (js2-node-parent node)))
4617 (and (js2-function-node-p node) node))
4618
4619 (defun js2-mode-find-enclosing-fn (node)
4620 "Find function or root enclosing NODE."
4621 (if (js2-ast-root-p node)
4622 node
4623 (setq node (js2-node-parent node))
4624 (while (not (or (js2-ast-root-p node)
4625 (js2-function-node-p node)))
4626 (setq node (js2-node-parent node)))
4627 node))
4628
4629 (defun js2-mode-find-enclosing-node (beg end)
4630 "Find script or function fully enclosing BEG and END."
4631 (let ((node (js2-node-at-point beg))
4632 pos
4633 (continue t))
4634 (while continue
4635 (if (or (js2-ast-root-p node)
4636 (and (js2-function-node-p node)
4637 (<= (setq pos (js2-node-abs-pos node)) beg)
4638 (>= (+ pos (js2-node-len node)) end)))
4639 (setq continue nil)
4640 (setq node (js2-node-parent node))))
4641 node))
4642
4643 (defun js2-node-parent-script-or-fn (node)
4644 "Find script or function immediately enclosing NODE.
4645 If NODE is the ast-root, returns nil."
4646 (if (js2-ast-root-p node)
4647 nil
4648 (setq node (js2-node-parent node))
4649 (while (and node (not (or (js2-function-node-p node)
4650 (js2-script-node-p node))))
4651 (setq node (js2-node-parent node)))
4652 node))
4653
4654 (defsubst js2-nested-function-p (node)
4655 "Return t if NODE is a nested function, or is inside a nested function."
4656 (unless (js2-ast-root-p node)
4657 (js2-function-node-p (if (js2-function-node-p node)
4658 (js2-node-parent-script-or-fn node)
4659 (js2-node-parent-script-or-fn
4660 (js2-node-parent-script-or-fn node))))))
4661
4662 (defsubst js2-function-param-node-p (node)
4663 "Return non-nil if NODE is a param node of a `js2-function-node'."
4664 (let ((parent (js2-node-parent node)))
4665 (and parent
4666 (js2-function-node-p parent)
4667 (memq node (js2-function-node-params parent)))))
4668
4669 (defsubst js2-mode-shift-kids (kids start offset)
4670 (dolist (kid kids)
4671 (if (> (js2-node-pos kid) start)
4672 (incf (js2-node-pos kid) offset))))
4673
4674 (defsubst js2-mode-shift-children (parent start offset)
4675 "Update start-positions of all children of PARENT beyond START."
4676 (let ((root (js2-node-root parent)))
4677 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4678 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4679
4680 (defsubst js2-node-is-descendant (node ancestor)
4681 "Return t if NODE is a descendant of ANCESTOR."
4682 (while (and node
4683 (not (eq node ancestor)))
4684 (setq node (js2-node-parent node)))
4685 node)
4686
4687 ;;; visitor infrastructure
4688
4689 (defun js2-visit-none (node callback)
4690 "Visitor for AST node that have no node children."
4691 nil)
4692
4693 (defun js2-print-none (node indent)
4694 "Visitor for AST node with no printed representation.")
4695
4696 (defun js2-print-body (node indent)
4697 "Print a statement, or a block without braces."
4698 (if (js2-block-node-p node)
4699 (dolist (kid (js2-block-node-kids node))
4700 (js2-print-ast kid indent))
4701 (js2-print-ast node indent)))
4702
4703 (defun js2-print-list (args &optional delimiter)
4704 (loop with len = (length args)
4705 for arg in args
4706 for count from 1
4707 do
4708 (js2-print-ast arg 0)
4709 (if (< count len)
4710 (insert (or delimiter ", ")))))
4711
4712 (defun js2-print-tree (ast)
4713 "Prints an AST to the current buffer.
4714 Makes `js2-ast-parent-nodes' available to the printer functions."
4715 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4716 (js2-print-ast ast)))
4717
4718 (defun js2-print-ast (node &optional indent)
4719 "Helper function for printing AST nodes.
4720 Requires `js2-ast-parent-nodes' to be non-nil.
4721 You should use `js2-print-tree' instead of this function."
4722 (let ((printer (get (aref node 0) 'js2-printer))
4723 (i (or indent 0))
4724 (pos (js2-node-abs-pos node)))
4725 ;; TODO: wedge comments in here somewhere
4726 (if printer
4727 (funcall printer node i))))
4728
4729 (defconst js2-side-effecting-tokens
4730 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4731 (dolist (tt (list js2-ASSIGN
4732 js2-ASSIGN_ADD
4733 js2-ASSIGN_BITAND
4734 js2-ASSIGN_BITOR
4735 js2-ASSIGN_BITXOR
4736 js2-ASSIGN_DIV
4737 js2-ASSIGN_LSH
4738 js2-ASSIGN_MOD
4739 js2-ASSIGN_MUL
4740 js2-ASSIGN_RSH
4741 js2-ASSIGN_SUB
4742 js2-ASSIGN_URSH
4743 js2-BLOCK
4744 js2-BREAK
4745 js2-CALL
4746 js2-CATCH
4747 js2-CATCH_SCOPE
4748 js2-CONST
4749 js2-CONTINUE
4750 js2-DEBUGGER
4751 js2-DEC
4752 js2-DELPROP
4753 js2-DEL_REF
4754 js2-DO
4755 js2-ELSE
4756 js2-EMPTY
4757 js2-ENTERWITH
4758 js2-EXPORT
4759 js2-EXPR_RESULT
4760 js2-FINALLY
4761 js2-FOR
4762 js2-FUNCTION
4763 js2-GOTO
4764 js2-IF
4765 js2-IFEQ
4766 js2-IFNE
4767 js2-IMPORT
4768 js2-INC
4769 js2-JSR
4770 js2-LABEL
4771 js2-LEAVEWITH
4772 js2-LET
4773 js2-LETEXPR
4774 js2-LOCAL_BLOCK
4775 js2-LOOP
4776 js2-NEW
4777 js2-REF_CALL
4778 js2-RETHROW
4779 js2-RETURN
4780 js2-RETURN_RESULT
4781 js2-SEMI
4782 js2-SETELEM
4783 js2-SETELEM_OP
4784 js2-SETNAME
4785 js2-SETPROP
4786 js2-SETPROP_OP
4787 js2-SETVAR
4788 js2-SET_REF
4789 js2-SET_REF_OP
4790 js2-SWITCH
4791 js2-TARGET
4792 js2-THROW
4793 js2-TRY
4794 js2-VAR
4795 js2-WHILE
4796 js2-WITH
4797 js2-WITHEXPR
4798 js2-YIELD))
4799 (aset tokens tt t))
4800 (if js2-instanceof-has-side-effects
4801 (aset tokens js2-INSTANCEOF t))
4802 tokens))
4803
4804 (defun js2-node-has-side-effects (node)
4805 "Return t if NODE has side effects."
4806 (when node ; makes it easier to handle malformed expressions
4807 (let ((tt (js2-node-type node)))
4808 (cond
4809 ;; This doubtless needs some work, since EXPR_VOID is used
4810 ;; in several ways in Rhino, and I may not have caught them all.
4811 ;; I'll wait for people to notice incorrect warnings.
4812 ((and (= tt js2-EXPR_VOID)
4813 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4814 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4815 ((= tt js2-COMMA)
4816 (js2-node-has-side-effects (js2-infix-node-right node)))
4817 ((or (= tt js2-AND)
4818 (= tt js2-OR))
4819 (or (js2-node-has-side-effects (js2-infix-node-right node))
4820 (js2-node-has-side-effects (js2-infix-node-left node))))
4821 ((= tt js2-HOOK)
4822 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4823 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4824 ((js2-paren-node-p node)
4825 (js2-node-has-side-effects (js2-paren-node-expr node)))
4826 ((= tt js2-ERROR) ; avoid cascaded error messages
4827 nil)
4828 (t
4829 (aref js2-side-effecting-tokens tt))))))
4830
4831 (defun js2-member-expr-leftmost-name (node)
4832 "For an expr such as foo.bar.baz, return leftmost node foo.
4833 NODE is any `js2-node' object. If it represents a member expression,
4834 which is any sequence of property gets, element-gets, function calls,
4835 or xml descendants/filter operators, then we look at the lexically
4836 leftmost (first) node in the chain. If it is a name-node we return it.
4837 Note that NODE can be a raw name-node and it will be returned as well.
4838 If NODE is not a name-node or member expression, or if it is a member
4839 expression whose leftmost target is not a name node, returns nil."
4840 (let ((continue t)
4841 result)
4842 (while (and continue (not result))
4843 (cond
4844 ((js2-name-node-p node)
4845 (setq result node))
4846 ((js2-prop-get-node-p node)
4847 (setq node (js2-prop-get-node-left node)))
4848 ;; TODO: handle call-nodes, xml-nodes, others?
4849 (t
4850 (setq continue nil))))
4851 result))
4852
4853 (defconst js2-stmt-node-types
4854 (list js2-BLOCK
4855 js2-BREAK
4856 js2-CONTINUE
4857 js2-DEFAULT ; e4x "default xml namespace" statement
4858 js2-DO
4859 js2-EXPR_RESULT
4860 js2-EXPR_VOID
4861 js2-FOR
4862 js2-IF
4863 js2-RETURN
4864 js2-SWITCH
4865 js2-THROW
4866 js2-TRY
4867 js2-WHILE
4868 js2-WITH)
4869 "Node types that only appear in statement contexts.
4870 The list does not include nodes that always appear as the child
4871 of another specific statement type, such as switch-cases,
4872 catch and finally blocks, and else-clauses. The list also excludes
4873 nodes like yield, let and var, which may appear in either expression
4874 or statement context, and in the latter context always have a
4875 `js2-expr-stmt-node' parent. Finally, the list does not include
4876 functions or scripts, which are treated separately from statements
4877 by the JavaScript parser and runtime.")
4878
4879 (defun js2-stmt-node-p (node)
4880 "Heuristic for figuring out if NODE is a statement.
4881 Some node types can appear in either an expression context or a
4882 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4883 For these node types in a statement context, the parent will be a
4884 `js2-expr-stmt-node'.
4885 Functions aren't included in the check."
4886 (memq (js2-node-type node) js2-stmt-node-types))
4887
4888 (defsubst js2-mode-find-first-stmt (node)
4889 "Search upward starting from NODE looking for a statement.
4890 For purposes of this function, a `js2-function-node' counts."
4891 (while (not (or (js2-stmt-node-p node)
4892 (js2-function-node-p node)))
4893 (setq node (js2-node-parent node)))
4894 node)
4895
4896 (defun js2-node-parent-stmt (node)
4897 "Return the node's first ancestor that is a statement.
4898 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4899 appearing in a statement context will have a parent that is a
4900 `js2-expr-stmt-node' that will be returned by this function."
4901 (let ((parent (js2-node-parent node)))
4902 (if (or (null parent)
4903 (js2-stmt-node-p parent)
4904 (and (js2-function-node-p parent)
4905 (not (eq (js2-function-node-form parent)
4906 'FUNCTION_EXPRESSION))))
4907 parent
4908 (js2-node-parent-stmt parent))))
4909
4910 ;; In the Mozilla Rhino sources, Roshan James writes:
4911 ;; Does consistent-return analysis on the function body when strict mode is
4912 ;; enabled.
4913 ;;
4914 ;; function (x) { return (x+1) }
4915 ;;
4916 ;; is ok, but
4917 ;;
4918 ;; function (x) { if (x < 0) return (x+1); }
4919 ;;
4920 ;; is not because the function can potentially return a value when the
4921 ;; condition is satisfied and if not, the function does not explicitly
4922 ;; return a value.
4923 ;;
4924 ;; This extends to checking mismatches such as "return" and "return <value>"
4925 ;; used in the same function. Warnings are not emitted if inconsistent
4926 ;; returns exist in code that can be statically shown to be unreachable.
4927 ;; Ex.
4928 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4929 ;;
4930 ;; emits no warning. However if the loop had a break statement, then a
4931 ;; warning would be emitted.
4932 ;;
4933 ;; The consistency analysis looks at control structures such as loops, ifs,
4934 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4935 ;; warns the user about an inconsistent set of termination possibilities.
4936 ;;
4937 ;; These flags enumerate the possible ways a statement/function can
4938 ;; terminate. These flags are used by endCheck() and by the Parser to
4939 ;; detect inconsistent return usage.
4940 ;;
4941 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4942 ;; able to execute (example: throw, continue)
4943 ;;
4944 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4945 ;; next one. Statement such as return dont. A compound statement may have
4946 ;; some branch that drops off control to the next statement.
4947 ;;
4948 ;; END_RETURNS indicates that the statement can return with no value.
4949 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4950 ;;
4951 ;; A compound statement such as
4952 ;; if (condition) {
4953 ;; return value;
4954 ;; }
4955 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4956
4957 (defconst js2-END_UNREACHED 0)
4958 (defconst js2-END_DROPS_OFF 1)
4959 (defconst js2-END_RETURNS 2)
4960 (defconst js2-END_RETURNS_VALUE 4)
4961 (defconst js2-END_YIELDS 8)
4962
4963 (defun js2-has-consistent-return-usage (node)
4964 "Check that every return usage in a function body is consistent.
4965 Returns t if the function satisfies strict mode requirement."
4966 (let ((n (js2-end-check node)))
4967 ;; either it doesn't return a value in any branch...
4968 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4969 ;; or it returns a value (or is unreached) at every branch
4970 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4971 js2-END_RETURNS
4972 js2-END_YIELDS)))))
4973
4974 (defun js2-end-check-if (node)
4975 "Returns in the then and else blocks must be consistent with each other.
4976 If there is no else block, then the return statement can fall through.
4977 Returns logical OR of END_* flags"
4978 (let ((th (js2-if-node-then-part node))
4979 (el (js2-if-node-else-part node)))
4980 (if (null th)
4981 js2-END_UNREACHED
4982 (logior (js2-end-check th) (if el
4983 (js2-end-check el)
4984 js2-END_DROPS_OFF)))))
4985
4986 (defun js2-end-check-switch (node)
4987 "Consistency of return statements is checked between the case statements.
4988 If there is no default, then the switch can fall through. If there is a
4989 default, we check to see if all code paths in the default return or if
4990 there is a code path that can fall through.
4991 Returns logical OR of END_* flags."
4992 (let ((rv js2-END_UNREACHED)
4993 default-case)
4994 ;; examine the cases
4995 (catch 'break
4996 (dolist (c (js2-switch-node-cases node))
4997 (if (js2-case-node-expr c)
4998 (js2-set-flag rv (js2-end-check-block c))
4999 (setq default-case c)
5000 (throw 'break nil))))
5001 ;; we don't care how the cases drop into each other
5002 (js2-clear-flag rv js2-END_DROPS_OFF)
5003 ;; examine the default
5004 (js2-set-flag rv (if default-case
5005 (js2-end-check default-case)
5006 js2-END_DROPS_OFF))
5007 rv))
5008
5009 (defun js2-end-check-try (node)
5010 "If the block has a finally, return consistency is checked in the
5011 finally block. If all code paths in the finally return, then the
5012 returns in the try-catch blocks don't matter. If there is a code path
5013 that does not return or if there is no finally block, the returns
5014 of the try and catch blocks are checked for mismatch.
5015 Returns logical OR of END_* flags."
5016 (let ((finally (js2-try-node-finally-block node))
5017 rv)
5018 ;; check the finally if it exists
5019 (setq rv (if finally
5020 (js2-end-check (js2-finally-node-body finally))
5021 js2-END_DROPS_OFF))
5022 ;; If the finally block always returns, then none of the returns
5023 ;; in the try or catch blocks matter.
5024 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5025 (js2-clear-flag rv js2-END_DROPS_OFF)
5026 ;; examine the try block
5027 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5028 ;; check each catch block
5029 (dolist (cb (js2-try-node-catch-clauses node))
5030 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5031 rv))
5032
5033 (defun js2-end-check-loop (node)
5034 "Return statement in the loop body must be consistent. The default
5035 assumption for any kind of a loop is that it will eventually terminate.
5036 The only exception is a loop with a constant true condition. Code that
5037 follows such a loop is examined only if one can statically determine
5038 that there is a break out of the loop.
5039
5040 for(... ; ... ; ...) {}
5041 for(... in ... ) {}
5042 while(...) { }
5043 do { } while(...)
5044
5045 Returns logical OR of END_* flags."
5046 (let ((rv (js2-end-check (js2-loop-node-body node)))
5047 (condition (cond
5048 ((js2-while-node-p node)
5049 (js2-while-node-condition node))
5050 ((js2-do-node-p node)
5051 (js2-do-node-condition node))
5052 ((js2-for-node-p node)
5053 (js2-for-node-condition node)))))
5054
5055 ;; check to see if the loop condition is always true
5056 (if (and condition
5057 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5058 (js2-clear-flag rv js2-END_DROPS_OFF))
5059
5060 ;; look for effect of breaks
5061 (js2-set-flag rv (js2-node-get-prop node
5062 'CONTROL_BLOCK_PROP
5063 js2-END_UNREACHED))
5064 rv))
5065
5066 (defun js2-end-check-block (node)
5067 "A general block of code is examined statement by statement.
5068 If any statement (even a compound one) returns in all branches, then
5069 subsequent statements are not examined.
5070 Returns logical OR of END_* flags."
5071 (let* ((rv js2-END_DROPS_OFF)
5072 (kids (js2-block-node-kids node))
5073 (n (car kids)))
5074 ;; Check each statment. If the statement can continue onto the next
5075 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5076 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5077 (js2-clear-flag rv js2-END_DROPS_OFF)
5078 (js2-set-flag rv (js2-end-check n))
5079 (setq kids (cdr kids)
5080 n (car kids)))
5081 rv))
5082
5083 (defun js2-end-check-label (node)
5084 "A labeled statement implies that there may be a break to the label.
5085 The function processes the labeled statement and then checks the
5086 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5087 particular label.
5088 Returns logical OR of END_* flags."
5089 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5090 (logior rv (js2-node-get-prop node
5091 'CONTROL_BLOCK_PROP
5092 js2-END_UNREACHED))))
5093
5094 (defun js2-end-check-break (node)
5095 "When a break is encountered annotate the statement being broken
5096 out of by setting its CONTROL_BLOCK_PROP property.
5097 Returns logical OR of END_* flags."
5098 (and (js2-break-node-target node)
5099 (js2-node-set-prop (js2-break-node-target node)
5100 'CONTROL_BLOCK_PROP
5101 js2-END_DROPS_OFF))
5102 js2-END_UNREACHED)
5103
5104 (defun js2-end-check (node)
5105 "Examine the body of a function, doing a basic reachability analysis.
5106 Returns a combination of flags END_* flags that indicate
5107 how the function execution can terminate. These constitute only the
5108 pessimistic set of termination conditions. It is possible that at
5109 runtime certain code paths will never be actually taken. Hence this
5110 analysis will flag errors in cases where there may not be errors.
5111 Returns logical OR of END_* flags"
5112 (let (kid)
5113 (cond
5114 ((js2-break-node-p node)
5115 (js2-end-check-break node))
5116 ((js2-expr-stmt-node-p node)
5117 (if (setq kid (js2-expr-stmt-node-expr node))
5118 (js2-end-check kid)
5119 js2-END_DROPS_OFF))
5120 ((or (js2-continue-node-p node)
5121 (js2-throw-node-p node))
5122 js2-END_UNREACHED)
5123 ((js2-return-node-p node)
5124 (if (setq kid (js2-return-node-retval node))
5125 js2-END_RETURNS_VALUE
5126 js2-END_RETURNS))
5127 ((js2-loop-node-p node)
5128 (js2-end-check-loop node))
5129 ((js2-switch-node-p node)
5130 (js2-end-check-switch node))
5131 ((js2-labeled-stmt-node-p node)
5132 (js2-end-check-label node))
5133 ((js2-if-node-p node)
5134 (js2-end-check-if node))
5135 ((js2-try-node-p node)
5136 (js2-end-check-try node))
5137 ((js2-block-node-p node)
5138 (if (null (js2-block-node-kids node))
5139 js2-END_DROPS_OFF
5140 (js2-end-check-block node)))
5141 ((js2-yield-node-p node)
5142 js2-END_YIELDS)
5143 (t
5144 js2-END_DROPS_OFF))))
5145
5146 (defun js2-always-defined-boolean-p (node)
5147 "Check if NODE always evaluates to true or false in boolean context.
5148 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5149 nor always false."
5150 (let ((tt (js2-node-type node))
5151 num)
5152 (cond
5153 ((or (= tt js2-FALSE) (= tt js2-NULL))
5154 'ALWAYS_FALSE)
5155 ((= tt js2-TRUE)
5156 'ALWAYS_TRUE)
5157 ((= tt js2-NUMBER)
5158 (setq num (js2-number-node-num-value node))
5159 (if (and (not (eq num 0.0e+NaN))
5160 (not (zerop num)))
5161 'ALWAYS_TRUE
5162 'ALWAYS_FALSE))
5163 (t
5164 nil))))
5165
5166 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5167 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5168
5169 (defvar js2-tokens nil
5170 "List of all defined token names.") ; initialized in `js2-token-names'
5171
5172 (defconst js2-token-names
5173 (let* ((names (make-vector js2-num-tokens -1))
5174 (case-fold-search nil) ; only match js2-UPPER_CASE
5175 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5176 (loop for sym in syms
5177 for i from 0
5178 do
5179 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5180 (not (boundp sym)))
5181 (aset names (symbol-value sym) ; code, e.g. 152
5182 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5183 (push sym js2-tokens)))
5184 names)
5185 "Vector mapping int values to token string names, sans `js2-' prefix.")
5186
5187 (defun js2-token-name (tok)
5188 "Return a string name for TOK, a token symbol or code.
5189 Signals an error if it's not a recognized token."
5190 (let ((code tok))
5191 (if (symbolp tok)
5192 (setq code (symbol-value tok)))
5193 (if (eq code -1)
5194 "ERROR"
5195 (if (and (numberp code)
5196 (not (minusp code))
5197 (< code js2-num-tokens))
5198 (aref js2-token-names code)
5199 (error "Invalid token: %s" code)))))
5200
5201 (defsubst js2-token-sym (tok)
5202 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5203 (intern (js2-token-name tok)))
5204
5205 (defconst js2-token-codes
5206 (let ((table (make-hash-table :test 'eq :size 256)))
5207 (loop for name across js2-token-names
5208 for sym = (intern (concat "js2-" name))
5209 do
5210 (puthash sym (symbol-value sym) table))
5211 ;; clean up a few that are "wrong" in Rhino's token codes
5212 (puthash 'js2-DELETE js2-DELPROP table)
5213 table)
5214 "Hashtable mapping token symbols to their bytecodes.")
5215
5216 (defsubst js2-token-code (sym)
5217 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5218 (or (gethash sym js2-token-codes)
5219 (error "Invalid token symbol: %s " sym))) ; signal code bug
5220
5221 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5222 (setq js2-token-end js2-ts-cursor)
5223 (js2-report-error msg nil
5224 (or beg js2-token-beg)
5225 (or len (- js2-token-end js2-token-beg)))
5226 (unless no-throw
5227 (throw 'return js2-ERROR)))
5228
5229 (defsubst js2-get-string-from-buffer ()
5230 "Reverse the char accumulator and return it as a string."
5231 (setq js2-token-end js2-ts-cursor)
5232 (if js2-ts-string-buffer
5233 (apply #'string (nreverse js2-ts-string-buffer))
5234 ""))
5235
5236 ;; TODO: could potentially avoid a lot of consing by allocating a
5237 ;; char buffer the way Rhino does.
5238 (defsubst js2-add-to-string (c)
5239 (push c js2-ts-string-buffer))
5240
5241 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5242 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5243 ;; any other character: when it's not part of the current token, we
5244 ;; unget it, allowing it to be read again by the following call.
5245 (defsubst js2-unget-char ()
5246 (decf js2-ts-cursor))
5247
5248 ;; Rhino distinguishes \r and \n line endings. We don't need to
5249 ;; because we only scan from Emacs buffers, which always use \n.
5250 (defsubst js2-get-char ()
5251 "Read and return the next character from the input buffer.
5252 Increments `js2-ts-lineno' if the return value is a newline char.
5253 Updates `js2-ts-cursor' to the point after the returned char.
5254 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5255 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5256 (let (c)
5257 ;; check for end of buffer
5258 (if (>= js2-ts-cursor (point-max))
5259 (setq js2-ts-hit-eof t
5260 js2-ts-cursor (1+ js2-ts-cursor)
5261 c js2-EOF_CHAR) ; return value
5262 ;; otherwise read next char
5263 (setq c (char-before (incf js2-ts-cursor)))
5264 ;; if we read a newline, update counters
5265 (if (= c ?\n)
5266 (setq js2-ts-line-start js2-ts-cursor
5267 js2-ts-lineno (1+ js2-ts-lineno)))
5268 ;; TODO: skip over format characters
5269 c)))
5270
5271 (defsubst js2-read-unicode-escape ()
5272 "Read a \\uNNNN sequence from the input.
5273 Assumes the ?\ and ?u have already been read.
5274 Returns the unicode character, or nil if it wasn't a valid character.
5275 Doesn't change the values of any scanner variables."
5276 ;; I really wish I knew a better way to do this, but I can't
5277 ;; find the Emacs function that takes a 16-bit int and converts
5278 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5279 ;; Have to first check that it's 4 hex characters or it may stop
5280 ;; the read early.
5281 (ignore-errors
5282 (let ((s (buffer-substring-no-properties js2-ts-cursor
5283 (+ 4 js2-ts-cursor))))
5284 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5285 (read (concat "?\\u" s))))))
5286
5287 (defsubst js2-match-char (test)
5288 "Consume and return next character if it matches TEST, a character.
5289 Returns nil and consumes nothing if TEST is not the next character."
5290 (let ((c (js2-get-char)))
5291 (if (eq c test)
5292 t
5293 (js2-unget-char)
5294 nil)))
5295
5296 (defsubst js2-peek-char ()
5297 (prog1
5298 (js2-get-char)
5299 (js2-unget-char)))
5300
5301 (defsubst js2-java-identifier-start-p (c)
5302 (or
5303 (memq c '(?$ ?_))
5304 (js2-char-uppercase-p c)
5305 (js2-char-lowercase-p c)))
5306
5307 (defsubst js2-java-identifier-part-p (c)
5308 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5309 ;; TODO: make me Unicode-friendly. See comments above.
5310 (or
5311 (memq c '(?$ ?_))
5312 (js2-char-uppercase-p c)
5313 (js2-char-lowercase-p c)
5314 (and (>= c ?0) (<= c ?9))))
5315
5316 (defsubst js2-alpha-p (c)
5317 (cond ((and (<= ?A c) (<= c ?Z)) t)
5318 ((and (<= ?a c) (<= c ?z)) t)
5319 (t nil)))
5320
5321 (defsubst js2-digit-p (c)
5322 (and (<= ?0 c) (<= c ?9)))
5323
5324 (defsubst js2-js-space-p (c)
5325 (if (<= c 127)
5326 (memq c '(#x20 #x9 #xB #xC #xD))
5327 (or
5328 (eq c #xA0)
5329 ;; TODO: change this nil to check for Unicode space character
5330 nil)))
5331
5332 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5333
5334 (defsubst js2-skip-line ()
5335 "Skip to end of line"
5336 (let (c)
5337 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5338 (js2-unget-char)
5339 (setq js2-token-end js2-ts-cursor)))
5340
5341 (defun js2-init-scanner (&optional buf line)
5342 "Create token stream for BUF starting on LINE.
5343 BUF defaults to current-buffer and line defaults to 1.
5344
5345 A buffer can only have one scanner active at a time, which yields
5346 dramatically simpler code than using a defstruct. If you need to
5347 have simultaneous scanners in a buffer, copy the regions to scan
5348 into temp buffers."
5349 (save-excursion
5350 (when buf
5351 (set-buffer buf))
5352 (setq js2-ts-dirty-line nil
5353 js2-ts-regexp-flags nil
5354 js2-ts-string ""
5355 js2-ts-number nil
5356 js2-ts-hit-eof nil
5357 js2-ts-line-start 0
5358 js2-ts-lineno (or line 1)
5359 js2-ts-line-end-char -1
5360 js2-ts-cursor (point-min)
5361 js2-ts-is-xml-attribute nil
5362 js2-ts-xml-is-tag-content nil
5363 js2-ts-xml-open-tags-count 0
5364 js2-ts-string-buffer nil)))
5365
5366 ;; This function uses the cached op, string and number fields in
5367 ;; TokenStream; if getToken has been called since the passed token
5368 ;; was scanned, the op or string printed may be incorrect.
5369 (defun js2-token-to-string (token)
5370 ;; Not sure where this function is used in Rhino. Not tested.
5371 (if (not js2-debug-print-trees)
5372 ""
5373 (let ((name (js2-token-name token)))
5374 (cond
5375 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5376 (concat name " `" js2-ts-string "'"))
5377 ((eq token js2-NUMBER)
5378 (format "NUMBER %g" js2-ts-number))
5379 (t
5380 name)))))
5381
5382 (defconst js2-keywords
5383 '(break
5384 case catch const continue
5385 debugger default delete do
5386 else enum
5387 false finally for function
5388 if in instanceof import
5389 let
5390 new null
5391 return
5392 switch
5393 this throw true try typeof
5394 var void
5395 while with
5396 yield))
5397
5398 ;; Token names aren't exactly the same as the keywords, unfortunately.
5399 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5400 (defconst js2-kwd-tokens
5401 (let ((table (make-vector js2-num-tokens nil))
5402 (tokens
5403 (list js2-BREAK
5404 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5405 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5406 js2-ELSE
5407 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5408 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5409 js2-LET
5410 js2-NEW js2-NULL
5411 js2-RETURN
5412 js2-SWITCH
5413 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5414 js2-VAR
5415 js2-WHILE js2-WITH
5416 js2-YIELD)))
5417 (dolist (i tokens)
5418 (aset table i 'font-lock-keyword-face))
5419 (aset table js2-STRING 'font-lock-string-face)
5420 (aset table js2-REGEXP 'font-lock-string-face)
5421 (aset table js2-COMMENT 'font-lock-comment-face)
5422 (aset table js2-THIS 'font-lock-builtin-face)
5423 (aset table js2-VOID 'font-lock-constant-face)
5424 (aset table js2-NULL 'font-lock-constant-face)
5425 (aset table js2-TRUE 'font-lock-constant-face)
5426 (aset table js2-FALSE 'font-lock-constant-face)
5427 table)
5428 "Vector whose values are non-nil for tokens that are keywords.
5429 The values are default faces to use for highlighting the keywords.")
5430
5431 (defconst js2-reserved-words
5432 '(abstract
5433 boolean byte
5434 char class
5435 double
5436 enum export extends
5437 final float
5438 goto
5439 implements import int interface
5440 long
5441 native
5442 package private protected public
5443 short static super synchronized
5444 throws transient
5445 volatile))
5446
5447 (defconst js2-keyword-names
5448 (let ((table (make-hash-table :test 'equal)))
5449 (loop for k in js2-keywords
5450 do (puthash
5451 (symbol-name k) ; instanceof
5452 (intern (concat "js2-"
5453 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5454 table))
5455 table)
5456 "JavaScript keywords by name, mapped to their symbols.")
5457
5458 (defconst js2-reserved-word-names
5459 (let ((table (make-hash-table :test 'equal)))
5460 (loop for k in js2-reserved-words
5461 do
5462 (puthash (symbol-name k) 'js2-RESERVED table))
5463 table)
5464 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5465
5466 (defsubst js2-collect-string (buf)
5467 "Convert BUF, a list of chars, to a string.
5468 Reverses BUF before converting."
5469 (cond
5470 ((stringp buf)
5471 buf)
5472 ((null buf) ; for emacs21 compat
5473 "")
5474 (t
5475 (if buf
5476 (apply #'string (nreverse buf))
5477 ""))))
5478
5479 (defun js2-string-to-keyword (s)
5480 "Return token for S, a string, if S is a keyword or reserved word.
5481 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5482 (or (gethash s js2-keyword-names)
5483 (gethash s js2-reserved-word-names)))
5484
5485 (defsubst js2-ts-set-char-token-bounds ()
5486 "Used when next token is one character."
5487 (setq js2-token-beg (1- js2-ts-cursor)
5488 js2-token-end js2-ts-cursor))
5489
5490 (defsubst js2-ts-return (token)
5491 "Return an N-character TOKEN from `js2-get-token'.
5492 Updates `js2-token-end' accordingly."
5493 (setq js2-token-end js2-ts-cursor)
5494 (throw 'return token))
5495
5496 (defsubst js2-x-digit-to-int (c accumulator)
5497 "Build up a hex number.
5498 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5499 corresponding number. Otherwise return -1."
5500 (catch 'return
5501 (catch 'check
5502 ;; Use 0..9 < A..Z < a..z
5503 (cond
5504 ((<= c ?9)
5505 (decf c ?0)
5506 (if (<= 0 c)
5507 (throw 'check nil)))
5508 ((<= c ?F)
5509 (when (<= ?A c)
5510 (decf c (- ?A 10))
5511 (throw 'check nil)))
5512 ((<= c ?f)
5513 (when (<= ?a c)
5514 (decf c (- ?a 10))
5515 (throw 'check nil))))
5516 (throw 'return -1))
5517 (logior c (lsh accumulator 4))))
5518
5519 (defun js2-get-token ()
5520 "Return next JavaScript token, an int such as js2-RETURN."
5521 (let (c
5522 c1
5523 identifier-start
5524 is-unicode-escape-start
5525 contains-escape
5526 escape-val
5527 escape-start
5528 str
5529 result
5530 base
5531 is-integer
5532 quote-char
5533 val
5534 look-for-slash
5535 continue)
5536 (catch 'return
5537 (while t
5538 ;; Eat whitespace, possibly sensitive to newlines.
5539 (setq continue t)
5540 (while continue
5541 (setq c (js2-get-char))
5542 (cond
5543 ((eq c js2-EOF_CHAR)
5544 (js2-ts-set-char-token-bounds)
5545 (throw 'return js2-EOF))
5546 ((eq c ?\n)
5547 (js2-ts-set-char-token-bounds)
5548 (setq js2-ts-dirty-line nil)
5549 (throw 'return js2-EOL))
5550 ((not (js2-js-space-p c))
5551 (if (/= c ?-) ; in case end of HTML comment
5552 (setq js2-ts-dirty-line t))
5553 (setq continue nil))))
5554 ;; Assume the token will be 1 char - fixed up below.
5555 (js2-ts-set-char-token-bounds)
5556 (when (eq c ?@)
5557 (throw 'return js2-XMLATTR))
5558 ;; identifier/keyword/instanceof?
5559 ;; watch out for starting with a <backslash>
5560 (cond
5561 ((eq c ?\\)
5562 (setq c (js2-get-char))
5563 (if (eq c ?u)
5564 (setq identifier-start t
5565 is-unicode-escape-start t
5566 js2-ts-string-buffer nil)
5567 (setq identifier-start nil)
5568 (js2-unget-char)
5569 (setq c ?\\)))
5570 (t
5571 (when (setq identifier-start (js2-java-identifier-start-p c))
5572 (setq js2-ts-string-buffer nil)
5573 (js2-add-to-string c))))
5574 (when identifier-start
5575 (setq contains-escape is-unicode-escape-start)
5576 (catch 'break
5577 (while t
5578 (if is-unicode-escape-start
5579 ;; strictly speaking we should probably push-back
5580 ;; all the bad characters if the <backslash>uXXXX
5581 ;; sequence is malformed. But since there isn't a
5582 ;; correct context(is there?) for a bad Unicode
5583 ;; escape sequence in an identifier, we can report
5584 ;; an error here.
5585 (progn
5586 (setq escape-val 0)
5587 (dotimes (i 4)
5588 (setq c (js2-get-char)
5589 escape-val (js2-x-digit-to-int c escape-val))
5590 ;; Next check takes care of c < 0 and bad escape
5591 (if (minusp escape-val)
5592 (throw 'break nil)))
5593 (if (minusp escape-val)
5594 (js2-report-scan-error "msg.invalid.escape" t))
5595 (js2-add-to-string escape-val)
5596 (setq is-unicode-escape-start nil))
5597 (setq c (js2-get-char))
5598 (cond
5599 ((eq c ?\\)
5600 (setq c (js2-get-char))
5601 (if (eq c ?u)
5602 (setq is-unicode-escape-start t
5603 contains-escape t)
5604 (js2-report-scan-error "msg.illegal.character" t)))
5605 (t
5606 (if (or (eq c js2-EOF_CHAR)
5607 (not (js2-java-identifier-part-p c)))
5608 (throw 'break nil))
5609 (js2-add-to-string c))))))
5610 (js2-unget-char)
5611 (setq str (js2-get-string-from-buffer))
5612 (unless contains-escape
5613 ;; OPT we shouldn't have to make a string (object!) to
5614 ;; check if it's a keyword.
5615 ;; Return the corresponding token if it's a keyword
5616 (when (setq result (js2-string-to-keyword str))
5617 (if (and (< js2-language-version 170)
5618 (memq result '(js2-LET js2-YIELD)))
5619 ;; LET and YIELD are tokens only in 1.7 and later
5620 (setq result 'js2-NAME))
5621 (if (not (eq result 'js2-RESERVED))
5622 (throw 'return (js2-token-code result)))
5623 (js2-report-warning "msg.reserved.keyword" str)))
5624 ;; If we want to intern these as Rhino does, just use (intern str)
5625 (setq js2-ts-string str)
5626 (throw 'return js2-NAME)) ; end identifier/kwd check
5627 ;; is it a number?
5628 (when (or (js2-digit-p c)
5629 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5630 (setq js2-ts-string-buffer nil
5631 base 10)
5632 (when (eq c ?0)
5633 (setq c (js2-get-char))
5634 (cond
5635 ((or (eq c ?x) (eq c ?X))
5636 (setq base 16)
5637 (setq c (js2-get-char)))
5638 ((js2-digit-p c)
5639 (setq base 8))
5640 (t
5641 (js2-add-to-string ?0))))
5642 (if (eq base 16)
5643 (while (<= 0 (js2-x-digit-to-int c 0))
5644 (js2-add-to-string c)
5645 (setq c (js2-get-char)))
5646 (while (and (<= ?0 c) (<= c ?9))
5647 ;; We permit 08 and 09 as decimal numbers, which
5648 ;; makes our behavior a superset of the ECMA
5649 ;; numeric grammar. We might not always be so
5650 ;; permissive, so we warn about it.
5651 (when (and (eq base 8) (>= c ?8))
5652 (js2-report-warning "msg.bad.octal.literal"
5653 (if (eq c ?8) "8" "9"))
5654 (setq base 10))
5655 (js2-add-to-string c)
5656 (setq c (js2-get-char))))
5657 (setq is-integer t)
5658 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5659 (setq is-integer nil)
5660 (when (eq c ?.)
5661 (loop do
5662 (js2-add-to-string c)
5663 (setq c (js2-get-char))
5664 while (js2-digit-p c)))
5665 (when (memq c '(?e ?E))
5666 (js2-add-to-string c)
5667 (setq c (js2-get-char))
5668 (when (memq c '(?+ ?-))
5669 (js2-add-to-string c)
5670 (setq c (js2-get-char)))
5671 (unless (js2-digit-p c)
5672 (js2-report-scan-error "msg.missing.exponent" t))
5673 (loop do
5674 (js2-add-to-string c)
5675 (setq c (js2-get-char))
5676 while (js2-digit-p c))))
5677 (js2-unget-char)
5678 (setq js2-ts-string (js2-get-string-from-buffer)
5679 js2-ts-number
5680 (if (and (eq base 10) (not is-integer))
5681 (string-to-number js2-ts-string)
5682 ;; TODO: call runtime number-parser. Some of it is in
5683 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5684 (string-to-number js2-ts-string)))
5685 (throw 'return js2-NUMBER))
5686 ;; is it a string?
5687 (when (memq c '(?\" ?\'))
5688 ;; We attempt to accumulate a string the fast way, by
5689 ;; building it directly out of the reader. But if there
5690 ;; are any escaped characters in the string, we revert to
5691 ;; building it out of a string buffer.
5692 (setq quote-char c
5693 js2-ts-string-buffer nil
5694 c (js2-get-char))
5695 (catch 'break
5696 (while (/= c quote-char)
5697 (catch 'continue
5698 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5699 (js2-unget-char)
5700 (setq js2-token-end js2-ts-cursor)
5701 (js2-report-error "msg.unterminated.string.lit")
5702 (throw 'return js2-STRING))
5703 (when (eq c ?\\)
5704 ;; We've hit an escaped character
5705 (setq c (js2-get-char))
5706 (case c
5707 (?b (setq c ?\b))
5708 (?f (setq c ?\f))
5709 (?n (setq c ?\n))
5710 (?r (setq c ?\r))
5711 (?t (setq c ?\t))
5712 (?v (setq c ?\v))
5713 (?u
5714 (setq c1 (js2-read-unicode-escape))
5715 (if js2-parse-ide-mode
5716 (if c1
5717 (progn
5718 ;; just copy the string in IDE-mode
5719 (js2-add-to-string ?\\)
5720 (js2-add-to-string ?u)
5721 (dotimes (i 3)
5722 (js2-add-to-string (js2-get-char)))
5723 (setq c (js2-get-char))) ; added at end of loop
5724 ;; flag it as an invalid escape
5725 (js2-report-warning "msg.invalid.escape"
5726 nil (- js2-ts-cursor 2) 6))
5727 ;; Get 4 hex digits; if the u escape is not
5728 ;; followed by 4 hex digits, use 'u' + the
5729 ;; literal character sequence that follows.
5730 (js2-add-to-string ?u)
5731 (setq escape-val 0)
5732 (dotimes (i 4)
5733 (setq c (js2-get-char)
5734 escape-val (js2-x-digit-to-int c escape-val))
5735 (if (minusp escape-val)
5736 (throw 'continue nil))
5737 (js2-add-to-string c))
5738 ;; prepare for replace of stored 'u' sequence by escape value
5739 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5740 c escape-val)))
5741 (?x
5742 ;; Get 2 hex digits, defaulting to 'x'+literal
5743 ;; sequence, as above.
5744 (setq c (js2-get-char)
5745 escape-val (js2-x-digit-to-int c 0))
5746 (if (minusp escape-val)
5747 (progn
5748 (js2-add-to-string ?x)
5749 (throw 'continue nil))
5750 (setq c1 c
5751 c (js2-get-char)
5752 escape-val (js2-x-digit-to-int c escape-val))
5753 (if (minusp escape-val)
5754 (progn
5755 (js2-add-to-string ?x)
5756 (js2-add-to-string c1)
5757 (throw 'continue nil))
5758 ;; got 2 hex digits
5759 (setq c escape-val))))
5760 (?\n
5761 ;; Remove line terminator after escape to follow
5762 ;; SpiderMonkey and C/C++
5763 (setq c (js2-get-char))
5764 (throw 'continue nil))
5765 (t
5766 (when (and (<= ?0 c) (< c ?8))
5767 (setq val (- c ?0)
5768 c (js2-get-char))
5769 (when (and (<= ?0 c) (< c ?8))
5770 (setq val (- (+ (* 8 val) c) ?0)
5771 c (js2-get-char))
5772 (when (and (<= ?0 c)
5773 (< c ?8)
5774 (< val #o37))
5775 ;; c is 3rd char of octal sequence only
5776 ;; if the resulting val <= 0377
5777 (setq val (- (+ (* 8 val) c) ?0)
5778 c (js2-get-char))))
5779 (js2-unget-char)
5780 (setq c val)))))
5781 (js2-add-to-string c)
5782 (setq c (js2-get-char)))))
5783 (setq js2-ts-string (js2-get-string-from-buffer))
5784 (throw 'return js2-STRING))
5785 (case c
5786 (?\;
5787 (throw 'return js2-SEMI))
5788 (?\[
5789 (throw 'return js2-LB))
5790 (?\]
5791 (throw 'return js2-RB))
5792 (?{
5793 (throw 'return js2-LC))
5794 (?}
5795 (throw 'return js2-RC))
5796 (?\(
5797 (throw 'return js2-LP))
5798 (?\)
5799 (throw 'return js2-RP))
5800 (?,
5801 (throw 'return js2-COMMA))
5802 (??
5803 (throw 'return js2-HOOK))
5804 (?:
5805 (if (js2-match-char ?:)
5806 (js2-ts-return js2-COLONCOLON)
5807 (throw 'return js2-COLON)))
5808 (?.
5809 (if (js2-match-char ?.)
5810 (js2-ts-return js2-DOTDOT)
5811 (if (js2-match-char ?\()
5812 (js2-ts-return js2-DOTQUERY)
5813 (throw 'return js2-DOT))))
5814 (?|
5815 (if (js2-match-char ?|)
5816 (throw 'return js2-OR)
5817 (if (js2-match-char ?=)
5818 (js2-ts-return js2-ASSIGN_BITOR)
5819 (throw 'return js2-BITOR))))
5820 (?^
5821 (if (js2-match-char ?=)
5822 (js2-ts-return js2-ASSIGN_BITOR)
5823 (throw 'return js2-BITXOR)))
5824 (?&
5825 (if (js2-match-char ?&)
5826 (throw 'return js2-AND)
5827 (if (js2-match-char ?=)
5828 (js2-ts-return js2-ASSIGN_BITAND)
5829 (throw 'return js2-BITAND))))
5830 (?=
5831 (if (js2-match-char ?=)
5832 (if (js2-match-char ?=)
5833 (js2-ts-return js2-SHEQ)
5834 (throw 'return js2-EQ))
5835 (throw 'return js2-ASSIGN)))
5836 (?!
5837 (if (js2-match-char ?=)
5838 (if (js2-match-char ?=)
5839 (js2-ts-return js2-SHNE)
5840 (js2-ts-return js2-NE))
5841 (throw 'return js2-NOT)))
5842 (?<
5843 ;; NB:treat HTML begin-comment as comment-till-eol
5844 (when (js2-match-char ?!)
5845 (when (js2-match-char ?-)
5846 (when (js2-match-char ?-)
5847 (js2-skip-line)
5848 (setq js2-ts-comment-type 'html)
5849 (throw 'return js2-COMMENT)))
5850 (js2-unget-char))
5851 (if (js2-match-char ?<)
5852 (if (js2-match-char ?=)
5853 (js2-ts-return js2-ASSIGN_LSH)
5854 (js2-ts-return js2-LSH))
5855 (if (js2-match-char ?=)
5856 (js2-ts-return js2-LE)
5857 (throw 'return js2-LT))))
5858 (?>
5859 (if (js2-match-char ?>)
5860 (if (js2-match-char ?>)
5861 (if (js2-match-char ?=)
5862 (js2-ts-return js2-ASSIGN_URSH)
5863 (js2-ts-return js2-URSH))
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-ASSIGN_RSH)
5866 (js2-ts-return js2-RSH)))
5867 (if (js2-match-char ?=)
5868 (js2-ts-return js2-GE)
5869 (throw 'return js2-GT))))
5870 (?*
5871 (if (js2-match-char ?=)
5872 (js2-ts-return js2-ASSIGN_MUL)
5873 (throw 'return js2-MUL)))
5874 (?/
5875 ;; is it a // comment?
5876 (when (js2-match-char ?/)
5877 (setq js2-token-beg (- js2-ts-cursor 2))
5878 (js2-skip-line)
5879 (setq js2-ts-comment-type 'line)
5880 ;; include newline so highlighting goes to end of window
5881 (incf js2-token-end)
5882 (throw 'return js2-COMMENT))
5883 ;; is it a /* comment?
5884 (when (js2-match-char ?*)
5885 (setq look-for-slash nil
5886 js2-token-beg (- js2-ts-cursor 2)
5887 js2-ts-comment-type
5888 (if (js2-match-char ?*)
5889 (progn
5890 (setq look-for-slash t)
5891 'jsdoc)
5892 'block))
5893 (while t
5894 (setq c (js2-get-char))
5895 (cond
5896 ((eq c js2-EOF_CHAR)
5897 (setq js2-token-end (1- js2-ts-cursor))
5898 (js2-report-error "msg.unterminated.comment")
5899 (throw 'return js2-COMMENT))
5900 ((eq c ?*)
5901 (setq look-for-slash t))
5902 ((eq c ?/)
5903 (if look-for-slash
5904 (js2-ts-return js2-COMMENT)))
5905 (t
5906 (setq look-for-slash nil
5907 js2-token-end js2-ts-cursor)))))
5908 (if (js2-match-char ?=)
5909 (js2-ts-return js2-ASSIGN_DIV)
5910 (throw 'return js2-DIV)))
5911 (?#
5912 (when js2-skip-preprocessor-directives
5913 (js2-skip-line)
5914 (setq js2-ts-comment-type 'preprocessor
5915 js2-token-end js2-ts-cursor)
5916 (throw 'return js2-COMMENT))
5917 (throw 'return js2-ERROR))
5918 (?%
5919 (if (js2-match-char ?=)
5920 (js2-ts-return js2-ASSIGN_MOD)
5921 (throw 'return js2-MOD)))
5922 (?~
5923 (throw 'return js2-BITNOT))
5924 (?+
5925 (if (js2-match-char ?=)
5926 (js2-ts-return js2-ASSIGN_ADD)
5927 (if (js2-match-char ?+)
5928 (js2-ts-return js2-INC)
5929 (throw 'return js2-ADD))))
5930 (?-
5931 (cond
5932 ((js2-match-char ?=)
5933 (setq c js2-ASSIGN_SUB))
5934 ((js2-match-char ?-)
5935 (unless js2-ts-dirty-line
5936 ;; treat HTML end-comment after possible whitespace
5937 ;; after line start as comment-until-eol
5938 (when (js2-match-char ?>)
5939 (js2-skip-line)
5940 (setq js2-ts-comment-type 'html)
5941 (throw 'return js2-COMMENT)))
5942 (setq c js2-DEC))
5943 (t
5944 (setq c js2-SUB)))
5945 (setq js2-ts-dirty-line t)
5946 (js2-ts-return c))
5947 (otherwise
5948 (js2-report-scan-error "msg.illegal.character")))))))
5949
5950 (defun js2-read-regexp (start-token)
5951 "Called by parser when it gets / or /= in literal context."
5952 (let (c
5953 err
5954 in-class ; inside a '[' .. ']' character-class
5955 flags
5956 (continue t))
5957 (setq js2-token-beg js2-ts-cursor
5958 js2-ts-string-buffer nil
5959 js2-ts-regexp-flags nil)
5960 (if (eq start-token js2-ASSIGN_DIV)
5961 ;; mis-scanned /=
5962 (js2-add-to-string ?=)
5963 (if (not (eq start-token js2-DIV))
5964 (error "failed assertion")))
5965 (while (and (not err)
5966 (or (/= (setq c (js2-get-char)) ?/)
5967 in-class))
5968 (cond
5969 ((or (= c ?\n)
5970 (= c js2-EOF_CHAR))
5971 (setq js2-token-end (1- js2-ts-cursor)
5972 err t
5973 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5974 (js2-report-error "msg.unterminated.re.lit"))
5975 (t (cond
5976 ((= c ?\\)
5977 (js2-add-to-string c)
5978 (setq c (js2-get-char)))
5979 ((= c ?\[)
5980 (setq in-class t))
5981 ((= c ?\])
5982 (setq in-class nil)))
5983 (js2-add-to-string c))))
5984 (unless err
5985 (while continue
5986 (cond
5987 ((js2-match-char ?g)
5988 (push ?g flags))
5989 ((js2-match-char ?i)
5990 (push ?i flags))
5991 ((js2-match-char ?m)
5992 (push ?m flags))
5993 (t
5994 (setq continue nil))))
5995 (if (js2-alpha-p (js2-peek-char))
5996 (js2-report-scan-error "msg.invalid.re.flag" t
5997 js2-ts-cursor 1))
5998 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5999 js2-ts-regexp-flags (js2-collect-string flags)
6000 js2-token-end js2-ts-cursor)
6001 ;; tell `parse-partial-sexp' to ignore this range of chars
6002 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6003
6004 (defun js2-get-first-xml-token ()
6005 (setq js2-ts-xml-open-tags-count 0
6006 js2-ts-is-xml-attribute nil
6007 js2-ts-xml-is-tag-content nil)
6008 (js2-unget-char)
6009 (js2-get-next-xml-token))
6010
6011 (defsubst js2-xml-discard-string ()
6012 "Throw away the string in progress and flag an XML parse error."
6013 (setq js2-ts-string-buffer nil
6014 js2-ts-string nil)
6015 (js2-report-scan-error "msg.XML.bad.form" t))
6016
6017 (defun js2-get-next-xml-token ()
6018 (setq js2-ts-string-buffer nil ; for recording the XML
6019 js2-token-beg js2-ts-cursor)
6020 (let (c result)
6021 (setq result
6022 (catch 'return
6023 (while t
6024 (setq c (js2-get-char))
6025 (cond
6026 ((= c js2-EOF_CHAR)
6027 (throw 'return js2-ERROR))
6028 (js2-ts-xml-is-tag-content
6029 (case c
6030 (?>
6031 (js2-add-to-string c)
6032 (setq js2-ts-xml-is-tag-content nil
6033 js2-ts-is-xml-attribute nil))
6034 (?/
6035 (js2-add-to-string c)
6036 (when (eq ?> (js2-peek-char))
6037 (setq c (js2-get-char))
6038 (js2-add-to-string c)
6039 (setq js2-ts-xml-is-tag-content nil)
6040 (decf js2-ts-xml-open-tags-count)))
6041 (?{
6042 (js2-unget-char)
6043 (setq js2-ts-string (js2-get-string-from-buffer))
6044 (throw 'return js2-XML))
6045 ((?\' ?\")
6046 (js2-add-to-string c)
6047 (unless (js2-read-quoted-string c)
6048 (throw 'return js2-ERROR)))
6049 (?=
6050 (js2-add-to-string c)
6051 (setq js2-ts-is-xml-attribute t))
6052 ((? ?\t ?\r ?\n)
6053 (js2-add-to-string c))
6054 (t
6055 (js2-add-to-string c)
6056 (setq js2-ts-is-xml-attribute nil)))
6057 (when (and (not js2-ts-xml-is-tag-content)
6058 (zerop js2-ts-xml-open-tags-count))
6059 (setq js2-ts-string (js2-get-string-from-buffer))
6060 (throw 'return js2-XMLEND)))
6061 (t
6062 ;; else not tag content
6063 (case c
6064 (?<
6065 (js2-add-to-string c)
6066 (setq c (js2-peek-char))
6067 (case c
6068 (?!
6069 (setq c (js2-get-char)) ;; skip !
6070 (js2-add-to-string c)
6071 (setq c (js2-peek-char))
6072 (case c
6073 (?-
6074 (setq c (js2-get-char)) ;; skip -
6075 (js2-add-to-string c)
6076 (if (eq c ?-)
6077 (progn
6078 (js2-add-to-string c)
6079 (unless (js2-read-xml-comment)
6080 (throw 'return js2-ERROR)))
6081 (js2-xml-discard-string)
6082 (throw 'return js2-ERROR)))
6083 (?\[
6084 (setq c (js2-get-char)) ;; skip [
6085 (js2-add-to-string c)
6086 (if (and (= (js2-get-char) ?C)
6087 (= (js2-get-char) ?D)
6088 (= (js2-get-char) ?A)
6089 (= (js2-get-char) ?T)
6090 (= (js2-get-char) ?A)
6091 (= (js2-get-char) ?\[))
6092 (progn
6093 (js2-add-to-string ?C)
6094 (js2-add-to-string ?D)
6095 (js2-add-to-string ?A)
6096 (js2-add-to-string ?T)
6097 (js2-add-to-string ?A)
6098 (js2-add-to-string ?\[)
6099 (unless (js2-read-cdata)
6100 (throw 'return js2-ERROR)))
6101 (js2-xml-discard-string)
6102 (throw 'return js2-ERROR)))
6103 (t
6104 (unless (js2-read-entity)
6105 (throw 'return js2-ERROR)))))
6106 (??
6107 (setq c (js2-get-char)) ;; skip ?
6108 (js2-add-to-string c)
6109 (unless (js2-read-PI)
6110 (throw 'return js2-ERROR)))
6111 (?/
6112 ;; end tag
6113 (setq c (js2-get-char)) ;; skip /
6114 (js2-add-to-string c)
6115 (when (zerop js2-ts-xml-open-tags-count)
6116 (js2-xml-discard-string)
6117 (throw 'return js2-ERROR))
6118 (setq js2-ts-xml-is-tag-content t)
6119 (decf js2-ts-xml-open-tags-count))
6120 (t
6121 ;; start tag
6122 (setq js2-ts-xml-is-tag-content t)
6123 (incf js2-ts-xml-open-tags-count))))
6124 (?{
6125 (js2-unget-char)
6126 (setq js2-ts-string (js2-get-string-from-buffer))
6127 (throw 'return js2-XML))
6128 (t
6129 (js2-add-to-string c))))))))
6130 (setq js2-token-end js2-ts-cursor)
6131 result))
6132
6133 (defun js2-read-quoted-string (quote)
6134 (let (c)
6135 (catch 'return
6136 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6137 (js2-add-to-string c)
6138 (if (eq c quote)
6139 (throw 'return t)))
6140 (js2-xml-discard-string) ;; throw away string in progress
6141 nil)))
6142
6143 (defun js2-read-xml-comment ()
6144 (let ((c (js2-get-char)))
6145 (catch 'return
6146 (while (/= c js2-EOF_CHAR)
6147 (catch 'continue
6148 (js2-add-to-string c)
6149 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6150 (setq c (js2-get-char))
6151 (js2-add-to-string c)
6152 (if (eq (js2-peek-char) ?>)
6153 (progn
6154 (setq c (js2-get-char)) ;; skip >
6155 (js2-add-to-string c)
6156 (throw 'return t))
6157 (throw 'continue nil)))
6158 (setq c (js2-get-char))))
6159 (js2-xml-discard-string)
6160 nil)))
6161
6162 (defun js2-read-cdata ()
6163 (let ((c (js2-get-char)))
6164 (catch 'return
6165 (while (/= c js2-EOF_CHAR)
6166 (catch 'continue
6167 (js2-add-to-string c)
6168 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6169 (setq c (js2-get-char))
6170 (js2-add-to-string c)
6171 (if (eq (js2-peek-char) ?>)
6172 (progn
6173 (setq c (js2-get-char)) ;; Skip >
6174 (js2-add-to-string c)
6175 (throw 'return t))
6176 (throw 'continue nil)))
6177 (setq c (js2-get-char))))
6178 (js2-xml-discard-string)
6179 nil)))
6180
6181 (defun js2-read-entity ()
6182 (let ((decl-tags 1)
6183 c)
6184 (catch 'return
6185 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6186 (js2-add-to-string c)
6187 (case c
6188 (?<
6189 (incf decl-tags))
6190 (?>
6191 (decf decl-tags)
6192 (if (zerop decl-tags)
6193 (throw 'return t)))))
6194 (js2-xml-discard-string)
6195 nil)))
6196
6197 (defun js2-read-PI ()
6198 "Scan an XML processing instruction."
6199 (let (c)
6200 (catch 'return
6201 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6202 (js2-add-to-string c)
6203 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6204 (setq c (js2-get-char)) ;; Skip >
6205 (js2-add-to-string c)
6206 (throw 'return t)))
6207 (js2-xml-discard-string)
6208 nil)))
6209
6210 (defun js2-scanner-get-line ()
6211 "Return the text of the current scan line."
6212 (buffer-substring (point-at-bol) (point-at-eol)))
6213
6214 ;;; Highlighting
6215
6216 (defsubst js2-set-face (beg end face &optional record)
6217 "Fontify a region. If RECORD is non-nil, record for later."
6218 (when (plusp js2-highlight-level)
6219 (setq beg (min (point-max) beg)
6220 beg (max (point-min) beg)
6221 end (min (point-max) end)
6222 end (max (point-min) end))
6223 (if record
6224 (push (list beg end face) js2-mode-fontifications)
6225 (put-text-property beg end 'face face))))
6226
6227 (defsubst js2-set-kid-face (pos kid len face)
6228 "Set-face on a child node.
6229 POS is absolute buffer position of parent.
6230 KID is the child node.
6231 LEN is the length to fontify.
6232 FACE is the face to fontify with."
6233 (js2-set-face (+ pos (js2-node-pos kid))
6234 (+ pos (js2-node-pos kid) (js2-node-len kid))
6235 face))
6236
6237 (defsubst js2-fontify-kwd (start length)
6238 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6239
6240 (defsubst js2-clear-face (beg end)
6241 (remove-text-properties beg end '(face nil
6242 help-echo nil
6243 point-entered nil
6244 c-in-sws nil)))
6245
6246 (defconst js2-ecma-global-props
6247 (concat "^"
6248 (regexp-opt
6249 '("Infinity" "NaN" "undefined" "arguments") t)
6250 "$")
6251 "Value properties of the Ecma-262 Global Object.
6252 Shown at or above `js2-highlight-level' 2.")
6253
6254 ;; might want to add the name "arguments" to this list?
6255 (defconst js2-ecma-object-props
6256 (concat "^"
6257 (regexp-opt
6258 '("prototype" "__proto__" "__parent__") t)
6259 "$")
6260 "Value properties of the Ecma-262 Object constructor.
6261 Shown at or above `js2-highlight-level' 2.")
6262
6263 (defconst js2-ecma-global-funcs
6264 (concat
6265 "^"
6266 (regexp-opt
6267 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6268 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6269 "$")
6270 "Function properties of the Ecma-262 Global object.
6271 Shown at or above `js2-highlight-level' 2.")
6272
6273 (defconst js2-ecma-number-props
6274 (concat "^"
6275 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6276 "NEGATIVE_INFINITY"
6277 "POSITIVE_INFINITY") t)
6278 "$")
6279 "Properties of the Ecma-262 Number constructor.
6280 Shown at or above `js2-highlight-level' 2.")
6281
6282 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6283 "Properties of the Ecma-262 Date constructor.
6284 Shown at or above `js2-highlight-level' 2.")
6285
6286 (defconst js2-ecma-math-props
6287 (concat "^"
6288 (regexp-opt
6289 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6290 t)
6291 "$")
6292 "Properties of the Ecma-262 Math object.
6293 Shown at or above `js2-highlight-level' 2.")
6294
6295 (defconst js2-ecma-math-funcs
6296 (concat "^"
6297 (regexp-opt
6298 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6299 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6300 "$")
6301 "Function properties of the Ecma-262 Math object.
6302 Shown at or above `js2-highlight-level' 2.")
6303
6304 (defconst js2-ecma-function-props
6305 (concat
6306 "^"
6307 (regexp-opt
6308 '(;; properties of the Object prototype object
6309 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6310 "toLocaleString" "toString" "valueOf"
6311 ;; properties of the Function prototype object
6312 "apply" "call"
6313 ;; properties of the Array prototype object
6314 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6315 "splice" "unshift"
6316 ;; properties of the String prototype object
6317 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6318 "localeCompare" "match" "replace" "search" "split" "substring"
6319 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6320 "toUpperCase"
6321 ;; properties of the Number prototype object
6322 "toExponential" "toFixed" "toPrecision"
6323 ;; properties of the Date prototype object
6324 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6325 "getMinutes" "getMonth" "getSeconds" "getTime"
6326 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6327 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6328 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6329 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6330 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6331 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6332 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6333 "toTimeString" "toUTCString"
6334 ;; properties of the RegExp prototype object
6335 "exec" "test"
6336 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6337 "toSource" "__defineGetter__" "__defineSetter__"
6338 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6339 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6340 t)
6341 "$")
6342 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6343 Shown at or above `js2-highlight-level' 3.")
6344
6345 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6346 (let ((target-name (and target
6347 (js2-name-node-p target)
6348 (js2-name-node-name target)))
6349 (prop-name (if prop (js2-name-node-name prop)))
6350 (level1 (>= js2-highlight-level 1))
6351 (level2 (>= js2-highlight-level 2))
6352 (level3 (>= js2-highlight-level 3))
6353 pos
6354 face)
6355 (when level2
6356 (if call-p
6357 (cond
6358 ((and target prop)
6359 (cond
6360 ((and level3 (string-match js2-ecma-function-props prop-name))
6361 (setq face 'font-lock-builtin-face))
6362 ((and target-name prop)
6363 (cond
6364 ((string= target-name "Date")
6365 (if (string-match js2-ecma-date-props prop-name)
6366 (setq face 'font-lock-builtin-face)))
6367 ((string= target-name "Math")
6368 (if (string-match js2-ecma-math-funcs prop-name)
6369 (setq face 'font-lock-builtin-face)))))))
6370 (prop
6371 (if (string-match js2-ecma-global-funcs prop-name)
6372 (setq face 'font-lock-builtin-face))))
6373 (cond
6374 ((and target prop)
6375 (cond
6376 ((string= target-name "Number")
6377 (if (string-match js2-ecma-number-props prop-name)
6378 (setq face 'font-lock-constant-face)))
6379 ((string= target-name "Math")
6380 (if (string-match js2-ecma-math-props prop-name)
6381 (setq face 'font-lock-constant-face)))))
6382 (prop
6383 (if (string-match js2-ecma-object-props prop-name)
6384 (setq face 'font-lock-constant-face)))))
6385 (when face
6386 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6387 (js2-node-pos prop))) ; relative
6388 (+ pos (js2-node-len prop))
6389 face)))))
6390
6391 (defun js2-parse-highlight-member-expr-node (node)
6392 "Perform syntax highlighting of EcmaScript built-in properties.
6393 The variable `js2-highlight-level' governs this highighting."
6394 (let (face target prop name pos end parent call-p callee)
6395 (cond
6396 ;; case 1: simple name, e.g. foo
6397 ((js2-name-node-p node)
6398 (setq name (js2-name-node-name node))
6399 ;; possible for name to be nil in rare cases - saw it when
6400 ;; running js2-mode on an elisp buffer. Might as well try to
6401 ;; make it so js2-mode never barfs.
6402 (when name
6403 (setq face (if (string-match js2-ecma-global-props name)
6404 'font-lock-constant-face))
6405 (when face
6406 (setq pos (js2-node-pos node)
6407 end (+ pos (js2-node-len node)))
6408 (js2-set-face pos end face))))
6409 ;; case 2: property access or function call
6410 ((or (js2-prop-get-node-p node)
6411 ;; highlight function call if expr is a prop-get node
6412 ;; or a plain name (i.e. unqualified function call)
6413 (and (setq call-p (js2-call-node-p node))
6414 (setq callee (js2-call-node-target node)) ; separate setq!
6415 (or (js2-prop-get-node-p callee)
6416 (js2-name-node-p callee))))
6417 (setq parent node
6418 node (if call-p callee node))
6419 (if (and call-p (js2-name-node-p callee))
6420 (setq prop callee)
6421 (setq target (js2-prop-get-node-left node)
6422 prop (js2-prop-get-node-right node)))
6423 (cond
6424 ((js2-name-node-p target)
6425 (if (js2-name-node-p prop)
6426 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6427 (js2-parse-highlight-prop-get parent target prop call-p)
6428 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6429 (js2-parse-highlight-prop-get parent target nil call-p)))
6430 ((js2-name-node-p prop)
6431 ;; case 2c: complex target, simple name, e.g. x[y].bar
6432 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6433
6434 (defun js2-parse-highlight-member-expr-fn-name (expr)
6435 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6436 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6437 We currently only handle the case where the last component is a prop-get
6438 of a simple name. Called before EXPR has a parent node."
6439 (let (pos
6440 (name (and (js2-prop-get-node-p expr)
6441 (js2-prop-get-node-right expr))))
6442 (when (js2-name-node-p name)
6443 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6444 (js2-node-pos name)))
6445 (+ pos (js2-node-len name))
6446 'font-lock-function-name-face
6447 'record))))
6448
6449 ;; source: http://jsdoc.sourceforge.net/
6450 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6451 ;; allows type specifications, and needs work before entering the wild.
6452
6453 (defconst js2-jsdoc-param-tag-regexp
6454 (concat "^\\s-*\\*+\\s-*\\(@"
6455 "\\(?:param\\|argument\\)"
6456 "\\)"
6457 "\\s-*\\({[^}]+}\\)?" ; optional type
6458 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6459 "\\>")
6460 "Matches jsdoc tags with optional type and optional param name.")
6461
6462 (defconst js2-jsdoc-typed-tag-regexp
6463 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6464 (regexp-opt
6465 '("enum"
6466 "extends"
6467 "field"
6468 "id"
6469 "implements"
6470 "lends"
6471 "mods"
6472 "requires"
6473 "return"
6474 "returns"
6475 "throw"
6476 "throws"))
6477 "\\)\\)\\s-*\\({[^}]+}\\)?")
6478 "Matches jsdoc tags with optional type.")
6479
6480 (defconst js2-jsdoc-arg-tag-regexp
6481 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6482 (regexp-opt
6483 '("alias"
6484 "augments"
6485 "borrows"
6486 "bug"
6487 "base"
6488 "config"
6489 "default"
6490 "define"
6491 "exception"
6492 "function"
6493 "member"
6494 "memberOf"
6495 "name"
6496 "namespace"
6497 "property"
6498 "since"
6499 "suppress"
6500 "this"
6501 "throws"
6502 "type"
6503 "version"))
6504 "\\)\\)\\s-+\\([^ \t]+\\)")
6505 "Matches jsdoc tags with a single argument.")
6506
6507 (defconst js2-jsdoc-empty-tag-regexp
6508 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6509 (regexp-opt
6510 '("addon"
6511 "author"
6512 "class"
6513 "const"
6514 "constant"
6515 "constructor"
6516 "constructs"
6517 "deprecated"
6518 "desc"
6519 "description"
6520 "event"
6521 "example"
6522 "exec"
6523 "export"
6524 "fileoverview"
6525 "final"
6526 "function"
6527 "hidden"
6528 "ignore"
6529 "implicitCast"
6530 "inheritDoc"
6531 "inner"
6532 "interface"
6533 "license"
6534 "noalias"
6535 "noshadow"
6536 "notypecheck"
6537 "override"
6538 "owner"
6539 "preserve"
6540 "preserveTry"
6541 "private"
6542 "protected"
6543 "public"
6544 "static"
6545 "supported"
6546 ))
6547 "\\)\\)\\s-*")
6548 "Matches empty jsdoc tags.")
6549
6550 (defconst js2-jsdoc-link-tag-regexp
6551 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6552 "Matches a jsdoc link or code tag.")
6553
6554 (defconst js2-jsdoc-see-tag-regexp
6555 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6556 "Matches a jsdoc @see tag.")
6557
6558 (defconst js2-jsdoc-html-tag-regexp
6559 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6560 "Matches a simple (no attributes) html start- or end-tag.")
6561
6562 (defsubst js2-jsdoc-highlight-helper ()
6563 (js2-set-face (match-beginning 1)
6564 (match-end 1)
6565 'js2-jsdoc-tag-face)
6566 (if (match-beginning 2)
6567 (if (save-excursion
6568 (goto-char (match-beginning 2))
6569 (= (char-after) ?{))
6570 (js2-set-face (1+ (match-beginning 2))
6571 (1- (match-end 2))
6572 'js2-jsdoc-type-face)
6573 (js2-set-face (match-beginning 2)
6574 (match-end 2)
6575 'js2-jsdoc-value-face)))
6576 (if (match-beginning 3)
6577 (js2-set-face (match-beginning 3)
6578 (match-end 3)
6579 'js2-jsdoc-value-face)))
6580
6581 (defun js2-highlight-jsdoc (ast)
6582 "Highlight doc comment tags."
6583 (let ((comments (js2-ast-root-comments ast))
6584 beg end)
6585 (save-excursion
6586 (dolist (node comments)
6587 (when (eq (js2-comment-node-format node) 'jsdoc)
6588 (setq beg (js2-node-abs-pos node)
6589 end (+ beg (js2-node-len node)))
6590 (save-restriction
6591 (narrow-to-region beg end)
6592 (dolist (re (list js2-jsdoc-param-tag-regexp
6593 js2-jsdoc-typed-tag-regexp
6594 js2-jsdoc-arg-tag-regexp
6595 js2-jsdoc-link-tag-regexp
6596 js2-jsdoc-see-tag-regexp
6597 js2-jsdoc-empty-tag-regexp))
6598 (goto-char beg)
6599 (while (re-search-forward re nil t)
6600 (js2-jsdoc-highlight-helper)))
6601 ;; simple highlighting for html tags
6602 (goto-char beg)
6603 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6604 (js2-set-face (match-beginning 1)
6605 (match-end 1)
6606 'js2-jsdoc-html-tag-delimiter-face)
6607 (js2-set-face (match-beginning 2)
6608 (match-end 2)
6609 'js2-jsdoc-html-tag-name-face)
6610 (js2-set-face (match-beginning 3)
6611 (match-end 3)
6612 'js2-jsdoc-html-tag-delimiter-face))))))))
6613
6614 (defun js2-highlight-assign-targets (node left right)
6615 "Highlight function properties and external variables."
6616 (let (leftpos end name)
6617 ;; highlight vars and props assigned function values
6618 (when (js2-function-node-p right)
6619 (cond
6620 ;; var foo = function() {...}
6621 ((js2-name-node-p left)
6622 (setq name left))
6623 ;; foo.bar.baz = function() {...}
6624 ((and (js2-prop-get-node-p left)
6625 (js2-name-node-p (js2-prop-get-node-right left)))
6626 (setq name (js2-prop-get-node-right left))))
6627 (when name
6628 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6629 (+ leftpos (js2-node-len name))
6630 'font-lock-function-name-face
6631 'record)))))
6632
6633 (defun js2-record-name-node (node)
6634 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6635 later. NODE must be a name node."
6636 (let (leftpos end)
6637 (push (list node js2-current-scope
6638 (setq leftpos (js2-node-abs-pos node))
6639 (setq end (+ leftpos (js2-node-len node))))
6640 js2-recorded-identifiers)))
6641
6642 (defun js2-highlight-undeclared-vars ()
6643 "After entire parse is finished, look for undeclared variable references.
6644 We have to wait until entire buffer is parsed, since JavaScript permits var
6645 decls to occur after they're used.
6646
6647 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6648 it is considered declared."
6649 (let (name)
6650 (dolist (entry js2-recorded-identifiers)
6651 (destructuring-bind (name-node scope pos end) entry
6652 (setq name (js2-name-node-name name-node))
6653 (unless (or (member name js2-global-externs)
6654 (member name js2-default-externs)
6655 (member name js2-additional-externs)
6656 (js2-get-defining-scope scope name))
6657 (js2-set-face pos end 'js2-external-variable-face 'record)
6658 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6659 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6660 (setq js2-recorded-identifiers nil)))
6661
6662 ;;; IMenu support
6663
6664 ;; We currently only support imenu, but eventually should support speedbar and
6665 ;; possibly other browsing mechanisms.
6666
6667 ;; The basic strategy is to identify function assignment targets of the form
6668 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6669 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6670 ;; for imenu after parsing is finished.
6671
6672 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6673 ;; JavaScript, and the general problem is undecidable. However, several forms
6674 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6675 ;; include:
6676
6677 ;; function foo() -- function declaration
6678 ;; foo = function() -- function expression assigned to variable
6679 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6680 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6681 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6682 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6683 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6684 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6685 ;; function foo() {function bar() {...}} -- nested function
6686 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6687
6688 ;; This list boils down to a few forms that can be combined recursively.
6689 ;; Top-level named function declarations include both the left-hand (name)
6690 ;; and the right-hand (function value) expressions needed to produce an imenu
6691 ;; entry. The other "right-hand" forms we need to look for are:
6692 ;; - functions declared as props/getters/setters in object literals
6693 ;; - nested named function declarations
6694 ;; The "left-hand" expressions that functions can be assigned to include:
6695 ;; - local/global variables
6696 ;; - nested property-get expressions like a.b.c.d
6697 ;; - element gets like foo[10] or foo['bar'] where the index
6698 ;; expression can be trivially converted to a property name. They
6699 ;; effectively then become property gets.
6700
6701 ;; All the different definition types are canonicalized into the form
6702 ;; foo.bar.baz = position-of-function-keyword
6703
6704 ;; We need to build a trie-like structure for imenu. As an example,
6705 ;; consider the following JavaScript code:
6706
6707 ;; a = function() {...} // function at position 5
6708 ;; b = function() {...} // function at position 25
6709 ;; foo = function() {...} // function at position 100
6710 ;; foo.bar = function() {...} // function at position 200
6711 ;; foo.bar.baz = function() {...} // function at position 300
6712 ;; foo.bar.zab = function() {...} // function at position 400
6713
6714 ;; During parsing we accumulate an entry for each definition in
6715 ;; the variable `js2-imenu-recorder', like so:
6716
6717 ;; '((a 5)
6718 ;; (b 25)
6719 ;; (foo 100)
6720 ;; (foo bar 200)
6721 ;; (foo bar baz 300)
6722 ;; (foo bar zab 400))
6723
6724 ;; After parsing these entries are merged into this alist-trie:
6725
6726 ;; '((a . 1)
6727 ;; (b . 2)
6728 ;; (foo (<definition> . 3)
6729 ;; (bar (<definition> . 6)
6730 ;; (baz . 100)
6731 ;; (zab . 200))))
6732
6733 ;; Note the wacky need for a <definition> name. The token can be anything
6734 ;; that isn't a valid JavaScript identifier, because you might make foo
6735 ;; a function and then start setting properties on it that are also functions.
6736
6737 (defsubst js2-prop-node-name (node)
6738 "Return the name of a node that may be a property-get/property-name.
6739 If NODE is not a valid name-node, string-node or integral number-node,
6740 returns nil. Otherwise returns the string name/value of the node."
6741 (cond
6742 ((js2-name-node-p node)
6743 (js2-name-node-name node))
6744 ((js2-string-node-p node)
6745 (js2-string-node-value node))
6746 ((and (js2-number-node-p node)
6747 (string-match "^[0-9]+$" (js2-number-node-value node)))
6748 (js2-number-node-value node))
6749 ((js2-this-node-p node)
6750 "this")))
6751
6752 (defsubst js2-node-qname-component (node)
6753 "Test function: return the name of this node, if it contributes to a qname.
6754 Returns nil if the node doesn't contribute."
6755 (copy-sequence
6756 (or (js2-prop-node-name node)
6757 (if (and (js2-function-node-p node)
6758 (js2-function-node-name node))
6759 (js2-name-node-name (js2-function-node-name node))))))
6760
6761 (defsubst js2-record-function-qname (fn-node qname)
6762 "Associate FN-NODE with its QNAME for later lookup.
6763 This is used in postprocessing the chain list. When we find a chain
6764 whose first element is a js2-THIS keyword node, we look up the parent
6765 function and see (using this map) whether it is the tail of a chain.
6766 If so, we replace the this-node with a copy of the parent's qname."
6767 (unless js2-imenu-function-map
6768 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6769 (puthash fn-node qname js2-imenu-function-map))
6770
6771 (defun js2-record-imenu-functions (node &optional var)
6772 "Record function definitions for imenu.
6773 NODE is a function node or an object literal.
6774 VAR, if non-nil, is the expression that NODE is being assigned to."
6775 (when js2-parse-ide-mode
6776 (let ((fun-p (js2-function-node-p node))
6777 qname left fname-node pos)
6778 (cond
6779 ;; non-anonymous function declaration?
6780 ((and fun-p
6781 (not var)
6782 (setq fname-node (js2-function-node-name node)))
6783 (push (setq qname (list fname-node (js2-node-pos node)))
6784 js2-imenu-recorder)
6785 (js2-record-function-qname node qname))
6786 ;; for remaining forms, compute left-side tree branch first
6787 ((and var (setq qname (js2-compute-nested-prop-get var)))
6788 (cond
6789 ;; foo.bar.baz = function
6790 (fun-p
6791 (push (nconc qname (list (js2-node-pos node)))
6792 js2-imenu-recorder)
6793 (js2-record-function-qname node qname))
6794 ;; foo.bar.baz = object-literal
6795 ;; look for nested functions: {a: {b: function() {...} }}
6796 ((js2-object-node-p node)
6797 ;; Node position here is still absolute, since the parser
6798 ;; passes the assignment target and value expressions
6799 ;; to us before they are added as children of the assignment node.
6800 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6801
6802 (defun js2-compute-nested-prop-get (node)
6803 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6804 component nodes as a list. Otherwise return nil. Element-gets are treated
6805 as property-gets if the index expression is a string, or a positive integer."
6806 (let (left right head)
6807 (cond
6808 ((or (js2-name-node-p node)
6809 (js2-this-node-p node))
6810 (list node))
6811 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6812 ((js2-prop-get-node-p node) ; foo.bar
6813 (setq left (js2-prop-get-node-left node)
6814 right (js2-prop-get-node-right node))
6815 (if (setq head (js2-compute-nested-prop-get left))
6816 (nconc head (list right))))
6817 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6818 (setq left (js2-elem-get-node-target node)
6819 right (js2-elem-get-node-element node))
6820 (if (or (js2-string-node-p right) ; ['bar']
6821 (and (js2-number-node-p right) ; [10]
6822 (string-match "^[0-9]+$"
6823 (js2-number-node-value right))))
6824 (if (setq head (js2-compute-nested-prop-get left))
6825 (nconc head (list right))))))))
6826
6827 (defun js2-record-object-literal (node qname pos)
6828 "Recursively process an object literal looking for functions.
6829 NODE is an object literal that is the right-hand child of an assignment
6830 expression. QNAME is a list of nodes representing the assignment target,
6831 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6832 POS is the absolute position of the node.
6833 We do a depth-first traversal of NODE. Any functions we find are prefixed
6834 with QNAME plus the property name of the function and appended to the
6835 variable `js2-imenu-recorder'."
6836 (let (left right)
6837 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6838 (let ((left (js2-infix-node-left e))
6839 ;; Element positions are relative to the parent position.
6840 (pos (+ pos (js2-node-pos e))))
6841 (cond
6842 ;; foo: function() {...}
6843 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6844 (when (js2-prop-node-name left)
6845 ;; As a policy decision, we record the position of the property,
6846 ;; not the position of the `function' keyword, since the property
6847 ;; is effectively the name of the function.
6848 (push (append qname (list left pos))
6849 js2-imenu-recorder)
6850 (js2-record-function-qname right qname)))
6851 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6852 ((js2-object-node-p right)
6853 (js2-record-object-literal right
6854 (append qname (list (js2-infix-node-left e)))
6855 (+ pos (js2-node-pos right)))))))))
6856
6857 (defsubst js2-node-top-level-decl-p (node)
6858 "Return t if NODE's name is defined in the top-level scope.
6859 Also returns t if NODE's name is not defined in any scope, since it implies
6860 that it's an external variable, which must also be in the top-level scope."
6861 (let* ((name (js2-prop-node-name node))
6862 (this-scope (js2-node-get-enclosing-scope node))
6863 defining-scope)
6864 (cond
6865 ((js2-this-node-p node)
6866 nil)
6867 ((null this-scope)
6868 t)
6869 ((setq defining-scope (js2-get-defining-scope this-scope name))
6870 (js2-ast-root-p defining-scope))
6871 (t t))))
6872
6873 (defsubst js2-anonymous-wrapper-fn-p (node)
6874 "Returns t if NODE is an anonymous function that's invoked immediately.
6875 NODE must be `js2-function-node'."
6876 (let ((parent (js2-node-parent node)))
6877 (and (js2-paren-node-p parent)
6878 ;; (function(){...})();
6879 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6880 ;; (function(){...}).call(this);
6881 (and (js2-prop-get-node-p parent)
6882 (member (js2-name-node-name (js2-prop-get-node-right parent))
6883 '("call" "apply"))
6884 (js2-call-node-p (js2-node-parent parent)))))))
6885
6886 (defun js2-browse-postprocess-chains (chains)
6887 "Modify function-declaration name chains after parsing finishes.
6888 Some of the information is only available after the parse tree is complete.
6889 For instance, following a 'this' reference requires a parent function node."
6890 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6891 result head fn fn-type parent-chain p elem parent)
6892 (dolist (chain chains)
6893 ;; examine the head of each node to get its defining scope
6894 (setq head (car chain))
6895 ;; if top-level/external, keep as-is
6896 (if (js2-node-top-level-decl-p head)
6897 (push chain result)
6898 (cond
6899 ;; starts with this-reference
6900 ((js2-this-node-p head)
6901 (setq fn (js2-node-parent-script-or-fn head)
6902 chain (cdr chain))) ; discard this-node
6903 ;; nested named function
6904 ((js2-function-node-p (setq parent (js2-node-parent head)))
6905 (setq fn (js2-node-parent-script-or-fn parent)))
6906 ;; variable assigned a function expression
6907 (t (setq fn (js2-node-parent-script-or-fn head))))
6908 (when fn
6909 (setq fn-type (gethash fn js2-imenu-fn-type-map))
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-label-set nil)
7313 (js2-init-scanner)
7314 (setq ast (js2-with-unmodifying-text-property-changes
7315 (js2-do-parse)))
7316 (unless js2-ts-hit-eof
7317 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7318 (setf (js2-ast-root-errors ast) js2-parsed-errors
7319 (js2-ast-root-warnings ast) js2-parsed-warnings)
7320 ;; if we didn't find any declarations, put a dummy in this list so we
7321 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7322 (unless js2-imenu-recorder
7323 (setq js2-imenu-recorder 'empty))
7324 (run-hooks 'js2-parse-finished-hook)
7325 ast)))
7326
7327 ;; Corresponds to Rhino's Parser.parse() method.
7328 (defun js2-do-parse ()
7329 "Parse current buffer starting from current point.
7330 Scanner should be initialized."
7331 (let ((pos js2-ts-cursor)
7332 (end js2-ts-cursor) ; in case file is empty
7333 root n tt)
7334 ;; initialize buffer-local parsing vars
7335 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7336 js2-current-script-or-fn root
7337 js2-current-scope root
7338 js2-current-flagged-token js2-EOF
7339 js2-nesting-of-function 0
7340 js2-labeled-stmt nil
7341 js2-recorded-identifiers nil) ; for js2-highlight
7342 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7343 (if (= tt js2-FUNCTION)
7344 (progn
7345 (js2-consume-token)
7346 (setq n (js2-parse-function (if js2-called-by-compile-function
7347 'FUNCTION_EXPRESSION
7348 'FUNCTION_STATEMENT))))
7349 ;; not a function - parse a statement
7350 (setq n (js2-parse-statement)))
7351 ;; add function or statement to script
7352 (setq end (js2-node-end n))
7353 (js2-block-node-push root n))
7354 ;; add comments to root in lexical order
7355 (when js2-scanned-comments
7356 ;; if we find a comment beyond end of normal kids, use its end
7357 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7358 (dolist (comment js2-scanned-comments)
7359 (push comment (js2-ast-root-comments root))
7360 (js2-node-add-children root comment)))
7361 (setf (js2-node-len root) (- end pos))
7362 ;; Give extensions a chance to muck with things before highlighting starts.
7363 (dolist (callback js2-post-parse-callbacks)
7364 (funcall callback))
7365 (js2-highlight-undeclared-vars)
7366 root))
7367
7368 (defun js2-function-parser ()
7369 (js2-consume-token)
7370 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7371
7372 (defun js2-parse-function-closure-body (fn-node)
7373 "Parse a JavaScript 1.8 function closure body."
7374 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7375 (if js2-ts-hit-eof
7376 (js2-report-error "msg.no.brace.body" nil
7377 (js2-node-pos fn-node)
7378 (- js2-ts-cursor (js2-node-pos fn-node)))
7379 (js2-node-add-children fn-node
7380 (setf (js2-function-node-body fn-node)
7381 (js2-parse-expr t))))))
7382
7383 (defun js2-parse-function-body (fn-node)
7384 (js2-must-match js2-LC "msg.no.brace.body"
7385 (js2-node-pos fn-node)
7386 (- js2-ts-cursor (js2-node-pos fn-node)))
7387 (let ((pos js2-token-beg) ; LC position
7388 (pn (make-js2-block-node)) ; starts at LC position
7389 tt
7390 end)
7391 (incf js2-nesting-of-function)
7392 (unwind-protect
7393 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7394 (= tt js2-EOF)
7395 (= tt js2-RC)))
7396 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7397 (js2-parse-statement)
7398 (js2-consume-token)
7399 (js2-parse-function 'FUNCTION_STATEMENT))))
7400 (decf js2-nesting-of-function))
7401 (setq end js2-token-end) ; assume no curly and leave at current token
7402 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7403 (setq end js2-token-end))
7404 (setf (js2-node-pos pn) pos
7405 (js2-node-len pn) (- end pos))
7406 (setf (js2-function-node-body fn-node) pn)
7407 (js2-node-add-children fn-node pn)
7408 pn))
7409
7410 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7411 "Declare and fontify destructuring parameters inside NODE.
7412 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7413 (cond
7414 ((js2-name-node-p node)
7415 (let (leftpos)
7416 (js2-define-symbol decl-type (js2-name-node-name node)
7417 node ignore-not-in-block)
7418 (when face
7419 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7420 (+ leftpos (js2-node-len node))
7421 face 'record))))
7422 ((js2-object-node-p node)
7423 (dolist (elem (js2-object-node-elems node))
7424 (js2-define-destruct-symbols
7425 (if (js2-object-prop-node-p elem)
7426 (js2-object-prop-node-right elem)
7427 ;; abbreviated destructuring {a, b}
7428 elem)
7429 decl-type face ignore-not-in-block)))
7430 ((js2-array-node-p node)
7431 (dolist (elem (js2-array-node-elems node))
7432 (when elem
7433 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7434 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7435 (js2-node-len node)))))
7436
7437 (defun js2-parse-function-params (fn-node pos)
7438 (if (js2-match-token js2-RP)
7439 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7440 (let (params len param)
7441 (loop for tt = (js2-peek-token)
7442 do
7443 (cond
7444 ;; destructuring param
7445 ((or (= tt js2-LB) (= tt js2-LC))
7446 (setq param (js2-parse-primary-expr-lhs))
7447 (js2-define-destruct-symbols param
7448 js2-LP
7449 'js2-function-param-face)
7450 (push param params))
7451 ;; simple name
7452 (t
7453 (js2-must-match js2-NAME "msg.no.parm")
7454 (js2-record-face 'js2-function-param-face)
7455 (setq param (js2-create-name-node))
7456 (js2-define-symbol js2-LP js2-ts-string param)
7457 (push param params)))
7458 while
7459 (js2-match-token js2-COMMA))
7460 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7461 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7462 (dolist (p params)
7463 (js2-node-add-children fn-node p)
7464 (push p (js2-function-node-params fn-node))))))
7465
7466 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7467 "Possibly show inconsistent-return warning.
7468 Last token scanned is the close-curly for the function body."
7469 (when (and js2-mode-show-strict-warnings
7470 js2-strict-inconsistent-return-warning
7471 (not (js2-has-consistent-return-usage
7472 (js2-function-node-body fn-node))))
7473 ;; Have it extend from close-curly to bol or beginning of block.
7474 (let ((pos (save-excursion
7475 (goto-char js2-token-end)
7476 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7477 (point-at-bol))))
7478 (end js2-token-end))
7479 (if (plusp (js2-name-node-length name))
7480 (js2-add-strict-warning "msg.no.return.value"
7481 (js2-name-node-name name) pos end)
7482 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7483
7484 (defun js2-parse-function (function-type)
7485 "Function parser. FUNCTION-TYPE is a symbol."
7486 (let ((pos js2-token-beg) ; start of 'function' keyword
7487 name
7488 name-beg
7489 name-end
7490 fn-node
7491 lp
7492 (synthetic-type function-type)
7493 member-expr-node)
7494 ;; parse function name, expression, or non-name (anonymous)
7495 (cond
7496 ;; function foo(...)
7497 ((js2-match-token js2-NAME)
7498 (setq name (js2-create-name-node t)
7499 name-beg js2-token-beg
7500 name-end js2-token-end)
7501 (unless (js2-match-token js2-LP)
7502 (when js2-allow-member-expr-as-function-name
7503 ;; function foo.bar(...)
7504 (setq member-expr-node name
7505 name nil
7506 member-expr-node (js2-parse-member-expr-tail
7507 nil member-expr-node)))
7508 (js2-must-match js2-LP "msg.no.paren.parms")))
7509 ((js2-match-token js2-LP)
7510 nil) ; anonymous function: leave name as null
7511 (t
7512 ;; function random-member-expr(...)
7513 (when js2-allow-member-expr-as-function-name
7514 ;; Note that memberExpr can not start with '(' like
7515 ;; in function (1+2).toString(), because 'function (' already
7516 ;; processed as anonymous function
7517 (setq member-expr-node (js2-parse-member-expr)))
7518 (js2-must-match js2-LP "msg.no.paren.parms")))
7519 (if (= js2-current-token js2-LP) ; eventually matched LP?
7520 (setq lp js2-token-beg))
7521 (if member-expr-node
7522 (progn
7523 (setq synthetic-type 'FUNCTION_EXPRESSION)
7524 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7525 (if name
7526 (js2-set-face name-beg name-end
7527 'font-lock-function-name-face 'record)))
7528 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7529 (plusp (js2-name-node-length name)))
7530 ;; Function statements define a symbol in the enclosing scope
7531 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7532 (setf fn-node (make-js2-function-node :pos pos
7533 :name name
7534 :form function-type
7535 :lp (if lp (- lp pos))))
7536 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7537 ;; 1. Nested functions are not affected by the dynamic scope flag
7538 ;; as dynamic scope is already a parent of their scope.
7539 ;; 2. Functions defined under the with statement also immune to
7540 ;; this setup, in which case dynamic scope is ignored in favor
7541 ;; of the with object.
7542 (setf (js2-function-node-ignore-dynamic fn-node) t))
7543 ;; dynamically bind all the per-function variables
7544 (let ((js2-current-script-or-fn fn-node)
7545 (js2-current-scope fn-node)
7546 (js2-nesting-of-with 0)
7547 (js2-end-flags 0)
7548 js2-label-set
7549 js2-loop-set
7550 js2-loop-and-switch-set)
7551 (js2-parse-function-params fn-node pos)
7552 (if (and (>= js2-language-version 180)
7553 (/= (js2-peek-token) js2-LC))
7554 (js2-parse-function-closure-body fn-node)
7555 (js2-parse-function-body fn-node))
7556 (if name
7557 (js2-node-add-children fn-node name))
7558 (js2-check-inconsistent-return-warning fn-node name)
7559 ;; Function expressions define a name only in the body of the
7560 ;; function, and only if not hidden by a parameter name
7561 (if (and name
7562 (eq synthetic-type 'FUNCTION_EXPRESSION)
7563 (null (js2-scope-get-symbol js2-current-scope
7564 (js2-name-node-name name))))
7565 (js2-define-symbol js2-FUNCTION
7566 (js2-name-node-name name)
7567 fn-node))
7568 (if (and name
7569 (not (eq function-type 'FUNCTION_EXPRESSION)))
7570 (js2-record-imenu-functions fn-node)))
7571 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7572 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7573 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7574 ;; We wait until after parsing the function to set its parent scope,
7575 ;; since `js2-define-symbol' needs the defining-scope check to stop
7576 ;; at the function boundary when checking for redeclarations.
7577 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7578 fn-node))
7579
7580 (defun js2-parse-statements (&optional parent)
7581 "Parse a statement list. Last token consumed must be js2-LC.
7582
7583 PARENT can be a `js2-block-node', in which case the statements are
7584 appended to PARENT. Otherwise a new `js2-block-node' is created
7585 and returned.
7586
7587 This function does not match the closing js2-RC: the caller
7588 matches the RC so it can provide a suitable error message if not
7589 matched. This means it's up to the caller to set the length of
7590 the node to include the closing RC. The node start pos is set to
7591 the absolute buffer start position, and the caller should fix it
7592 up to be relative to the parent node. All children of this block
7593 node are given relative start positions and correct lengths."
7594 (let ((pn (or parent (make-js2-block-node)))
7595 tt)
7596 (setf (js2-node-pos pn) js2-token-beg)
7597 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7598 (/= tt js2-RC))
7599 (js2-block-node-push pn (js2-parse-statement)))
7600 pn))
7601
7602 (defun js2-parse-statement ()
7603 (let (tt pn beg end)
7604 ;; coarse-grained user-interrupt check - needs work
7605 (and js2-parse-interruptable-p
7606 (zerop (% (incf js2-parse-stmt-count)
7607 js2-statements-per-pause))
7608 (input-pending-p)
7609 (throw 'interrupted t))
7610 (setq pn (js2-statement-helper))
7611 ;; no-side-effects warning check
7612 (unless (js2-node-has-side-effects pn)
7613 (setq end (js2-node-end pn))
7614 (save-excursion
7615 (goto-char end)
7616 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7617 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7618 pn))
7619
7620 ;; These correspond to the switch cases in Parser.statementHelper
7621 (defconst js2-parsers
7622 (let ((parsers (make-vector js2-num-tokens
7623 #'js2-parse-expr-stmt)))
7624 (aset parsers js2-BREAK #'js2-parse-break)
7625 (aset parsers js2-CONST #'js2-parse-const-var)
7626 (aset parsers js2-CONTINUE #'js2-parse-continue)
7627 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7628 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7629 (aset parsers js2-DO #'js2-parse-do)
7630 (aset parsers js2-FOR #'js2-parse-for)
7631 (aset parsers js2-FUNCTION #'js2-function-parser)
7632 (aset parsers js2-IF #'js2-parse-if)
7633 (aset parsers js2-LC #'js2-parse-block)
7634 (aset parsers js2-LET #'js2-parse-let-stmt)
7635 (aset parsers js2-NAME #'js2-parse-name-or-label)
7636 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7637 (aset parsers js2-SEMI #'js2-parse-semi)
7638 (aset parsers js2-SWITCH #'js2-parse-switch)
7639 (aset parsers js2-THROW #'js2-parse-throw)
7640 (aset parsers js2-TRY #'js2-parse-try)
7641 (aset parsers js2-VAR #'js2-parse-const-var)
7642 (aset parsers js2-WHILE #'js2-parse-while)
7643 (aset parsers js2-WITH #'js2-parse-with)
7644 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7645 parsers)
7646 "A vector mapping token types to parser functions.")
7647
7648 (defsubst js2-parse-warn-missing-semi (beg end)
7649 (and js2-mode-show-strict-warnings
7650 js2-strict-missing-semi-warning
7651 (js2-add-strict-warning
7652 "msg.missing.semi" nil
7653 ;; back up to beginning of statement or line
7654 (max beg (save-excursion
7655 (goto-char end)
7656 (point-at-bol)))
7657 end)))
7658
7659 (defconst js2-no-semi-insertion
7660 (list js2-IF
7661 js2-SWITCH
7662 js2-WHILE
7663 js2-DO
7664 js2-FOR
7665 js2-TRY
7666 js2-WITH
7667 js2-LC
7668 js2-ERROR
7669 js2-SEMI
7670 js2-FUNCTION)
7671 "List of tokens that don't do automatic semicolon insertion.")
7672
7673 (defconst js2-autoinsert-semi-and-warn
7674 (list js2-ERROR js2-EOF js2-RC))
7675
7676 (defun js2-statement-helper ()
7677 (let* ((tt (js2-peek-token))
7678 (first-tt tt)
7679 (beg js2-token-beg)
7680 (parser (if (= tt js2-ERROR)
7681 #'js2-parse-semi
7682 (aref js2-parsers tt)))
7683 pn
7684 tt-flagged)
7685 ;; If the statement is set, then it's been told its label by now.
7686 (and js2-labeled-stmt
7687 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7688 (setq js2-labeled-stmt nil))
7689 (setq pn (funcall parser))
7690 ;; Don't do auto semi insertion for certain statement types.
7691 (unless (or (memq first-tt js2-no-semi-insertion)
7692 (js2-labeled-stmt-node-p pn))
7693 (js2-auto-insert-semicolon pn))
7694 pn))
7695
7696 (defun js2-auto-insert-semicolon (pn)
7697 (let* ((tt-flagged (js2-peek-flagged-token))
7698 (tt (logand tt-flagged js2-clear-ti-mask))
7699 (pos (js2-node-pos pn)))
7700 (cond
7701 ((= tt js2-SEMI)
7702 ;; Consume ';' as a part of expression
7703 (js2-consume-token)
7704 ;; extend the node bounds to include the semicolon.
7705 (setf (js2-node-len pn) (- js2-token-end pos)))
7706 ((memq tt js2-autoinsert-semi-and-warn)
7707 ;; Autoinsert ;
7708 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7709 (t
7710 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7711 ;; Report error if no EOL or autoinsert ';' otherwise
7712 (js2-report-error "msg.no.semi.stmt")
7713 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7714
7715 (defun js2-parse-condition ()
7716 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7717 The parens are discarded and the expression node is returned.
7718 The `pos' field of the return value is set to an absolute position
7719 that must be fixed up by the caller.
7720 Return value is a list (EXPR LP RP), with absolute paren positions."
7721 (let (pn lp rp)
7722 (if (js2-must-match js2-LP "msg.no.paren.cond")
7723 (setq lp js2-token-beg))
7724 (setq pn (js2-parse-expr))
7725 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7726 (setq rp js2-token-beg))
7727 ;; Report strict warning on code like "if (a = 7) ..."
7728 (if (and js2-strict-cond-assign-warning
7729 (js2-assign-node-p pn))
7730 (js2-add-strict-warning "msg.equal.as.assign" nil
7731 (js2-node-pos pn)
7732 (+ (js2-node-pos pn)
7733 (js2-node-len pn))))
7734 (list pn lp rp)))
7735
7736 (defun js2-parse-if ()
7737 "Parser for if-statement. Last matched token must be js2-IF."
7738 (let ((pos js2-token-beg)
7739 cond
7740 if-true
7741 if-false
7742 else-pos
7743 end
7744 pn)
7745 (js2-consume-token)
7746 (setq cond (js2-parse-condition)
7747 if-true (js2-parse-statement)
7748 if-false (if (js2-match-token js2-ELSE)
7749 (progn
7750 (setq else-pos (- js2-token-beg pos))
7751 (js2-parse-statement)))
7752 end (js2-node-end (or if-false if-true))
7753 pn (make-js2-if-node :pos pos
7754 :len (- end pos)
7755 :condition (car cond)
7756 :then-part if-true
7757 :else-part if-false
7758 :else-pos else-pos
7759 :lp (js2-relpos (second cond) pos)
7760 :rp (js2-relpos (third cond) pos)))
7761 (js2-node-add-children pn (car cond) if-true if-false)
7762 pn))
7763
7764 (defun js2-parse-switch ()
7765 "Parser for if-statement. Last matched token must be js2-SWITCH."
7766 (let ((pos js2-token-beg)
7767 tt
7768 pn
7769 discriminant
7770 has-default
7771 case-expr
7772 case-node
7773 case-pos
7774 cases
7775 stmt
7776 lp
7777 rp)
7778 (js2-consume-token)
7779 (if (js2-must-match js2-LP "msg.no.paren.switch")
7780 (setq lp js2-token-beg))
7781 (setq discriminant (js2-parse-expr)
7782 pn (make-js2-switch-node :discriminant discriminant
7783 :pos pos
7784 :lp (js2-relpos lp pos)))
7785 (js2-node-add-children pn discriminant)
7786 (js2-enter-switch pn)
7787 (unwind-protect
7788 (progn
7789 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7790 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7791 (js2-must-match js2-LC "msg.no.brace.switch")
7792 (catch 'break
7793 (while t
7794 (setq tt (js2-next-token)
7795 case-pos js2-token-beg)
7796 (cond
7797 ((= tt js2-RC)
7798 (setf (js2-node-len pn) (- js2-token-end pos))
7799 (throw 'break nil)) ; done
7800 ((= tt js2-CASE)
7801 (setq case-expr (js2-parse-expr))
7802 (js2-must-match js2-COLON "msg.no.colon.case"))
7803 ((= tt js2-DEFAULT)
7804 (if has-default
7805 (js2-report-error "msg.double.switch.default"))
7806 (setq has-default t
7807 case-expr nil)
7808 (js2-must-match js2-COLON "msg.no.colon.case"))
7809 (t
7810 (js2-report-error "msg.bad.switch")
7811 (throw 'break nil)))
7812 (setq case-node (make-js2-case-node :pos case-pos
7813 :len (- js2-token-end case-pos)
7814 :expr case-expr))
7815 (js2-node-add-children case-node case-expr)
7816 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7817 (/= tt js2-CASE)
7818 (/= tt js2-DEFAULT)
7819 (/= tt js2-EOF))
7820 (setf stmt (js2-parse-statement)
7821 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7822 (js2-block-node-push case-node stmt))
7823 (push case-node cases)))
7824 ;; add cases last, as pushing reverses the order to be correct
7825 (dolist (kid cases)
7826 (js2-node-add-children pn kid)
7827 (push kid (js2-switch-node-cases pn)))
7828 pn) ; return value
7829 (js2-exit-switch))))
7830
7831 (defun js2-parse-while ()
7832 "Parser for while-statement. Last matched token must be js2-WHILE."
7833 (let ((pos js2-token-beg)
7834 (pn (make-js2-while-node))
7835 cond
7836 body)
7837 (js2-consume-token)
7838 (js2-enter-loop pn)
7839 (unwind-protect
7840 (progn
7841 (setf cond (js2-parse-condition)
7842 (js2-while-node-condition pn) (car cond)
7843 body (js2-parse-statement)
7844 (js2-while-node-body pn) body
7845 (js2-node-len pn) (- (js2-node-end body) pos)
7846 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7847 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7848 (js2-node-add-children pn body (car cond)))
7849 (js2-exit-loop))
7850 pn))
7851
7852 (defun js2-parse-do ()
7853 "Parser for do-statement. Last matched token must be js2-DO."
7854 (let ((pos js2-token-beg)
7855 (pn (make-js2-do-node))
7856 cond
7857 body
7858 end)
7859 (js2-consume-token)
7860 (js2-enter-loop pn)
7861 (unwind-protect
7862 (progn
7863 (setq body (js2-parse-statement))
7864 (js2-must-match js2-WHILE "msg.no.while.do")
7865 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7866 cond (js2-parse-condition)
7867 (js2-do-node-condition pn) (car cond)
7868 (js2-do-node-body pn) body
7869 end js2-ts-cursor
7870 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7871 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7872 (js2-node-add-children pn (car cond) body))
7873 (js2-exit-loop))
7874 ;; Always auto-insert semicolon to follow SpiderMonkey:
7875 ;; It is required by ECMAScript but is ignored by the rest of
7876 ;; world; see bug 238945
7877 (if (js2-match-token js2-SEMI)
7878 (setq end js2-ts-cursor))
7879 (setf (js2-node-len pn) (- end pos))
7880 pn))
7881
7882 (defun js2-parse-for ()
7883 "Parser for for-statement. Last matched token must be js2-FOR.
7884 Parses for, for-in, and for each-in statements."
7885 (let ((for-pos js2-token-beg)
7886 pn
7887 is-for-each
7888 is-for-in
7889 in-pos
7890 each-pos
7891 tmp-pos
7892 init ; Node init is also foo in 'foo in object'
7893 cond ; Node cond is also object in 'foo in object'
7894 incr ; 3rd section of for-loop initializer
7895 body
7896 tt
7897 lp
7898 rp)
7899 (js2-consume-token)
7900 ;; See if this is a for each () instead of just a for ()
7901 (when (js2-match-token js2-NAME)
7902 (if (string= "each" js2-ts-string)
7903 (progn
7904 (setq is-for-each t
7905 each-pos (- js2-token-beg for-pos)) ; relative
7906 (js2-record-face 'font-lock-keyword-face))
7907 (js2-report-error "msg.no.paren.for")))
7908 (if (js2-must-match js2-LP "msg.no.paren.for")
7909 (setq lp (- js2-token-beg for-pos)))
7910 (setq tt (js2-peek-token))
7911 ;; 'for' makes local scope
7912 (js2-push-scope (make-js2-scope))
7913 (unwind-protect
7914 ;; parse init clause
7915 (let ((js2-in-for-init t)) ; set as dynamic variable
7916 (cond
7917 ((= tt js2-SEMI)
7918 (setq init (make-js2-empty-expr-node)))
7919 ((or (= tt js2-VAR) (= tt js2-LET))
7920 (js2-consume-token)
7921 (setq init (js2-parse-variables tt js2-token-beg)))
7922 (t
7923 (setq init (js2-parse-expr)))))
7924 (if (js2-match-token js2-IN)
7925 (setq is-for-in t
7926 in-pos (- js2-token-beg for-pos)
7927 cond (js2-parse-expr)) ; object over which we're iterating
7928 ;; else ordinary for loop - parse cond and incr
7929 (js2-must-match js2-SEMI "msg.no.semi.for")
7930 (setq cond (if (= (js2-peek-token) js2-SEMI)
7931 (make-js2-empty-expr-node) ; no loop condition
7932 (js2-parse-expr)))
7933 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7934 (setq tmp-pos js2-token-end
7935 incr (if (= (js2-peek-token) js2-RP)
7936 (make-js2-empty-expr-node :pos tmp-pos)
7937 (js2-parse-expr))))
7938 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7939 (setq rp (- js2-token-beg for-pos)))
7940 (if (not is-for-in)
7941 (setq pn (make-js2-for-node :init init
7942 :condition cond
7943 :update incr
7944 :lp lp
7945 :rp rp))
7946 ;; cond could be null if 'in obj' got eaten by the init node.
7947 (if (js2-infix-node-p init)
7948 ;; it was (foo in bar) instead of (var foo in bar)
7949 (setq cond (js2-infix-node-right init)
7950 init (js2-infix-node-left init))
7951 (if (and (js2-var-decl-node-p init)
7952 (> (length (js2-var-decl-node-kids init)) 1))
7953 (js2-report-error "msg.mult.index")))
7954 (setq pn (make-js2-for-in-node :iterator init
7955 :object cond
7956 :in-pos in-pos
7957 :foreach-p is-for-each
7958 :each-pos each-pos
7959 :lp lp
7960 :rp rp)))
7961 (unwind-protect
7962 (progn
7963 (js2-enter-loop pn)
7964 ;; We have to parse the body -after- creating the loop node,
7965 ;; so that the loop node appears in the js2-loop-set, allowing
7966 ;; break/continue statements to find the enclosing loop.
7967 (setf body (js2-parse-statement)
7968 (js2-loop-node-body pn) body
7969 (js2-node-pos pn) for-pos
7970 (js2-node-len pn) (- (js2-node-end body) for-pos))
7971 (js2-node-add-children pn init cond incr body))
7972 ;; finally
7973 (js2-exit-loop))
7974 (js2-pop-scope))
7975 pn))
7976
7977 (defun js2-parse-try ()
7978 "Parser for try-statement. Last matched token must be js2-TRY."
7979 (let ((try-pos js2-token-beg)
7980 try-end
7981 try-block
7982 catch-blocks
7983 finally-block
7984 saw-default-catch
7985 peek
7986 param
7987 catch-cond
7988 catch-node
7989 guard-kwd
7990 catch-pos
7991 finally-pos
7992 pn
7993 block
7994 lp
7995 rp)
7996 (js2-consume-token)
7997 (if (/= (js2-peek-token) js2-LC)
7998 (js2-report-error "msg.no.brace.try"))
7999 (setq try-block (js2-parse-statement)
8000 try-end (js2-node-end try-block)
8001 peek (js2-peek-token))
8002 (cond
8003 ((= peek js2-CATCH)
8004 (while (js2-match-token js2-CATCH)
8005 (setq catch-pos js2-token-beg
8006 guard-kwd nil
8007 catch-cond nil
8008 lp nil
8009 rp nil)
8010 (if saw-default-catch
8011 (js2-report-error "msg.catch.unreachable"))
8012 (if (js2-must-match js2-LP "msg.no.paren.catch")
8013 (setq lp (- js2-token-beg catch-pos)))
8014 (js2-push-scope (make-js2-scope))
8015 (let ((tt (js2-peek-token)))
8016 (cond
8017 ;; destructuring pattern
8018 ;; catch ({ message, file }) { ... }
8019 ((or (= tt js2-LB) (= tt js2-LC))
8020 (setq param
8021 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8022 js2-LET nil)))
8023 ;; simple name
8024 (t
8025 (js2-must-match js2-NAME "msg.bad.catchcond")
8026 (setq param (js2-create-name-node))
8027 (js2-define-symbol js2-LET js2-ts-string param))))
8028 ;; pattern guard
8029 (if (js2-match-token js2-IF)
8030 (setq guard-kwd (- js2-token-beg catch-pos)
8031 catch-cond (js2-parse-expr))
8032 (setq saw-default-catch t))
8033 (if (js2-must-match js2-RP "msg.bad.catchcond")
8034 (setq rp (- js2-token-beg catch-pos)))
8035 (js2-must-match js2-LC "msg.no.brace.catchblock")
8036 (setq block (js2-parse-statements)
8037 try-end (js2-node-end block)
8038 catch-node (make-js2-catch-node :pos catch-pos
8039 :param param
8040 :guard-expr catch-cond
8041 :guard-kwd guard-kwd
8042 :block block
8043 :lp lp
8044 :rp rp))
8045 (js2-pop-scope)
8046 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8047 (setq try-end js2-token-beg))
8048 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8049 (js2-node-len catch-node) (- try-end catch-pos))
8050 (js2-node-add-children catch-node param catch-cond block)
8051 (push catch-node catch-blocks)))
8052 ((/= peek js2-FINALLY)
8053 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8054 (js2-node-pos try-block)
8055 (- (setq try-end (js2-node-end try-block))
8056 (js2-node-pos try-block)))))
8057 (when (js2-match-token js2-FINALLY)
8058 (setq finally-pos js2-token-beg
8059 block (js2-parse-statement)
8060 try-end (js2-node-end block)
8061 finally-block (make-js2-finally-node :pos finally-pos
8062 :len (- try-end finally-pos)
8063 :body block))
8064 (js2-node-add-children finally-block block))
8065 (setq pn (make-js2-try-node :pos try-pos
8066 :len (- try-end try-pos)
8067 :try-block try-block
8068 :finally-block finally-block))
8069 (js2-node-add-children pn try-block finally-block)
8070 ;; push them onto the try-node, which reverses and corrects their order
8071 (dolist (cb catch-blocks)
8072 (js2-node-add-children pn cb)
8073 (push cb (js2-try-node-catch-clauses pn)))
8074 pn))
8075
8076 (defun js2-parse-throw ()
8077 "Parser for throw-statement. Last matched token must be js2-THROW."
8078 (let ((pos js2-token-beg)
8079 expr
8080 pn)
8081 (js2-consume-token)
8082 (if (= (js2-peek-token-or-eol) js2-EOL)
8083 ;; ECMAScript does not allow new lines before throw expression,
8084 ;; see bug 256617
8085 (js2-report-error "msg.bad.throw.eol"))
8086 (setq expr (js2-parse-expr)
8087 pn (make-js2-throw-node :pos pos
8088 :len (- (js2-node-end expr) pos)
8089 :expr expr))
8090 (js2-node-add-children pn expr)
8091 pn))
8092
8093 (defsubst js2-match-jump-label-name (label-name)
8094 "If break/continue specified a label, return that label's labeled stmt.
8095 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8096 does not match an existing label, reports an error and returns nil."
8097 (let ((bundle (cdr (assoc label-name js2-label-set))))
8098 (if (null bundle)
8099 (js2-report-error "msg.undef.label"))
8100 bundle))
8101
8102 (defun js2-parse-break ()
8103 "Parser for break-statement. Last matched token must be js2-BREAK."
8104 (let ((pos js2-token-beg)
8105 (end js2-token-end)
8106 break-target ; statement to break from
8107 break-label ; in "break foo", name-node representing the foo
8108 labels ; matching labeled statement to break to
8109 pn)
8110 (js2-consume-token) ; `break'
8111 (when (eq (js2-peek-token-or-eol) js2-NAME)
8112 (js2-consume-token)
8113 (setq break-label (js2-create-name-node)
8114 end (js2-node-end break-label)
8115 ;; matchJumpLabelName only matches if there is one
8116 labels (js2-match-jump-label-name js2-ts-string)
8117 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8118 (unless (or break-target break-label)
8119 ;; no break target specified - try for innermost enclosing loop/switch
8120 (if (null js2-loop-and-switch-set)
8121 (unless break-label
8122 (js2-report-error "msg.bad.break" nil pos (length "break")))
8123 (setq break-target (car js2-loop-and-switch-set))))
8124 (setq pn (make-js2-break-node :pos pos
8125 :len (- end pos)
8126 :label break-label
8127 :target break-target))
8128 (js2-node-add-children pn break-label) ; but not break-target
8129 pn))
8130
8131 (defun js2-parse-continue ()
8132 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8133 (let ((pos js2-token-beg)
8134 (end js2-token-end)
8135 label ; optional user-specified label, a `js2-name-node'
8136 labels ; current matching labeled stmt, if any
8137 target ; the `js2-loop-node' target of this continue stmt
8138 pn)
8139 (js2-consume-token) ; `continue'
8140 (when (= (js2-peek-token-or-eol) js2-NAME)
8141 (js2-consume-token)
8142 (setq label (js2-create-name-node)
8143 end (js2-node-end label)
8144 ;; matchJumpLabelName only matches if there is one
8145 labels (js2-match-jump-label-name js2-ts-string)))
8146 (cond
8147 ((null labels) ; no current label to go to
8148 (if (null js2-loop-set) ; no loop to continue to
8149 (js2-report-error "msg.continue.outside" nil pos
8150 (length "continue"))
8151 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8152 (t
8153 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8154 (setq target (js2-labeled-stmt-node-stmt labels))
8155 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8156 (setq pn (make-js2-continue-node :pos pos
8157 :len (- end pos)
8158 :label label
8159 :target target))
8160 (js2-node-add-children pn label) ; but not target - it's not our child
8161 pn))
8162
8163 (defun js2-parse-with ()
8164 "Parser for with-statement. Last matched token must be js2-WITH."
8165 (js2-consume-token)
8166 (let ((pos js2-token-beg)
8167 obj body pn lp rp)
8168 (if (js2-must-match js2-LP "msg.no.paren.with")
8169 (setq lp js2-token-beg))
8170 (setq obj (js2-parse-expr))
8171 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8172 (setq rp js2-token-beg))
8173 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8174 (setq body (js2-parse-statement)))
8175 (setq pn (make-js2-with-node :pos pos
8176 :len (- (js2-node-end body) pos)
8177 :object obj
8178 :body body
8179 :lp (js2-relpos lp pos)
8180 :rp (js2-relpos rp pos)))
8181 (js2-node-add-children pn obj body)
8182 pn))
8183
8184 (defun js2-parse-const-var ()
8185 "Parser for var- or const-statement.
8186 Last matched token must be js2-CONST or js2-VAR."
8187 (let ((tt (js2-peek-token))
8188 (pos js2-token-beg)
8189 expr
8190 pn)
8191 (js2-consume-token)
8192 (setq expr (js2-parse-variables tt js2-token-beg)
8193 pn (make-js2-expr-stmt-node :pos pos
8194 :len (- (js2-node-end expr) pos)
8195 :expr expr))
8196 (js2-node-add-children pn expr)
8197 pn))
8198
8199 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8200 (let ((pn (make-js2-expr-stmt-node :pos pos
8201 :len (js2-node-len expr)
8202 :type (if (js2-inside-function)
8203 js2-EXPR_VOID
8204 js2-EXPR_RESULT)
8205 :expr expr)))
8206 (if add-child
8207 (js2-node-add-children pn expr))
8208 pn))
8209
8210 (defun js2-parse-let-stmt ()
8211 "Parser for let-statement. Last matched token must be js2-LET."
8212 (js2-consume-token)
8213 (let ((pos js2-token-beg)
8214 expr
8215 pn)
8216 (if (= (js2-peek-token) js2-LP)
8217 ;; let expression in statement context
8218 (setq expr (js2-parse-let pos 'statement)
8219 pn (js2-wrap-with-expr-stmt pos expr t))
8220 ;; else we're looking at a statement like let x=6, y=7;
8221 (setf expr (js2-parse-variables js2-LET pos)
8222 pn (js2-wrap-with-expr-stmt pos expr t)
8223 (js2-node-type pn) js2-EXPR_RESULT))
8224 pn))
8225
8226 (defun js2-parse-ret-yield ()
8227 (js2-parse-return-or-yield (js2-peek-token) nil))
8228
8229 (defconst js2-parse-return-stmt-enders
8230 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8231
8232 (defsubst js2-now-all-set (before after mask)
8233 "Return whether or not the bits in the mask have changed to all set.
8234 BEFORE is bits before change, AFTER is bits after change, and MASK is
8235 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8236 but not BEFORE."
8237 (and (/= (logand before mask) mask)
8238 (= (logand after mask) mask)))
8239
8240 (defun js2-parse-return-or-yield (tt expr-context)
8241 (let ((pos js2-token-beg)
8242 (end js2-token-end)
8243 (before js2-end-flags)
8244 (inside-function (js2-inside-function))
8245 e
8246 ret
8247 name)
8248 (unless inside-function
8249 (js2-report-error (if (eq tt js2-RETURN)
8250 "msg.bad.return"
8251 "msg.bad.yield")))
8252 (js2-consume-token)
8253 ;; This is ugly, but we don't want to require a semicolon.
8254 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8255 (setq e (js2-parse-expr)
8256 end (js2-node-end e)))
8257 (cond
8258 ((eq tt js2-RETURN)
8259 (js2-set-flag js2-end-flags (if (null e)
8260 js2-end-returns
8261 js2-end-returns-value))
8262 (setq ret (make-js2-return-node :pos pos
8263 :len (- end pos)
8264 :retval e))
8265 (js2-node-add-children ret e)
8266 ;; See if we need a strict mode warning.
8267 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8268 ;; more thorough and accurate than this before/after flag check.
8269 ;; E.g. if there's a finally-block that always returns, we shouldn't
8270 ;; show a warning generated by inconsistent returns in the catch blocks.
8271 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8272 ;; so we know which returns/yields to highlight, and we should get rid of
8273 ;; all the checking in `js2-parse-return-or-yield'.
8274 (if (and js2-strict-inconsistent-return-warning
8275 (js2-now-all-set before js2-end-flags
8276 (logior js2-end-returns js2-end-returns-value)))
8277 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8278 (t
8279 (unless (js2-inside-function)
8280 (js2-report-error "msg.bad.yield"))
8281 (js2-set-flag js2-end-flags js2-end-yields)
8282 (setq ret (make-js2-yield-node :pos pos
8283 :len (- end pos)
8284 :value e))
8285 (js2-node-add-children ret e)
8286 (unless expr-context
8287 (setq e ret
8288 ret (js2-wrap-with-expr-stmt pos e t))
8289 (js2-set-requires-activation)
8290 (js2-set-is-generator))))
8291 ;; see if we are mixing yields and value returns.
8292 (when (and inside-function
8293 (js2-now-all-set before js2-end-flags
8294 (logior js2-end-yields js2-end-returns-value)))
8295 (setq name (js2-function-name js2-current-script-or-fn))
8296 (if (zerop (length name))
8297 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8298 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8299 ret))
8300
8301 (defun js2-parse-debugger ()
8302 (js2-consume-token)
8303 (make-js2-keyword-node :type js2-DEBUGGER))
8304
8305 (defun js2-parse-block ()
8306 "Parser for a curly-delimited statement block.
8307 Last token matched must be js2-LC."
8308 (let ((pos js2-token-beg)
8309 (pn (make-js2-scope)))
8310 (js2-consume-token)
8311 (js2-push-scope pn)
8312 (unwind-protect
8313 (progn
8314 (js2-parse-statements pn)
8315 (js2-must-match js2-RC "msg.no.brace.block")
8316 (setf (js2-node-len pn) (- js2-token-end pos)))
8317 (js2-pop-scope))
8318 pn))
8319
8320 ;; for js2-ERROR too, to have a node for error recovery to work on
8321 (defun js2-parse-semi ()
8322 "Parse a statement or handle an error.
8323 Last matched token is js-SEMI or js-ERROR."
8324 (let ((tt (js2-peek-token)) pos len)
8325 (js2-consume-token)
8326 (if (eq tt js2-SEMI)
8327 (make-js2-empty-expr-node :len 1)
8328 (setq pos js2-token-beg
8329 len (- js2-token-beg pos))
8330 (js2-report-error "msg.syntax" nil pos len)
8331 (make-js2-error-node :pos pos :len len))))
8332
8333 (defun js2-parse-default-xml-namespace ()
8334 "Parse a `default xml namespace = <expr>' e4x statement."
8335 (let ((pos js2-token-beg)
8336 end len expr unary es)
8337 (js2-consume-token)
8338 (js2-must-have-xml)
8339 (js2-set-requires-activation)
8340 (setq len (- js2-ts-cursor pos))
8341 (unless (and (js2-match-token js2-NAME)
8342 (string= js2-ts-string "xml"))
8343 (js2-report-error "msg.bad.namespace" nil pos len))
8344 (unless (and (js2-match-token js2-NAME)
8345 (string= js2-ts-string "namespace"))
8346 (js2-report-error "msg.bad.namespace" nil pos len))
8347 (unless (js2-match-token js2-ASSIGN)
8348 (js2-report-error "msg.bad.namespace" nil pos len))
8349 (setq expr (js2-parse-expr)
8350 end (js2-node-end expr)
8351 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8352 :pos pos
8353 :len (- end pos)
8354 :operand expr))
8355 (js2-node-add-children unary expr)
8356 (make-js2-expr-stmt-node :pos pos
8357 :len (- end pos)
8358 :expr unary)))
8359
8360 (defun js2-record-label (label bundle)
8361 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8362 (js2-consume-token)
8363 (let ((name (js2-label-node-name label))
8364 labeled-stmt
8365 dup)
8366 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8367 ;; flag both labels if possible when used in editing mode
8368 (if (and js2-parse-ide-mode
8369 (setq dup (js2-get-label-by-name labeled-stmt name)))
8370 (js2-report-error "msg.dup.label" nil
8371 (js2-node-abs-pos dup) (js2-node-len dup)))
8372 (js2-report-error "msg.dup.label" nil
8373 (js2-node-pos label) (js2-node-len label)))
8374 (js2-labeled-stmt-node-add-label bundle label)
8375 (js2-node-add-children bundle label)
8376 ;; Add one reference to the bundle per label in `js2-label-set'
8377 (push (cons name bundle) js2-label-set)))
8378
8379 (defun js2-parse-name-or-label ()
8380 "Parser for identifier or label. Last token matched must be js2-NAME.
8381 Called when we found a name in a statement context. If it's a label, we gather
8382 up any following labels and the next non-label statement into a
8383 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8384 expression and return it wrapped in a `js2-expr-stmt-node'."
8385 (let ((pos js2-token-beg)
8386 (end js2-token-end)
8387 expr
8388 stmt
8389 pn
8390 bundle
8391 (continue t))
8392 ;; set check for label and call down to `js2-parse-primary-expr'
8393 (js2-set-check-for-label)
8394 (setq expr (js2-parse-expr))
8395 (if (/= (js2-node-type expr) js2-LABEL)
8396 ;; Parsed non-label expression - wrap with expression stmt.
8397 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8398 ;; else parsed a label
8399 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8400 (js2-record-label expr bundle)
8401 ;; look for more labels
8402 (while (and continue (= (js2-peek-token) js2-NAME))
8403 (js2-set-check-for-label)
8404 (setq expr (js2-parse-expr))
8405 (if (/= (js2-node-type expr) js2-LABEL)
8406 (progn
8407 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8408 continue nil)
8409 (js2-auto-insert-semicolon stmt))
8410 (js2-record-label expr bundle)))
8411 ;; no more labels; now parse the labeled statement
8412 (unwind-protect
8413 (unless stmt
8414 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8415 (setq stmt (js2-statement-helper))))
8416 ;; remove the labels for this statement from the global set
8417 (dolist (label (js2-labeled-stmt-node-labels bundle))
8418 (setq js2-label-set (remove label js2-label-set))))
8419 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8420 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8421 (js2-node-add-children bundle stmt)
8422 bundle)))
8423
8424 (defun js2-parse-expr-stmt ()
8425 "Default parser in statement context, if no recognized statement found."
8426 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8427
8428 (defun js2-parse-variables (decl-type pos)
8429 "Parse a comma-separated list of variable declarations.
8430 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8431
8432 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8433 For 'var' or 'const', the keyword should be the token last scanned.
8434
8435 POS is the position where the node should start. It's sometimes the
8436 var/const/let keyword, and other times the beginning of the first token
8437 in the first variable declaration.
8438
8439 Returns the parsed `js2-var-decl-node' expression node."
8440 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8441 :pos pos))
8442 destructuring
8443 kid-pos
8444 tt
8445 init
8446 name
8447 end
8448 nbeg nend
8449 vi
8450 (continue t))
8451 ;; Example:
8452 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8453 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8454 ;; var {a, b} = baz;
8455 (while continue
8456 (setq destructuring nil
8457 name nil
8458 tt (js2-peek-token)
8459 kid-pos js2-token-beg
8460 end js2-token-end
8461 init nil)
8462 (if (or (= tt js2-LB) (= tt js2-LC))
8463 ;; Destructuring assignment, e.g., var [a, b] = ...
8464 (setq destructuring (js2-parse-primary-expr-lhs)
8465 end (js2-node-end destructuring))
8466 ;; Simple variable name
8467 (when (js2-must-match js2-NAME "msg.bad.var")
8468 (setq name (js2-create-name-node)
8469 nbeg js2-token-beg
8470 nend js2-token-end
8471 end nend)
8472 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8473 (when (js2-match-token js2-ASSIGN)
8474 (setq init (js2-parse-assign-expr)
8475 end (js2-node-end init))
8476 (if (and js2-parse-ide-mode
8477 (or (js2-object-node-p init)
8478 (js2-function-node-p init)))
8479 (js2-record-imenu-functions init name)))
8480 (when name
8481 (js2-set-face nbeg nend (if (js2-function-node-p init)
8482 'font-lock-function-name-face
8483 'font-lock-variable-name-face)
8484 'record))
8485 (setq vi (make-js2-var-init-node :pos kid-pos
8486 :len (- end kid-pos)
8487 :type decl-type))
8488 (if destructuring
8489 (progn
8490 (if (and (null init) (not js2-in-for-init))
8491 (js2-report-error "msg.destruct.assign.no.init"))
8492 (js2-define-destruct-symbols destructuring
8493 decl-type
8494 'font-lock-variable-name-face)
8495 (setf (js2-var-init-node-target vi) destructuring))
8496 (setf (js2-var-init-node-target vi) name))
8497 (setf (js2-var-init-node-initializer vi) init)
8498 (js2-node-add-children vi name destructuring init)
8499 (js2-block-node-push result vi)
8500 (unless (js2-match-token js2-COMMA)
8501 (setq continue nil)))
8502 (setf (js2-node-len result) (- end pos))
8503 result))
8504
8505 (defun js2-parse-let (pos &optional stmt-p)
8506 "Parse a let expression or statement.
8507 A let-expression is of the form `let (vars) expr'.
8508 A let-statment is of the form `let (vars) {statements}'.
8509 The third form of let is a variable declaration list, handled
8510 by `js2-parse-variables'."
8511 (let ((pn (make-js2-let-node :pos pos))
8512 beg vars body)
8513 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8514 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8515 (js2-push-scope pn)
8516 (unwind-protect
8517 (progn
8518 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8519 (if (js2-must-match js2-RP "msg.no.paren.let")
8520 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8521 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8522 ;; let statement
8523 (progn
8524 (js2-consume-token)
8525 (setf beg js2-token-beg ; position stmt at LC
8526 body (js2-parse-statements))
8527 (js2-must-match js2-RC "msg.no.curly.let")
8528 (setf (js2-node-len body) (- js2-token-end beg)
8529 (js2-node-len pn) (- js2-token-end pos)
8530 (js2-let-node-body pn) body
8531 (js2-node-type pn) js2-LET))
8532 ;; let expression
8533 (setf body (js2-parse-expr)
8534 (js2-node-len pn) (- (js2-node-end body) pos)
8535 (js2-let-node-body pn) body))
8536 (js2-node-add-children pn vars body))
8537 (js2-pop-scope))
8538 pn))
8539
8540 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8541 (js2-scope-put-symbol (or scope js2-current-scope)
8542 name
8543 (make-js2-symbol decl-type name node)))
8544
8545 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8546 "Define a symbol in the current scope.
8547 If NODE is non-nil, it is the AST node associated with the symbol."
8548 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8549 (symbol (if defining-scope
8550 (js2-scope-get-symbol defining-scope name)))
8551 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8552 (cond
8553 ((and symbol ; already defined
8554 (or (= sdt js2-CONST) ; old version is const
8555 (= decl-type js2-CONST) ; new version is const
8556 ;; two let-bound vars in this block have same name
8557 (and (= sdt js2-LET)
8558 (eq defining-scope js2-current-scope))))
8559 (js2-report-error
8560 (cond
8561 ((= sdt js2-CONST) "msg.const.redecl")
8562 ((= sdt js2-LET) "msg.let.redecl")
8563 ((= sdt js2-VAR) "msg.var.redecl")
8564 ((= sdt js2-FUNCTION) "msg.function.redecl")
8565 (t "msg.parm.redecl"))
8566 name))
8567 ((= decl-type js2-LET)
8568 (if (and (not ignore-not-in-block)
8569 (or (= (js2-node-type js2-current-scope) js2-IF)
8570 (js2-loop-node-p js2-current-scope)))
8571 (js2-report-error "msg.let.decl.not.in.block")
8572 (js2-define-new-symbol decl-type name node)))
8573 ((or (= decl-type js2-VAR)
8574 (= decl-type js2-CONST)
8575 (= decl-type js2-FUNCTION))
8576 (if symbol
8577 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8578 (js2-add-strict-warning "msg.var.redecl" name)
8579 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8580 (js2-add-strict-warning "msg.var.hides.arg" name)))
8581 (js2-define-new-symbol decl-type name node
8582 js2-current-script-or-fn)))
8583 ((= decl-type js2-LP)
8584 (if symbol
8585 ;; must be duplicate parameter. Second parameter hides the
8586 ;; first, so go ahead and add the second pararameter
8587 (js2-report-warning "msg.dup.parms" name))
8588 (js2-define-new-symbol decl-type name node))
8589 (t (js2-code-bug)))))
8590
8591 (defun js2-parse-expr (&optional oneshot)
8592 (let* ((pn (js2-parse-assign-expr))
8593 (pos (js2-node-pos pn))
8594 left
8595 right
8596 op-pos)
8597 (while (and (not oneshot)
8598 (js2-match-token js2-COMMA))
8599 (setq op-pos (- js2-token-beg pos)) ; relative
8600 (if (= (js2-peek-token) js2-YIELD)
8601 (js2-report-error "msg.yield.parenthesized"))
8602 (setq right (js2-parse-assign-expr)
8603 left pn
8604 pn (make-js2-infix-node :type js2-COMMA
8605 :pos pos
8606 :len (- js2-ts-cursor pos)
8607 :op-pos op-pos
8608 :left left
8609 :right right))
8610 (js2-node-add-children pn left right))
8611 pn))
8612
8613 (defun js2-parse-assign-expr ()
8614 (let ((tt (js2-peek-token))
8615 (pos js2-token-beg)
8616 pn
8617 left
8618 right
8619 op-pos)
8620 (if (= tt js2-YIELD)
8621 (js2-parse-return-or-yield tt t)
8622 ;; not yield - parse assignment expression
8623 (setq pn (js2-parse-cond-expr)
8624 tt (js2-peek-token))
8625 (when (and (<= js2-first-assign tt)
8626 (<= tt js2-last-assign))
8627 ;; tt express assignment (=, |=, ^=, ..., %=)
8628 (js2-consume-token)
8629 (setq op-pos (- js2-token-beg pos) ; relative
8630 left pn
8631 right (js2-parse-assign-expr)
8632 pn (make-js2-assign-node :type tt
8633 :pos pos
8634 :len (- (js2-node-end right) pos)
8635 :op-pos op-pos
8636 :left left
8637 :right right))
8638 (when js2-parse-ide-mode
8639 (js2-highlight-assign-targets pn left right)
8640 (if (or (js2-function-node-p right)
8641 (js2-object-node-p right))
8642 (js2-record-imenu-functions right left)))
8643 ;; do this last so ide checks above can use absolute positions
8644 (js2-node-add-children pn left right))
8645 pn)))
8646
8647 (defun js2-parse-cond-expr ()
8648 (let ((pos js2-token-beg)
8649 (pn (js2-parse-or-expr))
8650 test-expr
8651 if-true
8652 if-false
8653 q-pos
8654 c-pos)
8655 (when (js2-match-token js2-HOOK)
8656 (setq q-pos (- js2-token-beg pos)
8657 if-true (js2-parse-assign-expr))
8658 (js2-must-match js2-COLON "msg.no.colon.cond")
8659 (setq c-pos (- js2-token-beg pos)
8660 if-false (js2-parse-assign-expr)
8661 test-expr pn
8662 pn (make-js2-cond-node :pos pos
8663 :len (- (js2-node-end if-false) pos)
8664 :test-expr test-expr
8665 :true-expr if-true
8666 :false-expr if-false
8667 :q-pos q-pos
8668 :c-pos c-pos))
8669 (js2-node-add-children pn test-expr if-true if-false))
8670 pn))
8671
8672 (defun js2-make-binary (type left parser)
8673 "Helper for constructing a binary-operator AST node.
8674 LEFT is the left-side-expression, already parsed, and the
8675 binary operator should have just been matched.
8676 PARSER is a function to call to parse the right operand,
8677 or a `js2-node' struct if it has already been parsed."
8678 (let* ((pos (js2-node-pos left))
8679 (op-pos (- js2-token-beg pos))
8680 (right (if (js2-node-p parser)
8681 parser
8682 (funcall parser)))
8683 (pn (make-js2-infix-node :type type
8684 :pos pos
8685 :len (- (js2-node-end right) pos)
8686 :op-pos op-pos
8687 :left left
8688 :right right)))
8689 (js2-node-add-children pn left right)
8690 pn))
8691
8692 (defun js2-parse-or-expr ()
8693 (let ((pn (js2-parse-and-expr)))
8694 (when (js2-match-token js2-OR)
8695 (setq pn (js2-make-binary js2-OR
8696 pn
8697 'js2-parse-or-expr)))
8698 pn))
8699
8700 (defun js2-parse-and-expr ()
8701 (let ((pn (js2-parse-bit-or-expr)))
8702 (when (js2-match-token js2-AND)
8703 (setq pn (js2-make-binary js2-AND
8704 pn
8705 'js2-parse-and-expr)))
8706 pn))
8707
8708 (defun js2-parse-bit-or-expr ()
8709 (let ((pn (js2-parse-bit-xor-expr)))
8710 (while (js2-match-token js2-BITOR)
8711 (setq pn (js2-make-binary js2-BITOR
8712 pn
8713 'js2-parse-bit-xor-expr)))
8714 pn))
8715
8716 (defun js2-parse-bit-xor-expr ()
8717 (let ((pn (js2-parse-bit-and-expr)))
8718 (while (js2-match-token js2-BITXOR)
8719 (setq pn (js2-make-binary js2-BITXOR
8720 pn
8721 'js2-parse-bit-and-expr)))
8722 pn))
8723
8724 (defun js2-parse-bit-and-expr ()
8725 (let ((pn (js2-parse-eq-expr)))
8726 (while (js2-match-token js2-BITAND)
8727 (setq pn (js2-make-binary js2-BITAND
8728 pn
8729 'js2-parse-eq-expr)))
8730 pn))
8731
8732 (defconst js2-parse-eq-ops
8733 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8734
8735 (defun js2-parse-eq-expr ()
8736 (let ((pn (js2-parse-rel-expr))
8737 tt)
8738 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8739 (js2-consume-token)
8740 (setq pn (js2-make-binary tt
8741 pn
8742 'js2-parse-rel-expr)))
8743 pn))
8744
8745 (defconst js2-parse-rel-ops
8746 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8747
8748 (defun js2-parse-rel-expr ()
8749 (let ((pn (js2-parse-shift-expr))
8750 (continue t)
8751 tt)
8752 (while continue
8753 (setq tt (js2-peek-token))
8754 (cond
8755 ((and js2-in-for-init (= tt js2-IN))
8756 (setq continue nil))
8757 ((memq tt js2-parse-rel-ops)
8758 (js2-consume-token)
8759 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8760 (t
8761 (setq continue nil))))
8762 pn))
8763
8764 (defconst js2-parse-shift-ops
8765 (list js2-LSH js2-URSH js2-RSH))
8766
8767 (defun js2-parse-shift-expr ()
8768 (let ((pn (js2-parse-add-expr))
8769 tt
8770 (continue t))
8771 (while continue
8772 (setq tt (js2-peek-token))
8773 (if (memq tt js2-parse-shift-ops)
8774 (progn
8775 (js2-consume-token)
8776 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8777 (setq continue nil)))
8778 pn))
8779
8780 (defun js2-parse-add-expr ()
8781 (let ((pn (js2-parse-mul-expr))
8782 tt
8783 (continue t))
8784 (while continue
8785 (setq tt (js2-peek-token))
8786 (if (or (= tt js2-ADD) (= tt js2-SUB))
8787 (progn
8788 (js2-consume-token)
8789 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8790 (setq continue nil)))
8791 pn))
8792
8793 (defconst js2-parse-mul-ops
8794 (list js2-MUL js2-DIV js2-MOD))
8795
8796 (defun js2-parse-mul-expr ()
8797 (let ((pn (js2-parse-unary-expr))
8798 tt
8799 (continue t))
8800 (while continue
8801 (setq tt (js2-peek-token))
8802 (if (memq tt js2-parse-mul-ops)
8803 (progn
8804 (js2-consume-token)
8805 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8806 (setq continue nil)))
8807 pn))
8808
8809 (defsubst js2-make-unary (type parser &rest args)
8810 "Make a unary node of type TYPE.
8811 PARSER is either a node (for postfix operators) or a function to call
8812 to parse the operand (for prefix operators)."
8813 (let* ((pos js2-token-beg)
8814 (postfix (js2-node-p parser))
8815 (expr (if postfix
8816 parser
8817 (apply parser args)))
8818 end
8819 pn)
8820 (if postfix ; e.g. i++
8821 (setq pos (js2-node-pos expr)
8822 end js2-token-end)
8823 (setq end (js2-node-end expr)))
8824 (setq pn (make-js2-unary-node :type type
8825 :pos pos
8826 :len (- end pos)
8827 :operand expr))
8828 (js2-node-add-children pn expr)
8829 pn))
8830
8831 (defconst js2-incrementable-node-types
8832 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8833 "Node types that can be the operand of a ++ or -- operator.")
8834
8835 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8836 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8837 js2-incrementable-node-types)
8838 (js2-report-error (if (= tt js2-INC)
8839 "msg.bad.incr"
8840 "msg.bad.decr")
8841 nil beg (- end beg))))
8842
8843 (defun js2-parse-unary-expr ()
8844 (let ((tt (js2-peek-token))
8845 pn expr beg end)
8846 (cond
8847 ((or (= tt js2-VOID)
8848 (= tt js2-NOT)
8849 (= tt js2-BITNOT)
8850 (= tt js2-TYPEOF))
8851 (js2-consume-token)
8852 (js2-make-unary tt 'js2-parse-unary-expr))
8853 ((= tt js2-ADD)
8854 (js2-consume-token)
8855 ;; Convert to special POS token in decompiler and parse tree
8856 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8857 ((= tt js2-SUB)
8858 (js2-consume-token)
8859 ;; Convert to special NEG token in decompiler and parse tree
8860 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8861 ((or (= tt js2-INC)
8862 (= tt js2-DEC))
8863 (js2-consume-token)
8864 (prog1
8865 (setq beg js2-token-beg
8866 end js2-token-end
8867 expr (js2-make-unary tt 'js2-parse-member-expr t))
8868 (js2-check-bad-inc-dec tt beg end expr)))
8869 ((= tt js2-DELPROP)
8870 (js2-consume-token)
8871 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8872 ((= tt js2-ERROR)
8873 (js2-consume-token)
8874 (make-js2-error-node)) ; try to continue
8875 ((and (= tt js2-LT)
8876 js2-compiler-xml-available)
8877 ;; XML stream encountered in expression.
8878 (js2-consume-token)
8879 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8880 (t
8881 (setq pn (js2-parse-member-expr t)
8882 ;; Don't look across a newline boundary for a postfix incop.
8883 tt (js2-peek-token-or-eol))
8884 (when (or (= tt js2-INC) (= tt js2-DEC))
8885 (js2-consume-token)
8886 (setf expr pn
8887 pn (js2-make-unary tt expr))
8888 (js2-node-set-prop pn 'postfix t)
8889 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8890 pn))))
8891
8892 (defun js2-parse-xml-initializer ()
8893 "Parse an E4X XML initializer.
8894 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8895 Then I'll postprocess the result, depending on whether we're in IDE
8896 mode or codegen mode, and generate the appropriate rewritten AST.
8897 IDE mode uses a rich AST that models the XML structure. Codegen mode
8898 just concatenates everything and makes a new XML or XMLList out of it."
8899 (let ((tt (js2-get-first-xml-token))
8900 pn-xml
8901 pn
8902 expr
8903 kids
8904 expr-pos
8905 (continue t)
8906 (first-token t))
8907 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8908 (js2-report-error "msg.syntax"))
8909 (setq pn-xml (make-js2-xml-node))
8910 (while continue
8911 (if first-token
8912 (setq first-token nil)
8913 (setq tt (js2-get-next-xml-token)))
8914 (cond
8915 ;; js2-XML means we found a {expr} in the XML stream.
8916 ;; The js2-ts-string is the XML up to the left-curly.
8917 ((= tt js2-XML)
8918 (push (make-js2-string-node :pos js2-token-beg
8919 :len (- js2-ts-cursor js2-token-beg))
8920 kids)
8921 (js2-must-match js2-LC "msg.syntax")
8922 (setq expr-pos js2-ts-cursor
8923 expr (if (eq (js2-peek-token) js2-RC)
8924 (make-js2-empty-expr-node :pos expr-pos)
8925 (js2-parse-expr)))
8926 (js2-must-match js2-RC "msg.syntax")
8927 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8928 :len (js2-node-len expr)
8929 :expr expr))
8930 (js2-node-add-children pn expr)
8931 (push pn kids))
8932 ;; a js2-XMLEND token means we hit the final close-tag.
8933 ((= tt js2-XMLEND)
8934 (push (make-js2-string-node :pos js2-token-beg
8935 :len (- js2-ts-cursor js2-token-beg))
8936 kids)
8937 (dolist (kid (nreverse kids))
8938 (js2-block-node-push pn-xml kid))
8939 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8940 (js2-node-pos pn-xml))
8941 continue nil))
8942 (t
8943 (js2-report-error "msg.syntax")
8944 (setq continue nil))))
8945 pn-xml))
8946
8947
8948 (defun js2-parse-argument-list ()
8949 "Parse an argument list and return it as a lisp list of nodes.
8950 Returns the list in reverse order. Consumes the right-paren token."
8951 (let (result)
8952 (unless (js2-match-token js2-RP)
8953 (loop do
8954 (if (= (js2-peek-token) js2-YIELD)
8955 (js2-report-error "msg.yield.parenthesized"))
8956 (push (js2-parse-assign-expr) result)
8957 while
8958 (js2-match-token js2-COMMA))
8959 (js2-must-match js2-RP "msg.no.paren.arg")
8960 result)))
8961
8962 (defun js2-parse-member-expr (&optional allow-call-syntax)
8963 (let ((tt (js2-peek-token))
8964 pn
8965 pos
8966 target
8967 args
8968 beg
8969 end
8970 init
8971 tail)
8972 (if (/= tt js2-NEW)
8973 (setq pn (js2-parse-primary-expr))
8974 ;; parse a 'new' expression
8975 (js2-consume-token)
8976 (setq pos js2-token-beg
8977 beg pos
8978 target (js2-parse-member-expr)
8979 end (js2-node-end target)
8980 pn (make-js2-new-node :pos pos
8981 :target target
8982 :len (- end pos)))
8983 (js2-node-add-children pn target)
8984 (when (js2-match-token js2-LP)
8985 ;; Add the arguments to pn, if any are supplied.
8986 (setf beg pos ; start of "new" keyword
8987 pos js2-token-beg
8988 args (nreverse (js2-parse-argument-list))
8989 (js2-new-node-args pn) args
8990 end js2-token-end
8991 (js2-new-node-lp pn) (- pos beg)
8992 (js2-new-node-rp pn) (- end 1 beg))
8993 (apply #'js2-node-add-children pn args))
8994 (when (and js2-allow-rhino-new-expr-initializer
8995 (js2-match-token js2-LC))
8996 (setf init (js2-parse-object-literal)
8997 end (js2-node-end init)
8998 (js2-new-node-initializer pn) init)
8999 (js2-node-add-children pn init))
9000 (setf (js2-node-len pn) (- end beg))) ; end outer if
9001 (js2-parse-member-expr-tail allow-call-syntax pn)))
9002
9003 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9004 "Parse a chain of property/array accesses or function calls.
9005 Includes parsing for E4X operators like `..' and `.@'.
9006 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9007 Returns an expression tree that includes PN, the parent node."
9008 (let ((beg (js2-node-pos pn))
9009 tt
9010 (continue t))
9011 (while continue
9012 (setq tt (js2-peek-token))
9013 (cond
9014 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9015 (setq pn (js2-parse-property-access tt pn)))
9016 ((= tt js2-DOTQUERY)
9017 (setq pn (js2-parse-dot-query pn)))
9018 ((= tt js2-LB)
9019 (setq pn (js2-parse-element-get pn)))
9020 ((= tt js2-LP)
9021 (if allow-call-syntax
9022 (setq pn (js2-parse-function-call pn))
9023 (setq continue nil)))
9024 (t
9025 (setq continue nil))))
9026 (if (>= js2-highlight-level 2)
9027 (js2-parse-highlight-member-expr-node pn))
9028 pn))
9029
9030 (defun js2-parse-dot-query (pn)
9031 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9032 Last token parsed must be `js2-DOTQUERY'."
9033 (let ((pos (js2-node-pos pn))
9034 op-pos
9035 expr
9036 end)
9037 (js2-consume-token)
9038 (js2-must-have-xml)
9039 (js2-set-requires-activation)
9040 (setq op-pos js2-token-beg
9041 expr (js2-parse-expr)
9042 end (js2-node-end expr)
9043 pn (make-js2-xml-dot-query-node :left pn
9044 :pos pos
9045 :op-pos op-pos
9046 :right expr))
9047 (js2-node-add-children pn
9048 (js2-xml-dot-query-node-left pn)
9049 (js2-xml-dot-query-node-right pn))
9050 (if (js2-must-match js2-RP "msg.no.paren")
9051 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9052 end js2-token-end))
9053 (setf (js2-node-len pn) (- end pos))
9054 pn))
9055
9056 (defun js2-parse-element-get (pn)
9057 "Parse an element-get expression, e.g. foo[bar].
9058 Last token parsed must be `js2-RB'."
9059 (let ((lb js2-token-beg)
9060 (pos (js2-node-pos pn))
9061 rb
9062 expr)
9063 (js2-consume-token)
9064 (setq expr (js2-parse-expr))
9065 (if (js2-must-match js2-RB "msg.no.bracket.index")
9066 (setq rb js2-token-beg))
9067 (setq pn (make-js2-elem-get-node :target pn
9068 :pos pos
9069 :element expr
9070 :lb (js2-relpos lb pos)
9071 :rb (js2-relpos rb pos)
9072 :len (- js2-token-end pos)))
9073 (js2-node-add-children pn
9074 (js2-elem-get-node-target pn)
9075 (js2-elem-get-node-element pn))
9076 pn))
9077
9078 (defun js2-parse-function-call (pn)
9079 (let (args
9080 (pos (js2-node-pos pn)))
9081 (js2-consume-token)
9082 (setq pn (make-js2-call-node :pos pos
9083 :target pn
9084 :lp (- js2-token-beg pos)))
9085 (js2-node-add-children pn (js2-call-node-target pn))
9086 ;; Add the arguments to pn, if any are supplied.
9087 (setf args (nreverse (js2-parse-argument-list))
9088 (js2-call-node-rp pn) (- js2-token-beg pos)
9089 (js2-call-node-args pn) args)
9090 (apply #'js2-node-add-children pn args)
9091 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9092 pn))
9093
9094 (defun js2-parse-property-access (tt pn)
9095 "Parse a property access, XML descendants access, or XML attr access."
9096 (let ((member-type-flags 0)
9097 (dot-pos js2-token-beg)
9098 (dot-len (if (= tt js2-DOTDOT) 2 1))
9099 name
9100 ref ; right side of . or .. operator
9101 result)
9102 (js2-consume-token)
9103 (when (= tt js2-DOTDOT)
9104 (js2-must-have-xml)
9105 (setq member-type-flags js2-descendants-flag))
9106 (if (not js2-compiler-xml-available)
9107 (progn
9108 (js2-must-match-prop-name "msg.no.name.after.dot")
9109 (setq name (js2-create-name-node t js2-GETPROP)
9110 result (make-js2-prop-get-node :left pn
9111 :pos js2-token-beg
9112 :right name
9113 :len (- js2-token-end
9114 js2-token-beg)))
9115 (js2-node-add-children result pn name)
9116 result)
9117 ;; otherwise look for XML operators
9118 (setf result (if (= tt js2-DOT)
9119 (make-js2-prop-get-node)
9120 (make-js2-infix-node :type js2-DOTDOT))
9121 (js2-node-pos result) (js2-node-pos pn)
9122 (js2-infix-node-op-pos result) dot-pos
9123 (js2-infix-node-left result) pn ; do this after setting position
9124 tt (js2-next-token))
9125 (cond
9126 ;; needed for generator.throw()
9127 ((= tt js2-THROW)
9128 (js2-save-name-token-data js2-token-beg "throw")
9129 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9130 ;; handles: name, ns::name, ns::*, ns::[expr]
9131 ((js2-valid-prop-name-token tt)
9132 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9133 ;; handles: *, *::name, *::*, *::[expr]
9134 ((= tt js2-MUL)
9135 (js2-save-name-token-data js2-token-beg "*")
9136 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9137 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9138 ((= tt js2-XMLATTR)
9139 (setq result (js2-parse-attribute-access)))
9140 (t
9141 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9142 (if ref
9143 (setf (js2-node-len result) (- (js2-node-end ref)
9144 (js2-node-pos result))
9145 (js2-infix-node-right result) ref))
9146 (if (js2-infix-node-p result)
9147 (js2-node-add-children result
9148 (js2-infix-node-left result)
9149 (js2-infix-node-right result)))
9150 result)))
9151
9152 (defun js2-parse-attribute-access ()
9153 "Parse an E4X XML attribute expression.
9154 This includes expressions of the forms:
9155
9156 @attr @ns::attr @ns::*
9157 @* @*::attr @*::*
9158 @[expr] @*::[expr] @ns::[expr]
9159
9160 Called if we peeked an '@' token."
9161 (let ((tt (js2-next-token))
9162 (at-pos js2-token-beg))
9163 (cond
9164 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9165 ((js2-valid-prop-name-token tt)
9166 (js2-parse-property-name at-pos js2-ts-string 0))
9167 ;; handles: @*, @*::name, @*::*, @*::[expr]
9168 ((= tt js2-MUL)
9169 (js2-save-name-token-data js2-token-beg "*")
9170 (js2-parse-property-name js2-token-beg "*" 0))
9171 ;; handles @[expr]
9172 ((= tt js2-LB)
9173 (js2-parse-xml-elem-ref at-pos))
9174 (t
9175 (js2-report-error "msg.no.name.after.xmlAttr")
9176 ;; Avoid cascaded errors that happen if we make an error node here.
9177 (js2-save-name-token-data js2-token-beg "")
9178 (js2-parse-property-name js2-token-beg "" 0)))))
9179
9180 (defun js2-parse-property-name (at-pos s member-type-flags)
9181 "Check if :: follows name in which case it becomes qualified name.
9182
9183 AT-POS is a natural number if we just read an '@' token, else nil.
9184 S is the name or string that was matched: an identifier, 'throw' or '*'.
9185 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9186
9187 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9188 operator, or the name is followed by ::. For a plain name, returns a
9189 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9190 (let ((pos (or at-pos js2-token-beg))
9191 colon-pos
9192 (name (js2-create-name-node t js2-current-token))
9193 ns
9194 tt
9195 ref
9196 pn)
9197 (catch 'return
9198 (when (js2-match-token js2-COLONCOLON)
9199 (setq ns name
9200 colon-pos js2-token-beg
9201 tt (js2-next-token))
9202 (cond
9203 ;; handles name::name
9204 ((js2-valid-prop-name-token tt)
9205 (setq name (js2-create-name-node)))
9206 ;; handles name::*
9207 ((= tt js2-MUL)
9208 (js2-save-name-token-data js2-token-beg "*")
9209 (setq name (js2-create-name-node)))
9210 ;; handles name::[expr]
9211 ((= tt js2-LB)
9212 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9213 (t
9214 (js2-report-error "msg.no.name.after.coloncolon"))))
9215 (if (and (null ns) (zerop member-type-flags))
9216 name
9217 (prog1
9218 (setq pn
9219 (make-js2-xml-prop-ref-node :pos pos
9220 :len (- (js2-node-end name) pos)
9221 :at-pos at-pos
9222 :colon-pos colon-pos
9223 :propname name))
9224 (js2-node-add-children pn name))))))
9225
9226 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9227 "Parse the [expr] portion of an xml element reference.
9228 For instance, @[expr], @*::[expr], or ns::[expr]."
9229 (let* ((lb js2-token-beg)
9230 (pos (or at-pos lb))
9231 rb
9232 (expr (js2-parse-expr))
9233 (end (js2-node-end expr))
9234 pn)
9235 (if (js2-must-match js2-RB "msg.no.bracket.index")
9236 (setq rb js2-token-beg
9237 end js2-token-end))
9238 (prog1
9239 (setq pn
9240 (make-js2-xml-elem-ref-node :pos pos
9241 :len (- end pos)
9242 :namespace namespace
9243 :colon-pos colon-pos
9244 :at-pos at-pos
9245 :expr expr
9246 :lb (js2-relpos lb pos)
9247 :rb (js2-relpos rb pos)))
9248 (js2-node-add-children pn namespace expr))))
9249
9250 (defsubst js2-parse-primary-expr-lhs ()
9251 (let ((js2-is-in-lhs t))
9252 (js2-parse-primary-expr)))
9253
9254 (defun js2-parse-primary-expr ()
9255 "Parses a literal (leaf) expression of some sort.
9256 Includes complex literals such as functions, object-literals,
9257 array-literals, array comprehensions and regular expressions."
9258 (let ((tt-flagged (js2-next-flagged-token))
9259 pn ; parent node (usually return value)
9260 tt
9261 px-pos ; paren-expr pos
9262 len
9263 flags ; regexp flags
9264 expr)
9265 (setq tt js2-current-token)
9266 (cond
9267 ((= tt js2-FUNCTION)
9268 (js2-parse-function 'FUNCTION_EXPRESSION))
9269 ((= tt js2-LB)
9270 (js2-parse-array-literal))
9271 ((= tt js2-LC)
9272 (js2-parse-object-literal))
9273 ((= tt js2-LET)
9274 (js2-parse-let js2-token-beg))
9275 ((= tt js2-LP)
9276 (setq px-pos js2-token-beg
9277 expr (js2-parse-expr))
9278 (js2-must-match js2-RP "msg.no.paren")
9279 (setq pn (make-js2-paren-node :pos px-pos
9280 :expr expr
9281 :len (- js2-token-end px-pos)))
9282 (js2-node-add-children pn (js2-paren-node-expr pn))
9283 pn)
9284 ((= tt js2-XMLATTR)
9285 (js2-must-have-xml)
9286 (js2-parse-attribute-access))
9287 ((= tt js2-NAME)
9288 (js2-parse-name tt-flagged tt))
9289 ((= tt js2-NUMBER)
9290 (make-js2-number-node))
9291 ((= tt js2-STRING)
9292 (prog1
9293 (make-js2-string-node)
9294 (js2-record-face 'font-lock-string-face)))
9295 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9296 ;; Got / or /= which in this context means a regexp literal
9297 (setq px-pos js2-token-beg)
9298 (js2-read-regexp tt)
9299 (setq flags js2-ts-regexp-flags
9300 js2-ts-regexp-flags nil)
9301 (prog1
9302 (make-js2-regexp-node :pos px-pos
9303 :len (- js2-ts-cursor px-pos)
9304 :value js2-ts-string
9305 :flags flags)
9306 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9307 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9308 ((or (= tt js2-NULL)
9309 (= tt js2-THIS)
9310 (= tt js2-FALSE)
9311 (= tt js2-TRUE))
9312 (make-js2-keyword-node :type tt))
9313 ((= tt js2-RESERVED)
9314 (js2-report-error "msg.reserved.id")
9315 (make-js2-name-node))
9316 ((= tt js2-ERROR)
9317 ;; the scanner or one of its subroutines reported the error.
9318 (make-js2-error-node))
9319 ((= tt js2-EOF)
9320 (setq px-pos (point-at-bol)
9321 len (- js2-ts-cursor px-pos))
9322 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9323 (make-js2-error-node :pos px-pos :len len))
9324 (t
9325 (js2-report-error "msg.syntax")
9326 (make-js2-error-node)))))
9327
9328 (defun js2-parse-name (tt-flagged tt)
9329 (let ((name js2-ts-string)
9330 (name-pos js2-token-beg)
9331 node)
9332 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9333 (= (js2-peek-token) js2-COLON))
9334 (prog1
9335 ;; Do not consume colon, it is used as unwind indicator
9336 ;; to return to statementHelper.
9337 (make-js2-label-node :pos name-pos
9338 :len (- js2-token-end name-pos)
9339 :name name)
9340 (js2-set-face name-pos
9341 js2-token-end
9342 'font-lock-variable-name-face 'record))
9343 ;; Otherwise not a label, just a name. Unfortunately peeking
9344 ;; the next token to check for a colon has biffed js2-token-beg
9345 ;; and js2-token-end. We store the name's bounds in buffer vars
9346 ;; and `js2-create-name-node' uses them.
9347 (js2-save-name-token-data name-pos name)
9348 (setq node (if js2-compiler-xml-available
9349 (js2-parse-property-name nil name 0)
9350 (js2-create-name-node 'check-activation)))
9351 (if js2-highlight-external-variables
9352 (js2-record-name-node node))
9353 node)))
9354
9355 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9356 (js2-add-strict-warning
9357 msg nil
9358 ;; back up from comma to beginning of line or array/objlit
9359 (max (if elems
9360 (js2-node-pos (car elems))
9361 pos)
9362 (save-excursion
9363 (goto-char comma-pos)
9364 (back-to-indentation)
9365 (point)))
9366 comma-pos))
9367
9368 (defun js2-parse-array-literal ()
9369 (let ((pos js2-token-beg)
9370 (end js2-token-end)
9371 (after-lb-or-comma t)
9372 after-comma
9373 tt
9374 elems
9375 pn
9376 (continue t))
9377 (unless js2-is-in-lhs
9378 (js2-push-scope (make-js2-scope))) ; for array comp
9379 (while continue
9380 (setq tt (js2-peek-token))
9381 (cond
9382 ;; comma
9383 ((= tt js2-COMMA)
9384 (js2-consume-token)
9385 (setq after-comma js2-token-end)
9386 (if (not after-lb-or-comma)
9387 (setq after-lb-or-comma t)
9388 (push nil elems)))
9389 ;; end of array
9390 ((or (= tt js2-RB)
9391 (= tt js2-EOF)) ; prevent infinite loop
9392 (if (= tt js2-EOF)
9393 (js2-report-error "msg.no.bracket.arg" nil pos)
9394 (js2-consume-token))
9395 (setq continue nil
9396 end js2-token-end
9397 pn (make-js2-array-node :pos pos
9398 :len (- js2-ts-cursor pos)
9399 :elems (nreverse elems)))
9400 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9401 (when after-comma
9402 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9403 pos elems after-comma)))
9404 ;; destructuring binding
9405 (js2-is-in-lhs
9406 (push (if (or (= tt js2-LC)
9407 (= tt js2-LB)
9408 (= tt js2-NAME))
9409 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9410 (js2-parse-primary-expr-lhs)
9411 ;; invalid pattern
9412 (js2-consume-token)
9413 (js2-report-error "msg.bad.var")
9414 (make-js2-error-node))
9415 elems)
9416 (setq after-lb-or-comma nil
9417 after-comma nil))
9418 ;; array comp
9419 ((and (>= js2-language-version 170)
9420 (= tt js2-FOR) ; check for array comprehension
9421 (not after-lb-or-comma) ; "for" can't follow a comma
9422 elems ; must have at least 1 element
9423 (not (cdr elems))) ; but no 2nd element
9424 (setf continue nil
9425 pn (js2-parse-array-comprehension (car elems) pos)))
9426
9427 ;; another element
9428 (t
9429 (unless after-lb-or-comma
9430 (js2-report-error "msg.no.bracket.arg"))
9431 (push (js2-parse-assign-expr) elems)
9432 (setq after-lb-or-comma nil
9433 after-comma nil))))
9434 (unless js2-is-in-lhs
9435 (js2-pop-scope))
9436 pn))
9437
9438 (defun js2-parse-array-comprehension (expr pos)
9439 "Parse a JavaScript 1.7 Array Comprehension.
9440 EXPR is the first expression after the opening left-bracket.
9441 POS is the beginning of the LB token preceding EXPR.
9442 We should have just parsed the 'for' keyword before calling this function."
9443 (let (loops
9444 loop
9445 first
9446 prev
9447 filter
9448 if-pos
9449 result)
9450 (while (= (js2-peek-token) js2-FOR)
9451 (let ((prev (car loops))) ; rearrange scope chain
9452 (push (setq loop (js2-parse-array-comp-loop)) loops)
9453 (if prev ; each loop is parent scope to the next one
9454 (setf (js2-scope-parent-scope loop) prev)
9455 ; first loop takes expr scope's parent
9456 (setf (js2-scope-parent-scope (setq first loop))
9457 (js2-scope-parent-scope js2-current-scope)))))
9458 ;; set expr scope's parent to the last loop
9459 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9460 (when (= (js2-peek-token) js2-IF)
9461 (js2-consume-token)
9462 (setq if-pos (- js2-token-beg pos) ; relative
9463 filter (js2-parse-condition)))
9464 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9465 (setq result (make-js2-array-comp-node :pos pos
9466 :len (- js2-ts-cursor pos)
9467 :result expr
9468 :loops (nreverse loops)
9469 :filter (car filter)
9470 :lp (js2-relpos (second filter) pos)
9471 :rp (js2-relpos (third filter) pos)
9472 :if-pos if-pos))
9473 (apply #'js2-node-add-children result expr (car filter)
9474 (js2-array-comp-node-loops result))
9475 (setq js2-current-scope first) ; pop to the first loop
9476 result))
9477
9478 (defun js2-parse-array-comp-loop ()
9479 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9480 Last token peeked should be the initial FOR."
9481 (let ((pos js2-token-beg)
9482 (pn (make-js2-array-comp-loop-node))
9483 tt
9484 iter
9485 obj
9486 foreach-p
9487 in-pos
9488 each-pos
9489 lp
9490 rp)
9491 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9492 (js2-push-scope pn)
9493 (unwind-protect
9494 (progn
9495 (when (js2-match-token js2-NAME)
9496 (if (string= js2-ts-string "each")
9497 (progn
9498 (setq foreach-p t
9499 each-pos (- js2-token-beg pos)) ; relative
9500 (js2-record-face 'font-lock-keyword-face))
9501 (js2-report-error "msg.no.paren.for")))
9502 (if (js2-must-match js2-LP "msg.no.paren.for")
9503 (setq lp (- js2-token-beg pos)))
9504 (setq tt (js2-peek-token))
9505 (cond
9506 ((or (= tt js2-LB)
9507 (= tt js2-LC))
9508 ;; handle destructuring assignment
9509 (setq iter (js2-parse-primary-expr-lhs))
9510 (js2-define-destruct-symbols iter js2-LET
9511 'font-lock-variable-name-face t))
9512 ((js2-valid-prop-name-token tt)
9513 (js2-consume-token)
9514 (setq iter (js2-create-name-node)))
9515 (t
9516 (js2-report-error "msg.bad.var")))
9517 ;; Define as a let since we want the scope of the variable to
9518 ;; be restricted to the array comprehension
9519 (if (js2-name-node-p iter)
9520 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9521 (if (js2-must-match js2-IN "msg.in.after.for.name")
9522 (setq in-pos (- js2-token-beg pos)))
9523 (setq obj (js2-parse-expr))
9524 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9525 (setq rp (- js2-token-beg pos)))
9526 (setf (js2-node-pos pn) pos
9527 (js2-node-len pn) (- js2-ts-cursor pos)
9528 (js2-array-comp-loop-node-iterator pn) iter
9529 (js2-array-comp-loop-node-object pn) obj
9530 (js2-array-comp-loop-node-in-pos pn) in-pos
9531 (js2-array-comp-loop-node-each-pos pn) each-pos
9532 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9533 (js2-array-comp-loop-node-lp pn) lp
9534 (js2-array-comp-loop-node-rp pn) rp)
9535 (js2-node-add-children pn iter obj))
9536 (js2-pop-scope))
9537 pn))
9538
9539 (defun js2-parse-object-literal ()
9540 (let ((pos js2-token-beg)
9541 tt
9542 elems
9543 result
9544 after-comma
9545 (continue t))
9546 (while continue
9547 (setq tt (js2-peek-token))
9548 (cond
9549 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9550 ((or (js2-valid-prop-name-token tt)
9551 (= tt js2-STRING))
9552 (setq after-comma nil
9553 result (js2-parse-named-prop tt))
9554 (if (and (null result)
9555 (not js2-recover-from-parse-errors))
9556 (setq continue nil)
9557 (push result elems)))
9558 ;; {12: x} or {10.7: x}
9559 ((= tt js2-NUMBER)
9560 (js2-consume-token)
9561 (setq after-comma nil)
9562 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9563 ;; trailing comma
9564 ((= tt js2-RC)
9565 (setq continue nil)
9566 (if after-comma
9567 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9568 pos elems after-comma)))
9569 (t
9570 (js2-report-error "msg.bad.prop")
9571 (unless js2-recover-from-parse-errors
9572 (setq continue nil)))) ; end switch
9573 (if (js2-match-token js2-COMMA)
9574 (setq after-comma js2-token-end)
9575 (setq continue nil))) ; end loop
9576 (js2-must-match js2-RC "msg.no.brace.prop")
9577 (setq result (make-js2-object-node :pos pos
9578 :len (- js2-ts-cursor pos)
9579 :elems (nreverse elems)))
9580 (apply #'js2-node-add-children result (js2-object-node-elems result))
9581 result))
9582
9583 (defun js2-parse-named-prop (tt)
9584 "Parse a name, string, or getter/setter object property.
9585 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9586 (js2-consume-token)
9587 (let ((string-prop (and (= tt js2-STRING)
9588 (make-js2-string-node)))
9589 expr
9590 (ppos js2-token-beg)
9591 (pend js2-token-end)
9592 (name (js2-create-name-node))
9593 (prop js2-ts-string))
9594 (cond
9595 ;; getter/setter prop
9596 ((and (= tt js2-NAME)
9597 (= (js2-peek-token) js2-NAME)
9598 (or (string= prop "get")
9599 (string= prop "set")))
9600 (js2-consume-token)
9601 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9602 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9603 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9604 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9605 ;; abbreviated destructuring bind e.g., {a, b} = c;
9606 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9607 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9608 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9609 ;; assignment but it's difficult because it requires looking ahead of expression.
9610 ((and js2-is-in-lhs
9611 (= tt js2-NAME)
9612 (let ((ctk (js2-peek-token)))
9613 (or (= ctk js2-COMMA)
9614 (= ctk js2-RC)
9615 (js2-valid-prop-name-token ctk))))
9616 name)
9617 ;; regular prop
9618 (t
9619 (prog1
9620 (setq expr (js2-parse-plain-property (or string-prop name)))
9621 (js2-set-face ppos pend
9622 (if (js2-function-node-p
9623 (js2-object-prop-node-right expr))
9624 'font-lock-function-name-face
9625 'font-lock-variable-name-face)
9626 'record))))))
9627
9628 (defun js2-parse-plain-property (prop)
9629 "Parse a non-getter/setter property in an object literal.
9630 PROP is the node representing the property: a number, name or string."
9631 (js2-must-match js2-COLON "msg.no.colon.prop")
9632 (let* ((pos (js2-node-pos prop))
9633 (colon (- js2-token-beg pos))
9634 (expr (js2-parse-assign-expr))
9635 (result (make-js2-object-prop-node
9636 :pos pos
9637 ;; don't include last consumed token in length
9638 :len (- (+ (js2-node-pos expr)
9639 (js2-node-len expr))
9640 pos)
9641 :left prop
9642 :right expr
9643 :op-pos colon)))
9644 (js2-node-add-children result prop expr)
9645 result))
9646
9647 (defun js2-parse-getter-setter-prop (pos prop get-p)
9648 "Parse getter or setter property in an object literal.
9649 JavaScript syntax is:
9650
9651 { get foo() {...}, set foo(x) {...} }
9652
9653 and expression closure style is also supported
9654
9655 { get foo() x, set foo(x) _x = x }
9656
9657 POS is the start position of the `get' or `set' keyword.
9658 PROP is the `js2-name-node' representing the property name.
9659 GET-P is non-nil if the keyword was `get'."
9660 (let ((type (if get-p js2-GET js2-SET))
9661 result
9662 end
9663 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9664 ;; it has to be an anonymous function, as we already parsed the name
9665 (if (/= (js2-node-type fn) js2-FUNCTION)
9666 (js2-report-error "msg.bad.prop")
9667 (if (plusp (length (js2-function-name fn)))
9668 (js2-report-error "msg.bad.prop")))
9669 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9670 (setq end (js2-node-end fn)
9671 result (make-js2-getter-setter-node :type type
9672 :pos pos
9673 :len (- end pos)
9674 :left prop
9675 :right fn))
9676 (js2-node-add-children result prop fn)
9677 result))
9678
9679 (defun js2-create-name-node (&optional check-activation-p token)
9680 "Create a name node using the token info from last scanned name.
9681 In some cases we need to either synthesize a name node, or we lost
9682 the name token information by peeking. If the TOKEN parameter is
9683 not `js2-NAME', then we use the token info saved in instance vars."
9684 (let ((beg js2-token-beg)
9685 (s js2-ts-string)
9686 name)
9687 (when (/= js2-current-token js2-NAME)
9688 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9689 s js2-prev-name-token-string
9690 js2-prev-name-token-start nil
9691 js2-prev-name-token-string nil))
9692 (setq name (make-js2-name-node :pos beg
9693 :name s
9694 :len (length s)))
9695 (if check-activation-p
9696 (js2-check-activation-name s (or token js2-NAME)))
9697 name))
9698
9699 ;;; Indentation support
9700
9701 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9702 ;; Karl cleverly deduces that the desired indentation level is often a
9703 ;; function of paren/bracket/brace nesting depth, which can be determined
9704 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9705 ;; then does some equally clever checks to see if we're in the context of a
9706 ;; substatement of a possibly braceless statement keyword such as if, while,
9707 ;; or finally. This approach yields pretty good results.
9708
9709 ;; The indenter is often "wrong", however, and needs to be overridden.
9710 ;; The right long-term solution is probably to emulate (or integrate
9711 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9712 ;; parse tree from `js2-parse' is present, which is not true at the
9713 ;; moment the user is typing, computing indentation is still thousands
9714 ;; of lines of code to handle every possible syntactic edge case.
9715
9716 ;; In the meantime, the compromise solution is that we offer a "bounce
9717 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9718 ;; current line indent among various likely guess points. This approach
9719 ;; is far from perfect, but should at least make it slightly easier to
9720 ;; move the line towards its desired indentation when manually
9721 ;; overriding Karl's heuristic nesting guesser.
9722
9723 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9724 ;; extensions such as `let' and Array comprehensions. Major kudos to
9725 ;; Karl for coming up with the initial approach, which packs a lot of
9726 ;; punch for so little code.
9727
9728 (defconst js-possibly-braceless-keyword-re
9729 (regexp-opt
9730 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9731 'words)
9732 "Regular expression matching keywords that are optionally
9733 followed by an opening brace.")
9734
9735 (defconst js-possibly-braceless-keywords-re
9736 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9737 "Regular expression which matches the keywords which are consist of more than 2 words
9738 like 'if else' and 'for each', and optionally followed by an opening brace.")
9739
9740 (defconst js-indent-operator-re
9741 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9742 (regexp-opt '("in" "instanceof") 'words))
9743 "Regular expression matching operators that affect indentation
9744 of continued expressions.")
9745
9746 ;; This function has horrible results if you're typing an array
9747 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9748 ;; in conjunction with electric-indent, so just disabling it.
9749 (defsubst js2-code-at-bol-p ()
9750 "Return t if the first character on line is non-whitespace."
9751 nil)
9752
9753 (defun js2-insert-and-indent (key)
9754 "Run command bound to key and indent current line. Runs the command
9755 bound to KEY in the global keymap and indents the current line."
9756 (interactive (list (this-command-keys)))
9757 (let ((cmd (lookup-key (current-global-map) key)))
9758 (if (commandp cmd)
9759 (call-interactively cmd)))
9760 ;; don't do the electric keys inside comments or strings,
9761 ;; and don't do bounce-indent with them.
9762 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9763 (js2-bounce-indent-p (js2-code-at-bol-p)))
9764 (unless (or (nth 3 parse-state)
9765 (nth 4 parse-state))
9766 (indent-according-to-mode))))
9767
9768 (defun js-re-search-forward-inner (regexp &optional bound count)
9769 "Auxiliary function for `js-re-search-forward'."
9770 (let ((parse)
9771 (saved-point (point-min)))
9772 (while (> count 0)
9773 (re-search-forward regexp bound)
9774 (setq parse (parse-partial-sexp saved-point (point)))
9775 (cond ((nth 3 parse)
9776 (re-search-forward
9777 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9778 (save-excursion (end-of-line) (point)) t))
9779 ((nth 7 parse)
9780 (forward-line))
9781 ((or (nth 4 parse)
9782 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9783 (re-search-forward "\\*/"))
9784 (t
9785 (setq count (1- count))))
9786 (setq saved-point (point))))
9787 (point))
9788
9789 (defun js-re-search-forward (regexp &optional bound noerror count)
9790 "Search forward but ignore strings and comments. Invokes
9791 `re-search-forward' but treats the buffer as if strings and
9792 comments have been removed."
9793 (let ((saved-point (point))
9794 (search-expr
9795 (cond ((null count)
9796 '(js-re-search-forward-inner regexp bound 1))
9797 ((< count 0)
9798 '(js-re-search-backward-inner regexp bound (- count)))
9799 ((> count 0)
9800 '(js-re-search-forward-inner regexp bound count)))))
9801 (condition-case err
9802 (eval search-expr)
9803 (search-failed
9804 (goto-char saved-point)
9805 (unless noerror
9806 (error (error-message-string err)))))))
9807
9808 (defun js-re-search-backward-inner (regexp &optional bound count)
9809 "Auxiliary function for `js-re-search-backward'."
9810 (let ((parse)
9811 (saved-point (point-min)))
9812 (while (> count 0)
9813 (re-search-backward regexp bound)
9814 (setq parse (parse-partial-sexp saved-point (point)))
9815 (cond ((nth 3 parse)
9816 (re-search-backward
9817 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9818 (save-excursion (beginning-of-line) (point)) t))
9819 ((nth 7 parse)
9820 (goto-char (nth 8 parse)))
9821 ((or (nth 4 parse)
9822 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9823 (re-search-backward "/\\*"))
9824 (t
9825 (setq count (1- count))))))
9826 (point))
9827
9828 (defun js-re-search-backward (regexp &optional bound noerror count)
9829 "Search backward but ignore strings and comments. Invokes
9830 `re-search-backward' but treats the buffer as if strings and
9831 comments have been removed."
9832 (let ((saved-point (point))
9833 (search-expr
9834 (cond ((null count)
9835 '(js-re-search-backward-inner regexp bound 1))
9836 ((< count 0)
9837 '(js-re-search-forward-inner regexp bound (- count)))
9838 ((> count 0)
9839 '(js-re-search-backward-inner regexp bound count)))))
9840 (condition-case err
9841 (eval search-expr)
9842 (search-failed
9843 (goto-char saved-point)
9844 (unless noerror
9845 (error (error-message-string err)))))))
9846
9847 (defun js-looking-at-operator-p ()
9848 "Return non-nil if text after point is an operator (that is not
9849 a comma)."
9850 (save-match-data
9851 (and (looking-at js-indent-operator-re)
9852 (or (not (looking-at ":"))
9853 (save-excursion
9854 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9855 (looking-at "?")))))))
9856
9857 (defun js-continued-expression-p ()
9858 "Returns non-nil if the current line continues an expression."
9859 (save-excursion
9860 (back-to-indentation)
9861 (or (js-looking-at-operator-p)
9862 ;; comment
9863 (and (js-re-search-backward "\n" nil t)
9864 (progn
9865 (skip-chars-backward " \t")
9866 (backward-char)
9867 (and (js-looking-at-operator-p)
9868 (and (progn (backward-char)
9869 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9870
9871 (defun js-end-of-do-while-loop-p ()
9872 "Returns non-nil if word after point is `while' of a do-while
9873 statement, else returns nil. A braceless do-while statement
9874 spanning several lines requires that the start of the loop is
9875 indented to the same column as the current line."
9876 (interactive)
9877 (save-excursion
9878 (save-match-data
9879 (when (looking-at "\\s-*\\<while\\>")
9880 (if (save-excursion
9881 (skip-chars-backward "[ \t\n]*}")
9882 (looking-at "[ \t\n]*}"))
9883 (save-excursion
9884 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9885 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9886 (or (looking-at "\\<do\\>")
9887 (let ((saved-indent (current-indentation)))
9888 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9889 (/= (current-indentation) saved-indent)))
9890 (and (looking-at "[ \t]*\\<do\\>")
9891 (not (js-re-search-forward
9892 "\\<while\\>" (point-at-eol) t))
9893 (= (current-indentation) saved-indent)))))))))
9894
9895 (defun js-get-multiline-declaration-offset ()
9896 "Returns offset (> 0) if the current line is part of
9897 multi-line variable declaration like below example, and
9898 returns 0 otherwise.
9899
9900 var a = 10,
9901 b = 20,
9902 c = 30;
9903
9904 "
9905 (let* ((node (js2-node-at-point))
9906 (pnode (and node (js2-node-parent node)))
9907 (pnode-type (and pnode (js2-node-type pnode))))
9908 (if (and node
9909 (= js2-NAME (js2-node-type node))
9910 (or
9911 (= js2-VAR pnode-type)
9912 (= js2-LET pnode-type)
9913 (= js2-CONST pnode-type)))
9914 (if (= js2-CONST pnode-type)
9915 6
9916 4)
9917 0)))
9918
9919 (defun js-ctrl-statement-indentation ()
9920 "Returns the proper indentation of the current line if it
9921 starts the body of a control statement without braces, else
9922 returns nil."
9923 (let (forward-sexp-function) ; temporarily unbind it
9924 (save-excursion
9925 (back-to-indentation)
9926 (when (save-excursion
9927 (and (not (js2-same-line (point-min)))
9928 (not (looking-at "{"))
9929 (js-re-search-backward "[[:graph:]]" nil t)
9930 (not (looking-at "[{([]"))
9931 (progn
9932 (forward-char)
9933 ;; scan-sexps sometimes throws an error
9934 (ignore-errors (backward-sexp))
9935 (when (looking-at "(") (backward-word 1))
9936 (and (save-excursion
9937 (skip-chars-backward " \t}" (point-at-bol))
9938 (or (bolp)
9939 (and (backward-word 1)
9940 (skip-chars-backward " \t}" (point-at-bol))
9941 (bolp)
9942 (looking-at js-possibly-braceless-keywords-re))))
9943 (looking-at js-possibly-braceless-keyword-re)
9944 (not (js-end-of-do-while-loop-p))))))
9945 (save-excursion
9946 (goto-char (match-beginning 0))
9947 (+ (current-indentation) js2-basic-offset))))))
9948
9949 (defun js2-indent-in-array-comp (parse-status)
9950 "Return non-nil if we think we're in an array comprehension.
9951 In particular, return the buffer position of the first `for' kwd."
9952 (let ((end (point)))
9953 (when (nth 1 parse-status)
9954 (save-excursion
9955 (goto-char (nth 1 parse-status))
9956 (when (looking-at "\\[")
9957 (forward-char 1)
9958 (js2-forward-sws)
9959 (if (looking-at "[[{]")
9960 (let (forward-sexp-function) ; use lisp version
9961 (forward-sexp) ; skip destructuring form
9962 (js2-forward-sws)
9963 (if (and (/= (char-after) ?,) ; regular array
9964 (looking-at "for"))
9965 (match-beginning 0)))
9966 ;; to skip arbitrary expressions we need the parser,
9967 ;; so we'll just guess at it.
9968 (if (re-search-forward "[^,]* \\(for\\) " end t)
9969 (match-beginning 1))))))))
9970
9971 (defun js2-array-comp-indentation (parse-status for-kwd)
9972 (if (js2-same-line for-kwd)
9973 ;; first continuation line
9974 (save-excursion
9975 (goto-char (nth 1 parse-status))
9976 (forward-char 1)
9977 (skip-chars-forward " \t")
9978 (current-column))
9979 (save-excursion
9980 (goto-char for-kwd)
9981 (current-column))))
9982
9983 (defun js-proper-indentation (parse-status)
9984 "Return the proper indentation for the current line."
9985 (save-excursion
9986 (back-to-indentation)
9987 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9988 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9989 (continued-expr-p (js-continued-expression-p))
9990 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9991 (js-get-multiline-declaration-offset))
9992 0))
9993 (bracket (nth 1 parse-status))
9994 beg)
9995 (cond
9996 ;; indent array comprehension continuation lines specially
9997 ((and bracket
9998 (not (js2-same-line bracket))
9999 (setq beg (js2-indent-in-array-comp parse-status))
10000 (>= (point) (save-excursion
10001 (goto-char beg)
10002 (point-at-bol)))) ; at or after first loop?
10003 (js2-array-comp-indentation parse-status beg))
10004
10005 (ctrl-stmt-indent)
10006
10007 (bracket
10008 (goto-char bracket)
10009 (cond
10010 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10011 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10012 (when (save-excursion (skip-chars-backward " \t)")
10013 (looking-at ")"))
10014 (backward-list))
10015 (if (and (nth 1 p)
10016 (not js2-consistent-level-indent-inner-bracket-p))
10017 (progn (goto-char (1+ (nth 1 p)))
10018 (skip-chars-forward " \t"))
10019 (back-to-indentation))
10020 (cond (same-indent-p
10021 (current-column))
10022 (continued-expr-p
10023 (+ (current-column) (* 2 js2-basic-offset)))
10024 ((> multiline-declaration-offset 0)
10025 (+ (current-column) js2-basic-offset multiline-declaration-offset))
10026 (t
10027 (+ (current-column) js2-basic-offset)))))
10028 (t
10029 (unless same-indent-p
10030 (forward-char)
10031 (skip-chars-forward " \t"))
10032 (current-column))))
10033
10034 (continued-expr-p js2-basic-offset)
10035
10036 ((> multiline-declaration-offset 0)
10037 (+ multiline-declaration-offset))
10038
10039 (t 0)))))
10040
10041 (defun js2-lineup-comment (parse-status)
10042 "Indent a multi-line block comment continuation line."
10043 (let* ((beg (nth 8 parse-status))
10044 (first-line (js2-same-line beg))
10045 (offset (save-excursion
10046 (goto-char beg)
10047 (if (looking-at "/\\*")
10048 (+ 1 (current-column))
10049 0))))
10050 (unless first-line
10051 (indent-line-to offset))))
10052
10053 (defun js2-backward-sws ()
10054 "Move backward through whitespace and comments."
10055 (interactive)
10056 (while (forward-comment -1)))
10057
10058 (defun js2-forward-sws ()
10059 "Move forward through whitespace and comments."
10060 (interactive)
10061 (while (forward-comment 1)))
10062
10063 (defsubst js2-current-indent (&optional pos)
10064 "Return column of indentation on current line.
10065 If POS is non-nil, go to that point and return indentation for that line."
10066 (save-excursion
10067 (if pos
10068 (goto-char pos))
10069 (back-to-indentation)
10070 (current-column)))
10071
10072 (defsubst js2-arglist-close ()
10073 "Return non-nil if we're on a line beginning with a close-paren/brace."
10074 (save-match-data
10075 (save-excursion
10076 (goto-char (point-at-bol))
10077 (js2-forward-sws)
10078 (looking-at "[])}]"))))
10079
10080 (defsubst js2-indent-looks-like-label-p ()
10081 (goto-char (point-at-bol))
10082 (js2-forward-sws)
10083 (looking-at (concat js2-mode-identifier-re ":")))
10084
10085 (defun js2-indent-in-objlit-p (parse-status)
10086 "Return non-nil if this looks like an object-literal entry."
10087 (let ((start (nth 1 parse-status)))
10088 (and
10089 start
10090 (save-excursion
10091 (and (zerop (forward-line -1))
10092 (not (< (point) start)) ; crossed a {} boundary
10093 (js2-indent-looks-like-label-p)))
10094 (save-excursion
10095 (js2-indent-looks-like-label-p)))))
10096
10097 ;; if prev line looks like foobar({ then we're passing an object
10098 ;; literal to a function call, and people pretty much always want to
10099 ;; de-dent back to the previous line, so move the 'basic-offset'
10100 ;; position to the front.
10101 (defsubst js2-indent-objlit-arg-p (parse-status)
10102 (save-excursion
10103 (back-to-indentation)
10104 (js2-backward-sws)
10105 (and (eq (1- (point)) (nth 1 parse-status))
10106 (eq (char-before) ?{)
10107 (progn
10108 (forward-char -1)
10109 (skip-chars-backward " \t")
10110 (eq (char-before) ?\()))))
10111
10112 (defsubst js2-indent-case-block-p ()
10113 (save-excursion
10114 (back-to-indentation)
10115 (js2-backward-sws)
10116 (goto-char (point-at-bol))
10117 (skip-chars-forward " \t")
10118 (save-match-data
10119 (looking-at "case\\s-.+:"))))
10120
10121 (defsubst js2-syntax-bol ()
10122 "Return the point at the first non-whitespace char on the line.
10123 Returns `point-at-bol' if the line is empty."
10124 (save-excursion
10125 (beginning-of-line)
10126 (skip-chars-forward " \t")
10127 (point)))
10128
10129 (defun js2-bounce-indent (normal-col parse-status backwards)
10130 "Cycle among alternate computed indentation positions.
10131 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10132 of the buffer to the current point. NORMAL-COL is the indentation
10133 column computed by the heuristic guesser based on current paren,
10134 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10135 in reverse."
10136 (let ((cur-indent (js2-current-indent))
10137 (old-buffer-undo-list buffer-undo-list)
10138 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10139 (current-line (save-excursion
10140 (forward-line 0) ; move to bol
10141 (1+ (count-lines (point-min) (point)))))
10142 positions
10143 pos
10144 main-pos
10145 anchor
10146 arglist-cont
10147 same-indent
10148 prev-line-col
10149 basic-offset
10150 computed-pos)
10151 ;; temporarily don't record undo info, if user requested this
10152 (if js2-mode-indent-inhibit-undo
10153 (setq buffer-undo-list t))
10154 (unwind-protect
10155 (progn
10156 ;; first likely point: indent from beginning of previous code line
10157 (push (setq basic-offset
10158 (+ (save-excursion
10159 (back-to-indentation)
10160 (js2-backward-sws)
10161 (back-to-indentation)
10162 (setq prev-line-col (current-column)))
10163 js2-basic-offset))
10164 positions)
10165
10166 ;; (first + epsilon) likely point: indent 2x from beginning of
10167 ;; previous code line. Some companies like this approach. Ahem.
10168 ;; Seriously, though -- 4-space indent for expression continuation
10169 ;; lines isn't a bad idea. We should eventually implement it
10170 ;; that way.
10171 (push (setq basic-offset
10172 (+ (save-excursion
10173 (back-to-indentation)
10174 (js2-backward-sws)
10175 (back-to-indentation)
10176 (setq prev-line-col (current-column)))
10177 (* 2 js2-basic-offset)))
10178 positions)
10179
10180 ;; second likely point: indent from assign-expr RHS. This
10181 ;; is just a crude guess based on finding " = " on the previous
10182 ;; line containing actual code.
10183 (setq pos (save-excursion
10184 (save-match-data
10185 (forward-line -1)
10186 (goto-char (point-at-bol))
10187 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10188 (point-at-eol) t)
10189 (goto-char (match-end 1))
10190 (skip-chars-forward " \t\r\n")
10191 (current-column)))))
10192 (when pos
10193 (incf pos js2-basic-offset)
10194 (push pos positions))
10195
10196 ;; third likely point: same indent as previous line of code.
10197 ;; Make it the first likely point if we're not on an
10198 ;; arglist-close line and previous line ends in a comma, or
10199 ;; both this line and prev line look like object-literal
10200 ;; elements.
10201 (setq pos (save-excursion
10202 (goto-char (point-at-bol))
10203 (js2-backward-sws)
10204 (back-to-indentation)
10205 (prog1
10206 (current-column)
10207 ;; while we're here, look for trailing comma
10208 (if (save-excursion
10209 (goto-char (point-at-eol))
10210 (js2-backward-sws)
10211 (eq (char-before) ?,))
10212 (setq arglist-cont (1- (point)))))))
10213 (when pos
10214 (if (and (or arglist-cont
10215 (js2-indent-in-objlit-p parse-status))
10216 (not (js2-arglist-close)))
10217 (setq same-indent pos))
10218 (push pos positions))
10219
10220 ;; fourth likely point: first preceding code with less indentation
10221 ;; than the immediately preceding code line.
10222 (setq pos (save-excursion
10223 (back-to-indentation)
10224 (js2-backward-sws)
10225 (back-to-indentation)
10226 (setq anchor (current-column))
10227 (while (and (zerop (forward-line -1))
10228 (>= (progn
10229 (back-to-indentation)
10230 (current-column))
10231 anchor)))
10232 (setq pos (current-column))))
10233 (push pos positions)
10234
10235 ;; nesting-heuristic position, main by default
10236 (push (setq main-pos normal-col) positions)
10237
10238 ;; delete duplicates and sort positions list
10239 (setq positions (sort (delete-dups positions) '<))
10240
10241 ;; comma-list continuation lines: prev line indent takes precedence
10242 (if same-indent
10243 (setq main-pos same-indent))
10244
10245 ;; common special cases where we want to indent in from previous line
10246 (if (or (js2-indent-case-block-p)
10247 (js2-indent-objlit-arg-p parse-status))
10248 (setq main-pos basic-offset))
10249
10250 ;; if bouncing backwards, reverse positions list
10251 (if backwards
10252 (setq positions (reverse positions)))
10253
10254 ;; record whether we're already sitting on one of the alternatives
10255 (setq pos (member cur-indent positions))
10256
10257 (cond
10258 ;; case 0: we're one one of the alternatives and this is the
10259 ;; first time they've pressed TAB on this line (best-guess).
10260 ((and js2-mode-indent-ignore-first-tab
10261 pos
10262 ;; first time pressing TAB on this line?
10263 (not (eq js2-mode-last-indented-line current-line)))
10264 ;; do nothing
10265 (setq computed-pos nil))
10266 ;; case 1: only one computed position => use it
10267 ((null (cdr positions))
10268 (setq computed-pos 0))
10269 ;; case 2: not on any of the computed spots => use main spot
10270 ((not pos)
10271 (setq computed-pos (js2-position main-pos positions)))
10272 ;; case 3: on last position: cycle to first position
10273 ((null (cdr pos))
10274 (setq computed-pos 0))
10275 ;; case 4: on intermediate position: cycle to next position
10276 (t
10277 (setq computed-pos (js2-position (second pos) positions))))
10278
10279 ;; see if any hooks want to indent; otherwise we do it
10280 (loop with result = nil
10281 for hook in js2-indent-hook
10282 while (null result)
10283 do
10284 (setq result (funcall hook positions computed-pos))
10285 finally do
10286 (unless (or result (null computed-pos))
10287 (indent-line-to (nth computed-pos positions)))))
10288
10289 ;; finally
10290 (if js2-mode-indent-inhibit-undo
10291 (setq buffer-undo-list old-buffer-undo-list))
10292 ;; see commentary for `js2-mode-last-indented-line'
10293 (setq js2-mode-last-indented-line current-line))))
10294
10295 (defun js2-indent-bounce-backwards ()
10296 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10297 cycles between the computed indentation positions in reverse order."
10298 (interactive)
10299 (js2-indent-line t))
10300
10301 (defsubst js2-1-line-comment-continuation-p ()
10302 "Return t if we're in a 1-line comment continuation.
10303 If so, we don't ever want to use bounce-indent."
10304 (save-excursion
10305 (save-match-data
10306 (and (progn
10307 (forward-line 0)
10308 (looking-at "\\s-*//"))
10309 (progn
10310 (forward-line -1)
10311 (forward-line 0)
10312 (when (looking-at "\\s-*$")
10313 (js2-backward-sws)
10314 (forward-line 0))
10315 (looking-at "\\s-*//"))))))
10316
10317 (defun js2-indent-line (&optional bounce-backwards)
10318 "Indent the current line as JavaScript source text."
10319 (interactive)
10320 (when js2-use-ast-for-indentation-p
10321 (js2-reparse))
10322 (let (parse-status
10323 current-indent
10324 offset
10325 indent-col
10326 moved
10327 ;; don't whine about errors/warnings when we're indenting.
10328 ;; This has to be set before calling parse-partial-sexp below.
10329 (inhibit-point-motion-hooks t))
10330 (setq parse-status (save-excursion
10331 (parse-partial-sexp (point-min)
10332 (point-at-bol)))
10333 offset (- (point) (save-excursion
10334 (back-to-indentation)
10335 (setq current-indent (current-column))
10336 (point))))
10337 (js2-with-underscore-as-word-syntax
10338 (if (nth 4 parse-status)
10339 (js2-lineup-comment parse-status)
10340 (setq indent-col (js-proper-indentation parse-status))
10341 ;; see comments below about js2-mode-last-indented-line
10342 (when
10343 (cond
10344 ;; bounce-indenting is disabled during electric-key indent.
10345 ;; It doesn't work well on first line of buffer.
10346 ((and js2-bounce-indent-p
10347 (not (js2-same-line (point-min)))
10348 (not (js2-1-line-comment-continuation-p)))
10349 (js2-bounce-indent indent-col parse-status bounce-backwards)
10350 (setq moved t))
10351 ;; just indent to the guesser's likely spot
10352 ((/= current-indent indent-col)
10353 (indent-line-to indent-col)
10354 (setq moved t)))
10355 (when (and moved (plusp offset))
10356 (forward-char offset)))))))
10357
10358 (defun js2-indent-region (start end)
10359 "Indent the region, but don't use bounce indenting."
10360 (let ((js2-bounce-indent-p nil)
10361 (indent-region-function nil))
10362 (indent-region start end nil))) ; nil for byte-compiler
10363
10364 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10365
10366 ;;;###autoload
10367 (defun js2-mode ()
10368 "Major mode for editing JavaScript code."
10369 (interactive)
10370 (kill-all-local-variables)
10371 (set-syntax-table js2-mode-syntax-table)
10372 (use-local-map js2-mode-map)
10373 (make-local-variable 'comment-start)
10374 (make-local-variable 'comment-end)
10375 (make-local-variable 'comment-start-skip)
10376 (setq major-mode 'js2-mode
10377 mode-name "JavaScript-IDE"
10378 comment-start "//" ; used by comment-region; don't change it
10379 comment-end "")
10380 (setq local-abbrev-table js2-mode-abbrev-table)
10381 (set (make-local-variable 'max-lisp-eval-depth)
10382 (max max-lisp-eval-depth 3000))
10383 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10384 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10385
10386 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10387 ;; on most platforms other than the one I originally wrote it on. So it's
10388 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10389 ;; with our binding of the RET key inside comments: short lines stay short.
10390 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10391
10392 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10393 (set (make-local-variable 'next-error-function) #'js2-next-error)
10394 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10395 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10396 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10397 ;; for characters inside regexp literals.
10398 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10399 ;; this is necessary to make `show-paren-function' work properly
10400 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10401 ;; needed for M-x rgrep, among other things
10402 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10403
10404 ;; some variables needed by cc-engine for paragraph-fill, etc.
10405 (setq c-buffer-is-cc-mode t
10406 c-comment-prefix-regexp js2-comment-prefix-regexp
10407 c-comment-start-regexp "/[*/]\\|\\s|"
10408 c-paragraph-start js2-paragraph-start
10409 c-paragraph-separate "$"
10410 comment-start-skip js2-comment-start-skip
10411 c-syntactic-ws-start js2-syntactic-ws-start
10412 c-syntactic-ws-end js2-syntactic-ws-end
10413 c-syntactic-eol js2-syntactic-eol)
10414
10415 (setq js2-default-externs
10416 (append js2-ecma-262-externs
10417 (if js2-include-browser-externs
10418 js2-browser-externs)
10419 (if js2-include-gears-externs
10420 js2-gears-externs)
10421 (if js2-include-rhino-externs
10422 js2-rhino-externs)))
10423
10424 ;; We do our own syntax highlighting based on the parse tree.
10425 ;; However, we want minor modes that add keywords to highlight properly
10426 ;; (examples: doxymacs, column-marker). We do this by not letting
10427 ;; font-lock unfontify anything, and telling it to fontify after we
10428 ;; re-parse and re-highlight the buffer. (We currently don't do any
10429 ;; work with regions other than the whole buffer.)
10430 (dolist (var '(font-lock-unfontify-buffer-function
10431 font-lock-unfontify-region-function))
10432 (set (make-local-variable var) (lambda (&rest args) t)))
10433
10434 ;; Don't let font-lock do syntactic (string/comment) fontification.
10435 (set (make-local-variable #'font-lock-syntactic-face-function)
10436 (lambda (state) nil))
10437
10438 ;; Experiment: make reparse-delay longer for longer files.
10439 (if (plusp js2-dynamic-idle-timer-adjust)
10440 (setq js2-idle-timer-delay
10441 (* js2-idle-timer-delay
10442 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10443
10444 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10445 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10446 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10447 (imenu-add-to-menubar (concat "IM-" mode-name))
10448 (when js2-mirror-mode
10449 (js2-enter-mirror-mode))
10450 (add-to-invisibility-spec '(js2-outline . t))
10451 (set (make-local-variable 'line-move-ignore-invisible) t)
10452 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10453 (setq js2-mode-functions-hidden nil
10454 js2-mode-comments-hidden nil
10455 js2-mode-buffer-dirty-p t
10456 js2-mode-parsing nil)
10457 (js2-reparse)
10458
10459 (if (fboundp 'run-mode-hooks)
10460 (run-mode-hooks 'js2-mode-hook)
10461 (run-hooks 'js2-mode-hook)))
10462
10463 (defun js2-mode-exit ()
10464 "Exit `js2-mode' and clean up."
10465 (interactive)
10466 (when js2-mode-node-overlay
10467 (delete-overlay js2-mode-node-overlay)
10468 (setq js2-mode-node-overlay nil))
10469 (js2-remove-overlays)
10470 (setq js2-mode-ast nil)
10471 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10472 (remove-from-invisibility-spec '(js2-outline . t))
10473 (js2-mode-show-all)
10474 (js2-with-unmodifying-text-property-changes
10475 (js2-clear-face (point-min) (point-max))))
10476
10477 (defun js2-before-save ()
10478 "Clean up whitespace before saving file.
10479 You can disable this by customizing `js2-cleanup-whitespace'."
10480 (when js2-cleanup-whitespace
10481 (let ((col (current-column)))
10482 (delete-trailing-whitespace)
10483 ;; don't change trailing whitespace on current line
10484 (unless (eq (current-column) col)
10485 (indent-to col)))))
10486
10487 (defsubst js2-mode-reset-timer ()
10488 "Cancel any existing parse timer and schedule a new one."
10489 (if js2-mode-parse-timer
10490 (cancel-timer js2-mode-parse-timer))
10491 (setq js2-mode-parsing nil)
10492 (setq js2-mode-parse-timer
10493 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10494
10495 (defun js2-mode-edit (beg end len)
10496 "Schedule a new parse after buffer is edited.
10497 Buffer edit spans from BEG to END and is of length LEN.
10498 Also clears the `js2-magic' bit on autoinserted parens/brackets
10499 if the edit occurred on a line different from the magic paren."
10500 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10501 (line (if magic-pos (line-number-at-pos magic-pos))))
10502 (and line
10503 (or (/= (line-number-at-pos beg) line)
10504 (and (> 0 len)
10505 (/= (line-number-at-pos end) line)))
10506 (js2-mode-mundanify-parens)))
10507 (setq js2-mode-buffer-dirty-p t)
10508 (js2-mode-hide-overlay)
10509 (js2-mode-reset-timer))
10510
10511 (defun js2-mode-run-font-lock ()
10512 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10513 This is intended to allow modes that install their own font-lock keywords
10514 to work with js2-mode. In practice it never seems to work for long.
10515 Hopefully the Emacs maintainers can help figure out a way to make it work."
10516 (when (and (boundp 'font-lock-keywords)
10517 font-lock-keywords
10518 (boundp 'font-lock-mode)
10519 font-lock-mode)
10520 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10521 ;; play nicely with js2-mode. They go out of their way to fail to
10522 ;; provide any option for saying "look, fontify the farging buffer
10523 ;; with just the keywords already". Argh.
10524 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10525 (let (font-lock-verbose)
10526 (font-lock-fontify-buffer))))
10527
10528 (defun js2-reparse (&optional force)
10529 "Re-parse current buffer after user finishes some data entry.
10530 If we get any user input while parsing, including cursor motion,
10531 we discard the parse and reschedule it. If FORCE is nil, then the
10532 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10533 (let (time
10534 interrupted-p
10535 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10536 (unless js2-mode-parsing
10537 (setq js2-mode-parsing t)
10538 (unwind-protect
10539 (when (or js2-mode-buffer-dirty-p force)
10540 (js2-remove-overlays)
10541 (js2-with-unmodifying-text-property-changes
10542 (setq js2-mode-buffer-dirty-p nil
10543 js2-mode-fontifications nil
10544 js2-mode-deferred-properties nil
10545 js2-additional-externs nil)
10546 (if js2-mode-verbose-parse-p
10547 (message "parsing..."))
10548 (setq time
10549 (js2-time
10550 (setq interrupted-p
10551 (catch 'interrupted
10552 (setq js2-mode-ast (js2-parse))
10553 ;; if parsing is interrupted, comments and regex
10554 ;; literals stay ignored by `parse-partial-sexp'
10555 (remove-text-properties (point-min) (point-max)
10556 '(syntax-table))
10557 (js2-mode-apply-deferred-properties)
10558 (js2-mode-remove-suppressed-warnings)
10559 (js2-mode-show-warnings)
10560 (js2-mode-show-errors)
10561 (js2-mode-run-font-lock) ; note: doesn't work
10562 (js2-mode-highlight-magic-parens)
10563 (if (>= js2-highlight-level 1)
10564 (js2-highlight-jsdoc js2-mode-ast))
10565 nil))))
10566 (if interrupted-p
10567 (progn
10568 ;; unfinished parse => try again
10569 (setq js2-mode-buffer-dirty-p t)
10570 (js2-mode-reset-timer))
10571 (if js2-mode-verbose-parse-p
10572 (message "Parse time: %s" time)))))
10573 (setq js2-mode-parsing nil)
10574 (unless interrupted-p
10575 (setq js2-mode-parse-timer nil))))))
10576
10577 (defun js2-mode-show-node ()
10578 "Debugging aid: highlight selected AST node on mouse click."
10579 (interactive)
10580 (let ((node (js2-node-at-point))
10581 beg
10582 end)
10583 (when js2-mode-show-overlay
10584 (if (null node)
10585 (message "No node found at location %s" (point))
10586 (setq beg (js2-node-abs-pos node)
10587 end (+ beg (js2-node-len node)))
10588 (if js2-mode-node-overlay
10589 (move-overlay js2-mode-node-overlay beg end)
10590 (setq js2-mode-node-overlay (make-overlay beg end))
10591 (overlay-put js2-mode-node-overlay 'face 'highlight))
10592 (js2-with-unmodifying-text-property-changes
10593 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10594 (message "%s, parent: %s"
10595 (js2-node-short-name node)
10596 (if (js2-node-parent node)
10597 (js2-node-short-name (js2-node-parent node))
10598 "nil"))))))
10599
10600 (defun js2-mode-hide-overlay (&optional p1 p2)
10601 "Remove the debugging overlay when the point moves.
10602 P1 and P2 are the old and new values of point, respectively."
10603 (when js2-mode-node-overlay
10604 (let ((beg (overlay-start js2-mode-node-overlay))
10605 (end (overlay-end js2-mode-node-overlay)))
10606 ;; Sometimes we're called spuriously.
10607 (unless (and p2
10608 (>= p2 beg)
10609 (<= p2 end))
10610 (js2-with-unmodifying-text-property-changes
10611 (remove-text-properties beg end '(point-left nil)))
10612 (delete-overlay js2-mode-node-overlay)
10613 (setq js2-mode-node-overlay nil)))))
10614
10615 (defun js2-mode-reset ()
10616 "Debugging helper: reset everything."
10617 (interactive)
10618 (js2-mode-exit)
10619 (js2-mode))
10620
10621 (defsubst js2-mode-show-warn-or-err (e face)
10622 "Highlight a warning or error E with FACE.
10623 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10624 (let* ((key (first e))
10625 (beg (second e))
10626 (end (+ beg (third e)))
10627 ;; Don't inadvertently go out of bounds.
10628 (beg (max (point-min) (min beg (point-max))))
10629 (end (max (point-min) (min end (point-max))))
10630 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10631 (ovl (make-overlay beg end)))
10632 (overlay-put ovl 'face face)
10633 (overlay-put ovl 'js2-error t)
10634 (put-text-property beg end 'help-echo (js2-get-msg key))
10635 (put-text-property beg end 'point-entered #'js2-echo-error)))
10636
10637 (defun js2-remove-overlays ()
10638 "Remove overlays from buffer that have a `js2-error' property."
10639 (let ((beg (point-min))
10640 (end (point-max)))
10641 (save-excursion
10642 (dolist (o (overlays-in beg end))
10643 (when (overlay-get o 'js2-error)
10644 (delete-overlay o))))))
10645
10646 (defun js2-error-at-point (&optional pos)
10647 "Return non-nil if there's an error overlay at POS.
10648 Defaults to point."
10649 (loop with pos = (or pos (point))
10650 for o in (overlays-at pos)
10651 thereis (overlay-get o 'js2-error)))
10652
10653 (defun js2-mode-apply-deferred-properties ()
10654 "Apply fontifications and other text properties recorded during parsing."
10655 (when (plusp js2-highlight-level)
10656 ;; We defer clearing faces as long as possible to eliminate flashing.
10657 (js2-clear-face (point-min) (point-max))
10658 ;; Have to reverse the recorded fontifications list so that errors
10659 ;; and warnings overwrite the normal fontifications.
10660 (dolist (f (nreverse js2-mode-fontifications))
10661 (put-text-property (first f) (second f) 'face (third f)))
10662 (setq js2-mode-fontifications nil))
10663 (dolist (p js2-mode-deferred-properties)
10664 (apply #'put-text-property p))
10665 (setq js2-mode-deferred-properties nil))
10666
10667 (defun js2-mode-show-errors ()
10668 "Highlight syntax errors."
10669 (when js2-mode-show-parse-errors
10670 (dolist (e (js2-ast-root-errors js2-mode-ast))
10671 (js2-mode-show-warn-or-err e 'js2-error-face))))
10672
10673 (defun js2-mode-remove-suppressed-warnings ()
10674 "Take suppressed warnings out of the AST warnings list.
10675 This ensures that the counts and `next-error' are correct."
10676 (setf (js2-ast-root-warnings js2-mode-ast)
10677 (js2-delete-if
10678 (lambda (e)
10679 (let ((key (caar e)))
10680 (or
10681 (and (not js2-strict-trailing-comma-warning)
10682 (string-match "trailing\\.comma" key))
10683 (and (not js2-strict-cond-assign-warning)
10684 (string= key "msg.equal.as.assign"))
10685 (and js2-missing-semi-one-line-override
10686 (string= key "msg.missing.semi")
10687 (let* ((beg (second e))
10688 (node (js2-node-at-point beg))
10689 (fn (js2-mode-find-parent-fn node))
10690 (body (and fn (js2-function-node-body fn)))
10691 (lc (and body (js2-node-abs-pos body)))
10692 (rc (and lc (+ lc (js2-node-len body)))))
10693 (and fn
10694 (or (null body)
10695 (save-excursion
10696 (goto-char beg)
10697 (and (js2-same-line lc)
10698 (js2-same-line rc))))))))))
10699 (js2-ast-root-warnings js2-mode-ast))))
10700
10701 (defun js2-mode-show-warnings ()
10702 "Highlight strict-mode warnings."
10703 (when js2-mode-show-strict-warnings
10704 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10705 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10706
10707 (defun js2-echo-error (old-point new-point)
10708 "Called by point-motion hooks."
10709 (let ((msg (get-text-property new-point 'help-echo)))
10710 (if msg
10711 (message msg))))
10712
10713 (defalias #'js2-echo-help #'js2-echo-error)
10714
10715 (defun js2-enter-key ()
10716 "Handle user pressing the Enter key."
10717 (interactive)
10718 (let ((parse-status (save-excursion
10719 (parse-partial-sexp (point-min) (point)))))
10720 (cond
10721 ;; check if we're inside a string
10722 ((nth 3 parse-status)
10723 (js2-mode-split-string parse-status))
10724 ;; check if inside a block comment
10725 ((nth 4 parse-status)
10726 (js2-mode-extend-comment))
10727 (t
10728 ;; should probably figure out what the mode-map says we should do
10729 (if js2-indent-on-enter-key
10730 (let ((js2-bounce-indent-p nil))
10731 (js2-indent-line)))
10732 (insert "\n")
10733 (if js2-enter-indents-newline
10734 (let ((js2-bounce-indent-p nil))
10735 (js2-indent-line)))))))
10736
10737 (defun js2-mode-split-string (parse-status)
10738 "Turn a newline in mid-string into a string concatenation.
10739 PARSE-STATUS is as documented in `parse-partial-sexp'."
10740 (let* ((col (current-column))
10741 (quote-char (nth 3 parse-status))
10742 (quote-string (string quote-char))
10743 (string-beg (nth 8 parse-status))
10744 (indent (save-match-data
10745 (or
10746 (save-excursion
10747 (back-to-indentation)
10748 (if (looking-at "\\+")
10749 (current-column)))
10750 (save-excursion
10751 (goto-char string-beg)
10752 (if (looking-back "\\+\\s-+")
10753 (goto-char (match-beginning 0)))
10754 (current-column))))))
10755 (insert quote-char "\n")
10756 (indent-to indent)
10757 (insert "+ " quote-string)
10758 (when (eolp)
10759 (insert quote-string)
10760 (backward-char 1))))
10761
10762 (defun js2-mode-extend-comment ()
10763 "When inside a comment block, add comment prefix."
10764 (let (star single col first-line needs-close)
10765 (save-excursion
10766 (back-to-indentation)
10767 (cond
10768 ((looking-at "\\*[^/]")
10769 (setq star t
10770 col (current-column)))
10771 ((looking-at "/\\*")
10772 (setq star t
10773 first-line t
10774 col (1+ (current-column))))
10775 ((looking-at "//")
10776 (setq single t
10777 col (current-column)))))
10778 ;; Heuristic for whether we need to close the comment:
10779 ;; if we've got a parse error here, assume it's an unterminated
10780 ;; comment.
10781 (setq needs-close
10782 (or
10783 (eq (get-text-property (1- (point)) 'point-entered)
10784 'js2-echo-error)
10785 ;; The heuristic above doesn't work well when we're
10786 ;; creating a comment and there's another one downstream,
10787 ;; as our parser thinks this one ends at the end of the
10788 ;; next one. (You can have a /* inside a js block comment.)
10789 ;; So just close it if the next non-ws char isn't a *.
10790 (and first-line
10791 (eolp)
10792 (save-excursion
10793 (skip-chars-forward " \t\r\n")
10794 (not (eq (char-after) ?*))))))
10795 (insert "\n")
10796 (cond
10797 (star
10798 (indent-to col)
10799 (insert "* ")
10800 (if (and first-line needs-close)
10801 (save-excursion
10802 (insert "\n")
10803 (indent-to col)
10804 (insert "*/"))))
10805 (single
10806 (when (save-excursion
10807 (and (zerop (forward-line 1))
10808 (looking-at "\\s-*//")))
10809 (indent-to col)
10810 (insert "// "))))))
10811
10812 (defun js2-beginning-of-line ()
10813 "Toggles point between bol and first non-whitespace char in line.
10814 Also moves past comment delimiters when inside comments."
10815 (interactive)
10816 (let (node beg)
10817 (cond
10818 ((bolp)
10819 (back-to-indentation))
10820 ((looking-at "//")
10821 (skip-chars-forward "/ \t"))
10822 ((and (eq (char-after) ?*)
10823 (setq node (js2-comment-at-point))
10824 (memq (js2-comment-node-format node) '(jsdoc block))
10825 (save-excursion
10826 (skip-chars-backward " \t")
10827 (bolp)))
10828 (skip-chars-forward "\* \t"))
10829 (t
10830 (goto-char (point-at-bol))))))
10831
10832 (defun js2-end-of-line ()
10833 "Toggles point between eol and last non-whitespace char in line."
10834 (interactive)
10835 (if (eolp)
10836 (skip-chars-backward " \t")
10837 (goto-char (point-at-eol))))
10838
10839 (defun js2-enter-mirror-mode()
10840 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10841 on insertion."
10842 (interactive)
10843 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10844 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10845 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10846 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10847 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10848 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10849 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10850 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10851
10852 (defun js2-leave-mirror-mode()
10853 "Turns off mirror mode."
10854 (interactive)
10855 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10856 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10857
10858 (defsubst js2-mode-inside-string ()
10859 "Return non-nil if inside a string.
10860 Actually returns the quote character that begins the string."
10861 (let ((parse-state (save-excursion
10862 (parse-partial-sexp (point-min) (point)))))
10863 (nth 3 parse-state)))
10864
10865 (defsubst js2-mode-inside-comment-or-string ()
10866 "Return non-nil if inside a comment or string."
10867 (or
10868 (let ((comment-start
10869 (save-excursion
10870 (goto-char (point-at-bol))
10871 (if (re-search-forward "//" (point-at-eol) t)
10872 (match-beginning 0)))))
10873 (and comment-start
10874 (<= comment-start (point))))
10875 (let ((parse-state (save-excursion
10876 (parse-partial-sexp (point-min) (point)))))
10877 (or (nth 3 parse-state)
10878 (nth 4 parse-state)))))
10879
10880 (defsubst js2-make-magic-delimiter (delim &optional pos)
10881 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10882 Sets value of `js2-magic' text property to line number at POS."
10883 (propertize delim
10884 'js2-magic (line-number-at-pos pos)
10885 'face 'js2-magic-paren-face))
10886
10887 (defun js2-mode-match-delimiter (open close)
10888 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10889 The rule we use, which as far as we can tell is how Eclipse works,
10890 is that we insert the match if we're not in a comment or string,
10891 and the next non-whitespace character is either punctuation or
10892 occurs on another line."
10893 (insert open)
10894 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10895 (not (js2-mode-inside-comment-or-string)))
10896 (save-excursion
10897 (insert (js2-make-magic-delimiter close)))
10898 (when js2-auto-indent-p
10899 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10900 (js2-indent-line)))))
10901
10902 (defun js2-mode-match-bracket ()
10903 "Insert matching bracket."
10904 (interactive)
10905 (js2-mode-match-delimiter "[" "]"))
10906
10907 (defun js2-mode-match-paren ()
10908 "Insert matching paren unless already inserted."
10909 (interactive)
10910 (js2-mode-match-delimiter "(" ")"))
10911
10912 (defun js2-mode-match-curly (arg)
10913 "Insert matching curly-brace.
10914 With prefix arg, no formatting or indentation will occur -- the close-brace
10915 is simply inserted directly at the point."
10916 (interactive "p")
10917 (let (try-pos)
10918 (cond
10919 (current-prefix-arg
10920 (js2-mode-match-delimiter "{" "}"))
10921 ((and js2-auto-insert-catch-block
10922 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10923 (point-at-bol))
10924 (match-beginning 1))))
10925 (js2-insert-catch-skel try-pos))
10926 (t
10927 ;; Otherwise try to do something smarter.
10928 (insert "{")
10929 (unless (or (not (looking-at "\\s-*$"))
10930 (save-excursion
10931 (skip-chars-forward " \t\r\n")
10932 (and (looking-at "}")
10933 (js2-error-at-point)))
10934 (js2-mode-inside-comment-or-string))
10935 (undo-boundary)
10936 ;; absolutely mystifying bug: when inserting the next "\n",
10937 ;; the buffer-undo-list is given two new entries: the inserted range,
10938 ;; and the incorrect position of the point. It's recorded incorrectly
10939 ;; as being before the opening "{", not after it. But it's recorded
10940 ;; as the correct value if you're debugging `js2-mode-match-curly'
10941 ;; in edebug. I have no idea why it's doing this, but incrementing
10942 ;; the inserted position fixes the problem, so that the undo takes us
10943 ;; back to just after the user-inserted "{".
10944 (insert "\n")
10945 (ignore-errors
10946 (incf (cadr buffer-undo-list)))
10947 (js2-indent-line)
10948 (save-excursion
10949 (insert "\n}")
10950 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10951 (js2-indent-line))))))))
10952
10953 (defun js2-insert-catch-skel (try-pos)
10954 "Complete a try/catch block after inserting a { following a try keyword.
10955 Rationale is that a try always needs a catch or a finally, and the catch is
10956 the more likely of the two.
10957
10958 TRY-POS is the buffer position of the try keyword. The open-curly should
10959 already have been inserted."
10960 (insert "{")
10961 (let ((try-col (save-excursion
10962 (goto-char try-pos)
10963 (current-column))))
10964 (insert "\n")
10965 (undo-boundary)
10966 (js2-indent-line) ;; indent the blank line where cursor will end up
10967 (save-excursion
10968 (insert "\n")
10969 (indent-to try-col)
10970 (insert "} catch (x) {\n\n")
10971 (indent-to try-col)
10972 (insert "}"))))
10973
10974 (defun js2-mode-highlight-magic-parens ()
10975 "Re-highlight magic parens after parsing nukes the 'face prop."
10976 (let ((beg (point-min))
10977 end)
10978 (while (setq beg (next-single-property-change beg 'js2-magic))
10979 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10980 (if (get-text-property beg 'js2-magic)
10981 (js2-with-unmodifying-text-property-changes
10982 (put-text-property beg (or end (1+ beg))
10983 'face 'js2-magic-paren-face))))))
10984
10985 (defun js2-mode-mundanify-parens ()
10986 "Clear all magic parens and brackets."
10987 (let ((beg (point-min))
10988 end)
10989 (while (setq beg (next-single-property-change beg 'js2-magic))
10990 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10991 (remove-text-properties beg (or end (1+ beg))
10992 '(js2-magic face)))))
10993
10994 (defsubst js2-match-quote (quote-string)
10995 (let ((start-quote (js2-mode-inside-string)))
10996 (cond
10997 ;; inside a comment - don't do quote-matching, since we can't
10998 ;; reliably figure out if we're in a string inside the comment
10999 ((js2-comment-at-point)
11000 (insert quote-string))
11001 ((not start-quote)
11002 ;; not in string => insert matched quotes
11003 (insert quote-string)
11004 ;; exception: if we're just before a word, don't double it.
11005 (unless (looking-at "[^ \t\r\n]")
11006 (save-excursion
11007 (insert quote-string))))
11008 ((looking-at quote-string)
11009 (if (looking-back "[^\\]\\\\")
11010 (insert quote-string)
11011 (forward-char 1)))
11012 ((and js2-mode-escape-quotes
11013 (save-excursion
11014 (save-match-data
11015 (re-search-forward quote-string (point-at-eol) t))))
11016 ;; inside terminated string, escape quote (unless already escaped)
11017 (insert (if (looking-back "[^\\]\\\\")
11018 quote-string
11019 (concat "\\" quote-string))))
11020 (t
11021 (insert quote-string))))) ; else terminate the string
11022
11023 (defun js2-mode-match-single-quote ()
11024 "Insert matching single-quote."
11025 (interactive)
11026 (let ((parse-status (parse-partial-sexp (point-min) (point))))
11027 ;; don't match inside comments, since apostrophe is more common
11028 (if (nth 4 parse-status)
11029 (insert "'")
11030 (js2-match-quote "'"))))
11031
11032 (defun js2-mode-match-double-quote ()
11033 "Insert matching double-quote."
11034 (interactive)
11035 (js2-match-quote "\""))
11036
11037 ;; Eclipse works as follows:
11038 ;; * type an open-paren and it auto-inserts close-paren
11039 ;; - auto-inserted paren gets a green bracket
11040 ;; - green bracket means typing close-paren there will skip it
11041 ;; * if you insert any text on a different line, it turns off
11042 (defun js2-mode-magic-close-paren ()
11043 "Skip over close-paren rather than inserting, where appropriate."
11044 (interactive)
11045 (let* ((here (point))
11046 (parse-status (parse-partial-sexp (point-min) here))
11047 (open-pos (nth 1 parse-status))
11048 (close last-input-event)
11049 (open (cond
11050 ((eq close ?\))
11051 ?\()
11052 ((eq close ?\])
11053 ?\[)
11054 ((eq close ?})
11055 ?{)
11056 (t nil))))
11057 (if (and (eq (char-after) close)
11058 (eq open (char-after open-pos))
11059 (js2-same-line open-pos)
11060 (get-text-property here 'js2-magic))
11061 (progn
11062 (remove-text-properties here (1+ here) '(js2-magic face))
11063 (forward-char 1))
11064 (insert-char close 1))
11065 (blink-matching-open)))
11066
11067 (defun js2-mode-wait-for-parse (callback)
11068 "Invoke CALLBACK when parsing is finished.
11069 If parsing is already finished, calls CALLBACK immediately."
11070 (if (not js2-mode-buffer-dirty-p)
11071 (funcall callback)
11072 (push callback js2-mode-pending-parse-callbacks)
11073 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11074
11075 (defun js2-mode-parse-finished ()
11076 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11077 ;; We can't let errors propagate up, since it prevents the
11078 ;; `js2-parse' method from completing normally and returning
11079 ;; the ast, which makes things mysteriously not work right.
11080 (unwind-protect
11081 (dolist (cb js2-mode-pending-parse-callbacks)
11082 (condition-case err
11083 (funcall cb)
11084 (error (message "%s" err))))
11085 (setq js2-mode-pending-parse-callbacks nil)))
11086
11087 (defun js2-mode-flag-region (from to flag)
11088 "Hide or show text from FROM to TO, according to FLAG.
11089 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11090 Returns the created overlay if FLAG is non-nil."
11091 (remove-overlays from to 'invisible 'js2-outline)
11092 (when flag
11093 (let ((o (make-overlay from to)))
11094 (overlay-put o 'invisible 'js2-outline)
11095 (overlay-put o 'isearch-open-invisible
11096 'js2-isearch-open-invisible)
11097 o)))
11098
11099 ;; Function to be set as an outline-isearch-open-invisible' property
11100 ;; to the overlay that makes the outline invisible (see
11101 ;; `js2-mode-flag-region').
11102 (defun js2-isearch-open-invisible (overlay)
11103 ;; We rely on the fact that isearch places point on the matched text.
11104 (js2-mode-show-element))
11105
11106 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11107 "Return cons cell of bounds of folding overlay at POS.
11108 Returns nil if not found."
11109 (let ((overlays (overlays-at (or pos (point))))
11110 o)
11111 (while (and overlays
11112 (not o))
11113 (if (overlay-get (car overlays) 'invisible)
11114 (setq o (car overlays))
11115 (setq overlays (cdr overlays))))
11116 (if o
11117 (cons (overlay-start o) (overlay-end o)))))
11118
11119 (defun js2-mode-function-at-point (&optional pos)
11120 "Return the innermost function node enclosing current point.
11121 Returns nil if point is not in a function."
11122 (let ((node (js2-node-at-point pos)))
11123 (while (and node (not (js2-function-node-p node)))
11124 (setq node (js2-node-parent node)))
11125 (if (js2-function-node-p node)
11126 node)))
11127
11128 (defun js2-mode-toggle-element ()
11129 "Hide or show the foldable element at the point."
11130 (interactive)
11131 (let (comment fn pos)
11132 (save-excursion
11133 (save-match-data
11134 (cond
11135 ;; /* ... */ comment?
11136 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11137 (if (js2-mode-invisible-overlay-bounds
11138 (setq pos (+ 3 (js2-node-abs-pos comment))))
11139 (progn
11140 (goto-char pos)
11141 (js2-mode-show-element))
11142 (js2-mode-hide-element)))
11143 ;; //-comment?
11144 ((save-excursion
11145 (back-to-indentation)
11146 (looking-at js2-mode-//-comment-re))
11147 (js2-mode-toggle-//-comment))
11148 ;; function?
11149 ((setq fn (js2-mode-function-at-point))
11150 (setq pos (and (js2-function-node-body fn)
11151 (js2-node-abs-pos (js2-function-node-body fn))))
11152 (goto-char (1+ pos))
11153 (if (js2-mode-invisible-overlay-bounds)
11154 (js2-mode-show-element)
11155 (js2-mode-hide-element)))
11156 (t
11157 (message "Nothing at point to hide or show")))))))
11158
11159 (defun js2-mode-hide-element ()
11160 "Fold/hide contents of a block, showing ellipses.
11161 Show the hidden text with \\[js2-mode-show-element]."
11162 (interactive)
11163 (if js2-mode-buffer-dirty-p
11164 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11165 (let (node body beg end)
11166 (cond
11167 ((js2-mode-invisible-overlay-bounds)
11168 (message "already hidden"))
11169 (t
11170 (setq node (js2-node-at-point))
11171 (cond
11172 ((js2-block-comment-p node)
11173 (js2-mode-hide-comment node))
11174 (t
11175 (while (and node (not (js2-function-node-p node)))
11176 (setq node (js2-node-parent node)))
11177 (if (and node
11178 (setq body (js2-function-node-body node)))
11179 (progn
11180 (setq beg (js2-node-abs-pos body)
11181 end (+ beg (js2-node-len body)))
11182 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11183 (message "No collapsable element found at point"))))))))
11184
11185 (defun js2-mode-show-element ()
11186 "Show the hidden element at current point."
11187 (interactive)
11188 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11189 (if bounds
11190 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11191 (message "Nothing to un-hide"))))
11192
11193 (defun js2-mode-show-all ()
11194 "Show all of the text in the buffer."
11195 (interactive)
11196 (js2-mode-flag-region (point-min) (point-max) nil))
11197
11198 (defun js2-mode-toggle-hide-functions ()
11199 (interactive)
11200 (if js2-mode-functions-hidden
11201 (js2-mode-show-functions)
11202 (js2-mode-hide-functions)))
11203
11204 (defun js2-mode-hide-functions ()
11205 "Hides all non-nested function bodies in the buffer.
11206 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11207 to open an individual entry."
11208 (interactive)
11209 (if js2-mode-buffer-dirty-p
11210 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11211 (if (null js2-mode-ast)
11212 (message "Oops - parsing failed")
11213 (setq js2-mode-functions-hidden t)
11214 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11215
11216 (defun js2-mode-function-hider (n endp)
11217 (when (not endp)
11218 (let ((tt (js2-node-type n))
11219 body beg end)
11220 (cond
11221 ((and (= tt js2-FUNCTION)
11222 (setq body (js2-function-node-body n)))
11223 (setq beg (js2-node-abs-pos body)
11224 end (+ beg (js2-node-len body)))
11225 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11226 nil) ; don't process children of function
11227 (t
11228 t))))) ; keep processing other AST nodes
11229
11230 (defun js2-mode-show-functions ()
11231 "Un-hide any folded function bodies in the buffer."
11232 (interactive)
11233 (setq js2-mode-functions-hidden nil)
11234 (save-excursion
11235 (goto-char (point-min))
11236 (while (/= (goto-char (next-overlay-change (point)))
11237 (point-max))
11238 (dolist (o (overlays-at (point)))
11239 (when (and (overlay-get o 'invisible)
11240 (not (overlay-get o 'comment)))
11241 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11242
11243 (defun js2-mode-hide-comment (n)
11244 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11245 3 ; /**
11246 2)) ; /*
11247 (beg (+ (js2-node-abs-pos n) head))
11248 (end (- (+ beg (js2-node-len n)) head 2))
11249 (o (js2-mode-flag-region beg end 'hide)))
11250 (overlay-put o 'comment t)))
11251
11252 (defun js2-mode-toggle-hide-comments ()
11253 "Folds all block comments in the buffer.
11254 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11255 to open an individual entry."
11256 (interactive)
11257 (if js2-mode-comments-hidden
11258 (js2-mode-show-comments)
11259 (js2-mode-hide-comments)))
11260
11261 (defun js2-mode-hide-comments ()
11262 (interactive)
11263 (if js2-mode-buffer-dirty-p
11264 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11265 (if (null js2-mode-ast)
11266 (message "Oops - parsing failed")
11267 (setq js2-mode-comments-hidden t)
11268 (dolist (n (js2-ast-root-comments js2-mode-ast))
11269 (let ((format (js2-comment-node-format n)))
11270 (when (js2-block-comment-p n)
11271 (js2-mode-hide-comment n))))
11272 (js2-mode-hide-//-comments)))
11273
11274 (defsubst js2-mode-extend-//-comment (direction)
11275 "Find start or end of a block of similar //-comment lines.
11276 DIRECTION is -1 to look back, 1 to look forward.
11277 INDENT is the indentation level to match.
11278 Returns the end-of-line position of the furthest adjacent
11279 //-comment line with the same indentation as the current line.
11280 If there is no such matching line, returns current end of line."
11281 (let ((pos (point-at-eol))
11282 (indent (current-indentation)))
11283 (save-excursion
11284 (save-match-data
11285 (while (and (zerop (forward-line direction))
11286 (looking-at js2-mode-//-comment-re)
11287 (eq indent (length (match-string 1))))
11288 (setq pos (point-at-eol)))
11289 pos))))
11290
11291 (defun js2-mode-hide-//-comments ()
11292 "Fold adjacent 1-line comments, showing only snippet of first one."
11293 (let (beg end)
11294 (save-excursion
11295 (save-match-data
11296 (goto-char (point-min))
11297 (while (re-search-forward js2-mode-//-comment-re nil t)
11298 (setq beg (point)
11299 end (js2-mode-extend-//-comment 1))
11300 (unless (eq beg end)
11301 (overlay-put (js2-mode-flag-region beg end 'hide)
11302 'comment t))
11303 (goto-char end)
11304 (forward-char 1))))))
11305
11306 (defun js2-mode-toggle-//-comment ()
11307 "Fold or un-fold any multi-line //-comment at point.
11308 Caller should have determined that this line starts with a //-comment."
11309 (let* ((beg (point-at-eol))
11310 (end beg))
11311 (save-excursion
11312 (goto-char end)
11313 (if (js2-mode-invisible-overlay-bounds)
11314 (js2-mode-show-element)
11315 ;; else hide the comment
11316 (setq beg (js2-mode-extend-//-comment -1)
11317 end (js2-mode-extend-//-comment 1))
11318 (unless (eq beg end)
11319 (overlay-put (js2-mode-flag-region beg end 'hide)
11320 'comment t))))))
11321
11322 (defun js2-mode-show-comments ()
11323 "Un-hide any hidden comments, leaving other hidden elements alone."
11324 (interactive)
11325 (setq js2-mode-comments-hidden nil)
11326 (save-excursion
11327 (goto-char (point-min))
11328 (while (/= (goto-char (next-overlay-change (point)))
11329 (point-max))
11330 (dolist (o (overlays-at (point)))
11331 (when (overlay-get o 'comment)
11332 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11333
11334 (defun js2-mode-display-warnings-and-errors ()
11335 "Turn on display of warnings and errors."
11336 (interactive)
11337 (setq js2-mode-show-parse-errors t
11338 js2-mode-show-strict-warnings t)
11339 (js2-reparse 'force))
11340
11341 (defun js2-mode-hide-warnings-and-errors ()
11342 "Turn off display of warnings and errors."
11343 (interactive)
11344 (setq js2-mode-show-parse-errors nil
11345 js2-mode-show-strict-warnings nil)
11346 (js2-reparse 'force))
11347
11348 (defun js2-mode-toggle-warnings-and-errors ()
11349 "Toggle the display of warnings and errors.
11350 Some users don't like having warnings/errors reported while they type."
11351 (interactive)
11352 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11353 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11354 (if (interactive-p)
11355 (message "warnings and errors %s"
11356 (if js2-mode-show-parse-errors
11357 "enabled"
11358 "disabled")))
11359 (js2-reparse 'force))
11360
11361 (defun js2-mode-customize ()
11362 (interactive)
11363 (customize-group 'js2-mode))
11364
11365 (defun js2-mode-forward-sexp (&optional arg)
11366 "Move forward across one statement or balanced expression.
11367 With ARG, do it that many times. Negative arg -N means
11368 move backward across N balanced expressions."
11369 (interactive "p")
11370 (setq arg (or arg 1))
11371 (if js2-mode-buffer-dirty-p
11372 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11373 (let (node end (start (point)))
11374 (cond
11375 ;; backward-sexp
11376 ;; could probably make this better for some cases:
11377 ;; - if in statement block (e.g. function body), go to parent
11378 ;; - infix exprs like (foo in bar) - maybe go to beginning
11379 ;; of infix expr if in the right-side expression?
11380 ((and arg (minusp arg))
11381 (dotimes (i (- arg))
11382 (js2-backward-sws)
11383 (forward-char -1) ; enter the node we backed up to
11384 (setq node (js2-node-at-point (point) t))
11385 (goto-char (if node
11386 (js2-node-abs-pos node)
11387 (point-min)))))
11388 (t
11389 ;; forward-sexp
11390 (js2-forward-sws)
11391 (dotimes (i arg)
11392 (js2-forward-sws)
11393 (setq node (js2-node-at-point (point) t)
11394 end (if node (+ (js2-node-abs-pos node)
11395 (js2-node-len node))))
11396 (goto-char (or end (point-max))))))))
11397
11398 (defun js2-next-error (&optional arg reset)
11399 "Move to next parse error.
11400 Typically invoked via \\[next-error].
11401 ARG is the number of errors, forward or backward, to move.
11402 RESET means start over from the beginning."
11403 (interactive "p")
11404 (if (or (null js2-mode-ast)
11405 (and (null (js2-ast-root-errors js2-mode-ast))
11406 (null (js2-ast-root-warnings js2-mode-ast))))
11407 (message "No errors")
11408 (when reset
11409 (goto-char (point-min)))
11410 (let* ((errs (copy-sequence
11411 (append (js2-ast-root-errors js2-mode-ast)
11412 (js2-ast-root-warnings js2-mode-ast))))
11413 (continue t)
11414 (start (point))
11415 (count (or arg 1))
11416 (backward (minusp count))
11417 (sorter (if backward '> '<))
11418 (stopper (if backward '< '>))
11419 (count (abs count))
11420 all-errs
11421 err)
11422 ;; sort by start position
11423 (setq errs (sort errs (lambda (e1 e2)
11424 (funcall sorter (second e1) (second e2))))
11425 all-errs errs)
11426 ;; find nth error with pos > start
11427 (while (and errs continue)
11428 (when (funcall stopper (cadar errs) start)
11429 (setq err (car errs))
11430 (if (zerop (decf count))
11431 (setq continue nil)))
11432 (setq errs (cdr errs)))
11433 (if err
11434 (goto-char (second err))
11435 ;; wrap around to first error
11436 (goto-char (second (car all-errs)))
11437 ;; if we were already on it, echo msg again
11438 (if (= (point) start)
11439 (js2-echo-error (point) (point)))))))
11440
11441 (defun js2-down-mouse-3 ()
11442 "Make right-click move the point to the click location.
11443 This makes right-click context menu operations a bit more intuitive.
11444 The point will not move if the region is active, however, to avoid
11445 destroying the region selection."
11446 (interactive)
11447 (when (and js2-move-point-on-right-click
11448 (not mark-active))
11449 (let ((e last-input-event))
11450 (ignore-errors
11451 (goto-char (cadadr e))))))
11452
11453 (defun js2-mode-create-imenu-index ()
11454 "Return an alist for `imenu--index-alist'."
11455 ;; This is built up in `js2-parse-record-imenu' during parsing.
11456 (when js2-mode-ast
11457 ;; if we have an ast but no recorder, they're requesting a rescan
11458 (unless js2-imenu-recorder
11459 (js2-reparse 'force))
11460 (prog1
11461 (js2-build-imenu-index)
11462 (setq js2-imenu-recorder nil
11463 js2-imenu-function-map nil))))
11464
11465 (defun js2-mode-find-tag ()
11466 "Replacement for `find-tag-default'.
11467 `find-tag-default' returns a ridiculous answer inside comments."
11468 (let (beg end)
11469 (js2-with-underscore-as-word-syntax
11470 (save-excursion
11471 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11472 (looking-back "[A-Za-z0-9_$]"))
11473 (setq beg (progn (forward-word -1) (point))
11474 end (progn (forward-word 1) (point)))
11475 (setq beg (progn (forward-word 1) (point))
11476 end (progn (forward-word -1) (point))))
11477 (replace-regexp-in-string
11478 "[\"']" ""
11479 (buffer-substring-no-properties beg end))))))
11480
11481 (defun js2-mode-forward-sibling ()
11482 "Move to the end of the sibling following point in parent.
11483 Returns non-nil if successful, or nil if there was no following sibling."
11484 (let* ((node (js2-node-at-point))
11485 (parent (js2-mode-find-enclosing-fn node))
11486 sib)
11487 (when (setq sib (js2-node-find-child-after (point) parent))
11488 (goto-char (+ (js2-node-abs-pos sib)
11489 (js2-node-len sib))))))
11490
11491 (defun js2-mode-backward-sibling ()
11492 "Move to the beginning of the sibling node preceding point in parent.
11493 Parent is defined as the enclosing script or function."
11494 (let* ((node (js2-node-at-point))
11495 (parent (js2-mode-find-enclosing-fn node))
11496 sib)
11497 (when (setq sib (js2-node-find-child-before (point) parent))
11498 (goto-char (js2-node-abs-pos sib)))))
11499
11500 (defun js2-beginning-of-defun ()
11501 "Go to line on which current function starts, and return non-nil.
11502 If we're not in a function, go to beginning of previous script-level element."
11503 (interactive)
11504 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11505 pos sib)
11506 (cond
11507 ((and (js2-function-node-p parent)
11508 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11509 (goto-char pos))
11510 (t
11511 (js2-mode-backward-sibling)))))
11512
11513 (defun js2-end-of-defun ()
11514 "Go to the char after the last position of the current function.
11515 If we're not in a function, skips over the next script-level element."
11516 (interactive)
11517 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11518 (if (not (js2-function-node-p parent))
11519 ;; punt: skip over next script-level element beyond point
11520 (js2-mode-forward-sibling)
11521 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11522 (js2-node-len parent)))))))
11523
11524 (defun js2-mark-defun (&optional allow-extend)
11525 "Put mark at end of this function, point at beginning.
11526 The function marked is the one that contains point.
11527
11528 Interactively, if this command is repeated,
11529 or (in Transient Mark mode) if the mark is active,
11530 it marks the next defun after the ones already marked."
11531 (interactive "p")
11532 (let (extended)
11533 (when (and allow-extend
11534 (or (and (eq last-command this-command) (mark t))
11535 (and transient-mark-mode mark-active)))
11536 (let ((sib (save-excursion
11537 (goto-char (mark))
11538 (if (js2-mode-forward-sibling)
11539 (point))))
11540 node)
11541 (if sib
11542 (progn
11543 (set-mark sib)
11544 (setq extended t))
11545 ;; no more siblings - try extending to enclosing node
11546 (goto-char (mark t)))))
11547 (when (not extended)
11548 (let ((node (js2-node-at-point (point) t)) ; skip comments
11549 ast fn stmt parent beg end)
11550 (when (js2-ast-root-p node)
11551 (setq ast node
11552 node (or (js2-node-find-child-after (point) node)
11553 (js2-node-find-child-before (point) node))))
11554 ;; only mark whole buffer if we can't find any children
11555 (if (null node)
11556 (setq node ast))
11557 (if (js2-function-node-p node)
11558 (setq parent node)
11559 (setq fn (js2-mode-find-enclosing-fn node)
11560 stmt (if (or (null fn)
11561 (js2-ast-root-p fn))
11562 (js2-mode-find-first-stmt node))
11563 parent (or stmt fn)))
11564 (setq beg (js2-node-abs-pos parent)
11565 end (+ beg (js2-node-len parent)))
11566 (push-mark beg)
11567 (goto-char end)
11568 (exchange-point-and-mark)))))
11569
11570 (defun js2-narrow-to-defun ()
11571 "Narrow to the function enclosing point."
11572 (interactive)
11573 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11574 (fn (if (js2-script-node-p node)
11575 node
11576 (js2-mode-find-enclosing-fn node)))
11577 (beg (js2-node-abs-pos fn)))
11578 (unless (js2-ast-root-p fn)
11579 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11580
11581 (provide 'js2-mode)
11582
11583 ;;; js2-mode.el ends here