]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Array pattern of the destructuring assignment allows empty element.
[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 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 ;; I'd like to associate errors with nodes, but for now the
2028 ;; easiest thing to do is get the context info from the last token.
2029 (defsubst js2-record-parse-error (msg &optional arg pos len)
2030 (push (list (list msg arg)
2031 (or pos js2-token-beg)
2032 (or len (- js2-token-end js2-token-beg)))
2033 js2-parsed-errors))
2034
2035 (defsubst js2-report-error (msg &optional msg-arg pos len)
2036 "Signal a syntax error or record a parse error."
2037 (if js2-recover-from-parse-errors
2038 (js2-record-parse-error msg msg-arg pos len)
2039 (signal 'js2-syntax-error
2040 (list msg
2041 js2-ts-lineno
2042 (save-excursion
2043 (goto-char js2-ts-cursor)
2044 (current-column))
2045 js2-ts-hit-eof))))
2046
2047 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2048 (if js2-compiler-report-warning-as-error
2049 (js2-report-error msg msg-arg pos len)
2050 (push (list (list msg msg-arg)
2051 (or pos js2-token-beg)
2052 (or len (- js2-token-end js2-token-beg)))
2053 js2-parsed-warnings)))
2054
2055 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2056 (if js2-compiler-strict-mode
2057 (js2-report-warning msg-id msg-arg beg
2058 (and beg end (- end beg)))))
2059
2060 (put 'js2-syntax-error 'error-conditions
2061 '(error syntax-error js2-syntax-error))
2062 (put 'js2-syntax-error 'error-message "Syntax error")
2063
2064 (put 'js2-parse-error 'error-conditions
2065 '(error parse-error js2-parse-error))
2066 (put 'js2-parse-error 'error-message "Parse error")
2067
2068 (defmacro js2-clear-flag (flags flag)
2069 `(setq ,flags (logand ,flags (lognot ,flag))))
2070
2071 (defmacro js2-set-flag (flags flag)
2072 "Logical-or FLAG into FLAGS."
2073 `(setq ,flags (logior ,flags ,flag)))
2074
2075 (defsubst js2-flag-set-p (flags flag)
2076 (/= 0 (logand flags flag)))
2077
2078 (defsubst js2-flag-not-set-p (flags flag)
2079 (zerop (logand flags flag)))
2080
2081 ;; Stolen shamelessly from James Clark's nxml-mode.
2082 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2083 "Evaluate BODY without any text property changes modifying the buffer.
2084 Any text properties changes happen as usual but the changes are not treated as
2085 modifications to the buffer."
2086 (declare (indent 0) (debug t))
2087 (let ((modified (make-symbol "modified")))
2088 `(let ((,modified (buffer-modified-p))
2089 (inhibit-read-only t)
2090 (inhibit-modification-hooks t)
2091 (buffer-undo-list t)
2092 (deactivate-mark nil)
2093 ;; Apparently these avoid file locking problems.
2094 (buffer-file-name nil)
2095 (buffer-file-truename nil))
2096 (unwind-protect
2097 (progn ,@body)
2098 (unless ,modified
2099 (restore-buffer-modified-p nil))))))
2100
2101 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2102 "Evaluate BODY with the _ character set to be word-syntax."
2103 (declare (indent 0) (debug t))
2104 (let ((old-syntax (make-symbol "old-syntax")))
2105 `(let ((,old-syntax (string (char-syntax ?_))))
2106 (unwind-protect
2107 (progn
2108 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2109 ,@body)
2110 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2111
2112 (defsubst js2-char-uppercase-p (c)
2113 "Return t if C is an uppercase character.
2114 Handles unicode and latin chars properly."
2115 (/= c (downcase c)))
2116
2117 (defsubst js2-char-lowercase-p (c)
2118 "Return t if C is an uppercase character.
2119 Handles unicode and latin chars properly."
2120 (/= c (upcase c)))
2121
2122 ;;; AST struct and function definitions
2123
2124 ;; flags for ast node property 'member-type (used for e4x operators)
2125 (defvar js2-property-flag #x1 "property access: element is valid name")
2126 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2127 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2128
2129 (defsubst js2-relpos (pos anchor)
2130 "Convert POS to be relative to ANCHOR.
2131 If POS is nil, returns nil."
2132 (and pos (- pos anchor)))
2133
2134 (defsubst js2-make-pad (indent)
2135 (if (zerop indent)
2136 ""
2137 (make-string (* indent js2-basic-offset) ? )))
2138
2139 (defsubst js2-visit-ast (node callback)
2140 "Visit every node in ast NODE with visitor CALLBACK.
2141
2142 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2143 called twice: once to visit the node, and again after all the node's
2144 children have been processed. The END-P argument is nil on the first
2145 call and non-nil on the second call. The return value of the callback
2146 affects the traversal: if non-nil, the children of NODE are processed.
2147 If the callback returns nil, or if the node has no children, then the
2148 callback is called immediately with a non-nil END-P argument.
2149
2150 The node traversal is approximately lexical-order, although there
2151 are currently no guarantees around this."
2152 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2153 ;; visit the node
2154 (when (funcall callback node nil)
2155 ;; visit the kids
2156 (cond
2157 ((eq vfunc 'js2-visit-none)
2158 nil) ; don't even bother calling it
2159 ;; Each AST node type has to define a `js2-visitor' function
2160 ;; that takes a node and a callback, and calls `js2-visit-ast'
2161 ;; on each child of the node.
2162 (vfunc
2163 (funcall vfunc node callback))
2164 (t
2165 (error "%s does not define a visitor-traversal function"
2166 (aref node 0)))))
2167 ;; call the end-visit
2168 (funcall callback node t)))
2169
2170 (defstruct (js2-node
2171 (:constructor nil)) ; abstract
2172 "Base AST node type."
2173 (type -1) ; token type
2174 (pos -1) ; start position of this AST node in parsed input
2175 (len 1) ; num characters spanned by the node
2176 props ; optional node property list (an alist)
2177 parent) ; link to parent node; null for root
2178
2179 (defsubst js2-node-get-prop (node prop &optional default)
2180 (or (cadr (assoc prop (js2-node-props node))) default))
2181
2182 (defsubst js2-node-set-prop (node prop value)
2183 (setf (js2-node-props node)
2184 (cons (list prop value) (js2-node-props node))))
2185
2186 (defsubst js2-fixup-starts (n nodes)
2187 "Adjust the start positions of NODES to be relative to N.
2188 Any node in the list may be nil, for convenience."
2189 (dolist (node nodes)
2190 (when node
2191 (setf (js2-node-pos node) (- (js2-node-pos node)
2192 (js2-node-pos n))))))
2193
2194 (defsubst js2-node-add-children (parent &rest nodes)
2195 "Set parent node of NODES to PARENT, and return PARENT.
2196 Does nothing if we're not recording parent links.
2197 If any given node in NODES is nil, doesn't record that link."
2198 (js2-fixup-starts parent nodes)
2199 (dolist (node nodes)
2200 (and node
2201 (setf (js2-node-parent node) parent))))
2202
2203 ;; Non-recursive since it's called a frightening number of times.
2204 (defsubst js2-node-abs-pos (n)
2205 (let ((pos (js2-node-pos n)))
2206 (while (setq n (js2-node-parent n))
2207 (setq pos (+ pos (js2-node-pos n))))
2208 pos))
2209
2210 (defsubst js2-node-abs-end (n)
2211 "Return absolute buffer position of end of N."
2212 (+ (js2-node-abs-pos n) (js2-node-len n)))
2213
2214 ;; It's important to make sure block nodes have a lisp list for the
2215 ;; child nodes, to limit printing recursion depth in an AST that
2216 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2217 ;; a sufficiently large vector tree.
2218
2219 (defstruct (js2-block-node
2220 (:include js2-node)
2221 (:constructor nil)
2222 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2223 (pos js2-token-beg)
2224 len
2225 props
2226 kids)))
2227 "A block of statements."
2228 kids) ; a lisp list of the child statement nodes
2229
2230 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2231 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2232
2233 (defsubst js2-visit-block (ast callback)
2234 "Visit the `js2-block-node' children of AST."
2235 (dolist (kid (js2-block-node-kids ast))
2236 (js2-visit-ast kid callback)))
2237
2238 (defun js2-print-block (n i)
2239 (let ((pad (js2-make-pad i)))
2240 (insert pad "{\n")
2241 (dolist (kid (js2-block-node-kids n))
2242 (js2-print-ast kid (1+ i)))
2243 (insert pad "}")))
2244
2245 (defstruct (js2-scope
2246 (:include js2-block-node)
2247 (:constructor nil)
2248 (:constructor make-js2-scope (&key (type js2-BLOCK)
2249 (pos js2-token-beg)
2250 len
2251 kids)))
2252 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2253 ;; I don't have one of those handy, so I'll use an alist for now.
2254 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2255 ;; and is much lighter-weight to construct (both CPU and mem).
2256 ;; The keys are interned strings (symbols) for faster lookup.
2257 ;; Should switch to hybrid alist/hashtable eventually.
2258 symbol-table ; an alist of (symbol . js2-symbol)
2259 parent-scope ; a `js2-scope'
2260 top) ; top-level `js2-scope' (script/function)
2261
2262 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2263 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2264
2265 (defun js2-scope-set-parent-scope (scope parent)
2266 (setf (js2-scope-parent-scope scope) parent
2267 (js2-scope-top scope) (if (null parent)
2268 scope
2269 (js2-scope-top parent))))
2270
2271 (defun js2-node-get-enclosing-scope (node)
2272 "Return the innermost `js2-scope' node surrounding NODE.
2273 Returns nil if there is no enclosing scope node."
2274 (let ((parent (js2-node-parent node)))
2275 (while (not (js2-scope-p parent))
2276 (setq parent (js2-node-parent parent)))
2277 parent))
2278
2279 (defun js2-get-defining-scope (scope name)
2280 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2281 Returns `js2-scope' in which NAME is defined, or nil if not found."
2282 (let ((sym (if (symbolp name)
2283 name
2284 (intern name)))
2285 table
2286 result
2287 (continue t))
2288 (while (and scope continue)
2289 (if (and (setq table (js2-scope-symbol-table scope))
2290 (assq sym table))
2291 (setq continue nil
2292 result scope)
2293 (setq scope (js2-scope-parent-scope scope))))
2294 result))
2295
2296 (defsubst js2-scope-get-symbol (scope name)
2297 "Return symbol table entry for NAME in SCOPE.
2298 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2299 (and (js2-scope-symbol-table scope)
2300 (cdr (assq (if (symbolp name)
2301 name
2302 (intern name))
2303 (js2-scope-symbol-table scope)))))
2304
2305 (defsubst js2-scope-put-symbol (scope name symbol)
2306 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2307 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2308 (let* ((table (js2-scope-symbol-table scope))
2309 (sym (if (symbolp name) name (intern name)))
2310 (entry (assq sym table)))
2311 (if entry
2312 (setcdr entry symbol)
2313 (push (cons sym symbol)
2314 (js2-scope-symbol-table scope)))))
2315
2316 (defstruct (js2-symbol
2317 (:constructor nil)
2318 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2319 "A symbol table entry."
2320 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2321 ;; js2-LET, or js2-CONST
2322 decl-type
2323 name ; string
2324 ast-node) ; a `js2-node'
2325
2326 (defstruct (js2-error-node
2327 (:include js2-node)
2328 (:constructor nil) ; silence emacs21 byte-compiler
2329 (:constructor make-js2-error-node (&key (type js2-ERROR)
2330 (pos js2-token-beg)
2331 len)))
2332 "AST node representing a parse error.")
2333
2334 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2335 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2336
2337 (defstruct (js2-script-node
2338 (:include js2-scope)
2339 (:constructor nil)
2340 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2341 (pos js2-token-beg)
2342 len
2343 var-decls
2344 fun-decls)))
2345 functions ; lisp list of nested functions
2346 regexps ; lisp list of (string . flags)
2347 symbols ; alist (every symbol gets unique index)
2348 (param-count 0)
2349 var-names ; vector of string names
2350 consts ; bool-vector matching var-decls
2351 (temp-number 0)) ; for generating temp variables
2352
2353 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2354 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2355
2356 (defun js2-print-script (node indent)
2357 (dolist (kid (js2-block-node-kids node))
2358 (js2-print-ast kid indent)))
2359
2360 (defstruct (js2-ast-root
2361 (:include js2-script-node)
2362 (:constructor nil)
2363 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2364 (pos js2-token-beg)
2365 len
2366 buffer)))
2367 "The root node of a js2 AST."
2368 buffer ; the source buffer from which the code was parsed
2369 comments ; a lisp list of comments, ordered by start position
2370 errors ; a lisp list of errors found during parsing
2371 warnings ; a lisp list of warnings found during parsing
2372 node-count) ; number of nodes in the tree, including the root
2373
2374 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2375 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2376
2377 (defun js2-visit-ast-root (ast callback)
2378 (dolist (kid (js2-ast-root-kids ast))
2379 (js2-visit-ast kid callback))
2380 (dolist (comment (js2-ast-root-comments ast))
2381 (js2-visit-ast comment callback)))
2382
2383 (defstruct (js2-comment-node
2384 (:include js2-node)
2385 (:constructor nil)
2386 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2387 (pos js2-token-beg)
2388 len
2389 (format js2-ts-comment-type))))
2390 format) ; 'line, 'block, 'jsdoc or 'html
2391
2392 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2393 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2394
2395 (defun js2-print-comment (n i)
2396 ;; We really ought to link end-of-line comments to their nodes.
2397 ;; Or maybe we could add a new comment type, 'endline.
2398 (insert (js2-make-pad i)
2399 (js2-node-string n)))
2400
2401 (defstruct (js2-expr-stmt-node
2402 (:include js2-node)
2403 (:constructor nil)
2404 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2405 (pos js2-ts-cursor)
2406 len
2407 expr)))
2408 "An expression statement."
2409 expr)
2410
2411 (defsubst js2-expr-stmt-node-set-has-result (node)
2412 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2413 (setf (js2-node-type node) js2-EXPR_RESULT))
2414
2415 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2416 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2417
2418 (defun js2-visit-expr-stmt-node (n v)
2419 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2420
2421 (defun js2-print-expr-stmt-node (n indent)
2422 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2423 (insert ";\n"))
2424
2425 (defstruct (js2-loop-node
2426 (:include js2-scope)
2427 (:constructor nil))
2428 "Abstract supertype of loop nodes."
2429 body ; a `js2-block-node'
2430 lp ; position of left-paren, nil if omitted
2431 rp) ; position of right-paren, nil if omitted
2432
2433 (defstruct (js2-do-node
2434 (:include js2-loop-node)
2435 (:constructor nil)
2436 (:constructor make-js2-do-node (&key (type js2-DO)
2437 (pos js2-token-beg)
2438 len
2439 body
2440 condition
2441 while-pos
2442 lp
2443 rp)))
2444 "AST node for do-loop."
2445 condition ; while (expression)
2446 while-pos) ; buffer position of 'while' keyword
2447
2448 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2449 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2450
2451 (defun js2-visit-do-node (n v)
2452 (js2-visit-ast (js2-do-node-body n) v)
2453 (js2-visit-ast (js2-do-node-condition n) v))
2454
2455 (defun js2-print-do-node (n i)
2456 (let ((pad (js2-make-pad i)))
2457 (insert pad "do {\n")
2458 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2459 (js2-print-ast kid (1+ i)))
2460 (insert pad "} while (")
2461 (js2-print-ast (js2-do-node-condition n) 0)
2462 (insert ");\n")))
2463
2464 (defstruct (js2-while-node
2465 (:include js2-loop-node)
2466 (:constructor nil)
2467 (:constructor make-js2-while-node (&key (type js2-WHILE)
2468 (pos js2-token-beg)
2469 len
2470 body
2471 condition
2472 lp
2473 rp)))
2474 "AST node for while-loop."
2475 condition) ; while-condition
2476
2477 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2478 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2479
2480 (defun js2-visit-while-node (n v)
2481 (js2-visit-ast (js2-while-node-condition n) v)
2482 (js2-visit-ast (js2-while-node-body n) v))
2483
2484 (defun js2-print-while-node (n i)
2485 (let ((pad (js2-make-pad i)))
2486 (insert pad "while (")
2487 (js2-print-ast (js2-while-node-condition n) 0)
2488 (insert ") {\n")
2489 (js2-print-body (js2-while-node-body n) (1+ i))
2490 (insert pad "}\n")))
2491
2492 (defstruct (js2-for-node
2493 (:include js2-loop-node)
2494 (:constructor nil)
2495 (:constructor make-js2-for-node (&key (type js2-FOR)
2496 (pos js2-ts-cursor)
2497 len
2498 body
2499 init
2500 condition
2501 update
2502 lp
2503 rp)))
2504 "AST node for a C-style for-loop."
2505 init ; initialization expression
2506 condition ; loop condition
2507 update) ; update clause
2508
2509 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2510 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2511
2512 (defun js2-visit-for-node (n v)
2513 (js2-visit-ast (js2-for-node-init n) v)
2514 (js2-visit-ast (js2-for-node-condition n) v)
2515 (js2-visit-ast (js2-for-node-update n) v)
2516 (js2-visit-ast (js2-for-node-body n) v))
2517
2518 (defun js2-print-for-node (n i)
2519 (let ((pad (js2-make-pad i)))
2520 (insert pad "for (")
2521 (js2-print-ast (js2-for-node-init n) 0)
2522 (insert "; ")
2523 (js2-print-ast (js2-for-node-condition n) 0)
2524 (insert "; ")
2525 (js2-print-ast (js2-for-node-update n) 0)
2526 (insert ") {\n")
2527 (js2-print-body (js2-for-node-body n) (1+ i))
2528 (insert pad "}\n")))
2529
2530 (defstruct (js2-for-in-node
2531 (:include js2-loop-node)
2532 (:constructor nil)
2533 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2534 (pos js2-ts-cursor)
2535 len
2536 body
2537 iterator
2538 object
2539 in-pos
2540 each-pos
2541 foreach-p
2542 lp
2543 rp)))
2544 "AST node for a for..in loop."
2545 iterator ; [var] foo in ...
2546 object ; object over which we're iterating
2547 in-pos ; buffer position of 'in' keyword
2548 each-pos ; buffer position of 'each' keyword, if foreach-p
2549 foreach-p) ; t if it's a for-each loop
2550
2551 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2552 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2553
2554 (defun js2-visit-for-in-node (n v)
2555 (js2-visit-ast (js2-for-in-node-iterator n) v)
2556 (js2-visit-ast (js2-for-in-node-object n) v)
2557 (js2-visit-ast (js2-for-in-node-body n) v))
2558
2559 (defun js2-print-for-in-node (n i)
2560 (let ((pad (js2-make-pad i))
2561 (foreach (js2-for-in-node-foreach-p n)))
2562 (insert pad "for ")
2563 (if foreach
2564 (insert "each "))
2565 (insert "(")
2566 (js2-print-ast (js2-for-in-node-iterator n) 0)
2567 (insert " in ")
2568 (js2-print-ast (js2-for-in-node-object n) 0)
2569 (insert ") {\n")
2570 (js2-print-body (js2-for-in-node-body n) (1+ i))
2571 (insert pad "}\n")))
2572
2573 (defstruct (js2-return-node
2574 (:include js2-node)
2575 (:constructor nil)
2576 (:constructor make-js2-return-node (&key (type js2-RETURN)
2577 (pos js2-ts-cursor)
2578 len
2579 retval)))
2580 "AST node for a return statement."
2581 retval) ; expression to return, or 'undefined
2582
2583 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2584 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2585
2586 (defun js2-visit-return-node (n v)
2587 (if (js2-return-node-retval n)
2588 (js2-visit-ast (js2-return-node-retval n) v)))
2589
2590 (defun js2-print-return-node (n i)
2591 (insert (js2-make-pad i) "return")
2592 (when (js2-return-node-retval n)
2593 (insert " ")
2594 (js2-print-ast (js2-return-node-retval n) 0))
2595 (insert ";\n"))
2596
2597 (defstruct (js2-if-node
2598 (:include js2-node)
2599 (:constructor nil)
2600 (:constructor make-js2-if-node (&key (type js2-IF)
2601 (pos js2-ts-cursor)
2602 len
2603 condition
2604 then-part
2605 else-pos
2606 else-part
2607 lp
2608 rp)))
2609 "AST node for an if-statement."
2610 condition ; expression
2611 then-part ; statement or block
2612 else-pos ; optional buffer position of 'else' keyword
2613 else-part ; optional statement or block
2614 lp ; position of left-paren, nil if omitted
2615 rp) ; position of right-paren, nil if omitted
2616
2617 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2618 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2619
2620 (defun js2-visit-if-node (n v)
2621 (js2-visit-ast (js2-if-node-condition n) v)
2622 (js2-visit-ast (js2-if-node-then-part n) v)
2623 (if (js2-if-node-else-part n)
2624 (js2-visit-ast (js2-if-node-else-part n) v)))
2625
2626 (defun js2-print-if-node (n i)
2627 (let ((pad (js2-make-pad i))
2628 (then-part (js2-if-node-then-part n))
2629 (else-part (js2-if-node-else-part n)))
2630 (insert pad "if (")
2631 (js2-print-ast (js2-if-node-condition n) 0)
2632 (insert ") {\n")
2633 (js2-print-body then-part (1+ i))
2634 (insert pad "}")
2635 (cond
2636 ((not else-part)
2637 (insert "\n"))
2638 ((js2-if-node-p else-part)
2639 (insert " else ")
2640 (js2-print-body else-part i))
2641 (t
2642 (insert " else {\n")
2643 (js2-print-body else-part (1+ i))
2644 (insert pad "}\n")))))
2645
2646 (defstruct (js2-try-node
2647 (:include js2-node)
2648 (:constructor nil)
2649 (:constructor make-js2-try-node (&key (type js2-TRY)
2650 (pos js2-ts-cursor)
2651 len
2652 try-block
2653 catch-clauses
2654 finally-block)))
2655 "AST node for a try-statement."
2656 try-block
2657 catch-clauses ; a lisp list of `js2-catch-node'
2658 finally-block) ; a `js2-finally-node'
2659
2660 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2661 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2662
2663 (defun js2-visit-try-node (n v)
2664 (js2-visit-ast (js2-try-node-try-block n) v)
2665 (dolist (clause (js2-try-node-catch-clauses n))
2666 (js2-visit-ast clause v))
2667 (if (js2-try-node-finally-block n)
2668 (js2-visit-ast (js2-try-node-finally-block n) v)))
2669
2670 (defun js2-print-try-node (n i)
2671 (let ((pad (js2-make-pad i))
2672 (catches (js2-try-node-catch-clauses n))
2673 (finally (js2-try-node-finally-block n)))
2674 (insert pad "try {\n")
2675 (js2-print-body (js2-try-node-try-block n) (1+ i))
2676 (insert pad "}")
2677 (when catches
2678 (dolist (catch catches)
2679 (js2-print-ast catch i)))
2680 (if finally
2681 (js2-print-ast finally i)
2682 (insert "\n"))))
2683
2684 (defstruct (js2-catch-node
2685 (:include js2-node)
2686 (:constructor nil)
2687 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2688 (pos js2-ts-cursor)
2689 len
2690 var-name
2691 guard-kwd
2692 guard-expr
2693 block
2694 lp
2695 rp)))
2696 "AST node for a catch clause."
2697 var-name ; a `js2-name-node'
2698 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2699 guard-expr ; catch condition, a `js2-node'
2700 block ; statements, a `js2-block-node'
2701 lp ; buffer position of left-paren, nil if omitted
2702 rp) ; buffer position of right-paren, nil if omitted
2703
2704 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2705 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2706
2707 (defun js2-visit-catch-node (n v)
2708 (js2-visit-ast (js2-catch-node-var-name n) v)
2709 (when (js2-catch-node-guard-kwd n)
2710 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2711 (js2-visit-ast (js2-catch-node-block n) v))
2712
2713 (defun js2-print-catch-node (n i)
2714 (let ((pad (js2-make-pad i))
2715 (guard-kwd (js2-catch-node-guard-kwd n))
2716 (guard-expr (js2-catch-node-guard-expr n)))
2717 (insert " catch (")
2718 (js2-print-ast (js2-catch-node-var-name n) 0)
2719 (when guard-kwd
2720 (insert " if ")
2721 (js2-print-ast guard-expr 0))
2722 (insert ") {\n")
2723 (js2-print-body (js2-catch-node-block n) (1+ i))
2724 (insert pad "}")))
2725
2726 (defstruct (js2-finally-node
2727 (:include js2-node)
2728 (:constructor nil)
2729 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2730 (pos js2-ts-cursor)
2731 len
2732 body)))
2733 "AST node for a finally clause."
2734 body) ; a `js2-node', often but not always a block node
2735
2736 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2737 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2738
2739 (defun js2-visit-finally-node (n v)
2740 (js2-visit-ast (js2-finally-node-body n) v))
2741
2742 (defun js2-print-finally-node (n i)
2743 (let ((pad (js2-make-pad i)))
2744 (insert " finally {\n")
2745 (js2-print-body (js2-finally-node-body n) (1+ i))
2746 (insert pad "}\n")))
2747
2748 (defstruct (js2-switch-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2752 (pos js2-ts-cursor)
2753 len
2754 discriminant
2755 cases
2756 lp
2757 rp)))
2758 "AST node for a switch statement."
2759 discriminant ; a `js2-node' (switch expression)
2760 cases ; a lisp list of `js2-case-node'
2761 lp ; position of open-paren for discriminant, nil if omitted
2762 rp) ; position of close-paren for discriminant, nil if omitted
2763
2764 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2765 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2766
2767 (defun js2-visit-switch-node (n v)
2768 (js2-visit-ast (js2-switch-node-discriminant n) v)
2769 (dolist (c (js2-switch-node-cases n))
2770 (js2-visit-ast c v)))
2771
2772 (defun js2-print-switch-node (n i)
2773 (let ((pad (js2-make-pad i))
2774 (cases (js2-switch-node-cases n)))
2775 (insert pad "switch (")
2776 (js2-print-ast (js2-switch-node-discriminant n) 0)
2777 (insert ") {\n")
2778 (dolist (case cases)
2779 (js2-print-ast case i))
2780 (insert pad "}\n")))
2781
2782 (defstruct (js2-case-node
2783 (:include js2-block-node)
2784 (:constructor nil)
2785 (:constructor make-js2-case-node (&key (type js2-CASE)
2786 (pos js2-ts-cursor)
2787 len
2788 kids
2789 expr)))
2790 "AST node for a case clause of a switch statement."
2791 expr) ; the case expression (nil for default)
2792
2793 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2794 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2795
2796 (defun js2-visit-case-node (n v)
2797 (if (js2-case-node-expr n) ; nil for default: case
2798 (js2-visit-ast (js2-case-node-expr n) v))
2799 (js2-visit-block n v))
2800
2801 (defun js2-print-case-node (n i)
2802 (let ((pad (js2-make-pad i))
2803 (expr (js2-case-node-expr n)))
2804 (insert pad)
2805 (if (null expr)
2806 (insert "default:\n")
2807 (insert "case ")
2808 (js2-print-ast expr 0)
2809 (insert ":\n"))
2810 (dolist (kid (js2-case-node-kids n))
2811 (js2-print-ast kid (1+ i)))))
2812
2813 (defstruct (js2-throw-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 (:constructor make-js2-throw-node (&key (type js2-THROW)
2817 (pos js2-ts-cursor)
2818 len
2819 expr)))
2820 "AST node for a throw statement."
2821 expr) ; the expression to throw
2822
2823 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2824 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2825
2826 (defun js2-visit-throw-node (n v)
2827 (js2-visit-ast (js2-throw-node-expr n) v))
2828
2829 (defun js2-print-throw-node (n i)
2830 (insert (js2-make-pad i) "throw ")
2831 (js2-print-ast (js2-throw-node-expr n) 0)
2832 (insert ";\n"))
2833
2834 (defstruct (js2-with-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-with-node (&key (type js2-WITH)
2838 (pos js2-ts-cursor)
2839 len
2840 object
2841 body
2842 lp
2843 rp)))
2844 "AST node for a with-statement."
2845 object
2846 body
2847 lp ; buffer position of left-paren around object, nil if omitted
2848 rp) ; buffer position of right-paren around object, nil if omitted
2849
2850 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2851 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2852
2853 (defun js2-visit-with-node (n v)
2854 (js2-visit-ast (js2-with-node-object n) v)
2855 (js2-visit-ast (js2-with-node-body n) v))
2856
2857 (defun js2-print-with-node (n i)
2858 (let ((pad (js2-make-pad i)))
2859 (insert pad "with (")
2860 (js2-print-ast (js2-with-node-object n) 0)
2861 (insert ") {\n")
2862 (js2-print-body (js2-with-node-body n) (1+ i))
2863 (insert pad "}\n")))
2864
2865 (defstruct (js2-label-node
2866 (:include js2-node)
2867 (:constructor nil)
2868 (:constructor make-js2-label-node (&key (type js2-LABEL)
2869 (pos js2-ts-cursor)
2870 len
2871 name)))
2872 "AST node for a statement label or case label."
2873 name ; a string
2874 loop) ; for validating and code-generating continue-to-label
2875
2876 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2877 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2878
2879 (defun js2-print-label (n i)
2880 (insert (js2-make-pad i)
2881 (js2-label-node-name n)
2882 ":\n"))
2883
2884 (defstruct (js2-labeled-stmt-node
2885 (:include js2-node)
2886 (:constructor nil)
2887 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2888 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2889 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2890 (pos js2-ts-cursor)
2891 len
2892 labels
2893 stmt)))
2894 "AST node for a statement with one or more labels.
2895 Multiple labels for a statement are collapsed into the labels field."
2896 labels ; lisp list of `js2-label-node'
2897 stmt) ; the statement these labels are for
2898
2899 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2900 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2901
2902 (defun js2-get-label-by-name (lbl-stmt name)
2903 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2904 Returns nil if no such label is in the list."
2905 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2906 result)
2907 (while (and label-list (not result))
2908 (if (string= (js2-label-node-name (car label-list)) name)
2909 (setq result (car label-list))
2910 (setq label-list (cdr label-list))))
2911 result))
2912
2913 (defun js2-visit-labeled-stmt (n v)
2914 (dolist (label (js2-labeled-stmt-node-labels n))
2915 (js2-visit-ast label v))
2916 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2917
2918 (defun js2-print-labeled-stmt (n i)
2919 (dolist (label (js2-labeled-stmt-node-labels n))
2920 (js2-print-ast label i))
2921 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2922
2923 (defun js2-labeled-stmt-node-contains (node label)
2924 "Return t if NODE contains LABEL in its label set.
2925 NODE is a `js2-labels-node'. LABEL is an identifier."
2926 (loop for nl in (js2-labeled-stmt-node-labels node)
2927 if (string= label (js2-label-node-name nl))
2928 return t
2929 finally return nil))
2930
2931 (defsubst js2-labeled-stmt-node-add-label (node label)
2932 "Add a `js2-label-node' to the label set for this statement."
2933 (setf (js2-labeled-stmt-node-labels node)
2934 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2935
2936 (defstruct (js2-jump-node
2937 (:include js2-node)
2938 (:constructor nil))
2939 "Abstract supertype of break and continue nodes."
2940 label ; `js2-name-node' for location of label identifier, if present
2941 target) ; target js2-labels-node or loop/switch statement
2942
2943 (defun js2-visit-jump-node (n v)
2944 ;; we don't visit the target, since it's a back-link
2945 (if (js2-jump-node-label n)
2946 (js2-visit-ast (js2-jump-node-label n) v)))
2947
2948 (defstruct (js2-break-node
2949 (:include js2-jump-node)
2950 (:constructor nil)
2951 (:constructor make-js2-break-node (&key (type js2-BREAK)
2952 (pos js2-ts-cursor)
2953 len
2954 label
2955 target)))
2956 "AST node for a break statement.
2957 The label field is a `js2-name-node', possibly nil, for the named label
2958 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2959 is the target of the break - a label node or enclosing loop/switch statement.")
2960
2961 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2962 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2963
2964 (defun js2-print-break-node (n i)
2965 (insert (js2-make-pad i) "break")
2966 (when (js2-break-node-label n)
2967 (insert " ")
2968 (js2-print-ast (js2-break-node-label n) 0))
2969 (insert ";\n"))
2970
2971 (defstruct (js2-continue-node
2972 (:include js2-jump-node)
2973 (:constructor nil)
2974 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2975 (pos js2-ts-cursor)
2976 len
2977 label
2978 target)))
2979 "AST node for a continue statement.
2980 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2981 It is nil if continue specifies no label. The target field is the jump target:
2982 a `js2-label-node' or the innermost enclosing loop.")
2983
2984 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2985 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2986
2987 (defun js2-print-continue-node (n i)
2988 (insert (js2-make-pad i) "continue")
2989 (when (js2-continue-node-label n)
2990 (insert " ")
2991 (js2-print-ast (js2-continue-node-label n) 0))
2992 (insert ";\n"))
2993
2994 (defstruct (js2-function-node
2995 (:include js2-script-node)
2996 (:constructor nil)
2997 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2998 (pos js2-ts-cursor)
2999 len
3000 (ftype 'FUNCTION)
3001 (form 'FUNCTION_STATEMENT)
3002 (name "")
3003 params
3004 body
3005 lp
3006 rp)))
3007 "AST node for a function declaration.
3008 The `params' field is a lisp list of nodes. Each node is either a simple
3009 `js2-name-node', or if it's a destructuring-assignment parameter, a
3010 `js2-array-node' or `js2-object-node'."
3011 ftype ; FUNCTION, GETTER or SETTER
3012 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3013 name ; function name (a `js2-name-node', or nil if anonymous)
3014 params ; a lisp list of destructuring forms or simple name nodes
3015 body ; a `js2-block-node' or expression node (1.8 only)
3016 lp ; position of arg-list open-paren, or nil if omitted
3017 rp ; position of arg-list close-paren, or nil if omitted
3018 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3019 needs-activation ; t if we need an activation object for this frame
3020 is-generator ; t if this function contains a yield
3021 member-expr) ; nonstandard Ecma extension from Rhino
3022
3023 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3024 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3025
3026 (defun js2-visit-function-node (n v)
3027 (if (js2-function-node-name n)
3028 (js2-visit-ast (js2-function-node-name n) v))
3029 (dolist (p (js2-function-node-params n))
3030 (js2-visit-ast p v))
3031 (when (js2-function-node-body n)
3032 (js2-visit-ast (js2-function-node-body n) v)))
3033
3034 (defun js2-print-function-node (n i)
3035 (let ((pad (js2-make-pad i))
3036 (getter (js2-node-get-prop n 'GETTER_SETTER))
3037 (name (js2-function-node-name n))
3038 (params (js2-function-node-params n))
3039 (body (js2-function-node-body n))
3040 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3041 (unless getter
3042 (insert pad "function"))
3043 (when name
3044 (insert " ")
3045 (js2-print-ast name 0))
3046 (insert "(")
3047 (loop with len = (length params)
3048 for param in params
3049 for count from 1
3050 do
3051 (js2-print-ast param 0)
3052 (if (< count len)
3053 (insert ", ")))
3054 (insert ") {")
3055 (unless expr
3056 (insert "\n"))
3057 ;; TODO: fix this to be smarter about indenting, etc.
3058 (js2-print-body body (1+ i))
3059 (insert pad "}")
3060 (unless expr
3061 (insert "\n"))))
3062
3063 (defsubst js2-function-name (node)
3064 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3065 (and (js2-function-node-name node)
3066 (js2-name-node-name (js2-function-node-name node))))
3067
3068 ;; Having this be an expression node makes it more flexible.
3069 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3070 ;; that work better if you assume it's an expression. Whenever we have
3071 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3072 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3073 (defstruct (js2-var-decl-node
3074 (:include js2-node)
3075 (:constructor nil)
3076 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3077 (pos js2-token-beg)
3078 len
3079 kids
3080 decl-type)))
3081 "AST node for a variable declaration list (VAR, CONST or LET).
3082 The node bounds differ depending on the declaration type. For VAR or
3083 CONST declarations, the bounds include the var/const keyword. For LET
3084 declarations, the node begins at the position of the first child."
3085 kids ; a lisp list of `js2-var-init-node' structs.
3086 decl-type) ; js2-VAR, js2-CONST or js2-LET
3087
3088 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3089 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3090
3091 (defun js2-visit-var-decl (n v)
3092 (dolist (kid (js2-var-decl-node-kids n))
3093 (js2-visit-ast kid v)))
3094
3095 (defun js2-print-var-decl (n i)
3096 (let ((pad (js2-make-pad i))
3097 (tt (js2-var-decl-node-decl-type n)))
3098 (insert pad)
3099 (insert (cond
3100 ((= tt js2-VAR) "var ")
3101 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3102 ((= tt js2-CONST) "const ")
3103 (t
3104 (error "malformed var-decl node"))))
3105 (loop with kids = (js2-var-decl-node-kids n)
3106 with len = (length kids)
3107 for kid in kids
3108 for count from 1
3109 do
3110 (js2-print-ast kid 0)
3111 (if (< count len)
3112 (insert ", ")))))
3113
3114 (defstruct (js2-var-init-node
3115 (:include js2-node)
3116 (:constructor nil)
3117 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3118 (pos js2-ts-cursor)
3119 len
3120 target
3121 initializer)))
3122 "AST node for a variable declaration.
3123 The type field will be js2-CONST for a const decl."
3124 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3125 initializer) ; initializer expression, a `js2-node'
3126
3127 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3128 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3129
3130 (defun js2-visit-var-init-node (n v)
3131 (js2-visit-ast (js2-var-init-node-target n) v)
3132 (if (js2-var-init-node-initializer n)
3133 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3134
3135 (defun js2-print-var-init-node (n i)
3136 (let ((pad (js2-make-pad i))
3137 (name (js2-var-init-node-target n))
3138 (init (js2-var-init-node-initializer n)))
3139 (insert pad)
3140 (js2-print-ast name 0)
3141 (when init
3142 (insert " = ")
3143 (js2-print-ast init 0))))
3144
3145 (defstruct (js2-cond-node
3146 (:include js2-node)
3147 (:constructor nil)
3148 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3149 (pos js2-ts-cursor)
3150 len
3151 test-expr
3152 true-expr
3153 false-expr
3154 q-pos
3155 c-pos)))
3156 "AST node for the ternary operator"
3157 test-expr
3158 true-expr
3159 false-expr
3160 q-pos ; buffer position of ?
3161 c-pos) ; buffer position of :
3162
3163 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3164 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3165
3166 (defun js2-visit-cond-node (n v)
3167 (js2-visit-ast (js2-cond-node-test-expr n) v)
3168 (js2-visit-ast (js2-cond-node-true-expr n) v)
3169 (js2-visit-ast (js2-cond-node-false-expr n) v))
3170
3171 (defun js2-print-cond-node (n i)
3172 (let ((pad (js2-make-pad i)))
3173 (insert pad)
3174 (js2-print-ast (js2-cond-node-test-expr n) 0)
3175 (insert " ? ")
3176 (js2-print-ast (js2-cond-node-true-expr n) 0)
3177 (insert " : ")
3178 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3179
3180 (defstruct (js2-infix-node
3181 (:include js2-node)
3182 (:constructor nil)
3183 (:constructor make-js2-infix-node (&key type
3184 (pos js2-ts-cursor)
3185 len
3186 op-pos
3187 left
3188 right)))
3189 "Represents infix expressions.
3190 Includes assignment ops like `|=', and the comma operator.
3191 The type field inherited from `js2-node' holds the operator."
3192 op-pos ; buffer position where operator begins
3193 left ; any `js2-node'
3194 right) ; any `js2-node'
3195
3196 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3197 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3198
3199 (defun js2-visit-infix-node (n v)
3200 (when (js2-infix-node-left n)
3201 (js2-visit-ast (js2-infix-node-left n) v))
3202 (when (js2-infix-node-right n)
3203 (js2-visit-ast (js2-infix-node-right n) v)))
3204
3205 (defconst js2-operator-tokens
3206 (let ((table (make-hash-table :test 'eq))
3207 (tokens
3208 (list (cons js2-IN "in")
3209 (cons js2-TYPEOF "typeof")
3210 (cons js2-INSTANCEOF "instanceof")
3211 (cons js2-DELPROP "delete")
3212 (cons js2-COMMA ",")
3213 (cons js2-COLON ":")
3214 (cons js2-OR "||")
3215 (cons js2-AND "&&")
3216 (cons js2-INC "++")
3217 (cons js2-DEC "--")
3218 (cons js2-BITOR "|")
3219 (cons js2-BITXOR "^")
3220 (cons js2-BITAND "&")
3221 (cons js2-EQ "==")
3222 (cons js2-NE "!=")
3223 (cons js2-LT "<")
3224 (cons js2-LE "<=")
3225 (cons js2-GT ">")
3226 (cons js2-GE ">=")
3227 (cons js2-LSH "<<")
3228 (cons js2-RSH ">>")
3229 (cons js2-URSH ">>>")
3230 (cons js2-ADD "+") ; infix plus
3231 (cons js2-SUB "-") ; infix minus
3232 (cons js2-MUL "*")
3233 (cons js2-DIV "/")
3234 (cons js2-MOD "%")
3235 (cons js2-NOT "!")
3236 (cons js2-BITNOT "~")
3237 (cons js2-POS "+") ; unary plus
3238 (cons js2-NEG "-") ; unary minus
3239 (cons js2-SHEQ "===") ; shallow equality
3240 (cons js2-SHNE "!==") ; shallow inequality
3241 (cons js2-ASSIGN "=")
3242 (cons js2-ASSIGN_BITOR "|=")
3243 (cons js2-ASSIGN_BITXOR "^=")
3244 (cons js2-ASSIGN_BITAND "&=")
3245 (cons js2-ASSIGN_LSH "<<=")
3246 (cons js2-ASSIGN_RSH ">>=")
3247 (cons js2-ASSIGN_URSH ">>>=")
3248 (cons js2-ASSIGN_ADD "+=")
3249 (cons js2-ASSIGN_SUB "-=")
3250 (cons js2-ASSIGN_MUL "*=")
3251 (cons js2-ASSIGN_DIV "/=")
3252 (cons js2-ASSIGN_MOD "%="))))
3253 (loop for (k . v) in tokens do
3254 (puthash k v table))
3255 table))
3256
3257 (defun js2-print-infix-node (n i)
3258 (let* ((tt (js2-node-type n))
3259 (op (gethash tt js2-operator-tokens)))
3260 (unless op
3261 (error "unrecognized infix operator %s" (js2-node-type n)))
3262 (insert (js2-make-pad i))
3263 (js2-print-ast (js2-infix-node-left n) 0)
3264 (unless (= tt js2-COMMA)
3265 (insert " "))
3266 (insert op)
3267 (insert " ")
3268 (js2-print-ast (js2-infix-node-right n) 0)))
3269
3270 (defstruct (js2-assign-node
3271 (:include js2-infix-node)
3272 (:constructor nil)
3273 (:constructor make-js2-assign-node (&key type
3274 (pos js2-ts-cursor)
3275 len
3276 op-pos
3277 left
3278 right)))
3279 "Represents any assignment.
3280 The type field holds the actual assignment operator.")
3281
3282 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3283 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3284
3285 (defstruct (js2-unary-node
3286 (:include js2-node)
3287 (:constructor nil)
3288 (:constructor make-js2-unary-node (&key type ; required
3289 (pos js2-ts-cursor)
3290 len
3291 operand)))
3292 "AST node type for unary operator nodes.
3293 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3294 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3295 property is added if the operator follows the operand."
3296 operand) ; a `js2-node' expression
3297
3298 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3299 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3300
3301 (defun js2-visit-unary-node (n v)
3302 (js2-visit-ast (js2-unary-node-operand n) v))
3303
3304 (defun js2-print-unary-node (n i)
3305 (let* ((tt (js2-node-type n))
3306 (op (gethash tt js2-operator-tokens))
3307 (postfix (js2-node-get-prop n 'postfix)))
3308 (unless op
3309 (error "unrecognized unary operator %s" tt))
3310 (insert (js2-make-pad i))
3311 (unless postfix
3312 (insert op))
3313 (if (or (= tt js2-TYPEOF)
3314 (= tt js2-DELPROP))
3315 (insert " "))
3316 (js2-print-ast (js2-unary-node-operand n) 0)
3317 (when postfix
3318 (insert op))))
3319
3320 (defstruct (js2-let-node
3321 (:include js2-scope)
3322 (:constructor nil)
3323 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3324 (pos js2-token-beg)
3325 len
3326 vars
3327 body
3328 lp
3329 rp)))
3330 "AST node for a let expression or a let statement.
3331 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3332 vars ; a `js2-var-decl-node'
3333 body ; a `js2-node' representing the expression or body block
3334 lp
3335 rp)
3336
3337 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3338 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3339
3340 (defun js2-visit-let-node (n v)
3341 (when (js2-let-node-vars n)
3342 (js2-visit-ast (js2-let-node-vars n) v))
3343 (when (js2-let-node-body n)
3344 (js2-visit-ast (js2-let-node-body n) v)))
3345
3346 (defun js2-print-let-node (n i)
3347 (insert (js2-make-pad i) "let (")
3348 (js2-print-ast (js2-let-node-vars n) 0)
3349 (insert ") ")
3350 (js2-print-ast (js2-let-node-body n) i))
3351
3352 (defstruct (js2-keyword-node
3353 (:include js2-node)
3354 (:constructor nil)
3355 (:constructor make-js2-keyword-node (&key type
3356 (pos js2-token-beg)
3357 (len (- js2-ts-cursor pos)))))
3358 "AST node representing a literal keyword such as `null'.
3359 Used for `null', `this', `true', `false' and `debugger'.
3360 The node type is set to js2-NULL, js2-THIS, etc.")
3361
3362 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3363 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3364
3365 (defun js2-print-keyword-node (n i)
3366 (insert (js2-make-pad i)
3367 (let ((tt (js2-node-type n)))
3368 (cond
3369 ((= tt js2-THIS) "this")
3370 ((= tt js2-NULL) "null")
3371 ((= tt js2-TRUE) "true")
3372 ((= tt js2-FALSE) "false")
3373 ((= tt js2-DEBUGGER) "debugger")
3374 (t (error "Invalid keyword literal type: %d" tt))))))
3375
3376 (defsubst js2-this-node-p (node)
3377 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3378 (eq (js2-node-type node) js2-THIS))
3379
3380 (defstruct (js2-new-node
3381 (:include js2-node)
3382 (:constructor nil)
3383 (:constructor make-js2-new-node (&key (type js2-NEW)
3384 (pos js2-token-beg)
3385 len
3386 target
3387 args
3388 initializer
3389 lp
3390 rp)))
3391 "AST node for new-expression such as new Foo()."
3392 target ; an identifier or reference
3393 args ; a lisp list of argument nodes
3394 lp ; position of left-paren, nil if omitted
3395 rp ; position of right-paren, nil if omitted
3396 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3397
3398 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3399 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3400
3401 (defun js2-visit-new-node (n v)
3402 (js2-visit-ast (js2-new-node-target n) v)
3403 (dolist (arg (js2-new-node-args n))
3404 (js2-visit-ast arg v))
3405 (when (js2-new-node-initializer n)
3406 (js2-visit-ast (js2-new-node-initializer n) v)))
3407
3408 (defun js2-print-new-node (n i)
3409 (insert (js2-make-pad i) "new ")
3410 (js2-print-ast (js2-new-node-target n))
3411 (insert "(")
3412 (js2-print-list (js2-new-node-args n))
3413 (insert ")")
3414 (when (js2-new-node-initializer n)
3415 (insert " ")
3416 (js2-print-ast (js2-new-node-initializer n))))
3417
3418 (defstruct (js2-name-node
3419 (:include js2-node)
3420 (:constructor nil)
3421 (:constructor make-js2-name-node (&key (type js2-NAME)
3422 (pos js2-token-beg)
3423 (len (- js2-ts-cursor
3424 js2-token-beg))
3425 (name js2-ts-string))))
3426 "AST node for a JavaScript identifier"
3427 name ; a string
3428 scope) ; a `js2-scope' (optional, used for codegen)
3429
3430 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3431 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3432
3433 (defun js2-print-name-node (n i)
3434 (insert (js2-make-pad i)
3435 (js2-name-node-name n)))
3436
3437 (defsubst js2-name-node-length (node)
3438 "Return identifier length of NODE, a `js2-name-node'.
3439 Returns 0 if NODE is nil or its identifier field is nil."
3440 (if node
3441 (length (js2-name-node-name node))
3442 0))
3443
3444 (defstruct (js2-number-node
3445 (:include js2-node)
3446 (:constructor nil)
3447 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3448 (pos js2-token-beg)
3449 (len (- js2-ts-cursor
3450 js2-token-beg))
3451 (value js2-ts-string)
3452 (num-value js2-ts-number))))
3453 "AST node for a number literal."
3454 value ; the original string, e.g. "6.02e23"
3455 num-value) ; the parsed number value
3456
3457 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3458 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3459
3460 (defun js2-print-number-node (n i)
3461 (insert (js2-make-pad i)
3462 (number-to-string (js2-number-node-num-value n))))
3463
3464 (defstruct (js2-regexp-node
3465 (:include js2-node)
3466 (:constructor nil)
3467 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3468 (pos js2-token-beg)
3469 (len (- js2-ts-cursor
3470 js2-token-beg))
3471 value
3472 flags)))
3473 "AST node for a regular expression literal."
3474 value ; the regexp string, without // delimiters
3475 flags) ; a string of flags, e.g. `mi'.
3476
3477 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3478 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3479
3480 (defun js2-print-regexp (n i)
3481 (insert (js2-make-pad i)
3482 "/"
3483 (js2-regexp-node-value n)
3484 "/")
3485 (if (js2-regexp-node-flags n)
3486 (insert (js2-regexp-node-flags n))))
3487
3488 (defstruct (js2-string-node
3489 (:include js2-node)
3490 (:constructor nil)
3491 (:constructor make-js2-string-node (&key (type js2-STRING)
3492 (pos js2-token-beg)
3493 (len (- js2-ts-cursor
3494 js2-token-beg))
3495 (value js2-ts-string))))
3496 "String literal.
3497 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3498 You can tell the quote type by looking at the first character."
3499 value) ; the characters of the string, including the quotes
3500
3501 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3502 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3503
3504 (defun js2-print-string-node (n i)
3505 (insert (js2-make-pad i)
3506 (js2-node-string n)))
3507
3508 (defstruct (js2-array-node
3509 (:include js2-node)
3510 (:constructor nil)
3511 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3512 (pos js2-ts-cursor)
3513 len
3514 elems)))
3515 "AST node for an array literal."
3516 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3517
3518 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3519 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3520
3521 (defun js2-visit-array-node (n v)
3522 (dolist (e (js2-array-node-elems n))
3523 (when e ; can be nil, e.g. [a, ,b]
3524 (js2-visit-ast e v))))
3525
3526 (defun js2-print-array-node (n i)
3527 (insert (js2-make-pad i) "[")
3528 (js2-print-list (js2-array-node-elems n))
3529 (insert "]"))
3530
3531 (defstruct (js2-object-node
3532 (:include js2-node)
3533 (:constructor nil)
3534 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3535 (pos js2-ts-cursor)
3536 len
3537 elems)))
3538 "AST node for an object literal expression.
3539 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3540 the latter represents abbreviation in destructuring expressions."
3541 elems)
3542
3543 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3544 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3545
3546 (defun js2-visit-object-node (n v)
3547 (dolist (e (js2-object-node-elems n))
3548 (js2-visit-ast e v)))
3549
3550 (defun js2-print-object-node (n i)
3551 (insert (js2-make-pad i) "{")
3552 (js2-print-list (js2-object-node-elems n))
3553 (insert "}"))
3554
3555 (defstruct (js2-object-prop-node
3556 (:include js2-infix-node)
3557 (:constructor nil)
3558 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3559 (pos js2-ts-cursor)
3560 len
3561 left
3562 right
3563 op-pos)))
3564 "AST node for an object literal prop:value entry.
3565 The `left' field is the property: a name node, string node or number node.
3566 The `right' field is a `js2-node' representing the initializer value.")
3567
3568 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3569 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3570
3571 (defun js2-print-object-prop-node (n i)
3572 (insert (js2-make-pad i))
3573 (js2-print-ast (js2-object-prop-node-left n) 0)
3574 (insert ":")
3575 (js2-print-ast (js2-object-prop-node-right n) 0))
3576
3577 (defstruct (js2-getter-setter-node
3578 (:include js2-infix-node)
3579 (:constructor nil)
3580 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3581 (pos js2-ts-cursor)
3582 len
3583 left
3584 right)))
3585 "AST node for a getter/setter property in an object literal.
3586 The `left' field is the `js2-name-node' naming the getter/setter prop.
3587 The `right' field is always an anonymous `js2-function-node' with a node
3588 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3589
3590 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3591 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3592
3593 (defun js2-print-getter-setter (n i)
3594 (let ((pad (js2-make-pad i))
3595 (left (js2-getter-setter-node-left n))
3596 (right (js2-getter-setter-node-right n)))
3597 (insert pad)
3598 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3599 (js2-print-ast left 0)
3600 (js2-print-ast right 0)))
3601
3602 (defstruct (js2-prop-get-node
3603 (:include js2-infix-node)
3604 (:constructor nil)
3605 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3606 (pos js2-ts-cursor)
3607 len
3608 left
3609 right)))
3610 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3611
3612 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3613 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3614
3615 (defun js2-visit-prop-get-node (n v)
3616 (when (js2-prop-get-node-left n)
3617 (js2-visit-ast (js2-prop-get-node-left n) v))
3618 (when (js2-prop-get-node-right n)
3619 (js2-visit-ast (js2-prop-get-node-right n) v)))
3620
3621 (defun js2-print-prop-get-node (n i)
3622 (insert (js2-make-pad i))
3623 (js2-print-ast (js2-prop-get-node-left n) 0)
3624 (insert ".")
3625 (js2-print-ast (js2-prop-get-node-right n) 0))
3626
3627 (defstruct (js2-elem-get-node
3628 (:include js2-node)
3629 (:constructor nil)
3630 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3631 (pos js2-ts-cursor)
3632 len
3633 target
3634 element
3635 lb
3636 rb)))
3637 "AST node for an array index expression such as foo[bar]."
3638 target ; a `js2-node' - the expression preceding the "."
3639 element ; a `js2-node' - the expression in brackets
3640 lb ; position of left-bracket, nil if omitted
3641 rb) ; position of right-bracket, nil if omitted
3642
3643 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3644 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3645
3646 (defun js2-visit-elem-get-node (n v)
3647 (when (js2-elem-get-node-target n)
3648 (js2-visit-ast (js2-elem-get-node-target n) v))
3649 (when (js2-elem-get-node-element n)
3650 (js2-visit-ast (js2-elem-get-node-element n) v)))
3651
3652 (defun js2-print-elem-get-node (n i)
3653 (insert (js2-make-pad i))
3654 (js2-print-ast (js2-elem-get-node-target n) 0)
3655 (insert "[")
3656 (js2-print-ast (js2-elem-get-node-element n) 0)
3657 (insert "]"))
3658
3659 (defstruct (js2-call-node
3660 (:include js2-node)
3661 (:constructor nil)
3662 (:constructor make-js2-call-node (&key (type js2-CALL)
3663 (pos js2-ts-cursor)
3664 len
3665 target
3666 args
3667 lp
3668 rp)))
3669 "AST node for a JavaScript function call."
3670 target ; a `js2-node' evaluating to the function to call
3671 args ; a lisp list of `js2-node' arguments
3672 lp ; position of open-paren, or nil if missing
3673 rp) ; position of close-paren, or nil if missing
3674
3675 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3676 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3677
3678 (defun js2-visit-call-node (n v)
3679 (js2-visit-ast (js2-call-node-target n) v)
3680 (dolist (arg (js2-call-node-args n))
3681 (js2-visit-ast arg v)))
3682
3683 (defun js2-print-call-node (n i)
3684 (insert (js2-make-pad i))
3685 (js2-print-ast (js2-call-node-target n) 0)
3686 (insert "(")
3687 (js2-print-list (js2-call-node-args n))
3688 (insert ")"))
3689
3690 (defstruct (js2-yield-node
3691 (:include js2-node)
3692 (:constructor nil)
3693 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3694 (pos js2-ts-cursor)
3695 len
3696 value)))
3697 "AST node for yield statement or expression."
3698 value) ; optional: value to be yielded
3699
3700 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3701 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3702
3703 (defun js2-visit-yield-node (n v)
3704 (js2-visit-ast (js2-yield-node-value n) v))
3705
3706 (defun js2-print-yield-node (n i)
3707 (insert (js2-make-pad i))
3708 (insert "yield")
3709 (when (js2-yield-node-value n)
3710 (insert " ")
3711 (js2-print-ast (js2-yield-node-value n) 0)))
3712
3713 (defstruct (js2-paren-node
3714 (:include js2-node)
3715 (:constructor nil)
3716 (:constructor make-js2-paren-node (&key (type js2-LP)
3717 (pos js2-ts-cursor)
3718 len
3719 expr)))
3720 "AST node for a parenthesized expression.
3721 In particular, used when the parens are syntactically optional,
3722 as opposed to required parens such as those enclosing an if-conditional."
3723 expr) ; `js2-node'
3724
3725 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3726 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3727
3728 (defun js2-visit-paren-node (n v)
3729 (js2-visit-ast (js2-paren-node-expr n) v))
3730
3731 (defun js2-print-paren-node (n i)
3732 (insert (js2-make-pad i))
3733 (insert "(")
3734 (js2-print-ast (js2-paren-node-expr n) 0)
3735 (insert ")"))
3736
3737 (defstruct (js2-array-comp-node
3738 (:include js2-scope)
3739 (:constructor nil)
3740 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3741 (pos js2-ts-cursor)
3742 len
3743 result
3744 loops
3745 filter
3746 if-pos
3747 lp
3748 rp)))
3749 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3750 result ; result expression (just after left-bracket)
3751 loops ; a lisp list of `js2-array-comp-loop-node'
3752 filter ; guard/filter expression
3753 if-pos ; buffer pos of 'if' keyword, if present, else nil
3754 lp ; buffer position of if-guard left-paren, or nil if not present
3755 rp) ; buffer position of if-guard right-paren, or nil if not present
3756
3757 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3758 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3759
3760 (defun js2-visit-array-comp-node (n v)
3761 (js2-visit-ast (js2-array-comp-node-result n) v)
3762 (dolist (l (js2-array-comp-node-loops n))
3763 (js2-visit-ast l v))
3764 (if (js2-array-comp-node-filter n)
3765 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3766
3767 (defun js2-print-array-comp-node (n i)
3768 (let ((pad (js2-make-pad i))
3769 (result (js2-array-comp-node-result n))
3770 (loops (js2-array-comp-node-loops n))
3771 (filter (js2-array-comp-node-filter n)))
3772 (insert pad "[")
3773 (js2-print-ast result 0)
3774 (dolist (l loops)
3775 (insert " ")
3776 (js2-print-ast l 0))
3777 (when filter
3778 (insert " if (")
3779 (js2-print-ast filter 0))
3780 (insert ")]")))
3781
3782 (defstruct (js2-array-comp-loop-node
3783 (:include js2-for-in-node)
3784 (:constructor nil)
3785 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3786 (pos js2-ts-cursor)
3787 len
3788 iterator
3789 object
3790 in-pos
3791 foreach-p
3792 each-pos
3793 lp
3794 rp)))
3795 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3796
3797 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3798 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3799
3800 (defun js2-visit-array-comp-loop (n v)
3801 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3802 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3803
3804 (defun js2-print-array-comp-loop (n i)
3805 (insert "for (")
3806 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3807 (insert " in ")
3808 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3809 (insert ")"))
3810
3811 (defstruct (js2-empty-expr-node
3812 (:include js2-node)
3813 (:constructor nil)
3814 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3815 (pos js2-token-beg)
3816 len)))
3817 "AST node for an empty expression.")
3818
3819 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3820 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3821
3822 (defstruct (js2-xml-node
3823 (:include js2-block-node)
3824 (:constructor nil)
3825 (:constructor make-js2-xml-node (&key (type js2-XML)
3826 (pos js2-token-beg)
3827 len
3828 kids)))
3829 "AST node for initial parse of E4X literals.
3830 The kids field is a list of XML fragments, each a `js2-string-node' or
3831 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3832
3833 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3834 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3835
3836 (defun js2-print-xml-node (n i)
3837 (dolist (kid (js2-xml-node-kids n))
3838 (js2-print-ast kid i)))
3839
3840 (defstruct (js2-xml-js-expr-node
3841 (:include js2-xml-node)
3842 (:constructor nil)
3843 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3844 (pos js2-ts-cursor)
3845 len
3846 expr)))
3847 "AST node for an embedded JavaScript {expression} in an E4X literal.
3848 The start and end fields correspond to the curly-braces."
3849 expr) ; a `js2-expr-node' of some sort
3850
3851 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3852 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3853
3854 (defun js2-visit-xml-js-expr (n v)
3855 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3856
3857 (defun js2-print-xml-js-expr (n i)
3858 (insert (js2-make-pad i))
3859 (insert "{")
3860 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3861 (insert "}"))
3862
3863 (defstruct (js2-xml-dot-query-node
3864 (:include js2-infix-node)
3865 (:constructor nil)
3866 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3867 (pos js2-ts-cursor)
3868 op-pos
3869 len
3870 left
3871 right
3872 rp)))
3873 "AST node for an E4X foo.(bar) filter expression.
3874 Note that the left-paren is automatically the character immediately
3875 following the dot (.) in the operator. No whitespace is permitted
3876 between the dot and the lp by the scanner."
3877 rp)
3878
3879 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3880 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3881
3882 (defun js2-print-xml-dot-query (n i)
3883 (insert (js2-make-pad i))
3884 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3885 (insert ".(")
3886 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3887 (insert ")"))
3888
3889 (defstruct (js2-xml-ref-node
3890 (:include js2-node)
3891 (:constructor nil)) ; abstract
3892 "Base type for E4X XML attribute-access or property-get expressions.
3893 Such expressions can take a variety of forms. The general syntax has
3894 three parts:
3895
3896 - (optional) an @ (specifying an attribute access)
3897 - (optional) a namespace (a `js2-name-node') and double-colon
3898 - (required) either a `js2-name-node' or a bracketed [expression]
3899
3900 The property-name expressions (examples: ns::name, @name) are
3901 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3902 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3903
3904 This node type (or more specifically, its subclasses) will sometimes
3905 be the right-hand child of a `js2-prop-get-node' or a
3906 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3907 The `js2-xml-ref-node' may also be a standalone primary expression with
3908 no explicit target, which is valid in certain expression contexts such as
3909
3910 company..employee.(@id < 100)
3911
3912 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3913 expression whose parent is a `js2-xml-dot-query-node'."
3914 namespace
3915 at-pos
3916 colon-pos)
3917
3918 (defsubst js2-xml-ref-node-attr-access-p (node)
3919 "Return non-nil if this expression began with an @-token."
3920 (and (numberp (js2-xml-ref-node-at-pos node))
3921 (plusp (js2-xml-ref-node-at-pos node))))
3922
3923 (defstruct (js2-xml-prop-ref-node
3924 (:include js2-xml-ref-node)
3925 (:constructor nil)
3926 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3927 (pos js2-token-beg)
3928 len
3929 propname
3930 namespace
3931 at-pos
3932 colon-pos)))
3933 "AST node for an E4X XML [expr] property-ref expression.
3934 The JavaScript syntax is an optional @, an optional ns::, and a name.
3935
3936 [ '@' ] [ name '::' ] name
3937
3938 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3939 @ns::*, @*::attr, @*::*, and @*.
3940
3941 The node starts at the @ token, if present. Otherwise it starts at the
3942 namespace name. The node bounds extend through the closing right-bracket,
3943 or if it is missing due to a syntax error, through the end of the index
3944 expression."
3945 propname)
3946
3947 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3948 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3949
3950 (defun js2-visit-xml-prop-ref-node (n v)
3951 (if (js2-xml-prop-ref-node-namespace n)
3952 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3953 (if (js2-xml-prop-ref-node-propname n)
3954 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3955
3956 (defun js2-print-xml-prop-ref-node (n i)
3957 (insert (js2-make-pad i))
3958 (if (js2-xml-ref-node-attr-access-p n)
3959 (insert "@"))
3960 (when (js2-xml-prop-ref-node-namespace n)
3961 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3962 (insert "::"))
3963 (if (js2-xml-prop-ref-node-propname n)
3964 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3965
3966 (defstruct (js2-xml-elem-ref-node
3967 (:include js2-xml-ref-node)
3968 (:constructor nil)
3969 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3970 (pos js2-token-beg)
3971 len
3972 expr
3973 lb
3974 rb
3975 namespace
3976 at-pos
3977 colon-pos)))
3978 "AST node for an E4X XML [expr] member-ref expression.
3979 Syntax:
3980
3981 [ '@' ] [ name '::' ] '[' expr ']'
3982
3983 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3984
3985 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3986 is not a legal E4X XML element-ref expression, since it's already used
3987 for standard JavaScript element-get array indexing. Hence, a
3988 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3989 non-nil namespace node, or both.
3990
3991 The node starts at the @ token, if present. Otherwise it starts
3992 at the namespace name. The node bounds extend through the closing
3993 right-bracket, or if it is missing due to a syntax error, through the
3994 end of the index expression."
3995 expr ; the bracketed index expression
3996 lb
3997 rb)
3998
3999 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4000 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4001
4002 (defun js2-visit-xml-elem-ref-node (n v)
4003 (if (js2-xml-elem-ref-node-namespace n)
4004 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
4005 (if (js2-xml-elem-ref-node-expr n)
4006 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
4007
4008 (defun js2-print-xml-elem-ref-node (n i)
4009 (insert (js2-make-pad i))
4010 (if (js2-xml-ref-node-attr-access-p n)
4011 (insert "@"))
4012 (when (js2-xml-elem-ref-node-namespace n)
4013 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4014 (insert "::"))
4015 (insert "[")
4016 (if (js2-xml-elem-ref-node-expr n)
4017 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4018 (insert "]"))
4019
4020 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4021
4022 (defstruct (js2-xml-start-tag-node
4023 (:include js2-xml-node)
4024 (:constructor nil)
4025 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4026 (pos js2-ts-cursor)
4027 len
4028 name
4029 attrs
4030 kids
4031 empty-p)))
4032 "AST node for an XML start-tag. Not currently used.
4033 The `kids' field is a lisp list of child content nodes."
4034 name ; a `js2-xml-name-node'
4035 attrs ; a lisp list of `js2-xml-attr-node'
4036 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4037
4038 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4039 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4040
4041 (defun js2-visit-xml-start-tag (n v)
4042 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4043 (dolist (attr (js2-xml-start-tag-node-attrs n))
4044 (js2-visit-ast attr v))
4045 (js2-visit-block n v))
4046
4047 (defun js2-print-xml-start-tag (n i)
4048 (insert (js2-make-pad i) "<")
4049 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4050 (when (js2-xml-start-tag-node-attrs n)
4051 (insert " ")
4052 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4053 (insert ">"))
4054
4055 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4056 ;; and add the end-tag to the kids list of the parent as well.
4057 (defstruct (js2-xml-end-tag-node
4058 (:include js2-xml-node)
4059 (:constructor nil)
4060 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4061 (pos js2-ts-cursor)
4062 len
4063 name)))
4064 "AST node for an XML end-tag. Not currently used."
4065 name) ; a `js2-xml-name-node'
4066
4067 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4068 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4069
4070 (defun js2-visit-xml-end-tag (n v)
4071 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4072
4073 (defun js2-print-xml-end-tag (n i)
4074 (insert (js2-make-pad i))
4075 (insert "</")
4076 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4077 (insert ">"))
4078
4079 (defstruct (js2-xml-name-node
4080 (:include js2-xml-node)
4081 (:constructor nil)
4082 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4083 (pos js2-ts-cursor)
4084 len
4085 namespace
4086 kids)))
4087 "AST node for an E4X XML name. Not currently used.
4088 Any XML name can be qualified with a namespace, hence the namespace field.
4089 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4090 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4091 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4092 namespace) ; a `js2-string-node'
4093
4094 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4095 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4096
4097 (defun js2-visit-xml-name-node (n v)
4098 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4099
4100 (defun js2-print-xml-name-node (n i)
4101 (insert (js2-make-pad i))
4102 (when (js2-xml-name-node-namespace n)
4103 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4104 (insert "::"))
4105 (dolist (kid (js2-xml-name-node-kids n))
4106 (js2-print-ast kid 0)))
4107
4108 (defstruct (js2-xml-pi-node
4109 (:include js2-xml-node)
4110 (:constructor nil)
4111 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4112 (pos js2-ts-cursor)
4113 len
4114 name
4115 attrs)))
4116 "AST node for an E4X XML processing instruction. Not currently used."
4117 name ; a `js2-xml-name-node'
4118 attrs) ; a list of `js2-xml-attr-node'
4119
4120 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4121 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4122
4123 (defun js2-visit-xml-pi-node (n v)
4124 (js2-visit-ast (js2-xml-pi-node-name n) v)
4125 (dolist (attr (js2-xml-pi-node-attrs n))
4126 (js2-visit-ast attr v)))
4127
4128 (defun js2-print-xml-pi-node (n i)
4129 (insert (js2-make-pad i) "<?")
4130 (js2-print-ast (js2-xml-pi-node-name n))
4131 (when (js2-xml-pi-node-attrs n)
4132 (insert " ")
4133 (js2-print-list (js2-xml-pi-node-attrs n)))
4134 (insert "?>"))
4135
4136 (defstruct (js2-xml-cdata-node
4137 (:include js2-xml-node)
4138 (:constructor nil)
4139 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4140 (pos js2-ts-cursor)
4141 len
4142 content)))
4143 "AST node for a CDATA escape section. Not currently used."
4144 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4145
4146 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4147 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4148
4149 (defun js2-visit-xml-cdata-node (n v)
4150 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4151
4152 (defun js2-print-xml-cdata-node (n i)
4153 (insert (js2-make-pad i))
4154 (js2-print-ast (js2-xml-cdata-node-content n)))
4155
4156 (defstruct (js2-xml-attr-node
4157 (:include js2-xml-node)
4158 (:constructor nil)
4159 (:constructor make-js2-attr-node (&key (type js2-XML)
4160 (pos js2-ts-cursor)
4161 len
4162 name
4163 value
4164 eq-pos
4165 quote-type)))
4166 "AST node representing a foo='bar' XML attribute value. Not yet used."
4167 name ; a `js2-xml-name-node'
4168 value ; a `js2-xml-name-node'
4169 eq-pos ; buffer position of "=" sign
4170 quote-type) ; 'single or 'double
4171
4172 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4173 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4174
4175 (defun js2-visit-xml-attr-node (n v)
4176 (js2-visit-ast (js2-xml-attr-node-name n) v)
4177 (js2-visit-ast (js2-xml-attr-node-value n) v))
4178
4179 (defun js2-print-xml-attr-node (n i)
4180 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4181 "'"
4182 "\"")))
4183 (insert (js2-make-pad i))
4184 (js2-print-ast (js2-xml-attr-node-name n) 0)
4185 (insert "=" quote)
4186 (js2-print-ast (js2-xml-attr-node-value n) 0)
4187 (insert quote)))
4188
4189 (defstruct (js2-xml-text-node
4190 (:include js2-xml-node)
4191 (:constructor nil)
4192 (:constructor make-js2-text-node (&key (type js2-XML)
4193 (pos js2-ts-cursor)
4194 len
4195 content)))
4196 "AST node for an E4X XML text node. Not currently used."
4197 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4198
4199 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4200 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4201
4202 (defun js2-visit-xml-text-node (n v)
4203 (js2-visit-ast (js2-xml-text-node-content n) v))
4204
4205 (defun js2-print-xml-text-node (n i)
4206 (insert (js2-make-pad i))
4207 (dolist (kid (js2-xml-text-node-content n))
4208 (js2-print-ast kid)))
4209
4210 (defstruct (js2-xml-comment-node
4211 (:include js2-xml-node)
4212 (:constructor nil)
4213 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4214 (pos js2-ts-cursor)
4215 len)))
4216 "AST node for E4X XML comment. Not currently used.")
4217
4218 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4219 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4220
4221 (defun js2-print-xml-comment (n i)
4222 (insert (js2-make-pad i)
4223 (js2-node-string n)))
4224
4225 ;;; Node utilities
4226
4227 (defsubst js2-node-line (n)
4228 "Fetch the source line number at the start of node N.
4229 This is O(n) in the length of the source buffer; use prudently."
4230 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4231
4232 (defsubst js2-block-node-kid (n i)
4233 "Return child I of node N, or nil if there aren't that many."
4234 (nth i (js2-block-node-kids n)))
4235
4236 (defsubst js2-block-node-first (n)
4237 "Return first child of block node N, or nil if there is none."
4238 (first (js2-block-node-kids n)))
4239
4240 (defun js2-node-root (n)
4241 "Return the root of the AST containing N.
4242 If N has no parent pointer, returns N."
4243 (let ((parent (js2-node-parent n)))
4244 (if parent
4245 (js2-node-root parent)
4246 n)))
4247
4248 (defun js2-node-position-in-parent (node &optional parent)
4249 "Return the position of NODE in parent's block-kids list.
4250 PARENT can be supplied if known. Positioned returned is zero-indexed.
4251 Returns 0 if NODE is not a child of a block statement, or if NODE
4252 is not a statement node."
4253 (let ((p (or parent (js2-node-parent node)))
4254 (i 0))
4255 (if (not (js2-block-node-p p))
4256 i
4257 (or (js2-position node (js2-block-node-kids p))
4258 0))))
4259
4260 (defsubst js2-node-short-name (n)
4261 "Return the short name of node N as a string, e.g. `js2-if-node'."
4262 (substring (symbol-name (aref n 0))
4263 (length "cl-struct-")))
4264
4265 (defsubst js2-node-child-list (node)
4266 "Return the child list for NODE, a lisp list of nodes.
4267 Works for block nodes, array nodes, obj literals, funarg lists,
4268 var decls and try nodes (for catch clauses). Note that you should call
4269 `js2-block-node-kids' on the function body for the body statements.
4270 Returns nil for zero-length child lists or unsupported nodes."
4271 (cond
4272 ((js2-function-node-p node)
4273 (js2-function-node-params node))
4274 ((js2-block-node-p node)
4275 (js2-block-node-kids node))
4276 ((js2-try-node-p node)
4277 (js2-try-node-catch-clauses node))
4278 ((js2-array-node-p node)
4279 (js2-array-node-elems node))
4280 ((js2-object-node-p node)
4281 (js2-object-node-elems node))
4282 ((js2-call-node-p node)
4283 (js2-call-node-args node))
4284 ((js2-new-node-p node)
4285 (js2-new-node-args node))
4286 ((js2-var-decl-node-p node)
4287 (js2-var-decl-node-kids node))
4288 (t
4289 nil)))
4290
4291 (defsubst js2-node-set-child-list (node kids)
4292 "Set the child list for NODE to KIDS."
4293 (cond
4294 ((js2-function-node-p node)
4295 (setf (js2-function-node-params node) kids))
4296 ((js2-block-node-p node)
4297 (setf (js2-block-node-kids node) kids))
4298 ((js2-try-node-p node)
4299 (setf (js2-try-node-catch-clauses node) kids))
4300 ((js2-array-node-p node)
4301 (setf (js2-array-node-elems node) kids))
4302 ((js2-object-node-p node)
4303 (setf (js2-object-node-elems node) kids))
4304 ((js2-call-node-p node)
4305 (setf (js2-call-node-args node) kids))
4306 ((js2-new-node-p node)
4307 (setf (js2-new-node-args node) kids))
4308 ((js2-var-decl-node-p node)
4309 (setf (js2-var-decl-node-kids node) kids))
4310 (t
4311 (error "Unsupported node type: %s" (js2-node-short-name node))))
4312 kids)
4313
4314 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4315 (defconst js2-paren-expr-nodes
4316 '(cl-struct-js2-array-comp-loop-node
4317 cl-struct-js2-array-comp-node
4318 cl-struct-js2-call-node
4319 cl-struct-js2-catch-node
4320 cl-struct-js2-do-node
4321 cl-struct-js2-elem-get-node
4322 cl-struct-js2-for-in-node
4323 cl-struct-js2-for-node
4324 cl-struct-js2-function-node
4325 cl-struct-js2-if-node
4326 cl-struct-js2-let-node
4327 cl-struct-js2-new-node
4328 cl-struct-js2-paren-node
4329 cl-struct-js2-switch-node
4330 cl-struct-js2-while-node
4331 cl-struct-js2-with-node
4332 cl-struct-js2-xml-dot-query-node)
4333 "Node types that can have a parenthesized child expression.
4334 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4335
4336 (defsubst js2-paren-expr-node-p (node)
4337 "Return t for nodes that typically have a parenthesized child expression.
4338 Useful for computing the indentation anchors for arg-lists and conditions.
4339 Note that it may return a false positive, for instance when NODE is
4340 a `js2-new-node' and there are no arguments or parentheses."
4341 (memq (aref node 0) js2-paren-expr-nodes))
4342
4343 ;; Fake polymorphism... yech.
4344 (defsubst js2-node-lp (node)
4345 "Return relative left-paren position for NODE, if applicable.
4346 For `js2-elem-get-node' structs, returns left-bracket position.
4347 Note that the position may be nil in the case of a parse error."
4348 (cond
4349 ((js2-elem-get-node-p node)
4350 (js2-elem-get-node-lb node))
4351 ((js2-loop-node-p node)
4352 (js2-loop-node-lp node))
4353 ((js2-function-node-p node)
4354 (js2-function-node-lp node))
4355 ((js2-if-node-p node)
4356 (js2-if-node-lp node))
4357 ((js2-new-node-p node)
4358 (js2-new-node-lp node))
4359 ((js2-call-node-p node)
4360 (js2-call-node-lp node))
4361 ((js2-paren-node-p node)
4362 (js2-node-pos node))
4363 ((js2-switch-node-p node)
4364 (js2-switch-node-lp node))
4365 ((js2-catch-node-p node)
4366 (js2-catch-node-lp node))
4367 ((js2-let-node-p node)
4368 (js2-let-node-lp node))
4369 ((js2-array-comp-node-p node)
4370 (js2-array-comp-node-lp node))
4371 ((js2-with-node-p node)
4372 (js2-with-node-lp node))
4373 ((js2-xml-dot-query-node-p node)
4374 (1+ (js2-infix-node-op-pos node)))
4375 (t
4376 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4377
4378 ;; Fake polymorphism... blech.
4379 (defsubst js2-node-rp (node)
4380 "Return relative right-paren position for NODE, if applicable.
4381 For `js2-elem-get-node' structs, returns right-bracket position.
4382 Note that the position may be nil in the case of a parse error."
4383 (cond
4384 ((js2-elem-get-node-p node)
4385 (js2-elem-get-node-lb node))
4386 ((js2-loop-node-p node)
4387 (js2-loop-node-rp node))
4388 ((js2-function-node-p node)
4389 (js2-function-node-rp node))
4390 ((js2-if-node-p node)
4391 (js2-if-node-rp node))
4392 ((js2-new-node-p node)
4393 (js2-new-node-rp node))
4394 ((js2-call-node-p node)
4395 (js2-call-node-rp node))
4396 ((js2-paren-node-p node)
4397 (+ (js2-node-pos node) (js2-node-len node)))
4398 ((js2-switch-node-p node)
4399 (js2-switch-node-rp node))
4400 ((js2-catch-node-p node)
4401 (js2-catch-node-rp node))
4402 ((js2-let-node-p node)
4403 (js2-let-node-rp node))
4404 ((js2-array-comp-node-p node)
4405 (js2-array-comp-node-rp node))
4406 ((js2-with-node-p node)
4407 (js2-with-node-rp node))
4408 ((js2-xml-dot-query-node-p node)
4409 (1+ (js2-xml-dot-query-node-rp node)))
4410 (t
4411 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4412
4413 (defsubst js2-node-first-child (node)
4414 "Returns the first element of `js2-node-child-list' for NODE."
4415 (car (js2-node-child-list node)))
4416
4417 (defsubst js2-node-last-child (node)
4418 "Returns the last element of `js2-node-last-child' for NODE."
4419 (car (last (js2-node-child-list node))))
4420
4421 (defun js2-node-prev-sibling (node)
4422 "Return the previous statement in parent.
4423 Works for parents supported by `js2-node-child-list'.
4424 Returns nil if NODE is not in the parent, or PARENT is
4425 not a supported node, or if NODE is the first child."
4426 (let* ((p (js2-node-parent node))
4427 (kids (js2-node-child-list p))
4428 (sib (car kids)))
4429 (while (and kids
4430 (not (eq node (cadr kids))))
4431 (setq kids (cdr kids)
4432 sib (car kids)))
4433 sib))
4434
4435 (defun js2-node-next-sibling (node)
4436 "Return the next statement in parent block.
4437 Returns nil if NODE is not in the block, or PARENT is not
4438 a block node, or if NODE is the last statement."
4439 (let* ((p (js2-node-parent node))
4440 (kids (js2-node-child-list p)))
4441 (while (and kids
4442 (not (eq node (car kids))))
4443 (setq kids (cdr kids)))
4444 (cadr kids)))
4445
4446 (defun js2-node-find-child-before (pos parent &optional after)
4447 "Find the last child that starts before POS in parent.
4448 If AFTER is non-nil, returns first child starting after POS.
4449 POS is an absolute buffer position. PARENT is any node
4450 supported by `js2-node-child-list'.
4451 Returns nil if no applicable child is found."
4452 (let ((kids (if (js2-function-node-p parent)
4453 (js2-block-node-kids (js2-function-node-body parent))
4454 (js2-node-child-list parent)))
4455 (beg (if (js2-function-node-p parent)
4456 (js2-node-abs-pos (js2-function-node-body parent))
4457 (js2-node-abs-pos parent)))
4458 kid
4459 result
4460 fn
4461 (continue t))
4462 (setq fn (if after '> '<))
4463 (while (and kids continue)
4464 (setq kid (car kids))
4465 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4466 (setq result kid
4467 continue (if after nil t))
4468 (setq continue (if after t nil)))
4469 (setq kids (cdr kids)))
4470 result))
4471
4472 (defun js2-node-find-child-after (pos parent)
4473 "Find first child that starts after POS in parent.
4474 POS is an absolute buffer position. PARENT is any node
4475 supported by `js2-node-child-list'.
4476 Returns nil if no applicable child is found."
4477 (js2-node-find-child-before pos parent 'after))
4478
4479 (defun js2-node-replace-child (pos parent new-node)
4480 "Replace node at index POS in PARENT with NEW-NODE.
4481 Only works for parents supported by `js2-node-child-list'."
4482 (let ((kids (js2-node-child-list parent))
4483 (i 0))
4484 (while (< i pos)
4485 (setq kids (cdr kids)
4486 i (1+ i)))
4487 (setcar kids new-node)
4488 (js2-node-add-children parent new-node)))
4489
4490 (defun js2-node-buffer (n)
4491 "Return the buffer associated with AST N.
4492 Returns nil if the buffer is not set as a property on the root
4493 node, or if parent links were not recorded during parsing."
4494 (let ((root (js2-node-root n)))
4495 (and root
4496 (js2-ast-root-p root)
4497 (js2-ast-root-buffer root))))
4498
4499 (defsubst js2-block-node-push (n kid)
4500 "Push js2-node KID onto the end of js2-block-node N's child list.
4501 KID is always added to the -end- of the kids list.
4502 Function also calls `js2-node-add-children' to add the parent link."
4503 (let ((kids (js2-node-child-list n)))
4504 (if kids
4505 (setcdr kids (nconc (cdr kids) (list kid)))
4506 (js2-node-set-child-list n (list kid)))
4507 (js2-node-add-children n kid)))
4508
4509 (defun js2-node-string (node)
4510 (let ((buf (js2-node-buffer node))
4511 pos)
4512 (unless buf
4513 (error "No buffer available for node %s" node))
4514 (save-excursion
4515 (set-buffer buf)
4516 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4517 (+ pos (js2-node-len node))))))
4518
4519 ;; Container for storing the node we're looking for in a traversal.
4520 (js2-deflocal js2-discovered-node nil)
4521
4522 ;; Keep track of absolute node position during traversals.
4523 (js2-deflocal js2-visitor-offset nil)
4524
4525 (js2-deflocal js2-node-search-point nil)
4526
4527 (when js2-mode-dev-mode-p
4528 (defun js2-find-node-at-point ()
4529 (interactive)
4530 (let ((node (js2-node-at-point)))
4531 (message "%s" (or node "No node found at point"))))
4532 (defun js2-node-name-at-point ()
4533 (interactive)
4534 (let ((node (js2-node-at-point)))
4535 (message "%s" (if node
4536 (js2-node-short-name node)
4537 "No node found at point.")))))
4538
4539 (defun js2-node-at-point (&optional pos skip-comments)
4540 "Return AST node at POS, a buffer position, defaulting to current point.
4541 The `js2-mode-ast' variable must be set to the current parse tree.
4542 Signals an error if the AST (`js2-mode-ast') is nil.
4543 Always returns a node - if it can't find one, it returns the root.
4544 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4545 (let ((ast js2-mode-ast)
4546 result)
4547 (unless ast
4548 (error "No JavaScript AST available"))
4549 ;; Look through comments first, since they may be inside nodes that
4550 ;; would otherwise report a match.
4551 (setq pos (or pos (point))
4552 result (if (> pos (js2-node-abs-end ast))
4553 ast
4554 (if (not skip-comments)
4555 (js2-comment-at-point pos))))
4556 (unless result
4557 (setq js2-discovered-node nil
4558 js2-visitor-offset 0
4559 js2-node-search-point pos)
4560 (unwind-protect
4561 (catch 'js2-visit-done
4562 (js2-visit-ast ast #'js2-node-at-point-visitor))
4563 (setq js2-visitor-offset nil
4564 js2-node-search-point nil))
4565 (setq result js2-discovered-node))
4566 ;; may have found a comment beyond end of last child node,
4567 ;; since visiting the ast-root looks at the comment-list last.
4568 (if (and skip-comments
4569 (js2-comment-node-p result))
4570 (setq result nil))
4571 (or result js2-mode-ast)))
4572
4573 (defun js2-node-at-point-visitor (node end-p)
4574 (let ((rel-pos (js2-node-pos node))
4575 abs-pos
4576 abs-end
4577 (point js2-node-search-point))
4578 (cond
4579 (end-p
4580 ;; this evaluates to a non-nil return value, even if it's zero
4581 (decf js2-visitor-offset rel-pos))
4582 ;; we already looked for comments before visiting, and don't want them now
4583 ((js2-comment-node-p node)
4584 nil)
4585 (t
4586 (setq abs-pos (incf js2-visitor-offset rel-pos)
4587 ;; we only want to use the node if the point is before
4588 ;; the last character position in the node, so we decrement
4589 ;; the absolute end by 1.
4590 abs-end (+ abs-pos (js2-node-len node) -1))
4591 (cond
4592 ;; If this node starts after search-point, stop the search.
4593 ((> abs-pos point)
4594 (throw 'js2-visit-done nil))
4595 ;; If this node ends before the search-point, don't check kids.
4596 ((> point abs-end)
4597 nil)
4598 (t
4599 ;; Otherwise point is within this node, possibly in a child.
4600 (setq js2-discovered-node node)
4601 t)))))) ; keep processing kids to look for more specific match
4602
4603 (defsubst js2-block-comment-p (node)
4604 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4605 (and (js2-comment-node-p node)
4606 (memq (js2-comment-node-format node) '(jsdoc block))))
4607
4608 ;; TODO: put the comments in a vector and binary-search them instead
4609 (defun js2-comment-at-point (&optional pos)
4610 "Look through scanned comment nodes for one containing POS.
4611 POS is a buffer position that defaults to current point.
4612 Function returns nil if POS was not in any comment node."
4613 (let ((ast js2-mode-ast)
4614 (x (or pos (point)))
4615 beg
4616 end)
4617 (unless ast
4618 (error "No JavaScript AST available"))
4619 (catch 'done
4620 ;; Comments are stored in lexical order.
4621 (dolist (comment (js2-ast-root-comments ast) nil)
4622 (setq beg (js2-node-abs-pos comment)
4623 end (+ beg (js2-node-len comment)))
4624 (if (and (>= x beg)
4625 (<= x end))
4626 (throw 'done comment))))))
4627
4628 (defun js2-mode-find-parent-fn (node)
4629 "Find function enclosing NODE.
4630 Returns nil if NODE is not inside a function."
4631 (setq node (js2-node-parent node))
4632 (while (and node (not (js2-function-node-p node)))
4633 (setq node (js2-node-parent node)))
4634 (and (js2-function-node-p node) node))
4635
4636 (defun js2-mode-find-enclosing-fn (node)
4637 "Find function or root enclosing NODE."
4638 (if (js2-ast-root-p node)
4639 node
4640 (setq node (js2-node-parent node))
4641 (while (not (or (js2-ast-root-p node)
4642 (js2-function-node-p node)))
4643 (setq node (js2-node-parent node)))
4644 node))
4645
4646 (defun js2-mode-find-enclosing-node (beg end)
4647 "Find script or function fully enclosing BEG and END."
4648 (let ((node (js2-node-at-point beg))
4649 pos
4650 (continue t))
4651 (while continue
4652 (if (or (js2-ast-root-p node)
4653 (and (js2-function-node-p node)
4654 (<= (setq pos (js2-node-abs-pos node)) beg)
4655 (>= (+ pos (js2-node-len node)) end)))
4656 (setq continue nil)
4657 (setq node (js2-node-parent node))))
4658 node))
4659
4660 (defun js2-node-parent-script-or-fn (node)
4661 "Find script or function immediately enclosing NODE.
4662 If NODE is the ast-root, returns nil."
4663 (if (js2-ast-root-p node)
4664 nil
4665 (setq node (js2-node-parent node))
4666 (while (and node (not (or (js2-function-node-p node)
4667 (js2-script-node-p node))))
4668 (setq node (js2-node-parent node)))
4669 node))
4670
4671 (defsubst js2-nested-function-p (node)
4672 "Return t if NODE is a nested function, or is inside a nested function."
4673 (js2-function-node-p (if (js2-function-node-p node)
4674 (js2-node-parent-script-or-fn node)
4675 (js2-node-parent-script-or-fn
4676 (js2-node-parent-script-or-fn node)))))
4677
4678 (defsubst js2-function-param-node-p (node)
4679 "Return non-nil if NODE is a param node of a `js2-function-node'."
4680 (let ((parent (js2-node-parent node)))
4681 (and parent
4682 (js2-function-node-p parent)
4683 (memq node (js2-function-node-params parent)))))
4684
4685 (defsubst js2-mode-shift-kids (kids start offset)
4686 (dolist (kid kids)
4687 (if (> (js2-node-pos kid) start)
4688 (incf (js2-node-pos kid) offset))))
4689
4690 (defsubst js2-mode-shift-children (parent start offset)
4691 "Update start-positions of all children of PARENT beyond START."
4692 (let ((root (js2-node-root parent)))
4693 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4694 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4695
4696 (defsubst js2-node-is-descendant (node ancestor)
4697 "Return t if NODE is a descendant of ANCESTOR."
4698 (while (and node
4699 (not (eq node ancestor)))
4700 (setq node (js2-node-parent node)))
4701 node)
4702
4703 ;;; visitor infrastructure
4704
4705 (defun js2-visit-none (node callback)
4706 "Visitor for AST node that have no node children."
4707 nil)
4708
4709 (defun js2-print-none (node indent)
4710 "Visitor for AST node with no printed representation.")
4711
4712 (defun js2-print-body (node indent)
4713 "Print a statement, or a block without braces."
4714 (if (js2-block-node-p node)
4715 (dolist (kid (js2-block-node-kids node))
4716 (js2-print-ast kid indent))
4717 (js2-print-ast node indent)))
4718
4719 (defun js2-print-list (args &optional delimiter)
4720 (loop with len = (length args)
4721 for arg in args
4722 for count from 1
4723 do
4724 (js2-print-ast arg 0)
4725 (if (< count len)
4726 (insert (or delimiter ", ")))))
4727
4728 (defun js2-print-tree (ast)
4729 "Prints an AST to the current buffer.
4730 Makes `js2-ast-parent-nodes' available to the printer functions."
4731 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4732 (js2-print-ast ast)))
4733
4734 (defun js2-print-ast (node &optional indent)
4735 "Helper function for printing AST nodes.
4736 Requires `js2-ast-parent-nodes' to be non-nil.
4737 You should use `js2-print-tree' instead of this function."
4738 (let ((printer (get (aref node 0) 'js2-printer))
4739 (i (or indent 0))
4740 (pos (js2-node-abs-pos node)))
4741 ;; TODO: wedge comments in here somewhere
4742 (if printer
4743 (funcall printer node i))))
4744
4745 (defconst js2-side-effecting-tokens
4746 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4747 (dolist (tt (list js2-ASSIGN
4748 js2-ASSIGN_ADD
4749 js2-ASSIGN_BITAND
4750 js2-ASSIGN_BITOR
4751 js2-ASSIGN_BITXOR
4752 js2-ASSIGN_DIV
4753 js2-ASSIGN_LSH
4754 js2-ASSIGN_MOD
4755 js2-ASSIGN_MUL
4756 js2-ASSIGN_RSH
4757 js2-ASSIGN_SUB
4758 js2-ASSIGN_URSH
4759 js2-BLOCK
4760 js2-BREAK
4761 js2-CALL
4762 js2-CATCH
4763 js2-CATCH_SCOPE
4764 js2-CONST
4765 js2-CONTINUE
4766 js2-DEBUGGER
4767 js2-DEC
4768 js2-DELPROP
4769 js2-DEL_REF
4770 js2-DO
4771 js2-ELSE
4772 js2-EMPTY
4773 js2-ENTERWITH
4774 js2-EXPORT
4775 js2-EXPR_RESULT
4776 js2-FINALLY
4777 js2-FOR
4778 js2-FUNCTION
4779 js2-GOTO
4780 js2-IF
4781 js2-IFEQ
4782 js2-IFNE
4783 js2-IMPORT
4784 js2-INC
4785 js2-JSR
4786 js2-LABEL
4787 js2-LEAVEWITH
4788 js2-LET
4789 js2-LETEXPR
4790 js2-LOCAL_BLOCK
4791 js2-LOOP
4792 js2-NEW
4793 js2-REF_CALL
4794 js2-RETHROW
4795 js2-RETURN
4796 js2-RETURN_RESULT
4797 js2-SEMI
4798 js2-SETELEM
4799 js2-SETELEM_OP
4800 js2-SETNAME
4801 js2-SETPROP
4802 js2-SETPROP_OP
4803 js2-SETVAR
4804 js2-SET_REF
4805 js2-SET_REF_OP
4806 js2-SWITCH
4807 js2-TARGET
4808 js2-THROW
4809 js2-TRY
4810 js2-VAR
4811 js2-WHILE
4812 js2-WITH
4813 js2-WITHEXPR
4814 js2-YIELD))
4815 (aset tokens tt t))
4816 (if js2-instanceof-has-side-effects
4817 (aset tokens js2-INSTANCEOF t))
4818 tokens))
4819
4820 (defun js2-node-has-side-effects (node)
4821 "Return t if NODE has side effects."
4822 (when node ; makes it easier to handle malformed expressions
4823 (let ((tt (js2-node-type node)))
4824 (cond
4825 ;; This doubtless needs some work, since EXPR_VOID is used
4826 ;; in several ways in Rhino, and I may not have caught them all.
4827 ;; I'll wait for people to notice incorrect warnings.
4828 ((and (= tt js2-EXPR_VOID)
4829 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4830 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4831 ((= tt js2-COMMA)
4832 (js2-node-has-side-effects (js2-infix-node-right node)))
4833 ((or (= tt js2-AND)
4834 (= tt js2-OR))
4835 (or (js2-node-has-side-effects (js2-infix-node-right node))
4836 (js2-node-has-side-effects (js2-infix-node-left node))))
4837 ((= tt js2-HOOK)
4838 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4839 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4840 ((js2-paren-node-p node)
4841 (js2-node-has-side-effects (js2-paren-node-expr node)))
4842 ((= tt js2-ERROR) ; avoid cascaded error messages
4843 nil)
4844 (t
4845 (aref js2-side-effecting-tokens tt))))))
4846
4847 (defun js2-member-expr-leftmost-name (node)
4848 "For an expr such as foo.bar.baz, return leftmost node foo.
4849 NODE is any `js2-node' object. If it represents a member expression,
4850 which is any sequence of property gets, element-gets, function calls,
4851 or xml descendants/filter operators, then we look at the lexically
4852 leftmost (first) node in the chain. If it is a name-node we return it.
4853 Note that NODE can be a raw name-node and it will be returned as well.
4854 If NODE is not a name-node or member expression, or if it is a member
4855 expression whose leftmost target is not a name node, returns nil."
4856 (let ((continue t)
4857 result)
4858 (while (and continue (not result))
4859 (cond
4860 ((js2-name-node-p node)
4861 (setq result node))
4862 ((js2-prop-get-node-p node)
4863 (setq node (js2-prop-get-node-left node)))
4864 ;; TODO: handle call-nodes, xml-nodes, others?
4865 (t
4866 (setq continue nil))))
4867 result))
4868
4869 (defconst js2-stmt-node-types
4870 (list js2-BLOCK
4871 js2-BREAK
4872 js2-CONTINUE
4873 js2-DEFAULT ; e4x "default xml namespace" statement
4874 js2-DO
4875 js2-EXPR_RESULT
4876 js2-EXPR_VOID
4877 js2-FOR
4878 js2-IF
4879 js2-RETURN
4880 js2-SWITCH
4881 js2-THROW
4882 js2-TRY
4883 js2-WHILE
4884 js2-WITH)
4885 "Node types that only appear in statement contexts.
4886 The list does not include nodes that always appear as the child
4887 of another specific statement type, such as switch-cases,
4888 catch and finally blocks, and else-clauses. The list also excludes
4889 nodes like yield, let and var, which may appear in either expression
4890 or statement context, and in the latter context always have a
4891 `js2-expr-stmt-node' parent. Finally, the list does not include
4892 functions or scripts, which are treated separately from statements
4893 by the JavaScript parser and runtime.")
4894
4895 (defun js2-stmt-node-p (node)
4896 "Heuristic for figuring out if NODE is a statement.
4897 Some node types can appear in either an expression context or a
4898 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4899 For these node types in a statement context, the parent will be a
4900 `js2-expr-stmt-node'.
4901 Functions aren't included in the check."
4902 (memq (js2-node-type node) js2-stmt-node-types))
4903
4904 (defsubst js2-mode-find-first-stmt (node)
4905 "Search upward starting from NODE looking for a statement.
4906 For purposes of this function, a `js2-function-node' counts."
4907 (while (not (or (js2-stmt-node-p node)
4908 (js2-function-node-p node)))
4909 (setq node (js2-node-parent node)))
4910 node)
4911
4912 (defun js2-node-parent-stmt (node)
4913 "Return the node's first ancestor that is a statement.
4914 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4915 appearing in a statement context will have a parent that is a
4916 `js2-expr-stmt-node' that will be returned by this function."
4917 (let ((parent (js2-node-parent node)))
4918 (if (or (null parent)
4919 (js2-stmt-node-p parent)
4920 (and (js2-function-node-p parent)
4921 (not (eq (js2-function-node-form parent)
4922 'FUNCTION_EXPRESSION))))
4923 parent
4924 (js2-node-parent-stmt parent))))
4925
4926 ;; In the Mozilla Rhino sources, Roshan James writes:
4927 ;; Does consistent-return analysis on the function body when strict mode is
4928 ;; enabled.
4929 ;;
4930 ;; function (x) { return (x+1) }
4931 ;;
4932 ;; is ok, but
4933 ;;
4934 ;; function (x) { if (x < 0) return (x+1); }
4935 ;;
4936 ;; is not because the function can potentially return a value when the
4937 ;; condition is satisfied and if not, the function does not explicitly
4938 ;; return a value.
4939 ;;
4940 ;; This extends to checking mismatches such as "return" and "return <value>"
4941 ;; used in the same function. Warnings are not emitted if inconsistent
4942 ;; returns exist in code that can be statically shown to be unreachable.
4943 ;; Ex.
4944 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4945 ;;
4946 ;; emits no warning. However if the loop had a break statement, then a
4947 ;; warning would be emitted.
4948 ;;
4949 ;; The consistency analysis looks at control structures such as loops, ifs,
4950 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4951 ;; warns the user about an inconsistent set of termination possibilities.
4952 ;;
4953 ;; These flags enumerate the possible ways a statement/function can
4954 ;; terminate. These flags are used by endCheck() and by the Parser to
4955 ;; detect inconsistent return usage.
4956 ;;
4957 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4958 ;; able to execute (example: throw, continue)
4959 ;;
4960 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4961 ;; next one. Statement such as return dont. A compound statement may have
4962 ;; some branch that drops off control to the next statement.
4963 ;;
4964 ;; END_RETURNS indicates that the statement can return with no value.
4965 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4966 ;;
4967 ;; A compound statement such as
4968 ;; if (condition) {
4969 ;; return value;
4970 ;; }
4971 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4972
4973 (defconst js2-END_UNREACHED 0)
4974 (defconst js2-END_DROPS_OFF 1)
4975 (defconst js2-END_RETURNS 2)
4976 (defconst js2-END_RETURNS_VALUE 4)
4977 (defconst js2-END_YIELDS 8)
4978
4979 (defun js2-has-consistent-return-usage (node)
4980 "Check that every return usage in a function body is consistent.
4981 Returns t if the function satisfies strict mode requirement."
4982 (let ((n (js2-end-check node)))
4983 ;; either it doesn't return a value in any branch...
4984 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4985 ;; or it returns a value (or is unreached) at every branch
4986 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4987 js2-END_RETURNS
4988 js2-END_YIELDS)))))
4989
4990 (defun js2-end-check-if (node)
4991 "Returns in the then and else blocks must be consistent with each other.
4992 If there is no else block, then the return statement can fall through.
4993 Returns logical OR of END_* flags"
4994 (let ((th (js2-if-node-then-part node))
4995 (el (js2-if-node-else-part node)))
4996 (if (null th)
4997 js2-END_UNREACHED
4998 (logior (js2-end-check th) (if el
4999 (js2-end-check el)
5000 js2-END_DROPS_OFF)))))
5001
5002 (defun js2-end-check-switch (node)
5003 "Consistency of return statements is checked between the case statements.
5004 If there is no default, then the switch can fall through. If there is a
5005 default, we check to see if all code paths in the default return or if
5006 there is a code path that can fall through.
5007 Returns logical OR of END_* flags."
5008 (let ((rv js2-END_UNREACHED)
5009 default-case)
5010 ;; examine the cases
5011 (catch 'break
5012 (dolist (c (js2-switch-node-cases node))
5013 (if (js2-case-node-expr c)
5014 (js2-set-flag rv (js2-end-check-block c))
5015 (setq default-case c)
5016 (throw 'break nil))))
5017 ;; we don't care how the cases drop into each other
5018 (js2-clear-flag rv js2-END_DROPS_OFF)
5019 ;; examine the default
5020 (js2-set-flag rv (if default-case
5021 (js2-end-check default-case)
5022 js2-END_DROPS_OFF))
5023 rv))
5024
5025 (defun js2-end-check-try (node)
5026 "If the block has a finally, return consistency is checked in the
5027 finally block. If all code paths in the finally return, then the
5028 returns in the try-catch blocks don't matter. If there is a code path
5029 that does not return or if there is no finally block, the returns
5030 of the try and catch blocks are checked for mismatch.
5031 Returns logical OR of END_* flags."
5032 (let ((finally (js2-try-node-finally-block node))
5033 rv)
5034 ;; check the finally if it exists
5035 (setq rv (if finally
5036 (js2-end-check (js2-finally-node-body finally))
5037 js2-END_DROPS_OFF))
5038 ;; If the finally block always returns, then none of the returns
5039 ;; in the try or catch blocks matter.
5040 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5041 (js2-clear-flag rv js2-END_DROPS_OFF)
5042 ;; examine the try block
5043 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5044 ;; check each catch block
5045 (dolist (cb (js2-try-node-catch-clauses node))
5046 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5047 rv))
5048
5049 (defun js2-end-check-loop (node)
5050 "Return statement in the loop body must be consistent. The default
5051 assumption for any kind of a loop is that it will eventually terminate.
5052 The only exception is a loop with a constant true condition. Code that
5053 follows such a loop is examined only if one can statically determine
5054 that there is a break out of the loop.
5055
5056 for(... ; ... ; ...) {}
5057 for(... in ... ) {}
5058 while(...) { }
5059 do { } while(...)
5060
5061 Returns logical OR of END_* flags."
5062 (let ((rv (js2-end-check (js2-loop-node-body node)))
5063 (condition (cond
5064 ((js2-while-node-p node)
5065 (js2-while-node-condition node))
5066 ((js2-do-node-p node)
5067 (js2-do-node-condition node))
5068 ((js2-for-node-p node)
5069 (js2-for-node-condition node)))))
5070
5071 ;; check to see if the loop condition is always true
5072 (if (and condition
5073 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5074 (js2-clear-flag rv js2-END_DROPS_OFF))
5075
5076 ;; look for effect of breaks
5077 (js2-set-flag rv (js2-node-get-prop node
5078 'CONTROL_BLOCK_PROP
5079 js2-END_UNREACHED))
5080 rv))
5081
5082 (defun js2-end-check-block (node)
5083 "A general block of code is examined statement by statement.
5084 If any statement (even a compound one) returns in all branches, then
5085 subsequent statements are not examined.
5086 Returns logical OR of END_* flags."
5087 (let* ((rv js2-END_DROPS_OFF)
5088 (kids (js2-block-node-kids node))
5089 (n (car kids)))
5090 ;; Check each statment. If the statement can continue onto the next
5091 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5092 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5093 (js2-clear-flag rv js2-END_DROPS_OFF)
5094 (js2-set-flag rv (js2-end-check n))
5095 (setq kids (cdr kids)
5096 n (car kids)))
5097 rv))
5098
5099 (defun js2-end-check-label (node)
5100 "A labeled statement implies that there may be a break to the label.
5101 The function processes the labeled statement and then checks the
5102 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5103 particular label.
5104 Returns logical OR of END_* flags."
5105 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5106 (logior rv (js2-node-get-prop node
5107 'CONTROL_BLOCK_PROP
5108 js2-END_UNREACHED))))
5109
5110 (defun js2-end-check-break (node)
5111 "When a break is encountered annotate the statement being broken
5112 out of by setting its CONTROL_BLOCK_PROP property.
5113 Returns logical OR of END_* flags."
5114 (and (js2-break-node-target node)
5115 (js2-node-set-prop (js2-break-node-target node)
5116 'CONTROL_BLOCK_PROP
5117 js2-END_DROPS_OFF))
5118 js2-END_UNREACHED)
5119
5120 (defun js2-end-check (node)
5121 "Examine the body of a function, doing a basic reachability analysis.
5122 Returns a combination of flags END_* flags that indicate
5123 how the function execution can terminate. These constitute only the
5124 pessimistic set of termination conditions. It is possible that at
5125 runtime certain code paths will never be actually taken. Hence this
5126 analysis will flag errors in cases where there may not be errors.
5127 Returns logical OR of END_* flags"
5128 (let (kid)
5129 (cond
5130 ((js2-break-node-p node)
5131 (js2-end-check-break node))
5132 ((js2-expr-stmt-node-p node)
5133 (if (setq kid (js2-expr-stmt-node-expr node))
5134 (js2-end-check kid)
5135 js2-END_DROPS_OFF))
5136 ((or (js2-continue-node-p node)
5137 (js2-throw-node-p node))
5138 js2-END_UNREACHED)
5139 ((js2-return-node-p node)
5140 (if (setq kid (js2-return-node-retval node))
5141 js2-END_RETURNS_VALUE
5142 js2-END_RETURNS))
5143 ((js2-loop-node-p node)
5144 (js2-end-check-loop node))
5145 ((js2-switch-node-p node)
5146 (js2-end-check-switch node))
5147 ((js2-labeled-stmt-node-p node)
5148 (js2-end-check-label node))
5149 ((js2-if-node-p node)
5150 (js2-end-check-if node))
5151 ((js2-try-node-p node)
5152 (js2-end-check-try node))
5153 ((js2-block-node-p node)
5154 (if (null (js2-block-node-kids node))
5155 js2-END_DROPS_OFF
5156 (js2-end-check-block node)))
5157 ((js2-yield-node-p node)
5158 js2-END_YIELDS)
5159 (t
5160 js2-END_DROPS_OFF))))
5161
5162 (defun js2-always-defined-boolean-p (node)
5163 "Check if NODE always evaluates to true or false in boolean context.
5164 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5165 nor always false."
5166 (let ((tt (js2-node-type node))
5167 num)
5168 (cond
5169 ((or (= tt js2-FALSE) (= tt js2-NULL))
5170 'ALWAYS_FALSE)
5171 ((= tt js2-TRUE)
5172 'ALWAYS_TRUE)
5173 ((= tt js2-NUMBER)
5174 (setq num (js2-number-node-num-value node))
5175 (if (and (not (eq num 0.0e+NaN))
5176 (not (zerop num)))
5177 'ALWAYS_TRUE
5178 'ALWAYS_FALSE))
5179 (t
5180 nil))))
5181
5182 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5183 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5184
5185 (defvar js2-tokens nil
5186 "List of all defined token names.") ; initialized in `js2-token-names'
5187
5188 (defconst js2-token-names
5189 (let* ((names (make-vector js2-num-tokens -1))
5190 (case-fold-search nil) ; only match js2-UPPER_CASE
5191 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5192 (loop for sym in syms
5193 for i from 0
5194 do
5195 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5196 (not (boundp sym)))
5197 (aset names (symbol-value sym) ; code, e.g. 152
5198 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5199 (push sym js2-tokens)))
5200 names)
5201 "Vector mapping int values to token string names, sans `js2-' prefix.")
5202
5203 (defun js2-token-name (tok)
5204 "Return a string name for TOK, a token symbol or code.
5205 Signals an error if it's not a recognized token."
5206 (let ((code tok))
5207 (if (symbolp tok)
5208 (setq code (symbol-value tok)))
5209 (if (eq code -1)
5210 "ERROR"
5211 (if (and (numberp code)
5212 (not (minusp code))
5213 (< code js2-num-tokens))
5214 (aref js2-token-names code)
5215 (error "Invalid token: %s" code)))))
5216
5217 (defsubst js2-token-sym (tok)
5218 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5219 (intern (js2-token-name tok)))
5220
5221 (defconst js2-token-codes
5222 (let ((table (make-hash-table :test 'eq :size 256)))
5223 (loop for name across js2-token-names
5224 for sym = (intern (concat "js2-" name))
5225 do
5226 (puthash sym (symbol-value sym) table))
5227 ;; clean up a few that are "wrong" in Rhino's token codes
5228 (puthash 'js2-DELETE js2-DELPROP table)
5229 table)
5230 "Hashtable mapping token symbols to their bytecodes.")
5231
5232 (defsubst js2-token-code (sym)
5233 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5234 (or (gethash sym js2-token-codes)
5235 (error "Invalid token symbol: %s " sym))) ; signal code bug
5236
5237 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5238 (setq js2-token-end js2-ts-cursor)
5239 (js2-report-error msg nil
5240 (or beg js2-token-beg)
5241 (or len (- js2-token-end js2-token-beg)))
5242 (unless no-throw
5243 (throw 'return js2-ERROR)))
5244
5245 (defsubst js2-get-string-from-buffer ()
5246 "Reverse the char accumulator and return it as a string."
5247 (setq js2-token-end js2-ts-cursor)
5248 (if js2-ts-string-buffer
5249 (apply #'string (nreverse js2-ts-string-buffer))
5250 ""))
5251
5252 ;; TODO: could potentially avoid a lot of consing by allocating a
5253 ;; char buffer the way Rhino does.
5254 (defsubst js2-add-to-string (c)
5255 (push c js2-ts-string-buffer))
5256
5257 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5258 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5259 ;; any other character: when it's not part of the current token, we
5260 ;; unget it, allowing it to be read again by the following call.
5261 (defsubst js2-unget-char ()
5262 (decf js2-ts-cursor))
5263
5264 ;; Rhino distinguishes \r and \n line endings. We don't need to
5265 ;; because we only scan from Emacs buffers, which always use \n.
5266 (defsubst js2-get-char ()
5267 "Read and return the next character from the input buffer.
5268 Increments `js2-ts-lineno' if the return value is a newline char.
5269 Updates `js2-ts-cursor' to the point after the returned char.
5270 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5271 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5272 (let (c)
5273 ;; check for end of buffer
5274 (if (>= js2-ts-cursor (point-max))
5275 (setq js2-ts-hit-eof t
5276 js2-ts-cursor (1+ js2-ts-cursor)
5277 c js2-EOF_CHAR) ; return value
5278 ;; otherwise read next char
5279 (setq c (char-before (incf js2-ts-cursor)))
5280 ;; if we read a newline, update counters
5281 (if (= c ?\n)
5282 (setq js2-ts-line-start js2-ts-cursor
5283 js2-ts-lineno (1+ js2-ts-lineno)))
5284 ;; TODO: skip over format characters
5285 c)))
5286
5287 (defsubst js2-read-unicode-escape ()
5288 "Read a \\uNNNN sequence from the input.
5289 Assumes the ?\ and ?u have already been read.
5290 Returns the unicode character, or nil if it wasn't a valid character.
5291 Doesn't change the values of any scanner variables."
5292 ;; I really wish I knew a better way to do this, but I can't
5293 ;; find the Emacs function that takes a 16-bit int and converts
5294 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5295 ;; Have to first check that it's 4 hex characters or it may stop
5296 ;; the read early.
5297 (ignore-errors
5298 (let ((s (buffer-substring-no-properties js2-ts-cursor
5299 (+ 4 js2-ts-cursor))))
5300 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5301 (read (concat "?\\u" s))))))
5302
5303 (defsubst js2-match-char (test)
5304 "Consume and return next character if it matches TEST, a character.
5305 Returns nil and consumes nothing if TEST is not the next character."
5306 (let ((c (js2-get-char)))
5307 (if (eq c test)
5308 t
5309 (js2-unget-char)
5310 nil)))
5311
5312 (defsubst js2-peek-char ()
5313 (prog1
5314 (js2-get-char)
5315 (js2-unget-char)))
5316
5317 (defsubst js2-java-identifier-start-p (c)
5318 (or
5319 (memq c '(?$ ?_))
5320 (js2-char-uppercase-p c)
5321 (js2-char-lowercase-p c)))
5322
5323 (defsubst js2-java-identifier-part-p (c)
5324 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5325 ;; TODO: make me Unicode-friendly. See comments above.
5326 (or
5327 (memq c '(?$ ?_))
5328 (js2-char-uppercase-p c)
5329 (js2-char-lowercase-p c)
5330 (and (>= c ?0) (<= c ?9))))
5331
5332 (defsubst js2-alpha-p (c)
5333 (cond ((and (<= ?A c) (<= c ?Z)) t)
5334 ((and (<= ?a c) (<= c ?z)) t)
5335 (t nil)))
5336
5337 (defsubst js2-digit-p (c)
5338 (and (<= ?0 c) (<= c ?9)))
5339
5340 (defsubst js2-js-space-p (c)
5341 (if (<= c 127)
5342 (memq c '(#x20 #x9 #xB #xC #xD))
5343 (or
5344 (eq c #xA0)
5345 ;; TODO: change this nil to check for Unicode space character
5346 nil)))
5347
5348 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5349
5350 (defsubst js2-skip-line ()
5351 "Skip to end of line"
5352 (let (c)
5353 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5354 (js2-unget-char)
5355 (setq js2-token-end js2-ts-cursor)))
5356
5357 (defun js2-init-scanner (&optional buf line)
5358 "Create token stream for BUF starting on LINE.
5359 BUF defaults to current-buffer and line defaults to 1.
5360
5361 A buffer can only have one scanner active at a time, which yields
5362 dramatically simpler code than using a defstruct. If you need to
5363 have simultaneous scanners in a buffer, copy the regions to scan
5364 into temp buffers."
5365 (save-excursion
5366 (when buf
5367 (set-buffer buf))
5368 (setq js2-ts-dirty-line nil
5369 js2-ts-regexp-flags nil
5370 js2-ts-string ""
5371 js2-ts-number nil
5372 js2-ts-hit-eof nil
5373 js2-ts-line-start 0
5374 js2-ts-lineno (or line 1)
5375 js2-ts-line-end-char -1
5376 js2-ts-cursor (point-min)
5377 js2-ts-is-xml-attribute nil
5378 js2-ts-xml-is-tag-content nil
5379 js2-ts-xml-open-tags-count 0
5380 js2-ts-string-buffer nil)))
5381
5382 ;; This function uses the cached op, string and number fields in
5383 ;; TokenStream; if getToken has been called since the passed token
5384 ;; was scanned, the op or string printed may be incorrect.
5385 (defun js2-token-to-string (token)
5386 ;; Not sure where this function is used in Rhino. Not tested.
5387 (if (not js2-debug-print-trees)
5388 ""
5389 (let ((name (js2-token-name token)))
5390 (cond
5391 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5392 (concat name " `" js2-ts-string "'"))
5393 ((eq token js2-NUMBER)
5394 (format "NUMBER %g" js2-ts-number))
5395 (t
5396 name)))))
5397
5398 (defconst js2-keywords
5399 '(break
5400 case catch const continue
5401 debugger default delete do
5402 else enum
5403 false finally for function
5404 if in instanceof import
5405 let
5406 new null
5407 return
5408 switch
5409 this throw true try typeof
5410 var void
5411 while with
5412 yield))
5413
5414 ;; Token names aren't exactly the same as the keywords, unfortunately.
5415 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5416 (defconst js2-kwd-tokens
5417 (let ((table (make-vector js2-num-tokens nil))
5418 (tokens
5419 (list js2-BREAK
5420 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5421 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5422 js2-ELSE
5423 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5424 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5425 js2-LET
5426 js2-NEW js2-NULL
5427 js2-RETURN
5428 js2-SWITCH
5429 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5430 js2-VAR
5431 js2-WHILE js2-WITH
5432 js2-YIELD)))
5433 (dolist (i tokens)
5434 (aset table i 'font-lock-keyword-face))
5435 (aset table js2-STRING 'font-lock-string-face)
5436 (aset table js2-REGEXP 'font-lock-string-face)
5437 (aset table js2-COMMENT 'font-lock-comment-face)
5438 (aset table js2-THIS 'font-lock-builtin-face)
5439 (aset table js2-VOID 'font-lock-constant-face)
5440 (aset table js2-NULL 'font-lock-constant-face)
5441 (aset table js2-TRUE 'font-lock-constant-face)
5442 (aset table js2-FALSE 'font-lock-constant-face)
5443 table)
5444 "Vector whose values are non-nil for tokens that are keywords.
5445 The values are default faces to use for highlighting the keywords.")
5446
5447 (defconst js2-reserved-words
5448 '(abstract
5449 boolean byte
5450 char class
5451 double
5452 enum export extends
5453 final float
5454 goto
5455 implements import int interface
5456 long
5457 native
5458 package private protected public
5459 short static super synchronized
5460 throws transient
5461 volatile))
5462
5463 (defconst js2-keyword-names
5464 (let ((table (make-hash-table :test 'equal)))
5465 (loop for k in js2-keywords
5466 do (puthash
5467 (symbol-name k) ; instanceof
5468 (intern (concat "js2-"
5469 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5470 table))
5471 table)
5472 "JavaScript keywords by name, mapped to their symbols.")
5473
5474 (defconst js2-reserved-word-names
5475 (let ((table (make-hash-table :test 'equal)))
5476 (loop for k in js2-reserved-words
5477 do
5478 (puthash (symbol-name k) 'js2-RESERVED table))
5479 table)
5480 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5481
5482 (defsubst js2-collect-string (buf)
5483 "Convert BUF, a list of chars, to a string.
5484 Reverses BUF before converting."
5485 (cond
5486 ((stringp buf)
5487 buf)
5488 ((null buf) ; for emacs21 compat
5489 "")
5490 (t
5491 (if buf
5492 (apply #'string (nreverse buf))
5493 ""))))
5494
5495 (defun js2-string-to-keyword (s)
5496 "Return token for S, a string, if S is a keyword or reserved word.
5497 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5498 (or (gethash s js2-keyword-names)
5499 (gethash s js2-reserved-word-names)))
5500
5501 (defsubst js2-ts-set-char-token-bounds ()
5502 "Used when next token is one character."
5503 (setq js2-token-beg (1- js2-ts-cursor)
5504 js2-token-end js2-ts-cursor))
5505
5506 (defsubst js2-ts-return (token)
5507 "Return an N-character TOKEN from `js2-get-token'.
5508 Updates `js2-token-end' accordingly."
5509 (setq js2-token-end js2-ts-cursor)
5510 (throw 'return token))
5511
5512 (defsubst js2-x-digit-to-int (c accumulator)
5513 "Build up a hex number.
5514 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5515 corresponding number. Otherwise return -1."
5516 (catch 'return
5517 (catch 'check
5518 ;; Use 0..9 < A..Z < a..z
5519 (cond
5520 ((<= c ?9)
5521 (decf c ?0)
5522 (if (<= 0 c)
5523 (throw 'check nil)))
5524 ((<= c ?F)
5525 (when (<= ?A c)
5526 (decf c (- ?A 10))
5527 (throw 'check nil)))
5528 ((<= c ?f)
5529 (when (<= ?a c)
5530 (decf c (- ?a 10))
5531 (throw 'check nil))))
5532 (throw 'return -1))
5533 (logior c (lsh accumulator 4))))
5534
5535 (defun js2-get-token ()
5536 "Return next JavaScript token, an int such as js2-RETURN."
5537 (let (c
5538 c1
5539 identifier-start
5540 is-unicode-escape-start
5541 contains-escape
5542 escape-val
5543 escape-start
5544 str
5545 result
5546 base
5547 is-integer
5548 quote-char
5549 val
5550 look-for-slash
5551 continue)
5552 (catch 'return
5553 (while t
5554 ;; Eat whitespace, possibly sensitive to newlines.
5555 (setq continue t)
5556 (while continue
5557 (setq c (js2-get-char))
5558 (cond
5559 ((eq c js2-EOF_CHAR)
5560 (js2-ts-set-char-token-bounds)
5561 (throw 'return js2-EOF))
5562 ((eq c ?\n)
5563 (js2-ts-set-char-token-bounds)
5564 (setq js2-ts-dirty-line nil)
5565 (throw 'return js2-EOL))
5566 ((not (js2-js-space-p c))
5567 (if (/= c ?-) ; in case end of HTML comment
5568 (setq js2-ts-dirty-line t))
5569 (setq continue nil))))
5570 ;; Assume the token will be 1 char - fixed up below.
5571 (js2-ts-set-char-token-bounds)
5572 (when (eq c ?@)
5573 (throw 'return js2-XMLATTR))
5574 ;; identifier/keyword/instanceof?
5575 ;; watch out for starting with a <backslash>
5576 (cond
5577 ((eq c ?\\)
5578 (setq c (js2-get-char))
5579 (if (eq c ?u)
5580 (setq identifier-start t
5581 is-unicode-escape-start t
5582 js2-ts-string-buffer nil)
5583 (setq identifier-start nil)
5584 (js2-unget-char)
5585 (setq c ?\\)))
5586 (t
5587 (when (setq identifier-start (js2-java-identifier-start-p c))
5588 (setq js2-ts-string-buffer nil)
5589 (js2-add-to-string c))))
5590 (when identifier-start
5591 (setq contains-escape is-unicode-escape-start)
5592 (catch 'break
5593 (while t
5594 (if is-unicode-escape-start
5595 ;; strictly speaking we should probably push-back
5596 ;; all the bad characters if the <backslash>uXXXX
5597 ;; sequence is malformed. But since there isn't a
5598 ;; correct context(is there?) for a bad Unicode
5599 ;; escape sequence in an identifier, we can report
5600 ;; an error here.
5601 (progn
5602 (setq escape-val 0)
5603 (dotimes (i 4)
5604 (setq c (js2-get-char)
5605 escape-val (js2-x-digit-to-int c escape-val))
5606 ;; Next check takes care of c < 0 and bad escape
5607 (if (minusp escape-val)
5608 (throw 'break nil)))
5609 (if (minusp escape-val)
5610 (js2-report-scan-error "msg.invalid.escape" t))
5611 (js2-add-to-string escape-val)
5612 (setq is-unicode-escape-start nil))
5613 (setq c (js2-get-char))
5614 (cond
5615 ((eq c ?\\)
5616 (setq c (js2-get-char))
5617 (if (eq c ?u)
5618 (setq is-unicode-escape-start t
5619 contains-escape t)
5620 (js2-report-scan-error "msg.illegal.character" t)))
5621 (t
5622 (if (or (eq c js2-EOF_CHAR)
5623 (not (js2-java-identifier-part-p c)))
5624 (throw 'break nil))
5625 (js2-add-to-string c))))))
5626 (js2-unget-char)
5627 (setq str (js2-get-string-from-buffer))
5628 (unless contains-escape
5629 ;; OPT we shouldn't have to make a string (object!) to
5630 ;; check if it's a keyword.
5631 ;; Return the corresponding token if it's a keyword
5632 (when (setq result (js2-string-to-keyword str))
5633 (if (and (< js2-language-version 170)
5634 (memq result '(js2-LET js2-YIELD)))
5635 ;; LET and YIELD are tokens only in 1.7 and later
5636 (setq result 'js2-NAME))
5637 (if (not (eq result 'js2-RESERVED))
5638 (throw 'return (js2-token-code result)))
5639 (js2-report-warning "msg.reserved.keyword" str)))
5640 ;; If we want to intern these as Rhino does, just use (intern str)
5641 (setq js2-ts-string str)
5642 (throw 'return js2-NAME)) ; end identifier/kwd check
5643 ;; is it a number?
5644 (when (or (js2-digit-p c)
5645 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5646 (setq js2-ts-string-buffer nil
5647 base 10)
5648 (when (eq c ?0)
5649 (setq c (js2-get-char))
5650 (cond
5651 ((or (eq c ?x) (eq c ?X))
5652 (setq base 16)
5653 (setq c (js2-get-char)))
5654 ((js2-digit-p c)
5655 (setq base 8))
5656 (t
5657 (js2-add-to-string ?0))))
5658 (if (eq base 16)
5659 (while (<= 0 (js2-x-digit-to-int c 0))
5660 (js2-add-to-string c)
5661 (setq c (js2-get-char)))
5662 (while (and (<= ?0 c) (<= c ?9))
5663 ;; We permit 08 and 09 as decimal numbers, which
5664 ;; makes our behavior a superset of the ECMA
5665 ;; numeric grammar. We might not always be so
5666 ;; permissive, so we warn about it.
5667 (when (and (eq base 8) (>= c ?8))
5668 (js2-report-warning "msg.bad.octal.literal"
5669 (if (eq c ?8) "8" "9"))
5670 (setq base 10))
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char))))
5673 (setq is-integer t)
5674 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5675 (setq is-integer nil)
5676 (when (eq c ?.)
5677 (loop do
5678 (js2-add-to-string c)
5679 (setq c (js2-get-char))
5680 while (js2-digit-p c)))
5681 (when (memq c '(?e ?E))
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char))
5684 (when (memq c '(?+ ?-))
5685 (js2-add-to-string c)
5686 (setq c (js2-get-char)))
5687 (unless (js2-digit-p c)
5688 (js2-report-scan-error "msg.missing.exponent" t))
5689 (loop do
5690 (js2-add-to-string c)
5691 (setq c (js2-get-char))
5692 while (js2-digit-p c))))
5693 (js2-unget-char)
5694 (setq js2-ts-string (js2-get-string-from-buffer)
5695 js2-ts-number
5696 (if (and (eq base 10) (not is-integer))
5697 (string-to-number js2-ts-string)
5698 ;; TODO: call runtime number-parser. Some of it is in
5699 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5700 (string-to-number js2-ts-string)))
5701 (throw 'return js2-NUMBER))
5702 ;; is it a string?
5703 (when (memq c '(?\" ?\'))
5704 ;; We attempt to accumulate a string the fast way, by
5705 ;; building it directly out of the reader. But if there
5706 ;; are any escaped characters in the string, we revert to
5707 ;; building it out of a string buffer.
5708 (setq quote-char c
5709 js2-ts-string-buffer nil
5710 c (js2-get-char))
5711 (catch 'break
5712 (while (/= c quote-char)
5713 (catch 'continue
5714 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5715 (js2-unget-char)
5716 (setq js2-token-end js2-ts-cursor)
5717 (js2-report-error "msg.unterminated.string.lit")
5718 (throw 'return js2-STRING))
5719 (when (eq c ?\\)
5720 ;; We've hit an escaped character
5721 (setq c (js2-get-char))
5722 (case c
5723 (?b (setq c ?\b))
5724 (?f (setq c ?\f))
5725 (?n (setq c ?\n))
5726 (?r (setq c ?\r))
5727 (?t (setq c ?\t))
5728 (?v (setq c ?\v))
5729 (?u
5730 (setq c1 (js2-read-unicode-escape))
5731 (if js2-parse-ide-mode
5732 (if c1
5733 (progn
5734 ;; just copy the string in IDE-mode
5735 (js2-add-to-string ?\\)
5736 (js2-add-to-string ?u)
5737 (dotimes (i 3)
5738 (js2-add-to-string (js2-get-char)))
5739 (setq c (js2-get-char))) ; added at end of loop
5740 ;; flag it as an invalid escape
5741 (js2-report-warning "msg.invalid.escape"
5742 nil (- js2-ts-cursor 2) 6))
5743 ;; Get 4 hex digits; if the u escape is not
5744 ;; followed by 4 hex digits, use 'u' + the
5745 ;; literal character sequence that follows.
5746 (js2-add-to-string ?u)
5747 (setq escape-val 0)
5748 (dotimes (i 4)
5749 (setq c (js2-get-char)
5750 escape-val (js2-x-digit-to-int c escape-val))
5751 (if (minusp escape-val)
5752 (throw 'continue nil))
5753 (js2-add-to-string c))
5754 ;; prepare for replace of stored 'u' sequence by escape value
5755 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5756 c escape-val)))
5757 (?x
5758 ;; Get 2 hex digits, defaulting to 'x'+literal
5759 ;; sequence, as above.
5760 (setq c (js2-get-char)
5761 escape-val (js2-x-digit-to-int c 0))
5762 (if (minusp escape-val)
5763 (progn
5764 (js2-add-to-string ?x)
5765 (throw 'continue nil))
5766 (setq c1 c
5767 c (js2-get-char)
5768 escape-val (js2-x-digit-to-int c escape-val))
5769 (if (minusp escape-val)
5770 (progn
5771 (js2-add-to-string ?x)
5772 (js2-add-to-string c1)
5773 (throw 'continue nil))
5774 ;; got 2 hex digits
5775 (setq c escape-val))))
5776 (?\n
5777 ;; Remove line terminator after escape to follow
5778 ;; SpiderMonkey and C/C++
5779 (setq c (js2-get-char))
5780 (throw 'continue nil))
5781 (t
5782 (when (and (<= ?0 c) (< c ?8))
5783 (setq val (- c ?0)
5784 c (js2-get-char))
5785 (when (and (<= ?0 c) (< c ?8))
5786 (setq val (- (+ (* 8 val) c) ?0)
5787 c (js2-get-char))
5788 (when (and (<= ?0 c)
5789 (< c ?8)
5790 (< val #o37))
5791 ;; c is 3rd char of octal sequence only
5792 ;; if the resulting val <= 0377
5793 (setq val (- (+ (* 8 val) c) ?0)
5794 c (js2-get-char))))
5795 (js2-unget-char)
5796 (setq c val)))))
5797 (js2-add-to-string c)
5798 (setq c (js2-get-char)))))
5799 (setq js2-ts-string (js2-get-string-from-buffer))
5800 (throw 'return js2-STRING))
5801 (case c
5802 (?\;
5803 (throw 'return js2-SEMI))
5804 (?\[
5805 (throw 'return js2-LB))
5806 (?\]
5807 (throw 'return js2-RB))
5808 (?{
5809 (throw 'return js2-LC))
5810 (?}
5811 (throw 'return js2-RC))
5812 (?\(
5813 (throw 'return js2-LP))
5814 (?\)
5815 (throw 'return js2-RP))
5816 (?,
5817 (throw 'return js2-COMMA))
5818 (??
5819 (throw 'return js2-HOOK))
5820 (?:
5821 (if (js2-match-char ?:)
5822 (js2-ts-return js2-COLONCOLON)
5823 (throw 'return js2-COLON)))
5824 (?.
5825 (if (js2-match-char ?.)
5826 (js2-ts-return js2-DOTDOT)
5827 (if (js2-match-char ?\()
5828 (js2-ts-return js2-DOTQUERY)
5829 (throw 'return js2-DOT))))
5830 (?|
5831 (if (js2-match-char ?|)
5832 (throw 'return js2-OR)
5833 (if (js2-match-char ?=)
5834 (js2-ts-return js2-ASSIGN_BITOR)
5835 (throw 'return js2-BITOR))))
5836 (?^
5837 (if (js2-match-char ?=)
5838 (js2-ts-return js2-ASSIGN_BITOR)
5839 (throw 'return js2-BITXOR)))
5840 (?&
5841 (if (js2-match-char ?&)
5842 (throw 'return js2-AND)
5843 (if (js2-match-char ?=)
5844 (js2-ts-return js2-ASSIGN_BITAND)
5845 (throw 'return js2-BITAND))))
5846 (?=
5847 (if (js2-match-char ?=)
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-SHEQ)
5850 (throw 'return js2-EQ))
5851 (throw 'return js2-ASSIGN)))
5852 (?!
5853 (if (js2-match-char ?=)
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-SHNE)
5856 (js2-ts-return js2-NE))
5857 (throw 'return js2-NOT)))
5858 (?<
5859 ;; NB:treat HTML begin-comment as comment-till-eol
5860 (when (js2-match-char ?!)
5861 (when (js2-match-char ?-)
5862 (when (js2-match-char ?-)
5863 (js2-skip-line)
5864 (setq js2-ts-comment-type 'html)
5865 (throw 'return js2-COMMENT)))
5866 (js2-unget-char))
5867 (if (js2-match-char ?<)
5868 (if (js2-match-char ?=)
5869 (js2-ts-return js2-ASSIGN_LSH)
5870 (js2-ts-return js2-LSH))
5871 (if (js2-match-char ?=)
5872 (js2-ts-return js2-LE)
5873 (throw 'return js2-LT))))
5874 (?>
5875 (if (js2-match-char ?>)
5876 (if (js2-match-char ?>)
5877 (if (js2-match-char ?=)
5878 (js2-ts-return js2-ASSIGN_URSH)
5879 (js2-ts-return js2-URSH))
5880 (if (js2-match-char ?=)
5881 (js2-ts-return js2-ASSIGN_RSH)
5882 (js2-ts-return js2-RSH)))
5883 (if (js2-match-char ?=)
5884 (js2-ts-return js2-GE)
5885 (throw 'return js2-GT))))
5886 (?*
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-ASSIGN_MUL)
5889 (throw 'return js2-MUL)))
5890 (?/
5891 ;; is it a // comment?
5892 (when (js2-match-char ?/)
5893 (setq js2-token-beg (- js2-ts-cursor 2))
5894 (js2-skip-line)
5895 (setq js2-ts-comment-type 'line)
5896 ;; include newline so highlighting goes to end of window
5897 (incf js2-token-end)
5898 (throw 'return js2-COMMENT))
5899 ;; is it a /* comment?
5900 (when (js2-match-char ?*)
5901 (setq look-for-slash nil
5902 js2-token-beg (- js2-ts-cursor 2)
5903 js2-ts-comment-type
5904 (if (js2-match-char ?*)
5905 (progn
5906 (setq look-for-slash t)
5907 'jsdoc)
5908 'block))
5909 (while t
5910 (setq c (js2-get-char))
5911 (cond
5912 ((eq c js2-EOF_CHAR)
5913 (setq js2-token-end (1- js2-ts-cursor))
5914 (js2-report-error "msg.unterminated.comment")
5915 (throw 'return js2-COMMENT))
5916 ((eq c ?*)
5917 (setq look-for-slash t))
5918 ((eq c ?/)
5919 (if look-for-slash
5920 (js2-ts-return js2-COMMENT)))
5921 (t
5922 (setq look-for-slash nil
5923 js2-token-end js2-ts-cursor)))))
5924 (if (js2-match-char ?=)
5925 (js2-ts-return js2-ASSIGN_DIV)
5926 (throw 'return js2-DIV)))
5927 (?#
5928 (when js2-skip-preprocessor-directives
5929 (js2-skip-line)
5930 (setq js2-ts-comment-type 'preprocessor
5931 js2-token-end js2-ts-cursor)
5932 (throw 'return js2-COMMENT))
5933 (throw 'return js2-ERROR))
5934 (?%
5935 (if (js2-match-char ?=)
5936 (js2-ts-return js2-ASSIGN_MOD)
5937 (throw 'return js2-MOD)))
5938 (?~
5939 (throw 'return js2-BITNOT))
5940 (?+
5941 (if (js2-match-char ?=)
5942 (js2-ts-return js2-ASSIGN_ADD)
5943 (if (js2-match-char ?+)
5944 (js2-ts-return js2-INC)
5945 (throw 'return js2-ADD))))
5946 (?-
5947 (cond
5948 ((js2-match-char ?=)
5949 (setq c js2-ASSIGN_SUB))
5950 ((js2-match-char ?-)
5951 (unless js2-ts-dirty-line
5952 ;; treat HTML end-comment after possible whitespace
5953 ;; after line start as comment-until-eol
5954 (when (js2-match-char ?>)
5955 (js2-skip-line)
5956 (setq js2-ts-comment-type 'html)
5957 (throw 'return js2-COMMENT)))
5958 (setq c js2-DEC))
5959 (t
5960 (setq c js2-SUB)))
5961 (setq js2-ts-dirty-line t)
5962 (js2-ts-return c))
5963 (otherwise
5964 (js2-report-scan-error "msg.illegal.character")))))))
5965
5966 (defun js2-read-regexp (start-token)
5967 "Called by parser when it gets / or /= in literal context."
5968 (let (c
5969 err
5970 in-class ; inside a '[' .. ']' character-class
5971 flags
5972 (continue t))
5973 (setq js2-token-beg js2-ts-cursor
5974 js2-ts-string-buffer nil
5975 js2-ts-regexp-flags nil)
5976 (if (eq start-token js2-ASSIGN_DIV)
5977 ;; mis-scanned /=
5978 (js2-add-to-string ?=)
5979 (if (not (eq start-token js2-DIV))
5980 (error "failed assertion")))
5981 (while (and (not err)
5982 (or (/= (setq c (js2-get-char)) ?/)
5983 in-class))
5984 (cond
5985 ((or (= c ?\n)
5986 (= c js2-EOF_CHAR))
5987 (setq js2-token-end (1- js2-ts-cursor)
5988 err t
5989 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5990 (js2-report-error "msg.unterminated.re.lit"))
5991 (t (cond
5992 ((= c ?\\)
5993 (js2-add-to-string c)
5994 (setq c (js2-get-char)))
5995 ((= c ?\[)
5996 (setq in-class t))
5997 ((= c ?\])
5998 (setq in-class nil)))
5999 (js2-add-to-string c))))
6000 (unless err
6001 (while continue
6002 (cond
6003 ((js2-match-char ?g)
6004 (push ?g flags))
6005 ((js2-match-char ?i)
6006 (push ?i flags))
6007 ((js2-match-char ?m)
6008 (push ?m flags))
6009 (t
6010 (setq continue nil))))
6011 (if (js2-alpha-p (js2-peek-char))
6012 (js2-report-scan-error "msg.invalid.re.flag" t
6013 js2-ts-cursor 1))
6014 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6015 js2-ts-regexp-flags (js2-collect-string flags)
6016 js2-token-end js2-ts-cursor)
6017 ;; tell `parse-partial-sexp' to ignore this range of chars
6018 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6019
6020 (defun js2-get-first-xml-token ()
6021 (setq js2-ts-xml-open-tags-count 0
6022 js2-ts-is-xml-attribute nil
6023 js2-ts-xml-is-tag-content nil)
6024 (js2-unget-char)
6025 (js2-get-next-xml-token))
6026
6027 (defsubst js2-xml-discard-string ()
6028 "Throw away the string in progress and flag an XML parse error."
6029 (setq js2-ts-string-buffer nil
6030 js2-ts-string nil)
6031 (js2-report-scan-error "msg.XML.bad.form" t))
6032
6033 (defun js2-get-next-xml-token ()
6034 (setq js2-ts-string-buffer nil ; for recording the XML
6035 js2-token-beg js2-ts-cursor)
6036 (let (c result)
6037 (setq result
6038 (catch 'return
6039 (while t
6040 (setq c (js2-get-char))
6041 (cond
6042 ((= c js2-EOF_CHAR)
6043 (throw 'return js2-ERROR))
6044 (js2-ts-xml-is-tag-content
6045 (case c
6046 (?>
6047 (js2-add-to-string c)
6048 (setq js2-ts-xml-is-tag-content nil
6049 js2-ts-is-xml-attribute nil))
6050 (?/
6051 (js2-add-to-string c)
6052 (when (eq ?> (js2-peek-char))
6053 (setq c (js2-get-char))
6054 (js2-add-to-string c)
6055 (setq js2-ts-xml-is-tag-content nil)
6056 (decf js2-ts-xml-open-tags-count)))
6057 (?{
6058 (js2-unget-char)
6059 (setq js2-ts-string (js2-get-string-from-buffer))
6060 (throw 'return js2-XML))
6061 ((?\' ?\")
6062 (js2-add-to-string c)
6063 (unless (js2-read-quoted-string c)
6064 (throw 'return js2-ERROR)))
6065 (?=
6066 (js2-add-to-string c)
6067 (setq js2-ts-is-xml-attribute t))
6068 ((? ?\t ?\r ?\n)
6069 (js2-add-to-string c))
6070 (t
6071 (js2-add-to-string c)
6072 (setq js2-ts-is-xml-attribute nil)))
6073 (when (and (not js2-ts-xml-is-tag-content)
6074 (zerop js2-ts-xml-open-tags-count))
6075 (setq js2-ts-string (js2-get-string-from-buffer))
6076 (throw 'return js2-XMLEND)))
6077 (t
6078 ;; else not tag content
6079 (case c
6080 (?<
6081 (js2-add-to-string c)
6082 (setq c (js2-peek-char))
6083 (case c
6084 (?!
6085 (setq c (js2-get-char)) ;; skip !
6086 (js2-add-to-string c)
6087 (setq c (js2-peek-char))
6088 (case c
6089 (?-
6090 (setq c (js2-get-char)) ;; skip -
6091 (js2-add-to-string c)
6092 (if (eq c ?-)
6093 (progn
6094 (js2-add-to-string c)
6095 (unless (js2-read-xml-comment)
6096 (throw 'return js2-ERROR)))
6097 (js2-xml-discard-string)
6098 (throw 'return js2-ERROR)))
6099 (?\[
6100 (setq c (js2-get-char)) ;; skip [
6101 (js2-add-to-string c)
6102 (if (and (= (js2-get-char) ?C)
6103 (= (js2-get-char) ?D)
6104 (= (js2-get-char) ?A)
6105 (= (js2-get-char) ?T)
6106 (= (js2-get-char) ?A)
6107 (= (js2-get-char) ?\[))
6108 (progn
6109 (js2-add-to-string ?C)
6110 (js2-add-to-string ?D)
6111 (js2-add-to-string ?A)
6112 (js2-add-to-string ?T)
6113 (js2-add-to-string ?A)
6114 (js2-add-to-string ?\[)
6115 (unless (js2-read-cdata)
6116 (throw 'return js2-ERROR)))
6117 (js2-xml-discard-string)
6118 (throw 'return js2-ERROR)))
6119 (t
6120 (unless (js2-read-entity)
6121 (throw 'return js2-ERROR)))))
6122 (??
6123 (setq c (js2-get-char)) ;; skip ?
6124 (js2-add-to-string c)
6125 (unless (js2-read-PI)
6126 (throw 'return js2-ERROR)))
6127 (?/
6128 ;; end tag
6129 (setq c (js2-get-char)) ;; skip /
6130 (js2-add-to-string c)
6131 (when (zerop js2-ts-xml-open-tags-count)
6132 (js2-xml-discard-string)
6133 (throw 'return js2-ERROR))
6134 (setq js2-ts-xml-is-tag-content t)
6135 (decf js2-ts-xml-open-tags-count))
6136 (t
6137 ;; start tag
6138 (setq js2-ts-xml-is-tag-content t)
6139 (incf js2-ts-xml-open-tags-count))))
6140 (?{
6141 (js2-unget-char)
6142 (setq js2-ts-string (js2-get-string-from-buffer))
6143 (throw 'return js2-XML))
6144 (t
6145 (js2-add-to-string c))))))))
6146 (setq js2-token-end js2-ts-cursor)
6147 result))
6148
6149 (defun js2-read-quoted-string (quote)
6150 (let (c)
6151 (catch 'return
6152 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6153 (js2-add-to-string c)
6154 (if (eq c quote)
6155 (throw 'return t)))
6156 (js2-xml-discard-string) ;; throw away string in progress
6157 nil)))
6158
6159 (defun js2-read-xml-comment ()
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-cdata ()
6179 (let ((c (js2-get-char)))
6180 (catch 'return
6181 (while (/= c js2-EOF_CHAR)
6182 (catch 'continue
6183 (js2-add-to-string c)
6184 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6185 (setq c (js2-get-char))
6186 (js2-add-to-string c)
6187 (if (eq (js2-peek-char) ?>)
6188 (progn
6189 (setq c (js2-get-char)) ;; Skip >
6190 (js2-add-to-string c)
6191 (throw 'return t))
6192 (throw 'continue nil)))
6193 (setq c (js2-get-char))))
6194 (js2-xml-discard-string)
6195 nil)))
6196
6197 (defun js2-read-entity ()
6198 (let ((decl-tags 1)
6199 c)
6200 (catch 'return
6201 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6202 (js2-add-to-string c)
6203 (case c
6204 (?<
6205 (incf decl-tags))
6206 (?>
6207 (decf decl-tags)
6208 (if (zerop decl-tags)
6209 (throw 'return t)))))
6210 (js2-xml-discard-string)
6211 nil)))
6212
6213 (defun js2-read-PI ()
6214 "Scan an XML processing instruction."
6215 (let (c)
6216 (catch 'return
6217 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6218 (js2-add-to-string c)
6219 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6220 (setq c (js2-get-char)) ;; Skip >
6221 (js2-add-to-string c)
6222 (throw 'return t)))
6223 (js2-xml-discard-string)
6224 nil)))
6225
6226 (defun js2-scanner-get-line ()
6227 "Return the text of the current scan line."
6228 (buffer-substring (point-at-bol) (point-at-eol)))
6229
6230 ;;; Highlighting
6231
6232 (defsubst js2-set-face (beg end face &optional record)
6233 "Fontify a region. If RECORD is non-nil, record for later."
6234 (when (plusp js2-highlight-level)
6235 (setq beg (min (point-max) beg)
6236 beg (max (point-min) beg)
6237 end (min (point-max) end)
6238 end (max (point-min) end))
6239 (if record
6240 (push (list beg end face) js2-mode-fontifications)
6241 (put-text-property beg end 'face face))))
6242
6243 (defsubst js2-set-kid-face (pos kid len face)
6244 "Set-face on a child node.
6245 POS is absolute buffer position of parent.
6246 KID is the child node.
6247 LEN is the length to fontify.
6248 FACE is the face to fontify with."
6249 (js2-set-face (+ pos (js2-node-pos kid))
6250 (+ pos (js2-node-pos kid) (js2-node-len kid))
6251 face))
6252
6253 (defsubst js2-fontify-kwd (start length)
6254 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6255
6256 (defsubst js2-clear-face (beg end)
6257 (remove-text-properties beg end '(face nil
6258 help-echo nil
6259 point-entered nil
6260 c-in-sws nil)))
6261
6262 (defsubst js2-record-text-property (beg end prop value)
6263 "Record a text property to set when parsing finishes."
6264 (push (list beg end prop value) js2-mode-deferred-properties))
6265
6266 (defconst js2-ecma-global-props
6267 (concat "^"
6268 (regexp-opt
6269 '("Infinity" "NaN" "undefined" "arguments") t)
6270 "$")
6271 "Value properties of the Ecma-262 Global Object.
6272 Shown at or above `js2-highlight-level' 2.")
6273
6274 ;; might want to add the name "arguments" to this list?
6275 (defconst js2-ecma-object-props
6276 (concat "^"
6277 (regexp-opt
6278 '("prototype" "__proto__" "__parent__") t)
6279 "$")
6280 "Value properties of the Ecma-262 Object constructor.
6281 Shown at or above `js2-highlight-level' 2.")
6282
6283 (defconst js2-ecma-global-funcs
6284 (concat
6285 "^"
6286 (regexp-opt
6287 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6288 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6289 "$")
6290 "Function properties of the Ecma-262 Global object.
6291 Shown at or above `js2-highlight-level' 2.")
6292
6293 (defconst js2-ecma-number-props
6294 (concat "^"
6295 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6296 "NEGATIVE_INFINITY"
6297 "POSITIVE_INFINITY") t)
6298 "$")
6299 "Properties of the Ecma-262 Number constructor.
6300 Shown at or above `js2-highlight-level' 2.")
6301
6302 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6303 "Properties of the Ecma-262 Date constructor.
6304 Shown at or above `js2-highlight-level' 2.")
6305
6306 (defconst js2-ecma-math-props
6307 (concat "^"
6308 (regexp-opt
6309 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6310 t)
6311 "$")
6312 "Properties of the Ecma-262 Math object.
6313 Shown at or above `js2-highlight-level' 2.")
6314
6315 (defconst js2-ecma-math-funcs
6316 (concat "^"
6317 (regexp-opt
6318 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6319 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6320 "$")
6321 "Function properties of the Ecma-262 Math object.
6322 Shown at or above `js2-highlight-level' 2.")
6323
6324 (defconst js2-ecma-function-props
6325 (concat
6326 "^"
6327 (regexp-opt
6328 '(;; properties of the Object prototype object
6329 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6330 "toLocaleString" "toString" "valueOf"
6331 ;; properties of the Function prototype object
6332 "apply" "call"
6333 ;; properties of the Array prototype object
6334 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6335 "splice" "unshift"
6336 ;; properties of the String prototype object
6337 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6338 "localeCompare" "match" "replace" "search" "split" "substring"
6339 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6340 "toUpperCase"
6341 ;; properties of the Number prototype object
6342 "toExponential" "toFixed" "toPrecision"
6343 ;; properties of the Date prototype object
6344 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6345 "getMinutes" "getMonth" "getSeconds" "getTime"
6346 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6347 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6348 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6349 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6350 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6351 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6352 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6353 "toTimeString" "toUTCString"
6354 ;; properties of the RegExp prototype object
6355 "exec" "test"
6356 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6357 "toSource" "__defineGetter__" "__defineSetter__"
6358 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6359 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6360 t)
6361 "$")
6362 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6363 Shown at or above `js2-highlight-level' 3.")
6364
6365 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6366 (let ((target-name (and target
6367 (js2-name-node-p target)
6368 (js2-name-node-name target)))
6369 (prop-name (if prop (js2-name-node-name prop)))
6370 (level1 (>= js2-highlight-level 1))
6371 (level2 (>= js2-highlight-level 2))
6372 (level3 (>= js2-highlight-level 3))
6373 pos
6374 face)
6375 (when level2
6376 (if call-p
6377 (cond
6378 ((and target prop)
6379 (cond
6380 ((and level3 (string-match js2-ecma-function-props prop-name))
6381 (setq face 'font-lock-builtin-face))
6382 ((and target-name prop)
6383 (cond
6384 ((string= target-name "Date")
6385 (if (string-match js2-ecma-date-props prop-name)
6386 (setq face 'font-lock-builtin-face)))
6387 ((string= target-name "Math")
6388 (if (string-match js2-ecma-math-funcs prop-name)
6389 (setq face 'font-lock-builtin-face)))))))
6390 (prop
6391 (if (string-match js2-ecma-global-funcs prop-name)
6392 (setq face 'font-lock-builtin-face))))
6393 (cond
6394 ((and target prop)
6395 (cond
6396 ((string= target-name "Number")
6397 (if (string-match js2-ecma-number-props prop-name)
6398 (setq face 'font-lock-constant-face)))
6399 ((string= target-name "Math")
6400 (if (string-match js2-ecma-math-props prop-name)
6401 (setq face 'font-lock-constant-face)))))
6402 (prop
6403 (if (string-match js2-ecma-object-props prop-name)
6404 (setq face 'font-lock-constant-face)))))
6405 (when face
6406 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6407 (js2-node-pos prop))) ; relative
6408 (+ pos (js2-node-len prop))
6409 face)))))
6410
6411 (defun js2-parse-highlight-member-expr-node (node)
6412 "Perform syntax highlighting of EcmaScript built-in properties.
6413 The variable `js2-highlight-level' governs this highighting."
6414 (let (face target prop name pos end parent call-p callee)
6415 (cond
6416 ;; case 1: simple name, e.g. foo
6417 ((js2-name-node-p node)
6418 (setq name (js2-name-node-name node))
6419 ;; possible for name to be nil in rare cases - saw it when
6420 ;; running js2-mode on an elisp buffer. Might as well try to
6421 ;; make it so js2-mode never barfs.
6422 (when name
6423 (setq face (if (string-match js2-ecma-global-props name)
6424 'font-lock-constant-face))
6425 (when face
6426 (setq pos (js2-node-pos node)
6427 end (+ pos (js2-node-len node)))
6428 (js2-set-face pos end face))))
6429 ;; case 2: property access or function call
6430 ((or (js2-prop-get-node-p node)
6431 ;; highlight function call if expr is a prop-get node
6432 ;; or a plain name (i.e. unqualified function call)
6433 (and (setq call-p (js2-call-node-p node))
6434 (setq callee (js2-call-node-target node)) ; separate setq!
6435 (or (js2-prop-get-node-p callee)
6436 (js2-name-node-p callee))))
6437 (setq parent node
6438 node (if call-p callee node))
6439 (if (and call-p (js2-name-node-p callee))
6440 (setq prop callee)
6441 (setq target (js2-prop-get-node-left node)
6442 prop (js2-prop-get-node-right node)))
6443 (cond
6444 ((js2-name-node-p target)
6445 (if (js2-name-node-p prop)
6446 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6447 (js2-parse-highlight-prop-get parent target prop call-p)
6448 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6449 (js2-parse-highlight-prop-get parent target nil call-p)))
6450 ((js2-name-node-p prop)
6451 ;; case 2c: complex target, simple name, e.g. x[y].bar
6452 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6453
6454 (defun js2-parse-highlight-member-expr-fn-name (expr)
6455 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6456 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6457 We currently only handle the case where the last component is a prop-get
6458 of a simple name. Called before EXPR has a parent node."
6459 (let (pos
6460 (name (and (js2-prop-get-node-p expr)
6461 (js2-prop-get-node-right expr))))
6462 (when (js2-name-node-p name)
6463 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6464 (js2-node-pos name)))
6465 (+ pos (js2-node-len name))
6466 'font-lock-function-name-face
6467 'record))))
6468
6469 ;; source: http://jsdoc.sourceforge.net/
6470 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6471 ;; allows type specifications, and needs work before entering the wild.
6472
6473 (defconst js2-jsdoc-param-tag-regexp
6474 (concat "^\\s-*\\*+\\s-*\\(@"
6475 "\\(?:param\\|argument\\)"
6476 "\\)"
6477 "\\s-*\\({[^}]+}\\)?" ; optional type
6478 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6479 "\\>")
6480 "Matches jsdoc tags with optional type and optional param name.")
6481
6482 (defconst js2-jsdoc-typed-tag-regexp
6483 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6484 (regexp-opt
6485 '("enum"
6486 "extends"
6487 "field"
6488 "id"
6489 "implements"
6490 "lends"
6491 "mods"
6492 "requires"
6493 "return"
6494 "returns"
6495 "throw"
6496 "throws"))
6497 "\\)\\)\\s-*\\({[^}]+}\\)?")
6498 "Matches jsdoc tags with optional type.")
6499
6500 (defconst js2-jsdoc-arg-tag-regexp
6501 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6502 (regexp-opt
6503 '("alias"
6504 "augments"
6505 "borrows"
6506 "bug"
6507 "base"
6508 "config"
6509 "default"
6510 "define"
6511 "exception"
6512 "function"
6513 "member"
6514 "memberOf"
6515 "name"
6516 "namespace"
6517 "property"
6518 "since"
6519 "suppress"
6520 "this"
6521 "throws"
6522 "type"
6523 "version"))
6524 "\\)\\)\\s-+\\([^ \t]+\\)")
6525 "Matches jsdoc tags with a single argument.")
6526
6527 (defconst js2-jsdoc-empty-tag-regexp
6528 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6529 (regexp-opt
6530 '("addon"
6531 "author"
6532 "class"
6533 "const"
6534 "constant"
6535 "constructor"
6536 "constructs"
6537 "deprecated"
6538 "desc"
6539 "description"
6540 "event"
6541 "example"
6542 "exec"
6543 "export"
6544 "fileoverview"
6545 "final"
6546 "function"
6547 "hidden"
6548 "ignore"
6549 "implicitCast"
6550 "inheritDoc"
6551 "inner"
6552 "interface"
6553 "license"
6554 "noalias"
6555 "noshadow"
6556 "notypecheck"
6557 "override"
6558 "owner"
6559 "preserve"
6560 "preserveTry"
6561 "private"
6562 "protected"
6563 "public"
6564 "static"
6565 "supported"
6566 ))
6567 "\\)\\)\\s-*")
6568 "Matches empty jsdoc tags.")
6569
6570 (defconst js2-jsdoc-link-tag-regexp
6571 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6572 "Matches a jsdoc link or code tag.")
6573
6574 (defconst js2-jsdoc-see-tag-regexp
6575 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6576 "Matches a jsdoc @see tag.")
6577
6578 (defconst js2-jsdoc-html-tag-regexp
6579 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6580 "Matches a simple (no attributes) html start- or end-tag.")
6581
6582 (defsubst js2-jsdoc-highlight-helper ()
6583 (js2-set-face (match-beginning 1)
6584 (match-end 1)
6585 'js2-jsdoc-tag-face)
6586 (if (match-beginning 2)
6587 (if (save-excursion
6588 (goto-char (match-beginning 2))
6589 (= (char-after) ?{))
6590 (js2-set-face (1+ (match-beginning 2))
6591 (1- (match-end 2))
6592 'js2-jsdoc-type-face)
6593 (js2-set-face (match-beginning 2)
6594 (match-end 2)
6595 'js2-jsdoc-value-face)))
6596 (if (match-beginning 3)
6597 (js2-set-face (match-beginning 3)
6598 (match-end 3)
6599 'js2-jsdoc-value-face)))
6600
6601 (defun js2-highlight-jsdoc (ast)
6602 "Highlight doc comment tags."
6603 (let ((comments (js2-ast-root-comments ast))
6604 beg end)
6605 (save-excursion
6606 (dolist (node comments)
6607 (when (eq (js2-comment-node-format node) 'jsdoc)
6608 (setq beg (js2-node-abs-pos node)
6609 end (+ beg (js2-node-len node)))
6610 (save-restriction
6611 (narrow-to-region beg end)
6612 (dolist (re (list js2-jsdoc-param-tag-regexp
6613 js2-jsdoc-typed-tag-regexp
6614 js2-jsdoc-arg-tag-regexp
6615 js2-jsdoc-link-tag-regexp
6616 js2-jsdoc-see-tag-regexp
6617 js2-jsdoc-empty-tag-regexp))
6618 (goto-char beg)
6619 (while (re-search-forward re nil t)
6620 (js2-jsdoc-highlight-helper)))
6621 ;; simple highlighting for html tags
6622 (goto-char beg)
6623 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6624 (js2-set-face (match-beginning 1)
6625 (match-end 1)
6626 'js2-jsdoc-html-tag-delimiter-face)
6627 (js2-set-face (match-beginning 2)
6628 (match-end 2)
6629 'js2-jsdoc-html-tag-name-face)
6630 (js2-set-face (match-beginning 3)
6631 (match-end 3)
6632 'js2-jsdoc-html-tag-delimiter-face))))))))
6633
6634 (defun js2-highlight-assign-targets (node left right)
6635 "Highlight function properties and external variables."
6636 (let (leftpos end name)
6637 ;; highlight vars and props assigned function values
6638 (when (js2-function-node-p right)
6639 (cond
6640 ;; var foo = function() {...}
6641 ((js2-name-node-p left)
6642 (setq name left))
6643 ;; foo.bar.baz = function() {...}
6644 ((and (js2-prop-get-node-p left)
6645 (js2-name-node-p (js2-prop-get-node-right left)))
6646 (setq name (js2-prop-get-node-right left))))
6647 (when name
6648 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6649 (+ leftpos (js2-node-len name))
6650 'font-lock-function-name-face
6651 'record)))))
6652
6653 (defun js2-record-name-node (node)
6654 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6655 later. NODE must be a name node."
6656 (push (list node js2-current-scope
6657 (setq leftpos (js2-node-abs-pos node))
6658 (setq end (+ leftpos (js2-node-len node))))
6659 js2-recorded-identifiers))
6660
6661 (defun js2-highlight-undeclared-vars ()
6662 "After entire parse is finished, look for undeclared variable references.
6663 We have to wait until entire buffer is parsed, since JavaScript permits var
6664 decls to occur after they're used.
6665
6666 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6667 it is considered declared."
6668 (let (name)
6669 (dolist (entry js2-recorded-identifiers)
6670 (destructuring-bind (name-node scope pos end) entry
6671 (setq name (js2-name-node-name name-node))
6672 (unless (or (member name js2-global-externs)
6673 (member name js2-default-externs)
6674 (member name js2-additional-externs)
6675 (js2-get-defining-scope scope name))
6676 (js2-set-face pos end 'js2-external-variable-face 'record)
6677 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6678 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6679 (setq js2-recorded-identifiers nil)))
6680
6681 ;;; IMenu support
6682
6683 ;; We currently only support imenu, but eventually should support speedbar and
6684 ;; possibly other browsing mechanisms.
6685
6686 ;; The basic strategy is to identify function assignment targets of the form
6687 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6688 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6689 ;; for imenu after parsing is finished.
6690
6691 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6692 ;; JavaScript, and the general problem is undecidable. However, several forms
6693 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6694 ;; include:
6695
6696 ;; function foo() -- function declaration
6697 ;; foo = function() -- function expression assigned to variable
6698 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6699 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6700 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6701 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6702 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6703 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6704 ;; function foo() {function bar() {...}} -- nested function
6705 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6706
6707 ;; This list boils down to a few forms that can be combined recursively.
6708 ;; Top-level named function declarations include both the left-hand (name)
6709 ;; and the right-hand (function value) expressions needed to produce an imenu
6710 ;; entry. The other "right-hand" forms we need to look for are:
6711 ;; - functions declared as props/getters/setters in object literals
6712 ;; - nested named function declarations
6713 ;; The "left-hand" expressions that functions can be assigned to include:
6714 ;; - local/global variables
6715 ;; - nested property-get expressions like a.b.c.d
6716 ;; - element gets like foo[10] or foo['bar'] where the index
6717 ;; expression can be trivially converted to a property name. They
6718 ;; effectively then become property gets.
6719
6720 ;; All the different definition types are canonicalized into the form
6721 ;; foo.bar.baz = position-of-function-keyword
6722
6723 ;; We need to build a trie-like structure for imenu. As an example,
6724 ;; consider the following JavaScript code:
6725
6726 ;; a = function() {...} // function at position 5
6727 ;; b = function() {...} // function at position 25
6728 ;; foo = function() {...} // function at position 100
6729 ;; foo.bar = function() {...} // function at position 200
6730 ;; foo.bar.baz = function() {...} // function at position 300
6731 ;; foo.bar.zab = function() {...} // function at position 400
6732
6733 ;; During parsing we accumulate an entry for each definition in
6734 ;; the variable `js2-imenu-recorder', like so:
6735
6736 ;; '((a 5)
6737 ;; (b 25)
6738 ;; (foo 100)
6739 ;; (foo bar 200)
6740 ;; (foo bar baz 300)
6741 ;; (foo bar zab 400))
6742
6743 ;; After parsing these entries are merged into this alist-trie:
6744
6745 ;; '((a . 1)
6746 ;; (b . 2)
6747 ;; (foo (<definition> . 3)
6748 ;; (bar (<definition> . 6)
6749 ;; (baz . 100)
6750 ;; (zab . 200))))
6751
6752 ;; Note the wacky need for a <definition> name. The token can be anything
6753 ;; that isn't a valid JavaScript identifier, because you might make foo
6754 ;; a function and then start setting properties on it that are also functions.
6755
6756 (defsubst js2-prop-node-name (node)
6757 "Return the name of a node that may be a property-get/property-name.
6758 If NODE is not a valid name-node, string-node or integral number-node,
6759 returns nil. Otherwise returns the string name/value of the node."
6760 (cond
6761 ((js2-name-node-p node)
6762 (js2-name-node-name node))
6763 ((js2-string-node-p node)
6764 (js2-string-node-value node))
6765 ((and (js2-number-node-p node)
6766 (string-match "^[0-9]+$" (js2-number-node-value node)))
6767 (js2-number-node-value node))
6768 ((js2-this-node-p node)
6769 "this")))
6770
6771 (defsubst js2-node-qname-component (node)
6772 "Test function: return the name of this node, if it contributes to a qname.
6773 Returns nil if the node doesn't contribute."
6774 (copy-sequence
6775 (or (js2-prop-node-name node)
6776 (if (and (js2-function-node-p node)
6777 (js2-function-node-name node))
6778 (js2-name-node-name (js2-function-node-name node))))))
6779
6780 (defsubst js2-record-function-qname (fn-node qname)
6781 "Associate FN-NODE with its QNAME for later lookup.
6782 This is used in postprocessing the chain list. When we find a chain
6783 whose first element is a js2-THIS keyword node, we look up the parent
6784 function and see (using this map) whether it is the tail of a chain.
6785 If so, we replace the this-node with a copy of the parent's qname."
6786 (unless js2-imenu-function-map
6787 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6788 (puthash fn-node qname js2-imenu-function-map))
6789
6790 (defun js2-record-imenu-functions (node &optional var)
6791 "Record function definitions for imenu.
6792 NODE is a function node or an object literal.
6793 VAR, if non-nil, is the expression that NODE is being assigned to."
6794 (when js2-parse-ide-mode
6795 (let ((fun-p (js2-function-node-p node))
6796 qname left fname-node pos)
6797 (cond
6798 ;; non-anonymous function declaration?
6799 ((and fun-p
6800 (not var)
6801 (setq fname-node (js2-function-node-name node)))
6802 (push (setq qname (list fname-node (js2-node-pos node)))
6803 js2-imenu-recorder)
6804 (js2-record-function-qname node qname))
6805 ;; for remaining forms, compute left-side tree branch first
6806 ((and var (setq qname (js2-compute-nested-prop-get var)))
6807 (cond
6808 ;; foo.bar.baz = function
6809 (fun-p
6810 (push (nconc qname (list (js2-node-pos node)))
6811 js2-imenu-recorder)
6812 (js2-record-function-qname node qname))
6813 ;; foo.bar.baz = object-literal
6814 ;; look for nested functions: {a: {b: function() {...} }}
6815 ((js2-object-node-p node)
6816 ;; Node position here is still absolute, since the parser
6817 ;; passes the assignment target and value expressions
6818 ;; to us before they are added as children of the assignment node.
6819 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6820
6821 (defun js2-compute-nested-prop-get (node)
6822 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6823 component nodes as a list. Otherwise return nil. Element-gets are treated
6824 as property-gets if the index expression is a string, or a positive integer."
6825 (let (left right head)
6826 (cond
6827 ((or (js2-name-node-p node)
6828 (js2-this-node-p node))
6829 (list node))
6830 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6831 ((js2-prop-get-node-p node) ; foo.bar
6832 (setq left (js2-prop-get-node-left node)
6833 right (js2-prop-get-node-right node))
6834 (if (setq head (js2-compute-nested-prop-get left))
6835 (nconc head (list right))))
6836 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6837 (setq left (js2-elem-get-node-target node)
6838 right (js2-elem-get-node-element node))
6839 (if (or (js2-string-node-p right) ; ['bar']
6840 (and (js2-number-node-p right) ; [10]
6841 (string-match "^[0-9]+$"
6842 (js2-number-node-value right))))
6843 (if (setq head (js2-compute-nested-prop-get left))
6844 (nconc head (list right))))))))
6845
6846 (defun js2-record-object-literal (node qname pos)
6847 "Recursively process an object literal looking for functions.
6848 NODE is an object literal that is the right-hand child of an assignment
6849 expression. QNAME is a list of nodes representing the assignment target,
6850 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6851 POS is the absolute position of the node.
6852 We do a depth-first traversal of NODE. Any functions we find are prefixed
6853 with QNAME plus the property name of the function and appended to the
6854 variable `js2-imenu-recorder'."
6855 (let (left right)
6856 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6857 (let ((left (js2-infix-node-left e))
6858 ;; Element positions are relative to the parent position.
6859 (pos (+ pos (js2-node-pos e))))
6860 (cond
6861 ;; foo: function() {...}
6862 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6863 (when (js2-prop-node-name left)
6864 ;; As a policy decision, we record the position of the property,
6865 ;; not the position of the `function' keyword, since the property
6866 ;; is effectively the name of the function.
6867 (push (append qname (list left pos))
6868 js2-imenu-recorder)
6869 (js2-record-function-qname right qname)))
6870 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6871 ((js2-object-node-p right)
6872 (js2-record-object-literal right
6873 (append qname (list (js2-infix-node-left e)))
6874 (+ pos (js2-node-pos right)))))))))
6875
6876 (defsubst js2-node-top-level-decl-p (node)
6877 "Return t if NODE's name is defined in the top-level scope.
6878 Also returns t if NODE's name is not defined in any scope, since it implies
6879 that it's an external variable, which must also be in the top-level scope."
6880 (let* ((name (js2-prop-node-name node))
6881 (this-scope (js2-node-get-enclosing-scope node))
6882 defining-scope)
6883 (cond
6884 ((js2-this-node-p node)
6885 nil)
6886 ((null this-scope)
6887 t)
6888 ((setq defining-scope (js2-get-defining-scope this-scope name))
6889 (js2-ast-root-p defining-scope))
6890 (t t))))
6891
6892 (defun js2-browse-postprocess-chains (chains)
6893 "Modify function-declaration name chains after parsing finishes.
6894 Some of the information is only available after the parse tree is complete.
6895 For instance, following a 'this' reference requires a parent function node."
6896 (let (result head fn parent-chain p elem)
6897 (dolist (chain chains)
6898 ;; examine the head of each node to get its defining scope
6899 (setq head (car chain))
6900 ;; if top-level/external, keep as-is
6901 (if (js2-node-top-level-decl-p head)
6902 (push chain result)
6903 (cond
6904 ;; starts with this-reference
6905 ((js2-this-node-p head)
6906 (setq fn (js2-node-parent-script-or-fn head)
6907 chain (cdr chain))) ; discard this-node
6908 ;; nested named function
6909 ((js2-function-node-p (setq parent (js2-node-parent head)))
6910 (setq fn (js2-node-parent-script-or-fn parent)))
6911 ;; variable assigned a function expression
6912 (t (setq fn (js2-node-parent-script-or-fn head))))
6913 (unless (or (null fn) (js2-nested-function-p fn))
6914 ;; if the parent function is found, and it's not nested,
6915 ;; look it up in function-map.
6916 (if (setq parent-chain (and js2-imenu-function-map
6917 (gethash fn js2-imenu-function-map)))
6918 ;; prefix parent fn qname, which is the
6919 ;; parent-chain sans tail, to this chain.
6920 (push (append (butlast parent-chain) chain) result)
6921 ;; parent function is not nested, and not in function-map
6922 ;; => it's anonymous top-level wrapper, discard.
6923 (push chain result)))))
6924 ;; finally replace each node in each chain with its name.
6925 (dolist (chain result)
6926 (setq p chain)
6927 (while p
6928 (if (js2-node-p (setq elem (car p)))
6929 (setcar p (js2-node-qname-component elem)))
6930 (setq p (cdr p))))
6931 result))
6932
6933 ;; Merge name chains into a trie-like tree structure of nested lists.
6934 ;; To simplify construction of the trie, we first build it out using the rule
6935 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6936 ;; [key, num-or-list]. The second element can be a number; if so, this key
6937 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6938 ;; associated with the key at this level.) Otherwise the second element is
6939 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6940 ;; a simple recursive formulation.
6941 ;;
6942 ;; js2-mode is building the data structure for imenu. The imenu documentation
6943 ;; claims that it's the structure above, but in practice it wants the children
6944 ;; at the same list level as the key for that level, which is how I've drawn
6945 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6946 ;; list wrapper around the children at each level.
6947 ;;
6948 ;; A completed nested imenu-alist entry looks like this:
6949 ;; '(("foo"
6950 ;; ("<definition>" . 7)
6951 ;; ("bar"
6952 ;; ("a" . 40)
6953 ;; ("b" . 60))))
6954 ;;
6955 ;; In particular, the documentation for `imenu--index-alist' says that
6956 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6957 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6958
6959 (defsubst js2-treeify (lst)
6960 "Convert (a b c d) to (a ((b ((c d)))))"
6961 (if (null (cddr lst)) ; list length <= 2
6962 lst
6963 (list (car lst) (list (js2-treeify (cdr lst))))))
6964
6965 (defun js2-build-alist-trie (chains trie)
6966 "Merge declaration name chains into a trie-like alist structure for imenu.
6967 CHAINS is the qname chain list produced during parsing. TRIE is a
6968 list of elements built up so far."
6969 (let (head tail pos branch kids)
6970 (dolist (chain chains)
6971 (setq head (car chain)
6972 tail (cdr chain)
6973 pos (if (numberp (car tail)) (car tail))
6974 branch (js2-find-if (lambda (n)
6975 (string= (car n) head))
6976 trie)
6977 kids (second branch))
6978 (cond
6979 ;; case 1: this key isn't in the trie yet
6980 ((null branch)
6981 (if trie
6982 (setcdr (last trie) (list (js2-treeify chain)))
6983 (setq trie (list (js2-treeify chain)))))
6984 ;; case 2: key is present with a single number entry: replace w/ list
6985 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6986 ;; ("<definition>" 20)))
6987 ((numberp kids)
6988 (setcar (cdr branch)
6989 (list (list "<definition-1>" kids)
6990 (if pos
6991 (list "<definition-2>" pos)
6992 (js2-treeify tail)))))
6993 ;; case 3: key is there (with kids), and we're a number entry
6994 (pos
6995 (setcdr (last kids)
6996 (list
6997 (list (format "<definition-%d>"
6998 (1+ (loop for kid in kids
6999 count (eq ?< (aref (car kid) 0)))))
7000 pos))))
7001 ;; case 4: key is there with kids, need to merge in our chain
7002 (t
7003 (js2-build-alist-trie (list tail) kids))))
7004 trie))
7005
7006 (defun js2-flatten-trie (trie)
7007 "Convert TRIE to imenu-format.
7008 Recurses through nodes, and for each one whose second element is a list,
7009 appends the list's flattened elements to the current element. Also
7010 changes the tails into conses. For instance, this pre-flattened trie
7011
7012 '(a ((b 20)
7013 (c ((d 30)
7014 (e 40)))))
7015
7016 becomes
7017
7018 '(a (b . 20)
7019 (c (d . 30)
7020 (e . 40)))
7021
7022 Note that the root of the trie has no key, just a list of chains.
7023 This is also true for the value of any key with multiple children,
7024 e.g. key 'c' in the example above."
7025 (cond
7026 ((listp (car trie))
7027 (mapcar #'js2-flatten-trie trie))
7028 (t
7029 (if (numberp (second trie))
7030 (cons (car trie) (second trie))
7031 ;; else pop list and append its kids
7032 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7033
7034 (defun js2-build-imenu-index ()
7035 "Turn `js2-imenu-recorder' into an imenu data structure."
7036 (unless (eq js2-imenu-recorder 'empty)
7037 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7038 (result (js2-build-alist-trie chains nil)))
7039 (js2-flatten-trie result))))
7040
7041 (defun js2-test-print-chains (chains)
7042 "Print a list of qname chains.
7043 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7044 i.e. one or more nodes, and an integer position as the list tail."
7045 (mapconcat (lambda (chain)
7046 (concat "("
7047 (mapconcat (lambda (elem)
7048 (if (js2-node-p elem)
7049 (or (js2-node-qname-component elem)
7050 "nil")
7051 (number-to-string elem)))
7052 chain
7053 " ")
7054 ")"))
7055 chains
7056 "\n"))
7057
7058 ;;; Parser
7059
7060 (defconst js2-version "1.8.0"
7061 "Version of JavaScript supported, plus minor js2 version.")
7062
7063 (defmacro js2-record-face (face)
7064 "Record a style run of FACE for the current token."
7065 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7066
7067 (defsubst js2-node-end (n)
7068 "Computes the absolute end of node N.
7069 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7070 is only true until the node is added to its parent; i.e., while parsing."
7071 (+ (js2-node-pos n)
7072 (js2-node-len n)))
7073
7074 (defsubst js2-record-comment ()
7075 "Record a comment in `js2-scanned-comments'."
7076 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7077 :format js2-ts-comment-type)
7078 js2-scanned-comments)
7079 (when js2-parse-ide-mode
7080 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7081 'font-lock-doc-face
7082 'font-lock-comment-face))
7083 (when (memq js2-ts-comment-type '(html preprocessor))
7084 ;; Tell cc-engine the bounds of the comment.
7085 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7086
7087 ;; This function is called depressingly often, so it should be fast.
7088 ;; Most of the time it's looking at the same token it peeked before.
7089 (defsubst js2-peek-token ()
7090 "Returns the next token without consuming it.
7091 If previous token was consumed, calls scanner to get new token.
7092 If previous token was -not- consumed, returns it (idempotent).
7093
7094 This function will not return a newline (js2-EOL) - instead, it
7095 gobbles newlines until it finds a non-newline token, and flags
7096 that token as appearing just after a newline.
7097
7098 This function will also not return a js2-COMMENT. Instead, it
7099 records comments found in `js2-scanned-comments'. If the token
7100 returned by this function immediately follows a jsdoc comment,
7101 the token is flagged as such.
7102
7103 Note that this function always returned the un-flagged token!
7104 The flags, if any, are saved in `js2-current-flagged-token'."
7105 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7106 js2-current-token ; most common case - return already-peeked token
7107 (let ((tt (js2-get-token)) ; call scanner
7108 saw-eol
7109 face)
7110 ;; process comments and whitespace
7111 (while (or (= tt js2-EOL)
7112 (= tt js2-COMMENT))
7113 (if (= tt js2-EOL)
7114 (setq saw-eol t)
7115 (setq saw-eol nil)
7116 (if js2-record-comments
7117 (js2-record-comment)))
7118 (setq tt (js2-get-token))) ; call scanner
7119 (setq js2-current-token tt
7120 js2-current-flagged-token (if saw-eol
7121 (logior tt js2-ti-after-eol)
7122 tt))
7123 ;; perform lexical fontification as soon as token is scanned
7124 (when js2-parse-ide-mode
7125 (cond
7126 ((minusp tt)
7127 (js2-record-face 'js2-error-face))
7128 ((setq face (aref js2-kwd-tokens tt))
7129 (js2-record-face face))
7130 ((and (= tt js2-NAME)
7131 (equal js2-ts-string "undefined"))
7132 (js2-record-face 'font-lock-constant-face))))
7133 tt))) ; return unflagged token
7134
7135 (defsubst js2-peek-flagged-token ()
7136 "Returns the current token along with any flags set for it."
7137 (js2-peek-token)
7138 js2-current-flagged-token)
7139
7140 (defsubst js2-consume-token ()
7141 (setq js2-current-flagged-token js2-EOF))
7142
7143 (defsubst js2-next-token ()
7144 (prog1
7145 (js2-peek-token)
7146 (js2-consume-token)))
7147
7148 (defsubst js2-next-flagged-token ()
7149 (js2-peek-token)
7150 (prog1 js2-current-flagged-token
7151 (js2-consume-token)))
7152
7153 (defsubst js2-match-token (match)
7154 "Consume and return t if next token matches MATCH, a bytecode.
7155 Returns nil and consumes nothing if MATCH is not the next token."
7156 (if (/= (js2-peek-token) match)
7157 nil
7158 (js2-consume-token)
7159 t))
7160
7161 (defsubst js2-valid-prop-name-token (tt)
7162 (or (= tt js2-NAME)
7163 (and js2-allow-keywords-as-property-names
7164 (plusp tt)
7165 (aref js2-kwd-tokens tt))))
7166
7167 (defsubst js2-match-prop-name ()
7168 "Consume token and return t if next token is a valid property name.
7169 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7170 is non-nil and it's a keyword token."
7171 (if (js2-valid-prop-name-token (js2-peek-token))
7172 (progn
7173 (js2-consume-token)
7174 t)
7175 nil))
7176
7177 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7178 (if (js2-match-prop-name)
7179 t
7180 (js2-report-error msg-id nil pos len)
7181 nil))
7182
7183 (defsubst js2-peek-token-or-eol ()
7184 "Return js2-EOL if the current token immediately follows a newline.
7185 Else returns the current token. Used in situations where we don't
7186 consider certain token types valid if they are preceded by a newline.
7187 One example is the postfix ++ or -- operator, which has to be on the
7188 same line as its operand."
7189 (let ((tt (js2-peek-token)))
7190 ;; Check for last peeked token flags
7191 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7192 js2-EOL
7193 tt)))
7194
7195 (defsubst js2-set-check-for-label ()
7196 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7197 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7198
7199 (defsubst js2-must-match (token msg-id &optional pos len)
7200 "Match next token to token code TOKEN, or record a syntax error.
7201 MSG-ID is the error message to report if the match fails.
7202 Returns t on match, nil if no match."
7203 (if (js2-match-token token)
7204 t
7205 (js2-report-error msg-id nil pos len)
7206 nil))
7207
7208 (defsubst js2-inside-function ()
7209 (plusp js2-nesting-of-function))
7210
7211 (defsubst js2-set-requires-activation ()
7212 (if (js2-function-node-p js2-current-script-or-fn)
7213 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7214
7215 (defsubst js2-check-activation-name (name token)
7216 (when (js2-inside-function)
7217 ;; skip language-version 1.2 check from Rhino
7218 (if (or (string= "arguments" name)
7219 (and js2-compiler-activation-names ; only used in codegen
7220 (gethash name js2-compiler-activation-names)))
7221 (js2-set-requires-activation))))
7222
7223 (defsubst js2-set-is-generator ()
7224 (if (js2-function-node-p js2-current-script-or-fn)
7225 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7226
7227 (defsubst js2-must-have-xml ()
7228 (unless js2-compiler-xml-available
7229 (js2-report-error "msg.XML.not.available")))
7230
7231 (defsubst js2-push-scope (scope)
7232 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7233 (assert (js2-scope-p scope))
7234 (assert (null (js2-scope-parent-scope scope)))
7235 (assert (not (eq js2-current-scope scope)))
7236 (setf (js2-scope-parent-scope scope) js2-current-scope
7237 js2-current-scope scope))
7238
7239 (defsubst js2-pop-scope ()
7240 (setq js2-current-scope
7241 (js2-scope-parent-scope js2-current-scope)))
7242
7243 (defsubst js2-enter-loop (loop-node)
7244 (push loop-node js2-loop-set)
7245 (push loop-node js2-loop-and-switch-set)
7246 (js2-push-scope loop-node)
7247 ;; Tell the current labeled statement (if any) its statement,
7248 ;; and set the jump target of the first label to the loop.
7249 ;; These are used in `js2-parse-continue' to verify that the
7250 ;; continue target is an actual labeled loop. (And for codegen.)
7251 (when js2-labeled-stmt
7252 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7253 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7254 js2-labeled-stmt))) loop-node)))
7255
7256 (defsubst js2-exit-loop ()
7257 (pop js2-loop-set)
7258 (pop js2-loop-and-switch-set)
7259 (js2-pop-scope))
7260
7261 (defsubst js2-enter-switch (switch-node)
7262 (push switch-node js2-loop-and-switch-set))
7263
7264 (defsubst js2-exit-switch ()
7265 (pop js2-loop-and-switch-set))
7266
7267 (defun js2-parse (&optional buf cb)
7268 "Tells the js2 parser to parse a region of JavaScript.
7269
7270 BUF is a buffer or buffer name containing the code to parse.
7271 Call `narrow-to-region' first to parse only part of the buffer.
7272
7273 The returned AST root node is given some additional properties:
7274 `node-count' - total number of nodes in the AST
7275 `buffer' - BUF. The buffer it refers to may change or be killed,
7276 so the value is not necessarily reliable.
7277
7278 An optional callback CB can be specified to report parsing
7279 progress. If `(functionp CB)' returns t, it will be called with
7280 the current line number once before parsing begins, then again
7281 each time the lexer reaches a new line number.
7282
7283 CB can also be a list of the form `(symbol cb ...)' to specify
7284 multiple callbacks with different criteria. Each symbol is a
7285 criterion keyword, and the following element is the callback to
7286 call
7287
7288 :line - called whenever the line number changes
7289 :token - called for each new token consumed
7290
7291 The list of criteria could be extended to include entering or
7292 leaving a statement, an expression, or a function definition."
7293 (if (and cb (not (functionp cb)))
7294 (error "criteria callbacks not yet implemented"))
7295 (let ((inhibit-point-motion-hooks t)
7296 (js2-compiler-xml-available (>= js2-language-version 160))
7297 ;; This is a recursive-descent parser, so give it a big stack.
7298 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7299 (max-specpdl-size (max max-specpdl-size 3000))
7300 (case-fold-search nil)
7301 ast)
7302 (or buf (setq buf (current-buffer)))
7303 (message nil) ; clear any error message from previous parse
7304 (save-excursion
7305 (set-buffer buf)
7306 (setq js2-scanned-comments nil
7307 js2-parsed-errors nil
7308 js2-parsed-warnings nil
7309 js2-imenu-recorder nil
7310 js2-imenu-function-map nil
7311 js2-label-set nil)
7312 (js2-init-scanner)
7313 (setq ast (js2-with-unmodifying-text-property-changes
7314 (js2-do-parse)))
7315 (unless js2-ts-hit-eof
7316 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7317 (setf (js2-ast-root-errors ast) js2-parsed-errors
7318 (js2-ast-root-warnings ast) js2-parsed-warnings)
7319 ;; if we didn't find any declarations, put a dummy in this list so we
7320 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7321 (unless js2-imenu-recorder
7322 (setq js2-imenu-recorder 'empty))
7323 (run-hooks 'js2-parse-finished-hook)
7324 ast)))
7325
7326 ;; Corresponds to Rhino's Parser.parse() method.
7327 (defun js2-do-parse ()
7328 "Parse current buffer starting from current point.
7329 Scanner should be initialized."
7330 (let ((pos js2-ts-cursor)
7331 (end js2-ts-cursor) ; in case file is empty
7332 root n tt)
7333 ;; initialize buffer-local parsing vars
7334 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7335 js2-current-script-or-fn root
7336 js2-current-scope root
7337 js2-current-flagged-token js2-EOF
7338 js2-nesting-of-function 0
7339 js2-labeled-stmt nil
7340 js2-recorded-identifiers nil) ; for js2-highlight
7341 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7342 (if (= tt js2-FUNCTION)
7343 (progn
7344 (js2-consume-token)
7345 (setq n (js2-parse-function (if js2-called-by-compile-function
7346 'FUNCTION_EXPRESSION
7347 'FUNCTION_STATEMENT))))
7348 ;; not a function - parse a statement
7349 (setq n (js2-parse-statement)))
7350 ;; add function or statement to script
7351 (setq end (js2-node-end n))
7352 (js2-block-node-push root n))
7353 ;; add comments to root in lexical order
7354 (when js2-scanned-comments
7355 ;; if we find a comment beyond end of normal kids, use its end
7356 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7357 (dolist (comment js2-scanned-comments)
7358 (push comment (js2-ast-root-comments root))
7359 (js2-node-add-children root comment)))
7360 (setf (js2-node-len root) (- end pos))
7361 ;; Give extensions a chance to muck with things before highlighting starts.
7362 (dolist (callback js2-post-parse-callbacks)
7363 (funcall callback))
7364 (js2-highlight-undeclared-vars)
7365 root))
7366
7367 (defun js2-function-parser ()
7368 (js2-consume-token)
7369 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7370
7371 (defun js2-parse-function-closure-body (fn-node)
7372 "Parse a JavaScript 1.8 function closure body."
7373 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7374 (if js2-ts-hit-eof
7375 (js2-report-error "msg.no.brace.body" nil
7376 (js2-node-pos fn-node)
7377 (- js2-ts-cursor (js2-node-pos fn-node)))
7378 (js2-node-add-children fn-node
7379 (setf (js2-function-node-body fn-node)
7380 (js2-parse-expr t))))))
7381
7382 (defun js2-parse-function-body (fn-node)
7383 (js2-must-match js2-LC "msg.no.brace.body"
7384 (js2-node-pos fn-node)
7385 (- js2-ts-cursor (js2-node-pos fn-node)))
7386 (let ((pos js2-token-beg) ; LC position
7387 (pn (make-js2-block-node)) ; starts at LC position
7388 tt
7389 end)
7390 (incf js2-nesting-of-function)
7391 (unwind-protect
7392 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7393 (= tt js2-EOF)
7394 (= tt js2-RC)))
7395 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7396 (js2-parse-statement)
7397 (js2-consume-token)
7398 (js2-parse-function 'FUNCTION_STATEMENT))))
7399 (decf js2-nesting-of-function))
7400 (setq end js2-token-end) ; assume no curly and leave at current token
7401 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7402 (setq end js2-token-end))
7403 (setf (js2-node-pos pn) pos
7404 (js2-node-len pn) (- end pos))
7405 (setf (js2-function-node-body fn-node) pn)
7406 (js2-node-add-children fn-node pn)
7407 pn))
7408
7409 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7410 "Declare and fontify destructuring parameters inside NODE.
7411 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7412 (cond
7413 ((js2-name-node-p node)
7414 (let (leftpos)
7415 (js2-define-symbol decl-type (js2-name-node-name node)
7416 node ignore-not-in-block)
7417 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7418 (+ leftpos (js2-node-len node))
7419 face 'record)))
7420 ((js2-object-node-p node)
7421 (dolist (elem (js2-object-node-elems node))
7422 (js2-define-destruct-symbols
7423 (if (js2-object-prop-node-p elem)
7424 (js2-object-prop-node-right elem)
7425 ;; abbreviated destructuring {a, b}
7426 elem)
7427 decl-type face ignore-not-in-block)))
7428 ((js2-array-node-p node)
7429 (dolist (elem (js2-array-node-elems node))
7430 (when elem
7431 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7432 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7433 (js2-node-len node)))))
7434
7435 (defun js2-parse-function-params (fn-node pos)
7436 (if (js2-match-token js2-RP)
7437 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7438 (let (params len param)
7439 (loop for tt = (js2-peek-token)
7440 do
7441 (cond
7442 ;; destructuring param
7443 ((or (= tt js2-LB) (= tt js2-LC))
7444 (setq param (js2-parse-primary-expr-lhs))
7445 (js2-define-destruct-symbols param
7446 js2-LP
7447 'js2-function-param-face)
7448 (push param params))
7449 ;; simple name
7450 (t
7451 (js2-must-match js2-NAME "msg.no.parm")
7452 (js2-record-face 'js2-function-param-face)
7453 (setq param (js2-create-name-node))
7454 (js2-define-symbol js2-LP js2-ts-string param)
7455 (push param params)))
7456 while
7457 (js2-match-token js2-COMMA))
7458 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7459 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7460 (dolist (p params)
7461 (js2-node-add-children fn-node p)
7462 (push p (js2-function-node-params fn-node))))))
7463
7464 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7465 "Possibly show inconsistent-return warning.
7466 Last token scanned is the close-curly for the function body."
7467 (when (and js2-mode-show-strict-warnings
7468 js2-strict-inconsistent-return-warning
7469 (not (js2-has-consistent-return-usage
7470 (js2-function-node-body fn-node))))
7471 ;; Have it extend from close-curly to bol or beginning of block.
7472 (let ((pos (save-excursion
7473 (goto-char js2-token-end)
7474 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7475 (point-at-bol))))
7476 (end js2-token-end))
7477 (if (plusp (js2-name-node-length name))
7478 (js2-add-strict-warning "msg.no.return.value"
7479 (js2-name-node-name name) pos end)
7480 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7481
7482 (defun js2-parse-function (function-type)
7483 "Function parser. FUNCTION-TYPE is a symbol."
7484 (let ((pos js2-token-beg) ; start of 'function' keyword
7485 name
7486 name-beg
7487 name-end
7488 fn-node
7489 lp
7490 (synthetic-type function-type)
7491 member-expr-node)
7492 ;; parse function name, expression, or non-name (anonymous)
7493 (cond
7494 ;; function foo(...)
7495 ((js2-match-token js2-NAME)
7496 (setq name (js2-create-name-node t)
7497 name-beg js2-token-beg
7498 name-end js2-token-end)
7499 (unless (js2-match-token js2-LP)
7500 (when js2-allow-member-expr-as-function-name
7501 ;; function foo.bar(...)
7502 (setq member-expr-node name
7503 name nil
7504 member-expr-node (js2-parse-member-expr-tail
7505 nil member-expr-node)))
7506 (js2-must-match js2-LP "msg.no.paren.parms")))
7507 ((js2-match-token js2-LP)
7508 nil) ; anonymous function: leave name as null
7509 (t
7510 ;; function random-member-expr(...)
7511 (when js2-allow-member-expr-as-function-name
7512 ;; Note that memberExpr can not start with '(' like
7513 ;; in function (1+2).toString(), because 'function (' already
7514 ;; processed as anonymous function
7515 (setq member-expr-node (js2-parse-member-expr)))
7516 (js2-must-match js2-LP "msg.no.paren.parms")))
7517 (if (= js2-current-token js2-LP) ; eventually matched LP?
7518 (setq lp js2-token-beg))
7519 (if member-expr-node
7520 (progn
7521 (setq synthetic-type 'FUNCTION_EXPRESSION)
7522 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7523 (if name
7524 (js2-set-face name-beg name-end
7525 'font-lock-function-name-face 'record)))
7526 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7527 (plusp (js2-name-node-length name)))
7528 ;; Function statements define a symbol in the enclosing scope
7529 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7530 (setf fn-node (make-js2-function-node :pos pos
7531 :name name
7532 :form function-type
7533 :lp (if lp (- lp pos))))
7534 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7535 ;; 1. Nested functions are not affected by the dynamic scope flag
7536 ;; as dynamic scope is already a parent of their scope.
7537 ;; 2. Functions defined under the with statement also immune to
7538 ;; this setup, in which case dynamic scope is ignored in favor
7539 ;; of the with object.
7540 (setf (js2-function-node-ignore-dynamic fn-node) t))
7541 ;; dynamically bind all the per-function variables
7542 (let ((js2-current-script-or-fn fn-node)
7543 (js2-current-scope fn-node)
7544 (js2-nesting-of-with 0)
7545 (js2-end-flags 0)
7546 js2-label-set
7547 js2-loop-set
7548 js2-loop-and-switch-set)
7549 (js2-parse-function-params fn-node pos)
7550 (if (and (>= js2-language-version 180)
7551 (/= (js2-peek-token) js2-LC))
7552 (js2-parse-function-closure-body fn-node)
7553 (js2-parse-function-body fn-node))
7554 (if name
7555 (js2-node-add-children fn-node name))
7556 (js2-check-inconsistent-return-warning fn-node name)
7557 ;; Function expressions define a name only in the body of the
7558 ;; function, and only if not hidden by a parameter name
7559 (if (and name
7560 (eq synthetic-type 'FUNCTION_EXPRESSION)
7561 (null (js2-scope-get-symbol js2-current-scope
7562 (js2-name-node-name name))))
7563 (js2-define-symbol js2-FUNCTION
7564 (js2-name-node-name name)
7565 fn-node))
7566 (if (and name
7567 (not (eq function-type 'FUNCTION_EXPRESSION)))
7568 (js2-record-imenu-functions fn-node)))
7569 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7570 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7571 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7572 ;; We wait until after parsing the function to set its parent scope,
7573 ;; since `js2-define-symbol' needs the defining-scope check to stop
7574 ;; at the function boundary when checking for redeclarations.
7575 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7576 fn-node))
7577
7578 (defun js2-parse-statements (&optional parent)
7579 "Parse a statement list. Last token consumed must be js2-LC.
7580
7581 PARENT can be a `js2-block-node', in which case the statements are
7582 appended to PARENT. Otherwise a new `js2-block-node' is created
7583 and returned.
7584
7585 This function does not match the closing js2-RC: the caller
7586 matches the RC so it can provide a suitable error message if not
7587 matched. This means it's up to the caller to set the length of
7588 the node to include the closing RC. The node start pos is set to
7589 the absolute buffer start position, and the caller should fix it
7590 up to be relative to the parent node. All children of this block
7591 node are given relative start positions and correct lengths."
7592 (let ((pn (or parent (make-js2-block-node)))
7593 tt)
7594 (setf (js2-node-pos pn) js2-token-beg)
7595 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7596 (/= tt js2-RC))
7597 (js2-block-node-push pn (js2-parse-statement)))
7598 pn))
7599
7600 (defun js2-parse-statement ()
7601 (let (tt pn beg end)
7602 ;; coarse-grained user-interrupt check - needs work
7603 (and js2-parse-interruptable-p
7604 (zerop (% (incf js2-parse-stmt-count)
7605 js2-statements-per-pause))
7606 (input-pending-p)
7607 (throw 'interrupted t))
7608 (setq pn (js2-statement-helper))
7609 ;; no-side-effects warning check
7610 (unless (js2-node-has-side-effects pn)
7611 (setq end (js2-node-end pn))
7612 (save-excursion
7613 (goto-char end)
7614 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7615 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7616 pn))
7617
7618 ;; These correspond to the switch cases in Parser.statementHelper
7619 (defconst js2-parsers
7620 (let ((parsers (make-vector js2-num-tokens
7621 #'js2-parse-expr-stmt)))
7622 (aset parsers js2-BREAK #'js2-parse-break)
7623 (aset parsers js2-CONST #'js2-parse-const-var)
7624 (aset parsers js2-CONTINUE #'js2-parse-continue)
7625 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7626 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7627 (aset parsers js2-DO #'js2-parse-do)
7628 (aset parsers js2-FOR #'js2-parse-for)
7629 (aset parsers js2-FUNCTION #'js2-function-parser)
7630 (aset parsers js2-IF #'js2-parse-if)
7631 (aset parsers js2-LC #'js2-parse-block)
7632 (aset parsers js2-LET #'js2-parse-let-stmt)
7633 (aset parsers js2-NAME #'js2-parse-name-or-label)
7634 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7635 (aset parsers js2-SEMI #'js2-parse-semi)
7636 (aset parsers js2-SWITCH #'js2-parse-switch)
7637 (aset parsers js2-THROW #'js2-parse-throw)
7638 (aset parsers js2-TRY #'js2-parse-try)
7639 (aset parsers js2-VAR #'js2-parse-const-var)
7640 (aset parsers js2-WHILE #'js2-parse-while)
7641 (aset parsers js2-WITH #'js2-parse-with)
7642 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7643 parsers)
7644 "A vector mapping token types to parser functions.")
7645
7646 (defsubst js2-parse-warn-missing-semi (beg end)
7647 (and js2-mode-show-strict-warnings
7648 js2-strict-missing-semi-warning
7649 (js2-add-strict-warning
7650 "msg.missing.semi" nil
7651 ;; back up to beginning of statement or line
7652 (max beg (save-excursion
7653 (goto-char end)
7654 (point-at-bol)))
7655 end)))
7656
7657 (defconst js2-no-semi-insertion
7658 (list js2-IF
7659 js2-SWITCH
7660 js2-WHILE
7661 js2-DO
7662 js2-FOR
7663 js2-TRY
7664 js2-WITH
7665 js2-LC
7666 js2-ERROR
7667 js2-SEMI
7668 js2-FUNCTION)
7669 "List of tokens that don't do automatic semicolon insertion.")
7670
7671 (defconst js2-autoinsert-semi-and-warn
7672 (list js2-ERROR js2-EOF js2-RC))
7673
7674 (defun js2-statement-helper ()
7675 (let* ((tt (js2-peek-token))
7676 (first-tt tt)
7677 (beg js2-token-beg)
7678 (parser (if (= tt js2-ERROR)
7679 #'js2-parse-semi
7680 (aref js2-parsers tt)))
7681 pn
7682 tt-flagged)
7683 ;; If the statement is set, then it's been told its label by now.
7684 (and js2-labeled-stmt
7685 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7686 (setq js2-labeled-stmt nil))
7687 (setq pn (funcall parser))
7688 ;; Don't do auto semi insertion for certain statement types.
7689 (unless (or (memq first-tt js2-no-semi-insertion)
7690 (js2-labeled-stmt-node-p pn))
7691 (js2-auto-insert-semicolon pn))
7692 pn))
7693
7694 (defun js2-auto-insert-semicolon (pn)
7695 (let* ((tt-flagged (js2-peek-flagged-token))
7696 (tt (logand tt-flagged js2-clear-ti-mask))
7697 (pos (js2-node-pos pn)))
7698 (cond
7699 ((= tt js2-SEMI)
7700 ;; Consume ';' as a part of expression
7701 (js2-consume-token)
7702 ;; extend the node bounds to include the semicolon.
7703 (setf (js2-node-len pn) (- js2-token-end pos)))
7704 ((memq tt js2-autoinsert-semi-and-warn)
7705 ;; Autoinsert ;
7706 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7707 (t
7708 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7709 ;; Report error if no EOL or autoinsert ';' otherwise
7710 (js2-report-error "msg.no.semi.stmt")
7711 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7712
7713 (defun js2-parse-condition ()
7714 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7715 The parens are discarded and the expression node is returned.
7716 The `pos' field of the return value is set to an absolute position
7717 that must be fixed up by the caller.
7718 Return value is a list (EXPR LP RP), with absolute paren positions."
7719 (let (pn lp rp)
7720 (if (js2-must-match js2-LP "msg.no.paren.cond")
7721 (setq lp js2-token-beg))
7722 (setq pn (js2-parse-expr))
7723 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7724 (setq rp js2-token-beg))
7725 ;; Report strict warning on code like "if (a = 7) ..."
7726 (if (and js2-strict-cond-assign-warning
7727 (js2-assign-node-p pn))
7728 (js2-add-strict-warning "msg.equal.as.assign" nil
7729 (js2-node-pos pn)
7730 (+ (js2-node-pos pn)
7731 (js2-node-len pn))))
7732 (list pn lp rp)))
7733
7734 (defun js2-parse-if ()
7735 "Parser for if-statement. Last matched token must be js2-IF."
7736 (let ((pos js2-token-beg)
7737 cond
7738 if-true
7739 if-false
7740 else-pos
7741 end
7742 pn)
7743 (js2-consume-token)
7744 (setq cond (js2-parse-condition)
7745 if-true (js2-parse-statement)
7746 if-false (if (js2-match-token js2-ELSE)
7747 (progn
7748 (setq else-pos (- js2-token-beg pos))
7749 (js2-parse-statement)))
7750 end (js2-node-end (or if-false if-true))
7751 pn (make-js2-if-node :pos pos
7752 :len (- end pos)
7753 :condition (car cond)
7754 :then-part if-true
7755 :else-part if-false
7756 :else-pos else-pos
7757 :lp (js2-relpos (second cond) pos)
7758 :rp (js2-relpos (third cond) pos)))
7759 (js2-node-add-children pn (car cond) if-true if-false)
7760 pn))
7761
7762 (defun js2-parse-switch ()
7763 "Parser for if-statement. Last matched token must be js2-SWITCH."
7764 (let ((pos js2-token-beg)
7765 tt
7766 pn
7767 discriminant
7768 has-default
7769 case-expr
7770 case-node
7771 case-pos
7772 cases
7773 stmt
7774 lp
7775 rp)
7776 (js2-consume-token)
7777 (if (js2-must-match js2-LP "msg.no.paren.switch")
7778 (setq lp js2-token-beg))
7779 (setq discriminant (js2-parse-expr)
7780 pn (make-js2-switch-node :discriminant discriminant
7781 :pos pos
7782 :lp (js2-relpos lp pos)))
7783 (js2-node-add-children pn discriminant)
7784 (js2-enter-switch pn)
7785 (unwind-protect
7786 (progn
7787 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7788 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7789 (js2-must-match js2-LC "msg.no.brace.switch")
7790 (catch 'break
7791 (while t
7792 (setq tt (js2-next-token)
7793 case-pos js2-token-beg)
7794 (cond
7795 ((= tt js2-RC)
7796 (setf (js2-node-len pn) (- js2-token-end pos))
7797 (throw 'break nil)) ; done
7798 ((= tt js2-CASE)
7799 (setq case-expr (js2-parse-expr))
7800 (js2-must-match js2-COLON "msg.no.colon.case"))
7801 ((= tt js2-DEFAULT)
7802 (if has-default
7803 (js2-report-error "msg.double.switch.default"))
7804 (setq has-default t
7805 case-expr nil)
7806 (js2-must-match js2-COLON "msg.no.colon.case"))
7807 (t
7808 (js2-report-error "msg.bad.switch")
7809 (throw 'break nil)))
7810 (setq case-node (make-js2-case-node :pos case-pos
7811 :len (- js2-token-end case-pos)
7812 :expr case-expr))
7813 (js2-node-add-children case-node case-expr)
7814 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7815 (/= tt js2-CASE)
7816 (/= tt js2-DEFAULT)
7817 (/= tt js2-EOF))
7818 (setf stmt (js2-parse-statement)
7819 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7820 (js2-block-node-push case-node stmt))
7821 (push case-node cases)))
7822 ;; add cases last, as pushing reverses the order to be correct
7823 (dolist (kid cases)
7824 (js2-node-add-children pn kid)
7825 (push kid (js2-switch-node-cases pn)))
7826 pn) ; return value
7827 (js2-exit-switch))))
7828
7829 (defun js2-parse-while ()
7830 "Parser for while-statement. Last matched token must be js2-WHILE."
7831 (let ((pos js2-token-beg)
7832 (pn (make-js2-while-node))
7833 cond
7834 body)
7835 (js2-consume-token)
7836 (js2-enter-loop pn)
7837 (unwind-protect
7838 (progn
7839 (setf cond (js2-parse-condition)
7840 (js2-while-node-condition pn) (car cond)
7841 body (js2-parse-statement)
7842 (js2-while-node-body pn) body
7843 (js2-node-len pn) (- (js2-node-end body) pos)
7844 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7845 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7846 (js2-node-add-children pn body (car cond)))
7847 (js2-exit-loop))
7848 pn))
7849
7850 (defun js2-parse-do ()
7851 "Parser for do-statement. Last matched token must be js2-DO."
7852 (let ((pos js2-token-beg)
7853 (pn (make-js2-do-node))
7854 cond
7855 body
7856 end)
7857 (js2-consume-token)
7858 (js2-enter-loop pn)
7859 (unwind-protect
7860 (progn
7861 (setq body (js2-parse-statement))
7862 (js2-must-match js2-WHILE "msg.no.while.do")
7863 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7864 cond (js2-parse-condition)
7865 (js2-do-node-condition pn) (car cond)
7866 (js2-do-node-body pn) body
7867 end js2-ts-cursor
7868 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7869 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7870 (js2-node-add-children pn (car cond) body))
7871 (js2-exit-loop))
7872 ;; Always auto-insert semicolon to follow SpiderMonkey:
7873 ;; It is required by ECMAScript but is ignored by the rest of
7874 ;; world; see bug 238945
7875 (if (js2-match-token js2-SEMI)
7876 (setq end js2-ts-cursor))
7877 (setf (js2-node-len pn) (- end pos))
7878 pn))
7879
7880 (defun js2-parse-for ()
7881 "Parser for for-statement. Last matched token must be js2-FOR.
7882 Parses for, for-in, and for each-in statements."
7883 (let ((for-pos js2-token-beg)
7884 pn
7885 is-for-each
7886 is-for-in
7887 in-pos
7888 each-pos
7889 tmp-pos
7890 init ; Node init is also foo in 'foo in object'
7891 cond ; Node cond is also object in 'foo in object'
7892 incr ; 3rd section of for-loop initializer
7893 body
7894 tt
7895 lp
7896 rp)
7897 (js2-consume-token)
7898 ;; See if this is a for each () instead of just a for ()
7899 (when (js2-match-token js2-NAME)
7900 (if (string= "each" js2-ts-string)
7901 (progn
7902 (setq is-for-each t
7903 each-pos (- js2-token-beg for-pos)) ; relative
7904 (js2-record-face 'font-lock-keyword-face))
7905 (js2-report-error "msg.no.paren.for")))
7906 (if (js2-must-match js2-LP "msg.no.paren.for")
7907 (setq lp (- js2-token-beg for-pos)))
7908 (setq tt (js2-peek-token))
7909 ;; parse init clause
7910 (let ((js2-in-for-init t)) ; set as dynamic variable
7911 (cond
7912 ((= tt js2-SEMI)
7913 (setq init (make-js2-empty-expr-node)))
7914 ((or (= tt js2-VAR) (= tt js2-LET))
7915 (js2-consume-token)
7916 (setq init (js2-parse-variables tt js2-token-beg)))
7917 (t
7918 (setq init (js2-parse-expr)))))
7919 (if (js2-match-token js2-IN)
7920 (setq is-for-in t
7921 in-pos (- js2-token-beg for-pos)
7922 cond (js2-parse-expr)) ; object over which we're iterating
7923 ;; else ordinary for loop - parse cond and incr
7924 (js2-must-match js2-SEMI "msg.no.semi.for")
7925 (setq cond (if (= (js2-peek-token) js2-SEMI)
7926 (make-js2-empty-expr-node) ; no loop condition
7927 (js2-parse-expr)))
7928 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7929 (setq tmp-pos js2-token-end
7930 incr (if (= (js2-peek-token) js2-RP)
7931 (make-js2-empty-expr-node :pos tmp-pos)
7932 (js2-parse-expr))))
7933 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7934 (setq rp (- js2-token-beg for-pos)))
7935 (if (not is-for-in)
7936 (setq pn (make-js2-for-node :init init
7937 :condition cond
7938 :update incr
7939 :lp lp
7940 :rp rp))
7941 ;; cond could be null if 'in obj' got eaten by the init node.
7942 (if (js2-infix-node-p init)
7943 ;; it was (foo in bar) instead of (var foo in bar)
7944 (setq cond (js2-infix-node-right init)
7945 init (js2-infix-node-left init))
7946 (if (and (js2-var-decl-node-p init)
7947 (> (length (js2-var-decl-node-kids init)) 1))
7948 (js2-report-error "msg.mult.index")))
7949 (setq pn (make-js2-for-in-node :iterator init
7950 :object cond
7951 :in-pos in-pos
7952 :foreach-p is-for-each
7953 :each-pos each-pos
7954 :lp lp
7955 :rp rp)))
7956 (unwind-protect
7957 (progn
7958 (js2-enter-loop pn)
7959 ;; We have to parse the body -after- creating the loop node,
7960 ;; so that the loop node appears in the js2-loop-set, allowing
7961 ;; break/continue statements to find the enclosing loop.
7962 (setf body (js2-parse-statement)
7963 (js2-loop-node-body pn) body
7964 (js2-node-pos pn) for-pos
7965 (js2-node-len pn) (- (js2-node-end body) for-pos))
7966 (js2-node-add-children pn init cond incr body))
7967 ;; finally
7968 (js2-exit-loop))
7969 pn))
7970
7971 (defun js2-parse-try ()
7972 "Parser for try-statement. Last matched token must be js2-TRY."
7973 (let ((try-pos js2-token-beg)
7974 try-end
7975 try-block
7976 catch-blocks
7977 finally-block
7978 saw-default-catch
7979 peek
7980 var-name
7981 catch-cond
7982 catch-node
7983 guard-kwd
7984 catch-pos
7985 finally-pos
7986 pn
7987 block
7988 lp
7989 rp)
7990 (js2-consume-token)
7991 (if (/= (js2-peek-token) js2-LC)
7992 (js2-report-error "msg.no.brace.try"))
7993 (setq try-block (js2-parse-statement)
7994 try-end (js2-node-end try-block)
7995 peek (js2-peek-token))
7996 (cond
7997 ((= peek js2-CATCH)
7998 (while (js2-match-token js2-CATCH)
7999 (setq catch-pos js2-token-beg
8000 guard-kwd nil
8001 catch-cond nil
8002 lp nil
8003 rp nil)
8004 (if saw-default-catch
8005 (js2-report-error "msg.catch.unreachable"))
8006 (if (js2-must-match js2-LP "msg.no.paren.catch")
8007 (setq lp (- js2-token-beg catch-pos)))
8008 (js2-must-match js2-NAME "msg.bad.catchcond")
8009 (setq var-name (js2-create-name-node))
8010 (if (js2-match-token js2-IF)
8011 (setq guard-kwd (- js2-token-beg catch-pos)
8012 catch-cond (js2-parse-expr))
8013 (setq saw-default-catch t))
8014 (if (js2-must-match js2-RP "msg.bad.catchcond")
8015 (setq rp (- js2-token-beg catch-pos)))
8016 (js2-must-match js2-LC "msg.no.brace.catchblock")
8017 (setq block (js2-parse-statements)
8018 try-end (js2-node-end block)
8019 catch-node (make-js2-catch-node :pos catch-pos
8020 :var-name var-name
8021 :guard-expr catch-cond
8022 :guard-kwd guard-kwd
8023 :block block
8024 :lp lp
8025 :rp rp))
8026 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8027 (setq try-end js2-token-beg))
8028 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8029 (js2-node-len catch-node) (- try-end catch-pos))
8030 (js2-node-add-children catch-node var-name catch-cond block)
8031 (push catch-node catch-blocks)))
8032 ((/= peek js2-FINALLY)
8033 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8034 (js2-node-pos try-block)
8035 (- (setq try-end (js2-node-end try-block))
8036 (js2-node-pos try-block)))))
8037 (when (js2-match-token js2-FINALLY)
8038 (setq finally-pos js2-token-beg
8039 block (js2-parse-statement)
8040 try-end (js2-node-end block)
8041 finally-block (make-js2-finally-node :pos finally-pos
8042 :len (- try-end finally-pos)
8043 :body block))
8044 (js2-node-add-children finally-block block))
8045 (setq pn (make-js2-try-node :pos try-pos
8046 :len (- try-end try-pos)
8047 :try-block try-block
8048 :finally-block finally-block))
8049 (js2-node-add-children pn try-block finally-block)
8050 ;; push them onto the try-node, which reverses and corrects their order
8051 (dolist (cb catch-blocks)
8052 (js2-node-add-children pn cb)
8053 (push cb (js2-try-node-catch-clauses pn)))
8054 pn))
8055
8056 (defun js2-parse-throw ()
8057 "Parser for throw-statement. Last matched token must be js2-THROW."
8058 (let ((pos js2-token-beg)
8059 expr
8060 pn)
8061 (js2-consume-token)
8062 (if (= (js2-peek-token-or-eol) js2-EOL)
8063 ;; ECMAScript does not allow new lines before throw expression,
8064 ;; see bug 256617
8065 (js2-report-error "msg.bad.throw.eol"))
8066 (setq expr (js2-parse-expr)
8067 pn (make-js2-throw-node :pos pos
8068 :len (- (js2-node-end expr) pos)
8069 :expr expr))
8070 (js2-node-add-children pn expr)
8071 pn))
8072
8073 (defsubst js2-match-jump-label-name (label-name)
8074 "If break/continue specified a label, return that label's labeled stmt.
8075 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8076 does not match an existing label, reports an error and returns nil."
8077 (let ((bundle (cdr (assoc label-name js2-label-set))))
8078 (if (null bundle)
8079 (js2-report-error "msg.undef.label"))
8080 bundle))
8081
8082 (defun js2-parse-break ()
8083 "Parser for break-statement. Last matched token must be js2-BREAK."
8084 (let ((pos js2-token-beg)
8085 (end js2-token-end)
8086 break-target ; statement to break from
8087 break-label ; in "break foo", name-node representing the foo
8088 labels ; matching labeled statement to break to
8089 pn)
8090 (js2-consume-token) ; `break'
8091 (when (eq (js2-peek-token-or-eol) js2-NAME)
8092 (js2-consume-token)
8093 (setq break-label (js2-create-name-node)
8094 end (js2-node-end break-label)
8095 ;; matchJumpLabelName only matches if there is one
8096 labels (js2-match-jump-label-name js2-ts-string)
8097 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8098 (unless (or break-target break-label)
8099 ;; no break target specified - try for innermost enclosing loop/switch
8100 (if (null js2-loop-and-switch-set)
8101 (unless break-label
8102 (js2-report-error "msg.bad.break" nil pos (length "break")))
8103 (setq break-target (car js2-loop-and-switch-set))))
8104 (setq pn (make-js2-break-node :pos pos
8105 :len (- end pos)
8106 :label break-label
8107 :target break-target))
8108 (js2-node-add-children pn break-label) ; but not break-target
8109 pn))
8110
8111 (defun js2-parse-continue ()
8112 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8113 (let ((pos js2-token-beg)
8114 (end js2-token-end)
8115 label ; optional user-specified label, a `js2-name-node'
8116 labels ; current matching labeled stmt, if any
8117 target ; the `js2-loop-node' target of this continue stmt
8118 pn)
8119 (js2-consume-token) ; `continue'
8120 (when (= (js2-peek-token-or-eol) js2-NAME)
8121 (js2-consume-token)
8122 (setq label (js2-create-name-node)
8123 end (js2-node-end label)
8124 ;; matchJumpLabelName only matches if there is one
8125 labels (js2-match-jump-label-name js2-ts-string)))
8126 (cond
8127 ((null labels) ; no current label to go to
8128 (if (null js2-loop-set) ; no loop to continue to
8129 (js2-report-error "msg.continue.outside" nil pos
8130 (length "continue"))
8131 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8132 (t
8133 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8134 (setq target (js2-labeled-stmt-node-stmt labels))
8135 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8136 (setq pn (make-js2-continue-node :pos pos
8137 :len (- end pos)
8138 :label label
8139 :target target))
8140 (js2-node-add-children pn label) ; but not target - it's not our child
8141 pn))
8142
8143 (defun js2-parse-with ()
8144 "Parser for with-statement. Last matched token must be js2-WITH."
8145 (js2-consume-token)
8146 (let ((pos js2-token-beg)
8147 obj body pn lp rp)
8148 (if (js2-must-match js2-LP "msg.no.paren.with")
8149 (setq lp js2-token-beg))
8150 (setq obj (js2-parse-expr))
8151 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8152 (setq rp js2-token-beg))
8153 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8154 (setq body (js2-parse-statement)))
8155 (setq pn (make-js2-with-node :pos pos
8156 :len (- (js2-node-end body) pos)
8157 :object obj
8158 :body body
8159 :lp (js2-relpos lp pos)
8160 :rp (js2-relpos rp pos)))
8161 (js2-node-add-children pn obj body)
8162 pn))
8163
8164 (defun js2-parse-const-var ()
8165 "Parser for var- or const-statement.
8166 Last matched token must be js2-CONST or js2-VAR."
8167 (let ((tt (js2-peek-token))
8168 (pos js2-token-beg)
8169 expr
8170 pn)
8171 (js2-consume-token)
8172 (setq expr (js2-parse-variables tt js2-token-beg)
8173 pn (make-js2-expr-stmt-node :pos pos
8174 :len (- (js2-node-end expr) pos)
8175 :expr expr))
8176 (js2-node-add-children pn expr)
8177 pn))
8178
8179 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8180 (let ((pn (make-js2-expr-stmt-node :pos pos
8181 :len (js2-node-len expr)
8182 :type (if (js2-inside-function)
8183 js2-EXPR_VOID
8184 js2-EXPR_RESULT)
8185 :expr expr)))
8186 (if add-child
8187 (js2-node-add-children pn expr))
8188 pn))
8189
8190 (defun js2-parse-let-stmt ()
8191 "Parser for let-statement. Last matched token must be js2-LET."
8192 (js2-consume-token)
8193 (let ((pos js2-token-beg)
8194 expr
8195 pn)
8196 (if (= (js2-peek-token) js2-LP)
8197 ;; let expression in statement context
8198 (setq expr (js2-parse-let pos 'statement)
8199 pn (js2-wrap-with-expr-stmt pos expr t))
8200 ;; else we're looking at a statement like let x=6, y=7;
8201 (setf expr (js2-parse-variables js2-LET pos)
8202 pn (js2-wrap-with-expr-stmt pos expr t)
8203 (js2-node-type pn) js2-EXPR_RESULT))
8204 pn))
8205
8206 (defun js2-parse-ret-yield ()
8207 (js2-parse-return-or-yield (js2-peek-token) nil))
8208
8209 (defconst js2-parse-return-stmt-enders
8210 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8211
8212 (defsubst js2-now-all-set (before after mask)
8213 "Return whether or not the bits in the mask have changed to all set.
8214 BEFORE is bits before change, AFTER is bits after change, and MASK is
8215 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8216 but not BEFORE."
8217 (and (/= (logand before mask) mask)
8218 (= (logand after mask) mask)))
8219
8220 (defun js2-parse-return-or-yield (tt expr-context)
8221 (let ((pos js2-token-beg)
8222 (end js2-token-end)
8223 (before js2-end-flags)
8224 (inside-function (js2-inside-function))
8225 e
8226 ret
8227 name)
8228 (unless inside-function
8229 (js2-report-error (if (eq tt js2-RETURN)
8230 "msg.bad.return"
8231 "msg.bad.yield")))
8232 (js2-consume-token)
8233 ;; This is ugly, but we don't want to require a semicolon.
8234 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8235 (setq e (js2-parse-expr)
8236 end (js2-node-end e)))
8237 (cond
8238 ((eq tt js2-RETURN)
8239 (js2-set-flag js2-end-flags (if (null e)
8240 js2-end-returns
8241 js2-end-returns-value))
8242 (setq ret (make-js2-return-node :pos pos
8243 :len (- end pos)
8244 :retval e))
8245 (js2-node-add-children ret e)
8246 ;; See if we need a strict mode warning.
8247 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8248 ;; more thorough and accurate than this before/after flag check.
8249 ;; E.g. if there's a finally-block that always returns, we shouldn't
8250 ;; show a warning generated by inconsistent returns in the catch blocks.
8251 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8252 ;; so we know which returns/yields to highlight, and we should get rid of
8253 ;; all the checking in `js2-parse-return-or-yield'.
8254 (if (and js2-strict-inconsistent-return-warning
8255 (js2-now-all-set before js2-end-flags
8256 (logior js2-end-returns js2-end-returns-value)))
8257 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8258 (t
8259 (unless (js2-inside-function)
8260 (js2-report-error "msg.bad.yield"))
8261 (js2-set-flag js2-end-flags js2-end-yields)
8262 (setq ret (make-js2-yield-node :pos pos
8263 :len (- end pos)
8264 :value e))
8265 (js2-node-add-children ret e)
8266 (unless expr-context
8267 (setq e ret
8268 ret (js2-wrap-with-expr-stmt pos e t))
8269 (js2-set-requires-activation)
8270 (js2-set-is-generator))))
8271 ;; see if we are mixing yields and value returns.
8272 (when (and inside-function
8273 (js2-now-all-set before js2-end-flags
8274 (logior js2-end-yields js2-end-returns-value)))
8275 (setq name (js2-function-name js2-current-script-or-fn))
8276 (if (zerop (length name))
8277 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8278 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8279 ret))
8280
8281 (defun js2-parse-debugger ()
8282 (js2-consume-token)
8283 (make-js2-keyword-node :type js2-DEBUGGER))
8284
8285 (defun js2-parse-block ()
8286 "Parser for a curly-delimited statement block.
8287 Last token matched must be js2-LC."
8288 (let ((pos js2-token-beg)
8289 (pn (make-js2-scope)))
8290 (js2-consume-token)
8291 (js2-push-scope pn)
8292 (unwind-protect
8293 (progn
8294 (js2-parse-statements pn)
8295 (js2-must-match js2-RC "msg.no.brace.block")
8296 (setf (js2-node-len pn) (- js2-token-end pos)))
8297 (js2-pop-scope))
8298 pn))
8299
8300 ;; for js2-ERROR too, to have a node for error recovery to work on
8301 (defun js2-parse-semi ()
8302 "Parse a statement or handle an error.
8303 Last matched token is js-SEMI or js-ERROR."
8304 (let ((tt (js2-peek-token)) pos len)
8305 (js2-consume-token)
8306 (if (eq tt js2-SEMI)
8307 (make-js2-empty-expr-node :len 1)
8308 (setq pos js2-token-beg
8309 len (- js2-token-beg pos))
8310 (js2-report-error "msg.syntax" nil pos len)
8311 (make-js2-error-node :pos pos :len len))))
8312
8313 (defun js2-parse-default-xml-namespace ()
8314 "Parse a `default xml namespace = <expr>' e4x statement."
8315 (let ((pos js2-token-beg)
8316 end len expr unary es)
8317 (js2-consume-token)
8318 (js2-must-have-xml)
8319 (js2-set-requires-activation)
8320 (setq len (- js2-ts-cursor pos))
8321 (unless (and (js2-match-token js2-NAME)
8322 (string= js2-ts-string "xml"))
8323 (js2-report-error "msg.bad.namespace" nil pos len))
8324 (unless (and (js2-match-token js2-NAME)
8325 (string= js2-ts-string "namespace"))
8326 (js2-report-error "msg.bad.namespace" nil pos len))
8327 (unless (js2-match-token js2-ASSIGN)
8328 (js2-report-error "msg.bad.namespace" nil pos len))
8329 (setq expr (js2-parse-expr)
8330 end (js2-node-end expr)
8331 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8332 :pos pos
8333 :len (- end pos)
8334 :operand expr))
8335 (js2-node-add-children unary expr)
8336 (make-js2-expr-stmt-node :pos pos
8337 :len (- end pos)
8338 :expr unary)))
8339
8340 (defun js2-record-label (label bundle)
8341 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8342 (js2-consume-token)
8343 (let ((name (js2-label-node-name label))
8344 labeled-stmt
8345 dup)
8346 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8347 ;; flag both labels if possible when used in editing mode
8348 (if (and js2-parse-ide-mode
8349 (setq dup (js2-get-label-by-name labeled-stmt name)))
8350 (js2-report-error "msg.dup.label" nil
8351 (js2-node-abs-pos dup) (js2-node-len dup)))
8352 (js2-report-error "msg.dup.label" nil
8353 (js2-node-pos label) (js2-node-len label)))
8354 (js2-labeled-stmt-node-add-label bundle label)
8355 (js2-node-add-children bundle label)
8356 ;; Add one reference to the bundle per label in `js2-label-set'
8357 (push (cons name bundle) js2-label-set)))
8358
8359 (defun js2-parse-name-or-label ()
8360 "Parser for identifier or label. Last token matched must be js2-NAME.
8361 Called when we found a name in a statement context. If it's a label, we gather
8362 up any following labels and the next non-label statement into a
8363 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8364 expression and return it wrapped in a `js2-expr-stmt-node'."
8365 (let ((pos js2-token-beg)
8366 (end js2-token-end)
8367 expr
8368 stmt
8369 pn
8370 bundle
8371 (continue t))
8372 ;; set check for label and call down to `js2-parse-primary-expr'
8373 (js2-set-check-for-label)
8374 (setq expr (js2-parse-expr))
8375 (if (/= (js2-node-type expr) js2-LABEL)
8376 ;; Parsed non-label expression - wrap with expression stmt.
8377 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8378 ;; else parsed a label
8379 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8380 (js2-record-label expr bundle)
8381 ;; look for more labels
8382 (while (and continue (= (js2-peek-token) js2-NAME))
8383 (js2-set-check-for-label)
8384 (setq expr (js2-parse-expr))
8385 (if (/= (js2-node-type expr) js2-LABEL)
8386 (progn
8387 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8388 continue nil)
8389 (js2-auto-insert-semicolon stmt))
8390 (js2-record-label expr bundle)))
8391 ;; no more labels; now parse the labeled statement
8392 (unwind-protect
8393 (unless stmt
8394 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8395 (setq stmt (js2-statement-helper))))
8396 ;; remove the labels for this statement from the global set
8397 (dolist (label (js2-labeled-stmt-node-labels bundle))
8398 (setq js2-label-set (remove label js2-label-set))))
8399 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8400 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8401 (js2-node-add-children bundle stmt)
8402 bundle)))
8403
8404 (defun js2-parse-expr-stmt ()
8405 "Default parser in statement context, if no recognized statement found."
8406 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8407
8408 (defun js2-parse-variables (decl-type pos)
8409 "Parse a comma-separated list of variable declarations.
8410 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8411
8412 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8413 For 'var' or 'const', the keyword should be the token last scanned.
8414
8415 POS is the position where the node should start. It's sometimes the
8416 var/const/let keyword, and other times the beginning of the first token
8417 in the first variable declaration.
8418
8419 Returns the parsed `js2-var-decl-node' expression node."
8420 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8421 :pos pos))
8422 destructuring
8423 kid-pos
8424 tt
8425 init
8426 name
8427 end
8428 nbeg nend
8429 vi
8430 (continue t))
8431 ;; Example:
8432 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8433 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8434 ;; var {a, b} = baz;
8435 (while continue
8436 (setq destructuring nil
8437 name nil
8438 tt (js2-peek-token)
8439 kid-pos js2-token-beg
8440 end js2-token-end
8441 init nil)
8442 (if (or (= tt js2-LB) (= tt js2-LC))
8443 ;; Destructuring assignment, e.g., var [a, b] = ...
8444 (setq destructuring (js2-parse-primary-expr-lhs)
8445 end (js2-node-end destructuring))
8446 ;; Simple variable name
8447 (when (js2-must-match js2-NAME "msg.bad.var")
8448 (setq name (js2-create-name-node)
8449 nbeg js2-token-beg
8450 nend js2-token-end
8451 end nend)
8452 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8453 (when (js2-match-token js2-ASSIGN)
8454 (setq init (js2-parse-assign-expr)
8455 end (js2-node-end init))
8456 (if (and js2-parse-ide-mode
8457 (or (js2-object-node-p init)
8458 (js2-function-node-p init)))
8459 (js2-record-imenu-functions init name)))
8460 (when name
8461 (js2-set-face nbeg nend (if (js2-function-node-p init)
8462 'font-lock-function-name-face
8463 'font-lock-variable-name-face)
8464 'record))
8465 (setq vi (make-js2-var-init-node :pos kid-pos
8466 :len (- end kid-pos)
8467 :type decl-type))
8468 (if destructuring
8469 (progn
8470 (if (and (null init) (not js2-in-for-init))
8471 (js2-report-error "msg.destruct.assign.no.init"))
8472 (js2-define-destruct-symbols destructuring
8473 decl-type
8474 'font-lock-variable-name-face)
8475 (setf (js2-var-init-node-target vi) destructuring))
8476 (setf (js2-var-init-node-target vi) name))
8477 (setf (js2-var-init-node-initializer vi) init)
8478 (js2-node-add-children vi name destructuring init)
8479 (js2-block-node-push result vi)
8480 (unless (js2-match-token js2-COMMA)
8481 (setq continue nil)))
8482 (setf (js2-node-len result) (- end pos))
8483 result))
8484
8485 (defun js2-parse-let (pos &optional stmt-p)
8486 "Parse a let expression or statement.
8487 A let-expression is of the form `let (vars) expr'.
8488 A let-statment is of the form `let (vars) {statements}'.
8489 The third form of let is a variable declaration list, handled
8490 by `js2-parse-variables'."
8491 (let ((pn (make-js2-let-node :pos pos))
8492 beg vars body)
8493 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8494 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8495 (js2-push-scope pn)
8496 (unwind-protect
8497 (progn
8498 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8499 (if (js2-must-match js2-RP "msg.no.paren.let")
8500 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8501 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8502 ;; let statement
8503 (progn
8504 (js2-consume-token)
8505 (setf beg js2-token-beg ; position stmt at LC
8506 body (js2-parse-statements))
8507 (js2-must-match js2-RC "msg.no.curly.let")
8508 (setf (js2-node-len body) (- js2-token-end beg)
8509 (js2-node-len pn) (- js2-token-end pos)
8510 (js2-let-node-body pn) body
8511 (js2-node-type pn) js2-LET))
8512 ;; let expression
8513 (setf body (js2-parse-expr)
8514 (js2-node-len pn) (- (js2-node-end body) pos)
8515 (js2-let-node-body pn) body))
8516 (js2-node-add-children pn vars body))
8517 (js2-pop-scope))
8518 pn))
8519
8520 (defsubst js2-define-new-symbol (decl-type name node)
8521 (js2-scope-put-symbol js2-current-scope
8522 name
8523 (make-js2-symbol decl-type name node)))
8524
8525 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8526 "Define a symbol in the current scope.
8527 If NODE is non-nil, it is the AST node associated with the symbol."
8528 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8529 (symbol (if defining-scope
8530 (js2-scope-get-symbol defining-scope name)))
8531 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8532 (cond
8533 ((and symbol ; already defined
8534 (or (= sdt js2-CONST) ; old version is const
8535 (= decl-type js2-CONST) ; new version is const
8536 ;; two let-bound vars in this block have same name
8537 (and (= sdt js2-LET)
8538 (eq defining-scope js2-current-scope))))
8539 (js2-report-error
8540 (cond
8541 ((= sdt js2-CONST) "msg.const.redecl")
8542 ((= sdt js2-LET) "msg.let.redecl")
8543 ((= sdt js2-VAR) "msg.var.redecl")
8544 ((= sdt js2-FUNCTION) "msg.function.redecl")
8545 (t "msg.parm.redecl"))
8546 name))
8547 ((= decl-type js2-LET)
8548 (if (and (not ignore-not-in-block)
8549 (or (= (js2-node-type js2-current-scope) js2-IF)
8550 (js2-loop-node-p js2-current-scope)))
8551 (js2-report-error "msg.let.decl.not.in.block")
8552 (js2-define-new-symbol decl-type name node)))
8553 ((or (= decl-type js2-VAR)
8554 (= decl-type js2-CONST)
8555 (= decl-type js2-FUNCTION))
8556 (if symbol
8557 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8558 (js2-add-strict-warning "msg.var.redecl" name)
8559 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8560 (js2-add-strict-warning "msg.var.hides.arg" name)))
8561 (js2-define-new-symbol decl-type name node)))
8562 ((= decl-type js2-LP)
8563 (if symbol
8564 ;; must be duplicate parameter. Second parameter hides the
8565 ;; first, so go ahead and add the second pararameter
8566 (js2-report-warning "msg.dup.parms" name))
8567 (js2-define-new-symbol decl-type name node))
8568 (t (js2-code-bug)))))
8569
8570 (defun js2-parse-expr (&optional oneshot)
8571 (let* ((pn (js2-parse-assign-expr))
8572 (pos (js2-node-pos pn))
8573 left
8574 right
8575 op-pos)
8576 (while (and (not oneshot)
8577 (js2-match-token js2-COMMA))
8578 (setq op-pos (- js2-token-beg pos)) ; relative
8579 (if (= (js2-peek-token) js2-YIELD)
8580 (js2-report-error "msg.yield.parenthesized"))
8581 (setq right (js2-parse-assign-expr)
8582 left pn
8583 pn (make-js2-infix-node :type js2-COMMA
8584 :pos pos
8585 :len (- js2-ts-cursor pos)
8586 :op-pos op-pos
8587 :left left
8588 :right right))
8589 (js2-node-add-children pn left right))
8590 pn))
8591
8592 (defun js2-parse-assign-expr ()
8593 (let ((tt (js2-peek-token))
8594 (pos js2-token-beg)
8595 pn
8596 left
8597 right
8598 op-pos)
8599 (if (= tt js2-YIELD)
8600 (js2-parse-return-or-yield tt t)
8601 ;; not yield - parse assignment expression
8602 (setq pn (js2-parse-cond-expr)
8603 tt (js2-peek-token))
8604 (when (and (<= js2-first-assign tt)
8605 (<= tt js2-last-assign))
8606 ;; tt express assignment (=, |=, ^=, ..., %=)
8607 (js2-consume-token)
8608 (setq op-pos (- js2-token-beg pos) ; relative
8609 left pn
8610 right (js2-parse-assign-expr)
8611 pn (make-js2-assign-node :type tt
8612 :pos pos
8613 :len (- (js2-node-end right) pos)
8614 :op-pos op-pos
8615 :left left
8616 :right right))
8617 (when js2-parse-ide-mode
8618 (js2-highlight-assign-targets pn left right)
8619 (if (or (js2-function-node-p right)
8620 (js2-object-node-p right))
8621 (js2-record-imenu-functions right left)))
8622 ;; do this last so ide checks above can use absolute positions
8623 (js2-node-add-children pn left right))
8624 pn)))
8625
8626 (defun js2-parse-cond-expr ()
8627 (let ((pos js2-token-beg)
8628 (pn (js2-parse-or-expr))
8629 test-expr
8630 if-true
8631 if-false
8632 q-pos
8633 c-pos)
8634 (when (js2-match-token js2-HOOK)
8635 (setq q-pos (- js2-token-beg pos)
8636 if-true (js2-parse-assign-expr))
8637 (js2-must-match js2-COLON "msg.no.colon.cond")
8638 (setq c-pos (- js2-token-beg pos)
8639 if-false (js2-parse-assign-expr)
8640 test-expr pn
8641 pn (make-js2-cond-node :pos pos
8642 :len (- (js2-node-end if-false) pos)
8643 :test-expr test-expr
8644 :true-expr if-true
8645 :false-expr if-false
8646 :q-pos q-pos
8647 :c-pos c-pos))
8648 (js2-node-add-children pn test-expr if-true if-false))
8649 pn))
8650
8651 (defun js2-make-binary (type left parser)
8652 "Helper for constructing a binary-operator AST node.
8653 LEFT is the left-side-expression, already parsed, and the
8654 binary operator should have just been matched.
8655 PARSER is a function to call to parse the right operand,
8656 or a `js2-node' struct if it has already been parsed."
8657 (let* ((pos (js2-node-pos left))
8658 (op-pos (- js2-token-beg pos))
8659 (right (if (js2-node-p parser)
8660 parser
8661 (funcall parser)))
8662 (pn (make-js2-infix-node :type type
8663 :pos pos
8664 :len (- (js2-node-end right) pos)
8665 :op-pos op-pos
8666 :left left
8667 :right right)))
8668 (js2-node-add-children pn left right)
8669 pn))
8670
8671 (defun js2-parse-or-expr ()
8672 (let ((pn (js2-parse-and-expr)))
8673 (when (js2-match-token js2-OR)
8674 (setq pn (js2-make-binary js2-OR
8675 pn
8676 'js2-parse-or-expr)))
8677 pn))
8678
8679 (defun js2-parse-and-expr ()
8680 (let ((pn (js2-parse-bit-or-expr)))
8681 (when (js2-match-token js2-AND)
8682 (setq pn (js2-make-binary js2-AND
8683 pn
8684 'js2-parse-and-expr)))
8685 pn))
8686
8687 (defun js2-parse-bit-or-expr ()
8688 (let ((pn (js2-parse-bit-xor-expr)))
8689 (while (js2-match-token js2-BITOR)
8690 (setq pn (js2-make-binary js2-BITOR
8691 pn
8692 'js2-parse-bit-xor-expr)))
8693 pn))
8694
8695 (defun js2-parse-bit-xor-expr ()
8696 (let ((pn (js2-parse-bit-and-expr)))
8697 (while (js2-match-token js2-BITXOR)
8698 (setq pn (js2-make-binary js2-BITXOR
8699 pn
8700 'js2-parse-bit-and-expr)))
8701 pn))
8702
8703 (defun js2-parse-bit-and-expr ()
8704 (let ((pn (js2-parse-eq-expr)))
8705 (while (js2-match-token js2-BITAND)
8706 (setq pn (js2-make-binary js2-BITAND
8707 pn
8708 'js2-parse-eq-expr)))
8709 pn))
8710
8711 (defconst js2-parse-eq-ops
8712 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8713
8714 (defun js2-parse-eq-expr ()
8715 (let ((pn (js2-parse-rel-expr))
8716 tt)
8717 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8718 (js2-consume-token)
8719 (setq pn (js2-make-binary tt
8720 pn
8721 'js2-parse-rel-expr)))
8722 pn))
8723
8724 (defconst js2-parse-rel-ops
8725 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8726
8727 (defun js2-parse-rel-expr ()
8728 (let ((pn (js2-parse-shift-expr))
8729 (continue t)
8730 tt)
8731 (while continue
8732 (setq tt (js2-peek-token))
8733 (cond
8734 ((and js2-in-for-init (= tt js2-IN))
8735 (setq continue nil))
8736 ((memq tt js2-parse-rel-ops)
8737 (js2-consume-token)
8738 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8739 (t
8740 (setq continue nil))))
8741 pn))
8742
8743 (defconst js2-parse-shift-ops
8744 (list js2-LSH js2-URSH js2-RSH))
8745
8746 (defun js2-parse-shift-expr ()
8747 (let ((pn (js2-parse-add-expr))
8748 tt
8749 (continue t))
8750 (while continue
8751 (setq tt (js2-peek-token))
8752 (if (memq tt js2-parse-shift-ops)
8753 (progn
8754 (js2-consume-token)
8755 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8756 (setq continue nil)))
8757 pn))
8758
8759 (defun js2-parse-add-expr ()
8760 (let ((pn (js2-parse-mul-expr))
8761 tt
8762 (continue t))
8763 (while continue
8764 (setq tt (js2-peek-token))
8765 (if (or (= tt js2-ADD) (= tt js2-SUB))
8766 (progn
8767 (js2-consume-token)
8768 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8769 (setq continue nil)))
8770 pn))
8771
8772 (defconst js2-parse-mul-ops
8773 (list js2-MUL js2-DIV js2-MOD))
8774
8775 (defun js2-parse-mul-expr ()
8776 (let ((pn (js2-parse-unary-expr))
8777 tt
8778 (continue t))
8779 (while continue
8780 (setq tt (js2-peek-token))
8781 (if (memq tt js2-parse-mul-ops)
8782 (progn
8783 (js2-consume-token)
8784 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8785 (setq continue nil)))
8786 pn))
8787
8788 (defsubst js2-make-unary (type parser &rest args)
8789 "Make a unary node of type TYPE.
8790 PARSER is either a node (for postfix operators) or a function to call
8791 to parse the operand (for prefix operators)."
8792 (let* ((pos js2-token-beg)
8793 (postfix (js2-node-p parser))
8794 (expr (if postfix
8795 parser
8796 (apply parser args)))
8797 end
8798 pn)
8799 (if postfix ; e.g. i++
8800 (setq pos (js2-node-pos expr)
8801 end js2-token-end)
8802 (setq end (js2-node-end expr)))
8803 (setq pn (make-js2-unary-node :type type
8804 :pos pos
8805 :len (- end pos)
8806 :operand expr))
8807 (js2-node-add-children pn expr)
8808 pn))
8809
8810 (defconst js2-incrementable-node-types
8811 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8812 "Node types that can be the operand of a ++ or -- operator.")
8813
8814 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8815 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8816 js2-incrementable-node-types)
8817 (js2-report-error (if (= tt js2-INC)
8818 "msg.bad.incr"
8819 "msg.bad.decr")
8820 nil beg (- end beg))))
8821
8822 (defun js2-parse-unary-expr ()
8823 (let ((tt (js2-peek-token))
8824 pn expr beg end)
8825 (cond
8826 ((or (= tt js2-VOID)
8827 (= tt js2-NOT)
8828 (= tt js2-BITNOT)
8829 (= tt js2-TYPEOF))
8830 (js2-consume-token)
8831 (js2-make-unary tt 'js2-parse-unary-expr))
8832 ((= tt js2-ADD)
8833 (js2-consume-token)
8834 ;; Convert to special POS token in decompiler and parse tree
8835 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8836 ((= tt js2-SUB)
8837 (js2-consume-token)
8838 ;; Convert to special NEG token in decompiler and parse tree
8839 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8840 ((or (= tt js2-INC)
8841 (= tt js2-DEC))
8842 (js2-consume-token)
8843 (prog1
8844 (setq beg js2-token-beg
8845 end js2-token-end
8846 expr (js2-make-unary tt 'js2-parse-member-expr t))
8847 (js2-check-bad-inc-dec tt beg end expr)))
8848 ((= tt js2-DELPROP)
8849 (js2-consume-token)
8850 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8851 ((= tt js2-ERROR)
8852 (js2-consume-token)
8853 (make-js2-error-node)) ; try to continue
8854 ((and (= tt js2-LT)
8855 js2-compiler-xml-available)
8856 ;; XML stream encountered in expression.
8857 (js2-consume-token)
8858 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8859 (t
8860 (setq pn (js2-parse-member-expr t)
8861 ;; Don't look across a newline boundary for a postfix incop.
8862 tt (js2-peek-token-or-eol))
8863 (when (or (= tt js2-INC) (= tt js2-DEC))
8864 (js2-consume-token)
8865 (setf expr pn
8866 pn (js2-make-unary tt expr))
8867 (js2-node-set-prop pn 'postfix t)
8868 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8869 pn))))
8870
8871 (defun js2-parse-xml-initializer ()
8872 "Parse an E4X XML initializer.
8873 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8874 Then I'll postprocess the result, depending on whether we're in IDE
8875 mode or codegen mode, and generate the appropriate rewritten AST.
8876 IDE mode uses a rich AST that models the XML structure. Codegen mode
8877 just concatenates everything and makes a new XML or XMLList out of it."
8878 (let ((tt (js2-get-first-xml-token))
8879 pn-xml
8880 pn
8881 expr
8882 kids
8883 expr-pos
8884 (continue t)
8885 (first-token t))
8886 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8887 (js2-report-error "msg.syntax"))
8888 (setq pn-xml (make-js2-xml-node))
8889 (while continue
8890 (if first-token
8891 (setq first-token nil)
8892 (setq tt (js2-get-next-xml-token)))
8893 (cond
8894 ;; js2-XML means we found a {expr} in the XML stream.
8895 ;; The js2-ts-string is the XML up to the left-curly.
8896 ((= tt js2-XML)
8897 (push (make-js2-string-node :pos js2-token-beg
8898 :len (- js2-ts-cursor js2-token-beg))
8899 kids)
8900 (js2-must-match js2-LC "msg.syntax")
8901 (setq expr-pos js2-ts-cursor
8902 expr (if (eq (js2-peek-token) js2-RC)
8903 (make-js2-empty-expr-node :pos expr-pos)
8904 (js2-parse-expr)))
8905 (js2-must-match js2-RC "msg.syntax")
8906 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8907 :len (js2-node-len expr)
8908 :expr expr))
8909 (js2-node-add-children pn expr)
8910 (push pn kids))
8911 ;; a js2-XMLEND token means we hit the final close-tag.
8912 ((= tt js2-XMLEND)
8913 (push (make-js2-string-node :pos js2-token-beg
8914 :len (- js2-ts-cursor js2-token-beg))
8915 kids)
8916 (dolist (kid (nreverse kids))
8917 (js2-block-node-push pn-xml kid))
8918 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8919 (js2-node-pos pn-xml))
8920 continue nil))
8921 (t
8922 (js2-report-error "msg.syntax")
8923 (setq continue nil))))
8924 pn-xml))
8925
8926
8927 (defun js2-parse-argument-list ()
8928 "Parse an argument list and return it as a lisp list of nodes.
8929 Returns the list in reverse order. Consumes the right-paren token."
8930 (let (result)
8931 (unless (js2-match-token js2-RP)
8932 (loop do
8933 (if (= (js2-peek-token) js2-YIELD)
8934 (js2-report-error "msg.yield.parenthesized"))
8935 (push (js2-parse-assign-expr) result)
8936 while
8937 (js2-match-token js2-COMMA))
8938 (js2-must-match js2-RP "msg.no.paren.arg")
8939 result)))
8940
8941 (defun js2-parse-member-expr (&optional allow-call-syntax)
8942 (let ((tt (js2-peek-token))
8943 pn
8944 pos
8945 target
8946 args
8947 beg
8948 end
8949 init
8950 tail)
8951 (if (/= tt js2-NEW)
8952 (setq pn (js2-parse-primary-expr))
8953 ;; parse a 'new' expression
8954 (js2-consume-token)
8955 (setq pos js2-token-beg
8956 beg pos
8957 target (js2-parse-member-expr)
8958 end (js2-node-end target)
8959 pn (make-js2-new-node :pos pos
8960 :target target
8961 :len (- end pos)))
8962 (js2-node-add-children pn target)
8963 (when (js2-match-token js2-LP)
8964 ;; Add the arguments to pn, if any are supplied.
8965 (setf beg pos ; start of "new" keyword
8966 pos js2-token-beg
8967 args (nreverse (js2-parse-argument-list))
8968 (js2-new-node-args pn) args
8969 end js2-token-end
8970 (js2-new-node-lp pn) (- pos beg)
8971 (js2-new-node-rp pn) (- end 1 beg))
8972 (apply #'js2-node-add-children pn args))
8973 (when (and js2-allow-rhino-new-expr-initializer
8974 (js2-match-token js2-LC))
8975 (setf init (js2-parse-object-literal)
8976 end (js2-node-end init)
8977 (js2-new-node-initializer pn) init)
8978 (js2-node-add-children pn init))
8979 (setf (js2-node-len pn) (- end beg))) ; end outer if
8980 (js2-parse-member-expr-tail allow-call-syntax pn)))
8981
8982 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8983 "Parse a chain of property/array accesses or function calls.
8984 Includes parsing for E4X operators like `..' and `.@'.
8985 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8986 Returns an expression tree that includes PN, the parent node."
8987 (let ((beg (js2-node-pos pn))
8988 tt
8989 (continue t))
8990 (while continue
8991 (setq tt (js2-peek-token))
8992 (cond
8993 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8994 (setq pn (js2-parse-property-access tt pn)))
8995 ((= tt js2-DOTQUERY)
8996 (setq pn (js2-parse-dot-query pn)))
8997 ((= tt js2-LB)
8998 (setq pn (js2-parse-element-get pn)))
8999 ((= tt js2-LP)
9000 (if allow-call-syntax
9001 (setq pn (js2-parse-function-call pn))
9002 (setq continue nil)))
9003 (t
9004 (setq continue nil))))
9005 (if (>= js2-highlight-level 2)
9006 (js2-parse-highlight-member-expr-node pn))
9007 pn))
9008
9009 (defun js2-parse-dot-query (pn)
9010 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9011 Last token parsed must be `js2-DOTQUERY'."
9012 (let ((pos (js2-node-pos pn))
9013 op-pos
9014 expr
9015 end)
9016 (js2-consume-token)
9017 (js2-must-have-xml)
9018 (js2-set-requires-activation)
9019 (setq op-pos js2-token-beg
9020 expr (js2-parse-expr)
9021 end (js2-node-end expr)
9022 pn (make-js2-xml-dot-query-node :left pn
9023 :pos pos
9024 :op-pos op-pos
9025 :right expr))
9026 (js2-node-add-children pn
9027 (js2-xml-dot-query-node-left pn)
9028 (js2-xml-dot-query-node-right pn))
9029 (if (js2-must-match js2-RP "msg.no.paren")
9030 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9031 end js2-token-end))
9032 (setf (js2-node-len pn) (- end pos))
9033 pn))
9034
9035 (defun js2-parse-element-get (pn)
9036 "Parse an element-get expression, e.g. foo[bar].
9037 Last token parsed must be `js2-RB'."
9038 (let ((lb js2-token-beg)
9039 (pos (js2-node-pos pn))
9040 rb
9041 expr)
9042 (js2-consume-token)
9043 (setq expr (js2-parse-expr))
9044 (if (js2-must-match js2-RB "msg.no.bracket.index")
9045 (setq rb js2-token-beg))
9046 (setq pn (make-js2-elem-get-node :target pn
9047 :pos pos
9048 :element expr
9049 :lb (js2-relpos lb pos)
9050 :rb (js2-relpos rb pos)
9051 :len (- js2-token-end pos)))
9052 (js2-node-add-children pn
9053 (js2-elem-get-node-target pn)
9054 (js2-elem-get-node-element pn))
9055 pn))
9056
9057 (defun js2-parse-function-call (pn)
9058 (let (args
9059 (pos (js2-node-pos pn)))
9060 (js2-consume-token)
9061 (setq pn (make-js2-call-node :pos pos
9062 :target pn
9063 :lp (- js2-token-beg pos)))
9064 (js2-node-add-children pn (js2-call-node-target pn))
9065 ;; Add the arguments to pn, if any are supplied.
9066 (setf args (nreverse (js2-parse-argument-list))
9067 (js2-call-node-rp pn) (- js2-token-beg pos)
9068 (js2-call-node-args pn) args)
9069 (apply #'js2-node-add-children pn args)
9070 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9071 pn))
9072
9073 (defun js2-parse-property-access (tt pn)
9074 "Parse a property access, XML descendants access, or XML attr access."
9075 (let ((member-type-flags 0)
9076 (dot-pos js2-token-beg)
9077 (dot-len (if (= tt js2-DOTDOT) 2 1))
9078 name
9079 ref ; right side of . or .. operator
9080 result)
9081 (js2-consume-token)
9082 (when (= tt js2-DOTDOT)
9083 (js2-must-have-xml)
9084 (setq member-type-flags js2-descendants-flag))
9085 (if (not js2-compiler-xml-available)
9086 (progn
9087 (js2-must-match-prop-name "msg.no.name.after.dot")
9088 (setq name (js2-create-name-node t js2-GETPROP)
9089 result (make-js2-prop-get-node :left pn
9090 :pos js2-token-beg
9091 :right name
9092 :len (- js2-token-end
9093 js2-token-beg)))
9094 (js2-node-add-children result pn name)
9095 result)
9096 ;; otherwise look for XML operators
9097 (setf result (if (= tt js2-DOT)
9098 (make-js2-prop-get-node)
9099 (make-js2-infix-node :type js2-DOTDOT))
9100 (js2-node-pos result) (js2-node-pos pn)
9101 (js2-infix-node-op-pos result) dot-pos
9102 (js2-infix-node-left result) pn ; do this after setting position
9103 tt (js2-next-token))
9104 (cond
9105 ;; needed for generator.throw()
9106 ((= tt js2-THROW)
9107 (js2-save-name-token-data js2-token-beg "throw")
9108 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9109 ;; handles: name, ns::name, ns::*, ns::[expr]
9110 ((js2-valid-prop-name-token tt)
9111 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9112 ;; handles: *, *::name, *::*, *::[expr]
9113 ((= tt js2-MUL)
9114 (js2-save-name-token-data js2-token-beg "*")
9115 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9116 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9117 ((= tt js2-XMLATTR)
9118 (setq result (js2-parse-attribute-access)))
9119 (t
9120 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9121 (if ref
9122 (setf (js2-node-len result) (- (js2-node-end ref)
9123 (js2-node-pos result))
9124 (js2-infix-node-right result) ref))
9125 (if (js2-infix-node-p result)
9126 (js2-node-add-children result
9127 (js2-infix-node-left result)
9128 (js2-infix-node-right result)))
9129 result)))
9130
9131 (defun js2-parse-attribute-access ()
9132 "Parse an E4X XML attribute expression.
9133 This includes expressions of the forms:
9134
9135 @attr @ns::attr @ns::*
9136 @* @*::attr @*::*
9137 @[expr] @*::[expr] @ns::[expr]
9138
9139 Called if we peeked an '@' token."
9140 (let ((tt (js2-next-token))
9141 (at-pos js2-token-beg))
9142 (cond
9143 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9144 ((js2-valid-prop-name-token tt)
9145 (js2-parse-property-name at-pos js2-ts-string 0))
9146 ;; handles: @*, @*::name, @*::*, @*::[expr]
9147 ((= tt js2-MUL)
9148 (js2-save-name-token-data js2-token-beg "*")
9149 (js2-parse-property-name js2-token-beg "*" 0))
9150 ;; handles @[expr]
9151 ((= tt js2-LB)
9152 (js2-parse-xml-elem-ref at-pos))
9153 (t
9154 (js2-report-error "msg.no.name.after.xmlAttr")
9155 ;; Avoid cascaded errors that happen if we make an error node here.
9156 (js2-save-name-token-data js2-token-beg "")
9157 (js2-parse-property-name js2-token-beg "" 0)))))
9158
9159 (defun js2-parse-property-name (at-pos s member-type-flags)
9160 "Check if :: follows name in which case it becomes qualified name.
9161
9162 AT-POS is a natural number if we just read an '@' token, else nil.
9163 S is the name or string that was matched: an identifier, 'throw' or '*'.
9164 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9165
9166 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9167 operator, or the name is followed by ::. For a plain name, returns a
9168 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9169 (let ((pos (or at-pos js2-token-beg))
9170 colon-pos
9171 (name (js2-create-name-node t js2-current-token))
9172 ns
9173 tt
9174 ref
9175 pn)
9176 (catch 'return
9177 (when (js2-match-token js2-COLONCOLON)
9178 (setq ns name
9179 colon-pos js2-token-beg
9180 tt (js2-next-token))
9181 (cond
9182 ;; handles name::name
9183 ((js2-valid-prop-name-token tt)
9184 (setq name (js2-create-name-node)))
9185 ;; handles name::*
9186 ((= tt js2-MUL)
9187 (js2-save-name-token-data js2-token-beg "*")
9188 (setq name (js2-create-name-node)))
9189 ;; handles name::[expr]
9190 ((= tt js2-LB)
9191 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9192 (t
9193 (js2-report-error "msg.no.name.after.coloncolon"))))
9194 (if (and (null ns) (zerop member-type-flags))
9195 name
9196 (prog1
9197 (setq pn
9198 (make-js2-xml-prop-ref-node :pos pos
9199 :len (- (js2-node-end name) pos)
9200 :at-pos at-pos
9201 :colon-pos colon-pos
9202 :propname name))
9203 (js2-node-add-children pn name))))))
9204
9205 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9206 "Parse the [expr] portion of an xml element reference.
9207 For instance, @[expr], @*::[expr], or ns::[expr]."
9208 (let* ((lb js2-token-beg)
9209 (pos (or at-pos lb))
9210 rb
9211 (expr (js2-parse-expr))
9212 (end (js2-node-end expr))
9213 pn)
9214 (if (js2-must-match js2-RB "msg.no.bracket.index")
9215 (setq rb js2-token-beg
9216 end js2-token-end))
9217 (prog1
9218 (setq pn
9219 (make-js2-xml-elem-ref-node :pos pos
9220 :len (- end pos)
9221 :namespace namespace
9222 :colon-pos colon-pos
9223 :at-pos at-pos
9224 :expr expr
9225 :lb (js2-relpos lb pos)
9226 :rb (js2-relpos rb pos)))
9227 (js2-node-add-children pn namespace expr))))
9228
9229 (defsubst js2-parse-primary-expr-lhs ()
9230 (let ((js2-is-in-lhs t))
9231 (js2-parse-primary-expr)))
9232
9233 (defun js2-parse-primary-expr ()
9234 "Parses a literal (leaf) expression of some sort.
9235 Includes complex literals such as functions, object-literals,
9236 array-literals, array comprehensions and regular expressions."
9237 (let ((tt-flagged (js2-next-flagged-token))
9238 pn ; parent node (usually return value)
9239 tt
9240 px-pos ; paren-expr pos
9241 len
9242 flags ; regexp flags
9243 expr)
9244 (setq tt js2-current-token)
9245 (cond
9246 ((= tt js2-FUNCTION)
9247 (js2-parse-function 'FUNCTION_EXPRESSION))
9248 ((= tt js2-LB)
9249 (js2-parse-array-literal))
9250 ((= tt js2-LC)
9251 (js2-parse-object-literal))
9252 ((= tt js2-LET)
9253 (js2-parse-let js2-token-beg))
9254 ((= tt js2-LP)
9255 (setq px-pos js2-token-beg
9256 expr (js2-parse-expr))
9257 (js2-must-match js2-RP "msg.no.paren")
9258 (setq pn (make-js2-paren-node :pos px-pos
9259 :expr expr
9260 :len (- js2-token-end px-pos)))
9261 (js2-node-add-children pn (js2-paren-node-expr pn))
9262 pn)
9263 ((= tt js2-XMLATTR)
9264 (js2-must-have-xml)
9265 (js2-parse-attribute-access))
9266 ((= tt js2-NAME)
9267 (js2-parse-name tt-flagged tt))
9268 ((= tt js2-NUMBER)
9269 (make-js2-number-node))
9270 ((= tt js2-STRING)
9271 (prog1
9272 (make-js2-string-node)
9273 (js2-record-face 'font-lock-string-face)))
9274 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9275 ;; Got / or /= which in this context means a regexp literal
9276 (setq px-pos js2-token-beg)
9277 (js2-read-regexp tt)
9278 (setq flags js2-ts-regexp-flags
9279 js2-ts-regexp-flags nil)
9280 (prog1
9281 (make-js2-regexp-node :pos px-pos
9282 :len (- js2-ts-cursor px-pos)
9283 :value js2-ts-string
9284 :flags flags)
9285 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9286 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9287 ((or (= tt js2-NULL)
9288 (= tt js2-THIS)
9289 (= tt js2-FALSE)
9290 (= tt js2-TRUE))
9291 (make-js2-keyword-node :type tt))
9292 ((= tt js2-RESERVED)
9293 (js2-report-error "msg.reserved.id")
9294 (make-js2-name-node))
9295 ((= tt js2-ERROR)
9296 ;; the scanner or one of its subroutines reported the error.
9297 (make-js2-error-node))
9298 ((= tt js2-EOF)
9299 (setq px-pos (point-at-bol)
9300 len (- js2-ts-cursor px-pos))
9301 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9302 (make-js2-error-node :pos px-pos :len len))
9303 (t
9304 (js2-report-error "msg.syntax")
9305 (make-js2-error-node)))))
9306
9307 (defun js2-parse-name (tt-flagged tt)
9308 (let ((name js2-ts-string)
9309 (name-pos js2-token-beg)
9310 node)
9311 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9312 (= (js2-peek-token) js2-COLON))
9313 (prog1
9314 ;; Do not consume colon, it is used as unwind indicator
9315 ;; to return to statementHelper.
9316 (make-js2-label-node :pos name-pos
9317 :len (- js2-token-end name-pos)
9318 :name name)
9319 (js2-set-face name-pos
9320 js2-token-end
9321 'font-lock-variable-name-face 'record))
9322 ;; Otherwise not a label, just a name. Unfortunately peeking
9323 ;; the next token to check for a colon has biffed js2-token-beg
9324 ;; and js2-token-end. We store the name's bounds in buffer vars
9325 ;; and `js2-create-name-node' uses them.
9326 (js2-save-name-token-data name-pos name)
9327 (setq node (if js2-compiler-xml-available
9328 (js2-parse-property-name nil name 0)
9329 (js2-create-name-node 'check-activation)))
9330 (if js2-highlight-external-variables
9331 (js2-record-name-node node))
9332 node)))
9333
9334 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9335 (js2-add-strict-warning
9336 msg nil
9337 ;; back up from comma to beginning of line or array/objlit
9338 (max (if elems
9339 (js2-node-pos (car elems))
9340 pos)
9341 (save-excursion
9342 (goto-char comma-pos)
9343 (back-to-indentation)
9344 (point)))
9345 comma-pos))
9346
9347 (defun js2-parse-array-literal ()
9348 (let ((pos js2-token-beg)
9349 (end js2-token-end)
9350 (after-lb-or-comma t)
9351 after-comma
9352 tt
9353 elems
9354 pn
9355 (continue t))
9356 (unless js2-is-in-lhs
9357 (js2-push-scope (make-js2-scope))) ; for array comp
9358 (while continue
9359 (setq tt (js2-peek-token))
9360 (cond
9361 ;; comma
9362 ((= tt js2-COMMA)
9363 (js2-consume-token)
9364 (setq after-comma js2-token-end)
9365 (if (not after-lb-or-comma)
9366 (setq after-lb-or-comma t)
9367 (push nil elems)))
9368 ;; end of array
9369 ((or (= tt js2-RB)
9370 (= tt js2-EOF)) ; prevent infinite loop
9371 (if (= tt js2-EOF)
9372 (js2-report-error "msg.no.bracket.arg" nil pos)
9373 (js2-consume-token))
9374 (setq continue nil
9375 end js2-token-end
9376 pn (make-js2-array-node :pos pos
9377 :len (- js2-ts-cursor pos)
9378 :elems (nreverse elems)))
9379 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9380 (when after-comma
9381 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9382 pos elems after-comma)))
9383 ;; destructuring binding
9384 (js2-is-in-lhs
9385 (push (if (or (= tt js2-LC)
9386 (= tt js2-LB)
9387 (= tt js2-NAME))
9388 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9389 (js2-parse-primary-expr-lhs)
9390 ;; invalid pattern
9391 (js2-consume-token)
9392 (js2-report-error "msg.bad.var")
9393 (make-js2-error-node))
9394 elems)
9395 (setq after-lb-or-comma nil
9396 after-comma nil))
9397 ;; array comp
9398 ((and (>= js2-language-version 170)
9399 (= tt js2-FOR) ; check for array comprehension
9400 (not after-lb-or-comma) ; "for" can't follow a comma
9401 elems ; must have at least 1 element
9402 (not (cdr elems))) ; but no 2nd element
9403 (setf continue nil
9404 pn (js2-parse-array-comprehension (car elems) pos)))
9405
9406 ;; another element
9407 (t
9408 (unless after-lb-or-comma
9409 (js2-report-error "msg.no.bracket.arg"))
9410 (push (js2-parse-assign-expr) elems)
9411 (setq after-lb-or-comma nil
9412 after-comma nil))))
9413 (unless js2-is-in-lhs
9414 (js2-pop-scope))
9415 pn))
9416
9417 (defun js2-parse-array-comprehension (expr pos)
9418 "Parse a JavaScript 1.7 Array Comprehension.
9419 EXPR is the first expression after the opening left-bracket.
9420 POS is the beginning of the LB token preceding EXPR.
9421 We should have just parsed the 'for' keyword before calling this function."
9422 (let (loops
9423 loop
9424 first
9425 prev
9426 filter
9427 if-pos
9428 result)
9429 (while (= (js2-peek-token) js2-FOR)
9430 (let ((prev (car loops))) ; rearrange scope chain
9431 (push (setq loop (js2-parse-array-comp-loop)) loops)
9432 (if prev ; each loop is parent scope to the next one
9433 (setf (js2-scope-parent-scope loop) prev)
9434 ; first loop takes expr scope's parent
9435 (setf (js2-scope-parent-scope (setq first loop))
9436 (js2-scope-parent-scope js2-current-scope)))))
9437 ;; set expr scope's parent to the last loop
9438 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9439 (when (= (js2-peek-token) js2-IF)
9440 (js2-consume-token)
9441 (setq if-pos (- js2-token-beg pos) ; relative
9442 filter (js2-parse-condition)))
9443 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9444 (setq result (make-js2-array-comp-node :pos pos
9445 :len (- js2-ts-cursor pos)
9446 :result expr
9447 :loops (nreverse loops)
9448 :filter (car filter)
9449 :lp (js2-relpos (second filter) pos)
9450 :rp (js2-relpos (third filter) pos)
9451 :if-pos if-pos))
9452 (apply #'js2-node-add-children result expr (car filter)
9453 (js2-array-comp-node-loops result))
9454 (setq js2-current-scope first) ; pop to the first loop
9455 result))
9456
9457 (defun js2-parse-array-comp-loop ()
9458 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9459 Last token peeked should be the initial FOR."
9460 (let ((pos js2-token-beg)
9461 (pn (make-js2-array-comp-loop-node))
9462 tt
9463 iter
9464 obj
9465 foreach-p
9466 in-pos
9467 each-pos
9468 lp
9469 rp)
9470 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9471 (js2-push-scope pn)
9472 (unwind-protect
9473 (progn
9474 (when (js2-match-token js2-NAME)
9475 (if (string= js2-ts-string "each")
9476 (progn
9477 (setq foreach-p t
9478 each-pos (- js2-token-beg pos)) ; relative
9479 (js2-record-face 'font-lock-keyword-face))
9480 (js2-report-error "msg.no.paren.for")))
9481 (if (js2-must-match js2-LP "msg.no.paren.for")
9482 (setq lp (- js2-token-beg pos)))
9483 (setq tt (js2-peek-token))
9484 (cond
9485 ((or (= tt js2-LB)
9486 (= tt js2-LC))
9487 ;; handle destructuring assignment
9488 (setq iter (js2-parse-primary-expr-lhs))
9489 (js2-define-destruct-symbols iter js2-LET
9490 'font-lock-variable-name-face t))
9491 ((js2-valid-prop-name-token tt)
9492 (js2-consume-token)
9493 (setq iter (js2-create-name-node)))
9494 (t
9495 (js2-report-error "msg.bad.var")))
9496 ;; Define as a let since we want the scope of the variable to
9497 ;; be restricted to the array comprehension
9498 (if (js2-name-node-p iter)
9499 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9500 (if (js2-must-match js2-IN "msg.in.after.for.name")
9501 (setq in-pos (- js2-token-beg pos)))
9502 (setq obj (js2-parse-expr))
9503 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9504 (setq rp (- js2-token-beg pos)))
9505 (setf (js2-node-pos pn) pos
9506 (js2-node-len pn) (- js2-ts-cursor pos)
9507 (js2-array-comp-loop-node-iterator pn) iter
9508 (js2-array-comp-loop-node-object pn) obj
9509 (js2-array-comp-loop-node-in-pos pn) in-pos
9510 (js2-array-comp-loop-node-each-pos pn) each-pos
9511 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9512 (js2-array-comp-loop-node-lp pn) lp
9513 (js2-array-comp-loop-node-rp pn) rp)
9514 (js2-node-add-children pn iter obj))
9515 (js2-pop-scope))
9516 pn))
9517
9518 (defun js2-parse-object-literal ()
9519 (let ((pos js2-token-beg)
9520 tt
9521 elems
9522 result
9523 after-comma
9524 (continue t))
9525 (while continue
9526 (setq tt (js2-peek-token))
9527 (cond
9528 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9529 ((or (js2-valid-prop-name-token tt)
9530 (= tt js2-STRING))
9531 (setq after-comma nil
9532 result (js2-parse-named-prop tt))
9533 (if (and (null result)
9534 (not js2-recover-from-parse-errors))
9535 (setq continue nil)
9536 (push result elems)))
9537 ;; {12: x} or {10.7: x}
9538 ((= tt js2-NUMBER)
9539 (js2-consume-token)
9540 (setq after-comma nil)
9541 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9542 ;; trailing comma
9543 ((= tt js2-RC)
9544 (setq continue nil)
9545 (if after-comma
9546 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9547 pos elems after-comma)))
9548 (t
9549 (js2-report-error "msg.bad.prop")
9550 (unless js2-recover-from-parse-errors
9551 (setq continue nil)))) ; end switch
9552 (if (js2-match-token js2-COMMA)
9553 (setq after-comma js2-token-end)
9554 (setq continue nil))) ; end loop
9555 (js2-must-match js2-RC "msg.no.brace.prop")
9556 (setq result (make-js2-object-node :pos pos
9557 :len (- js2-ts-cursor pos)
9558 :elems (nreverse elems)))
9559 (apply #'js2-node-add-children result (js2-object-node-elems result))
9560 result))
9561
9562 (defun js2-parse-named-prop (tt)
9563 "Parse a name, string, or getter/setter object property.
9564 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9565 (js2-consume-token)
9566 (let ((string-prop (and (= tt js2-STRING)
9567 (make-js2-string-node)))
9568 expr
9569 (ppos js2-token-beg)
9570 (pend js2-token-end)
9571 (name (js2-create-name-node))
9572 (prop js2-ts-string))
9573 (cond
9574 ;; getter/setter prop
9575 ((and (= tt js2-NAME)
9576 (= (js2-peek-token) js2-NAME)
9577 (or (string= prop "get")
9578 (string= prop "set")))
9579 (js2-consume-token)
9580 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9581 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9582 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9583 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9584 ;; abbreviated destructuring bind e.g., {a, b} = c;
9585 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9586 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9587 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9588 ;; assignment but it's difficult because it requires looking ahead of expression.
9589 ((and js2-is-in-lhs
9590 (= tt js2-NAME)
9591 (let ((ctk (js2-peek-token)))
9592 (or (= ctk js2-COMMA)
9593 (= ctk js2-RC)
9594 (js2-valid-prop-name-token ctk))))
9595 name)
9596 ;; regular prop
9597 (t
9598 (prog1
9599 (setq expr (js2-parse-plain-property (or string-prop name)))
9600 (js2-set-face ppos pend
9601 (if (js2-function-node-p
9602 (js2-object-prop-node-right expr))
9603 'font-lock-function-name-face
9604 'font-lock-variable-name-face)
9605 'record))))))
9606
9607 (defun js2-parse-plain-property (prop)
9608 "Parse a non-getter/setter property in an object literal.
9609 PROP is the node representing the property: a number, name or string."
9610 (js2-must-match js2-COLON "msg.no.colon.prop")
9611 (let* ((pos (js2-node-pos prop))
9612 (colon (- js2-token-beg pos))
9613 (expr (js2-parse-assign-expr))
9614 (result (make-js2-object-prop-node
9615 :pos pos
9616 ;; don't include last consumed token in length
9617 :len (- (+ (js2-node-pos expr)
9618 (js2-node-len expr))
9619 pos)
9620 :left prop
9621 :right expr
9622 :op-pos colon)))
9623 (js2-node-add-children result prop expr)
9624 result))
9625
9626 (defun js2-parse-getter-setter-prop (pos prop get-p)
9627 "Parse getter or setter property in an object literal.
9628 JavaScript syntax is:
9629
9630 { get foo() {...}, set foo(x) {...} }
9631
9632 and expression closure style is also supported
9633
9634 { get foo() x, set foo(x) _x = x }
9635
9636 POS is the start position of the `get' or `set' keyword.
9637 PROP is the `js2-name-node' representing the property name.
9638 GET-P is non-nil if the keyword was `get'."
9639 (let ((type (if get-p js2-GET js2-SET))
9640 result
9641 end
9642 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9643 ;; it has to be an anonymous function, as we already parsed the name
9644 (if (/= (js2-node-type fn) js2-FUNCTION)
9645 (js2-report-error "msg.bad.prop")
9646 (if (plusp (length (js2-function-name fn)))
9647 (js2-report-error "msg.bad.prop")))
9648 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9649 (setq end (js2-node-end fn)
9650 result (make-js2-getter-setter-node :type type
9651 :pos pos
9652 :len (- end pos)
9653 :left prop
9654 :right fn))
9655 (js2-node-add-children result prop fn)
9656 result))
9657
9658 (defun js2-create-name-node (&optional check-activation-p token)
9659 "Create a name node using the token info from last scanned name.
9660 In some cases we need to either synthesize a name node, or we lost
9661 the name token information by peeking. If the TOKEN parameter is
9662 not `js2-NAME', then we use the token info saved in instance vars."
9663 (let ((beg js2-token-beg)
9664 (s js2-ts-string)
9665 name)
9666 (when (/= js2-current-token js2-NAME)
9667 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9668 s js2-prev-name-token-string
9669 js2-prev-name-token-start nil
9670 js2-prev-name-token-string nil))
9671 (setq name (make-js2-name-node :pos beg
9672 :name s
9673 :len (length s)))
9674 (if check-activation-p
9675 (js2-check-activation-name s (or token js2-NAME)))
9676 name))
9677
9678 ;;; Indentation support
9679
9680 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9681 ;; Karl cleverly deduces that the desired indentation level is often a
9682 ;; function of paren/bracket/brace nesting depth, which can be determined
9683 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9684 ;; then does some equally clever checks to see if we're in the context of a
9685 ;; substatement of a possibly braceless statement keyword such as if, while,
9686 ;; or finally. This approach yields pretty good results.
9687
9688 ;; The indenter is often "wrong", however, and needs to be overridden.
9689 ;; The right long-term solution is probably to emulate (or integrate
9690 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9691 ;; parse tree from `js2-parse' is present, which is not true at the
9692 ;; moment the user is typing, computing indentation is still thousands
9693 ;; of lines of code to handle every possible syntactic edge case.
9694
9695 ;; In the meantime, the compromise solution is that we offer a "bounce
9696 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9697 ;; current line indent among various likely guess points. This approach
9698 ;; is far from perfect, but should at least make it slightly easier to
9699 ;; move the line towards its desired indentation when manually
9700 ;; overriding Karl's heuristic nesting guesser.
9701
9702 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9703 ;; extensions such as `let' and Array comprehensions. Major kudos to
9704 ;; Karl for coming up with the initial approach, which packs a lot of
9705 ;; punch for so little code.
9706
9707 (defconst js-possibly-braceless-keyword-re
9708 (regexp-opt
9709 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9710 'words)
9711 "Regular expression matching keywords that are optionally
9712 followed by an opening brace.")
9713
9714 (defconst js-possibly-braceless-keywords-re
9715 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9716 "Regular expression which matches the keywords which are consist of more than 2 words
9717 like 'if else' and 'for each', and optionally followed by an opening brace.")
9718
9719 (defconst js-indent-operator-re
9720 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9721 (regexp-opt '("in" "instanceof") 'words))
9722 "Regular expression matching operators that affect indentation
9723 of continued expressions.")
9724
9725 ;; This function has horrible results if you're typing an array
9726 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9727 ;; in conjunction with electric-indent, so just disabling it.
9728 (defsubst js2-code-at-bol-p ()
9729 "Return t if the first character on line is non-whitespace."
9730 nil)
9731
9732 (defun js2-insert-and-indent (key)
9733 "Run command bound to key and indent current line. Runs the command
9734 bound to KEY in the global keymap and indents the current line."
9735 (interactive (list (this-command-keys)))
9736 (let ((cmd (lookup-key (current-global-map) key)))
9737 (if (commandp cmd)
9738 (call-interactively cmd)))
9739 ;; don't do the electric keys inside comments or strings,
9740 ;; and don't do bounce-indent with them.
9741 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9742 (js2-bounce-indent-p (js2-code-at-bol-p)))
9743 (unless (or (nth 3 parse-state)
9744 (nth 4 parse-state))
9745 (indent-according-to-mode))))
9746
9747 (defun js-re-search-forward-inner (regexp &optional bound count)
9748 "Auxiliary function for `js-re-search-forward'."
9749 (let ((parse)
9750 (saved-point (point-min)))
9751 (while (> count 0)
9752 (re-search-forward regexp bound)
9753 (setq parse (parse-partial-sexp saved-point (point)))
9754 (cond ((nth 3 parse)
9755 (re-search-forward
9756 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9757 (save-excursion (end-of-line) (point)) t))
9758 ((nth 7 parse)
9759 (forward-line))
9760 ((or (nth 4 parse)
9761 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9762 (re-search-forward "\\*/"))
9763 (t
9764 (setq count (1- count))))
9765 (setq saved-point (point))))
9766 (point))
9767
9768 (defun js-re-search-forward (regexp &optional bound noerror count)
9769 "Search forward but ignore strings and comments. Invokes
9770 `re-search-forward' but treats the buffer as if strings and
9771 comments have been removed."
9772 (let ((saved-point (point))
9773 (search-expr
9774 (cond ((null count)
9775 '(js-re-search-forward-inner regexp bound 1))
9776 ((< count 0)
9777 '(js-re-search-backward-inner regexp bound (- count)))
9778 ((> count 0)
9779 '(js-re-search-forward-inner regexp bound count)))))
9780 (condition-case err
9781 (eval search-expr)
9782 (search-failed
9783 (goto-char saved-point)
9784 (unless noerror
9785 (error (error-message-string err)))))))
9786
9787 (defun js-re-search-backward-inner (regexp &optional bound count)
9788 "Auxiliary function for `js-re-search-backward'."
9789 (let ((parse)
9790 (saved-point (point-min)))
9791 (while (> count 0)
9792 (re-search-backward regexp bound)
9793 (setq parse (parse-partial-sexp saved-point (point)))
9794 (cond ((nth 3 parse)
9795 (re-search-backward
9796 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9797 (save-excursion (beginning-of-line) (point)) t))
9798 ((nth 7 parse)
9799 (goto-char (nth 8 parse)))
9800 ((or (nth 4 parse)
9801 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9802 (re-search-backward "/\\*"))
9803 (t
9804 (setq count (1- count))))))
9805 (point))
9806
9807 (defun js-re-search-backward (regexp &optional bound noerror count)
9808 "Search backward but ignore strings and comments. Invokes
9809 `re-search-backward' but treats the buffer as if strings and
9810 comments have been removed."
9811 (let ((saved-point (point))
9812 (search-expr
9813 (cond ((null count)
9814 '(js-re-search-backward-inner regexp bound 1))
9815 ((< count 0)
9816 '(js-re-search-forward-inner regexp bound (- count)))
9817 ((> count 0)
9818 '(js-re-search-backward-inner regexp bound count)))))
9819 (condition-case err
9820 (eval search-expr)
9821 (search-failed
9822 (goto-char saved-point)
9823 (unless noerror
9824 (error (error-message-string err)))))))
9825
9826 (defun js-looking-at-operator-p ()
9827 "Return non-nil if text after point is an operator (that is not
9828 a comma)."
9829 (save-match-data
9830 (and (looking-at js-indent-operator-re)
9831 (or (not (looking-at ":"))
9832 (save-excursion
9833 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9834 (looking-at "?")))))))
9835
9836 (defun js-continued-expression-p ()
9837 "Returns non-nil if the current line continues an expression."
9838 (save-excursion
9839 (back-to-indentation)
9840 (or (js-looking-at-operator-p)
9841 ;; comment
9842 (and (js-re-search-backward "\n" nil t)
9843 (progn
9844 (skip-chars-backward " \t")
9845 (backward-char)
9846 (and (js-looking-at-operator-p)
9847 (and (progn (backward-char)
9848 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9849
9850 (defun js-end-of-do-while-loop-p ()
9851 "Returns non-nil if word after point is `while' of a do-while
9852 statement, else returns nil. A braceless do-while statement
9853 spanning several lines requires that the start of the loop is
9854 indented to the same column as the current line."
9855 (interactive)
9856 (save-excursion
9857 (save-match-data
9858 (when (looking-at "\\s-*\\<while\\>")
9859 (if (save-excursion
9860 (skip-chars-backward "[ \t\n]*}")
9861 (looking-at "[ \t\n]*}"))
9862 (save-excursion
9863 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9864 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9865 (or (looking-at "\\<do\\>")
9866 (let ((saved-indent (current-indentation)))
9867 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9868 (/= (current-indentation) saved-indent)))
9869 (and (looking-at "[ \t]*\\<do\\>")
9870 (not (js-re-search-forward
9871 "\\<while\\>" (point-at-eol) t))
9872 (= (current-indentation) saved-indent)))))))))
9873
9874 (defun js-get-multiline-declaration-offset ()
9875 "Returns offset (> 0) if the current line is part of
9876 multi-line variable declaration like below example, and
9877 returns 0 otherwise.
9878
9879 var a = 10,
9880 b = 20,
9881 c = 30;
9882
9883 "
9884 (let* ((node (js2-node-at-point))
9885 (pnode (and node (js2-node-parent node)))
9886 (pnode-type (and pnode (js2-node-type pnode))))
9887 (if (and node
9888 (= js2-NAME (js2-node-type node))
9889 (or
9890 (= js2-VAR pnode-type)
9891 (= js2-LET pnode-type)
9892 (= js2-CONST pnode-type)))
9893 (if (= js2-CONST pnode-type)
9894 6
9895 4)
9896 0)))
9897
9898 (defun js-ctrl-statement-indentation ()
9899 "Returns the proper indentation of the current line if it
9900 starts the body of a control statement without braces, else
9901 returns nil."
9902 (let (forward-sexp-function) ; temporarily unbind it
9903 (save-excursion
9904 (back-to-indentation)
9905 (when (save-excursion
9906 (and (not (js2-same-line (point-min)))
9907 (not (looking-at "{"))
9908 (js-re-search-backward "[[:graph:]]" nil t)
9909 (not (looking-at "[{([]"))
9910 (progn
9911 (forward-char)
9912 ;; scan-sexps sometimes throws an error
9913 (ignore-errors (backward-sexp))
9914 (when (looking-at "(") (backward-word 1))
9915 (and (save-excursion
9916 (skip-chars-backward " \t}" (point-at-bol))
9917 (or (bolp)
9918 (and (backward-word 1)
9919 (skip-chars-backward " \t}" (point-at-bol))
9920 (bolp)
9921 (looking-at js-possibly-braceless-keywords-re))))
9922 (looking-at js-possibly-braceless-keyword-re)
9923 (not (js-end-of-do-while-loop-p))))))
9924 (save-excursion
9925 (goto-char (match-beginning 0))
9926 (+ (current-indentation) js2-basic-offset))))))
9927
9928 (defun js2-indent-in-array-comp (parse-status)
9929 "Return non-nil if we think we're in an array comprehension.
9930 In particular, return the buffer position of the first `for' kwd."
9931 (let ((end (point)))
9932 (when (nth 1 parse-status)
9933 (save-excursion
9934 (goto-char (nth 1 parse-status))
9935 (when (looking-at "\\[")
9936 (forward-char 1)
9937 (js2-forward-sws)
9938 (if (looking-at "[[{]")
9939 (let (forward-sexp-function) ; use lisp version
9940 (forward-sexp) ; skip destructuring form
9941 (js2-forward-sws)
9942 (if (and (/= (char-after) ?,) ; regular array
9943 (looking-at "for"))
9944 (match-beginning 0)))
9945 ;; to skip arbitrary expressions we need the parser,
9946 ;; so we'll just guess at it.
9947 (if (re-search-forward "[^,]* \\(for\\) " end t)
9948 (match-beginning 1))))))))
9949
9950 (defun js2-array-comp-indentation (parse-status for-kwd)
9951 (if (js2-same-line for-kwd)
9952 ;; first continuation line
9953 (save-excursion
9954 (goto-char (nth 1 parse-status))
9955 (forward-char 1)
9956 (skip-chars-forward " \t")
9957 (current-column))
9958 (save-excursion
9959 (goto-char for-kwd)
9960 (current-column))))
9961
9962 (defun js-proper-indentation (parse-status)
9963 "Return the proper indentation for the current line."
9964 (save-excursion
9965 (back-to-indentation)
9966 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9967 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9968 (continued-expr-p (js-continued-expression-p))
9969 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9970 (js-get-multiline-declaration-offset))
9971 0))
9972 (bracket (nth 1 parse-status))
9973 beg)
9974 (cond
9975 ;; indent array comprehension continuation lines specially
9976 ((and bracket
9977 (not (js2-same-line bracket))
9978 (setq beg (js2-indent-in-array-comp parse-status))
9979 (>= (point) (save-excursion
9980 (goto-char beg)
9981 (point-at-bol)))) ; at or after first loop?
9982 (js2-array-comp-indentation parse-status beg))
9983
9984 (ctrl-stmt-indent)
9985
9986 (bracket
9987 (goto-char bracket)
9988 (cond
9989 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9990 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9991 (when (save-excursion (skip-chars-backward " \t)")
9992 (looking-at ")"))
9993 (backward-list))
9994 (if (and (nth 1 p)
9995 (not js2-consistent-level-indent-inner-bracket-p))
9996 (progn (goto-char (1+ (nth 1 p)))
9997 (skip-chars-forward " \t"))
9998 (back-to-indentation))
9999 (cond (same-indent-p
10000 (current-column))
10001 (continued-expr-p
10002 (+ (current-column) (* 2 js2-basic-offset)))
10003 ((> multiline-declaration-offset 0)
10004 (+ (current-column) js2-basic-offset multiline-declaration-offset))
10005 (t
10006 (+ (current-column) js2-basic-offset)))))
10007 (t
10008 (unless same-indent-p
10009 (forward-char)
10010 (skip-chars-forward " \t"))
10011 (current-column))))
10012
10013 (continued-expr-p js2-basic-offset)
10014
10015 ((> multiline-declaration-offset 0)
10016 (+ multiline-declaration-offset))
10017
10018 (t 0)))))
10019
10020 (defun js2-lineup-comment (parse-status)
10021 "Indent a multi-line block comment continuation line."
10022 (let* ((beg (nth 8 parse-status))
10023 (first-line (js2-same-line beg))
10024 (offset (save-excursion
10025 (goto-char beg)
10026 (if (looking-at "/\\*")
10027 (+ 1 (current-column))
10028 0))))
10029 (unless first-line
10030 (indent-line-to offset))))
10031
10032 (defun js2-backward-sws ()
10033 "Move backward through whitespace and comments."
10034 (interactive)
10035 (while (forward-comment -1)))
10036
10037 (defun js2-forward-sws ()
10038 "Move forward through whitespace and comments."
10039 (interactive)
10040 (while (forward-comment 1)))
10041
10042 (defsubst js2-current-indent (&optional pos)
10043 "Return column of indentation on current line.
10044 If POS is non-nil, go to that point and return indentation for that line."
10045 (save-excursion
10046 (if pos
10047 (goto-char pos))
10048 (back-to-indentation)
10049 (current-column)))
10050
10051 (defsubst js2-arglist-close ()
10052 "Return non-nil if we're on a line beginning with a close-paren/brace."
10053 (save-match-data
10054 (save-excursion
10055 (goto-char (point-at-bol))
10056 (js2-forward-sws)
10057 (looking-at "[])}]"))))
10058
10059 (defsubst js2-indent-looks-like-label-p ()
10060 (goto-char (point-at-bol))
10061 (js2-forward-sws)
10062 (looking-at (concat js2-mode-identifier-re ":")))
10063
10064 (defun js2-indent-in-objlit-p (parse-status)
10065 "Return non-nil if this looks like an object-literal entry."
10066 (let ((start (nth 1 parse-status)))
10067 (and
10068 start
10069 (save-excursion
10070 (and (zerop (forward-line -1))
10071 (not (< (point) start)) ; crossed a {} boundary
10072 (js2-indent-looks-like-label-p)))
10073 (save-excursion
10074 (js2-indent-looks-like-label-p)))))
10075
10076 ;; if prev line looks like foobar({ then we're passing an object
10077 ;; literal to a function call, and people pretty much always want to
10078 ;; de-dent back to the previous line, so move the 'basic-offset'
10079 ;; position to the front.
10080 (defsubst js2-indent-objlit-arg-p (parse-status)
10081 (save-excursion
10082 (back-to-indentation)
10083 (js2-backward-sws)
10084 (and (eq (1- (point)) (nth 1 parse-status))
10085 (eq (char-before) ?{)
10086 (progn
10087 (forward-char -1)
10088 (skip-chars-backward " \t")
10089 (eq (char-before) ?\()))))
10090
10091 (defsubst js2-indent-case-block-p ()
10092 (save-excursion
10093 (back-to-indentation)
10094 (js2-backward-sws)
10095 (goto-char (point-at-bol))
10096 (skip-chars-forward " \t")
10097 (save-match-data
10098 (looking-at "case\\s-.+:"))))
10099
10100 (defsubst js2-syntax-bol ()
10101 "Return the point at the first non-whitespace char on the line.
10102 Returns `point-at-bol' if the line is empty."
10103 (save-excursion
10104 (beginning-of-line)
10105 (skip-chars-forward " \t")
10106 (point)))
10107
10108 (defun js2-bounce-indent (normal-col parse-status)
10109 "Cycle among alternate computed indentation positions.
10110 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10111 of the buffer to the current point. NORMAL-COL is the indentation
10112 column computed by the heuristic guesser based on current paren,
10113 bracket, brace and statement nesting."
10114 (let ((cur-indent (js2-current-indent))
10115 (old-buffer-undo-list buffer-undo-list)
10116 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10117 (current-line (save-excursion
10118 (forward-line 0) ; move to bol
10119 (1+ (count-lines (point-min) (point)))))
10120 positions
10121 pos
10122 anchor
10123 arglist-cont
10124 same-indent
10125 prev-line-col
10126 basic-offset
10127 computed-pos)
10128 ;; temporarily don't record undo info, if user requested this
10129 (if js2-mode-indent-inhibit-undo
10130 (setq buffer-undo-list t))
10131 (unwind-protect
10132 (progn
10133 ;; first likely point: indent from beginning of previous code line
10134 (push (setq basic-offset
10135 (+ (save-excursion
10136 (back-to-indentation)
10137 (js2-backward-sws)
10138 (back-to-indentation)
10139 (setq prev-line-col (current-column)))
10140 js2-basic-offset))
10141 positions)
10142
10143 ;; (first + epsilon) likely point: indent 2x from beginning of
10144 ;; previous code line. Some companies like this approach. Ahem.
10145 ;; Seriously, though -- 4-space indent for expression continuation
10146 ;; lines isn't a bad idea. We should eventually implement it
10147 ;; that way.
10148 (push (setq basic-offset
10149 (+ (save-excursion
10150 (back-to-indentation)
10151 (js2-backward-sws)
10152 (back-to-indentation)
10153 (setq prev-line-col (current-column)))
10154 (* 2 js2-basic-offset)))
10155 positions)
10156
10157 ;; second likely point: indent from assign-expr RHS. This
10158 ;; is just a crude guess based on finding " = " on the previous
10159 ;; line containing actual code.
10160 (setq pos (save-excursion
10161 (save-match-data
10162 (forward-line -1)
10163 (goto-char (point-at-bol))
10164 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10165 (point-at-eol) t)
10166 (goto-char (match-end 1))
10167 (skip-chars-forward " \t\r\n")
10168 (current-column)))))
10169 (when pos
10170 (incf pos js2-basic-offset)
10171 (unless (member pos positions)
10172 (push pos positions)))
10173
10174 ;; third likely point: same indent as previous line of code.
10175 ;; Make it the first likely point if we're not on an
10176 ;; arglist-close line and previous line ends in a comma, or
10177 ;; both this line and prev line look like object-literal
10178 ;; elements.
10179 (setq pos (save-excursion
10180 (goto-char (point-at-bol))
10181 (js2-backward-sws)
10182 (back-to-indentation)
10183 (prog1
10184 (current-column)
10185 ;; while we're here, look for trailing comma
10186 (if (save-excursion
10187 (goto-char (point-at-eol))
10188 (js2-backward-sws)
10189 (eq (char-before) ?,))
10190 (setq arglist-cont (1- (point)))))))
10191 (when pos
10192 (if (and (or arglist-cont
10193 (js2-indent-in-objlit-p parse-status))
10194 (not (js2-arglist-close)))
10195 (setq same-indent pos))
10196 (unless (member pos positions)
10197 (push pos positions)))
10198
10199 ;; fourth likely point: first preceding code with less indentation
10200 ;; than the immediately preceding code line.
10201 (setq pos (save-excursion
10202 (js2-backward-sws)
10203 (back-to-indentation)
10204 (setq anchor (current-column))
10205 (while (and (zerop (forward-line -1))
10206 (>= (progn
10207 (back-to-indentation)
10208 (current-column))
10209 anchor)))
10210 (setq pos (current-column))))
10211 (unless (member pos positions)
10212 (push pos positions))
10213
10214 ;; put nesting-heuristic position first in list, sort rest
10215 (setq positions (nreverse (sort positions '<)))
10216 (setq positions (cons normal-col (delete normal-col positions)))
10217
10218 ;; comma-list continuation lines: prev line indent takes precedence
10219 (if same-indent
10220 (setq positions
10221 (cons same-indent
10222 (sort (delete same-indent positions) '<))))
10223
10224 ;; common special cases where we want to indent in from previous line
10225 (if (or (js2-indent-case-block-p)
10226 (js2-indent-objlit-arg-p parse-status))
10227 (setq positions
10228 (cons basic-offset
10229 (delete basic-offset positions))))
10230
10231 ;; record whether we're already sitting on one of the alternatives
10232 (setq pos (member cur-indent positions))
10233 (cond
10234 ;; case 0: we're one one of the alternatives and this is the
10235 ;; first time they've pressed TAB on this line (best-guess).
10236 ((and js2-mode-indent-ignore-first-tab
10237 pos
10238 ;; first time pressing TAB on this line?
10239 (not (eq js2-mode-last-indented-line current-line)))
10240 ;; do nothing
10241 (setq computed-pos nil))
10242 ;; case 1: only one computed position => use it
10243 ((null (cdr positions))
10244 (setq computed-pos 0))
10245 ;; case 2: not on any of the computed spots => use main spot
10246 ((not pos)
10247 (setq computed-pos 0))
10248 ;; case 3: on last position: cycle to first position
10249 ((null (cdr pos))
10250 (setq computed-pos 0))
10251 ;; case 4: on intermediate position: cycle to next position
10252 (t
10253 (setq computed-pos (js2-position (second pos) positions))))
10254
10255 ;; see if any hooks want to indent; otherwise we do it
10256 (loop with result = nil
10257 for hook in js2-indent-hook
10258 while (null result)
10259 do
10260 (setq result (funcall hook positions computed-pos))
10261 finally do
10262 (unless (or result (null computed-pos))
10263 (indent-line-to (nth computed-pos positions)))))
10264
10265 ;; finally
10266 (if js2-mode-indent-inhibit-undo
10267 (setq buffer-undo-list old-buffer-undo-list))
10268 ;; see commentary for `js2-mode-last-indented-line'
10269 (setq js2-mode-last-indented-line current-line))))
10270
10271 (defsubst js2-1-line-comment-continuation-p ()
10272 "Return t if we're in a 1-line comment continuation.
10273 If so, we don't ever want to use bounce-indent."
10274 (save-excursion
10275 (save-match-data
10276 (and (progn
10277 (forward-line 0)
10278 (looking-at "\\s-*//"))
10279 (progn
10280 (forward-line -1)
10281 (forward-line 0)
10282 (when (looking-at "\\s-*$")
10283 (js2-backward-sws)
10284 (forward-line 0))
10285 (looking-at "\\s-*//"))))))
10286
10287 (defun js2-indent-line ()
10288 "Indent the current line as JavaScript source text."
10289 (interactive)
10290 (when js2-use-ast-for-indentation-p
10291 (js2-reparse))
10292 (let (parse-status
10293 current-indent
10294 offset
10295 indent-col
10296 moved
10297 ;; don't whine about errors/warnings when we're indenting.
10298 ;; This has to be set before calling parse-partial-sexp below.
10299 (inhibit-point-motion-hooks t))
10300 (setq parse-status (save-excursion
10301 (parse-partial-sexp (point-min)
10302 (point-at-bol)))
10303 offset (- (point) (save-excursion
10304 (back-to-indentation)
10305 (setq current-indent (current-column))
10306 (point))))
10307 (js2-with-underscore-as-word-syntax
10308 (if (nth 4 parse-status)
10309 (js2-lineup-comment parse-status)
10310 (setq indent-col (js-proper-indentation parse-status))
10311 ;; see comments below about js2-mode-last-indented-line
10312 (when
10313 (cond
10314 ;; bounce-indenting is disabled during electric-key indent.
10315 ;; It doesn't work well on first line of buffer.
10316 ((and js2-bounce-indent-p
10317 (not (js2-same-line (point-min)))
10318 (not (js2-1-line-comment-continuation-p)))
10319 (js2-bounce-indent indent-col parse-status)
10320 (setq moved t))
10321 ;; just indent to the guesser's likely spot
10322 ((/= current-indent indent-col)
10323 (indent-line-to indent-col)
10324 (setq moved t)))
10325 (when (and moved (plusp offset))
10326 (forward-char offset)))))))
10327
10328 (defun js2-indent-region (start end)
10329 "Indent the region, but don't use bounce indenting."
10330 (let ((js2-bounce-indent-p nil)
10331 (indent-region-function nil))
10332 (indent-region start end nil))) ; nil for byte-compiler
10333
10334 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10335
10336 ;;;###autoload
10337 (defun js2-mode ()
10338 "Major mode for editing JavaScript code."
10339 (interactive)
10340 (kill-all-local-variables)
10341 (set-syntax-table js2-mode-syntax-table)
10342 (use-local-map js2-mode-map)
10343 (setq major-mode 'js2-mode
10344 mode-name "JavaScript-IDE"
10345 comment-start "//" ; used by comment-region; don't change it
10346 comment-end "")
10347 (setq local-abbrev-table js2-mode-abbrev-table)
10348 (set (make-local-variable 'max-lisp-eval-depth)
10349 (max max-lisp-eval-depth 3000))
10350 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10351 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10352
10353 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10354 ;; on most platforms other than the one I originally wrote it on. So it's
10355 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10356 ;; with our binding of the RET key inside comments: short lines stay short.
10357 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10358
10359 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10360 (set (make-local-variable 'next-error-function) #'js2-next-error)
10361 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10362 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10363 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10364 ;; for characters inside regexp literals.
10365 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10366 ;; this is necessary to make `show-paren-function' work properly
10367 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10368 ;; needed for M-x rgrep, among other things
10369 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10370
10371 ;; some variables needed by cc-engine for paragraph-fill, etc.
10372 (setq c-buffer-is-cc-mode t
10373 c-comment-prefix-regexp js2-comment-prefix-regexp
10374 c-comment-start-regexp "/[*/]\\|\\s|"
10375 c-paragraph-start js2-paragraph-start
10376 c-paragraph-separate "$"
10377 comment-start-skip js2-comment-start-skip
10378 c-syntactic-ws-start js2-syntactic-ws-start
10379 c-syntactic-ws-end js2-syntactic-ws-end
10380 c-syntactic-eol js2-syntactic-eol)
10381
10382 (setq js2-default-externs
10383 (append js2-ecma-262-externs
10384 (if js2-include-browser-externs
10385 js2-browser-externs)
10386 (if js2-include-gears-externs
10387 js2-gears-externs)
10388 (if js2-include-rhino-externs
10389 js2-rhino-externs)))
10390
10391 ;; We do our own syntax highlighting based on the parse tree.
10392 ;; However, we want minor modes that add keywords to highlight properly
10393 ;; (examples: doxymacs, column-marker). We do this by not letting
10394 ;; font-lock unfontify anything, and telling it to fontify after we
10395 ;; re-parse and re-highlight the buffer. (We currently don't do any
10396 ;; work with regions other than the whole buffer.)
10397 (dolist (var '(font-lock-unfontify-buffer-function
10398 font-lock-unfontify-region-function))
10399 (set (make-local-variable var) (lambda (&rest args) t)))
10400
10401 ;; Don't let font-lock do syntactic (string/comment) fontification.
10402 (set (make-local-variable #'font-lock-syntactic-face-function)
10403 (lambda (state) nil))
10404
10405 ;; Experiment: make reparse-delay longer for longer files.
10406 (if (plusp js2-dynamic-idle-timer-adjust)
10407 (setq js2-idle-timer-delay
10408 (* js2-idle-timer-delay
10409 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10410
10411 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10412 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10413 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10414 (imenu-add-to-menubar (concat "IM-" mode-name))
10415 (when js2-mirror-mode
10416 (js2-enter-mirror-mode))
10417 (add-to-invisibility-spec '(js2-outline . t))
10418 (set (make-local-variable 'line-move-ignore-invisible) t)
10419 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10420 (setq js2-mode-functions-hidden nil
10421 js2-mode-comments-hidden nil
10422 js2-mode-buffer-dirty-p t
10423 js2-mode-parsing nil)
10424 (js2-reparse)
10425 (run-hooks 'js2-mode-hook))
10426
10427 (defun js2-mode-exit ()
10428 "Exit `js2-mode' and clean up."
10429 (interactive)
10430 (when js2-mode-node-overlay
10431 (delete-overlay js2-mode-node-overlay)
10432 (setq js2-mode-node-overlay nil))
10433 (js2-remove-overlays)
10434 (setq js2-mode-ast nil)
10435 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10436 (remove-from-invisibility-spec '(js2-outline . t))
10437 (js2-mode-show-all)
10438 (js2-with-unmodifying-text-property-changes
10439 (js2-clear-face (point-min) (point-max))))
10440
10441 (defun js2-before-save ()
10442 "Clean up whitespace before saving file.
10443 You can disable this by customizing `js2-cleanup-whitespace'."
10444 (when js2-cleanup-whitespace
10445 (let ((col (current-column)))
10446 (delete-trailing-whitespace)
10447 ;; don't change trailing whitespace on current line
10448 (unless (eq (current-column) col)
10449 (indent-to col)))))
10450
10451 (defsubst js2-mode-reset-timer ()
10452 "Cancel any existing parse timer and schedule a new one."
10453 (if js2-mode-parse-timer
10454 (cancel-timer js2-mode-parse-timer))
10455 (setq js2-mode-parsing nil)
10456 (setq js2-mode-parse-timer
10457 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10458
10459 (defun js2-mode-edit (beg end len)
10460 "Schedule a new parse after buffer is edited.
10461 Buffer edit spans from BEG to END and is of length LEN.
10462 Also clears the `js2-magic' bit on autoinserted parens/brackets
10463 if the edit occurred on a line different from the magic paren."
10464 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10465 (line (if magic-pos (line-number-at-pos magic-pos))))
10466 (and line
10467 (or (/= (line-number-at-pos beg) line)
10468 (and (> 0 len)
10469 (/= (line-number-at-pos end) line)))
10470 (js2-mode-mundanify-parens)))
10471 (setq js2-mode-buffer-dirty-p t)
10472 (js2-mode-hide-overlay)
10473 (js2-mode-reset-timer))
10474
10475 (defun js2-mode-run-font-lock ()
10476 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10477 This is intended to allow modes that install their own font-lock keywords
10478 to work with js2-mode. In practice it never seems to work for long.
10479 Hopefully the Emacs maintainers can help figure out a way to make it work."
10480 (when (and (boundp 'font-lock-keywords)
10481 font-lock-keywords
10482 (boundp 'font-lock-mode)
10483 font-lock-mode)
10484 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10485 ;; play nicely with js2-mode. They go out of their way to fail to
10486 ;; provide any option for saying "look, fontify the farging buffer
10487 ;; with just the keywords already". Argh.
10488 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10489 (let (font-lock-verbose)
10490 (font-lock-fontify-buffer))))
10491
10492 (defun js2-reparse (&optional force)
10493 "Re-parse current buffer after user finishes some data entry.
10494 If we get any user input while parsing, including cursor motion,
10495 we discard the parse and reschedule it. If FORCE is nil, then the
10496 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10497 (let (time
10498 interrupted-p
10499 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10500 (unless js2-mode-parsing
10501 (setq js2-mode-parsing t)
10502 (unwind-protect
10503 (when (or js2-mode-buffer-dirty-p force)
10504 (js2-remove-overlays)
10505 (js2-with-unmodifying-text-property-changes
10506 (remove-text-properties (point-min) (point-max) '(syntax-table))
10507 (setq js2-mode-buffer-dirty-p nil
10508 js2-mode-fontifications nil
10509 js2-mode-deferred-properties nil
10510 js2-additional-externs nil)
10511 (if js2-mode-verbose-parse-p
10512 (message "parsing..."))
10513 (setq time
10514 (js2-time
10515 (setq interrupted-p
10516 (catch 'interrupted
10517 (setq js2-mode-ast (js2-parse))
10518 (when (plusp js2-highlight-level)
10519 (js2-mode-fontify-regions))
10520 (js2-mode-remove-suppressed-warnings)
10521 (js2-mode-show-warnings)
10522 (js2-mode-show-errors)
10523 (js2-mode-run-font-lock) ; note: doesn't work
10524 (js2-mode-highlight-magic-parens)
10525 (if (>= js2-highlight-level 1)
10526 (js2-highlight-jsdoc js2-mode-ast))
10527 nil))))
10528 (if interrupted-p
10529 (progn
10530 ;; unfinished parse => try again
10531 (setq js2-mode-buffer-dirty-p t)
10532 (js2-mode-reset-timer))
10533 (if js2-mode-verbose-parse-p
10534 (message "Parse time: %s" time)))))
10535 (setq js2-mode-parsing nil)
10536 (unless interrupted-p
10537 (setq js2-mode-parse-timer nil))))))
10538
10539 (defun js2-mode-show-node ()
10540 "Debugging aid: highlight selected AST node on mouse click."
10541 (interactive)
10542 (let ((node (js2-node-at-point))
10543 beg
10544 end)
10545 (when js2-mode-show-overlay
10546 (if (null node)
10547 (message "No node found at location %s" (point))
10548 (setq beg (js2-node-abs-pos node)
10549 end (+ beg (js2-node-len node)))
10550 (if js2-mode-node-overlay
10551 (move-overlay js2-mode-node-overlay beg end)
10552 (setq js2-mode-node-overlay (make-overlay beg end))
10553 (overlay-put js2-mode-node-overlay 'face 'highlight))
10554 (js2-with-unmodifying-text-property-changes
10555 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10556 (message "%s, parent: %s"
10557 (js2-node-short-name node)
10558 (if (js2-node-parent node)
10559 (js2-node-short-name (js2-node-parent node))
10560 "nil"))))))
10561
10562 (defun js2-mode-hide-overlay (&optional p1 p2)
10563 "Remove the debugging overlay when the point moves.
10564 P1 and P2 are the old and new values of point, respectively."
10565 (when js2-mode-node-overlay
10566 (let ((beg (overlay-start js2-mode-node-overlay))
10567 (end (overlay-end js2-mode-node-overlay)))
10568 ;; Sometimes we're called spuriously.
10569 (unless (and p2
10570 (>= p2 beg)
10571 (<= p2 end))
10572 (js2-with-unmodifying-text-property-changes
10573 (remove-text-properties beg end '(point-left nil)))
10574 (delete-overlay js2-mode-node-overlay)
10575 (setq js2-mode-node-overlay nil)))))
10576
10577 (defun js2-mode-reset ()
10578 "Debugging helper: reset everything."
10579 (interactive)
10580 (js2-mode-exit)
10581 (js2-mode))
10582
10583 (defsubst js2-mode-show-warn-or-err (e face)
10584 "Highlight a warning or error E with FACE.
10585 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10586 (let* ((key (first e))
10587 (beg (second e))
10588 (end (+ beg (third e)))
10589 ;; Don't inadvertently go out of bounds.
10590 (beg (max (point-min) (min beg (point-max))))
10591 (end (max (point-min) (min end (point-max))))
10592 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10593 (ovl (make-overlay beg end)))
10594 (overlay-put ovl 'face face)
10595 (overlay-put ovl 'js2-error t)
10596 (put-text-property beg end 'help-echo (js2-get-msg key))
10597 (put-text-property beg end 'point-entered #'js2-echo-error)))
10598
10599 (defun js2-remove-overlays ()
10600 "Remove overlays from buffer that have a `js2-error' property."
10601 (let ((beg (point-min))
10602 (end (point-max)))
10603 (save-excursion
10604 (dolist (o (overlays-in beg end))
10605 (when (overlay-get o 'js2-error)
10606 (delete-overlay o))))))
10607
10608 (defun js2-error-at-point (&optional pos)
10609 "Return non-nil if there's an error overlay at POS.
10610 Defaults to point."
10611 (loop with pos = (or pos (point))
10612 for o in (overlays-at pos)
10613 thereis (overlay-get o 'js2-error)))
10614
10615 (defun js2-mode-fontify-regions ()
10616 "Apply fontifications recorded during parsing."
10617 ;; We defer clearing faces as long as possible to eliminate flashing.
10618 (js2-clear-face (point-min) (point-max))
10619 ;; have to reverse the recorded fontifications so that errors and
10620 ;; warnings overwrite the normal fontifications
10621 (dolist (f (nreverse js2-mode-fontifications))
10622 (put-text-property (first f) (second f) 'face (third f)))
10623 (setq js2-mode-fontifications nil)
10624 (dolist (p js2-mode-deferred-properties)
10625 (apply #'put-text-property p))
10626 (setq js2-mode-deferred-properties nil))
10627
10628 (defun js2-mode-show-errors ()
10629 "Highlight syntax errors."
10630 (when js2-mode-show-parse-errors
10631 (dolist (e (js2-ast-root-errors js2-mode-ast))
10632 (js2-mode-show-warn-or-err e 'js2-error-face))))
10633
10634 (defun js2-mode-remove-suppressed-warnings ()
10635 "Take suppressed warnings out of the AST warnings list.
10636 This ensures that the counts and `next-error' are correct."
10637 (setf (js2-ast-root-warnings js2-mode-ast)
10638 (js2-delete-if
10639 (lambda (e)
10640 (let ((key (caar e)))
10641 (or
10642 (and (not js2-strict-trailing-comma-warning)
10643 (string-match "trailing\\.comma" key))
10644 (and (not js2-strict-cond-assign-warning)
10645 (string= key "msg.equal.as.assign"))
10646 (and js2-missing-semi-one-line-override
10647 (string= key "msg.missing.semi")
10648 (let* ((beg (second e))
10649 (node (js2-node-at-point beg))
10650 (fn (js2-mode-find-parent-fn node))
10651 (body (and fn (js2-function-node-body fn)))
10652 (lc (and body (js2-node-abs-pos body)))
10653 (rc (and lc (+ lc (js2-node-len body)))))
10654 (and fn
10655 (or (null body)
10656 (save-excursion
10657 (goto-char beg)
10658 (and (js2-same-line lc)
10659 (js2-same-line rc))))))))))
10660 (js2-ast-root-warnings js2-mode-ast))))
10661
10662 (defun js2-mode-show-warnings ()
10663 "Highlight strict-mode warnings."
10664 (when js2-mode-show-strict-warnings
10665 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10666 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10667
10668 (defun js2-echo-error (old-point new-point)
10669 "Called by point-motion hooks."
10670 (let ((msg (get-text-property new-point 'help-echo)))
10671 (if msg
10672 (message msg))))
10673
10674 (defalias #'js2-echo-help #'js2-echo-error)
10675
10676 (defun js2-enter-key ()
10677 "Handle user pressing the Enter key."
10678 (interactive)
10679 (let ((parse-status (save-excursion
10680 (parse-partial-sexp (point-min) (point)))))
10681 (cond
10682 ;; check if we're inside a string
10683 ((nth 3 parse-status)
10684 (js2-mode-split-string parse-status))
10685 ;; check if inside a block comment
10686 ((nth 4 parse-status)
10687 (js2-mode-extend-comment))
10688 (t
10689 ;; should probably figure out what the mode-map says we should do
10690 (if js2-indent-on-enter-key
10691 (let ((js2-bounce-indent-p nil))
10692 (js2-indent-line)))
10693 (insert "\n")
10694 (if js2-enter-indents-newline
10695 (let ((js2-bounce-indent-p nil))
10696 (js2-indent-line)))))))
10697
10698 (defun js2-mode-split-string (parse-status)
10699 "Turn a newline in mid-string into a string concatenation.
10700 PARSE-STATUS is as documented in `parse-partial-sexp'."
10701 (let* ((col (current-column))
10702 (quote-char (nth 3 parse-status))
10703 (quote-string (string quote-char))
10704 (string-beg (nth 8 parse-status))
10705 (indent (save-match-data
10706 (or
10707 (save-excursion
10708 (back-to-indentation)
10709 (if (looking-at "\\+")
10710 (current-column)))
10711 (save-excursion
10712 (goto-char string-beg)
10713 (if (looking-back "\\+\\s-+")
10714 (goto-char (match-beginning 0)))
10715 (current-column))))))
10716 (insert quote-char "\n")
10717 (indent-to indent)
10718 (insert "+ " quote-string)
10719 (when (eolp)
10720 (insert quote-string)
10721 (backward-char 1))))
10722
10723 (defun js2-mode-extend-comment ()
10724 "When inside a comment block, add comment prefix."
10725 (let (star single col first-line needs-close)
10726 (save-excursion
10727 (back-to-indentation)
10728 (cond
10729 ((looking-at "\\*[^/]")
10730 (setq star t
10731 col (current-column)))
10732 ((looking-at "/\\*")
10733 (setq star t
10734 first-line t
10735 col (1+ (current-column))))
10736 ((looking-at "//")
10737 (setq single t
10738 col (current-column)))))
10739 ;; Heuristic for whether we need to close the comment:
10740 ;; if we've got a parse error here, assume it's an unterminated
10741 ;; comment.
10742 (setq needs-close
10743 (or
10744 (eq (get-text-property (1- (point)) 'point-entered)
10745 'js2-echo-error)
10746 ;; The heuristic above doesn't work well when we're
10747 ;; creating a comment and there's another one downstream,
10748 ;; as our parser thinks this one ends at the end of the
10749 ;; next one. (You can have a /* inside a js block comment.)
10750 ;; So just close it if the next non-ws char isn't a *.
10751 (and first-line
10752 (eolp)
10753 (save-excursion
10754 (skip-chars-forward " \t\r\n")
10755 (not (eq (char-after) ?*))))))
10756 (insert "\n")
10757 (cond
10758 (star
10759 (indent-to col)
10760 (insert "* ")
10761 (if (and first-line needs-close)
10762 (save-excursion
10763 (insert "\n")
10764 (indent-to col)
10765 (insert "*/"))))
10766 (single
10767 (when (save-excursion
10768 (and (zerop (forward-line 1))
10769 (looking-at "\\s-*//")))
10770 (indent-to col)
10771 (insert "// "))))))
10772
10773 (defun js2-beginning-of-line ()
10774 "Toggles point between bol and first non-whitespace char in line.
10775 Also moves past comment delimiters when inside comments."
10776 (interactive)
10777 (let (node beg)
10778 (cond
10779 ((bolp)
10780 (back-to-indentation))
10781 ((looking-at "//")
10782 (skip-chars-forward "/ \t"))
10783 ((and (eq (char-after) ?*)
10784 (setq node (js2-comment-at-point))
10785 (memq (js2-comment-node-format node) '(jsdoc block))
10786 (save-excursion
10787 (skip-chars-backward " \t")
10788 (bolp)))
10789 (skip-chars-forward "\* \t"))
10790 (t
10791 (goto-char (point-at-bol))))))
10792
10793 (defun js2-end-of-line ()
10794 "Toggles point between eol and last non-whitespace char in line."
10795 (interactive)
10796 (if (eolp)
10797 (skip-chars-backward " \t")
10798 (goto-char (point-at-eol))))
10799
10800 (defun js2-enter-mirror-mode()
10801 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10802 on insertion."
10803 (interactive)
10804 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10805 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10806 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10807 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10808 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10809 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10810 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10811 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10812
10813 (defun js2-leave-mirror-mode()
10814 "Turns off mirror mode."
10815 (interactive)
10816 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10817 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10818
10819 (defsubst js2-mode-inside-string ()
10820 "Return non-nil if inside a string.
10821 Actually returns the quote character that begins the string."
10822 (let ((parse-state (save-excursion
10823 (parse-partial-sexp (point-min) (point)))))
10824 (nth 3 parse-state)))
10825
10826 (defsubst js2-mode-inside-comment-or-string ()
10827 "Return non-nil if inside a comment or string."
10828 (or
10829 (let ((comment-start
10830 (save-excursion
10831 (goto-char (point-at-bol))
10832 (if (re-search-forward "//" (point-at-eol) t)
10833 (match-beginning 0)))))
10834 (and comment-start
10835 (<= comment-start (point))))
10836 (let ((parse-state (save-excursion
10837 (parse-partial-sexp (point-min) (point)))))
10838 (or (nth 3 parse-state)
10839 (nth 4 parse-state)))))
10840
10841 (defsubst js2-make-magic-delimiter (delim &optional pos)
10842 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10843 Sets value of `js2-magic' text property to line number at POS."
10844 (propertize delim
10845 'js2-magic (line-number-at-pos pos)
10846 'face 'js2-magic-paren-face))
10847
10848 (defun js2-mode-match-delimiter (open close)
10849 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10850 The rule we use, which as far as we can tell is how Eclipse works,
10851 is that we insert the match if we're not in a comment or string,
10852 and the next non-whitespace character is either punctuation or
10853 occurs on another line."
10854 (insert open)
10855 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10856 (not (js2-mode-inside-comment-or-string)))
10857 (save-excursion
10858 (insert (js2-make-magic-delimiter close)))
10859 (when js2-auto-indent-p
10860 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10861 (js2-indent-line)))))
10862
10863 (defun js2-mode-match-bracket ()
10864 "Insert matching bracket."
10865 (interactive)
10866 (js2-mode-match-delimiter "[" "]"))
10867
10868 (defun js2-mode-match-paren ()
10869 "Insert matching paren unless already inserted."
10870 (interactive)
10871 (js2-mode-match-delimiter "(" ")"))
10872
10873 (defun js2-mode-match-curly (arg)
10874 "Insert matching curly-brace.
10875 With prefix arg, no formatting or indentation will occur -- the close-brace
10876 is simply inserted directly at the point."
10877 (interactive "p")
10878 (let (try-pos)
10879 (cond
10880 (current-prefix-arg
10881 (js2-mode-match-delimiter "{" "}"))
10882 ((and js2-auto-insert-catch-block
10883 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10884 (point-at-bol))
10885 (match-beginning 1))))
10886 (js2-insert-catch-skel try-pos))
10887 (t
10888 ;; Otherwise try to do something smarter.
10889 (insert "{")
10890 (unless (or (not (looking-at "\\s-*$"))
10891 (save-excursion
10892 (skip-chars-forward " \t\r\n")
10893 (and (looking-at "}")
10894 (js2-error-at-point)))
10895 (js2-mode-inside-comment-or-string))
10896 (undo-boundary)
10897 ;; absolutely mystifying bug: when inserting the next "\n",
10898 ;; the buffer-undo-list is given two new entries: the inserted range,
10899 ;; and the incorrect position of the point. It's recorded incorrectly
10900 ;; as being before the opening "{", not after it. But it's recorded
10901 ;; as the correct value if you're debugging `js2-mode-match-curly'
10902 ;; in edebug. I have no idea why it's doing this, but incrementing
10903 ;; the inserted position fixes the problem, so that the undo takes us
10904 ;; back to just after the user-inserted "{".
10905 (insert "\n")
10906 (ignore-errors
10907 (incf (cadr buffer-undo-list)))
10908 (js2-indent-line)
10909 (save-excursion
10910 (insert "\n}")
10911 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10912 (js2-indent-line))))))))
10913
10914 (defun js2-insert-catch-skel (try-pos)
10915 "Complete a try/catch block after inserting a { following a try keyword.
10916 Rationale is that a try always needs a catch or a finally, and the catch is
10917 the more likely of the two.
10918
10919 TRY-POS is the buffer position of the try keyword. The open-curly should
10920 already have been inserted."
10921 (insert "{")
10922 (let ((try-col (save-excursion
10923 (goto-char try-pos)
10924 (current-column))))
10925 (insert "\n")
10926 (undo-boundary)
10927 (js2-indent-line) ;; indent the blank line where cursor will end up
10928 (save-excursion
10929 (insert "\n")
10930 (indent-to try-col)
10931 (insert "} catch (x) {\n\n")
10932 (indent-to try-col)
10933 (insert "}"))))
10934
10935 (defun js2-mode-highlight-magic-parens ()
10936 "Re-highlight magic parens after parsing nukes the 'face prop."
10937 (let ((beg (point-min))
10938 end)
10939 (while (setq beg (next-single-property-change beg 'js2-magic))
10940 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10941 (if (get-text-property beg 'js2-magic)
10942 (js2-with-unmodifying-text-property-changes
10943 (put-text-property beg (or end (1+ beg))
10944 'face 'js2-magic-paren-face))))))
10945
10946 (defun js2-mode-mundanify-parens ()
10947 "Clear all magic parens and brackets."
10948 (let ((beg (point-min))
10949 end)
10950 (while (setq beg (next-single-property-change beg 'js2-magic))
10951 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10952 (remove-text-properties beg (or end (1+ beg))
10953 '(js2-magic face)))))
10954
10955 (defsubst js2-match-quote (quote-string)
10956 (let ((start-quote (js2-mode-inside-string)))
10957 (cond
10958 ;; inside a comment - don't do quote-matching, since we can't
10959 ;; reliably figure out if we're in a string inside the comment
10960 ((js2-comment-at-point)
10961 (insert quote-string))
10962 ((not start-quote)
10963 ;; not in string => insert matched quotes
10964 (insert quote-string)
10965 ;; exception: if we're just before a word, don't double it.
10966 (unless (looking-at "[^ \t\r\n]")
10967 (save-excursion
10968 (insert quote-string))))
10969 ((looking-at quote-string)
10970 (if (looking-back "[^\\]\\\\")
10971 (insert quote-string)
10972 (forward-char 1)))
10973 ((and js2-mode-escape-quotes
10974 (save-excursion
10975 (save-match-data
10976 (re-search-forward quote-string (point-at-eol) t))))
10977 ;; inside terminated string, escape quote (unless already escaped)
10978 (insert (if (looking-back "[^\\]\\\\")
10979 quote-string
10980 (concat "\\" quote-string))))
10981 (t
10982 (insert quote-string))))) ; else terminate the string
10983
10984 (defun js2-mode-match-single-quote ()
10985 "Insert matching single-quote."
10986 (interactive)
10987 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10988 ;; don't match inside comments, since apostrophe is more common
10989 (if (nth 4 parse-status)
10990 (insert "'")
10991 (js2-match-quote "'"))))
10992
10993 (defun js2-mode-match-double-quote ()
10994 "Insert matching double-quote."
10995 (interactive)
10996 (js2-match-quote "\""))
10997
10998 ;; Eclipse works as follows:
10999 ;; * type an open-paren and it auto-inserts close-paren
11000 ;; - auto-inserted paren gets a green bracket
11001 ;; - green bracket means typing close-paren there will skip it
11002 ;; * if you insert any text on a different line, it turns off
11003 (defun js2-mode-magic-close-paren ()
11004 "Skip over close-paren rather than inserting, where appropriate."
11005 (interactive)
11006 (let* ((here (point))
11007 (parse-status (parse-partial-sexp (point-min) here))
11008 (open-pos (nth 1 parse-status))
11009 (close last-input-event)
11010 (open (cond
11011 ((eq close ?\))
11012 ?\()
11013 ((eq close ?\])
11014 ?\[)
11015 ((eq close ?})
11016 ?{)
11017 (t nil))))
11018 (if (and (eq (char-after) close)
11019 (eq open (char-after open-pos))
11020 (js2-same-line open-pos)
11021 (get-text-property here 'js2-magic))
11022 (progn
11023 (remove-text-properties here (1+ here) '(js2-magic face))
11024 (forward-char 1))
11025 (insert-char close 1))
11026 (blink-matching-open)))
11027
11028 (defun js2-mode-wait-for-parse (callback)
11029 "Invoke CALLBACK when parsing is finished.
11030 If parsing is already finished, calls CALLBACK immediately."
11031 (if (not js2-mode-buffer-dirty-p)
11032 (funcall callback)
11033 (push callback js2-mode-pending-parse-callbacks)
11034 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11035
11036 (defun js2-mode-parse-finished ()
11037 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11038 ;; We can't let errors propagate up, since it prevents the
11039 ;; `js2-parse' method from completing normally and returning
11040 ;; the ast, which makes things mysteriously not work right.
11041 (unwind-protect
11042 (dolist (cb js2-mode-pending-parse-callbacks)
11043 (condition-case err
11044 (funcall cb)
11045 (error (message "%s" err))))
11046 (setq js2-mode-pending-parse-callbacks nil)))
11047
11048 (defun js2-mode-flag-region (from to flag)
11049 "Hide or show text from FROM to TO, according to FLAG.
11050 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11051 Returns the created overlay if FLAG is non-nil."
11052 (remove-overlays from to 'invisible 'js2-outline)
11053 (when flag
11054 (let ((o (make-overlay from to)))
11055 (overlay-put o 'invisible 'js2-outline)
11056 (overlay-put o 'isearch-open-invisible
11057 'js2-isearch-open-invisible)
11058 o)))
11059
11060 ;; Function to be set as an outline-isearch-open-invisible' property
11061 ;; to the overlay that makes the outline invisible (see
11062 ;; `js2-mode-flag-region').
11063 (defun js2-isearch-open-invisible (overlay)
11064 ;; We rely on the fact that isearch places point on the matched text.
11065 (js2-mode-show-element))
11066
11067 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11068 "Return cons cell of bounds of folding overlay at POS.
11069 Returns nil if not found."
11070 (let ((overlays (overlays-at (or pos (point))))
11071 o)
11072 (while (and overlays
11073 (not o))
11074 (if (overlay-get (car overlays) 'invisible)
11075 (setq o (car overlays))
11076 (setq overlays (cdr overlays))))
11077 (if o
11078 (cons (overlay-start o) (overlay-end o)))))
11079
11080 (defun js2-mode-function-at-point (&optional pos)
11081 "Return the innermost function node enclosing current point.
11082 Returns nil if point is not in a function."
11083 (let ((node (js2-node-at-point pos)))
11084 (while (and node (not (js2-function-node-p node)))
11085 (setq node (js2-node-parent node)))
11086 (if (js2-function-node-p node)
11087 node)))
11088
11089 (defun js2-mode-toggle-element ()
11090 "Hide or show the foldable element at the point."
11091 (interactive)
11092 (let (comment fn pos)
11093 (save-excursion
11094 (save-match-data
11095 (cond
11096 ;; /* ... */ comment?
11097 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11098 (if (js2-mode-invisible-overlay-bounds
11099 (setq pos (+ 3 (js2-node-abs-pos comment))))
11100 (progn
11101 (goto-char pos)
11102 (js2-mode-show-element))
11103 (js2-mode-hide-element)))
11104 ;; //-comment?
11105 ((save-excursion
11106 (back-to-indentation)
11107 (looking-at js2-mode-//-comment-re))
11108 (js2-mode-toggle-//-comment))
11109 ;; function?
11110 ((setq fn (js2-mode-function-at-point))
11111 (setq pos (and (js2-function-node-body fn)
11112 (js2-node-abs-pos (js2-function-node-body fn))))
11113 (goto-char (1+ pos))
11114 (if (js2-mode-invisible-overlay-bounds)
11115 (js2-mode-show-element)
11116 (js2-mode-hide-element)))
11117 (t
11118 (message "Nothing at point to hide or show")))))))
11119
11120 (defun js2-mode-hide-element ()
11121 "Fold/hide contents of a block, showing ellipses.
11122 Show the hidden text with \\[js2-mode-show-element]."
11123 (interactive)
11124 (if js2-mode-buffer-dirty-p
11125 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11126 (let (node body beg end)
11127 (cond
11128 ((js2-mode-invisible-overlay-bounds)
11129 (message "already hidden"))
11130 (t
11131 (setq node (js2-node-at-point))
11132 (cond
11133 ((js2-block-comment-p node)
11134 (js2-mode-hide-comment node))
11135 (t
11136 (while (and node (not (js2-function-node-p node)))
11137 (setq node (js2-node-parent node)))
11138 (if (and node
11139 (setq body (js2-function-node-body node)))
11140 (progn
11141 (setq beg (js2-node-abs-pos body)
11142 end (+ beg (js2-node-len body)))
11143 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11144 (message "No collapsable element found at point"))))))))
11145
11146 (defun js2-mode-show-element ()
11147 "Show the hidden element at current point."
11148 (interactive)
11149 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11150 (if bounds
11151 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11152 (message "Nothing to un-hide"))))
11153
11154 (defun js2-mode-show-all ()
11155 "Show all of the text in the buffer."
11156 (interactive)
11157 (js2-mode-flag-region (point-min) (point-max) nil))
11158
11159 (defun js2-mode-toggle-hide-functions ()
11160 (interactive)
11161 (if js2-mode-functions-hidden
11162 (js2-mode-show-functions)
11163 (js2-mode-hide-functions)))
11164
11165 (defun js2-mode-hide-functions ()
11166 "Hides all non-nested function bodies in the buffer.
11167 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11168 to open an individual entry."
11169 (interactive)
11170 (if js2-mode-buffer-dirty-p
11171 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11172 (if (null js2-mode-ast)
11173 (message "Oops - parsing failed")
11174 (setq js2-mode-functions-hidden t)
11175 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11176
11177 (defun js2-mode-function-hider (n endp)
11178 (when (not endp)
11179 (let ((tt (js2-node-type n))
11180 body beg end)
11181 (cond
11182 ((and (= tt js2-FUNCTION)
11183 (setq body (js2-function-node-body n)))
11184 (setq beg (js2-node-abs-pos body)
11185 end (+ beg (js2-node-len body)))
11186 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11187 nil) ; don't process children of function
11188 (t
11189 t))))) ; keep processing other AST nodes
11190
11191 (defun js2-mode-show-functions ()
11192 "Un-hide any folded function bodies in the buffer."
11193 (interactive)
11194 (setq js2-mode-functions-hidden nil)
11195 (save-excursion
11196 (goto-char (point-min))
11197 (while (/= (goto-char (next-overlay-change (point)))
11198 (point-max))
11199 (dolist (o (overlays-at (point)))
11200 (when (and (overlay-get o 'invisible)
11201 (not (overlay-get o 'comment)))
11202 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11203
11204 (defun js2-mode-hide-comment (n)
11205 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11206 3 ; /**
11207 2)) ; /*
11208 (beg (+ (js2-node-abs-pos n) head))
11209 (end (- (+ beg (js2-node-len n)) head 2))
11210 (o (js2-mode-flag-region beg end 'hide)))
11211 (overlay-put o 'comment t)))
11212
11213 (defun js2-mode-toggle-hide-comments ()
11214 "Folds all block comments in the buffer.
11215 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11216 to open an individual entry."
11217 (interactive)
11218 (if js2-mode-comments-hidden
11219 (js2-mode-show-comments)
11220 (js2-mode-hide-comments)))
11221
11222 (defun js2-mode-hide-comments ()
11223 (interactive)
11224 (if js2-mode-buffer-dirty-p
11225 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11226 (if (null js2-mode-ast)
11227 (message "Oops - parsing failed")
11228 (setq js2-mode-comments-hidden t)
11229 (dolist (n (js2-ast-root-comments js2-mode-ast))
11230 (let ((format (js2-comment-node-format n)))
11231 (when (js2-block-comment-p n)
11232 (js2-mode-hide-comment n))))
11233 (js2-mode-hide-//-comments)))
11234
11235 (defsubst js2-mode-extend-//-comment (direction)
11236 "Find start or end of a block of similar //-comment lines.
11237 DIRECTION is -1 to look back, 1 to look forward.
11238 INDENT is the indentation level to match.
11239 Returns the end-of-line position of the furthest adjacent
11240 //-comment line with the same indentation as the current line.
11241 If there is no such matching line, returns current end of line."
11242 (let ((pos (point-at-eol))
11243 (indent (current-indentation)))
11244 (save-excursion
11245 (save-match-data
11246 (while (and (zerop (forward-line direction))
11247 (looking-at js2-mode-//-comment-re)
11248 (eq indent (length (match-string 1))))
11249 (setq pos (point-at-eol)))
11250 pos))))
11251
11252 (defun js2-mode-hide-//-comments ()
11253 "Fold adjacent 1-line comments, showing only snippet of first one."
11254 (let (beg end)
11255 (save-excursion
11256 (save-match-data
11257 (goto-char (point-min))
11258 (while (re-search-forward js2-mode-//-comment-re nil t)
11259 (setq beg (point)
11260 end (js2-mode-extend-//-comment 1))
11261 (unless (eq beg end)
11262 (overlay-put (js2-mode-flag-region beg end 'hide)
11263 'comment t))
11264 (goto-char end)
11265 (forward-char 1))))))
11266
11267 (defun js2-mode-toggle-//-comment ()
11268 "Fold or un-fold any multi-line //-comment at point.
11269 Caller should have determined that this line starts with a //-comment."
11270 (let* ((beg (point-at-eol))
11271 (end beg))
11272 (save-excursion
11273 (goto-char end)
11274 (if (js2-mode-invisible-overlay-bounds)
11275 (js2-mode-show-element)
11276 ;; else hide the comment
11277 (setq beg (js2-mode-extend-//-comment -1)
11278 end (js2-mode-extend-//-comment 1))
11279 (unless (eq beg end)
11280 (overlay-put (js2-mode-flag-region beg end 'hide)
11281 'comment t))))))
11282
11283 (defun js2-mode-show-comments ()
11284 "Un-hide any hidden comments, leaving other hidden elements alone."
11285 (interactive)
11286 (setq js2-mode-comments-hidden nil)
11287 (save-excursion
11288 (goto-char (point-min))
11289 (while (/= (goto-char (next-overlay-change (point)))
11290 (point-max))
11291 (dolist (o (overlays-at (point)))
11292 (when (overlay-get o 'comment)
11293 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11294
11295 (defun js2-mode-display-warnings-and-errors ()
11296 "Turn on display of warnings and errors."
11297 (interactive)
11298 (setq js2-mode-show-parse-errors t
11299 js2-mode-show-strict-warnings t)
11300 (js2-reparse 'force))
11301
11302 (defun js2-mode-hide-warnings-and-errors ()
11303 "Turn off display of warnings and errors."
11304 (interactive)
11305 (setq js2-mode-show-parse-errors nil
11306 js2-mode-show-strict-warnings nil)
11307 (js2-reparse 'force))
11308
11309 (defun js2-mode-toggle-warnings-and-errors ()
11310 "Toggle the display of warnings and errors.
11311 Some users don't like having warnings/errors reported while they type."
11312 (interactive)
11313 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11314 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11315 (if (interactive-p)
11316 (message "warnings and errors %s"
11317 (if js2-mode-show-parse-errors
11318 "enabled"
11319 "disabled")))
11320 (js2-reparse 'force))
11321
11322 (defun js2-mode-customize ()
11323 (interactive)
11324 (customize-group 'js2-mode))
11325
11326 (defun js2-mode-forward-sexp (&optional arg)
11327 "Move forward across one statement or balanced expression.
11328 With ARG, do it that many times. Negative arg -N means
11329 move backward across N balanced expressions."
11330 (interactive "p")
11331 (setq arg (or arg 1))
11332 (if js2-mode-buffer-dirty-p
11333 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11334 (let (node end (start (point)))
11335 (cond
11336 ;; backward-sexp
11337 ;; could probably make this better for some cases:
11338 ;; - if in statement block (e.g. function body), go to parent
11339 ;; - infix exprs like (foo in bar) - maybe go to beginning
11340 ;; of infix expr if in the right-side expression?
11341 ((and arg (minusp arg))
11342 (dotimes (i (- arg))
11343 (js2-backward-sws)
11344 (forward-char -1) ; enter the node we backed up to
11345 (setq node (js2-node-at-point (point) t))
11346 (goto-char (if node
11347 (js2-node-abs-pos node)
11348 (point-min)))))
11349 (t
11350 ;; forward-sexp
11351 (js2-forward-sws)
11352 (dotimes (i arg)
11353 (js2-forward-sws)
11354 (setq node (js2-node-at-point (point) t)
11355 end (if node (+ (js2-node-abs-pos node)
11356 (js2-node-len node))))
11357 (goto-char (or end (point-max))))))))
11358
11359 (defun js2-next-error (&optional arg reset)
11360 "Move to next parse error.
11361 Typically invoked via \\[next-error].
11362 ARG is the number of errors, forward or backward, to move.
11363 RESET means start over from the beginning."
11364 (interactive "p")
11365 (if (or (null js2-mode-ast)
11366 (and (null (js2-ast-root-errors js2-mode-ast))
11367 (null (js2-ast-root-warnings js2-mode-ast))))
11368 (message "No errors")
11369 (when reset
11370 (goto-char (point-min)))
11371 (let* ((errs (copy-sequence
11372 (append (js2-ast-root-errors js2-mode-ast)
11373 (js2-ast-root-warnings js2-mode-ast))))
11374 (continue t)
11375 (start (point))
11376 (count (or arg 1))
11377 (backward (minusp count))
11378 (sorter (if backward '> '<))
11379 (stopper (if backward '< '>))
11380 (count (abs count))
11381 all-errs
11382 err)
11383 ;; sort by start position
11384 (setq errs (sort errs (lambda (e1 e2)
11385 (funcall sorter (second e1) (second e2))))
11386 all-errs errs)
11387 ;; find nth error with pos > start
11388 (while (and errs continue)
11389 (when (funcall stopper (cadar errs) start)
11390 (setq err (car errs))
11391 (if (zerop (decf count))
11392 (setq continue nil)))
11393 (setq errs (cdr errs)))
11394 (if err
11395 (goto-char (second err))
11396 ;; wrap around to first error
11397 (goto-char (second (car all-errs)))
11398 ;; if we were already on it, echo msg again
11399 (if (= (point) start)
11400 (js2-echo-error (point) (point)))))))
11401
11402 (defun js2-down-mouse-3 ()
11403 "Make right-click move the point to the click location.
11404 This makes right-click context menu operations a bit more intuitive.
11405 The point will not move if the region is active, however, to avoid
11406 destroying the region selection."
11407 (interactive)
11408 (when (and js2-move-point-on-right-click
11409 (not mark-active))
11410 (let ((e last-input-event))
11411 (ignore-errors
11412 (goto-char (cadadr e))))))
11413
11414 (defun js2-mode-create-imenu-index ()
11415 "Return an alist for `imenu--index-alist'."
11416 ;; This is built up in `js2-parse-record-imenu' during parsing.
11417 (when js2-mode-ast
11418 ;; if we have an ast but no recorder, they're requesting a rescan
11419 (unless js2-imenu-recorder
11420 (js2-reparse 'force))
11421 (prog1
11422 (js2-build-imenu-index)
11423 (setq js2-imenu-recorder nil
11424 js2-imenu-function-map nil))))
11425
11426 (defun js2-mode-find-tag ()
11427 "Replacement for `find-tag-default'.
11428 `find-tag-default' returns a ridiculous answer inside comments."
11429 (let (beg end)
11430 (js2-with-underscore-as-word-syntax
11431 (save-excursion
11432 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11433 (looking-back "[A-Za-z0-9_$]"))
11434 (setq beg (progn (forward-word -1) (point))
11435 end (progn (forward-word 1) (point)))
11436 (setq beg (progn (forward-word 1) (point))
11437 end (progn (forward-word -1) (point))))
11438 (replace-regexp-in-string
11439 "[\"']" ""
11440 (buffer-substring-no-properties beg end))))))
11441
11442 (defun js2-mode-forward-sibling ()
11443 "Move to the end of the sibling following point in parent.
11444 Returns non-nil if successful, or nil if there was no following sibling."
11445 (let* ((node (js2-node-at-point))
11446 (parent (js2-mode-find-enclosing-fn node))
11447 sib)
11448 (when (setq sib (js2-node-find-child-after (point) parent))
11449 (goto-char (+ (js2-node-abs-pos sib)
11450 (js2-node-len sib))))))
11451
11452 (defun js2-mode-backward-sibling ()
11453 "Move to the beginning of the sibling node preceding point in parent.
11454 Parent is defined as the enclosing script or function."
11455 (let* ((node (js2-node-at-point))
11456 (parent (js2-mode-find-enclosing-fn node))
11457 sib)
11458 (when (setq sib (js2-node-find-child-before (point) parent))
11459 (goto-char (js2-node-abs-pos sib)))))
11460
11461 (defun js2-beginning-of-defun ()
11462 "Go to line on which current function starts, and return non-nil.
11463 If we're not in a function, go to beginning of previous script-level element."
11464 (interactive)
11465 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11466 pos sib)
11467 (cond
11468 ((and (js2-function-node-p parent)
11469 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11470 (goto-char pos))
11471 (t
11472 (js2-mode-backward-sibling)))))
11473
11474 (defun js2-end-of-defun ()
11475 "Go to the char after the last position of the current function.
11476 If we're not in a function, skips over the next script-level element."
11477 (interactive)
11478 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11479 (if (not (js2-function-node-p parent))
11480 ;; punt: skip over next script-level element beyond point
11481 (js2-mode-forward-sibling)
11482 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11483 (js2-node-len parent)))))))
11484
11485 (defun js2-mark-defun (&optional allow-extend)
11486 "Put mark at end of this function, point at beginning.
11487 The function marked is the one that contains point.
11488
11489 Interactively, if this command is repeated,
11490 or (in Transient Mark mode) if the mark is active,
11491 it marks the next defun after the ones already marked."
11492 (interactive "p")
11493 (let (extended)
11494 (when (and allow-extend
11495 (or (and (eq last-command this-command) (mark t))
11496 (and transient-mark-mode mark-active)))
11497 (let ((sib (save-excursion
11498 (goto-char (mark))
11499 (if (js2-mode-forward-sibling)
11500 (point))))
11501 node)
11502 (if sib
11503 (progn
11504 (set-mark sib)
11505 (setq extended t))
11506 ;; no more siblings - try extending to enclosing node
11507 (goto-char (mark t)))))
11508 (when (not extended)
11509 (let ((node (js2-node-at-point (point) t)) ; skip comments
11510 ast fn stmt parent beg end)
11511 (when (js2-ast-root-p node)
11512 (setq ast node
11513 node (or (js2-node-find-child-after (point) node)
11514 (js2-node-find-child-before (point) node))))
11515 ;; only mark whole buffer if we can't find any children
11516 (if (null node)
11517 (setq node ast))
11518 (if (js2-function-node-p node)
11519 (setq parent node)
11520 (setq fn (js2-mode-find-enclosing-fn node)
11521 stmt (if (or (null fn)
11522 (js2-ast-root-p fn))
11523 (js2-mode-find-first-stmt node))
11524 parent (or stmt fn)))
11525 (setq beg (js2-node-abs-pos parent)
11526 end (+ beg (js2-node-len parent)))
11527 (push-mark beg)
11528 (goto-char end)
11529 (exchange-point-and-mark)))))
11530
11531 (defun js2-narrow-to-defun ()
11532 "Narrow to the function enclosing point."
11533 (interactive)
11534 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11535 (fn (if (js2-script-node-p node)
11536 node
11537 (js2-mode-find-enclosing-fn node)))
11538 (beg (js2-node-abs-pos fn)))
11539 (unless (js2-ast-root-p fn)
11540 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11541
11542 (provide 'js2-mode)
11543
11544 ;;; js2-mode.el ends here