]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Make comment-* vars buffer-local
[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 (defsubst js2-record-text-property (beg end prop value)
2028 "Record a text property to set when parsing finishes."
2029 (push (list beg end prop value) js2-mode-deferred-properties))
2030
2031 ;; I'd like to associate errors with nodes, but for now the
2032 ;; easiest thing to do is get the context info from the last token.
2033 (defsubst js2-record-parse-error (msg &optional arg pos len)
2034 (push (list (list msg arg)
2035 (or pos js2-token-beg)
2036 (or len (- js2-token-end js2-token-beg)))
2037 js2-parsed-errors))
2038
2039 (defsubst js2-report-error (msg &optional msg-arg pos len)
2040 "Signal a syntax error or record a parse error."
2041 (if js2-recover-from-parse-errors
2042 (js2-record-parse-error msg msg-arg pos len)
2043 (signal 'js2-syntax-error
2044 (list msg
2045 js2-ts-lineno
2046 (save-excursion
2047 (goto-char js2-ts-cursor)
2048 (current-column))
2049 js2-ts-hit-eof))))
2050
2051 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2052 (if js2-compiler-report-warning-as-error
2053 (js2-report-error msg msg-arg pos len)
2054 (push (list (list msg msg-arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2057 js2-parsed-warnings)))
2058
2059 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2060 (if js2-compiler-strict-mode
2061 (js2-report-warning msg-id msg-arg beg
2062 (and beg end (- end beg)))))
2063
2064 (put 'js2-syntax-error 'error-conditions
2065 '(error syntax-error js2-syntax-error))
2066 (put 'js2-syntax-error 'error-message "Syntax error")
2067
2068 (put 'js2-parse-error 'error-conditions
2069 '(error parse-error js2-parse-error))
2070 (put 'js2-parse-error 'error-message "Parse error")
2071
2072 (defmacro js2-clear-flag (flags flag)
2073 `(setq ,flags (logand ,flags (lognot ,flag))))
2074
2075 (defmacro js2-set-flag (flags flag)
2076 "Logical-or FLAG into FLAGS."
2077 `(setq ,flags (logior ,flags ,flag)))
2078
2079 (defsubst js2-flag-set-p (flags flag)
2080 (/= 0 (logand flags flag)))
2081
2082 (defsubst js2-flag-not-set-p (flags flag)
2083 (zerop (logand flags flag)))
2084
2085 ;; Stolen shamelessly from James Clark's nxml-mode.
2086 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2087 "Evaluate BODY without any text property changes modifying the buffer.
2088 Any text properties changes happen as usual but the changes are not treated as
2089 modifications to the buffer."
2090 (declare (indent 0) (debug t))
2091 (let ((modified (make-symbol "modified")))
2092 `(let ((,modified (buffer-modified-p))
2093 (inhibit-read-only t)
2094 (inhibit-modification-hooks t)
2095 (buffer-undo-list t)
2096 (deactivate-mark nil)
2097 ;; Apparently these avoid file locking problems.
2098 (buffer-file-name nil)
2099 (buffer-file-truename nil))
2100 (unwind-protect
2101 (progn ,@body)
2102 (unless ,modified
2103 (restore-buffer-modified-p nil))))))
2104
2105 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2106 "Evaluate BODY with the _ character set to be word-syntax."
2107 (declare (indent 0) (debug t))
2108 (let ((old-syntax (make-symbol "old-syntax")))
2109 `(let ((,old-syntax (string (char-syntax ?_))))
2110 (unwind-protect
2111 (progn
2112 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2113 ,@body)
2114 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2115
2116 (defsubst js2-char-uppercase-p (c)
2117 "Return t if C is an uppercase character.
2118 Handles unicode and latin chars properly."
2119 (/= c (downcase c)))
2120
2121 (defsubst js2-char-lowercase-p (c)
2122 "Return t if C is an uppercase character.
2123 Handles unicode and latin chars properly."
2124 (/= c (upcase c)))
2125
2126 ;;; AST struct and function definitions
2127
2128 ;; flags for ast node property 'member-type (used for e4x operators)
2129 (defvar js2-property-flag #x1 "property access: element is valid name")
2130 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2131 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2132
2133 (defsubst js2-relpos (pos anchor)
2134 "Convert POS to be relative to ANCHOR.
2135 If POS is nil, returns nil."
2136 (and pos (- pos anchor)))
2137
2138 (defsubst js2-make-pad (indent)
2139 (if (zerop indent)
2140 ""
2141 (make-string (* indent js2-basic-offset) ? )))
2142
2143 (defsubst js2-visit-ast (node callback)
2144 "Visit every node in ast NODE with visitor CALLBACK.
2145
2146 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2147 called twice: once to visit the node, and again after all the node's
2148 children have been processed. The END-P argument is nil on the first
2149 call and non-nil on the second call. The return value of the callback
2150 affects the traversal: if non-nil, the children of NODE are processed.
2151 If the callback returns nil, or if the node has no children, then the
2152 callback is called immediately with a non-nil END-P argument.
2153
2154 The node traversal is approximately lexical-order, although there
2155 are currently no guarantees around this."
2156 (if node
2157 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2158 ;; visit the node
2159 (when (funcall callback node nil)
2160 ;; visit the kids
2161 (cond
2162 ((eq vfunc 'js2-visit-none)
2163 nil) ; don't even bother calling it
2164 ;; Each AST node type has to define a `js2-visitor' function
2165 ;; that takes a node and a callback, and calls `js2-visit-ast'
2166 ;; on each child of the node.
2167 (vfunc
2168 (funcall vfunc node callback))
2169 (t
2170 (error "%s does not define a visitor-traversal function"
2171 (aref node 0)))))
2172 ;; call the end-visit
2173 (funcall callback node t))))
2174
2175 (defstruct (js2-node
2176 (:constructor nil)) ; abstract
2177 "Base AST node type."
2178 (type -1) ; token type
2179 (pos -1) ; start position of this AST node in parsed input
2180 (len 1) ; num characters spanned by the node
2181 props ; optional node property list (an alist)
2182 parent) ; link to parent node; null for root
2183
2184 (defsubst js2-node-get-prop (node prop &optional default)
2185 (or (cadr (assoc prop (js2-node-props node))) default))
2186
2187 (defsubst js2-node-set-prop (node prop value)
2188 (setf (js2-node-props node)
2189 (cons (list prop value) (js2-node-props node))))
2190
2191 (defsubst js2-fixup-starts (n nodes)
2192 "Adjust the start positions of NODES to be relative to N.
2193 Any node in the list may be nil, for convenience."
2194 (dolist (node nodes)
2195 (when node
2196 (setf (js2-node-pos node) (- (js2-node-pos node)
2197 (js2-node-pos n))))))
2198
2199 (defsubst js2-node-add-children (parent &rest nodes)
2200 "Set parent node of NODES to PARENT, and return PARENT.
2201 Does nothing if we're not recording parent links.
2202 If any given node in NODES is nil, doesn't record that link."
2203 (js2-fixup-starts parent nodes)
2204 (dolist (node nodes)
2205 (and node
2206 (setf (js2-node-parent node) parent))))
2207
2208 ;; Non-recursive since it's called a frightening number of times.
2209 (defsubst js2-node-abs-pos (n)
2210 (let ((pos (js2-node-pos n)))
2211 (while (setq n (js2-node-parent n))
2212 (setq pos (+ pos (js2-node-pos n))))
2213 pos))
2214
2215 (defsubst js2-node-abs-end (n)
2216 "Return absolute buffer position of end of N."
2217 (+ (js2-node-abs-pos n) (js2-node-len n)))
2218
2219 ;; It's important to make sure block nodes have a lisp list for the
2220 ;; child nodes, to limit printing recursion depth in an AST that
2221 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2222 ;; a sufficiently large vector tree.
2223
2224 (defstruct (js2-block-node
2225 (:include js2-node)
2226 (:constructor nil)
2227 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2228 (pos js2-token-beg)
2229 len
2230 props
2231 kids)))
2232 "A block of statements."
2233 kids) ; a lisp list of the child statement nodes
2234
2235 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2236 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2237
2238 (defsubst js2-visit-block (ast callback)
2239 "Visit the `js2-block-node' children of AST."
2240 (dolist (kid (js2-block-node-kids ast))
2241 (js2-visit-ast kid callback)))
2242
2243 (defun js2-print-block (n i)
2244 (let ((pad (js2-make-pad i)))
2245 (insert pad "{\n")
2246 (dolist (kid (js2-block-node-kids n))
2247 (js2-print-ast kid (1+ i)))
2248 (insert pad "}")))
2249
2250 (defstruct (js2-scope
2251 (:include js2-block-node)
2252 (:constructor nil)
2253 (:constructor make-js2-scope (&key (type js2-BLOCK)
2254 (pos js2-token-beg)
2255 len
2256 kids)))
2257 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2258 ;; I don't have one of those handy, so I'll use an alist for now.
2259 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2260 ;; and is much lighter-weight to construct (both CPU and mem).
2261 ;; The keys are interned strings (symbols) for faster lookup.
2262 ;; Should switch to hybrid alist/hashtable eventually.
2263 symbol-table ; an alist of (symbol . js2-symbol)
2264 parent-scope ; a `js2-scope'
2265 top) ; top-level `js2-scope' (script/function)
2266
2267 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2268 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2269
2270 (defun js2-scope-set-parent-scope (scope parent)
2271 (setf (js2-scope-parent-scope scope) parent
2272 (js2-scope-top scope) (if (null parent)
2273 scope
2274 (js2-scope-top parent))))
2275
2276 (defun js2-node-get-enclosing-scope (node)
2277 "Return the innermost `js2-scope' node surrounding NODE.
2278 Returns nil if there is no enclosing scope node."
2279 (let ((parent (js2-node-parent node)))
2280 (while (not (js2-scope-p parent))
2281 (setq parent (js2-node-parent parent)))
2282 parent))
2283
2284 (defun js2-get-defining-scope (scope name)
2285 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2286 Returns `js2-scope' in which NAME is defined, or nil if not found."
2287 (let ((sym (if (symbolp name)
2288 name
2289 (intern name)))
2290 table
2291 result
2292 (continue t))
2293 (while (and scope continue)
2294 (if (and (setq table (js2-scope-symbol-table scope))
2295 (assq sym table))
2296 (setq continue nil
2297 result scope)
2298 (setq scope (js2-scope-parent-scope scope))))
2299 result))
2300
2301 (defsubst js2-scope-get-symbol (scope name)
2302 "Return symbol table entry for NAME in SCOPE.
2303 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2304 (and (js2-scope-symbol-table scope)
2305 (cdr (assq (if (symbolp name)
2306 name
2307 (intern name))
2308 (js2-scope-symbol-table scope)))))
2309
2310 (defsubst js2-scope-put-symbol (scope name symbol)
2311 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2312 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2313 (let* ((table (js2-scope-symbol-table scope))
2314 (sym (if (symbolp name) name (intern name)))
2315 (entry (assq sym table)))
2316 (if entry
2317 (setcdr entry symbol)
2318 (push (cons sym symbol)
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defstruct (js2-symbol
2322 (:constructor nil)
2323 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2324 "A symbol table entry."
2325 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2326 ;; js2-LET, or js2-CONST
2327 decl-type
2328 name ; string
2329 ast-node) ; a `js2-node'
2330
2331 (defstruct (js2-error-node
2332 (:include js2-node)
2333 (:constructor nil) ; silence emacs21 byte-compiler
2334 (:constructor make-js2-error-node (&key (type js2-ERROR)
2335 (pos js2-token-beg)
2336 len)))
2337 "AST node representing a parse error.")
2338
2339 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2340 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2341
2342 (defstruct (js2-script-node
2343 (:include js2-scope)
2344 (:constructor nil)
2345 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2346 (pos js2-token-beg)
2347 len
2348 var-decls
2349 fun-decls)))
2350 functions ; lisp list of nested functions
2351 regexps ; lisp list of (string . flags)
2352 symbols ; alist (every symbol gets unique index)
2353 (param-count 0)
2354 var-names ; vector of string names
2355 consts ; bool-vector matching var-decls
2356 (temp-number 0)) ; for generating temp variables
2357
2358 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2359 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2360
2361 (defun js2-print-script (node indent)
2362 (dolist (kid (js2-block-node-kids node))
2363 (js2-print-ast kid indent)))
2364
2365 (defstruct (js2-ast-root
2366 (:include js2-script-node)
2367 (:constructor nil)
2368 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2369 (pos js2-token-beg)
2370 len
2371 buffer)))
2372 "The root node of a js2 AST."
2373 buffer ; the source buffer from which the code was parsed
2374 comments ; a lisp list of comments, ordered by start position
2375 errors ; a lisp list of errors found during parsing
2376 warnings ; a lisp list of warnings found during parsing
2377 node-count) ; number of nodes in the tree, including the root
2378
2379 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2380 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2381
2382 (defun js2-visit-ast-root (ast callback)
2383 (dolist (kid (js2-ast-root-kids ast))
2384 (js2-visit-ast kid callback))
2385 (dolist (comment (js2-ast-root-comments ast))
2386 (js2-visit-ast comment callback)))
2387
2388 (defstruct (js2-comment-node
2389 (:include js2-node)
2390 (:constructor nil)
2391 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2392 (pos js2-token-beg)
2393 len
2394 (format js2-ts-comment-type))))
2395 format) ; 'line, 'block, 'jsdoc or 'html
2396
2397 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2398 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2399
2400 (defun js2-print-comment (n i)
2401 ;; We really ought to link end-of-line comments to their nodes.
2402 ;; Or maybe we could add a new comment type, 'endline.
2403 (insert (js2-make-pad i)
2404 (js2-node-string n)))
2405
2406 (defstruct (js2-expr-stmt-node
2407 (:include js2-node)
2408 (:constructor nil)
2409 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2410 (pos js2-ts-cursor)
2411 len
2412 expr)))
2413 "An expression statement."
2414 expr)
2415
2416 (defsubst js2-expr-stmt-node-set-has-result (node)
2417 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2418 (setf (js2-node-type node) js2-EXPR_RESULT))
2419
2420 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2421 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2422
2423 (defun js2-visit-expr-stmt-node (n v)
2424 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2425
2426 (defun js2-print-expr-stmt-node (n indent)
2427 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2428 (insert ";\n"))
2429
2430 (defstruct (js2-loop-node
2431 (:include js2-scope)
2432 (:constructor nil))
2433 "Abstract supertype of loop nodes."
2434 body ; a `js2-block-node'
2435 lp ; position of left-paren, nil if omitted
2436 rp) ; position of right-paren, nil if omitted
2437
2438 (defstruct (js2-do-node
2439 (:include js2-loop-node)
2440 (:constructor nil)
2441 (:constructor make-js2-do-node (&key (type js2-DO)
2442 (pos js2-token-beg)
2443 len
2444 body
2445 condition
2446 while-pos
2447 lp
2448 rp)))
2449 "AST node for do-loop."
2450 condition ; while (expression)
2451 while-pos) ; buffer position of 'while' keyword
2452
2453 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2454 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2455
2456 (defun js2-visit-do-node (n v)
2457 (js2-visit-ast (js2-do-node-body n) v)
2458 (js2-visit-ast (js2-do-node-condition n) v))
2459
2460 (defun js2-print-do-node (n i)
2461 (let ((pad (js2-make-pad i)))
2462 (insert pad "do {\n")
2463 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2464 (js2-print-ast kid (1+ i)))
2465 (insert pad "} while (")
2466 (js2-print-ast (js2-do-node-condition n) 0)
2467 (insert ");\n")))
2468
2469 (defstruct (js2-while-node
2470 (:include js2-loop-node)
2471 (:constructor nil)
2472 (:constructor make-js2-while-node (&key (type js2-WHILE)
2473 (pos js2-token-beg)
2474 len
2475 body
2476 condition
2477 lp
2478 rp)))
2479 "AST node for while-loop."
2480 condition) ; while-condition
2481
2482 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2483 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2484
2485 (defun js2-visit-while-node (n v)
2486 (js2-visit-ast (js2-while-node-condition n) v)
2487 (js2-visit-ast (js2-while-node-body n) v))
2488
2489 (defun js2-print-while-node (n i)
2490 (let ((pad (js2-make-pad i)))
2491 (insert pad "while (")
2492 (js2-print-ast (js2-while-node-condition n) 0)
2493 (insert ") {\n")
2494 (js2-print-body (js2-while-node-body n) (1+ i))
2495 (insert pad "}\n")))
2496
2497 (defstruct (js2-for-node
2498 (:include js2-loop-node)
2499 (:constructor nil)
2500 (:constructor make-js2-for-node (&key (type js2-FOR)
2501 (pos js2-ts-cursor)
2502 len
2503 body
2504 init
2505 condition
2506 update
2507 lp
2508 rp)))
2509 "AST node for a C-style for-loop."
2510 init ; initialization expression
2511 condition ; loop condition
2512 update) ; update clause
2513
2514 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2515 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2516
2517 (defun js2-visit-for-node (n v)
2518 (js2-visit-ast (js2-for-node-init n) v)
2519 (js2-visit-ast (js2-for-node-condition n) v)
2520 (js2-visit-ast (js2-for-node-update n) v)
2521 (js2-visit-ast (js2-for-node-body n) v))
2522
2523 (defun js2-print-for-node (n i)
2524 (let ((pad (js2-make-pad i)))
2525 (insert pad "for (")
2526 (js2-print-ast (js2-for-node-init n) 0)
2527 (insert "; ")
2528 (js2-print-ast (js2-for-node-condition n) 0)
2529 (insert "; ")
2530 (js2-print-ast (js2-for-node-update n) 0)
2531 (insert ") {\n")
2532 (js2-print-body (js2-for-node-body n) (1+ i))
2533 (insert pad "}\n")))
2534
2535 (defstruct (js2-for-in-node
2536 (:include js2-loop-node)
2537 (:constructor nil)
2538 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2539 (pos js2-ts-cursor)
2540 len
2541 body
2542 iterator
2543 object
2544 in-pos
2545 each-pos
2546 foreach-p
2547 lp
2548 rp)))
2549 "AST node for a for..in loop."
2550 iterator ; [var] foo in ...
2551 object ; object over which we're iterating
2552 in-pos ; buffer position of 'in' keyword
2553 each-pos ; buffer position of 'each' keyword, if foreach-p
2554 foreach-p) ; t if it's a for-each loop
2555
2556 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2557 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2558
2559 (defun js2-visit-for-in-node (n v)
2560 (js2-visit-ast (js2-for-in-node-iterator n) v)
2561 (js2-visit-ast (js2-for-in-node-object n) v)
2562 (js2-visit-ast (js2-for-in-node-body n) v))
2563
2564 (defun js2-print-for-in-node (n i)
2565 (let ((pad (js2-make-pad i))
2566 (foreach (js2-for-in-node-foreach-p n)))
2567 (insert pad "for ")
2568 (if foreach
2569 (insert "each "))
2570 (insert "(")
2571 (js2-print-ast (js2-for-in-node-iterator n) 0)
2572 (insert " in ")
2573 (js2-print-ast (js2-for-in-node-object n) 0)
2574 (insert ") {\n")
2575 (js2-print-body (js2-for-in-node-body n) (1+ i))
2576 (insert pad "}\n")))
2577
2578 (defstruct (js2-return-node
2579 (:include js2-node)
2580 (:constructor nil)
2581 (:constructor make-js2-return-node (&key (type js2-RETURN)
2582 (pos js2-ts-cursor)
2583 len
2584 retval)))
2585 "AST node for a return statement."
2586 retval) ; expression to return, or 'undefined
2587
2588 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2589 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2590
2591 (defun js2-visit-return-node (n v)
2592 (js2-visit-ast (js2-return-node-retval n) v))
2593
2594 (defun js2-print-return-node (n i)
2595 (insert (js2-make-pad i) "return")
2596 (when (js2-return-node-retval n)
2597 (insert " ")
2598 (js2-print-ast (js2-return-node-retval n) 0))
2599 (insert ";\n"))
2600
2601 (defstruct (js2-if-node
2602 (:include js2-node)
2603 (:constructor nil)
2604 (:constructor make-js2-if-node (&key (type js2-IF)
2605 (pos js2-ts-cursor)
2606 len
2607 condition
2608 then-part
2609 else-pos
2610 else-part
2611 lp
2612 rp)))
2613 "AST node for an if-statement."
2614 condition ; expression
2615 then-part ; statement or block
2616 else-pos ; optional buffer position of 'else' keyword
2617 else-part ; optional statement or block
2618 lp ; position of left-paren, nil if omitted
2619 rp) ; position of right-paren, nil if omitted
2620
2621 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2622 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2623
2624 (defun js2-visit-if-node (n v)
2625 (js2-visit-ast (js2-if-node-condition n) v)
2626 (js2-visit-ast (js2-if-node-then-part n) v)
2627 (js2-visit-ast (js2-if-node-else-part n) v))
2628
2629 (defun js2-print-if-node (n i)
2630 (let ((pad (js2-make-pad i))
2631 (then-part (js2-if-node-then-part n))
2632 (else-part (js2-if-node-else-part n)))
2633 (insert pad "if (")
2634 (js2-print-ast (js2-if-node-condition n) 0)
2635 (insert ") {\n")
2636 (js2-print-body then-part (1+ i))
2637 (insert pad "}")
2638 (cond
2639 ((not else-part)
2640 (insert "\n"))
2641 ((js2-if-node-p else-part)
2642 (insert " else ")
2643 (js2-print-body else-part i))
2644 (t
2645 (insert " else {\n")
2646 (js2-print-body else-part (1+ i))
2647 (insert pad "}\n")))))
2648
2649 (defstruct (js2-try-node
2650 (:include js2-node)
2651 (:constructor nil)
2652 (:constructor make-js2-try-node (&key (type js2-TRY)
2653 (pos js2-ts-cursor)
2654 len
2655 try-block
2656 catch-clauses
2657 finally-block)))
2658 "AST node for a try-statement."
2659 try-block
2660 catch-clauses ; a lisp list of `js2-catch-node'
2661 finally-block) ; a `js2-finally-node'
2662
2663 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2664 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2665
2666 (defun js2-visit-try-node (n v)
2667 (js2-visit-ast (js2-try-node-try-block n) v)
2668 (dolist (clause (js2-try-node-catch-clauses n))
2669 (js2-visit-ast clause v))
2670 (js2-visit-ast (js2-try-node-finally-block n) v))
2671
2672 (defun js2-print-try-node (n i)
2673 (let ((pad (js2-make-pad i))
2674 (catches (js2-try-node-catch-clauses n))
2675 (finally (js2-try-node-finally-block n)))
2676 (insert pad "try {\n")
2677 (js2-print-body (js2-try-node-try-block n) (1+ i))
2678 (insert pad "}")
2679 (when catches
2680 (dolist (catch catches)
2681 (js2-print-ast catch i)))
2682 (if finally
2683 (js2-print-ast finally i)
2684 (insert "\n"))))
2685
2686 (defstruct (js2-catch-node
2687 (:include js2-node)
2688 (:constructor nil)
2689 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2690 (pos js2-ts-cursor)
2691 len
2692 param
2693 guard-kwd
2694 guard-expr
2695 block
2696 lp
2697 rp)))
2698 "AST node for a catch clause."
2699 param ; destructuring form or simple name node
2700 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2701 guard-expr ; catch condition, a `js2-node'
2702 block ; statements, a `js2-block-node'
2703 lp ; buffer position of left-paren, nil if omitted
2704 rp) ; buffer position of right-paren, nil if omitted
2705
2706 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2707 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2708
2709 (defun js2-visit-catch-node (n v)
2710 (js2-visit-ast (js2-catch-node-param n) v)
2711 (when (js2-catch-node-guard-kwd n)
2712 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2713 (js2-visit-ast (js2-catch-node-block n) v))
2714
2715 (defun js2-print-catch-node (n i)
2716 (let ((pad (js2-make-pad i))
2717 (guard-kwd (js2-catch-node-guard-kwd n))
2718 (guard-expr (js2-catch-node-guard-expr n)))
2719 (insert " catch (")
2720 (js2-print-ast (js2-catch-node-param n) 0)
2721 (when guard-kwd
2722 (insert " if ")
2723 (js2-print-ast guard-expr 0))
2724 (insert ") {\n")
2725 (js2-print-body (js2-catch-node-block n) (1+ i))
2726 (insert pad "}")))
2727
2728 (defstruct (js2-finally-node
2729 (:include js2-node)
2730 (:constructor nil)
2731 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2732 (pos js2-ts-cursor)
2733 len
2734 body)))
2735 "AST node for a finally clause."
2736 body) ; a `js2-node', often but not always a block node
2737
2738 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2739 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2740
2741 (defun js2-visit-finally-node (n v)
2742 (js2-visit-ast (js2-finally-node-body n) v))
2743
2744 (defun js2-print-finally-node (n i)
2745 (let ((pad (js2-make-pad i)))
2746 (insert " finally {\n")
2747 (js2-print-body (js2-finally-node-body n) (1+ i))
2748 (insert pad "}\n")))
2749
2750 (defstruct (js2-switch-node
2751 (:include js2-node)
2752 (:constructor nil)
2753 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2754 (pos js2-ts-cursor)
2755 len
2756 discriminant
2757 cases
2758 lp
2759 rp)))
2760 "AST node for a switch statement."
2761 discriminant ; a `js2-node' (switch expression)
2762 cases ; a lisp list of `js2-case-node'
2763 lp ; position of open-paren for discriminant, nil if omitted
2764 rp) ; position of close-paren for discriminant, nil if omitted
2765
2766 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2767 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2768
2769 (defun js2-visit-switch-node (n v)
2770 (js2-visit-ast (js2-switch-node-discriminant n) v)
2771 (dolist (c (js2-switch-node-cases n))
2772 (js2-visit-ast c v)))
2773
2774 (defun js2-print-switch-node (n i)
2775 (let ((pad (js2-make-pad i))
2776 (cases (js2-switch-node-cases n)))
2777 (insert pad "switch (")
2778 (js2-print-ast (js2-switch-node-discriminant n) 0)
2779 (insert ") {\n")
2780 (dolist (case cases)
2781 (js2-print-ast case i))
2782 (insert pad "}\n")))
2783
2784 (defstruct (js2-case-node
2785 (:include js2-block-node)
2786 (:constructor nil)
2787 (:constructor make-js2-case-node (&key (type js2-CASE)
2788 (pos js2-ts-cursor)
2789 len
2790 kids
2791 expr)))
2792 "AST node for a case clause of a switch statement."
2793 expr) ; the case expression (nil for default)
2794
2795 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2796 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2797
2798 (defun js2-visit-case-node (n v)
2799 (js2-visit-ast (js2-case-node-expr n) v)
2800 (js2-visit-block n v))
2801
2802 (defun js2-print-case-node (n i)
2803 (let ((pad (js2-make-pad i))
2804 (expr (js2-case-node-expr n)))
2805 (insert pad)
2806 (if (null expr)
2807 (insert "default:\n")
2808 (insert "case ")
2809 (js2-print-ast expr 0)
2810 (insert ":\n"))
2811 (dolist (kid (js2-case-node-kids n))
2812 (js2-print-ast kid (1+ i)))))
2813
2814 (defstruct (js2-throw-node
2815 (:include js2-node)
2816 (:constructor nil)
2817 (:constructor make-js2-throw-node (&key (type js2-THROW)
2818 (pos js2-ts-cursor)
2819 len
2820 expr)))
2821 "AST node for a throw statement."
2822 expr) ; the expression to throw
2823
2824 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2825 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2826
2827 (defun js2-visit-throw-node (n v)
2828 (js2-visit-ast (js2-throw-node-expr n) v))
2829
2830 (defun js2-print-throw-node (n i)
2831 (insert (js2-make-pad i) "throw ")
2832 (js2-print-ast (js2-throw-node-expr n) 0)
2833 (insert ";\n"))
2834
2835 (defstruct (js2-with-node
2836 (:include js2-node)
2837 (:constructor nil)
2838 (:constructor make-js2-with-node (&key (type js2-WITH)
2839 (pos js2-ts-cursor)
2840 len
2841 object
2842 body
2843 lp
2844 rp)))
2845 "AST node for a with-statement."
2846 object
2847 body
2848 lp ; buffer position of left-paren around object, nil if omitted
2849 rp) ; buffer position of right-paren around object, nil if omitted
2850
2851 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2852 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2853
2854 (defun js2-visit-with-node (n v)
2855 (js2-visit-ast (js2-with-node-object n) v)
2856 (js2-visit-ast (js2-with-node-body n) v))
2857
2858 (defun js2-print-with-node (n i)
2859 (let ((pad (js2-make-pad i)))
2860 (insert pad "with (")
2861 (js2-print-ast (js2-with-node-object n) 0)
2862 (insert ") {\n")
2863 (js2-print-body (js2-with-node-body n) (1+ i))
2864 (insert pad "}\n")))
2865
2866 (defstruct (js2-label-node
2867 (:include js2-node)
2868 (:constructor nil)
2869 (:constructor make-js2-label-node (&key (type js2-LABEL)
2870 (pos js2-ts-cursor)
2871 len
2872 name)))
2873 "AST node for a statement label or case label."
2874 name ; a string
2875 loop) ; for validating and code-generating continue-to-label
2876
2877 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2878 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2879
2880 (defun js2-print-label (n i)
2881 (insert (js2-make-pad i)
2882 (js2-label-node-name n)
2883 ":\n"))
2884
2885 (defstruct (js2-labeled-stmt-node
2886 (:include js2-node)
2887 (:constructor nil)
2888 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2889 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2890 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2891 (pos js2-ts-cursor)
2892 len
2893 labels
2894 stmt)))
2895 "AST node for a statement with one or more labels.
2896 Multiple labels for a statement are collapsed into the labels field."
2897 labels ; lisp list of `js2-label-node'
2898 stmt) ; the statement these labels are for
2899
2900 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2901 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2902
2903 (defun js2-get-label-by-name (lbl-stmt name)
2904 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2905 Returns nil if no such label is in the list."
2906 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2907 result)
2908 (while (and label-list (not result))
2909 (if (string= (js2-label-node-name (car label-list)) name)
2910 (setq result (car label-list))
2911 (setq label-list (cdr label-list))))
2912 result))
2913
2914 (defun js2-visit-labeled-stmt (n v)
2915 (dolist (label (js2-labeled-stmt-node-labels n))
2916 (js2-visit-ast label v))
2917 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2918
2919 (defun js2-print-labeled-stmt (n i)
2920 (dolist (label (js2-labeled-stmt-node-labels n))
2921 (js2-print-ast label i))
2922 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2923
2924 (defun js2-labeled-stmt-node-contains (node label)
2925 "Return t if NODE contains LABEL in its label set.
2926 NODE is a `js2-labels-node'. LABEL is an identifier."
2927 (loop for nl in (js2-labeled-stmt-node-labels node)
2928 if (string= label (js2-label-node-name nl))
2929 return t
2930 finally return nil))
2931
2932 (defsubst js2-labeled-stmt-node-add-label (node label)
2933 "Add a `js2-label-node' to the label set for this statement."
2934 (setf (js2-labeled-stmt-node-labels node)
2935 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2936
2937 (defstruct (js2-jump-node
2938 (:include js2-node)
2939 (:constructor nil))
2940 "Abstract supertype of break and continue nodes."
2941 label ; `js2-name-node' for location of label identifier, if present
2942 target) ; target js2-labels-node or loop/switch statement
2943
2944 (defun js2-visit-jump-node (n v)
2945 (js2-visit-ast (js2-jump-node-label n) v))
2946
2947 (defstruct (js2-break-node
2948 (:include js2-jump-node)
2949 (:constructor nil)
2950 (:constructor make-js2-break-node (&key (type js2-BREAK)
2951 (pos js2-ts-cursor)
2952 len
2953 label
2954 target)))
2955 "AST node for a break statement.
2956 The label field is a `js2-name-node', possibly nil, for the named label
2957 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2958 is the target of the break - a label node or enclosing loop/switch statement.")
2959
2960 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2961 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2962
2963 (defun js2-print-break-node (n i)
2964 (insert (js2-make-pad i) "break")
2965 (when (js2-break-node-label n)
2966 (insert " ")
2967 (js2-print-ast (js2-break-node-label n) 0))
2968 (insert ";\n"))
2969
2970 (defstruct (js2-continue-node
2971 (:include js2-jump-node)
2972 (:constructor nil)
2973 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2974 (pos js2-ts-cursor)
2975 len
2976 label
2977 target)))
2978 "AST node for a continue statement.
2979 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2980 It is nil if continue specifies no label. The target field is the jump target:
2981 a `js2-label-node' or the innermost enclosing loop.")
2982
2983 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2984 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2985
2986 (defun js2-print-continue-node (n i)
2987 (insert (js2-make-pad i) "continue")
2988 (when (js2-continue-node-label n)
2989 (insert " ")
2990 (js2-print-ast (js2-continue-node-label n) 0))
2991 (insert ";\n"))
2992
2993 (defstruct (js2-function-node
2994 (:include js2-script-node)
2995 (:constructor nil)
2996 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2997 (pos js2-ts-cursor)
2998 len
2999 (ftype 'FUNCTION)
3000 (form 'FUNCTION_STATEMENT)
3001 (name "")
3002 params
3003 body
3004 lp
3005 rp)))
3006 "AST node for a function declaration.
3007 The `params' field is a lisp list of nodes. Each node is either a simple
3008 `js2-name-node', or if it's a destructuring-assignment parameter, a
3009 `js2-array-node' or `js2-object-node'."
3010 ftype ; FUNCTION, GETTER or SETTER
3011 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3012 name ; function name (a `js2-name-node', or nil if anonymous)
3013 params ; a lisp list of destructuring forms or simple name nodes
3014 body ; a `js2-block-node' or expression node (1.8 only)
3015 lp ; position of arg-list open-paren, or nil if omitted
3016 rp ; position of arg-list close-paren, or nil if omitted
3017 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3018 needs-activation ; t if we need an activation object for this frame
3019 is-generator ; t if this function contains a yield
3020 member-expr) ; nonstandard Ecma extension from Rhino
3021
3022 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3023 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3024
3025 (defun js2-visit-function-node (n v)
3026 (js2-visit-ast (js2-function-node-name n) v)
3027 (dolist (p (js2-function-node-params n))
3028 (js2-visit-ast p v))
3029 (js2-visit-ast (js2-function-node-body n) v))
3030
3031 (defun js2-print-function-node (n i)
3032 (let ((pad (js2-make-pad i))
3033 (getter (js2-node-get-prop n 'GETTER_SETTER))
3034 (name (js2-function-node-name n))
3035 (params (js2-function-node-params n))
3036 (body (js2-function-node-body n))
3037 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3038 (unless getter
3039 (insert pad "function"))
3040 (when name
3041 (insert " ")
3042 (js2-print-ast name 0))
3043 (insert "(")
3044 (loop with len = (length params)
3045 for param in params
3046 for count from 1
3047 do
3048 (js2-print-ast param 0)
3049 (if (< count len)
3050 (insert ", ")))
3051 (insert ") {")
3052 (unless expr
3053 (insert "\n"))
3054 ;; TODO: fix this to be smarter about indenting, etc.
3055 (js2-print-body body (1+ i))
3056 (insert pad "}")
3057 (unless expr
3058 (insert "\n"))))
3059
3060 (defsubst js2-function-name (node)
3061 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3062 (and (js2-function-node-name node)
3063 (js2-name-node-name (js2-function-node-name node))))
3064
3065 ;; Having this be an expression node makes it more flexible.
3066 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3067 ;; that work better if you assume it's an expression. Whenever we have
3068 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3069 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3070 (defstruct (js2-var-decl-node
3071 (:include js2-node)
3072 (:constructor nil)
3073 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3074 (pos js2-token-beg)
3075 len
3076 kids
3077 decl-type)))
3078 "AST node for a variable declaration list (VAR, CONST or LET).
3079 The node bounds differ depending on the declaration type. For VAR or
3080 CONST declarations, the bounds include the var/const keyword. For LET
3081 declarations, the node begins at the position of the first child."
3082 kids ; a lisp list of `js2-var-init-node' structs.
3083 decl-type) ; js2-VAR, js2-CONST or js2-LET
3084
3085 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3086 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3087
3088 (defun js2-visit-var-decl (n v)
3089 (dolist (kid (js2-var-decl-node-kids n))
3090 (js2-visit-ast kid v)))
3091
3092 (defun js2-print-var-decl (n i)
3093 (let ((pad (js2-make-pad i))
3094 (tt (js2-var-decl-node-decl-type n)))
3095 (insert pad)
3096 (insert (cond
3097 ((= tt js2-VAR) "var ")
3098 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3099 ((= tt js2-CONST) "const ")
3100 (t
3101 (error "malformed var-decl node"))))
3102 (loop with kids = (js2-var-decl-node-kids n)
3103 with len = (length kids)
3104 for kid in kids
3105 for count from 1
3106 do
3107 (js2-print-ast kid 0)
3108 (if (< count len)
3109 (insert ", ")))))
3110
3111 (defstruct (js2-var-init-node
3112 (:include js2-node)
3113 (:constructor nil)
3114 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3115 (pos js2-ts-cursor)
3116 len
3117 target
3118 initializer)))
3119 "AST node for a variable declaration.
3120 The type field will be js2-CONST for a const decl."
3121 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3122 initializer) ; initializer expression, a `js2-node'
3123
3124 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3125 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3126
3127 (defun js2-visit-var-init-node (n v)
3128 (js2-visit-ast (js2-var-init-node-target n) v)
3129 (js2-visit-ast (js2-var-init-node-initializer n) v))
3130
3131 (defun js2-print-var-init-node (n i)
3132 (let ((pad (js2-make-pad i))
3133 (name (js2-var-init-node-target n))
3134 (init (js2-var-init-node-initializer n)))
3135 (insert pad)
3136 (js2-print-ast name 0)
3137 (when init
3138 (insert " = ")
3139 (js2-print-ast init 0))))
3140
3141 (defstruct (js2-cond-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3145 (pos js2-ts-cursor)
3146 len
3147 test-expr
3148 true-expr
3149 false-expr
3150 q-pos
3151 c-pos)))
3152 "AST node for the ternary operator"
3153 test-expr
3154 true-expr
3155 false-expr
3156 q-pos ; buffer position of ?
3157 c-pos) ; buffer position of :
3158
3159 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3160 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3161
3162 (defun js2-visit-cond-node (n v)
3163 (js2-visit-ast (js2-cond-node-test-expr n) v)
3164 (js2-visit-ast (js2-cond-node-true-expr n) v)
3165 (js2-visit-ast (js2-cond-node-false-expr n) v))
3166
3167 (defun js2-print-cond-node (n i)
3168 (let ((pad (js2-make-pad i)))
3169 (insert pad)
3170 (js2-print-ast (js2-cond-node-test-expr n) 0)
3171 (insert " ? ")
3172 (js2-print-ast (js2-cond-node-true-expr n) 0)
3173 (insert " : ")
3174 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3175
3176 (defstruct (js2-infix-node
3177 (:include js2-node)
3178 (:constructor nil)
3179 (:constructor make-js2-infix-node (&key type
3180 (pos js2-ts-cursor)
3181 len
3182 op-pos
3183 left
3184 right)))
3185 "Represents infix expressions.
3186 Includes assignment ops like `|=', and the comma operator.
3187 The type field inherited from `js2-node' holds the operator."
3188 op-pos ; buffer position where operator begins
3189 left ; any `js2-node'
3190 right) ; any `js2-node'
3191
3192 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3193 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3194
3195 (defun js2-visit-infix-node (n v)
3196 (js2-visit-ast (js2-infix-node-left n) v)
3197 (js2-visit-ast (js2-infix-node-right n) v))
3198
3199 (defconst js2-operator-tokens
3200 (let ((table (make-hash-table :test 'eq))
3201 (tokens
3202 (list (cons js2-IN "in")
3203 (cons js2-TYPEOF "typeof")
3204 (cons js2-INSTANCEOF "instanceof")
3205 (cons js2-DELPROP "delete")
3206 (cons js2-COMMA ",")
3207 (cons js2-COLON ":")
3208 (cons js2-OR "||")
3209 (cons js2-AND "&&")
3210 (cons js2-INC "++")
3211 (cons js2-DEC "--")
3212 (cons js2-BITOR "|")
3213 (cons js2-BITXOR "^")
3214 (cons js2-BITAND "&")
3215 (cons js2-EQ "==")
3216 (cons js2-NE "!=")
3217 (cons js2-LT "<")
3218 (cons js2-LE "<=")
3219 (cons js2-GT ">")
3220 (cons js2-GE ">=")
3221 (cons js2-LSH "<<")
3222 (cons js2-RSH ">>")
3223 (cons js2-URSH ">>>")
3224 (cons js2-ADD "+") ; infix plus
3225 (cons js2-SUB "-") ; infix minus
3226 (cons js2-MUL "*")
3227 (cons js2-DIV "/")
3228 (cons js2-MOD "%")
3229 (cons js2-NOT "!")
3230 (cons js2-BITNOT "~")
3231 (cons js2-POS "+") ; unary plus
3232 (cons js2-NEG "-") ; unary minus
3233 (cons js2-SHEQ "===") ; shallow equality
3234 (cons js2-SHNE "!==") ; shallow inequality
3235 (cons js2-ASSIGN "=")
3236 (cons js2-ASSIGN_BITOR "|=")
3237 (cons js2-ASSIGN_BITXOR "^=")
3238 (cons js2-ASSIGN_BITAND "&=")
3239 (cons js2-ASSIGN_LSH "<<=")
3240 (cons js2-ASSIGN_RSH ">>=")
3241 (cons js2-ASSIGN_URSH ">>>=")
3242 (cons js2-ASSIGN_ADD "+=")
3243 (cons js2-ASSIGN_SUB "-=")
3244 (cons js2-ASSIGN_MUL "*=")
3245 (cons js2-ASSIGN_DIV "/=")
3246 (cons js2-ASSIGN_MOD "%="))))
3247 (loop for (k . v) in tokens do
3248 (puthash k v table))
3249 table))
3250
3251 (defun js2-print-infix-node (n i)
3252 (let* ((tt (js2-node-type n))
3253 (op (gethash tt js2-operator-tokens)))
3254 (unless op
3255 (error "unrecognized infix operator %s" (js2-node-type n)))
3256 (insert (js2-make-pad i))
3257 (js2-print-ast (js2-infix-node-left n) 0)
3258 (unless (= tt js2-COMMA)
3259 (insert " "))
3260 (insert op)
3261 (insert " ")
3262 (js2-print-ast (js2-infix-node-right n) 0)))
3263
3264 (defstruct (js2-assign-node
3265 (:include js2-infix-node)
3266 (:constructor nil)
3267 (:constructor make-js2-assign-node (&key type
3268 (pos js2-ts-cursor)
3269 len
3270 op-pos
3271 left
3272 right)))
3273 "Represents any assignment.
3274 The type field holds the actual assignment operator.")
3275
3276 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3277 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3278
3279 (defstruct (js2-unary-node
3280 (:include js2-node)
3281 (:constructor nil)
3282 (:constructor make-js2-unary-node (&key type ; required
3283 (pos js2-ts-cursor)
3284 len
3285 operand)))
3286 "AST node type for unary operator nodes.
3287 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3288 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3289 property is added if the operator follows the operand."
3290 operand) ; a `js2-node' expression
3291
3292 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3293 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3294
3295 (defun js2-visit-unary-node (n v)
3296 (js2-visit-ast (js2-unary-node-operand n) v))
3297
3298 (defun js2-print-unary-node (n i)
3299 (let* ((tt (js2-node-type n))
3300 (op (gethash tt js2-operator-tokens))
3301 (postfix (js2-node-get-prop n 'postfix)))
3302 (unless op
3303 (error "unrecognized unary operator %s" tt))
3304 (insert (js2-make-pad i))
3305 (unless postfix
3306 (insert op))
3307 (if (or (= tt js2-TYPEOF)
3308 (= tt js2-DELPROP))
3309 (insert " "))
3310 (js2-print-ast (js2-unary-node-operand n) 0)
3311 (when postfix
3312 (insert op))))
3313
3314 (defstruct (js2-let-node
3315 (:include js2-scope)
3316 (:constructor nil)
3317 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3318 (pos js2-token-beg)
3319 len
3320 vars
3321 body
3322 lp
3323 rp)))
3324 "AST node for a let expression or a let statement.
3325 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3326 vars ; a `js2-var-decl-node'
3327 body ; a `js2-node' representing the expression or body block
3328 lp
3329 rp)
3330
3331 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3332 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3333
3334 (defun js2-visit-let-node (n v)
3335 (js2-visit-ast (js2-let-node-vars n) v)
3336 (js2-visit-ast (js2-let-node-body n) v))
3337
3338 (defun js2-print-let-node (n i)
3339 (insert (js2-make-pad i) "let (")
3340 (js2-print-ast (js2-let-node-vars n) 0)
3341 (insert ") ")
3342 (js2-print-ast (js2-let-node-body n) i))
3343
3344 (defstruct (js2-keyword-node
3345 (:include js2-node)
3346 (:constructor nil)
3347 (:constructor make-js2-keyword-node (&key type
3348 (pos js2-token-beg)
3349 (len (- js2-ts-cursor pos)))))
3350 "AST node representing a literal keyword such as `null'.
3351 Used for `null', `this', `true', `false' and `debugger'.
3352 The node type is set to js2-NULL, js2-THIS, etc.")
3353
3354 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3355 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3356
3357 (defun js2-print-keyword-node (n i)
3358 (insert (js2-make-pad i)
3359 (let ((tt (js2-node-type n)))
3360 (cond
3361 ((= tt js2-THIS) "this")
3362 ((= tt js2-NULL) "null")
3363 ((= tt js2-TRUE) "true")
3364 ((= tt js2-FALSE) "false")
3365 ((= tt js2-DEBUGGER) "debugger")
3366 (t (error "Invalid keyword literal type: %d" tt))))))
3367
3368 (defsubst js2-this-node-p (node)
3369 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3370 (eq (js2-node-type node) js2-THIS))
3371
3372 (defstruct (js2-new-node
3373 (:include js2-node)
3374 (:constructor nil)
3375 (:constructor make-js2-new-node (&key (type js2-NEW)
3376 (pos js2-token-beg)
3377 len
3378 target
3379 args
3380 initializer
3381 lp
3382 rp)))
3383 "AST node for new-expression such as new Foo()."
3384 target ; an identifier or reference
3385 args ; a lisp list of argument nodes
3386 lp ; position of left-paren, nil if omitted
3387 rp ; position of right-paren, nil if omitted
3388 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3389
3390 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3391 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3392
3393 (defun js2-visit-new-node (n v)
3394 (js2-visit-ast (js2-new-node-target n) v)
3395 (dolist (arg (js2-new-node-args n))
3396 (js2-visit-ast arg v))
3397 (js2-visit-ast (js2-new-node-initializer n) v))
3398
3399 (defun js2-print-new-node (n i)
3400 (insert (js2-make-pad i) "new ")
3401 (js2-print-ast (js2-new-node-target n))
3402 (insert "(")
3403 (js2-print-list (js2-new-node-args n))
3404 (insert ")")
3405 (when (js2-new-node-initializer n)
3406 (insert " ")
3407 (js2-print-ast (js2-new-node-initializer n))))
3408
3409 (defstruct (js2-name-node
3410 (:include js2-node)
3411 (:constructor nil)
3412 (:constructor make-js2-name-node (&key (type js2-NAME)
3413 (pos js2-token-beg)
3414 (len (- js2-ts-cursor
3415 js2-token-beg))
3416 (name js2-ts-string))))
3417 "AST node for a JavaScript identifier"
3418 name ; a string
3419 scope) ; a `js2-scope' (optional, used for codegen)
3420
3421 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3422 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3423
3424 (defun js2-print-name-node (n i)
3425 (insert (js2-make-pad i)
3426 (js2-name-node-name n)))
3427
3428 (defsubst js2-name-node-length (node)
3429 "Return identifier length of NODE, a `js2-name-node'.
3430 Returns 0 if NODE is nil or its identifier field is nil."
3431 (if node
3432 (length (js2-name-node-name node))
3433 0))
3434
3435 (defstruct (js2-number-node
3436 (:include js2-node)
3437 (:constructor nil)
3438 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3439 (pos js2-token-beg)
3440 (len (- js2-ts-cursor
3441 js2-token-beg))
3442 (value js2-ts-string)
3443 (num-value js2-ts-number))))
3444 "AST node for a number literal."
3445 value ; the original string, e.g. "6.02e23"
3446 num-value) ; the parsed number value
3447
3448 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3449 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3450
3451 (defun js2-print-number-node (n i)
3452 (insert (js2-make-pad i)
3453 (number-to-string (js2-number-node-num-value n))))
3454
3455 (defstruct (js2-regexp-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3459 (pos js2-token-beg)
3460 (len (- js2-ts-cursor
3461 js2-token-beg))
3462 value
3463 flags)))
3464 "AST node for a regular expression literal."
3465 value ; the regexp string, without // delimiters
3466 flags) ; a string of flags, e.g. `mi'.
3467
3468 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3470
3471 (defun js2-print-regexp (n i)
3472 (insert (js2-make-pad i)
3473 "/"
3474 (js2-regexp-node-value n)
3475 "/")
3476 (if (js2-regexp-node-flags n)
3477 (insert (js2-regexp-node-flags n))))
3478
3479 (defstruct (js2-string-node
3480 (:include js2-node)
3481 (:constructor nil)
3482 (:constructor make-js2-string-node (&key (type js2-STRING)
3483 (pos js2-token-beg)
3484 (len (- js2-ts-cursor
3485 js2-token-beg))
3486 (value js2-ts-string))))
3487 "String literal.
3488 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3489 You can tell the quote type by looking at the first character."
3490 value) ; the characters of the string, including the quotes
3491
3492 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3493 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3494
3495 (defun js2-print-string-node (n i)
3496 (insert (js2-make-pad i)
3497 (js2-node-string n)))
3498
3499 (defstruct (js2-array-node
3500 (:include js2-node)
3501 (:constructor nil)
3502 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3503 (pos js2-ts-cursor)
3504 len
3505 elems)))
3506 "AST node for an array literal."
3507 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3508
3509 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3510 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3511
3512 (defun js2-visit-array-node (n v)
3513 (dolist (e (js2-array-node-elems n))
3514 (js2-visit-ast e v)))
3515
3516 (defun js2-print-array-node (n i)
3517 (insert (js2-make-pad i) "[")
3518 (js2-print-list (js2-array-node-elems n))
3519 (insert "]"))
3520
3521 (defstruct (js2-object-node
3522 (:include js2-node)
3523 (:constructor nil)
3524 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3525 (pos js2-ts-cursor)
3526 len
3527 elems)))
3528 "AST node for an object literal expression.
3529 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3530 the latter represents abbreviation in destructuring expressions."
3531 elems)
3532
3533 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3534 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3535
3536 (defun js2-visit-object-node (n v)
3537 (dolist (e (js2-object-node-elems n))
3538 (js2-visit-ast e v)))
3539
3540 (defun js2-print-object-node (n i)
3541 (insert (js2-make-pad i) "{")
3542 (js2-print-list (js2-object-node-elems n))
3543 (insert "}"))
3544
3545 (defstruct (js2-object-prop-node
3546 (:include js2-infix-node)
3547 (:constructor nil)
3548 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3549 (pos js2-ts-cursor)
3550 len
3551 left
3552 right
3553 op-pos)))
3554 "AST node for an object literal prop:value entry.
3555 The `left' field is the property: a name node, string node or number node.
3556 The `right' field is a `js2-node' representing the initializer value.")
3557
3558 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3560
3561 (defun js2-print-object-prop-node (n i)
3562 (insert (js2-make-pad i))
3563 (js2-print-ast (js2-object-prop-node-left n) 0)
3564 (insert ":")
3565 (js2-print-ast (js2-object-prop-node-right n) 0))
3566
3567 (defstruct (js2-getter-setter-node
3568 (:include js2-infix-node)
3569 (:constructor nil)
3570 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3571 (pos js2-ts-cursor)
3572 len
3573 left
3574 right)))
3575 "AST node for a getter/setter property in an object literal.
3576 The `left' field is the `js2-name-node' naming the getter/setter prop.
3577 The `right' field is always an anonymous `js2-function-node' with a node
3578 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3579
3580 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3581 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3582
3583 (defun js2-print-getter-setter (n i)
3584 (let ((pad (js2-make-pad i))
3585 (left (js2-getter-setter-node-left n))
3586 (right (js2-getter-setter-node-right n)))
3587 (insert pad)
3588 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3589 (js2-print-ast left 0)
3590 (js2-print-ast right 0)))
3591
3592 (defstruct (js2-prop-get-node
3593 (:include js2-infix-node)
3594 (:constructor nil)
3595 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3596 (pos js2-ts-cursor)
3597 len
3598 left
3599 right)))
3600 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3601
3602 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3603 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3604
3605 (defun js2-visit-prop-get-node (n v)
3606 (js2-visit-ast (js2-prop-get-node-left n) v)
3607 (js2-visit-ast (js2-prop-get-node-right n) v))
3608
3609 (defun js2-print-prop-get-node (n i)
3610 (insert (js2-make-pad i))
3611 (js2-print-ast (js2-prop-get-node-left n) 0)
3612 (insert ".")
3613 (js2-print-ast (js2-prop-get-node-right n) 0))
3614
3615 (defstruct (js2-elem-get-node
3616 (:include js2-node)
3617 (:constructor nil)
3618 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3619 (pos js2-ts-cursor)
3620 len
3621 target
3622 element
3623 lb
3624 rb)))
3625 "AST node for an array index expression such as foo[bar]."
3626 target ; a `js2-node' - the expression preceding the "."
3627 element ; a `js2-node' - the expression in brackets
3628 lb ; position of left-bracket, nil if omitted
3629 rb) ; position of right-bracket, nil if omitted
3630
3631 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3632 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3633
3634 (defun js2-visit-elem-get-node (n v)
3635 (js2-visit-ast (js2-elem-get-node-target n) v)
3636 (js2-visit-ast (js2-elem-get-node-element n) v))
3637
3638 (defun js2-print-elem-get-node (n i)
3639 (insert (js2-make-pad i))
3640 (js2-print-ast (js2-elem-get-node-target n) 0)
3641 (insert "[")
3642 (js2-print-ast (js2-elem-get-node-element n) 0)
3643 (insert "]"))
3644
3645 (defstruct (js2-call-node
3646 (:include js2-node)
3647 (:constructor nil)
3648 (:constructor make-js2-call-node (&key (type js2-CALL)
3649 (pos js2-ts-cursor)
3650 len
3651 target
3652 args
3653 lp
3654 rp)))
3655 "AST node for a JavaScript function call."
3656 target ; a `js2-node' evaluating to the function to call
3657 args ; a lisp list of `js2-node' arguments
3658 lp ; position of open-paren, or nil if missing
3659 rp) ; position of close-paren, or nil if missing
3660
3661 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3662 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3663
3664 (defun js2-visit-call-node (n v)
3665 (js2-visit-ast (js2-call-node-target n) v)
3666 (dolist (arg (js2-call-node-args n))
3667 (js2-visit-ast arg v)))
3668
3669 (defun js2-print-call-node (n i)
3670 (insert (js2-make-pad i))
3671 (js2-print-ast (js2-call-node-target n) 0)
3672 (insert "(")
3673 (js2-print-list (js2-call-node-args n))
3674 (insert ")"))
3675
3676 (defstruct (js2-yield-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3680 (pos js2-ts-cursor)
3681 len
3682 value)))
3683 "AST node for yield statement or expression."
3684 value) ; optional: value to be yielded
3685
3686 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3687 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3688
3689 (defun js2-visit-yield-node (n v)
3690 (js2-visit-ast (js2-yield-node-value n) v))
3691
3692 (defun js2-print-yield-node (n i)
3693 (insert (js2-make-pad i))
3694 (insert "yield")
3695 (when (js2-yield-node-value n)
3696 (insert " ")
3697 (js2-print-ast (js2-yield-node-value n) 0)))
3698
3699 (defstruct (js2-paren-node
3700 (:include js2-node)
3701 (:constructor nil)
3702 (:constructor make-js2-paren-node (&key (type js2-LP)
3703 (pos js2-ts-cursor)
3704 len
3705 expr)))
3706 "AST node for a parenthesized expression.
3707 In particular, used when the parens are syntactically optional,
3708 as opposed to required parens such as those enclosing an if-conditional."
3709 expr) ; `js2-node'
3710
3711 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3712 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3713
3714 (defun js2-visit-paren-node (n v)
3715 (js2-visit-ast (js2-paren-node-expr n) v))
3716
3717 (defun js2-print-paren-node (n i)
3718 (insert (js2-make-pad i))
3719 (insert "(")
3720 (js2-print-ast (js2-paren-node-expr n) 0)
3721 (insert ")"))
3722
3723 (defstruct (js2-array-comp-node
3724 (:include js2-scope)
3725 (:constructor nil)
3726 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3727 (pos js2-ts-cursor)
3728 len
3729 result
3730 loops
3731 filter
3732 if-pos
3733 lp
3734 rp)))
3735 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3736 result ; result expression (just after left-bracket)
3737 loops ; a lisp list of `js2-array-comp-loop-node'
3738 filter ; guard/filter expression
3739 if-pos ; buffer pos of 'if' keyword, if present, else nil
3740 lp ; buffer position of if-guard left-paren, or nil if not present
3741 rp) ; buffer position of if-guard right-paren, or nil if not present
3742
3743 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3744 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3745
3746 (defun js2-visit-array-comp-node (n v)
3747 (js2-visit-ast (js2-array-comp-node-result n) v)
3748 (dolist (l (js2-array-comp-node-loops n))
3749 (js2-visit-ast l v))
3750 (js2-visit-ast (js2-array-comp-node-filter n) v))
3751
3752 (defun js2-print-array-comp-node (n i)
3753 (let ((pad (js2-make-pad i))
3754 (result (js2-array-comp-node-result n))
3755 (loops (js2-array-comp-node-loops n))
3756 (filter (js2-array-comp-node-filter n)))
3757 (insert pad "[")
3758 (js2-print-ast result 0)
3759 (dolist (l loops)
3760 (insert " ")
3761 (js2-print-ast l 0))
3762 (when filter
3763 (insert " if (")
3764 (js2-print-ast filter 0))
3765 (insert ")]")))
3766
3767 (defstruct (js2-array-comp-loop-node
3768 (:include js2-for-in-node)
3769 (:constructor nil)
3770 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3771 (pos js2-ts-cursor)
3772 len
3773 iterator
3774 object
3775 in-pos
3776 foreach-p
3777 each-pos
3778 lp
3779 rp)))
3780 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3781
3782 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3783 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3784
3785 (defun js2-visit-array-comp-loop (n v)
3786 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3787 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3788
3789 (defun js2-print-array-comp-loop (n i)
3790 (insert "for (")
3791 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3792 (insert " in ")
3793 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3794 (insert ")"))
3795
3796 (defstruct (js2-empty-expr-node
3797 (:include js2-node)
3798 (:constructor nil)
3799 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3800 (pos js2-token-beg)
3801 len)))
3802 "AST node for an empty expression.")
3803
3804 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3805 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3806
3807 (defstruct (js2-xml-node
3808 (:include js2-block-node)
3809 (:constructor nil)
3810 (:constructor make-js2-xml-node (&key (type js2-XML)
3811 (pos js2-token-beg)
3812 len
3813 kids)))
3814 "AST node for initial parse of E4X literals.
3815 The kids field is a list of XML fragments, each a `js2-string-node' or
3816 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3817
3818 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3819 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3820
3821 (defun js2-print-xml-node (n i)
3822 (dolist (kid (js2-xml-node-kids n))
3823 (js2-print-ast kid i)))
3824
3825 (defstruct (js2-xml-js-expr-node
3826 (:include js2-xml-node)
3827 (:constructor nil)
3828 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3829 (pos js2-ts-cursor)
3830 len
3831 expr)))
3832 "AST node for an embedded JavaScript {expression} in an E4X literal.
3833 The start and end fields correspond to the curly-braces."
3834 expr) ; a `js2-expr-node' of some sort
3835
3836 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3837 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3838
3839 (defun js2-visit-xml-js-expr (n v)
3840 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3841
3842 (defun js2-print-xml-js-expr (n i)
3843 (insert (js2-make-pad i))
3844 (insert "{")
3845 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3846 (insert "}"))
3847
3848 (defstruct (js2-xml-dot-query-node
3849 (:include js2-infix-node)
3850 (:constructor nil)
3851 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3852 (pos js2-ts-cursor)
3853 op-pos
3854 len
3855 left
3856 right
3857 rp)))
3858 "AST node for an E4X foo.(bar) filter expression.
3859 Note that the left-paren is automatically the character immediately
3860 following the dot (.) in the operator. No whitespace is permitted
3861 between the dot and the lp by the scanner."
3862 rp)
3863
3864 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3865 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3866
3867 (defun js2-print-xml-dot-query (n i)
3868 (insert (js2-make-pad i))
3869 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3870 (insert ".(")
3871 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3872 (insert ")"))
3873
3874 (defstruct (js2-xml-ref-node
3875 (:include js2-node)
3876 (:constructor nil)) ; abstract
3877 "Base type for E4X XML attribute-access or property-get expressions.
3878 Such expressions can take a variety of forms. The general syntax has
3879 three parts:
3880
3881 - (optional) an @ (specifying an attribute access)
3882 - (optional) a namespace (a `js2-name-node') and double-colon
3883 - (required) either a `js2-name-node' or a bracketed [expression]
3884
3885 The property-name expressions (examples: ns::name, @name) are
3886 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3887 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3888
3889 This node type (or more specifically, its subclasses) will sometimes
3890 be the right-hand child of a `js2-prop-get-node' or a
3891 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3892 The `js2-xml-ref-node' may also be a standalone primary expression with
3893 no explicit target, which is valid in certain expression contexts such as
3894
3895 company..employee.(@id < 100)
3896
3897 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3898 expression whose parent is a `js2-xml-dot-query-node'."
3899 namespace
3900 at-pos
3901 colon-pos)
3902
3903 (defsubst js2-xml-ref-node-attr-access-p (node)
3904 "Return non-nil if this expression began with an @-token."
3905 (and (numberp (js2-xml-ref-node-at-pos node))
3906 (plusp (js2-xml-ref-node-at-pos node))))
3907
3908 (defstruct (js2-xml-prop-ref-node
3909 (:include js2-xml-ref-node)
3910 (:constructor nil)
3911 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3912 (pos js2-token-beg)
3913 len
3914 propname
3915 namespace
3916 at-pos
3917 colon-pos)))
3918 "AST node for an E4X XML [expr] property-ref expression.
3919 The JavaScript syntax is an optional @, an optional ns::, and a name.
3920
3921 [ '@' ] [ name '::' ] name
3922
3923 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3924 @ns::*, @*::attr, @*::*, and @*.
3925
3926 The node starts at the @ token, if present. Otherwise it starts at the
3927 namespace name. The node bounds extend through the closing right-bracket,
3928 or if it is missing due to a syntax error, through the end of the index
3929 expression."
3930 propname)
3931
3932 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3933 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3934
3935 (defun js2-visit-xml-prop-ref-node (n v)
3936 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3937 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3938
3939 (defun js2-print-xml-prop-ref-node (n i)
3940 (insert (js2-make-pad i))
3941 (if (js2-xml-ref-node-attr-access-p n)
3942 (insert "@"))
3943 (when (js2-xml-prop-ref-node-namespace n)
3944 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3945 (insert "::"))
3946 (if (js2-xml-prop-ref-node-propname n)
3947 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3948
3949 (defstruct (js2-xml-elem-ref-node
3950 (:include js2-xml-ref-node)
3951 (:constructor nil)
3952 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3953 (pos js2-token-beg)
3954 len
3955 expr
3956 lb
3957 rb
3958 namespace
3959 at-pos
3960 colon-pos)))
3961 "AST node for an E4X XML [expr] member-ref expression.
3962 Syntax:
3963
3964 [ '@' ] [ name '::' ] '[' expr ']'
3965
3966 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3967
3968 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3969 is not a legal E4X XML element-ref expression, since it's already used
3970 for standard JavaScript element-get array indexing. Hence, a
3971 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3972 non-nil namespace node, or both.
3973
3974 The node starts at the @ token, if present. Otherwise it starts
3975 at the namespace name. The node bounds extend through the closing
3976 right-bracket, or if it is missing due to a syntax error, through the
3977 end of the index expression."
3978 expr ; the bracketed index expression
3979 lb
3980 rb)
3981
3982 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3983 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3984
3985 (defun js2-visit-xml-elem-ref-node (n v)
3986 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3987 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3988
3989 (defun js2-print-xml-elem-ref-node (n i)
3990 (insert (js2-make-pad i))
3991 (if (js2-xml-ref-node-attr-access-p n)
3992 (insert "@"))
3993 (when (js2-xml-elem-ref-node-namespace n)
3994 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3995 (insert "::"))
3996 (insert "[")
3997 (if (js2-xml-elem-ref-node-expr n)
3998 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3999 (insert "]"))
4000
4001 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4002
4003 (defstruct (js2-xml-start-tag-node
4004 (:include js2-xml-node)
4005 (:constructor nil)
4006 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4007 (pos js2-ts-cursor)
4008 len
4009 name
4010 attrs
4011 kids
4012 empty-p)))
4013 "AST node for an XML start-tag. Not currently used.
4014 The `kids' field is a lisp list of child content nodes."
4015 name ; a `js2-xml-name-node'
4016 attrs ; a lisp list of `js2-xml-attr-node'
4017 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4018
4019 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4020 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4021
4022 (defun js2-visit-xml-start-tag (n v)
4023 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4024 (dolist (attr (js2-xml-start-tag-node-attrs n))
4025 (js2-visit-ast attr v))
4026 (js2-visit-block n v))
4027
4028 (defun js2-print-xml-start-tag (n i)
4029 (insert (js2-make-pad i) "<")
4030 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4031 (when (js2-xml-start-tag-node-attrs n)
4032 (insert " ")
4033 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4034 (insert ">"))
4035
4036 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4037 ;; and add the end-tag to the kids list of the parent as well.
4038 (defstruct (js2-xml-end-tag-node
4039 (:include js2-xml-node)
4040 (:constructor nil)
4041 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4042 (pos js2-ts-cursor)
4043 len
4044 name)))
4045 "AST node for an XML end-tag. Not currently used."
4046 name) ; a `js2-xml-name-node'
4047
4048 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4049 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4050
4051 (defun js2-visit-xml-end-tag (n v)
4052 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4053
4054 (defun js2-print-xml-end-tag (n i)
4055 (insert (js2-make-pad i))
4056 (insert "</")
4057 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4058 (insert ">"))
4059
4060 (defstruct (js2-xml-name-node
4061 (:include js2-xml-node)
4062 (:constructor nil)
4063 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4064 (pos js2-ts-cursor)
4065 len
4066 namespace
4067 kids)))
4068 "AST node for an E4X XML name. Not currently used.
4069 Any XML name can be qualified with a namespace, hence the namespace field.
4070 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4071 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4072 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4073 namespace) ; a `js2-string-node'
4074
4075 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4076 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4077
4078 (defun js2-visit-xml-name-node (n v)
4079 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4080
4081 (defun js2-print-xml-name-node (n i)
4082 (insert (js2-make-pad i))
4083 (when (js2-xml-name-node-namespace n)
4084 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4085 (insert "::"))
4086 (dolist (kid (js2-xml-name-node-kids n))
4087 (js2-print-ast kid 0)))
4088
4089 (defstruct (js2-xml-pi-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len
4095 name
4096 attrs)))
4097 "AST node for an E4X XML processing instruction. Not currently used."
4098 name ; a `js2-xml-name-node'
4099 attrs) ; a list of `js2-xml-attr-node'
4100
4101 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4102 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4103
4104 (defun js2-visit-xml-pi-node (n v)
4105 (js2-visit-ast (js2-xml-pi-node-name n) v)
4106 (dolist (attr (js2-xml-pi-node-attrs n))
4107 (js2-visit-ast attr v)))
4108
4109 (defun js2-print-xml-pi-node (n i)
4110 (insert (js2-make-pad i) "<?")
4111 (js2-print-ast (js2-xml-pi-node-name n))
4112 (when (js2-xml-pi-node-attrs n)
4113 (insert " ")
4114 (js2-print-list (js2-xml-pi-node-attrs n)))
4115 (insert "?>"))
4116
4117 (defstruct (js2-xml-cdata-node
4118 (:include js2-xml-node)
4119 (:constructor nil)
4120 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4121 (pos js2-ts-cursor)
4122 len
4123 content)))
4124 "AST node for a CDATA escape section. Not currently used."
4125 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4126
4127 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4128 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4129
4130 (defun js2-visit-xml-cdata-node (n v)
4131 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4132
4133 (defun js2-print-xml-cdata-node (n i)
4134 (insert (js2-make-pad i))
4135 (js2-print-ast (js2-xml-cdata-node-content n)))
4136
4137 (defstruct (js2-xml-attr-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-attr-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 name
4144 value
4145 eq-pos
4146 quote-type)))
4147 "AST node representing a foo='bar' XML attribute value. Not yet used."
4148 name ; a `js2-xml-name-node'
4149 value ; a `js2-xml-name-node'
4150 eq-pos ; buffer position of "=" sign
4151 quote-type) ; 'single or 'double
4152
4153 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4154 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4155
4156 (defun js2-visit-xml-attr-node (n v)
4157 (js2-visit-ast (js2-xml-attr-node-name n) v)
4158 (js2-visit-ast (js2-xml-attr-node-value n) v))
4159
4160 (defun js2-print-xml-attr-node (n i)
4161 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4162 "'"
4163 "\"")))
4164 (insert (js2-make-pad i))
4165 (js2-print-ast (js2-xml-attr-node-name n) 0)
4166 (insert "=" quote)
4167 (js2-print-ast (js2-xml-attr-node-value n) 0)
4168 (insert quote)))
4169
4170 (defstruct (js2-xml-text-node
4171 (:include js2-xml-node)
4172 (:constructor nil)
4173 (:constructor make-js2-text-node (&key (type js2-XML)
4174 (pos js2-ts-cursor)
4175 len
4176 content)))
4177 "AST node for an E4X XML text node. Not currently used."
4178 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4179
4180 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4181 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4182
4183 (defun js2-visit-xml-text-node (n v)
4184 (js2-visit-ast (js2-xml-text-node-content n) v))
4185
4186 (defun js2-print-xml-text-node (n i)
4187 (insert (js2-make-pad i))
4188 (dolist (kid (js2-xml-text-node-content n))
4189 (js2-print-ast kid)))
4190
4191 (defstruct (js2-xml-comment-node
4192 (:include js2-xml-node)
4193 (:constructor nil)
4194 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4195 (pos js2-ts-cursor)
4196 len)))
4197 "AST node for E4X XML comment. Not currently used.")
4198
4199 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4200 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4201
4202 (defun js2-print-xml-comment (n i)
4203 (insert (js2-make-pad i)
4204 (js2-node-string n)))
4205
4206 ;;; Node utilities
4207
4208 (defsubst js2-node-line (n)
4209 "Fetch the source line number at the start of node N.
4210 This is O(n) in the length of the source buffer; use prudently."
4211 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4212
4213 (defsubst js2-block-node-kid (n i)
4214 "Return child I of node N, or nil if there aren't that many."
4215 (nth i (js2-block-node-kids n)))
4216
4217 (defsubst js2-block-node-first (n)
4218 "Return first child of block node N, or nil if there is none."
4219 (first (js2-block-node-kids n)))
4220
4221 (defun js2-node-root (n)
4222 "Return the root of the AST containing N.
4223 If N has no parent pointer, returns N."
4224 (let ((parent (js2-node-parent n)))
4225 (if parent
4226 (js2-node-root parent)
4227 n)))
4228
4229 (defun js2-node-position-in-parent (node &optional parent)
4230 "Return the position of NODE in parent's block-kids list.
4231 PARENT can be supplied if known. Positioned returned is zero-indexed.
4232 Returns 0 if NODE is not a child of a block statement, or if NODE
4233 is not a statement node."
4234 (let ((p (or parent (js2-node-parent node)))
4235 (i 0))
4236 (if (not (js2-block-node-p p))
4237 i
4238 (or (js2-position node (js2-block-node-kids p))
4239 0))))
4240
4241 (defsubst js2-node-short-name (n)
4242 "Return the short name of node N as a string, e.g. `js2-if-node'."
4243 (substring (symbol-name (aref n 0))
4244 (length "cl-struct-")))
4245
4246 (defsubst js2-node-child-list (node)
4247 "Return the child list for NODE, a lisp list of nodes.
4248 Works for block nodes, array nodes, obj literals, funarg lists,
4249 var decls and try nodes (for catch clauses). Note that you should call
4250 `js2-block-node-kids' on the function body for the body statements.
4251 Returns nil for zero-length child lists or unsupported nodes."
4252 (cond
4253 ((js2-function-node-p node)
4254 (js2-function-node-params node))
4255 ((js2-block-node-p node)
4256 (js2-block-node-kids node))
4257 ((js2-try-node-p node)
4258 (js2-try-node-catch-clauses node))
4259 ((js2-array-node-p node)
4260 (js2-array-node-elems node))
4261 ((js2-object-node-p node)
4262 (js2-object-node-elems node))
4263 ((js2-call-node-p node)
4264 (js2-call-node-args node))
4265 ((js2-new-node-p node)
4266 (js2-new-node-args node))
4267 ((js2-var-decl-node-p node)
4268 (js2-var-decl-node-kids node))
4269 (t
4270 nil)))
4271
4272 (defsubst js2-node-set-child-list (node kids)
4273 "Set the child list for NODE to KIDS."
4274 (cond
4275 ((js2-function-node-p node)
4276 (setf (js2-function-node-params node) kids))
4277 ((js2-block-node-p node)
4278 (setf (js2-block-node-kids node) kids))
4279 ((js2-try-node-p node)
4280 (setf (js2-try-node-catch-clauses node) kids))
4281 ((js2-array-node-p node)
4282 (setf (js2-array-node-elems node) kids))
4283 ((js2-object-node-p node)
4284 (setf (js2-object-node-elems node) kids))
4285 ((js2-call-node-p node)
4286 (setf (js2-call-node-args node) kids))
4287 ((js2-new-node-p node)
4288 (setf (js2-new-node-args node) kids))
4289 ((js2-var-decl-node-p node)
4290 (setf (js2-var-decl-node-kids node) kids))
4291 (t
4292 (error "Unsupported node type: %s" (js2-node-short-name node))))
4293 kids)
4294
4295 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4296 (defconst js2-paren-expr-nodes
4297 '(cl-struct-js2-array-comp-loop-node
4298 cl-struct-js2-array-comp-node
4299 cl-struct-js2-call-node
4300 cl-struct-js2-catch-node
4301 cl-struct-js2-do-node
4302 cl-struct-js2-elem-get-node
4303 cl-struct-js2-for-in-node
4304 cl-struct-js2-for-node
4305 cl-struct-js2-function-node
4306 cl-struct-js2-if-node
4307 cl-struct-js2-let-node
4308 cl-struct-js2-new-node
4309 cl-struct-js2-paren-node
4310 cl-struct-js2-switch-node
4311 cl-struct-js2-while-node
4312 cl-struct-js2-with-node
4313 cl-struct-js2-xml-dot-query-node)
4314 "Node types that can have a parenthesized child expression.
4315 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4316
4317 (defsubst js2-paren-expr-node-p (node)
4318 "Return t for nodes that typically have a parenthesized child expression.
4319 Useful for computing the indentation anchors for arg-lists and conditions.
4320 Note that it may return a false positive, for instance when NODE is
4321 a `js2-new-node' and there are no arguments or parentheses."
4322 (memq (aref node 0) js2-paren-expr-nodes))
4323
4324 ;; Fake polymorphism... yech.
4325 (defsubst js2-node-lp (node)
4326 "Return relative left-paren position for NODE, if applicable.
4327 For `js2-elem-get-node' structs, returns left-bracket position.
4328 Note that the position may be nil in the case of a parse error."
4329 (cond
4330 ((js2-elem-get-node-p node)
4331 (js2-elem-get-node-lb node))
4332 ((js2-loop-node-p node)
4333 (js2-loop-node-lp node))
4334 ((js2-function-node-p node)
4335 (js2-function-node-lp node))
4336 ((js2-if-node-p node)
4337 (js2-if-node-lp node))
4338 ((js2-new-node-p node)
4339 (js2-new-node-lp node))
4340 ((js2-call-node-p node)
4341 (js2-call-node-lp node))
4342 ((js2-paren-node-p node)
4343 (js2-node-pos node))
4344 ((js2-switch-node-p node)
4345 (js2-switch-node-lp node))
4346 ((js2-catch-node-p node)
4347 (js2-catch-node-lp node))
4348 ((js2-let-node-p node)
4349 (js2-let-node-lp node))
4350 ((js2-array-comp-node-p node)
4351 (js2-array-comp-node-lp node))
4352 ((js2-with-node-p node)
4353 (js2-with-node-lp node))
4354 ((js2-xml-dot-query-node-p node)
4355 (1+ (js2-infix-node-op-pos node)))
4356 (t
4357 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4358
4359 ;; Fake polymorphism... blech.
4360 (defsubst js2-node-rp (node)
4361 "Return relative right-paren position for NODE, if applicable.
4362 For `js2-elem-get-node' structs, returns right-bracket position.
4363 Note that the position may be nil in the case of a parse error."
4364 (cond
4365 ((js2-elem-get-node-p node)
4366 (js2-elem-get-node-lb node))
4367 ((js2-loop-node-p node)
4368 (js2-loop-node-rp node))
4369 ((js2-function-node-p node)
4370 (js2-function-node-rp node))
4371 ((js2-if-node-p node)
4372 (js2-if-node-rp node))
4373 ((js2-new-node-p node)
4374 (js2-new-node-rp node))
4375 ((js2-call-node-p node)
4376 (js2-call-node-rp node))
4377 ((js2-paren-node-p node)
4378 (+ (js2-node-pos node) (js2-node-len node)))
4379 ((js2-switch-node-p node)
4380 (js2-switch-node-rp node))
4381 ((js2-catch-node-p node)
4382 (js2-catch-node-rp node))
4383 ((js2-let-node-p node)
4384 (js2-let-node-rp node))
4385 ((js2-array-comp-node-p node)
4386 (js2-array-comp-node-rp node))
4387 ((js2-with-node-p node)
4388 (js2-with-node-rp node))
4389 ((js2-xml-dot-query-node-p node)
4390 (1+ (js2-xml-dot-query-node-rp node)))
4391 (t
4392 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4393
4394 (defsubst js2-node-first-child (node)
4395 "Returns the first element of `js2-node-child-list' for NODE."
4396 (car (js2-node-child-list node)))
4397
4398 (defsubst js2-node-last-child (node)
4399 "Returns the last element of `js2-node-last-child' for NODE."
4400 (car (last (js2-node-child-list node))))
4401
4402 (defun js2-node-prev-sibling (node)
4403 "Return the previous statement in parent.
4404 Works for parents supported by `js2-node-child-list'.
4405 Returns nil if NODE is not in the parent, or PARENT is
4406 not a supported node, or if NODE is the first child."
4407 (let* ((p (js2-node-parent node))
4408 (kids (js2-node-child-list p))
4409 (sib (car kids)))
4410 (while (and kids
4411 (not (eq node (cadr kids))))
4412 (setq kids (cdr kids)
4413 sib (car kids)))
4414 sib))
4415
4416 (defun js2-node-next-sibling (node)
4417 "Return the next statement in parent block.
4418 Returns nil if NODE is not in the block, or PARENT is not
4419 a block node, or if NODE is the last statement."
4420 (let* ((p (js2-node-parent node))
4421 (kids (js2-node-child-list p)))
4422 (while (and kids
4423 (not (eq node (car kids))))
4424 (setq kids (cdr kids)))
4425 (cadr kids)))
4426
4427 (defun js2-node-find-child-before (pos parent &optional after)
4428 "Find the last child that starts before POS in parent.
4429 If AFTER is non-nil, returns first child starting after POS.
4430 POS is an absolute buffer position. PARENT is any node
4431 supported by `js2-node-child-list'.
4432 Returns nil if no applicable child is found."
4433 (let ((kids (if (js2-function-node-p parent)
4434 (js2-block-node-kids (js2-function-node-body parent))
4435 (js2-node-child-list parent)))
4436 (beg (if (js2-function-node-p parent)
4437 (js2-node-abs-pos (js2-function-node-body parent))
4438 (js2-node-abs-pos parent)))
4439 kid
4440 result
4441 fn
4442 (continue t))
4443 (setq fn (if after '> '<))
4444 (while (and kids continue)
4445 (setq kid (car kids))
4446 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4447 (setq result kid
4448 continue (if after nil t))
4449 (setq continue (if after t nil)))
4450 (setq kids (cdr kids)))
4451 result))
4452
4453 (defun js2-node-find-child-after (pos parent)
4454 "Find first child that starts after POS in parent.
4455 POS is an absolute buffer position. PARENT is any node
4456 supported by `js2-node-child-list'.
4457 Returns nil if no applicable child is found."
4458 (js2-node-find-child-before pos parent 'after))
4459
4460 (defun js2-node-replace-child (pos parent new-node)
4461 "Replace node at index POS in PARENT with NEW-NODE.
4462 Only works for parents supported by `js2-node-child-list'."
4463 (let ((kids (js2-node-child-list parent))
4464 (i 0))
4465 (while (< i pos)
4466 (setq kids (cdr kids)
4467 i (1+ i)))
4468 (setcar kids new-node)
4469 (js2-node-add-children parent new-node)))
4470
4471 (defun js2-node-buffer (n)
4472 "Return the buffer associated with AST N.
4473 Returns nil if the buffer is not set as a property on the root
4474 node, or if parent links were not recorded during parsing."
4475 (let ((root (js2-node-root n)))
4476 (and root
4477 (js2-ast-root-p root)
4478 (js2-ast-root-buffer root))))
4479
4480 (defsubst js2-block-node-push (n kid)
4481 "Push js2-node KID onto the end of js2-block-node N's child list.
4482 KID is always added to the -end- of the kids list.
4483 Function also calls `js2-node-add-children' to add the parent link."
4484 (let ((kids (js2-node-child-list n)))
4485 (if kids
4486 (setcdr kids (nconc (cdr kids) (list kid)))
4487 (js2-node-set-child-list n (list kid)))
4488 (js2-node-add-children n kid)))
4489
4490 (defun js2-node-string (node)
4491 (let ((buf (js2-node-buffer node))
4492 pos)
4493 (unless buf
4494 (error "No buffer available for node %s" node))
4495 (save-excursion
4496 (set-buffer buf)
4497 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4498 (+ pos (js2-node-len node))))))
4499
4500 ;; Container for storing the node we're looking for in a traversal.
4501 (js2-deflocal js2-discovered-node nil)
4502
4503 ;; Keep track of absolute node position during traversals.
4504 (js2-deflocal js2-visitor-offset nil)
4505
4506 (js2-deflocal js2-node-search-point nil)
4507
4508 (when js2-mode-dev-mode-p
4509 (defun js2-find-node-at-point ()
4510 (interactive)
4511 (let ((node (js2-node-at-point)))
4512 (message "%s" (or node "No node found at point"))))
4513 (defun js2-node-name-at-point ()
4514 (interactive)
4515 (let ((node (js2-node-at-point)))
4516 (message "%s" (if node
4517 (js2-node-short-name node)
4518 "No node found at point.")))))
4519
4520 (defun js2-node-at-point (&optional pos skip-comments)
4521 "Return AST node at POS, a buffer position, defaulting to current point.
4522 The `js2-mode-ast' variable must be set to the current parse tree.
4523 Signals an error if the AST (`js2-mode-ast') is nil.
4524 Always returns a node - if it can't find one, it returns the root.
4525 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4526 (let ((ast js2-mode-ast)
4527 result)
4528 (unless ast
4529 (error "No JavaScript AST available"))
4530 ;; Look through comments first, since they may be inside nodes that
4531 ;; would otherwise report a match.
4532 (setq pos (or pos (point))
4533 result (if (> pos (js2-node-abs-end ast))
4534 ast
4535 (if (not skip-comments)
4536 (js2-comment-at-point pos))))
4537 (unless result
4538 (setq js2-discovered-node nil
4539 js2-visitor-offset 0
4540 js2-node-search-point pos)
4541 (unwind-protect
4542 (catch 'js2-visit-done
4543 (js2-visit-ast ast #'js2-node-at-point-visitor))
4544 (setq js2-visitor-offset nil
4545 js2-node-search-point nil))
4546 (setq result js2-discovered-node))
4547 ;; may have found a comment beyond end of last child node,
4548 ;; since visiting the ast-root looks at the comment-list last.
4549 (if (and skip-comments
4550 (js2-comment-node-p result))
4551 (setq result nil))
4552 (or result js2-mode-ast)))
4553
4554 (defun js2-node-at-point-visitor (node end-p)
4555 (let ((rel-pos (js2-node-pos node))
4556 abs-pos
4557 abs-end
4558 (point js2-node-search-point))
4559 (cond
4560 (end-p
4561 ;; this evaluates to a non-nil return value, even if it's zero
4562 (decf js2-visitor-offset rel-pos))
4563 ;; we already looked for comments before visiting, and don't want them now
4564 ((js2-comment-node-p node)
4565 nil)
4566 (t
4567 (setq abs-pos (incf js2-visitor-offset rel-pos)
4568 ;; we only want to use the node if the point is before
4569 ;; the last character position in the node, so we decrement
4570 ;; the absolute end by 1.
4571 abs-end (+ abs-pos (js2-node-len node) -1))
4572 (cond
4573 ;; If this node starts after search-point, stop the search.
4574 ((> abs-pos point)
4575 (throw 'js2-visit-done nil))
4576 ;; If this node ends before the search-point, don't check kids.
4577 ((> point abs-end)
4578 nil)
4579 (t
4580 ;; Otherwise point is within this node, possibly in a child.
4581 (setq js2-discovered-node node)
4582 t)))))) ; keep processing kids to look for more specific match
4583
4584 (defsubst js2-block-comment-p (node)
4585 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4586 (and (js2-comment-node-p node)
4587 (memq (js2-comment-node-format node) '(jsdoc block))))
4588
4589 ;; TODO: put the comments in a vector and binary-search them instead
4590 (defun js2-comment-at-point (&optional pos)
4591 "Look through scanned comment nodes for one containing POS.
4592 POS is a buffer position that defaults to current point.
4593 Function returns nil if POS was not in any comment node."
4594 (let ((ast js2-mode-ast)
4595 (x (or pos (point)))
4596 beg
4597 end)
4598 (unless ast
4599 (error "No JavaScript AST available"))
4600 (catch 'done
4601 ;; Comments are stored in lexical order.
4602 (dolist (comment (js2-ast-root-comments ast) nil)
4603 (setq beg (js2-node-abs-pos comment)
4604 end (+ beg (js2-node-len comment)))
4605 (if (and (>= x beg)
4606 (<= x end))
4607 (throw 'done comment))))))
4608
4609 (defun js2-mode-find-parent-fn (node)
4610 "Find function enclosing NODE.
4611 Returns nil if NODE is not inside a function."
4612 (setq node (js2-node-parent node))
4613 (while (and node (not (js2-function-node-p node)))
4614 (setq node (js2-node-parent node)))
4615 (and (js2-function-node-p node) node))
4616
4617 (defun js2-mode-find-enclosing-fn (node)
4618 "Find function or root enclosing NODE."
4619 (if (js2-ast-root-p node)
4620 node
4621 (setq node (js2-node-parent node))
4622 (while (not (or (js2-ast-root-p node)
4623 (js2-function-node-p node)))
4624 (setq node (js2-node-parent node)))
4625 node))
4626
4627 (defun js2-mode-find-enclosing-node (beg end)
4628 "Find script or function fully enclosing BEG and END."
4629 (let ((node (js2-node-at-point beg))
4630 pos
4631 (continue t))
4632 (while continue
4633 (if (or (js2-ast-root-p node)
4634 (and (js2-function-node-p node)
4635 (<= (setq pos (js2-node-abs-pos node)) beg)
4636 (>= (+ pos (js2-node-len node)) end)))
4637 (setq continue nil)
4638 (setq node (js2-node-parent node))))
4639 node))
4640
4641 (defun js2-node-parent-script-or-fn (node)
4642 "Find script or function immediately enclosing NODE.
4643 If NODE is the ast-root, returns nil."
4644 (if (js2-ast-root-p node)
4645 nil
4646 (setq node (js2-node-parent node))
4647 (while (and node (not (or (js2-function-node-p node)
4648 (js2-script-node-p node))))
4649 (setq node (js2-node-parent node)))
4650 node))
4651
4652 (defsubst js2-nested-function-p (node)
4653 "Return t if NODE is a nested function, or is inside a nested function."
4654 (unless (js2-ast-root-p node)
4655 (js2-function-node-p (if (js2-function-node-p node)
4656 (js2-node-parent-script-or-fn node)
4657 (js2-node-parent-script-or-fn
4658 (js2-node-parent-script-or-fn node))))))
4659
4660 (defsubst js2-function-param-node-p (node)
4661 "Return non-nil if NODE is a param node of a `js2-function-node'."
4662 (let ((parent (js2-node-parent node)))
4663 (and parent
4664 (js2-function-node-p parent)
4665 (memq node (js2-function-node-params parent)))))
4666
4667 (defsubst js2-mode-shift-kids (kids start offset)
4668 (dolist (kid kids)
4669 (if (> (js2-node-pos kid) start)
4670 (incf (js2-node-pos kid) offset))))
4671
4672 (defsubst js2-mode-shift-children (parent start offset)
4673 "Update start-positions of all children of PARENT beyond START."
4674 (let ((root (js2-node-root parent)))
4675 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4676 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4677
4678 (defsubst js2-node-is-descendant (node ancestor)
4679 "Return t if NODE is a descendant of ANCESTOR."
4680 (while (and node
4681 (not (eq node ancestor)))
4682 (setq node (js2-node-parent node)))
4683 node)
4684
4685 ;;; visitor infrastructure
4686
4687 (defun js2-visit-none (node callback)
4688 "Visitor for AST node that have no node children."
4689 nil)
4690
4691 (defun js2-print-none (node indent)
4692 "Visitor for AST node with no printed representation.")
4693
4694 (defun js2-print-body (node indent)
4695 "Print a statement, or a block without braces."
4696 (if (js2-block-node-p node)
4697 (dolist (kid (js2-block-node-kids node))
4698 (js2-print-ast kid indent))
4699 (js2-print-ast node indent)))
4700
4701 (defun js2-print-list (args &optional delimiter)
4702 (loop with len = (length args)
4703 for arg in args
4704 for count from 1
4705 do
4706 (js2-print-ast arg 0)
4707 (if (< count len)
4708 (insert (or delimiter ", ")))))
4709
4710 (defun js2-print-tree (ast)
4711 "Prints an AST to the current buffer.
4712 Makes `js2-ast-parent-nodes' available to the printer functions."
4713 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4714 (js2-print-ast ast)))
4715
4716 (defun js2-print-ast (node &optional indent)
4717 "Helper function for printing AST nodes.
4718 Requires `js2-ast-parent-nodes' to be non-nil.
4719 You should use `js2-print-tree' instead of this function."
4720 (let ((printer (get (aref node 0) 'js2-printer))
4721 (i (or indent 0))
4722 (pos (js2-node-abs-pos node)))
4723 ;; TODO: wedge comments in here somewhere
4724 (if printer
4725 (funcall printer node i))))
4726
4727 (defconst js2-side-effecting-tokens
4728 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4729 (dolist (tt (list js2-ASSIGN
4730 js2-ASSIGN_ADD
4731 js2-ASSIGN_BITAND
4732 js2-ASSIGN_BITOR
4733 js2-ASSIGN_BITXOR
4734 js2-ASSIGN_DIV
4735 js2-ASSIGN_LSH
4736 js2-ASSIGN_MOD
4737 js2-ASSIGN_MUL
4738 js2-ASSIGN_RSH
4739 js2-ASSIGN_SUB
4740 js2-ASSIGN_URSH
4741 js2-BLOCK
4742 js2-BREAK
4743 js2-CALL
4744 js2-CATCH
4745 js2-CATCH_SCOPE
4746 js2-CONST
4747 js2-CONTINUE
4748 js2-DEBUGGER
4749 js2-DEC
4750 js2-DELPROP
4751 js2-DEL_REF
4752 js2-DO
4753 js2-ELSE
4754 js2-EMPTY
4755 js2-ENTERWITH
4756 js2-EXPORT
4757 js2-EXPR_RESULT
4758 js2-FINALLY
4759 js2-FOR
4760 js2-FUNCTION
4761 js2-GOTO
4762 js2-IF
4763 js2-IFEQ
4764 js2-IFNE
4765 js2-IMPORT
4766 js2-INC
4767 js2-JSR
4768 js2-LABEL
4769 js2-LEAVEWITH
4770 js2-LET
4771 js2-LETEXPR
4772 js2-LOCAL_BLOCK
4773 js2-LOOP
4774 js2-NEW
4775 js2-REF_CALL
4776 js2-RETHROW
4777 js2-RETURN
4778 js2-RETURN_RESULT
4779 js2-SEMI
4780 js2-SETELEM
4781 js2-SETELEM_OP
4782 js2-SETNAME
4783 js2-SETPROP
4784 js2-SETPROP_OP
4785 js2-SETVAR
4786 js2-SET_REF
4787 js2-SET_REF_OP
4788 js2-SWITCH
4789 js2-TARGET
4790 js2-THROW
4791 js2-TRY
4792 js2-VAR
4793 js2-WHILE
4794 js2-WITH
4795 js2-WITHEXPR
4796 js2-YIELD))
4797 (aset tokens tt t))
4798 (if js2-instanceof-has-side-effects
4799 (aset tokens js2-INSTANCEOF t))
4800 tokens))
4801
4802 (defun js2-node-has-side-effects (node)
4803 "Return t if NODE has side effects."
4804 (when node ; makes it easier to handle malformed expressions
4805 (let ((tt (js2-node-type node)))
4806 (cond
4807 ;; This doubtless needs some work, since EXPR_VOID is used
4808 ;; in several ways in Rhino, and I may not have caught them all.
4809 ;; I'll wait for people to notice incorrect warnings.
4810 ((and (= tt js2-EXPR_VOID)
4811 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4812 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4813 ((= tt js2-COMMA)
4814 (js2-node-has-side-effects (js2-infix-node-right node)))
4815 ((or (= tt js2-AND)
4816 (= tt js2-OR))
4817 (or (js2-node-has-side-effects (js2-infix-node-right node))
4818 (js2-node-has-side-effects (js2-infix-node-left node))))
4819 ((= tt js2-HOOK)
4820 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4821 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4822 ((js2-paren-node-p node)
4823 (js2-node-has-side-effects (js2-paren-node-expr node)))
4824 ((= tt js2-ERROR) ; avoid cascaded error messages
4825 nil)
4826 (t
4827 (aref js2-side-effecting-tokens tt))))))
4828
4829 (defun js2-member-expr-leftmost-name (node)
4830 "For an expr such as foo.bar.baz, return leftmost node foo.
4831 NODE is any `js2-node' object. If it represents a member expression,
4832 which is any sequence of property gets, element-gets, function calls,
4833 or xml descendants/filter operators, then we look at the lexically
4834 leftmost (first) node in the chain. If it is a name-node we return it.
4835 Note that NODE can be a raw name-node and it will be returned as well.
4836 If NODE is not a name-node or member expression, or if it is a member
4837 expression whose leftmost target is not a name node, returns nil."
4838 (let ((continue t)
4839 result)
4840 (while (and continue (not result))
4841 (cond
4842 ((js2-name-node-p node)
4843 (setq result node))
4844 ((js2-prop-get-node-p node)
4845 (setq node (js2-prop-get-node-left node)))
4846 ;; TODO: handle call-nodes, xml-nodes, others?
4847 (t
4848 (setq continue nil))))
4849 result))
4850
4851 (defconst js2-stmt-node-types
4852 (list js2-BLOCK
4853 js2-BREAK
4854 js2-CONTINUE
4855 js2-DEFAULT ; e4x "default xml namespace" statement
4856 js2-DO
4857 js2-EXPR_RESULT
4858 js2-EXPR_VOID
4859 js2-FOR
4860 js2-IF
4861 js2-RETURN
4862 js2-SWITCH
4863 js2-THROW
4864 js2-TRY
4865 js2-WHILE
4866 js2-WITH)
4867 "Node types that only appear in statement contexts.
4868 The list does not include nodes that always appear as the child
4869 of another specific statement type, such as switch-cases,
4870 catch and finally blocks, and else-clauses. The list also excludes
4871 nodes like yield, let and var, which may appear in either expression
4872 or statement context, and in the latter context always have a
4873 `js2-expr-stmt-node' parent. Finally, the list does not include
4874 functions or scripts, which are treated separately from statements
4875 by the JavaScript parser and runtime.")
4876
4877 (defun js2-stmt-node-p (node)
4878 "Heuristic for figuring out if NODE is a statement.
4879 Some node types can appear in either an expression context or a
4880 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4881 For these node types in a statement context, the parent will be a
4882 `js2-expr-stmt-node'.
4883 Functions aren't included in the check."
4884 (memq (js2-node-type node) js2-stmt-node-types))
4885
4886 (defsubst js2-mode-find-first-stmt (node)
4887 "Search upward starting from NODE looking for a statement.
4888 For purposes of this function, a `js2-function-node' counts."
4889 (while (not (or (js2-stmt-node-p node)
4890 (js2-function-node-p node)))
4891 (setq node (js2-node-parent node)))
4892 node)
4893
4894 (defun js2-node-parent-stmt (node)
4895 "Return the node's first ancestor that is a statement.
4896 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4897 appearing in a statement context will have a parent that is a
4898 `js2-expr-stmt-node' that will be returned by this function."
4899 (let ((parent (js2-node-parent node)))
4900 (if (or (null parent)
4901 (js2-stmt-node-p parent)
4902 (and (js2-function-node-p parent)
4903 (not (eq (js2-function-node-form parent)
4904 'FUNCTION_EXPRESSION))))
4905 parent
4906 (js2-node-parent-stmt parent))))
4907
4908 ;; In the Mozilla Rhino sources, Roshan James writes:
4909 ;; Does consistent-return analysis on the function body when strict mode is
4910 ;; enabled.
4911 ;;
4912 ;; function (x) { return (x+1) }
4913 ;;
4914 ;; is ok, but
4915 ;;
4916 ;; function (x) { if (x < 0) return (x+1); }
4917 ;;
4918 ;; is not because the function can potentially return a value when the
4919 ;; condition is satisfied and if not, the function does not explicitly
4920 ;; return a value.
4921 ;;
4922 ;; This extends to checking mismatches such as "return" and "return <value>"
4923 ;; used in the same function. Warnings are not emitted if inconsistent
4924 ;; returns exist in code that can be statically shown to be unreachable.
4925 ;; Ex.
4926 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4927 ;;
4928 ;; emits no warning. However if the loop had a break statement, then a
4929 ;; warning would be emitted.
4930 ;;
4931 ;; The consistency analysis looks at control structures such as loops, ifs,
4932 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4933 ;; warns the user about an inconsistent set of termination possibilities.
4934 ;;
4935 ;; These flags enumerate the possible ways a statement/function can
4936 ;; terminate. These flags are used by endCheck() and by the Parser to
4937 ;; detect inconsistent return usage.
4938 ;;
4939 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4940 ;; able to execute (example: throw, continue)
4941 ;;
4942 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4943 ;; next one. Statement such as return dont. A compound statement may have
4944 ;; some branch that drops off control to the next statement.
4945 ;;
4946 ;; END_RETURNS indicates that the statement can return with no value.
4947 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4948 ;;
4949 ;; A compound statement such as
4950 ;; if (condition) {
4951 ;; return value;
4952 ;; }
4953 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4954
4955 (defconst js2-END_UNREACHED 0)
4956 (defconst js2-END_DROPS_OFF 1)
4957 (defconst js2-END_RETURNS 2)
4958 (defconst js2-END_RETURNS_VALUE 4)
4959 (defconst js2-END_YIELDS 8)
4960
4961 (defun js2-has-consistent-return-usage (node)
4962 "Check that every return usage in a function body is consistent.
4963 Returns t if the function satisfies strict mode requirement."
4964 (let ((n (js2-end-check node)))
4965 ;; either it doesn't return a value in any branch...
4966 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4967 ;; or it returns a value (or is unreached) at every branch
4968 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4969 js2-END_RETURNS
4970 js2-END_YIELDS)))))
4971
4972 (defun js2-end-check-if (node)
4973 "Returns in the then and else blocks must be consistent with each other.
4974 If there is no else block, then the return statement can fall through.
4975 Returns logical OR of END_* flags"
4976 (let ((th (js2-if-node-then-part node))
4977 (el (js2-if-node-else-part node)))
4978 (if (null th)
4979 js2-END_UNREACHED
4980 (logior (js2-end-check th) (if el
4981 (js2-end-check el)
4982 js2-END_DROPS_OFF)))))
4983
4984 (defun js2-end-check-switch (node)
4985 "Consistency of return statements is checked between the case statements.
4986 If there is no default, then the switch can fall through. If there is a
4987 default, we check to see if all code paths in the default return or if
4988 there is a code path that can fall through.
4989 Returns logical OR of END_* flags."
4990 (let ((rv js2-END_UNREACHED)
4991 default-case)
4992 ;; examine the cases
4993 (catch 'break
4994 (dolist (c (js2-switch-node-cases node))
4995 (if (js2-case-node-expr c)
4996 (js2-set-flag rv (js2-end-check-block c))
4997 (setq default-case c)
4998 (throw 'break nil))))
4999 ;; we don't care how the cases drop into each other
5000 (js2-clear-flag rv js2-END_DROPS_OFF)
5001 ;; examine the default
5002 (js2-set-flag rv (if default-case
5003 (js2-end-check default-case)
5004 js2-END_DROPS_OFF))
5005 rv))
5006
5007 (defun js2-end-check-try (node)
5008 "If the block has a finally, return consistency is checked in the
5009 finally block. If all code paths in the finally return, then the
5010 returns in the try-catch blocks don't matter. If there is a code path
5011 that does not return or if there is no finally block, the returns
5012 of the try and catch blocks are checked for mismatch.
5013 Returns logical OR of END_* flags."
5014 (let ((finally (js2-try-node-finally-block node))
5015 rv)
5016 ;; check the finally if it exists
5017 (setq rv (if finally
5018 (js2-end-check (js2-finally-node-body finally))
5019 js2-END_DROPS_OFF))
5020 ;; If the finally block always returns, then none of the returns
5021 ;; in the try or catch blocks matter.
5022 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5023 (js2-clear-flag rv js2-END_DROPS_OFF)
5024 ;; examine the try block
5025 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5026 ;; check each catch block
5027 (dolist (cb (js2-try-node-catch-clauses node))
5028 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5029 rv))
5030
5031 (defun js2-end-check-loop (node)
5032 "Return statement in the loop body must be consistent. The default
5033 assumption for any kind of a loop is that it will eventually terminate.
5034 The only exception is a loop with a constant true condition. Code that
5035 follows such a loop is examined only if one can statically determine
5036 that there is a break out of the loop.
5037
5038 for(... ; ... ; ...) {}
5039 for(... in ... ) {}
5040 while(...) { }
5041 do { } while(...)
5042
5043 Returns logical OR of END_* flags."
5044 (let ((rv (js2-end-check (js2-loop-node-body node)))
5045 (condition (cond
5046 ((js2-while-node-p node)
5047 (js2-while-node-condition node))
5048 ((js2-do-node-p node)
5049 (js2-do-node-condition node))
5050 ((js2-for-node-p node)
5051 (js2-for-node-condition node)))))
5052
5053 ;; check to see if the loop condition is always true
5054 (if (and condition
5055 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5056 (js2-clear-flag rv js2-END_DROPS_OFF))
5057
5058 ;; look for effect of breaks
5059 (js2-set-flag rv (js2-node-get-prop node
5060 'CONTROL_BLOCK_PROP
5061 js2-END_UNREACHED))
5062 rv))
5063
5064 (defun js2-end-check-block (node)
5065 "A general block of code is examined statement by statement.
5066 If any statement (even a compound one) returns in all branches, then
5067 subsequent statements are not examined.
5068 Returns logical OR of END_* flags."
5069 (let* ((rv js2-END_DROPS_OFF)
5070 (kids (js2-block-node-kids node))
5071 (n (car kids)))
5072 ;; Check each statment. If the statement can continue onto the next
5073 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5074 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5075 (js2-clear-flag rv js2-END_DROPS_OFF)
5076 (js2-set-flag rv (js2-end-check n))
5077 (setq kids (cdr kids)
5078 n (car kids)))
5079 rv))
5080
5081 (defun js2-end-check-label (node)
5082 "A labeled statement implies that there may be a break to the label.
5083 The function processes the labeled statement and then checks the
5084 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5085 particular label.
5086 Returns logical OR of END_* flags."
5087 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5088 (logior rv (js2-node-get-prop node
5089 'CONTROL_BLOCK_PROP
5090 js2-END_UNREACHED))))
5091
5092 (defun js2-end-check-break (node)
5093 "When a break is encountered annotate the statement being broken
5094 out of by setting its CONTROL_BLOCK_PROP property.
5095 Returns logical OR of END_* flags."
5096 (and (js2-break-node-target node)
5097 (js2-node-set-prop (js2-break-node-target node)
5098 'CONTROL_BLOCK_PROP
5099 js2-END_DROPS_OFF))
5100 js2-END_UNREACHED)
5101
5102 (defun js2-end-check (node)
5103 "Examine the body of a function, doing a basic reachability analysis.
5104 Returns a combination of flags END_* flags that indicate
5105 how the function execution can terminate. These constitute only the
5106 pessimistic set of termination conditions. It is possible that at
5107 runtime certain code paths will never be actually taken. Hence this
5108 analysis will flag errors in cases where there may not be errors.
5109 Returns logical OR of END_* flags"
5110 (let (kid)
5111 (cond
5112 ((js2-break-node-p node)
5113 (js2-end-check-break node))
5114 ((js2-expr-stmt-node-p node)
5115 (if (setq kid (js2-expr-stmt-node-expr node))
5116 (js2-end-check kid)
5117 js2-END_DROPS_OFF))
5118 ((or (js2-continue-node-p node)
5119 (js2-throw-node-p node))
5120 js2-END_UNREACHED)
5121 ((js2-return-node-p node)
5122 (if (setq kid (js2-return-node-retval node))
5123 js2-END_RETURNS_VALUE
5124 js2-END_RETURNS))
5125 ((js2-loop-node-p node)
5126 (js2-end-check-loop node))
5127 ((js2-switch-node-p node)
5128 (js2-end-check-switch node))
5129 ((js2-labeled-stmt-node-p node)
5130 (js2-end-check-label node))
5131 ((js2-if-node-p node)
5132 (js2-end-check-if node))
5133 ((js2-try-node-p node)
5134 (js2-end-check-try node))
5135 ((js2-block-node-p node)
5136 (if (null (js2-block-node-kids node))
5137 js2-END_DROPS_OFF
5138 (js2-end-check-block node)))
5139 ((js2-yield-node-p node)
5140 js2-END_YIELDS)
5141 (t
5142 js2-END_DROPS_OFF))))
5143
5144 (defun js2-always-defined-boolean-p (node)
5145 "Check if NODE always evaluates to true or false in boolean context.
5146 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5147 nor always false."
5148 (let ((tt (js2-node-type node))
5149 num)
5150 (cond
5151 ((or (= tt js2-FALSE) (= tt js2-NULL))
5152 'ALWAYS_FALSE)
5153 ((= tt js2-TRUE)
5154 'ALWAYS_TRUE)
5155 ((= tt js2-NUMBER)
5156 (setq num (js2-number-node-num-value node))
5157 (if (and (not (eq num 0.0e+NaN))
5158 (not (zerop num)))
5159 'ALWAYS_TRUE
5160 'ALWAYS_FALSE))
5161 (t
5162 nil))))
5163
5164 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5165 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5166
5167 (defvar js2-tokens nil
5168 "List of all defined token names.") ; initialized in `js2-token-names'
5169
5170 (defconst js2-token-names
5171 (let* ((names (make-vector js2-num-tokens -1))
5172 (case-fold-search nil) ; only match js2-UPPER_CASE
5173 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5174 (loop for sym in syms
5175 for i from 0
5176 do
5177 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5178 (not (boundp sym)))
5179 (aset names (symbol-value sym) ; code, e.g. 152
5180 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5181 (push sym js2-tokens)))
5182 names)
5183 "Vector mapping int values to token string names, sans `js2-' prefix.")
5184
5185 (defun js2-token-name (tok)
5186 "Return a string name for TOK, a token symbol or code.
5187 Signals an error if it's not a recognized token."
5188 (let ((code tok))
5189 (if (symbolp tok)
5190 (setq code (symbol-value tok)))
5191 (if (eq code -1)
5192 "ERROR"
5193 (if (and (numberp code)
5194 (not (minusp code))
5195 (< code js2-num-tokens))
5196 (aref js2-token-names code)
5197 (error "Invalid token: %s" code)))))
5198
5199 (defsubst js2-token-sym (tok)
5200 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5201 (intern (js2-token-name tok)))
5202
5203 (defconst js2-token-codes
5204 (let ((table (make-hash-table :test 'eq :size 256)))
5205 (loop for name across js2-token-names
5206 for sym = (intern (concat "js2-" name))
5207 do
5208 (puthash sym (symbol-value sym) table))
5209 ;; clean up a few that are "wrong" in Rhino's token codes
5210 (puthash 'js2-DELETE js2-DELPROP table)
5211 table)
5212 "Hashtable mapping token symbols to their bytecodes.")
5213
5214 (defsubst js2-token-code (sym)
5215 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5216 (or (gethash sym js2-token-codes)
5217 (error "Invalid token symbol: %s " sym))) ; signal code bug
5218
5219 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5220 (setq js2-token-end js2-ts-cursor)
5221 (js2-report-error msg nil
5222 (or beg js2-token-beg)
5223 (or len (- js2-token-end js2-token-beg)))
5224 (unless no-throw
5225 (throw 'return js2-ERROR)))
5226
5227 (defsubst js2-get-string-from-buffer ()
5228 "Reverse the char accumulator and return it as a string."
5229 (setq js2-token-end js2-ts-cursor)
5230 (if js2-ts-string-buffer
5231 (apply #'string (nreverse js2-ts-string-buffer))
5232 ""))
5233
5234 ;; TODO: could potentially avoid a lot of consing by allocating a
5235 ;; char buffer the way Rhino does.
5236 (defsubst js2-add-to-string (c)
5237 (push c js2-ts-string-buffer))
5238
5239 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5240 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5241 ;; any other character: when it's not part of the current token, we
5242 ;; unget it, allowing it to be read again by the following call.
5243 (defsubst js2-unget-char ()
5244 (decf js2-ts-cursor))
5245
5246 ;; Rhino distinguishes \r and \n line endings. We don't need to
5247 ;; because we only scan from Emacs buffers, which always use \n.
5248 (defsubst js2-get-char ()
5249 "Read and return the next character from the input buffer.
5250 Increments `js2-ts-lineno' if the return value is a newline char.
5251 Updates `js2-ts-cursor' to the point after the returned char.
5252 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5253 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5254 (let (c)
5255 ;; check for end of buffer
5256 (if (>= js2-ts-cursor (point-max))
5257 (setq js2-ts-hit-eof t
5258 js2-ts-cursor (1+ js2-ts-cursor)
5259 c js2-EOF_CHAR) ; return value
5260 ;; otherwise read next char
5261 (setq c (char-before (incf js2-ts-cursor)))
5262 ;; if we read a newline, update counters
5263 (if (= c ?\n)
5264 (setq js2-ts-line-start js2-ts-cursor
5265 js2-ts-lineno (1+ js2-ts-lineno)))
5266 ;; TODO: skip over format characters
5267 c)))
5268
5269 (defsubst js2-read-unicode-escape ()
5270 "Read a \\uNNNN sequence from the input.
5271 Assumes the ?\ and ?u have already been read.
5272 Returns the unicode character, or nil if it wasn't a valid character.
5273 Doesn't change the values of any scanner variables."
5274 ;; I really wish I knew a better way to do this, but I can't
5275 ;; find the Emacs function that takes a 16-bit int and converts
5276 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5277 ;; Have to first check that it's 4 hex characters or it may stop
5278 ;; the read early.
5279 (ignore-errors
5280 (let ((s (buffer-substring-no-properties js2-ts-cursor
5281 (+ 4 js2-ts-cursor))))
5282 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5283 (read (concat "?\\u" s))))))
5284
5285 (defsubst js2-match-char (test)
5286 "Consume and return next character if it matches TEST, a character.
5287 Returns nil and consumes nothing if TEST is not the next character."
5288 (let ((c (js2-get-char)))
5289 (if (eq c test)
5290 t
5291 (js2-unget-char)
5292 nil)))
5293
5294 (defsubst js2-peek-char ()
5295 (prog1
5296 (js2-get-char)
5297 (js2-unget-char)))
5298
5299 (defsubst js2-java-identifier-start-p (c)
5300 (or
5301 (memq c '(?$ ?_))
5302 (js2-char-uppercase-p c)
5303 (js2-char-lowercase-p c)))
5304
5305 (defsubst js2-java-identifier-part-p (c)
5306 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5307 ;; TODO: make me Unicode-friendly. See comments above.
5308 (or
5309 (memq c '(?$ ?_))
5310 (js2-char-uppercase-p c)
5311 (js2-char-lowercase-p c)
5312 (and (>= c ?0) (<= c ?9))))
5313
5314 (defsubst js2-alpha-p (c)
5315 (cond ((and (<= ?A c) (<= c ?Z)) t)
5316 ((and (<= ?a c) (<= c ?z)) t)
5317 (t nil)))
5318
5319 (defsubst js2-digit-p (c)
5320 (and (<= ?0 c) (<= c ?9)))
5321
5322 (defsubst js2-js-space-p (c)
5323 (if (<= c 127)
5324 (memq c '(#x20 #x9 #xB #xC #xD))
5325 (or
5326 (eq c #xA0)
5327 ;; TODO: change this nil to check for Unicode space character
5328 nil)))
5329
5330 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5331
5332 (defsubst js2-skip-line ()
5333 "Skip to end of line"
5334 (let (c)
5335 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5336 (js2-unget-char)
5337 (setq js2-token-end js2-ts-cursor)))
5338
5339 (defun js2-init-scanner (&optional buf line)
5340 "Create token stream for BUF starting on LINE.
5341 BUF defaults to current-buffer and line defaults to 1.
5342
5343 A buffer can only have one scanner active at a time, which yields
5344 dramatically simpler code than using a defstruct. If you need to
5345 have simultaneous scanners in a buffer, copy the regions to scan
5346 into temp buffers."
5347 (save-excursion
5348 (when buf
5349 (set-buffer buf))
5350 (setq js2-ts-dirty-line nil
5351 js2-ts-regexp-flags nil
5352 js2-ts-string ""
5353 js2-ts-number nil
5354 js2-ts-hit-eof nil
5355 js2-ts-line-start 0
5356 js2-ts-lineno (or line 1)
5357 js2-ts-line-end-char -1
5358 js2-ts-cursor (point-min)
5359 js2-ts-is-xml-attribute nil
5360 js2-ts-xml-is-tag-content nil
5361 js2-ts-xml-open-tags-count 0
5362 js2-ts-string-buffer nil)))
5363
5364 ;; This function uses the cached op, string and number fields in
5365 ;; TokenStream; if getToken has been called since the passed token
5366 ;; was scanned, the op or string printed may be incorrect.
5367 (defun js2-token-to-string (token)
5368 ;; Not sure where this function is used in Rhino. Not tested.
5369 (if (not js2-debug-print-trees)
5370 ""
5371 (let ((name (js2-token-name token)))
5372 (cond
5373 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5374 (concat name " `" js2-ts-string "'"))
5375 ((eq token js2-NUMBER)
5376 (format "NUMBER %g" js2-ts-number))
5377 (t
5378 name)))))
5379
5380 (defconst js2-keywords
5381 '(break
5382 case catch const continue
5383 debugger default delete do
5384 else enum
5385 false finally for function
5386 if in instanceof import
5387 let
5388 new null
5389 return
5390 switch
5391 this throw true try typeof
5392 var void
5393 while with
5394 yield))
5395
5396 ;; Token names aren't exactly the same as the keywords, unfortunately.
5397 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5398 (defconst js2-kwd-tokens
5399 (let ((table (make-vector js2-num-tokens nil))
5400 (tokens
5401 (list js2-BREAK
5402 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5403 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5404 js2-ELSE
5405 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5406 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5407 js2-LET
5408 js2-NEW js2-NULL
5409 js2-RETURN
5410 js2-SWITCH
5411 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5412 js2-VAR
5413 js2-WHILE js2-WITH
5414 js2-YIELD)))
5415 (dolist (i tokens)
5416 (aset table i 'font-lock-keyword-face))
5417 (aset table js2-STRING 'font-lock-string-face)
5418 (aset table js2-REGEXP 'font-lock-string-face)
5419 (aset table js2-COMMENT 'font-lock-comment-face)
5420 (aset table js2-THIS 'font-lock-builtin-face)
5421 (aset table js2-VOID 'font-lock-constant-face)
5422 (aset table js2-NULL 'font-lock-constant-face)
5423 (aset table js2-TRUE 'font-lock-constant-face)
5424 (aset table js2-FALSE 'font-lock-constant-face)
5425 table)
5426 "Vector whose values are non-nil for tokens that are keywords.
5427 The values are default faces to use for highlighting the keywords.")
5428
5429 (defconst js2-reserved-words
5430 '(abstract
5431 boolean byte
5432 char class
5433 double
5434 enum export extends
5435 final float
5436 goto
5437 implements import int interface
5438 long
5439 native
5440 package private protected public
5441 short static super synchronized
5442 throws transient
5443 volatile))
5444
5445 (defconst js2-keyword-names
5446 (let ((table (make-hash-table :test 'equal)))
5447 (loop for k in js2-keywords
5448 do (puthash
5449 (symbol-name k) ; instanceof
5450 (intern (concat "js2-"
5451 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5452 table))
5453 table)
5454 "JavaScript keywords by name, mapped to their symbols.")
5455
5456 (defconst js2-reserved-word-names
5457 (let ((table (make-hash-table :test 'equal)))
5458 (loop for k in js2-reserved-words
5459 do
5460 (puthash (symbol-name k) 'js2-RESERVED table))
5461 table)
5462 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5463
5464 (defsubst js2-collect-string (buf)
5465 "Convert BUF, a list of chars, to a string.
5466 Reverses BUF before converting."
5467 (cond
5468 ((stringp buf)
5469 buf)
5470 ((null buf) ; for emacs21 compat
5471 "")
5472 (t
5473 (if buf
5474 (apply #'string (nreverse buf))
5475 ""))))
5476
5477 (defun js2-string-to-keyword (s)
5478 "Return token for S, a string, if S is a keyword or reserved word.
5479 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5480 (or (gethash s js2-keyword-names)
5481 (gethash s js2-reserved-word-names)))
5482
5483 (defsubst js2-ts-set-char-token-bounds ()
5484 "Used when next token is one character."
5485 (setq js2-token-beg (1- js2-ts-cursor)
5486 js2-token-end js2-ts-cursor))
5487
5488 (defsubst js2-ts-return (token)
5489 "Return an N-character TOKEN from `js2-get-token'.
5490 Updates `js2-token-end' accordingly."
5491 (setq js2-token-end js2-ts-cursor)
5492 (throw 'return token))
5493
5494 (defsubst js2-x-digit-to-int (c accumulator)
5495 "Build up a hex number.
5496 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5497 corresponding number. Otherwise return -1."
5498 (catch 'return
5499 (catch 'check
5500 ;; Use 0..9 < A..Z < a..z
5501 (cond
5502 ((<= c ?9)
5503 (decf c ?0)
5504 (if (<= 0 c)
5505 (throw 'check nil)))
5506 ((<= c ?F)
5507 (when (<= ?A c)
5508 (decf c (- ?A 10))
5509 (throw 'check nil)))
5510 ((<= c ?f)
5511 (when (<= ?a c)
5512 (decf c (- ?a 10))
5513 (throw 'check nil))))
5514 (throw 'return -1))
5515 (logior c (lsh accumulator 4))))
5516
5517 (defun js2-get-token ()
5518 "Return next JavaScript token, an int such as js2-RETURN."
5519 (let (c
5520 c1
5521 identifier-start
5522 is-unicode-escape-start
5523 contains-escape
5524 escape-val
5525 escape-start
5526 str
5527 result
5528 base
5529 is-integer
5530 quote-char
5531 val
5532 look-for-slash
5533 continue)
5534 (catch 'return
5535 (while t
5536 ;; Eat whitespace, possibly sensitive to newlines.
5537 (setq continue t)
5538 (while continue
5539 (setq c (js2-get-char))
5540 (cond
5541 ((eq c js2-EOF_CHAR)
5542 (js2-ts-set-char-token-bounds)
5543 (throw 'return js2-EOF))
5544 ((eq c ?\n)
5545 (js2-ts-set-char-token-bounds)
5546 (setq js2-ts-dirty-line nil)
5547 (throw 'return js2-EOL))
5548 ((not (js2-js-space-p c))
5549 (if (/= c ?-) ; in case end of HTML comment
5550 (setq js2-ts-dirty-line t))
5551 (setq continue nil))))
5552 ;; Assume the token will be 1 char - fixed up below.
5553 (js2-ts-set-char-token-bounds)
5554 (when (eq c ?@)
5555 (throw 'return js2-XMLATTR))
5556 ;; identifier/keyword/instanceof?
5557 ;; watch out for starting with a <backslash>
5558 (cond
5559 ((eq c ?\\)
5560 (setq c (js2-get-char))
5561 (if (eq c ?u)
5562 (setq identifier-start t
5563 is-unicode-escape-start t
5564 js2-ts-string-buffer nil)
5565 (setq identifier-start nil)
5566 (js2-unget-char)
5567 (setq c ?\\)))
5568 (t
5569 (when (setq identifier-start (js2-java-identifier-start-p c))
5570 (setq js2-ts-string-buffer nil)
5571 (js2-add-to-string c))))
5572 (when identifier-start
5573 (setq contains-escape is-unicode-escape-start)
5574 (catch 'break
5575 (while t
5576 (if is-unicode-escape-start
5577 ;; strictly speaking we should probably push-back
5578 ;; all the bad characters if the <backslash>uXXXX
5579 ;; sequence is malformed. But since there isn't a
5580 ;; correct context(is there?) for a bad Unicode
5581 ;; escape sequence in an identifier, we can report
5582 ;; an error here.
5583 (progn
5584 (setq escape-val 0)
5585 (dotimes (i 4)
5586 (setq c (js2-get-char)
5587 escape-val (js2-x-digit-to-int c escape-val))
5588 ;; Next check takes care of c < 0 and bad escape
5589 (if (minusp escape-val)
5590 (throw 'break nil)))
5591 (if (minusp escape-val)
5592 (js2-report-scan-error "msg.invalid.escape" t))
5593 (js2-add-to-string escape-val)
5594 (setq is-unicode-escape-start nil))
5595 (setq c (js2-get-char))
5596 (cond
5597 ((eq c ?\\)
5598 (setq c (js2-get-char))
5599 (if (eq c ?u)
5600 (setq is-unicode-escape-start t
5601 contains-escape t)
5602 (js2-report-scan-error "msg.illegal.character" t)))
5603 (t
5604 (if (or (eq c js2-EOF_CHAR)
5605 (not (js2-java-identifier-part-p c)))
5606 (throw 'break nil))
5607 (js2-add-to-string c))))))
5608 (js2-unget-char)
5609 (setq str (js2-get-string-from-buffer))
5610 (unless contains-escape
5611 ;; OPT we shouldn't have to make a string (object!) to
5612 ;; check if it's a keyword.
5613 ;; Return the corresponding token if it's a keyword
5614 (when (setq result (js2-string-to-keyword str))
5615 (if (and (< js2-language-version 170)
5616 (memq result '(js2-LET js2-YIELD)))
5617 ;; LET and YIELD are tokens only in 1.7 and later
5618 (setq result 'js2-NAME))
5619 (if (not (eq result 'js2-RESERVED))
5620 (throw 'return (js2-token-code result)))
5621 (js2-report-warning "msg.reserved.keyword" str)))
5622 ;; If we want to intern these as Rhino does, just use (intern str)
5623 (setq js2-ts-string str)
5624 (throw 'return js2-NAME)) ; end identifier/kwd check
5625 ;; is it a number?
5626 (when (or (js2-digit-p c)
5627 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5628 (setq js2-ts-string-buffer nil
5629 base 10)
5630 (when (eq c ?0)
5631 (setq c (js2-get-char))
5632 (cond
5633 ((or (eq c ?x) (eq c ?X))
5634 (setq base 16)
5635 (setq c (js2-get-char)))
5636 ((js2-digit-p c)
5637 (setq base 8))
5638 (t
5639 (js2-add-to-string ?0))))
5640 (if (eq base 16)
5641 (while (<= 0 (js2-x-digit-to-int c 0))
5642 (js2-add-to-string c)
5643 (setq c (js2-get-char)))
5644 (while (and (<= ?0 c) (<= c ?9))
5645 ;; We permit 08 and 09 as decimal numbers, which
5646 ;; makes our behavior a superset of the ECMA
5647 ;; numeric grammar. We might not always be so
5648 ;; permissive, so we warn about it.
5649 (when (and (eq base 8) (>= c ?8))
5650 (js2-report-warning "msg.bad.octal.literal"
5651 (if (eq c ?8) "8" "9"))
5652 (setq base 10))
5653 (js2-add-to-string c)
5654 (setq c (js2-get-char))))
5655 (setq is-integer t)
5656 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5657 (setq is-integer nil)
5658 (when (eq c ?.)
5659 (loop do
5660 (js2-add-to-string c)
5661 (setq c (js2-get-char))
5662 while (js2-digit-p c)))
5663 (when (memq c '(?e ?E))
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))
5666 (when (memq c '(?+ ?-))
5667 (js2-add-to-string c)
5668 (setq c (js2-get-char)))
5669 (unless (js2-digit-p c)
5670 (js2-report-scan-error "msg.missing.exponent" t))
5671 (loop do
5672 (js2-add-to-string c)
5673 (setq c (js2-get-char))
5674 while (js2-digit-p c))))
5675 (js2-unget-char)
5676 (setq js2-ts-string (js2-get-string-from-buffer)
5677 js2-ts-number
5678 (if (and (eq base 10) (not is-integer))
5679 (string-to-number js2-ts-string)
5680 ;; TODO: call runtime number-parser. Some of it is in
5681 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5682 (string-to-number js2-ts-string)))
5683 (throw 'return js2-NUMBER))
5684 ;; is it a string?
5685 (when (memq c '(?\" ?\'))
5686 ;; We attempt to accumulate a string the fast way, by
5687 ;; building it directly out of the reader. But if there
5688 ;; are any escaped characters in the string, we revert to
5689 ;; building it out of a string buffer.
5690 (setq quote-char c
5691 js2-ts-string-buffer nil
5692 c (js2-get-char))
5693 (catch 'break
5694 (while (/= c quote-char)
5695 (catch 'continue
5696 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5697 (js2-unget-char)
5698 (setq js2-token-end js2-ts-cursor)
5699 (js2-report-error "msg.unterminated.string.lit")
5700 (throw 'return js2-STRING))
5701 (when (eq c ?\\)
5702 ;; We've hit an escaped character
5703 (setq c (js2-get-char))
5704 (case c
5705 (?b (setq c ?\b))
5706 (?f (setq c ?\f))
5707 (?n (setq c ?\n))
5708 (?r (setq c ?\r))
5709 (?t (setq c ?\t))
5710 (?v (setq c ?\v))
5711 (?u
5712 (setq c1 (js2-read-unicode-escape))
5713 (if js2-parse-ide-mode
5714 (if c1
5715 (progn
5716 ;; just copy the string in IDE-mode
5717 (js2-add-to-string ?\\)
5718 (js2-add-to-string ?u)
5719 (dotimes (i 3)
5720 (js2-add-to-string (js2-get-char)))
5721 (setq c (js2-get-char))) ; added at end of loop
5722 ;; flag it as an invalid escape
5723 (js2-report-warning "msg.invalid.escape"
5724 nil (- js2-ts-cursor 2) 6))
5725 ;; Get 4 hex digits; if the u escape is not
5726 ;; followed by 4 hex digits, use 'u' + the
5727 ;; literal character sequence that follows.
5728 (js2-add-to-string ?u)
5729 (setq escape-val 0)
5730 (dotimes (i 4)
5731 (setq c (js2-get-char)
5732 escape-val (js2-x-digit-to-int c escape-val))
5733 (if (minusp escape-val)
5734 (throw 'continue nil))
5735 (js2-add-to-string c))
5736 ;; prepare for replace of stored 'u' sequence by escape value
5737 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5738 c escape-val)))
5739 (?x
5740 ;; Get 2 hex digits, defaulting to 'x'+literal
5741 ;; sequence, as above.
5742 (setq c (js2-get-char)
5743 escape-val (js2-x-digit-to-int c 0))
5744 (if (minusp escape-val)
5745 (progn
5746 (js2-add-to-string ?x)
5747 (throw 'continue nil))
5748 (setq c1 c
5749 c (js2-get-char)
5750 escape-val (js2-x-digit-to-int c escape-val))
5751 (if (minusp escape-val)
5752 (progn
5753 (js2-add-to-string ?x)
5754 (js2-add-to-string c1)
5755 (throw 'continue nil))
5756 ;; got 2 hex digits
5757 (setq c escape-val))))
5758 (?\n
5759 ;; Remove line terminator after escape to follow
5760 ;; SpiderMonkey and C/C++
5761 (setq c (js2-get-char))
5762 (throw 'continue nil))
5763 (t
5764 (when (and (<= ?0 c) (< c ?8))
5765 (setq val (- c ?0)
5766 c (js2-get-char))
5767 (when (and (<= ?0 c) (< c ?8))
5768 (setq val (- (+ (* 8 val) c) ?0)
5769 c (js2-get-char))
5770 (when (and (<= ?0 c)
5771 (< c ?8)
5772 (< val #o37))
5773 ;; c is 3rd char of octal sequence only
5774 ;; if the resulting val <= 0377
5775 (setq val (- (+ (* 8 val) c) ?0)
5776 c (js2-get-char))))
5777 (js2-unget-char)
5778 (setq c val)))))
5779 (js2-add-to-string c)
5780 (setq c (js2-get-char)))))
5781 (setq js2-ts-string (js2-get-string-from-buffer))
5782 (throw 'return js2-STRING))
5783 (case c
5784 (?\;
5785 (throw 'return js2-SEMI))
5786 (?\[
5787 (throw 'return js2-LB))
5788 (?\]
5789 (throw 'return js2-RB))
5790 (?{
5791 (throw 'return js2-LC))
5792 (?}
5793 (throw 'return js2-RC))
5794 (?\(
5795 (throw 'return js2-LP))
5796 (?\)
5797 (throw 'return js2-RP))
5798 (?,
5799 (throw 'return js2-COMMA))
5800 (??
5801 (throw 'return js2-HOOK))
5802 (?:
5803 (if (js2-match-char ?:)
5804 (js2-ts-return js2-COLONCOLON)
5805 (throw 'return js2-COLON)))
5806 (?.
5807 (if (js2-match-char ?.)
5808 (js2-ts-return js2-DOTDOT)
5809 (if (js2-match-char ?\()
5810 (js2-ts-return js2-DOTQUERY)
5811 (throw 'return js2-DOT))))
5812 (?|
5813 (if (js2-match-char ?|)
5814 (throw 'return js2-OR)
5815 (if (js2-match-char ?=)
5816 (js2-ts-return js2-ASSIGN_BITOR)
5817 (throw 'return js2-BITOR))))
5818 (?^
5819 (if (js2-match-char ?=)
5820 (js2-ts-return js2-ASSIGN_BITOR)
5821 (throw 'return js2-BITXOR)))
5822 (?&
5823 (if (js2-match-char ?&)
5824 (throw 'return js2-AND)
5825 (if (js2-match-char ?=)
5826 (js2-ts-return js2-ASSIGN_BITAND)
5827 (throw 'return js2-BITAND))))
5828 (?=
5829 (if (js2-match-char ?=)
5830 (if (js2-match-char ?=)
5831 (js2-ts-return js2-SHEQ)
5832 (throw 'return js2-EQ))
5833 (throw 'return js2-ASSIGN)))
5834 (?!
5835 (if (js2-match-char ?=)
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-SHNE)
5838 (js2-ts-return js2-NE))
5839 (throw 'return js2-NOT)))
5840 (?<
5841 ;; NB:treat HTML begin-comment as comment-till-eol
5842 (when (js2-match-char ?!)
5843 (when (js2-match-char ?-)
5844 (when (js2-match-char ?-)
5845 (js2-skip-line)
5846 (setq js2-ts-comment-type 'html)
5847 (throw 'return js2-COMMENT)))
5848 (js2-unget-char))
5849 (if (js2-match-char ?<)
5850 (if (js2-match-char ?=)
5851 (js2-ts-return js2-ASSIGN_LSH)
5852 (js2-ts-return js2-LSH))
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-LE)
5855 (throw 'return js2-LT))))
5856 (?>
5857 (if (js2-match-char ?>)
5858 (if (js2-match-char ?>)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-ASSIGN_URSH)
5861 (js2-ts-return js2-URSH))
5862 (if (js2-match-char ?=)
5863 (js2-ts-return js2-ASSIGN_RSH)
5864 (js2-ts-return js2-RSH)))
5865 (if (js2-match-char ?=)
5866 (js2-ts-return js2-GE)
5867 (throw 'return js2-GT))))
5868 (?*
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-ASSIGN_MUL)
5871 (throw 'return js2-MUL)))
5872 (?/
5873 ;; is it a // comment?
5874 (when (js2-match-char ?/)
5875 (setq js2-token-beg (- js2-ts-cursor 2))
5876 (js2-skip-line)
5877 (setq js2-ts-comment-type 'line)
5878 ;; include newline so highlighting goes to end of window
5879 (incf js2-token-end)
5880 (throw 'return js2-COMMENT))
5881 ;; is it a /* comment?
5882 (when (js2-match-char ?*)
5883 (setq look-for-slash nil
5884 js2-token-beg (- js2-ts-cursor 2)
5885 js2-ts-comment-type
5886 (if (js2-match-char ?*)
5887 (progn
5888 (setq look-for-slash t)
5889 'jsdoc)
5890 'block))
5891 (while t
5892 (setq c (js2-get-char))
5893 (cond
5894 ((eq c js2-EOF_CHAR)
5895 (setq js2-token-end (1- js2-ts-cursor))
5896 (js2-report-error "msg.unterminated.comment")
5897 (throw 'return js2-COMMENT))
5898 ((eq c ?*)
5899 (setq look-for-slash t))
5900 ((eq c ?/)
5901 (if look-for-slash
5902 (js2-ts-return js2-COMMENT)))
5903 (t
5904 (setq look-for-slash nil
5905 js2-token-end js2-ts-cursor)))))
5906 (if (js2-match-char ?=)
5907 (js2-ts-return js2-ASSIGN_DIV)
5908 (throw 'return js2-DIV)))
5909 (?#
5910 (when js2-skip-preprocessor-directives
5911 (js2-skip-line)
5912 (setq js2-ts-comment-type 'preprocessor
5913 js2-token-end js2-ts-cursor)
5914 (throw 'return js2-COMMENT))
5915 (throw 'return js2-ERROR))
5916 (?%
5917 (if (js2-match-char ?=)
5918 (js2-ts-return js2-ASSIGN_MOD)
5919 (throw 'return js2-MOD)))
5920 (?~
5921 (throw 'return js2-BITNOT))
5922 (?+
5923 (if (js2-match-char ?=)
5924 (js2-ts-return js2-ASSIGN_ADD)
5925 (if (js2-match-char ?+)
5926 (js2-ts-return js2-INC)
5927 (throw 'return js2-ADD))))
5928 (?-
5929 (cond
5930 ((js2-match-char ?=)
5931 (setq c js2-ASSIGN_SUB))
5932 ((js2-match-char ?-)
5933 (unless js2-ts-dirty-line
5934 ;; treat HTML end-comment after possible whitespace
5935 ;; after line start as comment-until-eol
5936 (when (js2-match-char ?>)
5937 (js2-skip-line)
5938 (setq js2-ts-comment-type 'html)
5939 (throw 'return js2-COMMENT)))
5940 (setq c js2-DEC))
5941 (t
5942 (setq c js2-SUB)))
5943 (setq js2-ts-dirty-line t)
5944 (js2-ts-return c))
5945 (otherwise
5946 (js2-report-scan-error "msg.illegal.character")))))))
5947
5948 (defun js2-read-regexp (start-token)
5949 "Called by parser when it gets / or /= in literal context."
5950 (let (c
5951 err
5952 in-class ; inside a '[' .. ']' character-class
5953 flags
5954 (continue t))
5955 (setq js2-token-beg js2-ts-cursor
5956 js2-ts-string-buffer nil
5957 js2-ts-regexp-flags nil)
5958 (if (eq start-token js2-ASSIGN_DIV)
5959 ;; mis-scanned /=
5960 (js2-add-to-string ?=)
5961 (if (not (eq start-token js2-DIV))
5962 (error "failed assertion")))
5963 (while (and (not err)
5964 (or (/= (setq c (js2-get-char)) ?/)
5965 in-class))
5966 (cond
5967 ((or (= c ?\n)
5968 (= c js2-EOF_CHAR))
5969 (setq js2-token-end (1- js2-ts-cursor)
5970 err t
5971 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5972 (js2-report-error "msg.unterminated.re.lit"))
5973 (t (cond
5974 ((= c ?\\)
5975 (js2-add-to-string c)
5976 (setq c (js2-get-char)))
5977 ((= c ?\[)
5978 (setq in-class t))
5979 ((= c ?\])
5980 (setq in-class nil)))
5981 (js2-add-to-string c))))
5982 (unless err
5983 (while continue
5984 (cond
5985 ((js2-match-char ?g)
5986 (push ?g flags))
5987 ((js2-match-char ?i)
5988 (push ?i flags))
5989 ((js2-match-char ?m)
5990 (push ?m flags))
5991 (t
5992 (setq continue nil))))
5993 (if (js2-alpha-p (js2-peek-char))
5994 (js2-report-scan-error "msg.invalid.re.flag" t
5995 js2-ts-cursor 1))
5996 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5997 js2-ts-regexp-flags (js2-collect-string flags)
5998 js2-token-end js2-ts-cursor)
5999 ;; tell `parse-partial-sexp' to ignore this range of chars
6000 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6001
6002 (defun js2-get-first-xml-token ()
6003 (setq js2-ts-xml-open-tags-count 0
6004 js2-ts-is-xml-attribute nil
6005 js2-ts-xml-is-tag-content nil)
6006 (js2-unget-char)
6007 (js2-get-next-xml-token))
6008
6009 (defsubst js2-xml-discard-string ()
6010 "Throw away the string in progress and flag an XML parse error."
6011 (setq js2-ts-string-buffer nil
6012 js2-ts-string nil)
6013 (js2-report-scan-error "msg.XML.bad.form" t))
6014
6015 (defun js2-get-next-xml-token ()
6016 (setq js2-ts-string-buffer nil ; for recording the XML
6017 js2-token-beg js2-ts-cursor)
6018 (let (c result)
6019 (setq result
6020 (catch 'return
6021 (while t
6022 (setq c (js2-get-char))
6023 (cond
6024 ((= c js2-EOF_CHAR)
6025 (throw 'return js2-ERROR))
6026 (js2-ts-xml-is-tag-content
6027 (case c
6028 (?>
6029 (js2-add-to-string c)
6030 (setq js2-ts-xml-is-tag-content nil
6031 js2-ts-is-xml-attribute nil))
6032 (?/
6033 (js2-add-to-string c)
6034 (when (eq ?> (js2-peek-char))
6035 (setq c (js2-get-char))
6036 (js2-add-to-string c)
6037 (setq js2-ts-xml-is-tag-content nil)
6038 (decf js2-ts-xml-open-tags-count)))
6039 (?{
6040 (js2-unget-char)
6041 (setq js2-ts-string (js2-get-string-from-buffer))
6042 (throw 'return js2-XML))
6043 ((?\' ?\")
6044 (js2-add-to-string c)
6045 (unless (js2-read-quoted-string c)
6046 (throw 'return js2-ERROR)))
6047 (?=
6048 (js2-add-to-string c)
6049 (setq js2-ts-is-xml-attribute t))
6050 ((? ?\t ?\r ?\n)
6051 (js2-add-to-string c))
6052 (t
6053 (js2-add-to-string c)
6054 (setq js2-ts-is-xml-attribute nil)))
6055 (when (and (not js2-ts-xml-is-tag-content)
6056 (zerop js2-ts-xml-open-tags-count))
6057 (setq js2-ts-string (js2-get-string-from-buffer))
6058 (throw 'return js2-XMLEND)))
6059 (t
6060 ;; else not tag content
6061 (case c
6062 (?<
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 (setq c (js2-peek-char))
6070 (case c
6071 (?-
6072 (setq c (js2-get-char)) ;; skip -
6073 (js2-add-to-string c)
6074 (if (eq c ?-)
6075 (progn
6076 (js2-add-to-string c)
6077 (unless (js2-read-xml-comment)
6078 (throw 'return js2-ERROR)))
6079 (js2-xml-discard-string)
6080 (throw 'return js2-ERROR)))
6081 (?\[
6082 (setq c (js2-get-char)) ;; skip [
6083 (js2-add-to-string c)
6084 (if (and (= (js2-get-char) ?C)
6085 (= (js2-get-char) ?D)
6086 (= (js2-get-char) ?A)
6087 (= (js2-get-char) ?T)
6088 (= (js2-get-char) ?A)
6089 (= (js2-get-char) ?\[))
6090 (progn
6091 (js2-add-to-string ?C)
6092 (js2-add-to-string ?D)
6093 (js2-add-to-string ?A)
6094 (js2-add-to-string ?T)
6095 (js2-add-to-string ?A)
6096 (js2-add-to-string ?\[)
6097 (unless (js2-read-cdata)
6098 (throw 'return js2-ERROR)))
6099 (js2-xml-discard-string)
6100 (throw 'return js2-ERROR)))
6101 (t
6102 (unless (js2-read-entity)
6103 (throw 'return js2-ERROR)))))
6104 (??
6105 (setq c (js2-get-char)) ;; skip ?
6106 (js2-add-to-string c)
6107 (unless (js2-read-PI)
6108 (throw 'return js2-ERROR)))
6109 (?/
6110 ;; end tag
6111 (setq c (js2-get-char)) ;; skip /
6112 (js2-add-to-string c)
6113 (when (zerop js2-ts-xml-open-tags-count)
6114 (js2-xml-discard-string)
6115 (throw 'return js2-ERROR))
6116 (setq js2-ts-xml-is-tag-content t)
6117 (decf js2-ts-xml-open-tags-count))
6118 (t
6119 ;; start tag
6120 (setq js2-ts-xml-is-tag-content t)
6121 (incf js2-ts-xml-open-tags-count))))
6122 (?{
6123 (js2-unget-char)
6124 (setq js2-ts-string (js2-get-string-from-buffer))
6125 (throw 'return js2-XML))
6126 (t
6127 (js2-add-to-string c))))))))
6128 (setq js2-token-end js2-ts-cursor)
6129 result))
6130
6131 (defun js2-read-quoted-string (quote)
6132 (let (c)
6133 (catch 'return
6134 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6135 (js2-add-to-string c)
6136 (if (eq c quote)
6137 (throw 'return t)))
6138 (js2-xml-discard-string) ;; throw away string in progress
6139 nil)))
6140
6141 (defun js2-read-xml-comment ()
6142 (let ((c (js2-get-char)))
6143 (catch 'return
6144 (while (/= c js2-EOF_CHAR)
6145 (catch 'continue
6146 (js2-add-to-string c)
6147 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6148 (setq c (js2-get-char))
6149 (js2-add-to-string c)
6150 (if (eq (js2-peek-char) ?>)
6151 (progn
6152 (setq c (js2-get-char)) ;; skip >
6153 (js2-add-to-string c)
6154 (throw 'return t))
6155 (throw 'continue nil)))
6156 (setq c (js2-get-char))))
6157 (js2-xml-discard-string)
6158 nil)))
6159
6160 (defun js2-read-cdata ()
6161 (let ((c (js2-get-char)))
6162 (catch 'return
6163 (while (/= c js2-EOF_CHAR)
6164 (catch 'continue
6165 (js2-add-to-string c)
6166 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6167 (setq c (js2-get-char))
6168 (js2-add-to-string c)
6169 (if (eq (js2-peek-char) ?>)
6170 (progn
6171 (setq c (js2-get-char)) ;; Skip >
6172 (js2-add-to-string c)
6173 (throw 'return t))
6174 (throw 'continue nil)))
6175 (setq c (js2-get-char))))
6176 (js2-xml-discard-string)
6177 nil)))
6178
6179 (defun js2-read-entity ()
6180 (let ((decl-tags 1)
6181 c)
6182 (catch 'return
6183 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6184 (js2-add-to-string c)
6185 (case c
6186 (?<
6187 (incf decl-tags))
6188 (?>
6189 (decf decl-tags)
6190 (if (zerop decl-tags)
6191 (throw 'return t)))))
6192 (js2-xml-discard-string)
6193 nil)))
6194
6195 (defun js2-read-PI ()
6196 "Scan an XML processing instruction."
6197 (let (c)
6198 (catch 'return
6199 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6200 (js2-add-to-string c)
6201 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6202 (setq c (js2-get-char)) ;; Skip >
6203 (js2-add-to-string c)
6204 (throw 'return t)))
6205 (js2-xml-discard-string)
6206 nil)))
6207
6208 (defun js2-scanner-get-line ()
6209 "Return the text of the current scan line."
6210 (buffer-substring (point-at-bol) (point-at-eol)))
6211
6212 ;;; Highlighting
6213
6214 (defsubst js2-set-face (beg end face &optional record)
6215 "Fontify a region. If RECORD is non-nil, record for later."
6216 (when (plusp js2-highlight-level)
6217 (setq beg (min (point-max) beg)
6218 beg (max (point-min) beg)
6219 end (min (point-max) end)
6220 end (max (point-min) end))
6221 (if record
6222 (push (list beg end face) js2-mode-fontifications)
6223 (put-text-property beg end 'face face))))
6224
6225 (defsubst js2-set-kid-face (pos kid len face)
6226 "Set-face on a child node.
6227 POS is absolute buffer position of parent.
6228 KID is the child node.
6229 LEN is the length to fontify.
6230 FACE is the face to fontify with."
6231 (js2-set-face (+ pos (js2-node-pos kid))
6232 (+ pos (js2-node-pos kid) (js2-node-len kid))
6233 face))
6234
6235 (defsubst js2-fontify-kwd (start length)
6236 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6237
6238 (defsubst js2-clear-face (beg end)
6239 (remove-text-properties beg end '(face nil
6240 help-echo nil
6241 point-entered nil
6242 c-in-sws nil)))
6243
6244 (defconst js2-ecma-global-props
6245 (concat "^"
6246 (regexp-opt
6247 '("Infinity" "NaN" "undefined" "arguments") t)
6248 "$")
6249 "Value properties of the Ecma-262 Global Object.
6250 Shown at or above `js2-highlight-level' 2.")
6251
6252 ;; might want to add the name "arguments" to this list?
6253 (defconst js2-ecma-object-props
6254 (concat "^"
6255 (regexp-opt
6256 '("prototype" "__proto__" "__parent__") t)
6257 "$")
6258 "Value properties of the Ecma-262 Object constructor.
6259 Shown at or above `js2-highlight-level' 2.")
6260
6261 (defconst js2-ecma-global-funcs
6262 (concat
6263 "^"
6264 (regexp-opt
6265 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6266 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6267 "$")
6268 "Function properties of the Ecma-262 Global object.
6269 Shown at or above `js2-highlight-level' 2.")
6270
6271 (defconst js2-ecma-number-props
6272 (concat "^"
6273 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6274 "NEGATIVE_INFINITY"
6275 "POSITIVE_INFINITY") t)
6276 "$")
6277 "Properties of the Ecma-262 Number constructor.
6278 Shown at or above `js2-highlight-level' 2.")
6279
6280 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6281 "Properties of the Ecma-262 Date constructor.
6282 Shown at or above `js2-highlight-level' 2.")
6283
6284 (defconst js2-ecma-math-props
6285 (concat "^"
6286 (regexp-opt
6287 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6288 t)
6289 "$")
6290 "Properties of the Ecma-262 Math object.
6291 Shown at or above `js2-highlight-level' 2.")
6292
6293 (defconst js2-ecma-math-funcs
6294 (concat "^"
6295 (regexp-opt
6296 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6297 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6298 "$")
6299 "Function properties of the Ecma-262 Math object.
6300 Shown at or above `js2-highlight-level' 2.")
6301
6302 (defconst js2-ecma-function-props
6303 (concat
6304 "^"
6305 (regexp-opt
6306 '(;; properties of the Object prototype object
6307 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6308 "toLocaleString" "toString" "valueOf"
6309 ;; properties of the Function prototype object
6310 "apply" "call"
6311 ;; properties of the Array prototype object
6312 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6313 "splice" "unshift"
6314 ;; properties of the String prototype object
6315 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6316 "localeCompare" "match" "replace" "search" "split" "substring"
6317 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6318 "toUpperCase"
6319 ;; properties of the Number prototype object
6320 "toExponential" "toFixed" "toPrecision"
6321 ;; properties of the Date prototype object
6322 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6323 "getMinutes" "getMonth" "getSeconds" "getTime"
6324 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6325 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6326 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6327 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6328 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6329 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6330 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6331 "toTimeString" "toUTCString"
6332 ;; properties of the RegExp prototype object
6333 "exec" "test"
6334 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6335 "toSource" "__defineGetter__" "__defineSetter__"
6336 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6337 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6338 t)
6339 "$")
6340 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6341 Shown at or above `js2-highlight-level' 3.")
6342
6343 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6344 (let ((target-name (and target
6345 (js2-name-node-p target)
6346 (js2-name-node-name target)))
6347 (prop-name (if prop (js2-name-node-name prop)))
6348 (level1 (>= js2-highlight-level 1))
6349 (level2 (>= js2-highlight-level 2))
6350 (level3 (>= js2-highlight-level 3))
6351 pos
6352 face)
6353 (when level2
6354 (if call-p
6355 (cond
6356 ((and target prop)
6357 (cond
6358 ((and level3 (string-match js2-ecma-function-props prop-name))
6359 (setq face 'font-lock-builtin-face))
6360 ((and target-name prop)
6361 (cond
6362 ((string= target-name "Date")
6363 (if (string-match js2-ecma-date-props prop-name)
6364 (setq face 'font-lock-builtin-face)))
6365 ((string= target-name "Math")
6366 (if (string-match js2-ecma-math-funcs prop-name)
6367 (setq face 'font-lock-builtin-face)))))))
6368 (prop
6369 (if (string-match js2-ecma-global-funcs prop-name)
6370 (setq face 'font-lock-builtin-face))))
6371 (cond
6372 ((and target prop)
6373 (cond
6374 ((string= target-name "Number")
6375 (if (string-match js2-ecma-number-props prop-name)
6376 (setq face 'font-lock-constant-face)))
6377 ((string= target-name "Math")
6378 (if (string-match js2-ecma-math-props prop-name)
6379 (setq face 'font-lock-constant-face)))))
6380 (prop
6381 (if (string-match js2-ecma-object-props prop-name)
6382 (setq face 'font-lock-constant-face)))))
6383 (when face
6384 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6385 (js2-node-pos prop))) ; relative
6386 (+ pos (js2-node-len prop))
6387 face)))))
6388
6389 (defun js2-parse-highlight-member-expr-node (node)
6390 "Perform syntax highlighting of EcmaScript built-in properties.
6391 The variable `js2-highlight-level' governs this highighting."
6392 (let (face target prop name pos end parent call-p callee)
6393 (cond
6394 ;; case 1: simple name, e.g. foo
6395 ((js2-name-node-p node)
6396 (setq name (js2-name-node-name node))
6397 ;; possible for name to be nil in rare cases - saw it when
6398 ;; running js2-mode on an elisp buffer. Might as well try to
6399 ;; make it so js2-mode never barfs.
6400 (when name
6401 (setq face (if (string-match js2-ecma-global-props name)
6402 'font-lock-constant-face))
6403 (when face
6404 (setq pos (js2-node-pos node)
6405 end (+ pos (js2-node-len node)))
6406 (js2-set-face pos end face))))
6407 ;; case 2: property access or function call
6408 ((or (js2-prop-get-node-p node)
6409 ;; highlight function call if expr is a prop-get node
6410 ;; or a plain name (i.e. unqualified function call)
6411 (and (setq call-p (js2-call-node-p node))
6412 (setq callee (js2-call-node-target node)) ; separate setq!
6413 (or (js2-prop-get-node-p callee)
6414 (js2-name-node-p callee))))
6415 (setq parent node
6416 node (if call-p callee node))
6417 (if (and call-p (js2-name-node-p callee))
6418 (setq prop callee)
6419 (setq target (js2-prop-get-node-left node)
6420 prop (js2-prop-get-node-right node)))
6421 (cond
6422 ((js2-name-node-p target)
6423 (if (js2-name-node-p prop)
6424 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6425 (js2-parse-highlight-prop-get parent target prop call-p)
6426 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6427 (js2-parse-highlight-prop-get parent target nil call-p)))
6428 ((js2-name-node-p prop)
6429 ;; case 2c: complex target, simple name, e.g. x[y].bar
6430 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6431
6432 (defun js2-parse-highlight-member-expr-fn-name (expr)
6433 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6434 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6435 We currently only handle the case where the last component is a prop-get
6436 of a simple name. Called before EXPR has a parent node."
6437 (let (pos
6438 (name (and (js2-prop-get-node-p expr)
6439 (js2-prop-get-node-right expr))))
6440 (when (js2-name-node-p name)
6441 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6442 (js2-node-pos name)))
6443 (+ pos (js2-node-len name))
6444 'font-lock-function-name-face
6445 'record))))
6446
6447 ;; source: http://jsdoc.sourceforge.net/
6448 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6449 ;; allows type specifications, and needs work before entering the wild.
6450
6451 (defconst js2-jsdoc-param-tag-regexp
6452 (concat "^\\s-*\\*+\\s-*\\(@"
6453 "\\(?:param\\|argument\\)"
6454 "\\)"
6455 "\\s-*\\({[^}]+}\\)?" ; optional type
6456 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6457 "\\>")
6458 "Matches jsdoc tags with optional type and optional param name.")
6459
6460 (defconst js2-jsdoc-typed-tag-regexp
6461 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6462 (regexp-opt
6463 '("enum"
6464 "extends"
6465 "field"
6466 "id"
6467 "implements"
6468 "lends"
6469 "mods"
6470 "requires"
6471 "return"
6472 "returns"
6473 "throw"
6474 "throws"))
6475 "\\)\\)\\s-*\\({[^}]+}\\)?")
6476 "Matches jsdoc tags with optional type.")
6477
6478 (defconst js2-jsdoc-arg-tag-regexp
6479 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6480 (regexp-opt
6481 '("alias"
6482 "augments"
6483 "borrows"
6484 "bug"
6485 "base"
6486 "config"
6487 "default"
6488 "define"
6489 "exception"
6490 "function"
6491 "member"
6492 "memberOf"
6493 "name"
6494 "namespace"
6495 "property"
6496 "since"
6497 "suppress"
6498 "this"
6499 "throws"
6500 "type"
6501 "version"))
6502 "\\)\\)\\s-+\\([^ \t]+\\)")
6503 "Matches jsdoc tags with a single argument.")
6504
6505 (defconst js2-jsdoc-empty-tag-regexp
6506 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6507 (regexp-opt
6508 '("addon"
6509 "author"
6510 "class"
6511 "const"
6512 "constant"
6513 "constructor"
6514 "constructs"
6515 "deprecated"
6516 "desc"
6517 "description"
6518 "event"
6519 "example"
6520 "exec"
6521 "export"
6522 "fileoverview"
6523 "final"
6524 "function"
6525 "hidden"
6526 "ignore"
6527 "implicitCast"
6528 "inheritDoc"
6529 "inner"
6530 "interface"
6531 "license"
6532 "noalias"
6533 "noshadow"
6534 "notypecheck"
6535 "override"
6536 "owner"
6537 "preserve"
6538 "preserveTry"
6539 "private"
6540 "protected"
6541 "public"
6542 "static"
6543 "supported"
6544 ))
6545 "\\)\\)\\s-*")
6546 "Matches empty jsdoc tags.")
6547
6548 (defconst js2-jsdoc-link-tag-regexp
6549 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6550 "Matches a jsdoc link or code tag.")
6551
6552 (defconst js2-jsdoc-see-tag-regexp
6553 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6554 "Matches a jsdoc @see tag.")
6555
6556 (defconst js2-jsdoc-html-tag-regexp
6557 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6558 "Matches a simple (no attributes) html start- or end-tag.")
6559
6560 (defsubst js2-jsdoc-highlight-helper ()
6561 (js2-set-face (match-beginning 1)
6562 (match-end 1)
6563 'js2-jsdoc-tag-face)
6564 (if (match-beginning 2)
6565 (if (save-excursion
6566 (goto-char (match-beginning 2))
6567 (= (char-after) ?{))
6568 (js2-set-face (1+ (match-beginning 2))
6569 (1- (match-end 2))
6570 'js2-jsdoc-type-face)
6571 (js2-set-face (match-beginning 2)
6572 (match-end 2)
6573 'js2-jsdoc-value-face)))
6574 (if (match-beginning 3)
6575 (js2-set-face (match-beginning 3)
6576 (match-end 3)
6577 'js2-jsdoc-value-face)))
6578
6579 (defun js2-highlight-jsdoc (ast)
6580 "Highlight doc comment tags."
6581 (let ((comments (js2-ast-root-comments ast))
6582 beg end)
6583 (save-excursion
6584 (dolist (node comments)
6585 (when (eq (js2-comment-node-format node) 'jsdoc)
6586 (setq beg (js2-node-abs-pos node)
6587 end (+ beg (js2-node-len node)))
6588 (save-restriction
6589 (narrow-to-region beg end)
6590 (dolist (re (list js2-jsdoc-param-tag-regexp
6591 js2-jsdoc-typed-tag-regexp
6592 js2-jsdoc-arg-tag-regexp
6593 js2-jsdoc-link-tag-regexp
6594 js2-jsdoc-see-tag-regexp
6595 js2-jsdoc-empty-tag-regexp))
6596 (goto-char beg)
6597 (while (re-search-forward re nil t)
6598 (js2-jsdoc-highlight-helper)))
6599 ;; simple highlighting for html tags
6600 (goto-char beg)
6601 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6602 (js2-set-face (match-beginning 1)
6603 (match-end 1)
6604 'js2-jsdoc-html-tag-delimiter-face)
6605 (js2-set-face (match-beginning 2)
6606 (match-end 2)
6607 'js2-jsdoc-html-tag-name-face)
6608 (js2-set-face (match-beginning 3)
6609 (match-end 3)
6610 'js2-jsdoc-html-tag-delimiter-face))))))))
6611
6612 (defun js2-highlight-assign-targets (node left right)
6613 "Highlight function properties and external variables."
6614 (let (leftpos end name)
6615 ;; highlight vars and props assigned function values
6616 (when (js2-function-node-p right)
6617 (cond
6618 ;; var foo = function() {...}
6619 ((js2-name-node-p left)
6620 (setq name left))
6621 ;; foo.bar.baz = function() {...}
6622 ((and (js2-prop-get-node-p left)
6623 (js2-name-node-p (js2-prop-get-node-right left)))
6624 (setq name (js2-prop-get-node-right left))))
6625 (when name
6626 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6627 (+ leftpos (js2-node-len name))
6628 'font-lock-function-name-face
6629 'record)))))
6630
6631 (defun js2-record-name-node (node)
6632 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6633 later. NODE must be a name node."
6634 (let (leftpos end)
6635 (push (list node js2-current-scope
6636 (setq leftpos (js2-node-abs-pos node))
6637 (setq end (+ leftpos (js2-node-len node))))
6638 js2-recorded-identifiers)))
6639
6640 (defun js2-highlight-undeclared-vars ()
6641 "After entire parse is finished, look for undeclared variable references.
6642 We have to wait until entire buffer is parsed, since JavaScript permits var
6643 decls to occur after they're used.
6644
6645 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6646 it is considered declared."
6647 (let (name)
6648 (dolist (entry js2-recorded-identifiers)
6649 (destructuring-bind (name-node scope pos end) entry
6650 (setq name (js2-name-node-name name-node))
6651 (unless (or (member name js2-global-externs)
6652 (member name js2-default-externs)
6653 (member name js2-additional-externs)
6654 (js2-get-defining-scope scope name))
6655 (js2-set-face pos end 'js2-external-variable-face 'record)
6656 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6657 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6658 (setq js2-recorded-identifiers nil)))
6659
6660 ;;; IMenu support
6661
6662 ;; We currently only support imenu, but eventually should support speedbar and
6663 ;; possibly other browsing mechanisms.
6664
6665 ;; The basic strategy is to identify function assignment targets of the form
6666 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6667 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6668 ;; for imenu after parsing is finished.
6669
6670 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6671 ;; JavaScript, and the general problem is undecidable. However, several forms
6672 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6673 ;; include:
6674
6675 ;; function foo() -- function declaration
6676 ;; foo = function() -- function expression assigned to variable
6677 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6678 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6679 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6680 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6681 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6682 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6683 ;; function foo() {function bar() {...}} -- nested function
6684 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6685
6686 ;; This list boils down to a few forms that can be combined recursively.
6687 ;; Top-level named function declarations include both the left-hand (name)
6688 ;; and the right-hand (function value) expressions needed to produce an imenu
6689 ;; entry. The other "right-hand" forms we need to look for are:
6690 ;; - functions declared as props/getters/setters in object literals
6691 ;; - nested named function declarations
6692 ;; The "left-hand" expressions that functions can be assigned to include:
6693 ;; - local/global variables
6694 ;; - nested property-get expressions like a.b.c.d
6695 ;; - element gets like foo[10] or foo['bar'] where the index
6696 ;; expression can be trivially converted to a property name. They
6697 ;; effectively then become property gets.
6698
6699 ;; All the different definition types are canonicalized into the form
6700 ;; foo.bar.baz = position-of-function-keyword
6701
6702 ;; We need to build a trie-like structure for imenu. As an example,
6703 ;; consider the following JavaScript code:
6704
6705 ;; a = function() {...} // function at position 5
6706 ;; b = function() {...} // function at position 25
6707 ;; foo = function() {...} // function at position 100
6708 ;; foo.bar = function() {...} // function at position 200
6709 ;; foo.bar.baz = function() {...} // function at position 300
6710 ;; foo.bar.zab = function() {...} // function at position 400
6711
6712 ;; During parsing we accumulate an entry for each definition in
6713 ;; the variable `js2-imenu-recorder', like so:
6714
6715 ;; '((a 5)
6716 ;; (b 25)
6717 ;; (foo 100)
6718 ;; (foo bar 200)
6719 ;; (foo bar baz 300)
6720 ;; (foo bar zab 400))
6721
6722 ;; After parsing these entries are merged into this alist-trie:
6723
6724 ;; '((a . 1)
6725 ;; (b . 2)
6726 ;; (foo (<definition> . 3)
6727 ;; (bar (<definition> . 6)
6728 ;; (baz . 100)
6729 ;; (zab . 200))))
6730
6731 ;; Note the wacky need for a <definition> name. The token can be anything
6732 ;; that isn't a valid JavaScript identifier, because you might make foo
6733 ;; a function and then start setting properties on it that are also functions.
6734
6735 (defsubst js2-prop-node-name (node)
6736 "Return the name of a node that may be a property-get/property-name.
6737 If NODE is not a valid name-node, string-node or integral number-node,
6738 returns nil. Otherwise returns the string name/value of the node."
6739 (cond
6740 ((js2-name-node-p node)
6741 (js2-name-node-name node))
6742 ((js2-string-node-p node)
6743 (js2-string-node-value node))
6744 ((and (js2-number-node-p node)
6745 (string-match "^[0-9]+$" (js2-number-node-value node)))
6746 (js2-number-node-value node))
6747 ((js2-this-node-p node)
6748 "this")))
6749
6750 (defsubst js2-node-qname-component (node)
6751 "Test function: return the name of this node, if it contributes to a qname.
6752 Returns nil if the node doesn't contribute."
6753 (copy-sequence
6754 (or (js2-prop-node-name node)
6755 (if (and (js2-function-node-p node)
6756 (js2-function-node-name node))
6757 (js2-name-node-name (js2-function-node-name node))))))
6758
6759 (defsubst js2-record-function-qname (fn-node qname)
6760 "Associate FN-NODE with its QNAME for later lookup.
6761 This is used in postprocessing the chain list. When we find a chain
6762 whose first element is a js2-THIS keyword node, we look up the parent
6763 function and see (using this map) whether it is the tail of a chain.
6764 If so, we replace the this-node with a copy of the parent's qname."
6765 (unless js2-imenu-function-map
6766 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6767 (puthash fn-node qname js2-imenu-function-map))
6768
6769 (defun js2-record-imenu-functions (node &optional var)
6770 "Record function definitions for imenu.
6771 NODE is a function node or an object literal.
6772 VAR, if non-nil, is the expression that NODE is being assigned to."
6773 (when js2-parse-ide-mode
6774 (let ((fun-p (js2-function-node-p node))
6775 qname left fname-node pos)
6776 (cond
6777 ;; non-anonymous function declaration?
6778 ((and fun-p
6779 (not var)
6780 (setq fname-node (js2-function-node-name node)))
6781 (push (setq qname (list fname-node (js2-node-pos node)))
6782 js2-imenu-recorder)
6783 (js2-record-function-qname node qname))
6784 ;; for remaining forms, compute left-side tree branch first
6785 ((and var (setq qname (js2-compute-nested-prop-get var)))
6786 (cond
6787 ;; foo.bar.baz = function
6788 (fun-p
6789 (push (nconc qname (list (js2-node-pos node)))
6790 js2-imenu-recorder)
6791 (js2-record-function-qname node qname))
6792 ;; foo.bar.baz = object-literal
6793 ;; look for nested functions: {a: {b: function() {...} }}
6794 ((js2-object-node-p node)
6795 ;; Node position here is still absolute, since the parser
6796 ;; passes the assignment target and value expressions
6797 ;; to us before they are added as children of the assignment node.
6798 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6799
6800 (defun js2-compute-nested-prop-get (node)
6801 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6802 component nodes as a list. Otherwise return nil. Element-gets are treated
6803 as property-gets if the index expression is a string, or a positive integer."
6804 (let (left right head)
6805 (cond
6806 ((or (js2-name-node-p node)
6807 (js2-this-node-p node))
6808 (list node))
6809 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6810 ((js2-prop-get-node-p node) ; foo.bar
6811 (setq left (js2-prop-get-node-left node)
6812 right (js2-prop-get-node-right node))
6813 (if (setq head (js2-compute-nested-prop-get left))
6814 (nconc head (list right))))
6815 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6816 (setq left (js2-elem-get-node-target node)
6817 right (js2-elem-get-node-element node))
6818 (if (or (js2-string-node-p right) ; ['bar']
6819 (and (js2-number-node-p right) ; [10]
6820 (string-match "^[0-9]+$"
6821 (js2-number-node-value right))))
6822 (if (setq head (js2-compute-nested-prop-get left))
6823 (nconc head (list right))))))))
6824
6825 (defun js2-record-object-literal (node qname pos)
6826 "Recursively process an object literal looking for functions.
6827 NODE is an object literal that is the right-hand child of an assignment
6828 expression. QNAME is a list of nodes representing the assignment target,
6829 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6830 POS is the absolute position of the node.
6831 We do a depth-first traversal of NODE. Any functions we find are prefixed
6832 with QNAME plus the property name of the function and appended to the
6833 variable `js2-imenu-recorder'."
6834 (let (left right)
6835 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6836 (let ((left (js2-infix-node-left e))
6837 ;; Element positions are relative to the parent position.
6838 (pos (+ pos (js2-node-pos e))))
6839 (cond
6840 ;; foo: function() {...}
6841 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6842 (when (js2-prop-node-name left)
6843 ;; As a policy decision, we record the position of the property,
6844 ;; not the position of the `function' keyword, since the property
6845 ;; is effectively the name of the function.
6846 (push (append qname (list left pos))
6847 js2-imenu-recorder)
6848 (js2-record-function-qname right qname)))
6849 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6850 ((js2-object-node-p right)
6851 (js2-record-object-literal right
6852 (append qname (list (js2-infix-node-left e)))
6853 (+ pos (js2-node-pos right)))))))))
6854
6855 (defsubst js2-node-top-level-decl-p (node)
6856 "Return t if NODE's name is defined in the top-level scope.
6857 Also returns t if NODE's name is not defined in any scope, since it implies
6858 that it's an external variable, which must also be in the top-level scope."
6859 (let* ((name (js2-prop-node-name node))
6860 (this-scope (js2-node-get-enclosing-scope node))
6861 defining-scope)
6862 (cond
6863 ((js2-this-node-p node)
6864 nil)
6865 ((null this-scope)
6866 t)
6867 ((setq defining-scope (js2-get-defining-scope this-scope name))
6868 (js2-ast-root-p defining-scope))
6869 (t t))))
6870
6871 (defsubst js2-anonymous-wrapper-fn-p (node)
6872 "Returns t if NODE is an anonymous function that's invoked immediately.
6873 NODE must be `js2-function-node'."
6874 (let ((parent (js2-node-parent node)))
6875 (and (js2-paren-node-p parent)
6876 ;; (function(){...})();
6877 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6878 ;; (function(){...}).call(this);
6879 (and (js2-prop-get-node-p parent)
6880 (member (js2-name-node-name (js2-prop-get-node-right parent))
6881 '("call" "apply"))
6882 (js2-call-node-p (js2-node-parent parent)))))))
6883
6884 (defun js2-browse-postprocess-chains (chains)
6885 "Modify function-declaration name chains after parsing finishes.
6886 Some of the information is only available after the parse tree is complete.
6887 For instance, following a 'this' reference requires a parent function node."
6888 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6889 result head fn fn-type parent-chain p elem parent)
6890 (dolist (chain chains)
6891 ;; examine the head of each node to get its defining scope
6892 (setq head (car chain))
6893 ;; if top-level/external, keep as-is
6894 (if (js2-node-top-level-decl-p head)
6895 (push chain result)
6896 (cond
6897 ;; starts with this-reference
6898 ((js2-this-node-p head)
6899 (setq fn (js2-node-parent-script-or-fn head)
6900 chain (cdr chain))) ; discard this-node
6901 ;; nested named function
6902 ((js2-function-node-p (setq parent (js2-node-parent head)))
6903 (setq fn (js2-node-parent-script-or-fn parent)))
6904 ;; variable assigned a function expression
6905 (t (setq fn (js2-node-parent-script-or-fn head))))
6906 (when fn
6907 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6908 (unless fn-type
6909 (setq fn-type
6910 (cond ((js2-nested-function-p fn) 'skip)
6911 ((setq parent-chain
6912 (gethash fn js2-imenu-function-map))
6913 'named)
6914 ((js2-anonymous-wrapper-fn-p fn) 'anon)
6915 (t 'skip)))
6916 (puthash fn fn-type js2-imenu-fn-type-map))
6917 (case fn-type
6918 ('anon (push chain result)) ; anonymous top-level wrapper
6919 ('named ; top-level named function
6920 ;; prefix parent fn qname, which is
6921 ;; parent-chain sans last elem, to this chain.
6922 (push (append (butlast parent-chain) chain) result))))))
6923 ;; finally replace each node in each chain with its name.
6924 (dolist (chain result)
6925 (setq p chain)
6926 (while p
6927 (if (js2-node-p (setq elem (car p)))
6928 (setcar p (js2-node-qname-component elem)))
6929 (setq p (cdr p))))
6930 result))
6931
6932 ;; Merge name chains into a trie-like tree structure of nested lists.
6933 ;; To simplify construction of the trie, we first build it out using the rule
6934 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6935 ;; [key, num-or-list]. The second element can be a number; if so, this key
6936 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6937 ;; associated with the key at this level.) Otherwise the second element is
6938 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6939 ;; a simple recursive formulation.
6940 ;;
6941 ;; js2-mode is building the data structure for imenu. The imenu documentation
6942 ;; claims that it's the structure above, but in practice it wants the children
6943 ;; at the same list level as the key for that level, which is how I've drawn
6944 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6945 ;; list wrapper around the children at each level.
6946 ;;
6947 ;; A completed nested imenu-alist entry looks like this:
6948 ;; '(("foo"
6949 ;; ("<definition>" . 7)
6950 ;; ("bar"
6951 ;; ("a" . 40)
6952 ;; ("b" . 60))))
6953 ;;
6954 ;; In particular, the documentation for `imenu--index-alist' says that
6955 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6956 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6957
6958 (defsubst js2-treeify (lst)
6959 "Convert (a b c d) to (a ((b ((c d)))))"
6960 (if (null (cddr lst)) ; list length <= 2
6961 lst
6962 (list (car lst) (list (js2-treeify (cdr lst))))))
6963
6964 (defun js2-build-alist-trie (chains trie)
6965 "Merge declaration name chains into a trie-like alist structure for imenu.
6966 CHAINS is the qname chain list produced during parsing. TRIE is a
6967 list of elements built up so far."
6968 (let (head tail pos branch kids)
6969 (dolist (chain chains)
6970 (setq head (car chain)
6971 tail (cdr chain)
6972 pos (if (numberp (car tail)) (car tail))
6973 branch (js2-find-if (lambda (n)
6974 (string= (car n) head))
6975 trie)
6976 kids (second branch))
6977 (cond
6978 ;; case 1: this key isn't in the trie yet
6979 ((null branch)
6980 (if trie
6981 (setcdr (last trie) (list (js2-treeify chain)))
6982 (setq trie (list (js2-treeify chain)))))
6983 ;; case 2: key is present with a single number entry: replace w/ list
6984 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6985 ;; ("<definition>" 20)))
6986 ((numberp kids)
6987 (setcar (cdr branch)
6988 (list (list "<definition-1>" kids)
6989 (if pos
6990 (list "<definition-2>" pos)
6991 (js2-treeify tail)))))
6992 ;; case 3: key is there (with kids), and we're a number entry
6993 (pos
6994 (setcdr (last kids)
6995 (list
6996 (list (format "<definition-%d>"
6997 (1+ (loop for kid in kids
6998 count (eq ?< (aref (car kid) 0)))))
6999 pos))))
7000 ;; case 4: key is there with kids, need to merge in our chain
7001 (t
7002 (js2-build-alist-trie (list tail) kids))))
7003 trie))
7004
7005 (defun js2-flatten-trie (trie)
7006 "Convert TRIE to imenu-format.
7007 Recurses through nodes, and for each one whose second element is a list,
7008 appends the list's flattened elements to the current element. Also
7009 changes the tails into conses. For instance, this pre-flattened trie
7010
7011 '(a ((b 20)
7012 (c ((d 30)
7013 (e 40)))))
7014
7015 becomes
7016
7017 '(a (b . 20)
7018 (c (d . 30)
7019 (e . 40)))
7020
7021 Note that the root of the trie has no key, just a list of chains.
7022 This is also true for the value of any key with multiple children,
7023 e.g. key 'c' in the example above."
7024 (cond
7025 ((listp (car trie))
7026 (mapcar #'js2-flatten-trie trie))
7027 (t
7028 (if (numberp (second trie))
7029 (cons (car trie) (second trie))
7030 ;; else pop list and append its kids
7031 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7032
7033 (defun js2-build-imenu-index ()
7034 "Turn `js2-imenu-recorder' into an imenu data structure."
7035 (unless (eq js2-imenu-recorder 'empty)
7036 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7037 (result (js2-build-alist-trie chains nil)))
7038 (js2-flatten-trie result))))
7039
7040 (defun js2-test-print-chains (chains)
7041 "Print a list of qname chains.
7042 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7043 i.e. one or more nodes, and an integer position as the list tail."
7044 (mapconcat (lambda (chain)
7045 (concat "("
7046 (mapconcat (lambda (elem)
7047 (if (js2-node-p elem)
7048 (or (js2-node-qname-component elem)
7049 "nil")
7050 (number-to-string elem)))
7051 chain
7052 " ")
7053 ")"))
7054 chains
7055 "\n"))
7056
7057 ;;; Parser
7058
7059 (defconst js2-version "1.8.0"
7060 "Version of JavaScript supported, plus minor js2 version.")
7061
7062 (defmacro js2-record-face (face)
7063 "Record a style run of FACE for the current token."
7064 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7065
7066 (defsubst js2-node-end (n)
7067 "Computes the absolute end of node N.
7068 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7069 is only true until the node is added to its parent; i.e., while parsing."
7070 (+ (js2-node-pos n)
7071 (js2-node-len n)))
7072
7073 (defsubst js2-record-comment ()
7074 "Record a comment in `js2-scanned-comments'."
7075 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7076 :format js2-ts-comment-type)
7077 js2-scanned-comments)
7078 (when js2-parse-ide-mode
7079 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7080 'font-lock-doc-face
7081 'font-lock-comment-face))
7082 (when (memq js2-ts-comment-type '(html preprocessor))
7083 ;; Tell cc-engine the bounds of the comment.
7084 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7085
7086 ;; This function is called depressingly often, so it should be fast.
7087 ;; Most of the time it's looking at the same token it peeked before.
7088 (defsubst js2-peek-token ()
7089 "Returns the next token without consuming it.
7090 If previous token was consumed, calls scanner to get new token.
7091 If previous token was -not- consumed, returns it (idempotent).
7092
7093 This function will not return a newline (js2-EOL) - instead, it
7094 gobbles newlines until it finds a non-newline token, and flags
7095 that token as appearing just after a newline.
7096
7097 This function will also not return a js2-COMMENT. Instead, it
7098 records comments found in `js2-scanned-comments'. If the token
7099 returned by this function immediately follows a jsdoc comment,
7100 the token is flagged as such.
7101
7102 Note that this function always returned the un-flagged token!
7103 The flags, if any, are saved in `js2-current-flagged-token'."
7104 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7105 js2-current-token ; most common case - return already-peeked token
7106 (let ((tt (js2-get-token)) ; call scanner
7107 saw-eol
7108 face)
7109 ;; process comments and whitespace
7110 (while (or (= tt js2-EOL)
7111 (= tt js2-COMMENT))
7112 (if (= tt js2-EOL)
7113 (setq saw-eol t)
7114 (setq saw-eol nil)
7115 (if js2-record-comments
7116 (js2-record-comment)))
7117 (setq tt (js2-get-token))) ; call scanner
7118 (setq js2-current-token tt
7119 js2-current-flagged-token (if saw-eol
7120 (logior tt js2-ti-after-eol)
7121 tt))
7122 ;; perform lexical fontification as soon as token is scanned
7123 (when js2-parse-ide-mode
7124 (cond
7125 ((minusp tt)
7126 (js2-record-face 'js2-error-face))
7127 ((setq face (aref js2-kwd-tokens tt))
7128 (js2-record-face face))
7129 ((and (= tt js2-NAME)
7130 (equal js2-ts-string "undefined"))
7131 (js2-record-face 'font-lock-constant-face))))
7132 tt))) ; return unflagged token
7133
7134 (defsubst js2-peek-flagged-token ()
7135 "Returns the current token along with any flags set for it."
7136 (js2-peek-token)
7137 js2-current-flagged-token)
7138
7139 (defsubst js2-consume-token ()
7140 (setq js2-current-flagged-token js2-EOF))
7141
7142 (defsubst js2-next-token ()
7143 (prog1
7144 (js2-peek-token)
7145 (js2-consume-token)))
7146
7147 (defsubst js2-next-flagged-token ()
7148 (js2-peek-token)
7149 (prog1 js2-current-flagged-token
7150 (js2-consume-token)))
7151
7152 (defsubst js2-match-token (match)
7153 "Consume and return t if next token matches MATCH, a bytecode.
7154 Returns nil and consumes nothing if MATCH is not the next token."
7155 (if (/= (js2-peek-token) match)
7156 nil
7157 (js2-consume-token)
7158 t))
7159
7160 (defsubst js2-valid-prop-name-token (tt)
7161 (or (= tt js2-NAME)
7162 (and js2-allow-keywords-as-property-names
7163 (plusp tt)
7164 (aref js2-kwd-tokens tt))))
7165
7166 (defsubst js2-match-prop-name ()
7167 "Consume token and return t if next token is a valid property name.
7168 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7169 is non-nil and it's a keyword token."
7170 (if (js2-valid-prop-name-token (js2-peek-token))
7171 (progn
7172 (js2-consume-token)
7173 t)
7174 nil))
7175
7176 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7177 (if (js2-match-prop-name)
7178 t
7179 (js2-report-error msg-id nil pos len)
7180 nil))
7181
7182 (defsubst js2-peek-token-or-eol ()
7183 "Return js2-EOL if the current token immediately follows a newline.
7184 Else returns the current token. Used in situations where we don't
7185 consider certain token types valid if they are preceded by a newline.
7186 One example is the postfix ++ or -- operator, which has to be on the
7187 same line as its operand."
7188 (let ((tt (js2-peek-token)))
7189 ;; Check for last peeked token flags
7190 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7191 js2-EOL
7192 tt)))
7193
7194 (defsubst js2-set-check-for-label ()
7195 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7196 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7197
7198 (defsubst js2-must-match (token msg-id &optional pos len)
7199 "Match next token to token code TOKEN, or record a syntax error.
7200 MSG-ID is the error message to report if the match fails.
7201 Returns t on match, nil if no match."
7202 (if (js2-match-token token)
7203 t
7204 (js2-report-error msg-id nil pos len)
7205 nil))
7206
7207 (defsubst js2-inside-function ()
7208 (plusp js2-nesting-of-function))
7209
7210 (defsubst js2-set-requires-activation ()
7211 (if (js2-function-node-p js2-current-script-or-fn)
7212 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7213
7214 (defsubst js2-check-activation-name (name token)
7215 (when (js2-inside-function)
7216 ;; skip language-version 1.2 check from Rhino
7217 (if (or (string= "arguments" name)
7218 (and js2-compiler-activation-names ; only used in codegen
7219 (gethash name js2-compiler-activation-names)))
7220 (js2-set-requires-activation))))
7221
7222 (defsubst js2-set-is-generator ()
7223 (if (js2-function-node-p js2-current-script-or-fn)
7224 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7225
7226 (defsubst js2-must-have-xml ()
7227 (unless js2-compiler-xml-available
7228 (js2-report-error "msg.XML.not.available")))
7229
7230 (defsubst js2-push-scope (scope)
7231 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7232 (assert (js2-scope-p scope))
7233 (assert (null (js2-scope-parent-scope scope)))
7234 (assert (not (eq js2-current-scope scope)))
7235 (setf (js2-scope-parent-scope scope) js2-current-scope
7236 js2-current-scope scope))
7237
7238 (defsubst js2-pop-scope ()
7239 (setq js2-current-scope
7240 (js2-scope-parent-scope js2-current-scope)))
7241
7242 (defsubst js2-enter-loop (loop-node)
7243 (push loop-node js2-loop-set)
7244 (push loop-node js2-loop-and-switch-set)
7245 (js2-push-scope loop-node)
7246 ;; Tell the current labeled statement (if any) its statement,
7247 ;; and set the jump target of the first label to the loop.
7248 ;; These are used in `js2-parse-continue' to verify that the
7249 ;; continue target is an actual labeled loop. (And for codegen.)
7250 (when js2-labeled-stmt
7251 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7252 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7253 js2-labeled-stmt))) loop-node)))
7254
7255 (defsubst js2-exit-loop ()
7256 (pop js2-loop-set)
7257 (pop js2-loop-and-switch-set)
7258 (js2-pop-scope))
7259
7260 (defsubst js2-enter-switch (switch-node)
7261 (push switch-node js2-loop-and-switch-set))
7262
7263 (defsubst js2-exit-switch ()
7264 (pop js2-loop-and-switch-set))
7265
7266 (defun js2-parse (&optional buf cb)
7267 "Tells the js2 parser to parse a region of JavaScript.
7268
7269 BUF is a buffer or buffer name containing the code to parse.
7270 Call `narrow-to-region' first to parse only part of the buffer.
7271
7272 The returned AST root node is given some additional properties:
7273 `node-count' - total number of nodes in the AST
7274 `buffer' - BUF. The buffer it refers to may change or be killed,
7275 so the value is not necessarily reliable.
7276
7277 An optional callback CB can be specified to report parsing
7278 progress. If `(functionp CB)' returns t, it will be called with
7279 the current line number once before parsing begins, then again
7280 each time the lexer reaches a new line number.
7281
7282 CB can also be a list of the form `(symbol cb ...)' to specify
7283 multiple callbacks with different criteria. Each symbol is a
7284 criterion keyword, and the following element is the callback to
7285 call
7286
7287 :line - called whenever the line number changes
7288 :token - called for each new token consumed
7289
7290 The list of criteria could be extended to include entering or
7291 leaving a statement, an expression, or a function definition."
7292 (if (and cb (not (functionp cb)))
7293 (error "criteria callbacks not yet implemented"))
7294 (let ((inhibit-point-motion-hooks t)
7295 (js2-compiler-xml-available (>= js2-language-version 160))
7296 ;; This is a recursive-descent parser, so give it a big stack.
7297 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7298 (max-specpdl-size (max max-specpdl-size 3000))
7299 (case-fold-search nil)
7300 ast)
7301 (or buf (setq buf (current-buffer)))
7302 (message nil) ; clear any error message from previous parse
7303 (save-excursion
7304 (set-buffer buf)
7305 (setq js2-scanned-comments nil
7306 js2-parsed-errors nil
7307 js2-parsed-warnings nil
7308 js2-imenu-recorder nil
7309 js2-imenu-function-map nil
7310 js2-label-set nil)
7311 (js2-init-scanner)
7312 (setq ast (js2-with-unmodifying-text-property-changes
7313 (js2-do-parse)))
7314 (unless js2-ts-hit-eof
7315 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7316 (setf (js2-ast-root-errors ast) js2-parsed-errors
7317 (js2-ast-root-warnings ast) js2-parsed-warnings)
7318 ;; if we didn't find any declarations, put a dummy in this list so we
7319 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7320 (unless js2-imenu-recorder
7321 (setq js2-imenu-recorder 'empty))
7322 (run-hooks 'js2-parse-finished-hook)
7323 ast)))
7324
7325 ;; Corresponds to Rhino's Parser.parse() method.
7326 (defun js2-do-parse ()
7327 "Parse current buffer starting from current point.
7328 Scanner should be initialized."
7329 (let ((pos js2-ts-cursor)
7330 (end js2-ts-cursor) ; in case file is empty
7331 root n tt)
7332 ;; initialize buffer-local parsing vars
7333 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7334 js2-current-script-or-fn root
7335 js2-current-scope root
7336 js2-current-flagged-token js2-EOF
7337 js2-nesting-of-function 0
7338 js2-labeled-stmt nil
7339 js2-recorded-identifiers nil) ; for js2-highlight
7340 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7341 (if (= tt js2-FUNCTION)
7342 (progn
7343 (js2-consume-token)
7344 (setq n (js2-parse-function (if js2-called-by-compile-function
7345 'FUNCTION_EXPRESSION
7346 'FUNCTION_STATEMENT))))
7347 ;; not a function - parse a statement
7348 (setq n (js2-parse-statement)))
7349 ;; add function or statement to script
7350 (setq end (js2-node-end n))
7351 (js2-block-node-push root n))
7352 ;; add comments to root in lexical order
7353 (when js2-scanned-comments
7354 ;; if we find a comment beyond end of normal kids, use its end
7355 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7356 (dolist (comment js2-scanned-comments)
7357 (push comment (js2-ast-root-comments root))
7358 (js2-node-add-children root comment)))
7359 (setf (js2-node-len root) (- end pos))
7360 ;; Give extensions a chance to muck with things before highlighting starts.
7361 (dolist (callback js2-post-parse-callbacks)
7362 (funcall callback))
7363 (js2-highlight-undeclared-vars)
7364 root))
7365
7366 (defun js2-function-parser ()
7367 (js2-consume-token)
7368 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7369
7370 (defun js2-parse-function-closure-body (fn-node)
7371 "Parse a JavaScript 1.8 function closure body."
7372 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7373 (if js2-ts-hit-eof
7374 (js2-report-error "msg.no.brace.body" nil
7375 (js2-node-pos fn-node)
7376 (- js2-ts-cursor (js2-node-pos fn-node)))
7377 (js2-node-add-children fn-node
7378 (setf (js2-function-node-body fn-node)
7379 (js2-parse-expr t))))))
7380
7381 (defun js2-parse-function-body (fn-node)
7382 (js2-must-match js2-LC "msg.no.brace.body"
7383 (js2-node-pos fn-node)
7384 (- js2-ts-cursor (js2-node-pos fn-node)))
7385 (let ((pos js2-token-beg) ; LC position
7386 (pn (make-js2-block-node)) ; starts at LC position
7387 tt
7388 end)
7389 (incf js2-nesting-of-function)
7390 (unwind-protect
7391 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7392 (= tt js2-EOF)
7393 (= tt js2-RC)))
7394 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7395 (js2-parse-statement)
7396 (js2-consume-token)
7397 (js2-parse-function 'FUNCTION_STATEMENT))))
7398 (decf js2-nesting-of-function))
7399 (setq end js2-token-end) ; assume no curly and leave at current token
7400 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7401 (setq end js2-token-end))
7402 (setf (js2-node-pos pn) pos
7403 (js2-node-len pn) (- end pos))
7404 (setf (js2-function-node-body fn-node) pn)
7405 (js2-node-add-children fn-node pn)
7406 pn))
7407
7408 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7409 "Declare and fontify destructuring parameters inside NODE.
7410 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7411 (cond
7412 ((js2-name-node-p node)
7413 (let (leftpos)
7414 (js2-define-symbol decl-type (js2-name-node-name node)
7415 node ignore-not-in-block)
7416 (when face
7417 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7418 (+ leftpos (js2-node-len node))
7419 face 'record))))
7420 ((js2-object-node-p node)
7421 (dolist (elem (js2-object-node-elems node))
7422 (js2-define-destruct-symbols
7423 (if (js2-object-prop-node-p elem)
7424 (js2-object-prop-node-right elem)
7425 ;; abbreviated destructuring {a, b}
7426 elem)
7427 decl-type face ignore-not-in-block)))
7428 ((js2-array-node-p node)
7429 (dolist (elem (js2-array-node-elems node))
7430 (when elem
7431 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7432 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7433 (js2-node-len node)))))
7434
7435 (defun js2-parse-function-params (fn-node pos)
7436 (if (js2-match-token js2-RP)
7437 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7438 (let (params len param)
7439 (loop for tt = (js2-peek-token)
7440 do
7441 (cond
7442 ;; destructuring param
7443 ((or (= tt js2-LB) (= tt js2-LC))
7444 (setq param (js2-parse-primary-expr-lhs))
7445 (js2-define-destruct-symbols param
7446 js2-LP
7447 'js2-function-param-face)
7448 (push param params))
7449 ;; simple name
7450 (t
7451 (js2-must-match js2-NAME "msg.no.parm")
7452 (js2-record-face 'js2-function-param-face)
7453 (setq param (js2-create-name-node))
7454 (js2-define-symbol js2-LP js2-ts-string param)
7455 (push param params)))
7456 while
7457 (js2-match-token js2-COMMA))
7458 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7459 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7460 (dolist (p params)
7461 (js2-node-add-children fn-node p)
7462 (push p (js2-function-node-params fn-node))))))
7463
7464 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7465 "Possibly show inconsistent-return warning.
7466 Last token scanned is the close-curly for the function body."
7467 (when (and js2-mode-show-strict-warnings
7468 js2-strict-inconsistent-return-warning
7469 (not (js2-has-consistent-return-usage
7470 (js2-function-node-body fn-node))))
7471 ;; Have it extend from close-curly to bol or beginning of block.
7472 (let ((pos (save-excursion
7473 (goto-char js2-token-end)
7474 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7475 (point-at-bol))))
7476 (end js2-token-end))
7477 (if (plusp (js2-name-node-length name))
7478 (js2-add-strict-warning "msg.no.return.value"
7479 (js2-name-node-name name) pos end)
7480 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7481
7482 (defun js2-parse-function (function-type)
7483 "Function parser. FUNCTION-TYPE is a symbol."
7484 (let ((pos js2-token-beg) ; start of 'function' keyword
7485 name
7486 name-beg
7487 name-end
7488 fn-node
7489 lp
7490 (synthetic-type function-type)
7491 member-expr-node)
7492 ;; parse function name, expression, or non-name (anonymous)
7493 (cond
7494 ;; function foo(...)
7495 ((js2-match-token js2-NAME)
7496 (setq name (js2-create-name-node t)
7497 name-beg js2-token-beg
7498 name-end js2-token-end)
7499 (unless (js2-match-token js2-LP)
7500 (when js2-allow-member-expr-as-function-name
7501 ;; function foo.bar(...)
7502 (setq member-expr-node name
7503 name nil
7504 member-expr-node (js2-parse-member-expr-tail
7505 nil member-expr-node)))
7506 (js2-must-match js2-LP "msg.no.paren.parms")))
7507 ((js2-match-token js2-LP)
7508 nil) ; anonymous function: leave name as null
7509 (t
7510 ;; function random-member-expr(...)
7511 (when js2-allow-member-expr-as-function-name
7512 ;; Note that memberExpr can not start with '(' like
7513 ;; in function (1+2).toString(), because 'function (' already
7514 ;; processed as anonymous function
7515 (setq member-expr-node (js2-parse-member-expr)))
7516 (js2-must-match js2-LP "msg.no.paren.parms")))
7517 (if (= js2-current-token js2-LP) ; eventually matched LP?
7518 (setq lp js2-token-beg))
7519 (if member-expr-node
7520 (progn
7521 (setq synthetic-type 'FUNCTION_EXPRESSION)
7522 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7523 (if name
7524 (js2-set-face name-beg name-end
7525 'font-lock-function-name-face 'record)))
7526 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7527 (plusp (js2-name-node-length name)))
7528 ;; Function statements define a symbol in the enclosing scope
7529 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7530 (setf fn-node (make-js2-function-node :pos pos
7531 :name name
7532 :form function-type
7533 :lp (if lp (- lp pos))))
7534 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7535 ;; 1. Nested functions are not affected by the dynamic scope flag
7536 ;; as dynamic scope is already a parent of their scope.
7537 ;; 2. Functions defined under the with statement also immune to
7538 ;; this setup, in which case dynamic scope is ignored in favor
7539 ;; of the with object.
7540 (setf (js2-function-node-ignore-dynamic fn-node) t))
7541 ;; dynamically bind all the per-function variables
7542 (let ((js2-current-script-or-fn fn-node)
7543 (js2-current-scope fn-node)
7544 (js2-nesting-of-with 0)
7545 (js2-end-flags 0)
7546 js2-label-set
7547 js2-loop-set
7548 js2-loop-and-switch-set)
7549 (js2-parse-function-params fn-node pos)
7550 (if (and (>= js2-language-version 180)
7551 (/= (js2-peek-token) js2-LC))
7552 (js2-parse-function-closure-body fn-node)
7553 (js2-parse-function-body fn-node))
7554 (if name
7555 (js2-node-add-children fn-node name))
7556 (js2-check-inconsistent-return-warning fn-node name)
7557 ;; Function expressions define a name only in the body of the
7558 ;; function, and only if not hidden by a parameter name
7559 (if (and name
7560 (eq synthetic-type 'FUNCTION_EXPRESSION)
7561 (null (js2-scope-get-symbol js2-current-scope
7562 (js2-name-node-name name))))
7563 (js2-define-symbol js2-FUNCTION
7564 (js2-name-node-name name)
7565 fn-node))
7566 (if (and name
7567 (not (eq function-type 'FUNCTION_EXPRESSION)))
7568 (js2-record-imenu-functions fn-node)))
7569 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7570 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7571 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7572 ;; We wait until after parsing the function to set its parent scope,
7573 ;; since `js2-define-symbol' needs the defining-scope check to stop
7574 ;; at the function boundary when checking for redeclarations.
7575 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7576 fn-node))
7577
7578 (defun js2-parse-statements (&optional parent)
7579 "Parse a statement list. Last token consumed must be js2-LC.
7580
7581 PARENT can be a `js2-block-node', in which case the statements are
7582 appended to PARENT. Otherwise a new `js2-block-node' is created
7583 and returned.
7584
7585 This function does not match the closing js2-RC: the caller
7586 matches the RC so it can provide a suitable error message if not
7587 matched. This means it's up to the caller to set the length of
7588 the node to include the closing RC. The node start pos is set to
7589 the absolute buffer start position, and the caller should fix it
7590 up to be relative to the parent node. All children of this block
7591 node are given relative start positions and correct lengths."
7592 (let ((pn (or parent (make-js2-block-node)))
7593 tt)
7594 (setf (js2-node-pos pn) js2-token-beg)
7595 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7596 (/= tt js2-RC))
7597 (js2-block-node-push pn (js2-parse-statement)))
7598 pn))
7599
7600 (defun js2-parse-statement ()
7601 (let (tt pn beg end)
7602 ;; coarse-grained user-interrupt check - needs work
7603 (and js2-parse-interruptable-p
7604 (zerop (% (incf js2-parse-stmt-count)
7605 js2-statements-per-pause))
7606 (input-pending-p)
7607 (throw 'interrupted t))
7608 (setq pn (js2-statement-helper))
7609 ;; no-side-effects warning check
7610 (unless (js2-node-has-side-effects pn)
7611 (setq end (js2-node-end pn))
7612 (save-excursion
7613 (goto-char end)
7614 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7615 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7616 pn))
7617
7618 ;; These correspond to the switch cases in Parser.statementHelper
7619 (defconst js2-parsers
7620 (let ((parsers (make-vector js2-num-tokens
7621 #'js2-parse-expr-stmt)))
7622 (aset parsers js2-BREAK #'js2-parse-break)
7623 (aset parsers js2-CONST #'js2-parse-const-var)
7624 (aset parsers js2-CONTINUE #'js2-parse-continue)
7625 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7626 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7627 (aset parsers js2-DO #'js2-parse-do)
7628 (aset parsers js2-FOR #'js2-parse-for)
7629 (aset parsers js2-FUNCTION #'js2-function-parser)
7630 (aset parsers js2-IF #'js2-parse-if)
7631 (aset parsers js2-LC #'js2-parse-block)
7632 (aset parsers js2-LET #'js2-parse-let-stmt)
7633 (aset parsers js2-NAME #'js2-parse-name-or-label)
7634 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7635 (aset parsers js2-SEMI #'js2-parse-semi)
7636 (aset parsers js2-SWITCH #'js2-parse-switch)
7637 (aset parsers js2-THROW #'js2-parse-throw)
7638 (aset parsers js2-TRY #'js2-parse-try)
7639 (aset parsers js2-VAR #'js2-parse-const-var)
7640 (aset parsers js2-WHILE #'js2-parse-while)
7641 (aset parsers js2-WITH #'js2-parse-with)
7642 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7643 parsers)
7644 "A vector mapping token types to parser functions.")
7645
7646 (defsubst js2-parse-warn-missing-semi (beg end)
7647 (and js2-mode-show-strict-warnings
7648 js2-strict-missing-semi-warning
7649 (js2-add-strict-warning
7650 "msg.missing.semi" nil
7651 ;; back up to beginning of statement or line
7652 (max beg (save-excursion
7653 (goto-char end)
7654 (point-at-bol)))
7655 end)))
7656
7657 (defconst js2-no-semi-insertion
7658 (list js2-IF
7659 js2-SWITCH
7660 js2-WHILE
7661 js2-DO
7662 js2-FOR
7663 js2-TRY
7664 js2-WITH
7665 js2-LC
7666 js2-ERROR
7667 js2-SEMI
7668 js2-FUNCTION)
7669 "List of tokens that don't do automatic semicolon insertion.")
7670
7671 (defconst js2-autoinsert-semi-and-warn
7672 (list js2-ERROR js2-EOF js2-RC))
7673
7674 (defun js2-statement-helper ()
7675 (let* ((tt (js2-peek-token))
7676 (first-tt tt)
7677 (beg js2-token-beg)
7678 (parser (if (= tt js2-ERROR)
7679 #'js2-parse-semi
7680 (aref js2-parsers tt)))
7681 pn
7682 tt-flagged)
7683 ;; If the statement is set, then it's been told its label by now.
7684 (and js2-labeled-stmt
7685 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7686 (setq js2-labeled-stmt nil))
7687 (setq pn (funcall parser))
7688 ;; Don't do auto semi insertion for certain statement types.
7689 (unless (or (memq first-tt js2-no-semi-insertion)
7690 (js2-labeled-stmt-node-p pn))
7691 (js2-auto-insert-semicolon pn))
7692 pn))
7693
7694 (defun js2-auto-insert-semicolon (pn)
7695 (let* ((tt-flagged (js2-peek-flagged-token))
7696 (tt (logand tt-flagged js2-clear-ti-mask))
7697 (pos (js2-node-pos pn)))
7698 (cond
7699 ((= tt js2-SEMI)
7700 ;; Consume ';' as a part of expression
7701 (js2-consume-token)
7702 ;; extend the node bounds to include the semicolon.
7703 (setf (js2-node-len pn) (- js2-token-end pos)))
7704 ((memq tt js2-autoinsert-semi-and-warn)
7705 ;; Autoinsert ;
7706 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7707 (t
7708 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7709 ;; Report error if no EOL or autoinsert ';' otherwise
7710 (js2-report-error "msg.no.semi.stmt")
7711 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7712
7713 (defun js2-parse-condition ()
7714 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7715 The parens are discarded and the expression node is returned.
7716 The `pos' field of the return value is set to an absolute position
7717 that must be fixed up by the caller.
7718 Return value is a list (EXPR LP RP), with absolute paren positions."
7719 (let (pn lp rp)
7720 (if (js2-must-match js2-LP "msg.no.paren.cond")
7721 (setq lp js2-token-beg))
7722 (setq pn (js2-parse-expr))
7723 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7724 (setq rp js2-token-beg))
7725 ;; Report strict warning on code like "if (a = 7) ..."
7726 (if (and js2-strict-cond-assign-warning
7727 (js2-assign-node-p pn))
7728 (js2-add-strict-warning "msg.equal.as.assign" nil
7729 (js2-node-pos pn)
7730 (+ (js2-node-pos pn)
7731 (js2-node-len pn))))
7732 (list pn lp rp)))
7733
7734 (defun js2-parse-if ()
7735 "Parser for if-statement. Last matched token must be js2-IF."
7736 (let ((pos js2-token-beg)
7737 cond
7738 if-true
7739 if-false
7740 else-pos
7741 end
7742 pn)
7743 (js2-consume-token)
7744 (setq cond (js2-parse-condition)
7745 if-true (js2-parse-statement)
7746 if-false (if (js2-match-token js2-ELSE)
7747 (progn
7748 (setq else-pos (- js2-token-beg pos))
7749 (js2-parse-statement)))
7750 end (js2-node-end (or if-false if-true))
7751 pn (make-js2-if-node :pos pos
7752 :len (- end pos)
7753 :condition (car cond)
7754 :then-part if-true
7755 :else-part if-false
7756 :else-pos else-pos
7757 :lp (js2-relpos (second cond) pos)
7758 :rp (js2-relpos (third cond) pos)))
7759 (js2-node-add-children pn (car cond) if-true if-false)
7760 pn))
7761
7762 (defun js2-parse-switch ()
7763 "Parser for if-statement. Last matched token must be js2-SWITCH."
7764 (let ((pos js2-token-beg)
7765 tt
7766 pn
7767 discriminant
7768 has-default
7769 case-expr
7770 case-node
7771 case-pos
7772 cases
7773 stmt
7774 lp
7775 rp)
7776 (js2-consume-token)
7777 (if (js2-must-match js2-LP "msg.no.paren.switch")
7778 (setq lp js2-token-beg))
7779 (setq discriminant (js2-parse-expr)
7780 pn (make-js2-switch-node :discriminant discriminant
7781 :pos pos
7782 :lp (js2-relpos lp pos)))
7783 (js2-node-add-children pn discriminant)
7784 (js2-enter-switch pn)
7785 (unwind-protect
7786 (progn
7787 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7788 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7789 (js2-must-match js2-LC "msg.no.brace.switch")
7790 (catch 'break
7791 (while t
7792 (setq tt (js2-next-token)
7793 case-pos js2-token-beg)
7794 (cond
7795 ((= tt js2-RC)
7796 (setf (js2-node-len pn) (- js2-token-end pos))
7797 (throw 'break nil)) ; done
7798 ((= tt js2-CASE)
7799 (setq case-expr (js2-parse-expr))
7800 (js2-must-match js2-COLON "msg.no.colon.case"))
7801 ((= tt js2-DEFAULT)
7802 (if has-default
7803 (js2-report-error "msg.double.switch.default"))
7804 (setq has-default t
7805 case-expr nil)
7806 (js2-must-match js2-COLON "msg.no.colon.case"))
7807 (t
7808 (js2-report-error "msg.bad.switch")
7809 (throw 'break nil)))
7810 (setq case-node (make-js2-case-node :pos case-pos
7811 :len (- js2-token-end case-pos)
7812 :expr case-expr))
7813 (js2-node-add-children case-node case-expr)
7814 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7815 (/= tt js2-CASE)
7816 (/= tt js2-DEFAULT)
7817 (/= tt js2-EOF))
7818 (setf stmt (js2-parse-statement)
7819 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7820 (js2-block-node-push case-node stmt))
7821 (push case-node cases)))
7822 ;; add cases last, as pushing reverses the order to be correct
7823 (dolist (kid cases)
7824 (js2-node-add-children pn kid)
7825 (push kid (js2-switch-node-cases pn)))
7826 pn) ; return value
7827 (js2-exit-switch))))
7828
7829 (defun js2-parse-while ()
7830 "Parser for while-statement. Last matched token must be js2-WHILE."
7831 (let ((pos js2-token-beg)
7832 (pn (make-js2-while-node))
7833 cond
7834 body)
7835 (js2-consume-token)
7836 (js2-enter-loop pn)
7837 (unwind-protect
7838 (progn
7839 (setf cond (js2-parse-condition)
7840 (js2-while-node-condition pn) (car cond)
7841 body (js2-parse-statement)
7842 (js2-while-node-body pn) body
7843 (js2-node-len pn) (- (js2-node-end body) pos)
7844 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7845 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7846 (js2-node-add-children pn body (car cond)))
7847 (js2-exit-loop))
7848 pn))
7849
7850 (defun js2-parse-do ()
7851 "Parser for do-statement. Last matched token must be js2-DO."
7852 (let ((pos js2-token-beg)
7853 (pn (make-js2-do-node))
7854 cond
7855 body
7856 end)
7857 (js2-consume-token)
7858 (js2-enter-loop pn)
7859 (unwind-protect
7860 (progn
7861 (setq body (js2-parse-statement))
7862 (js2-must-match js2-WHILE "msg.no.while.do")
7863 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7864 cond (js2-parse-condition)
7865 (js2-do-node-condition pn) (car cond)
7866 (js2-do-node-body pn) body
7867 end js2-ts-cursor
7868 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7869 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7870 (js2-node-add-children pn (car cond) body))
7871 (js2-exit-loop))
7872 ;; Always auto-insert semicolon to follow SpiderMonkey:
7873 ;; It is required by ECMAScript but is ignored by the rest of
7874 ;; world; see bug 238945
7875 (if (js2-match-token js2-SEMI)
7876 (setq end js2-ts-cursor))
7877 (setf (js2-node-len pn) (- end pos))
7878 pn))
7879
7880 (defun js2-parse-for ()
7881 "Parser for for-statement. Last matched token must be js2-FOR.
7882 Parses for, for-in, and for each-in statements."
7883 (let ((for-pos js2-token-beg)
7884 pn
7885 is-for-each
7886 is-for-in
7887 in-pos
7888 each-pos
7889 tmp-pos
7890 init ; Node init is also foo in 'foo in object'
7891 cond ; Node cond is also object in 'foo in object'
7892 incr ; 3rd section of for-loop initializer
7893 body
7894 tt
7895 lp
7896 rp)
7897 (js2-consume-token)
7898 ;; See if this is a for each () instead of just a for ()
7899 (when (js2-match-token js2-NAME)
7900 (if (string= "each" js2-ts-string)
7901 (progn
7902 (setq is-for-each t
7903 each-pos (- js2-token-beg for-pos)) ; relative
7904 (js2-record-face 'font-lock-keyword-face))
7905 (js2-report-error "msg.no.paren.for")))
7906 (if (js2-must-match js2-LP "msg.no.paren.for")
7907 (setq lp (- js2-token-beg for-pos)))
7908 (setq tt (js2-peek-token))
7909 ;; parse init clause
7910 (let ((js2-in-for-init t)) ; set as dynamic variable
7911 (cond
7912 ((= tt js2-SEMI)
7913 (setq init (make-js2-empty-expr-node)))
7914 ((or (= tt js2-VAR) (= tt js2-LET))
7915 (js2-consume-token)
7916 (setq init (js2-parse-variables tt js2-token-beg)))
7917 (t
7918 (setq init (js2-parse-expr)))))
7919 (if (js2-match-token js2-IN)
7920 (setq is-for-in t
7921 in-pos (- js2-token-beg for-pos)
7922 cond (js2-parse-expr)) ; object over which we're iterating
7923 ;; else ordinary for loop - parse cond and incr
7924 (js2-must-match js2-SEMI "msg.no.semi.for")
7925 (setq cond (if (= (js2-peek-token) js2-SEMI)
7926 (make-js2-empty-expr-node) ; no loop condition
7927 (js2-parse-expr)))
7928 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7929 (setq tmp-pos js2-token-end
7930 incr (if (= (js2-peek-token) js2-RP)
7931 (make-js2-empty-expr-node :pos tmp-pos)
7932 (js2-parse-expr))))
7933 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7934 (setq rp (- js2-token-beg for-pos)))
7935 (if (not is-for-in)
7936 (setq pn (make-js2-for-node :init init
7937 :condition cond
7938 :update incr
7939 :lp lp
7940 :rp rp))
7941 ;; cond could be null if 'in obj' got eaten by the init node.
7942 (if (js2-infix-node-p init)
7943 ;; it was (foo in bar) instead of (var foo in bar)
7944 (setq cond (js2-infix-node-right init)
7945 init (js2-infix-node-left init))
7946 (if (and (js2-var-decl-node-p init)
7947 (> (length (js2-var-decl-node-kids init)) 1))
7948 (js2-report-error "msg.mult.index")))
7949 (setq pn (make-js2-for-in-node :iterator init
7950 :object cond
7951 :in-pos in-pos
7952 :foreach-p is-for-each
7953 :each-pos each-pos
7954 :lp lp
7955 :rp rp)))
7956 (unwind-protect
7957 (progn
7958 (js2-enter-loop pn)
7959 ;; We have to parse the body -after- creating the loop node,
7960 ;; so that the loop node appears in the js2-loop-set, allowing
7961 ;; break/continue statements to find the enclosing loop.
7962 (setf body (js2-parse-statement)
7963 (js2-loop-node-body pn) body
7964 (js2-node-pos pn) for-pos
7965 (js2-node-len pn) (- (js2-node-end body) for-pos))
7966 (js2-node-add-children pn init cond incr body))
7967 ;; finally
7968 (js2-exit-loop))
7969 pn))
7970
7971 (defun js2-parse-try ()
7972 "Parser for try-statement. Last matched token must be js2-TRY."
7973 (let ((try-pos js2-token-beg)
7974 try-end
7975 try-block
7976 catch-blocks
7977 finally-block
7978 saw-default-catch
7979 peek
7980 param
7981 catch-cond
7982 catch-node
7983 guard-kwd
7984 catch-pos
7985 finally-pos
7986 pn
7987 block
7988 lp
7989 rp)
7990 (js2-consume-token)
7991 (if (/= (js2-peek-token) js2-LC)
7992 (js2-report-error "msg.no.brace.try"))
7993 (setq try-block (js2-parse-statement)
7994 try-end (js2-node-end try-block)
7995 peek (js2-peek-token))
7996 (cond
7997 ((= peek js2-CATCH)
7998 (while (js2-match-token js2-CATCH)
7999 (setq catch-pos js2-token-beg
8000 guard-kwd nil
8001 catch-cond nil
8002 lp nil
8003 rp nil)
8004 (if saw-default-catch
8005 (js2-report-error "msg.catch.unreachable"))
8006 (if (js2-must-match js2-LP "msg.no.paren.catch")
8007 (setq lp (- js2-token-beg catch-pos)))
8008 (js2-push-scope (make-js2-scope))
8009 (let ((tt (js2-peek-token)))
8010 (cond
8011 ;; destructuring pattern
8012 ;; catch ({ message, file }) { ... }
8013 ((or (= tt js2-LB) (= tt js2-LC))
8014 (setq param
8015 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8016 js2-LET nil)))
8017 ;; simple name
8018 (t
8019 (js2-must-match js2-NAME "msg.bad.catchcond")
8020 (setq param (js2-create-name-node))
8021 (js2-define-symbol js2-LET js2-ts-string param))))
8022 ;; pattern guard
8023 (if (js2-match-token js2-IF)
8024 (setq guard-kwd (- js2-token-beg catch-pos)
8025 catch-cond (js2-parse-expr))
8026 (setq saw-default-catch t))
8027 (if (js2-must-match js2-RP "msg.bad.catchcond")
8028 (setq rp (- js2-token-beg catch-pos)))
8029 (js2-must-match js2-LC "msg.no.brace.catchblock")
8030 (setq block (js2-parse-statements)
8031 try-end (js2-node-end block)
8032 catch-node (make-js2-catch-node :pos catch-pos
8033 :param param
8034 :guard-expr catch-cond
8035 :guard-kwd guard-kwd
8036 :block block
8037 :lp lp
8038 :rp rp))
8039 (js2-pop-scope)
8040 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8041 (setq try-end js2-token-beg))
8042 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8043 (js2-node-len catch-node) (- try-end catch-pos))
8044 (js2-node-add-children catch-node param catch-cond block)
8045 (push catch-node catch-blocks)))
8046 ((/= peek js2-FINALLY)
8047 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8048 (js2-node-pos try-block)
8049 (- (setq try-end (js2-node-end try-block))
8050 (js2-node-pos try-block)))))
8051 (when (js2-match-token js2-FINALLY)
8052 (setq finally-pos js2-token-beg
8053 block (js2-parse-statement)
8054 try-end (js2-node-end block)
8055 finally-block (make-js2-finally-node :pos finally-pos
8056 :len (- try-end finally-pos)
8057 :body block))
8058 (js2-node-add-children finally-block block))
8059 (setq pn (make-js2-try-node :pos try-pos
8060 :len (- try-end try-pos)
8061 :try-block try-block
8062 :finally-block finally-block))
8063 (js2-node-add-children pn try-block finally-block)
8064 ;; push them onto the try-node, which reverses and corrects their order
8065 (dolist (cb catch-blocks)
8066 (js2-node-add-children pn cb)
8067 (push cb (js2-try-node-catch-clauses pn)))
8068 pn))
8069
8070 (defun js2-parse-throw ()
8071 "Parser for throw-statement. Last matched token must be js2-THROW."
8072 (let ((pos js2-token-beg)
8073 expr
8074 pn)
8075 (js2-consume-token)
8076 (if (= (js2-peek-token-or-eol) js2-EOL)
8077 ;; ECMAScript does not allow new lines before throw expression,
8078 ;; see bug 256617
8079 (js2-report-error "msg.bad.throw.eol"))
8080 (setq expr (js2-parse-expr)
8081 pn (make-js2-throw-node :pos pos
8082 :len (- (js2-node-end expr) pos)
8083 :expr expr))
8084 (js2-node-add-children pn expr)
8085 pn))
8086
8087 (defsubst js2-match-jump-label-name (label-name)
8088 "If break/continue specified a label, return that label's labeled stmt.
8089 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8090 does not match an existing label, reports an error and returns nil."
8091 (let ((bundle (cdr (assoc label-name js2-label-set))))
8092 (if (null bundle)
8093 (js2-report-error "msg.undef.label"))
8094 bundle))
8095
8096 (defun js2-parse-break ()
8097 "Parser for break-statement. Last matched token must be js2-BREAK."
8098 (let ((pos js2-token-beg)
8099 (end js2-token-end)
8100 break-target ; statement to break from
8101 break-label ; in "break foo", name-node representing the foo
8102 labels ; matching labeled statement to break to
8103 pn)
8104 (js2-consume-token) ; `break'
8105 (when (eq (js2-peek-token-or-eol) js2-NAME)
8106 (js2-consume-token)
8107 (setq break-label (js2-create-name-node)
8108 end (js2-node-end break-label)
8109 ;; matchJumpLabelName only matches if there is one
8110 labels (js2-match-jump-label-name js2-ts-string)
8111 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8112 (unless (or break-target break-label)
8113 ;; no break target specified - try for innermost enclosing loop/switch
8114 (if (null js2-loop-and-switch-set)
8115 (unless break-label
8116 (js2-report-error "msg.bad.break" nil pos (length "break")))
8117 (setq break-target (car js2-loop-and-switch-set))))
8118 (setq pn (make-js2-break-node :pos pos
8119 :len (- end pos)
8120 :label break-label
8121 :target break-target))
8122 (js2-node-add-children pn break-label) ; but not break-target
8123 pn))
8124
8125 (defun js2-parse-continue ()
8126 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8127 (let ((pos js2-token-beg)
8128 (end js2-token-end)
8129 label ; optional user-specified label, a `js2-name-node'
8130 labels ; current matching labeled stmt, if any
8131 target ; the `js2-loop-node' target of this continue stmt
8132 pn)
8133 (js2-consume-token) ; `continue'
8134 (when (= (js2-peek-token-or-eol) js2-NAME)
8135 (js2-consume-token)
8136 (setq label (js2-create-name-node)
8137 end (js2-node-end label)
8138 ;; matchJumpLabelName only matches if there is one
8139 labels (js2-match-jump-label-name js2-ts-string)))
8140 (cond
8141 ((null labels) ; no current label to go to
8142 (if (null js2-loop-set) ; no loop to continue to
8143 (js2-report-error "msg.continue.outside" nil pos
8144 (length "continue"))
8145 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8146 (t
8147 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8148 (setq target (js2-labeled-stmt-node-stmt labels))
8149 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8150 (setq pn (make-js2-continue-node :pos pos
8151 :len (- end pos)
8152 :label label
8153 :target target))
8154 (js2-node-add-children pn label) ; but not target - it's not our child
8155 pn))
8156
8157 (defun js2-parse-with ()
8158 "Parser for with-statement. Last matched token must be js2-WITH."
8159 (js2-consume-token)
8160 (let ((pos js2-token-beg)
8161 obj body pn lp rp)
8162 (if (js2-must-match js2-LP "msg.no.paren.with")
8163 (setq lp js2-token-beg))
8164 (setq obj (js2-parse-expr))
8165 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8166 (setq rp js2-token-beg))
8167 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8168 (setq body (js2-parse-statement)))
8169 (setq pn (make-js2-with-node :pos pos
8170 :len (- (js2-node-end body) pos)
8171 :object obj
8172 :body body
8173 :lp (js2-relpos lp pos)
8174 :rp (js2-relpos rp pos)))
8175 (js2-node-add-children pn obj body)
8176 pn))
8177
8178 (defun js2-parse-const-var ()
8179 "Parser for var- or const-statement.
8180 Last matched token must be js2-CONST or js2-VAR."
8181 (let ((tt (js2-peek-token))
8182 (pos js2-token-beg)
8183 expr
8184 pn)
8185 (js2-consume-token)
8186 (setq expr (js2-parse-variables tt js2-token-beg)
8187 pn (make-js2-expr-stmt-node :pos pos
8188 :len (- (js2-node-end expr) pos)
8189 :expr expr))
8190 (js2-node-add-children pn expr)
8191 pn))
8192
8193 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8194 (let ((pn (make-js2-expr-stmt-node :pos pos
8195 :len (js2-node-len expr)
8196 :type (if (js2-inside-function)
8197 js2-EXPR_VOID
8198 js2-EXPR_RESULT)
8199 :expr expr)))
8200 (if add-child
8201 (js2-node-add-children pn expr))
8202 pn))
8203
8204 (defun js2-parse-let-stmt ()
8205 "Parser for let-statement. Last matched token must be js2-LET."
8206 (js2-consume-token)
8207 (let ((pos js2-token-beg)
8208 expr
8209 pn)
8210 (if (= (js2-peek-token) js2-LP)
8211 ;; let expression in statement context
8212 (setq expr (js2-parse-let pos 'statement)
8213 pn (js2-wrap-with-expr-stmt pos expr t))
8214 ;; else we're looking at a statement like let x=6, y=7;
8215 (setf expr (js2-parse-variables js2-LET pos)
8216 pn (js2-wrap-with-expr-stmt pos expr t)
8217 (js2-node-type pn) js2-EXPR_RESULT))
8218 pn))
8219
8220 (defun js2-parse-ret-yield ()
8221 (js2-parse-return-or-yield (js2-peek-token) nil))
8222
8223 (defconst js2-parse-return-stmt-enders
8224 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8225
8226 (defsubst js2-now-all-set (before after mask)
8227 "Return whether or not the bits in the mask have changed to all set.
8228 BEFORE is bits before change, AFTER is bits after change, and MASK is
8229 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8230 but not BEFORE."
8231 (and (/= (logand before mask) mask)
8232 (= (logand after mask) mask)))
8233
8234 (defun js2-parse-return-or-yield (tt expr-context)
8235 (let ((pos js2-token-beg)
8236 (end js2-token-end)
8237 (before js2-end-flags)
8238 (inside-function (js2-inside-function))
8239 e
8240 ret
8241 name)
8242 (unless inside-function
8243 (js2-report-error (if (eq tt js2-RETURN)
8244 "msg.bad.return"
8245 "msg.bad.yield")))
8246 (js2-consume-token)
8247 ;; This is ugly, but we don't want to require a semicolon.
8248 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8249 (setq e (js2-parse-expr)
8250 end (js2-node-end e)))
8251 (cond
8252 ((eq tt js2-RETURN)
8253 (js2-set-flag js2-end-flags (if (null e)
8254 js2-end-returns
8255 js2-end-returns-value))
8256 (setq ret (make-js2-return-node :pos pos
8257 :len (- end pos)
8258 :retval e))
8259 (js2-node-add-children ret e)
8260 ;; See if we need a strict mode warning.
8261 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8262 ;; more thorough and accurate than this before/after flag check.
8263 ;; E.g. if there's a finally-block that always returns, we shouldn't
8264 ;; show a warning generated by inconsistent returns in the catch blocks.
8265 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8266 ;; so we know which returns/yields to highlight, and we should get rid of
8267 ;; all the checking in `js2-parse-return-or-yield'.
8268 (if (and js2-strict-inconsistent-return-warning
8269 (js2-now-all-set before js2-end-flags
8270 (logior js2-end-returns js2-end-returns-value)))
8271 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8272 (t
8273 (unless (js2-inside-function)
8274 (js2-report-error "msg.bad.yield"))
8275 (js2-set-flag js2-end-flags js2-end-yields)
8276 (setq ret (make-js2-yield-node :pos pos
8277 :len (- end pos)
8278 :value e))
8279 (js2-node-add-children ret e)
8280 (unless expr-context
8281 (setq e ret
8282 ret (js2-wrap-with-expr-stmt pos e t))
8283 (js2-set-requires-activation)
8284 (js2-set-is-generator))))
8285 ;; see if we are mixing yields and value returns.
8286 (when (and inside-function
8287 (js2-now-all-set before js2-end-flags
8288 (logior js2-end-yields js2-end-returns-value)))
8289 (setq name (js2-function-name js2-current-script-or-fn))
8290 (if (zerop (length name))
8291 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8292 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8293 ret))
8294
8295 (defun js2-parse-debugger ()
8296 (js2-consume-token)
8297 (make-js2-keyword-node :type js2-DEBUGGER))
8298
8299 (defun js2-parse-block ()
8300 "Parser for a curly-delimited statement block.
8301 Last token matched must be js2-LC."
8302 (let ((pos js2-token-beg)
8303 (pn (make-js2-scope)))
8304 (js2-consume-token)
8305 (js2-push-scope pn)
8306 (unwind-protect
8307 (progn
8308 (js2-parse-statements pn)
8309 (js2-must-match js2-RC "msg.no.brace.block")
8310 (setf (js2-node-len pn) (- js2-token-end pos)))
8311 (js2-pop-scope))
8312 pn))
8313
8314 ;; for js2-ERROR too, to have a node for error recovery to work on
8315 (defun js2-parse-semi ()
8316 "Parse a statement or handle an error.
8317 Last matched token is js-SEMI or js-ERROR."
8318 (let ((tt (js2-peek-token)) pos len)
8319 (js2-consume-token)
8320 (if (eq tt js2-SEMI)
8321 (make-js2-empty-expr-node :len 1)
8322 (setq pos js2-token-beg
8323 len (- js2-token-beg pos))
8324 (js2-report-error "msg.syntax" nil pos len)
8325 (make-js2-error-node :pos pos :len len))))
8326
8327 (defun js2-parse-default-xml-namespace ()
8328 "Parse a `default xml namespace = <expr>' e4x statement."
8329 (let ((pos js2-token-beg)
8330 end len expr unary es)
8331 (js2-consume-token)
8332 (js2-must-have-xml)
8333 (js2-set-requires-activation)
8334 (setq len (- js2-ts-cursor pos))
8335 (unless (and (js2-match-token js2-NAME)
8336 (string= js2-ts-string "xml"))
8337 (js2-report-error "msg.bad.namespace" nil pos len))
8338 (unless (and (js2-match-token js2-NAME)
8339 (string= js2-ts-string "namespace"))
8340 (js2-report-error "msg.bad.namespace" nil pos len))
8341 (unless (js2-match-token js2-ASSIGN)
8342 (js2-report-error "msg.bad.namespace" nil pos len))
8343 (setq expr (js2-parse-expr)
8344 end (js2-node-end expr)
8345 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8346 :pos pos
8347 :len (- end pos)
8348 :operand expr))
8349 (js2-node-add-children unary expr)
8350 (make-js2-expr-stmt-node :pos pos
8351 :len (- end pos)
8352 :expr unary)))
8353
8354 (defun js2-record-label (label bundle)
8355 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8356 (js2-consume-token)
8357 (let ((name (js2-label-node-name label))
8358 labeled-stmt
8359 dup)
8360 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8361 ;; flag both labels if possible when used in editing mode
8362 (if (and js2-parse-ide-mode
8363 (setq dup (js2-get-label-by-name labeled-stmt name)))
8364 (js2-report-error "msg.dup.label" nil
8365 (js2-node-abs-pos dup) (js2-node-len dup)))
8366 (js2-report-error "msg.dup.label" nil
8367 (js2-node-pos label) (js2-node-len label)))
8368 (js2-labeled-stmt-node-add-label bundle label)
8369 (js2-node-add-children bundle label)
8370 ;; Add one reference to the bundle per label in `js2-label-set'
8371 (push (cons name bundle) js2-label-set)))
8372
8373 (defun js2-parse-name-or-label ()
8374 "Parser for identifier or label. Last token matched must be js2-NAME.
8375 Called when we found a name in a statement context. If it's a label, we gather
8376 up any following labels and the next non-label statement into a
8377 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8378 expression and return it wrapped in a `js2-expr-stmt-node'."
8379 (let ((pos js2-token-beg)
8380 (end js2-token-end)
8381 expr
8382 stmt
8383 pn
8384 bundle
8385 (continue t))
8386 ;; set check for label and call down to `js2-parse-primary-expr'
8387 (js2-set-check-for-label)
8388 (setq expr (js2-parse-expr))
8389 (if (/= (js2-node-type expr) js2-LABEL)
8390 ;; Parsed non-label expression - wrap with expression stmt.
8391 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8392 ;; else parsed a label
8393 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8394 (js2-record-label expr bundle)
8395 ;; look for more labels
8396 (while (and continue (= (js2-peek-token) js2-NAME))
8397 (js2-set-check-for-label)
8398 (setq expr (js2-parse-expr))
8399 (if (/= (js2-node-type expr) js2-LABEL)
8400 (progn
8401 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8402 continue nil)
8403 (js2-auto-insert-semicolon stmt))
8404 (js2-record-label expr bundle)))
8405 ;; no more labels; now parse the labeled statement
8406 (unwind-protect
8407 (unless stmt
8408 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8409 (setq stmt (js2-statement-helper))))
8410 ;; remove the labels for this statement from the global set
8411 (dolist (label (js2-labeled-stmt-node-labels bundle))
8412 (setq js2-label-set (remove label js2-label-set))))
8413 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8414 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8415 (js2-node-add-children bundle stmt)
8416 bundle)))
8417
8418 (defun js2-parse-expr-stmt ()
8419 "Default parser in statement context, if no recognized statement found."
8420 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8421
8422 (defun js2-parse-variables (decl-type pos)
8423 "Parse a comma-separated list of variable declarations.
8424 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8425
8426 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8427 For 'var' or 'const', the keyword should be the token last scanned.
8428
8429 POS is the position where the node should start. It's sometimes the
8430 var/const/let keyword, and other times the beginning of the first token
8431 in the first variable declaration.
8432
8433 Returns the parsed `js2-var-decl-node' expression node."
8434 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8435 :pos pos))
8436 destructuring
8437 kid-pos
8438 tt
8439 init
8440 name
8441 end
8442 nbeg nend
8443 vi
8444 (continue t))
8445 ;; Example:
8446 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8447 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8448 ;; var {a, b} = baz;
8449 (while continue
8450 (setq destructuring nil
8451 name nil
8452 tt (js2-peek-token)
8453 kid-pos js2-token-beg
8454 end js2-token-end
8455 init nil)
8456 (if (or (= tt js2-LB) (= tt js2-LC))
8457 ;; Destructuring assignment, e.g., var [a, b] = ...
8458 (setq destructuring (js2-parse-primary-expr-lhs)
8459 end (js2-node-end destructuring))
8460 ;; Simple variable name
8461 (when (js2-must-match js2-NAME "msg.bad.var")
8462 (setq name (js2-create-name-node)
8463 nbeg js2-token-beg
8464 nend js2-token-end
8465 end nend)
8466 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8467 (when (js2-match-token js2-ASSIGN)
8468 (setq init (js2-parse-assign-expr)
8469 end (js2-node-end init))
8470 (if (and js2-parse-ide-mode
8471 (or (js2-object-node-p init)
8472 (js2-function-node-p init)))
8473 (js2-record-imenu-functions init name)))
8474 (when name
8475 (js2-set-face nbeg nend (if (js2-function-node-p init)
8476 'font-lock-function-name-face
8477 'font-lock-variable-name-face)
8478 'record))
8479 (setq vi (make-js2-var-init-node :pos kid-pos
8480 :len (- end kid-pos)
8481 :type decl-type))
8482 (if destructuring
8483 (progn
8484 (if (and (null init) (not js2-in-for-init))
8485 (js2-report-error "msg.destruct.assign.no.init"))
8486 (js2-define-destruct-symbols destructuring
8487 decl-type
8488 'font-lock-variable-name-face)
8489 (setf (js2-var-init-node-target vi) destructuring))
8490 (setf (js2-var-init-node-target vi) name))
8491 (setf (js2-var-init-node-initializer vi) init)
8492 (js2-node-add-children vi name destructuring init)
8493 (js2-block-node-push result vi)
8494 (unless (js2-match-token js2-COMMA)
8495 (setq continue nil)))
8496 (setf (js2-node-len result) (- end pos))
8497 result))
8498
8499 (defun js2-parse-let (pos &optional stmt-p)
8500 "Parse a let expression or statement.
8501 A let-expression is of the form `let (vars) expr'.
8502 A let-statment is of the form `let (vars) {statements}'.
8503 The third form of let is a variable declaration list, handled
8504 by `js2-parse-variables'."
8505 (let ((pn (make-js2-let-node :pos pos))
8506 beg vars body)
8507 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8508 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8509 (js2-push-scope pn)
8510 (unwind-protect
8511 (progn
8512 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8513 (if (js2-must-match js2-RP "msg.no.paren.let")
8514 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8515 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8516 ;; let statement
8517 (progn
8518 (js2-consume-token)
8519 (setf beg js2-token-beg ; position stmt at LC
8520 body (js2-parse-statements))
8521 (js2-must-match js2-RC "msg.no.curly.let")
8522 (setf (js2-node-len body) (- js2-token-end beg)
8523 (js2-node-len pn) (- js2-token-end pos)
8524 (js2-let-node-body pn) body
8525 (js2-node-type pn) js2-LET))
8526 ;; let expression
8527 (setf body (js2-parse-expr)
8528 (js2-node-len pn) (- (js2-node-end body) pos)
8529 (js2-let-node-body pn) body))
8530 (js2-node-add-children pn vars body))
8531 (js2-pop-scope))
8532 pn))
8533
8534 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8535 (js2-scope-put-symbol (or scope js2-current-scope)
8536 name
8537 (make-js2-symbol decl-type name node)))
8538
8539 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8540 "Define a symbol in the current scope.
8541 If NODE is non-nil, it is the AST node associated with the symbol."
8542 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8543 (symbol (if defining-scope
8544 (js2-scope-get-symbol defining-scope name)))
8545 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8546 (cond
8547 ((and symbol ; already defined
8548 (or (= sdt js2-CONST) ; old version is const
8549 (= decl-type js2-CONST) ; new version is const
8550 ;; two let-bound vars in this block have same name
8551 (and (= sdt js2-LET)
8552 (eq defining-scope js2-current-scope))))
8553 (js2-report-error
8554 (cond
8555 ((= sdt js2-CONST) "msg.const.redecl")
8556 ((= sdt js2-LET) "msg.let.redecl")
8557 ((= sdt js2-VAR) "msg.var.redecl")
8558 ((= sdt js2-FUNCTION) "msg.function.redecl")
8559 (t "msg.parm.redecl"))
8560 name))
8561 ((= decl-type js2-LET)
8562 (if (and (not ignore-not-in-block)
8563 (or (= (js2-node-type js2-current-scope) js2-IF)
8564 (js2-loop-node-p js2-current-scope)))
8565 (js2-report-error "msg.let.decl.not.in.block")
8566 (js2-define-new-symbol decl-type name node)))
8567 ((or (= decl-type js2-VAR)
8568 (= decl-type js2-CONST)
8569 (= decl-type js2-FUNCTION))
8570 (if symbol
8571 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8572 (js2-add-strict-warning "msg.var.redecl" name)
8573 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8574 (js2-add-strict-warning "msg.var.hides.arg" name)))
8575 (js2-define-new-symbol decl-type name node
8576 js2-current-script-or-fn)))
8577 ((= decl-type js2-LP)
8578 (if symbol
8579 ;; must be duplicate parameter. Second parameter hides the
8580 ;; first, so go ahead and add the second pararameter
8581 (js2-report-warning "msg.dup.parms" name))
8582 (js2-define-new-symbol decl-type name node))
8583 (t (js2-code-bug)))))
8584
8585 (defun js2-parse-expr (&optional oneshot)
8586 (let* ((pn (js2-parse-assign-expr))
8587 (pos (js2-node-pos pn))
8588 left
8589 right
8590 op-pos)
8591 (while (and (not oneshot)
8592 (js2-match-token js2-COMMA))
8593 (setq op-pos (- js2-token-beg pos)) ; relative
8594 (if (= (js2-peek-token) js2-YIELD)
8595 (js2-report-error "msg.yield.parenthesized"))
8596 (setq right (js2-parse-assign-expr)
8597 left pn
8598 pn (make-js2-infix-node :type js2-COMMA
8599 :pos pos
8600 :len (- js2-ts-cursor pos)
8601 :op-pos op-pos
8602 :left left
8603 :right right))
8604 (js2-node-add-children pn left right))
8605 pn))
8606
8607 (defun js2-parse-assign-expr ()
8608 (let ((tt (js2-peek-token))
8609 (pos js2-token-beg)
8610 pn
8611 left
8612 right
8613 op-pos)
8614 (if (= tt js2-YIELD)
8615 (js2-parse-return-or-yield tt t)
8616 ;; not yield - parse assignment expression
8617 (setq pn (js2-parse-cond-expr)
8618 tt (js2-peek-token))
8619 (when (and (<= js2-first-assign tt)
8620 (<= tt js2-last-assign))
8621 ;; tt express assignment (=, |=, ^=, ..., %=)
8622 (js2-consume-token)
8623 (setq op-pos (- js2-token-beg pos) ; relative
8624 left pn
8625 right (js2-parse-assign-expr)
8626 pn (make-js2-assign-node :type tt
8627 :pos pos
8628 :len (- (js2-node-end right) pos)
8629 :op-pos op-pos
8630 :left left
8631 :right right))
8632 (when js2-parse-ide-mode
8633 (js2-highlight-assign-targets pn left right)
8634 (if (or (js2-function-node-p right)
8635 (js2-object-node-p right))
8636 (js2-record-imenu-functions right left)))
8637 ;; do this last so ide checks above can use absolute positions
8638 (js2-node-add-children pn left right))
8639 pn)))
8640
8641 (defun js2-parse-cond-expr ()
8642 (let ((pos js2-token-beg)
8643 (pn (js2-parse-or-expr))
8644 test-expr
8645 if-true
8646 if-false
8647 q-pos
8648 c-pos)
8649 (when (js2-match-token js2-HOOK)
8650 (setq q-pos (- js2-token-beg pos)
8651 if-true (js2-parse-assign-expr))
8652 (js2-must-match js2-COLON "msg.no.colon.cond")
8653 (setq c-pos (- js2-token-beg pos)
8654 if-false (js2-parse-assign-expr)
8655 test-expr pn
8656 pn (make-js2-cond-node :pos pos
8657 :len (- (js2-node-end if-false) pos)
8658 :test-expr test-expr
8659 :true-expr if-true
8660 :false-expr if-false
8661 :q-pos q-pos
8662 :c-pos c-pos))
8663 (js2-node-add-children pn test-expr if-true if-false))
8664 pn))
8665
8666 (defun js2-make-binary (type left parser)
8667 "Helper for constructing a binary-operator AST node.
8668 LEFT is the left-side-expression, already parsed, and the
8669 binary operator should have just been matched.
8670 PARSER is a function to call to parse the right operand,
8671 or a `js2-node' struct if it has already been parsed."
8672 (let* ((pos (js2-node-pos left))
8673 (op-pos (- js2-token-beg pos))
8674 (right (if (js2-node-p parser)
8675 parser
8676 (funcall parser)))
8677 (pn (make-js2-infix-node :type type
8678 :pos pos
8679 :len (- (js2-node-end right) pos)
8680 :op-pos op-pos
8681 :left left
8682 :right right)))
8683 (js2-node-add-children pn left right)
8684 pn))
8685
8686 (defun js2-parse-or-expr ()
8687 (let ((pn (js2-parse-and-expr)))
8688 (when (js2-match-token js2-OR)
8689 (setq pn (js2-make-binary js2-OR
8690 pn
8691 'js2-parse-or-expr)))
8692 pn))
8693
8694 (defun js2-parse-and-expr ()
8695 (let ((pn (js2-parse-bit-or-expr)))
8696 (when (js2-match-token js2-AND)
8697 (setq pn (js2-make-binary js2-AND
8698 pn
8699 'js2-parse-and-expr)))
8700 pn))
8701
8702 (defun js2-parse-bit-or-expr ()
8703 (let ((pn (js2-parse-bit-xor-expr)))
8704 (while (js2-match-token js2-BITOR)
8705 (setq pn (js2-make-binary js2-BITOR
8706 pn
8707 'js2-parse-bit-xor-expr)))
8708 pn))
8709
8710 (defun js2-parse-bit-xor-expr ()
8711 (let ((pn (js2-parse-bit-and-expr)))
8712 (while (js2-match-token js2-BITXOR)
8713 (setq pn (js2-make-binary js2-BITXOR
8714 pn
8715 'js2-parse-bit-and-expr)))
8716 pn))
8717
8718 (defun js2-parse-bit-and-expr ()
8719 (let ((pn (js2-parse-eq-expr)))
8720 (while (js2-match-token js2-BITAND)
8721 (setq pn (js2-make-binary js2-BITAND
8722 pn
8723 'js2-parse-eq-expr)))
8724 pn))
8725
8726 (defconst js2-parse-eq-ops
8727 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8728
8729 (defun js2-parse-eq-expr ()
8730 (let ((pn (js2-parse-rel-expr))
8731 tt)
8732 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8733 (js2-consume-token)
8734 (setq pn (js2-make-binary tt
8735 pn
8736 'js2-parse-rel-expr)))
8737 pn))
8738
8739 (defconst js2-parse-rel-ops
8740 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8741
8742 (defun js2-parse-rel-expr ()
8743 (let ((pn (js2-parse-shift-expr))
8744 (continue t)
8745 tt)
8746 (while continue
8747 (setq tt (js2-peek-token))
8748 (cond
8749 ((and js2-in-for-init (= tt js2-IN))
8750 (setq continue nil))
8751 ((memq tt js2-parse-rel-ops)
8752 (js2-consume-token)
8753 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8754 (t
8755 (setq continue nil))))
8756 pn))
8757
8758 (defconst js2-parse-shift-ops
8759 (list js2-LSH js2-URSH js2-RSH))
8760
8761 (defun js2-parse-shift-expr ()
8762 (let ((pn (js2-parse-add-expr))
8763 tt
8764 (continue t))
8765 (while continue
8766 (setq tt (js2-peek-token))
8767 (if (memq tt js2-parse-shift-ops)
8768 (progn
8769 (js2-consume-token)
8770 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8771 (setq continue nil)))
8772 pn))
8773
8774 (defun js2-parse-add-expr ()
8775 (let ((pn (js2-parse-mul-expr))
8776 tt
8777 (continue t))
8778 (while continue
8779 (setq tt (js2-peek-token))
8780 (if (or (= tt js2-ADD) (= tt js2-SUB))
8781 (progn
8782 (js2-consume-token)
8783 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8784 (setq continue nil)))
8785 pn))
8786
8787 (defconst js2-parse-mul-ops
8788 (list js2-MUL js2-DIV js2-MOD))
8789
8790 (defun js2-parse-mul-expr ()
8791 (let ((pn (js2-parse-unary-expr))
8792 tt
8793 (continue t))
8794 (while continue
8795 (setq tt (js2-peek-token))
8796 (if (memq tt js2-parse-mul-ops)
8797 (progn
8798 (js2-consume-token)
8799 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8800 (setq continue nil)))
8801 pn))
8802
8803 (defsubst js2-make-unary (type parser &rest args)
8804 "Make a unary node of type TYPE.
8805 PARSER is either a node (for postfix operators) or a function to call
8806 to parse the operand (for prefix operators)."
8807 (let* ((pos js2-token-beg)
8808 (postfix (js2-node-p parser))
8809 (expr (if postfix
8810 parser
8811 (apply parser args)))
8812 end
8813 pn)
8814 (if postfix ; e.g. i++
8815 (setq pos (js2-node-pos expr)
8816 end js2-token-end)
8817 (setq end (js2-node-end expr)))
8818 (setq pn (make-js2-unary-node :type type
8819 :pos pos
8820 :len (- end pos)
8821 :operand expr))
8822 (js2-node-add-children pn expr)
8823 pn))
8824
8825 (defconst js2-incrementable-node-types
8826 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8827 "Node types that can be the operand of a ++ or -- operator.")
8828
8829 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8830 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8831 js2-incrementable-node-types)
8832 (js2-report-error (if (= tt js2-INC)
8833 "msg.bad.incr"
8834 "msg.bad.decr")
8835 nil beg (- end beg))))
8836
8837 (defun js2-parse-unary-expr ()
8838 (let ((tt (js2-peek-token))
8839 pn expr beg end)
8840 (cond
8841 ((or (= tt js2-VOID)
8842 (= tt js2-NOT)
8843 (= tt js2-BITNOT)
8844 (= tt js2-TYPEOF))
8845 (js2-consume-token)
8846 (js2-make-unary tt 'js2-parse-unary-expr))
8847 ((= tt js2-ADD)
8848 (js2-consume-token)
8849 ;; Convert to special POS token in decompiler and parse tree
8850 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8851 ((= tt js2-SUB)
8852 (js2-consume-token)
8853 ;; Convert to special NEG token in decompiler and parse tree
8854 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8855 ((or (= tt js2-INC)
8856 (= tt js2-DEC))
8857 (js2-consume-token)
8858 (prog1
8859 (setq beg js2-token-beg
8860 end js2-token-end
8861 expr (js2-make-unary tt 'js2-parse-member-expr t))
8862 (js2-check-bad-inc-dec tt beg end expr)))
8863 ((= tt js2-DELPROP)
8864 (js2-consume-token)
8865 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8866 ((= tt js2-ERROR)
8867 (js2-consume-token)
8868 (make-js2-error-node)) ; try to continue
8869 ((and (= tt js2-LT)
8870 js2-compiler-xml-available)
8871 ;; XML stream encountered in expression.
8872 (js2-consume-token)
8873 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8874 (t
8875 (setq pn (js2-parse-member-expr t)
8876 ;; Don't look across a newline boundary for a postfix incop.
8877 tt (js2-peek-token-or-eol))
8878 (when (or (= tt js2-INC) (= tt js2-DEC))
8879 (js2-consume-token)
8880 (setf expr pn
8881 pn (js2-make-unary tt expr))
8882 (js2-node-set-prop pn 'postfix t)
8883 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8884 pn))))
8885
8886 (defun js2-parse-xml-initializer ()
8887 "Parse an E4X XML initializer.
8888 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8889 Then I'll postprocess the result, depending on whether we're in IDE
8890 mode or codegen mode, and generate the appropriate rewritten AST.
8891 IDE mode uses a rich AST that models the XML structure. Codegen mode
8892 just concatenates everything and makes a new XML or XMLList out of it."
8893 (let ((tt (js2-get-first-xml-token))
8894 pn-xml
8895 pn
8896 expr
8897 kids
8898 expr-pos
8899 (continue t)
8900 (first-token t))
8901 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8902 (js2-report-error "msg.syntax"))
8903 (setq pn-xml (make-js2-xml-node))
8904 (while continue
8905 (if first-token
8906 (setq first-token nil)
8907 (setq tt (js2-get-next-xml-token)))
8908 (cond
8909 ;; js2-XML means we found a {expr} in the XML stream.
8910 ;; The js2-ts-string is the XML up to the left-curly.
8911 ((= tt js2-XML)
8912 (push (make-js2-string-node :pos js2-token-beg
8913 :len (- js2-ts-cursor js2-token-beg))
8914 kids)
8915 (js2-must-match js2-LC "msg.syntax")
8916 (setq expr-pos js2-ts-cursor
8917 expr (if (eq (js2-peek-token) js2-RC)
8918 (make-js2-empty-expr-node :pos expr-pos)
8919 (js2-parse-expr)))
8920 (js2-must-match js2-RC "msg.syntax")
8921 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8922 :len (js2-node-len expr)
8923 :expr expr))
8924 (js2-node-add-children pn expr)
8925 (push pn kids))
8926 ;; a js2-XMLEND token means we hit the final close-tag.
8927 ((= tt js2-XMLEND)
8928 (push (make-js2-string-node :pos js2-token-beg
8929 :len (- js2-ts-cursor js2-token-beg))
8930 kids)
8931 (dolist (kid (nreverse kids))
8932 (js2-block-node-push pn-xml kid))
8933 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8934 (js2-node-pos pn-xml))
8935 continue nil))
8936 (t
8937 (js2-report-error "msg.syntax")
8938 (setq continue nil))))
8939 pn-xml))
8940
8941
8942 (defun js2-parse-argument-list ()
8943 "Parse an argument list and return it as a lisp list of nodes.
8944 Returns the list in reverse order. Consumes the right-paren token."
8945 (let (result)
8946 (unless (js2-match-token js2-RP)
8947 (loop do
8948 (if (= (js2-peek-token) js2-YIELD)
8949 (js2-report-error "msg.yield.parenthesized"))
8950 (push (js2-parse-assign-expr) result)
8951 while
8952 (js2-match-token js2-COMMA))
8953 (js2-must-match js2-RP "msg.no.paren.arg")
8954 result)))
8955
8956 (defun js2-parse-member-expr (&optional allow-call-syntax)
8957 (let ((tt (js2-peek-token))
8958 pn
8959 pos
8960 target
8961 args
8962 beg
8963 end
8964 init
8965 tail)
8966 (if (/= tt js2-NEW)
8967 (setq pn (js2-parse-primary-expr))
8968 ;; parse a 'new' expression
8969 (js2-consume-token)
8970 (setq pos js2-token-beg
8971 beg pos
8972 target (js2-parse-member-expr)
8973 end (js2-node-end target)
8974 pn (make-js2-new-node :pos pos
8975 :target target
8976 :len (- end pos)))
8977 (js2-node-add-children pn target)
8978 (when (js2-match-token js2-LP)
8979 ;; Add the arguments to pn, if any are supplied.
8980 (setf beg pos ; start of "new" keyword
8981 pos js2-token-beg
8982 args (nreverse (js2-parse-argument-list))
8983 (js2-new-node-args pn) args
8984 end js2-token-end
8985 (js2-new-node-lp pn) (- pos beg)
8986 (js2-new-node-rp pn) (- end 1 beg))
8987 (apply #'js2-node-add-children pn args))
8988 (when (and js2-allow-rhino-new-expr-initializer
8989 (js2-match-token js2-LC))
8990 (setf init (js2-parse-object-literal)
8991 end (js2-node-end init)
8992 (js2-new-node-initializer pn) init)
8993 (js2-node-add-children pn init))
8994 (setf (js2-node-len pn) (- end beg))) ; end outer if
8995 (js2-parse-member-expr-tail allow-call-syntax pn)))
8996
8997 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8998 "Parse a chain of property/array accesses or function calls.
8999 Includes parsing for E4X operators like `..' and `.@'.
9000 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9001 Returns an expression tree that includes PN, the parent node."
9002 (let ((beg (js2-node-pos pn))
9003 tt
9004 (continue t))
9005 (while continue
9006 (setq tt (js2-peek-token))
9007 (cond
9008 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9009 (setq pn (js2-parse-property-access tt pn)))
9010 ((= tt js2-DOTQUERY)
9011 (setq pn (js2-parse-dot-query pn)))
9012 ((= tt js2-LB)
9013 (setq pn (js2-parse-element-get pn)))
9014 ((= tt js2-LP)
9015 (if allow-call-syntax
9016 (setq pn (js2-parse-function-call pn))
9017 (setq continue nil)))
9018 (t
9019 (setq continue nil))))
9020 (if (>= js2-highlight-level 2)
9021 (js2-parse-highlight-member-expr-node pn))
9022 pn))
9023
9024 (defun js2-parse-dot-query (pn)
9025 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9026 Last token parsed must be `js2-DOTQUERY'."
9027 (let ((pos (js2-node-pos pn))
9028 op-pos
9029 expr
9030 end)
9031 (js2-consume-token)
9032 (js2-must-have-xml)
9033 (js2-set-requires-activation)
9034 (setq op-pos js2-token-beg
9035 expr (js2-parse-expr)
9036 end (js2-node-end expr)
9037 pn (make-js2-xml-dot-query-node :left pn
9038 :pos pos
9039 :op-pos op-pos
9040 :right expr))
9041 (js2-node-add-children pn
9042 (js2-xml-dot-query-node-left pn)
9043 (js2-xml-dot-query-node-right pn))
9044 (if (js2-must-match js2-RP "msg.no.paren")
9045 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9046 end js2-token-end))
9047 (setf (js2-node-len pn) (- end pos))
9048 pn))
9049
9050 (defun js2-parse-element-get (pn)
9051 "Parse an element-get expression, e.g. foo[bar].
9052 Last token parsed must be `js2-RB'."
9053 (let ((lb js2-token-beg)
9054 (pos (js2-node-pos pn))
9055 rb
9056 expr)
9057 (js2-consume-token)
9058 (setq expr (js2-parse-expr))
9059 (if (js2-must-match js2-RB "msg.no.bracket.index")
9060 (setq rb js2-token-beg))
9061 (setq pn (make-js2-elem-get-node :target pn
9062 :pos pos
9063 :element expr
9064 :lb (js2-relpos lb pos)
9065 :rb (js2-relpos rb pos)
9066 :len (- js2-token-end pos)))
9067 (js2-node-add-children pn
9068 (js2-elem-get-node-target pn)
9069 (js2-elem-get-node-element pn))
9070 pn))
9071
9072 (defun js2-parse-function-call (pn)
9073 (let (args
9074 (pos (js2-node-pos pn)))
9075 (js2-consume-token)
9076 (setq pn (make-js2-call-node :pos pos
9077 :target pn
9078 :lp (- js2-token-beg pos)))
9079 (js2-node-add-children pn (js2-call-node-target pn))
9080 ;; Add the arguments to pn, if any are supplied.
9081 (setf args (nreverse (js2-parse-argument-list))
9082 (js2-call-node-rp pn) (- js2-token-beg pos)
9083 (js2-call-node-args pn) args)
9084 (apply #'js2-node-add-children pn args)
9085 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9086 pn))
9087
9088 (defun js2-parse-property-access (tt pn)
9089 "Parse a property access, XML descendants access, or XML attr access."
9090 (let ((member-type-flags 0)
9091 (dot-pos js2-token-beg)
9092 (dot-len (if (= tt js2-DOTDOT) 2 1))
9093 name
9094 ref ; right side of . or .. operator
9095 result)
9096 (js2-consume-token)
9097 (when (= tt js2-DOTDOT)
9098 (js2-must-have-xml)
9099 (setq member-type-flags js2-descendants-flag))
9100 (if (not js2-compiler-xml-available)
9101 (progn
9102 (js2-must-match-prop-name "msg.no.name.after.dot")
9103 (setq name (js2-create-name-node t js2-GETPROP)
9104 result (make-js2-prop-get-node :left pn
9105 :pos js2-token-beg
9106 :right name
9107 :len (- js2-token-end
9108 js2-token-beg)))
9109 (js2-node-add-children result pn name)
9110 result)
9111 ;; otherwise look for XML operators
9112 (setf result (if (= tt js2-DOT)
9113 (make-js2-prop-get-node)
9114 (make-js2-infix-node :type js2-DOTDOT))
9115 (js2-node-pos result) (js2-node-pos pn)
9116 (js2-infix-node-op-pos result) dot-pos
9117 (js2-infix-node-left result) pn ; do this after setting position
9118 tt (js2-next-token))
9119 (cond
9120 ;; needed for generator.throw()
9121 ((= tt js2-THROW)
9122 (js2-save-name-token-data js2-token-beg "throw")
9123 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9124 ;; handles: name, ns::name, ns::*, ns::[expr]
9125 ((js2-valid-prop-name-token tt)
9126 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9127 ;; handles: *, *::name, *::*, *::[expr]
9128 ((= tt js2-MUL)
9129 (js2-save-name-token-data js2-token-beg "*")
9130 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9131 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9132 ((= tt js2-XMLATTR)
9133 (setq result (js2-parse-attribute-access)))
9134 (t
9135 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9136 (if ref
9137 (setf (js2-node-len result) (- (js2-node-end ref)
9138 (js2-node-pos result))
9139 (js2-infix-node-right result) ref))
9140 (if (js2-infix-node-p result)
9141 (js2-node-add-children result
9142 (js2-infix-node-left result)
9143 (js2-infix-node-right result)))
9144 result)))
9145
9146 (defun js2-parse-attribute-access ()
9147 "Parse an E4X XML attribute expression.
9148 This includes expressions of the forms:
9149
9150 @attr @ns::attr @ns::*
9151 @* @*::attr @*::*
9152 @[expr] @*::[expr] @ns::[expr]
9153
9154 Called if we peeked an '@' token."
9155 (let ((tt (js2-next-token))
9156 (at-pos js2-token-beg))
9157 (cond
9158 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9159 ((js2-valid-prop-name-token tt)
9160 (js2-parse-property-name at-pos js2-ts-string 0))
9161 ;; handles: @*, @*::name, @*::*, @*::[expr]
9162 ((= tt js2-MUL)
9163 (js2-save-name-token-data js2-token-beg "*")
9164 (js2-parse-property-name js2-token-beg "*" 0))
9165 ;; handles @[expr]
9166 ((= tt js2-LB)
9167 (js2-parse-xml-elem-ref at-pos))
9168 (t
9169 (js2-report-error "msg.no.name.after.xmlAttr")
9170 ;; Avoid cascaded errors that happen if we make an error node here.
9171 (js2-save-name-token-data js2-token-beg "")
9172 (js2-parse-property-name js2-token-beg "" 0)))))
9173
9174 (defun js2-parse-property-name (at-pos s member-type-flags)
9175 "Check if :: follows name in which case it becomes qualified name.
9176
9177 AT-POS is a natural number if we just read an '@' token, else nil.
9178 S is the name or string that was matched: an identifier, 'throw' or '*'.
9179 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9180
9181 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9182 operator, or the name is followed by ::. For a plain name, returns a
9183 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9184 (let ((pos (or at-pos js2-token-beg))
9185 colon-pos
9186 (name (js2-create-name-node t js2-current-token))
9187 ns
9188 tt
9189 ref
9190 pn)
9191 (catch 'return
9192 (when (js2-match-token js2-COLONCOLON)
9193 (setq ns name
9194 colon-pos js2-token-beg
9195 tt (js2-next-token))
9196 (cond
9197 ;; handles name::name
9198 ((js2-valid-prop-name-token tt)
9199 (setq name (js2-create-name-node)))
9200 ;; handles name::*
9201 ((= tt js2-MUL)
9202 (js2-save-name-token-data js2-token-beg "*")
9203 (setq name (js2-create-name-node)))
9204 ;; handles name::[expr]
9205 ((= tt js2-LB)
9206 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9207 (t
9208 (js2-report-error "msg.no.name.after.coloncolon"))))
9209 (if (and (null ns) (zerop member-type-flags))
9210 name
9211 (prog1
9212 (setq pn
9213 (make-js2-xml-prop-ref-node :pos pos
9214 :len (- (js2-node-end name) pos)
9215 :at-pos at-pos
9216 :colon-pos colon-pos
9217 :propname name))
9218 (js2-node-add-children pn name))))))
9219
9220 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9221 "Parse the [expr] portion of an xml element reference.
9222 For instance, @[expr], @*::[expr], or ns::[expr]."
9223 (let* ((lb js2-token-beg)
9224 (pos (or at-pos lb))
9225 rb
9226 (expr (js2-parse-expr))
9227 (end (js2-node-end expr))
9228 pn)
9229 (if (js2-must-match js2-RB "msg.no.bracket.index")
9230 (setq rb js2-token-beg
9231 end js2-token-end))
9232 (prog1
9233 (setq pn
9234 (make-js2-xml-elem-ref-node :pos pos
9235 :len (- end pos)
9236 :namespace namespace
9237 :colon-pos colon-pos
9238 :at-pos at-pos
9239 :expr expr
9240 :lb (js2-relpos lb pos)
9241 :rb (js2-relpos rb pos)))
9242 (js2-node-add-children pn namespace expr))))
9243
9244 (defsubst js2-parse-primary-expr-lhs ()
9245 (let ((js2-is-in-lhs t))
9246 (js2-parse-primary-expr)))
9247
9248 (defun js2-parse-primary-expr ()
9249 "Parses a literal (leaf) expression of some sort.
9250 Includes complex literals such as functions, object-literals,
9251 array-literals, array comprehensions and regular expressions."
9252 (let ((tt-flagged (js2-next-flagged-token))
9253 pn ; parent node (usually return value)
9254 tt
9255 px-pos ; paren-expr pos
9256 len
9257 flags ; regexp flags
9258 expr)
9259 (setq tt js2-current-token)
9260 (cond
9261 ((= tt js2-FUNCTION)
9262 (js2-parse-function 'FUNCTION_EXPRESSION))
9263 ((= tt js2-LB)
9264 (js2-parse-array-literal))
9265 ((= tt js2-LC)
9266 (js2-parse-object-literal))
9267 ((= tt js2-LET)
9268 (js2-parse-let js2-token-beg))
9269 ((= tt js2-LP)
9270 (setq px-pos js2-token-beg
9271 expr (js2-parse-expr))
9272 (js2-must-match js2-RP "msg.no.paren")
9273 (setq pn (make-js2-paren-node :pos px-pos
9274 :expr expr
9275 :len (- js2-token-end px-pos)))
9276 (js2-node-add-children pn (js2-paren-node-expr pn))
9277 pn)
9278 ((= tt js2-XMLATTR)
9279 (js2-must-have-xml)
9280 (js2-parse-attribute-access))
9281 ((= tt js2-NAME)
9282 (js2-parse-name tt-flagged tt))
9283 ((= tt js2-NUMBER)
9284 (make-js2-number-node))
9285 ((= tt js2-STRING)
9286 (prog1
9287 (make-js2-string-node)
9288 (js2-record-face 'font-lock-string-face)))
9289 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9290 ;; Got / or /= which in this context means a regexp literal
9291 (setq px-pos js2-token-beg)
9292 (js2-read-regexp tt)
9293 (setq flags js2-ts-regexp-flags
9294 js2-ts-regexp-flags nil)
9295 (prog1
9296 (make-js2-regexp-node :pos px-pos
9297 :len (- js2-ts-cursor px-pos)
9298 :value js2-ts-string
9299 :flags flags)
9300 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9301 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9302 ((or (= tt js2-NULL)
9303 (= tt js2-THIS)
9304 (= tt js2-FALSE)
9305 (= tt js2-TRUE))
9306 (make-js2-keyword-node :type tt))
9307 ((= tt js2-RESERVED)
9308 (js2-report-error "msg.reserved.id")
9309 (make-js2-name-node))
9310 ((= tt js2-ERROR)
9311 ;; the scanner or one of its subroutines reported the error.
9312 (make-js2-error-node))
9313 ((= tt js2-EOF)
9314 (setq px-pos (point-at-bol)
9315 len (- js2-ts-cursor px-pos))
9316 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9317 (make-js2-error-node :pos px-pos :len len))
9318 (t
9319 (js2-report-error "msg.syntax")
9320 (make-js2-error-node)))))
9321
9322 (defun js2-parse-name (tt-flagged tt)
9323 (let ((name js2-ts-string)
9324 (name-pos js2-token-beg)
9325 node)
9326 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9327 (= (js2-peek-token) js2-COLON))
9328 (prog1
9329 ;; Do not consume colon, it is used as unwind indicator
9330 ;; to return to statementHelper.
9331 (make-js2-label-node :pos name-pos
9332 :len (- js2-token-end name-pos)
9333 :name name)
9334 (js2-set-face name-pos
9335 js2-token-end
9336 'font-lock-variable-name-face 'record))
9337 ;; Otherwise not a label, just a name. Unfortunately peeking
9338 ;; the next token to check for a colon has biffed js2-token-beg
9339 ;; and js2-token-end. We store the name's bounds in buffer vars
9340 ;; and `js2-create-name-node' uses them.
9341 (js2-save-name-token-data name-pos name)
9342 (setq node (if js2-compiler-xml-available
9343 (js2-parse-property-name nil name 0)
9344 (js2-create-name-node 'check-activation)))
9345 (if js2-highlight-external-variables
9346 (js2-record-name-node node))
9347 node)))
9348
9349 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9350 (js2-add-strict-warning
9351 msg nil
9352 ;; back up from comma to beginning of line or array/objlit
9353 (max (if elems
9354 (js2-node-pos (car elems))
9355 pos)
9356 (save-excursion
9357 (goto-char comma-pos)
9358 (back-to-indentation)
9359 (point)))
9360 comma-pos))
9361
9362 (defun js2-parse-array-literal ()
9363 (let ((pos js2-token-beg)
9364 (end js2-token-end)
9365 (after-lb-or-comma t)
9366 after-comma
9367 tt
9368 elems
9369 pn
9370 (continue t))
9371 (unless js2-is-in-lhs
9372 (js2-push-scope (make-js2-scope))) ; for array comp
9373 (while continue
9374 (setq tt (js2-peek-token))
9375 (cond
9376 ;; comma
9377 ((= tt js2-COMMA)
9378 (js2-consume-token)
9379 (setq after-comma js2-token-end)
9380 (if (not after-lb-or-comma)
9381 (setq after-lb-or-comma t)
9382 (push nil elems)))
9383 ;; end of array
9384 ((or (= tt js2-RB)
9385 (= tt js2-EOF)) ; prevent infinite loop
9386 (if (= tt js2-EOF)
9387 (js2-report-error "msg.no.bracket.arg" nil pos)
9388 (js2-consume-token))
9389 (setq continue nil
9390 end js2-token-end
9391 pn (make-js2-array-node :pos pos
9392 :len (- js2-ts-cursor pos)
9393 :elems (nreverse elems)))
9394 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9395 (when after-comma
9396 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9397 pos elems after-comma)))
9398 ;; destructuring binding
9399 (js2-is-in-lhs
9400 (push (if (or (= tt js2-LC)
9401 (= tt js2-LB)
9402 (= tt js2-NAME))
9403 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9404 (js2-parse-primary-expr-lhs)
9405 ;; invalid pattern
9406 (js2-consume-token)
9407 (js2-report-error "msg.bad.var")
9408 (make-js2-error-node))
9409 elems)
9410 (setq after-lb-or-comma nil
9411 after-comma nil))
9412 ;; array comp
9413 ((and (>= js2-language-version 170)
9414 (= tt js2-FOR) ; check for array comprehension
9415 (not after-lb-or-comma) ; "for" can't follow a comma
9416 elems ; must have at least 1 element
9417 (not (cdr elems))) ; but no 2nd element
9418 (setf continue nil
9419 pn (js2-parse-array-comprehension (car elems) pos)))
9420
9421 ;; another element
9422 (t
9423 (unless after-lb-or-comma
9424 (js2-report-error "msg.no.bracket.arg"))
9425 (push (js2-parse-assign-expr) elems)
9426 (setq after-lb-or-comma nil
9427 after-comma nil))))
9428 (unless js2-is-in-lhs
9429 (js2-pop-scope))
9430 pn))
9431
9432 (defun js2-parse-array-comprehension (expr pos)
9433 "Parse a JavaScript 1.7 Array Comprehension.
9434 EXPR is the first expression after the opening left-bracket.
9435 POS is the beginning of the LB token preceding EXPR.
9436 We should have just parsed the 'for' keyword before calling this function."
9437 (let (loops
9438 loop
9439 first
9440 prev
9441 filter
9442 if-pos
9443 result)
9444 (while (= (js2-peek-token) js2-FOR)
9445 (let ((prev (car loops))) ; rearrange scope chain
9446 (push (setq loop (js2-parse-array-comp-loop)) loops)
9447 (if prev ; each loop is parent scope to the next one
9448 (setf (js2-scope-parent-scope loop) prev)
9449 ; first loop takes expr scope's parent
9450 (setf (js2-scope-parent-scope (setq first loop))
9451 (js2-scope-parent-scope js2-current-scope)))))
9452 ;; set expr scope's parent to the last loop
9453 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9454 (when (= (js2-peek-token) js2-IF)
9455 (js2-consume-token)
9456 (setq if-pos (- js2-token-beg pos) ; relative
9457 filter (js2-parse-condition)))
9458 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9459 (setq result (make-js2-array-comp-node :pos pos
9460 :len (- js2-ts-cursor pos)
9461 :result expr
9462 :loops (nreverse loops)
9463 :filter (car filter)
9464 :lp (js2-relpos (second filter) pos)
9465 :rp (js2-relpos (third filter) pos)
9466 :if-pos if-pos))
9467 (apply #'js2-node-add-children result expr (car filter)
9468 (js2-array-comp-node-loops result))
9469 (setq js2-current-scope first) ; pop to the first loop
9470 result))
9471
9472 (defun js2-parse-array-comp-loop ()
9473 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9474 Last token peeked should be the initial FOR."
9475 (let ((pos js2-token-beg)
9476 (pn (make-js2-array-comp-loop-node))
9477 tt
9478 iter
9479 obj
9480 foreach-p
9481 in-pos
9482 each-pos
9483 lp
9484 rp)
9485 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9486 (js2-push-scope pn)
9487 (unwind-protect
9488 (progn
9489 (when (js2-match-token js2-NAME)
9490 (if (string= js2-ts-string "each")
9491 (progn
9492 (setq foreach-p t
9493 each-pos (- js2-token-beg pos)) ; relative
9494 (js2-record-face 'font-lock-keyword-face))
9495 (js2-report-error "msg.no.paren.for")))
9496 (if (js2-must-match js2-LP "msg.no.paren.for")
9497 (setq lp (- js2-token-beg pos)))
9498 (setq tt (js2-peek-token))
9499 (cond
9500 ((or (= tt js2-LB)
9501 (= tt js2-LC))
9502 ;; handle destructuring assignment
9503 (setq iter (js2-parse-primary-expr-lhs))
9504 (js2-define-destruct-symbols iter js2-LET
9505 'font-lock-variable-name-face t))
9506 ((js2-valid-prop-name-token tt)
9507 (js2-consume-token)
9508 (setq iter (js2-create-name-node)))
9509 (t
9510 (js2-report-error "msg.bad.var")))
9511 ;; Define as a let since we want the scope of the variable to
9512 ;; be restricted to the array comprehension
9513 (if (js2-name-node-p iter)
9514 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9515 (if (js2-must-match js2-IN "msg.in.after.for.name")
9516 (setq in-pos (- js2-token-beg pos)))
9517 (setq obj (js2-parse-expr))
9518 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9519 (setq rp (- js2-token-beg pos)))
9520 (setf (js2-node-pos pn) pos
9521 (js2-node-len pn) (- js2-ts-cursor pos)
9522 (js2-array-comp-loop-node-iterator pn) iter
9523 (js2-array-comp-loop-node-object pn) obj
9524 (js2-array-comp-loop-node-in-pos pn) in-pos
9525 (js2-array-comp-loop-node-each-pos pn) each-pos
9526 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9527 (js2-array-comp-loop-node-lp pn) lp
9528 (js2-array-comp-loop-node-rp pn) rp)
9529 (js2-node-add-children pn iter obj))
9530 (js2-pop-scope))
9531 pn))
9532
9533 (defun js2-parse-object-literal ()
9534 (let ((pos js2-token-beg)
9535 tt
9536 elems
9537 result
9538 after-comma
9539 (continue t))
9540 (while continue
9541 (setq tt (js2-peek-token))
9542 (cond
9543 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9544 ((or (js2-valid-prop-name-token tt)
9545 (= tt js2-STRING))
9546 (setq after-comma nil
9547 result (js2-parse-named-prop tt))
9548 (if (and (null result)
9549 (not js2-recover-from-parse-errors))
9550 (setq continue nil)
9551 (push result elems)))
9552 ;; {12: x} or {10.7: x}
9553 ((= tt js2-NUMBER)
9554 (js2-consume-token)
9555 (setq after-comma nil)
9556 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9557 ;; trailing comma
9558 ((= tt js2-RC)
9559 (setq continue nil)
9560 (if after-comma
9561 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9562 pos elems after-comma)))
9563 (t
9564 (js2-report-error "msg.bad.prop")
9565 (unless js2-recover-from-parse-errors
9566 (setq continue nil)))) ; end switch
9567 (if (js2-match-token js2-COMMA)
9568 (setq after-comma js2-token-end)
9569 (setq continue nil))) ; end loop
9570 (js2-must-match js2-RC "msg.no.brace.prop")
9571 (setq result (make-js2-object-node :pos pos
9572 :len (- js2-ts-cursor pos)
9573 :elems (nreverse elems)))
9574 (apply #'js2-node-add-children result (js2-object-node-elems result))
9575 result))
9576
9577 (defun js2-parse-named-prop (tt)
9578 "Parse a name, string, or getter/setter object property.
9579 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9580 (js2-consume-token)
9581 (let ((string-prop (and (= tt js2-STRING)
9582 (make-js2-string-node)))
9583 expr
9584 (ppos js2-token-beg)
9585 (pend js2-token-end)
9586 (name (js2-create-name-node))
9587 (prop js2-ts-string))
9588 (cond
9589 ;; getter/setter prop
9590 ((and (= tt js2-NAME)
9591 (= (js2-peek-token) js2-NAME)
9592 (or (string= prop "get")
9593 (string= prop "set")))
9594 (js2-consume-token)
9595 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9596 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9597 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9598 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9599 ;; abbreviated destructuring bind e.g., {a, b} = c;
9600 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9601 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9602 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9603 ;; assignment but it's difficult because it requires looking ahead of expression.
9604 ((and js2-is-in-lhs
9605 (= tt js2-NAME)
9606 (let ((ctk (js2-peek-token)))
9607 (or (= ctk js2-COMMA)
9608 (= ctk js2-RC)
9609 (js2-valid-prop-name-token ctk))))
9610 name)
9611 ;; regular prop
9612 (t
9613 (prog1
9614 (setq expr (js2-parse-plain-property (or string-prop name)))
9615 (js2-set-face ppos pend
9616 (if (js2-function-node-p
9617 (js2-object-prop-node-right expr))
9618 'font-lock-function-name-face
9619 'font-lock-variable-name-face)
9620 'record))))))
9621
9622 (defun js2-parse-plain-property (prop)
9623 "Parse a non-getter/setter property in an object literal.
9624 PROP is the node representing the property: a number, name or string."
9625 (js2-must-match js2-COLON "msg.no.colon.prop")
9626 (let* ((pos (js2-node-pos prop))
9627 (colon (- js2-token-beg pos))
9628 (expr (js2-parse-assign-expr))
9629 (result (make-js2-object-prop-node
9630 :pos pos
9631 ;; don't include last consumed token in length
9632 :len (- (+ (js2-node-pos expr)
9633 (js2-node-len expr))
9634 pos)
9635 :left prop
9636 :right expr
9637 :op-pos colon)))
9638 (js2-node-add-children result prop expr)
9639 result))
9640
9641 (defun js2-parse-getter-setter-prop (pos prop get-p)
9642 "Parse getter or setter property in an object literal.
9643 JavaScript syntax is:
9644
9645 { get foo() {...}, set foo(x) {...} }
9646
9647 and expression closure style is also supported
9648
9649 { get foo() x, set foo(x) _x = x }
9650
9651 POS is the start position of the `get' or `set' keyword.
9652 PROP is the `js2-name-node' representing the property name.
9653 GET-P is non-nil if the keyword was `get'."
9654 (let ((type (if get-p js2-GET js2-SET))
9655 result
9656 end
9657 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9658 ;; it has to be an anonymous function, as we already parsed the name
9659 (if (/= (js2-node-type fn) js2-FUNCTION)
9660 (js2-report-error "msg.bad.prop")
9661 (if (plusp (length (js2-function-name fn)))
9662 (js2-report-error "msg.bad.prop")))
9663 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9664 (setq end (js2-node-end fn)
9665 result (make-js2-getter-setter-node :type type
9666 :pos pos
9667 :len (- end pos)
9668 :left prop
9669 :right fn))
9670 (js2-node-add-children result prop fn)
9671 result))
9672
9673 (defun js2-create-name-node (&optional check-activation-p token)
9674 "Create a name node using the token info from last scanned name.
9675 In some cases we need to either synthesize a name node, or we lost
9676 the name token information by peeking. If the TOKEN parameter is
9677 not `js2-NAME', then we use the token info saved in instance vars."
9678 (let ((beg js2-token-beg)
9679 (s js2-ts-string)
9680 name)
9681 (when (/= js2-current-token js2-NAME)
9682 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9683 s js2-prev-name-token-string
9684 js2-prev-name-token-start nil
9685 js2-prev-name-token-string nil))
9686 (setq name (make-js2-name-node :pos beg
9687 :name s
9688 :len (length s)))
9689 (if check-activation-p
9690 (js2-check-activation-name s (or token js2-NAME)))
9691 name))
9692
9693 ;;; Indentation support
9694
9695 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9696 ;; Karl cleverly deduces that the desired indentation level is often a
9697 ;; function of paren/bracket/brace nesting depth, which can be determined
9698 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9699 ;; then does some equally clever checks to see if we're in the context of a
9700 ;; substatement of a possibly braceless statement keyword such as if, while,
9701 ;; or finally. This approach yields pretty good results.
9702
9703 ;; The indenter is often "wrong", however, and needs to be overridden.
9704 ;; The right long-term solution is probably to emulate (or integrate
9705 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9706 ;; parse tree from `js2-parse' is present, which is not true at the
9707 ;; moment the user is typing, computing indentation is still thousands
9708 ;; of lines of code to handle every possible syntactic edge case.
9709
9710 ;; In the meantime, the compromise solution is that we offer a "bounce
9711 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9712 ;; current line indent among various likely guess points. This approach
9713 ;; is far from perfect, but should at least make it slightly easier to
9714 ;; move the line towards its desired indentation when manually
9715 ;; overriding Karl's heuristic nesting guesser.
9716
9717 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9718 ;; extensions such as `let' and Array comprehensions. Major kudos to
9719 ;; Karl for coming up with the initial approach, which packs a lot of
9720 ;; punch for so little code.
9721
9722 (defconst js-possibly-braceless-keyword-re
9723 (regexp-opt
9724 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9725 'words)
9726 "Regular expression matching keywords that are optionally
9727 followed by an opening brace.")
9728
9729 (defconst js-possibly-braceless-keywords-re
9730 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9731 "Regular expression which matches the keywords which are consist of more than 2 words
9732 like 'if else' and 'for each', and optionally followed by an opening brace.")
9733
9734 (defconst js-indent-operator-re
9735 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9736 (regexp-opt '("in" "instanceof") 'words))
9737 "Regular expression matching operators that affect indentation
9738 of continued expressions.")
9739
9740 ;; This function has horrible results if you're typing an array
9741 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9742 ;; in conjunction with electric-indent, so just disabling it.
9743 (defsubst js2-code-at-bol-p ()
9744 "Return t if the first character on line is non-whitespace."
9745 nil)
9746
9747 (defun js2-insert-and-indent (key)
9748 "Run command bound to key and indent current line. Runs the command
9749 bound to KEY in the global keymap and indents the current line."
9750 (interactive (list (this-command-keys)))
9751 (let ((cmd (lookup-key (current-global-map) key)))
9752 (if (commandp cmd)
9753 (call-interactively cmd)))
9754 ;; don't do the electric keys inside comments or strings,
9755 ;; and don't do bounce-indent with them.
9756 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9757 (js2-bounce-indent-p (js2-code-at-bol-p)))
9758 (unless (or (nth 3 parse-state)
9759 (nth 4 parse-state))
9760 (indent-according-to-mode))))
9761
9762 (defun js-re-search-forward-inner (regexp &optional bound count)
9763 "Auxiliary function for `js-re-search-forward'."
9764 (let ((parse)
9765 (saved-point (point-min)))
9766 (while (> count 0)
9767 (re-search-forward regexp bound)
9768 (setq parse (parse-partial-sexp saved-point (point)))
9769 (cond ((nth 3 parse)
9770 (re-search-forward
9771 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9772 (save-excursion (end-of-line) (point)) t))
9773 ((nth 7 parse)
9774 (forward-line))
9775 ((or (nth 4 parse)
9776 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9777 (re-search-forward "\\*/"))
9778 (t
9779 (setq count (1- count))))
9780 (setq saved-point (point))))
9781 (point))
9782
9783 (defun js-re-search-forward (regexp &optional bound noerror count)
9784 "Search forward but ignore strings and comments. Invokes
9785 `re-search-forward' but treats the buffer as if strings and
9786 comments have been removed."
9787 (let ((saved-point (point))
9788 (search-expr
9789 (cond ((null count)
9790 '(js-re-search-forward-inner regexp bound 1))
9791 ((< count 0)
9792 '(js-re-search-backward-inner regexp bound (- count)))
9793 ((> count 0)
9794 '(js-re-search-forward-inner regexp bound count)))))
9795 (condition-case err
9796 (eval search-expr)
9797 (search-failed
9798 (goto-char saved-point)
9799 (unless noerror
9800 (error (error-message-string err)))))))
9801
9802 (defun js-re-search-backward-inner (regexp &optional bound count)
9803 "Auxiliary function for `js-re-search-backward'."
9804 (let ((parse)
9805 (saved-point (point-min)))
9806 (while (> count 0)
9807 (re-search-backward regexp bound)
9808 (setq parse (parse-partial-sexp saved-point (point)))
9809 (cond ((nth 3 parse)
9810 (re-search-backward
9811 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9812 (save-excursion (beginning-of-line) (point)) t))
9813 ((nth 7 parse)
9814 (goto-char (nth 8 parse)))
9815 ((or (nth 4 parse)
9816 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9817 (re-search-backward "/\\*"))
9818 (t
9819 (setq count (1- count))))))
9820 (point))
9821
9822 (defun js-re-search-backward (regexp &optional bound noerror count)
9823 "Search backward but ignore strings and comments. Invokes
9824 `re-search-backward' but treats the buffer as if strings and
9825 comments have been removed."
9826 (let ((saved-point (point))
9827 (search-expr
9828 (cond ((null count)
9829 '(js-re-search-backward-inner regexp bound 1))
9830 ((< count 0)
9831 '(js-re-search-forward-inner regexp bound (- count)))
9832 ((> count 0)
9833 '(js-re-search-backward-inner regexp bound count)))))
9834 (condition-case err
9835 (eval search-expr)
9836 (search-failed
9837 (goto-char saved-point)
9838 (unless noerror
9839 (error (error-message-string err)))))))
9840
9841 (defun js-looking-at-operator-p ()
9842 "Return non-nil if text after point is an operator (that is not
9843 a comma)."
9844 (save-match-data
9845 (and (looking-at js-indent-operator-re)
9846 (or (not (looking-at ":"))
9847 (save-excursion
9848 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9849 (looking-at "?")))))))
9850
9851 (defun js-continued-expression-p ()
9852 "Returns non-nil if the current line continues an expression."
9853 (save-excursion
9854 (back-to-indentation)
9855 (or (js-looking-at-operator-p)
9856 ;; comment
9857 (and (js-re-search-backward "\n" nil t)
9858 (progn
9859 (skip-chars-backward " \t")
9860 (backward-char)
9861 (and (js-looking-at-operator-p)
9862 (and (progn (backward-char)
9863 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9864
9865 (defun js-end-of-do-while-loop-p ()
9866 "Returns non-nil if word after point is `while' of a do-while
9867 statement, else returns nil. A braceless do-while statement
9868 spanning several lines requires that the start of the loop is
9869 indented to the same column as the current line."
9870 (interactive)
9871 (save-excursion
9872 (save-match-data
9873 (when (looking-at "\\s-*\\<while\\>")
9874 (if (save-excursion
9875 (skip-chars-backward "[ \t\n]*}")
9876 (looking-at "[ \t\n]*}"))
9877 (save-excursion
9878 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9879 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9880 (or (looking-at "\\<do\\>")
9881 (let ((saved-indent (current-indentation)))
9882 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9883 (/= (current-indentation) saved-indent)))
9884 (and (looking-at "[ \t]*\\<do\\>")
9885 (not (js-re-search-forward
9886 "\\<while\\>" (point-at-eol) t))
9887 (= (current-indentation) saved-indent)))))))))
9888
9889 (defun js-get-multiline-declaration-offset ()
9890 "Returns offset (> 0) if the current line is part of
9891 multi-line variable declaration like below example, and
9892 returns 0 otherwise.
9893
9894 var a = 10,
9895 b = 20,
9896 c = 30;
9897
9898 "
9899 (let* ((node (js2-node-at-point))
9900 (pnode (and node (js2-node-parent node)))
9901 (pnode-type (and pnode (js2-node-type pnode))))
9902 (if (and node
9903 (= js2-NAME (js2-node-type node))
9904 (or
9905 (= js2-VAR pnode-type)
9906 (= js2-LET pnode-type)
9907 (= js2-CONST pnode-type)))
9908 (if (= js2-CONST pnode-type)
9909 6
9910 4)
9911 0)))
9912
9913 (defun js-ctrl-statement-indentation ()
9914 "Returns the proper indentation of the current line if it
9915 starts the body of a control statement without braces, else
9916 returns nil."
9917 (let (forward-sexp-function) ; temporarily unbind it
9918 (save-excursion
9919 (back-to-indentation)
9920 (when (save-excursion
9921 (and (not (js2-same-line (point-min)))
9922 (not (looking-at "{"))
9923 (js-re-search-backward "[[:graph:]]" nil t)
9924 (not (looking-at "[{([]"))
9925 (progn
9926 (forward-char)
9927 ;; scan-sexps sometimes throws an error
9928 (ignore-errors (backward-sexp))
9929 (when (looking-at "(") (backward-word 1))
9930 (and (save-excursion
9931 (skip-chars-backward " \t}" (point-at-bol))
9932 (or (bolp)
9933 (and (backward-word 1)
9934 (skip-chars-backward " \t}" (point-at-bol))
9935 (bolp)
9936 (looking-at js-possibly-braceless-keywords-re))))
9937 (looking-at js-possibly-braceless-keyword-re)
9938 (not (js-end-of-do-while-loop-p))))))
9939 (save-excursion
9940 (goto-char (match-beginning 0))
9941 (+ (current-indentation) js2-basic-offset))))))
9942
9943 (defun js2-indent-in-array-comp (parse-status)
9944 "Return non-nil if we think we're in an array comprehension.
9945 In particular, return the buffer position of the first `for' kwd."
9946 (let ((end (point)))
9947 (when (nth 1 parse-status)
9948 (save-excursion
9949 (goto-char (nth 1 parse-status))
9950 (when (looking-at "\\[")
9951 (forward-char 1)
9952 (js2-forward-sws)
9953 (if (looking-at "[[{]")
9954 (let (forward-sexp-function) ; use lisp version
9955 (forward-sexp) ; skip destructuring form
9956 (js2-forward-sws)
9957 (if (and (/= (char-after) ?,) ; regular array
9958 (looking-at "for"))
9959 (match-beginning 0)))
9960 ;; to skip arbitrary expressions we need the parser,
9961 ;; so we'll just guess at it.
9962 (if (re-search-forward "[^,]* \\(for\\) " end t)
9963 (match-beginning 1))))))))
9964
9965 (defun js2-array-comp-indentation (parse-status for-kwd)
9966 (if (js2-same-line for-kwd)
9967 ;; first continuation line
9968 (save-excursion
9969 (goto-char (nth 1 parse-status))
9970 (forward-char 1)
9971 (skip-chars-forward " \t")
9972 (current-column))
9973 (save-excursion
9974 (goto-char for-kwd)
9975 (current-column))))
9976
9977 (defun js-proper-indentation (parse-status)
9978 "Return the proper indentation for the current line."
9979 (save-excursion
9980 (back-to-indentation)
9981 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9982 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9983 (continued-expr-p (js-continued-expression-p))
9984 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9985 (js-get-multiline-declaration-offset))
9986 0))
9987 (bracket (nth 1 parse-status))
9988 beg)
9989 (cond
9990 ;; indent array comprehension continuation lines specially
9991 ((and bracket
9992 (not (js2-same-line bracket))
9993 (setq beg (js2-indent-in-array-comp parse-status))
9994 (>= (point) (save-excursion
9995 (goto-char beg)
9996 (point-at-bol)))) ; at or after first loop?
9997 (js2-array-comp-indentation parse-status beg))
9998
9999 (ctrl-stmt-indent)
10000
10001 (bracket
10002 (goto-char bracket)
10003 (cond
10004 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10005 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10006 (when (save-excursion (skip-chars-backward " \t)")
10007 (looking-at ")"))
10008 (backward-list))
10009 (if (and (nth 1 p)
10010 (not js2-consistent-level-indent-inner-bracket-p))
10011 (progn (goto-char (1+ (nth 1 p)))
10012 (skip-chars-forward " \t"))
10013 (back-to-indentation))
10014 (cond (same-indent-p
10015 (current-column))
10016 (continued-expr-p
10017 (+ (current-column) (* 2 js2-basic-offset)))
10018 ((> multiline-declaration-offset 0)
10019 (+ (current-column) js2-basic-offset multiline-declaration-offset))
10020 (t
10021 (+ (current-column) js2-basic-offset)))))
10022 (t
10023 (unless same-indent-p
10024 (forward-char)
10025 (skip-chars-forward " \t"))
10026 (current-column))))
10027
10028 (continued-expr-p js2-basic-offset)
10029
10030 ((> multiline-declaration-offset 0)
10031 (+ multiline-declaration-offset))
10032
10033 (t 0)))))
10034
10035 (defun js2-lineup-comment (parse-status)
10036 "Indent a multi-line block comment continuation line."
10037 (let* ((beg (nth 8 parse-status))
10038 (first-line (js2-same-line beg))
10039 (offset (save-excursion
10040 (goto-char beg)
10041 (if (looking-at "/\\*")
10042 (+ 1 (current-column))
10043 0))))
10044 (unless first-line
10045 (indent-line-to offset))))
10046
10047 (defun js2-backward-sws ()
10048 "Move backward through whitespace and comments."
10049 (interactive)
10050 (while (forward-comment -1)))
10051
10052 (defun js2-forward-sws ()
10053 "Move forward through whitespace and comments."
10054 (interactive)
10055 (while (forward-comment 1)))
10056
10057 (defsubst js2-current-indent (&optional pos)
10058 "Return column of indentation on current line.
10059 If POS is non-nil, go to that point and return indentation for that line."
10060 (save-excursion
10061 (if pos
10062 (goto-char pos))
10063 (back-to-indentation)
10064 (current-column)))
10065
10066 (defsubst js2-arglist-close ()
10067 "Return non-nil if we're on a line beginning with a close-paren/brace."
10068 (save-match-data
10069 (save-excursion
10070 (goto-char (point-at-bol))
10071 (js2-forward-sws)
10072 (looking-at "[])}]"))))
10073
10074 (defsubst js2-indent-looks-like-label-p ()
10075 (goto-char (point-at-bol))
10076 (js2-forward-sws)
10077 (looking-at (concat js2-mode-identifier-re ":")))
10078
10079 (defun js2-indent-in-objlit-p (parse-status)
10080 "Return non-nil if this looks like an object-literal entry."
10081 (let ((start (nth 1 parse-status)))
10082 (and
10083 start
10084 (save-excursion
10085 (and (zerop (forward-line -1))
10086 (not (< (point) start)) ; crossed a {} boundary
10087 (js2-indent-looks-like-label-p)))
10088 (save-excursion
10089 (js2-indent-looks-like-label-p)))))
10090
10091 ;; if prev line looks like foobar({ then we're passing an object
10092 ;; literal to a function call, and people pretty much always want to
10093 ;; de-dent back to the previous line, so move the 'basic-offset'
10094 ;; position to the front.
10095 (defsubst js2-indent-objlit-arg-p (parse-status)
10096 (save-excursion
10097 (back-to-indentation)
10098 (js2-backward-sws)
10099 (and (eq (1- (point)) (nth 1 parse-status))
10100 (eq (char-before) ?{)
10101 (progn
10102 (forward-char -1)
10103 (skip-chars-backward " \t")
10104 (eq (char-before) ?\()))))
10105
10106 (defsubst js2-indent-case-block-p ()
10107 (save-excursion
10108 (back-to-indentation)
10109 (js2-backward-sws)
10110 (goto-char (point-at-bol))
10111 (skip-chars-forward " \t")
10112 (save-match-data
10113 (looking-at "case\\s-.+:"))))
10114
10115 (defsubst js2-syntax-bol ()
10116 "Return the point at the first non-whitespace char on the line.
10117 Returns `point-at-bol' if the line is empty."
10118 (save-excursion
10119 (beginning-of-line)
10120 (skip-chars-forward " \t")
10121 (point)))
10122
10123 (defun js2-bounce-indent (normal-col parse-status)
10124 "Cycle among alternate computed indentation positions.
10125 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10126 of the buffer to the current point. NORMAL-COL is the indentation
10127 column computed by the heuristic guesser based on current paren,
10128 bracket, brace and statement nesting."
10129 (let ((cur-indent (js2-current-indent))
10130 (old-buffer-undo-list buffer-undo-list)
10131 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10132 (current-line (save-excursion
10133 (forward-line 0) ; move to bol
10134 (1+ (count-lines (point-min) (point)))))
10135 positions
10136 pos
10137 anchor
10138 arglist-cont
10139 same-indent
10140 prev-line-col
10141 basic-offset
10142 computed-pos)
10143 ;; temporarily don't record undo info, if user requested this
10144 (if js2-mode-indent-inhibit-undo
10145 (setq buffer-undo-list t))
10146 (unwind-protect
10147 (progn
10148 ;; first likely point: indent from beginning of previous code line
10149 (push (setq basic-offset
10150 (+ (save-excursion
10151 (back-to-indentation)
10152 (js2-backward-sws)
10153 (back-to-indentation)
10154 (setq prev-line-col (current-column)))
10155 js2-basic-offset))
10156 positions)
10157
10158 ;; (first + epsilon) likely point: indent 2x from beginning of
10159 ;; previous code line. Some companies like this approach. Ahem.
10160 ;; Seriously, though -- 4-space indent for expression continuation
10161 ;; lines isn't a bad idea. We should eventually implement it
10162 ;; that way.
10163 (push (setq basic-offset
10164 (+ (save-excursion
10165 (back-to-indentation)
10166 (js2-backward-sws)
10167 (back-to-indentation)
10168 (setq prev-line-col (current-column)))
10169 (* 2 js2-basic-offset)))
10170 positions)
10171
10172 ;; second likely point: indent from assign-expr RHS. This
10173 ;; is just a crude guess based on finding " = " on the previous
10174 ;; line containing actual code.
10175 (setq pos (save-excursion
10176 (save-match-data
10177 (forward-line -1)
10178 (goto-char (point-at-bol))
10179 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10180 (point-at-eol) t)
10181 (goto-char (match-end 1))
10182 (skip-chars-forward " \t\r\n")
10183 (current-column)))))
10184 (when pos
10185 (incf pos js2-basic-offset)
10186 (unless (member pos positions)
10187 (push pos positions)))
10188
10189 ;; third likely point: same indent as previous line of code.
10190 ;; Make it the first likely point if we're not on an
10191 ;; arglist-close line and previous line ends in a comma, or
10192 ;; both this line and prev line look like object-literal
10193 ;; elements.
10194 (setq pos (save-excursion
10195 (goto-char (point-at-bol))
10196 (js2-backward-sws)
10197 (back-to-indentation)
10198 (prog1
10199 (current-column)
10200 ;; while we're here, look for trailing comma
10201 (if (save-excursion
10202 (goto-char (point-at-eol))
10203 (js2-backward-sws)
10204 (eq (char-before) ?,))
10205 (setq arglist-cont (1- (point)))))))
10206 (when pos
10207 (if (and (or arglist-cont
10208 (js2-indent-in-objlit-p parse-status))
10209 (not (js2-arglist-close)))
10210 (setq same-indent pos))
10211 (unless (member pos positions)
10212 (push pos positions)))
10213
10214 ;; fourth likely point: first preceding code with less indentation
10215 ;; than the immediately preceding code line.
10216 (setq pos (save-excursion
10217 (js2-backward-sws)
10218 (back-to-indentation)
10219 (setq anchor (current-column))
10220 (while (and (zerop (forward-line -1))
10221 (>= (progn
10222 (back-to-indentation)
10223 (current-column))
10224 anchor)))
10225 (setq pos (current-column))))
10226 (unless (member pos positions)
10227 (push pos positions))
10228
10229 ;; put nesting-heuristic position first in list, sort rest
10230 (setq positions (nreverse (sort positions '<)))
10231 (setq positions (cons normal-col (delete normal-col positions)))
10232
10233 ;; comma-list continuation lines: prev line indent takes precedence
10234 (if same-indent
10235 (setq positions
10236 (cons same-indent
10237 (sort (delete same-indent positions) '<))))
10238
10239 ;; common special cases where we want to indent in from previous line
10240 (if (or (js2-indent-case-block-p)
10241 (js2-indent-objlit-arg-p parse-status))
10242 (setq positions
10243 (cons basic-offset
10244 (delete basic-offset positions))))
10245
10246 ;; record whether we're already sitting on one of the alternatives
10247 (setq pos (member cur-indent positions))
10248 (cond
10249 ;; case 0: we're one one of the alternatives and this is the
10250 ;; first time they've pressed TAB on this line (best-guess).
10251 ((and js2-mode-indent-ignore-first-tab
10252 pos
10253 ;; first time pressing TAB on this line?
10254 (not (eq js2-mode-last-indented-line current-line)))
10255 ;; do nothing
10256 (setq computed-pos nil))
10257 ;; case 1: only one computed position => use it
10258 ((null (cdr positions))
10259 (setq computed-pos 0))
10260 ;; case 2: not on any of the computed spots => use main spot
10261 ((not pos)
10262 (setq computed-pos 0))
10263 ;; case 3: on last position: cycle to first position
10264 ((null (cdr pos))
10265 (setq computed-pos 0))
10266 ;; case 4: on intermediate position: cycle to next position
10267 (t
10268 (setq computed-pos (js2-position (second pos) positions))))
10269
10270 ;; see if any hooks want to indent; otherwise we do it
10271 (loop with result = nil
10272 for hook in js2-indent-hook
10273 while (null result)
10274 do
10275 (setq result (funcall hook positions computed-pos))
10276 finally do
10277 (unless (or result (null computed-pos))
10278 (indent-line-to (nth computed-pos positions)))))
10279
10280 ;; finally
10281 (if js2-mode-indent-inhibit-undo
10282 (setq buffer-undo-list old-buffer-undo-list))
10283 ;; see commentary for `js2-mode-last-indented-line'
10284 (setq js2-mode-last-indented-line current-line))))
10285
10286 (defsubst js2-1-line-comment-continuation-p ()
10287 "Return t if we're in a 1-line comment continuation.
10288 If so, we don't ever want to use bounce-indent."
10289 (save-excursion
10290 (save-match-data
10291 (and (progn
10292 (forward-line 0)
10293 (looking-at "\\s-*//"))
10294 (progn
10295 (forward-line -1)
10296 (forward-line 0)
10297 (when (looking-at "\\s-*$")
10298 (js2-backward-sws)
10299 (forward-line 0))
10300 (looking-at "\\s-*//"))))))
10301
10302 (defun js2-indent-line ()
10303 "Indent the current line as JavaScript source text."
10304 (interactive)
10305 (when js2-use-ast-for-indentation-p
10306 (js2-reparse))
10307 (let (parse-status
10308 current-indent
10309 offset
10310 indent-col
10311 moved
10312 ;; don't whine about errors/warnings when we're indenting.
10313 ;; This has to be set before calling parse-partial-sexp below.
10314 (inhibit-point-motion-hooks t))
10315 (setq parse-status (save-excursion
10316 (parse-partial-sexp (point-min)
10317 (point-at-bol)))
10318 offset (- (point) (save-excursion
10319 (back-to-indentation)
10320 (setq current-indent (current-column))
10321 (point))))
10322 (js2-with-underscore-as-word-syntax
10323 (if (nth 4 parse-status)
10324 (js2-lineup-comment parse-status)
10325 (setq indent-col (js-proper-indentation parse-status))
10326 ;; see comments below about js2-mode-last-indented-line
10327 (when
10328 (cond
10329 ;; bounce-indenting is disabled during electric-key indent.
10330 ;; It doesn't work well on first line of buffer.
10331 ((and js2-bounce-indent-p
10332 (not (js2-same-line (point-min)))
10333 (not (js2-1-line-comment-continuation-p)))
10334 (js2-bounce-indent indent-col parse-status)
10335 (setq moved t))
10336 ;; just indent to the guesser's likely spot
10337 ((/= current-indent indent-col)
10338 (indent-line-to indent-col)
10339 (setq moved t)))
10340 (when (and moved (plusp offset))
10341 (forward-char offset)))))))
10342
10343 (defun js2-indent-region (start end)
10344 "Indent the region, but don't use bounce indenting."
10345 (let ((js2-bounce-indent-p nil)
10346 (indent-region-function nil))
10347 (indent-region start end nil))) ; nil for byte-compiler
10348
10349 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10350
10351 ;;;###autoload
10352 (defun js2-mode ()
10353 "Major mode for editing JavaScript code."
10354 (interactive)
10355 (kill-all-local-variables)
10356 (set-syntax-table js2-mode-syntax-table)
10357 (use-local-map js2-mode-map)
10358 (make-local-variable 'comment-start)
10359 (make-local-variable 'comment-end)
10360 (make-local-variable 'comment-start-skip)
10361 (setq major-mode 'js2-mode
10362 mode-name "JavaScript-IDE"
10363 comment-start "//" ; used by comment-region; don't change it
10364 comment-end "")
10365 (setq local-abbrev-table js2-mode-abbrev-table)
10366 (set (make-local-variable 'max-lisp-eval-depth)
10367 (max max-lisp-eval-depth 3000))
10368 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10369 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10370
10371 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10372 ;; on most platforms other than the one I originally wrote it on. So it's
10373 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10374 ;; with our binding of the RET key inside comments: short lines stay short.
10375 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10376
10377 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10378 (set (make-local-variable 'next-error-function) #'js2-next-error)
10379 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10380 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10381 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10382 ;; for characters inside regexp literals.
10383 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10384 ;; this is necessary to make `show-paren-function' work properly
10385 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10386 ;; needed for M-x rgrep, among other things
10387 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10388
10389 ;; some variables needed by cc-engine for paragraph-fill, etc.
10390 (setq c-buffer-is-cc-mode t
10391 c-comment-prefix-regexp js2-comment-prefix-regexp
10392 c-comment-start-regexp "/[*/]\\|\\s|"
10393 c-paragraph-start js2-paragraph-start
10394 c-paragraph-separate "$"
10395 comment-start-skip js2-comment-start-skip
10396 c-syntactic-ws-start js2-syntactic-ws-start
10397 c-syntactic-ws-end js2-syntactic-ws-end
10398 c-syntactic-eol js2-syntactic-eol)
10399
10400 (setq js2-default-externs
10401 (append js2-ecma-262-externs
10402 (if js2-include-browser-externs
10403 js2-browser-externs)
10404 (if js2-include-gears-externs
10405 js2-gears-externs)
10406 (if js2-include-rhino-externs
10407 js2-rhino-externs)))
10408
10409 ;; We do our own syntax highlighting based on the parse tree.
10410 ;; However, we want minor modes that add keywords to highlight properly
10411 ;; (examples: doxymacs, column-marker). We do this by not letting
10412 ;; font-lock unfontify anything, and telling it to fontify after we
10413 ;; re-parse and re-highlight the buffer. (We currently don't do any
10414 ;; work with regions other than the whole buffer.)
10415 (dolist (var '(font-lock-unfontify-buffer-function
10416 font-lock-unfontify-region-function))
10417 (set (make-local-variable var) (lambda (&rest args) t)))
10418
10419 ;; Don't let font-lock do syntactic (string/comment) fontification.
10420 (set (make-local-variable #'font-lock-syntactic-face-function)
10421 (lambda (state) nil))
10422
10423 ;; Experiment: make reparse-delay longer for longer files.
10424 (if (plusp js2-dynamic-idle-timer-adjust)
10425 (setq js2-idle-timer-delay
10426 (* js2-idle-timer-delay
10427 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10428
10429 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10430 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10431 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10432 (imenu-add-to-menubar (concat "IM-" mode-name))
10433 (when js2-mirror-mode
10434 (js2-enter-mirror-mode))
10435 (add-to-invisibility-spec '(js2-outline . t))
10436 (set (make-local-variable 'line-move-ignore-invisible) t)
10437 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10438 (setq js2-mode-functions-hidden nil
10439 js2-mode-comments-hidden nil
10440 js2-mode-buffer-dirty-p t
10441 js2-mode-parsing nil)
10442 (js2-reparse)
10443 (run-hooks 'js2-mode-hook))
10444
10445 (defun js2-mode-exit ()
10446 "Exit `js2-mode' and clean up."
10447 (interactive)
10448 (when js2-mode-node-overlay
10449 (delete-overlay js2-mode-node-overlay)
10450 (setq js2-mode-node-overlay nil))
10451 (js2-remove-overlays)
10452 (setq js2-mode-ast nil)
10453 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10454 (remove-from-invisibility-spec '(js2-outline . t))
10455 (js2-mode-show-all)
10456 (js2-with-unmodifying-text-property-changes
10457 (js2-clear-face (point-min) (point-max))))
10458
10459 (defun js2-before-save ()
10460 "Clean up whitespace before saving file.
10461 You can disable this by customizing `js2-cleanup-whitespace'."
10462 (when js2-cleanup-whitespace
10463 (let ((col (current-column)))
10464 (delete-trailing-whitespace)
10465 ;; don't change trailing whitespace on current line
10466 (unless (eq (current-column) col)
10467 (indent-to col)))))
10468
10469 (defsubst js2-mode-reset-timer ()
10470 "Cancel any existing parse timer and schedule a new one."
10471 (if js2-mode-parse-timer
10472 (cancel-timer js2-mode-parse-timer))
10473 (setq js2-mode-parsing nil)
10474 (setq js2-mode-parse-timer
10475 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10476
10477 (defun js2-mode-edit (beg end len)
10478 "Schedule a new parse after buffer is edited.
10479 Buffer edit spans from BEG to END and is of length LEN.
10480 Also clears the `js2-magic' bit on autoinserted parens/brackets
10481 if the edit occurred on a line different from the magic paren."
10482 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10483 (line (if magic-pos (line-number-at-pos magic-pos))))
10484 (and line
10485 (or (/= (line-number-at-pos beg) line)
10486 (and (> 0 len)
10487 (/= (line-number-at-pos end) line)))
10488 (js2-mode-mundanify-parens)))
10489 (setq js2-mode-buffer-dirty-p t)
10490 (js2-mode-hide-overlay)
10491 (js2-mode-reset-timer))
10492
10493 (defun js2-mode-run-font-lock ()
10494 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10495 This is intended to allow modes that install their own font-lock keywords
10496 to work with js2-mode. In practice it never seems to work for long.
10497 Hopefully the Emacs maintainers can help figure out a way to make it work."
10498 (when (and (boundp 'font-lock-keywords)
10499 font-lock-keywords
10500 (boundp 'font-lock-mode)
10501 font-lock-mode)
10502 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10503 ;; play nicely with js2-mode. They go out of their way to fail to
10504 ;; provide any option for saying "look, fontify the farging buffer
10505 ;; with just the keywords already". Argh.
10506 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10507 (let (font-lock-verbose)
10508 (font-lock-fontify-buffer))))
10509
10510 (defun js2-reparse (&optional force)
10511 "Re-parse current buffer after user finishes some data entry.
10512 If we get any user input while parsing, including cursor motion,
10513 we discard the parse and reschedule it. If FORCE is nil, then the
10514 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10515 (let (time
10516 interrupted-p
10517 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10518 (unless js2-mode-parsing
10519 (setq js2-mode-parsing t)
10520 (unwind-protect
10521 (when (or js2-mode-buffer-dirty-p force)
10522 (js2-remove-overlays)
10523 (js2-with-unmodifying-text-property-changes
10524 (setq js2-mode-buffer-dirty-p nil
10525 js2-mode-fontifications nil
10526 js2-mode-deferred-properties nil
10527 js2-additional-externs nil)
10528 (if js2-mode-verbose-parse-p
10529 (message "parsing..."))
10530 (setq time
10531 (js2-time
10532 (setq interrupted-p
10533 (catch 'interrupted
10534 (setq js2-mode-ast (js2-parse))
10535 ;; if parsing is interrupted, comments and regex
10536 ;; literals stay ignored by `parse-partial-sexp'
10537 (remove-text-properties (point-min) (point-max)
10538 '(syntax-table))
10539 (js2-mode-apply-deferred-properties)
10540 (js2-mode-remove-suppressed-warnings)
10541 (js2-mode-show-warnings)
10542 (js2-mode-show-errors)
10543 (js2-mode-run-font-lock) ; note: doesn't work
10544 (js2-mode-highlight-magic-parens)
10545 (if (>= js2-highlight-level 1)
10546 (js2-highlight-jsdoc js2-mode-ast))
10547 nil))))
10548 (if interrupted-p
10549 (progn
10550 ;; unfinished parse => try again
10551 (setq js2-mode-buffer-dirty-p t)
10552 (js2-mode-reset-timer))
10553 (if js2-mode-verbose-parse-p
10554 (message "Parse time: %s" time)))))
10555 (setq js2-mode-parsing nil)
10556 (unless interrupted-p
10557 (setq js2-mode-parse-timer nil))))))
10558
10559 (defun js2-mode-show-node ()
10560 "Debugging aid: highlight selected AST node on mouse click."
10561 (interactive)
10562 (let ((node (js2-node-at-point))
10563 beg
10564 end)
10565 (when js2-mode-show-overlay
10566 (if (null node)
10567 (message "No node found at location %s" (point))
10568 (setq beg (js2-node-abs-pos node)
10569 end (+ beg (js2-node-len node)))
10570 (if js2-mode-node-overlay
10571 (move-overlay js2-mode-node-overlay beg end)
10572 (setq js2-mode-node-overlay (make-overlay beg end))
10573 (overlay-put js2-mode-node-overlay 'face 'highlight))
10574 (js2-with-unmodifying-text-property-changes
10575 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10576 (message "%s, parent: %s"
10577 (js2-node-short-name node)
10578 (if (js2-node-parent node)
10579 (js2-node-short-name (js2-node-parent node))
10580 "nil"))))))
10581
10582 (defun js2-mode-hide-overlay (&optional p1 p2)
10583 "Remove the debugging overlay when the point moves.
10584 P1 and P2 are the old and new values of point, respectively."
10585 (when js2-mode-node-overlay
10586 (let ((beg (overlay-start js2-mode-node-overlay))
10587 (end (overlay-end js2-mode-node-overlay)))
10588 ;; Sometimes we're called spuriously.
10589 (unless (and p2
10590 (>= p2 beg)
10591 (<= p2 end))
10592 (js2-with-unmodifying-text-property-changes
10593 (remove-text-properties beg end '(point-left nil)))
10594 (delete-overlay js2-mode-node-overlay)
10595 (setq js2-mode-node-overlay nil)))))
10596
10597 (defun js2-mode-reset ()
10598 "Debugging helper: reset everything."
10599 (interactive)
10600 (js2-mode-exit)
10601 (js2-mode))
10602
10603 (defsubst js2-mode-show-warn-or-err (e face)
10604 "Highlight a warning or error E with FACE.
10605 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10606 (let* ((key (first e))
10607 (beg (second e))
10608 (end (+ beg (third e)))
10609 ;; Don't inadvertently go out of bounds.
10610 (beg (max (point-min) (min beg (point-max))))
10611 (end (max (point-min) (min end (point-max))))
10612 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10613 (ovl (make-overlay beg end)))
10614 (overlay-put ovl 'face face)
10615 (overlay-put ovl 'js2-error t)
10616 (put-text-property beg end 'help-echo (js2-get-msg key))
10617 (put-text-property beg end 'point-entered #'js2-echo-error)))
10618
10619 (defun js2-remove-overlays ()
10620 "Remove overlays from buffer that have a `js2-error' property."
10621 (let ((beg (point-min))
10622 (end (point-max)))
10623 (save-excursion
10624 (dolist (o (overlays-in beg end))
10625 (when (overlay-get o 'js2-error)
10626 (delete-overlay o))))))
10627
10628 (defun js2-error-at-point (&optional pos)
10629 "Return non-nil if there's an error overlay at POS.
10630 Defaults to point."
10631 (loop with pos = (or pos (point))
10632 for o in (overlays-at pos)
10633 thereis (overlay-get o 'js2-error)))
10634
10635 (defun js2-mode-apply-deferred-properties ()
10636 "Apply fontifications and other text properties recorded during parsing."
10637 (when (plusp js2-highlight-level)
10638 ;; We defer clearing faces as long as possible to eliminate flashing.
10639 (js2-clear-face (point-min) (point-max))
10640 ;; Have to reverse the recorded fontifications list so that errors
10641 ;; and warnings overwrite the normal fontifications.
10642 (dolist (f (nreverse js2-mode-fontifications))
10643 (put-text-property (first f) (second f) 'face (third f)))
10644 (setq js2-mode-fontifications nil))
10645 (dolist (p js2-mode-deferred-properties)
10646 (apply #'put-text-property p))
10647 (setq js2-mode-deferred-properties nil))
10648
10649 (defun js2-mode-show-errors ()
10650 "Highlight syntax errors."
10651 (when js2-mode-show-parse-errors
10652 (dolist (e (js2-ast-root-errors js2-mode-ast))
10653 (js2-mode-show-warn-or-err e 'js2-error-face))))
10654
10655 (defun js2-mode-remove-suppressed-warnings ()
10656 "Take suppressed warnings out of the AST warnings list.
10657 This ensures that the counts and `next-error' are correct."
10658 (setf (js2-ast-root-warnings js2-mode-ast)
10659 (js2-delete-if
10660 (lambda (e)
10661 (let ((key (caar e)))
10662 (or
10663 (and (not js2-strict-trailing-comma-warning)
10664 (string-match "trailing\\.comma" key))
10665 (and (not js2-strict-cond-assign-warning)
10666 (string= key "msg.equal.as.assign"))
10667 (and js2-missing-semi-one-line-override
10668 (string= key "msg.missing.semi")
10669 (let* ((beg (second e))
10670 (node (js2-node-at-point beg))
10671 (fn (js2-mode-find-parent-fn node))
10672 (body (and fn (js2-function-node-body fn)))
10673 (lc (and body (js2-node-abs-pos body)))
10674 (rc (and lc (+ lc (js2-node-len body)))))
10675 (and fn
10676 (or (null body)
10677 (save-excursion
10678 (goto-char beg)
10679 (and (js2-same-line lc)
10680 (js2-same-line rc))))))))))
10681 (js2-ast-root-warnings js2-mode-ast))))
10682
10683 (defun js2-mode-show-warnings ()
10684 "Highlight strict-mode warnings."
10685 (when js2-mode-show-strict-warnings
10686 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10687 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10688
10689 (defun js2-echo-error (old-point new-point)
10690 "Called by point-motion hooks."
10691 (let ((msg (get-text-property new-point 'help-echo)))
10692 (if msg
10693 (message msg))))
10694
10695 (defalias #'js2-echo-help #'js2-echo-error)
10696
10697 (defun js2-enter-key ()
10698 "Handle user pressing the Enter key."
10699 (interactive)
10700 (let ((parse-status (save-excursion
10701 (parse-partial-sexp (point-min) (point)))))
10702 (cond
10703 ;; check if we're inside a string
10704 ((nth 3 parse-status)
10705 (js2-mode-split-string parse-status))
10706 ;; check if inside a block comment
10707 ((nth 4 parse-status)
10708 (js2-mode-extend-comment))
10709 (t
10710 ;; should probably figure out what the mode-map says we should do
10711 (if js2-indent-on-enter-key
10712 (let ((js2-bounce-indent-p nil))
10713 (js2-indent-line)))
10714 (insert "\n")
10715 (if js2-enter-indents-newline
10716 (let ((js2-bounce-indent-p nil))
10717 (js2-indent-line)))))))
10718
10719 (defun js2-mode-split-string (parse-status)
10720 "Turn a newline in mid-string into a string concatenation.
10721 PARSE-STATUS is as documented in `parse-partial-sexp'."
10722 (let* ((col (current-column))
10723 (quote-char (nth 3 parse-status))
10724 (quote-string (string quote-char))
10725 (string-beg (nth 8 parse-status))
10726 (indent (save-match-data
10727 (or
10728 (save-excursion
10729 (back-to-indentation)
10730 (if (looking-at "\\+")
10731 (current-column)))
10732 (save-excursion
10733 (goto-char string-beg)
10734 (if (looking-back "\\+\\s-+")
10735 (goto-char (match-beginning 0)))
10736 (current-column))))))
10737 (insert quote-char "\n")
10738 (indent-to indent)
10739 (insert "+ " quote-string)
10740 (when (eolp)
10741 (insert quote-string)
10742 (backward-char 1))))
10743
10744 (defun js2-mode-extend-comment ()
10745 "When inside a comment block, add comment prefix."
10746 (let (star single col first-line needs-close)
10747 (save-excursion
10748 (back-to-indentation)
10749 (cond
10750 ((looking-at "\\*[^/]")
10751 (setq star t
10752 col (current-column)))
10753 ((looking-at "/\\*")
10754 (setq star t
10755 first-line t
10756 col (1+ (current-column))))
10757 ((looking-at "//")
10758 (setq single t
10759 col (current-column)))))
10760 ;; Heuristic for whether we need to close the comment:
10761 ;; if we've got a parse error here, assume it's an unterminated
10762 ;; comment.
10763 (setq needs-close
10764 (or
10765 (eq (get-text-property (1- (point)) 'point-entered)
10766 'js2-echo-error)
10767 ;; The heuristic above doesn't work well when we're
10768 ;; creating a comment and there's another one downstream,
10769 ;; as our parser thinks this one ends at the end of the
10770 ;; next one. (You can have a /* inside a js block comment.)
10771 ;; So just close it if the next non-ws char isn't a *.
10772 (and first-line
10773 (eolp)
10774 (save-excursion
10775 (skip-chars-forward " \t\r\n")
10776 (not (eq (char-after) ?*))))))
10777 (insert "\n")
10778 (cond
10779 (star
10780 (indent-to col)
10781 (insert "* ")
10782 (if (and first-line needs-close)
10783 (save-excursion
10784 (insert "\n")
10785 (indent-to col)
10786 (insert "*/"))))
10787 (single
10788 (when (save-excursion
10789 (and (zerop (forward-line 1))
10790 (looking-at "\\s-*//")))
10791 (indent-to col)
10792 (insert "// "))))))
10793
10794 (defun js2-beginning-of-line ()
10795 "Toggles point between bol and first non-whitespace char in line.
10796 Also moves past comment delimiters when inside comments."
10797 (interactive)
10798 (let (node beg)
10799 (cond
10800 ((bolp)
10801 (back-to-indentation))
10802 ((looking-at "//")
10803 (skip-chars-forward "/ \t"))
10804 ((and (eq (char-after) ?*)
10805 (setq node (js2-comment-at-point))
10806 (memq (js2-comment-node-format node) '(jsdoc block))
10807 (save-excursion
10808 (skip-chars-backward " \t")
10809 (bolp)))
10810 (skip-chars-forward "\* \t"))
10811 (t
10812 (goto-char (point-at-bol))))))
10813
10814 (defun js2-end-of-line ()
10815 "Toggles point between eol and last non-whitespace char in line."
10816 (interactive)
10817 (if (eolp)
10818 (skip-chars-backward " \t")
10819 (goto-char (point-at-eol))))
10820
10821 (defun js2-enter-mirror-mode()
10822 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10823 on insertion."
10824 (interactive)
10825 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10826 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10827 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10828 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10829 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10830 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10831 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10832 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10833
10834 (defun js2-leave-mirror-mode()
10835 "Turns off mirror mode."
10836 (interactive)
10837 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10838 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10839
10840 (defsubst js2-mode-inside-string ()
10841 "Return non-nil if inside a string.
10842 Actually returns the quote character that begins the string."
10843 (let ((parse-state (save-excursion
10844 (parse-partial-sexp (point-min) (point)))))
10845 (nth 3 parse-state)))
10846
10847 (defsubst js2-mode-inside-comment-or-string ()
10848 "Return non-nil if inside a comment or string."
10849 (or
10850 (let ((comment-start
10851 (save-excursion
10852 (goto-char (point-at-bol))
10853 (if (re-search-forward "//" (point-at-eol) t)
10854 (match-beginning 0)))))
10855 (and comment-start
10856 (<= comment-start (point))))
10857 (let ((parse-state (save-excursion
10858 (parse-partial-sexp (point-min) (point)))))
10859 (or (nth 3 parse-state)
10860 (nth 4 parse-state)))))
10861
10862 (defsubst js2-make-magic-delimiter (delim &optional pos)
10863 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10864 Sets value of `js2-magic' text property to line number at POS."
10865 (propertize delim
10866 'js2-magic (line-number-at-pos pos)
10867 'face 'js2-magic-paren-face))
10868
10869 (defun js2-mode-match-delimiter (open close)
10870 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10871 The rule we use, which as far as we can tell is how Eclipse works,
10872 is that we insert the match if we're not in a comment or string,
10873 and the next non-whitespace character is either punctuation or
10874 occurs on another line."
10875 (insert open)
10876 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10877 (not (js2-mode-inside-comment-or-string)))
10878 (save-excursion
10879 (insert (js2-make-magic-delimiter close)))
10880 (when js2-auto-indent-p
10881 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10882 (js2-indent-line)))))
10883
10884 (defun js2-mode-match-bracket ()
10885 "Insert matching bracket."
10886 (interactive)
10887 (js2-mode-match-delimiter "[" "]"))
10888
10889 (defun js2-mode-match-paren ()
10890 "Insert matching paren unless already inserted."
10891 (interactive)
10892 (js2-mode-match-delimiter "(" ")"))
10893
10894 (defun js2-mode-match-curly (arg)
10895 "Insert matching curly-brace.
10896 With prefix arg, no formatting or indentation will occur -- the close-brace
10897 is simply inserted directly at the point."
10898 (interactive "p")
10899 (let (try-pos)
10900 (cond
10901 (current-prefix-arg
10902 (js2-mode-match-delimiter "{" "}"))
10903 ((and js2-auto-insert-catch-block
10904 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10905 (point-at-bol))
10906 (match-beginning 1))))
10907 (js2-insert-catch-skel try-pos))
10908 (t
10909 ;; Otherwise try to do something smarter.
10910 (insert "{")
10911 (unless (or (not (looking-at "\\s-*$"))
10912 (save-excursion
10913 (skip-chars-forward " \t\r\n")
10914 (and (looking-at "}")
10915 (js2-error-at-point)))
10916 (js2-mode-inside-comment-or-string))
10917 (undo-boundary)
10918 ;; absolutely mystifying bug: when inserting the next "\n",
10919 ;; the buffer-undo-list is given two new entries: the inserted range,
10920 ;; and the incorrect position of the point. It's recorded incorrectly
10921 ;; as being before the opening "{", not after it. But it's recorded
10922 ;; as the correct value if you're debugging `js2-mode-match-curly'
10923 ;; in edebug. I have no idea why it's doing this, but incrementing
10924 ;; the inserted position fixes the problem, so that the undo takes us
10925 ;; back to just after the user-inserted "{".
10926 (insert "\n")
10927 (ignore-errors
10928 (incf (cadr buffer-undo-list)))
10929 (js2-indent-line)
10930 (save-excursion
10931 (insert "\n}")
10932 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10933 (js2-indent-line))))))))
10934
10935 (defun js2-insert-catch-skel (try-pos)
10936 "Complete a try/catch block after inserting a { following a try keyword.
10937 Rationale is that a try always needs a catch or a finally, and the catch is
10938 the more likely of the two.
10939
10940 TRY-POS is the buffer position of the try keyword. The open-curly should
10941 already have been inserted."
10942 (insert "{")
10943 (let ((try-col (save-excursion
10944 (goto-char try-pos)
10945 (current-column))))
10946 (insert "\n")
10947 (undo-boundary)
10948 (js2-indent-line) ;; indent the blank line where cursor will end up
10949 (save-excursion
10950 (insert "\n")
10951 (indent-to try-col)
10952 (insert "} catch (x) {\n\n")
10953 (indent-to try-col)
10954 (insert "}"))))
10955
10956 (defun js2-mode-highlight-magic-parens ()
10957 "Re-highlight magic parens after parsing nukes the 'face prop."
10958 (let ((beg (point-min))
10959 end)
10960 (while (setq beg (next-single-property-change beg 'js2-magic))
10961 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10962 (if (get-text-property beg 'js2-magic)
10963 (js2-with-unmodifying-text-property-changes
10964 (put-text-property beg (or end (1+ beg))
10965 'face 'js2-magic-paren-face))))))
10966
10967 (defun js2-mode-mundanify-parens ()
10968 "Clear all magic parens and brackets."
10969 (let ((beg (point-min))
10970 end)
10971 (while (setq beg (next-single-property-change beg 'js2-magic))
10972 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10973 (remove-text-properties beg (or end (1+ beg))
10974 '(js2-magic face)))))
10975
10976 (defsubst js2-match-quote (quote-string)
10977 (let ((start-quote (js2-mode-inside-string)))
10978 (cond
10979 ;; inside a comment - don't do quote-matching, since we can't
10980 ;; reliably figure out if we're in a string inside the comment
10981 ((js2-comment-at-point)
10982 (insert quote-string))
10983 ((not start-quote)
10984 ;; not in string => insert matched quotes
10985 (insert quote-string)
10986 ;; exception: if we're just before a word, don't double it.
10987 (unless (looking-at "[^ \t\r\n]")
10988 (save-excursion
10989 (insert quote-string))))
10990 ((looking-at quote-string)
10991 (if (looking-back "[^\\]\\\\")
10992 (insert quote-string)
10993 (forward-char 1)))
10994 ((and js2-mode-escape-quotes
10995 (save-excursion
10996 (save-match-data
10997 (re-search-forward quote-string (point-at-eol) t))))
10998 ;; inside terminated string, escape quote (unless already escaped)
10999 (insert (if (looking-back "[^\\]\\\\")
11000 quote-string
11001 (concat "\\" quote-string))))
11002 (t
11003 (insert quote-string))))) ; else terminate the string
11004
11005 (defun js2-mode-match-single-quote ()
11006 "Insert matching single-quote."
11007 (interactive)
11008 (let ((parse-status (parse-partial-sexp (point-min) (point))))
11009 ;; don't match inside comments, since apostrophe is more common
11010 (if (nth 4 parse-status)
11011 (insert "'")
11012 (js2-match-quote "'"))))
11013
11014 (defun js2-mode-match-double-quote ()
11015 "Insert matching double-quote."
11016 (interactive)
11017 (js2-match-quote "\""))
11018
11019 ;; Eclipse works as follows:
11020 ;; * type an open-paren and it auto-inserts close-paren
11021 ;; - auto-inserted paren gets a green bracket
11022 ;; - green bracket means typing close-paren there will skip it
11023 ;; * if you insert any text on a different line, it turns off
11024 (defun js2-mode-magic-close-paren ()
11025 "Skip over close-paren rather than inserting, where appropriate."
11026 (interactive)
11027 (let* ((here (point))
11028 (parse-status (parse-partial-sexp (point-min) here))
11029 (open-pos (nth 1 parse-status))
11030 (close last-input-event)
11031 (open (cond
11032 ((eq close ?\))
11033 ?\()
11034 ((eq close ?\])
11035 ?\[)
11036 ((eq close ?})
11037 ?{)
11038 (t nil))))
11039 (if (and (eq (char-after) close)
11040 (eq open (char-after open-pos))
11041 (js2-same-line open-pos)
11042 (get-text-property here 'js2-magic))
11043 (progn
11044 (remove-text-properties here (1+ here) '(js2-magic face))
11045 (forward-char 1))
11046 (insert-char close 1))
11047 (blink-matching-open)))
11048
11049 (defun js2-mode-wait-for-parse (callback)
11050 "Invoke CALLBACK when parsing is finished.
11051 If parsing is already finished, calls CALLBACK immediately."
11052 (if (not js2-mode-buffer-dirty-p)
11053 (funcall callback)
11054 (push callback js2-mode-pending-parse-callbacks)
11055 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11056
11057 (defun js2-mode-parse-finished ()
11058 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11059 ;; We can't let errors propagate up, since it prevents the
11060 ;; `js2-parse' method from completing normally and returning
11061 ;; the ast, which makes things mysteriously not work right.
11062 (unwind-protect
11063 (dolist (cb js2-mode-pending-parse-callbacks)
11064 (condition-case err
11065 (funcall cb)
11066 (error (message "%s" err))))
11067 (setq js2-mode-pending-parse-callbacks nil)))
11068
11069 (defun js2-mode-flag-region (from to flag)
11070 "Hide or show text from FROM to TO, according to FLAG.
11071 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11072 Returns the created overlay if FLAG is non-nil."
11073 (remove-overlays from to 'invisible 'js2-outline)
11074 (when flag
11075 (let ((o (make-overlay from to)))
11076 (overlay-put o 'invisible 'js2-outline)
11077 (overlay-put o 'isearch-open-invisible
11078 'js2-isearch-open-invisible)
11079 o)))
11080
11081 ;; Function to be set as an outline-isearch-open-invisible' property
11082 ;; to the overlay that makes the outline invisible (see
11083 ;; `js2-mode-flag-region').
11084 (defun js2-isearch-open-invisible (overlay)
11085 ;; We rely on the fact that isearch places point on the matched text.
11086 (js2-mode-show-element))
11087
11088 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11089 "Return cons cell of bounds of folding overlay at POS.
11090 Returns nil if not found."
11091 (let ((overlays (overlays-at (or pos (point))))
11092 o)
11093 (while (and overlays
11094 (not o))
11095 (if (overlay-get (car overlays) 'invisible)
11096 (setq o (car overlays))
11097 (setq overlays (cdr overlays))))
11098 (if o
11099 (cons (overlay-start o) (overlay-end o)))))
11100
11101 (defun js2-mode-function-at-point (&optional pos)
11102 "Return the innermost function node enclosing current point.
11103 Returns nil if point is not in a function."
11104 (let ((node (js2-node-at-point pos)))
11105 (while (and node (not (js2-function-node-p node)))
11106 (setq node (js2-node-parent node)))
11107 (if (js2-function-node-p node)
11108 node)))
11109
11110 (defun js2-mode-toggle-element ()
11111 "Hide or show the foldable element at the point."
11112 (interactive)
11113 (let (comment fn pos)
11114 (save-excursion
11115 (save-match-data
11116 (cond
11117 ;; /* ... */ comment?
11118 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11119 (if (js2-mode-invisible-overlay-bounds
11120 (setq pos (+ 3 (js2-node-abs-pos comment))))
11121 (progn
11122 (goto-char pos)
11123 (js2-mode-show-element))
11124 (js2-mode-hide-element)))
11125 ;; //-comment?
11126 ((save-excursion
11127 (back-to-indentation)
11128 (looking-at js2-mode-//-comment-re))
11129 (js2-mode-toggle-//-comment))
11130 ;; function?
11131 ((setq fn (js2-mode-function-at-point))
11132 (setq pos (and (js2-function-node-body fn)
11133 (js2-node-abs-pos (js2-function-node-body fn))))
11134 (goto-char (1+ pos))
11135 (if (js2-mode-invisible-overlay-bounds)
11136 (js2-mode-show-element)
11137 (js2-mode-hide-element)))
11138 (t
11139 (message "Nothing at point to hide or show")))))))
11140
11141 (defun js2-mode-hide-element ()
11142 "Fold/hide contents of a block, showing ellipses.
11143 Show the hidden text with \\[js2-mode-show-element]."
11144 (interactive)
11145 (if js2-mode-buffer-dirty-p
11146 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11147 (let (node body beg end)
11148 (cond
11149 ((js2-mode-invisible-overlay-bounds)
11150 (message "already hidden"))
11151 (t
11152 (setq node (js2-node-at-point))
11153 (cond
11154 ((js2-block-comment-p node)
11155 (js2-mode-hide-comment node))
11156 (t
11157 (while (and node (not (js2-function-node-p node)))
11158 (setq node (js2-node-parent node)))
11159 (if (and node
11160 (setq body (js2-function-node-body node)))
11161 (progn
11162 (setq beg (js2-node-abs-pos body)
11163 end (+ beg (js2-node-len body)))
11164 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11165 (message "No collapsable element found at point"))))))))
11166
11167 (defun js2-mode-show-element ()
11168 "Show the hidden element at current point."
11169 (interactive)
11170 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11171 (if bounds
11172 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11173 (message "Nothing to un-hide"))))
11174
11175 (defun js2-mode-show-all ()
11176 "Show all of the text in the buffer."
11177 (interactive)
11178 (js2-mode-flag-region (point-min) (point-max) nil))
11179
11180 (defun js2-mode-toggle-hide-functions ()
11181 (interactive)
11182 (if js2-mode-functions-hidden
11183 (js2-mode-show-functions)
11184 (js2-mode-hide-functions)))
11185
11186 (defun js2-mode-hide-functions ()
11187 "Hides all non-nested function bodies in the buffer.
11188 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11189 to open an individual entry."
11190 (interactive)
11191 (if js2-mode-buffer-dirty-p
11192 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11193 (if (null js2-mode-ast)
11194 (message "Oops - parsing failed")
11195 (setq js2-mode-functions-hidden t)
11196 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11197
11198 (defun js2-mode-function-hider (n endp)
11199 (when (not endp)
11200 (let ((tt (js2-node-type n))
11201 body beg end)
11202 (cond
11203 ((and (= tt js2-FUNCTION)
11204 (setq body (js2-function-node-body n)))
11205 (setq beg (js2-node-abs-pos body)
11206 end (+ beg (js2-node-len body)))
11207 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11208 nil) ; don't process children of function
11209 (t
11210 t))))) ; keep processing other AST nodes
11211
11212 (defun js2-mode-show-functions ()
11213 "Un-hide any folded function bodies in the buffer."
11214 (interactive)
11215 (setq js2-mode-functions-hidden nil)
11216 (save-excursion
11217 (goto-char (point-min))
11218 (while (/= (goto-char (next-overlay-change (point)))
11219 (point-max))
11220 (dolist (o (overlays-at (point)))
11221 (when (and (overlay-get o 'invisible)
11222 (not (overlay-get o 'comment)))
11223 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11224
11225 (defun js2-mode-hide-comment (n)
11226 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11227 3 ; /**
11228 2)) ; /*
11229 (beg (+ (js2-node-abs-pos n) head))
11230 (end (- (+ beg (js2-node-len n)) head 2))
11231 (o (js2-mode-flag-region beg end 'hide)))
11232 (overlay-put o 'comment t)))
11233
11234 (defun js2-mode-toggle-hide-comments ()
11235 "Folds all block comments in the buffer.
11236 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11237 to open an individual entry."
11238 (interactive)
11239 (if js2-mode-comments-hidden
11240 (js2-mode-show-comments)
11241 (js2-mode-hide-comments)))
11242
11243 (defun js2-mode-hide-comments ()
11244 (interactive)
11245 (if js2-mode-buffer-dirty-p
11246 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11247 (if (null js2-mode-ast)
11248 (message "Oops - parsing failed")
11249 (setq js2-mode-comments-hidden t)
11250 (dolist (n (js2-ast-root-comments js2-mode-ast))
11251 (let ((format (js2-comment-node-format n)))
11252 (when (js2-block-comment-p n)
11253 (js2-mode-hide-comment n))))
11254 (js2-mode-hide-//-comments)))
11255
11256 (defsubst js2-mode-extend-//-comment (direction)
11257 "Find start or end of a block of similar //-comment lines.
11258 DIRECTION is -1 to look back, 1 to look forward.
11259 INDENT is the indentation level to match.
11260 Returns the end-of-line position of the furthest adjacent
11261 //-comment line with the same indentation as the current line.
11262 If there is no such matching line, returns current end of line."
11263 (let ((pos (point-at-eol))
11264 (indent (current-indentation)))
11265 (save-excursion
11266 (save-match-data
11267 (while (and (zerop (forward-line direction))
11268 (looking-at js2-mode-//-comment-re)
11269 (eq indent (length (match-string 1))))
11270 (setq pos (point-at-eol)))
11271 pos))))
11272
11273 (defun js2-mode-hide-//-comments ()
11274 "Fold adjacent 1-line comments, showing only snippet of first one."
11275 (let (beg end)
11276 (save-excursion
11277 (save-match-data
11278 (goto-char (point-min))
11279 (while (re-search-forward js2-mode-//-comment-re nil t)
11280 (setq beg (point)
11281 end (js2-mode-extend-//-comment 1))
11282 (unless (eq beg end)
11283 (overlay-put (js2-mode-flag-region beg end 'hide)
11284 'comment t))
11285 (goto-char end)
11286 (forward-char 1))))))
11287
11288 (defun js2-mode-toggle-//-comment ()
11289 "Fold or un-fold any multi-line //-comment at point.
11290 Caller should have determined that this line starts with a //-comment."
11291 (let* ((beg (point-at-eol))
11292 (end beg))
11293 (save-excursion
11294 (goto-char end)
11295 (if (js2-mode-invisible-overlay-bounds)
11296 (js2-mode-show-element)
11297 ;; else hide the comment
11298 (setq beg (js2-mode-extend-//-comment -1)
11299 end (js2-mode-extend-//-comment 1))
11300 (unless (eq beg end)
11301 (overlay-put (js2-mode-flag-region beg end 'hide)
11302 'comment t))))))
11303
11304 (defun js2-mode-show-comments ()
11305 "Un-hide any hidden comments, leaving other hidden elements alone."
11306 (interactive)
11307 (setq js2-mode-comments-hidden nil)
11308 (save-excursion
11309 (goto-char (point-min))
11310 (while (/= (goto-char (next-overlay-change (point)))
11311 (point-max))
11312 (dolist (o (overlays-at (point)))
11313 (when (overlay-get o 'comment)
11314 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11315
11316 (defun js2-mode-display-warnings-and-errors ()
11317 "Turn on display of warnings and errors."
11318 (interactive)
11319 (setq js2-mode-show-parse-errors t
11320 js2-mode-show-strict-warnings t)
11321 (js2-reparse 'force))
11322
11323 (defun js2-mode-hide-warnings-and-errors ()
11324 "Turn off display of warnings and errors."
11325 (interactive)
11326 (setq js2-mode-show-parse-errors nil
11327 js2-mode-show-strict-warnings nil)
11328 (js2-reparse 'force))
11329
11330 (defun js2-mode-toggle-warnings-and-errors ()
11331 "Toggle the display of warnings and errors.
11332 Some users don't like having warnings/errors reported while they type."
11333 (interactive)
11334 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11335 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11336 (if (interactive-p)
11337 (message "warnings and errors %s"
11338 (if js2-mode-show-parse-errors
11339 "enabled"
11340 "disabled")))
11341 (js2-reparse 'force))
11342
11343 (defun js2-mode-customize ()
11344 (interactive)
11345 (customize-group 'js2-mode))
11346
11347 (defun js2-mode-forward-sexp (&optional arg)
11348 "Move forward across one statement or balanced expression.
11349 With ARG, do it that many times. Negative arg -N means
11350 move backward across N balanced expressions."
11351 (interactive "p")
11352 (setq arg (or arg 1))
11353 (if js2-mode-buffer-dirty-p
11354 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11355 (let (node end (start (point)))
11356 (cond
11357 ;; backward-sexp
11358 ;; could probably make this better for some cases:
11359 ;; - if in statement block (e.g. function body), go to parent
11360 ;; - infix exprs like (foo in bar) - maybe go to beginning
11361 ;; of infix expr if in the right-side expression?
11362 ((and arg (minusp arg))
11363 (dotimes (i (- arg))
11364 (js2-backward-sws)
11365 (forward-char -1) ; enter the node we backed up to
11366 (setq node (js2-node-at-point (point) t))
11367 (goto-char (if node
11368 (js2-node-abs-pos node)
11369 (point-min)))))
11370 (t
11371 ;; forward-sexp
11372 (js2-forward-sws)
11373 (dotimes (i arg)
11374 (js2-forward-sws)
11375 (setq node (js2-node-at-point (point) t)
11376 end (if node (+ (js2-node-abs-pos node)
11377 (js2-node-len node))))
11378 (goto-char (or end (point-max))))))))
11379
11380 (defun js2-next-error (&optional arg reset)
11381 "Move to next parse error.
11382 Typically invoked via \\[next-error].
11383 ARG is the number of errors, forward or backward, to move.
11384 RESET means start over from the beginning."
11385 (interactive "p")
11386 (if (or (null js2-mode-ast)
11387 (and (null (js2-ast-root-errors js2-mode-ast))
11388 (null (js2-ast-root-warnings js2-mode-ast))))
11389 (message "No errors")
11390 (when reset
11391 (goto-char (point-min)))
11392 (let* ((errs (copy-sequence
11393 (append (js2-ast-root-errors js2-mode-ast)
11394 (js2-ast-root-warnings js2-mode-ast))))
11395 (continue t)
11396 (start (point))
11397 (count (or arg 1))
11398 (backward (minusp count))
11399 (sorter (if backward '> '<))
11400 (stopper (if backward '< '>))
11401 (count (abs count))
11402 all-errs
11403 err)
11404 ;; sort by start position
11405 (setq errs (sort errs (lambda (e1 e2)
11406 (funcall sorter (second e1) (second e2))))
11407 all-errs errs)
11408 ;; find nth error with pos > start
11409 (while (and errs continue)
11410 (when (funcall stopper (cadar errs) start)
11411 (setq err (car errs))
11412 (if (zerop (decf count))
11413 (setq continue nil)))
11414 (setq errs (cdr errs)))
11415 (if err
11416 (goto-char (second err))
11417 ;; wrap around to first error
11418 (goto-char (second (car all-errs)))
11419 ;; if we were already on it, echo msg again
11420 (if (= (point) start)
11421 (js2-echo-error (point) (point)))))))
11422
11423 (defun js2-down-mouse-3 ()
11424 "Make right-click move the point to the click location.
11425 This makes right-click context menu operations a bit more intuitive.
11426 The point will not move if the region is active, however, to avoid
11427 destroying the region selection."
11428 (interactive)
11429 (when (and js2-move-point-on-right-click
11430 (not mark-active))
11431 (let ((e last-input-event))
11432 (ignore-errors
11433 (goto-char (cadadr e))))))
11434
11435 (defun js2-mode-create-imenu-index ()
11436 "Return an alist for `imenu--index-alist'."
11437 ;; This is built up in `js2-parse-record-imenu' during parsing.
11438 (when js2-mode-ast
11439 ;; if we have an ast but no recorder, they're requesting a rescan
11440 (unless js2-imenu-recorder
11441 (js2-reparse 'force))
11442 (prog1
11443 (js2-build-imenu-index)
11444 (setq js2-imenu-recorder nil
11445 js2-imenu-function-map nil))))
11446
11447 (defun js2-mode-find-tag ()
11448 "Replacement for `find-tag-default'.
11449 `find-tag-default' returns a ridiculous answer inside comments."
11450 (let (beg end)
11451 (js2-with-underscore-as-word-syntax
11452 (save-excursion
11453 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11454 (looking-back "[A-Za-z0-9_$]"))
11455 (setq beg (progn (forward-word -1) (point))
11456 end (progn (forward-word 1) (point)))
11457 (setq beg (progn (forward-word 1) (point))
11458 end (progn (forward-word -1) (point))))
11459 (replace-regexp-in-string
11460 "[\"']" ""
11461 (buffer-substring-no-properties beg end))))))
11462
11463 (defun js2-mode-forward-sibling ()
11464 "Move to the end of the sibling following point in parent.
11465 Returns non-nil if successful, or nil if there was no following sibling."
11466 (let* ((node (js2-node-at-point))
11467 (parent (js2-mode-find-enclosing-fn node))
11468 sib)
11469 (when (setq sib (js2-node-find-child-after (point) parent))
11470 (goto-char (+ (js2-node-abs-pos sib)
11471 (js2-node-len sib))))))
11472
11473 (defun js2-mode-backward-sibling ()
11474 "Move to the beginning of the sibling node preceding point in parent.
11475 Parent is defined as the enclosing script or function."
11476 (let* ((node (js2-node-at-point))
11477 (parent (js2-mode-find-enclosing-fn node))
11478 sib)
11479 (when (setq sib (js2-node-find-child-before (point) parent))
11480 (goto-char (js2-node-abs-pos sib)))))
11481
11482 (defun js2-beginning-of-defun ()
11483 "Go to line on which current function starts, and return non-nil.
11484 If we're not in a function, go to beginning of previous script-level element."
11485 (interactive)
11486 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11487 pos sib)
11488 (cond
11489 ((and (js2-function-node-p parent)
11490 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11491 (goto-char pos))
11492 (t
11493 (js2-mode-backward-sibling)))))
11494
11495 (defun js2-end-of-defun ()
11496 "Go to the char after the last position of the current function.
11497 If we're not in a function, skips over the next script-level element."
11498 (interactive)
11499 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11500 (if (not (js2-function-node-p parent))
11501 ;; punt: skip over next script-level element beyond point
11502 (js2-mode-forward-sibling)
11503 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11504 (js2-node-len parent)))))))
11505
11506 (defun js2-mark-defun (&optional allow-extend)
11507 "Put mark at end of this function, point at beginning.
11508 The function marked is the one that contains point.
11509
11510 Interactively, if this command is repeated,
11511 or (in Transient Mark mode) if the mark is active,
11512 it marks the next defun after the ones already marked."
11513 (interactive "p")
11514 (let (extended)
11515 (when (and allow-extend
11516 (or (and (eq last-command this-command) (mark t))
11517 (and transient-mark-mode mark-active)))
11518 (let ((sib (save-excursion
11519 (goto-char (mark))
11520 (if (js2-mode-forward-sibling)
11521 (point))))
11522 node)
11523 (if sib
11524 (progn
11525 (set-mark sib)
11526 (setq extended t))
11527 ;; no more siblings - try extending to enclosing node
11528 (goto-char (mark t)))))
11529 (when (not extended)
11530 (let ((node (js2-node-at-point (point) t)) ; skip comments
11531 ast fn stmt parent beg end)
11532 (when (js2-ast-root-p node)
11533 (setq ast node
11534 node (or (js2-node-find-child-after (point) node)
11535 (js2-node-find-child-before (point) node))))
11536 ;; only mark whole buffer if we can't find any children
11537 (if (null node)
11538 (setq node ast))
11539 (if (js2-function-node-p node)
11540 (setq parent node)
11541 (setq fn (js2-mode-find-enclosing-fn node)
11542 stmt (if (or (null fn)
11543 (js2-ast-root-p fn))
11544 (js2-mode-find-first-stmt node))
11545 parent (or stmt fn)))
11546 (setq beg (js2-node-abs-pos parent)
11547 end (+ beg (js2-node-len parent)))
11548 (push-mark beg)
11549 (goto-char end)
11550 (exchange-point-and-mark)))))
11551
11552 (defun js2-narrow-to-defun ()
11553 "Narrow to the function enclosing point."
11554 (interactive)
11555 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11556 (fn (if (js2-script-node-p node)
11557 node
11558 (js2-mode-find-enclosing-fn node)))
11559 (beg (js2-node-abs-pos fn)))
11560 (unless (js2-ast-root-p fn)
11561 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11562
11563 (provide 'js2-mode)
11564
11565 ;;; js2-mode.el ends here