]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
fixed ugly indentation with multiple variable declaration. closes #1.
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Version: See `js2-mode-version'
8 ;; Keywords: languages, javascript
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This JavaScript editing mode supports:
28
29 ;; - strict recognition of the Ecma-262 language standard
30 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
31 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
32 ;; - accurate syntax highlighting using a recursive-descent parser
33 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
34 ;; - undeclared-variable warnings using a configurable externs framework
35 ;; - "bouncing" line indentation to choose among alternate indentation points
36 ;; - smart line-wrapping within comments and strings
37 ;; - code folding:
38 ;; - show some or all function bodies as {...}
39 ;; - show some or all block comments as /*...*/
40 ;; - context-sensitive menu bar and popup menus
41 ;; - code browsing using the `imenu' package
42 ;; - typing helpers such as automatic insertion of matching braces/parens
43 ;; - many customization options
44
45 ;; To customize how it works:
46 ;; M-x customize-group RET js2-mode RET
47
48 ;; Notes:
49
50 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
51 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
52 ;; `js2-mode' current as the EcmaScript language standard evolves.
53
54 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
55 ;; customizable. It is a surprising amount of work to support customizable
56 ;; indentation. The current compromise is that the tab key lets you cycle among
57 ;; various likely indentation points, similar to the behavior of python-mode.
58
59 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
60 ;; and `mumamo', although it could be made to do so with some effort.
61 ;; This means that `js2-mode' is currently only useful for editing JavaScript
62 ;; files, and not for editing JavaScript within <script> tags or templates.
63
64 ;;; Code:
65
66 (eval-when-compile
67 (require 'cl))
68
69 (require 'imenu)
70 (require 'cc-cmds) ; for `c-fill-paragraph'
71
72 (eval-and-compile
73 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
74 (require 'cc-langs) ; it's here in Emacs 21...
75 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
76
77 ;;; Externs (variables presumed to be defined by the host system)
78
79 (defvar js2-ecma-262-externs
80 (mapcar 'symbol-name
81 '(Array Boolean Date Error EvalError Function Infinity
82 Math NaN Number Object RangeError ReferenceError RegExp
83 String SyntaxError TypeError URIError arguments
84 decodeURI decodeURIComponent encodeURI
85 encodeURIComponent escape eval isFinite isNaN
86 parseFloat parseInt undefined unescape))
87 "Ecma-262 externs. Included in `js2-externs' by default.")
88
89 (defvar js2-browser-externs
90 (mapcar 'symbol-name
91 '(;; DOM level 1
92 Attr CDATASection CharacterData Comment DOMException
93 DOMImplementation Document DocumentFragment
94 DocumentType Element Entity EntityReference
95 ExceptionCode NamedNodeMap Node NodeList Notation
96 ProcessingInstruction Text
97
98 ;; DOM level 2
99 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
100 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
101 HTMLBodyElement HTMLButtonElement HTMLCollection
102 HTMLDListElement HTMLDirectoryElement HTMLDivElement
103 HTMLDocument HTMLElement HTMLFieldSetElement
104 HTMLFontElement HTMLFormElement HTMLFrameElement
105 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
106 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
107 HTMLImageElement HTMLInputElement HTMLIsIndexElement
108 HTMLLIElement HTMLLabelElement HTMLLegendElement
109 HTMLLinkElement HTMLMapElement HTMLMenuElement
110 HTMLMetaElement HTMLModElement HTMLOListElement
111 HTMLObjectElement HTMLOptGroupElement
112 HTMLOptionElement HTMLOptionsCollection
113 HTMLParagraphElement HTMLParamElement HTMLPreElement
114 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
115 HTMLStyleElement HTMLTableCaptionElement
116 HTMLTableCellElement HTMLTableColElement
117 HTMLTableElement HTMLTableRowElement
118 HTMLTableSectionElement HTMLTextAreaElement
119 HTMLTitleElement HTMLUListElement
120
121 ;; DOM level 3
122 DOMConfiguration DOMError DOMException
123 DOMImplementationList DOMImplementationSource
124 DOMLocator DOMStringList NameList TypeInfo
125 UserDataHandler
126
127 ;; Window
128 alert confirm document java navigator prompt screen
129 self top
130
131 ;; W3C CSS
132 CSSCharsetRule CSSFontFace CSSFontFaceRule
133 CSSImportRule CSSMediaRule CSSPageRule
134 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
135 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
136 CSSValue CSSValueList Counter DOMImplementationCSS
137 DocumentCSS DocumentStyle ElementCSSInlineStyle
138 LinkStyle MediaList RGBColor Rect StyleSheet
139 StyleSheetList ViewCSS
140
141 ;; W3C Event
142 EventListener EventTarget Event DocumentEvent UIEvent
143 MouseEvent MutationEvent KeyboardEvent
144
145 ;; W3C Range
146 DocumentRange Range RangeException
147
148 ;; W3C XML
149 XPathResult XMLHttpRequest))
150 "Browser externs.
151 You can cause these to be included or excluded with the custom
152 variable `js2-include-browser-externs'.")
153
154 (defvar js2-rhino-externs
155 (mapcar 'symbol-name
156 '(Packages importClass importPackage com org java
157 ;; Global object (shell) externs
158 defineClass deserialize doctest gc help load
159 loadClass print quit readFile readUrl runCommand seal
160 serialize spawn sync toint32 version))
161 "Mozilla Rhino externs.
162 Set `js2-include-rhino-externs' to t to include them.")
163
164 (defvar js2-gears-externs
165 (mapcar 'symbol-name
166 '(
167 ;; TODO(stevey): add these
168 ))
169 "Google Gears externs.
170 Set `js2-include-gears-externs' to t to include them.")
171
172 ;;; Variables
173
174 (defvar js2-emacs22 (>= emacs-major-version 22))
175
176 (defcustom js2-highlight-level 2
177 "Amount of syntax highlighting to perform.
178 0 or a negative value means do no highlighting.
179 1 adds basic syntax highlighting.
180 2 adds highlighting of some Ecma built-in properties.
181 3 adds highlighting of many Ecma built-in functions."
182 :group 'js2-mode
183 :type '(choice (const :tag "None" 0)
184 (const :tag "Basic" 1)
185 (const :tag "Include Properties" 2)
186 (const :tag "Include Functions" 3)))
187
188 (defvar js2-mode-dev-mode-p nil
189 "Non-nil if running in development mode. Normally nil.")
190
191 (defgroup js2-mode nil
192 "An improved JavaScript mode."
193 :group 'languages)
194
195 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
196 (numberp c-basic-offset))
197 c-basic-offset
198 4)
199 "Number of spaces to indent nested statements.
200 Similar to `c-basic-offset'."
201 :group 'js2-mode
202 :type 'integer)
203 (make-variable-buffer-local 'js2-basic-offset)
204
205 ;; TODO(stevey): move this code into a separate minor mode.
206 (defcustom js2-mirror-mode nil
207 "Non-nil to insert closing brackets, parens, etc. automatically."
208 :group 'js2-mode
209 :type 'boolean)
210
211 (defcustom js2-auto-indent-p nil
212 "Automatic indentation with punctuation characters.
213 If non-nil, the current line is indented when certain punctuations
214 are inserted."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-bounce-indent-p nil
219 "Non-nil to have indent-line function choose among alternatives.
220 If nil, the indent-line function will indent to a predetermined column
221 based on heuristic guessing. If non-nil, then if the current line is
222 already indented to that predetermined column, indenting will choose
223 another likely column and indent to that spot. Repeated invocation of
224 the indent-line function will cycle among the computed alternatives.
225 See the function `js2-bounce-indent' for details."
226 :type 'boolean
227 :group 'js2-mode)
228
229 (defcustom js2-consistent-level-indent-inner-bracket-p t
230 "Non-nil to make indentation level inner bracket consistent,
231 regardless of the beginning bracket position."
232 :group 'js2-mode
233 :type 'boolean)
234
235 (defcustom js2-indent-on-enter-key nil
236 "Non-nil to have Enter/Return key indent the line.
237 This is unusual for Emacs modes but common in IDEs like Eclipse."
238 :type 'boolean
239 :group 'js2-mode)
240
241 (defcustom js2-enter-indents-newline nil
242 "Non-nil to have Enter/Return key indent the newly-inserted line.
243 This is unusual for Emacs modes but common in IDEs like Eclipse."
244 :type 'boolean
245 :group 'js2-mode)
246
247 (defcustom js2-rebind-eol-bol-keys t
248 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
249 If non-nil, bounce between bol/eol and first/last non-whitespace char."
250 :group 'js2-mode
251 :type 'boolean)
252
253 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
254 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
255 Each value in the list is passed to `define-key'."
256 :type 'list
257 :group 'js2-mode)
258
259 (defcustom js2-idle-timer-delay 0.2
260 "Delay in secs before re-parsing after user makes changes.
261 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
262 :type 'number
263 :group 'js2-mode)
264 (make-variable-buffer-local 'js2-idle-timer-delay)
265
266 (defcustom js2-dynamic-idle-timer-adjust 0
267 "Positive to adjust `js2-idle-timer-delay' based on file size.
268 The idea is that for short files, parsing is faster so we can be
269 more responsive to user edits without interfering with editing.
270 The buffer length in characters (typically bytes) is divided by
271 this value and used to multiply `js2-idle-timer-delay' for the
272 buffer. For example, a 21k file and 10k adjust yields 21k/10k
273 == 2, so js2-idle-timer-delay is multiplied by 2.
274 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
275 `js2-idle-timer-delay' is not dependent on the file size."
276 :type 'number
277 :group 'js2-mode)
278
279 (defcustom js2-mode-escape-quotes t
280 "Non-nil to disable automatic quote-escaping inside strings."
281 :type 'boolean
282 :group 'js2-mode)
283
284 (defcustom js2-mode-squeeze-spaces t
285 "Non-nil to normalize whitespace when filling in comments.
286 Multiple runs of spaces are converted to a single space."
287 :type 'boolean
288 :group 'js2-mode)
289
290 (defcustom js2-mode-show-parse-errors t
291 "True to highlight parse errors."
292 :type 'boolean
293 :group 'js2-mode)
294
295 (defcustom js2-mode-show-strict-warnings t
296 "Non-nil to emit Ecma strict-mode warnings.
297 Some of the warnings can be individually disabled by other flags,
298 even if this flag is non-nil."
299 :type 'boolean
300 :group 'js2-mode)
301
302 (defcustom js2-strict-trailing-comma-warning t
303 "Non-nil to warn about trailing commas in array literals.
304 Ecma-262 forbids them, but many browsers permit them. IE is the
305 big exception, and can produce bugs if you have trailing commas."
306 :type 'boolean
307 :group 'js2-mode)
308
309 (defcustom js2-strict-missing-semi-warning t
310 "Non-nil to warn about semicolon auto-insertion after statement.
311 Technically this is legal per Ecma-262, but some style guides disallow
312 depending on it."
313 :type 'boolean
314 :group 'js2-mode)
315
316 (defcustom js2-missing-semi-one-line-override nil
317 "Non-nil to permit missing semicolons in one-line functions.
318 In one-liner functions such as `function identity(x) {return x}'
319 people often omit the semicolon for a cleaner look. If you are
320 such a person, you can suppress the missing-semicolon warning
321 by setting this variable to t."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-inconsistent-return-warning t
326 "Non-nil to warn about mixing returns with value-returns.
327 It's perfectly legal to have a `return' and a `return foo' in the
328 same function, but it's often an indicator of a bug, and it also
329 interferes with type inference (in systems that support it.)"
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-cond-assign-warning t
334 "Non-nil to warn about expressions like if (a = b).
335 This often should have been '==' instead of '='. If the warning
336 is enabled, you can suppress it on a per-expression basis by
337 parenthesizing the expression, e.g. if ((a = b)) ..."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-strict-cond-assign-warning t
342 "Non-nil to warn about expressions like if (a = b).
343 This often should have been '==' instead of '='. If the warning
344 is enabled, you can suppress it on a per-expression basis by
345 parenthesizing the expression, e.g. if ((a = b)) ..."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-var-redeclaration-warning t
350 "Non-nil to warn about redeclaring variables in a script or function."
351 :type 'boolean
352 :group 'js2-mode)
353
354 (defcustom js2-strict-var-hides-function-arg-warning t
355 "Non-nil to warn about a var decl hiding a function argument."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-skip-preprocessor-directives nil
360 "Non-nil to treat lines beginning with # as comments.
361 Useful for viewing Mozilla JavaScript source code."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-language-version 180
366 "Configures what JavaScript language version to recognize.
367 Currently versions 150, 160, 170 and 180 are supported, corresponding
368 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
369 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
370 and 1.8 adds function closures."
371 :type 'integer
372 :group 'js2-mode)
373
374 (defcustom js2-allow-keywords-as-property-names t
375 "If non-nil, you can use JavaScript keywords as object property names.
376 Examples:
377
378 var foo = {int: 5, while: 6, continue: 7};
379 foo.return = 8;
380
381 Ecma-262 forbids this syntax, but many browsers support it."
382 :type 'boolean
383 :group 'js2-mode)
384
385 (defcustom js2-instanceof-has-side-effects nil
386 "If non-nil, treats the instanceof operator as having side effects.
387 This is useful for xulrunner apps."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-cleanup-whitespace nil
392 "Non-nil to invoke `delete-trailing-whitespace' before saves."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-move-point-on-right-click t
397 "Non-nil to move insertion point when you right-click.
398 This makes right-click context menu behavior a bit more intuitive,
399 since menu operations generally apply to the point. The exception
400 is if there is a region selection, in which case the point does -not-
401 move, so cut/copy/paste etc. can work properly.
402
403 Note that IntelliJ moves the point, and Eclipse leaves it alone,
404 so this behavior is customizable."
405 :group 'js2-mode
406 :type 'boolean)
407
408 (defcustom js2-allow-rhino-new-expr-initializer t
409 "Non-nil to support a Rhino's experimental syntactic construct.
410
411 Rhino supports the ability to follow a `new' expression with an object
412 literal, which is used to set additional properties on the new object
413 after calling its constructor. Syntax:
414
415 new <expr> [ ( arglist ) ] [initializer]
416
417 Hence, this expression:
418
419 new Object {a: 1, b: 2}
420
421 results in an Object with properties a=1 and b=2. This syntax is
422 apparently not configurable in Rhino - it's currently always enabled,
423 as of Rhino version 1.7R2."
424 :type 'boolean
425 :group 'js2-mode)
426
427 (defcustom js2-allow-member-expr-as-function-name nil
428 "Non-nil to support experimental Rhino syntax for function names.
429
430 Rhino supports an experimental syntax configured via the Rhino Context
431 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
432
433 function <member-expr> ( [ arg-list ] ) { <body> }
434
435 Where member-expr is a non-parenthesized 'member expression', which
436 is anything at the grammar level of a new-expression or lower, meaning
437 any expression that does not involve infix or unary operators.
438
439 When <member-expr> is not a simple identifier, then it is syntactic
440 sugar for assigning the anonymous function to the <member-expr>. Hence,
441 this code:
442
443 function a.b().c[2] (x, y) { ... }
444
445 is rewritten as:
446
447 a.b().c[2] = function(x, y) {...}
448
449 which doesn't seem particularly useful, but Rhino permits it."
450 :type 'boolean
451 :group 'js2-mode)
452
453 (defvar js2-mode-version 20101228
454 "Release number for `js2-mode'.")
455
456 ;; scanner variables
457
458 (defmacro js2-deflocal (name value &optional comment)
459 "Define a buffer-local variable NAME with VALUE and COMMENT."
460 `(progn
461 (defvar ,name ,value ,comment)
462 (make-variable-buffer-local ',name)))
463
464 ;; We record the start and end position of each token.
465 (js2-deflocal js2-token-beg 1)
466 (js2-deflocal js2-token-end -1)
467
468 (defvar js2-EOF_CHAR -1
469 "Represents end of stream. Distinct from js2-EOF token type.")
470
471 ;; I originally used symbols to represent tokens, but Rhino uses
472 ;; ints and then sets various flag bits in them, so ints it is.
473 ;; The upshot is that we need a `js2-' prefix in front of each name.
474 (defvar js2-ERROR -1)
475 (defvar js2-EOF 0)
476 (defvar js2-EOL 1)
477 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
478 (defvar js2-LEAVEWITH 3)
479 (defvar js2-RETURN 4)
480 (defvar js2-GOTO 5)
481 (defvar js2-IFEQ 6)
482 (defvar js2-IFNE 7)
483 (defvar js2-SETNAME 8)
484 (defvar js2-BITOR 9)
485 (defvar js2-BITXOR 10)
486 (defvar js2-BITAND 11)
487 (defvar js2-EQ 12)
488 (defvar js2-NE 13)
489 (defvar js2-LT 14)
490 (defvar js2-LE 15)
491 (defvar js2-GT 16)
492 (defvar js2-GE 17)
493 (defvar js2-LSH 18)
494 (defvar js2-RSH 19)
495 (defvar js2-URSH 20)
496 (defvar js2-ADD 21) ; infix plus
497 (defvar js2-SUB 22) ; infix minus
498 (defvar js2-MUL 23)
499 (defvar js2-DIV 24)
500 (defvar js2-MOD 25)
501 (defvar js2-NOT 26)
502 (defvar js2-BITNOT 27)
503 (defvar js2-POS 28) ; unary plus
504 (defvar js2-NEG 29) ; unary minus
505 (defvar js2-NEW 30)
506 (defvar js2-DELPROP 31)
507 (defvar js2-TYPEOF 32)
508 (defvar js2-GETPROP 33)
509 (defvar js2-GETPROPNOWARN 34)
510 (defvar js2-SETPROP 35)
511 (defvar js2-GETELEM 36)
512 (defvar js2-SETELEM 37)
513 (defvar js2-CALL 38)
514 (defvar js2-NAME 39) ; an identifier
515 (defvar js2-NUMBER 40)
516 (defvar js2-STRING 41)
517 (defvar js2-NULL 42)
518 (defvar js2-THIS 43)
519 (defvar js2-FALSE 44)
520 (defvar js2-TRUE 45)
521 (defvar js2-SHEQ 46) ; shallow equality (===)
522 (defvar js2-SHNE 47) ; shallow inequality (!==)
523 (defvar js2-REGEXP 48)
524 (defvar js2-BINDNAME 49)
525 (defvar js2-THROW 50)
526 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
527 (defvar js2-IN 52)
528 (defvar js2-INSTANCEOF 53)
529 (defvar js2-LOCAL_LOAD 54)
530 (defvar js2-GETVAR 55)
531 (defvar js2-SETVAR 56)
532 (defvar js2-CATCH_SCOPE 57)
533 (defvar js2-ENUM_INIT_KEYS 58)
534 (defvar js2-ENUM_INIT_VALUES 59)
535 (defvar js2-ENUM_INIT_ARRAY 60)
536 (defvar js2-ENUM_NEXT 61)
537 (defvar js2-ENUM_ID 62)
538 (defvar js2-THISFN 63)
539 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
540 (defvar js2-ARRAYLIT 65) ; array literal
541 (defvar js2-OBJECTLIT 66) ; object literal
542 (defvar js2-GET_REF 67) ; *reference
543 (defvar js2-SET_REF 68) ; *reference = something
544 (defvar js2-DEL_REF 69) ; delete reference
545 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
546 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
547 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
548
549 ;; XML support
550 (defvar js2-DEFAULTNAMESPACE 73)
551 (defvar js2-ESCXMLATTR 74)
552 (defvar js2-ESCXMLTEXT 75)
553 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
554 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
555 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
556 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
557
558 (defvar js2-first-bytecode js2-ENTERWITH)
559 (defvar js2-last-bytecode js2-REF_NS_NAME)
560
561 (defvar js2-TRY 80)
562 (defvar js2-SEMI 81) ; semicolon
563 (defvar js2-LB 82) ; left and right brackets
564 (defvar js2-RB 83)
565 (defvar js2-LC 84) ; left and right curly-braces
566 (defvar js2-RC 85)
567 (defvar js2-LP 86) ; left and right parens
568 (defvar js2-RP 87)
569 (defvar js2-COMMA 88) ; comma operator
570
571 (defvar js2-ASSIGN 89) ; simple assignment (=)
572 (defvar js2-ASSIGN_BITOR 90) ; |=
573 (defvar js2-ASSIGN_BITXOR 91) ; ^=
574 (defvar js2-ASSIGN_BITAND 92) ; &=
575 (defvar js2-ASSIGN_LSH 93) ; <<=
576 (defvar js2-ASSIGN_RSH 94) ; >>=
577 (defvar js2-ASSIGN_URSH 95) ; >>>=
578 (defvar js2-ASSIGN_ADD 96) ; +=
579 (defvar js2-ASSIGN_SUB 97) ; -=
580 (defvar js2-ASSIGN_MUL 98) ; *=
581 (defvar js2-ASSIGN_DIV 99) ; /=
582 (defvar js2-ASSIGN_MOD 100) ; %=
583
584 (defvar js2-first-assign js2-ASSIGN)
585 (defvar js2-last-assign js2-ASSIGN_MOD)
586
587 (defvar js2-HOOK 101) ; conditional (?:)
588 (defvar js2-COLON 102)
589 (defvar js2-OR 103) ; logical or (||)
590 (defvar js2-AND 104) ; logical and (&&)
591 (defvar js2-INC 105) ; increment/decrement (++ --)
592 (defvar js2-DEC 106)
593 (defvar js2-DOT 107) ; member operator (.)
594 (defvar js2-FUNCTION 108) ; function keyword
595 (defvar js2-EXPORT 109) ; export keyword
596 (defvar js2-IMPORT 110) ; import keyword
597 (defvar js2-IF 111) ; if keyword
598 (defvar js2-ELSE 112) ; else keyword
599 (defvar js2-SWITCH 113) ; switch keyword
600 (defvar js2-CASE 114) ; case keyword
601 (defvar js2-DEFAULT 115) ; default keyword
602 (defvar js2-WHILE 116) ; while keyword
603 (defvar js2-DO 117) ; do keyword
604 (defvar js2-FOR 118) ; for keyword
605 (defvar js2-BREAK 119) ; break keyword
606 (defvar js2-CONTINUE 120) ; continue keyword
607 (defvar js2-VAR 121) ; var keyword
608 (defvar js2-WITH 122) ; with keyword
609 (defvar js2-CATCH 123) ; catch keyword
610 (defvar js2-FINALLY 124) ; finally keyword
611 (defvar js2-VOID 125) ; void keyword
612 (defvar js2-RESERVED 126) ; reserved keywords
613
614 (defvar js2-EMPTY 127)
615
616 ;; Types used for the parse tree - never returned by scanner.
617
618 (defvar js2-BLOCK 128) ; statement block
619 (defvar js2-LABEL 129) ; label
620 (defvar js2-TARGET 130)
621 (defvar js2-LOOP 131)
622 (defvar js2-EXPR_VOID 132) ; expression statement in functions
623 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
624 (defvar js2-JSR 134)
625 (defvar js2-SCRIPT 135) ; top-level node for entire script
626 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
627 (defvar js2-USE_STACK 137)
628 (defvar js2-SETPROP_OP 138) ; x.y op= something
629 (defvar js2-SETELEM_OP 139) ; x[y] op= something
630 (defvar js2-LOCAL_BLOCK 140)
631 (defvar js2-SET_REF_OP 141) ; *reference op= something
632
633 ;; For XML support:
634 (defvar js2-DOTDOT 142) ; member operator (..)
635 (defvar js2-COLONCOLON 143) ; namespace::name
636 (defvar js2-XML 144) ; XML type
637 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
638 (defvar js2-XMLATTR 146) ; @
639 (defvar js2-XMLEND 147)
640
641 ;; Optimizer-only tokens
642 (defvar js2-TO_OBJECT 148)
643 (defvar js2-TO_DOUBLE 149)
644
645 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
646 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
647 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
648 (defvar js2-CONST 153)
649 (defvar js2-SETCONST 154)
650 (defvar js2-SETCONSTVAR 155)
651 (defvar js2-ARRAYCOMP 156)
652 (defvar js2-LETEXPR 157)
653 (defvar js2-WITHEXPR 158)
654 (defvar js2-DEBUGGER 159)
655
656 (defvar js2-COMMENT 160)
657 (defvar js2-ENUM 161) ; for "enum" reserved word
658
659 (defconst js2-num-tokens (1+ js2-ENUM))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-regexp-flags nil
676 "Token stream buffer-local variable.")
677
678 (js2-deflocal js2-ts-string ""
679 "Token stream buffer-local variable.
680 Last string scanned.")
681
682 (js2-deflocal js2-ts-number nil
683 "Token stream buffer-local variable.
684 Last literal number scanned.")
685
686 (js2-deflocal js2-ts-hit-eof nil
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-line-start 0
690 "Token stream buffer-local variable.")
691
692 (js2-deflocal js2-ts-lineno 1
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-line-end-char -1
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
699 "Token stream buffer-local variable.
700 Current scan position.")
701
702 (js2-deflocal js2-ts-is-xml-attribute nil
703 "Token stream buffer-local variable.")
704
705 (js2-deflocal js2-ts-xml-is-tag-content nil
706 "Token stream buffer-local variable.")
707
708 (js2-deflocal js2-ts-xml-open-tags-count 0
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-string-buffer nil
712 "Token stream buffer-local variable.
713 List of chars built up while scanning various tokens.")
714
715 (js2-deflocal js2-ts-comment-type nil
716 "Token stream buffer-local variable.")
717
718 ;;; Parser variables
719
720 (js2-deflocal js2-parsed-errors nil
721 "List of errors produced during scanning/parsing.")
722
723 (js2-deflocal js2-parsed-warnings nil
724 "List of warnings produced during scanning/parsing.")
725
726 (js2-deflocal js2-recover-from-parse-errors t
727 "Non-nil to continue parsing after a syntax error.
728
729 In recovery mode, the AST will be built in full, and any error
730 nodes will be flagged with appropriate error information. If
731 this flag is nil, a syntax error will result in an error being
732 signaled.
733
734 The variable is automatically buffer-local, because different
735 modes that use the parser will need different settings.")
736
737 (js2-deflocal js2-parse-hook nil
738 "List of callbacks for receiving parsing progress.")
739
740 (defvar js2-parse-finished-hook nil
741 "List of callbacks to notify when parsing finishes.
742 Not called if parsing was interrupted.")
743
744 (js2-deflocal js2-is-eval-code nil
745 "True if we're evaluating code in a string.
746 If non-nil, the tokenizer will record the token text, and the AST nodes
747 will record their source text. Off by default for IDE modes, since the
748 text is available in the buffer.")
749
750 (defvar js2-parse-ide-mode t
751 "Non-nil if the parser is being used for `js2-mode'.
752 If non-nil, the parser will set text properties for fontification
753 and the syntax table. The value should be nil when using the
754 parser as a frontend to an interpreter or byte compiler.")
755
756 ;;; Parser instance variables (buffer-local vars for js2-parse)
757
758 (defconst js2-clear-ti-mask #xFFFF
759 "Mask to clear token information bits.")
760
761 (defconst js2-ti-after-eol (lsh 1 16)
762 "Flag: first token of the source line.")
763
764 (defconst js2-ti-check-label (lsh 1 17)
765 "Flag: indicates to check for label.")
766
767 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
768
769 (js2-deflocal js2-compiler-generate-debug-info t)
770 (js2-deflocal js2-compiler-use-dynamic-scope nil)
771 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
772 (js2-deflocal js2-compiler-xml-available t)
773 (js2-deflocal js2-compiler-optimization-level 0)
774 (js2-deflocal js2-compiler-generating-source t)
775 (js2-deflocal js2-compiler-strict-mode nil)
776 (js2-deflocal js2-compiler-report-warning-as-error nil)
777 (js2-deflocal js2-compiler-generate-observer-count nil)
778 (js2-deflocal js2-compiler-activation-names nil)
779
780 ;; SKIP: sourceURI
781
782 ;; There's a compileFunction method in Context.java - may need it.
783 (js2-deflocal js2-called-by-compile-function nil
784 "True if `js2-parse' was called by `js2-compile-function'.
785 Will only be used when we finish implementing the interpreter.")
786
787 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
788
789 (js2-deflocal js2-current-flagged-token js2-EOF)
790 (js2-deflocal js2-current-token js2-EOF)
791
792 ;; SKIP: node factory - we're going to just call functions directly,
793 ;; and eventually go to a unified AST format.
794
795 (js2-deflocal js2-nesting-of-function 0)
796
797 (js2-deflocal js2-recorded-assignments nil
798 "Tracks assignments found during parsing.")
799
800 (defmacro js2-in-lhs (body)
801 `(let ((js2-is-in-lhs t))
802 ,body))
803
804 (defmacro js2-in-rhs (body)
805 `(let ((js2-is-in-lhs nil))
806 ,body))
807
808 (js2-deflocal js2-is-in-lhs nil
809 "True while parsing lhs statement")
810
811 (defcustom js2-global-externs nil
812 "A list of any extern names you'd like to consider always declared.
813 This list is global and is used by all js2-mode files.
814 You can create buffer-local externs list using `js2-additional-externs'.
815
816 There is also a buffer-local variable `js2-default-externs',
817 which is initialized by default to include the Ecma-262 externs
818 and the standard browser externs. The three lists are all
819 checked during highlighting."
820 :type 'list
821 :group 'js2-mode)
822
823 (js2-deflocal js2-default-externs nil
824 "Default external declarations.
825
826 These are currently only used for highlighting undeclared variables,
827 which only worries about top-level (unqualified) references.
828 As js2-mode's processing improves, we will flesh out this list.
829
830 The initial value is set to `js2-ecma-262-externs', unless you
831 have set `js2-include-browser-externs', in which case the browser
832 externs are also included.
833
834 See `js2-additional-externs' for more information.")
835
836 (defcustom js2-include-browser-externs t
837 "Non-nil to include browser externs in the master externs list.
838 If you work on JavaScript files that are not intended for browsers,
839 such as Mozilla Rhino server-side JavaScript, set this to nil.
840 You can always include them on a per-file basis by calling
841 `js2-add-browser-externs' from a function on `js2-mode-hook'.
842
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-rhino-externs t
848 "Non-nil to include Mozilla Rhino externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-gears-externs t
854 "Non-nil to include Google Gears 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 (js2-deflocal js2-additional-externs nil
860 "A buffer-local list of additional external declarations.
861 It is used to decide whether variables are considered undeclared
862 for purposes of highlighting.
863
864 Each entry is a lisp string. The string should be the fully qualified
865 name of an external entity. All externs should be added to this list,
866 so that as js2-mode's processing improves it can take advantage of them.
867
868 You may want to declare your externs in three ways.
869 First, you can add externs that are valid for all your JavaScript files.
870 You should probably do this by adding them to `js2-global-externs', which
871 is a global list used for all js2-mode files.
872
873 Next, you can add a function to `js2-mode-hook' that adds additional
874 externs appropriate for the specific file, perhaps based on its path.
875 These should go in `js2-additional-externs', which is buffer-local.
876
877 Finally, you can add a function to `js2-post-parse-callbacks',
878 which is called after parsing completes, and `root' is bound to
879 the root of the parse tree. At this stage you can set up an AST
880 node visitor using `js2-visit-ast' and examine the parse tree
881 for specific import patterns that may imply the existence of
882 other externs, possibly tied to your build system. These should also
883 be added to `js2-additional-externs'.
884
885 Your post-parse callback may of course also use the simpler and
886 faster (but perhaps less robust) approach of simply scanning the
887 buffer text for your imports, using regular expressions.")
888
889 ;; SKIP: decompiler
890 ;; SKIP: encoded-source
891
892 ;;; The following variables are per-function and should be saved/restored
893 ;;; during function parsing...
894
895 (js2-deflocal js2-current-script-or-fn nil)
896 (js2-deflocal js2-current-scope nil)
897 (js2-deflocal js2-nesting-of-with 0)
898 (js2-deflocal js2-label-set nil
899 "An alist mapping label names to nodes.")
900
901 (js2-deflocal js2-loop-set nil)
902 (js2-deflocal js2-loop-and-switch-set nil)
903 (js2-deflocal js2-has-return-value nil)
904 (js2-deflocal js2-end-flags 0)
905
906 ;;; ...end of per function variables
907
908 ;; Without 2-token lookahead, labels are a problem.
909 ;; These vars store the token info of the last matched name,
910 ;; iff it wasn't the last matched token. Only valid in some contexts.
911 (defvar js2-prev-name-token-start nil)
912 (defvar js2-prev-name-token-string nil)
913
914 (defsubst js2-save-name-token-data (pos name)
915 (setq js2-prev-name-token-start pos
916 js2-prev-name-token-string name))
917
918 ;; These flags enumerate the possible ways a statement/function can
919 ;; terminate. These flags are used by endCheck() and by the Parser to
920 ;; detect inconsistent return usage.
921 ;;
922 ;; END_UNREACHED is reserved for code paths that are assumed to always be
923 ;; able to execute (example: throw, continue)
924 ;;
925 ;; END_DROPS_OFF indicates if the statement can transfer control to the
926 ;; next one. Statement such as return dont. A compound statement may have
927 ;; some branch that drops off control to the next statement.
928 ;;
929 ;; END_RETURNS indicates that the statement can return (without arguments)
930 ;; END_RETURNS_VALUE indicates that the statement can return a value.
931 ;;
932 ;; A compound statement such as
933 ;; if (condition) {
934 ;; return value;
935 ;; }
936 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
937
938 (defconst js2-end-unreached #x0)
939 (defconst js2-end-drops-off #x1)
940 (defconst js2-end-returns #x2)
941 (defconst js2-end-returns-value #x4)
942 (defconst js2-end-yields #x8)
943
944 ;; Rhino awkwardly passes a statementLabel parameter to the
945 ;; statementHelper() function, the main statement parser, which
946 ;; is then used by quite a few of the sub-parsers. We just make
947 ;; it a buffer-local variable and make sure it's cleaned up properly.
948 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
949
950 ;; Similarly, Rhino passes an inForInit boolean through about half
951 ;; the expression parsers. We use a dynamically-scoped variable,
952 ;; which makes it easier to funcall the parsers individually without
953 ;; worrying about whether they take the parameter or not.
954 (js2-deflocal js2-in-for-init nil)
955 (js2-deflocal js2-temp-name-counter 0)
956 (js2-deflocal js2-parse-stmt-count 0)
957
958 (defsubst js2-get-next-temp-name ()
959 (format "$%d" (incf js2-temp-name-counter)))
960
961 (defvar js2-parse-interruptable-p t
962 "Set this to nil to force parse to continue until finished.
963 This will mostly be useful for interpreters.")
964
965 (defvar js2-statements-per-pause 50
966 "Pause after this many statements to check for user input.
967 If user input is pending, stop the parse and discard the tree.
968 This makes for a smoother user experience for large files.
969 You may have to wait a second or two before the highlighting
970 and error-reporting appear, but you can always type ahead if
971 you wish. This appears to be more or less how Eclipse, IntelliJ
972 and other editors work.")
973
974 (js2-deflocal js2-record-comments t
975 "Instructs the scanner to record comments in `js2-scanned-comments'.")
976
977 (js2-deflocal js2-scanned-comments nil
978 "List of all comments from the current parse.")
979
980 (defcustom js2-mode-indent-inhibit-undo nil
981 "Non-nil to disable collection of Undo information when indenting lines.
982 Some users have requested this behavior. It's nil by default because
983 other Emacs modes don't work this way."
984 :type 'boolean
985 :group 'js2-mode)
986
987 (defcustom js2-mode-indent-ignore-first-tab nil
988 "If non-nil, ignore first TAB keypress if we look indented properly.
989 It's fairly common for users to navigate to an already-indented line
990 and press TAB for reassurance that it's been indented. For this class
991 of users, we want the first TAB press on a line to be ignored if the
992 line is already indented to one of the precomputed alternatives.
993
994 This behavior is only partly implemented. If you TAB-indent a line,
995 navigate to another line, and then navigate back, it fails to clear
996 the last-indented variable, so it thinks you've already hit TAB once,
997 and performs the indent. A full solution would involve getting on the
998 point-motion hooks for the entire buffer. If we come across another
999 use cases that requires watching point motion, I'll consider doing it.
1000
1001 If you set this variable to nil, then the TAB key will always change
1002 the indentation of the current line, if more than one alternative
1003 indentation spot exists."
1004 :type 'boolean
1005 :group 'js2-mode)
1006
1007 (defvar js2-indent-hook nil
1008 "A hook for user-defined indentation rules.
1009
1010 Functions on this hook should expect two arguments: (LIST INDEX)
1011 The LIST argument is the list of computed indentation points for
1012 the current line. INDEX is the list index of the indentation point
1013 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1014 indent function is not going to change the current line indentation.
1015
1016 If a hook function on this list returns a non-nil value, then
1017 `js2-bounce-indent' assumes the hook function has performed its own
1018 indentation, and will do nothing. If all hook functions on the list
1019 return nil, then `js2-bounce-indent' will use its computed indentation
1020 and reindent the line.
1021
1022 When hook functions on this hook list are called, the variable
1023 `js2-mode-ast' may or may not be set, depending on whether the
1024 parse tree is available. If the variable is nil, you can pass a
1025 callback to `js2-mode-wait-for-parse', and your callback will be
1026 called after the new parse tree is built. This can take some time
1027 in large files.")
1028
1029 (defface js2-warning-face
1030 `((((class color) (background light))
1031 (:underline "orange"))
1032 (((class color) (background dark))
1033 (:underline "orange"))
1034 (t (:underline t)))
1035 "Face for JavaScript warnings."
1036 :group 'js2-mode)
1037
1038 (defface js2-error-face
1039 `((((class color) (background light))
1040 (:foreground "red"))
1041 (((class color) (background dark))
1042 (:foreground "red"))
1043 (t (:foreground "red")))
1044 "Face for JavaScript errors."
1045 :group 'js2-mode)
1046
1047 (defface js2-jsdoc-tag-face
1048 '((t :foreground "SlateGray"))
1049 "Face used to highlight @whatever tags in jsdoc comments."
1050 :group 'js2-mode)
1051
1052 (defface js2-jsdoc-type-face
1053 '((t :foreground "SteelBlue"))
1054 "Face used to highlight {FooBar} types in jsdoc comments."
1055 :group 'js2-mode)
1056
1057 (defface js2-jsdoc-value-face
1058 '((t :foreground "PeachPuff3"))
1059 "Face used to highlight tag values in jsdoc comments."
1060 :group 'js2-mode)
1061
1062 (defface js2-function-param-face
1063 '((t :foreground "SeaGreen"))
1064 "Face used to highlight function parameters in javascript."
1065 :group 'js2-mode)
1066
1067 (defface js2-instance-member-face
1068 '((t :foreground "DarkOrchid"))
1069 "Face used to highlight instance variables in javascript.
1070 Not currently used."
1071 :group 'js2-mode)
1072
1073 (defface js2-private-member-face
1074 '((t :foreground "PeachPuff3"))
1075 "Face used to highlight calls to private methods in javascript.
1076 Not currently used."
1077 :group 'js2-mode)
1078
1079 (defface js2-private-function-call-face
1080 '((t :foreground "goldenrod"))
1081 "Face used to highlight calls to private functions in javascript.
1082 Not currently used."
1083 :group 'js2-mode)
1084
1085 (defface js2-jsdoc-html-tag-name-face
1086 (if js2-emacs22
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "rosybrown"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "yellow"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "magenta")))
1093 '((((type tty pc) (class color) (background light))
1094 (:foreground "magenta"))
1095 (((type tty pc) (class color) (background dark))
1096 (:foreground "yellow"))
1097 (t (:foreground "RosyBrown"))))
1098 "Face used to highlight jsdoc html tag names"
1099 :group 'js2-mode)
1100
1101 (defface js2-jsdoc-html-tag-delimiter-face
1102 (if js2-emacs22
1103 '((((class color) (min-colors 88) (background light))
1104 (:foreground "dark khaki"))
1105 (((class color) (min-colors 8) (background dark))
1106 (:foreground "green"))
1107 (((class color) (min-colors 8) (background light))
1108 (:foreground "green")))
1109 '((((type tty pc) (class color) (background light))
1110 (:foreground "green"))
1111 (((type tty pc) (class color) (background dark))
1112 (:foreground "green"))
1113 (t (:foreground "dark khaki"))))
1114 "Face used to highlight brackets in jsdoc html tags."
1115 :group 'js2-mode)
1116
1117 (defface js2-magic-paren-face
1118 '((t :underline t))
1119 "Face used to color parens that will be auto-overwritten."
1120 :group 'js2-mode)
1121
1122 (defcustom js2-post-parse-callbacks nil
1123 "A list of callback functions invoked after parsing finishes.
1124 Currently, the main use for this function is to add synthetic
1125 declarations to `js2-recorded-assignments', which see."
1126 :type 'list
1127 :group 'js2-mode)
1128
1129 (defface js2-external-variable-face
1130 '((t :foreground "orange"))
1131 "Face used to highlight assignments to undeclared variables.
1132 An undeclared variable is any variable not declared with var or let
1133 in the current scope or any lexically enclosing scope. If you assign
1134 to such a variable, then you are either expecting it to originate from
1135 another file, or you've got a potential bug."
1136 :group 'js2-mode)
1137
1138 (defcustom js2-highlight-external-variables t
1139 "Non-nil to higlight assignments to undeclared variables."
1140 :type 'boolean
1141 :group 'js2-mode)
1142
1143 (defcustom js2-auto-insert-catch-block t
1144 "Non-nil to insert matching catch block on open-curly after `try'."
1145 :type 'boolean
1146 :group 'js2-mode)
1147
1148 (defvar js2-mode-map
1149 (let ((map (make-sparse-keymap))
1150 keys)
1151 (define-key map [mouse-1] #'js2-mode-show-node)
1152 (define-key map (kbd "C-m") #'js2-enter-key)
1153 (when js2-rebind-eol-bol-keys
1154 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1155 (define-key map (kbd "C-e") #'js2-end-of-line))
1156 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1157 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1158 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1159 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1160 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1161 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1162 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1163 (define-key map (kbd "C-c C-`") #'js2-next-error)
1164 ;; also define user's preference for next-error, if available
1165 (if (setq keys (where-is-internal #'next-error))
1166 (define-key map (car keys) #'js2-next-error))
1167 (define-key map (or (car (where-is-internal #'mark-defun))
1168 (kbd "M-C-h"))
1169 #'js2-mark-defun)
1170 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1171 (kbd "C-x nd"))
1172 #'js2-narrow-to-defun)
1173 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1174 (when js2-auto-indent-p
1175 (mapc (lambda (key)
1176 (define-key map key #'js2-insert-and-indent))
1177 js2-electric-keys))
1178
1179 (define-key map [menu-bar javascript]
1180 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1181
1182 (define-key map [menu-bar javascript customize-js2-mode]
1183 '(menu-item "Customize js2-mode" js2-mode-customize
1184 :help "Customize the behavior of this mode"))
1185
1186 (define-key map [menu-bar javascript js2-force-refresh]
1187 '(menu-item "Force buffer refresh" js2-mode-reset
1188 :help "Re-parse the buffer from scratch"))
1189
1190 (define-key map [menu-bar javascript separator-2]
1191 '("--"))
1192
1193 (define-key map [menu-bar javascript next-error]
1194 '(menu-item "Next warning or error" js2-next-error
1195 :enabled (and js2-mode-ast
1196 (or (js2-ast-root-errors js2-mode-ast)
1197 (js2-ast-root-warnings js2-mode-ast)))
1198 :help "Move to next warning or error"))
1199
1200 (define-key map [menu-bar javascript display-errors]
1201 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1202 :visible (not js2-mode-show-parse-errors)
1203 :help "Turn on display of warnings and errors"))
1204
1205 (define-key map [menu-bar javascript hide-errors]
1206 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1207 :visible js2-mode-show-parse-errors
1208 :help "Turn off display of warnings and errors"))
1209
1210 (define-key map [menu-bar javascript separator-1]
1211 '("--"))
1212
1213 (define-key map [menu-bar javascript js2-toggle-function]
1214 '(menu-item "Show/collapse element" js2-mode-toggle-element
1215 :help "Hide or show function body or comment"))
1216
1217 (define-key map [menu-bar javascript show-comments]
1218 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1219 :visible js2-mode-comments-hidden
1220 :help "Expand all hidden block comments"))
1221
1222 (define-key map [menu-bar javascript hide-comments]
1223 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1224 :visible (not js2-mode-comments-hidden)
1225 :help "Show block comments as /*...*/"))
1226
1227 (define-key map [menu-bar javascript show-all-functions]
1228 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1229 :visible js2-mode-functions-hidden
1230 :help "Expand all hidden function bodies"))
1231
1232 (define-key map [menu-bar javascript hide-all-functions]
1233 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1234 :visible (not js2-mode-functions-hidden)
1235 :help "Show {...} for all top-level function bodies"))
1236
1237 map)
1238 "Keymap used in `js2-mode' buffers.")
1239
1240 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1241
1242 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1243 "Matches a //-comment line. Must be first non-whitespace on line.
1244 First match-group is the leading whitespace.")
1245
1246 (defvar js2-mode-hook nil)
1247
1248 (js2-deflocal js2-mode-ast nil "Private variable.")
1249 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1250 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1251 (js2-deflocal js2-mode-parsing nil "Private variable.")
1252 (js2-deflocal js2-mode-node-overlay nil)
1253
1254 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1255 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1256
1257 (js2-deflocal js2-mode-fontifications nil "Private variable")
1258 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1259 (js2-deflocal js2-imenu-recorder nil "Private variable")
1260 (js2-deflocal js2-imenu-function-map nil "Private variable")
1261
1262 (defvar js2-paragraph-start
1263 "\\(@[a-zA-Z]+\\>\\|$\\)")
1264
1265 ;; Note that we also set a 'c-in-sws text property in html comments,
1266 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1267 (defvar js2-syntactic-ws-start
1268 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1269
1270 (defvar js2-syntactic-ws-end
1271 "\\s \\|[\n\r/]\\|\\s!")
1272
1273 (defvar js2-syntactic-eol
1274 (concat "\\s *\\(/\\*[^*\n\r]*"
1275 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1276 "\\*+/\\s *\\)*"
1277 "\\(//\\|/\\*[^*\n\r]*"
1278 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1279 "\\|\\\\$\\|$\\)")
1280 "Copied from `java-mode'. Needed for some cc-engine functions.")
1281
1282 (defvar js2-comment-prefix-regexp
1283 "//+\\|\\**")
1284
1285 (defvar js2-comment-start-skip
1286 "\\(//+\\|/\\*+\\)\\s *")
1287
1288 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1289 "Non-nil to emit status messages during parsing.")
1290
1291 (defvar js2-mode-functions-hidden nil "private variable")
1292 (defvar js2-mode-comments-hidden nil "private variable")
1293
1294 (defvar js2-mode-syntax-table
1295 (let ((table (make-syntax-table)))
1296 (c-populate-syntax-table table)
1297 table)
1298 "Syntax table used in js2-mode buffers.")
1299
1300 (defvar js2-mode-abbrev-table nil
1301 "Abbrev table in use in `js2-mode' buffers.")
1302 (define-abbrev-table 'js2-mode-abbrev-table ())
1303
1304 (defvar js2-mode-pending-parse-callbacks nil
1305 "List of functions waiting to be notified that parse is finished.")
1306
1307 (defvar js2-mode-last-indented-line -1)
1308
1309 ;;; Localizable error and warning messages
1310
1311 ;; Messages are copied from Rhino's Messages.properties.
1312 ;; Many of the Java-specific messages have been elided.
1313 ;; Add any js2-specific ones at the end, so we can keep
1314 ;; this file synced with changes to Rhino's.
1315
1316 (defvar js2-message-table
1317 (make-hash-table :test 'equal :size 250)
1318 "Contains localized messages for js2-mode.")
1319
1320 ;; TODO(stevey): construct this table at compile-time.
1321 (defmacro js2-msg (key &rest strings)
1322 `(puthash ,key (funcall #'concat ,@strings)
1323 js2-message-table))
1324
1325 (defun js2-get-msg (msg-key)
1326 "Look up a localized message.
1327 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1328 the correct number of ARGS must be provided."
1329 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1330 (args (if (listp msg-key) (cdr msg-key)))
1331 (msg (gethash key js2-message-table)))
1332 (if msg
1333 (apply #'format msg args)
1334 key))) ; default to showing the key
1335
1336 (js2-msg "msg.dup.parms"
1337 "Duplicate parameter name '%s'.")
1338
1339 (js2-msg "msg.too.big.jump"
1340 "Program too complex: jump offset too big.")
1341
1342 (js2-msg "msg.too.big.index"
1343 "Program too complex: internal index exceeds 64K limit.")
1344
1345 (js2-msg "msg.while.compiling.fn"
1346 "Encountered code generation error while compiling function '%s': %s")
1347
1348 (js2-msg "msg.while.compiling.script"
1349 "Encountered code generation error while compiling script: %s")
1350
1351 ;; Context
1352 (js2-msg "msg.ctor.not.found"
1353 "Constructor for '%s' not found.")
1354
1355 (js2-msg "msg.not.ctor"
1356 "'%s' is not a constructor.")
1357
1358 ;; FunctionObject
1359 (js2-msg "msg.varargs.ctor"
1360 "Method or constructor '%s' must be static "
1361 "with the signature (Context cx, Object[] args, "
1362 "Function ctorObj, boolean inNewExpr) "
1363 "to define a variable arguments constructor.")
1364
1365 (js2-msg "msg.varargs.fun"
1366 "Method '%s' must be static with the signature "
1367 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1368 "to define a variable arguments function.")
1369
1370 (js2-msg "msg.incompat.call"
1371 "Method '%s' called on incompatible object.")
1372
1373 (js2-msg "msg.bad.parms"
1374 "Unsupported parameter type '%s' in method '%s'.")
1375
1376 (js2-msg "msg.bad.method.return"
1377 "Unsupported return type '%s' in method '%s'.")
1378
1379 (js2-msg "msg.bad.ctor.return"
1380 "Construction of objects of type '%s' is not supported.")
1381
1382 (js2-msg "msg.no.overload"
1383 "Method '%s' occurs multiple times in class '%s'.")
1384
1385 (js2-msg "msg.method.not.found"
1386 "Method '%s' not found in '%s'.")
1387
1388 ;; IRFactory
1389
1390 (js2-msg "msg.bad.for.in.lhs"
1391 "Invalid left-hand side of for..in loop.")
1392
1393 (js2-msg "msg.mult.index"
1394 "Only one variable allowed in for..in loop.")
1395
1396 (js2-msg "msg.bad.for.in.destruct"
1397 "Left hand side of for..in loop must be an array of "
1398 "length 2 to accept key/value pair.")
1399
1400 (js2-msg "msg.cant.convert"
1401 "Can't convert to type '%s'.")
1402
1403 (js2-msg "msg.bad.assign.left"
1404 "Invalid assignment left-hand side.")
1405
1406 (js2-msg "msg.bad.decr"
1407 "Invalid decerement operand.")
1408
1409 (js2-msg "msg.bad.incr"
1410 "Invalid increment operand.")
1411
1412 (js2-msg "msg.bad.yield"
1413 "yield must be in a function.")
1414
1415 (js2-msg "msg.yield.parenthesized"
1416 "yield expression must be parenthesized.")
1417
1418 ;; NativeGlobal
1419 (js2-msg "msg.cant.call.indirect"
1420 "Function '%s' must be called directly, and not by way of a "
1421 "function of another name.")
1422
1423 (js2-msg "msg.eval.nonstring"
1424 "Calling eval() with anything other than a primitive "
1425 "string value will simply return the value. "
1426 "Is this what you intended?")
1427
1428 (js2-msg "msg.eval.nonstring.strict"
1429 "Calling eval() with anything other than a primitive "
1430 "string value is not allowed in strict mode.")
1431
1432 (js2-msg "msg.bad.destruct.op"
1433 "Invalid destructuring assignment operator")
1434
1435 ;; NativeCall
1436 (js2-msg "msg.only.from.new"
1437 "'%s' may only be invoked from a `new' expression.")
1438
1439 (js2-msg "msg.deprec.ctor"
1440 "The '%s' constructor is deprecated.")
1441
1442 ;; NativeFunction
1443 (js2-msg "msg.no.function.ref.found"
1444 "no source found to decompile function reference %s")
1445
1446 (js2-msg "msg.arg.isnt.array"
1447 "second argument to Function.prototype.apply must be an array")
1448
1449 ;; NativeGlobal
1450 (js2-msg "msg.bad.esc.mask"
1451 "invalid string escape mask")
1452
1453 ;; NativeRegExp
1454 (js2-msg "msg.bad.quant"
1455 "Invalid quantifier %s")
1456
1457 (js2-msg "msg.overlarge.backref"
1458 "Overly large back reference %s")
1459
1460 (js2-msg "msg.overlarge.min"
1461 "Overly large minimum %s")
1462
1463 (js2-msg "msg.overlarge.max"
1464 "Overly large maximum %s")
1465
1466 (js2-msg "msg.zero.quant"
1467 "Zero quantifier %s")
1468
1469 (js2-msg "msg.max.lt.min"
1470 "Maximum %s less than minimum")
1471
1472 (js2-msg "msg.unterm.quant"
1473 "Unterminated quantifier %s")
1474
1475 (js2-msg "msg.unterm.paren"
1476 "Unterminated parenthetical %s")
1477
1478 (js2-msg "msg.unterm.class"
1479 "Unterminated character class %s")
1480
1481 (js2-msg "msg.bad.range"
1482 "Invalid range in character class.")
1483
1484 (js2-msg "msg.trail.backslash"
1485 "Trailing \\ in regular expression.")
1486
1487 (js2-msg "msg.re.unmatched.right.paren"
1488 "unmatched ) in regular expression.")
1489
1490 (js2-msg "msg.no.regexp"
1491 "Regular expressions are not available.")
1492
1493 (js2-msg "msg.bad.backref"
1494 "back-reference exceeds number of capturing parentheses.")
1495
1496 (js2-msg "msg.bad.regexp.compile"
1497 "Only one argument may be specified if the first "
1498 "argument to RegExp.prototype.compile is a RegExp object.")
1499
1500 ;; Parser
1501 (js2-msg "msg.got.syntax.errors"
1502 "Compilation produced %s syntax errors.")
1503
1504 (js2-msg "msg.var.redecl"
1505 "TypeError: redeclaration of var %s.")
1506
1507 (js2-msg "msg.const.redecl"
1508 "TypeError: redeclaration of const %s.")
1509
1510 (js2-msg "msg.let.redecl"
1511 "TypeError: redeclaration of variable %s.")
1512
1513 (js2-msg "msg.parm.redecl"
1514 "TypeError: redeclaration of formal parameter %s.")
1515
1516 (js2-msg "msg.fn.redecl"
1517 "TypeError: redeclaration of function %s.")
1518
1519 (js2-msg "msg.let.decl.not.in.block"
1520 "SyntaxError: let declaration not directly within block")
1521
1522 ;; NodeTransformer
1523 (js2-msg "msg.dup.label"
1524 "duplicated label")
1525
1526 (js2-msg "msg.undef.label"
1527 "undefined label")
1528
1529 (js2-msg "msg.bad.break"
1530 "unlabelled break must be inside loop or switch")
1531
1532 (js2-msg "msg.continue.outside"
1533 "continue must be inside loop")
1534
1535 (js2-msg "msg.continue.nonloop"
1536 "continue can only use labels of iteration statements")
1537
1538 (js2-msg "msg.bad.throw.eol"
1539 "Line terminator is not allowed between the throw "
1540 "keyword and throw expression.")
1541
1542 (js2-msg "msg.no.paren.parms"
1543 "missing ( before function parameters.")
1544
1545 (js2-msg "msg.no.parm"
1546 "missing formal parameter")
1547
1548 (js2-msg "msg.no.paren.after.parms"
1549 "missing ) after formal parameters")
1550
1551 (js2-msg "msg.no.brace.body"
1552 "missing '{' before function body")
1553
1554 (js2-msg "msg.no.brace.after.body"
1555 "missing } after function body")
1556
1557 (js2-msg "msg.no.paren.cond"
1558 "missing ( before condition")
1559
1560 (js2-msg "msg.no.paren.after.cond"
1561 "missing ) after condition")
1562
1563 (js2-msg "msg.no.semi.stmt"
1564 "missing ; before statement")
1565
1566 (js2-msg "msg.missing.semi"
1567 "missing ; after statement")
1568
1569 (js2-msg "msg.no.name.after.dot"
1570 "missing name after . operator")
1571
1572 (js2-msg "msg.no.name.after.coloncolon"
1573 "missing name after :: operator")
1574
1575 (js2-msg "msg.no.name.after.dotdot"
1576 "missing name after .. operator")
1577
1578 (js2-msg "msg.no.name.after.xmlAttr"
1579 "missing name after .@")
1580
1581 (js2-msg "msg.no.bracket.index"
1582 "missing ] in index expression")
1583
1584 (js2-msg "msg.no.paren.switch"
1585 "missing ( before switch expression")
1586
1587 (js2-msg "msg.no.paren.after.switch"
1588 "missing ) after switch expression")
1589
1590 (js2-msg "msg.no.brace.switch"
1591 "missing '{' before switch body")
1592
1593 (js2-msg "msg.bad.switch"
1594 "invalid switch statement")
1595
1596 (js2-msg "msg.no.colon.case"
1597 "missing : after case expression")
1598
1599 (js2-msg "msg.double.switch.default"
1600 "double default label in the switch statement")
1601
1602 (js2-msg "msg.no.while.do"
1603 "missing while after do-loop body")
1604
1605 (js2-msg "msg.no.paren.for"
1606 "missing ( after for")
1607
1608 (js2-msg "msg.no.semi.for"
1609 "missing ; after for-loop initializer")
1610
1611 (js2-msg "msg.no.semi.for.cond"
1612 "missing ; after for-loop condition")
1613
1614 (js2-msg "msg.in.after.for.name"
1615 "missing in after for")
1616
1617 (js2-msg "msg.no.paren.for.ctrl"
1618 "missing ) after for-loop control")
1619
1620 (js2-msg "msg.no.paren.with"
1621 "missing ( before with-statement object")
1622
1623 (js2-msg "msg.no.paren.after.with"
1624 "missing ) after with-statement object")
1625
1626 (js2-msg "msg.no.paren.after.let"
1627 "missing ( after let")
1628
1629 (js2-msg "msg.no.paren.let"
1630 "missing ) after variable list")
1631
1632 (js2-msg "msg.no.curly.let"
1633 "missing } after let statement")
1634
1635 (js2-msg "msg.bad.return"
1636 "invalid return")
1637
1638 (js2-msg "msg.no.brace.block"
1639 "missing } in compound statement")
1640
1641 (js2-msg "msg.bad.label"
1642 "invalid label")
1643
1644 (js2-msg "msg.bad.var"
1645 "missing variable name")
1646
1647 (js2-msg "msg.bad.var.init"
1648 "invalid variable initialization")
1649
1650 (js2-msg "msg.no.colon.cond"
1651 "missing : in conditional expression")
1652
1653 (js2-msg "msg.no.paren.arg"
1654 "missing ) after argument list")
1655
1656 (js2-msg "msg.no.bracket.arg"
1657 "missing ] after element list")
1658
1659 (js2-msg "msg.bad.prop"
1660 "invalid property id")
1661
1662 (js2-msg "msg.no.colon.prop"
1663 "missing : after property id")
1664
1665 (js2-msg "msg.no.brace.prop"
1666 "missing } after property list")
1667
1668 (js2-msg "msg.no.paren"
1669 "missing ) in parenthetical")
1670
1671 (js2-msg "msg.reserved.id"
1672 "identifier is a reserved word")
1673
1674 (js2-msg "msg.no.paren.catch"
1675 "missing ( before catch-block condition")
1676
1677 (js2-msg "msg.bad.catchcond"
1678 "invalid catch block condition")
1679
1680 (js2-msg "msg.catch.unreachable"
1681 "any catch clauses following an unqualified catch are unreachable")
1682
1683 (js2-msg "msg.no.brace.try"
1684 "missing '{' before try block")
1685
1686 (js2-msg "msg.no.brace.catchblock"
1687 "missing '{' before catch-block body")
1688
1689 (js2-msg "msg.try.no.catchfinally"
1690 "'try' without 'catch' or 'finally'")
1691
1692 (js2-msg "msg.no.return.value"
1693 "function %s does not always return a value")
1694
1695 (js2-msg "msg.anon.no.return.value"
1696 "anonymous function does not always return a value")
1697
1698 (js2-msg "msg.return.inconsistent"
1699 "return statement is inconsistent with previous usage")
1700
1701 (js2-msg "msg.generator.returns"
1702 "TypeError: generator function '%s' returns a value")
1703
1704 (js2-msg "msg.anon.generator.returns"
1705 "TypeError: anonymous generator function returns a value")
1706
1707 (js2-msg "msg.syntax"
1708 "syntax error")
1709
1710 (js2-msg "msg.unexpected.eof"
1711 "Unexpected end of file")
1712
1713 (js2-msg "msg.XML.bad.form"
1714 "illegally formed XML syntax")
1715
1716 (js2-msg "msg.XML.not.available"
1717 "XML runtime not available")
1718
1719 (js2-msg "msg.too.deep.parser.recursion"
1720 "Too deep recursion while parsing")
1721
1722 (js2-msg "msg.no.side.effects"
1723 "Code has no side effects")
1724
1725 (js2-msg "msg.extra.trailing.comma"
1726 "Trailing comma is not legal in an ECMA-262 object initializer")
1727
1728 (js2-msg "msg.array.trailing.comma"
1729 "Trailing comma yields different behavior across browsers")
1730
1731 (js2-msg "msg.equal.as.assign"
1732 (concat "Test for equality (==) mistyped as assignment (=)?"
1733 " (parenthesize to suppress warning)"))
1734
1735 (js2-msg "msg.var.hides.arg"
1736 "Variable %s hides argument")
1737
1738 (js2-msg "msg.destruct.assign.no.init"
1739 "Missing = in destructuring declaration")
1740
1741 ;; ScriptRuntime
1742 (js2-msg "msg.no.properties"
1743 "%s has no properties.")
1744
1745 (js2-msg "msg.invalid.iterator"
1746 "Invalid iterator value")
1747
1748 (js2-msg "msg.iterator.primitive"
1749 "__iterator__ returned a primitive value")
1750
1751 (js2-msg "msg.assn.create.strict"
1752 "Assignment to undeclared variable %s")
1753
1754 (js2-msg "msg.ref.undefined.prop"
1755 "Reference to undefined property '%s'")
1756
1757 (js2-msg "msg.prop.not.found"
1758 "Property %s not found.")
1759
1760 (js2-msg "msg.invalid.type"
1761 "Invalid JavaScript value of type %s")
1762
1763 (js2-msg "msg.primitive.expected"
1764 "Primitive type expected (had %s instead)")
1765
1766 (js2-msg "msg.namespace.expected"
1767 "Namespace object expected to left of :: (found %s instead)")
1768
1769 (js2-msg "msg.null.to.object"
1770 "Cannot convert null to an object.")
1771
1772 (js2-msg "msg.undef.to.object"
1773 "Cannot convert undefined to an object.")
1774
1775 (js2-msg "msg.cyclic.value"
1776 "Cyclic %s value not allowed.")
1777
1778 (js2-msg "msg.is.not.defined"
1779 "'%s' is not defined.")
1780
1781 (js2-msg "msg.undef.prop.read"
1782 "Cannot read property '%s' from %s")
1783
1784 (js2-msg "msg.undef.prop.write"
1785 "Cannot set property '%s' of %s to '%s'")
1786
1787 (js2-msg "msg.undef.prop.delete"
1788 "Cannot delete property '%s' of %s")
1789
1790 (js2-msg "msg.undef.method.call"
1791 "Cannot call method '%s' of %s")
1792
1793 (js2-msg "msg.undef.with"
1794 "Cannot apply 'with' to %s")
1795
1796 (js2-msg "msg.isnt.function"
1797 "%s is not a function, it is %s.")
1798
1799 (js2-msg "msg.isnt.function.in"
1800 "Cannot call property %s in object %s. "
1801 "It is not a function, it is '%s'.")
1802
1803 (js2-msg "msg.function.not.found"
1804 "Cannot find function %s.")
1805
1806 (js2-msg "msg.function.not.found.in"
1807 "Cannot find function %s in object %s.")
1808
1809 (js2-msg "msg.isnt.xml.object"
1810 "%s is not an xml object.")
1811
1812 (js2-msg "msg.no.ref.to.get"
1813 "%s is not a reference to read reference value.")
1814
1815 (js2-msg "msg.no.ref.to.set"
1816 "%s is not a reference to set reference value to %s.")
1817
1818 (js2-msg "msg.no.ref.from.function"
1819 "Function %s can not be used as the left-hand "
1820 "side of assignment or as an operand of ++ or -- operator.")
1821
1822 (js2-msg "msg.bad.default.value"
1823 "Object's getDefaultValue() method returned an object.")
1824
1825 (js2-msg "msg.instanceof.not.object"
1826 "Can't use instanceof on a non-object.")
1827
1828 (js2-msg "msg.instanceof.bad.prototype"
1829 "'prototype' property of %s is not an object.")
1830
1831 (js2-msg "msg.bad.radix"
1832 "illegal radix %s.")
1833
1834 ;; ScriptableObject
1835 (js2-msg "msg.default.value"
1836 "Cannot find default value for object.")
1837
1838 (js2-msg "msg.zero.arg.ctor"
1839 "Cannot load class '%s' which has no zero-parameter constructor.")
1840
1841 (js2-msg "msg.ctor.multiple.parms"
1842 "Can't define constructor or class %s since more than "
1843 "one constructor has multiple parameters.")
1844
1845 (js2-msg "msg.extend.scriptable"
1846 "%s must extend ScriptableObject in order to define property %s.")
1847
1848 (js2-msg "msg.bad.getter.parms"
1849 "In order to define a property, getter %s must have zero "
1850 "parameters or a single ScriptableObject parameter.")
1851
1852 (js2-msg "msg.obj.getter.parms"
1853 "Expected static or delegated getter %s to take "
1854 "a ScriptableObject parameter.")
1855
1856 (js2-msg "msg.getter.static"
1857 "Getter and setter must both be static or neither be static.")
1858
1859 (js2-msg "msg.setter.return"
1860 "Setter must have void return type: %s")
1861
1862 (js2-msg "msg.setter2.parms"
1863 "Two-parameter setter must take a ScriptableObject as "
1864 "its first parameter.")
1865
1866 (js2-msg "msg.setter1.parms"
1867 "Expected single parameter setter for %s")
1868
1869 (js2-msg "msg.setter2.expected"
1870 "Expected static or delegated setter %s to take two parameters.")
1871
1872 (js2-msg "msg.setter.parms"
1873 "Expected either one or two parameters for setter.")
1874
1875 (js2-msg "msg.setter.bad.type"
1876 "Unsupported parameter type '%s' in setter '%s'.")
1877
1878 (js2-msg "msg.add.sealed"
1879 "Cannot add a property to a sealed object: %s.")
1880
1881 (js2-msg "msg.remove.sealed"
1882 "Cannot remove a property from a sealed object: %s.")
1883
1884 (js2-msg "msg.modify.sealed"
1885 "Cannot modify a property of a sealed object: %s.")
1886
1887 (js2-msg "msg.modify.readonly"
1888 "Cannot modify readonly property: %s.")
1889
1890 ;; TokenStream
1891 (js2-msg "msg.missing.exponent"
1892 "missing exponent")
1893
1894 (js2-msg "msg.caught.nfe"
1895 "number format error")
1896
1897 (js2-msg "msg.unterminated.string.lit"
1898 "unterminated string literal")
1899
1900 (js2-msg "msg.unterminated.comment"
1901 "unterminated comment")
1902
1903 (js2-msg "msg.unterminated.re.lit"
1904 "unterminated regular expression literal")
1905
1906 (js2-msg "msg.invalid.re.flag"
1907 "invalid flag after regular expression")
1908
1909 (js2-msg "msg.no.re.input.for"
1910 "no input for %s")
1911
1912 (js2-msg "msg.illegal.character"
1913 "illegal character")
1914
1915 (js2-msg "msg.invalid.escape"
1916 "invalid Unicode escape sequence")
1917
1918 (js2-msg "msg.bad.namespace"
1919 "not a valid default namespace statement. "
1920 "Syntax is: default xml namespace = EXPRESSION;")
1921
1922 ;; TokensStream warnings
1923 (js2-msg "msg.bad.octal.literal"
1924 "illegal octal literal digit %s; "
1925 "interpreting it as a decimal digit")
1926
1927 (js2-msg "msg.reserved.keyword"
1928 "illegal usage of future reserved keyword %s; "
1929 "interpreting it as ordinary identifier")
1930
1931 (js2-msg "msg.script.is.not.constructor"
1932 "Script objects are not constructors.")
1933
1934 ;; Arrays
1935 (js2-msg "msg.arraylength.bad"
1936 "Inappropriate array length.")
1937
1938 ;; Arrays
1939 (js2-msg "msg.arraylength.too.big"
1940 "Array length %s exceeds supported capacity limit.")
1941
1942 ;; URI
1943 (js2-msg "msg.bad.uri"
1944 "Malformed URI sequence.")
1945
1946 ;; Number
1947 (js2-msg "msg.bad.precision"
1948 "Precision %s out of range.")
1949
1950 ;; NativeGenerator
1951 (js2-msg "msg.send.newborn"
1952 "Attempt to send value to newborn generator")
1953
1954 (js2-msg "msg.already.exec.gen"
1955 "Already executing generator")
1956
1957 (js2-msg "msg.StopIteration.invalid"
1958 "StopIteration may not be changed to an arbitrary object.")
1959
1960 ;; Interpreter
1961 (js2-msg "msg.yield.closing"
1962 "Yield from closing generator")
1963
1964 ;;; Utilities
1965
1966 (defun js2-delete-if (predicate list)
1967 "Remove all items satisfying PREDICATE in LIST."
1968 (loop for item in list
1969 if (not (funcall predicate item))
1970 collect item))
1971
1972 (defun js2-position (element list)
1973 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1974 Returns nil if element is not found in the list."
1975 (let ((count 0)
1976 found)
1977 (while (and list (not found))
1978 (if (eq element (car list))
1979 (setq found t)
1980 (setq count (1+ count)
1981 list (cdr list))))
1982 (if found count)))
1983
1984 (defun js2-find-if (predicate list)
1985 "Find first item satisfying PREDICATE in LIST."
1986 (let (result)
1987 (while (and list (not result))
1988 (if (funcall predicate (car list))
1989 (setq result (car list)))
1990 (setq list (cdr list)))
1991 result))
1992
1993 (defmacro js2-time (form)
1994 "Evaluate FORM, discard result, and return elapsed time in sec"
1995 (declare (debug t))
1996 (let ((beg (make-symbol "--js2-time-beg--"))
1997 (delta (make-symbol "--js2-time-end--")))
1998 `(let ((,beg (current-time))
1999 ,delta)
2000 ,form
2001 (/ (truncate (* (- (float-time (current-time))
2002 (float-time ,beg)))
2003 10000)
2004 10000.0))))
2005
2006 (defsubst js2-same-line (pos)
2007 "Return t if POS is on the same line as current point."
2008 (and (>= pos (point-at-bol))
2009 (<= pos (point-at-eol))))
2010
2011 (defsubst js2-same-line-2 (p1 p2)
2012 "Return t if p1 is on the same line as p2."
2013 (save-excursion
2014 (goto-char p1)
2015 (js2-same-line p2)))
2016
2017 (defun js2-code-bug ()
2018 "Signal an error when we encounter an unexpected code path."
2019 (error "failed assertion"))
2020
2021 ;; I'd like to associate errors with nodes, but for now the
2022 ;; easiest thing to do is get the context info from the last token.
2023 (defsubst js2-record-parse-error (msg &optional arg pos len)
2024 (push (list (list msg arg)
2025 (or pos js2-token-beg)
2026 (or len (- js2-token-end js2-token-beg)))
2027 js2-parsed-errors))
2028
2029 (defsubst js2-report-error (msg &optional msg-arg pos len)
2030 "Signal a syntax error or record a parse error."
2031 (if js2-recover-from-parse-errors
2032 (js2-record-parse-error msg msg-arg pos len)
2033 (signal 'js2-syntax-error
2034 (list msg
2035 js2-ts-lineno
2036 (save-excursion
2037 (goto-char js2-ts-cursor)
2038 (current-column))
2039 js2-ts-hit-eof))))
2040
2041 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2042 (if js2-compiler-report-warning-as-error
2043 (js2-report-error msg msg-arg pos len)
2044 (push (list (list msg msg-arg)
2045 (or pos js2-token-beg)
2046 (or len (- js2-token-end js2-token-beg)))
2047 js2-parsed-warnings)))
2048
2049 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2050 (if js2-compiler-strict-mode
2051 (js2-report-warning msg-id msg-arg beg
2052 (and beg end (- end beg)))))
2053
2054 (put 'js2-syntax-error 'error-conditions
2055 '(error syntax-error js2-syntax-error))
2056 (put 'js2-syntax-error 'error-message "Syntax error")
2057
2058 (put 'js2-parse-error 'error-conditions
2059 '(error parse-error js2-parse-error))
2060 (put 'js2-parse-error 'error-message "Parse error")
2061
2062 (defmacro js2-clear-flag (flags flag)
2063 `(setq ,flags (logand ,flags (lognot ,flag))))
2064
2065 (defmacro js2-set-flag (flags flag)
2066 "Logical-or FLAG into FLAGS."
2067 `(setq ,flags (logior ,flags ,flag)))
2068
2069 (defsubst js2-flag-set-p (flags flag)
2070 (/= 0 (logand flags flag)))
2071
2072 (defsubst js2-flag-not-set-p (flags flag)
2073 (zerop (logand flags flag)))
2074
2075 ;; Stolen shamelessly from James Clark's nxml-mode.
2076 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2077 "Evaluate BODY without any text property changes modifying the buffer.
2078 Any text properties changes happen as usual but the changes are not treated as
2079 modifications to the buffer."
2080 (declare (indent 0) (debug t))
2081 (let ((modified (make-symbol "modified")))
2082 `(let ((,modified (buffer-modified-p))
2083 (inhibit-read-only t)
2084 (inhibit-modification-hooks t)
2085 (buffer-undo-list t)
2086 (deactivate-mark nil)
2087 ;; Apparently these avoid file locking problems.
2088 (buffer-file-name nil)
2089 (buffer-file-truename nil))
2090 (unwind-protect
2091 (progn ,@body)
2092 (unless ,modified
2093 (restore-buffer-modified-p nil))))))
2094
2095 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2096 "Evaluate BODY with the _ character set to be word-syntax."
2097 (declare (indent 0) (debug t))
2098 (let ((old-syntax (make-symbol "old-syntax")))
2099 `(let ((,old-syntax (string (char-syntax ?_))))
2100 (unwind-protect
2101 (progn
2102 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2103 ,@body)
2104 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2105
2106 (defsubst js2-char-uppercase-p (c)
2107 "Return t if C is an uppercase character.
2108 Handles unicode and latin chars properly."
2109 (/= c (downcase c)))
2110
2111 (defsubst js2-char-lowercase-p (c)
2112 "Return t if C is an uppercase character.
2113 Handles unicode and latin chars properly."
2114 (/= c (upcase c)))
2115
2116 ;;; AST struct and function definitions
2117
2118 ;; flags for ast node property 'member-type (used for e4x operators)
2119 (defvar js2-property-flag #x1 "property access: element is valid name")
2120 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2121 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2122
2123 (defsubst js2-relpos (pos anchor)
2124 "Convert POS to be relative to ANCHOR.
2125 If POS is nil, returns nil."
2126 (and pos (- pos anchor)))
2127
2128 (defsubst js2-make-pad (indent)
2129 (if (zerop indent)
2130 ""
2131 (make-string (* indent js2-basic-offset) ? )))
2132
2133 (defsubst js2-visit-ast (node callback)
2134 "Visit every node in ast NODE with visitor CALLBACK.
2135
2136 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2137 called twice: once to visit the node, and again after all the node's
2138 children have been processed. The END-P argument is nil on the first
2139 call and non-nil on the second call. The return value of the callback
2140 affects the traversal: if non-nil, the children of NODE are processed.
2141 If the callback returns nil, or if the node has no children, then the
2142 callback is called immediately with a non-nil END-P argument.
2143
2144 The node traversal is approximately lexical-order, although there
2145 are currently no guarantees around this."
2146 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2147 ;; visit the node
2148 (when (funcall callback node nil)
2149 ;; visit the kids
2150 (cond
2151 ((eq vfunc 'js2-visit-none)
2152 nil) ; don't even bother calling it
2153 ;; Each AST node type has to define a `js2-visitor' function
2154 ;; that takes a node and a callback, and calls `js2-visit-ast'
2155 ;; on each child of the node.
2156 (vfunc
2157 (funcall vfunc node callback))
2158 (t
2159 (error "%s does not define a visitor-traversal function"
2160 (aref node 0)))))
2161 ;; call the end-visit
2162 (funcall callback node t)))
2163
2164 (defstruct (js2-node
2165 (:constructor nil)) ; abstract
2166 "Base AST node type."
2167 (type -1) ; token type
2168 (pos -1) ; start position of this AST node in parsed input
2169 (len 1) ; num characters spanned by the node
2170 props ; optional node property list (an alist)
2171 parent) ; link to parent node; null for root
2172
2173 (defsubst js2-node-get-prop (node prop &optional default)
2174 (or (cadr (assoc prop (js2-node-props node))) default))
2175
2176 (defsubst js2-node-set-prop (node prop value)
2177 (setf (js2-node-props node)
2178 (cons (list prop value) (js2-node-props node))))
2179
2180 (defsubst js2-fixup-starts (n nodes)
2181 "Adjust the start positions of NODES to be relative to N.
2182 Any node in the list may be nil, for convenience."
2183 (dolist (node nodes)
2184 (when node
2185 (setf (js2-node-pos node) (- (js2-node-pos node)
2186 (js2-node-pos n))))))
2187
2188 (defsubst js2-node-add-children (parent &rest nodes)
2189 "Set parent node of NODES to PARENT, and return PARENT.
2190 Does nothing if we're not recording parent links.
2191 If any given node in NODES is nil, doesn't record that link."
2192 (js2-fixup-starts parent nodes)
2193 (dolist (node nodes)
2194 (and node
2195 (setf (js2-node-parent node) parent))))
2196
2197 ;; Non-recursive since it's called a frightening number of times.
2198 (defsubst js2-node-abs-pos (n)
2199 (let ((pos (js2-node-pos n)))
2200 (while (setq n (js2-node-parent n))
2201 (setq pos (+ pos (js2-node-pos n))))
2202 pos))
2203
2204 (defsubst js2-node-abs-end (n)
2205 "Return absolute buffer position of end of N."
2206 (+ (js2-node-abs-pos n) (js2-node-len n)))
2207
2208 ;; It's important to make sure block nodes have a lisp list for the
2209 ;; child nodes, to limit printing recursion depth in an AST that
2210 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2211 ;; a sufficiently large vector tree.
2212
2213 (defstruct (js2-block-node
2214 (:include js2-node)
2215 (:constructor nil)
2216 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2217 (pos js2-token-beg)
2218 len
2219 props
2220 kids)))
2221 "A block of statements."
2222 kids) ; a lisp list of the child statement nodes
2223
2224 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2225 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2226
2227 (defsubst js2-visit-block (ast callback)
2228 "Visit the `js2-block-node' children of AST."
2229 (dolist (kid (js2-block-node-kids ast))
2230 (js2-visit-ast kid callback)))
2231
2232 (defun js2-print-block (n i)
2233 (let ((pad (js2-make-pad i)))
2234 (insert pad "{\n")
2235 (dolist (kid (js2-block-node-kids n))
2236 (js2-print-ast kid (1+ i)))
2237 (insert pad "}")))
2238
2239 (defstruct (js2-scope
2240 (:include js2-block-node)
2241 (:constructor nil)
2242 (:constructor make-js2-scope (&key (type js2-BLOCK)
2243 (pos js2-token-beg)
2244 len
2245 kids)))
2246 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2247 ;; I don't have one of those handy, so I'll use an alist for now.
2248 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2249 ;; and is much lighter-weight to construct (both CPU and mem).
2250 ;; The keys are interned strings (symbols) for faster lookup.
2251 ;; Should switch to hybrid alist/hashtable eventually.
2252 symbol-table ; an alist of (symbol . js2-symbol)
2253 parent-scope ; a `js2-scope'
2254 top) ; top-level `js2-scope' (script/function)
2255
2256 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2257 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2258
2259 (defun js2-scope-set-parent-scope (scope parent)
2260 (setf (js2-scope-parent-scope scope) parent
2261 (js2-scope-top scope) (if (null parent)
2262 scope
2263 (js2-scope-top parent))))
2264
2265 (defun js2-node-get-enclosing-scope (node)
2266 "Return the innermost `js2-scope' node surrounding NODE.
2267 Returns nil if there is no enclosing scope node."
2268 (let ((parent (js2-node-parent node)))
2269 (while (not (js2-scope-p parent))
2270 (setq parent (js2-node-parent parent)))
2271 parent))
2272
2273 (defun js2-get-defining-scope (scope name)
2274 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2275 Returns `js2-scope' in which NAME is defined, or nil if not found."
2276 (let ((sym (if (symbolp name)
2277 name
2278 (intern name)))
2279 table
2280 result
2281 (continue t))
2282 (while (and scope continue)
2283 (if (and (setq table (js2-scope-symbol-table scope))
2284 (assq sym table))
2285 (setq continue nil
2286 result scope)
2287 (setq scope (js2-scope-parent-scope scope))))
2288 result))
2289
2290 (defsubst js2-scope-get-symbol (scope name)
2291 "Return symbol table entry for NAME in SCOPE.
2292 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2293 (and (js2-scope-symbol-table scope)
2294 (cdr (assq (if (symbolp name)
2295 name
2296 (intern name))
2297 (js2-scope-symbol-table scope)))))
2298
2299 (defsubst js2-scope-put-symbol (scope name symbol)
2300 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2301 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2302 (let* ((table (js2-scope-symbol-table scope))
2303 (sym (if (symbolp name) name (intern name)))
2304 (entry (assq sym table)))
2305 (if entry
2306 (setcdr entry symbol)
2307 (push (cons sym symbol)
2308 (js2-scope-symbol-table scope)))))
2309
2310 (defstruct (js2-symbol
2311 (:constructor nil)
2312 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2313 "A symbol table entry."
2314 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2315 ;; js2-LET, or js2-CONST
2316 decl-type
2317 name ; string
2318 ast-node) ; a `js2-node'
2319
2320 (defstruct (js2-error-node
2321 (:include js2-node)
2322 (:constructor nil) ; silence emacs21 byte-compiler
2323 (:constructor make-js2-error-node (&key (type js2-ERROR)
2324 (pos js2-token-beg)
2325 len)))
2326 "AST node representing a parse error.")
2327
2328 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2329 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2330
2331 (defstruct (js2-script-node
2332 (:include js2-scope)
2333 (:constructor nil)
2334 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2335 (pos js2-token-beg)
2336 len
2337 var-decls
2338 fun-decls)))
2339 functions ; lisp list of nested functions
2340 regexps ; lisp list of (string . flags)
2341 symbols ; alist (every symbol gets unique index)
2342 (param-count 0)
2343 var-names ; vector of string names
2344 consts ; bool-vector matching var-decls
2345 (temp-number 0)) ; for generating temp variables
2346
2347 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2348 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2349
2350 (defun js2-print-script (node indent)
2351 (dolist (kid (js2-block-node-kids node))
2352 (js2-print-ast kid indent)))
2353
2354 (defstruct (js2-ast-root
2355 (:include js2-script-node)
2356 (:constructor nil)
2357 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2358 (pos js2-token-beg)
2359 len
2360 buffer)))
2361 "The root node of a js2 AST."
2362 buffer ; the source buffer from which the code was parsed
2363 comments ; a lisp list of comments, ordered by start position
2364 errors ; a lisp list of errors found during parsing
2365 warnings ; a lisp list of warnings found during parsing
2366 node-count) ; number of nodes in the tree, including the root
2367
2368 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2369 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2370
2371 (defun js2-visit-ast-root (ast callback)
2372 (dolist (kid (js2-ast-root-kids ast))
2373 (js2-visit-ast kid callback))
2374 (dolist (comment (js2-ast-root-comments ast))
2375 (js2-visit-ast comment callback)))
2376
2377 (defstruct (js2-comment-node
2378 (:include js2-node)
2379 (:constructor nil)
2380 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2381 (pos js2-token-beg)
2382 len
2383 (format js2-ts-comment-type))))
2384 format) ; 'line, 'block, 'jsdoc or 'html
2385
2386 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2387 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2388
2389 (defun js2-print-comment (n i)
2390 ;; We really ought to link end-of-line comments to their nodes.
2391 ;; Or maybe we could add a new comment type, 'endline.
2392 (insert (js2-make-pad i)
2393 (js2-node-string n)))
2394
2395 (defstruct (js2-expr-stmt-node
2396 (:include js2-node)
2397 (:constructor nil)
2398 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2399 (pos js2-ts-cursor)
2400 len
2401 expr)))
2402 "An expression statement."
2403 expr)
2404
2405 (defsubst js2-expr-stmt-node-set-has-result (node)
2406 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2407 (setf (js2-node-type node) js2-EXPR_RESULT))
2408
2409 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2410 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2411
2412 (defun js2-visit-expr-stmt-node (n v)
2413 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2414
2415 (defun js2-print-expr-stmt-node (n indent)
2416 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2417 (insert ";\n"))
2418
2419 (defstruct (js2-loop-node
2420 (:include js2-scope)
2421 (:constructor nil))
2422 "Abstract supertype of loop nodes."
2423 body ; a `js2-block-node'
2424 lp ; position of left-paren, nil if omitted
2425 rp) ; position of right-paren, nil if omitted
2426
2427 (defstruct (js2-do-node
2428 (:include js2-loop-node)
2429 (:constructor nil)
2430 (:constructor make-js2-do-node (&key (type js2-DO)
2431 (pos js2-token-beg)
2432 len
2433 body
2434 condition
2435 while-pos
2436 lp
2437 rp)))
2438 "AST node for do-loop."
2439 condition ; while (expression)
2440 while-pos) ; buffer position of 'while' keyword
2441
2442 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2443 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2444
2445 (defun js2-visit-do-node (n v)
2446 (js2-visit-ast (js2-do-node-body n) v)
2447 (js2-visit-ast (js2-do-node-condition n) v))
2448
2449 (defun js2-print-do-node (n i)
2450 (let ((pad (js2-make-pad i)))
2451 (insert pad "do {\n")
2452 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2453 (js2-print-ast kid (1+ i)))
2454 (insert pad "} while (")
2455 (js2-print-ast (js2-do-node-condition n) 0)
2456 (insert ");\n")))
2457
2458 (defstruct (js2-while-node
2459 (:include js2-loop-node)
2460 (:constructor nil)
2461 (:constructor make-js2-while-node (&key (type js2-WHILE)
2462 (pos js2-token-beg)
2463 len
2464 body
2465 condition
2466 lp
2467 rp)))
2468 "AST node for while-loop."
2469 condition) ; while-condition
2470
2471 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2472 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2473
2474 (defun js2-visit-while-node (n v)
2475 (js2-visit-ast (js2-while-node-condition n) v)
2476 (js2-visit-ast (js2-while-node-body n) v))
2477
2478 (defun js2-print-while-node (n i)
2479 (let ((pad (js2-make-pad i)))
2480 (insert pad "while (")
2481 (js2-print-ast (js2-while-node-condition n) 0)
2482 (insert ") {\n")
2483 (js2-print-body (js2-while-node-body n) (1+ i))
2484 (insert pad "}\n")))
2485
2486 (defstruct (js2-for-node
2487 (:include js2-loop-node)
2488 (:constructor nil)
2489 (:constructor make-js2-for-node (&key (type js2-FOR)
2490 (pos js2-ts-cursor)
2491 len
2492 body
2493 init
2494 condition
2495 update
2496 lp
2497 rp)))
2498 "AST node for a C-style for-loop."
2499 init ; initialization expression
2500 condition ; loop condition
2501 update) ; update clause
2502
2503 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2504 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2505
2506 (defun js2-visit-for-node (n v)
2507 (js2-visit-ast (js2-for-node-init n) v)
2508 (js2-visit-ast (js2-for-node-condition n) v)
2509 (js2-visit-ast (js2-for-node-update n) v)
2510 (js2-visit-ast (js2-for-node-body n) v))
2511
2512 (defun js2-print-for-node (n i)
2513 (let ((pad (js2-make-pad i)))
2514 (insert pad "for (")
2515 (js2-print-ast (js2-for-node-init n) 0)
2516 (insert "; ")
2517 (js2-print-ast (js2-for-node-condition n) 0)
2518 (insert "; ")
2519 (js2-print-ast (js2-for-node-update n) 0)
2520 (insert ") {\n")
2521 (js2-print-body (js2-for-node-body n) (1+ i))
2522 (insert pad "}\n")))
2523
2524 (defstruct (js2-for-in-node
2525 (:include js2-loop-node)
2526 (:constructor nil)
2527 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2528 (pos js2-ts-cursor)
2529 len
2530 body
2531 iterator
2532 object
2533 in-pos
2534 each-pos
2535 foreach-p
2536 lp
2537 rp)))
2538 "AST node for a for..in loop."
2539 iterator ; [var] foo in ...
2540 object ; object over which we're iterating
2541 in-pos ; buffer position of 'in' keyword
2542 each-pos ; buffer position of 'each' keyword, if foreach-p
2543 foreach-p) ; t if it's a for-each loop
2544
2545 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2546 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2547
2548 (defun js2-visit-for-in-node (n v)
2549 (js2-visit-ast (js2-for-in-node-iterator n) v)
2550 (js2-visit-ast (js2-for-in-node-object n) v)
2551 (js2-visit-ast (js2-for-in-node-body n) v))
2552
2553 (defun js2-print-for-in-node (n i)
2554 (let ((pad (js2-make-pad i))
2555 (foreach (js2-for-in-node-foreach-p n)))
2556 (insert pad "for ")
2557 (if foreach
2558 (insert "each "))
2559 (insert "(")
2560 (js2-print-ast (js2-for-in-node-iterator n) 0)
2561 (insert " in ")
2562 (js2-print-ast (js2-for-in-node-object n) 0)
2563 (insert ") {\n")
2564 (js2-print-body (js2-for-in-node-body n) (1+ i))
2565 (insert pad "}\n")))
2566
2567 (defstruct (js2-return-node
2568 (:include js2-node)
2569 (:constructor nil)
2570 (:constructor make-js2-return-node (&key (type js2-RETURN)
2571 (pos js2-ts-cursor)
2572 len
2573 retval)))
2574 "AST node for a return statement."
2575 retval) ; expression to return, or 'undefined
2576
2577 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2578 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2579
2580 (defun js2-visit-return-node (n v)
2581 (if (js2-return-node-retval n)
2582 (js2-visit-ast (js2-return-node-retval n) v)))
2583
2584 (defun js2-print-return-node (n i)
2585 (insert (js2-make-pad i) "return")
2586 (when (js2-return-node-retval n)
2587 (insert " ")
2588 (js2-print-ast (js2-return-node-retval n) 0))
2589 (insert ";\n"))
2590
2591 (defstruct (js2-if-node
2592 (:include js2-node)
2593 (:constructor nil)
2594 (:constructor make-js2-if-node (&key (type js2-IF)
2595 (pos js2-ts-cursor)
2596 len
2597 condition
2598 then-part
2599 else-pos
2600 else-part
2601 lp
2602 rp)))
2603 "AST node for an if-statement."
2604 condition ; expression
2605 then-part ; statement or block
2606 else-pos ; optional buffer position of 'else' keyword
2607 else-part ; optional statement or block
2608 lp ; position of left-paren, nil if omitted
2609 rp) ; position of right-paren, nil if omitted
2610
2611 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2612 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2613
2614 (defun js2-visit-if-node (n v)
2615 (js2-visit-ast (js2-if-node-condition n) v)
2616 (js2-visit-ast (js2-if-node-then-part n) v)
2617 (if (js2-if-node-else-part n)
2618 (js2-visit-ast (js2-if-node-else-part n) v)))
2619
2620 (defun js2-print-if-node (n i)
2621 (let ((pad (js2-make-pad i))
2622 (then-part (js2-if-node-then-part n))
2623 (else-part (js2-if-node-else-part n)))
2624 (insert pad "if (")
2625 (js2-print-ast (js2-if-node-condition n) 0)
2626 (insert ") {\n")
2627 (js2-print-body then-part (1+ i))
2628 (insert pad "}")
2629 (cond
2630 ((not else-part)
2631 (insert "\n"))
2632 ((js2-if-node-p else-part)
2633 (insert " else ")
2634 (js2-print-body else-part i))
2635 (t
2636 (insert " else {\n")
2637 (js2-print-body else-part (1+ i))
2638 (insert pad "}\n")))))
2639
2640 (defstruct (js2-try-node
2641 (:include js2-node)
2642 (:constructor nil)
2643 (:constructor make-js2-try-node (&key (type js2-TRY)
2644 (pos js2-ts-cursor)
2645 len
2646 try-block
2647 catch-clauses
2648 finally-block)))
2649 "AST node for a try-statement."
2650 try-block
2651 catch-clauses ; a lisp list of `js2-catch-node'
2652 finally-block) ; a `js2-finally-node'
2653
2654 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2655 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2656
2657 (defun js2-visit-try-node (n v)
2658 (js2-visit-ast (js2-try-node-try-block n) v)
2659 (dolist (clause (js2-try-node-catch-clauses n))
2660 (js2-visit-ast clause v))
2661 (if (js2-try-node-finally-block n)
2662 (js2-visit-ast (js2-try-node-finally-block n) v)))
2663
2664 (defun js2-print-try-node (n i)
2665 (let ((pad (js2-make-pad i))
2666 (catches (js2-try-node-catch-clauses n))
2667 (finally (js2-try-node-finally-block n)))
2668 (insert pad "try {\n")
2669 (js2-print-body (js2-try-node-try-block n) (1+ i))
2670 (insert pad "}")
2671 (when catches
2672 (dolist (catch catches)
2673 (js2-print-ast catch i)))
2674 (if finally
2675 (js2-print-ast finally i)
2676 (insert "\n"))))
2677
2678 (defstruct (js2-catch-node
2679 (:include js2-node)
2680 (:constructor nil)
2681 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2682 (pos js2-ts-cursor)
2683 len
2684 var-name
2685 guard-kwd
2686 guard-expr
2687 block
2688 lp
2689 rp)))
2690 "AST node for a catch clause."
2691 var-name ; a `js2-name-node'
2692 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2693 guard-expr ; catch condition, a `js2-node'
2694 block ; statements, a `js2-block-node'
2695 lp ; buffer position of left-paren, nil if omitted
2696 rp) ; buffer position of right-paren, nil if omitted
2697
2698 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2699 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2700
2701 (defun js2-visit-catch-node (n v)
2702 (js2-visit-ast (js2-catch-node-var-name n) v)
2703 (when (js2-catch-node-guard-kwd n)
2704 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2705 (js2-visit-ast (js2-catch-node-block n) v))
2706
2707 (defun js2-print-catch-node (n i)
2708 (let ((pad (js2-make-pad i))
2709 (guard-kwd (js2-catch-node-guard-kwd n))
2710 (guard-expr (js2-catch-node-guard-expr n)))
2711 (insert " catch (")
2712 (js2-print-ast (js2-catch-node-var-name n) 0)
2713 (when guard-kwd
2714 (insert " if ")
2715 (js2-print-ast guard-expr 0))
2716 (insert ") {\n")
2717 (js2-print-body (js2-catch-node-block n) (1+ i))
2718 (insert pad "}")))
2719
2720 (defstruct (js2-finally-node
2721 (:include js2-node)
2722 (:constructor nil)
2723 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2724 (pos js2-ts-cursor)
2725 len
2726 body)))
2727 "AST node for a finally clause."
2728 body) ; a `js2-node', often but not always a block node
2729
2730 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2731 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2732
2733 (defun js2-visit-finally-node (n v)
2734 (js2-visit-ast (js2-finally-node-body n) v))
2735
2736 (defun js2-print-finally-node (n i)
2737 (let ((pad (js2-make-pad i)))
2738 (insert " finally {\n")
2739 (js2-print-body (js2-finally-node-body n) (1+ i))
2740 (insert pad "}\n")))
2741
2742 (defstruct (js2-switch-node
2743 (:include js2-node)
2744 (:constructor nil)
2745 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2746 (pos js2-ts-cursor)
2747 len
2748 discriminant
2749 cases
2750 lp
2751 rp)))
2752 "AST node for a switch statement."
2753 discriminant ; a `js2-node' (switch expression)
2754 cases ; a lisp list of `js2-case-node'
2755 lp ; position of open-paren for discriminant, nil if omitted
2756 rp) ; position of close-paren for discriminant, nil if omitted
2757
2758 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2759 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2760
2761 (defun js2-visit-switch-node (n v)
2762 (js2-visit-ast (js2-switch-node-discriminant n) v)
2763 (dolist (c (js2-switch-node-cases n))
2764 (js2-visit-ast c v)))
2765
2766 (defun js2-print-switch-node (n i)
2767 (let ((pad (js2-make-pad i))
2768 (cases (js2-switch-node-cases n)))
2769 (insert pad "switch (")
2770 (js2-print-ast (js2-switch-node-discriminant n) 0)
2771 (insert ") {\n")
2772 (dolist (case cases)
2773 (js2-print-ast case i))
2774 (insert pad "}\n")))
2775
2776 (defstruct (js2-case-node
2777 (:include js2-block-node)
2778 (:constructor nil)
2779 (:constructor make-js2-case-node (&key (type js2-CASE)
2780 (pos js2-ts-cursor)
2781 len
2782 kids
2783 expr)))
2784 "AST node for a case clause of a switch statement."
2785 expr) ; the case expression (nil for default)
2786
2787 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2788 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2789
2790 (defun js2-visit-case-node (n v)
2791 (if (js2-case-node-expr n) ; nil for default: case
2792 (js2-visit-ast (js2-case-node-expr n) v))
2793 (js2-visit-block n v))
2794
2795 (defun js2-print-case-node (n i)
2796 (let ((pad (js2-make-pad i))
2797 (expr (js2-case-node-expr n)))
2798 (insert pad)
2799 (if (null expr)
2800 (insert "default:\n")
2801 (insert "case ")
2802 (js2-print-ast expr 0)
2803 (insert ":\n"))
2804 (dolist (kid (js2-case-node-kids n))
2805 (js2-print-ast kid (1+ i)))))
2806
2807 (defstruct (js2-throw-node
2808 (:include js2-node)
2809 (:constructor nil)
2810 (:constructor make-js2-throw-node (&key (type js2-THROW)
2811 (pos js2-ts-cursor)
2812 len
2813 expr)))
2814 "AST node for a throw statement."
2815 expr) ; the expression to throw
2816
2817 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2818 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2819
2820 (defun js2-visit-throw-node (n v)
2821 (js2-visit-ast (js2-throw-node-expr n) v))
2822
2823 (defun js2-print-throw-node (n i)
2824 (insert (js2-make-pad i) "throw ")
2825 (js2-print-ast (js2-throw-node-expr n) 0)
2826 (insert ";\n"))
2827
2828 (defstruct (js2-with-node
2829 (:include js2-node)
2830 (:constructor nil)
2831 (:constructor make-js2-with-node (&key (type js2-WITH)
2832 (pos js2-ts-cursor)
2833 len
2834 object
2835 body
2836 lp
2837 rp)))
2838 "AST node for a with-statement."
2839 object
2840 body
2841 lp ; buffer position of left-paren around object, nil if omitted
2842 rp) ; buffer position of right-paren around object, nil if omitted
2843
2844 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2845 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2846
2847 (defun js2-visit-with-node (n v)
2848 (js2-visit-ast (js2-with-node-object n) v)
2849 (js2-visit-ast (js2-with-node-body n) v))
2850
2851 (defun js2-print-with-node (n i)
2852 (let ((pad (js2-make-pad i)))
2853 (insert pad "with (")
2854 (js2-print-ast (js2-with-node-object n) 0)
2855 (insert ") {\n")
2856 (js2-print-body (js2-with-node-body n) (1+ i))
2857 (insert pad "}\n")))
2858
2859 (defstruct (js2-label-node
2860 (:include js2-node)
2861 (:constructor nil)
2862 (:constructor make-js2-label-node (&key (type js2-LABEL)
2863 (pos js2-ts-cursor)
2864 len
2865 name)))
2866 "AST node for a statement label or case label."
2867 name ; a string
2868 loop) ; for validating and code-generating continue-to-label
2869
2870 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2871 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2872
2873 (defun js2-print-label (n i)
2874 (insert (js2-make-pad i)
2875 (js2-label-node-name n)
2876 ":\n"))
2877
2878 (defstruct (js2-labeled-stmt-node
2879 (:include js2-node)
2880 (:constructor nil)
2881 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2882 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2883 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2884 (pos js2-ts-cursor)
2885 len
2886 labels
2887 stmt)))
2888 "AST node for a statement with one or more labels.
2889 Multiple labels for a statement are collapsed into the labels field."
2890 labels ; lisp list of `js2-label-node'
2891 stmt) ; the statement these labels are for
2892
2893 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2894 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2895
2896 (defun js2-get-label-by-name (lbl-stmt name)
2897 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2898 Returns nil if no such label is in the list."
2899 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2900 result)
2901 (while (and label-list (not result))
2902 (if (string= (js2-label-node-name (car label-list)) name)
2903 (setq result (car label-list))
2904 (setq label-list (cdr label-list))))
2905 result))
2906
2907 (defun js2-visit-labeled-stmt (n v)
2908 (dolist (label (js2-labeled-stmt-node-labels n))
2909 (js2-visit-ast label v))
2910 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2911
2912 (defun js2-print-labeled-stmt (n i)
2913 (dolist (label (js2-labeled-stmt-node-labels n))
2914 (js2-print-ast label i))
2915 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2916
2917 (defun js2-labeled-stmt-node-contains (node label)
2918 "Return t if NODE contains LABEL in its label set.
2919 NODE is a `js2-labels-node'. LABEL is an identifier."
2920 (loop for nl in (js2-labeled-stmt-node-labels node)
2921 if (string= label (js2-label-node-name nl))
2922 return t
2923 finally return nil))
2924
2925 (defsubst js2-labeled-stmt-node-add-label (node label)
2926 "Add a `js2-label-node' to the label set for this statement."
2927 (setf (js2-labeled-stmt-node-labels node)
2928 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2929
2930 (defstruct (js2-jump-node
2931 (:include js2-node)
2932 (:constructor nil))
2933 "Abstract supertype of break and continue nodes."
2934 label ; `js2-name-node' for location of label identifier, if present
2935 target) ; target js2-labels-node or loop/switch statement
2936
2937 (defun js2-visit-jump-node (n v)
2938 ;; we don't visit the target, since it's a back-link
2939 (if (js2-jump-node-label n)
2940 (js2-visit-ast (js2-jump-node-label n) v)))
2941
2942 (defstruct (js2-break-node
2943 (:include js2-jump-node)
2944 (:constructor nil)
2945 (:constructor make-js2-break-node (&key (type js2-BREAK)
2946 (pos js2-ts-cursor)
2947 len
2948 label
2949 target)))
2950 "AST node for a break statement.
2951 The label field is a `js2-name-node', possibly nil, for the named label
2952 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2953 is the target of the break - a label node or enclosing loop/switch statement.")
2954
2955 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2956 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2957
2958 (defun js2-print-break-node (n i)
2959 (insert (js2-make-pad i) "break")
2960 (when (js2-break-node-label n)
2961 (insert " ")
2962 (js2-print-ast (js2-break-node-label n) 0))
2963 (insert ";\n"))
2964
2965 (defstruct (js2-continue-node
2966 (:include js2-jump-node)
2967 (:constructor nil)
2968 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2969 (pos js2-ts-cursor)
2970 len
2971 label
2972 target)))
2973 "AST node for a continue statement.
2974 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2975 It is nil if continue specifies no label. The target field is the jump target:
2976 a `js2-label-node' or the innermost enclosing loop.")
2977
2978 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2979 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2980
2981 (defun js2-print-continue-node (n i)
2982 (insert (js2-make-pad i) "continue")
2983 (when (js2-continue-node-label n)
2984 (insert " ")
2985 (js2-print-ast (js2-continue-node-label n) 0))
2986 (insert ";\n"))
2987
2988 (defstruct (js2-function-node
2989 (:include js2-script-node)
2990 (:constructor nil)
2991 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2992 (pos js2-ts-cursor)
2993 len
2994 (ftype 'FUNCTION)
2995 (form 'FUNCTION_STATEMENT)
2996 (name "")
2997 params
2998 body
2999 lp
3000 rp)))
3001 "AST node for a function declaration.
3002 The `params' field is a lisp list of nodes. Each node is either a simple
3003 `js2-name-node', or if it's a destructuring-assignment parameter, a
3004 `js2-array-node' or `js2-object-node'."
3005 ftype ; FUNCTION, GETTER or SETTER
3006 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3007 name ; function name (a `js2-name-node', or nil if anonymous)
3008 params ; a lisp list of destructuring forms or simple name nodes
3009 body ; a `js2-block-node' or expression node (1.8 only)
3010 lp ; position of arg-list open-paren, or nil if omitted
3011 rp ; position of arg-list close-paren, or nil if omitted
3012 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3013 needs-activation ; t if we need an activation object for this frame
3014 is-generator ; t if this function contains a yield
3015 member-expr) ; nonstandard Ecma extension from Rhino
3016
3017 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3018 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3019
3020 (defun js2-visit-function-node (n v)
3021 (if (js2-function-node-name n)
3022 (js2-visit-ast (js2-function-node-name n) v))
3023 (dolist (p (js2-function-node-params n))
3024 (js2-visit-ast p v))
3025 (when (js2-function-node-body n)
3026 (js2-visit-ast (js2-function-node-body n) v)))
3027
3028 (defun js2-print-function-node (n i)
3029 (let ((pad (js2-make-pad i))
3030 (getter (js2-node-get-prop n 'GETTER_SETTER))
3031 (name (js2-function-node-name n))
3032 (params (js2-function-node-params n))
3033 (body (js2-function-node-body n))
3034 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3035 (unless getter
3036 (insert pad "function"))
3037 (when name
3038 (insert " ")
3039 (js2-print-ast name 0))
3040 (insert "(")
3041 (loop with len = (length params)
3042 for param in params
3043 for count from 1
3044 do
3045 (js2-print-ast param 0)
3046 (if (< count len)
3047 (insert ", ")))
3048 (insert ") {")
3049 (unless expr
3050 (insert "\n"))
3051 ;; TODO: fix this to be smarter about indenting, etc.
3052 (js2-print-body body (1+ i))
3053 (insert pad "}")
3054 (unless expr
3055 (insert "\n"))))
3056
3057 (defsubst js2-function-name (node)
3058 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3059 (and (js2-function-node-name node)
3060 (js2-name-node-name (js2-function-node-name node))))
3061
3062 ;; Having this be an expression node makes it more flexible.
3063 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3064 ;; that work better if you assume it's an expression. Whenever we have
3065 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3066 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3067 (defstruct (js2-var-decl-node
3068 (:include js2-node)
3069 (:constructor nil)
3070 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3071 (pos js2-token-beg)
3072 len
3073 kids
3074 decl-type)))
3075 "AST node for a variable declaration list (VAR, CONST or LET).
3076 The node bounds differ depending on the declaration type. For VAR or
3077 CONST declarations, the bounds include the var/const keyword. For LET
3078 declarations, the node begins at the position of the first child."
3079 kids ; a lisp list of `js2-var-init-node' structs.
3080 decl-type) ; js2-VAR, js2-CONST or js2-LET
3081
3082 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3083 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3084
3085 (defun js2-visit-var-decl (n v)
3086 (dolist (kid (js2-var-decl-node-kids n))
3087 (js2-visit-ast kid v)))
3088
3089 (defun js2-print-var-decl (n i)
3090 (let ((pad (js2-make-pad i))
3091 (tt (js2-var-decl-node-decl-type n)))
3092 (insert pad)
3093 (insert (cond
3094 ((= tt js2-VAR) "var ")
3095 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3096 ((= tt js2-CONST) "const ")
3097 (t
3098 (error "malformed var-decl node"))))
3099 (loop with kids = (js2-var-decl-node-kids n)
3100 with len = (length kids)
3101 for kid in kids
3102 for count from 1
3103 do
3104 (js2-print-ast kid 0)
3105 (if (< count len)
3106 (insert ", ")))))
3107
3108 (defstruct (js2-var-init-node
3109 (:include js2-node)
3110 (:constructor nil)
3111 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3112 (pos js2-ts-cursor)
3113 len
3114 target
3115 initializer)))
3116 "AST node for a variable declaration.
3117 The type field will be js2-CONST for a const decl."
3118 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3119 initializer) ; initializer expression, a `js2-node'
3120
3121 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3122 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3123
3124 (defun js2-visit-var-init-node (n v)
3125 (js2-visit-ast (js2-var-init-node-target n) v)
3126 (if (js2-var-init-node-initializer n)
3127 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3128
3129 (defun js2-print-var-init-node (n i)
3130 (let ((pad (js2-make-pad i))
3131 (name (js2-var-init-node-target n))
3132 (init (js2-var-init-node-initializer n)))
3133 (insert pad)
3134 (js2-print-ast name 0)
3135 (when init
3136 (insert " = ")
3137 (js2-print-ast init 0))))
3138
3139 (defstruct (js2-cond-node
3140 (:include js2-node)
3141 (:constructor nil)
3142 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3143 (pos js2-ts-cursor)
3144 len
3145 test-expr
3146 true-expr
3147 false-expr
3148 q-pos
3149 c-pos)))
3150 "AST node for the ternary operator"
3151 test-expr
3152 true-expr
3153 false-expr
3154 q-pos ; buffer position of ?
3155 c-pos) ; buffer position of :
3156
3157 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3158 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3159
3160 (defun js2-visit-cond-node (n v)
3161 (js2-visit-ast (js2-cond-node-test-expr n) v)
3162 (js2-visit-ast (js2-cond-node-true-expr n) v)
3163 (js2-visit-ast (js2-cond-node-false-expr n) v))
3164
3165 (defun js2-print-cond-node (n i)
3166 (let ((pad (js2-make-pad i)))
3167 (insert pad)
3168 (js2-print-ast (js2-cond-node-test-expr n) 0)
3169 (insert " ? ")
3170 (js2-print-ast (js2-cond-node-true-expr n) 0)
3171 (insert " : ")
3172 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3173
3174 (defstruct (js2-infix-node
3175 (:include js2-node)
3176 (:constructor nil)
3177 (:constructor make-js2-infix-node (&key type
3178 (pos js2-ts-cursor)
3179 len
3180 op-pos
3181 left
3182 right)))
3183 "Represents infix expressions.
3184 Includes assignment ops like `|=', and the comma operator.
3185 The type field inherited from `js2-node' holds the operator."
3186 op-pos ; buffer position where operator begins
3187 left ; any `js2-node'
3188 right) ; any `js2-node'
3189
3190 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3191 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3192
3193 (defun js2-visit-infix-node (n v)
3194 (when (js2-infix-node-left n)
3195 (js2-visit-ast (js2-infix-node-left n) v))
3196 (when (js2-infix-node-right n)
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 (when (js2-let-node-vars n)
3336 (js2-visit-ast (js2-let-node-vars n) v))
3337 (when (js2-let-node-body n)
3338 (js2-visit-ast (js2-let-node-body n) v)))
3339
3340 (defun js2-print-let-node (n i)
3341 (insert (js2-make-pad i) "let (")
3342 (js2-print-ast (js2-let-node-vars n) 0)
3343 (insert ") ")
3344 (js2-print-ast (js2-let-node-body n) i))
3345
3346 (defstruct (js2-keyword-node
3347 (:include js2-node)
3348 (:constructor nil)
3349 (:constructor make-js2-keyword-node (&key type
3350 (pos js2-token-beg)
3351 (len (- js2-ts-cursor pos)))))
3352 "AST node representing a literal keyword such as `null'.
3353 Used for `null', `this', `true', `false' and `debugger'.
3354 The node type is set to js2-NULL, js2-THIS, etc.")
3355
3356 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3357 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3358
3359 (defun js2-print-keyword-node (n i)
3360 (insert (js2-make-pad i)
3361 (let ((tt (js2-node-type n)))
3362 (cond
3363 ((= tt js2-THIS) "this")
3364 ((= tt js2-NULL) "null")
3365 ((= tt js2-TRUE) "true")
3366 ((= tt js2-FALSE) "false")
3367 ((= tt js2-DEBUGGER) "debugger")
3368 (t (error "Invalid keyword literal type: %d" tt))))))
3369
3370 (defsubst js2-this-node-p (node)
3371 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3372 (eq (js2-node-type node) js2-THIS))
3373
3374 (defstruct (js2-new-node
3375 (:include js2-node)
3376 (:constructor nil)
3377 (:constructor make-js2-new-node (&key (type js2-NEW)
3378 (pos js2-token-beg)
3379 len
3380 target
3381 args
3382 initializer
3383 lp
3384 rp)))
3385 "AST node for new-expression such as new Foo()."
3386 target ; an identifier or reference
3387 args ; a lisp list of argument nodes
3388 lp ; position of left-paren, nil if omitted
3389 rp ; position of right-paren, nil if omitted
3390 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3391
3392 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3393 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3394
3395 (defun js2-visit-new-node (n v)
3396 (js2-visit-ast (js2-new-node-target n) v)
3397 (dolist (arg (js2-new-node-args n))
3398 (js2-visit-ast arg v))
3399 (when (js2-new-node-initializer n)
3400 (js2-visit-ast (js2-new-node-initializer n) v)))
3401
3402 (defun js2-print-new-node (n i)
3403 (insert (js2-make-pad i) "new ")
3404 (js2-print-ast (js2-new-node-target n))
3405 (insert "(")
3406 (js2-print-list (js2-new-node-args n))
3407 (insert ")")
3408 (when (js2-new-node-initializer n)
3409 (insert " ")
3410 (js2-print-ast (js2-new-node-initializer n))))
3411
3412 (defstruct (js2-name-node
3413 (:include js2-node)
3414 (:constructor nil)
3415 (:constructor make-js2-name-node (&key (type js2-NAME)
3416 (pos js2-token-beg)
3417 (len (- js2-ts-cursor
3418 js2-token-beg))
3419 (name js2-ts-string))))
3420 "AST node for a JavaScript identifier"
3421 name ; a string
3422 scope) ; a `js2-scope' (optional, used for codegen)
3423
3424 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3425 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3426
3427 (defun js2-print-name-node (n i)
3428 (insert (js2-make-pad i)
3429 (js2-name-node-name n)))
3430
3431 (defsubst js2-name-node-length (node)
3432 "Return identifier length of NODE, a `js2-name-node'.
3433 Returns 0 if NODE is nil or its identifier field is nil."
3434 (if node
3435 (length (js2-name-node-name node))
3436 0))
3437
3438 (defstruct (js2-number-node
3439 (:include js2-node)
3440 (:constructor nil)
3441 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3442 (pos js2-token-beg)
3443 (len (- js2-ts-cursor
3444 js2-token-beg))
3445 (value js2-ts-string)
3446 (num-value js2-ts-number))))
3447 "AST node for a number literal."
3448 value ; the original string, e.g. "6.02e23"
3449 num-value) ; the parsed number value
3450
3451 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3452 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3453
3454 (defun js2-print-number-node (n i)
3455 (insert (js2-make-pad i)
3456 (number-to-string (js2-number-node-num-value n))))
3457
3458 (defstruct (js2-regexp-node
3459 (:include js2-node)
3460 (:constructor nil)
3461 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3462 (pos js2-token-beg)
3463 (len (- js2-ts-cursor
3464 js2-token-beg))
3465 value
3466 flags)))
3467 "AST node for a regular expression literal."
3468 value ; the regexp string, without // delimiters
3469 flags) ; a string of flags, e.g. `mi'.
3470
3471 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3472 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3473
3474 (defun js2-print-regexp (n i)
3475 (insert (js2-make-pad i)
3476 "/"
3477 (js2-regexp-node-value n)
3478 "/")
3479 (if (js2-regexp-node-flags n)
3480 (insert (js2-regexp-node-flags n))))
3481
3482 (defstruct (js2-string-node
3483 (:include js2-node)
3484 (:constructor nil)
3485 (:constructor make-js2-string-node (&key (type js2-STRING)
3486 (pos js2-token-beg)
3487 (len (- js2-ts-cursor
3488 js2-token-beg))
3489 (value js2-ts-string))))
3490 "String literal.
3491 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3492 You can tell the quote type by looking at the first character."
3493 value) ; the characters of the string, including the quotes
3494
3495 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3496 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3497
3498 (defun js2-print-string-node (n i)
3499 (insert (js2-make-pad i)
3500 (js2-node-string n)))
3501
3502 (defstruct (js2-array-node
3503 (:include js2-node)
3504 (:constructor nil)
3505 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3506 (pos js2-ts-cursor)
3507 len
3508 elems)))
3509 "AST node for an array literal."
3510 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3511
3512 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3513 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3514
3515 (defun js2-visit-array-node (n v)
3516 (dolist (e (js2-array-node-elems n))
3517 (when e ; can be nil, e.g. [a, ,b]
3518 (js2-visit-ast e v))))
3519
3520 (defun js2-print-array-node (n i)
3521 (insert (js2-make-pad i) "[")
3522 (js2-print-list (js2-array-node-elems n))
3523 (insert "]"))
3524
3525 (defstruct (js2-object-node
3526 (:include js2-node)
3527 (:constructor nil)
3528 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3529 (pos js2-ts-cursor)
3530 len
3531 elems)))
3532 "AST node for an object literal expression."
3533 elems) ; a lisp list of `js2-object-prop-node'
3534
3535 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3536 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3537
3538 (defun js2-visit-object-node (n v)
3539 (dolist (e (js2-object-node-elems n))
3540 (js2-visit-ast e v)))
3541
3542 (defun js2-print-object-node (n i)
3543 (insert (js2-make-pad i) "{")
3544 (js2-print-list (js2-object-node-elems n))
3545 (insert "}"))
3546
3547 (defstruct (js2-object-prop-node
3548 (:include js2-infix-node)
3549 (:constructor nil)
3550 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3551 (pos js2-ts-cursor)
3552 len
3553 left
3554 right
3555 op-pos)))
3556 "AST node for an object literal prop:value entry.
3557 The `left' field is the property: a name node, string node or number node.
3558 The `right' field is a `js2-node' representing the initializer value.")
3559
3560 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3561 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3562
3563 (defun js2-print-object-prop-node (n i)
3564 (insert (js2-make-pad i))
3565 (js2-print-ast (js2-object-prop-node-left n) 0)
3566 (insert ":")
3567 (js2-print-ast (js2-object-prop-node-right n) 0))
3568
3569 (defstruct (js2-getter-setter-node
3570 (:include js2-infix-node)
3571 (:constructor nil)
3572 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3573 (pos js2-ts-cursor)
3574 len
3575 left
3576 right)))
3577 "AST node for a getter/setter property in an object literal.
3578 The `left' field is the `js2-name-node' naming the getter/setter prop.
3579 The `right' field is always an anonymous `js2-function-node' with a node
3580 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3581
3582 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3583 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3584
3585 (defun js2-print-getter-setter (n i)
3586 (let ((pad (js2-make-pad i))
3587 (left (js2-getter-setter-node-left n))
3588 (right (js2-getter-setter-node-right n)))
3589 (insert pad)
3590 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3591 (js2-print-ast left 0)
3592 (js2-print-ast right 0)))
3593
3594 (defstruct (js2-prop-get-node
3595 (:include js2-infix-node)
3596 (:constructor nil)
3597 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3598 (pos js2-ts-cursor)
3599 len
3600 left
3601 right)))
3602 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3603
3604 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3605 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3606
3607 (defun js2-visit-prop-get-node (n v)
3608 (when (js2-prop-get-node-left n)
3609 (js2-visit-ast (js2-prop-get-node-left n) v))
3610 (when (js2-prop-get-node-right n)
3611 (js2-visit-ast (js2-prop-get-node-right n) v)))
3612
3613 (defun js2-print-prop-get-node (n i)
3614 (insert (js2-make-pad i))
3615 (js2-print-ast (js2-prop-get-node-left n) 0)
3616 (insert ".")
3617 (js2-print-ast (js2-prop-get-node-right n) 0))
3618
3619 (defstruct (js2-elem-get-node
3620 (:include js2-node)
3621 (:constructor nil)
3622 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3623 (pos js2-ts-cursor)
3624 len
3625 target
3626 element
3627 lb
3628 rb)))
3629 "AST node for an array index expression such as foo[bar]."
3630 target ; a `js2-node' - the expression preceding the "."
3631 element ; a `js2-node' - the expression in brackets
3632 lb ; position of left-bracket, nil if omitted
3633 rb) ; position of right-bracket, nil if omitted
3634
3635 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3636 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3637
3638 (defun js2-visit-elem-get-node (n v)
3639 (when (js2-elem-get-node-target n)
3640 (js2-visit-ast (js2-elem-get-node-target n) v))
3641 (when (js2-elem-get-node-element n)
3642 (js2-visit-ast (js2-elem-get-node-element n) v)))
3643
3644 (defun js2-print-elem-get-node (n i)
3645 (insert (js2-make-pad i))
3646 (js2-print-ast (js2-elem-get-node-target n) 0)
3647 (insert "[")
3648 (js2-print-ast (js2-elem-get-node-element n) 0)
3649 (insert "]"))
3650
3651 (defstruct (js2-call-node
3652 (:include js2-node)
3653 (:constructor nil)
3654 (:constructor make-js2-call-node (&key (type js2-CALL)
3655 (pos js2-ts-cursor)
3656 len
3657 target
3658 args
3659 lp
3660 rp)))
3661 "AST node for a JavaScript function call."
3662 target ; a `js2-node' evaluating to the function to call
3663 args ; a lisp list of `js2-node' arguments
3664 lp ; position of open-paren, or nil if missing
3665 rp) ; position of close-paren, or nil if missing
3666
3667 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3668 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3669
3670 (defun js2-visit-call-node (n v)
3671 (js2-visit-ast (js2-call-node-target n) v)
3672 (dolist (arg (js2-call-node-args n))
3673 (js2-visit-ast arg v)))
3674
3675 (defun js2-print-call-node (n i)
3676 (insert (js2-make-pad i))
3677 (js2-print-ast (js2-call-node-target n) 0)
3678 (insert "(")
3679 (js2-print-list (js2-call-node-args n))
3680 (insert ")"))
3681
3682 (defstruct (js2-yield-node
3683 (:include js2-node)
3684 (:constructor nil)
3685 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3686 (pos js2-ts-cursor)
3687 len
3688 value)))
3689 "AST node for yield statement or expression."
3690 value) ; optional: value to be yielded
3691
3692 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3693 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3694
3695 (defun js2-visit-yield-node (n v)
3696 (js2-visit-ast (js2-yield-node-value n) v))
3697
3698 (defun js2-print-yield-node (n i)
3699 (insert (js2-make-pad i))
3700 (insert "yield")
3701 (when (js2-yield-node-value n)
3702 (insert " ")
3703 (js2-print-ast (js2-yield-node-value n) 0)))
3704
3705 (defstruct (js2-paren-node
3706 (:include js2-node)
3707 (:constructor nil)
3708 (:constructor make-js2-paren-node (&key (type js2-LP)
3709 (pos js2-ts-cursor)
3710 len
3711 expr)))
3712 "AST node for a parenthesized expression.
3713 In particular, used when the parens are syntactically optional,
3714 as opposed to required parens such as those enclosing an if-conditional."
3715 expr) ; `js2-node'
3716
3717 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3718 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3719
3720 (defun js2-visit-paren-node (n v)
3721 (js2-visit-ast (js2-paren-node-expr n) v))
3722
3723 (defun js2-print-paren-node (n i)
3724 (insert (js2-make-pad i))
3725 (insert "(")
3726 (js2-print-ast (js2-paren-node-expr n) 0)
3727 (insert ")"))
3728
3729 (defstruct (js2-array-comp-node
3730 (:include js2-scope)
3731 (:constructor nil)
3732 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3733 (pos js2-ts-cursor)
3734 len
3735 result
3736 loops
3737 filter
3738 if-pos
3739 lp
3740 rp)))
3741 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3742 result ; result expression (just after left-bracket)
3743 loops ; a lisp list of `js2-array-comp-loop-node'
3744 filter ; guard/filter expression
3745 if-pos ; buffer pos of 'if' keyword, if present, else nil
3746 lp ; buffer position of if-guard left-paren, or nil if not present
3747 rp) ; buffer position of if-guard right-paren, or nil if not present
3748
3749 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3750 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3751
3752 (defun js2-visit-array-comp-node (n v)
3753 (js2-visit-ast (js2-array-comp-node-result n) v)
3754 (dolist (l (js2-array-comp-node-loops n))
3755 (js2-visit-ast l v))
3756 (if (js2-array-comp-node-filter n)
3757 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3758
3759 (defun js2-print-array-comp-node (n i)
3760 (let ((pad (js2-make-pad i))
3761 (result (js2-array-comp-node-result n))
3762 (loops (js2-array-comp-node-loops n))
3763 (filter (js2-array-comp-node-filter n)))
3764 (insert pad "[")
3765 (js2-print-ast result 0)
3766 (dolist (l loops)
3767 (insert " ")
3768 (js2-print-ast l 0))
3769 (when filter
3770 (insert " if (")
3771 (js2-print-ast filter 0))
3772 (insert ")]")))
3773
3774 (defstruct (js2-array-comp-loop-node
3775 (:include js2-for-in-node)
3776 (:constructor nil)
3777 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3778 (pos js2-ts-cursor)
3779 len
3780 iterator
3781 object
3782 in-pos
3783 foreach-p
3784 each-pos
3785 lp
3786 rp)))
3787 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3788
3789 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3790 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3791
3792 (defun js2-visit-array-comp-loop (n v)
3793 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3794 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3795
3796 (defun js2-print-array-comp-loop (n i)
3797 (insert "for (")
3798 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3799 (insert " in ")
3800 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3801 (insert ")"))
3802
3803 (defstruct (js2-empty-expr-node
3804 (:include js2-node)
3805 (:constructor nil)
3806 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3807 (pos js2-token-beg)
3808 len)))
3809 "AST node for an empty expression.")
3810
3811 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3812 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3813
3814 (defstruct (js2-xml-node
3815 (:include js2-block-node)
3816 (:constructor nil)
3817 (:constructor make-js2-xml-node (&key (type js2-XML)
3818 (pos js2-token-beg)
3819 len
3820 kids)))
3821 "AST node for initial parse of E4X literals.
3822 The kids field is a list of XML fragments, each a `js2-string-node' or
3823 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3824
3825 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3826 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3827
3828 (defun js2-print-xml-node (n i)
3829 (dolist (kid (js2-xml-node-kids n))
3830 (js2-print-ast kid i)))
3831
3832 (defstruct (js2-xml-js-expr-node
3833 (:include js2-xml-node)
3834 (:constructor nil)
3835 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3836 (pos js2-ts-cursor)
3837 len
3838 expr)))
3839 "AST node for an embedded JavaScript {expression} in an E4X literal.
3840 The start and end fields correspond to the curly-braces."
3841 expr) ; a `js2-expr-node' of some sort
3842
3843 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3844 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3845
3846 (defun js2-visit-xml-js-expr (n v)
3847 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3848
3849 (defun js2-print-xml-js-expr (n i)
3850 (insert (js2-make-pad i))
3851 (insert "{")
3852 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3853 (insert "}"))
3854
3855 (defstruct (js2-xml-dot-query-node
3856 (:include js2-infix-node)
3857 (:constructor nil)
3858 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3859 (pos js2-ts-cursor)
3860 op-pos
3861 len
3862 left
3863 right
3864 rp)))
3865 "AST node for an E4X foo.(bar) filter expression.
3866 Note that the left-paren is automatically the character immediately
3867 following the dot (.) in the operator. No whitespace is permitted
3868 between the dot and the lp by the scanner."
3869 rp)
3870
3871 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3872 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3873
3874 (defun js2-print-xml-dot-query (n i)
3875 (insert (js2-make-pad i))
3876 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3877 (insert ".(")
3878 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3879 (insert ")"))
3880
3881 (defstruct (js2-xml-ref-node
3882 (:include js2-node)
3883 (:constructor nil)) ; abstract
3884 "Base type for E4X XML attribute-access or property-get expressions.
3885 Such expressions can take a variety of forms. The general syntax has
3886 three parts:
3887
3888 - (optional) an @ (specifying an attribute access)
3889 - (optional) a namespace (a `js2-name-node') and double-colon
3890 - (required) either a `js2-name-node' or a bracketed [expression]
3891
3892 The property-name expressions (examples: ns::name, @name) are
3893 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3894 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3895
3896 This node type (or more specifically, its subclasses) will sometimes
3897 be the right-hand child of a `js2-prop-get-node' or a
3898 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3899 The `js2-xml-ref-node' may also be a standalone primary expression with
3900 no explicit target, which is valid in certain expression contexts such as
3901
3902 company..employee.(@id < 100)
3903
3904 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3905 expression whose parent is a `js2-xml-dot-query-node'."
3906 namespace
3907 at-pos
3908 colon-pos)
3909
3910 (defsubst js2-xml-ref-node-attr-access-p (node)
3911 "Return non-nil if this expression began with an @-token."
3912 (and (numberp (js2-xml-ref-node-at-pos node))
3913 (plusp (js2-xml-ref-node-at-pos node))))
3914
3915 (defstruct (js2-xml-prop-ref-node
3916 (:include js2-xml-ref-node)
3917 (:constructor nil)
3918 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3919 (pos js2-token-beg)
3920 len
3921 propname
3922 namespace
3923 at-pos
3924 colon-pos)))
3925 "AST node for an E4X XML [expr] property-ref expression.
3926 The JavaScript syntax is an optional @, an optional ns::, and a name.
3927
3928 [ '@' ] [ name '::' ] name
3929
3930 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3931 @ns::*, @*::attr, @*::*, and @*.
3932
3933 The node starts at the @ token, if present. Otherwise it starts at the
3934 namespace name. The node bounds extend through the closing right-bracket,
3935 or if it is missing due to a syntax error, through the end of the index
3936 expression."
3937 propname)
3938
3939 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3940 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3941
3942 (defun js2-visit-xml-prop-ref-node (n v)
3943 (if (js2-xml-prop-ref-node-namespace n)
3944 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3945 (if (js2-xml-prop-ref-node-propname n)
3946 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3947
3948 (defun js2-print-xml-prop-ref-node (n i)
3949 (insert (js2-make-pad i))
3950 (if (js2-xml-ref-node-attr-access-p n)
3951 (insert "@"))
3952 (when (js2-xml-prop-ref-node-namespace n)
3953 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3954 (insert "::"))
3955 (if (js2-xml-prop-ref-node-propname n)
3956 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3957
3958 (defstruct (js2-xml-elem-ref-node
3959 (:include js2-xml-ref-node)
3960 (:constructor nil)
3961 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3962 (pos js2-token-beg)
3963 len
3964 expr
3965 lb
3966 rb
3967 namespace
3968 at-pos
3969 colon-pos)))
3970 "AST node for an E4X XML [expr] member-ref expression.
3971 Syntax:
3972
3973 [ '@' ] [ name '::' ] '[' expr ']'
3974
3975 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3976
3977 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3978 is not a legal E4X XML element-ref expression, since it's already used
3979 for standard JavaScript element-get array indexing. Hence, a
3980 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3981 non-nil namespace node, or both.
3982
3983 The node starts at the @ token, if present. Otherwise it starts
3984 at the namespace name. The node bounds extend through the closing
3985 right-bracket, or if it is missing due to a syntax error, through the
3986 end of the index expression."
3987 expr ; the bracketed index expression
3988 lb
3989 rb)
3990
3991 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3992 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3993
3994 (defun js2-visit-xml-elem-ref-node (n v)
3995 (if (js2-xml-elem-ref-node-namespace n)
3996 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
3997 (if (js2-xml-elem-ref-node-expr n)
3998 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
3999
4000 (defun js2-print-xml-elem-ref-node (n i)
4001 (insert (js2-make-pad i))
4002 (if (js2-xml-ref-node-attr-access-p n)
4003 (insert "@"))
4004 (when (js2-xml-elem-ref-node-namespace n)
4005 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4006 (insert "::"))
4007 (insert "[")
4008 (if (js2-xml-elem-ref-node-expr n)
4009 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4010 (insert "]"))
4011
4012 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4013
4014 (defstruct (js2-xml-start-tag-node
4015 (:include js2-xml-node)
4016 (:constructor nil)
4017 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4018 (pos js2-ts-cursor)
4019 len
4020 name
4021 attrs
4022 kids
4023 empty-p)))
4024 "AST node for an XML start-tag. Not currently used.
4025 The `kids' field is a lisp list of child content nodes."
4026 name ; a `js2-xml-name-node'
4027 attrs ; a lisp list of `js2-xml-attr-node'
4028 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4029
4030 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4031 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4032
4033 (defun js2-visit-xml-start-tag (n v)
4034 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4035 (dolist (attr (js2-xml-start-tag-node-attrs n))
4036 (js2-visit-ast attr v))
4037 (js2-visit-block n v))
4038
4039 (defun js2-print-xml-start-tag (n i)
4040 (insert (js2-make-pad i) "<")
4041 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4042 (when (js2-xml-start-tag-node-attrs n)
4043 (insert " ")
4044 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4045 (insert ">"))
4046
4047 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4048 ;; and add the end-tag to the kids list of the parent as well.
4049 (defstruct (js2-xml-end-tag-node
4050 (:include js2-xml-node)
4051 (:constructor nil)
4052 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4053 (pos js2-ts-cursor)
4054 len
4055 name)))
4056 "AST node for an XML end-tag. Not currently used."
4057 name) ; a `js2-xml-name-node'
4058
4059 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4060 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4061
4062 (defun js2-visit-xml-end-tag (n v)
4063 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4064
4065 (defun js2-print-xml-end-tag (n i)
4066 (insert (js2-make-pad i))
4067 (insert "</")
4068 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4069 (insert ">"))
4070
4071 (defstruct (js2-xml-name-node
4072 (:include js2-xml-node)
4073 (:constructor nil)
4074 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4075 (pos js2-ts-cursor)
4076 len
4077 namespace
4078 kids)))
4079 "AST node for an E4X XML name. Not currently used.
4080 Any XML name can be qualified with a namespace, hence the namespace field.
4081 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4082 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4083 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4084 namespace) ; a `js2-string-node'
4085
4086 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4087 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4088
4089 (defun js2-visit-xml-name-node (n v)
4090 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4091
4092 (defun js2-print-xml-name-node (n i)
4093 (insert (js2-make-pad i))
4094 (when (js2-xml-name-node-namespace n)
4095 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4096 (insert "::"))
4097 (dolist (kid (js2-xml-name-node-kids n))
4098 (js2-print-ast kid 0)))
4099
4100 (defstruct (js2-xml-pi-node
4101 (:include js2-xml-node)
4102 (:constructor nil)
4103 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4104 (pos js2-ts-cursor)
4105 len
4106 name
4107 attrs)))
4108 "AST node for an E4X XML processing instruction. Not currently used."
4109 name ; a `js2-xml-name-node'
4110 attrs) ; a list of `js2-xml-attr-node'
4111
4112 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4113 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4114
4115 (defun js2-visit-xml-pi-node (n v)
4116 (js2-visit-ast (js2-xml-pi-node-name n) v)
4117 (dolist (attr (js2-xml-pi-node-attrs n))
4118 (js2-visit-ast attr v)))
4119
4120 (defun js2-print-xml-pi-node (n i)
4121 (insert (js2-make-pad i) "<?")
4122 (js2-print-ast (js2-xml-pi-node-name n))
4123 (when (js2-xml-pi-node-attrs n)
4124 (insert " ")
4125 (js2-print-list (js2-xml-pi-node-attrs n)))
4126 (insert "?>"))
4127
4128 (defstruct (js2-xml-cdata-node
4129 (:include js2-xml-node)
4130 (:constructor nil)
4131 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4132 (pos js2-ts-cursor)
4133 len
4134 content)))
4135 "AST node for a CDATA escape section. Not currently used."
4136 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4137
4138 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4139 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4140
4141 (defun js2-visit-xml-cdata-node (n v)
4142 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4143
4144 (defun js2-print-xml-cdata-node (n i)
4145 (insert (js2-make-pad i))
4146 (js2-print-ast (js2-xml-cdata-node-content n)))
4147
4148 (defstruct (js2-xml-attr-node
4149 (:include js2-xml-node)
4150 (:constructor nil)
4151 (:constructor make-js2-attr-node (&key (type js2-XML)
4152 (pos js2-ts-cursor)
4153 len
4154 name
4155 value
4156 eq-pos
4157 quote-type)))
4158 "AST node representing a foo='bar' XML attribute value. Not yet used."
4159 name ; a `js2-xml-name-node'
4160 value ; a `js2-xml-name-node'
4161 eq-pos ; buffer position of "=" sign
4162 quote-type) ; 'single or 'double
4163
4164 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4165 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4166
4167 (defun js2-visit-xml-attr-node (n v)
4168 (js2-visit-ast (js2-xml-attr-node-name n) v)
4169 (js2-visit-ast (js2-xml-attr-node-value n) v))
4170
4171 (defun js2-print-xml-attr-node (n i)
4172 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4173 "'"
4174 "\"")))
4175 (insert (js2-make-pad i))
4176 (js2-print-ast (js2-xml-attr-node-name n) 0)
4177 (insert "=" quote)
4178 (js2-print-ast (js2-xml-attr-node-value n) 0)
4179 (insert quote)))
4180
4181 (defstruct (js2-xml-text-node
4182 (:include js2-xml-node)
4183 (:constructor nil)
4184 (:constructor make-js2-text-node (&key (type js2-XML)
4185 (pos js2-ts-cursor)
4186 len
4187 content)))
4188 "AST node for an E4X XML text node. Not currently used."
4189 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4190
4191 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4192 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4193
4194 (defun js2-visit-xml-text-node (n v)
4195 (js2-visit-ast (js2-xml-text-node-content n) v))
4196
4197 (defun js2-print-xml-text-node (n i)
4198 (insert (js2-make-pad i))
4199 (dolist (kid (js2-xml-text-node-content n))
4200 (js2-print-ast kid)))
4201
4202 (defstruct (js2-xml-comment-node
4203 (:include js2-xml-node)
4204 (:constructor nil)
4205 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4206 (pos js2-ts-cursor)
4207 len)))
4208 "AST node for E4X XML comment. Not currently used.")
4209
4210 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4211 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4212
4213 (defun js2-print-xml-comment (n i)
4214 (insert (js2-make-pad i)
4215 (js2-node-string n)))
4216
4217 ;;; Node utilities
4218
4219 (defsubst js2-node-line (n)
4220 "Fetch the source line number at the start of node N.
4221 This is O(n) in the length of the source buffer; use prudently."
4222 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4223
4224 (defsubst js2-block-node-kid (n i)
4225 "Return child I of node N, or nil if there aren't that many."
4226 (nth i (js2-block-node-kids n)))
4227
4228 (defsubst js2-block-node-first (n)
4229 "Return first child of block node N, or nil if there is none."
4230 (first (js2-block-node-kids n)))
4231
4232 (defun js2-node-root (n)
4233 "Return the root of the AST containing N.
4234 If N has no parent pointer, returns N."
4235 (let ((parent (js2-node-parent n)))
4236 (if parent
4237 (js2-node-root parent)
4238 n)))
4239
4240 (defun js2-node-position-in-parent (node &optional parent)
4241 "Return the position of NODE in parent's block-kids list.
4242 PARENT can be supplied if known. Positioned returned is zero-indexed.
4243 Returns 0 if NODE is not a child of a block statement, or if NODE
4244 is not a statement node."
4245 (let ((p (or parent (js2-node-parent node)))
4246 (i 0))
4247 (if (not (js2-block-node-p p))
4248 i
4249 (or (js2-position node (js2-block-node-kids p))
4250 0))))
4251
4252 (defsubst js2-node-short-name (n)
4253 "Return the short name of node N as a string, e.g. `js2-if-node'."
4254 (substring (symbol-name (aref n 0))
4255 (length "cl-struct-")))
4256
4257 (defsubst js2-node-child-list (node)
4258 "Return the child list for NODE, a lisp list of nodes.
4259 Works for block nodes, array nodes, obj literals, funarg lists,
4260 var decls and try nodes (for catch clauses). Note that you should call
4261 `js2-block-node-kids' on the function body for the body statements.
4262 Returns nil for zero-length child lists or unsupported nodes."
4263 (cond
4264 ((js2-function-node-p node)
4265 (js2-function-node-params node))
4266 ((js2-block-node-p node)
4267 (js2-block-node-kids node))
4268 ((js2-try-node-p node)
4269 (js2-try-node-catch-clauses node))
4270 ((js2-array-node-p node)
4271 (js2-array-node-elems node))
4272 ((js2-object-node-p node)
4273 (js2-object-node-elems node))
4274 ((js2-call-node-p node)
4275 (js2-call-node-args node))
4276 ((js2-new-node-p node)
4277 (js2-new-node-args node))
4278 ((js2-var-decl-node-p node)
4279 (js2-var-decl-node-kids node))
4280 (t
4281 nil)))
4282
4283 (defsubst js2-node-set-child-list (node kids)
4284 "Set the child list for NODE to KIDS."
4285 (cond
4286 ((js2-function-node-p node)
4287 (setf (js2-function-node-params node) kids))
4288 ((js2-block-node-p node)
4289 (setf (js2-block-node-kids node) kids))
4290 ((js2-try-node-p node)
4291 (setf (js2-try-node-catch-clauses node) kids))
4292 ((js2-array-node-p node)
4293 (setf (js2-array-node-elems node) kids))
4294 ((js2-object-node-p node)
4295 (setf (js2-object-node-elems node) kids))
4296 ((js2-call-node-p node)
4297 (setf (js2-call-node-args node) kids))
4298 ((js2-new-node-p node)
4299 (setf (js2-new-node-args node) kids))
4300 ((js2-var-decl-node-p node)
4301 (setf (js2-var-decl-node-kids node) kids))
4302 (t
4303 (error "Unsupported node type: %s" (js2-node-short-name node))))
4304 kids)
4305
4306 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4307 (defconst js2-paren-expr-nodes
4308 '(cl-struct-js2-array-comp-loop-node
4309 cl-struct-js2-array-comp-node
4310 cl-struct-js2-call-node
4311 cl-struct-js2-catch-node
4312 cl-struct-js2-do-node
4313 cl-struct-js2-elem-get-node
4314 cl-struct-js2-for-in-node
4315 cl-struct-js2-for-node
4316 cl-struct-js2-function-node
4317 cl-struct-js2-if-node
4318 cl-struct-js2-let-node
4319 cl-struct-js2-new-node
4320 cl-struct-js2-paren-node
4321 cl-struct-js2-switch-node
4322 cl-struct-js2-while-node
4323 cl-struct-js2-with-node
4324 cl-struct-js2-xml-dot-query-node)
4325 "Node types that can have a parenthesized child expression.
4326 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4327
4328 (defsubst js2-paren-expr-node-p (node)
4329 "Return t for nodes that typically have a parenthesized child expression.
4330 Useful for computing the indentation anchors for arg-lists and conditions.
4331 Note that it may return a false positive, for instance when NODE is
4332 a `js2-new-node' and there are no arguments or parentheses."
4333 (memq (aref node 0) js2-paren-expr-nodes))
4334
4335 ;; Fake polymorphism... yech.
4336 (defsubst js2-node-lp (node)
4337 "Return relative left-paren position for NODE, if applicable.
4338 For `js2-elem-get-node' structs, returns left-bracket position.
4339 Note that the position may be nil in the case of a parse error."
4340 (cond
4341 ((js2-elem-get-node-p node)
4342 (js2-elem-get-node-lb node))
4343 ((js2-loop-node-p node)
4344 (js2-loop-node-lp node))
4345 ((js2-function-node-p node)
4346 (js2-function-node-lp node))
4347 ((js2-if-node-p node)
4348 (js2-if-node-lp node))
4349 ((js2-new-node-p node)
4350 (js2-new-node-lp node))
4351 ((js2-call-node-p node)
4352 (js2-call-node-lp node))
4353 ((js2-paren-node-p node)
4354 (js2-node-pos node))
4355 ((js2-switch-node-p node)
4356 (js2-switch-node-lp node))
4357 ((js2-catch-node-p node)
4358 (js2-catch-node-lp node))
4359 ((js2-let-node-p node)
4360 (js2-let-node-lp node))
4361 ((js2-array-comp-node-p node)
4362 (js2-array-comp-node-lp node))
4363 ((js2-with-node-p node)
4364 (js2-with-node-lp node))
4365 ((js2-xml-dot-query-node-p node)
4366 (1+ (js2-infix-node-op-pos node)))
4367 (t
4368 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4369
4370 ;; Fake polymorphism... blech.
4371 (defsubst js2-node-rp (node)
4372 "Return relative right-paren position for NODE, if applicable.
4373 For `js2-elem-get-node' structs, returns right-bracket position.
4374 Note that the position may be nil in the case of a parse error."
4375 (cond
4376 ((js2-elem-get-node-p node)
4377 (js2-elem-get-node-lb node))
4378 ((js2-loop-node-p node)
4379 (js2-loop-node-rp node))
4380 ((js2-function-node-p node)
4381 (js2-function-node-rp node))
4382 ((js2-if-node-p node)
4383 (js2-if-node-rp node))
4384 ((js2-new-node-p node)
4385 (js2-new-node-rp node))
4386 ((js2-call-node-p node)
4387 (js2-call-node-rp node))
4388 ((js2-paren-node-p node)
4389 (+ (js2-node-pos node) (js2-node-len node)))
4390 ((js2-switch-node-p node)
4391 (js2-switch-node-rp node))
4392 ((js2-catch-node-p node)
4393 (js2-catch-node-rp node))
4394 ((js2-let-node-p node)
4395 (js2-let-node-rp node))
4396 ((js2-array-comp-node-p node)
4397 (js2-array-comp-node-rp node))
4398 ((js2-with-node-p node)
4399 (js2-with-node-rp node))
4400 ((js2-xml-dot-query-node-p node)
4401 (1+ (js2-xml-dot-query-node-rp node)))
4402 (t
4403 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4404
4405 (defsubst js2-node-first-child (node)
4406 "Returns the first element of `js2-node-child-list' for NODE."
4407 (car (js2-node-child-list node)))
4408
4409 (defsubst js2-node-last-child (node)
4410 "Returns the last element of `js2-node-last-child' for NODE."
4411 (car (last (js2-node-child-list node))))
4412
4413 (defun js2-node-prev-sibling (node)
4414 "Return the previous statement in parent.
4415 Works for parents supported by `js2-node-child-list'.
4416 Returns nil if NODE is not in the parent, or PARENT is
4417 not a supported node, or if NODE is the first child."
4418 (let* ((p (js2-node-parent node))
4419 (kids (js2-node-child-list p))
4420 (sib (car kids)))
4421 (while (and kids
4422 (not (eq node (cadr kids))))
4423 (setq kids (cdr kids)
4424 sib (car kids)))
4425 sib))
4426
4427 (defun js2-node-next-sibling (node)
4428 "Return the next statement in parent block.
4429 Returns nil if NODE is not in the block, or PARENT is not
4430 a block node, or if NODE is the last statement."
4431 (let* ((p (js2-node-parent node))
4432 (kids (js2-node-child-list p)))
4433 (while (and kids
4434 (not (eq node (car kids))))
4435 (setq kids (cdr kids)))
4436 (cadr kids)))
4437
4438 (defun js2-node-find-child-before (pos parent &optional after)
4439 "Find the last child that starts before POS in parent.
4440 If AFTER is non-nil, returns first child starting after POS.
4441 POS is an absolute buffer position. PARENT is any node
4442 supported by `js2-node-child-list'.
4443 Returns nil if no applicable child is found."
4444 (let ((kids (if (js2-function-node-p parent)
4445 (js2-block-node-kids (js2-function-node-body parent))
4446 (js2-node-child-list parent)))
4447 (beg (if (js2-function-node-p parent)
4448 (js2-node-abs-pos (js2-function-node-body parent))
4449 (js2-node-abs-pos parent)))
4450 kid
4451 result
4452 fn
4453 (continue t))
4454 (setq fn (if after '> '<))
4455 (while (and kids continue)
4456 (setq kid (car kids))
4457 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4458 (setq result kid
4459 continue (if after nil t))
4460 (setq continue (if after t nil)))
4461 (setq kids (cdr kids)))
4462 result))
4463
4464 (defun js2-node-find-child-after (pos parent)
4465 "Find first child that starts after POS in parent.
4466 POS is an absolute buffer position. PARENT is any node
4467 supported by `js2-node-child-list'.
4468 Returns nil if no applicable child is found."
4469 (js2-node-find-child-before pos parent 'after))
4470
4471 (defun js2-node-replace-child (pos parent new-node)
4472 "Replace node at index POS in PARENT with NEW-NODE.
4473 Only works for parents supported by `js2-node-child-list'."
4474 (let ((kids (js2-node-child-list parent))
4475 (i 0))
4476 (while (< i pos)
4477 (setq kids (cdr kids)
4478 i (1+ i)))
4479 (setcar kids new-node)
4480 (js2-node-add-children parent new-node)))
4481
4482 (defun js2-node-buffer (n)
4483 "Return the buffer associated with AST N.
4484 Returns nil if the buffer is not set as a property on the root
4485 node, or if parent links were not recorded during parsing."
4486 (let ((root (js2-node-root n)))
4487 (and root
4488 (js2-ast-root-p root)
4489 (js2-ast-root-buffer root))))
4490
4491 (defsubst js2-block-node-push (n kid)
4492 "Push js2-node KID onto the end of js2-block-node N's child list.
4493 KID is always added to the -end- of the kids list.
4494 Function also calls `js2-node-add-children' to add the parent link."
4495 (let ((kids (js2-node-child-list n)))
4496 (if kids
4497 (setcdr kids (nconc (cdr kids) (list kid)))
4498 (js2-node-set-child-list n (list kid)))
4499 (js2-node-add-children n kid)))
4500
4501 (defun js2-node-string (node)
4502 (let ((buf (js2-node-buffer node))
4503 pos)
4504 (unless buf
4505 (error "No buffer available for node %s" node))
4506 (save-excursion
4507 (set-buffer buf)
4508 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4509 (+ pos (js2-node-len node))))))
4510
4511 ;; Container for storing the node we're looking for in a traversal.
4512 (js2-deflocal js2-discovered-node nil)
4513
4514 ;; Keep track of absolute node position during traversals.
4515 (js2-deflocal js2-visitor-offset nil)
4516
4517 (js2-deflocal js2-node-search-point nil)
4518
4519 (when js2-mode-dev-mode-p
4520 (defun js2-find-node-at-point ()
4521 (interactive)
4522 (let ((node (js2-node-at-point)))
4523 (message "%s" (or node "No node found at point"))))
4524 (defun js2-node-name-at-point ()
4525 (interactive)
4526 (let ((node (js2-node-at-point)))
4527 (message "%s" (if node
4528 (js2-node-short-name node)
4529 "No node found at point.")))))
4530
4531 (defun js2-node-at-point (&optional pos skip-comments)
4532 "Return AST node at POS, a buffer position, defaulting to current point.
4533 The `js2-mode-ast' variable must be set to the current parse tree.
4534 Signals an error if the AST (`js2-mode-ast') is nil.
4535 Always returns a node - if it can't find one, it returns the root.
4536 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4537 (let ((ast js2-mode-ast)
4538 result)
4539 (unless ast
4540 (error "No JavaScript AST available"))
4541 ;; Look through comments first, since they may be inside nodes that
4542 ;; would otherwise report a match.
4543 (setq pos (or pos (point))
4544 result (if (> pos (js2-node-abs-end ast))
4545 ast
4546 (if (not skip-comments)
4547 (js2-comment-at-point pos))))
4548 (unless result
4549 (setq js2-discovered-node nil
4550 js2-visitor-offset 0
4551 js2-node-search-point pos)
4552 (unwind-protect
4553 (catch 'js2-visit-done
4554 (js2-visit-ast ast #'js2-node-at-point-visitor))
4555 (setq js2-visitor-offset nil
4556 js2-node-search-point nil))
4557 (setq result js2-discovered-node))
4558 ;; may have found a comment beyond end of last child node,
4559 ;; since visiting the ast-root looks at the comment-list last.
4560 (if (and skip-comments
4561 (js2-comment-node-p result))
4562 (setq result nil))
4563 (or result js2-mode-ast)))
4564
4565 (defun js2-node-at-point-visitor (node end-p)
4566 (let ((rel-pos (js2-node-pos node))
4567 abs-pos
4568 abs-end
4569 (point js2-node-search-point))
4570 (cond
4571 (end-p
4572 ;; this evaluates to a non-nil return value, even if it's zero
4573 (decf js2-visitor-offset rel-pos))
4574 ;; we already looked for comments before visiting, and don't want them now
4575 ((js2-comment-node-p node)
4576 nil)
4577 (t
4578 (setq abs-pos (incf js2-visitor-offset rel-pos)
4579 ;; we only want to use the node if the point is before
4580 ;; the last character position in the node, so we decrement
4581 ;; the absolute end by 1.
4582 abs-end (+ abs-pos (js2-node-len node) -1))
4583 (cond
4584 ;; If this node starts after search-point, stop the search.
4585 ((> abs-pos point)
4586 (throw 'js2-visit-done nil))
4587 ;; If this node ends before the search-point, don't check kids.
4588 ((> point abs-end)
4589 nil)
4590 (t
4591 ;; Otherwise point is within this node, possibly in a child.
4592 (setq js2-discovered-node node)
4593 t)))))) ; keep processing kids to look for more specific match
4594
4595 (defsubst js2-block-comment-p (node)
4596 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4597 (and (js2-comment-node-p node)
4598 (memq (js2-comment-node-format node) '(jsdoc block))))
4599
4600 ;; TODO: put the comments in a vector and binary-search them instead
4601 (defun js2-comment-at-point (&optional pos)
4602 "Look through scanned comment nodes for one containing POS.
4603 POS is a buffer position that defaults to current point.
4604 Function returns nil if POS was not in any comment node."
4605 (let ((ast js2-mode-ast)
4606 (x (or pos (point)))
4607 beg
4608 end)
4609 (unless ast
4610 (error "No JavaScript AST available"))
4611 (catch 'done
4612 ;; Comments are stored in lexical order.
4613 (dolist (comment (js2-ast-root-comments ast) nil)
4614 (setq beg (js2-node-abs-pos comment)
4615 end (+ beg (js2-node-len comment)))
4616 (if (and (>= x beg)
4617 (<= x end))
4618 (throw 'done comment))))))
4619
4620 (defun js2-mode-find-parent-fn (node)
4621 "Find function enclosing NODE.
4622 Returns nil if NODE is not inside a function."
4623 (setq node (js2-node-parent node))
4624 (while (and node (not (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 (and (js2-function-node-p node) node))
4627
4628 (defun js2-mode-find-enclosing-fn (node)
4629 "Find function or root enclosing NODE."
4630 (if (js2-ast-root-p node)
4631 node
4632 (setq node (js2-node-parent node))
4633 (while (not (or (js2-ast-root-p node)
4634 (js2-function-node-p node)))
4635 (setq node (js2-node-parent node)))
4636 node))
4637
4638 (defun js2-mode-find-enclosing-node (beg end)
4639 "Find script or function fully enclosing BEG and END."
4640 (let ((node (js2-node-at-point beg))
4641 pos
4642 (continue t))
4643 (while continue
4644 (if (or (js2-ast-root-p node)
4645 (and (js2-function-node-p node)
4646 (<= (setq pos (js2-node-abs-pos node)) beg)
4647 (>= (+ pos (js2-node-len node)) end)))
4648 (setq continue nil)
4649 (setq node (js2-node-parent node))))
4650 node))
4651
4652 (defun js2-node-parent-script-or-fn (node)
4653 "Find script or function immediately enclosing NODE.
4654 If NODE is the ast-root, returns nil."
4655 (if (js2-ast-root-p node)
4656 nil
4657 (setq node (js2-node-parent node))
4658 (while (and node (not (or (js2-function-node-p node)
4659 (js2-script-node-p node))))
4660 (setq node (js2-node-parent node)))
4661 node))
4662
4663 (defsubst js2-nested-function-p (node)
4664 "Return t if NODE is a nested function, or is inside a nested function."
4665 (js2-function-node-p (if (js2-function-node-p node)
4666 (js2-node-parent-script-or-fn node)
4667 (js2-node-parent-script-or-fn
4668 (js2-node-parent-script-or-fn node)))))
4669
4670 (defsubst js2-function-param-node-p (node)
4671 "Return non-nil if NODE is a param node of a `js2-function-node'."
4672 (let ((parent (js2-node-parent node)))
4673 (and parent
4674 (js2-function-node-p parent)
4675 (memq node (js2-function-node-params parent)))))
4676
4677 (defsubst js2-mode-shift-kids (kids start offset)
4678 (dolist (kid kids)
4679 (if (> (js2-node-pos kid) start)
4680 (incf (js2-node-pos kid) offset))))
4681
4682 (defsubst js2-mode-shift-children (parent start offset)
4683 "Update start-positions of all children of PARENT beyond START."
4684 (let ((root (js2-node-root parent)))
4685 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4686 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4687
4688 (defsubst js2-node-is-descendant (node ancestor)
4689 "Return t if NODE is a descendant of ANCESTOR."
4690 (while (and node
4691 (not (eq node ancestor)))
4692 (setq node (js2-node-parent node)))
4693 node)
4694
4695 ;;; visitor infrastructure
4696
4697 (defun js2-visit-none (node callback)
4698 "Visitor for AST node that have no node children."
4699 nil)
4700
4701 (defun js2-print-none (node indent)
4702 "Visitor for AST node with no printed representation.")
4703
4704 (defun js2-print-body (node indent)
4705 "Print a statement, or a block without braces."
4706 (if (js2-block-node-p node)
4707 (dolist (kid (js2-block-node-kids node))
4708 (js2-print-ast kid indent))
4709 (js2-print-ast node indent)))
4710
4711 (defun js2-print-list (args &optional delimiter)
4712 (loop with len = (length args)
4713 for arg in args
4714 for count from 1
4715 do
4716 (js2-print-ast arg 0)
4717 (if (< count len)
4718 (insert (or delimiter ", ")))))
4719
4720 (defun js2-print-tree (ast)
4721 "Prints an AST to the current buffer.
4722 Makes `js2-ast-parent-nodes' available to the printer functions."
4723 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4724 (js2-print-ast ast)))
4725
4726 (defun js2-print-ast (node &optional indent)
4727 "Helper function for printing AST nodes.
4728 Requires `js2-ast-parent-nodes' to be non-nil.
4729 You should use `js2-print-tree' instead of this function."
4730 (let ((printer (get (aref node 0) 'js2-printer))
4731 (i (or indent 0))
4732 (pos (js2-node-abs-pos node)))
4733 ;; TODO: wedge comments in here somewhere
4734 (if printer
4735 (funcall printer node i))))
4736
4737 (defconst js2-side-effecting-tokens
4738 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4739 (dolist (tt (list js2-ASSIGN
4740 js2-ASSIGN_ADD
4741 js2-ASSIGN_BITAND
4742 js2-ASSIGN_BITOR
4743 js2-ASSIGN_BITXOR
4744 js2-ASSIGN_DIV
4745 js2-ASSIGN_LSH
4746 js2-ASSIGN_MOD
4747 js2-ASSIGN_MUL
4748 js2-ASSIGN_RSH
4749 js2-ASSIGN_SUB
4750 js2-ASSIGN_URSH
4751 js2-BLOCK
4752 js2-BREAK
4753 js2-CALL
4754 js2-CATCH
4755 js2-CATCH_SCOPE
4756 js2-CONST
4757 js2-CONTINUE
4758 js2-DEBUGGER
4759 js2-DEC
4760 js2-DELPROP
4761 js2-DEL_REF
4762 js2-DO
4763 js2-ELSE
4764 js2-EMPTY
4765 js2-ENTERWITH
4766 js2-EXPORT
4767 js2-EXPR_RESULT
4768 js2-FINALLY
4769 js2-FOR
4770 js2-FUNCTION
4771 js2-GOTO
4772 js2-IF
4773 js2-IFEQ
4774 js2-IFNE
4775 js2-IMPORT
4776 js2-INC
4777 js2-JSR
4778 js2-LABEL
4779 js2-LEAVEWITH
4780 js2-LET
4781 js2-LETEXPR
4782 js2-LOCAL_BLOCK
4783 js2-LOOP
4784 js2-NEW
4785 js2-REF_CALL
4786 js2-RETHROW
4787 js2-RETURN
4788 js2-RETURN_RESULT
4789 js2-SEMI
4790 js2-SETELEM
4791 js2-SETELEM_OP
4792 js2-SETNAME
4793 js2-SETPROP
4794 js2-SETPROP_OP
4795 js2-SETVAR
4796 js2-SET_REF
4797 js2-SET_REF_OP
4798 js2-SWITCH
4799 js2-TARGET
4800 js2-THROW
4801 js2-TRY
4802 js2-VAR
4803 js2-WHILE
4804 js2-WITH
4805 js2-WITHEXPR
4806 js2-YIELD))
4807 (aset tokens tt t))
4808 (if js2-instanceof-has-side-effects
4809 (aset tokens js2-INSTANCEOF t))
4810 tokens))
4811
4812 (defun js2-node-has-side-effects (node)
4813 "Return t if NODE has side effects."
4814 (when node ; makes it easier to handle malformed expressions
4815 (let ((tt (js2-node-type node)))
4816 (cond
4817 ;; This doubtless needs some work, since EXPR_VOID is used
4818 ;; in several ways in Rhino, and I may not have caught them all.
4819 ;; I'll wait for people to notice incorrect warnings.
4820 ((and (= tt js2-EXPR_VOID)
4821 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4822 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4823 ((= tt js2-COMMA)
4824 (js2-node-has-side-effects (js2-infix-node-right node)))
4825 ((or (= tt js2-AND)
4826 (= tt js2-OR))
4827 (or (js2-node-has-side-effects (js2-infix-node-right node))
4828 (js2-node-has-side-effects (js2-infix-node-left node))))
4829 ((= tt js2-HOOK)
4830 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4831 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4832 ((js2-paren-node-p node)
4833 (js2-node-has-side-effects (js2-paren-node-expr node)))
4834 ((= tt js2-ERROR) ; avoid cascaded error messages
4835 nil)
4836 (t
4837 (aref js2-side-effecting-tokens tt))))))
4838
4839 (defun js2-member-expr-leftmost-name (node)
4840 "For an expr such as foo.bar.baz, return leftmost node foo.
4841 NODE is any `js2-node' object. If it represents a member expression,
4842 which is any sequence of property gets, element-gets, function calls,
4843 or xml descendants/filter operators, then we look at the lexically
4844 leftmost (first) node in the chain. If it is a name-node we return it.
4845 Note that NODE can be a raw name-node and it will be returned as well.
4846 If NODE is not a name-node or member expression, or if it is a member
4847 expression whose leftmost target is not a name node, returns nil."
4848 (let ((continue t)
4849 result)
4850 (while (and continue (not result))
4851 (cond
4852 ((js2-name-node-p node)
4853 (setq result node))
4854 ((js2-prop-get-node-p node)
4855 (setq node (js2-prop-get-node-left node)))
4856 ;; TODO: handle call-nodes, xml-nodes, others?
4857 (t
4858 (setq continue nil))))
4859 result))
4860
4861 (defconst js2-stmt-node-types
4862 (list js2-BLOCK
4863 js2-BREAK
4864 js2-CONTINUE
4865 js2-DEFAULT ; e4x "default xml namespace" statement
4866 js2-DO
4867 js2-EXPR_RESULT
4868 js2-EXPR_VOID
4869 js2-FOR
4870 js2-IF
4871 js2-RETURN
4872 js2-SWITCH
4873 js2-THROW
4874 js2-TRY
4875 js2-WHILE
4876 js2-WITH)
4877 "Node types that only appear in statement contexts.
4878 The list does not include nodes that always appear as the child
4879 of another specific statement type, such as switch-cases,
4880 catch and finally blocks, and else-clauses. The list also excludes
4881 nodes like yield, let and var, which may appear in either expression
4882 or statement context, and in the latter context always have a
4883 `js2-expr-stmt-node' parent. Finally, the list does not include
4884 functions or scripts, which are treated separately from statements
4885 by the JavaScript parser and runtime.")
4886
4887 (defun js2-stmt-node-p (node)
4888 "Heuristic for figuring out if NODE is a statement.
4889 Some node types can appear in either an expression context or a
4890 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4891 For these node types in a statement context, the parent will be a
4892 `js2-expr-stmt-node'.
4893 Functions aren't included in the check."
4894 (memq (js2-node-type node) js2-stmt-node-types))
4895
4896 (defsubst js2-mode-find-first-stmt (node)
4897 "Search upward starting from NODE looking for a statement.
4898 For purposes of this function, a `js2-function-node' counts."
4899 (while (not (or (js2-stmt-node-p node)
4900 (js2-function-node-p node)))
4901 (setq node (js2-node-parent node)))
4902 node)
4903
4904 (defun js2-node-parent-stmt (node)
4905 "Return the node's first ancestor that is a statement.
4906 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4907 appearing in a statement context will have a parent that is a
4908 `js2-expr-stmt-node' that will be returned by this function."
4909 (let ((parent (js2-node-parent node)))
4910 (if (or (null parent)
4911 (js2-stmt-node-p parent)
4912 (and (js2-function-node-p parent)
4913 (not (eq (js2-function-node-form parent)
4914 'FUNCTION_EXPRESSION))))
4915 parent
4916 (js2-node-parent-stmt parent))))
4917
4918 ;; In the Mozilla Rhino sources, Roshan James writes:
4919 ;; Does consistent-return analysis on the function body when strict mode is
4920 ;; enabled.
4921 ;;
4922 ;; function (x) { return (x+1) }
4923 ;;
4924 ;; is ok, but
4925 ;;
4926 ;; function (x) { if (x < 0) return (x+1); }
4927 ;;
4928 ;; is not because the function can potentially return a value when the
4929 ;; condition is satisfied and if not, the function does not explicitly
4930 ;; return a value.
4931 ;;
4932 ;; This extends to checking mismatches such as "return" and "return <value>"
4933 ;; used in the same function. Warnings are not emitted if inconsistent
4934 ;; returns exist in code that can be statically shown to be unreachable.
4935 ;; Ex.
4936 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4937 ;;
4938 ;; emits no warning. However if the loop had a break statement, then a
4939 ;; warning would be emitted.
4940 ;;
4941 ;; The consistency analysis looks at control structures such as loops, ifs,
4942 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4943 ;; warns the user about an inconsistent set of termination possibilities.
4944 ;;
4945 ;; These flags enumerate the possible ways a statement/function can
4946 ;; terminate. These flags are used by endCheck() and by the Parser to
4947 ;; detect inconsistent return usage.
4948 ;;
4949 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4950 ;; able to execute (example: throw, continue)
4951 ;;
4952 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4953 ;; next one. Statement such as return dont. A compound statement may have
4954 ;; some branch that drops off control to the next statement.
4955 ;;
4956 ;; END_RETURNS indicates that the statement can return with no value.
4957 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4958 ;;
4959 ;; A compound statement such as
4960 ;; if (condition) {
4961 ;; return value;
4962 ;; }
4963 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4964
4965 (defconst js2-END_UNREACHED 0)
4966 (defconst js2-END_DROPS_OFF 1)
4967 (defconst js2-END_RETURNS 2)
4968 (defconst js2-END_RETURNS_VALUE 4)
4969 (defconst js2-END_YIELDS 8)
4970
4971 (defun js2-has-consistent-return-usage (node)
4972 "Check that every return usage in a function body is consistent.
4973 Returns t if the function satisfies strict mode requirement."
4974 (let ((n (js2-end-check node)))
4975 ;; either it doesn't return a value in any branch...
4976 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4977 ;; or it returns a value (or is unreached) at every branch
4978 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4979 js2-END_RETURNS
4980 js2-END_YIELDS)))))
4981
4982 (defun js2-end-check-if (node)
4983 "Returns in the then and else blocks must be consistent with each other.
4984 If there is no else block, then the return statement can fall through.
4985 Returns logical OR of END_* flags"
4986 (let ((th (js2-if-node-then-part node))
4987 (el (js2-if-node-else-part node)))
4988 (if (null th)
4989 js2-END_UNREACHED
4990 (logior (js2-end-check th) (if el
4991 (js2-end-check el)
4992 js2-END_DROPS_OFF)))))
4993
4994 (defun js2-end-check-switch (node)
4995 "Consistency of return statements is checked between the case statements.
4996 If there is no default, then the switch can fall through. If there is a
4997 default, we check to see if all code paths in the default return or if
4998 there is a code path that can fall through.
4999 Returns logical OR of END_* flags."
5000 (let ((rv js2-END_UNREACHED)
5001 default-case)
5002 ;; examine the cases
5003 (catch 'break
5004 (dolist (c (js2-switch-node-cases node))
5005 (if (js2-case-node-expr c)
5006 (js2-set-flag rv (js2-end-check-block c))
5007 (setq default-case c)
5008 (throw 'break nil))))
5009 ;; we don't care how the cases drop into each other
5010 (js2-clear-flag rv js2-END_DROPS_OFF)
5011 ;; examine the default
5012 (js2-set-flag rv (if default-case
5013 (js2-end-check default-case)
5014 js2-END_DROPS_OFF))
5015 rv))
5016
5017 (defun js2-end-check-try (node)
5018 "If the block has a finally, return consistency is checked in the
5019 finally block. If all code paths in the finally return, then the
5020 returns in the try-catch blocks don't matter. If there is a code path
5021 that does not return or if there is no finally block, the returns
5022 of the try and catch blocks are checked for mismatch.
5023 Returns logical OR of END_* flags."
5024 (let ((finally (js2-try-node-finally-block node))
5025 rv)
5026 ;; check the finally if it exists
5027 (setq rv (if finally
5028 (js2-end-check (js2-finally-node-body finally))
5029 js2-END_DROPS_OFF))
5030 ;; If the finally block always returns, then none of the returns
5031 ;; in the try or catch blocks matter.
5032 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5033 (js2-clear-flag rv js2-END_DROPS_OFF)
5034 ;; examine the try block
5035 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5036 ;; check each catch block
5037 (dolist (cb (js2-try-node-catch-clauses node))
5038 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5039 rv))
5040
5041 (defun js2-end-check-loop (node)
5042 "Return statement in the loop body must be consistent. The default
5043 assumption for any kind of a loop is that it will eventually terminate.
5044 The only exception is a loop with a constant true condition. Code that
5045 follows such a loop is examined only if one can statically determine
5046 that there is a break out of the loop.
5047
5048 for(... ; ... ; ...) {}
5049 for(... in ... ) {}
5050 while(...) { }
5051 do { } while(...)
5052
5053 Returns logical OR of END_* flags."
5054 (let ((rv (js2-end-check (js2-loop-node-body node)))
5055 (condition (cond
5056 ((js2-while-node-p node)
5057 (js2-while-node-condition node))
5058 ((js2-do-node-p node)
5059 (js2-do-node-condition node))
5060 ((js2-for-node-p node)
5061 (js2-for-node-condition node)))))
5062
5063 ;; check to see if the loop condition is always true
5064 (if (and condition
5065 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5066 (js2-clear-flag rv js2-END_DROPS_OFF))
5067
5068 ;; look for effect of breaks
5069 (js2-set-flag rv (js2-node-get-prop node
5070 'CONTROL_BLOCK_PROP
5071 js2-END_UNREACHED))
5072 rv))
5073
5074 (defun js2-end-check-block (node)
5075 "A general block of code is examined statement by statement.
5076 If any statement (even a compound one) returns in all branches, then
5077 subsequent statements are not examined.
5078 Returns logical OR of END_* flags."
5079 (let* ((rv js2-END_DROPS_OFF)
5080 (kids (js2-block-node-kids node))
5081 (n (car kids)))
5082 ;; Check each statment. If the statement can continue onto the next
5083 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5084 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5085 (js2-clear-flag rv js2-END_DROPS_OFF)
5086 (js2-set-flag rv (js2-end-check n))
5087 (setq kids (cdr kids)
5088 n (car kids)))
5089 rv))
5090
5091 (defun js2-end-check-label (node)
5092 "A labeled statement implies that there may be a break to the label.
5093 The function processes the labeled statement and then checks the
5094 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5095 particular label.
5096 Returns logical OR of END_* flags."
5097 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5098 (logior rv (js2-node-get-prop node
5099 'CONTROL_BLOCK_PROP
5100 js2-END_UNREACHED))))
5101
5102 (defun js2-end-check-break (node)
5103 "When a break is encountered annotate the statement being broken
5104 out of by setting its CONTROL_BLOCK_PROP property.
5105 Returns logical OR of END_* flags."
5106 (and (js2-break-node-target node)
5107 (js2-node-set-prop (js2-break-node-target node)
5108 'CONTROL_BLOCK_PROP
5109 js2-END_DROPS_OFF))
5110 js2-END_UNREACHED)
5111
5112 (defun js2-end-check (node)
5113 "Examine the body of a function, doing a basic reachability analysis.
5114 Returns a combination of flags END_* flags that indicate
5115 how the function execution can terminate. These constitute only the
5116 pessimistic set of termination conditions. It is possible that at
5117 runtime certain code paths will never be actually taken. Hence this
5118 analysis will flag errors in cases where there may not be errors.
5119 Returns logical OR of END_* flags"
5120 (let (kid)
5121 (cond
5122 ((js2-break-node-p node)
5123 (js2-end-check-break node))
5124 ((js2-expr-stmt-node-p node)
5125 (if (setq kid (js2-expr-stmt-node-expr node))
5126 (js2-end-check kid)
5127 js2-END_DROPS_OFF))
5128 ((or (js2-continue-node-p node)
5129 (js2-throw-node-p node))
5130 js2-END_UNREACHED)
5131 ((js2-return-node-p node)
5132 (if (setq kid (js2-return-node-retval node))
5133 js2-END_RETURNS_VALUE
5134 js2-END_RETURNS))
5135 ((js2-loop-node-p node)
5136 (js2-end-check-loop node))
5137 ((js2-switch-node-p node)
5138 (js2-end-check-switch node))
5139 ((js2-labeled-stmt-node-p node)
5140 (js2-end-check-label node))
5141 ((js2-if-node-p node)
5142 (js2-end-check-if node))
5143 ((js2-try-node-p node)
5144 (js2-end-check-try node))
5145 ((js2-block-node-p node)
5146 (if (null (js2-block-node-kids node))
5147 js2-END_DROPS_OFF
5148 (js2-end-check-block node)))
5149 ((js2-yield-node-p node)
5150 js2-END_YIELDS)
5151 (t
5152 js2-END_DROPS_OFF))))
5153
5154 (defun js2-always-defined-boolean-p (node)
5155 "Check if NODE always evaluates to true or false in boolean context.
5156 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5157 nor always false."
5158 (let ((tt (js2-node-type node))
5159 num)
5160 (cond
5161 ((or (= tt js2-FALSE) (= tt js2-NULL))
5162 'ALWAYS_FALSE)
5163 ((= tt js2-TRUE)
5164 'ALWAYS_TRUE)
5165 ((= tt js2-NUMBER)
5166 (setq num (js2-number-node-num-value node))
5167 (if (and (not (eq num 0.0e+NaN))
5168 (not (zerop num)))
5169 'ALWAYS_TRUE
5170 'ALWAYS_FALSE))
5171 (t
5172 nil))))
5173
5174 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5175 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5176
5177 (defvar js2-tokens nil
5178 "List of all defined token names.") ; initialized in `js2-token-names'
5179
5180 (defconst js2-token-names
5181 (let* ((names (make-vector js2-num-tokens -1))
5182 (case-fold-search nil) ; only match js2-UPPER_CASE
5183 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5184 (loop for sym in syms
5185 for i from 0
5186 do
5187 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5188 (not (boundp sym)))
5189 (aset names (symbol-value sym) ; code, e.g. 152
5190 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5191 (push sym js2-tokens)))
5192 names)
5193 "Vector mapping int values to token string names, sans `js2-' prefix.")
5194
5195 (defun js2-token-name (tok)
5196 "Return a string name for TOK, a token symbol or code.
5197 Signals an error if it's not a recognized token."
5198 (let ((code tok))
5199 (if (symbolp tok)
5200 (setq code (symbol-value tok)))
5201 (if (eq code -1)
5202 "ERROR"
5203 (if (and (numberp code)
5204 (not (minusp code))
5205 (< code js2-num-tokens))
5206 (aref js2-token-names code)
5207 (error "Invalid token: %s" code)))))
5208
5209 (defsubst js2-token-sym (tok)
5210 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5211 (intern (js2-token-name tok)))
5212
5213 (defconst js2-token-codes
5214 (let ((table (make-hash-table :test 'eq :size 256)))
5215 (loop for name across js2-token-names
5216 for sym = (intern (concat "js2-" name))
5217 do
5218 (puthash sym (symbol-value sym) table))
5219 ;; clean up a few that are "wrong" in Rhino's token codes
5220 (puthash 'js2-DELETE js2-DELPROP table)
5221 table)
5222 "Hashtable mapping token symbols to their bytecodes.")
5223
5224 (defsubst js2-token-code (sym)
5225 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5226 (or (gethash sym js2-token-codes)
5227 (error "Invalid token symbol: %s " sym))) ; signal code bug
5228
5229 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5230 (setq js2-token-end js2-ts-cursor)
5231 (js2-report-error msg nil
5232 (or beg js2-token-beg)
5233 (or len (- js2-token-end js2-token-beg)))
5234 (unless no-throw
5235 (throw 'return js2-ERROR)))
5236
5237 (defsubst js2-get-string-from-buffer ()
5238 "Reverse the char accumulator and return it as a string."
5239 (setq js2-token-end js2-ts-cursor)
5240 (if js2-ts-string-buffer
5241 (apply #'string (nreverse js2-ts-string-buffer))
5242 ""))
5243
5244 ;; TODO: could potentially avoid a lot of consing by allocating a
5245 ;; char buffer the way Rhino does.
5246 (defsubst js2-add-to-string (c)
5247 (push c js2-ts-string-buffer))
5248
5249 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5250 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5251 ;; any other character: when it's not part of the current token, we
5252 ;; unget it, allowing it to be read again by the following call.
5253 (defsubst js2-unget-char ()
5254 (decf js2-ts-cursor))
5255
5256 ;; Rhino distinguishes \r and \n line endings. We don't need to
5257 ;; because we only scan from Emacs buffers, which always use \n.
5258 (defsubst js2-get-char ()
5259 "Read and return the next character from the input buffer.
5260 Increments `js2-ts-lineno' if the return value is a newline char.
5261 Updates `js2-ts-cursor' to the point after the returned char.
5262 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5263 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5264 (let (c)
5265 ;; check for end of buffer
5266 (if (>= js2-ts-cursor (point-max))
5267 (setq js2-ts-hit-eof t
5268 js2-ts-cursor (1+ js2-ts-cursor)
5269 c js2-EOF_CHAR) ; return value
5270 ;; otherwise read next char
5271 (setq c (char-before (incf js2-ts-cursor)))
5272 ;; if we read a newline, update counters
5273 (if (= c ?\n)
5274 (setq js2-ts-line-start js2-ts-cursor
5275 js2-ts-lineno (1+ js2-ts-lineno)))
5276 ;; TODO: skip over format characters
5277 c)))
5278
5279 (defsubst js2-read-unicode-escape ()
5280 "Read a \\uNNNN sequence from the input.
5281 Assumes the ?\ and ?u have already been read.
5282 Returns the unicode character, or nil if it wasn't a valid character.
5283 Doesn't change the values of any scanner variables."
5284 ;; I really wish I knew a better way to do this, but I can't
5285 ;; find the Emacs function that takes a 16-bit int and converts
5286 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5287 ;; Have to first check that it's 4 hex characters or it may stop
5288 ;; the read early.
5289 (ignore-errors
5290 (let ((s (buffer-substring-no-properties js2-ts-cursor
5291 (+ 4 js2-ts-cursor))))
5292 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5293 (read (concat "?\\u" s))))))
5294
5295 (defsubst js2-match-char (test)
5296 "Consume and return next character if it matches TEST, a character.
5297 Returns nil and consumes nothing if TEST is not the next character."
5298 (let ((c (js2-get-char)))
5299 (if (eq c test)
5300 t
5301 (js2-unget-char)
5302 nil)))
5303
5304 (defsubst js2-peek-char ()
5305 (prog1
5306 (js2-get-char)
5307 (js2-unget-char)))
5308
5309 (defsubst js2-java-identifier-start-p (c)
5310 (or
5311 (memq c '(?$ ?_))
5312 (js2-char-uppercase-p c)
5313 (js2-char-lowercase-p c)))
5314
5315 (defsubst js2-java-identifier-part-p (c)
5316 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5317 ;; TODO: make me Unicode-friendly. See comments above.
5318 (or
5319 (memq c '(?$ ?_))
5320 (js2-char-uppercase-p c)
5321 (js2-char-lowercase-p c)
5322 (and (>= c ?0) (<= c ?9))))
5323
5324 (defsubst js2-alpha-p (c)
5325 (cond ((and (<= ?A c) (<= c ?Z)) t)
5326 ((and (<= ?a c) (<= c ?z)) t)
5327 (t nil)))
5328
5329 (defsubst js2-digit-p (c)
5330 (and (<= ?0 c) (<= c ?9)))
5331
5332 (defsubst js2-js-space-p (c)
5333 (if (<= c 127)
5334 (memq c '(#x20 #x9 #xB #xC #xD))
5335 (or
5336 (eq c #xA0)
5337 ;; TODO: change this nil to check for Unicode space character
5338 nil)))
5339
5340 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5341
5342 (defsubst js2-skip-line ()
5343 "Skip to end of line"
5344 (let (c)
5345 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5346 (js2-unget-char)
5347 (setq js2-token-end js2-ts-cursor)))
5348
5349 (defun js2-init-scanner (&optional buf line)
5350 "Create token stream for BUF starting on LINE.
5351 BUF defaults to current-buffer and line defaults to 1.
5352
5353 A buffer can only have one scanner active at a time, which yields
5354 dramatically simpler code than using a defstruct. If you need to
5355 have simultaneous scanners in a buffer, copy the regions to scan
5356 into temp buffers."
5357 (save-excursion
5358 (when buf
5359 (set-buffer buf))
5360 (setq js2-ts-dirty-line nil
5361 js2-ts-regexp-flags nil
5362 js2-ts-string ""
5363 js2-ts-number nil
5364 js2-ts-hit-eof nil
5365 js2-ts-line-start 0
5366 js2-ts-lineno (or line 1)
5367 js2-ts-line-end-char -1
5368 js2-ts-cursor (point-min)
5369 js2-ts-is-xml-attribute nil
5370 js2-ts-xml-is-tag-content nil
5371 js2-ts-xml-open-tags-count 0
5372 js2-ts-string-buffer nil)))
5373
5374 ;; This function uses the cached op, string and number fields in
5375 ;; TokenStream; if getToken has been called since the passed token
5376 ;; was scanned, the op or string printed may be incorrect.
5377 (defun js2-token-to-string (token)
5378 ;; Not sure where this function is used in Rhino. Not tested.
5379 (if (not js2-debug-print-trees)
5380 ""
5381 (let ((name (js2-token-name token)))
5382 (cond
5383 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5384 (concat name " `" js2-ts-string "'"))
5385 ((eq token js2-NUMBER)
5386 (format "NUMBER %g" js2-ts-number))
5387 (t
5388 name)))))
5389
5390 (defconst js2-keywords
5391 '(break
5392 case catch const continue
5393 debugger default delete do
5394 else enum
5395 false finally for function
5396 if in instanceof import
5397 let
5398 new null
5399 return
5400 switch
5401 this throw true try typeof
5402 var void
5403 while with
5404 yield))
5405
5406 ;; Token names aren't exactly the same as the keywords, unfortunately.
5407 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5408 (defconst js2-kwd-tokens
5409 (let ((table (make-vector js2-num-tokens nil))
5410 (tokens
5411 (list js2-BREAK
5412 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5413 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5414 js2-ELSE
5415 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5416 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5417 js2-LET
5418 js2-NEW js2-NULL
5419 js2-RETURN
5420 js2-SWITCH
5421 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5422 js2-VAR
5423 js2-WHILE js2-WITH
5424 js2-YIELD)))
5425 (dolist (i tokens)
5426 (aset table i 'font-lock-keyword-face))
5427 (aset table js2-STRING 'font-lock-string-face)
5428 (aset table js2-REGEXP 'font-lock-string-face)
5429 (aset table js2-COMMENT 'font-lock-comment-face)
5430 (aset table js2-THIS 'font-lock-builtin-face)
5431 (aset table js2-VOID 'font-lock-constant-face)
5432 (aset table js2-NULL 'font-lock-constant-face)
5433 (aset table js2-TRUE 'font-lock-constant-face)
5434 (aset table js2-FALSE 'font-lock-constant-face)
5435 table)
5436 "Vector whose values are non-nil for tokens that are keywords.
5437 The values are default faces to use for highlighting the keywords.")
5438
5439 (defconst js2-reserved-words
5440 '(abstract
5441 boolean byte
5442 char class
5443 double
5444 enum export extends
5445 final float
5446 goto
5447 implements import int interface
5448 long
5449 native
5450 package private protected public
5451 short static super synchronized
5452 throws transient
5453 volatile))
5454
5455 (defconst js2-keyword-names
5456 (let ((table (make-hash-table :test 'equal)))
5457 (loop for k in js2-keywords
5458 do (puthash
5459 (symbol-name k) ; instanceof
5460 (intern (concat "js2-"
5461 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5462 table))
5463 table)
5464 "JavaScript keywords by name, mapped to their symbols.")
5465
5466 (defconst js2-reserved-word-names
5467 (let ((table (make-hash-table :test 'equal)))
5468 (loop for k in js2-reserved-words
5469 do
5470 (puthash (symbol-name k) 'js2-RESERVED table))
5471 table)
5472 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5473
5474 (defsubst js2-collect-string (buf)
5475 "Convert BUF, a list of chars, to a string.
5476 Reverses BUF before converting."
5477 (cond
5478 ((stringp buf)
5479 buf)
5480 ((null buf) ; for emacs21 compat
5481 "")
5482 (t
5483 (if buf
5484 (apply #'string (nreverse buf))
5485 ""))))
5486
5487 (defun js2-string-to-keyword (s)
5488 "Return token for S, a string, if S is a keyword or reserved word.
5489 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5490 (or (gethash s js2-keyword-names)
5491 (gethash s js2-reserved-word-names)))
5492
5493 (defsubst js2-ts-set-char-token-bounds ()
5494 "Used when next token is one character."
5495 (setq js2-token-beg (1- js2-ts-cursor)
5496 js2-token-end js2-ts-cursor))
5497
5498 (defsubst js2-ts-return (token)
5499 "Return an N-character TOKEN from `js2-get-token'.
5500 Updates `js2-token-end' accordingly."
5501 (setq js2-token-end js2-ts-cursor)
5502 (throw 'return token))
5503
5504 (defsubst js2-x-digit-to-int (c accumulator)
5505 "Build up a hex number.
5506 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5507 corresponding number. Otherwise return -1."
5508 (catch 'return
5509 (catch 'check
5510 ;; Use 0..9 < A..Z < a..z
5511 (cond
5512 ((<= c ?9)
5513 (decf c ?0)
5514 (if (<= 0 c)
5515 (throw 'check nil)))
5516 ((<= c ?F)
5517 (when (<= ?A c)
5518 (decf c (- ?A 10))
5519 (throw 'check nil)))
5520 ((<= c ?f)
5521 (when (<= ?a c)
5522 (decf c (- ?a 10))
5523 (throw 'check nil))))
5524 (throw 'return -1))
5525 (logior c (lsh accumulator 4))))
5526
5527 (defun js2-get-token ()
5528 "Return next JavaScript token, an int such as js2-RETURN."
5529 (let (c
5530 c1
5531 identifier-start
5532 is-unicode-escape-start
5533 contains-escape
5534 escape-val
5535 escape-start
5536 str
5537 result
5538 base
5539 is-integer
5540 quote-char
5541 val
5542 look-for-slash
5543 continue)
5544 (catch 'return
5545 (while t
5546 ;; Eat whitespace, possibly sensitive to newlines.
5547 (setq continue t)
5548 (while continue
5549 (setq c (js2-get-char))
5550 (cond
5551 ((eq c js2-EOF_CHAR)
5552 (js2-ts-set-char-token-bounds)
5553 (throw 'return js2-EOF))
5554 ((eq c ?\n)
5555 (js2-ts-set-char-token-bounds)
5556 (setq js2-ts-dirty-line nil)
5557 (throw 'return js2-EOL))
5558 ((not (js2-js-space-p c))
5559 (if (/= c ?-) ; in case end of HTML comment
5560 (setq js2-ts-dirty-line t))
5561 (setq continue nil))))
5562 ;; Assume the token will be 1 char - fixed up below.
5563 (js2-ts-set-char-token-bounds)
5564 (when (eq c ?@)
5565 (throw 'return js2-XMLATTR))
5566 ;; identifier/keyword/instanceof?
5567 ;; watch out for starting with a <backslash>
5568 (cond
5569 ((eq c ?\\)
5570 (setq c (js2-get-char))
5571 (if (eq c ?u)
5572 (setq identifier-start t
5573 is-unicode-escape-start t
5574 js2-ts-string-buffer nil)
5575 (setq identifier-start nil)
5576 (js2-unget-char)
5577 (setq c ?\\)))
5578 (t
5579 (when (setq identifier-start (js2-java-identifier-start-p c))
5580 (setq js2-ts-string-buffer nil)
5581 (js2-add-to-string c))))
5582 (when identifier-start
5583 (setq contains-escape is-unicode-escape-start)
5584 (catch 'break
5585 (while t
5586 (if is-unicode-escape-start
5587 ;; strictly speaking we should probably push-back
5588 ;; all the bad characters if the <backslash>uXXXX
5589 ;; sequence is malformed. But since there isn't a
5590 ;; correct context(is there?) for a bad Unicode
5591 ;; escape sequence in an identifier, we can report
5592 ;; an error here.
5593 (progn
5594 (setq escape-val 0)
5595 (dotimes (i 4)
5596 (setq c (js2-get-char)
5597 escape-val (js2-x-digit-to-int c escape-val))
5598 ;; Next check takes care of c < 0 and bad escape
5599 (if (minusp escape-val)
5600 (throw 'break nil)))
5601 (if (minusp escape-val)
5602 (js2-report-scan-error "msg.invalid.escape" t))
5603 (js2-add-to-string escape-val)
5604 (setq is-unicode-escape-start nil))
5605 (setq c (js2-get-char))
5606 (cond
5607 ((eq c ?\\)
5608 (setq c (js2-get-char))
5609 (if (eq c ?u)
5610 (setq is-unicode-escape-start t
5611 contains-escape t)
5612 (js2-report-scan-error "msg.illegal.character" t)))
5613 (t
5614 (if (or (eq c js2-EOF_CHAR)
5615 (not (js2-java-identifier-part-p c)))
5616 (throw 'break nil))
5617 (js2-add-to-string c))))))
5618 (js2-unget-char)
5619 (setq str (js2-get-string-from-buffer))
5620 (unless contains-escape
5621 ;; OPT we shouldn't have to make a string (object!) to
5622 ;; check if it's a keyword.
5623 ;; Return the corresponding token if it's a keyword
5624 (when (setq result (js2-string-to-keyword str))
5625 (if (and (< js2-language-version 170)
5626 (memq result '(js2-LET js2-YIELD)))
5627 ;; LET and YIELD are tokens only in 1.7 and later
5628 (setq result 'js2-NAME))
5629 (if (not (eq result 'js2-RESERVED))
5630 (throw 'return (js2-token-code result)))
5631 (js2-report-warning "msg.reserved.keyword" str)))
5632 ;; If we want to intern these as Rhino does, just use (intern str)
5633 (setq js2-ts-string str)
5634 (throw 'return js2-NAME)) ; end identifier/kwd check
5635 ;; is it a number?
5636 (when (or (js2-digit-p c)
5637 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5638 (setq js2-ts-string-buffer nil
5639 base 10)
5640 (when (eq c ?0)
5641 (setq c (js2-get-char))
5642 (cond
5643 ((or (eq c ?x) (eq c ?X))
5644 (setq base 16)
5645 (setq c (js2-get-char)))
5646 ((js2-digit-p c)
5647 (setq base 8))
5648 (t
5649 (js2-add-to-string ?0))))
5650 (if (eq base 16)
5651 (while (<= 0 (js2-x-digit-to-int c 0))
5652 (js2-add-to-string c)
5653 (setq c (js2-get-char)))
5654 (while (and (<= ?0 c) (<= c ?9))
5655 ;; We permit 08 and 09 as decimal numbers, which
5656 ;; makes our behavior a superset of the ECMA
5657 ;; numeric grammar. We might not always be so
5658 ;; permissive, so we warn about it.
5659 (when (and (eq base 8) (>= c ?8))
5660 (js2-report-warning "msg.bad.octal.literal"
5661 (if (eq c ?8) "8" "9"))
5662 (setq base 10))
5663 (js2-add-to-string c)
5664 (setq c (js2-get-char))))
5665 (setq is-integer t)
5666 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5667 (setq is-integer nil)
5668 (when (eq c ?.)
5669 (loop do
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char))
5672 while (js2-digit-p c)))
5673 (when (memq c '(?e ?E))
5674 (js2-add-to-string c)
5675 (setq c (js2-get-char))
5676 (when (memq c '(?+ ?-))
5677 (js2-add-to-string c)
5678 (setq c (js2-get-char)))
5679 (unless (js2-digit-p c)
5680 (js2-report-scan-error "msg.missing.exponent" t))
5681 (loop do
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char))
5684 while (js2-digit-p c))))
5685 (js2-unget-char)
5686 (setq js2-ts-string (js2-get-string-from-buffer)
5687 js2-ts-number
5688 (if (and (eq base 10) (not is-integer))
5689 (string-to-number js2-ts-string)
5690 ;; TODO: call runtime number-parser. Some of it is in
5691 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5692 (string-to-number js2-ts-string)))
5693 (throw 'return js2-NUMBER))
5694 ;; is it a string?
5695 (when (memq c '(?\" ?\'))
5696 ;; We attempt to accumulate a string the fast way, by
5697 ;; building it directly out of the reader. But if there
5698 ;; are any escaped characters in the string, we revert to
5699 ;; building it out of a string buffer.
5700 (setq quote-char c
5701 js2-ts-string-buffer nil
5702 c (js2-get-char))
5703 (catch 'break
5704 (while (/= c quote-char)
5705 (catch 'continue
5706 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5707 (js2-unget-char)
5708 (setq js2-token-end js2-ts-cursor)
5709 (js2-report-error "msg.unterminated.string.lit")
5710 (throw 'return js2-STRING))
5711 (when (eq c ?\\)
5712 ;; We've hit an escaped character
5713 (setq c (js2-get-char))
5714 (case c
5715 (?b (setq c ?\b))
5716 (?f (setq c ?\f))
5717 (?n (setq c ?\n))
5718 (?r (setq c ?\r))
5719 (?t (setq c ?\t))
5720 (?v (setq c ?\v))
5721 (?u
5722 (setq c1 (js2-read-unicode-escape))
5723 (if js2-parse-ide-mode
5724 (if c1
5725 (progn
5726 ;; just copy the string in IDE-mode
5727 (js2-add-to-string ?\\)
5728 (js2-add-to-string ?u)
5729 (dotimes (i 3)
5730 (js2-add-to-string (js2-get-char)))
5731 (setq c (js2-get-char))) ; added at end of loop
5732 ;; flag it as an invalid escape
5733 (js2-report-warning "msg.invalid.escape"
5734 nil (- js2-ts-cursor 2) 6))
5735 ;; Get 4 hex digits; if the u escape is not
5736 ;; followed by 4 hex digits, use 'u' + the
5737 ;; literal character sequence that follows.
5738 (js2-add-to-string ?u)
5739 (setq escape-val 0)
5740 (dotimes (i 4)
5741 (setq c (js2-get-char)
5742 escape-val (js2-x-digit-to-int c escape-val))
5743 (if (minusp escape-val)
5744 (throw 'continue nil))
5745 (js2-add-to-string c))
5746 ;; prepare for replace of stored 'u' sequence by escape value
5747 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5748 c escape-val)))
5749 (?x
5750 ;; Get 2 hex digits, defaulting to 'x'+literal
5751 ;; sequence, as above.
5752 (setq c (js2-get-char)
5753 escape-val (js2-x-digit-to-int c 0))
5754 (if (minusp escape-val)
5755 (progn
5756 (js2-add-to-string ?x)
5757 (throw 'continue nil))
5758 (setq c1 c
5759 c (js2-get-char)
5760 escape-val (js2-x-digit-to-int c escape-val))
5761 (if (minusp escape-val)
5762 (progn
5763 (js2-add-to-string ?x)
5764 (js2-add-to-string c1)
5765 (throw 'continue nil))
5766 ;; got 2 hex digits
5767 (setq c escape-val))))
5768 (?\n
5769 ;; Remove line terminator after escape to follow
5770 ;; SpiderMonkey and C/C++
5771 (setq c (js2-get-char))
5772 (throw 'continue nil))
5773 (t
5774 (when (and (<= ?0 c) (< c ?8))
5775 (setq val (- c ?0)
5776 c (js2-get-char))
5777 (when (and (<= ?0 c) (< c ?8))
5778 (setq val (- (+ (* 8 val) c) ?0)
5779 c (js2-get-char))
5780 (when (and (<= ?0 c)
5781 (< c ?8)
5782 (< val #o37))
5783 ;; c is 3rd char of octal sequence only
5784 ;; if the resulting val <= 0377
5785 (setq val (- (+ (* 8 val) c) ?0)
5786 c (js2-get-char))))
5787 (js2-unget-char)
5788 (setq c val)))))
5789 (js2-add-to-string c)
5790 (setq c (js2-get-char)))))
5791 (setq js2-ts-string (js2-get-string-from-buffer))
5792 (throw 'return js2-STRING))
5793 (case c
5794 (?\;
5795 (throw 'return js2-SEMI))
5796 (?\[
5797 (throw 'return js2-LB))
5798 (?\]
5799 (throw 'return js2-RB))
5800 (?{
5801 (throw 'return js2-LC))
5802 (?}
5803 (throw 'return js2-RC))
5804 (?\(
5805 (throw 'return js2-LP))
5806 (?\)
5807 (throw 'return js2-RP))
5808 (?,
5809 (throw 'return js2-COMMA))
5810 (??
5811 (throw 'return js2-HOOK))
5812 (?:
5813 (if (js2-match-char ?:)
5814 (js2-ts-return js2-COLONCOLON)
5815 (throw 'return js2-COLON)))
5816 (?.
5817 (if (js2-match-char ?.)
5818 (js2-ts-return js2-DOTDOT)
5819 (if (js2-match-char ?\()
5820 (js2-ts-return js2-DOTQUERY)
5821 (throw 'return js2-DOT))))
5822 (?|
5823 (if (js2-match-char ?|)
5824 (throw 'return js2-OR)
5825 (if (js2-match-char ?=)
5826 (js2-ts-return js2-ASSIGN_BITOR)
5827 (throw 'return js2-BITOR))))
5828 (?^
5829 (if (js2-match-char ?=)
5830 (js2-ts-return js2-ASSIGN_BITOR)
5831 (throw 'return js2-BITXOR)))
5832 (?&
5833 (if (js2-match-char ?&)
5834 (throw 'return js2-AND)
5835 (if (js2-match-char ?=)
5836 (js2-ts-return js2-ASSIGN_BITAND)
5837 (throw 'return js2-BITAND))))
5838 (?=
5839 (if (js2-match-char ?=)
5840 (if (js2-match-char ?=)
5841 (js2-ts-return js2-SHEQ)
5842 (throw 'return js2-EQ))
5843 (throw 'return js2-ASSIGN)))
5844 (?!
5845 (if (js2-match-char ?=)
5846 (if (js2-match-char ?=)
5847 (js2-ts-return js2-SHNE)
5848 (js2-ts-return js2-NE))
5849 (throw 'return js2-NOT)))
5850 (?<
5851 ;; NB:treat HTML begin-comment as comment-till-eol
5852 (when (js2-match-char ?!)
5853 (when (js2-match-char ?-)
5854 (when (js2-match-char ?-)
5855 (js2-skip-line)
5856 (setq js2-ts-comment-type 'html)
5857 (throw 'return js2-COMMENT)))
5858 (js2-unget-char))
5859 (if (js2-match-char ?<)
5860 (if (js2-match-char ?=)
5861 (js2-ts-return js2-ASSIGN_LSH)
5862 (js2-ts-return js2-LSH))
5863 (if (js2-match-char ?=)
5864 (js2-ts-return js2-LE)
5865 (throw 'return js2-LT))))
5866 (?>
5867 (if (js2-match-char ?>)
5868 (if (js2-match-char ?>)
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-ASSIGN_URSH)
5871 (js2-ts-return js2-URSH))
5872 (if (js2-match-char ?=)
5873 (js2-ts-return js2-ASSIGN_RSH)
5874 (js2-ts-return js2-RSH)))
5875 (if (js2-match-char ?=)
5876 (js2-ts-return js2-GE)
5877 (throw 'return js2-GT))))
5878 (?*
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_MUL)
5881 (throw 'return js2-MUL)))
5882 (?/
5883 ;; is it a // comment?
5884 (when (js2-match-char ?/)
5885 (setq js2-token-beg (- js2-ts-cursor 2))
5886 (js2-skip-line)
5887 (setq js2-ts-comment-type 'line)
5888 ;; include newline so highlighting goes to end of window
5889 (incf js2-token-end)
5890 (throw 'return js2-COMMENT))
5891 ;; is it a /* comment?
5892 (when (js2-match-char ?*)
5893 (setq look-for-slash nil
5894 js2-token-beg (- js2-ts-cursor 2)
5895 js2-ts-comment-type
5896 (if (js2-match-char ?*)
5897 (progn
5898 (setq look-for-slash t)
5899 'jsdoc)
5900 'block))
5901 (while t
5902 (setq c (js2-get-char))
5903 (cond
5904 ((eq c js2-EOF_CHAR)
5905 (setq js2-token-end (1- js2-ts-cursor))
5906 (js2-report-error "msg.unterminated.comment")
5907 (throw 'return js2-COMMENT))
5908 ((eq c ?*)
5909 (setq look-for-slash t))
5910 ((eq c ?/)
5911 (if look-for-slash
5912 (js2-ts-return js2-COMMENT)))
5913 (t
5914 (setq look-for-slash nil
5915 js2-token-end js2-ts-cursor)))))
5916 (if (js2-match-char ?=)
5917 (js2-ts-return js2-ASSIGN_DIV)
5918 (throw 'return js2-DIV)))
5919 (?#
5920 (when js2-skip-preprocessor-directives
5921 (js2-skip-line)
5922 (setq js2-ts-comment-type 'preprocessor
5923 js2-token-end js2-ts-cursor)
5924 (throw 'return js2-COMMENT))
5925 (throw 'return js2-ERROR))
5926 (?%
5927 (if (js2-match-char ?=)
5928 (js2-ts-return js2-ASSIGN_MOD)
5929 (throw 'return js2-MOD)))
5930 (?~
5931 (throw 'return js2-BITNOT))
5932 (?+
5933 (if (js2-match-char ?=)
5934 (js2-ts-return js2-ASSIGN_ADD)
5935 (if (js2-match-char ?+)
5936 (js2-ts-return js2-INC)
5937 (throw 'return js2-ADD))))
5938 (?-
5939 (cond
5940 ((js2-match-char ?=)
5941 (setq c js2-ASSIGN_SUB))
5942 ((js2-match-char ?-)
5943 (unless js2-ts-dirty-line
5944 ;; treat HTML end-comment after possible whitespace
5945 ;; after line start as comment-until-eol
5946 (when (js2-match-char ?>)
5947 (js2-skip-line)
5948 (setq js2-ts-comment-type 'html)
5949 (throw 'return js2-COMMENT)))
5950 (setq c js2-DEC))
5951 (t
5952 (setq c js2-SUB)))
5953 (setq js2-ts-dirty-line t)
5954 (js2-ts-return c))
5955 (otherwise
5956 (js2-report-scan-error "msg.illegal.character")))))))
5957
5958 (defun js2-read-regexp (start-token)
5959 "Called by parser when it gets / or /= in literal context."
5960 (let (c
5961 err
5962 in-class ; inside a '[' .. ']' character-class
5963 flags
5964 (continue t))
5965 (setq js2-token-beg js2-ts-cursor
5966 js2-ts-string-buffer nil
5967 js2-ts-regexp-flags nil)
5968 (if (eq start-token js2-ASSIGN_DIV)
5969 ;; mis-scanned /=
5970 (js2-add-to-string ?=)
5971 (if (not (eq start-token js2-DIV))
5972 (error "failed assertion")))
5973 (while (and (not err)
5974 (or (/= (setq c (js2-get-char)) ?/)
5975 in-class))
5976 (cond
5977 ((or (= c ?\n)
5978 (= c js2-EOF_CHAR))
5979 (setq js2-token-end (1- js2-ts-cursor)
5980 err t
5981 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5982 (js2-report-error "msg.unterminated.re.lit"))
5983 (t (cond
5984 ((= c ?\\)
5985 (js2-add-to-string c)
5986 (setq c (js2-get-char)))
5987 ((= c ?\[)
5988 (setq in-class t))
5989 ((= c ?\])
5990 (setq in-class nil)))
5991 (js2-add-to-string c))))
5992 (unless err
5993 (while continue
5994 (cond
5995 ((js2-match-char ?g)
5996 (push ?g flags))
5997 ((js2-match-char ?i)
5998 (push ?i flags))
5999 ((js2-match-char ?m)
6000 (push ?m flags))
6001 (t
6002 (setq continue nil))))
6003 (if (js2-alpha-p (js2-peek-char))
6004 (js2-report-scan-error "msg.invalid.re.flag" t
6005 js2-ts-cursor 1))
6006 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6007 js2-ts-regexp-flags (js2-collect-string flags)
6008 js2-token-end js2-ts-cursor)
6009 ;; tell `parse-partial-sexp' to ignore this range of chars
6010 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6011
6012 (defun js2-get-first-xml-token ()
6013 (setq js2-ts-xml-open-tags-count 0
6014 js2-ts-is-xml-attribute nil
6015 js2-ts-xml-is-tag-content nil)
6016 (js2-unget-char)
6017 (js2-get-next-xml-token))
6018
6019 (defsubst js2-xml-discard-string ()
6020 "Throw away the string in progress and flag an XML parse error."
6021 (setq js2-ts-string-buffer nil
6022 js2-ts-string nil)
6023 (js2-report-scan-error "msg.XML.bad.form" t))
6024
6025 (defun js2-get-next-xml-token ()
6026 (setq js2-ts-string-buffer nil ; for recording the XML
6027 js2-token-beg js2-ts-cursor)
6028 (let (c result)
6029 (setq result
6030 (catch 'return
6031 (while t
6032 (setq c (js2-get-char))
6033 (cond
6034 ((= c js2-EOF_CHAR)
6035 (throw 'return js2-ERROR))
6036 (js2-ts-xml-is-tag-content
6037 (case c
6038 (?>
6039 (js2-add-to-string c)
6040 (setq js2-ts-xml-is-tag-content nil
6041 js2-ts-is-xml-attribute nil))
6042 (?/
6043 (js2-add-to-string c)
6044 (when (eq ?> (js2-peek-char))
6045 (setq c (js2-get-char))
6046 (js2-add-to-string c)
6047 (setq js2-ts-xml-is-tag-content nil)
6048 (decf js2-ts-xml-open-tags-count)))
6049 (?{
6050 (js2-unget-char)
6051 (setq js2-ts-string (js2-get-string-from-buffer))
6052 (throw 'return js2-XML))
6053 ((?\' ?\")
6054 (js2-add-to-string c)
6055 (unless (js2-read-quoted-string c)
6056 (throw 'return js2-ERROR)))
6057 (?=
6058 (js2-add-to-string c)
6059 (setq js2-ts-is-xml-attribute t))
6060 ((? ?\t ?\r ?\n)
6061 (js2-add-to-string c))
6062 (t
6063 (js2-add-to-string c)
6064 (setq js2-ts-is-xml-attribute nil)))
6065 (when (and (not js2-ts-xml-is-tag-content)
6066 (zerop js2-ts-xml-open-tags-count))
6067 (setq js2-ts-string (js2-get-string-from-buffer))
6068 (throw 'return js2-XMLEND)))
6069 (t
6070 ;; else not tag content
6071 (case c
6072 (?<
6073 (js2-add-to-string c)
6074 (setq c (js2-peek-char))
6075 (case c
6076 (?!
6077 (setq c (js2-get-char)) ;; skip !
6078 (js2-add-to-string c)
6079 (setq c (js2-peek-char))
6080 (case c
6081 (?-
6082 (setq c (js2-get-char)) ;; skip -
6083 (js2-add-to-string c)
6084 (if (eq c ?-)
6085 (progn
6086 (js2-add-to-string c)
6087 (unless (js2-read-xml-comment)
6088 (throw 'return js2-ERROR)))
6089 (js2-xml-discard-string)
6090 (throw 'return js2-ERROR)))
6091 (?\[
6092 (setq c (js2-get-char)) ;; skip [
6093 (js2-add-to-string c)
6094 (if (and (= (js2-get-char) ?C)
6095 (= (js2-get-char) ?D)
6096 (= (js2-get-char) ?A)
6097 (= (js2-get-char) ?T)
6098 (= (js2-get-char) ?A)
6099 (= (js2-get-char) ?\[))
6100 (progn
6101 (js2-add-to-string ?C)
6102 (js2-add-to-string ?D)
6103 (js2-add-to-string ?A)
6104 (js2-add-to-string ?T)
6105 (js2-add-to-string ?A)
6106 (js2-add-to-string ?\[)
6107 (unless (js2-read-cdata)
6108 (throw 'return js2-ERROR)))
6109 (js2-xml-discard-string)
6110 (throw 'return js2-ERROR)))
6111 (t
6112 (unless (js2-read-entity)
6113 (throw 'return js2-ERROR)))))
6114 (??
6115 (setq c (js2-get-char)) ;; skip ?
6116 (js2-add-to-string c)
6117 (unless (js2-read-PI)
6118 (throw 'return js2-ERROR)))
6119 (?/
6120 ;; end tag
6121 (setq c (js2-get-char)) ;; skip /
6122 (js2-add-to-string c)
6123 (when (zerop js2-ts-xml-open-tags-count)
6124 (js2-xml-discard-string)
6125 (throw 'return js2-ERROR))
6126 (setq js2-ts-xml-is-tag-content t)
6127 (decf js2-ts-xml-open-tags-count))
6128 (t
6129 ;; start tag
6130 (setq js2-ts-xml-is-tag-content t)
6131 (incf js2-ts-xml-open-tags-count))))
6132 (?{
6133 (js2-unget-char)
6134 (setq js2-ts-string (js2-get-string-from-buffer))
6135 (throw 'return js2-XML))
6136 (t
6137 (js2-add-to-string c))))))))
6138 (setq js2-token-end js2-ts-cursor)
6139 result))
6140
6141 (defun js2-read-quoted-string (quote)
6142 (let (c)
6143 (catch 'return
6144 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6145 (js2-add-to-string c)
6146 (if (eq c quote)
6147 (throw 'return t)))
6148 (js2-xml-discard-string) ;; throw away string in progress
6149 nil)))
6150
6151 (defun js2-read-xml-comment ()
6152 (let ((c (js2-get-char)))
6153 (catch 'return
6154 (while (/= c js2-EOF_CHAR)
6155 (catch 'continue
6156 (js2-add-to-string c)
6157 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6158 (setq c (js2-get-char))
6159 (js2-add-to-string c)
6160 (if (eq (js2-peek-char) ?>)
6161 (progn
6162 (setq c (js2-get-char)) ;; skip >
6163 (js2-add-to-string c)
6164 (throw 'return t))
6165 (throw 'continue nil)))
6166 (setq c (js2-get-char))))
6167 (js2-xml-discard-string)
6168 nil)))
6169
6170 (defun js2-read-cdata ()
6171 (let ((c (js2-get-char)))
6172 (catch 'return
6173 (while (/= c js2-EOF_CHAR)
6174 (catch 'continue
6175 (js2-add-to-string c)
6176 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6177 (setq c (js2-get-char))
6178 (js2-add-to-string c)
6179 (if (eq (js2-peek-char) ?>)
6180 (progn
6181 (setq c (js2-get-char)) ;; Skip >
6182 (js2-add-to-string c)
6183 (throw 'return t))
6184 (throw 'continue nil)))
6185 (setq c (js2-get-char))))
6186 (js2-xml-discard-string)
6187 nil)))
6188
6189 (defun js2-read-entity ()
6190 (let ((decl-tags 1)
6191 c)
6192 (catch 'return
6193 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6194 (js2-add-to-string c)
6195 (case c
6196 (?<
6197 (incf decl-tags))
6198 (?>
6199 (decf decl-tags)
6200 (if (zerop decl-tags)
6201 (throw 'return t)))))
6202 (js2-xml-discard-string)
6203 nil)))
6204
6205 (defun js2-read-PI ()
6206 "Scan an XML processing instruction."
6207 (let (c)
6208 (catch 'return
6209 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6210 (js2-add-to-string c)
6211 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6212 (setq c (js2-get-char)) ;; Skip >
6213 (js2-add-to-string c)
6214 (throw 'return t)))
6215 (js2-xml-discard-string)
6216 nil)))
6217
6218 (defun js2-scanner-get-line ()
6219 "Return the text of the current scan line."
6220 (buffer-substring (point-at-bol) (point-at-eol)))
6221
6222 ;;; Highlighting
6223
6224 (defsubst js2-set-face (beg end face &optional record)
6225 "Fontify a region. If RECORD is non-nil, record for later."
6226 (when (plusp js2-highlight-level)
6227 (setq beg (min (point-max) beg)
6228 beg (max (point-min) beg)
6229 end (min (point-max) end)
6230 end (max (point-min) end))
6231 (if record
6232 (push (list beg end face) js2-mode-fontifications)
6233 (put-text-property beg end 'face face))))
6234
6235 (defsubst js2-set-kid-face (pos kid len face)
6236 "Set-face on a child node.
6237 POS is absolute buffer position of parent.
6238 KID is the child node.
6239 LEN is the length to fontify.
6240 FACE is the face to fontify with."
6241 (js2-set-face (+ pos (js2-node-pos kid))
6242 (+ pos (js2-node-pos kid) (js2-node-len kid))
6243 face))
6244
6245 (defsubst js2-fontify-kwd (start length)
6246 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6247
6248 (defsubst js2-clear-face (beg end)
6249 (remove-text-properties beg end '(face nil
6250 help-echo nil
6251 point-entered nil
6252 c-in-sws nil)))
6253
6254 (defsubst js2-record-text-property (beg end prop value)
6255 "Record a text property to set when parsing finishes."
6256 (push (list beg end prop value) js2-mode-deferred-properties))
6257
6258 (defconst js2-ecma-global-props
6259 (concat "^"
6260 (regexp-opt
6261 '("Infinity" "NaN" "undefined" "arguments") t)
6262 "$")
6263 "Value properties of the Ecma-262 Global Object.
6264 Shown at or above `js2-highlight-level' 2.")
6265
6266 ;; might want to add the name "arguments" to this list?
6267 (defconst js2-ecma-object-props
6268 (concat "^"
6269 (regexp-opt
6270 '("prototype" "__proto__" "__parent__") t)
6271 "$")
6272 "Value properties of the Ecma-262 Object constructor.
6273 Shown at or above `js2-highlight-level' 2.")
6274
6275 (defconst js2-ecma-global-funcs
6276 (concat
6277 "^"
6278 (regexp-opt
6279 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6280 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6281 "$")
6282 "Function properties of the Ecma-262 Global object.
6283 Shown at or above `js2-highlight-level' 2.")
6284
6285 (defconst js2-ecma-number-props
6286 (concat "^"
6287 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6288 "NEGATIVE_INFINITY"
6289 "POSITIVE_INFINITY") t)
6290 "$")
6291 "Properties of the Ecma-262 Number constructor.
6292 Shown at or above `js2-highlight-level' 2.")
6293
6294 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6295 "Properties of the Ecma-262 Date constructor.
6296 Shown at or above `js2-highlight-level' 2.")
6297
6298 (defconst js2-ecma-math-props
6299 (concat "^"
6300 (regexp-opt
6301 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6302 t)
6303 "$")
6304 "Properties of the Ecma-262 Math object.
6305 Shown at or above `js2-highlight-level' 2.")
6306
6307 (defconst js2-ecma-math-funcs
6308 (concat "^"
6309 (regexp-opt
6310 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6311 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6312 "$")
6313 "Function properties of the Ecma-262 Math object.
6314 Shown at or above `js2-highlight-level' 2.")
6315
6316 (defconst js2-ecma-function-props
6317 (concat
6318 "^"
6319 (regexp-opt
6320 '(;; properties of the Object prototype object
6321 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6322 "toLocaleString" "toString" "valueOf"
6323 ;; properties of the Function prototype object
6324 "apply" "call"
6325 ;; properties of the Array prototype object
6326 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6327 "splice" "unshift"
6328 ;; properties of the String prototype object
6329 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6330 "localeCompare" "match" "replace" "search" "split" "substring"
6331 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6332 "toUpperCase"
6333 ;; properties of the Number prototype object
6334 "toExponential" "toFixed" "toPrecision"
6335 ;; properties of the Date prototype object
6336 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6337 "getMinutes" "getMonth" "getSeconds" "getTime"
6338 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6339 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6340 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6341 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6342 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6343 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6344 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6345 "toTimeString" "toUTCString"
6346 ;; properties of the RegExp prototype object
6347 "exec" "test"
6348 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6349 "toSource" "__defineGetter__" "__defineSetter__"
6350 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6351 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6352 t)
6353 "$")
6354 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6355 Shown at or above `js2-highlight-level' 3.")
6356
6357 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6358 (let ((target-name (and target
6359 (js2-name-node-p target)
6360 (js2-name-node-name target)))
6361 (prop-name (if prop (js2-name-node-name prop)))
6362 (level1 (>= js2-highlight-level 1))
6363 (level2 (>= js2-highlight-level 2))
6364 (level3 (>= js2-highlight-level 3))
6365 pos
6366 face)
6367 (when level2
6368 (if call-p
6369 (cond
6370 ((and target prop)
6371 (cond
6372 ((and level3 (string-match js2-ecma-function-props prop-name))
6373 (setq face 'font-lock-builtin-face))
6374 ((and target-name prop)
6375 (cond
6376 ((string= target-name "Date")
6377 (if (string-match js2-ecma-date-props prop-name)
6378 (setq face 'font-lock-builtin-face)))
6379 ((string= target-name "Math")
6380 (if (string-match js2-ecma-math-funcs prop-name)
6381 (setq face 'font-lock-builtin-face)))))))
6382 (prop
6383 (if (string-match js2-ecma-global-funcs prop-name)
6384 (setq face 'font-lock-builtin-face))))
6385 (cond
6386 ((and target prop)
6387 (cond
6388 ((string= target-name "Number")
6389 (if (string-match js2-ecma-number-props prop-name)
6390 (setq face 'font-lock-constant-face)))
6391 ((string= target-name "Math")
6392 (if (string-match js2-ecma-math-props prop-name)
6393 (setq face 'font-lock-constant-face)))))
6394 (prop
6395 (if (string-match js2-ecma-object-props prop-name)
6396 (setq face 'font-lock-constant-face)))))
6397 (when face
6398 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6399 (js2-node-pos prop))) ; relative
6400 (+ pos (js2-node-len prop))
6401 face)))))
6402
6403 (defun js2-parse-highlight-member-expr-node (node)
6404 "Perform syntax highlighting of EcmaScript built-in properties.
6405 The variable `js2-highlight-level' governs this highighting."
6406 (let (face target prop name pos end parent call-p callee)
6407 (cond
6408 ;; case 1: simple name, e.g. foo
6409 ((js2-name-node-p node)
6410 (setq name (js2-name-node-name node))
6411 ;; possible for name to be nil in rare cases - saw it when
6412 ;; running js2-mode on an elisp buffer. Might as well try to
6413 ;; make it so js2-mode never barfs.
6414 (when name
6415 (setq face (if (string-match js2-ecma-global-props name)
6416 'font-lock-constant-face))
6417 (when face
6418 (setq pos (js2-node-pos node)
6419 end (+ pos (js2-node-len node)))
6420 (js2-set-face pos end face))))
6421 ;; case 2: property access or function call
6422 ((or (js2-prop-get-node-p node)
6423 ;; highlight function call if expr is a prop-get node
6424 ;; or a plain name (i.e. unqualified function call)
6425 (and (setq call-p (js2-call-node-p node))
6426 (setq callee (js2-call-node-target node)) ; separate setq!
6427 (or (js2-prop-get-node-p callee)
6428 (js2-name-node-p callee))))
6429 (setq parent node
6430 node (if call-p callee node))
6431 (if (and call-p (js2-name-node-p callee))
6432 (setq prop callee)
6433 (setq target (js2-prop-get-node-left node)
6434 prop (js2-prop-get-node-right node)))
6435 (cond
6436 ((js2-name-node-p target)
6437 (if (js2-name-node-p prop)
6438 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6439 (js2-parse-highlight-prop-get parent target prop call-p)
6440 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6441 (js2-parse-highlight-prop-get parent target nil call-p)))
6442 ((js2-name-node-p prop)
6443 ;; case 2c: complex target, simple name, e.g. x[y].bar
6444 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6445
6446 (defun js2-parse-highlight-member-expr-fn-name (expr)
6447 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6448 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6449 We currently only handle the case where the last component is a prop-get
6450 of a simple name. Called before EXPR has a parent node."
6451 (let (pos
6452 (name (and (js2-prop-get-node-p expr)
6453 (js2-prop-get-node-right expr))))
6454 (when (js2-name-node-p name)
6455 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6456 (js2-node-pos name)))
6457 (+ pos (js2-node-len name))
6458 'font-lock-function-name-face
6459 'record))))
6460
6461 ;; source: http://jsdoc.sourceforge.net/
6462 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6463 ;; allows type specifications, and needs work before entering the wild.
6464
6465 (defconst js2-jsdoc-param-tag-regexp
6466 (concat "^\\s-*\\*+\\s-*\\(@"
6467 "\\(?:param\\|argument\\)"
6468 "\\)"
6469 "\\s-*\\({[^}]+}\\)?" ; optional type
6470 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6471 "\\>")
6472 "Matches jsdoc tags with optional type and optional param name.")
6473
6474 (defconst js2-jsdoc-typed-tag-regexp
6475 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6476 (regexp-opt
6477 '("enum"
6478 "extends"
6479 "field"
6480 "id"
6481 "implements"
6482 "lends"
6483 "mods"
6484 "requires"
6485 "return"
6486 "returns"
6487 "throw"
6488 "throws"))
6489 "\\)\\)\\s-*\\({[^}]+}\\)?")
6490 "Matches jsdoc tags with optional type.")
6491
6492 (defconst js2-jsdoc-arg-tag-regexp
6493 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6494 (regexp-opt
6495 '("alias"
6496 "augments"
6497 "borrows"
6498 "bug"
6499 "base"
6500 "config"
6501 "default"
6502 "define"
6503 "exception"
6504 "function"
6505 "member"
6506 "memberOf"
6507 "name"
6508 "namespace"
6509 "property"
6510 "since"
6511 "suppress"
6512 "this"
6513 "throws"
6514 "type"
6515 "version"))
6516 "\\)\\)\\s-+\\([^ \t]+\\)")
6517 "Matches jsdoc tags with a single argument.")
6518
6519 (defconst js2-jsdoc-empty-tag-regexp
6520 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6521 (regexp-opt
6522 '("addon"
6523 "author"
6524 "class"
6525 "const"
6526 "constant"
6527 "constructor"
6528 "constructs"
6529 "deprecated"
6530 "desc"
6531 "description"
6532 "event"
6533 "example"
6534 "exec"
6535 "export"
6536 "fileoverview"
6537 "final"
6538 "function"
6539 "hidden"
6540 "ignore"
6541 "implicitCast"
6542 "inheritDoc"
6543 "inner"
6544 "interface"
6545 "license"
6546 "noalias"
6547 "noshadow"
6548 "notypecheck"
6549 "override"
6550 "owner"
6551 "preserve"
6552 "preserveTry"
6553 "private"
6554 "protected"
6555 "public"
6556 "static"
6557 "supported"
6558 ))
6559 "\\)\\)\\s-*")
6560 "Matches empty jsdoc tags.")
6561
6562 (defconst js2-jsdoc-link-tag-regexp
6563 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6564 "Matches a jsdoc link or code tag.")
6565
6566 (defconst js2-jsdoc-see-tag-regexp
6567 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6568 "Matches a jsdoc @see tag.")
6569
6570 (defconst js2-jsdoc-html-tag-regexp
6571 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6572 "Matches a simple (no attributes) html start- or end-tag.")
6573
6574 (defsubst js2-jsdoc-highlight-helper ()
6575 (js2-set-face (match-beginning 1)
6576 (match-end 1)
6577 'js2-jsdoc-tag-face)
6578 (if (match-beginning 2)
6579 (if (save-excursion
6580 (goto-char (match-beginning 2))
6581 (= (char-after) ?{))
6582 (js2-set-face (1+ (match-beginning 2))
6583 (1- (match-end 2))
6584 'js2-jsdoc-type-face)
6585 (js2-set-face (match-beginning 2)
6586 (match-end 2)
6587 'js2-jsdoc-value-face)))
6588 (if (match-beginning 3)
6589 (js2-set-face (match-beginning 3)
6590 (match-end 3)
6591 'js2-jsdoc-value-face)))
6592
6593 (defun js2-highlight-jsdoc (ast)
6594 "Highlight doc comment tags."
6595 (let ((comments (js2-ast-root-comments ast))
6596 beg end)
6597 (save-excursion
6598 (dolist (node comments)
6599 (when (eq (js2-comment-node-format node) 'jsdoc)
6600 (setq beg (js2-node-abs-pos node)
6601 end (+ beg (js2-node-len node)))
6602 (save-restriction
6603 (narrow-to-region beg end)
6604 (dolist (re (list js2-jsdoc-param-tag-regexp
6605 js2-jsdoc-typed-tag-regexp
6606 js2-jsdoc-arg-tag-regexp
6607 js2-jsdoc-link-tag-regexp
6608 js2-jsdoc-see-tag-regexp
6609 js2-jsdoc-empty-tag-regexp))
6610 (goto-char beg)
6611 (while (re-search-forward re nil t)
6612 (js2-jsdoc-highlight-helper)))
6613 ;; simple highlighting for html tags
6614 (goto-char beg)
6615 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6616 (js2-set-face (match-beginning 1)
6617 (match-end 1)
6618 'js2-jsdoc-html-tag-delimiter-face)
6619 (js2-set-face (match-beginning 2)
6620 (match-end 2)
6621 'js2-jsdoc-html-tag-name-face)
6622 (js2-set-face (match-beginning 3)
6623 (match-end 3)
6624 'js2-jsdoc-html-tag-delimiter-face))))))))
6625
6626 (defun js2-highlight-assign-targets (node left right)
6627 "Highlight function properties and external variables."
6628 (let (leftpos end name)
6629 ;; highlight vars and props assigned function values
6630 (when (js2-function-node-p right)
6631 (cond
6632 ;; var foo = function() {...}
6633 ((js2-name-node-p left)
6634 (setq name left))
6635 ;; foo.bar.baz = function() {...}
6636 ((and (js2-prop-get-node-p left)
6637 (js2-name-node-p (js2-prop-get-node-right left)))
6638 (setq name (js2-prop-get-node-right left))))
6639 (when name
6640 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6641 (+ leftpos (js2-node-len name))
6642 'font-lock-function-name-face
6643 'record)))
6644 ;; save variable assignments so we can check for undeclared later
6645 ;; (can't do it here since var decls can come at end of script)
6646 (when (and js2-highlight-external-variables
6647 (setq name (js2-member-expr-leftmost-name left)))
6648 (push (list name js2-current-scope
6649 (setq leftpos (js2-node-abs-pos name))
6650 (setq end (+ leftpos (js2-node-len name))))
6651 js2-recorded-assignments))))
6652
6653 (defun js2-highlight-undeclared-vars ()
6654 "After entire parse is finished, look for undeclared variable assignments.
6655 We have to wait until entire buffer is parsed, since JavaScript permits var
6656 decls to occur after they're used.
6657
6658 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6659 it is considered declared."
6660 (let (name)
6661 (dolist (entry js2-recorded-assignments)
6662 (destructuring-bind (name-node scope pos end) entry
6663 (setq name (js2-name-node-name name-node))
6664 (unless (or (member name js2-global-externs)
6665 (member name js2-default-externs)
6666 (member name js2-additional-externs)
6667 (js2-get-defining-scope scope name))
6668 (js2-set-face pos end 'js2-external-variable-face 'record)
6669 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6670 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6671 (setq js2-recorded-assignments nil)))
6672
6673 ;;; IMenu support
6674
6675 ;; We currently only support imenu, but eventually should support speedbar and
6676 ;; possibly other browsing mechanisms.
6677
6678 ;; The basic strategy is to identify function assignment targets of the form
6679 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6680 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6681 ;; for imenu after parsing is finished.
6682
6683 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6684 ;; JavaScript, and the general problem is undecidable. However, several forms
6685 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6686 ;; include:
6687
6688 ;; function foo() -- function declaration
6689 ;; foo = function() -- function expression assigned to variable
6690 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6691 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6692 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6693 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6694 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6695 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6696 ;; function foo() {function bar() {...}} -- nested function
6697 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6698
6699 ;; This list boils down to a few forms that can be combined recursively.
6700 ;; Top-level named function declarations include both the left-hand (name)
6701 ;; and the right-hand (function value) expressions needed to produce an imenu
6702 ;; entry. The other "right-hand" forms we need to look for are:
6703 ;; - functions declared as props/getters/setters in object literals
6704 ;; - nested named function declarations
6705 ;; The "left-hand" expressions that functions can be assigned to include:
6706 ;; - local/global variables
6707 ;; - nested property-get expressions like a.b.c.d
6708 ;; - element gets like foo[10] or foo['bar'] where the index
6709 ;; expression can be trivially converted to a property name. They
6710 ;; effectively then become property gets.
6711
6712 ;; All the different definition types are canonicalized into the form
6713 ;; foo.bar.baz = position-of-function-keyword
6714
6715 ;; We need to build a trie-like structure for imenu. As an example,
6716 ;; consider the following JavaScript code:
6717
6718 ;; a = function() {...} // function at position 5
6719 ;; b = function() {...} // function at position 25
6720 ;; foo = function() {...} // function at position 100
6721 ;; foo.bar = function() {...} // function at position 200
6722 ;; foo.bar.baz = function() {...} // function at position 300
6723 ;; foo.bar.zab = function() {...} // function at position 400
6724
6725 ;; During parsing we accumulate an entry for each definition in
6726 ;; the variable `js2-imenu-recorder', like so:
6727
6728 ;; '((a 5)
6729 ;; (b 25)
6730 ;; (foo 100)
6731 ;; (foo bar 200)
6732 ;; (foo bar baz 300)
6733 ;; (foo bar zab 400))
6734
6735 ;; After parsing these entries are merged into this alist-trie:
6736
6737 ;; '((a . 1)
6738 ;; (b . 2)
6739 ;; (foo (<definition> . 3)
6740 ;; (bar (<definition> . 6)
6741 ;; (baz . 100)
6742 ;; (zab . 200))))
6743
6744 ;; Note the wacky need for a <definition> name. The token can be anything
6745 ;; that isn't a valid JavaScript identifier, because you might make foo
6746 ;; a function and then start setting properties on it that are also functions.
6747
6748 (defsubst js2-prop-node-name (node)
6749 "Return the name of a node that may be a property-get/property-name.
6750 If NODE is not a valid name-node, string-node or integral number-node,
6751 returns nil. Otherwise returns the string name/value of the node."
6752 (cond
6753 ((js2-name-node-p node)
6754 (js2-name-node-name node))
6755 ((js2-string-node-p node)
6756 (js2-string-node-value node))
6757 ((and (js2-number-node-p node)
6758 (string-match "^[0-9]+$" (js2-number-node-value node)))
6759 (js2-number-node-value node))
6760 ((js2-this-node-p node)
6761 "this")))
6762
6763 (defsubst js2-node-qname-component (node)
6764 "Test function: return the name of this node, if it contributes to a qname.
6765 Returns nil if the node doesn't contribute."
6766 (copy-sequence
6767 (or (js2-prop-node-name node)
6768 (if (and (js2-function-node-p node)
6769 (js2-function-node-name node))
6770 (js2-name-node-name (js2-function-node-name node))))))
6771
6772 (defsubst js2-record-function-qname (fn-node qname)
6773 "Associate FN-NODE with its QNAME for later lookup.
6774 This is used in postprocessing the chain list. When we find a chain
6775 whose first element is a js2-THIS keyword node, we look up the parent
6776 function and see (using this map) whether it is the tail of a chain.
6777 If so, we replace the this-node with a copy of the parent's qname."
6778 (unless js2-imenu-function-map
6779 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6780 (puthash fn-node qname js2-imenu-function-map))
6781
6782 (defun js2-record-imenu-functions (node &optional var)
6783 "Record function definitions for imenu.
6784 NODE is a function node or an object literal.
6785 VAR, if non-nil, is the expression that NODE is being assigned to."
6786 (when js2-parse-ide-mode
6787 (let ((fun-p (js2-function-node-p node))
6788 qname left fname-node pos)
6789 (cond
6790 ;; non-anonymous function declaration?
6791 ((and fun-p
6792 (not var)
6793 (setq fname-node (js2-function-node-name node)))
6794 (push (setq qname (list fname-node (js2-node-pos node)))
6795 js2-imenu-recorder)
6796 (js2-record-function-qname node qname))
6797 ;; for remaining forms, compute left-side tree branch first
6798 ((and var (setq qname (js2-compute-nested-prop-get var)))
6799 (cond
6800 ;; foo.bar.baz = function
6801 (fun-p
6802 (push (nconc qname (list (js2-node-pos node)))
6803 js2-imenu-recorder)
6804 (js2-record-function-qname node qname))
6805 ;; foo.bar.baz = object-literal
6806 ;; look for nested functions: {a: {b: function() {...} }}
6807 ((js2-object-node-p node)
6808 (js2-record-object-literal node qname))))))))
6809
6810 (defun js2-compute-nested-prop-get (node)
6811 "If NODE is of form foo.bar.baz, return component nodes as a list.
6812 Otherwise returns nil. Element-gets can be treated as property-gets
6813 if the index expression is a name, a string, or a positive integer."
6814 (let (left right head)
6815 (cond
6816 ((or (js2-name-node-p node)
6817 (js2-this-node-p node))
6818 (list node))
6819 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6820 ((js2-prop-get-node-p node) ; includes elem-get nodes
6821 (setq left (js2-prop-get-node-left node)
6822 right (js2-prop-get-node-right node))
6823 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6824 (js2-name-node-p left)
6825 (js2-this-node-p left)) ; or left == foo
6826 (or (js2-name-node-p right) ; .bar
6827 (js2-string-node-p right) ; ['bar']
6828 (and (js2-number-node-p right) ; [10]
6829 (string-match "^[0-9]+$"
6830 (js2-number-node-value right)))))
6831 (if (setq head (js2-compute-nested-prop-get left))
6832 (nconc head (list right))))))))
6833
6834 (defun js2-record-object-literal (node qname)
6835 "Recursively process an object literal looking for functions.
6836 NODE is an object literal that is the right-hand child of an assignment
6837 expression. QNAME is a list of nodes representing the assignment target,
6838 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6839 We do a depth-first traversal of NODE. Any functions we find are prefixed
6840 with QNAME plus the property name of the function and appended to the
6841 variable `js2-imenu-recorder'."
6842 ;; Elements are relative to parent position, which is still absolute,
6843 ;; since the parser passes the assignment target and value expressions
6844 ;; to us before they are added as children of the assignment node.
6845 (let ((pos (js2-node-pos node))
6846 left right)
6847 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6848 (setq left (js2-infix-node-left e))
6849 (cond
6850 ;; foo: function() {...}
6851 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6852 (when (js2-prop-node-name left)
6853 ;; As a policy decision, we record the position of the property,
6854 ;; not the position of the `function' keyword, since the property
6855 ;; is effectively the name of the function.
6856 (push (append qname (list left) (list (+ pos (js2-node-pos e))))
6857 js2-imenu-recorder)
6858 (js2-record-function-qname right qname)))
6859 ;; foo: {object-literal} -- add foo to qname and recurse
6860 ((js2-object-node-p right)
6861 (js2-record-object-literal right
6862 (append qname (list (js2-infix-node-left e)))))))))
6863
6864 (defsubst js2-node-top-level-decl-p (node)
6865 "Return t if NODE's name is defined in the top-level scope.
6866 Also returns t if NODE's name is not defined in any scope, since it implies
6867 that it's an external variable, which must also be in the top-level scope."
6868 (let* ((name (js2-prop-node-name node))
6869 (this-scope (js2-node-get-enclosing-scope node))
6870 defining-scope)
6871 (cond
6872 ((js2-this-node-p node)
6873 nil)
6874 ((null this-scope)
6875 t)
6876 ((setq defining-scope (js2-get-defining-scope this-scope name))
6877 (js2-ast-root-p defining-scope))
6878 (t t))))
6879
6880 (defun js2-browse-postprocess-chains (chains)
6881 "Modify function-declaration name chains after parsing finishes.
6882 Some of the information is only available after the parse tree is complete.
6883 For instance, following a 'this' reference requires a parent function node."
6884 (let (result head fn parent-chain p elem)
6885 (dolist (chain chains)
6886 ;; examine the head of each node to get its defining scope
6887 (setq head (car chain))
6888 (cond
6889 ;; if top-level/external, keep as-is
6890 ((js2-node-top-level-decl-p head)
6891 (push chain result))
6892 ;; check for a this-reference
6893 ((eq (js2-node-type head) js2-THIS)
6894 (setq fn (js2-node-parent-script-or-fn head))
6895 ;; if there is no parent function, or if the parent function
6896 ;; is nested, discard the head node and keep the rest of the chain.
6897 (if (or (null fn) (js2-nested-function-p fn))
6898 (push (cdr chain) result)
6899 ;; else look up parent in function-map. If not found, discard chain.
6900 (when (setq parent-chain (and js2-imenu-function-map
6901 (gethash fn js2-imenu-function-map)))
6902 ;; else discard head node and prefix parent fn qname, which is
6903 ;; the parent-chain sans tail, to this chain.
6904 (push (append (butlast parent-chain) (cdr chain)) result))))))
6905 ;; finally replace each node in each chain with its name.
6906 (dolist (chain result)
6907 (setq p chain)
6908 (while p
6909 (if (js2-node-p (setq elem (car p)))
6910 (setcar p (js2-node-qname-component elem)))
6911 (setq p (cdr p))))
6912 result))
6913
6914 ;; Merge name chains into a trie-like tree structure of nested lists.
6915 ;; To simplify construction of the trie, we first build it out using the rule
6916 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6917 ;; [key, num-or-list]. The second element can be a number; if so, this key
6918 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6919 ;; associated with the key at this level.) Otherwise the second element is
6920 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6921 ;; a simple recursive formulation.
6922 ;;
6923 ;; js2-mode is building the data structure for imenu. The imenu documentation
6924 ;; claims that it's the structure above, but in practice it wants the children
6925 ;; at the same list level as the key for that level, which is how I've drawn
6926 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6927 ;; list wrapper around the children at each level.
6928 ;;
6929 ;; A completed nested imenu-alist entry looks like this:
6930 ;; '(("foo"
6931 ;; ("<definition>" . 7)
6932 ;; ("bar"
6933 ;; ("a" . 40)
6934 ;; ("b" . 60))))
6935 ;;
6936 ;; In particular, the documentation for `imenu--index-alist' says that
6937 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6938 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6939
6940 (defsubst js2-treeify (lst)
6941 "Convert (a b c d) to (a ((b ((c d)))))"
6942 (if (null (cddr lst)) ; list length <= 2
6943 lst
6944 (list (car lst) (list (js2-treeify (cdr lst))))))
6945
6946 (defun js2-build-alist-trie (chains trie)
6947 "Merge declaration name chains into a trie-like alist structure for imenu.
6948 CHAINS is the qname chain list produced during parsing. TRIE is a
6949 list of elements built up so far."
6950 (let (head tail pos branch kids)
6951 (dolist (chain chains)
6952 (setq head (car chain)
6953 tail (cdr chain)
6954 pos (if (numberp (car tail)) (car tail))
6955 branch (js2-find-if (lambda (n)
6956 (string= (car n) head))
6957 trie)
6958 kids (second branch))
6959 (cond
6960 ;; case 1: this key isn't in the trie yet
6961 ((null branch)
6962 (if trie
6963 (setcdr (last trie) (list (js2-treeify chain)))
6964 (setq trie (list (js2-treeify chain)))))
6965 ;; case 2: key is present with a single number entry: replace w/ list
6966 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6967 ;; ("<definition>" 20)))
6968 ((numberp kids)
6969 (setcar (cdr branch)
6970 (list (list "<definition-1>" kids)
6971 (if pos
6972 (list "<definition-2>" pos)
6973 (js2-treeify tail)))))
6974 ;; case 3: key is there (with kids), and we're a number entry
6975 (pos
6976 (setcdr (last kids)
6977 (list
6978 (list (format "<definition-%d>"
6979 (1+ (loop for kid in kids
6980 count (eq ?< (aref (car kid) 0)))))
6981 pos))))
6982 ;; case 4: key is there with kids, need to merge in our chain
6983 (t
6984 (js2-build-alist-trie (list tail) kids))))
6985 trie))
6986
6987 (defun js2-flatten-trie (trie)
6988 "Convert TRIE to imenu-format.
6989 Recurses through nodes, and for each one whose second element is a list,
6990 appends the list's flattened elements to the current element. Also
6991 changes the tails into conses. For instance, this pre-flattened trie
6992
6993 '(a ((b 20)
6994 (c ((d 30)
6995 (e 40)))))
6996
6997 becomes
6998
6999 '(a (b . 20)
7000 (c (d . 30)
7001 (e . 40)))
7002
7003 Note that the root of the trie has no key, just a list of chains.
7004 This is also true for the value of any key with multiple children,
7005 e.g. key 'c' in the example above."
7006 (cond
7007 ((listp (car trie))
7008 (mapcar #'js2-flatten-trie trie))
7009 (t
7010 (if (numberp (second trie))
7011 (cons (car trie) (second trie))
7012 ;; else pop list and append its kids
7013 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7014
7015 (defun js2-build-imenu-index ()
7016 "Turn `js2-imenu-recorder' into an imenu data structure."
7017 (unless (eq js2-imenu-recorder 'empty)
7018 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7019 (result (js2-build-alist-trie chains nil)))
7020 (js2-flatten-trie result))))
7021
7022 (defun js2-test-print-chains (chains)
7023 "Print a list of qname chains.
7024 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7025 i.e. one or more nodes, and an integer position as the list tail."
7026 (mapconcat (lambda (chain)
7027 (concat "("
7028 (mapconcat (lambda (elem)
7029 (if (js2-node-p elem)
7030 (or (js2-node-qname-component elem)
7031 "nil")
7032 (number-to-string elem)))
7033 chain
7034 " ")
7035 ")"))
7036 chains
7037 "\n"))
7038
7039 ;;; Parser
7040
7041 (defconst js2-version "1.8.0"
7042 "Version of JavaScript supported, plus minor js2 version.")
7043
7044 (defmacro js2-record-face (face)
7045 "Record a style run of FACE for the current token."
7046 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7047
7048 (defsubst js2-node-end (n)
7049 "Computes the absolute end of node N.
7050 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7051 is only true until the node is added to its parent; i.e., while parsing."
7052 (+ (js2-node-pos n)
7053 (js2-node-len n)))
7054
7055 (defsubst js2-record-comment ()
7056 "Record a comment in `js2-scanned-comments'."
7057 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7058 :format js2-ts-comment-type)
7059 js2-scanned-comments)
7060 (when js2-parse-ide-mode
7061 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7062 'font-lock-doc-face
7063 'font-lock-comment-face))
7064 (when (memq js2-ts-comment-type '(html preprocessor))
7065 ;; Tell cc-engine the bounds of the comment.
7066 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7067
7068 ;; This function is called depressingly often, so it should be fast.
7069 ;; Most of the time it's looking at the same token it peeked before.
7070 (defsubst js2-peek-token ()
7071 "Returns the next token without consuming it.
7072 If previous token was consumed, calls scanner to get new token.
7073 If previous token was -not- consumed, returns it (idempotent).
7074
7075 This function will not return a newline (js2-EOL) - instead, it
7076 gobbles newlines until it finds a non-newline token, and flags
7077 that token as appearing just after a newline.
7078
7079 This function will also not return a js2-COMMENT. Instead, it
7080 records comments found in `js2-scanned-comments'. If the token
7081 returned by this function immediately follows a jsdoc comment,
7082 the token is flagged as such.
7083
7084 Note that this function always returned the un-flagged token!
7085 The flags, if any, are saved in `js2-current-flagged-token'."
7086 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7087 js2-current-token ; most common case - return already-peeked token
7088 (let ((tt (js2-get-token)) ; call scanner
7089 saw-eol
7090 face)
7091 ;; process comments and whitespace
7092 (while (or (= tt js2-EOL)
7093 (= tt js2-COMMENT))
7094 (if (= tt js2-EOL)
7095 (setq saw-eol t)
7096 (setq saw-eol nil)
7097 (if js2-record-comments
7098 (js2-record-comment)))
7099 (setq tt (js2-get-token))) ; call scanner
7100 (setq js2-current-token tt
7101 js2-current-flagged-token (if saw-eol
7102 (logior tt js2-ti-after-eol)
7103 tt))
7104 ;; perform lexical fontification as soon as token is scanned
7105 (when js2-parse-ide-mode
7106 (cond
7107 ((minusp tt)
7108 (js2-record-face 'js2-error-face))
7109 ((setq face (aref js2-kwd-tokens tt))
7110 (js2-record-face face))
7111 ((and (= tt js2-NAME)
7112 (equal js2-ts-string "undefined"))
7113 (js2-record-face 'font-lock-constant-face))))
7114 tt))) ; return unflagged token
7115
7116 (defsubst js2-peek-flagged-token ()
7117 "Returns the current token along with any flags set for it."
7118 (js2-peek-token)
7119 js2-current-flagged-token)
7120
7121 (defsubst js2-consume-token ()
7122 (setq js2-current-flagged-token js2-EOF))
7123
7124 (defsubst js2-next-token ()
7125 (prog1
7126 (js2-peek-token)
7127 (js2-consume-token)))
7128
7129 (defsubst js2-next-flagged-token ()
7130 (js2-peek-token)
7131 (prog1 js2-current-flagged-token
7132 (js2-consume-token)))
7133
7134 (defsubst js2-match-token (match)
7135 "Consume and return t if next token matches MATCH, a bytecode.
7136 Returns nil and consumes nothing if MATCH is not the next token."
7137 (if (/= (js2-peek-token) match)
7138 nil
7139 (js2-consume-token)
7140 t))
7141
7142 (defsubst js2-valid-prop-name-token (tt)
7143 (or (= tt js2-NAME)
7144 (and js2-allow-keywords-as-property-names
7145 (plusp tt)
7146 (aref js2-kwd-tokens tt))))
7147
7148 (defsubst js2-match-prop-name ()
7149 "Consume token and return t if next token is a valid property name.
7150 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7151 is non-nil and it's a keyword token."
7152 (if (js2-valid-prop-name-token (js2-peek-token))
7153 (progn
7154 (js2-consume-token)
7155 t)
7156 nil))
7157
7158 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7159 (if (js2-match-prop-name)
7160 t
7161 (js2-report-error msg-id nil pos len)
7162 nil))
7163
7164 (defsubst js2-peek-token-or-eol ()
7165 "Return js2-EOL if the current token immediately follows a newline.
7166 Else returns the current token. Used in situations where we don't
7167 consider certain token types valid if they are preceded by a newline.
7168 One example is the postfix ++ or -- operator, which has to be on the
7169 same line as its operand."
7170 (let ((tt (js2-peek-token)))
7171 ;; Check for last peeked token flags
7172 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7173 js2-EOL
7174 tt)))
7175
7176 (defsubst js2-set-check-for-label ()
7177 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7178 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7179
7180 (defsubst js2-must-match (token msg-id &optional pos len)
7181 "Match next token to token code TOKEN, or record a syntax error.
7182 MSG-ID is the error message to report if the match fails.
7183 Returns t on match, nil if no match."
7184 (if (js2-match-token token)
7185 t
7186 (js2-report-error msg-id nil pos len)
7187 nil))
7188
7189 (defsubst js2-inside-function ()
7190 (plusp js2-nesting-of-function))
7191
7192 (defsubst js2-set-requires-activation ()
7193 (if (js2-function-node-p js2-current-script-or-fn)
7194 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7195
7196 (defsubst js2-check-activation-name (name token)
7197 (when (js2-inside-function)
7198 ;; skip language-version 1.2 check from Rhino
7199 (if (or (string= "arguments" name)
7200 (and js2-compiler-activation-names ; only used in codegen
7201 (gethash name js2-compiler-activation-names)))
7202 (js2-set-requires-activation))))
7203
7204 (defsubst js2-set-is-generator ()
7205 (if (js2-function-node-p js2-current-script-or-fn)
7206 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7207
7208 (defsubst js2-must-have-xml ()
7209 (unless js2-compiler-xml-available
7210 (js2-report-error "msg.XML.not.available")))
7211
7212 (defsubst js2-push-scope (scope)
7213 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7214 (assert (js2-scope-p scope))
7215 (assert (null (js2-scope-parent-scope scope)))
7216 (assert (not (eq js2-current-scope scope)))
7217 (setf (js2-scope-parent-scope scope) js2-current-scope
7218 js2-current-scope scope))
7219
7220 (defsubst js2-pop-scope ()
7221 (setq js2-current-scope
7222 (js2-scope-parent-scope js2-current-scope)))
7223
7224 (defsubst js2-enter-loop (loop-node)
7225 (push loop-node js2-loop-set)
7226 (push loop-node js2-loop-and-switch-set)
7227 (js2-push-scope loop-node)
7228 ;; Tell the current labeled statement (if any) its statement,
7229 ;; and set the jump target of the first label to the loop.
7230 ;; These are used in `js2-parse-continue' to verify that the
7231 ;; continue target is an actual labeled loop. (And for codegen.)
7232 (when js2-labeled-stmt
7233 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7234 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7235 js2-labeled-stmt))) loop-node)))
7236
7237 (defsubst js2-exit-loop ()
7238 (pop js2-loop-set)
7239 (pop js2-loop-and-switch-set)
7240 (js2-pop-scope))
7241
7242 (defsubst js2-enter-switch (switch-node)
7243 (push switch-node js2-loop-and-switch-set))
7244
7245 (defsubst js2-exit-switch ()
7246 (pop js2-loop-and-switch-set))
7247
7248 (defun js2-parse (&optional buf cb)
7249 "Tells the js2 parser to parse a region of JavaScript.
7250
7251 BUF is a buffer or buffer name containing the code to parse.
7252 Call `narrow-to-region' first to parse only part of the buffer.
7253
7254 The returned AST root node is given some additional properties:
7255 `node-count' - total number of nodes in the AST
7256 `buffer' - BUF. The buffer it refers to may change or be killed,
7257 so the value is not necessarily reliable.
7258
7259 An optional callback CB can be specified to report parsing
7260 progress. If `(functionp CB)' returns t, it will be called with
7261 the current line number once before parsing begins, then again
7262 each time the lexer reaches a new line number.
7263
7264 CB can also be a list of the form `(symbol cb ...)' to specify
7265 multiple callbacks with different criteria. Each symbol is a
7266 criterion keyword, and the following element is the callback to
7267 call
7268
7269 :line - called whenever the line number changes
7270 :token - called for each new token consumed
7271
7272 The list of criteria could be extended to include entering or
7273 leaving a statement, an expression, or a function definition."
7274 (if (and cb (not (functionp cb)))
7275 (error "criteria callbacks not yet implemented"))
7276 (let ((inhibit-point-motion-hooks t)
7277 (js2-compiler-xml-available (>= js2-language-version 160))
7278 ;; This is a recursive-descent parser, so give it a big stack.
7279 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7280 (max-specpdl-size (max max-specpdl-size 3000))
7281 (case-fold-search nil)
7282 ast)
7283 (or buf (setq buf (current-buffer)))
7284 (message nil) ; clear any error message from previous parse
7285 (save-excursion
7286 (set-buffer buf)
7287 (setq js2-scanned-comments nil
7288 js2-parsed-errors nil
7289 js2-parsed-warnings nil
7290 js2-imenu-recorder nil
7291 js2-imenu-function-map nil
7292 js2-label-set nil)
7293 (js2-init-scanner)
7294 (setq ast (js2-with-unmodifying-text-property-changes
7295 (js2-do-parse)))
7296 (unless js2-ts-hit-eof
7297 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7298 (setf (js2-ast-root-errors ast) js2-parsed-errors
7299 (js2-ast-root-warnings ast) js2-parsed-warnings)
7300 ;; if we didn't find any declarations, put a dummy in this list so we
7301 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7302 (unless js2-imenu-recorder
7303 (setq js2-imenu-recorder 'empty))
7304 (run-hooks 'js2-parse-finished-hook)
7305 ast)))
7306
7307 ;; Corresponds to Rhino's Parser.parse() method.
7308 (defun js2-do-parse ()
7309 "Parse current buffer starting from current point.
7310 Scanner should be initialized."
7311 (let ((pos js2-ts-cursor)
7312 (end js2-ts-cursor) ; in case file is empty
7313 root n tt)
7314 ;; initialize buffer-local parsing vars
7315 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7316 js2-current-script-or-fn root
7317 js2-current-scope root
7318 js2-current-flagged-token js2-EOF
7319 js2-nesting-of-function 0
7320 js2-labeled-stmt nil
7321 js2-recorded-assignments nil) ; for js2-highlight
7322 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7323 (if (= tt js2-FUNCTION)
7324 (progn
7325 (js2-consume-token)
7326 (setq n (js2-parse-function (if js2-called-by-compile-function
7327 'FUNCTION_EXPRESSION
7328 'FUNCTION_STATEMENT)))
7329 (js2-record-imenu-functions n))
7330 ;; not a function - parse a statement
7331 (setq n (js2-parse-statement)))
7332 ;; add function or statement to script
7333 (setq end (js2-node-end n))
7334 (js2-block-node-push root n))
7335 ;; add comments to root in lexical order
7336 (when js2-scanned-comments
7337 ;; if we find a comment beyond end of normal kids, use its end
7338 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7339 (dolist (comment js2-scanned-comments)
7340 (push comment (js2-ast-root-comments root))
7341 (js2-node-add-children root comment)))
7342 (setf (js2-node-len root) (- end pos))
7343 ;; Give extensions a chance to muck with things before highlighting starts.
7344 (dolist (callback js2-post-parse-callbacks)
7345 (funcall callback))
7346 (js2-highlight-undeclared-vars)
7347 root))
7348
7349 (defun js2-function-parser ()
7350 (js2-consume-token)
7351 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7352
7353 (defun js2-parse-function-closure-body (fn-node)
7354 "Parse a JavaScript 1.8 function closure body."
7355 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7356 (if js2-ts-hit-eof
7357 (js2-report-error "msg.no.brace.body" nil
7358 (js2-node-pos fn-node)
7359 (- js2-ts-cursor (js2-node-pos fn-node)))
7360 (js2-node-add-children fn-node
7361 (setf (js2-function-node-body fn-node)
7362 (js2-parse-expr t))))))
7363
7364 (defun js2-parse-function-body (fn-node)
7365 (js2-must-match js2-LC "msg.no.brace.body"
7366 (js2-node-pos fn-node)
7367 (- js2-ts-cursor (js2-node-pos fn-node)))
7368 (let ((pos js2-token-beg) ; LC position
7369 (pn (make-js2-block-node)) ; starts at LC position
7370 tt
7371 end)
7372 (incf js2-nesting-of-function)
7373 (unwind-protect
7374 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7375 (= tt js2-EOF)
7376 (= tt js2-RC)))
7377 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7378 (js2-parse-statement)
7379 (js2-consume-token)
7380 (js2-parse-function 'FUNCTION_STATEMENT))))
7381 (decf js2-nesting-of-function))
7382 (setq end js2-token-end) ; assume no curly and leave at current token
7383 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7384 (setq end js2-token-end))
7385 (setf (js2-node-pos pn) pos
7386 (js2-node-len pn) (- end pos))
7387 (setf (js2-function-node-body fn-node) pn)
7388 (js2-node-add-children fn-node pn)
7389 pn))
7390
7391 (defun js2-parse-function-params (fn-node pos)
7392 (if (js2-match-token js2-RP)
7393 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7394 (let (params len param)
7395 (loop for tt = (js2-peek-token)
7396 do
7397 (cond
7398 ;; destructuring param
7399 ((or (= tt js2-LB) (= tt js2-LC))
7400 (push (js2-parse-primary-expr-lhs) params))
7401 ;; simple name
7402 (t
7403 (js2-must-match js2-NAME "msg.no.parm")
7404 (js2-record-face 'js2-function-param-face)
7405 (setq param (js2-create-name-node))
7406 (js2-define-symbol js2-LP js2-ts-string param)
7407 (push param params)))
7408 while
7409 (js2-match-token js2-COMMA))
7410 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7411 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7412 (dolist (p params)
7413 (js2-node-add-children fn-node p)
7414 (push p (js2-function-node-params fn-node))))))
7415
7416 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7417 "Possibly show inconsistent-return warning.
7418 Last token scanned is the close-curly for the function body."
7419 (when (and js2-mode-show-strict-warnings
7420 js2-strict-inconsistent-return-warning
7421 (not (js2-has-consistent-return-usage
7422 (js2-function-node-body fn-node))))
7423 ;; Have it extend from close-curly to bol or beginning of block.
7424 (let ((pos (save-excursion
7425 (goto-char js2-token-end)
7426 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7427 (point-at-bol))))
7428 (end js2-token-end))
7429 (if (plusp (js2-name-node-length name))
7430 (js2-add-strict-warning "msg.no.return.value"
7431 (js2-name-node-name name) pos end)
7432 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7433
7434 (defun js2-parse-function (function-type)
7435 "Function parser. FUNCTION-TYPE is a symbol."
7436 (let ((pos js2-token-beg) ; start of 'function' keyword
7437 name
7438 name-beg
7439 name-end
7440 fn-node
7441 lp
7442 (synthetic-type function-type)
7443 member-expr-node)
7444 ;; parse function name, expression, or non-name (anonymous)
7445 (cond
7446 ;; function foo(...)
7447 ((js2-match-token js2-NAME)
7448 (setq name (js2-create-name-node t)
7449 name-beg js2-token-beg
7450 name-end js2-token-end)
7451 (unless (js2-match-token js2-LP)
7452 (when js2-allow-member-expr-as-function-name
7453 ;; function foo.bar(...)
7454 (setq member-expr-node name
7455 name nil
7456 member-expr-node (js2-parse-member-expr-tail
7457 nil member-expr-node)))
7458 (js2-must-match js2-LP "msg.no.paren.parms")))
7459 ((js2-match-token js2-LP)
7460 nil) ; anonymous function: leave name as null
7461 (t
7462 ;; function random-member-expr(...)
7463 (when js2-allow-member-expr-as-function-name
7464 ;; Note that memberExpr can not start with '(' like
7465 ;; in function (1+2).toString(), because 'function (' already
7466 ;; processed as anonymous function
7467 (setq member-expr-node (js2-parse-member-expr)))
7468 (js2-must-match js2-LP "msg.no.paren.parms")))
7469 (if (= js2-current-token js2-LP) ; eventually matched LP?
7470 (setq lp js2-token-beg))
7471 (if member-expr-node
7472 (progn
7473 (setq synthetic-type 'FUNCTION_EXPRESSION)
7474 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7475 (if name
7476 (js2-set-face name-beg name-end
7477 'font-lock-function-name-face 'record)))
7478 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7479 (plusp (js2-name-node-length name)))
7480 ;; Function statements define a symbol in the enclosing scope
7481 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7482 (setf fn-node (make-js2-function-node :pos pos
7483 :name name
7484 :form function-type
7485 :lp (if lp (- lp pos))))
7486 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7487 ;; 1. Nested functions are not affected by the dynamic scope flag
7488 ;; as dynamic scope is already a parent of their scope.
7489 ;; 2. Functions defined under the with statement also immune to
7490 ;; this setup, in which case dynamic scope is ignored in favor
7491 ;; of the with object.
7492 (setf (js2-function-node-ignore-dynamic fn-node) t))
7493 ;; dynamically bind all the per-function variables
7494 (let ((js2-current-script-or-fn fn-node)
7495 (js2-current-scope fn-node)
7496 (js2-nesting-of-with 0)
7497 (js2-end-flags 0)
7498 js2-label-set
7499 js2-loop-set
7500 js2-loop-and-switch-set)
7501 (js2-parse-function-params fn-node pos)
7502 (if (and (>= js2-language-version 180)
7503 (/= (js2-peek-token) js2-LC))
7504 (js2-parse-function-closure-body fn-node)
7505 (js2-parse-function-body fn-node))
7506 (if name
7507 (js2-node-add-children fn-node name))
7508 (js2-check-inconsistent-return-warning fn-node name)
7509 ;; Function expressions define a name only in the body of the
7510 ;; function, and only if not hidden by a parameter name
7511 (if (and name
7512 (eq synthetic-type 'FUNCTION_EXPRESSION)
7513 (null (js2-scope-get-symbol js2-current-scope
7514 (js2-name-node-name name))))
7515 (js2-define-symbol js2-FUNCTION
7516 (js2-name-node-name name)
7517 fn-node))
7518 (if (and name
7519 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7520 (js2-record-imenu-functions fn-node)))
7521 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7522 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7523 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7524 ;; We wait until after parsing the function to set its parent scope,
7525 ;; since `js2-define-symbol' needs the defining-scope check to stop
7526 ;; at the function boundary when checking for redeclarations.
7527 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7528 fn-node))
7529
7530 (defun js2-parse-statements (&optional parent)
7531 "Parse a statement list. Last token consumed must be js2-LC.
7532
7533 PARENT can be a `js2-block-node', in which case the statements are
7534 appended to PARENT. Otherwise a new `js2-block-node' is created
7535 and returned.
7536
7537 This function does not match the closing js2-RC: the caller
7538 matches the RC so it can provide a suitable error message if not
7539 matched. This means it's up to the caller to set the length of
7540 the node to include the closing RC. The node start pos is set to
7541 the absolute buffer start position, and the caller should fix it
7542 up to be relative to the parent node. All children of this block
7543 node are given relative start positions and correct lengths."
7544 (let ((pn (or parent (make-js2-block-node)))
7545 tt)
7546 (setf (js2-node-pos pn) js2-token-beg)
7547 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7548 (/= tt js2-RC))
7549 (js2-block-node-push pn (js2-parse-statement)))
7550 pn))
7551
7552 (defun js2-parse-statement ()
7553 (let (tt pn beg end)
7554 ;; coarse-grained user-interrupt check - needs work
7555 (and js2-parse-interruptable-p
7556 (zerop (% (incf js2-parse-stmt-count)
7557 js2-statements-per-pause))
7558 (input-pending-p)
7559 (throw 'interrupted t))
7560 (setq pn (js2-statement-helper))
7561 ;; no-side-effects warning check
7562 (unless (js2-node-has-side-effects pn)
7563 (setq end (js2-node-end pn))
7564 (save-excursion
7565 (goto-char end)
7566 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7567 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7568 pn))
7569
7570 ;; These correspond to the switch cases in Parser.statementHelper
7571 (defconst js2-parsers
7572 (let ((parsers (make-vector js2-num-tokens
7573 #'js2-parse-expr-stmt)))
7574 (aset parsers js2-BREAK #'js2-parse-break)
7575 (aset parsers js2-CONST #'js2-parse-const-var)
7576 (aset parsers js2-CONTINUE #'js2-parse-continue)
7577 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7578 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7579 (aset parsers js2-DO #'js2-parse-do)
7580 (aset parsers js2-FOR #'js2-parse-for)
7581 (aset parsers js2-FUNCTION #'js2-function-parser)
7582 (aset parsers js2-IF #'js2-parse-if)
7583 (aset parsers js2-LC #'js2-parse-block)
7584 (aset parsers js2-LET #'js2-parse-let-stmt)
7585 (aset parsers js2-NAME #'js2-parse-name-or-label)
7586 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7587 (aset parsers js2-SEMI #'js2-parse-semi)
7588 (aset parsers js2-SWITCH #'js2-parse-switch)
7589 (aset parsers js2-THROW #'js2-parse-throw)
7590 (aset parsers js2-TRY #'js2-parse-try)
7591 (aset parsers js2-VAR #'js2-parse-const-var)
7592 (aset parsers js2-WHILE #'js2-parse-while)
7593 (aset parsers js2-WITH #'js2-parse-with)
7594 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7595 parsers)
7596 "A vector mapping token types to parser functions.")
7597
7598 (defsubst js2-parse-warn-missing-semi (beg end)
7599 (and js2-mode-show-strict-warnings
7600 js2-strict-missing-semi-warning
7601 (js2-add-strict-warning
7602 "msg.missing.semi" nil
7603 ;; back up to beginning of statement or line
7604 (max beg (save-excursion
7605 (goto-char end)
7606 (point-at-bol)))
7607 end)))
7608
7609 (defconst js2-no-semi-insertion
7610 (list js2-IF
7611 js2-SWITCH
7612 js2-WHILE
7613 js2-DO
7614 js2-FOR
7615 js2-TRY
7616 js2-WITH
7617 js2-LC
7618 js2-ERROR
7619 js2-SEMI
7620 js2-FUNCTION)
7621 "List of tokens that don't do automatic semicolon insertion.")
7622
7623 (defconst js2-autoinsert-semi-and-warn
7624 (list js2-ERROR js2-EOF js2-RC))
7625
7626 (defun js2-statement-helper ()
7627 (let* ((tt (js2-peek-token))
7628 (first-tt tt)
7629 (beg js2-token-beg)
7630 (parser (if (= tt js2-ERROR)
7631 #'js2-parse-semi
7632 (aref js2-parsers tt)))
7633 pn
7634 tt-flagged)
7635 ;; If the statement is set, then it's been told its label by now.
7636 (and js2-labeled-stmt
7637 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7638 (setq js2-labeled-stmt nil))
7639 (setq pn (funcall parser))
7640 ;; Don't do auto semi insertion for certain statement types.
7641 (unless (or (memq first-tt js2-no-semi-insertion)
7642 (js2-labeled-stmt-node-p pn))
7643 (js2-auto-insert-semicolon pn))
7644 pn))
7645
7646 (defun js2-auto-insert-semicolon (pn)
7647 (let* ((tt-flagged (js2-peek-flagged-token))
7648 (tt (logand tt-flagged js2-clear-ti-mask))
7649 (pos (js2-node-pos pn)))
7650 (cond
7651 ((= tt js2-SEMI)
7652 ;; Consume ';' as a part of expression
7653 (js2-consume-token)
7654 ;; extend the node bounds to include the semicolon.
7655 (setf (js2-node-len pn) (- js2-token-end pos)))
7656 ((memq tt js2-autoinsert-semi-and-warn)
7657 ;; Autoinsert ;
7658 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7659 (t
7660 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7661 ;; Report error if no EOL or autoinsert ';' otherwise
7662 (js2-report-error "msg.no.semi.stmt")
7663 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7664
7665 (defun js2-parse-condition ()
7666 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7667 The parens are discarded and the expression node is returned.
7668 The `pos' field of the return value is set to an absolute position
7669 that must be fixed up by the caller.
7670 Return value is a list (EXPR LP RP), with absolute paren positions."
7671 (let (pn lp rp)
7672 (if (js2-must-match js2-LP "msg.no.paren.cond")
7673 (setq lp js2-token-beg))
7674 (setq pn (js2-parse-expr))
7675 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7676 (setq rp js2-token-beg))
7677 ;; Report strict warning on code like "if (a = 7) ..."
7678 (if (and js2-strict-cond-assign-warning
7679 (js2-assign-node-p pn))
7680 (js2-add-strict-warning "msg.equal.as.assign" nil
7681 (js2-node-pos pn)
7682 (+ (js2-node-pos pn)
7683 (js2-node-len pn))))
7684 (list pn lp rp)))
7685
7686 (defun js2-parse-if ()
7687 "Parser for if-statement. Last matched token must be js2-IF."
7688 (let ((pos js2-token-beg)
7689 cond
7690 if-true
7691 if-false
7692 else-pos
7693 end
7694 pn)
7695 (js2-consume-token)
7696 (setq cond (js2-parse-condition)
7697 if-true (js2-parse-statement)
7698 if-false (if (js2-match-token js2-ELSE)
7699 (progn
7700 (setq else-pos (- js2-token-beg pos))
7701 (js2-parse-statement)))
7702 end (js2-node-end (or if-false if-true))
7703 pn (make-js2-if-node :pos pos
7704 :len (- end pos)
7705 :condition (car cond)
7706 :then-part if-true
7707 :else-part if-false
7708 :else-pos else-pos
7709 :lp (js2-relpos (second cond) pos)
7710 :rp (js2-relpos (third cond) pos)))
7711 (js2-node-add-children pn (car cond) if-true if-false)
7712 pn))
7713
7714 (defun js2-parse-switch ()
7715 "Parser for if-statement. Last matched token must be js2-SWITCH."
7716 (let ((pos js2-token-beg)
7717 tt
7718 pn
7719 discriminant
7720 has-default
7721 case-expr
7722 case-node
7723 case-pos
7724 cases
7725 stmt
7726 lp
7727 rp)
7728 (js2-consume-token)
7729 (if (js2-must-match js2-LP "msg.no.paren.switch")
7730 (setq lp js2-token-beg))
7731 (setq discriminant (js2-parse-expr)
7732 pn (make-js2-switch-node :discriminant discriminant
7733 :pos pos
7734 :lp (js2-relpos lp pos)))
7735 (js2-node-add-children pn discriminant)
7736 (js2-enter-switch pn)
7737 (unwind-protect
7738 (progn
7739 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7740 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7741 (js2-must-match js2-LC "msg.no.brace.switch")
7742 (catch 'break
7743 (while t
7744 (setq tt (js2-next-token)
7745 case-pos js2-token-beg)
7746 (cond
7747 ((= tt js2-RC)
7748 (setf (js2-node-len pn) (- js2-token-end pos))
7749 (throw 'break nil)) ; done
7750 ((= tt js2-CASE)
7751 (setq case-expr (js2-parse-expr))
7752 (js2-must-match js2-COLON "msg.no.colon.case"))
7753 ((= tt js2-DEFAULT)
7754 (if has-default
7755 (js2-report-error "msg.double.switch.default"))
7756 (setq has-default t
7757 case-expr nil)
7758 (js2-must-match js2-COLON "msg.no.colon.case"))
7759 (t
7760 (js2-report-error "msg.bad.switch")
7761 (throw 'break nil)))
7762 (setq case-node (make-js2-case-node :pos case-pos
7763 :len (- js2-token-end case-pos)
7764 :expr case-expr))
7765 (js2-node-add-children case-node case-expr)
7766 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7767 (/= tt js2-CASE)
7768 (/= tt js2-DEFAULT)
7769 (/= tt js2-EOF))
7770 (setf stmt (js2-parse-statement)
7771 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7772 (js2-block-node-push case-node stmt))
7773 (push case-node cases)))
7774 ;; add cases last, as pushing reverses the order to be correct
7775 (dolist (kid cases)
7776 (js2-node-add-children pn kid)
7777 (push kid (js2-switch-node-cases pn)))
7778 pn) ; return value
7779 (js2-exit-switch))))
7780
7781 (defun js2-parse-while ()
7782 "Parser for while-statement. Last matched token must be js2-WHILE."
7783 (let ((pos js2-token-beg)
7784 (pn (make-js2-while-node))
7785 cond
7786 body)
7787 (js2-consume-token)
7788 (js2-enter-loop pn)
7789 (unwind-protect
7790 (progn
7791 (setf cond (js2-parse-condition)
7792 (js2-while-node-condition pn) (car cond)
7793 body (js2-parse-statement)
7794 (js2-while-node-body pn) body
7795 (js2-node-len pn) (- (js2-node-end body) pos)
7796 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7797 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7798 (js2-node-add-children pn body (car cond)))
7799 (js2-exit-loop))
7800 pn))
7801
7802 (defun js2-parse-do ()
7803 "Parser for do-statement. Last matched token must be js2-DO."
7804 (let ((pos js2-token-beg)
7805 (pn (make-js2-do-node))
7806 cond
7807 body
7808 end)
7809 (js2-consume-token)
7810 (js2-enter-loop pn)
7811 (unwind-protect
7812 (progn
7813 (setq body (js2-parse-statement))
7814 (js2-must-match js2-WHILE "msg.no.while.do")
7815 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7816 cond (js2-parse-condition)
7817 (js2-do-node-condition pn) (car cond)
7818 (js2-do-node-body pn) body
7819 end js2-ts-cursor
7820 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7821 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7822 (js2-node-add-children pn (car cond) body))
7823 (js2-exit-loop))
7824 ;; Always auto-insert semicolon to follow SpiderMonkey:
7825 ;; It is required by ECMAScript but is ignored by the rest of
7826 ;; world; see bug 238945
7827 (if (js2-match-token js2-SEMI)
7828 (setq end js2-ts-cursor))
7829 (setf (js2-node-len pn) (- end pos))
7830 pn))
7831
7832 (defun js2-parse-for ()
7833 "Parser for for-statement. Last matched token must be js2-FOR.
7834 Parses for, for-in, and for each-in statements."
7835 (let ((for-pos js2-token-beg)
7836 pn
7837 is-for-each
7838 is-for-in
7839 in-pos
7840 each-pos
7841 tmp-pos
7842 init ; Node init is also foo in 'foo in object'
7843 cond ; Node cond is also object in 'foo in object'
7844 incr ; 3rd section of for-loop initializer
7845 body
7846 tt
7847 lp
7848 rp)
7849 (js2-consume-token)
7850 ;; See if this is a for each () instead of just a for ()
7851 (when (js2-match-token js2-NAME)
7852 (if (string= "each" js2-ts-string)
7853 (progn
7854 (setq is-for-each t
7855 each-pos (- js2-token-beg for-pos)) ; relative
7856 (js2-record-face 'font-lock-keyword-face))
7857 (js2-report-error "msg.no.paren.for")))
7858 (if (js2-must-match js2-LP "msg.no.paren.for")
7859 (setq lp (- js2-token-beg for-pos)))
7860 (setq tt (js2-peek-token))
7861 ;; parse init clause
7862 (let ((js2-in-for-init t)) ; set as dynamic variable
7863 (cond
7864 ((= tt js2-SEMI)
7865 (setq init (make-js2-empty-expr-node)))
7866 ((or (= tt js2-VAR) (= tt js2-LET))
7867 (js2-consume-token)
7868 (setq init (js2-parse-variables tt js2-token-beg)))
7869 (t
7870 (setq init (js2-parse-expr)))))
7871 (if (js2-match-token js2-IN)
7872 (setq is-for-in t
7873 in-pos (- js2-token-beg for-pos)
7874 cond (js2-parse-expr)) ; object over which we're iterating
7875 ;; else ordinary for loop - parse cond and incr
7876 (js2-must-match js2-SEMI "msg.no.semi.for")
7877 (setq cond (if (= (js2-peek-token) js2-SEMI)
7878 (make-js2-empty-expr-node) ; no loop condition
7879 (js2-parse-expr)))
7880 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7881 (setq tmp-pos js2-token-end
7882 incr (if (= (js2-peek-token) js2-RP)
7883 (make-js2-empty-expr-node :pos tmp-pos)
7884 (js2-parse-expr))))
7885 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7886 (setq rp (- js2-token-beg for-pos)))
7887 (if (not is-for-in)
7888 (setq pn (make-js2-for-node :init init
7889 :condition cond
7890 :update incr
7891 :lp lp
7892 :rp rp))
7893 ;; cond could be null if 'in obj' got eaten by the init node.
7894 (if (js2-infix-node-p init)
7895 ;; it was (foo in bar) instead of (var foo in bar)
7896 (setq cond (js2-infix-node-right init)
7897 init (js2-infix-node-left init))
7898 (if (and (js2-var-decl-node-p init)
7899 (> (length (js2-var-decl-node-kids init)) 1))
7900 (js2-report-error "msg.mult.index")))
7901 (setq pn (make-js2-for-in-node :iterator init
7902 :object cond
7903 :in-pos in-pos
7904 :foreach-p is-for-each
7905 :each-pos each-pos
7906 :lp lp
7907 :rp rp)))
7908 (unwind-protect
7909 (progn
7910 (js2-enter-loop pn)
7911 ;; We have to parse the body -after- creating the loop node,
7912 ;; so that the loop node appears in the js2-loop-set, allowing
7913 ;; break/continue statements to find the enclosing loop.
7914 (setf body (js2-parse-statement)
7915 (js2-loop-node-body pn) body
7916 (js2-node-pos pn) for-pos
7917 (js2-node-len pn) (- (js2-node-end body) for-pos))
7918 (js2-node-add-children pn init cond incr body))
7919 ;; finally
7920 (js2-exit-loop))
7921 pn))
7922
7923 (defun js2-parse-try ()
7924 "Parser for try-statement. Last matched token must be js2-TRY."
7925 (let ((try-pos js2-token-beg)
7926 try-end
7927 try-block
7928 catch-blocks
7929 finally-block
7930 saw-default-catch
7931 peek
7932 var-name
7933 catch-cond
7934 catch-node
7935 guard-kwd
7936 catch-pos
7937 finally-pos
7938 pn
7939 block
7940 lp
7941 rp)
7942 (js2-consume-token)
7943 (if (/= (js2-peek-token) js2-LC)
7944 (js2-report-error "msg.no.brace.try"))
7945 (setq try-block (js2-parse-statement)
7946 try-end (js2-node-end try-block)
7947 peek (js2-peek-token))
7948 (cond
7949 ((= peek js2-CATCH)
7950 (while (js2-match-token js2-CATCH)
7951 (setq catch-pos js2-token-beg
7952 guard-kwd nil
7953 catch-cond nil
7954 lp nil
7955 rp nil)
7956 (if saw-default-catch
7957 (js2-report-error "msg.catch.unreachable"))
7958 (if (js2-must-match js2-LP "msg.no.paren.catch")
7959 (setq lp (- js2-token-beg catch-pos)))
7960 (js2-must-match js2-NAME "msg.bad.catchcond")
7961 (setq var-name (js2-create-name-node))
7962 (if (js2-match-token js2-IF)
7963 (setq guard-kwd (- js2-token-beg catch-pos)
7964 catch-cond (js2-parse-expr))
7965 (setq saw-default-catch t))
7966 (if (js2-must-match js2-RP "msg.bad.catchcond")
7967 (setq rp (- js2-token-beg catch-pos)))
7968 (js2-must-match js2-LC "msg.no.brace.catchblock")
7969 (setq block (js2-parse-statements)
7970 try-end (js2-node-end block)
7971 catch-node (make-js2-catch-node :pos catch-pos
7972 :var-name var-name
7973 :guard-expr catch-cond
7974 :guard-kwd guard-kwd
7975 :block block
7976 :lp lp
7977 :rp rp))
7978 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7979 (setq try-end js2-token-beg))
7980 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7981 (js2-node-len catch-node) (- try-end catch-pos))
7982 (js2-node-add-children catch-node var-name catch-cond block)
7983 (push catch-node catch-blocks)))
7984 ((/= peek js2-FINALLY)
7985 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7986 (js2-node-pos try-block)
7987 (- (setq try-end (js2-node-end try-block))
7988 (js2-node-pos try-block)))))
7989 (when (js2-match-token js2-FINALLY)
7990 (setq finally-pos js2-token-beg
7991 block (js2-parse-statement)
7992 try-end (js2-node-end block)
7993 finally-block (make-js2-finally-node :pos finally-pos
7994 :len (- try-end finally-pos)
7995 :body block))
7996 (js2-node-add-children finally-block block))
7997 (setq pn (make-js2-try-node :pos try-pos
7998 :len (- try-end try-pos)
7999 :try-block try-block
8000 :finally-block finally-block))
8001 (js2-node-add-children pn try-block finally-block)
8002 ;; push them onto the try-node, which reverses and corrects their order
8003 (dolist (cb catch-blocks)
8004 (js2-node-add-children pn cb)
8005 (push cb (js2-try-node-catch-clauses pn)))
8006 pn))
8007
8008 (defun js2-parse-throw ()
8009 "Parser for throw-statement. Last matched token must be js2-THROW."
8010 (let ((pos js2-token-beg)
8011 expr
8012 pn)
8013 (js2-consume-token)
8014 (if (= (js2-peek-token-or-eol) js2-EOL)
8015 ;; ECMAScript does not allow new lines before throw expression,
8016 ;; see bug 256617
8017 (js2-report-error "msg.bad.throw.eol"))
8018 (setq expr (js2-parse-expr)
8019 pn (make-js2-throw-node :pos pos
8020 :len (- (js2-node-end expr) pos)
8021 :expr expr))
8022 (js2-node-add-children pn expr)
8023 pn))
8024
8025 (defsubst js2-match-jump-label-name (label-name)
8026 "If break/continue specified a label, return that label's labeled stmt.
8027 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8028 does not match an existing label, reports an error and returns nil."
8029 (let ((bundle (cdr (assoc label-name js2-label-set))))
8030 (if (null bundle)
8031 (js2-report-error "msg.undef.label"))
8032 bundle))
8033
8034 (defun js2-parse-break ()
8035 "Parser for break-statement. Last matched token must be js2-BREAK."
8036 (let ((pos js2-token-beg)
8037 (end js2-token-end)
8038 break-target ; statement to break from
8039 break-label ; in "break foo", name-node representing the foo
8040 labels ; matching labeled statement to break to
8041 pn)
8042 (js2-consume-token) ; `break'
8043 (when (eq (js2-peek-token-or-eol) js2-NAME)
8044 (js2-consume-token)
8045 (setq break-label (js2-create-name-node)
8046 end (js2-node-end break-label)
8047 ;; matchJumpLabelName only matches if there is one
8048 labels (js2-match-jump-label-name js2-ts-string)
8049 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8050 (unless (or break-target break-label)
8051 ;; no break target specified - try for innermost enclosing loop/switch
8052 (if (null js2-loop-and-switch-set)
8053 (unless break-label
8054 (js2-report-error "msg.bad.break" nil pos (length "break")))
8055 (setq break-target (car js2-loop-and-switch-set))))
8056 (setq pn (make-js2-break-node :pos pos
8057 :len (- end pos)
8058 :label break-label
8059 :target break-target))
8060 (js2-node-add-children pn break-label) ; but not break-target
8061 pn))
8062
8063 (defun js2-parse-continue ()
8064 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8065 (let ((pos js2-token-beg)
8066 (end js2-token-end)
8067 label ; optional user-specified label, a `js2-name-node'
8068 labels ; current matching labeled stmt, if any
8069 target ; the `js2-loop-node' target of this continue stmt
8070 pn)
8071 (js2-consume-token) ; `continue'
8072 (when (= (js2-peek-token-or-eol) js2-NAME)
8073 (js2-consume-token)
8074 (setq label (js2-create-name-node)
8075 end (js2-node-end label)
8076 ;; matchJumpLabelName only matches if there is one
8077 labels (js2-match-jump-label-name js2-ts-string)))
8078 (cond
8079 ((null labels) ; no current label to go to
8080 (if (null js2-loop-set) ; no loop to continue to
8081 (js2-report-error "msg.continue.outside" nil pos
8082 (length "continue"))
8083 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8084 (t
8085 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8086 (setq target (js2-labeled-stmt-node-stmt labels))
8087 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8088 (setq pn (make-js2-continue-node :pos pos
8089 :len (- end pos)
8090 :label label
8091 :target target))
8092 (js2-node-add-children pn label) ; but not target - it's not our child
8093 pn))
8094
8095 (defun js2-parse-with ()
8096 "Parser for with-statement. Last matched token must be js2-WITH."
8097 (js2-consume-token)
8098 (let ((pos js2-token-beg)
8099 obj body pn lp rp)
8100 (if (js2-must-match js2-LP "msg.no.paren.with")
8101 (setq lp js2-token-beg))
8102 (setq obj (js2-parse-expr))
8103 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8104 (setq rp js2-token-beg))
8105 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8106 (setq body (js2-parse-statement)))
8107 (setq pn (make-js2-with-node :pos pos
8108 :len (- (js2-node-end body) pos)
8109 :object obj
8110 :body body
8111 :lp (js2-relpos lp pos)
8112 :rp (js2-relpos rp pos)))
8113 (js2-node-add-children pn obj body)
8114 pn))
8115
8116 (defun js2-parse-const-var ()
8117 "Parser for var- or const-statement.
8118 Last matched token must be js2-CONST or js2-VAR."
8119 (let ((tt (js2-peek-token))
8120 (pos js2-token-beg)
8121 expr
8122 pn)
8123 (js2-consume-token)
8124 (setq expr (js2-parse-variables tt js2-token-beg)
8125 pn (make-js2-expr-stmt-node :pos pos
8126 :len (- (js2-node-end expr) pos)
8127 :expr expr))
8128 (js2-node-add-children pn expr)
8129 pn))
8130
8131 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8132 (let ((pn (make-js2-expr-stmt-node :pos pos
8133 :len (js2-node-len expr)
8134 :type (if (js2-inside-function)
8135 js2-EXPR_VOID
8136 js2-EXPR_RESULT)
8137 :expr expr)))
8138 (if add-child
8139 (js2-node-add-children pn expr))
8140 pn))
8141
8142 (defun js2-parse-let-stmt ()
8143 "Parser for let-statement. Last matched token must be js2-LET."
8144 (js2-consume-token)
8145 (let ((pos js2-token-beg)
8146 expr
8147 pn)
8148 (if (= (js2-peek-token) js2-LP)
8149 ;; let expression in statement context
8150 (setq expr (js2-parse-let pos 'statement)
8151 pn (js2-wrap-with-expr-stmt pos expr t))
8152 ;; else we're looking at a statement like let x=6, y=7;
8153 (setf expr (js2-parse-variables js2-LET pos)
8154 pn (js2-wrap-with-expr-stmt pos expr t)
8155 (js2-node-type pn) js2-EXPR_RESULT))
8156 pn))
8157
8158 (defun js2-parse-ret-yield ()
8159 (js2-parse-return-or-yield (js2-peek-token) nil))
8160
8161 (defconst js2-parse-return-stmt-enders
8162 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8163
8164 (defsubst js2-now-all-set (before after mask)
8165 "Return whether or not the bits in the mask have changed to all set.
8166 BEFORE is bits before change, AFTER is bits after change, and MASK is
8167 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8168 but not BEFORE."
8169 (and (/= (logand before mask) mask)
8170 (= (logand after mask) mask)))
8171
8172 (defun js2-parse-return-or-yield (tt expr-context)
8173 (let ((pos js2-token-beg)
8174 (end js2-token-end)
8175 (before js2-end-flags)
8176 (inside-function (js2-inside-function))
8177 e
8178 ret
8179 name)
8180 (unless inside-function
8181 (js2-report-error (if (eq tt js2-RETURN)
8182 "msg.bad.return"
8183 "msg.bad.yield")))
8184 (js2-consume-token)
8185 ;; This is ugly, but we don't want to require a semicolon.
8186 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8187 (setq e (js2-parse-expr)
8188 end (js2-node-end e)))
8189 (cond
8190 ((eq tt js2-RETURN)
8191 (js2-set-flag js2-end-flags (if (null e)
8192 js2-end-returns
8193 js2-end-returns-value))
8194 (setq ret (make-js2-return-node :pos pos
8195 :len (- end pos)
8196 :retval e))
8197 (js2-node-add-children ret e)
8198 ;; See if we need a strict mode warning.
8199 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8200 ;; more thorough and accurate than this before/after flag check.
8201 ;; E.g. if there's a finally-block that always returns, we shouldn't
8202 ;; show a warning generated by inconsistent returns in the catch blocks.
8203 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8204 ;; so we know which returns/yields to highlight, and we should get rid of
8205 ;; all the checking in `js2-parse-return-or-yield'.
8206 (if (and js2-strict-inconsistent-return-warning
8207 (js2-now-all-set before js2-end-flags
8208 (logior js2-end-returns js2-end-returns-value)))
8209 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8210 (t
8211 (unless (js2-inside-function)
8212 (js2-report-error "msg.bad.yield"))
8213 (js2-set-flag js2-end-flags js2-end-yields)
8214 (setq ret (make-js2-yield-node :pos pos
8215 :len (- end pos)
8216 :value e))
8217 (js2-node-add-children ret e)
8218 (unless expr-context
8219 (setq e ret
8220 ret (js2-wrap-with-expr-stmt pos e t))
8221 (js2-set-requires-activation)
8222 (js2-set-is-generator))))
8223 ;; see if we are mixing yields and value returns.
8224 (when (and inside-function
8225 (js2-now-all-set before js2-end-flags
8226 (logior js2-end-yields js2-end-returns-value)))
8227 (setq name (js2-function-name js2-current-script-or-fn))
8228 (if (zerop (length name))
8229 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8230 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8231 ret))
8232
8233 (defun js2-parse-debugger ()
8234 (js2-consume-token)
8235 (make-js2-keyword-node :type js2-DEBUGGER))
8236
8237 (defun js2-parse-block ()
8238 "Parser for a curly-delimited statement block.
8239 Last token matched must be js2-LC."
8240 (let ((pos js2-token-beg)
8241 (pn (make-js2-scope)))
8242 (js2-consume-token)
8243 (js2-push-scope pn)
8244 (unwind-protect
8245 (progn
8246 (js2-parse-statements pn)
8247 (js2-must-match js2-RC "msg.no.brace.block")
8248 (setf (js2-node-len pn) (- js2-token-end pos)))
8249 (js2-pop-scope))
8250 pn))
8251
8252 ;; for js2-ERROR too, to have a node for error recovery to work on
8253 (defun js2-parse-semi ()
8254 "Parse a statement or handle an error.
8255 Last matched token is js-SEMI or js-ERROR."
8256 (let ((tt (js2-peek-token)) pos len)
8257 (js2-consume-token)
8258 (if (eq tt js2-SEMI)
8259 (make-js2-empty-expr-node :len 1)
8260 (setq pos js2-token-beg
8261 len (- js2-token-beg pos))
8262 (js2-report-error "msg.syntax" nil pos len)
8263 (make-js2-error-node :pos pos :len len))))
8264
8265 (defun js2-parse-default-xml-namespace ()
8266 "Parse a `default xml namespace = <expr>' e4x statement."
8267 (let ((pos js2-token-beg)
8268 end len expr unary es)
8269 (js2-consume-token)
8270 (js2-must-have-xml)
8271 (js2-set-requires-activation)
8272 (setq len (- js2-ts-cursor pos))
8273 (unless (and (js2-match-token js2-NAME)
8274 (string= js2-ts-string "xml"))
8275 (js2-report-error "msg.bad.namespace" nil pos len))
8276 (unless (and (js2-match-token js2-NAME)
8277 (string= js2-ts-string "namespace"))
8278 (js2-report-error "msg.bad.namespace" nil pos len))
8279 (unless (js2-match-token js2-ASSIGN)
8280 (js2-report-error "msg.bad.namespace" nil pos len))
8281 (setq expr (js2-parse-expr)
8282 end (js2-node-end expr)
8283 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8284 :pos pos
8285 :len (- end pos)
8286 :operand expr))
8287 (js2-node-add-children unary expr)
8288 (make-js2-expr-stmt-node :pos pos
8289 :len (- end pos)
8290 :expr unary)))
8291
8292 (defun js2-record-label (label bundle)
8293 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8294 (js2-consume-token)
8295 (let ((name (js2-label-node-name label))
8296 labeled-stmt
8297 dup)
8298 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8299 ;; flag both labels if possible when used in editing mode
8300 (if (and js2-parse-ide-mode
8301 (setq dup (js2-get-label-by-name labeled-stmt name)))
8302 (js2-report-error "msg.dup.label" nil
8303 (js2-node-abs-pos dup) (js2-node-len dup)))
8304 (js2-report-error "msg.dup.label" nil
8305 (js2-node-pos label) (js2-node-len label)))
8306 (js2-labeled-stmt-node-add-label bundle label)
8307 (js2-node-add-children bundle label)
8308 ;; Add one reference to the bundle per label in `js2-label-set'
8309 (push (cons name bundle) js2-label-set)))
8310
8311 (defun js2-parse-name-or-label ()
8312 "Parser for identifier or label. Last token matched must be js2-NAME.
8313 Called when we found a name in a statement context. If it's a label, we gather
8314 up any following labels and the next non-label statement into a
8315 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8316 expression and return it wrapped in a `js2-expr-stmt-node'."
8317 (let ((pos js2-token-beg)
8318 (end js2-token-end)
8319 expr
8320 stmt
8321 pn
8322 bundle
8323 (continue t))
8324 ;; set check for label and call down to `js2-parse-primary-expr'
8325 (js2-set-check-for-label)
8326 (setq expr (js2-parse-expr))
8327 (if (/= (js2-node-type expr) js2-LABEL)
8328 ;; Parsed non-label expression - wrap with expression stmt.
8329 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8330 ;; else parsed a label
8331 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8332 (js2-record-label expr bundle)
8333 ;; look for more labels
8334 (while (and continue (= (js2-peek-token) js2-NAME))
8335 (js2-set-check-for-label)
8336 (setq expr (js2-parse-expr))
8337 (if (/= (js2-node-type expr) js2-LABEL)
8338 (progn
8339 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8340 continue nil)
8341 (js2-auto-insert-semicolon stmt))
8342 (js2-record-label expr bundle)))
8343 ;; no more labels; now parse the labeled statement
8344 (unwind-protect
8345 (unless stmt
8346 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8347 (setq stmt (js2-statement-helper))))
8348 ;; remove the labels for this statement from the global set
8349 (dolist (label (js2-labeled-stmt-node-labels bundle))
8350 (setq js2-label-set (remove label js2-label-set))))
8351 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8352 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8353 (js2-node-add-children bundle stmt)
8354 bundle)))
8355
8356 (defun js2-parse-expr-stmt ()
8357 "Default parser in statement context, if no recognized statement found."
8358 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8359
8360 (defun js2-parse-variables (decl-type pos)
8361 "Parse a comma-separated list of variable declarations.
8362 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8363
8364 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8365 For 'var' or 'const', the keyword should be the token last scanned.
8366
8367 POS is the position where the node should start. It's sometimes the
8368 var/const/let keyword, and other times the beginning of the first token
8369 in the first variable declaration.
8370
8371 Returns the parsed `js2-var-decl-node' expression node."
8372 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8373 :pos pos))
8374 destructuring
8375 kid-pos
8376 tt
8377 init
8378 name
8379 end
8380 nbeg nend
8381 vi
8382 (continue t))
8383 ;; Example:
8384 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8385 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8386 ;; var {a, b} = baz;
8387 (while continue
8388 (setq destructuring nil
8389 name nil
8390 tt (js2-peek-token)
8391 kid-pos js2-token-beg
8392 end js2-token-end
8393 init nil)
8394 (if (or (= tt js2-LB) (= tt js2-LC))
8395 ;; Destructuring assignment, e.g., var [a, b] = ...
8396 (setq destructuring (js2-parse-primary-expr-lhs)
8397 end (js2-node-end destructuring))
8398 ;; Simple variable name
8399 (when (js2-must-match js2-NAME "msg.bad.var")
8400 (setq name (js2-create-name-node)
8401 nbeg js2-token-beg
8402 nend js2-token-end
8403 end nend)
8404 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8405 (when (js2-match-token js2-ASSIGN)
8406 (setq init (js2-parse-assign-expr)
8407 end (js2-node-end init))
8408 (if (and js2-parse-ide-mode
8409 (or (js2-object-node-p init)
8410 (js2-function-node-p init)))
8411 (js2-record-imenu-functions init name)))
8412 (when name
8413 (js2-set-face nbeg nend (if (js2-function-node-p init)
8414 'font-lock-function-name-face
8415 'font-lock-variable-name-face)
8416 'record))
8417 (setq vi (make-js2-var-init-node :pos kid-pos
8418 :len (- end kid-pos)
8419 :type decl-type))
8420 (if destructuring
8421 (progn
8422 (if (and (null init) (not js2-in-for-init))
8423 (js2-report-error "msg.destruct.assign.no.init"))
8424 (setf (js2-var-init-node-target vi) destructuring))
8425 (setf (js2-var-init-node-target vi) name))
8426 (setf (js2-var-init-node-initializer vi) init)
8427 (js2-node-add-children vi name destructuring init)
8428 (js2-block-node-push result vi)
8429 (unless (js2-match-token js2-COMMA)
8430 (setq continue nil)))
8431 (setf (js2-node-len result) (- end pos))
8432 result))
8433
8434 (defun js2-parse-let (pos &optional stmt-p)
8435 "Parse a let expression or statement.
8436 A let-expression is of the form `let (vars) expr'.
8437 A let-statment is of the form `let (vars) {statements}'.
8438 The third form of let is a variable declaration list, handled
8439 by `js2-parse-variables'."
8440 (let ((pn (make-js2-let-node :pos pos))
8441 beg vars body)
8442 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8443 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8444 (js2-push-scope pn)
8445 (unwind-protect
8446 (progn
8447 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8448 (if (js2-must-match js2-RP "msg.no.paren.let")
8449 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8450 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8451 ;; let statement
8452 (progn
8453 (js2-consume-token)
8454 (setf beg js2-token-beg ; position stmt at LC
8455 body (js2-parse-statements))
8456 (js2-must-match js2-RC "msg.no.curly.let")
8457 (setf (js2-node-len body) (- js2-token-end beg)
8458 (js2-node-len pn) (- js2-token-end pos)
8459 (js2-let-node-body pn) body
8460 (js2-node-type pn) js2-LET))
8461 ;; let expression
8462 (setf body (js2-parse-expr)
8463 (js2-node-len pn) (- (js2-node-end body) pos)
8464 (js2-let-node-body pn) body))
8465 (js2-node-add-children pn vars body))
8466 (js2-pop-scope))
8467 pn))
8468
8469 (defsubst js2-define-new-symbol (decl-type name node)
8470 (js2-scope-put-symbol js2-current-scope
8471 name
8472 (make-js2-symbol decl-type name node)))
8473
8474 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8475 "Define a symbol in the current scope.
8476 If NODE is non-nil, it is the AST node associated with the symbol."
8477 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8478 (symbol (if defining-scope
8479 (js2-scope-get-symbol defining-scope name)))
8480 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8481 (cond
8482 ((and symbol ; already defined
8483 (or (= sdt js2-CONST) ; old version is const
8484 (= decl-type js2-CONST) ; new version is const
8485 ;; two let-bound vars in this block have same name
8486 (and (= sdt js2-LET)
8487 (eq defining-scope js2-current-scope))))
8488 (js2-report-error
8489 (cond
8490 ((= sdt js2-CONST) "msg.const.redecl")
8491 ((= sdt js2-LET) "msg.let.redecl")
8492 ((= sdt js2-VAR) "msg.var.redecl")
8493 ((= sdt js2-FUNCTION) "msg.function.redecl")
8494 (t "msg.parm.redecl"))
8495 name))
8496 ((= decl-type js2-LET)
8497 (if (and (not ignore-not-in-block)
8498 (or (= (js2-node-type js2-current-scope) js2-IF)
8499 (js2-loop-node-p js2-current-scope)))
8500 (js2-report-error "msg.let.decl.not.in.block")
8501 (js2-define-new-symbol decl-type name node)))
8502 ((or (= decl-type js2-VAR)
8503 (= decl-type js2-CONST)
8504 (= decl-type js2-FUNCTION))
8505 (if symbol
8506 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8507 (js2-add-strict-warning "msg.var.redecl" name)
8508 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8509 (js2-add-strict-warning "msg.var.hides.arg" name)))
8510 (js2-define-new-symbol decl-type name node)))
8511 ((= decl-type js2-LP)
8512 (if symbol
8513 ;; must be duplicate parameter. Second parameter hides the
8514 ;; first, so go ahead and add the second pararameter
8515 (js2-report-warning "msg.dup.parms" name))
8516 (js2-define-new-symbol decl-type name node))
8517 (t (js2-code-bug)))))
8518
8519 (defun js2-parse-expr (&optional oneshot)
8520 (let* ((pn (js2-parse-assign-expr))
8521 (pos (js2-node-pos pn))
8522 left
8523 right
8524 op-pos)
8525 (while (and (not oneshot)
8526 (js2-match-token js2-COMMA))
8527 (setq op-pos (- js2-token-beg pos)) ; relative
8528 (if (= (js2-peek-token) js2-YIELD)
8529 (js2-report-error "msg.yield.parenthesized"))
8530 (setq right (js2-parse-assign-expr)
8531 left pn
8532 pn (make-js2-infix-node :type js2-COMMA
8533 :pos pos
8534 :len (- js2-ts-cursor pos)
8535 :op-pos op-pos
8536 :left left
8537 :right right))
8538 (js2-node-add-children pn left right))
8539 pn))
8540
8541 (defun js2-parse-assign-expr ()
8542 (let ((tt (js2-peek-token))
8543 (pos js2-token-beg)
8544 pn
8545 left
8546 right
8547 op-pos)
8548 (if (= tt js2-YIELD)
8549 (js2-parse-return-or-yield tt t)
8550 ;; not yield - parse assignment expression
8551 (setq pn (js2-parse-cond-expr)
8552 tt (js2-peek-token))
8553 (when (and (<= js2-first-assign tt)
8554 (<= tt js2-last-assign))
8555 ;; tt express assignment (=, |=, ^=, ..., %=)
8556 (js2-consume-token)
8557 (setq op-pos (- js2-token-beg pos) ; relative
8558 left pn
8559 right (js2-parse-assign-expr)
8560 pn (make-js2-assign-node :type tt
8561 :pos pos
8562 :len (- (js2-node-end right) pos)
8563 :op-pos op-pos
8564 :left left
8565 :right right))
8566 (when js2-parse-ide-mode
8567 (js2-highlight-assign-targets pn left right)
8568 (if (or (js2-function-node-p right)
8569 (js2-object-node-p right))
8570 (js2-record-imenu-functions right left)))
8571 ;; do this last so ide checks above can use absolute positions
8572 (js2-node-add-children pn left right))
8573 pn)))
8574
8575 (defun js2-parse-cond-expr ()
8576 (let ((pos js2-token-beg)
8577 (pn (js2-parse-or-expr))
8578 test-expr
8579 if-true
8580 if-false
8581 q-pos
8582 c-pos)
8583 (when (js2-match-token js2-HOOK)
8584 (setq q-pos (- js2-token-beg pos)
8585 if-true (js2-parse-assign-expr))
8586 (js2-must-match js2-COLON "msg.no.colon.cond")
8587 (setq c-pos (- js2-token-beg pos)
8588 if-false (js2-parse-assign-expr)
8589 test-expr pn
8590 pn (make-js2-cond-node :pos pos
8591 :len (- (js2-node-end if-false) pos)
8592 :test-expr test-expr
8593 :true-expr if-true
8594 :false-expr if-false
8595 :q-pos q-pos
8596 :c-pos c-pos))
8597 (js2-node-add-children pn test-expr if-true if-false))
8598 pn))
8599
8600 (defun js2-make-binary (type left parser)
8601 "Helper for constructing a binary-operator AST node.
8602 LEFT is the left-side-expression, already parsed, and the
8603 binary operator should have just been matched.
8604 PARSER is a function to call to parse the right operand,
8605 or a `js2-node' struct if it has already been parsed."
8606 (let* ((pos (js2-node-pos left))
8607 (op-pos (- js2-token-beg pos))
8608 (right (if (js2-node-p parser)
8609 parser
8610 (funcall parser)))
8611 (pn (make-js2-infix-node :type type
8612 :pos pos
8613 :len (- (js2-node-end right) pos)
8614 :op-pos op-pos
8615 :left left
8616 :right right)))
8617 (js2-node-add-children pn left right)
8618 pn))
8619
8620 (defun js2-parse-or-expr ()
8621 (let ((pn (js2-parse-and-expr)))
8622 (when (js2-match-token js2-OR)
8623 (setq pn (js2-make-binary js2-OR
8624 pn
8625 'js2-parse-or-expr)))
8626 pn))
8627
8628 (defun js2-parse-and-expr ()
8629 (let ((pn (js2-parse-bit-or-expr)))
8630 (when (js2-match-token js2-AND)
8631 (setq pn (js2-make-binary js2-AND
8632 pn
8633 'js2-parse-and-expr)))
8634 pn))
8635
8636 (defun js2-parse-bit-or-expr ()
8637 (let ((pn (js2-parse-bit-xor-expr)))
8638 (while (js2-match-token js2-BITOR)
8639 (setq pn (js2-make-binary js2-BITOR
8640 pn
8641 'js2-parse-bit-xor-expr)))
8642 pn))
8643
8644 (defun js2-parse-bit-xor-expr ()
8645 (let ((pn (js2-parse-bit-and-expr)))
8646 (while (js2-match-token js2-BITXOR)
8647 (setq pn (js2-make-binary js2-BITXOR
8648 pn
8649 'js2-parse-bit-and-expr)))
8650 pn))
8651
8652 (defun js2-parse-bit-and-expr ()
8653 (let ((pn (js2-parse-eq-expr)))
8654 (while (js2-match-token js2-BITAND)
8655 (setq pn (js2-make-binary js2-BITAND
8656 pn
8657 'js2-parse-eq-expr)))
8658 pn))
8659
8660 (defconst js2-parse-eq-ops
8661 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8662
8663 (defun js2-parse-eq-expr ()
8664 (let ((pn (js2-parse-rel-expr))
8665 tt)
8666 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8667 (js2-consume-token)
8668 (setq pn (js2-make-binary tt
8669 pn
8670 'js2-parse-rel-expr)))
8671 pn))
8672
8673 (defconst js2-parse-rel-ops
8674 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8675
8676 (defun js2-parse-rel-expr ()
8677 (let ((pn (js2-parse-shift-expr))
8678 (continue t)
8679 tt)
8680 (while continue
8681 (setq tt (js2-peek-token))
8682 (cond
8683 ((and js2-in-for-init (= tt js2-IN))
8684 (setq continue nil))
8685 ((memq tt js2-parse-rel-ops)
8686 (js2-consume-token)
8687 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8688 (t
8689 (setq continue nil))))
8690 pn))
8691
8692 (defconst js2-parse-shift-ops
8693 (list js2-LSH js2-URSH js2-RSH))
8694
8695 (defun js2-parse-shift-expr ()
8696 (let ((pn (js2-parse-add-expr))
8697 tt
8698 (continue t))
8699 (while continue
8700 (setq tt (js2-peek-token))
8701 (if (memq tt js2-parse-shift-ops)
8702 (progn
8703 (js2-consume-token)
8704 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8705 (setq continue nil)))
8706 pn))
8707
8708 (defun js2-parse-add-expr ()
8709 (let ((pn (js2-parse-mul-expr))
8710 tt
8711 (continue t))
8712 (while continue
8713 (setq tt (js2-peek-token))
8714 (if (or (= tt js2-ADD) (= tt js2-SUB))
8715 (progn
8716 (js2-consume-token)
8717 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8718 (setq continue nil)))
8719 pn))
8720
8721 (defconst js2-parse-mul-ops
8722 (list js2-MUL js2-DIV js2-MOD))
8723
8724 (defun js2-parse-mul-expr ()
8725 (let ((pn (js2-parse-unary-expr))
8726 tt
8727 (continue t))
8728 (while continue
8729 (setq tt (js2-peek-token))
8730 (if (memq tt js2-parse-mul-ops)
8731 (progn
8732 (js2-consume-token)
8733 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8734 (setq continue nil)))
8735 pn))
8736
8737 (defsubst js2-make-unary (type parser &rest args)
8738 "Make a unary node of type TYPE.
8739 PARSER is either a node (for postfix operators) or a function to call
8740 to parse the operand (for prefix operators)."
8741 (let* ((pos js2-token-beg)
8742 (postfix (js2-node-p parser))
8743 (expr (if postfix
8744 parser
8745 (apply parser args)))
8746 end
8747 pn)
8748 (if postfix ; e.g. i++
8749 (setq pos (js2-node-pos expr)
8750 end js2-token-end)
8751 (setq end (js2-node-end expr)))
8752 (setq pn (make-js2-unary-node :type type
8753 :pos pos
8754 :len (- end pos)
8755 :operand expr))
8756 (js2-node-add-children pn expr)
8757 pn))
8758
8759 (defconst js2-incrementable-node-types
8760 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8761 "Node types that can be the operand of a ++ or -- operator.")
8762
8763 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8764 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8765 js2-incrementable-node-types)
8766 (js2-report-error (if (= tt js2-INC)
8767 "msg.bad.incr"
8768 "msg.bad.decr")
8769 nil beg (- end beg))))
8770
8771 (defun js2-parse-unary-expr ()
8772 (let ((tt (js2-peek-token))
8773 pn expr beg end)
8774 (cond
8775 ((or (= tt js2-VOID)
8776 (= tt js2-NOT)
8777 (= tt js2-BITNOT)
8778 (= tt js2-TYPEOF))
8779 (js2-consume-token)
8780 (js2-make-unary tt 'js2-parse-unary-expr))
8781 ((= tt js2-ADD)
8782 (js2-consume-token)
8783 ;; Convert to special POS token in decompiler and parse tree
8784 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8785 ((= tt js2-SUB)
8786 (js2-consume-token)
8787 ;; Convert to special NEG token in decompiler and parse tree
8788 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8789 ((or (= tt js2-INC)
8790 (= tt js2-DEC))
8791 (js2-consume-token)
8792 (prog1
8793 (setq beg js2-token-beg
8794 end js2-token-end
8795 expr (js2-make-unary tt 'js2-parse-member-expr t))
8796 (js2-check-bad-inc-dec tt beg end expr)))
8797 ((= tt js2-DELPROP)
8798 (js2-consume-token)
8799 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8800 ((= tt js2-ERROR)
8801 (js2-consume-token)
8802 (make-js2-error-node)) ; try to continue
8803 ((and (= tt js2-LT)
8804 js2-compiler-xml-available)
8805 ;; XML stream encountered in expression.
8806 (js2-consume-token)
8807 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8808 (t
8809 (setq pn (js2-parse-member-expr t)
8810 ;; Don't look across a newline boundary for a postfix incop.
8811 tt (js2-peek-token-or-eol))
8812 (when (or (= tt js2-INC) (= tt js2-DEC))
8813 (js2-consume-token)
8814 (setf expr pn
8815 pn (js2-make-unary tt expr))
8816 (js2-node-set-prop pn 'postfix t)
8817 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8818 pn))))
8819
8820 (defun js2-parse-xml-initializer ()
8821 "Parse an E4X XML initializer.
8822 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8823 Then I'll postprocess the result, depending on whether we're in IDE
8824 mode or codegen mode, and generate the appropriate rewritten AST.
8825 IDE mode uses a rich AST that models the XML structure. Codegen mode
8826 just concatenates everything and makes a new XML or XMLList out of it."
8827 (let ((tt (js2-get-first-xml-token))
8828 pn-xml
8829 pn
8830 expr
8831 kids
8832 expr-pos
8833 (continue t)
8834 (first-token t))
8835 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8836 (js2-report-error "msg.syntax"))
8837 (setq pn-xml (make-js2-xml-node))
8838 (while continue
8839 (if first-token
8840 (setq first-token nil)
8841 (setq tt (js2-get-next-xml-token)))
8842 (cond
8843 ;; js2-XML means we found a {expr} in the XML stream.
8844 ;; The js2-ts-string is the XML up to the left-curly.
8845 ((= tt js2-XML)
8846 (push (make-js2-string-node :pos js2-token-beg
8847 :len (- js2-ts-cursor js2-token-beg))
8848 kids)
8849 (js2-must-match js2-LC "msg.syntax")
8850 (setq expr-pos js2-ts-cursor
8851 expr (if (eq (js2-peek-token) js2-RC)
8852 (make-js2-empty-expr-node :pos expr-pos)
8853 (js2-parse-expr)))
8854 (js2-must-match js2-RC "msg.syntax")
8855 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8856 :len (js2-node-len expr)
8857 :expr expr))
8858 (js2-node-add-children pn expr)
8859 (push pn kids))
8860 ;; a js2-XMLEND token means we hit the final close-tag.
8861 ((= tt js2-XMLEND)
8862 (push (make-js2-string-node :pos js2-token-beg
8863 :len (- js2-ts-cursor js2-token-beg))
8864 kids)
8865 (dolist (kid (nreverse kids))
8866 (js2-block-node-push pn-xml kid))
8867 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8868 (js2-node-pos pn-xml))
8869 continue nil))
8870 (t
8871 (js2-report-error "msg.syntax")
8872 (setq continue nil))))
8873 pn-xml))
8874
8875
8876 (defun js2-parse-argument-list ()
8877 "Parse an argument list and return it as a lisp list of nodes.
8878 Returns the list in reverse order. Consumes the right-paren token."
8879 (let (result)
8880 (unless (js2-match-token js2-RP)
8881 (loop do
8882 (if (= (js2-peek-token) js2-YIELD)
8883 (js2-report-error "msg.yield.parenthesized"))
8884 (push (js2-parse-assign-expr) result)
8885 while
8886 (js2-match-token js2-COMMA))
8887 (js2-must-match js2-RP "msg.no.paren.arg")
8888 result)))
8889
8890 (defun js2-parse-member-expr (&optional allow-call-syntax)
8891 (let ((tt (js2-peek-token))
8892 pn
8893 pos
8894 target
8895 args
8896 beg
8897 end
8898 init
8899 tail)
8900 (if (/= tt js2-NEW)
8901 (setq pn (js2-parse-primary-expr))
8902 ;; parse a 'new' expression
8903 (js2-consume-token)
8904 (setq pos js2-token-beg
8905 beg pos
8906 target (js2-parse-member-expr)
8907 end (js2-node-end target)
8908 pn (make-js2-new-node :pos pos
8909 :target target
8910 :len (- end pos)))
8911 (js2-node-add-children pn target)
8912 (when (js2-match-token js2-LP)
8913 ;; Add the arguments to pn, if any are supplied.
8914 (setf beg pos ; start of "new" keyword
8915 pos js2-token-beg
8916 args (nreverse (js2-parse-argument-list))
8917 (js2-new-node-args pn) args
8918 end js2-token-end
8919 (js2-new-node-lp pn) (- pos beg)
8920 (js2-new-node-rp pn) (- end 1 beg))
8921 (apply #'js2-node-add-children pn args))
8922 (when (and js2-allow-rhino-new-expr-initializer
8923 (js2-match-token js2-LC))
8924 (setf init (js2-parse-object-literal)
8925 end (js2-node-end init)
8926 (js2-new-node-initializer pn) init)
8927 (js2-node-add-children pn init))
8928 (setf (js2-node-len pn) (- end beg))) ; end outer if
8929 (js2-parse-member-expr-tail allow-call-syntax pn)))
8930
8931 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8932 "Parse a chain of property/array accesses or function calls.
8933 Includes parsing for E4X operators like `..' and `.@'.
8934 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8935 Returns an expression tree that includes PN, the parent node."
8936 (let ((beg (js2-node-pos pn))
8937 tt
8938 (continue t))
8939 (while continue
8940 (setq tt (js2-peek-token))
8941 (cond
8942 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8943 (setq pn (js2-parse-property-access tt pn)))
8944 ((= tt js2-DOTQUERY)
8945 (setq pn (js2-parse-dot-query pn)))
8946 ((= tt js2-LB)
8947 (setq pn (js2-parse-element-get pn)))
8948 ((= tt js2-LP)
8949 (if allow-call-syntax
8950 (setq pn (js2-parse-function-call pn))
8951 (setq continue nil)))
8952 (t
8953 (setq continue nil))))
8954 (if (>= js2-highlight-level 2)
8955 (js2-parse-highlight-member-expr-node pn))
8956 pn))
8957
8958 (defun js2-parse-dot-query (pn)
8959 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8960 Last token parsed must be `js2-DOTQUERY'."
8961 (let ((pos (js2-node-pos pn))
8962 op-pos
8963 expr
8964 end)
8965 (js2-consume-token)
8966 (js2-must-have-xml)
8967 (js2-set-requires-activation)
8968 (setq op-pos js2-token-beg
8969 expr (js2-parse-expr)
8970 end (js2-node-end expr)
8971 pn (make-js2-xml-dot-query-node :left pn
8972 :pos pos
8973 :op-pos op-pos
8974 :right expr))
8975 (js2-node-add-children pn
8976 (js2-xml-dot-query-node-left pn)
8977 (js2-xml-dot-query-node-right pn))
8978 (if (js2-must-match js2-RP "msg.no.paren")
8979 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8980 end js2-token-end))
8981 (setf (js2-node-len pn) (- end pos))
8982 pn))
8983
8984 (defun js2-parse-element-get (pn)
8985 "Parse an element-get expression, e.g. foo[bar].
8986 Last token parsed must be `js2-RB'."
8987 (let ((lb js2-token-beg)
8988 (pos (js2-node-pos pn))
8989 rb
8990 expr)
8991 (js2-consume-token)
8992 (setq expr (js2-parse-expr))
8993 (if (js2-must-match js2-RB "msg.no.bracket.index")
8994 (setq rb js2-token-beg))
8995 (setq pn (make-js2-elem-get-node :target pn
8996 :pos pos
8997 :element expr
8998 :lb (js2-relpos lb pos)
8999 :rb (js2-relpos rb pos)
9000 :len (- js2-token-end pos)))
9001 (js2-node-add-children pn
9002 (js2-elem-get-node-target pn)
9003 (js2-elem-get-node-element pn))
9004 pn))
9005
9006 (defun js2-parse-function-call (pn)
9007 (let (args
9008 (pos (js2-node-pos pn)))
9009 (js2-consume-token)
9010 (setq pn (make-js2-call-node :pos pos
9011 :target pn
9012 :lp (- js2-token-beg pos)))
9013 (js2-node-add-children pn (js2-call-node-target pn))
9014 ;; Add the arguments to pn, if any are supplied.
9015 (setf args (nreverse (js2-parse-argument-list))
9016 (js2-call-node-rp pn) (- js2-token-beg pos)
9017 (js2-call-node-args pn) args)
9018 (apply #'js2-node-add-children pn args)
9019 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9020 pn))
9021
9022 (defun js2-parse-property-access (tt pn)
9023 "Parse a property access, XML descendants access, or XML attr access."
9024 (let ((member-type-flags 0)
9025 (dot-pos js2-token-beg)
9026 (dot-len (if (= tt js2-DOTDOT) 2 1))
9027 name
9028 ref ; right side of . or .. operator
9029 result)
9030 (js2-consume-token)
9031 (when (= tt js2-DOTDOT)
9032 (js2-must-have-xml)
9033 (setq member-type-flags js2-descendants-flag))
9034 (if (not js2-compiler-xml-available)
9035 (progn
9036 (js2-must-match-prop-name "msg.no.name.after.dot")
9037 (setq name (js2-create-name-node t js2-GETPROP)
9038 result (make-js2-prop-get-node :left pn
9039 :pos js2-token-beg
9040 :right name
9041 :len (- js2-token-end
9042 js2-token-beg)))
9043 (js2-node-add-children result pn name)
9044 result)
9045 ;; otherwise look for XML operators
9046 (setf result (if (= tt js2-DOT)
9047 (make-js2-prop-get-node)
9048 (make-js2-infix-node :type js2-DOTDOT))
9049 (js2-node-pos result) (js2-node-pos pn)
9050 (js2-infix-node-op-pos result) dot-pos
9051 (js2-infix-node-left result) pn ; do this after setting position
9052 tt (js2-next-token))
9053 (cond
9054 ;; needed for generator.throw()
9055 ((= tt js2-THROW)
9056 (js2-save-name-token-data js2-token-beg "throw")
9057 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9058 ;; handles: name, ns::name, ns::*, ns::[expr]
9059 ((js2-valid-prop-name-token tt)
9060 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9061 ;; handles: *, *::name, *::*, *::[expr]
9062 ((= tt js2-MUL)
9063 (js2-save-name-token-data js2-token-beg "*")
9064 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9065 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9066 ((= tt js2-XMLATTR)
9067 (setq result (js2-parse-attribute-access)))
9068 (t
9069 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9070 (if ref
9071 (setf (js2-node-len result) (- (js2-node-end ref)
9072 (js2-node-pos result))
9073 (js2-infix-node-right result) ref))
9074 (if (js2-infix-node-p result)
9075 (js2-node-add-children result
9076 (js2-infix-node-left result)
9077 (js2-infix-node-right result)))
9078 result)))
9079
9080 (defun js2-parse-attribute-access ()
9081 "Parse an E4X XML attribute expression.
9082 This includes expressions of the forms:
9083
9084 @attr @ns::attr @ns::*
9085 @* @*::attr @*::*
9086 @[expr] @*::[expr] @ns::[expr]
9087
9088 Called if we peeked an '@' token."
9089 (let ((tt (js2-next-token))
9090 (at-pos js2-token-beg))
9091 (cond
9092 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9093 ((js2-valid-prop-name-token tt)
9094 (js2-parse-property-name at-pos js2-ts-string 0))
9095 ;; handles: @*, @*::name, @*::*, @*::[expr]
9096 ((= tt js2-MUL)
9097 (js2-save-name-token-data js2-token-beg "*")
9098 (js2-parse-property-name js2-token-beg "*" 0))
9099 ;; handles @[expr]
9100 ((= tt js2-LB)
9101 (js2-parse-xml-elem-ref at-pos))
9102 (t
9103 (js2-report-error "msg.no.name.after.xmlAttr")
9104 ;; Avoid cascaded errors that happen if we make an error node here.
9105 (js2-save-name-token-data js2-token-beg "")
9106 (js2-parse-property-name js2-token-beg "" 0)))))
9107
9108 (defun js2-parse-property-name (at-pos s member-type-flags)
9109 "Check if :: follows name in which case it becomes qualified name.
9110
9111 AT-POS is a natural number if we just read an '@' token, else nil.
9112 S is the name or string that was matched: an identifier, 'throw' or '*'.
9113 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9114
9115 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9116 operator, or the name is followed by ::. For a plain name, returns a
9117 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9118 (let ((pos (or at-pos js2-token-beg))
9119 colon-pos
9120 (name (js2-create-name-node t js2-current-token))
9121 ns
9122 tt
9123 ref
9124 pn)
9125 (catch 'return
9126 (when (js2-match-token js2-COLONCOLON)
9127 (setq ns name
9128 colon-pos js2-token-beg
9129 tt (js2-next-token))
9130 (cond
9131 ;; handles name::name
9132 ((js2-valid-prop-name-token tt)
9133 (setq name (js2-create-name-node)))
9134 ;; handles name::*
9135 ((= tt js2-MUL)
9136 (js2-save-name-token-data js2-token-beg "*")
9137 (setq name (js2-create-name-node)))
9138 ;; handles name::[expr]
9139 ((= tt js2-LB)
9140 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9141 (t
9142 (js2-report-error "msg.no.name.after.coloncolon"))))
9143 (if (and (null ns) (zerop member-type-flags))
9144 name
9145 (prog1
9146 (setq pn
9147 (make-js2-xml-prop-ref-node :pos pos
9148 :len (- (js2-node-end name) pos)
9149 :at-pos at-pos
9150 :colon-pos colon-pos
9151 :propname name))
9152 (js2-node-add-children pn name))))))
9153
9154 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9155 "Parse the [expr] portion of an xml element reference.
9156 For instance, @[expr], @*::[expr], or ns::[expr]."
9157 (let* ((lb js2-token-beg)
9158 (pos (or at-pos lb))
9159 rb
9160 (expr (js2-parse-expr))
9161 (end (js2-node-end expr))
9162 pn)
9163 (if (js2-must-match js2-RB "msg.no.bracket.index")
9164 (setq rb js2-token-beg
9165 end js2-token-end))
9166 (prog1
9167 (setq pn
9168 (make-js2-xml-elem-ref-node :pos pos
9169 :len (- end pos)
9170 :namespace namespace
9171 :colon-pos colon-pos
9172 :at-pos at-pos
9173 :expr expr
9174 :lb (js2-relpos lb pos)
9175 :rb (js2-relpos rb pos)))
9176 (js2-node-add-children pn namespace expr))))
9177
9178 (defsubst js2-parse-primary-expr-lhs ()
9179 (let ((js2-is-in-lhs t))
9180 (js2-parse-primary-expr)))
9181
9182 (defun js2-parse-primary-expr ()
9183 "Parses a literal (leaf) expression of some sort.
9184 Includes complex literals such as functions, object-literals,
9185 array-literals, array comprehensions and regular expressions."
9186 (let ((tt-flagged (js2-next-flagged-token))
9187 pn ; parent node (usually return value)
9188 tt
9189 px-pos ; paren-expr pos
9190 len
9191 flags ; regexp flags
9192 expr)
9193 (setq tt js2-current-token)
9194 (cond
9195 ((= tt js2-FUNCTION)
9196 (js2-parse-function 'FUNCTION_EXPRESSION))
9197 ((= tt js2-LB)
9198 (js2-parse-array-literal))
9199 ((= tt js2-LC)
9200 (js2-parse-object-literal))
9201 ((= tt js2-LET)
9202 (js2-parse-let js2-token-beg))
9203 ((= tt js2-LP)
9204 (setq px-pos js2-token-beg
9205 expr (js2-parse-expr))
9206 (js2-must-match js2-RP "msg.no.paren")
9207 (setq pn (make-js2-paren-node :pos px-pos
9208 :expr expr
9209 :len (- js2-token-end px-pos)))
9210 (js2-node-add-children pn (js2-paren-node-expr pn))
9211 pn)
9212 ((= tt js2-XMLATTR)
9213 (js2-must-have-xml)
9214 (js2-parse-attribute-access))
9215 ((= tt js2-NAME)
9216 (js2-parse-name tt-flagged tt))
9217 ((= tt js2-NUMBER)
9218 (make-js2-number-node))
9219 ((= tt js2-STRING)
9220 (prog1
9221 (make-js2-string-node)
9222 (js2-record-face 'font-lock-string-face)))
9223 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9224 ;; Got / or /= which in this context means a regexp literal
9225 (setq px-pos js2-token-beg)
9226 (js2-read-regexp tt)
9227 (setq flags js2-ts-regexp-flags
9228 js2-ts-regexp-flags nil)
9229 (prog1
9230 (make-js2-regexp-node :pos px-pos
9231 :len (- js2-ts-cursor px-pos)
9232 :value js2-ts-string
9233 :flags flags)
9234 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9235 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9236 ((or (= tt js2-NULL)
9237 (= tt js2-THIS)
9238 (= tt js2-FALSE)
9239 (= tt js2-TRUE))
9240 (make-js2-keyword-node :type tt))
9241 ((= tt js2-RESERVED)
9242 (js2-report-error "msg.reserved.id")
9243 (make-js2-name-node))
9244 ((= tt js2-ERROR)
9245 ;; the scanner or one of its subroutines reported the error.
9246 (make-js2-error-node))
9247 ((= tt js2-EOF)
9248 (setq px-pos (point-at-bol)
9249 len (- js2-ts-cursor px-pos))
9250 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9251 (make-js2-error-node :pos px-pos :len len))
9252 (t
9253 (js2-report-error "msg.syntax")
9254 (make-js2-error-node)))))
9255
9256 (defun js2-parse-name (tt-flagged tt)
9257 (let ((name js2-ts-string)
9258 (name-pos js2-token-beg))
9259 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9260 (= (js2-peek-token) js2-COLON))
9261 (prog1
9262 ;; Do not consume colon, it is used as unwind indicator
9263 ;; to return to statementHelper.
9264 (make-js2-label-node :pos name-pos
9265 :len (- js2-token-end name-pos)
9266 :name name)
9267 (js2-set-face name-pos
9268 js2-token-end
9269 'font-lock-variable-name-face 'record))
9270 ;; Otherwise not a label, just a name. Unfortunately peeking
9271 ;; the next token to check for a colon has biffed js2-token-beg
9272 ;; and js2-token-end. We store the name's bounds in buffer vars
9273 ;; and `js2-create-name-node' uses them.
9274 (js2-save-name-token-data name-pos name)
9275 (if js2-compiler-xml-available
9276 (js2-parse-property-name nil name 0)
9277 (js2-create-name-node 'check-activation)))))
9278
9279 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9280 (js2-add-strict-warning
9281 msg nil
9282 ;; back up from comma to beginning of line or array/objlit
9283 (max (if elems
9284 (js2-node-pos (car elems))
9285 pos)
9286 (save-excursion
9287 (goto-char comma-pos)
9288 (back-to-indentation)
9289 (point)))
9290 comma-pos))
9291
9292 (defun js2-parse-array-literal ()
9293 (let ((pos js2-token-beg)
9294 (end js2-token-end)
9295 (after-lb-or-comma t)
9296 after-comma
9297 tt
9298 elems
9299 pn
9300 (continue t))
9301 (while continue
9302 (setq tt (js2-peek-token))
9303 (cond
9304 ;; comma
9305 ((= tt js2-COMMA)
9306 (js2-consume-token)
9307 (setq after-comma js2-token-end)
9308 (if (not after-lb-or-comma)
9309 (setq after-lb-or-comma t)
9310 (push nil elems)))
9311 ;; end of array
9312 ((or (= tt js2-RB)
9313 (= tt js2-EOF)) ; prevent infinite loop
9314 (if (= tt js2-EOF)
9315 (js2-report-error "msg.no.bracket.arg" nil pos)
9316 (js2-consume-token))
9317 (setq continue nil
9318 end js2-token-end
9319 pn (make-js2-array-node :pos pos
9320 :len (- js2-ts-cursor pos)
9321 :elems (nreverse elems)))
9322 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9323 (when after-comma
9324 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9325 pos elems after-comma)))
9326 ;; destructuring binding
9327 (js2-is-in-lhs
9328 (push (if (or (= tt js2-LC)
9329 (= tt js2-LB)
9330 (= tt js2-NAME))
9331 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9332 (js2-parse-primary-expr-lhs)
9333 ;; invalid pattern
9334 (js2-consume-token)
9335 (js2-report-error "msg.bad.var")
9336 (make-js2-error-node))
9337 elems)
9338 (setq after-lb-or-comma nil
9339 after-comma nil))
9340 ;; array comp
9341 ((and (>= js2-language-version 170)
9342 (= tt js2-FOR) ; check for array comprehension
9343 (not after-lb-or-comma) ; "for" can't follow a comma
9344 elems ; must have at least 1 element
9345 (not (cdr elems))) ; but no 2nd element
9346 (setf continue nil
9347 pn (js2-parse-array-comprehension (car elems) pos)))
9348
9349 ;; another element
9350 (t
9351 (unless after-lb-or-comma
9352 (js2-report-error "msg.no.bracket.arg"))
9353 (push (js2-parse-assign-expr) elems)
9354 (setq after-lb-or-comma nil
9355 after-comma nil))))
9356 pn))
9357
9358 (defun js2-parse-array-comprehension (expr pos)
9359 "Parse a JavaScript 1.7 Array Comprehension.
9360 EXPR is the first expression after the opening left-bracket.
9361 POS is the beginning of the LB token preceding EXPR.
9362 We should have just parsed the 'for' keyword before calling this function."
9363 (let (loops
9364 filter
9365 if-pos
9366 result)
9367 (while (= (js2-peek-token) js2-FOR)
9368 (push (js2-parse-array-comp-loop) loops))
9369 (when (= (js2-peek-token) js2-IF)
9370 (js2-consume-token)
9371 (setq if-pos (- js2-token-beg pos) ; relative
9372 filter (js2-parse-condition)))
9373 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9374 (setq result (make-js2-array-comp-node :pos pos
9375 :len (- js2-ts-cursor pos)
9376 :result expr
9377 :loops (nreverse loops)
9378 :filter (car filter)
9379 :lp (js2-relpos (second filter) pos)
9380 :rp (js2-relpos (third filter) pos)
9381 :if-pos if-pos))
9382 (apply #'js2-node-add-children result expr (car filter)
9383 (js2-array-comp-node-loops result))
9384 result))
9385
9386 (defun js2-parse-array-comp-loop ()
9387 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9388 Last token peeked should be the initial FOR."
9389 (let ((pos js2-token-beg)
9390 (pn (make-js2-array-comp-loop-node))
9391 tt
9392 iter
9393 obj
9394 foreach-p
9395 in-pos
9396 each-pos
9397 lp
9398 rp)
9399 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9400 (js2-push-scope pn)
9401 (unwind-protect
9402 (progn
9403 (when (js2-match-token js2-NAME)
9404 (if (string= js2-ts-string "each")
9405 (progn
9406 (setq foreach-p t
9407 each-pos (- js2-token-beg pos)) ; relative
9408 (js2-record-face 'font-lock-keyword-face))
9409 (js2-report-error "msg.no.paren.for")))
9410 (if (js2-must-match js2-LP "msg.no.paren.for")
9411 (setq lp (- js2-token-beg pos)))
9412 (setq tt (js2-peek-token))
9413 (cond
9414 ((or (= tt js2-LB)
9415 (= tt js2-LC))
9416 ;; handle destructuring assignment
9417 (setq iter (js2-parse-primary-expr-lhs)))
9418 ((js2-valid-prop-name-token tt)
9419 (js2-consume-token)
9420 (setq iter (js2-create-name-node)))
9421 (t
9422 (js2-report-error "msg.bad.var")))
9423 ;; Define as a let since we want the scope of the variable to
9424 ;; be restricted to the array comprehension
9425 (if (js2-name-node-p iter)
9426 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9427 (if (js2-must-match js2-IN "msg.in.after.for.name")
9428 (setq in-pos (- js2-token-beg pos)))
9429 (setq obj (js2-parse-expr))
9430 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9431 (setq rp (- js2-token-beg pos)))
9432 (setf (js2-node-pos pn) pos
9433 (js2-node-len pn) (- js2-ts-cursor pos)
9434 (js2-array-comp-loop-node-iterator pn) iter
9435 (js2-array-comp-loop-node-object pn) obj
9436 (js2-array-comp-loop-node-in-pos pn) in-pos
9437 (js2-array-comp-loop-node-each-pos pn) each-pos
9438 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9439 (js2-array-comp-loop-node-lp pn) lp
9440 (js2-array-comp-loop-node-rp pn) rp)
9441 (js2-node-add-children pn iter obj))
9442 (js2-pop-scope))
9443 pn))
9444
9445 (defun js2-parse-object-literal ()
9446 (let ((pos js2-token-beg)
9447 tt
9448 elems
9449 result
9450 after-comma
9451 (continue t))
9452 (while continue
9453 (setq tt (js2-peek-token))
9454 (cond
9455 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9456 ((or (js2-valid-prop-name-token tt)
9457 (= tt js2-STRING))
9458 (setq after-comma nil
9459 result (js2-parse-named-prop tt))
9460 (if (and (null result)
9461 (not js2-recover-from-parse-errors))
9462 (setq continue nil)
9463 (push result elems)))
9464 ;; {12: x} or {10.7: x}
9465 ((= tt js2-NUMBER)
9466 (js2-consume-token)
9467 (setq after-comma nil)
9468 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9469 ;; trailing comma
9470 ((= tt js2-RC)
9471 (setq continue nil)
9472 (if after-comma
9473 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9474 pos elems after-comma)))
9475 (t
9476 (js2-report-error "msg.bad.prop")
9477 (unless js2-recover-from-parse-errors
9478 (setq continue nil)))) ; end switch
9479 (if (js2-match-token js2-COMMA)
9480 (setq after-comma js2-token-end)
9481 (setq continue nil))) ; end loop
9482 (js2-must-match js2-RC "msg.no.brace.prop")
9483 (setq result (make-js2-object-node :pos pos
9484 :len (- js2-ts-cursor pos)
9485 :elems (nreverse elems)))
9486 (apply #'js2-node-add-children result (js2-object-node-elems result))
9487 result))
9488
9489 (defun js2-parse-named-prop (tt)
9490 "Parse a name, string, or getter/setter object property.
9491 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9492 (js2-consume-token)
9493 (let ((string-prop (and (= tt js2-STRING)
9494 (make-js2-string-node)))
9495 expr
9496 (ppos js2-token-beg)
9497 (pend js2-token-end)
9498 (name (js2-create-name-node))
9499 (prop js2-ts-string))
9500 (cond
9501 ;; getter/setter prop
9502 ((and (= tt js2-NAME)
9503 (= (js2-peek-token) js2-NAME)
9504 (or (string= prop "get")
9505 (string= prop "set")))
9506 (progn
9507 (js2-consume-token)
9508 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9509 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9510 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9511 (js2-parse-getter-setter-prop ppos name (string= prop "get"))))
9512 ;; abbreviated destructuring bind e.g., {a, b} = c;
9513 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9514 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9515 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9516 ;; assignment but it's difficult because it requires looking ahead of expression.
9517 ((and js2-is-in-lhs
9518 (= tt js2-NAME)
9519 (let ((ctk (js2-peek-token)))
9520 (or (= ctk js2-COMMA)
9521 (= ctk js2-RC)
9522 (js2-valid-prop-name-token ctk))))
9523 (js2-set-face ppos pend 'font-lock-variable-name-face 'record)
9524 name)
9525 ;; regular prop
9526 (t
9527 (prog1
9528 (setq expr (js2-parse-plain-property (or string-prop name)))
9529 (js2-set-face ppos pend
9530 (if (js2-function-node-p
9531 (js2-object-prop-node-right expr))
9532 'font-lock-function-name-face
9533 'font-lock-variable-name-face)
9534 'record))))))
9535
9536 (defun js2-parse-plain-property (prop)
9537 "Parse a non-getter/setter property in an object literal.
9538 PROP is the node representing the property: a number, name or string."
9539 (js2-must-match js2-COLON "msg.no.colon.prop")
9540 (let* ((pos (js2-node-pos prop))
9541 (colon (- js2-token-beg pos))
9542 (expr (js2-parse-assign-expr))
9543 (result (make-js2-object-prop-node
9544 :pos pos
9545 ;; don't include last consumed token in length
9546 :len (- (+ (js2-node-pos expr)
9547 (js2-node-len expr))
9548 pos)
9549 :left prop
9550 :right expr
9551 :op-pos colon)))
9552 (js2-node-add-children result prop expr)
9553 result))
9554
9555 (defun js2-parse-getter-setter-prop (pos prop get-p)
9556 "Parse getter or setter property in an object literal.
9557 JavaScript syntax is:
9558
9559 { get foo() {...}, set foo(x) {...} }
9560
9561 and expression closure style is also supported
9562
9563 { get foo() x, set foo(x) _x = x }
9564
9565 POS is the start position of the `get' or `set' keyword.
9566 PROP is the `js2-name-node' representing the property name.
9567 GET-P is non-nil if the keyword was `get'."
9568 (let ((type (if get-p js2-GET js2-SET))
9569 result
9570 end
9571 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9572 ;; it has to be an anonymous function, as we already parsed the name
9573 (if (/= (js2-node-type fn) js2-FUNCTION)
9574 (js2-report-error "msg.bad.prop")
9575 (if (plusp (length (js2-function-name fn)))
9576 (js2-report-error "msg.bad.prop")))
9577 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9578 (setq end (js2-node-end fn)
9579 result (make-js2-getter-setter-node :type type
9580 :pos pos
9581 :len (- end pos)
9582 :left prop
9583 :right fn))
9584 (js2-node-add-children result prop fn)
9585 result))
9586
9587 (defun js2-create-name-node (&optional check-activation-p token)
9588 "Create a name node using the token info from last scanned name.
9589 In some cases we need to either synthesize a name node, or we lost
9590 the name token information by peeking. If the TOKEN parameter is
9591 not `js2-NAME', then we use the token info saved in instance vars."
9592 (let ((beg js2-token-beg)
9593 (s js2-ts-string)
9594 name)
9595 (when (/= js2-current-token js2-NAME)
9596 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9597 s js2-prev-name-token-string
9598 js2-prev-name-token-start nil
9599 js2-prev-name-token-string nil))
9600 (setq name (make-js2-name-node :pos beg
9601 :name s
9602 :len (length s)))
9603 (if check-activation-p
9604 (js2-check-activation-name s (or token js2-NAME)))
9605 name))
9606
9607 ;;; Indentation support
9608
9609 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9610 ;; Karl cleverly deduces that the desired indentation level is often a
9611 ;; function of paren/bracket/brace nesting depth, which can be determined
9612 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9613 ;; then does some equally clever checks to see if we're in the context of a
9614 ;; substatement of a possibly braceless statement keyword such as if, while,
9615 ;; or finally. This approach yields pretty good results.
9616
9617 ;; The indenter is often "wrong", however, and needs to be overridden.
9618 ;; The right long-term solution is probably to emulate (or integrate
9619 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9620 ;; parse tree from `js2-parse' is present, which is not true at the
9621 ;; moment the user is typing, computing indentation is still thousands
9622 ;; of lines of code to handle every possible syntactic edge case.
9623
9624 ;; In the meantime, the compromise solution is that we offer a "bounce
9625 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9626 ;; current line indent among various likely guess points. This approach
9627 ;; is far from perfect, but should at least make it slightly easier to
9628 ;; move the line towards its desired indentation when manually
9629 ;; overriding Karl's heuristic nesting guesser.
9630
9631 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9632 ;; extensions such as `let' and Array comprehensions. Major kudos to
9633 ;; Karl for coming up with the initial approach, which packs a lot of
9634 ;; punch for so little code.
9635
9636 (defconst js-possibly-braceless-keyword-re
9637 (regexp-opt
9638 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9639 'words)
9640 "Regular expression matching keywords that are optionally
9641 followed by an opening brace.")
9642
9643 (defconst js-possibly-braceless-keywords-re
9644 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9645 "Regular expression which matches the keywords which are consist of more than 2 words
9646 like 'if else' and 'for each', and optionally followed by an opening brace.")
9647
9648 (defconst js-indent-operator-re
9649 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9650 (regexp-opt '("in" "instanceof") 'words))
9651 "Regular expression matching operators that affect indentation
9652 of continued expressions.")
9653
9654 ;; This function has horrible results if you're typing an array
9655 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9656 ;; in conjunction with electric-indent, so just disabling it.
9657 (defsubst js2-code-at-bol-p ()
9658 "Return t if the first character on line is non-whitespace."
9659 nil)
9660
9661 (defun js2-insert-and-indent (key)
9662 "Run command bound to key and indent current line. Runs the command
9663 bound to KEY in the global keymap and indents the current line."
9664 (interactive (list (this-command-keys)))
9665 (let ((cmd (lookup-key (current-global-map) key)))
9666 (if (commandp cmd)
9667 (call-interactively cmd)))
9668 ;; don't do the electric keys inside comments or strings,
9669 ;; and don't do bounce-indent with them.
9670 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9671 (js2-bounce-indent-p (js2-code-at-bol-p)))
9672 (unless (or (nth 3 parse-state)
9673 (nth 4 parse-state))
9674 (indent-according-to-mode))))
9675
9676 (defun js-re-search-forward-inner (regexp &optional bound count)
9677 "Auxiliary function for `js-re-search-forward'."
9678 (let ((parse)
9679 (saved-point (point-min)))
9680 (while (> count 0)
9681 (re-search-forward regexp bound)
9682 (setq parse (parse-partial-sexp saved-point (point)))
9683 (cond ((nth 3 parse)
9684 (re-search-forward
9685 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9686 (save-excursion (end-of-line) (point)) t))
9687 ((nth 7 parse)
9688 (forward-line))
9689 ((or (nth 4 parse)
9690 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9691 (re-search-forward "\\*/"))
9692 (t
9693 (setq count (1- count))))
9694 (setq saved-point (point))))
9695 (point))
9696
9697 (defun js-re-search-forward (regexp &optional bound noerror count)
9698 "Search forward but ignore strings and comments. Invokes
9699 `re-search-forward' but treats the buffer as if strings and
9700 comments have been removed."
9701 (let ((saved-point (point))
9702 (search-expr
9703 (cond ((null count)
9704 '(js-re-search-forward-inner regexp bound 1))
9705 ((< count 0)
9706 '(js-re-search-backward-inner regexp bound (- count)))
9707 ((> count 0)
9708 '(js-re-search-forward-inner regexp bound count)))))
9709 (condition-case err
9710 (eval search-expr)
9711 (search-failed
9712 (goto-char saved-point)
9713 (unless noerror
9714 (error (error-message-string err)))))))
9715
9716 (defun js-re-search-backward-inner (regexp &optional bound count)
9717 "Auxiliary function for `js-re-search-backward'."
9718 (let ((parse)
9719 (saved-point (point-min)))
9720 (while (> count 0)
9721 (re-search-backward regexp bound)
9722 (setq parse (parse-partial-sexp saved-point (point)))
9723 (cond ((nth 3 parse)
9724 (re-search-backward
9725 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9726 (save-excursion (beginning-of-line) (point)) t))
9727 ((nth 7 parse)
9728 (goto-char (nth 8 parse)))
9729 ((or (nth 4 parse)
9730 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9731 (re-search-backward "/\\*"))
9732 (t
9733 (setq count (1- count))))))
9734 (point))
9735
9736 (defun js-re-search-backward (regexp &optional bound noerror count)
9737 "Search backward but ignore strings and comments. Invokes
9738 `re-search-backward' but treats the buffer as if strings and
9739 comments have been removed."
9740 (let ((saved-point (point))
9741 (search-expr
9742 (cond ((null count)
9743 '(js-re-search-backward-inner regexp bound 1))
9744 ((< count 0)
9745 '(js-re-search-forward-inner regexp bound (- count)))
9746 ((> count 0)
9747 '(js-re-search-backward-inner regexp bound count)))))
9748 (condition-case err
9749 (eval search-expr)
9750 (search-failed
9751 (goto-char saved-point)
9752 (unless noerror
9753 (error (error-message-string err)))))))
9754
9755 (defun js-looking-at-operator-p ()
9756 "Return non-nil if text after point is an operator (that is not
9757 a comma)."
9758 (save-match-data
9759 (and (looking-at js-indent-operator-re)
9760 (or (not (looking-at ":"))
9761 (save-excursion
9762 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9763 (looking-at "?")))))))
9764
9765 (defun js-continued-expression-p ()
9766 "Returns non-nil if the current line continues an expression."
9767 (save-excursion
9768 (back-to-indentation)
9769 (or (js-looking-at-operator-p)
9770 ;; var a = 10,
9771 ;; b = 20; <- this
9772 (let* ((node (js2-node-at-point))
9773 (pnode (js2-node-parent node)))
9774 (and node
9775 (= js2-NAME (js2-node-type node))
9776 (or
9777 (= js2-VAR (js2-node-type pnode))
9778 (= js2-LET (js2-node-type pnode)))))
9779 ;; comment
9780 (and (js-re-search-backward "\n" nil t)
9781 (progn
9782 (skip-chars-backward " \t")
9783 (backward-char)
9784 (and (js-looking-at-operator-p)
9785 (and (progn (backward-char)
9786 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9787
9788 (defun js-end-of-do-while-loop-p ()
9789 "Returns non-nil if word after point is `while' of a do-while
9790 statement, else returns nil. A braceless do-while statement
9791 spanning several lines requires that the start of the loop is
9792 indented to the same column as the current line."
9793 (interactive)
9794 (save-excursion
9795 (save-match-data
9796 (when (looking-at "\\s-*\\<while\\>")
9797 (if (save-excursion
9798 (skip-chars-backward "[ \t\n]*}")
9799 (looking-at "[ \t\n]*}"))
9800 (save-excursion
9801 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9802 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9803 (or (looking-at "\\<do\\>")
9804 (let ((saved-indent (current-indentation)))
9805 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9806 (/= (current-indentation) saved-indent)))
9807 (and (looking-at "[ \t]*\\<do\\>")
9808 (not (js-re-search-forward
9809 "\\<while\\>" (point-at-eol) t))
9810 (= (current-indentation) saved-indent)))))))))
9811
9812 (defun js-ctrl-statement-indentation ()
9813 "Returns the proper indentation of the current line if it
9814 starts the body of a control statement without braces, else
9815 returns nil."
9816 (let (forward-sexp-function) ; temporarily unbind it
9817 (save-excursion
9818 (back-to-indentation)
9819 (when (save-excursion
9820 (and (not (js2-same-line (point-min)))
9821 (not (looking-at "{"))
9822 (js-re-search-backward "[[:graph:]]" nil t)
9823 (not (looking-at "[{([]"))
9824 (progn
9825 (forward-char)
9826 ;; scan-sexps sometimes throws an error
9827 (ignore-errors (backward-sexp))
9828 (when (looking-at "(") (backward-word 1))
9829 (and (save-excursion
9830 (skip-chars-backward " \t}" (point-at-bol))
9831 (or (bolp)
9832 (and (backward-word 1)
9833 (skip-chars-backward " \t}" (point-at-bol))
9834 (bolp)
9835 (looking-at js-possibly-braceless-keywords-re))))
9836 (looking-at js-possibly-braceless-keyword-re)
9837 (not (js-end-of-do-while-loop-p))))))
9838 (save-excursion
9839 (goto-char (match-beginning 0))
9840 (+ (current-indentation) js2-basic-offset))))))
9841
9842 (defun js2-indent-in-array-comp (parse-status)
9843 "Return non-nil if we think we're in an array comprehension.
9844 In particular, return the buffer position of the first `for' kwd."
9845 (let ((end (point)))
9846 (when (nth 1 parse-status)
9847 (save-excursion
9848 (goto-char (nth 1 parse-status))
9849 (when (looking-at "\\[")
9850 (forward-char 1)
9851 (js2-forward-sws)
9852 (if (looking-at "[[{]")
9853 (let (forward-sexp-function) ; use lisp version
9854 (forward-sexp) ; skip destructuring form
9855 (js2-forward-sws)
9856 (if (and (/= (char-after) ?,) ; regular array
9857 (looking-at "for"))
9858 (match-beginning 0)))
9859 ;; to skip arbitrary expressions we need the parser,
9860 ;; so we'll just guess at it.
9861 (if (re-search-forward "[^,]* \\(for\\) " end t)
9862 (match-beginning 1))))))))
9863
9864 (defun js2-array-comp-indentation (parse-status for-kwd)
9865 (if (js2-same-line for-kwd)
9866 ;; first continuation line
9867 (save-excursion
9868 (goto-char (nth 1 parse-status))
9869 (forward-char 1)
9870 (skip-chars-forward " \t")
9871 (current-column))
9872 (save-excursion
9873 (goto-char for-kwd)
9874 (current-column))))
9875
9876 (defun js-proper-indentation (parse-status)
9877 "Return the proper indentation for the current line."
9878 (save-excursion
9879 (back-to-indentation)
9880 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9881 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9882 (continued-expr-p (js-continued-expression-p))
9883 (bracket (nth 1 parse-status))
9884 beg)
9885 (cond
9886 ;; indent array comprehension continuation lines specially
9887 ((and bracket
9888 (not (js2-same-line bracket))
9889 (setq beg (js2-indent-in-array-comp parse-status))
9890 (>= (point) (save-excursion
9891 (goto-char beg)
9892 (point-at-bol)))) ; at or after first loop?
9893 (js2-array-comp-indentation parse-status beg))
9894
9895 (ctrl-stmt-indent)
9896
9897 (bracket
9898 (goto-char bracket)
9899 (cond
9900 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9901 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9902 (when (save-excursion (skip-chars-backward " \t)")
9903 (looking-at ")"))
9904 (backward-list))
9905 (if (and (nth 1 p)
9906 (not js2-consistent-level-indent-inner-bracket-p))
9907 (progn (goto-char (1+ (nth 1 p)))
9908 (skip-chars-forward " \t"))
9909 (back-to-indentation))
9910 (cond (same-indent-p
9911 (current-column))
9912 (continued-expr-p
9913 (+ (current-column) (* 2 js2-basic-offset)))
9914 (t
9915 (+ (current-column) js2-basic-offset)))))
9916 (t
9917 (unless same-indent-p
9918 (forward-char)
9919 (skip-chars-forward " \t"))
9920 (current-column))))
9921
9922 (continued-expr-p js2-basic-offset)
9923 (t 0)))))
9924
9925 (defun js2-lineup-comment (parse-status)
9926 "Indent a multi-line block comment continuation line."
9927 (let* ((beg (nth 8 parse-status))
9928 (first-line (js2-same-line beg))
9929 (offset (save-excursion
9930 (goto-char beg)
9931 (if (looking-at "/\\*")
9932 (+ 1 (current-column))
9933 0))))
9934 (unless first-line
9935 (indent-line-to offset))))
9936
9937 (defun js2-backward-sws ()
9938 "Move backward through whitespace and comments."
9939 (interactive)
9940 (while (forward-comment -1)))
9941
9942 (defun js2-forward-sws ()
9943 "Move forward through whitespace and comments."
9944 (interactive)
9945 (while (forward-comment 1)))
9946
9947 (defsubst js2-current-indent (&optional pos)
9948 "Return column of indentation on current line.
9949 If POS is non-nil, go to that point and return indentation for that line."
9950 (save-excursion
9951 (if pos
9952 (goto-char pos))
9953 (back-to-indentation)
9954 (current-column)))
9955
9956 (defsubst js2-arglist-close ()
9957 "Return non-nil if we're on a line beginning with a close-paren/brace."
9958 (save-match-data
9959 (save-excursion
9960 (goto-char (point-at-bol))
9961 (js2-forward-sws)
9962 (looking-at "[])}]"))))
9963
9964 (defsubst js2-indent-looks-like-label-p ()
9965 (goto-char (point-at-bol))
9966 (js2-forward-sws)
9967 (looking-at (concat js2-mode-identifier-re ":")))
9968
9969 (defun js2-indent-in-objlit-p (parse-status)
9970 "Return non-nil if this looks like an object-literal entry."
9971 (let ((start (nth 1 parse-status)))
9972 (and
9973 start
9974 (save-excursion
9975 (and (zerop (forward-line -1))
9976 (not (< (point) start)) ; crossed a {} boundary
9977 (js2-indent-looks-like-label-p)))
9978 (save-excursion
9979 (js2-indent-looks-like-label-p)))))
9980
9981 ;; if prev line looks like foobar({ then we're passing an object
9982 ;; literal to a function call, and people pretty much always want to
9983 ;; de-dent back to the previous line, so move the 'basic-offset'
9984 ;; position to the front.
9985 (defsubst js2-indent-objlit-arg-p (parse-status)
9986 (save-excursion
9987 (back-to-indentation)
9988 (js2-backward-sws)
9989 (and (eq (1- (point)) (nth 1 parse-status))
9990 (eq (char-before) ?{)
9991 (progn
9992 (forward-char -1)
9993 (skip-chars-backward " \t")
9994 (eq (char-before) ?\()))))
9995
9996 (defsubst js2-indent-case-block-p ()
9997 (save-excursion
9998 (back-to-indentation)
9999 (js2-backward-sws)
10000 (goto-char (point-at-bol))
10001 (skip-chars-forward " \t")
10002 (save-match-data
10003 (looking-at "case\\s-.+:"))))
10004
10005 (defsubst js2-syntax-bol ()
10006 "Return the point at the first non-whitespace char on the line.
10007 Returns `point-at-bol' if the line is empty."
10008 (save-excursion
10009 (beginning-of-line)
10010 (skip-chars-forward " \t")
10011 (point)))
10012
10013 (defun js2-bounce-indent (normal-col parse-status)
10014 "Cycle among alternate computed indentation positions.
10015 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10016 of the buffer to the current point. NORMAL-COL is the indentation
10017 column computed by the heuristic guesser based on current paren,
10018 bracket, brace and statement nesting."
10019 (let ((cur-indent (js2-current-indent))
10020 (old-buffer-undo-list buffer-undo-list)
10021 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10022 (current-line (save-excursion
10023 (forward-line 0) ; move to bol
10024 (1+ (count-lines (point-min) (point)))))
10025 positions
10026 pos
10027 anchor
10028 arglist-cont
10029 same-indent
10030 prev-line-col
10031 basic-offset
10032 computed-pos)
10033 ;; temporarily don't record undo info, if user requested this
10034 (if js2-mode-indent-inhibit-undo
10035 (setq buffer-undo-list t))
10036 (unwind-protect
10037 (progn
10038 ;; first likely point: indent from beginning of previous code line
10039 (push (setq basic-offset
10040 (+ (save-excursion
10041 (back-to-indentation)
10042 (js2-backward-sws)
10043 (back-to-indentation)
10044 (setq prev-line-col (current-column)))
10045 js2-basic-offset))
10046 positions)
10047
10048 ;; (first + epsilon) likely point: indent 2x from beginning of
10049 ;; previous code line. Some companies like this approach. Ahem.
10050 ;; Seriously, though -- 4-space indent for expression continuation
10051 ;; lines isn't a bad idea. We should eventually implement it
10052 ;; that way.
10053 (push (setq basic-offset
10054 (+ (save-excursion
10055 (back-to-indentation)
10056 (js2-backward-sws)
10057 (back-to-indentation)
10058 (setq prev-line-col (current-column)))
10059 (* 2 js2-basic-offset)))
10060 positions)
10061
10062 ;; second likely point: indent from assign-expr RHS. This
10063 ;; is just a crude guess based on finding " = " on the previous
10064 ;; line containing actual code.
10065 (setq pos (save-excursion
10066 (save-match-data
10067 (forward-line -1)
10068 (goto-char (point-at-bol))
10069 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10070 (point-at-eol) t)
10071 (goto-char (match-end 1))
10072 (skip-chars-forward " \t\r\n")
10073 (current-column)))))
10074 (when pos
10075 (incf pos js2-basic-offset)
10076 (unless (member pos positions)
10077 (push pos positions)))
10078
10079 ;; third likely point: same indent as previous line of code.
10080 ;; Make it the first likely point if we're not on an
10081 ;; arglist-close line and previous line ends in a comma, or
10082 ;; both this line and prev line look like object-literal
10083 ;; elements.
10084 (setq pos (save-excursion
10085 (goto-char (point-at-bol))
10086 (js2-backward-sws)
10087 (back-to-indentation)
10088 (prog1
10089 (current-column)
10090 ;; while we're here, look for trailing comma
10091 (if (save-excursion
10092 (goto-char (point-at-eol))
10093 (js2-backward-sws)
10094 (eq (char-before) ?,))
10095 (setq arglist-cont (1- (point)))))))
10096 (when pos
10097 (if (and (or arglist-cont
10098 (js2-indent-in-objlit-p parse-status))
10099 (not (js2-arglist-close)))
10100 (setq same-indent pos))
10101 (unless (member pos positions)
10102 (push pos positions)))
10103
10104 ;; fourth likely point: first preceding code with less indentation
10105 ;; than the immediately preceding code line.
10106 (setq pos (save-excursion
10107 (js2-backward-sws)
10108 (back-to-indentation)
10109 (setq anchor (current-column))
10110 (while (and (zerop (forward-line -1))
10111 (>= (progn
10112 (back-to-indentation)
10113 (current-column))
10114 anchor)))
10115 (setq pos (current-column))))
10116 (unless (member pos positions)
10117 (push pos positions))
10118
10119 ;; put nesting-heuristic position first in list, sort rest
10120 (setq positions (nreverse (sort positions '<)))
10121 (setq positions (cons normal-col (delete normal-col positions)))
10122
10123 ;; comma-list continuation lines: prev line indent takes precedence
10124 (if same-indent
10125 (setq positions
10126 (cons same-indent
10127 (sort (delete same-indent positions) '<))))
10128
10129 ;; common special cases where we want to indent in from previous line
10130 (if (or (js2-indent-case-block-p)
10131 (js2-indent-objlit-arg-p parse-status))
10132 (setq positions
10133 (cons basic-offset
10134 (delete basic-offset positions))))
10135
10136 ;; record whether we're already sitting on one of the alternatives
10137 (setq pos (member cur-indent positions))
10138 (cond
10139 ;; case 0: we're one one of the alternatives and this is the
10140 ;; first time they've pressed TAB on this line (best-guess).
10141 ((and js2-mode-indent-ignore-first-tab
10142 pos
10143 ;; first time pressing TAB on this line?
10144 (not (eq js2-mode-last-indented-line current-line)))
10145 ;; do nothing
10146 (setq computed-pos nil))
10147 ;; case 1: only one computed position => use it
10148 ((null (cdr positions))
10149 (setq computed-pos 0))
10150 ;; case 2: not on any of the computed spots => use main spot
10151 ((not pos)
10152 (setq computed-pos 0))
10153 ;; case 3: on last position: cycle to first position
10154 ((null (cdr pos))
10155 (setq computed-pos 0))
10156 ;; case 4: on intermediate position: cycle to next position
10157 (t
10158 (setq computed-pos (js2-position (second pos) positions))))
10159
10160 ;; see if any hooks want to indent; otherwise we do it
10161 (loop with result = nil
10162 for hook in js2-indent-hook
10163 while (null result)
10164 do
10165 (setq result (funcall hook positions computed-pos))
10166 finally do
10167 (unless (or result (null computed-pos))
10168 (indent-line-to (nth computed-pos positions)))))
10169
10170 ;; finally
10171 (if js2-mode-indent-inhibit-undo
10172 (setq buffer-undo-list old-buffer-undo-list))
10173 ;; see commentary for `js2-mode-last-indented-line'
10174 (setq js2-mode-last-indented-line current-line))))
10175
10176 (defsubst js2-1-line-comment-continuation-p ()
10177 "Return t if we're in a 1-line comment continuation.
10178 If so, we don't ever want to use bounce-indent."
10179 (save-excursion
10180 (save-match-data
10181 (and (progn
10182 (forward-line 0)
10183 (looking-at "\\s-*//"))
10184 (progn
10185 (forward-line -1)
10186 (forward-line 0)
10187 (when (looking-at "\\s-*$")
10188 (js2-backward-sws)
10189 (forward-line 0))
10190 (looking-at "\\s-*//"))))))
10191
10192 (defun js2-indent-line ()
10193 "Indent the current line as JavaScript source text."
10194 (interactive)
10195 (let (parse-status
10196 current-indent
10197 offset
10198 indent-col
10199 moved
10200 ;; don't whine about errors/warnings when we're indenting.
10201 ;; This has to be set before calling parse-partial-sexp below.
10202 (inhibit-point-motion-hooks t))
10203 (setq parse-status (save-excursion
10204 (parse-partial-sexp (point-min)
10205 (point-at-bol)))
10206 offset (- (point) (save-excursion
10207 (back-to-indentation)
10208 (setq current-indent (current-column))
10209 (point))))
10210 (js2-with-underscore-as-word-syntax
10211 (if (nth 4 parse-status)
10212 (js2-lineup-comment parse-status)
10213 (setq indent-col (js-proper-indentation parse-status))
10214 ;; see comments below about js2-mode-last-indented-line
10215 (when
10216 (cond
10217 ;; bounce-indenting is disabled during electric-key indent.
10218 ;; It doesn't work well on first line of buffer.
10219 ((and js2-bounce-indent-p
10220 (not (js2-same-line (point-min)))
10221 (not (js2-1-line-comment-continuation-p)))
10222 (js2-bounce-indent indent-col parse-status)
10223 (setq moved t))
10224 ;; just indent to the guesser's likely spot
10225 ((/= current-indent indent-col)
10226 (indent-line-to indent-col)
10227 (setq moved t)))
10228 (when (and moved (plusp offset))
10229 (forward-char offset)))))))
10230
10231 (defun js2-indent-region (start end)
10232 "Indent the region, but don't use bounce indenting."
10233 (let ((js2-bounce-indent-p nil)
10234 (indent-region-function nil))
10235 (indent-region start end nil))) ; nil for byte-compiler
10236
10237 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10238
10239 ;;;###autoload
10240 (defun js2-mode ()
10241 "Major mode for editing JavaScript code."
10242 (interactive)
10243 (kill-all-local-variables)
10244 (set-syntax-table js2-mode-syntax-table)
10245 (use-local-map js2-mode-map)
10246 (setq major-mode 'js2-mode
10247 mode-name "JavaScript-IDE"
10248 comment-start "//" ; used by comment-region; don't change it
10249 comment-end "")
10250 (setq local-abbrev-table js2-mode-abbrev-table)
10251 (set (make-local-variable 'max-lisp-eval-depth)
10252 (max max-lisp-eval-depth 3000))
10253 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10254 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10255
10256 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10257 ;; on most platforms other than the one I originally wrote it on. So it's
10258 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10259 ;; with our binding of the RET key inside comments: short lines stay short.
10260 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10261
10262 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10263 (set (make-local-variable 'next-error-function) #'js2-next-error)
10264 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10265 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10266 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10267 ;; for characters inside regexp literals.
10268 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10269 ;; this is necessary to make `show-paren-function' work properly
10270 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10271 ;; needed for M-x rgrep, among other things
10272 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10273
10274 ;; some variables needed by cc-engine for paragraph-fill, etc.
10275 (setq c-buffer-is-cc-mode t
10276 c-comment-prefix-regexp js2-comment-prefix-regexp
10277 c-comment-start-regexp "/[*/]\\|\\s|"
10278 c-paragraph-start js2-paragraph-start
10279 c-paragraph-separate "$"
10280 comment-start-skip js2-comment-start-skip
10281 c-syntactic-ws-start js2-syntactic-ws-start
10282 c-syntactic-ws-end js2-syntactic-ws-end
10283 c-syntactic-eol js2-syntactic-eol)
10284
10285 (setq js2-default-externs
10286 (append js2-ecma-262-externs
10287 (if js2-include-browser-externs
10288 js2-browser-externs)
10289 (if js2-include-gears-externs
10290 js2-gears-externs)
10291 (if js2-include-rhino-externs
10292 js2-rhino-externs)))
10293
10294 ;; We do our own syntax highlighting based on the parse tree.
10295 ;; However, we want minor modes that add keywords to highlight properly
10296 ;; (examples: doxymacs, column-marker). We do this by not letting
10297 ;; font-lock unfontify anything, and telling it to fontify after we
10298 ;; re-parse and re-highlight the buffer. (We currently don't do any
10299 ;; work with regions other than the whole buffer.)
10300 (dolist (var '(font-lock-unfontify-buffer-function
10301 font-lock-unfontify-region-function))
10302 (set (make-local-variable var) (lambda (&rest args) t)))
10303
10304 ;; Don't let font-lock do syntactic (string/comment) fontification.
10305 (set (make-local-variable #'font-lock-syntactic-face-function)
10306 (lambda (state) nil))
10307
10308 ;; Experiment: make reparse-delay longer for longer files.
10309 (if (plusp js2-dynamic-idle-timer-adjust)
10310 (setq js2-idle-timer-delay
10311 (* js2-idle-timer-delay
10312 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10313
10314 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10315 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10316 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10317 (imenu-add-to-menubar (concat "IM-" mode-name))
10318 (when js2-mirror-mode
10319 (js2-enter-mirror-mode))
10320 (add-to-invisibility-spec '(js2-outline . t))
10321 (set (make-local-variable 'line-move-ignore-invisible) t)
10322 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10323 (setq js2-mode-functions-hidden nil
10324 js2-mode-comments-hidden nil
10325 js2-mode-buffer-dirty-p t
10326 js2-mode-parsing nil)
10327 (js2-reparse)
10328 (run-hooks 'js2-mode-hook))
10329
10330 (defun js2-mode-exit ()
10331 "Exit `js2-mode' and clean up."
10332 (interactive)
10333 (when js2-mode-node-overlay
10334 (delete-overlay js2-mode-node-overlay)
10335 (setq js2-mode-node-overlay nil))
10336 (js2-remove-overlays)
10337 (setq js2-mode-ast nil)
10338 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10339 (remove-from-invisibility-spec '(js2-outline . t))
10340 (js2-mode-show-all)
10341 (js2-with-unmodifying-text-property-changes
10342 (js2-clear-face (point-min) (point-max))))
10343
10344 (defun js2-before-save ()
10345 "Clean up whitespace before saving file.
10346 You can disable this by customizing `js2-cleanup-whitespace'."
10347 (when js2-cleanup-whitespace
10348 (let ((col (current-column)))
10349 (delete-trailing-whitespace)
10350 ;; don't change trailing whitespace on current line
10351 (unless (eq (current-column) col)
10352 (indent-to col)))))
10353
10354 (defsubst js2-mode-reset-timer ()
10355 "Cancel any existing parse timer and schedule a new one."
10356 (if js2-mode-parse-timer
10357 (cancel-timer js2-mode-parse-timer))
10358 (setq js2-mode-parsing nil)
10359 (setq js2-mode-parse-timer
10360 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10361
10362 (defun js2-mode-edit (beg end len)
10363 "Schedule a new parse after buffer is edited.
10364 Buffer edit spans from BEG to END and is of length LEN.
10365 Also clears the `js2-magic' bit on autoinserted parens/brackets
10366 if the edit occurred on a line different from the magic paren."
10367 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10368 (line (if magic-pos (line-number-at-pos magic-pos))))
10369 (and line
10370 (or (/= (line-number-at-pos beg) line)
10371 (and (> 0 len)
10372 (/= (line-number-at-pos end) line)))
10373 (js2-mode-mundanify-parens)))
10374 (setq js2-mode-buffer-dirty-p t)
10375 (js2-mode-hide-overlay)
10376 (js2-mode-reset-timer))
10377
10378 (defun js2-mode-run-font-lock ()
10379 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10380 This is intended to allow modes that install their own font-lock keywords
10381 to work with js2-mode. In practice it never seems to work for long.
10382 Hopefully the Emacs maintainers can help figure out a way to make it work."
10383 (when (and (boundp 'font-lock-keywords)
10384 font-lock-keywords
10385 (boundp 'font-lock-mode)
10386 font-lock-mode)
10387 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10388 ;; play nicely with js2-mode. They go out of their way to fail to
10389 ;; provide any option for saying "look, fontify the farging buffer
10390 ;; with just the keywords already". Argh.
10391 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10392 (let (font-lock-verbose)
10393 (font-lock-fontify-buffer))))
10394
10395 (defun js2-reparse (&optional force)
10396 "Re-parse current buffer after user finishes some data entry.
10397 If we get any user input while parsing, including cursor motion,
10398 we discard the parse and reschedule it. If FORCE is nil, then the
10399 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10400 (let (time
10401 interrupted-p
10402 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10403 (unless js2-mode-parsing
10404 (setq js2-mode-parsing t)
10405 (unwind-protect
10406 (when (or js2-mode-buffer-dirty-p force)
10407 (js2-remove-overlays)
10408 (js2-with-unmodifying-text-property-changes
10409 (remove-text-properties (point-min) (point-max) '(syntax-table))
10410 (setq js2-mode-buffer-dirty-p nil
10411 js2-mode-fontifications nil
10412 js2-mode-deferred-properties nil
10413 js2-additional-externs nil)
10414 (if js2-mode-verbose-parse-p
10415 (message "parsing..."))
10416 (setq time
10417 (js2-time
10418 (setq interrupted-p
10419 (catch 'interrupted
10420 (setq js2-mode-ast (js2-parse))
10421 (when (plusp js2-highlight-level)
10422 (js2-mode-fontify-regions))
10423 (js2-mode-remove-suppressed-warnings)
10424 (js2-mode-show-warnings)
10425 (js2-mode-show-errors)
10426 (js2-mode-run-font-lock) ; note: doesn't work
10427 (js2-mode-highlight-magic-parens)
10428 (if (>= js2-highlight-level 1)
10429 (js2-highlight-jsdoc js2-mode-ast))
10430 nil))))
10431 (if interrupted-p
10432 (progn
10433 ;; unfinished parse => try again
10434 (setq js2-mode-buffer-dirty-p t)
10435 (js2-mode-reset-timer))
10436 (if js2-mode-verbose-parse-p
10437 (message "Parse time: %s" time)))))
10438 (setq js2-mode-parsing nil)
10439 (unless interrupted-p
10440 (setq js2-mode-parse-timer nil))))))
10441
10442 (defun js2-mode-show-node ()
10443 "Debugging aid: highlight selected AST node on mouse click."
10444 (interactive)
10445 (let ((node (js2-node-at-point))
10446 beg
10447 end)
10448 (when js2-mode-show-overlay
10449 (if (null node)
10450 (message "No node found at location %s" (point))
10451 (setq beg (js2-node-abs-pos node)
10452 end (+ beg (js2-node-len node)))
10453 (if js2-mode-node-overlay
10454 (move-overlay js2-mode-node-overlay beg end)
10455 (setq js2-mode-node-overlay (make-overlay beg end))
10456 (overlay-put js2-mode-node-overlay 'face 'highlight))
10457 (js2-with-unmodifying-text-property-changes
10458 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10459 (message "%s, parent: %s"
10460 (js2-node-short-name node)
10461 (if (js2-node-parent node)
10462 (js2-node-short-name (js2-node-parent node))
10463 "nil"))))))
10464
10465 (defun js2-mode-hide-overlay (&optional p1 p2)
10466 "Remove the debugging overlay when the point moves.
10467 P1 and P2 are the old and new values of point, respectively."
10468 (when js2-mode-node-overlay
10469 (let ((beg (overlay-start js2-mode-node-overlay))
10470 (end (overlay-end js2-mode-node-overlay)))
10471 ;; Sometimes we're called spuriously.
10472 (unless (and p2
10473 (>= p2 beg)
10474 (<= p2 end))
10475 (js2-with-unmodifying-text-property-changes
10476 (remove-text-properties beg end '(point-left nil)))
10477 (delete-overlay js2-mode-node-overlay)
10478 (setq js2-mode-node-overlay nil)))))
10479
10480 (defun js2-mode-reset ()
10481 "Debugging helper: reset everything."
10482 (interactive)
10483 (js2-mode-exit)
10484 (js2-mode))
10485
10486 (defsubst js2-mode-show-warn-or-err (e face)
10487 "Highlight a warning or error E with FACE.
10488 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10489 (let* ((key (first e))
10490 (beg (second e))
10491 (end (+ beg (third e)))
10492 ;; Don't inadvertently go out of bounds.
10493 (beg (max (point-min) (min beg (point-max))))
10494 (end (max (point-min) (min end (point-max))))
10495 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10496 (ovl (make-overlay beg end)))
10497 (overlay-put ovl 'face face)
10498 (overlay-put ovl 'js2-error t)
10499 (put-text-property beg end 'help-echo (js2-get-msg key))
10500 (put-text-property beg end 'point-entered #'js2-echo-error)))
10501
10502 (defun js2-remove-overlays ()
10503 "Remove overlays from buffer that have a `js2-error' property."
10504 (let ((beg (point-min))
10505 (end (point-max)))
10506 (save-excursion
10507 (dolist (o (overlays-in beg end))
10508 (when (overlay-get o 'js2-error)
10509 (delete-overlay o))))))
10510
10511 (defun js2-error-at-point (&optional pos)
10512 "Return non-nil if there's an error overlay at POS.
10513 Defaults to point."
10514 (loop with pos = (or pos (point))
10515 for o in (overlays-at pos)
10516 thereis (overlay-get o 'js2-error)))
10517
10518 (defun js2-mode-fontify-regions ()
10519 "Apply fontifications recorded during parsing."
10520 ;; We defer clearing faces as long as possible to eliminate flashing.
10521 (js2-clear-face (point-min) (point-max))
10522 ;; have to reverse the recorded fontifications so that errors and
10523 ;; warnings overwrite the normal fontifications
10524 (dolist (f (nreverse js2-mode-fontifications))
10525 (put-text-property (first f) (second f) 'face (third f)))
10526 (setq js2-mode-fontifications nil)
10527 (dolist (p js2-mode-deferred-properties)
10528 (apply #'put-text-property p))
10529 (setq js2-mode-deferred-properties nil))
10530
10531 (defun js2-mode-show-errors ()
10532 "Highlight syntax errors."
10533 (when js2-mode-show-parse-errors
10534 (dolist (e (js2-ast-root-errors js2-mode-ast))
10535 (js2-mode-show-warn-or-err e 'js2-error-face))))
10536
10537 (defun js2-mode-remove-suppressed-warnings ()
10538 "Take suppressed warnings out of the AST warnings list.
10539 This ensures that the counts and `next-error' are correct."
10540 (setf (js2-ast-root-warnings js2-mode-ast)
10541 (js2-delete-if
10542 (lambda (e)
10543 (let ((key (caar e)))
10544 (or
10545 (and (not js2-strict-trailing-comma-warning)
10546 (string-match "trailing\\.comma" key))
10547 (and (not js2-strict-cond-assign-warning)
10548 (string= key "msg.equal.as.assign"))
10549 (and js2-missing-semi-one-line-override
10550 (string= key "msg.missing.semi")
10551 (let* ((beg (second e))
10552 (node (js2-node-at-point beg))
10553 (fn (js2-mode-find-parent-fn node))
10554 (body (and fn (js2-function-node-body fn)))
10555 (lc (and body (js2-node-abs-pos body)))
10556 (rc (and lc (+ lc (js2-node-len body)))))
10557 (and fn
10558 (or (null body)
10559 (save-excursion
10560 (goto-char beg)
10561 (and (js2-same-line lc)
10562 (js2-same-line rc))))))))))
10563 (js2-ast-root-warnings js2-mode-ast))))
10564
10565 (defun js2-mode-show-warnings ()
10566 "Highlight strict-mode warnings."
10567 (when js2-mode-show-strict-warnings
10568 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10569 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10570
10571 (defun js2-echo-error (old-point new-point)
10572 "Called by point-motion hooks."
10573 (let ((msg (get-text-property new-point 'help-echo)))
10574 (if msg
10575 (message msg))))
10576
10577 (defalias #'js2-echo-help #'js2-echo-error)
10578
10579 (defun js2-enter-key ()
10580 "Handle user pressing the Enter key."
10581 (interactive)
10582 (let ((parse-status (save-excursion
10583 (parse-partial-sexp (point-min) (point)))))
10584 (cond
10585 ;; check if we're inside a string
10586 ((nth 3 parse-status)
10587 (js2-mode-split-string parse-status))
10588 ;; check if inside a block comment
10589 ((nth 4 parse-status)
10590 (js2-mode-extend-comment))
10591 (t
10592 ;; should probably figure out what the mode-map says we should do
10593 (if js2-indent-on-enter-key
10594 (let ((js2-bounce-indent-p nil))
10595 (js2-indent-line)))
10596 (insert "\n")
10597 (if js2-enter-indents-newline
10598 (let ((js2-bounce-indent-p nil))
10599 (js2-indent-line)))))))
10600
10601 (defun js2-mode-split-string (parse-status)
10602 "Turn a newline in mid-string into a string concatenation.
10603 PARSE-STATUS is as documented in `parse-partial-sexp'."
10604 (let* ((col (current-column))
10605 (quote-char (nth 3 parse-status))
10606 (quote-string (string quote-char))
10607 (string-beg (nth 8 parse-status))
10608 (indent (save-match-data
10609 (or
10610 (save-excursion
10611 (back-to-indentation)
10612 (if (looking-at "\\+")
10613 (current-column)))
10614 (save-excursion
10615 (goto-char string-beg)
10616 (if (looking-back "\\+\\s-+")
10617 (goto-char (match-beginning 0)))
10618 (current-column))))))
10619 (insert quote-char "\n")
10620 (indent-to indent)
10621 (insert "+ " quote-string)
10622 (when (eolp)
10623 (insert quote-string)
10624 (backward-char 1))))
10625
10626 (defun js2-mode-extend-comment ()
10627 "When inside a comment block, add comment prefix."
10628 (let (star single col first-line needs-close)
10629 (save-excursion
10630 (back-to-indentation)
10631 (cond
10632 ((looking-at "\\*[^/]")
10633 (setq star t
10634 col (current-column)))
10635 ((looking-at "/\\*")
10636 (setq star t
10637 first-line t
10638 col (1+ (current-column))))
10639 ((looking-at "//")
10640 (setq single t
10641 col (current-column)))))
10642 ;; Heuristic for whether we need to close the comment:
10643 ;; if we've got a parse error here, assume it's an unterminated
10644 ;; comment.
10645 (setq needs-close
10646 (or
10647 (eq (get-text-property (1- (point)) 'point-entered)
10648 'js2-echo-error)
10649 ;; The heuristic above doesn't work well when we're
10650 ;; creating a comment and there's another one downstream,
10651 ;; as our parser thinks this one ends at the end of the
10652 ;; next one. (You can have a /* inside a js block comment.)
10653 ;; So just close it if the next non-ws char isn't a *.
10654 (and first-line
10655 (eolp)
10656 (save-excursion
10657 (skip-chars-forward " \t\r\n")
10658 (not (eq (char-after) ?*))))))
10659 (insert "\n")
10660 (cond
10661 (star
10662 (indent-to col)
10663 (insert "* ")
10664 (if (and first-line needs-close)
10665 (save-excursion
10666 (insert "\n")
10667 (indent-to col)
10668 (insert "*/"))))
10669 (single
10670 (when (save-excursion
10671 (and (zerop (forward-line 1))
10672 (looking-at "\\s-*//")))
10673 (indent-to col)
10674 (insert "// "))))))
10675
10676 (defun js2-beginning-of-line ()
10677 "Toggles point between bol and first non-whitespace char in line.
10678 Also moves past comment delimiters when inside comments."
10679 (interactive)
10680 (let (node beg)
10681 (cond
10682 ((bolp)
10683 (back-to-indentation))
10684 ((looking-at "//")
10685 (skip-chars-forward "/ \t"))
10686 ((and (eq (char-after) ?*)
10687 (setq node (js2-comment-at-point))
10688 (memq (js2-comment-node-format node) '(jsdoc block))
10689 (save-excursion
10690 (skip-chars-backward " \t")
10691 (bolp)))
10692 (skip-chars-forward "\* \t"))
10693 (t
10694 (goto-char (point-at-bol))))))
10695
10696 (defun js2-end-of-line ()
10697 "Toggles point between eol and last non-whitespace char in line."
10698 (interactive)
10699 (if (eolp)
10700 (skip-chars-backward " \t")
10701 (goto-char (point-at-eol))))
10702
10703 (defun js2-enter-mirror-mode()
10704 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10705 on insertion."
10706 (interactive)
10707 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10708 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10709 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10710 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10711 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10712 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10713 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10714 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10715
10716 (defun js2-leave-mirror-mode()
10717 "Turns off mirror mode."
10718 (interactive)
10719 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10720 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10721
10722 (defsubst js2-mode-inside-string ()
10723 "Return non-nil if inside a string.
10724 Actually returns the quote character that begins the string."
10725 (let ((parse-state (save-excursion
10726 (parse-partial-sexp (point-min) (point)))))
10727 (nth 3 parse-state)))
10728
10729 (defsubst js2-mode-inside-comment-or-string ()
10730 "Return non-nil if inside a comment or string."
10731 (or
10732 (let ((comment-start
10733 (save-excursion
10734 (goto-char (point-at-bol))
10735 (if (re-search-forward "//" (point-at-eol) t)
10736 (match-beginning 0)))))
10737 (and comment-start
10738 (<= comment-start (point))))
10739 (let ((parse-state (save-excursion
10740 (parse-partial-sexp (point-min) (point)))))
10741 (or (nth 3 parse-state)
10742 (nth 4 parse-state)))))
10743
10744 (defsubst js2-make-magic-delimiter (delim &optional pos)
10745 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10746 Sets value of `js2-magic' text property to line number at POS."
10747 (propertize delim
10748 'js2-magic (line-number-at-pos pos)
10749 'face 'js2-magic-paren-face))
10750
10751 (defun js2-mode-match-delimiter (open close)
10752 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10753 The rule we use, which as far as we can tell is how Eclipse works,
10754 is that we insert the match if we're not in a comment or string,
10755 and the next non-whitespace character is either punctuation or
10756 occurs on another line."
10757 (insert open)
10758 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10759 (not (js2-mode-inside-comment-or-string)))
10760 (save-excursion
10761 (insert (js2-make-magic-delimiter close)))
10762 (when js2-auto-indent-p
10763 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10764 (js2-indent-line)))))
10765
10766 (defun js2-mode-match-bracket ()
10767 "Insert matching bracket."
10768 (interactive)
10769 (js2-mode-match-delimiter "[" "]"))
10770
10771 (defun js2-mode-match-paren ()
10772 "Insert matching paren unless already inserted."
10773 (interactive)
10774 (js2-mode-match-delimiter "(" ")"))
10775
10776 (defun js2-mode-match-curly (arg)
10777 "Insert matching curly-brace.
10778 With prefix arg, no formatting or indentation will occur -- the close-brace
10779 is simply inserted directly at the point."
10780 (interactive "p")
10781 (let (try-pos)
10782 (cond
10783 (current-prefix-arg
10784 (js2-mode-match-delimiter "{" "}"))
10785 ((and js2-auto-insert-catch-block
10786 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10787 (point-at-bol))
10788 (match-beginning 1))))
10789 (js2-insert-catch-skel try-pos))
10790 (t
10791 ;; Otherwise try to do something smarter.
10792 (insert "{")
10793 (unless (or (not (looking-at "\\s-*$"))
10794 (save-excursion
10795 (skip-chars-forward " \t\r\n")
10796 (and (looking-at "}")
10797 (js2-error-at-point)))
10798 (js2-mode-inside-comment-or-string))
10799 (undo-boundary)
10800 ;; absolutely mystifying bug: when inserting the next "\n",
10801 ;; the buffer-undo-list is given two new entries: the inserted range,
10802 ;; and the incorrect position of the point. It's recorded incorrectly
10803 ;; as being before the opening "{", not after it. But it's recorded
10804 ;; as the correct value if you're debugging `js2-mode-match-curly'
10805 ;; in edebug. I have no idea why it's doing this, but incrementing
10806 ;; the inserted position fixes the problem, so that the undo takes us
10807 ;; back to just after the user-inserted "{".
10808 (insert "\n")
10809 (ignore-errors
10810 (incf (cadr buffer-undo-list)))
10811 (js2-indent-line)
10812 (save-excursion
10813 (insert "\n}")
10814 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10815 (js2-indent-line))))))))
10816
10817 (defun js2-insert-catch-skel (try-pos)
10818 "Complete a try/catch block after inserting a { following a try keyword.
10819 Rationale is that a try always needs a catch or a finally, and the catch is
10820 the more likely of the two.
10821
10822 TRY-POS is the buffer position of the try keyword. The open-curly should
10823 already have been inserted."
10824 (insert "{")
10825 (let ((try-col (save-excursion
10826 (goto-char try-pos)
10827 (current-column))))
10828 (insert "\n")
10829 (undo-boundary)
10830 (js2-indent-line) ;; indent the blank line where cursor will end up
10831 (save-excursion
10832 (insert "\n")
10833 (indent-to try-col)
10834 (insert "} catch (x) {\n\n")
10835 (indent-to try-col)
10836 (insert "}"))))
10837
10838 (defun js2-mode-highlight-magic-parens ()
10839 "Re-highlight magic parens after parsing nukes the 'face prop."
10840 (let ((beg (point-min))
10841 end)
10842 (while (setq beg (next-single-property-change beg 'js2-magic))
10843 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10844 (if (get-text-property beg 'js2-magic)
10845 (js2-with-unmodifying-text-property-changes
10846 (put-text-property beg (or end (1+ beg))
10847 'face 'js2-magic-paren-face))))))
10848
10849 (defun js2-mode-mundanify-parens ()
10850 "Clear all magic parens and brackets."
10851 (let ((beg (point-min))
10852 end)
10853 (while (setq beg (next-single-property-change beg 'js2-magic))
10854 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10855 (remove-text-properties beg (or end (1+ beg))
10856 '(js2-magic face)))))
10857
10858 (defsubst js2-match-quote (quote-string)
10859 (let ((start-quote (js2-mode-inside-string)))
10860 (cond
10861 ;; inside a comment - don't do quote-matching, since we can't
10862 ;; reliably figure out if we're in a string inside the comment
10863 ((js2-comment-at-point)
10864 (insert quote-string))
10865 ((not start-quote)
10866 ;; not in string => insert matched quotes
10867 (insert quote-string)
10868 ;; exception: if we're just before a word, don't double it.
10869 (unless (looking-at "[^ \t\r\n]")
10870 (save-excursion
10871 (insert quote-string))))
10872 ((looking-at quote-string)
10873 (if (looking-back "[^\\]\\\\")
10874 (insert quote-string)
10875 (forward-char 1)))
10876 ((and js2-mode-escape-quotes
10877 (save-excursion
10878 (save-match-data
10879 (re-search-forward quote-string (point-at-eol) t))))
10880 ;; inside terminated string, escape quote (unless already escaped)
10881 (insert (if (looking-back "[^\\]\\\\")
10882 quote-string
10883 (concat "\\" quote-string))))
10884 (t
10885 (insert quote-string))))) ; else terminate the string
10886
10887 (defun js2-mode-match-single-quote ()
10888 "Insert matching single-quote."
10889 (interactive)
10890 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10891 ;; don't match inside comments, since apostrophe is more common
10892 (if (nth 4 parse-status)
10893 (insert "'")
10894 (js2-match-quote "'"))))
10895
10896 (defun js2-mode-match-double-quote ()
10897 "Insert matching double-quote."
10898 (interactive)
10899 (js2-match-quote "\""))
10900
10901 ;; Eclipse works as follows:
10902 ;; * type an open-paren and it auto-inserts close-paren
10903 ;; - auto-inserted paren gets a green bracket
10904 ;; - green bracket means typing close-paren there will skip it
10905 ;; * if you insert any text on a different line, it turns off
10906 (defun js2-mode-magic-close-paren ()
10907 "Skip over close-paren rather than inserting, where appropriate."
10908 (interactive)
10909 (let* ((here (point))
10910 (parse-status (parse-partial-sexp (point-min) here))
10911 (open-pos (nth 1 parse-status))
10912 (close last-input-event)
10913 (open (cond
10914 ((eq close ?\))
10915 ?\()
10916 ((eq close ?\])
10917 ?\[)
10918 ((eq close ?})
10919 ?{)
10920 (t nil))))
10921 (if (and (eq (char-after) close)
10922 (eq open (char-after open-pos))
10923 (js2-same-line open-pos)
10924 (get-text-property here 'js2-magic))
10925 (progn
10926 (remove-text-properties here (1+ here) '(js2-magic face))
10927 (forward-char 1))
10928 (insert-char close 1))
10929 (blink-matching-open)))
10930
10931 (defun js2-mode-wait-for-parse (callback)
10932 "Invoke CALLBACK when parsing is finished.
10933 If parsing is already finished, calls CALLBACK immediately."
10934 (if (not js2-mode-buffer-dirty-p)
10935 (funcall callback)
10936 (push callback js2-mode-pending-parse-callbacks)
10937 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10938
10939 (defun js2-mode-parse-finished ()
10940 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10941 ;; We can't let errors propagate up, since it prevents the
10942 ;; `js2-parse' method from completing normally and returning
10943 ;; the ast, which makes things mysteriously not work right.
10944 (unwind-protect
10945 (dolist (cb js2-mode-pending-parse-callbacks)
10946 (condition-case err
10947 (funcall cb)
10948 (error (message "%s" err))))
10949 (setq js2-mode-pending-parse-callbacks nil)))
10950
10951 (defun js2-mode-flag-region (from to flag)
10952 "Hide or show text from FROM to TO, according to FLAG.
10953 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10954 Returns the created overlay if FLAG is non-nil."
10955 (remove-overlays from to 'invisible 'js2-outline)
10956 (when flag
10957 (let ((o (make-overlay from to)))
10958 (overlay-put o 'invisible 'js2-outline)
10959 (overlay-put o 'isearch-open-invisible
10960 'js2-isearch-open-invisible)
10961 o)))
10962
10963 ;; Function to be set as an outline-isearch-open-invisible' property
10964 ;; to the overlay that makes the outline invisible (see
10965 ;; `js2-mode-flag-region').
10966 (defun js2-isearch-open-invisible (overlay)
10967 ;; We rely on the fact that isearch places point on the matched text.
10968 (js2-mode-show-element))
10969
10970 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10971 "Return cons cell of bounds of folding overlay at POS.
10972 Returns nil if not found."
10973 (let ((overlays (overlays-at (or pos (point))))
10974 o)
10975 (while (and overlays
10976 (not o))
10977 (if (overlay-get (car overlays) 'invisible)
10978 (setq o (car overlays))
10979 (setq overlays (cdr overlays))))
10980 (if o
10981 (cons (overlay-start o) (overlay-end o)))))
10982
10983 (defun js2-mode-function-at-point (&optional pos)
10984 "Return the innermost function node enclosing current point.
10985 Returns nil if point is not in a function."
10986 (let ((node (js2-node-at-point pos)))
10987 (while (and node (not (js2-function-node-p node)))
10988 (setq node (js2-node-parent node)))
10989 (if (js2-function-node-p node)
10990 node)))
10991
10992 (defun js2-mode-toggle-element ()
10993 "Hide or show the foldable element at the point."
10994 (interactive)
10995 (let (comment fn pos)
10996 (save-excursion
10997 (save-match-data
10998 (cond
10999 ;; /* ... */ comment?
11000 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11001 (if (js2-mode-invisible-overlay-bounds
11002 (setq pos (+ 3 (js2-node-abs-pos comment))))
11003 (progn
11004 (goto-char pos)
11005 (js2-mode-show-element))
11006 (js2-mode-hide-element)))
11007 ;; //-comment?
11008 ((save-excursion
11009 (back-to-indentation)
11010 (looking-at js2-mode-//-comment-re))
11011 (js2-mode-toggle-//-comment))
11012 ;; function?
11013 ((setq fn (js2-mode-function-at-point))
11014 (setq pos (and (js2-function-node-body fn)
11015 (js2-node-abs-pos (js2-function-node-body fn))))
11016 (goto-char (1+ pos))
11017 (if (js2-mode-invisible-overlay-bounds)
11018 (js2-mode-show-element)
11019 (js2-mode-hide-element)))
11020 (t
11021 (message "Nothing at point to hide or show")))))))
11022
11023 (defun js2-mode-hide-element ()
11024 "Fold/hide contents of a block, showing ellipses.
11025 Show the hidden text with \\[js2-mode-show-element]."
11026 (interactive)
11027 (if js2-mode-buffer-dirty-p
11028 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11029 (let (node body beg end)
11030 (cond
11031 ((js2-mode-invisible-overlay-bounds)
11032 (message "already hidden"))
11033 (t
11034 (setq node (js2-node-at-point))
11035 (cond
11036 ((js2-block-comment-p node)
11037 (js2-mode-hide-comment node))
11038 (t
11039 (while (and node (not (js2-function-node-p node)))
11040 (setq node (js2-node-parent node)))
11041 (if (and node
11042 (setq body (js2-function-node-body node)))
11043 (progn
11044 (setq beg (js2-node-abs-pos body)
11045 end (+ beg (js2-node-len body)))
11046 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11047 (message "No collapsable element found at point"))))))))
11048
11049 (defun js2-mode-show-element ()
11050 "Show the hidden element at current point."
11051 (interactive)
11052 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11053 (if bounds
11054 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11055 (message "Nothing to un-hide"))))
11056
11057 (defun js2-mode-show-all ()
11058 "Show all of the text in the buffer."
11059 (interactive)
11060 (js2-mode-flag-region (point-min) (point-max) nil))
11061
11062 (defun js2-mode-toggle-hide-functions ()
11063 (interactive)
11064 (if js2-mode-functions-hidden
11065 (js2-mode-show-functions)
11066 (js2-mode-hide-functions)))
11067
11068 (defun js2-mode-hide-functions ()
11069 "Hides all non-nested function bodies in the buffer.
11070 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11071 to open an individual entry."
11072 (interactive)
11073 (if js2-mode-buffer-dirty-p
11074 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11075 (if (null js2-mode-ast)
11076 (message "Oops - parsing failed")
11077 (setq js2-mode-functions-hidden t)
11078 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11079
11080 (defun js2-mode-function-hider (n endp)
11081 (when (not endp)
11082 (let ((tt (js2-node-type n))
11083 body beg end)
11084 (cond
11085 ((and (= tt js2-FUNCTION)
11086 (setq body (js2-function-node-body n)))
11087 (setq beg (js2-node-abs-pos body)
11088 end (+ beg (js2-node-len body)))
11089 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11090 nil) ; don't process children of function
11091 (t
11092 t))))) ; keep processing other AST nodes
11093
11094 (defun js2-mode-show-functions ()
11095 "Un-hide any folded function bodies in the buffer."
11096 (interactive)
11097 (setq js2-mode-functions-hidden nil)
11098 (save-excursion
11099 (goto-char (point-min))
11100 (while (/= (goto-char (next-overlay-change (point)))
11101 (point-max))
11102 (dolist (o (overlays-at (point)))
11103 (when (and (overlay-get o 'invisible)
11104 (not (overlay-get o 'comment)))
11105 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11106
11107 (defun js2-mode-hide-comment (n)
11108 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11109 3 ; /**
11110 2)) ; /*
11111 (beg (+ (js2-node-abs-pos n) head))
11112 (end (- (+ beg (js2-node-len n)) head 2))
11113 (o (js2-mode-flag-region beg end 'hide)))
11114 (overlay-put o 'comment t)))
11115
11116 (defun js2-mode-toggle-hide-comments ()
11117 "Folds all block comments in the buffer.
11118 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11119 to open an individual entry."
11120 (interactive)
11121 (if js2-mode-comments-hidden
11122 (js2-mode-show-comments)
11123 (js2-mode-hide-comments)))
11124
11125 (defun js2-mode-hide-comments ()
11126 (interactive)
11127 (if js2-mode-buffer-dirty-p
11128 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11129 (if (null js2-mode-ast)
11130 (message "Oops - parsing failed")
11131 (setq js2-mode-comments-hidden t)
11132 (dolist (n (js2-ast-root-comments js2-mode-ast))
11133 (let ((format (js2-comment-node-format n)))
11134 (when (js2-block-comment-p n)
11135 (js2-mode-hide-comment n))))
11136 (js2-mode-hide-//-comments)))
11137
11138 (defsubst js2-mode-extend-//-comment (direction)
11139 "Find start or end of a block of similar //-comment lines.
11140 DIRECTION is -1 to look back, 1 to look forward.
11141 INDENT is the indentation level to match.
11142 Returns the end-of-line position of the furthest adjacent
11143 //-comment line with the same indentation as the current line.
11144 If there is no such matching line, returns current end of line."
11145 (let ((pos (point-at-eol))
11146 (indent (current-indentation)))
11147 (save-excursion
11148 (save-match-data
11149 (while (and (zerop (forward-line direction))
11150 (looking-at js2-mode-//-comment-re)
11151 (eq indent (length (match-string 1))))
11152 (setq pos (point-at-eol)))
11153 pos))))
11154
11155 (defun js2-mode-hide-//-comments ()
11156 "Fold adjacent 1-line comments, showing only snippet of first one."
11157 (let (beg end)
11158 (save-excursion
11159 (save-match-data
11160 (goto-char (point-min))
11161 (while (re-search-forward js2-mode-//-comment-re nil t)
11162 (setq beg (point)
11163 end (js2-mode-extend-//-comment 1))
11164 (unless (eq beg end)
11165 (overlay-put (js2-mode-flag-region beg end 'hide)
11166 'comment t))
11167 (goto-char end)
11168 (forward-char 1))))))
11169
11170 (defun js2-mode-toggle-//-comment ()
11171 "Fold or un-fold any multi-line //-comment at point.
11172 Caller should have determined that this line starts with a //-comment."
11173 (let* ((beg (point-at-eol))
11174 (end beg))
11175 (save-excursion
11176 (goto-char end)
11177 (if (js2-mode-invisible-overlay-bounds)
11178 (js2-mode-show-element)
11179 ;; else hide the comment
11180 (setq beg (js2-mode-extend-//-comment -1)
11181 end (js2-mode-extend-//-comment 1))
11182 (unless (eq beg end)
11183 (overlay-put (js2-mode-flag-region beg end 'hide)
11184 'comment t))))))
11185
11186 (defun js2-mode-show-comments ()
11187 "Un-hide any hidden comments, leaving other hidden elements alone."
11188 (interactive)
11189 (setq js2-mode-comments-hidden nil)
11190 (save-excursion
11191 (goto-char (point-min))
11192 (while (/= (goto-char (next-overlay-change (point)))
11193 (point-max))
11194 (dolist (o (overlays-at (point)))
11195 (when (overlay-get o 'comment)
11196 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11197
11198 (defun js2-mode-display-warnings-and-errors ()
11199 "Turn on display of warnings and errors."
11200 (interactive)
11201 (setq js2-mode-show-parse-errors t
11202 js2-mode-show-strict-warnings t)
11203 (js2-reparse 'force))
11204
11205 (defun js2-mode-hide-warnings-and-errors ()
11206 "Turn off display of warnings and errors."
11207 (interactive)
11208 (setq js2-mode-show-parse-errors nil
11209 js2-mode-show-strict-warnings nil)
11210 (js2-reparse 'force))
11211
11212 (defun js2-mode-toggle-warnings-and-errors ()
11213 "Toggle the display of warnings and errors.
11214 Some users don't like having warnings/errors reported while they type."
11215 (interactive)
11216 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11217 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11218 (if (interactive-p)
11219 (message "warnings and errors %s"
11220 (if js2-mode-show-parse-errors
11221 "enabled"
11222 "disabled")))
11223 (js2-reparse 'force))
11224
11225 (defun js2-mode-customize ()
11226 (interactive)
11227 (customize-group 'js2-mode))
11228
11229 (defun js2-mode-forward-sexp (&optional arg)
11230 "Move forward across one statement or balanced expression.
11231 With ARG, do it that many times. Negative arg -N means
11232 move backward across N balanced expressions."
11233 (interactive "p")
11234 (setq arg (or arg 1))
11235 (if js2-mode-buffer-dirty-p
11236 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11237 (let (node end (start (point)))
11238 (cond
11239 ;; backward-sexp
11240 ;; could probably make this better for some cases:
11241 ;; - if in statement block (e.g. function body), go to parent
11242 ;; - infix exprs like (foo in bar) - maybe go to beginning
11243 ;; of infix expr if in the right-side expression?
11244 ((and arg (minusp arg))
11245 (dotimes (i (- arg))
11246 (js2-backward-sws)
11247 (forward-char -1) ; enter the node we backed up to
11248 (setq node (js2-node-at-point (point) t))
11249 (goto-char (if node
11250 (js2-node-abs-pos node)
11251 (point-min)))))
11252 (t
11253 ;; forward-sexp
11254 (js2-forward-sws)
11255 (dotimes (i arg)
11256 (js2-forward-sws)
11257 (setq node (js2-node-at-point (point) t)
11258 end (if node (+ (js2-node-abs-pos node)
11259 (js2-node-len node))))
11260 (goto-char (or end (point-max))))))))
11261
11262 (defun js2-next-error (&optional arg reset)
11263 "Move to next parse error.
11264 Typically invoked via \\[next-error].
11265 ARG is the number of errors, forward or backward, to move.
11266 RESET means start over from the beginning."
11267 (interactive "p")
11268 (if (or (null js2-mode-ast)
11269 (and (null (js2-ast-root-errors js2-mode-ast))
11270 (null (js2-ast-root-warnings js2-mode-ast))))
11271 (message "No errors")
11272 (when reset
11273 (goto-char (point-min)))
11274 (let* ((errs (copy-sequence
11275 (append (js2-ast-root-errors js2-mode-ast)
11276 (js2-ast-root-warnings js2-mode-ast))))
11277 (continue t)
11278 (start (point))
11279 (count (or arg 1))
11280 (backward (minusp count))
11281 (sorter (if backward '> '<))
11282 (stopper (if backward '< '>))
11283 (count (abs count))
11284 all-errs
11285 err)
11286 ;; sort by start position
11287 (setq errs (sort errs (lambda (e1 e2)
11288 (funcall sorter (second e1) (second e2))))
11289 all-errs errs)
11290 ;; find nth error with pos > start
11291 (while (and errs continue)
11292 (when (funcall stopper (cadar errs) start)
11293 (setq err (car errs))
11294 (if (zerop (decf count))
11295 (setq continue nil)))
11296 (setq errs (cdr errs)))
11297 (if err
11298 (goto-char (second err))
11299 ;; wrap around to first error
11300 (goto-char (second (car all-errs)))
11301 ;; if we were already on it, echo msg again
11302 (if (= (point) start)
11303 (js2-echo-error (point) (point)))))))
11304
11305 (defun js2-down-mouse-3 ()
11306 "Make right-click move the point to the click location.
11307 This makes right-click context menu operations a bit more intuitive.
11308 The point will not move if the region is active, however, to avoid
11309 destroying the region selection."
11310 (interactive)
11311 (when (and js2-move-point-on-right-click
11312 (not mark-active))
11313 (let ((e last-input-event))
11314 (ignore-errors
11315 (goto-char (cadadr e))))))
11316
11317 (defun js2-mode-create-imenu-index ()
11318 "Return an alist for `imenu--index-alist'."
11319 ;; This is built up in `js2-parse-record-imenu' during parsing.
11320 (when js2-mode-ast
11321 ;; if we have an ast but no recorder, they're requesting a rescan
11322 (unless js2-imenu-recorder
11323 (js2-reparse 'force))
11324 (prog1
11325 (js2-build-imenu-index)
11326 (setq js2-imenu-recorder nil
11327 js2-imenu-function-map nil))))
11328
11329 (defun js2-mode-find-tag ()
11330 "Replacement for `find-tag-default'.
11331 `find-tag-default' returns a ridiculous answer inside comments."
11332 (let (beg end)
11333 (js2-with-underscore-as-word-syntax
11334 (save-excursion
11335 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11336 (looking-back "[A-Za-z0-9_$]"))
11337 (setq beg (progn (forward-word -1) (point))
11338 end (progn (forward-word 1) (point)))
11339 (setq beg (progn (forward-word 1) (point))
11340 end (progn (forward-word -1) (point))))
11341 (replace-regexp-in-string
11342 "[\"']" ""
11343 (buffer-substring-no-properties beg end))))))
11344
11345 (defun js2-mode-forward-sibling ()
11346 "Move to the end of the sibling following point in parent.
11347 Returns non-nil if successful, or nil if there was no following sibling."
11348 (let* ((node (js2-node-at-point))
11349 (parent (js2-mode-find-enclosing-fn node))
11350 sib)
11351 (when (setq sib (js2-node-find-child-after (point) parent))
11352 (goto-char (+ (js2-node-abs-pos sib)
11353 (js2-node-len sib))))))
11354
11355 (defun js2-mode-backward-sibling ()
11356 "Move to the beginning of the sibling node preceding point in parent.
11357 Parent is defined as the enclosing script or function."
11358 (let* ((node (js2-node-at-point))
11359 (parent (js2-mode-find-enclosing-fn node))
11360 sib)
11361 (when (setq sib (js2-node-find-child-before (point) parent))
11362 (goto-char (js2-node-abs-pos sib)))))
11363
11364 (defun js2-beginning-of-defun ()
11365 "Go to line on which current function starts, and return non-nil.
11366 If we're not in a function, go to beginning of previous script-level element."
11367 (interactive)
11368 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11369 pos sib)
11370 (cond
11371 ((and (js2-function-node-p parent)
11372 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11373 (goto-char pos))
11374 (t
11375 (js2-mode-backward-sibling)))))
11376
11377 (defun js2-end-of-defun ()
11378 "Go to the char after the last position of the current function.
11379 If we're not in a function, skips over the next script-level element."
11380 (interactive)
11381 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11382 (if (not (js2-function-node-p parent))
11383 ;; punt: skip over next script-level element beyond point
11384 (js2-mode-forward-sibling)
11385 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11386 (js2-node-len parent)))))))
11387
11388 (defun js2-mark-defun (&optional allow-extend)
11389 "Put mark at end of this function, point at beginning.
11390 The function marked is the one that contains point.
11391
11392 Interactively, if this command is repeated,
11393 or (in Transient Mark mode) if the mark is active,
11394 it marks the next defun after the ones already marked."
11395 (interactive "p")
11396 (let (extended)
11397 (when (and allow-extend
11398 (or (and (eq last-command this-command) (mark t))
11399 (and transient-mark-mode mark-active)))
11400 (let ((sib (save-excursion
11401 (goto-char (mark))
11402 (if (js2-mode-forward-sibling)
11403 (point))))
11404 node)
11405 (if sib
11406 (progn
11407 (set-mark sib)
11408 (setq extended t))
11409 ;; no more siblings - try extending to enclosing node
11410 (goto-char (mark t)))))
11411 (when (not extended)
11412 (let ((node (js2-node-at-point (point) t)) ; skip comments
11413 ast fn stmt parent beg end)
11414 (when (js2-ast-root-p node)
11415 (setq ast node
11416 node (or (js2-node-find-child-after (point) node)
11417 (js2-node-find-child-before (point) node))))
11418 ;; only mark whole buffer if we can't find any children
11419 (if (null node)
11420 (setq node ast))
11421 (if (js2-function-node-p node)
11422 (setq parent node)
11423 (setq fn (js2-mode-find-enclosing-fn node)
11424 stmt (if (or (null fn)
11425 (js2-ast-root-p fn))
11426 (js2-mode-find-first-stmt node))
11427 parent (or stmt fn)))
11428 (setq beg (js2-node-abs-pos parent)
11429 end (+ beg (js2-node-len parent)))
11430 (push-mark beg)
11431 (goto-char end)
11432 (exchange-point-and-mark)))))
11433
11434 (defun js2-narrow-to-defun ()
11435 "Narrow to the function enclosing point."
11436 (interactive)
11437 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11438 (fn (if (js2-script-node-p node)
11439 node
11440 (js2-mode-find-enclosing-fn node)))
11441 (beg (js2-node-abs-pos fn)))
11442 (unless (js2-ast-root-p fn)
11443 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11444
11445 (provide 'js2-mode)
11446
11447 ;;; js2-mode.el ends here