]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Fix: when reserved words are used as identifier, js2-mode's parser will corrupt.
[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 ;; Version: See `js2-mode-version'
7 ;; Keywords: languages, javascript
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This JavaScript editing mode supports:
27
28 ;; - strict recognition of the Ecma-262 language standard
29 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
30 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
31 ;; - accurate syntax highlighting using a recursive-descent parser
32 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
33 ;; - undeclared-variable warnings using a configurable externs framework
34 ;; - "bouncing" line indentation to choose among alternate indentation points
35 ;; - smart line-wrapping within comments and strings
36 ;; - code folding:
37 ;; - show some or all function bodies as {...}
38 ;; - show some or all block comments as /*...*/
39 ;; - context-sensitive menu bar and popup menus
40 ;; - code browsing using the `imenu' package
41 ;; - typing helpers such as automatic insertion of matching braces/parens
42 ;; - many customization options
43
44 ;; To customize how it works:
45 ;; M-x customize-group RET js2-mode RET
46
47 ;; Notes:
48
49 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
50 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
51 ;; `js2-mode' current as the EcmaScript language standard evolves.
52
53 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
54 ;; customizable. It is a surprising amount of work to support customizable
55 ;; indentation. The current compromise is that the tab key lets you cycle among
56 ;; various likely indentation points, similar to the behavior of python-mode.
57
58 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
59 ;; and `mumamo', although it could be made to do so with some effort.
60 ;; This means that `js2-mode' is currently only useful for editing JavaScript
61 ;; files, and not for editing JavaScript within <script> tags or templates.
62
63 ;;; Code:
64
65 (eval-when-compile
66 (require 'cl))
67
68 (require 'imenu)
69 (require 'cc-cmds) ; for `c-fill-paragraph'
70
71 (eval-and-compile
72 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
73 (require 'cc-langs) ; it's here in Emacs 21...
74 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
75
76 ;;; Externs (variables presumed to be defined by the host system)
77
78 (defvar js2-ecma-262-externs
79 (mapcar 'symbol-name
80 '(Array Boolean Date Error EvalError Function Infinity
81 Math NaN Number Object RangeError ReferenceError RegExp
82 String SyntaxError TypeError URIError arguments
83 decodeURI decodeURIComponent encodeURI
84 encodeURIComponent escape eval isFinite isNaN
85 parseFloat parseInt undefined unescape))
86 "Ecma-262 externs. Included in `js2-externs' by default.")
87
88 (defvar js2-browser-externs
89 (mapcar 'symbol-name
90 '(;; DOM level 1
91 Attr CDATASection CharacterData Comment DOMException
92 DOMImplementation Document DocumentFragment
93 DocumentType Element Entity EntityReference
94 ExceptionCode NamedNodeMap Node NodeList Notation
95 ProcessingInstruction Text
96
97 ;; DOM level 2
98 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
99 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
100 HTMLBodyElement HTMLButtonElement HTMLCollection
101 HTMLDListElement HTMLDirectoryElement HTMLDivElement
102 HTMLDocument HTMLElement HTMLFieldSetElement
103 HTMLFontElement HTMLFormElement HTMLFrameElement
104 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
105 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
106 HTMLImageElement HTMLInputElement HTMLIsIndexElement
107 HTMLLIElement HTMLLabelElement HTMLLegendElement
108 HTMLLinkElement HTMLMapElement HTMLMenuElement
109 HTMLMetaElement HTMLModElement HTMLOListElement
110 HTMLObjectElement HTMLOptGroupElement
111 HTMLOptionElement HTMLOptionsCollection
112 HTMLParagraphElement HTMLParamElement HTMLPreElement
113 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
114 HTMLStyleElement HTMLTableCaptionElement
115 HTMLTableCellElement HTMLTableColElement
116 HTMLTableElement HTMLTableRowElement
117 HTMLTableSectionElement HTMLTextAreaElement
118 HTMLTitleElement HTMLUListElement
119
120 ;; DOM level 3
121 DOMConfiguration DOMError DOMException
122 DOMImplementationList DOMImplementationSource
123 DOMLocator DOMStringList NameList TypeInfo
124 UserDataHandler
125
126 ;; Window
127 alert confirm document java navigator prompt screen
128 self top
129
130 ;; W3C CSS
131 CSSCharsetRule CSSFontFace CSSFontFaceRule
132 CSSImportRule CSSMediaRule CSSPageRule
133 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
134 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
135 CSSValue CSSValueList Counter DOMImplementationCSS
136 DocumentCSS DocumentStyle ElementCSSInlineStyle
137 LinkStyle MediaList RGBColor Rect StyleSheet
138 StyleSheetList ViewCSS
139
140 ;; W3C Event
141 EventListener EventTarget Event DocumentEvent UIEvent
142 MouseEvent MutationEvent KeyboardEvent
143
144 ;; W3C Range
145 DocumentRange Range RangeException
146
147 ;; W3C XML
148 XPathResult XMLHttpRequest))
149 "Browser externs.
150 You can cause these to be included or excluded with the custom
151 variable `js2-include-browser-externs'.")
152
153 (defvar js2-rhino-externs
154 (mapcar 'symbol-name
155 '(Packages importClass importPackage com org java
156 ;; Global object (shell) externs
157 defineClass deserialize doctest gc help load
158 loadClass print quit readFile readUrl runCommand seal
159 serialize spawn sync toint32 version))
160 "Mozilla Rhino externs.
161 Set `js2-include-rhino-externs' to t to include them.")
162
163 (defvar js2-gears-externs
164 (mapcar 'symbol-name
165 '(
166 ;; TODO(stevey): add these
167 ))
168 "Google Gears externs.
169 Set `js2-include-gears-externs' to t to include them.")
170
171 ;;; Variables
172
173 (defvar js2-emacs22 (>= emacs-major-version 22))
174
175 (defcustom js2-highlight-level 2
176 "Amount of syntax highlighting to perform.
177 0 or a negative value means do no highlighting.
178 1 adds basic syntax highlighting.
179 2 adds highlighting of some Ecma built-in properties.
180 3 adds highlighting of many Ecma built-in functions."
181 :group 'js2-mode
182 :type '(choice (const :tag "None" 0)
183 (const :tag "Basic" 1)
184 (const :tag "Include Properties" 2)
185 (const :tag "Include Functions" 3)))
186
187 (defvar js2-mode-dev-mode-p nil
188 "Non-nil if running in development mode. Normally nil.")
189
190 (defgroup js2-mode nil
191 "An improved JavaScript mode."
192 :group 'languages)
193
194 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
195 (numberp c-basic-offset))
196 c-basic-offset
197 4)
198 "Number of spaces to indent nested statements.
199 Similar to `c-basic-offset'."
200 :group 'js2-mode
201 :type 'integer)
202 (make-variable-buffer-local 'js2-basic-offset)
203
204 ;; TODO(stevey): move this code into a separate minor mode.
205 (defcustom js2-mirror-mode nil
206 "Non-nil to insert closing brackets, parens, etc. automatically."
207 :group 'js2-mode
208 :type 'boolean)
209
210 (defcustom js2-auto-indent-p nil
211 "Automatic indentation with punctuation characters.
212 If non-nil, the current line is indented when certain punctuations
213 are inserted."
214 :group 'js2-mode
215 :type 'boolean)
216
217 (defcustom js2-bounce-indent-p nil
218 "Non-nil to have indent-line function choose among alternatives.
219 If nil, the indent-line function will indent to a predetermined column
220 based on heuristic guessing. If non-nil, then if the current line is
221 already indented to that predetermined column, indenting will choose
222 another likely column and indent to that spot. Repeated invocation of
223 the indent-line function will cycle among the computed alternatives.
224 See the function `js2-bounce-indent' for details."
225 :type 'boolean
226 :group 'js2-mode)
227
228 (defcustom js2-indent-on-enter-key nil
229 "Non-nil to have Enter/Return key indent the line.
230 This is unusual for Emacs modes but common in IDEs like Eclipse."
231 :type 'boolean
232 :group 'js2-mode)
233
234 (defcustom js2-enter-indents-newline nil
235 "Non-nil to have Enter/Return key indent the newly-inserted line.
236 This is unusual for Emacs modes but common in IDEs like Eclipse."
237 :type 'boolean
238 :group 'js2-mode)
239
240 (defcustom js2-rebind-eol-bol-keys t
241 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
242 If non-nil, bounce between bol/eol and first/last non-whitespace char."
243 :group 'js2-mode
244 :type 'boolean)
245
246 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
247 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
248 Each value in the list is passed to `define-key'."
249 :type 'list
250 :group 'js2-mode)
251
252 (defcustom js2-idle-timer-delay 0.2
253 "Delay in secs before re-parsing after user makes changes.
254 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
255 :type 'number
256 :group 'js2-mode)
257 (make-variable-buffer-local 'js2-idle-timer-delay)
258
259 (defcustom js2-dynamic-idle-timer-adjust 0
260 "Positive to adjust `js2-idle-timer-delay' based on file size.
261 The idea is that for short files, parsing is faster so we can be
262 more responsive to user edits without interfering with editing.
263 The buffer length in characters (typically bytes) is divided by
264 this value and used to multiply `js2-idle-timer-delay' for the
265 buffer. For example, a 21k file and 10k adjust yields 21k/10k
266 == 2, so js2-idle-timer-delay is multiplied by 2.
267 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
268 `js2-idle-timer-delay' is not dependent on the file size."
269 :type 'number
270 :group 'js2-mode)
271
272 (defcustom js2-mode-escape-quotes t
273 "Non-nil to disable automatic quote-escaping inside strings."
274 :type 'boolean
275 :group 'js2-mode)
276
277 (defcustom js2-mode-squeeze-spaces t
278 "Non-nil to normalize whitespace when filling in comments.
279 Multiple runs of spaces are converted to a single space."
280 :type 'boolean
281 :group 'js2-mode)
282
283 (defcustom js2-mode-show-parse-errors t
284 "True to highlight parse errors."
285 :type 'boolean
286 :group 'js2-mode)
287
288 (defcustom js2-mode-show-strict-warnings t
289 "Non-nil to emit Ecma strict-mode warnings.
290 Some of the warnings can be individually disabled by other flags,
291 even if this flag is non-nil."
292 :type 'boolean
293 :group 'js2-mode)
294
295 (defcustom js2-strict-trailing-comma-warning t
296 "Non-nil to warn about trailing commas in array literals.
297 Ecma-262 forbids them, but many browsers permit them. IE is the
298 big exception, and can produce bugs if you have trailing commas."
299 :type 'boolean
300 :group 'js2-mode)
301
302 (defcustom js2-strict-missing-semi-warning t
303 "Non-nil to warn about semicolon auto-insertion after statement.
304 Technically this is legal per Ecma-262, but some style guides disallow
305 depending on it."
306 :type 'boolean
307 :group 'js2-mode)
308
309 (defcustom js2-missing-semi-one-line-override nil
310 "Non-nil to permit missing semicolons in one-line functions.
311 In one-liner functions such as `function identity(x) {return x}'
312 people often omit the semicolon for a cleaner look. If you are
313 such a person, you can suppress the missing-semicolon warning
314 by setting this variable to t."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-strict-inconsistent-return-warning t
319 "Non-nil to warn about mixing returns with value-returns.
320 It's perfectly legal to have a `return' and a `return foo' in the
321 same function, but it's often an indicator of a bug, and it also
322 interferes with type inference (in systems that support it.)"
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-strict-cond-assign-warning t
327 "Non-nil to warn about expressions like if (a = b).
328 This often should have been '==' instead of '='. If the warning
329 is enabled, you can suppress it on a per-expression basis by
330 parenthesizing the expression, e.g. if ((a = b)) ..."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-strict-cond-assign-warning t
335 "Non-nil to warn about expressions like if (a = b).
336 This often should have been '==' instead of '='. If the warning
337 is enabled, you can suppress it on a per-expression basis by
338 parenthesizing the expression, e.g. if ((a = b)) ..."
339 :type 'boolean
340 :group 'js2-mode)
341
342 (defcustom js2-strict-var-redeclaration-warning t
343 "Non-nil to warn about redeclaring variables in a script or function."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-var-hides-function-arg-warning t
348 "Non-nil to warn about a var decl hiding a function argument."
349 :type 'boolean
350 :group 'js2-mode)
351
352 (defcustom js2-skip-preprocessor-directives nil
353 "Non-nil to treat lines beginning with # as comments.
354 Useful for viewing Mozilla JavaScript source code."
355 :type 'boolean
356 :group 'js2-mode)
357
358 (defcustom js2-language-version 180
359 "Configures what JavaScript language version to recognize.
360 Currently versions 150, 160, 170 and 180 are supported, corresponding
361 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
362 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
363 and 1.8 adds function closures."
364 :type 'integer
365 :group 'js2-mode)
366
367 (defcustom js2-allow-keywords-as-property-names t
368 "If non-nil, you can use JavaScript keywords as object property names.
369 Examples:
370
371 var foo = {int: 5, while: 6, continue: 7};
372 foo.return = 8;
373
374 Ecma-262 forbids this syntax, but many browsers support it."
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-instanceof-has-side-effects nil
379 "If non-nil, treats the instanceof operator as having side effects.
380 This is useful for xulrunner apps."
381 :type 'boolean
382 :group 'js2-mode)
383
384 (defcustom js2-cleanup-whitespace nil
385 "Non-nil to invoke `delete-trailing-whitespace' before saves."
386 :type 'boolean
387 :group 'js2-mode)
388
389 (defcustom js2-move-point-on-right-click t
390 "Non-nil to move insertion point when you right-click.
391 This makes right-click context menu behavior a bit more intuitive,
392 since menu operations generally apply to the point. The exception
393 is if there is a region selection, in which case the point does -not-
394 move, so cut/copy/paste etc. can work properly.
395
396 Note that IntelliJ moves the point, and Eclipse leaves it alone,
397 so this behavior is customizable."
398 :group 'js2-mode
399 :type 'boolean)
400
401 (defcustom js2-allow-rhino-new-expr-initializer t
402 "Non-nil to support a Rhino's experimental syntactic construct.
403
404 Rhino supports the ability to follow a `new' expression with an object
405 literal, which is used to set additional properties on the new object
406 after calling its constructor. Syntax:
407
408 new <expr> [ ( arglist ) ] [initializer]
409
410 Hence, this expression:
411
412 new Object {a: 1, b: 2}
413
414 results in an Object with properties a=1 and b=2. This syntax is
415 apparently not configurable in Rhino - it's currently always enabled,
416 as of Rhino version 1.7R2."
417 :type 'boolean
418 :group 'js2-mode)
419
420 (defcustom js2-allow-member-expr-as-function-name nil
421 "Non-nil to support experimental Rhino syntax for function names.
422
423 Rhino supports an experimental syntax configured via the Rhino Context
424 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
425
426 function <member-expr> ( [ arg-list ] ) { <body> }
427
428 Where member-expr is a non-parenthesized 'member expression', which
429 is anything at the grammar level of a new-expression or lower, meaning
430 any expression that does not involve infix or unary operators.
431
432 When <member-expr> is not a simple identifier, then it is syntactic
433 sugar for assigning the anonymous function to the <member-expr>. Hence,
434 this code:
435
436 function a.b().c[2] (x, y) { ... }
437
438 is rewritten as:
439
440 a.b().c[2] = function(x, y) {...}
441
442 which doesn't seem particularly useful, but Rhino permits it."
443 :type 'boolean
444 :group 'js2-mode)
445
446 (defvar js2-mode-version 20090727
447 "Release number for `js2-mode'.")
448
449 ;; scanner variables
450
451 (defmacro js2-deflocal (name value &optional comment)
452 "Define a buffer-local variable NAME with VALUE and COMMENT."
453 `(progn
454 (defvar ,name ,value ,comment)
455 (make-variable-buffer-local ',name)))
456
457 ;; We record the start and end position of each token.
458 (js2-deflocal js2-token-beg 1)
459 (js2-deflocal js2-token-end -1)
460
461 (defvar js2-EOF_CHAR -1
462 "Represents end of stream. Distinct from js2-EOF token type.")
463
464 ;; I originally used symbols to represent tokens, but Rhino uses
465 ;; ints and then sets various flag bits in them, so ints it is.
466 ;; The upshot is that we need a `js2-' prefix in front of each name.
467 (defvar js2-ERROR -1)
468 (defvar js2-EOF 0)
469 (defvar js2-EOL 1)
470 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
471 (defvar js2-LEAVEWITH 3)
472 (defvar js2-RETURN 4)
473 (defvar js2-GOTO 5)
474 (defvar js2-IFEQ 6)
475 (defvar js2-IFNE 7)
476 (defvar js2-SETNAME 8)
477 (defvar js2-BITOR 9)
478 (defvar js2-BITXOR 10)
479 (defvar js2-BITAND 11)
480 (defvar js2-EQ 12)
481 (defvar js2-NE 13)
482 (defvar js2-LT 14)
483 (defvar js2-LE 15)
484 (defvar js2-GT 16)
485 (defvar js2-GE 17)
486 (defvar js2-LSH 18)
487 (defvar js2-RSH 19)
488 (defvar js2-URSH 20)
489 (defvar js2-ADD 21) ; infix plus
490 (defvar js2-SUB 22) ; infix minus
491 (defvar js2-MUL 23)
492 (defvar js2-DIV 24)
493 (defvar js2-MOD 25)
494 (defvar js2-NOT 26)
495 (defvar js2-BITNOT 27)
496 (defvar js2-POS 28) ; unary plus
497 (defvar js2-NEG 29) ; unary minus
498 (defvar js2-NEW 30)
499 (defvar js2-DELPROP 31)
500 (defvar js2-TYPEOF 32)
501 (defvar js2-GETPROP 33)
502 (defvar js2-GETPROPNOWARN 34)
503 (defvar js2-SETPROP 35)
504 (defvar js2-GETELEM 36)
505 (defvar js2-SETELEM 37)
506 (defvar js2-CALL 38)
507 (defvar js2-NAME 39) ; an identifier
508 (defvar js2-NUMBER 40)
509 (defvar js2-STRING 41)
510 (defvar js2-NULL 42)
511 (defvar js2-THIS 43)
512 (defvar js2-FALSE 44)
513 (defvar js2-TRUE 45)
514 (defvar js2-SHEQ 46) ; shallow equality (===)
515 (defvar js2-SHNE 47) ; shallow inequality (!==)
516 (defvar js2-REGEXP 48)
517 (defvar js2-BINDNAME 49)
518 (defvar js2-THROW 50)
519 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
520 (defvar js2-IN 52)
521 (defvar js2-INSTANCEOF 53)
522 (defvar js2-LOCAL_LOAD 54)
523 (defvar js2-GETVAR 55)
524 (defvar js2-SETVAR 56)
525 (defvar js2-CATCH_SCOPE 57)
526 (defvar js2-ENUM_INIT_KEYS 58)
527 (defvar js2-ENUM_INIT_VALUES 59)
528 (defvar js2-ENUM_INIT_ARRAY 60)
529 (defvar js2-ENUM_NEXT 61)
530 (defvar js2-ENUM_ID 62)
531 (defvar js2-THISFN 63)
532 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
533 (defvar js2-ARRAYLIT 65) ; array literal
534 (defvar js2-OBJECTLIT 66) ; object literal
535 (defvar js2-GET_REF 67) ; *reference
536 (defvar js2-SET_REF 68) ; *reference = something
537 (defvar js2-DEL_REF 69) ; delete reference
538 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
539 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
540 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
541
542 ;; XML support
543 (defvar js2-DEFAULTNAMESPACE 73)
544 (defvar js2-ESCXMLATTR 74)
545 (defvar js2-ESCXMLTEXT 75)
546 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
547 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
548 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
549 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
550
551 (defvar js2-first-bytecode js2-ENTERWITH)
552 (defvar js2-last-bytecode js2-REF_NS_NAME)
553
554 (defvar js2-TRY 80)
555 (defvar js2-SEMI 81) ; semicolon
556 (defvar js2-LB 82) ; left and right brackets
557 (defvar js2-RB 83)
558 (defvar js2-LC 84) ; left and right curly-braces
559 (defvar js2-RC 85)
560 (defvar js2-LP 86) ; left and right parens
561 (defvar js2-RP 87)
562 (defvar js2-COMMA 88) ; comma operator
563
564 (defvar js2-ASSIGN 89) ; simple assignment (=)
565 (defvar js2-ASSIGN_BITOR 90) ; |=
566 (defvar js2-ASSIGN_BITXOR 91) ; ^=
567 (defvar js2-ASSIGN_BITAND 92) ; &=
568 (defvar js2-ASSIGN_LSH 93) ; <<=
569 (defvar js2-ASSIGN_RSH 94) ; >>=
570 (defvar js2-ASSIGN_URSH 95) ; >>>=
571 (defvar js2-ASSIGN_ADD 96) ; +=
572 (defvar js2-ASSIGN_SUB 97) ; -=
573 (defvar js2-ASSIGN_MUL 98) ; *=
574 (defvar js2-ASSIGN_DIV 99) ; /=
575 (defvar js2-ASSIGN_MOD 100) ; %=
576
577 (defvar js2-first-assign js2-ASSIGN)
578 (defvar js2-last-assign js2-ASSIGN_MOD)
579
580 (defvar js2-HOOK 101) ; conditional (?:)
581 (defvar js2-COLON 102)
582 (defvar js2-OR 103) ; logical or (||)
583 (defvar js2-AND 104) ; logical and (&&)
584 (defvar js2-INC 105) ; increment/decrement (++ --)
585 (defvar js2-DEC 106)
586 (defvar js2-DOT 107) ; member operator (.)
587 (defvar js2-FUNCTION 108) ; function keyword
588 (defvar js2-EXPORT 109) ; export keyword
589 (defvar js2-IMPORT 110) ; import keyword
590 (defvar js2-IF 111) ; if keyword
591 (defvar js2-ELSE 112) ; else keyword
592 (defvar js2-SWITCH 113) ; switch keyword
593 (defvar js2-CASE 114) ; case keyword
594 (defvar js2-DEFAULT 115) ; default keyword
595 (defvar js2-WHILE 116) ; while keyword
596 (defvar js2-DO 117) ; do keyword
597 (defvar js2-FOR 118) ; for keyword
598 (defvar js2-BREAK 119) ; break keyword
599 (defvar js2-CONTINUE 120) ; continue keyword
600 (defvar js2-VAR 121) ; var keyword
601 (defvar js2-WITH 122) ; with keyword
602 (defvar js2-CATCH 123) ; catch keyword
603 (defvar js2-FINALLY 124) ; finally keyword
604 (defvar js2-VOID 125) ; void keyword
605 (defvar js2-RESERVED 126) ; reserved keywords
606
607 (defvar js2-EMPTY 127)
608
609 ;; Types used for the parse tree - never returned by scanner.
610
611 (defvar js2-BLOCK 128) ; statement block
612 (defvar js2-LABEL 129) ; label
613 (defvar js2-TARGET 130)
614 (defvar js2-LOOP 131)
615 (defvar js2-EXPR_VOID 132) ; expression statement in functions
616 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
617 (defvar js2-JSR 134)
618 (defvar js2-SCRIPT 135) ; top-level node for entire script
619 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
620 (defvar js2-USE_STACK 137)
621 (defvar js2-SETPROP_OP 138) ; x.y op= something
622 (defvar js2-SETELEM_OP 139) ; x[y] op= something
623 (defvar js2-LOCAL_BLOCK 140)
624 (defvar js2-SET_REF_OP 141) ; *reference op= something
625
626 ;; For XML support:
627 (defvar js2-DOTDOT 142) ; member operator (..)
628 (defvar js2-COLONCOLON 143) ; namespace::name
629 (defvar js2-XML 144) ; XML type
630 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
631 (defvar js2-XMLATTR 146) ; @
632 (defvar js2-XMLEND 147)
633
634 ;; Optimizer-only tokens
635 (defvar js2-TO_OBJECT 148)
636 (defvar js2-TO_DOUBLE 149)
637
638 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
639 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
640 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
641 (defvar js2-CONST 153)
642 (defvar js2-SETCONST 154)
643 (defvar js2-SETCONSTVAR 155)
644 (defvar js2-ARRAYCOMP 156)
645 (defvar js2-LETEXPR 157)
646 (defvar js2-WITHEXPR 158)
647 (defvar js2-DEBUGGER 159)
648
649 (defvar js2-COMMENT 160)
650 (defvar js2-ENUM 161) ; for "enum" reserved word
651
652 (defconst js2-num-tokens (1+ js2-ENUM))
653
654 (defconst js2-debug-print-trees nil)
655
656 ;; Rhino accepts any string or stream as input. Emacs character
657 ;; processing works best in buffers, so we'll assume the input is a
658 ;; buffer. JavaScript strings can be copied into temp buffers before
659 ;; scanning them.
660
661 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
662 ;; They're the Emacs equivalent of instance variables, more or less.
663
664 (js2-deflocal js2-ts-dirty-line nil
665 "Token stream buffer-local variable.
666 Indicates stuff other than whitespace since start of line.")
667
668 (js2-deflocal js2-ts-regexp-flags nil
669 "Token stream buffer-local variable.")
670
671 (js2-deflocal js2-ts-string ""
672 "Token stream buffer-local variable.
673 Last string scanned.")
674
675 (js2-deflocal js2-ts-number nil
676 "Token stream buffer-local variable.
677 Last literal number scanned.")
678
679 (js2-deflocal js2-ts-hit-eof nil
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-line-start 0
683 "Token stream buffer-local variable.")
684
685 (js2-deflocal js2-ts-lineno 1
686 "Token stream buffer-local variable.")
687
688 (js2-deflocal js2-ts-line-end-char -1
689 "Token stream buffer-local variable.")
690
691 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
692 "Token stream buffer-local variable.
693 Current scan position.")
694
695 (js2-deflocal js2-ts-is-xml-attribute nil
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-xml-is-tag-content nil
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-xml-open-tags-count 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-string-buffer nil
705 "Token stream buffer-local variable.
706 List of chars built up while scanning various tokens.")
707
708 (js2-deflocal js2-ts-comment-type nil
709 "Token stream buffer-local variable.")
710
711 ;;; Parser variables
712
713 (js2-deflocal js2-parsed-errors nil
714 "List of errors produced during scanning/parsing.")
715
716 (js2-deflocal js2-parsed-warnings nil
717 "List of warnings produced during scanning/parsing.")
718
719 (js2-deflocal js2-recover-from-parse-errors t
720 "Non-nil to continue parsing after a syntax error.
721
722 In recovery mode, the AST will be built in full, and any error
723 nodes will be flagged with appropriate error information. If
724 this flag is nil, a syntax error will result in an error being
725 signaled.
726
727 The variable is automatically buffer-local, because different
728 modes that use the parser will need different settings.")
729
730 (js2-deflocal js2-parse-hook nil
731 "List of callbacks for receiving parsing progress.")
732
733 (defvar js2-parse-finished-hook nil
734 "List of callbacks to notify when parsing finishes.
735 Not called if parsing was interrupted.")
736
737 (js2-deflocal js2-is-eval-code nil
738 "True if we're evaluating code in a string.
739 If non-nil, the tokenizer will record the token text, and the AST nodes
740 will record their source text. Off by default for IDE modes, since the
741 text is available in the buffer.")
742
743 (defvar js2-parse-ide-mode t
744 "Non-nil if the parser is being used for `js2-mode'.
745 If non-nil, the parser will set text properties for fontification
746 and the syntax table. The value should be nil when using the
747 parser as a frontend to an interpreter or byte compiler.")
748
749 ;;; Parser instance variables (buffer-local vars for js2-parse)
750
751 (defconst js2-clear-ti-mask #xFFFF
752 "Mask to clear token information bits.")
753
754 (defconst js2-ti-after-eol (lsh 1 16)
755 "Flag: first token of the source line.")
756
757 (defconst js2-ti-check-label (lsh 1 17)
758 "Flag: indicates to check for label.")
759
760 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
761
762 (js2-deflocal js2-compiler-generate-debug-info t)
763 (js2-deflocal js2-compiler-use-dynamic-scope nil)
764 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
765 (js2-deflocal js2-compiler-xml-available t)
766 (js2-deflocal js2-compiler-optimization-level 0)
767 (js2-deflocal js2-compiler-generating-source t)
768 (js2-deflocal js2-compiler-strict-mode nil)
769 (js2-deflocal js2-compiler-report-warning-as-error nil)
770 (js2-deflocal js2-compiler-generate-observer-count nil)
771 (js2-deflocal js2-compiler-activation-names nil)
772
773 ;; SKIP: sourceURI
774
775 ;; There's a compileFunction method in Context.java - may need it.
776 (js2-deflocal js2-called-by-compile-function nil
777 "True if `js2-parse' was called by `js2-compile-function'.
778 Will only be used when we finish implementing the interpreter.")
779
780 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
781
782 (js2-deflocal js2-current-flagged-token js2-EOF)
783 (js2-deflocal js2-current-token js2-EOF)
784
785 ;; SKIP: node factory - we're going to just call functions directly,
786 ;; and eventually go to a unified AST format.
787
788 (js2-deflocal js2-nesting-of-function 0)
789
790 (js2-deflocal js2-recorded-assignments nil
791 "Tracks assignments found during parsing.")
792
793 (defcustom js2-global-externs nil
794 "A list of any extern names you'd like to consider always declared.
795 This list is global and is used by all js2-mode files.
796 You can create buffer-local externs list using `js2-additional-externs'.
797
798 There is also a buffer-local variable `js2-default-externs',
799 which is initialized by default to include the Ecma-262 externs
800 and the standard browser externs. The three lists are all
801 checked during highlighting."
802 :type 'list
803 :group 'js2-mode)
804
805 (js2-deflocal js2-default-externs nil
806 "Default external declarations.
807
808 These are currently only used for highlighting undeclared variables,
809 which only worries about top-level (unqualified) references.
810 As js2-mode's processing improves, we will flesh out this list.
811
812 The initial value is set to `js2-ecma-262-externs', unless you
813 have set `js2-include-browser-externs', in which case the browser
814 externs are also included.
815
816 See `js2-additional-externs' for more information.")
817
818 (defcustom js2-include-browser-externs t
819 "Non-nil to include browser externs in the master externs list.
820 If you work on JavaScript files that are not intended for browsers,
821 such as Mozilla Rhino server-side JavaScript, set this to nil.
822 You can always include them on a per-file basis by calling
823 `js2-add-browser-externs' from a function on `js2-mode-hook'.
824
825 See `js2-additional-externs' for more information about externs."
826 :type 'boolean
827 :group 'js2-mode)
828
829 (defcustom js2-include-rhino-externs t
830 "Non-nil to include Mozilla Rhino externs in the master externs list.
831 See `js2-additional-externs' for more information about externs."
832 :type 'boolean
833 :group 'js2-mode)
834
835 (defcustom js2-include-gears-externs t
836 "Non-nil to include Google Gears externs in the master externs list.
837 See `js2-additional-externs' for more information about externs."
838 :type 'boolean
839 :group 'js2-mode)
840
841 (js2-deflocal js2-additional-externs nil
842 "A buffer-local list of additional external declarations.
843 It is used to decide whether variables are considered undeclared
844 for purposes of highlighting.
845
846 Each entry is a lisp string. The string should be the fully qualified
847 name of an external entity. All externs should be added to this list,
848 so that as js2-mode's processing improves it can take advantage of them.
849
850 You may want to declare your externs in three ways.
851 First, you can add externs that are valid for all your JavaScript files.
852 You should probably do this by adding them to `js2-global-externs', which
853 is a global list used for all js2-mode files.
854
855 Next, you can add a function to `js2-mode-hook' that adds additional
856 externs appropriate for the specific file, perhaps based on its path.
857 These should go in `js2-additional-externs', which is buffer-local.
858
859 Finally, you can add a function to `js2-post-parse-callbacks',
860 which is called after parsing completes, and `root' is bound to
861 the root of the parse tree. At this stage you can set up an AST
862 node visitor using `js2-visit-ast' and examine the parse tree
863 for specific import patterns that may imply the existence of
864 other externs, possibly tied to your build system. These should also
865 be added to `js2-additional-externs'.
866
867 Your post-parse callback may of course also use the simpler and
868 faster (but perhaps less robust) approach of simply scanning the
869 buffer text for your imports, using regular expressions.")
870
871 ;; SKIP: decompiler
872 ;; SKIP: encoded-source
873
874 ;;; The following variables are per-function and should be saved/restored
875 ;;; during function parsing...
876
877 (js2-deflocal js2-current-script-or-fn nil)
878 (js2-deflocal js2-current-scope nil)
879 (js2-deflocal js2-nesting-of-with 0)
880 (js2-deflocal js2-label-set nil
881 "An alist mapping label names to nodes.")
882
883 (js2-deflocal js2-loop-set nil)
884 (js2-deflocal js2-loop-and-switch-set nil)
885 (js2-deflocal js2-has-return-value nil)
886 (js2-deflocal js2-end-flags 0)
887
888 ;;; ...end of per function variables
889
890 ;; Without 2-token lookahead, labels are a problem.
891 ;; These vars store the token info of the last matched name,
892 ;; iff it wasn't the last matched token. Only valid in some contexts.
893 (defvar js2-prev-name-token-start nil)
894 (defvar js2-prev-name-token-string nil)
895
896 (defsubst js2-save-name-token-data (pos name)
897 (setq js2-prev-name-token-start pos
898 js2-prev-name-token-string name))
899
900 ;; These flags enumerate the possible ways a statement/function can
901 ;; terminate. These flags are used by endCheck() and by the Parser to
902 ;; detect inconsistent return usage.
903 ;;
904 ;; END_UNREACHED is reserved for code paths that are assumed to always be
905 ;; able to execute (example: throw, continue)
906 ;;
907 ;; END_DROPS_OFF indicates if the statement can transfer control to the
908 ;; next one. Statement such as return dont. A compound statement may have
909 ;; some branch that drops off control to the next statement.
910 ;;
911 ;; END_RETURNS indicates that the statement can return (without arguments)
912 ;; END_RETURNS_VALUE indicates that the statement can return a value.
913 ;;
914 ;; A compound statement such as
915 ;; if (condition) {
916 ;; return value;
917 ;; }
918 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
919
920 (defconst js2-end-unreached #x0)
921 (defconst js2-end-drops-off #x1)
922 (defconst js2-end-returns #x2)
923 (defconst js2-end-returns-value #x4)
924 (defconst js2-end-yields #x8)
925
926 ;; Rhino awkwardly passes a statementLabel parameter to the
927 ;; statementHelper() function, the main statement parser, which
928 ;; is then used by quite a few of the sub-parsers. We just make
929 ;; it a buffer-local variable and make sure it's cleaned up properly.
930 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
931
932 ;; Similarly, Rhino passes an inForInit boolean through about half
933 ;; the expression parsers. We use a dynamically-scoped variable,
934 ;; which makes it easier to funcall the parsers individually without
935 ;; worrying about whether they take the parameter or not.
936 (js2-deflocal js2-in-for-init nil)
937 (js2-deflocal js2-temp-name-counter 0)
938 (js2-deflocal js2-parse-stmt-count 0)
939
940 (defsubst js2-get-next-temp-name ()
941 (format "$%d" (incf js2-temp-name-counter)))
942
943 (defvar js2-parse-interruptable-p t
944 "Set this to nil to force parse to continue until finished.
945 This will mostly be useful for interpreters.")
946
947 (defvar js2-statements-per-pause 50
948 "Pause after this many statements to check for user input.
949 If user input is pending, stop the parse and discard the tree.
950 This makes for a smoother user experience for large files.
951 You may have to wait a second or two before the highlighting
952 and error-reporting appear, but you can always type ahead if
953 you wish. This appears to be more or less how Eclipse, IntelliJ
954 and other editors work.")
955
956 (js2-deflocal js2-record-comments t
957 "Instructs the scanner to record comments in `js2-scanned-comments'.")
958
959 (js2-deflocal js2-scanned-comments nil
960 "List of all comments from the current parse.")
961
962 (defcustom js2-mode-indent-inhibit-undo nil
963 "Non-nil to disable collection of Undo information when indenting lines.
964 Some users have requested this behavior. It's nil by default because
965 other Emacs modes don't work this way."
966 :type 'boolean
967 :group 'js2-mode)
968
969 (defcustom js2-mode-indent-ignore-first-tab nil
970 "If non-nil, ignore first TAB keypress if we look indented properly.
971 It's fairly common for users to navigate to an already-indented line
972 and press TAB for reassurance that it's been indented. For this class
973 of users, we want the first TAB press on a line to be ignored if the
974 line is already indented to one of the precomputed alternatives.
975
976 This behavior is only partly implemented. If you TAB-indent a line,
977 navigate to another line, and then navigate back, it fails to clear
978 the last-indented variable, so it thinks you've already hit TAB once,
979 and performs the indent. A full solution would involve getting on the
980 point-motion hooks for the entire buffer. If we come across another
981 use cases that requires watching point motion, I'll consider doing it.
982
983 If you set this variable to nil, then the TAB key will always change
984 the indentation of the current line, if more than one alternative
985 indentation spot exists."
986 :type 'boolean
987 :group 'js2-mode)
988
989 (defvar js2-indent-hook nil
990 "A hook for user-defined indentation rules.
991
992 Functions on this hook should expect two arguments: (LIST INDEX)
993 The LIST argument is the list of computed indentation points for
994 the current line. INDEX is the list index of the indentation point
995 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
996 indent function is not going to change the current line indentation.
997
998 If a hook function on this list returns a non-nil value, then
999 `js2-bounce-indent' assumes the hook function has performed its own
1000 indentation, and will do nothing. If all hook functions on the list
1001 return nil, then `js2-bounce-indent' will use its computed indentation
1002 and reindent the line.
1003
1004 When hook functions on this hook list are called, the variable
1005 `js2-mode-ast' may or may not be set, depending on whether the
1006 parse tree is available. If the variable is nil, you can pass a
1007 callback to `js2-mode-wait-for-parse', and your callback will be
1008 called after the new parse tree is built. This can take some time
1009 in large files.")
1010
1011 (defface js2-warning-face
1012 `((((class color) (background light))
1013 (:underline "orange"))
1014 (((class color) (background dark))
1015 (:underline "orange"))
1016 (t (:underline t)))
1017 "Face for JavaScript warnings."
1018 :group 'js2-mode)
1019
1020 (defface js2-error-face
1021 `((((class color) (background light))
1022 (:foreground "red"))
1023 (((class color) (background dark))
1024 (:foreground "red"))
1025 (t (:foreground "red")))
1026 "Face for JavaScript errors."
1027 :group 'js2-mode)
1028
1029 (defface js2-jsdoc-tag-face
1030 '((t :foreground "SlateGray"))
1031 "Face used to highlight @whatever tags in jsdoc comments."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-type-face
1035 '((t :foreground "SteelBlue"))
1036 "Face used to highlight {FooBar} types in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-value-face
1040 '((t :foreground "PeachPuff3"))
1041 "Face used to highlight tag values in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-function-param-face
1045 '((t :foreground "SeaGreen"))
1046 "Face used to highlight function parameters in javascript."
1047 :group 'js2-mode)
1048
1049 (defface js2-instance-member-face
1050 '((t :foreground "DarkOrchid"))
1051 "Face used to highlight instance variables in javascript.
1052 Not currently used."
1053 :group 'js2-mode)
1054
1055 (defface js2-private-member-face
1056 '((t :foreground "PeachPuff3"))
1057 "Face used to highlight calls to private methods in javascript.
1058 Not currently used."
1059 :group 'js2-mode)
1060
1061 (defface js2-private-function-call-face
1062 '((t :foreground "goldenrod"))
1063 "Face used to highlight calls to private functions in javascript.
1064 Not currently used."
1065 :group 'js2-mode)
1066
1067 (defface js2-jsdoc-html-tag-name-face
1068 (if js2-emacs22
1069 '((((class color) (min-colors 88) (background light))
1070 (:foreground "rosybrown"))
1071 (((class color) (min-colors 8) (background dark))
1072 (:foreground "yellow"))
1073 (((class color) (min-colors 8) (background light))
1074 (:foreground "magenta")))
1075 '((((type tty pc) (class color) (background light))
1076 (:foreground "magenta"))
1077 (((type tty pc) (class color) (background dark))
1078 (:foreground "yellow"))
1079 (t (:foreground "RosyBrown"))))
1080 "Face used to highlight jsdoc html tag names"
1081 :group 'js2-mode)
1082
1083 (defface js2-jsdoc-html-tag-delimiter-face
1084 (if js2-emacs22
1085 '((((class color) (min-colors 88) (background light))
1086 (:foreground "dark khaki"))
1087 (((class color) (min-colors 8) (background dark))
1088 (:foreground "green"))
1089 (((class color) (min-colors 8) (background light))
1090 (:foreground "green")))
1091 '((((type tty pc) (class color) (background light))
1092 (:foreground "green"))
1093 (((type tty pc) (class color) (background dark))
1094 (:foreground "green"))
1095 (t (:foreground "dark khaki"))))
1096 "Face used to highlight brackets in jsdoc html tags."
1097 :group 'js2-mode)
1098
1099 (defface js2-magic-paren-face
1100 '((t :underline t))
1101 "Face used to color parens that will be auto-overwritten."
1102 :group 'js2-mode)
1103
1104 (defcustom js2-post-parse-callbacks nil
1105 "A list of callback functions invoked after parsing finishes.
1106 Currently, the main use for this function is to add synthetic
1107 declarations to `js2-recorded-assignments', which see."
1108 :type 'list
1109 :group 'js2-mode)
1110
1111 (defface js2-external-variable-face
1112 '((t :foreground "orange"))
1113 "Face used to highlight assignments to undeclared variables.
1114 An undeclared variable is any variable not declared with var or let
1115 in the current scope or any lexically enclosing scope. If you assign
1116 to such a variable, then you are either expecting it to originate from
1117 another file, or you've got a potential bug."
1118 :group 'js2-mode)
1119
1120 (defcustom js2-highlight-external-variables t
1121 "Non-nil to higlight assignments to undeclared variables."
1122 :type 'boolean
1123 :group 'js2-mode)
1124
1125 (defcustom js2-auto-insert-catch-block t
1126 "Non-nil to insert matching catch block on open-curly after `try'."
1127 :type 'boolean
1128 :group 'js2-mode)
1129
1130 (defvar js2-mode-map
1131 (let ((map (make-sparse-keymap))
1132 keys)
1133 (define-key map [mouse-1] #'js2-mode-show-node)
1134 (define-key map (kbd "C-m") #'js2-enter-key)
1135 (when js2-rebind-eol-bol-keys
1136 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1137 (define-key map (kbd "C-e") #'js2-end-of-line))
1138 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1139 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1140 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1141 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1142 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1143 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1144 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1145 (define-key map (kbd "C-c C-`") #'js2-next-error)
1146 ;; also define user's preference for next-error, if available
1147 (if (setq keys (where-is-internal #'next-error))
1148 (define-key map (car keys) #'js2-next-error))
1149 (define-key map (or (car (where-is-internal #'mark-defun))
1150 (kbd "M-C-h"))
1151 #'js2-mark-defun)
1152 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1153 (kbd "C-x nd"))
1154 #'js2-narrow-to-defun)
1155 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1156 (when js2-auto-indent-p
1157 (mapc (lambda (key)
1158 (define-key map key #'js2-insert-and-indent))
1159 js2-electric-keys))
1160
1161 (define-key map [menu-bar javascript]
1162 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1163
1164 (define-key map [menu-bar javascript customize-js2-mode]
1165 '(menu-item "Customize js2-mode" js2-mode-customize
1166 :help "Customize the behavior of this mode"))
1167
1168 (define-key map [menu-bar javascript js2-force-refresh]
1169 '(menu-item "Force buffer refresh" js2-mode-reset
1170 :help "Re-parse the buffer from scratch"))
1171
1172 (define-key map [menu-bar javascript separator-2]
1173 '("--"))
1174
1175 (define-key map [menu-bar javascript next-error]
1176 '(menu-item "Next warning or error" js2-next-error
1177 :enabled (and js2-mode-ast
1178 (or (js2-ast-root-errors js2-mode-ast)
1179 (js2-ast-root-warnings js2-mode-ast)))
1180 :help "Move to next warning or error"))
1181
1182 (define-key map [menu-bar javascript display-errors]
1183 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1184 :visible (not js2-mode-show-parse-errors)
1185 :help "Turn on display of warnings and errors"))
1186
1187 (define-key map [menu-bar javascript hide-errors]
1188 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1189 :visible js2-mode-show-parse-errors
1190 :help "Turn off display of warnings and errors"))
1191
1192 (define-key map [menu-bar javascript separator-1]
1193 '("--"))
1194
1195 (define-key map [menu-bar javascript js2-toggle-function]
1196 '(menu-item "Show/collapse element" js2-mode-toggle-element
1197 :help "Hide or show function body or comment"))
1198
1199 (define-key map [menu-bar javascript show-comments]
1200 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1201 :visible js2-mode-comments-hidden
1202 :help "Expand all hidden block comments"))
1203
1204 (define-key map [menu-bar javascript hide-comments]
1205 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1206 :visible (not js2-mode-comments-hidden)
1207 :help "Show block comments as /*...*/"))
1208
1209 (define-key map [menu-bar javascript show-all-functions]
1210 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1211 :visible js2-mode-functions-hidden
1212 :help "Expand all hidden function bodies"))
1213
1214 (define-key map [menu-bar javascript hide-all-functions]
1215 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1216 :visible (not js2-mode-functions-hidden)
1217 :help "Show {...} for all top-level function bodies"))
1218
1219 map)
1220 "Keymap used in `js2-mode' buffers.")
1221
1222 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1223
1224 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1225 "Matches a //-comment line. Must be first non-whitespace on line.
1226 First match-group is the leading whitespace.")
1227
1228 (defvar js2-mode-hook nil)
1229
1230 (js2-deflocal js2-mode-ast nil "Private variable.")
1231 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1232 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1233 (js2-deflocal js2-mode-parsing nil "Private variable.")
1234 (js2-deflocal js2-mode-node-overlay nil)
1235
1236 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1237 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1238
1239 (js2-deflocal js2-mode-fontifications nil "Private variable")
1240 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1241 (js2-deflocal js2-imenu-recorder nil "Private variable")
1242 (js2-deflocal js2-imenu-function-map nil "Private variable")
1243
1244 (defvar js2-paragraph-start
1245 "\\(@[a-zA-Z]+\\>\\|$\\)")
1246
1247 ;; Note that we also set a 'c-in-sws text property in html comments,
1248 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1249 (defvar js2-syntactic-ws-start
1250 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1251
1252 (defvar js2-syntactic-ws-end
1253 "\\s \\|[\n\r/]\\|\\s!")
1254
1255 (defvar js2-syntactic-eol
1256 (concat "\\s *\\(/\\*[^*\n\r]*"
1257 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1258 "\\*+/\\s *\\)*"
1259 "\\(//\\|/\\*[^*\n\r]*"
1260 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1261 "\\|\\\\$\\|$\\)")
1262 "Copied from `java-mode'. Needed for some cc-engine functions.")
1263
1264 (defvar js2-comment-prefix-regexp
1265 "//+\\|\\**")
1266
1267 (defvar js2-comment-start-skip
1268 "\\(//+\\|/\\*+\\)\\s *")
1269
1270 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1271 "Non-nil to emit status messages during parsing.")
1272
1273 (defvar js2-mode-functions-hidden nil "private variable")
1274 (defvar js2-mode-comments-hidden nil "private variable")
1275
1276 (defvar js2-mode-syntax-table
1277 (let ((table (make-syntax-table)))
1278 (c-populate-syntax-table table)
1279 table)
1280 "Syntax table used in js2-mode buffers.")
1281
1282 (defvar js2-mode-abbrev-table nil
1283 "Abbrev table in use in `js2-mode' buffers.")
1284 (define-abbrev-table 'js2-mode-abbrev-table ())
1285
1286 (defvar js2-mode-pending-parse-callbacks nil
1287 "List of functions waiting to be notified that parse is finished.")
1288
1289 (defvar js2-mode-last-indented-line -1)
1290
1291 ;;; Localizable error and warning messages
1292
1293 ;; Messages are copied from Rhino's Messages.properties.
1294 ;; Many of the Java-specific messages have been elided.
1295 ;; Add any js2-specific ones at the end, so we can keep
1296 ;; this file synced with changes to Rhino's.
1297
1298 (defvar js2-message-table
1299 (make-hash-table :test 'equal :size 250)
1300 "Contains localized messages for js2-mode.")
1301
1302 ;; TODO(stevey): construct this table at compile-time.
1303 (defmacro js2-msg (key &rest strings)
1304 `(puthash ,key (funcall #'concat ,@strings)
1305 js2-message-table))
1306
1307 (defun js2-get-msg (msg-key)
1308 "Look up a localized message.
1309 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1310 the correct number of ARGS must be provided."
1311 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1312 (args (if (listp msg-key) (cdr msg-key)))
1313 (msg (gethash key js2-message-table)))
1314 (if msg
1315 (apply #'format msg args)
1316 key))) ; default to showing the key
1317
1318 (js2-msg "msg.dup.parms"
1319 "Duplicate parameter name '%s'.")
1320
1321 (js2-msg "msg.too.big.jump"
1322 "Program too complex: jump offset too big.")
1323
1324 (js2-msg "msg.too.big.index"
1325 "Program too complex: internal index exceeds 64K limit.")
1326
1327 (js2-msg "msg.while.compiling.fn"
1328 "Encountered code generation error while compiling function '%s': %s")
1329
1330 (js2-msg "msg.while.compiling.script"
1331 "Encountered code generation error while compiling script: %s")
1332
1333 ;; Context
1334 (js2-msg "msg.ctor.not.found"
1335 "Constructor for '%s' not found.")
1336
1337 (js2-msg "msg.not.ctor"
1338 "'%s' is not a constructor.")
1339
1340 ;; FunctionObject
1341 (js2-msg "msg.varargs.ctor"
1342 "Method or constructor '%s' must be static "
1343 "with the signature (Context cx, Object[] args, "
1344 "Function ctorObj, boolean inNewExpr) "
1345 "to define a variable arguments constructor.")
1346
1347 (js2-msg "msg.varargs.fun"
1348 "Method '%s' must be static with the signature "
1349 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1350 "to define a variable arguments function.")
1351
1352 (js2-msg "msg.incompat.call"
1353 "Method '%s' called on incompatible object.")
1354
1355 (js2-msg "msg.bad.parms"
1356 "Unsupported parameter type '%s' in method '%s'.")
1357
1358 (js2-msg "msg.bad.method.return"
1359 "Unsupported return type '%s' in method '%s'.")
1360
1361 (js2-msg "msg.bad.ctor.return"
1362 "Construction of objects of type '%s' is not supported.")
1363
1364 (js2-msg "msg.no.overload"
1365 "Method '%s' occurs multiple times in class '%s'.")
1366
1367 (js2-msg "msg.method.not.found"
1368 "Method '%s' not found in '%s'.")
1369
1370 ;; IRFactory
1371
1372 (js2-msg "msg.bad.for.in.lhs"
1373 "Invalid left-hand side of for..in loop.")
1374
1375 (js2-msg "msg.mult.index"
1376 "Only one variable allowed in for..in loop.")
1377
1378 (js2-msg "msg.bad.for.in.destruct"
1379 "Left hand side of for..in loop must be an array of "
1380 "length 2 to accept key/value pair.")
1381
1382 (js2-msg "msg.cant.convert"
1383 "Can't convert to type '%s'.")
1384
1385 (js2-msg "msg.bad.assign.left"
1386 "Invalid assignment left-hand side.")
1387
1388 (js2-msg "msg.bad.decr"
1389 "Invalid decerement operand.")
1390
1391 (js2-msg "msg.bad.incr"
1392 "Invalid increment operand.")
1393
1394 (js2-msg "msg.bad.yield"
1395 "yield must be in a function.")
1396
1397 (js2-msg "msg.yield.parenthesized"
1398 "yield expression must be parenthesized.")
1399
1400 ;; NativeGlobal
1401 (js2-msg "msg.cant.call.indirect"
1402 "Function '%s' must be called directly, and not by way of a "
1403 "function of another name.")
1404
1405 (js2-msg "msg.eval.nonstring"
1406 "Calling eval() with anything other than a primitive "
1407 "string value will simply return the value. "
1408 "Is this what you intended?")
1409
1410 (js2-msg "msg.eval.nonstring.strict"
1411 "Calling eval() with anything other than a primitive "
1412 "string value is not allowed in strict mode.")
1413
1414 (js2-msg "msg.bad.destruct.op"
1415 "Invalid destructuring assignment operator")
1416
1417 ;; NativeCall
1418 (js2-msg "msg.only.from.new"
1419 "'%s' may only be invoked from a `new' expression.")
1420
1421 (js2-msg "msg.deprec.ctor"
1422 "The '%s' constructor is deprecated.")
1423
1424 ;; NativeFunction
1425 (js2-msg "msg.no.function.ref.found"
1426 "no source found to decompile function reference %s")
1427
1428 (js2-msg "msg.arg.isnt.array"
1429 "second argument to Function.prototype.apply must be an array")
1430
1431 ;; NativeGlobal
1432 (js2-msg "msg.bad.esc.mask"
1433 "invalid string escape mask")
1434
1435 ;; NativeRegExp
1436 (js2-msg "msg.bad.quant"
1437 "Invalid quantifier %s")
1438
1439 (js2-msg "msg.overlarge.backref"
1440 "Overly large back reference %s")
1441
1442 (js2-msg "msg.overlarge.min"
1443 "Overly large minimum %s")
1444
1445 (js2-msg "msg.overlarge.max"
1446 "Overly large maximum %s")
1447
1448 (js2-msg "msg.zero.quant"
1449 "Zero quantifier %s")
1450
1451 (js2-msg "msg.max.lt.min"
1452 "Maximum %s less than minimum")
1453
1454 (js2-msg "msg.unterm.quant"
1455 "Unterminated quantifier %s")
1456
1457 (js2-msg "msg.unterm.paren"
1458 "Unterminated parenthetical %s")
1459
1460 (js2-msg "msg.unterm.class"
1461 "Unterminated character class %s")
1462
1463 (js2-msg "msg.bad.range"
1464 "Invalid range in character class.")
1465
1466 (js2-msg "msg.trail.backslash"
1467 "Trailing \\ in regular expression.")
1468
1469 (js2-msg "msg.re.unmatched.right.paren"
1470 "unmatched ) in regular expression.")
1471
1472 (js2-msg "msg.no.regexp"
1473 "Regular expressions are not available.")
1474
1475 (js2-msg "msg.bad.backref"
1476 "back-reference exceeds number of capturing parentheses.")
1477
1478 (js2-msg "msg.bad.regexp.compile"
1479 "Only one argument may be specified if the first "
1480 "argument to RegExp.prototype.compile is a RegExp object.")
1481
1482 ;; Parser
1483 (js2-msg "msg.got.syntax.errors"
1484 "Compilation produced %s syntax errors.")
1485
1486 (js2-msg "msg.var.redecl"
1487 "TypeError: redeclaration of var %s.")
1488
1489 (js2-msg "msg.const.redecl"
1490 "TypeError: redeclaration of const %s.")
1491
1492 (js2-msg "msg.let.redecl"
1493 "TypeError: redeclaration of variable %s.")
1494
1495 (js2-msg "msg.parm.redecl"
1496 "TypeError: redeclaration of formal parameter %s.")
1497
1498 (js2-msg "msg.fn.redecl"
1499 "TypeError: redeclaration of function %s.")
1500
1501 (js2-msg "msg.let.decl.not.in.block"
1502 "SyntaxError: let declaration not directly within block")
1503
1504 ;; NodeTransformer
1505 (js2-msg "msg.dup.label"
1506 "duplicated label")
1507
1508 (js2-msg "msg.undef.label"
1509 "undefined label")
1510
1511 (js2-msg "msg.bad.break"
1512 "unlabelled break must be inside loop or switch")
1513
1514 (js2-msg "msg.continue.outside"
1515 "continue must be inside loop")
1516
1517 (js2-msg "msg.continue.nonloop"
1518 "continue can only use labels of iteration statements")
1519
1520 (js2-msg "msg.bad.throw.eol"
1521 "Line terminator is not allowed between the throw "
1522 "keyword and throw expression.")
1523
1524 (js2-msg "msg.no.paren.parms"
1525 "missing ( before function parameters.")
1526
1527 (js2-msg "msg.no.parm"
1528 "missing formal parameter")
1529
1530 (js2-msg "msg.no.paren.after.parms"
1531 "missing ) after formal parameters")
1532
1533 (js2-msg "msg.no.brace.body"
1534 "missing '{' before function body")
1535
1536 (js2-msg "msg.no.brace.after.body"
1537 "missing } after function body")
1538
1539 (js2-msg "msg.no.paren.cond"
1540 "missing ( before condition")
1541
1542 (js2-msg "msg.no.paren.after.cond"
1543 "missing ) after condition")
1544
1545 (js2-msg "msg.no.semi.stmt"
1546 "missing ; before statement")
1547
1548 (js2-msg "msg.missing.semi"
1549 "missing ; after statement")
1550
1551 (js2-msg "msg.no.name.after.dot"
1552 "missing name after . operator")
1553
1554 (js2-msg "msg.no.name.after.coloncolon"
1555 "missing name after :: operator")
1556
1557 (js2-msg "msg.no.name.after.dotdot"
1558 "missing name after .. operator")
1559
1560 (js2-msg "msg.no.name.after.xmlAttr"
1561 "missing name after .@")
1562
1563 (js2-msg "msg.no.bracket.index"
1564 "missing ] in index expression")
1565
1566 (js2-msg "msg.no.paren.switch"
1567 "missing ( before switch expression")
1568
1569 (js2-msg "msg.no.paren.after.switch"
1570 "missing ) after switch expression")
1571
1572 (js2-msg "msg.no.brace.switch"
1573 "missing '{' before switch body")
1574
1575 (js2-msg "msg.bad.switch"
1576 "invalid switch statement")
1577
1578 (js2-msg "msg.no.colon.case"
1579 "missing : after case expression")
1580
1581 (js2-msg "msg.double.switch.default"
1582 "double default label in the switch statement")
1583
1584 (js2-msg "msg.no.while.do"
1585 "missing while after do-loop body")
1586
1587 (js2-msg "msg.no.paren.for"
1588 "missing ( after for")
1589
1590 (js2-msg "msg.no.semi.for"
1591 "missing ; after for-loop initializer")
1592
1593 (js2-msg "msg.no.semi.for.cond"
1594 "missing ; after for-loop condition")
1595
1596 (js2-msg "msg.in.after.for.name"
1597 "missing in after for")
1598
1599 (js2-msg "msg.no.paren.for.ctrl"
1600 "missing ) after for-loop control")
1601
1602 (js2-msg "msg.no.paren.with"
1603 "missing ( before with-statement object")
1604
1605 (js2-msg "msg.no.paren.after.with"
1606 "missing ) after with-statement object")
1607
1608 (js2-msg "msg.no.paren.after.let"
1609 "missing ( after let")
1610
1611 (js2-msg "msg.no.paren.let"
1612 "missing ) after variable list")
1613
1614 (js2-msg "msg.no.curly.let"
1615 "missing } after let statement")
1616
1617 (js2-msg "msg.bad.return"
1618 "invalid return")
1619
1620 (js2-msg "msg.no.brace.block"
1621 "missing } in compound statement")
1622
1623 (js2-msg "msg.bad.label"
1624 "invalid label")
1625
1626 (js2-msg "msg.bad.var"
1627 "missing variable name")
1628
1629 (js2-msg "msg.bad.var.init"
1630 "invalid variable initialization")
1631
1632 (js2-msg "msg.no.colon.cond"
1633 "missing : in conditional expression")
1634
1635 (js2-msg "msg.no.paren.arg"
1636 "missing ) after argument list")
1637
1638 (js2-msg "msg.no.bracket.arg"
1639 "missing ] after element list")
1640
1641 (js2-msg "msg.bad.prop"
1642 "invalid property id")
1643
1644 (js2-msg "msg.no.colon.prop"
1645 "missing : after property id")
1646
1647 (js2-msg "msg.no.brace.prop"
1648 "missing } after property list")
1649
1650 (js2-msg "msg.no.paren"
1651 "missing ) in parenthetical")
1652
1653 (js2-msg "msg.reserved.id"
1654 "identifier is a reserved word")
1655
1656 (js2-msg "msg.no.paren.catch"
1657 "missing ( before catch-block condition")
1658
1659 (js2-msg "msg.bad.catchcond"
1660 "invalid catch block condition")
1661
1662 (js2-msg "msg.catch.unreachable"
1663 "any catch clauses following an unqualified catch are unreachable")
1664
1665 (js2-msg "msg.no.brace.try"
1666 "missing '{' before try block")
1667
1668 (js2-msg "msg.no.brace.catchblock"
1669 "missing '{' before catch-block body")
1670
1671 (js2-msg "msg.try.no.catchfinally"
1672 "'try' without 'catch' or 'finally'")
1673
1674 (js2-msg "msg.no.return.value"
1675 "function %s does not always return a value")
1676
1677 (js2-msg "msg.anon.no.return.value"
1678 "anonymous function does not always return a value")
1679
1680 (js2-msg "msg.return.inconsistent"
1681 "return statement is inconsistent with previous usage")
1682
1683 (js2-msg "msg.generator.returns"
1684 "TypeError: generator function '%s' returns a value")
1685
1686 (js2-msg "msg.anon.generator.returns"
1687 "TypeError: anonymous generator function returns a value")
1688
1689 (js2-msg "msg.syntax"
1690 "syntax error")
1691
1692 (js2-msg "msg.unexpected.eof"
1693 "Unexpected end of file")
1694
1695 (js2-msg "msg.XML.bad.form"
1696 "illegally formed XML syntax")
1697
1698 (js2-msg "msg.XML.not.available"
1699 "XML runtime not available")
1700
1701 (js2-msg "msg.too.deep.parser.recursion"
1702 "Too deep recursion while parsing")
1703
1704 (js2-msg "msg.no.side.effects"
1705 "Code has no side effects")
1706
1707 (js2-msg "msg.extra.trailing.comma"
1708 "Trailing comma is not legal in an ECMA-262 object initializer")
1709
1710 (js2-msg "msg.array.trailing.comma"
1711 "Trailing comma yields different behavior across browsers")
1712
1713 (js2-msg "msg.equal.as.assign"
1714 (concat "Test for equality (==) mistyped as assignment (=)?"
1715 " (parenthesize to suppress warning)"))
1716
1717 (js2-msg "msg.var.hides.arg"
1718 "Variable %s hides argument")
1719
1720 (js2-msg "msg.destruct.assign.no.init"
1721 "Missing = in destructuring declaration")
1722
1723 ;; ScriptRuntime
1724 (js2-msg "msg.no.properties"
1725 "%s has no properties.")
1726
1727 (js2-msg "msg.invalid.iterator"
1728 "Invalid iterator value")
1729
1730 (js2-msg "msg.iterator.primitive"
1731 "__iterator__ returned a primitive value")
1732
1733 (js2-msg "msg.assn.create.strict"
1734 "Assignment to undeclared variable %s")
1735
1736 (js2-msg "msg.ref.undefined.prop"
1737 "Reference to undefined property '%s'")
1738
1739 (js2-msg "msg.prop.not.found"
1740 "Property %s not found.")
1741
1742 (js2-msg "msg.invalid.type"
1743 "Invalid JavaScript value of type %s")
1744
1745 (js2-msg "msg.primitive.expected"
1746 "Primitive type expected (had %s instead)")
1747
1748 (js2-msg "msg.namespace.expected"
1749 "Namespace object expected to left of :: (found %s instead)")
1750
1751 (js2-msg "msg.null.to.object"
1752 "Cannot convert null to an object.")
1753
1754 (js2-msg "msg.undef.to.object"
1755 "Cannot convert undefined to an object.")
1756
1757 (js2-msg "msg.cyclic.value"
1758 "Cyclic %s value not allowed.")
1759
1760 (js2-msg "msg.is.not.defined"
1761 "'%s' is not defined.")
1762
1763 (js2-msg "msg.undef.prop.read"
1764 "Cannot read property '%s' from %s")
1765
1766 (js2-msg "msg.undef.prop.write"
1767 "Cannot set property '%s' of %s to '%s'")
1768
1769 (js2-msg "msg.undef.prop.delete"
1770 "Cannot delete property '%s' of %s")
1771
1772 (js2-msg "msg.undef.method.call"
1773 "Cannot call method '%s' of %s")
1774
1775 (js2-msg "msg.undef.with"
1776 "Cannot apply 'with' to %s")
1777
1778 (js2-msg "msg.isnt.function"
1779 "%s is not a function, it is %s.")
1780
1781 (js2-msg "msg.isnt.function.in"
1782 "Cannot call property %s in object %s. "
1783 "It is not a function, it is '%s'.")
1784
1785 (js2-msg "msg.function.not.found"
1786 "Cannot find function %s.")
1787
1788 (js2-msg "msg.function.not.found.in"
1789 "Cannot find function %s in object %s.")
1790
1791 (js2-msg "msg.isnt.xml.object"
1792 "%s is not an xml object.")
1793
1794 (js2-msg "msg.no.ref.to.get"
1795 "%s is not a reference to read reference value.")
1796
1797 (js2-msg "msg.no.ref.to.set"
1798 "%s is not a reference to set reference value to %s.")
1799
1800 (js2-msg "msg.no.ref.from.function"
1801 "Function %s can not be used as the left-hand "
1802 "side of assignment or as an operand of ++ or -- operator.")
1803
1804 (js2-msg "msg.bad.default.value"
1805 "Object's getDefaultValue() method returned an object.")
1806
1807 (js2-msg "msg.instanceof.not.object"
1808 "Can't use instanceof on a non-object.")
1809
1810 (js2-msg "msg.instanceof.bad.prototype"
1811 "'prototype' property of %s is not an object.")
1812
1813 (js2-msg "msg.bad.radix"
1814 "illegal radix %s.")
1815
1816 ;; ScriptableObject
1817 (js2-msg "msg.default.value"
1818 "Cannot find default value for object.")
1819
1820 (js2-msg "msg.zero.arg.ctor"
1821 "Cannot load class '%s' which has no zero-parameter constructor.")
1822
1823 (js2-msg "msg.ctor.multiple.parms"
1824 "Can't define constructor or class %s since more than "
1825 "one constructor has multiple parameters.")
1826
1827 (js2-msg "msg.extend.scriptable"
1828 "%s must extend ScriptableObject in order to define property %s.")
1829
1830 (js2-msg "msg.bad.getter.parms"
1831 "In order to define a property, getter %s must have zero "
1832 "parameters or a single ScriptableObject parameter.")
1833
1834 (js2-msg "msg.obj.getter.parms"
1835 "Expected static or delegated getter %s to take "
1836 "a ScriptableObject parameter.")
1837
1838 (js2-msg "msg.getter.static"
1839 "Getter and setter must both be static or neither be static.")
1840
1841 (js2-msg "msg.setter.return"
1842 "Setter must have void return type: %s")
1843
1844 (js2-msg "msg.setter2.parms"
1845 "Two-parameter setter must take a ScriptableObject as "
1846 "its first parameter.")
1847
1848 (js2-msg "msg.setter1.parms"
1849 "Expected single parameter setter for %s")
1850
1851 (js2-msg "msg.setter2.expected"
1852 "Expected static or delegated setter %s to take two parameters.")
1853
1854 (js2-msg "msg.setter.parms"
1855 "Expected either one or two parameters for setter.")
1856
1857 (js2-msg "msg.setter.bad.type"
1858 "Unsupported parameter type '%s' in setter '%s'.")
1859
1860 (js2-msg "msg.add.sealed"
1861 "Cannot add a property to a sealed object: %s.")
1862
1863 (js2-msg "msg.remove.sealed"
1864 "Cannot remove a property from a sealed object: %s.")
1865
1866 (js2-msg "msg.modify.sealed"
1867 "Cannot modify a property of a sealed object: %s.")
1868
1869 (js2-msg "msg.modify.readonly"
1870 "Cannot modify readonly property: %s.")
1871
1872 ;; TokenStream
1873 (js2-msg "msg.missing.exponent"
1874 "missing exponent")
1875
1876 (js2-msg "msg.caught.nfe"
1877 "number format error")
1878
1879 (js2-msg "msg.unterminated.string.lit"
1880 "unterminated string literal")
1881
1882 (js2-msg "msg.unterminated.comment"
1883 "unterminated comment")
1884
1885 (js2-msg "msg.unterminated.re.lit"
1886 "unterminated regular expression literal")
1887
1888 (js2-msg "msg.invalid.re.flag"
1889 "invalid flag after regular expression")
1890
1891 (js2-msg "msg.no.re.input.for"
1892 "no input for %s")
1893
1894 (js2-msg "msg.illegal.character"
1895 "illegal character")
1896
1897 (js2-msg "msg.invalid.escape"
1898 "invalid Unicode escape sequence")
1899
1900 (js2-msg "msg.bad.namespace"
1901 "not a valid default namespace statement. "
1902 "Syntax is: default xml namespace = EXPRESSION;")
1903
1904 ;; TokensStream warnings
1905 (js2-msg "msg.bad.octal.literal"
1906 "illegal octal literal digit %s; "
1907 "interpreting it as a decimal digit")
1908
1909 (js2-msg "msg.reserved.keyword"
1910 "illegal usage of future reserved keyword %s; "
1911 "interpreting it as ordinary identifier")
1912
1913 (js2-msg "msg.script.is.not.constructor"
1914 "Script objects are not constructors.")
1915
1916 ;; Arrays
1917 (js2-msg "msg.arraylength.bad"
1918 "Inappropriate array length.")
1919
1920 ;; Arrays
1921 (js2-msg "msg.arraylength.too.big"
1922 "Array length %s exceeds supported capacity limit.")
1923
1924 ;; URI
1925 (js2-msg "msg.bad.uri"
1926 "Malformed URI sequence.")
1927
1928 ;; Number
1929 (js2-msg "msg.bad.precision"
1930 "Precision %s out of range.")
1931
1932 ;; NativeGenerator
1933 (js2-msg "msg.send.newborn"
1934 "Attempt to send value to newborn generator")
1935
1936 (js2-msg "msg.already.exec.gen"
1937 "Already executing generator")
1938
1939 (js2-msg "msg.StopIteration.invalid"
1940 "StopIteration may not be changed to an arbitrary object.")
1941
1942 ;; Interpreter
1943 (js2-msg "msg.yield.closing"
1944 "Yield from closing generator")
1945
1946 ;;; Utilities
1947
1948 (defun js2-delete-if (predicate list)
1949 "Remove all items satisfying PREDICATE in LIST."
1950 (loop for item in list
1951 if (not (funcall predicate item))
1952 collect item))
1953
1954 (defun js2-position (element list)
1955 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1956 Returns nil if element is not found in the list."
1957 (let ((count 0)
1958 found)
1959 (while (and list (not found))
1960 (if (eq element (car list))
1961 (setq found t)
1962 (setq count (1+ count)
1963 list (cdr list))))
1964 (if found count)))
1965
1966 (defun js2-find-if (predicate list)
1967 "Find first item satisfying PREDICATE in LIST."
1968 (let (result)
1969 (while (and list (not result))
1970 (if (funcall predicate (car list))
1971 (setq result (car list)))
1972 (setq list (cdr list)))
1973 result))
1974
1975 (defmacro js2-time (form)
1976 "Evaluate FORM, discard result, and return elapsed time in sec"
1977 (declare (debug t))
1978 (let ((beg (make-symbol "--js2-time-beg--"))
1979 (delta (make-symbol "--js2-time-end--")))
1980 `(let ((,beg (current-time))
1981 ,delta)
1982 ,form
1983 (/ (truncate (* (- (float-time (current-time))
1984 (float-time ,beg)))
1985 10000)
1986 10000.0))))
1987
1988 (defsubst js2-same-line (pos)
1989 "Return t if POS is on the same line as current point."
1990 (and (>= pos (point-at-bol))
1991 (<= pos (point-at-eol))))
1992
1993 (defsubst js2-same-line-2 (p1 p2)
1994 "Return t if p1 is on the same line as p2."
1995 (save-excursion
1996 (goto-char p1)
1997 (js2-same-line p2)))
1998
1999 (defun js2-code-bug ()
2000 "Signal an error when we encounter an unexpected code path."
2001 (error "failed assertion"))
2002
2003 ;; I'd like to associate errors with nodes, but for now the
2004 ;; easiest thing to do is get the context info from the last token.
2005 (defsubst js2-record-parse-error (msg &optional arg pos len)
2006 (push (list (list msg arg)
2007 (or pos js2-token-beg)
2008 (or len (- js2-token-end js2-token-beg)))
2009 js2-parsed-errors))
2010
2011 (defsubst js2-report-error (msg &optional msg-arg pos len)
2012 "Signal a syntax error or record a parse error."
2013 (if js2-recover-from-parse-errors
2014 (js2-record-parse-error msg msg-arg pos len)
2015 (signal 'js2-syntax-error
2016 (list msg
2017 js2-ts-lineno
2018 (save-excursion
2019 (goto-char js2-ts-cursor)
2020 (current-column))
2021 js2-ts-hit-eof))))
2022
2023 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2024 (if js2-compiler-report-warning-as-error
2025 (js2-report-error msg msg-arg pos len)
2026 (push (list (list msg msg-arg)
2027 (or pos js2-token-beg)
2028 (or len (- js2-token-end js2-token-beg)))
2029 js2-parsed-warnings)))
2030
2031 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2032 (if js2-compiler-strict-mode
2033 (js2-report-warning msg-id msg-arg beg
2034 (and beg end (- end beg)))))
2035
2036 (put 'js2-syntax-error 'error-conditions
2037 '(error syntax-error js2-syntax-error))
2038 (put 'js2-syntax-error 'error-message "Syntax error")
2039
2040 (put 'js2-parse-error 'error-conditions
2041 '(error parse-error js2-parse-error))
2042 (put 'js2-parse-error 'error-message "Parse error")
2043
2044 (defmacro js2-clear-flag (flags flag)
2045 `(setq ,flags (logand ,flags (lognot ,flag))))
2046
2047 (defmacro js2-set-flag (flags flag)
2048 "Logical-or FLAG into FLAGS."
2049 `(setq ,flags (logior ,flags ,flag)))
2050
2051 (defsubst js2-flag-set-p (flags flag)
2052 (/= 0 (logand flags flag)))
2053
2054 (defsubst js2-flag-not-set-p (flags flag)
2055 (zerop (logand flags flag)))
2056
2057 ;; Stolen shamelessly from James Clark's nxml-mode.
2058 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2059 "Evaluate BODY without any text property changes modifying the buffer.
2060 Any text properties changes happen as usual but the changes are not treated as
2061 modifications to the buffer."
2062 (declare (indent 0) (debug t))
2063 (let ((modified (make-symbol "modified")))
2064 `(let ((,modified (buffer-modified-p))
2065 (inhibit-read-only t)
2066 (inhibit-modification-hooks t)
2067 (buffer-undo-list t)
2068 (deactivate-mark nil)
2069 ;; Apparently these avoid file locking problems.
2070 (buffer-file-name nil)
2071 (buffer-file-truename nil))
2072 (unwind-protect
2073 (progn ,@body)
2074 (unless ,modified
2075 (restore-buffer-modified-p nil))))))
2076
2077 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2078 "Evaluate BODY with the _ character set to be word-syntax."
2079 (declare (indent 0) (debug t))
2080 (let ((old-syntax (make-symbol "old-syntax")))
2081 `(let ((,old-syntax (string (char-syntax ?_))))
2082 (unwind-protect
2083 (progn
2084 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2085 ,@body)
2086 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2087
2088 (defsubst js2-char-uppercase-p (c)
2089 "Return t if C is an uppercase character.
2090 Handles unicode and latin chars properly."
2091 (/= c (downcase c)))
2092
2093 (defsubst js2-char-lowercase-p (c)
2094 "Return t if C is an uppercase character.
2095 Handles unicode and latin chars properly."
2096 (/= c (upcase c)))
2097
2098 ;;; AST struct and function definitions
2099
2100 ;; flags for ast node property 'member-type (used for e4x operators)
2101 (defvar js2-property-flag #x1 "property access: element is valid name")
2102 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2103 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2104
2105 (defsubst js2-relpos (pos anchor)
2106 "Convert POS to be relative to ANCHOR.
2107 If POS is nil, returns nil."
2108 (and pos (- pos anchor)))
2109
2110 (defsubst js2-make-pad (indent)
2111 (if (zerop indent)
2112 ""
2113 (make-string (* indent js2-basic-offset) ? )))
2114
2115 (defsubst js2-visit-ast (node callback)
2116 "Visit every node in ast NODE with visitor CALLBACK.
2117
2118 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2119 called twice: once to visit the node, and again after all the node's
2120 children have been processed. The END-P argument is nil on the first
2121 call and non-nil on the second call. The return value of the callback
2122 affects the traversal: if non-nil, the children of NODE are processed.
2123 If the callback returns nil, or if the node has no children, then the
2124 callback is called immediately with a non-nil END-P argument.
2125
2126 The node traversal is approximately lexical-order, although there
2127 are currently no guarantees around this."
2128 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2129 ;; visit the node
2130 (when (funcall callback node nil)
2131 ;; visit the kids
2132 (cond
2133 ((eq vfunc 'js2-visit-none)
2134 nil) ; don't even bother calling it
2135 ;; Each AST node type has to define a `js2-visitor' function
2136 ;; that takes a node and a callback, and calls `js2-visit-ast'
2137 ;; on each child of the node.
2138 (vfunc
2139 (funcall vfunc node callback))
2140 (t
2141 (error "%s does not define a visitor-traversal function"
2142 (aref node 0)))))
2143 ;; call the end-visit
2144 (funcall callback node t)))
2145
2146 (defstruct (js2-node
2147 (:constructor nil)) ; abstract
2148 "Base AST node type."
2149 (type -1) ; token type
2150 (pos -1) ; start position of this AST node in parsed input
2151 (len 1) ; num characters spanned by the node
2152 props ; optional node property list (an alist)
2153 parent) ; link to parent node; null for root
2154
2155 (defsubst js2-node-get-prop (node prop &optional default)
2156 (or (cadr (assoc prop (js2-node-props node))) default))
2157
2158 (defsubst js2-node-set-prop (node prop value)
2159 (setf (js2-node-props node)
2160 (cons (list prop value) (js2-node-props node))))
2161
2162 (defsubst js2-fixup-starts (n nodes)
2163 "Adjust the start positions of NODES to be relative to N.
2164 Any node in the list may be nil, for convenience."
2165 (dolist (node nodes)
2166 (when node
2167 (setf (js2-node-pos node) (- (js2-node-pos node)
2168 (js2-node-pos n))))))
2169
2170 (defsubst js2-node-add-children (parent &rest nodes)
2171 "Set parent node of NODES to PARENT, and return PARENT.
2172 Does nothing if we're not recording parent links.
2173 If any given node in NODES is nil, doesn't record that link."
2174 (js2-fixup-starts parent nodes)
2175 (dolist (node nodes)
2176 (and node
2177 (setf (js2-node-parent node) parent))))
2178
2179 ;; Non-recursive since it's called a frightening number of times.
2180 (defsubst js2-node-abs-pos (n)
2181 (let ((pos (js2-node-pos n)))
2182 (while (setq n (js2-node-parent n))
2183 (setq pos (+ pos (js2-node-pos n))))
2184 pos))
2185
2186 (defsubst js2-node-abs-end (n)
2187 "Return absolute buffer position of end of N."
2188 (+ (js2-node-abs-pos n) (js2-node-len n)))
2189
2190 ;; It's important to make sure block nodes have a lisp list for the
2191 ;; child nodes, to limit printing recursion depth in an AST that
2192 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2193 ;; a sufficiently large vector tree.
2194
2195 (defstruct (js2-block-node
2196 (:include js2-node)
2197 (:constructor nil)
2198 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2199 (pos js2-token-beg)
2200 len
2201 props
2202 kids)))
2203 "A block of statements."
2204 kids) ; a lisp list of the child statement nodes
2205
2206 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2207 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2208
2209 (defsubst js2-visit-block (ast callback)
2210 "Visit the `js2-block-node' children of AST."
2211 (dolist (kid (js2-block-node-kids ast))
2212 (js2-visit-ast kid callback)))
2213
2214 (defun js2-print-block (n i)
2215 (let ((pad (js2-make-pad i)))
2216 (insert pad "{\n")
2217 (dolist (kid (js2-block-node-kids n))
2218 (js2-print-ast kid (1+ i)))
2219 (insert pad "}")))
2220
2221 (defstruct (js2-scope
2222 (:include js2-block-node)
2223 (:constructor nil)
2224 (:constructor make-js2-scope (&key (type js2-BLOCK)
2225 (pos js2-token-beg)
2226 len
2227 kids)))
2228 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2229 ;; I don't have one of those handy, so I'll use an alist for now.
2230 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2231 ;; and is much lighter-weight to construct (both CPU and mem).
2232 ;; The keys are interned strings (symbols) for faster lookup.
2233 ;; Should switch to hybrid alist/hashtable eventually.
2234 symbol-table ; an alist of (symbol . js2-symbol)
2235 parent-scope ; a `js2-scope'
2236 top) ; top-level `js2-scope' (script/function)
2237
2238 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2239 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2240
2241 (defun js2-scope-set-parent-scope (scope parent)
2242 (setf (js2-scope-parent-scope scope) parent
2243 (js2-scope-top scope) (if (null parent)
2244 scope
2245 (js2-scope-top parent))))
2246
2247 (defun js2-node-get-enclosing-scope (node)
2248 "Return the innermost `js2-scope' node surrounding NODE.
2249 Returns nil if there is no enclosing scope node."
2250 (let ((parent (js2-node-parent node)))
2251 (while (not (js2-scope-p parent))
2252 (setq parent (js2-node-parent parent)))
2253 parent))
2254
2255 (defun js2-get-defining-scope (scope name)
2256 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2257 Returns `js2-scope' in which NAME is defined, or nil if not found."
2258 (let ((sym (if (symbolp name)
2259 name
2260 (intern name)))
2261 table
2262 result
2263 (continue t))
2264 (while (and scope continue)
2265 (if (and (setq table (js2-scope-symbol-table scope))
2266 (assq sym table))
2267 (setq continue nil
2268 result scope)
2269 (setq scope (js2-scope-parent-scope scope))))
2270 result))
2271
2272 (defsubst js2-scope-get-symbol (scope name)
2273 "Return symbol table entry for NAME in SCOPE.
2274 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2275 (and (js2-scope-symbol-table scope)
2276 (cdr (assq (if (symbolp name)
2277 name
2278 (intern name))
2279 (js2-scope-symbol-table scope)))))
2280
2281 (defsubst js2-scope-put-symbol (scope name symbol)
2282 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2283 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2284 (let* ((table (js2-scope-symbol-table scope))
2285 (sym (if (symbolp name) name (intern name)))
2286 (entry (assq sym table)))
2287 (if entry
2288 (setcdr entry symbol)
2289 (push (cons sym symbol)
2290 (js2-scope-symbol-table scope)))))
2291
2292 (defstruct (js2-symbol
2293 (:constructor nil)
2294 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2295 "A symbol table entry."
2296 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2297 ;; js2-LET, or js2-CONST
2298 decl-type
2299 name ; string
2300 ast-node) ; a `js2-node'
2301
2302 (defstruct (js2-error-node
2303 (:include js2-node)
2304 (:constructor nil) ; silence emacs21 byte-compiler
2305 (:constructor make-js2-error-node (&key (type js2-ERROR)
2306 (pos js2-token-beg)
2307 len)))
2308 "AST node representing a parse error.")
2309
2310 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2311 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2312
2313 (defstruct (js2-script-node
2314 (:include js2-scope)
2315 (:constructor nil)
2316 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2317 (pos js2-token-beg)
2318 len
2319 var-decls
2320 fun-decls)))
2321 functions ; lisp list of nested functions
2322 regexps ; lisp list of (string . flags)
2323 symbols ; alist (every symbol gets unique index)
2324 (param-count 0)
2325 var-names ; vector of string names
2326 consts ; bool-vector matching var-decls
2327 (temp-number 0)) ; for generating temp variables
2328
2329 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2330 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2331
2332 (defun js2-print-script (node indent)
2333 (dolist (kid (js2-block-node-kids node))
2334 (js2-print-ast kid indent)))
2335
2336 (defstruct (js2-ast-root
2337 (:include js2-script-node)
2338 (:constructor nil)
2339 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2340 (pos js2-token-beg)
2341 len
2342 buffer)))
2343 "The root node of a js2 AST."
2344 buffer ; the source buffer from which the code was parsed
2345 comments ; a lisp list of comments, ordered by start position
2346 errors ; a lisp list of errors found during parsing
2347 warnings ; a lisp list of warnings found during parsing
2348 node-count) ; number of nodes in the tree, including the root
2349
2350 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2351 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2352
2353 (defun js2-visit-ast-root (ast callback)
2354 (dolist (kid (js2-ast-root-kids ast))
2355 (js2-visit-ast kid callback))
2356 (dolist (comment (js2-ast-root-comments ast))
2357 (js2-visit-ast comment callback)))
2358
2359 (defstruct (js2-comment-node
2360 (:include js2-node)
2361 (:constructor nil)
2362 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2363 (pos js2-token-beg)
2364 len
2365 (format js2-ts-comment-type))))
2366 format) ; 'line, 'block, 'jsdoc or 'html
2367
2368 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2369 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2370
2371 (defun js2-print-comment (n i)
2372 ;; We really ought to link end-of-line comments to their nodes.
2373 ;; Or maybe we could add a new comment type, 'endline.
2374 (insert (js2-make-pad i)
2375 (js2-node-string n)))
2376
2377 (defstruct (js2-expr-stmt-node
2378 (:include js2-node)
2379 (:constructor nil)
2380 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2381 (pos js2-ts-cursor)
2382 len
2383 expr)))
2384 "An expression statement."
2385 expr)
2386
2387 (defsubst js2-expr-stmt-node-set-has-result (node)
2388 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2389 (setf (js2-node-type node) js2-EXPR_RESULT))
2390
2391 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2392 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2393
2394 (defun js2-visit-expr-stmt-node (n v)
2395 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2396
2397 (defun js2-print-expr-stmt-node (n indent)
2398 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2399 (insert ";\n"))
2400
2401 (defstruct (js2-loop-node
2402 (:include js2-scope)
2403 (:constructor nil))
2404 "Abstract supertype of loop nodes."
2405 body ; a `js2-block-node'
2406 lp ; position of left-paren, nil if omitted
2407 rp) ; position of right-paren, nil if omitted
2408
2409 (defstruct (js2-do-node
2410 (:include js2-loop-node)
2411 (:constructor nil)
2412 (:constructor make-js2-do-node (&key (type js2-DO)
2413 (pos js2-token-beg)
2414 len
2415 body
2416 condition
2417 while-pos
2418 lp
2419 rp)))
2420 "AST node for do-loop."
2421 condition ; while (expression)
2422 while-pos) ; buffer position of 'while' keyword
2423
2424 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2425 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2426
2427 (defun js2-visit-do-node (n v)
2428 (js2-visit-ast (js2-do-node-body n) v)
2429 (js2-visit-ast (js2-do-node-condition n) v))
2430
2431 (defun js2-print-do-node (n i)
2432 (let ((pad (js2-make-pad i)))
2433 (insert pad "do {\n")
2434 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2435 (js2-print-ast kid (1+ i)))
2436 (insert pad "} while (")
2437 (js2-print-ast (js2-do-node-condition n) 0)
2438 (insert ");\n")))
2439
2440 (defstruct (js2-while-node
2441 (:include js2-loop-node)
2442 (:constructor nil)
2443 (:constructor make-js2-while-node (&key (type js2-WHILE)
2444 (pos js2-token-beg)
2445 len
2446 body
2447 condition
2448 lp
2449 rp)))
2450 "AST node for while-loop."
2451 condition) ; while-condition
2452
2453 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2454 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2455
2456 (defun js2-visit-while-node (n v)
2457 (js2-visit-ast (js2-while-node-condition n) v)
2458 (js2-visit-ast (js2-while-node-body n) v))
2459
2460 (defun js2-print-while-node (n i)
2461 (let ((pad (js2-make-pad i)))
2462 (insert pad "while (")
2463 (js2-print-ast (js2-while-node-condition n) 0)
2464 (insert ") {\n")
2465 (js2-print-body (js2-while-node-body n) (1+ i))
2466 (insert pad "}\n")))
2467
2468 (defstruct (js2-for-node
2469 (:include js2-loop-node)
2470 (:constructor nil)
2471 (:constructor make-js2-for-node (&key (type js2-FOR)
2472 (pos js2-ts-cursor)
2473 len
2474 body
2475 init
2476 condition
2477 update
2478 lp
2479 rp)))
2480 "AST node for a C-style for-loop."
2481 init ; initialization expression
2482 condition ; loop condition
2483 update) ; update clause
2484
2485 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2486 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2487
2488 (defun js2-visit-for-node (n v)
2489 (js2-visit-ast (js2-for-node-init n) v)
2490 (js2-visit-ast (js2-for-node-condition n) v)
2491 (js2-visit-ast (js2-for-node-update n) v)
2492 (js2-visit-ast (js2-for-node-body n) v))
2493
2494 (defun js2-print-for-node (n i)
2495 (let ((pad (js2-make-pad i)))
2496 (insert pad "for (")
2497 (js2-print-ast (js2-for-node-init n) 0)
2498 (insert "; ")
2499 (js2-print-ast (js2-for-node-condition n) 0)
2500 (insert "; ")
2501 (js2-print-ast (js2-for-node-update n) 0)
2502 (insert ") {\n")
2503 (js2-print-body (js2-for-node-body n) (1+ i))
2504 (insert pad "}\n")))
2505
2506 (defstruct (js2-for-in-node
2507 (:include js2-loop-node)
2508 (:constructor nil)
2509 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2510 (pos js2-ts-cursor)
2511 len
2512 body
2513 iterator
2514 object
2515 in-pos
2516 each-pos
2517 foreach-p
2518 lp
2519 rp)))
2520 "AST node for a for..in loop."
2521 iterator ; [var] foo in ...
2522 object ; object over which we're iterating
2523 in-pos ; buffer position of 'in' keyword
2524 each-pos ; buffer position of 'each' keyword, if foreach-p
2525 foreach-p) ; t if it's a for-each loop
2526
2527 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2528 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2529
2530 (defun js2-visit-for-in-node (n v)
2531 (js2-visit-ast (js2-for-in-node-iterator n) v)
2532 (js2-visit-ast (js2-for-in-node-object n) v)
2533 (js2-visit-ast (js2-for-in-node-body n) v))
2534
2535 (defun js2-print-for-in-node (n i)
2536 (let ((pad (js2-make-pad i))
2537 (foreach (js2-for-in-node-foreach-p n)))
2538 (insert pad "for ")
2539 (if foreach
2540 (insert "each "))
2541 (insert "(")
2542 (js2-print-ast (js2-for-in-node-iterator n) 0)
2543 (insert " in ")
2544 (js2-print-ast (js2-for-in-node-object n) 0)
2545 (insert ") {\n")
2546 (js2-print-body (js2-for-in-node-body n) (1+ i))
2547 (insert pad "}\n")))
2548
2549 (defstruct (js2-return-node
2550 (:include js2-node)
2551 (:constructor nil)
2552 (:constructor make-js2-return-node (&key (type js2-RETURN)
2553 (pos js2-ts-cursor)
2554 len
2555 retval)))
2556 "AST node for a return statement."
2557 retval) ; expression to return, or 'undefined
2558
2559 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2560 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2561
2562 (defun js2-visit-return-node (n v)
2563 (if (js2-return-node-retval n)
2564 (js2-visit-ast (js2-return-node-retval n) v)))
2565
2566 (defun js2-print-return-node (n i)
2567 (insert (js2-make-pad i) "return")
2568 (when (js2-return-node-retval n)
2569 (insert " ")
2570 (js2-print-ast (js2-return-node-retval n) 0))
2571 (insert ";\n"))
2572
2573 (defstruct (js2-if-node
2574 (:include js2-node)
2575 (:constructor nil)
2576 (:constructor make-js2-if-node (&key (type js2-IF)
2577 (pos js2-ts-cursor)
2578 len
2579 condition
2580 then-part
2581 else-pos
2582 else-part
2583 lp
2584 rp)))
2585 "AST node for an if-statement."
2586 condition ; expression
2587 then-part ; statement or block
2588 else-pos ; optional buffer position of 'else' keyword
2589 else-part ; optional statement or block
2590 lp ; position of left-paren, nil if omitted
2591 rp) ; position of right-paren, nil if omitted
2592
2593 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2594 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2595
2596 (defun js2-visit-if-node (n v)
2597 (js2-visit-ast (js2-if-node-condition n) v)
2598 (js2-visit-ast (js2-if-node-then-part n) v)
2599 (if (js2-if-node-else-part n)
2600 (js2-visit-ast (js2-if-node-else-part n) v)))
2601
2602 (defun js2-print-if-node (n i)
2603 (let ((pad (js2-make-pad i))
2604 (then-part (js2-if-node-then-part n))
2605 (else-part (js2-if-node-else-part n)))
2606 (insert pad "if (")
2607 (js2-print-ast (js2-if-node-condition n) 0)
2608 (insert ") {\n")
2609 (js2-print-body then-part (1+ i))
2610 (insert pad "}")
2611 (cond
2612 ((not else-part)
2613 (insert "\n"))
2614 ((js2-if-node-p else-part)
2615 (insert " else ")
2616 (js2-print-body else-part i))
2617 (t
2618 (insert " else {\n")
2619 (js2-print-body else-part (1+ i))
2620 (insert pad "}\n")))))
2621
2622 (defstruct (js2-try-node
2623 (:include js2-node)
2624 (:constructor nil)
2625 (:constructor make-js2-try-node (&key (type js2-TRY)
2626 (pos js2-ts-cursor)
2627 len
2628 try-block
2629 catch-clauses
2630 finally-block)))
2631 "AST node for a try-statement."
2632 try-block
2633 catch-clauses ; a lisp list of `js2-catch-node'
2634 finally-block) ; a `js2-finally-node'
2635
2636 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2637 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2638
2639 (defun js2-visit-try-node (n v)
2640 (js2-visit-ast (js2-try-node-try-block n) v)
2641 (dolist (clause (js2-try-node-catch-clauses n))
2642 (js2-visit-ast clause v))
2643 (if (js2-try-node-finally-block n)
2644 (js2-visit-ast (js2-try-node-finally-block n) v)))
2645
2646 (defun js2-print-try-node (n i)
2647 (let ((pad (js2-make-pad i))
2648 (catches (js2-try-node-catch-clauses n))
2649 (finally (js2-try-node-finally-block n)))
2650 (insert pad "try {\n")
2651 (js2-print-body (js2-try-node-try-block n) (1+ i))
2652 (insert pad "}")
2653 (when catches
2654 (dolist (catch catches)
2655 (js2-print-ast catch i)))
2656 (if finally
2657 (js2-print-ast finally i)
2658 (insert "\n"))))
2659
2660 (defstruct (js2-catch-node
2661 (:include js2-node)
2662 (:constructor nil)
2663 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2664 (pos js2-ts-cursor)
2665 len
2666 var-name
2667 guard-kwd
2668 guard-expr
2669 block
2670 lp
2671 rp)))
2672 "AST node for a catch clause."
2673 var-name ; a `js2-name-node'
2674 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2675 guard-expr ; catch condition, a `js2-node'
2676 block ; statements, a `js2-block-node'
2677 lp ; buffer position of left-paren, nil if omitted
2678 rp) ; buffer position of right-paren, nil if omitted
2679
2680 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2681 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2682
2683 (defun js2-visit-catch-node (n v)
2684 (js2-visit-ast (js2-catch-node-var-name n) v)
2685 (when (js2-catch-node-guard-kwd n)
2686 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2687 (js2-visit-ast (js2-catch-node-block n) v))
2688
2689 (defun js2-print-catch-node (n i)
2690 (let ((pad (js2-make-pad i))
2691 (guard-kwd (js2-catch-node-guard-kwd n))
2692 (guard-expr (js2-catch-node-guard-expr n)))
2693 (insert " catch (")
2694 (js2-print-ast (js2-catch-node-var-name n) 0)
2695 (when guard-kwd
2696 (insert " if ")
2697 (js2-print-ast guard-expr 0))
2698 (insert ") {\n")
2699 (js2-print-body (js2-catch-node-block n) (1+ i))
2700 (insert pad "}")))
2701
2702 (defstruct (js2-finally-node
2703 (:include js2-node)
2704 (:constructor nil)
2705 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2706 (pos js2-ts-cursor)
2707 len
2708 body)))
2709 "AST node for a finally clause."
2710 body) ; a `js2-node', often but not always a block node
2711
2712 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2713 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2714
2715 (defun js2-visit-finally-node (n v)
2716 (js2-visit-ast (js2-finally-node-body n) v))
2717
2718 (defun js2-print-finally-node (n i)
2719 (let ((pad (js2-make-pad i)))
2720 (insert " finally {\n")
2721 (js2-print-body (js2-finally-node-body n) (1+ i))
2722 (insert pad "}\n")))
2723
2724 (defstruct (js2-switch-node
2725 (:include js2-node)
2726 (:constructor nil)
2727 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2728 (pos js2-ts-cursor)
2729 len
2730 discriminant
2731 cases
2732 lp
2733 rp)))
2734 "AST node for a switch statement."
2735 discriminant ; a `js2-node' (switch expression)
2736 cases ; a lisp list of `js2-case-node'
2737 lp ; position of open-paren for discriminant, nil if omitted
2738 rp) ; position of close-paren for discriminant, nil if omitted
2739
2740 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2741 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2742
2743 (defun js2-visit-switch-node (n v)
2744 (js2-visit-ast (js2-switch-node-discriminant n) v)
2745 (dolist (c (js2-switch-node-cases n))
2746 (js2-visit-ast c v)))
2747
2748 (defun js2-print-switch-node (n i)
2749 (let ((pad (js2-make-pad i))
2750 (cases (js2-switch-node-cases n)))
2751 (insert pad "switch (")
2752 (js2-print-ast (js2-switch-node-discriminant n) 0)
2753 (insert ") {\n")
2754 (dolist (case cases)
2755 (js2-print-ast case i))
2756 (insert pad "}\n")))
2757
2758 (defstruct (js2-case-node
2759 (:include js2-block-node)
2760 (:constructor nil)
2761 (:constructor make-js2-case-node (&key (type js2-CASE)
2762 (pos js2-ts-cursor)
2763 len
2764 kids
2765 expr)))
2766 "AST node for a case clause of a switch statement."
2767 expr) ; the case expression (nil for default)
2768
2769 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2770 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2771
2772 (defun js2-visit-case-node (n v)
2773 (if (js2-case-node-expr n) ; nil for default: case
2774 (js2-visit-ast (js2-case-node-expr n) v))
2775 (js2-visit-block n v))
2776
2777 (defun js2-print-case-node (n i)
2778 (let ((pad (js2-make-pad i))
2779 (expr (js2-case-node-expr n)))
2780 (insert pad)
2781 (if (null expr)
2782 (insert "default:\n")
2783 (insert "case ")
2784 (js2-print-ast expr 0)
2785 (insert ":\n"))
2786 (dolist (kid (js2-case-node-kids n))
2787 (js2-print-ast kid (1+ i)))))
2788
2789 (defstruct (js2-throw-node
2790 (:include js2-node)
2791 (:constructor nil)
2792 (:constructor make-js2-throw-node (&key (type js2-THROW)
2793 (pos js2-ts-cursor)
2794 len
2795 expr)))
2796 "AST node for a throw statement."
2797 expr) ; the expression to throw
2798
2799 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2800 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2801
2802 (defun js2-visit-throw-node (n v)
2803 (js2-visit-ast (js2-throw-node-expr n) v))
2804
2805 (defun js2-print-throw-node (n i)
2806 (insert (js2-make-pad i) "throw ")
2807 (js2-print-ast (js2-throw-node-expr n) 0)
2808 (insert ";\n"))
2809
2810 (defstruct (js2-with-node
2811 (:include js2-node)
2812 (:constructor nil)
2813 (:constructor make-js2-with-node (&key (type js2-WITH)
2814 (pos js2-ts-cursor)
2815 len
2816 object
2817 body
2818 lp
2819 rp)))
2820 "AST node for a with-statement."
2821 object
2822 body
2823 lp ; buffer position of left-paren around object, nil if omitted
2824 rp) ; buffer position of right-paren around object, nil if omitted
2825
2826 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2827 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2828
2829 (defun js2-visit-with-node (n v)
2830 (js2-visit-ast (js2-with-node-object n) v)
2831 (js2-visit-ast (js2-with-node-body n) v))
2832
2833 (defun js2-print-with-node (n i)
2834 (let ((pad (js2-make-pad i)))
2835 (insert pad "with (")
2836 (js2-print-ast (js2-with-node-object n) 0)
2837 (insert ") {\n")
2838 (js2-print-body (js2-with-node-body n) (1+ i))
2839 (insert pad "}\n")))
2840
2841 (defstruct (js2-label-node
2842 (:include js2-node)
2843 (:constructor nil)
2844 (:constructor make-js2-label-node (&key (type js2-LABEL)
2845 (pos js2-ts-cursor)
2846 len
2847 name)))
2848 "AST node for a statement label or case label."
2849 name ; a string
2850 loop) ; for validating and code-generating continue-to-label
2851
2852 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2853 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2854
2855 (defun js2-print-label (n i)
2856 (insert (js2-make-pad i)
2857 (js2-label-node-name n)
2858 ":\n"))
2859
2860 (defstruct (js2-labeled-stmt-node
2861 (:include js2-node)
2862 (:constructor nil)
2863 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2864 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2865 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2866 (pos js2-ts-cursor)
2867 len
2868 labels
2869 stmt)))
2870 "AST node for a statement with one or more labels.
2871 Multiple labels for a statement are collapsed into the labels field."
2872 labels ; lisp list of `js2-label-node'
2873 stmt) ; the statement these labels are for
2874
2875 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2876 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2877
2878 (defun js2-get-label-by-name (lbl-stmt name)
2879 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2880 Returns nil if no such label is in the list."
2881 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2882 result)
2883 (while (and label-list (not result))
2884 (if (string= (js2-label-node-name (car label-list)) name)
2885 (setq result (car label-list))
2886 (setq label-list (cdr label-list))))
2887 result))
2888
2889 (defun js2-visit-labeled-stmt (n v)
2890 (dolist (label (js2-labeled-stmt-node-labels n))
2891 (js2-visit-ast label v))
2892 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2893
2894 (defun js2-print-labeled-stmt (n i)
2895 (dolist (label (js2-labeled-stmt-node-labels n))
2896 (js2-print-ast label i))
2897 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2898
2899 (defun js2-labeled-stmt-node-contains (node label)
2900 "Return t if NODE contains LABEL in its label set.
2901 NODE is a `js2-labels-node'. LABEL is an identifier."
2902 (loop for nl in (js2-labeled-stmt-node-labels node)
2903 if (string= label (js2-label-node-name nl))
2904 return t
2905 finally return nil))
2906
2907 (defsubst js2-labeled-stmt-node-add-label (node label)
2908 "Add a `js2-label-node' to the label set for this statement."
2909 (setf (js2-labeled-stmt-node-labels node)
2910 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2911
2912 (defstruct (js2-jump-node
2913 (:include js2-node)
2914 (:constructor nil))
2915 "Abstract supertype of break and continue nodes."
2916 label ; `js2-name-node' for location of label identifier, if present
2917 target) ; target js2-labels-node or loop/switch statement
2918
2919 (defun js2-visit-jump-node (n v)
2920 ;; we don't visit the target, since it's a back-link
2921 (if (js2-jump-node-label n)
2922 (js2-visit-ast (js2-jump-node-label n) v)))
2923
2924 (defstruct (js2-break-node
2925 (:include js2-jump-node)
2926 (:constructor nil)
2927 (:constructor make-js2-break-node (&key (type js2-BREAK)
2928 (pos js2-ts-cursor)
2929 len
2930 label
2931 target)))
2932 "AST node for a break statement.
2933 The label field is a `js2-name-node', possibly nil, for the named label
2934 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2935 is the target of the break - a label node or enclosing loop/switch statement.")
2936
2937 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2938 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2939
2940 (defun js2-print-break-node (n i)
2941 (insert (js2-make-pad i) "break")
2942 (when (js2-break-node-label n)
2943 (insert " ")
2944 (js2-print-ast (js2-break-node-label n) 0))
2945 (insert ";\n"))
2946
2947 (defstruct (js2-continue-node
2948 (:include js2-jump-node)
2949 (:constructor nil)
2950 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2951 (pos js2-ts-cursor)
2952 len
2953 label
2954 target)))
2955 "AST node for a continue statement.
2956 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2957 It is nil if continue specifies no label. The target field is the jump target:
2958 a `js2-label-node' or the innermost enclosing loop.")
2959
2960 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2961 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2962
2963 (defun js2-print-continue-node (n i)
2964 (insert (js2-make-pad i) "continue")
2965 (when (js2-continue-node-label n)
2966 (insert " ")
2967 (js2-print-ast (js2-continue-node-label n) 0))
2968 (insert ";\n"))
2969
2970 (defstruct (js2-function-node
2971 (:include js2-script-node)
2972 (:constructor nil)
2973 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2974 (pos js2-ts-cursor)
2975 len
2976 (ftype 'FUNCTION)
2977 (form 'FUNCTION_STATEMENT)
2978 (name "")
2979 params
2980 body
2981 lp
2982 rp)))
2983 "AST node for a function declaration.
2984 The `params' field is a lisp list of nodes. Each node is either a simple
2985 `js2-name-node', or if it's a destructuring-assignment parameter, a
2986 `js2-array-node' or `js2-object-node'."
2987 ftype ; FUNCTION, GETTER or SETTER
2988 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2989 name ; function name (a `js2-name-node', or nil if anonymous)
2990 params ; a lisp list of destructuring forms or simple name nodes
2991 body ; a `js2-block-node' or expression node (1.8 only)
2992 lp ; position of arg-list open-paren, or nil if omitted
2993 rp ; position of arg-list close-paren, or nil if omitted
2994 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2995 needs-activation ; t if we need an activation object for this frame
2996 is-generator ; t if this function contains a yield
2997 member-expr) ; nonstandard Ecma extension from Rhino
2998
2999 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3000 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3001
3002 (defun js2-visit-function-node (n v)
3003 (if (js2-function-node-name n)
3004 (js2-visit-ast (js2-function-node-name n) v))
3005 (dolist (p (js2-function-node-params n))
3006 (js2-visit-ast p v))
3007 (when (js2-function-node-body n)
3008 (js2-visit-ast (js2-function-node-body n) v)))
3009
3010 (defun js2-print-function-node (n i)
3011 (let ((pad (js2-make-pad i))
3012 (getter (js2-node-get-prop n 'GETTER_SETTER))
3013 (name (js2-function-node-name n))
3014 (params (js2-function-node-params n))
3015 (body (js2-function-node-body n))
3016 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3017 (unless getter
3018 (insert pad "function"))
3019 (when name
3020 (insert " ")
3021 (js2-print-ast name 0))
3022 (insert "(")
3023 (loop with len = (length params)
3024 for param in params
3025 for count from 1
3026 do
3027 (js2-print-ast param 0)
3028 (if (< count len)
3029 (insert ", ")))
3030 (insert ") {")
3031 (unless expr
3032 (insert "\n"))
3033 ;; TODO: fix this to be smarter about indenting, etc.
3034 (js2-print-body body (1+ i))
3035 (insert pad "}")
3036 (unless expr
3037 (insert "\n"))))
3038
3039 (defsubst js2-function-name (node)
3040 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3041 (and (js2-function-node-name node)
3042 (js2-name-node-name (js2-function-node-name node))))
3043
3044 ;; Having this be an expression node makes it more flexible.
3045 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3046 ;; that work better if you assume it's an expression. Whenever we have
3047 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3048 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3049 (defstruct (js2-var-decl-node
3050 (:include js2-node)
3051 (:constructor nil)
3052 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3053 (pos js2-token-beg)
3054 len
3055 kids
3056 decl-type)))
3057 "AST node for a variable declaration list (VAR, CONST or LET).
3058 The node bounds differ depending on the declaration type. For VAR or
3059 CONST declarations, the bounds include the var/const keyword. For LET
3060 declarations, the node begins at the position of the first child."
3061 kids ; a lisp list of `js2-var-init-node' structs.
3062 decl-type) ; js2-VAR, js2-CONST or js2-LET
3063
3064 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3065 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3066
3067 (defun js2-visit-var-decl (n v)
3068 (dolist (kid (js2-var-decl-node-kids n))
3069 (js2-visit-ast kid v)))
3070
3071 (defun js2-print-var-decl (n i)
3072 (let ((pad (js2-make-pad i))
3073 (tt (js2-var-decl-node-decl-type n)))
3074 (insert pad)
3075 (insert (cond
3076 ((= tt js2-VAR) "var ")
3077 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3078 ((= tt js2-CONST) "const ")
3079 (t
3080 (error "malformed var-decl node"))))
3081 (loop with kids = (js2-var-decl-node-kids n)
3082 with len = (length kids)
3083 for kid in kids
3084 for count from 1
3085 do
3086 (js2-print-ast kid 0)
3087 (if (< count len)
3088 (insert ", ")))))
3089
3090 (defstruct (js2-var-init-node
3091 (:include js2-node)
3092 (:constructor nil)
3093 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3094 (pos js2-ts-cursor)
3095 len
3096 target
3097 initializer)))
3098 "AST node for a variable declaration.
3099 The type field will be js2-CONST for a const decl."
3100 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3101 initializer) ; initializer expression, a `js2-node'
3102
3103 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3104 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3105
3106 (defun js2-visit-var-init-node (n v)
3107 (js2-visit-ast (js2-var-init-node-target n) v)
3108 (if (js2-var-init-node-initializer n)
3109 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3110
3111 (defun js2-print-var-init-node (n i)
3112 (let ((pad (js2-make-pad i))
3113 (name (js2-var-init-node-target n))
3114 (init (js2-var-init-node-initializer n)))
3115 (insert pad)
3116 (js2-print-ast name 0)
3117 (when init
3118 (insert " = ")
3119 (js2-print-ast init 0))))
3120
3121 (defstruct (js2-cond-node
3122 (:include js2-node)
3123 (:constructor nil)
3124 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3125 (pos js2-ts-cursor)
3126 len
3127 test-expr
3128 true-expr
3129 false-expr
3130 q-pos
3131 c-pos)))
3132 "AST node for the ternary operator"
3133 test-expr
3134 true-expr
3135 false-expr
3136 q-pos ; buffer position of ?
3137 c-pos) ; buffer position of :
3138
3139 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3140 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3141
3142 (defun js2-visit-cond-node (n v)
3143 (js2-visit-ast (js2-cond-node-test-expr n) v)
3144 (js2-visit-ast (js2-cond-node-true-expr n) v)
3145 (js2-visit-ast (js2-cond-node-false-expr n) v))
3146
3147 (defun js2-print-cond-node (n i)
3148 (let ((pad (js2-make-pad i)))
3149 (insert pad)
3150 (js2-print-ast (js2-cond-node-test-expr n) 0)
3151 (insert " ? ")
3152 (js2-print-ast (js2-cond-node-true-expr n) 0)
3153 (insert " : ")
3154 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3155
3156 (defstruct (js2-infix-node
3157 (:include js2-node)
3158 (:constructor nil)
3159 (:constructor make-js2-infix-node (&key type
3160 (pos js2-ts-cursor)
3161 len
3162 op-pos
3163 left
3164 right)))
3165 "Represents infix expressions.
3166 Includes assignment ops like `|=', and the comma operator.
3167 The type field inherited from `js2-node' holds the operator."
3168 op-pos ; buffer position where operator begins
3169 left ; any `js2-node'
3170 right) ; any `js2-node'
3171
3172 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3173 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3174
3175 (defun js2-visit-infix-node (n v)
3176 (when (js2-infix-node-left n)
3177 (js2-visit-ast (js2-infix-node-left n) v))
3178 (when (js2-infix-node-right n)
3179 (js2-visit-ast (js2-infix-node-right n) v)))
3180
3181 (defconst js2-operator-tokens
3182 (let ((table (make-hash-table :test 'eq))
3183 (tokens
3184 (list (cons js2-IN "in")
3185 (cons js2-TYPEOF "typeof")
3186 (cons js2-INSTANCEOF "instanceof")
3187 (cons js2-DELPROP "delete")
3188 (cons js2-COMMA ",")
3189 (cons js2-COLON ":")
3190 (cons js2-OR "||")
3191 (cons js2-AND "&&")
3192 (cons js2-INC "++")
3193 (cons js2-DEC "--")
3194 (cons js2-BITOR "|")
3195 (cons js2-BITXOR "^")
3196 (cons js2-BITAND "&")
3197 (cons js2-EQ "==")
3198 (cons js2-NE "!=")
3199 (cons js2-LT "<")
3200 (cons js2-LE "<=")
3201 (cons js2-GT ">")
3202 (cons js2-GE ">=")
3203 (cons js2-LSH "<<")
3204 (cons js2-RSH ">>")
3205 (cons js2-URSH ">>>")
3206 (cons js2-ADD "+") ; infix plus
3207 (cons js2-SUB "-") ; infix minus
3208 (cons js2-MUL "*")
3209 (cons js2-DIV "/")
3210 (cons js2-MOD "%")
3211 (cons js2-NOT "!")
3212 (cons js2-BITNOT "~")
3213 (cons js2-POS "+") ; unary plus
3214 (cons js2-NEG "-") ; unary minus
3215 (cons js2-SHEQ "===") ; shallow equality
3216 (cons js2-SHNE "!==") ; shallow inequality
3217 (cons js2-ASSIGN "=")
3218 (cons js2-ASSIGN_BITOR "|=")
3219 (cons js2-ASSIGN_BITXOR "^=")
3220 (cons js2-ASSIGN_BITAND "&=")
3221 (cons js2-ASSIGN_LSH "<<=")
3222 (cons js2-ASSIGN_RSH ">>=")
3223 (cons js2-ASSIGN_URSH ">>>=")
3224 (cons js2-ASSIGN_ADD "+=")
3225 (cons js2-ASSIGN_SUB "-=")
3226 (cons js2-ASSIGN_MUL "*=")
3227 (cons js2-ASSIGN_DIV "/=")
3228 (cons js2-ASSIGN_MOD "%="))))
3229 (loop for (k . v) in tokens do
3230 (puthash k v table))
3231 table))
3232
3233 (defun js2-print-infix-node (n i)
3234 (let* ((tt (js2-node-type n))
3235 (op (gethash tt js2-operator-tokens)))
3236 (unless op
3237 (error "unrecognized infix operator %s" (js2-node-type n)))
3238 (insert (js2-make-pad i))
3239 (js2-print-ast (js2-infix-node-left n) 0)
3240 (unless (= tt js2-COMMA)
3241 (insert " "))
3242 (insert op)
3243 (insert " ")
3244 (js2-print-ast (js2-infix-node-right n) 0)))
3245
3246 (defstruct (js2-assign-node
3247 (:include js2-infix-node)
3248 (:constructor nil)
3249 (:constructor make-js2-assign-node (&key type
3250 (pos js2-ts-cursor)
3251 len
3252 op-pos
3253 left
3254 right)))
3255 "Represents any assignment.
3256 The type field holds the actual assignment operator.")
3257
3258 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3259 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3260
3261 (defstruct (js2-unary-node
3262 (:include js2-node)
3263 (:constructor nil)
3264 (:constructor make-js2-unary-node (&key type ; required
3265 (pos js2-ts-cursor)
3266 len
3267 operand)))
3268 "AST node type for unary operator nodes.
3269 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3270 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3271 property is added if the operator follows the operand."
3272 operand) ; a `js2-node' expression
3273
3274 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3275 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3276
3277 (defun js2-visit-unary-node (n v)
3278 (js2-visit-ast (js2-unary-node-operand n) v))
3279
3280 (defun js2-print-unary-node (n i)
3281 (let* ((tt (js2-node-type n))
3282 (op (gethash tt js2-operator-tokens))
3283 (postfix (js2-node-get-prop n 'postfix)))
3284 (unless op
3285 (error "unrecognized unary operator %s" tt))
3286 (insert (js2-make-pad i))
3287 (unless postfix
3288 (insert op))
3289 (if (or (= tt js2-TYPEOF)
3290 (= tt js2-DELPROP))
3291 (insert " "))
3292 (js2-print-ast (js2-unary-node-operand n) 0)
3293 (when postfix
3294 (insert op))))
3295
3296 (defstruct (js2-let-node
3297 (:include js2-scope)
3298 (:constructor nil)
3299 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3300 (pos js2-token-beg)
3301 len
3302 vars
3303 body
3304 lp
3305 rp)))
3306 "AST node for a let expression or a let statement.
3307 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3308 vars ; a `js2-var-decl-node'
3309 body ; a `js2-node' representing the expression or body block
3310 lp
3311 rp)
3312
3313 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3314 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3315
3316 (defun js2-visit-let-node (n v)
3317 (when (js2-let-node-vars n)
3318 (js2-visit-ast (js2-let-node-vars n) v))
3319 (when (js2-let-node-body n)
3320 (js2-visit-ast (js2-let-node-body n) v)))
3321
3322 (defun js2-print-let-node (n i)
3323 (insert (js2-make-pad i) "let (")
3324 (js2-print-ast (js2-let-node-vars n) 0)
3325 (insert ") ")
3326 (js2-print-ast (js2-let-node-body n) i))
3327
3328 (defstruct (js2-keyword-node
3329 (:include js2-node)
3330 (:constructor nil)
3331 (:constructor make-js2-keyword-node (&key type
3332 (pos js2-token-beg)
3333 (len (- js2-ts-cursor pos)))))
3334 "AST node representing a literal keyword such as `null'.
3335 Used for `null', `this', `true', `false' and `debugger'.
3336 The node type is set to js2-NULL, js2-THIS, etc.")
3337
3338 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3339 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3340
3341 (defun js2-print-keyword-node (n i)
3342 (insert (js2-make-pad i)
3343 (let ((tt (js2-node-type n)))
3344 (cond
3345 ((= tt js2-THIS) "this")
3346 ((= tt js2-NULL) "null")
3347 ((= tt js2-TRUE) "true")
3348 ((= tt js2-FALSE) "false")
3349 ((= tt js2-DEBUGGER) "debugger")
3350 (t (error "Invalid keyword literal type: %d" tt))))))
3351
3352 (defsubst js2-this-node-p (node)
3353 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3354 (eq (js2-node-type node) js2-THIS))
3355
3356 (defstruct (js2-new-node
3357 (:include js2-node)
3358 (:constructor nil)
3359 (:constructor make-js2-new-node (&key (type js2-NEW)
3360 (pos js2-token-beg)
3361 len
3362 target
3363 args
3364 initializer
3365 lp
3366 rp)))
3367 "AST node for new-expression such as new Foo()."
3368 target ; an identifier or reference
3369 args ; a lisp list of argument nodes
3370 lp ; position of left-paren, nil if omitted
3371 rp ; position of right-paren, nil if omitted
3372 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3373
3374 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3375 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3376
3377 (defun js2-visit-new-node (n v)
3378 (js2-visit-ast (js2-new-node-target n) v)
3379 (dolist (arg (js2-new-node-args n))
3380 (js2-visit-ast arg v))
3381 (when (js2-new-node-initializer n)
3382 (js2-visit-ast (js2-new-node-initializer n) v)))
3383
3384 (defun js2-print-new-node (n i)
3385 (insert (js2-make-pad i) "new ")
3386 (js2-print-ast (js2-new-node-target n))
3387 (insert "(")
3388 (js2-print-list (js2-new-node-args n))
3389 (insert ")")
3390 (when (js2-new-node-initializer n)
3391 (insert " ")
3392 (js2-print-ast (js2-new-node-initializer n))))
3393
3394 (defstruct (js2-name-node
3395 (:include js2-node)
3396 (:constructor nil)
3397 (:constructor make-js2-name-node (&key (type js2-NAME)
3398 (pos js2-token-beg)
3399 (len (- js2-ts-cursor
3400 js2-token-beg))
3401 (name js2-ts-string))))
3402 "AST node for a JavaScript identifier"
3403 name ; a string
3404 scope) ; a `js2-scope' (optional, used for codegen)
3405
3406 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3407 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3408
3409 (defun js2-print-name-node (n i)
3410 (insert (js2-make-pad i)
3411 (js2-name-node-name n)))
3412
3413 (defsubst js2-name-node-length (node)
3414 "Return identifier length of NODE, a `js2-name-node'.
3415 Returns 0 if NODE is nil or its identifier field is nil."
3416 (if node
3417 (length (js2-name-node-name node))
3418 0))
3419
3420 (defstruct (js2-number-node
3421 (:include js2-node)
3422 (:constructor nil)
3423 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3424 (pos js2-token-beg)
3425 (len (- js2-ts-cursor
3426 js2-token-beg))
3427 (value js2-ts-string)
3428 (num-value js2-ts-number))))
3429 "AST node for a number literal."
3430 value ; the original string, e.g. "6.02e23"
3431 num-value) ; the parsed number value
3432
3433 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3434 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3435
3436 (defun js2-print-number-node (n i)
3437 (insert (js2-make-pad i)
3438 (number-to-string (js2-number-node-num-value n))))
3439
3440 (defstruct (js2-regexp-node
3441 (:include js2-node)
3442 (:constructor nil)
3443 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3444 (pos js2-token-beg)
3445 (len (- js2-ts-cursor
3446 js2-token-beg))
3447 value
3448 flags)))
3449 "AST node for a regular expression literal."
3450 value ; the regexp string, without // delimiters
3451 flags) ; a string of flags, e.g. `mi'.
3452
3453 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3454 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3455
3456 (defun js2-print-regexp (n i)
3457 (insert (js2-make-pad i)
3458 "/"
3459 (js2-regexp-node-value n)
3460 "/")
3461 (if (js2-regexp-node-flags n)
3462 (insert (js2-regexp-node-flags n))))
3463
3464 (defstruct (js2-string-node
3465 (:include js2-node)
3466 (:constructor nil)
3467 (:constructor make-js2-string-node (&key (type js2-STRING)
3468 (pos js2-token-beg)
3469 (len (- js2-ts-cursor
3470 js2-token-beg))
3471 (value js2-ts-string))))
3472 "String literal.
3473 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3474 You can tell the quote type by looking at the first character."
3475 value) ; the characters of the string, including the quotes
3476
3477 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3478 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3479
3480 (defun js2-print-string-node (n i)
3481 (insert (js2-make-pad i)
3482 (js2-node-string n)))
3483
3484 (defstruct (js2-array-node
3485 (:include js2-node)
3486 (:constructor nil)
3487 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3488 (pos js2-ts-cursor)
3489 len
3490 elems)))
3491 "AST node for an array literal."
3492 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3493
3494 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3495 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3496
3497 (defun js2-visit-array-node (n v)
3498 (dolist (e (js2-array-node-elems n))
3499 (when e ; can be nil, e.g. [a, ,b]
3500 (js2-visit-ast e v))))
3501
3502 (defun js2-print-array-node (n i)
3503 (insert (js2-make-pad i) "[")
3504 (js2-print-list (js2-array-node-elems n))
3505 (insert "]"))
3506
3507 (defstruct (js2-object-node
3508 (:include js2-node)
3509 (:constructor nil)
3510 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3511 (pos js2-ts-cursor)
3512 len
3513 elems)))
3514 "AST node for an object literal expression."
3515 elems) ; a lisp list of `js2-object-prop-node'
3516
3517 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3518 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3519
3520 (defun js2-visit-object-node (n v)
3521 (dolist (e (js2-object-node-elems n))
3522 (js2-visit-ast e v)))
3523
3524 (defun js2-print-object-node (n i)
3525 (insert (js2-make-pad i) "{")
3526 (js2-print-list (js2-object-node-elems n))
3527 (insert "}"))
3528
3529 (defstruct (js2-object-prop-node
3530 (:include js2-infix-node)
3531 (:constructor nil)
3532 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3533 (pos js2-ts-cursor)
3534 len
3535 left
3536 right
3537 op-pos)))
3538 "AST node for an object literal prop:value entry.
3539 The `left' field is the property: a name node, string node or number node.
3540 The `right' field is a `js2-node' representing the initializer value.")
3541
3542 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3543 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3544
3545 (defun js2-print-object-prop-node (n i)
3546 (insert (js2-make-pad i))
3547 (js2-print-ast (js2-object-prop-node-left n) 0)
3548 (insert ":")
3549 (js2-print-ast (js2-object-prop-node-right n) 0))
3550
3551 (defstruct (js2-getter-setter-node
3552 (:include js2-infix-node)
3553 (:constructor nil)
3554 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3555 (pos js2-ts-cursor)
3556 len
3557 left
3558 right)))
3559 "AST node for a getter/setter property in an object literal.
3560 The `left' field is the `js2-name-node' naming the getter/setter prop.
3561 The `right' field is always an anonymous `js2-function-node' with a node
3562 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3563
3564 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3565 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3566
3567 (defun js2-print-getter-setter (n i)
3568 (let ((pad (js2-make-pad i))
3569 (left (js2-getter-setter-node-left n))
3570 (right (js2-getter-setter-node-right n)))
3571 (insert pad)
3572 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3573 (js2-print-ast left 0)
3574 (js2-print-ast right 0)))
3575
3576 (defstruct (js2-prop-get-node
3577 (:include js2-infix-node)
3578 (:constructor nil)
3579 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3580 (pos js2-ts-cursor)
3581 len
3582 left
3583 right)))
3584 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3585
3586 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3587 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3588
3589 (defun js2-visit-prop-get-node (n v)
3590 (when (js2-prop-get-node-left n)
3591 (js2-visit-ast (js2-prop-get-node-left n) v))
3592 (when (js2-prop-get-node-right n)
3593 (js2-visit-ast (js2-prop-get-node-right n) v)))
3594
3595 (defun js2-print-prop-get-node (n i)
3596 (insert (js2-make-pad i))
3597 (js2-print-ast (js2-prop-get-node-left n) 0)
3598 (insert ".")
3599 (js2-print-ast (js2-prop-get-node-right n) 0))
3600
3601 (defstruct (js2-elem-get-node
3602 (:include js2-node)
3603 (:constructor nil)
3604 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3605 (pos js2-ts-cursor)
3606 len
3607 target
3608 element
3609 lb
3610 rb)))
3611 "AST node for an array index expression such as foo[bar]."
3612 target ; a `js2-node' - the expression preceding the "."
3613 element ; a `js2-node' - the expression in brackets
3614 lb ; position of left-bracket, nil if omitted
3615 rb) ; position of right-bracket, nil if omitted
3616
3617 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3618 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3619
3620 (defun js2-visit-elem-get-node (n v)
3621 (when (js2-elem-get-node-target n)
3622 (js2-visit-ast (js2-elem-get-node-target n) v))
3623 (when (js2-elem-get-node-element n)
3624 (js2-visit-ast (js2-elem-get-node-element n) v)))
3625
3626 (defun js2-print-elem-get-node (n i)
3627 (insert (js2-make-pad i))
3628 (js2-print-ast (js2-elem-get-node-target n) 0)
3629 (insert "[")
3630 (js2-print-ast (js2-elem-get-node-element n) 0)
3631 (insert "]"))
3632
3633 (defstruct (js2-call-node
3634 (:include js2-node)
3635 (:constructor nil)
3636 (:constructor make-js2-call-node (&key (type js2-CALL)
3637 (pos js2-ts-cursor)
3638 len
3639 target
3640 args
3641 lp
3642 rp)))
3643 "AST node for a JavaScript function call."
3644 target ; a `js2-node' evaluating to the function to call
3645 args ; a lisp list of `js2-node' arguments
3646 lp ; position of open-paren, or nil if missing
3647 rp) ; position of close-paren, or nil if missing
3648
3649 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3650 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3651
3652 (defun js2-visit-call-node (n v)
3653 (js2-visit-ast (js2-call-node-target n) v)
3654 (dolist (arg (js2-call-node-args n))
3655 (js2-visit-ast arg v)))
3656
3657 (defun js2-print-call-node (n i)
3658 (insert (js2-make-pad i))
3659 (js2-print-ast (js2-call-node-target n) 0)
3660 (insert "(")
3661 (js2-print-list (js2-call-node-args n))
3662 (insert ")"))
3663
3664 (defstruct (js2-yield-node
3665 (:include js2-node)
3666 (:constructor nil)
3667 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3668 (pos js2-ts-cursor)
3669 len
3670 value)))
3671 "AST node for yield statement or expression."
3672 value) ; optional: value to be yielded
3673
3674 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3675 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3676
3677 (defun js2-visit-yield-node (n v)
3678 (js2-visit-ast (js2-yield-node-value n) v))
3679
3680 (defun js2-print-yield-node (n i)
3681 (insert (js2-make-pad i))
3682 (insert "yield")
3683 (when (js2-yield-node-value n)
3684 (insert " ")
3685 (js2-print-ast (js2-yield-node-value n) 0)))
3686
3687 (defstruct (js2-paren-node
3688 (:include js2-node)
3689 (:constructor nil)
3690 (:constructor make-js2-paren-node (&key (type js2-LP)
3691 (pos js2-ts-cursor)
3692 len
3693 expr)))
3694 "AST node for a parenthesized expression.
3695 In particular, used when the parens are syntactically optional,
3696 as opposed to required parens such as those enclosing an if-conditional."
3697 expr) ; `js2-node'
3698
3699 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3700 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3701
3702 (defun js2-visit-paren-node (n v)
3703 (js2-visit-ast (js2-paren-node-expr n) v))
3704
3705 (defun js2-print-paren-node (n i)
3706 (insert (js2-make-pad i))
3707 (insert "(")
3708 (js2-print-ast (js2-paren-node-expr n) 0)
3709 (insert ")"))
3710
3711 (defstruct (js2-array-comp-node
3712 (:include js2-scope)
3713 (:constructor nil)
3714 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3715 (pos js2-ts-cursor)
3716 len
3717 result
3718 loops
3719 filter
3720 if-pos
3721 lp
3722 rp)))
3723 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3724 result ; result expression (just after left-bracket)
3725 loops ; a lisp list of `js2-array-comp-loop-node'
3726 filter ; guard/filter expression
3727 if-pos ; buffer pos of 'if' keyword, if present, else nil
3728 lp ; buffer position of if-guard left-paren, or nil if not present
3729 rp) ; buffer position of if-guard right-paren, or nil if not present
3730
3731 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3732 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3733
3734 (defun js2-visit-array-comp-node (n v)
3735 (js2-visit-ast (js2-array-comp-node-result n) v)
3736 (dolist (l (js2-array-comp-node-loops n))
3737 (js2-visit-ast l v))
3738 (if (js2-array-comp-node-filter n)
3739 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3740
3741 (defun js2-print-array-comp-node (n i)
3742 (let ((pad (js2-make-pad i))
3743 (result (js2-array-comp-node-result n))
3744 (loops (js2-array-comp-node-loops n))
3745 (filter (js2-array-comp-node-filter n)))
3746 (insert pad "[")
3747 (js2-print-ast result 0)
3748 (dolist (l loops)
3749 (insert " ")
3750 (js2-print-ast l 0))
3751 (when filter
3752 (insert " if (")
3753 (js2-print-ast filter 0))
3754 (insert ")]")))
3755
3756 (defstruct (js2-array-comp-loop-node
3757 (:include js2-for-in-node)
3758 (:constructor nil)
3759 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3760 (pos js2-ts-cursor)
3761 len
3762 iterator
3763 object
3764 in-pos
3765 foreach-p
3766 each-pos
3767 lp
3768 rp)))
3769 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3770
3771 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3772 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3773
3774 (defun js2-visit-array-comp-loop (n v)
3775 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3776 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3777
3778 (defun js2-print-array-comp-loop (n i)
3779 (insert "for (")
3780 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3781 (insert " in ")
3782 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3783 (insert ")"))
3784
3785 (defstruct (js2-empty-expr-node
3786 (:include js2-node)
3787 (:constructor nil)
3788 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3789 (pos js2-token-beg)
3790 len)))
3791 "AST node for an empty expression.")
3792
3793 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3794 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3795
3796 (defstruct (js2-xml-node
3797 (:include js2-block-node)
3798 (:constructor nil)
3799 (:constructor make-js2-xml-node (&key (type js2-XML)
3800 (pos js2-token-beg)
3801 len
3802 kids)))
3803 "AST node for initial parse of E4X literals.
3804 The kids field is a list of XML fragments, each a `js2-string-node' or
3805 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3806
3807 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3808 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3809
3810 (defun js2-print-xml-node (n i)
3811 (dolist (kid (js2-xml-node-kids n))
3812 (js2-print-ast kid i)))
3813
3814 (defstruct (js2-xml-js-expr-node
3815 (:include js2-xml-node)
3816 (:constructor nil)
3817 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3818 (pos js2-ts-cursor)
3819 len
3820 expr)))
3821 "AST node for an embedded JavaScript {expression} in an E4X literal.
3822 The start and end fields correspond to the curly-braces."
3823 expr) ; a `js2-expr-node' of some sort
3824
3825 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3826 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3827
3828 (defun js2-visit-xml-js-expr (n v)
3829 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3830
3831 (defun js2-print-xml-js-expr (n i)
3832 (insert (js2-make-pad i))
3833 (insert "{")
3834 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3835 (insert "}"))
3836
3837 (defstruct (js2-xml-dot-query-node
3838 (:include js2-infix-node)
3839 (:constructor nil)
3840 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3841 (pos js2-ts-cursor)
3842 op-pos
3843 len
3844 left
3845 right
3846 rp)))
3847 "AST node for an E4X foo.(bar) filter expression.
3848 Note that the left-paren is automatically the character immediately
3849 following the dot (.) in the operator. No whitespace is permitted
3850 between the dot and the lp by the scanner."
3851 rp)
3852
3853 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3854 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3855
3856 (defun js2-print-xml-dot-query (n i)
3857 (insert (js2-make-pad i))
3858 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3859 (insert ".(")
3860 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3861 (insert ")"))
3862
3863 (defstruct (js2-xml-ref-node
3864 (:include js2-node)
3865 (:constructor nil)) ; abstract
3866 "Base type for E4X XML attribute-access or property-get expressions.
3867 Such expressions can take a variety of forms. The general syntax has
3868 three parts:
3869
3870 - (optional) an @ (specifying an attribute access)
3871 - (optional) a namespace (a `js2-name-node') and double-colon
3872 - (required) either a `js2-name-node' or a bracketed [expression]
3873
3874 The property-name expressions (examples: ns::name, @name) are
3875 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3876 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3877
3878 This node type (or more specifically, its subclasses) will sometimes
3879 be the right-hand child of a `js2-prop-get-node' or a
3880 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3881 The `js2-xml-ref-node' may also be a standalone primary expression with
3882 no explicit target, which is valid in certain expression contexts such as
3883
3884 company..employee.(@id < 100)
3885
3886 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3887 expression whose parent is a `js2-xml-dot-query-node'."
3888 namespace
3889 at-pos
3890 colon-pos)
3891
3892 (defsubst js2-xml-ref-node-attr-access-p (node)
3893 "Return non-nil if this expression began with an @-token."
3894 (and (numberp (js2-xml-ref-node-at-pos node))
3895 (plusp (js2-xml-ref-node-at-pos node))))
3896
3897 (defstruct (js2-xml-prop-ref-node
3898 (:include js2-xml-ref-node)
3899 (:constructor nil)
3900 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3901 (pos js2-token-beg)
3902 len
3903 propname
3904 namespace
3905 at-pos
3906 colon-pos)))
3907 "AST node for an E4X XML [expr] property-ref expression.
3908 The JavaScript syntax is an optional @, an optional ns::, and a name.
3909
3910 [ '@' ] [ name '::' ] name
3911
3912 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3913 @ns::*, @*::attr, @*::*, and @*.
3914
3915 The node starts at the @ token, if present. Otherwise it starts at the
3916 namespace name. The node bounds extend through the closing right-bracket,
3917 or if it is missing due to a syntax error, through the end of the index
3918 expression."
3919 propname)
3920
3921 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3922 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3923
3924 (defun js2-visit-xml-prop-ref-node (n v)
3925 (if (js2-xml-prop-ref-node-namespace n)
3926 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3927 (if (js2-xml-prop-ref-node-propname n)
3928 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3929
3930 (defun js2-print-xml-prop-ref-node (n i)
3931 (insert (js2-make-pad i))
3932 (if (js2-xml-ref-node-attr-access-p n)
3933 (insert "@"))
3934 (when (js2-xml-prop-ref-node-namespace n)
3935 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3936 (insert "::"))
3937 (if (js2-xml-prop-ref-node-propname n)
3938 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3939
3940 (defstruct (js2-xml-elem-ref-node
3941 (:include js2-xml-ref-node)
3942 (:constructor nil)
3943 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3944 (pos js2-token-beg)
3945 len
3946 expr
3947 lb
3948 rb
3949 namespace
3950 at-pos
3951 colon-pos)))
3952 "AST node for an E4X XML [expr] member-ref expression.
3953 Syntax:
3954
3955 [ '@' ] [ name '::' ] '[' expr ']'
3956
3957 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3958
3959 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3960 is not a legal E4X XML element-ref expression, since it's already used
3961 for standard JavaScript element-get array indexing. Hence, a
3962 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3963 non-nil namespace node, or both.
3964
3965 The node starts at the @ token, if present. Otherwise it starts
3966 at the namespace name. The node bounds extend through the closing
3967 right-bracket, or if it is missing due to a syntax error, through the
3968 end of the index expression."
3969 expr ; the bracketed index expression
3970 lb
3971 rb)
3972
3973 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3974 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3975
3976 (defun js2-visit-xml-elem-ref-node (n v)
3977 (if (js2-xml-elem-ref-node-namespace n)
3978 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
3979 (if (js2-xml-elem-ref-node-expr n)
3980 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
3981
3982 (defun js2-print-xml-elem-ref-node (n i)
3983 (insert (js2-make-pad i))
3984 (if (js2-xml-ref-node-attr-access-p n)
3985 (insert "@"))
3986 (when (js2-xml-elem-ref-node-namespace n)
3987 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3988 (insert "::"))
3989 (insert "[")
3990 (if (js2-xml-elem-ref-node-expr n)
3991 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3992 (insert "]"))
3993
3994 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3995
3996 (defstruct (js2-xml-start-tag-node
3997 (:include js2-xml-node)
3998 (:constructor nil)
3999 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4000 (pos js2-ts-cursor)
4001 len
4002 name
4003 attrs
4004 kids
4005 empty-p)))
4006 "AST node for an XML start-tag. Not currently used.
4007 The `kids' field is a lisp list of child content nodes."
4008 name ; a `js2-xml-name-node'
4009 attrs ; a lisp list of `js2-xml-attr-node'
4010 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4011
4012 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4013 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4014
4015 (defun js2-visit-xml-start-tag (n v)
4016 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4017 (dolist (attr (js2-xml-start-tag-node-attrs n))
4018 (js2-visit-ast attr v))
4019 (js2-visit-block n v))
4020
4021 (defun js2-print-xml-start-tag (n i)
4022 (insert (js2-make-pad i) "<")
4023 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4024 (when (js2-xml-start-tag-node-attrs n)
4025 (insert " ")
4026 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4027 (insert ">"))
4028
4029 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4030 ;; and add the end-tag to the kids list of the parent as well.
4031 (defstruct (js2-xml-end-tag-node
4032 (:include js2-xml-node)
4033 (:constructor nil)
4034 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4035 (pos js2-ts-cursor)
4036 len
4037 name)))
4038 "AST node for an XML end-tag. Not currently used."
4039 name) ; a `js2-xml-name-node'
4040
4041 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4042 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4043
4044 (defun js2-visit-xml-end-tag (n v)
4045 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4046
4047 (defun js2-print-xml-end-tag (n i)
4048 (insert (js2-make-pad i))
4049 (insert "</")
4050 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4051 (insert ">"))
4052
4053 (defstruct (js2-xml-name-node
4054 (:include js2-xml-node)
4055 (:constructor nil)
4056 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4057 (pos js2-ts-cursor)
4058 len
4059 namespace
4060 kids)))
4061 "AST node for an E4X XML name. Not currently used.
4062 Any XML name can be qualified with a namespace, hence the namespace field.
4063 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4064 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4065 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4066 namespace) ; a `js2-string-node'
4067
4068 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4069 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4070
4071 (defun js2-visit-xml-name-node (n v)
4072 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4073
4074 (defun js2-print-xml-name-node (n i)
4075 (insert (js2-make-pad i))
4076 (when (js2-xml-name-node-namespace n)
4077 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4078 (insert "::"))
4079 (dolist (kid (js2-xml-name-node-kids n))
4080 (js2-print-ast kid 0)))
4081
4082 (defstruct (js2-xml-pi-node
4083 (:include js2-xml-node)
4084 (:constructor nil)
4085 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4086 (pos js2-ts-cursor)
4087 len
4088 name
4089 attrs)))
4090 "AST node for an E4X XML processing instruction. Not currently used."
4091 name ; a `js2-xml-name-node'
4092 attrs) ; a list of `js2-xml-attr-node'
4093
4094 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4095 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4096
4097 (defun js2-visit-xml-pi-node (n v)
4098 (js2-visit-ast (js2-xml-pi-node-name n) v)
4099 (dolist (attr (js2-xml-pi-node-attrs n))
4100 (js2-visit-ast attr v)))
4101
4102 (defun js2-print-xml-pi-node (n i)
4103 (insert (js2-make-pad i) "<?")
4104 (js2-print-ast (js2-xml-pi-node-name n))
4105 (when (js2-xml-pi-node-attrs n)
4106 (insert " ")
4107 (js2-print-list (js2-xml-pi-node-attrs n)))
4108 (insert "?>"))
4109
4110 (defstruct (js2-xml-cdata-node
4111 (:include js2-xml-node)
4112 (:constructor nil)
4113 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4114 (pos js2-ts-cursor)
4115 len
4116 content)))
4117 "AST node for a CDATA escape section. Not currently used."
4118 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4119
4120 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4121 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4122
4123 (defun js2-visit-xml-cdata-node (n v)
4124 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4125
4126 (defun js2-print-xml-cdata-node (n i)
4127 (insert (js2-make-pad i))
4128 (js2-print-ast (js2-xml-cdata-node-content n)))
4129
4130 (defstruct (js2-xml-attr-node
4131 (:include js2-xml-node)
4132 (:constructor nil)
4133 (:constructor make-js2-attr-node (&key (type js2-XML)
4134 (pos js2-ts-cursor)
4135 len
4136 name
4137 value
4138 eq-pos
4139 quote-type)))
4140 "AST node representing a foo='bar' XML attribute value. Not yet used."
4141 name ; a `js2-xml-name-node'
4142 value ; a `js2-xml-name-node'
4143 eq-pos ; buffer position of "=" sign
4144 quote-type) ; 'single or 'double
4145
4146 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4147 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4148
4149 (defun js2-visit-xml-attr-node (n v)
4150 (js2-visit-ast (js2-xml-attr-node-name n) v)
4151 (js2-visit-ast (js2-xml-attr-node-value n) v))
4152
4153 (defun js2-print-xml-attr-node (n i)
4154 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4155 "'"
4156 "\"")))
4157 (insert (js2-make-pad i))
4158 (js2-print-ast (js2-xml-attr-node-name n) 0)
4159 (insert "=" quote)
4160 (js2-print-ast (js2-xml-attr-node-value n) 0)
4161 (insert quote)))
4162
4163 (defstruct (js2-xml-text-node
4164 (:include js2-xml-node)
4165 (:constructor nil)
4166 (:constructor make-js2-text-node (&key (type js2-XML)
4167 (pos js2-ts-cursor)
4168 len
4169 content)))
4170 "AST node for an E4X XML text node. Not currently used."
4171 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4172
4173 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4174 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4175
4176 (defun js2-visit-xml-text-node (n v)
4177 (js2-visit-ast (js2-xml-text-node-content n) v))
4178
4179 (defun js2-print-xml-text-node (n i)
4180 (insert (js2-make-pad i))
4181 (dolist (kid (js2-xml-text-node-content n))
4182 (js2-print-ast kid)))
4183
4184 (defstruct (js2-xml-comment-node
4185 (:include js2-xml-node)
4186 (:constructor nil)
4187 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4188 (pos js2-ts-cursor)
4189 len)))
4190 "AST node for E4X XML comment. Not currently used.")
4191
4192 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4193 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4194
4195 (defun js2-print-xml-comment (n i)
4196 (insert (js2-make-pad i)
4197 (js2-node-string n)))
4198
4199 ;;; Node utilities
4200
4201 (defsubst js2-node-line (n)
4202 "Fetch the source line number at the start of node N.
4203 This is O(n) in the length of the source buffer; use prudently."
4204 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4205
4206 (defsubst js2-block-node-kid (n i)
4207 "Return child I of node N, or nil if there aren't that many."
4208 (nth i (js2-block-node-kids n)))
4209
4210 (defsubst js2-block-node-first (n)
4211 "Return first child of block node N, or nil if there is none."
4212 (first (js2-block-node-kids n)))
4213
4214 (defun js2-node-root (n)
4215 "Return the root of the AST containing N.
4216 If N has no parent pointer, returns N."
4217 (let ((parent (js2-node-parent n)))
4218 (if parent
4219 (js2-node-root parent)
4220 n)))
4221
4222 (defun js2-node-position-in-parent (node &optional parent)
4223 "Return the position of NODE in parent's block-kids list.
4224 PARENT can be supplied if known. Positioned returned is zero-indexed.
4225 Returns 0 if NODE is not a child of a block statement, or if NODE
4226 is not a statement node."
4227 (let ((p (or parent (js2-node-parent node)))
4228 (i 0))
4229 (if (not (js2-block-node-p p))
4230 i
4231 (or (js2-position node (js2-block-node-kids p))
4232 0))))
4233
4234 (defsubst js2-node-short-name (n)
4235 "Return the short name of node N as a string, e.g. `js2-if-node'."
4236 (substring (symbol-name (aref n 0))
4237 (length "cl-struct-")))
4238
4239 (defsubst js2-node-child-list (node)
4240 "Return the child list for NODE, a lisp list of nodes.
4241 Works for block nodes, array nodes, obj literals, funarg lists,
4242 var decls and try nodes (for catch clauses). Note that you should call
4243 `js2-block-node-kids' on the function body for the body statements.
4244 Returns nil for zero-length child lists or unsupported nodes."
4245 (cond
4246 ((js2-function-node-p node)
4247 (js2-function-node-params node))
4248 ((js2-block-node-p node)
4249 (js2-block-node-kids node))
4250 ((js2-try-node-p node)
4251 (js2-try-node-catch-clauses node))
4252 ((js2-array-node-p node)
4253 (js2-array-node-elems node))
4254 ((js2-object-node-p node)
4255 (js2-object-node-elems node))
4256 ((js2-call-node-p node)
4257 (js2-call-node-args node))
4258 ((js2-new-node-p node)
4259 (js2-new-node-args node))
4260 ((js2-var-decl-node-p node)
4261 (js2-var-decl-node-kids node))
4262 (t
4263 nil)))
4264
4265 (defsubst js2-node-set-child-list (node kids)
4266 "Set the child list for NODE to KIDS."
4267 (cond
4268 ((js2-function-node-p node)
4269 (setf (js2-function-node-params node) kids))
4270 ((js2-block-node-p node)
4271 (setf (js2-block-node-kids node) kids))
4272 ((js2-try-node-p node)
4273 (setf (js2-try-node-catch-clauses node) kids))
4274 ((js2-array-node-p node)
4275 (setf (js2-array-node-elems node) kids))
4276 ((js2-object-node-p node)
4277 (setf (js2-object-node-elems node) kids))
4278 ((js2-call-node-p node)
4279 (setf (js2-call-node-args node) kids))
4280 ((js2-new-node-p node)
4281 (setf (js2-new-node-args node) kids))
4282 ((js2-var-decl-node-p node)
4283 (setf (js2-var-decl-node-kids node) kids))
4284 (t
4285 (error "Unsupported node type: %s" (js2-node-short-name node))))
4286 kids)
4287
4288 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4289 (defconst js2-paren-expr-nodes
4290 '(cl-struct-js2-array-comp-loop-node
4291 cl-struct-js2-array-comp-node
4292 cl-struct-js2-call-node
4293 cl-struct-js2-catch-node
4294 cl-struct-js2-do-node
4295 cl-struct-js2-elem-get-node
4296 cl-struct-js2-for-in-node
4297 cl-struct-js2-for-node
4298 cl-struct-js2-function-node
4299 cl-struct-js2-if-node
4300 cl-struct-js2-let-node
4301 cl-struct-js2-new-node
4302 cl-struct-js2-paren-node
4303 cl-struct-js2-switch-node
4304 cl-struct-js2-while-node
4305 cl-struct-js2-with-node
4306 cl-struct-js2-xml-dot-query-node)
4307 "Node types that can have a parenthesized child expression.
4308 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4309
4310 (defsubst js2-paren-expr-node-p (node)
4311 "Return t for nodes that typically have a parenthesized child expression.
4312 Useful for computing the indentation anchors for arg-lists and conditions.
4313 Note that it may return a false positive, for instance when NODE is
4314 a `js2-new-node' and there are no arguments or parentheses."
4315 (memq (aref node 0) js2-paren-expr-nodes))
4316
4317 ;; Fake polymorphism... yech.
4318 (defsubst js2-node-lp (node)
4319 "Return relative left-paren position for NODE, if applicable.
4320 For `js2-elem-get-node' structs, returns left-bracket position.
4321 Note that the position may be nil in the case of a parse error."
4322 (cond
4323 ((js2-elem-get-node-p node)
4324 (js2-elem-get-node-lb node))
4325 ((js2-loop-node-p node)
4326 (js2-loop-node-lp node))
4327 ((js2-function-node-p node)
4328 (js2-function-node-lp node))
4329 ((js2-if-node-p node)
4330 (js2-if-node-lp node))
4331 ((js2-new-node-p node)
4332 (js2-new-node-lp node))
4333 ((js2-call-node-p node)
4334 (js2-call-node-lp node))
4335 ((js2-paren-node-p node)
4336 (js2-node-pos node))
4337 ((js2-switch-node-p node)
4338 (js2-switch-node-lp node))
4339 ((js2-catch-node-p node)
4340 (js2-catch-node-lp node))
4341 ((js2-let-node-p node)
4342 (js2-let-node-lp node))
4343 ((js2-array-comp-node-p node)
4344 (js2-array-comp-node-lp node))
4345 ((js2-with-node-p node)
4346 (js2-with-node-lp node))
4347 ((js2-xml-dot-query-node-p node)
4348 (1+ (js2-infix-node-op-pos node)))
4349 (t
4350 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4351
4352 ;; Fake polymorphism... blech.
4353 (defsubst js2-node-rp (node)
4354 "Return relative right-paren position for NODE, if applicable.
4355 For `js2-elem-get-node' structs, returns right-bracket position.
4356 Note that the position may be nil in the case of a parse error."
4357 (cond
4358 ((js2-elem-get-node-p node)
4359 (js2-elem-get-node-lb node))
4360 ((js2-loop-node-p node)
4361 (js2-loop-node-rp node))
4362 ((js2-function-node-p node)
4363 (js2-function-node-rp node))
4364 ((js2-if-node-p node)
4365 (js2-if-node-rp node))
4366 ((js2-new-node-p node)
4367 (js2-new-node-rp node))
4368 ((js2-call-node-p node)
4369 (js2-call-node-rp node))
4370 ((js2-paren-node-p node)
4371 (+ (js2-node-pos node) (js2-node-len node)))
4372 ((js2-switch-node-p node)
4373 (js2-switch-node-rp node))
4374 ((js2-catch-node-p node)
4375 (js2-catch-node-rp node))
4376 ((js2-let-node-p node)
4377 (js2-let-node-rp node))
4378 ((js2-array-comp-node-p node)
4379 (js2-array-comp-node-rp node))
4380 ((js2-with-node-p node)
4381 (js2-with-node-rp node))
4382 ((js2-xml-dot-query-node-p node)
4383 (1+ (js2-xml-dot-query-node-rp node)))
4384 (t
4385 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4386
4387 (defsubst js2-node-first-child (node)
4388 "Returns the first element of `js2-node-child-list' for NODE."
4389 (car (js2-node-child-list node)))
4390
4391 (defsubst js2-node-last-child (node)
4392 "Returns the last element of `js2-node-last-child' for NODE."
4393 (car (last (js2-node-child-list node))))
4394
4395 (defun js2-node-prev-sibling (node)
4396 "Return the previous statement in parent.
4397 Works for parents supported by `js2-node-child-list'.
4398 Returns nil if NODE is not in the parent, or PARENT is
4399 not a supported node, or if NODE is the first child."
4400 (let* ((p (js2-node-parent node))
4401 (kids (js2-node-child-list p))
4402 (sib (car kids)))
4403 (while (and kids
4404 (not (eq node (cadr kids))))
4405 (setq kids (cdr kids)
4406 sib (car kids)))
4407 sib))
4408
4409 (defun js2-node-next-sibling (node)
4410 "Return the next statement in parent block.
4411 Returns nil if NODE is not in the block, or PARENT is not
4412 a block node, or if NODE is the last statement."
4413 (let* ((p (js2-node-parent node))
4414 (kids (js2-node-child-list p)))
4415 (while (and kids
4416 (not (eq node (car kids))))
4417 (setq kids (cdr kids)))
4418 (cadr kids)))
4419
4420 (defun js2-node-find-child-before (pos parent &optional after)
4421 "Find the last child that starts before POS in parent.
4422 If AFTER is non-nil, returns first child starting after POS.
4423 POS is an absolute buffer position. PARENT is any node
4424 supported by `js2-node-child-list'.
4425 Returns nil if no applicable child is found."
4426 (let ((kids (if (js2-function-node-p parent)
4427 (js2-block-node-kids (js2-function-node-body parent))
4428 (js2-node-child-list parent)))
4429 (beg (if (js2-function-node-p parent)
4430 (js2-node-abs-pos (js2-function-node-body parent))
4431 (js2-node-abs-pos parent)))
4432 kid
4433 result
4434 fn
4435 (continue t))
4436 (setq fn (if after '> '<))
4437 (while (and kids continue)
4438 (setq kid (car kids))
4439 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4440 (setq result kid
4441 continue (if after nil t))
4442 (setq continue (if after t nil)))
4443 (setq kids (cdr kids)))
4444 result))
4445
4446 (defun js2-node-find-child-after (pos parent)
4447 "Find first child that starts after POS in parent.
4448 POS is an absolute buffer position. PARENT is any node
4449 supported by `js2-node-child-list'.
4450 Returns nil if no applicable child is found."
4451 (js2-node-find-child-before pos parent 'after))
4452
4453 (defun js2-node-replace-child (pos parent new-node)
4454 "Replace node at index POS in PARENT with NEW-NODE.
4455 Only works for parents supported by `js2-node-child-list'."
4456 (let ((kids (js2-node-child-list parent))
4457 (i 0))
4458 (while (< i pos)
4459 (setq kids (cdr kids)
4460 i (1+ i)))
4461 (setcar kids new-node)
4462 (js2-node-add-children parent new-node)))
4463
4464 (defun js2-node-buffer (n)
4465 "Return the buffer associated with AST N.
4466 Returns nil if the buffer is not set as a property on the root
4467 node, or if parent links were not recorded during parsing."
4468 (let ((root (js2-node-root n)))
4469 (and root
4470 (js2-ast-root-p root)
4471 (js2-ast-root-buffer root))))
4472
4473 (defsubst js2-block-node-push (n kid)
4474 "Push js2-node KID onto the end of js2-block-node N's child list.
4475 KID is always added to the -end- of the kids list.
4476 Function also calls `js2-node-add-children' to add the parent link."
4477 (let ((kids (js2-node-child-list n)))
4478 (if kids
4479 (setcdr kids (nconc (cdr kids) (list kid)))
4480 (js2-node-set-child-list n (list kid)))
4481 (js2-node-add-children n kid)))
4482
4483 (defun js2-node-string (node)
4484 (let ((buf (js2-node-buffer node))
4485 pos)
4486 (unless buf
4487 (error "No buffer available for node %s" node))
4488 (save-excursion
4489 (set-buffer buf)
4490 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4491 (+ pos (js2-node-len node))))))
4492
4493 ;; Container for storing the node we're looking for in a traversal.
4494 (js2-deflocal js2-discovered-node nil)
4495
4496 ;; Keep track of absolute node position during traversals.
4497 (js2-deflocal js2-visitor-offset nil)
4498
4499 (js2-deflocal js2-node-search-point nil)
4500
4501 (when js2-mode-dev-mode-p
4502 (defun js2-find-node-at-point ()
4503 (interactive)
4504 (let ((node (js2-node-at-point)))
4505 (message "%s" (or node "No node found at point"))))
4506 (defun js2-node-name-at-point ()
4507 (interactive)
4508 (let ((node (js2-node-at-point)))
4509 (message "%s" (if node
4510 (js2-node-short-name node)
4511 "No node found at point.")))))
4512
4513 (defun js2-node-at-point (&optional pos skip-comments)
4514 "Return AST node at POS, a buffer position, defaulting to current point.
4515 The `js2-mode-ast' variable must be set to the current parse tree.
4516 Signals an error if the AST (`js2-mode-ast') is nil.
4517 Always returns a node - if it can't find one, it returns the root.
4518 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4519 (let ((ast js2-mode-ast)
4520 result)
4521 (unless ast
4522 (error "No JavaScript AST available"))
4523 ;; Look through comments first, since they may be inside nodes that
4524 ;; would otherwise report a match.
4525 (setq pos (or pos (point))
4526 result (if (> pos (js2-node-abs-end ast))
4527 ast
4528 (if (not skip-comments)
4529 (js2-comment-at-point pos))))
4530 (unless result
4531 (setq js2-discovered-node nil
4532 js2-visitor-offset 0
4533 js2-node-search-point pos)
4534 (unwind-protect
4535 (catch 'js2-visit-done
4536 (js2-visit-ast ast #'js2-node-at-point-visitor))
4537 (setq js2-visitor-offset nil
4538 js2-node-search-point nil))
4539 (setq result js2-discovered-node))
4540 ;; may have found a comment beyond end of last child node,
4541 ;; since visiting the ast-root looks at the comment-list last.
4542 (if (and skip-comments
4543 (js2-comment-node-p result))
4544 (setq result nil))
4545 (or result js2-mode-ast)))
4546
4547 (defun js2-node-at-point-visitor (node end-p)
4548 (let ((rel-pos (js2-node-pos node))
4549 abs-pos
4550 abs-end
4551 (point js2-node-search-point))
4552 (cond
4553 (end-p
4554 ;; this evaluates to a non-nil return value, even if it's zero
4555 (decf js2-visitor-offset rel-pos))
4556 ;; we already looked for comments before visiting, and don't want them now
4557 ((js2-comment-node-p node)
4558 nil)
4559 (t
4560 (setq abs-pos (incf js2-visitor-offset rel-pos)
4561 ;; we only want to use the node if the point is before
4562 ;; the last character position in the node, so we decrement
4563 ;; the absolute end by 1.
4564 abs-end (+ abs-pos (js2-node-len node) -1))
4565 (cond
4566 ;; If this node starts after search-point, stop the search.
4567 ((> abs-pos point)
4568 (throw 'js2-visit-done nil))
4569 ;; If this node ends before the search-point, don't check kids.
4570 ((> point abs-end)
4571 nil)
4572 (t
4573 ;; Otherwise point is within this node, possibly in a child.
4574 (setq js2-discovered-node node)
4575 t)))))) ; keep processing kids to look for more specific match
4576
4577 (defsubst js2-block-comment-p (node)
4578 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4579 (and (js2-comment-node-p node)
4580 (memq (js2-comment-node-format node) '(jsdoc block))))
4581
4582 ;; TODO: put the comments in a vector and binary-search them instead
4583 (defun js2-comment-at-point (&optional pos)
4584 "Look through scanned comment nodes for one containing POS.
4585 POS is a buffer position that defaults to current point.
4586 Function returns nil if POS was not in any comment node."
4587 (let ((ast js2-mode-ast)
4588 (x (or pos (point)))
4589 beg
4590 end)
4591 (unless ast
4592 (error "No JavaScript AST available"))
4593 (catch 'done
4594 ;; Comments are stored in lexical order.
4595 (dolist (comment (js2-ast-root-comments ast) nil)
4596 (setq beg (js2-node-abs-pos comment)
4597 end (+ beg (js2-node-len comment)))
4598 (if (and (>= x beg)
4599 (<= x end))
4600 (throw 'done comment))))))
4601
4602 (defun js2-mode-find-parent-fn (node)
4603 "Find function enclosing NODE.
4604 Returns nil if NODE is not inside a function."
4605 (setq node (js2-node-parent node))
4606 (while (and node (not (js2-function-node-p node)))
4607 (setq node (js2-node-parent node)))
4608 (and (js2-function-node-p node) node))
4609
4610 (defun js2-mode-find-enclosing-fn (node)
4611 "Find function or root enclosing NODE."
4612 (if (js2-ast-root-p node)
4613 node
4614 (setq node (js2-node-parent node))
4615 (while (not (or (js2-ast-root-p node)
4616 (js2-function-node-p node)))
4617 (setq node (js2-node-parent node)))
4618 node))
4619
4620 (defun js2-mode-find-enclosing-node (beg end)
4621 "Find script or function fully enclosing BEG and END."
4622 (let ((node (js2-node-at-point beg))
4623 pos
4624 (continue t))
4625 (while continue
4626 (if (or (js2-ast-root-p node)
4627 (and (js2-function-node-p node)
4628 (<= (setq pos (js2-node-abs-pos node)) beg)
4629 (>= (+ pos (js2-node-len node)) end)))
4630 (setq continue nil)
4631 (setq node (js2-node-parent node))))
4632 node))
4633
4634 (defun js2-node-parent-script-or-fn (node)
4635 "Find script or function immediately enclosing NODE.
4636 If NODE is the ast-root, returns nil."
4637 (if (js2-ast-root-p node)
4638 nil
4639 (setq node (js2-node-parent node))
4640 (while (and node (not (or (js2-function-node-p node)
4641 (js2-script-node-p node))))
4642 (setq node (js2-node-parent node)))
4643 node))
4644
4645 (defsubst js2-nested-function-p (node)
4646 "Return t if NODE is a nested function, or is inside a nested function."
4647 (js2-function-node-p (if (js2-function-node-p node)
4648 (js2-node-parent-script-or-fn node)
4649 (js2-node-parent-script-or-fn
4650 (js2-node-parent-script-or-fn node)))))
4651
4652 (defsubst js2-function-param-node-p (node)
4653 "Return non-nil if NODE is a param node of a `js2-function-node'."
4654 (let ((parent (js2-node-parent node)))
4655 (and parent
4656 (js2-function-node-p parent)
4657 (memq node (js2-function-node-params parent)))))
4658
4659 (defsubst js2-mode-shift-kids (kids start offset)
4660 (dolist (kid kids)
4661 (if (> (js2-node-pos kid) start)
4662 (incf (js2-node-pos kid) offset))))
4663
4664 (defsubst js2-mode-shift-children (parent start offset)
4665 "Update start-positions of all children of PARENT beyond START."
4666 (let ((root (js2-node-root parent)))
4667 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4668 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4669
4670 (defsubst js2-node-is-descendant (node ancestor)
4671 "Return t if NODE is a descendant of ANCESTOR."
4672 (while (and node
4673 (not (eq node ancestor)))
4674 (setq node (js2-node-parent node)))
4675 node)
4676
4677 ;;; visitor infrastructure
4678
4679 (defun js2-visit-none (node callback)
4680 "Visitor for AST node that have no node children."
4681 nil)
4682
4683 (defun js2-print-none (node indent)
4684 "Visitor for AST node with no printed representation.")
4685
4686 (defun js2-print-body (node indent)
4687 "Print a statement, or a block without braces."
4688 (if (js2-block-node-p node)
4689 (dolist (kid (js2-block-node-kids node))
4690 (js2-print-ast kid indent))
4691 (js2-print-ast node indent)))
4692
4693 (defun js2-print-list (args &optional delimiter)
4694 (loop with len = (length args)
4695 for arg in args
4696 for count from 1
4697 do
4698 (js2-print-ast arg 0)
4699 (if (< count len)
4700 (insert (or delimiter ", ")))))
4701
4702 (defun js2-print-tree (ast)
4703 "Prints an AST to the current buffer.
4704 Makes `js2-ast-parent-nodes' available to the printer functions."
4705 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4706 (js2-print-ast ast)))
4707
4708 (defun js2-print-ast (node &optional indent)
4709 "Helper function for printing AST nodes.
4710 Requires `js2-ast-parent-nodes' to be non-nil.
4711 You should use `js2-print-tree' instead of this function."
4712 (let ((printer (get (aref node 0) 'js2-printer))
4713 (i (or indent 0))
4714 (pos (js2-node-abs-pos node)))
4715 ;; TODO: wedge comments in here somewhere
4716 (if printer
4717 (funcall printer node i))))
4718
4719 (defconst js2-side-effecting-tokens
4720 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4721 (dolist (tt (list js2-ASSIGN
4722 js2-ASSIGN_ADD
4723 js2-ASSIGN_BITAND
4724 js2-ASSIGN_BITOR
4725 js2-ASSIGN_BITXOR
4726 js2-ASSIGN_DIV
4727 js2-ASSIGN_LSH
4728 js2-ASSIGN_MOD
4729 js2-ASSIGN_MUL
4730 js2-ASSIGN_RSH
4731 js2-ASSIGN_SUB
4732 js2-ASSIGN_URSH
4733 js2-BLOCK
4734 js2-BREAK
4735 js2-CALL
4736 js2-CATCH
4737 js2-CATCH_SCOPE
4738 js2-CONST
4739 js2-CONTINUE
4740 js2-DEBUGGER
4741 js2-DEC
4742 js2-DELPROP
4743 js2-DEL_REF
4744 js2-DO
4745 js2-ELSE
4746 js2-EMPTY
4747 js2-ENTERWITH
4748 js2-EXPORT
4749 js2-EXPR_RESULT
4750 js2-FINALLY
4751 js2-FOR
4752 js2-FUNCTION
4753 js2-GOTO
4754 js2-IF
4755 js2-IFEQ
4756 js2-IFNE
4757 js2-IMPORT
4758 js2-INC
4759 js2-JSR
4760 js2-LABEL
4761 js2-LEAVEWITH
4762 js2-LET
4763 js2-LETEXPR
4764 js2-LOCAL_BLOCK
4765 js2-LOOP
4766 js2-NEW
4767 js2-REF_CALL
4768 js2-RETHROW
4769 js2-RETURN
4770 js2-RETURN_RESULT
4771 js2-SEMI
4772 js2-SETELEM
4773 js2-SETELEM_OP
4774 js2-SETNAME
4775 js2-SETPROP
4776 js2-SETPROP_OP
4777 js2-SETVAR
4778 js2-SET_REF
4779 js2-SET_REF_OP
4780 js2-SWITCH
4781 js2-TARGET
4782 js2-THROW
4783 js2-TRY
4784 js2-VAR
4785 js2-WHILE
4786 js2-WITH
4787 js2-WITHEXPR
4788 js2-YIELD))
4789 (aset tokens tt t))
4790 (if js2-instanceof-has-side-effects
4791 (aset tokens js2-INSTANCEOF t))
4792 tokens))
4793
4794 (defun js2-node-has-side-effects (node)
4795 "Return t if NODE has side effects."
4796 (when node ; makes it easier to handle malformed expressions
4797 (let ((tt (js2-node-type node)))
4798 (cond
4799 ;; This doubtless needs some work, since EXPR_VOID is used
4800 ;; in several ways in Rhino, and I may not have caught them all.
4801 ;; I'll wait for people to notice incorrect warnings.
4802 ((and (= tt js2-EXPR_VOID)
4803 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4804 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4805 ((= tt js2-COMMA)
4806 (js2-node-has-side-effects (js2-infix-node-right node)))
4807 ((or (= tt js2-AND)
4808 (= tt js2-OR))
4809 (or (js2-node-has-side-effects (js2-infix-node-right node))
4810 (js2-node-has-side-effects (js2-infix-node-left node))))
4811 ((= tt js2-HOOK)
4812 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4813 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4814 ((js2-paren-node-p node)
4815 (js2-node-has-side-effects (js2-paren-node-expr node)))
4816 ((= tt js2-ERROR) ; avoid cascaded error messages
4817 nil)
4818 (t
4819 (aref js2-side-effecting-tokens tt))))))
4820
4821 (defun js2-member-expr-leftmost-name (node)
4822 "For an expr such as foo.bar.baz, return leftmost node foo.
4823 NODE is any `js2-node' object. If it represents a member expression,
4824 which is any sequence of property gets, element-gets, function calls,
4825 or xml descendants/filter operators, then we look at the lexically
4826 leftmost (first) node in the chain. If it is a name-node we return it.
4827 Note that NODE can be a raw name-node and it will be returned as well.
4828 If NODE is not a name-node or member expression, or if it is a member
4829 expression whose leftmost target is not a name node, returns nil."
4830 (let ((continue t)
4831 result)
4832 (while (and continue (not result))
4833 (cond
4834 ((js2-name-node-p node)
4835 (setq result node))
4836 ((js2-prop-get-node-p node)
4837 (setq node (js2-prop-get-node-left node)))
4838 ;; TODO: handle call-nodes, xml-nodes, others?
4839 (t
4840 (setq continue nil))))
4841 result))
4842
4843 (defconst js2-stmt-node-types
4844 (list js2-BLOCK
4845 js2-BREAK
4846 js2-CONTINUE
4847 js2-DEFAULT ; e4x "default xml namespace" statement
4848 js2-DO
4849 js2-EXPR_RESULT
4850 js2-EXPR_VOID
4851 js2-FOR
4852 js2-IF
4853 js2-RETURN
4854 js2-SWITCH
4855 js2-THROW
4856 js2-TRY
4857 js2-WHILE
4858 js2-WITH)
4859 "Node types that only appear in statement contexts.
4860 The list does not include nodes that always appear as the child
4861 of another specific statement type, such as switch-cases,
4862 catch and finally blocks, and else-clauses. The list also excludes
4863 nodes like yield, let and var, which may appear in either expression
4864 or statement context, and in the latter context always have a
4865 `js2-expr-stmt-node' parent. Finally, the list does not include
4866 functions or scripts, which are treated separately from statements
4867 by the JavaScript parser and runtime.")
4868
4869 (defun js2-stmt-node-p (node)
4870 "Heuristic for figuring out if NODE is a statement.
4871 Some node types can appear in either an expression context or a
4872 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4873 For these node types in a statement context, the parent will be a
4874 `js2-expr-stmt-node'.
4875 Functions aren't included in the check."
4876 (memq (js2-node-type node) js2-stmt-node-types))
4877
4878 (defsubst js2-mode-find-first-stmt (node)
4879 "Search upward starting from NODE looking for a statement.
4880 For purposes of this function, a `js2-function-node' counts."
4881 (while (not (or (js2-stmt-node-p node)
4882 (js2-function-node-p node)))
4883 (setq node (js2-node-parent node)))
4884 node)
4885
4886 (defun js2-node-parent-stmt (node)
4887 "Return the node's first ancestor that is a statement.
4888 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4889 appearing in a statement context will have a parent that is a
4890 `js2-expr-stmt-node' that will be returned by this function."
4891 (let ((parent (js2-node-parent node)))
4892 (if (or (null parent)
4893 (js2-stmt-node-p parent)
4894 (and (js2-function-node-p parent)
4895 (not (eq (js2-function-node-form parent)
4896 'FUNCTION_EXPRESSION))))
4897 parent
4898 (js2-node-parent-stmt parent))))
4899
4900 ;; In the Mozilla Rhino sources, Roshan James writes:
4901 ;; Does consistent-return analysis on the function body when strict mode is
4902 ;; enabled.
4903 ;;
4904 ;; function (x) { return (x+1) }
4905 ;;
4906 ;; is ok, but
4907 ;;
4908 ;; function (x) { if (x < 0) return (x+1); }
4909 ;;
4910 ;; is not because the function can potentially return a value when the
4911 ;; condition is satisfied and if not, the function does not explicitly
4912 ;; return a value.
4913 ;;
4914 ;; This extends to checking mismatches such as "return" and "return <value>"
4915 ;; used in the same function. Warnings are not emitted if inconsistent
4916 ;; returns exist in code that can be statically shown to be unreachable.
4917 ;; Ex.
4918 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4919 ;;
4920 ;; emits no warning. However if the loop had a break statement, then a
4921 ;; warning would be emitted.
4922 ;;
4923 ;; The consistency analysis looks at control structures such as loops, ifs,
4924 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4925 ;; warns the user about an inconsistent set of termination possibilities.
4926 ;;
4927 ;; These flags enumerate the possible ways a statement/function can
4928 ;; terminate. These flags are used by endCheck() and by the Parser to
4929 ;; detect inconsistent return usage.
4930 ;;
4931 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4932 ;; able to execute (example: throw, continue)
4933 ;;
4934 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4935 ;; next one. Statement such as return dont. A compound statement may have
4936 ;; some branch that drops off control to the next statement.
4937 ;;
4938 ;; END_RETURNS indicates that the statement can return with no value.
4939 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4940 ;;
4941 ;; A compound statement such as
4942 ;; if (condition) {
4943 ;; return value;
4944 ;; }
4945 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4946
4947 (defconst js2-END_UNREACHED 0)
4948 (defconst js2-END_DROPS_OFF 1)
4949 (defconst js2-END_RETURNS 2)
4950 (defconst js2-END_RETURNS_VALUE 4)
4951 (defconst js2-END_YIELDS 8)
4952
4953 (defun js2-has-consistent-return-usage (node)
4954 "Check that every return usage in a function body is consistent.
4955 Returns t if the function satisfies strict mode requirement."
4956 (let ((n (js2-end-check node)))
4957 ;; either it doesn't return a value in any branch...
4958 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4959 ;; or it returns a value (or is unreached) at every branch
4960 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4961 js2-END_RETURNS
4962 js2-END_YIELDS)))))
4963
4964 (defun js2-end-check-if (node)
4965 "Returns in the then and else blocks must be consistent with each other.
4966 If there is no else block, then the return statement can fall through.
4967 Returns logical OR of END_* flags"
4968 (let ((th (js2-if-node-then-part node))
4969 (el (js2-if-node-else-part node)))
4970 (if (null th)
4971 js2-END_UNREACHED
4972 (logior (js2-end-check th) (if el
4973 (js2-end-check el)
4974 js2-END_DROPS_OFF)))))
4975
4976 (defun js2-end-check-switch (node)
4977 "Consistency of return statements is checked between the case statements.
4978 If there is no default, then the switch can fall through. If there is a
4979 default, we check to see if all code paths in the default return or if
4980 there is a code path that can fall through.
4981 Returns logical OR of END_* flags."
4982 (let ((rv js2-END_UNREACHED)
4983 default-case)
4984 ;; examine the cases
4985 (catch 'break
4986 (dolist (c (js2-switch-node-cases node))
4987 (if (js2-case-node-expr c)
4988 (js2-set-flag rv (js2-end-check-block c))
4989 (setq default-case c)
4990 (throw 'break nil))))
4991 ;; we don't care how the cases drop into each other
4992 (js2-clear-flag rv js2-END_DROPS_OFF)
4993 ;; examine the default
4994 (js2-set-flag rv (if default-case
4995 (js2-end-check default-case)
4996 js2-END_DROPS_OFF))
4997 rv))
4998
4999 (defun js2-end-check-try (node)
5000 "If the block has a finally, return consistency is checked in the
5001 finally block. If all code paths in the finally return, then the
5002 returns in the try-catch blocks don't matter. If there is a code path
5003 that does not return or if there is no finally block, the returns
5004 of the try and catch blocks are checked for mismatch.
5005 Returns logical OR of END_* flags."
5006 (let ((finally (js2-try-node-finally-block node))
5007 rv)
5008 ;; check the finally if it exists
5009 (setq rv (if finally
5010 (js2-end-check (js2-finally-node-body finally))
5011 js2-END_DROPS_OFF))
5012 ;; If the finally block always returns, then none of the returns
5013 ;; in the try or catch blocks matter.
5014 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5015 (js2-clear-flag rv js2-END_DROPS_OFF)
5016 ;; examine the try block
5017 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5018 ;; check each catch block
5019 (dolist (cb (js2-try-node-catch-clauses node))
5020 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5021 rv))
5022
5023 (defun js2-end-check-loop (node)
5024 "Return statement in the loop body must be consistent. The default
5025 assumption for any kind of a loop is that it will eventually terminate.
5026 The only exception is a loop with a constant true condition. Code that
5027 follows such a loop is examined only if one can statically determine
5028 that there is a break out of the loop.
5029
5030 for(... ; ... ; ...) {}
5031 for(... in ... ) {}
5032 while(...) { }
5033 do { } while(...)
5034
5035 Returns logical OR of END_* flags."
5036 (let ((rv (js2-end-check (js2-loop-node-body node)))
5037 (condition (cond
5038 ((js2-while-node-p node)
5039 (js2-while-node-condition node))
5040 ((js2-do-node-p node)
5041 (js2-do-node-condition node))
5042 ((js2-for-node-p node)
5043 (js2-for-node-condition node)))))
5044
5045 ;; check to see if the loop condition is always true
5046 (if (and condition
5047 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5048 (js2-clear-flag rv js2-END_DROPS_OFF))
5049
5050 ;; look for effect of breaks
5051 (js2-set-flag rv (js2-node-get-prop node
5052 'CONTROL_BLOCK_PROP
5053 js2-END_UNREACHED))
5054 rv))
5055
5056 (defun js2-end-check-block (node)
5057 "A general block of code is examined statement by statement.
5058 If any statement (even a compound one) returns in all branches, then
5059 subsequent statements are not examined.
5060 Returns logical OR of END_* flags."
5061 (let* ((rv js2-END_DROPS_OFF)
5062 (kids (js2-block-node-kids node))
5063 (n (car kids)))
5064 ;; Check each statment. If the statement can continue onto the next
5065 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5066 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5067 (js2-clear-flag rv js2-END_DROPS_OFF)
5068 (js2-set-flag rv (js2-end-check n))
5069 (setq kids (cdr kids)
5070 n (car kids)))
5071 rv))
5072
5073 (defun js2-end-check-label (node)
5074 "A labeled statement implies that there may be a break to the label.
5075 The function processes the labeled statement and then checks the
5076 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5077 particular label.
5078 Returns logical OR of END_* flags."
5079 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5080 (logior rv (js2-node-get-prop node
5081 'CONTROL_BLOCK_PROP
5082 js2-END_UNREACHED))))
5083
5084 (defun js2-end-check-break (node)
5085 "When a break is encountered annotate the statement being broken
5086 out of by setting its CONTROL_BLOCK_PROP property.
5087 Returns logical OR of END_* flags."
5088 (and (js2-break-node-target node)
5089 (js2-node-set-prop (js2-break-node-target node)
5090 'CONTROL_BLOCK_PROP
5091 js2-END_DROPS_OFF))
5092 js2-END_UNREACHED)
5093
5094 (defun js2-end-check (node)
5095 "Examine the body of a function, doing a basic reachability analysis.
5096 Returns a combination of flags END_* flags that indicate
5097 how the function execution can terminate. These constitute only the
5098 pessimistic set of termination conditions. It is possible that at
5099 runtime certain code paths will never be actually taken. Hence this
5100 analysis will flag errors in cases where there may not be errors.
5101 Returns logical OR of END_* flags"
5102 (let (kid)
5103 (cond
5104 ((js2-break-node-p node)
5105 (js2-end-check-break node))
5106 ((js2-expr-stmt-node-p node)
5107 (if (setq kid (js2-expr-stmt-node-expr node))
5108 (js2-end-check kid)
5109 js2-END_DROPS_OFF))
5110 ((or (js2-continue-node-p node)
5111 (js2-throw-node-p node))
5112 js2-END_UNREACHED)
5113 ((js2-return-node-p node)
5114 (if (setq kid (js2-return-node-retval node))
5115 js2-END_RETURNS_VALUE
5116 js2-END_RETURNS))
5117 ((js2-loop-node-p node)
5118 (js2-end-check-loop node))
5119 ((js2-switch-node-p node)
5120 (js2-end-check-switch node))
5121 ((js2-labeled-stmt-node-p node)
5122 (js2-end-check-label node))
5123 ((js2-if-node-p node)
5124 (js2-end-check-if node))
5125 ((js2-try-node-p node)
5126 (js2-end-check-try node))
5127 ((js2-block-node-p node)
5128 (if (null (js2-block-node-kids node))
5129 js2-END_DROPS_OFF
5130 (js2-end-check-block node)))
5131 ((js2-yield-node-p node)
5132 js2-END_YIELDS)
5133 (t
5134 js2-END_DROPS_OFF))))
5135
5136 (defun js2-always-defined-boolean-p (node)
5137 "Check if NODE always evaluates to true or false in boolean context.
5138 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5139 nor always false."
5140 (let ((tt (js2-node-type node))
5141 num)
5142 (cond
5143 ((or (= tt js2-FALSE) (= tt js2-NULL))
5144 'ALWAYS_FALSE)
5145 ((= tt js2-TRUE)
5146 'ALWAYS_TRUE)
5147 ((= tt js2-NUMBER)
5148 (setq num (js2-number-node-num-value node))
5149 (if (and (not (eq num 0.0e+NaN))
5150 (not (zerop num)))
5151 'ALWAYS_TRUE
5152 'ALWAYS_FALSE))
5153 (t
5154 nil))))
5155
5156 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5157 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5158
5159 (defvar js2-tokens nil
5160 "List of all defined token names.") ; initialized in `js2-token-names'
5161
5162 (defconst js2-token-names
5163 (let* ((names (make-vector js2-num-tokens -1))
5164 (case-fold-search nil) ; only match js2-UPPER_CASE
5165 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5166 (loop for sym in syms
5167 for i from 0
5168 do
5169 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5170 (not (boundp sym)))
5171 (aset names (symbol-value sym) ; code, e.g. 152
5172 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5173 (push sym js2-tokens)))
5174 names)
5175 "Vector mapping int values to token string names, sans `js2-' prefix.")
5176
5177 (defun js2-token-name (tok)
5178 "Return a string name for TOK, a token symbol or code.
5179 Signals an error if it's not a recognized token."
5180 (let ((code tok))
5181 (if (symbolp tok)
5182 (setq code (symbol-value tok)))
5183 (if (eq code -1)
5184 "ERROR"
5185 (if (and (numberp code)
5186 (not (minusp code))
5187 (< code js2-num-tokens))
5188 (aref js2-token-names code)
5189 (error "Invalid token: %s" code)))))
5190
5191 (defsubst js2-token-sym (tok)
5192 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5193 (intern (js2-token-name tok)))
5194
5195 (defconst js2-token-codes
5196 (let ((table (make-hash-table :test 'eq :size 256)))
5197 (loop for name across js2-token-names
5198 for sym = (intern (concat "js2-" name))
5199 do
5200 (puthash sym (symbol-value sym) table))
5201 ;; clean up a few that are "wrong" in Rhino's token codes
5202 (puthash 'js2-DELETE js2-DELPROP table)
5203 table)
5204 "Hashtable mapping token symbols to their bytecodes.")
5205
5206 (defsubst js2-token-code (sym)
5207 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5208 (or (gethash sym js2-token-codes)
5209 (error "Invalid token symbol: %s " sym))) ; signal code bug
5210
5211 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5212 (setq js2-token-end js2-ts-cursor)
5213 (js2-report-error msg nil
5214 (or beg js2-token-beg)
5215 (or len (- js2-token-end js2-token-beg)))
5216 (unless no-throw
5217 (throw 'return js2-ERROR)))
5218
5219 (defsubst js2-get-string-from-buffer ()
5220 "Reverse the char accumulator and return it as a string."
5221 (setq js2-token-end js2-ts-cursor)
5222 (if js2-ts-string-buffer
5223 (apply #'string (nreverse js2-ts-string-buffer))
5224 ""))
5225
5226 ;; TODO: could potentially avoid a lot of consing by allocating a
5227 ;; char buffer the way Rhino does.
5228 (defsubst js2-add-to-string (c)
5229 (push c js2-ts-string-buffer))
5230
5231 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5232 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5233 ;; any other character: when it's not part of the current token, we
5234 ;; unget it, allowing it to be read again by the following call.
5235 (defsubst js2-unget-char ()
5236 (decf js2-ts-cursor))
5237
5238 ;; Rhino distinguishes \r and \n line endings. We don't need to
5239 ;; because we only scan from Emacs buffers, which always use \n.
5240 (defsubst js2-get-char ()
5241 "Read and return the next character from the input buffer.
5242 Increments `js2-ts-lineno' if the return value is a newline char.
5243 Updates `js2-ts-cursor' to the point after the returned char.
5244 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5245 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5246 (let (c)
5247 ;; check for end of buffer
5248 (if (>= js2-ts-cursor (point-max))
5249 (setq js2-ts-hit-eof t
5250 js2-ts-cursor (1+ js2-ts-cursor)
5251 c js2-EOF_CHAR) ; return value
5252 ;; otherwise read next char
5253 (setq c (char-before (incf js2-ts-cursor)))
5254 ;; if we read a newline, update counters
5255 (if (= c ?\n)
5256 (setq js2-ts-line-start js2-ts-cursor
5257 js2-ts-lineno (1+ js2-ts-lineno)))
5258 ;; TODO: skip over format characters
5259 c)))
5260
5261 (defsubst js2-read-unicode-escape ()
5262 "Read a \\uNNNN sequence from the input.
5263 Assumes the ?\ and ?u have already been read.
5264 Returns the unicode character, or nil if it wasn't a valid character.
5265 Doesn't change the values of any scanner variables."
5266 ;; I really wish I knew a better way to do this, but I can't
5267 ;; find the Emacs function that takes a 16-bit int and converts
5268 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5269 ;; Have to first check that it's 4 hex characters or it may stop
5270 ;; the read early.
5271 (ignore-errors
5272 (let ((s (buffer-substring-no-properties js2-ts-cursor
5273 (+ 4 js2-ts-cursor))))
5274 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5275 (read (concat "?\\u" s))))))
5276
5277 (defsubst js2-match-char (test)
5278 "Consume and return next character if it matches TEST, a character.
5279 Returns nil and consumes nothing if TEST is not the next character."
5280 (let ((c (js2-get-char)))
5281 (if (eq c test)
5282 t
5283 (js2-unget-char)
5284 nil)))
5285
5286 (defsubst js2-peek-char ()
5287 (prog1
5288 (js2-get-char)
5289 (js2-unget-char)))
5290
5291 (defsubst js2-java-identifier-start-p (c)
5292 (or
5293 (memq c '(?$ ?_))
5294 (js2-char-uppercase-p c)
5295 (js2-char-lowercase-p c)))
5296
5297 (defsubst js2-java-identifier-part-p (c)
5298 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5299 ;; TODO: make me Unicode-friendly. See comments above.
5300 (or
5301 (memq c '(?$ ?_))
5302 (js2-char-uppercase-p c)
5303 (js2-char-lowercase-p c)
5304 (and (>= c ?0) (<= c ?9))))
5305
5306 (defsubst js2-alpha-p (c)
5307 (cond ((and (<= ?A c) (<= c ?Z)) t)
5308 ((and (<= ?a c) (<= c ?z)) t)
5309 (t nil)))
5310
5311 (defsubst js2-digit-p (c)
5312 (and (<= ?0 c) (<= c ?9)))
5313
5314 (defsubst js2-js-space-p (c)
5315 (if (<= c 127)
5316 (memq c '(#x20 #x9 #xB #xC #xD))
5317 (or
5318 (eq c #xA0)
5319 ;; TODO: change this nil to check for Unicode space character
5320 nil)))
5321
5322 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5323
5324 (defsubst js2-skip-line ()
5325 "Skip to end of line"
5326 (let (c)
5327 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5328 (js2-unget-char)
5329 (setq js2-token-end js2-ts-cursor)))
5330
5331 (defun js2-init-scanner (&optional buf line)
5332 "Create token stream for BUF starting on LINE.
5333 BUF defaults to current-buffer and line defaults to 1.
5334
5335 A buffer can only have one scanner active at a time, which yields
5336 dramatically simpler code than using a defstruct. If you need to
5337 have simultaneous scanners in a buffer, copy the regions to scan
5338 into temp buffers."
5339 (save-excursion
5340 (when buf
5341 (set-buffer buf))
5342 (setq js2-ts-dirty-line nil
5343 js2-ts-regexp-flags nil
5344 js2-ts-string ""
5345 js2-ts-number nil
5346 js2-ts-hit-eof nil
5347 js2-ts-line-start 0
5348 js2-ts-lineno (or line 1)
5349 js2-ts-line-end-char -1
5350 js2-ts-cursor (point-min)
5351 js2-ts-is-xml-attribute nil
5352 js2-ts-xml-is-tag-content nil
5353 js2-ts-xml-open-tags-count 0
5354 js2-ts-string-buffer nil)))
5355
5356 ;; This function uses the cached op, string and number fields in
5357 ;; TokenStream; if getToken has been called since the passed token
5358 ;; was scanned, the op or string printed may be incorrect.
5359 (defun js2-token-to-string (token)
5360 ;; Not sure where this function is used in Rhino. Not tested.
5361 (if (not js2-debug-print-trees)
5362 ""
5363 (let ((name (js2-token-name token)))
5364 (cond
5365 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5366 (concat name " `" js2-ts-string "'"))
5367 ((eq token js2-NUMBER)
5368 (format "NUMBER %g" js2-ts-number))
5369 (t
5370 name)))))
5371
5372 (defconst js2-keywords
5373 '(break
5374 case catch const continue
5375 debugger default delete do
5376 else enum
5377 false finally for function
5378 if in instanceof import
5379 let
5380 new null
5381 return
5382 switch
5383 this throw true try typeof
5384 var void
5385 while with
5386 yield))
5387
5388 ;; Token names aren't exactly the same as the keywords, unfortunately.
5389 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5390 (defconst js2-kwd-tokens
5391 (let ((table (make-vector js2-num-tokens nil))
5392 (tokens
5393 (list js2-BREAK
5394 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5395 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5396 js2-ELSE
5397 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5398 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5399 js2-LET
5400 js2-NEW js2-NULL
5401 js2-RETURN
5402 js2-SWITCH
5403 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5404 js2-VAR
5405 js2-WHILE js2-WITH
5406 js2-YIELD)))
5407 (dolist (i tokens)
5408 (aset table i 'font-lock-keyword-face))
5409 (aset table js2-STRING 'font-lock-string-face)
5410 (aset table js2-REGEXP 'font-lock-string-face)
5411 (aset table js2-COMMENT 'font-lock-comment-face)
5412 (aset table js2-THIS 'font-lock-builtin-face)
5413 (aset table js2-VOID 'font-lock-constant-face)
5414 (aset table js2-NULL 'font-lock-constant-face)
5415 (aset table js2-TRUE 'font-lock-constant-face)
5416 (aset table js2-FALSE 'font-lock-constant-face)
5417 table)
5418 "Vector whose values are non-nil for tokens that are keywords.
5419 The values are default faces to use for highlighting the keywords.")
5420
5421 (defconst js2-reserved-words
5422 '(abstract
5423 boolean byte
5424 char class
5425 double
5426 enum export extends
5427 final float
5428 goto
5429 implements import int interface
5430 long
5431 native
5432 package private protected public
5433 short static super synchronized
5434 throws transient
5435 volatile))
5436
5437 (defconst js2-keyword-names
5438 (let ((table (make-hash-table :test 'equal)))
5439 (loop for k in js2-keywords
5440 do (puthash
5441 (symbol-name k) ; instanceof
5442 (intern (concat "js2-"
5443 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5444 table))
5445 table)
5446 "JavaScript keywords by name, mapped to their symbols.")
5447
5448 (defconst js2-reserved-word-names
5449 (let ((table (make-hash-table :test 'equal)))
5450 (loop for k in js2-reserved-words
5451 do
5452 (puthash (symbol-name k) 'js2-RESERVED table))
5453 table)
5454 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5455
5456 (defsubst js2-collect-string (buf)
5457 "Convert BUF, a list of chars, to a string.
5458 Reverses BUF before converting."
5459 (cond
5460 ((stringp buf)
5461 buf)
5462 ((null buf) ; for emacs21 compat
5463 "")
5464 (t
5465 (if buf
5466 (apply #'string (nreverse buf))
5467 ""))))
5468
5469 (defun js2-string-to-keyword (s)
5470 "Return token for S, a string, if S is a keyword or reserved word.
5471 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5472 (or (gethash s js2-keyword-names)
5473 (gethash s js2-reserved-word-names)))
5474
5475 (defsubst js2-ts-set-char-token-bounds ()
5476 "Used when next token is one character."
5477 (setq js2-token-beg (1- js2-ts-cursor)
5478 js2-token-end js2-ts-cursor))
5479
5480 (defsubst js2-ts-return (token)
5481 "Return an N-character TOKEN from `js2-get-token'.
5482 Updates `js2-token-end' accordingly."
5483 (setq js2-token-end js2-ts-cursor)
5484 (throw 'return token))
5485
5486 (defsubst js2-x-digit-to-int (c accumulator)
5487 "Build up a hex number.
5488 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5489 corresponding number. Otherwise return -1."
5490 (catch 'return
5491 (catch 'check
5492 ;; Use 0..9 < A..Z < a..z
5493 (cond
5494 ((<= c ?9)
5495 (decf c ?0)
5496 (if (<= 0 c)
5497 (throw 'check nil)))
5498 ((<= c ?F)
5499 (when (<= ?A c)
5500 (decf c (- ?A 10))
5501 (throw 'check nil)))
5502 ((<= c ?f)
5503 (when (<= ?a c)
5504 (decf c (- ?a 10))
5505 (throw 'check nil))))
5506 (throw 'return -1))
5507 (logior c (lsh accumulator 4))))
5508
5509 (defun js2-get-token ()
5510 "Return next JavaScript token, an int such as js2-RETURN."
5511 (let (c
5512 c1
5513 identifier-start
5514 is-unicode-escape-start
5515 contains-escape
5516 escape-val
5517 escape-start
5518 str
5519 result
5520 base
5521 is-integer
5522 quote-char
5523 val
5524 look-for-slash
5525 continue)
5526 (catch 'return
5527 (while t
5528 ;; Eat whitespace, possibly sensitive to newlines.
5529 (setq continue t)
5530 (while continue
5531 (setq c (js2-get-char))
5532 (cond
5533 ((eq c js2-EOF_CHAR)
5534 (js2-ts-set-char-token-bounds)
5535 (throw 'return js2-EOF))
5536 ((eq c ?\n)
5537 (js2-ts-set-char-token-bounds)
5538 (setq js2-ts-dirty-line nil)
5539 (throw 'return js2-EOL))
5540 ((not (js2-js-space-p c))
5541 (if (/= c ?-) ; in case end of HTML comment
5542 (setq js2-ts-dirty-line t))
5543 (setq continue nil))))
5544 ;; Assume the token will be 1 char - fixed up below.
5545 (js2-ts-set-char-token-bounds)
5546 (when (eq c ?@)
5547 (throw 'return js2-XMLATTR))
5548 ;; identifier/keyword/instanceof?
5549 ;; watch out for starting with a <backslash>
5550 (cond
5551 ((eq c ?\\)
5552 (setq c (js2-get-char))
5553 (if (eq c ?u)
5554 (setq identifier-start t
5555 is-unicode-escape-start t
5556 js2-ts-string-buffer nil)
5557 (setq identifier-start nil)
5558 (js2-unget-char)
5559 (setq c ?\\)))
5560 (t
5561 (when (setq identifier-start (js2-java-identifier-start-p c))
5562 (setq js2-ts-string-buffer nil)
5563 (js2-add-to-string c))))
5564 (when identifier-start
5565 (setq contains-escape is-unicode-escape-start)
5566 (catch 'break
5567 (while t
5568 (if is-unicode-escape-start
5569 ;; strictly speaking we should probably push-back
5570 ;; all the bad characters if the <backslash>uXXXX
5571 ;; sequence is malformed. But since there isn't a
5572 ;; correct context(is there?) for a bad Unicode
5573 ;; escape sequence in an identifier, we can report
5574 ;; an error here.
5575 (progn
5576 (setq escape-val 0)
5577 (dotimes (i 4)
5578 (setq c (js2-get-char)
5579 escape-val (js2-x-digit-to-int c escape-val))
5580 ;; Next check takes care of c < 0 and bad escape
5581 (if (minusp escape-val)
5582 (throw 'break nil)))
5583 (if (minusp escape-val)
5584 (js2-report-scan-error "msg.invalid.escape" t))
5585 (js2-add-to-string escape-val)
5586 (setq is-unicode-escape-start nil))
5587 (setq c (js2-get-char))
5588 (cond
5589 ((eq c ?\\)
5590 (setq c (js2-get-char))
5591 (if (eq c ?u)
5592 (setq is-unicode-escape-start t
5593 contains-escape t)
5594 (js2-report-scan-error "msg.illegal.character" t)))
5595 (t
5596 (if (or (eq c js2-EOF_CHAR)
5597 (not (js2-java-identifier-part-p c)))
5598 (throw 'break nil))
5599 (js2-add-to-string c))))))
5600 (js2-unget-char)
5601 (setq str (js2-get-string-from-buffer))
5602 (unless contains-escape
5603 ;; OPT we shouldn't have to make a string (object!) to
5604 ;; check if it's a keyword.
5605 ;; Return the corresponding token if it's a keyword
5606 (when (setq result (js2-string-to-keyword str))
5607 (if (and (< js2-language-version 170)
5608 (memq result '(js2-LET js2-YIELD)))
5609 ;; LET and YIELD are tokens only in 1.7 and later
5610 (setq result 'js2-NAME))
5611 (if (not (eq result 'js2-RESERVED))
5612 (throw 'return (js2-token-code result)))
5613 (js2-report-warning "msg.reserved.keyword" str)))
5614 ;; If we want to intern these as Rhino does, just use (intern str)
5615 (setq js2-ts-string str)
5616 (throw 'return js2-NAME)) ; end identifier/kwd check
5617 ;; is it a number?
5618 (when (or (js2-digit-p c)
5619 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5620 (setq js2-ts-string-buffer nil
5621 base 10)
5622 (when (eq c ?0)
5623 (setq c (js2-get-char))
5624 (cond
5625 ((or (eq c ?x) (eq c ?X))
5626 (setq base 16)
5627 (setq c (js2-get-char)))
5628 ((js2-digit-p c)
5629 (setq base 8))
5630 (t
5631 (js2-add-to-string ?0))))
5632 (if (eq base 16)
5633 (while (<= 0 (js2-x-digit-to-int c 0))
5634 (js2-add-to-string c)
5635 (setq c (js2-get-char)))
5636 (while (and (<= ?0 c) (<= c ?9))
5637 ;; We permit 08 and 09 as decimal numbers, which
5638 ;; makes our behavior a superset of the ECMA
5639 ;; numeric grammar. We might not always be so
5640 ;; permissive, so we warn about it.
5641 (when (and (eq base 8) (>= c ?8))
5642 (js2-report-warning "msg.bad.octal.literal"
5643 (if (eq c ?8) "8" "9"))
5644 (setq base 10))
5645 (js2-add-to-string c)
5646 (setq c (js2-get-char))))
5647 (setq is-integer t)
5648 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5649 (setq is-integer nil)
5650 (when (eq c ?.)
5651 (loop do
5652 (js2-add-to-string c)
5653 (setq c (js2-get-char))
5654 while (js2-digit-p c)))
5655 (when (memq c '(?e ?E))
5656 (js2-add-to-string c)
5657 (setq c (js2-get-char))
5658 (when (memq c '(?+ ?-))
5659 (js2-add-to-string c)
5660 (setq c (js2-get-char)))
5661 (unless (js2-digit-p c)
5662 (js2-report-scan-error "msg.missing.exponent" t))
5663 (loop do
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))
5666 while (js2-digit-p c))))
5667 (js2-unget-char)
5668 (setq js2-ts-string (js2-get-string-from-buffer)
5669 js2-ts-number
5670 (if (and (eq base 10) (not is-integer))
5671 (string-to-number js2-ts-string)
5672 ;; TODO: call runtime number-parser. Some of it is in
5673 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5674 (string-to-number js2-ts-string)))
5675 (throw 'return js2-NUMBER))
5676 ;; is it a string?
5677 (when (memq c '(?\" ?\'))
5678 ;; We attempt to accumulate a string the fast way, by
5679 ;; building it directly out of the reader. But if there
5680 ;; are any escaped characters in the string, we revert to
5681 ;; building it out of a string buffer.
5682 (setq quote-char c
5683 js2-ts-string-buffer nil
5684 c (js2-get-char))
5685 (catch 'break
5686 (while (/= c quote-char)
5687 (catch 'continue
5688 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5689 (js2-unget-char)
5690 (setq js2-token-end js2-ts-cursor)
5691 (js2-report-error "msg.unterminated.string.lit")
5692 (throw 'return js2-STRING))
5693 (when (eq c ?\\)
5694 ;; We've hit an escaped character
5695 (setq c (js2-get-char))
5696 (case c
5697 (?b (setq c ?\b))
5698 (?f (setq c ?\f))
5699 (?n (setq c ?\n))
5700 (?r (setq c ?\r))
5701 (?t (setq c ?\t))
5702 (?v (setq c ?\v))
5703 (?u
5704 (setq c1 (js2-read-unicode-escape))
5705 (if js2-parse-ide-mode
5706 (if c1
5707 (progn
5708 ;; just copy the string in IDE-mode
5709 (js2-add-to-string ?\\)
5710 (js2-add-to-string ?u)
5711 (dotimes (i 3)
5712 (js2-add-to-string (js2-get-char)))
5713 (setq c (js2-get-char))) ; added at end of loop
5714 ;; flag it as an invalid escape
5715 (js2-report-warning "msg.invalid.escape"
5716 nil (- js2-ts-cursor 2) 6))
5717 ;; Get 4 hex digits; if the u escape is not
5718 ;; followed by 4 hex digits, use 'u' + the
5719 ;; literal character sequence that follows.
5720 (js2-add-to-string ?u)
5721 (setq escape-val 0)
5722 (dotimes (i 4)
5723 (setq c (js2-get-char)
5724 escape-val (js2-x-digit-to-int c escape-val))
5725 (if (minusp escape-val)
5726 (throw 'continue nil))
5727 (js2-add-to-string c))
5728 ;; prepare for replace of stored 'u' sequence by escape value
5729 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5730 c escape-val)))
5731 (?x
5732 ;; Get 2 hex digits, defaulting to 'x'+literal
5733 ;; sequence, as above.
5734 (setq c (js2-get-char)
5735 escape-val (js2-x-digit-to-int c 0))
5736 (if (minusp escape-val)
5737 (progn
5738 (js2-add-to-string ?x)
5739 (throw 'continue nil))
5740 (setq c1 c
5741 c (js2-get-char)
5742 escape-val (js2-x-digit-to-int c escape-val))
5743 (if (minusp escape-val)
5744 (progn
5745 (js2-add-to-string ?x)
5746 (js2-add-to-string c1)
5747 (throw 'continue nil))
5748 ;; got 2 hex digits
5749 (setq c escape-val))))
5750 (?\n
5751 ;; Remove line terminator after escape to follow
5752 ;; SpiderMonkey and C/C++
5753 (setq c (js2-get-char))
5754 (throw 'continue nil))
5755 (t
5756 (when (and (<= ?0 c) (< c ?8))
5757 (setq val (- c ?0)
5758 c (js2-get-char))
5759 (when (and (<= ?0 c) (< c ?8))
5760 (setq val (- (+ (* 8 val) c) ?0)
5761 c (js2-get-char))
5762 (when (and (<= ?0 c)
5763 (< c ?8)
5764 (< val #o37))
5765 ;; c is 3rd char of octal sequence only
5766 ;; if the resulting val <= 0377
5767 (setq val (- (+ (* 8 val) c) ?0)
5768 c (js2-get-char))))
5769 (js2-unget-char)
5770 (setq c val)))))
5771 (js2-add-to-string c)
5772 (setq c (js2-get-char)))))
5773 (setq js2-ts-string (js2-get-string-from-buffer))
5774 (throw 'return js2-STRING))
5775 (case c
5776 (?\;
5777 (throw 'return js2-SEMI))
5778 (?\[
5779 (throw 'return js2-LB))
5780 (?\]
5781 (throw 'return js2-RB))
5782 (?{
5783 (throw 'return js2-LC))
5784 (?}
5785 (throw 'return js2-RC))
5786 (?\(
5787 (throw 'return js2-LP))
5788 (?\)
5789 (throw 'return js2-RP))
5790 (?,
5791 (throw 'return js2-COMMA))
5792 (??
5793 (throw 'return js2-HOOK))
5794 (?:
5795 (if (js2-match-char ?:)
5796 (js2-ts-return js2-COLONCOLON)
5797 (throw 'return js2-COLON)))
5798 (?.
5799 (if (js2-match-char ?.)
5800 (js2-ts-return js2-DOTDOT)
5801 (if (js2-match-char ?\()
5802 (js2-ts-return js2-DOTQUERY)
5803 (throw 'return js2-DOT))))
5804 (?|
5805 (if (js2-match-char ?|)
5806 (throw 'return js2-OR)
5807 (if (js2-match-char ?=)
5808 (js2-ts-return js2-ASSIGN_BITOR)
5809 (throw 'return js2-BITOR))))
5810 (?^
5811 (if (js2-match-char ?=)
5812 (js2-ts-return js2-ASSIGN_BITOR)
5813 (throw 'return js2-BITXOR)))
5814 (?&
5815 (if (js2-match-char ?&)
5816 (throw 'return js2-AND)
5817 (if (js2-match-char ?=)
5818 (js2-ts-return js2-ASSIGN_BITAND)
5819 (throw 'return js2-BITAND))))
5820 (?=
5821 (if (js2-match-char ?=)
5822 (if (js2-match-char ?=)
5823 (js2-ts-return js2-SHEQ)
5824 (throw 'return js2-EQ))
5825 (throw 'return js2-ASSIGN)))
5826 (?!
5827 (if (js2-match-char ?=)
5828 (if (js2-match-char ?=)
5829 (js2-ts-return js2-SHNE)
5830 (js2-ts-return js2-NE))
5831 (throw 'return js2-NOT)))
5832 (?<
5833 ;; NB:treat HTML begin-comment as comment-till-eol
5834 (when (js2-match-char ?!)
5835 (when (js2-match-char ?-)
5836 (when (js2-match-char ?-)
5837 (js2-skip-line)
5838 (setq js2-ts-comment-type 'html)
5839 (throw 'return js2-COMMENT)))
5840 (js2-unget-char))
5841 (if (js2-match-char ?<)
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_LSH)
5844 (js2-ts-return js2-LSH))
5845 (if (js2-match-char ?=)
5846 (js2-ts-return js2-LE)
5847 (throw 'return js2-LT))))
5848 (?>
5849 (if (js2-match-char ?>)
5850 (if (js2-match-char ?>)
5851 (if (js2-match-char ?=)
5852 (js2-ts-return js2-ASSIGN_URSH)
5853 (js2-ts-return js2-URSH))
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-ASSIGN_RSH)
5856 (js2-ts-return js2-RSH)))
5857 (if (js2-match-char ?=)
5858 (js2-ts-return js2-GE)
5859 (throw 'return js2-GT))))
5860 (?*
5861 (if (js2-match-char ?=)
5862 (js2-ts-return js2-ASSIGN_MUL)
5863 (throw 'return js2-MUL)))
5864 (?/
5865 ;; is it a // comment?
5866 (when (js2-match-char ?/)
5867 (setq js2-token-beg (- js2-ts-cursor 2))
5868 (js2-skip-line)
5869 (setq js2-ts-comment-type 'line)
5870 ;; include newline so highlighting goes to end of window
5871 (incf js2-token-end)
5872 (throw 'return js2-COMMENT))
5873 ;; is it a /* comment?
5874 (when (js2-match-char ?*)
5875 (setq look-for-slash nil
5876 js2-token-beg (- js2-ts-cursor 2)
5877 js2-ts-comment-type
5878 (if (js2-match-char ?*)
5879 (progn
5880 (setq look-for-slash t)
5881 'jsdoc)
5882 'block))
5883 (while t
5884 (setq c (js2-get-char))
5885 (cond
5886 ((eq c js2-EOF_CHAR)
5887 (setq js2-token-end (1- js2-ts-cursor))
5888 (js2-report-error "msg.unterminated.comment")
5889 (throw 'return js2-COMMENT))
5890 ((eq c ?*)
5891 (setq look-for-slash t))
5892 ((eq c ?/)
5893 (if look-for-slash
5894 (js2-ts-return js2-COMMENT)))
5895 (t
5896 (setq look-for-slash nil
5897 js2-token-end js2-ts-cursor)))))
5898 (if (js2-match-char ?=)
5899 (js2-ts-return js2-ASSIGN_DIV)
5900 (throw 'return js2-DIV)))
5901 (?#
5902 (when js2-skip-preprocessor-directives
5903 (js2-skip-line)
5904 (setq js2-ts-comment-type 'preprocessor
5905 js2-token-end js2-ts-cursor)
5906 (throw 'return js2-COMMENT))
5907 (throw 'return js2-ERROR))
5908 (?%
5909 (if (js2-match-char ?=)
5910 (js2-ts-return js2-ASSIGN_MOD)
5911 (throw 'return js2-MOD)))
5912 (?~
5913 (throw 'return js2-BITNOT))
5914 (?+
5915 (if (js2-match-char ?=)
5916 (js2-ts-return js2-ASSIGN_ADD)
5917 (if (js2-match-char ?+)
5918 (js2-ts-return js2-INC)
5919 (throw 'return js2-ADD))))
5920 (?-
5921 (cond
5922 ((js2-match-char ?=)
5923 (setq c js2-ASSIGN_SUB))
5924 ((js2-match-char ?-)
5925 (unless js2-ts-dirty-line
5926 ;; treat HTML end-comment after possible whitespace
5927 ;; after line start as comment-until-eol
5928 (when (js2-match-char ?>)
5929 (js2-skip-line)
5930 (setq js2-ts-comment-type 'html)
5931 (throw 'return js2-COMMENT)))
5932 (setq c js2-DEC))
5933 (t
5934 (setq c js2-SUB)))
5935 (setq js2-ts-dirty-line t)
5936 (js2-ts-return c))
5937 (otherwise
5938 (js2-report-scan-error "msg.illegal.character")))))))
5939
5940 (defun js2-read-regexp (start-token)
5941 "Called by parser when it gets / or /= in literal context."
5942 (let (c
5943 err
5944 in-class ; inside a '[' .. ']' character-class
5945 flags
5946 (continue t))
5947 (setq js2-token-beg js2-ts-cursor
5948 js2-ts-string-buffer nil
5949 js2-ts-regexp-flags nil)
5950 (if (eq start-token js2-ASSIGN_DIV)
5951 ;; mis-scanned /=
5952 (js2-add-to-string ?=)
5953 (if (not (eq start-token js2-DIV))
5954 (error "failed assertion")))
5955 (while (and (not err)
5956 (or (/= (setq c (js2-get-char)) ?/)
5957 in-class))
5958 (cond
5959 ((or (= c ?\n)
5960 (= c js2-EOF_CHAR))
5961 (setq js2-token-end (1- js2-ts-cursor)
5962 err t
5963 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5964 (js2-report-error "msg.unterminated.re.lit"))
5965 (t (cond
5966 ((= c ?\\)
5967 (js2-add-to-string c)
5968 (setq c (js2-get-char)))
5969 ((= c ?\[)
5970 (setq in-class t))
5971 ((= c ?\])
5972 (setq in-class nil)))
5973 (js2-add-to-string c))))
5974 (unless err
5975 (while continue
5976 (cond
5977 ((js2-match-char ?g)
5978 (push ?g flags))
5979 ((js2-match-char ?i)
5980 (push ?i flags))
5981 ((js2-match-char ?m)
5982 (push ?m flags))
5983 (t
5984 (setq continue nil))))
5985 (if (js2-alpha-p (js2-peek-char))
5986 (js2-report-scan-error "msg.invalid.re.flag" t
5987 js2-ts-cursor 1))
5988 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5989 js2-ts-regexp-flags (js2-collect-string flags)
5990 js2-token-end js2-ts-cursor)
5991 ;; tell `parse-partial-sexp' to ignore this range of chars
5992 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5993
5994 (defun js2-get-first-xml-token ()
5995 (setq js2-ts-xml-open-tags-count 0
5996 js2-ts-is-xml-attribute nil
5997 js2-ts-xml-is-tag-content nil)
5998 (js2-unget-char)
5999 (js2-get-next-xml-token))
6000
6001 (defsubst js2-xml-discard-string ()
6002 "Throw away the string in progress and flag an XML parse error."
6003 (setq js2-ts-string-buffer nil
6004 js2-ts-string nil)
6005 (js2-report-scan-error "msg.XML.bad.form" t))
6006
6007 (defun js2-get-next-xml-token ()
6008 (setq js2-ts-string-buffer nil ; for recording the XML
6009 js2-token-beg js2-ts-cursor)
6010 (let (c result)
6011 (setq result
6012 (catch 'return
6013 (while t
6014 (setq c (js2-get-char))
6015 (cond
6016 ((= c js2-EOF_CHAR)
6017 (throw 'return js2-ERROR))
6018 (js2-ts-xml-is-tag-content
6019 (case c
6020 (?>
6021 (js2-add-to-string c)
6022 (setq js2-ts-xml-is-tag-content nil
6023 js2-ts-is-xml-attribute nil))
6024 (?/
6025 (js2-add-to-string c)
6026 (when (eq ?> (js2-peek-char))
6027 (setq c (js2-get-char))
6028 (js2-add-to-string c)
6029 (setq js2-ts-xml-is-tag-content nil)
6030 (decf js2-ts-xml-open-tags-count)))
6031 (?{
6032 (js2-unget-char)
6033 (setq js2-ts-string (js2-get-string-from-buffer))
6034 (throw 'return js2-XML))
6035 ((?\' ?\")
6036 (js2-add-to-string c)
6037 (unless (js2-read-quoted-string c)
6038 (throw 'return js2-ERROR)))
6039 (?=
6040 (js2-add-to-string c)
6041 (setq js2-ts-is-xml-attribute t))
6042 ((? ?\t ?\r ?\n)
6043 (js2-add-to-string c))
6044 (t
6045 (js2-add-to-string c)
6046 (setq js2-ts-is-xml-attribute nil)))
6047 (when (and (not js2-ts-xml-is-tag-content)
6048 (zerop js2-ts-xml-open-tags-count))
6049 (setq js2-ts-string (js2-get-string-from-buffer))
6050 (throw 'return js2-XMLEND)))
6051 (t
6052 ;; else not tag content
6053 (case c
6054 (?<
6055 (js2-add-to-string c)
6056 (setq c (js2-peek-char))
6057 (case c
6058 (?!
6059 (setq c (js2-get-char)) ;; skip !
6060 (js2-add-to-string c)
6061 (setq c (js2-peek-char))
6062 (case c
6063 (?-
6064 (setq c (js2-get-char)) ;; skip -
6065 (js2-add-to-string c)
6066 (if (eq c ?-)
6067 (progn
6068 (js2-add-to-string c)
6069 (unless (js2-read-xml-comment)
6070 (throw 'return js2-ERROR)))
6071 (js2-xml-discard-string)
6072 (throw 'return js2-ERROR)))
6073 (?\[
6074 (setq c (js2-get-char)) ;; skip [
6075 (js2-add-to-string c)
6076 (if (and (= (js2-get-char) ?C)
6077 (= (js2-get-char) ?D)
6078 (= (js2-get-char) ?A)
6079 (= (js2-get-char) ?T)
6080 (= (js2-get-char) ?A)
6081 (= (js2-get-char) ?\[))
6082 (progn
6083 (js2-add-to-string ?C)
6084 (js2-add-to-string ?D)
6085 (js2-add-to-string ?A)
6086 (js2-add-to-string ?T)
6087 (js2-add-to-string ?A)
6088 (js2-add-to-string ?\[)
6089 (unless (js2-read-cdata)
6090 (throw 'return js2-ERROR)))
6091 (js2-xml-discard-string)
6092 (throw 'return js2-ERROR)))
6093 (t
6094 (unless (js2-read-entity)
6095 (throw 'return js2-ERROR)))))
6096 (??
6097 (setq c (js2-get-char)) ;; skip ?
6098 (js2-add-to-string c)
6099 (unless (js2-read-PI)
6100 (throw 'return js2-ERROR)))
6101 (?/
6102 ;; end tag
6103 (setq c (js2-get-char)) ;; skip /
6104 (js2-add-to-string c)
6105 (when (zerop js2-ts-xml-open-tags-count)
6106 (js2-xml-discard-string)
6107 (throw 'return js2-ERROR))
6108 (setq js2-ts-xml-is-tag-content t)
6109 (decf js2-ts-xml-open-tags-count))
6110 (t
6111 ;; start tag
6112 (setq js2-ts-xml-is-tag-content t)
6113 (incf js2-ts-xml-open-tags-count))))
6114 (?{
6115 (js2-unget-char)
6116 (setq js2-ts-string (js2-get-string-from-buffer))
6117 (throw 'return js2-XML))
6118 (t
6119 (js2-add-to-string c))))))))
6120 (setq js2-token-end js2-ts-cursor)
6121 result))
6122
6123 (defun js2-read-quoted-string (quote)
6124 (let (c)
6125 (catch 'return
6126 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6127 (js2-add-to-string c)
6128 (if (eq c quote)
6129 (throw 'return t)))
6130 (js2-xml-discard-string) ;; throw away string in progress
6131 nil)))
6132
6133 (defun js2-read-xml-comment ()
6134 (let ((c (js2-get-char)))
6135 (catch 'return
6136 (while (/= c js2-EOF_CHAR)
6137 (catch 'continue
6138 (js2-add-to-string c)
6139 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6140 (setq c (js2-get-char))
6141 (js2-add-to-string c)
6142 (if (eq (js2-peek-char) ?>)
6143 (progn
6144 (setq c (js2-get-char)) ;; skip >
6145 (js2-add-to-string c)
6146 (throw 'return t))
6147 (throw 'continue nil)))
6148 (setq c (js2-get-char))))
6149 (js2-xml-discard-string)
6150 nil)))
6151
6152 (defun js2-read-cdata ()
6153 (let ((c (js2-get-char)))
6154 (catch 'return
6155 (while (/= c js2-EOF_CHAR)
6156 (catch 'continue
6157 (js2-add-to-string c)
6158 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6159 (setq c (js2-get-char))
6160 (js2-add-to-string c)
6161 (if (eq (js2-peek-char) ?>)
6162 (progn
6163 (setq c (js2-get-char)) ;; Skip >
6164 (js2-add-to-string c)
6165 (throw 'return t))
6166 (throw 'continue nil)))
6167 (setq c (js2-get-char))))
6168 (js2-xml-discard-string)
6169 nil)))
6170
6171 (defun js2-read-entity ()
6172 (let ((decl-tags 1)
6173 c)
6174 (catch 'return
6175 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6176 (js2-add-to-string c)
6177 (case c
6178 (?<
6179 (incf decl-tags))
6180 (?>
6181 (decf decl-tags)
6182 (if (zerop decl-tags)
6183 (throw 'return t)))))
6184 (js2-xml-discard-string)
6185 nil)))
6186
6187 (defun js2-read-PI ()
6188 "Scan an XML processing instruction."
6189 (let (c)
6190 (catch 'return
6191 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6192 (js2-add-to-string c)
6193 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6194 (setq c (js2-get-char)) ;; Skip >
6195 (js2-add-to-string c)
6196 (throw 'return t)))
6197 (js2-xml-discard-string)
6198 nil)))
6199
6200 (defun js2-scanner-get-line ()
6201 "Return the text of the current scan line."
6202 (buffer-substring (point-at-bol) (point-at-eol)))
6203
6204 ;;; Highlighting
6205
6206 (defsubst js2-set-face (beg end face &optional record)
6207 "Fontify a region. If RECORD is non-nil, record for later."
6208 (when (plusp js2-highlight-level)
6209 (setq beg (min (point-max) beg)
6210 beg (max (point-min) beg)
6211 end (min (point-max) end)
6212 end (max (point-min) end))
6213 (if record
6214 (push (list beg end face) js2-mode-fontifications)
6215 (put-text-property beg end 'face face))))
6216
6217 (defsubst js2-set-kid-face (pos kid len face)
6218 "Set-face on a child node.
6219 POS is absolute buffer position of parent.
6220 KID is the child node.
6221 LEN is the length to fontify.
6222 FACE is the face to fontify with."
6223 (js2-set-face (+ pos (js2-node-pos kid))
6224 (+ pos (js2-node-pos kid) (js2-node-len kid))
6225 face))
6226
6227 (defsubst js2-fontify-kwd (start length)
6228 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6229
6230 (defsubst js2-clear-face (beg end)
6231 (remove-text-properties beg end '(face nil
6232 help-echo nil
6233 point-entered nil
6234 c-in-sws nil)))
6235
6236 (defsubst js2-record-text-property (beg end prop value)
6237 "Record a text property to set when parsing finishes."
6238 (push (list beg end prop value) js2-mode-deferred-properties))
6239
6240 (defconst js2-ecma-global-props
6241 (concat "^"
6242 (regexp-opt
6243 '("Infinity" "NaN" "undefined" "arguments") t)
6244 "$")
6245 "Value properties of the Ecma-262 Global Object.
6246 Shown at or above `js2-highlight-level' 2.")
6247
6248 ;; might want to add the name "arguments" to this list?
6249 (defconst js2-ecma-object-props
6250 (concat "^"
6251 (regexp-opt
6252 '("prototype" "__proto__" "__parent__") t)
6253 "$")
6254 "Value properties of the Ecma-262 Object constructor.
6255 Shown at or above `js2-highlight-level' 2.")
6256
6257 (defconst js2-ecma-global-funcs
6258 (concat
6259 "^"
6260 (regexp-opt
6261 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6262 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6263 "$")
6264 "Function properties of the Ecma-262 Global object.
6265 Shown at or above `js2-highlight-level' 2.")
6266
6267 (defconst js2-ecma-number-props
6268 (concat "^"
6269 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6270 "NEGATIVE_INFINITY"
6271 "POSITIVE_INFINITY") t)
6272 "$")
6273 "Properties of the Ecma-262 Number constructor.
6274 Shown at or above `js2-highlight-level' 2.")
6275
6276 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6277 "Properties of the Ecma-262 Date constructor.
6278 Shown at or above `js2-highlight-level' 2.")
6279
6280 (defconst js2-ecma-math-props
6281 (concat "^"
6282 (regexp-opt
6283 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6284 t)
6285 "$")
6286 "Properties of the Ecma-262 Math object.
6287 Shown at or above `js2-highlight-level' 2.")
6288
6289 (defconst js2-ecma-math-funcs
6290 (concat "^"
6291 (regexp-opt
6292 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6293 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6294 "$")
6295 "Function properties of the Ecma-262 Math object.
6296 Shown at or above `js2-highlight-level' 2.")
6297
6298 (defconst js2-ecma-function-props
6299 (concat
6300 "^"
6301 (regexp-opt
6302 '(;; properties of the Object prototype object
6303 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6304 "toLocaleString" "toString" "valueOf"
6305 ;; properties of the Function prototype object
6306 "apply" "call"
6307 ;; properties of the Array prototype object
6308 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6309 "splice" "unshift"
6310 ;; properties of the String prototype object
6311 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6312 "localeCompare" "match" "replace" "search" "split" "substring"
6313 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6314 "toUpperCase"
6315 ;; properties of the Number prototype object
6316 "toExponential" "toFixed" "toPrecision"
6317 ;; properties of the Date prototype object
6318 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6319 "getMinutes" "getMonth" "getSeconds" "getTime"
6320 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6321 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6322 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6323 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6324 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6325 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6326 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6327 "toTimeString" "toUTCString"
6328 ;; properties of the RegExp prototype object
6329 "exec" "test"
6330 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6331 "toSource" "__defineGetter__" "__defineSetter__"
6332 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6333 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6334 t)
6335 "$")
6336 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6337 Shown at or above `js2-highlight-level' 3.")
6338
6339 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6340 (let ((target-name (and target
6341 (js2-name-node-p target)
6342 (js2-name-node-name target)))
6343 (prop-name (if prop (js2-name-node-name prop)))
6344 (level1 (>= js2-highlight-level 1))
6345 (level2 (>= js2-highlight-level 2))
6346 (level3 (>= js2-highlight-level 3))
6347 pos
6348 face)
6349 (when level2
6350 (if call-p
6351 (cond
6352 ((and target prop)
6353 (cond
6354 ((and level3 (string-match js2-ecma-function-props prop-name))
6355 (setq face 'font-lock-builtin-face))
6356 ((and target-name prop)
6357 (cond
6358 ((string= target-name "Date")
6359 (if (string-match js2-ecma-date-props prop-name)
6360 (setq face 'font-lock-builtin-face)))
6361 ((string= target-name "Math")
6362 (if (string-match js2-ecma-math-funcs prop-name)
6363 (setq face 'font-lock-builtin-face)))))))
6364 (prop
6365 (if (string-match js2-ecma-global-funcs prop-name)
6366 (setq face 'font-lock-builtin-face))))
6367 (cond
6368 ((and target prop)
6369 (cond
6370 ((string= target-name "Number")
6371 (if (string-match js2-ecma-number-props prop-name)
6372 (setq face 'font-lock-constant-face)))
6373 ((string= target-name "Math")
6374 (if (string-match js2-ecma-math-props prop-name)
6375 (setq face 'font-lock-constant-face)))))
6376 (prop
6377 (if (string-match js2-ecma-object-props prop-name)
6378 (setq face 'font-lock-constant-face)))))
6379 (when face
6380 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6381 (js2-node-pos prop))) ; relative
6382 (+ pos (js2-node-len prop))
6383 face)))))
6384
6385 (defun js2-parse-highlight-member-expr-node (node)
6386 "Perform syntax highlighting of EcmaScript built-in properties.
6387 The variable `js2-highlight-level' governs this highighting."
6388 (let (face target prop name pos end parent call-p callee)
6389 (cond
6390 ;; case 1: simple name, e.g. foo
6391 ((js2-name-node-p node)
6392 (setq name (js2-name-node-name node))
6393 ;; possible for name to be nil in rare cases - saw it when
6394 ;; running js2-mode on an elisp buffer. Might as well try to
6395 ;; make it so js2-mode never barfs.
6396 (when name
6397 (setq face (if (string-match js2-ecma-global-props name)
6398 'font-lock-constant-face))
6399 (when face
6400 (setq pos (js2-node-pos node)
6401 end (+ pos (js2-node-len node)))
6402 (js2-set-face pos end face))))
6403 ;; case 2: property access or function call
6404 ((or (js2-prop-get-node-p node)
6405 ;; highlight function call if expr is a prop-get node
6406 ;; or a plain name (i.e. unqualified function call)
6407 (and (setq call-p (js2-call-node-p node))
6408 (setq callee (js2-call-node-target node)) ; separate setq!
6409 (or (js2-prop-get-node-p callee)
6410 (js2-name-node-p callee))))
6411 (setq parent node
6412 node (if call-p callee node))
6413 (if (and call-p (js2-name-node-p callee))
6414 (setq prop callee)
6415 (setq target (js2-prop-get-node-left node)
6416 prop (js2-prop-get-node-right node)))
6417 (cond
6418 ((js2-name-node-p target)
6419 (if (js2-name-node-p prop)
6420 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6421 (js2-parse-highlight-prop-get parent target prop call-p)
6422 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6423 (js2-parse-highlight-prop-get parent target nil call-p)))
6424 ((js2-name-node-p prop)
6425 ;; case 2c: complex target, simple name, e.g. x[y].bar
6426 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6427
6428 (defun js2-parse-highlight-member-expr-fn-name (expr)
6429 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6430 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6431 We currently only handle the case where the last component is a prop-get
6432 of a simple name. Called before EXPR has a parent node."
6433 (let (pos
6434 (name (and (js2-prop-get-node-p expr)
6435 (js2-prop-get-node-right expr))))
6436 (when (js2-name-node-p name)
6437 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6438 (js2-node-pos name)))
6439 (+ pos (js2-node-len name))
6440 'font-lock-function-name-face
6441 'record))))
6442
6443 ;; source: http://jsdoc.sourceforge.net/
6444 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6445 ;; allows type specifications, and needs work before entering the wild.
6446
6447 (defconst js2-jsdoc-param-tag-regexp
6448 (concat "^\\s-*\\*+\\s-*\\(@"
6449 "\\(?:param\\|argument\\)"
6450 "\\)"
6451 "\\s-*\\({[^}]+}\\)?" ; optional type
6452 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6453 "\\>")
6454 "Matches jsdoc tags with optional type and optional param name.")
6455
6456 (defconst js2-jsdoc-typed-tag-regexp
6457 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6458 (regexp-opt
6459 '("enum"
6460 "extends"
6461 "field"
6462 "id"
6463 "implements"
6464 "lends"
6465 "mods"
6466 "requires"
6467 "return"
6468 "returns"
6469 "throw"
6470 "throws"))
6471 "\\)\\)\\s-*\\({[^}]+}\\)?")
6472 "Matches jsdoc tags with optional type.")
6473
6474 (defconst js2-jsdoc-arg-tag-regexp
6475 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6476 (regexp-opt
6477 '("alias"
6478 "augments"
6479 "borrows"
6480 "bug"
6481 "base"
6482 "config"
6483 "default"
6484 "define"
6485 "exception"
6486 "function"
6487 "member"
6488 "memberOf"
6489 "name"
6490 "namespace"
6491 "property"
6492 "since"
6493 "suppress"
6494 "this"
6495 "throws"
6496 "type"
6497 "version"))
6498 "\\)\\)\\s-+\\([^ \t]+\\)")
6499 "Matches jsdoc tags with a single argument.")
6500
6501 (defconst js2-jsdoc-empty-tag-regexp
6502 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6503 (regexp-opt
6504 '("addon"
6505 "author"
6506 "class"
6507 "const"
6508 "constant"
6509 "constructor"
6510 "constructs"
6511 "deprecated"
6512 "desc"
6513 "description"
6514 "event"
6515 "example"
6516 "exec"
6517 "export"
6518 "fileoverview"
6519 "final"
6520 "function"
6521 "hidden"
6522 "ignore"
6523 "implicitCast"
6524 "inheritDoc"
6525 "inner"
6526 "interface"
6527 "license"
6528 "noalias"
6529 "noshadow"
6530 "notypecheck"
6531 "override"
6532 "owner"
6533 "preserve"
6534 "preserveTry"
6535 "private"
6536 "protected"
6537 "public"
6538 "static"
6539 "supported"
6540 ))
6541 "\\)\\)\\s-*")
6542 "Matches empty jsdoc tags.")
6543
6544 (defconst js2-jsdoc-link-tag-regexp
6545 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6546 "Matches a jsdoc link or code tag.")
6547
6548 (defconst js2-jsdoc-see-tag-regexp
6549 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6550 "Matches a jsdoc @see tag.")
6551
6552 (defconst js2-jsdoc-html-tag-regexp
6553 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6554 "Matches a simple (no attributes) html start- or end-tag.")
6555
6556 (defsubst js2-jsdoc-highlight-helper ()
6557 (js2-set-face (match-beginning 1)
6558 (match-end 1)
6559 'js2-jsdoc-tag-face)
6560 (if (match-beginning 2)
6561 (if (save-excursion
6562 (goto-char (match-beginning 2))
6563 (= (char-after) ?{))
6564 (js2-set-face (1+ (match-beginning 2))
6565 (1- (match-end 2))
6566 'js2-jsdoc-type-face)
6567 (js2-set-face (match-beginning 2)
6568 (match-end 2)
6569 'js2-jsdoc-value-face)))
6570 (if (match-beginning 3)
6571 (js2-set-face (match-beginning 3)
6572 (match-end 3)
6573 'js2-jsdoc-value-face)))
6574
6575 (defun js2-highlight-jsdoc (ast)
6576 "Highlight doc comment tags."
6577 (let ((comments (js2-ast-root-comments ast))
6578 beg end)
6579 (save-excursion
6580 (dolist (node comments)
6581 (when (eq (js2-comment-node-format node) 'jsdoc)
6582 (setq beg (js2-node-abs-pos node)
6583 end (+ beg (js2-node-len node)))
6584 (save-restriction
6585 (narrow-to-region beg end)
6586 (dolist (re (list js2-jsdoc-param-tag-regexp
6587 js2-jsdoc-typed-tag-regexp
6588 js2-jsdoc-arg-tag-regexp
6589 js2-jsdoc-link-tag-regexp
6590 js2-jsdoc-see-tag-regexp
6591 js2-jsdoc-empty-tag-regexp))
6592 (goto-char beg)
6593 (while (re-search-forward re nil t)
6594 (js2-jsdoc-highlight-helper)))
6595 ;; simple highlighting for html tags
6596 (goto-char beg)
6597 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6598 (js2-set-face (match-beginning 1)
6599 (match-end 1)
6600 'js2-jsdoc-html-tag-delimiter-face)
6601 (js2-set-face (match-beginning 2)
6602 (match-end 2)
6603 'js2-jsdoc-html-tag-name-face)
6604 (js2-set-face (match-beginning 3)
6605 (match-end 3)
6606 'js2-jsdoc-html-tag-delimiter-face))))))))
6607
6608 (defun js2-highlight-assign-targets (node left right)
6609 "Highlight function properties and external variables."
6610 (let (leftpos end name)
6611 ;; highlight vars and props assigned function values
6612 (when (js2-function-node-p right)
6613 (cond
6614 ;; var foo = function() {...}
6615 ((js2-name-node-p left)
6616 (setq name left))
6617 ;; foo.bar.baz = function() {...}
6618 ((and (js2-prop-get-node-p left)
6619 (js2-name-node-p (js2-prop-get-node-right left)))
6620 (setq name (js2-prop-get-node-right left))))
6621 (when name
6622 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6623 (+ leftpos (js2-node-len name))
6624 'font-lock-function-name-face
6625 'record)))
6626 ;; save variable assignments so we can check for undeclared later
6627 ;; (can't do it here since var decls can come at end of script)
6628 (when (and js2-highlight-external-variables
6629 (setq name (js2-member-expr-leftmost-name left)))
6630 (push (list name js2-current-scope
6631 (setq leftpos (js2-node-abs-pos name))
6632 (setq end (+ leftpos (js2-node-len name))))
6633 js2-recorded-assignments))))
6634
6635 (defun js2-highlight-undeclared-vars ()
6636 "After entire parse is finished, look for undeclared variable assignments.
6637 We have to wait until entire buffer is parsed, since JavaScript permits var
6638 decls to occur after they're used.
6639
6640 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6641 it is considered declared."
6642 (let (name)
6643 (dolist (entry js2-recorded-assignments)
6644 (destructuring-bind (name-node scope pos end) entry
6645 (setq name (js2-name-node-name name-node))
6646 (unless (or (member name js2-global-externs)
6647 (member name js2-default-externs)
6648 (member name js2-additional-externs)
6649 (js2-get-defining-scope scope name))
6650 (js2-set-face pos end 'js2-external-variable-face 'record)
6651 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6652 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6653 (setq js2-recorded-assignments nil)))
6654
6655 ;;; IMenu support
6656
6657 ;; We currently only support imenu, but eventually should support speedbar and
6658 ;; possibly other browsing mechanisms.
6659
6660 ;; The basic strategy is to identify function assignment targets of the form
6661 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6662 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6663 ;; for imenu after parsing is finished.
6664
6665 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6666 ;; JavaScript, and the general problem is undecidable. However, several forms
6667 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6668 ;; include:
6669
6670 ;; function foo() -- function declaration
6671 ;; foo = function() -- function expression assigned to variable
6672 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6673 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6674 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6675 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6676 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6677 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6678 ;; function foo() {function bar() {...}} -- nested function
6679 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6680
6681 ;; This list boils down to a few forms that can be combined recursively.
6682 ;; Top-level named function declarations include both the left-hand (name)
6683 ;; and the right-hand (function value) expressions needed to produce an imenu
6684 ;; entry. The other "right-hand" forms we need to look for are:
6685 ;; - functions declared as props/getters/setters in object literals
6686 ;; - nested named function declarations
6687 ;; The "left-hand" expressions that functions can be assigned to include:
6688 ;; - local/global variables
6689 ;; - nested property-get expressions like a.b.c.d
6690 ;; - element gets like foo[10] or foo['bar'] where the index
6691 ;; expression can be trivially converted to a property name. They
6692 ;; effectively then become property gets.
6693
6694 ;; All the different definition types are canonicalized into the form
6695 ;; foo.bar.baz = position-of-function-keyword
6696
6697 ;; We need to build a trie-like structure for imenu. As an example,
6698 ;; consider the following JavaScript code:
6699
6700 ;; a = function() {...} // function at position 5
6701 ;; b = function() {...} // function at position 25
6702 ;; foo = function() {...} // function at position 100
6703 ;; foo.bar = function() {...} // function at position 200
6704 ;; foo.bar.baz = function() {...} // function at position 300
6705 ;; foo.bar.zab = function() {...} // function at position 400
6706
6707 ;; During parsing we accumulate an entry for each definition in
6708 ;; the variable `js2-imenu-recorder', like so:
6709
6710 ;; '((a 5)
6711 ;; (b 25)
6712 ;; (foo 100)
6713 ;; (foo bar 200)
6714 ;; (foo bar baz 300)
6715 ;; (foo bar zab 400))
6716
6717 ;; After parsing these entries are merged into this alist-trie:
6718
6719 ;; '((a . 1)
6720 ;; (b . 2)
6721 ;; (foo (<definition> . 3)
6722 ;; (bar (<definition> . 6)
6723 ;; (baz . 100)
6724 ;; (zab . 200))))
6725
6726 ;; Note the wacky need for a <definition> name. The token can be anything
6727 ;; that isn't a valid JavaScript identifier, because you might make foo
6728 ;; a function and then start setting properties on it that are also functions.
6729
6730 (defsubst js2-prop-node-name (node)
6731 "Return the name of a node that may be a property-get/property-name.
6732 If NODE is not a valid name-node, string-node or integral number-node,
6733 returns nil. Otherwise returns the string name/value of the node."
6734 (cond
6735 ((js2-name-node-p node)
6736 (js2-name-node-name node))
6737 ((js2-string-node-p node)
6738 (js2-string-node-value node))
6739 ((and (js2-number-node-p node)
6740 (string-match "^[0-9]+$" (js2-number-node-value node)))
6741 (js2-number-node-value node))
6742 ((js2-this-node-p node)
6743 "this")))
6744
6745 (defsubst js2-node-qname-component (node)
6746 "Test function: return the name of this node, if it contributes to a qname.
6747 Returns nil if the node doesn't contribute."
6748 (copy-sequence
6749 (or (js2-prop-node-name node)
6750 (if (and (js2-function-node-p node)
6751 (js2-function-node-name node))
6752 (js2-name-node-name (js2-function-node-name node))))))
6753
6754 (defsubst js2-record-function-qname (fn-node qname)
6755 "Associate FN-NODE with its QNAME for later lookup.
6756 This is used in postprocessing the chain list. When we find a chain
6757 whose first element is a js2-THIS keyword node, we look up the parent
6758 function and see (using this map) whether it is the tail of a chain.
6759 If so, we replace the this-node with a copy of the parent's qname."
6760 (unless js2-imenu-function-map
6761 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6762 (puthash fn-node qname js2-imenu-function-map))
6763
6764 (defun js2-record-imenu-functions (node &optional var)
6765 "Record function definitions for imenu.
6766 NODE is a function node or an object literal.
6767 VAR, if non-nil, is the expression that NODE is being assigned to."
6768 (when js2-parse-ide-mode
6769 (let ((fun-p (js2-function-node-p node))
6770 qname left fname-node pos)
6771 (cond
6772 ;; non-anonymous function declaration?
6773 ((and fun-p
6774 (not var)
6775 (setq fname-node (js2-function-node-name node)))
6776 (push (setq qname (list fname-node (js2-node-pos node)))
6777 js2-imenu-recorder)
6778 (js2-record-function-qname node qname))
6779 ;; for remaining forms, compute left-side tree branch first
6780 ((and var (setq qname (js2-compute-nested-prop-get var)))
6781 (cond
6782 ;; foo.bar.baz = function
6783 (fun-p
6784 (push (nconc qname (list (js2-node-pos node)))
6785 js2-imenu-recorder)
6786 (js2-record-function-qname node qname))
6787 ;; foo.bar.baz = object-literal
6788 ;; look for nested functions: {a: {b: function() {...} }}
6789 ((js2-object-node-p node)
6790 (js2-record-object-literal node qname))))))))
6791
6792 (defun js2-compute-nested-prop-get (node)
6793 "If NODE is of form foo.bar.baz, return component nodes as a list.
6794 Otherwise returns nil. Element-gets can be treated as property-gets
6795 if the index expression is a name, a string, or a positive integer."
6796 (let (left right head)
6797 (cond
6798 ((or (js2-name-node-p node)
6799 (js2-this-node-p node))
6800 (list node))
6801 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6802 ((js2-prop-get-node-p node) ; includes elem-get nodes
6803 (setq left (js2-prop-get-node-left node)
6804 right (js2-prop-get-node-right node))
6805 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6806 (js2-name-node-p left)
6807 (js2-this-node-p left)) ; or left == foo
6808 (or (js2-name-node-p right) ; .bar
6809 (js2-string-node-p right) ; ['bar']
6810 (and (js2-number-node-p right) ; [10]
6811 (string-match "^[0-9]+$"
6812 (js2-number-node-value right)))))
6813 (if (setq head (js2-compute-nested-prop-get left))
6814 (nconc head (list right))))))))
6815
6816 (defun js2-record-object-literal (node qname)
6817 "Recursively process an object literal looking for functions.
6818 NODE is an object literal that is the right-hand child of an assignment
6819 expression. QNAME is a list of nodes representing the assignment target,
6820 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6821 We do a depth-first traversal of NODE. Any functions we find are prefixed
6822 with QNAME plus the property name of the function and appended to the
6823 variable `js2-imenu-recorder'."
6824 ;; Elements are relative to parent position, which is still absolute,
6825 ;; since the parser passes the assignment target and value expressions
6826 ;; to us before they are added as children of the assignment node.
6827 (let ((pos (js2-node-pos node))
6828 left right)
6829 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6830 (setq left (js2-infix-node-left e))
6831 (cond
6832 ;; foo: function() {...}
6833 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6834 (when (js2-prop-node-name left)
6835 ;; As a policy decision, we record the position of the property,
6836 ;; not the position of the `function' keyword, since the property
6837 ;; is effectively the name of the function.
6838 (push (append qname (list left) (list (+ pos (js2-node-pos e))))
6839 js2-imenu-recorder)
6840 (js2-record-function-qname right qname)))
6841 ;; foo: {object-literal} -- add foo to qname and recurse
6842 ((js2-object-node-p right)
6843 (js2-record-object-literal right
6844 (append qname (list (js2-infix-node-left e)))))))))
6845
6846 (defsubst js2-node-top-level-decl-p (node)
6847 "Return t if NODE's name is defined in the top-level scope.
6848 Also returns t if NODE's name is not defined in any scope, since it implies
6849 that it's an external variable, which must also be in the top-level scope."
6850 (let* ((name (js2-prop-node-name node))
6851 (this-scope (js2-node-get-enclosing-scope node))
6852 defining-scope)
6853 (cond
6854 ((js2-this-node-p node)
6855 nil)
6856 ((null this-scope)
6857 t)
6858 ((setq defining-scope (js2-get-defining-scope this-scope name))
6859 (js2-ast-root-p defining-scope))
6860 (t t))))
6861
6862 (defun js2-browse-postprocess-chains (chains)
6863 "Modify function-declaration name chains after parsing finishes.
6864 Some of the information is only available after the parse tree is complete.
6865 For instance, following a 'this' reference requires a parent function node."
6866 (let (result head fn parent-chain p elem)
6867 (dolist (chain chains)
6868 ;; examine the head of each node to get its defining scope
6869 (setq head (car chain))
6870 (cond
6871 ;; if top-level/external, keep as-is
6872 ((js2-node-top-level-decl-p head)
6873 (push chain result))
6874 ;; check for a this-reference
6875 ((eq (js2-node-type head) js2-THIS)
6876 (setq fn (js2-node-parent-script-or-fn head))
6877 ;; if there is no parent function, or if the parent function
6878 ;; is nested, discard the head node and keep the rest of the chain.
6879 (if (or (null fn) (js2-nested-function-p fn))
6880 (push (cdr chain) result)
6881 ;; else look up parent in function-map. If not found, discard chain.
6882 (when (setq parent-chain (and js2-imenu-function-map
6883 (gethash fn js2-imenu-function-map)))
6884 ;; else discard head node and prefix parent fn qname, which is
6885 ;; the parent-chain sans tail, to this chain.
6886 (push (append (butlast parent-chain) (cdr chain)) result))))))
6887 ;; finally replace each node in each chain with its name.
6888 (dolist (chain result)
6889 (setq p chain)
6890 (while p
6891 (if (js2-node-p (setq elem (car p)))
6892 (setcar p (js2-node-qname-component elem)))
6893 (setq p (cdr p))))
6894 result))
6895
6896 ;; Merge name chains into a trie-like tree structure of nested lists.
6897 ;; To simplify construction of the trie, we first build it out using the rule
6898 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6899 ;; [key, num-or-list]. The second element can be a number; if so, this key
6900 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6901 ;; associated with the key at this level.) Otherwise the second element is
6902 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6903 ;; a simple recursive formulation.
6904 ;;
6905 ;; js2-mode is building the data structure for imenu. The imenu documentation
6906 ;; claims that it's the structure above, but in practice it wants the children
6907 ;; at the same list level as the key for that level, which is how I've drawn
6908 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6909 ;; list wrapper around the children at each level.
6910 ;;
6911 ;; A completed nested imenu-alist entry looks like this:
6912 ;; '(("foo"
6913 ;; ("<definition>" . 7)
6914 ;; ("bar"
6915 ;; ("a" . 40)
6916 ;; ("b" . 60))))
6917 ;;
6918 ;; In particular, the documentation for `imenu--index-alist' says that
6919 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6920 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6921
6922 (defsubst js2-treeify (lst)
6923 "Convert (a b c d) to (a ((b ((c d)))))"
6924 (if (null (cddr lst)) ; list length <= 2
6925 lst
6926 (list (car lst) (list (js2-treeify (cdr lst))))))
6927
6928 (defun js2-build-alist-trie (chains trie)
6929 "Merge declaration name chains into a trie-like alist structure for imenu.
6930 CHAINS is the qname chain list produced during parsing. TRIE is a
6931 list of elements built up so far."
6932 (let (head tail pos branch kids)
6933 (dolist (chain chains)
6934 (setq head (car chain)
6935 tail (cdr chain)
6936 pos (if (numberp (car tail)) (car tail))
6937 branch (js2-find-if (lambda (n)
6938 (string= (car n) head))
6939 trie)
6940 kids (second branch))
6941 (cond
6942 ;; case 1: this key isn't in the trie yet
6943 ((null branch)
6944 (if trie
6945 (setcdr (last trie) (list (js2-treeify chain)))
6946 (setq trie (list (js2-treeify chain)))))
6947 ;; case 2: key is present with a single number entry: replace w/ list
6948 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6949 ;; ("<definition>" 20)))
6950 ((numberp kids)
6951 (setcar (cdr branch)
6952 (list (list "<definition-1>" kids)
6953 (if pos
6954 (list "<definition-2>" pos)
6955 (js2-treeify tail)))))
6956 ;; case 3: key is there (with kids), and we're a number entry
6957 (pos
6958 (setcdr (last kids)
6959 (list
6960 (list (format "<definition-%d>"
6961 (1+ (loop for kid in kids
6962 count (eq ?< (aref (car kid) 0)))))
6963 pos))))
6964 ;; case 4: key is there with kids, need to merge in our chain
6965 (t
6966 (js2-build-alist-trie (list tail) kids))))
6967 trie))
6968
6969 (defun js2-flatten-trie (trie)
6970 "Convert TRIE to imenu-format.
6971 Recurses through nodes, and for each one whose second element is a list,
6972 appends the list's flattened elements to the current element. Also
6973 changes the tails into conses. For instance, this pre-flattened trie
6974
6975 '(a ((b 20)
6976 (c ((d 30)
6977 (e 40)))))
6978
6979 becomes
6980
6981 '(a (b . 20)
6982 (c (d . 30)
6983 (e . 40)))
6984
6985 Note that the root of the trie has no key, just a list of chains.
6986 This is also true for the value of any key with multiple children,
6987 e.g. key 'c' in the example above."
6988 (cond
6989 ((listp (car trie))
6990 (mapcar #'js2-flatten-trie trie))
6991 (t
6992 (if (numberp (second trie))
6993 (cons (car trie) (second trie))
6994 ;; else pop list and append its kids
6995 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6996
6997 (defun js2-build-imenu-index ()
6998 "Turn `js2-imenu-recorder' into an imenu data structure."
6999 (unless (eq js2-imenu-recorder 'empty)
7000 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7001 (result (js2-build-alist-trie chains nil)))
7002 (js2-flatten-trie result))))
7003
7004 (defun js2-test-print-chains (chains)
7005 "Print a list of qname chains.
7006 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7007 i.e. one or more nodes, and an integer position as the list tail."
7008 (mapconcat (lambda (chain)
7009 (concat "("
7010 (mapconcat (lambda (elem)
7011 (if (js2-node-p elem)
7012 (or (js2-node-qname-component elem)
7013 "nil")
7014 (number-to-string elem)))
7015 chain
7016 " ")
7017 ")"))
7018 chains
7019 "\n"))
7020
7021 ;;; Parser
7022
7023 (defconst js2-version "1.8.0"
7024 "Version of JavaScript supported, plus minor js2 version.")
7025
7026 (defmacro js2-record-face (face)
7027 "Record a style run of FACE for the current token."
7028 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7029
7030 (defsubst js2-node-end (n)
7031 "Computes the absolute end of node N.
7032 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7033 is only true until the node is added to its parent; i.e., while parsing."
7034 (+ (js2-node-pos n)
7035 (js2-node-len n)))
7036
7037 (defsubst js2-record-comment ()
7038 "Record a comment in `js2-scanned-comments'."
7039 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7040 :format js2-ts-comment-type)
7041 js2-scanned-comments)
7042 (when js2-parse-ide-mode
7043 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7044 'font-lock-doc-face
7045 'font-lock-comment-face))
7046 (when (memq js2-ts-comment-type '(html preprocessor))
7047 ;; Tell cc-engine the bounds of the comment.
7048 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7049
7050 ;; This function is called depressingly often, so it should be fast.
7051 ;; Most of the time it's looking at the same token it peeked before.
7052 (defsubst js2-peek-token ()
7053 "Returns the next token without consuming it.
7054 If previous token was consumed, calls scanner to get new token.
7055 If previous token was -not- consumed, returns it (idempotent).
7056
7057 This function will not return a newline (js2-EOL) - instead, it
7058 gobbles newlines until it finds a non-newline token, and flags
7059 that token as appearing just after a newline.
7060
7061 This function will also not return a js2-COMMENT. Instead, it
7062 records comments found in `js2-scanned-comments'. If the token
7063 returned by this function immediately follows a jsdoc comment,
7064 the token is flagged as such.
7065
7066 Note that this function always returned the un-flagged token!
7067 The flags, if any, are saved in `js2-current-flagged-token'."
7068 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7069 js2-current-token ; most common case - return already-peeked token
7070 (let ((tt (js2-get-token)) ; call scanner
7071 saw-eol
7072 face)
7073 ;; process comments and whitespace
7074 (while (or (= tt js2-EOL)
7075 (= tt js2-COMMENT))
7076 (if (= tt js2-EOL)
7077 (setq saw-eol t)
7078 (setq saw-eol nil)
7079 (if js2-record-comments
7080 (js2-record-comment)))
7081 (setq tt (js2-get-token))) ; call scanner
7082 (setq js2-current-token tt
7083 js2-current-flagged-token (if saw-eol
7084 (logior tt js2-ti-after-eol)
7085 tt))
7086 ;; perform lexical fontification as soon as token is scanned
7087 (when js2-parse-ide-mode
7088 (cond
7089 ((minusp tt)
7090 (js2-record-face 'js2-error-face))
7091 ((setq face (aref js2-kwd-tokens tt))
7092 (js2-record-face face))
7093 ((and (= tt js2-NAME)
7094 (equal js2-ts-string "undefined"))
7095 (js2-record-face 'font-lock-constant-face))))
7096 tt))) ; return unflagged token
7097
7098 (defsubst js2-peek-flagged-token ()
7099 "Returns the current token along with any flags set for it."
7100 (js2-peek-token)
7101 js2-current-flagged-token)
7102
7103 (defsubst js2-consume-token ()
7104 (setq js2-current-flagged-token js2-EOF))
7105
7106 (defsubst js2-next-token ()
7107 (prog1
7108 (js2-peek-token)
7109 (js2-consume-token)))
7110
7111 (defsubst js2-next-flagged-token ()
7112 (js2-peek-token)
7113 (prog1 js2-current-flagged-token
7114 (js2-consume-token)))
7115
7116 (defsubst js2-match-token (match)
7117 "Consume and return t if next token matches MATCH, a bytecode.
7118 Returns nil and consumes nothing if MATCH is not the next token."
7119 (if (/= (js2-peek-token) match)
7120 nil
7121 (js2-consume-token)
7122 t))
7123
7124 (defsubst js2-valid-prop-name-token (tt)
7125 (or (= tt js2-NAME)
7126 (and js2-allow-keywords-as-property-names
7127 (plusp tt)
7128 (aref js2-kwd-tokens tt))))
7129
7130 (defsubst js2-match-prop-name ()
7131 "Consume token and return t if next token is a valid property name.
7132 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7133 is non-nil and it's a keyword token."
7134 (if (js2-valid-prop-name-token (js2-peek-token))
7135 (progn
7136 (js2-consume-token)
7137 t)
7138 nil))
7139
7140 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7141 (if (js2-match-prop-name)
7142 t
7143 (js2-report-error msg-id nil pos len)
7144 nil))
7145
7146 (defsubst js2-peek-token-or-eol ()
7147 "Return js2-EOL if the current token immediately follows a newline.
7148 Else returns the current token. Used in situations where we don't
7149 consider certain token types valid if they are preceded by a newline.
7150 One example is the postfix ++ or -- operator, which has to be on the
7151 same line as its operand."
7152 (let ((tt (js2-peek-token)))
7153 ;; Check for last peeked token flags
7154 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7155 js2-EOL
7156 tt)))
7157
7158 (defsubst js2-set-check-for-label ()
7159 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7160 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7161
7162 (defsubst js2-must-match (token msg-id &optional pos len)
7163 "Match next token to token code TOKEN, or record a syntax error.
7164 MSG-ID is the error message to report if the match fails.
7165 Returns t on match, nil if no match."
7166 (if (js2-match-token token)
7167 t
7168 (js2-report-error msg-id nil pos len)
7169 nil))
7170
7171 (defsubst js2-inside-function ()
7172 (plusp js2-nesting-of-function))
7173
7174 (defsubst js2-set-requires-activation ()
7175 (if (js2-function-node-p js2-current-script-or-fn)
7176 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7177
7178 (defsubst js2-check-activation-name (name token)
7179 (when (js2-inside-function)
7180 ;; skip language-version 1.2 check from Rhino
7181 (if (or (string= "arguments" name)
7182 (and js2-compiler-activation-names ; only used in codegen
7183 (gethash name js2-compiler-activation-names)))
7184 (js2-set-requires-activation))))
7185
7186 (defsubst js2-set-is-generator ()
7187 (if (js2-function-node-p js2-current-script-or-fn)
7188 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7189
7190 (defsubst js2-must-have-xml ()
7191 (unless js2-compiler-xml-available
7192 (js2-report-error "msg.XML.not.available")))
7193
7194 (defsubst js2-push-scope (scope)
7195 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7196 (assert (js2-scope-p scope))
7197 (assert (null (js2-scope-parent-scope scope)))
7198 (assert (not (eq js2-current-scope scope)))
7199 (setf (js2-scope-parent-scope scope) js2-current-scope
7200 js2-current-scope scope))
7201
7202 (defsubst js2-pop-scope ()
7203 (setq js2-current-scope
7204 (js2-scope-parent-scope js2-current-scope)))
7205
7206 (defsubst js2-enter-loop (loop-node)
7207 (push loop-node js2-loop-set)
7208 (push loop-node js2-loop-and-switch-set)
7209 (js2-push-scope loop-node)
7210 ;; Tell the current labeled statement (if any) its statement,
7211 ;; and set the jump target of the first label to the loop.
7212 ;; These are used in `js2-parse-continue' to verify that the
7213 ;; continue target is an actual labeled loop. (And for codegen.)
7214 (when js2-labeled-stmt
7215 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7216 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7217 js2-labeled-stmt))) loop-node)))
7218
7219 (defsubst js2-exit-loop ()
7220 (pop js2-loop-set)
7221 (pop js2-loop-and-switch-set)
7222 (js2-pop-scope))
7223
7224 (defsubst js2-enter-switch (switch-node)
7225 (push switch-node js2-loop-and-switch-set))
7226
7227 (defsubst js2-exit-switch ()
7228 (pop js2-loop-and-switch-set))
7229
7230 (defun js2-parse (&optional buf cb)
7231 "Tells the js2 parser to parse a region of JavaScript.
7232
7233 BUF is a buffer or buffer name containing the code to parse.
7234 Call `narrow-to-region' first to parse only part of the buffer.
7235
7236 The returned AST root node is given some additional properties:
7237 `node-count' - total number of nodes in the AST
7238 `buffer' - BUF. The buffer it refers to may change or be killed,
7239 so the value is not necessarily reliable.
7240
7241 An optional callback CB can be specified to report parsing
7242 progress. If `(functionp CB)' returns t, it will be called with
7243 the current line number once before parsing begins, then again
7244 each time the lexer reaches a new line number.
7245
7246 CB can also be a list of the form `(symbol cb ...)' to specify
7247 multiple callbacks with different criteria. Each symbol is a
7248 criterion keyword, and the following element is the callback to
7249 call
7250
7251 :line - called whenever the line number changes
7252 :token - called for each new token consumed
7253
7254 The list of criteria could be extended to include entering or
7255 leaving a statement, an expression, or a function definition."
7256 (if (and cb (not (functionp cb)))
7257 (error "criteria callbacks not yet implemented"))
7258 (let ((inhibit-point-motion-hooks t)
7259 (js2-compiler-xml-available (>= js2-language-version 160))
7260 ;; This is a recursive-descent parser, so give it a big stack.
7261 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7262 (max-specpdl-size (max max-specpdl-size 3000))
7263 (case-fold-search nil)
7264 ast)
7265 (or buf (setq buf (current-buffer)))
7266 (message nil) ; clear any error message from previous parse
7267 (save-excursion
7268 (set-buffer buf)
7269 (setq js2-scanned-comments nil
7270 js2-parsed-errors nil
7271 js2-parsed-warnings nil
7272 js2-imenu-recorder nil
7273 js2-imenu-function-map nil
7274 js2-label-set nil)
7275 (js2-init-scanner)
7276 (setq ast (js2-with-unmodifying-text-property-changes
7277 (js2-do-parse)))
7278 (unless js2-ts-hit-eof
7279 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7280 (setf (js2-ast-root-errors ast) js2-parsed-errors
7281 (js2-ast-root-warnings ast) js2-parsed-warnings)
7282 ;; if we didn't find any declarations, put a dummy in this list so we
7283 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7284 (unless js2-imenu-recorder
7285 (setq js2-imenu-recorder 'empty))
7286 (run-hooks 'js2-parse-finished-hook)
7287 ast)))
7288
7289 ;; Corresponds to Rhino's Parser.parse() method.
7290 (defun js2-do-parse ()
7291 "Parse current buffer starting from current point.
7292 Scanner should be initialized."
7293 (let ((pos js2-ts-cursor)
7294 (end js2-ts-cursor) ; in case file is empty
7295 root n tt)
7296 ;; initialize buffer-local parsing vars
7297 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7298 js2-current-script-or-fn root
7299 js2-current-scope root
7300 js2-current-flagged-token js2-EOF
7301 js2-nesting-of-function 0
7302 js2-labeled-stmt nil
7303 js2-recorded-assignments nil) ; for js2-highlight
7304 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7305 (if (= tt js2-FUNCTION)
7306 (progn
7307 (js2-consume-token)
7308 (setq n (js2-parse-function (if js2-called-by-compile-function
7309 'FUNCTION_EXPRESSION
7310 'FUNCTION_STATEMENT)))
7311 (js2-record-imenu-functions n))
7312 ;; not a function - parse a statement
7313 (setq n (js2-parse-statement)))
7314 ;; add function or statement to script
7315 (setq end (js2-node-end n))
7316 (js2-block-node-push root n))
7317 ;; add comments to root in lexical order
7318 (when js2-scanned-comments
7319 ;; if we find a comment beyond end of normal kids, use its end
7320 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7321 (dolist (comment js2-scanned-comments)
7322 (push comment (js2-ast-root-comments root))
7323 (js2-node-add-children root comment)))
7324 (setf (js2-node-len root) (- end pos))
7325 ;; Give extensions a chance to muck with things before highlighting starts.
7326 (dolist (callback js2-post-parse-callbacks)
7327 (funcall callback))
7328 (js2-highlight-undeclared-vars)
7329 root))
7330
7331 (defun js2-function-parser ()
7332 (js2-consume-token)
7333 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7334
7335 (defun js2-parse-function-closure-body (fn-node)
7336 "Parse a JavaScript 1.8 function closure body."
7337 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7338 (if js2-ts-hit-eof
7339 (js2-report-error "msg.no.brace.body" nil
7340 (js2-node-pos fn-node)
7341 (- js2-ts-cursor (js2-node-pos fn-node)))
7342 (js2-node-add-children fn-node
7343 (setf (js2-function-node-body fn-node)
7344 (js2-parse-expr t))))))
7345
7346 (defun js2-parse-function-body (fn-node)
7347 (js2-must-match js2-LC "msg.no.brace.body"
7348 (js2-node-pos fn-node)
7349 (- js2-ts-cursor (js2-node-pos fn-node)))
7350 (let ((pos js2-token-beg) ; LC position
7351 (pn (make-js2-block-node)) ; starts at LC position
7352 tt
7353 end)
7354 (incf js2-nesting-of-function)
7355 (unwind-protect
7356 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7357 (= tt js2-EOF)
7358 (= tt js2-RC)))
7359 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7360 (js2-parse-statement)
7361 (js2-consume-token)
7362 (js2-parse-function 'FUNCTION_STATEMENT))))
7363 (decf js2-nesting-of-function))
7364 (setq end js2-token-end) ; assume no curly and leave at current token
7365 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7366 (setq end js2-token-end))
7367 (setf (js2-node-pos pn) pos
7368 (js2-node-len pn) (- end pos))
7369 (setf (js2-function-node-body fn-node) pn)
7370 (js2-node-add-children fn-node pn)
7371 pn))
7372
7373 (defun js2-parse-function-params (fn-node pos)
7374 (if (js2-match-token js2-RP)
7375 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7376 (let (params len param)
7377 (loop for tt = (js2-peek-token)
7378 do
7379 (cond
7380 ;; destructuring param
7381 ((or (= tt js2-LB) (= tt js2-LC))
7382 (push (js2-parse-primary-expr t) params))
7383 ;; simple name
7384 (t
7385 (js2-must-match js2-NAME "msg.no.parm")
7386 (js2-record-face 'js2-function-param-face)
7387 (setq param (js2-create-name-node))
7388 (js2-define-symbol js2-LP js2-ts-string param)
7389 (push param params)))
7390 while
7391 (js2-match-token js2-COMMA))
7392 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7393 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7394 (dolist (p params)
7395 (js2-node-add-children fn-node p)
7396 (push p (js2-function-node-params fn-node))))))
7397
7398 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7399 "Possibly show inconsistent-return warning.
7400 Last token scanned is the close-curly for the function body."
7401 (when (and js2-mode-show-strict-warnings
7402 js2-strict-inconsistent-return-warning
7403 (not (js2-has-consistent-return-usage
7404 (js2-function-node-body fn-node))))
7405 ;; Have it extend from close-curly to bol or beginning of block.
7406 (let ((pos (save-excursion
7407 (goto-char js2-token-end)
7408 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7409 (point-at-bol))))
7410 (end js2-token-end))
7411 (if (plusp (js2-name-node-length name))
7412 (js2-add-strict-warning "msg.no.return.value"
7413 (js2-name-node-name name) pos end)
7414 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7415
7416 (defun js2-parse-function (function-type)
7417 "Function parser. FUNCTION-TYPE is a symbol."
7418 (let ((pos js2-token-beg) ; start of 'function' keyword
7419 name
7420 name-beg
7421 name-end
7422 fn-node
7423 lp
7424 (synthetic-type function-type)
7425 member-expr-node)
7426 ;; parse function name, expression, or non-name (anonymous)
7427 (cond
7428 ;; function foo(...)
7429 ((js2-match-token js2-NAME)
7430 (setq name (js2-create-name-node t)
7431 name-beg js2-token-beg
7432 name-end js2-token-end)
7433 (unless (js2-match-token js2-LP)
7434 (when js2-allow-member-expr-as-function-name
7435 ;; function foo.bar(...)
7436 (setq member-expr-node name
7437 name nil
7438 member-expr-node (js2-parse-member-expr-tail
7439 nil member-expr-node)))
7440 (js2-must-match js2-LP "msg.no.paren.parms")))
7441 ((js2-match-token js2-LP)
7442 nil) ; anonymous function: leave name as null
7443 (t
7444 ;; function random-member-expr(...)
7445 (when js2-allow-member-expr-as-function-name
7446 ;; Note that memberExpr can not start with '(' like
7447 ;; in function (1+2).toString(), because 'function (' already
7448 ;; processed as anonymous function
7449 (setq member-expr-node (js2-parse-member-expr)))
7450 (js2-must-match js2-LP "msg.no.paren.parms")))
7451 (if (= js2-current-token js2-LP) ; eventually matched LP?
7452 (setq lp js2-token-beg))
7453 (if member-expr-node
7454 (progn
7455 (setq synthetic-type 'FUNCTION_EXPRESSION)
7456 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7457 (if name
7458 (js2-set-face name-beg name-end
7459 'font-lock-function-name-face 'record)))
7460 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7461 (plusp (js2-name-node-length name)))
7462 ;; Function statements define a symbol in the enclosing scope
7463 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7464 (setf fn-node (make-js2-function-node :pos pos
7465 :name name
7466 :form function-type
7467 :lp (if lp (- lp pos))))
7468 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7469 ;; 1. Nested functions are not affected by the dynamic scope flag
7470 ;; as dynamic scope is already a parent of their scope.
7471 ;; 2. Functions defined under the with statement also immune to
7472 ;; this setup, in which case dynamic scope is ignored in favor
7473 ;; of the with object.
7474 (setf (js2-function-node-ignore-dynamic fn-node) t))
7475 ;; dynamically bind all the per-function variables
7476 (let ((js2-current-script-or-fn fn-node)
7477 (js2-current-scope fn-node)
7478 (js2-nesting-of-with 0)
7479 (js2-end-flags 0)
7480 js2-label-set
7481 js2-loop-set
7482 js2-loop-and-switch-set)
7483 (js2-parse-function-params fn-node pos)
7484 (if (and (>= js2-language-version 180)
7485 (/= (js2-peek-token) js2-LC))
7486 (js2-parse-function-closure-body fn-node)
7487 (js2-parse-function-body fn-node))
7488 (if name
7489 (js2-node-add-children fn-node name))
7490 (js2-check-inconsistent-return-warning fn-node name)
7491 ;; Function expressions define a name only in the body of the
7492 ;; function, and only if not hidden by a parameter name
7493 (if (and name
7494 (eq synthetic-type 'FUNCTION_EXPRESSION)
7495 (null (js2-scope-get-symbol js2-current-scope
7496 (js2-name-node-name name))))
7497 (js2-define-symbol js2-FUNCTION
7498 (js2-name-node-name name)
7499 fn-node))
7500 (if (and name
7501 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7502 (js2-record-imenu-functions fn-node)))
7503 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7504 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7505 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7506 ;; We wait until after parsing the function to set its parent scope,
7507 ;; since `js2-define-symbol' needs the defining-scope check to stop
7508 ;; at the function boundary when checking for redeclarations.
7509 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7510 fn-node))
7511
7512 (defun js2-parse-statements (&optional parent)
7513 "Parse a statement list. Last token consumed must be js2-LC.
7514
7515 PARENT can be a `js2-block-node', in which case the statements are
7516 appended to PARENT. Otherwise a new `js2-block-node' is created
7517 and returned.
7518
7519 This function does not match the closing js2-RC: the caller
7520 matches the RC so it can provide a suitable error message if not
7521 matched. This means it's up to the caller to set the length of
7522 the node to include the closing RC. The node start pos is set to
7523 the absolute buffer start position, and the caller should fix it
7524 up to be relative to the parent node. All children of this block
7525 node are given relative start positions and correct lengths."
7526 (let ((pn (or parent (make-js2-block-node)))
7527 tt)
7528 (setf (js2-node-pos pn) js2-token-beg)
7529 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7530 (/= tt js2-RC))
7531 (js2-block-node-push pn (js2-parse-statement)))
7532 pn))
7533
7534 (defun js2-parse-statement ()
7535 (let (tt pn beg end)
7536 ;; coarse-grained user-interrupt check - needs work
7537 (and js2-parse-interruptable-p
7538 (zerop (% (incf js2-parse-stmt-count)
7539 js2-statements-per-pause))
7540 (input-pending-p)
7541 (throw 'interrupted t))
7542 (setq pn (js2-statement-helper))
7543 ;; no-side-effects warning check
7544 (unless (js2-node-has-side-effects pn)
7545 (setq end (js2-node-end pn))
7546 (save-excursion
7547 (goto-char end)
7548 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7549 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7550 pn))
7551
7552 ;; These correspond to the switch cases in Parser.statementHelper
7553 (defconst js2-parsers
7554 (let ((parsers (make-vector js2-num-tokens
7555 #'js2-parse-expr-stmt)))
7556 (aset parsers js2-BREAK #'js2-parse-break)
7557 (aset parsers js2-CONST #'js2-parse-const-var)
7558 (aset parsers js2-CONTINUE #'js2-parse-continue)
7559 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7560 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7561 (aset parsers js2-DO #'js2-parse-do)
7562 (aset parsers js2-FOR #'js2-parse-for)
7563 (aset parsers js2-FUNCTION #'js2-function-parser)
7564 (aset parsers js2-IF #'js2-parse-if)
7565 (aset parsers js2-LC #'js2-parse-block)
7566 (aset parsers js2-LET #'js2-parse-let-stmt)
7567 (aset parsers js2-NAME #'js2-parse-name-or-label)
7568 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7569 (aset parsers js2-SEMI #'js2-parse-semi)
7570 (aset parsers js2-SWITCH #'js2-parse-switch)
7571 (aset parsers js2-THROW #'js2-parse-throw)
7572 (aset parsers js2-TRY #'js2-parse-try)
7573 (aset parsers js2-VAR #'js2-parse-const-var)
7574 (aset parsers js2-WHILE #'js2-parse-while)
7575 (aset parsers js2-WITH #'js2-parse-with)
7576 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7577 parsers)
7578 "A vector mapping token types to parser functions.")
7579
7580 (defsubst js2-parse-warn-missing-semi (beg end)
7581 (and js2-mode-show-strict-warnings
7582 js2-strict-missing-semi-warning
7583 (js2-add-strict-warning
7584 "msg.missing.semi" nil
7585 ;; back up to beginning of statement or line
7586 (max beg (save-excursion
7587 (goto-char end)
7588 (point-at-bol)))
7589 end)))
7590
7591 (defconst js2-no-semi-insertion
7592 (list js2-IF
7593 js2-SWITCH
7594 js2-WHILE
7595 js2-DO
7596 js2-FOR
7597 js2-TRY
7598 js2-WITH
7599 js2-LC
7600 js2-ERROR
7601 js2-SEMI
7602 js2-FUNCTION)
7603 "List of tokens that don't do automatic semicolon insertion.")
7604
7605 (defconst js2-autoinsert-semi-and-warn
7606 (list js2-ERROR js2-EOF js2-RC))
7607
7608 (defun js2-statement-helper ()
7609 (let* ((tt (js2-peek-token))
7610 (first-tt tt)
7611 (beg js2-token-beg)
7612 (parser (if (= tt js2-ERROR)
7613 #'js2-parse-semi
7614 (aref js2-parsers tt)))
7615 pn
7616 tt-flagged)
7617 ;; If the statement is set, then it's been told its label by now.
7618 (and js2-labeled-stmt
7619 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7620 (setq js2-labeled-stmt nil))
7621 (setq pn (funcall parser))
7622 ;; Don't do auto semi insertion for certain statement types.
7623 (unless (or (memq first-tt js2-no-semi-insertion)
7624 (js2-labeled-stmt-node-p pn))
7625 (js2-auto-insert-semicolon pn))
7626 pn))
7627
7628 (defun js2-auto-insert-semicolon (pn)
7629 (let* ((tt-flagged (js2-peek-flagged-token))
7630 (tt (logand tt-flagged js2-clear-ti-mask))
7631 (pos (js2-node-pos pn)))
7632 (cond
7633 ((= tt js2-SEMI)
7634 ;; Consume ';' as a part of expression
7635 (js2-consume-token)
7636 ;; extend the node bounds to include the semicolon.
7637 (setf (js2-node-len pn) (- js2-token-end pos)))
7638 ((memq tt js2-autoinsert-semi-and-warn)
7639 ;; Autoinsert ;
7640 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7641 (t
7642 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7643 ;; Report error if no EOL or autoinsert ';' otherwise
7644 (js2-report-error "msg.no.semi.stmt")
7645 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7646
7647 (defun js2-parse-condition ()
7648 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7649 The parens are discarded and the expression node is returned.
7650 The `pos' field of the return value is set to an absolute position
7651 that must be fixed up by the caller.
7652 Return value is a list (EXPR LP RP), with absolute paren positions."
7653 (let (pn lp rp)
7654 (if (js2-must-match js2-LP "msg.no.paren.cond")
7655 (setq lp js2-token-beg))
7656 (setq pn (js2-parse-expr))
7657 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7658 (setq rp js2-token-beg))
7659 ;; Report strict warning on code like "if (a = 7) ..."
7660 (if (and js2-strict-cond-assign-warning
7661 (js2-assign-node-p pn))
7662 (js2-add-strict-warning "msg.equal.as.assign" nil
7663 (js2-node-pos pn)
7664 (+ (js2-node-pos pn)
7665 (js2-node-len pn))))
7666 (list pn lp rp)))
7667
7668 (defun js2-parse-if ()
7669 "Parser for if-statement. Last matched token must be js2-IF."
7670 (let ((pos js2-token-beg)
7671 cond
7672 if-true
7673 if-false
7674 else-pos
7675 end
7676 pn)
7677 (js2-consume-token)
7678 (setq cond (js2-parse-condition)
7679 if-true (js2-parse-statement)
7680 if-false (if (js2-match-token js2-ELSE)
7681 (progn
7682 (setq else-pos (- js2-token-beg pos))
7683 (js2-parse-statement)))
7684 end (js2-node-end (or if-false if-true))
7685 pn (make-js2-if-node :pos pos
7686 :len (- end pos)
7687 :condition (car cond)
7688 :then-part if-true
7689 :else-part if-false
7690 :else-pos else-pos
7691 :lp (js2-relpos (second cond) pos)
7692 :rp (js2-relpos (third cond) pos)))
7693 (js2-node-add-children pn (car cond) if-true if-false)
7694 pn))
7695
7696 (defun js2-parse-switch ()
7697 "Parser for if-statement. Last matched token must be js2-SWITCH."
7698 (let ((pos js2-token-beg)
7699 tt
7700 pn
7701 discriminant
7702 has-default
7703 case-expr
7704 case-node
7705 case-pos
7706 cases
7707 stmt
7708 lp
7709 rp)
7710 (js2-consume-token)
7711 (if (js2-must-match js2-LP "msg.no.paren.switch")
7712 (setq lp js2-token-beg))
7713 (setq discriminant (js2-parse-expr)
7714 pn (make-js2-switch-node :discriminant discriminant
7715 :pos pos
7716 :lp (js2-relpos lp pos)))
7717 (js2-node-add-children pn discriminant)
7718 (js2-enter-switch pn)
7719 (unwind-protect
7720 (progn
7721 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7722 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7723 (js2-must-match js2-LC "msg.no.brace.switch")
7724 (catch 'break
7725 (while t
7726 (setq tt (js2-next-token)
7727 case-pos js2-token-beg)
7728 (cond
7729 ((= tt js2-RC)
7730 (setf (js2-node-len pn) (- js2-token-end pos))
7731 (throw 'break nil)) ; done
7732 ((= tt js2-CASE)
7733 (setq case-expr (js2-parse-expr))
7734 (js2-must-match js2-COLON "msg.no.colon.case"))
7735 ((= tt js2-DEFAULT)
7736 (if has-default
7737 (js2-report-error "msg.double.switch.default"))
7738 (setq has-default t
7739 case-expr nil)
7740 (js2-must-match js2-COLON "msg.no.colon.case"))
7741 (t
7742 (js2-report-error "msg.bad.switch")
7743 (throw 'break nil)))
7744 (setq case-node (make-js2-case-node :pos case-pos
7745 :len (- js2-token-end case-pos)
7746 :expr case-expr))
7747 (js2-node-add-children case-node case-expr)
7748 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7749 (/= tt js2-CASE)
7750 (/= tt js2-DEFAULT)
7751 (/= tt js2-EOF))
7752 (setf stmt (js2-parse-statement)
7753 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7754 (js2-block-node-push case-node stmt))
7755 (push case-node cases)))
7756 ;; add cases last, as pushing reverses the order to be correct
7757 (dolist (kid cases)
7758 (js2-node-add-children pn kid)
7759 (push kid (js2-switch-node-cases pn)))
7760 pn) ; return value
7761 (js2-exit-switch))))
7762
7763 (defun js2-parse-while ()
7764 "Parser for while-statement. Last matched token must be js2-WHILE."
7765 (let ((pos js2-token-beg)
7766 (pn (make-js2-while-node))
7767 cond
7768 body)
7769 (js2-consume-token)
7770 (js2-enter-loop pn)
7771 (unwind-protect
7772 (progn
7773 (setf cond (js2-parse-condition)
7774 (js2-while-node-condition pn) (car cond)
7775 body (js2-parse-statement)
7776 (js2-while-node-body pn) body
7777 (js2-node-len pn) (- (js2-node-end body) pos)
7778 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7779 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7780 (js2-node-add-children pn body (car cond)))
7781 (js2-exit-loop))
7782 pn))
7783
7784 (defun js2-parse-do ()
7785 "Parser for do-statement. Last matched token must be js2-DO."
7786 (let ((pos js2-token-beg)
7787 (pn (make-js2-do-node))
7788 cond
7789 body
7790 end)
7791 (js2-consume-token)
7792 (js2-enter-loop pn)
7793 (unwind-protect
7794 (progn
7795 (setq body (js2-parse-statement))
7796 (js2-must-match js2-WHILE "msg.no.while.do")
7797 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7798 cond (js2-parse-condition)
7799 (js2-do-node-condition pn) (car cond)
7800 (js2-do-node-body pn) body
7801 end js2-ts-cursor
7802 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7803 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7804 (js2-node-add-children pn (car cond) body))
7805 (js2-exit-loop))
7806 ;; Always auto-insert semicolon to follow SpiderMonkey:
7807 ;; It is required by ECMAScript but is ignored by the rest of
7808 ;; world; see bug 238945
7809 (if (js2-match-token js2-SEMI)
7810 (setq end js2-ts-cursor))
7811 (setf (js2-node-len pn) (- end pos))
7812 pn))
7813
7814 (defun js2-parse-for ()
7815 "Parser for for-statement. Last matched token must be js2-FOR.
7816 Parses for, for-in, and for each-in statements."
7817 (let ((for-pos js2-token-beg)
7818 pn
7819 is-for-each
7820 is-for-in
7821 in-pos
7822 each-pos
7823 tmp-pos
7824 init ; Node init is also foo in 'foo in object'
7825 cond ; Node cond is also object in 'foo in object'
7826 incr ; 3rd section of for-loop initializer
7827 body
7828 tt
7829 lp
7830 rp)
7831 (js2-consume-token)
7832 ;; See if this is a for each () instead of just a for ()
7833 (when (js2-match-token js2-NAME)
7834 (if (string= "each" js2-ts-string)
7835 (progn
7836 (setq is-for-each t
7837 each-pos (- js2-token-beg for-pos)) ; relative
7838 (js2-record-face 'font-lock-keyword-face))
7839 (js2-report-error "msg.no.paren.for")))
7840 (if (js2-must-match js2-LP "msg.no.paren.for")
7841 (setq lp (- js2-token-beg for-pos)))
7842 (setq tt (js2-peek-token))
7843 ;; parse init clause
7844 (let ((js2-in-for-init t)) ; set as dynamic variable
7845 (cond
7846 ((= tt js2-SEMI)
7847 (setq init (make-js2-empty-expr-node)))
7848 ((or (= tt js2-VAR) (= tt js2-LET))
7849 (js2-consume-token)
7850 (setq init (js2-parse-variables tt js2-token-beg)))
7851 (t
7852 (setq init (js2-parse-expr)))))
7853 (if (js2-match-token js2-IN)
7854 (setq is-for-in t
7855 in-pos (- js2-token-beg for-pos)
7856 cond (js2-parse-expr)) ; object over which we're iterating
7857 ;; else ordinary for loop - parse cond and incr
7858 (js2-must-match js2-SEMI "msg.no.semi.for")
7859 (setq cond (if (= (js2-peek-token) js2-SEMI)
7860 (make-js2-empty-expr-node) ; no loop condition
7861 (js2-parse-expr)))
7862 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7863 (setq tmp-pos js2-token-end
7864 incr (if (= (js2-peek-token) js2-RP)
7865 (make-js2-empty-expr-node :pos tmp-pos)
7866 (js2-parse-expr))))
7867 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7868 (setq rp (- js2-token-beg for-pos)))
7869 (if (not is-for-in)
7870 (setq pn (make-js2-for-node :init init
7871 :condition cond
7872 :update incr
7873 :lp lp
7874 :rp rp))
7875 ;; cond could be null if 'in obj' got eaten by the init node.
7876 (if (js2-infix-node-p init)
7877 ;; it was (foo in bar) instead of (var foo in bar)
7878 (setq cond (js2-infix-node-right init)
7879 init (js2-infix-node-left init))
7880 (if (and (js2-var-decl-node-p init)
7881 (> (length (js2-var-decl-node-kids init)) 1))
7882 (js2-report-error "msg.mult.index")))
7883 (setq pn (make-js2-for-in-node :iterator init
7884 :object cond
7885 :in-pos in-pos
7886 :foreach-p is-for-each
7887 :each-pos each-pos
7888 :lp lp
7889 :rp rp)))
7890 (unwind-protect
7891 (progn
7892 (js2-enter-loop pn)
7893 ;; We have to parse the body -after- creating the loop node,
7894 ;; so that the loop node appears in the js2-loop-set, allowing
7895 ;; break/continue statements to find the enclosing loop.
7896 (setf body (js2-parse-statement)
7897 (js2-loop-node-body pn) body
7898 (js2-node-pos pn) for-pos
7899 (js2-node-len pn) (- (js2-node-end body) for-pos))
7900 (js2-node-add-children pn init cond incr body))
7901 ;; finally
7902 (js2-exit-loop))
7903 pn))
7904
7905 (defun js2-parse-try ()
7906 "Parser for try-statement. Last matched token must be js2-TRY."
7907 (let ((try-pos js2-token-beg)
7908 try-end
7909 try-block
7910 catch-blocks
7911 finally-block
7912 saw-default-catch
7913 peek
7914 var-name
7915 catch-cond
7916 catch-node
7917 guard-kwd
7918 catch-pos
7919 finally-pos
7920 pn
7921 block
7922 lp
7923 rp)
7924 (js2-consume-token)
7925 (if (/= (js2-peek-token) js2-LC)
7926 (js2-report-error "msg.no.brace.try"))
7927 (setq try-block (js2-parse-statement)
7928 try-end (js2-node-end try-block)
7929 peek (js2-peek-token))
7930 (cond
7931 ((= peek js2-CATCH)
7932 (while (js2-match-token js2-CATCH)
7933 (setq catch-pos js2-token-beg
7934 guard-kwd nil
7935 catch-cond nil
7936 lp nil
7937 rp nil)
7938 (if saw-default-catch
7939 (js2-report-error "msg.catch.unreachable"))
7940 (if (js2-must-match js2-LP "msg.no.paren.catch")
7941 (setq lp (- js2-token-beg catch-pos)))
7942 (js2-must-match js2-NAME "msg.bad.catchcond")
7943 (setq var-name (js2-create-name-node))
7944 (if (js2-match-token js2-IF)
7945 (setq guard-kwd (- js2-token-beg catch-pos)
7946 catch-cond (js2-parse-expr))
7947 (setq saw-default-catch t))
7948 (if (js2-must-match js2-RP "msg.bad.catchcond")
7949 (setq rp (- js2-token-beg catch-pos)))
7950 (js2-must-match js2-LC "msg.no.brace.catchblock")
7951 (setq block (js2-parse-statements)
7952 try-end (js2-node-end block)
7953 catch-node (make-js2-catch-node :pos catch-pos
7954 :var-name var-name
7955 :guard-expr catch-cond
7956 :guard-kwd guard-kwd
7957 :block block
7958 :lp lp
7959 :rp rp))
7960 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7961 (setq try-end js2-token-beg))
7962 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7963 (js2-node-len catch-node) (- try-end catch-pos))
7964 (js2-node-add-children catch-node var-name catch-cond block)
7965 (push catch-node catch-blocks)))
7966 ((/= peek js2-FINALLY)
7967 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7968 (js2-node-pos try-block)
7969 (- (setq try-end (js2-node-end try-block))
7970 (js2-node-pos try-block)))))
7971 (when (js2-match-token js2-FINALLY)
7972 (setq finally-pos js2-token-beg
7973 block (js2-parse-statement)
7974 try-end (js2-node-end block)
7975 finally-block (make-js2-finally-node :pos finally-pos
7976 :len (- try-end finally-pos)
7977 :body block))
7978 (js2-node-add-children finally-block block))
7979 (setq pn (make-js2-try-node :pos try-pos
7980 :len (- try-end try-pos)
7981 :try-block try-block
7982 :finally-block finally-block))
7983 (js2-node-add-children pn try-block finally-block)
7984 ;; push them onto the try-node, which reverses and corrects their order
7985 (dolist (cb catch-blocks)
7986 (js2-node-add-children pn cb)
7987 (push cb (js2-try-node-catch-clauses pn)))
7988 pn))
7989
7990 (defun js2-parse-throw ()
7991 "Parser for throw-statement. Last matched token must be js2-THROW."
7992 (let ((pos js2-token-beg)
7993 expr
7994 pn)
7995 (js2-consume-token)
7996 (if (= (js2-peek-token-or-eol) js2-EOL)
7997 ;; ECMAScript does not allow new lines before throw expression,
7998 ;; see bug 256617
7999 (js2-report-error "msg.bad.throw.eol"))
8000 (setq expr (js2-parse-expr)
8001 pn (make-js2-throw-node :pos pos
8002 :len (- (js2-node-end expr) pos)
8003 :expr expr))
8004 (js2-node-add-children pn expr)
8005 pn))
8006
8007 (defsubst js2-match-jump-label-name (label-name)
8008 "If break/continue specified a label, return that label's labeled stmt.
8009 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8010 does not match an existing label, reports an error and returns nil."
8011 (let ((bundle (cdr (assoc label-name js2-label-set))))
8012 (if (null bundle)
8013 (js2-report-error "msg.undef.label"))
8014 bundle))
8015
8016 (defun js2-parse-break ()
8017 "Parser for break-statement. Last matched token must be js2-BREAK."
8018 (let ((pos js2-token-beg)
8019 (end js2-token-end)
8020 break-target ; statement to break from
8021 break-label ; in "break foo", name-node representing the foo
8022 labels ; matching labeled statement to break to
8023 pn)
8024 (js2-consume-token) ; `break'
8025 (when (eq (js2-peek-token-or-eol) js2-NAME)
8026 (js2-consume-token)
8027 (setq break-label (js2-create-name-node)
8028 end (js2-node-end break-label)
8029 ;; matchJumpLabelName only matches if there is one
8030 labels (js2-match-jump-label-name js2-ts-string)
8031 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8032 (unless (or break-target break-label)
8033 ;; no break target specified - try for innermost enclosing loop/switch
8034 (if (null js2-loop-and-switch-set)
8035 (unless break-label
8036 (js2-report-error "msg.bad.break" nil pos (length "break")))
8037 (setq break-target (car js2-loop-and-switch-set))))
8038 (setq pn (make-js2-break-node :pos pos
8039 :len (- end pos)
8040 :label break-label
8041 :target break-target))
8042 (js2-node-add-children pn break-label) ; but not break-target
8043 pn))
8044
8045 (defun js2-parse-continue ()
8046 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8047 (let ((pos js2-token-beg)
8048 (end js2-token-end)
8049 label ; optional user-specified label, a `js2-name-node'
8050 labels ; current matching labeled stmt, if any
8051 target ; the `js2-loop-node' target of this continue stmt
8052 pn)
8053 (js2-consume-token) ; `continue'
8054 (when (= (js2-peek-token-or-eol) js2-NAME)
8055 (js2-consume-token)
8056 (setq label (js2-create-name-node)
8057 end (js2-node-end label)
8058 ;; matchJumpLabelName only matches if there is one
8059 labels (js2-match-jump-label-name js2-ts-string)))
8060 (cond
8061 ((null labels) ; no current label to go to
8062 (if (null js2-loop-set) ; no loop to continue to
8063 (js2-report-error "msg.continue.outside" nil pos
8064 (length "continue"))
8065 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8066 (t
8067 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8068 (setq target (js2-labeled-stmt-node-stmt labels))
8069 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8070 (setq pn (make-js2-continue-node :pos pos
8071 :len (- end pos)
8072 :label label
8073 :target target))
8074 (js2-node-add-children pn label) ; but not target - it's not our child
8075 pn))
8076
8077 (defun js2-parse-with ()
8078 "Parser for with-statement. Last matched token must be js2-WITH."
8079 (js2-consume-token)
8080 (let ((pos js2-token-beg)
8081 obj body pn lp rp)
8082 (if (js2-must-match js2-LP "msg.no.paren.with")
8083 (setq lp js2-token-beg))
8084 (setq obj (js2-parse-expr))
8085 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8086 (setq rp js2-token-beg))
8087 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8088 (setq body (js2-parse-statement)))
8089 (setq pn (make-js2-with-node :pos pos
8090 :len (- (js2-node-end body) pos)
8091 :object obj
8092 :body body
8093 :lp (js2-relpos lp pos)
8094 :rp (js2-relpos rp pos)))
8095 (js2-node-add-children pn obj body)
8096 pn))
8097
8098 (defun js2-parse-const-var ()
8099 "Parser for var- or const-statement.
8100 Last matched token must be js2-CONST or js2-VAR."
8101 (let ((tt (js2-peek-token))
8102 (pos js2-token-beg)
8103 expr
8104 pn)
8105 (js2-consume-token)
8106 (setq expr (js2-parse-variables tt js2-token-beg)
8107 pn (make-js2-expr-stmt-node :pos pos
8108 :len (- (js2-node-end expr) pos)
8109 :expr expr))
8110 (js2-node-add-children pn expr)
8111 pn))
8112
8113 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8114 (let ((pn (make-js2-expr-stmt-node :pos pos
8115 :len (js2-node-len expr)
8116 :type (if (js2-inside-function)
8117 js2-EXPR_VOID
8118 js2-EXPR_RESULT)
8119 :expr expr)))
8120 (if add-child
8121 (js2-node-add-children pn expr))
8122 pn))
8123
8124 (defun js2-parse-let-stmt ()
8125 "Parser for let-statement. Last matched token must be js2-LET."
8126 (js2-consume-token)
8127 (let ((pos js2-token-beg)
8128 expr
8129 pn)
8130 (if (= (js2-peek-token) js2-LP)
8131 ;; let expression in statement context
8132 (setq expr (js2-parse-let pos 'statement)
8133 pn (js2-wrap-with-expr-stmt pos expr t))
8134 ;; else we're looking at a statement like let x=6, y=7;
8135 (setf expr (js2-parse-variables js2-LET pos)
8136 pn (js2-wrap-with-expr-stmt pos expr t)
8137 (js2-node-type pn) js2-EXPR_RESULT))
8138 pn))
8139
8140 (defun js2-parse-ret-yield ()
8141 (js2-parse-return-or-yield (js2-peek-token) nil))
8142
8143 (defconst js2-parse-return-stmt-enders
8144 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8145
8146 (defsubst js2-now-all-set (before after mask)
8147 "Return whether or not the bits in the mask have changed to all set.
8148 BEFORE is bits before change, AFTER is bits after change, and MASK is
8149 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8150 but not BEFORE."
8151 (and (/= (logand before mask) mask)
8152 (= (logand after mask) mask)))
8153
8154 (defun js2-parse-return-or-yield (tt expr-context)
8155 (let ((pos js2-token-beg)
8156 (end js2-token-end)
8157 (before js2-end-flags)
8158 (inside-function (js2-inside-function))
8159 e
8160 ret
8161 name)
8162 (unless inside-function
8163 (js2-report-error (if (eq tt js2-RETURN)
8164 "msg.bad.return"
8165 "msg.bad.yield")))
8166 (js2-consume-token)
8167 ;; This is ugly, but we don't want to require a semicolon.
8168 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8169 (setq e (js2-parse-expr)
8170 end (js2-node-end e)))
8171 (cond
8172 ((eq tt js2-RETURN)
8173 (js2-set-flag js2-end-flags (if (null e)
8174 js2-end-returns
8175 js2-end-returns-value))
8176 (setq ret (make-js2-return-node :pos pos
8177 :len (- end pos)
8178 :retval e))
8179 (js2-node-add-children ret e)
8180 ;; See if we need a strict mode warning.
8181 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8182 ;; more thorough and accurate than this before/after flag check.
8183 ;; E.g. if there's a finally-block that always returns, we shouldn't
8184 ;; show a warning generated by inconsistent returns in the catch blocks.
8185 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8186 ;; so we know which returns/yields to highlight, and we should get rid of
8187 ;; all the checking in `js2-parse-return-or-yield'.
8188 (if (and js2-strict-inconsistent-return-warning
8189 (js2-now-all-set before js2-end-flags
8190 (logior js2-end-returns js2-end-returns-value)))
8191 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8192 (t
8193 (unless (js2-inside-function)
8194 (js2-report-error "msg.bad.yield"))
8195 (js2-set-flag js2-end-flags js2-end-yields)
8196 (setq ret (make-js2-yield-node :pos pos
8197 :len (- end pos)
8198 :value e))
8199 (js2-node-add-children ret e)
8200 (unless expr-context
8201 (setq e ret
8202 ret (js2-wrap-with-expr-stmt pos e t))
8203 (js2-set-requires-activation)
8204 (js2-set-is-generator))))
8205 ;; see if we are mixing yields and value returns.
8206 (when (and inside-function
8207 (js2-now-all-set before js2-end-flags
8208 (logior js2-end-yields js2-end-returns-value)))
8209 (setq name (js2-function-name js2-current-script-or-fn))
8210 (if (zerop (length name))
8211 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8212 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8213 ret))
8214
8215 (defun js2-parse-debugger ()
8216 (js2-consume-token)
8217 (make-js2-keyword-node :type js2-DEBUGGER))
8218
8219 (defun js2-parse-block ()
8220 "Parser for a curly-delimited statement block.
8221 Last token matched must be js2-LC."
8222 (let ((pos js2-token-beg)
8223 (pn (make-js2-scope)))
8224 (js2-consume-token)
8225 (js2-push-scope pn)
8226 (unwind-protect
8227 (progn
8228 (js2-parse-statements pn)
8229 (js2-must-match js2-RC "msg.no.brace.block")
8230 (setf (js2-node-len pn) (- js2-token-end pos)))
8231 (js2-pop-scope))
8232 pn))
8233
8234 ;; for js2-ERROR too, to have a node for error recovery to work on
8235 (defun js2-parse-semi ()
8236 "Parse a statement or handle an error.
8237 Last matched token is js-SEMI or js-ERROR."
8238 (let ((tt (js2-peek-token)) pos len)
8239 (js2-consume-token)
8240 (if (eq tt js2-SEMI)
8241 (make-js2-empty-expr-node :len 1)
8242 (setq pos js2-token-beg
8243 len (- js2-token-beg pos))
8244 (js2-report-error "msg.syntax" nil pos len)
8245 (make-js2-error-node :pos pos :len len))))
8246
8247 (defun js2-parse-default-xml-namespace ()
8248 "Parse a `default xml namespace = <expr>' e4x statement."
8249 (let ((pos js2-token-beg)
8250 end len expr unary es)
8251 (js2-consume-token)
8252 (js2-must-have-xml)
8253 (js2-set-requires-activation)
8254 (setq len (- js2-ts-cursor pos))
8255 (unless (and (js2-match-token js2-NAME)
8256 (string= js2-ts-string "xml"))
8257 (js2-report-error "msg.bad.namespace" nil pos len))
8258 (unless (and (js2-match-token js2-NAME)
8259 (string= js2-ts-string "namespace"))
8260 (js2-report-error "msg.bad.namespace" nil pos len))
8261 (unless (js2-match-token js2-ASSIGN)
8262 (js2-report-error "msg.bad.namespace" nil pos len))
8263 (setq expr (js2-parse-expr)
8264 end (js2-node-end expr)
8265 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8266 :pos pos
8267 :len (- end pos)
8268 :operand expr))
8269 (js2-node-add-children unary expr)
8270 (make-js2-expr-stmt-node :pos pos
8271 :len (- end pos)
8272 :expr unary)))
8273
8274 (defun js2-record-label (label bundle)
8275 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8276 (js2-consume-token)
8277 (let ((name (js2-label-node-name label))
8278 labeled-stmt
8279 dup)
8280 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8281 ;; flag both labels if possible when used in editing mode
8282 (if (and js2-parse-ide-mode
8283 (setq dup (js2-get-label-by-name labeled-stmt name)))
8284 (js2-report-error "msg.dup.label" nil
8285 (js2-node-abs-pos dup) (js2-node-len dup)))
8286 (js2-report-error "msg.dup.label" nil
8287 (js2-node-pos label) (js2-node-len label)))
8288 (js2-labeled-stmt-node-add-label bundle label)
8289 (js2-node-add-children bundle label)
8290 ;; Add one reference to the bundle per label in `js2-label-set'
8291 (push (cons name bundle) js2-label-set)))
8292
8293 (defun js2-parse-name-or-label ()
8294 "Parser for identifier or label. Last token matched must be js2-NAME.
8295 Called when we found a name in a statement context. If it's a label, we gather
8296 up any following labels and the next non-label statement into a
8297 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8298 expression and return it wrapped in a `js2-expr-stmt-node'."
8299 (let ((pos js2-token-beg)
8300 (end js2-token-end)
8301 expr
8302 stmt
8303 pn
8304 bundle
8305 (continue t))
8306 ;; set check for label and call down to `js2-parse-primary-expr'
8307 (js2-set-check-for-label)
8308 (setq expr (js2-parse-expr))
8309 (if (/= (js2-node-type expr) js2-LABEL)
8310 ;; Parsed non-label expression - wrap with expression stmt.
8311 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8312 ;; else parsed a label
8313 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8314 (js2-record-label expr bundle)
8315 ;; look for more labels
8316 (while (and continue (= (js2-peek-token) js2-NAME))
8317 (js2-set-check-for-label)
8318 (setq expr (js2-parse-expr))
8319 (if (/= (js2-node-type expr) js2-LABEL)
8320 (progn
8321 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8322 continue nil)
8323 (js2-auto-insert-semicolon stmt))
8324 (js2-record-label expr bundle)))
8325 ;; no more labels; now parse the labeled statement
8326 (unwind-protect
8327 (unless stmt
8328 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8329 (setq stmt (js2-statement-helper))))
8330 ;; remove the labels for this statement from the global set
8331 (dolist (label (js2-labeled-stmt-node-labels bundle))
8332 (setq js2-label-set (remove label js2-label-set))))
8333 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8334 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8335 (js2-node-add-children bundle stmt)
8336 bundle)))
8337
8338 (defun js2-parse-expr-stmt ()
8339 "Default parser in statement context, if no recognized statement found."
8340 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8341
8342 (defun js2-parse-variables (decl-type pos)
8343 "Parse a comma-separated list of variable declarations.
8344 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8345
8346 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8347 For 'var' or 'const', the keyword should be the token last scanned.
8348
8349 POS is the position where the node should start. It's sometimes the
8350 var/const/let keyword, and other times the beginning of the first token
8351 in the first variable declaration.
8352
8353 Returns the parsed `js2-var-decl-node' expression node."
8354 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8355 :pos pos))
8356 destructuring
8357 kid-pos
8358 tt
8359 init
8360 name
8361 end
8362 nbeg nend
8363 vi
8364 (continue t))
8365 ;; Example:
8366 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8367 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8368 ;; var {a, b} = baz;
8369 (while continue
8370 (setq destructuring nil
8371 name nil
8372 tt (js2-peek-token)
8373 kid-pos js2-token-beg
8374 end js2-token-end
8375 init nil)
8376 (if (or (= tt js2-LB) (= tt js2-LC))
8377 ;; Destructuring assignment, e.g., var [a, b] = ...
8378 (setq destructuring (js2-parse-primary-expr t)
8379 end (js2-node-end destructuring))
8380 ;; Simple variable name
8381 (when (js2-must-match js2-NAME "msg.bad.var")
8382 (setq name (js2-create-name-node)
8383 nbeg js2-token-beg
8384 nend js2-token-end
8385 end nend)
8386 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8387 (when (js2-match-token js2-ASSIGN)
8388 (setq init (js2-parse-assign-expr)
8389 end (js2-node-end init))
8390 (if (and js2-parse-ide-mode
8391 (or (js2-object-node-p init)
8392 (js2-function-node-p init)))
8393 (js2-record-imenu-functions init name)))
8394 (when name
8395 (js2-set-face nbeg nend (if (js2-function-node-p init)
8396 'font-lock-function-name-face
8397 'font-lock-variable-name-face)
8398 'record))
8399 (setq vi (make-js2-var-init-node :pos kid-pos
8400 :len (- end kid-pos)
8401 :type decl-type))
8402 (if destructuring
8403 (progn
8404 (if (and (null init) (not js2-in-for-init))
8405 (js2-report-error "msg.destruct.assign.no.init"))
8406 (setf (js2-var-init-node-target vi) destructuring))
8407 (setf (js2-var-init-node-target vi) name))
8408 (setf (js2-var-init-node-initializer vi) init)
8409 (js2-node-add-children vi name destructuring init)
8410 (js2-block-node-push result vi)
8411 (unless (js2-match-token js2-COMMA)
8412 (setq continue nil)))
8413 (setf (js2-node-len result) (- end pos))
8414 result))
8415
8416 (defun js2-parse-let (pos &optional stmt-p)
8417 "Parse a let expression or statement.
8418 A let-expression is of the form `let (vars) expr'.
8419 A let-statment is of the form `let (vars) {statements}'.
8420 The third form of let is a variable declaration list, handled
8421 by `js2-parse-variables'."
8422 (let ((pn (make-js2-let-node :pos pos))
8423 beg vars body)
8424 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8425 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8426 (js2-push-scope pn)
8427 (unwind-protect
8428 (progn
8429 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8430 (if (js2-must-match js2-RP "msg.no.paren.let")
8431 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8432 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8433 ;; let statement
8434 (progn
8435 (js2-consume-token)
8436 (setf beg js2-token-beg ; position stmt at LC
8437 body (js2-parse-statements))
8438 (js2-must-match js2-RC "msg.no.curly.let")
8439 (setf (js2-node-len body) (- js2-token-end beg)
8440 (js2-node-len pn) (- js2-token-end pos)
8441 (js2-let-node-body pn) body
8442 (js2-node-type pn) js2-LET))
8443 ;; let expression
8444 (setf body (js2-parse-expr)
8445 (js2-node-len pn) (- (js2-node-end body) pos)
8446 (js2-let-node-body pn) body))
8447 (js2-node-add-children pn vars body))
8448 (js2-pop-scope))
8449 pn))
8450
8451 (defsubst js2-define-new-symbol (decl-type name node)
8452 (js2-scope-put-symbol js2-current-scope
8453 name
8454 (make-js2-symbol decl-type name node)))
8455
8456 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8457 "Define a symbol in the current scope.
8458 If NODE is non-nil, it is the AST node associated with the symbol."
8459 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8460 (symbol (if defining-scope
8461 (js2-scope-get-symbol defining-scope name)))
8462 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8463 (cond
8464 ((and symbol ; already defined
8465 (or (= sdt js2-CONST) ; old version is const
8466 (= decl-type js2-CONST) ; new version is const
8467 ;; two let-bound vars in this block have same name
8468 (and (= sdt js2-LET)
8469 (eq defining-scope js2-current-scope))))
8470 (js2-report-error
8471 (cond
8472 ((= sdt js2-CONST) "msg.const.redecl")
8473 ((= sdt js2-LET) "msg.let.redecl")
8474 ((= sdt js2-VAR) "msg.var.redecl")
8475 ((= sdt js2-FUNCTION) "msg.function.redecl")
8476 (t "msg.parm.redecl"))
8477 name))
8478 ((= decl-type js2-LET)
8479 (if (and (not ignore-not-in-block)
8480 (or (= (js2-node-type js2-current-scope) js2-IF)
8481 (js2-loop-node-p js2-current-scope)))
8482 (js2-report-error "msg.let.decl.not.in.block")
8483 (js2-define-new-symbol decl-type name node)))
8484 ((or (= decl-type js2-VAR)
8485 (= decl-type js2-CONST)
8486 (= decl-type js2-FUNCTION))
8487 (if symbol
8488 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8489 (js2-add-strict-warning "msg.var.redecl" name)
8490 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8491 (js2-add-strict-warning "msg.var.hides.arg" name)))
8492 (js2-define-new-symbol decl-type name node)))
8493 ((= decl-type js2-LP)
8494 (if symbol
8495 ;; must be duplicate parameter. Second parameter hides the
8496 ;; first, so go ahead and add the second pararameter
8497 (js2-report-warning "msg.dup.parms" name))
8498 (js2-define-new-symbol decl-type name node))
8499 (t (js2-code-bug)))))
8500
8501 (defun js2-parse-expr (&optional oneshot)
8502 (let* ((pn (js2-parse-assign-expr))
8503 (pos (js2-node-pos pn))
8504 left
8505 right
8506 op-pos)
8507 (while (and (not oneshot)
8508 (js2-match-token js2-COMMA))
8509 (setq op-pos (- js2-token-beg pos)) ; relative
8510 (if (= (js2-peek-token) js2-YIELD)
8511 (js2-report-error "msg.yield.parenthesized"))
8512 (setq right (js2-parse-assign-expr)
8513 left pn
8514 pn (make-js2-infix-node :type js2-COMMA
8515 :pos pos
8516 :len (- js2-ts-cursor pos)
8517 :op-pos op-pos
8518 :left left
8519 :right right))
8520 (js2-node-add-children pn left right))
8521 pn))
8522
8523 (defun js2-parse-assign-expr ()
8524 (let ((tt (js2-peek-token))
8525 (pos js2-token-beg)
8526 pn
8527 left
8528 right
8529 op-pos)
8530 (if (= tt js2-YIELD)
8531 (js2-parse-return-or-yield tt t)
8532 ;; not yield - parse assignment expression
8533 (setq pn (js2-parse-cond-expr)
8534 tt (js2-peek-token))
8535 (when (and (<= js2-first-assign tt)
8536 (<= tt js2-last-assign))
8537 (js2-consume-token)
8538 (setq op-pos (- js2-token-beg pos) ; relative
8539 left pn
8540 right (js2-parse-assign-expr)
8541 pn (make-js2-assign-node :type tt
8542 :pos pos
8543 :len (- (js2-node-end right) pos)
8544 :op-pos op-pos
8545 :left left
8546 :right right))
8547 (when js2-parse-ide-mode
8548 (js2-highlight-assign-targets pn left right)
8549 (if (or (js2-function-node-p right)
8550 (js2-object-node-p right))
8551 (js2-record-imenu-functions right left)))
8552 ;; do this last so ide checks above can use absolute positions
8553 (js2-node-add-children pn left right))
8554 pn)))
8555
8556 (defun js2-parse-cond-expr ()
8557 (let ((pos js2-token-beg)
8558 (pn (js2-parse-or-expr))
8559 test-expr
8560 if-true
8561 if-false
8562 q-pos
8563 c-pos)
8564 (when (js2-match-token js2-HOOK)
8565 (setq q-pos (- js2-token-beg pos)
8566 if-true (js2-parse-assign-expr))
8567 (js2-must-match js2-COLON "msg.no.colon.cond")
8568 (setq c-pos (- js2-token-beg pos)
8569 if-false (js2-parse-assign-expr)
8570 test-expr pn
8571 pn (make-js2-cond-node :pos pos
8572 :len (- (js2-node-end if-false) pos)
8573 :test-expr test-expr
8574 :true-expr if-true
8575 :false-expr if-false
8576 :q-pos q-pos
8577 :c-pos c-pos))
8578 (js2-node-add-children pn test-expr if-true if-false))
8579 pn))
8580
8581 (defun js2-make-binary (type left parser)
8582 "Helper for constructing a binary-operator AST node.
8583 LEFT is the left-side-expression, already parsed, and the
8584 binary operator should have just been matched.
8585 PARSER is a function to call to parse the right operand,
8586 or a `js2-node' struct if it has already been parsed."
8587 (let* ((pos (js2-node-pos left))
8588 (op-pos (- js2-token-beg pos))
8589 (right (if (js2-node-p parser)
8590 parser
8591 (funcall parser)))
8592 (pn (make-js2-infix-node :type type
8593 :pos pos
8594 :len (- (js2-node-end right) pos)
8595 :op-pos op-pos
8596 :left left
8597 :right right)))
8598 (js2-node-add-children pn left right)
8599 pn))
8600
8601 (defun js2-parse-or-expr ()
8602 (let ((pn (js2-parse-and-expr)))
8603 (when (js2-match-token js2-OR)
8604 (setq pn (js2-make-binary js2-OR
8605 pn
8606 'js2-parse-or-expr)))
8607 pn))
8608
8609 (defun js2-parse-and-expr ()
8610 (let ((pn (js2-parse-bit-or-expr)))
8611 (when (js2-match-token js2-AND)
8612 (setq pn (js2-make-binary js2-AND
8613 pn
8614 'js2-parse-and-expr)))
8615 pn))
8616
8617 (defun js2-parse-bit-or-expr ()
8618 (let ((pn (js2-parse-bit-xor-expr)))
8619 (while (js2-match-token js2-BITOR)
8620 (setq pn (js2-make-binary js2-BITOR
8621 pn
8622 'js2-parse-bit-xor-expr)))
8623 pn))
8624
8625 (defun js2-parse-bit-xor-expr ()
8626 (let ((pn (js2-parse-bit-and-expr)))
8627 (while (js2-match-token js2-BITXOR)
8628 (setq pn (js2-make-binary js2-BITXOR
8629 pn
8630 'js2-parse-bit-and-expr)))
8631 pn))
8632
8633 (defun js2-parse-bit-and-expr ()
8634 (let ((pn (js2-parse-eq-expr)))
8635 (while (js2-match-token js2-BITAND)
8636 (setq pn (js2-make-binary js2-BITAND
8637 pn
8638 'js2-parse-eq-expr)))
8639 pn))
8640
8641 (defconst js2-parse-eq-ops
8642 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8643
8644 (defun js2-parse-eq-expr ()
8645 (let ((pn (js2-parse-rel-expr))
8646 tt)
8647 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8648 (js2-consume-token)
8649 (setq pn (js2-make-binary tt
8650 pn
8651 'js2-parse-rel-expr)))
8652 pn))
8653
8654 (defconst js2-parse-rel-ops
8655 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8656
8657 (defun js2-parse-rel-expr ()
8658 (let ((pn (js2-parse-shift-expr))
8659 (continue t)
8660 tt)
8661 (while continue
8662 (setq tt (js2-peek-token))
8663 (cond
8664 ((and js2-in-for-init (= tt js2-IN))
8665 (setq continue nil))
8666 ((memq tt js2-parse-rel-ops)
8667 (js2-consume-token)
8668 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8669 (t
8670 (setq continue nil))))
8671 pn))
8672
8673 (defconst js2-parse-shift-ops
8674 (list js2-LSH js2-URSH js2-RSH))
8675
8676 (defun js2-parse-shift-expr ()
8677 (let ((pn (js2-parse-add-expr))
8678 tt
8679 (continue t))
8680 (while continue
8681 (setq tt (js2-peek-token))
8682 (if (memq tt js2-parse-shift-ops)
8683 (progn
8684 (js2-consume-token)
8685 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8686 (setq continue nil)))
8687 pn))
8688
8689 (defun js2-parse-add-expr ()
8690 (let ((pn (js2-parse-mul-expr))
8691 tt
8692 (continue t))
8693 (while continue
8694 (setq tt (js2-peek-token))
8695 (if (or (= tt js2-ADD) (= tt js2-SUB))
8696 (progn
8697 (js2-consume-token)
8698 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8699 (setq continue nil)))
8700 pn))
8701
8702 (defconst js2-parse-mul-ops
8703 (list js2-MUL js2-DIV js2-MOD))
8704
8705 (defun js2-parse-mul-expr ()
8706 (let ((pn (js2-parse-unary-expr))
8707 tt
8708 (continue t))
8709 (while continue
8710 (setq tt (js2-peek-token))
8711 (if (memq tt js2-parse-mul-ops)
8712 (progn
8713 (js2-consume-token)
8714 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8715 (setq continue nil)))
8716 pn))
8717
8718 (defsubst js2-make-unary (type parser &rest args)
8719 "Make a unary node of type TYPE.
8720 PARSER is either a node (for postfix operators) or a function to call
8721 to parse the operand (for prefix operators)."
8722 (let* ((pos js2-token-beg)
8723 (postfix (js2-node-p parser))
8724 (expr (if postfix
8725 parser
8726 (apply parser args)))
8727 end
8728 pn)
8729 (if postfix ; e.g. i++
8730 (setq pos (js2-node-pos expr)
8731 end js2-token-end)
8732 (setq end (js2-node-end expr)))
8733 (setq pn (make-js2-unary-node :type type
8734 :pos pos
8735 :len (- end pos)
8736 :operand expr))
8737 (js2-node-add-children pn expr)
8738 pn))
8739
8740 (defconst js2-incrementable-node-types
8741 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8742 "Node types that can be the operand of a ++ or -- operator.")
8743
8744 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8745 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8746 js2-incrementable-node-types)
8747 (js2-report-error (if (= tt js2-INC)
8748 "msg.bad.incr"
8749 "msg.bad.decr")
8750 nil beg (- end beg))))
8751
8752 (defun js2-parse-unary-expr ()
8753 (let ((tt (js2-peek-token))
8754 pn expr beg end)
8755 (cond
8756 ((or (= tt js2-VOID)
8757 (= tt js2-NOT)
8758 (= tt js2-BITNOT)
8759 (= tt js2-TYPEOF))
8760 (js2-consume-token)
8761 (js2-make-unary tt 'js2-parse-unary-expr))
8762 ((= tt js2-ADD)
8763 (js2-consume-token)
8764 ;; Convert to special POS token in decompiler and parse tree
8765 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8766 ((= tt js2-SUB)
8767 (js2-consume-token)
8768 ;; Convert to special NEG token in decompiler and parse tree
8769 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8770 ((or (= tt js2-INC)
8771 (= tt js2-DEC))
8772 (js2-consume-token)
8773 (prog1
8774 (setq beg js2-token-beg
8775 end js2-token-end
8776 expr (js2-make-unary tt 'js2-parse-member-expr t))
8777 (js2-check-bad-inc-dec tt beg end expr)))
8778 ((= tt js2-DELPROP)
8779 (js2-consume-token)
8780 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8781 ((= tt js2-ERROR)
8782 (js2-consume-token)
8783 (make-js2-error-node)) ; try to continue
8784 ((and (= tt js2-LT)
8785 js2-compiler-xml-available)
8786 ;; XML stream encountered in expression.
8787 (js2-consume-token)
8788 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8789 (t
8790 (setq pn (js2-parse-member-expr t)
8791 ;; Don't look across a newline boundary for a postfix incop.
8792 tt (js2-peek-token-or-eol))
8793 (when (or (= tt js2-INC) (= tt js2-DEC))
8794 (js2-consume-token)
8795 (setf expr pn
8796 pn (js2-make-unary tt expr))
8797 (js2-node-set-prop pn 'postfix t)
8798 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8799 pn))))
8800
8801 (defun js2-parse-xml-initializer ()
8802 "Parse an E4X XML initializer.
8803 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8804 Then I'll postprocess the result, depending on whether we're in IDE
8805 mode or codegen mode, and generate the appropriate rewritten AST.
8806 IDE mode uses a rich AST that models the XML structure. Codegen mode
8807 just concatenates everything and makes a new XML or XMLList out of it."
8808 (let ((tt (js2-get-first-xml-token))
8809 pn-xml
8810 pn
8811 expr
8812 kids
8813 expr-pos
8814 (continue t)
8815 (first-token t))
8816 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8817 (js2-report-error "msg.syntax"))
8818 (setq pn-xml (make-js2-xml-node))
8819 (while continue
8820 (if first-token
8821 (setq first-token nil)
8822 (setq tt (js2-get-next-xml-token)))
8823 (cond
8824 ;; js2-XML means we found a {expr} in the XML stream.
8825 ;; The js2-ts-string is the XML up to the left-curly.
8826 ((= tt js2-XML)
8827 (push (make-js2-string-node :pos js2-token-beg
8828 :len (- js2-ts-cursor js2-token-beg))
8829 kids)
8830 (js2-must-match js2-LC "msg.syntax")
8831 (setq expr-pos js2-ts-cursor
8832 expr (if (eq (js2-peek-token) js2-RC)
8833 (make-js2-empty-expr-node :pos expr-pos)
8834 (js2-parse-expr)))
8835 (js2-must-match js2-RC "msg.syntax")
8836 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8837 :len (js2-node-len expr)
8838 :expr expr))
8839 (js2-node-add-children pn expr)
8840 (push pn kids))
8841 ;; a js2-XMLEND token means we hit the final close-tag.
8842 ((= tt js2-XMLEND)
8843 (push (make-js2-string-node :pos js2-token-beg
8844 :len (- js2-ts-cursor js2-token-beg))
8845 kids)
8846 (dolist (kid (nreverse kids))
8847 (js2-block-node-push pn-xml kid))
8848 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8849 (js2-node-pos pn-xml))
8850 continue nil))
8851 (t
8852 (js2-report-error "msg.syntax")
8853 (setq continue nil))))
8854 pn-xml))
8855
8856
8857 (defun js2-parse-argument-list ()
8858 "Parse an argument list and return it as a lisp list of nodes.
8859 Returns the list in reverse order. Consumes the right-paren token."
8860 (let (result)
8861 (unless (js2-match-token js2-RP)
8862 (loop do
8863 (if (= (js2-peek-token) js2-YIELD)
8864 (js2-report-error "msg.yield.parenthesized"))
8865 (push (js2-parse-assign-expr) result)
8866 while
8867 (js2-match-token js2-COMMA))
8868 (js2-must-match js2-RP "msg.no.paren.arg")
8869 result)))
8870
8871 (defun js2-parse-member-expr (&optional allow-call-syntax)
8872 (let ((tt (js2-peek-token))
8873 pn
8874 pos
8875 target
8876 args
8877 beg
8878 end
8879 init
8880 tail)
8881 (if (/= tt js2-NEW)
8882 (setq pn (js2-parse-primary-expr))
8883 ;; parse a 'new' expression
8884 (js2-consume-token)
8885 (setq pos js2-token-beg
8886 beg pos
8887 target (js2-parse-member-expr)
8888 end (js2-node-end target)
8889 pn (make-js2-new-node :pos pos
8890 :target target
8891 :len (- end pos)))
8892 (js2-node-add-children pn target)
8893 (when (js2-match-token js2-LP)
8894 ;; Add the arguments to pn, if any are supplied.
8895 (setf beg pos ; start of "new" keyword
8896 pos js2-token-beg
8897 args (nreverse (js2-parse-argument-list))
8898 (js2-new-node-args pn) args
8899 end js2-token-end
8900 (js2-new-node-lp pn) (- pos beg)
8901 (js2-new-node-rp pn) (- end 1 beg))
8902 (apply #'js2-node-add-children pn args))
8903 (when (and js2-allow-rhino-new-expr-initializer
8904 (js2-match-token js2-LC))
8905 (setf init (js2-parse-object-literal)
8906 end (js2-node-end init)
8907 (js2-new-node-initializer pn) init)
8908 (js2-node-add-children pn init))
8909 (setf (js2-node-len pn) (- end beg))) ; end outer if
8910 (js2-parse-member-expr-tail allow-call-syntax pn)))
8911
8912 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8913 "Parse a chain of property/array accesses or function calls.
8914 Includes parsing for E4X operators like `..' and `.@'.
8915 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8916 Returns an expression tree that includes PN, the parent node."
8917 (let ((beg (js2-node-pos pn))
8918 tt
8919 (continue t))
8920 (while continue
8921 (setq tt (js2-peek-token))
8922 (cond
8923 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8924 (setq pn (js2-parse-property-access tt pn)))
8925 ((= tt js2-DOTQUERY)
8926 (setq pn (js2-parse-dot-query pn)))
8927 ((= tt js2-LB)
8928 (setq pn (js2-parse-element-get pn)))
8929 ((= tt js2-LP)
8930 (if allow-call-syntax
8931 (setq pn (js2-parse-function-call pn))
8932 (setq continue nil)))
8933 (t
8934 (setq continue nil))))
8935 (if (>= js2-highlight-level 2)
8936 (js2-parse-highlight-member-expr-node pn))
8937 pn))
8938
8939 (defun js2-parse-dot-query (pn)
8940 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8941 Last token parsed must be `js2-DOTQUERY'."
8942 (let ((pos (js2-node-pos pn))
8943 op-pos
8944 expr
8945 end)
8946 (js2-consume-token)
8947 (js2-must-have-xml)
8948 (js2-set-requires-activation)
8949 (setq op-pos js2-token-beg
8950 expr (js2-parse-expr)
8951 end (js2-node-end expr)
8952 pn (make-js2-xml-dot-query-node :left pn
8953 :pos pos
8954 :op-pos op-pos
8955 :right expr))
8956 (js2-node-add-children pn
8957 (js2-xml-dot-query-node-left pn)
8958 (js2-xml-dot-query-node-right pn))
8959 (if (js2-must-match js2-RP "msg.no.paren")
8960 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8961 end js2-token-end))
8962 (setf (js2-node-len pn) (- end pos))
8963 pn))
8964
8965 (defun js2-parse-element-get (pn)
8966 "Parse an element-get expression, e.g. foo[bar].
8967 Last token parsed must be `js2-RB'."
8968 (let ((lb js2-token-beg)
8969 (pos (js2-node-pos pn))
8970 rb
8971 expr)
8972 (js2-consume-token)
8973 (setq expr (js2-parse-expr))
8974 (if (js2-must-match js2-RB "msg.no.bracket.index")
8975 (setq rb js2-token-beg))
8976 (setq pn (make-js2-elem-get-node :target pn
8977 :pos pos
8978 :element expr
8979 :lb (js2-relpos lb pos)
8980 :rb (js2-relpos rb pos)
8981 :len (- js2-token-end pos)))
8982 (js2-node-add-children pn
8983 (js2-elem-get-node-target pn)
8984 (js2-elem-get-node-element pn))
8985 pn))
8986
8987 (defun js2-parse-function-call (pn)
8988 (let (args
8989 (pos (js2-node-pos pn)))
8990 (js2-consume-token)
8991 (setq pn (make-js2-call-node :pos pos
8992 :target pn
8993 :lp (- js2-token-beg pos)))
8994 (js2-node-add-children pn (js2-call-node-target pn))
8995 ;; Add the arguments to pn, if any are supplied.
8996 (setf args (nreverse (js2-parse-argument-list))
8997 (js2-call-node-rp pn) (- js2-token-beg pos)
8998 (js2-call-node-args pn) args)
8999 (apply #'js2-node-add-children pn args)
9000 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9001 pn))
9002
9003 (defun js2-parse-property-access (tt pn)
9004 "Parse a property access, XML descendants access, or XML attr access."
9005 (let ((member-type-flags 0)
9006 (dot-pos js2-token-beg)
9007 (dot-len (if (= tt js2-DOTDOT) 2 1))
9008 name
9009 ref ; right side of . or .. operator
9010 result)
9011 (js2-consume-token)
9012 (when (= tt js2-DOTDOT)
9013 (js2-must-have-xml)
9014 (setq member-type-flags js2-descendants-flag))
9015 (if (not js2-compiler-xml-available)
9016 (progn
9017 (js2-must-match-prop-name "msg.no.name.after.dot")
9018 (setq name (js2-create-name-node t js2-GETPROP)
9019 result (make-js2-prop-get-node :left pn
9020 :pos js2-token-beg
9021 :right name
9022 :len (- js2-token-end
9023 js2-token-beg)))
9024 (js2-node-add-children result pn name)
9025 result)
9026 ;; otherwise look for XML operators
9027 (setf result (if (= tt js2-DOT)
9028 (make-js2-prop-get-node)
9029 (make-js2-infix-node :type js2-DOTDOT))
9030 (js2-node-pos result) (js2-node-pos pn)
9031 (js2-infix-node-op-pos result) dot-pos
9032 (js2-infix-node-left result) pn ; do this after setting position
9033 tt (js2-next-token))
9034 (cond
9035 ;; needed for generator.throw()
9036 ((= tt js2-THROW)
9037 (js2-save-name-token-data js2-token-beg "throw")
9038 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9039 ;; handles: name, ns::name, ns::*, ns::[expr]
9040 ((js2-valid-prop-name-token tt)
9041 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9042 ;; handles: *, *::name, *::*, *::[expr]
9043 ((= tt js2-MUL)
9044 (js2-save-name-token-data js2-token-beg "*")
9045 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9046 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9047 ((= tt js2-XMLATTR)
9048 (setq result (js2-parse-attribute-access)))
9049 (t
9050 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9051 (if ref
9052 (setf (js2-node-len result) (- (js2-node-end ref)
9053 (js2-node-pos result))
9054 (js2-infix-node-right result) ref))
9055 (if (js2-infix-node-p result)
9056 (js2-node-add-children result
9057 (js2-infix-node-left result)
9058 (js2-infix-node-right result)))
9059 result)))
9060
9061 (defun js2-parse-attribute-access ()
9062 "Parse an E4X XML attribute expression.
9063 This includes expressions of the forms:
9064
9065 @attr @ns::attr @ns::*
9066 @* @*::attr @*::*
9067 @[expr] @*::[expr] @ns::[expr]
9068
9069 Called if we peeked an '@' token."
9070 (let ((tt (js2-next-token))
9071 (at-pos js2-token-beg))
9072 (cond
9073 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9074 ((js2-valid-prop-name-token tt)
9075 (js2-parse-property-name at-pos js2-ts-string 0))
9076 ;; handles: @*, @*::name, @*::*, @*::[expr]
9077 ((= tt js2-MUL)
9078 (js2-save-name-token-data js2-token-beg "*")
9079 (js2-parse-property-name js2-token-beg "*" 0))
9080 ;; handles @[expr]
9081 ((= tt js2-LB)
9082 (js2-parse-xml-elem-ref at-pos))
9083 (t
9084 (js2-report-error "msg.no.name.after.xmlAttr")
9085 ;; Avoid cascaded errors that happen if we make an error node here.
9086 (js2-save-name-token-data js2-token-beg "")
9087 (js2-parse-property-name js2-token-beg "" 0)))))
9088
9089 (defun js2-parse-property-name (at-pos s member-type-flags)
9090 "Check if :: follows name in which case it becomes qualified name.
9091
9092 AT-POS is a natural number if we just read an '@' token, else nil.
9093 S is the name or string that was matched: an identifier, 'throw' or '*'.
9094 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9095
9096 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9097 operator, or the name is followed by ::. For a plain name, returns a
9098 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9099 (let ((pos (or at-pos js2-token-beg))
9100 colon-pos
9101 (name (js2-create-name-node t js2-current-token))
9102 ns
9103 tt
9104 ref
9105 pn)
9106 (catch 'return
9107 (when (js2-match-token js2-COLONCOLON)
9108 (setq ns name
9109 colon-pos js2-token-beg
9110 tt (js2-next-token))
9111 (cond
9112 ;; handles name::name
9113 ((js2-valid-prop-name-token tt)
9114 (setq name (js2-create-name-node)))
9115 ;; handles name::*
9116 ((= tt js2-MUL)
9117 (js2-save-name-token-data js2-token-beg "*")
9118 (setq name (js2-create-name-node)))
9119 ;; handles name::[expr]
9120 ((= tt js2-LB)
9121 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9122 (t
9123 (js2-report-error "msg.no.name.after.coloncolon"))))
9124 (if (and (null ns) (zerop member-type-flags))
9125 name
9126 (prog1
9127 (setq pn
9128 (make-js2-xml-prop-ref-node :pos pos
9129 :len (- (js2-node-end name) pos)
9130 :at-pos at-pos
9131 :colon-pos colon-pos
9132 :propname name))
9133 (js2-node-add-children pn name))))))
9134
9135 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9136 "Parse the [expr] portion of an xml element reference.
9137 For instance, @[expr], @*::[expr], or ns::[expr]."
9138 (let* ((lb js2-token-beg)
9139 (pos (or at-pos lb))
9140 rb
9141 (expr (js2-parse-expr))
9142 (end (js2-node-end expr))
9143 pn)
9144 (if (js2-must-match js2-RB "msg.no.bracket.index")
9145 (setq rb js2-token-beg
9146 end js2-token-end))
9147 (prog1
9148 (setq pn
9149 (make-js2-xml-elem-ref-node :pos pos
9150 :len (- end pos)
9151 :namespace namespace
9152 :colon-pos colon-pos
9153 :at-pos at-pos
9154 :expr expr
9155 :lb (js2-relpos lb pos)
9156 :rb (js2-relpos rb pos)))
9157 (js2-node-add-children pn namespace expr))))
9158
9159 (defun js2-parse-primary-expr (&optional lhs)
9160 "Parses a literal (leaf) expression of some sort.
9161 Includes complex literals such as functions, object-literals,
9162 array-literals, array comprehensions and regular expressions.
9163 When `lhs' is t, we assume the given primary expression appeared in the left hand side
9164 and treat it in the somewhat special way.
9165 ex) {a, b} is permitted only when the `lhs' is t."
9166 (let ((tt-flagged (js2-next-flagged-token))
9167 pn ; parent node (usually return value)
9168 tt
9169 px-pos ; paren-expr pos
9170 len
9171 flags ; regexp flags
9172 expr)
9173 (setq tt js2-current-token)
9174 (cond
9175 ((= tt js2-FUNCTION)
9176 (js2-parse-function 'FUNCTION_EXPRESSION))
9177 ((= tt js2-LB)
9178 (js2-parse-array-literal))
9179 ((= tt js2-LC)
9180 (js2-parse-object-literal lhs))
9181 ((= tt js2-LET)
9182 (js2-parse-let js2-token-beg))
9183 ((= tt js2-LP)
9184 (setq px-pos js2-token-beg
9185 expr (js2-parse-expr))
9186 (js2-must-match js2-RP "msg.no.paren")
9187 (setq pn (make-js2-paren-node :pos px-pos
9188 :expr expr
9189 :len (- js2-token-end px-pos)))
9190 (js2-node-add-children pn (js2-paren-node-expr pn))
9191 pn)
9192 ((= tt js2-XMLATTR)
9193 (js2-must-have-xml)
9194 (js2-parse-attribute-access))
9195 ((= tt js2-NAME)
9196 (js2-parse-name tt-flagged tt))
9197 ((= tt js2-NUMBER)
9198 (make-js2-number-node))
9199 ((= tt js2-STRING)
9200 (prog1
9201 (make-js2-string-node)
9202 (js2-record-face 'font-lock-string-face)))
9203 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9204 ;; Got / or /= which in this context means a regexp literal
9205 (setq px-pos js2-token-beg)
9206 (js2-read-regexp tt)
9207 (setq flags js2-ts-regexp-flags
9208 js2-ts-regexp-flags nil)
9209 (prog1
9210 (make-js2-regexp-node :pos px-pos
9211 :len (- js2-ts-cursor px-pos)
9212 :value js2-ts-string
9213 :flags flags)
9214 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9215 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9216 ((or (= tt js2-NULL)
9217 (= tt js2-THIS)
9218 (= tt js2-FALSE)
9219 (= tt js2-TRUE))
9220 (make-js2-keyword-node :type tt))
9221 ((= tt js2-RESERVED)
9222 (js2-report-error "msg.reserved.id")
9223 (make-js2-name-node))
9224 ((= tt js2-ERROR)
9225 ;; the scanner or one of its subroutines reported the error.
9226 (make-js2-error-node))
9227 ((= tt js2-EOF)
9228 (setq px-pos (point-at-bol)
9229 len (- js2-ts-cursor px-pos))
9230 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9231 (make-js2-error-node :pos px-pos :len len))
9232 (t
9233 (js2-report-error "msg.syntax")
9234 (make-js2-error-node)))))
9235
9236 (defun js2-parse-name (tt-flagged tt)
9237 (let ((name js2-ts-string)
9238 (name-pos js2-token-beg))
9239 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9240 (= (js2-peek-token) js2-COLON))
9241 (prog1
9242 ;; Do not consume colon, it is used as unwind indicator
9243 ;; to return to statementHelper.
9244 (make-js2-label-node :pos name-pos
9245 :len (- js2-token-end name-pos)
9246 :name name)
9247 (js2-set-face name-pos
9248 js2-token-end
9249 'font-lock-variable-name-face 'record))
9250 ;; Otherwise not a label, just a name. Unfortunately peeking
9251 ;; the next token to check for a colon has biffed js2-token-beg
9252 ;; and js2-token-end. We store the name's bounds in buffer vars
9253 ;; and `js2-create-name-node' uses them.
9254 (js2-save-name-token-data name-pos name)
9255 (if js2-compiler-xml-available
9256 (js2-parse-property-name nil name 0)
9257 (js2-create-name-node 'check-activation)))))
9258
9259 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9260 (js2-add-strict-warning
9261 msg nil
9262 ;; back up from comma to beginning of line or array/objlit
9263 (max (if elems
9264 (js2-node-pos (car elems))
9265 pos)
9266 (save-excursion
9267 (goto-char comma-pos)
9268 (back-to-indentation)
9269 (point)))
9270 comma-pos))
9271
9272 (defun js2-parse-array-literal ()
9273 (let ((pos js2-token-beg)
9274 (end js2-token-end)
9275 (after-lb-or-comma t)
9276 after-comma
9277 tt
9278 elems
9279 pn
9280 (continue t))
9281 (while continue
9282 (setq tt (js2-peek-token))
9283 (cond
9284 ;; comma
9285 ((= tt js2-COMMA)
9286 (js2-consume-token)
9287 (setq after-comma js2-token-end)
9288 (if (not after-lb-or-comma)
9289 (setq after-lb-or-comma t)
9290 (push nil elems)))
9291 ;; end of array
9292 ((or (= tt js2-RB)
9293 (= tt js2-EOF)) ; prevent infinite loop
9294 (if (= tt js2-EOF)
9295 (js2-report-error "msg.no.bracket.arg" nil pos)
9296 (js2-consume-token))
9297 (setq continue nil
9298 end js2-token-end
9299 pn (make-js2-array-node :pos pos
9300 :len (- js2-ts-cursor pos)
9301 :elems (nreverse elems)))
9302 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9303 (when after-comma
9304 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9305 pos elems after-comma)))
9306 ;; array comp
9307 ((and (>= js2-language-version 170)
9308 (= tt js2-FOR) ; check for array comprehension
9309 (not after-lb-or-comma) ; "for" can't follow a comma
9310 elems ; must have at least 1 element
9311 (not (cdr elems))) ; but no 2nd element
9312 (setf continue nil
9313 pn (js2-parse-array-comprehension (car elems) pos)))
9314 ;; another element
9315 (t
9316 (unless after-lb-or-comma
9317 (js2-report-error "msg.no.bracket.arg"))
9318 (push (js2-parse-assign-expr) elems)
9319 (setq after-lb-or-comma nil
9320 after-comma nil))))
9321 pn))
9322
9323 (defun js2-parse-array-comprehension (expr pos)
9324 "Parse a JavaScript 1.7 Array Comprehension.
9325 EXPR is the first expression after the opening left-bracket.
9326 POS is the beginning of the LB token preceding EXPR.
9327 We should have just parsed the 'for' keyword before calling this function."
9328 (let (loops
9329 filter
9330 if-pos
9331 result)
9332 (while (= (js2-peek-token) js2-FOR)
9333 (push (js2-parse-array-comp-loop) loops))
9334 (when (= (js2-peek-token) js2-IF)
9335 (js2-consume-token)
9336 (setq if-pos (- js2-token-beg pos) ; relative
9337 filter (js2-parse-condition)))
9338 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9339 (setq result (make-js2-array-comp-node :pos pos
9340 :len (- js2-ts-cursor pos)
9341 :result expr
9342 :loops (nreverse loops)
9343 :filter (car filter)
9344 :lp (js2-relpos (second filter) pos)
9345 :rp (js2-relpos (third filter) pos)
9346 :if-pos if-pos))
9347 (apply #'js2-node-add-children result expr (car filter)
9348 (js2-array-comp-node-loops result))
9349 result))
9350
9351 (defun js2-parse-array-comp-loop ()
9352 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9353 Last token peeked should be the initial FOR."
9354 (let ((pos js2-token-beg)
9355 (pn (make-js2-array-comp-loop-node))
9356 tt
9357 iter
9358 obj
9359 foreach-p
9360 in-pos
9361 each-pos
9362 lp
9363 rp)
9364 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9365 (js2-push-scope pn)
9366 (unwind-protect
9367 (progn
9368 (when (js2-match-token js2-NAME)
9369 (if (string= js2-ts-string "each")
9370 (progn
9371 (setq foreach-p t
9372 each-pos (- js2-token-beg pos)) ; relative
9373 (js2-record-face 'font-lock-keyword-face))
9374 (js2-report-error "msg.no.paren.for")))
9375 (if (js2-must-match js2-LP "msg.no.paren.for")
9376 (setq lp (- js2-token-beg pos)))
9377 (setq tt (js2-peek-token))
9378 (cond
9379 ((or (= tt js2-LB)
9380 (= tt js2-LC))
9381 ;; handle destructuring assignment
9382 (setq iter (js2-parse-primary-expr)))
9383 ((js2-valid-prop-name-token tt)
9384 (js2-consume-token)
9385 (setq iter (js2-create-name-node)))
9386 (t
9387 (js2-report-error "msg.bad.var")))
9388 ;; Define as a let since we want the scope of the variable to
9389 ;; be restricted to the array comprehension
9390 (if (js2-name-node-p iter)
9391 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9392 (if (js2-must-match js2-IN "msg.in.after.for.name")
9393 (setq in-pos (- js2-token-beg pos)))
9394 (setq obj (js2-parse-expr))
9395 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9396 (setq rp (- js2-token-beg pos)))
9397 (setf (js2-node-pos pn) pos
9398 (js2-node-len pn) (- js2-ts-cursor pos)
9399 (js2-array-comp-loop-node-iterator pn) iter
9400 (js2-array-comp-loop-node-object pn) obj
9401 (js2-array-comp-loop-node-in-pos pn) in-pos
9402 (js2-array-comp-loop-node-each-pos pn) each-pos
9403 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9404 (js2-array-comp-loop-node-lp pn) lp
9405 (js2-array-comp-loop-node-rp pn) rp)
9406 (js2-node-add-children pn iter obj))
9407 (js2-pop-scope))
9408 pn))
9409
9410 (defun js2-parse-object-literal (&optional lhs)
9411 (let ((pos js2-token-beg)
9412 tt
9413 elems
9414 result
9415 after-comma
9416 (continue t))
9417 (while continue
9418 (setq tt (js2-peek-token))
9419 (cond
9420 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9421 ((or (js2-valid-prop-name-token tt)
9422 (= tt js2-STRING))
9423 (setq after-comma nil
9424 result (js2-parse-named-prop tt lhs))
9425 (if (and (null result)
9426 (not js2-recover-from-parse-errors))
9427 (setq continue nil)
9428 (push result elems)))
9429 ;; {12: x} or {10.7: x}
9430 ((= tt js2-NUMBER)
9431 (js2-consume-token)
9432 (setq after-comma nil)
9433 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9434 ;; trailing comma
9435 ((= tt js2-RC)
9436 (setq continue nil)
9437 (if after-comma
9438 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9439 pos elems after-comma)))
9440 (t
9441 (js2-report-error "msg.bad.prop")
9442 (unless js2-recover-from-parse-errors
9443 (setq continue nil)))) ; end switch
9444 (if (js2-match-token js2-COMMA)
9445 (setq after-comma js2-token-end)
9446 (setq continue nil))) ; end loop
9447 (js2-must-match js2-RC "msg.no.brace.prop")
9448 (setq result (make-js2-object-node :pos pos
9449 :len (- js2-ts-cursor pos)
9450 :elems (nreverse elems)))
9451 (apply #'js2-node-add-children result (js2-object-node-elems result))
9452 result))
9453
9454 (defun js2-parse-named-prop (tt &optional lhs)
9455 "Parse a name, string, or getter/setter object property.
9456 When `lhs' is t, forms like {a, b, c} will be permitted."
9457 (js2-consume-token)
9458 (let ((string-prop (and (= tt js2-STRING)
9459 (make-js2-string-node)))
9460 expr
9461 (ppos js2-token-beg)
9462 (pend js2-token-end)
9463 (name (js2-create-name-node))
9464 (prop js2-ts-string))
9465 (cond
9466 ;; getter/setter prop
9467 ((and (= tt js2-NAME)
9468 (= (js2-peek-token) js2-NAME)
9469 (or (string= prop "get")
9470 (string= prop "set")))
9471 (progn
9472 (js2-consume-token)
9473 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9474 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9475 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9476 (js2-parse-getter-setter-prop ppos name (string= prop "get"))))
9477 ;; abbreviated destructuring bind e.g., {a, b} = c;
9478 ((and lhs
9479 (= tt js2-NAME)
9480 (let ((ctk (js2-peek-token)))
9481 (or (= ctk js2-COMMA)
9482 (= ctk js2-RC)
9483 (js2-valid-prop-name-token ctk))))
9484 (js2-set-face ppos pend 'font-lock-variable-name-face 'record)
9485 name)
9486 ;; regular prop
9487 (t
9488 (prog1
9489 (setq expr (js2-parse-plain-property (or string-prop name)))
9490 (js2-set-face ppos pend
9491 (if (js2-function-node-p
9492 (js2-object-prop-node-right expr))
9493 'font-lock-function-name-face
9494 'font-lock-variable-name-face)
9495 'record))))))
9496
9497 (defun js2-parse-plain-property (prop)
9498 "Parse a non-getter/setter property in an object literal.
9499 PROP is the node representing the property: a number, name or string."
9500 (js2-must-match js2-COLON "msg.no.colon.prop")
9501 (let* ((pos (js2-node-pos prop))
9502 (colon (- js2-token-beg pos))
9503 (expr (js2-parse-assign-expr))
9504 (result (make-js2-object-prop-node
9505 :pos pos
9506 ;; don't include last consumed token in length
9507 :len (- (+ (js2-node-pos expr)
9508 (js2-node-len expr))
9509 pos)
9510 :left prop
9511 :right expr
9512 :op-pos colon)))
9513 (js2-node-add-children result prop expr)
9514 result))
9515
9516 (defun js2-parse-getter-setter-prop (pos prop get-p)
9517 "Parse getter or setter property in an object literal.
9518 JavaScript syntax is:
9519
9520 { get foo() {...}, set foo(x) {...} }
9521
9522 and expression closure style is also supported
9523
9524 { get foo() x, set foo(x) _x = x }
9525
9526 POS is the start position of the `get' or `set' keyword.
9527 PROP is the `js2-name-node' representing the property name.
9528 GET-P is non-nil if the keyword was `get'."
9529 (let ((type (if get-p js2-GET js2-SET))
9530 result
9531 end
9532 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9533 ;; it has to be an anonymous function, as we already parsed the name
9534 (if (/= (js2-node-type fn) js2-FUNCTION)
9535 (js2-report-error "msg.bad.prop")
9536 (if (plusp (length (js2-function-name fn)))
9537 (js2-report-error "msg.bad.prop")))
9538 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9539 (setq end (js2-node-end fn)
9540 result (make-js2-getter-setter-node :type type
9541 :pos pos
9542 :len (- end pos)
9543 :left prop
9544 :right fn))
9545 (js2-node-add-children result prop fn)
9546 result))
9547
9548 (defun js2-create-name-node (&optional check-activation-p token)
9549 "Create a name node using the token info from last scanned name.
9550 In some cases we need to either synthesize a name node, or we lost
9551 the name token information by peeking. If the TOKEN parameter is
9552 not `js2-NAME', then we use the token info saved in instance vars."
9553 (let ((beg js2-token-beg)
9554 (s js2-ts-string)
9555 name)
9556 (when (/= js2-current-token js2-NAME)
9557 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9558 s js2-prev-name-token-string
9559 js2-prev-name-token-start nil
9560 js2-prev-name-token-string nil))
9561 (setq name (make-js2-name-node :pos beg
9562 :name s
9563 :len (length s)))
9564 (if check-activation-p
9565 (js2-check-activation-name s (or token js2-NAME)))
9566 name))
9567
9568 ;;; Indentation support
9569
9570 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9571 ;; Karl cleverly deduces that the desired indentation level is often a
9572 ;; function of paren/bracket/brace nesting depth, which can be determined
9573 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9574 ;; then does some equally clever checks to see if we're in the context of a
9575 ;; substatement of a possibly braceless statement keyword such as if, while,
9576 ;; or finally. This approach yields pretty good results.
9577
9578 ;; The indenter is often "wrong", however, and needs to be overridden.
9579 ;; The right long-term solution is probably to emulate (or integrate
9580 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9581 ;; parse tree from `js2-parse' is present, which is not true at the
9582 ;; moment the user is typing, computing indentation is still thousands
9583 ;; of lines of code to handle every possible syntactic edge case.
9584
9585 ;; In the meantime, the compromise solution is that we offer a "bounce
9586 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9587 ;; current line indent among various likely guess points. This approach
9588 ;; is far from perfect, but should at least make it slightly easier to
9589 ;; move the line towards its desired indentation when manually
9590 ;; overriding Karl's heuristic nesting guesser.
9591
9592 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9593 ;; extensions such as `let' and Array comprehensions. Major kudos to
9594 ;; Karl for coming up with the initial approach, which packs a lot of
9595 ;; punch for so little code.
9596
9597 (defconst js-possibly-braceless-keyword-re
9598 (regexp-opt
9599 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with" "let")
9600 'words)
9601 "Regular expression matching keywords that are optionally
9602 followed by an opening brace.")
9603
9604 (defconst js-indent-operator-re
9605 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9606 (regexp-opt '("in" "instanceof") 'words))
9607 "Regular expression matching operators that affect indentation
9608 of continued expressions.")
9609
9610 ;; This function has horrible results if you're typing an array
9611 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9612 ;; in conjunction with electric-indent, so just disabling it.
9613 (defsubst js2-code-at-bol-p ()
9614 "Return t if the first character on line is non-whitespace."
9615 nil)
9616
9617 (defun js2-insert-and-indent (key)
9618 "Run command bound to key and indent current line. Runs the command
9619 bound to KEY in the global keymap and indents the current line."
9620 (interactive (list (this-command-keys)))
9621 (let ((cmd (lookup-key (current-global-map) key)))
9622 (if (commandp cmd)
9623 (call-interactively cmd)))
9624 ;; don't do the electric keys inside comments or strings,
9625 ;; and don't do bounce-indent with them.
9626 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9627 (js2-bounce-indent-p (js2-code-at-bol-p)))
9628 (unless (or (nth 3 parse-state)
9629 (nth 4 parse-state))
9630 (indent-according-to-mode))))
9631
9632 (defun js-re-search-forward-inner (regexp &optional bound count)
9633 "Auxiliary function for `js-re-search-forward'."
9634 (let ((parse)
9635 (saved-point (point-min)))
9636 (while (> count 0)
9637 (re-search-forward regexp bound)
9638 (setq parse (parse-partial-sexp saved-point (point)))
9639 (cond ((nth 3 parse)
9640 (re-search-forward
9641 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9642 (save-excursion (end-of-line) (point)) t))
9643 ((nth 7 parse)
9644 (forward-line))
9645 ((or (nth 4 parse)
9646 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9647 (re-search-forward "\\*/"))
9648 (t
9649 (setq count (1- count))))
9650 (setq saved-point (point))))
9651 (point))
9652
9653 (defun js-re-search-forward (regexp &optional bound noerror count)
9654 "Search forward but ignore strings and comments. Invokes
9655 `re-search-forward' but treats the buffer as if strings and
9656 comments have been removed."
9657 (let ((saved-point (point))
9658 (search-expr
9659 (cond ((null count)
9660 '(js-re-search-forward-inner regexp bound 1))
9661 ((< count 0)
9662 '(js-re-search-backward-inner regexp bound (- count)))
9663 ((> count 0)
9664 '(js-re-search-forward-inner regexp bound count)))))
9665 (condition-case err
9666 (eval search-expr)
9667 (search-failed
9668 (goto-char saved-point)
9669 (unless noerror
9670 (error (error-message-string err)))))))
9671
9672 (defun js-re-search-backward-inner (regexp &optional bound count)
9673 "Auxiliary function for `js-re-search-backward'."
9674 (let ((parse)
9675 (saved-point (point-min)))
9676 (while (> count 0)
9677 (re-search-backward regexp bound)
9678 (setq parse (parse-partial-sexp saved-point (point)))
9679 (cond ((nth 3 parse)
9680 (re-search-backward
9681 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9682 (save-excursion (beginning-of-line) (point)) t))
9683 ((nth 7 parse)
9684 (goto-char (nth 8 parse)))
9685 ((or (nth 4 parse)
9686 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9687 (re-search-backward "/\\*"))
9688 (t
9689 (setq count (1- count))))))
9690 (point))
9691
9692 (defun js-re-search-backward (regexp &optional bound noerror count)
9693 "Search backward but ignore strings and comments. Invokes
9694 `re-search-backward' but treats the buffer as if strings and
9695 comments have been removed."
9696 (let ((saved-point (point))
9697 (search-expr
9698 (cond ((null count)
9699 '(js-re-search-backward-inner regexp bound 1))
9700 ((< count 0)
9701 '(js-re-search-forward-inner regexp bound (- count)))
9702 ((> count 0)
9703 '(js-re-search-backward-inner regexp bound count)))))
9704 (condition-case err
9705 (eval search-expr)
9706 (search-failed
9707 (goto-char saved-point)
9708 (unless noerror
9709 (error (error-message-string err)))))))
9710
9711 (defun js-looking-at-operator-p ()
9712 "Return non-nil if text after point is an operator (that is not
9713 a comma)."
9714 (save-match-data
9715 (and (looking-at js-indent-operator-re)
9716 (or (not (looking-at ":"))
9717 (save-excursion
9718 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9719 (looking-at "?")))))))
9720
9721 (defun js-continued-expression-p ()
9722 "Returns non-nil if the current line continues an expression."
9723 (save-excursion
9724 (back-to-indentation)
9725 (or (js-looking-at-operator-p)
9726 (and (js-re-search-backward "\n" nil t)
9727 (progn
9728 (skip-chars-backward " \t")
9729 (backward-char)
9730 (and (js-looking-at-operator-p)
9731 (and (progn (backward-char)
9732 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9733
9734 (defun js-end-of-do-while-loop-p ()
9735 "Returns non-nil if word after point is `while' of a do-while
9736 statement, else returns nil. A braceless do-while statement
9737 spanning several lines requires that the start of the loop is
9738 indented to the same column as the current line."
9739 (interactive)
9740 (save-excursion
9741 (save-match-data
9742 (when (looking-at "\\s-*\\<while\\>")
9743 (if (save-excursion
9744 (skip-chars-backward "[ \t\n]*}")
9745 (looking-at "[ \t\n]*}"))
9746 (save-excursion
9747 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9748 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9749 (or (looking-at "\\<do\\>")
9750 (let ((saved-indent (current-indentation)))
9751 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9752 (/= (current-indentation) saved-indent)))
9753 (and (looking-at "[ \t]*\\<do\\>")
9754 (not (js-re-search-forward
9755 "\\<while\\>" (point-at-eol) t))
9756 (= (current-indentation) saved-indent)))))))))
9757
9758 (defun js-ctrl-statement-indentation ()
9759 "Returns the proper indentation of the current line if it
9760 starts the body of a control statement without braces, else
9761 returns nil."
9762 (let (forward-sexp-function) ; temporarily unbind it
9763 (save-excursion
9764 (back-to-indentation)
9765 (when (save-excursion
9766 (and (not (js2-same-line (point-min)))
9767 (not (looking-at "{"))
9768 (js-re-search-backward "[[:graph:]]" nil t)
9769 (not (looking-at "[{([]"))
9770 (progn
9771 (forward-char)
9772 ;; scan-sexps sometimes throws an error
9773 (ignore-errors (backward-sexp))
9774 (when (looking-at "(") (backward-word 1))
9775 (and (save-excursion
9776 (skip-chars-backward " \t}" (point-at-bol))
9777 (or (bolp)
9778 (and (backward-word 1)
9779 (skip-chars-backward " \t}" (point-at-bol))
9780 (bolp)
9781 (looking-at "[ \t}]*else[ \t]+if"))))
9782 (looking-at js-possibly-braceless-keyword-re)
9783 (not (js-end-of-do-while-loop-p))))))
9784 (save-excursion
9785 (goto-char (match-beginning 0))
9786 (+ (current-indentation) js2-basic-offset))))))
9787
9788 (defun js2-indent-in-array-comp (parse-status)
9789 "Return non-nil if we think we're in an array comprehension.
9790 In particular, return the buffer position of the first `for' kwd."
9791 (let ((end (point)))
9792 (when (nth 1 parse-status)
9793 (save-excursion
9794 (goto-char (nth 1 parse-status))
9795 (when (looking-at "\\[")
9796 (forward-char 1)
9797 (js2-forward-sws)
9798 (if (looking-at "[[{]")
9799 (let (forward-sexp-function) ; use lisp version
9800 (forward-sexp) ; skip destructuring form
9801 (js2-forward-sws)
9802 (if (and (/= (char-after) ?,) ; regular array
9803 (looking-at "for"))
9804 (match-beginning 0)))
9805 ;; to skip arbitrary expressions we need the parser,
9806 ;; so we'll just guess at it.
9807 (if (re-search-forward "[^,]* \\(for\\) " end t)
9808 (match-beginning 1))))))))
9809
9810 (defun js2-array-comp-indentation (parse-status for-kwd)
9811 (if (js2-same-line for-kwd)
9812 ;; first continuation line
9813 (save-excursion
9814 (goto-char (nth 1 parse-status))
9815 (forward-char 1)
9816 (skip-chars-forward " \t")
9817 (current-column))
9818 (save-excursion
9819 (goto-char for-kwd)
9820 (current-column))))
9821
9822 (defun js-proper-indentation (parse-status)
9823 "Return the proper indentation for the current line."
9824 (save-excursion
9825 (back-to-indentation)
9826 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9827 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9828 (continued-expr-p (js-continued-expression-p))
9829 (bracket (nth 1 parse-status))
9830 beg)
9831 (cond
9832 ;; indent array comprehension continuation lines specially
9833 ((and bracket
9834 (not (js2-same-line bracket))
9835 (setq beg (js2-indent-in-array-comp parse-status))
9836 (>= (point) (save-excursion
9837 (goto-char beg)
9838 (point-at-bol)))) ; at or after first loop?
9839 (js2-array-comp-indentation parse-status beg))
9840
9841 (ctrl-stmt-indent)
9842
9843 (bracket
9844 (goto-char bracket)
9845 (cond
9846 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9847 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9848 (when (save-excursion (skip-chars-backward " \t)")
9849 (looking-at ")"))
9850 (backward-list))
9851 (if (nth 1 p)
9852 (progn (goto-char (1+ (nth 1 p)))
9853 (skip-chars-forward " \t"))
9854 (back-to-indentation))
9855 (cond (same-indent-p
9856 (current-column))
9857 (continued-expr-p
9858 (+ (current-column) (* 2 js2-basic-offset)))
9859 (t
9860 (+ (current-column) js2-basic-offset)))))
9861 (t
9862 (unless same-indent-p
9863 (forward-char)
9864 (skip-chars-forward " \t"))
9865 (current-column))))
9866
9867 (continued-expr-p js2-basic-offset)
9868 (t 0)))))
9869
9870 (defun js2-lineup-comment (parse-status)
9871 "Indent a multi-line block comment continuation line."
9872 (let* ((beg (nth 8 parse-status))
9873 (first-line (js2-same-line beg))
9874 (offset (save-excursion
9875 (goto-char beg)
9876 (if (looking-at "/\\*")
9877 (+ 1 (current-column))
9878 0))))
9879 (unless first-line
9880 (indent-line-to offset))))
9881
9882 (defun js2-backward-sws ()
9883 "Move backward through whitespace and comments."
9884 (interactive)
9885 (while (forward-comment -1)))
9886
9887 (defun js2-forward-sws ()
9888 "Move forward through whitespace and comments."
9889 (interactive)
9890 (while (forward-comment 1)))
9891
9892 (defsubst js2-current-indent (&optional pos)
9893 "Return column of indentation on current line.
9894 If POS is non-nil, go to that point and return indentation for that line."
9895 (save-excursion
9896 (if pos
9897 (goto-char pos))
9898 (back-to-indentation)
9899 (current-column)))
9900
9901 (defsubst js2-arglist-close ()
9902 "Return non-nil if we're on a line beginning with a close-paren/brace."
9903 (save-match-data
9904 (save-excursion
9905 (goto-char (point-at-bol))
9906 (js2-forward-sws)
9907 (looking-at "[])}]"))))
9908
9909 (defsubst js2-indent-looks-like-label-p ()
9910 (goto-char (point-at-bol))
9911 (js2-forward-sws)
9912 (looking-at (concat js2-mode-identifier-re ":")))
9913
9914 (defun js2-indent-in-objlit-p (parse-status)
9915 "Return non-nil if this looks like an object-literal entry."
9916 (let ((start (nth 1 parse-status)))
9917 (and
9918 start
9919 (save-excursion
9920 (and (zerop (forward-line -1))
9921 (not (< (point) start)) ; crossed a {} boundary
9922 (js2-indent-looks-like-label-p)))
9923 (save-excursion
9924 (js2-indent-looks-like-label-p)))))
9925
9926 ;; if prev line looks like foobar({ then we're passing an object
9927 ;; literal to a function call, and people pretty much always want to
9928 ;; de-dent back to the previous line, so move the 'basic-offset'
9929 ;; position to the front.
9930 (defsubst js2-indent-objlit-arg-p (parse-status)
9931 (save-excursion
9932 (back-to-indentation)
9933 (js2-backward-sws)
9934 (and (eq (1- (point)) (nth 1 parse-status))
9935 (eq (char-before) ?{)
9936 (progn
9937 (forward-char -1)
9938 (skip-chars-backward " \t")
9939 (eq (char-before) ?\()))))
9940
9941 (defsubst js2-indent-case-block-p ()
9942 (save-excursion
9943 (back-to-indentation)
9944 (js2-backward-sws)
9945 (goto-char (point-at-bol))
9946 (skip-chars-forward " \t")
9947 (save-match-data
9948 (looking-at "case\\s-.+:"))))
9949
9950 (defsubst js2-syntax-bol ()
9951 "Return the point at the first non-whitespace char on the line.
9952 Returns `point-at-bol' if the line is empty."
9953 (save-excursion
9954 (beginning-of-line)
9955 (skip-chars-forward " \t")
9956 (point)))
9957
9958 (defun js2-bounce-indent (normal-col parse-status)
9959 "Cycle among alternate computed indentation positions.
9960 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9961 of the buffer to the current point. NORMAL-COL is the indentation
9962 column computed by the heuristic guesser based on current paren,
9963 bracket, brace and statement nesting."
9964 (let ((cur-indent (js2-current-indent))
9965 (old-buffer-undo-list buffer-undo-list)
9966 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9967 (current-line (save-excursion
9968 (forward-line 0) ; move to bol
9969 (1+ (count-lines (point-min) (point)))))
9970 positions
9971 pos
9972 anchor
9973 arglist-cont
9974 same-indent
9975 prev-line-col
9976 basic-offset
9977 computed-pos)
9978 ;; temporarily don't record undo info, if user requested this
9979 (if js2-mode-indent-inhibit-undo
9980 (setq buffer-undo-list t))
9981 (unwind-protect
9982 (progn
9983 ;; first likely point: indent from beginning of previous code line
9984 (push (setq basic-offset
9985 (+ (save-excursion
9986 (back-to-indentation)
9987 (js2-backward-sws)
9988 (back-to-indentation)
9989 (setq prev-line-col (current-column)))
9990 js2-basic-offset))
9991 positions)
9992
9993 ;; (first + epsilon) likely point: indent 2x from beginning of
9994 ;; previous code line. Some companies like this approach. Ahem.
9995 ;; Seriously, though -- 4-space indent for expression continuation
9996 ;; lines isn't a bad idea. We should eventually implement it
9997 ;; that way.
9998 (push (setq basic-offset
9999 (+ (save-excursion
10000 (back-to-indentation)
10001 (js2-backward-sws)
10002 (back-to-indentation)
10003 (setq prev-line-col (current-column)))
10004 (* 2 js2-basic-offset)))
10005 positions)
10006
10007 ;; second likely point: indent from assign-expr RHS. This
10008 ;; is just a crude guess based on finding " = " on the previous
10009 ;; line containing actual code.
10010 (setq pos (save-excursion
10011 (save-match-data
10012 (forward-line -1)
10013 (goto-char (point-at-bol))
10014 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10015 (point-at-eol) t)
10016 (goto-char (match-end 1))
10017 (skip-chars-forward " \t\r\n")
10018 (current-column)))))
10019 (when pos
10020 (incf pos js2-basic-offset)
10021 (unless (member pos positions)
10022 (push pos positions)))
10023
10024 ;; third likely point: same indent as previous line of code.
10025 ;; Make it the first likely point if we're not on an
10026 ;; arglist-close line and previous line ends in a comma, or
10027 ;; both this line and prev line look like object-literal
10028 ;; elements.
10029 (setq pos (save-excursion
10030 (goto-char (point-at-bol))
10031 (js2-backward-sws)
10032 (back-to-indentation)
10033 (prog1
10034 (current-column)
10035 ;; while we're here, look for trailing comma
10036 (if (save-excursion
10037 (goto-char (point-at-eol))
10038 (js2-backward-sws)
10039 (eq (char-before) ?,))
10040 (setq arglist-cont (1- (point)))))))
10041 (when pos
10042 (if (and (or arglist-cont
10043 (js2-indent-in-objlit-p parse-status))
10044 (not (js2-arglist-close)))
10045 (setq same-indent pos))
10046 (unless (member pos positions)
10047 (push pos positions)))
10048
10049 ;; fourth likely point: first preceding code with less indentation
10050 ;; than the immediately preceding code line.
10051 (setq pos (save-excursion
10052 (js2-backward-sws)
10053 (back-to-indentation)
10054 (setq anchor (current-column))
10055 (while (and (zerop (forward-line -1))
10056 (>= (progn
10057 (back-to-indentation)
10058 (current-column))
10059 anchor)))
10060 (setq pos (current-column))))
10061 (unless (member pos positions)
10062 (push pos positions))
10063
10064 ;; put nesting-heuristic position first in list, sort rest
10065 (setq positions (nreverse (sort positions '<)))
10066 (setq positions (cons normal-col (delete normal-col positions)))
10067
10068 ;; comma-list continuation lines: prev line indent takes precedence
10069 (if same-indent
10070 (setq positions
10071 (cons same-indent
10072 (sort (delete same-indent positions) '<))))
10073
10074 ;; common special cases where we want to indent in from previous line
10075 (if (or (js2-indent-case-block-p)
10076 (js2-indent-objlit-arg-p parse-status))
10077 (setq positions
10078 (cons basic-offset
10079 (delete basic-offset positions))))
10080
10081 ;; record whether we're already sitting on one of the alternatives
10082 (setq pos (member cur-indent positions))
10083 (cond
10084 ;; case 0: we're one one of the alternatives and this is the
10085 ;; first time they've pressed TAB on this line (best-guess).
10086 ((and js2-mode-indent-ignore-first-tab
10087 pos
10088 ;; first time pressing TAB on this line?
10089 (not (eq js2-mode-last-indented-line current-line)))
10090 ;; do nothing
10091 (setq computed-pos nil))
10092 ;; case 1: only one computed position => use it
10093 ((null (cdr positions))
10094 (setq computed-pos 0))
10095 ;; case 2: not on any of the computed spots => use main spot
10096 ((not pos)
10097 (setq computed-pos 0))
10098 ;; case 3: on last position: cycle to first position
10099 ((null (cdr pos))
10100 (setq computed-pos 0))
10101 ;; case 4: on intermediate position: cycle to next position
10102 (t
10103 (setq computed-pos (js2-position (second pos) positions))))
10104
10105 ;; see if any hooks want to indent; otherwise we do it
10106 (loop with result = nil
10107 for hook in js2-indent-hook
10108 while (null result)
10109 do
10110 (setq result (funcall hook positions computed-pos))
10111 finally do
10112 (unless (or result (null computed-pos))
10113 (indent-line-to (nth computed-pos positions)))))
10114
10115 ;; finally
10116 (if js2-mode-indent-inhibit-undo
10117 (setq buffer-undo-list old-buffer-undo-list))
10118 ;; see commentary for `js2-mode-last-indented-line'
10119 (setq js2-mode-last-indented-line current-line))))
10120
10121 (defsubst js2-1-line-comment-continuation-p ()
10122 "Return t if we're in a 1-line comment continuation.
10123 If so, we don't ever want to use bounce-indent."
10124 (save-excursion
10125 (save-match-data
10126 (and (progn
10127 (forward-line 0)
10128 (looking-at "\\s-*//"))
10129 (progn
10130 (forward-line -1)
10131 (forward-line 0)
10132 (when (looking-at "\\s-*$")
10133 (js2-backward-sws)
10134 (forward-line 0))
10135 (looking-at "\\s-*//"))))))
10136
10137 (defun js2-indent-line ()
10138 "Indent the current line as JavaScript source text."
10139 (interactive)
10140 (let (parse-status
10141 current-indent
10142 offset
10143 indent-col
10144 moved
10145 ;; don't whine about errors/warnings when we're indenting.
10146 ;; This has to be set before calling parse-partial-sexp below.
10147 (inhibit-point-motion-hooks t))
10148 (setq parse-status (save-excursion
10149 (parse-partial-sexp (point-min)
10150 (point-at-bol)))
10151 offset (- (point) (save-excursion
10152 (back-to-indentation)
10153 (setq current-indent (current-column))
10154 (point))))
10155 (js2-with-underscore-as-word-syntax
10156 (if (nth 4 parse-status)
10157 (js2-lineup-comment parse-status)
10158 (setq indent-col (js-proper-indentation parse-status))
10159 ;; see comments below about js2-mode-last-indented-line
10160 (when
10161 (cond
10162 ;; bounce-indenting is disabled during electric-key indent.
10163 ;; It doesn't work well on first line of buffer.
10164 ((and js2-bounce-indent-p
10165 (not (js2-same-line (point-min)))
10166 (not (js2-1-line-comment-continuation-p)))
10167 (js2-bounce-indent indent-col parse-status)
10168 (setq moved t))
10169 ;; just indent to the guesser's likely spot
10170 ((/= current-indent indent-col)
10171 (indent-line-to indent-col)
10172 (setq moved t)))
10173 (when (and moved (plusp offset))
10174 (forward-char offset)))))))
10175
10176 (defun js2-indent-region (start end)
10177 "Indent the region, but don't use bounce indenting."
10178 (let ((js2-bounce-indent-p nil)
10179 (indent-region-function nil))
10180 (indent-region start end nil))) ; nil for byte-compiler
10181
10182 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10183
10184 ;;;###autoload
10185 (defun js2-mode ()
10186 "Major mode for editing JavaScript code."
10187 (interactive)
10188 (kill-all-local-variables)
10189 (set-syntax-table js2-mode-syntax-table)
10190 (use-local-map js2-mode-map)
10191 (setq major-mode 'js2-mode
10192 mode-name "JavaScript-IDE"
10193 comment-start "//" ; used by comment-region; don't change it
10194 comment-end "")
10195 (setq local-abbrev-table js2-mode-abbrev-table)
10196 (set (make-local-variable 'max-lisp-eval-depth)
10197 (max max-lisp-eval-depth 3000))
10198 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10199 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10200
10201 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10202 ;; on most platforms other than the one I originally wrote it on. So it's
10203 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10204 ;; with our binding of the RET key inside comments: short lines stay short.
10205 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10206
10207 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10208 (set (make-local-variable 'next-error-function) #'js2-next-error)
10209 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10210 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10211 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10212 ;; for characters inside regexp literals.
10213 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10214 ;; this is necessary to make `show-paren-function' work properly
10215 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10216 ;; needed for M-x rgrep, among other things
10217 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10218
10219 ;; some variables needed by cc-engine for paragraph-fill, etc.
10220 (setq c-buffer-is-cc-mode t
10221 c-comment-prefix-regexp js2-comment-prefix-regexp
10222 c-comment-start-regexp "/[*/]\\|\\s|"
10223 c-paragraph-start js2-paragraph-start
10224 c-paragraph-separate "$"
10225 comment-start-skip js2-comment-start-skip
10226 c-syntactic-ws-start js2-syntactic-ws-start
10227 c-syntactic-ws-end js2-syntactic-ws-end
10228 c-syntactic-eol js2-syntactic-eol)
10229
10230 (setq js2-default-externs
10231 (append js2-ecma-262-externs
10232 (if js2-include-browser-externs
10233 js2-browser-externs)
10234 (if js2-include-gears-externs
10235 js2-gears-externs)
10236 (if js2-include-rhino-externs
10237 js2-rhino-externs)))
10238
10239 ;; We do our own syntax highlighting based on the parse tree.
10240 ;; However, we want minor modes that add keywords to highlight properly
10241 ;; (examples: doxymacs, column-marker). We do this by not letting
10242 ;; font-lock unfontify anything, and telling it to fontify after we
10243 ;; re-parse and re-highlight the buffer. (We currently don't do any
10244 ;; work with regions other than the whole buffer.)
10245 (dolist (var '(font-lock-unfontify-buffer-function
10246 font-lock-unfontify-region-function))
10247 (set (make-local-variable var) (lambda (&rest args) t)))
10248
10249 ;; Don't let font-lock do syntactic (string/comment) fontification.
10250 (set (make-local-variable #'font-lock-syntactic-face-function)
10251 (lambda (state) nil))
10252
10253 ;; Experiment: make reparse-delay longer for longer files.
10254 (if (plusp js2-dynamic-idle-timer-adjust)
10255 (setq js2-idle-timer-delay
10256 (* js2-idle-timer-delay
10257 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10258
10259 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10260 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10261 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10262 (imenu-add-to-menubar (concat "IM-" mode-name))
10263 (when js2-mirror-mode
10264 (js2-enter-mirror-mode))
10265 (add-to-invisibility-spec '(js2-outline . t))
10266 (set (make-local-variable 'line-move-ignore-invisible) t)
10267 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10268 (setq js2-mode-functions-hidden nil
10269 js2-mode-comments-hidden nil
10270 js2-mode-buffer-dirty-p t
10271 js2-mode-parsing nil)
10272 (js2-reparse)
10273 (run-hooks 'js2-mode-hook))
10274
10275 (defun js2-mode-exit ()
10276 "Exit `js2-mode' and clean up."
10277 (interactive)
10278 (when js2-mode-node-overlay
10279 (delete-overlay js2-mode-node-overlay)
10280 (setq js2-mode-node-overlay nil))
10281 (js2-remove-overlays)
10282 (setq js2-mode-ast nil)
10283 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10284 (remove-from-invisibility-spec '(js2-outline . t))
10285 (js2-mode-show-all)
10286 (js2-with-unmodifying-text-property-changes
10287 (js2-clear-face (point-min) (point-max))))
10288
10289 (defun js2-before-save ()
10290 "Clean up whitespace before saving file.
10291 You can disable this by customizing `js2-cleanup-whitespace'."
10292 (when js2-cleanup-whitespace
10293 (let ((col (current-column)))
10294 (delete-trailing-whitespace)
10295 ;; don't change trailing whitespace on current line
10296 (unless (eq (current-column) col)
10297 (indent-to col)))))
10298
10299 (defsubst js2-mode-reset-timer ()
10300 "Cancel any existing parse timer and schedule a new one."
10301 (if js2-mode-parse-timer
10302 (cancel-timer js2-mode-parse-timer))
10303 (setq js2-mode-parsing nil)
10304 (setq js2-mode-parse-timer
10305 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10306
10307 (defun js2-mode-edit (beg end len)
10308 "Schedule a new parse after buffer is edited.
10309 Buffer edit spans from BEG to END and is of length LEN.
10310 Also clears the `js2-magic' bit on autoinserted parens/brackets
10311 if the edit occurred on a line different from the magic paren."
10312 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10313 (line (if magic-pos (line-number-at-pos magic-pos))))
10314 (and line
10315 (or (/= (line-number-at-pos beg) line)
10316 (and (> 0 len)
10317 (/= (line-number-at-pos end) line)))
10318 (js2-mode-mundanify-parens)))
10319 (setq js2-mode-buffer-dirty-p t)
10320 (js2-mode-hide-overlay)
10321 (js2-mode-reset-timer))
10322
10323 (defun js2-mode-run-font-lock ()
10324 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10325 This is intended to allow modes that install their own font-lock keywords
10326 to work with js2-mode. In practice it never seems to work for long.
10327 Hopefully the Emacs maintainers can help figure out a way to make it work."
10328 (when (and (boundp 'font-lock-keywords)
10329 font-lock-keywords
10330 (boundp 'font-lock-mode)
10331 font-lock-mode)
10332 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10333 ;; play nicely with js2-mode. They go out of their way to fail to
10334 ;; provide any option for saying "look, fontify the farging buffer
10335 ;; with just the keywords already". Argh.
10336 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10337 (let (font-lock-verbose)
10338 (font-lock-fontify-buffer))))
10339
10340 (defun js2-reparse (&optional force)
10341 "Re-parse current buffer after user finishes some data entry.
10342 If we get any user input while parsing, including cursor motion,
10343 we discard the parse and reschedule it. If FORCE is nil, then the
10344 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10345 (let (time
10346 interrupted-p
10347 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10348 (unless js2-mode-parsing
10349 (setq js2-mode-parsing t)
10350 (unwind-protect
10351 (when (or js2-mode-buffer-dirty-p force)
10352 (js2-remove-overlays)
10353 (js2-with-unmodifying-text-property-changes
10354 (remove-text-properties (point-min) (point-max) '(syntax-table))
10355 (setq js2-mode-buffer-dirty-p nil
10356 js2-mode-fontifications nil
10357 js2-mode-deferred-properties nil
10358 js2-additional-externs nil)
10359 (if js2-mode-verbose-parse-p
10360 (message "parsing..."))
10361 (setq time
10362 (js2-time
10363 (setq interrupted-p
10364 (catch 'interrupted
10365 (setq js2-mode-ast (js2-parse))
10366 (when (plusp js2-highlight-level)
10367 (js2-mode-fontify-regions))
10368 (js2-mode-remove-suppressed-warnings)
10369 (js2-mode-show-warnings)
10370 (js2-mode-show-errors)
10371 (js2-mode-run-font-lock) ; note: doesn't work
10372 (js2-mode-highlight-magic-parens)
10373 (if (>= js2-highlight-level 1)
10374 (js2-highlight-jsdoc js2-mode-ast))
10375 nil))))
10376 (if interrupted-p
10377 (progn
10378 ;; unfinished parse => try again
10379 (setq js2-mode-buffer-dirty-p t)
10380 (js2-mode-reset-timer))
10381 (if js2-mode-verbose-parse-p
10382 (message "Parse time: %s" time)))))
10383 (setq js2-mode-parsing nil)
10384 (unless interrupted-p
10385 (setq js2-mode-parse-timer nil))))))
10386
10387 (defun js2-mode-show-node ()
10388 "Debugging aid: highlight selected AST node on mouse click."
10389 (interactive)
10390 (let ((node (js2-node-at-point))
10391 beg
10392 end)
10393 (when js2-mode-show-overlay
10394 (if (null node)
10395 (message "No node found at location %s" (point))
10396 (setq beg (js2-node-abs-pos node)
10397 end (+ beg (js2-node-len node)))
10398 (if js2-mode-node-overlay
10399 (move-overlay js2-mode-node-overlay beg end)
10400 (setq js2-mode-node-overlay (make-overlay beg end))
10401 (overlay-put js2-mode-node-overlay 'face 'highlight))
10402 (js2-with-unmodifying-text-property-changes
10403 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10404 (message "%s, parent: %s"
10405 (js2-node-short-name node)
10406 (if (js2-node-parent node)
10407 (js2-node-short-name (js2-node-parent node))
10408 "nil"))))))
10409
10410 (defun js2-mode-hide-overlay (&optional p1 p2)
10411 "Remove the debugging overlay when the point moves.
10412 P1 and P2 are the old and new values of point, respectively."
10413 (when js2-mode-node-overlay
10414 (let ((beg (overlay-start js2-mode-node-overlay))
10415 (end (overlay-end js2-mode-node-overlay)))
10416 ;; Sometimes we're called spuriously.
10417 (unless (and p2
10418 (>= p2 beg)
10419 (<= p2 end))
10420 (js2-with-unmodifying-text-property-changes
10421 (remove-text-properties beg end '(point-left nil)))
10422 (delete-overlay js2-mode-node-overlay)
10423 (setq js2-mode-node-overlay nil)))))
10424
10425 (defun js2-mode-reset ()
10426 "Debugging helper: reset everything."
10427 (interactive)
10428 (js2-mode-exit)
10429 (js2-mode))
10430
10431 (defsubst js2-mode-show-warn-or-err (e face)
10432 "Highlight a warning or error E with FACE.
10433 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10434 (let* ((key (first e))
10435 (beg (second e))
10436 (end (+ beg (third e)))
10437 ;; Don't inadvertently go out of bounds.
10438 (beg (max (point-min) (min beg (point-max))))
10439 (end (max (point-min) (min end (point-max))))
10440 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10441 (ovl (make-overlay beg end)))
10442 (overlay-put ovl 'face face)
10443 (overlay-put ovl 'js2-error t)
10444 (put-text-property beg end 'help-echo (js2-get-msg key))
10445 (put-text-property beg end 'point-entered #'js2-echo-error)))
10446
10447 (defun js2-remove-overlays ()
10448 "Remove overlays from buffer that have a `js2-error' property."
10449 (let ((beg (point-min))
10450 (end (point-max)))
10451 (save-excursion
10452 (dolist (o (overlays-in beg end))
10453 (when (overlay-get o 'js2-error)
10454 (delete-overlay o))))))
10455
10456 (defun js2-error-at-point (&optional pos)
10457 "Return non-nil if there's an error overlay at POS.
10458 Defaults to point."
10459 (loop with pos = (or pos (point))
10460 for o in (overlays-at pos)
10461 thereis (overlay-get o 'js2-error)))
10462
10463 (defun js2-mode-fontify-regions ()
10464 "Apply fontifications recorded during parsing."
10465 ;; We defer clearing faces as long as possible to eliminate flashing.
10466 (js2-clear-face (point-min) (point-max))
10467 ;; have to reverse the recorded fontifications so that errors and
10468 ;; warnings overwrite the normal fontifications
10469 (dolist (f (nreverse js2-mode-fontifications))
10470 (put-text-property (first f) (second f) 'face (third f)))
10471 (setq js2-mode-fontifications nil)
10472 (dolist (p js2-mode-deferred-properties)
10473 (apply #'put-text-property p))
10474 (setq js2-mode-deferred-properties nil))
10475
10476 (defun js2-mode-show-errors ()
10477 "Highlight syntax errors."
10478 (when js2-mode-show-parse-errors
10479 (dolist (e (js2-ast-root-errors js2-mode-ast))
10480 (js2-mode-show-warn-or-err e 'js2-error-face))))
10481
10482 (defun js2-mode-remove-suppressed-warnings ()
10483 "Take suppressed warnings out of the AST warnings list.
10484 This ensures that the counts and `next-error' are correct."
10485 (setf (js2-ast-root-warnings js2-mode-ast)
10486 (js2-delete-if
10487 (lambda (e)
10488 (let ((key (caar e)))
10489 (or
10490 (and (not js2-strict-trailing-comma-warning)
10491 (string-match "trailing\\.comma" key))
10492 (and (not js2-strict-cond-assign-warning)
10493 (string= key "msg.equal.as.assign"))
10494 (and js2-missing-semi-one-line-override
10495 (string= key "msg.missing.semi")
10496 (let* ((beg (second e))
10497 (node (js2-node-at-point beg))
10498 (fn (js2-mode-find-parent-fn node))
10499 (body (and fn (js2-function-node-body fn)))
10500 (lc (and body (js2-node-abs-pos body)))
10501 (rc (and lc (+ lc (js2-node-len body)))))
10502 (and fn
10503 (or (null body)
10504 (save-excursion
10505 (goto-char beg)
10506 (and (js2-same-line lc)
10507 (js2-same-line rc))))))))))
10508 (js2-ast-root-warnings js2-mode-ast))))
10509
10510 (defun js2-mode-show-warnings ()
10511 "Highlight strict-mode warnings."
10512 (when js2-mode-show-strict-warnings
10513 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10514 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10515
10516 (defun js2-echo-error (old-point new-point)
10517 "Called by point-motion hooks."
10518 (let ((msg (get-text-property new-point 'help-echo)))
10519 (if msg
10520 (message msg))))
10521
10522 (defalias #'js2-echo-help #'js2-echo-error)
10523
10524 (defun js2-enter-key ()
10525 "Handle user pressing the Enter key."
10526 (interactive)
10527 (let ((parse-status (save-excursion
10528 (parse-partial-sexp (point-min) (point)))))
10529 (cond
10530 ;; check if we're inside a string
10531 ((nth 3 parse-status)
10532 (js2-mode-split-string parse-status))
10533 ;; check if inside a block comment
10534 ((nth 4 parse-status)
10535 (js2-mode-extend-comment))
10536 (t
10537 ;; should probably figure out what the mode-map says we should do
10538 (if js2-indent-on-enter-key
10539 (let ((js2-bounce-indent-p nil))
10540 (js2-indent-line)))
10541 (insert "\n")
10542 (if js2-enter-indents-newline
10543 (let ((js2-bounce-indent-p nil))
10544 (js2-indent-line)))))))
10545
10546 (defun js2-mode-split-string (parse-status)
10547 "Turn a newline in mid-string into a string concatenation.
10548 PARSE-STATUS is as documented in `parse-partial-sexp'."
10549 (let* ((col (current-column))
10550 (quote-char (nth 3 parse-status))
10551 (quote-string (string quote-char))
10552 (string-beg (nth 8 parse-status))
10553 (indent (save-match-data
10554 (or
10555 (save-excursion
10556 (back-to-indentation)
10557 (if (looking-at "\\+")
10558 (current-column)))
10559 (save-excursion
10560 (goto-char string-beg)
10561 (if (looking-back "\\+\\s-+")
10562 (goto-char (match-beginning 0)))
10563 (current-column))))))
10564 (insert quote-char "\n")
10565 (indent-to indent)
10566 (insert "+ " quote-string)
10567 (when (eolp)
10568 (insert quote-string)
10569 (backward-char 1))))
10570
10571 (defun js2-mode-extend-comment ()
10572 "When inside a comment block, add comment prefix."
10573 (let (star single col first-line needs-close)
10574 (save-excursion
10575 (back-to-indentation)
10576 (cond
10577 ((looking-at "\\*[^/]")
10578 (setq star t
10579 col (current-column)))
10580 ((looking-at "/\\*")
10581 (setq star t
10582 first-line t
10583 col (1+ (current-column))))
10584 ((looking-at "//")
10585 (setq single t
10586 col (current-column)))))
10587 ;; Heuristic for whether we need to close the comment:
10588 ;; if we've got a parse error here, assume it's an unterminated
10589 ;; comment.
10590 (setq needs-close
10591 (or
10592 (eq (get-text-property (1- (point)) 'point-entered)
10593 'js2-echo-error)
10594 ;; The heuristic above doesn't work well when we're
10595 ;; creating a comment and there's another one downstream,
10596 ;; as our parser thinks this one ends at the end of the
10597 ;; next one. (You can have a /* inside a js block comment.)
10598 ;; So just close it if the next non-ws char isn't a *.
10599 (and first-line
10600 (eolp)
10601 (save-excursion
10602 (skip-chars-forward " \t\r\n")
10603 (not (eq (char-after) ?*))))))
10604 (insert "\n")
10605 (cond
10606 (star
10607 (indent-to col)
10608 (insert "* ")
10609 (if (and first-line needs-close)
10610 (save-excursion
10611 (insert "\n")
10612 (indent-to col)
10613 (insert "*/"))))
10614 (single
10615 (when (save-excursion
10616 (and (zerop (forward-line 1))
10617 (looking-at "\\s-*//")))
10618 (indent-to col)
10619 (insert "// "))))))
10620
10621 (defun js2-beginning-of-line ()
10622 "Toggles point between bol and first non-whitespace char in line.
10623 Also moves past comment delimiters when inside comments."
10624 (interactive)
10625 (let (node beg)
10626 (cond
10627 ((bolp)
10628 (back-to-indentation))
10629 ((looking-at "//")
10630 (skip-chars-forward "/ \t"))
10631 ((and (eq (char-after) ?*)
10632 (setq node (js2-comment-at-point))
10633 (memq (js2-comment-node-format node) '(jsdoc block))
10634 (save-excursion
10635 (skip-chars-backward " \t")
10636 (bolp)))
10637 (skip-chars-forward "\* \t"))
10638 (t
10639 (goto-char (point-at-bol))))))
10640
10641 (defun js2-end-of-line ()
10642 "Toggles point between eol and last non-whitespace char in line."
10643 (interactive)
10644 (if (eolp)
10645 (skip-chars-backward " \t")
10646 (goto-char (point-at-eol))))
10647
10648 (defun js2-enter-mirror-mode()
10649 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10650 on insertion."
10651 (interactive)
10652 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10653 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10654 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10655 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10656 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10657 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10658 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10659 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10660
10661 (defun js2-leave-mirror-mode()
10662 "Turns off mirror mode."
10663 (interactive)
10664 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10665 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10666
10667 (defsubst js2-mode-inside-string ()
10668 "Return non-nil if inside a string.
10669 Actually returns the quote character that begins the string."
10670 (let ((parse-state (save-excursion
10671 (parse-partial-sexp (point-min) (point)))))
10672 (nth 3 parse-state)))
10673
10674 (defsubst js2-mode-inside-comment-or-string ()
10675 "Return non-nil if inside a comment or string."
10676 (or
10677 (let ((comment-start
10678 (save-excursion
10679 (goto-char (point-at-bol))
10680 (if (re-search-forward "//" (point-at-eol) t)
10681 (match-beginning 0)))))
10682 (and comment-start
10683 (<= comment-start (point))))
10684 (let ((parse-state (save-excursion
10685 (parse-partial-sexp (point-min) (point)))))
10686 (or (nth 3 parse-state)
10687 (nth 4 parse-state)))))
10688
10689 (defsubst js2-make-magic-delimiter (delim &optional pos)
10690 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10691 Sets value of `js2-magic' text property to line number at POS."
10692 (propertize delim
10693 'js2-magic (line-number-at-pos pos)
10694 'face 'js2-magic-paren-face))
10695
10696 (defun js2-mode-match-delimiter (open close)
10697 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10698 The rule we use, which as far as we can tell is how Eclipse works,
10699 is that we insert the match if we're not in a comment or string,
10700 and the next non-whitespace character is either punctuation or
10701 occurs on another line."
10702 (insert open)
10703 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10704 (not (js2-mode-inside-comment-or-string)))
10705 (save-excursion
10706 (insert (js2-make-magic-delimiter close)))
10707 (when js2-auto-indent-p
10708 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10709 (js2-indent-line)))))
10710
10711 (defun js2-mode-match-bracket ()
10712 "Insert matching bracket."
10713 (interactive)
10714 (js2-mode-match-delimiter "[" "]"))
10715
10716 (defun js2-mode-match-paren ()
10717 "Insert matching paren unless already inserted."
10718 (interactive)
10719 (js2-mode-match-delimiter "(" ")"))
10720
10721 (defun js2-mode-match-curly (arg)
10722 "Insert matching curly-brace.
10723 With prefix arg, no formatting or indentation will occur -- the close-brace
10724 is simply inserted directly at the point."
10725 (interactive "p")
10726 (let (try-pos)
10727 (cond
10728 (current-prefix-arg
10729 (js2-mode-match-delimiter "{" "}"))
10730 ((and js2-auto-insert-catch-block
10731 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10732 (point-at-bol))
10733 (match-beginning 1))))
10734 (js2-insert-catch-skel try-pos))
10735 (t
10736 ;; Otherwise try to do something smarter.
10737 (insert "{")
10738 (unless (or (not (looking-at "\\s-*$"))
10739 (save-excursion
10740 (skip-chars-forward " \t\r\n")
10741 (and (looking-at "}")
10742 (js2-error-at-point)))
10743 (js2-mode-inside-comment-or-string))
10744 (undo-boundary)
10745 ;; absolutely mystifying bug: when inserting the next "\n",
10746 ;; the buffer-undo-list is given two new entries: the inserted range,
10747 ;; and the incorrect position of the point. It's recorded incorrectly
10748 ;; as being before the opening "{", not after it. But it's recorded
10749 ;; as the correct value if you're debugging `js2-mode-match-curly'
10750 ;; in edebug. I have no idea why it's doing this, but incrementing
10751 ;; the inserted position fixes the problem, so that the undo takes us
10752 ;; back to just after the user-inserted "{".
10753 (insert "\n")
10754 (ignore-errors
10755 (incf (cadr buffer-undo-list)))
10756 (js2-indent-line)
10757 (save-excursion
10758 (insert "\n}")
10759 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10760 (js2-indent-line))))))))
10761
10762 (defun js2-insert-catch-skel (try-pos)
10763 "Complete a try/catch block after inserting a { following a try keyword.
10764 Rationale is that a try always needs a catch or a finally, and the catch is
10765 the more likely of the two.
10766
10767 TRY-POS is the buffer position of the try keyword. The open-curly should
10768 already have been inserted."
10769 (insert "{")
10770 (let ((try-col (save-excursion
10771 (goto-char try-pos)
10772 (current-column))))
10773 (insert "\n")
10774 (undo-boundary)
10775 (js2-indent-line) ;; indent the blank line where cursor will end up
10776 (save-excursion
10777 (insert "\n")
10778 (indent-to try-col)
10779 (insert "} catch (x) {\n\n")
10780 (indent-to try-col)
10781 (insert "}"))))
10782
10783 (defun js2-mode-highlight-magic-parens ()
10784 "Re-highlight magic parens after parsing nukes the 'face prop."
10785 (let ((beg (point-min))
10786 end)
10787 (while (setq beg (next-single-property-change beg 'js2-magic))
10788 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10789 (if (get-text-property beg 'js2-magic)
10790 (js2-with-unmodifying-text-property-changes
10791 (put-text-property beg (or end (1+ beg))
10792 'face 'js2-magic-paren-face))))))
10793
10794 (defun js2-mode-mundanify-parens ()
10795 "Clear all magic parens and brackets."
10796 (let ((beg (point-min))
10797 end)
10798 (while (setq beg (next-single-property-change beg 'js2-magic))
10799 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10800 (remove-text-properties beg (or end (1+ beg))
10801 '(js2-magic face)))))
10802
10803 (defsubst js2-match-quote (quote-string)
10804 (let ((start-quote (js2-mode-inside-string)))
10805 (cond
10806 ;; inside a comment - don't do quote-matching, since we can't
10807 ;; reliably figure out if we're in a string inside the comment
10808 ((js2-comment-at-point)
10809 (insert quote-string))
10810 ((not start-quote)
10811 ;; not in string => insert matched quotes
10812 (insert quote-string)
10813 ;; exception: if we're just before a word, don't double it.
10814 (unless (looking-at "[^ \t\r\n]")
10815 (save-excursion
10816 (insert quote-string))))
10817 ((looking-at quote-string)
10818 (if (looking-back "[^\\]\\\\")
10819 (insert quote-string)
10820 (forward-char 1)))
10821 ((and js2-mode-escape-quotes
10822 (save-excursion
10823 (save-match-data
10824 (re-search-forward quote-string (point-at-eol) t))))
10825 ;; inside terminated string, escape quote (unless already escaped)
10826 (insert (if (looking-back "[^\\]\\\\")
10827 quote-string
10828 (concat "\\" quote-string))))
10829 (t
10830 (insert quote-string))))) ; else terminate the string
10831
10832 (defun js2-mode-match-single-quote ()
10833 "Insert matching single-quote."
10834 (interactive)
10835 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10836 ;; don't match inside comments, since apostrophe is more common
10837 (if (nth 4 parse-status)
10838 (insert "'")
10839 (js2-match-quote "'"))))
10840
10841 (defun js2-mode-match-double-quote ()
10842 "Insert matching double-quote."
10843 (interactive)
10844 (js2-match-quote "\""))
10845
10846 ;; Eclipse works as follows:
10847 ;; * type an open-paren and it auto-inserts close-paren
10848 ;; - auto-inserted paren gets a green bracket
10849 ;; - green bracket means typing close-paren there will skip it
10850 ;; * if you insert any text on a different line, it turns off
10851 (defun js2-mode-magic-close-paren ()
10852 "Skip over close-paren rather than inserting, where appropriate."
10853 (interactive)
10854 (let* ((here (point))
10855 (parse-status (parse-partial-sexp (point-min) here))
10856 (open-pos (nth 1 parse-status))
10857 (close last-input-event)
10858 (open (cond
10859 ((eq close ?\))
10860 ?\()
10861 ((eq close ?\])
10862 ?\[)
10863 ((eq close ?})
10864 ?{)
10865 (t nil))))
10866 (if (and (eq (char-after) close)
10867 (eq open (char-after open-pos))
10868 (js2-same-line open-pos)
10869 (get-text-property here 'js2-magic))
10870 (progn
10871 (remove-text-properties here (1+ here) '(js2-magic face))
10872 (forward-char 1))
10873 (insert-char close 1))
10874 (blink-matching-open)))
10875
10876 (defun js2-mode-wait-for-parse (callback)
10877 "Invoke CALLBACK when parsing is finished.
10878 If parsing is already finished, calls CALLBACK immediately."
10879 (if (not js2-mode-buffer-dirty-p)
10880 (funcall callback)
10881 (push callback js2-mode-pending-parse-callbacks)
10882 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10883
10884 (defun js2-mode-parse-finished ()
10885 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10886 ;; We can't let errors propagate up, since it prevents the
10887 ;; `js2-parse' method from completing normally and returning
10888 ;; the ast, which makes things mysteriously not work right.
10889 (unwind-protect
10890 (dolist (cb js2-mode-pending-parse-callbacks)
10891 (condition-case err
10892 (funcall cb)
10893 (error (message "%s" err))))
10894 (setq js2-mode-pending-parse-callbacks nil)))
10895
10896 (defun js2-mode-flag-region (from to flag)
10897 "Hide or show text from FROM to TO, according to FLAG.
10898 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10899 Returns the created overlay if FLAG is non-nil."
10900 (remove-overlays from to 'invisible 'js2-outline)
10901 (when flag
10902 (let ((o (make-overlay from to)))
10903 (overlay-put o 'invisible 'js2-outline)
10904 (overlay-put o 'isearch-open-invisible
10905 'js2-isearch-open-invisible)
10906 o)))
10907
10908 ;; Function to be set as an outline-isearch-open-invisible' property
10909 ;; to the overlay that makes the outline invisible (see
10910 ;; `js2-mode-flag-region').
10911 (defun js2-isearch-open-invisible (overlay)
10912 ;; We rely on the fact that isearch places point on the matched text.
10913 (js2-mode-show-element))
10914
10915 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10916 "Return cons cell of bounds of folding overlay at POS.
10917 Returns nil if not found."
10918 (let ((overlays (overlays-at (or pos (point))))
10919 o)
10920 (while (and overlays
10921 (not o))
10922 (if (overlay-get (car overlays) 'invisible)
10923 (setq o (car overlays))
10924 (setq overlays (cdr overlays))))
10925 (if o
10926 (cons (overlay-start o) (overlay-end o)))))
10927
10928 (defun js2-mode-function-at-point (&optional pos)
10929 "Return the innermost function node enclosing current point.
10930 Returns nil if point is not in a function."
10931 (let ((node (js2-node-at-point pos)))
10932 (while (and node (not (js2-function-node-p node)))
10933 (setq node (js2-node-parent node)))
10934 (if (js2-function-node-p node)
10935 node)))
10936
10937 (defun js2-mode-toggle-element ()
10938 "Hide or show the foldable element at the point."
10939 (interactive)
10940 (let (comment fn pos)
10941 (save-excursion
10942 (save-match-data
10943 (cond
10944 ;; /* ... */ comment?
10945 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10946 (if (js2-mode-invisible-overlay-bounds
10947 (setq pos (+ 3 (js2-node-abs-pos comment))))
10948 (progn
10949 (goto-char pos)
10950 (js2-mode-show-element))
10951 (js2-mode-hide-element)))
10952 ;; //-comment?
10953 ((save-excursion
10954 (back-to-indentation)
10955 (looking-at js2-mode-//-comment-re))
10956 (js2-mode-toggle-//-comment))
10957 ;; function?
10958 ((setq fn (js2-mode-function-at-point))
10959 (setq pos (and (js2-function-node-body fn)
10960 (js2-node-abs-pos (js2-function-node-body fn))))
10961 (goto-char (1+ pos))
10962 (if (js2-mode-invisible-overlay-bounds)
10963 (js2-mode-show-element)
10964 (js2-mode-hide-element)))
10965 (t
10966 (message "Nothing at point to hide or show")))))))
10967
10968 (defun js2-mode-hide-element ()
10969 "Fold/hide contents of a block, showing ellipses.
10970 Show the hidden text with \\[js2-mode-show-element]."
10971 (interactive)
10972 (if js2-mode-buffer-dirty-p
10973 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10974 (let (node body beg end)
10975 (cond
10976 ((js2-mode-invisible-overlay-bounds)
10977 (message "already hidden"))
10978 (t
10979 (setq node (js2-node-at-point))
10980 (cond
10981 ((js2-block-comment-p node)
10982 (js2-mode-hide-comment node))
10983 (t
10984 (while (and node (not (js2-function-node-p node)))
10985 (setq node (js2-node-parent node)))
10986 (if (and node
10987 (setq body (js2-function-node-body node)))
10988 (progn
10989 (setq beg (js2-node-abs-pos body)
10990 end (+ beg (js2-node-len body)))
10991 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10992 (message "No collapsable element found at point"))))))))
10993
10994 (defun js2-mode-show-element ()
10995 "Show the hidden element at current point."
10996 (interactive)
10997 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10998 (if bounds
10999 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11000 (message "Nothing to un-hide"))))
11001
11002 (defun js2-mode-show-all ()
11003 "Show all of the text in the buffer."
11004 (interactive)
11005 (js2-mode-flag-region (point-min) (point-max) nil))
11006
11007 (defun js2-mode-toggle-hide-functions ()
11008 (interactive)
11009 (if js2-mode-functions-hidden
11010 (js2-mode-show-functions)
11011 (js2-mode-hide-functions)))
11012
11013 (defun js2-mode-hide-functions ()
11014 "Hides all non-nested function bodies in the buffer.
11015 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11016 to open an individual entry."
11017 (interactive)
11018 (if js2-mode-buffer-dirty-p
11019 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11020 (if (null js2-mode-ast)
11021 (message "Oops - parsing failed")
11022 (setq js2-mode-functions-hidden t)
11023 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11024
11025 (defun js2-mode-function-hider (n endp)
11026 (when (not endp)
11027 (let ((tt (js2-node-type n))
11028 body beg end)
11029 (cond
11030 ((and (= tt js2-FUNCTION)
11031 (setq body (js2-function-node-body n)))
11032 (setq beg (js2-node-abs-pos body)
11033 end (+ beg (js2-node-len body)))
11034 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11035 nil) ; don't process children of function
11036 (t
11037 t))))) ; keep processing other AST nodes
11038
11039 (defun js2-mode-show-functions ()
11040 "Un-hide any folded function bodies in the buffer."
11041 (interactive)
11042 (setq js2-mode-functions-hidden nil)
11043 (save-excursion
11044 (goto-char (point-min))
11045 (while (/= (goto-char (next-overlay-change (point)))
11046 (point-max))
11047 (dolist (o (overlays-at (point)))
11048 (when (and (overlay-get o 'invisible)
11049 (not (overlay-get o 'comment)))
11050 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11051
11052 (defun js2-mode-hide-comment (n)
11053 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11054 3 ; /**
11055 2)) ; /*
11056 (beg (+ (js2-node-abs-pos n) head))
11057 (end (- (+ beg (js2-node-len n)) head 2))
11058 (o (js2-mode-flag-region beg end 'hide)))
11059 (overlay-put o 'comment t)))
11060
11061 (defun js2-mode-toggle-hide-comments ()
11062 "Folds all block comments in the buffer.
11063 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11064 to open an individual entry."
11065 (interactive)
11066 (if js2-mode-comments-hidden
11067 (js2-mode-show-comments)
11068 (js2-mode-hide-comments)))
11069
11070 (defun js2-mode-hide-comments ()
11071 (interactive)
11072 (if js2-mode-buffer-dirty-p
11073 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11074 (if (null js2-mode-ast)
11075 (message "Oops - parsing failed")
11076 (setq js2-mode-comments-hidden t)
11077 (dolist (n (js2-ast-root-comments js2-mode-ast))
11078 (let ((format (js2-comment-node-format n)))
11079 (when (js2-block-comment-p n)
11080 (js2-mode-hide-comment n))))
11081 (js2-mode-hide-//-comments)))
11082
11083 (defsubst js2-mode-extend-//-comment (direction)
11084 "Find start or end of a block of similar //-comment lines.
11085 DIRECTION is -1 to look back, 1 to look forward.
11086 INDENT is the indentation level to match.
11087 Returns the end-of-line position of the furthest adjacent
11088 //-comment line with the same indentation as the current line.
11089 If there is no such matching line, returns current end of line."
11090 (let ((pos (point-at-eol))
11091 (indent (current-indentation)))
11092 (save-excursion
11093 (save-match-data
11094 (while (and (zerop (forward-line direction))
11095 (looking-at js2-mode-//-comment-re)
11096 (eq indent (length (match-string 1))))
11097 (setq pos (point-at-eol)))
11098 pos))))
11099
11100 (defun js2-mode-hide-//-comments ()
11101 "Fold adjacent 1-line comments, showing only snippet of first one."
11102 (let (beg end)
11103 (save-excursion
11104 (save-match-data
11105 (goto-char (point-min))
11106 (while (re-search-forward js2-mode-//-comment-re nil t)
11107 (setq beg (point)
11108 end (js2-mode-extend-//-comment 1))
11109 (unless (eq beg end)
11110 (overlay-put (js2-mode-flag-region beg end 'hide)
11111 'comment t))
11112 (goto-char end)
11113 (forward-char 1))))))
11114
11115 (defun js2-mode-toggle-//-comment ()
11116 "Fold or un-fold any multi-line //-comment at point.
11117 Caller should have determined that this line starts with a //-comment."
11118 (let* ((beg (point-at-eol))
11119 (end beg))
11120 (save-excursion
11121 (goto-char end)
11122 (if (js2-mode-invisible-overlay-bounds)
11123 (js2-mode-show-element)
11124 ;; else hide the comment
11125 (setq beg (js2-mode-extend-//-comment -1)
11126 end (js2-mode-extend-//-comment 1))
11127 (unless (eq beg end)
11128 (overlay-put (js2-mode-flag-region beg end 'hide)
11129 'comment t))))))
11130
11131 (defun js2-mode-show-comments ()
11132 "Un-hide any hidden comments, leaving other hidden elements alone."
11133 (interactive)
11134 (setq js2-mode-comments-hidden nil)
11135 (save-excursion
11136 (goto-char (point-min))
11137 (while (/= (goto-char (next-overlay-change (point)))
11138 (point-max))
11139 (dolist (o (overlays-at (point)))
11140 (when (overlay-get o 'comment)
11141 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11142
11143 (defun js2-mode-display-warnings-and-errors ()
11144 "Turn on display of warnings and errors."
11145 (interactive)
11146 (setq js2-mode-show-parse-errors t
11147 js2-mode-show-strict-warnings t)
11148 (js2-reparse 'force))
11149
11150 (defun js2-mode-hide-warnings-and-errors ()
11151 "Turn off display of warnings and errors."
11152 (interactive)
11153 (setq js2-mode-show-parse-errors nil
11154 js2-mode-show-strict-warnings nil)
11155 (js2-reparse 'force))
11156
11157 (defun js2-mode-toggle-warnings-and-errors ()
11158 "Toggle the display of warnings and errors.
11159 Some users don't like having warnings/errors reported while they type."
11160 (interactive)
11161 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11162 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11163 (if (interactive-p)
11164 (message "warnings and errors %s"
11165 (if js2-mode-show-parse-errors
11166 "enabled"
11167 "disabled")))
11168 (js2-reparse 'force))
11169
11170 (defun js2-mode-customize ()
11171 (interactive)
11172 (customize-group 'js2-mode))
11173
11174 (defun js2-mode-forward-sexp (&optional arg)
11175 "Move forward across one statement or balanced expression.
11176 With ARG, do it that many times. Negative arg -N means
11177 move backward across N balanced expressions."
11178 (interactive "p")
11179 (setq arg (or arg 1))
11180 (if js2-mode-buffer-dirty-p
11181 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11182 (let (node end (start (point)))
11183 (cond
11184 ;; backward-sexp
11185 ;; could probably make this better for some cases:
11186 ;; - if in statement block (e.g. function body), go to parent
11187 ;; - infix exprs like (foo in bar) - maybe go to beginning
11188 ;; of infix expr if in the right-side expression?
11189 ((and arg (minusp arg))
11190 (dotimes (i (- arg))
11191 (js2-backward-sws)
11192 (forward-char -1) ; enter the node we backed up to
11193 (setq node (js2-node-at-point (point) t))
11194 (goto-char (if node
11195 (js2-node-abs-pos node)
11196 (point-min)))))
11197 (t
11198 ;; forward-sexp
11199 (js2-forward-sws)
11200 (dotimes (i arg)
11201 (js2-forward-sws)
11202 (setq node (js2-node-at-point (point) t)
11203 end (if node (+ (js2-node-abs-pos node)
11204 (js2-node-len node))))
11205 (goto-char (or end (point-max))))))))
11206
11207 (defun js2-next-error (&optional arg reset)
11208 "Move to next parse error.
11209 Typically invoked via \\[next-error].
11210 ARG is the number of errors, forward or backward, to move.
11211 RESET means start over from the beginning."
11212 (interactive "p")
11213 (if (or (null js2-mode-ast)
11214 (and (null (js2-ast-root-errors js2-mode-ast))
11215 (null (js2-ast-root-warnings js2-mode-ast))))
11216 (message "No errors")
11217 (when reset
11218 (goto-char (point-min)))
11219 (let* ((errs (copy-sequence
11220 (append (js2-ast-root-errors js2-mode-ast)
11221 (js2-ast-root-warnings js2-mode-ast))))
11222 (continue t)
11223 (start (point))
11224 (count (or arg 1))
11225 (backward (minusp count))
11226 (sorter (if backward '> '<))
11227 (stopper (if backward '< '>))
11228 (count (abs count))
11229 all-errs
11230 err)
11231 ;; sort by start position
11232 (setq errs (sort errs (lambda (e1 e2)
11233 (funcall sorter (second e1) (second e2))))
11234 all-errs errs)
11235 ;; find nth error with pos > start
11236 (while (and errs continue)
11237 (when (funcall stopper (cadar errs) start)
11238 (setq err (car errs))
11239 (if (zerop (decf count))
11240 (setq continue nil)))
11241 (setq errs (cdr errs)))
11242 (if err
11243 (goto-char (second err))
11244 ;; wrap around to first error
11245 (goto-char (second (car all-errs)))
11246 ;; if we were already on it, echo msg again
11247 (if (= (point) start)
11248 (js2-echo-error (point) (point)))))))
11249
11250 (defun js2-down-mouse-3 ()
11251 "Make right-click move the point to the click location.
11252 This makes right-click context menu operations a bit more intuitive.
11253 The point will not move if the region is active, however, to avoid
11254 destroying the region selection."
11255 (interactive)
11256 (when (and js2-move-point-on-right-click
11257 (not mark-active))
11258 (let ((e last-input-event))
11259 (ignore-errors
11260 (goto-char (cadadr e))))))
11261
11262 (defun js2-mode-create-imenu-index ()
11263 "Return an alist for `imenu--index-alist'."
11264 ;; This is built up in `js2-parse-record-imenu' during parsing.
11265 (when js2-mode-ast
11266 ;; if we have an ast but no recorder, they're requesting a rescan
11267 (unless js2-imenu-recorder
11268 (js2-reparse 'force))
11269 (prog1
11270 (js2-build-imenu-index)
11271 (setq js2-imenu-recorder nil
11272 js2-imenu-function-map nil))))
11273
11274 (defun js2-mode-find-tag ()
11275 "Replacement for `find-tag-default'.
11276 `find-tag-default' returns a ridiculous answer inside comments."
11277 (let (beg end)
11278 (js2-with-underscore-as-word-syntax
11279 (save-excursion
11280 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11281 (looking-back "[A-Za-z0-9_$]"))
11282 (setq beg (progn (forward-word -1) (point))
11283 end (progn (forward-word 1) (point)))
11284 (setq beg (progn (forward-word 1) (point))
11285 end (progn (forward-word -1) (point))))
11286 (replace-regexp-in-string
11287 "[\"']" ""
11288 (buffer-substring-no-properties beg end))))))
11289
11290 (defun js2-mode-forward-sibling ()
11291 "Move to the end of the sibling following point in parent.
11292 Returns non-nil if successful, or nil if there was no following sibling."
11293 (let* ((node (js2-node-at-point))
11294 (parent (js2-mode-find-enclosing-fn node))
11295 sib)
11296 (when (setq sib (js2-node-find-child-after (point) parent))
11297 (goto-char (+ (js2-node-abs-pos sib)
11298 (js2-node-len sib))))))
11299
11300 (defun js2-mode-backward-sibling ()
11301 "Move to the beginning of the sibling node preceding point in parent.
11302 Parent is defined as the enclosing script or function."
11303 (let* ((node (js2-node-at-point))
11304 (parent (js2-mode-find-enclosing-fn node))
11305 sib)
11306 (when (setq sib (js2-node-find-child-before (point) parent))
11307 (goto-char (js2-node-abs-pos sib)))))
11308
11309 (defun js2-beginning-of-defun ()
11310 "Go to line on which current function starts, and return non-nil.
11311 If we're not in a function, go to beginning of previous script-level element."
11312 (interactive)
11313 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11314 pos sib)
11315 (cond
11316 ((and (js2-function-node-p parent)
11317 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11318 (goto-char pos))
11319 (t
11320 (js2-mode-backward-sibling)))))
11321
11322 (defun js2-end-of-defun ()
11323 "Go to the char after the last position of the current function.
11324 If we're not in a function, skips over the next script-level element."
11325 (interactive)
11326 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11327 (if (not (js2-function-node-p parent))
11328 ;; punt: skip over next script-level element beyond point
11329 (js2-mode-forward-sibling)
11330 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11331 (js2-node-len parent)))))))
11332
11333 (defun js2-mark-defun (&optional allow-extend)
11334 "Put mark at end of this function, point at beginning.
11335 The function marked is the one that contains point.
11336
11337 Interactively, if this command is repeated,
11338 or (in Transient Mark mode) if the mark is active,
11339 it marks the next defun after the ones already marked."
11340 (interactive "p")
11341 (let (extended)
11342 (when (and allow-extend
11343 (or (and (eq last-command this-command) (mark t))
11344 (and transient-mark-mode mark-active)))
11345 (let ((sib (save-excursion
11346 (goto-char (mark))
11347 (if (js2-mode-forward-sibling)
11348 (point))))
11349 node)
11350 (if sib
11351 (progn
11352 (set-mark sib)
11353 (setq extended t))
11354 ;; no more siblings - try extending to enclosing node
11355 (goto-char (mark t)))))
11356 (when (not extended)
11357 (let ((node (js2-node-at-point (point) t)) ; skip comments
11358 ast fn stmt parent beg end)
11359 (when (js2-ast-root-p node)
11360 (setq ast node
11361 node (or (js2-node-find-child-after (point) node)
11362 (js2-node-find-child-before (point) node))))
11363 ;; only mark whole buffer if we can't find any children
11364 (if (null node)
11365 (setq node ast))
11366 (if (js2-function-node-p node)
11367 (setq parent node)
11368 (setq fn (js2-mode-find-enclosing-fn node)
11369 stmt (if (or (null fn)
11370 (js2-ast-root-p fn))
11371 (js2-mode-find-first-stmt node))
11372 parent (or stmt fn)))
11373 (setq beg (js2-node-abs-pos parent)
11374 end (+ beg (js2-node-len parent)))
11375 (push-mark beg)
11376 (goto-char end)
11377 (exchange-point-and-mark)))))
11378
11379 (defun js2-narrow-to-defun ()
11380 "Narrow to the function enclosing point."
11381 (interactive)
11382 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11383 (fn (if (js2-script-node-p node)
11384 node
11385 (js2-mode-find-enclosing-fn node)))
11386 (beg (js2-node-abs-pos fn)))
11387 (unless (js2-ast-root-p fn)
11388 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11389
11390 (provide 'js2-mode)
11391
11392 ;;; js2-mode.el ends here