]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Remove unnecessary checks
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defvar js2-emacs22 (>= emacs-major-version 22))
176
177 (defcustom js2-highlight-level 2
178 "Amount of syntax highlighting to perform.
179 0 or a negative value means do no highlighting.
180 1 adds basic syntax highlighting.
181 2 adds highlighting of some Ecma built-in properties.
182 3 adds highlighting of many Ecma built-in functions."
183 :group 'js2-mode
184 :type '(choice (const :tag "None" 0)
185 (const :tag "Basic" 1)
186 (const :tag "Include Properties" 2)
187 (const :tag "Include Functions" 3)))
188
189 (defvar js2-mode-dev-mode-p nil
190 "Non-nil if running in development mode. Normally nil.")
191
192 (defgroup js2-mode nil
193 "An improved JavaScript mode."
194 :group 'languages)
195
196 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
197 (numberp c-basic-offset))
198 c-basic-offset
199 4)
200 "Number of spaces to indent nested statements.
201 Similar to `c-basic-offset'."
202 :group 'js2-mode
203 :type 'integer)
204 (make-variable-buffer-local 'js2-basic-offset)
205
206 ;; TODO(stevey): move this code into a separate minor mode.
207 (defcustom js2-mirror-mode nil
208 "Non-nil to insert closing brackets, parens, etc. automatically."
209 :group 'js2-mode
210 :type 'boolean)
211
212 (defcustom js2-auto-indent-p nil
213 "Automatic indentation with punctuation characters.
214 If non-nil, the current line is indented when certain punctuations
215 are inserted."
216 :group 'js2-mode
217 :type 'boolean)
218
219 (defcustom js2-bounce-indent-p nil
220 "Non-nil to have indent-line function choose among alternatives.
221 If nil, the indent-line function will indent to a predetermined column
222 based on heuristic guessing. If non-nil, then if the current line is
223 already indented to that predetermined column, indenting will choose
224 another likely column and indent to that spot. Repeated invocation of
225 the indent-line function will cycle among the computed alternatives.
226 See the function `js2-bounce-indent' for details."
227 :type 'boolean
228 :group 'js2-mode)
229
230 (defcustom js2-consistent-level-indent-inner-bracket-p t
231 "Non-nil to make indentation level inner bracket consistent,
232 regardless of the beginning bracket position."
233 :group 'js2-mode
234 :type 'boolean)
235
236 (defcustom js2-use-ast-for-indentation-p nil
237 "Non-nil to use AST for indentation and make it more robust."
238 :group 'js2-mode
239 :type 'boolean)
240
241 (defcustom js2-indent-on-enter-key nil
242 "Non-nil to have Enter/Return key indent the line.
243 This is unusual for Emacs modes but common in IDEs like Eclipse."
244 :type 'boolean
245 :group 'js2-mode)
246
247 (defcustom js2-enter-indents-newline nil
248 "Non-nil to have Enter/Return key indent the newly-inserted line.
249 This is unusual for Emacs modes but common in IDEs like Eclipse."
250 :type 'boolean
251 :group 'js2-mode)
252
253 (defcustom js2-rebind-eol-bol-keys t
254 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
255 If non-nil, bounce between bol/eol and first/last non-whitespace char."
256 :group 'js2-mode
257 :type 'boolean)
258
259 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
260 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
261 Each value in the list is passed to `define-key'."
262 :type 'list
263 :group 'js2-mode)
264
265 (defcustom js2-idle-timer-delay 0.2
266 "Delay in secs before re-parsing after user makes changes.
267 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
268 :type 'number
269 :group 'js2-mode)
270 (make-variable-buffer-local 'js2-idle-timer-delay)
271
272 (defcustom js2-dynamic-idle-timer-adjust 0
273 "Positive to adjust `js2-idle-timer-delay' based on file size.
274 The idea is that for short files, parsing is faster so we can be
275 more responsive to user edits without interfering with editing.
276 The buffer length in characters (typically bytes) is divided by
277 this value and used to multiply `js2-idle-timer-delay' for the
278 buffer. For example, a 21k file and 10k adjust yields 21k/10k
279 == 2, so js2-idle-timer-delay is multiplied by 2.
280 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
281 `js2-idle-timer-delay' is not dependent on the file size."
282 :type 'number
283 :group 'js2-mode)
284
285 (defcustom js2-mode-escape-quotes t
286 "Non-nil to disable automatic quote-escaping inside strings."
287 :type 'boolean
288 :group 'js2-mode)
289
290 (defcustom js2-mode-squeeze-spaces t
291 "Non-nil to normalize whitespace when filling in comments.
292 Multiple runs of spaces are converted to a single space."
293 :type 'boolean
294 :group 'js2-mode)
295
296 (defcustom js2-mode-show-parse-errors t
297 "True to highlight parse errors."
298 :type 'boolean
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-strict-warnings t
302 "Non-nil to emit Ecma strict-mode warnings.
303 Some of the warnings can be individually disabled by other flags,
304 even if this flag is non-nil."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-strict-trailing-comma-warning t
309 "Non-nil to warn about trailing commas in array literals.
310 Ecma-262 forbids them, but many browsers permit them. IE is the
311 big exception, and can produce bugs if you have trailing commas."
312 :type 'boolean
313 :group 'js2-mode)
314
315 (defcustom js2-strict-missing-semi-warning t
316 "Non-nil to warn about semicolon auto-insertion after statement.
317 Technically this is legal per Ecma-262, but some style guides disallow
318 depending on it."
319 :type 'boolean
320 :group 'js2-mode)
321
322 (defcustom js2-missing-semi-one-line-override nil
323 "Non-nil to permit missing semicolons in one-line functions.
324 In one-liner functions such as `function identity(x) {return x}'
325 people often omit the semicolon for a cleaner look. If you are
326 such a person, you can suppress the missing-semicolon warning
327 by setting this variable to t."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-inconsistent-return-warning t
332 "Non-nil to warn about mixing returns with value-returns.
333 It's perfectly legal to have a `return' and a `return foo' in the
334 same function, but it's often an indicator of a bug, and it also
335 interferes with type inference (in systems that support it.)"
336 :type 'boolean
337 :group 'js2-mode)
338
339 (defcustom js2-strict-cond-assign-warning t
340 "Non-nil to warn about expressions like if (a = b).
341 This often should have been '==' instead of '='. If the warning
342 is enabled, you can suppress it on a per-expression basis by
343 parenthesizing the expression, e.g. if ((a = b)) ..."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-cond-assign-warning t
348 "Non-nil to warn about expressions like if (a = b).
349 This often should have been '==' instead of '='. If the warning
350 is enabled, you can suppress it on a per-expression basis by
351 parenthesizing the expression, e.g. if ((a = b)) ..."
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-var-redeclaration-warning t
356 "Non-nil to warn about redeclaring variables in a script or function."
357 :type 'boolean
358 :group 'js2-mode)
359
360 (defcustom js2-strict-var-hides-function-arg-warning t
361 "Non-nil to warn about a var decl hiding a function argument."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-skip-preprocessor-directives nil
366 "Non-nil to treat lines beginning with # as comments.
367 Useful for viewing Mozilla JavaScript source code."
368 :type 'boolean
369 :group 'js2-mode)
370
371 (defcustom js2-language-version 180
372 "Configures what JavaScript language version to recognize.
373 Currently versions 150, 160, 170 and 180 are supported, corresponding
374 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
375 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
376 and 1.8 adds function closures."
377 :type 'integer
378 :group 'js2-mode)
379
380 (defcustom js2-allow-keywords-as-property-names t
381 "If non-nil, you can use JavaScript keywords as object property names.
382 Examples:
383
384 var foo = {int: 5, while: 6, continue: 7};
385 foo.return = 8;
386
387 Ecma-262 forbids this syntax, but many browsers support it."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-instanceof-has-side-effects nil
392 "If non-nil, treats the instanceof operator as having side effects.
393 This is useful for xulrunner apps."
394 :type 'boolean
395 :group 'js2-mode)
396
397 (defcustom js2-cleanup-whitespace nil
398 "Non-nil to invoke `delete-trailing-whitespace' before saves."
399 :type 'boolean
400 :group 'js2-mode)
401
402 (defcustom js2-move-point-on-right-click t
403 "Non-nil to move insertion point when you right-click.
404 This makes right-click context menu behavior a bit more intuitive,
405 since menu operations generally apply to the point. The exception
406 is if there is a region selection, in which case the point does -not-
407 move, so cut/copy/paste etc. can work properly.
408
409 Note that IntelliJ moves the point, and Eclipse leaves it alone,
410 so this behavior is customizable."
411 :group 'js2-mode
412 :type 'boolean)
413
414 (defcustom js2-allow-rhino-new-expr-initializer t
415 "Non-nil to support a Rhino's experimental syntactic construct.
416
417 Rhino supports the ability to follow a `new' expression with an object
418 literal, which is used to set additional properties on the new object
419 after calling its constructor. Syntax:
420
421 new <expr> [ ( arglist ) ] [initializer]
422
423 Hence, this expression:
424
425 new Object {a: 1, b: 2}
426
427 results in an Object with properties a=1 and b=2. This syntax is
428 apparently not configurable in Rhino - it's currently always enabled,
429 as of Rhino version 1.7R2."
430 :type 'boolean
431 :group 'js2-mode)
432
433 (defcustom js2-allow-member-expr-as-function-name nil
434 "Non-nil to support experimental Rhino syntax for function names.
435
436 Rhino supports an experimental syntax configured via the Rhino Context
437 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
438
439 function <member-expr> ( [ arg-list ] ) { <body> }
440
441 Where member-expr is a non-parenthesized 'member expression', which
442 is anything at the grammar level of a new-expression or lower, meaning
443 any expression that does not involve infix or unary operators.
444
445 When <member-expr> is not a simple identifier, then it is syntactic
446 sugar for assigning the anonymous function to the <member-expr>. Hence,
447 this code:
448
449 function a.b().c[2] (x, y) { ... }
450
451 is rewritten as:
452
453 a.b().c[2] = function(x, y) {...}
454
455 which doesn't seem particularly useful, but Rhino permits it."
456 :type 'boolean
457 :group 'js2-mode)
458
459 (defvar js2-mode-version 20101228
460 "Release number for `js2-mode'.")
461
462 ;; scanner variables
463
464 (defmacro js2-deflocal (name value &optional comment)
465 "Define a buffer-local variable NAME with VALUE and COMMENT."
466 `(progn
467 (defvar ,name ,value ,comment)
468 (make-variable-buffer-local ',name)))
469
470 ;; We record the start and end position of each token.
471 (js2-deflocal js2-token-beg 1)
472 (js2-deflocal js2-token-end -1)
473
474 (defvar js2-EOF_CHAR -1
475 "Represents end of stream. Distinct from js2-EOF token type.")
476
477 ;; I originally used symbols to represent tokens, but Rhino uses
478 ;; ints and then sets various flag bits in them, so ints it is.
479 ;; The upshot is that we need a `js2-' prefix in front of each name.
480 (defvar js2-ERROR -1)
481 (defvar js2-EOF 0)
482 (defvar js2-EOL 1)
483 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
484 (defvar js2-LEAVEWITH 3)
485 (defvar js2-RETURN 4)
486 (defvar js2-GOTO 5)
487 (defvar js2-IFEQ 6)
488 (defvar js2-IFNE 7)
489 (defvar js2-SETNAME 8)
490 (defvar js2-BITOR 9)
491 (defvar js2-BITXOR 10)
492 (defvar js2-BITAND 11)
493 (defvar js2-EQ 12)
494 (defvar js2-NE 13)
495 (defvar js2-LT 14)
496 (defvar js2-LE 15)
497 (defvar js2-GT 16)
498 (defvar js2-GE 17)
499 (defvar js2-LSH 18)
500 (defvar js2-RSH 19)
501 (defvar js2-URSH 20)
502 (defvar js2-ADD 21) ; infix plus
503 (defvar js2-SUB 22) ; infix minus
504 (defvar js2-MUL 23)
505 (defvar js2-DIV 24)
506 (defvar js2-MOD 25)
507 (defvar js2-NOT 26)
508 (defvar js2-BITNOT 27)
509 (defvar js2-POS 28) ; unary plus
510 (defvar js2-NEG 29) ; unary minus
511 (defvar js2-NEW 30)
512 (defvar js2-DELPROP 31)
513 (defvar js2-TYPEOF 32)
514 (defvar js2-GETPROP 33)
515 (defvar js2-GETPROPNOWARN 34)
516 (defvar js2-SETPROP 35)
517 (defvar js2-GETELEM 36)
518 (defvar js2-SETELEM 37)
519 (defvar js2-CALL 38)
520 (defvar js2-NAME 39) ; an identifier
521 (defvar js2-NUMBER 40)
522 (defvar js2-STRING 41)
523 (defvar js2-NULL 42)
524 (defvar js2-THIS 43)
525 (defvar js2-FALSE 44)
526 (defvar js2-TRUE 45)
527 (defvar js2-SHEQ 46) ; shallow equality (===)
528 (defvar js2-SHNE 47) ; shallow inequality (!==)
529 (defvar js2-REGEXP 48)
530 (defvar js2-BINDNAME 49)
531 (defvar js2-THROW 50)
532 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
533 (defvar js2-IN 52)
534 (defvar js2-INSTANCEOF 53)
535 (defvar js2-LOCAL_LOAD 54)
536 (defvar js2-GETVAR 55)
537 (defvar js2-SETVAR 56)
538 (defvar js2-CATCH_SCOPE 57)
539 (defvar js2-ENUM_INIT_KEYS 58)
540 (defvar js2-ENUM_INIT_VALUES 59)
541 (defvar js2-ENUM_INIT_ARRAY 60)
542 (defvar js2-ENUM_NEXT 61)
543 (defvar js2-ENUM_ID 62)
544 (defvar js2-THISFN 63)
545 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
546 (defvar js2-ARRAYLIT 65) ; array literal
547 (defvar js2-OBJECTLIT 66) ; object literal
548 (defvar js2-GET_REF 67) ; *reference
549 (defvar js2-SET_REF 68) ; *reference = something
550 (defvar js2-DEL_REF 69) ; delete reference
551 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
552 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
553 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
554
555 ;; XML support
556 (defvar js2-DEFAULTNAMESPACE 73)
557 (defvar js2-ESCXMLATTR 74)
558 (defvar js2-ESCXMLTEXT 75)
559 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
560 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
561 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
562 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
563
564 (defvar js2-first-bytecode js2-ENTERWITH)
565 (defvar js2-last-bytecode js2-REF_NS_NAME)
566
567 (defvar js2-TRY 80)
568 (defvar js2-SEMI 81) ; semicolon
569 (defvar js2-LB 82) ; left and right brackets
570 (defvar js2-RB 83)
571 (defvar js2-LC 84) ; left and right curly-braces
572 (defvar js2-RC 85)
573 (defvar js2-LP 86) ; left and right parens
574 (defvar js2-RP 87)
575 (defvar js2-COMMA 88) ; comma operator
576
577 (defvar js2-ASSIGN 89) ; simple assignment (=)
578 (defvar js2-ASSIGN_BITOR 90) ; |=
579 (defvar js2-ASSIGN_BITXOR 91) ; ^=
580 (defvar js2-ASSIGN_BITAND 92) ; &=
581 (defvar js2-ASSIGN_LSH 93) ; <<=
582 (defvar js2-ASSIGN_RSH 94) ; >>=
583 (defvar js2-ASSIGN_URSH 95) ; >>>=
584 (defvar js2-ASSIGN_ADD 96) ; +=
585 (defvar js2-ASSIGN_SUB 97) ; -=
586 (defvar js2-ASSIGN_MUL 98) ; *=
587 (defvar js2-ASSIGN_DIV 99) ; /=
588 (defvar js2-ASSIGN_MOD 100) ; %=
589
590 (defvar js2-first-assign js2-ASSIGN)
591 (defvar js2-last-assign js2-ASSIGN_MOD)
592
593 (defvar js2-HOOK 101) ; conditional (?:)
594 (defvar js2-COLON 102)
595 (defvar js2-OR 103) ; logical or (||)
596 (defvar js2-AND 104) ; logical and (&&)
597 (defvar js2-INC 105) ; increment/decrement (++ --)
598 (defvar js2-DEC 106)
599 (defvar js2-DOT 107) ; member operator (.)
600 (defvar js2-FUNCTION 108) ; function keyword
601 (defvar js2-EXPORT 109) ; export keyword
602 (defvar js2-IMPORT 110) ; import keyword
603 (defvar js2-IF 111) ; if keyword
604 (defvar js2-ELSE 112) ; else keyword
605 (defvar js2-SWITCH 113) ; switch keyword
606 (defvar js2-CASE 114) ; case keyword
607 (defvar js2-DEFAULT 115) ; default keyword
608 (defvar js2-WHILE 116) ; while keyword
609 (defvar js2-DO 117) ; do keyword
610 (defvar js2-FOR 118) ; for keyword
611 (defvar js2-BREAK 119) ; break keyword
612 (defvar js2-CONTINUE 120) ; continue keyword
613 (defvar js2-VAR 121) ; var keyword
614 (defvar js2-WITH 122) ; with keyword
615 (defvar js2-CATCH 123) ; catch keyword
616 (defvar js2-FINALLY 124) ; finally keyword
617 (defvar js2-VOID 125) ; void keyword
618 (defvar js2-RESERVED 126) ; reserved keywords
619
620 (defvar js2-EMPTY 127)
621
622 ;; Types used for the parse tree - never returned by scanner.
623
624 (defvar js2-BLOCK 128) ; statement block
625 (defvar js2-LABEL 129) ; label
626 (defvar js2-TARGET 130)
627 (defvar js2-LOOP 131)
628 (defvar js2-EXPR_VOID 132) ; expression statement in functions
629 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
630 (defvar js2-JSR 134)
631 (defvar js2-SCRIPT 135) ; top-level node for entire script
632 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
633 (defvar js2-USE_STACK 137)
634 (defvar js2-SETPROP_OP 138) ; x.y op= something
635 (defvar js2-SETELEM_OP 139) ; x[y] op= something
636 (defvar js2-LOCAL_BLOCK 140)
637 (defvar js2-SET_REF_OP 141) ; *reference op= something
638
639 ;; For XML support:
640 (defvar js2-DOTDOT 142) ; member operator (..)
641 (defvar js2-COLONCOLON 143) ; namespace::name
642 (defvar js2-XML 144) ; XML type
643 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
644 (defvar js2-XMLATTR 146) ; @
645 (defvar js2-XMLEND 147)
646
647 ;; Optimizer-only tokens
648 (defvar js2-TO_OBJECT 148)
649 (defvar js2-TO_DOUBLE 149)
650
651 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
652 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
653 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
654 (defvar js2-CONST 153)
655 (defvar js2-SETCONST 154)
656 (defvar js2-SETCONSTVAR 155)
657 (defvar js2-ARRAYCOMP 156)
658 (defvar js2-LETEXPR 157)
659 (defvar js2-WITHEXPR 158)
660 (defvar js2-DEBUGGER 159)
661
662 (defvar js2-COMMENT 160)
663 (defvar js2-ENUM 161) ; for "enum" reserved word
664
665 (defconst js2-num-tokens (1+ js2-ENUM))
666
667 (defconst js2-debug-print-trees nil)
668
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
672 ;; scanning them.
673
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
676
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
680
681 (js2-deflocal js2-ts-regexp-flags nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-string ""
685 "Token stream buffer-local variable.
686 Last string scanned.")
687
688 (js2-deflocal js2-ts-number nil
689 "Token stream buffer-local variable.
690 Last literal number scanned.")
691
692 (js2-deflocal js2-ts-hit-eof nil
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-line-start 0
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-lineno 1
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-line-end-char -1
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
705 "Token stream buffer-local variable.
706 Current scan position.")
707
708 (js2-deflocal js2-ts-is-xml-attribute nil
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-xml-is-tag-content nil
712 "Token stream buffer-local variable.")
713
714 (js2-deflocal js2-ts-xml-open-tags-count 0
715 "Token stream buffer-local variable.")
716
717 (js2-deflocal js2-ts-string-buffer nil
718 "Token stream buffer-local variable.
719 List of chars built up while scanning various tokens.")
720
721 (js2-deflocal js2-ts-comment-type nil
722 "Token stream buffer-local variable.")
723
724 ;;; Parser variables
725
726 (js2-deflocal js2-parsed-errors nil
727 "List of errors produced during scanning/parsing.")
728
729 (js2-deflocal js2-parsed-warnings nil
730 "List of warnings produced during scanning/parsing.")
731
732 (js2-deflocal js2-recover-from-parse-errors t
733 "Non-nil to continue parsing after a syntax error.
734
735 In recovery mode, the AST will be built in full, and any error
736 nodes will be flagged with appropriate error information. If
737 this flag is nil, a syntax error will result in an error being
738 signaled.
739
740 The variable is automatically buffer-local, because different
741 modes that use the parser will need different settings.")
742
743 (js2-deflocal js2-parse-hook nil
744 "List of callbacks for receiving parsing progress.")
745
746 (defvar js2-parse-finished-hook nil
747 "List of callbacks to notify when parsing finishes.
748 Not called if parsing was interrupted.")
749
750 (js2-deflocal js2-is-eval-code nil
751 "True if we're evaluating code in a string.
752 If non-nil, the tokenizer will record the token text, and the AST nodes
753 will record their source text. Off by default for IDE modes, since the
754 text is available in the buffer.")
755
756 (defvar js2-parse-ide-mode t
757 "Non-nil if the parser is being used for `js2-mode'.
758 If non-nil, the parser will set text properties for fontification
759 and the syntax table. The value should be nil when using the
760 parser as a frontend to an interpreter or byte compiler.")
761
762 ;;; Parser instance variables (buffer-local vars for js2-parse)
763
764 (defconst js2-clear-ti-mask #xFFFF
765 "Mask to clear token information bits.")
766
767 (defconst js2-ti-after-eol (lsh 1 16)
768 "Flag: first token of the source line.")
769
770 (defconst js2-ti-check-label (lsh 1 17)
771 "Flag: indicates to check for label.")
772
773 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
774
775 (js2-deflocal js2-compiler-generate-debug-info t)
776 (js2-deflocal js2-compiler-use-dynamic-scope nil)
777 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
778 (js2-deflocal js2-compiler-xml-available t)
779 (js2-deflocal js2-compiler-optimization-level 0)
780 (js2-deflocal js2-compiler-generating-source t)
781 (js2-deflocal js2-compiler-strict-mode nil)
782 (js2-deflocal js2-compiler-report-warning-as-error nil)
783 (js2-deflocal js2-compiler-generate-observer-count nil)
784 (js2-deflocal js2-compiler-activation-names nil)
785
786 ;; SKIP: sourceURI
787
788 ;; There's a compileFunction method in Context.java - may need it.
789 (js2-deflocal js2-called-by-compile-function nil
790 "True if `js2-parse' was called by `js2-compile-function'.
791 Will only be used when we finish implementing the interpreter.")
792
793 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
794
795 (js2-deflocal js2-current-flagged-token js2-EOF)
796 (js2-deflocal js2-current-token js2-EOF)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (defmacro js2-in-lhs (body)
807 `(let ((js2-is-in-lhs t))
808 ,body))
809
810 (defmacro js2-in-rhs (body)
811 `(let ((js2-is-in-lhs nil))
812 ,body))
813
814 (js2-deflocal js2-is-in-lhs nil
815 "True while parsing lhs statement")
816
817 (defcustom js2-global-externs nil
818 "A list of any extern names you'd like to consider always declared.
819 This list is global and is used by all js2-mode files.
820 You can create buffer-local externs list using `js2-additional-externs'.
821
822 There is also a buffer-local variable `js2-default-externs',
823 which is initialized by default to include the Ecma-262 externs
824 and the standard browser externs. The three lists are all
825 checked during highlighting."
826 :type 'list
827 :group 'js2-mode)
828
829 (js2-deflocal js2-default-externs nil
830 "Default external declarations.
831
832 These are currently only used for highlighting undeclared variables,
833 which only worries about top-level (unqualified) references.
834 As js2-mode's processing improves, we will flesh out this list.
835
836 The initial value is set to `js2-ecma-262-externs', unless you
837 have set `js2-include-browser-externs', in which case the browser
838 externs are also included.
839
840 See `js2-additional-externs' for more information.")
841
842 (defcustom js2-include-browser-externs t
843 "Non-nil to include browser externs in the master externs list.
844 If you work on JavaScript files that are not intended for browsers,
845 such as Mozilla Rhino server-side JavaScript, set this to nil.
846 You can always include them on a per-file basis by calling
847 `js2-add-browser-externs' from a function on `js2-mode-hook'.
848
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-rhino-externs t
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (defcustom js2-include-gears-externs t
860 "Non-nil to include Google Gears externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
862 :type 'boolean
863 :group 'js2-mode)
864
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
869
870 Each entry is a lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
873
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
878
879 Next, you can add a function to `js2-mode-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
882
883 Finally, you can add a function to `js2-post-parse-callbacks',
884 which is called after parsing completes, and `root' is bound to
885 the root of the parse tree. At this stage you can set up an AST
886 node visitor using `js2-visit-ast' and examine the parse tree
887 for specific import patterns that may imply the existence of
888 other externs, possibly tied to your build system. These should also
889 be added to `js2-additional-externs'.
890
891 Your post-parse callback may of course also use the simpler and
892 faster (but perhaps less robust) approach of simply scanning the
893 buffer text for your imports, using regular expressions.")
894
895 ;; SKIP: decompiler
896 ;; SKIP: encoded-source
897
898 ;;; The following variables are per-function and should be saved/restored
899 ;;; during function parsing...
900
901 (js2-deflocal js2-current-script-or-fn nil)
902 (js2-deflocal js2-current-scope nil)
903 (js2-deflocal js2-nesting-of-with 0)
904 (js2-deflocal js2-label-set nil
905 "An alist mapping label names to nodes.")
906
907 (js2-deflocal js2-loop-set nil)
908 (js2-deflocal js2-loop-and-switch-set nil)
909 (js2-deflocal js2-has-return-value nil)
910 (js2-deflocal js2-end-flags 0)
911
912 ;;; ...end of per function variables
913
914 ;; Without 2-token lookahead, labels are a problem.
915 ;; These vars store the token info of the last matched name,
916 ;; iff it wasn't the last matched token. Only valid in some contexts.
917 (defvar js2-prev-name-token-start nil)
918 (defvar js2-prev-name-token-string nil)
919
920 (defsubst js2-save-name-token-data (pos name)
921 (setq js2-prev-name-token-start pos
922 js2-prev-name-token-string name))
923
924 ;; These flags enumerate the possible ways a statement/function can
925 ;; terminate. These flags are used by endCheck() and by the Parser to
926 ;; detect inconsistent return usage.
927 ;;
928 ;; END_UNREACHED is reserved for code paths that are assumed to always be
929 ;; able to execute (example: throw, continue)
930 ;;
931 ;; END_DROPS_OFF indicates if the statement can transfer control to the
932 ;; next one. Statement such as return dont. A compound statement may have
933 ;; some branch that drops off control to the next statement.
934 ;;
935 ;; END_RETURNS indicates that the statement can return (without arguments)
936 ;; END_RETURNS_VALUE indicates that the statement can return a value.
937 ;;
938 ;; A compound statement such as
939 ;; if (condition) {
940 ;; return value;
941 ;; }
942 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
943
944 (defconst js2-end-unreached #x0)
945 (defconst js2-end-drops-off #x1)
946 (defconst js2-end-returns #x2)
947 (defconst js2-end-returns-value #x4)
948 (defconst js2-end-yields #x8)
949
950 ;; Rhino awkwardly passes a statementLabel parameter to the
951 ;; statementHelper() function, the main statement parser, which
952 ;; is then used by quite a few of the sub-parsers. We just make
953 ;; it a buffer-local variable and make sure it's cleaned up properly.
954 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
955
956 ;; Similarly, Rhino passes an inForInit boolean through about half
957 ;; the expression parsers. We use a dynamically-scoped variable,
958 ;; which makes it easier to funcall the parsers individually without
959 ;; worrying about whether they take the parameter or not.
960 (js2-deflocal js2-in-for-init nil)
961 (js2-deflocal js2-temp-name-counter 0)
962 (js2-deflocal js2-parse-stmt-count 0)
963
964 (defsubst js2-get-next-temp-name ()
965 (format "$%d" (incf js2-temp-name-counter)))
966
967 (defvar js2-parse-interruptable-p t
968 "Set this to nil to force parse to continue until finished.
969 This will mostly be useful for interpreters.")
970
971 (defvar js2-statements-per-pause 50
972 "Pause after this many statements to check for user input.
973 If user input is pending, stop the parse and discard the tree.
974 This makes for a smoother user experience for large files.
975 You may have to wait a second or two before the highlighting
976 and error-reporting appear, but you can always type ahead if
977 you wish. This appears to be more or less how Eclipse, IntelliJ
978 and other editors work.")
979
980 (js2-deflocal js2-record-comments t
981 "Instructs the scanner to record comments in `js2-scanned-comments'.")
982
983 (js2-deflocal js2-scanned-comments nil
984 "List of all comments from the current parse.")
985
986 (defcustom js2-mode-indent-inhibit-undo nil
987 "Non-nil to disable collection of Undo information when indenting lines.
988 Some users have requested this behavior. It's nil by default because
989 other Emacs modes don't work this way."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defcustom js2-mode-indent-ignore-first-tab nil
994 "If non-nil, ignore first TAB keypress if we look indented properly.
995 It's fairly common for users to navigate to an already-indented line
996 and press TAB for reassurance that it's been indented. For this class
997 of users, we want the first TAB press on a line to be ignored if the
998 line is already indented to one of the precomputed alternatives.
999
1000 This behavior is only partly implemented. If you TAB-indent a line,
1001 navigate to another line, and then navigate back, it fails to clear
1002 the last-indented variable, so it thinks you've already hit TAB once,
1003 and performs the indent. A full solution would involve getting on the
1004 point-motion hooks for the entire buffer. If we come across another
1005 use cases that requires watching point motion, I'll consider doing it.
1006
1007 If you set this variable to nil, then the TAB key will always change
1008 the indentation of the current line, if more than one alternative
1009 indentation spot exists."
1010 :type 'boolean
1011 :group 'js2-mode)
1012
1013 (defvar js2-indent-hook nil
1014 "A hook for user-defined indentation rules.
1015
1016 Functions on this hook should expect two arguments: (LIST INDEX)
1017 The LIST argument is the list of computed indentation points for
1018 the current line. INDEX is the list index of the indentation point
1019 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1020 indent function is not going to change the current line indentation.
1021
1022 If a hook function on this list returns a non-nil value, then
1023 `js2-bounce-indent' assumes the hook function has performed its own
1024 indentation, and will do nothing. If all hook functions on the list
1025 return nil, then `js2-bounce-indent' will use its computed indentation
1026 and reindent the line.
1027
1028 When hook functions on this hook list are called, the variable
1029 `js2-mode-ast' may or may not be set, depending on whether the
1030 parse tree is available. If the variable is nil, you can pass a
1031 callback to `js2-mode-wait-for-parse', and your callback will be
1032 called after the new parse tree is built. This can take some time
1033 in large files.")
1034
1035 (defface js2-warning-face
1036 `((((class color) (background light))
1037 (:underline "orange"))
1038 (((class color) (background dark))
1039 (:underline "orange"))
1040 (t (:underline t)))
1041 "Face for JavaScript warnings."
1042 :group 'js2-mode)
1043
1044 (defface js2-error-face
1045 `((((class color) (background light))
1046 (:foreground "red"))
1047 (((class color) (background dark))
1048 (:foreground "red"))
1049 (t (:foreground "red")))
1050 "Face for JavaScript errors."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-tag-face
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1056 :group 'js2-mode)
1057
1058 (defface js2-jsdoc-type-face
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-value-face
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1066 :group 'js2-mode)
1067
1068 (defface js2-function-param-face
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1071 :group 'js2-mode)
1072
1073 (defface js2-instance-member-face
1074 '((t :foreground "DarkOrchid"))
1075 "Face used to highlight instance variables in javascript.
1076 Not currently used."
1077 :group 'js2-mode)
1078
1079 (defface js2-private-member-face
1080 '((t :foreground "PeachPuff3"))
1081 "Face used to highlight calls to private methods in javascript.
1082 Not currently used."
1083 :group 'js2-mode)
1084
1085 (defface js2-private-function-call-face
1086 '((t :foreground "goldenrod"))
1087 "Face used to highlight calls to private functions in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-jsdoc-html-tag-name-face
1092 (if js2-emacs22
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "rosybrown"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "yellow"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "magenta")))
1099 '((((type tty pc) (class color) (background light))
1100 (:foreground "magenta"))
1101 (((type tty pc) (class color) (background dark))
1102 (:foreground "yellow"))
1103 (t (:foreground "RosyBrown"))))
1104 "Face used to highlight jsdoc html tag names"
1105 :group 'js2-mode)
1106
1107 (defface js2-jsdoc-html-tag-delimiter-face
1108 (if js2-emacs22
1109 '((((class color) (min-colors 88) (background light))
1110 (:foreground "dark khaki"))
1111 (((class color) (min-colors 8) (background dark))
1112 (:foreground "green"))
1113 (((class color) (min-colors 8) (background light))
1114 (:foreground "green")))
1115 '((((type tty pc) (class color) (background light))
1116 (:foreground "green"))
1117 (((type tty pc) (class color) (background dark))
1118 (:foreground "green"))
1119 (t (:foreground "dark khaki"))))
1120 "Face used to highlight brackets in jsdoc html tags."
1121 :group 'js2-mode)
1122
1123 (defface js2-magic-paren-face
1124 '((t :underline t))
1125 "Face used to color parens that will be auto-overwritten."
1126 :group 'js2-mode)
1127
1128 (defcustom js2-post-parse-callbacks nil
1129 "A list of callback functions invoked after parsing finishes.
1130 Currently, the main use for this function is to add synthetic
1131 declarations to `js2-recorded-identifiers', which see."
1132 :type 'list
1133 :group 'js2-mode)
1134
1135 (defface js2-external-variable-face
1136 '((t :foreground "orange"))
1137 "Face used to highlight undeclared variable identifiers.
1138 An undeclared variable is any variable not declared with var or let
1139 in the current scope or any lexically enclosing scope. If you use
1140 such a variable, then you are either expecting it to originate from
1141 another file, or you've got a potential bug."
1142 :group 'js2-mode)
1143
1144 (defcustom js2-highlight-external-variables t
1145 "Non-nil to highlight undeclared variable identifiers."
1146 :type 'boolean
1147 :group 'js2-mode)
1148
1149 (defcustom js2-auto-insert-catch-block t
1150 "Non-nil to insert matching catch block on open-curly after `try'."
1151 :type 'boolean
1152 :group 'js2-mode)
1153
1154 (defvar js2-mode-map
1155 (let ((map (make-sparse-keymap))
1156 keys)
1157 (define-key map [mouse-1] #'js2-mode-show-node)
1158 (define-key map (kbd "C-m") #'js2-enter-key)
1159 (when js2-rebind-eol-bol-keys
1160 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1161 (define-key map (kbd "C-e") #'js2-end-of-line))
1162 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1163 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1164 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1165 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1166 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1167 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1168 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1169 (define-key map (kbd "C-c C-`") #'js2-next-error)
1170 ;; also define user's preference for next-error, if available
1171 (if (setq keys (where-is-internal #'next-error))
1172 (define-key map (car keys) #'js2-next-error))
1173 (define-key map (or (car (where-is-internal #'mark-defun))
1174 (kbd "M-C-h"))
1175 #'js2-mark-defun)
1176 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1177 (kbd "C-x nd"))
1178 #'js2-narrow-to-defun)
1179 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1180 (when js2-auto-indent-p
1181 (mapc (lambda (key)
1182 (define-key map key #'js2-insert-and-indent))
1183 js2-electric-keys))
1184
1185 (define-key map [menu-bar javascript]
1186 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1187
1188 (define-key map [menu-bar javascript customize-js2-mode]
1189 '(menu-item "Customize js2-mode" js2-mode-customize
1190 :help "Customize the behavior of this mode"))
1191
1192 (define-key map [menu-bar javascript js2-force-refresh]
1193 '(menu-item "Force buffer refresh" js2-mode-reset
1194 :help "Re-parse the buffer from scratch"))
1195
1196 (define-key map [menu-bar javascript separator-2]
1197 '("--"))
1198
1199 (define-key map [menu-bar javascript next-error]
1200 '(menu-item "Next warning or error" js2-next-error
1201 :enabled (and js2-mode-ast
1202 (or (js2-ast-root-errors js2-mode-ast)
1203 (js2-ast-root-warnings js2-mode-ast)))
1204 :help "Move to next warning or error"))
1205
1206 (define-key map [menu-bar javascript display-errors]
1207 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1208 :visible (not js2-mode-show-parse-errors)
1209 :help "Turn on display of warnings and errors"))
1210
1211 (define-key map [menu-bar javascript hide-errors]
1212 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1213 :visible js2-mode-show-parse-errors
1214 :help "Turn off display of warnings and errors"))
1215
1216 (define-key map [menu-bar javascript separator-1]
1217 '("--"))
1218
1219 (define-key map [menu-bar javascript js2-toggle-function]
1220 '(menu-item "Show/collapse element" js2-mode-toggle-element
1221 :help "Hide or show function body or comment"))
1222
1223 (define-key map [menu-bar javascript show-comments]
1224 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1225 :visible js2-mode-comments-hidden
1226 :help "Expand all hidden block comments"))
1227
1228 (define-key map [menu-bar javascript hide-comments]
1229 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1230 :visible (not js2-mode-comments-hidden)
1231 :help "Show block comments as /*...*/"))
1232
1233 (define-key map [menu-bar javascript show-all-functions]
1234 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1235 :visible js2-mode-functions-hidden
1236 :help "Expand all hidden function bodies"))
1237
1238 (define-key map [menu-bar javascript hide-all-functions]
1239 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1240 :visible (not js2-mode-functions-hidden)
1241 :help "Show {...} for all top-level function bodies"))
1242
1243 map)
1244 "Keymap used in `js2-mode' buffers.")
1245
1246 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1247
1248 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1249 "Matches a //-comment line. Must be first non-whitespace on line.
1250 First match-group is the leading whitespace.")
1251
1252 (defvar js2-mode-hook nil)
1253
1254 (js2-deflocal js2-mode-ast nil "Private variable.")
1255 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1256 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1257 (js2-deflocal js2-mode-parsing nil "Private variable.")
1258 (js2-deflocal js2-mode-node-overlay nil)
1259
1260 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1261 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1262
1263 (js2-deflocal js2-mode-fontifications nil "Private variable")
1264 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1265 (js2-deflocal js2-imenu-recorder nil "Private variable")
1266 (js2-deflocal js2-imenu-function-map nil "Private variable")
1267
1268 (defvar js2-paragraph-start
1269 "\\(@[a-zA-Z]+\\>\\|$\\)")
1270
1271 ;; Note that we also set a 'c-in-sws text property in html comments,
1272 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1273 (defvar js2-syntactic-ws-start
1274 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1275
1276 (defvar js2-syntactic-ws-end
1277 "\\s \\|[\n\r/]\\|\\s!")
1278
1279 (defvar js2-syntactic-eol
1280 (concat "\\s *\\(/\\*[^*\n\r]*"
1281 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1282 "\\*+/\\s *\\)*"
1283 "\\(//\\|/\\*[^*\n\r]*"
1284 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1285 "\\|\\\\$\\|$\\)")
1286 "Copied from `java-mode'. Needed for some cc-engine functions.")
1287
1288 (defvar js2-comment-prefix-regexp
1289 "//+\\|\\**")
1290
1291 (defvar js2-comment-start-skip
1292 "\\(//+\\|/\\*+\\)\\s *")
1293
1294 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1295 "Non-nil to emit status messages during parsing.")
1296
1297 (defvar js2-mode-functions-hidden nil "private variable")
1298 (defvar js2-mode-comments-hidden nil "private variable")
1299
1300 (defvar js2-mode-syntax-table
1301 (let ((table (make-syntax-table)))
1302 (c-populate-syntax-table table)
1303 table)
1304 "Syntax table used in js2-mode buffers.")
1305
1306 (defvar js2-mode-abbrev-table nil
1307 "Abbrev table in use in `js2-mode' buffers.")
1308 (define-abbrev-table 'js2-mode-abbrev-table ())
1309
1310 (defvar js2-mode-pending-parse-callbacks nil
1311 "List of functions waiting to be notified that parse is finished.")
1312
1313 (defvar js2-mode-last-indented-line -1)
1314
1315 ;;; Localizable error and warning messages
1316
1317 ;; Messages are copied from Rhino's Messages.properties.
1318 ;; Many of the Java-specific messages have been elided.
1319 ;; Add any js2-specific ones at the end, so we can keep
1320 ;; this file synced with changes to Rhino's.
1321
1322 (defvar js2-message-table
1323 (make-hash-table :test 'equal :size 250)
1324 "Contains localized messages for js2-mode.")
1325
1326 ;; TODO(stevey): construct this table at compile-time.
1327 (defmacro js2-msg (key &rest strings)
1328 `(puthash ,key (funcall #'concat ,@strings)
1329 js2-message-table))
1330
1331 (defun js2-get-msg (msg-key)
1332 "Look up a localized message.
1333 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1334 the correct number of ARGS must be provided."
1335 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1336 (args (if (listp msg-key) (cdr msg-key)))
1337 (msg (gethash key js2-message-table)))
1338 (if msg
1339 (apply #'format msg args)
1340 key))) ; default to showing the key
1341
1342 (js2-msg "msg.dup.parms"
1343 "Duplicate parameter name '%s'.")
1344
1345 (js2-msg "msg.too.big.jump"
1346 "Program too complex: jump offset too big.")
1347
1348 (js2-msg "msg.too.big.index"
1349 "Program too complex: internal index exceeds 64K limit.")
1350
1351 (js2-msg "msg.while.compiling.fn"
1352 "Encountered code generation error while compiling function '%s': %s")
1353
1354 (js2-msg "msg.while.compiling.script"
1355 "Encountered code generation error while compiling script: %s")
1356
1357 ;; Context
1358 (js2-msg "msg.ctor.not.found"
1359 "Constructor for '%s' not found.")
1360
1361 (js2-msg "msg.not.ctor"
1362 "'%s' is not a constructor.")
1363
1364 ;; FunctionObject
1365 (js2-msg "msg.varargs.ctor"
1366 "Method or constructor '%s' must be static "
1367 "with the signature (Context cx, Object[] args, "
1368 "Function ctorObj, boolean inNewExpr) "
1369 "to define a variable arguments constructor.")
1370
1371 (js2-msg "msg.varargs.fun"
1372 "Method '%s' must be static with the signature "
1373 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1374 "to define a variable arguments function.")
1375
1376 (js2-msg "msg.incompat.call"
1377 "Method '%s' called on incompatible object.")
1378
1379 (js2-msg "msg.bad.parms"
1380 "Unsupported parameter type '%s' in method '%s'.")
1381
1382 (js2-msg "msg.bad.method.return"
1383 "Unsupported return type '%s' in method '%s'.")
1384
1385 (js2-msg "msg.bad.ctor.return"
1386 "Construction of objects of type '%s' is not supported.")
1387
1388 (js2-msg "msg.no.overload"
1389 "Method '%s' occurs multiple times in class '%s'.")
1390
1391 (js2-msg "msg.method.not.found"
1392 "Method '%s' not found in '%s'.")
1393
1394 ;; IRFactory
1395
1396 (js2-msg "msg.bad.for.in.lhs"
1397 "Invalid left-hand side of for..in loop.")
1398
1399 (js2-msg "msg.mult.index"
1400 "Only one variable allowed in for..in loop.")
1401
1402 (js2-msg "msg.bad.for.in.destruct"
1403 "Left hand side of for..in loop must be an array of "
1404 "length 2 to accept key/value pair.")
1405
1406 (js2-msg "msg.cant.convert"
1407 "Can't convert to type '%s'.")
1408
1409 (js2-msg "msg.bad.assign.left"
1410 "Invalid assignment left-hand side.")
1411
1412 (js2-msg "msg.bad.decr"
1413 "Invalid decerement operand.")
1414
1415 (js2-msg "msg.bad.incr"
1416 "Invalid increment operand.")
1417
1418 (js2-msg "msg.bad.yield"
1419 "yield must be in a function.")
1420
1421 (js2-msg "msg.yield.parenthesized"
1422 "yield expression must be parenthesized.")
1423
1424 ;; NativeGlobal
1425 (js2-msg "msg.cant.call.indirect"
1426 "Function '%s' must be called directly, and not by way of a "
1427 "function of another name.")
1428
1429 (js2-msg "msg.eval.nonstring"
1430 "Calling eval() with anything other than a primitive "
1431 "string value will simply return the value. "
1432 "Is this what you intended?")
1433
1434 (js2-msg "msg.eval.nonstring.strict"
1435 "Calling eval() with anything other than a primitive "
1436 "string value is not allowed in strict mode.")
1437
1438 (js2-msg "msg.bad.destruct.op"
1439 "Invalid destructuring assignment operator")
1440
1441 ;; NativeCall
1442 (js2-msg "msg.only.from.new"
1443 "'%s' may only be invoked from a `new' expression.")
1444
1445 (js2-msg "msg.deprec.ctor"
1446 "The '%s' constructor is deprecated.")
1447
1448 ;; NativeFunction
1449 (js2-msg "msg.no.function.ref.found"
1450 "no source found to decompile function reference %s")
1451
1452 (js2-msg "msg.arg.isnt.array"
1453 "second argument to Function.prototype.apply must be an array")
1454
1455 ;; NativeGlobal
1456 (js2-msg "msg.bad.esc.mask"
1457 "invalid string escape mask")
1458
1459 ;; NativeRegExp
1460 (js2-msg "msg.bad.quant"
1461 "Invalid quantifier %s")
1462
1463 (js2-msg "msg.overlarge.backref"
1464 "Overly large back reference %s")
1465
1466 (js2-msg "msg.overlarge.min"
1467 "Overly large minimum %s")
1468
1469 (js2-msg "msg.overlarge.max"
1470 "Overly large maximum %s")
1471
1472 (js2-msg "msg.zero.quant"
1473 "Zero quantifier %s")
1474
1475 (js2-msg "msg.max.lt.min"
1476 "Maximum %s less than minimum")
1477
1478 (js2-msg "msg.unterm.quant"
1479 "Unterminated quantifier %s")
1480
1481 (js2-msg "msg.unterm.paren"
1482 "Unterminated parenthetical %s")
1483
1484 (js2-msg "msg.unterm.class"
1485 "Unterminated character class %s")
1486
1487 (js2-msg "msg.bad.range"
1488 "Invalid range in character class.")
1489
1490 (js2-msg "msg.trail.backslash"
1491 "Trailing \\ in regular expression.")
1492
1493 (js2-msg "msg.re.unmatched.right.paren"
1494 "unmatched ) in regular expression.")
1495
1496 (js2-msg "msg.no.regexp"
1497 "Regular expressions are not available.")
1498
1499 (js2-msg "msg.bad.backref"
1500 "back-reference exceeds number of capturing parentheses.")
1501
1502 (js2-msg "msg.bad.regexp.compile"
1503 "Only one argument may be specified if the first "
1504 "argument to RegExp.prototype.compile is a RegExp object.")
1505
1506 ;; Parser
1507 (js2-msg "msg.got.syntax.errors"
1508 "Compilation produced %s syntax errors.")
1509
1510 (js2-msg "msg.var.redecl"
1511 "TypeError: redeclaration of var %s.")
1512
1513 (js2-msg "msg.const.redecl"
1514 "TypeError: redeclaration of const %s.")
1515
1516 (js2-msg "msg.let.redecl"
1517 "TypeError: redeclaration of variable %s.")
1518
1519 (js2-msg "msg.parm.redecl"
1520 "TypeError: redeclaration of formal parameter %s.")
1521
1522 (js2-msg "msg.fn.redecl"
1523 "TypeError: redeclaration of function %s.")
1524
1525 (js2-msg "msg.let.decl.not.in.block"
1526 "SyntaxError: let declaration not directly within block")
1527
1528 ;; NodeTransformer
1529 (js2-msg "msg.dup.label"
1530 "duplicated label")
1531
1532 (js2-msg "msg.undef.label"
1533 "undefined label")
1534
1535 (js2-msg "msg.bad.break"
1536 "unlabelled break must be inside loop or switch")
1537
1538 (js2-msg "msg.continue.outside"
1539 "continue must be inside loop")
1540
1541 (js2-msg "msg.continue.nonloop"
1542 "continue can only use labels of iteration statements")
1543
1544 (js2-msg "msg.bad.throw.eol"
1545 "Line terminator is not allowed between the throw "
1546 "keyword and throw expression.")
1547
1548 (js2-msg "msg.no.paren.parms"
1549 "missing ( before function parameters.")
1550
1551 (js2-msg "msg.no.parm"
1552 "missing formal parameter")
1553
1554 (js2-msg "msg.no.paren.after.parms"
1555 "missing ) after formal parameters")
1556
1557 (js2-msg "msg.no.brace.body"
1558 "missing '{' before function body")
1559
1560 (js2-msg "msg.no.brace.after.body"
1561 "missing } after function body")
1562
1563 (js2-msg "msg.no.paren.cond"
1564 "missing ( before condition")
1565
1566 (js2-msg "msg.no.paren.after.cond"
1567 "missing ) after condition")
1568
1569 (js2-msg "msg.no.semi.stmt"
1570 "missing ; before statement")
1571
1572 (js2-msg "msg.missing.semi"
1573 "missing ; after statement")
1574
1575 (js2-msg "msg.no.name.after.dot"
1576 "missing name after . operator")
1577
1578 (js2-msg "msg.no.name.after.coloncolon"
1579 "missing name after :: operator")
1580
1581 (js2-msg "msg.no.name.after.dotdot"
1582 "missing name after .. operator")
1583
1584 (js2-msg "msg.no.name.after.xmlAttr"
1585 "missing name after .@")
1586
1587 (js2-msg "msg.no.bracket.index"
1588 "missing ] in index expression")
1589
1590 (js2-msg "msg.no.paren.switch"
1591 "missing ( before switch expression")
1592
1593 (js2-msg "msg.no.paren.after.switch"
1594 "missing ) after switch expression")
1595
1596 (js2-msg "msg.no.brace.switch"
1597 "missing '{' before switch body")
1598
1599 (js2-msg "msg.bad.switch"
1600 "invalid switch statement")
1601
1602 (js2-msg "msg.no.colon.case"
1603 "missing : after case expression")
1604
1605 (js2-msg "msg.double.switch.default"
1606 "double default label in the switch statement")
1607
1608 (js2-msg "msg.no.while.do"
1609 "missing while after do-loop body")
1610
1611 (js2-msg "msg.no.paren.for"
1612 "missing ( after for")
1613
1614 (js2-msg "msg.no.semi.for"
1615 "missing ; after for-loop initializer")
1616
1617 (js2-msg "msg.no.semi.for.cond"
1618 "missing ; after for-loop condition")
1619
1620 (js2-msg "msg.in.after.for.name"
1621 "missing in after for")
1622
1623 (js2-msg "msg.no.paren.for.ctrl"
1624 "missing ) after for-loop control")
1625
1626 (js2-msg "msg.no.paren.with"
1627 "missing ( before with-statement object")
1628
1629 (js2-msg "msg.no.paren.after.with"
1630 "missing ) after with-statement object")
1631
1632 (js2-msg "msg.no.paren.after.let"
1633 "missing ( after let")
1634
1635 (js2-msg "msg.no.paren.let"
1636 "missing ) after variable list")
1637
1638 (js2-msg "msg.no.curly.let"
1639 "missing } after let statement")
1640
1641 (js2-msg "msg.bad.return"
1642 "invalid return")
1643
1644 (js2-msg "msg.no.brace.block"
1645 "missing } in compound statement")
1646
1647 (js2-msg "msg.bad.label"
1648 "invalid label")
1649
1650 (js2-msg "msg.bad.var"
1651 "missing variable name")
1652
1653 (js2-msg "msg.bad.var.init"
1654 "invalid variable initialization")
1655
1656 (js2-msg "msg.no.colon.cond"
1657 "missing : in conditional expression")
1658
1659 (js2-msg "msg.no.paren.arg"
1660 "missing ) after argument list")
1661
1662 (js2-msg "msg.no.bracket.arg"
1663 "missing ] after element list")
1664
1665 (js2-msg "msg.bad.prop"
1666 "invalid property id")
1667
1668 (js2-msg "msg.no.colon.prop"
1669 "missing : after property id")
1670
1671 (js2-msg "msg.no.brace.prop"
1672 "missing } after property list")
1673
1674 (js2-msg "msg.no.paren"
1675 "missing ) in parenthetical")
1676
1677 (js2-msg "msg.reserved.id"
1678 "identifier is a reserved word")
1679
1680 (js2-msg "msg.no.paren.catch"
1681 "missing ( before catch-block condition")
1682
1683 (js2-msg "msg.bad.catchcond"
1684 "invalid catch block condition")
1685
1686 (js2-msg "msg.catch.unreachable"
1687 "any catch clauses following an unqualified catch are unreachable")
1688
1689 (js2-msg "msg.no.brace.try"
1690 "missing '{' before try block")
1691
1692 (js2-msg "msg.no.brace.catchblock"
1693 "missing '{' before catch-block body")
1694
1695 (js2-msg "msg.try.no.catchfinally"
1696 "'try' without 'catch' or 'finally'")
1697
1698 (js2-msg "msg.no.return.value"
1699 "function %s does not always return a value")
1700
1701 (js2-msg "msg.anon.no.return.value"
1702 "anonymous function does not always return a value")
1703
1704 (js2-msg "msg.return.inconsistent"
1705 "return statement is inconsistent with previous usage")
1706
1707 (js2-msg "msg.generator.returns"
1708 "TypeError: generator function '%s' returns a value")
1709
1710 (js2-msg "msg.anon.generator.returns"
1711 "TypeError: anonymous generator function returns a value")
1712
1713 (js2-msg "msg.syntax"
1714 "syntax error")
1715
1716 (js2-msg "msg.unexpected.eof"
1717 "Unexpected end of file")
1718
1719 (js2-msg "msg.XML.bad.form"
1720 "illegally formed XML syntax")
1721
1722 (js2-msg "msg.XML.not.available"
1723 "XML runtime not available")
1724
1725 (js2-msg "msg.too.deep.parser.recursion"
1726 "Too deep recursion while parsing")
1727
1728 (js2-msg "msg.no.side.effects"
1729 "Code has no side effects")
1730
1731 (js2-msg "msg.extra.trailing.comma"
1732 "Trailing comma is not legal in an ECMA-262 object initializer")
1733
1734 (js2-msg "msg.array.trailing.comma"
1735 "Trailing comma yields different behavior across browsers")
1736
1737 (js2-msg "msg.equal.as.assign"
1738 (concat "Test for equality (==) mistyped as assignment (=)?"
1739 " (parenthesize to suppress warning)"))
1740
1741 (js2-msg "msg.var.hides.arg"
1742 "Variable %s hides argument")
1743
1744 (js2-msg "msg.destruct.assign.no.init"
1745 "Missing = in destructuring declaration")
1746
1747 ;; ScriptRuntime
1748 (js2-msg "msg.no.properties"
1749 "%s has no properties.")
1750
1751 (js2-msg "msg.invalid.iterator"
1752 "Invalid iterator value")
1753
1754 (js2-msg "msg.iterator.primitive"
1755 "__iterator__ returned a primitive value")
1756
1757 (js2-msg "msg.assn.create.strict"
1758 "Assignment to undeclared variable %s")
1759
1760 (js2-msg "msg.ref.undefined.prop"
1761 "Reference to undefined property '%s'")
1762
1763 (js2-msg "msg.prop.not.found"
1764 "Property %s not found.")
1765
1766 (js2-msg "msg.invalid.type"
1767 "Invalid JavaScript value of type %s")
1768
1769 (js2-msg "msg.primitive.expected"
1770 "Primitive type expected (had %s instead)")
1771
1772 (js2-msg "msg.namespace.expected"
1773 "Namespace object expected to left of :: (found %s instead)")
1774
1775 (js2-msg "msg.null.to.object"
1776 "Cannot convert null to an object.")
1777
1778 (js2-msg "msg.undef.to.object"
1779 "Cannot convert undefined to an object.")
1780
1781 (js2-msg "msg.cyclic.value"
1782 "Cyclic %s value not allowed.")
1783
1784 (js2-msg "msg.is.not.defined"
1785 "'%s' is not defined.")
1786
1787 (js2-msg "msg.undef.prop.read"
1788 "Cannot read property '%s' from %s")
1789
1790 (js2-msg "msg.undef.prop.write"
1791 "Cannot set property '%s' of %s to '%s'")
1792
1793 (js2-msg "msg.undef.prop.delete"
1794 "Cannot delete property '%s' of %s")
1795
1796 (js2-msg "msg.undef.method.call"
1797 "Cannot call method '%s' of %s")
1798
1799 (js2-msg "msg.undef.with"
1800 "Cannot apply 'with' to %s")
1801
1802 (js2-msg "msg.isnt.function"
1803 "%s is not a function, it is %s.")
1804
1805 (js2-msg "msg.isnt.function.in"
1806 "Cannot call property %s in object %s. "
1807 "It is not a function, it is '%s'.")
1808
1809 (js2-msg "msg.function.not.found"
1810 "Cannot find function %s.")
1811
1812 (js2-msg "msg.function.not.found.in"
1813 "Cannot find function %s in object %s.")
1814
1815 (js2-msg "msg.isnt.xml.object"
1816 "%s is not an xml object.")
1817
1818 (js2-msg "msg.no.ref.to.get"
1819 "%s is not a reference to read reference value.")
1820
1821 (js2-msg "msg.no.ref.to.set"
1822 "%s is not a reference to set reference value to %s.")
1823
1824 (js2-msg "msg.no.ref.from.function"
1825 "Function %s can not be used as the left-hand "
1826 "side of assignment or as an operand of ++ or -- operator.")
1827
1828 (js2-msg "msg.bad.default.value"
1829 "Object's getDefaultValue() method returned an object.")
1830
1831 (js2-msg "msg.instanceof.not.object"
1832 "Can't use instanceof on a non-object.")
1833
1834 (js2-msg "msg.instanceof.bad.prototype"
1835 "'prototype' property of %s is not an object.")
1836
1837 (js2-msg "msg.bad.radix"
1838 "illegal radix %s.")
1839
1840 ;; ScriptableObject
1841 (js2-msg "msg.default.value"
1842 "Cannot find default value for object.")
1843
1844 (js2-msg "msg.zero.arg.ctor"
1845 "Cannot load class '%s' which has no zero-parameter constructor.")
1846
1847 (js2-msg "msg.ctor.multiple.parms"
1848 "Can't define constructor or class %s since more than "
1849 "one constructor has multiple parameters.")
1850
1851 (js2-msg "msg.extend.scriptable"
1852 "%s must extend ScriptableObject in order to define property %s.")
1853
1854 (js2-msg "msg.bad.getter.parms"
1855 "In order to define a property, getter %s must have zero "
1856 "parameters or a single ScriptableObject parameter.")
1857
1858 (js2-msg "msg.obj.getter.parms"
1859 "Expected static or delegated getter %s to take "
1860 "a ScriptableObject parameter.")
1861
1862 (js2-msg "msg.getter.static"
1863 "Getter and setter must both be static or neither be static.")
1864
1865 (js2-msg "msg.setter.return"
1866 "Setter must have void return type: %s")
1867
1868 (js2-msg "msg.setter2.parms"
1869 "Two-parameter setter must take a ScriptableObject as "
1870 "its first parameter.")
1871
1872 (js2-msg "msg.setter1.parms"
1873 "Expected single parameter setter for %s")
1874
1875 (js2-msg "msg.setter2.expected"
1876 "Expected static or delegated setter %s to take two parameters.")
1877
1878 (js2-msg "msg.setter.parms"
1879 "Expected either one or two parameters for setter.")
1880
1881 (js2-msg "msg.setter.bad.type"
1882 "Unsupported parameter type '%s' in setter '%s'.")
1883
1884 (js2-msg "msg.add.sealed"
1885 "Cannot add a property to a sealed object: %s.")
1886
1887 (js2-msg "msg.remove.sealed"
1888 "Cannot remove a property from a sealed object: %s.")
1889
1890 (js2-msg "msg.modify.sealed"
1891 "Cannot modify a property of a sealed object: %s.")
1892
1893 (js2-msg "msg.modify.readonly"
1894 "Cannot modify readonly property: %s.")
1895
1896 ;; TokenStream
1897 (js2-msg "msg.missing.exponent"
1898 "missing exponent")
1899
1900 (js2-msg "msg.caught.nfe"
1901 "number format error")
1902
1903 (js2-msg "msg.unterminated.string.lit"
1904 "unterminated string literal")
1905
1906 (js2-msg "msg.unterminated.comment"
1907 "unterminated comment")
1908
1909 (js2-msg "msg.unterminated.re.lit"
1910 "unterminated regular expression literal")
1911
1912 (js2-msg "msg.invalid.re.flag"
1913 "invalid flag after regular expression")
1914
1915 (js2-msg "msg.no.re.input.for"
1916 "no input for %s")
1917
1918 (js2-msg "msg.illegal.character"
1919 "illegal character")
1920
1921 (js2-msg "msg.invalid.escape"
1922 "invalid Unicode escape sequence")
1923
1924 (js2-msg "msg.bad.namespace"
1925 "not a valid default namespace statement. "
1926 "Syntax is: default xml namespace = EXPRESSION;")
1927
1928 ;; TokensStream warnings
1929 (js2-msg "msg.bad.octal.literal"
1930 "illegal octal literal digit %s; "
1931 "interpreting it as a decimal digit")
1932
1933 (js2-msg "msg.reserved.keyword"
1934 "illegal usage of future reserved keyword %s; "
1935 "interpreting it as ordinary identifier")
1936
1937 (js2-msg "msg.script.is.not.constructor"
1938 "Script objects are not constructors.")
1939
1940 ;; Arrays
1941 (js2-msg "msg.arraylength.bad"
1942 "Inappropriate array length.")
1943
1944 ;; Arrays
1945 (js2-msg "msg.arraylength.too.big"
1946 "Array length %s exceeds supported capacity limit.")
1947
1948 ;; URI
1949 (js2-msg "msg.bad.uri"
1950 "Malformed URI sequence.")
1951
1952 ;; Number
1953 (js2-msg "msg.bad.precision"
1954 "Precision %s out of range.")
1955
1956 ;; NativeGenerator
1957 (js2-msg "msg.send.newborn"
1958 "Attempt to send value to newborn generator")
1959
1960 (js2-msg "msg.already.exec.gen"
1961 "Already executing generator")
1962
1963 (js2-msg "msg.StopIteration.invalid"
1964 "StopIteration may not be changed to an arbitrary object.")
1965
1966 ;; Interpreter
1967 (js2-msg "msg.yield.closing"
1968 "Yield from closing generator")
1969
1970 ;;; Utilities
1971
1972 (defun js2-delete-if (predicate list)
1973 "Remove all items satisfying PREDICATE in LIST."
1974 (loop for item in list
1975 if (not (funcall predicate item))
1976 collect item))
1977
1978 (defun js2-position (element list)
1979 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1980 Returns nil if element is not found in the list."
1981 (let ((count 0)
1982 found)
1983 (while (and list (not found))
1984 (if (eq element (car list))
1985 (setq found t)
1986 (setq count (1+ count)
1987 list (cdr list))))
1988 (if found count)))
1989
1990 (defun js2-find-if (predicate list)
1991 "Find first item satisfying PREDICATE in LIST."
1992 (let (result)
1993 (while (and list (not result))
1994 (if (funcall predicate (car list))
1995 (setq result (car list)))
1996 (setq list (cdr list)))
1997 result))
1998
1999 (defmacro js2-time (form)
2000 "Evaluate FORM, discard result, and return elapsed time in sec"
2001 (declare (debug t))
2002 (let ((beg (make-symbol "--js2-time-beg--"))
2003 (delta (make-symbol "--js2-time-end--")))
2004 `(let ((,beg (current-time))
2005 ,delta)
2006 ,form
2007 (/ (truncate (* (- (float-time (current-time))
2008 (float-time ,beg))
2009 10000))
2010 10000.0))))
2011
2012 (defsubst js2-same-line (pos)
2013 "Return t if POS is on the same line as current point."
2014 (and (>= pos (point-at-bol))
2015 (<= pos (point-at-eol))))
2016
2017 (defsubst js2-same-line-2 (p1 p2)
2018 "Return t if p1 is on the same line as p2."
2019 (save-excursion
2020 (goto-char p1)
2021 (js2-same-line p2)))
2022
2023 (defun js2-code-bug ()
2024 "Signal an error when we encounter an unexpected code path."
2025 (error "failed assertion"))
2026
2027 ;; I'd like to associate errors with nodes, but for now the
2028 ;; easiest thing to do is get the context info from the last token.
2029 (defsubst js2-record-parse-error (msg &optional arg pos len)
2030 (push (list (list msg arg)
2031 (or pos js2-token-beg)
2032 (or len (- js2-token-end js2-token-beg)))
2033 js2-parsed-errors))
2034
2035 (defsubst js2-report-error (msg &optional msg-arg pos len)
2036 "Signal a syntax error or record a parse error."
2037 (if js2-recover-from-parse-errors
2038 (js2-record-parse-error msg msg-arg pos len)
2039 (signal 'js2-syntax-error
2040 (list msg
2041 js2-ts-lineno
2042 (save-excursion
2043 (goto-char js2-ts-cursor)
2044 (current-column))
2045 js2-ts-hit-eof))))
2046
2047 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2048 (if js2-compiler-report-warning-as-error
2049 (js2-report-error msg msg-arg pos len)
2050 (push (list (list msg msg-arg)
2051 (or pos js2-token-beg)
2052 (or len (- js2-token-end js2-token-beg)))
2053 js2-parsed-warnings)))
2054
2055 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2056 (if js2-compiler-strict-mode
2057 (js2-report-warning msg-id msg-arg beg
2058 (and beg end (- end beg)))))
2059
2060 (put 'js2-syntax-error 'error-conditions
2061 '(error syntax-error js2-syntax-error))
2062 (put 'js2-syntax-error 'error-message "Syntax error")
2063
2064 (put 'js2-parse-error 'error-conditions
2065 '(error parse-error js2-parse-error))
2066 (put 'js2-parse-error 'error-message "Parse error")
2067
2068 (defmacro js2-clear-flag (flags flag)
2069 `(setq ,flags (logand ,flags (lognot ,flag))))
2070
2071 (defmacro js2-set-flag (flags flag)
2072 "Logical-or FLAG into FLAGS."
2073 `(setq ,flags (logior ,flags ,flag)))
2074
2075 (defsubst js2-flag-set-p (flags flag)
2076 (/= 0 (logand flags flag)))
2077
2078 (defsubst js2-flag-not-set-p (flags flag)
2079 (zerop (logand flags flag)))
2080
2081 ;; Stolen shamelessly from James Clark's nxml-mode.
2082 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2083 "Evaluate BODY without any text property changes modifying the buffer.
2084 Any text properties changes happen as usual but the changes are not treated as
2085 modifications to the buffer."
2086 (declare (indent 0) (debug t))
2087 (let ((modified (make-symbol "modified")))
2088 `(let ((,modified (buffer-modified-p))
2089 (inhibit-read-only t)
2090 (inhibit-modification-hooks t)
2091 (buffer-undo-list t)
2092 (deactivate-mark nil)
2093 ;; Apparently these avoid file locking problems.
2094 (buffer-file-name nil)
2095 (buffer-file-truename nil))
2096 (unwind-protect
2097 (progn ,@body)
2098 (unless ,modified
2099 (restore-buffer-modified-p nil))))))
2100
2101 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2102 "Evaluate BODY with the _ character set to be word-syntax."
2103 (declare (indent 0) (debug t))
2104 (let ((old-syntax (make-symbol "old-syntax")))
2105 `(let ((,old-syntax (string (char-syntax ?_))))
2106 (unwind-protect
2107 (progn
2108 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2109 ,@body)
2110 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2111
2112 (defsubst js2-char-uppercase-p (c)
2113 "Return t if C is an uppercase character.
2114 Handles unicode and latin chars properly."
2115 (/= c (downcase c)))
2116
2117 (defsubst js2-char-lowercase-p (c)
2118 "Return t if C is an uppercase character.
2119 Handles unicode and latin chars properly."
2120 (/= c (upcase c)))
2121
2122 ;;; AST struct and function definitions
2123
2124 ;; flags for ast node property 'member-type (used for e4x operators)
2125 (defvar js2-property-flag #x1 "property access: element is valid name")
2126 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2127 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2128
2129 (defsubst js2-relpos (pos anchor)
2130 "Convert POS to be relative to ANCHOR.
2131 If POS is nil, returns nil."
2132 (and pos (- pos anchor)))
2133
2134 (defsubst js2-make-pad (indent)
2135 (if (zerop indent)
2136 ""
2137 (make-string (* indent js2-basic-offset) ? )))
2138
2139 (defsubst js2-visit-ast (node callback)
2140 "Visit every node in ast NODE with visitor CALLBACK.
2141
2142 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2143 called twice: once to visit the node, and again after all the node's
2144 children have been processed. The END-P argument is nil on the first
2145 call and non-nil on the second call. The return value of the callback
2146 affects the traversal: if non-nil, the children of NODE are processed.
2147 If the callback returns nil, or if the node has no children, then the
2148 callback is called immediately with a non-nil END-P argument.
2149
2150 The node traversal is approximately lexical-order, although there
2151 are currently no guarantees around this."
2152 (if node
2153 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2154 ;; visit the node
2155 (when (funcall callback node nil)
2156 ;; visit the kids
2157 (cond
2158 ((eq vfunc 'js2-visit-none)
2159 nil) ; don't even bother calling it
2160 ;; Each AST node type has to define a `js2-visitor' function
2161 ;; that takes a node and a callback, and calls `js2-visit-ast'
2162 ;; on each child of the node.
2163 (vfunc
2164 (funcall vfunc node callback))
2165 (t
2166 (error "%s does not define a visitor-traversal function"
2167 (aref node 0)))))
2168 ;; call the end-visit
2169 (funcall callback node t))))
2170
2171 (defstruct (js2-node
2172 (:constructor nil)) ; abstract
2173 "Base AST node type."
2174 (type -1) ; token type
2175 (pos -1) ; start position of this AST node in parsed input
2176 (len 1) ; num characters spanned by the node
2177 props ; optional node property list (an alist)
2178 parent) ; link to parent node; null for root
2179
2180 (defsubst js2-node-get-prop (node prop &optional default)
2181 (or (cadr (assoc prop (js2-node-props node))) default))
2182
2183 (defsubst js2-node-set-prop (node prop value)
2184 (setf (js2-node-props node)
2185 (cons (list prop value) (js2-node-props node))))
2186
2187 (defsubst js2-fixup-starts (n nodes)
2188 "Adjust the start positions of NODES to be relative to N.
2189 Any node in the list may be nil, for convenience."
2190 (dolist (node nodes)
2191 (when node
2192 (setf (js2-node-pos node) (- (js2-node-pos node)
2193 (js2-node-pos n))))))
2194
2195 (defsubst js2-node-add-children (parent &rest nodes)
2196 "Set parent node of NODES to PARENT, and return PARENT.
2197 Does nothing if we're not recording parent links.
2198 If any given node in NODES is nil, doesn't record that link."
2199 (js2-fixup-starts parent nodes)
2200 (dolist (node nodes)
2201 (and node
2202 (setf (js2-node-parent node) parent))))
2203
2204 ;; Non-recursive since it's called a frightening number of times.
2205 (defsubst js2-node-abs-pos (n)
2206 (let ((pos (js2-node-pos n)))
2207 (while (setq n (js2-node-parent n))
2208 (setq pos (+ pos (js2-node-pos n))))
2209 pos))
2210
2211 (defsubst js2-node-abs-end (n)
2212 "Return absolute buffer position of end of N."
2213 (+ (js2-node-abs-pos n) (js2-node-len n)))
2214
2215 ;; It's important to make sure block nodes have a lisp list for the
2216 ;; child nodes, to limit printing recursion depth in an AST that
2217 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2218 ;; a sufficiently large vector tree.
2219
2220 (defstruct (js2-block-node
2221 (:include js2-node)
2222 (:constructor nil)
2223 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2224 (pos js2-token-beg)
2225 len
2226 props
2227 kids)))
2228 "A block of statements."
2229 kids) ; a lisp list of the child statement nodes
2230
2231 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2232 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2233
2234 (defsubst js2-visit-block (ast callback)
2235 "Visit the `js2-block-node' children of AST."
2236 (dolist (kid (js2-block-node-kids ast))
2237 (js2-visit-ast kid callback)))
2238
2239 (defun js2-print-block (n i)
2240 (let ((pad (js2-make-pad i)))
2241 (insert pad "{\n")
2242 (dolist (kid (js2-block-node-kids n))
2243 (js2-print-ast kid (1+ i)))
2244 (insert pad "}")))
2245
2246 (defstruct (js2-scope
2247 (:include js2-block-node)
2248 (:constructor nil)
2249 (:constructor make-js2-scope (&key (type js2-BLOCK)
2250 (pos js2-token-beg)
2251 len
2252 kids)))
2253 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2254 ;; I don't have one of those handy, so I'll use an alist for now.
2255 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2256 ;; and is much lighter-weight to construct (both CPU and mem).
2257 ;; The keys are interned strings (symbols) for faster lookup.
2258 ;; Should switch to hybrid alist/hashtable eventually.
2259 symbol-table ; an alist of (symbol . js2-symbol)
2260 parent-scope ; a `js2-scope'
2261 top) ; top-level `js2-scope' (script/function)
2262
2263 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2264 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2265
2266 (defun js2-scope-set-parent-scope (scope parent)
2267 (setf (js2-scope-parent-scope scope) parent
2268 (js2-scope-top scope) (if (null parent)
2269 scope
2270 (js2-scope-top parent))))
2271
2272 (defun js2-node-get-enclosing-scope (node)
2273 "Return the innermost `js2-scope' node surrounding NODE.
2274 Returns nil if there is no enclosing scope node."
2275 (let ((parent (js2-node-parent node)))
2276 (while (not (js2-scope-p parent))
2277 (setq parent (js2-node-parent parent)))
2278 parent))
2279
2280 (defun js2-get-defining-scope (scope name)
2281 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2282 Returns `js2-scope' in which NAME is defined, or nil if not found."
2283 (let ((sym (if (symbolp name)
2284 name
2285 (intern name)))
2286 table
2287 result
2288 (continue t))
2289 (while (and scope continue)
2290 (if (and (setq table (js2-scope-symbol-table scope))
2291 (assq sym table))
2292 (setq continue nil
2293 result scope)
2294 (setq scope (js2-scope-parent-scope scope))))
2295 result))
2296
2297 (defsubst js2-scope-get-symbol (scope name)
2298 "Return symbol table entry for NAME in SCOPE.
2299 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2300 (and (js2-scope-symbol-table scope)
2301 (cdr (assq (if (symbolp name)
2302 name
2303 (intern name))
2304 (js2-scope-symbol-table scope)))))
2305
2306 (defsubst js2-scope-put-symbol (scope name symbol)
2307 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2308 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2309 (let* ((table (js2-scope-symbol-table scope))
2310 (sym (if (symbolp name) name (intern name)))
2311 (entry (assq sym table)))
2312 (if entry
2313 (setcdr entry symbol)
2314 (push (cons sym symbol)
2315 (js2-scope-symbol-table scope)))))
2316
2317 (defstruct (js2-symbol
2318 (:constructor nil)
2319 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2320 "A symbol table entry."
2321 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2322 ;; js2-LET, or js2-CONST
2323 decl-type
2324 name ; string
2325 ast-node) ; a `js2-node'
2326
2327 (defstruct (js2-error-node
2328 (:include js2-node)
2329 (:constructor nil) ; silence emacs21 byte-compiler
2330 (:constructor make-js2-error-node (&key (type js2-ERROR)
2331 (pos js2-token-beg)
2332 len)))
2333 "AST node representing a parse error.")
2334
2335 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2336 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2337
2338 (defstruct (js2-script-node
2339 (:include js2-scope)
2340 (:constructor nil)
2341 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2342 (pos js2-token-beg)
2343 len
2344 var-decls
2345 fun-decls)))
2346 functions ; lisp list of nested functions
2347 regexps ; lisp list of (string . flags)
2348 symbols ; alist (every symbol gets unique index)
2349 (param-count 0)
2350 var-names ; vector of string names
2351 consts ; bool-vector matching var-decls
2352 (temp-number 0)) ; for generating temp variables
2353
2354 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2355 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2356
2357 (defun js2-print-script (node indent)
2358 (dolist (kid (js2-block-node-kids node))
2359 (js2-print-ast kid indent)))
2360
2361 (defstruct (js2-ast-root
2362 (:include js2-script-node)
2363 (:constructor nil)
2364 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2365 (pos js2-token-beg)
2366 len
2367 buffer)))
2368 "The root node of a js2 AST."
2369 buffer ; the source buffer from which the code was parsed
2370 comments ; a lisp list of comments, ordered by start position
2371 errors ; a lisp list of errors found during parsing
2372 warnings ; a lisp list of warnings found during parsing
2373 node-count) ; number of nodes in the tree, including the root
2374
2375 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2376 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2377
2378 (defun js2-visit-ast-root (ast callback)
2379 (dolist (kid (js2-ast-root-kids ast))
2380 (js2-visit-ast kid callback))
2381 (dolist (comment (js2-ast-root-comments ast))
2382 (js2-visit-ast comment callback)))
2383
2384 (defstruct (js2-comment-node
2385 (:include js2-node)
2386 (:constructor nil)
2387 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2388 (pos js2-token-beg)
2389 len
2390 (format js2-ts-comment-type))))
2391 format) ; 'line, 'block, 'jsdoc or 'html
2392
2393 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2394 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2395
2396 (defun js2-print-comment (n i)
2397 ;; We really ought to link end-of-line comments to their nodes.
2398 ;; Or maybe we could add a new comment type, 'endline.
2399 (insert (js2-make-pad i)
2400 (js2-node-string n)))
2401
2402 (defstruct (js2-expr-stmt-node
2403 (:include js2-node)
2404 (:constructor nil)
2405 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2406 (pos js2-ts-cursor)
2407 len
2408 expr)))
2409 "An expression statement."
2410 expr)
2411
2412 (defsubst js2-expr-stmt-node-set-has-result (node)
2413 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2414 (setf (js2-node-type node) js2-EXPR_RESULT))
2415
2416 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2417 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2418
2419 (defun js2-visit-expr-stmt-node (n v)
2420 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2421
2422 (defun js2-print-expr-stmt-node (n indent)
2423 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2424 (insert ";\n"))
2425
2426 (defstruct (js2-loop-node
2427 (:include js2-scope)
2428 (:constructor nil))
2429 "Abstract supertype of loop nodes."
2430 body ; a `js2-block-node'
2431 lp ; position of left-paren, nil if omitted
2432 rp) ; position of right-paren, nil if omitted
2433
2434 (defstruct (js2-do-node
2435 (:include js2-loop-node)
2436 (:constructor nil)
2437 (:constructor make-js2-do-node (&key (type js2-DO)
2438 (pos js2-token-beg)
2439 len
2440 body
2441 condition
2442 while-pos
2443 lp
2444 rp)))
2445 "AST node for do-loop."
2446 condition ; while (expression)
2447 while-pos) ; buffer position of 'while' keyword
2448
2449 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2450 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2451
2452 (defun js2-visit-do-node (n v)
2453 (js2-visit-ast (js2-do-node-body n) v)
2454 (js2-visit-ast (js2-do-node-condition n) v))
2455
2456 (defun js2-print-do-node (n i)
2457 (let ((pad (js2-make-pad i)))
2458 (insert pad "do {\n")
2459 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2460 (js2-print-ast kid (1+ i)))
2461 (insert pad "} while (")
2462 (js2-print-ast (js2-do-node-condition n) 0)
2463 (insert ");\n")))
2464
2465 (defstruct (js2-while-node
2466 (:include js2-loop-node)
2467 (:constructor nil)
2468 (:constructor make-js2-while-node (&key (type js2-WHILE)
2469 (pos js2-token-beg)
2470 len
2471 body
2472 condition
2473 lp
2474 rp)))
2475 "AST node for while-loop."
2476 condition) ; while-condition
2477
2478 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2479 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2480
2481 (defun js2-visit-while-node (n v)
2482 (js2-visit-ast (js2-while-node-condition n) v)
2483 (js2-visit-ast (js2-while-node-body n) v))
2484
2485 (defun js2-print-while-node (n i)
2486 (let ((pad (js2-make-pad i)))
2487 (insert pad "while (")
2488 (js2-print-ast (js2-while-node-condition n) 0)
2489 (insert ") {\n")
2490 (js2-print-body (js2-while-node-body n) (1+ i))
2491 (insert pad "}\n")))
2492
2493 (defstruct (js2-for-node
2494 (:include js2-loop-node)
2495 (:constructor nil)
2496 (:constructor make-js2-for-node (&key (type js2-FOR)
2497 (pos js2-ts-cursor)
2498 len
2499 body
2500 init
2501 condition
2502 update
2503 lp
2504 rp)))
2505 "AST node for a C-style for-loop."
2506 init ; initialization expression
2507 condition ; loop condition
2508 update) ; update clause
2509
2510 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2511 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2512
2513 (defun js2-visit-for-node (n v)
2514 (js2-visit-ast (js2-for-node-init n) v)
2515 (js2-visit-ast (js2-for-node-condition n) v)
2516 (js2-visit-ast (js2-for-node-update n) v)
2517 (js2-visit-ast (js2-for-node-body n) v))
2518
2519 (defun js2-print-for-node (n i)
2520 (let ((pad (js2-make-pad i)))
2521 (insert pad "for (")
2522 (js2-print-ast (js2-for-node-init n) 0)
2523 (insert "; ")
2524 (js2-print-ast (js2-for-node-condition n) 0)
2525 (insert "; ")
2526 (js2-print-ast (js2-for-node-update n) 0)
2527 (insert ") {\n")
2528 (js2-print-body (js2-for-node-body n) (1+ i))
2529 (insert pad "}\n")))
2530
2531 (defstruct (js2-for-in-node
2532 (:include js2-loop-node)
2533 (:constructor nil)
2534 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2535 (pos js2-ts-cursor)
2536 len
2537 body
2538 iterator
2539 object
2540 in-pos
2541 each-pos
2542 foreach-p
2543 lp
2544 rp)))
2545 "AST node for a for..in loop."
2546 iterator ; [var] foo in ...
2547 object ; object over which we're iterating
2548 in-pos ; buffer position of 'in' keyword
2549 each-pos ; buffer position of 'each' keyword, if foreach-p
2550 foreach-p) ; t if it's a for-each loop
2551
2552 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2553 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2554
2555 (defun js2-visit-for-in-node (n v)
2556 (js2-visit-ast (js2-for-in-node-iterator n) v)
2557 (js2-visit-ast (js2-for-in-node-object n) v)
2558 (js2-visit-ast (js2-for-in-node-body n) v))
2559
2560 (defun js2-print-for-in-node (n i)
2561 (let ((pad (js2-make-pad i))
2562 (foreach (js2-for-in-node-foreach-p n)))
2563 (insert pad "for ")
2564 (if foreach
2565 (insert "each "))
2566 (insert "(")
2567 (js2-print-ast (js2-for-in-node-iterator n) 0)
2568 (insert " in ")
2569 (js2-print-ast (js2-for-in-node-object n) 0)
2570 (insert ") {\n")
2571 (js2-print-body (js2-for-in-node-body n) (1+ i))
2572 (insert pad "}\n")))
2573
2574 (defstruct (js2-return-node
2575 (:include js2-node)
2576 (:constructor nil)
2577 (:constructor make-js2-return-node (&key (type js2-RETURN)
2578 (pos js2-ts-cursor)
2579 len
2580 retval)))
2581 "AST node for a return statement."
2582 retval) ; expression to return, or 'undefined
2583
2584 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2585 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2586
2587 (defun js2-visit-return-node (n v)
2588 (js2-visit-ast (js2-return-node-retval n) v))
2589
2590 (defun js2-print-return-node (n i)
2591 (insert (js2-make-pad i) "return")
2592 (when (js2-return-node-retval n)
2593 (insert " ")
2594 (js2-print-ast (js2-return-node-retval n) 0))
2595 (insert ";\n"))
2596
2597 (defstruct (js2-if-node
2598 (:include js2-node)
2599 (:constructor nil)
2600 (:constructor make-js2-if-node (&key (type js2-IF)
2601 (pos js2-ts-cursor)
2602 len
2603 condition
2604 then-part
2605 else-pos
2606 else-part
2607 lp
2608 rp)))
2609 "AST node for an if-statement."
2610 condition ; expression
2611 then-part ; statement or block
2612 else-pos ; optional buffer position of 'else' keyword
2613 else-part ; optional statement or block
2614 lp ; position of left-paren, nil if omitted
2615 rp) ; position of right-paren, nil if omitted
2616
2617 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2618 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2619
2620 (defun js2-visit-if-node (n v)
2621 (js2-visit-ast (js2-if-node-condition n) v)
2622 (js2-visit-ast (js2-if-node-then-part n) v)
2623 (js2-visit-ast (js2-if-node-else-part n) v))
2624
2625 (defun js2-print-if-node (n i)
2626 (let ((pad (js2-make-pad i))
2627 (then-part (js2-if-node-then-part n))
2628 (else-part (js2-if-node-else-part n)))
2629 (insert pad "if (")
2630 (js2-print-ast (js2-if-node-condition n) 0)
2631 (insert ") {\n")
2632 (js2-print-body then-part (1+ i))
2633 (insert pad "}")
2634 (cond
2635 ((not else-part)
2636 (insert "\n"))
2637 ((js2-if-node-p else-part)
2638 (insert " else ")
2639 (js2-print-body else-part i))
2640 (t
2641 (insert " else {\n")
2642 (js2-print-body else-part (1+ i))
2643 (insert pad "}\n")))))
2644
2645 (defstruct (js2-try-node
2646 (:include js2-node)
2647 (:constructor nil)
2648 (:constructor make-js2-try-node (&key (type js2-TRY)
2649 (pos js2-ts-cursor)
2650 len
2651 try-block
2652 catch-clauses
2653 finally-block)))
2654 "AST node for a try-statement."
2655 try-block
2656 catch-clauses ; a lisp list of `js2-catch-node'
2657 finally-block) ; a `js2-finally-node'
2658
2659 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2660 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2661
2662 (defun js2-visit-try-node (n v)
2663 (js2-visit-ast (js2-try-node-try-block n) v)
2664 (dolist (clause (js2-try-node-catch-clauses n))
2665 (js2-visit-ast clause v))
2666 (js2-visit-ast (js2-try-node-finally-block n) v))
2667
2668 (defun js2-print-try-node (n i)
2669 (let ((pad (js2-make-pad i))
2670 (catches (js2-try-node-catch-clauses n))
2671 (finally (js2-try-node-finally-block n)))
2672 (insert pad "try {\n")
2673 (js2-print-body (js2-try-node-try-block n) (1+ i))
2674 (insert pad "}")
2675 (when catches
2676 (dolist (catch catches)
2677 (js2-print-ast catch i)))
2678 (if finally
2679 (js2-print-ast finally i)
2680 (insert "\n"))))
2681
2682 (defstruct (js2-catch-node
2683 (:include js2-node)
2684 (:constructor nil)
2685 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2686 (pos js2-ts-cursor)
2687 len
2688 var-name
2689 guard-kwd
2690 guard-expr
2691 block
2692 lp
2693 rp)))
2694 "AST node for a catch clause."
2695 var-name ; a `js2-name-node'
2696 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2697 guard-expr ; catch condition, a `js2-node'
2698 block ; statements, a `js2-block-node'
2699 lp ; buffer position of left-paren, nil if omitted
2700 rp) ; buffer position of right-paren, nil if omitted
2701
2702 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2703 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2704
2705 (defun js2-visit-catch-node (n v)
2706 (js2-visit-ast (js2-catch-node-var-name n) v)
2707 (when (js2-catch-node-guard-kwd n)
2708 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2709 (js2-visit-ast (js2-catch-node-block n) v))
2710
2711 (defun js2-print-catch-node (n i)
2712 (let ((pad (js2-make-pad i))
2713 (guard-kwd (js2-catch-node-guard-kwd n))
2714 (guard-expr (js2-catch-node-guard-expr n)))
2715 (insert " catch (")
2716 (js2-print-ast (js2-catch-node-var-name n) 0)
2717 (when guard-kwd
2718 (insert " if ")
2719 (js2-print-ast guard-expr 0))
2720 (insert ") {\n")
2721 (js2-print-body (js2-catch-node-block n) (1+ i))
2722 (insert pad "}")))
2723
2724 (defstruct (js2-finally-node
2725 (:include js2-node)
2726 (:constructor nil)
2727 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2728 (pos js2-ts-cursor)
2729 len
2730 body)))
2731 "AST node for a finally clause."
2732 body) ; a `js2-node', often but not always a block node
2733
2734 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2735 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2736
2737 (defun js2-visit-finally-node (n v)
2738 (js2-visit-ast (js2-finally-node-body n) v))
2739
2740 (defun js2-print-finally-node (n i)
2741 (let ((pad (js2-make-pad i)))
2742 (insert " finally {\n")
2743 (js2-print-body (js2-finally-node-body n) (1+ i))
2744 (insert pad "}\n")))
2745
2746 (defstruct (js2-switch-node
2747 (:include js2-node)
2748 (:constructor nil)
2749 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2750 (pos js2-ts-cursor)
2751 len
2752 discriminant
2753 cases
2754 lp
2755 rp)))
2756 "AST node for a switch statement."
2757 discriminant ; a `js2-node' (switch expression)
2758 cases ; a lisp list of `js2-case-node'
2759 lp ; position of open-paren for discriminant, nil if omitted
2760 rp) ; position of close-paren for discriminant, nil if omitted
2761
2762 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2763 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2764
2765 (defun js2-visit-switch-node (n v)
2766 (js2-visit-ast (js2-switch-node-discriminant n) v)
2767 (dolist (c (js2-switch-node-cases n))
2768 (js2-visit-ast c v)))
2769
2770 (defun js2-print-switch-node (n i)
2771 (let ((pad (js2-make-pad i))
2772 (cases (js2-switch-node-cases n)))
2773 (insert pad "switch (")
2774 (js2-print-ast (js2-switch-node-discriminant n) 0)
2775 (insert ") {\n")
2776 (dolist (case cases)
2777 (js2-print-ast case i))
2778 (insert pad "}\n")))
2779
2780 (defstruct (js2-case-node
2781 (:include js2-block-node)
2782 (:constructor nil)
2783 (:constructor make-js2-case-node (&key (type js2-CASE)
2784 (pos js2-ts-cursor)
2785 len
2786 kids
2787 expr)))
2788 "AST node for a case clause of a switch statement."
2789 expr) ; the case expression (nil for default)
2790
2791 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2792 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2793
2794 (defun js2-visit-case-node (n v)
2795 (js2-visit-ast (js2-case-node-expr n) v)
2796 (js2-visit-block n v))
2797
2798 (defun js2-print-case-node (n i)
2799 (let ((pad (js2-make-pad i))
2800 (expr (js2-case-node-expr n)))
2801 (insert pad)
2802 (if (null expr)
2803 (insert "default:\n")
2804 (insert "case ")
2805 (js2-print-ast expr 0)
2806 (insert ":\n"))
2807 (dolist (kid (js2-case-node-kids n))
2808 (js2-print-ast kid (1+ i)))))
2809
2810 (defstruct (js2-throw-node
2811 (:include js2-node)
2812 (:constructor nil)
2813 (:constructor make-js2-throw-node (&key (type js2-THROW)
2814 (pos js2-ts-cursor)
2815 len
2816 expr)))
2817 "AST node for a throw statement."
2818 expr) ; the expression to throw
2819
2820 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2821 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2822
2823 (defun js2-visit-throw-node (n v)
2824 (js2-visit-ast (js2-throw-node-expr n) v))
2825
2826 (defun js2-print-throw-node (n i)
2827 (insert (js2-make-pad i) "throw ")
2828 (js2-print-ast (js2-throw-node-expr n) 0)
2829 (insert ";\n"))
2830
2831 (defstruct (js2-with-node
2832 (:include js2-node)
2833 (:constructor nil)
2834 (:constructor make-js2-with-node (&key (type js2-WITH)
2835 (pos js2-ts-cursor)
2836 len
2837 object
2838 body
2839 lp
2840 rp)))
2841 "AST node for a with-statement."
2842 object
2843 body
2844 lp ; buffer position of left-paren around object, nil if omitted
2845 rp) ; buffer position of right-paren around object, nil if omitted
2846
2847 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2848 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2849
2850 (defun js2-visit-with-node (n v)
2851 (js2-visit-ast (js2-with-node-object n) v)
2852 (js2-visit-ast (js2-with-node-body n) v))
2853
2854 (defun js2-print-with-node (n i)
2855 (let ((pad (js2-make-pad i)))
2856 (insert pad "with (")
2857 (js2-print-ast (js2-with-node-object n) 0)
2858 (insert ") {\n")
2859 (js2-print-body (js2-with-node-body n) (1+ i))
2860 (insert pad "}\n")))
2861
2862 (defstruct (js2-label-node
2863 (:include js2-node)
2864 (:constructor nil)
2865 (:constructor make-js2-label-node (&key (type js2-LABEL)
2866 (pos js2-ts-cursor)
2867 len
2868 name)))
2869 "AST node for a statement label or case label."
2870 name ; a string
2871 loop) ; for validating and code-generating continue-to-label
2872
2873 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2874 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2875
2876 (defun js2-print-label (n i)
2877 (insert (js2-make-pad i)
2878 (js2-label-node-name n)
2879 ":\n"))
2880
2881 (defstruct (js2-labeled-stmt-node
2882 (:include js2-node)
2883 (:constructor nil)
2884 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2885 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2886 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2887 (pos js2-ts-cursor)
2888 len
2889 labels
2890 stmt)))
2891 "AST node for a statement with one or more labels.
2892 Multiple labels for a statement are collapsed into the labels field."
2893 labels ; lisp list of `js2-label-node'
2894 stmt) ; the statement these labels are for
2895
2896 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2897 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2898
2899 (defun js2-get-label-by-name (lbl-stmt name)
2900 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2901 Returns nil if no such label is in the list."
2902 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2903 result)
2904 (while (and label-list (not result))
2905 (if (string= (js2-label-node-name (car label-list)) name)
2906 (setq result (car label-list))
2907 (setq label-list (cdr label-list))))
2908 result))
2909
2910 (defun js2-visit-labeled-stmt (n v)
2911 (dolist (label (js2-labeled-stmt-node-labels n))
2912 (js2-visit-ast label v))
2913 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2914
2915 (defun js2-print-labeled-stmt (n i)
2916 (dolist (label (js2-labeled-stmt-node-labels n))
2917 (js2-print-ast label i))
2918 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2919
2920 (defun js2-labeled-stmt-node-contains (node label)
2921 "Return t if NODE contains LABEL in its label set.
2922 NODE is a `js2-labels-node'. LABEL is an identifier."
2923 (loop for nl in (js2-labeled-stmt-node-labels node)
2924 if (string= label (js2-label-node-name nl))
2925 return t
2926 finally return nil))
2927
2928 (defsubst js2-labeled-stmt-node-add-label (node label)
2929 "Add a `js2-label-node' to the label set for this statement."
2930 (setf (js2-labeled-stmt-node-labels node)
2931 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2932
2933 (defstruct (js2-jump-node
2934 (:include js2-node)
2935 (:constructor nil))
2936 "Abstract supertype of break and continue nodes."
2937 label ; `js2-name-node' for location of label identifier, if present
2938 target) ; target js2-labels-node or loop/switch statement
2939
2940 (defun js2-visit-jump-node (n v)
2941 (js2-visit-ast (js2-jump-node-label n) v))
2942
2943 (defstruct (js2-break-node
2944 (:include js2-jump-node)
2945 (:constructor nil)
2946 (:constructor make-js2-break-node (&key (type js2-BREAK)
2947 (pos js2-ts-cursor)
2948 len
2949 label
2950 target)))
2951 "AST node for a break statement.
2952 The label field is a `js2-name-node', possibly nil, for the named label
2953 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2954 is the target of the break - a label node or enclosing loop/switch statement.")
2955
2956 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2957 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2958
2959 (defun js2-print-break-node (n i)
2960 (insert (js2-make-pad i) "break")
2961 (when (js2-break-node-label n)
2962 (insert " ")
2963 (js2-print-ast (js2-break-node-label n) 0))
2964 (insert ";\n"))
2965
2966 (defstruct (js2-continue-node
2967 (:include js2-jump-node)
2968 (:constructor nil)
2969 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2970 (pos js2-ts-cursor)
2971 len
2972 label
2973 target)))
2974 "AST node for a continue statement.
2975 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2976 It is nil if continue specifies no label. The target field is the jump target:
2977 a `js2-label-node' or the innermost enclosing loop.")
2978
2979 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2980 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2981
2982 (defun js2-print-continue-node (n i)
2983 (insert (js2-make-pad i) "continue")
2984 (when (js2-continue-node-label n)
2985 (insert " ")
2986 (js2-print-ast (js2-continue-node-label n) 0))
2987 (insert ";\n"))
2988
2989 (defstruct (js2-function-node
2990 (:include js2-script-node)
2991 (:constructor nil)
2992 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2993 (pos js2-ts-cursor)
2994 len
2995 (ftype 'FUNCTION)
2996 (form 'FUNCTION_STATEMENT)
2997 (name "")
2998 params
2999 body
3000 lp
3001 rp)))
3002 "AST node for a function declaration.
3003 The `params' field is a lisp list of nodes. Each node is either a simple
3004 `js2-name-node', or if it's a destructuring-assignment parameter, a
3005 `js2-array-node' or `js2-object-node'."
3006 ftype ; FUNCTION, GETTER or SETTER
3007 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3008 name ; function name (a `js2-name-node', or nil if anonymous)
3009 params ; a lisp list of destructuring forms or simple name nodes
3010 body ; a `js2-block-node' or expression node (1.8 only)
3011 lp ; position of arg-list open-paren, or nil if omitted
3012 rp ; position of arg-list close-paren, or nil if omitted
3013 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3014 needs-activation ; t if we need an activation object for this frame
3015 is-generator ; t if this function contains a yield
3016 member-expr) ; nonstandard Ecma extension from Rhino
3017
3018 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3019 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3020
3021 (defun js2-visit-function-node (n v)
3022 (js2-visit-ast (js2-function-node-name n) v)
3023 (dolist (p (js2-function-node-params n))
3024 (js2-visit-ast p v))
3025 (js2-visit-ast (js2-function-node-body n) v))
3026
3027 (defun js2-print-function-node (n i)
3028 (let ((pad (js2-make-pad i))
3029 (getter (js2-node-get-prop n 'GETTER_SETTER))
3030 (name (js2-function-node-name n))
3031 (params (js2-function-node-params n))
3032 (body (js2-function-node-body n))
3033 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3034 (unless getter
3035 (insert pad "function"))
3036 (when name
3037 (insert " ")
3038 (js2-print-ast name 0))
3039 (insert "(")
3040 (loop with len = (length params)
3041 for param in params
3042 for count from 1
3043 do
3044 (js2-print-ast param 0)
3045 (if (< count len)
3046 (insert ", ")))
3047 (insert ") {")
3048 (unless expr
3049 (insert "\n"))
3050 ;; TODO: fix this to be smarter about indenting, etc.
3051 (js2-print-body body (1+ i))
3052 (insert pad "}")
3053 (unless expr
3054 (insert "\n"))))
3055
3056 (defsubst js2-function-name (node)
3057 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3058 (and (js2-function-node-name node)
3059 (js2-name-node-name (js2-function-node-name node))))
3060
3061 ;; Having this be an expression node makes it more flexible.
3062 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3063 ;; that work better if you assume it's an expression. Whenever we have
3064 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3065 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3066 (defstruct (js2-var-decl-node
3067 (:include js2-node)
3068 (:constructor nil)
3069 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3070 (pos js2-token-beg)
3071 len
3072 kids
3073 decl-type)))
3074 "AST node for a variable declaration list (VAR, CONST or LET).
3075 The node bounds differ depending on the declaration type. For VAR or
3076 CONST declarations, the bounds include the var/const keyword. For LET
3077 declarations, the node begins at the position of the first child."
3078 kids ; a lisp list of `js2-var-init-node' structs.
3079 decl-type) ; js2-VAR, js2-CONST or js2-LET
3080
3081 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3082 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3083
3084 (defun js2-visit-var-decl (n v)
3085 (dolist (kid (js2-var-decl-node-kids n))
3086 (js2-visit-ast kid v)))
3087
3088 (defun js2-print-var-decl (n i)
3089 (let ((pad (js2-make-pad i))
3090 (tt (js2-var-decl-node-decl-type n)))
3091 (insert pad)
3092 (insert (cond
3093 ((= tt js2-VAR) "var ")
3094 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3095 ((= tt js2-CONST) "const ")
3096 (t
3097 (error "malformed var-decl node"))))
3098 (loop with kids = (js2-var-decl-node-kids n)
3099 with len = (length kids)
3100 for kid in kids
3101 for count from 1
3102 do
3103 (js2-print-ast kid 0)
3104 (if (< count len)
3105 (insert ", ")))))
3106
3107 (defstruct (js2-var-init-node
3108 (:include js2-node)
3109 (:constructor nil)
3110 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3111 (pos js2-ts-cursor)
3112 len
3113 target
3114 initializer)))
3115 "AST node for a variable declaration.
3116 The type field will be js2-CONST for a const decl."
3117 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3118 initializer) ; initializer expression, a `js2-node'
3119
3120 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3121 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3122
3123 (defun js2-visit-var-init-node (n v)
3124 (js2-visit-ast (js2-var-init-node-target n) v)
3125 (js2-visit-ast (js2-var-init-node-initializer n) v))
3126
3127 (defun js2-print-var-init-node (n i)
3128 (let ((pad (js2-make-pad i))
3129 (name (js2-var-init-node-target n))
3130 (init (js2-var-init-node-initializer n)))
3131 (insert pad)
3132 (js2-print-ast name 0)
3133 (when init
3134 (insert " = ")
3135 (js2-print-ast init 0))))
3136
3137 (defstruct (js2-cond-node
3138 (:include js2-node)
3139 (:constructor nil)
3140 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3141 (pos js2-ts-cursor)
3142 len
3143 test-expr
3144 true-expr
3145 false-expr
3146 q-pos
3147 c-pos)))
3148 "AST node for the ternary operator"
3149 test-expr
3150 true-expr
3151 false-expr
3152 q-pos ; buffer position of ?
3153 c-pos) ; buffer position of :
3154
3155 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3156 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3157
3158 (defun js2-visit-cond-node (n v)
3159 (js2-visit-ast (js2-cond-node-test-expr n) v)
3160 (js2-visit-ast (js2-cond-node-true-expr n) v)
3161 (js2-visit-ast (js2-cond-node-false-expr n) v))
3162
3163 (defun js2-print-cond-node (n i)
3164 (let ((pad (js2-make-pad i)))
3165 (insert pad)
3166 (js2-print-ast (js2-cond-node-test-expr n) 0)
3167 (insert " ? ")
3168 (js2-print-ast (js2-cond-node-true-expr n) 0)
3169 (insert " : ")
3170 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3171
3172 (defstruct (js2-infix-node
3173 (:include js2-node)
3174 (:constructor nil)
3175 (:constructor make-js2-infix-node (&key type
3176 (pos js2-ts-cursor)
3177 len
3178 op-pos
3179 left
3180 right)))
3181 "Represents infix expressions.
3182 Includes assignment ops like `|=', and the comma operator.
3183 The type field inherited from `js2-node' holds the operator."
3184 op-pos ; buffer position where operator begins
3185 left ; any `js2-node'
3186 right) ; any `js2-node'
3187
3188 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3189 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3190
3191 (defun js2-visit-infix-node (n v)
3192 (js2-visit-ast (js2-infix-node-left n) v)
3193 (js2-visit-ast (js2-infix-node-right n) v))
3194
3195 (defconst js2-operator-tokens
3196 (let ((table (make-hash-table :test 'eq))
3197 (tokens
3198 (list (cons js2-IN "in")
3199 (cons js2-TYPEOF "typeof")
3200 (cons js2-INSTANCEOF "instanceof")
3201 (cons js2-DELPROP "delete")
3202 (cons js2-COMMA ",")
3203 (cons js2-COLON ":")
3204 (cons js2-OR "||")
3205 (cons js2-AND "&&")
3206 (cons js2-INC "++")
3207 (cons js2-DEC "--")
3208 (cons js2-BITOR "|")
3209 (cons js2-BITXOR "^")
3210 (cons js2-BITAND "&")
3211 (cons js2-EQ "==")
3212 (cons js2-NE "!=")
3213 (cons js2-LT "<")
3214 (cons js2-LE "<=")
3215 (cons js2-GT ">")
3216 (cons js2-GE ">=")
3217 (cons js2-LSH "<<")
3218 (cons js2-RSH ">>")
3219 (cons js2-URSH ">>>")
3220 (cons js2-ADD "+") ; infix plus
3221 (cons js2-SUB "-") ; infix minus
3222 (cons js2-MUL "*")
3223 (cons js2-DIV "/")
3224 (cons js2-MOD "%")
3225 (cons js2-NOT "!")
3226 (cons js2-BITNOT "~")
3227 (cons js2-POS "+") ; unary plus
3228 (cons js2-NEG "-") ; unary minus
3229 (cons js2-SHEQ "===") ; shallow equality
3230 (cons js2-SHNE "!==") ; shallow inequality
3231 (cons js2-ASSIGN "=")
3232 (cons js2-ASSIGN_BITOR "|=")
3233 (cons js2-ASSIGN_BITXOR "^=")
3234 (cons js2-ASSIGN_BITAND "&=")
3235 (cons js2-ASSIGN_LSH "<<=")
3236 (cons js2-ASSIGN_RSH ">>=")
3237 (cons js2-ASSIGN_URSH ">>>=")
3238 (cons js2-ASSIGN_ADD "+=")
3239 (cons js2-ASSIGN_SUB "-=")
3240 (cons js2-ASSIGN_MUL "*=")
3241 (cons js2-ASSIGN_DIV "/=")
3242 (cons js2-ASSIGN_MOD "%="))))
3243 (loop for (k . v) in tokens do
3244 (puthash k v table))
3245 table))
3246
3247 (defun js2-print-infix-node (n i)
3248 (let* ((tt (js2-node-type n))
3249 (op (gethash tt js2-operator-tokens)))
3250 (unless op
3251 (error "unrecognized infix operator %s" (js2-node-type n)))
3252 (insert (js2-make-pad i))
3253 (js2-print-ast (js2-infix-node-left n) 0)
3254 (unless (= tt js2-COMMA)
3255 (insert " "))
3256 (insert op)
3257 (insert " ")
3258 (js2-print-ast (js2-infix-node-right n) 0)))
3259
3260 (defstruct (js2-assign-node
3261 (:include js2-infix-node)
3262 (:constructor nil)
3263 (:constructor make-js2-assign-node (&key type
3264 (pos js2-ts-cursor)
3265 len
3266 op-pos
3267 left
3268 right)))
3269 "Represents any assignment.
3270 The type field holds the actual assignment operator.")
3271
3272 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3273 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3274
3275 (defstruct (js2-unary-node
3276 (:include js2-node)
3277 (:constructor nil)
3278 (:constructor make-js2-unary-node (&key type ; required
3279 (pos js2-ts-cursor)
3280 len
3281 operand)))
3282 "AST node type for unary operator nodes.
3283 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3284 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3285 property is added if the operator follows the operand."
3286 operand) ; a `js2-node' expression
3287
3288 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3289 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3290
3291 (defun js2-visit-unary-node (n v)
3292 (js2-visit-ast (js2-unary-node-operand n) v))
3293
3294 (defun js2-print-unary-node (n i)
3295 (let* ((tt (js2-node-type n))
3296 (op (gethash tt js2-operator-tokens))
3297 (postfix (js2-node-get-prop n 'postfix)))
3298 (unless op
3299 (error "unrecognized unary operator %s" tt))
3300 (insert (js2-make-pad i))
3301 (unless postfix
3302 (insert op))
3303 (if (or (= tt js2-TYPEOF)
3304 (= tt js2-DELPROP))
3305 (insert " "))
3306 (js2-print-ast (js2-unary-node-operand n) 0)
3307 (when postfix
3308 (insert op))))
3309
3310 (defstruct (js2-let-node
3311 (:include js2-scope)
3312 (:constructor nil)
3313 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3314 (pos js2-token-beg)
3315 len
3316 vars
3317 body
3318 lp
3319 rp)))
3320 "AST node for a let expression or a let statement.
3321 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3322 vars ; a `js2-var-decl-node'
3323 body ; a `js2-node' representing the expression or body block
3324 lp
3325 rp)
3326
3327 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3328 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3329
3330 (defun js2-visit-let-node (n v)
3331 (js2-visit-ast (js2-let-node-vars n) v)
3332 (js2-visit-ast (js2-let-node-body n) v))
3333
3334 (defun js2-print-let-node (n i)
3335 (insert (js2-make-pad i) "let (")
3336 (js2-print-ast (js2-let-node-vars n) 0)
3337 (insert ") ")
3338 (js2-print-ast (js2-let-node-body n) i))
3339
3340 (defstruct (js2-keyword-node
3341 (:include js2-node)
3342 (:constructor nil)
3343 (:constructor make-js2-keyword-node (&key type
3344 (pos js2-token-beg)
3345 (len (- js2-ts-cursor pos)))))
3346 "AST node representing a literal keyword such as `null'.
3347 Used for `null', `this', `true', `false' and `debugger'.
3348 The node type is set to js2-NULL, js2-THIS, etc.")
3349
3350 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3351 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3352
3353 (defun js2-print-keyword-node (n i)
3354 (insert (js2-make-pad i)
3355 (let ((tt (js2-node-type n)))
3356 (cond
3357 ((= tt js2-THIS) "this")
3358 ((= tt js2-NULL) "null")
3359 ((= tt js2-TRUE) "true")
3360 ((= tt js2-FALSE) "false")
3361 ((= tt js2-DEBUGGER) "debugger")
3362 (t (error "Invalid keyword literal type: %d" tt))))))
3363
3364 (defsubst js2-this-node-p (node)
3365 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3366 (eq (js2-node-type node) js2-THIS))
3367
3368 (defstruct (js2-new-node
3369 (:include js2-node)
3370 (:constructor nil)
3371 (:constructor make-js2-new-node (&key (type js2-NEW)
3372 (pos js2-token-beg)
3373 len
3374 target
3375 args
3376 initializer
3377 lp
3378 rp)))
3379 "AST node for new-expression such as new Foo()."
3380 target ; an identifier or reference
3381 args ; a lisp list of argument nodes
3382 lp ; position of left-paren, nil if omitted
3383 rp ; position of right-paren, nil if omitted
3384 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3385
3386 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3387 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3388
3389 (defun js2-visit-new-node (n v)
3390 (js2-visit-ast (js2-new-node-target n) v)
3391 (dolist (arg (js2-new-node-args n))
3392 (js2-visit-ast arg v))
3393 (js2-visit-ast (js2-new-node-initializer n) v))
3394
3395 (defun js2-print-new-node (n i)
3396 (insert (js2-make-pad i) "new ")
3397 (js2-print-ast (js2-new-node-target n))
3398 (insert "(")
3399 (js2-print-list (js2-new-node-args n))
3400 (insert ")")
3401 (when (js2-new-node-initializer n)
3402 (insert " ")
3403 (js2-print-ast (js2-new-node-initializer n))))
3404
3405 (defstruct (js2-name-node
3406 (:include js2-node)
3407 (:constructor nil)
3408 (:constructor make-js2-name-node (&key (type js2-NAME)
3409 (pos js2-token-beg)
3410 (len (- js2-ts-cursor
3411 js2-token-beg))
3412 (name js2-ts-string))))
3413 "AST node for a JavaScript identifier"
3414 name ; a string
3415 scope) ; a `js2-scope' (optional, used for codegen)
3416
3417 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3418 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3419
3420 (defun js2-print-name-node (n i)
3421 (insert (js2-make-pad i)
3422 (js2-name-node-name n)))
3423
3424 (defsubst js2-name-node-length (node)
3425 "Return identifier length of NODE, a `js2-name-node'.
3426 Returns 0 if NODE is nil or its identifier field is nil."
3427 (if node
3428 (length (js2-name-node-name node))
3429 0))
3430
3431 (defstruct (js2-number-node
3432 (:include js2-node)
3433 (:constructor nil)
3434 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3435 (pos js2-token-beg)
3436 (len (- js2-ts-cursor
3437 js2-token-beg))
3438 (value js2-ts-string)
3439 (num-value js2-ts-number))))
3440 "AST node for a number literal."
3441 value ; the original string, e.g. "6.02e23"
3442 num-value) ; the parsed number value
3443
3444 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3445 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3446
3447 (defun js2-print-number-node (n i)
3448 (insert (js2-make-pad i)
3449 (number-to-string (js2-number-node-num-value n))))
3450
3451 (defstruct (js2-regexp-node
3452 (:include js2-node)
3453 (:constructor nil)
3454 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3455 (pos js2-token-beg)
3456 (len (- js2-ts-cursor
3457 js2-token-beg))
3458 value
3459 flags)))
3460 "AST node for a regular expression literal."
3461 value ; the regexp string, without // delimiters
3462 flags) ; a string of flags, e.g. `mi'.
3463
3464 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3465 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3466
3467 (defun js2-print-regexp (n i)
3468 (insert (js2-make-pad i)
3469 "/"
3470 (js2-regexp-node-value n)
3471 "/")
3472 (if (js2-regexp-node-flags n)
3473 (insert (js2-regexp-node-flags n))))
3474
3475 (defstruct (js2-string-node
3476 (:include js2-node)
3477 (:constructor nil)
3478 (:constructor make-js2-string-node (&key (type js2-STRING)
3479 (pos js2-token-beg)
3480 (len (- js2-ts-cursor
3481 js2-token-beg))
3482 (value js2-ts-string))))
3483 "String literal.
3484 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3485 You can tell the quote type by looking at the first character."
3486 value) ; the characters of the string, including the quotes
3487
3488 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3489 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3490
3491 (defun js2-print-string-node (n i)
3492 (insert (js2-make-pad i)
3493 (js2-node-string n)))
3494
3495 (defstruct (js2-array-node
3496 (:include js2-node)
3497 (:constructor nil)
3498 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3499 (pos js2-ts-cursor)
3500 len
3501 elems)))
3502 "AST node for an array literal."
3503 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3504
3505 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3506 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3507
3508 (defun js2-visit-array-node (n v)
3509 (dolist (e (js2-array-node-elems n))
3510 (js2-visit-ast e v)))
3511
3512 (defun js2-print-array-node (n i)
3513 (insert (js2-make-pad i) "[")
3514 (js2-print-list (js2-array-node-elems n))
3515 (insert "]"))
3516
3517 (defstruct (js2-object-node
3518 (:include js2-node)
3519 (:constructor nil)
3520 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3521 (pos js2-ts-cursor)
3522 len
3523 elems)))
3524 "AST node for an object literal expression.
3525 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3526 the latter represents abbreviation in destructuring expressions."
3527 elems)
3528
3529 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3530 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3531
3532 (defun js2-visit-object-node (n v)
3533 (dolist (e (js2-object-node-elems n))
3534 (js2-visit-ast e v)))
3535
3536 (defun js2-print-object-node (n i)
3537 (insert (js2-make-pad i) "{")
3538 (js2-print-list (js2-object-node-elems n))
3539 (insert "}"))
3540
3541 (defstruct (js2-object-prop-node
3542 (:include js2-infix-node)
3543 (:constructor nil)
3544 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3545 (pos js2-ts-cursor)
3546 len
3547 left
3548 right
3549 op-pos)))
3550 "AST node for an object literal prop:value entry.
3551 The `left' field is the property: a name node, string node or number node.
3552 The `right' field is a `js2-node' representing the initializer value.")
3553
3554 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3555 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3556
3557 (defun js2-print-object-prop-node (n i)
3558 (insert (js2-make-pad i))
3559 (js2-print-ast (js2-object-prop-node-left n) 0)
3560 (insert ":")
3561 (js2-print-ast (js2-object-prop-node-right n) 0))
3562
3563 (defstruct (js2-getter-setter-node
3564 (:include js2-infix-node)
3565 (:constructor nil)
3566 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3567 (pos js2-ts-cursor)
3568 len
3569 left
3570 right)))
3571 "AST node for a getter/setter property in an object literal.
3572 The `left' field is the `js2-name-node' naming the getter/setter prop.
3573 The `right' field is always an anonymous `js2-function-node' with a node
3574 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3575
3576 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3577 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3578
3579 (defun js2-print-getter-setter (n i)
3580 (let ((pad (js2-make-pad i))
3581 (left (js2-getter-setter-node-left n))
3582 (right (js2-getter-setter-node-right n)))
3583 (insert pad)
3584 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3585 (js2-print-ast left 0)
3586 (js2-print-ast right 0)))
3587
3588 (defstruct (js2-prop-get-node
3589 (:include js2-infix-node)
3590 (:constructor nil)
3591 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3592 (pos js2-ts-cursor)
3593 len
3594 left
3595 right)))
3596 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3597
3598 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3599 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3600
3601 (defun js2-visit-prop-get-node (n v)
3602 (js2-visit-ast (js2-prop-get-node-left n) v)
3603 (js2-visit-ast (js2-prop-get-node-right n) v))
3604
3605 (defun js2-print-prop-get-node (n i)
3606 (insert (js2-make-pad i))
3607 (js2-print-ast (js2-prop-get-node-left n) 0)
3608 (insert ".")
3609 (js2-print-ast (js2-prop-get-node-right n) 0))
3610
3611 (defstruct (js2-elem-get-node
3612 (:include js2-node)
3613 (:constructor nil)
3614 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3615 (pos js2-ts-cursor)
3616 len
3617 target
3618 element
3619 lb
3620 rb)))
3621 "AST node for an array index expression such as foo[bar]."
3622 target ; a `js2-node' - the expression preceding the "."
3623 element ; a `js2-node' - the expression in brackets
3624 lb ; position of left-bracket, nil if omitted
3625 rb) ; position of right-bracket, nil if omitted
3626
3627 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3628 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3629
3630 (defun js2-visit-elem-get-node (n v)
3631 (js2-visit-ast (js2-elem-get-node-target n) v)
3632 (js2-visit-ast (js2-elem-get-node-element n) v))
3633
3634 (defun js2-print-elem-get-node (n i)
3635 (insert (js2-make-pad i))
3636 (js2-print-ast (js2-elem-get-node-target n) 0)
3637 (insert "[")
3638 (js2-print-ast (js2-elem-get-node-element n) 0)
3639 (insert "]"))
3640
3641 (defstruct (js2-call-node
3642 (:include js2-node)
3643 (:constructor nil)
3644 (:constructor make-js2-call-node (&key (type js2-CALL)
3645 (pos js2-ts-cursor)
3646 len
3647 target
3648 args
3649 lp
3650 rp)))
3651 "AST node for a JavaScript function call."
3652 target ; a `js2-node' evaluating to the function to call
3653 args ; a lisp list of `js2-node' arguments
3654 lp ; position of open-paren, or nil if missing
3655 rp) ; position of close-paren, or nil if missing
3656
3657 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3658 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3659
3660 (defun js2-visit-call-node (n v)
3661 (js2-visit-ast (js2-call-node-target n) v)
3662 (dolist (arg (js2-call-node-args n))
3663 (js2-visit-ast arg v)))
3664
3665 (defun js2-print-call-node (n i)
3666 (insert (js2-make-pad i))
3667 (js2-print-ast (js2-call-node-target n) 0)
3668 (insert "(")
3669 (js2-print-list (js2-call-node-args n))
3670 (insert ")"))
3671
3672 (defstruct (js2-yield-node
3673 (:include js2-node)
3674 (:constructor nil)
3675 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3676 (pos js2-ts-cursor)
3677 len
3678 value)))
3679 "AST node for yield statement or expression."
3680 value) ; optional: value to be yielded
3681
3682 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3683 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3684
3685 (defun js2-visit-yield-node (n v)
3686 (js2-visit-ast (js2-yield-node-value n) v))
3687
3688 (defun js2-print-yield-node (n i)
3689 (insert (js2-make-pad i))
3690 (insert "yield")
3691 (when (js2-yield-node-value n)
3692 (insert " ")
3693 (js2-print-ast (js2-yield-node-value n) 0)))
3694
3695 (defstruct (js2-paren-node
3696 (:include js2-node)
3697 (:constructor nil)
3698 (:constructor make-js2-paren-node (&key (type js2-LP)
3699 (pos js2-ts-cursor)
3700 len
3701 expr)))
3702 "AST node for a parenthesized expression.
3703 In particular, used when the parens are syntactically optional,
3704 as opposed to required parens such as those enclosing an if-conditional."
3705 expr) ; `js2-node'
3706
3707 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3708 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3709
3710 (defun js2-visit-paren-node (n v)
3711 (js2-visit-ast (js2-paren-node-expr n) v))
3712
3713 (defun js2-print-paren-node (n i)
3714 (insert (js2-make-pad i))
3715 (insert "(")
3716 (js2-print-ast (js2-paren-node-expr n) 0)
3717 (insert ")"))
3718
3719 (defstruct (js2-array-comp-node
3720 (:include js2-scope)
3721 (:constructor nil)
3722 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3723 (pos js2-ts-cursor)
3724 len
3725 result
3726 loops
3727 filter
3728 if-pos
3729 lp
3730 rp)))
3731 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3732 result ; result expression (just after left-bracket)
3733 loops ; a lisp list of `js2-array-comp-loop-node'
3734 filter ; guard/filter expression
3735 if-pos ; buffer pos of 'if' keyword, if present, else nil
3736 lp ; buffer position of if-guard left-paren, or nil if not present
3737 rp) ; buffer position of if-guard right-paren, or nil if not present
3738
3739 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3740 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3741
3742 (defun js2-visit-array-comp-node (n v)
3743 (js2-visit-ast (js2-array-comp-node-result n) v)
3744 (dolist (l (js2-array-comp-node-loops n))
3745 (js2-visit-ast l v))
3746 (js2-visit-ast (js2-array-comp-node-filter n) v))
3747
3748 (defun js2-print-array-comp-node (n i)
3749 (let ((pad (js2-make-pad i))
3750 (result (js2-array-comp-node-result n))
3751 (loops (js2-array-comp-node-loops n))
3752 (filter (js2-array-comp-node-filter n)))
3753 (insert pad "[")
3754 (js2-print-ast result 0)
3755 (dolist (l loops)
3756 (insert " ")
3757 (js2-print-ast l 0))
3758 (when filter
3759 (insert " if (")
3760 (js2-print-ast filter 0))
3761 (insert ")]")))
3762
3763 (defstruct (js2-array-comp-loop-node
3764 (:include js2-for-in-node)
3765 (:constructor nil)
3766 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3767 (pos js2-ts-cursor)
3768 len
3769 iterator
3770 object
3771 in-pos
3772 foreach-p
3773 each-pos
3774 lp
3775 rp)))
3776 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3777
3778 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3779 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3780
3781 (defun js2-visit-array-comp-loop (n v)
3782 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3783 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3784
3785 (defun js2-print-array-comp-loop (n i)
3786 (insert "for (")
3787 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3788 (insert " in ")
3789 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3790 (insert ")"))
3791
3792 (defstruct (js2-empty-expr-node
3793 (:include js2-node)
3794 (:constructor nil)
3795 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3796 (pos js2-token-beg)
3797 len)))
3798 "AST node for an empty expression.")
3799
3800 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3801 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3802
3803 (defstruct (js2-xml-node
3804 (:include js2-block-node)
3805 (:constructor nil)
3806 (:constructor make-js2-xml-node (&key (type js2-XML)
3807 (pos js2-token-beg)
3808 len
3809 kids)))
3810 "AST node for initial parse of E4X literals.
3811 The kids field is a list of XML fragments, each a `js2-string-node' or
3812 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3813
3814 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3815 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3816
3817 (defun js2-print-xml-node (n i)
3818 (dolist (kid (js2-xml-node-kids n))
3819 (js2-print-ast kid i)))
3820
3821 (defstruct (js2-xml-js-expr-node
3822 (:include js2-xml-node)
3823 (:constructor nil)
3824 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3825 (pos js2-ts-cursor)
3826 len
3827 expr)))
3828 "AST node for an embedded JavaScript {expression} in an E4X literal.
3829 The start and end fields correspond to the curly-braces."
3830 expr) ; a `js2-expr-node' of some sort
3831
3832 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3833 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3834
3835 (defun js2-visit-xml-js-expr (n v)
3836 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3837
3838 (defun js2-print-xml-js-expr (n i)
3839 (insert (js2-make-pad i))
3840 (insert "{")
3841 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3842 (insert "}"))
3843
3844 (defstruct (js2-xml-dot-query-node
3845 (:include js2-infix-node)
3846 (:constructor nil)
3847 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3848 (pos js2-ts-cursor)
3849 op-pos
3850 len
3851 left
3852 right
3853 rp)))
3854 "AST node for an E4X foo.(bar) filter expression.
3855 Note that the left-paren is automatically the character immediately
3856 following the dot (.) in the operator. No whitespace is permitted
3857 between the dot and the lp by the scanner."
3858 rp)
3859
3860 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3861 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3862
3863 (defun js2-print-xml-dot-query (n i)
3864 (insert (js2-make-pad i))
3865 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3866 (insert ".(")
3867 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3868 (insert ")"))
3869
3870 (defstruct (js2-xml-ref-node
3871 (:include js2-node)
3872 (:constructor nil)) ; abstract
3873 "Base type for E4X XML attribute-access or property-get expressions.
3874 Such expressions can take a variety of forms. The general syntax has
3875 three parts:
3876
3877 - (optional) an @ (specifying an attribute access)
3878 - (optional) a namespace (a `js2-name-node') and double-colon
3879 - (required) either a `js2-name-node' or a bracketed [expression]
3880
3881 The property-name expressions (examples: ns::name, @name) are
3882 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3883 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3884
3885 This node type (or more specifically, its subclasses) will sometimes
3886 be the right-hand child of a `js2-prop-get-node' or a
3887 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3888 The `js2-xml-ref-node' may also be a standalone primary expression with
3889 no explicit target, which is valid in certain expression contexts such as
3890
3891 company..employee.(@id < 100)
3892
3893 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3894 expression whose parent is a `js2-xml-dot-query-node'."
3895 namespace
3896 at-pos
3897 colon-pos)
3898
3899 (defsubst js2-xml-ref-node-attr-access-p (node)
3900 "Return non-nil if this expression began with an @-token."
3901 (and (numberp (js2-xml-ref-node-at-pos node))
3902 (plusp (js2-xml-ref-node-at-pos node))))
3903
3904 (defstruct (js2-xml-prop-ref-node
3905 (:include js2-xml-ref-node)
3906 (:constructor nil)
3907 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3908 (pos js2-token-beg)
3909 len
3910 propname
3911 namespace
3912 at-pos
3913 colon-pos)))
3914 "AST node for an E4X XML [expr] property-ref expression.
3915 The JavaScript syntax is an optional @, an optional ns::, and a name.
3916
3917 [ '@' ] [ name '::' ] name
3918
3919 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3920 @ns::*, @*::attr, @*::*, and @*.
3921
3922 The node starts at the @ token, if present. Otherwise it starts at the
3923 namespace name. The node bounds extend through the closing right-bracket,
3924 or if it is missing due to a syntax error, through the end of the index
3925 expression."
3926 propname)
3927
3928 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3929 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3930
3931 (defun js2-visit-xml-prop-ref-node (n v)
3932 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3933 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3934
3935 (defun js2-print-xml-prop-ref-node (n i)
3936 (insert (js2-make-pad i))
3937 (if (js2-xml-ref-node-attr-access-p n)
3938 (insert "@"))
3939 (when (js2-xml-prop-ref-node-namespace n)
3940 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3941 (insert "::"))
3942 (if (js2-xml-prop-ref-node-propname n)
3943 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3944
3945 (defstruct (js2-xml-elem-ref-node
3946 (:include js2-xml-ref-node)
3947 (:constructor nil)
3948 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3949 (pos js2-token-beg)
3950 len
3951 expr
3952 lb
3953 rb
3954 namespace
3955 at-pos
3956 colon-pos)))
3957 "AST node for an E4X XML [expr] member-ref expression.
3958 Syntax:
3959
3960 [ '@' ] [ name '::' ] '[' expr ']'
3961
3962 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3963
3964 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3965 is not a legal E4X XML element-ref expression, since it's already used
3966 for standard JavaScript element-get array indexing. Hence, a
3967 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3968 non-nil namespace node, or both.
3969
3970 The node starts at the @ token, if present. Otherwise it starts
3971 at the namespace name. The node bounds extend through the closing
3972 right-bracket, or if it is missing due to a syntax error, through the
3973 end of the index expression."
3974 expr ; the bracketed index expression
3975 lb
3976 rb)
3977
3978 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3979 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3980
3981 (defun js2-visit-xml-elem-ref-node (n v)
3982 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3983 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3984
3985 (defun js2-print-xml-elem-ref-node (n i)
3986 (insert (js2-make-pad i))
3987 (if (js2-xml-ref-node-attr-access-p n)
3988 (insert "@"))
3989 (when (js2-xml-elem-ref-node-namespace n)
3990 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3991 (insert "::"))
3992 (insert "[")
3993 (if (js2-xml-elem-ref-node-expr n)
3994 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3995 (insert "]"))
3996
3997 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3998
3999 (defstruct (js2-xml-start-tag-node
4000 (:include js2-xml-node)
4001 (:constructor nil)
4002 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4003 (pos js2-ts-cursor)
4004 len
4005 name
4006 attrs
4007 kids
4008 empty-p)))
4009 "AST node for an XML start-tag. Not currently used.
4010 The `kids' field is a lisp list of child content nodes."
4011 name ; a `js2-xml-name-node'
4012 attrs ; a lisp list of `js2-xml-attr-node'
4013 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4014
4015 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4016 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4017
4018 (defun js2-visit-xml-start-tag (n v)
4019 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4020 (dolist (attr (js2-xml-start-tag-node-attrs n))
4021 (js2-visit-ast attr v))
4022 (js2-visit-block n v))
4023
4024 (defun js2-print-xml-start-tag (n i)
4025 (insert (js2-make-pad i) "<")
4026 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4027 (when (js2-xml-start-tag-node-attrs n)
4028 (insert " ")
4029 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4030 (insert ">"))
4031
4032 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4033 ;; and add the end-tag to the kids list of the parent as well.
4034 (defstruct (js2-xml-end-tag-node
4035 (:include js2-xml-node)
4036 (:constructor nil)
4037 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4038 (pos js2-ts-cursor)
4039 len
4040 name)))
4041 "AST node for an XML end-tag. Not currently used."
4042 name) ; a `js2-xml-name-node'
4043
4044 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4045 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4046
4047 (defun js2-visit-xml-end-tag (n v)
4048 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4049
4050 (defun js2-print-xml-end-tag (n i)
4051 (insert (js2-make-pad i))
4052 (insert "</")
4053 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4054 (insert ">"))
4055
4056 (defstruct (js2-xml-name-node
4057 (:include js2-xml-node)
4058 (:constructor nil)
4059 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4060 (pos js2-ts-cursor)
4061 len
4062 namespace
4063 kids)))
4064 "AST node for an E4X XML name. Not currently used.
4065 Any XML name can be qualified with a namespace, hence the namespace field.
4066 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4067 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4068 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4069 namespace) ; a `js2-string-node'
4070
4071 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4072 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4073
4074 (defun js2-visit-xml-name-node (n v)
4075 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4076
4077 (defun js2-print-xml-name-node (n i)
4078 (insert (js2-make-pad i))
4079 (when (js2-xml-name-node-namespace n)
4080 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4081 (insert "::"))
4082 (dolist (kid (js2-xml-name-node-kids n))
4083 (js2-print-ast kid 0)))
4084
4085 (defstruct (js2-xml-pi-node
4086 (:include js2-xml-node)
4087 (:constructor nil)
4088 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4089 (pos js2-ts-cursor)
4090 len
4091 name
4092 attrs)))
4093 "AST node for an E4X XML processing instruction. Not currently used."
4094 name ; a `js2-xml-name-node'
4095 attrs) ; a list of `js2-xml-attr-node'
4096
4097 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4098 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4099
4100 (defun js2-visit-xml-pi-node (n v)
4101 (js2-visit-ast (js2-xml-pi-node-name n) v)
4102 (dolist (attr (js2-xml-pi-node-attrs n))
4103 (js2-visit-ast attr v)))
4104
4105 (defun js2-print-xml-pi-node (n i)
4106 (insert (js2-make-pad i) "<?")
4107 (js2-print-ast (js2-xml-pi-node-name n))
4108 (when (js2-xml-pi-node-attrs n)
4109 (insert " ")
4110 (js2-print-list (js2-xml-pi-node-attrs n)))
4111 (insert "?>"))
4112
4113 (defstruct (js2-xml-cdata-node
4114 (:include js2-xml-node)
4115 (:constructor nil)
4116 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4117 (pos js2-ts-cursor)
4118 len
4119 content)))
4120 "AST node for a CDATA escape section. Not currently used."
4121 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4122
4123 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4124 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4125
4126 (defun js2-visit-xml-cdata-node (n v)
4127 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4128
4129 (defun js2-print-xml-cdata-node (n i)
4130 (insert (js2-make-pad i))
4131 (js2-print-ast (js2-xml-cdata-node-content n)))
4132
4133 (defstruct (js2-xml-attr-node
4134 (:include js2-xml-node)
4135 (:constructor nil)
4136 (:constructor make-js2-attr-node (&key (type js2-XML)
4137 (pos js2-ts-cursor)
4138 len
4139 name
4140 value
4141 eq-pos
4142 quote-type)))
4143 "AST node representing a foo='bar' XML attribute value. Not yet used."
4144 name ; a `js2-xml-name-node'
4145 value ; a `js2-xml-name-node'
4146 eq-pos ; buffer position of "=" sign
4147 quote-type) ; 'single or 'double
4148
4149 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4150 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4151
4152 (defun js2-visit-xml-attr-node (n v)
4153 (js2-visit-ast (js2-xml-attr-node-name n) v)
4154 (js2-visit-ast (js2-xml-attr-node-value n) v))
4155
4156 (defun js2-print-xml-attr-node (n i)
4157 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4158 "'"
4159 "\"")))
4160 (insert (js2-make-pad i))
4161 (js2-print-ast (js2-xml-attr-node-name n) 0)
4162 (insert "=" quote)
4163 (js2-print-ast (js2-xml-attr-node-value n) 0)
4164 (insert quote)))
4165
4166 (defstruct (js2-xml-text-node
4167 (:include js2-xml-node)
4168 (:constructor nil)
4169 (:constructor make-js2-text-node (&key (type js2-XML)
4170 (pos js2-ts-cursor)
4171 len
4172 content)))
4173 "AST node for an E4X XML text node. Not currently used."
4174 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4175
4176 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4177 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4178
4179 (defun js2-visit-xml-text-node (n v)
4180 (js2-visit-ast (js2-xml-text-node-content n) v))
4181
4182 (defun js2-print-xml-text-node (n i)
4183 (insert (js2-make-pad i))
4184 (dolist (kid (js2-xml-text-node-content n))
4185 (js2-print-ast kid)))
4186
4187 (defstruct (js2-xml-comment-node
4188 (:include js2-xml-node)
4189 (:constructor nil)
4190 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4191 (pos js2-ts-cursor)
4192 len)))
4193 "AST node for E4X XML comment. Not currently used.")
4194
4195 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4196 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4197
4198 (defun js2-print-xml-comment (n i)
4199 (insert (js2-make-pad i)
4200 (js2-node-string n)))
4201
4202 ;;; Node utilities
4203
4204 (defsubst js2-node-line (n)
4205 "Fetch the source line number at the start of node N.
4206 This is O(n) in the length of the source buffer; use prudently."
4207 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4208
4209 (defsubst js2-block-node-kid (n i)
4210 "Return child I of node N, or nil if there aren't that many."
4211 (nth i (js2-block-node-kids n)))
4212
4213 (defsubst js2-block-node-first (n)
4214 "Return first child of block node N, or nil if there is none."
4215 (first (js2-block-node-kids n)))
4216
4217 (defun js2-node-root (n)
4218 "Return the root of the AST containing N.
4219 If N has no parent pointer, returns N."
4220 (let ((parent (js2-node-parent n)))
4221 (if parent
4222 (js2-node-root parent)
4223 n)))
4224
4225 (defun js2-node-position-in-parent (node &optional parent)
4226 "Return the position of NODE in parent's block-kids list.
4227 PARENT can be supplied if known. Positioned returned is zero-indexed.
4228 Returns 0 if NODE is not a child of a block statement, or if NODE
4229 is not a statement node."
4230 (let ((p (or parent (js2-node-parent node)))
4231 (i 0))
4232 (if (not (js2-block-node-p p))
4233 i
4234 (or (js2-position node (js2-block-node-kids p))
4235 0))))
4236
4237 (defsubst js2-node-short-name (n)
4238 "Return the short name of node N as a string, e.g. `js2-if-node'."
4239 (substring (symbol-name (aref n 0))
4240 (length "cl-struct-")))
4241
4242 (defsubst js2-node-child-list (node)
4243 "Return the child list for NODE, a lisp list of nodes.
4244 Works for block nodes, array nodes, obj literals, funarg lists,
4245 var decls and try nodes (for catch clauses). Note that you should call
4246 `js2-block-node-kids' on the function body for the body statements.
4247 Returns nil for zero-length child lists or unsupported nodes."
4248 (cond
4249 ((js2-function-node-p node)
4250 (js2-function-node-params node))
4251 ((js2-block-node-p node)
4252 (js2-block-node-kids node))
4253 ((js2-try-node-p node)
4254 (js2-try-node-catch-clauses node))
4255 ((js2-array-node-p node)
4256 (js2-array-node-elems node))
4257 ((js2-object-node-p node)
4258 (js2-object-node-elems node))
4259 ((js2-call-node-p node)
4260 (js2-call-node-args node))
4261 ((js2-new-node-p node)
4262 (js2-new-node-args node))
4263 ((js2-var-decl-node-p node)
4264 (js2-var-decl-node-kids node))
4265 (t
4266 nil)))
4267
4268 (defsubst js2-node-set-child-list (node kids)
4269 "Set the child list for NODE to KIDS."
4270 (cond
4271 ((js2-function-node-p node)
4272 (setf (js2-function-node-params node) kids))
4273 ((js2-block-node-p node)
4274 (setf (js2-block-node-kids node) kids))
4275 ((js2-try-node-p node)
4276 (setf (js2-try-node-catch-clauses node) kids))
4277 ((js2-array-node-p node)
4278 (setf (js2-array-node-elems node) kids))
4279 ((js2-object-node-p node)
4280 (setf (js2-object-node-elems node) kids))
4281 ((js2-call-node-p node)
4282 (setf (js2-call-node-args node) kids))
4283 ((js2-new-node-p node)
4284 (setf (js2-new-node-args node) kids))
4285 ((js2-var-decl-node-p node)
4286 (setf (js2-var-decl-node-kids node) kids))
4287 (t
4288 (error "Unsupported node type: %s" (js2-node-short-name node))))
4289 kids)
4290
4291 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4292 (defconst js2-paren-expr-nodes
4293 '(cl-struct-js2-array-comp-loop-node
4294 cl-struct-js2-array-comp-node
4295 cl-struct-js2-call-node
4296 cl-struct-js2-catch-node
4297 cl-struct-js2-do-node
4298 cl-struct-js2-elem-get-node
4299 cl-struct-js2-for-in-node
4300 cl-struct-js2-for-node
4301 cl-struct-js2-function-node
4302 cl-struct-js2-if-node
4303 cl-struct-js2-let-node
4304 cl-struct-js2-new-node
4305 cl-struct-js2-paren-node
4306 cl-struct-js2-switch-node
4307 cl-struct-js2-while-node
4308 cl-struct-js2-with-node
4309 cl-struct-js2-xml-dot-query-node)
4310 "Node types that can have a parenthesized child expression.
4311 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4312
4313 (defsubst js2-paren-expr-node-p (node)
4314 "Return t for nodes that typically have a parenthesized child expression.
4315 Useful for computing the indentation anchors for arg-lists and conditions.
4316 Note that it may return a false positive, for instance when NODE is
4317 a `js2-new-node' and there are no arguments or parentheses."
4318 (memq (aref node 0) js2-paren-expr-nodes))
4319
4320 ;; Fake polymorphism... yech.
4321 (defsubst js2-node-lp (node)
4322 "Return relative left-paren position for NODE, if applicable.
4323 For `js2-elem-get-node' structs, returns left-bracket position.
4324 Note that the position may be nil in the case of a parse error."
4325 (cond
4326 ((js2-elem-get-node-p node)
4327 (js2-elem-get-node-lb node))
4328 ((js2-loop-node-p node)
4329 (js2-loop-node-lp node))
4330 ((js2-function-node-p node)
4331 (js2-function-node-lp node))
4332 ((js2-if-node-p node)
4333 (js2-if-node-lp node))
4334 ((js2-new-node-p node)
4335 (js2-new-node-lp node))
4336 ((js2-call-node-p node)
4337 (js2-call-node-lp node))
4338 ((js2-paren-node-p node)
4339 (js2-node-pos node))
4340 ((js2-switch-node-p node)
4341 (js2-switch-node-lp node))
4342 ((js2-catch-node-p node)
4343 (js2-catch-node-lp node))
4344 ((js2-let-node-p node)
4345 (js2-let-node-lp node))
4346 ((js2-array-comp-node-p node)
4347 (js2-array-comp-node-lp node))
4348 ((js2-with-node-p node)
4349 (js2-with-node-lp node))
4350 ((js2-xml-dot-query-node-p node)
4351 (1+ (js2-infix-node-op-pos node)))
4352 (t
4353 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4354
4355 ;; Fake polymorphism... blech.
4356 (defsubst js2-node-rp (node)
4357 "Return relative right-paren position for NODE, if applicable.
4358 For `js2-elem-get-node' structs, returns right-bracket position.
4359 Note that the position may be nil in the case of a parse error."
4360 (cond
4361 ((js2-elem-get-node-p node)
4362 (js2-elem-get-node-lb node))
4363 ((js2-loop-node-p node)
4364 (js2-loop-node-rp node))
4365 ((js2-function-node-p node)
4366 (js2-function-node-rp node))
4367 ((js2-if-node-p node)
4368 (js2-if-node-rp node))
4369 ((js2-new-node-p node)
4370 (js2-new-node-rp node))
4371 ((js2-call-node-p node)
4372 (js2-call-node-rp node))
4373 ((js2-paren-node-p node)
4374 (+ (js2-node-pos node) (js2-node-len node)))
4375 ((js2-switch-node-p node)
4376 (js2-switch-node-rp node))
4377 ((js2-catch-node-p node)
4378 (js2-catch-node-rp node))
4379 ((js2-let-node-p node)
4380 (js2-let-node-rp node))
4381 ((js2-array-comp-node-p node)
4382 (js2-array-comp-node-rp node))
4383 ((js2-with-node-p node)
4384 (js2-with-node-rp node))
4385 ((js2-xml-dot-query-node-p node)
4386 (1+ (js2-xml-dot-query-node-rp node)))
4387 (t
4388 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4389
4390 (defsubst js2-node-first-child (node)
4391 "Returns the first element of `js2-node-child-list' for NODE."
4392 (car (js2-node-child-list node)))
4393
4394 (defsubst js2-node-last-child (node)
4395 "Returns the last element of `js2-node-last-child' for NODE."
4396 (car (last (js2-node-child-list node))))
4397
4398 (defun js2-node-prev-sibling (node)
4399 "Return the previous statement in parent.
4400 Works for parents supported by `js2-node-child-list'.
4401 Returns nil if NODE is not in the parent, or PARENT is
4402 not a supported node, or if NODE is the first child."
4403 (let* ((p (js2-node-parent node))
4404 (kids (js2-node-child-list p))
4405 (sib (car kids)))
4406 (while (and kids
4407 (not (eq node (cadr kids))))
4408 (setq kids (cdr kids)
4409 sib (car kids)))
4410 sib))
4411
4412 (defun js2-node-next-sibling (node)
4413 "Return the next statement in parent block.
4414 Returns nil if NODE is not in the block, or PARENT is not
4415 a block node, or if NODE is the last statement."
4416 (let* ((p (js2-node-parent node))
4417 (kids (js2-node-child-list p)))
4418 (while (and kids
4419 (not (eq node (car kids))))
4420 (setq kids (cdr kids)))
4421 (cadr kids)))
4422
4423 (defun js2-node-find-child-before (pos parent &optional after)
4424 "Find the last child that starts before POS in parent.
4425 If AFTER is non-nil, returns first child starting after POS.
4426 POS is an absolute buffer position. PARENT is any node
4427 supported by `js2-node-child-list'.
4428 Returns nil if no applicable child is found."
4429 (let ((kids (if (js2-function-node-p parent)
4430 (js2-block-node-kids (js2-function-node-body parent))
4431 (js2-node-child-list parent)))
4432 (beg (if (js2-function-node-p parent)
4433 (js2-node-abs-pos (js2-function-node-body parent))
4434 (js2-node-abs-pos parent)))
4435 kid
4436 result
4437 fn
4438 (continue t))
4439 (setq fn (if after '> '<))
4440 (while (and kids continue)
4441 (setq kid (car kids))
4442 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4443 (setq result kid
4444 continue (if after nil t))
4445 (setq continue (if after t nil)))
4446 (setq kids (cdr kids)))
4447 result))
4448
4449 (defun js2-node-find-child-after (pos parent)
4450 "Find first child that starts after POS in parent.
4451 POS is an absolute buffer position. PARENT is any node
4452 supported by `js2-node-child-list'.
4453 Returns nil if no applicable child is found."
4454 (js2-node-find-child-before pos parent 'after))
4455
4456 (defun js2-node-replace-child (pos parent new-node)
4457 "Replace node at index POS in PARENT with NEW-NODE.
4458 Only works for parents supported by `js2-node-child-list'."
4459 (let ((kids (js2-node-child-list parent))
4460 (i 0))
4461 (while (< i pos)
4462 (setq kids (cdr kids)
4463 i (1+ i)))
4464 (setcar kids new-node)
4465 (js2-node-add-children parent new-node)))
4466
4467 (defun js2-node-buffer (n)
4468 "Return the buffer associated with AST N.
4469 Returns nil if the buffer is not set as a property on the root
4470 node, or if parent links were not recorded during parsing."
4471 (let ((root (js2-node-root n)))
4472 (and root
4473 (js2-ast-root-p root)
4474 (js2-ast-root-buffer root))))
4475
4476 (defsubst js2-block-node-push (n kid)
4477 "Push js2-node KID onto the end of js2-block-node N's child list.
4478 KID is always added to the -end- of the kids list.
4479 Function also calls `js2-node-add-children' to add the parent link."
4480 (let ((kids (js2-node-child-list n)))
4481 (if kids
4482 (setcdr kids (nconc (cdr kids) (list kid)))
4483 (js2-node-set-child-list n (list kid)))
4484 (js2-node-add-children n kid)))
4485
4486 (defun js2-node-string (node)
4487 (let ((buf (js2-node-buffer node))
4488 pos)
4489 (unless buf
4490 (error "No buffer available for node %s" node))
4491 (save-excursion
4492 (set-buffer buf)
4493 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4494 (+ pos (js2-node-len node))))))
4495
4496 ;; Container for storing the node we're looking for in a traversal.
4497 (js2-deflocal js2-discovered-node nil)
4498
4499 ;; Keep track of absolute node position during traversals.
4500 (js2-deflocal js2-visitor-offset nil)
4501
4502 (js2-deflocal js2-node-search-point nil)
4503
4504 (when js2-mode-dev-mode-p
4505 (defun js2-find-node-at-point ()
4506 (interactive)
4507 (let ((node (js2-node-at-point)))
4508 (message "%s" (or node "No node found at point"))))
4509 (defun js2-node-name-at-point ()
4510 (interactive)
4511 (let ((node (js2-node-at-point)))
4512 (message "%s" (if node
4513 (js2-node-short-name node)
4514 "No node found at point.")))))
4515
4516 (defun js2-node-at-point (&optional pos skip-comments)
4517 "Return AST node at POS, a buffer position, defaulting to current point.
4518 The `js2-mode-ast' variable must be set to the current parse tree.
4519 Signals an error if the AST (`js2-mode-ast') is nil.
4520 Always returns a node - if it can't find one, it returns the root.
4521 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4522 (let ((ast js2-mode-ast)
4523 result)
4524 (unless ast
4525 (error "No JavaScript AST available"))
4526 ;; Look through comments first, since they may be inside nodes that
4527 ;; would otherwise report a match.
4528 (setq pos (or pos (point))
4529 result (if (> pos (js2-node-abs-end ast))
4530 ast
4531 (if (not skip-comments)
4532 (js2-comment-at-point pos))))
4533 (unless result
4534 (setq js2-discovered-node nil
4535 js2-visitor-offset 0
4536 js2-node-search-point pos)
4537 (unwind-protect
4538 (catch 'js2-visit-done
4539 (js2-visit-ast ast #'js2-node-at-point-visitor))
4540 (setq js2-visitor-offset nil
4541 js2-node-search-point nil))
4542 (setq result js2-discovered-node))
4543 ;; may have found a comment beyond end of last child node,
4544 ;; since visiting the ast-root looks at the comment-list last.
4545 (if (and skip-comments
4546 (js2-comment-node-p result))
4547 (setq result nil))
4548 (or result js2-mode-ast)))
4549
4550 (defun js2-node-at-point-visitor (node end-p)
4551 (let ((rel-pos (js2-node-pos node))
4552 abs-pos
4553 abs-end
4554 (point js2-node-search-point))
4555 (cond
4556 (end-p
4557 ;; this evaluates to a non-nil return value, even if it's zero
4558 (decf js2-visitor-offset rel-pos))
4559 ;; we already looked for comments before visiting, and don't want them now
4560 ((js2-comment-node-p node)
4561 nil)
4562 (t
4563 (setq abs-pos (incf js2-visitor-offset rel-pos)
4564 ;; we only want to use the node if the point is before
4565 ;; the last character position in the node, so we decrement
4566 ;; the absolute end by 1.
4567 abs-end (+ abs-pos (js2-node-len node) -1))
4568 (cond
4569 ;; If this node starts after search-point, stop the search.
4570 ((> abs-pos point)
4571 (throw 'js2-visit-done nil))
4572 ;; If this node ends before the search-point, don't check kids.
4573 ((> point abs-end)
4574 nil)
4575 (t
4576 ;; Otherwise point is within this node, possibly in a child.
4577 (setq js2-discovered-node node)
4578 t)))))) ; keep processing kids to look for more specific match
4579
4580 (defsubst js2-block-comment-p (node)
4581 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4582 (and (js2-comment-node-p node)
4583 (memq (js2-comment-node-format node) '(jsdoc block))))
4584
4585 ;; TODO: put the comments in a vector and binary-search them instead
4586 (defun js2-comment-at-point (&optional pos)
4587 "Look through scanned comment nodes for one containing POS.
4588 POS is a buffer position that defaults to current point.
4589 Function returns nil if POS was not in any comment node."
4590 (let ((ast js2-mode-ast)
4591 (x (or pos (point)))
4592 beg
4593 end)
4594 (unless ast
4595 (error "No JavaScript AST available"))
4596 (catch 'done
4597 ;; Comments are stored in lexical order.
4598 (dolist (comment (js2-ast-root-comments ast) nil)
4599 (setq beg (js2-node-abs-pos comment)
4600 end (+ beg (js2-node-len comment)))
4601 (if (and (>= x beg)
4602 (<= x end))
4603 (throw 'done comment))))))
4604
4605 (defun js2-mode-find-parent-fn (node)
4606 "Find function enclosing NODE.
4607 Returns nil if NODE is not inside a function."
4608 (setq node (js2-node-parent node))
4609 (while (and node (not (js2-function-node-p node)))
4610 (setq node (js2-node-parent node)))
4611 (and (js2-function-node-p node) node))
4612
4613 (defun js2-mode-find-enclosing-fn (node)
4614 "Find function or root enclosing NODE."
4615 (if (js2-ast-root-p node)
4616 node
4617 (setq node (js2-node-parent node))
4618 (while (not (or (js2-ast-root-p node)
4619 (js2-function-node-p node)))
4620 (setq node (js2-node-parent node)))
4621 node))
4622
4623 (defun js2-mode-find-enclosing-node (beg end)
4624 "Find script or function fully enclosing BEG and END."
4625 (let ((node (js2-node-at-point beg))
4626 pos
4627 (continue t))
4628 (while continue
4629 (if (or (js2-ast-root-p node)
4630 (and (js2-function-node-p node)
4631 (<= (setq pos (js2-node-abs-pos node)) beg)
4632 (>= (+ pos (js2-node-len node)) end)))
4633 (setq continue nil)
4634 (setq node (js2-node-parent node))))
4635 node))
4636
4637 (defun js2-node-parent-script-or-fn (node)
4638 "Find script or function immediately enclosing NODE.
4639 If NODE is the ast-root, returns nil."
4640 (if (js2-ast-root-p node)
4641 nil
4642 (setq node (js2-node-parent node))
4643 (while (and node (not (or (js2-function-node-p node)
4644 (js2-script-node-p node))))
4645 (setq node (js2-node-parent node)))
4646 node))
4647
4648 (defsubst js2-nested-function-p (node)
4649 "Return t if NODE is a nested function, or is inside a nested function."
4650 (js2-function-node-p (if (js2-function-node-p node)
4651 (js2-node-parent-script-or-fn node)
4652 (js2-node-parent-script-or-fn
4653 (js2-node-parent-script-or-fn node)))))
4654
4655 (defsubst js2-function-param-node-p (node)
4656 "Return non-nil if NODE is a param node of a `js2-function-node'."
4657 (let ((parent (js2-node-parent node)))
4658 (and parent
4659 (js2-function-node-p parent)
4660 (memq node (js2-function-node-params parent)))))
4661
4662 (defsubst js2-mode-shift-kids (kids start offset)
4663 (dolist (kid kids)
4664 (if (> (js2-node-pos kid) start)
4665 (incf (js2-node-pos kid) offset))))
4666
4667 (defsubst js2-mode-shift-children (parent start offset)
4668 "Update start-positions of all children of PARENT beyond START."
4669 (let ((root (js2-node-root parent)))
4670 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4671 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4672
4673 (defsubst js2-node-is-descendant (node ancestor)
4674 "Return t if NODE is a descendant of ANCESTOR."
4675 (while (and node
4676 (not (eq node ancestor)))
4677 (setq node (js2-node-parent node)))
4678 node)
4679
4680 ;;; visitor infrastructure
4681
4682 (defun js2-visit-none (node callback)
4683 "Visitor for AST node that have no node children."
4684 nil)
4685
4686 (defun js2-print-none (node indent)
4687 "Visitor for AST node with no printed representation.")
4688
4689 (defun js2-print-body (node indent)
4690 "Print a statement, or a block without braces."
4691 (if (js2-block-node-p node)
4692 (dolist (kid (js2-block-node-kids node))
4693 (js2-print-ast kid indent))
4694 (js2-print-ast node indent)))
4695
4696 (defun js2-print-list (args &optional delimiter)
4697 (loop with len = (length args)
4698 for arg in args
4699 for count from 1
4700 do
4701 (js2-print-ast arg 0)
4702 (if (< count len)
4703 (insert (or delimiter ", ")))))
4704
4705 (defun js2-print-tree (ast)
4706 "Prints an AST to the current buffer.
4707 Makes `js2-ast-parent-nodes' available to the printer functions."
4708 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4709 (js2-print-ast ast)))
4710
4711 (defun js2-print-ast (node &optional indent)
4712 "Helper function for printing AST nodes.
4713 Requires `js2-ast-parent-nodes' to be non-nil.
4714 You should use `js2-print-tree' instead of this function."
4715 (let ((printer (get (aref node 0) 'js2-printer))
4716 (i (or indent 0))
4717 (pos (js2-node-abs-pos node)))
4718 ;; TODO: wedge comments in here somewhere
4719 (if printer
4720 (funcall printer node i))))
4721
4722 (defconst js2-side-effecting-tokens
4723 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4724 (dolist (tt (list js2-ASSIGN
4725 js2-ASSIGN_ADD
4726 js2-ASSIGN_BITAND
4727 js2-ASSIGN_BITOR
4728 js2-ASSIGN_BITXOR
4729 js2-ASSIGN_DIV
4730 js2-ASSIGN_LSH
4731 js2-ASSIGN_MOD
4732 js2-ASSIGN_MUL
4733 js2-ASSIGN_RSH
4734 js2-ASSIGN_SUB
4735 js2-ASSIGN_URSH
4736 js2-BLOCK
4737 js2-BREAK
4738 js2-CALL
4739 js2-CATCH
4740 js2-CATCH_SCOPE
4741 js2-CONST
4742 js2-CONTINUE
4743 js2-DEBUGGER
4744 js2-DEC
4745 js2-DELPROP
4746 js2-DEL_REF
4747 js2-DO
4748 js2-ELSE
4749 js2-EMPTY
4750 js2-ENTERWITH
4751 js2-EXPORT
4752 js2-EXPR_RESULT
4753 js2-FINALLY
4754 js2-FOR
4755 js2-FUNCTION
4756 js2-GOTO
4757 js2-IF
4758 js2-IFEQ
4759 js2-IFNE
4760 js2-IMPORT
4761 js2-INC
4762 js2-JSR
4763 js2-LABEL
4764 js2-LEAVEWITH
4765 js2-LET
4766 js2-LETEXPR
4767 js2-LOCAL_BLOCK
4768 js2-LOOP
4769 js2-NEW
4770 js2-REF_CALL
4771 js2-RETHROW
4772 js2-RETURN
4773 js2-RETURN_RESULT
4774 js2-SEMI
4775 js2-SETELEM
4776 js2-SETELEM_OP
4777 js2-SETNAME
4778 js2-SETPROP
4779 js2-SETPROP_OP
4780 js2-SETVAR
4781 js2-SET_REF
4782 js2-SET_REF_OP
4783 js2-SWITCH
4784 js2-TARGET
4785 js2-THROW
4786 js2-TRY
4787 js2-VAR
4788 js2-WHILE
4789 js2-WITH
4790 js2-WITHEXPR
4791 js2-YIELD))
4792 (aset tokens tt t))
4793 (if js2-instanceof-has-side-effects
4794 (aset tokens js2-INSTANCEOF t))
4795 tokens))
4796
4797 (defun js2-node-has-side-effects (node)
4798 "Return t if NODE has side effects."
4799 (when node ; makes it easier to handle malformed expressions
4800 (let ((tt (js2-node-type node)))
4801 (cond
4802 ;; This doubtless needs some work, since EXPR_VOID is used
4803 ;; in several ways in Rhino, and I may not have caught them all.
4804 ;; I'll wait for people to notice incorrect warnings.
4805 ((and (= tt js2-EXPR_VOID)
4806 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4807 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4808 ((= tt js2-COMMA)
4809 (js2-node-has-side-effects (js2-infix-node-right node)))
4810 ((or (= tt js2-AND)
4811 (= tt js2-OR))
4812 (or (js2-node-has-side-effects (js2-infix-node-right node))
4813 (js2-node-has-side-effects (js2-infix-node-left node))))
4814 ((= tt js2-HOOK)
4815 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4816 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4817 ((js2-paren-node-p node)
4818 (js2-node-has-side-effects (js2-paren-node-expr node)))
4819 ((= tt js2-ERROR) ; avoid cascaded error messages
4820 nil)
4821 (t
4822 (aref js2-side-effecting-tokens tt))))))
4823
4824 (defun js2-member-expr-leftmost-name (node)
4825 "For an expr such as foo.bar.baz, return leftmost node foo.
4826 NODE is any `js2-node' object. If it represents a member expression,
4827 which is any sequence of property gets, element-gets, function calls,
4828 or xml descendants/filter operators, then we look at the lexically
4829 leftmost (first) node in the chain. If it is a name-node we return it.
4830 Note that NODE can be a raw name-node and it will be returned as well.
4831 If NODE is not a name-node or member expression, or if it is a member
4832 expression whose leftmost target is not a name node, returns nil."
4833 (let ((continue t)
4834 result)
4835 (while (and continue (not result))
4836 (cond
4837 ((js2-name-node-p node)
4838 (setq result node))
4839 ((js2-prop-get-node-p node)
4840 (setq node (js2-prop-get-node-left node)))
4841 ;; TODO: handle call-nodes, xml-nodes, others?
4842 (t
4843 (setq continue nil))))
4844 result))
4845
4846 (defconst js2-stmt-node-types
4847 (list js2-BLOCK
4848 js2-BREAK
4849 js2-CONTINUE
4850 js2-DEFAULT ; e4x "default xml namespace" statement
4851 js2-DO
4852 js2-EXPR_RESULT
4853 js2-EXPR_VOID
4854 js2-FOR
4855 js2-IF
4856 js2-RETURN
4857 js2-SWITCH
4858 js2-THROW
4859 js2-TRY
4860 js2-WHILE
4861 js2-WITH)
4862 "Node types that only appear in statement contexts.
4863 The list does not include nodes that always appear as the child
4864 of another specific statement type, such as switch-cases,
4865 catch and finally blocks, and else-clauses. The list also excludes
4866 nodes like yield, let and var, which may appear in either expression
4867 or statement context, and in the latter context always have a
4868 `js2-expr-stmt-node' parent. Finally, the list does not include
4869 functions or scripts, which are treated separately from statements
4870 by the JavaScript parser and runtime.")
4871
4872 (defun js2-stmt-node-p (node)
4873 "Heuristic for figuring out if NODE is a statement.
4874 Some node types can appear in either an expression context or a
4875 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4876 For these node types in a statement context, the parent will be a
4877 `js2-expr-stmt-node'.
4878 Functions aren't included in the check."
4879 (memq (js2-node-type node) js2-stmt-node-types))
4880
4881 (defsubst js2-mode-find-first-stmt (node)
4882 "Search upward starting from NODE looking for a statement.
4883 For purposes of this function, a `js2-function-node' counts."
4884 (while (not (or (js2-stmt-node-p node)
4885 (js2-function-node-p node)))
4886 (setq node (js2-node-parent node)))
4887 node)
4888
4889 (defun js2-node-parent-stmt (node)
4890 "Return the node's first ancestor that is a statement.
4891 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4892 appearing in a statement context will have a parent that is a
4893 `js2-expr-stmt-node' that will be returned by this function."
4894 (let ((parent (js2-node-parent node)))
4895 (if (or (null parent)
4896 (js2-stmt-node-p parent)
4897 (and (js2-function-node-p parent)
4898 (not (eq (js2-function-node-form parent)
4899 'FUNCTION_EXPRESSION))))
4900 parent
4901 (js2-node-parent-stmt parent))))
4902
4903 ;; In the Mozilla Rhino sources, Roshan James writes:
4904 ;; Does consistent-return analysis on the function body when strict mode is
4905 ;; enabled.
4906 ;;
4907 ;; function (x) { return (x+1) }
4908 ;;
4909 ;; is ok, but
4910 ;;
4911 ;; function (x) { if (x < 0) return (x+1); }
4912 ;;
4913 ;; is not because the function can potentially return a value when the
4914 ;; condition is satisfied and if not, the function does not explicitly
4915 ;; return a value.
4916 ;;
4917 ;; This extends to checking mismatches such as "return" and "return <value>"
4918 ;; used in the same function. Warnings are not emitted if inconsistent
4919 ;; returns exist in code that can be statically shown to be unreachable.
4920 ;; Ex.
4921 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4922 ;;
4923 ;; emits no warning. However if the loop had a break statement, then a
4924 ;; warning would be emitted.
4925 ;;
4926 ;; The consistency analysis looks at control structures such as loops, ifs,
4927 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4928 ;; warns the user about an inconsistent set of termination possibilities.
4929 ;;
4930 ;; These flags enumerate the possible ways a statement/function can
4931 ;; terminate. These flags are used by endCheck() and by the Parser to
4932 ;; detect inconsistent return usage.
4933 ;;
4934 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4935 ;; able to execute (example: throw, continue)
4936 ;;
4937 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4938 ;; next one. Statement such as return dont. A compound statement may have
4939 ;; some branch that drops off control to the next statement.
4940 ;;
4941 ;; END_RETURNS indicates that the statement can return with no value.
4942 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4943 ;;
4944 ;; A compound statement such as
4945 ;; if (condition) {
4946 ;; return value;
4947 ;; }
4948 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4949
4950 (defconst js2-END_UNREACHED 0)
4951 (defconst js2-END_DROPS_OFF 1)
4952 (defconst js2-END_RETURNS 2)
4953 (defconst js2-END_RETURNS_VALUE 4)
4954 (defconst js2-END_YIELDS 8)
4955
4956 (defun js2-has-consistent-return-usage (node)
4957 "Check that every return usage in a function body is consistent.
4958 Returns t if the function satisfies strict mode requirement."
4959 (let ((n (js2-end-check node)))
4960 ;; either it doesn't return a value in any branch...
4961 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4962 ;; or it returns a value (or is unreached) at every branch
4963 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4964 js2-END_RETURNS
4965 js2-END_YIELDS)))))
4966
4967 (defun js2-end-check-if (node)
4968 "Returns in the then and else blocks must be consistent with each other.
4969 If there is no else block, then the return statement can fall through.
4970 Returns logical OR of END_* flags"
4971 (let ((th (js2-if-node-then-part node))
4972 (el (js2-if-node-else-part node)))
4973 (if (null th)
4974 js2-END_UNREACHED
4975 (logior (js2-end-check th) (if el
4976 (js2-end-check el)
4977 js2-END_DROPS_OFF)))))
4978
4979 (defun js2-end-check-switch (node)
4980 "Consistency of return statements is checked between the case statements.
4981 If there is no default, then the switch can fall through. If there is a
4982 default, we check to see if all code paths in the default return or if
4983 there is a code path that can fall through.
4984 Returns logical OR of END_* flags."
4985 (let ((rv js2-END_UNREACHED)
4986 default-case)
4987 ;; examine the cases
4988 (catch 'break
4989 (dolist (c (js2-switch-node-cases node))
4990 (if (js2-case-node-expr c)
4991 (js2-set-flag rv (js2-end-check-block c))
4992 (setq default-case c)
4993 (throw 'break nil))))
4994 ;; we don't care how the cases drop into each other
4995 (js2-clear-flag rv js2-END_DROPS_OFF)
4996 ;; examine the default
4997 (js2-set-flag rv (if default-case
4998 (js2-end-check default-case)
4999 js2-END_DROPS_OFF))
5000 rv))
5001
5002 (defun js2-end-check-try (node)
5003 "If the block has a finally, return consistency is checked in the
5004 finally block. If all code paths in the finally return, then the
5005 returns in the try-catch blocks don't matter. If there is a code path
5006 that does not return or if there is no finally block, the returns
5007 of the try and catch blocks are checked for mismatch.
5008 Returns logical OR of END_* flags."
5009 (let ((finally (js2-try-node-finally-block node))
5010 rv)
5011 ;; check the finally if it exists
5012 (setq rv (if finally
5013 (js2-end-check (js2-finally-node-body finally))
5014 js2-END_DROPS_OFF))
5015 ;; If the finally block always returns, then none of the returns
5016 ;; in the try or catch blocks matter.
5017 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5018 (js2-clear-flag rv js2-END_DROPS_OFF)
5019 ;; examine the try block
5020 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5021 ;; check each catch block
5022 (dolist (cb (js2-try-node-catch-clauses node))
5023 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5024 rv))
5025
5026 (defun js2-end-check-loop (node)
5027 "Return statement in the loop body must be consistent. The default
5028 assumption for any kind of a loop is that it will eventually terminate.
5029 The only exception is a loop with a constant true condition. Code that
5030 follows such a loop is examined only if one can statically determine
5031 that there is a break out of the loop.
5032
5033 for(... ; ... ; ...) {}
5034 for(... in ... ) {}
5035 while(...) { }
5036 do { } while(...)
5037
5038 Returns logical OR of END_* flags."
5039 (let ((rv (js2-end-check (js2-loop-node-body node)))
5040 (condition (cond
5041 ((js2-while-node-p node)
5042 (js2-while-node-condition node))
5043 ((js2-do-node-p node)
5044 (js2-do-node-condition node))
5045 ((js2-for-node-p node)
5046 (js2-for-node-condition node)))))
5047
5048 ;; check to see if the loop condition is always true
5049 (if (and condition
5050 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5051 (js2-clear-flag rv js2-END_DROPS_OFF))
5052
5053 ;; look for effect of breaks
5054 (js2-set-flag rv (js2-node-get-prop node
5055 'CONTROL_BLOCK_PROP
5056 js2-END_UNREACHED))
5057 rv))
5058
5059 (defun js2-end-check-block (node)
5060 "A general block of code is examined statement by statement.
5061 If any statement (even a compound one) returns in all branches, then
5062 subsequent statements are not examined.
5063 Returns logical OR of END_* flags."
5064 (let* ((rv js2-END_DROPS_OFF)
5065 (kids (js2-block-node-kids node))
5066 (n (car kids)))
5067 ;; Check each statment. If the statement can continue onto the next
5068 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5069 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5070 (js2-clear-flag rv js2-END_DROPS_OFF)
5071 (js2-set-flag rv (js2-end-check n))
5072 (setq kids (cdr kids)
5073 n (car kids)))
5074 rv))
5075
5076 (defun js2-end-check-label (node)
5077 "A labeled statement implies that there may be a break to the label.
5078 The function processes the labeled statement and then checks the
5079 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5080 particular label.
5081 Returns logical OR of END_* flags."
5082 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5083 (logior rv (js2-node-get-prop node
5084 'CONTROL_BLOCK_PROP
5085 js2-END_UNREACHED))))
5086
5087 (defun js2-end-check-break (node)
5088 "When a break is encountered annotate the statement being broken
5089 out of by setting its CONTROL_BLOCK_PROP property.
5090 Returns logical OR of END_* flags."
5091 (and (js2-break-node-target node)
5092 (js2-node-set-prop (js2-break-node-target node)
5093 'CONTROL_BLOCK_PROP
5094 js2-END_DROPS_OFF))
5095 js2-END_UNREACHED)
5096
5097 (defun js2-end-check (node)
5098 "Examine the body of a function, doing a basic reachability analysis.
5099 Returns a combination of flags END_* flags that indicate
5100 how the function execution can terminate. These constitute only the
5101 pessimistic set of termination conditions. It is possible that at
5102 runtime certain code paths will never be actually taken. Hence this
5103 analysis will flag errors in cases where there may not be errors.
5104 Returns logical OR of END_* flags"
5105 (let (kid)
5106 (cond
5107 ((js2-break-node-p node)
5108 (js2-end-check-break node))
5109 ((js2-expr-stmt-node-p node)
5110 (if (setq kid (js2-expr-stmt-node-expr node))
5111 (js2-end-check kid)
5112 js2-END_DROPS_OFF))
5113 ((or (js2-continue-node-p node)
5114 (js2-throw-node-p node))
5115 js2-END_UNREACHED)
5116 ((js2-return-node-p node)
5117 (if (setq kid (js2-return-node-retval node))
5118 js2-END_RETURNS_VALUE
5119 js2-END_RETURNS))
5120 ((js2-loop-node-p node)
5121 (js2-end-check-loop node))
5122 ((js2-switch-node-p node)
5123 (js2-end-check-switch node))
5124 ((js2-labeled-stmt-node-p node)
5125 (js2-end-check-label node))
5126 ((js2-if-node-p node)
5127 (js2-end-check-if node))
5128 ((js2-try-node-p node)
5129 (js2-end-check-try node))
5130 ((js2-block-node-p node)
5131 (if (null (js2-block-node-kids node))
5132 js2-END_DROPS_OFF
5133 (js2-end-check-block node)))
5134 ((js2-yield-node-p node)
5135 js2-END_YIELDS)
5136 (t
5137 js2-END_DROPS_OFF))))
5138
5139 (defun js2-always-defined-boolean-p (node)
5140 "Check if NODE always evaluates to true or false in boolean context.
5141 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5142 nor always false."
5143 (let ((tt (js2-node-type node))
5144 num)
5145 (cond
5146 ((or (= tt js2-FALSE) (= tt js2-NULL))
5147 'ALWAYS_FALSE)
5148 ((= tt js2-TRUE)
5149 'ALWAYS_TRUE)
5150 ((= tt js2-NUMBER)
5151 (setq num (js2-number-node-num-value node))
5152 (if (and (not (eq num 0.0e+NaN))
5153 (not (zerop num)))
5154 'ALWAYS_TRUE
5155 'ALWAYS_FALSE))
5156 (t
5157 nil))))
5158
5159 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5160 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5161
5162 (defvar js2-tokens nil
5163 "List of all defined token names.") ; initialized in `js2-token-names'
5164
5165 (defconst js2-token-names
5166 (let* ((names (make-vector js2-num-tokens -1))
5167 (case-fold-search nil) ; only match js2-UPPER_CASE
5168 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5169 (loop for sym in syms
5170 for i from 0
5171 do
5172 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5173 (not (boundp sym)))
5174 (aset names (symbol-value sym) ; code, e.g. 152
5175 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5176 (push sym js2-tokens)))
5177 names)
5178 "Vector mapping int values to token string names, sans `js2-' prefix.")
5179
5180 (defun js2-token-name (tok)
5181 "Return a string name for TOK, a token symbol or code.
5182 Signals an error if it's not a recognized token."
5183 (let ((code tok))
5184 (if (symbolp tok)
5185 (setq code (symbol-value tok)))
5186 (if (eq code -1)
5187 "ERROR"
5188 (if (and (numberp code)
5189 (not (minusp code))
5190 (< code js2-num-tokens))
5191 (aref js2-token-names code)
5192 (error "Invalid token: %s" code)))))
5193
5194 (defsubst js2-token-sym (tok)
5195 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5196 (intern (js2-token-name tok)))
5197
5198 (defconst js2-token-codes
5199 (let ((table (make-hash-table :test 'eq :size 256)))
5200 (loop for name across js2-token-names
5201 for sym = (intern (concat "js2-" name))
5202 do
5203 (puthash sym (symbol-value sym) table))
5204 ;; clean up a few that are "wrong" in Rhino's token codes
5205 (puthash 'js2-DELETE js2-DELPROP table)
5206 table)
5207 "Hashtable mapping token symbols to their bytecodes.")
5208
5209 (defsubst js2-token-code (sym)
5210 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5211 (or (gethash sym js2-token-codes)
5212 (error "Invalid token symbol: %s " sym))) ; signal code bug
5213
5214 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5215 (setq js2-token-end js2-ts-cursor)
5216 (js2-report-error msg nil
5217 (or beg js2-token-beg)
5218 (or len (- js2-token-end js2-token-beg)))
5219 (unless no-throw
5220 (throw 'return js2-ERROR)))
5221
5222 (defsubst js2-get-string-from-buffer ()
5223 "Reverse the char accumulator and return it as a string."
5224 (setq js2-token-end js2-ts-cursor)
5225 (if js2-ts-string-buffer
5226 (apply #'string (nreverse js2-ts-string-buffer))
5227 ""))
5228
5229 ;; TODO: could potentially avoid a lot of consing by allocating a
5230 ;; char buffer the way Rhino does.
5231 (defsubst js2-add-to-string (c)
5232 (push c js2-ts-string-buffer))
5233
5234 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5235 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5236 ;; any other character: when it's not part of the current token, we
5237 ;; unget it, allowing it to be read again by the following call.
5238 (defsubst js2-unget-char ()
5239 (decf js2-ts-cursor))
5240
5241 ;; Rhino distinguishes \r and \n line endings. We don't need to
5242 ;; because we only scan from Emacs buffers, which always use \n.
5243 (defsubst js2-get-char ()
5244 "Read and return the next character from the input buffer.
5245 Increments `js2-ts-lineno' if the return value is a newline char.
5246 Updates `js2-ts-cursor' to the point after the returned char.
5247 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5248 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5249 (let (c)
5250 ;; check for end of buffer
5251 (if (>= js2-ts-cursor (point-max))
5252 (setq js2-ts-hit-eof t
5253 js2-ts-cursor (1+ js2-ts-cursor)
5254 c js2-EOF_CHAR) ; return value
5255 ;; otherwise read next char
5256 (setq c (char-before (incf js2-ts-cursor)))
5257 ;; if we read a newline, update counters
5258 (if (= c ?\n)
5259 (setq js2-ts-line-start js2-ts-cursor
5260 js2-ts-lineno (1+ js2-ts-lineno)))
5261 ;; TODO: skip over format characters
5262 c)))
5263
5264 (defsubst js2-read-unicode-escape ()
5265 "Read a \\uNNNN sequence from the input.
5266 Assumes the ?\ and ?u have already been read.
5267 Returns the unicode character, or nil if it wasn't a valid character.
5268 Doesn't change the values of any scanner variables."
5269 ;; I really wish I knew a better way to do this, but I can't
5270 ;; find the Emacs function that takes a 16-bit int and converts
5271 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5272 ;; Have to first check that it's 4 hex characters or it may stop
5273 ;; the read early.
5274 (ignore-errors
5275 (let ((s (buffer-substring-no-properties js2-ts-cursor
5276 (+ 4 js2-ts-cursor))))
5277 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5278 (read (concat "?\\u" s))))))
5279
5280 (defsubst js2-match-char (test)
5281 "Consume and return next character if it matches TEST, a character.
5282 Returns nil and consumes nothing if TEST is not the next character."
5283 (let ((c (js2-get-char)))
5284 (if (eq c test)
5285 t
5286 (js2-unget-char)
5287 nil)))
5288
5289 (defsubst js2-peek-char ()
5290 (prog1
5291 (js2-get-char)
5292 (js2-unget-char)))
5293
5294 (defsubst js2-java-identifier-start-p (c)
5295 (or
5296 (memq c '(?$ ?_))
5297 (js2-char-uppercase-p c)
5298 (js2-char-lowercase-p c)))
5299
5300 (defsubst js2-java-identifier-part-p (c)
5301 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5302 ;; TODO: make me Unicode-friendly. See comments above.
5303 (or
5304 (memq c '(?$ ?_))
5305 (js2-char-uppercase-p c)
5306 (js2-char-lowercase-p c)
5307 (and (>= c ?0) (<= c ?9))))
5308
5309 (defsubst js2-alpha-p (c)
5310 (cond ((and (<= ?A c) (<= c ?Z)) t)
5311 ((and (<= ?a c) (<= c ?z)) t)
5312 (t nil)))
5313
5314 (defsubst js2-digit-p (c)
5315 (and (<= ?0 c) (<= c ?9)))
5316
5317 (defsubst js2-js-space-p (c)
5318 (if (<= c 127)
5319 (memq c '(#x20 #x9 #xB #xC #xD))
5320 (or
5321 (eq c #xA0)
5322 ;; TODO: change this nil to check for Unicode space character
5323 nil)))
5324
5325 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5326
5327 (defsubst js2-skip-line ()
5328 "Skip to end of line"
5329 (let (c)
5330 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5331 (js2-unget-char)
5332 (setq js2-token-end js2-ts-cursor)))
5333
5334 (defun js2-init-scanner (&optional buf line)
5335 "Create token stream for BUF starting on LINE.
5336 BUF defaults to current-buffer and line defaults to 1.
5337
5338 A buffer can only have one scanner active at a time, which yields
5339 dramatically simpler code than using a defstruct. If you need to
5340 have simultaneous scanners in a buffer, copy the regions to scan
5341 into temp buffers."
5342 (save-excursion
5343 (when buf
5344 (set-buffer buf))
5345 (setq js2-ts-dirty-line nil
5346 js2-ts-regexp-flags nil
5347 js2-ts-string ""
5348 js2-ts-number nil
5349 js2-ts-hit-eof nil
5350 js2-ts-line-start 0
5351 js2-ts-lineno (or line 1)
5352 js2-ts-line-end-char -1
5353 js2-ts-cursor (point-min)
5354 js2-ts-is-xml-attribute nil
5355 js2-ts-xml-is-tag-content nil
5356 js2-ts-xml-open-tags-count 0
5357 js2-ts-string-buffer nil)))
5358
5359 ;; This function uses the cached op, string and number fields in
5360 ;; TokenStream; if getToken has been called since the passed token
5361 ;; was scanned, the op or string printed may be incorrect.
5362 (defun js2-token-to-string (token)
5363 ;; Not sure where this function is used in Rhino. Not tested.
5364 (if (not js2-debug-print-trees)
5365 ""
5366 (let ((name (js2-token-name token)))
5367 (cond
5368 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5369 (concat name " `" js2-ts-string "'"))
5370 ((eq token js2-NUMBER)
5371 (format "NUMBER %g" js2-ts-number))
5372 (t
5373 name)))))
5374
5375 (defconst js2-keywords
5376 '(break
5377 case catch const continue
5378 debugger default delete do
5379 else enum
5380 false finally for function
5381 if in instanceof import
5382 let
5383 new null
5384 return
5385 switch
5386 this throw true try typeof
5387 var void
5388 while with
5389 yield))
5390
5391 ;; Token names aren't exactly the same as the keywords, unfortunately.
5392 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5393 (defconst js2-kwd-tokens
5394 (let ((table (make-vector js2-num-tokens nil))
5395 (tokens
5396 (list js2-BREAK
5397 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5398 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5399 js2-ELSE
5400 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5401 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5402 js2-LET
5403 js2-NEW js2-NULL
5404 js2-RETURN
5405 js2-SWITCH
5406 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5407 js2-VAR
5408 js2-WHILE js2-WITH
5409 js2-YIELD)))
5410 (dolist (i tokens)
5411 (aset table i 'font-lock-keyword-face))
5412 (aset table js2-STRING 'font-lock-string-face)
5413 (aset table js2-REGEXP 'font-lock-string-face)
5414 (aset table js2-COMMENT 'font-lock-comment-face)
5415 (aset table js2-THIS 'font-lock-builtin-face)
5416 (aset table js2-VOID 'font-lock-constant-face)
5417 (aset table js2-NULL 'font-lock-constant-face)
5418 (aset table js2-TRUE 'font-lock-constant-face)
5419 (aset table js2-FALSE 'font-lock-constant-face)
5420 table)
5421 "Vector whose values are non-nil for tokens that are keywords.
5422 The values are default faces to use for highlighting the keywords.")
5423
5424 (defconst js2-reserved-words
5425 '(abstract
5426 boolean byte
5427 char class
5428 double
5429 enum export extends
5430 final float
5431 goto
5432 implements import int interface
5433 long
5434 native
5435 package private protected public
5436 short static super synchronized
5437 throws transient
5438 volatile))
5439
5440 (defconst js2-keyword-names
5441 (let ((table (make-hash-table :test 'equal)))
5442 (loop for k in js2-keywords
5443 do (puthash
5444 (symbol-name k) ; instanceof
5445 (intern (concat "js2-"
5446 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5447 table))
5448 table)
5449 "JavaScript keywords by name, mapped to their symbols.")
5450
5451 (defconst js2-reserved-word-names
5452 (let ((table (make-hash-table :test 'equal)))
5453 (loop for k in js2-reserved-words
5454 do
5455 (puthash (symbol-name k) 'js2-RESERVED table))
5456 table)
5457 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5458
5459 (defsubst js2-collect-string (buf)
5460 "Convert BUF, a list of chars, to a string.
5461 Reverses BUF before converting."
5462 (cond
5463 ((stringp buf)
5464 buf)
5465 ((null buf) ; for emacs21 compat
5466 "")
5467 (t
5468 (if buf
5469 (apply #'string (nreverse buf))
5470 ""))))
5471
5472 (defun js2-string-to-keyword (s)
5473 "Return token for S, a string, if S is a keyword or reserved word.
5474 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5475 (or (gethash s js2-keyword-names)
5476 (gethash s js2-reserved-word-names)))
5477
5478 (defsubst js2-ts-set-char-token-bounds ()
5479 "Used when next token is one character."
5480 (setq js2-token-beg (1- js2-ts-cursor)
5481 js2-token-end js2-ts-cursor))
5482
5483 (defsubst js2-ts-return (token)
5484 "Return an N-character TOKEN from `js2-get-token'.
5485 Updates `js2-token-end' accordingly."
5486 (setq js2-token-end js2-ts-cursor)
5487 (throw 'return token))
5488
5489 (defsubst js2-x-digit-to-int (c accumulator)
5490 "Build up a hex number.
5491 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5492 corresponding number. Otherwise return -1."
5493 (catch 'return
5494 (catch 'check
5495 ;; Use 0..9 < A..Z < a..z
5496 (cond
5497 ((<= c ?9)
5498 (decf c ?0)
5499 (if (<= 0 c)
5500 (throw 'check nil)))
5501 ((<= c ?F)
5502 (when (<= ?A c)
5503 (decf c (- ?A 10))
5504 (throw 'check nil)))
5505 ((<= c ?f)
5506 (when (<= ?a c)
5507 (decf c (- ?a 10))
5508 (throw 'check nil))))
5509 (throw 'return -1))
5510 (logior c (lsh accumulator 4))))
5511
5512 (defun js2-get-token ()
5513 "Return next JavaScript token, an int such as js2-RETURN."
5514 (let (c
5515 c1
5516 identifier-start
5517 is-unicode-escape-start
5518 contains-escape
5519 escape-val
5520 escape-start
5521 str
5522 result
5523 base
5524 is-integer
5525 quote-char
5526 val
5527 look-for-slash
5528 continue)
5529 (catch 'return
5530 (while t
5531 ;; Eat whitespace, possibly sensitive to newlines.
5532 (setq continue t)
5533 (while continue
5534 (setq c (js2-get-char))
5535 (cond
5536 ((eq c js2-EOF_CHAR)
5537 (js2-ts-set-char-token-bounds)
5538 (throw 'return js2-EOF))
5539 ((eq c ?\n)
5540 (js2-ts-set-char-token-bounds)
5541 (setq js2-ts-dirty-line nil)
5542 (throw 'return js2-EOL))
5543 ((not (js2-js-space-p c))
5544 (if (/= c ?-) ; in case end of HTML comment
5545 (setq js2-ts-dirty-line t))
5546 (setq continue nil))))
5547 ;; Assume the token will be 1 char - fixed up below.
5548 (js2-ts-set-char-token-bounds)
5549 (when (eq c ?@)
5550 (throw 'return js2-XMLATTR))
5551 ;; identifier/keyword/instanceof?
5552 ;; watch out for starting with a <backslash>
5553 (cond
5554 ((eq c ?\\)
5555 (setq c (js2-get-char))
5556 (if (eq c ?u)
5557 (setq identifier-start t
5558 is-unicode-escape-start t
5559 js2-ts-string-buffer nil)
5560 (setq identifier-start nil)
5561 (js2-unget-char)
5562 (setq c ?\\)))
5563 (t
5564 (when (setq identifier-start (js2-java-identifier-start-p c))
5565 (setq js2-ts-string-buffer nil)
5566 (js2-add-to-string c))))
5567 (when identifier-start
5568 (setq contains-escape is-unicode-escape-start)
5569 (catch 'break
5570 (while t
5571 (if is-unicode-escape-start
5572 ;; strictly speaking we should probably push-back
5573 ;; all the bad characters if the <backslash>uXXXX
5574 ;; sequence is malformed. But since there isn't a
5575 ;; correct context(is there?) for a bad Unicode
5576 ;; escape sequence in an identifier, we can report
5577 ;; an error here.
5578 (progn
5579 (setq escape-val 0)
5580 (dotimes (i 4)
5581 (setq c (js2-get-char)
5582 escape-val (js2-x-digit-to-int c escape-val))
5583 ;; Next check takes care of c < 0 and bad escape
5584 (if (minusp escape-val)
5585 (throw 'break nil)))
5586 (if (minusp escape-val)
5587 (js2-report-scan-error "msg.invalid.escape" t))
5588 (js2-add-to-string escape-val)
5589 (setq is-unicode-escape-start nil))
5590 (setq c (js2-get-char))
5591 (cond
5592 ((eq c ?\\)
5593 (setq c (js2-get-char))
5594 (if (eq c ?u)
5595 (setq is-unicode-escape-start t
5596 contains-escape t)
5597 (js2-report-scan-error "msg.illegal.character" t)))
5598 (t
5599 (if (or (eq c js2-EOF_CHAR)
5600 (not (js2-java-identifier-part-p c)))
5601 (throw 'break nil))
5602 (js2-add-to-string c))))))
5603 (js2-unget-char)
5604 (setq str (js2-get-string-from-buffer))
5605 (unless contains-escape
5606 ;; OPT we shouldn't have to make a string (object!) to
5607 ;; check if it's a keyword.
5608 ;; Return the corresponding token if it's a keyword
5609 (when (setq result (js2-string-to-keyword str))
5610 (if (and (< js2-language-version 170)
5611 (memq result '(js2-LET js2-YIELD)))
5612 ;; LET and YIELD are tokens only in 1.7 and later
5613 (setq result 'js2-NAME))
5614 (if (not (eq result 'js2-RESERVED))
5615 (throw 'return (js2-token-code result)))
5616 (js2-report-warning "msg.reserved.keyword" str)))
5617 ;; If we want to intern these as Rhino does, just use (intern str)
5618 (setq js2-ts-string str)
5619 (throw 'return js2-NAME)) ; end identifier/kwd check
5620 ;; is it a number?
5621 (when (or (js2-digit-p c)
5622 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5623 (setq js2-ts-string-buffer nil
5624 base 10)
5625 (when (eq c ?0)
5626 (setq c (js2-get-char))
5627 (cond
5628 ((or (eq c ?x) (eq c ?X))
5629 (setq base 16)
5630 (setq c (js2-get-char)))
5631 ((js2-digit-p c)
5632 (setq base 8))
5633 (t
5634 (js2-add-to-string ?0))))
5635 (if (eq base 16)
5636 (while (<= 0 (js2-x-digit-to-int c 0))
5637 (js2-add-to-string c)
5638 (setq c (js2-get-char)))
5639 (while (and (<= ?0 c) (<= c ?9))
5640 ;; We permit 08 and 09 as decimal numbers, which
5641 ;; makes our behavior a superset of the ECMA
5642 ;; numeric grammar. We might not always be so
5643 ;; permissive, so we warn about it.
5644 (when (and (eq base 8) (>= c ?8))
5645 (js2-report-warning "msg.bad.octal.literal"
5646 (if (eq c ?8) "8" "9"))
5647 (setq base 10))
5648 (js2-add-to-string c)
5649 (setq c (js2-get-char))))
5650 (setq is-integer t)
5651 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5652 (setq is-integer nil)
5653 (when (eq c ?.)
5654 (loop do
5655 (js2-add-to-string c)
5656 (setq c (js2-get-char))
5657 while (js2-digit-p c)))
5658 (when (memq c '(?e ?E))
5659 (js2-add-to-string c)
5660 (setq c (js2-get-char))
5661 (when (memq c '(?+ ?-))
5662 (js2-add-to-string c)
5663 (setq c (js2-get-char)))
5664 (unless (js2-digit-p c)
5665 (js2-report-scan-error "msg.missing.exponent" t))
5666 (loop do
5667 (js2-add-to-string c)
5668 (setq c (js2-get-char))
5669 while (js2-digit-p c))))
5670 (js2-unget-char)
5671 (setq js2-ts-string (js2-get-string-from-buffer)
5672 js2-ts-number
5673 (if (and (eq base 10) (not is-integer))
5674 (string-to-number js2-ts-string)
5675 ;; TODO: call runtime number-parser. Some of it is in
5676 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5677 (string-to-number js2-ts-string)))
5678 (throw 'return js2-NUMBER))
5679 ;; is it a string?
5680 (when (memq c '(?\" ?\'))
5681 ;; We attempt to accumulate a string the fast way, by
5682 ;; building it directly out of the reader. But if there
5683 ;; are any escaped characters in the string, we revert to
5684 ;; building it out of a string buffer.
5685 (setq quote-char c
5686 js2-ts-string-buffer nil
5687 c (js2-get-char))
5688 (catch 'break
5689 (while (/= c quote-char)
5690 (catch 'continue
5691 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5692 (js2-unget-char)
5693 (setq js2-token-end js2-ts-cursor)
5694 (js2-report-error "msg.unterminated.string.lit")
5695 (throw 'return js2-STRING))
5696 (when (eq c ?\\)
5697 ;; We've hit an escaped character
5698 (setq c (js2-get-char))
5699 (case c
5700 (?b (setq c ?\b))
5701 (?f (setq c ?\f))
5702 (?n (setq c ?\n))
5703 (?r (setq c ?\r))
5704 (?t (setq c ?\t))
5705 (?v (setq c ?\v))
5706 (?u
5707 (setq c1 (js2-read-unicode-escape))
5708 (if js2-parse-ide-mode
5709 (if c1
5710 (progn
5711 ;; just copy the string in IDE-mode
5712 (js2-add-to-string ?\\)
5713 (js2-add-to-string ?u)
5714 (dotimes (i 3)
5715 (js2-add-to-string (js2-get-char)))
5716 (setq c (js2-get-char))) ; added at end of loop
5717 ;; flag it as an invalid escape
5718 (js2-report-warning "msg.invalid.escape"
5719 nil (- js2-ts-cursor 2) 6))
5720 ;; Get 4 hex digits; if the u escape is not
5721 ;; followed by 4 hex digits, use 'u' + the
5722 ;; literal character sequence that follows.
5723 (js2-add-to-string ?u)
5724 (setq escape-val 0)
5725 (dotimes (i 4)
5726 (setq c (js2-get-char)
5727 escape-val (js2-x-digit-to-int c escape-val))
5728 (if (minusp escape-val)
5729 (throw 'continue nil))
5730 (js2-add-to-string c))
5731 ;; prepare for replace of stored 'u' sequence by escape value
5732 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5733 c escape-val)))
5734 (?x
5735 ;; Get 2 hex digits, defaulting to 'x'+literal
5736 ;; sequence, as above.
5737 (setq c (js2-get-char)
5738 escape-val (js2-x-digit-to-int c 0))
5739 (if (minusp escape-val)
5740 (progn
5741 (js2-add-to-string ?x)
5742 (throw 'continue nil))
5743 (setq c1 c
5744 c (js2-get-char)
5745 escape-val (js2-x-digit-to-int c escape-val))
5746 (if (minusp escape-val)
5747 (progn
5748 (js2-add-to-string ?x)
5749 (js2-add-to-string c1)
5750 (throw 'continue nil))
5751 ;; got 2 hex digits
5752 (setq c escape-val))))
5753 (?\n
5754 ;; Remove line terminator after escape to follow
5755 ;; SpiderMonkey and C/C++
5756 (setq c (js2-get-char))
5757 (throw 'continue nil))
5758 (t
5759 (when (and (<= ?0 c) (< c ?8))
5760 (setq val (- c ?0)
5761 c (js2-get-char))
5762 (when (and (<= ?0 c) (< c ?8))
5763 (setq val (- (+ (* 8 val) c) ?0)
5764 c (js2-get-char))
5765 (when (and (<= ?0 c)
5766 (< c ?8)
5767 (< val #o37))
5768 ;; c is 3rd char of octal sequence only
5769 ;; if the resulting val <= 0377
5770 (setq val (- (+ (* 8 val) c) ?0)
5771 c (js2-get-char))))
5772 (js2-unget-char)
5773 (setq c val)))))
5774 (js2-add-to-string c)
5775 (setq c (js2-get-char)))))
5776 (setq js2-ts-string (js2-get-string-from-buffer))
5777 (throw 'return js2-STRING))
5778 (case c
5779 (?\;
5780 (throw 'return js2-SEMI))
5781 (?\[
5782 (throw 'return js2-LB))
5783 (?\]
5784 (throw 'return js2-RB))
5785 (?{
5786 (throw 'return js2-LC))
5787 (?}
5788 (throw 'return js2-RC))
5789 (?\(
5790 (throw 'return js2-LP))
5791 (?\)
5792 (throw 'return js2-RP))
5793 (?,
5794 (throw 'return js2-COMMA))
5795 (??
5796 (throw 'return js2-HOOK))
5797 (?:
5798 (if (js2-match-char ?:)
5799 (js2-ts-return js2-COLONCOLON)
5800 (throw 'return js2-COLON)))
5801 (?.
5802 (if (js2-match-char ?.)
5803 (js2-ts-return js2-DOTDOT)
5804 (if (js2-match-char ?\()
5805 (js2-ts-return js2-DOTQUERY)
5806 (throw 'return js2-DOT))))
5807 (?|
5808 (if (js2-match-char ?|)
5809 (throw 'return js2-OR)
5810 (if (js2-match-char ?=)
5811 (js2-ts-return js2-ASSIGN_BITOR)
5812 (throw 'return js2-BITOR))))
5813 (?^
5814 (if (js2-match-char ?=)
5815 (js2-ts-return js2-ASSIGN_BITOR)
5816 (throw 'return js2-BITXOR)))
5817 (?&
5818 (if (js2-match-char ?&)
5819 (throw 'return js2-AND)
5820 (if (js2-match-char ?=)
5821 (js2-ts-return js2-ASSIGN_BITAND)
5822 (throw 'return js2-BITAND))))
5823 (?=
5824 (if (js2-match-char ?=)
5825 (if (js2-match-char ?=)
5826 (js2-ts-return js2-SHEQ)
5827 (throw 'return js2-EQ))
5828 (throw 'return js2-ASSIGN)))
5829 (?!
5830 (if (js2-match-char ?=)
5831 (if (js2-match-char ?=)
5832 (js2-ts-return js2-SHNE)
5833 (js2-ts-return js2-NE))
5834 (throw 'return js2-NOT)))
5835 (?<
5836 ;; NB:treat HTML begin-comment as comment-till-eol
5837 (when (js2-match-char ?!)
5838 (when (js2-match-char ?-)
5839 (when (js2-match-char ?-)
5840 (js2-skip-line)
5841 (setq js2-ts-comment-type 'html)
5842 (throw 'return js2-COMMENT)))
5843 (js2-unget-char))
5844 (if (js2-match-char ?<)
5845 (if (js2-match-char ?=)
5846 (js2-ts-return js2-ASSIGN_LSH)
5847 (js2-ts-return js2-LSH))
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-LE)
5850 (throw 'return js2-LT))))
5851 (?>
5852 (if (js2-match-char ?>)
5853 (if (js2-match-char ?>)
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-ASSIGN_URSH)
5856 (js2-ts-return js2-URSH))
5857 (if (js2-match-char ?=)
5858 (js2-ts-return js2-ASSIGN_RSH)
5859 (js2-ts-return js2-RSH)))
5860 (if (js2-match-char ?=)
5861 (js2-ts-return js2-GE)
5862 (throw 'return js2-GT))))
5863 (?*
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-ASSIGN_MUL)
5866 (throw 'return js2-MUL)))
5867 (?/
5868 ;; is it a // comment?
5869 (when (js2-match-char ?/)
5870 (setq js2-token-beg (- js2-ts-cursor 2))
5871 (js2-skip-line)
5872 (setq js2-ts-comment-type 'line)
5873 ;; include newline so highlighting goes to end of window
5874 (incf js2-token-end)
5875 (throw 'return js2-COMMENT))
5876 ;; is it a /* comment?
5877 (when (js2-match-char ?*)
5878 (setq look-for-slash nil
5879 js2-token-beg (- js2-ts-cursor 2)
5880 js2-ts-comment-type
5881 (if (js2-match-char ?*)
5882 (progn
5883 (setq look-for-slash t)
5884 'jsdoc)
5885 'block))
5886 (while t
5887 (setq c (js2-get-char))
5888 (cond
5889 ((eq c js2-EOF_CHAR)
5890 (setq js2-token-end (1- js2-ts-cursor))
5891 (js2-report-error "msg.unterminated.comment")
5892 (throw 'return js2-COMMENT))
5893 ((eq c ?*)
5894 (setq look-for-slash t))
5895 ((eq c ?/)
5896 (if look-for-slash
5897 (js2-ts-return js2-COMMENT)))
5898 (t
5899 (setq look-for-slash nil
5900 js2-token-end js2-ts-cursor)))))
5901 (if (js2-match-char ?=)
5902 (js2-ts-return js2-ASSIGN_DIV)
5903 (throw 'return js2-DIV)))
5904 (?#
5905 (when js2-skip-preprocessor-directives
5906 (js2-skip-line)
5907 (setq js2-ts-comment-type 'preprocessor
5908 js2-token-end js2-ts-cursor)
5909 (throw 'return js2-COMMENT))
5910 (throw 'return js2-ERROR))
5911 (?%
5912 (if (js2-match-char ?=)
5913 (js2-ts-return js2-ASSIGN_MOD)
5914 (throw 'return js2-MOD)))
5915 (?~
5916 (throw 'return js2-BITNOT))
5917 (?+
5918 (if (js2-match-char ?=)
5919 (js2-ts-return js2-ASSIGN_ADD)
5920 (if (js2-match-char ?+)
5921 (js2-ts-return js2-INC)
5922 (throw 'return js2-ADD))))
5923 (?-
5924 (cond
5925 ((js2-match-char ?=)
5926 (setq c js2-ASSIGN_SUB))
5927 ((js2-match-char ?-)
5928 (unless js2-ts-dirty-line
5929 ;; treat HTML end-comment after possible whitespace
5930 ;; after line start as comment-until-eol
5931 (when (js2-match-char ?>)
5932 (js2-skip-line)
5933 (setq js2-ts-comment-type 'html)
5934 (throw 'return js2-COMMENT)))
5935 (setq c js2-DEC))
5936 (t
5937 (setq c js2-SUB)))
5938 (setq js2-ts-dirty-line t)
5939 (js2-ts-return c))
5940 (otherwise
5941 (js2-report-scan-error "msg.illegal.character")))))))
5942
5943 (defun js2-read-regexp (start-token)
5944 "Called by parser when it gets / or /= in literal context."
5945 (let (c
5946 err
5947 in-class ; inside a '[' .. ']' character-class
5948 flags
5949 (continue t))
5950 (setq js2-token-beg js2-ts-cursor
5951 js2-ts-string-buffer nil
5952 js2-ts-regexp-flags nil)
5953 (if (eq start-token js2-ASSIGN_DIV)
5954 ;; mis-scanned /=
5955 (js2-add-to-string ?=)
5956 (if (not (eq start-token js2-DIV))
5957 (error "failed assertion")))
5958 (while (and (not err)
5959 (or (/= (setq c (js2-get-char)) ?/)
5960 in-class))
5961 (cond
5962 ((or (= c ?\n)
5963 (= c js2-EOF_CHAR))
5964 (setq js2-token-end (1- js2-ts-cursor)
5965 err t
5966 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5967 (js2-report-error "msg.unterminated.re.lit"))
5968 (t (cond
5969 ((= c ?\\)
5970 (js2-add-to-string c)
5971 (setq c (js2-get-char)))
5972 ((= c ?\[)
5973 (setq in-class t))
5974 ((= c ?\])
5975 (setq in-class nil)))
5976 (js2-add-to-string c))))
5977 (unless err
5978 (while continue
5979 (cond
5980 ((js2-match-char ?g)
5981 (push ?g flags))
5982 ((js2-match-char ?i)
5983 (push ?i flags))
5984 ((js2-match-char ?m)
5985 (push ?m flags))
5986 (t
5987 (setq continue nil))))
5988 (if (js2-alpha-p (js2-peek-char))
5989 (js2-report-scan-error "msg.invalid.re.flag" t
5990 js2-ts-cursor 1))
5991 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5992 js2-ts-regexp-flags (js2-collect-string flags)
5993 js2-token-end js2-ts-cursor)
5994 ;; tell `parse-partial-sexp' to ignore this range of chars
5995 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5996
5997 (defun js2-get-first-xml-token ()
5998 (setq js2-ts-xml-open-tags-count 0
5999 js2-ts-is-xml-attribute nil
6000 js2-ts-xml-is-tag-content nil)
6001 (js2-unget-char)
6002 (js2-get-next-xml-token))
6003
6004 (defsubst js2-xml-discard-string ()
6005 "Throw away the string in progress and flag an XML parse error."
6006 (setq js2-ts-string-buffer nil
6007 js2-ts-string nil)
6008 (js2-report-scan-error "msg.XML.bad.form" t))
6009
6010 (defun js2-get-next-xml-token ()
6011 (setq js2-ts-string-buffer nil ; for recording the XML
6012 js2-token-beg js2-ts-cursor)
6013 (let (c result)
6014 (setq result
6015 (catch 'return
6016 (while t
6017 (setq c (js2-get-char))
6018 (cond
6019 ((= c js2-EOF_CHAR)
6020 (throw 'return js2-ERROR))
6021 (js2-ts-xml-is-tag-content
6022 (case c
6023 (?>
6024 (js2-add-to-string c)
6025 (setq js2-ts-xml-is-tag-content nil
6026 js2-ts-is-xml-attribute nil))
6027 (?/
6028 (js2-add-to-string c)
6029 (when (eq ?> (js2-peek-char))
6030 (setq c (js2-get-char))
6031 (js2-add-to-string c)
6032 (setq js2-ts-xml-is-tag-content nil)
6033 (decf js2-ts-xml-open-tags-count)))
6034 (?{
6035 (js2-unget-char)
6036 (setq js2-ts-string (js2-get-string-from-buffer))
6037 (throw 'return js2-XML))
6038 ((?\' ?\")
6039 (js2-add-to-string c)
6040 (unless (js2-read-quoted-string c)
6041 (throw 'return js2-ERROR)))
6042 (?=
6043 (js2-add-to-string c)
6044 (setq js2-ts-is-xml-attribute t))
6045 ((? ?\t ?\r ?\n)
6046 (js2-add-to-string c))
6047 (t
6048 (js2-add-to-string c)
6049 (setq js2-ts-is-xml-attribute nil)))
6050 (when (and (not js2-ts-xml-is-tag-content)
6051 (zerop js2-ts-xml-open-tags-count))
6052 (setq js2-ts-string (js2-get-string-from-buffer))
6053 (throw 'return js2-XMLEND)))
6054 (t
6055 ;; else not tag content
6056 (case c
6057 (?<
6058 (js2-add-to-string c)
6059 (setq c (js2-peek-char))
6060 (case c
6061 (?!
6062 (setq c (js2-get-char)) ;; skip !
6063 (js2-add-to-string c)
6064 (setq c (js2-peek-char))
6065 (case c
6066 (?-
6067 (setq c (js2-get-char)) ;; skip -
6068 (js2-add-to-string c)
6069 (if (eq c ?-)
6070 (progn
6071 (js2-add-to-string c)
6072 (unless (js2-read-xml-comment)
6073 (throw 'return js2-ERROR)))
6074 (js2-xml-discard-string)
6075 (throw 'return js2-ERROR)))
6076 (?\[
6077 (setq c (js2-get-char)) ;; skip [
6078 (js2-add-to-string c)
6079 (if (and (= (js2-get-char) ?C)
6080 (= (js2-get-char) ?D)
6081 (= (js2-get-char) ?A)
6082 (= (js2-get-char) ?T)
6083 (= (js2-get-char) ?A)
6084 (= (js2-get-char) ?\[))
6085 (progn
6086 (js2-add-to-string ?C)
6087 (js2-add-to-string ?D)
6088 (js2-add-to-string ?A)
6089 (js2-add-to-string ?T)
6090 (js2-add-to-string ?A)
6091 (js2-add-to-string ?\[)
6092 (unless (js2-read-cdata)
6093 (throw 'return js2-ERROR)))
6094 (js2-xml-discard-string)
6095 (throw 'return js2-ERROR)))
6096 (t
6097 (unless (js2-read-entity)
6098 (throw 'return js2-ERROR)))))
6099 (??
6100 (setq c (js2-get-char)) ;; skip ?
6101 (js2-add-to-string c)
6102 (unless (js2-read-PI)
6103 (throw 'return js2-ERROR)))
6104 (?/
6105 ;; end tag
6106 (setq c (js2-get-char)) ;; skip /
6107 (js2-add-to-string c)
6108 (when (zerop js2-ts-xml-open-tags-count)
6109 (js2-xml-discard-string)
6110 (throw 'return js2-ERROR))
6111 (setq js2-ts-xml-is-tag-content t)
6112 (decf js2-ts-xml-open-tags-count))
6113 (t
6114 ;; start tag
6115 (setq js2-ts-xml-is-tag-content t)
6116 (incf js2-ts-xml-open-tags-count))))
6117 (?{
6118 (js2-unget-char)
6119 (setq js2-ts-string (js2-get-string-from-buffer))
6120 (throw 'return js2-XML))
6121 (t
6122 (js2-add-to-string c))))))))
6123 (setq js2-token-end js2-ts-cursor)
6124 result))
6125
6126 (defun js2-read-quoted-string (quote)
6127 (let (c)
6128 (catch 'return
6129 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6130 (js2-add-to-string c)
6131 (if (eq c quote)
6132 (throw 'return t)))
6133 (js2-xml-discard-string) ;; throw away string in progress
6134 nil)))
6135
6136 (defun js2-read-xml-comment ()
6137 (let ((c (js2-get-char)))
6138 (catch 'return
6139 (while (/= c js2-EOF_CHAR)
6140 (catch 'continue
6141 (js2-add-to-string c)
6142 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6143 (setq c (js2-get-char))
6144 (js2-add-to-string c)
6145 (if (eq (js2-peek-char) ?>)
6146 (progn
6147 (setq c (js2-get-char)) ;; skip >
6148 (js2-add-to-string c)
6149 (throw 'return t))
6150 (throw 'continue nil)))
6151 (setq c (js2-get-char))))
6152 (js2-xml-discard-string)
6153 nil)))
6154
6155 (defun js2-read-cdata ()
6156 (let ((c (js2-get-char)))
6157 (catch 'return
6158 (while (/= c js2-EOF_CHAR)
6159 (catch 'continue
6160 (js2-add-to-string c)
6161 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6162 (setq c (js2-get-char))
6163 (js2-add-to-string c)
6164 (if (eq (js2-peek-char) ?>)
6165 (progn
6166 (setq c (js2-get-char)) ;; Skip >
6167 (js2-add-to-string c)
6168 (throw 'return t))
6169 (throw 'continue nil)))
6170 (setq c (js2-get-char))))
6171 (js2-xml-discard-string)
6172 nil)))
6173
6174 (defun js2-read-entity ()
6175 (let ((decl-tags 1)
6176 c)
6177 (catch 'return
6178 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6179 (js2-add-to-string c)
6180 (case c
6181 (?<
6182 (incf decl-tags))
6183 (?>
6184 (decf decl-tags)
6185 (if (zerop decl-tags)
6186 (throw 'return t)))))
6187 (js2-xml-discard-string)
6188 nil)))
6189
6190 (defun js2-read-PI ()
6191 "Scan an XML processing instruction."
6192 (let (c)
6193 (catch 'return
6194 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6195 (js2-add-to-string c)
6196 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6197 (setq c (js2-get-char)) ;; Skip >
6198 (js2-add-to-string c)
6199 (throw 'return t)))
6200 (js2-xml-discard-string)
6201 nil)))
6202
6203 (defun js2-scanner-get-line ()
6204 "Return the text of the current scan line."
6205 (buffer-substring (point-at-bol) (point-at-eol)))
6206
6207 ;;; Highlighting
6208
6209 (defsubst js2-set-face (beg end face &optional record)
6210 "Fontify a region. If RECORD is non-nil, record for later."
6211 (when (plusp js2-highlight-level)
6212 (setq beg (min (point-max) beg)
6213 beg (max (point-min) beg)
6214 end (min (point-max) end)
6215 end (max (point-min) end))
6216 (if record
6217 (push (list beg end face) js2-mode-fontifications)
6218 (put-text-property beg end 'face face))))
6219
6220 (defsubst js2-set-kid-face (pos kid len face)
6221 "Set-face on a child node.
6222 POS is absolute buffer position of parent.
6223 KID is the child node.
6224 LEN is the length to fontify.
6225 FACE is the face to fontify with."
6226 (js2-set-face (+ pos (js2-node-pos kid))
6227 (+ pos (js2-node-pos kid) (js2-node-len kid))
6228 face))
6229
6230 (defsubst js2-fontify-kwd (start length)
6231 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6232
6233 (defsubst js2-clear-face (beg end)
6234 (remove-text-properties beg end '(face nil
6235 help-echo nil
6236 point-entered nil
6237 c-in-sws nil)))
6238
6239 (defsubst js2-record-text-property (beg end prop value)
6240 "Record a text property to set when parsing finishes."
6241 (push (list beg end prop value) js2-mode-deferred-properties))
6242
6243 (defconst js2-ecma-global-props
6244 (concat "^"
6245 (regexp-opt
6246 '("Infinity" "NaN" "undefined" "arguments") t)
6247 "$")
6248 "Value properties of the Ecma-262 Global Object.
6249 Shown at or above `js2-highlight-level' 2.")
6250
6251 ;; might want to add the name "arguments" to this list?
6252 (defconst js2-ecma-object-props
6253 (concat "^"
6254 (regexp-opt
6255 '("prototype" "__proto__" "__parent__") t)
6256 "$")
6257 "Value properties of the Ecma-262 Object constructor.
6258 Shown at or above `js2-highlight-level' 2.")
6259
6260 (defconst js2-ecma-global-funcs
6261 (concat
6262 "^"
6263 (regexp-opt
6264 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6265 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6266 "$")
6267 "Function properties of the Ecma-262 Global object.
6268 Shown at or above `js2-highlight-level' 2.")
6269
6270 (defconst js2-ecma-number-props
6271 (concat "^"
6272 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6273 "NEGATIVE_INFINITY"
6274 "POSITIVE_INFINITY") t)
6275 "$")
6276 "Properties of the Ecma-262 Number constructor.
6277 Shown at or above `js2-highlight-level' 2.")
6278
6279 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6280 "Properties of the Ecma-262 Date constructor.
6281 Shown at or above `js2-highlight-level' 2.")
6282
6283 (defconst js2-ecma-math-props
6284 (concat "^"
6285 (regexp-opt
6286 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6287 t)
6288 "$")
6289 "Properties of the Ecma-262 Math object.
6290 Shown at or above `js2-highlight-level' 2.")
6291
6292 (defconst js2-ecma-math-funcs
6293 (concat "^"
6294 (regexp-opt
6295 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6296 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6297 "$")
6298 "Function properties of the Ecma-262 Math object.
6299 Shown at or above `js2-highlight-level' 2.")
6300
6301 (defconst js2-ecma-function-props
6302 (concat
6303 "^"
6304 (regexp-opt
6305 '(;; properties of the Object prototype object
6306 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6307 "toLocaleString" "toString" "valueOf"
6308 ;; properties of the Function prototype object
6309 "apply" "call"
6310 ;; properties of the Array prototype object
6311 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6312 "splice" "unshift"
6313 ;; properties of the String prototype object
6314 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6315 "localeCompare" "match" "replace" "search" "split" "substring"
6316 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6317 "toUpperCase"
6318 ;; properties of the Number prototype object
6319 "toExponential" "toFixed" "toPrecision"
6320 ;; properties of the Date prototype object
6321 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6322 "getMinutes" "getMonth" "getSeconds" "getTime"
6323 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6324 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6325 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6326 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6327 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6328 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6329 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6330 "toTimeString" "toUTCString"
6331 ;; properties of the RegExp prototype object
6332 "exec" "test"
6333 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6334 "toSource" "__defineGetter__" "__defineSetter__"
6335 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6336 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6337 t)
6338 "$")
6339 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6340 Shown at or above `js2-highlight-level' 3.")
6341
6342 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6343 (let ((target-name (and target
6344 (js2-name-node-p target)
6345 (js2-name-node-name target)))
6346 (prop-name (if prop (js2-name-node-name prop)))
6347 (level1 (>= js2-highlight-level 1))
6348 (level2 (>= js2-highlight-level 2))
6349 (level3 (>= js2-highlight-level 3))
6350 pos
6351 face)
6352 (when level2
6353 (if call-p
6354 (cond
6355 ((and target prop)
6356 (cond
6357 ((and level3 (string-match js2-ecma-function-props prop-name))
6358 (setq face 'font-lock-builtin-face))
6359 ((and target-name prop)
6360 (cond
6361 ((string= target-name "Date")
6362 (if (string-match js2-ecma-date-props prop-name)
6363 (setq face 'font-lock-builtin-face)))
6364 ((string= target-name "Math")
6365 (if (string-match js2-ecma-math-funcs prop-name)
6366 (setq face 'font-lock-builtin-face)))))))
6367 (prop
6368 (if (string-match js2-ecma-global-funcs prop-name)
6369 (setq face 'font-lock-builtin-face))))
6370 (cond
6371 ((and target prop)
6372 (cond
6373 ((string= target-name "Number")
6374 (if (string-match js2-ecma-number-props prop-name)
6375 (setq face 'font-lock-constant-face)))
6376 ((string= target-name "Math")
6377 (if (string-match js2-ecma-math-props prop-name)
6378 (setq face 'font-lock-constant-face)))))
6379 (prop
6380 (if (string-match js2-ecma-object-props prop-name)
6381 (setq face 'font-lock-constant-face)))))
6382 (when face
6383 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6384 (js2-node-pos prop))) ; relative
6385 (+ pos (js2-node-len prop))
6386 face)))))
6387
6388 (defun js2-parse-highlight-member-expr-node (node)
6389 "Perform syntax highlighting of EcmaScript built-in properties.
6390 The variable `js2-highlight-level' governs this highighting."
6391 (let (face target prop name pos end parent call-p callee)
6392 (cond
6393 ;; case 1: simple name, e.g. foo
6394 ((js2-name-node-p node)
6395 (setq name (js2-name-node-name node))
6396 ;; possible for name to be nil in rare cases - saw it when
6397 ;; running js2-mode on an elisp buffer. Might as well try to
6398 ;; make it so js2-mode never barfs.
6399 (when name
6400 (setq face (if (string-match js2-ecma-global-props name)
6401 'font-lock-constant-face))
6402 (when face
6403 (setq pos (js2-node-pos node)
6404 end (+ pos (js2-node-len node)))
6405 (js2-set-face pos end face))))
6406 ;; case 2: property access or function call
6407 ((or (js2-prop-get-node-p node)
6408 ;; highlight function call if expr is a prop-get node
6409 ;; or a plain name (i.e. unqualified function call)
6410 (and (setq call-p (js2-call-node-p node))
6411 (setq callee (js2-call-node-target node)) ; separate setq!
6412 (or (js2-prop-get-node-p callee)
6413 (js2-name-node-p callee))))
6414 (setq parent node
6415 node (if call-p callee node))
6416 (if (and call-p (js2-name-node-p callee))
6417 (setq prop callee)
6418 (setq target (js2-prop-get-node-left node)
6419 prop (js2-prop-get-node-right node)))
6420 (cond
6421 ((js2-name-node-p target)
6422 (if (js2-name-node-p prop)
6423 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6424 (js2-parse-highlight-prop-get parent target prop call-p)
6425 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6426 (js2-parse-highlight-prop-get parent target nil call-p)))
6427 ((js2-name-node-p prop)
6428 ;; case 2c: complex target, simple name, e.g. x[y].bar
6429 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6430
6431 (defun js2-parse-highlight-member-expr-fn-name (expr)
6432 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6433 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6434 We currently only handle the case where the last component is a prop-get
6435 of a simple name. Called before EXPR has a parent node."
6436 (let (pos
6437 (name (and (js2-prop-get-node-p expr)
6438 (js2-prop-get-node-right expr))))
6439 (when (js2-name-node-p name)
6440 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6441 (js2-node-pos name)))
6442 (+ pos (js2-node-len name))
6443 'font-lock-function-name-face
6444 'record))))
6445
6446 ;; source: http://jsdoc.sourceforge.net/
6447 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6448 ;; allows type specifications, and needs work before entering the wild.
6449
6450 (defconst js2-jsdoc-param-tag-regexp
6451 (concat "^\\s-*\\*+\\s-*\\(@"
6452 "\\(?:param\\|argument\\)"
6453 "\\)"
6454 "\\s-*\\({[^}]+}\\)?" ; optional type
6455 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6456 "\\>")
6457 "Matches jsdoc tags with optional type and optional param name.")
6458
6459 (defconst js2-jsdoc-typed-tag-regexp
6460 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6461 (regexp-opt
6462 '("enum"
6463 "extends"
6464 "field"
6465 "id"
6466 "implements"
6467 "lends"
6468 "mods"
6469 "requires"
6470 "return"
6471 "returns"
6472 "throw"
6473 "throws"))
6474 "\\)\\)\\s-*\\({[^}]+}\\)?")
6475 "Matches jsdoc tags with optional type.")
6476
6477 (defconst js2-jsdoc-arg-tag-regexp
6478 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6479 (regexp-opt
6480 '("alias"
6481 "augments"
6482 "borrows"
6483 "bug"
6484 "base"
6485 "config"
6486 "default"
6487 "define"
6488 "exception"
6489 "function"
6490 "member"
6491 "memberOf"
6492 "name"
6493 "namespace"
6494 "property"
6495 "since"
6496 "suppress"
6497 "this"
6498 "throws"
6499 "type"
6500 "version"))
6501 "\\)\\)\\s-+\\([^ \t]+\\)")
6502 "Matches jsdoc tags with a single argument.")
6503
6504 (defconst js2-jsdoc-empty-tag-regexp
6505 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6506 (regexp-opt
6507 '("addon"
6508 "author"
6509 "class"
6510 "const"
6511 "constant"
6512 "constructor"
6513 "constructs"
6514 "deprecated"
6515 "desc"
6516 "description"
6517 "event"
6518 "example"
6519 "exec"
6520 "export"
6521 "fileoverview"
6522 "final"
6523 "function"
6524 "hidden"
6525 "ignore"
6526 "implicitCast"
6527 "inheritDoc"
6528 "inner"
6529 "interface"
6530 "license"
6531 "noalias"
6532 "noshadow"
6533 "notypecheck"
6534 "override"
6535 "owner"
6536 "preserve"
6537 "preserveTry"
6538 "private"
6539 "protected"
6540 "public"
6541 "static"
6542 "supported"
6543 ))
6544 "\\)\\)\\s-*")
6545 "Matches empty jsdoc tags.")
6546
6547 (defconst js2-jsdoc-link-tag-regexp
6548 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6549 "Matches a jsdoc link or code tag.")
6550
6551 (defconst js2-jsdoc-see-tag-regexp
6552 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6553 "Matches a jsdoc @see tag.")
6554
6555 (defconst js2-jsdoc-html-tag-regexp
6556 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6557 "Matches a simple (no attributes) html start- or end-tag.")
6558
6559 (defsubst js2-jsdoc-highlight-helper ()
6560 (js2-set-face (match-beginning 1)
6561 (match-end 1)
6562 'js2-jsdoc-tag-face)
6563 (if (match-beginning 2)
6564 (if (save-excursion
6565 (goto-char (match-beginning 2))
6566 (= (char-after) ?{))
6567 (js2-set-face (1+ (match-beginning 2))
6568 (1- (match-end 2))
6569 'js2-jsdoc-type-face)
6570 (js2-set-face (match-beginning 2)
6571 (match-end 2)
6572 'js2-jsdoc-value-face)))
6573 (if (match-beginning 3)
6574 (js2-set-face (match-beginning 3)
6575 (match-end 3)
6576 'js2-jsdoc-value-face)))
6577
6578 (defun js2-highlight-jsdoc (ast)
6579 "Highlight doc comment tags."
6580 (let ((comments (js2-ast-root-comments ast))
6581 beg end)
6582 (save-excursion
6583 (dolist (node comments)
6584 (when (eq (js2-comment-node-format node) 'jsdoc)
6585 (setq beg (js2-node-abs-pos node)
6586 end (+ beg (js2-node-len node)))
6587 (save-restriction
6588 (narrow-to-region beg end)
6589 (dolist (re (list js2-jsdoc-param-tag-regexp
6590 js2-jsdoc-typed-tag-regexp
6591 js2-jsdoc-arg-tag-regexp
6592 js2-jsdoc-link-tag-regexp
6593 js2-jsdoc-see-tag-regexp
6594 js2-jsdoc-empty-tag-regexp))
6595 (goto-char beg)
6596 (while (re-search-forward re nil t)
6597 (js2-jsdoc-highlight-helper)))
6598 ;; simple highlighting for html tags
6599 (goto-char beg)
6600 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6601 (js2-set-face (match-beginning 1)
6602 (match-end 1)
6603 'js2-jsdoc-html-tag-delimiter-face)
6604 (js2-set-face (match-beginning 2)
6605 (match-end 2)
6606 'js2-jsdoc-html-tag-name-face)
6607 (js2-set-face (match-beginning 3)
6608 (match-end 3)
6609 'js2-jsdoc-html-tag-delimiter-face))))))))
6610
6611 (defun js2-highlight-assign-targets (node left right)
6612 "Highlight function properties and external variables."
6613 (let (leftpos end name)
6614 ;; highlight vars and props assigned function values
6615 (when (js2-function-node-p right)
6616 (cond
6617 ;; var foo = function() {...}
6618 ((js2-name-node-p left)
6619 (setq name left))
6620 ;; foo.bar.baz = function() {...}
6621 ((and (js2-prop-get-node-p left)
6622 (js2-name-node-p (js2-prop-get-node-right left)))
6623 (setq name (js2-prop-get-node-right left))))
6624 (when name
6625 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6626 (+ leftpos (js2-node-len name))
6627 'font-lock-function-name-face
6628 'record)))))
6629
6630 (defun js2-record-name-node (node)
6631 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6632 later. NODE must be a name node."
6633 (push (list node js2-current-scope
6634 (setq leftpos (js2-node-abs-pos node))
6635 (setq end (+ leftpos (js2-node-len node))))
6636 js2-recorded-identifiers))
6637
6638 (defun js2-highlight-undeclared-vars ()
6639 "After entire parse is finished, look for undeclared variable references.
6640 We have to wait until entire buffer is parsed, since JavaScript permits var
6641 decls to occur after they're used.
6642
6643 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6644 it is considered declared."
6645 (let (name)
6646 (dolist (entry js2-recorded-identifiers)
6647 (destructuring-bind (name-node scope pos end) entry
6648 (setq name (js2-name-node-name name-node))
6649 (unless (or (member name js2-global-externs)
6650 (member name js2-default-externs)
6651 (member name js2-additional-externs)
6652 (js2-get-defining-scope scope name))
6653 (js2-set-face pos end 'js2-external-variable-face 'record)
6654 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6655 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6656 (setq js2-recorded-identifiers nil)))
6657
6658 ;;; IMenu support
6659
6660 ;; We currently only support imenu, but eventually should support speedbar and
6661 ;; possibly other browsing mechanisms.
6662
6663 ;; The basic strategy is to identify function assignment targets of the form
6664 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6665 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6666 ;; for imenu after parsing is finished.
6667
6668 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6669 ;; JavaScript, and the general problem is undecidable. However, several forms
6670 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6671 ;; include:
6672
6673 ;; function foo() -- function declaration
6674 ;; foo = function() -- function expression assigned to variable
6675 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6676 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6677 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6678 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6679 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6680 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6681 ;; function foo() {function bar() {...}} -- nested function
6682 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6683
6684 ;; This list boils down to a few forms that can be combined recursively.
6685 ;; Top-level named function declarations include both the left-hand (name)
6686 ;; and the right-hand (function value) expressions needed to produce an imenu
6687 ;; entry. The other "right-hand" forms we need to look for are:
6688 ;; - functions declared as props/getters/setters in object literals
6689 ;; - nested named function declarations
6690 ;; The "left-hand" expressions that functions can be assigned to include:
6691 ;; - local/global variables
6692 ;; - nested property-get expressions like a.b.c.d
6693 ;; - element gets like foo[10] or foo['bar'] where the index
6694 ;; expression can be trivially converted to a property name. They
6695 ;; effectively then become property gets.
6696
6697 ;; All the different definition types are canonicalized into the form
6698 ;; foo.bar.baz = position-of-function-keyword
6699
6700 ;; We need to build a trie-like structure for imenu. As an example,
6701 ;; consider the following JavaScript code:
6702
6703 ;; a = function() {...} // function at position 5
6704 ;; b = function() {...} // function at position 25
6705 ;; foo = function() {...} // function at position 100
6706 ;; foo.bar = function() {...} // function at position 200
6707 ;; foo.bar.baz = function() {...} // function at position 300
6708 ;; foo.bar.zab = function() {...} // function at position 400
6709
6710 ;; During parsing we accumulate an entry for each definition in
6711 ;; the variable `js2-imenu-recorder', like so:
6712
6713 ;; '((a 5)
6714 ;; (b 25)
6715 ;; (foo 100)
6716 ;; (foo bar 200)
6717 ;; (foo bar baz 300)
6718 ;; (foo bar zab 400))
6719
6720 ;; After parsing these entries are merged into this alist-trie:
6721
6722 ;; '((a . 1)
6723 ;; (b . 2)
6724 ;; (foo (<definition> . 3)
6725 ;; (bar (<definition> . 6)
6726 ;; (baz . 100)
6727 ;; (zab . 200))))
6728
6729 ;; Note the wacky need for a <definition> name. The token can be anything
6730 ;; that isn't a valid JavaScript identifier, because you might make foo
6731 ;; a function and then start setting properties on it that are also functions.
6732
6733 (defsubst js2-prop-node-name (node)
6734 "Return the name of a node that may be a property-get/property-name.
6735 If NODE is not a valid name-node, string-node or integral number-node,
6736 returns nil. Otherwise returns the string name/value of the node."
6737 (cond
6738 ((js2-name-node-p node)
6739 (js2-name-node-name node))
6740 ((js2-string-node-p node)
6741 (js2-string-node-value node))
6742 ((and (js2-number-node-p node)
6743 (string-match "^[0-9]+$" (js2-number-node-value node)))
6744 (js2-number-node-value node))
6745 ((js2-this-node-p node)
6746 "this")))
6747
6748 (defsubst js2-node-qname-component (node)
6749 "Test function: return the name of this node, if it contributes to a qname.
6750 Returns nil if the node doesn't contribute."
6751 (copy-sequence
6752 (or (js2-prop-node-name node)
6753 (if (and (js2-function-node-p node)
6754 (js2-function-node-name node))
6755 (js2-name-node-name (js2-function-node-name node))))))
6756
6757 (defsubst js2-record-function-qname (fn-node qname)
6758 "Associate FN-NODE with its QNAME for later lookup.
6759 This is used in postprocessing the chain list. When we find a chain
6760 whose first element is a js2-THIS keyword node, we look up the parent
6761 function and see (using this map) whether it is the tail of a chain.
6762 If so, we replace the this-node with a copy of the parent's qname."
6763 (unless js2-imenu-function-map
6764 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6765 (puthash fn-node qname js2-imenu-function-map))
6766
6767 (defun js2-record-imenu-functions (node &optional var)
6768 "Record function definitions for imenu.
6769 NODE is a function node or an object literal.
6770 VAR, if non-nil, is the expression that NODE is being assigned to."
6771 (when js2-parse-ide-mode
6772 (let ((fun-p (js2-function-node-p node))
6773 qname left fname-node pos)
6774 (cond
6775 ;; non-anonymous function declaration?
6776 ((and fun-p
6777 (not var)
6778 (setq fname-node (js2-function-node-name node)))
6779 (push (setq qname (list fname-node (js2-node-pos node)))
6780 js2-imenu-recorder)
6781 (js2-record-function-qname node qname))
6782 ;; for remaining forms, compute left-side tree branch first
6783 ((and var (setq qname (js2-compute-nested-prop-get var)))
6784 (cond
6785 ;; foo.bar.baz = function
6786 (fun-p
6787 (push (nconc qname (list (js2-node-pos node)))
6788 js2-imenu-recorder)
6789 (js2-record-function-qname node qname))
6790 ;; foo.bar.baz = object-literal
6791 ;; look for nested functions: {a: {b: function() {...} }}
6792 ((js2-object-node-p node)
6793 ;; Node position here is still absolute, since the parser
6794 ;; passes the assignment target and value expressions
6795 ;; to us before they are added as children of the assignment node.
6796 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6797
6798 (defun js2-compute-nested-prop-get (node)
6799 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6800 component nodes as a list. Otherwise return nil. Element-gets are treated
6801 as property-gets if the index expression is a string, or a positive integer."
6802 (let (left right head)
6803 (cond
6804 ((or (js2-name-node-p node)
6805 (js2-this-node-p node))
6806 (list node))
6807 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6808 ((js2-prop-get-node-p node) ; foo.bar
6809 (setq left (js2-prop-get-node-left node)
6810 right (js2-prop-get-node-right node))
6811 (if (setq head (js2-compute-nested-prop-get left))
6812 (nconc head (list right))))
6813 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6814 (setq left (js2-elem-get-node-target node)
6815 right (js2-elem-get-node-element node))
6816 (if (or (js2-string-node-p right) ; ['bar']
6817 (and (js2-number-node-p right) ; [10]
6818 (string-match "^[0-9]+$"
6819 (js2-number-node-value right))))
6820 (if (setq head (js2-compute-nested-prop-get left))
6821 (nconc head (list right))))))))
6822
6823 (defun js2-record-object-literal (node qname pos)
6824 "Recursively process an object literal looking for functions.
6825 NODE is an object literal that is the right-hand child of an assignment
6826 expression. QNAME is a list of nodes representing the assignment target,
6827 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6828 POS is the absolute position of the node.
6829 We do a depth-first traversal of NODE. Any functions we find are prefixed
6830 with QNAME plus the property name of the function and appended to the
6831 variable `js2-imenu-recorder'."
6832 (let (left right)
6833 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6834 (let ((left (js2-infix-node-left e))
6835 ;; Element positions are relative to the parent position.
6836 (pos (+ pos (js2-node-pos e))))
6837 (cond
6838 ;; foo: function() {...}
6839 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6840 (when (js2-prop-node-name left)
6841 ;; As a policy decision, we record the position of the property,
6842 ;; not the position of the `function' keyword, since the property
6843 ;; is effectively the name of the function.
6844 (push (append qname (list left pos))
6845 js2-imenu-recorder)
6846 (js2-record-function-qname right qname)))
6847 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6848 ((js2-object-node-p right)
6849 (js2-record-object-literal right
6850 (append qname (list (js2-infix-node-left e)))
6851 (+ pos (js2-node-pos right)))))))))
6852
6853 (defsubst js2-node-top-level-decl-p (node)
6854 "Return t if NODE's name is defined in the top-level scope.
6855 Also returns t if NODE's name is not defined in any scope, since it implies
6856 that it's an external variable, which must also be in the top-level scope."
6857 (let* ((name (js2-prop-node-name node))
6858 (this-scope (js2-node-get-enclosing-scope node))
6859 defining-scope)
6860 (cond
6861 ((js2-this-node-p node)
6862 nil)
6863 ((null this-scope)
6864 t)
6865 ((setq defining-scope (js2-get-defining-scope this-scope name))
6866 (js2-ast-root-p defining-scope))
6867 (t t))))
6868
6869 (defun js2-browse-postprocess-chains (chains)
6870 "Modify function-declaration name chains after parsing finishes.
6871 Some of the information is only available after the parse tree is complete.
6872 For instance, following a 'this' reference requires a parent function node."
6873 (let (result head fn parent-chain p elem)
6874 (dolist (chain chains)
6875 ;; examine the head of each node to get its defining scope
6876 (setq head (car chain))
6877 ;; if top-level/external, keep as-is
6878 (if (js2-node-top-level-decl-p head)
6879 (push chain result)
6880 (cond
6881 ;; starts with this-reference
6882 ((js2-this-node-p head)
6883 (setq fn (js2-node-parent-script-or-fn head)
6884 chain (cdr chain))) ; discard this-node
6885 ;; nested named function
6886 ((js2-function-node-p (setq parent (js2-node-parent head)))
6887 (setq fn (js2-node-parent-script-or-fn parent)))
6888 ;; variable assigned a function expression
6889 (t (setq fn (js2-node-parent-script-or-fn head))))
6890 (unless (or (null fn) (js2-nested-function-p fn))
6891 ;; if the parent function is found, and it's not nested,
6892 ;; look it up in function-map.
6893 (if (setq parent-chain (and js2-imenu-function-map
6894 (gethash fn js2-imenu-function-map)))
6895 ;; prefix parent fn qname, which is the
6896 ;; parent-chain sans tail, to this chain.
6897 (push (append (butlast parent-chain) chain) result)
6898 ;; parent function is not nested, and not in function-map
6899 ;; => it's anonymous top-level wrapper, discard.
6900 (push chain result)))))
6901 ;; finally replace each node in each chain with its name.
6902 (dolist (chain result)
6903 (setq p chain)
6904 (while p
6905 (if (js2-node-p (setq elem (car p)))
6906 (setcar p (js2-node-qname-component elem)))
6907 (setq p (cdr p))))
6908 result))
6909
6910 ;; Merge name chains into a trie-like tree structure of nested lists.
6911 ;; To simplify construction of the trie, we first build it out using the rule
6912 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6913 ;; [key, num-or-list]. The second element can be a number; if so, this key
6914 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6915 ;; associated with the key at this level.) Otherwise the second element is
6916 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6917 ;; a simple recursive formulation.
6918 ;;
6919 ;; js2-mode is building the data structure for imenu. The imenu documentation
6920 ;; claims that it's the structure above, but in practice it wants the children
6921 ;; at the same list level as the key for that level, which is how I've drawn
6922 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6923 ;; list wrapper around the children at each level.
6924 ;;
6925 ;; A completed nested imenu-alist entry looks like this:
6926 ;; '(("foo"
6927 ;; ("<definition>" . 7)
6928 ;; ("bar"
6929 ;; ("a" . 40)
6930 ;; ("b" . 60))))
6931 ;;
6932 ;; In particular, the documentation for `imenu--index-alist' says that
6933 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6934 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6935
6936 (defsubst js2-treeify (lst)
6937 "Convert (a b c d) to (a ((b ((c d)))))"
6938 (if (null (cddr lst)) ; list length <= 2
6939 lst
6940 (list (car lst) (list (js2-treeify (cdr lst))))))
6941
6942 (defun js2-build-alist-trie (chains trie)
6943 "Merge declaration name chains into a trie-like alist structure for imenu.
6944 CHAINS is the qname chain list produced during parsing. TRIE is a
6945 list of elements built up so far."
6946 (let (head tail pos branch kids)
6947 (dolist (chain chains)
6948 (setq head (car chain)
6949 tail (cdr chain)
6950 pos (if (numberp (car tail)) (car tail))
6951 branch (js2-find-if (lambda (n)
6952 (string= (car n) head))
6953 trie)
6954 kids (second branch))
6955 (cond
6956 ;; case 1: this key isn't in the trie yet
6957 ((null branch)
6958 (if trie
6959 (setcdr (last trie) (list (js2-treeify chain)))
6960 (setq trie (list (js2-treeify chain)))))
6961 ;; case 2: key is present with a single number entry: replace w/ list
6962 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6963 ;; ("<definition>" 20)))
6964 ((numberp kids)
6965 (setcar (cdr branch)
6966 (list (list "<definition-1>" kids)
6967 (if pos
6968 (list "<definition-2>" pos)
6969 (js2-treeify tail)))))
6970 ;; case 3: key is there (with kids), and we're a number entry
6971 (pos
6972 (setcdr (last kids)
6973 (list
6974 (list (format "<definition-%d>"
6975 (1+ (loop for kid in kids
6976 count (eq ?< (aref (car kid) 0)))))
6977 pos))))
6978 ;; case 4: key is there with kids, need to merge in our chain
6979 (t
6980 (js2-build-alist-trie (list tail) kids))))
6981 trie))
6982
6983 (defun js2-flatten-trie (trie)
6984 "Convert TRIE to imenu-format.
6985 Recurses through nodes, and for each one whose second element is a list,
6986 appends the list's flattened elements to the current element. Also
6987 changes the tails into conses. For instance, this pre-flattened trie
6988
6989 '(a ((b 20)
6990 (c ((d 30)
6991 (e 40)))))
6992
6993 becomes
6994
6995 '(a (b . 20)
6996 (c (d . 30)
6997 (e . 40)))
6998
6999 Note that the root of the trie has no key, just a list of chains.
7000 This is also true for the value of any key with multiple children,
7001 e.g. key 'c' in the example above."
7002 (cond
7003 ((listp (car trie))
7004 (mapcar #'js2-flatten-trie trie))
7005 (t
7006 (if (numberp (second trie))
7007 (cons (car trie) (second trie))
7008 ;; else pop list and append its kids
7009 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7010
7011 (defun js2-build-imenu-index ()
7012 "Turn `js2-imenu-recorder' into an imenu data structure."
7013 (unless (eq js2-imenu-recorder 'empty)
7014 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7015 (result (js2-build-alist-trie chains nil)))
7016 (js2-flatten-trie result))))
7017
7018 (defun js2-test-print-chains (chains)
7019 "Print a list of qname chains.
7020 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7021 i.e. one or more nodes, and an integer position as the list tail."
7022 (mapconcat (lambda (chain)
7023 (concat "("
7024 (mapconcat (lambda (elem)
7025 (if (js2-node-p elem)
7026 (or (js2-node-qname-component elem)
7027 "nil")
7028 (number-to-string elem)))
7029 chain
7030 " ")
7031 ")"))
7032 chains
7033 "\n"))
7034
7035 ;;; Parser
7036
7037 (defconst js2-version "1.8.0"
7038 "Version of JavaScript supported, plus minor js2 version.")
7039
7040 (defmacro js2-record-face (face)
7041 "Record a style run of FACE for the current token."
7042 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7043
7044 (defsubst js2-node-end (n)
7045 "Computes the absolute end of node N.
7046 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7047 is only true until the node is added to its parent; i.e., while parsing."
7048 (+ (js2-node-pos n)
7049 (js2-node-len n)))
7050
7051 (defsubst js2-record-comment ()
7052 "Record a comment in `js2-scanned-comments'."
7053 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7054 :format js2-ts-comment-type)
7055 js2-scanned-comments)
7056 (when js2-parse-ide-mode
7057 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7058 'font-lock-doc-face
7059 'font-lock-comment-face))
7060 (when (memq js2-ts-comment-type '(html preprocessor))
7061 ;; Tell cc-engine the bounds of the comment.
7062 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7063
7064 ;; This function is called depressingly often, so it should be fast.
7065 ;; Most of the time it's looking at the same token it peeked before.
7066 (defsubst js2-peek-token ()
7067 "Returns the next token without consuming it.
7068 If previous token was consumed, calls scanner to get new token.
7069 If previous token was -not- consumed, returns it (idempotent).
7070
7071 This function will not return a newline (js2-EOL) - instead, it
7072 gobbles newlines until it finds a non-newline token, and flags
7073 that token as appearing just after a newline.
7074
7075 This function will also not return a js2-COMMENT. Instead, it
7076 records comments found in `js2-scanned-comments'. If the token
7077 returned by this function immediately follows a jsdoc comment,
7078 the token is flagged as such.
7079
7080 Note that this function always returned the un-flagged token!
7081 The flags, if any, are saved in `js2-current-flagged-token'."
7082 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7083 js2-current-token ; most common case - return already-peeked token
7084 (let ((tt (js2-get-token)) ; call scanner
7085 saw-eol
7086 face)
7087 ;; process comments and whitespace
7088 (while (or (= tt js2-EOL)
7089 (= tt js2-COMMENT))
7090 (if (= tt js2-EOL)
7091 (setq saw-eol t)
7092 (setq saw-eol nil)
7093 (if js2-record-comments
7094 (js2-record-comment)))
7095 (setq tt (js2-get-token))) ; call scanner
7096 (setq js2-current-token tt
7097 js2-current-flagged-token (if saw-eol
7098 (logior tt js2-ti-after-eol)
7099 tt))
7100 ;; perform lexical fontification as soon as token is scanned
7101 (when js2-parse-ide-mode
7102 (cond
7103 ((minusp tt)
7104 (js2-record-face 'js2-error-face))
7105 ((setq face (aref js2-kwd-tokens tt))
7106 (js2-record-face face))
7107 ((and (= tt js2-NAME)
7108 (equal js2-ts-string "undefined"))
7109 (js2-record-face 'font-lock-constant-face))))
7110 tt))) ; return unflagged token
7111
7112 (defsubst js2-peek-flagged-token ()
7113 "Returns the current token along with any flags set for it."
7114 (js2-peek-token)
7115 js2-current-flagged-token)
7116
7117 (defsubst js2-consume-token ()
7118 (setq js2-current-flagged-token js2-EOF))
7119
7120 (defsubst js2-next-token ()
7121 (prog1
7122 (js2-peek-token)
7123 (js2-consume-token)))
7124
7125 (defsubst js2-next-flagged-token ()
7126 (js2-peek-token)
7127 (prog1 js2-current-flagged-token
7128 (js2-consume-token)))
7129
7130 (defsubst js2-match-token (match)
7131 "Consume and return t if next token matches MATCH, a bytecode.
7132 Returns nil and consumes nothing if MATCH is not the next token."
7133 (if (/= (js2-peek-token) match)
7134 nil
7135 (js2-consume-token)
7136 t))
7137
7138 (defsubst js2-valid-prop-name-token (tt)
7139 (or (= tt js2-NAME)
7140 (and js2-allow-keywords-as-property-names
7141 (plusp tt)
7142 (aref js2-kwd-tokens tt))))
7143
7144 (defsubst js2-match-prop-name ()
7145 "Consume token and return t if next token is a valid property name.
7146 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7147 is non-nil and it's a keyword token."
7148 (if (js2-valid-prop-name-token (js2-peek-token))
7149 (progn
7150 (js2-consume-token)
7151 t)
7152 nil))
7153
7154 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7155 (if (js2-match-prop-name)
7156 t
7157 (js2-report-error msg-id nil pos len)
7158 nil))
7159
7160 (defsubst js2-peek-token-or-eol ()
7161 "Return js2-EOL if the current token immediately follows a newline.
7162 Else returns the current token. Used in situations where we don't
7163 consider certain token types valid if they are preceded by a newline.
7164 One example is the postfix ++ or -- operator, which has to be on the
7165 same line as its operand."
7166 (let ((tt (js2-peek-token)))
7167 ;; Check for last peeked token flags
7168 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7169 js2-EOL
7170 tt)))
7171
7172 (defsubst js2-set-check-for-label ()
7173 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7174 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7175
7176 (defsubst js2-must-match (token msg-id &optional pos len)
7177 "Match next token to token code TOKEN, or record a syntax error.
7178 MSG-ID is the error message to report if the match fails.
7179 Returns t on match, nil if no match."
7180 (if (js2-match-token token)
7181 t
7182 (js2-report-error msg-id nil pos len)
7183 nil))
7184
7185 (defsubst js2-inside-function ()
7186 (plusp js2-nesting-of-function))
7187
7188 (defsubst js2-set-requires-activation ()
7189 (if (js2-function-node-p js2-current-script-or-fn)
7190 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7191
7192 (defsubst js2-check-activation-name (name token)
7193 (when (js2-inside-function)
7194 ;; skip language-version 1.2 check from Rhino
7195 (if (or (string= "arguments" name)
7196 (and js2-compiler-activation-names ; only used in codegen
7197 (gethash name js2-compiler-activation-names)))
7198 (js2-set-requires-activation))))
7199
7200 (defsubst js2-set-is-generator ()
7201 (if (js2-function-node-p js2-current-script-or-fn)
7202 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7203
7204 (defsubst js2-must-have-xml ()
7205 (unless js2-compiler-xml-available
7206 (js2-report-error "msg.XML.not.available")))
7207
7208 (defsubst js2-push-scope (scope)
7209 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7210 (assert (js2-scope-p scope))
7211 (assert (null (js2-scope-parent-scope scope)))
7212 (assert (not (eq js2-current-scope scope)))
7213 (setf (js2-scope-parent-scope scope) js2-current-scope
7214 js2-current-scope scope))
7215
7216 (defsubst js2-pop-scope ()
7217 (setq js2-current-scope
7218 (js2-scope-parent-scope js2-current-scope)))
7219
7220 (defsubst js2-enter-loop (loop-node)
7221 (push loop-node js2-loop-set)
7222 (push loop-node js2-loop-and-switch-set)
7223 (js2-push-scope loop-node)
7224 ;; Tell the current labeled statement (if any) its statement,
7225 ;; and set the jump target of the first label to the loop.
7226 ;; These are used in `js2-parse-continue' to verify that the
7227 ;; continue target is an actual labeled loop. (And for codegen.)
7228 (when js2-labeled-stmt
7229 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7230 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7231 js2-labeled-stmt))) loop-node)))
7232
7233 (defsubst js2-exit-loop ()
7234 (pop js2-loop-set)
7235 (pop js2-loop-and-switch-set)
7236 (js2-pop-scope))
7237
7238 (defsubst js2-enter-switch (switch-node)
7239 (push switch-node js2-loop-and-switch-set))
7240
7241 (defsubst js2-exit-switch ()
7242 (pop js2-loop-and-switch-set))
7243
7244 (defun js2-parse (&optional buf cb)
7245 "Tells the js2 parser to parse a region of JavaScript.
7246
7247 BUF is a buffer or buffer name containing the code to parse.
7248 Call `narrow-to-region' first to parse only part of the buffer.
7249
7250 The returned AST root node is given some additional properties:
7251 `node-count' - total number of nodes in the AST
7252 `buffer' - BUF. The buffer it refers to may change or be killed,
7253 so the value is not necessarily reliable.
7254
7255 An optional callback CB can be specified to report parsing
7256 progress. If `(functionp CB)' returns t, it will be called with
7257 the current line number once before parsing begins, then again
7258 each time the lexer reaches a new line number.
7259
7260 CB can also be a list of the form `(symbol cb ...)' to specify
7261 multiple callbacks with different criteria. Each symbol is a
7262 criterion keyword, and the following element is the callback to
7263 call
7264
7265 :line - called whenever the line number changes
7266 :token - called for each new token consumed
7267
7268 The list of criteria could be extended to include entering or
7269 leaving a statement, an expression, or a function definition."
7270 (if (and cb (not (functionp cb)))
7271 (error "criteria callbacks not yet implemented"))
7272 (let ((inhibit-point-motion-hooks t)
7273 (js2-compiler-xml-available (>= js2-language-version 160))
7274 ;; This is a recursive-descent parser, so give it a big stack.
7275 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7276 (max-specpdl-size (max max-specpdl-size 3000))
7277 (case-fold-search nil)
7278 ast)
7279 (or buf (setq buf (current-buffer)))
7280 (message nil) ; clear any error message from previous parse
7281 (save-excursion
7282 (set-buffer buf)
7283 (setq js2-scanned-comments nil
7284 js2-parsed-errors nil
7285 js2-parsed-warnings nil
7286 js2-imenu-recorder nil
7287 js2-imenu-function-map nil
7288 js2-label-set nil)
7289 (js2-init-scanner)
7290 (setq ast (js2-with-unmodifying-text-property-changes
7291 (js2-do-parse)))
7292 (unless js2-ts-hit-eof
7293 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7294 (setf (js2-ast-root-errors ast) js2-parsed-errors
7295 (js2-ast-root-warnings ast) js2-parsed-warnings)
7296 ;; if we didn't find any declarations, put a dummy in this list so we
7297 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7298 (unless js2-imenu-recorder
7299 (setq js2-imenu-recorder 'empty))
7300 (run-hooks 'js2-parse-finished-hook)
7301 ast)))
7302
7303 ;; Corresponds to Rhino's Parser.parse() method.
7304 (defun js2-do-parse ()
7305 "Parse current buffer starting from current point.
7306 Scanner should be initialized."
7307 (let ((pos js2-ts-cursor)
7308 (end js2-ts-cursor) ; in case file is empty
7309 root n tt)
7310 ;; initialize buffer-local parsing vars
7311 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7312 js2-current-script-or-fn root
7313 js2-current-scope root
7314 js2-current-flagged-token js2-EOF
7315 js2-nesting-of-function 0
7316 js2-labeled-stmt nil
7317 js2-recorded-identifiers nil) ; for js2-highlight
7318 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7319 (if (= tt js2-FUNCTION)
7320 (progn
7321 (js2-consume-token)
7322 (setq n (js2-parse-function (if js2-called-by-compile-function
7323 'FUNCTION_EXPRESSION
7324 'FUNCTION_STATEMENT))))
7325 ;; not a function - parse a statement
7326 (setq n (js2-parse-statement)))
7327 ;; add function or statement to script
7328 (setq end (js2-node-end n))
7329 (js2-block-node-push root n))
7330 ;; add comments to root in lexical order
7331 (when js2-scanned-comments
7332 ;; if we find a comment beyond end of normal kids, use its end
7333 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7334 (dolist (comment js2-scanned-comments)
7335 (push comment (js2-ast-root-comments root))
7336 (js2-node-add-children root comment)))
7337 (setf (js2-node-len root) (- end pos))
7338 ;; Give extensions a chance to muck with things before highlighting starts.
7339 (dolist (callback js2-post-parse-callbacks)
7340 (funcall callback))
7341 (js2-highlight-undeclared-vars)
7342 root))
7343
7344 (defun js2-function-parser ()
7345 (js2-consume-token)
7346 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7347
7348 (defun js2-parse-function-closure-body (fn-node)
7349 "Parse a JavaScript 1.8 function closure body."
7350 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7351 (if js2-ts-hit-eof
7352 (js2-report-error "msg.no.brace.body" nil
7353 (js2-node-pos fn-node)
7354 (- js2-ts-cursor (js2-node-pos fn-node)))
7355 (js2-node-add-children fn-node
7356 (setf (js2-function-node-body fn-node)
7357 (js2-parse-expr t))))))
7358
7359 (defun js2-parse-function-body (fn-node)
7360 (js2-must-match js2-LC "msg.no.brace.body"
7361 (js2-node-pos fn-node)
7362 (- js2-ts-cursor (js2-node-pos fn-node)))
7363 (let ((pos js2-token-beg) ; LC position
7364 (pn (make-js2-block-node)) ; starts at LC position
7365 tt
7366 end)
7367 (incf js2-nesting-of-function)
7368 (unwind-protect
7369 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7370 (= tt js2-EOF)
7371 (= tt js2-RC)))
7372 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7373 (js2-parse-statement)
7374 (js2-consume-token)
7375 (js2-parse-function 'FUNCTION_STATEMENT))))
7376 (decf js2-nesting-of-function))
7377 (setq end js2-token-end) ; assume no curly and leave at current token
7378 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7379 (setq end js2-token-end))
7380 (setf (js2-node-pos pn) pos
7381 (js2-node-len pn) (- end pos))
7382 (setf (js2-function-node-body fn-node) pn)
7383 (js2-node-add-children fn-node pn)
7384 pn))
7385
7386 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7387 "Declare and fontify destructuring parameters inside NODE.
7388 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7389 (cond
7390 ((js2-name-node-p node)
7391 (let (leftpos)
7392 (js2-define-symbol decl-type (js2-name-node-name node)
7393 node ignore-not-in-block)
7394 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7395 (+ leftpos (js2-node-len node))
7396 face 'record)))
7397 ((js2-object-node-p node)
7398 (dolist (elem (js2-object-node-elems node))
7399 (js2-define-destruct-symbols
7400 (if (js2-object-prop-node-p elem)
7401 (js2-object-prop-node-right elem)
7402 ;; abbreviated destructuring {a, b}
7403 elem)
7404 decl-type face ignore-not-in-block)))
7405 ((js2-array-node-p node)
7406 (dolist (elem (js2-array-node-elems node))
7407 (when elem
7408 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7409 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7410 (js2-node-len node)))))
7411
7412 (defun js2-parse-function-params (fn-node pos)
7413 (if (js2-match-token js2-RP)
7414 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7415 (let (params len param)
7416 (loop for tt = (js2-peek-token)
7417 do
7418 (cond
7419 ;; destructuring param
7420 ((or (= tt js2-LB) (= tt js2-LC))
7421 (setq param (js2-parse-primary-expr-lhs))
7422 (js2-define-destruct-symbols param
7423 js2-LP
7424 'js2-function-param-face)
7425 (push param params))
7426 ;; simple name
7427 (t
7428 (js2-must-match js2-NAME "msg.no.parm")
7429 (js2-record-face 'js2-function-param-face)
7430 (setq param (js2-create-name-node))
7431 (js2-define-symbol js2-LP js2-ts-string param)
7432 (push param params)))
7433 while
7434 (js2-match-token js2-COMMA))
7435 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7436 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7437 (dolist (p params)
7438 (js2-node-add-children fn-node p)
7439 (push p (js2-function-node-params fn-node))))))
7440
7441 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7442 "Possibly show inconsistent-return warning.
7443 Last token scanned is the close-curly for the function body."
7444 (when (and js2-mode-show-strict-warnings
7445 js2-strict-inconsistent-return-warning
7446 (not (js2-has-consistent-return-usage
7447 (js2-function-node-body fn-node))))
7448 ;; Have it extend from close-curly to bol or beginning of block.
7449 (let ((pos (save-excursion
7450 (goto-char js2-token-end)
7451 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7452 (point-at-bol))))
7453 (end js2-token-end))
7454 (if (plusp (js2-name-node-length name))
7455 (js2-add-strict-warning "msg.no.return.value"
7456 (js2-name-node-name name) pos end)
7457 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7458
7459 (defun js2-parse-function (function-type)
7460 "Function parser. FUNCTION-TYPE is a symbol."
7461 (let ((pos js2-token-beg) ; start of 'function' keyword
7462 name
7463 name-beg
7464 name-end
7465 fn-node
7466 lp
7467 (synthetic-type function-type)
7468 member-expr-node)
7469 ;; parse function name, expression, or non-name (anonymous)
7470 (cond
7471 ;; function foo(...)
7472 ((js2-match-token js2-NAME)
7473 (setq name (js2-create-name-node t)
7474 name-beg js2-token-beg
7475 name-end js2-token-end)
7476 (unless (js2-match-token js2-LP)
7477 (when js2-allow-member-expr-as-function-name
7478 ;; function foo.bar(...)
7479 (setq member-expr-node name
7480 name nil
7481 member-expr-node (js2-parse-member-expr-tail
7482 nil member-expr-node)))
7483 (js2-must-match js2-LP "msg.no.paren.parms")))
7484 ((js2-match-token js2-LP)
7485 nil) ; anonymous function: leave name as null
7486 (t
7487 ;; function random-member-expr(...)
7488 (when js2-allow-member-expr-as-function-name
7489 ;; Note that memberExpr can not start with '(' like
7490 ;; in function (1+2).toString(), because 'function (' already
7491 ;; processed as anonymous function
7492 (setq member-expr-node (js2-parse-member-expr)))
7493 (js2-must-match js2-LP "msg.no.paren.parms")))
7494 (if (= js2-current-token js2-LP) ; eventually matched LP?
7495 (setq lp js2-token-beg))
7496 (if member-expr-node
7497 (progn
7498 (setq synthetic-type 'FUNCTION_EXPRESSION)
7499 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7500 (if name
7501 (js2-set-face name-beg name-end
7502 'font-lock-function-name-face 'record)))
7503 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7504 (plusp (js2-name-node-length name)))
7505 ;; Function statements define a symbol in the enclosing scope
7506 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7507 (setf fn-node (make-js2-function-node :pos pos
7508 :name name
7509 :form function-type
7510 :lp (if lp (- lp pos))))
7511 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7512 ;; 1. Nested functions are not affected by the dynamic scope flag
7513 ;; as dynamic scope is already a parent of their scope.
7514 ;; 2. Functions defined under the with statement also immune to
7515 ;; this setup, in which case dynamic scope is ignored in favor
7516 ;; of the with object.
7517 (setf (js2-function-node-ignore-dynamic fn-node) t))
7518 ;; dynamically bind all the per-function variables
7519 (let ((js2-current-script-or-fn fn-node)
7520 (js2-current-scope fn-node)
7521 (js2-nesting-of-with 0)
7522 (js2-end-flags 0)
7523 js2-label-set
7524 js2-loop-set
7525 js2-loop-and-switch-set)
7526 (js2-parse-function-params fn-node pos)
7527 (if (and (>= js2-language-version 180)
7528 (/= (js2-peek-token) js2-LC))
7529 (js2-parse-function-closure-body fn-node)
7530 (js2-parse-function-body fn-node))
7531 (if name
7532 (js2-node-add-children fn-node name))
7533 (js2-check-inconsistent-return-warning fn-node name)
7534 ;; Function expressions define a name only in the body of the
7535 ;; function, and only if not hidden by a parameter name
7536 (if (and name
7537 (eq synthetic-type 'FUNCTION_EXPRESSION)
7538 (null (js2-scope-get-symbol js2-current-scope
7539 (js2-name-node-name name))))
7540 (js2-define-symbol js2-FUNCTION
7541 (js2-name-node-name name)
7542 fn-node))
7543 (if (and name
7544 (not (eq function-type 'FUNCTION_EXPRESSION)))
7545 (js2-record-imenu-functions fn-node)))
7546 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7547 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7548 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7549 ;; We wait until after parsing the function to set its parent scope,
7550 ;; since `js2-define-symbol' needs the defining-scope check to stop
7551 ;; at the function boundary when checking for redeclarations.
7552 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7553 fn-node))
7554
7555 (defun js2-parse-statements (&optional parent)
7556 "Parse a statement list. Last token consumed must be js2-LC.
7557
7558 PARENT can be a `js2-block-node', in which case the statements are
7559 appended to PARENT. Otherwise a new `js2-block-node' is created
7560 and returned.
7561
7562 This function does not match the closing js2-RC: the caller
7563 matches the RC so it can provide a suitable error message if not
7564 matched. This means it's up to the caller to set the length of
7565 the node to include the closing RC. The node start pos is set to
7566 the absolute buffer start position, and the caller should fix it
7567 up to be relative to the parent node. All children of this block
7568 node are given relative start positions and correct lengths."
7569 (let ((pn (or parent (make-js2-block-node)))
7570 tt)
7571 (setf (js2-node-pos pn) js2-token-beg)
7572 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7573 (/= tt js2-RC))
7574 (js2-block-node-push pn (js2-parse-statement)))
7575 pn))
7576
7577 (defun js2-parse-statement ()
7578 (let (tt pn beg end)
7579 ;; coarse-grained user-interrupt check - needs work
7580 (and js2-parse-interruptable-p
7581 (zerop (% (incf js2-parse-stmt-count)
7582 js2-statements-per-pause))
7583 (input-pending-p)
7584 (throw 'interrupted t))
7585 (setq pn (js2-statement-helper))
7586 ;; no-side-effects warning check
7587 (unless (js2-node-has-side-effects pn)
7588 (setq end (js2-node-end pn))
7589 (save-excursion
7590 (goto-char end)
7591 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7592 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7593 pn))
7594
7595 ;; These correspond to the switch cases in Parser.statementHelper
7596 (defconst js2-parsers
7597 (let ((parsers (make-vector js2-num-tokens
7598 #'js2-parse-expr-stmt)))
7599 (aset parsers js2-BREAK #'js2-parse-break)
7600 (aset parsers js2-CONST #'js2-parse-const-var)
7601 (aset parsers js2-CONTINUE #'js2-parse-continue)
7602 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7603 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7604 (aset parsers js2-DO #'js2-parse-do)
7605 (aset parsers js2-FOR #'js2-parse-for)
7606 (aset parsers js2-FUNCTION #'js2-function-parser)
7607 (aset parsers js2-IF #'js2-parse-if)
7608 (aset parsers js2-LC #'js2-parse-block)
7609 (aset parsers js2-LET #'js2-parse-let-stmt)
7610 (aset parsers js2-NAME #'js2-parse-name-or-label)
7611 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7612 (aset parsers js2-SEMI #'js2-parse-semi)
7613 (aset parsers js2-SWITCH #'js2-parse-switch)
7614 (aset parsers js2-THROW #'js2-parse-throw)
7615 (aset parsers js2-TRY #'js2-parse-try)
7616 (aset parsers js2-VAR #'js2-parse-const-var)
7617 (aset parsers js2-WHILE #'js2-parse-while)
7618 (aset parsers js2-WITH #'js2-parse-with)
7619 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7620 parsers)
7621 "A vector mapping token types to parser functions.")
7622
7623 (defsubst js2-parse-warn-missing-semi (beg end)
7624 (and js2-mode-show-strict-warnings
7625 js2-strict-missing-semi-warning
7626 (js2-add-strict-warning
7627 "msg.missing.semi" nil
7628 ;; back up to beginning of statement or line
7629 (max beg (save-excursion
7630 (goto-char end)
7631 (point-at-bol)))
7632 end)))
7633
7634 (defconst js2-no-semi-insertion
7635 (list js2-IF
7636 js2-SWITCH
7637 js2-WHILE
7638 js2-DO
7639 js2-FOR
7640 js2-TRY
7641 js2-WITH
7642 js2-LC
7643 js2-ERROR
7644 js2-SEMI
7645 js2-FUNCTION)
7646 "List of tokens that don't do automatic semicolon insertion.")
7647
7648 (defconst js2-autoinsert-semi-and-warn
7649 (list js2-ERROR js2-EOF js2-RC))
7650
7651 (defun js2-statement-helper ()
7652 (let* ((tt (js2-peek-token))
7653 (first-tt tt)
7654 (beg js2-token-beg)
7655 (parser (if (= tt js2-ERROR)
7656 #'js2-parse-semi
7657 (aref js2-parsers tt)))
7658 pn
7659 tt-flagged)
7660 ;; If the statement is set, then it's been told its label by now.
7661 (and js2-labeled-stmt
7662 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7663 (setq js2-labeled-stmt nil))
7664 (setq pn (funcall parser))
7665 ;; Don't do auto semi insertion for certain statement types.
7666 (unless (or (memq first-tt js2-no-semi-insertion)
7667 (js2-labeled-stmt-node-p pn))
7668 (js2-auto-insert-semicolon pn))
7669 pn))
7670
7671 (defun js2-auto-insert-semicolon (pn)
7672 (let* ((tt-flagged (js2-peek-flagged-token))
7673 (tt (logand tt-flagged js2-clear-ti-mask))
7674 (pos (js2-node-pos pn)))
7675 (cond
7676 ((= tt js2-SEMI)
7677 ;; Consume ';' as a part of expression
7678 (js2-consume-token)
7679 ;; extend the node bounds to include the semicolon.
7680 (setf (js2-node-len pn) (- js2-token-end pos)))
7681 ((memq tt js2-autoinsert-semi-and-warn)
7682 ;; Autoinsert ;
7683 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7684 (t
7685 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7686 ;; Report error if no EOL or autoinsert ';' otherwise
7687 (js2-report-error "msg.no.semi.stmt")
7688 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7689
7690 (defun js2-parse-condition ()
7691 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7692 The parens are discarded and the expression node is returned.
7693 The `pos' field of the return value is set to an absolute position
7694 that must be fixed up by the caller.
7695 Return value is a list (EXPR LP RP), with absolute paren positions."
7696 (let (pn lp rp)
7697 (if (js2-must-match js2-LP "msg.no.paren.cond")
7698 (setq lp js2-token-beg))
7699 (setq pn (js2-parse-expr))
7700 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7701 (setq rp js2-token-beg))
7702 ;; Report strict warning on code like "if (a = 7) ..."
7703 (if (and js2-strict-cond-assign-warning
7704 (js2-assign-node-p pn))
7705 (js2-add-strict-warning "msg.equal.as.assign" nil
7706 (js2-node-pos pn)
7707 (+ (js2-node-pos pn)
7708 (js2-node-len pn))))
7709 (list pn lp rp)))
7710
7711 (defun js2-parse-if ()
7712 "Parser for if-statement. Last matched token must be js2-IF."
7713 (let ((pos js2-token-beg)
7714 cond
7715 if-true
7716 if-false
7717 else-pos
7718 end
7719 pn)
7720 (js2-consume-token)
7721 (setq cond (js2-parse-condition)
7722 if-true (js2-parse-statement)
7723 if-false (if (js2-match-token js2-ELSE)
7724 (progn
7725 (setq else-pos (- js2-token-beg pos))
7726 (js2-parse-statement)))
7727 end (js2-node-end (or if-false if-true))
7728 pn (make-js2-if-node :pos pos
7729 :len (- end pos)
7730 :condition (car cond)
7731 :then-part if-true
7732 :else-part if-false
7733 :else-pos else-pos
7734 :lp (js2-relpos (second cond) pos)
7735 :rp (js2-relpos (third cond) pos)))
7736 (js2-node-add-children pn (car cond) if-true if-false)
7737 pn))
7738
7739 (defun js2-parse-switch ()
7740 "Parser for if-statement. Last matched token must be js2-SWITCH."
7741 (let ((pos js2-token-beg)
7742 tt
7743 pn
7744 discriminant
7745 has-default
7746 case-expr
7747 case-node
7748 case-pos
7749 cases
7750 stmt
7751 lp
7752 rp)
7753 (js2-consume-token)
7754 (if (js2-must-match js2-LP "msg.no.paren.switch")
7755 (setq lp js2-token-beg))
7756 (setq discriminant (js2-parse-expr)
7757 pn (make-js2-switch-node :discriminant discriminant
7758 :pos pos
7759 :lp (js2-relpos lp pos)))
7760 (js2-node-add-children pn discriminant)
7761 (js2-enter-switch pn)
7762 (unwind-protect
7763 (progn
7764 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7765 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7766 (js2-must-match js2-LC "msg.no.brace.switch")
7767 (catch 'break
7768 (while t
7769 (setq tt (js2-next-token)
7770 case-pos js2-token-beg)
7771 (cond
7772 ((= tt js2-RC)
7773 (setf (js2-node-len pn) (- js2-token-end pos))
7774 (throw 'break nil)) ; done
7775 ((= tt js2-CASE)
7776 (setq case-expr (js2-parse-expr))
7777 (js2-must-match js2-COLON "msg.no.colon.case"))
7778 ((= tt js2-DEFAULT)
7779 (if has-default
7780 (js2-report-error "msg.double.switch.default"))
7781 (setq has-default t
7782 case-expr nil)
7783 (js2-must-match js2-COLON "msg.no.colon.case"))
7784 (t
7785 (js2-report-error "msg.bad.switch")
7786 (throw 'break nil)))
7787 (setq case-node (make-js2-case-node :pos case-pos
7788 :len (- js2-token-end case-pos)
7789 :expr case-expr))
7790 (js2-node-add-children case-node case-expr)
7791 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7792 (/= tt js2-CASE)
7793 (/= tt js2-DEFAULT)
7794 (/= tt js2-EOF))
7795 (setf stmt (js2-parse-statement)
7796 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7797 (js2-block-node-push case-node stmt))
7798 (push case-node cases)))
7799 ;; add cases last, as pushing reverses the order to be correct
7800 (dolist (kid cases)
7801 (js2-node-add-children pn kid)
7802 (push kid (js2-switch-node-cases pn)))
7803 pn) ; return value
7804 (js2-exit-switch))))
7805
7806 (defun js2-parse-while ()
7807 "Parser for while-statement. Last matched token must be js2-WHILE."
7808 (let ((pos js2-token-beg)
7809 (pn (make-js2-while-node))
7810 cond
7811 body)
7812 (js2-consume-token)
7813 (js2-enter-loop pn)
7814 (unwind-protect
7815 (progn
7816 (setf cond (js2-parse-condition)
7817 (js2-while-node-condition pn) (car cond)
7818 body (js2-parse-statement)
7819 (js2-while-node-body pn) body
7820 (js2-node-len pn) (- (js2-node-end body) pos)
7821 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7822 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7823 (js2-node-add-children pn body (car cond)))
7824 (js2-exit-loop))
7825 pn))
7826
7827 (defun js2-parse-do ()
7828 "Parser for do-statement. Last matched token must be js2-DO."
7829 (let ((pos js2-token-beg)
7830 (pn (make-js2-do-node))
7831 cond
7832 body
7833 end)
7834 (js2-consume-token)
7835 (js2-enter-loop pn)
7836 (unwind-protect
7837 (progn
7838 (setq body (js2-parse-statement))
7839 (js2-must-match js2-WHILE "msg.no.while.do")
7840 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7841 cond (js2-parse-condition)
7842 (js2-do-node-condition pn) (car cond)
7843 (js2-do-node-body pn) body
7844 end js2-ts-cursor
7845 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7846 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7847 (js2-node-add-children pn (car cond) body))
7848 (js2-exit-loop))
7849 ;; Always auto-insert semicolon to follow SpiderMonkey:
7850 ;; It is required by ECMAScript but is ignored by the rest of
7851 ;; world; see bug 238945
7852 (if (js2-match-token js2-SEMI)
7853 (setq end js2-ts-cursor))
7854 (setf (js2-node-len pn) (- end pos))
7855 pn))
7856
7857 (defun js2-parse-for ()
7858 "Parser for for-statement. Last matched token must be js2-FOR.
7859 Parses for, for-in, and for each-in statements."
7860 (let ((for-pos js2-token-beg)
7861 pn
7862 is-for-each
7863 is-for-in
7864 in-pos
7865 each-pos
7866 tmp-pos
7867 init ; Node init is also foo in 'foo in object'
7868 cond ; Node cond is also object in 'foo in object'
7869 incr ; 3rd section of for-loop initializer
7870 body
7871 tt
7872 lp
7873 rp)
7874 (js2-consume-token)
7875 ;; See if this is a for each () instead of just a for ()
7876 (when (js2-match-token js2-NAME)
7877 (if (string= "each" js2-ts-string)
7878 (progn
7879 (setq is-for-each t
7880 each-pos (- js2-token-beg for-pos)) ; relative
7881 (js2-record-face 'font-lock-keyword-face))
7882 (js2-report-error "msg.no.paren.for")))
7883 (if (js2-must-match js2-LP "msg.no.paren.for")
7884 (setq lp (- js2-token-beg for-pos)))
7885 (setq tt (js2-peek-token))
7886 ;; parse init clause
7887 (let ((js2-in-for-init t)) ; set as dynamic variable
7888 (cond
7889 ((= tt js2-SEMI)
7890 (setq init (make-js2-empty-expr-node)))
7891 ((or (= tt js2-VAR) (= tt js2-LET))
7892 (js2-consume-token)
7893 (setq init (js2-parse-variables tt js2-token-beg)))
7894 (t
7895 (setq init (js2-parse-expr)))))
7896 (if (js2-match-token js2-IN)
7897 (setq is-for-in t
7898 in-pos (- js2-token-beg for-pos)
7899 cond (js2-parse-expr)) ; object over which we're iterating
7900 ;; else ordinary for loop - parse cond and incr
7901 (js2-must-match js2-SEMI "msg.no.semi.for")
7902 (setq cond (if (= (js2-peek-token) js2-SEMI)
7903 (make-js2-empty-expr-node) ; no loop condition
7904 (js2-parse-expr)))
7905 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7906 (setq tmp-pos js2-token-end
7907 incr (if (= (js2-peek-token) js2-RP)
7908 (make-js2-empty-expr-node :pos tmp-pos)
7909 (js2-parse-expr))))
7910 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7911 (setq rp (- js2-token-beg for-pos)))
7912 (if (not is-for-in)
7913 (setq pn (make-js2-for-node :init init
7914 :condition cond
7915 :update incr
7916 :lp lp
7917 :rp rp))
7918 ;; cond could be null if 'in obj' got eaten by the init node.
7919 (if (js2-infix-node-p init)
7920 ;; it was (foo in bar) instead of (var foo in bar)
7921 (setq cond (js2-infix-node-right init)
7922 init (js2-infix-node-left init))
7923 (if (and (js2-var-decl-node-p init)
7924 (> (length (js2-var-decl-node-kids init)) 1))
7925 (js2-report-error "msg.mult.index")))
7926 (setq pn (make-js2-for-in-node :iterator init
7927 :object cond
7928 :in-pos in-pos
7929 :foreach-p is-for-each
7930 :each-pos each-pos
7931 :lp lp
7932 :rp rp)))
7933 (unwind-protect
7934 (progn
7935 (js2-enter-loop pn)
7936 ;; We have to parse the body -after- creating the loop node,
7937 ;; so that the loop node appears in the js2-loop-set, allowing
7938 ;; break/continue statements to find the enclosing loop.
7939 (setf body (js2-parse-statement)
7940 (js2-loop-node-body pn) body
7941 (js2-node-pos pn) for-pos
7942 (js2-node-len pn) (- (js2-node-end body) for-pos))
7943 (js2-node-add-children pn init cond incr body))
7944 ;; finally
7945 (js2-exit-loop))
7946 pn))
7947
7948 (defun js2-parse-try ()
7949 "Parser for try-statement. Last matched token must be js2-TRY."
7950 (let ((try-pos js2-token-beg)
7951 try-end
7952 try-block
7953 catch-blocks
7954 finally-block
7955 saw-default-catch
7956 peek
7957 var-name
7958 catch-cond
7959 catch-node
7960 guard-kwd
7961 catch-pos
7962 finally-pos
7963 pn
7964 block
7965 lp
7966 rp)
7967 (js2-consume-token)
7968 (if (/= (js2-peek-token) js2-LC)
7969 (js2-report-error "msg.no.brace.try"))
7970 (setq try-block (js2-parse-statement)
7971 try-end (js2-node-end try-block)
7972 peek (js2-peek-token))
7973 (cond
7974 ((= peek js2-CATCH)
7975 (while (js2-match-token js2-CATCH)
7976 (setq catch-pos js2-token-beg
7977 guard-kwd nil
7978 catch-cond nil
7979 lp nil
7980 rp nil)
7981 (if saw-default-catch
7982 (js2-report-error "msg.catch.unreachable"))
7983 (if (js2-must-match js2-LP "msg.no.paren.catch")
7984 (setq lp (- js2-token-beg catch-pos)))
7985 (js2-must-match js2-NAME "msg.bad.catchcond")
7986 (setq var-name (js2-create-name-node))
7987 (if (js2-match-token js2-IF)
7988 (setq guard-kwd (- js2-token-beg catch-pos)
7989 catch-cond (js2-parse-expr))
7990 (setq saw-default-catch t))
7991 (if (js2-must-match js2-RP "msg.bad.catchcond")
7992 (setq rp (- js2-token-beg catch-pos)))
7993 (js2-must-match js2-LC "msg.no.brace.catchblock")
7994 (setq block (js2-parse-statements)
7995 try-end (js2-node-end block)
7996 catch-node (make-js2-catch-node :pos catch-pos
7997 :var-name var-name
7998 :guard-expr catch-cond
7999 :guard-kwd guard-kwd
8000 :block block
8001 :lp lp
8002 :rp rp))
8003 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8004 (setq try-end js2-token-beg))
8005 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8006 (js2-node-len catch-node) (- try-end catch-pos))
8007 (js2-node-add-children catch-node var-name catch-cond block)
8008 (push catch-node catch-blocks)))
8009 ((/= peek js2-FINALLY)
8010 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8011 (js2-node-pos try-block)
8012 (- (setq try-end (js2-node-end try-block))
8013 (js2-node-pos try-block)))))
8014 (when (js2-match-token js2-FINALLY)
8015 (setq finally-pos js2-token-beg
8016 block (js2-parse-statement)
8017 try-end (js2-node-end block)
8018 finally-block (make-js2-finally-node :pos finally-pos
8019 :len (- try-end finally-pos)
8020 :body block))
8021 (js2-node-add-children finally-block block))
8022 (setq pn (make-js2-try-node :pos try-pos
8023 :len (- try-end try-pos)
8024 :try-block try-block
8025 :finally-block finally-block))
8026 (js2-node-add-children pn try-block finally-block)
8027 ;; push them onto the try-node, which reverses and corrects their order
8028 (dolist (cb catch-blocks)
8029 (js2-node-add-children pn cb)
8030 (push cb (js2-try-node-catch-clauses pn)))
8031 pn))
8032
8033 (defun js2-parse-throw ()
8034 "Parser for throw-statement. Last matched token must be js2-THROW."
8035 (let ((pos js2-token-beg)
8036 expr
8037 pn)
8038 (js2-consume-token)
8039 (if (= (js2-peek-token-or-eol) js2-EOL)
8040 ;; ECMAScript does not allow new lines before throw expression,
8041 ;; see bug 256617
8042 (js2-report-error "msg.bad.throw.eol"))
8043 (setq expr (js2-parse-expr)
8044 pn (make-js2-throw-node :pos pos
8045 :len (- (js2-node-end expr) pos)
8046 :expr expr))
8047 (js2-node-add-children pn expr)
8048 pn))
8049
8050 (defsubst js2-match-jump-label-name (label-name)
8051 "If break/continue specified a label, return that label's labeled stmt.
8052 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8053 does not match an existing label, reports an error and returns nil."
8054 (let ((bundle (cdr (assoc label-name js2-label-set))))
8055 (if (null bundle)
8056 (js2-report-error "msg.undef.label"))
8057 bundle))
8058
8059 (defun js2-parse-break ()
8060 "Parser for break-statement. Last matched token must be js2-BREAK."
8061 (let ((pos js2-token-beg)
8062 (end js2-token-end)
8063 break-target ; statement to break from
8064 break-label ; in "break foo", name-node representing the foo
8065 labels ; matching labeled statement to break to
8066 pn)
8067 (js2-consume-token) ; `break'
8068 (when (eq (js2-peek-token-or-eol) js2-NAME)
8069 (js2-consume-token)
8070 (setq break-label (js2-create-name-node)
8071 end (js2-node-end break-label)
8072 ;; matchJumpLabelName only matches if there is one
8073 labels (js2-match-jump-label-name js2-ts-string)
8074 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8075 (unless (or break-target break-label)
8076 ;; no break target specified - try for innermost enclosing loop/switch
8077 (if (null js2-loop-and-switch-set)
8078 (unless break-label
8079 (js2-report-error "msg.bad.break" nil pos (length "break")))
8080 (setq break-target (car js2-loop-and-switch-set))))
8081 (setq pn (make-js2-break-node :pos pos
8082 :len (- end pos)
8083 :label break-label
8084 :target break-target))
8085 (js2-node-add-children pn break-label) ; but not break-target
8086 pn))
8087
8088 (defun js2-parse-continue ()
8089 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8090 (let ((pos js2-token-beg)
8091 (end js2-token-end)
8092 label ; optional user-specified label, a `js2-name-node'
8093 labels ; current matching labeled stmt, if any
8094 target ; the `js2-loop-node' target of this continue stmt
8095 pn)
8096 (js2-consume-token) ; `continue'
8097 (when (= (js2-peek-token-or-eol) js2-NAME)
8098 (js2-consume-token)
8099 (setq label (js2-create-name-node)
8100 end (js2-node-end label)
8101 ;; matchJumpLabelName only matches if there is one
8102 labels (js2-match-jump-label-name js2-ts-string)))
8103 (cond
8104 ((null labels) ; no current label to go to
8105 (if (null js2-loop-set) ; no loop to continue to
8106 (js2-report-error "msg.continue.outside" nil pos
8107 (length "continue"))
8108 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8109 (t
8110 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8111 (setq target (js2-labeled-stmt-node-stmt labels))
8112 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8113 (setq pn (make-js2-continue-node :pos pos
8114 :len (- end pos)
8115 :label label
8116 :target target))
8117 (js2-node-add-children pn label) ; but not target - it's not our child
8118 pn))
8119
8120 (defun js2-parse-with ()
8121 "Parser for with-statement. Last matched token must be js2-WITH."
8122 (js2-consume-token)
8123 (let ((pos js2-token-beg)
8124 obj body pn lp rp)
8125 (if (js2-must-match js2-LP "msg.no.paren.with")
8126 (setq lp js2-token-beg))
8127 (setq obj (js2-parse-expr))
8128 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8129 (setq rp js2-token-beg))
8130 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8131 (setq body (js2-parse-statement)))
8132 (setq pn (make-js2-with-node :pos pos
8133 :len (- (js2-node-end body) pos)
8134 :object obj
8135 :body body
8136 :lp (js2-relpos lp pos)
8137 :rp (js2-relpos rp pos)))
8138 (js2-node-add-children pn obj body)
8139 pn))
8140
8141 (defun js2-parse-const-var ()
8142 "Parser for var- or const-statement.
8143 Last matched token must be js2-CONST or js2-VAR."
8144 (let ((tt (js2-peek-token))
8145 (pos js2-token-beg)
8146 expr
8147 pn)
8148 (js2-consume-token)
8149 (setq expr (js2-parse-variables tt js2-token-beg)
8150 pn (make-js2-expr-stmt-node :pos pos
8151 :len (- (js2-node-end expr) pos)
8152 :expr expr))
8153 (js2-node-add-children pn expr)
8154 pn))
8155
8156 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8157 (let ((pn (make-js2-expr-stmt-node :pos pos
8158 :len (js2-node-len expr)
8159 :type (if (js2-inside-function)
8160 js2-EXPR_VOID
8161 js2-EXPR_RESULT)
8162 :expr expr)))
8163 (if add-child
8164 (js2-node-add-children pn expr))
8165 pn))
8166
8167 (defun js2-parse-let-stmt ()
8168 "Parser for let-statement. Last matched token must be js2-LET."
8169 (js2-consume-token)
8170 (let ((pos js2-token-beg)
8171 expr
8172 pn)
8173 (if (= (js2-peek-token) js2-LP)
8174 ;; let expression in statement context
8175 (setq expr (js2-parse-let pos 'statement)
8176 pn (js2-wrap-with-expr-stmt pos expr t))
8177 ;; else we're looking at a statement like let x=6, y=7;
8178 (setf expr (js2-parse-variables js2-LET pos)
8179 pn (js2-wrap-with-expr-stmt pos expr t)
8180 (js2-node-type pn) js2-EXPR_RESULT))
8181 pn))
8182
8183 (defun js2-parse-ret-yield ()
8184 (js2-parse-return-or-yield (js2-peek-token) nil))
8185
8186 (defconst js2-parse-return-stmt-enders
8187 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8188
8189 (defsubst js2-now-all-set (before after mask)
8190 "Return whether or not the bits in the mask have changed to all set.
8191 BEFORE is bits before change, AFTER is bits after change, and MASK is
8192 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8193 but not BEFORE."
8194 (and (/= (logand before mask) mask)
8195 (= (logand after mask) mask)))
8196
8197 (defun js2-parse-return-or-yield (tt expr-context)
8198 (let ((pos js2-token-beg)
8199 (end js2-token-end)
8200 (before js2-end-flags)
8201 (inside-function (js2-inside-function))
8202 e
8203 ret
8204 name)
8205 (unless inside-function
8206 (js2-report-error (if (eq tt js2-RETURN)
8207 "msg.bad.return"
8208 "msg.bad.yield")))
8209 (js2-consume-token)
8210 ;; This is ugly, but we don't want to require a semicolon.
8211 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8212 (setq e (js2-parse-expr)
8213 end (js2-node-end e)))
8214 (cond
8215 ((eq tt js2-RETURN)
8216 (js2-set-flag js2-end-flags (if (null e)
8217 js2-end-returns
8218 js2-end-returns-value))
8219 (setq ret (make-js2-return-node :pos pos
8220 :len (- end pos)
8221 :retval e))
8222 (js2-node-add-children ret e)
8223 ;; See if we need a strict mode warning.
8224 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8225 ;; more thorough and accurate than this before/after flag check.
8226 ;; E.g. if there's a finally-block that always returns, we shouldn't
8227 ;; show a warning generated by inconsistent returns in the catch blocks.
8228 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8229 ;; so we know which returns/yields to highlight, and we should get rid of
8230 ;; all the checking in `js2-parse-return-or-yield'.
8231 (if (and js2-strict-inconsistent-return-warning
8232 (js2-now-all-set before js2-end-flags
8233 (logior js2-end-returns js2-end-returns-value)))
8234 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8235 (t
8236 (unless (js2-inside-function)
8237 (js2-report-error "msg.bad.yield"))
8238 (js2-set-flag js2-end-flags js2-end-yields)
8239 (setq ret (make-js2-yield-node :pos pos
8240 :len (- end pos)
8241 :value e))
8242 (js2-node-add-children ret e)
8243 (unless expr-context
8244 (setq e ret
8245 ret (js2-wrap-with-expr-stmt pos e t))
8246 (js2-set-requires-activation)
8247 (js2-set-is-generator))))
8248 ;; see if we are mixing yields and value returns.
8249 (when (and inside-function
8250 (js2-now-all-set before js2-end-flags
8251 (logior js2-end-yields js2-end-returns-value)))
8252 (setq name (js2-function-name js2-current-script-or-fn))
8253 (if (zerop (length name))
8254 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8255 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8256 ret))
8257
8258 (defun js2-parse-debugger ()
8259 (js2-consume-token)
8260 (make-js2-keyword-node :type js2-DEBUGGER))
8261
8262 (defun js2-parse-block ()
8263 "Parser for a curly-delimited statement block.
8264 Last token matched must be js2-LC."
8265 (let ((pos js2-token-beg)
8266 (pn (make-js2-scope)))
8267 (js2-consume-token)
8268 (js2-push-scope pn)
8269 (unwind-protect
8270 (progn
8271 (js2-parse-statements pn)
8272 (js2-must-match js2-RC "msg.no.brace.block")
8273 (setf (js2-node-len pn) (- js2-token-end pos)))
8274 (js2-pop-scope))
8275 pn))
8276
8277 ;; for js2-ERROR too, to have a node for error recovery to work on
8278 (defun js2-parse-semi ()
8279 "Parse a statement or handle an error.
8280 Last matched token is js-SEMI or js-ERROR."
8281 (let ((tt (js2-peek-token)) pos len)
8282 (js2-consume-token)
8283 (if (eq tt js2-SEMI)
8284 (make-js2-empty-expr-node :len 1)
8285 (setq pos js2-token-beg
8286 len (- js2-token-beg pos))
8287 (js2-report-error "msg.syntax" nil pos len)
8288 (make-js2-error-node :pos pos :len len))))
8289
8290 (defun js2-parse-default-xml-namespace ()
8291 "Parse a `default xml namespace = <expr>' e4x statement."
8292 (let ((pos js2-token-beg)
8293 end len expr unary es)
8294 (js2-consume-token)
8295 (js2-must-have-xml)
8296 (js2-set-requires-activation)
8297 (setq len (- js2-ts-cursor pos))
8298 (unless (and (js2-match-token js2-NAME)
8299 (string= js2-ts-string "xml"))
8300 (js2-report-error "msg.bad.namespace" nil pos len))
8301 (unless (and (js2-match-token js2-NAME)
8302 (string= js2-ts-string "namespace"))
8303 (js2-report-error "msg.bad.namespace" nil pos len))
8304 (unless (js2-match-token js2-ASSIGN)
8305 (js2-report-error "msg.bad.namespace" nil pos len))
8306 (setq expr (js2-parse-expr)
8307 end (js2-node-end expr)
8308 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8309 :pos pos
8310 :len (- end pos)
8311 :operand expr))
8312 (js2-node-add-children unary expr)
8313 (make-js2-expr-stmt-node :pos pos
8314 :len (- end pos)
8315 :expr unary)))
8316
8317 (defun js2-record-label (label bundle)
8318 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8319 (js2-consume-token)
8320 (let ((name (js2-label-node-name label))
8321 labeled-stmt
8322 dup)
8323 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8324 ;; flag both labels if possible when used in editing mode
8325 (if (and js2-parse-ide-mode
8326 (setq dup (js2-get-label-by-name labeled-stmt name)))
8327 (js2-report-error "msg.dup.label" nil
8328 (js2-node-abs-pos dup) (js2-node-len dup)))
8329 (js2-report-error "msg.dup.label" nil
8330 (js2-node-pos label) (js2-node-len label)))
8331 (js2-labeled-stmt-node-add-label bundle label)
8332 (js2-node-add-children bundle label)
8333 ;; Add one reference to the bundle per label in `js2-label-set'
8334 (push (cons name bundle) js2-label-set)))
8335
8336 (defun js2-parse-name-or-label ()
8337 "Parser for identifier or label. Last token matched must be js2-NAME.
8338 Called when we found a name in a statement context. If it's a label, we gather
8339 up any following labels and the next non-label statement into a
8340 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8341 expression and return it wrapped in a `js2-expr-stmt-node'."
8342 (let ((pos js2-token-beg)
8343 (end js2-token-end)
8344 expr
8345 stmt
8346 pn
8347 bundle
8348 (continue t))
8349 ;; set check for label and call down to `js2-parse-primary-expr'
8350 (js2-set-check-for-label)
8351 (setq expr (js2-parse-expr))
8352 (if (/= (js2-node-type expr) js2-LABEL)
8353 ;; Parsed non-label expression - wrap with expression stmt.
8354 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8355 ;; else parsed a label
8356 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8357 (js2-record-label expr bundle)
8358 ;; look for more labels
8359 (while (and continue (= (js2-peek-token) js2-NAME))
8360 (js2-set-check-for-label)
8361 (setq expr (js2-parse-expr))
8362 (if (/= (js2-node-type expr) js2-LABEL)
8363 (progn
8364 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8365 continue nil)
8366 (js2-auto-insert-semicolon stmt))
8367 (js2-record-label expr bundle)))
8368 ;; no more labels; now parse the labeled statement
8369 (unwind-protect
8370 (unless stmt
8371 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8372 (setq stmt (js2-statement-helper))))
8373 ;; remove the labels for this statement from the global set
8374 (dolist (label (js2-labeled-stmt-node-labels bundle))
8375 (setq js2-label-set (remove label js2-label-set))))
8376 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8377 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8378 (js2-node-add-children bundle stmt)
8379 bundle)))
8380
8381 (defun js2-parse-expr-stmt ()
8382 "Default parser in statement context, if no recognized statement found."
8383 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8384
8385 (defun js2-parse-variables (decl-type pos)
8386 "Parse a comma-separated list of variable declarations.
8387 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8388
8389 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8390 For 'var' or 'const', the keyword should be the token last scanned.
8391
8392 POS is the position where the node should start. It's sometimes the
8393 var/const/let keyword, and other times the beginning of the first token
8394 in the first variable declaration.
8395
8396 Returns the parsed `js2-var-decl-node' expression node."
8397 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8398 :pos pos))
8399 destructuring
8400 kid-pos
8401 tt
8402 init
8403 name
8404 end
8405 nbeg nend
8406 vi
8407 (continue t))
8408 ;; Example:
8409 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8410 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8411 ;; var {a, b} = baz;
8412 (while continue
8413 (setq destructuring nil
8414 name nil
8415 tt (js2-peek-token)
8416 kid-pos js2-token-beg
8417 end js2-token-end
8418 init nil)
8419 (if (or (= tt js2-LB) (= tt js2-LC))
8420 ;; Destructuring assignment, e.g., var [a, b] = ...
8421 (setq destructuring (js2-parse-primary-expr-lhs)
8422 end (js2-node-end destructuring))
8423 ;; Simple variable name
8424 (when (js2-must-match js2-NAME "msg.bad.var")
8425 (setq name (js2-create-name-node)
8426 nbeg js2-token-beg
8427 nend js2-token-end
8428 end nend)
8429 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8430 (when (js2-match-token js2-ASSIGN)
8431 (setq init (js2-parse-assign-expr)
8432 end (js2-node-end init))
8433 (if (and js2-parse-ide-mode
8434 (or (js2-object-node-p init)
8435 (js2-function-node-p init)))
8436 (js2-record-imenu-functions init name)))
8437 (when name
8438 (js2-set-face nbeg nend (if (js2-function-node-p init)
8439 'font-lock-function-name-face
8440 'font-lock-variable-name-face)
8441 'record))
8442 (setq vi (make-js2-var-init-node :pos kid-pos
8443 :len (- end kid-pos)
8444 :type decl-type))
8445 (if destructuring
8446 (progn
8447 (if (and (null init) (not js2-in-for-init))
8448 (js2-report-error "msg.destruct.assign.no.init"))
8449 (js2-define-destruct-symbols destructuring
8450 decl-type
8451 'font-lock-variable-name-face)
8452 (setf (js2-var-init-node-target vi) destructuring))
8453 (setf (js2-var-init-node-target vi) name))
8454 (setf (js2-var-init-node-initializer vi) init)
8455 (js2-node-add-children vi name destructuring init)
8456 (js2-block-node-push result vi)
8457 (unless (js2-match-token js2-COMMA)
8458 (setq continue nil)))
8459 (setf (js2-node-len result) (- end pos))
8460 result))
8461
8462 (defun js2-parse-let (pos &optional stmt-p)
8463 "Parse a let expression or statement.
8464 A let-expression is of the form `let (vars) expr'.
8465 A let-statment is of the form `let (vars) {statements}'.
8466 The third form of let is a variable declaration list, handled
8467 by `js2-parse-variables'."
8468 (let ((pn (make-js2-let-node :pos pos))
8469 beg vars body)
8470 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8471 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8472 (js2-push-scope pn)
8473 (unwind-protect
8474 (progn
8475 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8476 (if (js2-must-match js2-RP "msg.no.paren.let")
8477 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8478 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8479 ;; let statement
8480 (progn
8481 (js2-consume-token)
8482 (setf beg js2-token-beg ; position stmt at LC
8483 body (js2-parse-statements))
8484 (js2-must-match js2-RC "msg.no.curly.let")
8485 (setf (js2-node-len body) (- js2-token-end beg)
8486 (js2-node-len pn) (- js2-token-end pos)
8487 (js2-let-node-body pn) body
8488 (js2-node-type pn) js2-LET))
8489 ;; let expression
8490 (setf body (js2-parse-expr)
8491 (js2-node-len pn) (- (js2-node-end body) pos)
8492 (js2-let-node-body pn) body))
8493 (js2-node-add-children pn vars body))
8494 (js2-pop-scope))
8495 pn))
8496
8497 (defsubst js2-define-new-symbol (decl-type name node)
8498 (js2-scope-put-symbol js2-current-scope
8499 name
8500 (make-js2-symbol decl-type name node)))
8501
8502 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8503 "Define a symbol in the current scope.
8504 If NODE is non-nil, it is the AST node associated with the symbol."
8505 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8506 (symbol (if defining-scope
8507 (js2-scope-get-symbol defining-scope name)))
8508 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8509 (cond
8510 ((and symbol ; already defined
8511 (or (= sdt js2-CONST) ; old version is const
8512 (= decl-type js2-CONST) ; new version is const
8513 ;; two let-bound vars in this block have same name
8514 (and (= sdt js2-LET)
8515 (eq defining-scope js2-current-scope))))
8516 (js2-report-error
8517 (cond
8518 ((= sdt js2-CONST) "msg.const.redecl")
8519 ((= sdt js2-LET) "msg.let.redecl")
8520 ((= sdt js2-VAR) "msg.var.redecl")
8521 ((= sdt js2-FUNCTION) "msg.function.redecl")
8522 (t "msg.parm.redecl"))
8523 name))
8524 ((= decl-type js2-LET)
8525 (if (and (not ignore-not-in-block)
8526 (or (= (js2-node-type js2-current-scope) js2-IF)
8527 (js2-loop-node-p js2-current-scope)))
8528 (js2-report-error "msg.let.decl.not.in.block")
8529 (js2-define-new-symbol decl-type name node)))
8530 ((or (= decl-type js2-VAR)
8531 (= decl-type js2-CONST)
8532 (= decl-type js2-FUNCTION))
8533 (if symbol
8534 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8535 (js2-add-strict-warning "msg.var.redecl" name)
8536 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8537 (js2-add-strict-warning "msg.var.hides.arg" name)))
8538 (js2-define-new-symbol decl-type name node)))
8539 ((= decl-type js2-LP)
8540 (if symbol
8541 ;; must be duplicate parameter. Second parameter hides the
8542 ;; first, so go ahead and add the second pararameter
8543 (js2-report-warning "msg.dup.parms" name))
8544 (js2-define-new-symbol decl-type name node))
8545 (t (js2-code-bug)))))
8546
8547 (defun js2-parse-expr (&optional oneshot)
8548 (let* ((pn (js2-parse-assign-expr))
8549 (pos (js2-node-pos pn))
8550 left
8551 right
8552 op-pos)
8553 (while (and (not oneshot)
8554 (js2-match-token js2-COMMA))
8555 (setq op-pos (- js2-token-beg pos)) ; relative
8556 (if (= (js2-peek-token) js2-YIELD)
8557 (js2-report-error "msg.yield.parenthesized"))
8558 (setq right (js2-parse-assign-expr)
8559 left pn
8560 pn (make-js2-infix-node :type js2-COMMA
8561 :pos pos
8562 :len (- js2-ts-cursor pos)
8563 :op-pos op-pos
8564 :left left
8565 :right right))
8566 (js2-node-add-children pn left right))
8567 pn))
8568
8569 (defun js2-parse-assign-expr ()
8570 (let ((tt (js2-peek-token))
8571 (pos js2-token-beg)
8572 pn
8573 left
8574 right
8575 op-pos)
8576 (if (= tt js2-YIELD)
8577 (js2-parse-return-or-yield tt t)
8578 ;; not yield - parse assignment expression
8579 (setq pn (js2-parse-cond-expr)
8580 tt (js2-peek-token))
8581 (when (and (<= js2-first-assign tt)
8582 (<= tt js2-last-assign))
8583 ;; tt express assignment (=, |=, ^=, ..., %=)
8584 (js2-consume-token)
8585 (setq op-pos (- js2-token-beg pos) ; relative
8586 left pn
8587 right (js2-parse-assign-expr)
8588 pn (make-js2-assign-node :type tt
8589 :pos pos
8590 :len (- (js2-node-end right) pos)
8591 :op-pos op-pos
8592 :left left
8593 :right right))
8594 (when js2-parse-ide-mode
8595 (js2-highlight-assign-targets pn left right)
8596 (if (or (js2-function-node-p right)
8597 (js2-object-node-p right))
8598 (js2-record-imenu-functions right left)))
8599 ;; do this last so ide checks above can use absolute positions
8600 (js2-node-add-children pn left right))
8601 pn)))
8602
8603 (defun js2-parse-cond-expr ()
8604 (let ((pos js2-token-beg)
8605 (pn (js2-parse-or-expr))
8606 test-expr
8607 if-true
8608 if-false
8609 q-pos
8610 c-pos)
8611 (when (js2-match-token js2-HOOK)
8612 (setq q-pos (- js2-token-beg pos)
8613 if-true (js2-parse-assign-expr))
8614 (js2-must-match js2-COLON "msg.no.colon.cond")
8615 (setq c-pos (- js2-token-beg pos)
8616 if-false (js2-parse-assign-expr)
8617 test-expr pn
8618 pn (make-js2-cond-node :pos pos
8619 :len (- (js2-node-end if-false) pos)
8620 :test-expr test-expr
8621 :true-expr if-true
8622 :false-expr if-false
8623 :q-pos q-pos
8624 :c-pos c-pos))
8625 (js2-node-add-children pn test-expr if-true if-false))
8626 pn))
8627
8628 (defun js2-make-binary (type left parser)
8629 "Helper for constructing a binary-operator AST node.
8630 LEFT is the left-side-expression, already parsed, and the
8631 binary operator should have just been matched.
8632 PARSER is a function to call to parse the right operand,
8633 or a `js2-node' struct if it has already been parsed."
8634 (let* ((pos (js2-node-pos left))
8635 (op-pos (- js2-token-beg pos))
8636 (right (if (js2-node-p parser)
8637 parser
8638 (funcall parser)))
8639 (pn (make-js2-infix-node :type type
8640 :pos pos
8641 :len (- (js2-node-end right) pos)
8642 :op-pos op-pos
8643 :left left
8644 :right right)))
8645 (js2-node-add-children pn left right)
8646 pn))
8647
8648 (defun js2-parse-or-expr ()
8649 (let ((pn (js2-parse-and-expr)))
8650 (when (js2-match-token js2-OR)
8651 (setq pn (js2-make-binary js2-OR
8652 pn
8653 'js2-parse-or-expr)))
8654 pn))
8655
8656 (defun js2-parse-and-expr ()
8657 (let ((pn (js2-parse-bit-or-expr)))
8658 (when (js2-match-token js2-AND)
8659 (setq pn (js2-make-binary js2-AND
8660 pn
8661 'js2-parse-and-expr)))
8662 pn))
8663
8664 (defun js2-parse-bit-or-expr ()
8665 (let ((pn (js2-parse-bit-xor-expr)))
8666 (while (js2-match-token js2-BITOR)
8667 (setq pn (js2-make-binary js2-BITOR
8668 pn
8669 'js2-parse-bit-xor-expr)))
8670 pn))
8671
8672 (defun js2-parse-bit-xor-expr ()
8673 (let ((pn (js2-parse-bit-and-expr)))
8674 (while (js2-match-token js2-BITXOR)
8675 (setq pn (js2-make-binary js2-BITXOR
8676 pn
8677 'js2-parse-bit-and-expr)))
8678 pn))
8679
8680 (defun js2-parse-bit-and-expr ()
8681 (let ((pn (js2-parse-eq-expr)))
8682 (while (js2-match-token js2-BITAND)
8683 (setq pn (js2-make-binary js2-BITAND
8684 pn
8685 'js2-parse-eq-expr)))
8686 pn))
8687
8688 (defconst js2-parse-eq-ops
8689 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8690
8691 (defun js2-parse-eq-expr ()
8692 (let ((pn (js2-parse-rel-expr))
8693 tt)
8694 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8695 (js2-consume-token)
8696 (setq pn (js2-make-binary tt
8697 pn
8698 'js2-parse-rel-expr)))
8699 pn))
8700
8701 (defconst js2-parse-rel-ops
8702 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8703
8704 (defun js2-parse-rel-expr ()
8705 (let ((pn (js2-parse-shift-expr))
8706 (continue t)
8707 tt)
8708 (while continue
8709 (setq tt (js2-peek-token))
8710 (cond
8711 ((and js2-in-for-init (= tt js2-IN))
8712 (setq continue nil))
8713 ((memq tt js2-parse-rel-ops)
8714 (js2-consume-token)
8715 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8716 (t
8717 (setq continue nil))))
8718 pn))
8719
8720 (defconst js2-parse-shift-ops
8721 (list js2-LSH js2-URSH js2-RSH))
8722
8723 (defun js2-parse-shift-expr ()
8724 (let ((pn (js2-parse-add-expr))
8725 tt
8726 (continue t))
8727 (while continue
8728 (setq tt (js2-peek-token))
8729 (if (memq tt js2-parse-shift-ops)
8730 (progn
8731 (js2-consume-token)
8732 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8733 (setq continue nil)))
8734 pn))
8735
8736 (defun js2-parse-add-expr ()
8737 (let ((pn (js2-parse-mul-expr))
8738 tt
8739 (continue t))
8740 (while continue
8741 (setq tt (js2-peek-token))
8742 (if (or (= tt js2-ADD) (= tt js2-SUB))
8743 (progn
8744 (js2-consume-token)
8745 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8746 (setq continue nil)))
8747 pn))
8748
8749 (defconst js2-parse-mul-ops
8750 (list js2-MUL js2-DIV js2-MOD))
8751
8752 (defun js2-parse-mul-expr ()
8753 (let ((pn (js2-parse-unary-expr))
8754 tt
8755 (continue t))
8756 (while continue
8757 (setq tt (js2-peek-token))
8758 (if (memq tt js2-parse-mul-ops)
8759 (progn
8760 (js2-consume-token)
8761 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8762 (setq continue nil)))
8763 pn))
8764
8765 (defsubst js2-make-unary (type parser &rest args)
8766 "Make a unary node of type TYPE.
8767 PARSER is either a node (for postfix operators) or a function to call
8768 to parse the operand (for prefix operators)."
8769 (let* ((pos js2-token-beg)
8770 (postfix (js2-node-p parser))
8771 (expr (if postfix
8772 parser
8773 (apply parser args)))
8774 end
8775 pn)
8776 (if postfix ; e.g. i++
8777 (setq pos (js2-node-pos expr)
8778 end js2-token-end)
8779 (setq end (js2-node-end expr)))
8780 (setq pn (make-js2-unary-node :type type
8781 :pos pos
8782 :len (- end pos)
8783 :operand expr))
8784 (js2-node-add-children pn expr)
8785 pn))
8786
8787 (defconst js2-incrementable-node-types
8788 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8789 "Node types that can be the operand of a ++ or -- operator.")
8790
8791 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8792 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8793 js2-incrementable-node-types)
8794 (js2-report-error (if (= tt js2-INC)
8795 "msg.bad.incr"
8796 "msg.bad.decr")
8797 nil beg (- end beg))))
8798
8799 (defun js2-parse-unary-expr ()
8800 (let ((tt (js2-peek-token))
8801 pn expr beg end)
8802 (cond
8803 ((or (= tt js2-VOID)
8804 (= tt js2-NOT)
8805 (= tt js2-BITNOT)
8806 (= tt js2-TYPEOF))
8807 (js2-consume-token)
8808 (js2-make-unary tt 'js2-parse-unary-expr))
8809 ((= tt js2-ADD)
8810 (js2-consume-token)
8811 ;; Convert to special POS token in decompiler and parse tree
8812 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8813 ((= tt js2-SUB)
8814 (js2-consume-token)
8815 ;; Convert to special NEG token in decompiler and parse tree
8816 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8817 ((or (= tt js2-INC)
8818 (= tt js2-DEC))
8819 (js2-consume-token)
8820 (prog1
8821 (setq beg js2-token-beg
8822 end js2-token-end
8823 expr (js2-make-unary tt 'js2-parse-member-expr t))
8824 (js2-check-bad-inc-dec tt beg end expr)))
8825 ((= tt js2-DELPROP)
8826 (js2-consume-token)
8827 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8828 ((= tt js2-ERROR)
8829 (js2-consume-token)
8830 (make-js2-error-node)) ; try to continue
8831 ((and (= tt js2-LT)
8832 js2-compiler-xml-available)
8833 ;; XML stream encountered in expression.
8834 (js2-consume-token)
8835 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8836 (t
8837 (setq pn (js2-parse-member-expr t)
8838 ;; Don't look across a newline boundary for a postfix incop.
8839 tt (js2-peek-token-or-eol))
8840 (when (or (= tt js2-INC) (= tt js2-DEC))
8841 (js2-consume-token)
8842 (setf expr pn
8843 pn (js2-make-unary tt expr))
8844 (js2-node-set-prop pn 'postfix t)
8845 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8846 pn))))
8847
8848 (defun js2-parse-xml-initializer ()
8849 "Parse an E4X XML initializer.
8850 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8851 Then I'll postprocess the result, depending on whether we're in IDE
8852 mode or codegen mode, and generate the appropriate rewritten AST.
8853 IDE mode uses a rich AST that models the XML structure. Codegen mode
8854 just concatenates everything and makes a new XML or XMLList out of it."
8855 (let ((tt (js2-get-first-xml-token))
8856 pn-xml
8857 pn
8858 expr
8859 kids
8860 expr-pos
8861 (continue t)
8862 (first-token t))
8863 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8864 (js2-report-error "msg.syntax"))
8865 (setq pn-xml (make-js2-xml-node))
8866 (while continue
8867 (if first-token
8868 (setq first-token nil)
8869 (setq tt (js2-get-next-xml-token)))
8870 (cond
8871 ;; js2-XML means we found a {expr} in the XML stream.
8872 ;; The js2-ts-string is the XML up to the left-curly.
8873 ((= tt js2-XML)
8874 (push (make-js2-string-node :pos js2-token-beg
8875 :len (- js2-ts-cursor js2-token-beg))
8876 kids)
8877 (js2-must-match js2-LC "msg.syntax")
8878 (setq expr-pos js2-ts-cursor
8879 expr (if (eq (js2-peek-token) js2-RC)
8880 (make-js2-empty-expr-node :pos expr-pos)
8881 (js2-parse-expr)))
8882 (js2-must-match js2-RC "msg.syntax")
8883 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8884 :len (js2-node-len expr)
8885 :expr expr))
8886 (js2-node-add-children pn expr)
8887 (push pn kids))
8888 ;; a js2-XMLEND token means we hit the final close-tag.
8889 ((= tt js2-XMLEND)
8890 (push (make-js2-string-node :pos js2-token-beg
8891 :len (- js2-ts-cursor js2-token-beg))
8892 kids)
8893 (dolist (kid (nreverse kids))
8894 (js2-block-node-push pn-xml kid))
8895 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8896 (js2-node-pos pn-xml))
8897 continue nil))
8898 (t
8899 (js2-report-error "msg.syntax")
8900 (setq continue nil))))
8901 pn-xml))
8902
8903
8904 (defun js2-parse-argument-list ()
8905 "Parse an argument list and return it as a lisp list of nodes.
8906 Returns the list in reverse order. Consumes the right-paren token."
8907 (let (result)
8908 (unless (js2-match-token js2-RP)
8909 (loop do
8910 (if (= (js2-peek-token) js2-YIELD)
8911 (js2-report-error "msg.yield.parenthesized"))
8912 (push (js2-parse-assign-expr) result)
8913 while
8914 (js2-match-token js2-COMMA))
8915 (js2-must-match js2-RP "msg.no.paren.arg")
8916 result)))
8917
8918 (defun js2-parse-member-expr (&optional allow-call-syntax)
8919 (let ((tt (js2-peek-token))
8920 pn
8921 pos
8922 target
8923 args
8924 beg
8925 end
8926 init
8927 tail)
8928 (if (/= tt js2-NEW)
8929 (setq pn (js2-parse-primary-expr))
8930 ;; parse a 'new' expression
8931 (js2-consume-token)
8932 (setq pos js2-token-beg
8933 beg pos
8934 target (js2-parse-member-expr)
8935 end (js2-node-end target)
8936 pn (make-js2-new-node :pos pos
8937 :target target
8938 :len (- end pos)))
8939 (js2-node-add-children pn target)
8940 (when (js2-match-token js2-LP)
8941 ;; Add the arguments to pn, if any are supplied.
8942 (setf beg pos ; start of "new" keyword
8943 pos js2-token-beg
8944 args (nreverse (js2-parse-argument-list))
8945 (js2-new-node-args pn) args
8946 end js2-token-end
8947 (js2-new-node-lp pn) (- pos beg)
8948 (js2-new-node-rp pn) (- end 1 beg))
8949 (apply #'js2-node-add-children pn args))
8950 (when (and js2-allow-rhino-new-expr-initializer
8951 (js2-match-token js2-LC))
8952 (setf init (js2-parse-object-literal)
8953 end (js2-node-end init)
8954 (js2-new-node-initializer pn) init)
8955 (js2-node-add-children pn init))
8956 (setf (js2-node-len pn) (- end beg))) ; end outer if
8957 (js2-parse-member-expr-tail allow-call-syntax pn)))
8958
8959 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8960 "Parse a chain of property/array accesses or function calls.
8961 Includes parsing for E4X operators like `..' and `.@'.
8962 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8963 Returns an expression tree that includes PN, the parent node."
8964 (let ((beg (js2-node-pos pn))
8965 tt
8966 (continue t))
8967 (while continue
8968 (setq tt (js2-peek-token))
8969 (cond
8970 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8971 (setq pn (js2-parse-property-access tt pn)))
8972 ((= tt js2-DOTQUERY)
8973 (setq pn (js2-parse-dot-query pn)))
8974 ((= tt js2-LB)
8975 (setq pn (js2-parse-element-get pn)))
8976 ((= tt js2-LP)
8977 (if allow-call-syntax
8978 (setq pn (js2-parse-function-call pn))
8979 (setq continue nil)))
8980 (t
8981 (setq continue nil))))
8982 (if (>= js2-highlight-level 2)
8983 (js2-parse-highlight-member-expr-node pn))
8984 pn))
8985
8986 (defun js2-parse-dot-query (pn)
8987 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8988 Last token parsed must be `js2-DOTQUERY'."
8989 (let ((pos (js2-node-pos pn))
8990 op-pos
8991 expr
8992 end)
8993 (js2-consume-token)
8994 (js2-must-have-xml)
8995 (js2-set-requires-activation)
8996 (setq op-pos js2-token-beg
8997 expr (js2-parse-expr)
8998 end (js2-node-end expr)
8999 pn (make-js2-xml-dot-query-node :left pn
9000 :pos pos
9001 :op-pos op-pos
9002 :right expr))
9003 (js2-node-add-children pn
9004 (js2-xml-dot-query-node-left pn)
9005 (js2-xml-dot-query-node-right pn))
9006 (if (js2-must-match js2-RP "msg.no.paren")
9007 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9008 end js2-token-end))
9009 (setf (js2-node-len pn) (- end pos))
9010 pn))
9011
9012 (defun js2-parse-element-get (pn)
9013 "Parse an element-get expression, e.g. foo[bar].
9014 Last token parsed must be `js2-RB'."
9015 (let ((lb js2-token-beg)
9016 (pos (js2-node-pos pn))
9017 rb
9018 expr)
9019 (js2-consume-token)
9020 (setq expr (js2-parse-expr))
9021 (if (js2-must-match js2-RB "msg.no.bracket.index")
9022 (setq rb js2-token-beg))
9023 (setq pn (make-js2-elem-get-node :target pn
9024 :pos pos
9025 :element expr
9026 :lb (js2-relpos lb pos)
9027 :rb (js2-relpos rb pos)
9028 :len (- js2-token-end pos)))
9029 (js2-node-add-children pn
9030 (js2-elem-get-node-target pn)
9031 (js2-elem-get-node-element pn))
9032 pn))
9033
9034 (defun js2-parse-function-call (pn)
9035 (let (args
9036 (pos (js2-node-pos pn)))
9037 (js2-consume-token)
9038 (setq pn (make-js2-call-node :pos pos
9039 :target pn
9040 :lp (- js2-token-beg pos)))
9041 (js2-node-add-children pn (js2-call-node-target pn))
9042 ;; Add the arguments to pn, if any are supplied.
9043 (setf args (nreverse (js2-parse-argument-list))
9044 (js2-call-node-rp pn) (- js2-token-beg pos)
9045 (js2-call-node-args pn) args)
9046 (apply #'js2-node-add-children pn args)
9047 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9048 pn))
9049
9050 (defun js2-parse-property-access (tt pn)
9051 "Parse a property access, XML descendants access, or XML attr access."
9052 (let ((member-type-flags 0)
9053 (dot-pos js2-token-beg)
9054 (dot-len (if (= tt js2-DOTDOT) 2 1))
9055 name
9056 ref ; right side of . or .. operator
9057 result)
9058 (js2-consume-token)
9059 (when (= tt js2-DOTDOT)
9060 (js2-must-have-xml)
9061 (setq member-type-flags js2-descendants-flag))
9062 (if (not js2-compiler-xml-available)
9063 (progn
9064 (js2-must-match-prop-name "msg.no.name.after.dot")
9065 (setq name (js2-create-name-node t js2-GETPROP)
9066 result (make-js2-prop-get-node :left pn
9067 :pos js2-token-beg
9068 :right name
9069 :len (- js2-token-end
9070 js2-token-beg)))
9071 (js2-node-add-children result pn name)
9072 result)
9073 ;; otherwise look for XML operators
9074 (setf result (if (= tt js2-DOT)
9075 (make-js2-prop-get-node)
9076 (make-js2-infix-node :type js2-DOTDOT))
9077 (js2-node-pos result) (js2-node-pos pn)
9078 (js2-infix-node-op-pos result) dot-pos
9079 (js2-infix-node-left result) pn ; do this after setting position
9080 tt (js2-next-token))
9081 (cond
9082 ;; needed for generator.throw()
9083 ((= tt js2-THROW)
9084 (js2-save-name-token-data js2-token-beg "throw")
9085 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9086 ;; handles: name, ns::name, ns::*, ns::[expr]
9087 ((js2-valid-prop-name-token tt)
9088 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9089 ;; handles: *, *::name, *::*, *::[expr]
9090 ((= tt js2-MUL)
9091 (js2-save-name-token-data js2-token-beg "*")
9092 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9093 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9094 ((= tt js2-XMLATTR)
9095 (setq result (js2-parse-attribute-access)))
9096 (t
9097 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9098 (if ref
9099 (setf (js2-node-len result) (- (js2-node-end ref)
9100 (js2-node-pos result))
9101 (js2-infix-node-right result) ref))
9102 (if (js2-infix-node-p result)
9103 (js2-node-add-children result
9104 (js2-infix-node-left result)
9105 (js2-infix-node-right result)))
9106 result)))
9107
9108 (defun js2-parse-attribute-access ()
9109 "Parse an E4X XML attribute expression.
9110 This includes expressions of the forms:
9111
9112 @attr @ns::attr @ns::*
9113 @* @*::attr @*::*
9114 @[expr] @*::[expr] @ns::[expr]
9115
9116 Called if we peeked an '@' token."
9117 (let ((tt (js2-next-token))
9118 (at-pos js2-token-beg))
9119 (cond
9120 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9121 ((js2-valid-prop-name-token tt)
9122 (js2-parse-property-name at-pos js2-ts-string 0))
9123 ;; handles: @*, @*::name, @*::*, @*::[expr]
9124 ((= tt js2-MUL)
9125 (js2-save-name-token-data js2-token-beg "*")
9126 (js2-parse-property-name js2-token-beg "*" 0))
9127 ;; handles @[expr]
9128 ((= tt js2-LB)
9129 (js2-parse-xml-elem-ref at-pos))
9130 (t
9131 (js2-report-error "msg.no.name.after.xmlAttr")
9132 ;; Avoid cascaded errors that happen if we make an error node here.
9133 (js2-save-name-token-data js2-token-beg "")
9134 (js2-parse-property-name js2-token-beg "" 0)))))
9135
9136 (defun js2-parse-property-name (at-pos s member-type-flags)
9137 "Check if :: follows name in which case it becomes qualified name.
9138
9139 AT-POS is a natural number if we just read an '@' token, else nil.
9140 S is the name or string that was matched: an identifier, 'throw' or '*'.
9141 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9142
9143 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9144 operator, or the name is followed by ::. For a plain name, returns a
9145 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9146 (let ((pos (or at-pos js2-token-beg))
9147 colon-pos
9148 (name (js2-create-name-node t js2-current-token))
9149 ns
9150 tt
9151 ref
9152 pn)
9153 (catch 'return
9154 (when (js2-match-token js2-COLONCOLON)
9155 (setq ns name
9156 colon-pos js2-token-beg
9157 tt (js2-next-token))
9158 (cond
9159 ;; handles name::name
9160 ((js2-valid-prop-name-token tt)
9161 (setq name (js2-create-name-node)))
9162 ;; handles name::*
9163 ((= tt js2-MUL)
9164 (js2-save-name-token-data js2-token-beg "*")
9165 (setq name (js2-create-name-node)))
9166 ;; handles name::[expr]
9167 ((= tt js2-LB)
9168 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9169 (t
9170 (js2-report-error "msg.no.name.after.coloncolon"))))
9171 (if (and (null ns) (zerop member-type-flags))
9172 name
9173 (prog1
9174 (setq pn
9175 (make-js2-xml-prop-ref-node :pos pos
9176 :len (- (js2-node-end name) pos)
9177 :at-pos at-pos
9178 :colon-pos colon-pos
9179 :propname name))
9180 (js2-node-add-children pn name))))))
9181
9182 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9183 "Parse the [expr] portion of an xml element reference.
9184 For instance, @[expr], @*::[expr], or ns::[expr]."
9185 (let* ((lb js2-token-beg)
9186 (pos (or at-pos lb))
9187 rb
9188 (expr (js2-parse-expr))
9189 (end (js2-node-end expr))
9190 pn)
9191 (if (js2-must-match js2-RB "msg.no.bracket.index")
9192 (setq rb js2-token-beg
9193 end js2-token-end))
9194 (prog1
9195 (setq pn
9196 (make-js2-xml-elem-ref-node :pos pos
9197 :len (- end pos)
9198 :namespace namespace
9199 :colon-pos colon-pos
9200 :at-pos at-pos
9201 :expr expr
9202 :lb (js2-relpos lb pos)
9203 :rb (js2-relpos rb pos)))
9204 (js2-node-add-children pn namespace expr))))
9205
9206 (defsubst js2-parse-primary-expr-lhs ()
9207 (let ((js2-is-in-lhs t))
9208 (js2-parse-primary-expr)))
9209
9210 (defun js2-parse-primary-expr ()
9211 "Parses a literal (leaf) expression of some sort.
9212 Includes complex literals such as functions, object-literals,
9213 array-literals, array comprehensions and regular expressions."
9214 (let ((tt-flagged (js2-next-flagged-token))
9215 pn ; parent node (usually return value)
9216 tt
9217 px-pos ; paren-expr pos
9218 len
9219 flags ; regexp flags
9220 expr)
9221 (setq tt js2-current-token)
9222 (cond
9223 ((= tt js2-FUNCTION)
9224 (js2-parse-function 'FUNCTION_EXPRESSION))
9225 ((= tt js2-LB)
9226 (js2-parse-array-literal))
9227 ((= tt js2-LC)
9228 (js2-parse-object-literal))
9229 ((= tt js2-LET)
9230 (js2-parse-let js2-token-beg))
9231 ((= tt js2-LP)
9232 (setq px-pos js2-token-beg
9233 expr (js2-parse-expr))
9234 (js2-must-match js2-RP "msg.no.paren")
9235 (setq pn (make-js2-paren-node :pos px-pos
9236 :expr expr
9237 :len (- js2-token-end px-pos)))
9238 (js2-node-add-children pn (js2-paren-node-expr pn))
9239 pn)
9240 ((= tt js2-XMLATTR)
9241 (js2-must-have-xml)
9242 (js2-parse-attribute-access))
9243 ((= tt js2-NAME)
9244 (js2-parse-name tt-flagged tt))
9245 ((= tt js2-NUMBER)
9246 (make-js2-number-node))
9247 ((= tt js2-STRING)
9248 (prog1
9249 (make-js2-string-node)
9250 (js2-record-face 'font-lock-string-face)))
9251 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9252 ;; Got / or /= which in this context means a regexp literal
9253 (setq px-pos js2-token-beg)
9254 (js2-read-regexp tt)
9255 (setq flags js2-ts-regexp-flags
9256 js2-ts-regexp-flags nil)
9257 (prog1
9258 (make-js2-regexp-node :pos px-pos
9259 :len (- js2-ts-cursor px-pos)
9260 :value js2-ts-string
9261 :flags flags)
9262 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9263 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9264 ((or (= tt js2-NULL)
9265 (= tt js2-THIS)
9266 (= tt js2-FALSE)
9267 (= tt js2-TRUE))
9268 (make-js2-keyword-node :type tt))
9269 ((= tt js2-RESERVED)
9270 (js2-report-error "msg.reserved.id")
9271 (make-js2-name-node))
9272 ((= tt js2-ERROR)
9273 ;; the scanner or one of its subroutines reported the error.
9274 (make-js2-error-node))
9275 ((= tt js2-EOF)
9276 (setq px-pos (point-at-bol)
9277 len (- js2-ts-cursor px-pos))
9278 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9279 (make-js2-error-node :pos px-pos :len len))
9280 (t
9281 (js2-report-error "msg.syntax")
9282 (make-js2-error-node)))))
9283
9284 (defun js2-parse-name (tt-flagged tt)
9285 (let ((name js2-ts-string)
9286 (name-pos js2-token-beg)
9287 node)
9288 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9289 (= (js2-peek-token) js2-COLON))
9290 (prog1
9291 ;; Do not consume colon, it is used as unwind indicator
9292 ;; to return to statementHelper.
9293 (make-js2-label-node :pos name-pos
9294 :len (- js2-token-end name-pos)
9295 :name name)
9296 (js2-set-face name-pos
9297 js2-token-end
9298 'font-lock-variable-name-face 'record))
9299 ;; Otherwise not a label, just a name. Unfortunately peeking
9300 ;; the next token to check for a colon has biffed js2-token-beg
9301 ;; and js2-token-end. We store the name's bounds in buffer vars
9302 ;; and `js2-create-name-node' uses them.
9303 (js2-save-name-token-data name-pos name)
9304 (setq node (if js2-compiler-xml-available
9305 (js2-parse-property-name nil name 0)
9306 (js2-create-name-node 'check-activation)))
9307 (if js2-highlight-external-variables
9308 (js2-record-name-node node))
9309 node)))
9310
9311 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9312 (js2-add-strict-warning
9313 msg nil
9314 ;; back up from comma to beginning of line or array/objlit
9315 (max (if elems
9316 (js2-node-pos (car elems))
9317 pos)
9318 (save-excursion
9319 (goto-char comma-pos)
9320 (back-to-indentation)
9321 (point)))
9322 comma-pos))
9323
9324 (defun js2-parse-array-literal ()
9325 (let ((pos js2-token-beg)
9326 (end js2-token-end)
9327 (after-lb-or-comma t)
9328 after-comma
9329 tt
9330 elems
9331 pn
9332 (continue t))
9333 (unless js2-is-in-lhs
9334 (js2-push-scope (make-js2-scope))) ; for array comp
9335 (while continue
9336 (setq tt (js2-peek-token))
9337 (cond
9338 ;; comma
9339 ((= tt js2-COMMA)
9340 (js2-consume-token)
9341 (setq after-comma js2-token-end)
9342 (if (not after-lb-or-comma)
9343 (setq after-lb-or-comma t)
9344 (push nil elems)))
9345 ;; end of array
9346 ((or (= tt js2-RB)
9347 (= tt js2-EOF)) ; prevent infinite loop
9348 (if (= tt js2-EOF)
9349 (js2-report-error "msg.no.bracket.arg" nil pos)
9350 (js2-consume-token))
9351 (setq continue nil
9352 end js2-token-end
9353 pn (make-js2-array-node :pos pos
9354 :len (- js2-ts-cursor pos)
9355 :elems (nreverse elems)))
9356 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9357 (when after-comma
9358 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9359 pos elems after-comma)))
9360 ;; destructuring binding
9361 (js2-is-in-lhs
9362 (push (if (or (= tt js2-LC)
9363 (= tt js2-LB)
9364 (= tt js2-NAME))
9365 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9366 (js2-parse-primary-expr-lhs)
9367 ;; invalid pattern
9368 (js2-consume-token)
9369 (js2-report-error "msg.bad.var")
9370 (make-js2-error-node))
9371 elems)
9372 (setq after-lb-or-comma nil
9373 after-comma nil))
9374 ;; array comp
9375 ((and (>= js2-language-version 170)
9376 (= tt js2-FOR) ; check for array comprehension
9377 (not after-lb-or-comma) ; "for" can't follow a comma
9378 elems ; must have at least 1 element
9379 (not (cdr elems))) ; but no 2nd element
9380 (setf continue nil
9381 pn (js2-parse-array-comprehension (car elems) pos)))
9382
9383 ;; another element
9384 (t
9385 (unless after-lb-or-comma
9386 (js2-report-error "msg.no.bracket.arg"))
9387 (push (js2-parse-assign-expr) elems)
9388 (setq after-lb-or-comma nil
9389 after-comma nil))))
9390 (unless js2-is-in-lhs
9391 (js2-pop-scope))
9392 pn))
9393
9394 (defun js2-parse-array-comprehension (expr pos)
9395 "Parse a JavaScript 1.7 Array Comprehension.
9396 EXPR is the first expression after the opening left-bracket.
9397 POS is the beginning of the LB token preceding EXPR.
9398 We should have just parsed the 'for' keyword before calling this function."
9399 (let (loops
9400 loop
9401 first
9402 prev
9403 filter
9404 if-pos
9405 result)
9406 (while (= (js2-peek-token) js2-FOR)
9407 (let ((prev (car loops))) ; rearrange scope chain
9408 (push (setq loop (js2-parse-array-comp-loop)) loops)
9409 (if prev ; each loop is parent scope to the next one
9410 (setf (js2-scope-parent-scope loop) prev)
9411 ; first loop takes expr scope's parent
9412 (setf (js2-scope-parent-scope (setq first loop))
9413 (js2-scope-parent-scope js2-current-scope)))))
9414 ;; set expr scope's parent to the last loop
9415 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9416 (when (= (js2-peek-token) js2-IF)
9417 (js2-consume-token)
9418 (setq if-pos (- js2-token-beg pos) ; relative
9419 filter (js2-parse-condition)))
9420 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9421 (setq result (make-js2-array-comp-node :pos pos
9422 :len (- js2-ts-cursor pos)
9423 :result expr
9424 :loops (nreverse loops)
9425 :filter (car filter)
9426 :lp (js2-relpos (second filter) pos)
9427 :rp (js2-relpos (third filter) pos)
9428 :if-pos if-pos))
9429 (apply #'js2-node-add-children result expr (car filter)
9430 (js2-array-comp-node-loops result))
9431 (setq js2-current-scope first) ; pop to the first loop
9432 result))
9433
9434 (defun js2-parse-array-comp-loop ()
9435 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9436 Last token peeked should be the initial FOR."
9437 (let ((pos js2-token-beg)
9438 (pn (make-js2-array-comp-loop-node))
9439 tt
9440 iter
9441 obj
9442 foreach-p
9443 in-pos
9444 each-pos
9445 lp
9446 rp)
9447 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9448 (js2-push-scope pn)
9449 (unwind-protect
9450 (progn
9451 (when (js2-match-token js2-NAME)
9452 (if (string= js2-ts-string "each")
9453 (progn
9454 (setq foreach-p t
9455 each-pos (- js2-token-beg pos)) ; relative
9456 (js2-record-face 'font-lock-keyword-face))
9457 (js2-report-error "msg.no.paren.for")))
9458 (if (js2-must-match js2-LP "msg.no.paren.for")
9459 (setq lp (- js2-token-beg pos)))
9460 (setq tt (js2-peek-token))
9461 (cond
9462 ((or (= tt js2-LB)
9463 (= tt js2-LC))
9464 ;; handle destructuring assignment
9465 (setq iter (js2-parse-primary-expr-lhs))
9466 (js2-define-destruct-symbols iter js2-LET
9467 'font-lock-variable-name-face t))
9468 ((js2-valid-prop-name-token tt)
9469 (js2-consume-token)
9470 (setq iter (js2-create-name-node)))
9471 (t
9472 (js2-report-error "msg.bad.var")))
9473 ;; Define as a let since we want the scope of the variable to
9474 ;; be restricted to the array comprehension
9475 (if (js2-name-node-p iter)
9476 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9477 (if (js2-must-match js2-IN "msg.in.after.for.name")
9478 (setq in-pos (- js2-token-beg pos)))
9479 (setq obj (js2-parse-expr))
9480 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9481 (setq rp (- js2-token-beg pos)))
9482 (setf (js2-node-pos pn) pos
9483 (js2-node-len pn) (- js2-ts-cursor pos)
9484 (js2-array-comp-loop-node-iterator pn) iter
9485 (js2-array-comp-loop-node-object pn) obj
9486 (js2-array-comp-loop-node-in-pos pn) in-pos
9487 (js2-array-comp-loop-node-each-pos pn) each-pos
9488 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9489 (js2-array-comp-loop-node-lp pn) lp
9490 (js2-array-comp-loop-node-rp pn) rp)
9491 (js2-node-add-children pn iter obj))
9492 (js2-pop-scope))
9493 pn))
9494
9495 (defun js2-parse-object-literal ()
9496 (let ((pos js2-token-beg)
9497 tt
9498 elems
9499 result
9500 after-comma
9501 (continue t))
9502 (while continue
9503 (setq tt (js2-peek-token))
9504 (cond
9505 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9506 ((or (js2-valid-prop-name-token tt)
9507 (= tt js2-STRING))
9508 (setq after-comma nil
9509 result (js2-parse-named-prop tt))
9510 (if (and (null result)
9511 (not js2-recover-from-parse-errors))
9512 (setq continue nil)
9513 (push result elems)))
9514 ;; {12: x} or {10.7: x}
9515 ((= tt js2-NUMBER)
9516 (js2-consume-token)
9517 (setq after-comma nil)
9518 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9519 ;; trailing comma
9520 ((= tt js2-RC)
9521 (setq continue nil)
9522 (if after-comma
9523 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9524 pos elems after-comma)))
9525 (t
9526 (js2-report-error "msg.bad.prop")
9527 (unless js2-recover-from-parse-errors
9528 (setq continue nil)))) ; end switch
9529 (if (js2-match-token js2-COMMA)
9530 (setq after-comma js2-token-end)
9531 (setq continue nil))) ; end loop
9532 (js2-must-match js2-RC "msg.no.brace.prop")
9533 (setq result (make-js2-object-node :pos pos
9534 :len (- js2-ts-cursor pos)
9535 :elems (nreverse elems)))
9536 (apply #'js2-node-add-children result (js2-object-node-elems result))
9537 result))
9538
9539 (defun js2-parse-named-prop (tt)
9540 "Parse a name, string, or getter/setter object property.
9541 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9542 (js2-consume-token)
9543 (let ((string-prop (and (= tt js2-STRING)
9544 (make-js2-string-node)))
9545 expr
9546 (ppos js2-token-beg)
9547 (pend js2-token-end)
9548 (name (js2-create-name-node))
9549 (prop js2-ts-string))
9550 (cond
9551 ;; getter/setter prop
9552 ((and (= tt js2-NAME)
9553 (= (js2-peek-token) js2-NAME)
9554 (or (string= prop "get")
9555 (string= prop "set")))
9556 (js2-consume-token)
9557 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9558 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9559 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9560 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9561 ;; abbreviated destructuring bind e.g., {a, b} = c;
9562 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9563 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9564 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9565 ;; assignment but it's difficult because it requires looking ahead of expression.
9566 ((and js2-is-in-lhs
9567 (= tt js2-NAME)
9568 (let ((ctk (js2-peek-token)))
9569 (or (= ctk js2-COMMA)
9570 (= ctk js2-RC)
9571 (js2-valid-prop-name-token ctk))))
9572 name)
9573 ;; regular prop
9574 (t
9575 (prog1
9576 (setq expr (js2-parse-plain-property (or string-prop name)))
9577 (js2-set-face ppos pend
9578 (if (js2-function-node-p
9579 (js2-object-prop-node-right expr))
9580 'font-lock-function-name-face
9581 'font-lock-variable-name-face)
9582 'record))))))
9583
9584 (defun js2-parse-plain-property (prop)
9585 "Parse a non-getter/setter property in an object literal.
9586 PROP is the node representing the property: a number, name or string."
9587 (js2-must-match js2-COLON "msg.no.colon.prop")
9588 (let* ((pos (js2-node-pos prop))
9589 (colon (- js2-token-beg pos))
9590 (expr (js2-parse-assign-expr))
9591 (result (make-js2-object-prop-node
9592 :pos pos
9593 ;; don't include last consumed token in length
9594 :len (- (+ (js2-node-pos expr)
9595 (js2-node-len expr))
9596 pos)
9597 :left prop
9598 :right expr
9599 :op-pos colon)))
9600 (js2-node-add-children result prop expr)
9601 result))
9602
9603 (defun js2-parse-getter-setter-prop (pos prop get-p)
9604 "Parse getter or setter property in an object literal.
9605 JavaScript syntax is:
9606
9607 { get foo() {...}, set foo(x) {...} }
9608
9609 and expression closure style is also supported
9610
9611 { get foo() x, set foo(x) _x = x }
9612
9613 POS is the start position of the `get' or `set' keyword.
9614 PROP is the `js2-name-node' representing the property name.
9615 GET-P is non-nil if the keyword was `get'."
9616 (let ((type (if get-p js2-GET js2-SET))
9617 result
9618 end
9619 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9620 ;; it has to be an anonymous function, as we already parsed the name
9621 (if (/= (js2-node-type fn) js2-FUNCTION)
9622 (js2-report-error "msg.bad.prop")
9623 (if (plusp (length (js2-function-name fn)))
9624 (js2-report-error "msg.bad.prop")))
9625 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9626 (setq end (js2-node-end fn)
9627 result (make-js2-getter-setter-node :type type
9628 :pos pos
9629 :len (- end pos)
9630 :left prop
9631 :right fn))
9632 (js2-node-add-children result prop fn)
9633 result))
9634
9635 (defun js2-create-name-node (&optional check-activation-p token)
9636 "Create a name node using the token info from last scanned name.
9637 In some cases we need to either synthesize a name node, or we lost
9638 the name token information by peeking. If the TOKEN parameter is
9639 not `js2-NAME', then we use the token info saved in instance vars."
9640 (let ((beg js2-token-beg)
9641 (s js2-ts-string)
9642 name)
9643 (when (/= js2-current-token js2-NAME)
9644 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9645 s js2-prev-name-token-string
9646 js2-prev-name-token-start nil
9647 js2-prev-name-token-string nil))
9648 (setq name (make-js2-name-node :pos beg
9649 :name s
9650 :len (length s)))
9651 (if check-activation-p
9652 (js2-check-activation-name s (or token js2-NAME)))
9653 name))
9654
9655 ;;; Indentation support
9656
9657 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9658 ;; Karl cleverly deduces that the desired indentation level is often a
9659 ;; function of paren/bracket/brace nesting depth, which can be determined
9660 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9661 ;; then does some equally clever checks to see if we're in the context of a
9662 ;; substatement of a possibly braceless statement keyword such as if, while,
9663 ;; or finally. This approach yields pretty good results.
9664
9665 ;; The indenter is often "wrong", however, and needs to be overridden.
9666 ;; The right long-term solution is probably to emulate (or integrate
9667 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9668 ;; parse tree from `js2-parse' is present, which is not true at the
9669 ;; moment the user is typing, computing indentation is still thousands
9670 ;; of lines of code to handle every possible syntactic edge case.
9671
9672 ;; In the meantime, the compromise solution is that we offer a "bounce
9673 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9674 ;; current line indent among various likely guess points. This approach
9675 ;; is far from perfect, but should at least make it slightly easier to
9676 ;; move the line towards its desired indentation when manually
9677 ;; overriding Karl's heuristic nesting guesser.
9678
9679 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9680 ;; extensions such as `let' and Array comprehensions. Major kudos to
9681 ;; Karl for coming up with the initial approach, which packs a lot of
9682 ;; punch for so little code.
9683
9684 (defconst js-possibly-braceless-keyword-re
9685 (regexp-opt
9686 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9687 'words)
9688 "Regular expression matching keywords that are optionally
9689 followed by an opening brace.")
9690
9691 (defconst js-possibly-braceless-keywords-re
9692 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9693 "Regular expression which matches the keywords which are consist of more than 2 words
9694 like 'if else' and 'for each', and optionally followed by an opening brace.")
9695
9696 (defconst js-indent-operator-re
9697 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9698 (regexp-opt '("in" "instanceof") 'words))
9699 "Regular expression matching operators that affect indentation
9700 of continued expressions.")
9701
9702 ;; This function has horrible results if you're typing an array
9703 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9704 ;; in conjunction with electric-indent, so just disabling it.
9705 (defsubst js2-code-at-bol-p ()
9706 "Return t if the first character on line is non-whitespace."
9707 nil)
9708
9709 (defun js2-insert-and-indent (key)
9710 "Run command bound to key and indent current line. Runs the command
9711 bound to KEY in the global keymap and indents the current line."
9712 (interactive (list (this-command-keys)))
9713 (let ((cmd (lookup-key (current-global-map) key)))
9714 (if (commandp cmd)
9715 (call-interactively cmd)))
9716 ;; don't do the electric keys inside comments or strings,
9717 ;; and don't do bounce-indent with them.
9718 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9719 (js2-bounce-indent-p (js2-code-at-bol-p)))
9720 (unless (or (nth 3 parse-state)
9721 (nth 4 parse-state))
9722 (indent-according-to-mode))))
9723
9724 (defun js-re-search-forward-inner (regexp &optional bound count)
9725 "Auxiliary function for `js-re-search-forward'."
9726 (let ((parse)
9727 (saved-point (point-min)))
9728 (while (> count 0)
9729 (re-search-forward regexp bound)
9730 (setq parse (parse-partial-sexp saved-point (point)))
9731 (cond ((nth 3 parse)
9732 (re-search-forward
9733 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9734 (save-excursion (end-of-line) (point)) t))
9735 ((nth 7 parse)
9736 (forward-line))
9737 ((or (nth 4 parse)
9738 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9739 (re-search-forward "\\*/"))
9740 (t
9741 (setq count (1- count))))
9742 (setq saved-point (point))))
9743 (point))
9744
9745 (defun js-re-search-forward (regexp &optional bound noerror count)
9746 "Search forward but ignore strings and comments. Invokes
9747 `re-search-forward' but treats the buffer as if strings and
9748 comments have been removed."
9749 (let ((saved-point (point))
9750 (search-expr
9751 (cond ((null count)
9752 '(js-re-search-forward-inner regexp bound 1))
9753 ((< count 0)
9754 '(js-re-search-backward-inner regexp bound (- count)))
9755 ((> count 0)
9756 '(js-re-search-forward-inner regexp bound count)))))
9757 (condition-case err
9758 (eval search-expr)
9759 (search-failed
9760 (goto-char saved-point)
9761 (unless noerror
9762 (error (error-message-string err)))))))
9763
9764 (defun js-re-search-backward-inner (regexp &optional bound count)
9765 "Auxiliary function for `js-re-search-backward'."
9766 (let ((parse)
9767 (saved-point (point-min)))
9768 (while (> count 0)
9769 (re-search-backward regexp bound)
9770 (setq parse (parse-partial-sexp saved-point (point)))
9771 (cond ((nth 3 parse)
9772 (re-search-backward
9773 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9774 (save-excursion (beginning-of-line) (point)) t))
9775 ((nth 7 parse)
9776 (goto-char (nth 8 parse)))
9777 ((or (nth 4 parse)
9778 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9779 (re-search-backward "/\\*"))
9780 (t
9781 (setq count (1- count))))))
9782 (point))
9783
9784 (defun js-re-search-backward (regexp &optional bound noerror count)
9785 "Search backward but ignore strings and comments. Invokes
9786 `re-search-backward' but treats the buffer as if strings and
9787 comments have been removed."
9788 (let ((saved-point (point))
9789 (search-expr
9790 (cond ((null count)
9791 '(js-re-search-backward-inner regexp bound 1))
9792 ((< count 0)
9793 '(js-re-search-forward-inner regexp bound (- count)))
9794 ((> count 0)
9795 '(js-re-search-backward-inner regexp bound count)))))
9796 (condition-case err
9797 (eval search-expr)
9798 (search-failed
9799 (goto-char saved-point)
9800 (unless noerror
9801 (error (error-message-string err)))))))
9802
9803 (defun js-looking-at-operator-p ()
9804 "Return non-nil if text after point is an operator (that is not
9805 a comma)."
9806 (save-match-data
9807 (and (looking-at js-indent-operator-re)
9808 (or (not (looking-at ":"))
9809 (save-excursion
9810 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9811 (looking-at "?")))))))
9812
9813 (defun js-continued-expression-p ()
9814 "Returns non-nil if the current line continues an expression."
9815 (save-excursion
9816 (back-to-indentation)
9817 (or (js-looking-at-operator-p)
9818 ;; comment
9819 (and (js-re-search-backward "\n" nil t)
9820 (progn
9821 (skip-chars-backward " \t")
9822 (backward-char)
9823 (and (js-looking-at-operator-p)
9824 (and (progn (backward-char)
9825 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9826
9827 (defun js-end-of-do-while-loop-p ()
9828 "Returns non-nil if word after point is `while' of a do-while
9829 statement, else returns nil. A braceless do-while statement
9830 spanning several lines requires that the start of the loop is
9831 indented to the same column as the current line."
9832 (interactive)
9833 (save-excursion
9834 (save-match-data
9835 (when (looking-at "\\s-*\\<while\\>")
9836 (if (save-excursion
9837 (skip-chars-backward "[ \t\n]*}")
9838 (looking-at "[ \t\n]*}"))
9839 (save-excursion
9840 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9841 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9842 (or (looking-at "\\<do\\>")
9843 (let ((saved-indent (current-indentation)))
9844 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9845 (/= (current-indentation) saved-indent)))
9846 (and (looking-at "[ \t]*\\<do\\>")
9847 (not (js-re-search-forward
9848 "\\<while\\>" (point-at-eol) t))
9849 (= (current-indentation) saved-indent)))))))))
9850
9851 (defun js-get-multiline-declaration-offset ()
9852 "Returns offset (> 0) if the current line is part of
9853 multi-line variable declaration like below example, and
9854 returns 0 otherwise.
9855
9856 var a = 10,
9857 b = 20,
9858 c = 30;
9859
9860 "
9861 (let* ((node (js2-node-at-point))
9862 (pnode (and node (js2-node-parent node)))
9863 (pnode-type (and pnode (js2-node-type pnode))))
9864 (if (and node
9865 (= js2-NAME (js2-node-type node))
9866 (or
9867 (= js2-VAR pnode-type)
9868 (= js2-LET pnode-type)
9869 (= js2-CONST pnode-type)))
9870 (if (= js2-CONST pnode-type)
9871 6
9872 4)
9873 0)))
9874
9875 (defun js-ctrl-statement-indentation ()
9876 "Returns the proper indentation of the current line if it
9877 starts the body of a control statement without braces, else
9878 returns nil."
9879 (let (forward-sexp-function) ; temporarily unbind it
9880 (save-excursion
9881 (back-to-indentation)
9882 (when (save-excursion
9883 (and (not (js2-same-line (point-min)))
9884 (not (looking-at "{"))
9885 (js-re-search-backward "[[:graph:]]" nil t)
9886 (not (looking-at "[{([]"))
9887 (progn
9888 (forward-char)
9889 ;; scan-sexps sometimes throws an error
9890 (ignore-errors (backward-sexp))
9891 (when (looking-at "(") (backward-word 1))
9892 (and (save-excursion
9893 (skip-chars-backward " \t}" (point-at-bol))
9894 (or (bolp)
9895 (and (backward-word 1)
9896 (skip-chars-backward " \t}" (point-at-bol))
9897 (bolp)
9898 (looking-at js-possibly-braceless-keywords-re))))
9899 (looking-at js-possibly-braceless-keyword-re)
9900 (not (js-end-of-do-while-loop-p))))))
9901 (save-excursion
9902 (goto-char (match-beginning 0))
9903 (+ (current-indentation) js2-basic-offset))))))
9904
9905 (defun js2-indent-in-array-comp (parse-status)
9906 "Return non-nil if we think we're in an array comprehension.
9907 In particular, return the buffer position of the first `for' kwd."
9908 (let ((end (point)))
9909 (when (nth 1 parse-status)
9910 (save-excursion
9911 (goto-char (nth 1 parse-status))
9912 (when (looking-at "\\[")
9913 (forward-char 1)
9914 (js2-forward-sws)
9915 (if (looking-at "[[{]")
9916 (let (forward-sexp-function) ; use lisp version
9917 (forward-sexp) ; skip destructuring form
9918 (js2-forward-sws)
9919 (if (and (/= (char-after) ?,) ; regular array
9920 (looking-at "for"))
9921 (match-beginning 0)))
9922 ;; to skip arbitrary expressions we need the parser,
9923 ;; so we'll just guess at it.
9924 (if (re-search-forward "[^,]* \\(for\\) " end t)
9925 (match-beginning 1))))))))
9926
9927 (defun js2-array-comp-indentation (parse-status for-kwd)
9928 (if (js2-same-line for-kwd)
9929 ;; first continuation line
9930 (save-excursion
9931 (goto-char (nth 1 parse-status))
9932 (forward-char 1)
9933 (skip-chars-forward " \t")
9934 (current-column))
9935 (save-excursion
9936 (goto-char for-kwd)
9937 (current-column))))
9938
9939 (defun js-proper-indentation (parse-status)
9940 "Return the proper indentation for the current line."
9941 (save-excursion
9942 (back-to-indentation)
9943 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9944 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9945 (continued-expr-p (js-continued-expression-p))
9946 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9947 (js-get-multiline-declaration-offset))
9948 0))
9949 (bracket (nth 1 parse-status))
9950 beg)
9951 (cond
9952 ;; indent array comprehension continuation lines specially
9953 ((and bracket
9954 (not (js2-same-line bracket))
9955 (setq beg (js2-indent-in-array-comp parse-status))
9956 (>= (point) (save-excursion
9957 (goto-char beg)
9958 (point-at-bol)))) ; at or after first loop?
9959 (js2-array-comp-indentation parse-status beg))
9960
9961 (ctrl-stmt-indent)
9962
9963 (bracket
9964 (goto-char bracket)
9965 (cond
9966 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9967 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9968 (when (save-excursion (skip-chars-backward " \t)")
9969 (looking-at ")"))
9970 (backward-list))
9971 (if (and (nth 1 p)
9972 (not js2-consistent-level-indent-inner-bracket-p))
9973 (progn (goto-char (1+ (nth 1 p)))
9974 (skip-chars-forward " \t"))
9975 (back-to-indentation))
9976 (cond (same-indent-p
9977 (current-column))
9978 (continued-expr-p
9979 (+ (current-column) (* 2 js2-basic-offset)))
9980 ((> multiline-declaration-offset 0)
9981 (+ (current-column) js2-basic-offset multiline-declaration-offset))
9982 (t
9983 (+ (current-column) js2-basic-offset)))))
9984 (t
9985 (unless same-indent-p
9986 (forward-char)
9987 (skip-chars-forward " \t"))
9988 (current-column))))
9989
9990 (continued-expr-p js2-basic-offset)
9991
9992 ((> multiline-declaration-offset 0)
9993 (+ multiline-declaration-offset))
9994
9995 (t 0)))))
9996
9997 (defun js2-lineup-comment (parse-status)
9998 "Indent a multi-line block comment continuation line."
9999 (let* ((beg (nth 8 parse-status))
10000 (first-line (js2-same-line beg))
10001 (offset (save-excursion
10002 (goto-char beg)
10003 (if (looking-at "/\\*")
10004 (+ 1 (current-column))
10005 0))))
10006 (unless first-line
10007 (indent-line-to offset))))
10008
10009 (defun js2-backward-sws ()
10010 "Move backward through whitespace and comments."
10011 (interactive)
10012 (while (forward-comment -1)))
10013
10014 (defun js2-forward-sws ()
10015 "Move forward through whitespace and comments."
10016 (interactive)
10017 (while (forward-comment 1)))
10018
10019 (defsubst js2-current-indent (&optional pos)
10020 "Return column of indentation on current line.
10021 If POS is non-nil, go to that point and return indentation for that line."
10022 (save-excursion
10023 (if pos
10024 (goto-char pos))
10025 (back-to-indentation)
10026 (current-column)))
10027
10028 (defsubst js2-arglist-close ()
10029 "Return non-nil if we're on a line beginning with a close-paren/brace."
10030 (save-match-data
10031 (save-excursion
10032 (goto-char (point-at-bol))
10033 (js2-forward-sws)
10034 (looking-at "[])}]"))))
10035
10036 (defsubst js2-indent-looks-like-label-p ()
10037 (goto-char (point-at-bol))
10038 (js2-forward-sws)
10039 (looking-at (concat js2-mode-identifier-re ":")))
10040
10041 (defun js2-indent-in-objlit-p (parse-status)
10042 "Return non-nil if this looks like an object-literal entry."
10043 (let ((start (nth 1 parse-status)))
10044 (and
10045 start
10046 (save-excursion
10047 (and (zerop (forward-line -1))
10048 (not (< (point) start)) ; crossed a {} boundary
10049 (js2-indent-looks-like-label-p)))
10050 (save-excursion
10051 (js2-indent-looks-like-label-p)))))
10052
10053 ;; if prev line looks like foobar({ then we're passing an object
10054 ;; literal to a function call, and people pretty much always want to
10055 ;; de-dent back to the previous line, so move the 'basic-offset'
10056 ;; position to the front.
10057 (defsubst js2-indent-objlit-arg-p (parse-status)
10058 (save-excursion
10059 (back-to-indentation)
10060 (js2-backward-sws)
10061 (and (eq (1- (point)) (nth 1 parse-status))
10062 (eq (char-before) ?{)
10063 (progn
10064 (forward-char -1)
10065 (skip-chars-backward " \t")
10066 (eq (char-before) ?\()))))
10067
10068 (defsubst js2-indent-case-block-p ()
10069 (save-excursion
10070 (back-to-indentation)
10071 (js2-backward-sws)
10072 (goto-char (point-at-bol))
10073 (skip-chars-forward " \t")
10074 (save-match-data
10075 (looking-at "case\\s-.+:"))))
10076
10077 (defsubst js2-syntax-bol ()
10078 "Return the point at the first non-whitespace char on the line.
10079 Returns `point-at-bol' if the line is empty."
10080 (save-excursion
10081 (beginning-of-line)
10082 (skip-chars-forward " \t")
10083 (point)))
10084
10085 (defun js2-bounce-indent (normal-col parse-status)
10086 "Cycle among alternate computed indentation positions.
10087 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10088 of the buffer to the current point. NORMAL-COL is the indentation
10089 column computed by the heuristic guesser based on current paren,
10090 bracket, brace and statement nesting."
10091 (let ((cur-indent (js2-current-indent))
10092 (old-buffer-undo-list buffer-undo-list)
10093 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10094 (current-line (save-excursion
10095 (forward-line 0) ; move to bol
10096 (1+ (count-lines (point-min) (point)))))
10097 positions
10098 pos
10099 anchor
10100 arglist-cont
10101 same-indent
10102 prev-line-col
10103 basic-offset
10104 computed-pos)
10105 ;; temporarily don't record undo info, if user requested this
10106 (if js2-mode-indent-inhibit-undo
10107 (setq buffer-undo-list t))
10108 (unwind-protect
10109 (progn
10110 ;; first likely point: indent from beginning of previous code line
10111 (push (setq basic-offset
10112 (+ (save-excursion
10113 (back-to-indentation)
10114 (js2-backward-sws)
10115 (back-to-indentation)
10116 (setq prev-line-col (current-column)))
10117 js2-basic-offset))
10118 positions)
10119
10120 ;; (first + epsilon) likely point: indent 2x from beginning of
10121 ;; previous code line. Some companies like this approach. Ahem.
10122 ;; Seriously, though -- 4-space indent for expression continuation
10123 ;; lines isn't a bad idea. We should eventually implement it
10124 ;; that way.
10125 (push (setq basic-offset
10126 (+ (save-excursion
10127 (back-to-indentation)
10128 (js2-backward-sws)
10129 (back-to-indentation)
10130 (setq prev-line-col (current-column)))
10131 (* 2 js2-basic-offset)))
10132 positions)
10133
10134 ;; second likely point: indent from assign-expr RHS. This
10135 ;; is just a crude guess based on finding " = " on the previous
10136 ;; line containing actual code.
10137 (setq pos (save-excursion
10138 (save-match-data
10139 (forward-line -1)
10140 (goto-char (point-at-bol))
10141 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10142 (point-at-eol) t)
10143 (goto-char (match-end 1))
10144 (skip-chars-forward " \t\r\n")
10145 (current-column)))))
10146 (when pos
10147 (incf pos js2-basic-offset)
10148 (unless (member pos positions)
10149 (push pos positions)))
10150
10151 ;; third likely point: same indent as previous line of code.
10152 ;; Make it the first likely point if we're not on an
10153 ;; arglist-close line and previous line ends in a comma, or
10154 ;; both this line and prev line look like object-literal
10155 ;; elements.
10156 (setq pos (save-excursion
10157 (goto-char (point-at-bol))
10158 (js2-backward-sws)
10159 (back-to-indentation)
10160 (prog1
10161 (current-column)
10162 ;; while we're here, look for trailing comma
10163 (if (save-excursion
10164 (goto-char (point-at-eol))
10165 (js2-backward-sws)
10166 (eq (char-before) ?,))
10167 (setq arglist-cont (1- (point)))))))
10168 (when pos
10169 (if (and (or arglist-cont
10170 (js2-indent-in-objlit-p parse-status))
10171 (not (js2-arglist-close)))
10172 (setq same-indent pos))
10173 (unless (member pos positions)
10174 (push pos positions)))
10175
10176 ;; fourth likely point: first preceding code with less indentation
10177 ;; than the immediately preceding code line.
10178 (setq pos (save-excursion
10179 (js2-backward-sws)
10180 (back-to-indentation)
10181 (setq anchor (current-column))
10182 (while (and (zerop (forward-line -1))
10183 (>= (progn
10184 (back-to-indentation)
10185 (current-column))
10186 anchor)))
10187 (setq pos (current-column))))
10188 (unless (member pos positions)
10189 (push pos positions))
10190
10191 ;; put nesting-heuristic position first in list, sort rest
10192 (setq positions (nreverse (sort positions '<)))
10193 (setq positions (cons normal-col (delete normal-col positions)))
10194
10195 ;; comma-list continuation lines: prev line indent takes precedence
10196 (if same-indent
10197 (setq positions
10198 (cons same-indent
10199 (sort (delete same-indent positions) '<))))
10200
10201 ;; common special cases where we want to indent in from previous line
10202 (if (or (js2-indent-case-block-p)
10203 (js2-indent-objlit-arg-p parse-status))
10204 (setq positions
10205 (cons basic-offset
10206 (delete basic-offset positions))))
10207
10208 ;; record whether we're already sitting on one of the alternatives
10209 (setq pos (member cur-indent positions))
10210 (cond
10211 ;; case 0: we're one one of the alternatives and this is the
10212 ;; first time they've pressed TAB on this line (best-guess).
10213 ((and js2-mode-indent-ignore-first-tab
10214 pos
10215 ;; first time pressing TAB on this line?
10216 (not (eq js2-mode-last-indented-line current-line)))
10217 ;; do nothing
10218 (setq computed-pos nil))
10219 ;; case 1: only one computed position => use it
10220 ((null (cdr positions))
10221 (setq computed-pos 0))
10222 ;; case 2: not on any of the computed spots => use main spot
10223 ((not pos)
10224 (setq computed-pos 0))
10225 ;; case 3: on last position: cycle to first position
10226 ((null (cdr pos))
10227 (setq computed-pos 0))
10228 ;; case 4: on intermediate position: cycle to next position
10229 (t
10230 (setq computed-pos (js2-position (second pos) positions))))
10231
10232 ;; see if any hooks want to indent; otherwise we do it
10233 (loop with result = nil
10234 for hook in js2-indent-hook
10235 while (null result)
10236 do
10237 (setq result (funcall hook positions computed-pos))
10238 finally do
10239 (unless (or result (null computed-pos))
10240 (indent-line-to (nth computed-pos positions)))))
10241
10242 ;; finally
10243 (if js2-mode-indent-inhibit-undo
10244 (setq buffer-undo-list old-buffer-undo-list))
10245 ;; see commentary for `js2-mode-last-indented-line'
10246 (setq js2-mode-last-indented-line current-line))))
10247
10248 (defsubst js2-1-line-comment-continuation-p ()
10249 "Return t if we're in a 1-line comment continuation.
10250 If so, we don't ever want to use bounce-indent."
10251 (save-excursion
10252 (save-match-data
10253 (and (progn
10254 (forward-line 0)
10255 (looking-at "\\s-*//"))
10256 (progn
10257 (forward-line -1)
10258 (forward-line 0)
10259 (when (looking-at "\\s-*$")
10260 (js2-backward-sws)
10261 (forward-line 0))
10262 (looking-at "\\s-*//"))))))
10263
10264 (defun js2-indent-line ()
10265 "Indent the current line as JavaScript source text."
10266 (interactive)
10267 (when js2-use-ast-for-indentation-p
10268 (js2-reparse))
10269 (let (parse-status
10270 current-indent
10271 offset
10272 indent-col
10273 moved
10274 ;; don't whine about errors/warnings when we're indenting.
10275 ;; This has to be set before calling parse-partial-sexp below.
10276 (inhibit-point-motion-hooks t))
10277 (setq parse-status (save-excursion
10278 (parse-partial-sexp (point-min)
10279 (point-at-bol)))
10280 offset (- (point) (save-excursion
10281 (back-to-indentation)
10282 (setq current-indent (current-column))
10283 (point))))
10284 (js2-with-underscore-as-word-syntax
10285 (if (nth 4 parse-status)
10286 (js2-lineup-comment parse-status)
10287 (setq indent-col (js-proper-indentation parse-status))
10288 ;; see comments below about js2-mode-last-indented-line
10289 (when
10290 (cond
10291 ;; bounce-indenting is disabled during electric-key indent.
10292 ;; It doesn't work well on first line of buffer.
10293 ((and js2-bounce-indent-p
10294 (not (js2-same-line (point-min)))
10295 (not (js2-1-line-comment-continuation-p)))
10296 (js2-bounce-indent indent-col parse-status)
10297 (setq moved t))
10298 ;; just indent to the guesser's likely spot
10299 ((/= current-indent indent-col)
10300 (indent-line-to indent-col)
10301 (setq moved t)))
10302 (when (and moved (plusp offset))
10303 (forward-char offset)))))))
10304
10305 (defun js2-indent-region (start end)
10306 "Indent the region, but don't use bounce indenting."
10307 (let ((js2-bounce-indent-p nil)
10308 (indent-region-function nil))
10309 (indent-region start end nil))) ; nil for byte-compiler
10310
10311 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10312
10313 ;;;###autoload
10314 (defun js2-mode ()
10315 "Major mode for editing JavaScript code."
10316 (interactive)
10317 (kill-all-local-variables)
10318 (set-syntax-table js2-mode-syntax-table)
10319 (use-local-map js2-mode-map)
10320 (setq major-mode 'js2-mode
10321 mode-name "JavaScript-IDE"
10322 comment-start "//" ; used by comment-region; don't change it
10323 comment-end "")
10324 (setq local-abbrev-table js2-mode-abbrev-table)
10325 (set (make-local-variable 'max-lisp-eval-depth)
10326 (max max-lisp-eval-depth 3000))
10327 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10328 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10329
10330 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10331 ;; on most platforms other than the one I originally wrote it on. So it's
10332 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10333 ;; with our binding of the RET key inside comments: short lines stay short.
10334 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10335
10336 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10337 (set (make-local-variable 'next-error-function) #'js2-next-error)
10338 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10339 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10340 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10341 ;; for characters inside regexp literals.
10342 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10343 ;; this is necessary to make `show-paren-function' work properly
10344 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10345 ;; needed for M-x rgrep, among other things
10346 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10347
10348 ;; some variables needed by cc-engine for paragraph-fill, etc.
10349 (setq c-buffer-is-cc-mode t
10350 c-comment-prefix-regexp js2-comment-prefix-regexp
10351 c-comment-start-regexp "/[*/]\\|\\s|"
10352 c-paragraph-start js2-paragraph-start
10353 c-paragraph-separate "$"
10354 comment-start-skip js2-comment-start-skip
10355 c-syntactic-ws-start js2-syntactic-ws-start
10356 c-syntactic-ws-end js2-syntactic-ws-end
10357 c-syntactic-eol js2-syntactic-eol)
10358
10359 (setq js2-default-externs
10360 (append js2-ecma-262-externs
10361 (if js2-include-browser-externs
10362 js2-browser-externs)
10363 (if js2-include-gears-externs
10364 js2-gears-externs)
10365 (if js2-include-rhino-externs
10366 js2-rhino-externs)))
10367
10368 ;; We do our own syntax highlighting based on the parse tree.
10369 ;; However, we want minor modes that add keywords to highlight properly
10370 ;; (examples: doxymacs, column-marker). We do this by not letting
10371 ;; font-lock unfontify anything, and telling it to fontify after we
10372 ;; re-parse and re-highlight the buffer. (We currently don't do any
10373 ;; work with regions other than the whole buffer.)
10374 (dolist (var '(font-lock-unfontify-buffer-function
10375 font-lock-unfontify-region-function))
10376 (set (make-local-variable var) (lambda (&rest args) t)))
10377
10378 ;; Don't let font-lock do syntactic (string/comment) fontification.
10379 (set (make-local-variable #'font-lock-syntactic-face-function)
10380 (lambda (state) nil))
10381
10382 ;; Experiment: make reparse-delay longer for longer files.
10383 (if (plusp js2-dynamic-idle-timer-adjust)
10384 (setq js2-idle-timer-delay
10385 (* js2-idle-timer-delay
10386 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10387
10388 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10389 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10390 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10391 (imenu-add-to-menubar (concat "IM-" mode-name))
10392 (when js2-mirror-mode
10393 (js2-enter-mirror-mode))
10394 (add-to-invisibility-spec '(js2-outline . t))
10395 (set (make-local-variable 'line-move-ignore-invisible) t)
10396 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10397 (setq js2-mode-functions-hidden nil
10398 js2-mode-comments-hidden nil
10399 js2-mode-buffer-dirty-p t
10400 js2-mode-parsing nil)
10401 (js2-reparse)
10402 (run-hooks 'js2-mode-hook))
10403
10404 (defun js2-mode-exit ()
10405 "Exit `js2-mode' and clean up."
10406 (interactive)
10407 (when js2-mode-node-overlay
10408 (delete-overlay js2-mode-node-overlay)
10409 (setq js2-mode-node-overlay nil))
10410 (js2-remove-overlays)
10411 (setq js2-mode-ast nil)
10412 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10413 (remove-from-invisibility-spec '(js2-outline . t))
10414 (js2-mode-show-all)
10415 (js2-with-unmodifying-text-property-changes
10416 (js2-clear-face (point-min) (point-max))))
10417
10418 (defun js2-before-save ()
10419 "Clean up whitespace before saving file.
10420 You can disable this by customizing `js2-cleanup-whitespace'."
10421 (when js2-cleanup-whitespace
10422 (let ((col (current-column)))
10423 (delete-trailing-whitespace)
10424 ;; don't change trailing whitespace on current line
10425 (unless (eq (current-column) col)
10426 (indent-to col)))))
10427
10428 (defsubst js2-mode-reset-timer ()
10429 "Cancel any existing parse timer and schedule a new one."
10430 (if js2-mode-parse-timer
10431 (cancel-timer js2-mode-parse-timer))
10432 (setq js2-mode-parsing nil)
10433 (setq js2-mode-parse-timer
10434 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10435
10436 (defun js2-mode-edit (beg end len)
10437 "Schedule a new parse after buffer is edited.
10438 Buffer edit spans from BEG to END and is of length LEN.
10439 Also clears the `js2-magic' bit on autoinserted parens/brackets
10440 if the edit occurred on a line different from the magic paren."
10441 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10442 (line (if magic-pos (line-number-at-pos magic-pos))))
10443 (and line
10444 (or (/= (line-number-at-pos beg) line)
10445 (and (> 0 len)
10446 (/= (line-number-at-pos end) line)))
10447 (js2-mode-mundanify-parens)))
10448 (setq js2-mode-buffer-dirty-p t)
10449 (js2-mode-hide-overlay)
10450 (js2-mode-reset-timer))
10451
10452 (defun js2-mode-run-font-lock ()
10453 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10454 This is intended to allow modes that install their own font-lock keywords
10455 to work with js2-mode. In practice it never seems to work for long.
10456 Hopefully the Emacs maintainers can help figure out a way to make it work."
10457 (when (and (boundp 'font-lock-keywords)
10458 font-lock-keywords
10459 (boundp 'font-lock-mode)
10460 font-lock-mode)
10461 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10462 ;; play nicely with js2-mode. They go out of their way to fail to
10463 ;; provide any option for saying "look, fontify the farging buffer
10464 ;; with just the keywords already". Argh.
10465 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10466 (let (font-lock-verbose)
10467 (font-lock-fontify-buffer))))
10468
10469 (defun js2-reparse (&optional force)
10470 "Re-parse current buffer after user finishes some data entry.
10471 If we get any user input while parsing, including cursor motion,
10472 we discard the parse and reschedule it. If FORCE is nil, then the
10473 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10474 (let (time
10475 interrupted-p
10476 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10477 (unless js2-mode-parsing
10478 (setq js2-mode-parsing t)
10479 (unwind-protect
10480 (when (or js2-mode-buffer-dirty-p force)
10481 (js2-remove-overlays)
10482 (js2-with-unmodifying-text-property-changes
10483 (remove-text-properties (point-min) (point-max) '(syntax-table))
10484 (setq js2-mode-buffer-dirty-p nil
10485 js2-mode-fontifications nil
10486 js2-mode-deferred-properties nil
10487 js2-additional-externs nil)
10488 (if js2-mode-verbose-parse-p
10489 (message "parsing..."))
10490 (setq time
10491 (js2-time
10492 (setq interrupted-p
10493 (catch 'interrupted
10494 (setq js2-mode-ast (js2-parse))
10495 (when (plusp js2-highlight-level)
10496 (js2-mode-fontify-regions))
10497 (js2-mode-remove-suppressed-warnings)
10498 (js2-mode-show-warnings)
10499 (js2-mode-show-errors)
10500 (js2-mode-run-font-lock) ; note: doesn't work
10501 (js2-mode-highlight-magic-parens)
10502 (if (>= js2-highlight-level 1)
10503 (js2-highlight-jsdoc js2-mode-ast))
10504 nil))))
10505 (if interrupted-p
10506 (progn
10507 ;; unfinished parse => try again
10508 (setq js2-mode-buffer-dirty-p t)
10509 (js2-mode-reset-timer))
10510 (if js2-mode-verbose-parse-p
10511 (message "Parse time: %s" time)))))
10512 (setq js2-mode-parsing nil)
10513 (unless interrupted-p
10514 (setq js2-mode-parse-timer nil))))))
10515
10516 (defun js2-mode-show-node ()
10517 "Debugging aid: highlight selected AST node on mouse click."
10518 (interactive)
10519 (let ((node (js2-node-at-point))
10520 beg
10521 end)
10522 (when js2-mode-show-overlay
10523 (if (null node)
10524 (message "No node found at location %s" (point))
10525 (setq beg (js2-node-abs-pos node)
10526 end (+ beg (js2-node-len node)))
10527 (if js2-mode-node-overlay
10528 (move-overlay js2-mode-node-overlay beg end)
10529 (setq js2-mode-node-overlay (make-overlay beg end))
10530 (overlay-put js2-mode-node-overlay 'face 'highlight))
10531 (js2-with-unmodifying-text-property-changes
10532 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10533 (message "%s, parent: %s"
10534 (js2-node-short-name node)
10535 (if (js2-node-parent node)
10536 (js2-node-short-name (js2-node-parent node))
10537 "nil"))))))
10538
10539 (defun js2-mode-hide-overlay (&optional p1 p2)
10540 "Remove the debugging overlay when the point moves.
10541 P1 and P2 are the old and new values of point, respectively."
10542 (when js2-mode-node-overlay
10543 (let ((beg (overlay-start js2-mode-node-overlay))
10544 (end (overlay-end js2-mode-node-overlay)))
10545 ;; Sometimes we're called spuriously.
10546 (unless (and p2
10547 (>= p2 beg)
10548 (<= p2 end))
10549 (js2-with-unmodifying-text-property-changes
10550 (remove-text-properties beg end '(point-left nil)))
10551 (delete-overlay js2-mode-node-overlay)
10552 (setq js2-mode-node-overlay nil)))))
10553
10554 (defun js2-mode-reset ()
10555 "Debugging helper: reset everything."
10556 (interactive)
10557 (js2-mode-exit)
10558 (js2-mode))
10559
10560 (defsubst js2-mode-show-warn-or-err (e face)
10561 "Highlight a warning or error E with FACE.
10562 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10563 (let* ((key (first e))
10564 (beg (second e))
10565 (end (+ beg (third e)))
10566 ;; Don't inadvertently go out of bounds.
10567 (beg (max (point-min) (min beg (point-max))))
10568 (end (max (point-min) (min end (point-max))))
10569 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10570 (ovl (make-overlay beg end)))
10571 (overlay-put ovl 'face face)
10572 (overlay-put ovl 'js2-error t)
10573 (put-text-property beg end 'help-echo (js2-get-msg key))
10574 (put-text-property beg end 'point-entered #'js2-echo-error)))
10575
10576 (defun js2-remove-overlays ()
10577 "Remove overlays from buffer that have a `js2-error' property."
10578 (let ((beg (point-min))
10579 (end (point-max)))
10580 (save-excursion
10581 (dolist (o (overlays-in beg end))
10582 (when (overlay-get o 'js2-error)
10583 (delete-overlay o))))))
10584
10585 (defun js2-error-at-point (&optional pos)
10586 "Return non-nil if there's an error overlay at POS.
10587 Defaults to point."
10588 (loop with pos = (or pos (point))
10589 for o in (overlays-at pos)
10590 thereis (overlay-get o 'js2-error)))
10591
10592 (defun js2-mode-fontify-regions ()
10593 "Apply fontifications recorded during parsing."
10594 ;; We defer clearing faces as long as possible to eliminate flashing.
10595 (js2-clear-face (point-min) (point-max))
10596 ;; have to reverse the recorded fontifications so that errors and
10597 ;; warnings overwrite the normal fontifications
10598 (dolist (f (nreverse js2-mode-fontifications))
10599 (put-text-property (first f) (second f) 'face (third f)))
10600 (setq js2-mode-fontifications nil)
10601 (dolist (p js2-mode-deferred-properties)
10602 (apply #'put-text-property p))
10603 (setq js2-mode-deferred-properties nil))
10604
10605 (defun js2-mode-show-errors ()
10606 "Highlight syntax errors."
10607 (when js2-mode-show-parse-errors
10608 (dolist (e (js2-ast-root-errors js2-mode-ast))
10609 (js2-mode-show-warn-or-err e 'js2-error-face))))
10610
10611 (defun js2-mode-remove-suppressed-warnings ()
10612 "Take suppressed warnings out of the AST warnings list.
10613 This ensures that the counts and `next-error' are correct."
10614 (setf (js2-ast-root-warnings js2-mode-ast)
10615 (js2-delete-if
10616 (lambda (e)
10617 (let ((key (caar e)))
10618 (or
10619 (and (not js2-strict-trailing-comma-warning)
10620 (string-match "trailing\\.comma" key))
10621 (and (not js2-strict-cond-assign-warning)
10622 (string= key "msg.equal.as.assign"))
10623 (and js2-missing-semi-one-line-override
10624 (string= key "msg.missing.semi")
10625 (let* ((beg (second e))
10626 (node (js2-node-at-point beg))
10627 (fn (js2-mode-find-parent-fn node))
10628 (body (and fn (js2-function-node-body fn)))
10629 (lc (and body (js2-node-abs-pos body)))
10630 (rc (and lc (+ lc (js2-node-len body)))))
10631 (and fn
10632 (or (null body)
10633 (save-excursion
10634 (goto-char beg)
10635 (and (js2-same-line lc)
10636 (js2-same-line rc))))))))))
10637 (js2-ast-root-warnings js2-mode-ast))))
10638
10639 (defun js2-mode-show-warnings ()
10640 "Highlight strict-mode warnings."
10641 (when js2-mode-show-strict-warnings
10642 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10643 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10644
10645 (defun js2-echo-error (old-point new-point)
10646 "Called by point-motion hooks."
10647 (let ((msg (get-text-property new-point 'help-echo)))
10648 (if msg
10649 (message msg))))
10650
10651 (defalias #'js2-echo-help #'js2-echo-error)
10652
10653 (defun js2-enter-key ()
10654 "Handle user pressing the Enter key."
10655 (interactive)
10656 (let ((parse-status (save-excursion
10657 (parse-partial-sexp (point-min) (point)))))
10658 (cond
10659 ;; check if we're inside a string
10660 ((nth 3 parse-status)
10661 (js2-mode-split-string parse-status))
10662 ;; check if inside a block comment
10663 ((nth 4 parse-status)
10664 (js2-mode-extend-comment))
10665 (t
10666 ;; should probably figure out what the mode-map says we should do
10667 (if js2-indent-on-enter-key
10668 (let ((js2-bounce-indent-p nil))
10669 (js2-indent-line)))
10670 (insert "\n")
10671 (if js2-enter-indents-newline
10672 (let ((js2-bounce-indent-p nil))
10673 (js2-indent-line)))))))
10674
10675 (defun js2-mode-split-string (parse-status)
10676 "Turn a newline in mid-string into a string concatenation.
10677 PARSE-STATUS is as documented in `parse-partial-sexp'."
10678 (let* ((col (current-column))
10679 (quote-char (nth 3 parse-status))
10680 (quote-string (string quote-char))
10681 (string-beg (nth 8 parse-status))
10682 (indent (save-match-data
10683 (or
10684 (save-excursion
10685 (back-to-indentation)
10686 (if (looking-at "\\+")
10687 (current-column)))
10688 (save-excursion
10689 (goto-char string-beg)
10690 (if (looking-back "\\+\\s-+")
10691 (goto-char (match-beginning 0)))
10692 (current-column))))))
10693 (insert quote-char "\n")
10694 (indent-to indent)
10695 (insert "+ " quote-string)
10696 (when (eolp)
10697 (insert quote-string)
10698 (backward-char 1))))
10699
10700 (defun js2-mode-extend-comment ()
10701 "When inside a comment block, add comment prefix."
10702 (let (star single col first-line needs-close)
10703 (save-excursion
10704 (back-to-indentation)
10705 (cond
10706 ((looking-at "\\*[^/]")
10707 (setq star t
10708 col (current-column)))
10709 ((looking-at "/\\*")
10710 (setq star t
10711 first-line t
10712 col (1+ (current-column))))
10713 ((looking-at "//")
10714 (setq single t
10715 col (current-column)))))
10716 ;; Heuristic for whether we need to close the comment:
10717 ;; if we've got a parse error here, assume it's an unterminated
10718 ;; comment.
10719 (setq needs-close
10720 (or
10721 (eq (get-text-property (1- (point)) 'point-entered)
10722 'js2-echo-error)
10723 ;; The heuristic above doesn't work well when we're
10724 ;; creating a comment and there's another one downstream,
10725 ;; as our parser thinks this one ends at the end of the
10726 ;; next one. (You can have a /* inside a js block comment.)
10727 ;; So just close it if the next non-ws char isn't a *.
10728 (and first-line
10729 (eolp)
10730 (save-excursion
10731 (skip-chars-forward " \t\r\n")
10732 (not (eq (char-after) ?*))))))
10733 (insert "\n")
10734 (cond
10735 (star
10736 (indent-to col)
10737 (insert "* ")
10738 (if (and first-line needs-close)
10739 (save-excursion
10740 (insert "\n")
10741 (indent-to col)
10742 (insert "*/"))))
10743 (single
10744 (when (save-excursion
10745 (and (zerop (forward-line 1))
10746 (looking-at "\\s-*//")))
10747 (indent-to col)
10748 (insert "// "))))))
10749
10750 (defun js2-beginning-of-line ()
10751 "Toggles point between bol and first non-whitespace char in line.
10752 Also moves past comment delimiters when inside comments."
10753 (interactive)
10754 (let (node beg)
10755 (cond
10756 ((bolp)
10757 (back-to-indentation))
10758 ((looking-at "//")
10759 (skip-chars-forward "/ \t"))
10760 ((and (eq (char-after) ?*)
10761 (setq node (js2-comment-at-point))
10762 (memq (js2-comment-node-format node) '(jsdoc block))
10763 (save-excursion
10764 (skip-chars-backward " \t")
10765 (bolp)))
10766 (skip-chars-forward "\* \t"))
10767 (t
10768 (goto-char (point-at-bol))))))
10769
10770 (defun js2-end-of-line ()
10771 "Toggles point between eol and last non-whitespace char in line."
10772 (interactive)
10773 (if (eolp)
10774 (skip-chars-backward " \t")
10775 (goto-char (point-at-eol))))
10776
10777 (defun js2-enter-mirror-mode()
10778 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10779 on insertion."
10780 (interactive)
10781 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10782 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10783 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10784 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10785 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10786 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10787 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10788 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10789
10790 (defun js2-leave-mirror-mode()
10791 "Turns off mirror mode."
10792 (interactive)
10793 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10794 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10795
10796 (defsubst js2-mode-inside-string ()
10797 "Return non-nil if inside a string.
10798 Actually returns the quote character that begins the string."
10799 (let ((parse-state (save-excursion
10800 (parse-partial-sexp (point-min) (point)))))
10801 (nth 3 parse-state)))
10802
10803 (defsubst js2-mode-inside-comment-or-string ()
10804 "Return non-nil if inside a comment or string."
10805 (or
10806 (let ((comment-start
10807 (save-excursion
10808 (goto-char (point-at-bol))
10809 (if (re-search-forward "//" (point-at-eol) t)
10810 (match-beginning 0)))))
10811 (and comment-start
10812 (<= comment-start (point))))
10813 (let ((parse-state (save-excursion
10814 (parse-partial-sexp (point-min) (point)))))
10815 (or (nth 3 parse-state)
10816 (nth 4 parse-state)))))
10817
10818 (defsubst js2-make-magic-delimiter (delim &optional pos)
10819 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10820 Sets value of `js2-magic' text property to line number at POS."
10821 (propertize delim
10822 'js2-magic (line-number-at-pos pos)
10823 'face 'js2-magic-paren-face))
10824
10825 (defun js2-mode-match-delimiter (open close)
10826 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10827 The rule we use, which as far as we can tell is how Eclipse works,
10828 is that we insert the match if we're not in a comment or string,
10829 and the next non-whitespace character is either punctuation or
10830 occurs on another line."
10831 (insert open)
10832 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10833 (not (js2-mode-inside-comment-or-string)))
10834 (save-excursion
10835 (insert (js2-make-magic-delimiter close)))
10836 (when js2-auto-indent-p
10837 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10838 (js2-indent-line)))))
10839
10840 (defun js2-mode-match-bracket ()
10841 "Insert matching bracket."
10842 (interactive)
10843 (js2-mode-match-delimiter "[" "]"))
10844
10845 (defun js2-mode-match-paren ()
10846 "Insert matching paren unless already inserted."
10847 (interactive)
10848 (js2-mode-match-delimiter "(" ")"))
10849
10850 (defun js2-mode-match-curly (arg)
10851 "Insert matching curly-brace.
10852 With prefix arg, no formatting or indentation will occur -- the close-brace
10853 is simply inserted directly at the point."
10854 (interactive "p")
10855 (let (try-pos)
10856 (cond
10857 (current-prefix-arg
10858 (js2-mode-match-delimiter "{" "}"))
10859 ((and js2-auto-insert-catch-block
10860 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10861 (point-at-bol))
10862 (match-beginning 1))))
10863 (js2-insert-catch-skel try-pos))
10864 (t
10865 ;; Otherwise try to do something smarter.
10866 (insert "{")
10867 (unless (or (not (looking-at "\\s-*$"))
10868 (save-excursion
10869 (skip-chars-forward " \t\r\n")
10870 (and (looking-at "}")
10871 (js2-error-at-point)))
10872 (js2-mode-inside-comment-or-string))
10873 (undo-boundary)
10874 ;; absolutely mystifying bug: when inserting the next "\n",
10875 ;; the buffer-undo-list is given two new entries: the inserted range,
10876 ;; and the incorrect position of the point. It's recorded incorrectly
10877 ;; as being before the opening "{", not after it. But it's recorded
10878 ;; as the correct value if you're debugging `js2-mode-match-curly'
10879 ;; in edebug. I have no idea why it's doing this, but incrementing
10880 ;; the inserted position fixes the problem, so that the undo takes us
10881 ;; back to just after the user-inserted "{".
10882 (insert "\n")
10883 (ignore-errors
10884 (incf (cadr buffer-undo-list)))
10885 (js2-indent-line)
10886 (save-excursion
10887 (insert "\n}")
10888 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10889 (js2-indent-line))))))))
10890
10891 (defun js2-insert-catch-skel (try-pos)
10892 "Complete a try/catch block after inserting a { following a try keyword.
10893 Rationale is that a try always needs a catch or a finally, and the catch is
10894 the more likely of the two.
10895
10896 TRY-POS is the buffer position of the try keyword. The open-curly should
10897 already have been inserted."
10898 (insert "{")
10899 (let ((try-col (save-excursion
10900 (goto-char try-pos)
10901 (current-column))))
10902 (insert "\n")
10903 (undo-boundary)
10904 (js2-indent-line) ;; indent the blank line where cursor will end up
10905 (save-excursion
10906 (insert "\n")
10907 (indent-to try-col)
10908 (insert "} catch (x) {\n\n")
10909 (indent-to try-col)
10910 (insert "}"))))
10911
10912 (defun js2-mode-highlight-magic-parens ()
10913 "Re-highlight magic parens after parsing nukes the 'face prop."
10914 (let ((beg (point-min))
10915 end)
10916 (while (setq beg (next-single-property-change beg 'js2-magic))
10917 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10918 (if (get-text-property beg 'js2-magic)
10919 (js2-with-unmodifying-text-property-changes
10920 (put-text-property beg (or end (1+ beg))
10921 'face 'js2-magic-paren-face))))))
10922
10923 (defun js2-mode-mundanify-parens ()
10924 "Clear all magic parens and brackets."
10925 (let ((beg (point-min))
10926 end)
10927 (while (setq beg (next-single-property-change beg 'js2-magic))
10928 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10929 (remove-text-properties beg (or end (1+ beg))
10930 '(js2-magic face)))))
10931
10932 (defsubst js2-match-quote (quote-string)
10933 (let ((start-quote (js2-mode-inside-string)))
10934 (cond
10935 ;; inside a comment - don't do quote-matching, since we can't
10936 ;; reliably figure out if we're in a string inside the comment
10937 ((js2-comment-at-point)
10938 (insert quote-string))
10939 ((not start-quote)
10940 ;; not in string => insert matched quotes
10941 (insert quote-string)
10942 ;; exception: if we're just before a word, don't double it.
10943 (unless (looking-at "[^ \t\r\n]")
10944 (save-excursion
10945 (insert quote-string))))
10946 ((looking-at quote-string)
10947 (if (looking-back "[^\\]\\\\")
10948 (insert quote-string)
10949 (forward-char 1)))
10950 ((and js2-mode-escape-quotes
10951 (save-excursion
10952 (save-match-data
10953 (re-search-forward quote-string (point-at-eol) t))))
10954 ;; inside terminated string, escape quote (unless already escaped)
10955 (insert (if (looking-back "[^\\]\\\\")
10956 quote-string
10957 (concat "\\" quote-string))))
10958 (t
10959 (insert quote-string))))) ; else terminate the string
10960
10961 (defun js2-mode-match-single-quote ()
10962 "Insert matching single-quote."
10963 (interactive)
10964 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10965 ;; don't match inside comments, since apostrophe is more common
10966 (if (nth 4 parse-status)
10967 (insert "'")
10968 (js2-match-quote "'"))))
10969
10970 (defun js2-mode-match-double-quote ()
10971 "Insert matching double-quote."
10972 (interactive)
10973 (js2-match-quote "\""))
10974
10975 ;; Eclipse works as follows:
10976 ;; * type an open-paren and it auto-inserts close-paren
10977 ;; - auto-inserted paren gets a green bracket
10978 ;; - green bracket means typing close-paren there will skip it
10979 ;; * if you insert any text on a different line, it turns off
10980 (defun js2-mode-magic-close-paren ()
10981 "Skip over close-paren rather than inserting, where appropriate."
10982 (interactive)
10983 (let* ((here (point))
10984 (parse-status (parse-partial-sexp (point-min) here))
10985 (open-pos (nth 1 parse-status))
10986 (close last-input-event)
10987 (open (cond
10988 ((eq close ?\))
10989 ?\()
10990 ((eq close ?\])
10991 ?\[)
10992 ((eq close ?})
10993 ?{)
10994 (t nil))))
10995 (if (and (eq (char-after) close)
10996 (eq open (char-after open-pos))
10997 (js2-same-line open-pos)
10998 (get-text-property here 'js2-magic))
10999 (progn
11000 (remove-text-properties here (1+ here) '(js2-magic face))
11001 (forward-char 1))
11002 (insert-char close 1))
11003 (blink-matching-open)))
11004
11005 (defun js2-mode-wait-for-parse (callback)
11006 "Invoke CALLBACK when parsing is finished.
11007 If parsing is already finished, calls CALLBACK immediately."
11008 (if (not js2-mode-buffer-dirty-p)
11009 (funcall callback)
11010 (push callback js2-mode-pending-parse-callbacks)
11011 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11012
11013 (defun js2-mode-parse-finished ()
11014 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11015 ;; We can't let errors propagate up, since it prevents the
11016 ;; `js2-parse' method from completing normally and returning
11017 ;; the ast, which makes things mysteriously not work right.
11018 (unwind-protect
11019 (dolist (cb js2-mode-pending-parse-callbacks)
11020 (condition-case err
11021 (funcall cb)
11022 (error (message "%s" err))))
11023 (setq js2-mode-pending-parse-callbacks nil)))
11024
11025 (defun js2-mode-flag-region (from to flag)
11026 "Hide or show text from FROM to TO, according to FLAG.
11027 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11028 Returns the created overlay if FLAG is non-nil."
11029 (remove-overlays from to 'invisible 'js2-outline)
11030 (when flag
11031 (let ((o (make-overlay from to)))
11032 (overlay-put o 'invisible 'js2-outline)
11033 (overlay-put o 'isearch-open-invisible
11034 'js2-isearch-open-invisible)
11035 o)))
11036
11037 ;; Function to be set as an outline-isearch-open-invisible' property
11038 ;; to the overlay that makes the outline invisible (see
11039 ;; `js2-mode-flag-region').
11040 (defun js2-isearch-open-invisible (overlay)
11041 ;; We rely on the fact that isearch places point on the matched text.
11042 (js2-mode-show-element))
11043
11044 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11045 "Return cons cell of bounds of folding overlay at POS.
11046 Returns nil if not found."
11047 (let ((overlays (overlays-at (or pos (point))))
11048 o)
11049 (while (and overlays
11050 (not o))
11051 (if (overlay-get (car overlays) 'invisible)
11052 (setq o (car overlays))
11053 (setq overlays (cdr overlays))))
11054 (if o
11055 (cons (overlay-start o) (overlay-end o)))))
11056
11057 (defun js2-mode-function-at-point (&optional pos)
11058 "Return the innermost function node enclosing current point.
11059 Returns nil if point is not in a function."
11060 (let ((node (js2-node-at-point pos)))
11061 (while (and node (not (js2-function-node-p node)))
11062 (setq node (js2-node-parent node)))
11063 (if (js2-function-node-p node)
11064 node)))
11065
11066 (defun js2-mode-toggle-element ()
11067 "Hide or show the foldable element at the point."
11068 (interactive)
11069 (let (comment fn pos)
11070 (save-excursion
11071 (save-match-data
11072 (cond
11073 ;; /* ... */ comment?
11074 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11075 (if (js2-mode-invisible-overlay-bounds
11076 (setq pos (+ 3 (js2-node-abs-pos comment))))
11077 (progn
11078 (goto-char pos)
11079 (js2-mode-show-element))
11080 (js2-mode-hide-element)))
11081 ;; //-comment?
11082 ((save-excursion
11083 (back-to-indentation)
11084 (looking-at js2-mode-//-comment-re))
11085 (js2-mode-toggle-//-comment))
11086 ;; function?
11087 ((setq fn (js2-mode-function-at-point))
11088 (setq pos (and (js2-function-node-body fn)
11089 (js2-node-abs-pos (js2-function-node-body fn))))
11090 (goto-char (1+ pos))
11091 (if (js2-mode-invisible-overlay-bounds)
11092 (js2-mode-show-element)
11093 (js2-mode-hide-element)))
11094 (t
11095 (message "Nothing at point to hide or show")))))))
11096
11097 (defun js2-mode-hide-element ()
11098 "Fold/hide contents of a block, showing ellipses.
11099 Show the hidden text with \\[js2-mode-show-element]."
11100 (interactive)
11101 (if js2-mode-buffer-dirty-p
11102 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11103 (let (node body beg end)
11104 (cond
11105 ((js2-mode-invisible-overlay-bounds)
11106 (message "already hidden"))
11107 (t
11108 (setq node (js2-node-at-point))
11109 (cond
11110 ((js2-block-comment-p node)
11111 (js2-mode-hide-comment node))
11112 (t
11113 (while (and node (not (js2-function-node-p node)))
11114 (setq node (js2-node-parent node)))
11115 (if (and node
11116 (setq body (js2-function-node-body node)))
11117 (progn
11118 (setq beg (js2-node-abs-pos body)
11119 end (+ beg (js2-node-len body)))
11120 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11121 (message "No collapsable element found at point"))))))))
11122
11123 (defun js2-mode-show-element ()
11124 "Show the hidden element at current point."
11125 (interactive)
11126 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11127 (if bounds
11128 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11129 (message "Nothing to un-hide"))))
11130
11131 (defun js2-mode-show-all ()
11132 "Show all of the text in the buffer."
11133 (interactive)
11134 (js2-mode-flag-region (point-min) (point-max) nil))
11135
11136 (defun js2-mode-toggle-hide-functions ()
11137 (interactive)
11138 (if js2-mode-functions-hidden
11139 (js2-mode-show-functions)
11140 (js2-mode-hide-functions)))
11141
11142 (defun js2-mode-hide-functions ()
11143 "Hides all non-nested function bodies in the buffer.
11144 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11145 to open an individual entry."
11146 (interactive)
11147 (if js2-mode-buffer-dirty-p
11148 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11149 (if (null js2-mode-ast)
11150 (message "Oops - parsing failed")
11151 (setq js2-mode-functions-hidden t)
11152 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11153
11154 (defun js2-mode-function-hider (n endp)
11155 (when (not endp)
11156 (let ((tt (js2-node-type n))
11157 body beg end)
11158 (cond
11159 ((and (= tt js2-FUNCTION)
11160 (setq body (js2-function-node-body n)))
11161 (setq beg (js2-node-abs-pos body)
11162 end (+ beg (js2-node-len body)))
11163 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11164 nil) ; don't process children of function
11165 (t
11166 t))))) ; keep processing other AST nodes
11167
11168 (defun js2-mode-show-functions ()
11169 "Un-hide any folded function bodies in the buffer."
11170 (interactive)
11171 (setq js2-mode-functions-hidden nil)
11172 (save-excursion
11173 (goto-char (point-min))
11174 (while (/= (goto-char (next-overlay-change (point)))
11175 (point-max))
11176 (dolist (o (overlays-at (point)))
11177 (when (and (overlay-get o 'invisible)
11178 (not (overlay-get o 'comment)))
11179 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11180
11181 (defun js2-mode-hide-comment (n)
11182 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11183 3 ; /**
11184 2)) ; /*
11185 (beg (+ (js2-node-abs-pos n) head))
11186 (end (- (+ beg (js2-node-len n)) head 2))
11187 (o (js2-mode-flag-region beg end 'hide)))
11188 (overlay-put o 'comment t)))
11189
11190 (defun js2-mode-toggle-hide-comments ()
11191 "Folds all block comments in the buffer.
11192 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11193 to open an individual entry."
11194 (interactive)
11195 (if js2-mode-comments-hidden
11196 (js2-mode-show-comments)
11197 (js2-mode-hide-comments)))
11198
11199 (defun js2-mode-hide-comments ()
11200 (interactive)
11201 (if js2-mode-buffer-dirty-p
11202 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11203 (if (null js2-mode-ast)
11204 (message "Oops - parsing failed")
11205 (setq js2-mode-comments-hidden t)
11206 (dolist (n (js2-ast-root-comments js2-mode-ast))
11207 (let ((format (js2-comment-node-format n)))
11208 (when (js2-block-comment-p n)
11209 (js2-mode-hide-comment n))))
11210 (js2-mode-hide-//-comments)))
11211
11212 (defsubst js2-mode-extend-//-comment (direction)
11213 "Find start or end of a block of similar //-comment lines.
11214 DIRECTION is -1 to look back, 1 to look forward.
11215 INDENT is the indentation level to match.
11216 Returns the end-of-line position of the furthest adjacent
11217 //-comment line with the same indentation as the current line.
11218 If there is no such matching line, returns current end of line."
11219 (let ((pos (point-at-eol))
11220 (indent (current-indentation)))
11221 (save-excursion
11222 (save-match-data
11223 (while (and (zerop (forward-line direction))
11224 (looking-at js2-mode-//-comment-re)
11225 (eq indent (length (match-string 1))))
11226 (setq pos (point-at-eol)))
11227 pos))))
11228
11229 (defun js2-mode-hide-//-comments ()
11230 "Fold adjacent 1-line comments, showing only snippet of first one."
11231 (let (beg end)
11232 (save-excursion
11233 (save-match-data
11234 (goto-char (point-min))
11235 (while (re-search-forward js2-mode-//-comment-re nil t)
11236 (setq beg (point)
11237 end (js2-mode-extend-//-comment 1))
11238 (unless (eq beg end)
11239 (overlay-put (js2-mode-flag-region beg end 'hide)
11240 'comment t))
11241 (goto-char end)
11242 (forward-char 1))))))
11243
11244 (defun js2-mode-toggle-//-comment ()
11245 "Fold or un-fold any multi-line //-comment at point.
11246 Caller should have determined that this line starts with a //-comment."
11247 (let* ((beg (point-at-eol))
11248 (end beg))
11249 (save-excursion
11250 (goto-char end)
11251 (if (js2-mode-invisible-overlay-bounds)
11252 (js2-mode-show-element)
11253 ;; else hide the comment
11254 (setq beg (js2-mode-extend-//-comment -1)
11255 end (js2-mode-extend-//-comment 1))
11256 (unless (eq beg end)
11257 (overlay-put (js2-mode-flag-region beg end 'hide)
11258 'comment t))))))
11259
11260 (defun js2-mode-show-comments ()
11261 "Un-hide any hidden comments, leaving other hidden elements alone."
11262 (interactive)
11263 (setq js2-mode-comments-hidden nil)
11264 (save-excursion
11265 (goto-char (point-min))
11266 (while (/= (goto-char (next-overlay-change (point)))
11267 (point-max))
11268 (dolist (o (overlays-at (point)))
11269 (when (overlay-get o 'comment)
11270 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11271
11272 (defun js2-mode-display-warnings-and-errors ()
11273 "Turn on display of warnings and errors."
11274 (interactive)
11275 (setq js2-mode-show-parse-errors t
11276 js2-mode-show-strict-warnings t)
11277 (js2-reparse 'force))
11278
11279 (defun js2-mode-hide-warnings-and-errors ()
11280 "Turn off display of warnings and errors."
11281 (interactive)
11282 (setq js2-mode-show-parse-errors nil
11283 js2-mode-show-strict-warnings nil)
11284 (js2-reparse 'force))
11285
11286 (defun js2-mode-toggle-warnings-and-errors ()
11287 "Toggle the display of warnings and errors.
11288 Some users don't like having warnings/errors reported while they type."
11289 (interactive)
11290 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11291 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11292 (if (interactive-p)
11293 (message "warnings and errors %s"
11294 (if js2-mode-show-parse-errors
11295 "enabled"
11296 "disabled")))
11297 (js2-reparse 'force))
11298
11299 (defun js2-mode-customize ()
11300 (interactive)
11301 (customize-group 'js2-mode))
11302
11303 (defun js2-mode-forward-sexp (&optional arg)
11304 "Move forward across one statement or balanced expression.
11305 With ARG, do it that many times. Negative arg -N means
11306 move backward across N balanced expressions."
11307 (interactive "p")
11308 (setq arg (or arg 1))
11309 (if js2-mode-buffer-dirty-p
11310 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11311 (let (node end (start (point)))
11312 (cond
11313 ;; backward-sexp
11314 ;; could probably make this better for some cases:
11315 ;; - if in statement block (e.g. function body), go to parent
11316 ;; - infix exprs like (foo in bar) - maybe go to beginning
11317 ;; of infix expr if in the right-side expression?
11318 ((and arg (minusp arg))
11319 (dotimes (i (- arg))
11320 (js2-backward-sws)
11321 (forward-char -1) ; enter the node we backed up to
11322 (setq node (js2-node-at-point (point) t))
11323 (goto-char (if node
11324 (js2-node-abs-pos node)
11325 (point-min)))))
11326 (t
11327 ;; forward-sexp
11328 (js2-forward-sws)
11329 (dotimes (i arg)
11330 (js2-forward-sws)
11331 (setq node (js2-node-at-point (point) t)
11332 end (if node (+ (js2-node-abs-pos node)
11333 (js2-node-len node))))
11334 (goto-char (or end (point-max))))))))
11335
11336 (defun js2-next-error (&optional arg reset)
11337 "Move to next parse error.
11338 Typically invoked via \\[next-error].
11339 ARG is the number of errors, forward or backward, to move.
11340 RESET means start over from the beginning."
11341 (interactive "p")
11342 (if (or (null js2-mode-ast)
11343 (and (null (js2-ast-root-errors js2-mode-ast))
11344 (null (js2-ast-root-warnings js2-mode-ast))))
11345 (message "No errors")
11346 (when reset
11347 (goto-char (point-min)))
11348 (let* ((errs (copy-sequence
11349 (append (js2-ast-root-errors js2-mode-ast)
11350 (js2-ast-root-warnings js2-mode-ast))))
11351 (continue t)
11352 (start (point))
11353 (count (or arg 1))
11354 (backward (minusp count))
11355 (sorter (if backward '> '<))
11356 (stopper (if backward '< '>))
11357 (count (abs count))
11358 all-errs
11359 err)
11360 ;; sort by start position
11361 (setq errs (sort errs (lambda (e1 e2)
11362 (funcall sorter (second e1) (second e2))))
11363 all-errs errs)
11364 ;; find nth error with pos > start
11365 (while (and errs continue)
11366 (when (funcall stopper (cadar errs) start)
11367 (setq err (car errs))
11368 (if (zerop (decf count))
11369 (setq continue nil)))
11370 (setq errs (cdr errs)))
11371 (if err
11372 (goto-char (second err))
11373 ;; wrap around to first error
11374 (goto-char (second (car all-errs)))
11375 ;; if we were already on it, echo msg again
11376 (if (= (point) start)
11377 (js2-echo-error (point) (point)))))))
11378
11379 (defun js2-down-mouse-3 ()
11380 "Make right-click move the point to the click location.
11381 This makes right-click context menu operations a bit more intuitive.
11382 The point will not move if the region is active, however, to avoid
11383 destroying the region selection."
11384 (interactive)
11385 (when (and js2-move-point-on-right-click
11386 (not mark-active))
11387 (let ((e last-input-event))
11388 (ignore-errors
11389 (goto-char (cadadr e))))))
11390
11391 (defun js2-mode-create-imenu-index ()
11392 "Return an alist for `imenu--index-alist'."
11393 ;; This is built up in `js2-parse-record-imenu' during parsing.
11394 (when js2-mode-ast
11395 ;; if we have an ast but no recorder, they're requesting a rescan
11396 (unless js2-imenu-recorder
11397 (js2-reparse 'force))
11398 (prog1
11399 (js2-build-imenu-index)
11400 (setq js2-imenu-recorder nil
11401 js2-imenu-function-map nil))))
11402
11403 (defun js2-mode-find-tag ()
11404 "Replacement for `find-tag-default'.
11405 `find-tag-default' returns a ridiculous answer inside comments."
11406 (let (beg end)
11407 (js2-with-underscore-as-word-syntax
11408 (save-excursion
11409 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11410 (looking-back "[A-Za-z0-9_$]"))
11411 (setq beg (progn (forward-word -1) (point))
11412 end (progn (forward-word 1) (point)))
11413 (setq beg (progn (forward-word 1) (point))
11414 end (progn (forward-word -1) (point))))
11415 (replace-regexp-in-string
11416 "[\"']" ""
11417 (buffer-substring-no-properties beg end))))))
11418
11419 (defun js2-mode-forward-sibling ()
11420 "Move to the end of the sibling following point in parent.
11421 Returns non-nil if successful, or nil if there was no following sibling."
11422 (let* ((node (js2-node-at-point))
11423 (parent (js2-mode-find-enclosing-fn node))
11424 sib)
11425 (when (setq sib (js2-node-find-child-after (point) parent))
11426 (goto-char (+ (js2-node-abs-pos sib)
11427 (js2-node-len sib))))))
11428
11429 (defun js2-mode-backward-sibling ()
11430 "Move to the beginning of the sibling node preceding point in parent.
11431 Parent is defined as the enclosing script or function."
11432 (let* ((node (js2-node-at-point))
11433 (parent (js2-mode-find-enclosing-fn node))
11434 sib)
11435 (when (setq sib (js2-node-find-child-before (point) parent))
11436 (goto-char (js2-node-abs-pos sib)))))
11437
11438 (defun js2-beginning-of-defun ()
11439 "Go to line on which current function starts, and return non-nil.
11440 If we're not in a function, go to beginning of previous script-level element."
11441 (interactive)
11442 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11443 pos sib)
11444 (cond
11445 ((and (js2-function-node-p parent)
11446 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11447 (goto-char pos))
11448 (t
11449 (js2-mode-backward-sibling)))))
11450
11451 (defun js2-end-of-defun ()
11452 "Go to the char after the last position of the current function.
11453 If we're not in a function, skips over the next script-level element."
11454 (interactive)
11455 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11456 (if (not (js2-function-node-p parent))
11457 ;; punt: skip over next script-level element beyond point
11458 (js2-mode-forward-sibling)
11459 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11460 (js2-node-len parent)))))))
11461
11462 (defun js2-mark-defun (&optional allow-extend)
11463 "Put mark at end of this function, point at beginning.
11464 The function marked is the one that contains point.
11465
11466 Interactively, if this command is repeated,
11467 or (in Transient Mark mode) if the mark is active,
11468 it marks the next defun after the ones already marked."
11469 (interactive "p")
11470 (let (extended)
11471 (when (and allow-extend
11472 (or (and (eq last-command this-command) (mark t))
11473 (and transient-mark-mode mark-active)))
11474 (let ((sib (save-excursion
11475 (goto-char (mark))
11476 (if (js2-mode-forward-sibling)
11477 (point))))
11478 node)
11479 (if sib
11480 (progn
11481 (set-mark sib)
11482 (setq extended t))
11483 ;; no more siblings - try extending to enclosing node
11484 (goto-char (mark t)))))
11485 (when (not extended)
11486 (let ((node (js2-node-at-point (point) t)) ; skip comments
11487 ast fn stmt parent beg end)
11488 (when (js2-ast-root-p node)
11489 (setq ast node
11490 node (or (js2-node-find-child-after (point) node)
11491 (js2-node-find-child-before (point) node))))
11492 ;; only mark whole buffer if we can't find any children
11493 (if (null node)
11494 (setq node ast))
11495 (if (js2-function-node-p node)
11496 (setq parent node)
11497 (setq fn (js2-mode-find-enclosing-fn node)
11498 stmt (if (or (null fn)
11499 (js2-ast-root-p fn))
11500 (js2-mode-find-first-stmt node))
11501 parent (or stmt fn)))
11502 (setq beg (js2-node-abs-pos parent)
11503 end (+ beg (js2-node-len parent)))
11504 (push-mark beg)
11505 (goto-char end)
11506 (exchange-point-and-mark)))))
11507
11508 (defun js2-narrow-to-defun ()
11509 "Narrow to the function enclosing point."
11510 (interactive)
11511 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11512 (fn (if (js2-script-node-p node)
11513 node
11514 (js2-mode-find-enclosing-fn node)))
11515 (beg (js2-node-abs-pos fn)))
11516 (unless (js2-ast-root-p fn)
11517 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11518
11519 (provide 'js2-mode)
11520
11521 ;;; js2-mode.el ends here