]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Rearrange expr and loop scopes in array comprehension
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Version: See `js2-mode-version'
8 ;; Keywords: languages, javascript
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This JavaScript editing mode supports:
28
29 ;; - strict recognition of the Ecma-262 language standard
30 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
31 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
32 ;; - accurate syntax highlighting using a recursive-descent parser
33 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
34 ;; - undeclared-variable warnings using a configurable externs framework
35 ;; - "bouncing" line indentation to choose among alternate indentation points
36 ;; - smart line-wrapping within comments and strings
37 ;; - code folding:
38 ;; - show some or all function bodies as {...}
39 ;; - show some or all block comments as /*...*/
40 ;; - context-sensitive menu bar and popup menus
41 ;; - code browsing using the `imenu' package
42 ;; - typing helpers such as automatic insertion of matching braces/parens
43 ;; - many customization options
44
45 ;; To customize how it works:
46 ;; M-x customize-group RET js2-mode RET
47
48 ;; Notes:
49
50 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
51 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
52 ;; `js2-mode' current as the EcmaScript language standard evolves.
53
54 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
55 ;; customizable. It is a surprising amount of work to support customizable
56 ;; indentation. The current compromise is that the tab key lets you cycle among
57 ;; various likely indentation points, similar to the behavior of python-mode.
58
59 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
60 ;; and `mumamo', although it could be made to do so with some effort.
61 ;; This means that `js2-mode' is currently only useful for editing JavaScript
62 ;; files, and not for editing JavaScript within <script> tags or templates.
63
64 ;;; Code:
65
66 (eval-when-compile
67 (require 'cl))
68
69 (require 'imenu)
70 (require 'cc-cmds) ; for `c-fill-paragraph'
71
72 (eval-and-compile
73 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
74 (require 'cc-langs) ; it's here in Emacs 21...
75 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
76
77 ;;; Externs (variables presumed to be defined by the host system)
78
79 (defvar js2-ecma-262-externs
80 (mapcar 'symbol-name
81 '(Array Boolean Date Error EvalError Function Infinity
82 Math NaN Number Object RangeError ReferenceError RegExp
83 String SyntaxError TypeError URIError arguments
84 decodeURI decodeURIComponent encodeURI
85 encodeURIComponent escape eval isFinite isNaN
86 parseFloat parseInt undefined unescape))
87 "Ecma-262 externs. Included in `js2-externs' by default.")
88
89 (defvar js2-browser-externs
90 (mapcar 'symbol-name
91 '(;; DOM level 1
92 Attr CDATASection CharacterData Comment DOMException
93 DOMImplementation Document DocumentFragment
94 DocumentType Element Entity EntityReference
95 ExceptionCode NamedNodeMap Node NodeList Notation
96 ProcessingInstruction Text
97
98 ;; DOM level 2
99 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
100 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
101 HTMLBodyElement HTMLButtonElement HTMLCollection
102 HTMLDListElement HTMLDirectoryElement HTMLDivElement
103 HTMLDocument HTMLElement HTMLFieldSetElement
104 HTMLFontElement HTMLFormElement HTMLFrameElement
105 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
106 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
107 HTMLImageElement HTMLInputElement HTMLIsIndexElement
108 HTMLLIElement HTMLLabelElement HTMLLegendElement
109 HTMLLinkElement HTMLMapElement HTMLMenuElement
110 HTMLMetaElement HTMLModElement HTMLOListElement
111 HTMLObjectElement HTMLOptGroupElement
112 HTMLOptionElement HTMLOptionsCollection
113 HTMLParagraphElement HTMLParamElement HTMLPreElement
114 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
115 HTMLStyleElement HTMLTableCaptionElement
116 HTMLTableCellElement HTMLTableColElement
117 HTMLTableElement HTMLTableRowElement
118 HTMLTableSectionElement HTMLTextAreaElement
119 HTMLTitleElement HTMLUListElement
120
121 ;; DOM level 3
122 DOMConfiguration DOMError DOMException
123 DOMImplementationList DOMImplementationSource
124 DOMLocator DOMStringList NameList TypeInfo
125 UserDataHandler
126
127 ;; Window
128 alert confirm document java navigator prompt screen
129 self top
130
131 ;; W3C CSS
132 CSSCharsetRule CSSFontFace CSSFontFaceRule
133 CSSImportRule CSSMediaRule CSSPageRule
134 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
135 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
136 CSSValue CSSValueList Counter DOMImplementationCSS
137 DocumentCSS DocumentStyle ElementCSSInlineStyle
138 LinkStyle MediaList RGBColor Rect StyleSheet
139 StyleSheetList ViewCSS
140
141 ;; W3C Event
142 EventListener EventTarget Event DocumentEvent UIEvent
143 MouseEvent MutationEvent KeyboardEvent
144
145 ;; W3C Range
146 DocumentRange Range RangeException
147
148 ;; W3C XML
149 XPathResult XMLHttpRequest))
150 "Browser externs.
151 You can cause these to be included or excluded with the custom
152 variable `js2-include-browser-externs'.")
153
154 (defvar js2-rhino-externs
155 (mapcar 'symbol-name
156 '(Packages importClass importPackage com org java
157 ;; Global object (shell) externs
158 defineClass deserialize doctest gc help load
159 loadClass print quit readFile readUrl runCommand seal
160 serialize spawn sync toint32 version))
161 "Mozilla Rhino externs.
162 Set `js2-include-rhino-externs' to t to include them.")
163
164 (defvar js2-gears-externs
165 (mapcar 'symbol-name
166 '(
167 ;; TODO(stevey): add these
168 ))
169 "Google Gears externs.
170 Set `js2-include-gears-externs' to t to include them.")
171
172 ;;; Variables
173
174 (defvar js2-emacs22 (>= emacs-major-version 22))
175
176 (defcustom js2-highlight-level 2
177 "Amount of syntax highlighting to perform.
178 0 or a negative value means do no highlighting.
179 1 adds basic syntax highlighting.
180 2 adds highlighting of some Ecma built-in properties.
181 3 adds highlighting of many Ecma built-in functions."
182 :group 'js2-mode
183 :type '(choice (const :tag "None" 0)
184 (const :tag "Basic" 1)
185 (const :tag "Include Properties" 2)
186 (const :tag "Include Functions" 3)))
187
188 (defvar js2-mode-dev-mode-p nil
189 "Non-nil if running in development mode. Normally nil.")
190
191 (defgroup js2-mode nil
192 "An improved JavaScript mode."
193 :group 'languages)
194
195 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
196 (numberp c-basic-offset))
197 c-basic-offset
198 4)
199 "Number of spaces to indent nested statements.
200 Similar to `c-basic-offset'."
201 :group 'js2-mode
202 :type 'integer)
203 (make-variable-buffer-local 'js2-basic-offset)
204
205 ;; TODO(stevey): move this code into a separate minor mode.
206 (defcustom js2-mirror-mode nil
207 "Non-nil to insert closing brackets, parens, etc. automatically."
208 :group 'js2-mode
209 :type 'boolean)
210
211 (defcustom js2-auto-indent-p nil
212 "Automatic indentation with punctuation characters.
213 If non-nil, the current line is indented when certain punctuations
214 are inserted."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-bounce-indent-p nil
219 "Non-nil to have indent-line function choose among alternatives.
220 If nil, the indent-line function will indent to a predetermined column
221 based on heuristic guessing. If non-nil, then if the current line is
222 already indented to that predetermined column, indenting will choose
223 another likely column and indent to that spot. Repeated invocation of
224 the indent-line function will cycle among the computed alternatives.
225 See the function `js2-bounce-indent' for details."
226 :type 'boolean
227 :group 'js2-mode)
228
229 (defcustom js2-consistent-level-indent-inner-bracket-p t
230 "Non-nil to make indentation level inner bracket consistent,
231 regardless of the beginning bracket position."
232 :group 'js2-mode
233 :type 'boolean)
234
235 (defcustom js2-use-ast-for-indentation-p nil
236 "Non-nil to use AST for indentation and make it more robust."
237 :group 'js2-mode
238 :type 'boolean)
239
240 (defcustom js2-indent-on-enter-key nil
241 "Non-nil to have Enter/Return key indent the line.
242 This is unusual for Emacs modes but common in IDEs like Eclipse."
243 :type 'boolean
244 :group 'js2-mode)
245
246 (defcustom js2-enter-indents-newline nil
247 "Non-nil to have Enter/Return key indent the newly-inserted line.
248 This is unusual for Emacs modes but common in IDEs like Eclipse."
249 :type 'boolean
250 :group 'js2-mode)
251
252 (defcustom js2-rebind-eol-bol-keys t
253 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
254 If non-nil, bounce between bol/eol and first/last non-whitespace char."
255 :group 'js2-mode
256 :type 'boolean)
257
258 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
259 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
260 Each value in the list is passed to `define-key'."
261 :type 'list
262 :group 'js2-mode)
263
264 (defcustom js2-idle-timer-delay 0.2
265 "Delay in secs before re-parsing after user makes changes.
266 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
267 :type 'number
268 :group 'js2-mode)
269 (make-variable-buffer-local 'js2-idle-timer-delay)
270
271 (defcustom js2-dynamic-idle-timer-adjust 0
272 "Positive to adjust `js2-idle-timer-delay' based on file size.
273 The idea is that for short files, parsing is faster so we can be
274 more responsive to user edits without interfering with editing.
275 The buffer length in characters (typically bytes) is divided by
276 this value and used to multiply `js2-idle-timer-delay' for the
277 buffer. For example, a 21k file and 10k adjust yields 21k/10k
278 == 2, so js2-idle-timer-delay is multiplied by 2.
279 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
280 `js2-idle-timer-delay' is not dependent on the file size."
281 :type 'number
282 :group 'js2-mode)
283
284 (defcustom js2-mode-escape-quotes t
285 "Non-nil to disable automatic quote-escaping inside strings."
286 :type 'boolean
287 :group 'js2-mode)
288
289 (defcustom js2-mode-squeeze-spaces t
290 "Non-nil to normalize whitespace when filling in comments.
291 Multiple runs of spaces are converted to a single space."
292 :type 'boolean
293 :group 'js2-mode)
294
295 (defcustom js2-mode-show-parse-errors t
296 "True to highlight parse errors."
297 :type 'boolean
298 :group 'js2-mode)
299
300 (defcustom js2-mode-show-strict-warnings t
301 "Non-nil to emit Ecma strict-mode warnings.
302 Some of the warnings can be individually disabled by other flags,
303 even if this flag is non-nil."
304 :type 'boolean
305 :group 'js2-mode)
306
307 (defcustom js2-strict-trailing-comma-warning t
308 "Non-nil to warn about trailing commas in array literals.
309 Ecma-262 forbids them, but many browsers permit them. IE is the
310 big exception, and can produce bugs if you have trailing commas."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-strict-missing-semi-warning t
315 "Non-nil to warn about semicolon auto-insertion after statement.
316 Technically this is legal per Ecma-262, but some style guides disallow
317 depending on it."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-missing-semi-one-line-override nil
322 "Non-nil to permit missing semicolons in one-line functions.
323 In one-liner functions such as `function identity(x) {return x}'
324 people often omit the semicolon for a cleaner look. If you are
325 such a person, you can suppress the missing-semicolon warning
326 by setting this variable to t."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-inconsistent-return-warning t
331 "Non-nil to warn about mixing returns with value-returns.
332 It's perfectly legal to have a `return' and a `return foo' in the
333 same function, but it's often an indicator of a bug, and it also
334 interferes with type inference (in systems that support it.)"
335 :type 'boolean
336 :group 'js2-mode)
337
338 (defcustom js2-strict-cond-assign-warning t
339 "Non-nil to warn about expressions like if (a = b).
340 This often should have been '==' instead of '='. If the warning
341 is enabled, you can suppress it on a per-expression basis by
342 parenthesizing the expression, e.g. if ((a = b)) ..."
343 :type 'boolean
344 :group 'js2-mode)
345
346 (defcustom js2-strict-cond-assign-warning t
347 "Non-nil to warn about expressions like if (a = b).
348 This often should have been '==' instead of '='. If the warning
349 is enabled, you can suppress it on a per-expression basis by
350 parenthesizing the expression, e.g. if ((a = b)) ..."
351 :type 'boolean
352 :group 'js2-mode)
353
354 (defcustom js2-strict-var-redeclaration-warning t
355 "Non-nil to warn about redeclaring variables in a script or function."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-strict-var-hides-function-arg-warning t
360 "Non-nil to warn about a var decl hiding a function argument."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-skip-preprocessor-directives nil
365 "Non-nil to treat lines beginning with # as comments.
366 Useful for viewing Mozilla JavaScript source code."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-language-version 180
371 "Configures what JavaScript language version to recognize.
372 Currently versions 150, 160, 170 and 180 are supported, corresponding
373 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
374 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
375 and 1.8 adds function closures."
376 :type 'integer
377 :group 'js2-mode)
378
379 (defcustom js2-allow-keywords-as-property-names t
380 "If non-nil, you can use JavaScript keywords as object property names.
381 Examples:
382
383 var foo = {int: 5, while: 6, continue: 7};
384 foo.return = 8;
385
386 Ecma-262 forbids this syntax, but many browsers support it."
387 :type 'boolean
388 :group 'js2-mode)
389
390 (defcustom js2-instanceof-has-side-effects nil
391 "If non-nil, treats the instanceof operator as having side effects.
392 This is useful for xulrunner apps."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-cleanup-whitespace nil
397 "Non-nil to invoke `delete-trailing-whitespace' before saves."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-move-point-on-right-click t
402 "Non-nil to move insertion point when you right-click.
403 This makes right-click context menu behavior a bit more intuitive,
404 since menu operations generally apply to the point. The exception
405 is if there is a region selection, in which case the point does -not-
406 move, so cut/copy/paste etc. can work properly.
407
408 Note that IntelliJ moves the point, and Eclipse leaves it alone,
409 so this behavior is customizable."
410 :group 'js2-mode
411 :type 'boolean)
412
413 (defcustom js2-allow-rhino-new-expr-initializer t
414 "Non-nil to support a Rhino's experimental syntactic construct.
415
416 Rhino supports the ability to follow a `new' expression with an object
417 literal, which is used to set additional properties on the new object
418 after calling its constructor. Syntax:
419
420 new <expr> [ ( arglist ) ] [initializer]
421
422 Hence, this expression:
423
424 new Object {a: 1, b: 2}
425
426 results in an Object with properties a=1 and b=2. This syntax is
427 apparently not configurable in Rhino - it's currently always enabled,
428 as of Rhino version 1.7R2."
429 :type 'boolean
430 :group 'js2-mode)
431
432 (defcustom js2-allow-member-expr-as-function-name nil
433 "Non-nil to support experimental Rhino syntax for function names.
434
435 Rhino supports an experimental syntax configured via the Rhino Context
436 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
437
438 function <member-expr> ( [ arg-list ] ) { <body> }
439
440 Where member-expr is a non-parenthesized 'member expression', which
441 is anything at the grammar level of a new-expression or lower, meaning
442 any expression that does not involve infix or unary operators.
443
444 When <member-expr> is not a simple identifier, then it is syntactic
445 sugar for assigning the anonymous function to the <member-expr>. Hence,
446 this code:
447
448 function a.b().c[2] (x, y) { ... }
449
450 is rewritten as:
451
452 a.b().c[2] = function(x, y) {...}
453
454 which doesn't seem particularly useful, but Rhino permits it."
455 :type 'boolean
456 :group 'js2-mode)
457
458 (defvar js2-mode-version 20101228
459 "Release number for `js2-mode'.")
460
461 ;; scanner variables
462
463 (defmacro js2-deflocal (name value &optional comment)
464 "Define a buffer-local variable NAME with VALUE and COMMENT."
465 `(progn
466 (defvar ,name ,value ,comment)
467 (make-variable-buffer-local ',name)))
468
469 ;; We record the start and end position of each token.
470 (js2-deflocal js2-token-beg 1)
471 (js2-deflocal js2-token-end -1)
472
473 (defvar js2-EOF_CHAR -1
474 "Represents end of stream. Distinct from js2-EOF token type.")
475
476 ;; I originally used symbols to represent tokens, but Rhino uses
477 ;; ints and then sets various flag bits in them, so ints it is.
478 ;; The upshot is that we need a `js2-' prefix in front of each name.
479 (defvar js2-ERROR -1)
480 (defvar js2-EOF 0)
481 (defvar js2-EOL 1)
482 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
483 (defvar js2-LEAVEWITH 3)
484 (defvar js2-RETURN 4)
485 (defvar js2-GOTO 5)
486 (defvar js2-IFEQ 6)
487 (defvar js2-IFNE 7)
488 (defvar js2-SETNAME 8)
489 (defvar js2-BITOR 9)
490 (defvar js2-BITXOR 10)
491 (defvar js2-BITAND 11)
492 (defvar js2-EQ 12)
493 (defvar js2-NE 13)
494 (defvar js2-LT 14)
495 (defvar js2-LE 15)
496 (defvar js2-GT 16)
497 (defvar js2-GE 17)
498 (defvar js2-LSH 18)
499 (defvar js2-RSH 19)
500 (defvar js2-URSH 20)
501 (defvar js2-ADD 21) ; infix plus
502 (defvar js2-SUB 22) ; infix minus
503 (defvar js2-MUL 23)
504 (defvar js2-DIV 24)
505 (defvar js2-MOD 25)
506 (defvar js2-NOT 26)
507 (defvar js2-BITNOT 27)
508 (defvar js2-POS 28) ; unary plus
509 (defvar js2-NEG 29) ; unary minus
510 (defvar js2-NEW 30)
511 (defvar js2-DELPROP 31)
512 (defvar js2-TYPEOF 32)
513 (defvar js2-GETPROP 33)
514 (defvar js2-GETPROPNOWARN 34)
515 (defvar js2-SETPROP 35)
516 (defvar js2-GETELEM 36)
517 (defvar js2-SETELEM 37)
518 (defvar js2-CALL 38)
519 (defvar js2-NAME 39) ; an identifier
520 (defvar js2-NUMBER 40)
521 (defvar js2-STRING 41)
522 (defvar js2-NULL 42)
523 (defvar js2-THIS 43)
524 (defvar js2-FALSE 44)
525 (defvar js2-TRUE 45)
526 (defvar js2-SHEQ 46) ; shallow equality (===)
527 (defvar js2-SHNE 47) ; shallow inequality (!==)
528 (defvar js2-REGEXP 48)
529 (defvar js2-BINDNAME 49)
530 (defvar js2-THROW 50)
531 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
532 (defvar js2-IN 52)
533 (defvar js2-INSTANCEOF 53)
534 (defvar js2-LOCAL_LOAD 54)
535 (defvar js2-GETVAR 55)
536 (defvar js2-SETVAR 56)
537 (defvar js2-CATCH_SCOPE 57)
538 (defvar js2-ENUM_INIT_KEYS 58)
539 (defvar js2-ENUM_INIT_VALUES 59)
540 (defvar js2-ENUM_INIT_ARRAY 60)
541 (defvar js2-ENUM_NEXT 61)
542 (defvar js2-ENUM_ID 62)
543 (defvar js2-THISFN 63)
544 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
545 (defvar js2-ARRAYLIT 65) ; array literal
546 (defvar js2-OBJECTLIT 66) ; object literal
547 (defvar js2-GET_REF 67) ; *reference
548 (defvar js2-SET_REF 68) ; *reference = something
549 (defvar js2-DEL_REF 69) ; delete reference
550 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
551 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
552 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
553
554 ;; XML support
555 (defvar js2-DEFAULTNAMESPACE 73)
556 (defvar js2-ESCXMLATTR 74)
557 (defvar js2-ESCXMLTEXT 75)
558 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
559 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
560 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
561 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
562
563 (defvar js2-first-bytecode js2-ENTERWITH)
564 (defvar js2-last-bytecode js2-REF_NS_NAME)
565
566 (defvar js2-TRY 80)
567 (defvar js2-SEMI 81) ; semicolon
568 (defvar js2-LB 82) ; left and right brackets
569 (defvar js2-RB 83)
570 (defvar js2-LC 84) ; left and right curly-braces
571 (defvar js2-RC 85)
572 (defvar js2-LP 86) ; left and right parens
573 (defvar js2-RP 87)
574 (defvar js2-COMMA 88) ; comma operator
575
576 (defvar js2-ASSIGN 89) ; simple assignment (=)
577 (defvar js2-ASSIGN_BITOR 90) ; |=
578 (defvar js2-ASSIGN_BITXOR 91) ; ^=
579 (defvar js2-ASSIGN_BITAND 92) ; &=
580 (defvar js2-ASSIGN_LSH 93) ; <<=
581 (defvar js2-ASSIGN_RSH 94) ; >>=
582 (defvar js2-ASSIGN_URSH 95) ; >>>=
583 (defvar js2-ASSIGN_ADD 96) ; +=
584 (defvar js2-ASSIGN_SUB 97) ; -=
585 (defvar js2-ASSIGN_MUL 98) ; *=
586 (defvar js2-ASSIGN_DIV 99) ; /=
587 (defvar js2-ASSIGN_MOD 100) ; %=
588
589 (defvar js2-first-assign js2-ASSIGN)
590 (defvar js2-last-assign js2-ASSIGN_MOD)
591
592 (defvar js2-HOOK 101) ; conditional (?:)
593 (defvar js2-COLON 102)
594 (defvar js2-OR 103) ; logical or (||)
595 (defvar js2-AND 104) ; logical and (&&)
596 (defvar js2-INC 105) ; increment/decrement (++ --)
597 (defvar js2-DEC 106)
598 (defvar js2-DOT 107) ; member operator (.)
599 (defvar js2-FUNCTION 108) ; function keyword
600 (defvar js2-EXPORT 109) ; export keyword
601 (defvar js2-IMPORT 110) ; import keyword
602 (defvar js2-IF 111) ; if keyword
603 (defvar js2-ELSE 112) ; else keyword
604 (defvar js2-SWITCH 113) ; switch keyword
605 (defvar js2-CASE 114) ; case keyword
606 (defvar js2-DEFAULT 115) ; default keyword
607 (defvar js2-WHILE 116) ; while keyword
608 (defvar js2-DO 117) ; do keyword
609 (defvar js2-FOR 118) ; for keyword
610 (defvar js2-BREAK 119) ; break keyword
611 (defvar js2-CONTINUE 120) ; continue keyword
612 (defvar js2-VAR 121) ; var keyword
613 (defvar js2-WITH 122) ; with keyword
614 (defvar js2-CATCH 123) ; catch keyword
615 (defvar js2-FINALLY 124) ; finally keyword
616 (defvar js2-VOID 125) ; void keyword
617 (defvar js2-RESERVED 126) ; reserved keywords
618
619 (defvar js2-EMPTY 127)
620
621 ;; Types used for the parse tree - never returned by scanner.
622
623 (defvar js2-BLOCK 128) ; statement block
624 (defvar js2-LABEL 129) ; label
625 (defvar js2-TARGET 130)
626 (defvar js2-LOOP 131)
627 (defvar js2-EXPR_VOID 132) ; expression statement in functions
628 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
629 (defvar js2-JSR 134)
630 (defvar js2-SCRIPT 135) ; top-level node for entire script
631 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
632 (defvar js2-USE_STACK 137)
633 (defvar js2-SETPROP_OP 138) ; x.y op= something
634 (defvar js2-SETELEM_OP 139) ; x[y] op= something
635 (defvar js2-LOCAL_BLOCK 140)
636 (defvar js2-SET_REF_OP 141) ; *reference op= something
637
638 ;; For XML support:
639 (defvar js2-DOTDOT 142) ; member operator (..)
640 (defvar js2-COLONCOLON 143) ; namespace::name
641 (defvar js2-XML 144) ; XML type
642 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
643 (defvar js2-XMLATTR 146) ; @
644 (defvar js2-XMLEND 147)
645
646 ;; Optimizer-only tokens
647 (defvar js2-TO_OBJECT 148)
648 (defvar js2-TO_DOUBLE 149)
649
650 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
651 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
652 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
653 (defvar js2-CONST 153)
654 (defvar js2-SETCONST 154)
655 (defvar js2-SETCONSTVAR 155)
656 (defvar js2-ARRAYCOMP 156)
657 (defvar js2-LETEXPR 157)
658 (defvar js2-WITHEXPR 158)
659 (defvar js2-DEBUGGER 159)
660
661 (defvar js2-COMMENT 160)
662 (defvar js2-ENUM 161) ; for "enum" reserved word
663
664 (defconst js2-num-tokens (1+ js2-ENUM))
665
666 (defconst js2-debug-print-trees nil)
667
668 ;; Rhino accepts any string or stream as input. Emacs character
669 ;; processing works best in buffers, so we'll assume the input is a
670 ;; buffer. JavaScript strings can be copied into temp buffers before
671 ;; scanning them.
672
673 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
674 ;; They're the Emacs equivalent of instance variables, more or less.
675
676 (js2-deflocal js2-ts-dirty-line nil
677 "Token stream buffer-local variable.
678 Indicates stuff other than whitespace since start of line.")
679
680 (js2-deflocal js2-ts-regexp-flags nil
681 "Token stream buffer-local variable.")
682
683 (js2-deflocal js2-ts-string ""
684 "Token stream buffer-local variable.
685 Last string scanned.")
686
687 (js2-deflocal js2-ts-number nil
688 "Token stream buffer-local variable.
689 Last literal number scanned.")
690
691 (js2-deflocal js2-ts-hit-eof nil
692 "Token stream buffer-local variable.")
693
694 (js2-deflocal js2-ts-line-start 0
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-lineno 1
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-line-end-char -1
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
704 "Token stream buffer-local variable.
705 Current scan position.")
706
707 (js2-deflocal js2-ts-is-xml-attribute nil
708 "Token stream buffer-local variable.")
709
710 (js2-deflocal js2-ts-xml-is-tag-content nil
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-xml-open-tags-count 0
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-string-buffer nil
717 "Token stream buffer-local variable.
718 List of chars built up while scanning various tokens.")
719
720 (js2-deflocal js2-ts-comment-type nil
721 "Token stream buffer-local variable.")
722
723 ;;; Parser variables
724
725 (js2-deflocal js2-parsed-errors nil
726 "List of errors produced during scanning/parsing.")
727
728 (js2-deflocal js2-parsed-warnings nil
729 "List of warnings produced during scanning/parsing.")
730
731 (js2-deflocal js2-recover-from-parse-errors t
732 "Non-nil to continue parsing after a syntax error.
733
734 In recovery mode, the AST will be built in full, and any error
735 nodes will be flagged with appropriate error information. If
736 this flag is nil, a syntax error will result in an error being
737 signaled.
738
739 The variable is automatically buffer-local, because different
740 modes that use the parser will need different settings.")
741
742 (js2-deflocal js2-parse-hook nil
743 "List of callbacks for receiving parsing progress.")
744
745 (defvar js2-parse-finished-hook nil
746 "List of callbacks to notify when parsing finishes.
747 Not called if parsing was interrupted.")
748
749 (js2-deflocal js2-is-eval-code nil
750 "True if we're evaluating code in a string.
751 If non-nil, the tokenizer will record the token text, and the AST nodes
752 will record their source text. Off by default for IDE modes, since the
753 text is available in the buffer.")
754
755 (defvar js2-parse-ide-mode t
756 "Non-nil if the parser is being used for `js2-mode'.
757 If non-nil, the parser will set text properties for fontification
758 and the syntax table. The value should be nil when using the
759 parser as a frontend to an interpreter or byte compiler.")
760
761 ;;; Parser instance variables (buffer-local vars for js2-parse)
762
763 (defconst js2-clear-ti-mask #xFFFF
764 "Mask to clear token information bits.")
765
766 (defconst js2-ti-after-eol (lsh 1 16)
767 "Flag: first token of the source line.")
768
769 (defconst js2-ti-check-label (lsh 1 17)
770 "Flag: indicates to check for label.")
771
772 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
773
774 (js2-deflocal js2-compiler-generate-debug-info t)
775 (js2-deflocal js2-compiler-use-dynamic-scope nil)
776 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
777 (js2-deflocal js2-compiler-xml-available t)
778 (js2-deflocal js2-compiler-optimization-level 0)
779 (js2-deflocal js2-compiler-generating-source t)
780 (js2-deflocal js2-compiler-strict-mode nil)
781 (js2-deflocal js2-compiler-report-warning-as-error nil)
782 (js2-deflocal js2-compiler-generate-observer-count nil)
783 (js2-deflocal js2-compiler-activation-names nil)
784
785 ;; SKIP: sourceURI
786
787 ;; There's a compileFunction method in Context.java - may need it.
788 (js2-deflocal js2-called-by-compile-function nil
789 "True if `js2-parse' was called by `js2-compile-function'.
790 Will only be used when we finish implementing the interpreter.")
791
792 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
793
794 (js2-deflocal js2-current-flagged-token js2-EOF)
795 (js2-deflocal js2-current-token js2-EOF)
796
797 ;; SKIP: node factory - we're going to just call functions directly,
798 ;; and eventually go to a unified AST format.
799
800 (js2-deflocal js2-nesting-of-function 0)
801
802 (js2-deflocal js2-recorded-identifiers nil
803 "Tracks identifiers found during parsing.")
804
805 (defmacro js2-in-lhs (body)
806 `(let ((js2-is-in-lhs t))
807 ,body))
808
809 (defmacro js2-in-rhs (body)
810 `(let ((js2-is-in-lhs nil))
811 ,body))
812
813 (js2-deflocal js2-is-in-lhs nil
814 "True while parsing lhs statement")
815
816 (defcustom js2-global-externs nil
817 "A list of any extern names you'd like to consider always declared.
818 This list is global and is used by all js2-mode files.
819 You can create buffer-local externs list using `js2-additional-externs'.
820
821 There is also a buffer-local variable `js2-default-externs',
822 which is initialized by default to include the Ecma-262 externs
823 and the standard browser externs. The three lists are all
824 checked during highlighting."
825 :type 'list
826 :group 'js2-mode)
827
828 (js2-deflocal js2-default-externs nil
829 "Default external declarations.
830
831 These are currently only used for highlighting undeclared variables,
832 which only worries about top-level (unqualified) references.
833 As js2-mode's processing improves, we will flesh out this list.
834
835 The initial value is set to `js2-ecma-262-externs', unless you
836 have set `js2-include-browser-externs', in which case the browser
837 externs are also included.
838
839 See `js2-additional-externs' for more information.")
840
841 (defcustom js2-include-browser-externs t
842 "Non-nil to include browser externs in the master externs list.
843 If you work on JavaScript files that are not intended for browsers,
844 such as Mozilla Rhino server-side JavaScript, set this to nil.
845 You can always include them on a per-file basis by calling
846 `js2-add-browser-externs' from a function on `js2-mode-hook'.
847
848 See `js2-additional-externs' for more information about externs."
849 :type 'boolean
850 :group 'js2-mode)
851
852 (defcustom js2-include-rhino-externs t
853 "Non-nil to include Mozilla Rhino externs in the master externs list.
854 See `js2-additional-externs' for more information about externs."
855 :type 'boolean
856 :group 'js2-mode)
857
858 (defcustom js2-include-gears-externs t
859 "Non-nil to include Google Gears externs in the master externs list.
860 See `js2-additional-externs' for more information about externs."
861 :type 'boolean
862 :group 'js2-mode)
863
864 (js2-deflocal js2-additional-externs nil
865 "A buffer-local list of additional external declarations.
866 It is used to decide whether variables are considered undeclared
867 for purposes of highlighting.
868
869 Each entry is a lisp string. The string should be the fully qualified
870 name of an external entity. All externs should be added to this list,
871 so that as js2-mode's processing improves it can take advantage of them.
872
873 You may want to declare your externs in three ways.
874 First, you can add externs that are valid for all your JavaScript files.
875 You should probably do this by adding them to `js2-global-externs', which
876 is a global list used for all js2-mode files.
877
878 Next, you can add a function to `js2-mode-hook' that adds additional
879 externs appropriate for the specific file, perhaps based on its path.
880 These should go in `js2-additional-externs', which is buffer-local.
881
882 Finally, you can add a function to `js2-post-parse-callbacks',
883 which is called after parsing completes, and `root' is bound to
884 the root of the parse tree. At this stage you can set up an AST
885 node visitor using `js2-visit-ast' and examine the parse tree
886 for specific import patterns that may imply the existence of
887 other externs, possibly tied to your build system. These should also
888 be added to `js2-additional-externs'.
889
890 Your post-parse callback may of course also use the simpler and
891 faster (but perhaps less robust) approach of simply scanning the
892 buffer text for your imports, using regular expressions.")
893
894 ;; SKIP: decompiler
895 ;; SKIP: encoded-source
896
897 ;;; The following variables are per-function and should be saved/restored
898 ;;; during function parsing...
899
900 (js2-deflocal js2-current-script-or-fn nil)
901 (js2-deflocal js2-current-scope nil)
902 (js2-deflocal js2-nesting-of-with 0)
903 (js2-deflocal js2-label-set nil
904 "An alist mapping label names to nodes.")
905
906 (js2-deflocal js2-loop-set nil)
907 (js2-deflocal js2-loop-and-switch-set nil)
908 (js2-deflocal js2-has-return-value nil)
909 (js2-deflocal js2-end-flags 0)
910
911 ;;; ...end of per function variables
912
913 ;; Without 2-token lookahead, labels are a problem.
914 ;; These vars store the token info of the last matched name,
915 ;; iff it wasn't the last matched token. Only valid in some contexts.
916 (defvar js2-prev-name-token-start nil)
917 (defvar js2-prev-name-token-string nil)
918
919 (defsubst js2-save-name-token-data (pos name)
920 (setq js2-prev-name-token-start pos
921 js2-prev-name-token-string name))
922
923 ;; These flags enumerate the possible ways a statement/function can
924 ;; terminate. These flags are used by endCheck() and by the Parser to
925 ;; detect inconsistent return usage.
926 ;;
927 ;; END_UNREACHED is reserved for code paths that are assumed to always be
928 ;; able to execute (example: throw, continue)
929 ;;
930 ;; END_DROPS_OFF indicates if the statement can transfer control to the
931 ;; next one. Statement such as return dont. A compound statement may have
932 ;; some branch that drops off control to the next statement.
933 ;;
934 ;; END_RETURNS indicates that the statement can return (without arguments)
935 ;; END_RETURNS_VALUE indicates that the statement can return a value.
936 ;;
937 ;; A compound statement such as
938 ;; if (condition) {
939 ;; return value;
940 ;; }
941 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
942
943 (defconst js2-end-unreached #x0)
944 (defconst js2-end-drops-off #x1)
945 (defconst js2-end-returns #x2)
946 (defconst js2-end-returns-value #x4)
947 (defconst js2-end-yields #x8)
948
949 ;; Rhino awkwardly passes a statementLabel parameter to the
950 ;; statementHelper() function, the main statement parser, which
951 ;; is then used by quite a few of the sub-parsers. We just make
952 ;; it a buffer-local variable and make sure it's cleaned up properly.
953 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
954
955 ;; Similarly, Rhino passes an inForInit boolean through about half
956 ;; the expression parsers. We use a dynamically-scoped variable,
957 ;; which makes it easier to funcall the parsers individually without
958 ;; worrying about whether they take the parameter or not.
959 (js2-deflocal js2-in-for-init nil)
960 (js2-deflocal js2-temp-name-counter 0)
961 (js2-deflocal js2-parse-stmt-count 0)
962
963 (defsubst js2-get-next-temp-name ()
964 (format "$%d" (incf js2-temp-name-counter)))
965
966 (defvar js2-parse-interruptable-p t
967 "Set this to nil to force parse to continue until finished.
968 This will mostly be useful for interpreters.")
969
970 (defvar js2-statements-per-pause 50
971 "Pause after this many statements to check for user input.
972 If user input is pending, stop the parse and discard the tree.
973 This makes for a smoother user experience for large files.
974 You may have to wait a second or two before the highlighting
975 and error-reporting appear, but you can always type ahead if
976 you wish. This appears to be more or less how Eclipse, IntelliJ
977 and other editors work.")
978
979 (js2-deflocal js2-record-comments t
980 "Instructs the scanner to record comments in `js2-scanned-comments'.")
981
982 (js2-deflocal js2-scanned-comments nil
983 "List of all comments from the current parse.")
984
985 (defcustom js2-mode-indent-inhibit-undo nil
986 "Non-nil to disable collection of Undo information when indenting lines.
987 Some users have requested this behavior. It's nil by default because
988 other Emacs modes don't work this way."
989 :type 'boolean
990 :group 'js2-mode)
991
992 (defcustom js2-mode-indent-ignore-first-tab nil
993 "If non-nil, ignore first TAB keypress if we look indented properly.
994 It's fairly common for users to navigate to an already-indented line
995 and press TAB for reassurance that it's been indented. For this class
996 of users, we want the first TAB press on a line to be ignored if the
997 line is already indented to one of the precomputed alternatives.
998
999 This behavior is only partly implemented. If you TAB-indent a line,
1000 navigate to another line, and then navigate back, it fails to clear
1001 the last-indented variable, so it thinks you've already hit TAB once,
1002 and performs the indent. A full solution would involve getting on the
1003 point-motion hooks for the entire buffer. If we come across another
1004 use cases that requires watching point motion, I'll consider doing it.
1005
1006 If you set this variable to nil, then the TAB key will always change
1007 the indentation of the current line, if more than one alternative
1008 indentation spot exists."
1009 :type 'boolean
1010 :group 'js2-mode)
1011
1012 (defvar js2-indent-hook nil
1013 "A hook for user-defined indentation rules.
1014
1015 Functions on this hook should expect two arguments: (LIST INDEX)
1016 The LIST argument is the list of computed indentation points for
1017 the current line. INDEX is the list index of the indentation point
1018 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1019 indent function is not going to change the current line indentation.
1020
1021 If a hook function on this list returns a non-nil value, then
1022 `js2-bounce-indent' assumes the hook function has performed its own
1023 indentation, and will do nothing. If all hook functions on the list
1024 return nil, then `js2-bounce-indent' will use its computed indentation
1025 and reindent the line.
1026
1027 When hook functions on this hook list are called, the variable
1028 `js2-mode-ast' may or may not be set, depending on whether the
1029 parse tree is available. If the variable is nil, you can pass a
1030 callback to `js2-mode-wait-for-parse', and your callback will be
1031 called after the new parse tree is built. This can take some time
1032 in large files.")
1033
1034 (defface js2-warning-face
1035 `((((class color) (background light))
1036 (:underline "orange"))
1037 (((class color) (background dark))
1038 (:underline "orange"))
1039 (t (:underline t)))
1040 "Face for JavaScript warnings."
1041 :group 'js2-mode)
1042
1043 (defface js2-error-face
1044 `((((class color) (background light))
1045 (:foreground "red"))
1046 (((class color) (background dark))
1047 (:foreground "red"))
1048 (t (:foreground "red")))
1049 "Face for JavaScript errors."
1050 :group 'js2-mode)
1051
1052 (defface js2-jsdoc-tag-face
1053 '((t :foreground "SlateGray"))
1054 "Face used to highlight @whatever tags in jsdoc comments."
1055 :group 'js2-mode)
1056
1057 (defface js2-jsdoc-type-face
1058 '((t :foreground "SteelBlue"))
1059 "Face used to highlight {FooBar} types in jsdoc comments."
1060 :group 'js2-mode)
1061
1062 (defface js2-jsdoc-value-face
1063 '((t :foreground "PeachPuff3"))
1064 "Face used to highlight tag values in jsdoc comments."
1065 :group 'js2-mode)
1066
1067 (defface js2-function-param-face
1068 '((t :foreground "SeaGreen"))
1069 "Face used to highlight function parameters in javascript."
1070 :group 'js2-mode)
1071
1072 (defface js2-instance-member-face
1073 '((t :foreground "DarkOrchid"))
1074 "Face used to highlight instance variables in javascript.
1075 Not currently used."
1076 :group 'js2-mode)
1077
1078 (defface js2-private-member-face
1079 '((t :foreground "PeachPuff3"))
1080 "Face used to highlight calls to private methods in javascript.
1081 Not currently used."
1082 :group 'js2-mode)
1083
1084 (defface js2-private-function-call-face
1085 '((t :foreground "goldenrod"))
1086 "Face used to highlight calls to private functions in javascript.
1087 Not currently used."
1088 :group 'js2-mode)
1089
1090 (defface js2-jsdoc-html-tag-name-face
1091 (if js2-emacs22
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "rosybrown"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "yellow"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "magenta")))
1098 '((((type tty pc) (class color) (background light))
1099 (:foreground "magenta"))
1100 (((type tty pc) (class color) (background dark))
1101 (:foreground "yellow"))
1102 (t (:foreground "RosyBrown"))))
1103 "Face used to highlight jsdoc html tag names"
1104 :group 'js2-mode)
1105
1106 (defface js2-jsdoc-html-tag-delimiter-face
1107 (if js2-emacs22
1108 '((((class color) (min-colors 88) (background light))
1109 (:foreground "dark khaki"))
1110 (((class color) (min-colors 8) (background dark))
1111 (:foreground "green"))
1112 (((class color) (min-colors 8) (background light))
1113 (:foreground "green")))
1114 '((((type tty pc) (class color) (background light))
1115 (:foreground "green"))
1116 (((type tty pc) (class color) (background dark))
1117 (:foreground "green"))
1118 (t (:foreground "dark khaki"))))
1119 "Face used to highlight brackets in jsdoc html tags."
1120 :group 'js2-mode)
1121
1122 (defface js2-magic-paren-face
1123 '((t :underline t))
1124 "Face used to color parens that will be auto-overwritten."
1125 :group 'js2-mode)
1126
1127 (defcustom js2-post-parse-callbacks nil
1128 "A list of callback functions invoked after parsing finishes.
1129 Currently, the main use for this function is to add synthetic
1130 declarations to `js2-recorded-identifiers', which see."
1131 :type 'list
1132 :group 'js2-mode)
1133
1134 (defface js2-external-variable-face
1135 '((t :foreground "orange"))
1136 "Face used to highlight undeclared variable identifiers.
1137 An undeclared variable is any variable not declared with var or let
1138 in the current scope or any lexically enclosing scope. If you use
1139 such a variable, then you are either expecting it to originate from
1140 another file, or you've got a potential bug."
1141 :group 'js2-mode)
1142
1143 (defcustom js2-highlight-external-variables t
1144 "Non-nil to highlight undeclared variable identifiers."
1145 :type 'boolean
1146 :group 'js2-mode)
1147
1148 (defcustom js2-auto-insert-catch-block t
1149 "Non-nil to insert matching catch block on open-curly after `try'."
1150 :type 'boolean
1151 :group 'js2-mode)
1152
1153 (defvar js2-mode-map
1154 (let ((map (make-sparse-keymap))
1155 keys)
1156 (define-key map [mouse-1] #'js2-mode-show-node)
1157 (define-key map (kbd "C-m") #'js2-enter-key)
1158 (when js2-rebind-eol-bol-keys
1159 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1160 (define-key map (kbd "C-e") #'js2-end-of-line))
1161 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1162 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1163 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1164 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1165 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1166 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1167 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1168 (define-key map (kbd "C-c C-`") #'js2-next-error)
1169 ;; also define user's preference for next-error, if available
1170 (if (setq keys (where-is-internal #'next-error))
1171 (define-key map (car keys) #'js2-next-error))
1172 (define-key map (or (car (where-is-internal #'mark-defun))
1173 (kbd "M-C-h"))
1174 #'js2-mark-defun)
1175 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1176 (kbd "C-x nd"))
1177 #'js2-narrow-to-defun)
1178 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1179 (when js2-auto-indent-p
1180 (mapc (lambda (key)
1181 (define-key map key #'js2-insert-and-indent))
1182 js2-electric-keys))
1183
1184 (define-key map [menu-bar javascript]
1185 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1186
1187 (define-key map [menu-bar javascript customize-js2-mode]
1188 '(menu-item "Customize js2-mode" js2-mode-customize
1189 :help "Customize the behavior of this mode"))
1190
1191 (define-key map [menu-bar javascript js2-force-refresh]
1192 '(menu-item "Force buffer refresh" js2-mode-reset
1193 :help "Re-parse the buffer from scratch"))
1194
1195 (define-key map [menu-bar javascript separator-2]
1196 '("--"))
1197
1198 (define-key map [menu-bar javascript next-error]
1199 '(menu-item "Next warning or error" js2-next-error
1200 :enabled (and js2-mode-ast
1201 (or (js2-ast-root-errors js2-mode-ast)
1202 (js2-ast-root-warnings js2-mode-ast)))
1203 :help "Move to next warning or error"))
1204
1205 (define-key map [menu-bar javascript display-errors]
1206 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1207 :visible (not js2-mode-show-parse-errors)
1208 :help "Turn on display of warnings and errors"))
1209
1210 (define-key map [menu-bar javascript hide-errors]
1211 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1212 :visible js2-mode-show-parse-errors
1213 :help "Turn off display of warnings and errors"))
1214
1215 (define-key map [menu-bar javascript separator-1]
1216 '("--"))
1217
1218 (define-key map [menu-bar javascript js2-toggle-function]
1219 '(menu-item "Show/collapse element" js2-mode-toggle-element
1220 :help "Hide or show function body or comment"))
1221
1222 (define-key map [menu-bar javascript show-comments]
1223 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1224 :visible js2-mode-comments-hidden
1225 :help "Expand all hidden block comments"))
1226
1227 (define-key map [menu-bar javascript hide-comments]
1228 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1229 :visible (not js2-mode-comments-hidden)
1230 :help "Show block comments as /*...*/"))
1231
1232 (define-key map [menu-bar javascript show-all-functions]
1233 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1234 :visible js2-mode-functions-hidden
1235 :help "Expand all hidden function bodies"))
1236
1237 (define-key map [menu-bar javascript hide-all-functions]
1238 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1239 :visible (not js2-mode-functions-hidden)
1240 :help "Show {...} for all top-level function bodies"))
1241
1242 map)
1243 "Keymap used in `js2-mode' buffers.")
1244
1245 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1246
1247 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1248 "Matches a //-comment line. Must be first non-whitespace on line.
1249 First match-group is the leading whitespace.")
1250
1251 (defvar js2-mode-hook nil)
1252
1253 (js2-deflocal js2-mode-ast nil "Private variable.")
1254 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1255 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1256 (js2-deflocal js2-mode-parsing nil "Private variable.")
1257 (js2-deflocal js2-mode-node-overlay nil)
1258
1259 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1260 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1261
1262 (js2-deflocal js2-mode-fontifications nil "Private variable")
1263 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1264 (js2-deflocal js2-imenu-recorder nil "Private variable")
1265 (js2-deflocal js2-imenu-function-map nil "Private variable")
1266
1267 (defvar js2-paragraph-start
1268 "\\(@[a-zA-Z]+\\>\\|$\\)")
1269
1270 ;; Note that we also set a 'c-in-sws text property in html comments,
1271 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1272 (defvar js2-syntactic-ws-start
1273 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1274
1275 (defvar js2-syntactic-ws-end
1276 "\\s \\|[\n\r/]\\|\\s!")
1277
1278 (defvar js2-syntactic-eol
1279 (concat "\\s *\\(/\\*[^*\n\r]*"
1280 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1281 "\\*+/\\s *\\)*"
1282 "\\(//\\|/\\*[^*\n\r]*"
1283 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1284 "\\|\\\\$\\|$\\)")
1285 "Copied from `java-mode'. Needed for some cc-engine functions.")
1286
1287 (defvar js2-comment-prefix-regexp
1288 "//+\\|\\**")
1289
1290 (defvar js2-comment-start-skip
1291 "\\(//+\\|/\\*+\\)\\s *")
1292
1293 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1294 "Non-nil to emit status messages during parsing.")
1295
1296 (defvar js2-mode-functions-hidden nil "private variable")
1297 (defvar js2-mode-comments-hidden nil "private variable")
1298
1299 (defvar js2-mode-syntax-table
1300 (let ((table (make-syntax-table)))
1301 (c-populate-syntax-table table)
1302 table)
1303 "Syntax table used in js2-mode buffers.")
1304
1305 (defvar js2-mode-abbrev-table nil
1306 "Abbrev table in use in `js2-mode' buffers.")
1307 (define-abbrev-table 'js2-mode-abbrev-table ())
1308
1309 (defvar js2-mode-pending-parse-callbacks nil
1310 "List of functions waiting to be notified that parse is finished.")
1311
1312 (defvar js2-mode-last-indented-line -1)
1313
1314 ;;; Localizable error and warning messages
1315
1316 ;; Messages are copied from Rhino's Messages.properties.
1317 ;; Many of the Java-specific messages have been elided.
1318 ;; Add any js2-specific ones at the end, so we can keep
1319 ;; this file synced with changes to Rhino's.
1320
1321 (defvar js2-message-table
1322 (make-hash-table :test 'equal :size 250)
1323 "Contains localized messages for js2-mode.")
1324
1325 ;; TODO(stevey): construct this table at compile-time.
1326 (defmacro js2-msg (key &rest strings)
1327 `(puthash ,key (funcall #'concat ,@strings)
1328 js2-message-table))
1329
1330 (defun js2-get-msg (msg-key)
1331 "Look up a localized message.
1332 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1333 the correct number of ARGS must be provided."
1334 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1335 (args (if (listp msg-key) (cdr msg-key)))
1336 (msg (gethash key js2-message-table)))
1337 (if msg
1338 (apply #'format msg args)
1339 key))) ; default to showing the key
1340
1341 (js2-msg "msg.dup.parms"
1342 "Duplicate parameter name '%s'.")
1343
1344 (js2-msg "msg.too.big.jump"
1345 "Program too complex: jump offset too big.")
1346
1347 (js2-msg "msg.too.big.index"
1348 "Program too complex: internal index exceeds 64K limit.")
1349
1350 (js2-msg "msg.while.compiling.fn"
1351 "Encountered code generation error while compiling function '%s': %s")
1352
1353 (js2-msg "msg.while.compiling.script"
1354 "Encountered code generation error while compiling script: %s")
1355
1356 ;; Context
1357 (js2-msg "msg.ctor.not.found"
1358 "Constructor for '%s' not found.")
1359
1360 (js2-msg "msg.not.ctor"
1361 "'%s' is not a constructor.")
1362
1363 ;; FunctionObject
1364 (js2-msg "msg.varargs.ctor"
1365 "Method or constructor '%s' must be static "
1366 "with the signature (Context cx, Object[] args, "
1367 "Function ctorObj, boolean inNewExpr) "
1368 "to define a variable arguments constructor.")
1369
1370 (js2-msg "msg.varargs.fun"
1371 "Method '%s' must be static with the signature "
1372 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1373 "to define a variable arguments function.")
1374
1375 (js2-msg "msg.incompat.call"
1376 "Method '%s' called on incompatible object.")
1377
1378 (js2-msg "msg.bad.parms"
1379 "Unsupported parameter type '%s' in method '%s'.")
1380
1381 (js2-msg "msg.bad.method.return"
1382 "Unsupported return type '%s' in method '%s'.")
1383
1384 (js2-msg "msg.bad.ctor.return"
1385 "Construction of objects of type '%s' is not supported.")
1386
1387 (js2-msg "msg.no.overload"
1388 "Method '%s' occurs multiple times in class '%s'.")
1389
1390 (js2-msg "msg.method.not.found"
1391 "Method '%s' not found in '%s'.")
1392
1393 ;; IRFactory
1394
1395 (js2-msg "msg.bad.for.in.lhs"
1396 "Invalid left-hand side of for..in loop.")
1397
1398 (js2-msg "msg.mult.index"
1399 "Only one variable allowed in for..in loop.")
1400
1401 (js2-msg "msg.bad.for.in.destruct"
1402 "Left hand side of for..in loop must be an array of "
1403 "length 2 to accept key/value pair.")
1404
1405 (js2-msg "msg.cant.convert"
1406 "Can't convert to type '%s'.")
1407
1408 (js2-msg "msg.bad.assign.left"
1409 "Invalid assignment left-hand side.")
1410
1411 (js2-msg "msg.bad.decr"
1412 "Invalid decerement operand.")
1413
1414 (js2-msg "msg.bad.incr"
1415 "Invalid increment operand.")
1416
1417 (js2-msg "msg.bad.yield"
1418 "yield must be in a function.")
1419
1420 (js2-msg "msg.yield.parenthesized"
1421 "yield expression must be parenthesized.")
1422
1423 ;; NativeGlobal
1424 (js2-msg "msg.cant.call.indirect"
1425 "Function '%s' must be called directly, and not by way of a "
1426 "function of another name.")
1427
1428 (js2-msg "msg.eval.nonstring"
1429 "Calling eval() with anything other than a primitive "
1430 "string value will simply return the value. "
1431 "Is this what you intended?")
1432
1433 (js2-msg "msg.eval.nonstring.strict"
1434 "Calling eval() with anything other than a primitive "
1435 "string value is not allowed in strict mode.")
1436
1437 (js2-msg "msg.bad.destruct.op"
1438 "Invalid destructuring assignment operator")
1439
1440 ;; NativeCall
1441 (js2-msg "msg.only.from.new"
1442 "'%s' may only be invoked from a `new' expression.")
1443
1444 (js2-msg "msg.deprec.ctor"
1445 "The '%s' constructor is deprecated.")
1446
1447 ;; NativeFunction
1448 (js2-msg "msg.no.function.ref.found"
1449 "no source found to decompile function reference %s")
1450
1451 (js2-msg "msg.arg.isnt.array"
1452 "second argument to Function.prototype.apply must be an array")
1453
1454 ;; NativeGlobal
1455 (js2-msg "msg.bad.esc.mask"
1456 "invalid string escape mask")
1457
1458 ;; NativeRegExp
1459 (js2-msg "msg.bad.quant"
1460 "Invalid quantifier %s")
1461
1462 (js2-msg "msg.overlarge.backref"
1463 "Overly large back reference %s")
1464
1465 (js2-msg "msg.overlarge.min"
1466 "Overly large minimum %s")
1467
1468 (js2-msg "msg.overlarge.max"
1469 "Overly large maximum %s")
1470
1471 (js2-msg "msg.zero.quant"
1472 "Zero quantifier %s")
1473
1474 (js2-msg "msg.max.lt.min"
1475 "Maximum %s less than minimum")
1476
1477 (js2-msg "msg.unterm.quant"
1478 "Unterminated quantifier %s")
1479
1480 (js2-msg "msg.unterm.paren"
1481 "Unterminated parenthetical %s")
1482
1483 (js2-msg "msg.unterm.class"
1484 "Unterminated character class %s")
1485
1486 (js2-msg "msg.bad.range"
1487 "Invalid range in character class.")
1488
1489 (js2-msg "msg.trail.backslash"
1490 "Trailing \\ in regular expression.")
1491
1492 (js2-msg "msg.re.unmatched.right.paren"
1493 "unmatched ) in regular expression.")
1494
1495 (js2-msg "msg.no.regexp"
1496 "Regular expressions are not available.")
1497
1498 (js2-msg "msg.bad.backref"
1499 "back-reference exceeds number of capturing parentheses.")
1500
1501 (js2-msg "msg.bad.regexp.compile"
1502 "Only one argument may be specified if the first "
1503 "argument to RegExp.prototype.compile is a RegExp object.")
1504
1505 ;; Parser
1506 (js2-msg "msg.got.syntax.errors"
1507 "Compilation produced %s syntax errors.")
1508
1509 (js2-msg "msg.var.redecl"
1510 "TypeError: redeclaration of var %s.")
1511
1512 (js2-msg "msg.const.redecl"
1513 "TypeError: redeclaration of const %s.")
1514
1515 (js2-msg "msg.let.redecl"
1516 "TypeError: redeclaration of variable %s.")
1517
1518 (js2-msg "msg.parm.redecl"
1519 "TypeError: redeclaration of formal parameter %s.")
1520
1521 (js2-msg "msg.fn.redecl"
1522 "TypeError: redeclaration of function %s.")
1523
1524 (js2-msg "msg.let.decl.not.in.block"
1525 "SyntaxError: let declaration not directly within block")
1526
1527 ;; NodeTransformer
1528 (js2-msg "msg.dup.label"
1529 "duplicated label")
1530
1531 (js2-msg "msg.undef.label"
1532 "undefined label")
1533
1534 (js2-msg "msg.bad.break"
1535 "unlabelled break must be inside loop or switch")
1536
1537 (js2-msg "msg.continue.outside"
1538 "continue must be inside loop")
1539
1540 (js2-msg "msg.continue.nonloop"
1541 "continue can only use labels of iteration statements")
1542
1543 (js2-msg "msg.bad.throw.eol"
1544 "Line terminator is not allowed between the throw "
1545 "keyword and throw expression.")
1546
1547 (js2-msg "msg.no.paren.parms"
1548 "missing ( before function parameters.")
1549
1550 (js2-msg "msg.no.parm"
1551 "missing formal parameter")
1552
1553 (js2-msg "msg.no.paren.after.parms"
1554 "missing ) after formal parameters")
1555
1556 (js2-msg "msg.no.brace.body"
1557 "missing '{' before function body")
1558
1559 (js2-msg "msg.no.brace.after.body"
1560 "missing } after function body")
1561
1562 (js2-msg "msg.no.paren.cond"
1563 "missing ( before condition")
1564
1565 (js2-msg "msg.no.paren.after.cond"
1566 "missing ) after condition")
1567
1568 (js2-msg "msg.no.semi.stmt"
1569 "missing ; before statement")
1570
1571 (js2-msg "msg.missing.semi"
1572 "missing ; after statement")
1573
1574 (js2-msg "msg.no.name.after.dot"
1575 "missing name after . operator")
1576
1577 (js2-msg "msg.no.name.after.coloncolon"
1578 "missing name after :: operator")
1579
1580 (js2-msg "msg.no.name.after.dotdot"
1581 "missing name after .. operator")
1582
1583 (js2-msg "msg.no.name.after.xmlAttr"
1584 "missing name after .@")
1585
1586 (js2-msg "msg.no.bracket.index"
1587 "missing ] in index expression")
1588
1589 (js2-msg "msg.no.paren.switch"
1590 "missing ( before switch expression")
1591
1592 (js2-msg "msg.no.paren.after.switch"
1593 "missing ) after switch expression")
1594
1595 (js2-msg "msg.no.brace.switch"
1596 "missing '{' before switch body")
1597
1598 (js2-msg "msg.bad.switch"
1599 "invalid switch statement")
1600
1601 (js2-msg "msg.no.colon.case"
1602 "missing : after case expression")
1603
1604 (js2-msg "msg.double.switch.default"
1605 "double default label in the switch statement")
1606
1607 (js2-msg "msg.no.while.do"
1608 "missing while after do-loop body")
1609
1610 (js2-msg "msg.no.paren.for"
1611 "missing ( after for")
1612
1613 (js2-msg "msg.no.semi.for"
1614 "missing ; after for-loop initializer")
1615
1616 (js2-msg "msg.no.semi.for.cond"
1617 "missing ; after for-loop condition")
1618
1619 (js2-msg "msg.in.after.for.name"
1620 "missing in after for")
1621
1622 (js2-msg "msg.no.paren.for.ctrl"
1623 "missing ) after for-loop control")
1624
1625 (js2-msg "msg.no.paren.with"
1626 "missing ( before with-statement object")
1627
1628 (js2-msg "msg.no.paren.after.with"
1629 "missing ) after with-statement object")
1630
1631 (js2-msg "msg.no.paren.after.let"
1632 "missing ( after let")
1633
1634 (js2-msg "msg.no.paren.let"
1635 "missing ) after variable list")
1636
1637 (js2-msg "msg.no.curly.let"
1638 "missing } after let statement")
1639
1640 (js2-msg "msg.bad.return"
1641 "invalid return")
1642
1643 (js2-msg "msg.no.brace.block"
1644 "missing } in compound statement")
1645
1646 (js2-msg "msg.bad.label"
1647 "invalid label")
1648
1649 (js2-msg "msg.bad.var"
1650 "missing variable name")
1651
1652 (js2-msg "msg.bad.var.init"
1653 "invalid variable initialization")
1654
1655 (js2-msg "msg.no.colon.cond"
1656 "missing : in conditional expression")
1657
1658 (js2-msg "msg.no.paren.arg"
1659 "missing ) after argument list")
1660
1661 (js2-msg "msg.no.bracket.arg"
1662 "missing ] after element list")
1663
1664 (js2-msg "msg.bad.prop"
1665 "invalid property id")
1666
1667 (js2-msg "msg.no.colon.prop"
1668 "missing : after property id")
1669
1670 (js2-msg "msg.no.brace.prop"
1671 "missing } after property list")
1672
1673 (js2-msg "msg.no.paren"
1674 "missing ) in parenthetical")
1675
1676 (js2-msg "msg.reserved.id"
1677 "identifier is a reserved word")
1678
1679 (js2-msg "msg.no.paren.catch"
1680 "missing ( before catch-block condition")
1681
1682 (js2-msg "msg.bad.catchcond"
1683 "invalid catch block condition")
1684
1685 (js2-msg "msg.catch.unreachable"
1686 "any catch clauses following an unqualified catch are unreachable")
1687
1688 (js2-msg "msg.no.brace.try"
1689 "missing '{' before try block")
1690
1691 (js2-msg "msg.no.brace.catchblock"
1692 "missing '{' before catch-block body")
1693
1694 (js2-msg "msg.try.no.catchfinally"
1695 "'try' without 'catch' or 'finally'")
1696
1697 (js2-msg "msg.no.return.value"
1698 "function %s does not always return a value")
1699
1700 (js2-msg "msg.anon.no.return.value"
1701 "anonymous function does not always return a value")
1702
1703 (js2-msg "msg.return.inconsistent"
1704 "return statement is inconsistent with previous usage")
1705
1706 (js2-msg "msg.generator.returns"
1707 "TypeError: generator function '%s' returns a value")
1708
1709 (js2-msg "msg.anon.generator.returns"
1710 "TypeError: anonymous generator function returns a value")
1711
1712 (js2-msg "msg.syntax"
1713 "syntax error")
1714
1715 (js2-msg "msg.unexpected.eof"
1716 "Unexpected end of file")
1717
1718 (js2-msg "msg.XML.bad.form"
1719 "illegally formed XML syntax")
1720
1721 (js2-msg "msg.XML.not.available"
1722 "XML runtime not available")
1723
1724 (js2-msg "msg.too.deep.parser.recursion"
1725 "Too deep recursion while parsing")
1726
1727 (js2-msg "msg.no.side.effects"
1728 "Code has no side effects")
1729
1730 (js2-msg "msg.extra.trailing.comma"
1731 "Trailing comma is not legal in an ECMA-262 object initializer")
1732
1733 (js2-msg "msg.array.trailing.comma"
1734 "Trailing comma yields different behavior across browsers")
1735
1736 (js2-msg "msg.equal.as.assign"
1737 (concat "Test for equality (==) mistyped as assignment (=)?"
1738 " (parenthesize to suppress warning)"))
1739
1740 (js2-msg "msg.var.hides.arg"
1741 "Variable %s hides argument")
1742
1743 (js2-msg "msg.destruct.assign.no.init"
1744 "Missing = in destructuring declaration")
1745
1746 ;; ScriptRuntime
1747 (js2-msg "msg.no.properties"
1748 "%s has no properties.")
1749
1750 (js2-msg "msg.invalid.iterator"
1751 "Invalid iterator value")
1752
1753 (js2-msg "msg.iterator.primitive"
1754 "__iterator__ returned a primitive value")
1755
1756 (js2-msg "msg.assn.create.strict"
1757 "Assignment to undeclared variable %s")
1758
1759 (js2-msg "msg.ref.undefined.prop"
1760 "Reference to undefined property '%s'")
1761
1762 (js2-msg "msg.prop.not.found"
1763 "Property %s not found.")
1764
1765 (js2-msg "msg.invalid.type"
1766 "Invalid JavaScript value of type %s")
1767
1768 (js2-msg "msg.primitive.expected"
1769 "Primitive type expected (had %s instead)")
1770
1771 (js2-msg "msg.namespace.expected"
1772 "Namespace object expected to left of :: (found %s instead)")
1773
1774 (js2-msg "msg.null.to.object"
1775 "Cannot convert null to an object.")
1776
1777 (js2-msg "msg.undef.to.object"
1778 "Cannot convert undefined to an object.")
1779
1780 (js2-msg "msg.cyclic.value"
1781 "Cyclic %s value not allowed.")
1782
1783 (js2-msg "msg.is.not.defined"
1784 "'%s' is not defined.")
1785
1786 (js2-msg "msg.undef.prop.read"
1787 "Cannot read property '%s' from %s")
1788
1789 (js2-msg "msg.undef.prop.write"
1790 "Cannot set property '%s' of %s to '%s'")
1791
1792 (js2-msg "msg.undef.prop.delete"
1793 "Cannot delete property '%s' of %s")
1794
1795 (js2-msg "msg.undef.method.call"
1796 "Cannot call method '%s' of %s")
1797
1798 (js2-msg "msg.undef.with"
1799 "Cannot apply 'with' to %s")
1800
1801 (js2-msg "msg.isnt.function"
1802 "%s is not a function, it is %s.")
1803
1804 (js2-msg "msg.isnt.function.in"
1805 "Cannot call property %s in object %s. "
1806 "It is not a function, it is '%s'.")
1807
1808 (js2-msg "msg.function.not.found"
1809 "Cannot find function %s.")
1810
1811 (js2-msg "msg.function.not.found.in"
1812 "Cannot find function %s in object %s.")
1813
1814 (js2-msg "msg.isnt.xml.object"
1815 "%s is not an xml object.")
1816
1817 (js2-msg "msg.no.ref.to.get"
1818 "%s is not a reference to read reference value.")
1819
1820 (js2-msg "msg.no.ref.to.set"
1821 "%s is not a reference to set reference value to %s.")
1822
1823 (js2-msg "msg.no.ref.from.function"
1824 "Function %s can not be used as the left-hand "
1825 "side of assignment or as an operand of ++ or -- operator.")
1826
1827 (js2-msg "msg.bad.default.value"
1828 "Object's getDefaultValue() method returned an object.")
1829
1830 (js2-msg "msg.instanceof.not.object"
1831 "Can't use instanceof on a non-object.")
1832
1833 (js2-msg "msg.instanceof.bad.prototype"
1834 "'prototype' property of %s is not an object.")
1835
1836 (js2-msg "msg.bad.radix"
1837 "illegal radix %s.")
1838
1839 ;; ScriptableObject
1840 (js2-msg "msg.default.value"
1841 "Cannot find default value for object.")
1842
1843 (js2-msg "msg.zero.arg.ctor"
1844 "Cannot load class '%s' which has no zero-parameter constructor.")
1845
1846 (js2-msg "msg.ctor.multiple.parms"
1847 "Can't define constructor or class %s since more than "
1848 "one constructor has multiple parameters.")
1849
1850 (js2-msg "msg.extend.scriptable"
1851 "%s must extend ScriptableObject in order to define property %s.")
1852
1853 (js2-msg "msg.bad.getter.parms"
1854 "In order to define a property, getter %s must have zero "
1855 "parameters or a single ScriptableObject parameter.")
1856
1857 (js2-msg "msg.obj.getter.parms"
1858 "Expected static or delegated getter %s to take "
1859 "a ScriptableObject parameter.")
1860
1861 (js2-msg "msg.getter.static"
1862 "Getter and setter must both be static or neither be static.")
1863
1864 (js2-msg "msg.setter.return"
1865 "Setter must have void return type: %s")
1866
1867 (js2-msg "msg.setter2.parms"
1868 "Two-parameter setter must take a ScriptableObject as "
1869 "its first parameter.")
1870
1871 (js2-msg "msg.setter1.parms"
1872 "Expected single parameter setter for %s")
1873
1874 (js2-msg "msg.setter2.expected"
1875 "Expected static or delegated setter %s to take two parameters.")
1876
1877 (js2-msg "msg.setter.parms"
1878 "Expected either one or two parameters for setter.")
1879
1880 (js2-msg "msg.setter.bad.type"
1881 "Unsupported parameter type '%s' in setter '%s'.")
1882
1883 (js2-msg "msg.add.sealed"
1884 "Cannot add a property to a sealed object: %s.")
1885
1886 (js2-msg "msg.remove.sealed"
1887 "Cannot remove a property from a sealed object: %s.")
1888
1889 (js2-msg "msg.modify.sealed"
1890 "Cannot modify a property of a sealed object: %s.")
1891
1892 (js2-msg "msg.modify.readonly"
1893 "Cannot modify readonly property: %s.")
1894
1895 ;; TokenStream
1896 (js2-msg "msg.missing.exponent"
1897 "missing exponent")
1898
1899 (js2-msg "msg.caught.nfe"
1900 "number format error")
1901
1902 (js2-msg "msg.unterminated.string.lit"
1903 "unterminated string literal")
1904
1905 (js2-msg "msg.unterminated.comment"
1906 "unterminated comment")
1907
1908 (js2-msg "msg.unterminated.re.lit"
1909 "unterminated regular expression literal")
1910
1911 (js2-msg "msg.invalid.re.flag"
1912 "invalid flag after regular expression")
1913
1914 (js2-msg "msg.no.re.input.for"
1915 "no input for %s")
1916
1917 (js2-msg "msg.illegal.character"
1918 "illegal character")
1919
1920 (js2-msg "msg.invalid.escape"
1921 "invalid Unicode escape sequence")
1922
1923 (js2-msg "msg.bad.namespace"
1924 "not a valid default namespace statement. "
1925 "Syntax is: default xml namespace = EXPRESSION;")
1926
1927 ;; TokensStream warnings
1928 (js2-msg "msg.bad.octal.literal"
1929 "illegal octal literal digit %s; "
1930 "interpreting it as a decimal digit")
1931
1932 (js2-msg "msg.reserved.keyword"
1933 "illegal usage of future reserved keyword %s; "
1934 "interpreting it as ordinary identifier")
1935
1936 (js2-msg "msg.script.is.not.constructor"
1937 "Script objects are not constructors.")
1938
1939 ;; Arrays
1940 (js2-msg "msg.arraylength.bad"
1941 "Inappropriate array length.")
1942
1943 ;; Arrays
1944 (js2-msg "msg.arraylength.too.big"
1945 "Array length %s exceeds supported capacity limit.")
1946
1947 ;; URI
1948 (js2-msg "msg.bad.uri"
1949 "Malformed URI sequence.")
1950
1951 ;; Number
1952 (js2-msg "msg.bad.precision"
1953 "Precision %s out of range.")
1954
1955 ;; NativeGenerator
1956 (js2-msg "msg.send.newborn"
1957 "Attempt to send value to newborn generator")
1958
1959 (js2-msg "msg.already.exec.gen"
1960 "Already executing generator")
1961
1962 (js2-msg "msg.StopIteration.invalid"
1963 "StopIteration may not be changed to an arbitrary object.")
1964
1965 ;; Interpreter
1966 (js2-msg "msg.yield.closing"
1967 "Yield from closing generator")
1968
1969 ;;; Utilities
1970
1971 (defun js2-delete-if (predicate list)
1972 "Remove all items satisfying PREDICATE in LIST."
1973 (loop for item in list
1974 if (not (funcall predicate item))
1975 collect item))
1976
1977 (defun js2-position (element list)
1978 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1979 Returns nil if element is not found in the list."
1980 (let ((count 0)
1981 found)
1982 (while (and list (not found))
1983 (if (eq element (car list))
1984 (setq found t)
1985 (setq count (1+ count)
1986 list (cdr list))))
1987 (if found count)))
1988
1989 (defun js2-find-if (predicate list)
1990 "Find first item satisfying PREDICATE in LIST."
1991 (let (result)
1992 (while (and list (not result))
1993 (if (funcall predicate (car list))
1994 (setq result (car list)))
1995 (setq list (cdr list)))
1996 result))
1997
1998 (defmacro js2-time (form)
1999 "Evaluate FORM, discard result, and return elapsed time in sec"
2000 (declare (debug t))
2001 (let ((beg (make-symbol "--js2-time-beg--"))
2002 (delta (make-symbol "--js2-time-end--")))
2003 `(let ((,beg (current-time))
2004 ,delta)
2005 ,form
2006 (/ (truncate (* (- (float-time (current-time))
2007 (float-time ,beg)))
2008 10000)
2009 10000.0))))
2010
2011 (defsubst js2-same-line (pos)
2012 "Return t if POS is on the same line as current point."
2013 (and (>= pos (point-at-bol))
2014 (<= pos (point-at-eol))))
2015
2016 (defsubst js2-same-line-2 (p1 p2)
2017 "Return t if p1 is on the same line as p2."
2018 (save-excursion
2019 (goto-char p1)
2020 (js2-same-line p2)))
2021
2022 (defun js2-code-bug ()
2023 "Signal an error when we encounter an unexpected code path."
2024 (error "failed assertion"))
2025
2026 ;; I'd like to associate errors with nodes, but for now the
2027 ;; easiest thing to do is get the context info from the last token.
2028 (defsubst js2-record-parse-error (msg &optional arg pos len)
2029 (push (list (list msg arg)
2030 (or pos js2-token-beg)
2031 (or len (- js2-token-end js2-token-beg)))
2032 js2-parsed-errors))
2033
2034 (defsubst js2-report-error (msg &optional msg-arg pos len)
2035 "Signal a syntax error or record a parse error."
2036 (if js2-recover-from-parse-errors
2037 (js2-record-parse-error msg msg-arg pos len)
2038 (signal 'js2-syntax-error
2039 (list msg
2040 js2-ts-lineno
2041 (save-excursion
2042 (goto-char js2-ts-cursor)
2043 (current-column))
2044 js2-ts-hit-eof))))
2045
2046 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2047 (if js2-compiler-report-warning-as-error
2048 (js2-report-error msg msg-arg pos len)
2049 (push (list (list msg msg-arg)
2050 (or pos js2-token-beg)
2051 (or len (- js2-token-end js2-token-beg)))
2052 js2-parsed-warnings)))
2053
2054 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2055 (if js2-compiler-strict-mode
2056 (js2-report-warning msg-id msg-arg beg
2057 (and beg end (- end beg)))))
2058
2059 (put 'js2-syntax-error 'error-conditions
2060 '(error syntax-error js2-syntax-error))
2061 (put 'js2-syntax-error 'error-message "Syntax error")
2062
2063 (put 'js2-parse-error 'error-conditions
2064 '(error parse-error js2-parse-error))
2065 (put 'js2-parse-error 'error-message "Parse error")
2066
2067 (defmacro js2-clear-flag (flags flag)
2068 `(setq ,flags (logand ,flags (lognot ,flag))))
2069
2070 (defmacro js2-set-flag (flags flag)
2071 "Logical-or FLAG into FLAGS."
2072 `(setq ,flags (logior ,flags ,flag)))
2073
2074 (defsubst js2-flag-set-p (flags flag)
2075 (/= 0 (logand flags flag)))
2076
2077 (defsubst js2-flag-not-set-p (flags flag)
2078 (zerop (logand flags flag)))
2079
2080 ;; Stolen shamelessly from James Clark's nxml-mode.
2081 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2082 "Evaluate BODY without any text property changes modifying the buffer.
2083 Any text properties changes happen as usual but the changes are not treated as
2084 modifications to the buffer."
2085 (declare (indent 0) (debug t))
2086 (let ((modified (make-symbol "modified")))
2087 `(let ((,modified (buffer-modified-p))
2088 (inhibit-read-only t)
2089 (inhibit-modification-hooks t)
2090 (buffer-undo-list t)
2091 (deactivate-mark nil)
2092 ;; Apparently these avoid file locking problems.
2093 (buffer-file-name nil)
2094 (buffer-file-truename nil))
2095 (unwind-protect
2096 (progn ,@body)
2097 (unless ,modified
2098 (restore-buffer-modified-p nil))))))
2099
2100 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2101 "Evaluate BODY with the _ character set to be word-syntax."
2102 (declare (indent 0) (debug t))
2103 (let ((old-syntax (make-symbol "old-syntax")))
2104 `(let ((,old-syntax (string (char-syntax ?_))))
2105 (unwind-protect
2106 (progn
2107 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2108 ,@body)
2109 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2110
2111 (defsubst js2-char-uppercase-p (c)
2112 "Return t if C is an uppercase character.
2113 Handles unicode and latin chars properly."
2114 (/= c (downcase c)))
2115
2116 (defsubst js2-char-lowercase-p (c)
2117 "Return t if C is an uppercase character.
2118 Handles unicode and latin chars properly."
2119 (/= c (upcase c)))
2120
2121 ;;; AST struct and function definitions
2122
2123 ;; flags for ast node property 'member-type (used for e4x operators)
2124 (defvar js2-property-flag #x1 "property access: element is valid name")
2125 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2126 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2127
2128 (defsubst js2-relpos (pos anchor)
2129 "Convert POS to be relative to ANCHOR.
2130 If POS is nil, returns nil."
2131 (and pos (- pos anchor)))
2132
2133 (defsubst js2-make-pad (indent)
2134 (if (zerop indent)
2135 ""
2136 (make-string (* indent js2-basic-offset) ? )))
2137
2138 (defsubst js2-visit-ast (node callback)
2139 "Visit every node in ast NODE with visitor CALLBACK.
2140
2141 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2142 called twice: once to visit the node, and again after all the node's
2143 children have been processed. The END-P argument is nil on the first
2144 call and non-nil on the second call. The return value of the callback
2145 affects the traversal: if non-nil, the children of NODE are processed.
2146 If the callback returns nil, or if the node has no children, then the
2147 callback is called immediately with a non-nil END-P argument.
2148
2149 The node traversal is approximately lexical-order, although there
2150 are currently no guarantees around this."
2151 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2152 ;; visit the node
2153 (when (funcall callback node nil)
2154 ;; visit the kids
2155 (cond
2156 ((eq vfunc 'js2-visit-none)
2157 nil) ; don't even bother calling it
2158 ;; Each AST node type has to define a `js2-visitor' function
2159 ;; that takes a node and a callback, and calls `js2-visit-ast'
2160 ;; on each child of the node.
2161 (vfunc
2162 (funcall vfunc node callback))
2163 (t
2164 (error "%s does not define a visitor-traversal function"
2165 (aref node 0)))))
2166 ;; call the end-visit
2167 (funcall callback node t)))
2168
2169 (defstruct (js2-node
2170 (:constructor nil)) ; abstract
2171 "Base AST node type."
2172 (type -1) ; token type
2173 (pos -1) ; start position of this AST node in parsed input
2174 (len 1) ; num characters spanned by the node
2175 props ; optional node property list (an alist)
2176 parent) ; link to parent node; null for root
2177
2178 (defsubst js2-node-get-prop (node prop &optional default)
2179 (or (cadr (assoc prop (js2-node-props node))) default))
2180
2181 (defsubst js2-node-set-prop (node prop value)
2182 (setf (js2-node-props node)
2183 (cons (list prop value) (js2-node-props node))))
2184
2185 (defsubst js2-fixup-starts (n nodes)
2186 "Adjust the start positions of NODES to be relative to N.
2187 Any node in the list may be nil, for convenience."
2188 (dolist (node nodes)
2189 (when node
2190 (setf (js2-node-pos node) (- (js2-node-pos node)
2191 (js2-node-pos n))))))
2192
2193 (defsubst js2-node-add-children (parent &rest nodes)
2194 "Set parent node of NODES to PARENT, and return PARENT.
2195 Does nothing if we're not recording parent links.
2196 If any given node in NODES is nil, doesn't record that link."
2197 (js2-fixup-starts parent nodes)
2198 (dolist (node nodes)
2199 (and node
2200 (setf (js2-node-parent node) parent))))
2201
2202 ;; Non-recursive since it's called a frightening number of times.
2203 (defsubst js2-node-abs-pos (n)
2204 (let ((pos (js2-node-pos n)))
2205 (while (setq n (js2-node-parent n))
2206 (setq pos (+ pos (js2-node-pos n))))
2207 pos))
2208
2209 (defsubst js2-node-abs-end (n)
2210 "Return absolute buffer position of end of N."
2211 (+ (js2-node-abs-pos n) (js2-node-len n)))
2212
2213 ;; It's important to make sure block nodes have a lisp list for the
2214 ;; child nodes, to limit printing recursion depth in an AST that
2215 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2216 ;; a sufficiently large vector tree.
2217
2218 (defstruct (js2-block-node
2219 (:include js2-node)
2220 (:constructor nil)
2221 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2222 (pos js2-token-beg)
2223 len
2224 props
2225 kids)))
2226 "A block of statements."
2227 kids) ; a lisp list of the child statement nodes
2228
2229 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2230 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2231
2232 (defsubst js2-visit-block (ast callback)
2233 "Visit the `js2-block-node' children of AST."
2234 (dolist (kid (js2-block-node-kids ast))
2235 (js2-visit-ast kid callback)))
2236
2237 (defun js2-print-block (n i)
2238 (let ((pad (js2-make-pad i)))
2239 (insert pad "{\n")
2240 (dolist (kid (js2-block-node-kids n))
2241 (js2-print-ast kid (1+ i)))
2242 (insert pad "}")))
2243
2244 (defstruct (js2-scope
2245 (:include js2-block-node)
2246 (:constructor nil)
2247 (:constructor make-js2-scope (&key (type js2-BLOCK)
2248 (pos js2-token-beg)
2249 len
2250 kids)))
2251 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2252 ;; I don't have one of those handy, so I'll use an alist for now.
2253 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2254 ;; and is much lighter-weight to construct (both CPU and mem).
2255 ;; The keys are interned strings (symbols) for faster lookup.
2256 ;; Should switch to hybrid alist/hashtable eventually.
2257 symbol-table ; an alist of (symbol . js2-symbol)
2258 parent-scope ; a `js2-scope'
2259 top) ; top-level `js2-scope' (script/function)
2260
2261 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2262 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2263
2264 (defun js2-scope-set-parent-scope (scope parent)
2265 (setf (js2-scope-parent-scope scope) parent
2266 (js2-scope-top scope) (if (null parent)
2267 scope
2268 (js2-scope-top parent))))
2269
2270 (defun js2-node-get-enclosing-scope (node)
2271 "Return the innermost `js2-scope' node surrounding NODE.
2272 Returns nil if there is no enclosing scope node."
2273 (let ((parent (js2-node-parent node)))
2274 (while (not (js2-scope-p parent))
2275 (setq parent (js2-node-parent parent)))
2276 parent))
2277
2278 (defun js2-get-defining-scope (scope name)
2279 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2280 Returns `js2-scope' in which NAME is defined, or nil if not found."
2281 (let ((sym (if (symbolp name)
2282 name
2283 (intern name)))
2284 table
2285 result
2286 (continue t))
2287 (while (and scope continue)
2288 (if (and (setq table (js2-scope-symbol-table scope))
2289 (assq sym table))
2290 (setq continue nil
2291 result scope)
2292 (setq scope (js2-scope-parent-scope scope))))
2293 result))
2294
2295 (defsubst js2-scope-get-symbol (scope name)
2296 "Return symbol table entry for NAME in SCOPE.
2297 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2298 (and (js2-scope-symbol-table scope)
2299 (cdr (assq (if (symbolp name)
2300 name
2301 (intern name))
2302 (js2-scope-symbol-table scope)))))
2303
2304 (defsubst js2-scope-put-symbol (scope name symbol)
2305 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2306 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2307 (let* ((table (js2-scope-symbol-table scope))
2308 (sym (if (symbolp name) name (intern name)))
2309 (entry (assq sym table)))
2310 (if entry
2311 (setcdr entry symbol)
2312 (push (cons sym symbol)
2313 (js2-scope-symbol-table scope)))))
2314
2315 (defstruct (js2-symbol
2316 (:constructor nil)
2317 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2318 "A symbol table entry."
2319 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2320 ;; js2-LET, or js2-CONST
2321 decl-type
2322 name ; string
2323 ast-node) ; a `js2-node'
2324
2325 (defstruct (js2-error-node
2326 (:include js2-node)
2327 (:constructor nil) ; silence emacs21 byte-compiler
2328 (:constructor make-js2-error-node (&key (type js2-ERROR)
2329 (pos js2-token-beg)
2330 len)))
2331 "AST node representing a parse error.")
2332
2333 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2334 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2335
2336 (defstruct (js2-script-node
2337 (:include js2-scope)
2338 (:constructor nil)
2339 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2340 (pos js2-token-beg)
2341 len
2342 var-decls
2343 fun-decls)))
2344 functions ; lisp list of nested functions
2345 regexps ; lisp list of (string . flags)
2346 symbols ; alist (every symbol gets unique index)
2347 (param-count 0)
2348 var-names ; vector of string names
2349 consts ; bool-vector matching var-decls
2350 (temp-number 0)) ; for generating temp variables
2351
2352 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2353 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2354
2355 (defun js2-print-script (node indent)
2356 (dolist (kid (js2-block-node-kids node))
2357 (js2-print-ast kid indent)))
2358
2359 (defstruct (js2-ast-root
2360 (:include js2-script-node)
2361 (:constructor nil)
2362 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2363 (pos js2-token-beg)
2364 len
2365 buffer)))
2366 "The root node of a js2 AST."
2367 buffer ; the source buffer from which the code was parsed
2368 comments ; a lisp list of comments, ordered by start position
2369 errors ; a lisp list of errors found during parsing
2370 warnings ; a lisp list of warnings found during parsing
2371 node-count) ; number of nodes in the tree, including the root
2372
2373 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2374 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2375
2376 (defun js2-visit-ast-root (ast callback)
2377 (dolist (kid (js2-ast-root-kids ast))
2378 (js2-visit-ast kid callback))
2379 (dolist (comment (js2-ast-root-comments ast))
2380 (js2-visit-ast comment callback)))
2381
2382 (defstruct (js2-comment-node
2383 (:include js2-node)
2384 (:constructor nil)
2385 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2386 (pos js2-token-beg)
2387 len
2388 (format js2-ts-comment-type))))
2389 format) ; 'line, 'block, 'jsdoc or 'html
2390
2391 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2392 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2393
2394 (defun js2-print-comment (n i)
2395 ;; We really ought to link end-of-line comments to their nodes.
2396 ;; Or maybe we could add a new comment type, 'endline.
2397 (insert (js2-make-pad i)
2398 (js2-node-string n)))
2399
2400 (defstruct (js2-expr-stmt-node
2401 (:include js2-node)
2402 (:constructor nil)
2403 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2404 (pos js2-ts-cursor)
2405 len
2406 expr)))
2407 "An expression statement."
2408 expr)
2409
2410 (defsubst js2-expr-stmt-node-set-has-result (node)
2411 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2412 (setf (js2-node-type node) js2-EXPR_RESULT))
2413
2414 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2415 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2416
2417 (defun js2-visit-expr-stmt-node (n v)
2418 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2419
2420 (defun js2-print-expr-stmt-node (n indent)
2421 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2422 (insert ";\n"))
2423
2424 (defstruct (js2-loop-node
2425 (:include js2-scope)
2426 (:constructor nil))
2427 "Abstract supertype of loop nodes."
2428 body ; a `js2-block-node'
2429 lp ; position of left-paren, nil if omitted
2430 rp) ; position of right-paren, nil if omitted
2431
2432 (defstruct (js2-do-node
2433 (:include js2-loop-node)
2434 (:constructor nil)
2435 (:constructor make-js2-do-node (&key (type js2-DO)
2436 (pos js2-token-beg)
2437 len
2438 body
2439 condition
2440 while-pos
2441 lp
2442 rp)))
2443 "AST node for do-loop."
2444 condition ; while (expression)
2445 while-pos) ; buffer position of 'while' keyword
2446
2447 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2448 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2449
2450 (defun js2-visit-do-node (n v)
2451 (js2-visit-ast (js2-do-node-body n) v)
2452 (js2-visit-ast (js2-do-node-condition n) v))
2453
2454 (defun js2-print-do-node (n i)
2455 (let ((pad (js2-make-pad i)))
2456 (insert pad "do {\n")
2457 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2458 (js2-print-ast kid (1+ i)))
2459 (insert pad "} while (")
2460 (js2-print-ast (js2-do-node-condition n) 0)
2461 (insert ");\n")))
2462
2463 (defstruct (js2-while-node
2464 (:include js2-loop-node)
2465 (:constructor nil)
2466 (:constructor make-js2-while-node (&key (type js2-WHILE)
2467 (pos js2-token-beg)
2468 len
2469 body
2470 condition
2471 lp
2472 rp)))
2473 "AST node for while-loop."
2474 condition) ; while-condition
2475
2476 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2477 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2478
2479 (defun js2-visit-while-node (n v)
2480 (js2-visit-ast (js2-while-node-condition n) v)
2481 (js2-visit-ast (js2-while-node-body n) v))
2482
2483 (defun js2-print-while-node (n i)
2484 (let ((pad (js2-make-pad i)))
2485 (insert pad "while (")
2486 (js2-print-ast (js2-while-node-condition n) 0)
2487 (insert ") {\n")
2488 (js2-print-body (js2-while-node-body n) (1+ i))
2489 (insert pad "}\n")))
2490
2491 (defstruct (js2-for-node
2492 (:include js2-loop-node)
2493 (:constructor nil)
2494 (:constructor make-js2-for-node (&key (type js2-FOR)
2495 (pos js2-ts-cursor)
2496 len
2497 body
2498 init
2499 condition
2500 update
2501 lp
2502 rp)))
2503 "AST node for a C-style for-loop."
2504 init ; initialization expression
2505 condition ; loop condition
2506 update) ; update clause
2507
2508 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2509 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2510
2511 (defun js2-visit-for-node (n v)
2512 (js2-visit-ast (js2-for-node-init n) v)
2513 (js2-visit-ast (js2-for-node-condition n) v)
2514 (js2-visit-ast (js2-for-node-update n) v)
2515 (js2-visit-ast (js2-for-node-body n) v))
2516
2517 (defun js2-print-for-node (n i)
2518 (let ((pad (js2-make-pad i)))
2519 (insert pad "for (")
2520 (js2-print-ast (js2-for-node-init n) 0)
2521 (insert "; ")
2522 (js2-print-ast (js2-for-node-condition n) 0)
2523 (insert "; ")
2524 (js2-print-ast (js2-for-node-update n) 0)
2525 (insert ") {\n")
2526 (js2-print-body (js2-for-node-body n) (1+ i))
2527 (insert pad "}\n")))
2528
2529 (defstruct (js2-for-in-node
2530 (:include js2-loop-node)
2531 (:constructor nil)
2532 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2533 (pos js2-ts-cursor)
2534 len
2535 body
2536 iterator
2537 object
2538 in-pos
2539 each-pos
2540 foreach-p
2541 lp
2542 rp)))
2543 "AST node for a for..in loop."
2544 iterator ; [var] foo in ...
2545 object ; object over which we're iterating
2546 in-pos ; buffer position of 'in' keyword
2547 each-pos ; buffer position of 'each' keyword, if foreach-p
2548 foreach-p) ; t if it's a for-each loop
2549
2550 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2551 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2552
2553 (defun js2-visit-for-in-node (n v)
2554 (js2-visit-ast (js2-for-in-node-iterator n) v)
2555 (js2-visit-ast (js2-for-in-node-object n) v)
2556 (js2-visit-ast (js2-for-in-node-body n) v))
2557
2558 (defun js2-print-for-in-node (n i)
2559 (let ((pad (js2-make-pad i))
2560 (foreach (js2-for-in-node-foreach-p n)))
2561 (insert pad "for ")
2562 (if foreach
2563 (insert "each "))
2564 (insert "(")
2565 (js2-print-ast (js2-for-in-node-iterator n) 0)
2566 (insert " in ")
2567 (js2-print-ast (js2-for-in-node-object n) 0)
2568 (insert ") {\n")
2569 (js2-print-body (js2-for-in-node-body n) (1+ i))
2570 (insert pad "}\n")))
2571
2572 (defstruct (js2-return-node
2573 (:include js2-node)
2574 (:constructor nil)
2575 (:constructor make-js2-return-node (&key (type js2-RETURN)
2576 (pos js2-ts-cursor)
2577 len
2578 retval)))
2579 "AST node for a return statement."
2580 retval) ; expression to return, or 'undefined
2581
2582 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2583 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2584
2585 (defun js2-visit-return-node (n v)
2586 (if (js2-return-node-retval n)
2587 (js2-visit-ast (js2-return-node-retval n) v)))
2588
2589 (defun js2-print-return-node (n i)
2590 (insert (js2-make-pad i) "return")
2591 (when (js2-return-node-retval n)
2592 (insert " ")
2593 (js2-print-ast (js2-return-node-retval n) 0))
2594 (insert ";\n"))
2595
2596 (defstruct (js2-if-node
2597 (:include js2-node)
2598 (:constructor nil)
2599 (:constructor make-js2-if-node (&key (type js2-IF)
2600 (pos js2-ts-cursor)
2601 len
2602 condition
2603 then-part
2604 else-pos
2605 else-part
2606 lp
2607 rp)))
2608 "AST node for an if-statement."
2609 condition ; expression
2610 then-part ; statement or block
2611 else-pos ; optional buffer position of 'else' keyword
2612 else-part ; optional statement or block
2613 lp ; position of left-paren, nil if omitted
2614 rp) ; position of right-paren, nil if omitted
2615
2616 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2617 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2618
2619 (defun js2-visit-if-node (n v)
2620 (js2-visit-ast (js2-if-node-condition n) v)
2621 (js2-visit-ast (js2-if-node-then-part n) v)
2622 (if (js2-if-node-else-part n)
2623 (js2-visit-ast (js2-if-node-else-part n) v)))
2624
2625 (defun js2-print-if-node (n i)
2626 (let ((pad (js2-make-pad i))
2627 (then-part (js2-if-node-then-part n))
2628 (else-part (js2-if-node-else-part n)))
2629 (insert pad "if (")
2630 (js2-print-ast (js2-if-node-condition n) 0)
2631 (insert ") {\n")
2632 (js2-print-body then-part (1+ i))
2633 (insert pad "}")
2634 (cond
2635 ((not else-part)
2636 (insert "\n"))
2637 ((js2-if-node-p else-part)
2638 (insert " else ")
2639 (js2-print-body else-part i))
2640 (t
2641 (insert " else {\n")
2642 (js2-print-body else-part (1+ i))
2643 (insert pad "}\n")))))
2644
2645 (defstruct (js2-try-node
2646 (:include js2-node)
2647 (:constructor nil)
2648 (:constructor make-js2-try-node (&key (type js2-TRY)
2649 (pos js2-ts-cursor)
2650 len
2651 try-block
2652 catch-clauses
2653 finally-block)))
2654 "AST node for a try-statement."
2655 try-block
2656 catch-clauses ; a lisp list of `js2-catch-node'
2657 finally-block) ; a `js2-finally-node'
2658
2659 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2660 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2661
2662 (defun js2-visit-try-node (n v)
2663 (js2-visit-ast (js2-try-node-try-block n) v)
2664 (dolist (clause (js2-try-node-catch-clauses n))
2665 (js2-visit-ast clause v))
2666 (if (js2-try-node-finally-block n)
2667 (js2-visit-ast (js2-try-node-finally-block n) v)))
2668
2669 (defun js2-print-try-node (n i)
2670 (let ((pad (js2-make-pad i))
2671 (catches (js2-try-node-catch-clauses n))
2672 (finally (js2-try-node-finally-block n)))
2673 (insert pad "try {\n")
2674 (js2-print-body (js2-try-node-try-block n) (1+ i))
2675 (insert pad "}")
2676 (when catches
2677 (dolist (catch catches)
2678 (js2-print-ast catch i)))
2679 (if finally
2680 (js2-print-ast finally i)
2681 (insert "\n"))))
2682
2683 (defstruct (js2-catch-node
2684 (:include js2-node)
2685 (:constructor nil)
2686 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2687 (pos js2-ts-cursor)
2688 len
2689 var-name
2690 guard-kwd
2691 guard-expr
2692 block
2693 lp
2694 rp)))
2695 "AST node for a catch clause."
2696 var-name ; a `js2-name-node'
2697 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2698 guard-expr ; catch condition, a `js2-node'
2699 block ; statements, a `js2-block-node'
2700 lp ; buffer position of left-paren, nil if omitted
2701 rp) ; buffer position of right-paren, nil if omitted
2702
2703 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2704 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2705
2706 (defun js2-visit-catch-node (n v)
2707 (js2-visit-ast (js2-catch-node-var-name n) v)
2708 (when (js2-catch-node-guard-kwd n)
2709 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2710 (js2-visit-ast (js2-catch-node-block n) v))
2711
2712 (defun js2-print-catch-node (n i)
2713 (let ((pad (js2-make-pad i))
2714 (guard-kwd (js2-catch-node-guard-kwd n))
2715 (guard-expr (js2-catch-node-guard-expr n)))
2716 (insert " catch (")
2717 (js2-print-ast (js2-catch-node-var-name n) 0)
2718 (when guard-kwd
2719 (insert " if ")
2720 (js2-print-ast guard-expr 0))
2721 (insert ") {\n")
2722 (js2-print-body (js2-catch-node-block n) (1+ i))
2723 (insert pad "}")))
2724
2725 (defstruct (js2-finally-node
2726 (:include js2-node)
2727 (:constructor nil)
2728 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2729 (pos js2-ts-cursor)
2730 len
2731 body)))
2732 "AST node for a finally clause."
2733 body) ; a `js2-node', often but not always a block node
2734
2735 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2736 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2737
2738 (defun js2-visit-finally-node (n v)
2739 (js2-visit-ast (js2-finally-node-body n) v))
2740
2741 (defun js2-print-finally-node (n i)
2742 (let ((pad (js2-make-pad i)))
2743 (insert " finally {\n")
2744 (js2-print-body (js2-finally-node-body n) (1+ i))
2745 (insert pad "}\n")))
2746
2747 (defstruct (js2-switch-node
2748 (:include js2-node)
2749 (:constructor nil)
2750 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2751 (pos js2-ts-cursor)
2752 len
2753 discriminant
2754 cases
2755 lp
2756 rp)))
2757 "AST node for a switch statement."
2758 discriminant ; a `js2-node' (switch expression)
2759 cases ; a lisp list of `js2-case-node'
2760 lp ; position of open-paren for discriminant, nil if omitted
2761 rp) ; position of close-paren for discriminant, nil if omitted
2762
2763 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2764 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2765
2766 (defun js2-visit-switch-node (n v)
2767 (js2-visit-ast (js2-switch-node-discriminant n) v)
2768 (dolist (c (js2-switch-node-cases n))
2769 (js2-visit-ast c v)))
2770
2771 (defun js2-print-switch-node (n i)
2772 (let ((pad (js2-make-pad i))
2773 (cases (js2-switch-node-cases n)))
2774 (insert pad "switch (")
2775 (js2-print-ast (js2-switch-node-discriminant n) 0)
2776 (insert ") {\n")
2777 (dolist (case cases)
2778 (js2-print-ast case i))
2779 (insert pad "}\n")))
2780
2781 (defstruct (js2-case-node
2782 (:include js2-block-node)
2783 (:constructor nil)
2784 (:constructor make-js2-case-node (&key (type js2-CASE)
2785 (pos js2-ts-cursor)
2786 len
2787 kids
2788 expr)))
2789 "AST node for a case clause of a switch statement."
2790 expr) ; the case expression (nil for default)
2791
2792 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2793 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2794
2795 (defun js2-visit-case-node (n v)
2796 (if (js2-case-node-expr n) ; nil for default: case
2797 (js2-visit-ast (js2-case-node-expr n) v))
2798 (js2-visit-block n v))
2799
2800 (defun js2-print-case-node (n i)
2801 (let ((pad (js2-make-pad i))
2802 (expr (js2-case-node-expr n)))
2803 (insert pad)
2804 (if (null expr)
2805 (insert "default:\n")
2806 (insert "case ")
2807 (js2-print-ast expr 0)
2808 (insert ":\n"))
2809 (dolist (kid (js2-case-node-kids n))
2810 (js2-print-ast kid (1+ i)))))
2811
2812 (defstruct (js2-throw-node
2813 (:include js2-node)
2814 (:constructor nil)
2815 (:constructor make-js2-throw-node (&key (type js2-THROW)
2816 (pos js2-ts-cursor)
2817 len
2818 expr)))
2819 "AST node for a throw statement."
2820 expr) ; the expression to throw
2821
2822 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2823 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2824
2825 (defun js2-visit-throw-node (n v)
2826 (js2-visit-ast (js2-throw-node-expr n) v))
2827
2828 (defun js2-print-throw-node (n i)
2829 (insert (js2-make-pad i) "throw ")
2830 (js2-print-ast (js2-throw-node-expr n) 0)
2831 (insert ";\n"))
2832
2833 (defstruct (js2-with-node
2834 (:include js2-node)
2835 (:constructor nil)
2836 (:constructor make-js2-with-node (&key (type js2-WITH)
2837 (pos js2-ts-cursor)
2838 len
2839 object
2840 body
2841 lp
2842 rp)))
2843 "AST node for a with-statement."
2844 object
2845 body
2846 lp ; buffer position of left-paren around object, nil if omitted
2847 rp) ; buffer position of right-paren around object, nil if omitted
2848
2849 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2850 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2851
2852 (defun js2-visit-with-node (n v)
2853 (js2-visit-ast (js2-with-node-object n) v)
2854 (js2-visit-ast (js2-with-node-body n) v))
2855
2856 (defun js2-print-with-node (n i)
2857 (let ((pad (js2-make-pad i)))
2858 (insert pad "with (")
2859 (js2-print-ast (js2-with-node-object n) 0)
2860 (insert ") {\n")
2861 (js2-print-body (js2-with-node-body n) (1+ i))
2862 (insert pad "}\n")))
2863
2864 (defstruct (js2-label-node
2865 (:include js2-node)
2866 (:constructor nil)
2867 (:constructor make-js2-label-node (&key (type js2-LABEL)
2868 (pos js2-ts-cursor)
2869 len
2870 name)))
2871 "AST node for a statement label or case label."
2872 name ; a string
2873 loop) ; for validating and code-generating continue-to-label
2874
2875 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2876 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2877
2878 (defun js2-print-label (n i)
2879 (insert (js2-make-pad i)
2880 (js2-label-node-name n)
2881 ":\n"))
2882
2883 (defstruct (js2-labeled-stmt-node
2884 (:include js2-node)
2885 (:constructor nil)
2886 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2887 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2888 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2889 (pos js2-ts-cursor)
2890 len
2891 labels
2892 stmt)))
2893 "AST node for a statement with one or more labels.
2894 Multiple labels for a statement are collapsed into the labels field."
2895 labels ; lisp list of `js2-label-node'
2896 stmt) ; the statement these labels are for
2897
2898 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2899 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2900
2901 (defun js2-get-label-by-name (lbl-stmt name)
2902 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2903 Returns nil if no such label is in the list."
2904 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2905 result)
2906 (while (and label-list (not result))
2907 (if (string= (js2-label-node-name (car label-list)) name)
2908 (setq result (car label-list))
2909 (setq label-list (cdr label-list))))
2910 result))
2911
2912 (defun js2-visit-labeled-stmt (n v)
2913 (dolist (label (js2-labeled-stmt-node-labels n))
2914 (js2-visit-ast label v))
2915 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2916
2917 (defun js2-print-labeled-stmt (n i)
2918 (dolist (label (js2-labeled-stmt-node-labels n))
2919 (js2-print-ast label i))
2920 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2921
2922 (defun js2-labeled-stmt-node-contains (node label)
2923 "Return t if NODE contains LABEL in its label set.
2924 NODE is a `js2-labels-node'. LABEL is an identifier."
2925 (loop for nl in (js2-labeled-stmt-node-labels node)
2926 if (string= label (js2-label-node-name nl))
2927 return t
2928 finally return nil))
2929
2930 (defsubst js2-labeled-stmt-node-add-label (node label)
2931 "Add a `js2-label-node' to the label set for this statement."
2932 (setf (js2-labeled-stmt-node-labels node)
2933 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2934
2935 (defstruct (js2-jump-node
2936 (:include js2-node)
2937 (:constructor nil))
2938 "Abstract supertype of break and continue nodes."
2939 label ; `js2-name-node' for location of label identifier, if present
2940 target) ; target js2-labels-node or loop/switch statement
2941
2942 (defun js2-visit-jump-node (n v)
2943 ;; we don't visit the target, since it's a back-link
2944 (if (js2-jump-node-label n)
2945 (js2-visit-ast (js2-jump-node-label n) v)))
2946
2947 (defstruct (js2-break-node
2948 (:include js2-jump-node)
2949 (:constructor nil)
2950 (:constructor make-js2-break-node (&key (type js2-BREAK)
2951 (pos js2-ts-cursor)
2952 len
2953 label
2954 target)))
2955 "AST node for a break statement.
2956 The label field is a `js2-name-node', possibly nil, for the named label
2957 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2958 is the target of the break - a label node or enclosing loop/switch statement.")
2959
2960 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2961 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2962
2963 (defun js2-print-break-node (n i)
2964 (insert (js2-make-pad i) "break")
2965 (when (js2-break-node-label n)
2966 (insert " ")
2967 (js2-print-ast (js2-break-node-label n) 0))
2968 (insert ";\n"))
2969
2970 (defstruct (js2-continue-node
2971 (:include js2-jump-node)
2972 (:constructor nil)
2973 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2974 (pos js2-ts-cursor)
2975 len
2976 label
2977 target)))
2978 "AST node for a continue statement.
2979 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2980 It is nil if continue specifies no label. The target field is the jump target:
2981 a `js2-label-node' or the innermost enclosing loop.")
2982
2983 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2984 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2985
2986 (defun js2-print-continue-node (n i)
2987 (insert (js2-make-pad i) "continue")
2988 (when (js2-continue-node-label n)
2989 (insert " ")
2990 (js2-print-ast (js2-continue-node-label n) 0))
2991 (insert ";\n"))
2992
2993 (defstruct (js2-function-node
2994 (:include js2-script-node)
2995 (:constructor nil)
2996 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2997 (pos js2-ts-cursor)
2998 len
2999 (ftype 'FUNCTION)
3000 (form 'FUNCTION_STATEMENT)
3001 (name "")
3002 params
3003 body
3004 lp
3005 rp)))
3006 "AST node for a function declaration.
3007 The `params' field is a lisp list of nodes. Each node is either a simple
3008 `js2-name-node', or if it's a destructuring-assignment parameter, a
3009 `js2-array-node' or `js2-object-node'."
3010 ftype ; FUNCTION, GETTER or SETTER
3011 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3012 name ; function name (a `js2-name-node', or nil if anonymous)
3013 params ; a lisp list of destructuring forms or simple name nodes
3014 body ; a `js2-block-node' or expression node (1.8 only)
3015 lp ; position of arg-list open-paren, or nil if omitted
3016 rp ; position of arg-list close-paren, or nil if omitted
3017 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3018 needs-activation ; t if we need an activation object for this frame
3019 is-generator ; t if this function contains a yield
3020 member-expr) ; nonstandard Ecma extension from Rhino
3021
3022 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3023 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3024
3025 (defun js2-visit-function-node (n v)
3026 (if (js2-function-node-name n)
3027 (js2-visit-ast (js2-function-node-name n) v))
3028 (dolist (p (js2-function-node-params n))
3029 (js2-visit-ast p v))
3030 (when (js2-function-node-body n)
3031 (js2-visit-ast (js2-function-node-body n) v)))
3032
3033 (defun js2-print-function-node (n i)
3034 (let ((pad (js2-make-pad i))
3035 (getter (js2-node-get-prop n 'GETTER_SETTER))
3036 (name (js2-function-node-name n))
3037 (params (js2-function-node-params n))
3038 (body (js2-function-node-body n))
3039 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3040 (unless getter
3041 (insert pad "function"))
3042 (when name
3043 (insert " ")
3044 (js2-print-ast name 0))
3045 (insert "(")
3046 (loop with len = (length params)
3047 for param in params
3048 for count from 1
3049 do
3050 (js2-print-ast param 0)
3051 (if (< count len)
3052 (insert ", ")))
3053 (insert ") {")
3054 (unless expr
3055 (insert "\n"))
3056 ;; TODO: fix this to be smarter about indenting, etc.
3057 (js2-print-body body (1+ i))
3058 (insert pad "}")
3059 (unless expr
3060 (insert "\n"))))
3061
3062 (defsubst js2-function-name (node)
3063 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3064 (and (js2-function-node-name node)
3065 (js2-name-node-name (js2-function-node-name node))))
3066
3067 ;; Having this be an expression node makes it more flexible.
3068 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3069 ;; that work better if you assume it's an expression. Whenever we have
3070 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3071 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3072 (defstruct (js2-var-decl-node
3073 (:include js2-node)
3074 (:constructor nil)
3075 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3076 (pos js2-token-beg)
3077 len
3078 kids
3079 decl-type)))
3080 "AST node for a variable declaration list (VAR, CONST or LET).
3081 The node bounds differ depending on the declaration type. For VAR or
3082 CONST declarations, the bounds include the var/const keyword. For LET
3083 declarations, the node begins at the position of the first child."
3084 kids ; a lisp list of `js2-var-init-node' structs.
3085 decl-type) ; js2-VAR, js2-CONST or js2-LET
3086
3087 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3088 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3089
3090 (defun js2-visit-var-decl (n v)
3091 (dolist (kid (js2-var-decl-node-kids n))
3092 (js2-visit-ast kid v)))
3093
3094 (defun js2-print-var-decl (n i)
3095 (let ((pad (js2-make-pad i))
3096 (tt (js2-var-decl-node-decl-type n)))
3097 (insert pad)
3098 (insert (cond
3099 ((= tt js2-VAR) "var ")
3100 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3101 ((= tt js2-CONST) "const ")
3102 (t
3103 (error "malformed var-decl node"))))
3104 (loop with kids = (js2-var-decl-node-kids n)
3105 with len = (length kids)
3106 for kid in kids
3107 for count from 1
3108 do
3109 (js2-print-ast kid 0)
3110 (if (< count len)
3111 (insert ", ")))))
3112
3113 (defstruct (js2-var-init-node
3114 (:include js2-node)
3115 (:constructor nil)
3116 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3117 (pos js2-ts-cursor)
3118 len
3119 target
3120 initializer)))
3121 "AST node for a variable declaration.
3122 The type field will be js2-CONST for a const decl."
3123 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3124 initializer) ; initializer expression, a `js2-node'
3125
3126 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3127 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3128
3129 (defun js2-visit-var-init-node (n v)
3130 (js2-visit-ast (js2-var-init-node-target n) v)
3131 (if (js2-var-init-node-initializer n)
3132 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3133
3134 (defun js2-print-var-init-node (n i)
3135 (let ((pad (js2-make-pad i))
3136 (name (js2-var-init-node-target n))
3137 (init (js2-var-init-node-initializer n)))
3138 (insert pad)
3139 (js2-print-ast name 0)
3140 (when init
3141 (insert " = ")
3142 (js2-print-ast init 0))))
3143
3144 (defstruct (js2-cond-node
3145 (:include js2-node)
3146 (:constructor nil)
3147 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3148 (pos js2-ts-cursor)
3149 len
3150 test-expr
3151 true-expr
3152 false-expr
3153 q-pos
3154 c-pos)))
3155 "AST node for the ternary operator"
3156 test-expr
3157 true-expr
3158 false-expr
3159 q-pos ; buffer position of ?
3160 c-pos) ; buffer position of :
3161
3162 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3163 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3164
3165 (defun js2-visit-cond-node (n v)
3166 (js2-visit-ast (js2-cond-node-test-expr n) v)
3167 (js2-visit-ast (js2-cond-node-true-expr n) v)
3168 (js2-visit-ast (js2-cond-node-false-expr n) v))
3169
3170 (defun js2-print-cond-node (n i)
3171 (let ((pad (js2-make-pad i)))
3172 (insert pad)
3173 (js2-print-ast (js2-cond-node-test-expr n) 0)
3174 (insert " ? ")
3175 (js2-print-ast (js2-cond-node-true-expr n) 0)
3176 (insert " : ")
3177 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3178
3179 (defstruct (js2-infix-node
3180 (:include js2-node)
3181 (:constructor nil)
3182 (:constructor make-js2-infix-node (&key type
3183 (pos js2-ts-cursor)
3184 len
3185 op-pos
3186 left
3187 right)))
3188 "Represents infix expressions.
3189 Includes assignment ops like `|=', and the comma operator.
3190 The type field inherited from `js2-node' holds the operator."
3191 op-pos ; buffer position where operator begins
3192 left ; any `js2-node'
3193 right) ; any `js2-node'
3194
3195 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3196 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3197
3198 (defun js2-visit-infix-node (n v)
3199 (when (js2-infix-node-left n)
3200 (js2-visit-ast (js2-infix-node-left n) v))
3201 (when (js2-infix-node-right n)
3202 (js2-visit-ast (js2-infix-node-right n) v)))
3203
3204 (defconst js2-operator-tokens
3205 (let ((table (make-hash-table :test 'eq))
3206 (tokens
3207 (list (cons js2-IN "in")
3208 (cons js2-TYPEOF "typeof")
3209 (cons js2-INSTANCEOF "instanceof")
3210 (cons js2-DELPROP "delete")
3211 (cons js2-COMMA ",")
3212 (cons js2-COLON ":")
3213 (cons js2-OR "||")
3214 (cons js2-AND "&&")
3215 (cons js2-INC "++")
3216 (cons js2-DEC "--")
3217 (cons js2-BITOR "|")
3218 (cons js2-BITXOR "^")
3219 (cons js2-BITAND "&")
3220 (cons js2-EQ "==")
3221 (cons js2-NE "!=")
3222 (cons js2-LT "<")
3223 (cons js2-LE "<=")
3224 (cons js2-GT ">")
3225 (cons js2-GE ">=")
3226 (cons js2-LSH "<<")
3227 (cons js2-RSH ">>")
3228 (cons js2-URSH ">>>")
3229 (cons js2-ADD "+") ; infix plus
3230 (cons js2-SUB "-") ; infix minus
3231 (cons js2-MUL "*")
3232 (cons js2-DIV "/")
3233 (cons js2-MOD "%")
3234 (cons js2-NOT "!")
3235 (cons js2-BITNOT "~")
3236 (cons js2-POS "+") ; unary plus
3237 (cons js2-NEG "-") ; unary minus
3238 (cons js2-SHEQ "===") ; shallow equality
3239 (cons js2-SHNE "!==") ; shallow inequality
3240 (cons js2-ASSIGN "=")
3241 (cons js2-ASSIGN_BITOR "|=")
3242 (cons js2-ASSIGN_BITXOR "^=")
3243 (cons js2-ASSIGN_BITAND "&=")
3244 (cons js2-ASSIGN_LSH "<<=")
3245 (cons js2-ASSIGN_RSH ">>=")
3246 (cons js2-ASSIGN_URSH ">>>=")
3247 (cons js2-ASSIGN_ADD "+=")
3248 (cons js2-ASSIGN_SUB "-=")
3249 (cons js2-ASSIGN_MUL "*=")
3250 (cons js2-ASSIGN_DIV "/=")
3251 (cons js2-ASSIGN_MOD "%="))))
3252 (loop for (k . v) in tokens do
3253 (puthash k v table))
3254 table))
3255
3256 (defun js2-print-infix-node (n i)
3257 (let* ((tt (js2-node-type n))
3258 (op (gethash tt js2-operator-tokens)))
3259 (unless op
3260 (error "unrecognized infix operator %s" (js2-node-type n)))
3261 (insert (js2-make-pad i))
3262 (js2-print-ast (js2-infix-node-left n) 0)
3263 (unless (= tt js2-COMMA)
3264 (insert " "))
3265 (insert op)
3266 (insert " ")
3267 (js2-print-ast (js2-infix-node-right n) 0)))
3268
3269 (defstruct (js2-assign-node
3270 (:include js2-infix-node)
3271 (:constructor nil)
3272 (:constructor make-js2-assign-node (&key type
3273 (pos js2-ts-cursor)
3274 len
3275 op-pos
3276 left
3277 right)))
3278 "Represents any assignment.
3279 The type field holds the actual assignment operator.")
3280
3281 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3282 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3283
3284 (defstruct (js2-unary-node
3285 (:include js2-node)
3286 (:constructor nil)
3287 (:constructor make-js2-unary-node (&key type ; required
3288 (pos js2-ts-cursor)
3289 len
3290 operand)))
3291 "AST node type for unary operator nodes.
3292 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3293 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3294 property is added if the operator follows the operand."
3295 operand) ; a `js2-node' expression
3296
3297 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3298 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3299
3300 (defun js2-visit-unary-node (n v)
3301 (js2-visit-ast (js2-unary-node-operand n) v))
3302
3303 (defun js2-print-unary-node (n i)
3304 (let* ((tt (js2-node-type n))
3305 (op (gethash tt js2-operator-tokens))
3306 (postfix (js2-node-get-prop n 'postfix)))
3307 (unless op
3308 (error "unrecognized unary operator %s" tt))
3309 (insert (js2-make-pad i))
3310 (unless postfix
3311 (insert op))
3312 (if (or (= tt js2-TYPEOF)
3313 (= tt js2-DELPROP))
3314 (insert " "))
3315 (js2-print-ast (js2-unary-node-operand n) 0)
3316 (when postfix
3317 (insert op))))
3318
3319 (defstruct (js2-let-node
3320 (:include js2-scope)
3321 (:constructor nil)
3322 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3323 (pos js2-token-beg)
3324 len
3325 vars
3326 body
3327 lp
3328 rp)))
3329 "AST node for a let expression or a let statement.
3330 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3331 vars ; a `js2-var-decl-node'
3332 body ; a `js2-node' representing the expression or body block
3333 lp
3334 rp)
3335
3336 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3337 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3338
3339 (defun js2-visit-let-node (n v)
3340 (when (js2-let-node-vars n)
3341 (js2-visit-ast (js2-let-node-vars n) v))
3342 (when (js2-let-node-body n)
3343 (js2-visit-ast (js2-let-node-body n) v)))
3344
3345 (defun js2-print-let-node (n i)
3346 (insert (js2-make-pad i) "let (")
3347 (js2-print-ast (js2-let-node-vars n) 0)
3348 (insert ") ")
3349 (js2-print-ast (js2-let-node-body n) i))
3350
3351 (defstruct (js2-keyword-node
3352 (:include js2-node)
3353 (:constructor nil)
3354 (:constructor make-js2-keyword-node (&key type
3355 (pos js2-token-beg)
3356 (len (- js2-ts-cursor pos)))))
3357 "AST node representing a literal keyword such as `null'.
3358 Used for `null', `this', `true', `false' and `debugger'.
3359 The node type is set to js2-NULL, js2-THIS, etc.")
3360
3361 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3362 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3363
3364 (defun js2-print-keyword-node (n i)
3365 (insert (js2-make-pad i)
3366 (let ((tt (js2-node-type n)))
3367 (cond
3368 ((= tt js2-THIS) "this")
3369 ((= tt js2-NULL) "null")
3370 ((= tt js2-TRUE) "true")
3371 ((= tt js2-FALSE) "false")
3372 ((= tt js2-DEBUGGER) "debugger")
3373 (t (error "Invalid keyword literal type: %d" tt))))))
3374
3375 (defsubst js2-this-node-p (node)
3376 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3377 (eq (js2-node-type node) js2-THIS))
3378
3379 (defstruct (js2-new-node
3380 (:include js2-node)
3381 (:constructor nil)
3382 (:constructor make-js2-new-node (&key (type js2-NEW)
3383 (pos js2-token-beg)
3384 len
3385 target
3386 args
3387 initializer
3388 lp
3389 rp)))
3390 "AST node for new-expression such as new Foo()."
3391 target ; an identifier or reference
3392 args ; a lisp list of argument nodes
3393 lp ; position of left-paren, nil if omitted
3394 rp ; position of right-paren, nil if omitted
3395 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3396
3397 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3398 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3399
3400 (defun js2-visit-new-node (n v)
3401 (js2-visit-ast (js2-new-node-target n) v)
3402 (dolist (arg (js2-new-node-args n))
3403 (js2-visit-ast arg v))
3404 (when (js2-new-node-initializer n)
3405 (js2-visit-ast (js2-new-node-initializer n) v)))
3406
3407 (defun js2-print-new-node (n i)
3408 (insert (js2-make-pad i) "new ")
3409 (js2-print-ast (js2-new-node-target n))
3410 (insert "(")
3411 (js2-print-list (js2-new-node-args n))
3412 (insert ")")
3413 (when (js2-new-node-initializer n)
3414 (insert " ")
3415 (js2-print-ast (js2-new-node-initializer n))))
3416
3417 (defstruct (js2-name-node
3418 (:include js2-node)
3419 (:constructor nil)
3420 (:constructor make-js2-name-node (&key (type js2-NAME)
3421 (pos js2-token-beg)
3422 (len (- js2-ts-cursor
3423 js2-token-beg))
3424 (name js2-ts-string))))
3425 "AST node for a JavaScript identifier"
3426 name ; a string
3427 scope) ; a `js2-scope' (optional, used for codegen)
3428
3429 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3430 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3431
3432 (defun js2-print-name-node (n i)
3433 (insert (js2-make-pad i)
3434 (js2-name-node-name n)))
3435
3436 (defsubst js2-name-node-length (node)
3437 "Return identifier length of NODE, a `js2-name-node'.
3438 Returns 0 if NODE is nil or its identifier field is nil."
3439 (if node
3440 (length (js2-name-node-name node))
3441 0))
3442
3443 (defstruct (js2-number-node
3444 (:include js2-node)
3445 (:constructor nil)
3446 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3447 (pos js2-token-beg)
3448 (len (- js2-ts-cursor
3449 js2-token-beg))
3450 (value js2-ts-string)
3451 (num-value js2-ts-number))))
3452 "AST node for a number literal."
3453 value ; the original string, e.g. "6.02e23"
3454 num-value) ; the parsed number value
3455
3456 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3457 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3458
3459 (defun js2-print-number-node (n i)
3460 (insert (js2-make-pad i)
3461 (number-to-string (js2-number-node-num-value n))))
3462
3463 (defstruct (js2-regexp-node
3464 (:include js2-node)
3465 (:constructor nil)
3466 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3467 (pos js2-token-beg)
3468 (len (- js2-ts-cursor
3469 js2-token-beg))
3470 value
3471 flags)))
3472 "AST node for a regular expression literal."
3473 value ; the regexp string, without // delimiters
3474 flags) ; a string of flags, e.g. `mi'.
3475
3476 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3477 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3478
3479 (defun js2-print-regexp (n i)
3480 (insert (js2-make-pad i)
3481 "/"
3482 (js2-regexp-node-value n)
3483 "/")
3484 (if (js2-regexp-node-flags n)
3485 (insert (js2-regexp-node-flags n))))
3486
3487 (defstruct (js2-string-node
3488 (:include js2-node)
3489 (:constructor nil)
3490 (:constructor make-js2-string-node (&key (type js2-STRING)
3491 (pos js2-token-beg)
3492 (len (- js2-ts-cursor
3493 js2-token-beg))
3494 (value js2-ts-string))))
3495 "String literal.
3496 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3497 You can tell the quote type by looking at the first character."
3498 value) ; the characters of the string, including the quotes
3499
3500 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3501 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3502
3503 (defun js2-print-string-node (n i)
3504 (insert (js2-make-pad i)
3505 (js2-node-string n)))
3506
3507 (defstruct (js2-array-node
3508 (:include js2-node)
3509 (:constructor nil)
3510 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3511 (pos js2-ts-cursor)
3512 len
3513 elems)))
3514 "AST node for an array literal."
3515 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3516
3517 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3518 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3519
3520 (defun js2-visit-array-node (n v)
3521 (dolist (e (js2-array-node-elems n))
3522 (when e ; can be nil, e.g. [a, ,b]
3523 (js2-visit-ast e v))))
3524
3525 (defun js2-print-array-node (n i)
3526 (insert (js2-make-pad i) "[")
3527 (js2-print-list (js2-array-node-elems n))
3528 (insert "]"))
3529
3530 (defstruct (js2-object-node
3531 (:include js2-node)
3532 (:constructor nil)
3533 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3534 (pos js2-ts-cursor)
3535 len
3536 elems)))
3537 "AST node for an object literal expression.
3538 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3539 the latter represents abbreviation in destructuring expressions."
3540 elems)
3541
3542 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3543 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3544
3545 (defun js2-visit-object-node (n v)
3546 (dolist (e (js2-object-node-elems n))
3547 (js2-visit-ast e v)))
3548
3549 (defun js2-print-object-node (n i)
3550 (insert (js2-make-pad i) "{")
3551 (js2-print-list (js2-object-node-elems n))
3552 (insert "}"))
3553
3554 (defstruct (js2-object-prop-node
3555 (:include js2-infix-node)
3556 (:constructor nil)
3557 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3558 (pos js2-ts-cursor)
3559 len
3560 left
3561 right
3562 op-pos)))
3563 "AST node for an object literal prop:value entry.
3564 The `left' field is the property: a name node, string node or number node.
3565 The `right' field is a `js2-node' representing the initializer value.")
3566
3567 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3568 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3569
3570 (defun js2-print-object-prop-node (n i)
3571 (insert (js2-make-pad i))
3572 (js2-print-ast (js2-object-prop-node-left n) 0)
3573 (insert ":")
3574 (js2-print-ast (js2-object-prop-node-right n) 0))
3575
3576 (defstruct (js2-getter-setter-node
3577 (:include js2-infix-node)
3578 (:constructor nil)
3579 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3580 (pos js2-ts-cursor)
3581 len
3582 left
3583 right)))
3584 "AST node for a getter/setter property in an object literal.
3585 The `left' field is the `js2-name-node' naming the getter/setter prop.
3586 The `right' field is always an anonymous `js2-function-node' with a node
3587 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3588
3589 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3590 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3591
3592 (defun js2-print-getter-setter (n i)
3593 (let ((pad (js2-make-pad i))
3594 (left (js2-getter-setter-node-left n))
3595 (right (js2-getter-setter-node-right n)))
3596 (insert pad)
3597 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3598 (js2-print-ast left 0)
3599 (js2-print-ast right 0)))
3600
3601 (defstruct (js2-prop-get-node
3602 (:include js2-infix-node)
3603 (:constructor nil)
3604 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3605 (pos js2-ts-cursor)
3606 len
3607 left
3608 right)))
3609 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3610
3611 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3612 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3613
3614 (defun js2-visit-prop-get-node (n v)
3615 (when (js2-prop-get-node-left n)
3616 (js2-visit-ast (js2-prop-get-node-left n) v))
3617 (when (js2-prop-get-node-right n)
3618 (js2-visit-ast (js2-prop-get-node-right n) v)))
3619
3620 (defun js2-print-prop-get-node (n i)
3621 (insert (js2-make-pad i))
3622 (js2-print-ast (js2-prop-get-node-left n) 0)
3623 (insert ".")
3624 (js2-print-ast (js2-prop-get-node-right n) 0))
3625
3626 (defstruct (js2-elem-get-node
3627 (:include js2-node)
3628 (:constructor nil)
3629 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3630 (pos js2-ts-cursor)
3631 len
3632 target
3633 element
3634 lb
3635 rb)))
3636 "AST node for an array index expression such as foo[bar]."
3637 target ; a `js2-node' - the expression preceding the "."
3638 element ; a `js2-node' - the expression in brackets
3639 lb ; position of left-bracket, nil if omitted
3640 rb) ; position of right-bracket, nil if omitted
3641
3642 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3643 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3644
3645 (defun js2-visit-elem-get-node (n v)
3646 (when (js2-elem-get-node-target n)
3647 (js2-visit-ast (js2-elem-get-node-target n) v))
3648 (when (js2-elem-get-node-element n)
3649 (js2-visit-ast (js2-elem-get-node-element n) v)))
3650
3651 (defun js2-print-elem-get-node (n i)
3652 (insert (js2-make-pad i))
3653 (js2-print-ast (js2-elem-get-node-target n) 0)
3654 (insert "[")
3655 (js2-print-ast (js2-elem-get-node-element n) 0)
3656 (insert "]"))
3657
3658 (defstruct (js2-call-node
3659 (:include js2-node)
3660 (:constructor nil)
3661 (:constructor make-js2-call-node (&key (type js2-CALL)
3662 (pos js2-ts-cursor)
3663 len
3664 target
3665 args
3666 lp
3667 rp)))
3668 "AST node for a JavaScript function call."
3669 target ; a `js2-node' evaluating to the function to call
3670 args ; a lisp list of `js2-node' arguments
3671 lp ; position of open-paren, or nil if missing
3672 rp) ; position of close-paren, or nil if missing
3673
3674 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3675 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3676
3677 (defun js2-visit-call-node (n v)
3678 (js2-visit-ast (js2-call-node-target n) v)
3679 (dolist (arg (js2-call-node-args n))
3680 (js2-visit-ast arg v)))
3681
3682 (defun js2-print-call-node (n i)
3683 (insert (js2-make-pad i))
3684 (js2-print-ast (js2-call-node-target n) 0)
3685 (insert "(")
3686 (js2-print-list (js2-call-node-args n))
3687 (insert ")"))
3688
3689 (defstruct (js2-yield-node
3690 (:include js2-node)
3691 (:constructor nil)
3692 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3693 (pos js2-ts-cursor)
3694 len
3695 value)))
3696 "AST node for yield statement or expression."
3697 value) ; optional: value to be yielded
3698
3699 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3700 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3701
3702 (defun js2-visit-yield-node (n v)
3703 (js2-visit-ast (js2-yield-node-value n) v))
3704
3705 (defun js2-print-yield-node (n i)
3706 (insert (js2-make-pad i))
3707 (insert "yield")
3708 (when (js2-yield-node-value n)
3709 (insert " ")
3710 (js2-print-ast (js2-yield-node-value n) 0)))
3711
3712 (defstruct (js2-paren-node
3713 (:include js2-node)
3714 (:constructor nil)
3715 (:constructor make-js2-paren-node (&key (type js2-LP)
3716 (pos js2-ts-cursor)
3717 len
3718 expr)))
3719 "AST node for a parenthesized expression.
3720 In particular, used when the parens are syntactically optional,
3721 as opposed to required parens such as those enclosing an if-conditional."
3722 expr) ; `js2-node'
3723
3724 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3725 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3726
3727 (defun js2-visit-paren-node (n v)
3728 (js2-visit-ast (js2-paren-node-expr n) v))
3729
3730 (defun js2-print-paren-node (n i)
3731 (insert (js2-make-pad i))
3732 (insert "(")
3733 (js2-print-ast (js2-paren-node-expr n) 0)
3734 (insert ")"))
3735
3736 (defstruct (js2-array-comp-node
3737 (:include js2-scope)
3738 (:constructor nil)
3739 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3740 (pos js2-ts-cursor)
3741 len
3742 result
3743 loops
3744 filter
3745 if-pos
3746 lp
3747 rp)))
3748 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3749 result ; result expression (just after left-bracket)
3750 loops ; a lisp list of `js2-array-comp-loop-node'
3751 filter ; guard/filter expression
3752 if-pos ; buffer pos of 'if' keyword, if present, else nil
3753 lp ; buffer position of if-guard left-paren, or nil if not present
3754 rp) ; buffer position of if-guard right-paren, or nil if not present
3755
3756 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3757 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3758
3759 (defun js2-visit-array-comp-node (n v)
3760 (js2-visit-ast (js2-array-comp-node-result n) v)
3761 (dolist (l (js2-array-comp-node-loops n))
3762 (js2-visit-ast l v))
3763 (if (js2-array-comp-node-filter n)
3764 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3765
3766 (defun js2-print-array-comp-node (n i)
3767 (let ((pad (js2-make-pad i))
3768 (result (js2-array-comp-node-result n))
3769 (loops (js2-array-comp-node-loops n))
3770 (filter (js2-array-comp-node-filter n)))
3771 (insert pad "[")
3772 (js2-print-ast result 0)
3773 (dolist (l loops)
3774 (insert " ")
3775 (js2-print-ast l 0))
3776 (when filter
3777 (insert " if (")
3778 (js2-print-ast filter 0))
3779 (insert ")]")))
3780
3781 (defstruct (js2-array-comp-loop-node
3782 (:include js2-for-in-node)
3783 (:constructor nil)
3784 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3785 (pos js2-ts-cursor)
3786 len
3787 iterator
3788 object
3789 in-pos
3790 foreach-p
3791 each-pos
3792 lp
3793 rp)))
3794 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3795
3796 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3797 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3798
3799 (defun js2-visit-array-comp-loop (n v)
3800 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3801 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3802
3803 (defun js2-print-array-comp-loop (n i)
3804 (insert "for (")
3805 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3806 (insert " in ")
3807 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3808 (insert ")"))
3809
3810 (defstruct (js2-empty-expr-node
3811 (:include js2-node)
3812 (:constructor nil)
3813 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3814 (pos js2-token-beg)
3815 len)))
3816 "AST node for an empty expression.")
3817
3818 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3819 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3820
3821 (defstruct (js2-xml-node
3822 (:include js2-block-node)
3823 (:constructor nil)
3824 (:constructor make-js2-xml-node (&key (type js2-XML)
3825 (pos js2-token-beg)
3826 len
3827 kids)))
3828 "AST node for initial parse of E4X literals.
3829 The kids field is a list of XML fragments, each a `js2-string-node' or
3830 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3831
3832 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3833 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3834
3835 (defun js2-print-xml-node (n i)
3836 (dolist (kid (js2-xml-node-kids n))
3837 (js2-print-ast kid i)))
3838
3839 (defstruct (js2-xml-js-expr-node
3840 (:include js2-xml-node)
3841 (:constructor nil)
3842 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3843 (pos js2-ts-cursor)
3844 len
3845 expr)))
3846 "AST node for an embedded JavaScript {expression} in an E4X literal.
3847 The start and end fields correspond to the curly-braces."
3848 expr) ; a `js2-expr-node' of some sort
3849
3850 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3851 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3852
3853 (defun js2-visit-xml-js-expr (n v)
3854 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3855
3856 (defun js2-print-xml-js-expr (n i)
3857 (insert (js2-make-pad i))
3858 (insert "{")
3859 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3860 (insert "}"))
3861
3862 (defstruct (js2-xml-dot-query-node
3863 (:include js2-infix-node)
3864 (:constructor nil)
3865 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3866 (pos js2-ts-cursor)
3867 op-pos
3868 len
3869 left
3870 right
3871 rp)))
3872 "AST node for an E4X foo.(bar) filter expression.
3873 Note that the left-paren is automatically the character immediately
3874 following the dot (.) in the operator. No whitespace is permitted
3875 between the dot and the lp by the scanner."
3876 rp)
3877
3878 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3879 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3880
3881 (defun js2-print-xml-dot-query (n i)
3882 (insert (js2-make-pad i))
3883 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3884 (insert ".(")
3885 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3886 (insert ")"))
3887
3888 (defstruct (js2-xml-ref-node
3889 (:include js2-node)
3890 (:constructor nil)) ; abstract
3891 "Base type for E4X XML attribute-access or property-get expressions.
3892 Such expressions can take a variety of forms. The general syntax has
3893 three parts:
3894
3895 - (optional) an @ (specifying an attribute access)
3896 - (optional) a namespace (a `js2-name-node') and double-colon
3897 - (required) either a `js2-name-node' or a bracketed [expression]
3898
3899 The property-name expressions (examples: ns::name, @name) are
3900 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3901 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3902
3903 This node type (or more specifically, its subclasses) will sometimes
3904 be the right-hand child of a `js2-prop-get-node' or a
3905 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3906 The `js2-xml-ref-node' may also be a standalone primary expression with
3907 no explicit target, which is valid in certain expression contexts such as
3908
3909 company..employee.(@id < 100)
3910
3911 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3912 expression whose parent is a `js2-xml-dot-query-node'."
3913 namespace
3914 at-pos
3915 colon-pos)
3916
3917 (defsubst js2-xml-ref-node-attr-access-p (node)
3918 "Return non-nil if this expression began with an @-token."
3919 (and (numberp (js2-xml-ref-node-at-pos node))
3920 (plusp (js2-xml-ref-node-at-pos node))))
3921
3922 (defstruct (js2-xml-prop-ref-node
3923 (:include js2-xml-ref-node)
3924 (:constructor nil)
3925 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3926 (pos js2-token-beg)
3927 len
3928 propname
3929 namespace
3930 at-pos
3931 colon-pos)))
3932 "AST node for an E4X XML [expr] property-ref expression.
3933 The JavaScript syntax is an optional @, an optional ns::, and a name.
3934
3935 [ '@' ] [ name '::' ] name
3936
3937 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3938 @ns::*, @*::attr, @*::*, and @*.
3939
3940 The node starts at the @ token, if present. Otherwise it starts at the
3941 namespace name. The node bounds extend through the closing right-bracket,
3942 or if it is missing due to a syntax error, through the end of the index
3943 expression."
3944 propname)
3945
3946 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3947 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3948
3949 (defun js2-visit-xml-prop-ref-node (n v)
3950 (if (js2-xml-prop-ref-node-namespace n)
3951 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3952 (if (js2-xml-prop-ref-node-propname n)
3953 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3954
3955 (defun js2-print-xml-prop-ref-node (n i)
3956 (insert (js2-make-pad i))
3957 (if (js2-xml-ref-node-attr-access-p n)
3958 (insert "@"))
3959 (when (js2-xml-prop-ref-node-namespace n)
3960 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3961 (insert "::"))
3962 (if (js2-xml-prop-ref-node-propname n)
3963 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3964
3965 (defstruct (js2-xml-elem-ref-node
3966 (:include js2-xml-ref-node)
3967 (:constructor nil)
3968 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3969 (pos js2-token-beg)
3970 len
3971 expr
3972 lb
3973 rb
3974 namespace
3975 at-pos
3976 colon-pos)))
3977 "AST node for an E4X XML [expr] member-ref expression.
3978 Syntax:
3979
3980 [ '@' ] [ name '::' ] '[' expr ']'
3981
3982 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3983
3984 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3985 is not a legal E4X XML element-ref expression, since it's already used
3986 for standard JavaScript element-get array indexing. Hence, a
3987 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3988 non-nil namespace node, or both.
3989
3990 The node starts at the @ token, if present. Otherwise it starts
3991 at the namespace name. The node bounds extend through the closing
3992 right-bracket, or if it is missing due to a syntax error, through the
3993 end of the index expression."
3994 expr ; the bracketed index expression
3995 lb
3996 rb)
3997
3998 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3999 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4000
4001 (defun js2-visit-xml-elem-ref-node (n v)
4002 (if (js2-xml-elem-ref-node-namespace n)
4003 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
4004 (if (js2-xml-elem-ref-node-expr n)
4005 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
4006
4007 (defun js2-print-xml-elem-ref-node (n i)
4008 (insert (js2-make-pad i))
4009 (if (js2-xml-ref-node-attr-access-p n)
4010 (insert "@"))
4011 (when (js2-xml-elem-ref-node-namespace n)
4012 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4013 (insert "::"))
4014 (insert "[")
4015 (if (js2-xml-elem-ref-node-expr n)
4016 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4017 (insert "]"))
4018
4019 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4020
4021 (defstruct (js2-xml-start-tag-node
4022 (:include js2-xml-node)
4023 (:constructor nil)
4024 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4025 (pos js2-ts-cursor)
4026 len
4027 name
4028 attrs
4029 kids
4030 empty-p)))
4031 "AST node for an XML start-tag. Not currently used.
4032 The `kids' field is a lisp list of child content nodes."
4033 name ; a `js2-xml-name-node'
4034 attrs ; a lisp list of `js2-xml-attr-node'
4035 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4036
4037 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4038 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4039
4040 (defun js2-visit-xml-start-tag (n v)
4041 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4042 (dolist (attr (js2-xml-start-tag-node-attrs n))
4043 (js2-visit-ast attr v))
4044 (js2-visit-block n v))
4045
4046 (defun js2-print-xml-start-tag (n i)
4047 (insert (js2-make-pad i) "<")
4048 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4049 (when (js2-xml-start-tag-node-attrs n)
4050 (insert " ")
4051 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4052 (insert ">"))
4053
4054 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4055 ;; and add the end-tag to the kids list of the parent as well.
4056 (defstruct (js2-xml-end-tag-node
4057 (:include js2-xml-node)
4058 (:constructor nil)
4059 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4060 (pos js2-ts-cursor)
4061 len
4062 name)))
4063 "AST node for an XML end-tag. Not currently used."
4064 name) ; a `js2-xml-name-node'
4065
4066 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4067 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4068
4069 (defun js2-visit-xml-end-tag (n v)
4070 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4071
4072 (defun js2-print-xml-end-tag (n i)
4073 (insert (js2-make-pad i))
4074 (insert "</")
4075 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4076 (insert ">"))
4077
4078 (defstruct (js2-xml-name-node
4079 (:include js2-xml-node)
4080 (:constructor nil)
4081 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4082 (pos js2-ts-cursor)
4083 len
4084 namespace
4085 kids)))
4086 "AST node for an E4X XML name. Not currently used.
4087 Any XML name can be qualified with a namespace, hence the namespace field.
4088 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4089 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4090 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4091 namespace) ; a `js2-string-node'
4092
4093 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4094 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4095
4096 (defun js2-visit-xml-name-node (n v)
4097 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4098
4099 (defun js2-print-xml-name-node (n i)
4100 (insert (js2-make-pad i))
4101 (when (js2-xml-name-node-namespace n)
4102 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4103 (insert "::"))
4104 (dolist (kid (js2-xml-name-node-kids n))
4105 (js2-print-ast kid 0)))
4106
4107 (defstruct (js2-xml-pi-node
4108 (:include js2-xml-node)
4109 (:constructor nil)
4110 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4111 (pos js2-ts-cursor)
4112 len
4113 name
4114 attrs)))
4115 "AST node for an E4X XML processing instruction. Not currently used."
4116 name ; a `js2-xml-name-node'
4117 attrs) ; a list of `js2-xml-attr-node'
4118
4119 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4120 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4121
4122 (defun js2-visit-xml-pi-node (n v)
4123 (js2-visit-ast (js2-xml-pi-node-name n) v)
4124 (dolist (attr (js2-xml-pi-node-attrs n))
4125 (js2-visit-ast attr v)))
4126
4127 (defun js2-print-xml-pi-node (n i)
4128 (insert (js2-make-pad i) "<?")
4129 (js2-print-ast (js2-xml-pi-node-name n))
4130 (when (js2-xml-pi-node-attrs n)
4131 (insert " ")
4132 (js2-print-list (js2-xml-pi-node-attrs n)))
4133 (insert "?>"))
4134
4135 (defstruct (js2-xml-cdata-node
4136 (:include js2-xml-node)
4137 (:constructor nil)
4138 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4139 (pos js2-ts-cursor)
4140 len
4141 content)))
4142 "AST node for a CDATA escape section. Not currently used."
4143 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4144
4145 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4146 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4147
4148 (defun js2-visit-xml-cdata-node (n v)
4149 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4150
4151 (defun js2-print-xml-cdata-node (n i)
4152 (insert (js2-make-pad i))
4153 (js2-print-ast (js2-xml-cdata-node-content n)))
4154
4155 (defstruct (js2-xml-attr-node
4156 (:include js2-xml-node)
4157 (:constructor nil)
4158 (:constructor make-js2-attr-node (&key (type js2-XML)
4159 (pos js2-ts-cursor)
4160 len
4161 name
4162 value
4163 eq-pos
4164 quote-type)))
4165 "AST node representing a foo='bar' XML attribute value. Not yet used."
4166 name ; a `js2-xml-name-node'
4167 value ; a `js2-xml-name-node'
4168 eq-pos ; buffer position of "=" sign
4169 quote-type) ; 'single or 'double
4170
4171 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4172 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4173
4174 (defun js2-visit-xml-attr-node (n v)
4175 (js2-visit-ast (js2-xml-attr-node-name n) v)
4176 (js2-visit-ast (js2-xml-attr-node-value n) v))
4177
4178 (defun js2-print-xml-attr-node (n i)
4179 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4180 "'"
4181 "\"")))
4182 (insert (js2-make-pad i))
4183 (js2-print-ast (js2-xml-attr-node-name n) 0)
4184 (insert "=" quote)
4185 (js2-print-ast (js2-xml-attr-node-value n) 0)
4186 (insert quote)))
4187
4188 (defstruct (js2-xml-text-node
4189 (:include js2-xml-node)
4190 (:constructor nil)
4191 (:constructor make-js2-text-node (&key (type js2-XML)
4192 (pos js2-ts-cursor)
4193 len
4194 content)))
4195 "AST node for an E4X XML text node. Not currently used."
4196 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4197
4198 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4199 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4200
4201 (defun js2-visit-xml-text-node (n v)
4202 (js2-visit-ast (js2-xml-text-node-content n) v))
4203
4204 (defun js2-print-xml-text-node (n i)
4205 (insert (js2-make-pad i))
4206 (dolist (kid (js2-xml-text-node-content n))
4207 (js2-print-ast kid)))
4208
4209 (defstruct (js2-xml-comment-node
4210 (:include js2-xml-node)
4211 (:constructor nil)
4212 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4213 (pos js2-ts-cursor)
4214 len)))
4215 "AST node for E4X XML comment. Not currently used.")
4216
4217 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4218 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4219
4220 (defun js2-print-xml-comment (n i)
4221 (insert (js2-make-pad i)
4222 (js2-node-string n)))
4223
4224 ;;; Node utilities
4225
4226 (defsubst js2-node-line (n)
4227 "Fetch the source line number at the start of node N.
4228 This is O(n) in the length of the source buffer; use prudently."
4229 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4230
4231 (defsubst js2-block-node-kid (n i)
4232 "Return child I of node N, or nil if there aren't that many."
4233 (nth i (js2-block-node-kids n)))
4234
4235 (defsubst js2-block-node-first (n)
4236 "Return first child of block node N, or nil if there is none."
4237 (first (js2-block-node-kids n)))
4238
4239 (defun js2-node-root (n)
4240 "Return the root of the AST containing N.
4241 If N has no parent pointer, returns N."
4242 (let ((parent (js2-node-parent n)))
4243 (if parent
4244 (js2-node-root parent)
4245 n)))
4246
4247 (defun js2-node-position-in-parent (node &optional parent)
4248 "Return the position of NODE in parent's block-kids list.
4249 PARENT can be supplied if known. Positioned returned is zero-indexed.
4250 Returns 0 if NODE is not a child of a block statement, or if NODE
4251 is not a statement node."
4252 (let ((p (or parent (js2-node-parent node)))
4253 (i 0))
4254 (if (not (js2-block-node-p p))
4255 i
4256 (or (js2-position node (js2-block-node-kids p))
4257 0))))
4258
4259 (defsubst js2-node-short-name (n)
4260 "Return the short name of node N as a string, e.g. `js2-if-node'."
4261 (substring (symbol-name (aref n 0))
4262 (length "cl-struct-")))
4263
4264 (defsubst js2-node-child-list (node)
4265 "Return the child list for NODE, a lisp list of nodes.
4266 Works for block nodes, array nodes, obj literals, funarg lists,
4267 var decls and try nodes (for catch clauses). Note that you should call
4268 `js2-block-node-kids' on the function body for the body statements.
4269 Returns nil for zero-length child lists or unsupported nodes."
4270 (cond
4271 ((js2-function-node-p node)
4272 (js2-function-node-params node))
4273 ((js2-block-node-p node)
4274 (js2-block-node-kids node))
4275 ((js2-try-node-p node)
4276 (js2-try-node-catch-clauses node))
4277 ((js2-array-node-p node)
4278 (js2-array-node-elems node))
4279 ((js2-object-node-p node)
4280 (js2-object-node-elems node))
4281 ((js2-call-node-p node)
4282 (js2-call-node-args node))
4283 ((js2-new-node-p node)
4284 (js2-new-node-args node))
4285 ((js2-var-decl-node-p node)
4286 (js2-var-decl-node-kids node))
4287 (t
4288 nil)))
4289
4290 (defsubst js2-node-set-child-list (node kids)
4291 "Set the child list for NODE to KIDS."
4292 (cond
4293 ((js2-function-node-p node)
4294 (setf (js2-function-node-params node) kids))
4295 ((js2-block-node-p node)
4296 (setf (js2-block-node-kids node) kids))
4297 ((js2-try-node-p node)
4298 (setf (js2-try-node-catch-clauses node) kids))
4299 ((js2-array-node-p node)
4300 (setf (js2-array-node-elems node) kids))
4301 ((js2-object-node-p node)
4302 (setf (js2-object-node-elems node) kids))
4303 ((js2-call-node-p node)
4304 (setf (js2-call-node-args node) kids))
4305 ((js2-new-node-p node)
4306 (setf (js2-new-node-args node) kids))
4307 ((js2-var-decl-node-p node)
4308 (setf (js2-var-decl-node-kids node) kids))
4309 (t
4310 (error "Unsupported node type: %s" (js2-node-short-name node))))
4311 kids)
4312
4313 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4314 (defconst js2-paren-expr-nodes
4315 '(cl-struct-js2-array-comp-loop-node
4316 cl-struct-js2-array-comp-node
4317 cl-struct-js2-call-node
4318 cl-struct-js2-catch-node
4319 cl-struct-js2-do-node
4320 cl-struct-js2-elem-get-node
4321 cl-struct-js2-for-in-node
4322 cl-struct-js2-for-node
4323 cl-struct-js2-function-node
4324 cl-struct-js2-if-node
4325 cl-struct-js2-let-node
4326 cl-struct-js2-new-node
4327 cl-struct-js2-paren-node
4328 cl-struct-js2-switch-node
4329 cl-struct-js2-while-node
4330 cl-struct-js2-with-node
4331 cl-struct-js2-xml-dot-query-node)
4332 "Node types that can have a parenthesized child expression.
4333 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4334
4335 (defsubst js2-paren-expr-node-p (node)
4336 "Return t for nodes that typically have a parenthesized child expression.
4337 Useful for computing the indentation anchors for arg-lists and conditions.
4338 Note that it may return a false positive, for instance when NODE is
4339 a `js2-new-node' and there are no arguments or parentheses."
4340 (memq (aref node 0) js2-paren-expr-nodes))
4341
4342 ;; Fake polymorphism... yech.
4343 (defsubst js2-node-lp (node)
4344 "Return relative left-paren position for NODE, if applicable.
4345 For `js2-elem-get-node' structs, returns left-bracket position.
4346 Note that the position may be nil in the case of a parse error."
4347 (cond
4348 ((js2-elem-get-node-p node)
4349 (js2-elem-get-node-lb node))
4350 ((js2-loop-node-p node)
4351 (js2-loop-node-lp node))
4352 ((js2-function-node-p node)
4353 (js2-function-node-lp node))
4354 ((js2-if-node-p node)
4355 (js2-if-node-lp node))
4356 ((js2-new-node-p node)
4357 (js2-new-node-lp node))
4358 ((js2-call-node-p node)
4359 (js2-call-node-lp node))
4360 ((js2-paren-node-p node)
4361 (js2-node-pos node))
4362 ((js2-switch-node-p node)
4363 (js2-switch-node-lp node))
4364 ((js2-catch-node-p node)
4365 (js2-catch-node-lp node))
4366 ((js2-let-node-p node)
4367 (js2-let-node-lp node))
4368 ((js2-array-comp-node-p node)
4369 (js2-array-comp-node-lp node))
4370 ((js2-with-node-p node)
4371 (js2-with-node-lp node))
4372 ((js2-xml-dot-query-node-p node)
4373 (1+ (js2-infix-node-op-pos node)))
4374 (t
4375 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4376
4377 ;; Fake polymorphism... blech.
4378 (defsubst js2-node-rp (node)
4379 "Return relative right-paren position for NODE, if applicable.
4380 For `js2-elem-get-node' structs, returns right-bracket position.
4381 Note that the position may be nil in the case of a parse error."
4382 (cond
4383 ((js2-elem-get-node-p node)
4384 (js2-elem-get-node-lb node))
4385 ((js2-loop-node-p node)
4386 (js2-loop-node-rp node))
4387 ((js2-function-node-p node)
4388 (js2-function-node-rp node))
4389 ((js2-if-node-p node)
4390 (js2-if-node-rp node))
4391 ((js2-new-node-p node)
4392 (js2-new-node-rp node))
4393 ((js2-call-node-p node)
4394 (js2-call-node-rp node))
4395 ((js2-paren-node-p node)
4396 (+ (js2-node-pos node) (js2-node-len node)))
4397 ((js2-switch-node-p node)
4398 (js2-switch-node-rp node))
4399 ((js2-catch-node-p node)
4400 (js2-catch-node-rp node))
4401 ((js2-let-node-p node)
4402 (js2-let-node-rp node))
4403 ((js2-array-comp-node-p node)
4404 (js2-array-comp-node-rp node))
4405 ((js2-with-node-p node)
4406 (js2-with-node-rp node))
4407 ((js2-xml-dot-query-node-p node)
4408 (1+ (js2-xml-dot-query-node-rp node)))
4409 (t
4410 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4411
4412 (defsubst js2-node-first-child (node)
4413 "Returns the first element of `js2-node-child-list' for NODE."
4414 (car (js2-node-child-list node)))
4415
4416 (defsubst js2-node-last-child (node)
4417 "Returns the last element of `js2-node-last-child' for NODE."
4418 (car (last (js2-node-child-list node))))
4419
4420 (defun js2-node-prev-sibling (node)
4421 "Return the previous statement in parent.
4422 Works for parents supported by `js2-node-child-list'.
4423 Returns nil if NODE is not in the parent, or PARENT is
4424 not a supported node, or if NODE is the first child."
4425 (let* ((p (js2-node-parent node))
4426 (kids (js2-node-child-list p))
4427 (sib (car kids)))
4428 (while (and kids
4429 (not (eq node (cadr kids))))
4430 (setq kids (cdr kids)
4431 sib (car kids)))
4432 sib))
4433
4434 (defun js2-node-next-sibling (node)
4435 "Return the next statement in parent block.
4436 Returns nil if NODE is not in the block, or PARENT is not
4437 a block node, or if NODE is the last statement."
4438 (let* ((p (js2-node-parent node))
4439 (kids (js2-node-child-list p)))
4440 (while (and kids
4441 (not (eq node (car kids))))
4442 (setq kids (cdr kids)))
4443 (cadr kids)))
4444
4445 (defun js2-node-find-child-before (pos parent &optional after)
4446 "Find the last child that starts before POS in parent.
4447 If AFTER is non-nil, returns first child starting after POS.
4448 POS is an absolute buffer position. PARENT is any node
4449 supported by `js2-node-child-list'.
4450 Returns nil if no applicable child is found."
4451 (let ((kids (if (js2-function-node-p parent)
4452 (js2-block-node-kids (js2-function-node-body parent))
4453 (js2-node-child-list parent)))
4454 (beg (if (js2-function-node-p parent)
4455 (js2-node-abs-pos (js2-function-node-body parent))
4456 (js2-node-abs-pos parent)))
4457 kid
4458 result
4459 fn
4460 (continue t))
4461 (setq fn (if after '> '<))
4462 (while (and kids continue)
4463 (setq kid (car kids))
4464 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4465 (setq result kid
4466 continue (if after nil t))
4467 (setq continue (if after t nil)))
4468 (setq kids (cdr kids)))
4469 result))
4470
4471 (defun js2-node-find-child-after (pos parent)
4472 "Find first child that starts after POS in parent.
4473 POS is an absolute buffer position. PARENT is any node
4474 supported by `js2-node-child-list'.
4475 Returns nil if no applicable child is found."
4476 (js2-node-find-child-before pos parent 'after))
4477
4478 (defun js2-node-replace-child (pos parent new-node)
4479 "Replace node at index POS in PARENT with NEW-NODE.
4480 Only works for parents supported by `js2-node-child-list'."
4481 (let ((kids (js2-node-child-list parent))
4482 (i 0))
4483 (while (< i pos)
4484 (setq kids (cdr kids)
4485 i (1+ i)))
4486 (setcar kids new-node)
4487 (js2-node-add-children parent new-node)))
4488
4489 (defun js2-node-buffer (n)
4490 "Return the buffer associated with AST N.
4491 Returns nil if the buffer is not set as a property on the root
4492 node, or if parent links were not recorded during parsing."
4493 (let ((root (js2-node-root n)))
4494 (and root
4495 (js2-ast-root-p root)
4496 (js2-ast-root-buffer root))))
4497
4498 (defsubst js2-block-node-push (n kid)
4499 "Push js2-node KID onto the end of js2-block-node N's child list.
4500 KID is always added to the -end- of the kids list.
4501 Function also calls `js2-node-add-children' to add the parent link."
4502 (let ((kids (js2-node-child-list n)))
4503 (if kids
4504 (setcdr kids (nconc (cdr kids) (list kid)))
4505 (js2-node-set-child-list n (list kid)))
4506 (js2-node-add-children n kid)))
4507
4508 (defun js2-node-string (node)
4509 (let ((buf (js2-node-buffer node))
4510 pos)
4511 (unless buf
4512 (error "No buffer available for node %s" node))
4513 (save-excursion
4514 (set-buffer buf)
4515 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4516 (+ pos (js2-node-len node))))))
4517
4518 ;; Container for storing the node we're looking for in a traversal.
4519 (js2-deflocal js2-discovered-node nil)
4520
4521 ;; Keep track of absolute node position during traversals.
4522 (js2-deflocal js2-visitor-offset nil)
4523
4524 (js2-deflocal js2-node-search-point nil)
4525
4526 (when js2-mode-dev-mode-p
4527 (defun js2-find-node-at-point ()
4528 (interactive)
4529 (let ((node (js2-node-at-point)))
4530 (message "%s" (or node "No node found at point"))))
4531 (defun js2-node-name-at-point ()
4532 (interactive)
4533 (let ((node (js2-node-at-point)))
4534 (message "%s" (if node
4535 (js2-node-short-name node)
4536 "No node found at point.")))))
4537
4538 (defun js2-node-at-point (&optional pos skip-comments)
4539 "Return AST node at POS, a buffer position, defaulting to current point.
4540 The `js2-mode-ast' variable must be set to the current parse tree.
4541 Signals an error if the AST (`js2-mode-ast') is nil.
4542 Always returns a node - if it can't find one, it returns the root.
4543 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4544 (let ((ast js2-mode-ast)
4545 result)
4546 (unless ast
4547 (error "No JavaScript AST available"))
4548 ;; Look through comments first, since they may be inside nodes that
4549 ;; would otherwise report a match.
4550 (setq pos (or pos (point))
4551 result (if (> pos (js2-node-abs-end ast))
4552 ast
4553 (if (not skip-comments)
4554 (js2-comment-at-point pos))))
4555 (unless result
4556 (setq js2-discovered-node nil
4557 js2-visitor-offset 0
4558 js2-node-search-point pos)
4559 (unwind-protect
4560 (catch 'js2-visit-done
4561 (js2-visit-ast ast #'js2-node-at-point-visitor))
4562 (setq js2-visitor-offset nil
4563 js2-node-search-point nil))
4564 (setq result js2-discovered-node))
4565 ;; may have found a comment beyond end of last child node,
4566 ;; since visiting the ast-root looks at the comment-list last.
4567 (if (and skip-comments
4568 (js2-comment-node-p result))
4569 (setq result nil))
4570 (or result js2-mode-ast)))
4571
4572 (defun js2-node-at-point-visitor (node end-p)
4573 (let ((rel-pos (js2-node-pos node))
4574 abs-pos
4575 abs-end
4576 (point js2-node-search-point))
4577 (cond
4578 (end-p
4579 ;; this evaluates to a non-nil return value, even if it's zero
4580 (decf js2-visitor-offset rel-pos))
4581 ;; we already looked for comments before visiting, and don't want them now
4582 ((js2-comment-node-p node)
4583 nil)
4584 (t
4585 (setq abs-pos (incf js2-visitor-offset rel-pos)
4586 ;; we only want to use the node if the point is before
4587 ;; the last character position in the node, so we decrement
4588 ;; the absolute end by 1.
4589 abs-end (+ abs-pos (js2-node-len node) -1))
4590 (cond
4591 ;; If this node starts after search-point, stop the search.
4592 ((> abs-pos point)
4593 (throw 'js2-visit-done nil))
4594 ;; If this node ends before the search-point, don't check kids.
4595 ((> point abs-end)
4596 nil)
4597 (t
4598 ;; Otherwise point is within this node, possibly in a child.
4599 (setq js2-discovered-node node)
4600 t)))))) ; keep processing kids to look for more specific match
4601
4602 (defsubst js2-block-comment-p (node)
4603 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4604 (and (js2-comment-node-p node)
4605 (memq (js2-comment-node-format node) '(jsdoc block))))
4606
4607 ;; TODO: put the comments in a vector and binary-search them instead
4608 (defun js2-comment-at-point (&optional pos)
4609 "Look through scanned comment nodes for one containing POS.
4610 POS is a buffer position that defaults to current point.
4611 Function returns nil if POS was not in any comment node."
4612 (let ((ast js2-mode-ast)
4613 (x (or pos (point)))
4614 beg
4615 end)
4616 (unless ast
4617 (error "No JavaScript AST available"))
4618 (catch 'done
4619 ;; Comments are stored in lexical order.
4620 (dolist (comment (js2-ast-root-comments ast) nil)
4621 (setq beg (js2-node-abs-pos comment)
4622 end (+ beg (js2-node-len comment)))
4623 (if (and (>= x beg)
4624 (<= x end))
4625 (throw 'done comment))))))
4626
4627 (defun js2-mode-find-parent-fn (node)
4628 "Find function enclosing NODE.
4629 Returns nil if NODE is not inside a function."
4630 (setq node (js2-node-parent node))
4631 (while (and node (not (js2-function-node-p node)))
4632 (setq node (js2-node-parent node)))
4633 (and (js2-function-node-p node) node))
4634
4635 (defun js2-mode-find-enclosing-fn (node)
4636 "Find function or root enclosing NODE."
4637 (if (js2-ast-root-p node)
4638 node
4639 (setq node (js2-node-parent node))
4640 (while (not (or (js2-ast-root-p node)
4641 (js2-function-node-p node)))
4642 (setq node (js2-node-parent node)))
4643 node))
4644
4645 (defun js2-mode-find-enclosing-node (beg end)
4646 "Find script or function fully enclosing BEG and END."
4647 (let ((node (js2-node-at-point beg))
4648 pos
4649 (continue t))
4650 (while continue
4651 (if (or (js2-ast-root-p node)
4652 (and (js2-function-node-p node)
4653 (<= (setq pos (js2-node-abs-pos node)) beg)
4654 (>= (+ pos (js2-node-len node)) end)))
4655 (setq continue nil)
4656 (setq node (js2-node-parent node))))
4657 node))
4658
4659 (defun js2-node-parent-script-or-fn (node)
4660 "Find script or function immediately enclosing NODE.
4661 If NODE is the ast-root, returns nil."
4662 (if (js2-ast-root-p node)
4663 nil
4664 (setq node (js2-node-parent node))
4665 (while (and node (not (or (js2-function-node-p node)
4666 (js2-script-node-p node))))
4667 (setq node (js2-node-parent node)))
4668 node))
4669
4670 (defsubst js2-nested-function-p (node)
4671 "Return t if NODE is a nested function, or is inside a nested function."
4672 (js2-function-node-p (if (js2-function-node-p node)
4673 (js2-node-parent-script-or-fn node)
4674 (js2-node-parent-script-or-fn
4675 (js2-node-parent-script-or-fn node)))))
4676
4677 (defsubst js2-function-param-node-p (node)
4678 "Return non-nil if NODE is a param node of a `js2-function-node'."
4679 (let ((parent (js2-node-parent node)))
4680 (and parent
4681 (js2-function-node-p parent)
4682 (memq node (js2-function-node-params parent)))))
4683
4684 (defsubst js2-mode-shift-kids (kids start offset)
4685 (dolist (kid kids)
4686 (if (> (js2-node-pos kid) start)
4687 (incf (js2-node-pos kid) offset))))
4688
4689 (defsubst js2-mode-shift-children (parent start offset)
4690 "Update start-positions of all children of PARENT beyond START."
4691 (let ((root (js2-node-root parent)))
4692 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4693 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4694
4695 (defsubst js2-node-is-descendant (node ancestor)
4696 "Return t if NODE is a descendant of ANCESTOR."
4697 (while (and node
4698 (not (eq node ancestor)))
4699 (setq node (js2-node-parent node)))
4700 node)
4701
4702 ;;; visitor infrastructure
4703
4704 (defun js2-visit-none (node callback)
4705 "Visitor for AST node that have no node children."
4706 nil)
4707
4708 (defun js2-print-none (node indent)
4709 "Visitor for AST node with no printed representation.")
4710
4711 (defun js2-print-body (node indent)
4712 "Print a statement, or a block without braces."
4713 (if (js2-block-node-p node)
4714 (dolist (kid (js2-block-node-kids node))
4715 (js2-print-ast kid indent))
4716 (js2-print-ast node indent)))
4717
4718 (defun js2-print-list (args &optional delimiter)
4719 (loop with len = (length args)
4720 for arg in args
4721 for count from 1
4722 do
4723 (js2-print-ast arg 0)
4724 (if (< count len)
4725 (insert (or delimiter ", ")))))
4726
4727 (defun js2-print-tree (ast)
4728 "Prints an AST to the current buffer.
4729 Makes `js2-ast-parent-nodes' available to the printer functions."
4730 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4731 (js2-print-ast ast)))
4732
4733 (defun js2-print-ast (node &optional indent)
4734 "Helper function for printing AST nodes.
4735 Requires `js2-ast-parent-nodes' to be non-nil.
4736 You should use `js2-print-tree' instead of this function."
4737 (let ((printer (get (aref node 0) 'js2-printer))
4738 (i (or indent 0))
4739 (pos (js2-node-abs-pos node)))
4740 ;; TODO: wedge comments in here somewhere
4741 (if printer
4742 (funcall printer node i))))
4743
4744 (defconst js2-side-effecting-tokens
4745 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4746 (dolist (tt (list js2-ASSIGN
4747 js2-ASSIGN_ADD
4748 js2-ASSIGN_BITAND
4749 js2-ASSIGN_BITOR
4750 js2-ASSIGN_BITXOR
4751 js2-ASSIGN_DIV
4752 js2-ASSIGN_LSH
4753 js2-ASSIGN_MOD
4754 js2-ASSIGN_MUL
4755 js2-ASSIGN_RSH
4756 js2-ASSIGN_SUB
4757 js2-ASSIGN_URSH
4758 js2-BLOCK
4759 js2-BREAK
4760 js2-CALL
4761 js2-CATCH
4762 js2-CATCH_SCOPE
4763 js2-CONST
4764 js2-CONTINUE
4765 js2-DEBUGGER
4766 js2-DEC
4767 js2-DELPROP
4768 js2-DEL_REF
4769 js2-DO
4770 js2-ELSE
4771 js2-EMPTY
4772 js2-ENTERWITH
4773 js2-EXPORT
4774 js2-EXPR_RESULT
4775 js2-FINALLY
4776 js2-FOR
4777 js2-FUNCTION
4778 js2-GOTO
4779 js2-IF
4780 js2-IFEQ
4781 js2-IFNE
4782 js2-IMPORT
4783 js2-INC
4784 js2-JSR
4785 js2-LABEL
4786 js2-LEAVEWITH
4787 js2-LET
4788 js2-LETEXPR
4789 js2-LOCAL_BLOCK
4790 js2-LOOP
4791 js2-NEW
4792 js2-REF_CALL
4793 js2-RETHROW
4794 js2-RETURN
4795 js2-RETURN_RESULT
4796 js2-SEMI
4797 js2-SETELEM
4798 js2-SETELEM_OP
4799 js2-SETNAME
4800 js2-SETPROP
4801 js2-SETPROP_OP
4802 js2-SETVAR
4803 js2-SET_REF
4804 js2-SET_REF_OP
4805 js2-SWITCH
4806 js2-TARGET
4807 js2-THROW
4808 js2-TRY
4809 js2-VAR
4810 js2-WHILE
4811 js2-WITH
4812 js2-WITHEXPR
4813 js2-YIELD))
4814 (aset tokens tt t))
4815 (if js2-instanceof-has-side-effects
4816 (aset tokens js2-INSTANCEOF t))
4817 tokens))
4818
4819 (defun js2-node-has-side-effects (node)
4820 "Return t if NODE has side effects."
4821 (when node ; makes it easier to handle malformed expressions
4822 (let ((tt (js2-node-type node)))
4823 (cond
4824 ;; This doubtless needs some work, since EXPR_VOID is used
4825 ;; in several ways in Rhino, and I may not have caught them all.
4826 ;; I'll wait for people to notice incorrect warnings.
4827 ((and (= tt js2-EXPR_VOID)
4828 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4829 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4830 ((= tt js2-COMMA)
4831 (js2-node-has-side-effects (js2-infix-node-right node)))
4832 ((or (= tt js2-AND)
4833 (= tt js2-OR))
4834 (or (js2-node-has-side-effects (js2-infix-node-right node))
4835 (js2-node-has-side-effects (js2-infix-node-left node))))
4836 ((= tt js2-HOOK)
4837 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4838 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4839 ((js2-paren-node-p node)
4840 (js2-node-has-side-effects (js2-paren-node-expr node)))
4841 ((= tt js2-ERROR) ; avoid cascaded error messages
4842 nil)
4843 (t
4844 (aref js2-side-effecting-tokens tt))))))
4845
4846 (defun js2-member-expr-leftmost-name (node)
4847 "For an expr such as foo.bar.baz, return leftmost node foo.
4848 NODE is any `js2-node' object. If it represents a member expression,
4849 which is any sequence of property gets, element-gets, function calls,
4850 or xml descendants/filter operators, then we look at the lexically
4851 leftmost (first) node in the chain. If it is a name-node we return it.
4852 Note that NODE can be a raw name-node and it will be returned as well.
4853 If NODE is not a name-node or member expression, or if it is a member
4854 expression whose leftmost target is not a name node, returns nil."
4855 (let ((continue t)
4856 result)
4857 (while (and continue (not result))
4858 (cond
4859 ((js2-name-node-p node)
4860 (setq result node))
4861 ((js2-prop-get-node-p node)
4862 (setq node (js2-prop-get-node-left node)))
4863 ;; TODO: handle call-nodes, xml-nodes, others?
4864 (t
4865 (setq continue nil))))
4866 result))
4867
4868 (defconst js2-stmt-node-types
4869 (list js2-BLOCK
4870 js2-BREAK
4871 js2-CONTINUE
4872 js2-DEFAULT ; e4x "default xml namespace" statement
4873 js2-DO
4874 js2-EXPR_RESULT
4875 js2-EXPR_VOID
4876 js2-FOR
4877 js2-IF
4878 js2-RETURN
4879 js2-SWITCH
4880 js2-THROW
4881 js2-TRY
4882 js2-WHILE
4883 js2-WITH)
4884 "Node types that only appear in statement contexts.
4885 The list does not include nodes that always appear as the child
4886 of another specific statement type, such as switch-cases,
4887 catch and finally blocks, and else-clauses. The list also excludes
4888 nodes like yield, let and var, which may appear in either expression
4889 or statement context, and in the latter context always have a
4890 `js2-expr-stmt-node' parent. Finally, the list does not include
4891 functions or scripts, which are treated separately from statements
4892 by the JavaScript parser and runtime.")
4893
4894 (defun js2-stmt-node-p (node)
4895 "Heuristic for figuring out if NODE is a statement.
4896 Some node types can appear in either an expression context or a
4897 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4898 For these node types in a statement context, the parent will be a
4899 `js2-expr-stmt-node'.
4900 Functions aren't included in the check."
4901 (memq (js2-node-type node) js2-stmt-node-types))
4902
4903 (defsubst js2-mode-find-first-stmt (node)
4904 "Search upward starting from NODE looking for a statement.
4905 For purposes of this function, a `js2-function-node' counts."
4906 (while (not (or (js2-stmt-node-p node)
4907 (js2-function-node-p node)))
4908 (setq node (js2-node-parent node)))
4909 node)
4910
4911 (defun js2-node-parent-stmt (node)
4912 "Return the node's first ancestor that is a statement.
4913 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4914 appearing in a statement context will have a parent that is a
4915 `js2-expr-stmt-node' that will be returned by this function."
4916 (let ((parent (js2-node-parent node)))
4917 (if (or (null parent)
4918 (js2-stmt-node-p parent)
4919 (and (js2-function-node-p parent)
4920 (not (eq (js2-function-node-form parent)
4921 'FUNCTION_EXPRESSION))))
4922 parent
4923 (js2-node-parent-stmt parent))))
4924
4925 ;; In the Mozilla Rhino sources, Roshan James writes:
4926 ;; Does consistent-return analysis on the function body when strict mode is
4927 ;; enabled.
4928 ;;
4929 ;; function (x) { return (x+1) }
4930 ;;
4931 ;; is ok, but
4932 ;;
4933 ;; function (x) { if (x < 0) return (x+1); }
4934 ;;
4935 ;; is not because the function can potentially return a value when the
4936 ;; condition is satisfied and if not, the function does not explicitly
4937 ;; return a value.
4938 ;;
4939 ;; This extends to checking mismatches such as "return" and "return <value>"
4940 ;; used in the same function. Warnings are not emitted if inconsistent
4941 ;; returns exist in code that can be statically shown to be unreachable.
4942 ;; Ex.
4943 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4944 ;;
4945 ;; emits no warning. However if the loop had a break statement, then a
4946 ;; warning would be emitted.
4947 ;;
4948 ;; The consistency analysis looks at control structures such as loops, ifs,
4949 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4950 ;; warns the user about an inconsistent set of termination possibilities.
4951 ;;
4952 ;; These flags enumerate the possible ways a statement/function can
4953 ;; terminate. These flags are used by endCheck() and by the Parser to
4954 ;; detect inconsistent return usage.
4955 ;;
4956 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4957 ;; able to execute (example: throw, continue)
4958 ;;
4959 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4960 ;; next one. Statement such as return dont. A compound statement may have
4961 ;; some branch that drops off control to the next statement.
4962 ;;
4963 ;; END_RETURNS indicates that the statement can return with no value.
4964 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4965 ;;
4966 ;; A compound statement such as
4967 ;; if (condition) {
4968 ;; return value;
4969 ;; }
4970 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4971
4972 (defconst js2-END_UNREACHED 0)
4973 (defconst js2-END_DROPS_OFF 1)
4974 (defconst js2-END_RETURNS 2)
4975 (defconst js2-END_RETURNS_VALUE 4)
4976 (defconst js2-END_YIELDS 8)
4977
4978 (defun js2-has-consistent-return-usage (node)
4979 "Check that every return usage in a function body is consistent.
4980 Returns t if the function satisfies strict mode requirement."
4981 (let ((n (js2-end-check node)))
4982 ;; either it doesn't return a value in any branch...
4983 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4984 ;; or it returns a value (or is unreached) at every branch
4985 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4986 js2-END_RETURNS
4987 js2-END_YIELDS)))))
4988
4989 (defun js2-end-check-if (node)
4990 "Returns in the then and else blocks must be consistent with each other.
4991 If there is no else block, then the return statement can fall through.
4992 Returns logical OR of END_* flags"
4993 (let ((th (js2-if-node-then-part node))
4994 (el (js2-if-node-else-part node)))
4995 (if (null th)
4996 js2-END_UNREACHED
4997 (logior (js2-end-check th) (if el
4998 (js2-end-check el)
4999 js2-END_DROPS_OFF)))))
5000
5001 (defun js2-end-check-switch (node)
5002 "Consistency of return statements is checked between the case statements.
5003 If there is no default, then the switch can fall through. If there is a
5004 default, we check to see if all code paths in the default return or if
5005 there is a code path that can fall through.
5006 Returns logical OR of END_* flags."
5007 (let ((rv js2-END_UNREACHED)
5008 default-case)
5009 ;; examine the cases
5010 (catch 'break
5011 (dolist (c (js2-switch-node-cases node))
5012 (if (js2-case-node-expr c)
5013 (js2-set-flag rv (js2-end-check-block c))
5014 (setq default-case c)
5015 (throw 'break nil))))
5016 ;; we don't care how the cases drop into each other
5017 (js2-clear-flag rv js2-END_DROPS_OFF)
5018 ;; examine the default
5019 (js2-set-flag rv (if default-case
5020 (js2-end-check default-case)
5021 js2-END_DROPS_OFF))
5022 rv))
5023
5024 (defun js2-end-check-try (node)
5025 "If the block has a finally, return consistency is checked in the
5026 finally block. If all code paths in the finally return, then the
5027 returns in the try-catch blocks don't matter. If there is a code path
5028 that does not return or if there is no finally block, the returns
5029 of the try and catch blocks are checked for mismatch.
5030 Returns logical OR of END_* flags."
5031 (let ((finally (js2-try-node-finally-block node))
5032 rv)
5033 ;; check the finally if it exists
5034 (setq rv (if finally
5035 (js2-end-check (js2-finally-node-body finally))
5036 js2-END_DROPS_OFF))
5037 ;; If the finally block always returns, then none of the returns
5038 ;; in the try or catch blocks matter.
5039 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5040 (js2-clear-flag rv js2-END_DROPS_OFF)
5041 ;; examine the try block
5042 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5043 ;; check each catch block
5044 (dolist (cb (js2-try-node-catch-clauses node))
5045 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5046 rv))
5047
5048 (defun js2-end-check-loop (node)
5049 "Return statement in the loop body must be consistent. The default
5050 assumption for any kind of a loop is that it will eventually terminate.
5051 The only exception is a loop with a constant true condition. Code that
5052 follows such a loop is examined only if one can statically determine
5053 that there is a break out of the loop.
5054
5055 for(... ; ... ; ...) {}
5056 for(... in ... ) {}
5057 while(...) { }
5058 do { } while(...)
5059
5060 Returns logical OR of END_* flags."
5061 (let ((rv (js2-end-check (js2-loop-node-body node)))
5062 (condition (cond
5063 ((js2-while-node-p node)
5064 (js2-while-node-condition node))
5065 ((js2-do-node-p node)
5066 (js2-do-node-condition node))
5067 ((js2-for-node-p node)
5068 (js2-for-node-condition node)))))
5069
5070 ;; check to see if the loop condition is always true
5071 (if (and condition
5072 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5073 (js2-clear-flag rv js2-END_DROPS_OFF))
5074
5075 ;; look for effect of breaks
5076 (js2-set-flag rv (js2-node-get-prop node
5077 'CONTROL_BLOCK_PROP
5078 js2-END_UNREACHED))
5079 rv))
5080
5081 (defun js2-end-check-block (node)
5082 "A general block of code is examined statement by statement.
5083 If any statement (even a compound one) returns in all branches, then
5084 subsequent statements are not examined.
5085 Returns logical OR of END_* flags."
5086 (let* ((rv js2-END_DROPS_OFF)
5087 (kids (js2-block-node-kids node))
5088 (n (car kids)))
5089 ;; Check each statment. If the statement can continue onto the next
5090 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5091 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5092 (js2-clear-flag rv js2-END_DROPS_OFF)
5093 (js2-set-flag rv (js2-end-check n))
5094 (setq kids (cdr kids)
5095 n (car kids)))
5096 rv))
5097
5098 (defun js2-end-check-label (node)
5099 "A labeled statement implies that there may be a break to the label.
5100 The function processes the labeled statement and then checks the
5101 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5102 particular label.
5103 Returns logical OR of END_* flags."
5104 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5105 (logior rv (js2-node-get-prop node
5106 'CONTROL_BLOCK_PROP
5107 js2-END_UNREACHED))))
5108
5109 (defun js2-end-check-break (node)
5110 "When a break is encountered annotate the statement being broken
5111 out of by setting its CONTROL_BLOCK_PROP property.
5112 Returns logical OR of END_* flags."
5113 (and (js2-break-node-target node)
5114 (js2-node-set-prop (js2-break-node-target node)
5115 'CONTROL_BLOCK_PROP
5116 js2-END_DROPS_OFF))
5117 js2-END_UNREACHED)
5118
5119 (defun js2-end-check (node)
5120 "Examine the body of a function, doing a basic reachability analysis.
5121 Returns a combination of flags END_* flags that indicate
5122 how the function execution can terminate. These constitute only the
5123 pessimistic set of termination conditions. It is possible that at
5124 runtime certain code paths will never be actually taken. Hence this
5125 analysis will flag errors in cases where there may not be errors.
5126 Returns logical OR of END_* flags"
5127 (let (kid)
5128 (cond
5129 ((js2-break-node-p node)
5130 (js2-end-check-break node))
5131 ((js2-expr-stmt-node-p node)
5132 (if (setq kid (js2-expr-stmt-node-expr node))
5133 (js2-end-check kid)
5134 js2-END_DROPS_OFF))
5135 ((or (js2-continue-node-p node)
5136 (js2-throw-node-p node))
5137 js2-END_UNREACHED)
5138 ((js2-return-node-p node)
5139 (if (setq kid (js2-return-node-retval node))
5140 js2-END_RETURNS_VALUE
5141 js2-END_RETURNS))
5142 ((js2-loop-node-p node)
5143 (js2-end-check-loop node))
5144 ((js2-switch-node-p node)
5145 (js2-end-check-switch node))
5146 ((js2-labeled-stmt-node-p node)
5147 (js2-end-check-label node))
5148 ((js2-if-node-p node)
5149 (js2-end-check-if node))
5150 ((js2-try-node-p node)
5151 (js2-end-check-try node))
5152 ((js2-block-node-p node)
5153 (if (null (js2-block-node-kids node))
5154 js2-END_DROPS_OFF
5155 (js2-end-check-block node)))
5156 ((js2-yield-node-p node)
5157 js2-END_YIELDS)
5158 (t
5159 js2-END_DROPS_OFF))))
5160
5161 (defun js2-always-defined-boolean-p (node)
5162 "Check if NODE always evaluates to true or false in boolean context.
5163 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5164 nor always false."
5165 (let ((tt (js2-node-type node))
5166 num)
5167 (cond
5168 ((or (= tt js2-FALSE) (= tt js2-NULL))
5169 'ALWAYS_FALSE)
5170 ((= tt js2-TRUE)
5171 'ALWAYS_TRUE)
5172 ((= tt js2-NUMBER)
5173 (setq num (js2-number-node-num-value node))
5174 (if (and (not (eq num 0.0e+NaN))
5175 (not (zerop num)))
5176 'ALWAYS_TRUE
5177 'ALWAYS_FALSE))
5178 (t
5179 nil))))
5180
5181 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5182 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5183
5184 (defvar js2-tokens nil
5185 "List of all defined token names.") ; initialized in `js2-token-names'
5186
5187 (defconst js2-token-names
5188 (let* ((names (make-vector js2-num-tokens -1))
5189 (case-fold-search nil) ; only match js2-UPPER_CASE
5190 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5191 (loop for sym in syms
5192 for i from 0
5193 do
5194 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5195 (not (boundp sym)))
5196 (aset names (symbol-value sym) ; code, e.g. 152
5197 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5198 (push sym js2-tokens)))
5199 names)
5200 "Vector mapping int values to token string names, sans `js2-' prefix.")
5201
5202 (defun js2-token-name (tok)
5203 "Return a string name for TOK, a token symbol or code.
5204 Signals an error if it's not a recognized token."
5205 (let ((code tok))
5206 (if (symbolp tok)
5207 (setq code (symbol-value tok)))
5208 (if (eq code -1)
5209 "ERROR"
5210 (if (and (numberp code)
5211 (not (minusp code))
5212 (< code js2-num-tokens))
5213 (aref js2-token-names code)
5214 (error "Invalid token: %s" code)))))
5215
5216 (defsubst js2-token-sym (tok)
5217 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5218 (intern (js2-token-name tok)))
5219
5220 (defconst js2-token-codes
5221 (let ((table (make-hash-table :test 'eq :size 256)))
5222 (loop for name across js2-token-names
5223 for sym = (intern (concat "js2-" name))
5224 do
5225 (puthash sym (symbol-value sym) table))
5226 ;; clean up a few that are "wrong" in Rhino's token codes
5227 (puthash 'js2-DELETE js2-DELPROP table)
5228 table)
5229 "Hashtable mapping token symbols to their bytecodes.")
5230
5231 (defsubst js2-token-code (sym)
5232 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5233 (or (gethash sym js2-token-codes)
5234 (error "Invalid token symbol: %s " sym))) ; signal code bug
5235
5236 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5237 (setq js2-token-end js2-ts-cursor)
5238 (js2-report-error msg nil
5239 (or beg js2-token-beg)
5240 (or len (- js2-token-end js2-token-beg)))
5241 (unless no-throw
5242 (throw 'return js2-ERROR)))
5243
5244 (defsubst js2-get-string-from-buffer ()
5245 "Reverse the char accumulator and return it as a string."
5246 (setq js2-token-end js2-ts-cursor)
5247 (if js2-ts-string-buffer
5248 (apply #'string (nreverse js2-ts-string-buffer))
5249 ""))
5250
5251 ;; TODO: could potentially avoid a lot of consing by allocating a
5252 ;; char buffer the way Rhino does.
5253 (defsubst js2-add-to-string (c)
5254 (push c js2-ts-string-buffer))
5255
5256 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5257 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5258 ;; any other character: when it's not part of the current token, we
5259 ;; unget it, allowing it to be read again by the following call.
5260 (defsubst js2-unget-char ()
5261 (decf js2-ts-cursor))
5262
5263 ;; Rhino distinguishes \r and \n line endings. We don't need to
5264 ;; because we only scan from Emacs buffers, which always use \n.
5265 (defsubst js2-get-char ()
5266 "Read and return the next character from the input buffer.
5267 Increments `js2-ts-lineno' if the return value is a newline char.
5268 Updates `js2-ts-cursor' to the point after the returned char.
5269 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5270 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5271 (let (c)
5272 ;; check for end of buffer
5273 (if (>= js2-ts-cursor (point-max))
5274 (setq js2-ts-hit-eof t
5275 js2-ts-cursor (1+ js2-ts-cursor)
5276 c js2-EOF_CHAR) ; return value
5277 ;; otherwise read next char
5278 (setq c (char-before (incf js2-ts-cursor)))
5279 ;; if we read a newline, update counters
5280 (if (= c ?\n)
5281 (setq js2-ts-line-start js2-ts-cursor
5282 js2-ts-lineno (1+ js2-ts-lineno)))
5283 ;; TODO: skip over format characters
5284 c)))
5285
5286 (defsubst js2-read-unicode-escape ()
5287 "Read a \\uNNNN sequence from the input.
5288 Assumes the ?\ and ?u have already been read.
5289 Returns the unicode character, or nil if it wasn't a valid character.
5290 Doesn't change the values of any scanner variables."
5291 ;; I really wish I knew a better way to do this, but I can't
5292 ;; find the Emacs function that takes a 16-bit int and converts
5293 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5294 ;; Have to first check that it's 4 hex characters or it may stop
5295 ;; the read early.
5296 (ignore-errors
5297 (let ((s (buffer-substring-no-properties js2-ts-cursor
5298 (+ 4 js2-ts-cursor))))
5299 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5300 (read (concat "?\\u" s))))))
5301
5302 (defsubst js2-match-char (test)
5303 "Consume and return next character if it matches TEST, a character.
5304 Returns nil and consumes nothing if TEST is not the next character."
5305 (let ((c (js2-get-char)))
5306 (if (eq c test)
5307 t
5308 (js2-unget-char)
5309 nil)))
5310
5311 (defsubst js2-peek-char ()
5312 (prog1
5313 (js2-get-char)
5314 (js2-unget-char)))
5315
5316 (defsubst js2-java-identifier-start-p (c)
5317 (or
5318 (memq c '(?$ ?_))
5319 (js2-char-uppercase-p c)
5320 (js2-char-lowercase-p c)))
5321
5322 (defsubst js2-java-identifier-part-p (c)
5323 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5324 ;; TODO: make me Unicode-friendly. See comments above.
5325 (or
5326 (memq c '(?$ ?_))
5327 (js2-char-uppercase-p c)
5328 (js2-char-lowercase-p c)
5329 (and (>= c ?0) (<= c ?9))))
5330
5331 (defsubst js2-alpha-p (c)
5332 (cond ((and (<= ?A c) (<= c ?Z)) t)
5333 ((and (<= ?a c) (<= c ?z)) t)
5334 (t nil)))
5335
5336 (defsubst js2-digit-p (c)
5337 (and (<= ?0 c) (<= c ?9)))
5338
5339 (defsubst js2-js-space-p (c)
5340 (if (<= c 127)
5341 (memq c '(#x20 #x9 #xB #xC #xD))
5342 (or
5343 (eq c #xA0)
5344 ;; TODO: change this nil to check for Unicode space character
5345 nil)))
5346
5347 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5348
5349 (defsubst js2-skip-line ()
5350 "Skip to end of line"
5351 (let (c)
5352 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5353 (js2-unget-char)
5354 (setq js2-token-end js2-ts-cursor)))
5355
5356 (defun js2-init-scanner (&optional buf line)
5357 "Create token stream for BUF starting on LINE.
5358 BUF defaults to current-buffer and line defaults to 1.
5359
5360 A buffer can only have one scanner active at a time, which yields
5361 dramatically simpler code than using a defstruct. If you need to
5362 have simultaneous scanners in a buffer, copy the regions to scan
5363 into temp buffers."
5364 (save-excursion
5365 (when buf
5366 (set-buffer buf))
5367 (setq js2-ts-dirty-line nil
5368 js2-ts-regexp-flags nil
5369 js2-ts-string ""
5370 js2-ts-number nil
5371 js2-ts-hit-eof nil
5372 js2-ts-line-start 0
5373 js2-ts-lineno (or line 1)
5374 js2-ts-line-end-char -1
5375 js2-ts-cursor (point-min)
5376 js2-ts-is-xml-attribute nil
5377 js2-ts-xml-is-tag-content nil
5378 js2-ts-xml-open-tags-count 0
5379 js2-ts-string-buffer nil)))
5380
5381 ;; This function uses the cached op, string and number fields in
5382 ;; TokenStream; if getToken has been called since the passed token
5383 ;; was scanned, the op or string printed may be incorrect.
5384 (defun js2-token-to-string (token)
5385 ;; Not sure where this function is used in Rhino. Not tested.
5386 (if (not js2-debug-print-trees)
5387 ""
5388 (let ((name (js2-token-name token)))
5389 (cond
5390 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5391 (concat name " `" js2-ts-string "'"))
5392 ((eq token js2-NUMBER)
5393 (format "NUMBER %g" js2-ts-number))
5394 (t
5395 name)))))
5396
5397 (defconst js2-keywords
5398 '(break
5399 case catch const continue
5400 debugger default delete do
5401 else enum
5402 false finally for function
5403 if in instanceof import
5404 let
5405 new null
5406 return
5407 switch
5408 this throw true try typeof
5409 var void
5410 while with
5411 yield))
5412
5413 ;; Token names aren't exactly the same as the keywords, unfortunately.
5414 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5415 (defconst js2-kwd-tokens
5416 (let ((table (make-vector js2-num-tokens nil))
5417 (tokens
5418 (list js2-BREAK
5419 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5420 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5421 js2-ELSE
5422 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5423 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5424 js2-LET
5425 js2-NEW js2-NULL
5426 js2-RETURN
5427 js2-SWITCH
5428 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5429 js2-VAR
5430 js2-WHILE js2-WITH
5431 js2-YIELD)))
5432 (dolist (i tokens)
5433 (aset table i 'font-lock-keyword-face))
5434 (aset table js2-STRING 'font-lock-string-face)
5435 (aset table js2-REGEXP 'font-lock-string-face)
5436 (aset table js2-COMMENT 'font-lock-comment-face)
5437 (aset table js2-THIS 'font-lock-builtin-face)
5438 (aset table js2-VOID 'font-lock-constant-face)
5439 (aset table js2-NULL 'font-lock-constant-face)
5440 (aset table js2-TRUE 'font-lock-constant-face)
5441 (aset table js2-FALSE 'font-lock-constant-face)
5442 table)
5443 "Vector whose values are non-nil for tokens that are keywords.
5444 The values are default faces to use for highlighting the keywords.")
5445
5446 (defconst js2-reserved-words
5447 '(abstract
5448 boolean byte
5449 char class
5450 double
5451 enum export extends
5452 final float
5453 goto
5454 implements import int interface
5455 long
5456 native
5457 package private protected public
5458 short static super synchronized
5459 throws transient
5460 volatile))
5461
5462 (defconst js2-keyword-names
5463 (let ((table (make-hash-table :test 'equal)))
5464 (loop for k in js2-keywords
5465 do (puthash
5466 (symbol-name k) ; instanceof
5467 (intern (concat "js2-"
5468 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5469 table))
5470 table)
5471 "JavaScript keywords by name, mapped to their symbols.")
5472
5473 (defconst js2-reserved-word-names
5474 (let ((table (make-hash-table :test 'equal)))
5475 (loop for k in js2-reserved-words
5476 do
5477 (puthash (symbol-name k) 'js2-RESERVED table))
5478 table)
5479 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5480
5481 (defsubst js2-collect-string (buf)
5482 "Convert BUF, a list of chars, to a string.
5483 Reverses BUF before converting."
5484 (cond
5485 ((stringp buf)
5486 buf)
5487 ((null buf) ; for emacs21 compat
5488 "")
5489 (t
5490 (if buf
5491 (apply #'string (nreverse buf))
5492 ""))))
5493
5494 (defun js2-string-to-keyword (s)
5495 "Return token for S, a string, if S is a keyword or reserved word.
5496 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5497 (or (gethash s js2-keyword-names)
5498 (gethash s js2-reserved-word-names)))
5499
5500 (defsubst js2-ts-set-char-token-bounds ()
5501 "Used when next token is one character."
5502 (setq js2-token-beg (1- js2-ts-cursor)
5503 js2-token-end js2-ts-cursor))
5504
5505 (defsubst js2-ts-return (token)
5506 "Return an N-character TOKEN from `js2-get-token'.
5507 Updates `js2-token-end' accordingly."
5508 (setq js2-token-end js2-ts-cursor)
5509 (throw 'return token))
5510
5511 (defsubst js2-x-digit-to-int (c accumulator)
5512 "Build up a hex number.
5513 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5514 corresponding number. Otherwise return -1."
5515 (catch 'return
5516 (catch 'check
5517 ;; Use 0..9 < A..Z < a..z
5518 (cond
5519 ((<= c ?9)
5520 (decf c ?0)
5521 (if (<= 0 c)
5522 (throw 'check nil)))
5523 ((<= c ?F)
5524 (when (<= ?A c)
5525 (decf c (- ?A 10))
5526 (throw 'check nil)))
5527 ((<= c ?f)
5528 (when (<= ?a c)
5529 (decf c (- ?a 10))
5530 (throw 'check nil))))
5531 (throw 'return -1))
5532 (logior c (lsh accumulator 4))))
5533
5534 (defun js2-get-token ()
5535 "Return next JavaScript token, an int such as js2-RETURN."
5536 (let (c
5537 c1
5538 identifier-start
5539 is-unicode-escape-start
5540 contains-escape
5541 escape-val
5542 escape-start
5543 str
5544 result
5545 base
5546 is-integer
5547 quote-char
5548 val
5549 look-for-slash
5550 continue)
5551 (catch 'return
5552 (while t
5553 ;; Eat whitespace, possibly sensitive to newlines.
5554 (setq continue t)
5555 (while continue
5556 (setq c (js2-get-char))
5557 (cond
5558 ((eq c js2-EOF_CHAR)
5559 (js2-ts-set-char-token-bounds)
5560 (throw 'return js2-EOF))
5561 ((eq c ?\n)
5562 (js2-ts-set-char-token-bounds)
5563 (setq js2-ts-dirty-line nil)
5564 (throw 'return js2-EOL))
5565 ((not (js2-js-space-p c))
5566 (if (/= c ?-) ; in case end of HTML comment
5567 (setq js2-ts-dirty-line t))
5568 (setq continue nil))))
5569 ;; Assume the token will be 1 char - fixed up below.
5570 (js2-ts-set-char-token-bounds)
5571 (when (eq c ?@)
5572 (throw 'return js2-XMLATTR))
5573 ;; identifier/keyword/instanceof?
5574 ;; watch out for starting with a <backslash>
5575 (cond
5576 ((eq c ?\\)
5577 (setq c (js2-get-char))
5578 (if (eq c ?u)
5579 (setq identifier-start t
5580 is-unicode-escape-start t
5581 js2-ts-string-buffer nil)
5582 (setq identifier-start nil)
5583 (js2-unget-char)
5584 (setq c ?\\)))
5585 (t
5586 (when (setq identifier-start (js2-java-identifier-start-p c))
5587 (setq js2-ts-string-buffer nil)
5588 (js2-add-to-string c))))
5589 (when identifier-start
5590 (setq contains-escape is-unicode-escape-start)
5591 (catch 'break
5592 (while t
5593 (if is-unicode-escape-start
5594 ;; strictly speaking we should probably push-back
5595 ;; all the bad characters if the <backslash>uXXXX
5596 ;; sequence is malformed. But since there isn't a
5597 ;; correct context(is there?) for a bad Unicode
5598 ;; escape sequence in an identifier, we can report
5599 ;; an error here.
5600 (progn
5601 (setq escape-val 0)
5602 (dotimes (i 4)
5603 (setq c (js2-get-char)
5604 escape-val (js2-x-digit-to-int c escape-val))
5605 ;; Next check takes care of c < 0 and bad escape
5606 (if (minusp escape-val)
5607 (throw 'break nil)))
5608 (if (minusp escape-val)
5609 (js2-report-scan-error "msg.invalid.escape" t))
5610 (js2-add-to-string escape-val)
5611 (setq is-unicode-escape-start nil))
5612 (setq c (js2-get-char))
5613 (cond
5614 ((eq c ?\\)
5615 (setq c (js2-get-char))
5616 (if (eq c ?u)
5617 (setq is-unicode-escape-start t
5618 contains-escape t)
5619 (js2-report-scan-error "msg.illegal.character" t)))
5620 (t
5621 (if (or (eq c js2-EOF_CHAR)
5622 (not (js2-java-identifier-part-p c)))
5623 (throw 'break nil))
5624 (js2-add-to-string c))))))
5625 (js2-unget-char)
5626 (setq str (js2-get-string-from-buffer))
5627 (unless contains-escape
5628 ;; OPT we shouldn't have to make a string (object!) to
5629 ;; check if it's a keyword.
5630 ;; Return the corresponding token if it's a keyword
5631 (when (setq result (js2-string-to-keyword str))
5632 (if (and (< js2-language-version 170)
5633 (memq result '(js2-LET js2-YIELD)))
5634 ;; LET and YIELD are tokens only in 1.7 and later
5635 (setq result 'js2-NAME))
5636 (if (not (eq result 'js2-RESERVED))
5637 (throw 'return (js2-token-code result)))
5638 (js2-report-warning "msg.reserved.keyword" str)))
5639 ;; If we want to intern these as Rhino does, just use (intern str)
5640 (setq js2-ts-string str)
5641 (throw 'return js2-NAME)) ; end identifier/kwd check
5642 ;; is it a number?
5643 (when (or (js2-digit-p c)
5644 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5645 (setq js2-ts-string-buffer nil
5646 base 10)
5647 (when (eq c ?0)
5648 (setq c (js2-get-char))
5649 (cond
5650 ((or (eq c ?x) (eq c ?X))
5651 (setq base 16)
5652 (setq c (js2-get-char)))
5653 ((js2-digit-p c)
5654 (setq base 8))
5655 (t
5656 (js2-add-to-string ?0))))
5657 (if (eq base 16)
5658 (while (<= 0 (js2-x-digit-to-int c 0))
5659 (js2-add-to-string c)
5660 (setq c (js2-get-char)))
5661 (while (and (<= ?0 c) (<= c ?9))
5662 ;; We permit 08 and 09 as decimal numbers, which
5663 ;; makes our behavior a superset of the ECMA
5664 ;; numeric grammar. We might not always be so
5665 ;; permissive, so we warn about it.
5666 (when (and (eq base 8) (>= c ?8))
5667 (js2-report-warning "msg.bad.octal.literal"
5668 (if (eq c ?8) "8" "9"))
5669 (setq base 10))
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char))))
5672 (setq is-integer t)
5673 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5674 (setq is-integer nil)
5675 (when (eq c ?.)
5676 (loop do
5677 (js2-add-to-string c)
5678 (setq c (js2-get-char))
5679 while (js2-digit-p c)))
5680 (when (memq c '(?e ?E))
5681 (js2-add-to-string c)
5682 (setq c (js2-get-char))
5683 (when (memq c '(?+ ?-))
5684 (js2-add-to-string c)
5685 (setq c (js2-get-char)))
5686 (unless (js2-digit-p c)
5687 (js2-report-scan-error "msg.missing.exponent" t))
5688 (loop do
5689 (js2-add-to-string c)
5690 (setq c (js2-get-char))
5691 while (js2-digit-p c))))
5692 (js2-unget-char)
5693 (setq js2-ts-string (js2-get-string-from-buffer)
5694 js2-ts-number
5695 (if (and (eq base 10) (not is-integer))
5696 (string-to-number js2-ts-string)
5697 ;; TODO: call runtime number-parser. Some of it is in
5698 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5699 (string-to-number js2-ts-string)))
5700 (throw 'return js2-NUMBER))
5701 ;; is it a string?
5702 (when (memq c '(?\" ?\'))
5703 ;; We attempt to accumulate a string the fast way, by
5704 ;; building it directly out of the reader. But if there
5705 ;; are any escaped characters in the string, we revert to
5706 ;; building it out of a string buffer.
5707 (setq quote-char c
5708 js2-ts-string-buffer nil
5709 c (js2-get-char))
5710 (catch 'break
5711 (while (/= c quote-char)
5712 (catch 'continue
5713 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5714 (js2-unget-char)
5715 (setq js2-token-end js2-ts-cursor)
5716 (js2-report-error "msg.unterminated.string.lit")
5717 (throw 'return js2-STRING))
5718 (when (eq c ?\\)
5719 ;; We've hit an escaped character
5720 (setq c (js2-get-char))
5721 (case c
5722 (?b (setq c ?\b))
5723 (?f (setq c ?\f))
5724 (?n (setq c ?\n))
5725 (?r (setq c ?\r))
5726 (?t (setq c ?\t))
5727 (?v (setq c ?\v))
5728 (?u
5729 (setq c1 (js2-read-unicode-escape))
5730 (if js2-parse-ide-mode
5731 (if c1
5732 (progn
5733 ;; just copy the string in IDE-mode
5734 (js2-add-to-string ?\\)
5735 (js2-add-to-string ?u)
5736 (dotimes (i 3)
5737 (js2-add-to-string (js2-get-char)))
5738 (setq c (js2-get-char))) ; added at end of loop
5739 ;; flag it as an invalid escape
5740 (js2-report-warning "msg.invalid.escape"
5741 nil (- js2-ts-cursor 2) 6))
5742 ;; Get 4 hex digits; if the u escape is not
5743 ;; followed by 4 hex digits, use 'u' + the
5744 ;; literal character sequence that follows.
5745 (js2-add-to-string ?u)
5746 (setq escape-val 0)
5747 (dotimes (i 4)
5748 (setq c (js2-get-char)
5749 escape-val (js2-x-digit-to-int c escape-val))
5750 (if (minusp escape-val)
5751 (throw 'continue nil))
5752 (js2-add-to-string c))
5753 ;; prepare for replace of stored 'u' sequence by escape value
5754 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5755 c escape-val)))
5756 (?x
5757 ;; Get 2 hex digits, defaulting to 'x'+literal
5758 ;; sequence, as above.
5759 (setq c (js2-get-char)
5760 escape-val (js2-x-digit-to-int c 0))
5761 (if (minusp escape-val)
5762 (progn
5763 (js2-add-to-string ?x)
5764 (throw 'continue nil))
5765 (setq c1 c
5766 c (js2-get-char)
5767 escape-val (js2-x-digit-to-int c escape-val))
5768 (if (minusp escape-val)
5769 (progn
5770 (js2-add-to-string ?x)
5771 (js2-add-to-string c1)
5772 (throw 'continue nil))
5773 ;; got 2 hex digits
5774 (setq c escape-val))))
5775 (?\n
5776 ;; Remove line terminator after escape to follow
5777 ;; SpiderMonkey and C/C++
5778 (setq c (js2-get-char))
5779 (throw 'continue nil))
5780 (t
5781 (when (and (<= ?0 c) (< c ?8))
5782 (setq val (- c ?0)
5783 c (js2-get-char))
5784 (when (and (<= ?0 c) (< c ?8))
5785 (setq val (- (+ (* 8 val) c) ?0)
5786 c (js2-get-char))
5787 (when (and (<= ?0 c)
5788 (< c ?8)
5789 (< val #o37))
5790 ;; c is 3rd char of octal sequence only
5791 ;; if the resulting val <= 0377
5792 (setq val (- (+ (* 8 val) c) ?0)
5793 c (js2-get-char))))
5794 (js2-unget-char)
5795 (setq c val)))))
5796 (js2-add-to-string c)
5797 (setq c (js2-get-char)))))
5798 (setq js2-ts-string (js2-get-string-from-buffer))
5799 (throw 'return js2-STRING))
5800 (case c
5801 (?\;
5802 (throw 'return js2-SEMI))
5803 (?\[
5804 (throw 'return js2-LB))
5805 (?\]
5806 (throw 'return js2-RB))
5807 (?{
5808 (throw 'return js2-LC))
5809 (?}
5810 (throw 'return js2-RC))
5811 (?\(
5812 (throw 'return js2-LP))
5813 (?\)
5814 (throw 'return js2-RP))
5815 (?,
5816 (throw 'return js2-COMMA))
5817 (??
5818 (throw 'return js2-HOOK))
5819 (?:
5820 (if (js2-match-char ?:)
5821 (js2-ts-return js2-COLONCOLON)
5822 (throw 'return js2-COLON)))
5823 (?.
5824 (if (js2-match-char ?.)
5825 (js2-ts-return js2-DOTDOT)
5826 (if (js2-match-char ?\()
5827 (js2-ts-return js2-DOTQUERY)
5828 (throw 'return js2-DOT))))
5829 (?|
5830 (if (js2-match-char ?|)
5831 (throw 'return js2-OR)
5832 (if (js2-match-char ?=)
5833 (js2-ts-return js2-ASSIGN_BITOR)
5834 (throw 'return js2-BITOR))))
5835 (?^
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-ASSIGN_BITOR)
5838 (throw 'return js2-BITXOR)))
5839 (?&
5840 (if (js2-match-char ?&)
5841 (throw 'return js2-AND)
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_BITAND)
5844 (throw 'return js2-BITAND))))
5845 (?=
5846 (if (js2-match-char ?=)
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-SHEQ)
5849 (throw 'return js2-EQ))
5850 (throw 'return js2-ASSIGN)))
5851 (?!
5852 (if (js2-match-char ?=)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-SHNE)
5855 (js2-ts-return js2-NE))
5856 (throw 'return js2-NOT)))
5857 (?<
5858 ;; NB:treat HTML begin-comment as comment-till-eol
5859 (when (js2-match-char ?!)
5860 (when (js2-match-char ?-)
5861 (when (js2-match-char ?-)
5862 (js2-skip-line)
5863 (setq js2-ts-comment-type 'html)
5864 (throw 'return js2-COMMENT)))
5865 (js2-unget-char))
5866 (if (js2-match-char ?<)
5867 (if (js2-match-char ?=)
5868 (js2-ts-return js2-ASSIGN_LSH)
5869 (js2-ts-return js2-LSH))
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-LE)
5872 (throw 'return js2-LT))))
5873 (?>
5874 (if (js2-match-char ?>)
5875 (if (js2-match-char ?>)
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-ASSIGN_URSH)
5878 (js2-ts-return js2-URSH))
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_RSH)
5881 (js2-ts-return js2-RSH)))
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-GE)
5884 (throw 'return js2-GT))))
5885 (?*
5886 (if (js2-match-char ?=)
5887 (js2-ts-return js2-ASSIGN_MUL)
5888 (throw 'return js2-MUL)))
5889 (?/
5890 ;; is it a // comment?
5891 (when (js2-match-char ?/)
5892 (setq js2-token-beg (- js2-ts-cursor 2))
5893 (js2-skip-line)
5894 (setq js2-ts-comment-type 'line)
5895 ;; include newline so highlighting goes to end of window
5896 (incf js2-token-end)
5897 (throw 'return js2-COMMENT))
5898 ;; is it a /* comment?
5899 (when (js2-match-char ?*)
5900 (setq look-for-slash nil
5901 js2-token-beg (- js2-ts-cursor 2)
5902 js2-ts-comment-type
5903 (if (js2-match-char ?*)
5904 (progn
5905 (setq look-for-slash t)
5906 'jsdoc)
5907 'block))
5908 (while t
5909 (setq c (js2-get-char))
5910 (cond
5911 ((eq c js2-EOF_CHAR)
5912 (setq js2-token-end (1- js2-ts-cursor))
5913 (js2-report-error "msg.unterminated.comment")
5914 (throw 'return js2-COMMENT))
5915 ((eq c ?*)
5916 (setq look-for-slash t))
5917 ((eq c ?/)
5918 (if look-for-slash
5919 (js2-ts-return js2-COMMENT)))
5920 (t
5921 (setq look-for-slash nil
5922 js2-token-end js2-ts-cursor)))))
5923 (if (js2-match-char ?=)
5924 (js2-ts-return js2-ASSIGN_DIV)
5925 (throw 'return js2-DIV)))
5926 (?#
5927 (when js2-skip-preprocessor-directives
5928 (js2-skip-line)
5929 (setq js2-ts-comment-type 'preprocessor
5930 js2-token-end js2-ts-cursor)
5931 (throw 'return js2-COMMENT))
5932 (throw 'return js2-ERROR))
5933 (?%
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_MOD)
5936 (throw 'return js2-MOD)))
5937 (?~
5938 (throw 'return js2-BITNOT))
5939 (?+
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_ADD)
5942 (if (js2-match-char ?+)
5943 (js2-ts-return js2-INC)
5944 (throw 'return js2-ADD))))
5945 (?-
5946 (cond
5947 ((js2-match-char ?=)
5948 (setq c js2-ASSIGN_SUB))
5949 ((js2-match-char ?-)
5950 (unless js2-ts-dirty-line
5951 ;; treat HTML end-comment after possible whitespace
5952 ;; after line start as comment-until-eol
5953 (when (js2-match-char ?>)
5954 (js2-skip-line)
5955 (setq js2-ts-comment-type 'html)
5956 (throw 'return js2-COMMENT)))
5957 (setq c js2-DEC))
5958 (t
5959 (setq c js2-SUB)))
5960 (setq js2-ts-dirty-line t)
5961 (js2-ts-return c))
5962 (otherwise
5963 (js2-report-scan-error "msg.illegal.character")))))))
5964
5965 (defun js2-read-regexp (start-token)
5966 "Called by parser when it gets / or /= in literal context."
5967 (let (c
5968 err
5969 in-class ; inside a '[' .. ']' character-class
5970 flags
5971 (continue t))
5972 (setq js2-token-beg js2-ts-cursor
5973 js2-ts-string-buffer nil
5974 js2-ts-regexp-flags nil)
5975 (if (eq start-token js2-ASSIGN_DIV)
5976 ;; mis-scanned /=
5977 (js2-add-to-string ?=)
5978 (if (not (eq start-token js2-DIV))
5979 (error "failed assertion")))
5980 (while (and (not err)
5981 (or (/= (setq c (js2-get-char)) ?/)
5982 in-class))
5983 (cond
5984 ((or (= c ?\n)
5985 (= c js2-EOF_CHAR))
5986 (setq js2-token-end (1- js2-ts-cursor)
5987 err t
5988 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5989 (js2-report-error "msg.unterminated.re.lit"))
5990 (t (cond
5991 ((= c ?\\)
5992 (js2-add-to-string c)
5993 (setq c (js2-get-char)))
5994 ((= c ?\[)
5995 (setq in-class t))
5996 ((= c ?\])
5997 (setq in-class nil)))
5998 (js2-add-to-string c))))
5999 (unless err
6000 (while continue
6001 (cond
6002 ((js2-match-char ?g)
6003 (push ?g flags))
6004 ((js2-match-char ?i)
6005 (push ?i flags))
6006 ((js2-match-char ?m)
6007 (push ?m flags))
6008 (t
6009 (setq continue nil))))
6010 (if (js2-alpha-p (js2-peek-char))
6011 (js2-report-scan-error "msg.invalid.re.flag" t
6012 js2-ts-cursor 1))
6013 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6014 js2-ts-regexp-flags (js2-collect-string flags)
6015 js2-token-end js2-ts-cursor)
6016 ;; tell `parse-partial-sexp' to ignore this range of chars
6017 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6018
6019 (defun js2-get-first-xml-token ()
6020 (setq js2-ts-xml-open-tags-count 0
6021 js2-ts-is-xml-attribute nil
6022 js2-ts-xml-is-tag-content nil)
6023 (js2-unget-char)
6024 (js2-get-next-xml-token))
6025
6026 (defsubst js2-xml-discard-string ()
6027 "Throw away the string in progress and flag an XML parse error."
6028 (setq js2-ts-string-buffer nil
6029 js2-ts-string nil)
6030 (js2-report-scan-error "msg.XML.bad.form" t))
6031
6032 (defun js2-get-next-xml-token ()
6033 (setq js2-ts-string-buffer nil ; for recording the XML
6034 js2-token-beg js2-ts-cursor)
6035 (let (c result)
6036 (setq result
6037 (catch 'return
6038 (while t
6039 (setq c (js2-get-char))
6040 (cond
6041 ((= c js2-EOF_CHAR)
6042 (throw 'return js2-ERROR))
6043 (js2-ts-xml-is-tag-content
6044 (case c
6045 (?>
6046 (js2-add-to-string c)
6047 (setq js2-ts-xml-is-tag-content nil
6048 js2-ts-is-xml-attribute nil))
6049 (?/
6050 (js2-add-to-string c)
6051 (when (eq ?> (js2-peek-char))
6052 (setq c (js2-get-char))
6053 (js2-add-to-string c)
6054 (setq js2-ts-xml-is-tag-content nil)
6055 (decf js2-ts-xml-open-tags-count)))
6056 (?{
6057 (js2-unget-char)
6058 (setq js2-ts-string (js2-get-string-from-buffer))
6059 (throw 'return js2-XML))
6060 ((?\' ?\")
6061 (js2-add-to-string c)
6062 (unless (js2-read-quoted-string c)
6063 (throw 'return js2-ERROR)))
6064 (?=
6065 (js2-add-to-string c)
6066 (setq js2-ts-is-xml-attribute t))
6067 ((? ?\t ?\r ?\n)
6068 (js2-add-to-string c))
6069 (t
6070 (js2-add-to-string c)
6071 (setq js2-ts-is-xml-attribute nil)))
6072 (when (and (not js2-ts-xml-is-tag-content)
6073 (zerop js2-ts-xml-open-tags-count))
6074 (setq js2-ts-string (js2-get-string-from-buffer))
6075 (throw 'return js2-XMLEND)))
6076 (t
6077 ;; else not tag content
6078 (case c
6079 (?<
6080 (js2-add-to-string c)
6081 (setq c (js2-peek-char))
6082 (case c
6083 (?!
6084 (setq c (js2-get-char)) ;; skip !
6085 (js2-add-to-string c)
6086 (setq c (js2-peek-char))
6087 (case c
6088 (?-
6089 (setq c (js2-get-char)) ;; skip -
6090 (js2-add-to-string c)
6091 (if (eq c ?-)
6092 (progn
6093 (js2-add-to-string c)
6094 (unless (js2-read-xml-comment)
6095 (throw 'return js2-ERROR)))
6096 (js2-xml-discard-string)
6097 (throw 'return js2-ERROR)))
6098 (?\[
6099 (setq c (js2-get-char)) ;; skip [
6100 (js2-add-to-string c)
6101 (if (and (= (js2-get-char) ?C)
6102 (= (js2-get-char) ?D)
6103 (= (js2-get-char) ?A)
6104 (= (js2-get-char) ?T)
6105 (= (js2-get-char) ?A)
6106 (= (js2-get-char) ?\[))
6107 (progn
6108 (js2-add-to-string ?C)
6109 (js2-add-to-string ?D)
6110 (js2-add-to-string ?A)
6111 (js2-add-to-string ?T)
6112 (js2-add-to-string ?A)
6113 (js2-add-to-string ?\[)
6114 (unless (js2-read-cdata)
6115 (throw 'return js2-ERROR)))
6116 (js2-xml-discard-string)
6117 (throw 'return js2-ERROR)))
6118 (t
6119 (unless (js2-read-entity)
6120 (throw 'return js2-ERROR)))))
6121 (??
6122 (setq c (js2-get-char)) ;; skip ?
6123 (js2-add-to-string c)
6124 (unless (js2-read-PI)
6125 (throw 'return js2-ERROR)))
6126 (?/
6127 ;; end tag
6128 (setq c (js2-get-char)) ;; skip /
6129 (js2-add-to-string c)
6130 (when (zerop js2-ts-xml-open-tags-count)
6131 (js2-xml-discard-string)
6132 (throw 'return js2-ERROR))
6133 (setq js2-ts-xml-is-tag-content t)
6134 (decf js2-ts-xml-open-tags-count))
6135 (t
6136 ;; start tag
6137 (setq js2-ts-xml-is-tag-content t)
6138 (incf js2-ts-xml-open-tags-count))))
6139 (?{
6140 (js2-unget-char)
6141 (setq js2-ts-string (js2-get-string-from-buffer))
6142 (throw 'return js2-XML))
6143 (t
6144 (js2-add-to-string c))))))))
6145 (setq js2-token-end js2-ts-cursor)
6146 result))
6147
6148 (defun js2-read-quoted-string (quote)
6149 (let (c)
6150 (catch 'return
6151 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6152 (js2-add-to-string c)
6153 (if (eq c quote)
6154 (throw 'return t)))
6155 (js2-xml-discard-string) ;; throw away string in progress
6156 nil)))
6157
6158 (defun js2-read-xml-comment ()
6159 (let ((c (js2-get-char)))
6160 (catch 'return
6161 (while (/= c js2-EOF_CHAR)
6162 (catch 'continue
6163 (js2-add-to-string c)
6164 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6165 (setq c (js2-get-char))
6166 (js2-add-to-string c)
6167 (if (eq (js2-peek-char) ?>)
6168 (progn
6169 (setq c (js2-get-char)) ;; skip >
6170 (js2-add-to-string c)
6171 (throw 'return t))
6172 (throw 'continue nil)))
6173 (setq c (js2-get-char))))
6174 (js2-xml-discard-string)
6175 nil)))
6176
6177 (defun js2-read-cdata ()
6178 (let ((c (js2-get-char)))
6179 (catch 'return
6180 (while (/= c js2-EOF_CHAR)
6181 (catch 'continue
6182 (js2-add-to-string c)
6183 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6184 (setq c (js2-get-char))
6185 (js2-add-to-string c)
6186 (if (eq (js2-peek-char) ?>)
6187 (progn
6188 (setq c (js2-get-char)) ;; Skip >
6189 (js2-add-to-string c)
6190 (throw 'return t))
6191 (throw 'continue nil)))
6192 (setq c (js2-get-char))))
6193 (js2-xml-discard-string)
6194 nil)))
6195
6196 (defun js2-read-entity ()
6197 (let ((decl-tags 1)
6198 c)
6199 (catch 'return
6200 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6201 (js2-add-to-string c)
6202 (case c
6203 (?<
6204 (incf decl-tags))
6205 (?>
6206 (decf decl-tags)
6207 (if (zerop decl-tags)
6208 (throw 'return t)))))
6209 (js2-xml-discard-string)
6210 nil)))
6211
6212 (defun js2-read-PI ()
6213 "Scan an XML processing instruction."
6214 (let (c)
6215 (catch 'return
6216 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6217 (js2-add-to-string c)
6218 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6219 (setq c (js2-get-char)) ;; Skip >
6220 (js2-add-to-string c)
6221 (throw 'return t)))
6222 (js2-xml-discard-string)
6223 nil)))
6224
6225 (defun js2-scanner-get-line ()
6226 "Return the text of the current scan line."
6227 (buffer-substring (point-at-bol) (point-at-eol)))
6228
6229 ;;; Highlighting
6230
6231 (defsubst js2-set-face (beg end face &optional record)
6232 "Fontify a region. If RECORD is non-nil, record for later."
6233 (when (plusp js2-highlight-level)
6234 (setq beg (min (point-max) beg)
6235 beg (max (point-min) beg)
6236 end (min (point-max) end)
6237 end (max (point-min) end))
6238 (if record
6239 (push (list beg end face) js2-mode-fontifications)
6240 (put-text-property beg end 'face face))))
6241
6242 (defsubst js2-set-kid-face (pos kid len face)
6243 "Set-face on a child node.
6244 POS is absolute buffer position of parent.
6245 KID is the child node.
6246 LEN is the length to fontify.
6247 FACE is the face to fontify with."
6248 (js2-set-face (+ pos (js2-node-pos kid))
6249 (+ pos (js2-node-pos kid) (js2-node-len kid))
6250 face))
6251
6252 (defsubst js2-fontify-kwd (start length)
6253 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6254
6255 (defsubst js2-clear-face (beg end)
6256 (remove-text-properties beg end '(face nil
6257 help-echo nil
6258 point-entered nil
6259 c-in-sws nil)))
6260
6261 (defsubst js2-record-text-property (beg end prop value)
6262 "Record a text property to set when parsing finishes."
6263 (push (list beg end prop value) js2-mode-deferred-properties))
6264
6265 (defconst js2-ecma-global-props
6266 (concat "^"
6267 (regexp-opt
6268 '("Infinity" "NaN" "undefined" "arguments") t)
6269 "$")
6270 "Value properties of the Ecma-262 Global Object.
6271 Shown at or above `js2-highlight-level' 2.")
6272
6273 ;; might want to add the name "arguments" to this list?
6274 (defconst js2-ecma-object-props
6275 (concat "^"
6276 (regexp-opt
6277 '("prototype" "__proto__" "__parent__") t)
6278 "$")
6279 "Value properties of the Ecma-262 Object constructor.
6280 Shown at or above `js2-highlight-level' 2.")
6281
6282 (defconst js2-ecma-global-funcs
6283 (concat
6284 "^"
6285 (regexp-opt
6286 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6287 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6288 "$")
6289 "Function properties of the Ecma-262 Global object.
6290 Shown at or above `js2-highlight-level' 2.")
6291
6292 (defconst js2-ecma-number-props
6293 (concat "^"
6294 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6295 "NEGATIVE_INFINITY"
6296 "POSITIVE_INFINITY") t)
6297 "$")
6298 "Properties of the Ecma-262 Number constructor.
6299 Shown at or above `js2-highlight-level' 2.")
6300
6301 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6302 "Properties of the Ecma-262 Date constructor.
6303 Shown at or above `js2-highlight-level' 2.")
6304
6305 (defconst js2-ecma-math-props
6306 (concat "^"
6307 (regexp-opt
6308 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6309 t)
6310 "$")
6311 "Properties of the Ecma-262 Math object.
6312 Shown at or above `js2-highlight-level' 2.")
6313
6314 (defconst js2-ecma-math-funcs
6315 (concat "^"
6316 (regexp-opt
6317 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6318 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6319 "$")
6320 "Function properties of the Ecma-262 Math object.
6321 Shown at or above `js2-highlight-level' 2.")
6322
6323 (defconst js2-ecma-function-props
6324 (concat
6325 "^"
6326 (regexp-opt
6327 '(;; properties of the Object prototype object
6328 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6329 "toLocaleString" "toString" "valueOf"
6330 ;; properties of the Function prototype object
6331 "apply" "call"
6332 ;; properties of the Array prototype object
6333 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6334 "splice" "unshift"
6335 ;; properties of the String prototype object
6336 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6337 "localeCompare" "match" "replace" "search" "split" "substring"
6338 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6339 "toUpperCase"
6340 ;; properties of the Number prototype object
6341 "toExponential" "toFixed" "toPrecision"
6342 ;; properties of the Date prototype object
6343 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6344 "getMinutes" "getMonth" "getSeconds" "getTime"
6345 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6346 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6347 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6348 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6349 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6350 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6351 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6352 "toTimeString" "toUTCString"
6353 ;; properties of the RegExp prototype object
6354 "exec" "test"
6355 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6356 "toSource" "__defineGetter__" "__defineSetter__"
6357 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6358 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6359 t)
6360 "$")
6361 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6362 Shown at or above `js2-highlight-level' 3.")
6363
6364 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6365 (let ((target-name (and target
6366 (js2-name-node-p target)
6367 (js2-name-node-name target)))
6368 (prop-name (if prop (js2-name-node-name prop)))
6369 (level1 (>= js2-highlight-level 1))
6370 (level2 (>= js2-highlight-level 2))
6371 (level3 (>= js2-highlight-level 3))
6372 pos
6373 face)
6374 (when level2
6375 (if call-p
6376 (cond
6377 ((and target prop)
6378 (cond
6379 ((and level3 (string-match js2-ecma-function-props prop-name))
6380 (setq face 'font-lock-builtin-face))
6381 ((and target-name prop)
6382 (cond
6383 ((string= target-name "Date")
6384 (if (string-match js2-ecma-date-props prop-name)
6385 (setq face 'font-lock-builtin-face)))
6386 ((string= target-name "Math")
6387 (if (string-match js2-ecma-math-funcs prop-name)
6388 (setq face 'font-lock-builtin-face)))))))
6389 (prop
6390 (if (string-match js2-ecma-global-funcs prop-name)
6391 (setq face 'font-lock-builtin-face))))
6392 (cond
6393 ((and target prop)
6394 (cond
6395 ((string= target-name "Number")
6396 (if (string-match js2-ecma-number-props prop-name)
6397 (setq face 'font-lock-constant-face)))
6398 ((string= target-name "Math")
6399 (if (string-match js2-ecma-math-props prop-name)
6400 (setq face 'font-lock-constant-face)))))
6401 (prop
6402 (if (string-match js2-ecma-object-props prop-name)
6403 (setq face 'font-lock-constant-face)))))
6404 (when face
6405 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6406 (js2-node-pos prop))) ; relative
6407 (+ pos (js2-node-len prop))
6408 face)))))
6409
6410 (defun js2-parse-highlight-member-expr-node (node)
6411 "Perform syntax highlighting of EcmaScript built-in properties.
6412 The variable `js2-highlight-level' governs this highighting."
6413 (let (face target prop name pos end parent call-p callee)
6414 (cond
6415 ;; case 1: simple name, e.g. foo
6416 ((js2-name-node-p node)
6417 (setq name (js2-name-node-name node))
6418 ;; possible for name to be nil in rare cases - saw it when
6419 ;; running js2-mode on an elisp buffer. Might as well try to
6420 ;; make it so js2-mode never barfs.
6421 (when name
6422 (setq face (if (string-match js2-ecma-global-props name)
6423 'font-lock-constant-face))
6424 (when face
6425 (setq pos (js2-node-pos node)
6426 end (+ pos (js2-node-len node)))
6427 (js2-set-face pos end face))))
6428 ;; case 2: property access or function call
6429 ((or (js2-prop-get-node-p node)
6430 ;; highlight function call if expr is a prop-get node
6431 ;; or a plain name (i.e. unqualified function call)
6432 (and (setq call-p (js2-call-node-p node))
6433 (setq callee (js2-call-node-target node)) ; separate setq!
6434 (or (js2-prop-get-node-p callee)
6435 (js2-name-node-p callee))))
6436 (setq parent node
6437 node (if call-p callee node))
6438 (if (and call-p (js2-name-node-p callee))
6439 (setq prop callee)
6440 (setq target (js2-prop-get-node-left node)
6441 prop (js2-prop-get-node-right node)))
6442 (cond
6443 ((js2-name-node-p target)
6444 (if (js2-name-node-p prop)
6445 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6446 (js2-parse-highlight-prop-get parent target prop call-p)
6447 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6448 (js2-parse-highlight-prop-get parent target nil call-p)))
6449 ((js2-name-node-p prop)
6450 ;; case 2c: complex target, simple name, e.g. x[y].bar
6451 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6452
6453 (defun js2-parse-highlight-member-expr-fn-name (expr)
6454 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6455 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6456 We currently only handle the case where the last component is a prop-get
6457 of a simple name. Called before EXPR has a parent node."
6458 (let (pos
6459 (name (and (js2-prop-get-node-p expr)
6460 (js2-prop-get-node-right expr))))
6461 (when (js2-name-node-p name)
6462 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6463 (js2-node-pos name)))
6464 (+ pos (js2-node-len name))
6465 'font-lock-function-name-face
6466 'record))))
6467
6468 ;; source: http://jsdoc.sourceforge.net/
6469 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6470 ;; allows type specifications, and needs work before entering the wild.
6471
6472 (defconst js2-jsdoc-param-tag-regexp
6473 (concat "^\\s-*\\*+\\s-*\\(@"
6474 "\\(?:param\\|argument\\)"
6475 "\\)"
6476 "\\s-*\\({[^}]+}\\)?" ; optional type
6477 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6478 "\\>")
6479 "Matches jsdoc tags with optional type and optional param name.")
6480
6481 (defconst js2-jsdoc-typed-tag-regexp
6482 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6483 (regexp-opt
6484 '("enum"
6485 "extends"
6486 "field"
6487 "id"
6488 "implements"
6489 "lends"
6490 "mods"
6491 "requires"
6492 "return"
6493 "returns"
6494 "throw"
6495 "throws"))
6496 "\\)\\)\\s-*\\({[^}]+}\\)?")
6497 "Matches jsdoc tags with optional type.")
6498
6499 (defconst js2-jsdoc-arg-tag-regexp
6500 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6501 (regexp-opt
6502 '("alias"
6503 "augments"
6504 "borrows"
6505 "bug"
6506 "base"
6507 "config"
6508 "default"
6509 "define"
6510 "exception"
6511 "function"
6512 "member"
6513 "memberOf"
6514 "name"
6515 "namespace"
6516 "property"
6517 "since"
6518 "suppress"
6519 "this"
6520 "throws"
6521 "type"
6522 "version"))
6523 "\\)\\)\\s-+\\([^ \t]+\\)")
6524 "Matches jsdoc tags with a single argument.")
6525
6526 (defconst js2-jsdoc-empty-tag-regexp
6527 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6528 (regexp-opt
6529 '("addon"
6530 "author"
6531 "class"
6532 "const"
6533 "constant"
6534 "constructor"
6535 "constructs"
6536 "deprecated"
6537 "desc"
6538 "description"
6539 "event"
6540 "example"
6541 "exec"
6542 "export"
6543 "fileoverview"
6544 "final"
6545 "function"
6546 "hidden"
6547 "ignore"
6548 "implicitCast"
6549 "inheritDoc"
6550 "inner"
6551 "interface"
6552 "license"
6553 "noalias"
6554 "noshadow"
6555 "notypecheck"
6556 "override"
6557 "owner"
6558 "preserve"
6559 "preserveTry"
6560 "private"
6561 "protected"
6562 "public"
6563 "static"
6564 "supported"
6565 ))
6566 "\\)\\)\\s-*")
6567 "Matches empty jsdoc tags.")
6568
6569 (defconst js2-jsdoc-link-tag-regexp
6570 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6571 "Matches a jsdoc link or code tag.")
6572
6573 (defconst js2-jsdoc-see-tag-regexp
6574 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6575 "Matches a jsdoc @see tag.")
6576
6577 (defconst js2-jsdoc-html-tag-regexp
6578 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6579 "Matches a simple (no attributes) html start- or end-tag.")
6580
6581 (defsubst js2-jsdoc-highlight-helper ()
6582 (js2-set-face (match-beginning 1)
6583 (match-end 1)
6584 'js2-jsdoc-tag-face)
6585 (if (match-beginning 2)
6586 (if (save-excursion
6587 (goto-char (match-beginning 2))
6588 (= (char-after) ?{))
6589 (js2-set-face (1+ (match-beginning 2))
6590 (1- (match-end 2))
6591 'js2-jsdoc-type-face)
6592 (js2-set-face (match-beginning 2)
6593 (match-end 2)
6594 'js2-jsdoc-value-face)))
6595 (if (match-beginning 3)
6596 (js2-set-face (match-beginning 3)
6597 (match-end 3)
6598 'js2-jsdoc-value-face)))
6599
6600 (defun js2-highlight-jsdoc (ast)
6601 "Highlight doc comment tags."
6602 (let ((comments (js2-ast-root-comments ast))
6603 beg end)
6604 (save-excursion
6605 (dolist (node comments)
6606 (when (eq (js2-comment-node-format node) 'jsdoc)
6607 (setq beg (js2-node-abs-pos node)
6608 end (+ beg (js2-node-len node)))
6609 (save-restriction
6610 (narrow-to-region beg end)
6611 (dolist (re (list js2-jsdoc-param-tag-regexp
6612 js2-jsdoc-typed-tag-regexp
6613 js2-jsdoc-arg-tag-regexp
6614 js2-jsdoc-link-tag-regexp
6615 js2-jsdoc-see-tag-regexp
6616 js2-jsdoc-empty-tag-regexp))
6617 (goto-char beg)
6618 (while (re-search-forward re nil t)
6619 (js2-jsdoc-highlight-helper)))
6620 ;; simple highlighting for html tags
6621 (goto-char beg)
6622 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6623 (js2-set-face (match-beginning 1)
6624 (match-end 1)
6625 'js2-jsdoc-html-tag-delimiter-face)
6626 (js2-set-face (match-beginning 2)
6627 (match-end 2)
6628 'js2-jsdoc-html-tag-name-face)
6629 (js2-set-face (match-beginning 3)
6630 (match-end 3)
6631 'js2-jsdoc-html-tag-delimiter-face))))))))
6632
6633 (defun js2-highlight-assign-targets (node left right)
6634 "Highlight function properties and external variables."
6635 (let (leftpos end name)
6636 ;; highlight vars and props assigned function values
6637 (when (js2-function-node-p right)
6638 (cond
6639 ;; var foo = function() {...}
6640 ((js2-name-node-p left)
6641 (setq name left))
6642 ;; foo.bar.baz = function() {...}
6643 ((and (js2-prop-get-node-p left)
6644 (js2-name-node-p (js2-prop-get-node-right left)))
6645 (setq name (js2-prop-get-node-right left))))
6646 (when name
6647 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6648 (+ leftpos (js2-node-len name))
6649 'font-lock-function-name-face
6650 'record)))))
6651
6652 (defun js2-record-name-node (node)
6653 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6654 later. NODE must be a name node."
6655 (push (list node js2-current-scope
6656 (setq leftpos (js2-node-abs-pos node))
6657 (setq end (+ leftpos (js2-node-len node))))
6658 js2-recorded-identifiers))
6659
6660 (defun js2-highlight-undeclared-vars ()
6661 "After entire parse is finished, look for undeclared variable references.
6662 We have to wait until entire buffer is parsed, since JavaScript permits var
6663 decls to occur after they're used.
6664
6665 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6666 it is considered declared."
6667 (let (name)
6668 (dolist (entry js2-recorded-identifiers)
6669 (destructuring-bind (name-node scope pos end) entry
6670 (setq name (js2-name-node-name name-node))
6671 (unless (or (member name js2-global-externs)
6672 (member name js2-default-externs)
6673 (member name js2-additional-externs)
6674 (js2-get-defining-scope scope name))
6675 (js2-set-face pos end 'js2-external-variable-face 'record)
6676 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6677 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6678 (setq js2-recorded-identifiers nil)))
6679
6680 ;;; IMenu support
6681
6682 ;; We currently only support imenu, but eventually should support speedbar and
6683 ;; possibly other browsing mechanisms.
6684
6685 ;; The basic strategy is to identify function assignment targets of the form
6686 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6687 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6688 ;; for imenu after parsing is finished.
6689
6690 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6691 ;; JavaScript, and the general problem is undecidable. However, several forms
6692 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6693 ;; include:
6694
6695 ;; function foo() -- function declaration
6696 ;; foo = function() -- function expression assigned to variable
6697 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6698 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6699 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6700 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6701 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6702 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6703 ;; function foo() {function bar() {...}} -- nested function
6704 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6705
6706 ;; This list boils down to a few forms that can be combined recursively.
6707 ;; Top-level named function declarations include both the left-hand (name)
6708 ;; and the right-hand (function value) expressions needed to produce an imenu
6709 ;; entry. The other "right-hand" forms we need to look for are:
6710 ;; - functions declared as props/getters/setters in object literals
6711 ;; - nested named function declarations
6712 ;; The "left-hand" expressions that functions can be assigned to include:
6713 ;; - local/global variables
6714 ;; - nested property-get expressions like a.b.c.d
6715 ;; - element gets like foo[10] or foo['bar'] where the index
6716 ;; expression can be trivially converted to a property name. They
6717 ;; effectively then become property gets.
6718
6719 ;; All the different definition types are canonicalized into the form
6720 ;; foo.bar.baz = position-of-function-keyword
6721
6722 ;; We need to build a trie-like structure for imenu. As an example,
6723 ;; consider the following JavaScript code:
6724
6725 ;; a = function() {...} // function at position 5
6726 ;; b = function() {...} // function at position 25
6727 ;; foo = function() {...} // function at position 100
6728 ;; foo.bar = function() {...} // function at position 200
6729 ;; foo.bar.baz = function() {...} // function at position 300
6730 ;; foo.bar.zab = function() {...} // function at position 400
6731
6732 ;; During parsing we accumulate an entry for each definition in
6733 ;; the variable `js2-imenu-recorder', like so:
6734
6735 ;; '((a 5)
6736 ;; (b 25)
6737 ;; (foo 100)
6738 ;; (foo bar 200)
6739 ;; (foo bar baz 300)
6740 ;; (foo bar zab 400))
6741
6742 ;; After parsing these entries are merged into this alist-trie:
6743
6744 ;; '((a . 1)
6745 ;; (b . 2)
6746 ;; (foo (<definition> . 3)
6747 ;; (bar (<definition> . 6)
6748 ;; (baz . 100)
6749 ;; (zab . 200))))
6750
6751 ;; Note the wacky need for a <definition> name. The token can be anything
6752 ;; that isn't a valid JavaScript identifier, because you might make foo
6753 ;; a function and then start setting properties on it that are also functions.
6754
6755 (defsubst js2-prop-node-name (node)
6756 "Return the name of a node that may be a property-get/property-name.
6757 If NODE is not a valid name-node, string-node or integral number-node,
6758 returns nil. Otherwise returns the string name/value of the node."
6759 (cond
6760 ((js2-name-node-p node)
6761 (js2-name-node-name node))
6762 ((js2-string-node-p node)
6763 (js2-string-node-value node))
6764 ((and (js2-number-node-p node)
6765 (string-match "^[0-9]+$" (js2-number-node-value node)))
6766 (js2-number-node-value node))
6767 ((js2-this-node-p node)
6768 "this")))
6769
6770 (defsubst js2-node-qname-component (node)
6771 "Test function: return the name of this node, if it contributes to a qname.
6772 Returns nil if the node doesn't contribute."
6773 (copy-sequence
6774 (or (js2-prop-node-name node)
6775 (if (and (js2-function-node-p node)
6776 (js2-function-node-name node))
6777 (js2-name-node-name (js2-function-node-name node))))))
6778
6779 (defsubst js2-record-function-qname (fn-node qname)
6780 "Associate FN-NODE with its QNAME for later lookup.
6781 This is used in postprocessing the chain list. When we find a chain
6782 whose first element is a js2-THIS keyword node, we look up the parent
6783 function and see (using this map) whether it is the tail of a chain.
6784 If so, we replace the this-node with a copy of the parent's qname."
6785 (unless js2-imenu-function-map
6786 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6787 (puthash fn-node qname js2-imenu-function-map))
6788
6789 (defun js2-record-imenu-functions (node &optional var)
6790 "Record function definitions for imenu.
6791 NODE is a function node or an object literal.
6792 VAR, if non-nil, is the expression that NODE is being assigned to."
6793 (when js2-parse-ide-mode
6794 (let ((fun-p (js2-function-node-p node))
6795 qname left fname-node pos)
6796 (cond
6797 ;; non-anonymous function declaration?
6798 ((and fun-p
6799 (not var)
6800 (setq fname-node (js2-function-node-name node)))
6801 (push (setq qname (list fname-node (js2-node-pos node)))
6802 js2-imenu-recorder)
6803 (js2-record-function-qname node qname))
6804 ;; for remaining forms, compute left-side tree branch first
6805 ((and var (setq qname (js2-compute-nested-prop-get var)))
6806 (cond
6807 ;; foo.bar.baz = function
6808 (fun-p
6809 (push (nconc qname (list (js2-node-pos node)))
6810 js2-imenu-recorder)
6811 (js2-record-function-qname node qname))
6812 ;; foo.bar.baz = object-literal
6813 ;; look for nested functions: {a: {b: function() {...} }}
6814 ((js2-object-node-p node)
6815 ;; Node position here is still absolute, since the parser
6816 ;; passes the assignment target and value expressions
6817 ;; to us before they are added as children of the assignment node.
6818 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6819
6820 (defun js2-compute-nested-prop-get (node)
6821 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6822 component nodes as a list. Otherwise return nil. Element-gets are treated
6823 as property-gets if the index expression is a string, or a positive integer."
6824 (let (left right head)
6825 (cond
6826 ((or (js2-name-node-p node)
6827 (js2-this-node-p node))
6828 (list node))
6829 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6830 ((js2-prop-get-node-p node) ; foo.bar
6831 (setq left (js2-prop-get-node-left node)
6832 right (js2-prop-get-node-right node))
6833 (if (setq head (js2-compute-nested-prop-get left))
6834 (nconc head (list right))))
6835 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6836 (setq left (js2-elem-get-node-target node)
6837 right (js2-elem-get-node-element node))
6838 (if (or (js2-string-node-p right) ; ['bar']
6839 (and (js2-number-node-p right) ; [10]
6840 (string-match "^[0-9]+$"
6841 (js2-number-node-value right))))
6842 (if (setq head (js2-compute-nested-prop-get left))
6843 (nconc head (list right))))))))
6844
6845 (defun js2-record-object-literal (node qname pos)
6846 "Recursively process an object literal looking for functions.
6847 NODE is an object literal that is the right-hand child of an assignment
6848 expression. QNAME is a list of nodes representing the assignment target,
6849 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6850 POS is the absolute position of the node.
6851 We do a depth-first traversal of NODE. Any functions we find are prefixed
6852 with QNAME plus the property name of the function and appended to the
6853 variable `js2-imenu-recorder'."
6854 (let (left right)
6855 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6856 (let ((left (js2-infix-node-left e))
6857 ;; Element positions are relative to the parent position.
6858 (pos (+ pos (js2-node-pos e))))
6859 (cond
6860 ;; foo: function() {...}
6861 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6862 (when (js2-prop-node-name left)
6863 ;; As a policy decision, we record the position of the property,
6864 ;; not the position of the `function' keyword, since the property
6865 ;; is effectively the name of the function.
6866 (push (append qname (list left pos))
6867 js2-imenu-recorder)
6868 (js2-record-function-qname right qname)))
6869 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6870 ((js2-object-node-p right)
6871 (js2-record-object-literal right
6872 (append qname (list (js2-infix-node-left e)))
6873 (+ pos (js2-node-pos right)))))))))
6874
6875 (defsubst js2-node-top-level-decl-p (node)
6876 "Return t if NODE's name is defined in the top-level scope.
6877 Also returns t if NODE's name is not defined in any scope, since it implies
6878 that it's an external variable, which must also be in the top-level scope."
6879 (let* ((name (js2-prop-node-name node))
6880 (this-scope (js2-node-get-enclosing-scope node))
6881 defining-scope)
6882 (cond
6883 ((js2-this-node-p node)
6884 nil)
6885 ((null this-scope)
6886 t)
6887 ((setq defining-scope (js2-get-defining-scope this-scope name))
6888 (js2-ast-root-p defining-scope))
6889 (t t))))
6890
6891 (defun js2-browse-postprocess-chains (chains)
6892 "Modify function-declaration name chains after parsing finishes.
6893 Some of the information is only available after the parse tree is complete.
6894 For instance, following a 'this' reference requires a parent function node."
6895 (let (result head fn parent-chain p elem)
6896 (dolist (chain chains)
6897 ;; examine the head of each node to get its defining scope
6898 (setq head (car chain))
6899 ;; if top-level/external, keep as-is
6900 (if (js2-node-top-level-decl-p head)
6901 (push chain result)
6902 (cond
6903 ;; starts with this-reference
6904 ((js2-this-node-p head)
6905 (setq fn (js2-node-parent-script-or-fn head)
6906 chain (cdr chain))) ; discard this-node
6907 ;; nested named function
6908 ((js2-function-node-p (setq parent (js2-node-parent head)))
6909 (setq fn (js2-node-parent-script-or-fn parent)))
6910 ;; variable assigned a function expression
6911 (t (setq fn (js2-node-parent-script-or-fn head))))
6912 (unless (or (null fn) (js2-nested-function-p fn))
6913 ;; if the parent function is found, and it's not nested,
6914 ;; look it up in function-map.
6915 (if (setq parent-chain (and js2-imenu-function-map
6916 (gethash fn js2-imenu-function-map)))
6917 ;; prefix parent fn qname, which is the
6918 ;; parent-chain sans tail, to this chain.
6919 (push (append (butlast parent-chain) chain) result)
6920 ;; parent function is not nested, and not in function-map
6921 ;; => it's anonymous top-level wrapper, discard.
6922 (push chain result)))))
6923 ;; finally replace each node in each chain with its name.
6924 (dolist (chain result)
6925 (setq p chain)
6926 (while p
6927 (if (js2-node-p (setq elem (car p)))
6928 (setcar p (js2-node-qname-component elem)))
6929 (setq p (cdr p))))
6930 result))
6931
6932 ;; Merge name chains into a trie-like tree structure of nested lists.
6933 ;; To simplify construction of the trie, we first build it out using the rule
6934 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6935 ;; [key, num-or-list]. The second element can be a number; if so, this key
6936 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6937 ;; associated with the key at this level.) Otherwise the second element is
6938 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6939 ;; a simple recursive formulation.
6940 ;;
6941 ;; js2-mode is building the data structure for imenu. The imenu documentation
6942 ;; claims that it's the structure above, but in practice it wants the children
6943 ;; at the same list level as the key for that level, which is how I've drawn
6944 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6945 ;; list wrapper around the children at each level.
6946 ;;
6947 ;; A completed nested imenu-alist entry looks like this:
6948 ;; '(("foo"
6949 ;; ("<definition>" . 7)
6950 ;; ("bar"
6951 ;; ("a" . 40)
6952 ;; ("b" . 60))))
6953 ;;
6954 ;; In particular, the documentation for `imenu--index-alist' says that
6955 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6956 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6957
6958 (defsubst js2-treeify (lst)
6959 "Convert (a b c d) to (a ((b ((c d)))))"
6960 (if (null (cddr lst)) ; list length <= 2
6961 lst
6962 (list (car lst) (list (js2-treeify (cdr lst))))))
6963
6964 (defun js2-build-alist-trie (chains trie)
6965 "Merge declaration name chains into a trie-like alist structure for imenu.
6966 CHAINS is the qname chain list produced during parsing. TRIE is a
6967 list of elements built up so far."
6968 (let (head tail pos branch kids)
6969 (dolist (chain chains)
6970 (setq head (car chain)
6971 tail (cdr chain)
6972 pos (if (numberp (car tail)) (car tail))
6973 branch (js2-find-if (lambda (n)
6974 (string= (car n) head))
6975 trie)
6976 kids (second branch))
6977 (cond
6978 ;; case 1: this key isn't in the trie yet
6979 ((null branch)
6980 (if trie
6981 (setcdr (last trie) (list (js2-treeify chain)))
6982 (setq trie (list (js2-treeify chain)))))
6983 ;; case 2: key is present with a single number entry: replace w/ list
6984 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6985 ;; ("<definition>" 20)))
6986 ((numberp kids)
6987 (setcar (cdr branch)
6988 (list (list "<definition-1>" kids)
6989 (if pos
6990 (list "<definition-2>" pos)
6991 (js2-treeify tail)))))
6992 ;; case 3: key is there (with kids), and we're a number entry
6993 (pos
6994 (setcdr (last kids)
6995 (list
6996 (list (format "<definition-%d>"
6997 (1+ (loop for kid in kids
6998 count (eq ?< (aref (car kid) 0)))))
6999 pos))))
7000 ;; case 4: key is there with kids, need to merge in our chain
7001 (t
7002 (js2-build-alist-trie (list tail) kids))))
7003 trie))
7004
7005 (defun js2-flatten-trie (trie)
7006 "Convert TRIE to imenu-format.
7007 Recurses through nodes, and for each one whose second element is a list,
7008 appends the list's flattened elements to the current element. Also
7009 changes the tails into conses. For instance, this pre-flattened trie
7010
7011 '(a ((b 20)
7012 (c ((d 30)
7013 (e 40)))))
7014
7015 becomes
7016
7017 '(a (b . 20)
7018 (c (d . 30)
7019 (e . 40)))
7020
7021 Note that the root of the trie has no key, just a list of chains.
7022 This is also true for the value of any key with multiple children,
7023 e.g. key 'c' in the example above."
7024 (cond
7025 ((listp (car trie))
7026 (mapcar #'js2-flatten-trie trie))
7027 (t
7028 (if (numberp (second trie))
7029 (cons (car trie) (second trie))
7030 ;; else pop list and append its kids
7031 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7032
7033 (defun js2-build-imenu-index ()
7034 "Turn `js2-imenu-recorder' into an imenu data structure."
7035 (unless (eq js2-imenu-recorder 'empty)
7036 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7037 (result (js2-build-alist-trie chains nil)))
7038 (js2-flatten-trie result))))
7039
7040 (defun js2-test-print-chains (chains)
7041 "Print a list of qname chains.
7042 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7043 i.e. one or more nodes, and an integer position as the list tail."
7044 (mapconcat (lambda (chain)
7045 (concat "("
7046 (mapconcat (lambda (elem)
7047 (if (js2-node-p elem)
7048 (or (js2-node-qname-component elem)
7049 "nil")
7050 (number-to-string elem)))
7051 chain
7052 " ")
7053 ")"))
7054 chains
7055 "\n"))
7056
7057 ;;; Parser
7058
7059 (defconst js2-version "1.8.0"
7060 "Version of JavaScript supported, plus minor js2 version.")
7061
7062 (defmacro js2-record-face (face)
7063 "Record a style run of FACE for the current token."
7064 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7065
7066 (defsubst js2-node-end (n)
7067 "Computes the absolute end of node N.
7068 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7069 is only true until the node is added to its parent; i.e., while parsing."
7070 (+ (js2-node-pos n)
7071 (js2-node-len n)))
7072
7073 (defsubst js2-record-comment ()
7074 "Record a comment in `js2-scanned-comments'."
7075 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7076 :format js2-ts-comment-type)
7077 js2-scanned-comments)
7078 (when js2-parse-ide-mode
7079 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7080 'font-lock-doc-face
7081 'font-lock-comment-face))
7082 (when (memq js2-ts-comment-type '(html preprocessor))
7083 ;; Tell cc-engine the bounds of the comment.
7084 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7085
7086 ;; This function is called depressingly often, so it should be fast.
7087 ;; Most of the time it's looking at the same token it peeked before.
7088 (defsubst js2-peek-token ()
7089 "Returns the next token without consuming it.
7090 If previous token was consumed, calls scanner to get new token.
7091 If previous token was -not- consumed, returns it (idempotent).
7092
7093 This function will not return a newline (js2-EOL) - instead, it
7094 gobbles newlines until it finds a non-newline token, and flags
7095 that token as appearing just after a newline.
7096
7097 This function will also not return a js2-COMMENT. Instead, it
7098 records comments found in `js2-scanned-comments'. If the token
7099 returned by this function immediately follows a jsdoc comment,
7100 the token is flagged as such.
7101
7102 Note that this function always returned the un-flagged token!
7103 The flags, if any, are saved in `js2-current-flagged-token'."
7104 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7105 js2-current-token ; most common case - return already-peeked token
7106 (let ((tt (js2-get-token)) ; call scanner
7107 saw-eol
7108 face)
7109 ;; process comments and whitespace
7110 (while (or (= tt js2-EOL)
7111 (= tt js2-COMMENT))
7112 (if (= tt js2-EOL)
7113 (setq saw-eol t)
7114 (setq saw-eol nil)
7115 (if js2-record-comments
7116 (js2-record-comment)))
7117 (setq tt (js2-get-token))) ; call scanner
7118 (setq js2-current-token tt
7119 js2-current-flagged-token (if saw-eol
7120 (logior tt js2-ti-after-eol)
7121 tt))
7122 ;; perform lexical fontification as soon as token is scanned
7123 (when js2-parse-ide-mode
7124 (cond
7125 ((minusp tt)
7126 (js2-record-face 'js2-error-face))
7127 ((setq face (aref js2-kwd-tokens tt))
7128 (js2-record-face face))
7129 ((and (= tt js2-NAME)
7130 (equal js2-ts-string "undefined"))
7131 (js2-record-face 'font-lock-constant-face))))
7132 tt))) ; return unflagged token
7133
7134 (defsubst js2-peek-flagged-token ()
7135 "Returns the current token along with any flags set for it."
7136 (js2-peek-token)
7137 js2-current-flagged-token)
7138
7139 (defsubst js2-consume-token ()
7140 (setq js2-current-flagged-token js2-EOF))
7141
7142 (defsubst js2-next-token ()
7143 (prog1
7144 (js2-peek-token)
7145 (js2-consume-token)))
7146
7147 (defsubst js2-next-flagged-token ()
7148 (js2-peek-token)
7149 (prog1 js2-current-flagged-token
7150 (js2-consume-token)))
7151
7152 (defsubst js2-match-token (match)
7153 "Consume and return t if next token matches MATCH, a bytecode.
7154 Returns nil and consumes nothing if MATCH is not the next token."
7155 (if (/= (js2-peek-token) match)
7156 nil
7157 (js2-consume-token)
7158 t))
7159
7160 (defsubst js2-valid-prop-name-token (tt)
7161 (or (= tt js2-NAME)
7162 (and js2-allow-keywords-as-property-names
7163 (plusp tt)
7164 (aref js2-kwd-tokens tt))))
7165
7166 (defsubst js2-match-prop-name ()
7167 "Consume token and return t if next token is a valid property name.
7168 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7169 is non-nil and it's a keyword token."
7170 (if (js2-valid-prop-name-token (js2-peek-token))
7171 (progn
7172 (js2-consume-token)
7173 t)
7174 nil))
7175
7176 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7177 (if (js2-match-prop-name)
7178 t
7179 (js2-report-error msg-id nil pos len)
7180 nil))
7181
7182 (defsubst js2-peek-token-or-eol ()
7183 "Return js2-EOL if the current token immediately follows a newline.
7184 Else returns the current token. Used in situations where we don't
7185 consider certain token types valid if they are preceded by a newline.
7186 One example is the postfix ++ or -- operator, which has to be on the
7187 same line as its operand."
7188 (let ((tt (js2-peek-token)))
7189 ;; Check for last peeked token flags
7190 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7191 js2-EOL
7192 tt)))
7193
7194 (defsubst js2-set-check-for-label ()
7195 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7196 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7197
7198 (defsubst js2-must-match (token msg-id &optional pos len)
7199 "Match next token to token code TOKEN, or record a syntax error.
7200 MSG-ID is the error message to report if the match fails.
7201 Returns t on match, nil if no match."
7202 (if (js2-match-token token)
7203 t
7204 (js2-report-error msg-id nil pos len)
7205 nil))
7206
7207 (defsubst js2-inside-function ()
7208 (plusp js2-nesting-of-function))
7209
7210 (defsubst js2-set-requires-activation ()
7211 (if (js2-function-node-p js2-current-script-or-fn)
7212 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7213
7214 (defsubst js2-check-activation-name (name token)
7215 (when (js2-inside-function)
7216 ;; skip language-version 1.2 check from Rhino
7217 (if (or (string= "arguments" name)
7218 (and js2-compiler-activation-names ; only used in codegen
7219 (gethash name js2-compiler-activation-names)))
7220 (js2-set-requires-activation))))
7221
7222 (defsubst js2-set-is-generator ()
7223 (if (js2-function-node-p js2-current-script-or-fn)
7224 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7225
7226 (defsubst js2-must-have-xml ()
7227 (unless js2-compiler-xml-available
7228 (js2-report-error "msg.XML.not.available")))
7229
7230 (defsubst js2-push-scope (scope)
7231 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7232 (assert (js2-scope-p scope))
7233 (assert (null (js2-scope-parent-scope scope)))
7234 (assert (not (eq js2-current-scope scope)))
7235 (setf (js2-scope-parent-scope scope) js2-current-scope
7236 js2-current-scope scope))
7237
7238 (defsubst js2-pop-scope ()
7239 (setq js2-current-scope
7240 (js2-scope-parent-scope js2-current-scope)))
7241
7242 (defsubst js2-enter-loop (loop-node)
7243 (push loop-node js2-loop-set)
7244 (push loop-node js2-loop-and-switch-set)
7245 (js2-push-scope loop-node)
7246 ;; Tell the current labeled statement (if any) its statement,
7247 ;; and set the jump target of the first label to the loop.
7248 ;; These are used in `js2-parse-continue' to verify that the
7249 ;; continue target is an actual labeled loop. (And for codegen.)
7250 (when js2-labeled-stmt
7251 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7252 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7253 js2-labeled-stmt))) loop-node)))
7254
7255 (defsubst js2-exit-loop ()
7256 (pop js2-loop-set)
7257 (pop js2-loop-and-switch-set)
7258 (js2-pop-scope))
7259
7260 (defsubst js2-enter-switch (switch-node)
7261 (push switch-node js2-loop-and-switch-set))
7262
7263 (defsubst js2-exit-switch ()
7264 (pop js2-loop-and-switch-set))
7265
7266 (defun js2-parse (&optional buf cb)
7267 "Tells the js2 parser to parse a region of JavaScript.
7268
7269 BUF is a buffer or buffer name containing the code to parse.
7270 Call `narrow-to-region' first to parse only part of the buffer.
7271
7272 The returned AST root node is given some additional properties:
7273 `node-count' - total number of nodes in the AST
7274 `buffer' - BUF. The buffer it refers to may change or be killed,
7275 so the value is not necessarily reliable.
7276
7277 An optional callback CB can be specified to report parsing
7278 progress. If `(functionp CB)' returns t, it will be called with
7279 the current line number once before parsing begins, then again
7280 each time the lexer reaches a new line number.
7281
7282 CB can also be a list of the form `(symbol cb ...)' to specify
7283 multiple callbacks with different criteria. Each symbol is a
7284 criterion keyword, and the following element is the callback to
7285 call
7286
7287 :line - called whenever the line number changes
7288 :token - called for each new token consumed
7289
7290 The list of criteria could be extended to include entering or
7291 leaving a statement, an expression, or a function definition."
7292 (if (and cb (not (functionp cb)))
7293 (error "criteria callbacks not yet implemented"))
7294 (let ((inhibit-point-motion-hooks t)
7295 (js2-compiler-xml-available (>= js2-language-version 160))
7296 ;; This is a recursive-descent parser, so give it a big stack.
7297 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7298 (max-specpdl-size (max max-specpdl-size 3000))
7299 (case-fold-search nil)
7300 ast)
7301 (or buf (setq buf (current-buffer)))
7302 (message nil) ; clear any error message from previous parse
7303 (save-excursion
7304 (set-buffer buf)
7305 (setq js2-scanned-comments nil
7306 js2-parsed-errors nil
7307 js2-parsed-warnings nil
7308 js2-imenu-recorder nil
7309 js2-imenu-function-map nil
7310 js2-label-set nil)
7311 (js2-init-scanner)
7312 (setq ast (js2-with-unmodifying-text-property-changes
7313 (js2-do-parse)))
7314 (unless js2-ts-hit-eof
7315 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7316 (setf (js2-ast-root-errors ast) js2-parsed-errors
7317 (js2-ast-root-warnings ast) js2-parsed-warnings)
7318 ;; if we didn't find any declarations, put a dummy in this list so we
7319 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7320 (unless js2-imenu-recorder
7321 (setq js2-imenu-recorder 'empty))
7322 (run-hooks 'js2-parse-finished-hook)
7323 ast)))
7324
7325 ;; Corresponds to Rhino's Parser.parse() method.
7326 (defun js2-do-parse ()
7327 "Parse current buffer starting from current point.
7328 Scanner should be initialized."
7329 (let ((pos js2-ts-cursor)
7330 (end js2-ts-cursor) ; in case file is empty
7331 root n tt)
7332 ;; initialize buffer-local parsing vars
7333 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7334 js2-current-script-or-fn root
7335 js2-current-scope root
7336 js2-current-flagged-token js2-EOF
7337 js2-nesting-of-function 0
7338 js2-labeled-stmt nil
7339 js2-recorded-identifiers nil) ; for js2-highlight
7340 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7341 (if (= tt js2-FUNCTION)
7342 (progn
7343 (js2-consume-token)
7344 (setq n (js2-parse-function (if js2-called-by-compile-function
7345 'FUNCTION_EXPRESSION
7346 'FUNCTION_STATEMENT))))
7347 ;; not a function - parse a statement
7348 (setq n (js2-parse-statement)))
7349 ;; add function or statement to script
7350 (setq end (js2-node-end n))
7351 (js2-block-node-push root n))
7352 ;; add comments to root in lexical order
7353 (when js2-scanned-comments
7354 ;; if we find a comment beyond end of normal kids, use its end
7355 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7356 (dolist (comment js2-scanned-comments)
7357 (push comment (js2-ast-root-comments root))
7358 (js2-node-add-children root comment)))
7359 (setf (js2-node-len root) (- end pos))
7360 ;; Give extensions a chance to muck with things before highlighting starts.
7361 (dolist (callback js2-post-parse-callbacks)
7362 (funcall callback))
7363 (js2-highlight-undeclared-vars)
7364 root))
7365
7366 (defun js2-function-parser ()
7367 (js2-consume-token)
7368 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7369
7370 (defun js2-parse-function-closure-body (fn-node)
7371 "Parse a JavaScript 1.8 function closure body."
7372 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7373 (if js2-ts-hit-eof
7374 (js2-report-error "msg.no.brace.body" nil
7375 (js2-node-pos fn-node)
7376 (- js2-ts-cursor (js2-node-pos fn-node)))
7377 (js2-node-add-children fn-node
7378 (setf (js2-function-node-body fn-node)
7379 (js2-parse-expr t))))))
7380
7381 (defun js2-parse-function-body (fn-node)
7382 (js2-must-match js2-LC "msg.no.brace.body"
7383 (js2-node-pos fn-node)
7384 (- js2-ts-cursor (js2-node-pos fn-node)))
7385 (let ((pos js2-token-beg) ; LC position
7386 (pn (make-js2-block-node)) ; starts at LC position
7387 tt
7388 end)
7389 (incf js2-nesting-of-function)
7390 (unwind-protect
7391 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7392 (= tt js2-EOF)
7393 (= tt js2-RC)))
7394 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7395 (js2-parse-statement)
7396 (js2-consume-token)
7397 (js2-parse-function 'FUNCTION_STATEMENT))))
7398 (decf js2-nesting-of-function))
7399 (setq end js2-token-end) ; assume no curly and leave at current token
7400 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7401 (setq end js2-token-end))
7402 (setf (js2-node-pos pn) pos
7403 (js2-node-len pn) (- end pos))
7404 (setf (js2-function-node-body fn-node) pn)
7405 (js2-node-add-children fn-node pn)
7406 pn))
7407
7408 (defun js2-define-destruct-symbols (decl-type face node)
7409 "Declare and fontify destructuring parameters inside NODE.
7410 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7411 (cond
7412 ((js2-name-node-p node)
7413 (let (leftpos)
7414 (js2-define-symbol decl-type (js2-name-node-name node) node)
7415 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7416 (+ leftpos (js2-node-len node))
7417 face 'record)))
7418 ((js2-object-node-p node)
7419 (dolist (elem (js2-object-node-elems node))
7420 (js2-define-destruct-symbols
7421 decl-type face
7422 (if (js2-object-prop-node-p elem)
7423 (js2-object-prop-node-right elem)
7424 ;; abbreviated destructuring {a, b}
7425 elem))))
7426 ((js2-array-node-p node)
7427 (dolist (elem (js2-array-node-elems node))
7428 (js2-define-destruct-symbols decl-type face elem)))
7429 (t (js2-report-error "msg.no.parm"))))
7430
7431 (defun js2-parse-function-params (fn-node pos)
7432 (if (js2-match-token js2-RP)
7433 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7434 (let (params len param)
7435 (loop for tt = (js2-peek-token)
7436 do
7437 (cond
7438 ;; destructuring param
7439 ((or (= tt js2-LB) (= tt js2-LC))
7440 (setq param (js2-parse-primary-expr-lhs))
7441 (js2-define-destruct-symbols js2-LP
7442 'js2-function-param-face
7443 param)
7444 (push param params))
7445 ;; simple name
7446 (t
7447 (js2-must-match js2-NAME "msg.no.parm")
7448 (js2-record-face 'js2-function-param-face)
7449 (setq param (js2-create-name-node))
7450 (js2-define-symbol js2-LP js2-ts-string param)
7451 (push param params)))
7452 while
7453 (js2-match-token js2-COMMA))
7454 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7455 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7456 (dolist (p params)
7457 (js2-node-add-children fn-node p)
7458 (push p (js2-function-node-params fn-node))))))
7459
7460 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7461 "Possibly show inconsistent-return warning.
7462 Last token scanned is the close-curly for the function body."
7463 (when (and js2-mode-show-strict-warnings
7464 js2-strict-inconsistent-return-warning
7465 (not (js2-has-consistent-return-usage
7466 (js2-function-node-body fn-node))))
7467 ;; Have it extend from close-curly to bol or beginning of block.
7468 (let ((pos (save-excursion
7469 (goto-char js2-token-end)
7470 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7471 (point-at-bol))))
7472 (end js2-token-end))
7473 (if (plusp (js2-name-node-length name))
7474 (js2-add-strict-warning "msg.no.return.value"
7475 (js2-name-node-name name) pos end)
7476 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7477
7478 (defun js2-parse-function (function-type)
7479 "Function parser. FUNCTION-TYPE is a symbol."
7480 (let ((pos js2-token-beg) ; start of 'function' keyword
7481 name
7482 name-beg
7483 name-end
7484 fn-node
7485 lp
7486 (synthetic-type function-type)
7487 member-expr-node)
7488 ;; parse function name, expression, or non-name (anonymous)
7489 (cond
7490 ;; function foo(...)
7491 ((js2-match-token js2-NAME)
7492 (setq name (js2-create-name-node t)
7493 name-beg js2-token-beg
7494 name-end js2-token-end)
7495 (unless (js2-match-token js2-LP)
7496 (when js2-allow-member-expr-as-function-name
7497 ;; function foo.bar(...)
7498 (setq member-expr-node name
7499 name nil
7500 member-expr-node (js2-parse-member-expr-tail
7501 nil member-expr-node)))
7502 (js2-must-match js2-LP "msg.no.paren.parms")))
7503 ((js2-match-token js2-LP)
7504 nil) ; anonymous function: leave name as null
7505 (t
7506 ;; function random-member-expr(...)
7507 (when js2-allow-member-expr-as-function-name
7508 ;; Note that memberExpr can not start with '(' like
7509 ;; in function (1+2).toString(), because 'function (' already
7510 ;; processed as anonymous function
7511 (setq member-expr-node (js2-parse-member-expr)))
7512 (js2-must-match js2-LP "msg.no.paren.parms")))
7513 (if (= js2-current-token js2-LP) ; eventually matched LP?
7514 (setq lp js2-token-beg))
7515 (if member-expr-node
7516 (progn
7517 (setq synthetic-type 'FUNCTION_EXPRESSION)
7518 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7519 (if name
7520 (js2-set-face name-beg name-end
7521 'font-lock-function-name-face 'record)))
7522 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7523 (plusp (js2-name-node-length name)))
7524 ;; Function statements define a symbol in the enclosing scope
7525 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7526 (setf fn-node (make-js2-function-node :pos pos
7527 :name name
7528 :form function-type
7529 :lp (if lp (- lp pos))))
7530 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7531 ;; 1. Nested functions are not affected by the dynamic scope flag
7532 ;; as dynamic scope is already a parent of their scope.
7533 ;; 2. Functions defined under the with statement also immune to
7534 ;; this setup, in which case dynamic scope is ignored in favor
7535 ;; of the with object.
7536 (setf (js2-function-node-ignore-dynamic fn-node) t))
7537 ;; dynamically bind all the per-function variables
7538 (let ((js2-current-script-or-fn fn-node)
7539 (js2-current-scope fn-node)
7540 (js2-nesting-of-with 0)
7541 (js2-end-flags 0)
7542 js2-label-set
7543 js2-loop-set
7544 js2-loop-and-switch-set)
7545 (js2-parse-function-params fn-node pos)
7546 (if (and (>= js2-language-version 180)
7547 (/= (js2-peek-token) js2-LC))
7548 (js2-parse-function-closure-body fn-node)
7549 (js2-parse-function-body fn-node))
7550 (if name
7551 (js2-node-add-children fn-node name))
7552 (js2-check-inconsistent-return-warning fn-node name)
7553 ;; Function expressions define a name only in the body of the
7554 ;; function, and only if not hidden by a parameter name
7555 (if (and name
7556 (eq synthetic-type 'FUNCTION_EXPRESSION)
7557 (null (js2-scope-get-symbol js2-current-scope
7558 (js2-name-node-name name))))
7559 (js2-define-symbol js2-FUNCTION
7560 (js2-name-node-name name)
7561 fn-node))
7562 (if (and name
7563 (not (eq function-type 'FUNCTION_EXPRESSION)))
7564 (js2-record-imenu-functions fn-node)))
7565 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7566 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7567 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7568 ;; We wait until after parsing the function to set its parent scope,
7569 ;; since `js2-define-symbol' needs the defining-scope check to stop
7570 ;; at the function boundary when checking for redeclarations.
7571 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7572 fn-node))
7573
7574 (defun js2-parse-statements (&optional parent)
7575 "Parse a statement list. Last token consumed must be js2-LC.
7576
7577 PARENT can be a `js2-block-node', in which case the statements are
7578 appended to PARENT. Otherwise a new `js2-block-node' is created
7579 and returned.
7580
7581 This function does not match the closing js2-RC: the caller
7582 matches the RC so it can provide a suitable error message if not
7583 matched. This means it's up to the caller to set the length of
7584 the node to include the closing RC. The node start pos is set to
7585 the absolute buffer start position, and the caller should fix it
7586 up to be relative to the parent node. All children of this block
7587 node are given relative start positions and correct lengths."
7588 (let ((pn (or parent (make-js2-block-node)))
7589 tt)
7590 (setf (js2-node-pos pn) js2-token-beg)
7591 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7592 (/= tt js2-RC))
7593 (js2-block-node-push pn (js2-parse-statement)))
7594 pn))
7595
7596 (defun js2-parse-statement ()
7597 (let (tt pn beg end)
7598 ;; coarse-grained user-interrupt check - needs work
7599 (and js2-parse-interruptable-p
7600 (zerop (% (incf js2-parse-stmt-count)
7601 js2-statements-per-pause))
7602 (input-pending-p)
7603 (throw 'interrupted t))
7604 (setq pn (js2-statement-helper))
7605 ;; no-side-effects warning check
7606 (unless (js2-node-has-side-effects pn)
7607 (setq end (js2-node-end pn))
7608 (save-excursion
7609 (goto-char end)
7610 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7611 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7612 pn))
7613
7614 ;; These correspond to the switch cases in Parser.statementHelper
7615 (defconst js2-parsers
7616 (let ((parsers (make-vector js2-num-tokens
7617 #'js2-parse-expr-stmt)))
7618 (aset parsers js2-BREAK #'js2-parse-break)
7619 (aset parsers js2-CONST #'js2-parse-const-var)
7620 (aset parsers js2-CONTINUE #'js2-parse-continue)
7621 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7622 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7623 (aset parsers js2-DO #'js2-parse-do)
7624 (aset parsers js2-FOR #'js2-parse-for)
7625 (aset parsers js2-FUNCTION #'js2-function-parser)
7626 (aset parsers js2-IF #'js2-parse-if)
7627 (aset parsers js2-LC #'js2-parse-block)
7628 (aset parsers js2-LET #'js2-parse-let-stmt)
7629 (aset parsers js2-NAME #'js2-parse-name-or-label)
7630 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7631 (aset parsers js2-SEMI #'js2-parse-semi)
7632 (aset parsers js2-SWITCH #'js2-parse-switch)
7633 (aset parsers js2-THROW #'js2-parse-throw)
7634 (aset parsers js2-TRY #'js2-parse-try)
7635 (aset parsers js2-VAR #'js2-parse-const-var)
7636 (aset parsers js2-WHILE #'js2-parse-while)
7637 (aset parsers js2-WITH #'js2-parse-with)
7638 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7639 parsers)
7640 "A vector mapping token types to parser functions.")
7641
7642 (defsubst js2-parse-warn-missing-semi (beg end)
7643 (and js2-mode-show-strict-warnings
7644 js2-strict-missing-semi-warning
7645 (js2-add-strict-warning
7646 "msg.missing.semi" nil
7647 ;; back up to beginning of statement or line
7648 (max beg (save-excursion
7649 (goto-char end)
7650 (point-at-bol)))
7651 end)))
7652
7653 (defconst js2-no-semi-insertion
7654 (list js2-IF
7655 js2-SWITCH
7656 js2-WHILE
7657 js2-DO
7658 js2-FOR
7659 js2-TRY
7660 js2-WITH
7661 js2-LC
7662 js2-ERROR
7663 js2-SEMI
7664 js2-FUNCTION)
7665 "List of tokens that don't do automatic semicolon insertion.")
7666
7667 (defconst js2-autoinsert-semi-and-warn
7668 (list js2-ERROR js2-EOF js2-RC))
7669
7670 (defun js2-statement-helper ()
7671 (let* ((tt (js2-peek-token))
7672 (first-tt tt)
7673 (beg js2-token-beg)
7674 (parser (if (= tt js2-ERROR)
7675 #'js2-parse-semi
7676 (aref js2-parsers tt)))
7677 pn
7678 tt-flagged)
7679 ;; If the statement is set, then it's been told its label by now.
7680 (and js2-labeled-stmt
7681 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7682 (setq js2-labeled-stmt nil))
7683 (setq pn (funcall parser))
7684 ;; Don't do auto semi insertion for certain statement types.
7685 (unless (or (memq first-tt js2-no-semi-insertion)
7686 (js2-labeled-stmt-node-p pn))
7687 (js2-auto-insert-semicolon pn))
7688 pn))
7689
7690 (defun js2-auto-insert-semicolon (pn)
7691 (let* ((tt-flagged (js2-peek-flagged-token))
7692 (tt (logand tt-flagged js2-clear-ti-mask))
7693 (pos (js2-node-pos pn)))
7694 (cond
7695 ((= tt js2-SEMI)
7696 ;; Consume ';' as a part of expression
7697 (js2-consume-token)
7698 ;; extend the node bounds to include the semicolon.
7699 (setf (js2-node-len pn) (- js2-token-end pos)))
7700 ((memq tt js2-autoinsert-semi-and-warn)
7701 ;; Autoinsert ;
7702 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7703 (t
7704 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7705 ;; Report error if no EOL or autoinsert ';' otherwise
7706 (js2-report-error "msg.no.semi.stmt")
7707 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7708
7709 (defun js2-parse-condition ()
7710 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7711 The parens are discarded and the expression node is returned.
7712 The `pos' field of the return value is set to an absolute position
7713 that must be fixed up by the caller.
7714 Return value is a list (EXPR LP RP), with absolute paren positions."
7715 (let (pn lp rp)
7716 (if (js2-must-match js2-LP "msg.no.paren.cond")
7717 (setq lp js2-token-beg))
7718 (setq pn (js2-parse-expr))
7719 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7720 (setq rp js2-token-beg))
7721 ;; Report strict warning on code like "if (a = 7) ..."
7722 (if (and js2-strict-cond-assign-warning
7723 (js2-assign-node-p pn))
7724 (js2-add-strict-warning "msg.equal.as.assign" nil
7725 (js2-node-pos pn)
7726 (+ (js2-node-pos pn)
7727 (js2-node-len pn))))
7728 (list pn lp rp)))
7729
7730 (defun js2-parse-if ()
7731 "Parser for if-statement. Last matched token must be js2-IF."
7732 (let ((pos js2-token-beg)
7733 cond
7734 if-true
7735 if-false
7736 else-pos
7737 end
7738 pn)
7739 (js2-consume-token)
7740 (setq cond (js2-parse-condition)
7741 if-true (js2-parse-statement)
7742 if-false (if (js2-match-token js2-ELSE)
7743 (progn
7744 (setq else-pos (- js2-token-beg pos))
7745 (js2-parse-statement)))
7746 end (js2-node-end (or if-false if-true))
7747 pn (make-js2-if-node :pos pos
7748 :len (- end pos)
7749 :condition (car cond)
7750 :then-part if-true
7751 :else-part if-false
7752 :else-pos else-pos
7753 :lp (js2-relpos (second cond) pos)
7754 :rp (js2-relpos (third cond) pos)))
7755 (js2-node-add-children pn (car cond) if-true if-false)
7756 pn))
7757
7758 (defun js2-parse-switch ()
7759 "Parser for if-statement. Last matched token must be js2-SWITCH."
7760 (let ((pos js2-token-beg)
7761 tt
7762 pn
7763 discriminant
7764 has-default
7765 case-expr
7766 case-node
7767 case-pos
7768 cases
7769 stmt
7770 lp
7771 rp)
7772 (js2-consume-token)
7773 (if (js2-must-match js2-LP "msg.no.paren.switch")
7774 (setq lp js2-token-beg))
7775 (setq discriminant (js2-parse-expr)
7776 pn (make-js2-switch-node :discriminant discriminant
7777 :pos pos
7778 :lp (js2-relpos lp pos)))
7779 (js2-node-add-children pn discriminant)
7780 (js2-enter-switch pn)
7781 (unwind-protect
7782 (progn
7783 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7784 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7785 (js2-must-match js2-LC "msg.no.brace.switch")
7786 (catch 'break
7787 (while t
7788 (setq tt (js2-next-token)
7789 case-pos js2-token-beg)
7790 (cond
7791 ((= tt js2-RC)
7792 (setf (js2-node-len pn) (- js2-token-end pos))
7793 (throw 'break nil)) ; done
7794 ((= tt js2-CASE)
7795 (setq case-expr (js2-parse-expr))
7796 (js2-must-match js2-COLON "msg.no.colon.case"))
7797 ((= tt js2-DEFAULT)
7798 (if has-default
7799 (js2-report-error "msg.double.switch.default"))
7800 (setq has-default t
7801 case-expr nil)
7802 (js2-must-match js2-COLON "msg.no.colon.case"))
7803 (t
7804 (js2-report-error "msg.bad.switch")
7805 (throw 'break nil)))
7806 (setq case-node (make-js2-case-node :pos case-pos
7807 :len (- js2-token-end case-pos)
7808 :expr case-expr))
7809 (js2-node-add-children case-node case-expr)
7810 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7811 (/= tt js2-CASE)
7812 (/= tt js2-DEFAULT)
7813 (/= tt js2-EOF))
7814 (setf stmt (js2-parse-statement)
7815 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7816 (js2-block-node-push case-node stmt))
7817 (push case-node cases)))
7818 ;; add cases last, as pushing reverses the order to be correct
7819 (dolist (kid cases)
7820 (js2-node-add-children pn kid)
7821 (push kid (js2-switch-node-cases pn)))
7822 pn) ; return value
7823 (js2-exit-switch))))
7824
7825 (defun js2-parse-while ()
7826 "Parser for while-statement. Last matched token must be js2-WHILE."
7827 (let ((pos js2-token-beg)
7828 (pn (make-js2-while-node))
7829 cond
7830 body)
7831 (js2-consume-token)
7832 (js2-enter-loop pn)
7833 (unwind-protect
7834 (progn
7835 (setf cond (js2-parse-condition)
7836 (js2-while-node-condition pn) (car cond)
7837 body (js2-parse-statement)
7838 (js2-while-node-body pn) body
7839 (js2-node-len pn) (- (js2-node-end body) pos)
7840 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7841 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7842 (js2-node-add-children pn body (car cond)))
7843 (js2-exit-loop))
7844 pn))
7845
7846 (defun js2-parse-do ()
7847 "Parser for do-statement. Last matched token must be js2-DO."
7848 (let ((pos js2-token-beg)
7849 (pn (make-js2-do-node))
7850 cond
7851 body
7852 end)
7853 (js2-consume-token)
7854 (js2-enter-loop pn)
7855 (unwind-protect
7856 (progn
7857 (setq body (js2-parse-statement))
7858 (js2-must-match js2-WHILE "msg.no.while.do")
7859 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7860 cond (js2-parse-condition)
7861 (js2-do-node-condition pn) (car cond)
7862 (js2-do-node-body pn) body
7863 end js2-ts-cursor
7864 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7865 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7866 (js2-node-add-children pn (car cond) body))
7867 (js2-exit-loop))
7868 ;; Always auto-insert semicolon to follow SpiderMonkey:
7869 ;; It is required by ECMAScript but is ignored by the rest of
7870 ;; world; see bug 238945
7871 (if (js2-match-token js2-SEMI)
7872 (setq end js2-ts-cursor))
7873 (setf (js2-node-len pn) (- end pos))
7874 pn))
7875
7876 (defun js2-parse-for ()
7877 "Parser for for-statement. Last matched token must be js2-FOR.
7878 Parses for, for-in, and for each-in statements."
7879 (let ((for-pos js2-token-beg)
7880 pn
7881 is-for-each
7882 is-for-in
7883 in-pos
7884 each-pos
7885 tmp-pos
7886 init ; Node init is also foo in 'foo in object'
7887 cond ; Node cond is also object in 'foo in object'
7888 incr ; 3rd section of for-loop initializer
7889 body
7890 tt
7891 lp
7892 rp)
7893 (js2-consume-token)
7894 ;; See if this is a for each () instead of just a for ()
7895 (when (js2-match-token js2-NAME)
7896 (if (string= "each" js2-ts-string)
7897 (progn
7898 (setq is-for-each t
7899 each-pos (- js2-token-beg for-pos)) ; relative
7900 (js2-record-face 'font-lock-keyword-face))
7901 (js2-report-error "msg.no.paren.for")))
7902 (if (js2-must-match js2-LP "msg.no.paren.for")
7903 (setq lp (- js2-token-beg for-pos)))
7904 (setq tt (js2-peek-token))
7905 ;; parse init clause
7906 (let ((js2-in-for-init t)) ; set as dynamic variable
7907 (cond
7908 ((= tt js2-SEMI)
7909 (setq init (make-js2-empty-expr-node)))
7910 ((or (= tt js2-VAR) (= tt js2-LET))
7911 (js2-consume-token)
7912 (setq init (js2-parse-variables tt js2-token-beg)))
7913 (t
7914 (setq init (js2-parse-expr)))))
7915 (if (js2-match-token js2-IN)
7916 (setq is-for-in t
7917 in-pos (- js2-token-beg for-pos)
7918 cond (js2-parse-expr)) ; object over which we're iterating
7919 ;; else ordinary for loop - parse cond and incr
7920 (js2-must-match js2-SEMI "msg.no.semi.for")
7921 (setq cond (if (= (js2-peek-token) js2-SEMI)
7922 (make-js2-empty-expr-node) ; no loop condition
7923 (js2-parse-expr)))
7924 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7925 (setq tmp-pos js2-token-end
7926 incr (if (= (js2-peek-token) js2-RP)
7927 (make-js2-empty-expr-node :pos tmp-pos)
7928 (js2-parse-expr))))
7929 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7930 (setq rp (- js2-token-beg for-pos)))
7931 (if (not is-for-in)
7932 (setq pn (make-js2-for-node :init init
7933 :condition cond
7934 :update incr
7935 :lp lp
7936 :rp rp))
7937 ;; cond could be null if 'in obj' got eaten by the init node.
7938 (if (js2-infix-node-p init)
7939 ;; it was (foo in bar) instead of (var foo in bar)
7940 (setq cond (js2-infix-node-right init)
7941 init (js2-infix-node-left init))
7942 (if (and (js2-var-decl-node-p init)
7943 (> (length (js2-var-decl-node-kids init)) 1))
7944 (js2-report-error "msg.mult.index")))
7945 (setq pn (make-js2-for-in-node :iterator init
7946 :object cond
7947 :in-pos in-pos
7948 :foreach-p is-for-each
7949 :each-pos each-pos
7950 :lp lp
7951 :rp rp)))
7952 (unwind-protect
7953 (progn
7954 (js2-enter-loop pn)
7955 ;; We have to parse the body -after- creating the loop node,
7956 ;; so that the loop node appears in the js2-loop-set, allowing
7957 ;; break/continue statements to find the enclosing loop.
7958 (setf body (js2-parse-statement)
7959 (js2-loop-node-body pn) body
7960 (js2-node-pos pn) for-pos
7961 (js2-node-len pn) (- (js2-node-end body) for-pos))
7962 (js2-node-add-children pn init cond incr body))
7963 ;; finally
7964 (js2-exit-loop))
7965 pn))
7966
7967 (defun js2-parse-try ()
7968 "Parser for try-statement. Last matched token must be js2-TRY."
7969 (let ((try-pos js2-token-beg)
7970 try-end
7971 try-block
7972 catch-blocks
7973 finally-block
7974 saw-default-catch
7975 peek
7976 var-name
7977 catch-cond
7978 catch-node
7979 guard-kwd
7980 catch-pos
7981 finally-pos
7982 pn
7983 block
7984 lp
7985 rp)
7986 (js2-consume-token)
7987 (if (/= (js2-peek-token) js2-LC)
7988 (js2-report-error "msg.no.brace.try"))
7989 (setq try-block (js2-parse-statement)
7990 try-end (js2-node-end try-block)
7991 peek (js2-peek-token))
7992 (cond
7993 ((= peek js2-CATCH)
7994 (while (js2-match-token js2-CATCH)
7995 (setq catch-pos js2-token-beg
7996 guard-kwd nil
7997 catch-cond nil
7998 lp nil
7999 rp nil)
8000 (if saw-default-catch
8001 (js2-report-error "msg.catch.unreachable"))
8002 (if (js2-must-match js2-LP "msg.no.paren.catch")
8003 (setq lp (- js2-token-beg catch-pos)))
8004 (js2-must-match js2-NAME "msg.bad.catchcond")
8005 (setq var-name (js2-create-name-node))
8006 (if (js2-match-token js2-IF)
8007 (setq guard-kwd (- js2-token-beg catch-pos)
8008 catch-cond (js2-parse-expr))
8009 (setq saw-default-catch t))
8010 (if (js2-must-match js2-RP "msg.bad.catchcond")
8011 (setq rp (- js2-token-beg catch-pos)))
8012 (js2-must-match js2-LC "msg.no.brace.catchblock")
8013 (setq block (js2-parse-statements)
8014 try-end (js2-node-end block)
8015 catch-node (make-js2-catch-node :pos catch-pos
8016 :var-name var-name
8017 :guard-expr catch-cond
8018 :guard-kwd guard-kwd
8019 :block block
8020 :lp lp
8021 :rp rp))
8022 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8023 (setq try-end js2-token-beg))
8024 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8025 (js2-node-len catch-node) (- try-end catch-pos))
8026 (js2-node-add-children catch-node var-name catch-cond block)
8027 (push catch-node catch-blocks)))
8028 ((/= peek js2-FINALLY)
8029 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8030 (js2-node-pos try-block)
8031 (- (setq try-end (js2-node-end try-block))
8032 (js2-node-pos try-block)))))
8033 (when (js2-match-token js2-FINALLY)
8034 (setq finally-pos js2-token-beg
8035 block (js2-parse-statement)
8036 try-end (js2-node-end block)
8037 finally-block (make-js2-finally-node :pos finally-pos
8038 :len (- try-end finally-pos)
8039 :body block))
8040 (js2-node-add-children finally-block block))
8041 (setq pn (make-js2-try-node :pos try-pos
8042 :len (- try-end try-pos)
8043 :try-block try-block
8044 :finally-block finally-block))
8045 (js2-node-add-children pn try-block finally-block)
8046 ;; push them onto the try-node, which reverses and corrects their order
8047 (dolist (cb catch-blocks)
8048 (js2-node-add-children pn cb)
8049 (push cb (js2-try-node-catch-clauses pn)))
8050 pn))
8051
8052 (defun js2-parse-throw ()
8053 "Parser for throw-statement. Last matched token must be js2-THROW."
8054 (let ((pos js2-token-beg)
8055 expr
8056 pn)
8057 (js2-consume-token)
8058 (if (= (js2-peek-token-or-eol) js2-EOL)
8059 ;; ECMAScript does not allow new lines before throw expression,
8060 ;; see bug 256617
8061 (js2-report-error "msg.bad.throw.eol"))
8062 (setq expr (js2-parse-expr)
8063 pn (make-js2-throw-node :pos pos
8064 :len (- (js2-node-end expr) pos)
8065 :expr expr))
8066 (js2-node-add-children pn expr)
8067 pn))
8068
8069 (defsubst js2-match-jump-label-name (label-name)
8070 "If break/continue specified a label, return that label's labeled stmt.
8071 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8072 does not match an existing label, reports an error and returns nil."
8073 (let ((bundle (cdr (assoc label-name js2-label-set))))
8074 (if (null bundle)
8075 (js2-report-error "msg.undef.label"))
8076 bundle))
8077
8078 (defun js2-parse-break ()
8079 "Parser for break-statement. Last matched token must be js2-BREAK."
8080 (let ((pos js2-token-beg)
8081 (end js2-token-end)
8082 break-target ; statement to break from
8083 break-label ; in "break foo", name-node representing the foo
8084 labels ; matching labeled statement to break to
8085 pn)
8086 (js2-consume-token) ; `break'
8087 (when (eq (js2-peek-token-or-eol) js2-NAME)
8088 (js2-consume-token)
8089 (setq break-label (js2-create-name-node)
8090 end (js2-node-end break-label)
8091 ;; matchJumpLabelName only matches if there is one
8092 labels (js2-match-jump-label-name js2-ts-string)
8093 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8094 (unless (or break-target break-label)
8095 ;; no break target specified - try for innermost enclosing loop/switch
8096 (if (null js2-loop-and-switch-set)
8097 (unless break-label
8098 (js2-report-error "msg.bad.break" nil pos (length "break")))
8099 (setq break-target (car js2-loop-and-switch-set))))
8100 (setq pn (make-js2-break-node :pos pos
8101 :len (- end pos)
8102 :label break-label
8103 :target break-target))
8104 (js2-node-add-children pn break-label) ; but not break-target
8105 pn))
8106
8107 (defun js2-parse-continue ()
8108 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8109 (let ((pos js2-token-beg)
8110 (end js2-token-end)
8111 label ; optional user-specified label, a `js2-name-node'
8112 labels ; current matching labeled stmt, if any
8113 target ; the `js2-loop-node' target of this continue stmt
8114 pn)
8115 (js2-consume-token) ; `continue'
8116 (when (= (js2-peek-token-or-eol) js2-NAME)
8117 (js2-consume-token)
8118 (setq label (js2-create-name-node)
8119 end (js2-node-end label)
8120 ;; matchJumpLabelName only matches if there is one
8121 labels (js2-match-jump-label-name js2-ts-string)))
8122 (cond
8123 ((null labels) ; no current label to go to
8124 (if (null js2-loop-set) ; no loop to continue to
8125 (js2-report-error "msg.continue.outside" nil pos
8126 (length "continue"))
8127 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8128 (t
8129 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8130 (setq target (js2-labeled-stmt-node-stmt labels))
8131 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8132 (setq pn (make-js2-continue-node :pos pos
8133 :len (- end pos)
8134 :label label
8135 :target target))
8136 (js2-node-add-children pn label) ; but not target - it's not our child
8137 pn))
8138
8139 (defun js2-parse-with ()
8140 "Parser for with-statement. Last matched token must be js2-WITH."
8141 (js2-consume-token)
8142 (let ((pos js2-token-beg)
8143 obj body pn lp rp)
8144 (if (js2-must-match js2-LP "msg.no.paren.with")
8145 (setq lp js2-token-beg))
8146 (setq obj (js2-parse-expr))
8147 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8148 (setq rp js2-token-beg))
8149 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8150 (setq body (js2-parse-statement)))
8151 (setq pn (make-js2-with-node :pos pos
8152 :len (- (js2-node-end body) pos)
8153 :object obj
8154 :body body
8155 :lp (js2-relpos lp pos)
8156 :rp (js2-relpos rp pos)))
8157 (js2-node-add-children pn obj body)
8158 pn))
8159
8160 (defun js2-parse-const-var ()
8161 "Parser for var- or const-statement.
8162 Last matched token must be js2-CONST or js2-VAR."
8163 (let ((tt (js2-peek-token))
8164 (pos js2-token-beg)
8165 expr
8166 pn)
8167 (js2-consume-token)
8168 (setq expr (js2-parse-variables tt js2-token-beg)
8169 pn (make-js2-expr-stmt-node :pos pos
8170 :len (- (js2-node-end expr) pos)
8171 :expr expr))
8172 (js2-node-add-children pn expr)
8173 pn))
8174
8175 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8176 (let ((pn (make-js2-expr-stmt-node :pos pos
8177 :len (js2-node-len expr)
8178 :type (if (js2-inside-function)
8179 js2-EXPR_VOID
8180 js2-EXPR_RESULT)
8181 :expr expr)))
8182 (if add-child
8183 (js2-node-add-children pn expr))
8184 pn))
8185
8186 (defun js2-parse-let-stmt ()
8187 "Parser for let-statement. Last matched token must be js2-LET."
8188 (js2-consume-token)
8189 (let ((pos js2-token-beg)
8190 expr
8191 pn)
8192 (if (= (js2-peek-token) js2-LP)
8193 ;; let expression in statement context
8194 (setq expr (js2-parse-let pos 'statement)
8195 pn (js2-wrap-with-expr-stmt pos expr t))
8196 ;; else we're looking at a statement like let x=6, y=7;
8197 (setf expr (js2-parse-variables js2-LET pos)
8198 pn (js2-wrap-with-expr-stmt pos expr t)
8199 (js2-node-type pn) js2-EXPR_RESULT))
8200 pn))
8201
8202 (defun js2-parse-ret-yield ()
8203 (js2-parse-return-or-yield (js2-peek-token) nil))
8204
8205 (defconst js2-parse-return-stmt-enders
8206 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8207
8208 (defsubst js2-now-all-set (before after mask)
8209 "Return whether or not the bits in the mask have changed to all set.
8210 BEFORE is bits before change, AFTER is bits after change, and MASK is
8211 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8212 but not BEFORE."
8213 (and (/= (logand before mask) mask)
8214 (= (logand after mask) mask)))
8215
8216 (defun js2-parse-return-or-yield (tt expr-context)
8217 (let ((pos js2-token-beg)
8218 (end js2-token-end)
8219 (before js2-end-flags)
8220 (inside-function (js2-inside-function))
8221 e
8222 ret
8223 name)
8224 (unless inside-function
8225 (js2-report-error (if (eq tt js2-RETURN)
8226 "msg.bad.return"
8227 "msg.bad.yield")))
8228 (js2-consume-token)
8229 ;; This is ugly, but we don't want to require a semicolon.
8230 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8231 (setq e (js2-parse-expr)
8232 end (js2-node-end e)))
8233 (cond
8234 ((eq tt js2-RETURN)
8235 (js2-set-flag js2-end-flags (if (null e)
8236 js2-end-returns
8237 js2-end-returns-value))
8238 (setq ret (make-js2-return-node :pos pos
8239 :len (- end pos)
8240 :retval e))
8241 (js2-node-add-children ret e)
8242 ;; See if we need a strict mode warning.
8243 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8244 ;; more thorough and accurate than this before/after flag check.
8245 ;; E.g. if there's a finally-block that always returns, we shouldn't
8246 ;; show a warning generated by inconsistent returns in the catch blocks.
8247 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8248 ;; so we know which returns/yields to highlight, and we should get rid of
8249 ;; all the checking in `js2-parse-return-or-yield'.
8250 (if (and js2-strict-inconsistent-return-warning
8251 (js2-now-all-set before js2-end-flags
8252 (logior js2-end-returns js2-end-returns-value)))
8253 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8254 (t
8255 (unless (js2-inside-function)
8256 (js2-report-error "msg.bad.yield"))
8257 (js2-set-flag js2-end-flags js2-end-yields)
8258 (setq ret (make-js2-yield-node :pos pos
8259 :len (- end pos)
8260 :value e))
8261 (js2-node-add-children ret e)
8262 (unless expr-context
8263 (setq e ret
8264 ret (js2-wrap-with-expr-stmt pos e t))
8265 (js2-set-requires-activation)
8266 (js2-set-is-generator))))
8267 ;; see if we are mixing yields and value returns.
8268 (when (and inside-function
8269 (js2-now-all-set before js2-end-flags
8270 (logior js2-end-yields js2-end-returns-value)))
8271 (setq name (js2-function-name js2-current-script-or-fn))
8272 (if (zerop (length name))
8273 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8274 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8275 ret))
8276
8277 (defun js2-parse-debugger ()
8278 (js2-consume-token)
8279 (make-js2-keyword-node :type js2-DEBUGGER))
8280
8281 (defun js2-parse-block ()
8282 "Parser for a curly-delimited statement block.
8283 Last token matched must be js2-LC."
8284 (let ((pos js2-token-beg)
8285 (pn (make-js2-scope)))
8286 (js2-consume-token)
8287 (js2-push-scope pn)
8288 (unwind-protect
8289 (progn
8290 (js2-parse-statements pn)
8291 (js2-must-match js2-RC "msg.no.brace.block")
8292 (setf (js2-node-len pn) (- js2-token-end pos)))
8293 (js2-pop-scope))
8294 pn))
8295
8296 ;; for js2-ERROR too, to have a node for error recovery to work on
8297 (defun js2-parse-semi ()
8298 "Parse a statement or handle an error.
8299 Last matched token is js-SEMI or js-ERROR."
8300 (let ((tt (js2-peek-token)) pos len)
8301 (js2-consume-token)
8302 (if (eq tt js2-SEMI)
8303 (make-js2-empty-expr-node :len 1)
8304 (setq pos js2-token-beg
8305 len (- js2-token-beg pos))
8306 (js2-report-error "msg.syntax" nil pos len)
8307 (make-js2-error-node :pos pos :len len))))
8308
8309 (defun js2-parse-default-xml-namespace ()
8310 "Parse a `default xml namespace = <expr>' e4x statement."
8311 (let ((pos js2-token-beg)
8312 end len expr unary es)
8313 (js2-consume-token)
8314 (js2-must-have-xml)
8315 (js2-set-requires-activation)
8316 (setq len (- js2-ts-cursor pos))
8317 (unless (and (js2-match-token js2-NAME)
8318 (string= js2-ts-string "xml"))
8319 (js2-report-error "msg.bad.namespace" nil pos len))
8320 (unless (and (js2-match-token js2-NAME)
8321 (string= js2-ts-string "namespace"))
8322 (js2-report-error "msg.bad.namespace" nil pos len))
8323 (unless (js2-match-token js2-ASSIGN)
8324 (js2-report-error "msg.bad.namespace" nil pos len))
8325 (setq expr (js2-parse-expr)
8326 end (js2-node-end expr)
8327 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8328 :pos pos
8329 :len (- end pos)
8330 :operand expr))
8331 (js2-node-add-children unary expr)
8332 (make-js2-expr-stmt-node :pos pos
8333 :len (- end pos)
8334 :expr unary)))
8335
8336 (defun js2-record-label (label bundle)
8337 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8338 (js2-consume-token)
8339 (let ((name (js2-label-node-name label))
8340 labeled-stmt
8341 dup)
8342 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8343 ;; flag both labels if possible when used in editing mode
8344 (if (and js2-parse-ide-mode
8345 (setq dup (js2-get-label-by-name labeled-stmt name)))
8346 (js2-report-error "msg.dup.label" nil
8347 (js2-node-abs-pos dup) (js2-node-len dup)))
8348 (js2-report-error "msg.dup.label" nil
8349 (js2-node-pos label) (js2-node-len label)))
8350 (js2-labeled-stmt-node-add-label bundle label)
8351 (js2-node-add-children bundle label)
8352 ;; Add one reference to the bundle per label in `js2-label-set'
8353 (push (cons name bundle) js2-label-set)))
8354
8355 (defun js2-parse-name-or-label ()
8356 "Parser for identifier or label. Last token matched must be js2-NAME.
8357 Called when we found a name in a statement context. If it's a label, we gather
8358 up any following labels and the next non-label statement into a
8359 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8360 expression and return it wrapped in a `js2-expr-stmt-node'."
8361 (let ((pos js2-token-beg)
8362 (end js2-token-end)
8363 expr
8364 stmt
8365 pn
8366 bundle
8367 (continue t))
8368 ;; set check for label and call down to `js2-parse-primary-expr'
8369 (js2-set-check-for-label)
8370 (setq expr (js2-parse-expr))
8371 (if (/= (js2-node-type expr) js2-LABEL)
8372 ;; Parsed non-label expression - wrap with expression stmt.
8373 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8374 ;; else parsed a label
8375 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8376 (js2-record-label expr bundle)
8377 ;; look for more labels
8378 (while (and continue (= (js2-peek-token) js2-NAME))
8379 (js2-set-check-for-label)
8380 (setq expr (js2-parse-expr))
8381 (if (/= (js2-node-type expr) js2-LABEL)
8382 (progn
8383 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8384 continue nil)
8385 (js2-auto-insert-semicolon stmt))
8386 (js2-record-label expr bundle)))
8387 ;; no more labels; now parse the labeled statement
8388 (unwind-protect
8389 (unless stmt
8390 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8391 (setq stmt (js2-statement-helper))))
8392 ;; remove the labels for this statement from the global set
8393 (dolist (label (js2-labeled-stmt-node-labels bundle))
8394 (setq js2-label-set (remove label js2-label-set))))
8395 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8396 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8397 (js2-node-add-children bundle stmt)
8398 bundle)))
8399
8400 (defun js2-parse-expr-stmt ()
8401 "Default parser in statement context, if no recognized statement found."
8402 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8403
8404 (defun js2-parse-variables (decl-type pos)
8405 "Parse a comma-separated list of variable declarations.
8406 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8407
8408 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8409 For 'var' or 'const', the keyword should be the token last scanned.
8410
8411 POS is the position where the node should start. It's sometimes the
8412 var/const/let keyword, and other times the beginning of the first token
8413 in the first variable declaration.
8414
8415 Returns the parsed `js2-var-decl-node' expression node."
8416 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8417 :pos pos))
8418 destructuring
8419 kid-pos
8420 tt
8421 init
8422 name
8423 end
8424 nbeg nend
8425 vi
8426 (continue t))
8427 ;; Example:
8428 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8429 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8430 ;; var {a, b} = baz;
8431 (while continue
8432 (setq destructuring nil
8433 name nil
8434 tt (js2-peek-token)
8435 kid-pos js2-token-beg
8436 end js2-token-end
8437 init nil)
8438 (if (or (= tt js2-LB) (= tt js2-LC))
8439 ;; Destructuring assignment, e.g., var [a, b] = ...
8440 (setq destructuring (js2-parse-primary-expr-lhs)
8441 end (js2-node-end destructuring))
8442 ;; Simple variable name
8443 (when (js2-must-match js2-NAME "msg.bad.var")
8444 (setq name (js2-create-name-node)
8445 nbeg js2-token-beg
8446 nend js2-token-end
8447 end nend)
8448 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8449 (when (js2-match-token js2-ASSIGN)
8450 (setq init (js2-parse-assign-expr)
8451 end (js2-node-end init))
8452 (if (and js2-parse-ide-mode
8453 (or (js2-object-node-p init)
8454 (js2-function-node-p init)))
8455 (js2-record-imenu-functions init name)))
8456 (when name
8457 (js2-set-face nbeg nend (if (js2-function-node-p init)
8458 'font-lock-function-name-face
8459 'font-lock-variable-name-face)
8460 'record))
8461 (setq vi (make-js2-var-init-node :pos kid-pos
8462 :len (- end kid-pos)
8463 :type decl-type))
8464 (if destructuring
8465 (progn
8466 (if (and (null init) (not js2-in-for-init))
8467 (js2-report-error "msg.destruct.assign.no.init"))
8468 (js2-define-destruct-symbols decl-type
8469 'font-lock-variable-name-face
8470 destructuring)
8471 (setf (js2-var-init-node-target vi) destructuring))
8472 (setf (js2-var-init-node-target vi) name))
8473 (setf (js2-var-init-node-initializer vi) init)
8474 (js2-node-add-children vi name destructuring init)
8475 (js2-block-node-push result vi)
8476 (unless (js2-match-token js2-COMMA)
8477 (setq continue nil)))
8478 (setf (js2-node-len result) (- end pos))
8479 result))
8480
8481 (defun js2-parse-let (pos &optional stmt-p)
8482 "Parse a let expression or statement.
8483 A let-expression is of the form `let (vars) expr'.
8484 A let-statment is of the form `let (vars) {statements}'.
8485 The third form of let is a variable declaration list, handled
8486 by `js2-parse-variables'."
8487 (let ((pn (make-js2-let-node :pos pos))
8488 beg vars body)
8489 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8490 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8491 (js2-push-scope pn)
8492 (unwind-protect
8493 (progn
8494 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8495 (if (js2-must-match js2-RP "msg.no.paren.let")
8496 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8497 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8498 ;; let statement
8499 (progn
8500 (js2-consume-token)
8501 (setf beg js2-token-beg ; position stmt at LC
8502 body (js2-parse-statements))
8503 (js2-must-match js2-RC "msg.no.curly.let")
8504 (setf (js2-node-len body) (- js2-token-end beg)
8505 (js2-node-len pn) (- js2-token-end pos)
8506 (js2-let-node-body pn) body
8507 (js2-node-type pn) js2-LET))
8508 ;; let expression
8509 (setf body (js2-parse-expr)
8510 (js2-node-len pn) (- (js2-node-end body) pos)
8511 (js2-let-node-body pn) body))
8512 (js2-node-add-children pn vars body))
8513 (js2-pop-scope))
8514 pn))
8515
8516 (defsubst js2-define-new-symbol (decl-type name node)
8517 (js2-scope-put-symbol js2-current-scope
8518 name
8519 (make-js2-symbol decl-type name node)))
8520
8521 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8522 "Define a symbol in the current scope.
8523 If NODE is non-nil, it is the AST node associated with the symbol."
8524 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8525 (symbol (if defining-scope
8526 (js2-scope-get-symbol defining-scope name)))
8527 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8528 (cond
8529 ((and symbol ; already defined
8530 (or (= sdt js2-CONST) ; old version is const
8531 (= decl-type js2-CONST) ; new version is const
8532 ;; two let-bound vars in this block have same name
8533 (and (= sdt js2-LET)
8534 (eq defining-scope js2-current-scope))))
8535 (js2-report-error
8536 (cond
8537 ((= sdt js2-CONST) "msg.const.redecl")
8538 ((= sdt js2-LET) "msg.let.redecl")
8539 ((= sdt js2-VAR) "msg.var.redecl")
8540 ((= sdt js2-FUNCTION) "msg.function.redecl")
8541 (t "msg.parm.redecl"))
8542 name))
8543 ((= decl-type js2-LET)
8544 (if (and (not ignore-not-in-block)
8545 (or (= (js2-node-type js2-current-scope) js2-IF)
8546 (js2-loop-node-p js2-current-scope)))
8547 (js2-report-error "msg.let.decl.not.in.block")
8548 (js2-define-new-symbol decl-type name node)))
8549 ((or (= decl-type js2-VAR)
8550 (= decl-type js2-CONST)
8551 (= decl-type js2-FUNCTION))
8552 (if symbol
8553 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8554 (js2-add-strict-warning "msg.var.redecl" name)
8555 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8556 (js2-add-strict-warning "msg.var.hides.arg" name)))
8557 (js2-define-new-symbol decl-type name node)))
8558 ((= decl-type js2-LP)
8559 (if symbol
8560 ;; must be duplicate parameter. Second parameter hides the
8561 ;; first, so go ahead and add the second pararameter
8562 (js2-report-warning "msg.dup.parms" name))
8563 (js2-define-new-symbol decl-type name node))
8564 (t (js2-code-bug)))))
8565
8566 (defun js2-parse-expr (&optional oneshot)
8567 (let* ((pn (js2-parse-assign-expr))
8568 (pos (js2-node-pos pn))
8569 left
8570 right
8571 op-pos)
8572 (while (and (not oneshot)
8573 (js2-match-token js2-COMMA))
8574 (setq op-pos (- js2-token-beg pos)) ; relative
8575 (if (= (js2-peek-token) js2-YIELD)
8576 (js2-report-error "msg.yield.parenthesized"))
8577 (setq right (js2-parse-assign-expr)
8578 left pn
8579 pn (make-js2-infix-node :type js2-COMMA
8580 :pos pos
8581 :len (- js2-ts-cursor pos)
8582 :op-pos op-pos
8583 :left left
8584 :right right))
8585 (js2-node-add-children pn left right))
8586 pn))
8587
8588 (defun js2-parse-assign-expr ()
8589 (let ((tt (js2-peek-token))
8590 (pos js2-token-beg)
8591 pn
8592 left
8593 right
8594 op-pos)
8595 (if (= tt js2-YIELD)
8596 (js2-parse-return-or-yield tt t)
8597 ;; not yield - parse assignment expression
8598 (setq pn (js2-parse-cond-expr)
8599 tt (js2-peek-token))
8600 (when (and (<= js2-first-assign tt)
8601 (<= tt js2-last-assign))
8602 ;; tt express assignment (=, |=, ^=, ..., %=)
8603 (js2-consume-token)
8604 (setq op-pos (- js2-token-beg pos) ; relative
8605 left pn
8606 right (js2-parse-assign-expr)
8607 pn (make-js2-assign-node :type tt
8608 :pos pos
8609 :len (- (js2-node-end right) pos)
8610 :op-pos op-pos
8611 :left left
8612 :right right))
8613 (when js2-parse-ide-mode
8614 (js2-highlight-assign-targets pn left right)
8615 (if (or (js2-function-node-p right)
8616 (js2-object-node-p right))
8617 (js2-record-imenu-functions right left)))
8618 ;; do this last so ide checks above can use absolute positions
8619 (js2-node-add-children pn left right))
8620 pn)))
8621
8622 (defun js2-parse-cond-expr ()
8623 (let ((pos js2-token-beg)
8624 (pn (js2-parse-or-expr))
8625 test-expr
8626 if-true
8627 if-false
8628 q-pos
8629 c-pos)
8630 (when (js2-match-token js2-HOOK)
8631 (setq q-pos (- js2-token-beg pos)
8632 if-true (js2-parse-assign-expr))
8633 (js2-must-match js2-COLON "msg.no.colon.cond")
8634 (setq c-pos (- js2-token-beg pos)
8635 if-false (js2-parse-assign-expr)
8636 test-expr pn
8637 pn (make-js2-cond-node :pos pos
8638 :len (- (js2-node-end if-false) pos)
8639 :test-expr test-expr
8640 :true-expr if-true
8641 :false-expr if-false
8642 :q-pos q-pos
8643 :c-pos c-pos))
8644 (js2-node-add-children pn test-expr if-true if-false))
8645 pn))
8646
8647 (defun js2-make-binary (type left parser)
8648 "Helper for constructing a binary-operator AST node.
8649 LEFT is the left-side-expression, already parsed, and the
8650 binary operator should have just been matched.
8651 PARSER is a function to call to parse the right operand,
8652 or a `js2-node' struct if it has already been parsed."
8653 (let* ((pos (js2-node-pos left))
8654 (op-pos (- js2-token-beg pos))
8655 (right (if (js2-node-p parser)
8656 parser
8657 (funcall parser)))
8658 (pn (make-js2-infix-node :type type
8659 :pos pos
8660 :len (- (js2-node-end right) pos)
8661 :op-pos op-pos
8662 :left left
8663 :right right)))
8664 (js2-node-add-children pn left right)
8665 pn))
8666
8667 (defun js2-parse-or-expr ()
8668 (let ((pn (js2-parse-and-expr)))
8669 (when (js2-match-token js2-OR)
8670 (setq pn (js2-make-binary js2-OR
8671 pn
8672 'js2-parse-or-expr)))
8673 pn))
8674
8675 (defun js2-parse-and-expr ()
8676 (let ((pn (js2-parse-bit-or-expr)))
8677 (when (js2-match-token js2-AND)
8678 (setq pn (js2-make-binary js2-AND
8679 pn
8680 'js2-parse-and-expr)))
8681 pn))
8682
8683 (defun js2-parse-bit-or-expr ()
8684 (let ((pn (js2-parse-bit-xor-expr)))
8685 (while (js2-match-token js2-BITOR)
8686 (setq pn (js2-make-binary js2-BITOR
8687 pn
8688 'js2-parse-bit-xor-expr)))
8689 pn))
8690
8691 (defun js2-parse-bit-xor-expr ()
8692 (let ((pn (js2-parse-bit-and-expr)))
8693 (while (js2-match-token js2-BITXOR)
8694 (setq pn (js2-make-binary js2-BITXOR
8695 pn
8696 'js2-parse-bit-and-expr)))
8697 pn))
8698
8699 (defun js2-parse-bit-and-expr ()
8700 (let ((pn (js2-parse-eq-expr)))
8701 (while (js2-match-token js2-BITAND)
8702 (setq pn (js2-make-binary js2-BITAND
8703 pn
8704 'js2-parse-eq-expr)))
8705 pn))
8706
8707 (defconst js2-parse-eq-ops
8708 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8709
8710 (defun js2-parse-eq-expr ()
8711 (let ((pn (js2-parse-rel-expr))
8712 tt)
8713 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8714 (js2-consume-token)
8715 (setq pn (js2-make-binary tt
8716 pn
8717 'js2-parse-rel-expr)))
8718 pn))
8719
8720 (defconst js2-parse-rel-ops
8721 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8722
8723 (defun js2-parse-rel-expr ()
8724 (let ((pn (js2-parse-shift-expr))
8725 (continue t)
8726 tt)
8727 (while continue
8728 (setq tt (js2-peek-token))
8729 (cond
8730 ((and js2-in-for-init (= tt js2-IN))
8731 (setq continue nil))
8732 ((memq tt js2-parse-rel-ops)
8733 (js2-consume-token)
8734 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8735 (t
8736 (setq continue nil))))
8737 pn))
8738
8739 (defconst js2-parse-shift-ops
8740 (list js2-LSH js2-URSH js2-RSH))
8741
8742 (defun js2-parse-shift-expr ()
8743 (let ((pn (js2-parse-add-expr))
8744 tt
8745 (continue t))
8746 (while continue
8747 (setq tt (js2-peek-token))
8748 (if (memq tt js2-parse-shift-ops)
8749 (progn
8750 (js2-consume-token)
8751 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8752 (setq continue nil)))
8753 pn))
8754
8755 (defun js2-parse-add-expr ()
8756 (let ((pn (js2-parse-mul-expr))
8757 tt
8758 (continue t))
8759 (while continue
8760 (setq tt (js2-peek-token))
8761 (if (or (= tt js2-ADD) (= tt js2-SUB))
8762 (progn
8763 (js2-consume-token)
8764 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8765 (setq continue nil)))
8766 pn))
8767
8768 (defconst js2-parse-mul-ops
8769 (list js2-MUL js2-DIV js2-MOD))
8770
8771 (defun js2-parse-mul-expr ()
8772 (let ((pn (js2-parse-unary-expr))
8773 tt
8774 (continue t))
8775 (while continue
8776 (setq tt (js2-peek-token))
8777 (if (memq tt js2-parse-mul-ops)
8778 (progn
8779 (js2-consume-token)
8780 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8781 (setq continue nil)))
8782 pn))
8783
8784 (defsubst js2-make-unary (type parser &rest args)
8785 "Make a unary node of type TYPE.
8786 PARSER is either a node (for postfix operators) or a function to call
8787 to parse the operand (for prefix operators)."
8788 (let* ((pos js2-token-beg)
8789 (postfix (js2-node-p parser))
8790 (expr (if postfix
8791 parser
8792 (apply parser args)))
8793 end
8794 pn)
8795 (if postfix ; e.g. i++
8796 (setq pos (js2-node-pos expr)
8797 end js2-token-end)
8798 (setq end (js2-node-end expr)))
8799 (setq pn (make-js2-unary-node :type type
8800 :pos pos
8801 :len (- end pos)
8802 :operand expr))
8803 (js2-node-add-children pn expr)
8804 pn))
8805
8806 (defconst js2-incrementable-node-types
8807 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8808 "Node types that can be the operand of a ++ or -- operator.")
8809
8810 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8811 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8812 js2-incrementable-node-types)
8813 (js2-report-error (if (= tt js2-INC)
8814 "msg.bad.incr"
8815 "msg.bad.decr")
8816 nil beg (- end beg))))
8817
8818 (defun js2-parse-unary-expr ()
8819 (let ((tt (js2-peek-token))
8820 pn expr beg end)
8821 (cond
8822 ((or (= tt js2-VOID)
8823 (= tt js2-NOT)
8824 (= tt js2-BITNOT)
8825 (= tt js2-TYPEOF))
8826 (js2-consume-token)
8827 (js2-make-unary tt 'js2-parse-unary-expr))
8828 ((= tt js2-ADD)
8829 (js2-consume-token)
8830 ;; Convert to special POS token in decompiler and parse tree
8831 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8832 ((= tt js2-SUB)
8833 (js2-consume-token)
8834 ;; Convert to special NEG token in decompiler and parse tree
8835 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8836 ((or (= tt js2-INC)
8837 (= tt js2-DEC))
8838 (js2-consume-token)
8839 (prog1
8840 (setq beg js2-token-beg
8841 end js2-token-end
8842 expr (js2-make-unary tt 'js2-parse-member-expr t))
8843 (js2-check-bad-inc-dec tt beg end expr)))
8844 ((= tt js2-DELPROP)
8845 (js2-consume-token)
8846 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8847 ((= tt js2-ERROR)
8848 (js2-consume-token)
8849 (make-js2-error-node)) ; try to continue
8850 ((and (= tt js2-LT)
8851 js2-compiler-xml-available)
8852 ;; XML stream encountered in expression.
8853 (js2-consume-token)
8854 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8855 (t
8856 (setq pn (js2-parse-member-expr t)
8857 ;; Don't look across a newline boundary for a postfix incop.
8858 tt (js2-peek-token-or-eol))
8859 (when (or (= tt js2-INC) (= tt js2-DEC))
8860 (js2-consume-token)
8861 (setf expr pn
8862 pn (js2-make-unary tt expr))
8863 (js2-node-set-prop pn 'postfix t)
8864 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8865 pn))))
8866
8867 (defun js2-parse-xml-initializer ()
8868 "Parse an E4X XML initializer.
8869 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8870 Then I'll postprocess the result, depending on whether we're in IDE
8871 mode or codegen mode, and generate the appropriate rewritten AST.
8872 IDE mode uses a rich AST that models the XML structure. Codegen mode
8873 just concatenates everything and makes a new XML or XMLList out of it."
8874 (let ((tt (js2-get-first-xml-token))
8875 pn-xml
8876 pn
8877 expr
8878 kids
8879 expr-pos
8880 (continue t)
8881 (first-token t))
8882 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8883 (js2-report-error "msg.syntax"))
8884 (setq pn-xml (make-js2-xml-node))
8885 (while continue
8886 (if first-token
8887 (setq first-token nil)
8888 (setq tt (js2-get-next-xml-token)))
8889 (cond
8890 ;; js2-XML means we found a {expr} in the XML stream.
8891 ;; The js2-ts-string is the XML up to the left-curly.
8892 ((= tt js2-XML)
8893 (push (make-js2-string-node :pos js2-token-beg
8894 :len (- js2-ts-cursor js2-token-beg))
8895 kids)
8896 (js2-must-match js2-LC "msg.syntax")
8897 (setq expr-pos js2-ts-cursor
8898 expr (if (eq (js2-peek-token) js2-RC)
8899 (make-js2-empty-expr-node :pos expr-pos)
8900 (js2-parse-expr)))
8901 (js2-must-match js2-RC "msg.syntax")
8902 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8903 :len (js2-node-len expr)
8904 :expr expr))
8905 (js2-node-add-children pn expr)
8906 (push pn kids))
8907 ;; a js2-XMLEND token means we hit the final close-tag.
8908 ((= tt js2-XMLEND)
8909 (push (make-js2-string-node :pos js2-token-beg
8910 :len (- js2-ts-cursor js2-token-beg))
8911 kids)
8912 (dolist (kid (nreverse kids))
8913 (js2-block-node-push pn-xml kid))
8914 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8915 (js2-node-pos pn-xml))
8916 continue nil))
8917 (t
8918 (js2-report-error "msg.syntax")
8919 (setq continue nil))))
8920 pn-xml))
8921
8922
8923 (defun js2-parse-argument-list ()
8924 "Parse an argument list and return it as a lisp list of nodes.
8925 Returns the list in reverse order. Consumes the right-paren token."
8926 (let (result)
8927 (unless (js2-match-token js2-RP)
8928 (loop do
8929 (if (= (js2-peek-token) js2-YIELD)
8930 (js2-report-error "msg.yield.parenthesized"))
8931 (push (js2-parse-assign-expr) result)
8932 while
8933 (js2-match-token js2-COMMA))
8934 (js2-must-match js2-RP "msg.no.paren.arg")
8935 result)))
8936
8937 (defun js2-parse-member-expr (&optional allow-call-syntax)
8938 (let ((tt (js2-peek-token))
8939 pn
8940 pos
8941 target
8942 args
8943 beg
8944 end
8945 init
8946 tail)
8947 (if (/= tt js2-NEW)
8948 (setq pn (js2-parse-primary-expr))
8949 ;; parse a 'new' expression
8950 (js2-consume-token)
8951 (setq pos js2-token-beg
8952 beg pos
8953 target (js2-parse-member-expr)
8954 end (js2-node-end target)
8955 pn (make-js2-new-node :pos pos
8956 :target target
8957 :len (- end pos)))
8958 (js2-node-add-children pn target)
8959 (when (js2-match-token js2-LP)
8960 ;; Add the arguments to pn, if any are supplied.
8961 (setf beg pos ; start of "new" keyword
8962 pos js2-token-beg
8963 args (nreverse (js2-parse-argument-list))
8964 (js2-new-node-args pn) args
8965 end js2-token-end
8966 (js2-new-node-lp pn) (- pos beg)
8967 (js2-new-node-rp pn) (- end 1 beg))
8968 (apply #'js2-node-add-children pn args))
8969 (when (and js2-allow-rhino-new-expr-initializer
8970 (js2-match-token js2-LC))
8971 (setf init (js2-parse-object-literal)
8972 end (js2-node-end init)
8973 (js2-new-node-initializer pn) init)
8974 (js2-node-add-children pn init))
8975 (setf (js2-node-len pn) (- end beg))) ; end outer if
8976 (js2-parse-member-expr-tail allow-call-syntax pn)))
8977
8978 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8979 "Parse a chain of property/array accesses or function calls.
8980 Includes parsing for E4X operators like `..' and `.@'.
8981 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8982 Returns an expression tree that includes PN, the parent node."
8983 (let ((beg (js2-node-pos pn))
8984 tt
8985 (continue t))
8986 (while continue
8987 (setq tt (js2-peek-token))
8988 (cond
8989 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8990 (setq pn (js2-parse-property-access tt pn)))
8991 ((= tt js2-DOTQUERY)
8992 (setq pn (js2-parse-dot-query pn)))
8993 ((= tt js2-LB)
8994 (setq pn (js2-parse-element-get pn)))
8995 ((= tt js2-LP)
8996 (if allow-call-syntax
8997 (setq pn (js2-parse-function-call pn))
8998 (setq continue nil)))
8999 (t
9000 (setq continue nil))))
9001 (if (>= js2-highlight-level 2)
9002 (js2-parse-highlight-member-expr-node pn))
9003 pn))
9004
9005 (defun js2-parse-dot-query (pn)
9006 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9007 Last token parsed must be `js2-DOTQUERY'."
9008 (let ((pos (js2-node-pos pn))
9009 op-pos
9010 expr
9011 end)
9012 (js2-consume-token)
9013 (js2-must-have-xml)
9014 (js2-set-requires-activation)
9015 (setq op-pos js2-token-beg
9016 expr (js2-parse-expr)
9017 end (js2-node-end expr)
9018 pn (make-js2-xml-dot-query-node :left pn
9019 :pos pos
9020 :op-pos op-pos
9021 :right expr))
9022 (js2-node-add-children pn
9023 (js2-xml-dot-query-node-left pn)
9024 (js2-xml-dot-query-node-right pn))
9025 (if (js2-must-match js2-RP "msg.no.paren")
9026 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9027 end js2-token-end))
9028 (setf (js2-node-len pn) (- end pos))
9029 pn))
9030
9031 (defun js2-parse-element-get (pn)
9032 "Parse an element-get expression, e.g. foo[bar].
9033 Last token parsed must be `js2-RB'."
9034 (let ((lb js2-token-beg)
9035 (pos (js2-node-pos pn))
9036 rb
9037 expr)
9038 (js2-consume-token)
9039 (setq expr (js2-parse-expr))
9040 (if (js2-must-match js2-RB "msg.no.bracket.index")
9041 (setq rb js2-token-beg))
9042 (setq pn (make-js2-elem-get-node :target pn
9043 :pos pos
9044 :element expr
9045 :lb (js2-relpos lb pos)
9046 :rb (js2-relpos rb pos)
9047 :len (- js2-token-end pos)))
9048 (js2-node-add-children pn
9049 (js2-elem-get-node-target pn)
9050 (js2-elem-get-node-element pn))
9051 pn))
9052
9053 (defun js2-parse-function-call (pn)
9054 (let (args
9055 (pos (js2-node-pos pn)))
9056 (js2-consume-token)
9057 (setq pn (make-js2-call-node :pos pos
9058 :target pn
9059 :lp (- js2-token-beg pos)))
9060 (js2-node-add-children pn (js2-call-node-target pn))
9061 ;; Add the arguments to pn, if any are supplied.
9062 (setf args (nreverse (js2-parse-argument-list))
9063 (js2-call-node-rp pn) (- js2-token-beg pos)
9064 (js2-call-node-args pn) args)
9065 (apply #'js2-node-add-children pn args)
9066 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9067 pn))
9068
9069 (defun js2-parse-property-access (tt pn)
9070 "Parse a property access, XML descendants access, or XML attr access."
9071 (let ((member-type-flags 0)
9072 (dot-pos js2-token-beg)
9073 (dot-len (if (= tt js2-DOTDOT) 2 1))
9074 name
9075 ref ; right side of . or .. operator
9076 result)
9077 (js2-consume-token)
9078 (when (= tt js2-DOTDOT)
9079 (js2-must-have-xml)
9080 (setq member-type-flags js2-descendants-flag))
9081 (if (not js2-compiler-xml-available)
9082 (progn
9083 (js2-must-match-prop-name "msg.no.name.after.dot")
9084 (setq name (js2-create-name-node t js2-GETPROP)
9085 result (make-js2-prop-get-node :left pn
9086 :pos js2-token-beg
9087 :right name
9088 :len (- js2-token-end
9089 js2-token-beg)))
9090 (js2-node-add-children result pn name)
9091 result)
9092 ;; otherwise look for XML operators
9093 (setf result (if (= tt js2-DOT)
9094 (make-js2-prop-get-node)
9095 (make-js2-infix-node :type js2-DOTDOT))
9096 (js2-node-pos result) (js2-node-pos pn)
9097 (js2-infix-node-op-pos result) dot-pos
9098 (js2-infix-node-left result) pn ; do this after setting position
9099 tt (js2-next-token))
9100 (cond
9101 ;; needed for generator.throw()
9102 ((= tt js2-THROW)
9103 (js2-save-name-token-data js2-token-beg "throw")
9104 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9105 ;; handles: name, ns::name, ns::*, ns::[expr]
9106 ((js2-valid-prop-name-token tt)
9107 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9108 ;; handles: *, *::name, *::*, *::[expr]
9109 ((= tt js2-MUL)
9110 (js2-save-name-token-data js2-token-beg "*")
9111 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9112 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9113 ((= tt js2-XMLATTR)
9114 (setq result (js2-parse-attribute-access)))
9115 (t
9116 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9117 (if ref
9118 (setf (js2-node-len result) (- (js2-node-end ref)
9119 (js2-node-pos result))
9120 (js2-infix-node-right result) ref))
9121 (if (js2-infix-node-p result)
9122 (js2-node-add-children result
9123 (js2-infix-node-left result)
9124 (js2-infix-node-right result)))
9125 result)))
9126
9127 (defun js2-parse-attribute-access ()
9128 "Parse an E4X XML attribute expression.
9129 This includes expressions of the forms:
9130
9131 @attr @ns::attr @ns::*
9132 @* @*::attr @*::*
9133 @[expr] @*::[expr] @ns::[expr]
9134
9135 Called if we peeked an '@' token."
9136 (let ((tt (js2-next-token))
9137 (at-pos js2-token-beg))
9138 (cond
9139 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9140 ((js2-valid-prop-name-token tt)
9141 (js2-parse-property-name at-pos js2-ts-string 0))
9142 ;; handles: @*, @*::name, @*::*, @*::[expr]
9143 ((= tt js2-MUL)
9144 (js2-save-name-token-data js2-token-beg "*")
9145 (js2-parse-property-name js2-token-beg "*" 0))
9146 ;; handles @[expr]
9147 ((= tt js2-LB)
9148 (js2-parse-xml-elem-ref at-pos))
9149 (t
9150 (js2-report-error "msg.no.name.after.xmlAttr")
9151 ;; Avoid cascaded errors that happen if we make an error node here.
9152 (js2-save-name-token-data js2-token-beg "")
9153 (js2-parse-property-name js2-token-beg "" 0)))))
9154
9155 (defun js2-parse-property-name (at-pos s member-type-flags)
9156 "Check if :: follows name in which case it becomes qualified name.
9157
9158 AT-POS is a natural number if we just read an '@' token, else nil.
9159 S is the name or string that was matched: an identifier, 'throw' or '*'.
9160 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9161
9162 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9163 operator, or the name is followed by ::. For a plain name, returns a
9164 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9165 (let ((pos (or at-pos js2-token-beg))
9166 colon-pos
9167 (name (js2-create-name-node t js2-current-token))
9168 ns
9169 tt
9170 ref
9171 pn)
9172 (catch 'return
9173 (when (js2-match-token js2-COLONCOLON)
9174 (setq ns name
9175 colon-pos js2-token-beg
9176 tt (js2-next-token))
9177 (cond
9178 ;; handles name::name
9179 ((js2-valid-prop-name-token tt)
9180 (setq name (js2-create-name-node)))
9181 ;; handles name::*
9182 ((= tt js2-MUL)
9183 (js2-save-name-token-data js2-token-beg "*")
9184 (setq name (js2-create-name-node)))
9185 ;; handles name::[expr]
9186 ((= tt js2-LB)
9187 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9188 (t
9189 (js2-report-error "msg.no.name.after.coloncolon"))))
9190 (if (and (null ns) (zerop member-type-flags))
9191 name
9192 (prog1
9193 (setq pn
9194 (make-js2-xml-prop-ref-node :pos pos
9195 :len (- (js2-node-end name) pos)
9196 :at-pos at-pos
9197 :colon-pos colon-pos
9198 :propname name))
9199 (js2-node-add-children pn name))))))
9200
9201 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9202 "Parse the [expr] portion of an xml element reference.
9203 For instance, @[expr], @*::[expr], or ns::[expr]."
9204 (let* ((lb js2-token-beg)
9205 (pos (or at-pos lb))
9206 rb
9207 (expr (js2-parse-expr))
9208 (end (js2-node-end expr))
9209 pn)
9210 (if (js2-must-match js2-RB "msg.no.bracket.index")
9211 (setq rb js2-token-beg
9212 end js2-token-end))
9213 (prog1
9214 (setq pn
9215 (make-js2-xml-elem-ref-node :pos pos
9216 :len (- end pos)
9217 :namespace namespace
9218 :colon-pos colon-pos
9219 :at-pos at-pos
9220 :expr expr
9221 :lb (js2-relpos lb pos)
9222 :rb (js2-relpos rb pos)))
9223 (js2-node-add-children pn namespace expr))))
9224
9225 (defsubst js2-parse-primary-expr-lhs ()
9226 (let ((js2-is-in-lhs t))
9227 (js2-parse-primary-expr)))
9228
9229 (defun js2-parse-primary-expr ()
9230 "Parses a literal (leaf) expression of some sort.
9231 Includes complex literals such as functions, object-literals,
9232 array-literals, array comprehensions and regular expressions."
9233 (let ((tt-flagged (js2-next-flagged-token))
9234 pn ; parent node (usually return value)
9235 tt
9236 px-pos ; paren-expr pos
9237 len
9238 flags ; regexp flags
9239 expr)
9240 (setq tt js2-current-token)
9241 (cond
9242 ((= tt js2-FUNCTION)
9243 (js2-parse-function 'FUNCTION_EXPRESSION))
9244 ((= tt js2-LB)
9245 (js2-parse-array-literal))
9246 ((= tt js2-LC)
9247 (js2-parse-object-literal))
9248 ((= tt js2-LET)
9249 (js2-parse-let js2-token-beg))
9250 ((= tt js2-LP)
9251 (setq px-pos js2-token-beg
9252 expr (js2-parse-expr))
9253 (js2-must-match js2-RP "msg.no.paren")
9254 (setq pn (make-js2-paren-node :pos px-pos
9255 :expr expr
9256 :len (- js2-token-end px-pos)))
9257 (js2-node-add-children pn (js2-paren-node-expr pn))
9258 pn)
9259 ((= tt js2-XMLATTR)
9260 (js2-must-have-xml)
9261 (js2-parse-attribute-access))
9262 ((= tt js2-NAME)
9263 (js2-parse-name tt-flagged tt))
9264 ((= tt js2-NUMBER)
9265 (make-js2-number-node))
9266 ((= tt js2-STRING)
9267 (prog1
9268 (make-js2-string-node)
9269 (js2-record-face 'font-lock-string-face)))
9270 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9271 ;; Got / or /= which in this context means a regexp literal
9272 (setq px-pos js2-token-beg)
9273 (js2-read-regexp tt)
9274 (setq flags js2-ts-regexp-flags
9275 js2-ts-regexp-flags nil)
9276 (prog1
9277 (make-js2-regexp-node :pos px-pos
9278 :len (- js2-ts-cursor px-pos)
9279 :value js2-ts-string
9280 :flags flags)
9281 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9282 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9283 ((or (= tt js2-NULL)
9284 (= tt js2-THIS)
9285 (= tt js2-FALSE)
9286 (= tt js2-TRUE))
9287 (make-js2-keyword-node :type tt))
9288 ((= tt js2-RESERVED)
9289 (js2-report-error "msg.reserved.id")
9290 (make-js2-name-node))
9291 ((= tt js2-ERROR)
9292 ;; the scanner or one of its subroutines reported the error.
9293 (make-js2-error-node))
9294 ((= tt js2-EOF)
9295 (setq px-pos (point-at-bol)
9296 len (- js2-ts-cursor px-pos))
9297 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9298 (make-js2-error-node :pos px-pos :len len))
9299 (t
9300 (js2-report-error "msg.syntax")
9301 (make-js2-error-node)))))
9302
9303 (defun js2-parse-name (tt-flagged tt)
9304 (let ((name js2-ts-string)
9305 (name-pos js2-token-beg)
9306 node)
9307 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9308 (= (js2-peek-token) js2-COLON))
9309 (prog1
9310 ;; Do not consume colon, it is used as unwind indicator
9311 ;; to return to statementHelper.
9312 (make-js2-label-node :pos name-pos
9313 :len (- js2-token-end name-pos)
9314 :name name)
9315 (js2-set-face name-pos
9316 js2-token-end
9317 'font-lock-variable-name-face 'record))
9318 ;; Otherwise not a label, just a name. Unfortunately peeking
9319 ;; the next token to check for a colon has biffed js2-token-beg
9320 ;; and js2-token-end. We store the name's bounds in buffer vars
9321 ;; and `js2-create-name-node' uses them.
9322 (js2-save-name-token-data name-pos name)
9323 (setq node (if js2-compiler-xml-available
9324 (js2-parse-property-name nil name 0)
9325 (js2-create-name-node 'check-activation)))
9326 (if js2-highlight-external-variables
9327 (js2-record-name-node node))
9328 node)))
9329
9330 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9331 (js2-add-strict-warning
9332 msg nil
9333 ;; back up from comma to beginning of line or array/objlit
9334 (max (if elems
9335 (js2-node-pos (car elems))
9336 pos)
9337 (save-excursion
9338 (goto-char comma-pos)
9339 (back-to-indentation)
9340 (point)))
9341 comma-pos))
9342
9343 (defun js2-parse-array-literal ()
9344 (let ((pos js2-token-beg)
9345 (end js2-token-end)
9346 (after-lb-or-comma t)
9347 after-comma
9348 tt
9349 elems
9350 pn
9351 (continue t))
9352 (unless js2-is-in-lhs
9353 (js2-push-scope (make-js2-scope))) ; for array comp
9354 (while continue
9355 (setq tt (js2-peek-token))
9356 (cond
9357 ;; comma
9358 ((= tt js2-COMMA)
9359 (js2-consume-token)
9360 (setq after-comma js2-token-end)
9361 (if (not after-lb-or-comma)
9362 (setq after-lb-or-comma t)
9363 (push nil elems)))
9364 ;; end of array
9365 ((or (= tt js2-RB)
9366 (= tt js2-EOF)) ; prevent infinite loop
9367 (if (= tt js2-EOF)
9368 (js2-report-error "msg.no.bracket.arg" nil pos)
9369 (js2-consume-token))
9370 (setq continue nil
9371 end js2-token-end
9372 pn (make-js2-array-node :pos pos
9373 :len (- js2-ts-cursor pos)
9374 :elems (nreverse elems)))
9375 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9376 (when after-comma
9377 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9378 pos elems after-comma)))
9379 ;; destructuring binding
9380 (js2-is-in-lhs
9381 (push (if (or (= tt js2-LC)
9382 (= tt js2-LB)
9383 (= tt js2-NAME))
9384 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9385 (js2-parse-primary-expr-lhs)
9386 ;; invalid pattern
9387 (js2-consume-token)
9388 (js2-report-error "msg.bad.var")
9389 (make-js2-error-node))
9390 elems)
9391 (setq after-lb-or-comma nil
9392 after-comma nil))
9393 ;; array comp
9394 ((and (>= js2-language-version 170)
9395 (= tt js2-FOR) ; check for array comprehension
9396 (not after-lb-or-comma) ; "for" can't follow a comma
9397 elems ; must have at least 1 element
9398 (not (cdr elems))) ; but no 2nd element
9399 (setf continue nil
9400 pn (js2-parse-array-comprehension (car elems) pos)))
9401
9402 ;; another element
9403 (t
9404 (unless after-lb-or-comma
9405 (js2-report-error "msg.no.bracket.arg"))
9406 (push (js2-parse-assign-expr) elems)
9407 (setq after-lb-or-comma nil
9408 after-comma nil))))
9409 (unless js2-is-in-lhs
9410 (js2-pop-scope))
9411 pn))
9412
9413 (defun js2-parse-array-comprehension (expr pos)
9414 "Parse a JavaScript 1.7 Array Comprehension.
9415 EXPR is the first expression after the opening left-bracket.
9416 POS is the beginning of the LB token preceding EXPR.
9417 We should have just parsed the 'for' keyword before calling this function."
9418 (let (loops
9419 loop
9420 first
9421 prev
9422 filter
9423 if-pos
9424 result)
9425 (while (= (js2-peek-token) js2-FOR)
9426 (let ((prev (car loops))) ; rearrange scope chain
9427 (push (setq loop (js2-parse-array-comp-loop)) loops)
9428 (if prev ; each loop is parent scope to the next one
9429 (setf (js2-scope-parent-scope loop) prev)
9430 ; first loop takes expr scope's parent
9431 (setf (js2-scope-parent-scope (setq first loop))
9432 (js2-scope-parent-scope js2-current-scope)))))
9433 ;; set expr scope's parent to the last loop
9434 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9435 (when (= (js2-peek-token) js2-IF)
9436 (js2-consume-token)
9437 (setq if-pos (- js2-token-beg pos) ; relative
9438 filter (js2-parse-condition)))
9439 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9440 (setq result (make-js2-array-comp-node :pos pos
9441 :len (- js2-ts-cursor pos)
9442 :result expr
9443 :loops (nreverse loops)
9444 :filter (car filter)
9445 :lp (js2-relpos (second filter) pos)
9446 :rp (js2-relpos (third filter) pos)
9447 :if-pos if-pos))
9448 (apply #'js2-node-add-children result expr (car filter)
9449 (js2-array-comp-node-loops result))
9450 (setq js2-current-scope first) ; pop to the first loop
9451 result))
9452
9453 (defun js2-parse-array-comp-loop ()
9454 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9455 Last token peeked should be the initial FOR."
9456 (let ((pos js2-token-beg)
9457 (pn (make-js2-array-comp-loop-node))
9458 tt
9459 iter
9460 obj
9461 foreach-p
9462 in-pos
9463 each-pos
9464 lp
9465 rp)
9466 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9467 (js2-push-scope pn)
9468 (unwind-protect
9469 (progn
9470 (when (js2-match-token js2-NAME)
9471 (if (string= js2-ts-string "each")
9472 (progn
9473 (setq foreach-p t
9474 each-pos (- js2-token-beg pos)) ; relative
9475 (js2-record-face 'font-lock-keyword-face))
9476 (js2-report-error "msg.no.paren.for")))
9477 (if (js2-must-match js2-LP "msg.no.paren.for")
9478 (setq lp (- js2-token-beg pos)))
9479 (setq tt (js2-peek-token))
9480 (cond
9481 ((or (= tt js2-LB)
9482 (= tt js2-LC))
9483 ;; handle destructuring assignment
9484 (setq iter (js2-parse-primary-expr-lhs)))
9485 ((js2-valid-prop-name-token tt)
9486 (js2-consume-token)
9487 (setq iter (js2-create-name-node)))
9488 (t
9489 (js2-report-error "msg.bad.var")))
9490 ;; Define as a let since we want the scope of the variable to
9491 ;; be restricted to the array comprehension
9492 (if (js2-name-node-p iter)
9493 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9494 (if (js2-must-match js2-IN "msg.in.after.for.name")
9495 (setq in-pos (- js2-token-beg pos)))
9496 (setq obj (js2-parse-expr))
9497 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9498 (setq rp (- js2-token-beg pos)))
9499 (setf (js2-node-pos pn) pos
9500 (js2-node-len pn) (- js2-ts-cursor pos)
9501 (js2-array-comp-loop-node-iterator pn) iter
9502 (js2-array-comp-loop-node-object pn) obj
9503 (js2-array-comp-loop-node-in-pos pn) in-pos
9504 (js2-array-comp-loop-node-each-pos pn) each-pos
9505 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9506 (js2-array-comp-loop-node-lp pn) lp
9507 (js2-array-comp-loop-node-rp pn) rp)
9508 (js2-node-add-children pn iter obj))
9509 (js2-pop-scope))
9510 pn))
9511
9512 (defun js2-parse-object-literal ()
9513 (let ((pos js2-token-beg)
9514 tt
9515 elems
9516 result
9517 after-comma
9518 (continue t))
9519 (while continue
9520 (setq tt (js2-peek-token))
9521 (cond
9522 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9523 ((or (js2-valid-prop-name-token tt)
9524 (= tt js2-STRING))
9525 (setq after-comma nil
9526 result (js2-parse-named-prop tt))
9527 (if (and (null result)
9528 (not js2-recover-from-parse-errors))
9529 (setq continue nil)
9530 (push result elems)))
9531 ;; {12: x} or {10.7: x}
9532 ((= tt js2-NUMBER)
9533 (js2-consume-token)
9534 (setq after-comma nil)
9535 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9536 ;; trailing comma
9537 ((= tt js2-RC)
9538 (setq continue nil)
9539 (if after-comma
9540 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9541 pos elems after-comma)))
9542 (t
9543 (js2-report-error "msg.bad.prop")
9544 (unless js2-recover-from-parse-errors
9545 (setq continue nil)))) ; end switch
9546 (if (js2-match-token js2-COMMA)
9547 (setq after-comma js2-token-end)
9548 (setq continue nil))) ; end loop
9549 (js2-must-match js2-RC "msg.no.brace.prop")
9550 (setq result (make-js2-object-node :pos pos
9551 :len (- js2-ts-cursor pos)
9552 :elems (nreverse elems)))
9553 (apply #'js2-node-add-children result (js2-object-node-elems result))
9554 result))
9555
9556 (defun js2-parse-named-prop (tt)
9557 "Parse a name, string, or getter/setter object property.
9558 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9559 (js2-consume-token)
9560 (let ((string-prop (and (= tt js2-STRING)
9561 (make-js2-string-node)))
9562 expr
9563 (ppos js2-token-beg)
9564 (pend js2-token-end)
9565 (name (js2-create-name-node))
9566 (prop js2-ts-string))
9567 (cond
9568 ;; getter/setter prop
9569 ((and (= tt js2-NAME)
9570 (= (js2-peek-token) js2-NAME)
9571 (or (string= prop "get")
9572 (string= prop "set")))
9573 (js2-consume-token)
9574 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9575 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9576 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9577 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9578 ;; abbreviated destructuring bind e.g., {a, b} = c;
9579 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9580 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9581 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9582 ;; assignment but it's difficult because it requires looking ahead of expression.
9583 ((and js2-is-in-lhs
9584 (= tt js2-NAME)
9585 (let ((ctk (js2-peek-token)))
9586 (or (= ctk js2-COMMA)
9587 (= ctk js2-RC)
9588 (js2-valid-prop-name-token ctk))))
9589 name)
9590 ;; regular prop
9591 (t
9592 (prog1
9593 (setq expr (js2-parse-plain-property (or string-prop name)))
9594 (js2-set-face ppos pend
9595 (if (js2-function-node-p
9596 (js2-object-prop-node-right expr))
9597 'font-lock-function-name-face
9598 'font-lock-variable-name-face)
9599 'record))))))
9600
9601 (defun js2-parse-plain-property (prop)
9602 "Parse a non-getter/setter property in an object literal.
9603 PROP is the node representing the property: a number, name or string."
9604 (js2-must-match js2-COLON "msg.no.colon.prop")
9605 (let* ((pos (js2-node-pos prop))
9606 (colon (- js2-token-beg pos))
9607 (expr (js2-parse-assign-expr))
9608 (result (make-js2-object-prop-node
9609 :pos pos
9610 ;; don't include last consumed token in length
9611 :len (- (+ (js2-node-pos expr)
9612 (js2-node-len expr))
9613 pos)
9614 :left prop
9615 :right expr
9616 :op-pos colon)))
9617 (js2-node-add-children result prop expr)
9618 result))
9619
9620 (defun js2-parse-getter-setter-prop (pos prop get-p)
9621 "Parse getter or setter property in an object literal.
9622 JavaScript syntax is:
9623
9624 { get foo() {...}, set foo(x) {...} }
9625
9626 and expression closure style is also supported
9627
9628 { get foo() x, set foo(x) _x = x }
9629
9630 POS is the start position of the `get' or `set' keyword.
9631 PROP is the `js2-name-node' representing the property name.
9632 GET-P is non-nil if the keyword was `get'."
9633 (let ((type (if get-p js2-GET js2-SET))
9634 result
9635 end
9636 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9637 ;; it has to be an anonymous function, as we already parsed the name
9638 (if (/= (js2-node-type fn) js2-FUNCTION)
9639 (js2-report-error "msg.bad.prop")
9640 (if (plusp (length (js2-function-name fn)))
9641 (js2-report-error "msg.bad.prop")))
9642 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9643 (setq end (js2-node-end fn)
9644 result (make-js2-getter-setter-node :type type
9645 :pos pos
9646 :len (- end pos)
9647 :left prop
9648 :right fn))
9649 (js2-node-add-children result prop fn)
9650 result))
9651
9652 (defun js2-create-name-node (&optional check-activation-p token)
9653 "Create a name node using the token info from last scanned name.
9654 In some cases we need to either synthesize a name node, or we lost
9655 the name token information by peeking. If the TOKEN parameter is
9656 not `js2-NAME', then we use the token info saved in instance vars."
9657 (let ((beg js2-token-beg)
9658 (s js2-ts-string)
9659 name)
9660 (when (/= js2-current-token js2-NAME)
9661 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9662 s js2-prev-name-token-string
9663 js2-prev-name-token-start nil
9664 js2-prev-name-token-string nil))
9665 (setq name (make-js2-name-node :pos beg
9666 :name s
9667 :len (length s)))
9668 (if check-activation-p
9669 (js2-check-activation-name s (or token js2-NAME)))
9670 name))
9671
9672 ;;; Indentation support
9673
9674 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9675 ;; Karl cleverly deduces that the desired indentation level is often a
9676 ;; function of paren/bracket/brace nesting depth, which can be determined
9677 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9678 ;; then does some equally clever checks to see if we're in the context of a
9679 ;; substatement of a possibly braceless statement keyword such as if, while,
9680 ;; or finally. This approach yields pretty good results.
9681
9682 ;; The indenter is often "wrong", however, and needs to be overridden.
9683 ;; The right long-term solution is probably to emulate (or integrate
9684 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9685 ;; parse tree from `js2-parse' is present, which is not true at the
9686 ;; moment the user is typing, computing indentation is still thousands
9687 ;; of lines of code to handle every possible syntactic edge case.
9688
9689 ;; In the meantime, the compromise solution is that we offer a "bounce
9690 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9691 ;; current line indent among various likely guess points. This approach
9692 ;; is far from perfect, but should at least make it slightly easier to
9693 ;; move the line towards its desired indentation when manually
9694 ;; overriding Karl's heuristic nesting guesser.
9695
9696 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9697 ;; extensions such as `let' and Array comprehensions. Major kudos to
9698 ;; Karl for coming up with the initial approach, which packs a lot of
9699 ;; punch for so little code.
9700
9701 (defconst js-possibly-braceless-keyword-re
9702 (regexp-opt
9703 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9704 'words)
9705 "Regular expression matching keywords that are optionally
9706 followed by an opening brace.")
9707
9708 (defconst js-possibly-braceless-keywords-re
9709 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9710 "Regular expression which matches the keywords which are consist of more than 2 words
9711 like 'if else' and 'for each', and optionally followed by an opening brace.")
9712
9713 (defconst js-indent-operator-re
9714 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9715 (regexp-opt '("in" "instanceof") 'words))
9716 "Regular expression matching operators that affect indentation
9717 of continued expressions.")
9718
9719 ;; This function has horrible results if you're typing an array
9720 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9721 ;; in conjunction with electric-indent, so just disabling it.
9722 (defsubst js2-code-at-bol-p ()
9723 "Return t if the first character on line is non-whitespace."
9724 nil)
9725
9726 (defun js2-insert-and-indent (key)
9727 "Run command bound to key and indent current line. Runs the command
9728 bound to KEY in the global keymap and indents the current line."
9729 (interactive (list (this-command-keys)))
9730 (let ((cmd (lookup-key (current-global-map) key)))
9731 (if (commandp cmd)
9732 (call-interactively cmd)))
9733 ;; don't do the electric keys inside comments or strings,
9734 ;; and don't do bounce-indent with them.
9735 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9736 (js2-bounce-indent-p (js2-code-at-bol-p)))
9737 (unless (or (nth 3 parse-state)
9738 (nth 4 parse-state))
9739 (indent-according-to-mode))))
9740
9741 (defun js-re-search-forward-inner (regexp &optional bound count)
9742 "Auxiliary function for `js-re-search-forward'."
9743 (let ((parse)
9744 (saved-point (point-min)))
9745 (while (> count 0)
9746 (re-search-forward regexp bound)
9747 (setq parse (parse-partial-sexp saved-point (point)))
9748 (cond ((nth 3 parse)
9749 (re-search-forward
9750 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9751 (save-excursion (end-of-line) (point)) t))
9752 ((nth 7 parse)
9753 (forward-line))
9754 ((or (nth 4 parse)
9755 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9756 (re-search-forward "\\*/"))
9757 (t
9758 (setq count (1- count))))
9759 (setq saved-point (point))))
9760 (point))
9761
9762 (defun js-re-search-forward (regexp &optional bound noerror count)
9763 "Search forward but ignore strings and comments. Invokes
9764 `re-search-forward' but treats the buffer as if strings and
9765 comments have been removed."
9766 (let ((saved-point (point))
9767 (search-expr
9768 (cond ((null count)
9769 '(js-re-search-forward-inner regexp bound 1))
9770 ((< count 0)
9771 '(js-re-search-backward-inner regexp bound (- count)))
9772 ((> count 0)
9773 '(js-re-search-forward-inner regexp bound count)))))
9774 (condition-case err
9775 (eval search-expr)
9776 (search-failed
9777 (goto-char saved-point)
9778 (unless noerror
9779 (error (error-message-string err)))))))
9780
9781 (defun js-re-search-backward-inner (regexp &optional bound count)
9782 "Auxiliary function for `js-re-search-backward'."
9783 (let ((parse)
9784 (saved-point (point-min)))
9785 (while (> count 0)
9786 (re-search-backward regexp bound)
9787 (setq parse (parse-partial-sexp saved-point (point)))
9788 (cond ((nth 3 parse)
9789 (re-search-backward
9790 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9791 (save-excursion (beginning-of-line) (point)) t))
9792 ((nth 7 parse)
9793 (goto-char (nth 8 parse)))
9794 ((or (nth 4 parse)
9795 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9796 (re-search-backward "/\\*"))
9797 (t
9798 (setq count (1- count))))))
9799 (point))
9800
9801 (defun js-re-search-backward (regexp &optional bound noerror count)
9802 "Search backward but ignore strings and comments. Invokes
9803 `re-search-backward' but treats the buffer as if strings and
9804 comments have been removed."
9805 (let ((saved-point (point))
9806 (search-expr
9807 (cond ((null count)
9808 '(js-re-search-backward-inner regexp bound 1))
9809 ((< count 0)
9810 '(js-re-search-forward-inner regexp bound (- count)))
9811 ((> count 0)
9812 '(js-re-search-backward-inner regexp bound count)))))
9813 (condition-case err
9814 (eval search-expr)
9815 (search-failed
9816 (goto-char saved-point)
9817 (unless noerror
9818 (error (error-message-string err)))))))
9819
9820 (defun js-looking-at-operator-p ()
9821 "Return non-nil if text after point is an operator (that is not
9822 a comma)."
9823 (save-match-data
9824 (and (looking-at js-indent-operator-re)
9825 (or (not (looking-at ":"))
9826 (save-excursion
9827 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9828 (looking-at "?")))))))
9829
9830 (defun js-continued-expression-p ()
9831 "Returns non-nil if the current line continues an expression."
9832 (save-excursion
9833 (back-to-indentation)
9834 (or (js-looking-at-operator-p)
9835 ;; comment
9836 (and (js-re-search-backward "\n" nil t)
9837 (progn
9838 (skip-chars-backward " \t")
9839 (backward-char)
9840 (and (js-looking-at-operator-p)
9841 (and (progn (backward-char)
9842 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9843
9844 (defun js-end-of-do-while-loop-p ()
9845 "Returns non-nil if word after point is `while' of a do-while
9846 statement, else returns nil. A braceless do-while statement
9847 spanning several lines requires that the start of the loop is
9848 indented to the same column as the current line."
9849 (interactive)
9850 (save-excursion
9851 (save-match-data
9852 (when (looking-at "\\s-*\\<while\\>")
9853 (if (save-excursion
9854 (skip-chars-backward "[ \t\n]*}")
9855 (looking-at "[ \t\n]*}"))
9856 (save-excursion
9857 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9858 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9859 (or (looking-at "\\<do\\>")
9860 (let ((saved-indent (current-indentation)))
9861 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9862 (/= (current-indentation) saved-indent)))
9863 (and (looking-at "[ \t]*\\<do\\>")
9864 (not (js-re-search-forward
9865 "\\<while\\>" (point-at-eol) t))
9866 (= (current-indentation) saved-indent)))))))))
9867
9868 (defun js-get-multiline-declaration-offset ()
9869 "Returns offset (> 0) if the current line is part of
9870 multi-line variable declaration like below example, and
9871 returns 0 otherwise.
9872
9873 var a = 10,
9874 b = 20,
9875 c = 30;
9876
9877 "
9878 (let* ((node (js2-node-at-point))
9879 (pnode (and node (js2-node-parent node)))
9880 (pnode-type (and pnode (js2-node-type pnode))))
9881 (if (and node
9882 (= js2-NAME (js2-node-type node))
9883 (or
9884 (= js2-VAR pnode-type)
9885 (= js2-LET pnode-type)
9886 (= js2-CONST pnode-type)))
9887 (if (= js2-CONST pnode-type)
9888 6
9889 4)
9890 0)))
9891
9892 (defun js-ctrl-statement-indentation ()
9893 "Returns the proper indentation of the current line if it
9894 starts the body of a control statement without braces, else
9895 returns nil."
9896 (let (forward-sexp-function) ; temporarily unbind it
9897 (save-excursion
9898 (back-to-indentation)
9899 (when (save-excursion
9900 (and (not (js2-same-line (point-min)))
9901 (not (looking-at "{"))
9902 (js-re-search-backward "[[:graph:]]" nil t)
9903 (not (looking-at "[{([]"))
9904 (progn
9905 (forward-char)
9906 ;; scan-sexps sometimes throws an error
9907 (ignore-errors (backward-sexp))
9908 (when (looking-at "(") (backward-word 1))
9909 (and (save-excursion
9910 (skip-chars-backward " \t}" (point-at-bol))
9911 (or (bolp)
9912 (and (backward-word 1)
9913 (skip-chars-backward " \t}" (point-at-bol))
9914 (bolp)
9915 (looking-at js-possibly-braceless-keywords-re))))
9916 (looking-at js-possibly-braceless-keyword-re)
9917 (not (js-end-of-do-while-loop-p))))))
9918 (save-excursion
9919 (goto-char (match-beginning 0))
9920 (+ (current-indentation) js2-basic-offset))))))
9921
9922 (defun js2-indent-in-array-comp (parse-status)
9923 "Return non-nil if we think we're in an array comprehension.
9924 In particular, return the buffer position of the first `for' kwd."
9925 (let ((end (point)))
9926 (when (nth 1 parse-status)
9927 (save-excursion
9928 (goto-char (nth 1 parse-status))
9929 (when (looking-at "\\[")
9930 (forward-char 1)
9931 (js2-forward-sws)
9932 (if (looking-at "[[{]")
9933 (let (forward-sexp-function) ; use lisp version
9934 (forward-sexp) ; skip destructuring form
9935 (js2-forward-sws)
9936 (if (and (/= (char-after) ?,) ; regular array
9937 (looking-at "for"))
9938 (match-beginning 0)))
9939 ;; to skip arbitrary expressions we need the parser,
9940 ;; so we'll just guess at it.
9941 (if (re-search-forward "[^,]* \\(for\\) " end t)
9942 (match-beginning 1))))))))
9943
9944 (defun js2-array-comp-indentation (parse-status for-kwd)
9945 (if (js2-same-line for-kwd)
9946 ;; first continuation line
9947 (save-excursion
9948 (goto-char (nth 1 parse-status))
9949 (forward-char 1)
9950 (skip-chars-forward " \t")
9951 (current-column))
9952 (save-excursion
9953 (goto-char for-kwd)
9954 (current-column))))
9955
9956 (defun js-proper-indentation (parse-status)
9957 "Return the proper indentation for the current line."
9958 (save-excursion
9959 (back-to-indentation)
9960 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9961 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9962 (continued-expr-p (js-continued-expression-p))
9963 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9964 (js-get-multiline-declaration-offset))
9965 0))
9966 (bracket (nth 1 parse-status))
9967 beg)
9968 (cond
9969 ;; indent array comprehension continuation lines specially
9970 ((and bracket
9971 (not (js2-same-line bracket))
9972 (setq beg (js2-indent-in-array-comp parse-status))
9973 (>= (point) (save-excursion
9974 (goto-char beg)
9975 (point-at-bol)))) ; at or after first loop?
9976 (js2-array-comp-indentation parse-status beg))
9977
9978 (ctrl-stmt-indent)
9979
9980 (bracket
9981 (goto-char bracket)
9982 (cond
9983 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9984 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9985 (when (save-excursion (skip-chars-backward " \t)")
9986 (looking-at ")"))
9987 (backward-list))
9988 (if (and (nth 1 p)
9989 (not js2-consistent-level-indent-inner-bracket-p))
9990 (progn (goto-char (1+ (nth 1 p)))
9991 (skip-chars-forward " \t"))
9992 (back-to-indentation))
9993 (cond (same-indent-p
9994 (current-column))
9995 (continued-expr-p
9996 (+ (current-column) (* 2 js2-basic-offset)))
9997 ((> multiline-declaration-offset 0)
9998 (+ (current-column) js2-basic-offset multiline-declaration-offset))
9999 (t
10000 (+ (current-column) js2-basic-offset)))))
10001 (t
10002 (unless same-indent-p
10003 (forward-char)
10004 (skip-chars-forward " \t"))
10005 (current-column))))
10006
10007 (continued-expr-p js2-basic-offset)
10008
10009 ((> multiline-declaration-offset 0)
10010 (+ multiline-declaration-offset))
10011
10012 (t 0)))))
10013
10014 (defun js2-lineup-comment (parse-status)
10015 "Indent a multi-line block comment continuation line."
10016 (let* ((beg (nth 8 parse-status))
10017 (first-line (js2-same-line beg))
10018 (offset (save-excursion
10019 (goto-char beg)
10020 (if (looking-at "/\\*")
10021 (+ 1 (current-column))
10022 0))))
10023 (unless first-line
10024 (indent-line-to offset))))
10025
10026 (defun js2-backward-sws ()
10027 "Move backward through whitespace and comments."
10028 (interactive)
10029 (while (forward-comment -1)))
10030
10031 (defun js2-forward-sws ()
10032 "Move forward through whitespace and comments."
10033 (interactive)
10034 (while (forward-comment 1)))
10035
10036 (defsubst js2-current-indent (&optional pos)
10037 "Return column of indentation on current line.
10038 If POS is non-nil, go to that point and return indentation for that line."
10039 (save-excursion
10040 (if pos
10041 (goto-char pos))
10042 (back-to-indentation)
10043 (current-column)))
10044
10045 (defsubst js2-arglist-close ()
10046 "Return non-nil if we're on a line beginning with a close-paren/brace."
10047 (save-match-data
10048 (save-excursion
10049 (goto-char (point-at-bol))
10050 (js2-forward-sws)
10051 (looking-at "[])}]"))))
10052
10053 (defsubst js2-indent-looks-like-label-p ()
10054 (goto-char (point-at-bol))
10055 (js2-forward-sws)
10056 (looking-at (concat js2-mode-identifier-re ":")))
10057
10058 (defun js2-indent-in-objlit-p (parse-status)
10059 "Return non-nil if this looks like an object-literal entry."
10060 (let ((start (nth 1 parse-status)))
10061 (and
10062 start
10063 (save-excursion
10064 (and (zerop (forward-line -1))
10065 (not (< (point) start)) ; crossed a {} boundary
10066 (js2-indent-looks-like-label-p)))
10067 (save-excursion
10068 (js2-indent-looks-like-label-p)))))
10069
10070 ;; if prev line looks like foobar({ then we're passing an object
10071 ;; literal to a function call, and people pretty much always want to
10072 ;; de-dent back to the previous line, so move the 'basic-offset'
10073 ;; position to the front.
10074 (defsubst js2-indent-objlit-arg-p (parse-status)
10075 (save-excursion
10076 (back-to-indentation)
10077 (js2-backward-sws)
10078 (and (eq (1- (point)) (nth 1 parse-status))
10079 (eq (char-before) ?{)
10080 (progn
10081 (forward-char -1)
10082 (skip-chars-backward " \t")
10083 (eq (char-before) ?\()))))
10084
10085 (defsubst js2-indent-case-block-p ()
10086 (save-excursion
10087 (back-to-indentation)
10088 (js2-backward-sws)
10089 (goto-char (point-at-bol))
10090 (skip-chars-forward " \t")
10091 (save-match-data
10092 (looking-at "case\\s-.+:"))))
10093
10094 (defsubst js2-syntax-bol ()
10095 "Return the point at the first non-whitespace char on the line.
10096 Returns `point-at-bol' if the line is empty."
10097 (save-excursion
10098 (beginning-of-line)
10099 (skip-chars-forward " \t")
10100 (point)))
10101
10102 (defun js2-bounce-indent (normal-col parse-status)
10103 "Cycle among alternate computed indentation positions.
10104 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10105 of the buffer to the current point. NORMAL-COL is the indentation
10106 column computed by the heuristic guesser based on current paren,
10107 bracket, brace and statement nesting."
10108 (let ((cur-indent (js2-current-indent))
10109 (old-buffer-undo-list buffer-undo-list)
10110 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10111 (current-line (save-excursion
10112 (forward-line 0) ; move to bol
10113 (1+ (count-lines (point-min) (point)))))
10114 positions
10115 pos
10116 anchor
10117 arglist-cont
10118 same-indent
10119 prev-line-col
10120 basic-offset
10121 computed-pos)
10122 ;; temporarily don't record undo info, if user requested this
10123 (if js2-mode-indent-inhibit-undo
10124 (setq buffer-undo-list t))
10125 (unwind-protect
10126 (progn
10127 ;; first likely point: indent from beginning of previous code line
10128 (push (setq basic-offset
10129 (+ (save-excursion
10130 (back-to-indentation)
10131 (js2-backward-sws)
10132 (back-to-indentation)
10133 (setq prev-line-col (current-column)))
10134 js2-basic-offset))
10135 positions)
10136
10137 ;; (first + epsilon) likely point: indent 2x from beginning of
10138 ;; previous code line. Some companies like this approach. Ahem.
10139 ;; Seriously, though -- 4-space indent for expression continuation
10140 ;; lines isn't a bad idea. We should eventually implement it
10141 ;; that way.
10142 (push (setq basic-offset
10143 (+ (save-excursion
10144 (back-to-indentation)
10145 (js2-backward-sws)
10146 (back-to-indentation)
10147 (setq prev-line-col (current-column)))
10148 (* 2 js2-basic-offset)))
10149 positions)
10150
10151 ;; second likely point: indent from assign-expr RHS. This
10152 ;; is just a crude guess based on finding " = " on the previous
10153 ;; line containing actual code.
10154 (setq pos (save-excursion
10155 (save-match-data
10156 (forward-line -1)
10157 (goto-char (point-at-bol))
10158 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10159 (point-at-eol) t)
10160 (goto-char (match-end 1))
10161 (skip-chars-forward " \t\r\n")
10162 (current-column)))))
10163 (when pos
10164 (incf pos js2-basic-offset)
10165 (unless (member pos positions)
10166 (push pos positions)))
10167
10168 ;; third likely point: same indent as previous line of code.
10169 ;; Make it the first likely point if we're not on an
10170 ;; arglist-close line and previous line ends in a comma, or
10171 ;; both this line and prev line look like object-literal
10172 ;; elements.
10173 (setq pos (save-excursion
10174 (goto-char (point-at-bol))
10175 (js2-backward-sws)
10176 (back-to-indentation)
10177 (prog1
10178 (current-column)
10179 ;; while we're here, look for trailing comma
10180 (if (save-excursion
10181 (goto-char (point-at-eol))
10182 (js2-backward-sws)
10183 (eq (char-before) ?,))
10184 (setq arglist-cont (1- (point)))))))
10185 (when pos
10186 (if (and (or arglist-cont
10187 (js2-indent-in-objlit-p parse-status))
10188 (not (js2-arglist-close)))
10189 (setq same-indent pos))
10190 (unless (member pos positions)
10191 (push pos positions)))
10192
10193 ;; fourth likely point: first preceding code with less indentation
10194 ;; than the immediately preceding code line.
10195 (setq pos (save-excursion
10196 (js2-backward-sws)
10197 (back-to-indentation)
10198 (setq anchor (current-column))
10199 (while (and (zerop (forward-line -1))
10200 (>= (progn
10201 (back-to-indentation)
10202 (current-column))
10203 anchor)))
10204 (setq pos (current-column))))
10205 (unless (member pos positions)
10206 (push pos positions))
10207
10208 ;; put nesting-heuristic position first in list, sort rest
10209 (setq positions (nreverse (sort positions '<)))
10210 (setq positions (cons normal-col (delete normal-col positions)))
10211
10212 ;; comma-list continuation lines: prev line indent takes precedence
10213 (if same-indent
10214 (setq positions
10215 (cons same-indent
10216 (sort (delete same-indent positions) '<))))
10217
10218 ;; common special cases where we want to indent in from previous line
10219 (if (or (js2-indent-case-block-p)
10220 (js2-indent-objlit-arg-p parse-status))
10221 (setq positions
10222 (cons basic-offset
10223 (delete basic-offset positions))))
10224
10225 ;; record whether we're already sitting on one of the alternatives
10226 (setq pos (member cur-indent positions))
10227 (cond
10228 ;; case 0: we're one one of the alternatives and this is the
10229 ;; first time they've pressed TAB on this line (best-guess).
10230 ((and js2-mode-indent-ignore-first-tab
10231 pos
10232 ;; first time pressing TAB on this line?
10233 (not (eq js2-mode-last-indented-line current-line)))
10234 ;; do nothing
10235 (setq computed-pos nil))
10236 ;; case 1: only one computed position => use it
10237 ((null (cdr positions))
10238 (setq computed-pos 0))
10239 ;; case 2: not on any of the computed spots => use main spot
10240 ((not pos)
10241 (setq computed-pos 0))
10242 ;; case 3: on last position: cycle to first position
10243 ((null (cdr pos))
10244 (setq computed-pos 0))
10245 ;; case 4: on intermediate position: cycle to next position
10246 (t
10247 (setq computed-pos (js2-position (second pos) positions))))
10248
10249 ;; see if any hooks want to indent; otherwise we do it
10250 (loop with result = nil
10251 for hook in js2-indent-hook
10252 while (null result)
10253 do
10254 (setq result (funcall hook positions computed-pos))
10255 finally do
10256 (unless (or result (null computed-pos))
10257 (indent-line-to (nth computed-pos positions)))))
10258
10259 ;; finally
10260 (if js2-mode-indent-inhibit-undo
10261 (setq buffer-undo-list old-buffer-undo-list))
10262 ;; see commentary for `js2-mode-last-indented-line'
10263 (setq js2-mode-last-indented-line current-line))))
10264
10265 (defsubst js2-1-line-comment-continuation-p ()
10266 "Return t if we're in a 1-line comment continuation.
10267 If so, we don't ever want to use bounce-indent."
10268 (save-excursion
10269 (save-match-data
10270 (and (progn
10271 (forward-line 0)
10272 (looking-at "\\s-*//"))
10273 (progn
10274 (forward-line -1)
10275 (forward-line 0)
10276 (when (looking-at "\\s-*$")
10277 (js2-backward-sws)
10278 (forward-line 0))
10279 (looking-at "\\s-*//"))))))
10280
10281 (defun js2-indent-line ()
10282 "Indent the current line as JavaScript source text."
10283 (interactive)
10284 (when js2-use-ast-for-indentation-p
10285 (js2-reparse))
10286 (let (parse-status
10287 current-indent
10288 offset
10289 indent-col
10290 moved
10291 ;; don't whine about errors/warnings when we're indenting.
10292 ;; This has to be set before calling parse-partial-sexp below.
10293 (inhibit-point-motion-hooks t))
10294 (setq parse-status (save-excursion
10295 (parse-partial-sexp (point-min)
10296 (point-at-bol)))
10297 offset (- (point) (save-excursion
10298 (back-to-indentation)
10299 (setq current-indent (current-column))
10300 (point))))
10301 (js2-with-underscore-as-word-syntax
10302 (if (nth 4 parse-status)
10303 (js2-lineup-comment parse-status)
10304 (setq indent-col (js-proper-indentation parse-status))
10305 ;; see comments below about js2-mode-last-indented-line
10306 (when
10307 (cond
10308 ;; bounce-indenting is disabled during electric-key indent.
10309 ;; It doesn't work well on first line of buffer.
10310 ((and js2-bounce-indent-p
10311 (not (js2-same-line (point-min)))
10312 (not (js2-1-line-comment-continuation-p)))
10313 (js2-bounce-indent indent-col parse-status)
10314 (setq moved t))
10315 ;; just indent to the guesser's likely spot
10316 ((/= current-indent indent-col)
10317 (indent-line-to indent-col)
10318 (setq moved t)))
10319 (when (and moved (plusp offset))
10320 (forward-char offset)))))))
10321
10322 (defun js2-indent-region (start end)
10323 "Indent the region, but don't use bounce indenting."
10324 (let ((js2-bounce-indent-p nil)
10325 (indent-region-function nil))
10326 (indent-region start end nil))) ; nil for byte-compiler
10327
10328 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10329
10330 ;;;###autoload
10331 (defun js2-mode ()
10332 "Major mode for editing JavaScript code."
10333 (interactive)
10334 (kill-all-local-variables)
10335 (set-syntax-table js2-mode-syntax-table)
10336 (use-local-map js2-mode-map)
10337 (setq major-mode 'js2-mode
10338 mode-name "JavaScript-IDE"
10339 comment-start "//" ; used by comment-region; don't change it
10340 comment-end "")
10341 (setq local-abbrev-table js2-mode-abbrev-table)
10342 (set (make-local-variable 'max-lisp-eval-depth)
10343 (max max-lisp-eval-depth 3000))
10344 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10345 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10346
10347 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10348 ;; on most platforms other than the one I originally wrote it on. So it's
10349 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10350 ;; with our binding of the RET key inside comments: short lines stay short.
10351 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10352
10353 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10354 (set (make-local-variable 'next-error-function) #'js2-next-error)
10355 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10356 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10357 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10358 ;; for characters inside regexp literals.
10359 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10360 ;; this is necessary to make `show-paren-function' work properly
10361 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10362 ;; needed for M-x rgrep, among other things
10363 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10364
10365 ;; some variables needed by cc-engine for paragraph-fill, etc.
10366 (setq c-buffer-is-cc-mode t
10367 c-comment-prefix-regexp js2-comment-prefix-regexp
10368 c-comment-start-regexp "/[*/]\\|\\s|"
10369 c-paragraph-start js2-paragraph-start
10370 c-paragraph-separate "$"
10371 comment-start-skip js2-comment-start-skip
10372 c-syntactic-ws-start js2-syntactic-ws-start
10373 c-syntactic-ws-end js2-syntactic-ws-end
10374 c-syntactic-eol js2-syntactic-eol)
10375
10376 (setq js2-default-externs
10377 (append js2-ecma-262-externs
10378 (if js2-include-browser-externs
10379 js2-browser-externs)
10380 (if js2-include-gears-externs
10381 js2-gears-externs)
10382 (if js2-include-rhino-externs
10383 js2-rhino-externs)))
10384
10385 ;; We do our own syntax highlighting based on the parse tree.
10386 ;; However, we want minor modes that add keywords to highlight properly
10387 ;; (examples: doxymacs, column-marker). We do this by not letting
10388 ;; font-lock unfontify anything, and telling it to fontify after we
10389 ;; re-parse and re-highlight the buffer. (We currently don't do any
10390 ;; work with regions other than the whole buffer.)
10391 (dolist (var '(font-lock-unfontify-buffer-function
10392 font-lock-unfontify-region-function))
10393 (set (make-local-variable var) (lambda (&rest args) t)))
10394
10395 ;; Don't let font-lock do syntactic (string/comment) fontification.
10396 (set (make-local-variable #'font-lock-syntactic-face-function)
10397 (lambda (state) nil))
10398
10399 ;; Experiment: make reparse-delay longer for longer files.
10400 (if (plusp js2-dynamic-idle-timer-adjust)
10401 (setq js2-idle-timer-delay
10402 (* js2-idle-timer-delay
10403 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10404
10405 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10406 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10407 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10408 (imenu-add-to-menubar (concat "IM-" mode-name))
10409 (when js2-mirror-mode
10410 (js2-enter-mirror-mode))
10411 (add-to-invisibility-spec '(js2-outline . t))
10412 (set (make-local-variable 'line-move-ignore-invisible) t)
10413 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10414 (setq js2-mode-functions-hidden nil
10415 js2-mode-comments-hidden nil
10416 js2-mode-buffer-dirty-p t
10417 js2-mode-parsing nil)
10418 (js2-reparse)
10419 (run-hooks 'js2-mode-hook))
10420
10421 (defun js2-mode-exit ()
10422 "Exit `js2-mode' and clean up."
10423 (interactive)
10424 (when js2-mode-node-overlay
10425 (delete-overlay js2-mode-node-overlay)
10426 (setq js2-mode-node-overlay nil))
10427 (js2-remove-overlays)
10428 (setq js2-mode-ast nil)
10429 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10430 (remove-from-invisibility-spec '(js2-outline . t))
10431 (js2-mode-show-all)
10432 (js2-with-unmodifying-text-property-changes
10433 (js2-clear-face (point-min) (point-max))))
10434
10435 (defun js2-before-save ()
10436 "Clean up whitespace before saving file.
10437 You can disable this by customizing `js2-cleanup-whitespace'."
10438 (when js2-cleanup-whitespace
10439 (let ((col (current-column)))
10440 (delete-trailing-whitespace)
10441 ;; don't change trailing whitespace on current line
10442 (unless (eq (current-column) col)
10443 (indent-to col)))))
10444
10445 (defsubst js2-mode-reset-timer ()
10446 "Cancel any existing parse timer and schedule a new one."
10447 (if js2-mode-parse-timer
10448 (cancel-timer js2-mode-parse-timer))
10449 (setq js2-mode-parsing nil)
10450 (setq js2-mode-parse-timer
10451 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10452
10453 (defun js2-mode-edit (beg end len)
10454 "Schedule a new parse after buffer is edited.
10455 Buffer edit spans from BEG to END and is of length LEN.
10456 Also clears the `js2-magic' bit on autoinserted parens/brackets
10457 if the edit occurred on a line different from the magic paren."
10458 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10459 (line (if magic-pos (line-number-at-pos magic-pos))))
10460 (and line
10461 (or (/= (line-number-at-pos beg) line)
10462 (and (> 0 len)
10463 (/= (line-number-at-pos end) line)))
10464 (js2-mode-mundanify-parens)))
10465 (setq js2-mode-buffer-dirty-p t)
10466 (js2-mode-hide-overlay)
10467 (js2-mode-reset-timer))
10468
10469 (defun js2-mode-run-font-lock ()
10470 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10471 This is intended to allow modes that install their own font-lock keywords
10472 to work with js2-mode. In practice it never seems to work for long.
10473 Hopefully the Emacs maintainers can help figure out a way to make it work."
10474 (when (and (boundp 'font-lock-keywords)
10475 font-lock-keywords
10476 (boundp 'font-lock-mode)
10477 font-lock-mode)
10478 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10479 ;; play nicely with js2-mode. They go out of their way to fail to
10480 ;; provide any option for saying "look, fontify the farging buffer
10481 ;; with just the keywords already". Argh.
10482 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10483 (let (font-lock-verbose)
10484 (font-lock-fontify-buffer))))
10485
10486 (defun js2-reparse (&optional force)
10487 "Re-parse current buffer after user finishes some data entry.
10488 If we get any user input while parsing, including cursor motion,
10489 we discard the parse and reschedule it. If FORCE is nil, then the
10490 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10491 (let (time
10492 interrupted-p
10493 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10494 (unless js2-mode-parsing
10495 (setq js2-mode-parsing t)
10496 (unwind-protect
10497 (when (or js2-mode-buffer-dirty-p force)
10498 (js2-remove-overlays)
10499 (js2-with-unmodifying-text-property-changes
10500 (remove-text-properties (point-min) (point-max) '(syntax-table))
10501 (setq js2-mode-buffer-dirty-p nil
10502 js2-mode-fontifications nil
10503 js2-mode-deferred-properties nil
10504 js2-additional-externs nil)
10505 (if js2-mode-verbose-parse-p
10506 (message "parsing..."))
10507 (setq time
10508 (js2-time
10509 (setq interrupted-p
10510 (catch 'interrupted
10511 (setq js2-mode-ast (js2-parse))
10512 (when (plusp js2-highlight-level)
10513 (js2-mode-fontify-regions))
10514 (js2-mode-remove-suppressed-warnings)
10515 (js2-mode-show-warnings)
10516 (js2-mode-show-errors)
10517 (js2-mode-run-font-lock) ; note: doesn't work
10518 (js2-mode-highlight-magic-parens)
10519 (if (>= js2-highlight-level 1)
10520 (js2-highlight-jsdoc js2-mode-ast))
10521 nil))))
10522 (if interrupted-p
10523 (progn
10524 ;; unfinished parse => try again
10525 (setq js2-mode-buffer-dirty-p t)
10526 (js2-mode-reset-timer))
10527 (if js2-mode-verbose-parse-p
10528 (message "Parse time: %s" time)))))
10529 (setq js2-mode-parsing nil)
10530 (unless interrupted-p
10531 (setq js2-mode-parse-timer nil))))))
10532
10533 (defun js2-mode-show-node ()
10534 "Debugging aid: highlight selected AST node on mouse click."
10535 (interactive)
10536 (let ((node (js2-node-at-point))
10537 beg
10538 end)
10539 (when js2-mode-show-overlay
10540 (if (null node)
10541 (message "No node found at location %s" (point))
10542 (setq beg (js2-node-abs-pos node)
10543 end (+ beg (js2-node-len node)))
10544 (if js2-mode-node-overlay
10545 (move-overlay js2-mode-node-overlay beg end)
10546 (setq js2-mode-node-overlay (make-overlay beg end))
10547 (overlay-put js2-mode-node-overlay 'face 'highlight))
10548 (js2-with-unmodifying-text-property-changes
10549 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10550 (message "%s, parent: %s"
10551 (js2-node-short-name node)
10552 (if (js2-node-parent node)
10553 (js2-node-short-name (js2-node-parent node))
10554 "nil"))))))
10555
10556 (defun js2-mode-hide-overlay (&optional p1 p2)
10557 "Remove the debugging overlay when the point moves.
10558 P1 and P2 are the old and new values of point, respectively."
10559 (when js2-mode-node-overlay
10560 (let ((beg (overlay-start js2-mode-node-overlay))
10561 (end (overlay-end js2-mode-node-overlay)))
10562 ;; Sometimes we're called spuriously.
10563 (unless (and p2
10564 (>= p2 beg)
10565 (<= p2 end))
10566 (js2-with-unmodifying-text-property-changes
10567 (remove-text-properties beg end '(point-left nil)))
10568 (delete-overlay js2-mode-node-overlay)
10569 (setq js2-mode-node-overlay nil)))))
10570
10571 (defun js2-mode-reset ()
10572 "Debugging helper: reset everything."
10573 (interactive)
10574 (js2-mode-exit)
10575 (js2-mode))
10576
10577 (defsubst js2-mode-show-warn-or-err (e face)
10578 "Highlight a warning or error E with FACE.
10579 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10580 (let* ((key (first e))
10581 (beg (second e))
10582 (end (+ beg (third e)))
10583 ;; Don't inadvertently go out of bounds.
10584 (beg (max (point-min) (min beg (point-max))))
10585 (end (max (point-min) (min end (point-max))))
10586 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10587 (ovl (make-overlay beg end)))
10588 (overlay-put ovl 'face face)
10589 (overlay-put ovl 'js2-error t)
10590 (put-text-property beg end 'help-echo (js2-get-msg key))
10591 (put-text-property beg end 'point-entered #'js2-echo-error)))
10592
10593 (defun js2-remove-overlays ()
10594 "Remove overlays from buffer that have a `js2-error' property."
10595 (let ((beg (point-min))
10596 (end (point-max)))
10597 (save-excursion
10598 (dolist (o (overlays-in beg end))
10599 (when (overlay-get o 'js2-error)
10600 (delete-overlay o))))))
10601
10602 (defun js2-error-at-point (&optional pos)
10603 "Return non-nil if there's an error overlay at POS.
10604 Defaults to point."
10605 (loop with pos = (or pos (point))
10606 for o in (overlays-at pos)
10607 thereis (overlay-get o 'js2-error)))
10608
10609 (defun js2-mode-fontify-regions ()
10610 "Apply fontifications recorded during parsing."
10611 ;; We defer clearing faces as long as possible to eliminate flashing.
10612 (js2-clear-face (point-min) (point-max))
10613 ;; have to reverse the recorded fontifications so that errors and
10614 ;; warnings overwrite the normal fontifications
10615 (dolist (f (nreverse js2-mode-fontifications))
10616 (put-text-property (first f) (second f) 'face (third f)))
10617 (setq js2-mode-fontifications nil)
10618 (dolist (p js2-mode-deferred-properties)
10619 (apply #'put-text-property p))
10620 (setq js2-mode-deferred-properties nil))
10621
10622 (defun js2-mode-show-errors ()
10623 "Highlight syntax errors."
10624 (when js2-mode-show-parse-errors
10625 (dolist (e (js2-ast-root-errors js2-mode-ast))
10626 (js2-mode-show-warn-or-err e 'js2-error-face))))
10627
10628 (defun js2-mode-remove-suppressed-warnings ()
10629 "Take suppressed warnings out of the AST warnings list.
10630 This ensures that the counts and `next-error' are correct."
10631 (setf (js2-ast-root-warnings js2-mode-ast)
10632 (js2-delete-if
10633 (lambda (e)
10634 (let ((key (caar e)))
10635 (or
10636 (and (not js2-strict-trailing-comma-warning)
10637 (string-match "trailing\\.comma" key))
10638 (and (not js2-strict-cond-assign-warning)
10639 (string= key "msg.equal.as.assign"))
10640 (and js2-missing-semi-one-line-override
10641 (string= key "msg.missing.semi")
10642 (let* ((beg (second e))
10643 (node (js2-node-at-point beg))
10644 (fn (js2-mode-find-parent-fn node))
10645 (body (and fn (js2-function-node-body fn)))
10646 (lc (and body (js2-node-abs-pos body)))
10647 (rc (and lc (+ lc (js2-node-len body)))))
10648 (and fn
10649 (or (null body)
10650 (save-excursion
10651 (goto-char beg)
10652 (and (js2-same-line lc)
10653 (js2-same-line rc))))))))))
10654 (js2-ast-root-warnings js2-mode-ast))))
10655
10656 (defun js2-mode-show-warnings ()
10657 "Highlight strict-mode warnings."
10658 (when js2-mode-show-strict-warnings
10659 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10660 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10661
10662 (defun js2-echo-error (old-point new-point)
10663 "Called by point-motion hooks."
10664 (let ((msg (get-text-property new-point 'help-echo)))
10665 (if msg
10666 (message msg))))
10667
10668 (defalias #'js2-echo-help #'js2-echo-error)
10669
10670 (defun js2-enter-key ()
10671 "Handle user pressing the Enter key."
10672 (interactive)
10673 (let ((parse-status (save-excursion
10674 (parse-partial-sexp (point-min) (point)))))
10675 (cond
10676 ;; check if we're inside a string
10677 ((nth 3 parse-status)
10678 (js2-mode-split-string parse-status))
10679 ;; check if inside a block comment
10680 ((nth 4 parse-status)
10681 (js2-mode-extend-comment))
10682 (t
10683 ;; should probably figure out what the mode-map says we should do
10684 (if js2-indent-on-enter-key
10685 (let ((js2-bounce-indent-p nil))
10686 (js2-indent-line)))
10687 (insert "\n")
10688 (if js2-enter-indents-newline
10689 (let ((js2-bounce-indent-p nil))
10690 (js2-indent-line)))))))
10691
10692 (defun js2-mode-split-string (parse-status)
10693 "Turn a newline in mid-string into a string concatenation.
10694 PARSE-STATUS is as documented in `parse-partial-sexp'."
10695 (let* ((col (current-column))
10696 (quote-char (nth 3 parse-status))
10697 (quote-string (string quote-char))
10698 (string-beg (nth 8 parse-status))
10699 (indent (save-match-data
10700 (or
10701 (save-excursion
10702 (back-to-indentation)
10703 (if (looking-at "\\+")
10704 (current-column)))
10705 (save-excursion
10706 (goto-char string-beg)
10707 (if (looking-back "\\+\\s-+")
10708 (goto-char (match-beginning 0)))
10709 (current-column))))))
10710 (insert quote-char "\n")
10711 (indent-to indent)
10712 (insert "+ " quote-string)
10713 (when (eolp)
10714 (insert quote-string)
10715 (backward-char 1))))
10716
10717 (defun js2-mode-extend-comment ()
10718 "When inside a comment block, add comment prefix."
10719 (let (star single col first-line needs-close)
10720 (save-excursion
10721 (back-to-indentation)
10722 (cond
10723 ((looking-at "\\*[^/]")
10724 (setq star t
10725 col (current-column)))
10726 ((looking-at "/\\*")
10727 (setq star t
10728 first-line t
10729 col (1+ (current-column))))
10730 ((looking-at "//")
10731 (setq single t
10732 col (current-column)))))
10733 ;; Heuristic for whether we need to close the comment:
10734 ;; if we've got a parse error here, assume it's an unterminated
10735 ;; comment.
10736 (setq needs-close
10737 (or
10738 (eq (get-text-property (1- (point)) 'point-entered)
10739 'js2-echo-error)
10740 ;; The heuristic above doesn't work well when we're
10741 ;; creating a comment and there's another one downstream,
10742 ;; as our parser thinks this one ends at the end of the
10743 ;; next one. (You can have a /* inside a js block comment.)
10744 ;; So just close it if the next non-ws char isn't a *.
10745 (and first-line
10746 (eolp)
10747 (save-excursion
10748 (skip-chars-forward " \t\r\n")
10749 (not (eq (char-after) ?*))))))
10750 (insert "\n")
10751 (cond
10752 (star
10753 (indent-to col)
10754 (insert "* ")
10755 (if (and first-line needs-close)
10756 (save-excursion
10757 (insert "\n")
10758 (indent-to col)
10759 (insert "*/"))))
10760 (single
10761 (when (save-excursion
10762 (and (zerop (forward-line 1))
10763 (looking-at "\\s-*//")))
10764 (indent-to col)
10765 (insert "// "))))))
10766
10767 (defun js2-beginning-of-line ()
10768 "Toggles point between bol and first non-whitespace char in line.
10769 Also moves past comment delimiters when inside comments."
10770 (interactive)
10771 (let (node beg)
10772 (cond
10773 ((bolp)
10774 (back-to-indentation))
10775 ((looking-at "//")
10776 (skip-chars-forward "/ \t"))
10777 ((and (eq (char-after) ?*)
10778 (setq node (js2-comment-at-point))
10779 (memq (js2-comment-node-format node) '(jsdoc block))
10780 (save-excursion
10781 (skip-chars-backward " \t")
10782 (bolp)))
10783 (skip-chars-forward "\* \t"))
10784 (t
10785 (goto-char (point-at-bol))))))
10786
10787 (defun js2-end-of-line ()
10788 "Toggles point between eol and last non-whitespace char in line."
10789 (interactive)
10790 (if (eolp)
10791 (skip-chars-backward " \t")
10792 (goto-char (point-at-eol))))
10793
10794 (defun js2-enter-mirror-mode()
10795 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10796 on insertion."
10797 (interactive)
10798 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10799 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10800 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10801 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10802 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10803 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10804 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10805 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10806
10807 (defun js2-leave-mirror-mode()
10808 "Turns off mirror mode."
10809 (interactive)
10810 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10811 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10812
10813 (defsubst js2-mode-inside-string ()
10814 "Return non-nil if inside a string.
10815 Actually returns the quote character that begins the string."
10816 (let ((parse-state (save-excursion
10817 (parse-partial-sexp (point-min) (point)))))
10818 (nth 3 parse-state)))
10819
10820 (defsubst js2-mode-inside-comment-or-string ()
10821 "Return non-nil if inside a comment or string."
10822 (or
10823 (let ((comment-start
10824 (save-excursion
10825 (goto-char (point-at-bol))
10826 (if (re-search-forward "//" (point-at-eol) t)
10827 (match-beginning 0)))))
10828 (and comment-start
10829 (<= comment-start (point))))
10830 (let ((parse-state (save-excursion
10831 (parse-partial-sexp (point-min) (point)))))
10832 (or (nth 3 parse-state)
10833 (nth 4 parse-state)))))
10834
10835 (defsubst js2-make-magic-delimiter (delim &optional pos)
10836 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10837 Sets value of `js2-magic' text property to line number at POS."
10838 (propertize delim
10839 'js2-magic (line-number-at-pos pos)
10840 'face 'js2-magic-paren-face))
10841
10842 (defun js2-mode-match-delimiter (open close)
10843 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10844 The rule we use, which as far as we can tell is how Eclipse works,
10845 is that we insert the match if we're not in a comment or string,
10846 and the next non-whitespace character is either punctuation or
10847 occurs on another line."
10848 (insert open)
10849 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10850 (not (js2-mode-inside-comment-or-string)))
10851 (save-excursion
10852 (insert (js2-make-magic-delimiter close)))
10853 (when js2-auto-indent-p
10854 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10855 (js2-indent-line)))))
10856
10857 (defun js2-mode-match-bracket ()
10858 "Insert matching bracket."
10859 (interactive)
10860 (js2-mode-match-delimiter "[" "]"))
10861
10862 (defun js2-mode-match-paren ()
10863 "Insert matching paren unless already inserted."
10864 (interactive)
10865 (js2-mode-match-delimiter "(" ")"))
10866
10867 (defun js2-mode-match-curly (arg)
10868 "Insert matching curly-brace.
10869 With prefix arg, no formatting or indentation will occur -- the close-brace
10870 is simply inserted directly at the point."
10871 (interactive "p")
10872 (let (try-pos)
10873 (cond
10874 (current-prefix-arg
10875 (js2-mode-match-delimiter "{" "}"))
10876 ((and js2-auto-insert-catch-block
10877 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10878 (point-at-bol))
10879 (match-beginning 1))))
10880 (js2-insert-catch-skel try-pos))
10881 (t
10882 ;; Otherwise try to do something smarter.
10883 (insert "{")
10884 (unless (or (not (looking-at "\\s-*$"))
10885 (save-excursion
10886 (skip-chars-forward " \t\r\n")
10887 (and (looking-at "}")
10888 (js2-error-at-point)))
10889 (js2-mode-inside-comment-or-string))
10890 (undo-boundary)
10891 ;; absolutely mystifying bug: when inserting the next "\n",
10892 ;; the buffer-undo-list is given two new entries: the inserted range,
10893 ;; and the incorrect position of the point. It's recorded incorrectly
10894 ;; as being before the opening "{", not after it. But it's recorded
10895 ;; as the correct value if you're debugging `js2-mode-match-curly'
10896 ;; in edebug. I have no idea why it's doing this, but incrementing
10897 ;; the inserted position fixes the problem, so that the undo takes us
10898 ;; back to just after the user-inserted "{".
10899 (insert "\n")
10900 (ignore-errors
10901 (incf (cadr buffer-undo-list)))
10902 (js2-indent-line)
10903 (save-excursion
10904 (insert "\n}")
10905 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10906 (js2-indent-line))))))))
10907
10908 (defun js2-insert-catch-skel (try-pos)
10909 "Complete a try/catch block after inserting a { following a try keyword.
10910 Rationale is that a try always needs a catch or a finally, and the catch is
10911 the more likely of the two.
10912
10913 TRY-POS is the buffer position of the try keyword. The open-curly should
10914 already have been inserted."
10915 (insert "{")
10916 (let ((try-col (save-excursion
10917 (goto-char try-pos)
10918 (current-column))))
10919 (insert "\n")
10920 (undo-boundary)
10921 (js2-indent-line) ;; indent the blank line where cursor will end up
10922 (save-excursion
10923 (insert "\n")
10924 (indent-to try-col)
10925 (insert "} catch (x) {\n\n")
10926 (indent-to try-col)
10927 (insert "}"))))
10928
10929 (defun js2-mode-highlight-magic-parens ()
10930 "Re-highlight magic parens after parsing nukes the 'face prop."
10931 (let ((beg (point-min))
10932 end)
10933 (while (setq beg (next-single-property-change beg 'js2-magic))
10934 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10935 (if (get-text-property beg 'js2-magic)
10936 (js2-with-unmodifying-text-property-changes
10937 (put-text-property beg (or end (1+ beg))
10938 'face 'js2-magic-paren-face))))))
10939
10940 (defun js2-mode-mundanify-parens ()
10941 "Clear all magic parens and brackets."
10942 (let ((beg (point-min))
10943 end)
10944 (while (setq beg (next-single-property-change beg 'js2-magic))
10945 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10946 (remove-text-properties beg (or end (1+ beg))
10947 '(js2-magic face)))))
10948
10949 (defsubst js2-match-quote (quote-string)
10950 (let ((start-quote (js2-mode-inside-string)))
10951 (cond
10952 ;; inside a comment - don't do quote-matching, since we can't
10953 ;; reliably figure out if we're in a string inside the comment
10954 ((js2-comment-at-point)
10955 (insert quote-string))
10956 ((not start-quote)
10957 ;; not in string => insert matched quotes
10958 (insert quote-string)
10959 ;; exception: if we're just before a word, don't double it.
10960 (unless (looking-at "[^ \t\r\n]")
10961 (save-excursion
10962 (insert quote-string))))
10963 ((looking-at quote-string)
10964 (if (looking-back "[^\\]\\\\")
10965 (insert quote-string)
10966 (forward-char 1)))
10967 ((and js2-mode-escape-quotes
10968 (save-excursion
10969 (save-match-data
10970 (re-search-forward quote-string (point-at-eol) t))))
10971 ;; inside terminated string, escape quote (unless already escaped)
10972 (insert (if (looking-back "[^\\]\\\\")
10973 quote-string
10974 (concat "\\" quote-string))))
10975 (t
10976 (insert quote-string))))) ; else terminate the string
10977
10978 (defun js2-mode-match-single-quote ()
10979 "Insert matching single-quote."
10980 (interactive)
10981 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10982 ;; don't match inside comments, since apostrophe is more common
10983 (if (nth 4 parse-status)
10984 (insert "'")
10985 (js2-match-quote "'"))))
10986
10987 (defun js2-mode-match-double-quote ()
10988 "Insert matching double-quote."
10989 (interactive)
10990 (js2-match-quote "\""))
10991
10992 ;; Eclipse works as follows:
10993 ;; * type an open-paren and it auto-inserts close-paren
10994 ;; - auto-inserted paren gets a green bracket
10995 ;; - green bracket means typing close-paren there will skip it
10996 ;; * if you insert any text on a different line, it turns off
10997 (defun js2-mode-magic-close-paren ()
10998 "Skip over close-paren rather than inserting, where appropriate."
10999 (interactive)
11000 (let* ((here (point))
11001 (parse-status (parse-partial-sexp (point-min) here))
11002 (open-pos (nth 1 parse-status))
11003 (close last-input-event)
11004 (open (cond
11005 ((eq close ?\))
11006 ?\()
11007 ((eq close ?\])
11008 ?\[)
11009 ((eq close ?})
11010 ?{)
11011 (t nil))))
11012 (if (and (eq (char-after) close)
11013 (eq open (char-after open-pos))
11014 (js2-same-line open-pos)
11015 (get-text-property here 'js2-magic))
11016 (progn
11017 (remove-text-properties here (1+ here) '(js2-magic face))
11018 (forward-char 1))
11019 (insert-char close 1))
11020 (blink-matching-open)))
11021
11022 (defun js2-mode-wait-for-parse (callback)
11023 "Invoke CALLBACK when parsing is finished.
11024 If parsing is already finished, calls CALLBACK immediately."
11025 (if (not js2-mode-buffer-dirty-p)
11026 (funcall callback)
11027 (push callback js2-mode-pending-parse-callbacks)
11028 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11029
11030 (defun js2-mode-parse-finished ()
11031 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11032 ;; We can't let errors propagate up, since it prevents the
11033 ;; `js2-parse' method from completing normally and returning
11034 ;; the ast, which makes things mysteriously not work right.
11035 (unwind-protect
11036 (dolist (cb js2-mode-pending-parse-callbacks)
11037 (condition-case err
11038 (funcall cb)
11039 (error (message "%s" err))))
11040 (setq js2-mode-pending-parse-callbacks nil)))
11041
11042 (defun js2-mode-flag-region (from to flag)
11043 "Hide or show text from FROM to TO, according to FLAG.
11044 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11045 Returns the created overlay if FLAG is non-nil."
11046 (remove-overlays from to 'invisible 'js2-outline)
11047 (when flag
11048 (let ((o (make-overlay from to)))
11049 (overlay-put o 'invisible 'js2-outline)
11050 (overlay-put o 'isearch-open-invisible
11051 'js2-isearch-open-invisible)
11052 o)))
11053
11054 ;; Function to be set as an outline-isearch-open-invisible' property
11055 ;; to the overlay that makes the outline invisible (see
11056 ;; `js2-mode-flag-region').
11057 (defun js2-isearch-open-invisible (overlay)
11058 ;; We rely on the fact that isearch places point on the matched text.
11059 (js2-mode-show-element))
11060
11061 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11062 "Return cons cell of bounds of folding overlay at POS.
11063 Returns nil if not found."
11064 (let ((overlays (overlays-at (or pos (point))))
11065 o)
11066 (while (and overlays
11067 (not o))
11068 (if (overlay-get (car overlays) 'invisible)
11069 (setq o (car overlays))
11070 (setq overlays (cdr overlays))))
11071 (if o
11072 (cons (overlay-start o) (overlay-end o)))))
11073
11074 (defun js2-mode-function-at-point (&optional pos)
11075 "Return the innermost function node enclosing current point.
11076 Returns nil if point is not in a function."
11077 (let ((node (js2-node-at-point pos)))
11078 (while (and node (not (js2-function-node-p node)))
11079 (setq node (js2-node-parent node)))
11080 (if (js2-function-node-p node)
11081 node)))
11082
11083 (defun js2-mode-toggle-element ()
11084 "Hide or show the foldable element at the point."
11085 (interactive)
11086 (let (comment fn pos)
11087 (save-excursion
11088 (save-match-data
11089 (cond
11090 ;; /* ... */ comment?
11091 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11092 (if (js2-mode-invisible-overlay-bounds
11093 (setq pos (+ 3 (js2-node-abs-pos comment))))
11094 (progn
11095 (goto-char pos)
11096 (js2-mode-show-element))
11097 (js2-mode-hide-element)))
11098 ;; //-comment?
11099 ((save-excursion
11100 (back-to-indentation)
11101 (looking-at js2-mode-//-comment-re))
11102 (js2-mode-toggle-//-comment))
11103 ;; function?
11104 ((setq fn (js2-mode-function-at-point))
11105 (setq pos (and (js2-function-node-body fn)
11106 (js2-node-abs-pos (js2-function-node-body fn))))
11107 (goto-char (1+ pos))
11108 (if (js2-mode-invisible-overlay-bounds)
11109 (js2-mode-show-element)
11110 (js2-mode-hide-element)))
11111 (t
11112 (message "Nothing at point to hide or show")))))))
11113
11114 (defun js2-mode-hide-element ()
11115 "Fold/hide contents of a block, showing ellipses.
11116 Show the hidden text with \\[js2-mode-show-element]."
11117 (interactive)
11118 (if js2-mode-buffer-dirty-p
11119 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11120 (let (node body beg end)
11121 (cond
11122 ((js2-mode-invisible-overlay-bounds)
11123 (message "already hidden"))
11124 (t
11125 (setq node (js2-node-at-point))
11126 (cond
11127 ((js2-block-comment-p node)
11128 (js2-mode-hide-comment node))
11129 (t
11130 (while (and node (not (js2-function-node-p node)))
11131 (setq node (js2-node-parent node)))
11132 (if (and node
11133 (setq body (js2-function-node-body node)))
11134 (progn
11135 (setq beg (js2-node-abs-pos body)
11136 end (+ beg (js2-node-len body)))
11137 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11138 (message "No collapsable element found at point"))))))))
11139
11140 (defun js2-mode-show-element ()
11141 "Show the hidden element at current point."
11142 (interactive)
11143 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11144 (if bounds
11145 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11146 (message "Nothing to un-hide"))))
11147
11148 (defun js2-mode-show-all ()
11149 "Show all of the text in the buffer."
11150 (interactive)
11151 (js2-mode-flag-region (point-min) (point-max) nil))
11152
11153 (defun js2-mode-toggle-hide-functions ()
11154 (interactive)
11155 (if js2-mode-functions-hidden
11156 (js2-mode-show-functions)
11157 (js2-mode-hide-functions)))
11158
11159 (defun js2-mode-hide-functions ()
11160 "Hides all non-nested function bodies in the buffer.
11161 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11162 to open an individual entry."
11163 (interactive)
11164 (if js2-mode-buffer-dirty-p
11165 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11166 (if (null js2-mode-ast)
11167 (message "Oops - parsing failed")
11168 (setq js2-mode-functions-hidden t)
11169 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11170
11171 (defun js2-mode-function-hider (n endp)
11172 (when (not endp)
11173 (let ((tt (js2-node-type n))
11174 body beg end)
11175 (cond
11176 ((and (= tt js2-FUNCTION)
11177 (setq body (js2-function-node-body n)))
11178 (setq beg (js2-node-abs-pos body)
11179 end (+ beg (js2-node-len body)))
11180 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11181 nil) ; don't process children of function
11182 (t
11183 t))))) ; keep processing other AST nodes
11184
11185 (defun js2-mode-show-functions ()
11186 "Un-hide any folded function bodies in the buffer."
11187 (interactive)
11188 (setq js2-mode-functions-hidden nil)
11189 (save-excursion
11190 (goto-char (point-min))
11191 (while (/= (goto-char (next-overlay-change (point)))
11192 (point-max))
11193 (dolist (o (overlays-at (point)))
11194 (when (and (overlay-get o 'invisible)
11195 (not (overlay-get o 'comment)))
11196 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11197
11198 (defun js2-mode-hide-comment (n)
11199 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11200 3 ; /**
11201 2)) ; /*
11202 (beg (+ (js2-node-abs-pos n) head))
11203 (end (- (+ beg (js2-node-len n)) head 2))
11204 (o (js2-mode-flag-region beg end 'hide)))
11205 (overlay-put o 'comment t)))
11206
11207 (defun js2-mode-toggle-hide-comments ()
11208 "Folds all block comments in the buffer.
11209 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11210 to open an individual entry."
11211 (interactive)
11212 (if js2-mode-comments-hidden
11213 (js2-mode-show-comments)
11214 (js2-mode-hide-comments)))
11215
11216 (defun js2-mode-hide-comments ()
11217 (interactive)
11218 (if js2-mode-buffer-dirty-p
11219 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11220 (if (null js2-mode-ast)
11221 (message "Oops - parsing failed")
11222 (setq js2-mode-comments-hidden t)
11223 (dolist (n (js2-ast-root-comments js2-mode-ast))
11224 (let ((format (js2-comment-node-format n)))
11225 (when (js2-block-comment-p n)
11226 (js2-mode-hide-comment n))))
11227 (js2-mode-hide-//-comments)))
11228
11229 (defsubst js2-mode-extend-//-comment (direction)
11230 "Find start or end of a block of similar //-comment lines.
11231 DIRECTION is -1 to look back, 1 to look forward.
11232 INDENT is the indentation level to match.
11233 Returns the end-of-line position of the furthest adjacent
11234 //-comment line with the same indentation as the current line.
11235 If there is no such matching line, returns current end of line."
11236 (let ((pos (point-at-eol))
11237 (indent (current-indentation)))
11238 (save-excursion
11239 (save-match-data
11240 (while (and (zerop (forward-line direction))
11241 (looking-at js2-mode-//-comment-re)
11242 (eq indent (length (match-string 1))))
11243 (setq pos (point-at-eol)))
11244 pos))))
11245
11246 (defun js2-mode-hide-//-comments ()
11247 "Fold adjacent 1-line comments, showing only snippet of first one."
11248 (let (beg end)
11249 (save-excursion
11250 (save-match-data
11251 (goto-char (point-min))
11252 (while (re-search-forward js2-mode-//-comment-re nil t)
11253 (setq beg (point)
11254 end (js2-mode-extend-//-comment 1))
11255 (unless (eq beg end)
11256 (overlay-put (js2-mode-flag-region beg end 'hide)
11257 'comment t))
11258 (goto-char end)
11259 (forward-char 1))))))
11260
11261 (defun js2-mode-toggle-//-comment ()
11262 "Fold or un-fold any multi-line //-comment at point.
11263 Caller should have determined that this line starts with a //-comment."
11264 (let* ((beg (point-at-eol))
11265 (end beg))
11266 (save-excursion
11267 (goto-char end)
11268 (if (js2-mode-invisible-overlay-bounds)
11269 (js2-mode-show-element)
11270 ;; else hide the comment
11271 (setq beg (js2-mode-extend-//-comment -1)
11272 end (js2-mode-extend-//-comment 1))
11273 (unless (eq beg end)
11274 (overlay-put (js2-mode-flag-region beg end 'hide)
11275 'comment t))))))
11276
11277 (defun js2-mode-show-comments ()
11278 "Un-hide any hidden comments, leaving other hidden elements alone."
11279 (interactive)
11280 (setq js2-mode-comments-hidden nil)
11281 (save-excursion
11282 (goto-char (point-min))
11283 (while (/= (goto-char (next-overlay-change (point)))
11284 (point-max))
11285 (dolist (o (overlays-at (point)))
11286 (when (overlay-get o 'comment)
11287 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11288
11289 (defun js2-mode-display-warnings-and-errors ()
11290 "Turn on display of warnings and errors."
11291 (interactive)
11292 (setq js2-mode-show-parse-errors t
11293 js2-mode-show-strict-warnings t)
11294 (js2-reparse 'force))
11295
11296 (defun js2-mode-hide-warnings-and-errors ()
11297 "Turn off display of warnings and errors."
11298 (interactive)
11299 (setq js2-mode-show-parse-errors nil
11300 js2-mode-show-strict-warnings nil)
11301 (js2-reparse 'force))
11302
11303 (defun js2-mode-toggle-warnings-and-errors ()
11304 "Toggle the display of warnings and errors.
11305 Some users don't like having warnings/errors reported while they type."
11306 (interactive)
11307 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11308 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11309 (if (interactive-p)
11310 (message "warnings and errors %s"
11311 (if js2-mode-show-parse-errors
11312 "enabled"
11313 "disabled")))
11314 (js2-reparse 'force))
11315
11316 (defun js2-mode-customize ()
11317 (interactive)
11318 (customize-group 'js2-mode))
11319
11320 (defun js2-mode-forward-sexp (&optional arg)
11321 "Move forward across one statement or balanced expression.
11322 With ARG, do it that many times. Negative arg -N means
11323 move backward across N balanced expressions."
11324 (interactive "p")
11325 (setq arg (or arg 1))
11326 (if js2-mode-buffer-dirty-p
11327 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11328 (let (node end (start (point)))
11329 (cond
11330 ;; backward-sexp
11331 ;; could probably make this better for some cases:
11332 ;; - if in statement block (e.g. function body), go to parent
11333 ;; - infix exprs like (foo in bar) - maybe go to beginning
11334 ;; of infix expr if in the right-side expression?
11335 ((and arg (minusp arg))
11336 (dotimes (i (- arg))
11337 (js2-backward-sws)
11338 (forward-char -1) ; enter the node we backed up to
11339 (setq node (js2-node-at-point (point) t))
11340 (goto-char (if node
11341 (js2-node-abs-pos node)
11342 (point-min)))))
11343 (t
11344 ;; forward-sexp
11345 (js2-forward-sws)
11346 (dotimes (i arg)
11347 (js2-forward-sws)
11348 (setq node (js2-node-at-point (point) t)
11349 end (if node (+ (js2-node-abs-pos node)
11350 (js2-node-len node))))
11351 (goto-char (or end (point-max))))))))
11352
11353 (defun js2-next-error (&optional arg reset)
11354 "Move to next parse error.
11355 Typically invoked via \\[next-error].
11356 ARG is the number of errors, forward or backward, to move.
11357 RESET means start over from the beginning."
11358 (interactive "p")
11359 (if (or (null js2-mode-ast)
11360 (and (null (js2-ast-root-errors js2-mode-ast))
11361 (null (js2-ast-root-warnings js2-mode-ast))))
11362 (message "No errors")
11363 (when reset
11364 (goto-char (point-min)))
11365 (let* ((errs (copy-sequence
11366 (append (js2-ast-root-errors js2-mode-ast)
11367 (js2-ast-root-warnings js2-mode-ast))))
11368 (continue t)
11369 (start (point))
11370 (count (or arg 1))
11371 (backward (minusp count))
11372 (sorter (if backward '> '<))
11373 (stopper (if backward '< '>))
11374 (count (abs count))
11375 all-errs
11376 err)
11377 ;; sort by start position
11378 (setq errs (sort errs (lambda (e1 e2)
11379 (funcall sorter (second e1) (second e2))))
11380 all-errs errs)
11381 ;; find nth error with pos > start
11382 (while (and errs continue)
11383 (when (funcall stopper (cadar errs) start)
11384 (setq err (car errs))
11385 (if (zerop (decf count))
11386 (setq continue nil)))
11387 (setq errs (cdr errs)))
11388 (if err
11389 (goto-char (second err))
11390 ;; wrap around to first error
11391 (goto-char (second (car all-errs)))
11392 ;; if we were already on it, echo msg again
11393 (if (= (point) start)
11394 (js2-echo-error (point) (point)))))))
11395
11396 (defun js2-down-mouse-3 ()
11397 "Make right-click move the point to the click location.
11398 This makes right-click context menu operations a bit more intuitive.
11399 The point will not move if the region is active, however, to avoid
11400 destroying the region selection."
11401 (interactive)
11402 (when (and js2-move-point-on-right-click
11403 (not mark-active))
11404 (let ((e last-input-event))
11405 (ignore-errors
11406 (goto-char (cadadr e))))))
11407
11408 (defun js2-mode-create-imenu-index ()
11409 "Return an alist for `imenu--index-alist'."
11410 ;; This is built up in `js2-parse-record-imenu' during parsing.
11411 (when js2-mode-ast
11412 ;; if we have an ast but no recorder, they're requesting a rescan
11413 (unless js2-imenu-recorder
11414 (js2-reparse 'force))
11415 (prog1
11416 (js2-build-imenu-index)
11417 (setq js2-imenu-recorder nil
11418 js2-imenu-function-map nil))))
11419
11420 (defun js2-mode-find-tag ()
11421 "Replacement for `find-tag-default'.
11422 `find-tag-default' returns a ridiculous answer inside comments."
11423 (let (beg end)
11424 (js2-with-underscore-as-word-syntax
11425 (save-excursion
11426 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11427 (looking-back "[A-Za-z0-9_$]"))
11428 (setq beg (progn (forward-word -1) (point))
11429 end (progn (forward-word 1) (point)))
11430 (setq beg (progn (forward-word 1) (point))
11431 end (progn (forward-word -1) (point))))
11432 (replace-regexp-in-string
11433 "[\"']" ""
11434 (buffer-substring-no-properties beg end))))))
11435
11436 (defun js2-mode-forward-sibling ()
11437 "Move to the end of the sibling following point in parent.
11438 Returns non-nil if successful, or nil if there was no following sibling."
11439 (let* ((node (js2-node-at-point))
11440 (parent (js2-mode-find-enclosing-fn node))
11441 sib)
11442 (when (setq sib (js2-node-find-child-after (point) parent))
11443 (goto-char (+ (js2-node-abs-pos sib)
11444 (js2-node-len sib))))))
11445
11446 (defun js2-mode-backward-sibling ()
11447 "Move to the beginning of the sibling node preceding point in parent.
11448 Parent is defined as the enclosing script or function."
11449 (let* ((node (js2-node-at-point))
11450 (parent (js2-mode-find-enclosing-fn node))
11451 sib)
11452 (when (setq sib (js2-node-find-child-before (point) parent))
11453 (goto-char (js2-node-abs-pos sib)))))
11454
11455 (defun js2-beginning-of-defun ()
11456 "Go to line on which current function starts, and return non-nil.
11457 If we're not in a function, go to beginning of previous script-level element."
11458 (interactive)
11459 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11460 pos sib)
11461 (cond
11462 ((and (js2-function-node-p parent)
11463 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11464 (goto-char pos))
11465 (t
11466 (js2-mode-backward-sibling)))))
11467
11468 (defun js2-end-of-defun ()
11469 "Go to the char after the last position of the current function.
11470 If we're not in a function, skips over the next script-level element."
11471 (interactive)
11472 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11473 (if (not (js2-function-node-p parent))
11474 ;; punt: skip over next script-level element beyond point
11475 (js2-mode-forward-sibling)
11476 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11477 (js2-node-len parent)))))))
11478
11479 (defun js2-mark-defun (&optional allow-extend)
11480 "Put mark at end of this function, point at beginning.
11481 The function marked is the one that contains point.
11482
11483 Interactively, if this command is repeated,
11484 or (in Transient Mark mode) if the mark is active,
11485 it marks the next defun after the ones already marked."
11486 (interactive "p")
11487 (let (extended)
11488 (when (and allow-extend
11489 (or (and (eq last-command this-command) (mark t))
11490 (and transient-mark-mode mark-active)))
11491 (let ((sib (save-excursion
11492 (goto-char (mark))
11493 (if (js2-mode-forward-sibling)
11494 (point))))
11495 node)
11496 (if sib
11497 (progn
11498 (set-mark sib)
11499 (setq extended t))
11500 ;; no more siblings - try extending to enclosing node
11501 (goto-char (mark t)))))
11502 (when (not extended)
11503 (let ((node (js2-node-at-point (point) t)) ; skip comments
11504 ast fn stmt parent beg end)
11505 (when (js2-ast-root-p node)
11506 (setq ast node
11507 node (or (js2-node-find-child-after (point) node)
11508 (js2-node-find-child-before (point) node))))
11509 ;; only mark whole buffer if we can't find any children
11510 (if (null node)
11511 (setq node ast))
11512 (if (js2-function-node-p node)
11513 (setq parent node)
11514 (setq fn (js2-mode-find-enclosing-fn node)
11515 stmt (if (or (null fn)
11516 (js2-ast-root-p fn))
11517 (js2-mode-find-first-stmt node))
11518 parent (or stmt fn)))
11519 (setq beg (js2-node-abs-pos parent)
11520 end (+ beg (js2-node-len parent)))
11521 (push-mark beg)
11522 (goto-char end)
11523 (exchange-point-and-mark)))))
11524
11525 (defun js2-narrow-to-defun ()
11526 "Narrow to the function enclosing point."
11527 (interactive)
11528 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11529 (fn (if (js2-script-node-p node)
11530 node
11531 (js2-mode-find-enclosing-fn node)))
11532 (beg (js2-node-abs-pos fn)))
11533 (unless (js2-ast-root-p fn)
11534 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11535
11536 (provide 'js2-mode)
11537
11538 ;;; js2-mode.el ends here