]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Reverted commits 312, 313, and 315.
[gnu-emacs-elpa] / packages / js2-mode / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Version: 20090814
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 nil, zero or negative means none.
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" nil)
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 (defcustom js2-bounce-indent-p nil
205 "Non-nil to have indent-line function choose among alternatives.
206 If nil, the indent-line function will indent to a predetermined column
207 based on heuristic guessing. If non-nil, then if the current line is
208 already indented to that predetermined column, indenting will choose
209 another likely column and indent to that spot. Repeated invocation of
210 the indent-line function will cycle among the computed alternatives.
211 See the function `js2-bounce-indent' for details."
212 :type 'boolean
213 :group 'js2-mode)
214
215 (defcustom js2-idle-timer-delay 0.2
216 "Delay in secs before re-parsing after user makes changes.
217 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
218 :type 'number
219 :group 'js2-mode)
220 (make-variable-buffer-local 'js2-idle-timer-delay)
221
222 (defcustom js2-dynamic-idle-timer-adjust 0
223 "Positive to adjust `js2-idle-timer-delay' based on file size.
224 The idea is that for short files, parsing is faster so we can be
225 more responsive to user edits without interfering with editing.
226 The buffer length in characters (typically bytes) is divided by
227 this value and used to multiply `js2-idle-timer-delay' for the
228 buffer. For example, a 21k file and 10k adjust yields 21k/10k
229 == 2, so js2-idle-timer-delay is multiplied by 2.
230 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
231 `js2-idle-timer-delay' is not dependent on the file size."
232 :type 'number
233 :group 'js2-mode)
234
235 (defcustom js2-mode-escape-quotes t
236 "Non-nil to disable automatic quote-escaping inside strings."
237 :type 'boolean
238 :group 'js2-mode)
239
240 (defcustom js2-mode-squeeze-spaces t
241 "Non-nil to normalize whitespace when filling in comments.
242 Multiple runs of spaces are converted to a single space."
243 :type 'boolean
244 :group 'js2-mode)
245
246 (defcustom js2-mode-show-parse-errors t
247 "True to highlight parse errors."
248 :type 'boolean
249 :group 'js2-mode)
250
251 (defcustom js2-mode-show-strict-warnings t
252 "Non-nil to emit Ecma strict-mode warnings.
253 Some of the warnings can be individually disabled by other flags,
254 even if this flag is non-nil."
255 :type 'boolean
256 :group 'js2-mode)
257
258 (defcustom js2-strict-trailing-comma-warning t
259 "Non-nil to warn about trailing commas in array literals.
260 Ecma-262 forbids them, but many browsers permit them. IE is the
261 big exception, and can produce bugs if you have trailing commas."
262 :type 'boolean
263 :group 'js2-mode)
264
265 (defcustom js2-strict-missing-semi-warning t
266 "Non-nil to warn about semicolon auto-insertion after statement.
267 Technically this is legal per Ecma-262, but some style guides disallow
268 depending on it."
269 :type 'boolean
270 :group 'js2-mode)
271
272 (defcustom js2-missing-semi-one-line-override nil
273 "Non-nil to permit missing semicolons in one-line functions.
274 In one-liner functions such as `function identity(x) {return x}'
275 people often omit the semicolon for a cleaner look. If you are
276 such a person, you can suppress the missing-semicolon warning
277 by setting this variable to t."
278 :type 'boolean
279 :group 'js2-mode)
280
281 (defcustom js2-strict-inconsistent-return-warning t
282 "Non-nil to warn about mixing returns with value-returns.
283 It's perfectly legal to have a `return' and a `return foo' in the
284 same function, but it's often an indicator of a bug, and it also
285 interferes with type inference (in systems that support it.)"
286 :type 'boolean
287 :group 'js2-mode)
288
289 (defcustom js2-strict-cond-assign-warning t
290 "Non-nil to warn about expressions like if (a = b).
291 This often should have been '==' instead of '='. If the warning
292 is enabled, you can suppress it on a per-expression basis by
293 parenthesizing the expression, e.g. if ((a = b)) ..."
294 :type 'boolean
295 :group 'js2-mode)
296
297 (defcustom js2-strict-cond-assign-warning t
298 "Non-nil to warn about expressions like if (a = b).
299 This often should have been '==' instead of '='. If the warning
300 is enabled, you can suppress it on a per-expression basis by
301 parenthesizing the expression, e.g. if ((a = b)) ..."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-strict-var-redeclaration-warning t
306 "Non-nil to warn about redeclaring variables in a script or function."
307 :type 'boolean
308 :group 'js2-mode)
309
310 (defcustom js2-strict-var-hides-function-arg-warning t
311 "Non-nil to warn about a var decl hiding a function argument."
312 :type 'boolean
313 :group 'js2-mode)
314
315 (defcustom js2-skip-preprocessor-directives nil
316 "Non-nil to treat lines beginning with # as comments.
317 Useful for viewing Mozilla JavaScript source code."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-language-version 180
322 "Configures what JavaScript language version to recognize.
323 Currently versions 150, 160, 170 and 180 are supported, corresponding
324 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
325 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
326 and 1.8 adds function closures."
327 :type 'integer
328 :group 'js2-mode)
329
330 (defcustom js2-allow-keywords-as-property-names t
331 "If non-nil, you can use JavaScript keywords as object property names.
332 Examples:
333
334 var foo = {int: 5, while: 6, continue: 7};
335 foo.return = 8;
336
337 Ecma-262 forbids this syntax, but many browsers support it."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-instanceof-has-side-effects nil
342 "If non-nil, treats the instanceof operator as having side effects.
343 This is useful for xulrunner apps."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-cleanup-whitespace nil
348 "Non-nil to invoke `delete-trailing-whitespace' before saves."
349 :type 'boolean
350 :group 'js2-mode)
351
352 (defcustom js2-move-point-on-right-click t
353 "Non-nil to move insertion point when you right-click.
354 This makes right-click context menu behavior a bit more intuitive,
355 since menu operations generally apply to the point. The exception
356 is if there is a region selection, in which case the point does -not-
357 move, so cut/copy/paste can work properly.
358
359 Note that IntelliJ moves the point, and Eclipse leaves it alone,
360 so this behavior is customizable."
361 :group 'js2-mode
362 :type 'boolean)
363
364 (defcustom js2-allow-rhino-new-expr-initializer t
365 "Non-nil to support a Rhino's experimental syntactic construct.
366
367 Rhino supports the ability to follow a `new' expression with an object
368 literal, which is used to set additional properties on the new object
369 after calling its constructor. Syntax:
370
371 new <expr> [ ( arglist ) ] [initializer]
372
373 Hence, this expression:
374
375 new Object {a: 1, b: 2}
376
377 results in an Object with properties a=1 and b=2. This syntax is
378 apparently not configurable in Rhino - it's currently always enabled,
379 as of Rhino version 1.7R2."
380 :type 'boolean
381 :group 'js2-mode)
382
383 (defcustom js2-allow-member-expr-as-function-name nil
384 "Non-nil to support experimental Rhino syntax for function names.
385
386 Rhino supports an experimental syntax configured via the Rhino Context
387 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
388
389 function <member-expr> ( [ arg-list ] ) { <body> }
390
391 Where member-expr is a non-parenthesized 'member expression', which
392 is anything at the grammar level of a new-expression or lower, meaning
393 any expression that does not involve infix or unary operators.
394
395 When <member-expr> is not a simple identifier, then it is syntactic
396 sugar for assigning the anonymous function to the <member-expr>. Hence,
397 this code:
398
399 function a.b().c[2] (x, y) { ... }
400
401 is rewritten as:
402
403 a.b().c[2] = function(x, y) {...}
404
405 which doesn't seem particularly useful, but Rhino permits it."
406 :type 'boolean
407 :group 'js2-mode)
408
409 (defvar js2-mode-version 20090727
410 "Release number for `js2-mode'.")
411
412 ;; scanner variables
413
414 (defmacro js2-deflocal (name value &optional comment)
415 "Define a buffer-local variable NAME with VALUE and COMMENT."
416 `(progn
417 (defvar ,name ,value ,comment)
418 (make-variable-buffer-local ',name)))
419
420 ;; We record the start and end position of each token.
421 (js2-deflocal js2-token-beg 1)
422 (js2-deflocal js2-token-end -1)
423
424 (defvar js2-EOF_CHAR -1
425 "Represents end of stream. Distinct from js2-EOF token type.")
426
427 ;; I originally used symbols to represent tokens, but Rhino uses
428 ;; ints and then sets various flag bits in them, so ints it is.
429 ;; The upshot is that we need a `js2-' prefix in front of each name.
430 (defvar js2-ERROR -1)
431 (defvar js2-EOF 0)
432 (defvar js2-EOL 1)
433 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
434 (defvar js2-LEAVEWITH 3)
435 (defvar js2-RETURN 4)
436 (defvar js2-GOTO 5)
437 (defvar js2-IFEQ 6)
438 (defvar js2-IFNE 7)
439 (defvar js2-SETNAME 8)
440 (defvar js2-BITOR 9)
441 (defvar js2-BITXOR 10)
442 (defvar js2-BITAND 11)
443 (defvar js2-EQ 12)
444 (defvar js2-NE 13)
445 (defvar js2-LT 14)
446 (defvar js2-LE 15)
447 (defvar js2-GT 16)
448 (defvar js2-GE 17)
449 (defvar js2-LSH 18)
450 (defvar js2-RSH 19)
451 (defvar js2-URSH 20)
452 (defvar js2-ADD 21) ; infix plus
453 (defvar js2-SUB 22) ; infix minus
454 (defvar js2-MUL 23)
455 (defvar js2-DIV 24)
456 (defvar js2-MOD 25)
457 (defvar js2-NOT 26)
458 (defvar js2-BITNOT 27)
459 (defvar js2-POS 28) ; unary plus
460 (defvar js2-NEG 29) ; unary minus
461 (defvar js2-NEW 30)
462 (defvar js2-DELPROP 31)
463 (defvar js2-TYPEOF 32)
464 (defvar js2-GETPROP 33)
465 (defvar js2-GETPROPNOWARN 34)
466 (defvar js2-SETPROP 35)
467 (defvar js2-GETELEM 36)
468 (defvar js2-SETELEM 37)
469 (defvar js2-CALL 38)
470 (defvar js2-NAME 39) ; an identifier
471 (defvar js2-NUMBER 40)
472 (defvar js2-STRING 41)
473 (defvar js2-NULL 42)
474 (defvar js2-THIS 43)
475 (defvar js2-FALSE 44)
476 (defvar js2-TRUE 45)
477 (defvar js2-SHEQ 46) ; shallow equality (===)
478 (defvar js2-SHNE 47) ; shallow inequality (!==)
479 (defvar js2-REGEXP 48)
480 (defvar js2-BINDNAME 49)
481 (defvar js2-THROW 50)
482 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
483 (defvar js2-IN 52)
484 (defvar js2-INSTANCEOF 53)
485 (defvar js2-LOCAL_LOAD 54)
486 (defvar js2-GETVAR 55)
487 (defvar js2-SETVAR 56)
488 (defvar js2-CATCH_SCOPE 57)
489 (defvar js2-ENUM_INIT_KEYS 58)
490 (defvar js2-ENUM_INIT_VALUES 59)
491 (defvar js2-ENUM_INIT_ARRAY 60)
492 (defvar js2-ENUM_NEXT 61)
493 (defvar js2-ENUM_ID 62)
494 (defvar js2-THISFN 63)
495 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
496 (defvar js2-ARRAYLIT 65) ; array literal
497 (defvar js2-OBJECTLIT 66) ; object literal
498 (defvar js2-GET_REF 67) ; *reference
499 (defvar js2-SET_REF 68) ; *reference = something
500 (defvar js2-DEL_REF 69) ; delete reference
501 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
502 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
503 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
504
505 ;; XML support
506 (defvar js2-DEFAULTNAMESPACE 73)
507 (defvar js2-ESCXMLATTR 74)
508 (defvar js2-ESCXMLTEXT 75)
509 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
510 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
511 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
512 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
513
514 (defvar js2-first-bytecode js2-ENTERWITH)
515 (defvar js2-last-bytecode js2-REF_NS_NAME)
516
517 (defvar js2-TRY 80)
518 (defvar js2-SEMI 81) ; semicolon
519 (defvar js2-LB 82) ; left and right brackets
520 (defvar js2-RB 83)
521 (defvar js2-LC 84) ; left and right curly-braces
522 (defvar js2-RC 85)
523 (defvar js2-LP 86) ; left and right parens
524 (defvar js2-RP 87)
525 (defvar js2-COMMA 88) ; comma operator
526
527 (defvar js2-ASSIGN 89) ; simple assignment (=)
528 (defvar js2-ASSIGN_BITOR 90) ; |=
529 (defvar js2-ASSIGN_BITXOR 91) ; ^=
530 (defvar js2-ASSIGN_BITAND 92) ; &=
531 (defvar js2-ASSIGN_LSH 93) ; <<=
532 (defvar js2-ASSIGN_RSH 94) ; >>=
533 (defvar js2-ASSIGN_URSH 95) ; >>>=
534 (defvar js2-ASSIGN_ADD 96) ; +=
535 (defvar js2-ASSIGN_SUB 97) ; -=
536 (defvar js2-ASSIGN_MUL 98) ; *=
537 (defvar js2-ASSIGN_DIV 99) ; /=
538 (defvar js2-ASSIGN_MOD 100) ; %=
539
540 (defvar js2-first-assign js2-ASSIGN)
541 (defvar js2-last-assign js2-ASSIGN_MOD)
542
543 (defvar js2-HOOK 101) ; conditional (?:)
544 (defvar js2-COLON 102)
545 (defvar js2-OR 103) ; logical or (||)
546 (defvar js2-AND 104) ; logical and (&&)
547 (defvar js2-INC 105) ; increment/decrement (++ --)
548 (defvar js2-DEC 106)
549 (defvar js2-DOT 107) ; member operator (.)
550 (defvar js2-FUNCTION 108) ; function keyword
551 (defvar js2-EXPORT 109) ; export keyword
552 (defvar js2-IMPORT 110) ; import keyword
553 (defvar js2-IF 111) ; if keyword
554 (defvar js2-ELSE 112) ; else keyword
555 (defvar js2-SWITCH 113) ; switch keyword
556 (defvar js2-CASE 114) ; case keyword
557 (defvar js2-DEFAULT 115) ; default keyword
558 (defvar js2-WHILE 116) ; while keyword
559 (defvar js2-DO 117) ; do keyword
560 (defvar js2-FOR 118) ; for keyword
561 (defvar js2-BREAK 119) ; break keyword
562 (defvar js2-CONTINUE 120) ; continue keyword
563 (defvar js2-VAR 121) ; var keyword
564 (defvar js2-WITH 122) ; with keyword
565 (defvar js2-CATCH 123) ; catch keyword
566 (defvar js2-FINALLY 124) ; finally keyword
567 (defvar js2-VOID 125) ; void keyword
568 (defvar js2-RESERVED 126) ; reserved keywords
569
570 (defvar js2-EMPTY 127)
571
572 ;; Types used for the parse tree - never returned by scanner.
573
574 (defvar js2-BLOCK 128) ; statement block
575 (defvar js2-LABEL 129) ; label
576 (defvar js2-TARGET 130)
577 (defvar js2-LOOP 131)
578 (defvar js2-EXPR_VOID 132) ; expression statement in functions
579 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
580 (defvar js2-JSR 134)
581 (defvar js2-SCRIPT 135) ; top-level node for entire script
582 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
583 (defvar js2-USE_STACK 137)
584 (defvar js2-SETPROP_OP 138) ; x.y op= something
585 (defvar js2-SETELEM_OP 139) ; x[y] op= something
586 (defvar js2-LOCAL_BLOCK 140)
587 (defvar js2-SET_REF_OP 141) ; *reference op= something
588
589 ;; For XML support:
590 (defvar js2-DOTDOT 142) ; member operator (..)
591 (defvar js2-COLONCOLON 143) ; namespace::name
592 (defvar js2-XML 144) ; XML type
593 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
594 (defvar js2-XMLATTR 146) ; @
595 (defvar js2-XMLEND 147)
596
597 ;; Optimizer-only tokens
598 (defvar js2-TO_OBJECT 148)
599 (defvar js2-TO_DOUBLE 149)
600
601 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
602 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
603 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
604 (defvar js2-CONST 153)
605 (defvar js2-SETCONST 154)
606 (defvar js2-SETCONSTVAR 155)
607 (defvar js2-ARRAYCOMP 156)
608 (defvar js2-LETEXPR 157)
609 (defvar js2-WITHEXPR 158)
610 (defvar js2-DEBUGGER 159)
611
612 (defvar js2-COMMENT 160)
613 (defvar js2-ENUM 161) ; for "enum" reserved word
614
615 (defconst js2-num-tokens (1+ js2-ENUM))
616
617 (defconst js2-debug-print-trees nil)
618
619 ;; Rhino accepts any string or stream as input. Emacs character
620 ;; processing works best in buffers, so we'll assume the input is a
621 ;; buffer. JavaScript strings can be copied into temp buffers before
622 ;; scanning them.
623
624 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
625 ;; They're the Emacs equivalent of instance variables, more or less.
626
627 (js2-deflocal js2-ts-dirty-line nil
628 "Token stream buffer-local variable.
629 Indicates stuff other than whitespace since start of line.")
630
631 (js2-deflocal js2-ts-regexp-flags nil
632 "Token stream buffer-local variable.")
633
634 (js2-deflocal js2-ts-string ""
635 "Token stream buffer-local variable.
636 Last string scanned.")
637
638 (js2-deflocal js2-ts-number nil
639 "Token stream buffer-local variable.
640 Last literal number scanned.")
641
642 (js2-deflocal js2-ts-hit-eof nil
643 "Token stream buffer-local variable.")
644
645 (js2-deflocal js2-ts-line-start 0
646 "Token stream buffer-local variable.")
647
648 (js2-deflocal js2-ts-lineno 1
649 "Token stream buffer-local variable.")
650
651 (js2-deflocal js2-ts-line-end-char -1
652 "Token stream buffer-local variable.")
653
654 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
655 "Token stream buffer-local variable.
656 Current scan position.")
657
658 (js2-deflocal js2-ts-is-xml-attribute nil
659 "Token stream buffer-local variable.")
660
661 (js2-deflocal js2-ts-xml-is-tag-content nil
662 "Token stream buffer-local variable.")
663
664 (js2-deflocal js2-ts-xml-open-tags-count 0
665 "Token stream buffer-local variable.")
666
667 (js2-deflocal js2-ts-string-buffer nil
668 "Token stream buffer-local variable.
669 List of chars built up while scanning various tokens.")
670
671 (js2-deflocal js2-ts-comment-type nil
672 "Token stream buffer-local variable.")
673
674 ;;; Parser variables
675
676 (js2-deflocal js2-parsed-errors nil
677 "List of errors produced during scanning/parsing.")
678
679 (js2-deflocal js2-parsed-warnings nil
680 "List of warnings produced during scanning/parsing.")
681
682 (js2-deflocal js2-recover-from-parse-errors t
683 "Non-nil to continue parsing after a syntax error.
684
685 In recovery mode, the AST will be built in full, and any error
686 nodes will be flagged with appropriate error information. If
687 this flag is nil, a syntax error will result in an error being
688 signaled.
689
690 The variable is automatically buffer-local, because different
691 modes that use the parser will need different settings.")
692
693 (js2-deflocal js2-parse-hook nil
694 "List of callbacks for receiving parsing progress.")
695
696 (defvar js2-parse-finished-hook nil
697 "List of callbacks to notify when parsing finishes.
698 Not called if parsing was interrupted.")
699
700 (js2-deflocal js2-is-eval-code nil
701 "True if we're evaluating code in a string.
702 If non-nil, the tokenizer will record the token text, and the AST nodes
703 will record their source text. Off by default for IDE modes, since the
704 text is available in the buffer.")
705
706 (defvar js2-parse-ide-mode t
707 "Non-nil if the parser is being used for `js2-mode'.
708 If non-nil, the parser will set text properties for fontification
709 and the syntax table. The value should be nil when using the
710 parser as a frontend to an interpreter or byte compiler.")
711
712 ;;; Parser instance variables (buffer-local vars for js2-parse)
713
714 (defconst js2-clear-ti-mask #xFFFF
715 "Mask to clear token information bits.")
716
717 (defconst js2-ti-after-eol (lsh 1 16)
718 "Flag: first token of the source line.")
719
720 (defconst js2-ti-check-label (lsh 1 17)
721 "Flag: indicates to check for label.")
722
723 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
724
725 (js2-deflocal js2-compiler-generate-debug-info t)
726 (js2-deflocal js2-compiler-use-dynamic-scope nil)
727 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
728 (js2-deflocal js2-compiler-xml-available t)
729 (js2-deflocal js2-compiler-optimization-level 0)
730 (js2-deflocal js2-compiler-generating-source t)
731 (js2-deflocal js2-compiler-strict-mode nil)
732 (js2-deflocal js2-compiler-report-warning-as-error nil)
733 (js2-deflocal js2-compiler-generate-observer-count nil)
734 (js2-deflocal js2-compiler-activation-names nil)
735
736 ;; SKIP: sourceURI
737
738 ;; There's a compileFunction method in Context.java - may need it.
739 (js2-deflocal js2-called-by-compile-function nil
740 "True if `js2-parse' was called by `js2-compile-function'.
741 Will only be used when we finish implementing the interpreter.")
742
743 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
744
745 (js2-deflocal js2-current-flagged-token js2-EOF)
746 (js2-deflocal js2-current-token js2-EOF)
747
748 ;; SKIP: node factory - we're going to just call functions directly,
749 ;; and eventually go to a unified AST format.
750
751 (js2-deflocal js2-nesting-of-function 0)
752
753 (js2-deflocal js2-recorded-assignments nil
754 "Tracks assignments found during parsing.")
755
756 (defcustom js2-global-externs nil
757 "A list of any extern names you'd like to consider always declared.
758 This list is global and is used by all `js2-mode' files.
759 You can create buffer-local externs list using `js2-additional-externs'.
760
761 There is also a buffer-local variable `js2-default-externs',
762 which is initialized by default to include the Ecma-262 externs
763 and the standard browser externs. The three lists are all
764 checked during highlighting."
765 :type 'list
766 :group 'js2-mode)
767
768 (js2-deflocal js2-default-externs nil
769 "Default external declarations.
770
771 These are currently only used for highlighting undeclared variables,
772 which only worries about top-level (unqualified) references.
773 As js2-mode's processing improves, we will flesh out this list.
774
775 The initial value is set to `js2-ecma-262-externs', unless you
776 have set `js2-include-browser-externs', in which case the browser
777 externs are also included.
778
779 See `js2-additional-externs' for more information.")
780
781 (defcustom js2-include-browser-externs t
782 "Non-nil to include browser externs in the master externs list.
783 If you work on JavaScript files that are not intended for browsers,
784 such as Mozilla Rhino server-side JavaScript, set this to nil.
785 You can always include them on a per-file basis by calling
786 `js2-add-browser-externs' from a function on `js2-mode-hook'.
787
788 See `js2-additional-externs' for more information about externs."
789 :type 'boolean
790 :group 'js2-mode)
791
792 (defcustom js2-include-rhino-externs t
793 "Non-nil to include Mozilla Rhino externs in the master externs list.
794 See `js2-additional-externs' for more information about externs."
795 :type 'boolean
796 :group 'js2-mode)
797
798 (defcustom js2-include-gears-externs t
799 "Non-nil to include Google Gears externs in the master externs list.
800 See `js2-additional-externs' for more information about externs."
801 :type 'boolean
802 :group 'js2-mode)
803
804 (js2-deflocal js2-additional-externs nil
805 "A buffer-local list of additional external declarations.
806 It is used to decide whether variables are considered undeclared
807 for purposes of highlighting.
808
809 Each entry is a lisp string. The string should be the fully qualified
810 name of an external entity. All externs should be added to this list,
811 so that as js2-mode's processing improves it can take advantage of them.
812
813 You may want to declare your externs in three ways.
814 First, you can add externs that are valid for all your JavaScript files.
815 You should probably do this by adding them to `js2-global-externs', which
816 is a global list used for all js2-mode files.
817
818 Next, you can add a function to `js2-mode-hook' that adds additional
819 externs appropriate for the specific file, perhaps based on its path.
820 These should go in `js2-additional-externs', which is buffer-local.
821
822 Finally, you can add a function to `js2-post-parse-callbacks',
823 which is called after parsing completes, and `root' is bound to
824 the root of the parse tree. At this stage you can set up an AST
825 node visitor using `js2-visit-ast' and examine the parse tree
826 for specific import patterns that may imply the existence of
827 other externs, possibly tied to your build system. These should also
828 be added to `js2-additional-externs'.
829
830 Your post-parse callback may of course also use the simpler and
831 faster (but perhaps less robust) approach of simply scanning the
832 buffer text for your imports, using regular expressions.")
833
834 ;; SKIP: decompiler
835 ;; SKIP: encoded-source
836
837 ;;; The following variables are per-function and should be saved/restored
838 ;;; during function parsing...
839
840 (js2-deflocal js2-current-script-or-fn nil)
841 (js2-deflocal js2-current-scope nil)
842 (js2-deflocal js2-nesting-of-with 0)
843 (js2-deflocal js2-label-set nil
844 "An alist mapping label names to nodes.")
845
846 (js2-deflocal js2-loop-set nil)
847 (js2-deflocal js2-loop-and-switch-set nil)
848 (js2-deflocal js2-has-return-value nil)
849 (js2-deflocal js2-end-flags 0)
850
851 ;;; ...end of per function variables
852
853 ;; Without 2-token lookahead, labels are a problem.
854 ;; These vars store the token info of the last matched name,
855 ;; iff it wasn't the last matched token. Only valid in some contexts.
856 (defvar js2-prev-name-token-start nil)
857 (defvar js2-prev-name-token-string nil)
858
859 (defsubst js2-save-name-token-data (pos name)
860 (setq js2-prev-name-token-start pos
861 js2-prev-name-token-string name))
862
863 ;; These flags enumerate the possible ways a statement/function can
864 ;; terminate. These flags are used by endCheck() and by the Parser to
865 ;; detect inconsistent return usage.
866 ;;
867 ;; END_UNREACHED is reserved for code paths that are assumed to always be
868 ;; able to execute (example: throw, continue)
869 ;;
870 ;; END_DROPS_OFF indicates if the statement can transfer control to the
871 ;; next one. Statement such as return dont. A compound statement may have
872 ;; some branch that drops off control to the next statement.
873 ;;
874 ;; END_RETURNS indicates that the statement can return (without arguments)
875 ;; END_RETURNS_VALUE indicates that the statement can return a value.
876 ;;
877 ;; A compound statement such as
878 ;; if (condition) {
879 ;; return value;
880 ;; }
881 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
882
883 (defconst js2-end-unreached #x0)
884 (defconst js2-end-drops-off #x1)
885 (defconst js2-end-returns #x2)
886 (defconst js2-end-returns-value #x4)
887 (defconst js2-end-yields #x8)
888
889 ;; Rhino awkwardly passes a statementLabel parameter to the
890 ;; statementHelper() function, the main statement parser, which
891 ;; is then used by quite a few of the sub-parsers. We just make
892 ;; it a buffer-local variable and make sure it's cleaned up properly.
893 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
894
895 ;; Similarly, Rhino passes an inForInit boolean through about half
896 ;; the expression parsers. We use a dynamically-scoped variable,
897 ;; which makes it easier to funcall the parsers individually without
898 ;; worrying about whether they take the parameter or not.
899 (js2-deflocal js2-in-for-init nil)
900 (js2-deflocal js2-temp-name-counter 0)
901 (js2-deflocal js2-parse-stmt-count 0)
902
903 (defsubst js2-get-next-temp-name ()
904 (format "$%d" (incf js2-temp-name-counter)))
905
906 (defvar js2-parse-interruptable-p t
907 "Set this to nil to force parse to continue until finished.
908 This will mostly be useful for interpreters.")
909
910 (defvar js2-statements-per-pause 50
911 "Pause after this many statements to check for user input.
912 If user input is pending, stop the parse and discard the tree.
913 This makes for a smoother user experience for large files.
914 You may have to wait a second or two before the highlighting
915 and error-reporting appear, but you can always type ahead if
916 you wish. This appears to be more or less how Eclipse, IntelliJ
917 and other editors work.")
918
919 (js2-deflocal js2-record-comments t
920 "Instructs the scanner to record comments in `js2-scanned-comments'.")
921
922 (js2-deflocal js2-scanned-comments nil
923 "List of all comments from the current parse.")
924
925 (defcustom js2-mode-indent-inhibit-undo nil
926 "Non-nil to disable collection of Undo information when indenting lines.
927 Some users have requested this behavior. It's nil by default because
928 other Emacs modes don't work this way."
929 :type 'boolean
930 :group 'js2-mode)
931
932 (defcustom js2-mode-indent-ignore-first-tab nil
933 "If non-nil, ignore first TAB keypress if we look indented properly.
934 It's fairly common for users to navigate to an already-indented line
935 and press TAB for reassurance that it's been indented. For this class
936 of users, we want the first TAB press on a line to be ignored if the
937 line is already indented to one of the precomputed alternatives.
938
939 This behavior is only partly implemented. If you TAB-indent a line,
940 navigate to another line, and then navigate back, it fails to clear
941 the last-indented variable, so it thinks you've already hit TAB once,
942 and performs the indent. A full solution would involve getting on the
943 point-motion hooks for the entire buffer. If we come across another
944 use cases that requires watching point motion, I'll consider doing it.
945
946 If you set this variable to nil, then the TAB key will always change
947 the indentation of the current line, if more than one alternative
948 indentation spot exists."
949 :type 'boolean
950 :group 'js2-mode)
951
952 (defvar js2-indent-hook nil
953 "A hook for user-defined indentation rules.
954
955 Functions on this hook should expect two arguments: (LIST INDEX)
956 The LIST argument is the list of computed indentation points for
957 the current line. INDEX is the list index of the indentation point
958 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
959 indent function is not going to change the current line indentation.
960
961 If a hook function on this list returns a non-nil value, then
962 `js2-bounce-indent' assumes the hook function has performed its own
963 indentation, and will do nothing. If all hook functions on the list
964 return nil, then `js2-bounce-indent' will use its computed indentation
965 and reindent the line.
966
967 When hook functions on this hook list are called, the variable
968 `js2-mode-ast' may or may not be set, depending on whether the
969 parse tree is available. If the variable is nil, you can pass a
970 callback to `js2-mode-wait-for-parse', and your callback will be
971 called after the new parse tree is built. This can take some time
972 in large files.")
973
974 (defface js2-warning
975 `((((class color) (background light))
976 (:underline "orange"))
977 (((class color) (background dark))
978 (:underline "orange"))
979 (t (:underline t)))
980 "Face for JavaScript warnings."
981 :group 'js2-mode)
982
983 (defface js2-error
984 `((((class color) (background light))
985 (:foreground "red"))
986 (((class color) (background dark))
987 (:foreground "red"))
988 (t (:foreground "red")))
989 "Face for JavaScript errors."
990 :group 'js2-mode)
991
992 (defface js2-jsdoc-tag
993 '((t :foreground "SlateGray"))
994 "Face used to highlight @whatever tags in jsdoc comments."
995 :group 'js2-mode)
996
997 (defface js2-jsdoc-type
998 '((t :foreground "SteelBlue"))
999 "Face used to highlight {FooBar} types in jsdoc comments."
1000 :group 'js2-mode)
1001
1002 (defface js2-jsdoc-value
1003 '((t :foreground "PeachPuff3"))
1004 "Face used to highlight tag values in jsdoc comments."
1005 :group 'js2-mode)
1006
1007 (defface js2-function-param
1008 '((t :foreground "SeaGreen"))
1009 "Face used to highlight function parameters in javascript."
1010 :group 'js2-mode)
1011
1012 (defface js2-instance-member
1013 '((t :foreground "DarkOrchid"))
1014 "Face used to highlight instance variables in javascript.
1015 Not currently used."
1016 :group 'js2-mode)
1017
1018 (defface js2-private-member
1019 '((t :foreground "PeachPuff3"))
1020 "Face used to highlight calls to private methods in javascript.
1021 Not currently used."
1022 :group 'js2-mode)
1023
1024 (defface js2-private-function-call
1025 '((t :foreground "goldenrod"))
1026 "Face used to highlight calls to private functions in javascript.
1027 Not currently used."
1028 :group 'js2-mode)
1029
1030 (defface js2-jsdoc-html-tag-name
1031 (if js2-emacs22
1032 '((((class color) (min-colors 88) (background light))
1033 (:foreground "rosybrown"))
1034 (((class color) (min-colors 8) (background dark))
1035 (:foreground "yellow"))
1036 (((class color) (min-colors 8) (background light))
1037 (:foreground "magenta")))
1038 '((((type tty pc) (class color) (background light))
1039 (:foreground "magenta"))
1040 (((type tty pc) (class color) (background dark))
1041 (:foreground "yellow"))
1042 (t (:foreground "RosyBrown"))))
1043 "Face used to highlight jsdoc html tag names"
1044 :group 'js2-mode)
1045
1046 (defface js2-jsdoc-html-tag-delimiter
1047 (if js2-emacs22
1048 '((((class color) (min-colors 88) (background light))
1049 (:foreground "dark khaki"))
1050 (((class color) (min-colors 8) (background dark))
1051 (:foreground "green"))
1052 (((class color) (min-colors 8) (background light))
1053 (:foreground "green")))
1054 '((((type tty pc) (class color) (background light))
1055 (:foreground "green"))
1056 (((type tty pc) (class color) (background dark))
1057 (:foreground "green"))
1058 (t (:foreground "dark khaki"))))
1059 "Face used to highlight brackets in jsdoc html tags."
1060 :group 'js2-mode)
1061
1062 (defface js2-magic-paren
1063 '((t :underline t))
1064 "Face used to color parens that will be auto-overwritten."
1065 :group 'js2-mode)
1066
1067 (defcustom js2-post-parse-callbacks nil
1068 "A list of callback functions invoked after parsing finishes.
1069 Currently, the main use for this function is to add synthetic
1070 declarations to `js2-recorded-assignments', which see."
1071 :type 'list
1072 :group 'js2-mode)
1073
1074 (defface js2-external-variable
1075 '((t :foreground "orange"))
1076 "Face used to highlight assignments to undeclared variables.
1077 An undeclared variable is any variable not declared with var or let
1078 in the current scope or any lexically enclosing scope. If you assign
1079 to such a variable, then you are either expecting it to originate from
1080 another file, or you've got a potential bug."
1081 :group 'js2-mode)
1082
1083 (defcustom js2-highlight-external-variables t
1084 "Non-nil to higlight assignments to undeclared variables."
1085 :type 'boolean
1086 :group 'js2-mode)
1087
1088 (defcustom js2-auto-insert-catch-block t
1089 "Non-nil to insert matching catch block on open-curly after `try'."
1090 :type 'boolean
1091 :group 'js2-mode)
1092
1093 (defvar js2-mode-map
1094 (let ((map (make-sparse-keymap))
1095 keys)
1096 (define-key map [mouse-1] #'js2-mode-show-node)
1097 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1098 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1099 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1100 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1101 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1102 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1103 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1104 ;; FIXME: Why isn't it sufficient to set {beginning,end}-of-defun-function?
1105 (define-key map [remap mark-defun] #'js2-mark-defun)
1106 (define-key map [remap narrow-to-defun] #'js2-narrow-to-defun)
1107 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1108
1109 (define-key map [menu-bar javascript]
1110 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1111
1112 (define-key map [menu-bar javascript customize-js2-mode]
1113 '(menu-item "Customize js2-mode" js2-mode-customize
1114 :help "Customize the behavior of this mode"))
1115
1116 (define-key map [menu-bar javascript js2-force-refresh]
1117 '(menu-item "Force buffer refresh" js2-mode-reset
1118 :help "Re-parse the buffer from scratch"))
1119
1120 (define-key map [menu-bar javascript separator-2]
1121 '("--"))
1122
1123 (define-key map [menu-bar javascript next-error]
1124 '(menu-item "Next warning or error" next-error
1125 :enabled (and js2-mode-ast
1126 (or (js2-ast-root-errors js2-mode-ast)
1127 (js2-ast-root-warnings js2-mode-ast)))
1128 :help "Move to next warning or error"))
1129
1130 (define-key map [menu-bar javascript display-errors]
1131 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1132 :visible (not js2-mode-show-parse-errors)
1133 :help "Turn on display of warnings and errors"))
1134
1135 (define-key map [menu-bar javascript hide-errors]
1136 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1137 :visible js2-mode-show-parse-errors
1138 :help "Turn off display of warnings and errors"))
1139
1140 (define-key map [menu-bar javascript separator-1]
1141 '("--"))
1142
1143 (define-key map [menu-bar javascript js2-toggle-function]
1144 '(menu-item "Show/collapse element" js2-mode-toggle-element
1145 :help "Hide or show function body or comment"))
1146
1147 (define-key map [menu-bar javascript show-comments]
1148 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1149 :visible js2-mode-comments-hidden
1150 :help "Expand all hidden block comments"))
1151
1152 (define-key map [menu-bar javascript hide-comments]
1153 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1154 :visible (not js2-mode-comments-hidden)
1155 :help "Show block comments as /*...*/"))
1156
1157 (define-key map [menu-bar javascript show-all-functions]
1158 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1159 :visible js2-mode-functions-hidden
1160 :help "Expand all hidden function bodies"))
1161
1162 (define-key map [menu-bar javascript hide-all-functions]
1163 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1164 :visible (not js2-mode-functions-hidden)
1165 :help "Show {...} for all top-level function bodies"))
1166
1167 map)
1168 "Keymap used in `js2-mode' buffers.")
1169
1170 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1171
1172 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1173 "Matches a //-comment line. Must be first non-whitespace on line.
1174 First match-group is the leading whitespace.")
1175
1176 (defvar js2-mode-hook nil)
1177
1178 (js2-deflocal js2-mode-ast nil "Private variable.")
1179 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1180 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1181 (js2-deflocal js2-mode-parsing nil "Private variable.")
1182 (js2-deflocal js2-mode-node-overlay nil)
1183
1184 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1185 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1186
1187 (js2-deflocal js2-mode-fontifications nil "Private variable")
1188 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1189 (js2-deflocal js2-imenu-recorder nil "Private variable")
1190 (js2-deflocal js2-imenu-function-map nil "Private variable")
1191
1192 (defvar js2-paragraph-start
1193 "\\(@[a-zA-Z]+\\>\\|$\\)")
1194
1195 ;; Note that we also set a 'c-in-sws text property in html comments,
1196 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1197 (defvar js2-syntactic-ws-start
1198 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1199
1200 (defvar js2-syntactic-ws-end
1201 "\\s \\|[\n\r/]\\|\\s!")
1202
1203 (defvar js2-syntactic-eol
1204 (concat "\\s *\\(/\\*[^*\n\r]*"
1205 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1206 "\\*+/\\s *\\)*"
1207 "\\(//\\|/\\*[^*\n\r]*"
1208 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1209 "\\|\\\\$\\|$\\)")
1210 "Copied from `java-mode'. Needed for some cc-engine functions.")
1211
1212 (defvar js2-comment-prefix-regexp
1213 "//+\\|\\**")
1214
1215 (defvar js2-comment-start-skip
1216 "\\(//+\\|/\\*+\\)\\s *")
1217
1218 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1219 "Non-nil to emit status messages during parsing.")
1220
1221 (defvar js2-mode-functions-hidden nil "Private variable.")
1222 (defvar js2-mode-comments-hidden nil "Private variable.")
1223
1224 (defvar js2-mode-syntax-table
1225 (let ((table (make-syntax-table)))
1226 (c-populate-syntax-table table)
1227 table)
1228 "Syntax table used in `js2-mode' buffers.")
1229
1230 (defvar js2-mode-abbrev-table nil
1231 "Abbrev table in use in `js2-mode' buffers.")
1232 (define-abbrev-table 'js2-mode-abbrev-table ())
1233
1234 (defvar js2-mode-pending-parse-callbacks nil
1235 "List of functions waiting to be notified that parse is finished.")
1236
1237 (defvar js2-mode-last-indented-line -1)
1238
1239 ;;; Localizable error and warning messages
1240
1241 ;; Messages are copied from Rhino's Messages.properties.
1242 ;; Many of the Java-specific messages have been elided.
1243 ;; Add any js2-specific ones at the end, so we can keep
1244 ;; this file synced with changes to Rhino's.
1245
1246 (defvar js2-message-table
1247 (make-hash-table :test 'equal :size 250)
1248 "Contains localized messages for `js2-mode'.")
1249
1250 ;; TODO(stevey): construct this table at compile-time.
1251 (defmacro js2-msg (key &rest strings)
1252 `(puthash ,key (funcall #'concat ,@strings)
1253 js2-message-table))
1254
1255 (defun js2-get-msg (msg-key)
1256 "Look up a localized message.
1257 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1258 the correct number of ARGS must be provided."
1259 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1260 (args (if (listp msg-key) (cdr msg-key)))
1261 (msg (gethash key js2-message-table)))
1262 (if msg
1263 (apply #'format msg args)
1264 key))) ; default to showing the key
1265
1266 (js2-msg "msg.dup.parms"
1267 "Duplicate parameter name '%s'.")
1268
1269 (js2-msg "msg.too.big.jump"
1270 "Program too complex: jump offset too big.")
1271
1272 (js2-msg "msg.too.big.index"
1273 "Program too complex: internal index exceeds 64K limit.")
1274
1275 (js2-msg "msg.while.compiling.fn"
1276 "Encountered code generation error while compiling function '%s': %s")
1277
1278 (js2-msg "msg.while.compiling.script"
1279 "Encountered code generation error while compiling script: %s")
1280
1281 ;; Context
1282 (js2-msg "msg.ctor.not.found"
1283 "Constructor for '%s' not found.")
1284
1285 (js2-msg "msg.not.ctor"
1286 "'%s' is not a constructor.")
1287
1288 ;; FunctionObject
1289 (js2-msg "msg.varargs.ctor"
1290 "Method or constructor '%s' must be static "
1291 "with the signature (Context cx, Object[] args, "
1292 "Function ctorObj, boolean inNewExpr) "
1293 "to define a variable arguments constructor.")
1294
1295 (js2-msg "msg.varargs.fun"
1296 "Method '%s' must be static with the signature "
1297 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1298 "to define a variable arguments function.")
1299
1300 (js2-msg "msg.incompat.call"
1301 "Method '%s' called on incompatible object.")
1302
1303 (js2-msg "msg.bad.parms"
1304 "Unsupported parameter type '%s' in method '%s'.")
1305
1306 (js2-msg "msg.bad.method.return"
1307 "Unsupported return type '%s' in method '%s'.")
1308
1309 (js2-msg "msg.bad.ctor.return"
1310 "Construction of objects of type '%s' is not supported.")
1311
1312 (js2-msg "msg.no.overload"
1313 "Method '%s' occurs multiple times in class '%s'.")
1314
1315 (js2-msg "msg.method.not.found"
1316 "Method '%s' not found in '%s'.")
1317
1318 ;; IRFactory
1319
1320 (js2-msg "msg.bad.for.in.lhs"
1321 "Invalid left-hand side of for..in loop.")
1322
1323 (js2-msg "msg.mult.index"
1324 "Only one variable allowed in for..in loop.")
1325
1326 (js2-msg "msg.bad.for.in.destruct"
1327 "Left hand side of for..in loop must be an array of "
1328 "length 2 to accept key/value pair.")
1329
1330 (js2-msg "msg.cant.convert"
1331 "Can't convert to type '%s'.")
1332
1333 (js2-msg "msg.bad.assign.left"
1334 "Invalid assignment left-hand side.")
1335
1336 (js2-msg "msg.bad.decr"
1337 "Invalid decerement operand.")
1338
1339 (js2-msg "msg.bad.incr"
1340 "Invalid increment operand.")
1341
1342 (js2-msg "msg.bad.yield"
1343 "yield must be in a function.")
1344
1345 (js2-msg "msg.yield.parenthesized"
1346 "yield expression must be parenthesized.")
1347
1348 ;; NativeGlobal
1349 (js2-msg "msg.cant.call.indirect"
1350 "Function '%s' must be called directly, and not by way of a "
1351 "function of another name.")
1352
1353 (js2-msg "msg.eval.nonstring"
1354 "Calling eval() with anything other than a primitive "
1355 "string value will simply return the value. "
1356 "Is this what you intended?")
1357
1358 (js2-msg "msg.eval.nonstring.strict"
1359 "Calling eval() with anything other than a primitive "
1360 "string value is not allowed in strict mode.")
1361
1362 (js2-msg "msg.bad.destruct.op"
1363 "Invalid destructuring assignment operator")
1364
1365 ;; NativeCall
1366 (js2-msg "msg.only.from.new"
1367 "'%s' may only be invoked from a `new' expression.")
1368
1369 (js2-msg "msg.deprec.ctor"
1370 "The '%s' constructor is deprecated.")
1371
1372 ;; NativeFunction
1373 (js2-msg "msg.no.function.ref.found"
1374 "no source found to decompile function reference %s")
1375
1376 (js2-msg "msg.arg.isnt.array"
1377 "second argument to Function.prototype.apply must be an array")
1378
1379 ;; NativeGlobal
1380 (js2-msg "msg.bad.esc.mask"
1381 "invalid string escape mask")
1382
1383 ;; NativeRegExp
1384 (js2-msg "msg.bad.quant"
1385 "Invalid quantifier %s")
1386
1387 (js2-msg "msg.overlarge.backref"
1388 "Overly large back reference %s")
1389
1390 (js2-msg "msg.overlarge.min"
1391 "Overly large minimum %s")
1392
1393 (js2-msg "msg.overlarge.max"
1394 "Overly large maximum %s")
1395
1396 (js2-msg "msg.zero.quant"
1397 "Zero quantifier %s")
1398
1399 (js2-msg "msg.max.lt.min"
1400 "Maximum %s less than minimum")
1401
1402 (js2-msg "msg.unterm.quant"
1403 "Unterminated quantifier %s")
1404
1405 (js2-msg "msg.unterm.paren"
1406 "Unterminated parenthetical %s")
1407
1408 (js2-msg "msg.unterm.class"
1409 "Unterminated character class %s")
1410
1411 (js2-msg "msg.bad.range"
1412 "Invalid range in character class.")
1413
1414 (js2-msg "msg.trail.backslash"
1415 "Trailing \\ in regular expression.")
1416
1417 (js2-msg "msg.re.unmatched.right.paren"
1418 "unmatched ) in regular expression.")
1419
1420 (js2-msg "msg.no.regexp"
1421 "Regular expressions are not available.")
1422
1423 (js2-msg "msg.bad.backref"
1424 "back-reference exceeds number of capturing parentheses.")
1425
1426 (js2-msg "msg.bad.regexp.compile"
1427 "Only one argument may be specified if the first "
1428 "argument to RegExp.prototype.compile is a RegExp object.")
1429
1430 ;; Parser
1431 (js2-msg "msg.got.syntax.errors"
1432 "Compilation produced %s syntax errors.")
1433
1434 (js2-msg "msg.var.redecl"
1435 "TypeError: redeclaration of var %s.")
1436
1437 (js2-msg "msg.const.redecl"
1438 "TypeError: redeclaration of const %s.")
1439
1440 (js2-msg "msg.let.redecl"
1441 "TypeError: redeclaration of variable %s.")
1442
1443 (js2-msg "msg.parm.redecl"
1444 "TypeError: redeclaration of formal parameter %s.")
1445
1446 (js2-msg "msg.fn.redecl"
1447 "TypeError: redeclaration of function %s.")
1448
1449 (js2-msg "msg.let.decl.not.in.block"
1450 "SyntaxError: let declaration not directly within block")
1451
1452 ;; NodeTransformer
1453 (js2-msg "msg.dup.label"
1454 "duplicated label")
1455
1456 (js2-msg "msg.undef.label"
1457 "undefined label")
1458
1459 (js2-msg "msg.bad.break"
1460 "unlabelled break must be inside loop or switch")
1461
1462 (js2-msg "msg.continue.outside"
1463 "continue must be inside loop")
1464
1465 (js2-msg "msg.continue.nonloop"
1466 "continue can only use labels of iteration statements")
1467
1468 (js2-msg "msg.bad.throw.eol"
1469 "Line terminator is not allowed between the throw "
1470 "keyword and throw expression.")
1471
1472 (js2-msg "msg.no.paren.parms"
1473 "missing ( before function parameters.")
1474
1475 (js2-msg "msg.no.parm"
1476 "missing formal parameter")
1477
1478 (js2-msg "msg.no.paren.after.parms"
1479 "missing ) after formal parameters")
1480
1481 (js2-msg "msg.no.brace.body"
1482 "missing '{' before function body")
1483
1484 (js2-msg "msg.no.brace.after.body"
1485 "missing } after function body")
1486
1487 (js2-msg "msg.no.paren.cond"
1488 "missing ( before condition")
1489
1490 (js2-msg "msg.no.paren.after.cond"
1491 "missing ) after condition")
1492
1493 (js2-msg "msg.no.semi.stmt"
1494 "missing ; before statement")
1495
1496 (js2-msg "msg.missing.semi"
1497 "missing ; after statement")
1498
1499 (js2-msg "msg.no.name.after.dot"
1500 "missing name after . operator")
1501
1502 (js2-msg "msg.no.name.after.coloncolon"
1503 "missing name after :: operator")
1504
1505 (js2-msg "msg.no.name.after.dotdot"
1506 "missing name after .. operator")
1507
1508 (js2-msg "msg.no.name.after.xmlAttr"
1509 "missing name after .@")
1510
1511 (js2-msg "msg.no.bracket.index"
1512 "missing ] in index expression")
1513
1514 (js2-msg "msg.no.paren.switch"
1515 "missing ( before switch expression")
1516
1517 (js2-msg "msg.no.paren.after.switch"
1518 "missing ) after switch expression")
1519
1520 (js2-msg "msg.no.brace.switch"
1521 "missing '{' before switch body")
1522
1523 (js2-msg "msg.bad.switch"
1524 "invalid switch statement")
1525
1526 (js2-msg "msg.no.colon.case"
1527 "missing : after case expression")
1528
1529 (js2-msg "msg.double.switch.default"
1530 "double default label in the switch statement")
1531
1532 (js2-msg "msg.no.while.do"
1533 "missing while after do-loop body")
1534
1535 (js2-msg "msg.no.paren.for"
1536 "missing ( after for")
1537
1538 (js2-msg "msg.no.semi.for"
1539 "missing ; after for-loop initializer")
1540
1541 (js2-msg "msg.no.semi.for.cond"
1542 "missing ; after for-loop condition")
1543
1544 (js2-msg "msg.in.after.for.name"
1545 "missing in after for")
1546
1547 (js2-msg "msg.no.paren.for.ctrl"
1548 "missing ) after for-loop control")
1549
1550 (js2-msg "msg.no.paren.with"
1551 "missing ( before with-statement object")
1552
1553 (js2-msg "msg.no.paren.after.with"
1554 "missing ) after with-statement object")
1555
1556 (js2-msg "msg.no.paren.after.let"
1557 "missing ( after let")
1558
1559 (js2-msg "msg.no.paren.let"
1560 "missing ) after variable list")
1561
1562 (js2-msg "msg.no.curly.let"
1563 "missing } after let statement")
1564
1565 (js2-msg "msg.bad.return"
1566 "invalid return")
1567
1568 (js2-msg "msg.no.brace.block"
1569 "missing } in compound statement")
1570
1571 (js2-msg "msg.bad.label"
1572 "invalid label")
1573
1574 (js2-msg "msg.bad.var"
1575 "missing variable name")
1576
1577 (js2-msg "msg.bad.var.init"
1578 "invalid variable initialization")
1579
1580 (js2-msg "msg.no.colon.cond"
1581 "missing : in conditional expression")
1582
1583 (js2-msg "msg.no.paren.arg"
1584 "missing ) after argument list")
1585
1586 (js2-msg "msg.no.bracket.arg"
1587 "missing ] after element list")
1588
1589 (js2-msg "msg.bad.prop"
1590 "invalid property id")
1591
1592 (js2-msg "msg.no.colon.prop"
1593 "missing : after property id")
1594
1595 (js2-msg "msg.no.brace.prop"
1596 "missing } after property list")
1597
1598 (js2-msg "msg.no.paren"
1599 "missing ) in parenthetical")
1600
1601 (js2-msg "msg.reserved.id"
1602 "identifier is a reserved word")
1603
1604 (js2-msg "msg.no.paren.catch"
1605 "missing ( before catch-block condition")
1606
1607 (js2-msg "msg.bad.catchcond"
1608 "invalid catch block condition")
1609
1610 (js2-msg "msg.catch.unreachable"
1611 "any catch clauses following an unqualified catch are unreachable")
1612
1613 (js2-msg "msg.no.brace.try"
1614 "missing '{' before try block")
1615
1616 (js2-msg "msg.no.brace.catchblock"
1617 "missing '{' before catch-block body")
1618
1619 (js2-msg "msg.try.no.catchfinally"
1620 "'try' without 'catch' or 'finally'")
1621
1622 (js2-msg "msg.no.return.value"
1623 "function %s does not always return a value")
1624
1625 (js2-msg "msg.anon.no.return.value"
1626 "anonymous function does not always return a value")
1627
1628 (js2-msg "msg.return.inconsistent"
1629 "return statement is inconsistent with previous usage")
1630
1631 (js2-msg "msg.generator.returns"
1632 "TypeError: generator function '%s' returns a value")
1633
1634 (js2-msg "msg.anon.generator.returns"
1635 "TypeError: anonymous generator function returns a value")
1636
1637 (js2-msg "msg.syntax"
1638 "syntax error")
1639
1640 (js2-msg "msg.unexpected.eof"
1641 "Unexpected end of file")
1642
1643 (js2-msg "msg.XML.bad.form"
1644 "illegally formed XML syntax")
1645
1646 (js2-msg "msg.XML.not.available"
1647 "XML runtime not available")
1648
1649 (js2-msg "msg.too.deep.parser.recursion"
1650 "Too deep recursion while parsing")
1651
1652 (js2-msg "msg.no.side.effects"
1653 "Code has no side effects")
1654
1655 (js2-msg "msg.extra.trailing.comma"
1656 "Trailing comma is not legal in an ECMA-262 object initializer")
1657
1658 (js2-msg "msg.array.trailing.comma"
1659 "Trailing comma yields different behavior across browsers")
1660
1661 (js2-msg "msg.equal.as.assign"
1662 (concat "Test for equality (==) mistyped as assignment (=)?"
1663 " (parenthesize to suppress warning)"))
1664
1665 (js2-msg "msg.var.hides.arg"
1666 "Variable %s hides argument")
1667
1668 (js2-msg "msg.destruct.assign.no.init"
1669 "Missing = in destructuring declaration")
1670
1671 ;; ScriptRuntime
1672 (js2-msg "msg.no.properties"
1673 "%s has no properties.")
1674
1675 (js2-msg "msg.invalid.iterator"
1676 "Invalid iterator value")
1677
1678 (js2-msg "msg.iterator.primitive"
1679 "__iterator__ returned a primitive value")
1680
1681 (js2-msg "msg.assn.create.strict"
1682 "Assignment to undeclared variable %s")
1683
1684 (js2-msg "msg.ref.undefined.prop"
1685 "Reference to undefined property '%s'")
1686
1687 (js2-msg "msg.prop.not.found"
1688 "Property %s not found.")
1689
1690 (js2-msg "msg.invalid.type"
1691 "Invalid JavaScript value of type %s")
1692
1693 (js2-msg "msg.primitive.expected"
1694 "Primitive type expected (had %s instead)")
1695
1696 (js2-msg "msg.namespace.expected"
1697 "Namespace object expected to left of :: (found %s instead)")
1698
1699 (js2-msg "msg.null.to.object"
1700 "Cannot convert null to an object.")
1701
1702 (js2-msg "msg.undef.to.object"
1703 "Cannot convert undefined to an object.")
1704
1705 (js2-msg "msg.cyclic.value"
1706 "Cyclic %s value not allowed.")
1707
1708 (js2-msg "msg.is.not.defined"
1709 "'%s' is not defined.")
1710
1711 (js2-msg "msg.undef.prop.read"
1712 "Cannot read property '%s' from %s")
1713
1714 (js2-msg "msg.undef.prop.write"
1715 "Cannot set property '%s' of %s to '%s'")
1716
1717 (js2-msg "msg.undef.prop.delete"
1718 "Cannot delete property '%s' of %s")
1719
1720 (js2-msg "msg.undef.method.call"
1721 "Cannot call method '%s' of %s")
1722
1723 (js2-msg "msg.undef.with"
1724 "Cannot apply 'with' to %s")
1725
1726 (js2-msg "msg.isnt.function"
1727 "%s is not a function, it is %s.")
1728
1729 (js2-msg "msg.isnt.function.in"
1730 "Cannot call property %s in object %s. "
1731 "It is not a function, it is '%s'.")
1732
1733 (js2-msg "msg.function.not.found"
1734 "Cannot find function %s.")
1735
1736 (js2-msg "msg.function.not.found.in"
1737 "Cannot find function %s in object %s.")
1738
1739 (js2-msg "msg.isnt.xml.object"
1740 "%s is not an xml object.")
1741
1742 (js2-msg "msg.no.ref.to.get"
1743 "%s is not a reference to read reference value.")
1744
1745 (js2-msg "msg.no.ref.to.set"
1746 "%s is not a reference to set reference value to %s.")
1747
1748 (js2-msg "msg.no.ref.from.function"
1749 "Function %s can not be used as the left-hand "
1750 "side of assignment or as an operand of ++ or -- operator.")
1751
1752 (js2-msg "msg.bad.default.value"
1753 "Object's getDefaultValue() method returned an object.")
1754
1755 (js2-msg "msg.instanceof.not.object"
1756 "Can't use instanceof on a non-object.")
1757
1758 (js2-msg "msg.instanceof.bad.prototype"
1759 "'prototype' property of %s is not an object.")
1760
1761 (js2-msg "msg.bad.radix"
1762 "illegal radix %s.")
1763
1764 ;; ScriptableObject
1765 (js2-msg "msg.default.value"
1766 "Cannot find default value for object.")
1767
1768 (js2-msg "msg.zero.arg.ctor"
1769 "Cannot load class '%s' which has no zero-parameter constructor.")
1770
1771 (js2-msg "msg.ctor.multiple.parms"
1772 "Can't define constructor or class %s since more than "
1773 "one constructor has multiple parameters.")
1774
1775 (js2-msg "msg.extend.scriptable"
1776 "%s must extend ScriptableObject in order to define property %s.")
1777
1778 (js2-msg "msg.bad.getter.parms"
1779 "In order to define a property, getter %s must have zero "
1780 "parameters or a single ScriptableObject parameter.")
1781
1782 (js2-msg "msg.obj.getter.parms"
1783 "Expected static or delegated getter %s to take "
1784 "a ScriptableObject parameter.")
1785
1786 (js2-msg "msg.getter.static"
1787 "Getter and setter must both be static or neither be static.")
1788
1789 (js2-msg "msg.setter.return"
1790 "Setter must have void return type: %s")
1791
1792 (js2-msg "msg.setter2.parms"
1793 "Two-parameter setter must take a ScriptableObject as "
1794 "its first parameter.")
1795
1796 (js2-msg "msg.setter1.parms"
1797 "Expected single parameter setter for %s")
1798
1799 (js2-msg "msg.setter2.expected"
1800 "Expected static or delegated setter %s to take two parameters.")
1801
1802 (js2-msg "msg.setter.parms"
1803 "Expected either one or two parameters for setter.")
1804
1805 (js2-msg "msg.setter.bad.type"
1806 "Unsupported parameter type '%s' in setter '%s'.")
1807
1808 (js2-msg "msg.add.sealed"
1809 "Cannot add a property to a sealed object: %s.")
1810
1811 (js2-msg "msg.remove.sealed"
1812 "Cannot remove a property from a sealed object: %s.")
1813
1814 (js2-msg "msg.modify.sealed"
1815 "Cannot modify a property of a sealed object: %s.")
1816
1817 (js2-msg "msg.modify.readonly"
1818 "Cannot modify readonly property: %s.")
1819
1820 ;; TokenStream
1821 (js2-msg "msg.missing.exponent"
1822 "missing exponent")
1823
1824 (js2-msg "msg.caught.nfe"
1825 "number format error")
1826
1827 (js2-msg "msg.unterminated.string.lit"
1828 "unterminated string literal")
1829
1830 (js2-msg "msg.unterminated.comment"
1831 "unterminated comment")
1832
1833 (js2-msg "msg.unterminated.re.lit"
1834 "unterminated regular expression literal")
1835
1836 (js2-msg "msg.invalid.re.flag"
1837 "invalid flag after regular expression")
1838
1839 (js2-msg "msg.no.re.input.for"
1840 "no input for %s")
1841
1842 (js2-msg "msg.illegal.character"
1843 "illegal character")
1844
1845 (js2-msg "msg.invalid.escape"
1846 "invalid Unicode escape sequence")
1847
1848 (js2-msg "msg.bad.namespace"
1849 "not a valid default namespace statement. "
1850 "Syntax is: default xml namespace = EXPRESSION;")
1851
1852 ;; TokensStream warnings
1853 (js2-msg "msg.bad.octal.literal"
1854 "illegal octal literal digit %s; "
1855 "interpreting it as a decimal digit")
1856
1857 (js2-msg "msg.reserved.keyword"
1858 "illegal usage of future reserved keyword %s; "
1859 "interpreting it as ordinary identifier")
1860
1861 (js2-msg "msg.script.is.not.constructor"
1862 "Script objects are not constructors.")
1863
1864 ;; Arrays
1865 (js2-msg "msg.arraylength.bad"
1866 "Inappropriate array length.")
1867
1868 ;; Arrays
1869 (js2-msg "msg.arraylength.too.big"
1870 "Array length %s exceeds supported capacity limit.")
1871
1872 ;; URI
1873 (js2-msg "msg.bad.uri"
1874 "Malformed URI sequence.")
1875
1876 ;; Number
1877 (js2-msg "msg.bad.precision"
1878 "Precision %s out of range.")
1879
1880 ;; NativeGenerator
1881 (js2-msg "msg.send.newborn"
1882 "Attempt to send value to newborn generator")
1883
1884 (js2-msg "msg.already.exec.gen"
1885 "Already executing generator")
1886
1887 (js2-msg "msg.StopIteration.invalid"
1888 "StopIteration may not be changed to an arbitrary object.")
1889
1890 ;; Interpreter
1891 (js2-msg "msg.yield.closing"
1892 "Yield from closing generator")
1893
1894 ;;; Utilities
1895
1896 (defun js2-delete-if (predicate list)
1897 "Remove all items satisfying PREDICATE in LIST."
1898 (loop for item in list
1899 if (not (funcall predicate item))
1900 collect item))
1901
1902 (defun js2-position (element list)
1903 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1904 Returns nil if element is not found in the list."
1905 (let ((count 0)
1906 found)
1907 (while (and list (not found))
1908 (if (eq element (car list))
1909 (setq found t)
1910 (setq count (1+ count)
1911 list (cdr list))))
1912 (if found count)))
1913
1914 (defun js2-find-if (predicate list)
1915 "Find first item satisfying PREDICATE in LIST."
1916 (let (result)
1917 (while (and list (not result))
1918 (if (funcall predicate (car list))
1919 (setq result (car list)))
1920 (setq list (cdr list)))
1921 result))
1922
1923 (defmacro js2-time (form)
1924 "Evaluate FORM, discard result, and return elapsed time in sec."
1925 (declare (debug t))
1926 (let ((beg (make-symbol "--js2-time-beg--"))
1927 (delta (make-symbol "--js2-time-end--")))
1928 `(let ((,beg (current-time))
1929 ,delta)
1930 ,form
1931 (/ (truncate (* (- (float-time (current-time))
1932 (float-time ,beg)))
1933 10000)
1934 10000.0))))
1935
1936 (defsubst js2-same-line (pos)
1937 "Return t if POS is on the same line as current point."
1938 (and (>= pos (point-at-bol))
1939 (<= pos (point-at-eol))))
1940
1941 (defsubst js2-same-line-2 (p1 p2)
1942 "Return t if P1 is on the same line as P2."
1943 (save-excursion
1944 (goto-char p1)
1945 (js2-same-line p2)))
1946
1947 (defun js2-code-bug ()
1948 "Signal an error when we encounter an unexpected code path."
1949 (error "failed assertion"))
1950
1951 ;; I'd like to associate errors with nodes, but for now the
1952 ;; easiest thing to do is get the context info from the last token.
1953 (defsubst js2-record-parse-error (msg &optional arg pos len)
1954 (push (list (list msg arg)
1955 (or pos js2-token-beg)
1956 (or len (- js2-token-end js2-token-beg)))
1957 js2-parsed-errors))
1958
1959 (defsubst js2-report-error (msg &optional msg-arg pos len)
1960 "Signal a syntax error or record a parse error."
1961 (if js2-recover-from-parse-errors
1962 (js2-record-parse-error msg msg-arg pos len)
1963 (signal 'js2-syntax-error
1964 (list msg
1965 js2-ts-lineno
1966 (save-excursion
1967 (goto-char js2-ts-cursor)
1968 (current-column))
1969 js2-ts-hit-eof))))
1970
1971 (defsubst js2-report-warning (msg &optional msg-arg pos len)
1972 (if js2-compiler-report-warning-as-error
1973 (js2-report-error msg msg-arg pos len)
1974 (push (list (list msg msg-arg)
1975 (or pos js2-token-beg)
1976 (or len (- js2-token-end js2-token-beg)))
1977 js2-parsed-warnings)))
1978
1979 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
1980 (if js2-compiler-strict-mode
1981 (js2-report-warning msg-id msg-arg beg
1982 (and beg end (- end beg)))))
1983
1984 (put 'js2-syntax-error 'error-conditions
1985 '(error syntax-error js2-syntax-error))
1986 (put 'js2-syntax-error 'error-message "Syntax error")
1987
1988 (put 'js2-parse-error 'error-conditions
1989 '(error parse-error js2-parse-error))
1990 (put 'js2-parse-error 'error-message "Parse error")
1991
1992 (defmacro js2-clear-flag (flags flag)
1993 `(setq ,flags (logand ,flags (lognot ,flag))))
1994
1995 (defmacro js2-set-flag (flags flag)
1996 "Logical-or FLAG into FLAGS."
1997 `(setq ,flags (logior ,flags ,flag)))
1998
1999 (defsubst js2-flag-set-p (flags flag)
2000 (/= 0 (logand flags flag)))
2001
2002 (defsubst js2-flag-not-set-p (flags flag)
2003 (zerop (logand flags flag)))
2004
2005 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2006 "Evaluate BODY with the _ character set to be word-syntax."
2007 (declare (indent 0) (debug t))
2008 (let ((old-syntax (make-symbol "old-syntax")))
2009 `(let ((,old-syntax (string (char-syntax ?_))))
2010 (unwind-protect
2011 (progn
2012 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2013 ,@body)
2014 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2015
2016 (defsubst js2-char-uppercase-p (c)
2017 "Return t if C is an uppercase character.
2018 Handles unicode and latin chars properly."
2019 (/= c (downcase c)))
2020
2021 (defsubst js2-char-lowercase-p (c)
2022 "Return t if C is an uppercase character.
2023 Handles unicode and latin chars properly."
2024 (/= c (upcase c)))
2025
2026 ;;; AST struct and function definitions
2027
2028 ;; flags for ast node property 'member-type (used for e4x operators)
2029 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2030 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2031 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2032
2033 (defsubst js2-relpos (pos anchor)
2034 "Convert POS to be relative to ANCHOR.
2035 If POS is nil, returns nil."
2036 (and pos (- pos anchor)))
2037
2038 (defsubst js2-make-pad (indent)
2039 (if (zerop indent)
2040 ""
2041 (make-string (* indent js2-basic-offset) ? )))
2042
2043 (defsubst js2-visit-ast (node callback)
2044 "Visit every node in ast NODE with visitor CALLBACK.
2045
2046 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2047 called twice: once to visit the node, and again after all the node's
2048 children have been processed. The END-P argument is nil on the first
2049 call and non-nil on the second call. The return value of the callback
2050 affects the traversal: if non-nil, the children of NODE are processed.
2051 If the callback returns nil, or if the node has no children, then the
2052 callback is called immediately with a non-nil END-P argument.
2053
2054 The node traversal is approximately lexical-order, although there
2055 are currently no guarantees around this."
2056 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2057 ;; visit the node
2058 (when (funcall callback node nil)
2059 ;; visit the kids
2060 (cond
2061 ((eq vfunc 'js2-visit-none)
2062 nil) ; don't even bother calling it
2063 ;; Each AST node type has to define a `js2-visitor' function
2064 ;; that takes a node and a callback, and calls `js2-visit-ast'
2065 ;; on each child of the node.
2066 (vfunc
2067 (funcall vfunc node callback))
2068 (t
2069 (error "%s does not define a visitor-traversal function"
2070 (aref node 0)))))
2071 ;; call the end-visit
2072 (funcall callback node t)))
2073
2074 (defstruct (js2-node
2075 (:constructor nil)) ; abstract
2076 "Base AST node type."
2077 (type -1) ; token type
2078 (pos -1) ; start position of this AST node in parsed input
2079 (len 1) ; num characters spanned by the node
2080 props ; optional node property list (an alist)
2081 parent) ; link to parent node; null for root
2082
2083 (defsubst js2-node-get-prop (node prop &optional default)
2084 (or (cadr (assoc prop (js2-node-props node))) default))
2085
2086 (defsubst js2-node-set-prop (node prop value)
2087 (setf (js2-node-props node)
2088 (cons (list prop value) (js2-node-props node))))
2089
2090 (defsubst js2-fixup-starts (n nodes)
2091 "Adjust the start positions of NODES to be relative to N.
2092 Any node in the list may be nil, for convenience."
2093 (dolist (node nodes)
2094 (when node
2095 (setf (js2-node-pos node) (- (js2-node-pos node)
2096 (js2-node-pos n))))))
2097
2098 (defsubst js2-node-add-children (parent &rest nodes)
2099 "Set parent node of NODES to PARENT, and return PARENT.
2100 Does nothing if we're not recording parent links.
2101 If any given node in NODES is nil, doesn't record that link."
2102 (js2-fixup-starts parent nodes)
2103 (dolist (node nodes)
2104 (and node
2105 (setf (js2-node-parent node) parent))))
2106
2107 ;; Non-recursive since it's called a frightening number of times.
2108 (defsubst js2-node-abs-pos (n)
2109 (let ((pos (js2-node-pos n)))
2110 (while (setq n (js2-node-parent n))
2111 (setq pos (+ pos (js2-node-pos n))))
2112 pos))
2113
2114 (defsubst js2-node-abs-end (n)
2115 "Return absolute buffer position of end of N."
2116 (+ (js2-node-abs-pos n) (js2-node-len n)))
2117
2118 ;; It's important to make sure block nodes have a lisp list for the
2119 ;; child nodes, to limit printing recursion depth in an AST that
2120 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2121 ;; a sufficiently large vector tree.
2122
2123 (defstruct (js2-block-node
2124 (:include js2-node)
2125 (:constructor nil)
2126 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2127 (pos js2-token-beg)
2128 len
2129 props
2130 kids)))
2131 "A block of statements."
2132 kids) ; a lisp list of the child statement nodes
2133
2134 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2135 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2136
2137 (defsubst js2-visit-block (ast callback)
2138 "Visit the `js2-block-node' children of AST."
2139 (dolist (kid (js2-block-node-kids ast))
2140 (js2-visit-ast kid callback)))
2141
2142 (defun js2-print-block (n i)
2143 (let ((pad (js2-make-pad i)))
2144 (insert pad "{\n")
2145 (dolist (kid (js2-block-node-kids n))
2146 (js2-print-ast kid (1+ i)))
2147 (insert pad "}")))
2148
2149 (defstruct (js2-scope
2150 (:include js2-block-node)
2151 (:constructor nil)
2152 (:constructor make-js2-scope (&key (type js2-BLOCK)
2153 (pos js2-token-beg)
2154 len
2155 kids)))
2156 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2157 ;; I don't have one of those handy, so I'll use an alist for now.
2158 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2159 ;; and is much lighter-weight to construct (both CPU and mem).
2160 ;; The keys are interned strings (symbols) for faster lookup.
2161 ;; Should switch to hybrid alist/hashtable eventually.
2162 symbol-table ; an alist of (symbol . js2-symbol)
2163 parent-scope ; a `js2-scope'
2164 top) ; top-level `js2-scope' (script/function)
2165
2166 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-none)
2167 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2168
2169 (defun js2-scope-set-parent-scope (scope parent)
2170 (setf (js2-scope-parent-scope scope) parent
2171 (js2-scope-top scope) (if (null parent)
2172 scope
2173 (js2-scope-top parent))))
2174
2175 (defun js2-node-get-enclosing-scope (node)
2176 "Return the innermost `js2-scope' node surrounding NODE.
2177 Returns nil if there is no enclosing scope node."
2178 (let ((parent (js2-node-parent node)))
2179 (while (not (js2-scope-p parent))
2180 (setq parent (js2-node-parent parent)))
2181 parent))
2182
2183 (defun js2-get-defining-scope (scope name)
2184 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2185 Returns `js2-scope' in which NAME is defined, or nil if not found."
2186 (let ((sym (if (symbolp name)
2187 name
2188 (intern name)))
2189 table
2190 result
2191 (continue t))
2192 (while (and scope continue)
2193 (if (and (setq table (js2-scope-symbol-table scope))
2194 (assq sym table))
2195 (setq continue nil
2196 result scope)
2197 (setq scope (js2-scope-parent-scope scope))))
2198 result))
2199
2200 (defsubst js2-scope-get-symbol (scope name)
2201 "Return symbol table entry for NAME in SCOPE.
2202 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2203 (and (js2-scope-symbol-table scope)
2204 (cdr (assq (if (symbolp name)
2205 name
2206 (intern name))
2207 (js2-scope-symbol-table scope)))))
2208
2209 (defsubst js2-scope-put-symbol (scope name symbol)
2210 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2211 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2212 (let* ((table (js2-scope-symbol-table scope))
2213 (sym (if (symbolp name) name (intern name)))
2214 (entry (assq sym table)))
2215 (if entry
2216 (setcdr entry symbol)
2217 (push (cons sym symbol)
2218 (js2-scope-symbol-table scope)))))
2219
2220 (defstruct (js2-symbol
2221 (:constructor nil)
2222 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2223 "A symbol table entry."
2224 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2225 ;; js2-LET, or js2-CONST
2226 decl-type
2227 name ; string
2228 ast-node) ; a `js2-node'
2229
2230 (defstruct (js2-error-node
2231 (:include js2-node)
2232 (:constructor nil) ; silence emacs21 byte-compiler
2233 (:constructor make-js2-error-node (&key (type js2-ERROR)
2234 (pos js2-token-beg)
2235 len)))
2236 "AST node representing a parse error.")
2237
2238 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2239 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2240
2241 (defstruct (js2-script-node
2242 (:include js2-scope)
2243 (:constructor nil)
2244 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2245 (pos js2-token-beg)
2246 len
2247 var-decls
2248 fun-decls)))
2249 functions ; lisp list of nested functions
2250 regexps ; lisp list of (string . flags)
2251 symbols ; alist (every symbol gets unique index)
2252 (param-count 0)
2253 var-names ; vector of string names
2254 consts ; bool-vector matching var-decls
2255 (temp-number 0)) ; for generating temp variables
2256
2257 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2258 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2259
2260 (defun js2-print-script (node indent)
2261 (dolist (kid (js2-block-node-kids node))
2262 (js2-print-ast kid indent)))
2263
2264 (defstruct (js2-ast-root
2265 (:include js2-script-node)
2266 (:constructor nil)
2267 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2268 (pos js2-token-beg)
2269 len
2270 buffer)))
2271 "The root node of a js2 AST."
2272 buffer ; the source buffer from which the code was parsed
2273 comments ; a lisp list of comments, ordered by start position
2274 errors ; a lisp list of errors found during parsing
2275 warnings ; a lisp list of warnings found during parsing
2276 node-count) ; number of nodes in the tree, including the root
2277
2278 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2279 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2280
2281 (defun js2-visit-ast-root (ast callback)
2282 (dolist (kid (js2-ast-root-kids ast))
2283 (js2-visit-ast kid callback))
2284 (dolist (comment (js2-ast-root-comments ast))
2285 (js2-visit-ast comment callback)))
2286
2287 (defstruct (js2-comment-node
2288 (:include js2-node)
2289 (:constructor nil)
2290 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2291 (pos js2-token-beg)
2292 len
2293 (format js2-ts-comment-type))))
2294 format) ; 'line, 'block, 'jsdoc or 'html
2295
2296 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2297 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2298
2299 (defun js2-print-comment (n i)
2300 ;; We really ought to link end-of-line comments to their nodes.
2301 ;; Or maybe we could add a new comment type, 'endline.
2302 (insert (js2-make-pad i)
2303 (js2-node-string n)))
2304
2305 (defstruct (js2-expr-stmt-node
2306 (:include js2-node)
2307 (:constructor nil)
2308 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2309 (pos js2-ts-cursor)
2310 len
2311 expr)))
2312 "An expression statement."
2313 expr)
2314
2315 (defsubst js2-expr-stmt-node-set-has-result (node)
2316 "Change the NODE type to `js2-EXPR_RESULT'. Used for code generation."
2317 (setf (js2-node-type node) js2-EXPR_RESULT))
2318
2319 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2320 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2321
2322 (defun js2-visit-expr-stmt-node (n v)
2323 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2324
2325 (defun js2-print-expr-stmt-node (n indent)
2326 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2327 (insert ";\n"))
2328
2329 (defstruct (js2-loop-node
2330 (:include js2-scope)
2331 (:constructor nil))
2332 "Abstract supertype of loop nodes."
2333 body ; a `js2-block-node'
2334 lp ; position of left-paren, nil if omitted
2335 rp) ; position of right-paren, nil if omitted
2336
2337 (defstruct (js2-do-node
2338 (:include js2-loop-node)
2339 (:constructor nil)
2340 (:constructor make-js2-do-node (&key (type js2-DO)
2341 (pos js2-token-beg)
2342 len
2343 body
2344 condition
2345 while-pos
2346 lp
2347 rp)))
2348 "AST node for do-loop."
2349 condition ; while (expression)
2350 while-pos) ; buffer position of 'while' keyword
2351
2352 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2353 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2354
2355 (defun js2-visit-do-node (n v)
2356 (js2-visit-ast (js2-do-node-body n) v)
2357 (js2-visit-ast (js2-do-node-condition n) v))
2358
2359 (defun js2-print-do-node (n i)
2360 (let ((pad (js2-make-pad i)))
2361 (insert pad "do {\n")
2362 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2363 (js2-print-ast kid (1+ i)))
2364 (insert pad "} while (")
2365 (js2-print-ast (js2-do-node-condition n) 0)
2366 (insert ");\n")))
2367
2368 (defstruct (js2-while-node
2369 (:include js2-loop-node)
2370 (:constructor nil)
2371 (:constructor make-js2-while-node (&key (type js2-WHILE)
2372 (pos js2-token-beg)
2373 len
2374 body
2375 condition
2376 lp
2377 rp)))
2378 "AST node for while-loop."
2379 condition) ; while-condition
2380
2381 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2382 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2383
2384 (defun js2-visit-while-node (n v)
2385 (js2-visit-ast (js2-while-node-condition n) v)
2386 (js2-visit-ast (js2-while-node-body n) v))
2387
2388 (defun js2-print-while-node (n i)
2389 (let ((pad (js2-make-pad i)))
2390 (insert pad "while (")
2391 (js2-print-ast (js2-while-node-condition n) 0)
2392 (insert ") {\n")
2393 (js2-print-body (js2-while-node-body n) (1+ i))
2394 (insert pad "}\n")))
2395
2396 (defstruct (js2-for-node
2397 (:include js2-loop-node)
2398 (:constructor nil)
2399 (:constructor make-js2-for-node (&key (type js2-FOR)
2400 (pos js2-ts-cursor)
2401 len
2402 body
2403 init
2404 condition
2405 update
2406 lp
2407 rp)))
2408 "AST node for a C-style for-loop."
2409 init ; initialization expression
2410 condition ; loop condition
2411 update) ; update clause
2412
2413 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2414 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2415
2416 (defun js2-visit-for-node (n v)
2417 (js2-visit-ast (js2-for-node-init n) v)
2418 (js2-visit-ast (js2-for-node-condition n) v)
2419 (js2-visit-ast (js2-for-node-update n) v)
2420 (js2-visit-ast (js2-for-node-body n) v))
2421
2422 (defun js2-print-for-node (n i)
2423 (let ((pad (js2-make-pad i)))
2424 (insert pad "for (")
2425 (js2-print-ast (js2-for-node-init n) 0)
2426 (insert "; ")
2427 (js2-print-ast (js2-for-node-condition n) 0)
2428 (insert "; ")
2429 (js2-print-ast (js2-for-node-update n) 0)
2430 (insert ") {\n")
2431 (js2-print-body (js2-for-node-body n) (1+ i))
2432 (insert pad "}\n")))
2433
2434 (defstruct (js2-for-in-node
2435 (:include js2-loop-node)
2436 (:constructor nil)
2437 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2438 (pos js2-ts-cursor)
2439 len
2440 body
2441 iterator
2442 object
2443 in-pos
2444 each-pos
2445 foreach-p
2446 lp
2447 rp)))
2448 "AST node for a for..in loop."
2449 iterator ; [var] foo in ...
2450 object ; object over which we're iterating
2451 in-pos ; buffer position of 'in' keyword
2452 each-pos ; buffer position of 'each' keyword, if foreach-p
2453 foreach-p) ; t if it's a for-each loop
2454
2455 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2456 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2457
2458 (defun js2-visit-for-in-node (n v)
2459 (js2-visit-ast (js2-for-in-node-iterator n) v)
2460 (js2-visit-ast (js2-for-in-node-object n) v)
2461 (js2-visit-ast (js2-for-in-node-body n) v))
2462
2463 (defun js2-print-for-in-node (n i)
2464 (let ((pad (js2-make-pad i))
2465 (foreach (js2-for-in-node-foreach-p n)))
2466 (insert pad "for ")
2467 (if foreach
2468 (insert "each "))
2469 (insert "(")
2470 (js2-print-ast (js2-for-in-node-iterator n) 0)
2471 (insert " in ")
2472 (js2-print-ast (js2-for-in-node-object n) 0)
2473 (insert ") {\n")
2474 (js2-print-body (js2-for-in-node-body n) (1+ i))
2475 (insert pad "}\n")))
2476
2477 (defstruct (js2-return-node
2478 (:include js2-node)
2479 (:constructor nil)
2480 (:constructor make-js2-return-node (&key (type js2-RETURN)
2481 (pos js2-ts-cursor)
2482 len
2483 retval)))
2484 "AST node for a return statement."
2485 retval) ; expression to return, or 'undefined
2486
2487 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2488 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2489
2490 (defun js2-visit-return-node (n v)
2491 (if (js2-return-node-retval n)
2492 (js2-visit-ast (js2-return-node-retval n) v)))
2493
2494 (defun js2-print-return-node (n i)
2495 (insert (js2-make-pad i) "return")
2496 (when (js2-return-node-retval n)
2497 (insert " ")
2498 (js2-print-ast (js2-return-node-retval n) 0))
2499 (insert ";\n"))
2500
2501 (defstruct (js2-if-node
2502 (:include js2-node)
2503 (:constructor nil)
2504 (:constructor make-js2-if-node (&key (type js2-IF)
2505 (pos js2-ts-cursor)
2506 len
2507 condition
2508 then-part
2509 else-pos
2510 else-part
2511 lp
2512 rp)))
2513 "AST node for an if-statement."
2514 condition ; expression
2515 then-part ; statement or block
2516 else-pos ; optional buffer position of 'else' keyword
2517 else-part ; optional statement or block
2518 lp ; position of left-paren, nil if omitted
2519 rp) ; position of right-paren, nil if omitted
2520
2521 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2522 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2523
2524 (defun js2-visit-if-node (n v)
2525 (js2-visit-ast (js2-if-node-condition n) v)
2526 (js2-visit-ast (js2-if-node-then-part n) v)
2527 (if (js2-if-node-else-part n)
2528 (js2-visit-ast (js2-if-node-else-part n) v)))
2529
2530 (defun js2-print-if-node (n i)
2531 (let ((pad (js2-make-pad i))
2532 (then-part (js2-if-node-then-part n))
2533 (else-part (js2-if-node-else-part n)))
2534 (insert pad "if (")
2535 (js2-print-ast (js2-if-node-condition n) 0)
2536 (insert ") {\n")
2537 (js2-print-body then-part (1+ i))
2538 (insert pad "}")
2539 (cond
2540 ((not else-part)
2541 (insert "\n"))
2542 ((js2-if-node-p else-part)
2543 (insert " else ")
2544 (js2-print-body else-part i))
2545 (t
2546 (insert " else {\n")
2547 (js2-print-body else-part (1+ i))
2548 (insert pad "}\n")))))
2549
2550 (defstruct (js2-try-node
2551 (:include js2-node)
2552 (:constructor nil)
2553 (:constructor make-js2-try-node (&key (type js2-TRY)
2554 (pos js2-ts-cursor)
2555 len
2556 try-block
2557 catch-clauses
2558 finally-block)))
2559 "AST node for a try-statement."
2560 try-block
2561 catch-clauses ; a lisp list of `js2-catch-node'
2562 finally-block) ; a `js2-finally-node'
2563
2564 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2565 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2566
2567 (defun js2-visit-try-node (n v)
2568 (js2-visit-ast (js2-try-node-try-block n) v)
2569 (dolist (clause (js2-try-node-catch-clauses n))
2570 (js2-visit-ast clause v))
2571 (if (js2-try-node-finally-block n)
2572 (js2-visit-ast (js2-try-node-finally-block n) v)))
2573
2574 (defun js2-print-try-node (n i)
2575 (let ((pad (js2-make-pad i))
2576 (catches (js2-try-node-catch-clauses n))
2577 (finally (js2-try-node-finally-block n)))
2578 (insert pad "try {\n")
2579 (js2-print-body (js2-try-node-try-block n) (1+ i))
2580 (insert pad "}")
2581 (when catches
2582 (dolist (catch catches)
2583 (js2-print-ast catch i)))
2584 (if finally
2585 (js2-print-ast finally i)
2586 (insert "\n"))))
2587
2588 (defstruct (js2-catch-node
2589 (:include js2-node)
2590 (:constructor nil)
2591 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2592 (pos js2-ts-cursor)
2593 len
2594 var-name
2595 guard-kwd
2596 guard-expr
2597 block
2598 lp
2599 rp)))
2600 "AST node for a catch clause."
2601 var-name ; a `js2-name-node'
2602 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2603 guard-expr ; catch condition, a `js2-node'
2604 block ; statements, a `js2-block-node'
2605 lp ; buffer position of left-paren, nil if omitted
2606 rp) ; buffer position of right-paren, nil if omitted
2607
2608 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2609 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2610
2611 (defun js2-visit-catch-node (n v)
2612 (js2-visit-ast (js2-catch-node-var-name n) v)
2613 (when (js2-catch-node-guard-kwd n)
2614 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2615 (js2-visit-ast (js2-catch-node-block n) v))
2616
2617 (defun js2-print-catch-node (n i)
2618 (let ((pad (js2-make-pad i))
2619 (guard-kwd (js2-catch-node-guard-kwd n))
2620 (guard-expr (js2-catch-node-guard-expr n)))
2621 (insert " catch (")
2622 (js2-print-ast (js2-catch-node-var-name n) 0)
2623 (when guard-kwd
2624 (insert " if ")
2625 (js2-print-ast guard-expr 0))
2626 (insert ") {\n")
2627 (js2-print-body (js2-catch-node-block n) (1+ i))
2628 (insert pad "}")))
2629
2630 (defstruct (js2-finally-node
2631 (:include js2-node)
2632 (:constructor nil)
2633 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2634 (pos js2-ts-cursor)
2635 len
2636 body)))
2637 "AST node for a finally clause."
2638 body) ; a `js2-node', often but not always a block node
2639
2640 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2641 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2642
2643 (defun js2-visit-finally-node (n v)
2644 (js2-visit-ast (js2-finally-node-body n) v))
2645
2646 (defun js2-print-finally-node (n i)
2647 (let ((pad (js2-make-pad i)))
2648 (insert " finally {\n")
2649 (js2-print-body (js2-finally-node-body n) (1+ i))
2650 (insert pad "}\n")))
2651
2652 (defstruct (js2-switch-node
2653 (:include js2-node)
2654 (:constructor nil)
2655 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2656 (pos js2-ts-cursor)
2657 len
2658 discriminant
2659 cases
2660 lp
2661 rp)))
2662 "AST node for a switch statement."
2663 discriminant ; a `js2-node' (switch expression)
2664 cases ; a lisp list of `js2-case-node'
2665 lp ; position of open-paren for discriminant, nil if omitted
2666 rp) ; position of close-paren for discriminant, nil if omitted
2667
2668 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2669 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2670
2671 (defun js2-visit-switch-node (n v)
2672 (js2-visit-ast (js2-switch-node-discriminant n) v)
2673 (dolist (c (js2-switch-node-cases n))
2674 (js2-visit-ast c v)))
2675
2676 (defun js2-print-switch-node (n i)
2677 (let ((pad (js2-make-pad i))
2678 (cases (js2-switch-node-cases n)))
2679 (insert pad "switch (")
2680 (js2-print-ast (js2-switch-node-discriminant n) 0)
2681 (insert ") {\n")
2682 (dolist (case cases)
2683 (js2-print-ast case i))
2684 (insert pad "}\n")))
2685
2686 (defstruct (js2-case-node
2687 (:include js2-block-node)
2688 (:constructor nil)
2689 (:constructor make-js2-case-node (&key (type js2-CASE)
2690 (pos js2-ts-cursor)
2691 len
2692 kids
2693 expr)))
2694 "AST node for a case clause of a switch statement."
2695 expr) ; the case expression (nil for default)
2696
2697 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2698 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2699
2700 (defun js2-visit-case-node (n v)
2701 (if (js2-case-node-expr n) ; nil for default: case
2702 (js2-visit-ast (js2-case-node-expr n) v))
2703 (js2-visit-block n v))
2704
2705 (defun js2-print-case-node (n i)
2706 (let ((pad (js2-make-pad i))
2707 (expr (js2-case-node-expr n)))
2708 (insert pad)
2709 (if (null expr)
2710 (insert "default:\n")
2711 (insert "case ")
2712 (js2-print-ast expr 0)
2713 (insert ":\n"))
2714 (dolist (kid (js2-case-node-kids n))
2715 (js2-print-ast kid (1+ i)))))
2716
2717 (defstruct (js2-throw-node
2718 (:include js2-node)
2719 (:constructor nil)
2720 (:constructor make-js2-throw-node (&key (type js2-THROW)
2721 (pos js2-ts-cursor)
2722 len
2723 expr)))
2724 "AST node for a throw statement."
2725 expr) ; the expression to throw
2726
2727 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2728 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2729
2730 (defun js2-visit-throw-node (n v)
2731 (js2-visit-ast (js2-throw-node-expr n) v))
2732
2733 (defun js2-print-throw-node (n i)
2734 (insert (js2-make-pad i) "throw ")
2735 (js2-print-ast (js2-throw-node-expr n) 0)
2736 (insert ";\n"))
2737
2738 (defstruct (js2-with-node
2739 (:include js2-node)
2740 (:constructor nil)
2741 (:constructor make-js2-with-node (&key (type js2-WITH)
2742 (pos js2-ts-cursor)
2743 len
2744 object
2745 body
2746 lp
2747 rp)))
2748 "AST node for a with-statement."
2749 object
2750 body
2751 lp ; buffer position of left-paren around object, nil if omitted
2752 rp) ; buffer position of right-paren around object, nil if omitted
2753
2754 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2755 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2756
2757 (defun js2-visit-with-node (n v)
2758 (js2-visit-ast (js2-with-node-object n) v)
2759 (js2-visit-ast (js2-with-node-body n) v))
2760
2761 (defun js2-print-with-node (n i)
2762 (let ((pad (js2-make-pad i)))
2763 (insert pad "with (")
2764 (js2-print-ast (js2-with-node-object n) 0)
2765 (insert ") {\n")
2766 (js2-print-body (js2-with-node-body n) (1+ i))
2767 (insert pad "}\n")))
2768
2769 (defstruct (js2-label-node
2770 (:include js2-node)
2771 (:constructor nil)
2772 (:constructor make-js2-label-node (&key (type js2-LABEL)
2773 (pos js2-ts-cursor)
2774 len
2775 name)))
2776 "AST node for a statement label or case label."
2777 name ; a string
2778 loop) ; for validating and code-generating continue-to-label
2779
2780 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2781 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2782
2783 (defun js2-print-label (n i)
2784 (insert (js2-make-pad i)
2785 (js2-label-node-name n)
2786 ":\n"))
2787
2788 (defstruct (js2-labeled-stmt-node
2789 (:include js2-node)
2790 (:constructor nil)
2791 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2792 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2793 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2794 (pos js2-ts-cursor)
2795 len
2796 labels
2797 stmt)))
2798 "AST node for a statement with one or more labels.
2799 Multiple labels for a statement are collapsed into the labels field."
2800 labels ; lisp list of `js2-label-node'
2801 stmt) ; the statement these labels are for
2802
2803 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2804 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2805
2806 (defun js2-get-label-by-name (lbl-stmt name)
2807 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2808 Returns nil if no such label is in the list."
2809 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2810 result)
2811 (while (and label-list (not result))
2812 (if (string= (js2-label-node-name (car label-list)) name)
2813 (setq result (car label-list))
2814 (setq label-list (cdr label-list))))
2815 result))
2816
2817 (defun js2-visit-labeled-stmt (n v)
2818 (dolist (label (js2-labeled-stmt-node-labels n))
2819 (js2-visit-ast label v))
2820 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2821
2822 (defun js2-print-labeled-stmt (n i)
2823 (dolist (label (js2-labeled-stmt-node-labels n))
2824 (js2-print-ast label i))
2825 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2826
2827 (defun js2-labeled-stmt-node-contains (node label)
2828 "Return t if NODE contains LABEL in its label set.
2829 NODE is a `js2-labels-node'. LABEL is an identifier."
2830 (loop for nl in (js2-labeled-stmt-node-labels node)
2831 if (string= label (js2-label-node-name nl))
2832 return t
2833 finally return nil))
2834
2835 (defsubst js2-labeled-stmt-node-add-label (node label)
2836 "Add a `js2-label-node' to the label set for this statement."
2837 (setf (js2-labeled-stmt-node-labels node)
2838 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2839
2840 (defstruct (js2-jump-node
2841 (:include js2-node)
2842 (:constructor nil))
2843 "Abstract supertype of break and continue nodes."
2844 label ; `js2-name-node' for location of label identifier, if present
2845 target) ; target js2-labels-node or loop/switch statement
2846
2847 (defun js2-visit-jump-node (n v)
2848 ;; we don't visit the target, since it's a back-link
2849 (if (js2-jump-node-label n)
2850 (js2-visit-ast (js2-jump-node-label n) v)))
2851
2852 (defstruct (js2-break-node
2853 (:include js2-jump-node)
2854 (:constructor nil)
2855 (:constructor make-js2-break-node (&key (type js2-BREAK)
2856 (pos js2-ts-cursor)
2857 len
2858 label
2859 target)))
2860 "AST node for a break statement.
2861 The label field is a `js2-name-node', possibly nil, for the named label
2862 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2863 is the target of the break - a label node or enclosing loop/switch statement.")
2864
2865 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2866 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2867
2868 (defun js2-print-break-node (n i)
2869 (insert (js2-make-pad i) "break")
2870 (when (js2-break-node-label n)
2871 (insert " ")
2872 (js2-print-ast (js2-break-node-label n) 0))
2873 (insert ";\n"))
2874
2875 (defstruct (js2-continue-node
2876 (:include js2-jump-node)
2877 (:constructor nil)
2878 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2879 (pos js2-ts-cursor)
2880 len
2881 label
2882 target)))
2883 "AST node for a continue statement.
2884 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2885 It is nil if continue specifies no label. The target field is the jump target:
2886 a `js2-label-node' or the innermost enclosing loop.")
2887
2888 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2889 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2890
2891 (defun js2-print-continue-node (n i)
2892 (insert (js2-make-pad i) "continue")
2893 (when (js2-continue-node-label n)
2894 (insert " ")
2895 (js2-print-ast (js2-continue-node-label n) 0))
2896 (insert ";\n"))
2897
2898 (defstruct (js2-function-node
2899 (:include js2-script-node)
2900 (:constructor nil)
2901 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2902 (pos js2-ts-cursor)
2903 len
2904 (ftype 'FUNCTION)
2905 (form 'FUNCTION_STATEMENT)
2906 (name "")
2907 params
2908 body
2909 lp
2910 rp)))
2911 "AST node for a function declaration.
2912 The `params' field is a lisp list of nodes. Each node is either a simple
2913 `js2-name-node', or if it's a destructuring-assignment parameter, a
2914 `js2-array-node' or `js2-object-node'."
2915 ftype ; FUNCTION, GETTER or SETTER
2916 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2917 name ; function name (a `js2-name-node', or nil if anonymous)
2918 params ; a lisp list of destructuring forms or simple name nodes
2919 body ; a `js2-block-node' or expression node (1.8 only)
2920 lp ; position of arg-list open-paren, or nil if omitted
2921 rp ; position of arg-list close-paren, or nil if omitted
2922 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2923 needs-activation ; t if we need an activation object for this frame
2924 is-generator ; t if this function contains a yield
2925 member-expr) ; nonstandard Ecma extension from Rhino
2926
2927 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2928 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2929
2930 (defun js2-visit-function-node (n v)
2931 (if (js2-function-node-name n)
2932 (js2-visit-ast (js2-function-node-name n) v))
2933 (dolist (p (js2-function-node-params n))
2934 (js2-visit-ast p v))
2935 (js2-visit-ast (js2-function-node-body n) v))
2936
2937 (defun js2-print-function-node (n i)
2938 (let ((pad (js2-make-pad i))
2939 (getter (js2-node-get-prop n 'GETTER_SETTER))
2940 (name (js2-function-node-name n))
2941 (params (js2-function-node-params n))
2942 (body (js2-function-node-body n))
2943 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2944 (unless getter
2945 (insert pad "function"))
2946 (when name
2947 (insert " ")
2948 (js2-print-ast name 0))
2949 (insert "(")
2950 (loop with len = (length params)
2951 for param in params
2952 for count from 1
2953 do
2954 (js2-print-ast param 0)
2955 (if (< count len)
2956 (insert ", ")))
2957 (insert ") {")
2958 (unless expr
2959 (insert "\n"))
2960 ;; TODO: fix this to be smarter about indenting, etc.
2961 (js2-print-body body (1+ i))
2962 (insert pad "}")
2963 (unless expr
2964 (insert "\n"))))
2965
2966 (defsubst js2-function-name (node)
2967 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2968 (and (js2-function-node-name node)
2969 (js2-name-node-name (js2-function-node-name node))))
2970
2971 ;; Having this be an expression node makes it more flexible.
2972 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2973 ;; that work better if you assume it's an expression. Whenever we have
2974 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2975 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2976 (defstruct (js2-var-decl-node
2977 (:include js2-node)
2978 (:constructor nil)
2979 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2980 (pos js2-token-beg)
2981 len
2982 kids
2983 decl-type)))
2984 "AST node for a variable declaration list (VAR, CONST or LET).
2985 The node bounds differ depending on the declaration type. For VAR or
2986 CONST declarations, the bounds include the var/const keyword. For LET
2987 declarations, the node begins at the position of the first child."
2988 kids ; a lisp list of `js2-var-init-node' structs.
2989 decl-type) ; js2-VAR, js2-CONST or js2-LET
2990
2991 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2992 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2993
2994 (defun js2-visit-var-decl (n v)
2995 (dolist (kid (js2-var-decl-node-kids n))
2996 (js2-visit-ast kid v)))
2997
2998 (defun js2-print-var-decl (n i)
2999 (let ((pad (js2-make-pad i))
3000 (tt (js2-var-decl-node-decl-type n)))
3001 (insert pad)
3002 (insert (cond
3003 ((= tt js2-VAR) "var ")
3004 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3005 ((= tt js2-CONST) "const ")
3006 (t
3007 (error "malformed var-decl node"))))
3008 (loop with kids = (js2-var-decl-node-kids n)
3009 with len = (length kids)
3010 for kid in kids
3011 for count from 1
3012 do
3013 (js2-print-ast kid 0)
3014 (if (< count len)
3015 (insert ", ")))))
3016
3017 (defstruct (js2-var-init-node
3018 (:include js2-node)
3019 (:constructor nil)
3020 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3021 (pos js2-ts-cursor)
3022 len
3023 target
3024 initializer)))
3025 "AST node for a variable declaration.
3026 The type field will be js2-CONST for a const decl."
3027 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3028 initializer) ; initializer expression, a `js2-node'
3029
3030 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3031 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3032
3033 (defun js2-visit-var-init-node (n v)
3034 (js2-visit-ast (js2-var-init-node-target n) v)
3035 (if (js2-var-init-node-initializer n)
3036 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3037
3038 (defun js2-print-var-init-node (n i)
3039 (let ((pad (js2-make-pad i))
3040 (name (js2-var-init-node-target n))
3041 (init (js2-var-init-node-initializer n)))
3042 (insert pad)
3043 (js2-print-ast name 0)
3044 (when init
3045 (insert " = ")
3046 (js2-print-ast init 0))))
3047
3048 (defstruct (js2-cond-node
3049 (:include js2-node)
3050 (:constructor nil)
3051 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3052 (pos js2-ts-cursor)
3053 len
3054 test-expr
3055 true-expr
3056 false-expr
3057 q-pos
3058 c-pos)))
3059 "AST node for the ternary operator"
3060 test-expr
3061 true-expr
3062 false-expr
3063 q-pos ; buffer position of ?
3064 c-pos) ; buffer position of :
3065
3066 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3067 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3068
3069 (defun js2-visit-cond-node (n v)
3070 (js2-visit-ast (js2-cond-node-test-expr n) v)
3071 (js2-visit-ast (js2-cond-node-true-expr n) v)
3072 (js2-visit-ast (js2-cond-node-false-expr n) v))
3073
3074 (defun js2-print-cond-node (n i)
3075 (let ((pad (js2-make-pad i)))
3076 (insert pad)
3077 (js2-print-ast (js2-cond-node-test-expr n) 0)
3078 (insert " ? ")
3079 (js2-print-ast (js2-cond-node-true-expr n) 0)
3080 (insert " : ")
3081 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3082
3083 (defstruct (js2-infix-node
3084 (:include js2-node)
3085 (:constructor nil)
3086 (:constructor make-js2-infix-node (&key type
3087 (pos js2-ts-cursor)
3088 len
3089 op-pos
3090 left
3091 right)))
3092 "Represents infix expressions.
3093 Includes assignment ops like `|=', and the comma operator.
3094 The type field inherited from `js2-node' holds the operator."
3095 op-pos ; buffer position where operator begins
3096 left ; any `js2-node'
3097 right) ; any `js2-node'
3098
3099 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3100 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3101
3102 (defun js2-visit-infix-node (n v)
3103 (when (js2-infix-node-left n)
3104 (js2-visit-ast (js2-infix-node-left n) v))
3105 (when (js2-infix-node-right n)
3106 (js2-visit-ast (js2-infix-node-right n) v)))
3107
3108 (defconst js2-operator-tokens
3109 (let ((table (make-hash-table :test 'eq))
3110 (tokens
3111 (list (cons js2-IN "in")
3112 (cons js2-TYPEOF "typeof")
3113 (cons js2-INSTANCEOF "instanceof")
3114 (cons js2-DELPROP "delete")
3115 (cons js2-COMMA ",")
3116 (cons js2-COLON ":")
3117 (cons js2-OR "||")
3118 (cons js2-AND "&&")
3119 (cons js2-INC "++")
3120 (cons js2-DEC "--")
3121 (cons js2-BITOR "|")
3122 (cons js2-BITXOR "^")
3123 (cons js2-BITAND "&")
3124 (cons js2-EQ "==")
3125 (cons js2-NE "!=")
3126 (cons js2-LT "<")
3127 (cons js2-LE "<=")
3128 (cons js2-GT ">")
3129 (cons js2-GE ">=")
3130 (cons js2-LSH "<<")
3131 (cons js2-RSH ">>")
3132 (cons js2-URSH ">>>")
3133 (cons js2-ADD "+") ; infix plus
3134 (cons js2-SUB "-") ; infix minus
3135 (cons js2-MUL "*")
3136 (cons js2-DIV "/")
3137 (cons js2-MOD "%")
3138 (cons js2-NOT "!")
3139 (cons js2-BITNOT "~")
3140 (cons js2-POS "+") ; unary plus
3141 (cons js2-NEG "-") ; unary minus
3142 (cons js2-SHEQ "===") ; shallow equality
3143 (cons js2-SHNE "!==") ; shallow inequality
3144 (cons js2-ASSIGN "=")
3145 (cons js2-ASSIGN_BITOR "|=")
3146 (cons js2-ASSIGN_BITXOR "^=")
3147 (cons js2-ASSIGN_BITAND "&=")
3148 (cons js2-ASSIGN_LSH "<<=")
3149 (cons js2-ASSIGN_RSH ">>=")
3150 (cons js2-ASSIGN_URSH ">>>=")
3151 (cons js2-ASSIGN_ADD "+=")
3152 (cons js2-ASSIGN_SUB "-=")
3153 (cons js2-ASSIGN_MUL "*=")
3154 (cons js2-ASSIGN_DIV "/=")
3155 (cons js2-ASSIGN_MOD "%="))))
3156 (loop for (k . v) in tokens do
3157 (puthash k v table))
3158 table))
3159
3160 (defun js2-print-infix-node (n i)
3161 (let* ((tt (js2-node-type n))
3162 (op (gethash tt js2-operator-tokens)))
3163 (unless op
3164 (error "unrecognized infix operator %s" (js2-node-type n)))
3165 (insert (js2-make-pad i))
3166 (js2-print-ast (js2-infix-node-left n) 0)
3167 (unless (= tt js2-COMMA)
3168 (insert " "))
3169 (insert op)
3170 (insert " ")
3171 (js2-print-ast (js2-infix-node-right n) 0)))
3172
3173 (defstruct (js2-assign-node
3174 (:include js2-infix-node)
3175 (:constructor nil)
3176 (:constructor make-js2-assign-node (&key type
3177 (pos js2-ts-cursor)
3178 len
3179 op-pos
3180 left
3181 right)))
3182 "Represents any assignment.
3183 The type field holds the actual assignment operator.")
3184
3185 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3186 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3187
3188 (defstruct (js2-unary-node
3189 (:include js2-node)
3190 (:constructor nil)
3191 (:constructor make-js2-unary-node (&key type ; required
3192 (pos js2-ts-cursor)
3193 len
3194 operand)))
3195 "AST node type for unary operator nodes.
3196 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3197 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3198 property is added if the operator follows the operand."
3199 operand) ; a `js2-node' expression
3200
3201 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3202 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3203
3204 (defun js2-visit-unary-node (n v)
3205 (js2-visit-ast (js2-unary-node-operand n) v))
3206
3207 (defun js2-print-unary-node (n i)
3208 (let* ((tt (js2-node-type n))
3209 (op (gethash tt js2-operator-tokens))
3210 (postfix (js2-node-get-prop n 'postfix)))
3211 (unless op
3212 (error "unrecognized unary operator %s" tt))
3213 (insert (js2-make-pad i))
3214 (unless postfix
3215 (insert op))
3216 (if (or (= tt js2-TYPEOF)
3217 (= tt js2-DELPROP))
3218 (insert " "))
3219 (js2-print-ast (js2-unary-node-operand n) 0)
3220 (when postfix
3221 (insert op))))
3222
3223 (defstruct (js2-let-node
3224 (:include js2-scope)
3225 (:constructor nil)
3226 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3227 (pos js2-token-beg)
3228 len
3229 vars
3230 body
3231 lp
3232 rp)))
3233 "AST node for a let expression or a let statement.
3234 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3235 vars ; a `js2-var-decl-node'
3236 body ; a `js2-node' representing the expression or body block
3237 lp
3238 rp)
3239
3240 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3241 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3242
3243 (defun js2-visit-let-node (n v)
3244 (when (js2-let-node-vars n)
3245 (js2-visit-ast (js2-let-node-vars n) v))
3246 (when (js2-let-node-body n)
3247 (js2-visit-ast (js2-let-node-body n) v)))
3248
3249 (defun js2-print-let-node (n i)
3250 (insert (js2-make-pad i) "let (")
3251 (js2-print-ast (js2-let-node-vars n) 0)
3252 (insert ") ")
3253 (js2-print-ast (js2-let-node-body n) i))
3254
3255 (defstruct (js2-keyword-node
3256 (:include js2-node)
3257 (:constructor nil)
3258 (:constructor make-js2-keyword-node (&key type
3259 (pos js2-token-beg)
3260 (len (- js2-ts-cursor pos)))))
3261 "AST node representing a literal keyword such as `null'.
3262 Used for `null', `this', `true', `false' and `debugger'.
3263 The node type is set to js2-NULL, js2-THIS, etc.")
3264
3265 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3266 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3267
3268 (defun js2-print-keyword-node (n i)
3269 (insert (js2-make-pad i)
3270 (let ((tt (js2-node-type n)))
3271 (cond
3272 ((= tt 'js2-THIS) "this")
3273 ((= tt 'js2-NULL) "null")
3274 ((= tt 'js2-TRUE) "true")
3275 ((= tt 'js2-FALSE) "false")
3276 ((= tt 'js2-DEBUGGER) "debugger")
3277 (t (error "Invalid keyword literal type: %d" tt))))))
3278
3279 (defsubst js2-this-node-p (node)
3280 "Return t if this NODE is a `js2-literal-node' of type js2-THIS."
3281 (eq (js2-node-type node) js2-THIS))
3282
3283 (defstruct (js2-new-node
3284 (:include js2-node)
3285 (:constructor nil)
3286 (:constructor make-js2-new-node (&key (type js2-NEW)
3287 (pos js2-token-beg)
3288 len
3289 target
3290 args
3291 initializer
3292 lp
3293 rp)))
3294 "AST node for new-expression such as new Foo()."
3295 target ; an identifier or reference
3296 args ; a lisp list of argument nodes
3297 lp ; position of left-paren, nil if omitted
3298 rp ; position of right-paren, nil if omitted
3299 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3300
3301 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3302 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3303
3304 (defun js2-visit-new-node (n v)
3305 (js2-visit-ast (js2-new-node-target n) v)
3306 (dolist (arg (js2-new-node-args n))
3307 (js2-visit-ast arg v))
3308 (when (js2-new-node-initializer n)
3309 (js2-visit-ast (js2-new-node-initializer n) v)))
3310
3311 (defun js2-print-new-node (n i)
3312 (insert (js2-make-pad i) "new ")
3313 (js2-print-ast (js2-new-node-target n))
3314 (insert "(")
3315 (js2-print-list (js2-new-node-args n))
3316 (insert ")")
3317 (when (js2-new-node-initializer n)
3318 (insert " ")
3319 (js2-print-ast (js2-new-node-initializer n))))
3320
3321 (defstruct (js2-name-node
3322 (:include js2-node)
3323 (:constructor nil)
3324 (:constructor make-js2-name-node (&key (type js2-NAME)
3325 (pos js2-token-beg)
3326 (len (- js2-ts-cursor
3327 js2-token-beg))
3328 (name js2-ts-string))))
3329 "AST node for a JavaScript identifier"
3330 name ; a string
3331 scope) ; a `js2-scope' (optional, used for codegen)
3332
3333 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3334 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3335
3336 (defun js2-print-name-node (n i)
3337 (insert (js2-make-pad i)
3338 (js2-name-node-name n)))
3339
3340 (defsubst js2-name-node-length (node)
3341 "Return identifier length of NODE, a `js2-name-node'.
3342 Returns 0 if NODE is nil or its identifier field is nil."
3343 (if node
3344 (length (js2-name-node-name node))
3345 0))
3346
3347 (defstruct (js2-number-node
3348 (:include js2-node)
3349 (:constructor nil)
3350 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3351 (pos js2-token-beg)
3352 (len (- js2-ts-cursor
3353 js2-token-beg))
3354 (value js2-ts-string)
3355 (num-value js2-ts-number))))
3356 "AST node for a number literal."
3357 value ; the original string, e.g. "6.02e23"
3358 num-value) ; the parsed number value
3359
3360 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3361 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3362
3363 (defun js2-print-number-node (n i)
3364 (insert (js2-make-pad i)
3365 (number-to-string (js2-number-node-value n))))
3366
3367 (defstruct (js2-regexp-node
3368 (:include js2-node)
3369 (:constructor nil)
3370 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3371 (pos js2-token-beg)
3372 (len (- js2-ts-cursor
3373 js2-token-beg))
3374 value
3375 flags)))
3376 "AST node for a regular expression literal."
3377 value ; the regexp string, without // delimiters
3378 flags) ; a string of flags, e.g. `mi'.
3379
3380 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3381 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3382
3383 (defun js2-print-regexp (n i)
3384 (insert (js2-make-pad i)
3385 "/"
3386 (js2-regexp-node-value n)
3387 "/")
3388 (if (js2-regexp-node-flags n)
3389 (insert (js2-regexp-node-flags n))))
3390
3391 (defstruct (js2-string-node
3392 (:include js2-node)
3393 (:constructor nil)
3394 (:constructor make-js2-string-node (&key (type js2-STRING)
3395 (pos js2-token-beg)
3396 (len (- js2-ts-cursor
3397 js2-token-beg))
3398 (value js2-ts-string))))
3399 "String literal.
3400 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3401 You can tell the quote type by looking at the first character."
3402 value) ; the characters of the string, including the quotes
3403
3404 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3405 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3406
3407 (defun js2-print-string-node (n i)
3408 (insert (js2-make-pad i)
3409 (js2-node-string n)))
3410
3411 (defstruct (js2-array-node
3412 (:include js2-node)
3413 (:constructor nil)
3414 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3415 (pos js2-ts-cursor)
3416 len
3417 elems)))
3418 "AST node for an array literal."
3419 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3420
3421 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3422 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3423
3424 (defun js2-visit-array-node (n v)
3425 (dolist (e (js2-array-node-elems n))
3426 (when e ; can be nil, e.g. [a, ,b]
3427 (js2-visit-ast e v))))
3428
3429 (defun js2-print-array-node (n i)
3430 (insert (js2-make-pad i) "[")
3431 (js2-print-list (js2-array-node-elems n))
3432 (insert "]"))
3433
3434 (defstruct (js2-object-node
3435 (:include js2-node)
3436 (:constructor nil)
3437 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3438 (pos js2-ts-cursor)
3439 len
3440 elems)))
3441 "AST node for an object literal expression."
3442 elems) ; a lisp list of `js2-object-prop-node'
3443
3444 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3445 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3446
3447 (defun js2-visit-object-node (n v)
3448 (dolist (e (js2-object-node-elems n))
3449 (js2-visit-ast e v)))
3450
3451 (defun js2-print-object-node (n i)
3452 (insert (js2-make-pad i) "{")
3453 (js2-print-list (js2-object-node-elems n))
3454 (insert "}"))
3455
3456 (defstruct (js2-object-prop-node
3457 (:include js2-infix-node)
3458 (:constructor nil)
3459 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3460 (pos js2-ts-cursor)
3461 len
3462 left
3463 right
3464 op-pos)))
3465 "AST node for an object literal prop:value entry.
3466 The `left' field is the property: a name node, string node or number node.
3467 The `right' field is a `js2-node' representing the initializer value.")
3468
3469 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3470 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3471
3472 (defun js2-print-object-prop-node (n i)
3473 (insert (js2-make-pad i))
3474 (js2-print-ast (js2-object-prop-node-left n) 0)
3475 (insert ":")
3476 (js2-print-ast (js2-object-prop-node-right n) 0))
3477
3478 (defstruct (js2-getter-setter-node
3479 (:include js2-infix-node)
3480 (:constructor nil)
3481 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3482 (pos js2-ts-cursor)
3483 len
3484 left
3485 right)))
3486 "AST node for a getter/setter property in an object literal.
3487 The `left' field is the `js2-name-node' naming the getter/setter prop.
3488 The `right' field is always an anonymous `js2-function-node' with a node
3489 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3490
3491 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3492 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3493
3494 (defun js2-print-getter-setter (n i)
3495 (let ((pad (js2-make-pad i))
3496 (left (js2-getter-setter-node-left n))
3497 (right (js2-getter-setter-node-right n)))
3498 (insert pad)
3499 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3500 (js2-print-ast left 0)
3501 (js2-print-ast right 0)))
3502
3503 (defstruct (js2-prop-get-node
3504 (:include js2-infix-node)
3505 (:constructor nil)
3506 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3507 (pos js2-ts-cursor)
3508 len
3509 left
3510 right)))
3511 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3512
3513 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3514 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3515
3516 (defun js2-visit-prop-get-node (n v)
3517 (when (js2-prop-get-node-left n)
3518 (js2-visit-ast (js2-prop-get-node-left n) v))
3519 (when (js2-prop-get-node-right n)
3520 (js2-visit-ast (js2-prop-get-node-right n) v)))
3521
3522 (defun js2-print-prop-get-node (n i)
3523 (insert (js2-make-pad i))
3524 (js2-print-ast (js2-prop-get-node-left n) 0)
3525 (insert ".")
3526 (js2-print-ast (js2-prop-get-node-right n) 0))
3527
3528 (defstruct (js2-elem-get-node
3529 (:include js2-node)
3530 (:constructor nil)
3531 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3532 (pos js2-ts-cursor)
3533 len
3534 target
3535 element
3536 lb
3537 rb)))
3538 "AST node for an array index expression such as foo[bar]."
3539 target ; a `js2-node' - the expression preceding the "."
3540 element ; a `js2-node' - the expression in brackets
3541 lb ; position of left-bracket, nil if omitted
3542 rb) ; position of right-bracket, nil if omitted
3543
3544 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3545 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3546
3547 (defun js2-visit-elem-get-node (n v)
3548 (when (js2-elem-get-node-target n)
3549 (js2-visit-ast (js2-elem-get-node-target n) v))
3550 (when (js2-elem-get-node-element n)
3551 (js2-visit-ast (js2-elem-get-node-element n) v)))
3552
3553 (defun js2-print-elem-get-node (n i)
3554 (insert (js2-make-pad i))
3555 (js2-print-ast (js2-elem-get-node-target n) 0)
3556 (insert "[")
3557 (js2-print-ast (js2-elem-get-node-element n) 0)
3558 (insert "]"))
3559
3560 (defstruct (js2-call-node
3561 (:include js2-node)
3562 (:constructor nil)
3563 (:constructor make-js2-call-node (&key (type js2-CALL)
3564 (pos js2-ts-cursor)
3565 len
3566 target
3567 args
3568 lp
3569 rp)))
3570 "AST node for a JavaScript function call."
3571 target ; a `js2-node' evaluating to the function to call
3572 args ; a lisp list of `js2-node' arguments
3573 lp ; position of open-paren, or nil if missing
3574 rp) ; position of close-paren, or nil if missing
3575
3576 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3577 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3578
3579 (defun js2-visit-call-node (n v)
3580 (js2-visit-ast (js2-call-node-target n) v)
3581 (dolist (arg (js2-call-node-args n))
3582 (js2-visit-ast arg v)))
3583
3584 (defun js2-print-call-node (n i)
3585 (insert (js2-make-pad i))
3586 (js2-print-ast (js2-call-node-target n) 0)
3587 (insert "(")
3588 (js2-print-list (js2-call-node-args n))
3589 (insert ")"))
3590
3591 (defstruct (js2-yield-node
3592 (:include js2-node)
3593 (:constructor nil)
3594 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3595 (pos js2-ts-cursor)
3596 len
3597 value)))
3598 "AST node for yield statement or expression."
3599 value) ; optional: value to be yielded
3600
3601 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3602 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3603
3604 (defun js2-visit-yield-node (n v)
3605 (js2-visit-ast (js2-yield-node-value n) v))
3606
3607 (defun js2-print-yield-node (n i)
3608 (insert (js2-make-pad i))
3609 (insert "yield")
3610 (when (js2-yield-node-value n)
3611 (insert " ")
3612 (js2-print-ast (js2-yield-node-value n) 0)))
3613
3614 (defstruct (js2-paren-node
3615 (:include js2-node)
3616 (:constructor nil)
3617 (:constructor make-js2-paren-node (&key (type js2-LP)
3618 (pos js2-ts-cursor)
3619 len
3620 expr)))
3621 "AST node for a parenthesized expression.
3622 In particular, used when the parens are syntactically optional,
3623 as opposed to required parens such as those enclosing an if-conditional."
3624 expr) ; `js2-node'
3625
3626 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3627 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3628
3629 (defun js2-visit-paren-node (n v)
3630 (js2-visit-ast (js2-paren-node-expr n) v))
3631
3632 (defun js2-print-paren-node (n i)
3633 (insert (js2-make-pad i))
3634 (insert "(")
3635 (js2-print-ast (js2-paren-node-expr n) 0)
3636 (insert ")"))
3637
3638 (defstruct (js2-array-comp-node
3639 (:include js2-scope)
3640 (:constructor nil)
3641 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3642 (pos js2-ts-cursor)
3643 len
3644 result
3645 loops
3646 filter
3647 if-pos
3648 lp
3649 rp)))
3650 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3651 result ; result expression (just after left-bracket)
3652 loops ; a lisp list of `js2-array-comp-loop-node'
3653 filter ; guard/filter expression
3654 if-pos ; buffer pos of 'if' keyword, if present, else nil
3655 lp ; buffer position of if-guard left-paren, or nil if not present
3656 rp) ; buffer position of if-guard right-paren, or nil if not present
3657
3658 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3659 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3660
3661 (defun js2-visit-array-comp-node (n v)
3662 (js2-visit-ast (js2-array-comp-node-result n) v)
3663 (dolist (l (js2-array-comp-node-loops n))
3664 (js2-visit-ast l v))
3665 (if (js2-array-comp-node-filter n)
3666 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3667
3668 (defun js2-print-array-comp-node (n i)
3669 (let ((pad (js2-make-pad i))
3670 (result (js2-array-comp-node-result n))
3671 (loops (js2-array-comp-node-loops n))
3672 (filter (js2-array-comp-node-filter n)))
3673 (insert pad "[")
3674 (js2-print-ast result 0)
3675 (dolist (l loops)
3676 (insert " ")
3677 (js2-print-ast l 0))
3678 (when filter
3679 (insert " if (")
3680 (js2-print-ast filter 0))
3681 (insert ")]")))
3682
3683 (defstruct (js2-array-comp-loop-node
3684 (:include js2-for-in-node)
3685 (:constructor nil)
3686 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3687 (pos js2-ts-cursor)
3688 len
3689 iterator
3690 object
3691 in-pos
3692 foreach-p
3693 each-pos
3694 lp
3695 rp)))
3696 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3697
3698 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3699 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3700
3701 (defun js2-visit-array-comp-loop (n v)
3702 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3703 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3704
3705 (defun js2-print-array-comp-loop (n i)
3706 (insert "for (")
3707 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3708 (insert " in ")
3709 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3710 (insert ")"))
3711
3712 (defstruct (js2-empty-expr-node
3713 (:include js2-node)
3714 (:constructor nil)
3715 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3716 (pos js2-token-beg)
3717 len)))
3718 "AST node for an empty expression.")
3719
3720 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3721 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3722
3723 (defstruct (js2-xml-node
3724 (:include js2-block-node)
3725 (:constructor nil)
3726 (:constructor make-js2-xml-node (&key (type js2-XML)
3727 (pos js2-token-beg)
3728 len
3729 kids)))
3730 "AST node for initial parse of E4X literals.
3731 The kids field is a list of XML fragments, each a `js2-string-node' or
3732 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3733
3734 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3735 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3736
3737 (defun js2-print-xml-node (n i)
3738 (dolist (kid (js2-xml-node-kids n))
3739 (js2-print-ast kid i)))
3740
3741 (defstruct (js2-xml-js-expr-node
3742 (:include js2-xml-node)
3743 (:constructor nil)
3744 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3745 (pos js2-ts-cursor)
3746 len
3747 expr)))
3748 "AST node for an embedded JavaScript {expression} in an E4X literal.
3749 The start and end fields correspond to the curly-braces."
3750 expr) ; a `js2-expr-node' of some sort
3751
3752 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3753 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3754
3755 (defun js2-visit-xml-js-expr (n v)
3756 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3757
3758 (defun js2-print-xml-js-expr (n i)
3759 (insert (js2-make-pad i))
3760 (insert "{")
3761 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3762 (insert "}"))
3763
3764 (defstruct (js2-xml-dot-query-node
3765 (:include js2-infix-node)
3766 (:constructor nil)
3767 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3768 (pos js2-ts-cursor)
3769 op-pos
3770 len
3771 left
3772 right
3773 rp)))
3774 "AST node for an E4X foo.(bar) filter expression.
3775 Note that the left-paren is automatically the character immediately
3776 following the dot (.) in the operator. No whitespace is permitted
3777 between the dot and the lp by the scanner."
3778 rp)
3779
3780 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3781 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3782
3783 (defun js2-print-xml-dot-query (n i)
3784 (insert (js2-make-pad i))
3785 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3786 (insert ".(")
3787 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3788 (insert ")"))
3789
3790 (defstruct (js2-xml-ref-node
3791 (:include js2-node)
3792 (:constructor nil)) ; abstract
3793 "Base type for E4X XML attribute-access or property-get expressions.
3794 Such expressions can take a variety of forms. The general syntax has
3795 three parts:
3796
3797 - (optional) an @ (specifying an attribute access)
3798 - (optional) a namespace (a `js2-name-node') and double-colon
3799 - (required) either a `js2-name-node' or a bracketed [expression]
3800
3801 The property-name expressions (examples: ns::name, @name) are
3802 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3803 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3804
3805 This node type (or more specifically, its subclasses) will sometimes
3806 be the right-hand child of a `js2-prop-get-node' or a
3807 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3808 The `js2-xml-ref-node' may also be a standalone primary expression with
3809 no explicit target, which is valid in certain expression contexts such as
3810
3811 company..employee.(@id < 100)
3812
3813 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3814 expression whose parent is a `js2-xml-dot-query-node'."
3815 namespace
3816 at-pos
3817 colon-pos)
3818
3819 (defsubst js2-xml-ref-node-attr-access-p (node)
3820 "Return non-nil if this expression began with an @-token."
3821 (and (numberp (js2-xml-ref-node-at-pos node))
3822 (plusp (js2-xml-ref-node-at-pos node))))
3823
3824 (defstruct (js2-xml-prop-ref-node
3825 (:include js2-xml-ref-node)
3826 (:constructor nil)
3827 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3828 (pos js2-token-beg)
3829 len
3830 propname
3831 namespace
3832 at-pos
3833 colon-pos)))
3834 "AST node for an E4X XML [expr] property-ref expression.
3835 The JavaScript syntax is an optional @, an optional ns::, and a name.
3836
3837 [ '@' ] [ name '::' ] name
3838
3839 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3840 @ns::*, @*::attr, @*::*, and @*.
3841
3842 The node starts at the @ token, if present. Otherwise it starts at the
3843 namespace name. The node bounds extend through the closing right-bracket,
3844 or if it is missing due to a syntax error, through the end of the index
3845 expression."
3846 propname)
3847
3848 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3849 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3850
3851 (defun js2-visit-xml-prop-ref-node (n v)
3852 (if (js2-xml-prop-ref-node-namespace n)
3853 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3854 (if (js2-xml-prop-ref-node-propname n)
3855 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3856
3857 (defun js2-print-xml-prop-ref-node (n i)
3858 (insert (js2-make-pad i))
3859 (if (js2-xml-ref-node-attr-access-p n)
3860 (insert "@"))
3861 (when (js2-xml-prop-ref-node-namespace n)
3862 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3863 (insert "::"))
3864 (if (js2-xml-prop-ref-node-propname n)
3865 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3866
3867 (defstruct (js2-xml-elem-ref-node
3868 (:include js2-xml-ref-node)
3869 (:constructor nil)
3870 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3871 (pos js2-token-beg)
3872 len
3873 expr
3874 lb
3875 rb
3876 namespace
3877 at-pos
3878 colon-pos)))
3879 "AST node for an E4X XML [expr] member-ref expression.
3880 Syntax:
3881
3882 [ '@' ] [ name '::' ] '[' expr ']'
3883
3884 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3885
3886 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3887 is not a legal E4X XML element-ref expression, since it's already used
3888 for standard JavaScript element-get array indexing. Hence, a
3889 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3890 non-nil namespace node, or both.
3891
3892 The node starts at the @ token, if present. Otherwise it starts
3893 at the namespace name. The node bounds extend through the closing
3894 right-bracket, or if it is missing due to a syntax error, through the
3895 end of the index expression."
3896 expr ; the bracketed index expression
3897 lb
3898 rb)
3899
3900 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3901 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3902
3903 (defun js2-visit-xml-elem-ref-node (n v)
3904 (if (js2-xml-elem-ref-node-namespace n)
3905 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
3906 (if (js2-xml-elem-ref-node-expr n)
3907 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
3908
3909 (defun js2-print-xml-elem-ref-node (n i)
3910 (insert (js2-make-pad i))
3911 (if (js2-xml-ref-node-attr-access-p n)
3912 (insert "@"))
3913 (when (js2-xml-elem-ref-node-namespace n)
3914 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3915 (insert "::"))
3916 (insert "[")
3917 (if (js2-xml-elem-ref-node-expr n)
3918 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3919 (insert "]"))
3920
3921 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3922
3923 (defstruct (js2-xml-start-tag-node
3924 (:include js2-xml-node)
3925 (:constructor nil)
3926 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3927 (pos js2-ts-cursor)
3928 len
3929 name
3930 attrs
3931 kids
3932 empty-p)))
3933 "AST node for an XML start-tag. Not currently used.
3934 The `kids' field is a lisp list of child content nodes."
3935 name ; a `js2-xml-name-node'
3936 attrs ; a lisp list of `js2-xml-attr-node'
3937 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3938
3939 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3940 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3941
3942 (defun js2-visit-xml-start-tag (n v)
3943 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3944 (dolist (attr (js2-xml-start-tag-node-attrs n))
3945 (js2-visit-ast attr v))
3946 (js2-visit-block n v))
3947
3948 (defun js2-print-xml-start-tag (n i)
3949 (insert (js2-make-pad i) "<")
3950 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3951 (when (js2-xml-start-tag-node-attrs n)
3952 (insert " ")
3953 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3954 (insert ">"))
3955
3956 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3957 ;; and add the end-tag to the kids list of the parent as well.
3958 (defstruct (js2-xml-end-tag-node
3959 (:include js2-xml-node)
3960 (:constructor nil)
3961 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3962 (pos js2-ts-cursor)
3963 len
3964 name)))
3965 "AST node for an XML end-tag. Not currently used."
3966 name) ; a `js2-xml-name-node'
3967
3968 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3969 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3970
3971 (defun js2-visit-xml-end-tag (n v)
3972 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3973
3974 (defun js2-print-xml-end-tag (n i)
3975 (insert (js2-make-pad i))
3976 (insert "</")
3977 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3978 (insert ">"))
3979
3980 (defstruct (js2-xml-name-node
3981 (:include js2-xml-node)
3982 (:constructor nil)
3983 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3984 (pos js2-ts-cursor)
3985 len
3986 namespace
3987 kids)))
3988 "AST node for an E4X XML name. Not currently used.
3989 Any XML name can be qualified with a namespace, hence the namespace field.
3990 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3991 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3992 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3993 namespace) ; a `js2-string-node'
3994
3995 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3996 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3997
3998 (defun js2-visit-xml-name-node (n v)
3999 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4000
4001 (defun js2-print-xml-name-node (n i)
4002 (insert (js2-make-pad i))
4003 (when (js2-xml-name-node-namespace n)
4004 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4005 (insert "::"))
4006 (dolist (kid (js2-xml-name-node-kids n))
4007 (js2-print-ast kid 0)))
4008
4009 (defstruct (js2-xml-pi-node
4010 (:include js2-xml-node)
4011 (:constructor nil)
4012 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4013 (pos js2-ts-cursor)
4014 len
4015 name
4016 attrs)))
4017 "AST node for an E4X XML processing instruction. Not currently used."
4018 name ; a `js2-xml-name-node'
4019 attrs) ; a list of `js2-xml-attr-node'
4020
4021 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4022 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4023
4024 (defun js2-visit-xml-pi-node (n v)
4025 (js2-visit-ast (js2-xml-pi-node-name n) v)
4026 (dolist (attr (js2-xml-pi-node-attrs n))
4027 (js2-visit-ast attr v)))
4028
4029 (defun js2-print-xml-pi-node (n i)
4030 (insert (js2-make-pad i) "<?")
4031 (js2-print-ast (js2-xml-pi-node-name n))
4032 (when (js2-xml-pi-node-attrs n)
4033 (insert " ")
4034 (js2-print-list (js2-xml-pi-node-attrs n)))
4035 (insert "?>"))
4036
4037 (defstruct (js2-xml-cdata-node
4038 (:include js2-xml-node)
4039 (:constructor nil)
4040 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4041 (pos js2-ts-cursor)
4042 len
4043 content)))
4044 "AST node for a CDATA escape section. Not currently used."
4045 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4046
4047 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4048 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4049
4050 (defun js2-visit-xml-cdata-node (n v)
4051 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4052
4053 (defun js2-print-xml-cdata-node (n i)
4054 (insert (js2-make-pad i))
4055 (js2-print-ast (js2-xml-cdata-node-content n)))
4056
4057 (defstruct (js2-xml-attr-node
4058 (:include js2-xml-node)
4059 (:constructor nil)
4060 (:constructor make-js2-attr-node (&key (type js2-XML)
4061 (pos js2-ts-cursor)
4062 len
4063 name
4064 value
4065 eq-pos
4066 quote-type)))
4067 "AST node representing a foo='bar' XML attribute value. Not yet used."
4068 name ; a `js2-xml-name-node'
4069 value ; a `js2-xml-name-node'
4070 eq-pos ; buffer position of "=" sign
4071 quote-type) ; 'single or 'double
4072
4073 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4074 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4075
4076 (defun js2-visit-xml-attr-node (n v)
4077 (js2-visit-ast (js2-xml-attr-node-name n) v)
4078 (js2-visit-ast (js2-xml-attr-node-value n) v))
4079
4080 (defun js2-print-xml-attr-node (n i)
4081 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4082 "'"
4083 "\"")))
4084 (insert (js2-make-pad i))
4085 (js2-print-ast (js2-xml-attr-node-name n) 0)
4086 (insert "=" quote)
4087 (js2-print-ast (js2-xml-attr-node-value n) 0)
4088 (insert quote)))
4089
4090 (defstruct (js2-xml-text-node
4091 (:include js2-xml-node)
4092 (:constructor nil)
4093 (:constructor make-js2-text-node (&key (type js2-XML)
4094 (pos js2-ts-cursor)
4095 len
4096 content)))
4097 "AST node for an E4X XML text node. Not currently used."
4098 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4099
4100 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4101 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4102
4103 (defun js2-visit-xml-text-node (n v)
4104 (js2-visit-ast (js2-xml-text-node-content n) v))
4105
4106 (defun js2-print-xml-text-node (n i)
4107 (insert (js2-make-pad i))
4108 (dolist (kid (js2-xml-text-node-content n))
4109 (js2-print-ast kid)))
4110
4111 (defstruct (js2-xml-comment-node
4112 (:include js2-xml-node)
4113 (:constructor nil)
4114 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4115 (pos js2-ts-cursor)
4116 len)))
4117 "AST node for E4X XML comment. Not currently used.")
4118
4119 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4120 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4121
4122 (defun js2-print-xml-comment (n i)
4123 (insert (js2-make-pad i)
4124 (js2-node-string n)))
4125
4126 ;;; Node utilities
4127
4128 (defsubst js2-node-line (n)
4129 "Fetch the source line number at the start of node N.
4130 This is O(n) in the length of the source buffer; use prudently."
4131 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4132
4133 (defsubst js2-block-node-kid (n i)
4134 "Return child I of node N, or nil if there aren't that many."
4135 (nth i (js2-block-node-kids n)))
4136
4137 (defsubst js2-block-node-first (n)
4138 "Return first child of block node N, or nil if there is none."
4139 (first (js2-block-node-kids n)))
4140
4141 (defun js2-node-root (n)
4142 "Return the root of the AST containing N.
4143 If N has no parent pointer, returns N."
4144 (let ((parent (js2-node-parent n)))
4145 (if parent
4146 (js2-node-root parent)
4147 n)))
4148
4149 (defun js2-node-position-in-parent (node &optional parent)
4150 "Return the position of NODE in parent's block-kids list.
4151 PARENT can be supplied if known. Positioned returned is zero-indexed.
4152 Returns 0 if NODE is not a child of a block statement, or if NODE
4153 is not a statement node."
4154 (let ((p (or parent (js2-node-parent node)))
4155 (i 0))
4156 (if (not (js2-block-node-p p))
4157 i
4158 (or (js2-position node (js2-block-node-kids p))
4159 0))))
4160
4161 (defsubst js2-node-short-name (n)
4162 "Return the short name of node N as a string, e.g. `js2-if-node'."
4163 (substring (symbol-name (aref n 0))
4164 (length "cl-struct-")))
4165
4166 (defsubst js2-node-child-list (node)
4167 "Return the child list for NODE, a Lisp list of nodes.
4168 Works for block nodes, array nodes, obj literals, funarg lists,
4169 var decls and try nodes (for catch clauses). Note that you should call
4170 `js2-block-node-kids' on the function body for the body statements.
4171 Returns nil for zero-length child lists or unsupported nodes."
4172 (cond
4173 ((js2-function-node-p node)
4174 (js2-function-node-params node))
4175 ((js2-block-node-p node)
4176 (js2-block-node-kids node))
4177 ((js2-try-node-p node)
4178 (js2-try-node-catch-clauses node))
4179 ((js2-array-node-p node)
4180 (js2-array-node-elems node))
4181 ((js2-object-node-p node)
4182 (js2-object-node-elems node))
4183 ((js2-call-node-p node)
4184 (js2-call-node-args node))
4185 ((js2-new-node-p node)
4186 (js2-new-node-args node))
4187 ((js2-var-decl-node-p node)
4188 (js2-var-decl-node-kids node))
4189 (t
4190 nil)))
4191
4192 (defsubst js2-node-set-child-list (node kids)
4193 "Set the child list for NODE to KIDS."
4194 (cond
4195 ((js2-function-node-p node)
4196 (setf (js2-function-node-params node) kids))
4197 ((js2-block-node-p node)
4198 (setf (js2-block-node-kids node) kids))
4199 ((js2-try-node-p node)
4200 (setf (js2-try-node-catch-clauses node) kids))
4201 ((js2-array-node-p node)
4202 (setf (js2-array-node-elems node) kids))
4203 ((js2-object-node-p node)
4204 (setf (js2-object-node-elems node) kids))
4205 ((js2-call-node-p node)
4206 (setf (js2-call-node-args node) kids))
4207 ((js2-new-node-p node)
4208 (setf (js2-new-node-args node) kids))
4209 ((js2-var-decl-node-p node)
4210 (setf (js2-var-decl-node-kids node) kids))
4211 (t
4212 (error "Unsupported node type: %s" (js2-node-short-name node))))
4213 kids)
4214
4215 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4216 (defconst js2-paren-expr-nodes
4217 '(cl-struct-js2-array-comp-loop-node
4218 cl-struct-js2-array-comp-node
4219 cl-struct-js2-call-node
4220 cl-struct-js2-catch-node
4221 cl-struct-js2-do-node
4222 cl-struct-js2-elem-get-node
4223 cl-struct-js2-for-in-node
4224 cl-struct-js2-for-node
4225 cl-struct-js2-function-node
4226 cl-struct-js2-if-node
4227 cl-struct-js2-let-node
4228 cl-struct-js2-new-node
4229 cl-struct-js2-paren-node
4230 cl-struct-js2-switch-node
4231 cl-struct-js2-while-node
4232 cl-struct-js2-with-node
4233 cl-struct-js2-xml-dot-query-node)
4234 "Node types that can have a parenthesized child expression.
4235 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4236
4237 (defsubst js2-paren-expr-node-p (node)
4238 "Return t for nodes that typically have a parenthesized child expression.
4239 Useful for computing the indentation anchors for arg-lists and conditions.
4240 Note that it may return a false positive, for instance when NODE is
4241 a `js2-new-node' and there are no arguments or parentheses."
4242 (memq (aref node 0) js2-paren-expr-nodes))
4243
4244 ;; Fake polymorphism... yech.
4245 (defsubst js2-node-lp (node)
4246 "Return relative left-paren position for NODE, if applicable.
4247 For `js2-elem-get-node' structs, returns left-bracket position.
4248 Note that the position may be nil in the case of a parse error."
4249 (cond
4250 ((js2-elem-get-node-p node)
4251 (js2-elem-get-node-lb node))
4252 ((js2-loop-node-p node)
4253 (js2-loop-node-lp node))
4254 ((js2-function-node-p node)
4255 (js2-function-node-lp node))
4256 ((js2-if-node-p node)
4257 (js2-if-node-lp node))
4258 ((js2-new-node-p node)
4259 (js2-new-node-lp node))
4260 ((js2-call-node-p node)
4261 (js2-call-node-lp node))
4262 ((js2-paren-node-p node)
4263 (js2-node-pos node))
4264 ((js2-switch-node-p node)
4265 (js2-switch-node-lp node))
4266 ((js2-catch-node-p node)
4267 (js2-catch-node-lp node))
4268 ((js2-let-node-p node)
4269 (js2-let-node-lp node))
4270 ((js2-array-comp-node-p node)
4271 (js2-array-comp-node-lp node))
4272 ((js2-with-node-p node)
4273 (js2-with-node-lp node))
4274 ((js2-xml-dot-query-node-p node)
4275 (1+ (js2-infix-node-op-pos node)))
4276 (t
4277 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4278
4279 ;; Fake polymorphism... blech.
4280 (defsubst js2-node-rp (node)
4281 "Return relative right-paren position for NODE, if applicable.
4282 For `js2-elem-get-node' structs, returns right-bracket position.
4283 Note that the position may be nil in the case of a parse error."
4284 (cond
4285 ((js2-elem-get-node-p node)
4286 (js2-elem-get-node-lb node))
4287 ((js2-loop-node-p node)
4288 (js2-loop-node-rp node))
4289 ((js2-function-node-p node)
4290 (js2-function-node-rp node))
4291 ((js2-if-node-p node)
4292 (js2-if-node-rp node))
4293 ((js2-new-node-p node)
4294 (js2-new-node-rp node))
4295 ((js2-call-node-p node)
4296 (js2-call-node-rp node))
4297 ((js2-paren-node-p node)
4298 (+ (js2-node-pos node) (js2-node-len node)))
4299 ((js2-switch-node-p node)
4300 (js2-switch-node-rp node))
4301 ((js2-catch-node-p node)
4302 (js2-catch-node-rp node))
4303 ((js2-let-node-p node)
4304 (js2-let-node-rp node))
4305 ((js2-array-comp-node-p node)
4306 (js2-array-comp-node-rp node))
4307 ((js2-with-node-p node)
4308 (js2-with-node-rp node))
4309 ((js2-xml-dot-query-node-p node)
4310 (1+ (js2-xml-dot-query-node-rp node)))
4311 (t
4312 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4313
4314 (defsubst js2-node-first-child (node)
4315 "Return the first element of `js2-node-child-list' for NODE."
4316 (car (js2-node-child-list node)))
4317
4318 (defsubst js2-node-last-child (node)
4319 "Return the last element of `js2-node-last-child' for NODE."
4320 (car (last (js2-node-child-list node))))
4321
4322 (defun js2-node-prev-sibling (node)
4323 "Return the previous statement in parent.
4324 Works for parents supported by `js2-node-child-list'.
4325 Returns nil if NODE is not in the parent, or PARENT is
4326 not a supported node, or if NODE is the first child."
4327 (let* ((p (js2-node-parent node))
4328 (kids (js2-node-child-list p))
4329 (sib (car kids)))
4330 (while (and kids
4331 (not (eq node (cadr kids))))
4332 (setq kids (cdr kids)
4333 sib (car kids)))
4334 sib))
4335
4336 (defun js2-node-next-sibling (node)
4337 "Return the next statement in parent block.
4338 Returns nil if NODE is not in the block, or PARENT is not
4339 a block node, or if NODE is the last statement."
4340 (let* ((p (js2-node-parent node))
4341 (kids (js2-node-child-list p)))
4342 (while (and kids
4343 (not (eq node (car kids))))
4344 (setq kids (cdr kids)))
4345 (cadr kids)))
4346
4347 (defun js2-node-find-child-before (pos parent &optional after)
4348 "Find the last child that starts before POS in parent.
4349 If AFTER is non-nil, returns first child starting after POS.
4350 POS is an absolute buffer position. PARENT is any node
4351 supported by `js2-node-child-list'.
4352 Returns nil if no applicable child is found."
4353 (let ((kids (if (js2-function-node-p parent)
4354 (js2-block-node-kids (js2-function-node-body parent))
4355 (js2-node-child-list parent)))
4356 (beg (if (js2-function-node-p parent)
4357 (js2-node-abs-pos (js2-function-node-body parent))
4358 (js2-node-abs-pos parent)))
4359 kid
4360 result
4361 fn
4362 (continue t))
4363 (setq fn (if after '> '<))
4364 (while (and kids continue)
4365 (setq kid (car kids))
4366 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4367 (setq result kid
4368 continue (if after nil t))
4369 (setq continue (if after t nil)))
4370 (setq kids (cdr kids)))
4371 result))
4372
4373 (defun js2-node-find-child-after (pos parent)
4374 "Find first child that starts after POS in parent.
4375 POS is an absolute buffer position. PARENT is any node
4376 supported by `js2-node-child-list'.
4377 Returns nil if no applicable child is found."
4378 (js2-node-find-child-before pos parent 'after))
4379
4380 (defun js2-node-replace-child (pos parent new-node)
4381 "Replace node at index POS in PARENT with NEW-NODE.
4382 Only works for parents supported by `js2-node-child-list'."
4383 (let ((kids (js2-node-child-list parent))
4384 (i 0))
4385 (while (< i pos)
4386 (setq kids (cdr kids)
4387 i (1+ i)))
4388 (setcar kids new-node)
4389 (js2-node-add-children parent new-node)))
4390
4391 (defun js2-node-buffer (n)
4392 "Return the buffer associated with AST N.
4393 Returns nil if the buffer is not set as a property on the root
4394 node, or if parent links were not recorded during parsing."
4395 (let ((root (js2-node-root n)))
4396 (and root
4397 (js2-ast-root-p root)
4398 (js2-ast-root-buffer root))))
4399
4400 (defsubst js2-block-node-push (n kid)
4401 "Push js2-node KID onto the end of js2-block-node N's child list.
4402 KID is always added to the -end- of the kids list.
4403 Function also calls `js2-node-add-children' to add the parent link."
4404 (let ((kids (js2-node-child-list n)))
4405 (if kids
4406 (setcdr kids (nconc (cdr kids) (list kid)))
4407 (js2-node-set-child-list n (list kid)))
4408 (js2-node-add-children n kid)))
4409
4410 (defun js2-node-string (node)
4411 (let ((buf (js2-node-buffer node))
4412 pos)
4413 (unless buf
4414 (error "No buffer available for node %s" node))
4415 (with-current-buffer buf
4416 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4417 (+ pos (js2-node-len node))))))
4418
4419 ;; Container for storing the node we're looking for in a traversal.
4420 (js2-deflocal js2-discovered-node nil)
4421
4422 ;; Keep track of absolute node position during traversals.
4423 (js2-deflocal js2-visitor-offset nil)
4424
4425 (js2-deflocal js2-node-search-point nil)
4426
4427 (when js2-mode-dev-mode-p
4428 (defun js2-find-node-at-point ()
4429 (interactive)
4430 (let ((node (js2-node-at-point)))
4431 (message "%s" (or node "No node found at point"))))
4432 (defun js2-node-name-at-point ()
4433 (interactive)
4434 (let ((node (js2-node-at-point)))
4435 (message "%s" (if node
4436 (js2-node-short-name node)
4437 "No node found at point.")))))
4438
4439 (defun js2-node-at-point (&optional pos skip-comments)
4440 "Return AST node at POS, a buffer position, defaulting to current point.
4441 The `js2-mode-ast' variable must be set to the current parse tree.
4442 Signals an error if the AST (`js2-mode-ast') is nil.
4443 Always returns a node - if it can't find one, it returns the root.
4444 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4445 (let ((ast js2-mode-ast)
4446 result)
4447 (unless ast
4448 (error "No JavaScript AST available"))
4449 ;; Look through comments first, since they may be inside nodes that
4450 ;; would otherwise report a match.
4451 (setq pos (or pos (point))
4452 result (if (> pos (js2-node-abs-end ast))
4453 ast
4454 (if (not skip-comments)
4455 (js2-comment-at-point pos))))
4456 (unless result
4457 (setq js2-discovered-node nil
4458 js2-visitor-offset 0
4459 js2-node-search-point pos)
4460 (unwind-protect
4461 (catch 'js2-visit-done
4462 (js2-visit-ast ast #'js2-node-at-point-visitor))
4463 (setq js2-visitor-offset nil
4464 js2-node-search-point nil))
4465 (setq result js2-discovered-node))
4466 ;; may have found a comment beyond end of last child node,
4467 ;; since visiting the ast-root looks at the comment-list last.
4468 (if (and skip-comments
4469 (js2-comment-node-p result))
4470 (setq result nil))
4471 (or result js2-mode-ast)))
4472
4473 (defun js2-node-at-point-visitor (node end-p)
4474 (let ((rel-pos (js2-node-pos node))
4475 abs-pos
4476 abs-end
4477 (point js2-node-search-point))
4478 (cond
4479 (end-p
4480 ;; this evaluates to a non-nil return value, even if it's zero
4481 (decf js2-visitor-offset rel-pos))
4482 ;; we already looked for comments before visiting, and don't want them now
4483 ((js2-comment-node-p node)
4484 nil)
4485 (t
4486 (setq abs-pos (incf js2-visitor-offset rel-pos)
4487 ;; we only want to use the node if the point is before
4488 ;; the last character position in the node, so we decrement
4489 ;; the absolute end by 1.
4490 abs-end (+ abs-pos (js2-node-len node) -1))
4491 (cond
4492 ;; If this node starts after search-point, stop the search.
4493 ((> abs-pos point)
4494 (throw 'js2-visit-done nil))
4495 ;; If this node ends before the search-point, don't check kids.
4496 ((> point abs-end)
4497 nil)
4498 (t
4499 ;; Otherwise point is within this node, possibly in a child.
4500 (setq js2-discovered-node node)
4501 t)))))) ; keep processing kids to look for more specific match
4502
4503 (defsubst js2-block-comment-p (node)
4504 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4505 (and (js2-comment-node-p node)
4506 (memq (js2-comment-node-format node) '(jsdoc block))))
4507
4508 ;; TODO: put the comments in a vector and binary-search them instead
4509 (defun js2-comment-at-point (&optional pos)
4510 "Look through scanned comment nodes for one containing POS.
4511 POS is a buffer position that defaults to current point.
4512 Function returns nil if POS was not in any comment node."
4513 (let ((ast js2-mode-ast)
4514 (x (or pos (point)))
4515 beg
4516 end)
4517 (unless ast
4518 (error "No JavaScript AST available"))
4519 (catch 'done
4520 ;; Comments are stored in lexical order.
4521 (dolist (comment (js2-ast-root-comments ast) nil)
4522 (setq beg (js2-node-abs-pos comment)
4523 end (+ beg (js2-node-len comment)))
4524 (if (and (>= x beg)
4525 (<= x end))
4526 (throw 'done comment))))))
4527
4528 (defun js2-mode-find-parent-fn (node)
4529 "Find function enclosing NODE.
4530 Returns nil if NODE is not inside a function."
4531 (setq node (js2-node-parent node))
4532 (while (and node (not (js2-function-node-p node)))
4533 (setq node (js2-node-parent node)))
4534 (and (js2-function-node-p node) node))
4535
4536 (defun js2-mode-find-enclosing-fn (node)
4537 "Find function or root enclosing NODE."
4538 (if (js2-ast-root-p node)
4539 node
4540 (setq node (js2-node-parent node))
4541 (while (not (or (js2-ast-root-p node)
4542 (js2-function-node-p node)))
4543 (setq node (js2-node-parent node)))
4544 node))
4545
4546 (defun js2-mode-find-enclosing-node (beg end)
4547 "Find script or function fully enclosing BEG and END."
4548 (let ((node (js2-node-at-point beg))
4549 pos
4550 (continue t))
4551 (while continue
4552 (if (or (js2-ast-root-p node)
4553 (and (js2-function-node-p node)
4554 (<= (setq pos (js2-node-abs-pos node)) beg)
4555 (>= (+ pos (js2-node-len node)) end)))
4556 (setq continue nil)
4557 (setq node (js2-node-parent node))))
4558 node))
4559
4560 (defun js2-node-parent-script-or-fn (node)
4561 "Find script or function immediately enclosing NODE.
4562 If NODE is the ast-root, returns nil."
4563 (if (js2-ast-root-p node)
4564 nil
4565 (setq node (js2-node-parent node))
4566 (while (and node (not (or (js2-function-node-p node)
4567 (js2-script-node-p node))))
4568 (setq node (js2-node-parent node)))
4569 node))
4570
4571 (defsubst js2-nested-function-p (node)
4572 "Return t if NODE is a nested function, or is inside a nested function."
4573 (js2-function-node-p (if (js2-function-node-p node)
4574 (js2-node-parent-script-or-fn node)
4575 (js2-node-parent-script-or-fn
4576 (js2-node-parent-script-or-fn node)))))
4577
4578 (defsubst js2-mode-shift-kids (kids start offset)
4579 (dolist (kid kids)
4580 (if (> (js2-node-pos kid) start)
4581 (incf (js2-node-pos kid) offset))))
4582
4583 (defsubst js2-mode-shift-children (parent start offset)
4584 "Update start-positions of all children of PARENT beyond START."
4585 (let ((root (js2-node-root parent)))
4586 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4587 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4588
4589 (defsubst js2-node-is-descendant (node ancestor)
4590 "Return t if NODE is a descendant of ANCESTOR."
4591 (while (and node
4592 (not (eq node ancestor)))
4593 (setq node (js2-node-parent node)))
4594 node)
4595
4596 ;;; visitor infrastructure
4597
4598 (defun js2-visit-none (node callback)
4599 "Visitor for AST node that have no node children."
4600 nil)
4601
4602 (defun js2-print-none (node indent)
4603 "Visitor for AST node with no printed representation.")
4604
4605 (defun js2-print-body (node indent)
4606 "Print a statement, or a block without braces."
4607 (if (js2-block-node-p node)
4608 (dolist (kid (js2-block-node-kids node))
4609 (js2-print-ast kid indent))
4610 (js2-print-ast node indent)))
4611
4612 (defun js2-print-list (args &optional delimiter)
4613 (loop with len = (length args)
4614 for arg in args
4615 for count from 1
4616 do
4617 (js2-print-ast arg 0)
4618 (if (< count len)
4619 (insert (or delimiter ", ")))))
4620
4621 (defun js2-print-tree (ast)
4622 "Prints an AST to the current buffer.
4623 Makes `js2-ast-parent-nodes' available to the printer functions."
4624 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4625 (js2-print-ast ast)))
4626
4627 (defun js2-print-ast (node &optional indent)
4628 "Helper function for printing AST nodes.
4629 Requires `js2-ast-parent-nodes' to be non-nil.
4630 You should use `js2-print-tree' instead of this function."
4631 (let ((printer (get (aref node 0) 'js2-printer))
4632 (i (or indent 0))
4633 (pos (js2-node-abs-pos node)))
4634 ;; TODO: wedge comments in here somewhere
4635 (if printer
4636 (funcall printer node i))))
4637
4638 (defconst js2-side-effecting-tokens
4639 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4640 (dolist (tt (list js2-ASSIGN
4641 js2-ASSIGN_ADD
4642 js2-ASSIGN_BITAND
4643 js2-ASSIGN_BITOR
4644 js2-ASSIGN_BITXOR
4645 js2-ASSIGN_DIV
4646 js2-ASSIGN_LSH
4647 js2-ASSIGN_MOD
4648 js2-ASSIGN_MUL
4649 js2-ASSIGN_RSH
4650 js2-ASSIGN_SUB
4651 js2-ASSIGN_URSH
4652 js2-BLOCK
4653 js2-BREAK
4654 js2-CALL
4655 js2-CATCH
4656 js2-CATCH_SCOPE
4657 js2-CONST
4658 js2-CONTINUE
4659 js2-DEBUGGER
4660 js2-DEC
4661 js2-DELPROP
4662 js2-DEL_REF
4663 js2-DO
4664 js2-ELSE
4665 js2-EMPTY
4666 js2-ENTERWITH
4667 js2-EXPORT
4668 js2-EXPR_RESULT
4669 js2-FINALLY
4670 js2-FOR
4671 js2-FUNCTION
4672 js2-GOTO
4673 js2-IF
4674 js2-IFEQ
4675 js2-IFNE
4676 js2-IMPORT
4677 js2-INC
4678 js2-JSR
4679 js2-LABEL
4680 js2-LEAVEWITH
4681 js2-LET
4682 js2-LETEXPR
4683 js2-LOCAL_BLOCK
4684 js2-LOOP
4685 js2-NEW
4686 js2-REF_CALL
4687 js2-RETHROW
4688 js2-RETURN
4689 js2-RETURN_RESULT
4690 js2-SEMI
4691 js2-SETELEM
4692 js2-SETELEM_OP
4693 js2-SETNAME
4694 js2-SETPROP
4695 js2-SETPROP_OP
4696 js2-SETVAR
4697 js2-SET_REF
4698 js2-SET_REF_OP
4699 js2-SWITCH
4700 js2-TARGET
4701 js2-THROW
4702 js2-TRY
4703 js2-VAR
4704 js2-WHILE
4705 js2-WITH
4706 js2-WITHEXPR
4707 js2-YIELD))
4708 (aset tokens tt t))
4709 (if js2-instanceof-has-side-effects
4710 (aset tokens js2-INSTANCEOF t))
4711 tokens))
4712
4713 (defun js2-node-has-side-effects (node)
4714 "Return t if NODE has side effects."
4715 (when node ; makes it easier to handle malformed expressions
4716 (let ((tt (js2-node-type node)))
4717 (cond
4718 ;; This doubtless needs some work, since EXPR_VOID is used
4719 ;; in several ways in Rhino, and I may not have caught them all.
4720 ;; I'll wait for people to notice incorrect warnings.
4721 ((and (= tt js2-EXPR_VOID)
4722 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4723 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4724 ((= tt js2-COMMA)
4725 (js2-node-has-side-effects (js2-infix-node-right node)))
4726 ((or (= tt js2-AND)
4727 (= tt js2-OR))
4728 (or (js2-node-has-side-effects (js2-infix-node-right node))
4729 (js2-node-has-side-effects (js2-infix-node-left node))))
4730 ((= tt js2-HOOK)
4731 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4732 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4733 ((js2-paren-node-p node)
4734 (js2-node-has-side-effects (js2-paren-node-expr node)))
4735 ((= tt js2-ERROR) ; avoid cascaded error messages
4736 nil)
4737 (t
4738 (aref js2-side-effecting-tokens tt))))))
4739
4740 (defun js2-member-expr-leftmost-name (node)
4741 "For an expr such as foo.bar.baz, return leftmost node foo.
4742 NODE is any `js2-node' object. If it represents a member expression,
4743 which is any sequence of property gets, element-gets, function calls,
4744 or xml descendants/filter operators, then we look at the lexically
4745 leftmost (first) node in the chain. If it is a name-node we return it.
4746 Note that NODE can be a raw name-node and it will be returned as well.
4747 If NODE is not a name-node or member expression, or if it is a member
4748 expression whose leftmost target is not a name node, returns nil."
4749 (let ((continue t)
4750 result)
4751 (while (and continue (not result))
4752 (cond
4753 ((js2-name-node-p node)
4754 (setq result node))
4755 ((js2-prop-get-node-p node)
4756 (setq node (js2-prop-get-node-left node)))
4757 ;; TODO: handle call-nodes, xml-nodes, others?
4758 (t
4759 (setq continue nil))))
4760 result))
4761
4762 (defconst js2-stmt-node-types
4763 (list js2-BLOCK
4764 js2-BREAK
4765 js2-CONTINUE
4766 js2-DEFAULT ; e4x "default xml namespace" statement
4767 js2-DO
4768 js2-EXPR_RESULT
4769 js2-EXPR_VOID
4770 js2-FOR
4771 js2-IF
4772 js2-RETURN
4773 js2-SWITCH
4774 js2-THROW
4775 js2-TRY
4776 js2-WHILE
4777 js2-WITH)
4778 "Node types that only appear in statement contexts.
4779 The list does not include nodes that always appear as the child
4780 of another specific statement type, such as switch-cases,
4781 catch and finally blocks, and else-clauses. The list also excludes
4782 nodes like yield, let and var, which may appear in either expression
4783 or statement context, and in the latter context always have a
4784 `js2-expr-stmt-node' parent. Finally, the list does not include
4785 functions or scripts, which are treated separately from statements
4786 by the JavaScript parser and runtime.")
4787
4788 (defun js2-stmt-node-p (node)
4789 "Heuristic for figuring out if NODE is a statement.
4790 Some node types can appear in either an expression context or a
4791 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4792 For these node types in a statement context, the parent will be a
4793 `js2-expr-stmt-node'.
4794 Functions aren't included in the check."
4795 (memq (js2-node-type node) js2-stmt-node-types))
4796
4797 (defsubst js2-mode-find-first-stmt (node)
4798 "Search upward starting from NODE looking for a statement.
4799 For purposes of this function, a `js2-function-node' counts."
4800 (while (not (or (js2-stmt-node-p node)
4801 (js2-function-node-p node)))
4802 (setq node (js2-node-parent node)))
4803 node)
4804
4805 (defun js2-node-parent-stmt (node)
4806 "Return the node's first ancestor that is a statement.
4807 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4808 appearing in a statement context will have a parent that is a
4809 `js2-expr-stmt-node' that will be returned by this function."
4810 (let ((parent (js2-node-parent node)))
4811 (if (or (null parent)
4812 (js2-stmt-node-p parent)
4813 (and (js2-function-node-p parent)
4814 (not (eq (js2-function-node-form parent)
4815 'FUNCTION_EXPRESSION))))
4816 parent
4817 (js2-node-parent-stmt parent))))
4818
4819 ;; In the Mozilla Rhino sources, Roshan James writes:
4820 ;; Does consistent-return analysis on the function body when strict mode is
4821 ;; enabled.
4822 ;;
4823 ;; function (x) { return (x+1) }
4824 ;;
4825 ;; is ok, but
4826 ;;
4827 ;; function (x) { if (x < 0) return (x+1); }
4828 ;;
4829 ;; is not because the function can potentially return a value when the
4830 ;; condition is satisfied and if not, the function does not explicitly
4831 ;; return a value.
4832 ;;
4833 ;; This extends to checking mismatches such as "return" and "return <value>"
4834 ;; used in the same function. Warnings are not emitted if inconsistent
4835 ;; returns exist in code that can be statically shown to be unreachable.
4836 ;; Ex.
4837 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4838 ;;
4839 ;; emits no warning. However if the loop had a break statement, then a
4840 ;; warning would be emitted.
4841 ;;
4842 ;; The consistency analysis looks at control structures such as loops, ifs,
4843 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4844 ;; warns the user about an inconsistent set of termination possibilities.
4845 ;;
4846 ;; These flags enumerate the possible ways a statement/function can
4847 ;; terminate. These flags are used by endCheck() and by the Parser to
4848 ;; detect inconsistent return usage.
4849 ;;
4850 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4851 ;; able to execute (example: throw, continue)
4852 ;;
4853 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4854 ;; next one. Statement such as return dont. A compound statement may have
4855 ;; some branch that drops off control to the next statement.
4856 ;;
4857 ;; END_RETURNS indicates that the statement can return with no value.
4858 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4859 ;;
4860 ;; A compound statement such as
4861 ;; if (condition) {
4862 ;; return value;
4863 ;; }
4864 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4865
4866 (defconst js2-END_UNREACHED 0)
4867 (defconst js2-END_DROPS_OFF 1)
4868 (defconst js2-END_RETURNS 2)
4869 (defconst js2-END_RETURNS_VALUE 4)
4870 (defconst js2-END_YIELDS 8)
4871
4872 (defun js2-has-consistent-return-usage (node)
4873 "Check that every return usage in a function body is consistent.
4874 Returns t if the function satisfies strict mode requirement."
4875 (let ((n (js2-end-check node)))
4876 ;; either it doesn't return a value in any branch...
4877 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4878 ;; or it returns a value (or is unreached) at every branch
4879 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4880 js2-END_RETURNS
4881 js2-END_YIELDS)))))
4882
4883 (defun js2-end-check-if (node)
4884 "Return in the then and else blocks must be consistent with each other.
4885 If there is no else block, then the return statement can fall through.
4886 Returns logical OR of END_* flags"
4887 (let ((th (js2-if-node-then-part node))
4888 (el (js2-if-node-else-part node)))
4889 (if (null th)
4890 js2-END_UNREACHED
4891 (logior (js2-end-check th) (if el
4892 (js2-end-check el)
4893 js2-END_DROPS_OFF)))))
4894
4895 (defun js2-end-check-switch (node)
4896 "Consistency of return statements is checked between the case statements.
4897 If there is no default, then the switch can fall through. If there is a
4898 default, we check to see if all code paths in the default return or if
4899 there is a code path that can fall through.
4900 Returns logical OR of END_* flags."
4901 (let ((rv js2-END_UNREACHED)
4902 default-case)
4903 ;; examine the cases
4904 (catch 'break
4905 (dolist (c (js2-switch-node-cases node))
4906 (if (js2-case-node-expr c)
4907 (js2-set-flag rv (js2-end-check-block c))
4908 (setq default-case c)
4909 (throw 'break nil))))
4910 ;; we don't care how the cases drop into each other
4911 (js2-clear-flag rv js2-END_DROPS_OFF)
4912 ;; examine the default
4913 (js2-set-flag rv (if default-case
4914 (js2-end-check default-case)
4915 js2-END_DROPS_OFF))
4916 rv))
4917
4918 (defun js2-end-check-try (node)
4919 "If the block has a finally, return consistency is checked in the
4920 finally block. If all code paths in the finally return, then the
4921 returns in the try-catch blocks don't matter. If there is a code path
4922 that does not return or if there is no finally block, the returns
4923 of the try and catch blocks are checked for mismatch.
4924 Returns logical OR of END_* flags."
4925 (let ((finally (js2-try-node-finally-block node))
4926 rv)
4927 ;; check the finally if it exists
4928 (setq rv (if finally
4929 (js2-end-check (js2-finally-node-body finally))
4930 js2-END_DROPS_OFF))
4931 ;; If the finally block always returns, then none of the returns
4932 ;; in the try or catch blocks matter.
4933 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4934 (js2-clear-flag rv js2-END_DROPS_OFF)
4935 ;; examine the try block
4936 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4937 ;; check each catch block
4938 (dolist (cb (js2-try-node-catch-clauses node))
4939 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4940 rv))
4941
4942 (defun js2-end-check-loop (node)
4943 "Return statement in the loop body must be consistent.
4944 The default assumption for any kind of a loop is that it will eventually
4945 terminate. The only exception is a loop with a constant true condition.
4946 Code that follows such a loop is examined only if one can statically determine
4947 that there is a break out of the loop.
4948
4949 for(... ; ... ; ...) {}
4950 for(... in ... ) {}
4951 while(...) { }
4952 do { } while(...)
4953
4954 Returns logical OR of END_* flags."
4955 (let ((rv (js2-end-check (js2-loop-node-body node)))
4956 (condition (cond
4957 ((js2-while-node-p node)
4958 (js2-while-node-condition node))
4959 ((js2-do-node-p node)
4960 (js2-do-node-condition node))
4961 ((js2-for-node-p node)
4962 (js2-for-node-condition node)))))
4963
4964 ;; check to see if the loop condition is always true
4965 (if (and condition
4966 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4967 (js2-clear-flag rv js2-END_DROPS_OFF))
4968
4969 ;; look for effect of breaks
4970 (js2-set-flag rv (js2-node-get-prop node
4971 'CONTROL_BLOCK_PROP
4972 js2-END_UNREACHED))
4973 rv))
4974
4975 (defun js2-end-check-block (node)
4976 "A general block of code is examined statement by statement.
4977 If any statement (even a compound one) returns in all branches, then
4978 subsequent statements are not examined.
4979 Returns logical OR of END_* flags."
4980 (let* ((rv js2-END_DROPS_OFF)
4981 (kids (js2-block-node-kids node))
4982 (n (car kids)))
4983 ;; Check each statment. If the statement can continue onto the next
4984 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4985 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4986 (js2-clear-flag rv js2-END_DROPS_OFF)
4987 (js2-set-flag rv (js2-end-check n))
4988 (setq kids (cdr kids)
4989 n (car kids)))
4990 rv))
4991
4992 (defun js2-end-check-label (node)
4993 "A labeled statement implies that there may be a break to the label.
4994 The function processes the labeled statement and then checks the
4995 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4996 particular label.
4997 Returns logical OR of END_* flags."
4998 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4999 (logior rv (js2-node-get-prop node
5000 'CONTROL_BLOCK_PROP
5001 js2-END_UNREACHED))))
5002
5003 (defun js2-end-check-break (node)
5004 "When a break is encountered annotate the statement being broken
5005 out of by setting its CONTROL_BLOCK_PROP property.
5006 Returns logical OR of END_* flags."
5007 (and (js2-break-node-target node)
5008 (js2-node-set-prop (js2-break-node-target node)
5009 'CONTROL_BLOCK_PROP
5010 js2-END_DROPS_OFF))
5011 js2-END_UNREACHED)
5012
5013 (defun js2-end-check (node)
5014 "Examine the body of a function, doing a basic reachability analysis.
5015 Returns a combination of flags END_* flags that indicate
5016 how the function execution can terminate. These constitute only the
5017 pessimistic set of termination conditions. It is possible that at
5018 runtime certain code paths will never be actually taken. Hence this
5019 analysis will flag errors in cases where there may not be errors.
5020 Returns logical OR of END_* flags"
5021 (let (kid)
5022 (cond
5023 ((js2-break-node-p node)
5024 (js2-end-check-break node))
5025 ((js2-expr-stmt-node-p node)
5026 (if (setq kid (js2-expr-stmt-node-expr node))
5027 (js2-end-check kid)
5028 js2-END_DROPS_OFF))
5029 ((or (js2-continue-node-p node)
5030 (js2-throw-node-p node))
5031 js2-END_UNREACHED)
5032 ((js2-return-node-p node)
5033 (if (setq kid (js2-return-node-retval node))
5034 js2-END_RETURNS_VALUE
5035 js2-END_RETURNS))
5036 ((js2-loop-node-p node)
5037 (js2-end-check-loop node))
5038 ((js2-switch-node-p node)
5039 (js2-end-check-switch node))
5040 ((js2-labeled-stmt-node-p node)
5041 (js2-end-check-label node))
5042 ((js2-if-node-p node)
5043 (js2-end-check-if node))
5044 ((js2-try-node-p node)
5045 (js2-end-check-try node))
5046 ((js2-block-node-p node)
5047 (if (null (js2-block-node-kids node))
5048 js2-END_DROPS_OFF
5049 (js2-end-check-block node)))
5050 ((js2-yield-node-p node)
5051 js2-END_YIELDS)
5052 (t
5053 js2-END_DROPS_OFF))))
5054
5055 (defun js2-always-defined-boolean-p (node)
5056 "Check if NODE always evaluates to true or false in boolean context.
5057 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5058 nor always false."
5059 (let ((tt (js2-node-type node))
5060 num)
5061 (cond
5062 ((or (= tt js2-FALSE) (= tt js2-NULL))
5063 'ALWAYS_FALSE)
5064 ((= tt js2-TRUE)
5065 'ALWAYS_TRUE)
5066 ((= tt js2-NUMBER)
5067 (setq num (js2-number-node-num-value node))
5068 (if (and (not (eq num 0.0e+NaN))
5069 (not (zerop num)))
5070 'ALWAYS_TRUE
5071 'ALWAYS_FALSE))
5072 (t
5073 nil))))
5074
5075 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5076 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5077
5078 (defvar js2-tokens nil
5079 "List of all defined token names.") ; initialized in `js2-token-names'
5080
5081 (defconst js2-token-names
5082 (let* ((names (make-vector js2-num-tokens -1))
5083 (case-fold-search nil) ; only match js2-UPPER_CASE
5084 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5085 (loop for sym in syms
5086 for i from 0
5087 do
5088 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5089 (not (boundp sym)))
5090 (aset names (symbol-value sym) ; code, e.g. 152
5091 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5092 (push sym js2-tokens)))
5093 names)
5094 "Vector mapping int values to token string names, sans `js2-' prefix.")
5095
5096 (defun js2-token-name (tok)
5097 "Return a string name for TOK, a token symbol or code.
5098 Signals an error if it's not a recognized token."
5099 (let ((code tok))
5100 (if (symbolp tok)
5101 (setq code (symbol-value tok)))
5102 (if (eq code -1)
5103 "ERROR"
5104 (if (and (numberp code)
5105 (not (minusp code))
5106 (< code js2-num-tokens))
5107 (aref js2-token-names code)
5108 (error "Invalid token: %s" code)))))
5109
5110 (defsubst js2-token-sym (tok)
5111 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5112 (intern (js2-token-name tok)))
5113
5114 (defconst js2-token-codes
5115 (let ((table (make-hash-table :test 'eq :size 256)))
5116 (loop for name across js2-token-names
5117 for sym = (intern (concat "js2-" name))
5118 do
5119 (puthash sym (symbol-value sym) table))
5120 ;; clean up a few that are "wrong" in Rhino's token codes
5121 (puthash 'js2-DELETE js2-DELPROP table)
5122 table)
5123 "Hashtable mapping token symbols to their bytecodes.")
5124
5125 (defsubst js2-token-code (sym)
5126 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5127 (or (gethash sym js2-token-codes)
5128 (error "Invalid token symbol: %s " sym))) ; signal code bug
5129
5130 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5131 (setq js2-token-end js2-ts-cursor)
5132 (js2-report-error msg nil
5133 (or beg js2-token-beg)
5134 (or len (- js2-token-end js2-token-beg)))
5135 (unless no-throw
5136 (throw 'return js2-ERROR)))
5137
5138 (defsubst js2-get-string-from-buffer ()
5139 "Reverse the char accumulator and return it as a string."
5140 (setq js2-token-end js2-ts-cursor)
5141 (if js2-ts-string-buffer
5142 (apply #'string (nreverse js2-ts-string-buffer))
5143 ""))
5144
5145 ;; TODO: could potentially avoid a lot of consing by allocating a
5146 ;; char buffer the way Rhino does.
5147 (defsubst js2-add-to-string (c)
5148 (push c js2-ts-string-buffer))
5149
5150 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5151 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5152 ;; any other character: when it's not part of the current token, we
5153 ;; unget it, allowing it to be read again by the following call.
5154 (defsubst js2-unget-char ()
5155 (decf js2-ts-cursor))
5156
5157 ;; Rhino distinguishes \r and \n line endings. We don't need to
5158 ;; because we only scan from Emacs buffers, which always use \n.
5159 (defsubst js2-get-char ()
5160 "Read and return the next character from the input buffer.
5161 Increments `js2-ts-lineno' if the return value is a newline char.
5162 Updates `js2-ts-cursor' to the point after the returned char.
5163 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5164 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5165 (let (c)
5166 ;; check for end of buffer
5167 (if (>= js2-ts-cursor (point-max))
5168 (setq js2-ts-hit-eof t
5169 js2-ts-cursor (1+ js2-ts-cursor)
5170 c js2-EOF_CHAR) ; return value
5171 ;; otherwise read next char
5172 (setq c (char-before (incf js2-ts-cursor)))
5173 ;; if we read a newline, update counters
5174 (if (= c ?\n)
5175 (setq js2-ts-line-start js2-ts-cursor
5176 js2-ts-lineno (1+ js2-ts-lineno)))
5177 ;; TODO: skip over format characters
5178 c)))
5179
5180 (defsubst js2-read-unicode-escape ()
5181 "Read a \\uNNNN sequence from the input.
5182 Assumes the ?\ and ?u have already been read.
5183 Returns the unicode character, or nil if it wasn't a valid character.
5184 Doesn't change the values of any scanner variables."
5185 ;; I really wish I knew a better way to do this, but I can't
5186 ;; find the Emacs function that takes a 16-bit int and converts
5187 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5188 ;; Have to first check that it's 4 hex characters or it may stop
5189 ;; the read early.
5190 (ignore-errors
5191 (let ((s (buffer-substring-no-properties js2-ts-cursor
5192 (+ 4 js2-ts-cursor))))
5193 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5194 (read (concat "?\\u" s))))))
5195
5196 (defsubst js2-match-char (test)
5197 "Consume and return next character if it matches TEST, a character.
5198 Returns nil and consumes nothing if TEST is not the next character."
5199 (let ((c (js2-get-char)))
5200 (if (eq c test)
5201 t
5202 (js2-unget-char)
5203 nil)))
5204
5205 (defsubst js2-peek-char ()
5206 (prog1
5207 (js2-get-char)
5208 (js2-unget-char)))
5209
5210 (defsubst js2-java-identifier-start-p (c)
5211 (or
5212 (memq c '(?$ ?_))
5213 (js2-char-uppercase-p c)
5214 (js2-char-lowercase-p c)))
5215
5216 (defsubst js2-java-identifier-part-p (c)
5217 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5218 ;; TODO: make me Unicode-friendly. See comments above.
5219 (or
5220 (memq c '(?$ ?_))
5221 (js2-char-uppercase-p c)
5222 (js2-char-lowercase-p c)
5223 (and (>= c ?0) (<= c ?9))))
5224
5225 (defsubst js2-alpha-p (c)
5226 (cond ((and (<= ?A c) (<= c ?Z)) t)
5227 ((and (<= ?a c) (<= c ?z)) t)
5228 (t nil)))
5229
5230 (defsubst js2-digit-p (c)
5231 (and (<= ?0 c) (<= c ?9)))
5232
5233 (defsubst js2-js-space-p (c)
5234 (if (<= c 127)
5235 (memq c '(#x20 #x9 #xB #xC #xD))
5236 (or
5237 (eq c #xA0)
5238 ;; TODO: change this nil to check for Unicode space character
5239 nil)))
5240
5241 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5242
5243 (defsubst js2-skip-line ()
5244 "Skip to end of line."
5245 (let (c)
5246 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5247 (js2-unget-char)
5248 (setq js2-token-end js2-ts-cursor)))
5249
5250 (defun js2-init-scanner (&optional buf line)
5251 "Create token stream for BUF starting on LINE.
5252 BUF defaults to `current-buffer' and line defaults to 1.
5253
5254 A buffer can only have one scanner active at a time, which yields
5255 dramatically simpler code than using a defstruct. If you need to
5256 have simultaneous scanners in a buffer, copy the regions to scan
5257 into temp buffers."
5258 (with-current-buffer (or buf (current-buffer))
5259 (setq js2-ts-dirty-line nil
5260 js2-ts-regexp-flags nil
5261 js2-ts-string ""
5262 js2-ts-number nil
5263 js2-ts-hit-eof nil
5264 js2-ts-line-start 0
5265 js2-ts-lineno (or line 1)
5266 js2-ts-line-end-char -1
5267 js2-ts-cursor (point-min)
5268 js2-ts-is-xml-attribute nil
5269 js2-ts-xml-is-tag-content nil
5270 js2-ts-xml-open-tags-count 0
5271 js2-ts-string-buffer nil)))
5272
5273 ;; This function uses the cached op, string and number fields in
5274 ;; TokenStream; if getToken has been called since the passed token
5275 ;; was scanned, the op or string printed may be incorrect.
5276 (defun js2-token-to-string (token)
5277 ;; Not sure where this function is used in Rhino. Not tested.
5278 (if (not js2-debug-print-trees)
5279 ""
5280 (let ((name (js2-token-name token)))
5281 (cond
5282 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5283 (concat name " `" js2-ts-string "'"))
5284 ((eq token js2-NUMBER)
5285 (format "NUMBER %g" js2-ts-number))
5286 (t
5287 name)))))
5288
5289 (defconst js2-keywords
5290 '(break
5291 case catch const continue
5292 debugger default delete do
5293 else enum
5294 false finally for function
5295 if in instanceof import
5296 let
5297 new null
5298 return
5299 switch
5300 this throw true try typeof
5301 var void
5302 while with
5303 yield))
5304
5305 ;; Token names aren't exactly the same as the keywords, unfortunately.
5306 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5307 (defconst js2-kwd-tokens
5308 (let ((table (make-vector js2-num-tokens nil))
5309 (tokens
5310 (list js2-BREAK
5311 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5312 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5313 js2-ELSE
5314 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5315 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5316 js2-LET
5317 js2-NEW js2-NULL
5318 js2-RETURN
5319 js2-SWITCH
5320 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5321 js2-VAR
5322 js2-WHILE js2-WITH
5323 js2-YIELD)))
5324 (dolist (i tokens)
5325 (aset table i 'font-lock-keyword-face))
5326 (aset table js2-STRING 'font-lock-string-face)
5327 (aset table js2-REGEXP 'font-lock-string-face)
5328 (aset table js2-COMMENT 'font-lock-comment-face)
5329 (aset table js2-THIS 'font-lock-builtin-face)
5330 (aset table js2-VOID 'font-lock-constant-face)
5331 (aset table js2-NULL 'font-lock-constant-face)
5332 (aset table js2-TRUE 'font-lock-constant-face)
5333 (aset table js2-FALSE 'font-lock-constant-face)
5334 table)
5335 "Vector whose values are non-nil for tokens that are keywords.
5336 The values are default faces to use for highlighting the keywords.")
5337
5338 (defconst js2-reserved-words
5339 '(abstract
5340 boolean byte
5341 char class
5342 double
5343 enum export extends
5344 final float
5345 goto
5346 implements import int interface
5347 long
5348 native
5349 package private protected public
5350 short static super synchronized
5351 throws transient
5352 volatile))
5353
5354 (defconst js2-keyword-names
5355 (let ((table (make-hash-table :test 'equal)))
5356 (loop for k in js2-keywords
5357 do (puthash
5358 (symbol-name k) ; instanceof
5359 (intern (concat "js2-"
5360 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5361 table))
5362 table)
5363 "JavaScript keywords by name, mapped to their symbols.")
5364
5365 (defconst js2-reserved-word-names
5366 (let ((table (make-hash-table :test 'equal)))
5367 (loop for k in js2-reserved-words
5368 do
5369 (puthash (symbol-name k) 'js2-RESERVED table))
5370 table)
5371 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5372
5373 (defsubst js2-collect-string (buf)
5374 "Convert BUF, a list of chars, to a string.
5375 Reverses BUF before converting."
5376 (cond
5377 ((stringp buf)
5378 buf)
5379 ((null buf) ; for emacs21 compat
5380 "")
5381 (t
5382 (if buf
5383 (apply #'string (nreverse buf))
5384 ""))))
5385
5386 (defun js2-string-to-keyword (s)
5387 "Return token for S, a string, if S is a keyword or reserved word.
5388 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5389 (or (gethash s js2-keyword-names)
5390 (gethash s js2-reserved-word-names)))
5391
5392 (defsubst js2-ts-set-char-token-bounds ()
5393 "Used when next token is one character."
5394 (setq js2-token-beg (1- js2-ts-cursor)
5395 js2-token-end js2-ts-cursor))
5396
5397 (defsubst js2-ts-return (token)
5398 "Return an N-character TOKEN from `js2-get-token'.
5399 Updates `js2-token-end' accordingly."
5400 (setq js2-token-end js2-ts-cursor)
5401 (throw 'return token))
5402
5403 (defsubst js2-x-digit-to-int (c accumulator)
5404 "Build up a hex number.
5405 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5406 corresponding number. Otherwise return -1."
5407 (catch 'return
5408 (catch 'check
5409 ;; Use 0..9 < A..Z < a..z
5410 (cond
5411 ((<= c ?9)
5412 (decf c ?0)
5413 (if (<= 0 c)
5414 (throw 'check nil)))
5415 ((<= c ?F)
5416 (when (<= ?A c)
5417 (decf c (- ?A 10))
5418 (throw 'check nil)))
5419 ((<= c ?f)
5420 (when (<= ?a c)
5421 (decf c (- ?a 10))
5422 (throw 'check nil))))
5423 (throw 'return -1))
5424 (logior c (lsh accumulator 4))))
5425
5426 (defun js2-get-token ()
5427 "Return next JavaScript token, an int such as js2-RETURN."
5428 (let (c
5429 c1
5430 identifier-start
5431 is-unicode-escape-start
5432 contains-escape
5433 escape-val
5434 escape-start
5435 str
5436 result
5437 base
5438 is-integer
5439 quote-char
5440 val
5441 look-for-slash
5442 continue)
5443 (catch 'return
5444 (while t
5445 ;; Eat whitespace, possibly sensitive to newlines.
5446 (setq continue t)
5447 (while continue
5448 (setq c (js2-get-char))
5449 (cond
5450 ((eq c js2-EOF_CHAR)
5451 (js2-ts-set-char-token-bounds)
5452 (throw 'return js2-EOF))
5453 ((eq c ?\n)
5454 (js2-ts-set-char-token-bounds)
5455 (setq js2-ts-dirty-line nil)
5456 (throw 'return js2-EOL))
5457 ((not (js2-js-space-p c))
5458 (if (/= c ?-) ; in case end of HTML comment
5459 (setq js2-ts-dirty-line t))
5460 (setq continue nil))))
5461 ;; Assume the token will be 1 char - fixed up below.
5462 (js2-ts-set-char-token-bounds)
5463 (when (eq c ?@)
5464 (throw 'return js2-XMLATTR))
5465 ;; identifier/keyword/instanceof?
5466 ;; watch out for starting with a <backslash>
5467 (cond
5468 ((eq c ?\\)
5469 (setq c (js2-get-char))
5470 (if (eq c ?u)
5471 (setq identifier-start t
5472 is-unicode-escape-start t
5473 js2-ts-string-buffer nil)
5474 (setq identifier-start nil)
5475 (js2-unget-char)
5476 (setq c ?\\)))
5477 (t
5478 (when (setq identifier-start (js2-java-identifier-start-p c))
5479 (setq js2-ts-string-buffer nil)
5480 (js2-add-to-string c))))
5481 (when identifier-start
5482 (setq contains-escape is-unicode-escape-start)
5483 (catch 'break
5484 (while t
5485 (if is-unicode-escape-start
5486 ;; strictly speaking we should probably push-back
5487 ;; all the bad characters if the <backslash>uXXXX
5488 ;; sequence is malformed. But since there isn't a
5489 ;; correct context(is there?) for a bad Unicode
5490 ;; escape sequence in an identifier, we can report
5491 ;; an error here.
5492 (progn
5493 (setq escape-val 0)
5494 (dotimes (i 4)
5495 (setq c (js2-get-char)
5496 escape-val (js2-x-digit-to-int c escape-val))
5497 ;; Next check takes care of c < 0 and bad escape
5498 (if (minusp escape-val)
5499 (throw 'break nil)))
5500 (if (minusp escape-val)
5501 (js2-report-scan-error "msg.invalid.escape" t))
5502 (js2-add-to-string escape-val)
5503 (setq is-unicode-escape-start nil))
5504 (setq c (js2-get-char))
5505 (cond
5506 ((eq c ?\\)
5507 (setq c (js2-get-char))
5508 (if (eq c ?u)
5509 (setq is-unicode-escape-start t
5510 contains-escape t)
5511 (js2-report-scan-error "msg.illegal.character" t)))
5512 (t
5513 (if (or (eq c js2-EOF_CHAR)
5514 (not (js2-java-identifier-part-p c)))
5515 (throw 'break nil))
5516 (js2-add-to-string c))))))
5517 (js2-unget-char)
5518 (setq str (js2-get-string-from-buffer))
5519 (unless contains-escape
5520 ;; OPT we shouldn't have to make a string (object!) to
5521 ;; check if it's a keyword.
5522 ;; Return the corresponding token if it's a keyword
5523 (when (setq result (js2-string-to-keyword str))
5524 (if (and (< js2-language-version 170)
5525 (memq result '(js2-LET js2-YIELD)))
5526 ;; LET and YIELD are tokens only in 1.7 and later
5527 (setq result 'js2-NAME))
5528 (if (not (eq result js2-RESERVED))
5529 (throw 'return (js2-token-code result)))
5530 (js2-report-warning "msg.reserved.keyword" str)))
5531 ;; If we want to intern these as Rhino does, just use (intern str)
5532 (setq js2-ts-string str)
5533 (throw 'return js2-NAME)) ; end identifier/kwd check
5534 ;; is it a number?
5535 (when (or (js2-digit-p c)
5536 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5537 (setq js2-ts-string-buffer nil
5538 base 10)
5539 (when (eq c ?0)
5540 (setq c (js2-get-char))
5541 (cond
5542 ((or (eq c ?x) (eq c ?X))
5543 (setq base 16)
5544 (setq c (js2-get-char)))
5545 ((js2-digit-p c)
5546 (setq base 8))
5547 (t
5548 (js2-add-to-string ?0))))
5549 (if (eq base 16)
5550 (while (<= 0 (js2-x-digit-to-int c 0))
5551 (js2-add-to-string c)
5552 (setq c (js2-get-char)))
5553 (while (and (<= ?0 c) (<= c ?9))
5554 ;; We permit 08 and 09 as decimal numbers, which
5555 ;; makes our behavior a superset of the ECMA
5556 ;; numeric grammar. We might not always be so
5557 ;; permissive, so we warn about it.
5558 (when (and (eq base 8) (>= c ?8))
5559 (js2-report-warning "msg.bad.octal.literal"
5560 (if (eq c ?8) "8" "9"))
5561 (setq base 10))
5562 (js2-add-to-string c)
5563 (setq c (js2-get-char))))
5564 (setq is-integer t)
5565 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5566 (setq is-integer nil)
5567 (when (eq c ?.)
5568 (loop do
5569 (js2-add-to-string c)
5570 (setq c (js2-get-char))
5571 while (js2-digit-p c)))
5572 (when (memq c '(?e ?E))
5573 (js2-add-to-string c)
5574 (setq c (js2-get-char))
5575 (when (memq c '(?+ ?-))
5576 (js2-add-to-string c)
5577 (setq c (js2-get-char)))
5578 (unless (js2-digit-p c)
5579 (js2-report-scan-error "msg.missing.exponent" t))
5580 (loop do
5581 (js2-add-to-string c)
5582 (setq c (js2-get-char))
5583 while (js2-digit-p c))))
5584 (js2-unget-char)
5585 (setq js2-ts-string (js2-get-string-from-buffer)
5586 js2-ts-number
5587 (if (and (eq base 10) (not is-integer))
5588 (string-to-number js2-ts-string)
5589 ;; TODO: call runtime number-parser. Some of it is in
5590 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5591 (string-to-number js2-ts-string)))
5592 (throw 'return js2-NUMBER))
5593 ;; is it a string?
5594 (when (memq c '(?\" ?\'))
5595 ;; We attempt to accumulate a string the fast way, by
5596 ;; building it directly out of the reader. But if there
5597 ;; are any escaped characters in the string, we revert to
5598 ;; building it out of a string buffer.
5599 (setq quote-char c
5600 js2-ts-string-buffer nil
5601 c (js2-get-char))
5602 (catch 'break
5603 (while (/= c quote-char)
5604 (catch 'continue
5605 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5606 (js2-unget-char)
5607 (setq js2-token-end js2-ts-cursor)
5608 (js2-report-error "msg.unterminated.string.lit")
5609 (throw 'return js2-STRING))
5610 (when (eq c ?\\)
5611 ;; We've hit an escaped character
5612 (setq c (js2-get-char))
5613 (case c
5614 (?b (setq c ?\b))
5615 (?f (setq c ?\f))
5616 (?n (setq c ?\n))
5617 (?r (setq c ?\r))
5618 (?t (setq c ?\t))
5619 (?v (setq c ?\v))
5620 (?u
5621 (setq c1 (js2-read-unicode-escape))
5622 (if js2-parse-ide-mode
5623 (if c1
5624 (progn
5625 ;; just copy the string in IDE-mode
5626 (js2-add-to-string ?\\)
5627 (js2-add-to-string ?u)
5628 (dotimes (i 3)
5629 (js2-add-to-string (js2-get-char)))
5630 (setq c (js2-get-char))) ; added at end of loop
5631 ;; flag it as an invalid escape
5632 (js2-report-warning "msg.invalid.escape"
5633 nil (- js2-ts-cursor 2) 6))
5634 ;; Get 4 hex digits; if the u escape is not
5635 ;; followed by 4 hex digits, use 'u' + the
5636 ;; literal character sequence that follows.
5637 (js2-add-to-string ?u)
5638 (setq escape-val 0)
5639 (dotimes (i 4)
5640 (setq c (js2-get-char)
5641 escape-val (js2-x-digit-to-int c escape-val))
5642 (if (minusp escape-val)
5643 (throw 'continue nil))
5644 (js2-add-to-string c))
5645 ;; prepare for replace of stored 'u' sequence by escape value
5646 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5647 c escape-val)))
5648 (?x
5649 ;; Get 2 hex digits, defaulting to 'x'+literal
5650 ;; sequence, as above.
5651 (setq c (js2-get-char)
5652 escape-val (js2-x-digit-to-int c 0))
5653 (if (minusp escape-val)
5654 (progn
5655 (js2-add-to-string ?x)
5656 (throw 'continue nil))
5657 (setq c1 c
5658 c (js2-get-char)
5659 escape-val (js2-x-digit-to-int c escape-val))
5660 (if (minusp escape-val)
5661 (progn
5662 (js2-add-to-string ?x)
5663 (js2-add-to-string c1)
5664 (throw 'continue nil))
5665 ;; got 2 hex digits
5666 (setq c escape-val))))
5667 (?\n
5668 ;; Remove line terminator after escape to follow
5669 ;; SpiderMonkey and C/C++
5670 (setq c (js2-get-char))
5671 (throw 'continue nil))
5672 (t
5673 (when (and (<= ?0 c) (< c ?8))
5674 (setq val (- c ?0)
5675 c (js2-get-char))
5676 (when (and (<= ?0 c) (< c ?8))
5677 (setq val (- (+ (* 8 val) c) ?0)
5678 c (js2-get-char))
5679 (when (and (<= ?0 c)
5680 (< c ?8)
5681 (< val #o37))
5682 ;; c is 3rd char of octal sequence only
5683 ;; if the resulting val <= 0377
5684 (setq val (- (+ (* 8 val) c) ?0)
5685 c (js2-get-char))))
5686 (js2-unget-char)
5687 (setq c val)))))
5688 (js2-add-to-string c)
5689 (setq c (js2-get-char)))))
5690 (setq js2-ts-string (js2-get-string-from-buffer))
5691 (throw 'return js2-STRING))
5692 (case c
5693 (?\;
5694 (throw 'return js2-SEMI))
5695 (?\[
5696 (throw 'return js2-LB))
5697 (?\]
5698 (throw 'return js2-RB))
5699 (?{
5700 (throw 'return js2-LC))
5701 (?}
5702 (throw 'return js2-RC))
5703 (?\(
5704 (throw 'return js2-LP))
5705 (?\)
5706 (throw 'return js2-RP))
5707 (?,
5708 (throw 'return js2-COMMA))
5709 (??
5710 (throw 'return js2-HOOK))
5711 (?:
5712 (if (js2-match-char ?:)
5713 (js2-ts-return js2-COLONCOLON)
5714 (throw 'return js2-COLON)))
5715 (?.
5716 (if (js2-match-char ?.)
5717 (js2-ts-return js2-DOTDOT)
5718 (if (js2-match-char ?\()
5719 (js2-ts-return js2-DOTQUERY)
5720 (throw 'return js2-DOT))))
5721 (?|
5722 (if (js2-match-char ?|)
5723 (throw 'return js2-OR)
5724 (if (js2-match-char ?=)
5725 (js2-ts-return js2-ASSIGN_BITOR)
5726 (throw 'return js2-BITOR))))
5727 (?^
5728 (if (js2-match-char ?=)
5729 (js2-ts-return js2-ASSIGN_BITOR)
5730 (throw 'return js2-BITXOR)))
5731 (?&
5732 (if (js2-match-char ?&)
5733 (throw 'return js2-AND)
5734 (if (js2-match-char ?=)
5735 (js2-ts-return js2-ASSIGN_BITAND)
5736 (throw 'return js2-BITAND))))
5737 (?=
5738 (if (js2-match-char ?=)
5739 (if (js2-match-char ?=)
5740 (js2-ts-return js2-SHEQ)
5741 (throw 'return js2-EQ))
5742 (throw 'return js2-ASSIGN)))
5743 (?!
5744 (if (js2-match-char ?=)
5745 (if (js2-match-char ?=)
5746 (js2-ts-return js2-SHNE)
5747 (js2-ts-return js2-NE))
5748 (throw 'return js2-NOT)))
5749 (?<
5750 ;; NB:treat HTML begin-comment as comment-till-eol
5751 (when (js2-match-char ?!)
5752 (when (js2-match-char ?-)
5753 (when (js2-match-char ?-)
5754 (js2-skip-line)
5755 (setq js2-ts-comment-type 'html)
5756 (throw 'return js2-COMMENT)))
5757 (js2-unget-char))
5758 (if (js2-match-char ?<)
5759 (if (js2-match-char ?=)
5760 (js2-ts-return js2-ASSIGN_LSH)
5761 (js2-ts-return js2-LSH))
5762 (if (js2-match-char ?=)
5763 (js2-ts-return js2-LE)
5764 (throw 'return js2-LT))))
5765 (?>
5766 (if (js2-match-char ?>)
5767 (if (js2-match-char ?>)
5768 (if (js2-match-char ?=)
5769 (js2-ts-return js2-ASSIGN_URSH)
5770 (js2-ts-return js2-URSH))
5771 (if (js2-match-char ?=)
5772 (js2-ts-return js2-ASSIGN_RSH)
5773 (js2-ts-return js2-RSH)))
5774 (if (js2-match-char ?=)
5775 (js2-ts-return js2-GE)
5776 (throw 'return js2-GT))))
5777 (?*
5778 (if (js2-match-char ?=)
5779 (js2-ts-return js2-ASSIGN_MUL)
5780 (throw 'return js2-MUL)))
5781 (?/
5782 ;; is it a // comment?
5783 (when (js2-match-char ?/)
5784 (setq js2-token-beg (- js2-ts-cursor 2))
5785 (js2-skip-line)
5786 (setq js2-ts-comment-type 'line)
5787 ;; include newline so highlighting goes to end of window
5788 (incf js2-token-end)
5789 (throw 'return js2-COMMENT))
5790 ;; is it a /* comment?
5791 (when (js2-match-char ?*)
5792 (setq look-for-slash nil
5793 js2-token-beg (- js2-ts-cursor 2)
5794 js2-ts-comment-type
5795 (if (js2-match-char ?*)
5796 (progn
5797 (setq look-for-slash t)
5798 'jsdoc)
5799 'block))
5800 (while t
5801 (setq c (js2-get-char))
5802 (cond
5803 ((eq c js2-EOF_CHAR)
5804 (setq js2-token-end (1- js2-ts-cursor))
5805 (js2-report-error "msg.unterminated.comment")
5806 (throw 'return js2-COMMENT))
5807 ((eq c ?*)
5808 (setq look-for-slash t))
5809 ((eq c ?/)
5810 (if look-for-slash
5811 (js2-ts-return js2-COMMENT)))
5812 (t
5813 (setq look-for-slash nil
5814 js2-token-end js2-ts-cursor)))))
5815 (if (js2-match-char ?=)
5816 (js2-ts-return js2-ASSIGN_DIV)
5817 (throw 'return js2-DIV)))
5818 (?#
5819 (when js2-skip-preprocessor-directives
5820 (js2-skip-line)
5821 (setq js2-ts-comment-type 'preprocessor
5822 js2-token-end js2-ts-cursor)
5823 (throw 'return js2-COMMENT))
5824 (throw 'return js2-ERROR))
5825 (?%
5826 (if (js2-match-char ?=)
5827 (js2-ts-return js2-ASSIGN_MOD)
5828 (throw 'return js2-MOD)))
5829 (?~
5830 (throw 'return js2-BITNOT))
5831 (?+
5832 (if (js2-match-char ?=)
5833 (js2-ts-return js2-ASSIGN_ADD)
5834 (if (js2-match-char ?+)
5835 (js2-ts-return js2-INC)
5836 (throw 'return js2-ADD))))
5837 (?-
5838 (cond
5839 ((js2-match-char ?=)
5840 (setq c js2-ASSIGN_SUB))
5841 ((js2-match-char ?-)
5842 (unless js2-ts-dirty-line
5843 ;; treat HTML end-comment after possible whitespace
5844 ;; after line start as comment-until-eol
5845 (when (js2-match-char ?>)
5846 (js2-skip-line)
5847 (setq js2-ts-comment-type 'html)
5848 (throw 'return js2-COMMENT)))
5849 (setq c js2-DEC))
5850 (t
5851 (setq c js2-SUB)))
5852 (setq js2-ts-dirty-line t)
5853 (js2-ts-return c))
5854 (otherwise
5855 (js2-report-scan-error "msg.illegal.character")))))))
5856
5857 (defun js2-read-regexp (start-token)
5858 "Called by parser when it gets / or /= in literal context."
5859 (let (c
5860 err
5861 in-class ; inside a '[' .. ']' character-class
5862 flags
5863 (continue t))
5864 (setq js2-token-beg js2-ts-cursor
5865 js2-ts-string-buffer nil
5866 js2-ts-regexp-flags nil)
5867 (if (eq start-token js2-ASSIGN_DIV)
5868 ;; mis-scanned /=
5869 (js2-add-to-string ?=)
5870 (if (not (eq start-token js2-DIV))
5871 (error "failed assertion")))
5872 (while (and (not err)
5873 (or (/= (setq c (js2-get-char)) ?/)
5874 in-class))
5875 (cond
5876 ((or (= c ?\n)
5877 (= c js2-EOF_CHAR))
5878 (setq js2-token-end (1- js2-ts-cursor)
5879 err t
5880 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5881 (js2-report-error "msg.unterminated.re.lit"))
5882 (t (cond
5883 ((= c ?\\)
5884 (js2-add-to-string c)
5885 (setq c (js2-get-char)))
5886 ((= c ?\[)
5887 (setq in-class t))
5888 ((= c ?\])
5889 (setq in-class nil)))
5890 (js2-add-to-string c))))
5891 (unless err
5892 (while continue
5893 (cond
5894 ((js2-match-char ?g)
5895 (push ?g flags))
5896 ((js2-match-char ?i)
5897 (push ?i flags))
5898 ((js2-match-char ?m)
5899 (push ?m flags))
5900 (t
5901 (setq continue nil))))
5902 (if (js2-alpha-p (js2-peek-char))
5903 (js2-report-scan-error "msg.invalid.re.flag" t
5904 js2-ts-cursor 1))
5905 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5906 js2-ts-regexp-flags (js2-collect-string flags)
5907 js2-token-end js2-ts-cursor)
5908 ;; tell `parse-partial-sexp' to ignore this range of chars
5909 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5910
5911 (defun js2-get-first-xml-token ()
5912 (setq js2-ts-xml-open-tags-count 0
5913 js2-ts-is-xml-attribute nil
5914 js2-ts-xml-is-tag-content nil)
5915 (js2-unget-char)
5916 (js2-get-next-xml-token))
5917
5918 (defsubst js2-xml-discard-string ()
5919 "Throw away the string in progress and flag an XML parse error."
5920 (setq js2-ts-string-buffer nil
5921 js2-ts-string nil)
5922 (js2-report-scan-error "msg.XML.bad.form" t))
5923
5924 (defun js2-get-next-xml-token ()
5925 (setq js2-ts-string-buffer nil ; for recording the XML
5926 js2-token-beg js2-ts-cursor)
5927 (let (c result)
5928 (setq result
5929 (catch 'return
5930 (while t
5931 (setq c (js2-get-char))
5932 (cond
5933 ((= c js2-EOF_CHAR)
5934 (throw 'return js2-ERROR))
5935 (js2-ts-xml-is-tag-content
5936 (case c
5937 (?>
5938 (js2-add-to-string c)
5939 (setq js2-ts-xml-is-tag-content nil
5940 js2-ts-is-xml-attribute nil))
5941 (?/
5942 (js2-add-to-string c)
5943 (when (eq ?> (js2-peek-char))
5944 (setq c (js2-get-char))
5945 (js2-add-to-string c)
5946 (setq js2-ts-xml-is-tag-content nil)
5947 (decf js2-ts-xml-open-tags-count)))
5948 (?{
5949 (js2-unget-char)
5950 (setq js2-ts-string (js2-get-string-from-buffer))
5951 (throw 'return js2-XML))
5952 ((?\' ?\")
5953 (js2-add-to-string c)
5954 (unless (js2-read-quoted-string c)
5955 (throw 'return js2-ERROR)))
5956 (?=
5957 (js2-add-to-string c)
5958 (setq js2-ts-is-xml-attribute t))
5959 ((? ?\t ?\r ?\n)
5960 (js2-add-to-string c))
5961 (t
5962 (js2-add-to-string c)
5963 (setq js2-ts-is-xml-attribute nil)))
5964 (when (and (not js2-ts-xml-is-tag-content)
5965 (zerop js2-ts-xml-open-tags-count))
5966 (setq js2-ts-string (js2-get-string-from-buffer))
5967 (throw 'return js2-XMLEND)))
5968 (t
5969 ;; else not tag content
5970 (case c
5971 (?<
5972 (js2-add-to-string c)
5973 (setq c (js2-peek-char))
5974 (case c
5975 (?!
5976 (setq c (js2-get-char)) ;; skip !
5977 (js2-add-to-string c)
5978 (setq c (js2-peek-char))
5979 (case c
5980 (?-
5981 (setq c (js2-get-char)) ;; skip -
5982 (js2-add-to-string c)
5983 (if (eq c ?-)
5984 (progn
5985 (js2-add-to-string c)
5986 (unless (js2-read-xml-comment)
5987 (throw 'return js2-ERROR)))
5988 (js2-xml-discard-string)
5989 (throw 'return js2-ERROR)))
5990 (?\[
5991 (setq c (js2-get-char)) ;; skip [
5992 (js2-add-to-string c)
5993 (if (and (= (js2-get-char) ?C)
5994 (= (js2-get-char) ?D)
5995 (= (js2-get-char) ?A)
5996 (= (js2-get-char) ?T)
5997 (= (js2-get-char) ?A)
5998 (= (js2-get-char) ?\[))
5999 (progn
6000 (js2-add-to-string ?C)
6001 (js2-add-to-string ?D)
6002 (js2-add-to-string ?A)
6003 (js2-add-to-string ?T)
6004 (js2-add-to-string ?A)
6005 (js2-add-to-string ?\[)
6006 (unless (js2-read-cdata)
6007 (throw 'return js2-ERROR)))
6008 (js2-xml-discard-string)
6009 (throw 'return js2-ERROR)))
6010 (t
6011 (unless (js2-read-entity)
6012 (throw 'return js2-ERROR)))))
6013 (??
6014 (setq c (js2-get-char)) ;; skip ?
6015 (js2-add-to-string c)
6016 (unless (js2-read-PI)
6017 (throw 'return js2-ERROR)))
6018 (?/
6019 ;; end tag
6020 (setq c (js2-get-char)) ;; skip /
6021 (js2-add-to-string c)
6022 (when (zerop js2-ts-xml-open-tags-count)
6023 (js2-xml-discard-string)
6024 (throw 'return js2-ERROR))
6025 (setq js2-ts-xml-is-tag-content t)
6026 (decf js2-ts-xml-open-tags-count))
6027 (t
6028 ;; start tag
6029 (setq js2-ts-xml-is-tag-content t)
6030 (incf 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 (t
6036 (js2-add-to-string c))))))))
6037 (setq js2-token-end js2-ts-cursor)
6038 result))
6039
6040 (defun js2-read-quoted-string (quote)
6041 (let (c)
6042 (catch 'return
6043 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6044 (js2-add-to-string c)
6045 (if (eq c quote)
6046 (throw 'return t)))
6047 (js2-xml-discard-string) ;; throw away string in progress
6048 nil)))
6049
6050 (defun js2-read-xml-comment ()
6051 (let ((c (js2-get-char)))
6052 (catch 'return
6053 (while (/= c js2-EOF_CHAR)
6054 (catch 'continue
6055 (js2-add-to-string c)
6056 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6057 (setq c (js2-get-char))
6058 (js2-add-to-string c)
6059 (if (eq (js2-peek-char) ?>)
6060 (progn
6061 (setq c (js2-get-char)) ;; skip >
6062 (js2-add-to-string c)
6063 (throw 'return t))
6064 (throw 'continue nil)))
6065 (setq c (js2-get-char))))
6066 (js2-xml-discard-string)
6067 nil)))
6068
6069 (defun js2-read-cdata ()
6070 (let ((c (js2-get-char)))
6071 (catch 'return
6072 (while (/= c js2-EOF_CHAR)
6073 (catch 'continue
6074 (js2-add-to-string c)
6075 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6076 (setq c (js2-get-char))
6077 (js2-add-to-string c)
6078 (if (eq (js2-peek-char) ?>)
6079 (progn
6080 (setq c (js2-get-char)) ;; Skip >
6081 (js2-add-to-string c)
6082 (throw 'return t))
6083 (throw 'continue nil)))
6084 (setq c (js2-get-char))))
6085 (js2-xml-discard-string)
6086 nil)))
6087
6088 (defun js2-read-entity ()
6089 (let ((decl-tags 1)
6090 c)
6091 (catch 'return
6092 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6093 (js2-add-to-string c)
6094 (case c
6095 (?<
6096 (incf decl-tags))
6097 (?>
6098 (decf decl-tags)
6099 (if (zerop decl-tags)
6100 (throw 'return t)))))
6101 (js2-xml-discard-string)
6102 nil)))
6103
6104 (defun js2-read-PI ()
6105 "Scan an XML processing instruction."
6106 (let (c)
6107 (catch 'return
6108 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6109 (js2-add-to-string c)
6110 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6111 (setq c (js2-get-char)) ;; Skip >
6112 (js2-add-to-string c)
6113 (throw 'return t)))
6114 (js2-xml-discard-string)
6115 nil)))
6116
6117 (defun js2-scanner-get-line ()
6118 "Return the text of the current scan line."
6119 (buffer-substring (point-at-bol) (point-at-eol)))
6120
6121 ;;; Highlighting
6122
6123 (defsubst js2-set-face (beg end face &optional record)
6124 "Fontify a region. If RECORD is non-nil, record for later."
6125 (when (plusp js2-highlight-level)
6126 (setq beg (min (point-max) beg)
6127 beg (max (point-min) beg)
6128 end (min (point-max) end)
6129 end (max (point-min) end))
6130 (if record
6131 (push (list beg end face) js2-mode-fontifications)
6132 (put-text-property beg end 'face face))))
6133
6134 (defsubst js2-set-kid-face (pos kid len face)
6135 "Set-face on a child node.
6136 POS is absolute buffer position of parent.
6137 KID is the child node.
6138 LEN is the length to fontify.
6139 FACE is the face to fontify with."
6140 (js2-set-face (+ pos (js2-node-pos kid))
6141 (+ pos (js2-node-pos kid) (js2-node-len kid))
6142 face))
6143
6144 (defsubst js2-fontify-kwd (start length)
6145 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6146
6147 (defsubst js2-clear-face (beg end)
6148 (remove-text-properties beg end '(face nil
6149 help-echo nil
6150 point-entered nil
6151 c-in-sws nil)))
6152
6153 (defsubst js2-record-text-property (beg end prop value)
6154 "Record a text property to set when parsing finishes."
6155 (push (list beg end prop value) js2-mode-deferred-properties))
6156
6157 (defconst js2-ecma-global-props
6158 (concat "^"
6159 (regexp-opt
6160 '("Infinity" "NaN" "undefined" "arguments") t)
6161 "$")
6162 "Value properties of the Ecma-262 Global Object.
6163 Shown at or above `js2-highlight-level' 2.")
6164
6165 ;; might want to add the name "arguments" to this list?
6166 (defconst js2-ecma-object-props
6167 (concat "^"
6168 (regexp-opt
6169 '("prototype" "__proto__" "__parent__") t)
6170 "$")
6171 "Value properties of the Ecma-262 Object constructor.
6172 Shown at or above `js2-highlight-level' 2.")
6173
6174 (defconst js2-ecma-global-funcs
6175 (concat
6176 "^"
6177 (regexp-opt
6178 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6179 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6180 "$")
6181 "Function properties of the Ecma-262 Global object.
6182 Shown at or above `js2-highlight-level' 2.")
6183
6184 (defconst js2-ecma-number-props
6185 (concat "^"
6186 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6187 "NEGATIVE_INFINITY"
6188 "POSITIVE_INFINITY") t)
6189 "$")
6190 "Properties of the Ecma-262 Number constructor.
6191 Shown at or above `js2-highlight-level' 2.")
6192
6193 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6194 "Properties of the Ecma-262 Date constructor.
6195 Shown at or above `js2-highlight-level' 2.")
6196
6197 (defconst js2-ecma-math-props
6198 (concat "^"
6199 (regexp-opt
6200 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6201 t)
6202 "$")
6203 "Properties of the Ecma-262 Math object.
6204 Shown at or above `js2-highlight-level' 2.")
6205
6206 (defconst js2-ecma-math-funcs
6207 (concat "^"
6208 (regexp-opt
6209 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6210 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6211 "$")
6212 "Function properties of the Ecma-262 Math object.
6213 Shown at or above `js2-highlight-level' 2.")
6214
6215 (defconst js2-ecma-function-props
6216 (concat
6217 "^"
6218 (regexp-opt
6219 '(;; properties of the Object prototype object
6220 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6221 "toLocaleString" "toString" "valueOf"
6222 ;; properties of the Function prototype object
6223 "apply" "call"
6224 ;; properties of the Array prototype object
6225 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6226 "splice" "unshift"
6227 ;; properties of the String prototype object
6228 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6229 "localeCompare" "match" "replace" "search" "split" "substring"
6230 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6231 "toUpperCase"
6232 ;; properties of the Number prototype object
6233 "toExponential" "toFixed" "toPrecision"
6234 ;; properties of the Date prototype object
6235 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6236 "getMinutes" "getMonth" "getSeconds" "getTime"
6237 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6238 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6239 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6240 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6241 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6242 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6243 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6244 "toTimeString" "toUTCString"
6245 ;; properties of the RegExp prototype object
6246 "exec" "test"
6247 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6248 "toSource" "__defineGetter__" "__defineSetter__"
6249 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6250 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6251 t)
6252 "$")
6253 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6254 Shown at or above `js2-highlight-level' 3.")
6255
6256 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6257 (let ((target-name (and target
6258 (js2-name-node-p target)
6259 (js2-name-node-name target)))
6260 (prop-name (if prop (js2-name-node-name prop)))
6261 (level1 (>= js2-highlight-level 1))
6262 (level2 (>= js2-highlight-level 2))
6263 (level3 (>= js2-highlight-level 3))
6264 pos
6265 face)
6266 (when level2
6267 (if call-p
6268 (cond
6269 ((and target prop)
6270 (cond
6271 ((and level3 (string-match js2-ecma-function-props prop-name))
6272 (setq face 'font-lock-builtin-face))
6273 ((and target-name prop)
6274 (cond
6275 ((string= target-name "Date")
6276 (if (string-match js2-ecma-date-props prop-name)
6277 (setq face 'font-lock-builtin-face)))
6278 ((string= target-name "Math")
6279 (if (string-match js2-ecma-math-funcs prop-name)
6280 (setq face 'font-lock-builtin-face)))))))
6281 (prop
6282 (if (string-match js2-ecma-global-funcs prop-name)
6283 (setq face 'font-lock-builtin-face))))
6284 (cond
6285 ((and target prop)
6286 (cond
6287 ((string= target-name "Number")
6288 (if (string-match js2-ecma-number-props prop-name)
6289 (setq face 'font-lock-constant-face)))
6290 ((string= target-name "Math")
6291 (if (string-match js2-ecma-math-props prop-name)
6292 (setq face 'font-lock-constant-face)))))
6293 (prop
6294 (if (string-match js2-ecma-object-props prop-name)
6295 (setq face 'font-lock-constant-face)))))
6296 (when face
6297 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6298 (js2-node-pos prop))) ; relative
6299 (+ pos (js2-node-len prop))
6300 face)))))
6301
6302 (defun js2-parse-highlight-member-expr-node (node)
6303 "Perform syntax highlighting of EcmaScript built-in properties.
6304 The variable `js2-highlight-level' governs this highighting."
6305 (let (face target prop name pos end parent call-p callee)
6306 (cond
6307 ;; case 1: simple name, e.g. foo
6308 ((js2-name-node-p node)
6309 (setq name (js2-name-node-name node))
6310 ;; possible for name to be nil in rare cases - saw it when
6311 ;; running js2-mode on an elisp buffer. Might as well try to
6312 ;; make it so js2-mode never barfs.
6313 (when name
6314 (setq face (if (string-match js2-ecma-global-props name)
6315 'font-lock-constant-face))
6316 (when face
6317 (setq pos (js2-node-pos node)
6318 end (+ pos (js2-node-len node)))
6319 (js2-set-face pos end face))))
6320 ;; case 2: property access or function call
6321 ((or (js2-prop-get-node-p node)
6322 ;; highlight function call if expr is a prop-get node
6323 ;; or a plain name (i.e. unqualified function call)
6324 (and (setq call-p (js2-call-node-p node))
6325 (setq callee (js2-call-node-target node)) ; separate setq!
6326 (or (js2-prop-get-node-p callee)
6327 (js2-name-node-p callee))))
6328 (setq parent node
6329 node (if call-p callee node))
6330 (if (and call-p (js2-name-node-p callee))
6331 (setq prop callee)
6332 (setq target (js2-prop-get-node-left node)
6333 prop (js2-prop-get-node-right node)))
6334 (cond
6335 ((js2-name-node-p target)
6336 (if (js2-name-node-p prop)
6337 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6338 (js2-parse-highlight-prop-get parent target prop call-p)
6339 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6340 (js2-parse-highlight-prop-get parent target nil call-p)))
6341 ((js2-name-node-p prop)
6342 ;; case 2c: complex target, simple name, e.g. x[y].bar
6343 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6344
6345 (defun js2-parse-highlight-member-expr-fn-name (expr)
6346 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6347 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6348 We currently only handle the case where the last component is a prop-get
6349 of a simple name. Called before EXPR has a parent node."
6350 (let (pos
6351 (name (and (js2-prop-get-node-p expr)
6352 (js2-prop-get-node-right expr))))
6353 (when (js2-name-node-p name)
6354 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6355 (js2-node-pos name)))
6356 (+ pos (js2-node-len name))
6357 'font-lock-function-name-face
6358 'record))))
6359
6360 ;; source: http://jsdoc.sourceforge.net/
6361 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6362 ;; allows type specifications, and needs work before entering the wild.
6363
6364 (defconst js2-jsdoc-param-tag-regexp
6365 (concat "^\\s-*\\*+\\s-*\\(@"
6366 "\\(?:param\\|argument\\)"
6367 "\\)"
6368 "\\s-*\\({[^}]+}\\)?" ; optional type
6369 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6370 "\\>")
6371 "Matches jsdoc tags with optional type and optional param name.")
6372
6373 (defconst js2-jsdoc-typed-tag-regexp
6374 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6375 (regexp-opt
6376 '("enum"
6377 "extends"
6378 "field"
6379 "id"
6380 "implements"
6381 "lends"
6382 "mods"
6383 "requires"
6384 "return"
6385 "returns"
6386 "throw"
6387 "throws"))
6388 "\\)\\)\\s-*\\({[^}]+}\\)?")
6389 "Matches jsdoc tags with optional type.")
6390
6391 (defconst js2-jsdoc-arg-tag-regexp
6392 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6393 (regexp-opt
6394 '("alias"
6395 "augments"
6396 "borrows"
6397 "bug"
6398 "base"
6399 "config"
6400 "default"
6401 "define"
6402 "exception"
6403 "function"
6404 "member"
6405 "memberOf"
6406 "name"
6407 "namespace"
6408 "property"
6409 "since"
6410 "suppress"
6411 "this"
6412 "throws"
6413 "type"
6414 "version"))
6415 "\\)\\)\\s-+\\([^ \t]+\\)")
6416 "Matches jsdoc tags with a single argument.")
6417
6418 (defconst js2-jsdoc-empty-tag-regexp
6419 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6420 (regexp-opt
6421 '("addon"
6422 "author"
6423 "class"
6424 "const"
6425 "constant"
6426 "constructor"
6427 "constructs"
6428 "deprecated"
6429 "desc"
6430 "description"
6431 "event"
6432 "example"
6433 "exec"
6434 "export"
6435 "fileoverview"
6436 "final"
6437 "function"
6438 "hidden"
6439 "ignore"
6440 "implicitCast"
6441 "inheritDoc"
6442 "inner"
6443 "interface"
6444 "license"
6445 "noalias"
6446 "noshadow"
6447 "notypecheck"
6448 "override"
6449 "owner"
6450 "preserve"
6451 "preserveTry"
6452 "private"
6453 "protected"
6454 "public"
6455 "static"
6456 "supported"
6457 ))
6458 "\\)\\)\\s-*")
6459 "Matches empty jsdoc tags.")
6460
6461 (defconst js2-jsdoc-link-tag-regexp
6462 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6463 "Matches a jsdoc link or code tag.")
6464
6465 (defconst js2-jsdoc-see-tag-regexp
6466 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6467 "Matches a jsdoc @see tag.")
6468
6469 (defconst js2-jsdoc-html-tag-regexp
6470 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6471 "Matches a simple (no attributes) html start- or end-tag.")
6472
6473 (defsubst js2-jsdoc-highlight-helper ()
6474 (js2-set-face (match-beginning 1)
6475 (match-end 1)
6476 'js2-jsdoc-tag)
6477 (if (match-beginning 2)
6478 (if (save-excursion
6479 (goto-char (match-beginning 2))
6480 (= (char-after) ?{))
6481 (js2-set-face (1+ (match-beginning 2))
6482 (1- (match-end 2))
6483 'js2-jsdoc-type)
6484 (js2-set-face (match-beginning 2)
6485 (match-end 2)
6486 'js2-jsdoc-value)))
6487 (if (match-beginning 3)
6488 (js2-set-face (match-beginning 3)
6489 (match-end 3)
6490 'js2-jsdoc-value)))
6491
6492 (defun js2-highlight-jsdoc (ast)
6493 "Highlight doc comment tags."
6494 (let ((comments (js2-ast-root-comments ast))
6495 beg end)
6496 (save-excursion
6497 (dolist (node comments)
6498 (when (eq (js2-comment-node-format node) 'jsdoc)
6499 (setq beg (js2-node-abs-pos node)
6500 end (+ beg (js2-node-len node)))
6501 (save-restriction
6502 (narrow-to-region beg end)
6503 (dolist (re (list js2-jsdoc-param-tag-regexp
6504 js2-jsdoc-typed-tag-regexp
6505 js2-jsdoc-arg-tag-regexp
6506 js2-jsdoc-link-tag-regexp
6507 js2-jsdoc-see-tag-regexp
6508 js2-jsdoc-empty-tag-regexp))
6509 (goto-char beg)
6510 (while (re-search-forward re nil t)
6511 (js2-jsdoc-highlight-helper)))
6512 ;; simple highlighting for html tags
6513 (goto-char beg)
6514 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6515 (js2-set-face (match-beginning 1)
6516 (match-end 1)
6517 'js2-jsdoc-html-tag-delimiter)
6518 (js2-set-face (match-beginning 2)
6519 (match-end 2)
6520 'js2-jsdoc-html-tag-name)
6521 (js2-set-face (match-beginning 3)
6522 (match-end 3)
6523 'js2-jsdoc-html-tag-delimiter))))))))
6524
6525 (defun js2-highlight-assign-targets (node left right)
6526 "Highlight function properties and external variables."
6527 (let (leftpos end name)
6528 ;; highlight vars and props assigned function values
6529 (when (js2-function-node-p right)
6530 (cond
6531 ;; var foo = function() {...}
6532 ((js2-name-node-p left)
6533 (setq name left))
6534 ;; foo.bar.baz = function() {...}
6535 ((and (js2-prop-get-node-p left)
6536 (js2-name-node-p (js2-prop-get-node-right left)))
6537 (setq name (js2-prop-get-node-right left))))
6538 (when name
6539 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6540 (+ leftpos (js2-node-len name))
6541 'font-lock-function-name-face
6542 'record)))
6543 ;; save variable assignments so we can check for undeclared later
6544 ;; (can't do it here since var decls can come at end of script)
6545 (when (and js2-highlight-external-variables
6546 (setq name (js2-member-expr-leftmost-name left)))
6547 (push (list name js2-current-scope
6548 (setq leftpos (js2-node-abs-pos name))
6549 (setq end (+ leftpos (js2-node-len name))))
6550 js2-recorded-assignments))))
6551
6552 (defun js2-highlight-undeclared-vars ()
6553 "After entire parse is finished, look for undeclared variable assignments.
6554 We have to wait until entire buffer is parsed, since JavaScript permits var
6555 decls to occur after they're used.
6556
6557 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6558 it is considered declared."
6559 (let (name)
6560 (dolist (entry js2-recorded-assignments)
6561 (destructuring-bind (name-node scope pos end) entry
6562 (setq name (js2-name-node-name name-node))
6563 (unless (or (member name js2-global-externs)
6564 (member name js2-default-externs)
6565 (member name js2-additional-externs)
6566 (js2-get-defining-scope scope name))
6567 (js2-set-face pos end 'js2-external-variable 'record)
6568 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6569 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6570 (setq js2-recorded-assignments nil)))
6571
6572 ;;; IMenu support
6573
6574 ;; We currently only support imenu, but eventually should support speedbar and
6575 ;; possibly other browsing mechanisms.
6576
6577 ;; The basic strategy is to identify function assignment targets of the form
6578 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6579 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6580 ;; for imenu after parsing is finished.
6581
6582 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6583 ;; JavaScript, and the general problem is undecidable. However, several forms
6584 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6585 ;; include:
6586
6587 ;; function foo() -- function declaration
6588 ;; foo = function() -- function expression assigned to variable
6589 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6590 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6591 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6592 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6593 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6594 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6595 ;; function foo() {function bar() {...}} -- nested function
6596 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6597
6598 ;; This list boils down to a few forms that can be combined recursively.
6599 ;; Top-level named function declarations include both the left-hand (name)
6600 ;; and the right-hand (function value) expressions needed to produce an imenu
6601 ;; entry. The other "right-hand" forms we need to look for are:
6602 ;; - functions declared as props/getters/setters in object literals
6603 ;; - nested named function declarations
6604 ;; The "left-hand" expressions that functions can be assigned to include:
6605 ;; - local/global variables
6606 ;; - nested property-get expressions like a.b.c.d
6607 ;; - element gets like foo[10] or foo['bar'] where the index
6608 ;; expression can be trivially converted to a property name. They
6609 ;; effectively then become property gets.
6610
6611 ;; All the different definition types are canonicalized into the form
6612 ;; foo.bar.baz = position-of-function-keyword
6613
6614 ;; We need to build a trie-like structure for imenu. As an example,
6615 ;; consider the following JavaScript code:
6616
6617 ;; a = function() {...} // function at position 5
6618 ;; b = function() {...} // function at position 25
6619 ;; foo = function() {...} // function at position 100
6620 ;; foo.bar = function() {...} // function at position 200
6621 ;; foo.bar.baz = function() {...} // function at position 300
6622 ;; foo.bar.zab = function() {...} // function at position 400
6623
6624 ;; During parsing we accumulate an entry for each definition in
6625 ;; the variable `js2-imenu-recorder', like so:
6626
6627 ;; '((a 5)
6628 ;; (b 25)
6629 ;; (foo 100)
6630 ;; (foo bar 200)
6631 ;; (foo bar baz 300)
6632 ;; (foo bar zab 400))
6633
6634 ;; After parsing these entries are merged into this alist-trie:
6635
6636 ;; '((a . 1)
6637 ;; (b . 2)
6638 ;; (foo (<definition> . 3)
6639 ;; (bar (<definition> . 6)
6640 ;; (baz . 100)
6641 ;; (zab . 200))))
6642
6643 ;; Note the wacky need for a <definition> name. The token can be anything
6644 ;; that isn't a valid JavaScript identifier, because you might make foo
6645 ;; a function and then start setting properties on it that are also functions.
6646
6647 (defsubst js2-prop-node-name (node)
6648 "Return the name of a node that may be a property-get/property-name.
6649 If NODE is not a valid name-node, string-node or integral number-node,
6650 returns nil. Otherwise returns the string name/value of the node."
6651 (cond
6652 ((js2-name-node-p node)
6653 (js2-name-node-name node))
6654 ((js2-string-node-p node)
6655 (js2-string-node-value node))
6656 ((and (js2-number-node-p node)
6657 (string-match "^[0-9]+$" (js2-number-node-value node)))
6658 (js2-number-node-value node))
6659 ((js2-this-node-p node)
6660 "this")))
6661
6662 (defsubst js2-node-qname-component (node)
6663 "Test function: return the name of this node, if it contributes to a qname.
6664 Returns nil if the node doesn't contribute."
6665 (copy-sequence
6666 (or (js2-prop-node-name node)
6667 (if (and (js2-function-node-p node)
6668 (js2-function-node-name node))
6669 (js2-name-node-name (js2-function-node-name node))))))
6670
6671 (defsubst js2-record-function-qname (fn-node qname)
6672 "Associate FN-NODE with its QNAME for later lookup.
6673 This is used in postprocessing the chain list. When we find a chain
6674 whose first element is a js2-THIS keyword node, we look up the parent
6675 function and see (using this map) whether it is the tail of a chain.
6676 If so, we replace the this-node with a copy of the parent's qname."
6677 (unless js2-imenu-function-map
6678 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6679 (puthash fn-node qname js2-imenu-function-map))
6680
6681 (defun js2-record-imenu-functions (node &optional var)
6682 "Record function definitions for imenu.
6683 NODE is a function node or an object literal.
6684 VAR, if non-nil, is the expression that NODE is being assigned to."
6685 (when js2-parse-ide-mode
6686 (let ((fun-p (js2-function-node-p node))
6687 qname left fname-node pos)
6688 (cond
6689 ;; non-anonymous function declaration?
6690 ((and fun-p
6691 (not var)
6692 (setq fname-node (js2-function-node-name node)))
6693 (push (setq qname (list fname-node (js2-node-pos node)))
6694 js2-imenu-recorder)
6695 (js2-record-function-qname node qname))
6696 ;; for remaining forms, compute left-side tree branch first
6697 ((and var (setq qname (js2-compute-nested-prop-get var)))
6698 (cond
6699 ;; foo.bar.baz = function
6700 (fun-p
6701 (push (nconc qname (list (js2-node-pos node)))
6702 js2-imenu-recorder)
6703 (js2-record-function-qname node qname))
6704 ;; foo.bar.baz = object-literal
6705 ;; look for nested functions: {a: {b: function() {...} }}
6706 ((js2-object-node-p node)
6707 (js2-record-object-literal node qname))))))))
6708
6709 (defun js2-compute-nested-prop-get (node)
6710 "If NODE is of form foo.bar.baz, return component nodes as a list.
6711 Otherwise returns nil. Element-gets can be treated as property-gets
6712 if the index expression is a name, a string, or a positive integer."
6713 (let (left right head)
6714 (cond
6715 ((or (js2-name-node-p node)
6716 (js2-this-node-p node))
6717 (list node))
6718 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6719 ((js2-prop-get-node-p node) ; includes elem-get nodes
6720 (setq left (js2-prop-get-node-left node)
6721 right (js2-prop-get-node-right node))
6722 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6723 (js2-name-node-p left)
6724 (js2-this-node-p left)) ; or left == foo
6725 (or (js2-name-node-p right) ; .bar
6726 (js2-string-node-p right) ; ['bar']
6727 (and (js2-number-node-p right) ; [10]
6728 (string-match "^[0-9]+$"
6729 (js2-number-node-value right)))))
6730 (if (setq head (js2-compute-nested-prop-get left))
6731 (nconc head (list right))))))))
6732
6733 (defun js2-record-object-literal (node qname)
6734 "Recursively process an object literal looking for functions.
6735 NODE is an object literal that is the right-hand child of an assignment
6736 expression. QNAME is a list of nodes representing the assignment target,
6737 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6738 We do a depth-first traversal of NODE. Any functions we find are prefixed
6739 with QNAME plus the property name of the function and appended to the
6740 variable `js2-imenu-recorder'."
6741 ;; Elements are relative to parent position, which is still absolute,
6742 ;; since the parser passes the assignment target and value expressions
6743 ;; to us before they are added as children of the assignment node.
6744 (let ((pos (js2-node-pos node))
6745 left right)
6746 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6747 (setq left (js2-infix-node-left e))
6748 (cond
6749 ;; foo: function() {...}
6750 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6751 (when (js2-prop-node-name left)
6752 ;; As a policy decision, we record the position of the property,
6753 ;; not the position of the `function' keyword, since the property
6754 ;; is effectively the name of the function.
6755 (push (append qname (list left) (list (+ pos (js2-node-pos e))))
6756 js2-imenu-recorder)
6757 (js2-record-function-qname right qname)))
6758 ;; foo: {object-literal} -- add foo to qname and recurse
6759 ((js2-object-node-p right)
6760 (js2-record-object-literal right
6761 (append qname (list (js2-infix-node-left e)))))))))
6762
6763 (defsubst js2-node-top-level-decl-p (node)
6764 "Return t if NODE's name is defined in the top-level scope.
6765 Also returns t if NODE's name is not defined in any scope, since it implies
6766 that it's an external variable, which must also be in the top-level scope."
6767 (let* ((name (js2-prop-node-name node))
6768 (this-scope (js2-node-get-enclosing-scope node))
6769 defining-scope)
6770 (cond
6771 ((js2-this-node-p node)
6772 nil)
6773 ((null this-scope)
6774 t)
6775 ((setq defining-scope (js2-get-defining-scope this-scope name))
6776 (js2-ast-root-p defining-scope))
6777 (t t))))
6778
6779 (defun js2-browse-postprocess-chains (chains)
6780 "Modify function-declaration name chains after parsing finishes.
6781 Some of the information is only available after the parse tree is complete.
6782 For instance, following a 'this' reference requires a parent function node."
6783 (let (result head fn parent-chain p elem)
6784 (dolist (chain chains)
6785 ;; examine the head of each node to get its defining scope
6786 (setq head (car chain))
6787 (cond
6788 ;; if top-level/external, keep as-is
6789 ((js2-node-top-level-decl-p head)
6790 (push chain result))
6791 ;; check for a this-reference
6792 ((eq (js2-node-type head) js2-THIS)
6793 (setq fn (js2-node-parent-script-or-fn head))
6794 ;; if there is no parent function, or if the parent function
6795 ;; is nested, discard the head node and keep the rest of the chain.
6796 (if (or (null fn) (js2-nested-function-p fn))
6797 (push (cdr chain) result)
6798 ;; else look up parent in function-map. If not found, discard chain.
6799 (when (setq parent-chain (and js2-imenu-function-map
6800 (gethash fn js2-imenu-function-map)))
6801 ;; else discard head node and prefix parent fn qname, which is
6802 ;; the parent-chain sans tail, to this chain.
6803 (push (append (butlast parent-chain) (cdr chain)) result))))))
6804 ;; finally replace each node in each chain with its name.
6805 (dolist (chain result)
6806 (setq p chain)
6807 (while p
6808 (if (js2-node-p (setq elem (car p)))
6809 (setcar p (js2-node-qname-component elem)))
6810 (setq p (cdr p))))
6811 result))
6812
6813 ;; Merge name chains into a trie-like tree structure of nested lists.
6814 ;; To simplify construction of the trie, we first build it out using the rule
6815 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6816 ;; [key, num-or-list]. The second element can be a number; if so, this key
6817 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6818 ;; associated with the key at this level.) Otherwise the second element is
6819 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6820 ;; a simple recursive formulation.
6821 ;;
6822 ;; js2-mode is building the data structure for imenu. The imenu documentation
6823 ;; claims that it's the structure above, but in practice it wants the children
6824 ;; at the same list level as the key for that level, which is how I've drawn
6825 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6826 ;; list wrapper around the children at each level.
6827 ;;
6828 ;; A completed nested imenu-alist entry looks like this:
6829 ;; '(("foo"
6830 ;; ("<definition>" . 7)
6831 ;; ("bar"
6832 ;; ("a" . 40)
6833 ;; ("b" . 60))))
6834 ;;
6835 ;; In particular, the documentation for `imenu--index-alist' says that
6836 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6837 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6838
6839 (defsubst js2-treeify (lst)
6840 "Convert (a b c d) to (a ((b ((c d)))))."
6841 (if (null (cddr lst)) ; list length <= 2
6842 lst
6843 (list (car lst) (list (js2-treeify (cdr lst))))))
6844
6845 (defun js2-build-alist-trie (chains trie)
6846 "Merge declaration name chains into a trie-like alist structure for imenu.
6847 CHAINS is the qname chain list produced during parsing. TRIE is a
6848 list of elements built up so far."
6849 (let (head tail pos branch kids)
6850 (dolist (chain chains)
6851 (setq head (car chain)
6852 tail (cdr chain)
6853 pos (if (numberp (car tail)) (car tail))
6854 branch (js2-find-if (lambda (n)
6855 (string= (car n) head))
6856 trie)
6857 kids (second branch))
6858 (cond
6859 ;; case 1: this key isn't in the trie yet
6860 ((null branch)
6861 (if trie
6862 (setcdr (last trie) (list (js2-treeify chain)))
6863 (setq trie (list (js2-treeify chain)))))
6864 ;; case 2: key is present with a single number entry: replace w/ list
6865 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6866 ;; ("<definition>" 20)))
6867 ((numberp kids)
6868 (setcar (cdr branch)
6869 (list (list "<definition-1>" kids)
6870 (if pos
6871 (list "<definition-2>" pos)
6872 (js2-treeify tail)))))
6873 ;; case 3: key is there (with kids), and we're a number entry
6874 (pos
6875 (setcdr (last kids)
6876 (list
6877 (list (format "<definition-%d>"
6878 (1+ (loop for kid in kids
6879 count (eq ?< (aref (car kid) 0)))))
6880 pos))))
6881
6882 ;; case 4: key is there with kids, need to merge in our chain
6883 (t
6884 (js2-build-alist-trie (list tail) kids))))
6885 trie))
6886
6887 (defun js2-flatten-trie (trie)
6888 "Convert TRIE to imenu-format.
6889 Recurses through nodes, and for each one whose second element is a list,
6890 appends the list's flattened elements to the current element. Also
6891 changes the tails into conses. For instance, this pre-flattened trie
6892
6893 '(a ((b 20)
6894 (c ((d 30)
6895 (e 40)))))
6896
6897 becomes
6898
6899 '(a (b . 20)
6900 (c (d . 30)
6901 (e . 40)))
6902
6903 Note that the root of the trie has no key, just a list of chains.
6904 This is also true for the value of any key with multiple children,
6905 e.g. key 'c' in the example above."
6906 (cond
6907 ((listp (car trie))
6908 (mapcar #'js2-flatten-trie trie))
6909 (t
6910 (if (numberp (second trie))
6911 (cons (car trie) (second trie))
6912 ;; else pop list and append its kids
6913 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6914
6915 (defun js2-build-imenu-index ()
6916 "Turn `js2-imenu-recorder' into an imenu data structure."
6917 (unless (eq js2-imenu-recorder 'empty)
6918 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6919 (result (js2-build-alist-trie chains nil)))
6920 (js2-flatten-trie result))))
6921
6922 (defun js2-test-print-chains (chains)
6923 "Print a list of qname chains.
6924 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6925 i.e. one or more nodes, and an integer position as the list tail."
6926 (mapconcat (lambda (chain)
6927 (concat "("
6928 (mapconcat (lambda (elem)
6929 (if (js2-node-p elem)
6930 (or (js2-node-qname-component elem)
6931 "nil")
6932 (number-to-string elem)))
6933 chain
6934 " ")
6935 ")"))
6936 chains
6937 "\n"))
6938
6939 ;;; Parser
6940
6941 (defconst js2-version "1.8.0"
6942 "Version of JavaScript supported, plus minor js2 version.")
6943
6944 (defmacro js2-record-face (face)
6945 "Record a style run of FACE for the current token."
6946 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6947
6948 (defsubst js2-node-end (n)
6949 "Computes the absolute end of node N.
6950 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6951 is only true until the node is added to its parent; i.e., while parsing."
6952 (+ (js2-node-pos n)
6953 (js2-node-len n)))
6954
6955 (defsubst js2-record-comment ()
6956 "Record a comment in `js2-scanned-comments'."
6957 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6958 :format js2-ts-comment-type)
6959 js2-scanned-comments)
6960 (when js2-parse-ide-mode
6961 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6962 'font-lock-doc-face
6963 'font-lock-comment-face))
6964 (when (memq js2-ts-comment-type '(html preprocessor))
6965 ;; Tell cc-engine the bounds of the comment.
6966 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6967
6968 ;; This function is called depressingly often, so it should be fast.
6969 ;; Most of the time it's looking at the same token it peeked before.
6970 (defsubst js2-peek-token ()
6971 "Return the next token without consuming it.
6972 If previous token was consumed, calls scanner to get new token.
6973 If previous token was -not- consumed, returns it (idempotent).
6974
6975 This function will not return a newline (js2-EOL) - instead, it
6976 gobbles newlines until it finds a non-newline token, and flags
6977 that token as appearing just after a newline.
6978
6979 This function will also not return a js2-COMMENT. Instead, it
6980 records comments found in `js2-scanned-comments'. If the token
6981 returned by this function immediately follows a jsdoc comment,
6982 the token is flagged as such.
6983
6984 Note that this function always returned the un-flagged token!
6985 The flags, if any, are saved in `js2-current-flagged-token'."
6986 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6987 js2-current-token ; most common case - return already-peeked token
6988 (let ((tt (js2-get-token)) ; call scanner
6989 saw-eol
6990 face)
6991 ;; process comments and whitespace
6992 (while (or (= tt js2-EOL)
6993 (= tt js2-COMMENT))
6994 (if (= tt js2-EOL)
6995 (setq saw-eol t)
6996 (setq saw-eol nil)
6997 (if js2-record-comments
6998 (js2-record-comment)))
6999 (setq tt (js2-get-token))) ; call scanner
7000 (setq js2-current-token tt
7001 js2-current-flagged-token (if saw-eol
7002 (logior tt js2-ti-after-eol)
7003 tt))
7004 ;; perform lexical fontification as soon as token is scanned
7005 (when js2-parse-ide-mode
7006 (cond
7007 ((minusp tt)
7008 (js2-record-face 'js2-error))
7009 ((setq face (aref js2-kwd-tokens tt))
7010 (js2-record-face face))
7011 ((and (= tt js2-NAME)
7012 (equal js2-ts-string "undefined"))
7013 (js2-record-face 'font-lock-constant-face))))
7014 tt))) ; return unflagged token
7015
7016 (defsubst js2-peek-flagged-token ()
7017 "Return the current token along with any flags set for it."
7018 (js2-peek-token)
7019 js2-current-flagged-token)
7020
7021 (defsubst js2-consume-token ()
7022 (setq js2-current-flagged-token js2-EOF))
7023
7024 (defsubst js2-next-token ()
7025 (prog1
7026 (js2-peek-token)
7027 (js2-consume-token)))
7028
7029 (defsubst js2-next-flagged-token ()
7030 (js2-peek-token)
7031 (prog1 js2-current-flagged-token
7032 (js2-consume-token)))
7033
7034 (defsubst js2-match-token (match)
7035 "Consume and return t if next token matches MATCH, a bytecode.
7036 Returns nil and consumes nothing if MATCH is not the next token."
7037 (if (/= (js2-peek-token) match)
7038 nil
7039 (js2-consume-token)
7040 t))
7041
7042 (defsubst js2-valid-prop-name-token (tt)
7043 (or (= tt js2-NAME)
7044 (and js2-allow-keywords-as-property-names
7045 (plusp tt)
7046 (aref js2-kwd-tokens tt))))
7047
7048 (defsubst js2-match-prop-name ()
7049 "Consume token and return t if next token is a valid property name.
7050 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7051 is non-nil and it's a keyword token."
7052 (if (js2-valid-prop-name-token (js2-peek-token))
7053 (progn
7054 (js2-consume-token)
7055 t)
7056 nil))
7057
7058 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7059 (if (js2-match-prop-name)
7060 t
7061 (js2-report-error msg-id nil pos len)
7062 nil))
7063
7064 (defsubst js2-peek-token-or-eol ()
7065 "Return js2-EOL if the current token immediately follows a newline.
7066 Else returns the current token. Used in situations where we don't
7067 consider certain token types valid if they are preceded by a newline.
7068 One example is the postfix ++ or -- operator, which has to be on the
7069 same line as its operand."
7070 (let ((tt (js2-peek-token)))
7071 ;; Check for last peeked token flags
7072 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7073 js2-EOL
7074 tt)))
7075
7076 (defsubst js2-set-check-for-label ()
7077 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7078 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7079
7080 (defsubst js2-must-match (token msg-id &optional pos len)
7081 "Match next token to token code TOKEN, or record a syntax error.
7082 MSG-ID is the error message to report if the match fails.
7083 Returns t on match, nil if no match."
7084 (if (js2-match-token token)
7085 t
7086 (js2-report-error msg-id nil pos len)
7087 nil))
7088
7089 (defsubst js2-inside-function ()
7090 (plusp js2-nesting-of-function))
7091
7092 (defsubst js2-set-requires-activation ()
7093 (if (js2-function-node-p js2-current-script-or-fn)
7094 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7095
7096 (defsubst js2-check-activation-name (name token)
7097 (when (js2-inside-function)
7098 ;; skip language-version 1.2 check from Rhino
7099 (if (or (string= "arguments" name)
7100 (and js2-compiler-activation-names ; only used in codegen
7101 (gethash name js2-compiler-activation-names)))
7102 (js2-set-requires-activation))))
7103
7104 (defsubst js2-set-is-generator ()
7105 (if (js2-function-node-p js2-current-script-or-fn)
7106 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7107
7108 (defsubst js2-must-have-xml ()
7109 (unless js2-compiler-xml-available
7110 (js2-report-error "msg.XML.not.available")))
7111
7112 (defsubst js2-push-scope (scope)
7113 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7114 (assert (js2-scope-p scope))
7115 (assert (null (js2-scope-parent-scope scope)))
7116 (assert (not (eq js2-current-scope scope)))
7117 (setf (js2-scope-parent-scope scope) js2-current-scope
7118 js2-current-scope scope))
7119
7120 (defsubst js2-pop-scope ()
7121 (setq js2-current-scope
7122 (js2-scope-parent-scope js2-current-scope)))
7123
7124 (defsubst js2-enter-loop (loop-node)
7125 (push loop-node js2-loop-set)
7126 (push loop-node js2-loop-and-switch-set)
7127 (js2-push-scope loop-node)
7128 ;; Tell the current labeled statement (if any) its statement,
7129 ;; and set the jump target of the first label to the loop.
7130 ;; These are used in `js2-parse-continue' to verify that the
7131 ;; continue target is an actual labeled loop. (And for codegen.)
7132 (when js2-labeled-stmt
7133 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7134 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7135 js2-labeled-stmt))) loop-node)))
7136
7137 (defsubst js2-exit-loop ()
7138 (pop js2-loop-set)
7139 (pop js2-loop-and-switch-set)
7140 (js2-pop-scope))
7141
7142 (defsubst js2-enter-switch (switch-node)
7143 (push switch-node js2-loop-and-switch-set))
7144
7145 (defsubst js2-exit-switch ()
7146 (pop js2-loop-and-switch-set))
7147
7148 (defun js2-parse (&optional buf cb)
7149 "Tell the js2 parser to parse a region of JavaScript.
7150
7151 BUF is a buffer or buffer name containing the code to parse.
7152 Call `narrow-to-region' first to parse only part of the buffer.
7153
7154 The returned AST root node is given some additional properties:
7155 `node-count' - total number of nodes in the AST
7156 `buffer' - BUF. The buffer it refers to may change or be killed,
7157 so the value is not necessarily reliable.
7158
7159 An optional callback CB can be specified to report parsing
7160 progress. If `(functionp CB)' returns t, it will be called with
7161 the current line number once before parsing begins, then again
7162 each time the lexer reaches a new line number.
7163
7164 CB can also be a list of the form `(symbol cb ...)' to specify
7165 multiple callbacks with different criteria. Each symbol is a
7166 criterion keyword, and the following element is the callback to
7167 call
7168
7169 :line - called whenever the line number changes
7170 :token - called for each new token consumed
7171
7172 The list of criteria could be extended to include entering or
7173 leaving a statement, an expression, or a function definition."
7174 (if (and cb (not (functionp cb)))
7175 (error "criteria callbacks not yet implemented"))
7176 (let ((inhibit-point-motion-hooks t)
7177 (js2-compiler-xml-available (>= js2-language-version 160))
7178 ;; This is a recursive-descent parser, so give it a big stack.
7179 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7180 (max-specpdl-size (max max-specpdl-size 3000))
7181 (case-fold-search nil)
7182 ast)
7183 (or buf (setq buf (current-buffer)))
7184 (message nil) ; clear any error message from previous parse
7185 (with-current-buffer buf
7186 (setq js2-scanned-comments nil
7187 js2-parsed-errors nil
7188 js2-parsed-warnings nil
7189 js2-imenu-recorder nil
7190 js2-imenu-function-map nil
7191 js2-label-set nil)
7192 (js2-init-scanner)
7193 (setq ast (with-silent-modifications
7194 (js2-do-parse)))
7195 (unless js2-ts-hit-eof
7196 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7197 (setf (js2-ast-root-errors ast) js2-parsed-errors
7198 (js2-ast-root-warnings ast) js2-parsed-warnings)
7199 ;; if we didn't find any declarations, put a dummy in this list so we
7200 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7201 (unless js2-imenu-recorder
7202 (setq js2-imenu-recorder 'empty))
7203 (run-hooks 'js2-parse-finished-hook)
7204 ast)))
7205
7206 ;; Corresponds to Rhino's Parser.parse() method.
7207 (defun js2-do-parse ()
7208 "Parse current buffer starting from current point.
7209 Scanner should be initialized."
7210 (let ((pos js2-ts-cursor)
7211 (end js2-ts-cursor) ; in case file is empty
7212 root n tt)
7213 ;; initialize buffer-local parsing vars
7214 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7215 js2-current-script-or-fn root
7216 js2-current-scope root
7217 js2-current-flagged-token js2-EOF
7218 js2-nesting-of-function 0
7219 js2-labeled-stmt nil
7220 js2-recorded-assignments nil) ; for js2-highlight
7221 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7222 (if (= tt js2-FUNCTION)
7223 (progn
7224 (js2-consume-token)
7225 (setq n (js2-parse-function (if js2-called-by-compile-function
7226 'FUNCTION_EXPRESSION
7227 'FUNCTION_STATEMENT)))
7228 (js2-record-imenu-functions n))
7229 ;; not a function - parse a statement
7230 (setq n (js2-parse-statement)))
7231 ;; add function or statement to script
7232 (setq end (js2-node-end n))
7233 (js2-block-node-push root n))
7234 ;; add comments to root in lexical order
7235 (when js2-scanned-comments
7236 ;; if we find a comment beyond end of normal kids, use its end
7237 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7238 (dolist (comment js2-scanned-comments)
7239 (push comment (js2-ast-root-comments root))
7240 (js2-node-add-children root comment)))
7241 (setf (js2-node-len root) (- end pos))
7242 ;; Give extensions a chance to muck with things before highlighting starts.
7243 (dolist (callback js2-post-parse-callbacks)
7244 (funcall callback))
7245 (js2-highlight-undeclared-vars)
7246 root))
7247
7248 (defun js2-function-parser ()
7249 (js2-consume-token)
7250 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7251
7252 (defun js2-parse-function-closure-body (fn-node)
7253 "Parse a JavaScript 1.8 function closure body."
7254 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7255 (if js2-ts-hit-eof
7256 (js2-report-error "msg.no.brace.body" nil
7257 (js2-node-pos fn-node)
7258 (- js2-ts-cursor (js2-node-pos fn-node)))
7259 (js2-node-add-children fn-node
7260 (setf (js2-function-node-body fn-node)
7261 (js2-parse-expr))))))
7262
7263 (defun js2-parse-function-body (fn-node)
7264 (js2-must-match js2-LC "msg.no.brace.body"
7265 (js2-node-pos fn-node)
7266 (- js2-ts-cursor (js2-node-pos fn-node)))
7267 (let ((pos js2-token-beg) ; LC position
7268 (pn (make-js2-block-node)) ; starts at LC position
7269 tt
7270 end)
7271 (incf js2-nesting-of-function)
7272 (unwind-protect
7273 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7274 (= tt js2-EOF)
7275 (= tt js2-RC)))
7276 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7277 (js2-parse-statement)
7278 (js2-consume-token)
7279 (js2-parse-function 'FUNCTION_STATEMENT))))
7280 (decf js2-nesting-of-function))
7281 (setq end js2-token-end) ; assume no curly and leave at current token
7282 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7283 (setq end js2-token-end))
7284 (setf (js2-node-pos pn) pos
7285 (js2-node-len pn) (- end pos))
7286 (setf (js2-function-node-body fn-node) pn)
7287 (js2-node-add-children fn-node pn)
7288 pn))
7289
7290 (defun js2-parse-function-params (fn-node pos)
7291 (if (js2-match-token js2-RP)
7292 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7293 (let (params len param)
7294 (loop for tt = (js2-peek-token)
7295 do
7296 (cond
7297 ;; destructuring param
7298 ((or (= tt js2-LB) (= tt js2-LC))
7299 (push (js2-parse-primary-expr) params))
7300 ;; simple name
7301 (t
7302 (js2-must-match js2-NAME "msg.no.parm")
7303 (js2-record-face 'js2-function-param)
7304 (setq param (js2-create-name-node))
7305 (js2-define-symbol js2-LP js2-ts-string param)
7306 (push param params)))
7307 while
7308 (js2-match-token js2-COMMA))
7309 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7310 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7311 (dolist (p params)
7312 (js2-node-add-children fn-node p)
7313 (push p (js2-function-node-params fn-node))))))
7314
7315 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7316 "Possibly show inconsistent-return warning.
7317 Last token scanned is the close-curly for the function body."
7318 (when (and js2-mode-show-strict-warnings
7319 js2-strict-inconsistent-return-warning
7320 (not (js2-has-consistent-return-usage
7321 (js2-function-node-body fn-node))))
7322 ;; Have it extend from close-curly to bol or beginning of block.
7323 (let ((pos (save-excursion
7324 (goto-char js2-token-end)
7325 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7326 (point-at-bol))))
7327 (end js2-token-end))
7328 (if (plusp (js2-name-node-length name))
7329 (js2-add-strict-warning "msg.no.return.value"
7330 (js2-name-node-name name) pos end)
7331 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7332
7333 (defun js2-parse-function (function-type)
7334 "Function parser. FUNCTION-TYPE is a symbol."
7335 (let ((pos js2-token-beg) ; start of 'function' keyword
7336 name
7337 name-beg
7338 name-end
7339 fn-node
7340 lp
7341 (synthetic-type function-type)
7342 member-expr-node)
7343 ;; parse function name, expression, or non-name (anonymous)
7344 (cond
7345 ;; function foo(...)
7346 ((js2-match-token js2-NAME)
7347 (setq name (js2-create-name-node t)
7348 name-beg js2-token-beg
7349 name-end js2-token-end)
7350 (unless (js2-match-token js2-LP)
7351 (when js2-allow-member-expr-as-function-name
7352 ;; function foo.bar(...)
7353 (setq member-expr-node name
7354 name nil
7355 member-expr-node (js2-parse-member-expr-tail
7356 nil member-expr-node)))
7357 (js2-must-match js2-LP "msg.no.paren.parms")))
7358 ((js2-match-token js2-LP)
7359 nil) ; anonymous function: leave name as null
7360 (t
7361 ;; function random-member-expr(...)
7362 (when js2-allow-member-expr-as-function-name
7363 ;; Note that memberExpr can not start with '(' like
7364 ;; in function (1+2).toString(), because 'function (' already
7365 ;; processed as anonymous function
7366 (setq member-expr-node (js2-parse-member-expr)))
7367 (js2-must-match js2-LP "msg.no.paren.parms")))
7368 (if (= js2-current-token js2-LP) ; eventually matched LP?
7369 (setq lp js2-token-beg))
7370 (if member-expr-node
7371 (progn
7372 (setq synthetic-type 'FUNCTION_EXPRESSION)
7373 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7374 (if name
7375 (js2-set-face name-beg name-end
7376 'font-lock-function-name-face 'record)))
7377 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7378 (plusp (js2-name-node-length name)))
7379 ;; Function statements define a symbol in the enclosing scope
7380 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7381 (setf fn-node (make-js2-function-node :pos pos
7382 :name name
7383 :form function-type
7384 :lp (if lp (- lp pos))))
7385 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7386 ;; 1. Nested functions are not affected by the dynamic scope flag
7387 ;; as dynamic scope is already a parent of their scope.
7388 ;; 2. Functions defined under the with statement also immune to
7389 ;; this setup, in which case dynamic scope is ignored in favor
7390 ;; of the with object.
7391 (setf (js2-function-node-ignore-dynamic fn-node) t))
7392 ;; dynamically bind all the per-function variables
7393 (let ((js2-current-script-or-fn fn-node)
7394 (js2-current-scope fn-node)
7395 (js2-nesting-of-with 0)
7396 (js2-end-flags 0)
7397 js2-label-set
7398 js2-loop-set
7399 js2-loop-and-switch-set)
7400 (js2-parse-function-params fn-node pos)
7401 (if (and (>= js2-language-version 180)
7402 (/= (js2-peek-token) js2-LC))
7403 (js2-parse-function-closure-body fn-node)
7404 (js2-parse-function-body fn-node))
7405 (if name
7406 (js2-node-add-children fn-node name))
7407 (js2-check-inconsistent-return-warning fn-node name)
7408 ;; Function expressions define a name only in the body of the
7409 ;; function, and only if not hidden by a parameter name
7410 (if (and name
7411 (eq synthetic-type 'FUNCTION_EXPRESSION)
7412 (null (js2-scope-get-symbol js2-current-scope
7413 (js2-name-node-name name))))
7414 (js2-define-symbol js2-FUNCTION
7415 (js2-name-node-name name)
7416 fn-node))
7417 (if (and name
7418 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7419 (js2-record-imenu-functions fn-node)))
7420 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7421 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7422 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7423 ;; We wait until after parsing the function to set its parent scope,
7424 ;; since `js2-define-symbol' needs the defining-scope check to stop
7425 ;; at the function boundary when checking for redeclarations.
7426 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7427 fn-node))
7428
7429 (defun js2-parse-statements (&optional parent)
7430 "Parse a statement list. Last token consumed must be js2-LC.
7431
7432 PARENT can be a `js2-block-node', in which case the statements are
7433 appended to PARENT. Otherwise a new `js2-block-node' is created
7434 and returned.
7435
7436 This function does not match the closing js2-RC: the caller
7437 matches the RC so it can provide a suitable error message if not
7438 matched. This means it's up to the caller to set the length of
7439 the node to include the closing RC. The node start pos is set to
7440 the absolute buffer start position, and the caller should fix it
7441 up to be relative to the parent node. All children of this block
7442 node are given relative start positions and correct lengths."
7443 (let ((pn (or parent (make-js2-block-node)))
7444 tt)
7445 (setf (js2-node-pos pn) js2-token-beg)
7446 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7447 (/= tt js2-RC))
7448 (js2-block-node-push pn (js2-parse-statement)))
7449 pn))
7450
7451 (defun js2-parse-statement ()
7452 (let (tt pn beg end)
7453 ;; coarse-grained user-interrupt check - needs work
7454 (and js2-parse-interruptable-p
7455 (zerop (% (incf js2-parse-stmt-count)
7456 js2-statements-per-pause))
7457 (input-pending-p)
7458 (throw 'interrupted t))
7459 (setq pn (js2-statement-helper))
7460 ;; no-side-effects warning check
7461 (unless (js2-node-has-side-effects pn)
7462 (setq end (js2-node-end pn))
7463 (save-excursion
7464 (goto-char end)
7465 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7466 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7467 pn))
7468
7469 ;; These correspond to the switch cases in Parser.statementHelper
7470 (defconst js2-parsers
7471 (let ((parsers (make-vector js2-num-tokens
7472 #'js2-parse-expr-stmt)))
7473 (aset parsers js2-BREAK #'js2-parse-break)
7474 (aset parsers js2-CONST #'js2-parse-const-var)
7475 (aset parsers js2-CONTINUE #'js2-parse-continue)
7476 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7477 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7478 (aset parsers js2-DO #'js2-parse-do)
7479 (aset parsers js2-FOR #'js2-parse-for)
7480 (aset parsers js2-FUNCTION #'js2-function-parser)
7481 (aset parsers js2-IF #'js2-parse-if)
7482 (aset parsers js2-LC #'js2-parse-block)
7483 (aset parsers js2-LET #'js2-parse-let-stmt)
7484 (aset parsers js2-NAME #'js2-parse-name-or-label)
7485 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7486 (aset parsers js2-SEMI #'js2-parse-semi)
7487 (aset parsers js2-SWITCH #'js2-parse-switch)
7488 (aset parsers js2-THROW #'js2-parse-throw)
7489 (aset parsers js2-TRY #'js2-parse-try)
7490 (aset parsers js2-VAR #'js2-parse-const-var)
7491 (aset parsers js2-WHILE #'js2-parse-while)
7492 (aset parsers js2-WITH #'js2-parse-with)
7493 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7494 parsers)
7495 "A vector mapping token types to parser functions.")
7496
7497 (defsubst js2-parse-warn-missing-semi (beg end)
7498 (and js2-mode-show-strict-warnings
7499 js2-strict-missing-semi-warning
7500 (js2-add-strict-warning
7501 "msg.missing.semi" nil
7502 ;; back up to beginning of statement or line
7503 (max beg (save-excursion
7504 (goto-char end)
7505 (point-at-bol)))
7506 end)))
7507
7508 (defconst js2-no-semi-insertion
7509 (list js2-IF
7510 js2-SWITCH
7511 js2-WHILE
7512 js2-DO
7513 js2-FOR
7514 js2-TRY
7515 js2-WITH
7516 js2-LC
7517 js2-ERROR
7518 js2-SEMI
7519 js2-FUNCTION)
7520 "List of tokens that don't do automatic semicolon insertion.")
7521
7522 (defconst js2-autoinsert-semi-and-warn
7523 (list js2-ERROR js2-EOF js2-RC))
7524
7525 (defun js2-statement-helper ()
7526 (let* ((tt (js2-peek-token))
7527 (first-tt tt)
7528 (beg js2-token-beg)
7529 (parser (if (= tt js2-ERROR)
7530 #'js2-parse-semi
7531 (aref js2-parsers tt)))
7532 pn
7533 tt-flagged)
7534 ;; If the statement is set, then it's been told its label by now.
7535 (and js2-labeled-stmt
7536 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7537 (setq js2-labeled-stmt nil))
7538 (setq pn (funcall parser))
7539 ;; Don't do auto semi insertion for certain statement types.
7540 (unless (or (memq first-tt js2-no-semi-insertion)
7541 (js2-labeled-stmt-node-p pn))
7542 (js2-auto-insert-semicolon pn))
7543 pn))
7544
7545 (defun js2-auto-insert-semicolon (pn)
7546 (let* ((tt-flagged (js2-peek-flagged-token))
7547 (tt (logand tt-flagged js2-clear-ti-mask))
7548 (pos (js2-node-pos pn)))
7549 (cond
7550 ((= tt js2-SEMI)
7551 ;; Consume ';' as a part of expression
7552 (js2-consume-token)
7553 ;; extend the node bounds to include the semicolon.
7554 (setf (js2-node-len pn) (- js2-token-end pos)))
7555 ((memq tt js2-autoinsert-semi-and-warn)
7556 ;; Autoinsert ;
7557 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7558 (t
7559 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7560 ;; Report error if no EOL or autoinsert ';' otherwise
7561 (js2-report-error "msg.no.semi.stmt")
7562 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7563
7564 (defun js2-parse-condition ()
7565 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7566 The parens are discarded and the expression node is returned.
7567 The `pos' field of the return value is set to an absolute position
7568 that must be fixed up by the caller.
7569 Return value is a list (EXPR LP RP), with absolute paren positions."
7570 (let (pn lp rp)
7571 (if (js2-must-match js2-LP "msg.no.paren.cond")
7572 (setq lp js2-token-beg))
7573 (setq pn (js2-parse-expr))
7574 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7575 (setq rp js2-token-beg))
7576 ;; Report strict warning on code like "if (a = 7) ..."
7577 (if (and js2-strict-cond-assign-warning
7578 (js2-assign-node-p pn))
7579 (js2-add-strict-warning "msg.equal.as.assign" nil
7580 (js2-node-pos pn)
7581 (+ (js2-node-pos pn)
7582 (js2-node-len pn))))
7583 (list pn lp rp)))
7584
7585 (defun js2-parse-if ()
7586 "Parser for if-statement. Last matched token must be js2-IF."
7587 (let ((pos js2-token-beg)
7588 cond
7589 if-true
7590 if-false
7591 else-pos
7592 end
7593 pn)
7594 (js2-consume-token)
7595 (setq cond (js2-parse-condition)
7596 if-true (js2-parse-statement)
7597 if-false (if (js2-match-token js2-ELSE)
7598 (progn
7599 (setq else-pos (- js2-token-beg pos))
7600 (js2-parse-statement)))
7601 end (js2-node-end (or if-false if-true))
7602 pn (make-js2-if-node :pos pos
7603 :len (- end pos)
7604 :condition (car cond)
7605 :then-part if-true
7606 :else-part if-false
7607 :else-pos else-pos
7608 :lp (js2-relpos (second cond) pos)
7609 :rp (js2-relpos (third cond) pos)))
7610 (js2-node-add-children pn (car cond) if-true if-false)
7611 pn))
7612
7613 (defun js2-parse-switch ()
7614 "Parser for if-statement. Last matched token must be js2-SWITCH."
7615 (let ((pos js2-token-beg)
7616 tt
7617 pn
7618 discriminant
7619 has-default
7620 case-expr
7621 case-node
7622 case-pos
7623 cases
7624 stmt
7625 lp
7626 rp)
7627 (js2-consume-token)
7628 (if (js2-must-match js2-LP "msg.no.paren.switch")
7629 (setq lp js2-token-beg))
7630 (setq discriminant (js2-parse-expr)
7631 pn (make-js2-switch-node :discriminant discriminant
7632 :pos pos
7633 :lp (js2-relpos lp pos)))
7634 (js2-node-add-children pn discriminant)
7635 (js2-enter-switch pn)
7636 (unwind-protect
7637 (progn
7638 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7639 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7640 (js2-must-match js2-LC "msg.no.brace.switch")
7641 (catch 'break
7642 (while t
7643 (setq tt (js2-next-token)
7644 case-pos js2-token-beg)
7645 (cond
7646 ((= tt js2-RC)
7647 (setf (js2-node-len pn) (- js2-token-end pos))
7648 (throw 'break nil)) ; done
7649 ((= tt js2-CASE)
7650 (setq case-expr (js2-parse-expr))
7651 (js2-must-match js2-COLON "msg.no.colon.case"))
7652 ((= tt js2-DEFAULT)
7653 (if has-default
7654 (js2-report-error "msg.double.switch.default"))
7655 (setq has-default t
7656 case-expr nil)
7657 (js2-must-match js2-COLON "msg.no.colon.case"))
7658 (t
7659 (js2-report-error "msg.bad.switch")
7660 (throw 'break nil)))
7661 (setq case-node (make-js2-case-node :pos case-pos
7662 :len (- js2-token-end case-pos)
7663 :expr case-expr))
7664 (js2-node-add-children case-node case-expr)
7665 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7666 (/= tt js2-CASE)
7667 (/= tt js2-DEFAULT)
7668 (/= tt js2-EOF))
7669 (setf stmt (js2-parse-statement)
7670 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7671 (js2-block-node-push case-node stmt))
7672 (push case-node cases)))
7673 ;; add cases last, as pushing reverses the order to be correct
7674 (dolist (kid cases)
7675 (js2-node-add-children pn kid)
7676 (push kid (js2-switch-node-cases pn)))
7677 pn) ; return value
7678 (js2-exit-switch))))
7679
7680 (defun js2-parse-while ()
7681 "Parser for while-statement. Last matched token must be js2-WHILE."
7682 (let ((pos js2-token-beg)
7683 (pn (make-js2-while-node))
7684 cond
7685 body)
7686 (js2-consume-token)
7687 (js2-enter-loop pn)
7688 (unwind-protect
7689 (progn
7690 (setf cond (js2-parse-condition)
7691 (js2-while-node-condition pn) (car cond)
7692 body (js2-parse-statement)
7693 (js2-while-node-body pn) body
7694 (js2-node-len pn) (- (js2-node-end body) pos)
7695 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7696 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7697 (js2-node-add-children pn body (car cond)))
7698 (js2-exit-loop))
7699 pn))
7700
7701 (defun js2-parse-do ()
7702 "Parser for do-statement. Last matched token must be js2-DO."
7703 (let ((pos js2-token-beg)
7704 (pn (make-js2-do-node))
7705 cond
7706 body
7707 end)
7708 (js2-consume-token)
7709 (js2-enter-loop pn)
7710 (unwind-protect
7711 (progn
7712 (setq body (js2-parse-statement))
7713 (js2-must-match js2-WHILE "msg.no.while.do")
7714 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7715 cond (js2-parse-condition)
7716 (js2-do-node-condition pn) (car cond)
7717 (js2-do-node-body pn) body
7718 end js2-ts-cursor
7719 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7720 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7721 (js2-node-add-children pn (car cond) body))
7722 (js2-exit-loop))
7723 ;; Always auto-insert semicolon to follow SpiderMonkey:
7724 ;; It is required by ECMAScript but is ignored by the rest of
7725 ;; world; see bug 238945
7726 (if (js2-match-token js2-SEMI)
7727 (setq end js2-ts-cursor))
7728 (setf (js2-node-len pn) (- end pos))
7729 pn))
7730
7731 (defun js2-parse-for ()
7732 "Parser for for-statement. Last matched token must be js2-FOR.
7733 Parses for, for-in, and for each-in statements."
7734 (let ((for-pos js2-token-beg)
7735 pn
7736 is-for-each
7737 is-for-in
7738 in-pos
7739 each-pos
7740 tmp-pos
7741 init ; Node init is also foo in 'foo in object'
7742 cond ; Node cond is also object in 'foo in object'
7743 incr ; 3rd section of for-loop initializer
7744 body
7745 tt
7746 lp
7747 rp)
7748 (js2-consume-token)
7749 ;; See if this is a for each () instead of just a for ()
7750 (when (js2-match-token js2-NAME)
7751 (if (string= "each" js2-ts-string)
7752 (progn
7753 (setq is-for-each t
7754 each-pos (- js2-token-beg for-pos)) ; relative
7755 (js2-record-face 'font-lock-keyword-face))
7756 (js2-report-error "msg.no.paren.for")))
7757 (if (js2-must-match js2-LP "msg.no.paren.for")
7758 (setq lp (- js2-token-beg for-pos)))
7759 (setq tt (js2-peek-token))
7760 ;; parse init clause
7761 (let ((js2-in-for-init t)) ; set as dynamic variable
7762 (cond
7763 ((= tt js2-SEMI)
7764 (setq init (make-js2-empty-expr-node)))
7765 ((or (= tt js2-VAR) (= tt js2-LET))
7766 (js2-consume-token)
7767 (setq init (js2-parse-variables tt js2-token-beg)))
7768 (t
7769 (setq init (js2-parse-expr)))))
7770 (if (js2-match-token js2-IN)
7771 (setq is-for-in t
7772 in-pos (- js2-token-beg for-pos)
7773 cond (js2-parse-expr)) ; object over which we're iterating
7774 ;; else ordinary for loop - parse cond and incr
7775 (js2-must-match js2-SEMI "msg.no.semi.for")
7776 (setq cond (if (= (js2-peek-token) js2-SEMI)
7777 (make-js2-empty-expr-node) ; no loop condition
7778 (js2-parse-expr)))
7779 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7780 (setq tmp-pos js2-token-end
7781 incr (if (= (js2-peek-token) js2-RP)
7782 (make-js2-empty-expr-node :pos tmp-pos)
7783 (js2-parse-expr))))
7784 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7785 (setq rp (- js2-token-beg for-pos)))
7786 (if (not is-for-in)
7787 (setq pn (make-js2-for-node :init init
7788 :condition cond
7789 :update incr
7790 :lp lp
7791 :rp rp))
7792 ;; cond could be null if 'in obj' got eaten by the init node.
7793 (if (js2-infix-node-p init)
7794 ;; it was (foo in bar) instead of (var foo in bar)
7795 (setq cond (js2-infix-node-right init)
7796 init (js2-infix-node-left init))
7797 (if (and (js2-var-decl-node-p init)
7798 (> (length (js2-var-decl-node-kids init)) 1))
7799 (js2-report-error "msg.mult.index")))
7800 (setq pn (make-js2-for-in-node :iterator init
7801 :object cond
7802 :in-pos in-pos
7803 :foreach-p is-for-each
7804 :each-pos each-pos
7805 :lp lp
7806 :rp rp)))
7807 (unwind-protect
7808 (progn
7809 (js2-enter-loop pn)
7810 ;; We have to parse the body -after- creating the loop node,
7811 ;; so that the loop node appears in the js2-loop-set, allowing
7812 ;; break/continue statements to find the enclosing loop.
7813 (setf body (js2-parse-statement)
7814 (js2-loop-node-body pn) body
7815 (js2-node-pos pn) for-pos
7816 (js2-node-len pn) (- (js2-node-end body) for-pos))
7817 (js2-node-add-children pn init cond incr body))
7818 ;; finally
7819 (js2-exit-loop))
7820 pn))
7821
7822 (defun js2-parse-try ()
7823 "Parser for try-statement. Last matched token must be js2-TRY."
7824 (let ((try-pos js2-token-beg)
7825 try-end
7826 try-block
7827 catch-blocks
7828 finally-block
7829 saw-default-catch
7830 peek
7831 var-name
7832 catch-cond
7833 catch-node
7834 guard-kwd
7835 catch-pos
7836 finally-pos
7837 pn
7838 block
7839 lp
7840 rp)
7841 (js2-consume-token)
7842 (if (/= (js2-peek-token) js2-LC)
7843 (js2-report-error "msg.no.brace.try"))
7844 (setq try-block (js2-parse-statement)
7845 try-end (js2-node-end try-block)
7846 peek (js2-peek-token))
7847 (cond
7848 ((= peek js2-CATCH)
7849 (while (js2-match-token js2-CATCH)
7850 (setq catch-pos js2-token-beg
7851 guard-kwd nil
7852 catch-cond nil
7853 lp nil
7854 rp nil)
7855 (if saw-default-catch
7856 (js2-report-error "msg.catch.unreachable"))
7857 (if (js2-must-match js2-LP "msg.no.paren.catch")
7858 (setq lp (- js2-token-beg catch-pos)))
7859 (js2-must-match js2-NAME "msg.bad.catchcond")
7860 (setq var-name (js2-create-name-node))
7861 (if (js2-match-token js2-IF)
7862 (setq guard-kwd (- js2-token-beg catch-pos)
7863 catch-cond (js2-parse-expr))
7864 (setq saw-default-catch t))
7865 (if (js2-must-match js2-RP "msg.bad.catchcond")
7866 (setq rp (- js2-token-beg catch-pos)))
7867 (js2-must-match js2-LC "msg.no.brace.catchblock")
7868 (setq block (js2-parse-statements)
7869 try-end (js2-node-end block)
7870 catch-node (make-js2-catch-node :pos catch-pos
7871 :var-name var-name
7872 :guard-expr catch-cond
7873 :guard-kwd guard-kwd
7874 :block block
7875 :lp lp
7876 :rp rp))
7877 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7878 (setq try-end js2-token-beg))
7879 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7880 (js2-node-len catch-node) (- try-end catch-pos))
7881 (js2-node-add-children catch-node var-name catch-cond block)
7882 (push catch-node catch-blocks)))
7883 ((/= peek js2-FINALLY)
7884 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7885 (js2-node-pos try-block)
7886 (- (setq try-end (js2-node-end try-block))
7887 (js2-node-pos try-block)))))
7888 (when (js2-match-token js2-FINALLY)
7889 (setq finally-pos js2-token-beg
7890 block (js2-parse-statement)
7891 try-end (js2-node-end block)
7892 finally-block (make-js2-finally-node :pos finally-pos
7893 :len (- try-end finally-pos)
7894 :body block))
7895 (js2-node-add-children finally-block block))
7896 (setq pn (make-js2-try-node :pos try-pos
7897 :len (- try-end try-pos)
7898 :try-block try-block
7899 :finally-block finally-block))
7900 (js2-node-add-children pn try-block finally-block)
7901 ;; push them onto the try-node, which reverses and corrects their order
7902 (dolist (cb catch-blocks)
7903 (js2-node-add-children pn cb)
7904 (push cb (js2-try-node-catch-clauses pn)))
7905 pn))
7906
7907 (defun js2-parse-throw ()
7908 "Parser for throw-statement. Last matched token must be js2-THROW."
7909 (let ((pos js2-token-beg)
7910 expr
7911 pn)
7912 (js2-consume-token)
7913 (if (= (js2-peek-token-or-eol) js2-EOL)
7914 ;; ECMAScript does not allow new lines before throw expression,
7915 ;; see bug 256617
7916 (js2-report-error "msg.bad.throw.eol"))
7917 (setq expr (js2-parse-expr)
7918 pn (make-js2-throw-node :pos pos
7919 :len (- (js2-node-end expr) pos)
7920 :expr expr))
7921 (js2-node-add-children pn expr)
7922 pn))
7923
7924 (defsubst js2-match-jump-label-name (label-name)
7925 "If break/continue specified a label, return that label's labeled stmt.
7926 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7927 does not match an existing label, reports an error and returns nil."
7928 (let ((bundle (cdr (assoc label-name js2-label-set))))
7929 (if (null bundle)
7930 (js2-report-error "msg.undef.label"))
7931 bundle))
7932
7933 (defun js2-parse-break ()
7934 "Parser for break-statement. Last matched token must be js2-BREAK."
7935 (let ((pos js2-token-beg)
7936 (end js2-token-end)
7937 break-target ; statement to break from
7938 break-label ; in "break foo", name-node representing the foo
7939 labels ; matching labeled statement to break to
7940 pn)
7941 (js2-consume-token) ; `break'
7942 (when (eq (js2-peek-token-or-eol) js2-NAME)
7943 (js2-consume-token)
7944 (setq break-label (js2-create-name-node)
7945 end (js2-node-end break-label)
7946 ;; matchJumpLabelName only matches if there is one
7947 labels (js2-match-jump-label-name js2-ts-string)
7948 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7949 (unless (or break-target break-label)
7950 ;; no break target specified - try for innermost enclosing loop/switch
7951 (if (null js2-loop-and-switch-set)
7952 (unless break-label
7953 (js2-report-error "msg.bad.break" nil pos (length "break")))
7954 (setq break-target (car js2-loop-and-switch-set))))
7955 (setq pn (make-js2-break-node :pos pos
7956 :len (- end pos)
7957 :label break-label
7958 :target break-target))
7959 (js2-node-add-children pn break-label) ; but not break-target
7960 pn))
7961
7962 (defun js2-parse-continue ()
7963 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7964 (let ((pos js2-token-beg)
7965 (end js2-token-end)
7966 label ; optional user-specified label, a `js2-name-node'
7967 labels ; current matching labeled stmt, if any
7968 target ; the `js2-loop-node' target of this continue stmt
7969 pn)
7970 (js2-consume-token) ; `continue'
7971 (when (= (js2-peek-token-or-eol) js2-NAME)
7972 (js2-consume-token)
7973 (setq label (js2-create-name-node)
7974 end (js2-node-end label)
7975 ;; matchJumpLabelName only matches if there is one
7976 labels (js2-match-jump-label-name js2-ts-string)))
7977 (cond
7978 ((null labels) ; no current label to go to
7979 (if (null js2-loop-set) ; no loop to continue to
7980 (js2-report-error "msg.continue.outside" nil pos
7981 (length "continue"))
7982 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7983 (t
7984 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7985 (setq target (js2-labeled-stmt-node-stmt labels))
7986 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7987 (setq pn (make-js2-continue-node :pos pos
7988 :len (- end pos)
7989 :label label
7990 :target target))
7991 (js2-node-add-children pn label) ; but not target - it's not our child
7992 pn))
7993
7994 (defun js2-parse-with ()
7995 "Parser for with-statement. Last matched token must be js2-WITH."
7996 (js2-consume-token)
7997 (let ((pos js2-token-beg)
7998 obj body pn lp rp)
7999 (if (js2-must-match js2-LP "msg.no.paren.with")
8000 (setq lp js2-token-beg))
8001 (setq obj (js2-parse-expr))
8002 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8003 (setq rp js2-token-beg))
8004 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8005 (setq body (js2-parse-statement)))
8006 (setq pn (make-js2-with-node :pos pos
8007 :len (- (js2-node-end body) pos)
8008 :object obj
8009 :body body
8010 :lp (js2-relpos lp pos)
8011 :rp (js2-relpos rp pos)))
8012 (js2-node-add-children pn obj body)
8013 pn))
8014
8015 (defun js2-parse-const-var ()
8016 "Parser for var- or const-statement.
8017 Last matched token must be js2-CONST or js2-VAR."
8018 (let ((tt (js2-peek-token))
8019 (pos js2-token-beg)
8020 expr
8021 pn)
8022 (js2-consume-token)
8023 (setq expr (js2-parse-variables tt js2-token-beg)
8024 pn (make-js2-expr-stmt-node :pos pos
8025 :len (- (js2-node-end expr) pos)
8026 :expr expr))
8027 (js2-node-add-children pn expr)
8028 pn))
8029
8030 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8031 (let ((pn (make-js2-expr-stmt-node :pos pos
8032 :len (js2-node-len expr)
8033 :type (if (js2-inside-function)
8034 js2-EXPR_VOID
8035 js2-EXPR_RESULT)
8036 :expr expr)))
8037 (if add-child
8038 (js2-node-add-children pn expr))
8039 pn))
8040
8041 (defun js2-parse-let-stmt ()
8042 "Parser for let-statement. Last matched token must be js2-LET."
8043 (js2-consume-token)
8044 (let ((pos js2-token-beg)
8045 expr
8046 pn)
8047 (if (= (js2-peek-token) js2-LP)
8048 ;; let expression in statement context
8049 (setq expr (js2-parse-let pos 'statement)
8050 pn (js2-wrap-with-expr-stmt pos expr t))
8051 ;; else we're looking at a statement like let x=6, y=7;
8052 (setf expr (js2-parse-variables js2-LET pos)
8053 pn (js2-wrap-with-expr-stmt pos expr t)
8054 (js2-node-type pn) js2-EXPR_RESULT))
8055 pn))
8056
8057 (defun js2-parse-ret-yield ()
8058 (js2-parse-return-or-yield (js2-peek-token) nil))
8059
8060 (defconst js2-parse-return-stmt-enders
8061 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8062
8063 (defsubst js2-now-all-set (before after mask)
8064 "Return whether or not the bits in the mask have changed to all set.
8065 BEFORE is bits before change, AFTER is bits after change, and MASK is
8066 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8067 but not BEFORE."
8068 (and (/= (logand before mask) mask)
8069 (= (logand after mask) mask)))
8070
8071 (defun js2-parse-return-or-yield (tt expr-context)
8072 (let ((pos js2-token-beg)
8073 (end js2-token-end)
8074 (before js2-end-flags)
8075 (inside-function (js2-inside-function))
8076 e
8077 ret
8078 name)
8079 (unless inside-function
8080 (js2-report-error (if (eq tt js2-RETURN)
8081 "msg.bad.return"
8082 "msg.bad.yield")))
8083 (js2-consume-token)
8084 ;; This is ugly, but we don't want to require a semicolon.
8085 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8086 (setq e (js2-parse-expr)
8087 end (js2-node-end e)))
8088 (cond
8089 ((eq tt js2-RETURN)
8090 (js2-set-flag js2-end-flags (if (null e)
8091 js2-end-returns
8092 js2-end-returns-value))
8093 (setq ret (make-js2-return-node :pos pos
8094 :len (- end pos)
8095 :retval e))
8096 (js2-node-add-children ret e)
8097 ;; See if we need a strict mode warning.
8098 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8099 ;; more thorough and accurate than this before/after flag check.
8100 ;; E.g. if there's a finally-block that always returns, we shouldn't
8101 ;; show a warning generated by inconsistent returns in the catch blocks.
8102 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8103 ;; so we know which returns/yields to highlight, and we should get rid of
8104 ;; all the checking in `js2-parse-return-or-yield'.
8105 (if (and js2-strict-inconsistent-return-warning
8106 (js2-now-all-set before js2-end-flags
8107 (logior js2-end-returns js2-end-returns-value)))
8108 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8109 (t
8110 (unless (js2-inside-function)
8111 (js2-report-error "msg.bad.yield"))
8112 (js2-set-flag js2-end-flags js2-end-yields)
8113 (setq ret (make-js2-yield-node :pos pos
8114 :len (- end pos)
8115 :value e))
8116 (js2-node-add-children ret e)
8117 (unless expr-context
8118 (setq e ret
8119 ret (js2-wrap-with-expr-stmt pos e t))
8120 (js2-set-requires-activation)
8121 (js2-set-is-generator))))
8122 ;; see if we are mixing yields and value returns.
8123 (when (and inside-function
8124 (js2-now-all-set before js2-end-flags
8125 (logior js2-end-yields js2-end-returns-value)))
8126 (setq name (js2-function-name js2-current-script-or-fn))
8127 (if (zerop (length name))
8128 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8129 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8130 ret))
8131
8132 (defun js2-parse-debugger ()
8133 (js2-consume-token)
8134 (make-js2-keyword-node :type js2-DEBUGGER))
8135
8136 (defun js2-parse-block ()
8137 "Parser for a curly-delimited statement block.
8138 Last token matched must be js2-LC."
8139 (let ((pos js2-token-beg)
8140 (pn (make-js2-scope)))
8141 (js2-consume-token)
8142 (js2-push-scope pn)
8143 (unwind-protect
8144 (progn
8145 (js2-parse-statements pn)
8146 (js2-must-match js2-RC "msg.no.brace.block")
8147 (setf (js2-node-len pn) (- js2-token-end pos)))
8148 (js2-pop-scope))
8149 pn))
8150
8151 ;; for js2-ERROR too, to have a node for error recovery to work on
8152 (defun js2-parse-semi ()
8153 "Parse a statement or handle an error.
8154 Last matched token is js-SEMI or js-ERROR."
8155 (let ((tt (js2-peek-token)) pos len)
8156 (js2-consume-token)
8157 (if (eq tt js2-SEMI)
8158 (make-js2-empty-expr-node :len 1)
8159 (setq pos js2-token-beg
8160 len (- js2-token-beg pos))
8161 (js2-report-error "msg.syntax" nil pos len)
8162 (make-js2-error-node :pos pos :len len))))
8163
8164 (defun js2-parse-default-xml-namespace ()
8165 "Parse a `default xml namespace = <expr>' e4x statement."
8166 (let ((pos js2-token-beg)
8167 end len expr unary es)
8168 (js2-consume-token)
8169 (js2-must-have-xml)
8170 (js2-set-requires-activation)
8171 (setq len (- js2-ts-cursor pos))
8172 (unless (and (js2-match-token js2-NAME)
8173 (string= js2-ts-string "xml"))
8174 (js2-report-error "msg.bad.namespace" nil pos len))
8175 (unless (and (js2-match-token js2-NAME)
8176 (string= js2-ts-string "namespace"))
8177 (js2-report-error "msg.bad.namespace" nil pos len))
8178 (unless (js2-match-token js2-ASSIGN)
8179 (js2-report-error "msg.bad.namespace" nil pos len))
8180 (setq expr (js2-parse-expr)
8181 end (js2-node-end expr)
8182 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8183 :pos pos
8184 :len (- end pos)
8185 :operand expr))
8186 (js2-node-add-children unary expr)
8187 (make-js2-expr-stmt-node :pos pos
8188 :len (- end pos)
8189 :expr unary)))
8190
8191 (defun js2-record-label (label bundle)
8192 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8193 (js2-consume-token)
8194 (let ((name (js2-label-node-name label))
8195 labeled-stmt
8196 dup)
8197 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8198 ;; flag both labels if possible when used in editing mode
8199 (if (and js2-parse-ide-mode
8200 (setq dup (js2-get-label-by-name labeled-stmt name)))
8201 (js2-report-error "msg.dup.label" nil
8202 (js2-node-abs-pos dup) (js2-node-len dup)))
8203 (js2-report-error "msg.dup.label" nil
8204 (js2-node-pos label) (js2-node-len label)))
8205 (js2-labeled-stmt-node-add-label bundle label)
8206 (js2-node-add-children bundle label)
8207 ;; Add one reference to the bundle per label in `js2-label-set'
8208 (push (cons name bundle) js2-label-set)))
8209
8210 (defun js2-parse-name-or-label ()
8211 "Parser for identifier or label. Last token matched must be js2-NAME.
8212 Called when we found a name in a statement context. If it's a label, we gather
8213 up any following labels and the next non-label statement into a
8214 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8215 expression and return it wrapped in a `js2-expr-stmt-node'."
8216 (let ((pos js2-token-beg)
8217 (end js2-token-end)
8218 expr
8219 stmt
8220 pn
8221 bundle
8222 (continue t))
8223 ;; set check for label and call down to `js2-parse-primary-expr'
8224 (js2-set-check-for-label)
8225 (setq expr (js2-parse-expr))
8226 (if (/= (js2-node-type expr) js2-LABEL)
8227 ;; Parsed non-label expression - wrap with expression stmt.
8228 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8229 ;; else parsed a label
8230 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8231 (js2-record-label expr bundle)
8232 ;; look for more labels
8233 (while (and continue (= (js2-peek-token) js2-NAME))
8234 (js2-set-check-for-label)
8235 (setq expr (js2-parse-expr))
8236 (if (/= (js2-node-type expr) js2-LABEL)
8237 (progn
8238 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8239 continue nil)
8240 (js2-auto-insert-semicolon stmt))
8241 (js2-record-label expr bundle)))
8242 ;; no more labels; now parse the labeled statement
8243 (unwind-protect
8244 (unless stmt
8245 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8246 (setq stmt (js2-statement-helper))))
8247 ;; remove the labels for this statement from the global set
8248 (dolist (label (js2-labeled-stmt-node-labels bundle))
8249 (setq js2-label-set (remove label js2-label-set))))
8250 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8251 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8252 (js2-node-add-children bundle stmt)
8253 bundle)))
8254
8255 (defun js2-parse-expr-stmt ()
8256 "Default parser in statement context, if no recognized statement found."
8257 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8258
8259 (defun js2-parse-variables (decl-type pos)
8260 "Parse a comma-separated list of variable declarations.
8261 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8262
8263 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8264 For 'var' or 'const', the keyword should be the token last scanned.
8265
8266 POS is the position where the node should start. It's sometimes the
8267 var/const/let keyword, and other times the beginning of the first token
8268 in the first variable declaration.
8269
8270 Returns the parsed `js2-var-decl-node' expression node."
8271 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8272 :pos pos))
8273 destructuring
8274 kid-pos
8275 tt
8276 init
8277 name
8278 end
8279 nbeg nend
8280 vi
8281 (continue t))
8282 ;; Example:
8283 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8284 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8285 (while continue
8286 (setq destructuring nil
8287 name nil
8288 tt (js2-peek-token)
8289 kid-pos js2-token-beg
8290 end js2-token-end
8291 init nil)
8292 (if (or (= tt js2-LB) (= tt js2-LC))
8293 ;; Destructuring assignment, e.g., var [a, b] = ...
8294 (setq destructuring (js2-parse-primary-expr)
8295 end (js2-node-end destructuring))
8296 ;; Simple variable name
8297 (when (js2-must-match js2-NAME "msg.bad.var")
8298 (setq name (js2-create-name-node)
8299 nbeg js2-token-beg
8300 nend js2-token-end
8301 end nend)
8302 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8303 (when (js2-match-token js2-ASSIGN)
8304 (setq init (js2-parse-assign-expr)
8305 end (js2-node-end init))
8306 (if (and js2-parse-ide-mode
8307 (or (js2-object-node-p init)
8308 (js2-function-node-p init)))
8309 (js2-record-imenu-functions init name)))
8310 (when name
8311 (js2-set-face nbeg nend (if (js2-function-node-p init)
8312 'font-lock-function-name-face
8313 'font-lock-variable-name-face)
8314 'record))
8315 (setq vi (make-js2-var-init-node :pos kid-pos
8316 :len (- end kid-pos)
8317 :type decl-type))
8318 (if destructuring
8319 (progn
8320 (if (and (null init) (not js2-in-for-init))
8321 (js2-report-error "msg.destruct.assign.no.init"))
8322 (setf (js2-var-init-node-target vi) destructuring))
8323 (setf (js2-var-init-node-target vi) name))
8324 (setf (js2-var-init-node-initializer vi) init)
8325 (js2-node-add-children vi name destructuring init)
8326 (js2-block-node-push result vi)
8327 (unless (js2-match-token js2-COMMA)
8328 (setq continue nil)))
8329 (setf (js2-node-len result) (- end pos))
8330 result))
8331
8332 (defun js2-parse-let (pos &optional stmt-p)
8333 "Parse a let expression or statement.
8334 A let-expression is of the form `let (vars) expr'.
8335 A let-statment is of the form `let (vars) {statements}'.
8336 The third form of let is a variable declaration list, handled
8337 by `js2-parse-variables'."
8338 (let ((pn (make-js2-let-node :pos pos))
8339 beg vars body)
8340 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8341 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8342 (js2-push-scope pn)
8343 (unwind-protect
8344 (progn
8345 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8346 (if (js2-must-match js2-RP "msg.no.paren.let")
8347 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8348 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8349 ;; let statement
8350 (progn
8351 (js2-consume-token)
8352 (setf beg js2-token-beg ; position stmt at LC
8353 body (js2-parse-statements))
8354 (js2-must-match js2-RC "msg.no.curly.let")
8355 (setf (js2-node-len body) (- js2-token-end beg)
8356 (js2-node-len pn) (- js2-token-end pos)
8357 (js2-let-node-body pn) body
8358 (js2-node-type pn) js2-LET))
8359 ;; let expression
8360 (setf body (js2-parse-expr)
8361 (js2-node-len pn) (- (js2-node-end body) pos)
8362 (js2-let-node-body pn) body))
8363 (js2-node-add-children pn vars body))
8364 (js2-pop-scope))
8365 pn))
8366
8367 (defsubst js2-define-new-symbol (decl-type name node)
8368 (js2-scope-put-symbol js2-current-scope
8369 name
8370 (make-js2-symbol decl-type name node)))
8371
8372 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8373 "Define a symbol in the current scope.
8374 If NODE is non-nil, it is the AST node associated with the symbol."
8375 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8376 (symbol (if defining-scope
8377 (js2-scope-get-symbol defining-scope name)))
8378 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8379 (cond
8380 ((and symbol ; already defined
8381 (or (= sdt js2-CONST) ; old version is const
8382 (= decl-type js2-CONST) ; new version is const
8383 ;; two let-bound vars in this block have same name
8384 (and (= sdt js2-LET)
8385 (eq defining-scope js2-current-scope))))
8386 (js2-report-error
8387 (cond
8388 ((= sdt js2-CONST) "msg.const.redecl")
8389 ((= sdt js2-LET) "msg.let.redecl")
8390 ((= sdt js2-VAR) "msg.var.redecl")
8391 ((= sdt js2-FUNCTION) "msg.function.redecl")
8392 (t "msg.parm.redecl"))
8393 name))
8394 ((= decl-type js2-LET)
8395 (if (and (not ignore-not-in-block)
8396 (or (= (js2-node-type js2-current-scope) js2-IF)
8397 (js2-loop-node-p js2-current-scope)))
8398 (js2-report-error "msg.let.decl.not.in.block")
8399 (js2-define-new-symbol decl-type name node)))
8400 ((or (= decl-type js2-VAR)
8401 (= decl-type js2-CONST)
8402 (= decl-type js2-FUNCTION))
8403 (if symbol
8404 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8405 (js2-add-strict-warning "msg.var.redecl" name)
8406 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8407 (js2-add-strict-warning "msg.var.hides.arg" name)))
8408 (js2-define-new-symbol decl-type name node)))
8409 ((= decl-type js2-LP)
8410 (if symbol
8411 ;; must be duplicate parameter. Second parameter hides the
8412 ;; first, so go ahead and add the second pararameter
8413 (js2-report-warning "msg.dup.parms" name))
8414 (js2-define-new-symbol decl-type name node))
8415 (t (js2-code-bug)))))
8416
8417 (defun js2-parse-expr ()
8418 (let* ((pn (js2-parse-assign-expr))
8419 (pos (js2-node-pos pn))
8420 left
8421 right
8422 op-pos)
8423 (while (js2-match-token js2-COMMA)
8424 (setq op-pos (- js2-token-beg pos)) ; relative
8425 (if (= (js2-peek-token) js2-YIELD)
8426 (js2-report-error "msg.yield.parenthesized"))
8427 (setq right (js2-parse-assign-expr)
8428 left pn
8429 pn (make-js2-infix-node :type js2-COMMA
8430 :pos pos
8431 :len (- js2-ts-cursor pos)
8432 :op-pos op-pos
8433 :left left
8434 :right right))
8435 (js2-node-add-children pn left right))
8436 pn))
8437
8438 (defun js2-parse-assign-expr ()
8439 (let ((tt (js2-peek-token))
8440 (pos js2-token-beg)
8441 pn
8442 left
8443 right
8444 op-pos)
8445 (if (= tt js2-YIELD)
8446 (js2-parse-return-or-yield tt t)
8447 ;; not yield - parse assignment expression
8448 (setq pn (js2-parse-cond-expr)
8449 tt (js2-peek-token))
8450 (when (and (<= js2-first-assign tt)
8451 (<= tt js2-last-assign))
8452 (js2-consume-token)
8453 (setq op-pos (- js2-token-beg pos) ; relative
8454 left pn
8455 right (js2-parse-assign-expr)
8456 pn (make-js2-assign-node :type tt
8457 :pos pos
8458 :len (- (js2-node-end right) pos)
8459 :op-pos op-pos
8460 :left left
8461 :right right))
8462 (when js2-parse-ide-mode
8463 (js2-highlight-assign-targets pn left right)
8464 (if (or (js2-function-node-p right)
8465 (js2-object-node-p right))
8466 (js2-record-imenu-functions right left)))
8467 ;; do this last so ide checks above can use absolute positions
8468 (js2-node-add-children pn left right))
8469 pn)))
8470
8471 (defun js2-parse-cond-expr ()
8472 (let ((pos js2-token-beg)
8473 (pn (js2-parse-or-expr))
8474 test-expr
8475 if-true
8476 if-false
8477 q-pos
8478 c-pos)
8479 (when (js2-match-token js2-HOOK)
8480 (setq q-pos (- js2-token-beg pos)
8481 if-true (js2-parse-assign-expr))
8482 (js2-must-match js2-COLON "msg.no.colon.cond")
8483 (setq c-pos (- js2-token-beg pos)
8484 if-false (js2-parse-assign-expr)
8485 test-expr pn
8486 pn (make-js2-cond-node :pos pos
8487 :len (- (js2-node-end if-false) pos)
8488 :test-expr test-expr
8489 :true-expr if-true
8490 :false-expr if-false
8491 :q-pos q-pos
8492 :c-pos c-pos))
8493 (js2-node-add-children pn test-expr if-true if-false))
8494 pn))
8495
8496 (defun js2-make-binary (type left parser)
8497 "Helper for constructing a binary-operator AST node.
8498 LEFT is the left-side-expression, already parsed, and the
8499 binary operator should have just been matched.
8500 PARSER is a function to call to parse the right operand,
8501 or a `js2-node' struct if it has already been parsed."
8502 (let* ((pos (js2-node-pos left))
8503 (op-pos (- js2-token-beg pos))
8504 (right (if (js2-node-p parser)
8505 parser
8506 (funcall parser)))
8507 (pn (make-js2-infix-node :type type
8508 :pos pos
8509 :len (- (js2-node-end right) pos)
8510 :op-pos op-pos
8511 :left left
8512 :right right)))
8513 (js2-node-add-children pn left right)
8514 pn))
8515
8516 (defun js2-parse-or-expr ()
8517 (let ((pn (js2-parse-and-expr)))
8518 (when (js2-match-token js2-OR)
8519 (setq pn (js2-make-binary js2-OR
8520 pn
8521 'js2-parse-or-expr)))
8522 pn))
8523
8524 (defun js2-parse-and-expr ()
8525 (let ((pn (js2-parse-bit-or-expr)))
8526 (when (js2-match-token js2-AND)
8527 (setq pn (js2-make-binary js2-AND
8528 pn
8529 'js2-parse-and-expr)))
8530 pn))
8531
8532 (defun js2-parse-bit-or-expr ()
8533 (let ((pn (js2-parse-bit-xor-expr)))
8534 (while (js2-match-token js2-BITOR)
8535 (setq pn (js2-make-binary js2-BITOR
8536 pn
8537 'js2-parse-bit-xor-expr)))
8538 pn))
8539
8540 (defun js2-parse-bit-xor-expr ()
8541 (let ((pn (js2-parse-bit-and-expr)))
8542 (while (js2-match-token js2-BITXOR)
8543 (setq pn (js2-make-binary js2-BITXOR
8544 pn
8545 'js2-parse-bit-and-expr)))
8546 pn))
8547
8548 (defun js2-parse-bit-and-expr ()
8549 (let ((pn (js2-parse-eq-expr)))
8550 (while (js2-match-token js2-BITAND)
8551 (setq pn (js2-make-binary js2-BITAND
8552 pn
8553 'js2-parse-eq-expr)))
8554 pn))
8555
8556 (defconst js2-parse-eq-ops
8557 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8558
8559 (defun js2-parse-eq-expr ()
8560 (let ((pn (js2-parse-rel-expr))
8561 tt)
8562 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8563 (js2-consume-token)
8564 (setq pn (js2-make-binary tt
8565 pn
8566 'js2-parse-rel-expr)))
8567 pn))
8568
8569 (defconst js2-parse-rel-ops
8570 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8571
8572 (defun js2-parse-rel-expr ()
8573 (let ((pn (js2-parse-shift-expr))
8574 (continue t)
8575 tt)
8576 (while continue
8577 (setq tt (js2-peek-token))
8578 (cond
8579 ((and js2-in-for-init (= tt js2-IN))
8580 (setq continue nil))
8581 ((memq tt js2-parse-rel-ops)
8582 (js2-consume-token)
8583 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8584 (t
8585 (setq continue nil))))
8586 pn))
8587
8588 (defconst js2-parse-shift-ops
8589 (list js2-LSH js2-URSH js2-RSH))
8590
8591 (defun js2-parse-shift-expr ()
8592 (let ((pn (js2-parse-add-expr))
8593 tt
8594 (continue t))
8595 (while continue
8596 (setq tt (js2-peek-token))
8597 (if (memq tt js2-parse-shift-ops)
8598 (progn
8599 (js2-consume-token)
8600 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8601 (setq continue nil)))
8602 pn))
8603
8604 (defun js2-parse-add-expr ()
8605 (let ((pn (js2-parse-mul-expr))
8606 tt
8607 (continue t))
8608 (while continue
8609 (setq tt (js2-peek-token))
8610 (if (or (= tt js2-ADD) (= tt js2-SUB))
8611 (progn
8612 (js2-consume-token)
8613 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8614 (setq continue nil)))
8615 pn))
8616
8617 (defconst js2-parse-mul-ops
8618 (list js2-MUL js2-DIV js2-MOD))
8619
8620 (defun js2-parse-mul-expr ()
8621 (let ((pn (js2-parse-unary-expr))
8622 tt
8623 (continue t))
8624 (while continue
8625 (setq tt (js2-peek-token))
8626 (if (memq tt js2-parse-mul-ops)
8627 (progn
8628 (js2-consume-token)
8629 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8630 (setq continue nil)))
8631 pn))
8632
8633 (defsubst js2-make-unary (type parser &rest args)
8634 "Make a unary node of type TYPE.
8635 PARSER is either a node (for postfix operators) or a function to call
8636 to parse the operand (for prefix operators)."
8637 (let* ((pos js2-token-beg)
8638 (postfix (js2-node-p parser))
8639 (expr (if postfix
8640 parser
8641 (apply parser args)))
8642 end
8643 pn)
8644 (if postfix ; e.g. i++
8645 (setq pos (js2-node-pos expr)
8646 end js2-token-end)
8647 (setq end (js2-node-end expr)))
8648 (setq pn (make-js2-unary-node :type type
8649 :pos pos
8650 :len (- end pos)
8651 :operand expr))
8652 (js2-node-add-children pn expr)
8653 pn))
8654
8655 (defconst js2-incrementable-node-types
8656 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8657 "Node types that can be the operand of a ++ or -- operator.")
8658
8659 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8660 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8661 js2-incrementable-node-types)
8662 (js2-report-error (if (= tt js2-INC)
8663 "msg.bad.incr"
8664 "msg.bad.decr")
8665 nil beg (- end beg))))
8666
8667 (defun js2-parse-unary-expr ()
8668 (let ((tt (js2-peek-token))
8669 pn expr beg end)
8670 (cond
8671 ((or (= tt js2-VOID)
8672 (= tt js2-NOT)
8673 (= tt js2-BITNOT)
8674 (= tt js2-TYPEOF))
8675 (js2-consume-token)
8676 (js2-make-unary tt 'js2-parse-unary-expr))
8677 ((= tt js2-ADD)
8678 (js2-consume-token)
8679 ;; Convert to special POS token in decompiler and parse tree
8680 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8681 ((= tt js2-SUB)
8682 (js2-consume-token)
8683 ;; Convert to special NEG token in decompiler and parse tree
8684 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8685 ((or (= tt js2-INC)
8686 (= tt js2-DEC))
8687 (js2-consume-token)
8688 (prog1
8689 (setq beg js2-token-beg
8690 end js2-token-end
8691 expr (js2-make-unary tt 'js2-parse-member-expr t))
8692 (js2-check-bad-inc-dec tt beg end expr)))
8693 ((= tt js2-DELPROP)
8694 (js2-consume-token)
8695 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8696 ((= tt js2-ERROR)
8697 (js2-consume-token)
8698 (make-js2-error-node)) ; try to continue
8699 ((and (= tt js2-LT)
8700 js2-compiler-xml-available)
8701 ;; XML stream encountered in expression.
8702 (js2-consume-token)
8703 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8704 (t
8705 (setq pn (js2-parse-member-expr t)
8706 ;; Don't look across a newline boundary for a postfix incop.
8707 tt (js2-peek-token-or-eol))
8708 (when (or (= tt js2-INC) (= tt js2-DEC))
8709 (js2-consume-token)
8710 (setf expr pn
8711 pn (js2-make-unary tt expr))
8712 (js2-node-set-prop pn 'postfix t)
8713 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8714 pn))))
8715
8716 (defun js2-parse-xml-initializer ()
8717 "Parse an E4X XML initializer.
8718 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8719 Then I'll postprocess the result, depending on whether we're in IDE
8720 mode or codegen mode, and generate the appropriate rewritten AST.
8721 IDE mode uses a rich AST that models the XML structure. Codegen mode
8722 just concatenates everything and makes a new XML or XMLList out of it."
8723 (let ((tt (js2-get-first-xml-token))
8724 pn-xml
8725 pn
8726 expr
8727 kids
8728 expr-pos
8729 (continue t)
8730 (first-token t))
8731 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8732 (js2-report-error "msg.syntax"))
8733 (setq pn-xml (make-js2-xml-node))
8734 (while continue
8735 (if first-token
8736 (setq first-token nil)
8737 (setq tt (js2-get-next-xml-token)))
8738 (cond
8739 ;; js2-XML means we found a {expr} in the XML stream.
8740 ;; The js2-ts-string is the XML up to the left-curly.
8741 ((= tt js2-XML)
8742 (push (make-js2-string-node :pos js2-token-beg
8743 :len (- js2-ts-cursor js2-token-beg))
8744 kids)
8745 (js2-must-match js2-LC "msg.syntax")
8746 (setq expr-pos js2-ts-cursor
8747 expr (if (eq (js2-peek-token) js2-RC)
8748 (make-js2-empty-expr-node :pos expr-pos)
8749 (js2-parse-expr)))
8750 (js2-must-match js2-RC "msg.syntax")
8751 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8752 :len (js2-node-len expr)
8753 :expr expr))
8754 (js2-node-add-children pn expr)
8755 (push pn kids))
8756 ;; a js2-XMLEND token means we hit the final close-tag.
8757 ((= tt js2-XMLEND)
8758 (push (make-js2-string-node :pos js2-token-beg
8759 :len (- js2-ts-cursor js2-token-beg))
8760 kids)
8761 (dolist (kid (nreverse kids))
8762 (js2-block-node-push pn-xml kid))
8763 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8764 (js2-node-pos pn-xml))
8765 continue nil))
8766 (t
8767 (js2-report-error "msg.syntax")
8768 (setq continue nil))))
8769 pn-xml))
8770
8771
8772 (defun js2-parse-argument-list ()
8773 "Parse an argument list and return it as a Lisp list of nodes.
8774 Returns the list in reverse order. Consumes the right-paren token."
8775 (let (result)
8776 (unless (js2-match-token js2-RP)
8777 (loop do
8778 (if (= (js2-peek-token) js2-YIELD)
8779 (js2-report-error "msg.yield.parenthesized"))
8780 (push (js2-parse-assign-expr) result)
8781 while
8782 (js2-match-token js2-COMMA))
8783 (js2-must-match js2-RP "msg.no.paren.arg")
8784 result)))
8785
8786 (defun js2-parse-member-expr (&optional allow-call-syntax)
8787 (let ((tt (js2-peek-token))
8788 pn
8789 pos
8790 target
8791 args
8792 beg
8793 end
8794 init
8795 tail)
8796 (if (/= tt js2-NEW)
8797 (setq pn (js2-parse-primary-expr))
8798 ;; parse a 'new' expression
8799 (js2-consume-token)
8800 (setq pos js2-token-beg
8801 beg pos
8802 target (js2-parse-member-expr)
8803 end (js2-node-end target)
8804 pn (make-js2-new-node :pos pos
8805 :target target
8806 :len (- end pos)))
8807 (js2-node-add-children pn target)
8808 (when (js2-match-token js2-LP)
8809 ;; Add the arguments to pn, if any are supplied.
8810 (setf beg pos ; start of "new" keyword
8811 pos js2-token-beg
8812 args (nreverse (js2-parse-argument-list))
8813 (js2-new-node-args pn) args
8814 end js2-token-end
8815 (js2-new-node-lp pn) (- pos beg)
8816 (js2-new-node-rp pn) (- end 1 beg))
8817 (apply #'js2-node-add-children pn args))
8818 (when (and js2-allow-rhino-new-expr-initializer
8819 (js2-match-token js2-LC))
8820 (setf init (js2-parse-object-literal)
8821 end (js2-node-end init)
8822 (js2-new-node-initializer pn) init)
8823 (js2-node-add-children pn init))
8824 (setf (js2-node-len pn) (- beg pos))) ; end outer if
8825 (js2-parse-member-expr-tail allow-call-syntax pn)))
8826
8827 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8828 "Parse a chain of property/array accesses or function calls.
8829 Includes parsing for E4X operators like `..' and `.@'.
8830 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8831 Returns an expression tree that includes PN, the parent node."
8832 (let ((beg (js2-node-pos pn))
8833 tt
8834 (continue t))
8835 (while continue
8836 (setq tt (js2-peek-token))
8837 (cond
8838 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8839 (setq pn (js2-parse-property-access tt pn)))
8840 ((= tt js2-DOTQUERY)
8841 (setq pn (js2-parse-dot-query pn)))
8842 ((= tt js2-LB)
8843 (setq pn (js2-parse-element-get pn)))
8844 ((= tt js2-LP)
8845 (if allow-call-syntax
8846 (setq pn (js2-parse-function-call pn))
8847 (setq continue nil)))
8848 (t
8849 (setq continue nil))))
8850 (if (>= js2-highlight-level 2)
8851 (js2-parse-highlight-member-expr-node pn))
8852 pn))
8853
8854 (defun js2-parse-dot-query (pn)
8855 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8856 Last token parsed must be `js2-DOTQUERY'."
8857 (let ((pos (js2-node-pos pn))
8858 op-pos
8859 expr
8860 end)
8861 (js2-consume-token)
8862 (js2-must-have-xml)
8863 (js2-set-requires-activation)
8864 (setq op-pos js2-token-beg
8865 expr (js2-parse-expr)
8866 end (js2-node-end expr)
8867 pn (make-js2-xml-dot-query-node :left pn
8868 :pos pos
8869 :op-pos op-pos
8870 :right expr))
8871 (js2-node-add-children pn
8872 (js2-xml-dot-query-node-left pn)
8873 (js2-xml-dot-query-node-right pn))
8874 (if (js2-must-match js2-RP "msg.no.paren")
8875 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8876 end js2-token-end))
8877 (setf (js2-node-len pn) (- end pos))
8878 pn))
8879
8880 (defun js2-parse-element-get (pn)
8881 "Parse an element-get expression, e.g. foo[bar].
8882 Last token parsed must be `js2-RB'."
8883 (let ((lb js2-token-beg)
8884 (pos (js2-node-pos pn))
8885 rb
8886 expr)
8887 (js2-consume-token)
8888 (setq expr (js2-parse-expr))
8889 (if (js2-must-match js2-RB "msg.no.bracket.index")
8890 (setq rb js2-token-beg))
8891 (setq pn (make-js2-elem-get-node :target pn
8892 :pos pos
8893 :element expr
8894 :lb (js2-relpos lb pos)
8895 :rb (js2-relpos rb pos)
8896 :len (- js2-token-end pos)))
8897 (js2-node-add-children pn
8898 (js2-elem-get-node-target pn)
8899 (js2-elem-get-node-element pn))
8900 pn))
8901
8902 (defun js2-parse-function-call (pn)
8903 (let (args
8904 (pos (js2-node-pos pn)))
8905 (js2-consume-token)
8906 (setq pn (make-js2-call-node :pos pos
8907 :target pn
8908 :lp (- js2-token-beg pos)))
8909 (js2-node-add-children pn (js2-call-node-target pn))
8910 ;; Add the arguments to pn, if any are supplied.
8911 (setf args (nreverse (js2-parse-argument-list))
8912 (js2-call-node-rp pn) (- js2-token-beg pos)
8913 (js2-call-node-args pn) args)
8914 (apply #'js2-node-add-children pn args)
8915 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8916 pn))
8917
8918 (defun js2-parse-property-access (tt pn)
8919 "Parse a property access, XML descendants access, or XML attr access."
8920 (let ((member-type-flags 0)
8921 (dot-pos js2-token-beg)
8922 (dot-len (if (= tt js2-DOTDOT) 2 1))
8923 name
8924 ref ; right side of . or .. operator
8925 result)
8926 (js2-consume-token)
8927 (when (= tt js2-DOTDOT)
8928 (js2-must-have-xml)
8929 (setq member-type-flags js2-descendants-flag))
8930 (if (not js2-compiler-xml-available)
8931 (progn
8932 (js2-must-match-prop-name "msg.no.name.after.dot")
8933 (setq name (js2-create-name-node t js2-GETPROP)
8934 result (make-js2-prop-get-node :left pn
8935 :pos js2-token-beg
8936 :right name
8937 :len (- js2-token-end
8938 js2-token-beg)))
8939 (js2-node-add-children result pn name)
8940 result)
8941 ;; otherwise look for XML operators
8942 (setf result (if (= tt js2-DOT)
8943 (make-js2-prop-get-node)
8944 (make-js2-infix-node :type js2-DOTDOT))
8945 (js2-node-pos result) (js2-node-pos pn)
8946 (js2-infix-node-op-pos result) dot-pos
8947 (js2-infix-node-left result) pn ; do this after setting position
8948 tt (js2-next-token))
8949 (cond
8950 ;; needed for generator.throw()
8951 ((= tt js2-THROW)
8952 (js2-save-name-token-data js2-token-beg "throw")
8953 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8954 ;; handles: name, ns::name, ns::*, ns::[expr]
8955 ((js2-valid-prop-name-token tt)
8956 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8957 ;; handles: *, *::name, *::*, *::[expr]
8958 ((= tt js2-MUL)
8959 (js2-save-name-token-data js2-token-beg "*")
8960 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8961 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8962 ((= tt js2-XMLATTR)
8963 (setq result (js2-parse-attribute-access)))
8964 (t
8965 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8966 (if ref
8967 (setf (js2-node-len result) (- (js2-node-end ref)
8968 (js2-node-pos result))
8969 (js2-infix-node-right result) ref))
8970 (if (js2-infix-node-p result)
8971 (js2-node-add-children result
8972 (js2-infix-node-left result)
8973 (js2-infix-node-right result)))
8974 result)))
8975
8976 (defun js2-parse-attribute-access ()
8977 "Parse an E4X XML attribute expression.
8978 This includes expressions of the forms:
8979
8980 @attr @ns::attr @ns::*
8981 @* @*::attr @*::*
8982 @[expr] @*::[expr] @ns::[expr]
8983
8984 Called if we peeked an '@' token."
8985 (let ((tt (js2-next-token))
8986 (at-pos js2-token-beg))
8987 (cond
8988 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8989 ((js2-valid-prop-name-token tt)
8990 (js2-parse-property-name at-pos js2-ts-string 0))
8991 ;; handles: @*, @*::name, @*::*, @*::[expr]
8992 ((= tt js2-MUL)
8993 (js2-save-name-token-data js2-token-beg "*")
8994 (js2-parse-property-name js2-token-beg "*" 0))
8995 ;; handles @[expr]
8996 ((= tt js2-LB)
8997 (js2-parse-xml-elem-ref at-pos))
8998 (t
8999 (js2-report-error "msg.no.name.after.xmlAttr")
9000 ;; Avoid cascaded errors that happen if we make an error node here.
9001 (js2-save-name-token-data js2-token-beg "")
9002 (js2-parse-property-name js2-token-beg "" 0)))))
9003
9004 (defun js2-parse-property-name (at-pos s member-type-flags)
9005 "Check if :: follows name in which case it becomes qualified name.
9006
9007 AT-POS is a natural number if we just read an '@' token, else nil.
9008 S is the name or string that was matched: an identifier, 'throw' or '*'.
9009 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9010
9011 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9012 operator, or the name is followed by ::. For a plain name, returns a
9013 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9014 (let ((pos (or at-pos js2-token-beg))
9015 colon-pos
9016 (name (js2-create-name-node t js2-current-token))
9017 ns
9018 tt
9019 ref
9020 pn)
9021 (catch 'return
9022 (when (js2-match-token js2-COLONCOLON)
9023 (setq ns name
9024 colon-pos js2-token-beg
9025 tt (js2-next-token))
9026 (cond
9027 ;; handles name::name
9028 ((js2-valid-prop-name-token tt)
9029 (setq name (js2-create-name-node)))
9030 ;; handles name::*
9031 ((= tt js2-MUL)
9032 (js2-save-name-token-data js2-token-beg "*")
9033 (setq name (js2-create-name-node)))
9034 ;; handles name::[expr]
9035 ((= tt js2-LB)
9036 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9037 (t
9038 (js2-report-error "msg.no.name.after.coloncolon"))))
9039 (if (and (null ns) (zerop member-type-flags))
9040 name
9041 (prog1
9042 (setq pn
9043 (make-js2-xml-prop-ref-node :pos pos
9044 :len (- (js2-node-end name) pos)
9045 :at-pos at-pos
9046 :colon-pos colon-pos
9047 :propname name))
9048 (js2-node-add-children pn name))))))
9049
9050 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9051 "Parse the [expr] portion of an xml element reference.
9052 For instance, @[expr], @*::[expr], or ns::[expr]."
9053 (let* ((lb js2-token-beg)
9054 (pos (or at-pos lb))
9055 rb
9056 (expr (js2-parse-expr))
9057 (end (js2-node-end expr))
9058 pn)
9059 (if (js2-must-match js2-RB "msg.no.bracket.index")
9060 (setq rb js2-token-beg
9061 end js2-token-end))
9062 (prog1
9063 (setq pn
9064 (make-js2-xml-elem-ref-node :pos pos
9065 :len (- end pos)
9066 :namespace namespace
9067 :colon-pos colon-pos
9068 :at-pos at-pos
9069 :expr expr
9070 :lb (js2-relpos lb pos)
9071 :rb (js2-relpos rb pos)))
9072 (js2-node-add-children pn namespace expr))))
9073
9074 (defun js2-parse-primary-expr ()
9075 "Parse a literal (leaf) expression of some sort.
9076 Includes complex literals such as functions, object-literals,
9077 array-literals, array comprehensions and regular expressions."
9078 (let ((tt-flagged (js2-next-flagged-token))
9079 pn ; parent node (usually return value)
9080 tt
9081 px-pos ; paren-expr pos
9082 len
9083 flags ; regexp flags
9084 expr)
9085 (setq tt js2-current-token)
9086 (cond
9087 ((= tt js2-FUNCTION)
9088 (js2-parse-function 'FUNCTION_EXPRESSION))
9089 ((= tt js2-LB)
9090 (js2-parse-array-literal))
9091 ((= tt js2-LC)
9092 (js2-parse-object-literal))
9093 ((= tt js2-LET)
9094 (js2-parse-let js2-token-beg))
9095 ((= tt js2-LP)
9096 (setq px-pos js2-token-beg
9097 expr (js2-parse-expr))
9098 (js2-must-match js2-RP "msg.no.paren")
9099 (setq pn (make-js2-paren-node :pos px-pos
9100 :expr expr
9101 :len (- js2-token-end px-pos)))
9102 (js2-node-add-children pn (js2-paren-node-expr pn))
9103 pn)
9104 ((= tt js2-XMLATTR)
9105 (js2-must-have-xml)
9106 (js2-parse-attribute-access))
9107 ((= tt js2-NAME)
9108 (js2-parse-name tt-flagged tt))
9109 ((= tt js2-NUMBER)
9110 (make-js2-number-node))
9111 ((= tt js2-STRING)
9112 (prog1
9113 (make-js2-string-node)
9114 (js2-record-face 'font-lock-string-face)))
9115 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9116 ;; Got / or /= which in this context means a regexp literal
9117 (setq px-pos js2-token-beg)
9118 (js2-read-regexp tt)
9119 (setq flags js2-ts-regexp-flags
9120 js2-ts-regexp-flags nil)
9121 (prog1
9122 (make-js2-regexp-node :pos px-pos
9123 :len (- js2-ts-cursor px-pos)
9124 :value js2-ts-string
9125 :flags flags)
9126 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9127 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9128 ((or (= tt js2-NULL)
9129 (= tt js2-THIS)
9130 (= tt js2-FALSE)
9131 (= tt js2-TRUE))
9132 (make-js2-keyword-node :type tt))
9133 ((= tt js2-RESERVED)
9134 (js2-report-error "msg.reserved.id")
9135 (make-js2-name-node))
9136 ((= tt js2-ERROR)
9137 ;; the scanner or one of its subroutines reported the error.
9138 (make-js2-error-node))
9139 ((= tt js2-EOF)
9140 (setq px-pos (point-at-bol)
9141 len (- js2-ts-cursor px-pos))
9142 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9143 (make-js2-error-node :pos px-pos :len len))
9144 (t
9145 (js2-report-error "msg.syntax")
9146 (make-js2-error-node)))))
9147
9148 (defun js2-parse-name (tt-flagged tt)
9149 (let ((name js2-ts-string)
9150 (name-pos js2-token-beg))
9151 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9152 (= (js2-peek-token) js2-COLON))
9153 (prog1
9154 ;; Do not consume colon, it is used as unwind indicator
9155 ;; to return to statementHelper.
9156 (make-js2-label-node :pos name-pos
9157 :len (- js2-token-end name-pos)
9158 :name name)
9159 (js2-set-face name-pos
9160 js2-token-end
9161 'font-lock-variable-name-face 'record))
9162 ;; Otherwise not a label, just a name. Unfortunately peeking
9163 ;; the next token to check for a colon has biffed js2-token-beg
9164 ;; and js2-token-end. We store the name's bounds in buffer vars
9165 ;; and `js2-create-name-node' uses them.
9166 (js2-save-name-token-data name-pos name)
9167 (if js2-compiler-xml-available
9168 (js2-parse-property-name nil name 0)
9169 (js2-create-name-node 'check-activation)))))
9170
9171 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9172 (js2-add-strict-warning
9173 msg nil
9174 ;; back up from comma to beginning of line or array/objlit
9175 (max (if elems
9176 (js2-node-pos (car elems))
9177 pos)
9178 (save-excursion
9179 (goto-char comma-pos)
9180 (back-to-indentation)
9181 (point)))
9182 comma-pos))
9183
9184 (defun js2-parse-array-literal ()
9185 (let ((pos js2-token-beg)
9186 (end js2-token-end)
9187 (after-lb-or-comma t)
9188 after-comma
9189 tt
9190 elems
9191 pn
9192 (continue t))
9193 (while continue
9194 (setq tt (js2-peek-token))
9195 (cond
9196 ;; comma
9197 ((= tt js2-COMMA)
9198 (js2-consume-token)
9199 (setq after-comma js2-token-end)
9200 (if (not after-lb-or-comma)
9201 (setq after-lb-or-comma t)
9202 (push nil elems)))
9203 ;; end of array
9204 ((or (= tt js2-RB)
9205 (= tt js2-EOF)) ; prevent infinite loop
9206 (if (= tt js2-EOF)
9207 (js2-report-error "msg.no.bracket.arg" nil pos)
9208 (js2-consume-token))
9209 (setq continue nil
9210 end js2-token-end
9211 pn (make-js2-array-node :pos pos
9212 :len (- js2-ts-cursor pos)
9213 :elems (nreverse elems)))
9214 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9215 (when after-comma
9216 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9217 pos elems after-comma)))
9218 ;; array comp
9219 ((and (>= js2-language-version 170)
9220 (= tt js2-FOR) ; check for array comprehension
9221 (not after-lb-or-comma) ; "for" can't follow a comma
9222 elems ; must have at least 1 element
9223 (not (cdr elems))) ; but no 2nd element
9224 (setf continue nil
9225 pn (js2-parse-array-comprehension (car elems) pos)))
9226 ;; another element
9227 (t
9228 (unless after-lb-or-comma
9229 (js2-report-error "msg.no.bracket.arg"))
9230 (push (js2-parse-assign-expr) elems)
9231 (setq after-lb-or-comma nil
9232 after-comma nil))))
9233 pn))
9234
9235 (defun js2-parse-array-comprehension (expr pos)
9236 "Parse a JavaScript 1.7 Array Comprehension.
9237 EXPR is the first expression after the opening left-bracket.
9238 POS is the beginning of the LB token preceding EXPR.
9239 We should have just parsed the 'for' keyword before calling this function."
9240 (let (loops
9241 filter
9242 if-pos
9243 result)
9244 (while (= (js2-peek-token) js2-FOR)
9245 (push (js2-parse-array-comp-loop) loops))
9246 (when (= (js2-peek-token) js2-IF)
9247 (js2-consume-token)
9248 (setq if-pos (- js2-token-beg pos) ; relative
9249 filter (js2-parse-condition)))
9250 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9251 (setq result (make-js2-array-comp-node :pos pos
9252 :len (- js2-ts-cursor pos)
9253 :result expr
9254 :loops (nreverse loops)
9255 :filter (car filter)
9256 :lp (js2-relpos (second filter) pos)
9257 :rp (js2-relpos (third filter) pos)
9258 :if-pos if-pos))
9259 (apply #'js2-node-add-children result expr (car filter)
9260 (js2-array-comp-node-loops result))
9261 result))
9262
9263 (defun js2-parse-array-comp-loop ()
9264 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9265 Last token peeked should be the initial FOR."
9266 (let ((pos js2-token-beg)
9267 (pn (make-js2-array-comp-loop-node))
9268 tt
9269 iter
9270 obj
9271 foreach-p
9272 in-pos
9273 each-pos
9274 lp
9275 rp)
9276 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9277 (js2-push-scope pn)
9278 (unwind-protect
9279 (progn
9280 (when (js2-match-token js2-NAME)
9281 (if (string= js2-ts-string "each")
9282 (progn
9283 (setq foreach-p t
9284 each-pos (- js2-token-beg pos)) ; relative
9285 (js2-record-face 'font-lock-keyword-face))
9286 (js2-report-error "msg.no.paren.for")))
9287 (if (js2-must-match js2-LP "msg.no.paren.for")
9288 (setq lp (- js2-token-beg pos)))
9289 (setq tt (js2-peek-token))
9290 (cond
9291 ((or (= tt js2-LB)
9292 (= tt js2-LC))
9293 ;; handle destructuring assignment
9294 (setq iter (js2-parse-primary-expr)))
9295 ((js2-valid-prop-name-token tt)
9296 (js2-consume-token)
9297 (setq iter (js2-create-name-node)))
9298 (t
9299 (js2-report-error "msg.bad.var")))
9300 ;; Define as a let since we want the scope of the variable to
9301 ;; be restricted to the array comprehension
9302 (if (js2-name-node-p iter)
9303 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9304 (if (js2-must-match js2-IN "msg.in.after.for.name")
9305 (setq in-pos (- js2-token-beg pos)))
9306 (setq obj (js2-parse-expr))
9307 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9308 (setq rp (- js2-token-beg pos)))
9309 (setf (js2-node-pos pn) pos
9310 (js2-node-len pn) (- js2-ts-cursor pos)
9311 (js2-array-comp-loop-node-iterator pn) iter
9312 (js2-array-comp-loop-node-object pn) obj
9313 (js2-array-comp-loop-node-in-pos pn) in-pos
9314 (js2-array-comp-loop-node-each-pos pn) each-pos
9315 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9316 (js2-array-comp-loop-node-lp pn) lp
9317 (js2-array-comp-loop-node-rp pn) rp)
9318 (js2-node-add-children pn iter obj))
9319 (js2-pop-scope))
9320 pn))
9321
9322 (defun js2-parse-object-literal ()
9323 (let ((pos js2-token-beg)
9324 tt
9325 elems
9326 result
9327 after-comma
9328 (continue t))
9329 (while continue
9330 (setq tt (js2-peek-token))
9331 (cond
9332 ;; {foo: ...}, {'foo': ...}, {get foo() {...}}, or {set foo(x) {...}}
9333 ((or (js2-valid-prop-name-token tt)
9334 (= tt js2-STRING))
9335 (setq after-comma nil
9336 result (js2-parse-named-prop tt))
9337 (if (and (null result)
9338 (not js2-recover-from-parse-errors))
9339 (setq continue nil)
9340 (push result elems)))
9341 ;; {12: x} or {10.7: x}
9342 ((= tt js2-NUMBER)
9343 (js2-consume-token)
9344 (setq after-comma nil)
9345 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9346 ;; trailing comma
9347 ((= tt js2-RC)
9348 (setq continue nil)
9349 (if after-comma
9350 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9351 pos elems after-comma)))
9352 (t
9353 (js2-report-error "msg.bad.prop")
9354 (unless js2-recover-from-parse-errors
9355 (setq continue nil)))) ; end switch
9356 (if (js2-match-token js2-COMMA)
9357 (setq after-comma js2-token-end)
9358 (setq continue nil))) ; end loop
9359 (js2-must-match js2-RC "msg.no.brace.prop")
9360 (setq result (make-js2-object-node :pos pos
9361 :len (- js2-ts-cursor pos)
9362 :elems (nreverse elems)))
9363 (apply #'js2-node-add-children result (js2-object-node-elems result))
9364 result))
9365
9366 (defun js2-parse-named-prop (tt)
9367 "Parse a name, string, or getter/setter object property."
9368 (js2-consume-token)
9369 (let ((string-prop (and (= tt js2-STRING)
9370 (make-js2-string-node)))
9371 expr
9372 (ppos js2-token-beg)
9373 (pend js2-token-end)
9374 (name (js2-create-name-node))
9375 (prop js2-ts-string))
9376 (if (and (= tt js2-NAME)
9377 (= (js2-peek-token) js2-NAME)
9378 (or (string= prop "get")
9379 (string= prop "set")))
9380 (progn
9381 ;; getter/setter prop
9382 (js2-consume-token)
9383 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9384 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9385 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9386 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9387 ;; regular prop
9388 (prog1
9389 (setq expr (js2-parse-plain-property (or string-prop name)))
9390 (js2-set-face ppos pend
9391 (if (js2-function-node-p
9392 (js2-object-prop-node-right expr))
9393 'font-lock-function-name-face
9394 'font-lock-variable-name-face)
9395 'record)))))
9396
9397 (defun js2-parse-plain-property (prop)
9398 "Parse a non-getter/setter property in an object literal.
9399 PROP is the node representing the property: a number, name or string."
9400 (js2-must-match js2-COLON "msg.no.colon.prop")
9401 (let* ((pos (js2-node-pos prop))
9402 (colon (- js2-token-beg pos))
9403 (expr (js2-parse-assign-expr))
9404 (result (make-js2-object-prop-node
9405 :pos pos
9406 ;; don't include last consumed token in length
9407 :len (- (+ (js2-node-pos expr)
9408 (js2-node-len expr))
9409 pos)
9410 :left prop
9411 :right expr
9412 :op-pos colon)))
9413 (js2-node-add-children result prop expr)
9414 result))
9415
9416 (defun js2-parse-getter-setter-prop (pos prop get-p)
9417 "Parse getter or setter property in an object literal.
9418 JavaScript syntax is:
9419
9420 { get foo() {...}, set foo(x) {...} }
9421
9422 POS is the start position of the `get' or `set' keyword.
9423 PROP is the `js2-name-node' representing the property name.
9424 GET-P is non-nil if the keyword was `get'."
9425 (let ((type (if get-p js2-GET js2-SET))
9426 result
9427 end
9428 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9429 ;; it has to be an anonymous function, as we already parsed the name
9430 (if (/= (js2-node-type fn) js2-FUNCTION)
9431 (js2-report-error "msg.bad.prop")
9432 (if (plusp (length (js2-function-name fn)))
9433 (js2-report-error "msg.bad.prop")))
9434 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9435 (setq end (js2-node-end fn)
9436 result (make-js2-getter-setter-node :type type
9437 :pos pos
9438 :len (- end pos)
9439 :left prop
9440 :right fn))
9441 (js2-node-add-children result prop fn)
9442 result))
9443
9444 (defun js2-create-name-node (&optional check-activation-p token)
9445 "Create a name node using the token info from last scanned name.
9446 In some cases we need to either synthesize a name node, or we lost
9447 the name token information by peeking. If the TOKEN parameter is
9448 not `js2-NAME', then we use the token info saved in instance vars."
9449 (let ((beg js2-token-beg)
9450 (s js2-ts-string)
9451 name)
9452 (when (/= js2-current-token js2-NAME)
9453 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9454 s js2-prev-name-token-string
9455 js2-prev-name-token-start nil
9456 js2-prev-name-token-string nil))
9457 (setq name (make-js2-name-node :pos beg
9458 :name s
9459 :len (length s)))
9460 (if check-activation-p
9461 (js2-check-activation-name s (or token js2-NAME)))
9462 name))
9463
9464 ;;; Indentation support
9465
9466 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9467 ;; Karl cleverly deduces that the desired indentation level is often a
9468 ;; function of paren/bracket/brace nesting depth, which can be determined
9469 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9470 ;; then does some equally clever checks to see if we're in the context of a
9471 ;; substatement of a possibly braceless statement keyword such as if, while,
9472 ;; or finally. This approach yields pretty good results.
9473
9474 ;; The indenter is often "wrong", however, and needs to be overridden.
9475 ;; The right long-term solution is probably to emulate (or integrate
9476 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9477 ;; parse tree from `js2-parse' is present, which is not true at the
9478 ;; moment the user is typing, computing indentation is still thousands
9479 ;; of lines of code to handle every possible syntactic edge case.
9480
9481 ;; In the meantime, the compromise solution is that we offer a "bounce
9482 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9483 ;; current line indent among various likely guess points. This approach
9484 ;; is far from perfect, but should at least make it slightly easier to
9485 ;; move the line towards its desired indentation when manually
9486 ;; overriding Karl's heuristic nesting guesser.
9487
9488 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9489 ;; extensions such as `let' and Array comprehensions. Major kudos to
9490 ;; Karl for coming up with the initial approach, which packs a lot of
9491 ;; punch for so little code.
9492
9493 (defconst js-possibly-braceless-keyword-re
9494 (regexp-opt
9495 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with" "let")
9496 'words)
9497 "Regular expression matching keywords that are optionally
9498 followed by an opening brace.")
9499
9500 (defconst js-indent-operator-re
9501 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9502 (regexp-opt '("in" "instanceof") 'words))
9503 "Regular expression matching operators that affect indentation
9504 of continued expressions.")
9505
9506 ;; This function has horrible results if you're typing an array
9507 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9508 ;; in conjunction with electric-indent, so just disabling it.
9509 (defsubst js2-code-at-bol-p ()
9510 "Return t if the first character on line is non-whitespace."
9511 nil)
9512
9513 (defun js2-insert-and-indent (key)
9514 "Run command bound to key and indent current line.
9515 Runs the command bound to KEY in the global keymap and indents
9516 the current line."
9517 (interactive (list (this-command-keys)))
9518 (let ((cmd (lookup-key (current-global-map) key)))
9519 (if (commandp cmd)
9520 (call-interactively cmd)))
9521 ;; don't do the electric keys inside comments or strings,
9522 ;; and don't do bounce-indent with them.
9523 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9524 (js2-bounce-indent-p (js2-code-at-bol-p)))
9525 (unless (or (nth 3 parse-state)
9526 (nth 4 parse-state))
9527 (indent-according-to-mode))))
9528
9529 (defun js-re-search-forward-inner (regexp &optional bound count)
9530 "Auxiliary function for `js-re-search-forward'."
9531 (let ((parse)
9532 (saved-point (point-min)))
9533 (while (> count 0)
9534 (re-search-forward regexp bound)
9535 (setq parse (parse-partial-sexp saved-point (point)))
9536 (cond ((nth 3 parse)
9537 (re-search-forward
9538 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9539 (save-excursion (end-of-line) (point)) t))
9540 ((nth 7 parse)
9541 (forward-line))
9542 ((or (nth 4 parse)
9543 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9544 (re-search-forward "\\*/"))
9545 (t
9546 (setq count (1- count))))
9547 (setq saved-point (point))))
9548 (point))
9549
9550 (defun js-re-search-forward (regexp &optional bound noerror count)
9551 "Search forward but ignore strings and comments.
9552 Invokes `re-search-forward' but treats the buffer as if strings and
9553 comments have been removed."
9554 (let ((saved-point (point))
9555 (search-expr
9556 (cond ((null count)
9557 '(js-re-search-forward-inner regexp bound 1))
9558 ((< count 0)
9559 '(js-re-search-backward-inner regexp bound (- count)))
9560 ((> count 0)
9561 '(js-re-search-forward-inner regexp bound count)))))
9562 (condition-case err
9563 (eval search-expr)
9564 (search-failed
9565 (goto-char saved-point)
9566 (unless noerror
9567 (error (error-message-string err)))))))
9568
9569 (defun js-re-search-backward-inner (regexp &optional bound count)
9570 "Auxiliary function for `js-re-search-backward'."
9571 (let ((parse)
9572 (saved-point (point-min)))
9573 (while (> count 0)
9574 (re-search-backward regexp bound)
9575 (setq parse (parse-partial-sexp saved-point (point)))
9576 (cond ((nth 3 parse)
9577 (re-search-backward
9578 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9579 (line-beginning-position) t))
9580 ((nth 7 parse)
9581 (goto-char (nth 8 parse)))
9582 ((or (nth 4 parse)
9583 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9584 (re-search-backward "/\\*"))
9585 (t
9586 (setq count (1- count))))))
9587 (point))
9588
9589 (defun js-re-search-backward (regexp &optional bound noerror count)
9590 "Search backward but ignore strings and comments.
9591 Invokes `re-search-backward' but treats the buffer as if strings and
9592 comments have been removed."
9593 (let ((saved-point (point))
9594 (search-expr
9595 (cond ((null count)
9596 '(js-re-search-backward-inner regexp bound 1))
9597 ((< count 0)
9598 '(js-re-search-forward-inner regexp bound (- count)))
9599 ((> count 0)
9600 '(js-re-search-backward-inner regexp bound count)))))
9601 (condition-case err
9602 (eval search-expr)
9603 (search-failed
9604 (goto-char saved-point)
9605 (unless noerror
9606 (error (error-message-string err)))))))
9607
9608 (defun js-looking-at-operator-p ()
9609 "Return non-nil if text after point is an operator (that is not
9610 a comma)."
9611 (and (looking-at js-indent-operator-re)
9612 (or (not (looking-at ":"))
9613 (save-excursion
9614 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9615 (looking-at "?"))))))
9616
9617 (defun js-continued-expression-p ()
9618 "Return non-nil if the current line continues an expression."
9619 (save-excursion
9620 (back-to-indentation)
9621 (or (js-looking-at-operator-p)
9622 (when (js-re-search-backward "\n" nil t)
9623 (skip-chars-backward " \t")
9624 (backward-char)
9625 (when (js-looking-at-operator-p)
9626 (backward-char)
9627 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9628
9629 (defun js-end-of-do-while-loop-p ()
9630 "Return non-nil if word after point is `while' of a do-while
9631 statement, else returns nil. A braceless do-while statement
9632 spanning several lines requires that the start of the loop is
9633 indented to the same column as the current line."
9634 (interactive)
9635 (save-excursion
9636 (when (looking-at "\\s-*\\<while\\>")
9637 (if (save-excursion
9638 (skip-chars-backward "[ \t\n]*}")
9639 (looking-at "[ \t\n]*}"))
9640 (save-excursion
9641 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9642 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9643 (or (looking-at "\\<do\\>")
9644 (let ((saved-indent (current-indentation)))
9645 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9646 (/= (current-indentation) saved-indent)))
9647 (and (looking-at "[ \t]*\\<do\\>")
9648 (not (js-re-search-forward
9649 "\\<while\\>" (point-at-eol) t))
9650 (= (current-indentation) saved-indent))))))))
9651
9652 (defun js-ctrl-statement-indentation ()
9653 "Return the proper indentation of the current line if it
9654 starts the body of a control statement without braces, else
9655 returns nil."
9656 (let (forward-sexp-function) ; temporarily unbind it
9657 (save-excursion
9658 (back-to-indentation)
9659 (when (save-excursion
9660 (and (not (js2-same-line (point-min)))
9661 (not (looking-at "{"))
9662 (js-re-search-backward "[[:graph:]]" nil t)
9663 (not (looking-at "[{([]"))
9664 (progn
9665 (forward-char)
9666 ;; scan-sexps sometimes throws an error
9667 (ignore-errors (backward-sexp))
9668 (when (looking-at "(") (backward-word 1))
9669 (and (save-excursion
9670 (skip-chars-backward " \t}" (point-at-bol))
9671 (bolp))
9672 (looking-at js-possibly-braceless-keyword-re)
9673 (save-match-data
9674 (not (js-end-of-do-while-loop-p)))))))
9675 (save-excursion
9676 (goto-char (match-beginning 0))
9677 (+ (current-indentation) js2-basic-offset))))))
9678
9679 (defun js2-indent-in-array-comp (parse-status)
9680 "Return non-nil if we think we're in an array comprehension.
9681 In particular, return the buffer position of the first `for' kwd."
9682 (let ((end (point)))
9683 (when (nth 1 parse-status)
9684 (save-excursion
9685 (goto-char (nth 1 parse-status))
9686 (when (looking-at "\\[")
9687 (forward-char 1)
9688 (js2-forward-sws)
9689 (if (looking-at "[[{]")
9690 (let (forward-sexp-function) ; use lisp version
9691 (forward-sexp) ; skip destructuring form
9692 (js2-forward-sws)
9693 (if (and (/= (char-after) ?,) ; regular array
9694 (looking-at "for"))
9695 (match-beginning 0)))
9696 ;; to skip arbitrary expressions we need the parser,
9697 ;; so we'll just guess at it.
9698 (if (re-search-forward "[^,]* \\(for\\) " end t)
9699 (match-beginning 1))))))))
9700
9701 (defun js2-array-comp-indentation (parse-status for-kwd)
9702 (if (js2-same-line for-kwd)
9703 ;; first continuation line
9704 (save-excursion
9705 (goto-char (nth 1 parse-status))
9706 (forward-char 1)
9707 (skip-chars-forward " \t")
9708 (current-column))
9709 (save-excursion
9710 (goto-char for-kwd)
9711 (current-column))))
9712
9713 (defun js-proper-indentation (parse-status)
9714 "Return the proper indentation for the current line."
9715 (save-excursion
9716 (back-to-indentation)
9717 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9718 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9719 (continued-expr-p (js-continued-expression-p))
9720 (bracket (nth 1 parse-status))
9721 beg)
9722 (cond
9723 ;; indent array comprehension continuation lines specially
9724 ((and bracket
9725 (not (js2-same-line bracket))
9726 (setq beg (js2-indent-in-array-comp parse-status))
9727 (>= (point) (save-excursion
9728 (goto-char beg)
9729 (point-at-bol)))) ; at or after first loop?
9730 (js2-array-comp-indentation parse-status beg))
9731
9732 (ctrl-stmt-indent)
9733
9734 (bracket
9735 (goto-char bracket)
9736 (cond
9737 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9738 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9739 (when (save-excursion (skip-chars-backward " \t)")
9740 (looking-at ")"))
9741 (backward-list))
9742 (if (nth 1 p)
9743 (progn (goto-char (1+ (nth 1 p)))
9744 (skip-chars-forward " \t"))
9745 (back-to-indentation))
9746 (cond (same-indent-p
9747 (current-column))
9748 (continued-expr-p
9749 (+ (current-column) (* 2 js2-basic-offset)))
9750 (t
9751 (+ (current-column) js2-basic-offset)))))
9752 (t
9753 (unless same-indent-p
9754 (forward-char)
9755 (skip-chars-forward " \t"))
9756 (current-column))))
9757
9758 (continued-expr-p js2-basic-offset)
9759 (t 0)))))
9760
9761 (defun js2-lineup-comment (parse-status)
9762 "Indent a multi-line block comment continuation line."
9763 (let* ((beg (nth 8 parse-status))
9764 (first-line (js2-same-line beg))
9765 (offset (save-excursion
9766 (goto-char beg)
9767 (if (looking-at "/\\*")
9768 (+ 1 (current-column))
9769 0))))
9770 (unless first-line
9771 (indent-line-to offset))))
9772
9773 (defun js2-backward-sws ()
9774 "Move backward through whitespace and comments."
9775 (interactive)
9776 (while (forward-comment -1)))
9777
9778 (defun js2-forward-sws ()
9779 "Move forward through whitespace and comments."
9780 (interactive)
9781 (while (forward-comment 1)))
9782
9783 (defsubst js2-current-indent (&optional pos)
9784 "Return column of indentation on current line.
9785 If POS is non-nil, go to that point and return indentation for that line."
9786 (save-excursion
9787 (if pos
9788 (goto-char pos))
9789 (back-to-indentation)
9790 (current-column)))
9791
9792 (defsubst js2-arglist-close ()
9793 "Return non-nil if we're on a line beginning with a close-paren/brace."
9794 (save-excursion
9795 (goto-char (point-at-bol))
9796 (js2-forward-sws)
9797 (looking-at "[])}]")))
9798
9799 (defsubst js2-indent-looks-like-label-p ()
9800 (goto-char (point-at-bol))
9801 (js2-forward-sws)
9802 (looking-at (concat js2-mode-identifier-re ":")))
9803
9804 (defun js2-indent-in-objlit-p (parse-status)
9805 "Return non-nil if this looks like an object-literal entry."
9806 (let ((start (nth 1 parse-status)))
9807 (and
9808 start
9809 (save-excursion
9810 (and (zerop (forward-line -1))
9811 (not (< (point) start)) ; crossed a {} boundary
9812 (js2-indent-looks-like-label-p)))
9813 (save-excursion
9814 (js2-indent-looks-like-label-p)))))
9815
9816 ;; if prev line looks like foobar({ then we're passing an object
9817 ;; literal to a function call, and people pretty much always want to
9818 ;; de-dent back to the previous line, so move the 'basic-offset'
9819 ;; position to the front.
9820 (defsubst js2-indent-objlit-arg-p (parse-status)
9821 (save-excursion
9822 (back-to-indentation)
9823 (js2-backward-sws)
9824 (and (eq (1- (point)) (nth 1 parse-status))
9825 (eq (char-before) ?{)
9826 (progn
9827 (forward-char -1)
9828 (skip-chars-backward " \t")
9829 (eq (char-before) ?\()))))
9830
9831 (defsubst js2-indent-case-block-p ()
9832 (save-excursion
9833 (back-to-indentation)
9834 (js2-backward-sws)
9835 (goto-char (point-at-bol))
9836 (skip-chars-forward " \t")
9837 (looking-at-p "case\\s-.+:")))
9838
9839 (defsubst js2-syntax-bol ()
9840 "Return the point at the first non-whitespace char on the line.
9841 Returns `point-at-bol' if the line is empty."
9842 (save-excursion
9843 (beginning-of-line)
9844 (skip-chars-forward " \t")
9845 (point)))
9846
9847 (defun js2-bounce-indent (normal-col parse-status)
9848 "Cycle among alternate computed indentation positions.
9849 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9850 of the buffer to the current point. NORMAL-COL is the indentation
9851 column computed by the heuristic guesser based on current paren,
9852 bracket, brace and statement nesting."
9853 (let ((cur-indent (js2-current-indent))
9854 (old-buffer-undo-list buffer-undo-list)
9855 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9856 (current-line (save-excursion
9857 (forward-line 0) ; move to bol
9858 (1+ (count-lines (point-min) (point)))))
9859 positions
9860 pos
9861 anchor
9862 arglist-cont
9863 same-indent
9864 prev-line-col
9865 basic-offset
9866 computed-pos)
9867 ;; temporarily don't record undo info, if user requested this
9868 (if js2-mode-indent-inhibit-undo
9869 (setq buffer-undo-list t))
9870 (unwind-protect
9871 (progn
9872 ;; first likely point: indent from beginning of previous code line
9873 (push (setq basic-offset
9874 (+ (save-excursion
9875 (back-to-indentation)
9876 (js2-backward-sws)
9877 (back-to-indentation)
9878 (setq prev-line-col (current-column)))
9879 js2-basic-offset))
9880 positions)
9881
9882 ;; (first + epsilon) likely point: indent 2x from beginning of
9883 ;; previous code line. Some companies like this approach. Ahem.
9884 ;; Seriously, though -- 4-space indent for expression continuation
9885 ;; lines isn't a bad idea. We should eventually implement it
9886 ;; that way.
9887 (push (setq basic-offset
9888 (+ (save-excursion
9889 (back-to-indentation)
9890 (js2-backward-sws)
9891 (back-to-indentation)
9892 (setq prev-line-col (current-column)))
9893 (* 2 js2-basic-offset)))
9894 positions)
9895
9896 ;; second likely point: indent from assign-expr RHS. This
9897 ;; is just a crude guess based on finding " = " on the previous
9898 ;; line containing actual code.
9899 (setq pos (save-excursion
9900 (forward-line -1)
9901 (goto-char (point-at-bol))
9902 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9903 (point-at-eol) t)
9904 (goto-char (match-end 1))
9905 (skip-chars-forward " \t\r\n")
9906 (current-column))))
9907 (when pos
9908 (incf pos js2-basic-offset)
9909 (unless (member pos positions)
9910 (push pos positions)))
9911
9912 ;; third likely point: same indent as previous line of code.
9913 ;; Make it the first likely point if we're not on an
9914 ;; arglist-close line and previous line ends in a comma, or
9915 ;; both this line and prev line look like object-literal
9916 ;; elements.
9917 (setq pos (save-excursion
9918 (goto-char (point-at-bol))
9919 (js2-backward-sws)
9920 (back-to-indentation)
9921 (prog1
9922 (current-column)
9923 ;; while we're here, look for trailing comma
9924 (if (save-excursion
9925 (goto-char (point-at-eol))
9926 (js2-backward-sws)
9927 (eq (char-before) ?,))
9928 (setq arglist-cont (1- (point)))))))
9929 (when pos
9930 (if (and (or arglist-cont
9931 (js2-indent-in-objlit-p parse-status))
9932 (not (js2-arglist-close)))
9933 (setq same-indent pos))
9934 (unless (member pos positions)
9935 (push pos positions)))
9936
9937 ;; fourth likely point: first preceding code with less indentation
9938 ;; than the immediately preceding code line.
9939 (setq pos (save-excursion
9940 (js2-backward-sws)
9941 (back-to-indentation)
9942 (setq anchor (current-column))
9943 (while (and (zerop (forward-line -1))
9944 (>= (progn
9945 (back-to-indentation)
9946 (current-column))
9947 anchor)))
9948 (setq pos (current-column))))
9949 (unless (member pos positions)
9950 (push pos positions))
9951
9952 ;; put nesting-heuristic position first in list, sort rest
9953 (setq positions (nreverse (sort positions '<)))
9954 (setq positions (cons normal-col (delete normal-col positions)))
9955
9956 ;; comma-list continuation lines: prev line indent takes precedence
9957 (if same-indent
9958 (setq positions
9959 (cons same-indent
9960 (sort (delete same-indent positions) '<))))
9961
9962 ;; common special cases where we want to indent in from previous line
9963 (if (or (js2-indent-case-block-p)
9964 (js2-indent-objlit-arg-p parse-status))
9965 (setq positions
9966 (cons basic-offset
9967 (delete basic-offset positions))))
9968
9969 ;; record whether we're already sitting on one of the alternatives
9970 (setq pos (member cur-indent positions))
9971 (cond
9972 ;; case 0: we're one one of the alternatives and this is the
9973 ;; first time they've pressed TAB on this line (best-guess).
9974 ((and js2-mode-indent-ignore-first-tab
9975 pos
9976 ;; first time pressing TAB on this line?
9977 (not (eq js2-mode-last-indented-line current-line)))
9978 ;; do nothing
9979 (setq computed-pos nil))
9980 ;; case 1: only one computed position => use it
9981 ((null (cdr positions))
9982 (setq computed-pos 0))
9983 ;; case 2: not on any of the computed spots => use main spot
9984 ((not pos)
9985 (setq computed-pos 0))
9986 ;; case 3: on last position: cycle to first position
9987 ((null (cdr pos))
9988 (setq computed-pos 0))
9989 ;; case 4: on intermediate position: cycle to next position
9990 (t
9991 (setq computed-pos (js2-position (second pos) positions))))
9992
9993 ;; see if any hooks want to indent; otherwise we do it
9994 (loop with result = nil
9995 for hook in js2-indent-hook
9996 while (null result)
9997 do
9998 (setq result (funcall hook positions computed-pos))
9999 finally do
10000 (unless (or result (null computed-pos))
10001 (indent-line-to (nth computed-pos positions)))))
10002
10003 ;; finally
10004 (if js2-mode-indent-inhibit-undo
10005 (setq buffer-undo-list old-buffer-undo-list))
10006 ;; see commentary for `js2-mode-last-indented-line'
10007 (setq js2-mode-last-indented-line current-line))))
10008
10009 (defsubst js2-1-line-comment-continuation-p ()
10010 "Return t if we're in a 1-line comment continuation.
10011 If so, we don't ever want to use bounce-indent."
10012 (save-excursion
10013 (and (progn
10014 (forward-line 0)
10015 (looking-at "\\s-*//"))
10016 (progn
10017 (forward-line -1)
10018 (forward-line 0)
10019 (when (looking-at "\\s-*$")
10020 (js2-backward-sws)
10021 (forward-line 0))
10022 (looking-at "\\s-*//")))))
10023
10024 (defun js2-indent-line ()
10025 "Indent the current line as JavaScript source text."
10026 (interactive)
10027 (let (parse-status
10028 current-indent
10029 offset
10030 indent-col
10031 moved
10032 ;; don't whine about errors/warnings when we're indenting.
10033 ;; This has to be set before calling parse-partial-sexp below.
10034 (inhibit-point-motion-hooks t))
10035 (setq parse-status (save-excursion
10036 (syntax-ppss (point-at-bol)))
10037 offset (- (point) (save-excursion
10038 (back-to-indentation)
10039 (setq current-indent (current-column))
10040 (point))))
10041 (js2-with-underscore-as-word-syntax
10042 (if (nth 4 parse-status)
10043 (js2-lineup-comment parse-status)
10044 (setq indent-col (js-proper-indentation parse-status))
10045 ;; see comments below about js2-mode-last-indented-line
10046 (when
10047 (cond
10048 ;; bounce-indenting is disabled during electric-key indent.
10049 ;; It doesn't work well on first line of buffer.
10050 ((and js2-bounce-indent-p
10051 (not (js2-same-line (point-min)))
10052 (not (js2-1-line-comment-continuation-p)))
10053 (js2-bounce-indent indent-col parse-status)
10054 (setq moved t))
10055 ;; just indent to the guesser's likely spot
10056 ((/= current-indent indent-col)
10057 (indent-line-to indent-col)
10058 (setq moved t)))
10059 (when (and moved (plusp offset))
10060 (forward-char offset)))))))
10061
10062 (defun js2-indent-region (start end)
10063 "Indent the region, but don't use bounce indenting."
10064 (let ((js2-bounce-indent-p nil)
10065 (indent-region-function nil))
10066 (indent-region start end nil))) ; nil for byte-compiler
10067
10068 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
10069
10070 ;;;###autoload
10071 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10072 ;; FIXME: Should derive from js-mode.
10073 "Major mode for editing JavaScript code."
10074 (setq comment-start "//" ; used by comment-region; don't change it
10075 comment-end "")
10076 (set (make-local-variable 'max-lisp-eval-depth)
10077 (max max-lisp-eval-depth 3000))
10078 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10079 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10080
10081 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10082 ;; on most platforms other than the one I originally wrote it on. So it's
10083 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10084 ;; with our binding of the RET key inside comments: short lines stay short.
10085 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10086 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10087
10088 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10089 (set (make-local-variable 'next-error-function) #'js2-next-error)
10090 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10091 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10092 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10093 ;; for characters inside regexp literals.
10094 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10095 ;; this is necessary to make `show-paren-function' work properly
10096 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10097 ;; needed for M-x rgrep, among other things
10098 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10099
10100 (set (make-local-variable 'electric-indent-chars)
10101 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10102 electric-indent-chars))
10103 (set (make-local-variable 'electric-layout-rules)
10104 '((?\; . after) (?\{ . after) (?\} . before)))
10105
10106 ;; some variables needed by cc-engine for paragraph-fill, etc.
10107 (setq c-buffer-is-cc-mode t
10108 c-comment-prefix-regexp js2-comment-prefix-regexp
10109 c-comment-start-regexp "/[*/]\\|\\s|"
10110 c-paragraph-start js2-paragraph-start
10111 c-paragraph-separate "$"
10112 comment-start-skip js2-comment-start-skip
10113 c-syntactic-ws-start js2-syntactic-ws-start
10114 c-syntactic-ws-end js2-syntactic-ws-end
10115 c-syntactic-eol js2-syntactic-eol)
10116
10117 (setq js2-default-externs
10118 (append js2-ecma-262-externs
10119 (if js2-include-browser-externs
10120 js2-browser-externs)
10121 (if js2-include-gears-externs
10122 js2-gears-externs)
10123 (if js2-include-rhino-externs
10124 js2-rhino-externs)))
10125
10126 ;; We do our own syntax highlighting based on the parse tree.
10127 ;; However, we want minor modes that add keywords to highlight properly
10128 ;; (examples: doxymacs, column-marker). We do this by not letting
10129 ;; font-lock unfontify anything, and telling it to fontify after we
10130 ;; re-parse and re-highlight the buffer. (We currently don't do any
10131 ;; work with regions other than the whole buffer.)
10132 ;; FIXME: This is asking for trouble.
10133 (dolist (var '(font-lock-unfontify-buffer-function
10134 font-lock-unfontify-region-function))
10135 (set (make-local-variable var) (lambda (&rest args) t)))
10136
10137 ;; Don't let font-lock do syntactic (string/comment) fontification.
10138 ;; FIXME: Better tell font-lock to not do syntactic fontification.
10139 (set (make-local-variable #'font-lock-syntactic-face-function)
10140 (lambda (state) nil))
10141
10142 ;; Experiment: make reparse-delay longer for longer files.
10143 (if (plusp js2-dynamic-idle-timer-adjust)
10144 (setq js2-idle-timer-delay
10145 (* js2-idle-timer-delay
10146 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10147
10148 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10149 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10150 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10151 (imenu-add-to-menubar (concat "IM-" mode-name))
10152 (add-to-invisibility-spec '(js2-outline . t))
10153 (set (make-local-variable 'line-move-ignore-invisible) t)
10154 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10155 (setq js2-mode-functions-hidden nil
10156 js2-mode-comments-hidden nil
10157 js2-mode-buffer-dirty-p t
10158 js2-mode-parsing nil)
10159 (js2-reparse))
10160
10161 (defun js2-mode-exit ()
10162 "Exit `js2-mode' and clean up."
10163 (interactive)
10164 (when js2-mode-node-overlay
10165 (delete-overlay js2-mode-node-overlay)
10166 (setq js2-mode-node-overlay nil))
10167 (js2-remove-overlays)
10168 (setq js2-mode-ast nil)
10169 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10170 (remove-from-invisibility-spec '(js2-outline . t))
10171 (js2-mode-show-all)
10172 (with-silent-modifications
10173 (js2-clear-face (point-min) (point-max))))
10174
10175 (defun js2-before-save ()
10176 "Clean up whitespace before saving file.
10177 You can disable this by customizing `js2-cleanup-whitespace'."
10178 (when js2-cleanup-whitespace
10179 (let ((col (current-column)))
10180 (delete-trailing-whitespace)
10181 ;; don't change trailing whitespace on current line
10182 (unless (eq (current-column) col)
10183 (indent-to col)))))
10184
10185 (defsubst js2-mode-reset-timer ()
10186 "Cancel any existing parse timer and schedule a new one."
10187 (if js2-mode-parse-timer
10188 (cancel-timer js2-mode-parse-timer))
10189 (setq js2-mode-parsing nil)
10190 (setq js2-mode-parse-timer
10191 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10192
10193 (defun js2-mode-edit (beg end len)
10194 "Schedule a new parse after buffer is edited.
10195 Buffer edit spans from BEG to END and is of length LEN.
10196 Also clears the `js2-magic' bit on autoinserted parens/brackets
10197 if the edit occurred on a line different from the magic paren."
10198 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10199 (line (if magic-pos (line-number-at-pos magic-pos))))
10200 (and line
10201 (or (/= (line-number-at-pos beg) line)
10202 (and (> 0 len)
10203 (/= (line-number-at-pos end) line)))
10204 (js2-mode-mundanify-parens)))
10205 (setq js2-mode-buffer-dirty-p t)
10206 (js2-mode-hide-overlay)
10207 (js2-mode-reset-timer))
10208
10209 (defun js2-mode-run-font-lock ()
10210 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10211 This is intended to allow modes that install their own font-lock keywords
10212 to work with `js2-mode'. In practice it never seems to work for long.
10213 Hopefully the Emacs maintainers can help figure out a way to make it work."
10214 ;; FIXME: Throw away this function.
10215 ;; <note from="Emacs maintainer">
10216 ;; Just writing "hopefully the Emacs maintainers can help" in some file
10217 ;; somewhere on the Internet is not enough because we don't
10218 ;; have a web-crawler looking for such things. Instead, it's best to ask
10219 ;; explicitly on gnu.emacs.help or emacs-devel@gnu.org or something.
10220 ;; </note>
10221 ;; As for the answer: set font-lock-defaults in js2-mode once and for all.
10222 ;; It should have a value like '(js2-font-lock-keywords t) and
10223 ;; js2-font-lock-keywords should have a value like '(js2-fontify-region).
10224 (when (and (boundp 'font-lock-keywords)
10225 font-lock-keywords
10226 (boundp 'font-lock-mode)
10227 font-lock-mode)
10228 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10229 ;; play nicely with js2-mode. They go out of their way to fail to
10230 ;; provide any option for saying "look, fontify the farging buffer
10231 ;; with just the keywords already". Argh.
10232 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10233 (let (font-lock-verbose)
10234 (font-lock-default-fontify-buffer))))
10235
10236 (defun js2-reparse (&optional force)
10237 "Re-parse current buffer after user finishes some data entry.
10238 If we get any user input while parsing, including cursor motion,
10239 we discard the parse and reschedule it. If FORCE is nil, then the
10240 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10241 (let (time
10242 interrupted-p
10243 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10244 (unless js2-mode-parsing
10245 (setq js2-mode-parsing t)
10246 (unwind-protect
10247 (when (or js2-mode-buffer-dirty-p force)
10248 (js2-remove-overlays)
10249 (with-silent-modifications
10250 (remove-text-properties (point-min) (point-max) '(syntax-table))
10251 (setq js2-mode-buffer-dirty-p nil
10252 js2-mode-fontifications nil
10253 js2-mode-deferred-properties nil
10254 js2-additional-externs nil)
10255 (if js2-mode-verbose-parse-p
10256 (message "parsing..."))
10257 (setq time
10258 (js2-time
10259 (setq interrupted-p
10260 (catch 'interrupted
10261 (setq js2-mode-ast (js2-parse))
10262 (js2-mode-fontify-regions)
10263 (js2-mode-remove-suppressed-warnings)
10264 (js2-mode-show-warnings)
10265 (js2-mode-show-errors)
10266 (js2-mode-run-font-lock) ; note: doesn't work
10267 (js2-mode-highlight-magic-parens)
10268 (if (>= js2-highlight-level 1)
10269 (js2-highlight-jsdoc js2-mode-ast))
10270 nil))))
10271 (if interrupted-p
10272 (progn
10273 ;; unfinished parse => try again
10274 (setq js2-mode-buffer-dirty-p t)
10275 (js2-mode-reset-timer))
10276 (if js2-mode-verbose-parse-p
10277 (message "Parse time: %s" time)))))
10278 (setq js2-mode-parsing nil)
10279 (unless interrupted-p
10280 (setq js2-mode-parse-timer nil))))))
10281
10282 (defun js2-mode-show-node ()
10283 "Debugging aid: highlight selected AST node on mouse click."
10284 (interactive)
10285 (let ((node (js2-node-at-point))
10286 beg
10287 end)
10288 (when js2-mode-show-overlay
10289 (if (null node)
10290 (message "No node found at location %s" (point))
10291 (setq beg (js2-node-abs-pos node)
10292 end (+ beg (js2-node-len node)))
10293 (if js2-mode-node-overlay
10294 (move-overlay js2-mode-node-overlay beg end)
10295 (setq js2-mode-node-overlay (make-overlay beg end))
10296 (overlay-put js2-mode-node-overlay 'face 'highlight))
10297 (with-silent-modifications
10298 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10299 (message "%s, parent: %s"
10300 (js2-node-short-name node)
10301 (if (js2-node-parent node)
10302 (js2-node-short-name (js2-node-parent node))
10303 "nil"))))))
10304
10305 (defun js2-mode-hide-overlay (&optional p1 p2)
10306 "Remove the debugging overlay when the point moves.
10307 P1 and P2 are the old and new values of point, respectively."
10308 (when js2-mode-node-overlay
10309 (let ((beg (overlay-start js2-mode-node-overlay))
10310 (end (overlay-end js2-mode-node-overlay)))
10311 ;; Sometimes we're called spuriously.
10312 (unless (and p2
10313 (>= p2 beg)
10314 (<= p2 end))
10315 (with-silent-modifications
10316 (remove-text-properties beg end '(point-left nil)))
10317 (delete-overlay js2-mode-node-overlay)
10318 (setq js2-mode-node-overlay nil)))))
10319
10320 (defun js2-mode-reset ()
10321 "Debugging helper: reset everything."
10322 (interactive)
10323 (js2-mode-exit)
10324 (js2-mode))
10325
10326 (defsubst js2-mode-show-warn-or-err (e face)
10327 "Highlight a warning or error E with FACE.
10328 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10329 (let* ((key (first e))
10330 (beg (second e))
10331 (end (+ beg (third e)))
10332 ;; Don't inadvertently go out of bounds.
10333 (beg (max (point-min) (min beg (point-max))))
10334 (end (max (point-min) (min end (point-max))))
10335 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10336 (ovl (make-overlay beg end)))
10337 (overlay-put ovl 'face face)
10338 (overlay-put ovl 'js2-error t)
10339 (put-text-property beg end 'help-echo (js2-get-msg key))
10340 (put-text-property beg end 'point-entered #'js2-echo-error)))
10341
10342 (defun js2-remove-overlays ()
10343 "Remove overlays from buffer that have a `js2-error' property."
10344 (let ((beg (point-min))
10345 (end (point-max)))
10346 (save-excursion
10347 (dolist (o (overlays-in beg end))
10348 (when (overlay-get o 'js2-error)
10349 (delete-overlay o))))))
10350
10351 (defun js2-error-at-point (&optional pos)
10352 "Return non-nil if there's an error overlay at POS.
10353 Defaults to point."
10354 (loop with pos = (or pos (point))
10355 for o in (overlays-at pos)
10356 thereis (overlay-get o 'js2-error)))
10357
10358 (defun js2-mode-fontify-regions ()
10359 "Apply fontifications recorded during parsing."
10360 ;; We defer clearing faces as long as possible to eliminate flashing.
10361 (js2-clear-face (point-min) (point-max))
10362 ;; have to reverse the recorded fontifications so that errors and
10363 ;; warnings overwrite the normal fontifications
10364 (dolist (f (nreverse js2-mode-fontifications))
10365 (put-text-property (first f) (second f) 'face (third f)))
10366 (setq js2-mode-fontifications nil)
10367 (dolist (p js2-mode-deferred-properties)
10368 (apply #'put-text-property p))
10369 (setq js2-mode-deferred-properties nil))
10370
10371 (defun js2-mode-show-errors ()
10372 "Highlight syntax errors."
10373 (when js2-mode-show-parse-errors
10374 (dolist (e (js2-ast-root-errors js2-mode-ast))
10375 (js2-mode-show-warn-or-err e 'js2-error))))
10376
10377 (defun js2-mode-remove-suppressed-warnings ()
10378 "Take suppressed warnings out of the AST warnings list.
10379 This ensures that the counts and `next-error' are correct."
10380 (setf (js2-ast-root-warnings js2-mode-ast)
10381 (js2-delete-if
10382 (lambda (e)
10383 (let ((key (caar e)))
10384 (or
10385 (and (not js2-strict-trailing-comma-warning)
10386 (string-match "trailing\\.comma" key))
10387 (and (not js2-strict-cond-assign-warning)
10388 (string= key "msg.equal.as.assign"))
10389 (and js2-missing-semi-one-line-override
10390 (string= key "msg.missing.semi")
10391 (let* ((beg (second e))
10392 (node (js2-node-at-point beg))
10393 (fn (js2-mode-find-parent-fn node))
10394 (body (and fn (js2-function-node-body fn)))
10395 (lc (and body (js2-node-abs-pos body)))
10396 (rc (and lc (+ lc (js2-node-len body)))))
10397 (and fn
10398 (or (null body)
10399 (save-excursion
10400 (goto-char beg)
10401 (and (js2-same-line lc)
10402 (js2-same-line rc))))))))))
10403 (js2-ast-root-warnings js2-mode-ast))))
10404
10405 (defun js2-mode-show-warnings ()
10406 "Highlight strict-mode warnings."
10407 (when js2-mode-show-strict-warnings
10408 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10409 (js2-mode-show-warn-or-err e 'js2-warning))))
10410
10411 (defun js2-echo-error (old-point new-point)
10412 "Called by point-motion hooks."
10413 (let ((msg (get-text-property new-point 'help-echo)))
10414 (if msg
10415 (message msg))))
10416
10417 (defalias #'js2-echo-help #'js2-echo-error)
10418
10419 (defun js2-line-break (&optional soft)
10420 "Break line at point."
10421 (let ((parse-status (syntax-ppss)))
10422 (cond
10423 ;; Check if we're inside a string.
10424 ((nth 3 parse-status)
10425 (js2-mode-split-string parse-status))
10426 ;; Check if inside a block comment.
10427 ((nth 4 parse-status)
10428 (js2-mode-extend-comment))
10429 (t
10430 (newline)))))
10431
10432 (defun js2-mode-split-string (parse-status)
10433 "Turn a newline in mid-string into a string concatenation.
10434 PARSE-STATUS is as documented in `parse-partial-sexp'."
10435 (let* ((col (current-column))
10436 (quote-char (nth 3 parse-status))
10437 (quote-string (string quote-char))
10438 (string-beg (nth 8 parse-status))
10439 (indent (or
10440 (save-excursion
10441 (back-to-indentation)
10442 (if (looking-at "\\+")
10443 (current-column)))
10444 (save-excursion
10445 (goto-char string-beg)
10446 (if (looking-back "\\+\\s-+")
10447 (goto-char (match-beginning 0)))
10448 (current-column)))))
10449 (insert quote-char "\n")
10450 (indent-to indent)
10451 (insert "+ " quote-string)
10452 (when (eolp)
10453 (insert quote-string)
10454 (backward-char 1))))
10455
10456 (defun js2-mode-extend-comment ()
10457 "When inside a comment block, add comment prefix."
10458 (let (star single col first-line needs-close)
10459 (save-excursion
10460 (back-to-indentation)
10461 (cond
10462 ((looking-at "\\*[^/]")
10463 (setq star t
10464 col (current-column)))
10465 ((looking-at "/\\*")
10466 (setq star t
10467 first-line t
10468 col (1+ (current-column))))
10469 ((looking-at "//")
10470 (setq single t
10471 col (current-column)))))
10472 ;; Heuristic for whether we need to close the comment:
10473 ;; if we've got a parse error here, assume it's an unterminated
10474 ;; comment.
10475 (setq needs-close
10476 (or
10477 (eq (get-text-property (1- (point)) 'point-entered)
10478 'js2-echo-error)
10479 ;; The heuristic above doesn't work well when we're
10480 ;; creating a comment and there's another one downstream,
10481 ;; as our parser thinks this one ends at the end of the
10482 ;; next one. (You can have a /* inside a js block comment.)
10483 ;; So just close it if the next non-ws char isn't a *.
10484 (and first-line
10485 (eolp)
10486 (save-excursion
10487 (skip-chars-forward " \t\r\n")
10488 (not (eq (char-after) ?*))))))
10489 (insert "\n")
10490 (cond
10491 (star
10492 (indent-to col)
10493 (insert "* ")
10494 (if (and first-line needs-close)
10495 (save-excursion
10496 (insert "\n")
10497 (indent-to col)
10498 (insert "*/"))))
10499 (single
10500 (when (save-excursion
10501 (and (zerop (forward-line 1))
10502 (looking-at "\\s-*//")))
10503 (indent-to col)
10504 (insert "// "))))))
10505
10506 (defun js2-beginning-of-line ()
10507 "Toggle point between bol and first non-whitespace char in line.
10508 Also moves past comment delimiters when inside comments."
10509 (interactive)
10510 (let (node beg)
10511 (cond
10512 ((bolp)
10513 (back-to-indentation))
10514 ((looking-at "//")
10515 (skip-chars-forward "/ \t"))
10516 ((and (eq (char-after) ?*)
10517 (setq node (js2-comment-at-point))
10518 (memq (js2-comment-node-format node) '(jsdoc block))
10519 (save-excursion
10520 (skip-chars-backward " \t")
10521 (bolp)))
10522 (skip-chars-forward "\* \t"))
10523 (t
10524 (goto-char (point-at-bol))))))
10525
10526 (defun js2-end-of-line ()
10527 "Toggle point between eol and last non-whitespace char in line."
10528 (interactive)
10529 (if (eolp)
10530 (skip-chars-backward " \t")
10531 (goto-char (point-at-eol))))
10532
10533 (defsubst js2-mode-inside-string ()
10534 "Return non-nil if inside a string.
10535 Actually returns the quote character that begins the string."
10536 (let ((parse-state (syntax-ppss)))
10537 (nth 3 parse-state)))
10538
10539 (defsubst js2-mode-inside-comment-or-string ()
10540 "Return non-nil if inside a comment or string."
10541 (or
10542 (let ((comment-start
10543 (save-excursion
10544 (goto-char (point-at-bol))
10545 (if (re-search-forward "//" (point-at-eol) t)
10546 (match-beginning 0)))))
10547 (and comment-start
10548 (<= comment-start (point))))
10549 (let ((parse-state (syntax-ppss)))
10550 (or (nth 3 parse-state)
10551 (nth 4 parse-state)))))
10552
10553 (defsubst js2-make-magic-delimiter (delim &optional pos)
10554 "Add `js2-magic' and `js2-magic-paren' to DELIM, a string.
10555 Sets value of `js2-magic' text property to line number at POS."
10556 (propertize delim
10557 'js2-magic (line-number-at-pos pos)
10558 'face 'js2-magic-paren))
10559
10560 (defun js2-mode-match-delimiter (open close)
10561 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10562 The rule we use, which as far as we can tell is how Eclipse works,
10563 is that we insert the match if we're not in a comment or string,
10564 and the next non-whitespace character is either punctuation or
10565 occurs on another line."
10566 (insert open)
10567 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10568 (not (js2-mode-inside-comment-or-string)))
10569 (save-excursion
10570 (insert (js2-make-magic-delimiter close)))
10571 (when js2-auto-indent-p
10572 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10573 (js2-indent-line)))))
10574
10575 (defun js2-mode-match-bracket ()
10576 "Insert matching bracket."
10577 (interactive)
10578 (js2-mode-match-delimiter "[" "]"))
10579
10580 (defun js2-mode-match-paren ()
10581 "Insert matching paren unless already inserted."
10582 (interactive)
10583 (js2-mode-match-delimiter "(" ")"))
10584
10585 (defun js2-mode-match-curly (arg)
10586 "Insert matching curly-brace.
10587 With prefix arg, no formatting or indentation will occur -- the close-brace
10588 is simply inserted directly at point."
10589 (interactive "p")
10590 (let (try-pos)
10591 (cond
10592 (current-prefix-arg
10593 (js2-mode-match-delimiter "{" "}"))
10594 ((and js2-auto-insert-catch-block
10595 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10596 (point-at-bol))
10597 (match-beginning 1))))
10598 (js2-insert-catch-skel try-pos))
10599 (t
10600 ;; Otherwise try to do something smarter.
10601 (insert "{")
10602 (unless (or (not (looking-at "\\s-*$"))
10603 (save-excursion
10604 (skip-chars-forward " \t\r\n")
10605 (and (looking-at "}")
10606 (js2-error-at-point)))
10607 (js2-mode-inside-comment-or-string))
10608 (undo-boundary)
10609 ;; absolutely mystifying bug: when inserting the next "\n",
10610 ;; the buffer-undo-list is given two new entries: the inserted range,
10611 ;; and the incorrect position of the point. It's recorded incorrectly
10612 ;; as being before the opening "{", not after it. But it's recorded
10613 ;; as the correct value if you're debugging `js2-mode-match-curly'
10614 ;; in edebug. I have no idea why it's doing this, but incrementing
10615 ;; the inserted position fixes the problem, so that the undo takes us
10616 ;; back to just after the user-inserted "{".
10617 (insert "\n")
10618 (ignore-errors
10619 (incf (cadr buffer-undo-list)))
10620 (js2-indent-line)
10621 (save-excursion
10622 (insert "\n}")
10623 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10624 (js2-indent-line))))))))
10625
10626 (defun js2-insert-catch-skel (try-pos)
10627 "Complete a try/catch block after inserting a { following a try keyword.
10628 Rationale is that a try always needs a catch or a finally, and the catch is
10629 the more likely of the two.
10630
10631 TRY-POS is the buffer position of the try keyword. The open-curly should
10632 already have been inserted."
10633 (insert "{")
10634 (let ((try-col (save-excursion
10635 (goto-char try-pos)
10636 (current-column))))
10637 (insert "\n")
10638 (undo-boundary)
10639 (js2-indent-line) ;; indent the blank line where cursor will end up
10640 (save-excursion
10641 (insert "\n")
10642 (indent-to try-col)
10643 (insert "} catch (x) {\n\n")
10644 (indent-to try-col)
10645 (insert "}"))))
10646
10647 (defun js2-mode-highlight-magic-parens ()
10648 "Re-highlight magic parens after parsing nukes the 'face prop."
10649 (let ((beg (point-min))
10650 end)
10651 (while (setq beg (next-single-property-change beg 'js2-magic))
10652 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10653 (if (get-text-property beg 'js2-magic)
10654 (with-silent-modifications
10655 (put-text-property beg (or end (1+ beg))
10656 'face 'js2-magic-paren))))))
10657
10658 (defun js2-mode-mundanify-parens ()
10659 "Clear all magic parens and brackets."
10660 (let ((beg (point-min))
10661 end)
10662 (while (setq beg (next-single-property-change beg 'js2-magic))
10663 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10664 (remove-text-properties beg (or end (1+ beg))
10665 '(js2-magic face)))))
10666
10667 (defsubst js2-match-quote (quote-string)
10668 (let ((start-quote (js2-mode-inside-string)))
10669 (cond
10670 ;; inside a comment - don't do quote-matching, since we can't
10671 ;; reliably figure out if we're in a string inside the comment
10672 ((js2-comment-at-point)
10673 (insert quote-string))
10674 ((not start-quote)
10675 ;; not in string => insert matched quotes
10676 (insert quote-string)
10677 ;; exception: if we're just before a word, don't double it.
10678 (unless (looking-at "[^ \t\r\n]")
10679 (save-excursion
10680 (insert quote-string))))
10681 ((looking-at quote-string)
10682 (if (looking-back "[^\\]\\\\")
10683 (insert quote-string)
10684 (forward-char 1)))
10685 ((and js2-mode-escape-quotes
10686 (save-excursion
10687 (re-search-forward quote-string (point-at-eol) t)))
10688 ;; inside terminated string, escape quote (unless already escaped)
10689 (insert (if (looking-back "[^\\]\\\\")
10690 quote-string
10691 (concat "\\" quote-string))))
10692 (t
10693 (insert quote-string))))) ; else terminate the string
10694
10695 (defun js2-mode-match-single-quote ()
10696 "Insert matching single-quote."
10697 (interactive)
10698 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10699 ;; don't match inside comments, since apostrophe is more common
10700 (if (nth 4 parse-status)
10701 (insert "'")
10702 (js2-match-quote "'"))))
10703
10704 (defun js2-mode-match-double-quote ()
10705 "Insert matching double-quote."
10706 (interactive)
10707 (js2-match-quote "\""))
10708
10709 ;; Eclipse works as follows:
10710 ;; * type an open-paren and it auto-inserts close-paren
10711 ;; - auto-inserted paren gets a green bracket
10712 ;; - green bracket means typing close-paren there will skip it
10713 ;; * if you insert any text on a different line, it turns off
10714 (defun js2-mode-magic-close-paren ()
10715 "Skip over close-paren rather than inserting, where appropriate."
10716 (interactive)
10717 (let* ((here (point))
10718 (parse-status (parse-partial-sexp (point-min) here))
10719 (open-pos (nth 1 parse-status))
10720 (close last-input-event)
10721 (open (cond
10722 ((eq close ?\))
10723 ?\()
10724 ((eq close ?\])
10725 ?\[)
10726 ((eq close ?})
10727 ?{)
10728 (t nil))))
10729 (if (and (eq (char-after) close)
10730 (eq open (char-after open-pos))
10731 (js2-same-line open-pos)
10732 (get-text-property here 'js2-magic))
10733 (progn
10734 (remove-text-properties here (1+ here) '(js2-magic face))
10735 (forward-char 1))
10736 (insert-char close 1))
10737 (blink-matching-open)))
10738
10739 (defun js2-mode-wait-for-parse (callback)
10740 "Invoke CALLBACK when parsing is finished.
10741 If parsing is already finished, calls CALLBACK immediately."
10742 (if (not js2-mode-buffer-dirty-p)
10743 (funcall callback)
10744 (push callback js2-mode-pending-parse-callbacks)
10745 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10746
10747 (defun js2-mode-parse-finished ()
10748 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10749 ;; We can't let errors propagate up, since it prevents the
10750 ;; `js2-parse' method from completing normally and returning
10751 ;; the ast, which makes things mysteriously not work right.
10752 (unwind-protect
10753 (dolist (cb js2-mode-pending-parse-callbacks)
10754 (condition-case err
10755 (funcall cb)
10756 (error (message "%s" err))))
10757 (setq js2-mode-pending-parse-callbacks nil)))
10758
10759 (defun js2-mode-flag-region (from to flag)
10760 "Hide or show text from FROM to TO, according to FLAG.
10761 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10762 Returns the created overlay if FLAG is non-nil."
10763 (remove-overlays from to 'invisible 'js2-outline)
10764 (when flag
10765 (let ((o (make-overlay from to)))
10766 (overlay-put o 'invisible 'js2-outline)
10767 (overlay-put o 'isearch-open-invisible
10768 'js2-isearch-open-invisible)
10769 o)))
10770
10771 ;; Function to be set as an outline-isearch-open-invisible' property
10772 ;; to the overlay that makes the outline invisible (see
10773 ;; `js2-mode-flag-region').
10774 (defun js2-isearch-open-invisible (overlay)
10775 ;; We rely on the fact that isearch places point on the matched text.
10776 (js2-mode-show-element))
10777
10778 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10779 "Return cons cell of bounds of folding overlay at POS.
10780 Returns nil if not found."
10781 (let ((overlays (overlays-at (or pos (point))))
10782 o)
10783 (while (and overlays
10784 (not o))
10785 (if (overlay-get (car overlays) 'invisible)
10786 (setq o (car overlays))
10787 (setq overlays (cdr overlays))))
10788 (if o
10789 (cons (overlay-start o) (overlay-end o)))))
10790
10791 (defun js2-mode-function-at-point (&optional pos)
10792 "Return the innermost function node enclosing current point.
10793 Returns nil if point is not in a function."
10794 (let ((node (js2-node-at-point pos)))
10795 (while (and node (not (js2-function-node-p node)))
10796 (setq node (js2-node-parent node)))
10797 (if (js2-function-node-p node)
10798 node)))
10799
10800 (defun js2-mode-toggle-element ()
10801 "Hide or show the foldable element at the point."
10802 (interactive)
10803 (let (comment fn pos)
10804 (save-excursion
10805 (cond
10806 ;; /* ... */ comment?
10807 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10808 (if (js2-mode-invisible-overlay-bounds
10809 (setq pos (+ 3 (js2-node-abs-pos comment))))
10810 (progn
10811 (goto-char pos)
10812 (js2-mode-show-element))
10813 (js2-mode-hide-element)))
10814 ;; //-comment?
10815 ((save-excursion
10816 (back-to-indentation)
10817 (looking-at js2-mode-//-comment-re))
10818 (js2-mode-toggle-//-comment))
10819 ;; function?
10820 ((setq fn (js2-mode-function-at-point))
10821 (setq pos (and (js2-function-node-body fn)
10822 (js2-node-abs-pos (js2-function-node-body fn))))
10823 (goto-char (1+ pos))
10824 (if (js2-mode-invisible-overlay-bounds)
10825 (js2-mode-show-element)
10826 (js2-mode-hide-element)))
10827 (t
10828 (message "Nothing at point to hide or show"))))))
10829
10830 (defun js2-mode-hide-element ()
10831 "Fold/hide contents of a block, showing ellipses.
10832 Show the hidden text with \\[js2-mode-show-element]."
10833 (interactive)
10834 (if js2-mode-buffer-dirty-p
10835 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10836 (let (node body beg end)
10837 (cond
10838 ((js2-mode-invisible-overlay-bounds)
10839 (message "already hidden"))
10840 (t
10841 (setq node (js2-node-at-point))
10842 (cond
10843 ((js2-block-comment-p node)
10844 (js2-mode-hide-comment node))
10845 (t
10846 (while (and node (not (js2-function-node-p node)))
10847 (setq node (js2-node-parent node)))
10848 (if (and node
10849 (setq body (js2-function-node-body node)))
10850 (progn
10851 (setq beg (js2-node-abs-pos body)
10852 end (+ beg (js2-node-len body)))
10853 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10854 (message "No collapsable element found at point"))))))))
10855
10856 (defun js2-mode-show-element ()
10857 "Show the hidden element at current point."
10858 (interactive)
10859 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10860 (if bounds
10861 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10862 (message "Nothing to un-hide"))))
10863
10864 (defun js2-mode-show-all ()
10865 "Show all of the text in the buffer."
10866 (interactive)
10867 (js2-mode-flag-region (point-min) (point-max) nil))
10868
10869 (defun js2-mode-toggle-hide-functions ()
10870 (interactive)
10871 (if js2-mode-functions-hidden
10872 (js2-mode-show-functions)
10873 (js2-mode-hide-functions)))
10874
10875 (defun js2-mode-hide-functions ()
10876 "Hides all non-nested function bodies in the buffer.
10877 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10878 to open an individual entry."
10879 (interactive)
10880 (if js2-mode-buffer-dirty-p
10881 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10882 (if (null js2-mode-ast)
10883 (message "Oops - parsing failed")
10884 (setq js2-mode-functions-hidden t)
10885 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10886
10887 (defun js2-mode-function-hider (n endp)
10888 (when (not endp)
10889 (let ((tt (js2-node-type n))
10890 body beg end)
10891 (cond
10892 ((and (= tt js2-FUNCTION)
10893 (setq body (js2-function-node-body n)))
10894 (setq beg (js2-node-abs-pos body)
10895 end (+ beg (js2-node-len body)))
10896 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10897 nil) ; don't process children of function
10898 (t
10899 t))))) ; keep processing other AST nodes
10900
10901 (defun js2-mode-show-functions ()
10902 "Un-hide any folded function bodies in the buffer."
10903 (interactive)
10904 (setq js2-mode-functions-hidden nil)
10905 (save-excursion
10906 (goto-char (point-min))
10907 (while (/= (goto-char (next-overlay-change (point)))
10908 (point-max))
10909 (dolist (o (overlays-at (point)))
10910 (when (and (overlay-get o 'invisible)
10911 (not (overlay-get o 'comment)))
10912 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10913
10914 (defun js2-mode-hide-comment (n)
10915 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10916 3 ; /**
10917 2)) ; /*
10918 (beg (+ (js2-node-abs-pos n) head))
10919 (end (- (+ beg (js2-node-len n)) head 2))
10920 (o (js2-mode-flag-region beg end 'hide)))
10921 (overlay-put o 'comment t)))
10922
10923 (defun js2-mode-toggle-hide-comments ()
10924 "Folds all block comments in the buffer.
10925 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10926 to open an individual entry."
10927 (interactive)
10928 (if js2-mode-comments-hidden
10929 (js2-mode-show-comments)
10930 (js2-mode-hide-comments)))
10931
10932 (defun js2-mode-hide-comments ()
10933 (interactive)
10934 (if js2-mode-buffer-dirty-p
10935 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10936 (if (null js2-mode-ast)
10937 (message "Oops - parsing failed")
10938 (setq js2-mode-comments-hidden t)
10939 (dolist (n (js2-ast-root-comments js2-mode-ast))
10940 (let ((format (js2-comment-node-format n)))
10941 (when (js2-block-comment-p n)
10942 (js2-mode-hide-comment n))))
10943 (js2-mode-hide-//-comments)))
10944
10945 (defsubst js2-mode-extend-//-comment (direction)
10946 "Find start or end of a block of similar //-comment lines.
10947 DIRECTION is -1 to look back, 1 to look forward.
10948 INDENT is the indentation level to match.
10949 Returns the end-of-line position of the furthest adjacent
10950 //-comment line with the same indentation as the current line.
10951 If there is no such matching line, returns current end of line."
10952 (let ((pos (point-at-eol))
10953 (indent (current-indentation)))
10954 (save-excursion
10955 (while (and (zerop (forward-line direction))
10956 (looking-at js2-mode-//-comment-re)
10957 (eq indent (length (match-string 1))))
10958 (setq pos (point-at-eol)))
10959 pos)))
10960
10961 (defun js2-mode-hide-//-comments ()
10962 "Fold adjacent 1-line comments, showing only snippet of first one."
10963 (let (beg end)
10964 (save-excursion
10965 (goto-char (point-min))
10966 (while (re-search-forward js2-mode-//-comment-re nil t)
10967 (setq beg (point)
10968 end (js2-mode-extend-//-comment 1))
10969 (unless (eq beg end)
10970 (overlay-put (js2-mode-flag-region beg end 'hide)
10971 'comment t))
10972 (goto-char end)
10973 (forward-char 1)))))
10974
10975 (defun js2-mode-toggle-//-comment ()
10976 "Fold or un-fold any multi-line //-comment at point.
10977 Caller should have determined that this line starts with a //-comment."
10978 (let* ((beg (point-at-eol))
10979 (end beg))
10980 (save-excursion
10981 (goto-char end)
10982 (if (js2-mode-invisible-overlay-bounds)
10983 (js2-mode-show-element)
10984 ;; else hide the comment
10985 (setq beg (js2-mode-extend-//-comment -1)
10986 end (js2-mode-extend-//-comment 1))
10987 (unless (eq beg end)
10988 (overlay-put (js2-mode-flag-region beg end 'hide)
10989 'comment t))))))
10990
10991 (defun js2-mode-show-comments ()
10992 "Un-hide any hidden comments, leaving other hidden elements alone."
10993 (interactive)
10994 (setq js2-mode-comments-hidden nil)
10995 (save-excursion
10996 (goto-char (point-min))
10997 (while (/= (goto-char (next-overlay-change (point)))
10998 (point-max))
10999 (dolist (o (overlays-at (point)))
11000 (when (overlay-get o 'comment)
11001 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11002
11003 (defun js2-mode-display-warnings-and-errors ()
11004 "Turn on display of warnings and errors."
11005 (interactive)
11006 (setq js2-mode-show-parse-errors t
11007 js2-mode-show-strict-warnings t)
11008 (js2-reparse 'force))
11009
11010 (defun js2-mode-hide-warnings-and-errors ()
11011 "Turn off display of warnings and errors."
11012 (interactive)
11013 (setq js2-mode-show-parse-errors nil
11014 js2-mode-show-strict-warnings nil)
11015 (js2-reparse 'force))
11016
11017 (defun js2-mode-toggle-warnings-and-errors ()
11018 "Toggle the display of warnings and errors.
11019 Some users don't like having warnings/errors reported while they type."
11020 (interactive)
11021 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11022 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11023 (if (interactive-p)
11024 (message "warnings and errors %s"
11025 (if js2-mode-show-parse-errors
11026 "enabled"
11027 "disabled")))
11028 (js2-reparse 'force))
11029
11030 (defun js2-mode-customize ()
11031 (interactive)
11032 (customize-group 'js2-mode))
11033
11034 (defun js2-mode-forward-sexp (&optional arg)
11035 "Move forward across one statement or balanced expression.
11036 With ARG, do it that many times. Negative arg -N means
11037 move backward across N balanced expressions."
11038 (interactive "p")
11039 (setq arg (or arg 1))
11040 (if js2-mode-buffer-dirty-p
11041 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11042 (let (node end (start (point)))
11043 (cond
11044 ;; backward-sexp
11045 ;; could probably make this better for some cases:
11046 ;; - if in statement block (e.g. function body), go to parent
11047 ;; - infix exprs like (foo in bar) - maybe go to beginning
11048 ;; of infix expr if in the right-side expression?
11049 ((and arg (minusp arg))
11050 (dotimes (i (- arg))
11051 (js2-backward-sws)
11052 (forward-char -1) ; enter the node we backed up to
11053 (setq node (js2-node-at-point (point) t))
11054 (goto-char (if node
11055 (js2-node-abs-pos node)
11056 (point-min)))))
11057 (t
11058 ;; forward-sexp
11059 (js2-forward-sws)
11060 (dotimes (i arg)
11061 (js2-forward-sws)
11062 (setq node (js2-node-at-point (point) t)
11063 end (if node (+ (js2-node-abs-pos node)
11064 (js2-node-len node))))
11065 (goto-char (or end (point-max))))))))
11066
11067 (defun js2-next-error (&optional arg reset)
11068 "Move to next parse error.
11069 Typically invoked via \\[next-error].
11070 ARG is the number of errors, forward or backward, to move.
11071 RESET means start over from the beginning."
11072 (interactive "p")
11073 (if (or (null js2-mode-ast)
11074 (and (null (js2-ast-root-errors js2-mode-ast))
11075 (null (js2-ast-root-warnings js2-mode-ast))))
11076 (message "No errors")
11077 (when reset
11078 (goto-char (point-min)))
11079 (let* ((errs (copy-sequence
11080 (append (js2-ast-root-errors js2-mode-ast)
11081 (js2-ast-root-warnings js2-mode-ast))))
11082 (continue t)
11083 (start (point))
11084 (count (or arg 1))
11085 (backward (minusp count))
11086 (sorter (if backward '> '<))
11087 (stopper (if backward '< '>))
11088 (count (abs count))
11089 all-errs
11090 err)
11091 ;; sort by start position
11092 (setq errs (sort errs (lambda (e1 e2)
11093 (funcall sorter (second e1) (second e2))))
11094 all-errs errs)
11095 ;; find nth error with pos > start
11096 (while (and errs continue)
11097 (when (funcall stopper (cadar errs) start)
11098 (setq err (car errs))
11099 (if (zerop (decf count))
11100 (setq continue nil)))
11101 (setq errs (cdr errs)))
11102 (if err
11103 (goto-char (second err))
11104 ;; wrap around to first error
11105 (goto-char (second (car all-errs)))
11106 ;; if we were already on it, echo msg again
11107 (if (= (point) start)
11108 (js2-echo-error (point) (point)))))))
11109
11110 (defun js2-down-mouse-3 ()
11111 "Make right-click move the point to the click location.
11112 This makes right-click context menu operations a bit more intuitive.
11113 The point will not move if the region is active, however, to avoid
11114 destroying the region selection."
11115 (interactive)
11116 (when (and js2-move-point-on-right-click
11117 (not mark-active))
11118 (let ((e last-input-event))
11119 (ignore-errors
11120 (goto-char (cadadr e))))))
11121
11122 (defun js2-mode-create-imenu-index ()
11123 "Return an alist for `imenu--index-alist'."
11124 ;; This is built up in `js2-parse-record-imenu' during parsing.
11125 (when js2-mode-ast
11126 ;; if we have an ast but no recorder, they're requesting a rescan
11127 (unless js2-imenu-recorder
11128 (js2-reparse 'force))
11129 (prog1
11130 (js2-build-imenu-index)
11131 (setq js2-imenu-recorder nil
11132 js2-imenu-function-map nil))))
11133
11134 (defun js2-mode-find-tag ()
11135 "Replacement for `find-tag-default'.
11136 `find-tag-default' returns a ridiculous answer inside comments."
11137 (let (beg end)
11138 (js2-with-underscore-as-word-syntax
11139 (save-excursion
11140 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11141 (looking-back "[A-Za-z0-9_$]"))
11142 (setq beg (progn (forward-word -1) (point))
11143 end (progn (forward-word 1) (point)))
11144 (setq beg (progn (forward-word 1) (point))
11145 end (progn (forward-word -1) (point))))
11146 (replace-regexp-in-string
11147 "[\"']" ""
11148 (buffer-substring-no-properties beg end))))))
11149
11150 (defun js2-mode-forward-sibling ()
11151 "Move to the end of the sibling following point in parent.
11152 Returns non-nil if successful, or nil if there was no following sibling."
11153 (let* ((node (js2-node-at-point))
11154 (parent (js2-mode-find-enclosing-fn node))
11155 sib)
11156 (when (setq sib (js2-node-find-child-after (point) parent))
11157 (goto-char (+ (js2-node-abs-pos sib)
11158 (js2-node-len sib))))))
11159
11160 (defun js2-mode-backward-sibling ()
11161 "Move to the beginning of the sibling node preceding point in parent.
11162 Parent is defined as the enclosing script or function."
11163 (let* ((node (js2-node-at-point))
11164 (parent (js2-mode-find-enclosing-fn node))
11165 sib)
11166 (when (setq sib (js2-node-find-child-before (point) parent))
11167 (goto-char (js2-node-abs-pos sib)))))
11168
11169 (defun js2-beginning-of-defun ()
11170 "Go to line on which current function starts, and return non-nil.
11171 If we're not in a function, go to beginning of previous script-level element."
11172 (interactive)
11173 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11174 pos sib)
11175 (cond
11176 ((and (js2-function-node-p parent)
11177 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11178 (goto-char pos))
11179 (t
11180 (js2-mode-backward-sibling)))))
11181
11182 (defun js2-end-of-defun ()
11183 "Go to the char after the last position of the current function.
11184 If we're not in a function, skips over the next script-level element."
11185 (interactive)
11186 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11187 (if (not (js2-function-node-p parent))
11188 ;; punt: skip over next script-level element beyond point
11189 (js2-mode-forward-sibling)
11190 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11191 (js2-node-len parent)))))))
11192
11193 (defun js2-mark-defun (&optional allow-extend)
11194 "Put mark at end of this function, point at beginning.
11195 The function marked is the one that contains point.
11196
11197 Interactively, if this command is repeated,
11198 or (in Transient Mark mode) if the mark is active,
11199 it marks the next defun after the ones already marked."
11200 (interactive "p")
11201 (let (extended)
11202 (when (and allow-extend
11203 (or (and (eq last-command this-command) (mark t))
11204 (and transient-mark-mode mark-active)))
11205 (let ((sib (save-excursion
11206 (goto-char (mark))
11207 (if (js2-mode-forward-sibling)
11208 (point))))
11209 node)
11210 (if sib
11211 (progn
11212 (set-mark sib)
11213 (setq extended t))
11214 ;; no more siblings - try extending to enclosing node
11215 (goto-char (mark t)))))
11216 (when (not extended)
11217 (let ((node (js2-node-at-point (point) t)) ; skip comments
11218 ast fn stmt parent beg end)
11219 (when (js2-ast-root-p node)
11220 (setq ast node
11221 node (or (js2-node-find-child-after (point) node)
11222 (js2-node-find-child-before (point) node))))
11223 ;; only mark whole buffer if we can't find any children
11224 (if (null node)
11225 (setq node ast))
11226 (if (js2-function-node-p node)
11227 (setq parent node)
11228 (setq fn (js2-mode-find-enclosing-fn node)
11229 stmt (if (or (null fn)
11230 (js2-ast-root-p fn))
11231 (js2-mode-find-first-stmt node))
11232 parent (or stmt fn)))
11233 (setq beg (js2-node-abs-pos parent)
11234 end (+ beg (js2-node-len parent)))
11235 (push-mark beg)
11236 (goto-char end)
11237 (exchange-point-and-mark)))))
11238
11239 (defun js2-narrow-to-defun ()
11240 "Narrow to the function enclosing point."
11241 (interactive)
11242 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11243 (fn (if (js2-script-node-p node)
11244 node
11245 (js2-mode-find-enclosing-fn node)))
11246 (beg (js2-node-abs-pos fn)))
11247 (unless (js2-ast-root-p fn)
11248 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11249
11250 (provide 'js2-mode)
11251
11252 ;; arch-tag: 1dd56864-a3ef-4682-a63f-6341f6a42738
11253 ;;; js2-mode.el ends here