]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Declare exception symbol in the catch block
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defvar js2-emacs22 (>= emacs-major-version 22))
176
177 (defcustom js2-highlight-level 2
178 "Amount of syntax highlighting to perform.
179 0 or a negative value means do no highlighting.
180 1 adds basic syntax highlighting.
181 2 adds highlighting of some Ecma built-in properties.
182 3 adds highlighting of many Ecma built-in functions."
183 :group 'js2-mode
184 :type '(choice (const :tag "None" 0)
185 (const :tag "Basic" 1)
186 (const :tag "Include Properties" 2)
187 (const :tag "Include Functions" 3)))
188
189 (defvar js2-mode-dev-mode-p nil
190 "Non-nil if running in development mode. Normally nil.")
191
192 (defgroup js2-mode nil
193 "An improved JavaScript mode."
194 :group 'languages)
195
196 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
197 (numberp c-basic-offset))
198 c-basic-offset
199 4)
200 "Number of spaces to indent nested statements.
201 Similar to `c-basic-offset'."
202 :group 'js2-mode
203 :type 'integer)
204 (make-variable-buffer-local 'js2-basic-offset)
205
206 ;; TODO(stevey): move this code into a separate minor mode.
207 (defcustom js2-mirror-mode nil
208 "Non-nil to insert closing brackets, parens, etc. automatically."
209 :group 'js2-mode
210 :type 'boolean)
211
212 (defcustom js2-auto-indent-p nil
213 "Automatic indentation with punctuation characters.
214 If non-nil, the current line is indented when certain punctuations
215 are inserted."
216 :group 'js2-mode
217 :type 'boolean)
218
219 (defcustom js2-bounce-indent-p nil
220 "Non-nil to have indent-line function choose among alternatives.
221 If nil, the indent-line function will indent to a predetermined column
222 based on heuristic guessing. If non-nil, then if the current line is
223 already indented to that predetermined column, indenting will choose
224 another likely column and indent to that spot. Repeated invocation of
225 the indent-line function will cycle among the computed alternatives.
226 See the function `js2-bounce-indent' for details."
227 :type 'boolean
228 :group 'js2-mode)
229
230 (defcustom js2-consistent-level-indent-inner-bracket-p t
231 "Non-nil to make indentation level inner bracket consistent,
232 regardless of the beginning bracket position."
233 :group 'js2-mode
234 :type 'boolean)
235
236 (defcustom js2-use-ast-for-indentation-p nil
237 "Non-nil to use AST for indentation and make it more robust."
238 :group 'js2-mode
239 :type 'boolean)
240
241 (defcustom js2-indent-on-enter-key nil
242 "Non-nil to have Enter/Return key indent the line.
243 This is unusual for Emacs modes but common in IDEs like Eclipse."
244 :type 'boolean
245 :group 'js2-mode)
246
247 (defcustom js2-enter-indents-newline nil
248 "Non-nil to have Enter/Return key indent the newly-inserted line.
249 This is unusual for Emacs modes but common in IDEs like Eclipse."
250 :type 'boolean
251 :group 'js2-mode)
252
253 (defcustom js2-rebind-eol-bol-keys t
254 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
255 If non-nil, bounce between bol/eol and first/last non-whitespace char."
256 :group 'js2-mode
257 :type 'boolean)
258
259 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
260 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
261 Each value in the list is passed to `define-key'."
262 :type 'list
263 :group 'js2-mode)
264
265 (defcustom js2-idle-timer-delay 0.2
266 "Delay in secs before re-parsing after user makes changes.
267 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
268 :type 'number
269 :group 'js2-mode)
270 (make-variable-buffer-local 'js2-idle-timer-delay)
271
272 (defcustom js2-dynamic-idle-timer-adjust 0
273 "Positive to adjust `js2-idle-timer-delay' based on file size.
274 The idea is that for short files, parsing is faster so we can be
275 more responsive to user edits without interfering with editing.
276 The buffer length in characters (typically bytes) is divided by
277 this value and used to multiply `js2-idle-timer-delay' for the
278 buffer. For example, a 21k file and 10k adjust yields 21k/10k
279 == 2, so js2-idle-timer-delay is multiplied by 2.
280 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
281 `js2-idle-timer-delay' is not dependent on the file size."
282 :type 'number
283 :group 'js2-mode)
284
285 (defcustom js2-mode-escape-quotes t
286 "Non-nil to disable automatic quote-escaping inside strings."
287 :type 'boolean
288 :group 'js2-mode)
289
290 (defcustom js2-mode-squeeze-spaces t
291 "Non-nil to normalize whitespace when filling in comments.
292 Multiple runs of spaces are converted to a single space."
293 :type 'boolean
294 :group 'js2-mode)
295
296 (defcustom js2-mode-show-parse-errors t
297 "True to highlight parse errors."
298 :type 'boolean
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-strict-warnings t
302 "Non-nil to emit Ecma strict-mode warnings.
303 Some of the warnings can be individually disabled by other flags,
304 even if this flag is non-nil."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-strict-trailing-comma-warning t
309 "Non-nil to warn about trailing commas in array literals.
310 Ecma-262 forbids them, but many browsers permit them. IE is the
311 big exception, and can produce bugs if you have trailing commas."
312 :type 'boolean
313 :group 'js2-mode)
314
315 (defcustom js2-strict-missing-semi-warning t
316 "Non-nil to warn about semicolon auto-insertion after statement.
317 Technically this is legal per Ecma-262, but some style guides disallow
318 depending on it."
319 :type 'boolean
320 :group 'js2-mode)
321
322 (defcustom js2-missing-semi-one-line-override nil
323 "Non-nil to permit missing semicolons in one-line functions.
324 In one-liner functions such as `function identity(x) {return x}'
325 people often omit the semicolon for a cleaner look. If you are
326 such a person, you can suppress the missing-semicolon warning
327 by setting this variable to t."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-inconsistent-return-warning t
332 "Non-nil to warn about mixing returns with value-returns.
333 It's perfectly legal to have a `return' and a `return foo' in the
334 same function, but it's often an indicator of a bug, and it also
335 interferes with type inference (in systems that support it.)"
336 :type 'boolean
337 :group 'js2-mode)
338
339 (defcustom js2-strict-cond-assign-warning t
340 "Non-nil to warn about expressions like if (a = b).
341 This often should have been '==' instead of '='. If the warning
342 is enabled, you can suppress it on a per-expression basis by
343 parenthesizing the expression, e.g. if ((a = b)) ..."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-cond-assign-warning t
348 "Non-nil to warn about expressions like if (a = b).
349 This often should have been '==' instead of '='. If the warning
350 is enabled, you can suppress it on a per-expression basis by
351 parenthesizing the expression, e.g. if ((a = b)) ..."
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-var-redeclaration-warning t
356 "Non-nil to warn about redeclaring variables in a script or function."
357 :type 'boolean
358 :group 'js2-mode)
359
360 (defcustom js2-strict-var-hides-function-arg-warning t
361 "Non-nil to warn about a var decl hiding a function argument."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-skip-preprocessor-directives nil
366 "Non-nil to treat lines beginning with # as comments.
367 Useful for viewing Mozilla JavaScript source code."
368 :type 'boolean
369 :group 'js2-mode)
370
371 (defcustom js2-language-version 180
372 "Configures what JavaScript language version to recognize.
373 Currently versions 150, 160, 170 and 180 are supported, corresponding
374 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
375 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
376 and 1.8 adds function closures."
377 :type 'integer
378 :group 'js2-mode)
379
380 (defcustom js2-allow-keywords-as-property-names t
381 "If non-nil, you can use JavaScript keywords as object property names.
382 Examples:
383
384 var foo = {int: 5, while: 6, continue: 7};
385 foo.return = 8;
386
387 Ecma-262 forbids this syntax, but many browsers support it."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-instanceof-has-side-effects nil
392 "If non-nil, treats the instanceof operator as having side effects.
393 This is useful for xulrunner apps."
394 :type 'boolean
395 :group 'js2-mode)
396
397 (defcustom js2-cleanup-whitespace nil
398 "Non-nil to invoke `delete-trailing-whitespace' before saves."
399 :type 'boolean
400 :group 'js2-mode)
401
402 (defcustom js2-move-point-on-right-click t
403 "Non-nil to move insertion point when you right-click.
404 This makes right-click context menu behavior a bit more intuitive,
405 since menu operations generally apply to the point. The exception
406 is if there is a region selection, in which case the point does -not-
407 move, so cut/copy/paste etc. can work properly.
408
409 Note that IntelliJ moves the point, and Eclipse leaves it alone,
410 so this behavior is customizable."
411 :group 'js2-mode
412 :type 'boolean)
413
414 (defcustom js2-allow-rhino-new-expr-initializer t
415 "Non-nil to support a Rhino's experimental syntactic construct.
416
417 Rhino supports the ability to follow a `new' expression with an object
418 literal, which is used to set additional properties on the new object
419 after calling its constructor. Syntax:
420
421 new <expr> [ ( arglist ) ] [initializer]
422
423 Hence, this expression:
424
425 new Object {a: 1, b: 2}
426
427 results in an Object with properties a=1 and b=2. This syntax is
428 apparently not configurable in Rhino - it's currently always enabled,
429 as of Rhino version 1.7R2."
430 :type 'boolean
431 :group 'js2-mode)
432
433 (defcustom js2-allow-member-expr-as-function-name nil
434 "Non-nil to support experimental Rhino syntax for function names.
435
436 Rhino supports an experimental syntax configured via the Rhino Context
437 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
438
439 function <member-expr> ( [ arg-list ] ) { <body> }
440
441 Where member-expr is a non-parenthesized 'member expression', which
442 is anything at the grammar level of a new-expression or lower, meaning
443 any expression that does not involve infix or unary operators.
444
445 When <member-expr> is not a simple identifier, then it is syntactic
446 sugar for assigning the anonymous function to the <member-expr>. Hence,
447 this code:
448
449 function a.b().c[2] (x, y) { ... }
450
451 is rewritten as:
452
453 a.b().c[2] = function(x, y) {...}
454
455 which doesn't seem particularly useful, but Rhino permits it."
456 :type 'boolean
457 :group 'js2-mode)
458
459 (defvar js2-mode-version 20101228
460 "Release number for `js2-mode'.")
461
462 ;; scanner variables
463
464 (defmacro js2-deflocal (name value &optional comment)
465 "Define a buffer-local variable NAME with VALUE and COMMENT."
466 `(progn
467 (defvar ,name ,value ,comment)
468 (make-variable-buffer-local ',name)))
469
470 ;; We record the start and end position of each token.
471 (js2-deflocal js2-token-beg 1)
472 (js2-deflocal js2-token-end -1)
473
474 (defvar js2-EOF_CHAR -1
475 "Represents end of stream. Distinct from js2-EOF token type.")
476
477 ;; I originally used symbols to represent tokens, but Rhino uses
478 ;; ints and then sets various flag bits in them, so ints it is.
479 ;; The upshot is that we need a `js2-' prefix in front of each name.
480 (defvar js2-ERROR -1)
481 (defvar js2-EOF 0)
482 (defvar js2-EOL 1)
483 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
484 (defvar js2-LEAVEWITH 3)
485 (defvar js2-RETURN 4)
486 (defvar js2-GOTO 5)
487 (defvar js2-IFEQ 6)
488 (defvar js2-IFNE 7)
489 (defvar js2-SETNAME 8)
490 (defvar js2-BITOR 9)
491 (defvar js2-BITXOR 10)
492 (defvar js2-BITAND 11)
493 (defvar js2-EQ 12)
494 (defvar js2-NE 13)
495 (defvar js2-LT 14)
496 (defvar js2-LE 15)
497 (defvar js2-GT 16)
498 (defvar js2-GE 17)
499 (defvar js2-LSH 18)
500 (defvar js2-RSH 19)
501 (defvar js2-URSH 20)
502 (defvar js2-ADD 21) ; infix plus
503 (defvar js2-SUB 22) ; infix minus
504 (defvar js2-MUL 23)
505 (defvar js2-DIV 24)
506 (defvar js2-MOD 25)
507 (defvar js2-NOT 26)
508 (defvar js2-BITNOT 27)
509 (defvar js2-POS 28) ; unary plus
510 (defvar js2-NEG 29) ; unary minus
511 (defvar js2-NEW 30)
512 (defvar js2-DELPROP 31)
513 (defvar js2-TYPEOF 32)
514 (defvar js2-GETPROP 33)
515 (defvar js2-GETPROPNOWARN 34)
516 (defvar js2-SETPROP 35)
517 (defvar js2-GETELEM 36)
518 (defvar js2-SETELEM 37)
519 (defvar js2-CALL 38)
520 (defvar js2-NAME 39) ; an identifier
521 (defvar js2-NUMBER 40)
522 (defvar js2-STRING 41)
523 (defvar js2-NULL 42)
524 (defvar js2-THIS 43)
525 (defvar js2-FALSE 44)
526 (defvar js2-TRUE 45)
527 (defvar js2-SHEQ 46) ; shallow equality (===)
528 (defvar js2-SHNE 47) ; shallow inequality (!==)
529 (defvar js2-REGEXP 48)
530 (defvar js2-BINDNAME 49)
531 (defvar js2-THROW 50)
532 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
533 (defvar js2-IN 52)
534 (defvar js2-INSTANCEOF 53)
535 (defvar js2-LOCAL_LOAD 54)
536 (defvar js2-GETVAR 55)
537 (defvar js2-SETVAR 56)
538 (defvar js2-CATCH_SCOPE 57)
539 (defvar js2-ENUM_INIT_KEYS 58)
540 (defvar js2-ENUM_INIT_VALUES 59)
541 (defvar js2-ENUM_INIT_ARRAY 60)
542 (defvar js2-ENUM_NEXT 61)
543 (defvar js2-ENUM_ID 62)
544 (defvar js2-THISFN 63)
545 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
546 (defvar js2-ARRAYLIT 65) ; array literal
547 (defvar js2-OBJECTLIT 66) ; object literal
548 (defvar js2-GET_REF 67) ; *reference
549 (defvar js2-SET_REF 68) ; *reference = something
550 (defvar js2-DEL_REF 69) ; delete reference
551 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
552 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
553 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
554
555 ;; XML support
556 (defvar js2-DEFAULTNAMESPACE 73)
557 (defvar js2-ESCXMLATTR 74)
558 (defvar js2-ESCXMLTEXT 75)
559 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
560 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
561 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
562 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
563
564 (defvar js2-first-bytecode js2-ENTERWITH)
565 (defvar js2-last-bytecode js2-REF_NS_NAME)
566
567 (defvar js2-TRY 80)
568 (defvar js2-SEMI 81) ; semicolon
569 (defvar js2-LB 82) ; left and right brackets
570 (defvar js2-RB 83)
571 (defvar js2-LC 84) ; left and right curly-braces
572 (defvar js2-RC 85)
573 (defvar js2-LP 86) ; left and right parens
574 (defvar js2-RP 87)
575 (defvar js2-COMMA 88) ; comma operator
576
577 (defvar js2-ASSIGN 89) ; simple assignment (=)
578 (defvar js2-ASSIGN_BITOR 90) ; |=
579 (defvar js2-ASSIGN_BITXOR 91) ; ^=
580 (defvar js2-ASSIGN_BITAND 92) ; &=
581 (defvar js2-ASSIGN_LSH 93) ; <<=
582 (defvar js2-ASSIGN_RSH 94) ; >>=
583 (defvar js2-ASSIGN_URSH 95) ; >>>=
584 (defvar js2-ASSIGN_ADD 96) ; +=
585 (defvar js2-ASSIGN_SUB 97) ; -=
586 (defvar js2-ASSIGN_MUL 98) ; *=
587 (defvar js2-ASSIGN_DIV 99) ; /=
588 (defvar js2-ASSIGN_MOD 100) ; %=
589
590 (defvar js2-first-assign js2-ASSIGN)
591 (defvar js2-last-assign js2-ASSIGN_MOD)
592
593 (defvar js2-HOOK 101) ; conditional (?:)
594 (defvar js2-COLON 102)
595 (defvar js2-OR 103) ; logical or (||)
596 (defvar js2-AND 104) ; logical and (&&)
597 (defvar js2-INC 105) ; increment/decrement (++ --)
598 (defvar js2-DEC 106)
599 (defvar js2-DOT 107) ; member operator (.)
600 (defvar js2-FUNCTION 108) ; function keyword
601 (defvar js2-EXPORT 109) ; export keyword
602 (defvar js2-IMPORT 110) ; import keyword
603 (defvar js2-IF 111) ; if keyword
604 (defvar js2-ELSE 112) ; else keyword
605 (defvar js2-SWITCH 113) ; switch keyword
606 (defvar js2-CASE 114) ; case keyword
607 (defvar js2-DEFAULT 115) ; default keyword
608 (defvar js2-WHILE 116) ; while keyword
609 (defvar js2-DO 117) ; do keyword
610 (defvar js2-FOR 118) ; for keyword
611 (defvar js2-BREAK 119) ; break keyword
612 (defvar js2-CONTINUE 120) ; continue keyword
613 (defvar js2-VAR 121) ; var keyword
614 (defvar js2-WITH 122) ; with keyword
615 (defvar js2-CATCH 123) ; catch keyword
616 (defvar js2-FINALLY 124) ; finally keyword
617 (defvar js2-VOID 125) ; void keyword
618 (defvar js2-RESERVED 126) ; reserved keywords
619
620 (defvar js2-EMPTY 127)
621
622 ;; Types used for the parse tree - never returned by scanner.
623
624 (defvar js2-BLOCK 128) ; statement block
625 (defvar js2-LABEL 129) ; label
626 (defvar js2-TARGET 130)
627 (defvar js2-LOOP 131)
628 (defvar js2-EXPR_VOID 132) ; expression statement in functions
629 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
630 (defvar js2-JSR 134)
631 (defvar js2-SCRIPT 135) ; top-level node for entire script
632 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
633 (defvar js2-USE_STACK 137)
634 (defvar js2-SETPROP_OP 138) ; x.y op= something
635 (defvar js2-SETELEM_OP 139) ; x[y] op= something
636 (defvar js2-LOCAL_BLOCK 140)
637 (defvar js2-SET_REF_OP 141) ; *reference op= something
638
639 ;; For XML support:
640 (defvar js2-DOTDOT 142) ; member operator (..)
641 (defvar js2-COLONCOLON 143) ; namespace::name
642 (defvar js2-XML 144) ; XML type
643 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
644 (defvar js2-XMLATTR 146) ; @
645 (defvar js2-XMLEND 147)
646
647 ;; Optimizer-only tokens
648 (defvar js2-TO_OBJECT 148)
649 (defvar js2-TO_DOUBLE 149)
650
651 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
652 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
653 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
654 (defvar js2-CONST 153)
655 (defvar js2-SETCONST 154)
656 (defvar js2-SETCONSTVAR 155)
657 (defvar js2-ARRAYCOMP 156)
658 (defvar js2-LETEXPR 157)
659 (defvar js2-WITHEXPR 158)
660 (defvar js2-DEBUGGER 159)
661
662 (defvar js2-COMMENT 160)
663 (defvar js2-ENUM 161) ; for "enum" reserved word
664
665 (defconst js2-num-tokens (1+ js2-ENUM))
666
667 (defconst js2-debug-print-trees nil)
668
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
672 ;; scanning them.
673
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
676
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
680
681 (js2-deflocal js2-ts-regexp-flags nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-string ""
685 "Token stream buffer-local variable.
686 Last string scanned.")
687
688 (js2-deflocal js2-ts-number nil
689 "Token stream buffer-local variable.
690 Last literal number scanned.")
691
692 (js2-deflocal js2-ts-hit-eof nil
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-line-start 0
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-lineno 1
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-line-end-char -1
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
705 "Token stream buffer-local variable.
706 Current scan position.")
707
708 (js2-deflocal js2-ts-is-xml-attribute nil
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-xml-is-tag-content nil
712 "Token stream buffer-local variable.")
713
714 (js2-deflocal js2-ts-xml-open-tags-count 0
715 "Token stream buffer-local variable.")
716
717 (js2-deflocal js2-ts-string-buffer nil
718 "Token stream buffer-local variable.
719 List of chars built up while scanning various tokens.")
720
721 (js2-deflocal js2-ts-comment-type nil
722 "Token stream buffer-local variable.")
723
724 ;;; Parser variables
725
726 (js2-deflocal js2-parsed-errors nil
727 "List of errors produced during scanning/parsing.")
728
729 (js2-deflocal js2-parsed-warnings nil
730 "List of warnings produced during scanning/parsing.")
731
732 (js2-deflocal js2-recover-from-parse-errors t
733 "Non-nil to continue parsing after a syntax error.
734
735 In recovery mode, the AST will be built in full, and any error
736 nodes will be flagged with appropriate error information. If
737 this flag is nil, a syntax error will result in an error being
738 signaled.
739
740 The variable is automatically buffer-local, because different
741 modes that use the parser will need different settings.")
742
743 (js2-deflocal js2-parse-hook nil
744 "List of callbacks for receiving parsing progress.")
745
746 (defvar js2-parse-finished-hook nil
747 "List of callbacks to notify when parsing finishes.
748 Not called if parsing was interrupted.")
749
750 (js2-deflocal js2-is-eval-code nil
751 "True if we're evaluating code in a string.
752 If non-nil, the tokenizer will record the token text, and the AST nodes
753 will record their source text. Off by default for IDE modes, since the
754 text is available in the buffer.")
755
756 (defvar js2-parse-ide-mode t
757 "Non-nil if the parser is being used for `js2-mode'.
758 If non-nil, the parser will set text properties for fontification
759 and the syntax table. The value should be nil when using the
760 parser as a frontend to an interpreter or byte compiler.")
761
762 ;;; Parser instance variables (buffer-local vars for js2-parse)
763
764 (defconst js2-clear-ti-mask #xFFFF
765 "Mask to clear token information bits.")
766
767 (defconst js2-ti-after-eol (lsh 1 16)
768 "Flag: first token of the source line.")
769
770 (defconst js2-ti-check-label (lsh 1 17)
771 "Flag: indicates to check for label.")
772
773 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
774
775 (js2-deflocal js2-compiler-generate-debug-info t)
776 (js2-deflocal js2-compiler-use-dynamic-scope nil)
777 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
778 (js2-deflocal js2-compiler-xml-available t)
779 (js2-deflocal js2-compiler-optimization-level 0)
780 (js2-deflocal js2-compiler-generating-source t)
781 (js2-deflocal js2-compiler-strict-mode nil)
782 (js2-deflocal js2-compiler-report-warning-as-error nil)
783 (js2-deflocal js2-compiler-generate-observer-count nil)
784 (js2-deflocal js2-compiler-activation-names nil)
785
786 ;; SKIP: sourceURI
787
788 ;; There's a compileFunction method in Context.java - may need it.
789 (js2-deflocal js2-called-by-compile-function nil
790 "True if `js2-parse' was called by `js2-compile-function'.
791 Will only be used when we finish implementing the interpreter.")
792
793 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
794
795 (js2-deflocal js2-current-flagged-token js2-EOF)
796 (js2-deflocal js2-current-token js2-EOF)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (defmacro js2-in-lhs (body)
807 `(let ((js2-is-in-lhs t))
808 ,body))
809
810 (defmacro js2-in-rhs (body)
811 `(let ((js2-is-in-lhs nil))
812 ,body))
813
814 (js2-deflocal js2-is-in-lhs nil
815 "True while parsing lhs statement")
816
817 (defcustom js2-global-externs nil
818 "A list of any extern names you'd like to consider always declared.
819 This list is global and is used by all js2-mode files.
820 You can create buffer-local externs list using `js2-additional-externs'.
821
822 There is also a buffer-local variable `js2-default-externs',
823 which is initialized by default to include the Ecma-262 externs
824 and the standard browser externs. The three lists are all
825 checked during highlighting."
826 :type 'list
827 :group 'js2-mode)
828
829 (js2-deflocal js2-default-externs nil
830 "Default external declarations.
831
832 These are currently only used for highlighting undeclared variables,
833 which only worries about top-level (unqualified) references.
834 As js2-mode's processing improves, we will flesh out this list.
835
836 The initial value is set to `js2-ecma-262-externs', unless you
837 have set `js2-include-browser-externs', in which case the browser
838 externs are also included.
839
840 See `js2-additional-externs' for more information.")
841
842 (defcustom js2-include-browser-externs t
843 "Non-nil to include browser externs in the master externs list.
844 If you work on JavaScript files that are not intended for browsers,
845 such as Mozilla Rhino server-side JavaScript, set this to nil.
846 You can always include them on a per-file basis by calling
847 `js2-add-browser-externs' from a function on `js2-mode-hook'.
848
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-rhino-externs t
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (defcustom js2-include-gears-externs t
860 "Non-nil to include Google Gears externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
862 :type 'boolean
863 :group 'js2-mode)
864
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
869
870 Each entry is a lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
873
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
878
879 Next, you can add a function to `js2-mode-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
882
883 Finally, you can add a function to `js2-post-parse-callbacks',
884 which is called after parsing completes, and `root' is bound to
885 the root of the parse tree. At this stage you can set up an AST
886 node visitor using `js2-visit-ast' and examine the parse tree
887 for specific import patterns that may imply the existence of
888 other externs, possibly tied to your build system. These should also
889 be added to `js2-additional-externs'.
890
891 Your post-parse callback may of course also use the simpler and
892 faster (but perhaps less robust) approach of simply scanning the
893 buffer text for your imports, using regular expressions.")
894
895 ;; SKIP: decompiler
896 ;; SKIP: encoded-source
897
898 ;;; The following variables are per-function and should be saved/restored
899 ;;; during function parsing...
900
901 (js2-deflocal js2-current-script-or-fn nil)
902 (js2-deflocal js2-current-scope nil)
903 (js2-deflocal js2-nesting-of-with 0)
904 (js2-deflocal js2-label-set nil
905 "An alist mapping label names to nodes.")
906
907 (js2-deflocal js2-loop-set nil)
908 (js2-deflocal js2-loop-and-switch-set nil)
909 (js2-deflocal js2-has-return-value nil)
910 (js2-deflocal js2-end-flags 0)
911
912 ;;; ...end of per function variables
913
914 ;; Without 2-token lookahead, labels are a problem.
915 ;; These vars store the token info of the last matched name,
916 ;; iff it wasn't the last matched token. Only valid in some contexts.
917 (defvar js2-prev-name-token-start nil)
918 (defvar js2-prev-name-token-string nil)
919
920 (defsubst js2-save-name-token-data (pos name)
921 (setq js2-prev-name-token-start pos
922 js2-prev-name-token-string name))
923
924 ;; These flags enumerate the possible ways a statement/function can
925 ;; terminate. These flags are used by endCheck() and by the Parser to
926 ;; detect inconsistent return usage.
927 ;;
928 ;; END_UNREACHED is reserved for code paths that are assumed to always be
929 ;; able to execute (example: throw, continue)
930 ;;
931 ;; END_DROPS_OFF indicates if the statement can transfer control to the
932 ;; next one. Statement such as return dont. A compound statement may have
933 ;; some branch that drops off control to the next statement.
934 ;;
935 ;; END_RETURNS indicates that the statement can return (without arguments)
936 ;; END_RETURNS_VALUE indicates that the statement can return a value.
937 ;;
938 ;; A compound statement such as
939 ;; if (condition) {
940 ;; return value;
941 ;; }
942 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
943
944 (defconst js2-end-unreached #x0)
945 (defconst js2-end-drops-off #x1)
946 (defconst js2-end-returns #x2)
947 (defconst js2-end-returns-value #x4)
948 (defconst js2-end-yields #x8)
949
950 ;; Rhino awkwardly passes a statementLabel parameter to the
951 ;; statementHelper() function, the main statement parser, which
952 ;; is then used by quite a few of the sub-parsers. We just make
953 ;; it a buffer-local variable and make sure it's cleaned up properly.
954 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
955
956 ;; Similarly, Rhino passes an inForInit boolean through about half
957 ;; the expression parsers. We use a dynamically-scoped variable,
958 ;; which makes it easier to funcall the parsers individually without
959 ;; worrying about whether they take the parameter or not.
960 (js2-deflocal js2-in-for-init nil)
961 (js2-deflocal js2-temp-name-counter 0)
962 (js2-deflocal js2-parse-stmt-count 0)
963
964 (defsubst js2-get-next-temp-name ()
965 (format "$%d" (incf js2-temp-name-counter)))
966
967 (defvar js2-parse-interruptable-p t
968 "Set this to nil to force parse to continue until finished.
969 This will mostly be useful for interpreters.")
970
971 (defvar js2-statements-per-pause 50
972 "Pause after this many statements to check for user input.
973 If user input is pending, stop the parse and discard the tree.
974 This makes for a smoother user experience for large files.
975 You may have to wait a second or two before the highlighting
976 and error-reporting appear, but you can always type ahead if
977 you wish. This appears to be more or less how Eclipse, IntelliJ
978 and other editors work.")
979
980 (js2-deflocal js2-record-comments t
981 "Instructs the scanner to record comments in `js2-scanned-comments'.")
982
983 (js2-deflocal js2-scanned-comments nil
984 "List of all comments from the current parse.")
985
986 (defcustom js2-mode-indent-inhibit-undo nil
987 "Non-nil to disable collection of Undo information when indenting lines.
988 Some users have requested this behavior. It's nil by default because
989 other Emacs modes don't work this way."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defcustom js2-mode-indent-ignore-first-tab nil
994 "If non-nil, ignore first TAB keypress if we look indented properly.
995 It's fairly common for users to navigate to an already-indented line
996 and press TAB for reassurance that it's been indented. For this class
997 of users, we want the first TAB press on a line to be ignored if the
998 line is already indented to one of the precomputed alternatives.
999
1000 This behavior is only partly implemented. If you TAB-indent a line,
1001 navigate to another line, and then navigate back, it fails to clear
1002 the last-indented variable, so it thinks you've already hit TAB once,
1003 and performs the indent. A full solution would involve getting on the
1004 point-motion hooks for the entire buffer. If we come across another
1005 use cases that requires watching point motion, I'll consider doing it.
1006
1007 If you set this variable to nil, then the TAB key will always change
1008 the indentation of the current line, if more than one alternative
1009 indentation spot exists."
1010 :type 'boolean
1011 :group 'js2-mode)
1012
1013 (defvar js2-indent-hook nil
1014 "A hook for user-defined indentation rules.
1015
1016 Functions on this hook should expect two arguments: (LIST INDEX)
1017 The LIST argument is the list of computed indentation points for
1018 the current line. INDEX is the list index of the indentation point
1019 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1020 indent function is not going to change the current line indentation.
1021
1022 If a hook function on this list returns a non-nil value, then
1023 `js2-bounce-indent' assumes the hook function has performed its own
1024 indentation, and will do nothing. If all hook functions on the list
1025 return nil, then `js2-bounce-indent' will use its computed indentation
1026 and reindent the line.
1027
1028 When hook functions on this hook list are called, the variable
1029 `js2-mode-ast' may or may not be set, depending on whether the
1030 parse tree is available. If the variable is nil, you can pass a
1031 callback to `js2-mode-wait-for-parse', and your callback will be
1032 called after the new parse tree is built. This can take some time
1033 in large files.")
1034
1035 (defface js2-warning-face
1036 `((((class color) (background light))
1037 (:underline "orange"))
1038 (((class color) (background dark))
1039 (:underline "orange"))
1040 (t (:underline t)))
1041 "Face for JavaScript warnings."
1042 :group 'js2-mode)
1043
1044 (defface js2-error-face
1045 `((((class color) (background light))
1046 (:foreground "red"))
1047 (((class color) (background dark))
1048 (:foreground "red"))
1049 (t (:foreground "red")))
1050 "Face for JavaScript errors."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-tag-face
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1056 :group 'js2-mode)
1057
1058 (defface js2-jsdoc-type-face
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-value-face
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1066 :group 'js2-mode)
1067
1068 (defface js2-function-param-face
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1071 :group 'js2-mode)
1072
1073 (defface js2-instance-member-face
1074 '((t :foreground "DarkOrchid"))
1075 "Face used to highlight instance variables in javascript.
1076 Not currently used."
1077 :group 'js2-mode)
1078
1079 (defface js2-private-member-face
1080 '((t :foreground "PeachPuff3"))
1081 "Face used to highlight calls to private methods in javascript.
1082 Not currently used."
1083 :group 'js2-mode)
1084
1085 (defface js2-private-function-call-face
1086 '((t :foreground "goldenrod"))
1087 "Face used to highlight calls to private functions in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-jsdoc-html-tag-name-face
1092 (if js2-emacs22
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "rosybrown"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "yellow"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "magenta")))
1099 '((((type tty pc) (class color) (background light))
1100 (:foreground "magenta"))
1101 (((type tty pc) (class color) (background dark))
1102 (:foreground "yellow"))
1103 (t (:foreground "RosyBrown"))))
1104 "Face used to highlight jsdoc html tag names"
1105 :group 'js2-mode)
1106
1107 (defface js2-jsdoc-html-tag-delimiter-face
1108 (if js2-emacs22
1109 '((((class color) (min-colors 88) (background light))
1110 (:foreground "dark khaki"))
1111 (((class color) (min-colors 8) (background dark))
1112 (:foreground "green"))
1113 (((class color) (min-colors 8) (background light))
1114 (:foreground "green")))
1115 '((((type tty pc) (class color) (background light))
1116 (:foreground "green"))
1117 (((type tty pc) (class color) (background dark))
1118 (:foreground "green"))
1119 (t (:foreground "dark khaki"))))
1120 "Face used to highlight brackets in jsdoc html tags."
1121 :group 'js2-mode)
1122
1123 (defface js2-magic-paren-face
1124 '((t :underline t))
1125 "Face used to color parens that will be auto-overwritten."
1126 :group 'js2-mode)
1127
1128 (defcustom js2-post-parse-callbacks nil
1129 "A list of callback functions invoked after parsing finishes.
1130 Currently, the main use for this function is to add synthetic
1131 declarations to `js2-recorded-identifiers', which see."
1132 :type 'list
1133 :group 'js2-mode)
1134
1135 (defface js2-external-variable-face
1136 '((t :foreground "orange"))
1137 "Face used to highlight undeclared variable identifiers.
1138 An undeclared variable is any variable not declared with var or let
1139 in the current scope or any lexically enclosing scope. If you use
1140 such a variable, then you are either expecting it to originate from
1141 another file, or you've got a potential bug."
1142 :group 'js2-mode)
1143
1144 (defcustom js2-highlight-external-variables t
1145 "Non-nil to highlight undeclared variable identifiers."
1146 :type 'boolean
1147 :group 'js2-mode)
1148
1149 (defcustom js2-auto-insert-catch-block t
1150 "Non-nil to insert matching catch block on open-curly after `try'."
1151 :type 'boolean
1152 :group 'js2-mode)
1153
1154 (defvar js2-mode-map
1155 (let ((map (make-sparse-keymap))
1156 keys)
1157 (define-key map [mouse-1] #'js2-mode-show-node)
1158 (define-key map (kbd "C-m") #'js2-enter-key)
1159 (when js2-rebind-eol-bol-keys
1160 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1161 (define-key map (kbd "C-e") #'js2-end-of-line))
1162 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1163 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1164 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1165 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1166 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1167 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1168 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1169 (define-key map (kbd "C-c C-`") #'js2-next-error)
1170 ;; also define user's preference for next-error, if available
1171 (if (setq keys (where-is-internal #'next-error))
1172 (define-key map (car keys) #'js2-next-error))
1173 (define-key map (or (car (where-is-internal #'mark-defun))
1174 (kbd "M-C-h"))
1175 #'js2-mark-defun)
1176 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1177 (kbd "C-x nd"))
1178 #'js2-narrow-to-defun)
1179 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1180 (when js2-auto-indent-p
1181 (mapc (lambda (key)
1182 (define-key map key #'js2-insert-and-indent))
1183 js2-electric-keys))
1184
1185 (define-key map [menu-bar javascript]
1186 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1187
1188 (define-key map [menu-bar javascript customize-js2-mode]
1189 '(menu-item "Customize js2-mode" js2-mode-customize
1190 :help "Customize the behavior of this mode"))
1191
1192 (define-key map [menu-bar javascript js2-force-refresh]
1193 '(menu-item "Force buffer refresh" js2-mode-reset
1194 :help "Re-parse the buffer from scratch"))
1195
1196 (define-key map [menu-bar javascript separator-2]
1197 '("--"))
1198
1199 (define-key map [menu-bar javascript next-error]
1200 '(menu-item "Next warning or error" js2-next-error
1201 :enabled (and js2-mode-ast
1202 (or (js2-ast-root-errors js2-mode-ast)
1203 (js2-ast-root-warnings js2-mode-ast)))
1204 :help "Move to next warning or error"))
1205
1206 (define-key map [menu-bar javascript display-errors]
1207 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1208 :visible (not js2-mode-show-parse-errors)
1209 :help "Turn on display of warnings and errors"))
1210
1211 (define-key map [menu-bar javascript hide-errors]
1212 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1213 :visible js2-mode-show-parse-errors
1214 :help "Turn off display of warnings and errors"))
1215
1216 (define-key map [menu-bar javascript separator-1]
1217 '("--"))
1218
1219 (define-key map [menu-bar javascript js2-toggle-function]
1220 '(menu-item "Show/collapse element" js2-mode-toggle-element
1221 :help "Hide or show function body or comment"))
1222
1223 (define-key map [menu-bar javascript show-comments]
1224 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1225 :visible js2-mode-comments-hidden
1226 :help "Expand all hidden block comments"))
1227
1228 (define-key map [menu-bar javascript hide-comments]
1229 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1230 :visible (not js2-mode-comments-hidden)
1231 :help "Show block comments as /*...*/"))
1232
1233 (define-key map [menu-bar javascript show-all-functions]
1234 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1235 :visible js2-mode-functions-hidden
1236 :help "Expand all hidden function bodies"))
1237
1238 (define-key map [menu-bar javascript hide-all-functions]
1239 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1240 :visible (not js2-mode-functions-hidden)
1241 :help "Show {...} for all top-level function bodies"))
1242
1243 map)
1244 "Keymap used in `js2-mode' buffers.")
1245
1246 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1247
1248 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1249 "Matches a //-comment line. Must be first non-whitespace on line.
1250 First match-group is the leading whitespace.")
1251
1252 (defvar js2-mode-hook nil)
1253
1254 (js2-deflocal js2-mode-ast nil "Private variable.")
1255 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1256 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1257 (js2-deflocal js2-mode-parsing nil "Private variable.")
1258 (js2-deflocal js2-mode-node-overlay nil)
1259
1260 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1261 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1262
1263 (js2-deflocal js2-mode-fontifications nil "Private variable")
1264 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1265 (js2-deflocal js2-imenu-recorder nil "Private variable")
1266 (js2-deflocal js2-imenu-function-map nil "Private variable")
1267
1268 (defvar js2-paragraph-start
1269 "\\(@[a-zA-Z]+\\>\\|$\\)")
1270
1271 ;; Note that we also set a 'c-in-sws text property in html comments,
1272 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1273 (defvar js2-syntactic-ws-start
1274 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1275
1276 (defvar js2-syntactic-ws-end
1277 "\\s \\|[\n\r/]\\|\\s!")
1278
1279 (defvar js2-syntactic-eol
1280 (concat "\\s *\\(/\\*[^*\n\r]*"
1281 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1282 "\\*+/\\s *\\)*"
1283 "\\(//\\|/\\*[^*\n\r]*"
1284 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1285 "\\|\\\\$\\|$\\)")
1286 "Copied from `java-mode'. Needed for some cc-engine functions.")
1287
1288 (defvar js2-comment-prefix-regexp
1289 "//+\\|\\**")
1290
1291 (defvar js2-comment-start-skip
1292 "\\(//+\\|/\\*+\\)\\s *")
1293
1294 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1295 "Non-nil to emit status messages during parsing.")
1296
1297 (defvar js2-mode-functions-hidden nil "private variable")
1298 (defvar js2-mode-comments-hidden nil "private variable")
1299
1300 (defvar js2-mode-syntax-table
1301 (let ((table (make-syntax-table)))
1302 (c-populate-syntax-table table)
1303 table)
1304 "Syntax table used in js2-mode buffers.")
1305
1306 (defvar js2-mode-abbrev-table nil
1307 "Abbrev table in use in `js2-mode' buffers.")
1308 (define-abbrev-table 'js2-mode-abbrev-table ())
1309
1310 (defvar js2-mode-pending-parse-callbacks nil
1311 "List of functions waiting to be notified that parse is finished.")
1312
1313 (defvar js2-mode-last-indented-line -1)
1314
1315 ;;; Localizable error and warning messages
1316
1317 ;; Messages are copied from Rhino's Messages.properties.
1318 ;; Many of the Java-specific messages have been elided.
1319 ;; Add any js2-specific ones at the end, so we can keep
1320 ;; this file synced with changes to Rhino's.
1321
1322 (defvar js2-message-table
1323 (make-hash-table :test 'equal :size 250)
1324 "Contains localized messages for js2-mode.")
1325
1326 ;; TODO(stevey): construct this table at compile-time.
1327 (defmacro js2-msg (key &rest strings)
1328 `(puthash ,key (funcall #'concat ,@strings)
1329 js2-message-table))
1330
1331 (defun js2-get-msg (msg-key)
1332 "Look up a localized message.
1333 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1334 the correct number of ARGS must be provided."
1335 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1336 (args (if (listp msg-key) (cdr msg-key)))
1337 (msg (gethash key js2-message-table)))
1338 (if msg
1339 (apply #'format msg args)
1340 key))) ; default to showing the key
1341
1342 (js2-msg "msg.dup.parms"
1343 "Duplicate parameter name '%s'.")
1344
1345 (js2-msg "msg.too.big.jump"
1346 "Program too complex: jump offset too big.")
1347
1348 (js2-msg "msg.too.big.index"
1349 "Program too complex: internal index exceeds 64K limit.")
1350
1351 (js2-msg "msg.while.compiling.fn"
1352 "Encountered code generation error while compiling function '%s': %s")
1353
1354 (js2-msg "msg.while.compiling.script"
1355 "Encountered code generation error while compiling script: %s")
1356
1357 ;; Context
1358 (js2-msg "msg.ctor.not.found"
1359 "Constructor for '%s' not found.")
1360
1361 (js2-msg "msg.not.ctor"
1362 "'%s' is not a constructor.")
1363
1364 ;; FunctionObject
1365 (js2-msg "msg.varargs.ctor"
1366 "Method or constructor '%s' must be static "
1367 "with the signature (Context cx, Object[] args, "
1368 "Function ctorObj, boolean inNewExpr) "
1369 "to define a variable arguments constructor.")
1370
1371 (js2-msg "msg.varargs.fun"
1372 "Method '%s' must be static with the signature "
1373 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1374 "to define a variable arguments function.")
1375
1376 (js2-msg "msg.incompat.call"
1377 "Method '%s' called on incompatible object.")
1378
1379 (js2-msg "msg.bad.parms"
1380 "Unsupported parameter type '%s' in method '%s'.")
1381
1382 (js2-msg "msg.bad.method.return"
1383 "Unsupported return type '%s' in method '%s'.")
1384
1385 (js2-msg "msg.bad.ctor.return"
1386 "Construction of objects of type '%s' is not supported.")
1387
1388 (js2-msg "msg.no.overload"
1389 "Method '%s' occurs multiple times in class '%s'.")
1390
1391 (js2-msg "msg.method.not.found"
1392 "Method '%s' not found in '%s'.")
1393
1394 ;; IRFactory
1395
1396 (js2-msg "msg.bad.for.in.lhs"
1397 "Invalid left-hand side of for..in loop.")
1398
1399 (js2-msg "msg.mult.index"
1400 "Only one variable allowed in for..in loop.")
1401
1402 (js2-msg "msg.bad.for.in.destruct"
1403 "Left hand side of for..in loop must be an array of "
1404 "length 2 to accept key/value pair.")
1405
1406 (js2-msg "msg.cant.convert"
1407 "Can't convert to type '%s'.")
1408
1409 (js2-msg "msg.bad.assign.left"
1410 "Invalid assignment left-hand side.")
1411
1412 (js2-msg "msg.bad.decr"
1413 "Invalid decerement operand.")
1414
1415 (js2-msg "msg.bad.incr"
1416 "Invalid increment operand.")
1417
1418 (js2-msg "msg.bad.yield"
1419 "yield must be in a function.")
1420
1421 (js2-msg "msg.yield.parenthesized"
1422 "yield expression must be parenthesized.")
1423
1424 ;; NativeGlobal
1425 (js2-msg "msg.cant.call.indirect"
1426 "Function '%s' must be called directly, and not by way of a "
1427 "function of another name.")
1428
1429 (js2-msg "msg.eval.nonstring"
1430 "Calling eval() with anything other than a primitive "
1431 "string value will simply return the value. "
1432 "Is this what you intended?")
1433
1434 (js2-msg "msg.eval.nonstring.strict"
1435 "Calling eval() with anything other than a primitive "
1436 "string value is not allowed in strict mode.")
1437
1438 (js2-msg "msg.bad.destruct.op"
1439 "Invalid destructuring assignment operator")
1440
1441 ;; NativeCall
1442 (js2-msg "msg.only.from.new"
1443 "'%s' may only be invoked from a `new' expression.")
1444
1445 (js2-msg "msg.deprec.ctor"
1446 "The '%s' constructor is deprecated.")
1447
1448 ;; NativeFunction
1449 (js2-msg "msg.no.function.ref.found"
1450 "no source found to decompile function reference %s")
1451
1452 (js2-msg "msg.arg.isnt.array"
1453 "second argument to Function.prototype.apply must be an array")
1454
1455 ;; NativeGlobal
1456 (js2-msg "msg.bad.esc.mask"
1457 "invalid string escape mask")
1458
1459 ;; NativeRegExp
1460 (js2-msg "msg.bad.quant"
1461 "Invalid quantifier %s")
1462
1463 (js2-msg "msg.overlarge.backref"
1464 "Overly large back reference %s")
1465
1466 (js2-msg "msg.overlarge.min"
1467 "Overly large minimum %s")
1468
1469 (js2-msg "msg.overlarge.max"
1470 "Overly large maximum %s")
1471
1472 (js2-msg "msg.zero.quant"
1473 "Zero quantifier %s")
1474
1475 (js2-msg "msg.max.lt.min"
1476 "Maximum %s less than minimum")
1477
1478 (js2-msg "msg.unterm.quant"
1479 "Unterminated quantifier %s")
1480
1481 (js2-msg "msg.unterm.paren"
1482 "Unterminated parenthetical %s")
1483
1484 (js2-msg "msg.unterm.class"
1485 "Unterminated character class %s")
1486
1487 (js2-msg "msg.bad.range"
1488 "Invalid range in character class.")
1489
1490 (js2-msg "msg.trail.backslash"
1491 "Trailing \\ in regular expression.")
1492
1493 (js2-msg "msg.re.unmatched.right.paren"
1494 "unmatched ) in regular expression.")
1495
1496 (js2-msg "msg.no.regexp"
1497 "Regular expressions are not available.")
1498
1499 (js2-msg "msg.bad.backref"
1500 "back-reference exceeds number of capturing parentheses.")
1501
1502 (js2-msg "msg.bad.regexp.compile"
1503 "Only one argument may be specified if the first "
1504 "argument to RegExp.prototype.compile is a RegExp object.")
1505
1506 ;; Parser
1507 (js2-msg "msg.got.syntax.errors"
1508 "Compilation produced %s syntax errors.")
1509
1510 (js2-msg "msg.var.redecl"
1511 "TypeError: redeclaration of var %s.")
1512
1513 (js2-msg "msg.const.redecl"
1514 "TypeError: redeclaration of const %s.")
1515
1516 (js2-msg "msg.let.redecl"
1517 "TypeError: redeclaration of variable %s.")
1518
1519 (js2-msg "msg.parm.redecl"
1520 "TypeError: redeclaration of formal parameter %s.")
1521
1522 (js2-msg "msg.fn.redecl"
1523 "TypeError: redeclaration of function %s.")
1524
1525 (js2-msg "msg.let.decl.not.in.block"
1526 "SyntaxError: let declaration not directly within block")
1527
1528 ;; NodeTransformer
1529 (js2-msg "msg.dup.label"
1530 "duplicated label")
1531
1532 (js2-msg "msg.undef.label"
1533 "undefined label")
1534
1535 (js2-msg "msg.bad.break"
1536 "unlabelled break must be inside loop or switch")
1537
1538 (js2-msg "msg.continue.outside"
1539 "continue must be inside loop")
1540
1541 (js2-msg "msg.continue.nonloop"
1542 "continue can only use labels of iteration statements")
1543
1544 (js2-msg "msg.bad.throw.eol"
1545 "Line terminator is not allowed between the throw "
1546 "keyword and throw expression.")
1547
1548 (js2-msg "msg.no.paren.parms"
1549 "missing ( before function parameters.")
1550
1551 (js2-msg "msg.no.parm"
1552 "missing formal parameter")
1553
1554 (js2-msg "msg.no.paren.after.parms"
1555 "missing ) after formal parameters")
1556
1557 (js2-msg "msg.no.brace.body"
1558 "missing '{' before function body")
1559
1560 (js2-msg "msg.no.brace.after.body"
1561 "missing } after function body")
1562
1563 (js2-msg "msg.no.paren.cond"
1564 "missing ( before condition")
1565
1566 (js2-msg "msg.no.paren.after.cond"
1567 "missing ) after condition")
1568
1569 (js2-msg "msg.no.semi.stmt"
1570 "missing ; before statement")
1571
1572 (js2-msg "msg.missing.semi"
1573 "missing ; after statement")
1574
1575 (js2-msg "msg.no.name.after.dot"
1576 "missing name after . operator")
1577
1578 (js2-msg "msg.no.name.after.coloncolon"
1579 "missing name after :: operator")
1580
1581 (js2-msg "msg.no.name.after.dotdot"
1582 "missing name after .. operator")
1583
1584 (js2-msg "msg.no.name.after.xmlAttr"
1585 "missing name after .@")
1586
1587 (js2-msg "msg.no.bracket.index"
1588 "missing ] in index expression")
1589
1590 (js2-msg "msg.no.paren.switch"
1591 "missing ( before switch expression")
1592
1593 (js2-msg "msg.no.paren.after.switch"
1594 "missing ) after switch expression")
1595
1596 (js2-msg "msg.no.brace.switch"
1597 "missing '{' before switch body")
1598
1599 (js2-msg "msg.bad.switch"
1600 "invalid switch statement")
1601
1602 (js2-msg "msg.no.colon.case"
1603 "missing : after case expression")
1604
1605 (js2-msg "msg.double.switch.default"
1606 "double default label in the switch statement")
1607
1608 (js2-msg "msg.no.while.do"
1609 "missing while after do-loop body")
1610
1611 (js2-msg "msg.no.paren.for"
1612 "missing ( after for")
1613
1614 (js2-msg "msg.no.semi.for"
1615 "missing ; after for-loop initializer")
1616
1617 (js2-msg "msg.no.semi.for.cond"
1618 "missing ; after for-loop condition")
1619
1620 (js2-msg "msg.in.after.for.name"
1621 "missing in after for")
1622
1623 (js2-msg "msg.no.paren.for.ctrl"
1624 "missing ) after for-loop control")
1625
1626 (js2-msg "msg.no.paren.with"
1627 "missing ( before with-statement object")
1628
1629 (js2-msg "msg.no.paren.after.with"
1630 "missing ) after with-statement object")
1631
1632 (js2-msg "msg.no.paren.after.let"
1633 "missing ( after let")
1634
1635 (js2-msg "msg.no.paren.let"
1636 "missing ) after variable list")
1637
1638 (js2-msg "msg.no.curly.let"
1639 "missing } after let statement")
1640
1641 (js2-msg "msg.bad.return"
1642 "invalid return")
1643
1644 (js2-msg "msg.no.brace.block"
1645 "missing } in compound statement")
1646
1647 (js2-msg "msg.bad.label"
1648 "invalid label")
1649
1650 (js2-msg "msg.bad.var"
1651 "missing variable name")
1652
1653 (js2-msg "msg.bad.var.init"
1654 "invalid variable initialization")
1655
1656 (js2-msg "msg.no.colon.cond"
1657 "missing : in conditional expression")
1658
1659 (js2-msg "msg.no.paren.arg"
1660 "missing ) after argument list")
1661
1662 (js2-msg "msg.no.bracket.arg"
1663 "missing ] after element list")
1664
1665 (js2-msg "msg.bad.prop"
1666 "invalid property id")
1667
1668 (js2-msg "msg.no.colon.prop"
1669 "missing : after property id")
1670
1671 (js2-msg "msg.no.brace.prop"
1672 "missing } after property list")
1673
1674 (js2-msg "msg.no.paren"
1675 "missing ) in parenthetical")
1676
1677 (js2-msg "msg.reserved.id"
1678 "identifier is a reserved word")
1679
1680 (js2-msg "msg.no.paren.catch"
1681 "missing ( before catch-block condition")
1682
1683 (js2-msg "msg.bad.catchcond"
1684 "invalid catch block condition")
1685
1686 (js2-msg "msg.catch.unreachable"
1687 "any catch clauses following an unqualified catch are unreachable")
1688
1689 (js2-msg "msg.no.brace.try"
1690 "missing '{' before try block")
1691
1692 (js2-msg "msg.no.brace.catchblock"
1693 "missing '{' before catch-block body")
1694
1695 (js2-msg "msg.try.no.catchfinally"
1696 "'try' without 'catch' or 'finally'")
1697
1698 (js2-msg "msg.no.return.value"
1699 "function %s does not always return a value")
1700
1701 (js2-msg "msg.anon.no.return.value"
1702 "anonymous function does not always return a value")
1703
1704 (js2-msg "msg.return.inconsistent"
1705 "return statement is inconsistent with previous usage")
1706
1707 (js2-msg "msg.generator.returns"
1708 "TypeError: generator function '%s' returns a value")
1709
1710 (js2-msg "msg.anon.generator.returns"
1711 "TypeError: anonymous generator function returns a value")
1712
1713 (js2-msg "msg.syntax"
1714 "syntax error")
1715
1716 (js2-msg "msg.unexpected.eof"
1717 "Unexpected end of file")
1718
1719 (js2-msg "msg.XML.bad.form"
1720 "illegally formed XML syntax")
1721
1722 (js2-msg "msg.XML.not.available"
1723 "XML runtime not available")
1724
1725 (js2-msg "msg.too.deep.parser.recursion"
1726 "Too deep recursion while parsing")
1727
1728 (js2-msg "msg.no.side.effects"
1729 "Code has no side effects")
1730
1731 (js2-msg "msg.extra.trailing.comma"
1732 "Trailing comma is not legal in an ECMA-262 object initializer")
1733
1734 (js2-msg "msg.array.trailing.comma"
1735 "Trailing comma yields different behavior across browsers")
1736
1737 (js2-msg "msg.equal.as.assign"
1738 (concat "Test for equality (==) mistyped as assignment (=)?"
1739 " (parenthesize to suppress warning)"))
1740
1741 (js2-msg "msg.var.hides.arg"
1742 "Variable %s hides argument")
1743
1744 (js2-msg "msg.destruct.assign.no.init"
1745 "Missing = in destructuring declaration")
1746
1747 ;; ScriptRuntime
1748 (js2-msg "msg.no.properties"
1749 "%s has no properties.")
1750
1751 (js2-msg "msg.invalid.iterator"
1752 "Invalid iterator value")
1753
1754 (js2-msg "msg.iterator.primitive"
1755 "__iterator__ returned a primitive value")
1756
1757 (js2-msg "msg.assn.create.strict"
1758 "Assignment to undeclared variable %s")
1759
1760 (js2-msg "msg.ref.undefined.prop"
1761 "Reference to undefined property '%s'")
1762
1763 (js2-msg "msg.prop.not.found"
1764 "Property %s not found.")
1765
1766 (js2-msg "msg.invalid.type"
1767 "Invalid JavaScript value of type %s")
1768
1769 (js2-msg "msg.primitive.expected"
1770 "Primitive type expected (had %s instead)")
1771
1772 (js2-msg "msg.namespace.expected"
1773 "Namespace object expected to left of :: (found %s instead)")
1774
1775 (js2-msg "msg.null.to.object"
1776 "Cannot convert null to an object.")
1777
1778 (js2-msg "msg.undef.to.object"
1779 "Cannot convert undefined to an object.")
1780
1781 (js2-msg "msg.cyclic.value"
1782 "Cyclic %s value not allowed.")
1783
1784 (js2-msg "msg.is.not.defined"
1785 "'%s' is not defined.")
1786
1787 (js2-msg "msg.undef.prop.read"
1788 "Cannot read property '%s' from %s")
1789
1790 (js2-msg "msg.undef.prop.write"
1791 "Cannot set property '%s' of %s to '%s'")
1792
1793 (js2-msg "msg.undef.prop.delete"
1794 "Cannot delete property '%s' of %s")
1795
1796 (js2-msg "msg.undef.method.call"
1797 "Cannot call method '%s' of %s")
1798
1799 (js2-msg "msg.undef.with"
1800 "Cannot apply 'with' to %s")
1801
1802 (js2-msg "msg.isnt.function"
1803 "%s is not a function, it is %s.")
1804
1805 (js2-msg "msg.isnt.function.in"
1806 "Cannot call property %s in object %s. "
1807 "It is not a function, it is '%s'.")
1808
1809 (js2-msg "msg.function.not.found"
1810 "Cannot find function %s.")
1811
1812 (js2-msg "msg.function.not.found.in"
1813 "Cannot find function %s in object %s.")
1814
1815 (js2-msg "msg.isnt.xml.object"
1816 "%s is not an xml object.")
1817
1818 (js2-msg "msg.no.ref.to.get"
1819 "%s is not a reference to read reference value.")
1820
1821 (js2-msg "msg.no.ref.to.set"
1822 "%s is not a reference to set reference value to %s.")
1823
1824 (js2-msg "msg.no.ref.from.function"
1825 "Function %s can not be used as the left-hand "
1826 "side of assignment or as an operand of ++ or -- operator.")
1827
1828 (js2-msg "msg.bad.default.value"
1829 "Object's getDefaultValue() method returned an object.")
1830
1831 (js2-msg "msg.instanceof.not.object"
1832 "Can't use instanceof on a non-object.")
1833
1834 (js2-msg "msg.instanceof.bad.prototype"
1835 "'prototype' property of %s is not an object.")
1836
1837 (js2-msg "msg.bad.radix"
1838 "illegal radix %s.")
1839
1840 ;; ScriptableObject
1841 (js2-msg "msg.default.value"
1842 "Cannot find default value for object.")
1843
1844 (js2-msg "msg.zero.arg.ctor"
1845 "Cannot load class '%s' which has no zero-parameter constructor.")
1846
1847 (js2-msg "msg.ctor.multiple.parms"
1848 "Can't define constructor or class %s since more than "
1849 "one constructor has multiple parameters.")
1850
1851 (js2-msg "msg.extend.scriptable"
1852 "%s must extend ScriptableObject in order to define property %s.")
1853
1854 (js2-msg "msg.bad.getter.parms"
1855 "In order to define a property, getter %s must have zero "
1856 "parameters or a single ScriptableObject parameter.")
1857
1858 (js2-msg "msg.obj.getter.parms"
1859 "Expected static or delegated getter %s to take "
1860 "a ScriptableObject parameter.")
1861
1862 (js2-msg "msg.getter.static"
1863 "Getter and setter must both be static or neither be static.")
1864
1865 (js2-msg "msg.setter.return"
1866 "Setter must have void return type: %s")
1867
1868 (js2-msg "msg.setter2.parms"
1869 "Two-parameter setter must take a ScriptableObject as "
1870 "its first parameter.")
1871
1872 (js2-msg "msg.setter1.parms"
1873 "Expected single parameter setter for %s")
1874
1875 (js2-msg "msg.setter2.expected"
1876 "Expected static or delegated setter %s to take two parameters.")
1877
1878 (js2-msg "msg.setter.parms"
1879 "Expected either one or two parameters for setter.")
1880
1881 (js2-msg "msg.setter.bad.type"
1882 "Unsupported parameter type '%s' in setter '%s'.")
1883
1884 (js2-msg "msg.add.sealed"
1885 "Cannot add a property to a sealed object: %s.")
1886
1887 (js2-msg "msg.remove.sealed"
1888 "Cannot remove a property from a sealed object: %s.")
1889
1890 (js2-msg "msg.modify.sealed"
1891 "Cannot modify a property of a sealed object: %s.")
1892
1893 (js2-msg "msg.modify.readonly"
1894 "Cannot modify readonly property: %s.")
1895
1896 ;; TokenStream
1897 (js2-msg "msg.missing.exponent"
1898 "missing exponent")
1899
1900 (js2-msg "msg.caught.nfe"
1901 "number format error")
1902
1903 (js2-msg "msg.unterminated.string.lit"
1904 "unterminated string literal")
1905
1906 (js2-msg "msg.unterminated.comment"
1907 "unterminated comment")
1908
1909 (js2-msg "msg.unterminated.re.lit"
1910 "unterminated regular expression literal")
1911
1912 (js2-msg "msg.invalid.re.flag"
1913 "invalid flag after regular expression")
1914
1915 (js2-msg "msg.no.re.input.for"
1916 "no input for %s")
1917
1918 (js2-msg "msg.illegal.character"
1919 "illegal character")
1920
1921 (js2-msg "msg.invalid.escape"
1922 "invalid Unicode escape sequence")
1923
1924 (js2-msg "msg.bad.namespace"
1925 "not a valid default namespace statement. "
1926 "Syntax is: default xml namespace = EXPRESSION;")
1927
1928 ;; TokensStream warnings
1929 (js2-msg "msg.bad.octal.literal"
1930 "illegal octal literal digit %s; "
1931 "interpreting it as a decimal digit")
1932
1933 (js2-msg "msg.reserved.keyword"
1934 "illegal usage of future reserved keyword %s; "
1935 "interpreting it as ordinary identifier")
1936
1937 (js2-msg "msg.script.is.not.constructor"
1938 "Script objects are not constructors.")
1939
1940 ;; Arrays
1941 (js2-msg "msg.arraylength.bad"
1942 "Inappropriate array length.")
1943
1944 ;; Arrays
1945 (js2-msg "msg.arraylength.too.big"
1946 "Array length %s exceeds supported capacity limit.")
1947
1948 ;; URI
1949 (js2-msg "msg.bad.uri"
1950 "Malformed URI sequence.")
1951
1952 ;; Number
1953 (js2-msg "msg.bad.precision"
1954 "Precision %s out of range.")
1955
1956 ;; NativeGenerator
1957 (js2-msg "msg.send.newborn"
1958 "Attempt to send value to newborn generator")
1959
1960 (js2-msg "msg.already.exec.gen"
1961 "Already executing generator")
1962
1963 (js2-msg "msg.StopIteration.invalid"
1964 "StopIteration may not be changed to an arbitrary object.")
1965
1966 ;; Interpreter
1967 (js2-msg "msg.yield.closing"
1968 "Yield from closing generator")
1969
1970 ;;; Utilities
1971
1972 (defun js2-delete-if (predicate list)
1973 "Remove all items satisfying PREDICATE in LIST."
1974 (loop for item in list
1975 if (not (funcall predicate item))
1976 collect item))
1977
1978 (defun js2-position (element list)
1979 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1980 Returns nil if element is not found in the list."
1981 (let ((count 0)
1982 found)
1983 (while (and list (not found))
1984 (if (eq element (car list))
1985 (setq found t)
1986 (setq count (1+ count)
1987 list (cdr list))))
1988 (if found count)))
1989
1990 (defun js2-find-if (predicate list)
1991 "Find first item satisfying PREDICATE in LIST."
1992 (let (result)
1993 (while (and list (not result))
1994 (if (funcall predicate (car list))
1995 (setq result (car list)))
1996 (setq list (cdr list)))
1997 result))
1998
1999 (defmacro js2-time (form)
2000 "Evaluate FORM, discard result, and return elapsed time in sec"
2001 (declare (debug t))
2002 (let ((beg (make-symbol "--js2-time-beg--"))
2003 (delta (make-symbol "--js2-time-end--")))
2004 `(let ((,beg (current-time))
2005 ,delta)
2006 ,form
2007 (/ (truncate (* (- (float-time (current-time))
2008 (float-time ,beg))
2009 10000))
2010 10000.0))))
2011
2012 (defsubst js2-same-line (pos)
2013 "Return t if POS is on the same line as current point."
2014 (and (>= pos (point-at-bol))
2015 (<= pos (point-at-eol))))
2016
2017 (defsubst js2-same-line-2 (p1 p2)
2018 "Return t if p1 is on the same line as p2."
2019 (save-excursion
2020 (goto-char p1)
2021 (js2-same-line p2)))
2022
2023 (defun js2-code-bug ()
2024 "Signal an error when we encounter an unexpected code path."
2025 (error "failed assertion"))
2026
2027 (defsubst js2-record-text-property (beg end prop value)
2028 "Record a text property to set when parsing finishes."
2029 (push (list beg end prop value) js2-mode-deferred-properties))
2030
2031 ;; I'd like to associate errors with nodes, but for now the
2032 ;; easiest thing to do is get the context info from the last token.
2033 (defsubst js2-record-parse-error (msg &optional arg pos len)
2034 (push (list (list msg arg)
2035 (or pos js2-token-beg)
2036 (or len (- js2-token-end js2-token-beg)))
2037 js2-parsed-errors))
2038
2039 (defsubst js2-report-error (msg &optional msg-arg pos len)
2040 "Signal a syntax error or record a parse error."
2041 (if js2-recover-from-parse-errors
2042 (js2-record-parse-error msg msg-arg pos len)
2043 (signal 'js2-syntax-error
2044 (list msg
2045 js2-ts-lineno
2046 (save-excursion
2047 (goto-char js2-ts-cursor)
2048 (current-column))
2049 js2-ts-hit-eof))))
2050
2051 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2052 (if js2-compiler-report-warning-as-error
2053 (js2-report-error msg msg-arg pos len)
2054 (push (list (list msg msg-arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2057 js2-parsed-warnings)))
2058
2059 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2060 (if js2-compiler-strict-mode
2061 (js2-report-warning msg-id msg-arg beg
2062 (and beg end (- end beg)))))
2063
2064 (put 'js2-syntax-error 'error-conditions
2065 '(error syntax-error js2-syntax-error))
2066 (put 'js2-syntax-error 'error-message "Syntax error")
2067
2068 (put 'js2-parse-error 'error-conditions
2069 '(error parse-error js2-parse-error))
2070 (put 'js2-parse-error 'error-message "Parse error")
2071
2072 (defmacro js2-clear-flag (flags flag)
2073 `(setq ,flags (logand ,flags (lognot ,flag))))
2074
2075 (defmacro js2-set-flag (flags flag)
2076 "Logical-or FLAG into FLAGS."
2077 `(setq ,flags (logior ,flags ,flag)))
2078
2079 (defsubst js2-flag-set-p (flags flag)
2080 (/= 0 (logand flags flag)))
2081
2082 (defsubst js2-flag-not-set-p (flags flag)
2083 (zerop (logand flags flag)))
2084
2085 ;; Stolen shamelessly from James Clark's nxml-mode.
2086 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2087 "Evaluate BODY without any text property changes modifying the buffer.
2088 Any text properties changes happen as usual but the changes are not treated as
2089 modifications to the buffer."
2090 (declare (indent 0) (debug t))
2091 (let ((modified (make-symbol "modified")))
2092 `(let ((,modified (buffer-modified-p))
2093 (inhibit-read-only t)
2094 (inhibit-modification-hooks t)
2095 (buffer-undo-list t)
2096 (deactivate-mark nil)
2097 ;; Apparently these avoid file locking problems.
2098 (buffer-file-name nil)
2099 (buffer-file-truename nil))
2100 (unwind-protect
2101 (progn ,@body)
2102 (unless ,modified
2103 (restore-buffer-modified-p nil))))))
2104
2105 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2106 "Evaluate BODY with the _ character set to be word-syntax."
2107 (declare (indent 0) (debug t))
2108 (let ((old-syntax (make-symbol "old-syntax")))
2109 `(let ((,old-syntax (string (char-syntax ?_))))
2110 (unwind-protect
2111 (progn
2112 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2113 ,@body)
2114 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2115
2116 (defsubst js2-char-uppercase-p (c)
2117 "Return t if C is an uppercase character.
2118 Handles unicode and latin chars properly."
2119 (/= c (downcase c)))
2120
2121 (defsubst js2-char-lowercase-p (c)
2122 "Return t if C is an uppercase character.
2123 Handles unicode and latin chars properly."
2124 (/= c (upcase c)))
2125
2126 ;;; AST struct and function definitions
2127
2128 ;; flags for ast node property 'member-type (used for e4x operators)
2129 (defvar js2-property-flag #x1 "property access: element is valid name")
2130 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2131 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2132
2133 (defsubst js2-relpos (pos anchor)
2134 "Convert POS to be relative to ANCHOR.
2135 If POS is nil, returns nil."
2136 (and pos (- pos anchor)))
2137
2138 (defsubst js2-make-pad (indent)
2139 (if (zerop indent)
2140 ""
2141 (make-string (* indent js2-basic-offset) ? )))
2142
2143 (defsubst js2-visit-ast (node callback)
2144 "Visit every node in ast NODE with visitor CALLBACK.
2145
2146 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2147 called twice: once to visit the node, and again after all the node's
2148 children have been processed. The END-P argument is nil on the first
2149 call and non-nil on the second call. The return value of the callback
2150 affects the traversal: if non-nil, the children of NODE are processed.
2151 If the callback returns nil, or if the node has no children, then the
2152 callback is called immediately with a non-nil END-P argument.
2153
2154 The node traversal is approximately lexical-order, although there
2155 are currently no guarantees around this."
2156 (if node
2157 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2158 ;; visit the node
2159 (when (funcall callback node nil)
2160 ;; visit the kids
2161 (cond
2162 ((eq vfunc 'js2-visit-none)
2163 nil) ; don't even bother calling it
2164 ;; Each AST node type has to define a `js2-visitor' function
2165 ;; that takes a node and a callback, and calls `js2-visit-ast'
2166 ;; on each child of the node.
2167 (vfunc
2168 (funcall vfunc node callback))
2169 (t
2170 (error "%s does not define a visitor-traversal function"
2171 (aref node 0)))))
2172 ;; call the end-visit
2173 (funcall callback node t))))
2174
2175 (defstruct (js2-node
2176 (:constructor nil)) ; abstract
2177 "Base AST node type."
2178 (type -1) ; token type
2179 (pos -1) ; start position of this AST node in parsed input
2180 (len 1) ; num characters spanned by the node
2181 props ; optional node property list (an alist)
2182 parent) ; link to parent node; null for root
2183
2184 (defsubst js2-node-get-prop (node prop &optional default)
2185 (or (cadr (assoc prop (js2-node-props node))) default))
2186
2187 (defsubst js2-node-set-prop (node prop value)
2188 (setf (js2-node-props node)
2189 (cons (list prop value) (js2-node-props node))))
2190
2191 (defsubst js2-fixup-starts (n nodes)
2192 "Adjust the start positions of NODES to be relative to N.
2193 Any node in the list may be nil, for convenience."
2194 (dolist (node nodes)
2195 (when node
2196 (setf (js2-node-pos node) (- (js2-node-pos node)
2197 (js2-node-pos n))))))
2198
2199 (defsubst js2-node-add-children (parent &rest nodes)
2200 "Set parent node of NODES to PARENT, and return PARENT.
2201 Does nothing if we're not recording parent links.
2202 If any given node in NODES is nil, doesn't record that link."
2203 (js2-fixup-starts parent nodes)
2204 (dolist (node nodes)
2205 (and node
2206 (setf (js2-node-parent node) parent))))
2207
2208 ;; Non-recursive since it's called a frightening number of times.
2209 (defsubst js2-node-abs-pos (n)
2210 (let ((pos (js2-node-pos n)))
2211 (while (setq n (js2-node-parent n))
2212 (setq pos (+ pos (js2-node-pos n))))
2213 pos))
2214
2215 (defsubst js2-node-abs-end (n)
2216 "Return absolute buffer position of end of N."
2217 (+ (js2-node-abs-pos n) (js2-node-len n)))
2218
2219 ;; It's important to make sure block nodes have a lisp list for the
2220 ;; child nodes, to limit printing recursion depth in an AST that
2221 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2222 ;; a sufficiently large vector tree.
2223
2224 (defstruct (js2-block-node
2225 (:include js2-node)
2226 (:constructor nil)
2227 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2228 (pos js2-token-beg)
2229 len
2230 props
2231 kids)))
2232 "A block of statements."
2233 kids) ; a lisp list of the child statement nodes
2234
2235 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2236 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2237
2238 (defsubst js2-visit-block (ast callback)
2239 "Visit the `js2-block-node' children of AST."
2240 (dolist (kid (js2-block-node-kids ast))
2241 (js2-visit-ast kid callback)))
2242
2243 (defun js2-print-block (n i)
2244 (let ((pad (js2-make-pad i)))
2245 (insert pad "{\n")
2246 (dolist (kid (js2-block-node-kids n))
2247 (js2-print-ast kid (1+ i)))
2248 (insert pad "}")))
2249
2250 (defstruct (js2-scope
2251 (:include js2-block-node)
2252 (:constructor nil)
2253 (:constructor make-js2-scope (&key (type js2-BLOCK)
2254 (pos js2-token-beg)
2255 len
2256 kids)))
2257 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2258 ;; I don't have one of those handy, so I'll use an alist for now.
2259 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2260 ;; and is much lighter-weight to construct (both CPU and mem).
2261 ;; The keys are interned strings (symbols) for faster lookup.
2262 ;; Should switch to hybrid alist/hashtable eventually.
2263 symbol-table ; an alist of (symbol . js2-symbol)
2264 parent-scope ; a `js2-scope'
2265 top) ; top-level `js2-scope' (script/function)
2266
2267 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2268 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2269
2270 (defun js2-scope-set-parent-scope (scope parent)
2271 (setf (js2-scope-parent-scope scope) parent
2272 (js2-scope-top scope) (if (null parent)
2273 scope
2274 (js2-scope-top parent))))
2275
2276 (defun js2-node-get-enclosing-scope (node)
2277 "Return the innermost `js2-scope' node surrounding NODE.
2278 Returns nil if there is no enclosing scope node."
2279 (let ((parent (js2-node-parent node)))
2280 (while (not (js2-scope-p parent))
2281 (setq parent (js2-node-parent parent)))
2282 parent))
2283
2284 (defun js2-get-defining-scope (scope name)
2285 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2286 Returns `js2-scope' in which NAME is defined, or nil if not found."
2287 (let ((sym (if (symbolp name)
2288 name
2289 (intern name)))
2290 table
2291 result
2292 (continue t))
2293 (while (and scope continue)
2294 (if (and (setq table (js2-scope-symbol-table scope))
2295 (assq sym table))
2296 (setq continue nil
2297 result scope)
2298 (setq scope (js2-scope-parent-scope scope))))
2299 result))
2300
2301 (defsubst js2-scope-get-symbol (scope name)
2302 "Return symbol table entry for NAME in SCOPE.
2303 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2304 (and (js2-scope-symbol-table scope)
2305 (cdr (assq (if (symbolp name)
2306 name
2307 (intern name))
2308 (js2-scope-symbol-table scope)))))
2309
2310 (defsubst js2-scope-put-symbol (scope name symbol)
2311 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2312 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2313 (let* ((table (js2-scope-symbol-table scope))
2314 (sym (if (symbolp name) name (intern name)))
2315 (entry (assq sym table)))
2316 (if entry
2317 (setcdr entry symbol)
2318 (push (cons sym symbol)
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defstruct (js2-symbol
2322 (:constructor nil)
2323 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2324 "A symbol table entry."
2325 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2326 ;; js2-LET, or js2-CONST
2327 decl-type
2328 name ; string
2329 ast-node) ; a `js2-node'
2330
2331 (defstruct (js2-error-node
2332 (:include js2-node)
2333 (:constructor nil) ; silence emacs21 byte-compiler
2334 (:constructor make-js2-error-node (&key (type js2-ERROR)
2335 (pos js2-token-beg)
2336 len)))
2337 "AST node representing a parse error.")
2338
2339 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2340 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2341
2342 (defstruct (js2-script-node
2343 (:include js2-scope)
2344 (:constructor nil)
2345 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2346 (pos js2-token-beg)
2347 len
2348 var-decls
2349 fun-decls)))
2350 functions ; lisp list of nested functions
2351 regexps ; lisp list of (string . flags)
2352 symbols ; alist (every symbol gets unique index)
2353 (param-count 0)
2354 var-names ; vector of string names
2355 consts ; bool-vector matching var-decls
2356 (temp-number 0)) ; for generating temp variables
2357
2358 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2359 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2360
2361 (defun js2-print-script (node indent)
2362 (dolist (kid (js2-block-node-kids node))
2363 (js2-print-ast kid indent)))
2364
2365 (defstruct (js2-ast-root
2366 (:include js2-script-node)
2367 (:constructor nil)
2368 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2369 (pos js2-token-beg)
2370 len
2371 buffer)))
2372 "The root node of a js2 AST."
2373 buffer ; the source buffer from which the code was parsed
2374 comments ; a lisp list of comments, ordered by start position
2375 errors ; a lisp list of errors found during parsing
2376 warnings ; a lisp list of warnings found during parsing
2377 node-count) ; number of nodes in the tree, including the root
2378
2379 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2380 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2381
2382 (defun js2-visit-ast-root (ast callback)
2383 (dolist (kid (js2-ast-root-kids ast))
2384 (js2-visit-ast kid callback))
2385 (dolist (comment (js2-ast-root-comments ast))
2386 (js2-visit-ast comment callback)))
2387
2388 (defstruct (js2-comment-node
2389 (:include js2-node)
2390 (:constructor nil)
2391 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2392 (pos js2-token-beg)
2393 len
2394 (format js2-ts-comment-type))))
2395 format) ; 'line, 'block, 'jsdoc or 'html
2396
2397 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2398 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2399
2400 (defun js2-print-comment (n i)
2401 ;; We really ought to link end-of-line comments to their nodes.
2402 ;; Or maybe we could add a new comment type, 'endline.
2403 (insert (js2-make-pad i)
2404 (js2-node-string n)))
2405
2406 (defstruct (js2-expr-stmt-node
2407 (:include js2-node)
2408 (:constructor nil)
2409 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2410 (pos js2-ts-cursor)
2411 len
2412 expr)))
2413 "An expression statement."
2414 expr)
2415
2416 (defsubst js2-expr-stmt-node-set-has-result (node)
2417 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2418 (setf (js2-node-type node) js2-EXPR_RESULT))
2419
2420 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2421 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2422
2423 (defun js2-visit-expr-stmt-node (n v)
2424 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2425
2426 (defun js2-print-expr-stmt-node (n indent)
2427 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2428 (insert ";\n"))
2429
2430 (defstruct (js2-loop-node
2431 (:include js2-scope)
2432 (:constructor nil))
2433 "Abstract supertype of loop nodes."
2434 body ; a `js2-block-node'
2435 lp ; position of left-paren, nil if omitted
2436 rp) ; position of right-paren, nil if omitted
2437
2438 (defstruct (js2-do-node
2439 (:include js2-loop-node)
2440 (:constructor nil)
2441 (:constructor make-js2-do-node (&key (type js2-DO)
2442 (pos js2-token-beg)
2443 len
2444 body
2445 condition
2446 while-pos
2447 lp
2448 rp)))
2449 "AST node for do-loop."
2450 condition ; while (expression)
2451 while-pos) ; buffer position of 'while' keyword
2452
2453 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2454 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2455
2456 (defun js2-visit-do-node (n v)
2457 (js2-visit-ast (js2-do-node-body n) v)
2458 (js2-visit-ast (js2-do-node-condition n) v))
2459
2460 (defun js2-print-do-node (n i)
2461 (let ((pad (js2-make-pad i)))
2462 (insert pad "do {\n")
2463 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2464 (js2-print-ast kid (1+ i)))
2465 (insert pad "} while (")
2466 (js2-print-ast (js2-do-node-condition n) 0)
2467 (insert ");\n")))
2468
2469 (defstruct (js2-while-node
2470 (:include js2-loop-node)
2471 (:constructor nil)
2472 (:constructor make-js2-while-node (&key (type js2-WHILE)
2473 (pos js2-token-beg)
2474 len
2475 body
2476 condition
2477 lp
2478 rp)))
2479 "AST node for while-loop."
2480 condition) ; while-condition
2481
2482 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2483 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2484
2485 (defun js2-visit-while-node (n v)
2486 (js2-visit-ast (js2-while-node-condition n) v)
2487 (js2-visit-ast (js2-while-node-body n) v))
2488
2489 (defun js2-print-while-node (n i)
2490 (let ((pad (js2-make-pad i)))
2491 (insert pad "while (")
2492 (js2-print-ast (js2-while-node-condition n) 0)
2493 (insert ") {\n")
2494 (js2-print-body (js2-while-node-body n) (1+ i))
2495 (insert pad "}\n")))
2496
2497 (defstruct (js2-for-node
2498 (:include js2-loop-node)
2499 (:constructor nil)
2500 (:constructor make-js2-for-node (&key (type js2-FOR)
2501 (pos js2-ts-cursor)
2502 len
2503 body
2504 init
2505 condition
2506 update
2507 lp
2508 rp)))
2509 "AST node for a C-style for-loop."
2510 init ; initialization expression
2511 condition ; loop condition
2512 update) ; update clause
2513
2514 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2515 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2516
2517 (defun js2-visit-for-node (n v)
2518 (js2-visit-ast (js2-for-node-init n) v)
2519 (js2-visit-ast (js2-for-node-condition n) v)
2520 (js2-visit-ast (js2-for-node-update n) v)
2521 (js2-visit-ast (js2-for-node-body n) v))
2522
2523 (defun js2-print-for-node (n i)
2524 (let ((pad (js2-make-pad i)))
2525 (insert pad "for (")
2526 (js2-print-ast (js2-for-node-init n) 0)
2527 (insert "; ")
2528 (js2-print-ast (js2-for-node-condition n) 0)
2529 (insert "; ")
2530 (js2-print-ast (js2-for-node-update n) 0)
2531 (insert ") {\n")
2532 (js2-print-body (js2-for-node-body n) (1+ i))
2533 (insert pad "}\n")))
2534
2535 (defstruct (js2-for-in-node
2536 (:include js2-loop-node)
2537 (:constructor nil)
2538 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2539 (pos js2-ts-cursor)
2540 len
2541 body
2542 iterator
2543 object
2544 in-pos
2545 each-pos
2546 foreach-p
2547 lp
2548 rp)))
2549 "AST node for a for..in loop."
2550 iterator ; [var] foo in ...
2551 object ; object over which we're iterating
2552 in-pos ; buffer position of 'in' keyword
2553 each-pos ; buffer position of 'each' keyword, if foreach-p
2554 foreach-p) ; t if it's a for-each loop
2555
2556 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2557 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2558
2559 (defun js2-visit-for-in-node (n v)
2560 (js2-visit-ast (js2-for-in-node-iterator n) v)
2561 (js2-visit-ast (js2-for-in-node-object n) v)
2562 (js2-visit-ast (js2-for-in-node-body n) v))
2563
2564 (defun js2-print-for-in-node (n i)
2565 (let ((pad (js2-make-pad i))
2566 (foreach (js2-for-in-node-foreach-p n)))
2567 (insert pad "for ")
2568 (if foreach
2569 (insert "each "))
2570 (insert "(")
2571 (js2-print-ast (js2-for-in-node-iterator n) 0)
2572 (insert " in ")
2573 (js2-print-ast (js2-for-in-node-object n) 0)
2574 (insert ") {\n")
2575 (js2-print-body (js2-for-in-node-body n) (1+ i))
2576 (insert pad "}\n")))
2577
2578 (defstruct (js2-return-node
2579 (:include js2-node)
2580 (:constructor nil)
2581 (:constructor make-js2-return-node (&key (type js2-RETURN)
2582 (pos js2-ts-cursor)
2583 len
2584 retval)))
2585 "AST node for a return statement."
2586 retval) ; expression to return, or 'undefined
2587
2588 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2589 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2590
2591 (defun js2-visit-return-node (n v)
2592 (js2-visit-ast (js2-return-node-retval n) v))
2593
2594 (defun js2-print-return-node (n i)
2595 (insert (js2-make-pad i) "return")
2596 (when (js2-return-node-retval n)
2597 (insert " ")
2598 (js2-print-ast (js2-return-node-retval n) 0))
2599 (insert ";\n"))
2600
2601 (defstruct (js2-if-node
2602 (:include js2-node)
2603 (:constructor nil)
2604 (:constructor make-js2-if-node (&key (type js2-IF)
2605 (pos js2-ts-cursor)
2606 len
2607 condition
2608 then-part
2609 else-pos
2610 else-part
2611 lp
2612 rp)))
2613 "AST node for an if-statement."
2614 condition ; expression
2615 then-part ; statement or block
2616 else-pos ; optional buffer position of 'else' keyword
2617 else-part ; optional statement or block
2618 lp ; position of left-paren, nil if omitted
2619 rp) ; position of right-paren, nil if omitted
2620
2621 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2622 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2623
2624 (defun js2-visit-if-node (n v)
2625 (js2-visit-ast (js2-if-node-condition n) v)
2626 (js2-visit-ast (js2-if-node-then-part n) v)
2627 (js2-visit-ast (js2-if-node-else-part n) v))
2628
2629 (defun js2-print-if-node (n i)
2630 (let ((pad (js2-make-pad i))
2631 (then-part (js2-if-node-then-part n))
2632 (else-part (js2-if-node-else-part n)))
2633 (insert pad "if (")
2634 (js2-print-ast (js2-if-node-condition n) 0)
2635 (insert ") {\n")
2636 (js2-print-body then-part (1+ i))
2637 (insert pad "}")
2638 (cond
2639 ((not else-part)
2640 (insert "\n"))
2641 ((js2-if-node-p else-part)
2642 (insert " else ")
2643 (js2-print-body else-part i))
2644 (t
2645 (insert " else {\n")
2646 (js2-print-body else-part (1+ i))
2647 (insert pad "}\n")))))
2648
2649 (defstruct (js2-try-node
2650 (:include js2-node)
2651 (:constructor nil)
2652 (:constructor make-js2-try-node (&key (type js2-TRY)
2653 (pos js2-ts-cursor)
2654 len
2655 try-block
2656 catch-clauses
2657 finally-block)))
2658 "AST node for a try-statement."
2659 try-block
2660 catch-clauses ; a lisp list of `js2-catch-node'
2661 finally-block) ; a `js2-finally-node'
2662
2663 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2664 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2665
2666 (defun js2-visit-try-node (n v)
2667 (js2-visit-ast (js2-try-node-try-block n) v)
2668 (dolist (clause (js2-try-node-catch-clauses n))
2669 (js2-visit-ast clause v))
2670 (js2-visit-ast (js2-try-node-finally-block n) v))
2671
2672 (defun js2-print-try-node (n i)
2673 (let ((pad (js2-make-pad i))
2674 (catches (js2-try-node-catch-clauses n))
2675 (finally (js2-try-node-finally-block n)))
2676 (insert pad "try {\n")
2677 (js2-print-body (js2-try-node-try-block n) (1+ i))
2678 (insert pad "}")
2679 (when catches
2680 (dolist (catch catches)
2681 (js2-print-ast catch i)))
2682 (if finally
2683 (js2-print-ast finally i)
2684 (insert "\n"))))
2685
2686 (defstruct (js2-catch-node
2687 (:include js2-node)
2688 (:constructor nil)
2689 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2690 (pos js2-ts-cursor)
2691 len
2692 var-name
2693 guard-kwd
2694 guard-expr
2695 block
2696 lp
2697 rp)))
2698 "AST node for a catch clause."
2699 var-name ; a `js2-name-node'
2700 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2701 guard-expr ; catch condition, a `js2-node'
2702 block ; statements, a `js2-block-node'
2703 lp ; buffer position of left-paren, nil if omitted
2704 rp) ; buffer position of right-paren, nil if omitted
2705
2706 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2707 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2708
2709 (defun js2-visit-catch-node (n v)
2710 (js2-visit-ast (js2-catch-node-var-name n) v)
2711 (when (js2-catch-node-guard-kwd n)
2712 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2713 (js2-visit-ast (js2-catch-node-block n) v))
2714
2715 (defun js2-print-catch-node (n i)
2716 (let ((pad (js2-make-pad i))
2717 (guard-kwd (js2-catch-node-guard-kwd n))
2718 (guard-expr (js2-catch-node-guard-expr n)))
2719 (insert " catch (")
2720 (js2-print-ast (js2-catch-node-var-name n) 0)
2721 (when guard-kwd
2722 (insert " if ")
2723 (js2-print-ast guard-expr 0))
2724 (insert ") {\n")
2725 (js2-print-body (js2-catch-node-block n) (1+ i))
2726 (insert pad "}")))
2727
2728 (defstruct (js2-finally-node
2729 (:include js2-node)
2730 (:constructor nil)
2731 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2732 (pos js2-ts-cursor)
2733 len
2734 body)))
2735 "AST node for a finally clause."
2736 body) ; a `js2-node', often but not always a block node
2737
2738 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2739 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2740
2741 (defun js2-visit-finally-node (n v)
2742 (js2-visit-ast (js2-finally-node-body n) v))
2743
2744 (defun js2-print-finally-node (n i)
2745 (let ((pad (js2-make-pad i)))
2746 (insert " finally {\n")
2747 (js2-print-body (js2-finally-node-body n) (1+ i))
2748 (insert pad "}\n")))
2749
2750 (defstruct (js2-switch-node
2751 (:include js2-node)
2752 (:constructor nil)
2753 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2754 (pos js2-ts-cursor)
2755 len
2756 discriminant
2757 cases
2758 lp
2759 rp)))
2760 "AST node for a switch statement."
2761 discriminant ; a `js2-node' (switch expression)
2762 cases ; a lisp list of `js2-case-node'
2763 lp ; position of open-paren for discriminant, nil if omitted
2764 rp) ; position of close-paren for discriminant, nil if omitted
2765
2766 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2767 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2768
2769 (defun js2-visit-switch-node (n v)
2770 (js2-visit-ast (js2-switch-node-discriminant n) v)
2771 (dolist (c (js2-switch-node-cases n))
2772 (js2-visit-ast c v)))
2773
2774 (defun js2-print-switch-node (n i)
2775 (let ((pad (js2-make-pad i))
2776 (cases (js2-switch-node-cases n)))
2777 (insert pad "switch (")
2778 (js2-print-ast (js2-switch-node-discriminant n) 0)
2779 (insert ") {\n")
2780 (dolist (case cases)
2781 (js2-print-ast case i))
2782 (insert pad "}\n")))
2783
2784 (defstruct (js2-case-node
2785 (:include js2-block-node)
2786 (:constructor nil)
2787 (:constructor make-js2-case-node (&key (type js2-CASE)
2788 (pos js2-ts-cursor)
2789 len
2790 kids
2791 expr)))
2792 "AST node for a case clause of a switch statement."
2793 expr) ; the case expression (nil for default)
2794
2795 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2796 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2797
2798 (defun js2-visit-case-node (n v)
2799 (js2-visit-ast (js2-case-node-expr n) v)
2800 (js2-visit-block n v))
2801
2802 (defun js2-print-case-node (n i)
2803 (let ((pad (js2-make-pad i))
2804 (expr (js2-case-node-expr n)))
2805 (insert pad)
2806 (if (null expr)
2807 (insert "default:\n")
2808 (insert "case ")
2809 (js2-print-ast expr 0)
2810 (insert ":\n"))
2811 (dolist (kid (js2-case-node-kids n))
2812 (js2-print-ast kid (1+ i)))))
2813
2814 (defstruct (js2-throw-node
2815 (:include js2-node)
2816 (:constructor nil)
2817 (:constructor make-js2-throw-node (&key (type js2-THROW)
2818 (pos js2-ts-cursor)
2819 len
2820 expr)))
2821 "AST node for a throw statement."
2822 expr) ; the expression to throw
2823
2824 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2825 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2826
2827 (defun js2-visit-throw-node (n v)
2828 (js2-visit-ast (js2-throw-node-expr n) v))
2829
2830 (defun js2-print-throw-node (n i)
2831 (insert (js2-make-pad i) "throw ")
2832 (js2-print-ast (js2-throw-node-expr n) 0)
2833 (insert ";\n"))
2834
2835 (defstruct (js2-with-node
2836 (:include js2-node)
2837 (:constructor nil)
2838 (:constructor make-js2-with-node (&key (type js2-WITH)
2839 (pos js2-ts-cursor)
2840 len
2841 object
2842 body
2843 lp
2844 rp)))
2845 "AST node for a with-statement."
2846 object
2847 body
2848 lp ; buffer position of left-paren around object, nil if omitted
2849 rp) ; buffer position of right-paren around object, nil if omitted
2850
2851 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2852 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2853
2854 (defun js2-visit-with-node (n v)
2855 (js2-visit-ast (js2-with-node-object n) v)
2856 (js2-visit-ast (js2-with-node-body n) v))
2857
2858 (defun js2-print-with-node (n i)
2859 (let ((pad (js2-make-pad i)))
2860 (insert pad "with (")
2861 (js2-print-ast (js2-with-node-object n) 0)
2862 (insert ") {\n")
2863 (js2-print-body (js2-with-node-body n) (1+ i))
2864 (insert pad "}\n")))
2865
2866 (defstruct (js2-label-node
2867 (:include js2-node)
2868 (:constructor nil)
2869 (:constructor make-js2-label-node (&key (type js2-LABEL)
2870 (pos js2-ts-cursor)
2871 len
2872 name)))
2873 "AST node for a statement label or case label."
2874 name ; a string
2875 loop) ; for validating and code-generating continue-to-label
2876
2877 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2878 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2879
2880 (defun js2-print-label (n i)
2881 (insert (js2-make-pad i)
2882 (js2-label-node-name n)
2883 ":\n"))
2884
2885 (defstruct (js2-labeled-stmt-node
2886 (:include js2-node)
2887 (:constructor nil)
2888 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2889 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2890 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2891 (pos js2-ts-cursor)
2892 len
2893 labels
2894 stmt)))
2895 "AST node for a statement with one or more labels.
2896 Multiple labels for a statement are collapsed into the labels field."
2897 labels ; lisp list of `js2-label-node'
2898 stmt) ; the statement these labels are for
2899
2900 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2901 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2902
2903 (defun js2-get-label-by-name (lbl-stmt name)
2904 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2905 Returns nil if no such label is in the list."
2906 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2907 result)
2908 (while (and label-list (not result))
2909 (if (string= (js2-label-node-name (car label-list)) name)
2910 (setq result (car label-list))
2911 (setq label-list (cdr label-list))))
2912 result))
2913
2914 (defun js2-visit-labeled-stmt (n v)
2915 (dolist (label (js2-labeled-stmt-node-labels n))
2916 (js2-visit-ast label v))
2917 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2918
2919 (defun js2-print-labeled-stmt (n i)
2920 (dolist (label (js2-labeled-stmt-node-labels n))
2921 (js2-print-ast label i))
2922 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2923
2924 (defun js2-labeled-stmt-node-contains (node label)
2925 "Return t if NODE contains LABEL in its label set.
2926 NODE is a `js2-labels-node'. LABEL is an identifier."
2927 (loop for nl in (js2-labeled-stmt-node-labels node)
2928 if (string= label (js2-label-node-name nl))
2929 return t
2930 finally return nil))
2931
2932 (defsubst js2-labeled-stmt-node-add-label (node label)
2933 "Add a `js2-label-node' to the label set for this statement."
2934 (setf (js2-labeled-stmt-node-labels node)
2935 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2936
2937 (defstruct (js2-jump-node
2938 (:include js2-node)
2939 (:constructor nil))
2940 "Abstract supertype of break and continue nodes."
2941 label ; `js2-name-node' for location of label identifier, if present
2942 target) ; target js2-labels-node or loop/switch statement
2943
2944 (defun js2-visit-jump-node (n v)
2945 (js2-visit-ast (js2-jump-node-label n) v))
2946
2947 (defstruct (js2-break-node
2948 (:include js2-jump-node)
2949 (:constructor nil)
2950 (:constructor make-js2-break-node (&key (type js2-BREAK)
2951 (pos js2-ts-cursor)
2952 len
2953 label
2954 target)))
2955 "AST node for a break statement.
2956 The label field is a `js2-name-node', possibly nil, for the named label
2957 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2958 is the target of the break - a label node or enclosing loop/switch statement.")
2959
2960 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2961 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2962
2963 (defun js2-print-break-node (n i)
2964 (insert (js2-make-pad i) "break")
2965 (when (js2-break-node-label n)
2966 (insert " ")
2967 (js2-print-ast (js2-break-node-label n) 0))
2968 (insert ";\n"))
2969
2970 (defstruct (js2-continue-node
2971 (:include js2-jump-node)
2972 (:constructor nil)
2973 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2974 (pos js2-ts-cursor)
2975 len
2976 label
2977 target)))
2978 "AST node for a continue statement.
2979 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2980 It is nil if continue specifies no label. The target field is the jump target:
2981 a `js2-label-node' or the innermost enclosing loop.")
2982
2983 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2984 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2985
2986 (defun js2-print-continue-node (n i)
2987 (insert (js2-make-pad i) "continue")
2988 (when (js2-continue-node-label n)
2989 (insert " ")
2990 (js2-print-ast (js2-continue-node-label n) 0))
2991 (insert ";\n"))
2992
2993 (defstruct (js2-function-node
2994 (:include js2-script-node)
2995 (:constructor nil)
2996 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2997 (pos js2-ts-cursor)
2998 len
2999 (ftype 'FUNCTION)
3000 (form 'FUNCTION_STATEMENT)
3001 (name "")
3002 params
3003 body
3004 lp
3005 rp)))
3006 "AST node for a function declaration.
3007 The `params' field is a lisp list of nodes. Each node is either a simple
3008 `js2-name-node', or if it's a destructuring-assignment parameter, a
3009 `js2-array-node' or `js2-object-node'."
3010 ftype ; FUNCTION, GETTER or SETTER
3011 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3012 name ; function name (a `js2-name-node', or nil if anonymous)
3013 params ; a lisp list of destructuring forms or simple name nodes
3014 body ; a `js2-block-node' or expression node (1.8 only)
3015 lp ; position of arg-list open-paren, or nil if omitted
3016 rp ; position of arg-list close-paren, or nil if omitted
3017 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3018 needs-activation ; t if we need an activation object for this frame
3019 is-generator ; t if this function contains a yield
3020 member-expr) ; nonstandard Ecma extension from Rhino
3021
3022 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3023 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3024
3025 (defun js2-visit-function-node (n v)
3026 (js2-visit-ast (js2-function-node-name n) v)
3027 (dolist (p (js2-function-node-params n))
3028 (js2-visit-ast p v))
3029 (js2-visit-ast (js2-function-node-body n) v))
3030
3031 (defun js2-print-function-node (n i)
3032 (let ((pad (js2-make-pad i))
3033 (getter (js2-node-get-prop n 'GETTER_SETTER))
3034 (name (js2-function-node-name n))
3035 (params (js2-function-node-params n))
3036 (body (js2-function-node-body n))
3037 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3038 (unless getter
3039 (insert pad "function"))
3040 (when name
3041 (insert " ")
3042 (js2-print-ast name 0))
3043 (insert "(")
3044 (loop with len = (length params)
3045 for param in params
3046 for count from 1
3047 do
3048 (js2-print-ast param 0)
3049 (if (< count len)
3050 (insert ", ")))
3051 (insert ") {")
3052 (unless expr
3053 (insert "\n"))
3054 ;; TODO: fix this to be smarter about indenting, etc.
3055 (js2-print-body body (1+ i))
3056 (insert pad "}")
3057 (unless expr
3058 (insert "\n"))))
3059
3060 (defsubst js2-function-name (node)
3061 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3062 (and (js2-function-node-name node)
3063 (js2-name-node-name (js2-function-node-name node))))
3064
3065 ;; Having this be an expression node makes it more flexible.
3066 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3067 ;; that work better if you assume it's an expression. Whenever we have
3068 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3069 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3070 (defstruct (js2-var-decl-node
3071 (:include js2-node)
3072 (:constructor nil)
3073 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3074 (pos js2-token-beg)
3075 len
3076 kids
3077 decl-type)))
3078 "AST node for a variable declaration list (VAR, CONST or LET).
3079 The node bounds differ depending on the declaration type. For VAR or
3080 CONST declarations, the bounds include the var/const keyword. For LET
3081 declarations, the node begins at the position of the first child."
3082 kids ; a lisp list of `js2-var-init-node' structs.
3083 decl-type) ; js2-VAR, js2-CONST or js2-LET
3084
3085 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3086 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3087
3088 (defun js2-visit-var-decl (n v)
3089 (dolist (kid (js2-var-decl-node-kids n))
3090 (js2-visit-ast kid v)))
3091
3092 (defun js2-print-var-decl (n i)
3093 (let ((pad (js2-make-pad i))
3094 (tt (js2-var-decl-node-decl-type n)))
3095 (insert pad)
3096 (insert (cond
3097 ((= tt js2-VAR) "var ")
3098 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3099 ((= tt js2-CONST) "const ")
3100 (t
3101 (error "malformed var-decl node"))))
3102 (loop with kids = (js2-var-decl-node-kids n)
3103 with len = (length kids)
3104 for kid in kids
3105 for count from 1
3106 do
3107 (js2-print-ast kid 0)
3108 (if (< count len)
3109 (insert ", ")))))
3110
3111 (defstruct (js2-var-init-node
3112 (:include js2-node)
3113 (:constructor nil)
3114 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3115 (pos js2-ts-cursor)
3116 len
3117 target
3118 initializer)))
3119 "AST node for a variable declaration.
3120 The type field will be js2-CONST for a const decl."
3121 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3122 initializer) ; initializer expression, a `js2-node'
3123
3124 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3125 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3126
3127 (defun js2-visit-var-init-node (n v)
3128 (js2-visit-ast (js2-var-init-node-target n) v)
3129 (js2-visit-ast (js2-var-init-node-initializer n) v))
3130
3131 (defun js2-print-var-init-node (n i)
3132 (let ((pad (js2-make-pad i))
3133 (name (js2-var-init-node-target n))
3134 (init (js2-var-init-node-initializer n)))
3135 (insert pad)
3136 (js2-print-ast name 0)
3137 (when init
3138 (insert " = ")
3139 (js2-print-ast init 0))))
3140
3141 (defstruct (js2-cond-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3145 (pos js2-ts-cursor)
3146 len
3147 test-expr
3148 true-expr
3149 false-expr
3150 q-pos
3151 c-pos)))
3152 "AST node for the ternary operator"
3153 test-expr
3154 true-expr
3155 false-expr
3156 q-pos ; buffer position of ?
3157 c-pos) ; buffer position of :
3158
3159 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3160 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3161
3162 (defun js2-visit-cond-node (n v)
3163 (js2-visit-ast (js2-cond-node-test-expr n) v)
3164 (js2-visit-ast (js2-cond-node-true-expr n) v)
3165 (js2-visit-ast (js2-cond-node-false-expr n) v))
3166
3167 (defun js2-print-cond-node (n i)
3168 (let ((pad (js2-make-pad i)))
3169 (insert pad)
3170 (js2-print-ast (js2-cond-node-test-expr n) 0)
3171 (insert " ? ")
3172 (js2-print-ast (js2-cond-node-true-expr n) 0)
3173 (insert " : ")
3174 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3175
3176 (defstruct (js2-infix-node
3177 (:include js2-node)
3178 (:constructor nil)
3179 (:constructor make-js2-infix-node (&key type
3180 (pos js2-ts-cursor)
3181 len
3182 op-pos
3183 left
3184 right)))
3185 "Represents infix expressions.
3186 Includes assignment ops like `|=', and the comma operator.
3187 The type field inherited from `js2-node' holds the operator."
3188 op-pos ; buffer position where operator begins
3189 left ; any `js2-node'
3190 right) ; any `js2-node'
3191
3192 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3193 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3194
3195 (defun js2-visit-infix-node (n v)
3196 (js2-visit-ast (js2-infix-node-left n) v)
3197 (js2-visit-ast (js2-infix-node-right n) v))
3198
3199 (defconst js2-operator-tokens
3200 (let ((table (make-hash-table :test 'eq))
3201 (tokens
3202 (list (cons js2-IN "in")
3203 (cons js2-TYPEOF "typeof")
3204 (cons js2-INSTANCEOF "instanceof")
3205 (cons js2-DELPROP "delete")
3206 (cons js2-COMMA ",")
3207 (cons js2-COLON ":")
3208 (cons js2-OR "||")
3209 (cons js2-AND "&&")
3210 (cons js2-INC "++")
3211 (cons js2-DEC "--")
3212 (cons js2-BITOR "|")
3213 (cons js2-BITXOR "^")
3214 (cons js2-BITAND "&")
3215 (cons js2-EQ "==")
3216 (cons js2-NE "!=")
3217 (cons js2-LT "<")
3218 (cons js2-LE "<=")
3219 (cons js2-GT ">")
3220 (cons js2-GE ">=")
3221 (cons js2-LSH "<<")
3222 (cons js2-RSH ">>")
3223 (cons js2-URSH ">>>")
3224 (cons js2-ADD "+") ; infix plus
3225 (cons js2-SUB "-") ; infix minus
3226 (cons js2-MUL "*")
3227 (cons js2-DIV "/")
3228 (cons js2-MOD "%")
3229 (cons js2-NOT "!")
3230 (cons js2-BITNOT "~")
3231 (cons js2-POS "+") ; unary plus
3232 (cons js2-NEG "-") ; unary minus
3233 (cons js2-SHEQ "===") ; shallow equality
3234 (cons js2-SHNE "!==") ; shallow inequality
3235 (cons js2-ASSIGN "=")
3236 (cons js2-ASSIGN_BITOR "|=")
3237 (cons js2-ASSIGN_BITXOR "^=")
3238 (cons js2-ASSIGN_BITAND "&=")
3239 (cons js2-ASSIGN_LSH "<<=")
3240 (cons js2-ASSIGN_RSH ">>=")
3241 (cons js2-ASSIGN_URSH ">>>=")
3242 (cons js2-ASSIGN_ADD "+=")
3243 (cons js2-ASSIGN_SUB "-=")
3244 (cons js2-ASSIGN_MUL "*=")
3245 (cons js2-ASSIGN_DIV "/=")
3246 (cons js2-ASSIGN_MOD "%="))))
3247 (loop for (k . v) in tokens do
3248 (puthash k v table))
3249 table))
3250
3251 (defun js2-print-infix-node (n i)
3252 (let* ((tt (js2-node-type n))
3253 (op (gethash tt js2-operator-tokens)))
3254 (unless op
3255 (error "unrecognized infix operator %s" (js2-node-type n)))
3256 (insert (js2-make-pad i))
3257 (js2-print-ast (js2-infix-node-left n) 0)
3258 (unless (= tt js2-COMMA)
3259 (insert " "))
3260 (insert op)
3261 (insert " ")
3262 (js2-print-ast (js2-infix-node-right n) 0)))
3263
3264 (defstruct (js2-assign-node
3265 (:include js2-infix-node)
3266 (:constructor nil)
3267 (:constructor make-js2-assign-node (&key type
3268 (pos js2-ts-cursor)
3269 len
3270 op-pos
3271 left
3272 right)))
3273 "Represents any assignment.
3274 The type field holds the actual assignment operator.")
3275
3276 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3277 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3278
3279 (defstruct (js2-unary-node
3280 (:include js2-node)
3281 (:constructor nil)
3282 (:constructor make-js2-unary-node (&key type ; required
3283 (pos js2-ts-cursor)
3284 len
3285 operand)))
3286 "AST node type for unary operator nodes.
3287 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3288 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3289 property is added if the operator follows the operand."
3290 operand) ; a `js2-node' expression
3291
3292 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3293 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3294
3295 (defun js2-visit-unary-node (n v)
3296 (js2-visit-ast (js2-unary-node-operand n) v))
3297
3298 (defun js2-print-unary-node (n i)
3299 (let* ((tt (js2-node-type n))
3300 (op (gethash tt js2-operator-tokens))
3301 (postfix (js2-node-get-prop n 'postfix)))
3302 (unless op
3303 (error "unrecognized unary operator %s" tt))
3304 (insert (js2-make-pad i))
3305 (unless postfix
3306 (insert op))
3307 (if (or (= tt js2-TYPEOF)
3308 (= tt js2-DELPROP))
3309 (insert " "))
3310 (js2-print-ast (js2-unary-node-operand n) 0)
3311 (when postfix
3312 (insert op))))
3313
3314 (defstruct (js2-let-node
3315 (:include js2-scope)
3316 (:constructor nil)
3317 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3318 (pos js2-token-beg)
3319 len
3320 vars
3321 body
3322 lp
3323 rp)))
3324 "AST node for a let expression or a let statement.
3325 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3326 vars ; a `js2-var-decl-node'
3327 body ; a `js2-node' representing the expression or body block
3328 lp
3329 rp)
3330
3331 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3332 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3333
3334 (defun js2-visit-let-node (n v)
3335 (js2-visit-ast (js2-let-node-vars n) v)
3336 (js2-visit-ast (js2-let-node-body n) v))
3337
3338 (defun js2-print-let-node (n i)
3339 (insert (js2-make-pad i) "let (")
3340 (js2-print-ast (js2-let-node-vars n) 0)
3341 (insert ") ")
3342 (js2-print-ast (js2-let-node-body n) i))
3343
3344 (defstruct (js2-keyword-node
3345 (:include js2-node)
3346 (:constructor nil)
3347 (:constructor make-js2-keyword-node (&key type
3348 (pos js2-token-beg)
3349 (len (- js2-ts-cursor pos)))))
3350 "AST node representing a literal keyword such as `null'.
3351 Used for `null', `this', `true', `false' and `debugger'.
3352 The node type is set to js2-NULL, js2-THIS, etc.")
3353
3354 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3355 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3356
3357 (defun js2-print-keyword-node (n i)
3358 (insert (js2-make-pad i)
3359 (let ((tt (js2-node-type n)))
3360 (cond
3361 ((= tt js2-THIS) "this")
3362 ((= tt js2-NULL) "null")
3363 ((= tt js2-TRUE) "true")
3364 ((= tt js2-FALSE) "false")
3365 ((= tt js2-DEBUGGER) "debugger")
3366 (t (error "Invalid keyword literal type: %d" tt))))))
3367
3368 (defsubst js2-this-node-p (node)
3369 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3370 (eq (js2-node-type node) js2-THIS))
3371
3372 (defstruct (js2-new-node
3373 (:include js2-node)
3374 (:constructor nil)
3375 (:constructor make-js2-new-node (&key (type js2-NEW)
3376 (pos js2-token-beg)
3377 len
3378 target
3379 args
3380 initializer
3381 lp
3382 rp)))
3383 "AST node for new-expression such as new Foo()."
3384 target ; an identifier or reference
3385 args ; a lisp list of argument nodes
3386 lp ; position of left-paren, nil if omitted
3387 rp ; position of right-paren, nil if omitted
3388 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3389
3390 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3391 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3392
3393 (defun js2-visit-new-node (n v)
3394 (js2-visit-ast (js2-new-node-target n) v)
3395 (dolist (arg (js2-new-node-args n))
3396 (js2-visit-ast arg v))
3397 (js2-visit-ast (js2-new-node-initializer n) v))
3398
3399 (defun js2-print-new-node (n i)
3400 (insert (js2-make-pad i) "new ")
3401 (js2-print-ast (js2-new-node-target n))
3402 (insert "(")
3403 (js2-print-list (js2-new-node-args n))
3404 (insert ")")
3405 (when (js2-new-node-initializer n)
3406 (insert " ")
3407 (js2-print-ast (js2-new-node-initializer n))))
3408
3409 (defstruct (js2-name-node
3410 (:include js2-node)
3411 (:constructor nil)
3412 (:constructor make-js2-name-node (&key (type js2-NAME)
3413 (pos js2-token-beg)
3414 (len (- js2-ts-cursor
3415 js2-token-beg))
3416 (name js2-ts-string))))
3417 "AST node for a JavaScript identifier"
3418 name ; a string
3419 scope) ; a `js2-scope' (optional, used for codegen)
3420
3421 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3422 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3423
3424 (defun js2-print-name-node (n i)
3425 (insert (js2-make-pad i)
3426 (js2-name-node-name n)))
3427
3428 (defsubst js2-name-node-length (node)
3429 "Return identifier length of NODE, a `js2-name-node'.
3430 Returns 0 if NODE is nil or its identifier field is nil."
3431 (if node
3432 (length (js2-name-node-name node))
3433 0))
3434
3435 (defstruct (js2-number-node
3436 (:include js2-node)
3437 (:constructor nil)
3438 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3439 (pos js2-token-beg)
3440 (len (- js2-ts-cursor
3441 js2-token-beg))
3442 (value js2-ts-string)
3443 (num-value js2-ts-number))))
3444 "AST node for a number literal."
3445 value ; the original string, e.g. "6.02e23"
3446 num-value) ; the parsed number value
3447
3448 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3449 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3450
3451 (defun js2-print-number-node (n i)
3452 (insert (js2-make-pad i)
3453 (number-to-string (js2-number-node-num-value n))))
3454
3455 (defstruct (js2-regexp-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3459 (pos js2-token-beg)
3460 (len (- js2-ts-cursor
3461 js2-token-beg))
3462 value
3463 flags)))
3464 "AST node for a regular expression literal."
3465 value ; the regexp string, without // delimiters
3466 flags) ; a string of flags, e.g. `mi'.
3467
3468 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3470
3471 (defun js2-print-regexp (n i)
3472 (insert (js2-make-pad i)
3473 "/"
3474 (js2-regexp-node-value n)
3475 "/")
3476 (if (js2-regexp-node-flags n)
3477 (insert (js2-regexp-node-flags n))))
3478
3479 (defstruct (js2-string-node
3480 (:include js2-node)
3481 (:constructor nil)
3482 (:constructor make-js2-string-node (&key (type js2-STRING)
3483 (pos js2-token-beg)
3484 (len (- js2-ts-cursor
3485 js2-token-beg))
3486 (value js2-ts-string))))
3487 "String literal.
3488 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3489 You can tell the quote type by looking at the first character."
3490 value) ; the characters of the string, including the quotes
3491
3492 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3493 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3494
3495 (defun js2-print-string-node (n i)
3496 (insert (js2-make-pad i)
3497 (js2-node-string n)))
3498
3499 (defstruct (js2-array-node
3500 (:include js2-node)
3501 (:constructor nil)
3502 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3503 (pos js2-ts-cursor)
3504 len
3505 elems)))
3506 "AST node for an array literal."
3507 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3508
3509 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3510 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3511
3512 (defun js2-visit-array-node (n v)
3513 (dolist (e (js2-array-node-elems n))
3514 (js2-visit-ast e v)))
3515
3516 (defun js2-print-array-node (n i)
3517 (insert (js2-make-pad i) "[")
3518 (js2-print-list (js2-array-node-elems n))
3519 (insert "]"))
3520
3521 (defstruct (js2-object-node
3522 (:include js2-node)
3523 (:constructor nil)
3524 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3525 (pos js2-ts-cursor)
3526 len
3527 elems)))
3528 "AST node for an object literal expression.
3529 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3530 the latter represents abbreviation in destructuring expressions."
3531 elems)
3532
3533 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3534 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3535
3536 (defun js2-visit-object-node (n v)
3537 (dolist (e (js2-object-node-elems n))
3538 (js2-visit-ast e v)))
3539
3540 (defun js2-print-object-node (n i)
3541 (insert (js2-make-pad i) "{")
3542 (js2-print-list (js2-object-node-elems n))
3543 (insert "}"))
3544
3545 (defstruct (js2-object-prop-node
3546 (:include js2-infix-node)
3547 (:constructor nil)
3548 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3549 (pos js2-ts-cursor)
3550 len
3551 left
3552 right
3553 op-pos)))
3554 "AST node for an object literal prop:value entry.
3555 The `left' field is the property: a name node, string node or number node.
3556 The `right' field is a `js2-node' representing the initializer value.")
3557
3558 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3560
3561 (defun js2-print-object-prop-node (n i)
3562 (insert (js2-make-pad i))
3563 (js2-print-ast (js2-object-prop-node-left n) 0)
3564 (insert ":")
3565 (js2-print-ast (js2-object-prop-node-right n) 0))
3566
3567 (defstruct (js2-getter-setter-node
3568 (:include js2-infix-node)
3569 (:constructor nil)
3570 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3571 (pos js2-ts-cursor)
3572 len
3573 left
3574 right)))
3575 "AST node for a getter/setter property in an object literal.
3576 The `left' field is the `js2-name-node' naming the getter/setter prop.
3577 The `right' field is always an anonymous `js2-function-node' with a node
3578 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3579
3580 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3581 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3582
3583 (defun js2-print-getter-setter (n i)
3584 (let ((pad (js2-make-pad i))
3585 (left (js2-getter-setter-node-left n))
3586 (right (js2-getter-setter-node-right n)))
3587 (insert pad)
3588 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3589 (js2-print-ast left 0)
3590 (js2-print-ast right 0)))
3591
3592 (defstruct (js2-prop-get-node
3593 (:include js2-infix-node)
3594 (:constructor nil)
3595 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3596 (pos js2-ts-cursor)
3597 len
3598 left
3599 right)))
3600 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3601
3602 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3603 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3604
3605 (defun js2-visit-prop-get-node (n v)
3606 (js2-visit-ast (js2-prop-get-node-left n) v)
3607 (js2-visit-ast (js2-prop-get-node-right n) v))
3608
3609 (defun js2-print-prop-get-node (n i)
3610 (insert (js2-make-pad i))
3611 (js2-print-ast (js2-prop-get-node-left n) 0)
3612 (insert ".")
3613 (js2-print-ast (js2-prop-get-node-right n) 0))
3614
3615 (defstruct (js2-elem-get-node
3616 (:include js2-node)
3617 (:constructor nil)
3618 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3619 (pos js2-ts-cursor)
3620 len
3621 target
3622 element
3623 lb
3624 rb)))
3625 "AST node for an array index expression such as foo[bar]."
3626 target ; a `js2-node' - the expression preceding the "."
3627 element ; a `js2-node' - the expression in brackets
3628 lb ; position of left-bracket, nil if omitted
3629 rb) ; position of right-bracket, nil if omitted
3630
3631 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3632 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3633
3634 (defun js2-visit-elem-get-node (n v)
3635 (js2-visit-ast (js2-elem-get-node-target n) v)
3636 (js2-visit-ast (js2-elem-get-node-element n) v))
3637
3638 (defun js2-print-elem-get-node (n i)
3639 (insert (js2-make-pad i))
3640 (js2-print-ast (js2-elem-get-node-target n) 0)
3641 (insert "[")
3642 (js2-print-ast (js2-elem-get-node-element n) 0)
3643 (insert "]"))
3644
3645 (defstruct (js2-call-node
3646 (:include js2-node)
3647 (:constructor nil)
3648 (:constructor make-js2-call-node (&key (type js2-CALL)
3649 (pos js2-ts-cursor)
3650 len
3651 target
3652 args
3653 lp
3654 rp)))
3655 "AST node for a JavaScript function call."
3656 target ; a `js2-node' evaluating to the function to call
3657 args ; a lisp list of `js2-node' arguments
3658 lp ; position of open-paren, or nil if missing
3659 rp) ; position of close-paren, or nil if missing
3660
3661 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3662 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3663
3664 (defun js2-visit-call-node (n v)
3665 (js2-visit-ast (js2-call-node-target n) v)
3666 (dolist (arg (js2-call-node-args n))
3667 (js2-visit-ast arg v)))
3668
3669 (defun js2-print-call-node (n i)
3670 (insert (js2-make-pad i))
3671 (js2-print-ast (js2-call-node-target n) 0)
3672 (insert "(")
3673 (js2-print-list (js2-call-node-args n))
3674 (insert ")"))
3675
3676 (defstruct (js2-yield-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3680 (pos js2-ts-cursor)
3681 len
3682 value)))
3683 "AST node for yield statement or expression."
3684 value) ; optional: value to be yielded
3685
3686 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3687 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3688
3689 (defun js2-visit-yield-node (n v)
3690 (js2-visit-ast (js2-yield-node-value n) v))
3691
3692 (defun js2-print-yield-node (n i)
3693 (insert (js2-make-pad i))
3694 (insert "yield")
3695 (when (js2-yield-node-value n)
3696 (insert " ")
3697 (js2-print-ast (js2-yield-node-value n) 0)))
3698
3699 (defstruct (js2-paren-node
3700 (:include js2-node)
3701 (:constructor nil)
3702 (:constructor make-js2-paren-node (&key (type js2-LP)
3703 (pos js2-ts-cursor)
3704 len
3705 expr)))
3706 "AST node for a parenthesized expression.
3707 In particular, used when the parens are syntactically optional,
3708 as opposed to required parens such as those enclosing an if-conditional."
3709 expr) ; `js2-node'
3710
3711 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3712 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3713
3714 (defun js2-visit-paren-node (n v)
3715 (js2-visit-ast (js2-paren-node-expr n) v))
3716
3717 (defun js2-print-paren-node (n i)
3718 (insert (js2-make-pad i))
3719 (insert "(")
3720 (js2-print-ast (js2-paren-node-expr n) 0)
3721 (insert ")"))
3722
3723 (defstruct (js2-array-comp-node
3724 (:include js2-scope)
3725 (:constructor nil)
3726 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3727 (pos js2-ts-cursor)
3728 len
3729 result
3730 loops
3731 filter
3732 if-pos
3733 lp
3734 rp)))
3735 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3736 result ; result expression (just after left-bracket)
3737 loops ; a lisp list of `js2-array-comp-loop-node'
3738 filter ; guard/filter expression
3739 if-pos ; buffer pos of 'if' keyword, if present, else nil
3740 lp ; buffer position of if-guard left-paren, or nil if not present
3741 rp) ; buffer position of if-guard right-paren, or nil if not present
3742
3743 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3744 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3745
3746 (defun js2-visit-array-comp-node (n v)
3747 (js2-visit-ast (js2-array-comp-node-result n) v)
3748 (dolist (l (js2-array-comp-node-loops n))
3749 (js2-visit-ast l v))
3750 (js2-visit-ast (js2-array-comp-node-filter n) v))
3751
3752 (defun js2-print-array-comp-node (n i)
3753 (let ((pad (js2-make-pad i))
3754 (result (js2-array-comp-node-result n))
3755 (loops (js2-array-comp-node-loops n))
3756 (filter (js2-array-comp-node-filter n)))
3757 (insert pad "[")
3758 (js2-print-ast result 0)
3759 (dolist (l loops)
3760 (insert " ")
3761 (js2-print-ast l 0))
3762 (when filter
3763 (insert " if (")
3764 (js2-print-ast filter 0))
3765 (insert ")]")))
3766
3767 (defstruct (js2-array-comp-loop-node
3768 (:include js2-for-in-node)
3769 (:constructor nil)
3770 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3771 (pos js2-ts-cursor)
3772 len
3773 iterator
3774 object
3775 in-pos
3776 foreach-p
3777 each-pos
3778 lp
3779 rp)))
3780 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3781
3782 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3783 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3784
3785 (defun js2-visit-array-comp-loop (n v)
3786 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3787 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3788
3789 (defun js2-print-array-comp-loop (n i)
3790 (insert "for (")
3791 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3792 (insert " in ")
3793 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3794 (insert ")"))
3795
3796 (defstruct (js2-empty-expr-node
3797 (:include js2-node)
3798 (:constructor nil)
3799 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3800 (pos js2-token-beg)
3801 len)))
3802 "AST node for an empty expression.")
3803
3804 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3805 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3806
3807 (defstruct (js2-xml-node
3808 (:include js2-block-node)
3809 (:constructor nil)
3810 (:constructor make-js2-xml-node (&key (type js2-XML)
3811 (pos js2-token-beg)
3812 len
3813 kids)))
3814 "AST node for initial parse of E4X literals.
3815 The kids field is a list of XML fragments, each a `js2-string-node' or
3816 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3817
3818 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3819 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3820
3821 (defun js2-print-xml-node (n i)
3822 (dolist (kid (js2-xml-node-kids n))
3823 (js2-print-ast kid i)))
3824
3825 (defstruct (js2-xml-js-expr-node
3826 (:include js2-xml-node)
3827 (:constructor nil)
3828 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3829 (pos js2-ts-cursor)
3830 len
3831 expr)))
3832 "AST node for an embedded JavaScript {expression} in an E4X literal.
3833 The start and end fields correspond to the curly-braces."
3834 expr) ; a `js2-expr-node' of some sort
3835
3836 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3837 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3838
3839 (defun js2-visit-xml-js-expr (n v)
3840 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3841
3842 (defun js2-print-xml-js-expr (n i)
3843 (insert (js2-make-pad i))
3844 (insert "{")
3845 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3846 (insert "}"))
3847
3848 (defstruct (js2-xml-dot-query-node
3849 (:include js2-infix-node)
3850 (:constructor nil)
3851 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3852 (pos js2-ts-cursor)
3853 op-pos
3854 len
3855 left
3856 right
3857 rp)))
3858 "AST node for an E4X foo.(bar) filter expression.
3859 Note that the left-paren is automatically the character immediately
3860 following the dot (.) in the operator. No whitespace is permitted
3861 between the dot and the lp by the scanner."
3862 rp)
3863
3864 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3865 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3866
3867 (defun js2-print-xml-dot-query (n i)
3868 (insert (js2-make-pad i))
3869 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3870 (insert ".(")
3871 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3872 (insert ")"))
3873
3874 (defstruct (js2-xml-ref-node
3875 (:include js2-node)
3876 (:constructor nil)) ; abstract
3877 "Base type for E4X XML attribute-access or property-get expressions.
3878 Such expressions can take a variety of forms. The general syntax has
3879 three parts:
3880
3881 - (optional) an @ (specifying an attribute access)
3882 - (optional) a namespace (a `js2-name-node') and double-colon
3883 - (required) either a `js2-name-node' or a bracketed [expression]
3884
3885 The property-name expressions (examples: ns::name, @name) are
3886 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3887 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3888
3889 This node type (or more specifically, its subclasses) will sometimes
3890 be the right-hand child of a `js2-prop-get-node' or a
3891 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3892 The `js2-xml-ref-node' may also be a standalone primary expression with
3893 no explicit target, which is valid in certain expression contexts such as
3894
3895 company..employee.(@id < 100)
3896
3897 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3898 expression whose parent is a `js2-xml-dot-query-node'."
3899 namespace
3900 at-pos
3901 colon-pos)
3902
3903 (defsubst js2-xml-ref-node-attr-access-p (node)
3904 "Return non-nil if this expression began with an @-token."
3905 (and (numberp (js2-xml-ref-node-at-pos node))
3906 (plusp (js2-xml-ref-node-at-pos node))))
3907
3908 (defstruct (js2-xml-prop-ref-node
3909 (:include js2-xml-ref-node)
3910 (:constructor nil)
3911 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3912 (pos js2-token-beg)
3913 len
3914 propname
3915 namespace
3916 at-pos
3917 colon-pos)))
3918 "AST node for an E4X XML [expr] property-ref expression.
3919 The JavaScript syntax is an optional @, an optional ns::, and a name.
3920
3921 [ '@' ] [ name '::' ] name
3922
3923 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3924 @ns::*, @*::attr, @*::*, and @*.
3925
3926 The node starts at the @ token, if present. Otherwise it starts at the
3927 namespace name. The node bounds extend through the closing right-bracket,
3928 or if it is missing due to a syntax error, through the end of the index
3929 expression."
3930 propname)
3931
3932 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3933 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3934
3935 (defun js2-visit-xml-prop-ref-node (n v)
3936 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3937 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3938
3939 (defun js2-print-xml-prop-ref-node (n i)
3940 (insert (js2-make-pad i))
3941 (if (js2-xml-ref-node-attr-access-p n)
3942 (insert "@"))
3943 (when (js2-xml-prop-ref-node-namespace n)
3944 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3945 (insert "::"))
3946 (if (js2-xml-prop-ref-node-propname n)
3947 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3948
3949 (defstruct (js2-xml-elem-ref-node
3950 (:include js2-xml-ref-node)
3951 (:constructor nil)
3952 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3953 (pos js2-token-beg)
3954 len
3955 expr
3956 lb
3957 rb
3958 namespace
3959 at-pos
3960 colon-pos)))
3961 "AST node for an E4X XML [expr] member-ref expression.
3962 Syntax:
3963
3964 [ '@' ] [ name '::' ] '[' expr ']'
3965
3966 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3967
3968 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3969 is not a legal E4X XML element-ref expression, since it's already used
3970 for standard JavaScript element-get array indexing. Hence, a
3971 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3972 non-nil namespace node, or both.
3973
3974 The node starts at the @ token, if present. Otherwise it starts
3975 at the namespace name. The node bounds extend through the closing
3976 right-bracket, or if it is missing due to a syntax error, through the
3977 end of the index expression."
3978 expr ; the bracketed index expression
3979 lb
3980 rb)
3981
3982 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3983 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3984
3985 (defun js2-visit-xml-elem-ref-node (n v)
3986 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3987 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3988
3989 (defun js2-print-xml-elem-ref-node (n i)
3990 (insert (js2-make-pad i))
3991 (if (js2-xml-ref-node-attr-access-p n)
3992 (insert "@"))
3993 (when (js2-xml-elem-ref-node-namespace n)
3994 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3995 (insert "::"))
3996 (insert "[")
3997 (if (js2-xml-elem-ref-node-expr n)
3998 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3999 (insert "]"))
4000
4001 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4002
4003 (defstruct (js2-xml-start-tag-node
4004 (:include js2-xml-node)
4005 (:constructor nil)
4006 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4007 (pos js2-ts-cursor)
4008 len
4009 name
4010 attrs
4011 kids
4012 empty-p)))
4013 "AST node for an XML start-tag. Not currently used.
4014 The `kids' field is a lisp list of child content nodes."
4015 name ; a `js2-xml-name-node'
4016 attrs ; a lisp list of `js2-xml-attr-node'
4017 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4018
4019 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4020 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4021
4022 (defun js2-visit-xml-start-tag (n v)
4023 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4024 (dolist (attr (js2-xml-start-tag-node-attrs n))
4025 (js2-visit-ast attr v))
4026 (js2-visit-block n v))
4027
4028 (defun js2-print-xml-start-tag (n i)
4029 (insert (js2-make-pad i) "<")
4030 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4031 (when (js2-xml-start-tag-node-attrs n)
4032 (insert " ")
4033 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4034 (insert ">"))
4035
4036 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4037 ;; and add the end-tag to the kids list of the parent as well.
4038 (defstruct (js2-xml-end-tag-node
4039 (:include js2-xml-node)
4040 (:constructor nil)
4041 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4042 (pos js2-ts-cursor)
4043 len
4044 name)))
4045 "AST node for an XML end-tag. Not currently used."
4046 name) ; a `js2-xml-name-node'
4047
4048 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4049 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4050
4051 (defun js2-visit-xml-end-tag (n v)
4052 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4053
4054 (defun js2-print-xml-end-tag (n i)
4055 (insert (js2-make-pad i))
4056 (insert "</")
4057 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4058 (insert ">"))
4059
4060 (defstruct (js2-xml-name-node
4061 (:include js2-xml-node)
4062 (:constructor nil)
4063 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4064 (pos js2-ts-cursor)
4065 len
4066 namespace
4067 kids)))
4068 "AST node for an E4X XML name. Not currently used.
4069 Any XML name can be qualified with a namespace, hence the namespace field.
4070 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4071 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4072 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4073 namespace) ; a `js2-string-node'
4074
4075 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4076 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4077
4078 (defun js2-visit-xml-name-node (n v)
4079 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4080
4081 (defun js2-print-xml-name-node (n i)
4082 (insert (js2-make-pad i))
4083 (when (js2-xml-name-node-namespace n)
4084 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4085 (insert "::"))
4086 (dolist (kid (js2-xml-name-node-kids n))
4087 (js2-print-ast kid 0)))
4088
4089 (defstruct (js2-xml-pi-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len
4095 name
4096 attrs)))
4097 "AST node for an E4X XML processing instruction. Not currently used."
4098 name ; a `js2-xml-name-node'
4099 attrs) ; a list of `js2-xml-attr-node'
4100
4101 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4102 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4103
4104 (defun js2-visit-xml-pi-node (n v)
4105 (js2-visit-ast (js2-xml-pi-node-name n) v)
4106 (dolist (attr (js2-xml-pi-node-attrs n))
4107 (js2-visit-ast attr v)))
4108
4109 (defun js2-print-xml-pi-node (n i)
4110 (insert (js2-make-pad i) "<?")
4111 (js2-print-ast (js2-xml-pi-node-name n))
4112 (when (js2-xml-pi-node-attrs n)
4113 (insert " ")
4114 (js2-print-list (js2-xml-pi-node-attrs n)))
4115 (insert "?>"))
4116
4117 (defstruct (js2-xml-cdata-node
4118 (:include js2-xml-node)
4119 (:constructor nil)
4120 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4121 (pos js2-ts-cursor)
4122 len
4123 content)))
4124 "AST node for a CDATA escape section. Not currently used."
4125 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4126
4127 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4128 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4129
4130 (defun js2-visit-xml-cdata-node (n v)
4131 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4132
4133 (defun js2-print-xml-cdata-node (n i)
4134 (insert (js2-make-pad i))
4135 (js2-print-ast (js2-xml-cdata-node-content n)))
4136
4137 (defstruct (js2-xml-attr-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-attr-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 name
4144 value
4145 eq-pos
4146 quote-type)))
4147 "AST node representing a foo='bar' XML attribute value. Not yet used."
4148 name ; a `js2-xml-name-node'
4149 value ; a `js2-xml-name-node'
4150 eq-pos ; buffer position of "=" sign
4151 quote-type) ; 'single or 'double
4152
4153 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4154 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4155
4156 (defun js2-visit-xml-attr-node (n v)
4157 (js2-visit-ast (js2-xml-attr-node-name n) v)
4158 (js2-visit-ast (js2-xml-attr-node-value n) v))
4159
4160 (defun js2-print-xml-attr-node (n i)
4161 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4162 "'"
4163 "\"")))
4164 (insert (js2-make-pad i))
4165 (js2-print-ast (js2-xml-attr-node-name n) 0)
4166 (insert "=" quote)
4167 (js2-print-ast (js2-xml-attr-node-value n) 0)
4168 (insert quote)))
4169
4170 (defstruct (js2-xml-text-node
4171 (:include js2-xml-node)
4172 (:constructor nil)
4173 (:constructor make-js2-text-node (&key (type js2-XML)
4174 (pos js2-ts-cursor)
4175 len
4176 content)))
4177 "AST node for an E4X XML text node. Not currently used."
4178 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4179
4180 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4181 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4182
4183 (defun js2-visit-xml-text-node (n v)
4184 (js2-visit-ast (js2-xml-text-node-content n) v))
4185
4186 (defun js2-print-xml-text-node (n i)
4187 (insert (js2-make-pad i))
4188 (dolist (kid (js2-xml-text-node-content n))
4189 (js2-print-ast kid)))
4190
4191 (defstruct (js2-xml-comment-node
4192 (:include js2-xml-node)
4193 (:constructor nil)
4194 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4195 (pos js2-ts-cursor)
4196 len)))
4197 "AST node for E4X XML comment. Not currently used.")
4198
4199 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4200 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4201
4202 (defun js2-print-xml-comment (n i)
4203 (insert (js2-make-pad i)
4204 (js2-node-string n)))
4205
4206 ;;; Node utilities
4207
4208 (defsubst js2-node-line (n)
4209 "Fetch the source line number at the start of node N.
4210 This is O(n) in the length of the source buffer; use prudently."
4211 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4212
4213 (defsubst js2-block-node-kid (n i)
4214 "Return child I of node N, or nil if there aren't that many."
4215 (nth i (js2-block-node-kids n)))
4216
4217 (defsubst js2-block-node-first (n)
4218 "Return first child of block node N, or nil if there is none."
4219 (first (js2-block-node-kids n)))
4220
4221 (defun js2-node-root (n)
4222 "Return the root of the AST containing N.
4223 If N has no parent pointer, returns N."
4224 (let ((parent (js2-node-parent n)))
4225 (if parent
4226 (js2-node-root parent)
4227 n)))
4228
4229 (defun js2-node-position-in-parent (node &optional parent)
4230 "Return the position of NODE in parent's block-kids list.
4231 PARENT can be supplied if known. Positioned returned is zero-indexed.
4232 Returns 0 if NODE is not a child of a block statement, or if NODE
4233 is not a statement node."
4234 (let ((p (or parent (js2-node-parent node)))
4235 (i 0))
4236 (if (not (js2-block-node-p p))
4237 i
4238 (or (js2-position node (js2-block-node-kids p))
4239 0))))
4240
4241 (defsubst js2-node-short-name (n)
4242 "Return the short name of node N as a string, e.g. `js2-if-node'."
4243 (substring (symbol-name (aref n 0))
4244 (length "cl-struct-")))
4245
4246 (defsubst js2-node-child-list (node)
4247 "Return the child list for NODE, a lisp list of nodes.
4248 Works for block nodes, array nodes, obj literals, funarg lists,
4249 var decls and try nodes (for catch clauses). Note that you should call
4250 `js2-block-node-kids' on the function body for the body statements.
4251 Returns nil for zero-length child lists or unsupported nodes."
4252 (cond
4253 ((js2-function-node-p node)
4254 (js2-function-node-params node))
4255 ((js2-block-node-p node)
4256 (js2-block-node-kids node))
4257 ((js2-try-node-p node)
4258 (js2-try-node-catch-clauses node))
4259 ((js2-array-node-p node)
4260 (js2-array-node-elems node))
4261 ((js2-object-node-p node)
4262 (js2-object-node-elems node))
4263 ((js2-call-node-p node)
4264 (js2-call-node-args node))
4265 ((js2-new-node-p node)
4266 (js2-new-node-args node))
4267 ((js2-var-decl-node-p node)
4268 (js2-var-decl-node-kids node))
4269 (t
4270 nil)))
4271
4272 (defsubst js2-node-set-child-list (node kids)
4273 "Set the child list for NODE to KIDS."
4274 (cond
4275 ((js2-function-node-p node)
4276 (setf (js2-function-node-params node) kids))
4277 ((js2-block-node-p node)
4278 (setf (js2-block-node-kids node) kids))
4279 ((js2-try-node-p node)
4280 (setf (js2-try-node-catch-clauses node) kids))
4281 ((js2-array-node-p node)
4282 (setf (js2-array-node-elems node) kids))
4283 ((js2-object-node-p node)
4284 (setf (js2-object-node-elems node) kids))
4285 ((js2-call-node-p node)
4286 (setf (js2-call-node-args node) kids))
4287 ((js2-new-node-p node)
4288 (setf (js2-new-node-args node) kids))
4289 ((js2-var-decl-node-p node)
4290 (setf (js2-var-decl-node-kids node) kids))
4291 (t
4292 (error "Unsupported node type: %s" (js2-node-short-name node))))
4293 kids)
4294
4295 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4296 (defconst js2-paren-expr-nodes
4297 '(cl-struct-js2-array-comp-loop-node
4298 cl-struct-js2-array-comp-node
4299 cl-struct-js2-call-node
4300 cl-struct-js2-catch-node
4301 cl-struct-js2-do-node
4302 cl-struct-js2-elem-get-node
4303 cl-struct-js2-for-in-node
4304 cl-struct-js2-for-node
4305 cl-struct-js2-function-node
4306 cl-struct-js2-if-node
4307 cl-struct-js2-let-node
4308 cl-struct-js2-new-node
4309 cl-struct-js2-paren-node
4310 cl-struct-js2-switch-node
4311 cl-struct-js2-while-node
4312 cl-struct-js2-with-node
4313 cl-struct-js2-xml-dot-query-node)
4314 "Node types that can have a parenthesized child expression.
4315 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4316
4317 (defsubst js2-paren-expr-node-p (node)
4318 "Return t for nodes that typically have a parenthesized child expression.
4319 Useful for computing the indentation anchors for arg-lists and conditions.
4320 Note that it may return a false positive, for instance when NODE is
4321 a `js2-new-node' and there are no arguments or parentheses."
4322 (memq (aref node 0) js2-paren-expr-nodes))
4323
4324 ;; Fake polymorphism... yech.
4325 (defsubst js2-node-lp (node)
4326 "Return relative left-paren position for NODE, if applicable.
4327 For `js2-elem-get-node' structs, returns left-bracket position.
4328 Note that the position may be nil in the case of a parse error."
4329 (cond
4330 ((js2-elem-get-node-p node)
4331 (js2-elem-get-node-lb node))
4332 ((js2-loop-node-p node)
4333 (js2-loop-node-lp node))
4334 ((js2-function-node-p node)
4335 (js2-function-node-lp node))
4336 ((js2-if-node-p node)
4337 (js2-if-node-lp node))
4338 ((js2-new-node-p node)
4339 (js2-new-node-lp node))
4340 ((js2-call-node-p node)
4341 (js2-call-node-lp node))
4342 ((js2-paren-node-p node)
4343 (js2-node-pos node))
4344 ((js2-switch-node-p node)
4345 (js2-switch-node-lp node))
4346 ((js2-catch-node-p node)
4347 (js2-catch-node-lp node))
4348 ((js2-let-node-p node)
4349 (js2-let-node-lp node))
4350 ((js2-array-comp-node-p node)
4351 (js2-array-comp-node-lp node))
4352 ((js2-with-node-p node)
4353 (js2-with-node-lp node))
4354 ((js2-xml-dot-query-node-p node)
4355 (1+ (js2-infix-node-op-pos node)))
4356 (t
4357 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4358
4359 ;; Fake polymorphism... blech.
4360 (defsubst js2-node-rp (node)
4361 "Return relative right-paren position for NODE, if applicable.
4362 For `js2-elem-get-node' structs, returns right-bracket position.
4363 Note that the position may be nil in the case of a parse error."
4364 (cond
4365 ((js2-elem-get-node-p node)
4366 (js2-elem-get-node-lb node))
4367 ((js2-loop-node-p node)
4368 (js2-loop-node-rp node))
4369 ((js2-function-node-p node)
4370 (js2-function-node-rp node))
4371 ((js2-if-node-p node)
4372 (js2-if-node-rp node))
4373 ((js2-new-node-p node)
4374 (js2-new-node-rp node))
4375 ((js2-call-node-p node)
4376 (js2-call-node-rp node))
4377 ((js2-paren-node-p node)
4378 (+ (js2-node-pos node) (js2-node-len node)))
4379 ((js2-switch-node-p node)
4380 (js2-switch-node-rp node))
4381 ((js2-catch-node-p node)
4382 (js2-catch-node-rp node))
4383 ((js2-let-node-p node)
4384 (js2-let-node-rp node))
4385 ((js2-array-comp-node-p node)
4386 (js2-array-comp-node-rp node))
4387 ((js2-with-node-p node)
4388 (js2-with-node-rp node))
4389 ((js2-xml-dot-query-node-p node)
4390 (1+ (js2-xml-dot-query-node-rp node)))
4391 (t
4392 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4393
4394 (defsubst js2-node-first-child (node)
4395 "Returns the first element of `js2-node-child-list' for NODE."
4396 (car (js2-node-child-list node)))
4397
4398 (defsubst js2-node-last-child (node)
4399 "Returns the last element of `js2-node-last-child' for NODE."
4400 (car (last (js2-node-child-list node))))
4401
4402 (defun js2-node-prev-sibling (node)
4403 "Return the previous statement in parent.
4404 Works for parents supported by `js2-node-child-list'.
4405 Returns nil if NODE is not in the parent, or PARENT is
4406 not a supported node, or if NODE is the first child."
4407 (let* ((p (js2-node-parent node))
4408 (kids (js2-node-child-list p))
4409 (sib (car kids)))
4410 (while (and kids
4411 (not (eq node (cadr kids))))
4412 (setq kids (cdr kids)
4413 sib (car kids)))
4414 sib))
4415
4416 (defun js2-node-next-sibling (node)
4417 "Return the next statement in parent block.
4418 Returns nil if NODE is not in the block, or PARENT is not
4419 a block node, or if NODE is the last statement."
4420 (let* ((p (js2-node-parent node))
4421 (kids (js2-node-child-list p)))
4422 (while (and kids
4423 (not (eq node (car kids))))
4424 (setq kids (cdr kids)))
4425 (cadr kids)))
4426
4427 (defun js2-node-find-child-before (pos parent &optional after)
4428 "Find the last child that starts before POS in parent.
4429 If AFTER is non-nil, returns first child starting after POS.
4430 POS is an absolute buffer position. PARENT is any node
4431 supported by `js2-node-child-list'.
4432 Returns nil if no applicable child is found."
4433 (let ((kids (if (js2-function-node-p parent)
4434 (js2-block-node-kids (js2-function-node-body parent))
4435 (js2-node-child-list parent)))
4436 (beg (if (js2-function-node-p parent)
4437 (js2-node-abs-pos (js2-function-node-body parent))
4438 (js2-node-abs-pos parent)))
4439 kid
4440 result
4441 fn
4442 (continue t))
4443 (setq fn (if after '> '<))
4444 (while (and kids continue)
4445 (setq kid (car kids))
4446 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4447 (setq result kid
4448 continue (if after nil t))
4449 (setq continue (if after t nil)))
4450 (setq kids (cdr kids)))
4451 result))
4452
4453 (defun js2-node-find-child-after (pos parent)
4454 "Find first child that starts after POS in parent.
4455 POS is an absolute buffer position. PARENT is any node
4456 supported by `js2-node-child-list'.
4457 Returns nil if no applicable child is found."
4458 (js2-node-find-child-before pos parent 'after))
4459
4460 (defun js2-node-replace-child (pos parent new-node)
4461 "Replace node at index POS in PARENT with NEW-NODE.
4462 Only works for parents supported by `js2-node-child-list'."
4463 (let ((kids (js2-node-child-list parent))
4464 (i 0))
4465 (while (< i pos)
4466 (setq kids (cdr kids)
4467 i (1+ i)))
4468 (setcar kids new-node)
4469 (js2-node-add-children parent new-node)))
4470
4471 (defun js2-node-buffer (n)
4472 "Return the buffer associated with AST N.
4473 Returns nil if the buffer is not set as a property on the root
4474 node, or if parent links were not recorded during parsing."
4475 (let ((root (js2-node-root n)))
4476 (and root
4477 (js2-ast-root-p root)
4478 (js2-ast-root-buffer root))))
4479
4480 (defsubst js2-block-node-push (n kid)
4481 "Push js2-node KID onto the end of js2-block-node N's child list.
4482 KID is always added to the -end- of the kids list.
4483 Function also calls `js2-node-add-children' to add the parent link."
4484 (let ((kids (js2-node-child-list n)))
4485 (if kids
4486 (setcdr kids (nconc (cdr kids) (list kid)))
4487 (js2-node-set-child-list n (list kid)))
4488 (js2-node-add-children n kid)))
4489
4490 (defun js2-node-string (node)
4491 (let ((buf (js2-node-buffer node))
4492 pos)
4493 (unless buf
4494 (error "No buffer available for node %s" node))
4495 (save-excursion
4496 (set-buffer buf)
4497 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4498 (+ pos (js2-node-len node))))))
4499
4500 ;; Container for storing the node we're looking for in a traversal.
4501 (js2-deflocal js2-discovered-node nil)
4502
4503 ;; Keep track of absolute node position during traversals.
4504 (js2-deflocal js2-visitor-offset nil)
4505
4506 (js2-deflocal js2-node-search-point nil)
4507
4508 (when js2-mode-dev-mode-p
4509 (defun js2-find-node-at-point ()
4510 (interactive)
4511 (let ((node (js2-node-at-point)))
4512 (message "%s" (or node "No node found at point"))))
4513 (defun js2-node-name-at-point ()
4514 (interactive)
4515 (let ((node (js2-node-at-point)))
4516 (message "%s" (if node
4517 (js2-node-short-name node)
4518 "No node found at point.")))))
4519
4520 (defun js2-node-at-point (&optional pos skip-comments)
4521 "Return AST node at POS, a buffer position, defaulting to current point.
4522 The `js2-mode-ast' variable must be set to the current parse tree.
4523 Signals an error if the AST (`js2-mode-ast') is nil.
4524 Always returns a node - if it can't find one, it returns the root.
4525 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4526 (let ((ast js2-mode-ast)
4527 result)
4528 (unless ast
4529 (error "No JavaScript AST available"))
4530 ;; Look through comments first, since they may be inside nodes that
4531 ;; would otherwise report a match.
4532 (setq pos (or pos (point))
4533 result (if (> pos (js2-node-abs-end ast))
4534 ast
4535 (if (not skip-comments)
4536 (js2-comment-at-point pos))))
4537 (unless result
4538 (setq js2-discovered-node nil
4539 js2-visitor-offset 0
4540 js2-node-search-point pos)
4541 (unwind-protect
4542 (catch 'js2-visit-done
4543 (js2-visit-ast ast #'js2-node-at-point-visitor))
4544 (setq js2-visitor-offset nil
4545 js2-node-search-point nil))
4546 (setq result js2-discovered-node))
4547 ;; may have found a comment beyond end of last child node,
4548 ;; since visiting the ast-root looks at the comment-list last.
4549 (if (and skip-comments
4550 (js2-comment-node-p result))
4551 (setq result nil))
4552 (or result js2-mode-ast)))
4553
4554 (defun js2-node-at-point-visitor (node end-p)
4555 (let ((rel-pos (js2-node-pos node))
4556 abs-pos
4557 abs-end
4558 (point js2-node-search-point))
4559 (cond
4560 (end-p
4561 ;; this evaluates to a non-nil return value, even if it's zero
4562 (decf js2-visitor-offset rel-pos))
4563 ;; we already looked for comments before visiting, and don't want them now
4564 ((js2-comment-node-p node)
4565 nil)
4566 (t
4567 (setq abs-pos (incf js2-visitor-offset rel-pos)
4568 ;; we only want to use the node if the point is before
4569 ;; the last character position in the node, so we decrement
4570 ;; the absolute end by 1.
4571 abs-end (+ abs-pos (js2-node-len node) -1))
4572 (cond
4573 ;; If this node starts after search-point, stop the search.
4574 ((> abs-pos point)
4575 (throw 'js2-visit-done nil))
4576 ;; If this node ends before the search-point, don't check kids.
4577 ((> point abs-end)
4578 nil)
4579 (t
4580 ;; Otherwise point is within this node, possibly in a child.
4581 (setq js2-discovered-node node)
4582 t)))))) ; keep processing kids to look for more specific match
4583
4584 (defsubst js2-block-comment-p (node)
4585 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4586 (and (js2-comment-node-p node)
4587 (memq (js2-comment-node-format node) '(jsdoc block))))
4588
4589 ;; TODO: put the comments in a vector and binary-search them instead
4590 (defun js2-comment-at-point (&optional pos)
4591 "Look through scanned comment nodes for one containing POS.
4592 POS is a buffer position that defaults to current point.
4593 Function returns nil if POS was not in any comment node."
4594 (let ((ast js2-mode-ast)
4595 (x (or pos (point)))
4596 beg
4597 end)
4598 (unless ast
4599 (error "No JavaScript AST available"))
4600 (catch 'done
4601 ;; Comments are stored in lexical order.
4602 (dolist (comment (js2-ast-root-comments ast) nil)
4603 (setq beg (js2-node-abs-pos comment)
4604 end (+ beg (js2-node-len comment)))
4605 (if (and (>= x beg)
4606 (<= x end))
4607 (throw 'done comment))))))
4608
4609 (defun js2-mode-find-parent-fn (node)
4610 "Find function enclosing NODE.
4611 Returns nil if NODE is not inside a function."
4612 (setq node (js2-node-parent node))
4613 (while (and node (not (js2-function-node-p node)))
4614 (setq node (js2-node-parent node)))
4615 (and (js2-function-node-p node) node))
4616
4617 (defun js2-mode-find-enclosing-fn (node)
4618 "Find function or root enclosing NODE."
4619 (if (js2-ast-root-p node)
4620 node
4621 (setq node (js2-node-parent node))
4622 (while (not (or (js2-ast-root-p node)
4623 (js2-function-node-p node)))
4624 (setq node (js2-node-parent node)))
4625 node))
4626
4627 (defun js2-mode-find-enclosing-node (beg end)
4628 "Find script or function fully enclosing BEG and END."
4629 (let ((node (js2-node-at-point beg))
4630 pos
4631 (continue t))
4632 (while continue
4633 (if (or (js2-ast-root-p node)
4634 (and (js2-function-node-p node)
4635 (<= (setq pos (js2-node-abs-pos node)) beg)
4636 (>= (+ pos (js2-node-len node)) end)))
4637 (setq continue nil)
4638 (setq node (js2-node-parent node))))
4639 node))
4640
4641 (defun js2-node-parent-script-or-fn (node)
4642 "Find script or function immediately enclosing NODE.
4643 If NODE is the ast-root, returns nil."
4644 (if (js2-ast-root-p node)
4645 nil
4646 (setq node (js2-node-parent node))
4647 (while (and node (not (or (js2-function-node-p node)
4648 (js2-script-node-p node))))
4649 (setq node (js2-node-parent node)))
4650 node))
4651
4652 (defsubst js2-nested-function-p (node)
4653 "Return t if NODE is a nested function, or is inside a nested function."
4654 (js2-function-node-p (if (js2-function-node-p node)
4655 (js2-node-parent-script-or-fn node)
4656 (js2-node-parent-script-or-fn
4657 (js2-node-parent-script-or-fn node)))))
4658
4659 (defsubst js2-function-param-node-p (node)
4660 "Return non-nil if NODE is a param node of a `js2-function-node'."
4661 (let ((parent (js2-node-parent node)))
4662 (and parent
4663 (js2-function-node-p parent)
4664 (memq node (js2-function-node-params parent)))))
4665
4666 (defsubst js2-mode-shift-kids (kids start offset)
4667 (dolist (kid kids)
4668 (if (> (js2-node-pos kid) start)
4669 (incf (js2-node-pos kid) offset))))
4670
4671 (defsubst js2-mode-shift-children (parent start offset)
4672 "Update start-positions of all children of PARENT beyond START."
4673 (let ((root (js2-node-root parent)))
4674 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4675 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4676
4677 (defsubst js2-node-is-descendant (node ancestor)
4678 "Return t if NODE is a descendant of ANCESTOR."
4679 (while (and node
4680 (not (eq node ancestor)))
4681 (setq node (js2-node-parent node)))
4682 node)
4683
4684 ;;; visitor infrastructure
4685
4686 (defun js2-visit-none (node callback)
4687 "Visitor for AST node that have no node children."
4688 nil)
4689
4690 (defun js2-print-none (node indent)
4691 "Visitor for AST node with no printed representation.")
4692
4693 (defun js2-print-body (node indent)
4694 "Print a statement, or a block without braces."
4695 (if (js2-block-node-p node)
4696 (dolist (kid (js2-block-node-kids node))
4697 (js2-print-ast kid indent))
4698 (js2-print-ast node indent)))
4699
4700 (defun js2-print-list (args &optional delimiter)
4701 (loop with len = (length args)
4702 for arg in args
4703 for count from 1
4704 do
4705 (js2-print-ast arg 0)
4706 (if (< count len)
4707 (insert (or delimiter ", ")))))
4708
4709 (defun js2-print-tree (ast)
4710 "Prints an AST to the current buffer.
4711 Makes `js2-ast-parent-nodes' available to the printer functions."
4712 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4713 (js2-print-ast ast)))
4714
4715 (defun js2-print-ast (node &optional indent)
4716 "Helper function for printing AST nodes.
4717 Requires `js2-ast-parent-nodes' to be non-nil.
4718 You should use `js2-print-tree' instead of this function."
4719 (let ((printer (get (aref node 0) 'js2-printer))
4720 (i (or indent 0))
4721 (pos (js2-node-abs-pos node)))
4722 ;; TODO: wedge comments in here somewhere
4723 (if printer
4724 (funcall printer node i))))
4725
4726 (defconst js2-side-effecting-tokens
4727 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4728 (dolist (tt (list js2-ASSIGN
4729 js2-ASSIGN_ADD
4730 js2-ASSIGN_BITAND
4731 js2-ASSIGN_BITOR
4732 js2-ASSIGN_BITXOR
4733 js2-ASSIGN_DIV
4734 js2-ASSIGN_LSH
4735 js2-ASSIGN_MOD
4736 js2-ASSIGN_MUL
4737 js2-ASSIGN_RSH
4738 js2-ASSIGN_SUB
4739 js2-ASSIGN_URSH
4740 js2-BLOCK
4741 js2-BREAK
4742 js2-CALL
4743 js2-CATCH
4744 js2-CATCH_SCOPE
4745 js2-CONST
4746 js2-CONTINUE
4747 js2-DEBUGGER
4748 js2-DEC
4749 js2-DELPROP
4750 js2-DEL_REF
4751 js2-DO
4752 js2-ELSE
4753 js2-EMPTY
4754 js2-ENTERWITH
4755 js2-EXPORT
4756 js2-EXPR_RESULT
4757 js2-FINALLY
4758 js2-FOR
4759 js2-FUNCTION
4760 js2-GOTO
4761 js2-IF
4762 js2-IFEQ
4763 js2-IFNE
4764 js2-IMPORT
4765 js2-INC
4766 js2-JSR
4767 js2-LABEL
4768 js2-LEAVEWITH
4769 js2-LET
4770 js2-LETEXPR
4771 js2-LOCAL_BLOCK
4772 js2-LOOP
4773 js2-NEW
4774 js2-REF_CALL
4775 js2-RETHROW
4776 js2-RETURN
4777 js2-RETURN_RESULT
4778 js2-SEMI
4779 js2-SETELEM
4780 js2-SETELEM_OP
4781 js2-SETNAME
4782 js2-SETPROP
4783 js2-SETPROP_OP
4784 js2-SETVAR
4785 js2-SET_REF
4786 js2-SET_REF_OP
4787 js2-SWITCH
4788 js2-TARGET
4789 js2-THROW
4790 js2-TRY
4791 js2-VAR
4792 js2-WHILE
4793 js2-WITH
4794 js2-WITHEXPR
4795 js2-YIELD))
4796 (aset tokens tt t))
4797 (if js2-instanceof-has-side-effects
4798 (aset tokens js2-INSTANCEOF t))
4799 tokens))
4800
4801 (defun js2-node-has-side-effects (node)
4802 "Return t if NODE has side effects."
4803 (when node ; makes it easier to handle malformed expressions
4804 (let ((tt (js2-node-type node)))
4805 (cond
4806 ;; This doubtless needs some work, since EXPR_VOID is used
4807 ;; in several ways in Rhino, and I may not have caught them all.
4808 ;; I'll wait for people to notice incorrect warnings.
4809 ((and (= tt js2-EXPR_VOID)
4810 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4811 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4812 ((= tt js2-COMMA)
4813 (js2-node-has-side-effects (js2-infix-node-right node)))
4814 ((or (= tt js2-AND)
4815 (= tt js2-OR))
4816 (or (js2-node-has-side-effects (js2-infix-node-right node))
4817 (js2-node-has-side-effects (js2-infix-node-left node))))
4818 ((= tt js2-HOOK)
4819 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4820 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4821 ((js2-paren-node-p node)
4822 (js2-node-has-side-effects (js2-paren-node-expr node)))
4823 ((= tt js2-ERROR) ; avoid cascaded error messages
4824 nil)
4825 (t
4826 (aref js2-side-effecting-tokens tt))))))
4827
4828 (defun js2-member-expr-leftmost-name (node)
4829 "For an expr such as foo.bar.baz, return leftmost node foo.
4830 NODE is any `js2-node' object. If it represents a member expression,
4831 which is any sequence of property gets, element-gets, function calls,
4832 or xml descendants/filter operators, then we look at the lexically
4833 leftmost (first) node in the chain. If it is a name-node we return it.
4834 Note that NODE can be a raw name-node and it will be returned as well.
4835 If NODE is not a name-node or member expression, or if it is a member
4836 expression whose leftmost target is not a name node, returns nil."
4837 (let ((continue t)
4838 result)
4839 (while (and continue (not result))
4840 (cond
4841 ((js2-name-node-p node)
4842 (setq result node))
4843 ((js2-prop-get-node-p node)
4844 (setq node (js2-prop-get-node-left node)))
4845 ;; TODO: handle call-nodes, xml-nodes, others?
4846 (t
4847 (setq continue nil))))
4848 result))
4849
4850 (defconst js2-stmt-node-types
4851 (list js2-BLOCK
4852 js2-BREAK
4853 js2-CONTINUE
4854 js2-DEFAULT ; e4x "default xml namespace" statement
4855 js2-DO
4856 js2-EXPR_RESULT
4857 js2-EXPR_VOID
4858 js2-FOR
4859 js2-IF
4860 js2-RETURN
4861 js2-SWITCH
4862 js2-THROW
4863 js2-TRY
4864 js2-WHILE
4865 js2-WITH)
4866 "Node types that only appear in statement contexts.
4867 The list does not include nodes that always appear as the child
4868 of another specific statement type, such as switch-cases,
4869 catch and finally blocks, and else-clauses. The list also excludes
4870 nodes like yield, let and var, which may appear in either expression
4871 or statement context, and in the latter context always have a
4872 `js2-expr-stmt-node' parent. Finally, the list does not include
4873 functions or scripts, which are treated separately from statements
4874 by the JavaScript parser and runtime.")
4875
4876 (defun js2-stmt-node-p (node)
4877 "Heuristic for figuring out if NODE is a statement.
4878 Some node types can appear in either an expression context or a
4879 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4880 For these node types in a statement context, the parent will be a
4881 `js2-expr-stmt-node'.
4882 Functions aren't included in the check."
4883 (memq (js2-node-type node) js2-stmt-node-types))
4884
4885 (defsubst js2-mode-find-first-stmt (node)
4886 "Search upward starting from NODE looking for a statement.
4887 For purposes of this function, a `js2-function-node' counts."
4888 (while (not (or (js2-stmt-node-p node)
4889 (js2-function-node-p node)))
4890 (setq node (js2-node-parent node)))
4891 node)
4892
4893 (defun js2-node-parent-stmt (node)
4894 "Return the node's first ancestor that is a statement.
4895 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4896 appearing in a statement context will have a parent that is a
4897 `js2-expr-stmt-node' that will be returned by this function."
4898 (let ((parent (js2-node-parent node)))
4899 (if (or (null parent)
4900 (js2-stmt-node-p parent)
4901 (and (js2-function-node-p parent)
4902 (not (eq (js2-function-node-form parent)
4903 'FUNCTION_EXPRESSION))))
4904 parent
4905 (js2-node-parent-stmt parent))))
4906
4907 ;; In the Mozilla Rhino sources, Roshan James writes:
4908 ;; Does consistent-return analysis on the function body when strict mode is
4909 ;; enabled.
4910 ;;
4911 ;; function (x) { return (x+1) }
4912 ;;
4913 ;; is ok, but
4914 ;;
4915 ;; function (x) { if (x < 0) return (x+1); }
4916 ;;
4917 ;; is not because the function can potentially return a value when the
4918 ;; condition is satisfied and if not, the function does not explicitly
4919 ;; return a value.
4920 ;;
4921 ;; This extends to checking mismatches such as "return" and "return <value>"
4922 ;; used in the same function. Warnings are not emitted if inconsistent
4923 ;; returns exist in code that can be statically shown to be unreachable.
4924 ;; Ex.
4925 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4926 ;;
4927 ;; emits no warning. However if the loop had a break statement, then a
4928 ;; warning would be emitted.
4929 ;;
4930 ;; The consistency analysis looks at control structures such as loops, ifs,
4931 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4932 ;; warns the user about an inconsistent set of termination possibilities.
4933 ;;
4934 ;; These flags enumerate the possible ways a statement/function can
4935 ;; terminate. These flags are used by endCheck() and by the Parser to
4936 ;; detect inconsistent return usage.
4937 ;;
4938 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4939 ;; able to execute (example: throw, continue)
4940 ;;
4941 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4942 ;; next one. Statement such as return dont. A compound statement may have
4943 ;; some branch that drops off control to the next statement.
4944 ;;
4945 ;; END_RETURNS indicates that the statement can return with no value.
4946 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4947 ;;
4948 ;; A compound statement such as
4949 ;; if (condition) {
4950 ;; return value;
4951 ;; }
4952 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4953
4954 (defconst js2-END_UNREACHED 0)
4955 (defconst js2-END_DROPS_OFF 1)
4956 (defconst js2-END_RETURNS 2)
4957 (defconst js2-END_RETURNS_VALUE 4)
4958 (defconst js2-END_YIELDS 8)
4959
4960 (defun js2-has-consistent-return-usage (node)
4961 "Check that every return usage in a function body is consistent.
4962 Returns t if the function satisfies strict mode requirement."
4963 (let ((n (js2-end-check node)))
4964 ;; either it doesn't return a value in any branch...
4965 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4966 ;; or it returns a value (or is unreached) at every branch
4967 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4968 js2-END_RETURNS
4969 js2-END_YIELDS)))))
4970
4971 (defun js2-end-check-if (node)
4972 "Returns in the then and else blocks must be consistent with each other.
4973 If there is no else block, then the return statement can fall through.
4974 Returns logical OR of END_* flags"
4975 (let ((th (js2-if-node-then-part node))
4976 (el (js2-if-node-else-part node)))
4977 (if (null th)
4978 js2-END_UNREACHED
4979 (logior (js2-end-check th) (if el
4980 (js2-end-check el)
4981 js2-END_DROPS_OFF)))))
4982
4983 (defun js2-end-check-switch (node)
4984 "Consistency of return statements is checked between the case statements.
4985 If there is no default, then the switch can fall through. If there is a
4986 default, we check to see if all code paths in the default return or if
4987 there is a code path that can fall through.
4988 Returns logical OR of END_* flags."
4989 (let ((rv js2-END_UNREACHED)
4990 default-case)
4991 ;; examine the cases
4992 (catch 'break
4993 (dolist (c (js2-switch-node-cases node))
4994 (if (js2-case-node-expr c)
4995 (js2-set-flag rv (js2-end-check-block c))
4996 (setq default-case c)
4997 (throw 'break nil))))
4998 ;; we don't care how the cases drop into each other
4999 (js2-clear-flag rv js2-END_DROPS_OFF)
5000 ;; examine the default
5001 (js2-set-flag rv (if default-case
5002 (js2-end-check default-case)
5003 js2-END_DROPS_OFF))
5004 rv))
5005
5006 (defun js2-end-check-try (node)
5007 "If the block has a finally, return consistency is checked in the
5008 finally block. If all code paths in the finally return, then the
5009 returns in the try-catch blocks don't matter. If there is a code path
5010 that does not return or if there is no finally block, the returns
5011 of the try and catch blocks are checked for mismatch.
5012 Returns logical OR of END_* flags."
5013 (let ((finally (js2-try-node-finally-block node))
5014 rv)
5015 ;; check the finally if it exists
5016 (setq rv (if finally
5017 (js2-end-check (js2-finally-node-body finally))
5018 js2-END_DROPS_OFF))
5019 ;; If the finally block always returns, then none of the returns
5020 ;; in the try or catch blocks matter.
5021 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5022 (js2-clear-flag rv js2-END_DROPS_OFF)
5023 ;; examine the try block
5024 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5025 ;; check each catch block
5026 (dolist (cb (js2-try-node-catch-clauses node))
5027 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5028 rv))
5029
5030 (defun js2-end-check-loop (node)
5031 "Return statement in the loop body must be consistent. The default
5032 assumption for any kind of a loop is that it will eventually terminate.
5033 The only exception is a loop with a constant true condition. Code that
5034 follows such a loop is examined only if one can statically determine
5035 that there is a break out of the loop.
5036
5037 for(... ; ... ; ...) {}
5038 for(... in ... ) {}
5039 while(...) { }
5040 do { } while(...)
5041
5042 Returns logical OR of END_* flags."
5043 (let ((rv (js2-end-check (js2-loop-node-body node)))
5044 (condition (cond
5045 ((js2-while-node-p node)
5046 (js2-while-node-condition node))
5047 ((js2-do-node-p node)
5048 (js2-do-node-condition node))
5049 ((js2-for-node-p node)
5050 (js2-for-node-condition node)))))
5051
5052 ;; check to see if the loop condition is always true
5053 (if (and condition
5054 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5055 (js2-clear-flag rv js2-END_DROPS_OFF))
5056
5057 ;; look for effect of breaks
5058 (js2-set-flag rv (js2-node-get-prop node
5059 'CONTROL_BLOCK_PROP
5060 js2-END_UNREACHED))
5061 rv))
5062
5063 (defun js2-end-check-block (node)
5064 "A general block of code is examined statement by statement.
5065 If any statement (even a compound one) returns in all branches, then
5066 subsequent statements are not examined.
5067 Returns logical OR of END_* flags."
5068 (let* ((rv js2-END_DROPS_OFF)
5069 (kids (js2-block-node-kids node))
5070 (n (car kids)))
5071 ;; Check each statment. If the statement can continue onto the next
5072 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5073 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5074 (js2-clear-flag rv js2-END_DROPS_OFF)
5075 (js2-set-flag rv (js2-end-check n))
5076 (setq kids (cdr kids)
5077 n (car kids)))
5078 rv))
5079
5080 (defun js2-end-check-label (node)
5081 "A labeled statement implies that there may be a break to the label.
5082 The function processes the labeled statement and then checks the
5083 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5084 particular label.
5085 Returns logical OR of END_* flags."
5086 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5087 (logior rv (js2-node-get-prop node
5088 'CONTROL_BLOCK_PROP
5089 js2-END_UNREACHED))))
5090
5091 (defun js2-end-check-break (node)
5092 "When a break is encountered annotate the statement being broken
5093 out of by setting its CONTROL_BLOCK_PROP property.
5094 Returns logical OR of END_* flags."
5095 (and (js2-break-node-target node)
5096 (js2-node-set-prop (js2-break-node-target node)
5097 'CONTROL_BLOCK_PROP
5098 js2-END_DROPS_OFF))
5099 js2-END_UNREACHED)
5100
5101 (defun js2-end-check (node)
5102 "Examine the body of a function, doing a basic reachability analysis.
5103 Returns a combination of flags END_* flags that indicate
5104 how the function execution can terminate. These constitute only the
5105 pessimistic set of termination conditions. It is possible that at
5106 runtime certain code paths will never be actually taken. Hence this
5107 analysis will flag errors in cases where there may not be errors.
5108 Returns logical OR of END_* flags"
5109 (let (kid)
5110 (cond
5111 ((js2-break-node-p node)
5112 (js2-end-check-break node))
5113 ((js2-expr-stmt-node-p node)
5114 (if (setq kid (js2-expr-stmt-node-expr node))
5115 (js2-end-check kid)
5116 js2-END_DROPS_OFF))
5117 ((or (js2-continue-node-p node)
5118 (js2-throw-node-p node))
5119 js2-END_UNREACHED)
5120 ((js2-return-node-p node)
5121 (if (setq kid (js2-return-node-retval node))
5122 js2-END_RETURNS_VALUE
5123 js2-END_RETURNS))
5124 ((js2-loop-node-p node)
5125 (js2-end-check-loop node))
5126 ((js2-switch-node-p node)
5127 (js2-end-check-switch node))
5128 ((js2-labeled-stmt-node-p node)
5129 (js2-end-check-label node))
5130 ((js2-if-node-p node)
5131 (js2-end-check-if node))
5132 ((js2-try-node-p node)
5133 (js2-end-check-try node))
5134 ((js2-block-node-p node)
5135 (if (null (js2-block-node-kids node))
5136 js2-END_DROPS_OFF
5137 (js2-end-check-block node)))
5138 ((js2-yield-node-p node)
5139 js2-END_YIELDS)
5140 (t
5141 js2-END_DROPS_OFF))))
5142
5143 (defun js2-always-defined-boolean-p (node)
5144 "Check if NODE always evaluates to true or false in boolean context.
5145 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5146 nor always false."
5147 (let ((tt (js2-node-type node))
5148 num)
5149 (cond
5150 ((or (= tt js2-FALSE) (= tt js2-NULL))
5151 'ALWAYS_FALSE)
5152 ((= tt js2-TRUE)
5153 'ALWAYS_TRUE)
5154 ((= tt js2-NUMBER)
5155 (setq num (js2-number-node-num-value node))
5156 (if (and (not (eq num 0.0e+NaN))
5157 (not (zerop num)))
5158 'ALWAYS_TRUE
5159 'ALWAYS_FALSE))
5160 (t
5161 nil))))
5162
5163 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5164 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5165
5166 (defvar js2-tokens nil
5167 "List of all defined token names.") ; initialized in `js2-token-names'
5168
5169 (defconst js2-token-names
5170 (let* ((names (make-vector js2-num-tokens -1))
5171 (case-fold-search nil) ; only match js2-UPPER_CASE
5172 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5173 (loop for sym in syms
5174 for i from 0
5175 do
5176 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5177 (not (boundp sym)))
5178 (aset names (symbol-value sym) ; code, e.g. 152
5179 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5180 (push sym js2-tokens)))
5181 names)
5182 "Vector mapping int values to token string names, sans `js2-' prefix.")
5183
5184 (defun js2-token-name (tok)
5185 "Return a string name for TOK, a token symbol or code.
5186 Signals an error if it's not a recognized token."
5187 (let ((code tok))
5188 (if (symbolp tok)
5189 (setq code (symbol-value tok)))
5190 (if (eq code -1)
5191 "ERROR"
5192 (if (and (numberp code)
5193 (not (minusp code))
5194 (< code js2-num-tokens))
5195 (aref js2-token-names code)
5196 (error "Invalid token: %s" code)))))
5197
5198 (defsubst js2-token-sym (tok)
5199 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5200 (intern (js2-token-name tok)))
5201
5202 (defconst js2-token-codes
5203 (let ((table (make-hash-table :test 'eq :size 256)))
5204 (loop for name across js2-token-names
5205 for sym = (intern (concat "js2-" name))
5206 do
5207 (puthash sym (symbol-value sym) table))
5208 ;; clean up a few that are "wrong" in Rhino's token codes
5209 (puthash 'js2-DELETE js2-DELPROP table)
5210 table)
5211 "Hashtable mapping token symbols to their bytecodes.")
5212
5213 (defsubst js2-token-code (sym)
5214 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5215 (or (gethash sym js2-token-codes)
5216 (error "Invalid token symbol: %s " sym))) ; signal code bug
5217
5218 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5219 (setq js2-token-end js2-ts-cursor)
5220 (js2-report-error msg nil
5221 (or beg js2-token-beg)
5222 (or len (- js2-token-end js2-token-beg)))
5223 (unless no-throw
5224 (throw 'return js2-ERROR)))
5225
5226 (defsubst js2-get-string-from-buffer ()
5227 "Reverse the char accumulator and return it as a string."
5228 (setq js2-token-end js2-ts-cursor)
5229 (if js2-ts-string-buffer
5230 (apply #'string (nreverse js2-ts-string-buffer))
5231 ""))
5232
5233 ;; TODO: could potentially avoid a lot of consing by allocating a
5234 ;; char buffer the way Rhino does.
5235 (defsubst js2-add-to-string (c)
5236 (push c js2-ts-string-buffer))
5237
5238 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5239 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5240 ;; any other character: when it's not part of the current token, we
5241 ;; unget it, allowing it to be read again by the following call.
5242 (defsubst js2-unget-char ()
5243 (decf js2-ts-cursor))
5244
5245 ;; Rhino distinguishes \r and \n line endings. We don't need to
5246 ;; because we only scan from Emacs buffers, which always use \n.
5247 (defsubst js2-get-char ()
5248 "Read and return the next character from the input buffer.
5249 Increments `js2-ts-lineno' if the return value is a newline char.
5250 Updates `js2-ts-cursor' to the point after the returned char.
5251 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5252 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5253 (let (c)
5254 ;; check for end of buffer
5255 (if (>= js2-ts-cursor (point-max))
5256 (setq js2-ts-hit-eof t
5257 js2-ts-cursor (1+ js2-ts-cursor)
5258 c js2-EOF_CHAR) ; return value
5259 ;; otherwise read next char
5260 (setq c (char-before (incf js2-ts-cursor)))
5261 ;; if we read a newline, update counters
5262 (if (= c ?\n)
5263 (setq js2-ts-line-start js2-ts-cursor
5264 js2-ts-lineno (1+ js2-ts-lineno)))
5265 ;; TODO: skip over format characters
5266 c)))
5267
5268 (defsubst js2-read-unicode-escape ()
5269 "Read a \\uNNNN sequence from the input.
5270 Assumes the ?\ and ?u have already been read.
5271 Returns the unicode character, or nil if it wasn't a valid character.
5272 Doesn't change the values of any scanner variables."
5273 ;; I really wish I knew a better way to do this, but I can't
5274 ;; find the Emacs function that takes a 16-bit int and converts
5275 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5276 ;; Have to first check that it's 4 hex characters or it may stop
5277 ;; the read early.
5278 (ignore-errors
5279 (let ((s (buffer-substring-no-properties js2-ts-cursor
5280 (+ 4 js2-ts-cursor))))
5281 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5282 (read (concat "?\\u" s))))))
5283
5284 (defsubst js2-match-char (test)
5285 "Consume and return next character if it matches TEST, a character.
5286 Returns nil and consumes nothing if TEST is not the next character."
5287 (let ((c (js2-get-char)))
5288 (if (eq c test)
5289 t
5290 (js2-unget-char)
5291 nil)))
5292
5293 (defsubst js2-peek-char ()
5294 (prog1
5295 (js2-get-char)
5296 (js2-unget-char)))
5297
5298 (defsubst js2-java-identifier-start-p (c)
5299 (or
5300 (memq c '(?$ ?_))
5301 (js2-char-uppercase-p c)
5302 (js2-char-lowercase-p c)))
5303
5304 (defsubst js2-java-identifier-part-p (c)
5305 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5306 ;; TODO: make me Unicode-friendly. See comments above.
5307 (or
5308 (memq c '(?$ ?_))
5309 (js2-char-uppercase-p c)
5310 (js2-char-lowercase-p c)
5311 (and (>= c ?0) (<= c ?9))))
5312
5313 (defsubst js2-alpha-p (c)
5314 (cond ((and (<= ?A c) (<= c ?Z)) t)
5315 ((and (<= ?a c) (<= c ?z)) t)
5316 (t nil)))
5317
5318 (defsubst js2-digit-p (c)
5319 (and (<= ?0 c) (<= c ?9)))
5320
5321 (defsubst js2-js-space-p (c)
5322 (if (<= c 127)
5323 (memq c '(#x20 #x9 #xB #xC #xD))
5324 (or
5325 (eq c #xA0)
5326 ;; TODO: change this nil to check for Unicode space character
5327 nil)))
5328
5329 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5330
5331 (defsubst js2-skip-line ()
5332 "Skip to end of line"
5333 (let (c)
5334 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5335 (js2-unget-char)
5336 (setq js2-token-end js2-ts-cursor)))
5337
5338 (defun js2-init-scanner (&optional buf line)
5339 "Create token stream for BUF starting on LINE.
5340 BUF defaults to current-buffer and line defaults to 1.
5341
5342 A buffer can only have one scanner active at a time, which yields
5343 dramatically simpler code than using a defstruct. If you need to
5344 have simultaneous scanners in a buffer, copy the regions to scan
5345 into temp buffers."
5346 (save-excursion
5347 (when buf
5348 (set-buffer buf))
5349 (setq js2-ts-dirty-line nil
5350 js2-ts-regexp-flags nil
5351 js2-ts-string ""
5352 js2-ts-number nil
5353 js2-ts-hit-eof nil
5354 js2-ts-line-start 0
5355 js2-ts-lineno (or line 1)
5356 js2-ts-line-end-char -1
5357 js2-ts-cursor (point-min)
5358 js2-ts-is-xml-attribute nil
5359 js2-ts-xml-is-tag-content nil
5360 js2-ts-xml-open-tags-count 0
5361 js2-ts-string-buffer nil)))
5362
5363 ;; This function uses the cached op, string and number fields in
5364 ;; TokenStream; if getToken has been called since the passed token
5365 ;; was scanned, the op or string printed may be incorrect.
5366 (defun js2-token-to-string (token)
5367 ;; Not sure where this function is used in Rhino. Not tested.
5368 (if (not js2-debug-print-trees)
5369 ""
5370 (let ((name (js2-token-name token)))
5371 (cond
5372 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5373 (concat name " `" js2-ts-string "'"))
5374 ((eq token js2-NUMBER)
5375 (format "NUMBER %g" js2-ts-number))
5376 (t
5377 name)))))
5378
5379 (defconst js2-keywords
5380 '(break
5381 case catch const continue
5382 debugger default delete do
5383 else enum
5384 false finally for function
5385 if in instanceof import
5386 let
5387 new null
5388 return
5389 switch
5390 this throw true try typeof
5391 var void
5392 while with
5393 yield))
5394
5395 ;; Token names aren't exactly the same as the keywords, unfortunately.
5396 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5397 (defconst js2-kwd-tokens
5398 (let ((table (make-vector js2-num-tokens nil))
5399 (tokens
5400 (list js2-BREAK
5401 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5402 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5403 js2-ELSE
5404 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5405 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5406 js2-LET
5407 js2-NEW js2-NULL
5408 js2-RETURN
5409 js2-SWITCH
5410 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5411 js2-VAR
5412 js2-WHILE js2-WITH
5413 js2-YIELD)))
5414 (dolist (i tokens)
5415 (aset table i 'font-lock-keyword-face))
5416 (aset table js2-STRING 'font-lock-string-face)
5417 (aset table js2-REGEXP 'font-lock-string-face)
5418 (aset table js2-COMMENT 'font-lock-comment-face)
5419 (aset table js2-THIS 'font-lock-builtin-face)
5420 (aset table js2-VOID 'font-lock-constant-face)
5421 (aset table js2-NULL 'font-lock-constant-face)
5422 (aset table js2-TRUE 'font-lock-constant-face)
5423 (aset table js2-FALSE 'font-lock-constant-face)
5424 table)
5425 "Vector whose values are non-nil for tokens that are keywords.
5426 The values are default faces to use for highlighting the keywords.")
5427
5428 (defconst js2-reserved-words
5429 '(abstract
5430 boolean byte
5431 char class
5432 double
5433 enum export extends
5434 final float
5435 goto
5436 implements import int interface
5437 long
5438 native
5439 package private protected public
5440 short static super synchronized
5441 throws transient
5442 volatile))
5443
5444 (defconst js2-keyword-names
5445 (let ((table (make-hash-table :test 'equal)))
5446 (loop for k in js2-keywords
5447 do (puthash
5448 (symbol-name k) ; instanceof
5449 (intern (concat "js2-"
5450 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5451 table))
5452 table)
5453 "JavaScript keywords by name, mapped to their symbols.")
5454
5455 (defconst js2-reserved-word-names
5456 (let ((table (make-hash-table :test 'equal)))
5457 (loop for k in js2-reserved-words
5458 do
5459 (puthash (symbol-name k) 'js2-RESERVED table))
5460 table)
5461 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5462
5463 (defsubst js2-collect-string (buf)
5464 "Convert BUF, a list of chars, to a string.
5465 Reverses BUF before converting."
5466 (cond
5467 ((stringp buf)
5468 buf)
5469 ((null buf) ; for emacs21 compat
5470 "")
5471 (t
5472 (if buf
5473 (apply #'string (nreverse buf))
5474 ""))))
5475
5476 (defun js2-string-to-keyword (s)
5477 "Return token for S, a string, if S is a keyword or reserved word.
5478 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5479 (or (gethash s js2-keyword-names)
5480 (gethash s js2-reserved-word-names)))
5481
5482 (defsubst js2-ts-set-char-token-bounds ()
5483 "Used when next token is one character."
5484 (setq js2-token-beg (1- js2-ts-cursor)
5485 js2-token-end js2-ts-cursor))
5486
5487 (defsubst js2-ts-return (token)
5488 "Return an N-character TOKEN from `js2-get-token'.
5489 Updates `js2-token-end' accordingly."
5490 (setq js2-token-end js2-ts-cursor)
5491 (throw 'return token))
5492
5493 (defsubst js2-x-digit-to-int (c accumulator)
5494 "Build up a hex number.
5495 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5496 corresponding number. Otherwise return -1."
5497 (catch 'return
5498 (catch 'check
5499 ;; Use 0..9 < A..Z < a..z
5500 (cond
5501 ((<= c ?9)
5502 (decf c ?0)
5503 (if (<= 0 c)
5504 (throw 'check nil)))
5505 ((<= c ?F)
5506 (when (<= ?A c)
5507 (decf c (- ?A 10))
5508 (throw 'check nil)))
5509 ((<= c ?f)
5510 (when (<= ?a c)
5511 (decf c (- ?a 10))
5512 (throw 'check nil))))
5513 (throw 'return -1))
5514 (logior c (lsh accumulator 4))))
5515
5516 (defun js2-get-token ()
5517 "Return next JavaScript token, an int such as js2-RETURN."
5518 (let (c
5519 c1
5520 identifier-start
5521 is-unicode-escape-start
5522 contains-escape
5523 escape-val
5524 escape-start
5525 str
5526 result
5527 base
5528 is-integer
5529 quote-char
5530 val
5531 look-for-slash
5532 continue)
5533 (catch 'return
5534 (while t
5535 ;; Eat whitespace, possibly sensitive to newlines.
5536 (setq continue t)
5537 (while continue
5538 (setq c (js2-get-char))
5539 (cond
5540 ((eq c js2-EOF_CHAR)
5541 (js2-ts-set-char-token-bounds)
5542 (throw 'return js2-EOF))
5543 ((eq c ?\n)
5544 (js2-ts-set-char-token-bounds)
5545 (setq js2-ts-dirty-line nil)
5546 (throw 'return js2-EOL))
5547 ((not (js2-js-space-p c))
5548 (if (/= c ?-) ; in case end of HTML comment
5549 (setq js2-ts-dirty-line t))
5550 (setq continue nil))))
5551 ;; Assume the token will be 1 char - fixed up below.
5552 (js2-ts-set-char-token-bounds)
5553 (when (eq c ?@)
5554 (throw 'return js2-XMLATTR))
5555 ;; identifier/keyword/instanceof?
5556 ;; watch out for starting with a <backslash>
5557 (cond
5558 ((eq c ?\\)
5559 (setq c (js2-get-char))
5560 (if (eq c ?u)
5561 (setq identifier-start t
5562 is-unicode-escape-start t
5563 js2-ts-string-buffer nil)
5564 (setq identifier-start nil)
5565 (js2-unget-char)
5566 (setq c ?\\)))
5567 (t
5568 (when (setq identifier-start (js2-java-identifier-start-p c))
5569 (setq js2-ts-string-buffer nil)
5570 (js2-add-to-string c))))
5571 (when identifier-start
5572 (setq contains-escape is-unicode-escape-start)
5573 (catch 'break
5574 (while t
5575 (if is-unicode-escape-start
5576 ;; strictly speaking we should probably push-back
5577 ;; all the bad characters if the <backslash>uXXXX
5578 ;; sequence is malformed. But since there isn't a
5579 ;; correct context(is there?) for a bad Unicode
5580 ;; escape sequence in an identifier, we can report
5581 ;; an error here.
5582 (progn
5583 (setq escape-val 0)
5584 (dotimes (i 4)
5585 (setq c (js2-get-char)
5586 escape-val (js2-x-digit-to-int c escape-val))
5587 ;; Next check takes care of c < 0 and bad escape
5588 (if (minusp escape-val)
5589 (throw 'break nil)))
5590 (if (minusp escape-val)
5591 (js2-report-scan-error "msg.invalid.escape" t))
5592 (js2-add-to-string escape-val)
5593 (setq is-unicode-escape-start nil))
5594 (setq c (js2-get-char))
5595 (cond
5596 ((eq c ?\\)
5597 (setq c (js2-get-char))
5598 (if (eq c ?u)
5599 (setq is-unicode-escape-start t
5600 contains-escape t)
5601 (js2-report-scan-error "msg.illegal.character" t)))
5602 (t
5603 (if (or (eq c js2-EOF_CHAR)
5604 (not (js2-java-identifier-part-p c)))
5605 (throw 'break nil))
5606 (js2-add-to-string c))))))
5607 (js2-unget-char)
5608 (setq str (js2-get-string-from-buffer))
5609 (unless contains-escape
5610 ;; OPT we shouldn't have to make a string (object!) to
5611 ;; check if it's a keyword.
5612 ;; Return the corresponding token if it's a keyword
5613 (when (setq result (js2-string-to-keyword str))
5614 (if (and (< js2-language-version 170)
5615 (memq result '(js2-LET js2-YIELD)))
5616 ;; LET and YIELD are tokens only in 1.7 and later
5617 (setq result 'js2-NAME))
5618 (if (not (eq result 'js2-RESERVED))
5619 (throw 'return (js2-token-code result)))
5620 (js2-report-warning "msg.reserved.keyword" str)))
5621 ;; If we want to intern these as Rhino does, just use (intern str)
5622 (setq js2-ts-string str)
5623 (throw 'return js2-NAME)) ; end identifier/kwd check
5624 ;; is it a number?
5625 (when (or (js2-digit-p c)
5626 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5627 (setq js2-ts-string-buffer nil
5628 base 10)
5629 (when (eq c ?0)
5630 (setq c (js2-get-char))
5631 (cond
5632 ((or (eq c ?x) (eq c ?X))
5633 (setq base 16)
5634 (setq c (js2-get-char)))
5635 ((js2-digit-p c)
5636 (setq base 8))
5637 (t
5638 (js2-add-to-string ?0))))
5639 (if (eq base 16)
5640 (while (<= 0 (js2-x-digit-to-int c 0))
5641 (js2-add-to-string c)
5642 (setq c (js2-get-char)))
5643 (while (and (<= ?0 c) (<= c ?9))
5644 ;; We permit 08 and 09 as decimal numbers, which
5645 ;; makes our behavior a superset of the ECMA
5646 ;; numeric grammar. We might not always be so
5647 ;; permissive, so we warn about it.
5648 (when (and (eq base 8) (>= c ?8))
5649 (js2-report-warning "msg.bad.octal.literal"
5650 (if (eq c ?8) "8" "9"))
5651 (setq base 10))
5652 (js2-add-to-string c)
5653 (setq c (js2-get-char))))
5654 (setq is-integer t)
5655 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5656 (setq is-integer nil)
5657 (when (eq c ?.)
5658 (loop do
5659 (js2-add-to-string c)
5660 (setq c (js2-get-char))
5661 while (js2-digit-p c)))
5662 (when (memq c '(?e ?E))
5663 (js2-add-to-string c)
5664 (setq c (js2-get-char))
5665 (when (memq c '(?+ ?-))
5666 (js2-add-to-string c)
5667 (setq c (js2-get-char)))
5668 (unless (js2-digit-p c)
5669 (js2-report-scan-error "msg.missing.exponent" t))
5670 (loop do
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char))
5673 while (js2-digit-p c))))
5674 (js2-unget-char)
5675 (setq js2-ts-string (js2-get-string-from-buffer)
5676 js2-ts-number
5677 (if (and (eq base 10) (not is-integer))
5678 (string-to-number js2-ts-string)
5679 ;; TODO: call runtime number-parser. Some of it is in
5680 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5681 (string-to-number js2-ts-string)))
5682 (throw 'return js2-NUMBER))
5683 ;; is it a string?
5684 (when (memq c '(?\" ?\'))
5685 ;; We attempt to accumulate a string the fast way, by
5686 ;; building it directly out of the reader. But if there
5687 ;; are any escaped characters in the string, we revert to
5688 ;; building it out of a string buffer.
5689 (setq quote-char c
5690 js2-ts-string-buffer nil
5691 c (js2-get-char))
5692 (catch 'break
5693 (while (/= c quote-char)
5694 (catch 'continue
5695 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5696 (js2-unget-char)
5697 (setq js2-token-end js2-ts-cursor)
5698 (js2-report-error "msg.unterminated.string.lit")
5699 (throw 'return js2-STRING))
5700 (when (eq c ?\\)
5701 ;; We've hit an escaped character
5702 (setq c (js2-get-char))
5703 (case c
5704 (?b (setq c ?\b))
5705 (?f (setq c ?\f))
5706 (?n (setq c ?\n))
5707 (?r (setq c ?\r))
5708 (?t (setq c ?\t))
5709 (?v (setq c ?\v))
5710 (?u
5711 (setq c1 (js2-read-unicode-escape))
5712 (if js2-parse-ide-mode
5713 (if c1
5714 (progn
5715 ;; just copy the string in IDE-mode
5716 (js2-add-to-string ?\\)
5717 (js2-add-to-string ?u)
5718 (dotimes (i 3)
5719 (js2-add-to-string (js2-get-char)))
5720 (setq c (js2-get-char))) ; added at end of loop
5721 ;; flag it as an invalid escape
5722 (js2-report-warning "msg.invalid.escape"
5723 nil (- js2-ts-cursor 2) 6))
5724 ;; Get 4 hex digits; if the u escape is not
5725 ;; followed by 4 hex digits, use 'u' + the
5726 ;; literal character sequence that follows.
5727 (js2-add-to-string ?u)
5728 (setq escape-val 0)
5729 (dotimes (i 4)
5730 (setq c (js2-get-char)
5731 escape-val (js2-x-digit-to-int c escape-val))
5732 (if (minusp escape-val)
5733 (throw 'continue nil))
5734 (js2-add-to-string c))
5735 ;; prepare for replace of stored 'u' sequence by escape value
5736 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5737 c escape-val)))
5738 (?x
5739 ;; Get 2 hex digits, defaulting to 'x'+literal
5740 ;; sequence, as above.
5741 (setq c (js2-get-char)
5742 escape-val (js2-x-digit-to-int c 0))
5743 (if (minusp escape-val)
5744 (progn
5745 (js2-add-to-string ?x)
5746 (throw 'continue nil))
5747 (setq c1 c
5748 c (js2-get-char)
5749 escape-val (js2-x-digit-to-int c escape-val))
5750 (if (minusp escape-val)
5751 (progn
5752 (js2-add-to-string ?x)
5753 (js2-add-to-string c1)
5754 (throw 'continue nil))
5755 ;; got 2 hex digits
5756 (setq c escape-val))))
5757 (?\n
5758 ;; Remove line terminator after escape to follow
5759 ;; SpiderMonkey and C/C++
5760 (setq c (js2-get-char))
5761 (throw 'continue nil))
5762 (t
5763 (when (and (<= ?0 c) (< c ?8))
5764 (setq val (- c ?0)
5765 c (js2-get-char))
5766 (when (and (<= ?0 c) (< c ?8))
5767 (setq val (- (+ (* 8 val) c) ?0)
5768 c (js2-get-char))
5769 (when (and (<= ?0 c)
5770 (< c ?8)
5771 (< val #o37))
5772 ;; c is 3rd char of octal sequence only
5773 ;; if the resulting val <= 0377
5774 (setq val (- (+ (* 8 val) c) ?0)
5775 c (js2-get-char))))
5776 (js2-unget-char)
5777 (setq c val)))))
5778 (js2-add-to-string c)
5779 (setq c (js2-get-char)))))
5780 (setq js2-ts-string (js2-get-string-from-buffer))
5781 (throw 'return js2-STRING))
5782 (case c
5783 (?\;
5784 (throw 'return js2-SEMI))
5785 (?\[
5786 (throw 'return js2-LB))
5787 (?\]
5788 (throw 'return js2-RB))
5789 (?{
5790 (throw 'return js2-LC))
5791 (?}
5792 (throw 'return js2-RC))
5793 (?\(
5794 (throw 'return js2-LP))
5795 (?\)
5796 (throw 'return js2-RP))
5797 (?,
5798 (throw 'return js2-COMMA))
5799 (??
5800 (throw 'return js2-HOOK))
5801 (?:
5802 (if (js2-match-char ?:)
5803 (js2-ts-return js2-COLONCOLON)
5804 (throw 'return js2-COLON)))
5805 (?.
5806 (if (js2-match-char ?.)
5807 (js2-ts-return js2-DOTDOT)
5808 (if (js2-match-char ?\()
5809 (js2-ts-return js2-DOTQUERY)
5810 (throw 'return js2-DOT))))
5811 (?|
5812 (if (js2-match-char ?|)
5813 (throw 'return js2-OR)
5814 (if (js2-match-char ?=)
5815 (js2-ts-return js2-ASSIGN_BITOR)
5816 (throw 'return js2-BITOR))))
5817 (?^
5818 (if (js2-match-char ?=)
5819 (js2-ts-return js2-ASSIGN_BITOR)
5820 (throw 'return js2-BITXOR)))
5821 (?&
5822 (if (js2-match-char ?&)
5823 (throw 'return js2-AND)
5824 (if (js2-match-char ?=)
5825 (js2-ts-return js2-ASSIGN_BITAND)
5826 (throw 'return js2-BITAND))))
5827 (?=
5828 (if (js2-match-char ?=)
5829 (if (js2-match-char ?=)
5830 (js2-ts-return js2-SHEQ)
5831 (throw 'return js2-EQ))
5832 (throw 'return js2-ASSIGN)))
5833 (?!
5834 (if (js2-match-char ?=)
5835 (if (js2-match-char ?=)
5836 (js2-ts-return js2-SHNE)
5837 (js2-ts-return js2-NE))
5838 (throw 'return js2-NOT)))
5839 (?<
5840 ;; NB:treat HTML begin-comment as comment-till-eol
5841 (when (js2-match-char ?!)
5842 (when (js2-match-char ?-)
5843 (when (js2-match-char ?-)
5844 (js2-skip-line)
5845 (setq js2-ts-comment-type 'html)
5846 (throw 'return js2-COMMENT)))
5847 (js2-unget-char))
5848 (if (js2-match-char ?<)
5849 (if (js2-match-char ?=)
5850 (js2-ts-return js2-ASSIGN_LSH)
5851 (js2-ts-return js2-LSH))
5852 (if (js2-match-char ?=)
5853 (js2-ts-return js2-LE)
5854 (throw 'return js2-LT))))
5855 (?>
5856 (if (js2-match-char ?>)
5857 (if (js2-match-char ?>)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-ASSIGN_URSH)
5860 (js2-ts-return js2-URSH))
5861 (if (js2-match-char ?=)
5862 (js2-ts-return js2-ASSIGN_RSH)
5863 (js2-ts-return js2-RSH)))
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-GE)
5866 (throw 'return js2-GT))))
5867 (?*
5868 (if (js2-match-char ?=)
5869 (js2-ts-return js2-ASSIGN_MUL)
5870 (throw 'return js2-MUL)))
5871 (?/
5872 ;; is it a // comment?
5873 (when (js2-match-char ?/)
5874 (setq js2-token-beg (- js2-ts-cursor 2))
5875 (js2-skip-line)
5876 (setq js2-ts-comment-type 'line)
5877 ;; include newline so highlighting goes to end of window
5878 (incf js2-token-end)
5879 (throw 'return js2-COMMENT))
5880 ;; is it a /* comment?
5881 (when (js2-match-char ?*)
5882 (setq look-for-slash nil
5883 js2-token-beg (- js2-ts-cursor 2)
5884 js2-ts-comment-type
5885 (if (js2-match-char ?*)
5886 (progn
5887 (setq look-for-slash t)
5888 'jsdoc)
5889 'block))
5890 (while t
5891 (setq c (js2-get-char))
5892 (cond
5893 ((eq c js2-EOF_CHAR)
5894 (setq js2-token-end (1- js2-ts-cursor))
5895 (js2-report-error "msg.unterminated.comment")
5896 (throw 'return js2-COMMENT))
5897 ((eq c ?*)
5898 (setq look-for-slash t))
5899 ((eq c ?/)
5900 (if look-for-slash
5901 (js2-ts-return js2-COMMENT)))
5902 (t
5903 (setq look-for-slash nil
5904 js2-token-end js2-ts-cursor)))))
5905 (if (js2-match-char ?=)
5906 (js2-ts-return js2-ASSIGN_DIV)
5907 (throw 'return js2-DIV)))
5908 (?#
5909 (when js2-skip-preprocessor-directives
5910 (js2-skip-line)
5911 (setq js2-ts-comment-type 'preprocessor
5912 js2-token-end js2-ts-cursor)
5913 (throw 'return js2-COMMENT))
5914 (throw 'return js2-ERROR))
5915 (?%
5916 (if (js2-match-char ?=)
5917 (js2-ts-return js2-ASSIGN_MOD)
5918 (throw 'return js2-MOD)))
5919 (?~
5920 (throw 'return js2-BITNOT))
5921 (?+
5922 (if (js2-match-char ?=)
5923 (js2-ts-return js2-ASSIGN_ADD)
5924 (if (js2-match-char ?+)
5925 (js2-ts-return js2-INC)
5926 (throw 'return js2-ADD))))
5927 (?-
5928 (cond
5929 ((js2-match-char ?=)
5930 (setq c js2-ASSIGN_SUB))
5931 ((js2-match-char ?-)
5932 (unless js2-ts-dirty-line
5933 ;; treat HTML end-comment after possible whitespace
5934 ;; after line start as comment-until-eol
5935 (when (js2-match-char ?>)
5936 (js2-skip-line)
5937 (setq js2-ts-comment-type 'html)
5938 (throw 'return js2-COMMENT)))
5939 (setq c js2-DEC))
5940 (t
5941 (setq c js2-SUB)))
5942 (setq js2-ts-dirty-line t)
5943 (js2-ts-return c))
5944 (otherwise
5945 (js2-report-scan-error "msg.illegal.character")))))))
5946
5947 (defun js2-read-regexp (start-token)
5948 "Called by parser when it gets / or /= in literal context."
5949 (let (c
5950 err
5951 in-class ; inside a '[' .. ']' character-class
5952 flags
5953 (continue t))
5954 (setq js2-token-beg js2-ts-cursor
5955 js2-ts-string-buffer nil
5956 js2-ts-regexp-flags nil)
5957 (if (eq start-token js2-ASSIGN_DIV)
5958 ;; mis-scanned /=
5959 (js2-add-to-string ?=)
5960 (if (not (eq start-token js2-DIV))
5961 (error "failed assertion")))
5962 (while (and (not err)
5963 (or (/= (setq c (js2-get-char)) ?/)
5964 in-class))
5965 (cond
5966 ((or (= c ?\n)
5967 (= c js2-EOF_CHAR))
5968 (setq js2-token-end (1- js2-ts-cursor)
5969 err t
5970 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5971 (js2-report-error "msg.unterminated.re.lit"))
5972 (t (cond
5973 ((= c ?\\)
5974 (js2-add-to-string c)
5975 (setq c (js2-get-char)))
5976 ((= c ?\[)
5977 (setq in-class t))
5978 ((= c ?\])
5979 (setq in-class nil)))
5980 (js2-add-to-string c))))
5981 (unless err
5982 (while continue
5983 (cond
5984 ((js2-match-char ?g)
5985 (push ?g flags))
5986 ((js2-match-char ?i)
5987 (push ?i flags))
5988 ((js2-match-char ?m)
5989 (push ?m flags))
5990 (t
5991 (setq continue nil))))
5992 (if (js2-alpha-p (js2-peek-char))
5993 (js2-report-scan-error "msg.invalid.re.flag" t
5994 js2-ts-cursor 1))
5995 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5996 js2-ts-regexp-flags (js2-collect-string flags)
5997 js2-token-end js2-ts-cursor)
5998 ;; tell `parse-partial-sexp' to ignore this range of chars
5999 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6000
6001 (defun js2-get-first-xml-token ()
6002 (setq js2-ts-xml-open-tags-count 0
6003 js2-ts-is-xml-attribute nil
6004 js2-ts-xml-is-tag-content nil)
6005 (js2-unget-char)
6006 (js2-get-next-xml-token))
6007
6008 (defsubst js2-xml-discard-string ()
6009 "Throw away the string in progress and flag an XML parse error."
6010 (setq js2-ts-string-buffer nil
6011 js2-ts-string nil)
6012 (js2-report-scan-error "msg.XML.bad.form" t))
6013
6014 (defun js2-get-next-xml-token ()
6015 (setq js2-ts-string-buffer nil ; for recording the XML
6016 js2-token-beg js2-ts-cursor)
6017 (let (c result)
6018 (setq result
6019 (catch 'return
6020 (while t
6021 (setq c (js2-get-char))
6022 (cond
6023 ((= c js2-EOF_CHAR)
6024 (throw 'return js2-ERROR))
6025 (js2-ts-xml-is-tag-content
6026 (case c
6027 (?>
6028 (js2-add-to-string c)
6029 (setq js2-ts-xml-is-tag-content nil
6030 js2-ts-is-xml-attribute nil))
6031 (?/
6032 (js2-add-to-string c)
6033 (when (eq ?> (js2-peek-char))
6034 (setq c (js2-get-char))
6035 (js2-add-to-string c)
6036 (setq js2-ts-xml-is-tag-content nil)
6037 (decf js2-ts-xml-open-tags-count)))
6038 (?{
6039 (js2-unget-char)
6040 (setq js2-ts-string (js2-get-string-from-buffer))
6041 (throw 'return js2-XML))
6042 ((?\' ?\")
6043 (js2-add-to-string c)
6044 (unless (js2-read-quoted-string c)
6045 (throw 'return js2-ERROR)))
6046 (?=
6047 (js2-add-to-string c)
6048 (setq js2-ts-is-xml-attribute t))
6049 ((? ?\t ?\r ?\n)
6050 (js2-add-to-string c))
6051 (t
6052 (js2-add-to-string c)
6053 (setq js2-ts-is-xml-attribute nil)))
6054 (when (and (not js2-ts-xml-is-tag-content)
6055 (zerop js2-ts-xml-open-tags-count))
6056 (setq js2-ts-string (js2-get-string-from-buffer))
6057 (throw 'return js2-XMLEND)))
6058 (t
6059 ;; else not tag content
6060 (case c
6061 (?<
6062 (js2-add-to-string c)
6063 (setq c (js2-peek-char))
6064 (case c
6065 (?!
6066 (setq c (js2-get-char)) ;; skip !
6067 (js2-add-to-string c)
6068 (setq c (js2-peek-char))
6069 (case c
6070 (?-
6071 (setq c (js2-get-char)) ;; skip -
6072 (js2-add-to-string c)
6073 (if (eq c ?-)
6074 (progn
6075 (js2-add-to-string c)
6076 (unless (js2-read-xml-comment)
6077 (throw 'return js2-ERROR)))
6078 (js2-xml-discard-string)
6079 (throw 'return js2-ERROR)))
6080 (?\[
6081 (setq c (js2-get-char)) ;; skip [
6082 (js2-add-to-string c)
6083 (if (and (= (js2-get-char) ?C)
6084 (= (js2-get-char) ?D)
6085 (= (js2-get-char) ?A)
6086 (= (js2-get-char) ?T)
6087 (= (js2-get-char) ?A)
6088 (= (js2-get-char) ?\[))
6089 (progn
6090 (js2-add-to-string ?C)
6091 (js2-add-to-string ?D)
6092 (js2-add-to-string ?A)
6093 (js2-add-to-string ?T)
6094 (js2-add-to-string ?A)
6095 (js2-add-to-string ?\[)
6096 (unless (js2-read-cdata)
6097 (throw 'return js2-ERROR)))
6098 (js2-xml-discard-string)
6099 (throw 'return js2-ERROR)))
6100 (t
6101 (unless (js2-read-entity)
6102 (throw 'return js2-ERROR)))))
6103 (??
6104 (setq c (js2-get-char)) ;; skip ?
6105 (js2-add-to-string c)
6106 (unless (js2-read-PI)
6107 (throw 'return js2-ERROR)))
6108 (?/
6109 ;; end tag
6110 (setq c (js2-get-char)) ;; skip /
6111 (js2-add-to-string c)
6112 (when (zerop js2-ts-xml-open-tags-count)
6113 (js2-xml-discard-string)
6114 (throw 'return js2-ERROR))
6115 (setq js2-ts-xml-is-tag-content t)
6116 (decf js2-ts-xml-open-tags-count))
6117 (t
6118 ;; start tag
6119 (setq js2-ts-xml-is-tag-content t)
6120 (incf js2-ts-xml-open-tags-count))))
6121 (?{
6122 (js2-unget-char)
6123 (setq js2-ts-string (js2-get-string-from-buffer))
6124 (throw 'return js2-XML))
6125 (t
6126 (js2-add-to-string c))))))))
6127 (setq js2-token-end js2-ts-cursor)
6128 result))
6129
6130 (defun js2-read-quoted-string (quote)
6131 (let (c)
6132 (catch 'return
6133 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6134 (js2-add-to-string c)
6135 (if (eq c quote)
6136 (throw 'return t)))
6137 (js2-xml-discard-string) ;; throw away string in progress
6138 nil)))
6139
6140 (defun js2-read-xml-comment ()
6141 (let ((c (js2-get-char)))
6142 (catch 'return
6143 (while (/= c js2-EOF_CHAR)
6144 (catch 'continue
6145 (js2-add-to-string c)
6146 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6147 (setq c (js2-get-char))
6148 (js2-add-to-string c)
6149 (if (eq (js2-peek-char) ?>)
6150 (progn
6151 (setq c (js2-get-char)) ;; skip >
6152 (js2-add-to-string c)
6153 (throw 'return t))
6154 (throw 'continue nil)))
6155 (setq c (js2-get-char))))
6156 (js2-xml-discard-string)
6157 nil)))
6158
6159 (defun js2-read-cdata ()
6160 (let ((c (js2-get-char)))
6161 (catch 'return
6162 (while (/= c js2-EOF_CHAR)
6163 (catch 'continue
6164 (js2-add-to-string c)
6165 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6166 (setq c (js2-get-char))
6167 (js2-add-to-string c)
6168 (if (eq (js2-peek-char) ?>)
6169 (progn
6170 (setq c (js2-get-char)) ;; Skip >
6171 (js2-add-to-string c)
6172 (throw 'return t))
6173 (throw 'continue nil)))
6174 (setq c (js2-get-char))))
6175 (js2-xml-discard-string)
6176 nil)))
6177
6178 (defun js2-read-entity ()
6179 (let ((decl-tags 1)
6180 c)
6181 (catch 'return
6182 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6183 (js2-add-to-string c)
6184 (case c
6185 (?<
6186 (incf decl-tags))
6187 (?>
6188 (decf decl-tags)
6189 (if (zerop decl-tags)
6190 (throw 'return t)))))
6191 (js2-xml-discard-string)
6192 nil)))
6193
6194 (defun js2-read-PI ()
6195 "Scan an XML processing instruction."
6196 (let (c)
6197 (catch 'return
6198 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6199 (js2-add-to-string c)
6200 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6201 (setq c (js2-get-char)) ;; Skip >
6202 (js2-add-to-string c)
6203 (throw 'return t)))
6204 (js2-xml-discard-string)
6205 nil)))
6206
6207 (defun js2-scanner-get-line ()
6208 "Return the text of the current scan line."
6209 (buffer-substring (point-at-bol) (point-at-eol)))
6210
6211 ;;; Highlighting
6212
6213 (defsubst js2-set-face (beg end face &optional record)
6214 "Fontify a region. If RECORD is non-nil, record for later."
6215 (when (plusp js2-highlight-level)
6216 (setq beg (min (point-max) beg)
6217 beg (max (point-min) beg)
6218 end (min (point-max) end)
6219 end (max (point-min) end))
6220 (if record
6221 (push (list beg end face) js2-mode-fontifications)
6222 (put-text-property beg end 'face face))))
6223
6224 (defsubst js2-set-kid-face (pos kid len face)
6225 "Set-face on a child node.
6226 POS is absolute buffer position of parent.
6227 KID is the child node.
6228 LEN is the length to fontify.
6229 FACE is the face to fontify with."
6230 (js2-set-face (+ pos (js2-node-pos kid))
6231 (+ pos (js2-node-pos kid) (js2-node-len kid))
6232 face))
6233
6234 (defsubst js2-fontify-kwd (start length)
6235 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6236
6237 (defsubst js2-clear-face (beg end)
6238 (remove-text-properties beg end '(face nil
6239 help-echo nil
6240 point-entered nil
6241 c-in-sws nil)))
6242
6243 (defconst js2-ecma-global-props
6244 (concat "^"
6245 (regexp-opt
6246 '("Infinity" "NaN" "undefined" "arguments") t)
6247 "$")
6248 "Value properties of the Ecma-262 Global Object.
6249 Shown at or above `js2-highlight-level' 2.")
6250
6251 ;; might want to add the name "arguments" to this list?
6252 (defconst js2-ecma-object-props
6253 (concat "^"
6254 (regexp-opt
6255 '("prototype" "__proto__" "__parent__") t)
6256 "$")
6257 "Value properties of the Ecma-262 Object constructor.
6258 Shown at or above `js2-highlight-level' 2.")
6259
6260 (defconst js2-ecma-global-funcs
6261 (concat
6262 "^"
6263 (regexp-opt
6264 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6265 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6266 "$")
6267 "Function properties of the Ecma-262 Global object.
6268 Shown at or above `js2-highlight-level' 2.")
6269
6270 (defconst js2-ecma-number-props
6271 (concat "^"
6272 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6273 "NEGATIVE_INFINITY"
6274 "POSITIVE_INFINITY") t)
6275 "$")
6276 "Properties of the Ecma-262 Number constructor.
6277 Shown at or above `js2-highlight-level' 2.")
6278
6279 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6280 "Properties of the Ecma-262 Date constructor.
6281 Shown at or above `js2-highlight-level' 2.")
6282
6283 (defconst js2-ecma-math-props
6284 (concat "^"
6285 (regexp-opt
6286 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6287 t)
6288 "$")
6289 "Properties of the Ecma-262 Math object.
6290 Shown at or above `js2-highlight-level' 2.")
6291
6292 (defconst js2-ecma-math-funcs
6293 (concat "^"
6294 (regexp-opt
6295 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6296 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6297 "$")
6298 "Function properties of the Ecma-262 Math object.
6299 Shown at or above `js2-highlight-level' 2.")
6300
6301 (defconst js2-ecma-function-props
6302 (concat
6303 "^"
6304 (regexp-opt
6305 '(;; properties of the Object prototype object
6306 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6307 "toLocaleString" "toString" "valueOf"
6308 ;; properties of the Function prototype object
6309 "apply" "call"
6310 ;; properties of the Array prototype object
6311 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6312 "splice" "unshift"
6313 ;; properties of the String prototype object
6314 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6315 "localeCompare" "match" "replace" "search" "split" "substring"
6316 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6317 "toUpperCase"
6318 ;; properties of the Number prototype object
6319 "toExponential" "toFixed" "toPrecision"
6320 ;; properties of the Date prototype object
6321 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6322 "getMinutes" "getMonth" "getSeconds" "getTime"
6323 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6324 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6325 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6326 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6327 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6328 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6329 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6330 "toTimeString" "toUTCString"
6331 ;; properties of the RegExp prototype object
6332 "exec" "test"
6333 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6334 "toSource" "__defineGetter__" "__defineSetter__"
6335 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6336 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6337 t)
6338 "$")
6339 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6340 Shown at or above `js2-highlight-level' 3.")
6341
6342 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6343 (let ((target-name (and target
6344 (js2-name-node-p target)
6345 (js2-name-node-name target)))
6346 (prop-name (if prop (js2-name-node-name prop)))
6347 (level1 (>= js2-highlight-level 1))
6348 (level2 (>= js2-highlight-level 2))
6349 (level3 (>= js2-highlight-level 3))
6350 pos
6351 face)
6352 (when level2
6353 (if call-p
6354 (cond
6355 ((and target prop)
6356 (cond
6357 ((and level3 (string-match js2-ecma-function-props prop-name))
6358 (setq face 'font-lock-builtin-face))
6359 ((and target-name prop)
6360 (cond
6361 ((string= target-name "Date")
6362 (if (string-match js2-ecma-date-props prop-name)
6363 (setq face 'font-lock-builtin-face)))
6364 ((string= target-name "Math")
6365 (if (string-match js2-ecma-math-funcs prop-name)
6366 (setq face 'font-lock-builtin-face)))))))
6367 (prop
6368 (if (string-match js2-ecma-global-funcs prop-name)
6369 (setq face 'font-lock-builtin-face))))
6370 (cond
6371 ((and target prop)
6372 (cond
6373 ((string= target-name "Number")
6374 (if (string-match js2-ecma-number-props prop-name)
6375 (setq face 'font-lock-constant-face)))
6376 ((string= target-name "Math")
6377 (if (string-match js2-ecma-math-props prop-name)
6378 (setq face 'font-lock-constant-face)))))
6379 (prop
6380 (if (string-match js2-ecma-object-props prop-name)
6381 (setq face 'font-lock-constant-face)))))
6382 (when face
6383 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6384 (js2-node-pos prop))) ; relative
6385 (+ pos (js2-node-len prop))
6386 face)))))
6387
6388 (defun js2-parse-highlight-member-expr-node (node)
6389 "Perform syntax highlighting of EcmaScript built-in properties.
6390 The variable `js2-highlight-level' governs this highighting."
6391 (let (face target prop name pos end parent call-p callee)
6392 (cond
6393 ;; case 1: simple name, e.g. foo
6394 ((js2-name-node-p node)
6395 (setq name (js2-name-node-name node))
6396 ;; possible for name to be nil in rare cases - saw it when
6397 ;; running js2-mode on an elisp buffer. Might as well try to
6398 ;; make it so js2-mode never barfs.
6399 (when name
6400 (setq face (if (string-match js2-ecma-global-props name)
6401 'font-lock-constant-face))
6402 (when face
6403 (setq pos (js2-node-pos node)
6404 end (+ pos (js2-node-len node)))
6405 (js2-set-face pos end face))))
6406 ;; case 2: property access or function call
6407 ((or (js2-prop-get-node-p node)
6408 ;; highlight function call if expr is a prop-get node
6409 ;; or a plain name (i.e. unqualified function call)
6410 (and (setq call-p (js2-call-node-p node))
6411 (setq callee (js2-call-node-target node)) ; separate setq!
6412 (or (js2-prop-get-node-p callee)
6413 (js2-name-node-p callee))))
6414 (setq parent node
6415 node (if call-p callee node))
6416 (if (and call-p (js2-name-node-p callee))
6417 (setq prop callee)
6418 (setq target (js2-prop-get-node-left node)
6419 prop (js2-prop-get-node-right node)))
6420 (cond
6421 ((js2-name-node-p target)
6422 (if (js2-name-node-p prop)
6423 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6424 (js2-parse-highlight-prop-get parent target prop call-p)
6425 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6426 (js2-parse-highlight-prop-get parent target nil call-p)))
6427 ((js2-name-node-p prop)
6428 ;; case 2c: complex target, simple name, e.g. x[y].bar
6429 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6430
6431 (defun js2-parse-highlight-member-expr-fn-name (expr)
6432 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6433 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6434 We currently only handle the case where the last component is a prop-get
6435 of a simple name. Called before EXPR has a parent node."
6436 (let (pos
6437 (name (and (js2-prop-get-node-p expr)
6438 (js2-prop-get-node-right expr))))
6439 (when (js2-name-node-p name)
6440 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6441 (js2-node-pos name)))
6442 (+ pos (js2-node-len name))
6443 'font-lock-function-name-face
6444 'record))))
6445
6446 ;; source: http://jsdoc.sourceforge.net/
6447 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6448 ;; allows type specifications, and needs work before entering the wild.
6449
6450 (defconst js2-jsdoc-param-tag-regexp
6451 (concat "^\\s-*\\*+\\s-*\\(@"
6452 "\\(?:param\\|argument\\)"
6453 "\\)"
6454 "\\s-*\\({[^}]+}\\)?" ; optional type
6455 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6456 "\\>")
6457 "Matches jsdoc tags with optional type and optional param name.")
6458
6459 (defconst js2-jsdoc-typed-tag-regexp
6460 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6461 (regexp-opt
6462 '("enum"
6463 "extends"
6464 "field"
6465 "id"
6466 "implements"
6467 "lends"
6468 "mods"
6469 "requires"
6470 "return"
6471 "returns"
6472 "throw"
6473 "throws"))
6474 "\\)\\)\\s-*\\({[^}]+}\\)?")
6475 "Matches jsdoc tags with optional type.")
6476
6477 (defconst js2-jsdoc-arg-tag-regexp
6478 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6479 (regexp-opt
6480 '("alias"
6481 "augments"
6482 "borrows"
6483 "bug"
6484 "base"
6485 "config"
6486 "default"
6487 "define"
6488 "exception"
6489 "function"
6490 "member"
6491 "memberOf"
6492 "name"
6493 "namespace"
6494 "property"
6495 "since"
6496 "suppress"
6497 "this"
6498 "throws"
6499 "type"
6500 "version"))
6501 "\\)\\)\\s-+\\([^ \t]+\\)")
6502 "Matches jsdoc tags with a single argument.")
6503
6504 (defconst js2-jsdoc-empty-tag-regexp
6505 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6506 (regexp-opt
6507 '("addon"
6508 "author"
6509 "class"
6510 "const"
6511 "constant"
6512 "constructor"
6513 "constructs"
6514 "deprecated"
6515 "desc"
6516 "description"
6517 "event"
6518 "example"
6519 "exec"
6520 "export"
6521 "fileoverview"
6522 "final"
6523 "function"
6524 "hidden"
6525 "ignore"
6526 "implicitCast"
6527 "inheritDoc"
6528 "inner"
6529 "interface"
6530 "license"
6531 "noalias"
6532 "noshadow"
6533 "notypecheck"
6534 "override"
6535 "owner"
6536 "preserve"
6537 "preserveTry"
6538 "private"
6539 "protected"
6540 "public"
6541 "static"
6542 "supported"
6543 ))
6544 "\\)\\)\\s-*")
6545 "Matches empty jsdoc tags.")
6546
6547 (defconst js2-jsdoc-link-tag-regexp
6548 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6549 "Matches a jsdoc link or code tag.")
6550
6551 (defconst js2-jsdoc-see-tag-regexp
6552 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6553 "Matches a jsdoc @see tag.")
6554
6555 (defconst js2-jsdoc-html-tag-regexp
6556 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6557 "Matches a simple (no attributes) html start- or end-tag.")
6558
6559 (defsubst js2-jsdoc-highlight-helper ()
6560 (js2-set-face (match-beginning 1)
6561 (match-end 1)
6562 'js2-jsdoc-tag-face)
6563 (if (match-beginning 2)
6564 (if (save-excursion
6565 (goto-char (match-beginning 2))
6566 (= (char-after) ?{))
6567 (js2-set-face (1+ (match-beginning 2))
6568 (1- (match-end 2))
6569 'js2-jsdoc-type-face)
6570 (js2-set-face (match-beginning 2)
6571 (match-end 2)
6572 'js2-jsdoc-value-face)))
6573 (if (match-beginning 3)
6574 (js2-set-face (match-beginning 3)
6575 (match-end 3)
6576 'js2-jsdoc-value-face)))
6577
6578 (defun js2-highlight-jsdoc (ast)
6579 "Highlight doc comment tags."
6580 (let ((comments (js2-ast-root-comments ast))
6581 beg end)
6582 (save-excursion
6583 (dolist (node comments)
6584 (when (eq (js2-comment-node-format node) 'jsdoc)
6585 (setq beg (js2-node-abs-pos node)
6586 end (+ beg (js2-node-len node)))
6587 (save-restriction
6588 (narrow-to-region beg end)
6589 (dolist (re (list js2-jsdoc-param-tag-regexp
6590 js2-jsdoc-typed-tag-regexp
6591 js2-jsdoc-arg-tag-regexp
6592 js2-jsdoc-link-tag-regexp
6593 js2-jsdoc-see-tag-regexp
6594 js2-jsdoc-empty-tag-regexp))
6595 (goto-char beg)
6596 (while (re-search-forward re nil t)
6597 (js2-jsdoc-highlight-helper)))
6598 ;; simple highlighting for html tags
6599 (goto-char beg)
6600 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6601 (js2-set-face (match-beginning 1)
6602 (match-end 1)
6603 'js2-jsdoc-html-tag-delimiter-face)
6604 (js2-set-face (match-beginning 2)
6605 (match-end 2)
6606 'js2-jsdoc-html-tag-name-face)
6607 (js2-set-face (match-beginning 3)
6608 (match-end 3)
6609 'js2-jsdoc-html-tag-delimiter-face))))))))
6610
6611 (defun js2-highlight-assign-targets (node left right)
6612 "Highlight function properties and external variables."
6613 (let (leftpos end name)
6614 ;; highlight vars and props assigned function values
6615 (when (js2-function-node-p right)
6616 (cond
6617 ;; var foo = function() {...}
6618 ((js2-name-node-p left)
6619 (setq name left))
6620 ;; foo.bar.baz = function() {...}
6621 ((and (js2-prop-get-node-p left)
6622 (js2-name-node-p (js2-prop-get-node-right left)))
6623 (setq name (js2-prop-get-node-right left))))
6624 (when name
6625 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6626 (+ leftpos (js2-node-len name))
6627 'font-lock-function-name-face
6628 'record)))))
6629
6630 (defun js2-record-name-node (node)
6631 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6632 later. NODE must be a name node."
6633 (let (leftpos end)
6634 (push (list node js2-current-scope
6635 (setq leftpos (js2-node-abs-pos node))
6636 (setq end (+ leftpos (js2-node-len node))))
6637 js2-recorded-identifiers)))
6638
6639 (defun js2-highlight-undeclared-vars ()
6640 "After entire parse is finished, look for undeclared variable references.
6641 We have to wait until entire buffer is parsed, since JavaScript permits var
6642 decls to occur after they're used.
6643
6644 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6645 it is considered declared."
6646 (let (name)
6647 (dolist (entry js2-recorded-identifiers)
6648 (destructuring-bind (name-node scope pos end) entry
6649 (setq name (js2-name-node-name name-node))
6650 (unless (or (member name js2-global-externs)
6651 (member name js2-default-externs)
6652 (member name js2-additional-externs)
6653 (js2-get-defining-scope scope name))
6654 (js2-set-face pos end 'js2-external-variable-face 'record)
6655 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6656 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6657 (setq js2-recorded-identifiers nil)))
6658
6659 ;;; IMenu support
6660
6661 ;; We currently only support imenu, but eventually should support speedbar and
6662 ;; possibly other browsing mechanisms.
6663
6664 ;; The basic strategy is to identify function assignment targets of the form
6665 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6666 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6667 ;; for imenu after parsing is finished.
6668
6669 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6670 ;; JavaScript, and the general problem is undecidable. However, several forms
6671 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6672 ;; include:
6673
6674 ;; function foo() -- function declaration
6675 ;; foo = function() -- function expression assigned to variable
6676 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6677 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6678 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6679 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6680 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6681 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6682 ;; function foo() {function bar() {...}} -- nested function
6683 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6684
6685 ;; This list boils down to a few forms that can be combined recursively.
6686 ;; Top-level named function declarations include both the left-hand (name)
6687 ;; and the right-hand (function value) expressions needed to produce an imenu
6688 ;; entry. The other "right-hand" forms we need to look for are:
6689 ;; - functions declared as props/getters/setters in object literals
6690 ;; - nested named function declarations
6691 ;; The "left-hand" expressions that functions can be assigned to include:
6692 ;; - local/global variables
6693 ;; - nested property-get expressions like a.b.c.d
6694 ;; - element gets like foo[10] or foo['bar'] where the index
6695 ;; expression can be trivially converted to a property name. They
6696 ;; effectively then become property gets.
6697
6698 ;; All the different definition types are canonicalized into the form
6699 ;; foo.bar.baz = position-of-function-keyword
6700
6701 ;; We need to build a trie-like structure for imenu. As an example,
6702 ;; consider the following JavaScript code:
6703
6704 ;; a = function() {...} // function at position 5
6705 ;; b = function() {...} // function at position 25
6706 ;; foo = function() {...} // function at position 100
6707 ;; foo.bar = function() {...} // function at position 200
6708 ;; foo.bar.baz = function() {...} // function at position 300
6709 ;; foo.bar.zab = function() {...} // function at position 400
6710
6711 ;; During parsing we accumulate an entry for each definition in
6712 ;; the variable `js2-imenu-recorder', like so:
6713
6714 ;; '((a 5)
6715 ;; (b 25)
6716 ;; (foo 100)
6717 ;; (foo bar 200)
6718 ;; (foo bar baz 300)
6719 ;; (foo bar zab 400))
6720
6721 ;; After parsing these entries are merged into this alist-trie:
6722
6723 ;; '((a . 1)
6724 ;; (b . 2)
6725 ;; (foo (<definition> . 3)
6726 ;; (bar (<definition> . 6)
6727 ;; (baz . 100)
6728 ;; (zab . 200))))
6729
6730 ;; Note the wacky need for a <definition> name. The token can be anything
6731 ;; that isn't a valid JavaScript identifier, because you might make foo
6732 ;; a function and then start setting properties on it that are also functions.
6733
6734 (defsubst js2-prop-node-name (node)
6735 "Return the name of a node that may be a property-get/property-name.
6736 If NODE is not a valid name-node, string-node or integral number-node,
6737 returns nil. Otherwise returns the string name/value of the node."
6738 (cond
6739 ((js2-name-node-p node)
6740 (js2-name-node-name node))
6741 ((js2-string-node-p node)
6742 (js2-string-node-value node))
6743 ((and (js2-number-node-p node)
6744 (string-match "^[0-9]+$" (js2-number-node-value node)))
6745 (js2-number-node-value node))
6746 ((js2-this-node-p node)
6747 "this")))
6748
6749 (defsubst js2-node-qname-component (node)
6750 "Test function: return the name of this node, if it contributes to a qname.
6751 Returns nil if the node doesn't contribute."
6752 (copy-sequence
6753 (or (js2-prop-node-name node)
6754 (if (and (js2-function-node-p node)
6755 (js2-function-node-name node))
6756 (js2-name-node-name (js2-function-node-name node))))))
6757
6758 (defsubst js2-record-function-qname (fn-node qname)
6759 "Associate FN-NODE with its QNAME for later lookup.
6760 This is used in postprocessing the chain list. When we find a chain
6761 whose first element is a js2-THIS keyword node, we look up the parent
6762 function and see (using this map) whether it is the tail of a chain.
6763 If so, we replace the this-node with a copy of the parent's qname."
6764 (unless js2-imenu-function-map
6765 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6766 (puthash fn-node qname js2-imenu-function-map))
6767
6768 (defun js2-record-imenu-functions (node &optional var)
6769 "Record function definitions for imenu.
6770 NODE is a function node or an object literal.
6771 VAR, if non-nil, is the expression that NODE is being assigned to."
6772 (when js2-parse-ide-mode
6773 (let ((fun-p (js2-function-node-p node))
6774 qname left fname-node pos)
6775 (cond
6776 ;; non-anonymous function declaration?
6777 ((and fun-p
6778 (not var)
6779 (setq fname-node (js2-function-node-name node)))
6780 (push (setq qname (list fname-node (js2-node-pos node)))
6781 js2-imenu-recorder)
6782 (js2-record-function-qname node qname))
6783 ;; for remaining forms, compute left-side tree branch first
6784 ((and var (setq qname (js2-compute-nested-prop-get var)))
6785 (cond
6786 ;; foo.bar.baz = function
6787 (fun-p
6788 (push (nconc qname (list (js2-node-pos node)))
6789 js2-imenu-recorder)
6790 (js2-record-function-qname node qname))
6791 ;; foo.bar.baz = object-literal
6792 ;; look for nested functions: {a: {b: function() {...} }}
6793 ((js2-object-node-p node)
6794 ;; Node position here is still absolute, since the parser
6795 ;; passes the assignment target and value expressions
6796 ;; to us before they are added as children of the assignment node.
6797 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6798
6799 (defun js2-compute-nested-prop-get (node)
6800 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6801 component nodes as a list. Otherwise return nil. Element-gets are treated
6802 as property-gets if the index expression is a string, or a positive integer."
6803 (let (left right head)
6804 (cond
6805 ((or (js2-name-node-p node)
6806 (js2-this-node-p node))
6807 (list node))
6808 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6809 ((js2-prop-get-node-p node) ; foo.bar
6810 (setq left (js2-prop-get-node-left node)
6811 right (js2-prop-get-node-right node))
6812 (if (setq head (js2-compute-nested-prop-get left))
6813 (nconc head (list right))))
6814 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6815 (setq left (js2-elem-get-node-target node)
6816 right (js2-elem-get-node-element node))
6817 (if (or (js2-string-node-p right) ; ['bar']
6818 (and (js2-number-node-p right) ; [10]
6819 (string-match "^[0-9]+$"
6820 (js2-number-node-value right))))
6821 (if (setq head (js2-compute-nested-prop-get left))
6822 (nconc head (list right))))))))
6823
6824 (defun js2-record-object-literal (node qname pos)
6825 "Recursively process an object literal looking for functions.
6826 NODE is an object literal that is the right-hand child of an assignment
6827 expression. QNAME is a list of nodes representing the assignment target,
6828 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6829 POS is the absolute position of the node.
6830 We do a depth-first traversal of NODE. Any functions we find are prefixed
6831 with QNAME plus the property name of the function and appended to the
6832 variable `js2-imenu-recorder'."
6833 (let (left right)
6834 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6835 (let ((left (js2-infix-node-left e))
6836 ;; Element positions are relative to the parent position.
6837 (pos (+ pos (js2-node-pos e))))
6838 (cond
6839 ;; foo: function() {...}
6840 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6841 (when (js2-prop-node-name left)
6842 ;; As a policy decision, we record the position of the property,
6843 ;; not the position of the `function' keyword, since the property
6844 ;; is effectively the name of the function.
6845 (push (append qname (list left pos))
6846 js2-imenu-recorder)
6847 (js2-record-function-qname right qname)))
6848 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6849 ((js2-object-node-p right)
6850 (js2-record-object-literal right
6851 (append qname (list (js2-infix-node-left e)))
6852 (+ pos (js2-node-pos right)))))))))
6853
6854 (defsubst js2-node-top-level-decl-p (node)
6855 "Return t if NODE's name is defined in the top-level scope.
6856 Also returns t if NODE's name is not defined in any scope, since it implies
6857 that it's an external variable, which must also be in the top-level scope."
6858 (let* ((name (js2-prop-node-name node))
6859 (this-scope (js2-node-get-enclosing-scope node))
6860 defining-scope)
6861 (cond
6862 ((js2-this-node-p node)
6863 nil)
6864 ((null this-scope)
6865 t)
6866 ((setq defining-scope (js2-get-defining-scope this-scope name))
6867 (js2-ast-root-p defining-scope))
6868 (t t))))
6869
6870 (defun js2-browse-postprocess-chains (chains)
6871 "Modify function-declaration name chains after parsing finishes.
6872 Some of the information is only available after the parse tree is complete.
6873 For instance, following a 'this' reference requires a parent function node."
6874 (let (result head fn parent-chain p elem parent)
6875 (dolist (chain chains)
6876 ;; examine the head of each node to get its defining scope
6877 (setq head (car chain))
6878 ;; if top-level/external, keep as-is
6879 (if (js2-node-top-level-decl-p head)
6880 (push chain result)
6881 (cond
6882 ;; starts with this-reference
6883 ((js2-this-node-p head)
6884 (setq fn (js2-node-parent-script-or-fn head)
6885 chain (cdr chain))) ; discard this-node
6886 ;; nested named function
6887 ((js2-function-node-p (setq parent (js2-node-parent head)))
6888 (setq fn (js2-node-parent-script-or-fn parent)))
6889 ;; variable assigned a function expression
6890 (t (setq fn (js2-node-parent-script-or-fn head))))
6891 (unless (or (null fn) (js2-nested-function-p fn))
6892 ;; if the parent function is found, and it's not nested,
6893 ;; look it up in function-map.
6894 (if (setq parent-chain (and js2-imenu-function-map
6895 (gethash fn js2-imenu-function-map)))
6896 ;; prefix parent fn qname, which is the
6897 ;; parent-chain sans tail, to this chain.
6898 (push (append (butlast parent-chain) chain) result)
6899 ;; parent function is not nested, and not in function-map
6900 ;; => it's anonymous top-level wrapper, discard.
6901 (push chain result)))))
6902 ;; finally replace each node in each chain with its name.
6903 (dolist (chain result)
6904 (setq p chain)
6905 (while p
6906 (if (js2-node-p (setq elem (car p)))
6907 (setcar p (js2-node-qname-component elem)))
6908 (setq p (cdr p))))
6909 result))
6910
6911 ;; Merge name chains into a trie-like tree structure of nested lists.
6912 ;; To simplify construction of the trie, we first build it out using the rule
6913 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6914 ;; [key, num-or-list]. The second element can be a number; if so, this key
6915 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6916 ;; associated with the key at this level.) Otherwise the second element is
6917 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6918 ;; a simple recursive formulation.
6919 ;;
6920 ;; js2-mode is building the data structure for imenu. The imenu documentation
6921 ;; claims that it's the structure above, but in practice it wants the children
6922 ;; at the same list level as the key for that level, which is how I've drawn
6923 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6924 ;; list wrapper around the children at each level.
6925 ;;
6926 ;; A completed nested imenu-alist entry looks like this:
6927 ;; '(("foo"
6928 ;; ("<definition>" . 7)
6929 ;; ("bar"
6930 ;; ("a" . 40)
6931 ;; ("b" . 60))))
6932 ;;
6933 ;; In particular, the documentation for `imenu--index-alist' says that
6934 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6935 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6936
6937 (defsubst js2-treeify (lst)
6938 "Convert (a b c d) to (a ((b ((c d)))))"
6939 (if (null (cddr lst)) ; list length <= 2
6940 lst
6941 (list (car lst) (list (js2-treeify (cdr lst))))))
6942
6943 (defun js2-build-alist-trie (chains trie)
6944 "Merge declaration name chains into a trie-like alist structure for imenu.
6945 CHAINS is the qname chain list produced during parsing. TRIE is a
6946 list of elements built up so far."
6947 (let (head tail pos branch kids)
6948 (dolist (chain chains)
6949 (setq head (car chain)
6950 tail (cdr chain)
6951 pos (if (numberp (car tail)) (car tail))
6952 branch (js2-find-if (lambda (n)
6953 (string= (car n) head))
6954 trie)
6955 kids (second branch))
6956 (cond
6957 ;; case 1: this key isn't in the trie yet
6958 ((null branch)
6959 (if trie
6960 (setcdr (last trie) (list (js2-treeify chain)))
6961 (setq trie (list (js2-treeify chain)))))
6962 ;; case 2: key is present with a single number entry: replace w/ list
6963 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6964 ;; ("<definition>" 20)))
6965 ((numberp kids)
6966 (setcar (cdr branch)
6967 (list (list "<definition-1>" kids)
6968 (if pos
6969 (list "<definition-2>" pos)
6970 (js2-treeify tail)))))
6971 ;; case 3: key is there (with kids), and we're a number entry
6972 (pos
6973 (setcdr (last kids)
6974 (list
6975 (list (format "<definition-%d>"
6976 (1+ (loop for kid in kids
6977 count (eq ?< (aref (car kid) 0)))))
6978 pos))))
6979 ;; case 4: key is there with kids, need to merge in our chain
6980 (t
6981 (js2-build-alist-trie (list tail) kids))))
6982 trie))
6983
6984 (defun js2-flatten-trie (trie)
6985 "Convert TRIE to imenu-format.
6986 Recurses through nodes, and for each one whose second element is a list,
6987 appends the list's flattened elements to the current element. Also
6988 changes the tails into conses. For instance, this pre-flattened trie
6989
6990 '(a ((b 20)
6991 (c ((d 30)
6992 (e 40)))))
6993
6994 becomes
6995
6996 '(a (b . 20)
6997 (c (d . 30)
6998 (e . 40)))
6999
7000 Note that the root of the trie has no key, just a list of chains.
7001 This is also true for the value of any key with multiple children,
7002 e.g. key 'c' in the example above."
7003 (cond
7004 ((listp (car trie))
7005 (mapcar #'js2-flatten-trie trie))
7006 (t
7007 (if (numberp (second trie))
7008 (cons (car trie) (second trie))
7009 ;; else pop list and append its kids
7010 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7011
7012 (defun js2-build-imenu-index ()
7013 "Turn `js2-imenu-recorder' into an imenu data structure."
7014 (unless (eq js2-imenu-recorder 'empty)
7015 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7016 (result (js2-build-alist-trie chains nil)))
7017 (js2-flatten-trie result))))
7018
7019 (defun js2-test-print-chains (chains)
7020 "Print a list of qname chains.
7021 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7022 i.e. one or more nodes, and an integer position as the list tail."
7023 (mapconcat (lambda (chain)
7024 (concat "("
7025 (mapconcat (lambda (elem)
7026 (if (js2-node-p elem)
7027 (or (js2-node-qname-component elem)
7028 "nil")
7029 (number-to-string elem)))
7030 chain
7031 " ")
7032 ")"))
7033 chains
7034 "\n"))
7035
7036 ;;; Parser
7037
7038 (defconst js2-version "1.8.0"
7039 "Version of JavaScript supported, plus minor js2 version.")
7040
7041 (defmacro js2-record-face (face)
7042 "Record a style run of FACE for the current token."
7043 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7044
7045 (defsubst js2-node-end (n)
7046 "Computes the absolute end of node N.
7047 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7048 is only true until the node is added to its parent; i.e., while parsing."
7049 (+ (js2-node-pos n)
7050 (js2-node-len n)))
7051
7052 (defsubst js2-record-comment ()
7053 "Record a comment in `js2-scanned-comments'."
7054 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7055 :format js2-ts-comment-type)
7056 js2-scanned-comments)
7057 (when js2-parse-ide-mode
7058 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7059 'font-lock-doc-face
7060 'font-lock-comment-face))
7061 (when (memq js2-ts-comment-type '(html preprocessor))
7062 ;; Tell cc-engine the bounds of the comment.
7063 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7064
7065 ;; This function is called depressingly often, so it should be fast.
7066 ;; Most of the time it's looking at the same token it peeked before.
7067 (defsubst js2-peek-token ()
7068 "Returns the next token without consuming it.
7069 If previous token was consumed, calls scanner to get new token.
7070 If previous token was -not- consumed, returns it (idempotent).
7071
7072 This function will not return a newline (js2-EOL) - instead, it
7073 gobbles newlines until it finds a non-newline token, and flags
7074 that token as appearing just after a newline.
7075
7076 This function will also not return a js2-COMMENT. Instead, it
7077 records comments found in `js2-scanned-comments'. If the token
7078 returned by this function immediately follows a jsdoc comment,
7079 the token is flagged as such.
7080
7081 Note that this function always returned the un-flagged token!
7082 The flags, if any, are saved in `js2-current-flagged-token'."
7083 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7084 js2-current-token ; most common case - return already-peeked token
7085 (let ((tt (js2-get-token)) ; call scanner
7086 saw-eol
7087 face)
7088 ;; process comments and whitespace
7089 (while (or (= tt js2-EOL)
7090 (= tt js2-COMMENT))
7091 (if (= tt js2-EOL)
7092 (setq saw-eol t)
7093 (setq saw-eol nil)
7094 (if js2-record-comments
7095 (js2-record-comment)))
7096 (setq tt (js2-get-token))) ; call scanner
7097 (setq js2-current-token tt
7098 js2-current-flagged-token (if saw-eol
7099 (logior tt js2-ti-after-eol)
7100 tt))
7101 ;; perform lexical fontification as soon as token is scanned
7102 (when js2-parse-ide-mode
7103 (cond
7104 ((minusp tt)
7105 (js2-record-face 'js2-error-face))
7106 ((setq face (aref js2-kwd-tokens tt))
7107 (js2-record-face face))
7108 ((and (= tt js2-NAME)
7109 (equal js2-ts-string "undefined"))
7110 (js2-record-face 'font-lock-constant-face))))
7111 tt))) ; return unflagged token
7112
7113 (defsubst js2-peek-flagged-token ()
7114 "Returns the current token along with any flags set for it."
7115 (js2-peek-token)
7116 js2-current-flagged-token)
7117
7118 (defsubst js2-consume-token ()
7119 (setq js2-current-flagged-token js2-EOF))
7120
7121 (defsubst js2-next-token ()
7122 (prog1
7123 (js2-peek-token)
7124 (js2-consume-token)))
7125
7126 (defsubst js2-next-flagged-token ()
7127 (js2-peek-token)
7128 (prog1 js2-current-flagged-token
7129 (js2-consume-token)))
7130
7131 (defsubst js2-match-token (match)
7132 "Consume and return t if next token matches MATCH, a bytecode.
7133 Returns nil and consumes nothing if MATCH is not the next token."
7134 (if (/= (js2-peek-token) match)
7135 nil
7136 (js2-consume-token)
7137 t))
7138
7139 (defsubst js2-valid-prop-name-token (tt)
7140 (or (= tt js2-NAME)
7141 (and js2-allow-keywords-as-property-names
7142 (plusp tt)
7143 (aref js2-kwd-tokens tt))))
7144
7145 (defsubst js2-match-prop-name ()
7146 "Consume token and return t if next token is a valid property name.
7147 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7148 is non-nil and it's a keyword token."
7149 (if (js2-valid-prop-name-token (js2-peek-token))
7150 (progn
7151 (js2-consume-token)
7152 t)
7153 nil))
7154
7155 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7156 (if (js2-match-prop-name)
7157 t
7158 (js2-report-error msg-id nil pos len)
7159 nil))
7160
7161 (defsubst js2-peek-token-or-eol ()
7162 "Return js2-EOL if the current token immediately follows a newline.
7163 Else returns the current token. Used in situations where we don't
7164 consider certain token types valid if they are preceded by a newline.
7165 One example is the postfix ++ or -- operator, which has to be on the
7166 same line as its operand."
7167 (let ((tt (js2-peek-token)))
7168 ;; Check for last peeked token flags
7169 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7170 js2-EOL
7171 tt)))
7172
7173 (defsubst js2-set-check-for-label ()
7174 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7175 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7176
7177 (defsubst js2-must-match (token msg-id &optional pos len)
7178 "Match next token to token code TOKEN, or record a syntax error.
7179 MSG-ID is the error message to report if the match fails.
7180 Returns t on match, nil if no match."
7181 (if (js2-match-token token)
7182 t
7183 (js2-report-error msg-id nil pos len)
7184 nil))
7185
7186 (defsubst js2-inside-function ()
7187 (plusp js2-nesting-of-function))
7188
7189 (defsubst js2-set-requires-activation ()
7190 (if (js2-function-node-p js2-current-script-or-fn)
7191 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7192
7193 (defsubst js2-check-activation-name (name token)
7194 (when (js2-inside-function)
7195 ;; skip language-version 1.2 check from Rhino
7196 (if (or (string= "arguments" name)
7197 (and js2-compiler-activation-names ; only used in codegen
7198 (gethash name js2-compiler-activation-names)))
7199 (js2-set-requires-activation))))
7200
7201 (defsubst js2-set-is-generator ()
7202 (if (js2-function-node-p js2-current-script-or-fn)
7203 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7204
7205 (defsubst js2-must-have-xml ()
7206 (unless js2-compiler-xml-available
7207 (js2-report-error "msg.XML.not.available")))
7208
7209 (defsubst js2-push-scope (scope)
7210 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7211 (assert (js2-scope-p scope))
7212 (assert (null (js2-scope-parent-scope scope)))
7213 (assert (not (eq js2-current-scope scope)))
7214 (setf (js2-scope-parent-scope scope) js2-current-scope
7215 js2-current-scope scope))
7216
7217 (defsubst js2-pop-scope ()
7218 (setq js2-current-scope
7219 (js2-scope-parent-scope js2-current-scope)))
7220
7221 (defsubst js2-enter-loop (loop-node)
7222 (push loop-node js2-loop-set)
7223 (push loop-node js2-loop-and-switch-set)
7224 (js2-push-scope loop-node)
7225 ;; Tell the current labeled statement (if any) its statement,
7226 ;; and set the jump target of the first label to the loop.
7227 ;; These are used in `js2-parse-continue' to verify that the
7228 ;; continue target is an actual labeled loop. (And for codegen.)
7229 (when js2-labeled-stmt
7230 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7231 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7232 js2-labeled-stmt))) loop-node)))
7233
7234 (defsubst js2-exit-loop ()
7235 (pop js2-loop-set)
7236 (pop js2-loop-and-switch-set)
7237 (js2-pop-scope))
7238
7239 (defsubst js2-enter-switch (switch-node)
7240 (push switch-node js2-loop-and-switch-set))
7241
7242 (defsubst js2-exit-switch ()
7243 (pop js2-loop-and-switch-set))
7244
7245 (defun js2-parse (&optional buf cb)
7246 "Tells the js2 parser to parse a region of JavaScript.
7247
7248 BUF is a buffer or buffer name containing the code to parse.
7249 Call `narrow-to-region' first to parse only part of the buffer.
7250
7251 The returned AST root node is given some additional properties:
7252 `node-count' - total number of nodes in the AST
7253 `buffer' - BUF. The buffer it refers to may change or be killed,
7254 so the value is not necessarily reliable.
7255
7256 An optional callback CB can be specified to report parsing
7257 progress. If `(functionp CB)' returns t, it will be called with
7258 the current line number once before parsing begins, then again
7259 each time the lexer reaches a new line number.
7260
7261 CB can also be a list of the form `(symbol cb ...)' to specify
7262 multiple callbacks with different criteria. Each symbol is a
7263 criterion keyword, and the following element is the callback to
7264 call
7265
7266 :line - called whenever the line number changes
7267 :token - called for each new token consumed
7268
7269 The list of criteria could be extended to include entering or
7270 leaving a statement, an expression, or a function definition."
7271 (if (and cb (not (functionp cb)))
7272 (error "criteria callbacks not yet implemented"))
7273 (let ((inhibit-point-motion-hooks t)
7274 (js2-compiler-xml-available (>= js2-language-version 160))
7275 ;; This is a recursive-descent parser, so give it a big stack.
7276 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7277 (max-specpdl-size (max max-specpdl-size 3000))
7278 (case-fold-search nil)
7279 ast)
7280 (or buf (setq buf (current-buffer)))
7281 (message nil) ; clear any error message from previous parse
7282 (save-excursion
7283 (set-buffer buf)
7284 (setq js2-scanned-comments nil
7285 js2-parsed-errors nil
7286 js2-parsed-warnings nil
7287 js2-imenu-recorder nil
7288 js2-imenu-function-map nil
7289 js2-label-set nil)
7290 (js2-init-scanner)
7291 (setq ast (js2-with-unmodifying-text-property-changes
7292 (js2-do-parse)))
7293 (unless js2-ts-hit-eof
7294 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7295 (setf (js2-ast-root-errors ast) js2-parsed-errors
7296 (js2-ast-root-warnings ast) js2-parsed-warnings)
7297 ;; if we didn't find any declarations, put a dummy in this list so we
7298 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7299 (unless js2-imenu-recorder
7300 (setq js2-imenu-recorder 'empty))
7301 (run-hooks 'js2-parse-finished-hook)
7302 ast)))
7303
7304 ;; Corresponds to Rhino's Parser.parse() method.
7305 (defun js2-do-parse ()
7306 "Parse current buffer starting from current point.
7307 Scanner should be initialized."
7308 (let ((pos js2-ts-cursor)
7309 (end js2-ts-cursor) ; in case file is empty
7310 root n tt)
7311 ;; initialize buffer-local parsing vars
7312 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7313 js2-current-script-or-fn root
7314 js2-current-scope root
7315 js2-current-flagged-token js2-EOF
7316 js2-nesting-of-function 0
7317 js2-labeled-stmt nil
7318 js2-recorded-identifiers nil) ; for js2-highlight
7319 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7320 (if (= tt js2-FUNCTION)
7321 (progn
7322 (js2-consume-token)
7323 (setq n (js2-parse-function (if js2-called-by-compile-function
7324 'FUNCTION_EXPRESSION
7325 'FUNCTION_STATEMENT))))
7326 ;; not a function - parse a statement
7327 (setq n (js2-parse-statement)))
7328 ;; add function or statement to script
7329 (setq end (js2-node-end n))
7330 (js2-block-node-push root n))
7331 ;; add comments to root in lexical order
7332 (when js2-scanned-comments
7333 ;; if we find a comment beyond end of normal kids, use its end
7334 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7335 (dolist (comment js2-scanned-comments)
7336 (push comment (js2-ast-root-comments root))
7337 (js2-node-add-children root comment)))
7338 (setf (js2-node-len root) (- end pos))
7339 ;; Give extensions a chance to muck with things before highlighting starts.
7340 (dolist (callback js2-post-parse-callbacks)
7341 (funcall callback))
7342 (js2-highlight-undeclared-vars)
7343 root))
7344
7345 (defun js2-function-parser ()
7346 (js2-consume-token)
7347 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7348
7349 (defun js2-parse-function-closure-body (fn-node)
7350 "Parse a JavaScript 1.8 function closure body."
7351 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7352 (if js2-ts-hit-eof
7353 (js2-report-error "msg.no.brace.body" nil
7354 (js2-node-pos fn-node)
7355 (- js2-ts-cursor (js2-node-pos fn-node)))
7356 (js2-node-add-children fn-node
7357 (setf (js2-function-node-body fn-node)
7358 (js2-parse-expr t))))))
7359
7360 (defun js2-parse-function-body (fn-node)
7361 (js2-must-match js2-LC "msg.no.brace.body"
7362 (js2-node-pos fn-node)
7363 (- js2-ts-cursor (js2-node-pos fn-node)))
7364 (let ((pos js2-token-beg) ; LC position
7365 (pn (make-js2-block-node)) ; starts at LC position
7366 tt
7367 end)
7368 (incf js2-nesting-of-function)
7369 (unwind-protect
7370 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7371 (= tt js2-EOF)
7372 (= tt js2-RC)))
7373 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7374 (js2-parse-statement)
7375 (js2-consume-token)
7376 (js2-parse-function 'FUNCTION_STATEMENT))))
7377 (decf js2-nesting-of-function))
7378 (setq end js2-token-end) ; assume no curly and leave at current token
7379 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7380 (setq end js2-token-end))
7381 (setf (js2-node-pos pn) pos
7382 (js2-node-len pn) (- end pos))
7383 (setf (js2-function-node-body fn-node) pn)
7384 (js2-node-add-children fn-node pn)
7385 pn))
7386
7387 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7388 "Declare and fontify destructuring parameters inside NODE.
7389 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7390 (cond
7391 ((js2-name-node-p node)
7392 (let (leftpos)
7393 (js2-define-symbol decl-type (js2-name-node-name node)
7394 node ignore-not-in-block)
7395 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7396 (+ leftpos (js2-node-len node))
7397 face 'record)))
7398 ((js2-object-node-p node)
7399 (dolist (elem (js2-object-node-elems node))
7400 (js2-define-destruct-symbols
7401 (if (js2-object-prop-node-p elem)
7402 (js2-object-prop-node-right elem)
7403 ;; abbreviated destructuring {a, b}
7404 elem)
7405 decl-type face ignore-not-in-block)))
7406 ((js2-array-node-p node)
7407 (dolist (elem (js2-array-node-elems node))
7408 (when elem
7409 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7410 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7411 (js2-node-len node)))))
7412
7413 (defun js2-parse-function-params (fn-node pos)
7414 (if (js2-match-token js2-RP)
7415 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7416 (let (params len param)
7417 (loop for tt = (js2-peek-token)
7418 do
7419 (cond
7420 ;; destructuring param
7421 ((or (= tt js2-LB) (= tt js2-LC))
7422 (setq param (js2-parse-primary-expr-lhs))
7423 (js2-define-destruct-symbols param
7424 js2-LP
7425 'js2-function-param-face)
7426 (push param params))
7427 ;; simple name
7428 (t
7429 (js2-must-match js2-NAME "msg.no.parm")
7430 (js2-record-face 'js2-function-param-face)
7431 (setq param (js2-create-name-node))
7432 (js2-define-symbol js2-LP js2-ts-string param)
7433 (push param params)))
7434 while
7435 (js2-match-token js2-COMMA))
7436 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7437 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7438 (dolist (p params)
7439 (js2-node-add-children fn-node p)
7440 (push p (js2-function-node-params fn-node))))))
7441
7442 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7443 "Possibly show inconsistent-return warning.
7444 Last token scanned is the close-curly for the function body."
7445 (when (and js2-mode-show-strict-warnings
7446 js2-strict-inconsistent-return-warning
7447 (not (js2-has-consistent-return-usage
7448 (js2-function-node-body fn-node))))
7449 ;; Have it extend from close-curly to bol or beginning of block.
7450 (let ((pos (save-excursion
7451 (goto-char js2-token-end)
7452 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7453 (point-at-bol))))
7454 (end js2-token-end))
7455 (if (plusp (js2-name-node-length name))
7456 (js2-add-strict-warning "msg.no.return.value"
7457 (js2-name-node-name name) pos end)
7458 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7459
7460 (defun js2-parse-function (function-type)
7461 "Function parser. FUNCTION-TYPE is a symbol."
7462 (let ((pos js2-token-beg) ; start of 'function' keyword
7463 name
7464 name-beg
7465 name-end
7466 fn-node
7467 lp
7468 (synthetic-type function-type)
7469 member-expr-node)
7470 ;; parse function name, expression, or non-name (anonymous)
7471 (cond
7472 ;; function foo(...)
7473 ((js2-match-token js2-NAME)
7474 (setq name (js2-create-name-node t)
7475 name-beg js2-token-beg
7476 name-end js2-token-end)
7477 (unless (js2-match-token js2-LP)
7478 (when js2-allow-member-expr-as-function-name
7479 ;; function foo.bar(...)
7480 (setq member-expr-node name
7481 name nil
7482 member-expr-node (js2-parse-member-expr-tail
7483 nil member-expr-node)))
7484 (js2-must-match js2-LP "msg.no.paren.parms")))
7485 ((js2-match-token js2-LP)
7486 nil) ; anonymous function: leave name as null
7487 (t
7488 ;; function random-member-expr(...)
7489 (when js2-allow-member-expr-as-function-name
7490 ;; Note that memberExpr can not start with '(' like
7491 ;; in function (1+2).toString(), because 'function (' already
7492 ;; processed as anonymous function
7493 (setq member-expr-node (js2-parse-member-expr)))
7494 (js2-must-match js2-LP "msg.no.paren.parms")))
7495 (if (= js2-current-token js2-LP) ; eventually matched LP?
7496 (setq lp js2-token-beg))
7497 (if member-expr-node
7498 (progn
7499 (setq synthetic-type 'FUNCTION_EXPRESSION)
7500 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7501 (if name
7502 (js2-set-face name-beg name-end
7503 'font-lock-function-name-face 'record)))
7504 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7505 (plusp (js2-name-node-length name)))
7506 ;; Function statements define a symbol in the enclosing scope
7507 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7508 (setf fn-node (make-js2-function-node :pos pos
7509 :name name
7510 :form function-type
7511 :lp (if lp (- lp pos))))
7512 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7513 ;; 1. Nested functions are not affected by the dynamic scope flag
7514 ;; as dynamic scope is already a parent of their scope.
7515 ;; 2. Functions defined under the with statement also immune to
7516 ;; this setup, in which case dynamic scope is ignored in favor
7517 ;; of the with object.
7518 (setf (js2-function-node-ignore-dynamic fn-node) t))
7519 ;; dynamically bind all the per-function variables
7520 (let ((js2-current-script-or-fn fn-node)
7521 (js2-current-scope fn-node)
7522 (js2-nesting-of-with 0)
7523 (js2-end-flags 0)
7524 js2-label-set
7525 js2-loop-set
7526 js2-loop-and-switch-set)
7527 (js2-parse-function-params fn-node pos)
7528 (if (and (>= js2-language-version 180)
7529 (/= (js2-peek-token) js2-LC))
7530 (js2-parse-function-closure-body fn-node)
7531 (js2-parse-function-body fn-node))
7532 (if name
7533 (js2-node-add-children fn-node name))
7534 (js2-check-inconsistent-return-warning fn-node name)
7535 ;; Function expressions define a name only in the body of the
7536 ;; function, and only if not hidden by a parameter name
7537 (if (and name
7538 (eq synthetic-type 'FUNCTION_EXPRESSION)
7539 (null (js2-scope-get-symbol js2-current-scope
7540 (js2-name-node-name name))))
7541 (js2-define-symbol js2-FUNCTION
7542 (js2-name-node-name name)
7543 fn-node))
7544 (if (and name
7545 (not (eq function-type 'FUNCTION_EXPRESSION)))
7546 (js2-record-imenu-functions fn-node)))
7547 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7548 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7549 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7550 ;; We wait until after parsing the function to set its parent scope,
7551 ;; since `js2-define-symbol' needs the defining-scope check to stop
7552 ;; at the function boundary when checking for redeclarations.
7553 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7554 fn-node))
7555
7556 (defun js2-parse-statements (&optional parent)
7557 "Parse a statement list. Last token consumed must be js2-LC.
7558
7559 PARENT can be a `js2-block-node', in which case the statements are
7560 appended to PARENT. Otherwise a new `js2-block-node' is created
7561 and returned.
7562
7563 This function does not match the closing js2-RC: the caller
7564 matches the RC so it can provide a suitable error message if not
7565 matched. This means it's up to the caller to set the length of
7566 the node to include the closing RC. The node start pos is set to
7567 the absolute buffer start position, and the caller should fix it
7568 up to be relative to the parent node. All children of this block
7569 node are given relative start positions and correct lengths."
7570 (let ((pn (or parent (make-js2-block-node)))
7571 tt)
7572 (setf (js2-node-pos pn) js2-token-beg)
7573 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7574 (/= tt js2-RC))
7575 (js2-block-node-push pn (js2-parse-statement)))
7576 pn))
7577
7578 (defun js2-parse-statement ()
7579 (let (tt pn beg end)
7580 ;; coarse-grained user-interrupt check - needs work
7581 (and js2-parse-interruptable-p
7582 (zerop (% (incf js2-parse-stmt-count)
7583 js2-statements-per-pause))
7584 (input-pending-p)
7585 (throw 'interrupted t))
7586 (setq pn (js2-statement-helper))
7587 ;; no-side-effects warning check
7588 (unless (js2-node-has-side-effects pn)
7589 (setq end (js2-node-end pn))
7590 (save-excursion
7591 (goto-char end)
7592 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7593 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7594 pn))
7595
7596 ;; These correspond to the switch cases in Parser.statementHelper
7597 (defconst js2-parsers
7598 (let ((parsers (make-vector js2-num-tokens
7599 #'js2-parse-expr-stmt)))
7600 (aset parsers js2-BREAK #'js2-parse-break)
7601 (aset parsers js2-CONST #'js2-parse-const-var)
7602 (aset parsers js2-CONTINUE #'js2-parse-continue)
7603 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7604 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7605 (aset parsers js2-DO #'js2-parse-do)
7606 (aset parsers js2-FOR #'js2-parse-for)
7607 (aset parsers js2-FUNCTION #'js2-function-parser)
7608 (aset parsers js2-IF #'js2-parse-if)
7609 (aset parsers js2-LC #'js2-parse-block)
7610 (aset parsers js2-LET #'js2-parse-let-stmt)
7611 (aset parsers js2-NAME #'js2-parse-name-or-label)
7612 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7613 (aset parsers js2-SEMI #'js2-parse-semi)
7614 (aset parsers js2-SWITCH #'js2-parse-switch)
7615 (aset parsers js2-THROW #'js2-parse-throw)
7616 (aset parsers js2-TRY #'js2-parse-try)
7617 (aset parsers js2-VAR #'js2-parse-const-var)
7618 (aset parsers js2-WHILE #'js2-parse-while)
7619 (aset parsers js2-WITH #'js2-parse-with)
7620 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7621 parsers)
7622 "A vector mapping token types to parser functions.")
7623
7624 (defsubst js2-parse-warn-missing-semi (beg end)
7625 (and js2-mode-show-strict-warnings
7626 js2-strict-missing-semi-warning
7627 (js2-add-strict-warning
7628 "msg.missing.semi" nil
7629 ;; back up to beginning of statement or line
7630 (max beg (save-excursion
7631 (goto-char end)
7632 (point-at-bol)))
7633 end)))
7634
7635 (defconst js2-no-semi-insertion
7636 (list js2-IF
7637 js2-SWITCH
7638 js2-WHILE
7639 js2-DO
7640 js2-FOR
7641 js2-TRY
7642 js2-WITH
7643 js2-LC
7644 js2-ERROR
7645 js2-SEMI
7646 js2-FUNCTION)
7647 "List of tokens that don't do automatic semicolon insertion.")
7648
7649 (defconst js2-autoinsert-semi-and-warn
7650 (list js2-ERROR js2-EOF js2-RC))
7651
7652 (defun js2-statement-helper ()
7653 (let* ((tt (js2-peek-token))
7654 (first-tt tt)
7655 (beg js2-token-beg)
7656 (parser (if (= tt js2-ERROR)
7657 #'js2-parse-semi
7658 (aref js2-parsers tt)))
7659 pn
7660 tt-flagged)
7661 ;; If the statement is set, then it's been told its label by now.
7662 (and js2-labeled-stmt
7663 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7664 (setq js2-labeled-stmt nil))
7665 (setq pn (funcall parser))
7666 ;; Don't do auto semi insertion for certain statement types.
7667 (unless (or (memq first-tt js2-no-semi-insertion)
7668 (js2-labeled-stmt-node-p pn))
7669 (js2-auto-insert-semicolon pn))
7670 pn))
7671
7672 (defun js2-auto-insert-semicolon (pn)
7673 (let* ((tt-flagged (js2-peek-flagged-token))
7674 (tt (logand tt-flagged js2-clear-ti-mask))
7675 (pos (js2-node-pos pn)))
7676 (cond
7677 ((= tt js2-SEMI)
7678 ;; Consume ';' as a part of expression
7679 (js2-consume-token)
7680 ;; extend the node bounds to include the semicolon.
7681 (setf (js2-node-len pn) (- js2-token-end pos)))
7682 ((memq tt js2-autoinsert-semi-and-warn)
7683 ;; Autoinsert ;
7684 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7685 (t
7686 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7687 ;; Report error if no EOL or autoinsert ';' otherwise
7688 (js2-report-error "msg.no.semi.stmt")
7689 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7690
7691 (defun js2-parse-condition ()
7692 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7693 The parens are discarded and the expression node is returned.
7694 The `pos' field of the return value is set to an absolute position
7695 that must be fixed up by the caller.
7696 Return value is a list (EXPR LP RP), with absolute paren positions."
7697 (let (pn lp rp)
7698 (if (js2-must-match js2-LP "msg.no.paren.cond")
7699 (setq lp js2-token-beg))
7700 (setq pn (js2-parse-expr))
7701 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7702 (setq rp js2-token-beg))
7703 ;; Report strict warning on code like "if (a = 7) ..."
7704 (if (and js2-strict-cond-assign-warning
7705 (js2-assign-node-p pn))
7706 (js2-add-strict-warning "msg.equal.as.assign" nil
7707 (js2-node-pos pn)
7708 (+ (js2-node-pos pn)
7709 (js2-node-len pn))))
7710 (list pn lp rp)))
7711
7712 (defun js2-parse-if ()
7713 "Parser for if-statement. Last matched token must be js2-IF."
7714 (let ((pos js2-token-beg)
7715 cond
7716 if-true
7717 if-false
7718 else-pos
7719 end
7720 pn)
7721 (js2-consume-token)
7722 (setq cond (js2-parse-condition)
7723 if-true (js2-parse-statement)
7724 if-false (if (js2-match-token js2-ELSE)
7725 (progn
7726 (setq else-pos (- js2-token-beg pos))
7727 (js2-parse-statement)))
7728 end (js2-node-end (or if-false if-true))
7729 pn (make-js2-if-node :pos pos
7730 :len (- end pos)
7731 :condition (car cond)
7732 :then-part if-true
7733 :else-part if-false
7734 :else-pos else-pos
7735 :lp (js2-relpos (second cond) pos)
7736 :rp (js2-relpos (third cond) pos)))
7737 (js2-node-add-children pn (car cond) if-true if-false)
7738 pn))
7739
7740 (defun js2-parse-switch ()
7741 "Parser for if-statement. Last matched token must be js2-SWITCH."
7742 (let ((pos js2-token-beg)
7743 tt
7744 pn
7745 discriminant
7746 has-default
7747 case-expr
7748 case-node
7749 case-pos
7750 cases
7751 stmt
7752 lp
7753 rp)
7754 (js2-consume-token)
7755 (if (js2-must-match js2-LP "msg.no.paren.switch")
7756 (setq lp js2-token-beg))
7757 (setq discriminant (js2-parse-expr)
7758 pn (make-js2-switch-node :discriminant discriminant
7759 :pos pos
7760 :lp (js2-relpos lp pos)))
7761 (js2-node-add-children pn discriminant)
7762 (js2-enter-switch pn)
7763 (unwind-protect
7764 (progn
7765 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7766 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7767 (js2-must-match js2-LC "msg.no.brace.switch")
7768 (catch 'break
7769 (while t
7770 (setq tt (js2-next-token)
7771 case-pos js2-token-beg)
7772 (cond
7773 ((= tt js2-RC)
7774 (setf (js2-node-len pn) (- js2-token-end pos))
7775 (throw 'break nil)) ; done
7776 ((= tt js2-CASE)
7777 (setq case-expr (js2-parse-expr))
7778 (js2-must-match js2-COLON "msg.no.colon.case"))
7779 ((= tt js2-DEFAULT)
7780 (if has-default
7781 (js2-report-error "msg.double.switch.default"))
7782 (setq has-default t
7783 case-expr nil)
7784 (js2-must-match js2-COLON "msg.no.colon.case"))
7785 (t
7786 (js2-report-error "msg.bad.switch")
7787 (throw 'break nil)))
7788 (setq case-node (make-js2-case-node :pos case-pos
7789 :len (- js2-token-end case-pos)
7790 :expr case-expr))
7791 (js2-node-add-children case-node case-expr)
7792 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7793 (/= tt js2-CASE)
7794 (/= tt js2-DEFAULT)
7795 (/= tt js2-EOF))
7796 (setf stmt (js2-parse-statement)
7797 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7798 (js2-block-node-push case-node stmt))
7799 (push case-node cases)))
7800 ;; add cases last, as pushing reverses the order to be correct
7801 (dolist (kid cases)
7802 (js2-node-add-children pn kid)
7803 (push kid (js2-switch-node-cases pn)))
7804 pn) ; return value
7805 (js2-exit-switch))))
7806
7807 (defun js2-parse-while ()
7808 "Parser for while-statement. Last matched token must be js2-WHILE."
7809 (let ((pos js2-token-beg)
7810 (pn (make-js2-while-node))
7811 cond
7812 body)
7813 (js2-consume-token)
7814 (js2-enter-loop pn)
7815 (unwind-protect
7816 (progn
7817 (setf cond (js2-parse-condition)
7818 (js2-while-node-condition pn) (car cond)
7819 body (js2-parse-statement)
7820 (js2-while-node-body pn) body
7821 (js2-node-len pn) (- (js2-node-end body) pos)
7822 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7823 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7824 (js2-node-add-children pn body (car cond)))
7825 (js2-exit-loop))
7826 pn))
7827
7828 (defun js2-parse-do ()
7829 "Parser for do-statement. Last matched token must be js2-DO."
7830 (let ((pos js2-token-beg)
7831 (pn (make-js2-do-node))
7832 cond
7833 body
7834 end)
7835 (js2-consume-token)
7836 (js2-enter-loop pn)
7837 (unwind-protect
7838 (progn
7839 (setq body (js2-parse-statement))
7840 (js2-must-match js2-WHILE "msg.no.while.do")
7841 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7842 cond (js2-parse-condition)
7843 (js2-do-node-condition pn) (car cond)
7844 (js2-do-node-body pn) body
7845 end js2-ts-cursor
7846 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7847 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7848 (js2-node-add-children pn (car cond) body))
7849 (js2-exit-loop))
7850 ;; Always auto-insert semicolon to follow SpiderMonkey:
7851 ;; It is required by ECMAScript but is ignored by the rest of
7852 ;; world; see bug 238945
7853 (if (js2-match-token js2-SEMI)
7854 (setq end js2-ts-cursor))
7855 (setf (js2-node-len pn) (- end pos))
7856 pn))
7857
7858 (defun js2-parse-for ()
7859 "Parser for for-statement. Last matched token must be js2-FOR.
7860 Parses for, for-in, and for each-in statements."
7861 (let ((for-pos js2-token-beg)
7862 pn
7863 is-for-each
7864 is-for-in
7865 in-pos
7866 each-pos
7867 tmp-pos
7868 init ; Node init is also foo in 'foo in object'
7869 cond ; Node cond is also object in 'foo in object'
7870 incr ; 3rd section of for-loop initializer
7871 body
7872 tt
7873 lp
7874 rp)
7875 (js2-consume-token)
7876 ;; See if this is a for each () instead of just a for ()
7877 (when (js2-match-token js2-NAME)
7878 (if (string= "each" js2-ts-string)
7879 (progn
7880 (setq is-for-each t
7881 each-pos (- js2-token-beg for-pos)) ; relative
7882 (js2-record-face 'font-lock-keyword-face))
7883 (js2-report-error "msg.no.paren.for")))
7884 (if (js2-must-match js2-LP "msg.no.paren.for")
7885 (setq lp (- js2-token-beg for-pos)))
7886 (setq tt (js2-peek-token))
7887 ;; parse init clause
7888 (let ((js2-in-for-init t)) ; set as dynamic variable
7889 (cond
7890 ((= tt js2-SEMI)
7891 (setq init (make-js2-empty-expr-node)))
7892 ((or (= tt js2-VAR) (= tt js2-LET))
7893 (js2-consume-token)
7894 (setq init (js2-parse-variables tt js2-token-beg)))
7895 (t
7896 (setq init (js2-parse-expr)))))
7897 (if (js2-match-token js2-IN)
7898 (setq is-for-in t
7899 in-pos (- js2-token-beg for-pos)
7900 cond (js2-parse-expr)) ; object over which we're iterating
7901 ;; else ordinary for loop - parse cond and incr
7902 (js2-must-match js2-SEMI "msg.no.semi.for")
7903 (setq cond (if (= (js2-peek-token) js2-SEMI)
7904 (make-js2-empty-expr-node) ; no loop condition
7905 (js2-parse-expr)))
7906 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7907 (setq tmp-pos js2-token-end
7908 incr (if (= (js2-peek-token) js2-RP)
7909 (make-js2-empty-expr-node :pos tmp-pos)
7910 (js2-parse-expr))))
7911 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7912 (setq rp (- js2-token-beg for-pos)))
7913 (if (not is-for-in)
7914 (setq pn (make-js2-for-node :init init
7915 :condition cond
7916 :update incr
7917 :lp lp
7918 :rp rp))
7919 ;; cond could be null if 'in obj' got eaten by the init node.
7920 (if (js2-infix-node-p init)
7921 ;; it was (foo in bar) instead of (var foo in bar)
7922 (setq cond (js2-infix-node-right init)
7923 init (js2-infix-node-left init))
7924 (if (and (js2-var-decl-node-p init)
7925 (> (length (js2-var-decl-node-kids init)) 1))
7926 (js2-report-error "msg.mult.index")))
7927 (setq pn (make-js2-for-in-node :iterator init
7928 :object cond
7929 :in-pos in-pos
7930 :foreach-p is-for-each
7931 :each-pos each-pos
7932 :lp lp
7933 :rp rp)))
7934 (unwind-protect
7935 (progn
7936 (js2-enter-loop pn)
7937 ;; We have to parse the body -after- creating the loop node,
7938 ;; so that the loop node appears in the js2-loop-set, allowing
7939 ;; break/continue statements to find the enclosing loop.
7940 (setf body (js2-parse-statement)
7941 (js2-loop-node-body pn) body
7942 (js2-node-pos pn) for-pos
7943 (js2-node-len pn) (- (js2-node-end body) for-pos))
7944 (js2-node-add-children pn init cond incr body))
7945 ;; finally
7946 (js2-exit-loop))
7947 pn))
7948
7949 (defun js2-parse-try ()
7950 "Parser for try-statement. Last matched token must be js2-TRY."
7951 (let ((try-pos js2-token-beg)
7952 try-end
7953 try-block
7954 catch-blocks
7955 finally-block
7956 saw-default-catch
7957 peek
7958 var-name
7959 catch-cond
7960 catch-node
7961 guard-kwd
7962 catch-pos
7963 finally-pos
7964 pn
7965 block
7966 lp
7967 rp)
7968 (js2-consume-token)
7969 (if (/= (js2-peek-token) js2-LC)
7970 (js2-report-error "msg.no.brace.try"))
7971 (setq try-block (js2-parse-statement)
7972 try-end (js2-node-end try-block)
7973 peek (js2-peek-token))
7974 (cond
7975 ((= peek js2-CATCH)
7976 (while (js2-match-token js2-CATCH)
7977 (setq catch-pos js2-token-beg
7978 guard-kwd nil
7979 catch-cond nil
7980 lp nil
7981 rp nil)
7982 (if saw-default-catch
7983 (js2-report-error "msg.catch.unreachable"))
7984 (if (js2-must-match js2-LP "msg.no.paren.catch")
7985 (setq lp (- js2-token-beg catch-pos)))
7986 (js2-must-match js2-NAME "msg.bad.catchcond")
7987 (js2-push-scope (make-js2-scope))
7988 (setq var-name (js2-create-name-node))
7989 (js2-define-symbol js2-LET (js2-name-node-name var-name) var-name t)
7990 (if (js2-match-token js2-IF)
7991 (setq guard-kwd (- js2-token-beg catch-pos)
7992 catch-cond (js2-parse-expr))
7993 (setq saw-default-catch t))
7994 (if (js2-must-match js2-RP "msg.bad.catchcond")
7995 (setq rp (- js2-token-beg catch-pos)))
7996 (js2-must-match js2-LC "msg.no.brace.catchblock")
7997 (setq block (js2-parse-statements)
7998 try-end (js2-node-end block)
7999 catch-node (make-js2-catch-node :pos catch-pos
8000 :var-name var-name
8001 :guard-expr catch-cond
8002 :guard-kwd guard-kwd
8003 :block block
8004 :lp lp
8005 :rp rp))
8006 (js2-pop-scope)
8007 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8008 (setq try-end js2-token-beg))
8009 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8010 (js2-node-len catch-node) (- try-end catch-pos))
8011 (js2-node-add-children catch-node var-name catch-cond block)
8012 (push catch-node catch-blocks)))
8013 ((/= peek js2-FINALLY)
8014 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8015 (js2-node-pos try-block)
8016 (- (setq try-end (js2-node-end try-block))
8017 (js2-node-pos try-block)))))
8018 (when (js2-match-token js2-FINALLY)
8019 (setq finally-pos js2-token-beg
8020 block (js2-parse-statement)
8021 try-end (js2-node-end block)
8022 finally-block (make-js2-finally-node :pos finally-pos
8023 :len (- try-end finally-pos)
8024 :body block))
8025 (js2-node-add-children finally-block block))
8026 (setq pn (make-js2-try-node :pos try-pos
8027 :len (- try-end try-pos)
8028 :try-block try-block
8029 :finally-block finally-block))
8030 (js2-node-add-children pn try-block finally-block)
8031 ;; push them onto the try-node, which reverses and corrects their order
8032 (dolist (cb catch-blocks)
8033 (js2-node-add-children pn cb)
8034 (push cb (js2-try-node-catch-clauses pn)))
8035 pn))
8036
8037 (defun js2-parse-throw ()
8038 "Parser for throw-statement. Last matched token must be js2-THROW."
8039 (let ((pos js2-token-beg)
8040 expr
8041 pn)
8042 (js2-consume-token)
8043 (if (= (js2-peek-token-or-eol) js2-EOL)
8044 ;; ECMAScript does not allow new lines before throw expression,
8045 ;; see bug 256617
8046 (js2-report-error "msg.bad.throw.eol"))
8047 (setq expr (js2-parse-expr)
8048 pn (make-js2-throw-node :pos pos
8049 :len (- (js2-node-end expr) pos)
8050 :expr expr))
8051 (js2-node-add-children pn expr)
8052 pn))
8053
8054 (defsubst js2-match-jump-label-name (label-name)
8055 "If break/continue specified a label, return that label's labeled stmt.
8056 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8057 does not match an existing label, reports an error and returns nil."
8058 (let ((bundle (cdr (assoc label-name js2-label-set))))
8059 (if (null bundle)
8060 (js2-report-error "msg.undef.label"))
8061 bundle))
8062
8063 (defun js2-parse-break ()
8064 "Parser for break-statement. Last matched token must be js2-BREAK."
8065 (let ((pos js2-token-beg)
8066 (end js2-token-end)
8067 break-target ; statement to break from
8068 break-label ; in "break foo", name-node representing the foo
8069 labels ; matching labeled statement to break to
8070 pn)
8071 (js2-consume-token) ; `break'
8072 (when (eq (js2-peek-token-or-eol) js2-NAME)
8073 (js2-consume-token)
8074 (setq break-label (js2-create-name-node)
8075 end (js2-node-end break-label)
8076 ;; matchJumpLabelName only matches if there is one
8077 labels (js2-match-jump-label-name js2-ts-string)
8078 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8079 (unless (or break-target break-label)
8080 ;; no break target specified - try for innermost enclosing loop/switch
8081 (if (null js2-loop-and-switch-set)
8082 (unless break-label
8083 (js2-report-error "msg.bad.break" nil pos (length "break")))
8084 (setq break-target (car js2-loop-and-switch-set))))
8085 (setq pn (make-js2-break-node :pos pos
8086 :len (- end pos)
8087 :label break-label
8088 :target break-target))
8089 (js2-node-add-children pn break-label) ; but not break-target
8090 pn))
8091
8092 (defun js2-parse-continue ()
8093 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8094 (let ((pos js2-token-beg)
8095 (end js2-token-end)
8096 label ; optional user-specified label, a `js2-name-node'
8097 labels ; current matching labeled stmt, if any
8098 target ; the `js2-loop-node' target of this continue stmt
8099 pn)
8100 (js2-consume-token) ; `continue'
8101 (when (= (js2-peek-token-or-eol) js2-NAME)
8102 (js2-consume-token)
8103 (setq label (js2-create-name-node)
8104 end (js2-node-end label)
8105 ;; matchJumpLabelName only matches if there is one
8106 labels (js2-match-jump-label-name js2-ts-string)))
8107 (cond
8108 ((null labels) ; no current label to go to
8109 (if (null js2-loop-set) ; no loop to continue to
8110 (js2-report-error "msg.continue.outside" nil pos
8111 (length "continue"))
8112 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8113 (t
8114 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8115 (setq target (js2-labeled-stmt-node-stmt labels))
8116 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8117 (setq pn (make-js2-continue-node :pos pos
8118 :len (- end pos)
8119 :label label
8120 :target target))
8121 (js2-node-add-children pn label) ; but not target - it's not our child
8122 pn))
8123
8124 (defun js2-parse-with ()
8125 "Parser for with-statement. Last matched token must be js2-WITH."
8126 (js2-consume-token)
8127 (let ((pos js2-token-beg)
8128 obj body pn lp rp)
8129 (if (js2-must-match js2-LP "msg.no.paren.with")
8130 (setq lp js2-token-beg))
8131 (setq obj (js2-parse-expr))
8132 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8133 (setq rp js2-token-beg))
8134 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8135 (setq body (js2-parse-statement)))
8136 (setq pn (make-js2-with-node :pos pos
8137 :len (- (js2-node-end body) pos)
8138 :object obj
8139 :body body
8140 :lp (js2-relpos lp pos)
8141 :rp (js2-relpos rp pos)))
8142 (js2-node-add-children pn obj body)
8143 pn))
8144
8145 (defun js2-parse-const-var ()
8146 "Parser for var- or const-statement.
8147 Last matched token must be js2-CONST or js2-VAR."
8148 (let ((tt (js2-peek-token))
8149 (pos js2-token-beg)
8150 expr
8151 pn)
8152 (js2-consume-token)
8153 (setq expr (js2-parse-variables tt js2-token-beg)
8154 pn (make-js2-expr-stmt-node :pos pos
8155 :len (- (js2-node-end expr) pos)
8156 :expr expr))
8157 (js2-node-add-children pn expr)
8158 pn))
8159
8160 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8161 (let ((pn (make-js2-expr-stmt-node :pos pos
8162 :len (js2-node-len expr)
8163 :type (if (js2-inside-function)
8164 js2-EXPR_VOID
8165 js2-EXPR_RESULT)
8166 :expr expr)))
8167 (if add-child
8168 (js2-node-add-children pn expr))
8169 pn))
8170
8171 (defun js2-parse-let-stmt ()
8172 "Parser for let-statement. Last matched token must be js2-LET."
8173 (js2-consume-token)
8174 (let ((pos js2-token-beg)
8175 expr
8176 pn)
8177 (if (= (js2-peek-token) js2-LP)
8178 ;; let expression in statement context
8179 (setq expr (js2-parse-let pos 'statement)
8180 pn (js2-wrap-with-expr-stmt pos expr t))
8181 ;; else we're looking at a statement like let x=6, y=7;
8182 (setf expr (js2-parse-variables js2-LET pos)
8183 pn (js2-wrap-with-expr-stmt pos expr t)
8184 (js2-node-type pn) js2-EXPR_RESULT))
8185 pn))
8186
8187 (defun js2-parse-ret-yield ()
8188 (js2-parse-return-or-yield (js2-peek-token) nil))
8189
8190 (defconst js2-parse-return-stmt-enders
8191 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8192
8193 (defsubst js2-now-all-set (before after mask)
8194 "Return whether or not the bits in the mask have changed to all set.
8195 BEFORE is bits before change, AFTER is bits after change, and MASK is
8196 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8197 but not BEFORE."
8198 (and (/= (logand before mask) mask)
8199 (= (logand after mask) mask)))
8200
8201 (defun js2-parse-return-or-yield (tt expr-context)
8202 (let ((pos js2-token-beg)
8203 (end js2-token-end)
8204 (before js2-end-flags)
8205 (inside-function (js2-inside-function))
8206 e
8207 ret
8208 name)
8209 (unless inside-function
8210 (js2-report-error (if (eq tt js2-RETURN)
8211 "msg.bad.return"
8212 "msg.bad.yield")))
8213 (js2-consume-token)
8214 ;; This is ugly, but we don't want to require a semicolon.
8215 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8216 (setq e (js2-parse-expr)
8217 end (js2-node-end e)))
8218 (cond
8219 ((eq tt js2-RETURN)
8220 (js2-set-flag js2-end-flags (if (null e)
8221 js2-end-returns
8222 js2-end-returns-value))
8223 (setq ret (make-js2-return-node :pos pos
8224 :len (- end pos)
8225 :retval e))
8226 (js2-node-add-children ret e)
8227 ;; See if we need a strict mode warning.
8228 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8229 ;; more thorough and accurate than this before/after flag check.
8230 ;; E.g. if there's a finally-block that always returns, we shouldn't
8231 ;; show a warning generated by inconsistent returns in the catch blocks.
8232 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8233 ;; so we know which returns/yields to highlight, and we should get rid of
8234 ;; all the checking in `js2-parse-return-or-yield'.
8235 (if (and js2-strict-inconsistent-return-warning
8236 (js2-now-all-set before js2-end-flags
8237 (logior js2-end-returns js2-end-returns-value)))
8238 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8239 (t
8240 (unless (js2-inside-function)
8241 (js2-report-error "msg.bad.yield"))
8242 (js2-set-flag js2-end-flags js2-end-yields)
8243 (setq ret (make-js2-yield-node :pos pos
8244 :len (- end pos)
8245 :value e))
8246 (js2-node-add-children ret e)
8247 (unless expr-context
8248 (setq e ret
8249 ret (js2-wrap-with-expr-stmt pos e t))
8250 (js2-set-requires-activation)
8251 (js2-set-is-generator))))
8252 ;; see if we are mixing yields and value returns.
8253 (when (and inside-function
8254 (js2-now-all-set before js2-end-flags
8255 (logior js2-end-yields js2-end-returns-value)))
8256 (setq name (js2-function-name js2-current-script-or-fn))
8257 (if (zerop (length name))
8258 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8259 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8260 ret))
8261
8262 (defun js2-parse-debugger ()
8263 (js2-consume-token)
8264 (make-js2-keyword-node :type js2-DEBUGGER))
8265
8266 (defun js2-parse-block ()
8267 "Parser for a curly-delimited statement block.
8268 Last token matched must be js2-LC."
8269 (let ((pos js2-token-beg)
8270 (pn (make-js2-scope)))
8271 (js2-consume-token)
8272 (js2-push-scope pn)
8273 (unwind-protect
8274 (progn
8275 (js2-parse-statements pn)
8276 (js2-must-match js2-RC "msg.no.brace.block")
8277 (setf (js2-node-len pn) (- js2-token-end pos)))
8278 (js2-pop-scope))
8279 pn))
8280
8281 ;; for js2-ERROR too, to have a node for error recovery to work on
8282 (defun js2-parse-semi ()
8283 "Parse a statement or handle an error.
8284 Last matched token is js-SEMI or js-ERROR."
8285 (let ((tt (js2-peek-token)) pos len)
8286 (js2-consume-token)
8287 (if (eq tt js2-SEMI)
8288 (make-js2-empty-expr-node :len 1)
8289 (setq pos js2-token-beg
8290 len (- js2-token-beg pos))
8291 (js2-report-error "msg.syntax" nil pos len)
8292 (make-js2-error-node :pos pos :len len))))
8293
8294 (defun js2-parse-default-xml-namespace ()
8295 "Parse a `default xml namespace = <expr>' e4x statement."
8296 (let ((pos js2-token-beg)
8297 end len expr unary es)
8298 (js2-consume-token)
8299 (js2-must-have-xml)
8300 (js2-set-requires-activation)
8301 (setq len (- js2-ts-cursor pos))
8302 (unless (and (js2-match-token js2-NAME)
8303 (string= js2-ts-string "xml"))
8304 (js2-report-error "msg.bad.namespace" nil pos len))
8305 (unless (and (js2-match-token js2-NAME)
8306 (string= js2-ts-string "namespace"))
8307 (js2-report-error "msg.bad.namespace" nil pos len))
8308 (unless (js2-match-token js2-ASSIGN)
8309 (js2-report-error "msg.bad.namespace" nil pos len))
8310 (setq expr (js2-parse-expr)
8311 end (js2-node-end expr)
8312 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8313 :pos pos
8314 :len (- end pos)
8315 :operand expr))
8316 (js2-node-add-children unary expr)
8317 (make-js2-expr-stmt-node :pos pos
8318 :len (- end pos)
8319 :expr unary)))
8320
8321 (defun js2-record-label (label bundle)
8322 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8323 (js2-consume-token)
8324 (let ((name (js2-label-node-name label))
8325 labeled-stmt
8326 dup)
8327 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8328 ;; flag both labels if possible when used in editing mode
8329 (if (and js2-parse-ide-mode
8330 (setq dup (js2-get-label-by-name labeled-stmt name)))
8331 (js2-report-error "msg.dup.label" nil
8332 (js2-node-abs-pos dup) (js2-node-len dup)))
8333 (js2-report-error "msg.dup.label" nil
8334 (js2-node-pos label) (js2-node-len label)))
8335 (js2-labeled-stmt-node-add-label bundle label)
8336 (js2-node-add-children bundle label)
8337 ;; Add one reference to the bundle per label in `js2-label-set'
8338 (push (cons name bundle) js2-label-set)))
8339
8340 (defun js2-parse-name-or-label ()
8341 "Parser for identifier or label. Last token matched must be js2-NAME.
8342 Called when we found a name in a statement context. If it's a label, we gather
8343 up any following labels and the next non-label statement into a
8344 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8345 expression and return it wrapped in a `js2-expr-stmt-node'."
8346 (let ((pos js2-token-beg)
8347 (end js2-token-end)
8348 expr
8349 stmt
8350 pn
8351 bundle
8352 (continue t))
8353 ;; set check for label and call down to `js2-parse-primary-expr'
8354 (js2-set-check-for-label)
8355 (setq expr (js2-parse-expr))
8356 (if (/= (js2-node-type expr) js2-LABEL)
8357 ;; Parsed non-label expression - wrap with expression stmt.
8358 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8359 ;; else parsed a label
8360 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8361 (js2-record-label expr bundle)
8362 ;; look for more labels
8363 (while (and continue (= (js2-peek-token) js2-NAME))
8364 (js2-set-check-for-label)
8365 (setq expr (js2-parse-expr))
8366 (if (/= (js2-node-type expr) js2-LABEL)
8367 (progn
8368 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8369 continue nil)
8370 (js2-auto-insert-semicolon stmt))
8371 (js2-record-label expr bundle)))
8372 ;; no more labels; now parse the labeled statement
8373 (unwind-protect
8374 (unless stmt
8375 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8376 (setq stmt (js2-statement-helper))))
8377 ;; remove the labels for this statement from the global set
8378 (dolist (label (js2-labeled-stmt-node-labels bundle))
8379 (setq js2-label-set (remove label js2-label-set))))
8380 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8381 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8382 (js2-node-add-children bundle stmt)
8383 bundle)))
8384
8385 (defun js2-parse-expr-stmt ()
8386 "Default parser in statement context, if no recognized statement found."
8387 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8388
8389 (defun js2-parse-variables (decl-type pos)
8390 "Parse a comma-separated list of variable declarations.
8391 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8392
8393 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8394 For 'var' or 'const', the keyword should be the token last scanned.
8395
8396 POS is the position where the node should start. It's sometimes the
8397 var/const/let keyword, and other times the beginning of the first token
8398 in the first variable declaration.
8399
8400 Returns the parsed `js2-var-decl-node' expression node."
8401 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8402 :pos pos))
8403 destructuring
8404 kid-pos
8405 tt
8406 init
8407 name
8408 end
8409 nbeg nend
8410 vi
8411 (continue t))
8412 ;; Example:
8413 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8414 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8415 ;; var {a, b} = baz;
8416 (while continue
8417 (setq destructuring nil
8418 name nil
8419 tt (js2-peek-token)
8420 kid-pos js2-token-beg
8421 end js2-token-end
8422 init nil)
8423 (if (or (= tt js2-LB) (= tt js2-LC))
8424 ;; Destructuring assignment, e.g., var [a, b] = ...
8425 (setq destructuring (js2-parse-primary-expr-lhs)
8426 end (js2-node-end destructuring))
8427 ;; Simple variable name
8428 (when (js2-must-match js2-NAME "msg.bad.var")
8429 (setq name (js2-create-name-node)
8430 nbeg js2-token-beg
8431 nend js2-token-end
8432 end nend)
8433 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8434 (when (js2-match-token js2-ASSIGN)
8435 (setq init (js2-parse-assign-expr)
8436 end (js2-node-end init))
8437 (if (and js2-parse-ide-mode
8438 (or (js2-object-node-p init)
8439 (js2-function-node-p init)))
8440 (js2-record-imenu-functions init name)))
8441 (when name
8442 (js2-set-face nbeg nend (if (js2-function-node-p init)
8443 'font-lock-function-name-face
8444 'font-lock-variable-name-face)
8445 'record))
8446 (setq vi (make-js2-var-init-node :pos kid-pos
8447 :len (- end kid-pos)
8448 :type decl-type))
8449 (if destructuring
8450 (progn
8451 (if (and (null init) (not js2-in-for-init))
8452 (js2-report-error "msg.destruct.assign.no.init"))
8453 (js2-define-destruct-symbols destructuring
8454 decl-type
8455 'font-lock-variable-name-face)
8456 (setf (js2-var-init-node-target vi) destructuring))
8457 (setf (js2-var-init-node-target vi) name))
8458 (setf (js2-var-init-node-initializer vi) init)
8459 (js2-node-add-children vi name destructuring init)
8460 (js2-block-node-push result vi)
8461 (unless (js2-match-token js2-COMMA)
8462 (setq continue nil)))
8463 (setf (js2-node-len result) (- end pos))
8464 result))
8465
8466 (defun js2-parse-let (pos &optional stmt-p)
8467 "Parse a let expression or statement.
8468 A let-expression is of the form `let (vars) expr'.
8469 A let-statment is of the form `let (vars) {statements}'.
8470 The third form of let is a variable declaration list, handled
8471 by `js2-parse-variables'."
8472 (let ((pn (make-js2-let-node :pos pos))
8473 beg vars body)
8474 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8475 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8476 (js2-push-scope pn)
8477 (unwind-protect
8478 (progn
8479 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8480 (if (js2-must-match js2-RP "msg.no.paren.let")
8481 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8482 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8483 ;; let statement
8484 (progn
8485 (js2-consume-token)
8486 (setf beg js2-token-beg ; position stmt at LC
8487 body (js2-parse-statements))
8488 (js2-must-match js2-RC "msg.no.curly.let")
8489 (setf (js2-node-len body) (- js2-token-end beg)
8490 (js2-node-len pn) (- js2-token-end pos)
8491 (js2-let-node-body pn) body
8492 (js2-node-type pn) js2-LET))
8493 ;; let expression
8494 (setf body (js2-parse-expr)
8495 (js2-node-len pn) (- (js2-node-end body) pos)
8496 (js2-let-node-body pn) body))
8497 (js2-node-add-children pn vars body))
8498 (js2-pop-scope))
8499 pn))
8500
8501 (defsubst js2-define-new-symbol (decl-type name node)
8502 (js2-scope-put-symbol js2-current-scope
8503 name
8504 (make-js2-symbol decl-type name node)))
8505
8506 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8507 "Define a symbol in the current scope.
8508 If NODE is non-nil, it is the AST node associated with the symbol."
8509 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8510 (symbol (if defining-scope
8511 (js2-scope-get-symbol defining-scope name)))
8512 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8513 (cond
8514 ((and symbol ; already defined
8515 (or (= sdt js2-CONST) ; old version is const
8516 (= decl-type js2-CONST) ; new version is const
8517 ;; two let-bound vars in this block have same name
8518 (and (= sdt js2-LET)
8519 (eq defining-scope js2-current-scope))))
8520 (js2-report-error
8521 (cond
8522 ((= sdt js2-CONST) "msg.const.redecl")
8523 ((= sdt js2-LET) "msg.let.redecl")
8524 ((= sdt js2-VAR) "msg.var.redecl")
8525 ((= sdt js2-FUNCTION) "msg.function.redecl")
8526 (t "msg.parm.redecl"))
8527 name))
8528 ((= decl-type js2-LET)
8529 (if (and (not ignore-not-in-block)
8530 (or (= (js2-node-type js2-current-scope) js2-IF)
8531 (js2-loop-node-p js2-current-scope)))
8532 (js2-report-error "msg.let.decl.not.in.block")
8533 (js2-define-new-symbol decl-type name node)))
8534 ((or (= decl-type js2-VAR)
8535 (= decl-type js2-CONST)
8536 (= decl-type js2-FUNCTION))
8537 (if symbol
8538 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8539 (js2-add-strict-warning "msg.var.redecl" name)
8540 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8541 (js2-add-strict-warning "msg.var.hides.arg" name)))
8542 (js2-define-new-symbol decl-type name node)))
8543 ((= decl-type js2-LP)
8544 (if symbol
8545 ;; must be duplicate parameter. Second parameter hides the
8546 ;; first, so go ahead and add the second pararameter
8547 (js2-report-warning "msg.dup.parms" name))
8548 (js2-define-new-symbol decl-type name node))
8549 (t (js2-code-bug)))))
8550
8551 (defun js2-parse-expr (&optional oneshot)
8552 (let* ((pn (js2-parse-assign-expr))
8553 (pos (js2-node-pos pn))
8554 left
8555 right
8556 op-pos)
8557 (while (and (not oneshot)
8558 (js2-match-token js2-COMMA))
8559 (setq op-pos (- js2-token-beg pos)) ; relative
8560 (if (= (js2-peek-token) js2-YIELD)
8561 (js2-report-error "msg.yield.parenthesized"))
8562 (setq right (js2-parse-assign-expr)
8563 left pn
8564 pn (make-js2-infix-node :type js2-COMMA
8565 :pos pos
8566 :len (- js2-ts-cursor pos)
8567 :op-pos op-pos
8568 :left left
8569 :right right))
8570 (js2-node-add-children pn left right))
8571 pn))
8572
8573 (defun js2-parse-assign-expr ()
8574 (let ((tt (js2-peek-token))
8575 (pos js2-token-beg)
8576 pn
8577 left
8578 right
8579 op-pos)
8580 (if (= tt js2-YIELD)
8581 (js2-parse-return-or-yield tt t)
8582 ;; not yield - parse assignment expression
8583 (setq pn (js2-parse-cond-expr)
8584 tt (js2-peek-token))
8585 (when (and (<= js2-first-assign tt)
8586 (<= tt js2-last-assign))
8587 ;; tt express assignment (=, |=, ^=, ..., %=)
8588 (js2-consume-token)
8589 (setq op-pos (- js2-token-beg pos) ; relative
8590 left pn
8591 right (js2-parse-assign-expr)
8592 pn (make-js2-assign-node :type tt
8593 :pos pos
8594 :len (- (js2-node-end right) pos)
8595 :op-pos op-pos
8596 :left left
8597 :right right))
8598 (when js2-parse-ide-mode
8599 (js2-highlight-assign-targets pn left right)
8600 (if (or (js2-function-node-p right)
8601 (js2-object-node-p right))
8602 (js2-record-imenu-functions right left)))
8603 ;; do this last so ide checks above can use absolute positions
8604 (js2-node-add-children pn left right))
8605 pn)))
8606
8607 (defun js2-parse-cond-expr ()
8608 (let ((pos js2-token-beg)
8609 (pn (js2-parse-or-expr))
8610 test-expr
8611 if-true
8612 if-false
8613 q-pos
8614 c-pos)
8615 (when (js2-match-token js2-HOOK)
8616 (setq q-pos (- js2-token-beg pos)
8617 if-true (js2-parse-assign-expr))
8618 (js2-must-match js2-COLON "msg.no.colon.cond")
8619 (setq c-pos (- js2-token-beg pos)
8620 if-false (js2-parse-assign-expr)
8621 test-expr pn
8622 pn (make-js2-cond-node :pos pos
8623 :len (- (js2-node-end if-false) pos)
8624 :test-expr test-expr
8625 :true-expr if-true
8626 :false-expr if-false
8627 :q-pos q-pos
8628 :c-pos c-pos))
8629 (js2-node-add-children pn test-expr if-true if-false))
8630 pn))
8631
8632 (defun js2-make-binary (type left parser)
8633 "Helper for constructing a binary-operator AST node.
8634 LEFT is the left-side-expression, already parsed, and the
8635 binary operator should have just been matched.
8636 PARSER is a function to call to parse the right operand,
8637 or a `js2-node' struct if it has already been parsed."
8638 (let* ((pos (js2-node-pos left))
8639 (op-pos (- js2-token-beg pos))
8640 (right (if (js2-node-p parser)
8641 parser
8642 (funcall parser)))
8643 (pn (make-js2-infix-node :type type
8644 :pos pos
8645 :len (- (js2-node-end right) pos)
8646 :op-pos op-pos
8647 :left left
8648 :right right)))
8649 (js2-node-add-children pn left right)
8650 pn))
8651
8652 (defun js2-parse-or-expr ()
8653 (let ((pn (js2-parse-and-expr)))
8654 (when (js2-match-token js2-OR)
8655 (setq pn (js2-make-binary js2-OR
8656 pn
8657 'js2-parse-or-expr)))
8658 pn))
8659
8660 (defun js2-parse-and-expr ()
8661 (let ((pn (js2-parse-bit-or-expr)))
8662 (when (js2-match-token js2-AND)
8663 (setq pn (js2-make-binary js2-AND
8664 pn
8665 'js2-parse-and-expr)))
8666 pn))
8667
8668 (defun js2-parse-bit-or-expr ()
8669 (let ((pn (js2-parse-bit-xor-expr)))
8670 (while (js2-match-token js2-BITOR)
8671 (setq pn (js2-make-binary js2-BITOR
8672 pn
8673 'js2-parse-bit-xor-expr)))
8674 pn))
8675
8676 (defun js2-parse-bit-xor-expr ()
8677 (let ((pn (js2-parse-bit-and-expr)))
8678 (while (js2-match-token js2-BITXOR)
8679 (setq pn (js2-make-binary js2-BITXOR
8680 pn
8681 'js2-parse-bit-and-expr)))
8682 pn))
8683
8684 (defun js2-parse-bit-and-expr ()
8685 (let ((pn (js2-parse-eq-expr)))
8686 (while (js2-match-token js2-BITAND)
8687 (setq pn (js2-make-binary js2-BITAND
8688 pn
8689 'js2-parse-eq-expr)))
8690 pn))
8691
8692 (defconst js2-parse-eq-ops
8693 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8694
8695 (defun js2-parse-eq-expr ()
8696 (let ((pn (js2-parse-rel-expr))
8697 tt)
8698 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8699 (js2-consume-token)
8700 (setq pn (js2-make-binary tt
8701 pn
8702 'js2-parse-rel-expr)))
8703 pn))
8704
8705 (defconst js2-parse-rel-ops
8706 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8707
8708 (defun js2-parse-rel-expr ()
8709 (let ((pn (js2-parse-shift-expr))
8710 (continue t)
8711 tt)
8712 (while continue
8713 (setq tt (js2-peek-token))
8714 (cond
8715 ((and js2-in-for-init (= tt js2-IN))
8716 (setq continue nil))
8717 ((memq tt js2-parse-rel-ops)
8718 (js2-consume-token)
8719 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8720 (t
8721 (setq continue nil))))
8722 pn))
8723
8724 (defconst js2-parse-shift-ops
8725 (list js2-LSH js2-URSH js2-RSH))
8726
8727 (defun js2-parse-shift-expr ()
8728 (let ((pn (js2-parse-add-expr))
8729 tt
8730 (continue t))
8731 (while continue
8732 (setq tt (js2-peek-token))
8733 (if (memq tt js2-parse-shift-ops)
8734 (progn
8735 (js2-consume-token)
8736 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8737 (setq continue nil)))
8738 pn))
8739
8740 (defun js2-parse-add-expr ()
8741 (let ((pn (js2-parse-mul-expr))
8742 tt
8743 (continue t))
8744 (while continue
8745 (setq tt (js2-peek-token))
8746 (if (or (= tt js2-ADD) (= tt js2-SUB))
8747 (progn
8748 (js2-consume-token)
8749 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8750 (setq continue nil)))
8751 pn))
8752
8753 (defconst js2-parse-mul-ops
8754 (list js2-MUL js2-DIV js2-MOD))
8755
8756 (defun js2-parse-mul-expr ()
8757 (let ((pn (js2-parse-unary-expr))
8758 tt
8759 (continue t))
8760 (while continue
8761 (setq tt (js2-peek-token))
8762 (if (memq tt js2-parse-mul-ops)
8763 (progn
8764 (js2-consume-token)
8765 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8766 (setq continue nil)))
8767 pn))
8768
8769 (defsubst js2-make-unary (type parser &rest args)
8770 "Make a unary node of type TYPE.
8771 PARSER is either a node (for postfix operators) or a function to call
8772 to parse the operand (for prefix operators)."
8773 (let* ((pos js2-token-beg)
8774 (postfix (js2-node-p parser))
8775 (expr (if postfix
8776 parser
8777 (apply parser args)))
8778 end
8779 pn)
8780 (if postfix ; e.g. i++
8781 (setq pos (js2-node-pos expr)
8782 end js2-token-end)
8783 (setq end (js2-node-end expr)))
8784 (setq pn (make-js2-unary-node :type type
8785 :pos pos
8786 :len (- end pos)
8787 :operand expr))
8788 (js2-node-add-children pn expr)
8789 pn))
8790
8791 (defconst js2-incrementable-node-types
8792 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8793 "Node types that can be the operand of a ++ or -- operator.")
8794
8795 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8796 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8797 js2-incrementable-node-types)
8798 (js2-report-error (if (= tt js2-INC)
8799 "msg.bad.incr"
8800 "msg.bad.decr")
8801 nil beg (- end beg))))
8802
8803 (defun js2-parse-unary-expr ()
8804 (let ((tt (js2-peek-token))
8805 pn expr beg end)
8806 (cond
8807 ((or (= tt js2-VOID)
8808 (= tt js2-NOT)
8809 (= tt js2-BITNOT)
8810 (= tt js2-TYPEOF))
8811 (js2-consume-token)
8812 (js2-make-unary tt 'js2-parse-unary-expr))
8813 ((= tt js2-ADD)
8814 (js2-consume-token)
8815 ;; Convert to special POS token in decompiler and parse tree
8816 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8817 ((= tt js2-SUB)
8818 (js2-consume-token)
8819 ;; Convert to special NEG token in decompiler and parse tree
8820 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8821 ((or (= tt js2-INC)
8822 (= tt js2-DEC))
8823 (js2-consume-token)
8824 (prog1
8825 (setq beg js2-token-beg
8826 end js2-token-end
8827 expr (js2-make-unary tt 'js2-parse-member-expr t))
8828 (js2-check-bad-inc-dec tt beg end expr)))
8829 ((= tt js2-DELPROP)
8830 (js2-consume-token)
8831 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8832 ((= tt js2-ERROR)
8833 (js2-consume-token)
8834 (make-js2-error-node)) ; try to continue
8835 ((and (= tt js2-LT)
8836 js2-compiler-xml-available)
8837 ;; XML stream encountered in expression.
8838 (js2-consume-token)
8839 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8840 (t
8841 (setq pn (js2-parse-member-expr t)
8842 ;; Don't look across a newline boundary for a postfix incop.
8843 tt (js2-peek-token-or-eol))
8844 (when (or (= tt js2-INC) (= tt js2-DEC))
8845 (js2-consume-token)
8846 (setf expr pn
8847 pn (js2-make-unary tt expr))
8848 (js2-node-set-prop pn 'postfix t)
8849 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8850 pn))))
8851
8852 (defun js2-parse-xml-initializer ()
8853 "Parse an E4X XML initializer.
8854 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8855 Then I'll postprocess the result, depending on whether we're in IDE
8856 mode or codegen mode, and generate the appropriate rewritten AST.
8857 IDE mode uses a rich AST that models the XML structure. Codegen mode
8858 just concatenates everything and makes a new XML or XMLList out of it."
8859 (let ((tt (js2-get-first-xml-token))
8860 pn-xml
8861 pn
8862 expr
8863 kids
8864 expr-pos
8865 (continue t)
8866 (first-token t))
8867 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8868 (js2-report-error "msg.syntax"))
8869 (setq pn-xml (make-js2-xml-node))
8870 (while continue
8871 (if first-token
8872 (setq first-token nil)
8873 (setq tt (js2-get-next-xml-token)))
8874 (cond
8875 ;; js2-XML means we found a {expr} in the XML stream.
8876 ;; The js2-ts-string is the XML up to the left-curly.
8877 ((= tt js2-XML)
8878 (push (make-js2-string-node :pos js2-token-beg
8879 :len (- js2-ts-cursor js2-token-beg))
8880 kids)
8881 (js2-must-match js2-LC "msg.syntax")
8882 (setq expr-pos js2-ts-cursor
8883 expr (if (eq (js2-peek-token) js2-RC)
8884 (make-js2-empty-expr-node :pos expr-pos)
8885 (js2-parse-expr)))
8886 (js2-must-match js2-RC "msg.syntax")
8887 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8888 :len (js2-node-len expr)
8889 :expr expr))
8890 (js2-node-add-children pn expr)
8891 (push pn kids))
8892 ;; a js2-XMLEND token means we hit the final close-tag.
8893 ((= tt js2-XMLEND)
8894 (push (make-js2-string-node :pos js2-token-beg
8895 :len (- js2-ts-cursor js2-token-beg))
8896 kids)
8897 (dolist (kid (nreverse kids))
8898 (js2-block-node-push pn-xml kid))
8899 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8900 (js2-node-pos pn-xml))
8901 continue nil))
8902 (t
8903 (js2-report-error "msg.syntax")
8904 (setq continue nil))))
8905 pn-xml))
8906
8907
8908 (defun js2-parse-argument-list ()
8909 "Parse an argument list and return it as a lisp list of nodes.
8910 Returns the list in reverse order. Consumes the right-paren token."
8911 (let (result)
8912 (unless (js2-match-token js2-RP)
8913 (loop do
8914 (if (= (js2-peek-token) js2-YIELD)
8915 (js2-report-error "msg.yield.parenthesized"))
8916 (push (js2-parse-assign-expr) result)
8917 while
8918 (js2-match-token js2-COMMA))
8919 (js2-must-match js2-RP "msg.no.paren.arg")
8920 result)))
8921
8922 (defun js2-parse-member-expr (&optional allow-call-syntax)
8923 (let ((tt (js2-peek-token))
8924 pn
8925 pos
8926 target
8927 args
8928 beg
8929 end
8930 init
8931 tail)
8932 (if (/= tt js2-NEW)
8933 (setq pn (js2-parse-primary-expr))
8934 ;; parse a 'new' expression
8935 (js2-consume-token)
8936 (setq pos js2-token-beg
8937 beg pos
8938 target (js2-parse-member-expr)
8939 end (js2-node-end target)
8940 pn (make-js2-new-node :pos pos
8941 :target target
8942 :len (- end pos)))
8943 (js2-node-add-children pn target)
8944 (when (js2-match-token js2-LP)
8945 ;; Add the arguments to pn, if any are supplied.
8946 (setf beg pos ; start of "new" keyword
8947 pos js2-token-beg
8948 args (nreverse (js2-parse-argument-list))
8949 (js2-new-node-args pn) args
8950 end js2-token-end
8951 (js2-new-node-lp pn) (- pos beg)
8952 (js2-new-node-rp pn) (- end 1 beg))
8953 (apply #'js2-node-add-children pn args))
8954 (when (and js2-allow-rhino-new-expr-initializer
8955 (js2-match-token js2-LC))
8956 (setf init (js2-parse-object-literal)
8957 end (js2-node-end init)
8958 (js2-new-node-initializer pn) init)
8959 (js2-node-add-children pn init))
8960 (setf (js2-node-len pn) (- end beg))) ; end outer if
8961 (js2-parse-member-expr-tail allow-call-syntax pn)))
8962
8963 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8964 "Parse a chain of property/array accesses or function calls.
8965 Includes parsing for E4X operators like `..' and `.@'.
8966 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8967 Returns an expression tree that includes PN, the parent node."
8968 (let ((beg (js2-node-pos pn))
8969 tt
8970 (continue t))
8971 (while continue
8972 (setq tt (js2-peek-token))
8973 (cond
8974 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8975 (setq pn (js2-parse-property-access tt pn)))
8976 ((= tt js2-DOTQUERY)
8977 (setq pn (js2-parse-dot-query pn)))
8978 ((= tt js2-LB)
8979 (setq pn (js2-parse-element-get pn)))
8980 ((= tt js2-LP)
8981 (if allow-call-syntax
8982 (setq pn (js2-parse-function-call pn))
8983 (setq continue nil)))
8984 (t
8985 (setq continue nil))))
8986 (if (>= js2-highlight-level 2)
8987 (js2-parse-highlight-member-expr-node pn))
8988 pn))
8989
8990 (defun js2-parse-dot-query (pn)
8991 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8992 Last token parsed must be `js2-DOTQUERY'."
8993 (let ((pos (js2-node-pos pn))
8994 op-pos
8995 expr
8996 end)
8997 (js2-consume-token)
8998 (js2-must-have-xml)
8999 (js2-set-requires-activation)
9000 (setq op-pos js2-token-beg
9001 expr (js2-parse-expr)
9002 end (js2-node-end expr)
9003 pn (make-js2-xml-dot-query-node :left pn
9004 :pos pos
9005 :op-pos op-pos
9006 :right expr))
9007 (js2-node-add-children pn
9008 (js2-xml-dot-query-node-left pn)
9009 (js2-xml-dot-query-node-right pn))
9010 (if (js2-must-match js2-RP "msg.no.paren")
9011 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9012 end js2-token-end))
9013 (setf (js2-node-len pn) (- end pos))
9014 pn))
9015
9016 (defun js2-parse-element-get (pn)
9017 "Parse an element-get expression, e.g. foo[bar].
9018 Last token parsed must be `js2-RB'."
9019 (let ((lb js2-token-beg)
9020 (pos (js2-node-pos pn))
9021 rb
9022 expr)
9023 (js2-consume-token)
9024 (setq expr (js2-parse-expr))
9025 (if (js2-must-match js2-RB "msg.no.bracket.index")
9026 (setq rb js2-token-beg))
9027 (setq pn (make-js2-elem-get-node :target pn
9028 :pos pos
9029 :element expr
9030 :lb (js2-relpos lb pos)
9031 :rb (js2-relpos rb pos)
9032 :len (- js2-token-end pos)))
9033 (js2-node-add-children pn
9034 (js2-elem-get-node-target pn)
9035 (js2-elem-get-node-element pn))
9036 pn))
9037
9038 (defun js2-parse-function-call (pn)
9039 (let (args
9040 (pos (js2-node-pos pn)))
9041 (js2-consume-token)
9042 (setq pn (make-js2-call-node :pos pos
9043 :target pn
9044 :lp (- js2-token-beg pos)))
9045 (js2-node-add-children pn (js2-call-node-target pn))
9046 ;; Add the arguments to pn, if any are supplied.
9047 (setf args (nreverse (js2-parse-argument-list))
9048 (js2-call-node-rp pn) (- js2-token-beg pos)
9049 (js2-call-node-args pn) args)
9050 (apply #'js2-node-add-children pn args)
9051 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9052 pn))
9053
9054 (defun js2-parse-property-access (tt pn)
9055 "Parse a property access, XML descendants access, or XML attr access."
9056 (let ((member-type-flags 0)
9057 (dot-pos js2-token-beg)
9058 (dot-len (if (= tt js2-DOTDOT) 2 1))
9059 name
9060 ref ; right side of . or .. operator
9061 result)
9062 (js2-consume-token)
9063 (when (= tt js2-DOTDOT)
9064 (js2-must-have-xml)
9065 (setq member-type-flags js2-descendants-flag))
9066 (if (not js2-compiler-xml-available)
9067 (progn
9068 (js2-must-match-prop-name "msg.no.name.after.dot")
9069 (setq name (js2-create-name-node t js2-GETPROP)
9070 result (make-js2-prop-get-node :left pn
9071 :pos js2-token-beg
9072 :right name
9073 :len (- js2-token-end
9074 js2-token-beg)))
9075 (js2-node-add-children result pn name)
9076 result)
9077 ;; otherwise look for XML operators
9078 (setf result (if (= tt js2-DOT)
9079 (make-js2-prop-get-node)
9080 (make-js2-infix-node :type js2-DOTDOT))
9081 (js2-node-pos result) (js2-node-pos pn)
9082 (js2-infix-node-op-pos result) dot-pos
9083 (js2-infix-node-left result) pn ; do this after setting position
9084 tt (js2-next-token))
9085 (cond
9086 ;; needed for generator.throw()
9087 ((= tt js2-THROW)
9088 (js2-save-name-token-data js2-token-beg "throw")
9089 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9090 ;; handles: name, ns::name, ns::*, ns::[expr]
9091 ((js2-valid-prop-name-token tt)
9092 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9093 ;; handles: *, *::name, *::*, *::[expr]
9094 ((= tt js2-MUL)
9095 (js2-save-name-token-data js2-token-beg "*")
9096 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9097 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9098 ((= tt js2-XMLATTR)
9099 (setq result (js2-parse-attribute-access)))
9100 (t
9101 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9102 (if ref
9103 (setf (js2-node-len result) (- (js2-node-end ref)
9104 (js2-node-pos result))
9105 (js2-infix-node-right result) ref))
9106 (if (js2-infix-node-p result)
9107 (js2-node-add-children result
9108 (js2-infix-node-left result)
9109 (js2-infix-node-right result)))
9110 result)))
9111
9112 (defun js2-parse-attribute-access ()
9113 "Parse an E4X XML attribute expression.
9114 This includes expressions of the forms:
9115
9116 @attr @ns::attr @ns::*
9117 @* @*::attr @*::*
9118 @[expr] @*::[expr] @ns::[expr]
9119
9120 Called if we peeked an '@' token."
9121 (let ((tt (js2-next-token))
9122 (at-pos js2-token-beg))
9123 (cond
9124 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9125 ((js2-valid-prop-name-token tt)
9126 (js2-parse-property-name at-pos js2-ts-string 0))
9127 ;; handles: @*, @*::name, @*::*, @*::[expr]
9128 ((= tt js2-MUL)
9129 (js2-save-name-token-data js2-token-beg "*")
9130 (js2-parse-property-name js2-token-beg "*" 0))
9131 ;; handles @[expr]
9132 ((= tt js2-LB)
9133 (js2-parse-xml-elem-ref at-pos))
9134 (t
9135 (js2-report-error "msg.no.name.after.xmlAttr")
9136 ;; Avoid cascaded errors that happen if we make an error node here.
9137 (js2-save-name-token-data js2-token-beg "")
9138 (js2-parse-property-name js2-token-beg "" 0)))))
9139
9140 (defun js2-parse-property-name (at-pos s member-type-flags)
9141 "Check if :: follows name in which case it becomes qualified name.
9142
9143 AT-POS is a natural number if we just read an '@' token, else nil.
9144 S is the name or string that was matched: an identifier, 'throw' or '*'.
9145 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9146
9147 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9148 operator, or the name is followed by ::. For a plain name, returns a
9149 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9150 (let ((pos (or at-pos js2-token-beg))
9151 colon-pos
9152 (name (js2-create-name-node t js2-current-token))
9153 ns
9154 tt
9155 ref
9156 pn)
9157 (catch 'return
9158 (when (js2-match-token js2-COLONCOLON)
9159 (setq ns name
9160 colon-pos js2-token-beg
9161 tt (js2-next-token))
9162 (cond
9163 ;; handles name::name
9164 ((js2-valid-prop-name-token tt)
9165 (setq name (js2-create-name-node)))
9166 ;; handles name::*
9167 ((= tt js2-MUL)
9168 (js2-save-name-token-data js2-token-beg "*")
9169 (setq name (js2-create-name-node)))
9170 ;; handles name::[expr]
9171 ((= tt js2-LB)
9172 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9173 (t
9174 (js2-report-error "msg.no.name.after.coloncolon"))))
9175 (if (and (null ns) (zerop member-type-flags))
9176 name
9177 (prog1
9178 (setq pn
9179 (make-js2-xml-prop-ref-node :pos pos
9180 :len (- (js2-node-end name) pos)
9181 :at-pos at-pos
9182 :colon-pos colon-pos
9183 :propname name))
9184 (js2-node-add-children pn name))))))
9185
9186 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9187 "Parse the [expr] portion of an xml element reference.
9188 For instance, @[expr], @*::[expr], or ns::[expr]."
9189 (let* ((lb js2-token-beg)
9190 (pos (or at-pos lb))
9191 rb
9192 (expr (js2-parse-expr))
9193 (end (js2-node-end expr))
9194 pn)
9195 (if (js2-must-match js2-RB "msg.no.bracket.index")
9196 (setq rb js2-token-beg
9197 end js2-token-end))
9198 (prog1
9199 (setq pn
9200 (make-js2-xml-elem-ref-node :pos pos
9201 :len (- end pos)
9202 :namespace namespace
9203 :colon-pos colon-pos
9204 :at-pos at-pos
9205 :expr expr
9206 :lb (js2-relpos lb pos)
9207 :rb (js2-relpos rb pos)))
9208 (js2-node-add-children pn namespace expr))))
9209
9210 (defsubst js2-parse-primary-expr-lhs ()
9211 (let ((js2-is-in-lhs t))
9212 (js2-parse-primary-expr)))
9213
9214 (defun js2-parse-primary-expr ()
9215 "Parses a literal (leaf) expression of some sort.
9216 Includes complex literals such as functions, object-literals,
9217 array-literals, array comprehensions and regular expressions."
9218 (let ((tt-flagged (js2-next-flagged-token))
9219 pn ; parent node (usually return value)
9220 tt
9221 px-pos ; paren-expr pos
9222 len
9223 flags ; regexp flags
9224 expr)
9225 (setq tt js2-current-token)
9226 (cond
9227 ((= tt js2-FUNCTION)
9228 (js2-parse-function 'FUNCTION_EXPRESSION))
9229 ((= tt js2-LB)
9230 (js2-parse-array-literal))
9231 ((= tt js2-LC)
9232 (js2-parse-object-literal))
9233 ((= tt js2-LET)
9234 (js2-parse-let js2-token-beg))
9235 ((= tt js2-LP)
9236 (setq px-pos js2-token-beg
9237 expr (js2-parse-expr))
9238 (js2-must-match js2-RP "msg.no.paren")
9239 (setq pn (make-js2-paren-node :pos px-pos
9240 :expr expr
9241 :len (- js2-token-end px-pos)))
9242 (js2-node-add-children pn (js2-paren-node-expr pn))
9243 pn)
9244 ((= tt js2-XMLATTR)
9245 (js2-must-have-xml)
9246 (js2-parse-attribute-access))
9247 ((= tt js2-NAME)
9248 (js2-parse-name tt-flagged tt))
9249 ((= tt js2-NUMBER)
9250 (make-js2-number-node))
9251 ((= tt js2-STRING)
9252 (prog1
9253 (make-js2-string-node)
9254 (js2-record-face 'font-lock-string-face)))
9255 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9256 ;; Got / or /= which in this context means a regexp literal
9257 (setq px-pos js2-token-beg)
9258 (js2-read-regexp tt)
9259 (setq flags js2-ts-regexp-flags
9260 js2-ts-regexp-flags nil)
9261 (prog1
9262 (make-js2-regexp-node :pos px-pos
9263 :len (- js2-ts-cursor px-pos)
9264 :value js2-ts-string
9265 :flags flags)
9266 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9267 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9268 ((or (= tt js2-NULL)
9269 (= tt js2-THIS)
9270 (= tt js2-FALSE)
9271 (= tt js2-TRUE))
9272 (make-js2-keyword-node :type tt))
9273 ((= tt js2-RESERVED)
9274 (js2-report-error "msg.reserved.id")
9275 (make-js2-name-node))
9276 ((= tt js2-ERROR)
9277 ;; the scanner or one of its subroutines reported the error.
9278 (make-js2-error-node))
9279 ((= tt js2-EOF)
9280 (setq px-pos (point-at-bol)
9281 len (- js2-ts-cursor px-pos))
9282 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9283 (make-js2-error-node :pos px-pos :len len))
9284 (t
9285 (js2-report-error "msg.syntax")
9286 (make-js2-error-node)))))
9287
9288 (defun js2-parse-name (tt-flagged tt)
9289 (let ((name js2-ts-string)
9290 (name-pos js2-token-beg)
9291 node)
9292 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9293 (= (js2-peek-token) js2-COLON))
9294 (prog1
9295 ;; Do not consume colon, it is used as unwind indicator
9296 ;; to return to statementHelper.
9297 (make-js2-label-node :pos name-pos
9298 :len (- js2-token-end name-pos)
9299 :name name)
9300 (js2-set-face name-pos
9301 js2-token-end
9302 'font-lock-variable-name-face 'record))
9303 ;; Otherwise not a label, just a name. Unfortunately peeking
9304 ;; the next token to check for a colon has biffed js2-token-beg
9305 ;; and js2-token-end. We store the name's bounds in buffer vars
9306 ;; and `js2-create-name-node' uses them.
9307 (js2-save-name-token-data name-pos name)
9308 (setq node (if js2-compiler-xml-available
9309 (js2-parse-property-name nil name 0)
9310 (js2-create-name-node 'check-activation)))
9311 (if js2-highlight-external-variables
9312 (js2-record-name-node node))
9313 node)))
9314
9315 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9316 (js2-add-strict-warning
9317 msg nil
9318 ;; back up from comma to beginning of line or array/objlit
9319 (max (if elems
9320 (js2-node-pos (car elems))
9321 pos)
9322 (save-excursion
9323 (goto-char comma-pos)
9324 (back-to-indentation)
9325 (point)))
9326 comma-pos))
9327
9328 (defun js2-parse-array-literal ()
9329 (let ((pos js2-token-beg)
9330 (end js2-token-end)
9331 (after-lb-or-comma t)
9332 after-comma
9333 tt
9334 elems
9335 pn
9336 (continue t))
9337 (unless js2-is-in-lhs
9338 (js2-push-scope (make-js2-scope))) ; for array comp
9339 (while continue
9340 (setq tt (js2-peek-token))
9341 (cond
9342 ;; comma
9343 ((= tt js2-COMMA)
9344 (js2-consume-token)
9345 (setq after-comma js2-token-end)
9346 (if (not after-lb-or-comma)
9347 (setq after-lb-or-comma t)
9348 (push nil elems)))
9349 ;; end of array
9350 ((or (= tt js2-RB)
9351 (= tt js2-EOF)) ; prevent infinite loop
9352 (if (= tt js2-EOF)
9353 (js2-report-error "msg.no.bracket.arg" nil pos)
9354 (js2-consume-token))
9355 (setq continue nil
9356 end js2-token-end
9357 pn (make-js2-array-node :pos pos
9358 :len (- js2-ts-cursor pos)
9359 :elems (nreverse elems)))
9360 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9361 (when after-comma
9362 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9363 pos elems after-comma)))
9364 ;; destructuring binding
9365 (js2-is-in-lhs
9366 (push (if (or (= tt js2-LC)
9367 (= tt js2-LB)
9368 (= tt js2-NAME))
9369 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9370 (js2-parse-primary-expr-lhs)
9371 ;; invalid pattern
9372 (js2-consume-token)
9373 (js2-report-error "msg.bad.var")
9374 (make-js2-error-node))
9375 elems)
9376 (setq after-lb-or-comma nil
9377 after-comma nil))
9378 ;; array comp
9379 ((and (>= js2-language-version 170)
9380 (= tt js2-FOR) ; check for array comprehension
9381 (not after-lb-or-comma) ; "for" can't follow a comma
9382 elems ; must have at least 1 element
9383 (not (cdr elems))) ; but no 2nd element
9384 (setf continue nil
9385 pn (js2-parse-array-comprehension (car elems) pos)))
9386
9387 ;; another element
9388 (t
9389 (unless after-lb-or-comma
9390 (js2-report-error "msg.no.bracket.arg"))
9391 (push (js2-parse-assign-expr) elems)
9392 (setq after-lb-or-comma nil
9393 after-comma nil))))
9394 (unless js2-is-in-lhs
9395 (js2-pop-scope))
9396 pn))
9397
9398 (defun js2-parse-array-comprehension (expr pos)
9399 "Parse a JavaScript 1.7 Array Comprehension.
9400 EXPR is the first expression after the opening left-bracket.
9401 POS is the beginning of the LB token preceding EXPR.
9402 We should have just parsed the 'for' keyword before calling this function."
9403 (let (loops
9404 loop
9405 first
9406 prev
9407 filter
9408 if-pos
9409 result)
9410 (while (= (js2-peek-token) js2-FOR)
9411 (let ((prev (car loops))) ; rearrange scope chain
9412 (push (setq loop (js2-parse-array-comp-loop)) loops)
9413 (if prev ; each loop is parent scope to the next one
9414 (setf (js2-scope-parent-scope loop) prev)
9415 ; first loop takes expr scope's parent
9416 (setf (js2-scope-parent-scope (setq first loop))
9417 (js2-scope-parent-scope js2-current-scope)))))
9418 ;; set expr scope's parent to the last loop
9419 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9420 (when (= (js2-peek-token) js2-IF)
9421 (js2-consume-token)
9422 (setq if-pos (- js2-token-beg pos) ; relative
9423 filter (js2-parse-condition)))
9424 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9425 (setq result (make-js2-array-comp-node :pos pos
9426 :len (- js2-ts-cursor pos)
9427 :result expr
9428 :loops (nreverse loops)
9429 :filter (car filter)
9430 :lp (js2-relpos (second filter) pos)
9431 :rp (js2-relpos (third filter) pos)
9432 :if-pos if-pos))
9433 (apply #'js2-node-add-children result expr (car filter)
9434 (js2-array-comp-node-loops result))
9435 (setq js2-current-scope first) ; pop to the first loop
9436 result))
9437
9438 (defun js2-parse-array-comp-loop ()
9439 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9440 Last token peeked should be the initial FOR."
9441 (let ((pos js2-token-beg)
9442 (pn (make-js2-array-comp-loop-node))
9443 tt
9444 iter
9445 obj
9446 foreach-p
9447 in-pos
9448 each-pos
9449 lp
9450 rp)
9451 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9452 (js2-push-scope pn)
9453 (unwind-protect
9454 (progn
9455 (when (js2-match-token js2-NAME)
9456 (if (string= js2-ts-string "each")
9457 (progn
9458 (setq foreach-p t
9459 each-pos (- js2-token-beg pos)) ; relative
9460 (js2-record-face 'font-lock-keyword-face))
9461 (js2-report-error "msg.no.paren.for")))
9462 (if (js2-must-match js2-LP "msg.no.paren.for")
9463 (setq lp (- js2-token-beg pos)))
9464 (setq tt (js2-peek-token))
9465 (cond
9466 ((or (= tt js2-LB)
9467 (= tt js2-LC))
9468 ;; handle destructuring assignment
9469 (setq iter (js2-parse-primary-expr-lhs))
9470 (js2-define-destruct-symbols iter js2-LET
9471 'font-lock-variable-name-face t))
9472 ((js2-valid-prop-name-token tt)
9473 (js2-consume-token)
9474 (setq iter (js2-create-name-node)))
9475 (t
9476 (js2-report-error "msg.bad.var")))
9477 ;; Define as a let since we want the scope of the variable to
9478 ;; be restricted to the array comprehension
9479 (if (js2-name-node-p iter)
9480 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9481 (if (js2-must-match js2-IN "msg.in.after.for.name")
9482 (setq in-pos (- js2-token-beg pos)))
9483 (setq obj (js2-parse-expr))
9484 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9485 (setq rp (- js2-token-beg pos)))
9486 (setf (js2-node-pos pn) pos
9487 (js2-node-len pn) (- js2-ts-cursor pos)
9488 (js2-array-comp-loop-node-iterator pn) iter
9489 (js2-array-comp-loop-node-object pn) obj
9490 (js2-array-comp-loop-node-in-pos pn) in-pos
9491 (js2-array-comp-loop-node-each-pos pn) each-pos
9492 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9493 (js2-array-comp-loop-node-lp pn) lp
9494 (js2-array-comp-loop-node-rp pn) rp)
9495 (js2-node-add-children pn iter obj))
9496 (js2-pop-scope))
9497 pn))
9498
9499 (defun js2-parse-object-literal ()
9500 (let ((pos js2-token-beg)
9501 tt
9502 elems
9503 result
9504 after-comma
9505 (continue t))
9506 (while continue
9507 (setq tt (js2-peek-token))
9508 (cond
9509 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9510 ((or (js2-valid-prop-name-token tt)
9511 (= tt js2-STRING))
9512 (setq after-comma nil
9513 result (js2-parse-named-prop tt))
9514 (if (and (null result)
9515 (not js2-recover-from-parse-errors))
9516 (setq continue nil)
9517 (push result elems)))
9518 ;; {12: x} or {10.7: x}
9519 ((= tt js2-NUMBER)
9520 (js2-consume-token)
9521 (setq after-comma nil)
9522 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9523 ;; trailing comma
9524 ((= tt js2-RC)
9525 (setq continue nil)
9526 (if after-comma
9527 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9528 pos elems after-comma)))
9529 (t
9530 (js2-report-error "msg.bad.prop")
9531 (unless js2-recover-from-parse-errors
9532 (setq continue nil)))) ; end switch
9533 (if (js2-match-token js2-COMMA)
9534 (setq after-comma js2-token-end)
9535 (setq continue nil))) ; end loop
9536 (js2-must-match js2-RC "msg.no.brace.prop")
9537 (setq result (make-js2-object-node :pos pos
9538 :len (- js2-ts-cursor pos)
9539 :elems (nreverse elems)))
9540 (apply #'js2-node-add-children result (js2-object-node-elems result))
9541 result))
9542
9543 (defun js2-parse-named-prop (tt)
9544 "Parse a name, string, or getter/setter object property.
9545 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9546 (js2-consume-token)
9547 (let ((string-prop (and (= tt js2-STRING)
9548 (make-js2-string-node)))
9549 expr
9550 (ppos js2-token-beg)
9551 (pend js2-token-end)
9552 (name (js2-create-name-node))
9553 (prop js2-ts-string))
9554 (cond
9555 ;; getter/setter prop
9556 ((and (= tt js2-NAME)
9557 (= (js2-peek-token) js2-NAME)
9558 (or (string= prop "get")
9559 (string= prop "set")))
9560 (js2-consume-token)
9561 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9562 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9563 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9564 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9565 ;; abbreviated destructuring bind e.g., {a, b} = c;
9566 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9567 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9568 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9569 ;; assignment but it's difficult because it requires looking ahead of expression.
9570 ((and js2-is-in-lhs
9571 (= tt js2-NAME)
9572 (let ((ctk (js2-peek-token)))
9573 (or (= ctk js2-COMMA)
9574 (= ctk js2-RC)
9575 (js2-valid-prop-name-token ctk))))
9576 name)
9577 ;; regular prop
9578 (t
9579 (prog1
9580 (setq expr (js2-parse-plain-property (or string-prop name)))
9581 (js2-set-face ppos pend
9582 (if (js2-function-node-p
9583 (js2-object-prop-node-right expr))
9584 'font-lock-function-name-face
9585 'font-lock-variable-name-face)
9586 'record))))))
9587
9588 (defun js2-parse-plain-property (prop)
9589 "Parse a non-getter/setter property in an object literal.
9590 PROP is the node representing the property: a number, name or string."
9591 (js2-must-match js2-COLON "msg.no.colon.prop")
9592 (let* ((pos (js2-node-pos prop))
9593 (colon (- js2-token-beg pos))
9594 (expr (js2-parse-assign-expr))
9595 (result (make-js2-object-prop-node
9596 :pos pos
9597 ;; don't include last consumed token in length
9598 :len (- (+ (js2-node-pos expr)
9599 (js2-node-len expr))
9600 pos)
9601 :left prop
9602 :right expr
9603 :op-pos colon)))
9604 (js2-node-add-children result prop expr)
9605 result))
9606
9607 (defun js2-parse-getter-setter-prop (pos prop get-p)
9608 "Parse getter or setter property in an object literal.
9609 JavaScript syntax is:
9610
9611 { get foo() {...}, set foo(x) {...} }
9612
9613 and expression closure style is also supported
9614
9615 { get foo() x, set foo(x) _x = x }
9616
9617 POS is the start position of the `get' or `set' keyword.
9618 PROP is the `js2-name-node' representing the property name.
9619 GET-P is non-nil if the keyword was `get'."
9620 (let ((type (if get-p js2-GET js2-SET))
9621 result
9622 end
9623 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9624 ;; it has to be an anonymous function, as we already parsed the name
9625 (if (/= (js2-node-type fn) js2-FUNCTION)
9626 (js2-report-error "msg.bad.prop")
9627 (if (plusp (length (js2-function-name fn)))
9628 (js2-report-error "msg.bad.prop")))
9629 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9630 (setq end (js2-node-end fn)
9631 result (make-js2-getter-setter-node :type type
9632 :pos pos
9633 :len (- end pos)
9634 :left prop
9635 :right fn))
9636 (js2-node-add-children result prop fn)
9637 result))
9638
9639 (defun js2-create-name-node (&optional check-activation-p token)
9640 "Create a name node using the token info from last scanned name.
9641 In some cases we need to either synthesize a name node, or we lost
9642 the name token information by peeking. If the TOKEN parameter is
9643 not `js2-NAME', then we use the token info saved in instance vars."
9644 (let ((beg js2-token-beg)
9645 (s js2-ts-string)
9646 name)
9647 (when (/= js2-current-token js2-NAME)
9648 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9649 s js2-prev-name-token-string
9650 js2-prev-name-token-start nil
9651 js2-prev-name-token-string nil))
9652 (setq name (make-js2-name-node :pos beg
9653 :name s
9654 :len (length s)))
9655 (if check-activation-p
9656 (js2-check-activation-name s (or token js2-NAME)))
9657 name))
9658
9659 ;;; Indentation support
9660
9661 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9662 ;; Karl cleverly deduces that the desired indentation level is often a
9663 ;; function of paren/bracket/brace nesting depth, which can be determined
9664 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9665 ;; then does some equally clever checks to see if we're in the context of a
9666 ;; substatement of a possibly braceless statement keyword such as if, while,
9667 ;; or finally. This approach yields pretty good results.
9668
9669 ;; The indenter is often "wrong", however, and needs to be overridden.
9670 ;; The right long-term solution is probably to emulate (or integrate
9671 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9672 ;; parse tree from `js2-parse' is present, which is not true at the
9673 ;; moment the user is typing, computing indentation is still thousands
9674 ;; of lines of code to handle every possible syntactic edge case.
9675
9676 ;; In the meantime, the compromise solution is that we offer a "bounce
9677 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9678 ;; current line indent among various likely guess points. This approach
9679 ;; is far from perfect, but should at least make it slightly easier to
9680 ;; move the line towards its desired indentation when manually
9681 ;; overriding Karl's heuristic nesting guesser.
9682
9683 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9684 ;; extensions such as `let' and Array comprehensions. Major kudos to
9685 ;; Karl for coming up with the initial approach, which packs a lot of
9686 ;; punch for so little code.
9687
9688 (defconst js-possibly-braceless-keyword-re
9689 (regexp-opt
9690 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9691 'words)
9692 "Regular expression matching keywords that are optionally
9693 followed by an opening brace.")
9694
9695 (defconst js-possibly-braceless-keywords-re
9696 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9697 "Regular expression which matches the keywords which are consist of more than 2 words
9698 like 'if else' and 'for each', and optionally followed by an opening brace.")
9699
9700 (defconst js-indent-operator-re
9701 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9702 (regexp-opt '("in" "instanceof") 'words))
9703 "Regular expression matching operators that affect indentation
9704 of continued expressions.")
9705
9706 ;; This function has horrible results if you're typing an array
9707 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9708 ;; in conjunction with electric-indent, so just disabling it.
9709 (defsubst js2-code-at-bol-p ()
9710 "Return t if the first character on line is non-whitespace."
9711 nil)
9712
9713 (defun js2-insert-and-indent (key)
9714 "Run command bound to key and indent current line. Runs the command
9715 bound to KEY in the global keymap and indents the current line."
9716 (interactive (list (this-command-keys)))
9717 (let ((cmd (lookup-key (current-global-map) key)))
9718 (if (commandp cmd)
9719 (call-interactively cmd)))
9720 ;; don't do the electric keys inside comments or strings,
9721 ;; and don't do bounce-indent with them.
9722 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9723 (js2-bounce-indent-p (js2-code-at-bol-p)))
9724 (unless (or (nth 3 parse-state)
9725 (nth 4 parse-state))
9726 (indent-according-to-mode))))
9727
9728 (defun js-re-search-forward-inner (regexp &optional bound count)
9729 "Auxiliary function for `js-re-search-forward'."
9730 (let ((parse)
9731 (saved-point (point-min)))
9732 (while (> count 0)
9733 (re-search-forward regexp bound)
9734 (setq parse (parse-partial-sexp saved-point (point)))
9735 (cond ((nth 3 parse)
9736 (re-search-forward
9737 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9738 (save-excursion (end-of-line) (point)) t))
9739 ((nth 7 parse)
9740 (forward-line))
9741 ((or (nth 4 parse)
9742 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9743 (re-search-forward "\\*/"))
9744 (t
9745 (setq count (1- count))))
9746 (setq saved-point (point))))
9747 (point))
9748
9749 (defun js-re-search-forward (regexp &optional bound noerror count)
9750 "Search forward but ignore strings and comments. Invokes
9751 `re-search-forward' but treats the buffer as if strings and
9752 comments have been removed."
9753 (let ((saved-point (point))
9754 (search-expr
9755 (cond ((null count)
9756 '(js-re-search-forward-inner regexp bound 1))
9757 ((< count 0)
9758 '(js-re-search-backward-inner regexp bound (- count)))
9759 ((> count 0)
9760 '(js-re-search-forward-inner regexp bound count)))))
9761 (condition-case err
9762 (eval search-expr)
9763 (search-failed
9764 (goto-char saved-point)
9765 (unless noerror
9766 (error (error-message-string err)))))))
9767
9768 (defun js-re-search-backward-inner (regexp &optional bound count)
9769 "Auxiliary function for `js-re-search-backward'."
9770 (let ((parse)
9771 (saved-point (point-min)))
9772 (while (> count 0)
9773 (re-search-backward regexp bound)
9774 (setq parse (parse-partial-sexp saved-point (point)))
9775 (cond ((nth 3 parse)
9776 (re-search-backward
9777 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9778 (save-excursion (beginning-of-line) (point)) t))
9779 ((nth 7 parse)
9780 (goto-char (nth 8 parse)))
9781 ((or (nth 4 parse)
9782 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9783 (re-search-backward "/\\*"))
9784 (t
9785 (setq count (1- count))))))
9786 (point))
9787
9788 (defun js-re-search-backward (regexp &optional bound noerror count)
9789 "Search backward but ignore strings and comments. Invokes
9790 `re-search-backward' but treats the buffer as if strings and
9791 comments have been removed."
9792 (let ((saved-point (point))
9793 (search-expr
9794 (cond ((null count)
9795 '(js-re-search-backward-inner regexp bound 1))
9796 ((< count 0)
9797 '(js-re-search-forward-inner regexp bound (- count)))
9798 ((> count 0)
9799 '(js-re-search-backward-inner regexp bound count)))))
9800 (condition-case err
9801 (eval search-expr)
9802 (search-failed
9803 (goto-char saved-point)
9804 (unless noerror
9805 (error (error-message-string err)))))))
9806
9807 (defun js-looking-at-operator-p ()
9808 "Return non-nil if text after point is an operator (that is not
9809 a comma)."
9810 (save-match-data
9811 (and (looking-at js-indent-operator-re)
9812 (or (not (looking-at ":"))
9813 (save-excursion
9814 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9815 (looking-at "?")))))))
9816
9817 (defun js-continued-expression-p ()
9818 "Returns non-nil if the current line continues an expression."
9819 (save-excursion
9820 (back-to-indentation)
9821 (or (js-looking-at-operator-p)
9822 ;; comment
9823 (and (js-re-search-backward "\n" nil t)
9824 (progn
9825 (skip-chars-backward " \t")
9826 (backward-char)
9827 (and (js-looking-at-operator-p)
9828 (and (progn (backward-char)
9829 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9830
9831 (defun js-end-of-do-while-loop-p ()
9832 "Returns non-nil if word after point is `while' of a do-while
9833 statement, else returns nil. A braceless do-while statement
9834 spanning several lines requires that the start of the loop is
9835 indented to the same column as the current line."
9836 (interactive)
9837 (save-excursion
9838 (save-match-data
9839 (when (looking-at "\\s-*\\<while\\>")
9840 (if (save-excursion
9841 (skip-chars-backward "[ \t\n]*}")
9842 (looking-at "[ \t\n]*}"))
9843 (save-excursion
9844 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9845 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9846 (or (looking-at "\\<do\\>")
9847 (let ((saved-indent (current-indentation)))
9848 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9849 (/= (current-indentation) saved-indent)))
9850 (and (looking-at "[ \t]*\\<do\\>")
9851 (not (js-re-search-forward
9852 "\\<while\\>" (point-at-eol) t))
9853 (= (current-indentation) saved-indent)))))))))
9854
9855 (defun js-get-multiline-declaration-offset ()
9856 "Returns offset (> 0) if the current line is part of
9857 multi-line variable declaration like below example, and
9858 returns 0 otherwise.
9859
9860 var a = 10,
9861 b = 20,
9862 c = 30;
9863
9864 "
9865 (let* ((node (js2-node-at-point))
9866 (pnode (and node (js2-node-parent node)))
9867 (pnode-type (and pnode (js2-node-type pnode))))
9868 (if (and node
9869 (= js2-NAME (js2-node-type node))
9870 (or
9871 (= js2-VAR pnode-type)
9872 (= js2-LET pnode-type)
9873 (= js2-CONST pnode-type)))
9874 (if (= js2-CONST pnode-type)
9875 6
9876 4)
9877 0)))
9878
9879 (defun js-ctrl-statement-indentation ()
9880 "Returns the proper indentation of the current line if it
9881 starts the body of a control statement without braces, else
9882 returns nil."
9883 (let (forward-sexp-function) ; temporarily unbind it
9884 (save-excursion
9885 (back-to-indentation)
9886 (when (save-excursion
9887 (and (not (js2-same-line (point-min)))
9888 (not (looking-at "{"))
9889 (js-re-search-backward "[[:graph:]]" nil t)
9890 (not (looking-at "[{([]"))
9891 (progn
9892 (forward-char)
9893 ;; scan-sexps sometimes throws an error
9894 (ignore-errors (backward-sexp))
9895 (when (looking-at "(") (backward-word 1))
9896 (and (save-excursion
9897 (skip-chars-backward " \t}" (point-at-bol))
9898 (or (bolp)
9899 (and (backward-word 1)
9900 (skip-chars-backward " \t}" (point-at-bol))
9901 (bolp)
9902 (looking-at js-possibly-braceless-keywords-re))))
9903 (looking-at js-possibly-braceless-keyword-re)
9904 (not (js-end-of-do-while-loop-p))))))
9905 (save-excursion
9906 (goto-char (match-beginning 0))
9907 (+ (current-indentation) js2-basic-offset))))))
9908
9909 (defun js2-indent-in-array-comp (parse-status)
9910 "Return non-nil if we think we're in an array comprehension.
9911 In particular, return the buffer position of the first `for' kwd."
9912 (let ((end (point)))
9913 (when (nth 1 parse-status)
9914 (save-excursion
9915 (goto-char (nth 1 parse-status))
9916 (when (looking-at "\\[")
9917 (forward-char 1)
9918 (js2-forward-sws)
9919 (if (looking-at "[[{]")
9920 (let (forward-sexp-function) ; use lisp version
9921 (forward-sexp) ; skip destructuring form
9922 (js2-forward-sws)
9923 (if (and (/= (char-after) ?,) ; regular array
9924 (looking-at "for"))
9925 (match-beginning 0)))
9926 ;; to skip arbitrary expressions we need the parser,
9927 ;; so we'll just guess at it.
9928 (if (re-search-forward "[^,]* \\(for\\) " end t)
9929 (match-beginning 1))))))))
9930
9931 (defun js2-array-comp-indentation (parse-status for-kwd)
9932 (if (js2-same-line for-kwd)
9933 ;; first continuation line
9934 (save-excursion
9935 (goto-char (nth 1 parse-status))
9936 (forward-char 1)
9937 (skip-chars-forward " \t")
9938 (current-column))
9939 (save-excursion
9940 (goto-char for-kwd)
9941 (current-column))))
9942
9943 (defun js-proper-indentation (parse-status)
9944 "Return the proper indentation for the current line."
9945 (save-excursion
9946 (back-to-indentation)
9947 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9948 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9949 (continued-expr-p (js-continued-expression-p))
9950 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9951 (js-get-multiline-declaration-offset))
9952 0))
9953 (bracket (nth 1 parse-status))
9954 beg)
9955 (cond
9956 ;; indent array comprehension continuation lines specially
9957 ((and bracket
9958 (not (js2-same-line bracket))
9959 (setq beg (js2-indent-in-array-comp parse-status))
9960 (>= (point) (save-excursion
9961 (goto-char beg)
9962 (point-at-bol)))) ; at or after first loop?
9963 (js2-array-comp-indentation parse-status beg))
9964
9965 (ctrl-stmt-indent)
9966
9967 (bracket
9968 (goto-char bracket)
9969 (cond
9970 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9971 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9972 (when (save-excursion (skip-chars-backward " \t)")
9973 (looking-at ")"))
9974 (backward-list))
9975 (if (and (nth 1 p)
9976 (not js2-consistent-level-indent-inner-bracket-p))
9977 (progn (goto-char (1+ (nth 1 p)))
9978 (skip-chars-forward " \t"))
9979 (back-to-indentation))
9980 (cond (same-indent-p
9981 (current-column))
9982 (continued-expr-p
9983 (+ (current-column) (* 2 js2-basic-offset)))
9984 ((> multiline-declaration-offset 0)
9985 (+ (current-column) js2-basic-offset multiline-declaration-offset))
9986 (t
9987 (+ (current-column) js2-basic-offset)))))
9988 (t
9989 (unless same-indent-p
9990 (forward-char)
9991 (skip-chars-forward " \t"))
9992 (current-column))))
9993
9994 (continued-expr-p js2-basic-offset)
9995
9996 ((> multiline-declaration-offset 0)
9997 (+ multiline-declaration-offset))
9998
9999 (t 0)))))
10000
10001 (defun js2-lineup-comment (parse-status)
10002 "Indent a multi-line block comment continuation line."
10003 (let* ((beg (nth 8 parse-status))
10004 (first-line (js2-same-line beg))
10005 (offset (save-excursion
10006 (goto-char beg)
10007 (if (looking-at "/\\*")
10008 (+ 1 (current-column))
10009 0))))
10010 (unless first-line
10011 (indent-line-to offset))))
10012
10013 (defun js2-backward-sws ()
10014 "Move backward through whitespace and comments."
10015 (interactive)
10016 (while (forward-comment -1)))
10017
10018 (defun js2-forward-sws ()
10019 "Move forward through whitespace and comments."
10020 (interactive)
10021 (while (forward-comment 1)))
10022
10023 (defsubst js2-current-indent (&optional pos)
10024 "Return column of indentation on current line.
10025 If POS is non-nil, go to that point and return indentation for that line."
10026 (save-excursion
10027 (if pos
10028 (goto-char pos))
10029 (back-to-indentation)
10030 (current-column)))
10031
10032 (defsubst js2-arglist-close ()
10033 "Return non-nil if we're on a line beginning with a close-paren/brace."
10034 (save-match-data
10035 (save-excursion
10036 (goto-char (point-at-bol))
10037 (js2-forward-sws)
10038 (looking-at "[])}]"))))
10039
10040 (defsubst js2-indent-looks-like-label-p ()
10041 (goto-char (point-at-bol))
10042 (js2-forward-sws)
10043 (looking-at (concat js2-mode-identifier-re ":")))
10044
10045 (defun js2-indent-in-objlit-p (parse-status)
10046 "Return non-nil if this looks like an object-literal entry."
10047 (let ((start (nth 1 parse-status)))
10048 (and
10049 start
10050 (save-excursion
10051 (and (zerop (forward-line -1))
10052 (not (< (point) start)) ; crossed a {} boundary
10053 (js2-indent-looks-like-label-p)))
10054 (save-excursion
10055 (js2-indent-looks-like-label-p)))))
10056
10057 ;; if prev line looks like foobar({ then we're passing an object
10058 ;; literal to a function call, and people pretty much always want to
10059 ;; de-dent back to the previous line, so move the 'basic-offset'
10060 ;; position to the front.
10061 (defsubst js2-indent-objlit-arg-p (parse-status)
10062 (save-excursion
10063 (back-to-indentation)
10064 (js2-backward-sws)
10065 (and (eq (1- (point)) (nth 1 parse-status))
10066 (eq (char-before) ?{)
10067 (progn
10068 (forward-char -1)
10069 (skip-chars-backward " \t")
10070 (eq (char-before) ?\()))))
10071
10072 (defsubst js2-indent-case-block-p ()
10073 (save-excursion
10074 (back-to-indentation)
10075 (js2-backward-sws)
10076 (goto-char (point-at-bol))
10077 (skip-chars-forward " \t")
10078 (save-match-data
10079 (looking-at "case\\s-.+:"))))
10080
10081 (defsubst js2-syntax-bol ()
10082 "Return the point at the first non-whitespace char on the line.
10083 Returns `point-at-bol' if the line is empty."
10084 (save-excursion
10085 (beginning-of-line)
10086 (skip-chars-forward " \t")
10087 (point)))
10088
10089 (defun js2-bounce-indent (normal-col parse-status)
10090 "Cycle among alternate computed indentation positions.
10091 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10092 of the buffer to the current point. NORMAL-COL is the indentation
10093 column computed by the heuristic guesser based on current paren,
10094 bracket, brace and statement nesting."
10095 (let ((cur-indent (js2-current-indent))
10096 (old-buffer-undo-list buffer-undo-list)
10097 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10098 (current-line (save-excursion
10099 (forward-line 0) ; move to bol
10100 (1+ (count-lines (point-min) (point)))))
10101 positions
10102 pos
10103 anchor
10104 arglist-cont
10105 same-indent
10106 prev-line-col
10107 basic-offset
10108 computed-pos)
10109 ;; temporarily don't record undo info, if user requested this
10110 (if js2-mode-indent-inhibit-undo
10111 (setq buffer-undo-list t))
10112 (unwind-protect
10113 (progn
10114 ;; first likely point: indent from beginning of previous code line
10115 (push (setq basic-offset
10116 (+ (save-excursion
10117 (back-to-indentation)
10118 (js2-backward-sws)
10119 (back-to-indentation)
10120 (setq prev-line-col (current-column)))
10121 js2-basic-offset))
10122 positions)
10123
10124 ;; (first + epsilon) likely point: indent 2x from beginning of
10125 ;; previous code line. Some companies like this approach. Ahem.
10126 ;; Seriously, though -- 4-space indent for expression continuation
10127 ;; lines isn't a bad idea. We should eventually implement it
10128 ;; that way.
10129 (push (setq basic-offset
10130 (+ (save-excursion
10131 (back-to-indentation)
10132 (js2-backward-sws)
10133 (back-to-indentation)
10134 (setq prev-line-col (current-column)))
10135 (* 2 js2-basic-offset)))
10136 positions)
10137
10138 ;; second likely point: indent from assign-expr RHS. This
10139 ;; is just a crude guess based on finding " = " on the previous
10140 ;; line containing actual code.
10141 (setq pos (save-excursion
10142 (save-match-data
10143 (forward-line -1)
10144 (goto-char (point-at-bol))
10145 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10146 (point-at-eol) t)
10147 (goto-char (match-end 1))
10148 (skip-chars-forward " \t\r\n")
10149 (current-column)))))
10150 (when pos
10151 (incf pos js2-basic-offset)
10152 (unless (member pos positions)
10153 (push pos positions)))
10154
10155 ;; third likely point: same indent as previous line of code.
10156 ;; Make it the first likely point if we're not on an
10157 ;; arglist-close line and previous line ends in a comma, or
10158 ;; both this line and prev line look like object-literal
10159 ;; elements.
10160 (setq pos (save-excursion
10161 (goto-char (point-at-bol))
10162 (js2-backward-sws)
10163 (back-to-indentation)
10164 (prog1
10165 (current-column)
10166 ;; while we're here, look for trailing comma
10167 (if (save-excursion
10168 (goto-char (point-at-eol))
10169 (js2-backward-sws)
10170 (eq (char-before) ?,))
10171 (setq arglist-cont (1- (point)))))))
10172 (when pos
10173 (if (and (or arglist-cont
10174 (js2-indent-in-objlit-p parse-status))
10175 (not (js2-arglist-close)))
10176 (setq same-indent pos))
10177 (unless (member pos positions)
10178 (push pos positions)))
10179
10180 ;; fourth likely point: first preceding code with less indentation
10181 ;; than the immediately preceding code line.
10182 (setq pos (save-excursion
10183 (js2-backward-sws)
10184 (back-to-indentation)
10185 (setq anchor (current-column))
10186 (while (and (zerop (forward-line -1))
10187 (>= (progn
10188 (back-to-indentation)
10189 (current-column))
10190 anchor)))
10191 (setq pos (current-column))))
10192 (unless (member pos positions)
10193 (push pos positions))
10194
10195 ;; put nesting-heuristic position first in list, sort rest
10196 (setq positions (nreverse (sort positions '<)))
10197 (setq positions (cons normal-col (delete normal-col positions)))
10198
10199 ;; comma-list continuation lines: prev line indent takes precedence
10200 (if same-indent
10201 (setq positions
10202 (cons same-indent
10203 (sort (delete same-indent positions) '<))))
10204
10205 ;; common special cases where we want to indent in from previous line
10206 (if (or (js2-indent-case-block-p)
10207 (js2-indent-objlit-arg-p parse-status))
10208 (setq positions
10209 (cons basic-offset
10210 (delete basic-offset positions))))
10211
10212 ;; record whether we're already sitting on one of the alternatives
10213 (setq pos (member cur-indent positions))
10214 (cond
10215 ;; case 0: we're one one of the alternatives and this is the
10216 ;; first time they've pressed TAB on this line (best-guess).
10217 ((and js2-mode-indent-ignore-first-tab
10218 pos
10219 ;; first time pressing TAB on this line?
10220 (not (eq js2-mode-last-indented-line current-line)))
10221 ;; do nothing
10222 (setq computed-pos nil))
10223 ;; case 1: only one computed position => use it
10224 ((null (cdr positions))
10225 (setq computed-pos 0))
10226 ;; case 2: not on any of the computed spots => use main spot
10227 ((not pos)
10228 (setq computed-pos 0))
10229 ;; case 3: on last position: cycle to first position
10230 ((null (cdr pos))
10231 (setq computed-pos 0))
10232 ;; case 4: on intermediate position: cycle to next position
10233 (t
10234 (setq computed-pos (js2-position (second pos) positions))))
10235
10236 ;; see if any hooks want to indent; otherwise we do it
10237 (loop with result = nil
10238 for hook in js2-indent-hook
10239 while (null result)
10240 do
10241 (setq result (funcall hook positions computed-pos))
10242 finally do
10243 (unless (or result (null computed-pos))
10244 (indent-line-to (nth computed-pos positions)))))
10245
10246 ;; finally
10247 (if js2-mode-indent-inhibit-undo
10248 (setq buffer-undo-list old-buffer-undo-list))
10249 ;; see commentary for `js2-mode-last-indented-line'
10250 (setq js2-mode-last-indented-line current-line))))
10251
10252 (defsubst js2-1-line-comment-continuation-p ()
10253 "Return t if we're in a 1-line comment continuation.
10254 If so, we don't ever want to use bounce-indent."
10255 (save-excursion
10256 (save-match-data
10257 (and (progn
10258 (forward-line 0)
10259 (looking-at "\\s-*//"))
10260 (progn
10261 (forward-line -1)
10262 (forward-line 0)
10263 (when (looking-at "\\s-*$")
10264 (js2-backward-sws)
10265 (forward-line 0))
10266 (looking-at "\\s-*//"))))))
10267
10268 (defun js2-indent-line ()
10269 "Indent the current line as JavaScript source text."
10270 (interactive)
10271 (when js2-use-ast-for-indentation-p
10272 (js2-reparse))
10273 (let (parse-status
10274 current-indent
10275 offset
10276 indent-col
10277 moved
10278 ;; don't whine about errors/warnings when we're indenting.
10279 ;; This has to be set before calling parse-partial-sexp below.
10280 (inhibit-point-motion-hooks t))
10281 (setq parse-status (save-excursion
10282 (parse-partial-sexp (point-min)
10283 (point-at-bol)))
10284 offset (- (point) (save-excursion
10285 (back-to-indentation)
10286 (setq current-indent (current-column))
10287 (point))))
10288 (js2-with-underscore-as-word-syntax
10289 (if (nth 4 parse-status)
10290 (js2-lineup-comment parse-status)
10291 (setq indent-col (js-proper-indentation parse-status))
10292 ;; see comments below about js2-mode-last-indented-line
10293 (when
10294 (cond
10295 ;; bounce-indenting is disabled during electric-key indent.
10296 ;; It doesn't work well on first line of buffer.
10297 ((and js2-bounce-indent-p
10298 (not (js2-same-line (point-min)))
10299 (not (js2-1-line-comment-continuation-p)))
10300 (js2-bounce-indent indent-col parse-status)
10301 (setq moved t))
10302 ;; just indent to the guesser's likely spot
10303 ((/= current-indent indent-col)
10304 (indent-line-to indent-col)
10305 (setq moved t)))
10306 (when (and moved (plusp offset))
10307 (forward-char offset)))))))
10308
10309 (defun js2-indent-region (start end)
10310 "Indent the region, but don't use bounce indenting."
10311 (let ((js2-bounce-indent-p nil)
10312 (indent-region-function nil))
10313 (indent-region start end nil))) ; nil for byte-compiler
10314
10315 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10316
10317 ;;;###autoload
10318 (defun js2-mode ()
10319 "Major mode for editing JavaScript code."
10320 (interactive)
10321 (kill-all-local-variables)
10322 (set-syntax-table js2-mode-syntax-table)
10323 (use-local-map js2-mode-map)
10324 (setq major-mode 'js2-mode
10325 mode-name "JavaScript-IDE"
10326 comment-start "//" ; used by comment-region; don't change it
10327 comment-end "")
10328 (setq local-abbrev-table js2-mode-abbrev-table)
10329 (set (make-local-variable 'max-lisp-eval-depth)
10330 (max max-lisp-eval-depth 3000))
10331 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10332 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10333
10334 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10335 ;; on most platforms other than the one I originally wrote it on. So it's
10336 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10337 ;; with our binding of the RET key inside comments: short lines stay short.
10338 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10339
10340 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10341 (set (make-local-variable 'next-error-function) #'js2-next-error)
10342 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10343 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10344 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10345 ;; for characters inside regexp literals.
10346 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10347 ;; this is necessary to make `show-paren-function' work properly
10348 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10349 ;; needed for M-x rgrep, among other things
10350 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10351
10352 ;; some variables needed by cc-engine for paragraph-fill, etc.
10353 (setq c-buffer-is-cc-mode t
10354 c-comment-prefix-regexp js2-comment-prefix-regexp
10355 c-comment-start-regexp "/[*/]\\|\\s|"
10356 c-paragraph-start js2-paragraph-start
10357 c-paragraph-separate "$"
10358 comment-start-skip js2-comment-start-skip
10359 c-syntactic-ws-start js2-syntactic-ws-start
10360 c-syntactic-ws-end js2-syntactic-ws-end
10361 c-syntactic-eol js2-syntactic-eol)
10362
10363 (setq js2-default-externs
10364 (append js2-ecma-262-externs
10365 (if js2-include-browser-externs
10366 js2-browser-externs)
10367 (if js2-include-gears-externs
10368 js2-gears-externs)
10369 (if js2-include-rhino-externs
10370 js2-rhino-externs)))
10371
10372 ;; We do our own syntax highlighting based on the parse tree.
10373 ;; However, we want minor modes that add keywords to highlight properly
10374 ;; (examples: doxymacs, column-marker). We do this by not letting
10375 ;; font-lock unfontify anything, and telling it to fontify after we
10376 ;; re-parse and re-highlight the buffer. (We currently don't do any
10377 ;; work with regions other than the whole buffer.)
10378 (dolist (var '(font-lock-unfontify-buffer-function
10379 font-lock-unfontify-region-function))
10380 (set (make-local-variable var) (lambda (&rest args) t)))
10381
10382 ;; Don't let font-lock do syntactic (string/comment) fontification.
10383 (set (make-local-variable #'font-lock-syntactic-face-function)
10384 (lambda (state) nil))
10385
10386 ;; Experiment: make reparse-delay longer for longer files.
10387 (if (plusp js2-dynamic-idle-timer-adjust)
10388 (setq js2-idle-timer-delay
10389 (* js2-idle-timer-delay
10390 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10391
10392 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10393 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10394 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10395 (imenu-add-to-menubar (concat "IM-" mode-name))
10396 (when js2-mirror-mode
10397 (js2-enter-mirror-mode))
10398 (add-to-invisibility-spec '(js2-outline . t))
10399 (set (make-local-variable 'line-move-ignore-invisible) t)
10400 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10401 (setq js2-mode-functions-hidden nil
10402 js2-mode-comments-hidden nil
10403 js2-mode-buffer-dirty-p t
10404 js2-mode-parsing nil)
10405 (js2-reparse)
10406 (run-hooks 'js2-mode-hook))
10407
10408 (defun js2-mode-exit ()
10409 "Exit `js2-mode' and clean up."
10410 (interactive)
10411 (when js2-mode-node-overlay
10412 (delete-overlay js2-mode-node-overlay)
10413 (setq js2-mode-node-overlay nil))
10414 (js2-remove-overlays)
10415 (setq js2-mode-ast nil)
10416 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10417 (remove-from-invisibility-spec '(js2-outline . t))
10418 (js2-mode-show-all)
10419 (js2-with-unmodifying-text-property-changes
10420 (js2-clear-face (point-min) (point-max))))
10421
10422 (defun js2-before-save ()
10423 "Clean up whitespace before saving file.
10424 You can disable this by customizing `js2-cleanup-whitespace'."
10425 (when js2-cleanup-whitespace
10426 (let ((col (current-column)))
10427 (delete-trailing-whitespace)
10428 ;; don't change trailing whitespace on current line
10429 (unless (eq (current-column) col)
10430 (indent-to col)))))
10431
10432 (defsubst js2-mode-reset-timer ()
10433 "Cancel any existing parse timer and schedule a new one."
10434 (if js2-mode-parse-timer
10435 (cancel-timer js2-mode-parse-timer))
10436 (setq js2-mode-parsing nil)
10437 (setq js2-mode-parse-timer
10438 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10439
10440 (defun js2-mode-edit (beg end len)
10441 "Schedule a new parse after buffer is edited.
10442 Buffer edit spans from BEG to END and is of length LEN.
10443 Also clears the `js2-magic' bit on autoinserted parens/brackets
10444 if the edit occurred on a line different from the magic paren."
10445 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10446 (line (if magic-pos (line-number-at-pos magic-pos))))
10447 (and line
10448 (or (/= (line-number-at-pos beg) line)
10449 (and (> 0 len)
10450 (/= (line-number-at-pos end) line)))
10451 (js2-mode-mundanify-parens)))
10452 (setq js2-mode-buffer-dirty-p t)
10453 (js2-mode-hide-overlay)
10454 (js2-mode-reset-timer))
10455
10456 (defun js2-mode-run-font-lock ()
10457 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10458 This is intended to allow modes that install their own font-lock keywords
10459 to work with js2-mode. In practice it never seems to work for long.
10460 Hopefully the Emacs maintainers can help figure out a way to make it work."
10461 (when (and (boundp 'font-lock-keywords)
10462 font-lock-keywords
10463 (boundp 'font-lock-mode)
10464 font-lock-mode)
10465 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10466 ;; play nicely with js2-mode. They go out of their way to fail to
10467 ;; provide any option for saying "look, fontify the farging buffer
10468 ;; with just the keywords already". Argh.
10469 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10470 (let (font-lock-verbose)
10471 (font-lock-fontify-buffer))))
10472
10473 (defun js2-reparse (&optional force)
10474 "Re-parse current buffer after user finishes some data entry.
10475 If we get any user input while parsing, including cursor motion,
10476 we discard the parse and reschedule it. If FORCE is nil, then the
10477 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10478 (let (time
10479 interrupted-p
10480 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10481 (unless js2-mode-parsing
10482 (setq js2-mode-parsing t)
10483 (unwind-protect
10484 (when (or js2-mode-buffer-dirty-p force)
10485 (js2-remove-overlays)
10486 (js2-with-unmodifying-text-property-changes
10487 (setq js2-mode-buffer-dirty-p nil
10488 js2-mode-fontifications nil
10489 js2-mode-deferred-properties nil
10490 js2-additional-externs nil)
10491 (if js2-mode-verbose-parse-p
10492 (message "parsing..."))
10493 (setq time
10494 (js2-time
10495 (setq interrupted-p
10496 (catch 'interrupted
10497 (setq js2-mode-ast (js2-parse))
10498 ;; if parsing is interrupted, comments and regex
10499 ;; literals stay ignored by `parse-partial-sexp'
10500 (remove-text-properties (point-min) (point-max)
10501 '(syntax-table))
10502 (js2-mode-apply-deferred-properties)
10503 (js2-mode-remove-suppressed-warnings)
10504 (js2-mode-show-warnings)
10505 (js2-mode-show-errors)
10506 (js2-mode-run-font-lock) ; note: doesn't work
10507 (js2-mode-highlight-magic-parens)
10508 (if (>= js2-highlight-level 1)
10509 (js2-highlight-jsdoc js2-mode-ast))
10510 nil))))
10511 (if interrupted-p
10512 (progn
10513 ;; unfinished parse => try again
10514 (setq js2-mode-buffer-dirty-p t)
10515 (js2-mode-reset-timer))
10516 (if js2-mode-verbose-parse-p
10517 (message "Parse time: %s" time)))))
10518 (setq js2-mode-parsing nil)
10519 (unless interrupted-p
10520 (setq js2-mode-parse-timer nil))))))
10521
10522 (defun js2-mode-show-node ()
10523 "Debugging aid: highlight selected AST node on mouse click."
10524 (interactive)
10525 (let ((node (js2-node-at-point))
10526 beg
10527 end)
10528 (when js2-mode-show-overlay
10529 (if (null node)
10530 (message "No node found at location %s" (point))
10531 (setq beg (js2-node-abs-pos node)
10532 end (+ beg (js2-node-len node)))
10533 (if js2-mode-node-overlay
10534 (move-overlay js2-mode-node-overlay beg end)
10535 (setq js2-mode-node-overlay (make-overlay beg end))
10536 (overlay-put js2-mode-node-overlay 'face 'highlight))
10537 (js2-with-unmodifying-text-property-changes
10538 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10539 (message "%s, parent: %s"
10540 (js2-node-short-name node)
10541 (if (js2-node-parent node)
10542 (js2-node-short-name (js2-node-parent node))
10543 "nil"))))))
10544
10545 (defun js2-mode-hide-overlay (&optional p1 p2)
10546 "Remove the debugging overlay when the point moves.
10547 P1 and P2 are the old and new values of point, respectively."
10548 (when js2-mode-node-overlay
10549 (let ((beg (overlay-start js2-mode-node-overlay))
10550 (end (overlay-end js2-mode-node-overlay)))
10551 ;; Sometimes we're called spuriously.
10552 (unless (and p2
10553 (>= p2 beg)
10554 (<= p2 end))
10555 (js2-with-unmodifying-text-property-changes
10556 (remove-text-properties beg end '(point-left nil)))
10557 (delete-overlay js2-mode-node-overlay)
10558 (setq js2-mode-node-overlay nil)))))
10559
10560 (defun js2-mode-reset ()
10561 "Debugging helper: reset everything."
10562 (interactive)
10563 (js2-mode-exit)
10564 (js2-mode))
10565
10566 (defsubst js2-mode-show-warn-or-err (e face)
10567 "Highlight a warning or error E with FACE.
10568 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10569 (let* ((key (first e))
10570 (beg (second e))
10571 (end (+ beg (third e)))
10572 ;; Don't inadvertently go out of bounds.
10573 (beg (max (point-min) (min beg (point-max))))
10574 (end (max (point-min) (min end (point-max))))
10575 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10576 (ovl (make-overlay beg end)))
10577 (overlay-put ovl 'face face)
10578 (overlay-put ovl 'js2-error t)
10579 (put-text-property beg end 'help-echo (js2-get-msg key))
10580 (put-text-property beg end 'point-entered #'js2-echo-error)))
10581
10582 (defun js2-remove-overlays ()
10583 "Remove overlays from buffer that have a `js2-error' property."
10584 (let ((beg (point-min))
10585 (end (point-max)))
10586 (save-excursion
10587 (dolist (o (overlays-in beg end))
10588 (when (overlay-get o 'js2-error)
10589 (delete-overlay o))))))
10590
10591 (defun js2-error-at-point (&optional pos)
10592 "Return non-nil if there's an error overlay at POS.
10593 Defaults to point."
10594 (loop with pos = (or pos (point))
10595 for o in (overlays-at pos)
10596 thereis (overlay-get o 'js2-error)))
10597
10598 (defun js2-mode-apply-deferred-properties ()
10599 "Apply fontifications and other text properties recorded during parsing."
10600 (when (plusp js2-highlight-level)
10601 ;; We defer clearing faces as long as possible to eliminate flashing.
10602 (js2-clear-face (point-min) (point-max))
10603 ;; Have to reverse the recorded fontifications list so that errors
10604 ;; and warnings overwrite the normal fontifications.
10605 (dolist (f (nreverse js2-mode-fontifications))
10606 (put-text-property (first f) (second f) 'face (third f)))
10607 (setq js2-mode-fontifications nil))
10608 (dolist (p js2-mode-deferred-properties)
10609 (apply #'put-text-property p))
10610 (setq js2-mode-deferred-properties nil))
10611
10612 (defun js2-mode-show-errors ()
10613 "Highlight syntax errors."
10614 (when js2-mode-show-parse-errors
10615 (dolist (e (js2-ast-root-errors js2-mode-ast))
10616 (js2-mode-show-warn-or-err e 'js2-error-face))))
10617
10618 (defun js2-mode-remove-suppressed-warnings ()
10619 "Take suppressed warnings out of the AST warnings list.
10620 This ensures that the counts and `next-error' are correct."
10621 (setf (js2-ast-root-warnings js2-mode-ast)
10622 (js2-delete-if
10623 (lambda (e)
10624 (let ((key (caar e)))
10625 (or
10626 (and (not js2-strict-trailing-comma-warning)
10627 (string-match "trailing\\.comma" key))
10628 (and (not js2-strict-cond-assign-warning)
10629 (string= key "msg.equal.as.assign"))
10630 (and js2-missing-semi-one-line-override
10631 (string= key "msg.missing.semi")
10632 (let* ((beg (second e))
10633 (node (js2-node-at-point beg))
10634 (fn (js2-mode-find-parent-fn node))
10635 (body (and fn (js2-function-node-body fn)))
10636 (lc (and body (js2-node-abs-pos body)))
10637 (rc (and lc (+ lc (js2-node-len body)))))
10638 (and fn
10639 (or (null body)
10640 (save-excursion
10641 (goto-char beg)
10642 (and (js2-same-line lc)
10643 (js2-same-line rc))))))))))
10644 (js2-ast-root-warnings js2-mode-ast))))
10645
10646 (defun js2-mode-show-warnings ()
10647 "Highlight strict-mode warnings."
10648 (when js2-mode-show-strict-warnings
10649 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10650 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10651
10652 (defun js2-echo-error (old-point new-point)
10653 "Called by point-motion hooks."
10654 (let ((msg (get-text-property new-point 'help-echo)))
10655 (if msg
10656 (message msg))))
10657
10658 (defalias #'js2-echo-help #'js2-echo-error)
10659
10660 (defun js2-enter-key ()
10661 "Handle user pressing the Enter key."
10662 (interactive)
10663 (let ((parse-status (save-excursion
10664 (parse-partial-sexp (point-min) (point)))))
10665 (cond
10666 ;; check if we're inside a string
10667 ((nth 3 parse-status)
10668 (js2-mode-split-string parse-status))
10669 ;; check if inside a block comment
10670 ((nth 4 parse-status)
10671 (js2-mode-extend-comment))
10672 (t
10673 ;; should probably figure out what the mode-map says we should do
10674 (if js2-indent-on-enter-key
10675 (let ((js2-bounce-indent-p nil))
10676 (js2-indent-line)))
10677 (insert "\n")
10678 (if js2-enter-indents-newline
10679 (let ((js2-bounce-indent-p nil))
10680 (js2-indent-line)))))))
10681
10682 (defun js2-mode-split-string (parse-status)
10683 "Turn a newline in mid-string into a string concatenation.
10684 PARSE-STATUS is as documented in `parse-partial-sexp'."
10685 (let* ((col (current-column))
10686 (quote-char (nth 3 parse-status))
10687 (quote-string (string quote-char))
10688 (string-beg (nth 8 parse-status))
10689 (indent (save-match-data
10690 (or
10691 (save-excursion
10692 (back-to-indentation)
10693 (if (looking-at "\\+")
10694 (current-column)))
10695 (save-excursion
10696 (goto-char string-beg)
10697 (if (looking-back "\\+\\s-+")
10698 (goto-char (match-beginning 0)))
10699 (current-column))))))
10700 (insert quote-char "\n")
10701 (indent-to indent)
10702 (insert "+ " quote-string)
10703 (when (eolp)
10704 (insert quote-string)
10705 (backward-char 1))))
10706
10707 (defun js2-mode-extend-comment ()
10708 "When inside a comment block, add comment prefix."
10709 (let (star single col first-line needs-close)
10710 (save-excursion
10711 (back-to-indentation)
10712 (cond
10713 ((looking-at "\\*[^/]")
10714 (setq star t
10715 col (current-column)))
10716 ((looking-at "/\\*")
10717 (setq star t
10718 first-line t
10719 col (1+ (current-column))))
10720 ((looking-at "//")
10721 (setq single t
10722 col (current-column)))))
10723 ;; Heuristic for whether we need to close the comment:
10724 ;; if we've got a parse error here, assume it's an unterminated
10725 ;; comment.
10726 (setq needs-close
10727 (or
10728 (eq (get-text-property (1- (point)) 'point-entered)
10729 'js2-echo-error)
10730 ;; The heuristic above doesn't work well when we're
10731 ;; creating a comment and there's another one downstream,
10732 ;; as our parser thinks this one ends at the end of the
10733 ;; next one. (You can have a /* inside a js block comment.)
10734 ;; So just close it if the next non-ws char isn't a *.
10735 (and first-line
10736 (eolp)
10737 (save-excursion
10738 (skip-chars-forward " \t\r\n")
10739 (not (eq (char-after) ?*))))))
10740 (insert "\n")
10741 (cond
10742 (star
10743 (indent-to col)
10744 (insert "* ")
10745 (if (and first-line needs-close)
10746 (save-excursion
10747 (insert "\n")
10748 (indent-to col)
10749 (insert "*/"))))
10750 (single
10751 (when (save-excursion
10752 (and (zerop (forward-line 1))
10753 (looking-at "\\s-*//")))
10754 (indent-to col)
10755 (insert "// "))))))
10756
10757 (defun js2-beginning-of-line ()
10758 "Toggles point between bol and first non-whitespace char in line.
10759 Also moves past comment delimiters when inside comments."
10760 (interactive)
10761 (let (node beg)
10762 (cond
10763 ((bolp)
10764 (back-to-indentation))
10765 ((looking-at "//")
10766 (skip-chars-forward "/ \t"))
10767 ((and (eq (char-after) ?*)
10768 (setq node (js2-comment-at-point))
10769 (memq (js2-comment-node-format node) '(jsdoc block))
10770 (save-excursion
10771 (skip-chars-backward " \t")
10772 (bolp)))
10773 (skip-chars-forward "\* \t"))
10774 (t
10775 (goto-char (point-at-bol))))))
10776
10777 (defun js2-end-of-line ()
10778 "Toggles point between eol and last non-whitespace char in line."
10779 (interactive)
10780 (if (eolp)
10781 (skip-chars-backward " \t")
10782 (goto-char (point-at-eol))))
10783
10784 (defun js2-enter-mirror-mode()
10785 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10786 on insertion."
10787 (interactive)
10788 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10789 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10790 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10791 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10792 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10793 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10794 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10795 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10796
10797 (defun js2-leave-mirror-mode()
10798 "Turns off mirror mode."
10799 (interactive)
10800 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10801 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10802
10803 (defsubst js2-mode-inside-string ()
10804 "Return non-nil if inside a string.
10805 Actually returns the quote character that begins the string."
10806 (let ((parse-state (save-excursion
10807 (parse-partial-sexp (point-min) (point)))))
10808 (nth 3 parse-state)))
10809
10810 (defsubst js2-mode-inside-comment-or-string ()
10811 "Return non-nil if inside a comment or string."
10812 (or
10813 (let ((comment-start
10814 (save-excursion
10815 (goto-char (point-at-bol))
10816 (if (re-search-forward "//" (point-at-eol) t)
10817 (match-beginning 0)))))
10818 (and comment-start
10819 (<= comment-start (point))))
10820 (let ((parse-state (save-excursion
10821 (parse-partial-sexp (point-min) (point)))))
10822 (or (nth 3 parse-state)
10823 (nth 4 parse-state)))))
10824
10825 (defsubst js2-make-magic-delimiter (delim &optional pos)
10826 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10827 Sets value of `js2-magic' text property to line number at POS."
10828 (propertize delim
10829 'js2-magic (line-number-at-pos pos)
10830 'face 'js2-magic-paren-face))
10831
10832 (defun js2-mode-match-delimiter (open close)
10833 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10834 The rule we use, which as far as we can tell is how Eclipse works,
10835 is that we insert the match if we're not in a comment or string,
10836 and the next non-whitespace character is either punctuation or
10837 occurs on another line."
10838 (insert open)
10839 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10840 (not (js2-mode-inside-comment-or-string)))
10841 (save-excursion
10842 (insert (js2-make-magic-delimiter close)))
10843 (when js2-auto-indent-p
10844 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10845 (js2-indent-line)))))
10846
10847 (defun js2-mode-match-bracket ()
10848 "Insert matching bracket."
10849 (interactive)
10850 (js2-mode-match-delimiter "[" "]"))
10851
10852 (defun js2-mode-match-paren ()
10853 "Insert matching paren unless already inserted."
10854 (interactive)
10855 (js2-mode-match-delimiter "(" ")"))
10856
10857 (defun js2-mode-match-curly (arg)
10858 "Insert matching curly-brace.
10859 With prefix arg, no formatting or indentation will occur -- the close-brace
10860 is simply inserted directly at the point."
10861 (interactive "p")
10862 (let (try-pos)
10863 (cond
10864 (current-prefix-arg
10865 (js2-mode-match-delimiter "{" "}"))
10866 ((and js2-auto-insert-catch-block
10867 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10868 (point-at-bol))
10869 (match-beginning 1))))
10870 (js2-insert-catch-skel try-pos))
10871 (t
10872 ;; Otherwise try to do something smarter.
10873 (insert "{")
10874 (unless (or (not (looking-at "\\s-*$"))
10875 (save-excursion
10876 (skip-chars-forward " \t\r\n")
10877 (and (looking-at "}")
10878 (js2-error-at-point)))
10879 (js2-mode-inside-comment-or-string))
10880 (undo-boundary)
10881 ;; absolutely mystifying bug: when inserting the next "\n",
10882 ;; the buffer-undo-list is given two new entries: the inserted range,
10883 ;; and the incorrect position of the point. It's recorded incorrectly
10884 ;; as being before the opening "{", not after it. But it's recorded
10885 ;; as the correct value if you're debugging `js2-mode-match-curly'
10886 ;; in edebug. I have no idea why it's doing this, but incrementing
10887 ;; the inserted position fixes the problem, so that the undo takes us
10888 ;; back to just after the user-inserted "{".
10889 (insert "\n")
10890 (ignore-errors
10891 (incf (cadr buffer-undo-list)))
10892 (js2-indent-line)
10893 (save-excursion
10894 (insert "\n}")
10895 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10896 (js2-indent-line))))))))
10897
10898 (defun js2-insert-catch-skel (try-pos)
10899 "Complete a try/catch block after inserting a { following a try keyword.
10900 Rationale is that a try always needs a catch or a finally, and the catch is
10901 the more likely of the two.
10902
10903 TRY-POS is the buffer position of the try keyword. The open-curly should
10904 already have been inserted."
10905 (insert "{")
10906 (let ((try-col (save-excursion
10907 (goto-char try-pos)
10908 (current-column))))
10909 (insert "\n")
10910 (undo-boundary)
10911 (js2-indent-line) ;; indent the blank line where cursor will end up
10912 (save-excursion
10913 (insert "\n")
10914 (indent-to try-col)
10915 (insert "} catch (x) {\n\n")
10916 (indent-to try-col)
10917 (insert "}"))))
10918
10919 (defun js2-mode-highlight-magic-parens ()
10920 "Re-highlight magic parens after parsing nukes the 'face prop."
10921 (let ((beg (point-min))
10922 end)
10923 (while (setq beg (next-single-property-change beg 'js2-magic))
10924 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10925 (if (get-text-property beg 'js2-magic)
10926 (js2-with-unmodifying-text-property-changes
10927 (put-text-property beg (or end (1+ beg))
10928 'face 'js2-magic-paren-face))))))
10929
10930 (defun js2-mode-mundanify-parens ()
10931 "Clear all magic parens and brackets."
10932 (let ((beg (point-min))
10933 end)
10934 (while (setq beg (next-single-property-change beg 'js2-magic))
10935 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10936 (remove-text-properties beg (or end (1+ beg))
10937 '(js2-magic face)))))
10938
10939 (defsubst js2-match-quote (quote-string)
10940 (let ((start-quote (js2-mode-inside-string)))
10941 (cond
10942 ;; inside a comment - don't do quote-matching, since we can't
10943 ;; reliably figure out if we're in a string inside the comment
10944 ((js2-comment-at-point)
10945 (insert quote-string))
10946 ((not start-quote)
10947 ;; not in string => insert matched quotes
10948 (insert quote-string)
10949 ;; exception: if we're just before a word, don't double it.
10950 (unless (looking-at "[^ \t\r\n]")
10951 (save-excursion
10952 (insert quote-string))))
10953 ((looking-at quote-string)
10954 (if (looking-back "[^\\]\\\\")
10955 (insert quote-string)
10956 (forward-char 1)))
10957 ((and js2-mode-escape-quotes
10958 (save-excursion
10959 (save-match-data
10960 (re-search-forward quote-string (point-at-eol) t))))
10961 ;; inside terminated string, escape quote (unless already escaped)
10962 (insert (if (looking-back "[^\\]\\\\")
10963 quote-string
10964 (concat "\\" quote-string))))
10965 (t
10966 (insert quote-string))))) ; else terminate the string
10967
10968 (defun js2-mode-match-single-quote ()
10969 "Insert matching single-quote."
10970 (interactive)
10971 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10972 ;; don't match inside comments, since apostrophe is more common
10973 (if (nth 4 parse-status)
10974 (insert "'")
10975 (js2-match-quote "'"))))
10976
10977 (defun js2-mode-match-double-quote ()
10978 "Insert matching double-quote."
10979 (interactive)
10980 (js2-match-quote "\""))
10981
10982 ;; Eclipse works as follows:
10983 ;; * type an open-paren and it auto-inserts close-paren
10984 ;; - auto-inserted paren gets a green bracket
10985 ;; - green bracket means typing close-paren there will skip it
10986 ;; * if you insert any text on a different line, it turns off
10987 (defun js2-mode-magic-close-paren ()
10988 "Skip over close-paren rather than inserting, where appropriate."
10989 (interactive)
10990 (let* ((here (point))
10991 (parse-status (parse-partial-sexp (point-min) here))
10992 (open-pos (nth 1 parse-status))
10993 (close last-input-event)
10994 (open (cond
10995 ((eq close ?\))
10996 ?\()
10997 ((eq close ?\])
10998 ?\[)
10999 ((eq close ?})
11000 ?{)
11001 (t nil))))
11002 (if (and (eq (char-after) close)
11003 (eq open (char-after open-pos))
11004 (js2-same-line open-pos)
11005 (get-text-property here 'js2-magic))
11006 (progn
11007 (remove-text-properties here (1+ here) '(js2-magic face))
11008 (forward-char 1))
11009 (insert-char close 1))
11010 (blink-matching-open)))
11011
11012 (defun js2-mode-wait-for-parse (callback)
11013 "Invoke CALLBACK when parsing is finished.
11014 If parsing is already finished, calls CALLBACK immediately."
11015 (if (not js2-mode-buffer-dirty-p)
11016 (funcall callback)
11017 (push callback js2-mode-pending-parse-callbacks)
11018 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11019
11020 (defun js2-mode-parse-finished ()
11021 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11022 ;; We can't let errors propagate up, since it prevents the
11023 ;; `js2-parse' method from completing normally and returning
11024 ;; the ast, which makes things mysteriously not work right.
11025 (unwind-protect
11026 (dolist (cb js2-mode-pending-parse-callbacks)
11027 (condition-case err
11028 (funcall cb)
11029 (error (message "%s" err))))
11030 (setq js2-mode-pending-parse-callbacks nil)))
11031
11032 (defun js2-mode-flag-region (from to flag)
11033 "Hide or show text from FROM to TO, according to FLAG.
11034 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11035 Returns the created overlay if FLAG is non-nil."
11036 (remove-overlays from to 'invisible 'js2-outline)
11037 (when flag
11038 (let ((o (make-overlay from to)))
11039 (overlay-put o 'invisible 'js2-outline)
11040 (overlay-put o 'isearch-open-invisible
11041 'js2-isearch-open-invisible)
11042 o)))
11043
11044 ;; Function to be set as an outline-isearch-open-invisible' property
11045 ;; to the overlay that makes the outline invisible (see
11046 ;; `js2-mode-flag-region').
11047 (defun js2-isearch-open-invisible (overlay)
11048 ;; We rely on the fact that isearch places point on the matched text.
11049 (js2-mode-show-element))
11050
11051 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11052 "Return cons cell of bounds of folding overlay at POS.
11053 Returns nil if not found."
11054 (let ((overlays (overlays-at (or pos (point))))
11055 o)
11056 (while (and overlays
11057 (not o))
11058 (if (overlay-get (car overlays) 'invisible)
11059 (setq o (car overlays))
11060 (setq overlays (cdr overlays))))
11061 (if o
11062 (cons (overlay-start o) (overlay-end o)))))
11063
11064 (defun js2-mode-function-at-point (&optional pos)
11065 "Return the innermost function node enclosing current point.
11066 Returns nil if point is not in a function."
11067 (let ((node (js2-node-at-point pos)))
11068 (while (and node (not (js2-function-node-p node)))
11069 (setq node (js2-node-parent node)))
11070 (if (js2-function-node-p node)
11071 node)))
11072
11073 (defun js2-mode-toggle-element ()
11074 "Hide or show the foldable element at the point."
11075 (interactive)
11076 (let (comment fn pos)
11077 (save-excursion
11078 (save-match-data
11079 (cond
11080 ;; /* ... */ comment?
11081 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11082 (if (js2-mode-invisible-overlay-bounds
11083 (setq pos (+ 3 (js2-node-abs-pos comment))))
11084 (progn
11085 (goto-char pos)
11086 (js2-mode-show-element))
11087 (js2-mode-hide-element)))
11088 ;; //-comment?
11089 ((save-excursion
11090 (back-to-indentation)
11091 (looking-at js2-mode-//-comment-re))
11092 (js2-mode-toggle-//-comment))
11093 ;; function?
11094 ((setq fn (js2-mode-function-at-point))
11095 (setq pos (and (js2-function-node-body fn)
11096 (js2-node-abs-pos (js2-function-node-body fn))))
11097 (goto-char (1+ pos))
11098 (if (js2-mode-invisible-overlay-bounds)
11099 (js2-mode-show-element)
11100 (js2-mode-hide-element)))
11101 (t
11102 (message "Nothing at point to hide or show")))))))
11103
11104 (defun js2-mode-hide-element ()
11105 "Fold/hide contents of a block, showing ellipses.
11106 Show the hidden text with \\[js2-mode-show-element]."
11107 (interactive)
11108 (if js2-mode-buffer-dirty-p
11109 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11110 (let (node body beg end)
11111 (cond
11112 ((js2-mode-invisible-overlay-bounds)
11113 (message "already hidden"))
11114 (t
11115 (setq node (js2-node-at-point))
11116 (cond
11117 ((js2-block-comment-p node)
11118 (js2-mode-hide-comment node))
11119 (t
11120 (while (and node (not (js2-function-node-p node)))
11121 (setq node (js2-node-parent node)))
11122 (if (and node
11123 (setq body (js2-function-node-body node)))
11124 (progn
11125 (setq beg (js2-node-abs-pos body)
11126 end (+ beg (js2-node-len body)))
11127 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11128 (message "No collapsable element found at point"))))))))
11129
11130 (defun js2-mode-show-element ()
11131 "Show the hidden element at current point."
11132 (interactive)
11133 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11134 (if bounds
11135 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11136 (message "Nothing to un-hide"))))
11137
11138 (defun js2-mode-show-all ()
11139 "Show all of the text in the buffer."
11140 (interactive)
11141 (js2-mode-flag-region (point-min) (point-max) nil))
11142
11143 (defun js2-mode-toggle-hide-functions ()
11144 (interactive)
11145 (if js2-mode-functions-hidden
11146 (js2-mode-show-functions)
11147 (js2-mode-hide-functions)))
11148
11149 (defun js2-mode-hide-functions ()
11150 "Hides all non-nested function bodies in the buffer.
11151 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11152 to open an individual entry."
11153 (interactive)
11154 (if js2-mode-buffer-dirty-p
11155 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11156 (if (null js2-mode-ast)
11157 (message "Oops - parsing failed")
11158 (setq js2-mode-functions-hidden t)
11159 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11160
11161 (defun js2-mode-function-hider (n endp)
11162 (when (not endp)
11163 (let ((tt (js2-node-type n))
11164 body beg end)
11165 (cond
11166 ((and (= tt js2-FUNCTION)
11167 (setq body (js2-function-node-body n)))
11168 (setq beg (js2-node-abs-pos body)
11169 end (+ beg (js2-node-len body)))
11170 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11171 nil) ; don't process children of function
11172 (t
11173 t))))) ; keep processing other AST nodes
11174
11175 (defun js2-mode-show-functions ()
11176 "Un-hide any folded function bodies in the buffer."
11177 (interactive)
11178 (setq js2-mode-functions-hidden nil)
11179 (save-excursion
11180 (goto-char (point-min))
11181 (while (/= (goto-char (next-overlay-change (point)))
11182 (point-max))
11183 (dolist (o (overlays-at (point)))
11184 (when (and (overlay-get o 'invisible)
11185 (not (overlay-get o 'comment)))
11186 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11187
11188 (defun js2-mode-hide-comment (n)
11189 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11190 3 ; /**
11191 2)) ; /*
11192 (beg (+ (js2-node-abs-pos n) head))
11193 (end (- (+ beg (js2-node-len n)) head 2))
11194 (o (js2-mode-flag-region beg end 'hide)))
11195 (overlay-put o 'comment t)))
11196
11197 (defun js2-mode-toggle-hide-comments ()
11198 "Folds all block comments in the buffer.
11199 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11200 to open an individual entry."
11201 (interactive)
11202 (if js2-mode-comments-hidden
11203 (js2-mode-show-comments)
11204 (js2-mode-hide-comments)))
11205
11206 (defun js2-mode-hide-comments ()
11207 (interactive)
11208 (if js2-mode-buffer-dirty-p
11209 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11210 (if (null js2-mode-ast)
11211 (message "Oops - parsing failed")
11212 (setq js2-mode-comments-hidden t)
11213 (dolist (n (js2-ast-root-comments js2-mode-ast))
11214 (let ((format (js2-comment-node-format n)))
11215 (when (js2-block-comment-p n)
11216 (js2-mode-hide-comment n))))
11217 (js2-mode-hide-//-comments)))
11218
11219 (defsubst js2-mode-extend-//-comment (direction)
11220 "Find start or end of a block of similar //-comment lines.
11221 DIRECTION is -1 to look back, 1 to look forward.
11222 INDENT is the indentation level to match.
11223 Returns the end-of-line position of the furthest adjacent
11224 //-comment line with the same indentation as the current line.
11225 If there is no such matching line, returns current end of line."
11226 (let ((pos (point-at-eol))
11227 (indent (current-indentation)))
11228 (save-excursion
11229 (save-match-data
11230 (while (and (zerop (forward-line direction))
11231 (looking-at js2-mode-//-comment-re)
11232 (eq indent (length (match-string 1))))
11233 (setq pos (point-at-eol)))
11234 pos))))
11235
11236 (defun js2-mode-hide-//-comments ()
11237 "Fold adjacent 1-line comments, showing only snippet of first one."
11238 (let (beg end)
11239 (save-excursion
11240 (save-match-data
11241 (goto-char (point-min))
11242 (while (re-search-forward js2-mode-//-comment-re nil t)
11243 (setq beg (point)
11244 end (js2-mode-extend-//-comment 1))
11245 (unless (eq beg end)
11246 (overlay-put (js2-mode-flag-region beg end 'hide)
11247 'comment t))
11248 (goto-char end)
11249 (forward-char 1))))))
11250
11251 (defun js2-mode-toggle-//-comment ()
11252 "Fold or un-fold any multi-line //-comment at point.
11253 Caller should have determined that this line starts with a //-comment."
11254 (let* ((beg (point-at-eol))
11255 (end beg))
11256 (save-excursion
11257 (goto-char end)
11258 (if (js2-mode-invisible-overlay-bounds)
11259 (js2-mode-show-element)
11260 ;; else hide the comment
11261 (setq beg (js2-mode-extend-//-comment -1)
11262 end (js2-mode-extend-//-comment 1))
11263 (unless (eq beg end)
11264 (overlay-put (js2-mode-flag-region beg end 'hide)
11265 'comment t))))))
11266
11267 (defun js2-mode-show-comments ()
11268 "Un-hide any hidden comments, leaving other hidden elements alone."
11269 (interactive)
11270 (setq js2-mode-comments-hidden nil)
11271 (save-excursion
11272 (goto-char (point-min))
11273 (while (/= (goto-char (next-overlay-change (point)))
11274 (point-max))
11275 (dolist (o (overlays-at (point)))
11276 (when (overlay-get o 'comment)
11277 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11278
11279 (defun js2-mode-display-warnings-and-errors ()
11280 "Turn on display of warnings and errors."
11281 (interactive)
11282 (setq js2-mode-show-parse-errors t
11283 js2-mode-show-strict-warnings t)
11284 (js2-reparse 'force))
11285
11286 (defun js2-mode-hide-warnings-and-errors ()
11287 "Turn off display of warnings and errors."
11288 (interactive)
11289 (setq js2-mode-show-parse-errors nil
11290 js2-mode-show-strict-warnings nil)
11291 (js2-reparse 'force))
11292
11293 (defun js2-mode-toggle-warnings-and-errors ()
11294 "Toggle the display of warnings and errors.
11295 Some users don't like having warnings/errors reported while they type."
11296 (interactive)
11297 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11298 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11299 (if (interactive-p)
11300 (message "warnings and errors %s"
11301 (if js2-mode-show-parse-errors
11302 "enabled"
11303 "disabled")))
11304 (js2-reparse 'force))
11305
11306 (defun js2-mode-customize ()
11307 (interactive)
11308 (customize-group 'js2-mode))
11309
11310 (defun js2-mode-forward-sexp (&optional arg)
11311 "Move forward across one statement or balanced expression.
11312 With ARG, do it that many times. Negative arg -N means
11313 move backward across N balanced expressions."
11314 (interactive "p")
11315 (setq arg (or arg 1))
11316 (if js2-mode-buffer-dirty-p
11317 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11318 (let (node end (start (point)))
11319 (cond
11320 ;; backward-sexp
11321 ;; could probably make this better for some cases:
11322 ;; - if in statement block (e.g. function body), go to parent
11323 ;; - infix exprs like (foo in bar) - maybe go to beginning
11324 ;; of infix expr if in the right-side expression?
11325 ((and arg (minusp arg))
11326 (dotimes (i (- arg))
11327 (js2-backward-sws)
11328 (forward-char -1) ; enter the node we backed up to
11329 (setq node (js2-node-at-point (point) t))
11330 (goto-char (if node
11331 (js2-node-abs-pos node)
11332 (point-min)))))
11333 (t
11334 ;; forward-sexp
11335 (js2-forward-sws)
11336 (dotimes (i arg)
11337 (js2-forward-sws)
11338 (setq node (js2-node-at-point (point) t)
11339 end (if node (+ (js2-node-abs-pos node)
11340 (js2-node-len node))))
11341 (goto-char (or end (point-max))))))))
11342
11343 (defun js2-next-error (&optional arg reset)
11344 "Move to next parse error.
11345 Typically invoked via \\[next-error].
11346 ARG is the number of errors, forward or backward, to move.
11347 RESET means start over from the beginning."
11348 (interactive "p")
11349 (if (or (null js2-mode-ast)
11350 (and (null (js2-ast-root-errors js2-mode-ast))
11351 (null (js2-ast-root-warnings js2-mode-ast))))
11352 (message "No errors")
11353 (when reset
11354 (goto-char (point-min)))
11355 (let* ((errs (copy-sequence
11356 (append (js2-ast-root-errors js2-mode-ast)
11357 (js2-ast-root-warnings js2-mode-ast))))
11358 (continue t)
11359 (start (point))
11360 (count (or arg 1))
11361 (backward (minusp count))
11362 (sorter (if backward '> '<))
11363 (stopper (if backward '< '>))
11364 (count (abs count))
11365 all-errs
11366 err)
11367 ;; sort by start position
11368 (setq errs (sort errs (lambda (e1 e2)
11369 (funcall sorter (second e1) (second e2))))
11370 all-errs errs)
11371 ;; find nth error with pos > start
11372 (while (and errs continue)
11373 (when (funcall stopper (cadar errs) start)
11374 (setq err (car errs))
11375 (if (zerop (decf count))
11376 (setq continue nil)))
11377 (setq errs (cdr errs)))
11378 (if err
11379 (goto-char (second err))
11380 ;; wrap around to first error
11381 (goto-char (second (car all-errs)))
11382 ;; if we were already on it, echo msg again
11383 (if (= (point) start)
11384 (js2-echo-error (point) (point)))))))
11385
11386 (defun js2-down-mouse-3 ()
11387 "Make right-click move the point to the click location.
11388 This makes right-click context menu operations a bit more intuitive.
11389 The point will not move if the region is active, however, to avoid
11390 destroying the region selection."
11391 (interactive)
11392 (when (and js2-move-point-on-right-click
11393 (not mark-active))
11394 (let ((e last-input-event))
11395 (ignore-errors
11396 (goto-char (cadadr e))))))
11397
11398 (defun js2-mode-create-imenu-index ()
11399 "Return an alist for `imenu--index-alist'."
11400 ;; This is built up in `js2-parse-record-imenu' during parsing.
11401 (when js2-mode-ast
11402 ;; if we have an ast but no recorder, they're requesting a rescan
11403 (unless js2-imenu-recorder
11404 (js2-reparse 'force))
11405 (prog1
11406 (js2-build-imenu-index)
11407 (setq js2-imenu-recorder nil
11408 js2-imenu-function-map nil))))
11409
11410 (defun js2-mode-find-tag ()
11411 "Replacement for `find-tag-default'.
11412 `find-tag-default' returns a ridiculous answer inside comments."
11413 (let (beg end)
11414 (js2-with-underscore-as-word-syntax
11415 (save-excursion
11416 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11417 (looking-back "[A-Za-z0-9_$]"))
11418 (setq beg (progn (forward-word -1) (point))
11419 end (progn (forward-word 1) (point)))
11420 (setq beg (progn (forward-word 1) (point))
11421 end (progn (forward-word -1) (point))))
11422 (replace-regexp-in-string
11423 "[\"']" ""
11424 (buffer-substring-no-properties beg end))))))
11425
11426 (defun js2-mode-forward-sibling ()
11427 "Move to the end of the sibling following point in parent.
11428 Returns non-nil if successful, or nil if there was no following sibling."
11429 (let* ((node (js2-node-at-point))
11430 (parent (js2-mode-find-enclosing-fn node))
11431 sib)
11432 (when (setq sib (js2-node-find-child-after (point) parent))
11433 (goto-char (+ (js2-node-abs-pos sib)
11434 (js2-node-len sib))))))
11435
11436 (defun js2-mode-backward-sibling ()
11437 "Move to the beginning of the sibling node preceding point in parent.
11438 Parent is defined as the enclosing script or function."
11439 (let* ((node (js2-node-at-point))
11440 (parent (js2-mode-find-enclosing-fn node))
11441 sib)
11442 (when (setq sib (js2-node-find-child-before (point) parent))
11443 (goto-char (js2-node-abs-pos sib)))))
11444
11445 (defun js2-beginning-of-defun ()
11446 "Go to line on which current function starts, and return non-nil.
11447 If we're not in a function, go to beginning of previous script-level element."
11448 (interactive)
11449 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11450 pos sib)
11451 (cond
11452 ((and (js2-function-node-p parent)
11453 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11454 (goto-char pos))
11455 (t
11456 (js2-mode-backward-sibling)))))
11457
11458 (defun js2-end-of-defun ()
11459 "Go to the char after the last position of the current function.
11460 If we're not in a function, skips over the next script-level element."
11461 (interactive)
11462 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11463 (if (not (js2-function-node-p parent))
11464 ;; punt: skip over next script-level element beyond point
11465 (js2-mode-forward-sibling)
11466 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11467 (js2-node-len parent)))))))
11468
11469 (defun js2-mark-defun (&optional allow-extend)
11470 "Put mark at end of this function, point at beginning.
11471 The function marked is the one that contains point.
11472
11473 Interactively, if this command is repeated,
11474 or (in Transient Mark mode) if the mark is active,
11475 it marks the next defun after the ones already marked."
11476 (interactive "p")
11477 (let (extended)
11478 (when (and allow-extend
11479 (or (and (eq last-command this-command) (mark t))
11480 (and transient-mark-mode mark-active)))
11481 (let ((sib (save-excursion
11482 (goto-char (mark))
11483 (if (js2-mode-forward-sibling)
11484 (point))))
11485 node)
11486 (if sib
11487 (progn
11488 (set-mark sib)
11489 (setq extended t))
11490 ;; no more siblings - try extending to enclosing node
11491 (goto-char (mark t)))))
11492 (when (not extended)
11493 (let ((node (js2-node-at-point (point) t)) ; skip comments
11494 ast fn stmt parent beg end)
11495 (when (js2-ast-root-p node)
11496 (setq ast node
11497 node (or (js2-node-find-child-after (point) node)
11498 (js2-node-find-child-before (point) node))))
11499 ;; only mark whole buffer if we can't find any children
11500 (if (null node)
11501 (setq node ast))
11502 (if (js2-function-node-p node)
11503 (setq parent node)
11504 (setq fn (js2-mode-find-enclosing-fn node)
11505 stmt (if (or (null fn)
11506 (js2-ast-root-p fn))
11507 (js2-mode-find-first-stmt node))
11508 parent (or stmt fn)))
11509 (setq beg (js2-node-abs-pos parent)
11510 end (+ beg (js2-node-len parent)))
11511 (push-mark beg)
11512 (goto-char end)
11513 (exchange-point-and-mark)))))
11514
11515 (defun js2-narrow-to-defun ()
11516 "Narrow to the function enclosing point."
11517 (interactive)
11518 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11519 (fn (if (js2-script-node-p node)
11520 node
11521 (js2-mode-find-enclosing-fn node)))
11522 (beg (js2-node-abs-pos fn)))
11523 (unless (js2-ast-root-p fn)
11524 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11525
11526 (provide 'js2-mode)
11527
11528 ;;; js2-mode.el ends here