]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Record proper positions for function nodes in nested object literals
[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-assignments nil
803 "Tracks assignments 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-assignments', 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 assignments to undeclared variables.
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 assign
1139 to 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 higlight assignments to undeclared variables."
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) ; a lisp list of `js2-object-prop-node'
3539
3540 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3541 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3542
3543 (defun js2-visit-object-node (n v)
3544 (dolist (e (js2-object-node-elems n))
3545 (js2-visit-ast e v)))
3546
3547 (defun js2-print-object-node (n i)
3548 (insert (js2-make-pad i) "{")
3549 (js2-print-list (js2-object-node-elems n))
3550 (insert "}"))
3551
3552 (defstruct (js2-object-prop-node
3553 (:include js2-infix-node)
3554 (:constructor nil)
3555 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3556 (pos js2-ts-cursor)
3557 len
3558 left
3559 right
3560 op-pos)))
3561 "AST node for an object literal prop:value entry.
3562 The `left' field is the property: a name node, string node or number node.
3563 The `right' field is a `js2-node' representing the initializer value.")
3564
3565 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3566 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3567
3568 (defun js2-print-object-prop-node (n i)
3569 (insert (js2-make-pad i))
3570 (js2-print-ast (js2-object-prop-node-left n) 0)
3571 (insert ":")
3572 (js2-print-ast (js2-object-prop-node-right n) 0))
3573
3574 (defstruct (js2-getter-setter-node
3575 (:include js2-infix-node)
3576 (:constructor nil)
3577 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3578 (pos js2-ts-cursor)
3579 len
3580 left
3581 right)))
3582 "AST node for a getter/setter property in an object literal.
3583 The `left' field is the `js2-name-node' naming the getter/setter prop.
3584 The `right' field is always an anonymous `js2-function-node' with a node
3585 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3586
3587 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3588 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3589
3590 (defun js2-print-getter-setter (n i)
3591 (let ((pad (js2-make-pad i))
3592 (left (js2-getter-setter-node-left n))
3593 (right (js2-getter-setter-node-right n)))
3594 (insert pad)
3595 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3596 (js2-print-ast left 0)
3597 (js2-print-ast right 0)))
3598
3599 (defstruct (js2-prop-get-node
3600 (:include js2-infix-node)
3601 (:constructor nil)
3602 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3603 (pos js2-ts-cursor)
3604 len
3605 left
3606 right)))
3607 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3608
3609 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3610 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3611
3612 (defun js2-visit-prop-get-node (n v)
3613 (when (js2-prop-get-node-left n)
3614 (js2-visit-ast (js2-prop-get-node-left n) v))
3615 (when (js2-prop-get-node-right n)
3616 (js2-visit-ast (js2-prop-get-node-right n) v)))
3617
3618 (defun js2-print-prop-get-node (n i)
3619 (insert (js2-make-pad i))
3620 (js2-print-ast (js2-prop-get-node-left n) 0)
3621 (insert ".")
3622 (js2-print-ast (js2-prop-get-node-right n) 0))
3623
3624 (defstruct (js2-elem-get-node
3625 (:include js2-node)
3626 (:constructor nil)
3627 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3628 (pos js2-ts-cursor)
3629 len
3630 target
3631 element
3632 lb
3633 rb)))
3634 "AST node for an array index expression such as foo[bar]."
3635 target ; a `js2-node' - the expression preceding the "."
3636 element ; a `js2-node' - the expression in brackets
3637 lb ; position of left-bracket, nil if omitted
3638 rb) ; position of right-bracket, nil if omitted
3639
3640 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3641 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3642
3643 (defun js2-visit-elem-get-node (n v)
3644 (when (js2-elem-get-node-target n)
3645 (js2-visit-ast (js2-elem-get-node-target n) v))
3646 (when (js2-elem-get-node-element n)
3647 (js2-visit-ast (js2-elem-get-node-element n) v)))
3648
3649 (defun js2-print-elem-get-node (n i)
3650 (insert (js2-make-pad i))
3651 (js2-print-ast (js2-elem-get-node-target n) 0)
3652 (insert "[")
3653 (js2-print-ast (js2-elem-get-node-element n) 0)
3654 (insert "]"))
3655
3656 (defstruct (js2-call-node
3657 (:include js2-node)
3658 (:constructor nil)
3659 (:constructor make-js2-call-node (&key (type js2-CALL)
3660 (pos js2-ts-cursor)
3661 len
3662 target
3663 args
3664 lp
3665 rp)))
3666 "AST node for a JavaScript function call."
3667 target ; a `js2-node' evaluating to the function to call
3668 args ; a lisp list of `js2-node' arguments
3669 lp ; position of open-paren, or nil if missing
3670 rp) ; position of close-paren, or nil if missing
3671
3672 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3673 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3674
3675 (defun js2-visit-call-node (n v)
3676 (js2-visit-ast (js2-call-node-target n) v)
3677 (dolist (arg (js2-call-node-args n))
3678 (js2-visit-ast arg v)))
3679
3680 (defun js2-print-call-node (n i)
3681 (insert (js2-make-pad i))
3682 (js2-print-ast (js2-call-node-target n) 0)
3683 (insert "(")
3684 (js2-print-list (js2-call-node-args n))
3685 (insert ")"))
3686
3687 (defstruct (js2-yield-node
3688 (:include js2-node)
3689 (:constructor nil)
3690 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3691 (pos js2-ts-cursor)
3692 len
3693 value)))
3694 "AST node for yield statement or expression."
3695 value) ; optional: value to be yielded
3696
3697 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3698 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3699
3700 (defun js2-visit-yield-node (n v)
3701 (js2-visit-ast (js2-yield-node-value n) v))
3702
3703 (defun js2-print-yield-node (n i)
3704 (insert (js2-make-pad i))
3705 (insert "yield")
3706 (when (js2-yield-node-value n)
3707 (insert " ")
3708 (js2-print-ast (js2-yield-node-value n) 0)))
3709
3710 (defstruct (js2-paren-node
3711 (:include js2-node)
3712 (:constructor nil)
3713 (:constructor make-js2-paren-node (&key (type js2-LP)
3714 (pos js2-ts-cursor)
3715 len
3716 expr)))
3717 "AST node for a parenthesized expression.
3718 In particular, used when the parens are syntactically optional,
3719 as opposed to required parens such as those enclosing an if-conditional."
3720 expr) ; `js2-node'
3721
3722 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3723 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3724
3725 (defun js2-visit-paren-node (n v)
3726 (js2-visit-ast (js2-paren-node-expr n) v))
3727
3728 (defun js2-print-paren-node (n i)
3729 (insert (js2-make-pad i))
3730 (insert "(")
3731 (js2-print-ast (js2-paren-node-expr n) 0)
3732 (insert ")"))
3733
3734 (defstruct (js2-array-comp-node
3735 (:include js2-scope)
3736 (:constructor nil)
3737 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3738 (pos js2-ts-cursor)
3739 len
3740 result
3741 loops
3742 filter
3743 if-pos
3744 lp
3745 rp)))
3746 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3747 result ; result expression (just after left-bracket)
3748 loops ; a lisp list of `js2-array-comp-loop-node'
3749 filter ; guard/filter expression
3750 if-pos ; buffer pos of 'if' keyword, if present, else nil
3751 lp ; buffer position of if-guard left-paren, or nil if not present
3752 rp) ; buffer position of if-guard right-paren, or nil if not present
3753
3754 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3755 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3756
3757 (defun js2-visit-array-comp-node (n v)
3758 (js2-visit-ast (js2-array-comp-node-result n) v)
3759 (dolist (l (js2-array-comp-node-loops n))
3760 (js2-visit-ast l v))
3761 (if (js2-array-comp-node-filter n)
3762 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3763
3764 (defun js2-print-array-comp-node (n i)
3765 (let ((pad (js2-make-pad i))
3766 (result (js2-array-comp-node-result n))
3767 (loops (js2-array-comp-node-loops n))
3768 (filter (js2-array-comp-node-filter n)))
3769 (insert pad "[")
3770 (js2-print-ast result 0)
3771 (dolist (l loops)
3772 (insert " ")
3773 (js2-print-ast l 0))
3774 (when filter
3775 (insert " if (")
3776 (js2-print-ast filter 0))
3777 (insert ")]")))
3778
3779 (defstruct (js2-array-comp-loop-node
3780 (:include js2-for-in-node)
3781 (:constructor nil)
3782 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3783 (pos js2-ts-cursor)
3784 len
3785 iterator
3786 object
3787 in-pos
3788 foreach-p
3789 each-pos
3790 lp
3791 rp)))
3792 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3793
3794 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3795 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3796
3797 (defun js2-visit-array-comp-loop (n v)
3798 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3799 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3800
3801 (defun js2-print-array-comp-loop (n i)
3802 (insert "for (")
3803 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3804 (insert " in ")
3805 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3806 (insert ")"))
3807
3808 (defstruct (js2-empty-expr-node
3809 (:include js2-node)
3810 (:constructor nil)
3811 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3812 (pos js2-token-beg)
3813 len)))
3814 "AST node for an empty expression.")
3815
3816 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3817 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3818
3819 (defstruct (js2-xml-node
3820 (:include js2-block-node)
3821 (:constructor nil)
3822 (:constructor make-js2-xml-node (&key (type js2-XML)
3823 (pos js2-token-beg)
3824 len
3825 kids)))
3826 "AST node for initial parse of E4X literals.
3827 The kids field is a list of XML fragments, each a `js2-string-node' or
3828 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3829
3830 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3831 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3832
3833 (defun js2-print-xml-node (n i)
3834 (dolist (kid (js2-xml-node-kids n))
3835 (js2-print-ast kid i)))
3836
3837 (defstruct (js2-xml-js-expr-node
3838 (:include js2-xml-node)
3839 (:constructor nil)
3840 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3841 (pos js2-ts-cursor)
3842 len
3843 expr)))
3844 "AST node for an embedded JavaScript {expression} in an E4X literal.
3845 The start and end fields correspond to the curly-braces."
3846 expr) ; a `js2-expr-node' of some sort
3847
3848 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3849 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3850
3851 (defun js2-visit-xml-js-expr (n v)
3852 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3853
3854 (defun js2-print-xml-js-expr (n i)
3855 (insert (js2-make-pad i))
3856 (insert "{")
3857 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3858 (insert "}"))
3859
3860 (defstruct (js2-xml-dot-query-node
3861 (:include js2-infix-node)
3862 (:constructor nil)
3863 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3864 (pos js2-ts-cursor)
3865 op-pos
3866 len
3867 left
3868 right
3869 rp)))
3870 "AST node for an E4X foo.(bar) filter expression.
3871 Note that the left-paren is automatically the character immediately
3872 following the dot (.) in the operator. No whitespace is permitted
3873 between the dot and the lp by the scanner."
3874 rp)
3875
3876 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3877 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3878
3879 (defun js2-print-xml-dot-query (n i)
3880 (insert (js2-make-pad i))
3881 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3882 (insert ".(")
3883 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3884 (insert ")"))
3885
3886 (defstruct (js2-xml-ref-node
3887 (:include js2-node)
3888 (:constructor nil)) ; abstract
3889 "Base type for E4X XML attribute-access or property-get expressions.
3890 Such expressions can take a variety of forms. The general syntax has
3891 three parts:
3892
3893 - (optional) an @ (specifying an attribute access)
3894 - (optional) a namespace (a `js2-name-node') and double-colon
3895 - (required) either a `js2-name-node' or a bracketed [expression]
3896
3897 The property-name expressions (examples: ns::name, @name) are
3898 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3899 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3900
3901 This node type (or more specifically, its subclasses) will sometimes
3902 be the right-hand child of a `js2-prop-get-node' or a
3903 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3904 The `js2-xml-ref-node' may also be a standalone primary expression with
3905 no explicit target, which is valid in certain expression contexts such as
3906
3907 company..employee.(@id < 100)
3908
3909 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3910 expression whose parent is a `js2-xml-dot-query-node'."
3911 namespace
3912 at-pos
3913 colon-pos)
3914
3915 (defsubst js2-xml-ref-node-attr-access-p (node)
3916 "Return non-nil if this expression began with an @-token."
3917 (and (numberp (js2-xml-ref-node-at-pos node))
3918 (plusp (js2-xml-ref-node-at-pos node))))
3919
3920 (defstruct (js2-xml-prop-ref-node
3921 (:include js2-xml-ref-node)
3922 (:constructor nil)
3923 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3924 (pos js2-token-beg)
3925 len
3926 propname
3927 namespace
3928 at-pos
3929 colon-pos)))
3930 "AST node for an E4X XML [expr] property-ref expression.
3931 The JavaScript syntax is an optional @, an optional ns::, and a name.
3932
3933 [ '@' ] [ name '::' ] name
3934
3935 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3936 @ns::*, @*::attr, @*::*, and @*.
3937
3938 The node starts at the @ token, if present. Otherwise it starts at the
3939 namespace name. The node bounds extend through the closing right-bracket,
3940 or if it is missing due to a syntax error, through the end of the index
3941 expression."
3942 propname)
3943
3944 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3945 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3946
3947 (defun js2-visit-xml-prop-ref-node (n v)
3948 (if (js2-xml-prop-ref-node-namespace n)
3949 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3950 (if (js2-xml-prop-ref-node-propname n)
3951 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3952
3953 (defun js2-print-xml-prop-ref-node (n i)
3954 (insert (js2-make-pad i))
3955 (if (js2-xml-ref-node-attr-access-p n)
3956 (insert "@"))
3957 (when (js2-xml-prop-ref-node-namespace n)
3958 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3959 (insert "::"))
3960 (if (js2-xml-prop-ref-node-propname n)
3961 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3962
3963 (defstruct (js2-xml-elem-ref-node
3964 (:include js2-xml-ref-node)
3965 (:constructor nil)
3966 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3967 (pos js2-token-beg)
3968 len
3969 expr
3970 lb
3971 rb
3972 namespace
3973 at-pos
3974 colon-pos)))
3975 "AST node for an E4X XML [expr] member-ref expression.
3976 Syntax:
3977
3978 [ '@' ] [ name '::' ] '[' expr ']'
3979
3980 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3981
3982 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3983 is not a legal E4X XML element-ref expression, since it's already used
3984 for standard JavaScript element-get array indexing. Hence, a
3985 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3986 non-nil namespace node, or both.
3987
3988 The node starts at the @ token, if present. Otherwise it starts
3989 at the namespace name. The node bounds extend through the closing
3990 right-bracket, or if it is missing due to a syntax error, through the
3991 end of the index expression."
3992 expr ; the bracketed index expression
3993 lb
3994 rb)
3995
3996 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3997 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3998
3999 (defun js2-visit-xml-elem-ref-node (n v)
4000 (if (js2-xml-elem-ref-node-namespace n)
4001 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
4002 (if (js2-xml-elem-ref-node-expr n)
4003 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
4004
4005 (defun js2-print-xml-elem-ref-node (n i)
4006 (insert (js2-make-pad i))
4007 (if (js2-xml-ref-node-attr-access-p n)
4008 (insert "@"))
4009 (when (js2-xml-elem-ref-node-namespace n)
4010 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4011 (insert "::"))
4012 (insert "[")
4013 (if (js2-xml-elem-ref-node-expr n)
4014 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4015 (insert "]"))
4016
4017 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4018
4019 (defstruct (js2-xml-start-tag-node
4020 (:include js2-xml-node)
4021 (:constructor nil)
4022 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4023 (pos js2-ts-cursor)
4024 len
4025 name
4026 attrs
4027 kids
4028 empty-p)))
4029 "AST node for an XML start-tag. Not currently used.
4030 The `kids' field is a lisp list of child content nodes."
4031 name ; a `js2-xml-name-node'
4032 attrs ; a lisp list of `js2-xml-attr-node'
4033 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4034
4035 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4036 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4037
4038 (defun js2-visit-xml-start-tag (n v)
4039 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4040 (dolist (attr (js2-xml-start-tag-node-attrs n))
4041 (js2-visit-ast attr v))
4042 (js2-visit-block n v))
4043
4044 (defun js2-print-xml-start-tag (n i)
4045 (insert (js2-make-pad i) "<")
4046 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4047 (when (js2-xml-start-tag-node-attrs n)
4048 (insert " ")
4049 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4050 (insert ">"))
4051
4052 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4053 ;; and add the end-tag to the kids list of the parent as well.
4054 (defstruct (js2-xml-end-tag-node
4055 (:include js2-xml-node)
4056 (:constructor nil)
4057 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4058 (pos js2-ts-cursor)
4059 len
4060 name)))
4061 "AST node for an XML end-tag. Not currently used."
4062 name) ; a `js2-xml-name-node'
4063
4064 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4065 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4066
4067 (defun js2-visit-xml-end-tag (n v)
4068 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4069
4070 (defun js2-print-xml-end-tag (n i)
4071 (insert (js2-make-pad i))
4072 (insert "</")
4073 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4074 (insert ">"))
4075
4076 (defstruct (js2-xml-name-node
4077 (:include js2-xml-node)
4078 (:constructor nil)
4079 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4080 (pos js2-ts-cursor)
4081 len
4082 namespace
4083 kids)))
4084 "AST node for an E4X XML name. Not currently used.
4085 Any XML name can be qualified with a namespace, hence the namespace field.
4086 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4087 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4088 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4089 namespace) ; a `js2-string-node'
4090
4091 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4092 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4093
4094 (defun js2-visit-xml-name-node (n v)
4095 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4096
4097 (defun js2-print-xml-name-node (n i)
4098 (insert (js2-make-pad i))
4099 (when (js2-xml-name-node-namespace n)
4100 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4101 (insert "::"))
4102 (dolist (kid (js2-xml-name-node-kids n))
4103 (js2-print-ast kid 0)))
4104
4105 (defstruct (js2-xml-pi-node
4106 (:include js2-xml-node)
4107 (:constructor nil)
4108 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4109 (pos js2-ts-cursor)
4110 len
4111 name
4112 attrs)))
4113 "AST node for an E4X XML processing instruction. Not currently used."
4114 name ; a `js2-xml-name-node'
4115 attrs) ; a list of `js2-xml-attr-node'
4116
4117 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4118 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4119
4120 (defun js2-visit-xml-pi-node (n v)
4121 (js2-visit-ast (js2-xml-pi-node-name n) v)
4122 (dolist (attr (js2-xml-pi-node-attrs n))
4123 (js2-visit-ast attr v)))
4124
4125 (defun js2-print-xml-pi-node (n i)
4126 (insert (js2-make-pad i) "<?")
4127 (js2-print-ast (js2-xml-pi-node-name n))
4128 (when (js2-xml-pi-node-attrs n)
4129 (insert " ")
4130 (js2-print-list (js2-xml-pi-node-attrs n)))
4131 (insert "?>"))
4132
4133 (defstruct (js2-xml-cdata-node
4134 (:include js2-xml-node)
4135 (:constructor nil)
4136 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4137 (pos js2-ts-cursor)
4138 len
4139 content)))
4140 "AST node for a CDATA escape section. Not currently used."
4141 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4142
4143 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4144 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4145
4146 (defun js2-visit-xml-cdata-node (n v)
4147 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4148
4149 (defun js2-print-xml-cdata-node (n i)
4150 (insert (js2-make-pad i))
4151 (js2-print-ast (js2-xml-cdata-node-content n)))
4152
4153 (defstruct (js2-xml-attr-node
4154 (:include js2-xml-node)
4155 (:constructor nil)
4156 (:constructor make-js2-attr-node (&key (type js2-XML)
4157 (pos js2-ts-cursor)
4158 len
4159 name
4160 value
4161 eq-pos
4162 quote-type)))
4163 "AST node representing a foo='bar' XML attribute value. Not yet used."
4164 name ; a `js2-xml-name-node'
4165 value ; a `js2-xml-name-node'
4166 eq-pos ; buffer position of "=" sign
4167 quote-type) ; 'single or 'double
4168
4169 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4170 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4171
4172 (defun js2-visit-xml-attr-node (n v)
4173 (js2-visit-ast (js2-xml-attr-node-name n) v)
4174 (js2-visit-ast (js2-xml-attr-node-value n) v))
4175
4176 (defun js2-print-xml-attr-node (n i)
4177 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4178 "'"
4179 "\"")))
4180 (insert (js2-make-pad i))
4181 (js2-print-ast (js2-xml-attr-node-name n) 0)
4182 (insert "=" quote)
4183 (js2-print-ast (js2-xml-attr-node-value n) 0)
4184 (insert quote)))
4185
4186 (defstruct (js2-xml-text-node
4187 (:include js2-xml-node)
4188 (:constructor nil)
4189 (:constructor make-js2-text-node (&key (type js2-XML)
4190 (pos js2-ts-cursor)
4191 len
4192 content)))
4193 "AST node for an E4X XML text node. Not currently used."
4194 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4195
4196 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4197 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4198
4199 (defun js2-visit-xml-text-node (n v)
4200 (js2-visit-ast (js2-xml-text-node-content n) v))
4201
4202 (defun js2-print-xml-text-node (n i)
4203 (insert (js2-make-pad i))
4204 (dolist (kid (js2-xml-text-node-content n))
4205 (js2-print-ast kid)))
4206
4207 (defstruct (js2-xml-comment-node
4208 (:include js2-xml-node)
4209 (:constructor nil)
4210 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4211 (pos js2-ts-cursor)
4212 len)))
4213 "AST node for E4X XML comment. Not currently used.")
4214
4215 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4216 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4217
4218 (defun js2-print-xml-comment (n i)
4219 (insert (js2-make-pad i)
4220 (js2-node-string n)))
4221
4222 ;;; Node utilities
4223
4224 (defsubst js2-node-line (n)
4225 "Fetch the source line number at the start of node N.
4226 This is O(n) in the length of the source buffer; use prudently."
4227 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4228
4229 (defsubst js2-block-node-kid (n i)
4230 "Return child I of node N, or nil if there aren't that many."
4231 (nth i (js2-block-node-kids n)))
4232
4233 (defsubst js2-block-node-first (n)
4234 "Return first child of block node N, or nil if there is none."
4235 (first (js2-block-node-kids n)))
4236
4237 (defun js2-node-root (n)
4238 "Return the root of the AST containing N.
4239 If N has no parent pointer, returns N."
4240 (let ((parent (js2-node-parent n)))
4241 (if parent
4242 (js2-node-root parent)
4243 n)))
4244
4245 (defun js2-node-position-in-parent (node &optional parent)
4246 "Return the position of NODE in parent's block-kids list.
4247 PARENT can be supplied if known. Positioned returned is zero-indexed.
4248 Returns 0 if NODE is not a child of a block statement, or if NODE
4249 is not a statement node."
4250 (let ((p (or parent (js2-node-parent node)))
4251 (i 0))
4252 (if (not (js2-block-node-p p))
4253 i
4254 (or (js2-position node (js2-block-node-kids p))
4255 0))))
4256
4257 (defsubst js2-node-short-name (n)
4258 "Return the short name of node N as a string, e.g. `js2-if-node'."
4259 (substring (symbol-name (aref n 0))
4260 (length "cl-struct-")))
4261
4262 (defsubst js2-node-child-list (node)
4263 "Return the child list for NODE, a lisp list of nodes.
4264 Works for block nodes, array nodes, obj literals, funarg lists,
4265 var decls and try nodes (for catch clauses). Note that you should call
4266 `js2-block-node-kids' on the function body for the body statements.
4267 Returns nil for zero-length child lists or unsupported nodes."
4268 (cond
4269 ((js2-function-node-p node)
4270 (js2-function-node-params node))
4271 ((js2-block-node-p node)
4272 (js2-block-node-kids node))
4273 ((js2-try-node-p node)
4274 (js2-try-node-catch-clauses node))
4275 ((js2-array-node-p node)
4276 (js2-array-node-elems node))
4277 ((js2-object-node-p node)
4278 (js2-object-node-elems node))
4279 ((js2-call-node-p node)
4280 (js2-call-node-args node))
4281 ((js2-new-node-p node)
4282 (js2-new-node-args node))
4283 ((js2-var-decl-node-p node)
4284 (js2-var-decl-node-kids node))
4285 (t
4286 nil)))
4287
4288 (defsubst js2-node-set-child-list (node kids)
4289 "Set the child list for NODE to KIDS."
4290 (cond
4291 ((js2-function-node-p node)
4292 (setf (js2-function-node-params node) kids))
4293 ((js2-block-node-p node)
4294 (setf (js2-block-node-kids node) kids))
4295 ((js2-try-node-p node)
4296 (setf (js2-try-node-catch-clauses node) kids))
4297 ((js2-array-node-p node)
4298 (setf (js2-array-node-elems node) kids))
4299 ((js2-object-node-p node)
4300 (setf (js2-object-node-elems node) kids))
4301 ((js2-call-node-p node)
4302 (setf (js2-call-node-args node) kids))
4303 ((js2-new-node-p node)
4304 (setf (js2-new-node-args node) kids))
4305 ((js2-var-decl-node-p node)
4306 (setf (js2-var-decl-node-kids node) kids))
4307 (t
4308 (error "Unsupported node type: %s" (js2-node-short-name node))))
4309 kids)
4310
4311 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4312 (defconst js2-paren-expr-nodes
4313 '(cl-struct-js2-array-comp-loop-node
4314 cl-struct-js2-array-comp-node
4315 cl-struct-js2-call-node
4316 cl-struct-js2-catch-node
4317 cl-struct-js2-do-node
4318 cl-struct-js2-elem-get-node
4319 cl-struct-js2-for-in-node
4320 cl-struct-js2-for-node
4321 cl-struct-js2-function-node
4322 cl-struct-js2-if-node
4323 cl-struct-js2-let-node
4324 cl-struct-js2-new-node
4325 cl-struct-js2-paren-node
4326 cl-struct-js2-switch-node
4327 cl-struct-js2-while-node
4328 cl-struct-js2-with-node
4329 cl-struct-js2-xml-dot-query-node)
4330 "Node types that can have a parenthesized child expression.
4331 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4332
4333 (defsubst js2-paren-expr-node-p (node)
4334 "Return t for nodes that typically have a parenthesized child expression.
4335 Useful for computing the indentation anchors for arg-lists and conditions.
4336 Note that it may return a false positive, for instance when NODE is
4337 a `js2-new-node' and there are no arguments or parentheses."
4338 (memq (aref node 0) js2-paren-expr-nodes))
4339
4340 ;; Fake polymorphism... yech.
4341 (defsubst js2-node-lp (node)
4342 "Return relative left-paren position for NODE, if applicable.
4343 For `js2-elem-get-node' structs, returns left-bracket position.
4344 Note that the position may be nil in the case of a parse error."
4345 (cond
4346 ((js2-elem-get-node-p node)
4347 (js2-elem-get-node-lb node))
4348 ((js2-loop-node-p node)
4349 (js2-loop-node-lp node))
4350 ((js2-function-node-p node)
4351 (js2-function-node-lp node))
4352 ((js2-if-node-p node)
4353 (js2-if-node-lp node))
4354 ((js2-new-node-p node)
4355 (js2-new-node-lp node))
4356 ((js2-call-node-p node)
4357 (js2-call-node-lp node))
4358 ((js2-paren-node-p node)
4359 (js2-node-pos node))
4360 ((js2-switch-node-p node)
4361 (js2-switch-node-lp node))
4362 ((js2-catch-node-p node)
4363 (js2-catch-node-lp node))
4364 ((js2-let-node-p node)
4365 (js2-let-node-lp node))
4366 ((js2-array-comp-node-p node)
4367 (js2-array-comp-node-lp node))
4368 ((js2-with-node-p node)
4369 (js2-with-node-lp node))
4370 ((js2-xml-dot-query-node-p node)
4371 (1+ (js2-infix-node-op-pos node)))
4372 (t
4373 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4374
4375 ;; Fake polymorphism... blech.
4376 (defsubst js2-node-rp (node)
4377 "Return relative right-paren position for NODE, if applicable.
4378 For `js2-elem-get-node' structs, returns right-bracket position.
4379 Note that the position may be nil in the case of a parse error."
4380 (cond
4381 ((js2-elem-get-node-p node)
4382 (js2-elem-get-node-lb node))
4383 ((js2-loop-node-p node)
4384 (js2-loop-node-rp node))
4385 ((js2-function-node-p node)
4386 (js2-function-node-rp node))
4387 ((js2-if-node-p node)
4388 (js2-if-node-rp node))
4389 ((js2-new-node-p node)
4390 (js2-new-node-rp node))
4391 ((js2-call-node-p node)
4392 (js2-call-node-rp node))
4393 ((js2-paren-node-p node)
4394 (+ (js2-node-pos node) (js2-node-len node)))
4395 ((js2-switch-node-p node)
4396 (js2-switch-node-rp node))
4397 ((js2-catch-node-p node)
4398 (js2-catch-node-rp node))
4399 ((js2-let-node-p node)
4400 (js2-let-node-rp node))
4401 ((js2-array-comp-node-p node)
4402 (js2-array-comp-node-rp node))
4403 ((js2-with-node-p node)
4404 (js2-with-node-rp node))
4405 ((js2-xml-dot-query-node-p node)
4406 (1+ (js2-xml-dot-query-node-rp node)))
4407 (t
4408 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4409
4410 (defsubst js2-node-first-child (node)
4411 "Returns the first element of `js2-node-child-list' for NODE."
4412 (car (js2-node-child-list node)))
4413
4414 (defsubst js2-node-last-child (node)
4415 "Returns the last element of `js2-node-last-child' for NODE."
4416 (car (last (js2-node-child-list node))))
4417
4418 (defun js2-node-prev-sibling (node)
4419 "Return the previous statement in parent.
4420 Works for parents supported by `js2-node-child-list'.
4421 Returns nil if NODE is not in the parent, or PARENT is
4422 not a supported node, or if NODE is the first child."
4423 (let* ((p (js2-node-parent node))
4424 (kids (js2-node-child-list p))
4425 (sib (car kids)))
4426 (while (and kids
4427 (not (eq node (cadr kids))))
4428 (setq kids (cdr kids)
4429 sib (car kids)))
4430 sib))
4431
4432 (defun js2-node-next-sibling (node)
4433 "Return the next statement in parent block.
4434 Returns nil if NODE is not in the block, or PARENT is not
4435 a block node, or if NODE is the last statement."
4436 (let* ((p (js2-node-parent node))
4437 (kids (js2-node-child-list p)))
4438 (while (and kids
4439 (not (eq node (car kids))))
4440 (setq kids (cdr kids)))
4441 (cadr kids)))
4442
4443 (defun js2-node-find-child-before (pos parent &optional after)
4444 "Find the last child that starts before POS in parent.
4445 If AFTER is non-nil, returns first child starting after POS.
4446 POS is an absolute buffer position. PARENT is any node
4447 supported by `js2-node-child-list'.
4448 Returns nil if no applicable child is found."
4449 (let ((kids (if (js2-function-node-p parent)
4450 (js2-block-node-kids (js2-function-node-body parent))
4451 (js2-node-child-list parent)))
4452 (beg (if (js2-function-node-p parent)
4453 (js2-node-abs-pos (js2-function-node-body parent))
4454 (js2-node-abs-pos parent)))
4455 kid
4456 result
4457 fn
4458 (continue t))
4459 (setq fn (if after '> '<))
4460 (while (and kids continue)
4461 (setq kid (car kids))
4462 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4463 (setq result kid
4464 continue (if after nil t))
4465 (setq continue (if after t nil)))
4466 (setq kids (cdr kids)))
4467 result))
4468
4469 (defun js2-node-find-child-after (pos parent)
4470 "Find first child that starts after POS in parent.
4471 POS is an absolute buffer position. PARENT is any node
4472 supported by `js2-node-child-list'.
4473 Returns nil if no applicable child is found."
4474 (js2-node-find-child-before pos parent 'after))
4475
4476 (defun js2-node-replace-child (pos parent new-node)
4477 "Replace node at index POS in PARENT with NEW-NODE.
4478 Only works for parents supported by `js2-node-child-list'."
4479 (let ((kids (js2-node-child-list parent))
4480 (i 0))
4481 (while (< i pos)
4482 (setq kids (cdr kids)
4483 i (1+ i)))
4484 (setcar kids new-node)
4485 (js2-node-add-children parent new-node)))
4486
4487 (defun js2-node-buffer (n)
4488 "Return the buffer associated with AST N.
4489 Returns nil if the buffer is not set as a property on the root
4490 node, or if parent links were not recorded during parsing."
4491 (let ((root (js2-node-root n)))
4492 (and root
4493 (js2-ast-root-p root)
4494 (js2-ast-root-buffer root))))
4495
4496 (defsubst js2-block-node-push (n kid)
4497 "Push js2-node KID onto the end of js2-block-node N's child list.
4498 KID is always added to the -end- of the kids list.
4499 Function also calls `js2-node-add-children' to add the parent link."
4500 (let ((kids (js2-node-child-list n)))
4501 (if kids
4502 (setcdr kids (nconc (cdr kids) (list kid)))
4503 (js2-node-set-child-list n (list kid)))
4504 (js2-node-add-children n kid)))
4505
4506 (defun js2-node-string (node)
4507 (let ((buf (js2-node-buffer node))
4508 pos)
4509 (unless buf
4510 (error "No buffer available for node %s" node))
4511 (save-excursion
4512 (set-buffer buf)
4513 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4514 (+ pos (js2-node-len node))))))
4515
4516 ;; Container for storing the node we're looking for in a traversal.
4517 (js2-deflocal js2-discovered-node nil)
4518
4519 ;; Keep track of absolute node position during traversals.
4520 (js2-deflocal js2-visitor-offset nil)
4521
4522 (js2-deflocal js2-node-search-point nil)
4523
4524 (when js2-mode-dev-mode-p
4525 (defun js2-find-node-at-point ()
4526 (interactive)
4527 (let ((node (js2-node-at-point)))
4528 (message "%s" (or node "No node found at point"))))
4529 (defun js2-node-name-at-point ()
4530 (interactive)
4531 (let ((node (js2-node-at-point)))
4532 (message "%s" (if node
4533 (js2-node-short-name node)
4534 "No node found at point.")))))
4535
4536 (defun js2-node-at-point (&optional pos skip-comments)
4537 "Return AST node at POS, a buffer position, defaulting to current point.
4538 The `js2-mode-ast' variable must be set to the current parse tree.
4539 Signals an error if the AST (`js2-mode-ast') is nil.
4540 Always returns a node - if it can't find one, it returns the root.
4541 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4542 (let ((ast js2-mode-ast)
4543 result)
4544 (unless ast
4545 (error "No JavaScript AST available"))
4546 ;; Look through comments first, since they may be inside nodes that
4547 ;; would otherwise report a match.
4548 (setq pos (or pos (point))
4549 result (if (> pos (js2-node-abs-end ast))
4550 ast
4551 (if (not skip-comments)
4552 (js2-comment-at-point pos))))
4553 (unless result
4554 (setq js2-discovered-node nil
4555 js2-visitor-offset 0
4556 js2-node-search-point pos)
4557 (unwind-protect
4558 (catch 'js2-visit-done
4559 (js2-visit-ast ast #'js2-node-at-point-visitor))
4560 (setq js2-visitor-offset nil
4561 js2-node-search-point nil))
4562 (setq result js2-discovered-node))
4563 ;; may have found a comment beyond end of last child node,
4564 ;; since visiting the ast-root looks at the comment-list last.
4565 (if (and skip-comments
4566 (js2-comment-node-p result))
4567 (setq result nil))
4568 (or result js2-mode-ast)))
4569
4570 (defun js2-node-at-point-visitor (node end-p)
4571 (let ((rel-pos (js2-node-pos node))
4572 abs-pos
4573 abs-end
4574 (point js2-node-search-point))
4575 (cond
4576 (end-p
4577 ;; this evaluates to a non-nil return value, even if it's zero
4578 (decf js2-visitor-offset rel-pos))
4579 ;; we already looked for comments before visiting, and don't want them now
4580 ((js2-comment-node-p node)
4581 nil)
4582 (t
4583 (setq abs-pos (incf js2-visitor-offset rel-pos)
4584 ;; we only want to use the node if the point is before
4585 ;; the last character position in the node, so we decrement
4586 ;; the absolute end by 1.
4587 abs-end (+ abs-pos (js2-node-len node) -1))
4588 (cond
4589 ;; If this node starts after search-point, stop the search.
4590 ((> abs-pos point)
4591 (throw 'js2-visit-done nil))
4592 ;; If this node ends before the search-point, don't check kids.
4593 ((> point abs-end)
4594 nil)
4595 (t
4596 ;; Otherwise point is within this node, possibly in a child.
4597 (setq js2-discovered-node node)
4598 t)))))) ; keep processing kids to look for more specific match
4599
4600 (defsubst js2-block-comment-p (node)
4601 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4602 (and (js2-comment-node-p node)
4603 (memq (js2-comment-node-format node) '(jsdoc block))))
4604
4605 ;; TODO: put the comments in a vector and binary-search them instead
4606 (defun js2-comment-at-point (&optional pos)
4607 "Look through scanned comment nodes for one containing POS.
4608 POS is a buffer position that defaults to current point.
4609 Function returns nil if POS was not in any comment node."
4610 (let ((ast js2-mode-ast)
4611 (x (or pos (point)))
4612 beg
4613 end)
4614 (unless ast
4615 (error "No JavaScript AST available"))
4616 (catch 'done
4617 ;; Comments are stored in lexical order.
4618 (dolist (comment (js2-ast-root-comments ast) nil)
4619 (setq beg (js2-node-abs-pos comment)
4620 end (+ beg (js2-node-len comment)))
4621 (if (and (>= x beg)
4622 (<= x end))
4623 (throw 'done comment))))))
4624
4625 (defun js2-mode-find-parent-fn (node)
4626 "Find function enclosing NODE.
4627 Returns nil if NODE is not inside a function."
4628 (setq node (js2-node-parent node))
4629 (while (and node (not (js2-function-node-p node)))
4630 (setq node (js2-node-parent node)))
4631 (and (js2-function-node-p node) node))
4632
4633 (defun js2-mode-find-enclosing-fn (node)
4634 "Find function or root enclosing NODE."
4635 (if (js2-ast-root-p node)
4636 node
4637 (setq node (js2-node-parent node))
4638 (while (not (or (js2-ast-root-p node)
4639 (js2-function-node-p node)))
4640 (setq node (js2-node-parent node)))
4641 node))
4642
4643 (defun js2-mode-find-enclosing-node (beg end)
4644 "Find script or function fully enclosing BEG and END."
4645 (let ((node (js2-node-at-point beg))
4646 pos
4647 (continue t))
4648 (while continue
4649 (if (or (js2-ast-root-p node)
4650 (and (js2-function-node-p node)
4651 (<= (setq pos (js2-node-abs-pos node)) beg)
4652 (>= (+ pos (js2-node-len node)) end)))
4653 (setq continue nil)
4654 (setq node (js2-node-parent node))))
4655 node))
4656
4657 (defun js2-node-parent-script-or-fn (node)
4658 "Find script or function immediately enclosing NODE.
4659 If NODE is the ast-root, returns nil."
4660 (if (js2-ast-root-p node)
4661 nil
4662 (setq node (js2-node-parent node))
4663 (while (and node (not (or (js2-function-node-p node)
4664 (js2-script-node-p node))))
4665 (setq node (js2-node-parent node)))
4666 node))
4667
4668 (defsubst js2-nested-function-p (node)
4669 "Return t if NODE is a nested function, or is inside a nested function."
4670 (js2-function-node-p (if (js2-function-node-p node)
4671 (js2-node-parent-script-or-fn node)
4672 (js2-node-parent-script-or-fn
4673 (js2-node-parent-script-or-fn node)))))
4674
4675 (defsubst js2-function-param-node-p (node)
4676 "Return non-nil if NODE is a param node of a `js2-function-node'."
4677 (let ((parent (js2-node-parent node)))
4678 (and parent
4679 (js2-function-node-p parent)
4680 (memq node (js2-function-node-params parent)))))
4681
4682 (defsubst js2-mode-shift-kids (kids start offset)
4683 (dolist (kid kids)
4684 (if (> (js2-node-pos kid) start)
4685 (incf (js2-node-pos kid) offset))))
4686
4687 (defsubst js2-mode-shift-children (parent start offset)
4688 "Update start-positions of all children of PARENT beyond START."
4689 (let ((root (js2-node-root parent)))
4690 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4691 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4692
4693 (defsubst js2-node-is-descendant (node ancestor)
4694 "Return t if NODE is a descendant of ANCESTOR."
4695 (while (and node
4696 (not (eq node ancestor)))
4697 (setq node (js2-node-parent node)))
4698 node)
4699
4700 ;;; visitor infrastructure
4701
4702 (defun js2-visit-none (node callback)
4703 "Visitor for AST node that have no node children."
4704 nil)
4705
4706 (defun js2-print-none (node indent)
4707 "Visitor for AST node with no printed representation.")
4708
4709 (defun js2-print-body (node indent)
4710 "Print a statement, or a block without braces."
4711 (if (js2-block-node-p node)
4712 (dolist (kid (js2-block-node-kids node))
4713 (js2-print-ast kid indent))
4714 (js2-print-ast node indent)))
4715
4716 (defun js2-print-list (args &optional delimiter)
4717 (loop with len = (length args)
4718 for arg in args
4719 for count from 1
4720 do
4721 (js2-print-ast arg 0)
4722 (if (< count len)
4723 (insert (or delimiter ", ")))))
4724
4725 (defun js2-print-tree (ast)
4726 "Prints an AST to the current buffer.
4727 Makes `js2-ast-parent-nodes' available to the printer functions."
4728 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4729 (js2-print-ast ast)))
4730
4731 (defun js2-print-ast (node &optional indent)
4732 "Helper function for printing AST nodes.
4733 Requires `js2-ast-parent-nodes' to be non-nil.
4734 You should use `js2-print-tree' instead of this function."
4735 (let ((printer (get (aref node 0) 'js2-printer))
4736 (i (or indent 0))
4737 (pos (js2-node-abs-pos node)))
4738 ;; TODO: wedge comments in here somewhere
4739 (if printer
4740 (funcall printer node i))))
4741
4742 (defconst js2-side-effecting-tokens
4743 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4744 (dolist (tt (list js2-ASSIGN
4745 js2-ASSIGN_ADD
4746 js2-ASSIGN_BITAND
4747 js2-ASSIGN_BITOR
4748 js2-ASSIGN_BITXOR
4749 js2-ASSIGN_DIV
4750 js2-ASSIGN_LSH
4751 js2-ASSIGN_MOD
4752 js2-ASSIGN_MUL
4753 js2-ASSIGN_RSH
4754 js2-ASSIGN_SUB
4755 js2-ASSIGN_URSH
4756 js2-BLOCK
4757 js2-BREAK
4758 js2-CALL
4759 js2-CATCH
4760 js2-CATCH_SCOPE
4761 js2-CONST
4762 js2-CONTINUE
4763 js2-DEBUGGER
4764 js2-DEC
4765 js2-DELPROP
4766 js2-DEL_REF
4767 js2-DO
4768 js2-ELSE
4769 js2-EMPTY
4770 js2-ENTERWITH
4771 js2-EXPORT
4772 js2-EXPR_RESULT
4773 js2-FINALLY
4774 js2-FOR
4775 js2-FUNCTION
4776 js2-GOTO
4777 js2-IF
4778 js2-IFEQ
4779 js2-IFNE
4780 js2-IMPORT
4781 js2-INC
4782 js2-JSR
4783 js2-LABEL
4784 js2-LEAVEWITH
4785 js2-LET
4786 js2-LETEXPR
4787 js2-LOCAL_BLOCK
4788 js2-LOOP
4789 js2-NEW
4790 js2-REF_CALL
4791 js2-RETHROW
4792 js2-RETURN
4793 js2-RETURN_RESULT
4794 js2-SEMI
4795 js2-SETELEM
4796 js2-SETELEM_OP
4797 js2-SETNAME
4798 js2-SETPROP
4799 js2-SETPROP_OP
4800 js2-SETVAR
4801 js2-SET_REF
4802 js2-SET_REF_OP
4803 js2-SWITCH
4804 js2-TARGET
4805 js2-THROW
4806 js2-TRY
4807 js2-VAR
4808 js2-WHILE
4809 js2-WITH
4810 js2-WITHEXPR
4811 js2-YIELD))
4812 (aset tokens tt t))
4813 (if js2-instanceof-has-side-effects
4814 (aset tokens js2-INSTANCEOF t))
4815 tokens))
4816
4817 (defun js2-node-has-side-effects (node)
4818 "Return t if NODE has side effects."
4819 (when node ; makes it easier to handle malformed expressions
4820 (let ((tt (js2-node-type node)))
4821 (cond
4822 ;; This doubtless needs some work, since EXPR_VOID is used
4823 ;; in several ways in Rhino, and I may not have caught them all.
4824 ;; I'll wait for people to notice incorrect warnings.
4825 ((and (= tt js2-EXPR_VOID)
4826 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4827 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4828 ((= tt js2-COMMA)
4829 (js2-node-has-side-effects (js2-infix-node-right node)))
4830 ((or (= tt js2-AND)
4831 (= tt js2-OR))
4832 (or (js2-node-has-side-effects (js2-infix-node-right node))
4833 (js2-node-has-side-effects (js2-infix-node-left node))))
4834 ((= tt js2-HOOK)
4835 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4836 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4837 ((js2-paren-node-p node)
4838 (js2-node-has-side-effects (js2-paren-node-expr node)))
4839 ((= tt js2-ERROR) ; avoid cascaded error messages
4840 nil)
4841 (t
4842 (aref js2-side-effecting-tokens tt))))))
4843
4844 (defun js2-member-expr-leftmost-name (node)
4845 "For an expr such as foo.bar.baz, return leftmost node foo.
4846 NODE is any `js2-node' object. If it represents a member expression,
4847 which is any sequence of property gets, element-gets, function calls,
4848 or xml descendants/filter operators, then we look at the lexically
4849 leftmost (first) node in the chain. If it is a name-node we return it.
4850 Note that NODE can be a raw name-node and it will be returned as well.
4851 If NODE is not a name-node or member expression, or if it is a member
4852 expression whose leftmost target is not a name node, returns nil."
4853 (let ((continue t)
4854 result)
4855 (while (and continue (not result))
4856 (cond
4857 ((js2-name-node-p node)
4858 (setq result node))
4859 ((js2-prop-get-node-p node)
4860 (setq node (js2-prop-get-node-left node)))
4861 ;; TODO: handle call-nodes, xml-nodes, others?
4862 (t
4863 (setq continue nil))))
4864 result))
4865
4866 (defconst js2-stmt-node-types
4867 (list js2-BLOCK
4868 js2-BREAK
4869 js2-CONTINUE
4870 js2-DEFAULT ; e4x "default xml namespace" statement
4871 js2-DO
4872 js2-EXPR_RESULT
4873 js2-EXPR_VOID
4874 js2-FOR
4875 js2-IF
4876 js2-RETURN
4877 js2-SWITCH
4878 js2-THROW
4879 js2-TRY
4880 js2-WHILE
4881 js2-WITH)
4882 "Node types that only appear in statement contexts.
4883 The list does not include nodes that always appear as the child
4884 of another specific statement type, such as switch-cases,
4885 catch and finally blocks, and else-clauses. The list also excludes
4886 nodes like yield, let and var, which may appear in either expression
4887 or statement context, and in the latter context always have a
4888 `js2-expr-stmt-node' parent. Finally, the list does not include
4889 functions or scripts, which are treated separately from statements
4890 by the JavaScript parser and runtime.")
4891
4892 (defun js2-stmt-node-p (node)
4893 "Heuristic for figuring out if NODE is a statement.
4894 Some node types can appear in either an expression context or a
4895 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4896 For these node types in a statement context, the parent will be a
4897 `js2-expr-stmt-node'.
4898 Functions aren't included in the check."
4899 (memq (js2-node-type node) js2-stmt-node-types))
4900
4901 (defsubst js2-mode-find-first-stmt (node)
4902 "Search upward starting from NODE looking for a statement.
4903 For purposes of this function, a `js2-function-node' counts."
4904 (while (not (or (js2-stmt-node-p node)
4905 (js2-function-node-p node)))
4906 (setq node (js2-node-parent node)))
4907 node)
4908
4909 (defun js2-node-parent-stmt (node)
4910 "Return the node's first ancestor that is a statement.
4911 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4912 appearing in a statement context will have a parent that is a
4913 `js2-expr-stmt-node' that will be returned by this function."
4914 (let ((parent (js2-node-parent node)))
4915 (if (or (null parent)
4916 (js2-stmt-node-p parent)
4917 (and (js2-function-node-p parent)
4918 (not (eq (js2-function-node-form parent)
4919 'FUNCTION_EXPRESSION))))
4920 parent
4921 (js2-node-parent-stmt parent))))
4922
4923 ;; In the Mozilla Rhino sources, Roshan James writes:
4924 ;; Does consistent-return analysis on the function body when strict mode is
4925 ;; enabled.
4926 ;;
4927 ;; function (x) { return (x+1) }
4928 ;;
4929 ;; is ok, but
4930 ;;
4931 ;; function (x) { if (x < 0) return (x+1); }
4932 ;;
4933 ;; is not because the function can potentially return a value when the
4934 ;; condition is satisfied and if not, the function does not explicitly
4935 ;; return a value.
4936 ;;
4937 ;; This extends to checking mismatches such as "return" and "return <value>"
4938 ;; used in the same function. Warnings are not emitted if inconsistent
4939 ;; returns exist in code that can be statically shown to be unreachable.
4940 ;; Ex.
4941 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4942 ;;
4943 ;; emits no warning. However if the loop had a break statement, then a
4944 ;; warning would be emitted.
4945 ;;
4946 ;; The consistency analysis looks at control structures such as loops, ifs,
4947 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4948 ;; warns the user about an inconsistent set of termination possibilities.
4949 ;;
4950 ;; These flags enumerate the possible ways a statement/function can
4951 ;; terminate. These flags are used by endCheck() and by the Parser to
4952 ;; detect inconsistent return usage.
4953 ;;
4954 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4955 ;; able to execute (example: throw, continue)
4956 ;;
4957 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4958 ;; next one. Statement such as return dont. A compound statement may have
4959 ;; some branch that drops off control to the next statement.
4960 ;;
4961 ;; END_RETURNS indicates that the statement can return with no value.
4962 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4963 ;;
4964 ;; A compound statement such as
4965 ;; if (condition) {
4966 ;; return value;
4967 ;; }
4968 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4969
4970 (defconst js2-END_UNREACHED 0)
4971 (defconst js2-END_DROPS_OFF 1)
4972 (defconst js2-END_RETURNS 2)
4973 (defconst js2-END_RETURNS_VALUE 4)
4974 (defconst js2-END_YIELDS 8)
4975
4976 (defun js2-has-consistent-return-usage (node)
4977 "Check that every return usage in a function body is consistent.
4978 Returns t if the function satisfies strict mode requirement."
4979 (let ((n (js2-end-check node)))
4980 ;; either it doesn't return a value in any branch...
4981 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4982 ;; or it returns a value (or is unreached) at every branch
4983 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4984 js2-END_RETURNS
4985 js2-END_YIELDS)))))
4986
4987 (defun js2-end-check-if (node)
4988 "Returns in the then and else blocks must be consistent with each other.
4989 If there is no else block, then the return statement can fall through.
4990 Returns logical OR of END_* flags"
4991 (let ((th (js2-if-node-then-part node))
4992 (el (js2-if-node-else-part node)))
4993 (if (null th)
4994 js2-END_UNREACHED
4995 (logior (js2-end-check th) (if el
4996 (js2-end-check el)
4997 js2-END_DROPS_OFF)))))
4998
4999 (defun js2-end-check-switch (node)
5000 "Consistency of return statements is checked between the case statements.
5001 If there is no default, then the switch can fall through. If there is a
5002 default, we check to see if all code paths in the default return or if
5003 there is a code path that can fall through.
5004 Returns logical OR of END_* flags."
5005 (let ((rv js2-END_UNREACHED)
5006 default-case)
5007 ;; examine the cases
5008 (catch 'break
5009 (dolist (c (js2-switch-node-cases node))
5010 (if (js2-case-node-expr c)
5011 (js2-set-flag rv (js2-end-check-block c))
5012 (setq default-case c)
5013 (throw 'break nil))))
5014 ;; we don't care how the cases drop into each other
5015 (js2-clear-flag rv js2-END_DROPS_OFF)
5016 ;; examine the default
5017 (js2-set-flag rv (if default-case
5018 (js2-end-check default-case)
5019 js2-END_DROPS_OFF))
5020 rv))
5021
5022 (defun js2-end-check-try (node)
5023 "If the block has a finally, return consistency is checked in the
5024 finally block. If all code paths in the finally return, then the
5025 returns in the try-catch blocks don't matter. If there is a code path
5026 that does not return or if there is no finally block, the returns
5027 of the try and catch blocks are checked for mismatch.
5028 Returns logical OR of END_* flags."
5029 (let ((finally (js2-try-node-finally-block node))
5030 rv)
5031 ;; check the finally if it exists
5032 (setq rv (if finally
5033 (js2-end-check (js2-finally-node-body finally))
5034 js2-END_DROPS_OFF))
5035 ;; If the finally block always returns, then none of the returns
5036 ;; in the try or catch blocks matter.
5037 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5038 (js2-clear-flag rv js2-END_DROPS_OFF)
5039 ;; examine the try block
5040 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5041 ;; check each catch block
5042 (dolist (cb (js2-try-node-catch-clauses node))
5043 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5044 rv))
5045
5046 (defun js2-end-check-loop (node)
5047 "Return statement in the loop body must be consistent. The default
5048 assumption for any kind of a loop is that it will eventually terminate.
5049 The only exception is a loop with a constant true condition. Code that
5050 follows such a loop is examined only if one can statically determine
5051 that there is a break out of the loop.
5052
5053 for(... ; ... ; ...) {}
5054 for(... in ... ) {}
5055 while(...) { }
5056 do { } while(...)
5057
5058 Returns logical OR of END_* flags."
5059 (let ((rv (js2-end-check (js2-loop-node-body node)))
5060 (condition (cond
5061 ((js2-while-node-p node)
5062 (js2-while-node-condition node))
5063 ((js2-do-node-p node)
5064 (js2-do-node-condition node))
5065 ((js2-for-node-p node)
5066 (js2-for-node-condition node)))))
5067
5068 ;; check to see if the loop condition is always true
5069 (if (and condition
5070 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5071 (js2-clear-flag rv js2-END_DROPS_OFF))
5072
5073 ;; look for effect of breaks
5074 (js2-set-flag rv (js2-node-get-prop node
5075 'CONTROL_BLOCK_PROP
5076 js2-END_UNREACHED))
5077 rv))
5078
5079 (defun js2-end-check-block (node)
5080 "A general block of code is examined statement by statement.
5081 If any statement (even a compound one) returns in all branches, then
5082 subsequent statements are not examined.
5083 Returns logical OR of END_* flags."
5084 (let* ((rv js2-END_DROPS_OFF)
5085 (kids (js2-block-node-kids node))
5086 (n (car kids)))
5087 ;; Check each statment. If the statement can continue onto the next
5088 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5089 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5090 (js2-clear-flag rv js2-END_DROPS_OFF)
5091 (js2-set-flag rv (js2-end-check n))
5092 (setq kids (cdr kids)
5093 n (car kids)))
5094 rv))
5095
5096 (defun js2-end-check-label (node)
5097 "A labeled statement implies that there may be a break to the label.
5098 The function processes the labeled statement and then checks the
5099 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5100 particular label.
5101 Returns logical OR of END_* flags."
5102 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5103 (logior rv (js2-node-get-prop node
5104 'CONTROL_BLOCK_PROP
5105 js2-END_UNREACHED))))
5106
5107 (defun js2-end-check-break (node)
5108 "When a break is encountered annotate the statement being broken
5109 out of by setting its CONTROL_BLOCK_PROP property.
5110 Returns logical OR of END_* flags."
5111 (and (js2-break-node-target node)
5112 (js2-node-set-prop (js2-break-node-target node)
5113 'CONTROL_BLOCK_PROP
5114 js2-END_DROPS_OFF))
5115 js2-END_UNREACHED)
5116
5117 (defun js2-end-check (node)
5118 "Examine the body of a function, doing a basic reachability analysis.
5119 Returns a combination of flags END_* flags that indicate
5120 how the function execution can terminate. These constitute only the
5121 pessimistic set of termination conditions. It is possible that at
5122 runtime certain code paths will never be actually taken. Hence this
5123 analysis will flag errors in cases where there may not be errors.
5124 Returns logical OR of END_* flags"
5125 (let (kid)
5126 (cond
5127 ((js2-break-node-p node)
5128 (js2-end-check-break node))
5129 ((js2-expr-stmt-node-p node)
5130 (if (setq kid (js2-expr-stmt-node-expr node))
5131 (js2-end-check kid)
5132 js2-END_DROPS_OFF))
5133 ((or (js2-continue-node-p node)
5134 (js2-throw-node-p node))
5135 js2-END_UNREACHED)
5136 ((js2-return-node-p node)
5137 (if (setq kid (js2-return-node-retval node))
5138 js2-END_RETURNS_VALUE
5139 js2-END_RETURNS))
5140 ((js2-loop-node-p node)
5141 (js2-end-check-loop node))
5142 ((js2-switch-node-p node)
5143 (js2-end-check-switch node))
5144 ((js2-labeled-stmt-node-p node)
5145 (js2-end-check-label node))
5146 ((js2-if-node-p node)
5147 (js2-end-check-if node))
5148 ((js2-try-node-p node)
5149 (js2-end-check-try node))
5150 ((js2-block-node-p node)
5151 (if (null (js2-block-node-kids node))
5152 js2-END_DROPS_OFF
5153 (js2-end-check-block node)))
5154 ((js2-yield-node-p node)
5155 js2-END_YIELDS)
5156 (t
5157 js2-END_DROPS_OFF))))
5158
5159 (defun js2-always-defined-boolean-p (node)
5160 "Check if NODE always evaluates to true or false in boolean context.
5161 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5162 nor always false."
5163 (let ((tt (js2-node-type node))
5164 num)
5165 (cond
5166 ((or (= tt js2-FALSE) (= tt js2-NULL))
5167 'ALWAYS_FALSE)
5168 ((= tt js2-TRUE)
5169 'ALWAYS_TRUE)
5170 ((= tt js2-NUMBER)
5171 (setq num (js2-number-node-num-value node))
5172 (if (and (not (eq num 0.0e+NaN))
5173 (not (zerop num)))
5174 'ALWAYS_TRUE
5175 'ALWAYS_FALSE))
5176 (t
5177 nil))))
5178
5179 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5180 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5181
5182 (defvar js2-tokens nil
5183 "List of all defined token names.") ; initialized in `js2-token-names'
5184
5185 (defconst js2-token-names
5186 (let* ((names (make-vector js2-num-tokens -1))
5187 (case-fold-search nil) ; only match js2-UPPER_CASE
5188 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5189 (loop for sym in syms
5190 for i from 0
5191 do
5192 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5193 (not (boundp sym)))
5194 (aset names (symbol-value sym) ; code, e.g. 152
5195 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5196 (push sym js2-tokens)))
5197 names)
5198 "Vector mapping int values to token string names, sans `js2-' prefix.")
5199
5200 (defun js2-token-name (tok)
5201 "Return a string name for TOK, a token symbol or code.
5202 Signals an error if it's not a recognized token."
5203 (let ((code tok))
5204 (if (symbolp tok)
5205 (setq code (symbol-value tok)))
5206 (if (eq code -1)
5207 "ERROR"
5208 (if (and (numberp code)
5209 (not (minusp code))
5210 (< code js2-num-tokens))
5211 (aref js2-token-names code)
5212 (error "Invalid token: %s" code)))))
5213
5214 (defsubst js2-token-sym (tok)
5215 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5216 (intern (js2-token-name tok)))
5217
5218 (defconst js2-token-codes
5219 (let ((table (make-hash-table :test 'eq :size 256)))
5220 (loop for name across js2-token-names
5221 for sym = (intern (concat "js2-" name))
5222 do
5223 (puthash sym (symbol-value sym) table))
5224 ;; clean up a few that are "wrong" in Rhino's token codes
5225 (puthash 'js2-DELETE js2-DELPROP table)
5226 table)
5227 "Hashtable mapping token symbols to their bytecodes.")
5228
5229 (defsubst js2-token-code (sym)
5230 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5231 (or (gethash sym js2-token-codes)
5232 (error "Invalid token symbol: %s " sym))) ; signal code bug
5233
5234 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5235 (setq js2-token-end js2-ts-cursor)
5236 (js2-report-error msg nil
5237 (or beg js2-token-beg)
5238 (or len (- js2-token-end js2-token-beg)))
5239 (unless no-throw
5240 (throw 'return js2-ERROR)))
5241
5242 (defsubst js2-get-string-from-buffer ()
5243 "Reverse the char accumulator and return it as a string."
5244 (setq js2-token-end js2-ts-cursor)
5245 (if js2-ts-string-buffer
5246 (apply #'string (nreverse js2-ts-string-buffer))
5247 ""))
5248
5249 ;; TODO: could potentially avoid a lot of consing by allocating a
5250 ;; char buffer the way Rhino does.
5251 (defsubst js2-add-to-string (c)
5252 (push c js2-ts-string-buffer))
5253
5254 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5255 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5256 ;; any other character: when it's not part of the current token, we
5257 ;; unget it, allowing it to be read again by the following call.
5258 (defsubst js2-unget-char ()
5259 (decf js2-ts-cursor))
5260
5261 ;; Rhino distinguishes \r and \n line endings. We don't need to
5262 ;; because we only scan from Emacs buffers, which always use \n.
5263 (defsubst js2-get-char ()
5264 "Read and return the next character from the input buffer.
5265 Increments `js2-ts-lineno' if the return value is a newline char.
5266 Updates `js2-ts-cursor' to the point after the returned char.
5267 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5268 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5269 (let (c)
5270 ;; check for end of buffer
5271 (if (>= js2-ts-cursor (point-max))
5272 (setq js2-ts-hit-eof t
5273 js2-ts-cursor (1+ js2-ts-cursor)
5274 c js2-EOF_CHAR) ; return value
5275 ;; otherwise read next char
5276 (setq c (char-before (incf js2-ts-cursor)))
5277 ;; if we read a newline, update counters
5278 (if (= c ?\n)
5279 (setq js2-ts-line-start js2-ts-cursor
5280 js2-ts-lineno (1+ js2-ts-lineno)))
5281 ;; TODO: skip over format characters
5282 c)))
5283
5284 (defsubst js2-read-unicode-escape ()
5285 "Read a \\uNNNN sequence from the input.
5286 Assumes the ?\ and ?u have already been read.
5287 Returns the unicode character, or nil if it wasn't a valid character.
5288 Doesn't change the values of any scanner variables."
5289 ;; I really wish I knew a better way to do this, but I can't
5290 ;; find the Emacs function that takes a 16-bit int and converts
5291 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5292 ;; Have to first check that it's 4 hex characters or it may stop
5293 ;; the read early.
5294 (ignore-errors
5295 (let ((s (buffer-substring-no-properties js2-ts-cursor
5296 (+ 4 js2-ts-cursor))))
5297 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5298 (read (concat "?\\u" s))))))
5299
5300 (defsubst js2-match-char (test)
5301 "Consume and return next character if it matches TEST, a character.
5302 Returns nil and consumes nothing if TEST is not the next character."
5303 (let ((c (js2-get-char)))
5304 (if (eq c test)
5305 t
5306 (js2-unget-char)
5307 nil)))
5308
5309 (defsubst js2-peek-char ()
5310 (prog1
5311 (js2-get-char)
5312 (js2-unget-char)))
5313
5314 (defsubst js2-java-identifier-start-p (c)
5315 (or
5316 (memq c '(?$ ?_))
5317 (js2-char-uppercase-p c)
5318 (js2-char-lowercase-p c)))
5319
5320 (defsubst js2-java-identifier-part-p (c)
5321 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5322 ;; TODO: make me Unicode-friendly. See comments above.
5323 (or
5324 (memq c '(?$ ?_))
5325 (js2-char-uppercase-p c)
5326 (js2-char-lowercase-p c)
5327 (and (>= c ?0) (<= c ?9))))
5328
5329 (defsubst js2-alpha-p (c)
5330 (cond ((and (<= ?A c) (<= c ?Z)) t)
5331 ((and (<= ?a c) (<= c ?z)) t)
5332 (t nil)))
5333
5334 (defsubst js2-digit-p (c)
5335 (and (<= ?0 c) (<= c ?9)))
5336
5337 (defsubst js2-js-space-p (c)
5338 (if (<= c 127)
5339 (memq c '(#x20 #x9 #xB #xC #xD))
5340 (or
5341 (eq c #xA0)
5342 ;; TODO: change this nil to check for Unicode space character
5343 nil)))
5344
5345 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5346
5347 (defsubst js2-skip-line ()
5348 "Skip to end of line"
5349 (let (c)
5350 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5351 (js2-unget-char)
5352 (setq js2-token-end js2-ts-cursor)))
5353
5354 (defun js2-init-scanner (&optional buf line)
5355 "Create token stream for BUF starting on LINE.
5356 BUF defaults to current-buffer and line defaults to 1.
5357
5358 A buffer can only have one scanner active at a time, which yields
5359 dramatically simpler code than using a defstruct. If you need to
5360 have simultaneous scanners in a buffer, copy the regions to scan
5361 into temp buffers."
5362 (save-excursion
5363 (when buf
5364 (set-buffer buf))
5365 (setq js2-ts-dirty-line nil
5366 js2-ts-regexp-flags nil
5367 js2-ts-string ""
5368 js2-ts-number nil
5369 js2-ts-hit-eof nil
5370 js2-ts-line-start 0
5371 js2-ts-lineno (or line 1)
5372 js2-ts-line-end-char -1
5373 js2-ts-cursor (point-min)
5374 js2-ts-is-xml-attribute nil
5375 js2-ts-xml-is-tag-content nil
5376 js2-ts-xml-open-tags-count 0
5377 js2-ts-string-buffer nil)))
5378
5379 ;; This function uses the cached op, string and number fields in
5380 ;; TokenStream; if getToken has been called since the passed token
5381 ;; was scanned, the op or string printed may be incorrect.
5382 (defun js2-token-to-string (token)
5383 ;; Not sure where this function is used in Rhino. Not tested.
5384 (if (not js2-debug-print-trees)
5385 ""
5386 (let ((name (js2-token-name token)))
5387 (cond
5388 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5389 (concat name " `" js2-ts-string "'"))
5390 ((eq token js2-NUMBER)
5391 (format "NUMBER %g" js2-ts-number))
5392 (t
5393 name)))))
5394
5395 (defconst js2-keywords
5396 '(break
5397 case catch const continue
5398 debugger default delete do
5399 else enum
5400 false finally for function
5401 if in instanceof import
5402 let
5403 new null
5404 return
5405 switch
5406 this throw true try typeof
5407 var void
5408 while with
5409 yield))
5410
5411 ;; Token names aren't exactly the same as the keywords, unfortunately.
5412 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5413 (defconst js2-kwd-tokens
5414 (let ((table (make-vector js2-num-tokens nil))
5415 (tokens
5416 (list js2-BREAK
5417 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5418 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5419 js2-ELSE
5420 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5421 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5422 js2-LET
5423 js2-NEW js2-NULL
5424 js2-RETURN
5425 js2-SWITCH
5426 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5427 js2-VAR
5428 js2-WHILE js2-WITH
5429 js2-YIELD)))
5430 (dolist (i tokens)
5431 (aset table i 'font-lock-keyword-face))
5432 (aset table js2-STRING 'font-lock-string-face)
5433 (aset table js2-REGEXP 'font-lock-string-face)
5434 (aset table js2-COMMENT 'font-lock-comment-face)
5435 (aset table js2-THIS 'font-lock-builtin-face)
5436 (aset table js2-VOID 'font-lock-constant-face)
5437 (aset table js2-NULL 'font-lock-constant-face)
5438 (aset table js2-TRUE 'font-lock-constant-face)
5439 (aset table js2-FALSE 'font-lock-constant-face)
5440 table)
5441 "Vector whose values are non-nil for tokens that are keywords.
5442 The values are default faces to use for highlighting the keywords.")
5443
5444 (defconst js2-reserved-words
5445 '(abstract
5446 boolean byte
5447 char class
5448 double
5449 enum export extends
5450 final float
5451 goto
5452 implements import int interface
5453 long
5454 native
5455 package private protected public
5456 short static super synchronized
5457 throws transient
5458 volatile))
5459
5460 (defconst js2-keyword-names
5461 (let ((table (make-hash-table :test 'equal)))
5462 (loop for k in js2-keywords
5463 do (puthash
5464 (symbol-name k) ; instanceof
5465 (intern (concat "js2-"
5466 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5467 table))
5468 table)
5469 "JavaScript keywords by name, mapped to their symbols.")
5470
5471 (defconst js2-reserved-word-names
5472 (let ((table (make-hash-table :test 'equal)))
5473 (loop for k in js2-reserved-words
5474 do
5475 (puthash (symbol-name k) 'js2-RESERVED table))
5476 table)
5477 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5478
5479 (defsubst js2-collect-string (buf)
5480 "Convert BUF, a list of chars, to a string.
5481 Reverses BUF before converting."
5482 (cond
5483 ((stringp buf)
5484 buf)
5485 ((null buf) ; for emacs21 compat
5486 "")
5487 (t
5488 (if buf
5489 (apply #'string (nreverse buf))
5490 ""))))
5491
5492 (defun js2-string-to-keyword (s)
5493 "Return token for S, a string, if S is a keyword or reserved word.
5494 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5495 (or (gethash s js2-keyword-names)
5496 (gethash s js2-reserved-word-names)))
5497
5498 (defsubst js2-ts-set-char-token-bounds ()
5499 "Used when next token is one character."
5500 (setq js2-token-beg (1- js2-ts-cursor)
5501 js2-token-end js2-ts-cursor))
5502
5503 (defsubst js2-ts-return (token)
5504 "Return an N-character TOKEN from `js2-get-token'.
5505 Updates `js2-token-end' accordingly."
5506 (setq js2-token-end js2-ts-cursor)
5507 (throw 'return token))
5508
5509 (defsubst js2-x-digit-to-int (c accumulator)
5510 "Build up a hex number.
5511 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5512 corresponding number. Otherwise return -1."
5513 (catch 'return
5514 (catch 'check
5515 ;; Use 0..9 < A..Z < a..z
5516 (cond
5517 ((<= c ?9)
5518 (decf c ?0)
5519 (if (<= 0 c)
5520 (throw 'check nil)))
5521 ((<= c ?F)
5522 (when (<= ?A c)
5523 (decf c (- ?A 10))
5524 (throw 'check nil)))
5525 ((<= c ?f)
5526 (when (<= ?a c)
5527 (decf c (- ?a 10))
5528 (throw 'check nil))))
5529 (throw 'return -1))
5530 (logior c (lsh accumulator 4))))
5531
5532 (defun js2-get-token ()
5533 "Return next JavaScript token, an int such as js2-RETURN."
5534 (let (c
5535 c1
5536 identifier-start
5537 is-unicode-escape-start
5538 contains-escape
5539 escape-val
5540 escape-start
5541 str
5542 result
5543 base
5544 is-integer
5545 quote-char
5546 val
5547 look-for-slash
5548 continue)
5549 (catch 'return
5550 (while t
5551 ;; Eat whitespace, possibly sensitive to newlines.
5552 (setq continue t)
5553 (while continue
5554 (setq c (js2-get-char))
5555 (cond
5556 ((eq c js2-EOF_CHAR)
5557 (js2-ts-set-char-token-bounds)
5558 (throw 'return js2-EOF))
5559 ((eq c ?\n)
5560 (js2-ts-set-char-token-bounds)
5561 (setq js2-ts-dirty-line nil)
5562 (throw 'return js2-EOL))
5563 ((not (js2-js-space-p c))
5564 (if (/= c ?-) ; in case end of HTML comment
5565 (setq js2-ts-dirty-line t))
5566 (setq continue nil))))
5567 ;; Assume the token will be 1 char - fixed up below.
5568 (js2-ts-set-char-token-bounds)
5569 (when (eq c ?@)
5570 (throw 'return js2-XMLATTR))
5571 ;; identifier/keyword/instanceof?
5572 ;; watch out for starting with a <backslash>
5573 (cond
5574 ((eq c ?\\)
5575 (setq c (js2-get-char))
5576 (if (eq c ?u)
5577 (setq identifier-start t
5578 is-unicode-escape-start t
5579 js2-ts-string-buffer nil)
5580 (setq identifier-start nil)
5581 (js2-unget-char)
5582 (setq c ?\\)))
5583 (t
5584 (when (setq identifier-start (js2-java-identifier-start-p c))
5585 (setq js2-ts-string-buffer nil)
5586 (js2-add-to-string c))))
5587 (when identifier-start
5588 (setq contains-escape is-unicode-escape-start)
5589 (catch 'break
5590 (while t
5591 (if is-unicode-escape-start
5592 ;; strictly speaking we should probably push-back
5593 ;; all the bad characters if the <backslash>uXXXX
5594 ;; sequence is malformed. But since there isn't a
5595 ;; correct context(is there?) for a bad Unicode
5596 ;; escape sequence in an identifier, we can report
5597 ;; an error here.
5598 (progn
5599 (setq escape-val 0)
5600 (dotimes (i 4)
5601 (setq c (js2-get-char)
5602 escape-val (js2-x-digit-to-int c escape-val))
5603 ;; Next check takes care of c < 0 and bad escape
5604 (if (minusp escape-val)
5605 (throw 'break nil)))
5606 (if (minusp escape-val)
5607 (js2-report-scan-error "msg.invalid.escape" t))
5608 (js2-add-to-string escape-val)
5609 (setq is-unicode-escape-start nil))
5610 (setq c (js2-get-char))
5611 (cond
5612 ((eq c ?\\)
5613 (setq c (js2-get-char))
5614 (if (eq c ?u)
5615 (setq is-unicode-escape-start t
5616 contains-escape t)
5617 (js2-report-scan-error "msg.illegal.character" t)))
5618 (t
5619 (if (or (eq c js2-EOF_CHAR)
5620 (not (js2-java-identifier-part-p c)))
5621 (throw 'break nil))
5622 (js2-add-to-string c))))))
5623 (js2-unget-char)
5624 (setq str (js2-get-string-from-buffer))
5625 (unless contains-escape
5626 ;; OPT we shouldn't have to make a string (object!) to
5627 ;; check if it's a keyword.
5628 ;; Return the corresponding token if it's a keyword
5629 (when (setq result (js2-string-to-keyword str))
5630 (if (and (< js2-language-version 170)
5631 (memq result '(js2-LET js2-YIELD)))
5632 ;; LET and YIELD are tokens only in 1.7 and later
5633 (setq result 'js2-NAME))
5634 (if (not (eq result 'js2-RESERVED))
5635 (throw 'return (js2-token-code result)))
5636 (js2-report-warning "msg.reserved.keyword" str)))
5637 ;; If we want to intern these as Rhino does, just use (intern str)
5638 (setq js2-ts-string str)
5639 (throw 'return js2-NAME)) ; end identifier/kwd check
5640 ;; is it a number?
5641 (when (or (js2-digit-p c)
5642 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5643 (setq js2-ts-string-buffer nil
5644 base 10)
5645 (when (eq c ?0)
5646 (setq c (js2-get-char))
5647 (cond
5648 ((or (eq c ?x) (eq c ?X))
5649 (setq base 16)
5650 (setq c (js2-get-char)))
5651 ((js2-digit-p c)
5652 (setq base 8))
5653 (t
5654 (js2-add-to-string ?0))))
5655 (if (eq base 16)
5656 (while (<= 0 (js2-x-digit-to-int c 0))
5657 (js2-add-to-string c)
5658 (setq c (js2-get-char)))
5659 (while (and (<= ?0 c) (<= c ?9))
5660 ;; We permit 08 and 09 as decimal numbers, which
5661 ;; makes our behavior a superset of the ECMA
5662 ;; numeric grammar. We might not always be so
5663 ;; permissive, so we warn about it.
5664 (when (and (eq base 8) (>= c ?8))
5665 (js2-report-warning "msg.bad.octal.literal"
5666 (if (eq c ?8) "8" "9"))
5667 (setq base 10))
5668 (js2-add-to-string c)
5669 (setq c (js2-get-char))))
5670 (setq is-integer t)
5671 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5672 (setq is-integer nil)
5673 (when (eq c ?.)
5674 (loop do
5675 (js2-add-to-string c)
5676 (setq c (js2-get-char))
5677 while (js2-digit-p c)))
5678 (when (memq c '(?e ?E))
5679 (js2-add-to-string c)
5680 (setq c (js2-get-char))
5681 (when (memq c '(?+ ?-))
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char)))
5684 (unless (js2-digit-p c)
5685 (js2-report-scan-error "msg.missing.exponent" t))
5686 (loop do
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 while (js2-digit-p c))))
5690 (js2-unget-char)
5691 (setq js2-ts-string (js2-get-string-from-buffer)
5692 js2-ts-number
5693 (if (and (eq base 10) (not is-integer))
5694 (string-to-number js2-ts-string)
5695 ;; TODO: call runtime number-parser. Some of it is in
5696 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5697 (string-to-number js2-ts-string)))
5698 (throw 'return js2-NUMBER))
5699 ;; is it a string?
5700 (when (memq c '(?\" ?\'))
5701 ;; We attempt to accumulate a string the fast way, by
5702 ;; building it directly out of the reader. But if there
5703 ;; are any escaped characters in the string, we revert to
5704 ;; building it out of a string buffer.
5705 (setq quote-char c
5706 js2-ts-string-buffer nil
5707 c (js2-get-char))
5708 (catch 'break
5709 (while (/= c quote-char)
5710 (catch 'continue
5711 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5712 (js2-unget-char)
5713 (setq js2-token-end js2-ts-cursor)
5714 (js2-report-error "msg.unterminated.string.lit")
5715 (throw 'return js2-STRING))
5716 (when (eq c ?\\)
5717 ;; We've hit an escaped character
5718 (setq c (js2-get-char))
5719 (case c
5720 (?b (setq c ?\b))
5721 (?f (setq c ?\f))
5722 (?n (setq c ?\n))
5723 (?r (setq c ?\r))
5724 (?t (setq c ?\t))
5725 (?v (setq c ?\v))
5726 (?u
5727 (setq c1 (js2-read-unicode-escape))
5728 (if js2-parse-ide-mode
5729 (if c1
5730 (progn
5731 ;; just copy the string in IDE-mode
5732 (js2-add-to-string ?\\)
5733 (js2-add-to-string ?u)
5734 (dotimes (i 3)
5735 (js2-add-to-string (js2-get-char)))
5736 (setq c (js2-get-char))) ; added at end of loop
5737 ;; flag it as an invalid escape
5738 (js2-report-warning "msg.invalid.escape"
5739 nil (- js2-ts-cursor 2) 6))
5740 ;; Get 4 hex digits; if the u escape is not
5741 ;; followed by 4 hex digits, use 'u' + the
5742 ;; literal character sequence that follows.
5743 (js2-add-to-string ?u)
5744 (setq escape-val 0)
5745 (dotimes (i 4)
5746 (setq c (js2-get-char)
5747 escape-val (js2-x-digit-to-int c escape-val))
5748 (if (minusp escape-val)
5749 (throw 'continue nil))
5750 (js2-add-to-string c))
5751 ;; prepare for replace of stored 'u' sequence by escape value
5752 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5753 c escape-val)))
5754 (?x
5755 ;; Get 2 hex digits, defaulting to 'x'+literal
5756 ;; sequence, as above.
5757 (setq c (js2-get-char)
5758 escape-val (js2-x-digit-to-int c 0))
5759 (if (minusp escape-val)
5760 (progn
5761 (js2-add-to-string ?x)
5762 (throw 'continue nil))
5763 (setq c1 c
5764 c (js2-get-char)
5765 escape-val (js2-x-digit-to-int c escape-val))
5766 (if (minusp escape-val)
5767 (progn
5768 (js2-add-to-string ?x)
5769 (js2-add-to-string c1)
5770 (throw 'continue nil))
5771 ;; got 2 hex digits
5772 (setq c escape-val))))
5773 (?\n
5774 ;; Remove line terminator after escape to follow
5775 ;; SpiderMonkey and C/C++
5776 (setq c (js2-get-char))
5777 (throw 'continue nil))
5778 (t
5779 (when (and (<= ?0 c) (< c ?8))
5780 (setq val (- c ?0)
5781 c (js2-get-char))
5782 (when (and (<= ?0 c) (< c ?8))
5783 (setq val (- (+ (* 8 val) c) ?0)
5784 c (js2-get-char))
5785 (when (and (<= ?0 c)
5786 (< c ?8)
5787 (< val #o37))
5788 ;; c is 3rd char of octal sequence only
5789 ;; if the resulting val <= 0377
5790 (setq val (- (+ (* 8 val) c) ?0)
5791 c (js2-get-char))))
5792 (js2-unget-char)
5793 (setq c val)))))
5794 (js2-add-to-string c)
5795 (setq c (js2-get-char)))))
5796 (setq js2-ts-string (js2-get-string-from-buffer))
5797 (throw 'return js2-STRING))
5798 (case c
5799 (?\;
5800 (throw 'return js2-SEMI))
5801 (?\[
5802 (throw 'return js2-LB))
5803 (?\]
5804 (throw 'return js2-RB))
5805 (?{
5806 (throw 'return js2-LC))
5807 (?}
5808 (throw 'return js2-RC))
5809 (?\(
5810 (throw 'return js2-LP))
5811 (?\)
5812 (throw 'return js2-RP))
5813 (?,
5814 (throw 'return js2-COMMA))
5815 (??
5816 (throw 'return js2-HOOK))
5817 (?:
5818 (if (js2-match-char ?:)
5819 (js2-ts-return js2-COLONCOLON)
5820 (throw 'return js2-COLON)))
5821 (?.
5822 (if (js2-match-char ?.)
5823 (js2-ts-return js2-DOTDOT)
5824 (if (js2-match-char ?\()
5825 (js2-ts-return js2-DOTQUERY)
5826 (throw 'return js2-DOT))))
5827 (?|
5828 (if (js2-match-char ?|)
5829 (throw 'return js2-OR)
5830 (if (js2-match-char ?=)
5831 (js2-ts-return js2-ASSIGN_BITOR)
5832 (throw 'return js2-BITOR))))
5833 (?^
5834 (if (js2-match-char ?=)
5835 (js2-ts-return js2-ASSIGN_BITOR)
5836 (throw 'return js2-BITXOR)))
5837 (?&
5838 (if (js2-match-char ?&)
5839 (throw 'return js2-AND)
5840 (if (js2-match-char ?=)
5841 (js2-ts-return js2-ASSIGN_BITAND)
5842 (throw 'return js2-BITAND))))
5843 (?=
5844 (if (js2-match-char ?=)
5845 (if (js2-match-char ?=)
5846 (js2-ts-return js2-SHEQ)
5847 (throw 'return js2-EQ))
5848 (throw 'return js2-ASSIGN)))
5849 (?!
5850 (if (js2-match-char ?=)
5851 (if (js2-match-char ?=)
5852 (js2-ts-return js2-SHNE)
5853 (js2-ts-return js2-NE))
5854 (throw 'return js2-NOT)))
5855 (?<
5856 ;; NB:treat HTML begin-comment as comment-till-eol
5857 (when (js2-match-char ?!)
5858 (when (js2-match-char ?-)
5859 (when (js2-match-char ?-)
5860 (js2-skip-line)
5861 (setq js2-ts-comment-type 'html)
5862 (throw 'return js2-COMMENT)))
5863 (js2-unget-char))
5864 (if (js2-match-char ?<)
5865 (if (js2-match-char ?=)
5866 (js2-ts-return js2-ASSIGN_LSH)
5867 (js2-ts-return js2-LSH))
5868 (if (js2-match-char ?=)
5869 (js2-ts-return js2-LE)
5870 (throw 'return js2-LT))))
5871 (?>
5872 (if (js2-match-char ?>)
5873 (if (js2-match-char ?>)
5874 (if (js2-match-char ?=)
5875 (js2-ts-return js2-ASSIGN_URSH)
5876 (js2-ts-return js2-URSH))
5877 (if (js2-match-char ?=)
5878 (js2-ts-return js2-ASSIGN_RSH)
5879 (js2-ts-return js2-RSH)))
5880 (if (js2-match-char ?=)
5881 (js2-ts-return js2-GE)
5882 (throw 'return js2-GT))))
5883 (?*
5884 (if (js2-match-char ?=)
5885 (js2-ts-return js2-ASSIGN_MUL)
5886 (throw 'return js2-MUL)))
5887 (?/
5888 ;; is it a // comment?
5889 (when (js2-match-char ?/)
5890 (setq js2-token-beg (- js2-ts-cursor 2))
5891 (js2-skip-line)
5892 (setq js2-ts-comment-type 'line)
5893 ;; include newline so highlighting goes to end of window
5894 (incf js2-token-end)
5895 (throw 'return js2-COMMENT))
5896 ;; is it a /* comment?
5897 (when (js2-match-char ?*)
5898 (setq look-for-slash nil
5899 js2-token-beg (- js2-ts-cursor 2)
5900 js2-ts-comment-type
5901 (if (js2-match-char ?*)
5902 (progn
5903 (setq look-for-slash t)
5904 'jsdoc)
5905 'block))
5906 (while t
5907 (setq c (js2-get-char))
5908 (cond
5909 ((eq c js2-EOF_CHAR)
5910 (setq js2-token-end (1- js2-ts-cursor))
5911 (js2-report-error "msg.unterminated.comment")
5912 (throw 'return js2-COMMENT))
5913 ((eq c ?*)
5914 (setq look-for-slash t))
5915 ((eq c ?/)
5916 (if look-for-slash
5917 (js2-ts-return js2-COMMENT)))
5918 (t
5919 (setq look-for-slash nil
5920 js2-token-end js2-ts-cursor)))))
5921 (if (js2-match-char ?=)
5922 (js2-ts-return js2-ASSIGN_DIV)
5923 (throw 'return js2-DIV)))
5924 (?#
5925 (when js2-skip-preprocessor-directives
5926 (js2-skip-line)
5927 (setq js2-ts-comment-type 'preprocessor
5928 js2-token-end js2-ts-cursor)
5929 (throw 'return js2-COMMENT))
5930 (throw 'return js2-ERROR))
5931 (?%
5932 (if (js2-match-char ?=)
5933 (js2-ts-return js2-ASSIGN_MOD)
5934 (throw 'return js2-MOD)))
5935 (?~
5936 (throw 'return js2-BITNOT))
5937 (?+
5938 (if (js2-match-char ?=)
5939 (js2-ts-return js2-ASSIGN_ADD)
5940 (if (js2-match-char ?+)
5941 (js2-ts-return js2-INC)
5942 (throw 'return js2-ADD))))
5943 (?-
5944 (cond
5945 ((js2-match-char ?=)
5946 (setq c js2-ASSIGN_SUB))
5947 ((js2-match-char ?-)
5948 (unless js2-ts-dirty-line
5949 ;; treat HTML end-comment after possible whitespace
5950 ;; after line start as comment-until-eol
5951 (when (js2-match-char ?>)
5952 (js2-skip-line)
5953 (setq js2-ts-comment-type 'html)
5954 (throw 'return js2-COMMENT)))
5955 (setq c js2-DEC))
5956 (t
5957 (setq c js2-SUB)))
5958 (setq js2-ts-dirty-line t)
5959 (js2-ts-return c))
5960 (otherwise
5961 (js2-report-scan-error "msg.illegal.character")))))))
5962
5963 (defun js2-read-regexp (start-token)
5964 "Called by parser when it gets / or /= in literal context."
5965 (let (c
5966 err
5967 in-class ; inside a '[' .. ']' character-class
5968 flags
5969 (continue t))
5970 (setq js2-token-beg js2-ts-cursor
5971 js2-ts-string-buffer nil
5972 js2-ts-regexp-flags nil)
5973 (if (eq start-token js2-ASSIGN_DIV)
5974 ;; mis-scanned /=
5975 (js2-add-to-string ?=)
5976 (if (not (eq start-token js2-DIV))
5977 (error "failed assertion")))
5978 (while (and (not err)
5979 (or (/= (setq c (js2-get-char)) ?/)
5980 in-class))
5981 (cond
5982 ((or (= c ?\n)
5983 (= c js2-EOF_CHAR))
5984 (setq js2-token-end (1- js2-ts-cursor)
5985 err t
5986 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5987 (js2-report-error "msg.unterminated.re.lit"))
5988 (t (cond
5989 ((= c ?\\)
5990 (js2-add-to-string c)
5991 (setq c (js2-get-char)))
5992 ((= c ?\[)
5993 (setq in-class t))
5994 ((= c ?\])
5995 (setq in-class nil)))
5996 (js2-add-to-string c))))
5997 (unless err
5998 (while continue
5999 (cond
6000 ((js2-match-char ?g)
6001 (push ?g flags))
6002 ((js2-match-char ?i)
6003 (push ?i flags))
6004 ((js2-match-char ?m)
6005 (push ?m flags))
6006 (t
6007 (setq continue nil))))
6008 (if (js2-alpha-p (js2-peek-char))
6009 (js2-report-scan-error "msg.invalid.re.flag" t
6010 js2-ts-cursor 1))
6011 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6012 js2-ts-regexp-flags (js2-collect-string flags)
6013 js2-token-end js2-ts-cursor)
6014 ;; tell `parse-partial-sexp' to ignore this range of chars
6015 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6016
6017 (defun js2-get-first-xml-token ()
6018 (setq js2-ts-xml-open-tags-count 0
6019 js2-ts-is-xml-attribute nil
6020 js2-ts-xml-is-tag-content nil)
6021 (js2-unget-char)
6022 (js2-get-next-xml-token))
6023
6024 (defsubst js2-xml-discard-string ()
6025 "Throw away the string in progress and flag an XML parse error."
6026 (setq js2-ts-string-buffer nil
6027 js2-ts-string nil)
6028 (js2-report-scan-error "msg.XML.bad.form" t))
6029
6030 (defun js2-get-next-xml-token ()
6031 (setq js2-ts-string-buffer nil ; for recording the XML
6032 js2-token-beg js2-ts-cursor)
6033 (let (c result)
6034 (setq result
6035 (catch 'return
6036 (while t
6037 (setq c (js2-get-char))
6038 (cond
6039 ((= c js2-EOF_CHAR)
6040 (throw 'return js2-ERROR))
6041 (js2-ts-xml-is-tag-content
6042 (case c
6043 (?>
6044 (js2-add-to-string c)
6045 (setq js2-ts-xml-is-tag-content nil
6046 js2-ts-is-xml-attribute nil))
6047 (?/
6048 (js2-add-to-string c)
6049 (when (eq ?> (js2-peek-char))
6050 (setq c (js2-get-char))
6051 (js2-add-to-string c)
6052 (setq js2-ts-xml-is-tag-content nil)
6053 (decf js2-ts-xml-open-tags-count)))
6054 (?{
6055 (js2-unget-char)
6056 (setq js2-ts-string (js2-get-string-from-buffer))
6057 (throw 'return js2-XML))
6058 ((?\' ?\")
6059 (js2-add-to-string c)
6060 (unless (js2-read-quoted-string c)
6061 (throw 'return js2-ERROR)))
6062 (?=
6063 (js2-add-to-string c)
6064 (setq js2-ts-is-xml-attribute t))
6065 ((? ?\t ?\r ?\n)
6066 (js2-add-to-string c))
6067 (t
6068 (js2-add-to-string c)
6069 (setq js2-ts-is-xml-attribute nil)))
6070 (when (and (not js2-ts-xml-is-tag-content)
6071 (zerop js2-ts-xml-open-tags-count))
6072 (setq js2-ts-string (js2-get-string-from-buffer))
6073 (throw 'return js2-XMLEND)))
6074 (t
6075 ;; else not tag content
6076 (case c
6077 (?<
6078 (js2-add-to-string c)
6079 (setq c (js2-peek-char))
6080 (case c
6081 (?!
6082 (setq c (js2-get-char)) ;; skip !
6083 (js2-add-to-string c)
6084 (setq c (js2-peek-char))
6085 (case c
6086 (?-
6087 (setq c (js2-get-char)) ;; skip -
6088 (js2-add-to-string c)
6089 (if (eq c ?-)
6090 (progn
6091 (js2-add-to-string c)
6092 (unless (js2-read-xml-comment)
6093 (throw 'return js2-ERROR)))
6094 (js2-xml-discard-string)
6095 (throw 'return js2-ERROR)))
6096 (?\[
6097 (setq c (js2-get-char)) ;; skip [
6098 (js2-add-to-string c)
6099 (if (and (= (js2-get-char) ?C)
6100 (= (js2-get-char) ?D)
6101 (= (js2-get-char) ?A)
6102 (= (js2-get-char) ?T)
6103 (= (js2-get-char) ?A)
6104 (= (js2-get-char) ?\[))
6105 (progn
6106 (js2-add-to-string ?C)
6107 (js2-add-to-string ?D)
6108 (js2-add-to-string ?A)
6109 (js2-add-to-string ?T)
6110 (js2-add-to-string ?A)
6111 (js2-add-to-string ?\[)
6112 (unless (js2-read-cdata)
6113 (throw 'return js2-ERROR)))
6114 (js2-xml-discard-string)
6115 (throw 'return js2-ERROR)))
6116 (t
6117 (unless (js2-read-entity)
6118 (throw 'return js2-ERROR)))))
6119 (??
6120 (setq c (js2-get-char)) ;; skip ?
6121 (js2-add-to-string c)
6122 (unless (js2-read-PI)
6123 (throw 'return js2-ERROR)))
6124 (?/
6125 ;; end tag
6126 (setq c (js2-get-char)) ;; skip /
6127 (js2-add-to-string c)
6128 (when (zerop js2-ts-xml-open-tags-count)
6129 (js2-xml-discard-string)
6130 (throw 'return js2-ERROR))
6131 (setq js2-ts-xml-is-tag-content t)
6132 (decf js2-ts-xml-open-tags-count))
6133 (t
6134 ;; start tag
6135 (setq js2-ts-xml-is-tag-content t)
6136 (incf js2-ts-xml-open-tags-count))))
6137 (?{
6138 (js2-unget-char)
6139 (setq js2-ts-string (js2-get-string-from-buffer))
6140 (throw 'return js2-XML))
6141 (t
6142 (js2-add-to-string c))))))))
6143 (setq js2-token-end js2-ts-cursor)
6144 result))
6145
6146 (defun js2-read-quoted-string (quote)
6147 (let (c)
6148 (catch 'return
6149 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6150 (js2-add-to-string c)
6151 (if (eq c quote)
6152 (throw 'return t)))
6153 (js2-xml-discard-string) ;; throw away string in progress
6154 nil)))
6155
6156 (defun js2-read-xml-comment ()
6157 (let ((c (js2-get-char)))
6158 (catch 'return
6159 (while (/= c js2-EOF_CHAR)
6160 (catch 'continue
6161 (js2-add-to-string c)
6162 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6163 (setq c (js2-get-char))
6164 (js2-add-to-string c)
6165 (if (eq (js2-peek-char) ?>)
6166 (progn
6167 (setq c (js2-get-char)) ;; skip >
6168 (js2-add-to-string c)
6169 (throw 'return t))
6170 (throw 'continue nil)))
6171 (setq c (js2-get-char))))
6172 (js2-xml-discard-string)
6173 nil)))
6174
6175 (defun js2-read-cdata ()
6176 (let ((c (js2-get-char)))
6177 (catch 'return
6178 (while (/= c js2-EOF_CHAR)
6179 (catch 'continue
6180 (js2-add-to-string c)
6181 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6182 (setq c (js2-get-char))
6183 (js2-add-to-string c)
6184 (if (eq (js2-peek-char) ?>)
6185 (progn
6186 (setq c (js2-get-char)) ;; Skip >
6187 (js2-add-to-string c)
6188 (throw 'return t))
6189 (throw 'continue nil)))
6190 (setq c (js2-get-char))))
6191 (js2-xml-discard-string)
6192 nil)))
6193
6194 (defun js2-read-entity ()
6195 (let ((decl-tags 1)
6196 c)
6197 (catch 'return
6198 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6199 (js2-add-to-string c)
6200 (case c
6201 (?<
6202 (incf decl-tags))
6203 (?>
6204 (decf decl-tags)
6205 (if (zerop decl-tags)
6206 (throw 'return t)))))
6207 (js2-xml-discard-string)
6208 nil)))
6209
6210 (defun js2-read-PI ()
6211 "Scan an XML processing instruction."
6212 (let (c)
6213 (catch 'return
6214 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6215 (js2-add-to-string c)
6216 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6217 (setq c (js2-get-char)) ;; Skip >
6218 (js2-add-to-string c)
6219 (throw 'return t)))
6220 (js2-xml-discard-string)
6221 nil)))
6222
6223 (defun js2-scanner-get-line ()
6224 "Return the text of the current scan line."
6225 (buffer-substring (point-at-bol) (point-at-eol)))
6226
6227 ;;; Highlighting
6228
6229 (defsubst js2-set-face (beg end face &optional record)
6230 "Fontify a region. If RECORD is non-nil, record for later."
6231 (when (plusp js2-highlight-level)
6232 (setq beg (min (point-max) beg)
6233 beg (max (point-min) beg)
6234 end (min (point-max) end)
6235 end (max (point-min) end))
6236 (if record
6237 (push (list beg end face) js2-mode-fontifications)
6238 (put-text-property beg end 'face face))))
6239
6240 (defsubst js2-set-kid-face (pos kid len face)
6241 "Set-face on a child node.
6242 POS is absolute buffer position of parent.
6243 KID is the child node.
6244 LEN is the length to fontify.
6245 FACE is the face to fontify with."
6246 (js2-set-face (+ pos (js2-node-pos kid))
6247 (+ pos (js2-node-pos kid) (js2-node-len kid))
6248 face))
6249
6250 (defsubst js2-fontify-kwd (start length)
6251 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6252
6253 (defsubst js2-clear-face (beg end)
6254 (remove-text-properties beg end '(face nil
6255 help-echo nil
6256 point-entered nil
6257 c-in-sws nil)))
6258
6259 (defsubst js2-record-text-property (beg end prop value)
6260 "Record a text property to set when parsing finishes."
6261 (push (list beg end prop value) js2-mode-deferred-properties))
6262
6263 (defconst js2-ecma-global-props
6264 (concat "^"
6265 (regexp-opt
6266 '("Infinity" "NaN" "undefined" "arguments") t)
6267 "$")
6268 "Value properties of the Ecma-262 Global Object.
6269 Shown at or above `js2-highlight-level' 2.")
6270
6271 ;; might want to add the name "arguments" to this list?
6272 (defconst js2-ecma-object-props
6273 (concat "^"
6274 (regexp-opt
6275 '("prototype" "__proto__" "__parent__") t)
6276 "$")
6277 "Value properties of the Ecma-262 Object constructor.
6278 Shown at or above `js2-highlight-level' 2.")
6279
6280 (defconst js2-ecma-global-funcs
6281 (concat
6282 "^"
6283 (regexp-opt
6284 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6285 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6286 "$")
6287 "Function properties of the Ecma-262 Global object.
6288 Shown at or above `js2-highlight-level' 2.")
6289
6290 (defconst js2-ecma-number-props
6291 (concat "^"
6292 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6293 "NEGATIVE_INFINITY"
6294 "POSITIVE_INFINITY") t)
6295 "$")
6296 "Properties of the Ecma-262 Number constructor.
6297 Shown at or above `js2-highlight-level' 2.")
6298
6299 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6300 "Properties of the Ecma-262 Date constructor.
6301 Shown at or above `js2-highlight-level' 2.")
6302
6303 (defconst js2-ecma-math-props
6304 (concat "^"
6305 (regexp-opt
6306 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6307 t)
6308 "$")
6309 "Properties of the Ecma-262 Math object.
6310 Shown at or above `js2-highlight-level' 2.")
6311
6312 (defconst js2-ecma-math-funcs
6313 (concat "^"
6314 (regexp-opt
6315 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6316 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6317 "$")
6318 "Function properties of the Ecma-262 Math object.
6319 Shown at or above `js2-highlight-level' 2.")
6320
6321 (defconst js2-ecma-function-props
6322 (concat
6323 "^"
6324 (regexp-opt
6325 '(;; properties of the Object prototype object
6326 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6327 "toLocaleString" "toString" "valueOf"
6328 ;; properties of the Function prototype object
6329 "apply" "call"
6330 ;; properties of the Array prototype object
6331 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6332 "splice" "unshift"
6333 ;; properties of the String prototype object
6334 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6335 "localeCompare" "match" "replace" "search" "split" "substring"
6336 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6337 "toUpperCase"
6338 ;; properties of the Number prototype object
6339 "toExponential" "toFixed" "toPrecision"
6340 ;; properties of the Date prototype object
6341 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6342 "getMinutes" "getMonth" "getSeconds" "getTime"
6343 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6344 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6345 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6346 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6347 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6348 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6349 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6350 "toTimeString" "toUTCString"
6351 ;; properties of the RegExp prototype object
6352 "exec" "test"
6353 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6354 "toSource" "__defineGetter__" "__defineSetter__"
6355 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6356 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6357 t)
6358 "$")
6359 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6360 Shown at or above `js2-highlight-level' 3.")
6361
6362 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6363 (let ((target-name (and target
6364 (js2-name-node-p target)
6365 (js2-name-node-name target)))
6366 (prop-name (if prop (js2-name-node-name prop)))
6367 (level1 (>= js2-highlight-level 1))
6368 (level2 (>= js2-highlight-level 2))
6369 (level3 (>= js2-highlight-level 3))
6370 pos
6371 face)
6372 (when level2
6373 (if call-p
6374 (cond
6375 ((and target prop)
6376 (cond
6377 ((and level3 (string-match js2-ecma-function-props prop-name))
6378 (setq face 'font-lock-builtin-face))
6379 ((and target-name prop)
6380 (cond
6381 ((string= target-name "Date")
6382 (if (string-match js2-ecma-date-props prop-name)
6383 (setq face 'font-lock-builtin-face)))
6384 ((string= target-name "Math")
6385 (if (string-match js2-ecma-math-funcs prop-name)
6386 (setq face 'font-lock-builtin-face)))))))
6387 (prop
6388 (if (string-match js2-ecma-global-funcs prop-name)
6389 (setq face 'font-lock-builtin-face))))
6390 (cond
6391 ((and target prop)
6392 (cond
6393 ((string= target-name "Number")
6394 (if (string-match js2-ecma-number-props prop-name)
6395 (setq face 'font-lock-constant-face)))
6396 ((string= target-name "Math")
6397 (if (string-match js2-ecma-math-props prop-name)
6398 (setq face 'font-lock-constant-face)))))
6399 (prop
6400 (if (string-match js2-ecma-object-props prop-name)
6401 (setq face 'font-lock-constant-face)))))
6402 (when face
6403 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6404 (js2-node-pos prop))) ; relative
6405 (+ pos (js2-node-len prop))
6406 face)))))
6407
6408 (defun js2-parse-highlight-member-expr-node (node)
6409 "Perform syntax highlighting of EcmaScript built-in properties.
6410 The variable `js2-highlight-level' governs this highighting."
6411 (let (face target prop name pos end parent call-p callee)
6412 (cond
6413 ;; case 1: simple name, e.g. foo
6414 ((js2-name-node-p node)
6415 (setq name (js2-name-node-name node))
6416 ;; possible for name to be nil in rare cases - saw it when
6417 ;; running js2-mode on an elisp buffer. Might as well try to
6418 ;; make it so js2-mode never barfs.
6419 (when name
6420 (setq face (if (string-match js2-ecma-global-props name)
6421 'font-lock-constant-face))
6422 (when face
6423 (setq pos (js2-node-pos node)
6424 end (+ pos (js2-node-len node)))
6425 (js2-set-face pos end face))))
6426 ;; case 2: property access or function call
6427 ((or (js2-prop-get-node-p node)
6428 ;; highlight function call if expr is a prop-get node
6429 ;; or a plain name (i.e. unqualified function call)
6430 (and (setq call-p (js2-call-node-p node))
6431 (setq callee (js2-call-node-target node)) ; separate setq!
6432 (or (js2-prop-get-node-p callee)
6433 (js2-name-node-p callee))))
6434 (setq parent node
6435 node (if call-p callee node))
6436 (if (and call-p (js2-name-node-p callee))
6437 (setq prop callee)
6438 (setq target (js2-prop-get-node-left node)
6439 prop (js2-prop-get-node-right node)))
6440 (cond
6441 ((js2-name-node-p target)
6442 (if (js2-name-node-p prop)
6443 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6444 (js2-parse-highlight-prop-get parent target prop call-p)
6445 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6446 (js2-parse-highlight-prop-get parent target nil call-p)))
6447 ((js2-name-node-p prop)
6448 ;; case 2c: complex target, simple name, e.g. x[y].bar
6449 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6450
6451 (defun js2-parse-highlight-member-expr-fn-name (expr)
6452 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6453 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6454 We currently only handle the case where the last component is a prop-get
6455 of a simple name. Called before EXPR has a parent node."
6456 (let (pos
6457 (name (and (js2-prop-get-node-p expr)
6458 (js2-prop-get-node-right expr))))
6459 (when (js2-name-node-p name)
6460 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6461 (js2-node-pos name)))
6462 (+ pos (js2-node-len name))
6463 'font-lock-function-name-face
6464 'record))))
6465
6466 ;; source: http://jsdoc.sourceforge.net/
6467 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6468 ;; allows type specifications, and needs work before entering the wild.
6469
6470 (defconst js2-jsdoc-param-tag-regexp
6471 (concat "^\\s-*\\*+\\s-*\\(@"
6472 "\\(?:param\\|argument\\)"
6473 "\\)"
6474 "\\s-*\\({[^}]+}\\)?" ; optional type
6475 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6476 "\\>")
6477 "Matches jsdoc tags with optional type and optional param name.")
6478
6479 (defconst js2-jsdoc-typed-tag-regexp
6480 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6481 (regexp-opt
6482 '("enum"
6483 "extends"
6484 "field"
6485 "id"
6486 "implements"
6487 "lends"
6488 "mods"
6489 "requires"
6490 "return"
6491 "returns"
6492 "throw"
6493 "throws"))
6494 "\\)\\)\\s-*\\({[^}]+}\\)?")
6495 "Matches jsdoc tags with optional type.")
6496
6497 (defconst js2-jsdoc-arg-tag-regexp
6498 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6499 (regexp-opt
6500 '("alias"
6501 "augments"
6502 "borrows"
6503 "bug"
6504 "base"
6505 "config"
6506 "default"
6507 "define"
6508 "exception"
6509 "function"
6510 "member"
6511 "memberOf"
6512 "name"
6513 "namespace"
6514 "property"
6515 "since"
6516 "suppress"
6517 "this"
6518 "throws"
6519 "type"
6520 "version"))
6521 "\\)\\)\\s-+\\([^ \t]+\\)")
6522 "Matches jsdoc tags with a single argument.")
6523
6524 (defconst js2-jsdoc-empty-tag-regexp
6525 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6526 (regexp-opt
6527 '("addon"
6528 "author"
6529 "class"
6530 "const"
6531 "constant"
6532 "constructor"
6533 "constructs"
6534 "deprecated"
6535 "desc"
6536 "description"
6537 "event"
6538 "example"
6539 "exec"
6540 "export"
6541 "fileoverview"
6542 "final"
6543 "function"
6544 "hidden"
6545 "ignore"
6546 "implicitCast"
6547 "inheritDoc"
6548 "inner"
6549 "interface"
6550 "license"
6551 "noalias"
6552 "noshadow"
6553 "notypecheck"
6554 "override"
6555 "owner"
6556 "preserve"
6557 "preserveTry"
6558 "private"
6559 "protected"
6560 "public"
6561 "static"
6562 "supported"
6563 ))
6564 "\\)\\)\\s-*")
6565 "Matches empty jsdoc tags.")
6566
6567 (defconst js2-jsdoc-link-tag-regexp
6568 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6569 "Matches a jsdoc link or code tag.")
6570
6571 (defconst js2-jsdoc-see-tag-regexp
6572 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6573 "Matches a jsdoc @see tag.")
6574
6575 (defconst js2-jsdoc-html-tag-regexp
6576 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6577 "Matches a simple (no attributes) html start- or end-tag.")
6578
6579 (defsubst js2-jsdoc-highlight-helper ()
6580 (js2-set-face (match-beginning 1)
6581 (match-end 1)
6582 'js2-jsdoc-tag-face)
6583 (if (match-beginning 2)
6584 (if (save-excursion
6585 (goto-char (match-beginning 2))
6586 (= (char-after) ?{))
6587 (js2-set-face (1+ (match-beginning 2))
6588 (1- (match-end 2))
6589 'js2-jsdoc-type-face)
6590 (js2-set-face (match-beginning 2)
6591 (match-end 2)
6592 'js2-jsdoc-value-face)))
6593 (if (match-beginning 3)
6594 (js2-set-face (match-beginning 3)
6595 (match-end 3)
6596 'js2-jsdoc-value-face)))
6597
6598 (defun js2-highlight-jsdoc (ast)
6599 "Highlight doc comment tags."
6600 (let ((comments (js2-ast-root-comments ast))
6601 beg end)
6602 (save-excursion
6603 (dolist (node comments)
6604 (when (eq (js2-comment-node-format node) 'jsdoc)
6605 (setq beg (js2-node-abs-pos node)
6606 end (+ beg (js2-node-len node)))
6607 (save-restriction
6608 (narrow-to-region beg end)
6609 (dolist (re (list js2-jsdoc-param-tag-regexp
6610 js2-jsdoc-typed-tag-regexp
6611 js2-jsdoc-arg-tag-regexp
6612 js2-jsdoc-link-tag-regexp
6613 js2-jsdoc-see-tag-regexp
6614 js2-jsdoc-empty-tag-regexp))
6615 (goto-char beg)
6616 (while (re-search-forward re nil t)
6617 (js2-jsdoc-highlight-helper)))
6618 ;; simple highlighting for html tags
6619 (goto-char beg)
6620 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6621 (js2-set-face (match-beginning 1)
6622 (match-end 1)
6623 'js2-jsdoc-html-tag-delimiter-face)
6624 (js2-set-face (match-beginning 2)
6625 (match-end 2)
6626 'js2-jsdoc-html-tag-name-face)
6627 (js2-set-face (match-beginning 3)
6628 (match-end 3)
6629 'js2-jsdoc-html-tag-delimiter-face))))))))
6630
6631 (defun js2-highlight-assign-targets (node left right)
6632 "Highlight function properties and external variables."
6633 (let (leftpos end name)
6634 ;; highlight vars and props assigned function values
6635 (when (js2-function-node-p right)
6636 (cond
6637 ;; var foo = function() {...}
6638 ((js2-name-node-p left)
6639 (setq name left))
6640 ;; foo.bar.baz = function() {...}
6641 ((and (js2-prop-get-node-p left)
6642 (js2-name-node-p (js2-prop-get-node-right left)))
6643 (setq name (js2-prop-get-node-right left))))
6644 (when name
6645 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6646 (+ leftpos (js2-node-len name))
6647 'font-lock-function-name-face
6648 'record)))
6649 ;; save variable assignments so we can check for undeclared later
6650 ;; (can't do it here since var decls can come at end of script)
6651 (when (and js2-highlight-external-variables
6652 (setq name (js2-member-expr-leftmost-name left)))
6653 (push (list name js2-current-scope
6654 (setq leftpos (js2-node-abs-pos name))
6655 (setq end (+ leftpos (js2-node-len name))))
6656 js2-recorded-assignments))))
6657
6658 (defun js2-highlight-undeclared-vars ()
6659 "After entire parse is finished, look for undeclared variable assignments.
6660 We have to wait until entire buffer is parsed, since JavaScript permits var
6661 decls to occur after they're used.
6662
6663 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6664 it is considered declared."
6665 (let (name)
6666 (dolist (entry js2-recorded-assignments)
6667 (destructuring-bind (name-node scope pos end) entry
6668 (setq name (js2-name-node-name name-node))
6669 (unless (or (member name js2-global-externs)
6670 (member name js2-default-externs)
6671 (member name js2-additional-externs)
6672 (js2-get-defining-scope scope name))
6673 (js2-set-face pos end 'js2-external-variable-face 'record)
6674 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6675 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6676 (setq js2-recorded-assignments nil)))
6677
6678 ;;; IMenu support
6679
6680 ;; We currently only support imenu, but eventually should support speedbar and
6681 ;; possibly other browsing mechanisms.
6682
6683 ;; The basic strategy is to identify function assignment targets of the form
6684 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6685 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6686 ;; for imenu after parsing is finished.
6687
6688 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6689 ;; JavaScript, and the general problem is undecidable. However, several forms
6690 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6691 ;; include:
6692
6693 ;; function foo() -- function declaration
6694 ;; foo = function() -- function expression assigned to variable
6695 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6696 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6697 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6698 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6699 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6700 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6701 ;; function foo() {function bar() {...}} -- nested function
6702 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6703
6704 ;; This list boils down to a few forms that can be combined recursively.
6705 ;; Top-level named function declarations include both the left-hand (name)
6706 ;; and the right-hand (function value) expressions needed to produce an imenu
6707 ;; entry. The other "right-hand" forms we need to look for are:
6708 ;; - functions declared as props/getters/setters in object literals
6709 ;; - nested named function declarations
6710 ;; The "left-hand" expressions that functions can be assigned to include:
6711 ;; - local/global variables
6712 ;; - nested property-get expressions like a.b.c.d
6713 ;; - element gets like foo[10] or foo['bar'] where the index
6714 ;; expression can be trivially converted to a property name. They
6715 ;; effectively then become property gets.
6716
6717 ;; All the different definition types are canonicalized into the form
6718 ;; foo.bar.baz = position-of-function-keyword
6719
6720 ;; We need to build a trie-like structure for imenu. As an example,
6721 ;; consider the following JavaScript code:
6722
6723 ;; a = function() {...} // function at position 5
6724 ;; b = function() {...} // function at position 25
6725 ;; foo = function() {...} // function at position 100
6726 ;; foo.bar = function() {...} // function at position 200
6727 ;; foo.bar.baz = function() {...} // function at position 300
6728 ;; foo.bar.zab = function() {...} // function at position 400
6729
6730 ;; During parsing we accumulate an entry for each definition in
6731 ;; the variable `js2-imenu-recorder', like so:
6732
6733 ;; '((a 5)
6734 ;; (b 25)
6735 ;; (foo 100)
6736 ;; (foo bar 200)
6737 ;; (foo bar baz 300)
6738 ;; (foo bar zab 400))
6739
6740 ;; After parsing these entries are merged into this alist-trie:
6741
6742 ;; '((a . 1)
6743 ;; (b . 2)
6744 ;; (foo (<definition> . 3)
6745 ;; (bar (<definition> . 6)
6746 ;; (baz . 100)
6747 ;; (zab . 200))))
6748
6749 ;; Note the wacky need for a <definition> name. The token can be anything
6750 ;; that isn't a valid JavaScript identifier, because you might make foo
6751 ;; a function and then start setting properties on it that are also functions.
6752
6753 (defsubst js2-prop-node-name (node)
6754 "Return the name of a node that may be a property-get/property-name.
6755 If NODE is not a valid name-node, string-node or integral number-node,
6756 returns nil. Otherwise returns the string name/value of the node."
6757 (cond
6758 ((js2-name-node-p node)
6759 (js2-name-node-name node))
6760 ((js2-string-node-p node)
6761 (js2-string-node-value node))
6762 ((and (js2-number-node-p node)
6763 (string-match "^[0-9]+$" (js2-number-node-value node)))
6764 (js2-number-node-value node))
6765 ((js2-this-node-p node)
6766 "this")))
6767
6768 (defsubst js2-node-qname-component (node)
6769 "Test function: return the name of this node, if it contributes to a qname.
6770 Returns nil if the node doesn't contribute."
6771 (copy-sequence
6772 (or (js2-prop-node-name node)
6773 (if (and (js2-function-node-p node)
6774 (js2-function-node-name node))
6775 (js2-name-node-name (js2-function-node-name node))))))
6776
6777 (defsubst js2-record-function-qname (fn-node qname)
6778 "Associate FN-NODE with its QNAME for later lookup.
6779 This is used in postprocessing the chain list. When we find a chain
6780 whose first element is a js2-THIS keyword node, we look up the parent
6781 function and see (using this map) whether it is the tail of a chain.
6782 If so, we replace the this-node with a copy of the parent's qname."
6783 (unless js2-imenu-function-map
6784 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6785 (puthash fn-node qname js2-imenu-function-map))
6786
6787 (defun js2-record-imenu-functions (node &optional var)
6788 "Record function definitions for imenu.
6789 NODE is a function node or an object literal.
6790 VAR, if non-nil, is the expression that NODE is being assigned to."
6791 (when js2-parse-ide-mode
6792 (let ((fun-p (js2-function-node-p node))
6793 qname left fname-node pos)
6794 (cond
6795 ;; non-anonymous function declaration?
6796 ((and fun-p
6797 (not var)
6798 (setq fname-node (js2-function-node-name node)))
6799 (push (setq qname (list fname-node (js2-node-pos node)))
6800 js2-imenu-recorder)
6801 (js2-record-function-qname node qname))
6802 ;; for remaining forms, compute left-side tree branch first
6803 ((and var (setq qname (js2-compute-nested-prop-get var)))
6804 (cond
6805 ;; foo.bar.baz = function
6806 (fun-p
6807 (push (nconc qname (list (js2-node-pos node)))
6808 js2-imenu-recorder)
6809 (js2-record-function-qname node qname))
6810 ;; foo.bar.baz = object-literal
6811 ;; look for nested functions: {a: {b: function() {...} }}
6812 ((js2-object-node-p node)
6813 ;; Node position here is still absolute, since the parser
6814 ;; passes the assignment target and value expressions
6815 ;; to us before they are added as children of the assignment node.
6816 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6817
6818 (defun js2-compute-nested-prop-get (node)
6819 "If NODE is of form foo.bar.baz, return component nodes as a list.
6820 Otherwise returns nil. Element-gets can be treated as property-gets
6821 if the index expression is a name, a string, or a positive integer."
6822 (let (left right head)
6823 (cond
6824 ((or (js2-name-node-p node)
6825 (js2-this-node-p node))
6826 (list node))
6827 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6828 ((or (and (js2-prop-get-node-p node)
6829 (setq left (js2-prop-get-node-left node)
6830 right (js2-prop-get-node-right node)))
6831 (and (js2-elem-get-node-p node)
6832 (setq left (js2-elem-get-node-target node)
6833 right (js2-elem-get-node-element node))))
6834 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6835 (js2-elem-get-node-p left) ; left == foo['bar']
6836 (js2-name-node-p left) ; left == foo
6837 (js2-this-node-p left)) ; or left == this
6838 (or (js2-name-node-p right) ; .bar
6839 (js2-string-node-p right) ; ['bar']
6840 (and (js2-number-node-p right) ; [10]
6841 (string-match "^[0-9]+$"
6842 (js2-number-node-value right)))))
6843 (if (setq head (js2-compute-nested-prop-get left))
6844 (nconc head (list right))))))))
6845
6846 (defun js2-record-object-literal (node qname pos)
6847 "Recursively process an object literal looking for functions.
6848 NODE is an object literal that is the right-hand child of an assignment
6849 expression. QNAME is a list of nodes representing the assignment target,
6850 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6851 POS is the absolute position of the node.
6852 We do a depth-first traversal of NODE. Any functions we find are prefixed
6853 with QNAME plus the property name of the function and appended to the
6854 variable `js2-imenu-recorder'."
6855 (let (left right)
6856 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6857 (let ((left (js2-infix-node-left e))
6858 ;; Element positions are relative to the parent position.
6859 (pos (+ pos (js2-node-pos e))))
6860 (cond
6861 ;; foo: function() {...}
6862 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6863 (when (js2-prop-node-name left)
6864 ;; As a policy decision, we record the position of the property,
6865 ;; not the position of the `function' keyword, since the property
6866 ;; is effectively the name of the function.
6867 (push (append qname (list left pos))
6868 js2-imenu-recorder)
6869 (js2-record-function-qname right qname)))
6870 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6871 ((js2-object-node-p right)
6872 (js2-record-object-literal right
6873 (append qname (list (js2-infix-node-left e)))
6874 (+ pos (js2-node-pos right)))))))))
6875
6876 (defsubst js2-node-top-level-decl-p (node)
6877 "Return t if NODE's name is defined in the top-level scope.
6878 Also returns t if NODE's name is not defined in any scope, since it implies
6879 that it's an external variable, which must also be in the top-level scope."
6880 (let* ((name (js2-prop-node-name node))
6881 (this-scope (js2-node-get-enclosing-scope node))
6882 defining-scope)
6883 (cond
6884 ((js2-this-node-p node)
6885 nil)
6886 ((null this-scope)
6887 t)
6888 ((setq defining-scope (js2-get-defining-scope this-scope name))
6889 (js2-ast-root-p defining-scope))
6890 (t t))))
6891
6892 (defun js2-browse-postprocess-chains (chains)
6893 "Modify function-declaration name chains after parsing finishes.
6894 Some of the information is only available after the parse tree is complete.
6895 For instance, following a 'this' reference requires a parent function node."
6896 (let (result head fn parent-chain p elem)
6897 (dolist (chain chains)
6898 ;; examine the head of each node to get its defining scope
6899 (setq head (car chain))
6900 (cond
6901 ;; if top-level/external, keep as-is
6902 ((js2-node-top-level-decl-p head)
6903 (push chain result))
6904 ;; check for a this-reference
6905 ((eq (js2-node-type head) js2-THIS)
6906 (setq fn (js2-node-parent-script-or-fn head))
6907 ;; if there is no parent function, or if the parent function
6908 ;; is nested, discard the head node and keep the rest of the chain.
6909 (if (or (null fn) (js2-nested-function-p fn))
6910 (push (cdr chain) result)
6911 ;; else look up parent in function-map. If not found, discard chain.
6912 (when (setq parent-chain (and js2-imenu-function-map
6913 (gethash fn js2-imenu-function-map)))
6914 ;; else discard head node and prefix parent fn qname, which is
6915 ;; the parent-chain sans tail, to this chain.
6916 (push (append (butlast parent-chain) (cdr chain)) result))))))
6917 ;; finally replace each node in each chain with its name.
6918 (dolist (chain result)
6919 (setq p chain)
6920 (while p
6921 (if (js2-node-p (setq elem (car p)))
6922 (setcar p (js2-node-qname-component elem)))
6923 (setq p (cdr p))))
6924 result))
6925
6926 ;; Merge name chains into a trie-like tree structure of nested lists.
6927 ;; To simplify construction of the trie, we first build it out using the rule
6928 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6929 ;; [key, num-or-list]. The second element can be a number; if so, this key
6930 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6931 ;; associated with the key at this level.) Otherwise the second element is
6932 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6933 ;; a simple recursive formulation.
6934 ;;
6935 ;; js2-mode is building the data structure for imenu. The imenu documentation
6936 ;; claims that it's the structure above, but in practice it wants the children
6937 ;; at the same list level as the key for that level, which is how I've drawn
6938 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6939 ;; list wrapper around the children at each level.
6940 ;;
6941 ;; A completed nested imenu-alist entry looks like this:
6942 ;; '(("foo"
6943 ;; ("<definition>" . 7)
6944 ;; ("bar"
6945 ;; ("a" . 40)
6946 ;; ("b" . 60))))
6947 ;;
6948 ;; In particular, the documentation for `imenu--index-alist' says that
6949 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6950 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6951
6952 (defsubst js2-treeify (lst)
6953 "Convert (a b c d) to (a ((b ((c d)))))"
6954 (if (null (cddr lst)) ; list length <= 2
6955 lst
6956 (list (car lst) (list (js2-treeify (cdr lst))))))
6957
6958 (defun js2-build-alist-trie (chains trie)
6959 "Merge declaration name chains into a trie-like alist structure for imenu.
6960 CHAINS is the qname chain list produced during parsing. TRIE is a
6961 list of elements built up so far."
6962 (let (head tail pos branch kids)
6963 (dolist (chain chains)
6964 (setq head (car chain)
6965 tail (cdr chain)
6966 pos (if (numberp (car tail)) (car tail))
6967 branch (js2-find-if (lambda (n)
6968 (string= (car n) head))
6969 trie)
6970 kids (second branch))
6971 (cond
6972 ;; case 1: this key isn't in the trie yet
6973 ((null branch)
6974 (if trie
6975 (setcdr (last trie) (list (js2-treeify chain)))
6976 (setq trie (list (js2-treeify chain)))))
6977 ;; case 2: key is present with a single number entry: replace w/ list
6978 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6979 ;; ("<definition>" 20)))
6980 ((numberp kids)
6981 (setcar (cdr branch)
6982 (list (list "<definition-1>" kids)
6983 (if pos
6984 (list "<definition-2>" pos)
6985 (js2-treeify tail)))))
6986 ;; case 3: key is there (with kids), and we're a number entry
6987 (pos
6988 (setcdr (last kids)
6989 (list
6990 (list (format "<definition-%d>"
6991 (1+ (loop for kid in kids
6992 count (eq ?< (aref (car kid) 0)))))
6993 pos))))
6994 ;; case 4: key is there with kids, need to merge in our chain
6995 (t
6996 (js2-build-alist-trie (list tail) kids))))
6997 trie))
6998
6999 (defun js2-flatten-trie (trie)
7000 "Convert TRIE to imenu-format.
7001 Recurses through nodes, and for each one whose second element is a list,
7002 appends the list's flattened elements to the current element. Also
7003 changes the tails into conses. For instance, this pre-flattened trie
7004
7005 '(a ((b 20)
7006 (c ((d 30)
7007 (e 40)))))
7008
7009 becomes
7010
7011 '(a (b . 20)
7012 (c (d . 30)
7013 (e . 40)))
7014
7015 Note that the root of the trie has no key, just a list of chains.
7016 This is also true for the value of any key with multiple children,
7017 e.g. key 'c' in the example above."
7018 (cond
7019 ((listp (car trie))
7020 (mapcar #'js2-flatten-trie trie))
7021 (t
7022 (if (numberp (second trie))
7023 (cons (car trie) (second trie))
7024 ;; else pop list and append its kids
7025 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7026
7027 (defun js2-build-imenu-index ()
7028 "Turn `js2-imenu-recorder' into an imenu data structure."
7029 (unless (eq js2-imenu-recorder 'empty)
7030 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7031 (result (js2-build-alist-trie chains nil)))
7032 (js2-flatten-trie result))))
7033
7034 (defun js2-test-print-chains (chains)
7035 "Print a list of qname chains.
7036 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7037 i.e. one or more nodes, and an integer position as the list tail."
7038 (mapconcat (lambda (chain)
7039 (concat "("
7040 (mapconcat (lambda (elem)
7041 (if (js2-node-p elem)
7042 (or (js2-node-qname-component elem)
7043 "nil")
7044 (number-to-string elem)))
7045 chain
7046 " ")
7047 ")"))
7048 chains
7049 "\n"))
7050
7051 ;;; Parser
7052
7053 (defconst js2-version "1.8.0"
7054 "Version of JavaScript supported, plus minor js2 version.")
7055
7056 (defmacro js2-record-face (face)
7057 "Record a style run of FACE for the current token."
7058 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7059
7060 (defsubst js2-node-end (n)
7061 "Computes the absolute end of node N.
7062 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7063 is only true until the node is added to its parent; i.e., while parsing."
7064 (+ (js2-node-pos n)
7065 (js2-node-len n)))
7066
7067 (defsubst js2-record-comment ()
7068 "Record a comment in `js2-scanned-comments'."
7069 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7070 :format js2-ts-comment-type)
7071 js2-scanned-comments)
7072 (when js2-parse-ide-mode
7073 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7074 'font-lock-doc-face
7075 'font-lock-comment-face))
7076 (when (memq js2-ts-comment-type '(html preprocessor))
7077 ;; Tell cc-engine the bounds of the comment.
7078 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7079
7080 ;; This function is called depressingly often, so it should be fast.
7081 ;; Most of the time it's looking at the same token it peeked before.
7082 (defsubst js2-peek-token ()
7083 "Returns the next token without consuming it.
7084 If previous token was consumed, calls scanner to get new token.
7085 If previous token was -not- consumed, returns it (idempotent).
7086
7087 This function will not return a newline (js2-EOL) - instead, it
7088 gobbles newlines until it finds a non-newline token, and flags
7089 that token as appearing just after a newline.
7090
7091 This function will also not return a js2-COMMENT. Instead, it
7092 records comments found in `js2-scanned-comments'. If the token
7093 returned by this function immediately follows a jsdoc comment,
7094 the token is flagged as such.
7095
7096 Note that this function always returned the un-flagged token!
7097 The flags, if any, are saved in `js2-current-flagged-token'."
7098 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7099 js2-current-token ; most common case - return already-peeked token
7100 (let ((tt (js2-get-token)) ; call scanner
7101 saw-eol
7102 face)
7103 ;; process comments and whitespace
7104 (while (or (= tt js2-EOL)
7105 (= tt js2-COMMENT))
7106 (if (= tt js2-EOL)
7107 (setq saw-eol t)
7108 (setq saw-eol nil)
7109 (if js2-record-comments
7110 (js2-record-comment)))
7111 (setq tt (js2-get-token))) ; call scanner
7112 (setq js2-current-token tt
7113 js2-current-flagged-token (if saw-eol
7114 (logior tt js2-ti-after-eol)
7115 tt))
7116 ;; perform lexical fontification as soon as token is scanned
7117 (when js2-parse-ide-mode
7118 (cond
7119 ((minusp tt)
7120 (js2-record-face 'js2-error-face))
7121 ((setq face (aref js2-kwd-tokens tt))
7122 (js2-record-face face))
7123 ((and (= tt js2-NAME)
7124 (equal js2-ts-string "undefined"))
7125 (js2-record-face 'font-lock-constant-face))))
7126 tt))) ; return unflagged token
7127
7128 (defsubst js2-peek-flagged-token ()
7129 "Returns the current token along with any flags set for it."
7130 (js2-peek-token)
7131 js2-current-flagged-token)
7132
7133 (defsubst js2-consume-token ()
7134 (setq js2-current-flagged-token js2-EOF))
7135
7136 (defsubst js2-next-token ()
7137 (prog1
7138 (js2-peek-token)
7139 (js2-consume-token)))
7140
7141 (defsubst js2-next-flagged-token ()
7142 (js2-peek-token)
7143 (prog1 js2-current-flagged-token
7144 (js2-consume-token)))
7145
7146 (defsubst js2-match-token (match)
7147 "Consume and return t if next token matches MATCH, a bytecode.
7148 Returns nil and consumes nothing if MATCH is not the next token."
7149 (if (/= (js2-peek-token) match)
7150 nil
7151 (js2-consume-token)
7152 t))
7153
7154 (defsubst js2-valid-prop-name-token (tt)
7155 (or (= tt js2-NAME)
7156 (and js2-allow-keywords-as-property-names
7157 (plusp tt)
7158 (aref js2-kwd-tokens tt))))
7159
7160 (defsubst js2-match-prop-name ()
7161 "Consume token and return t if next token is a valid property name.
7162 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7163 is non-nil and it's a keyword token."
7164 (if (js2-valid-prop-name-token (js2-peek-token))
7165 (progn
7166 (js2-consume-token)
7167 t)
7168 nil))
7169
7170 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7171 (if (js2-match-prop-name)
7172 t
7173 (js2-report-error msg-id nil pos len)
7174 nil))
7175
7176 (defsubst js2-peek-token-or-eol ()
7177 "Return js2-EOL if the current token immediately follows a newline.
7178 Else returns the current token. Used in situations where we don't
7179 consider certain token types valid if they are preceded by a newline.
7180 One example is the postfix ++ or -- operator, which has to be on the
7181 same line as its operand."
7182 (let ((tt (js2-peek-token)))
7183 ;; Check for last peeked token flags
7184 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7185 js2-EOL
7186 tt)))
7187
7188 (defsubst js2-set-check-for-label ()
7189 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7190 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7191
7192 (defsubst js2-must-match (token msg-id &optional pos len)
7193 "Match next token to token code TOKEN, or record a syntax error.
7194 MSG-ID is the error message to report if the match fails.
7195 Returns t on match, nil if no match."
7196 (if (js2-match-token token)
7197 t
7198 (js2-report-error msg-id nil pos len)
7199 nil))
7200
7201 (defsubst js2-inside-function ()
7202 (plusp js2-nesting-of-function))
7203
7204 (defsubst js2-set-requires-activation ()
7205 (if (js2-function-node-p js2-current-script-or-fn)
7206 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7207
7208 (defsubst js2-check-activation-name (name token)
7209 (when (js2-inside-function)
7210 ;; skip language-version 1.2 check from Rhino
7211 (if (or (string= "arguments" name)
7212 (and js2-compiler-activation-names ; only used in codegen
7213 (gethash name js2-compiler-activation-names)))
7214 (js2-set-requires-activation))))
7215
7216 (defsubst js2-set-is-generator ()
7217 (if (js2-function-node-p js2-current-script-or-fn)
7218 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7219
7220 (defsubst js2-must-have-xml ()
7221 (unless js2-compiler-xml-available
7222 (js2-report-error "msg.XML.not.available")))
7223
7224 (defsubst js2-push-scope (scope)
7225 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7226 (assert (js2-scope-p scope))
7227 (assert (null (js2-scope-parent-scope scope)))
7228 (assert (not (eq js2-current-scope scope)))
7229 (setf (js2-scope-parent-scope scope) js2-current-scope
7230 js2-current-scope scope))
7231
7232 (defsubst js2-pop-scope ()
7233 (setq js2-current-scope
7234 (js2-scope-parent-scope js2-current-scope)))
7235
7236 (defsubst js2-enter-loop (loop-node)
7237 (push loop-node js2-loop-set)
7238 (push loop-node js2-loop-and-switch-set)
7239 (js2-push-scope loop-node)
7240 ;; Tell the current labeled statement (if any) its statement,
7241 ;; and set the jump target of the first label to the loop.
7242 ;; These are used in `js2-parse-continue' to verify that the
7243 ;; continue target is an actual labeled loop. (And for codegen.)
7244 (when js2-labeled-stmt
7245 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7246 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7247 js2-labeled-stmt))) loop-node)))
7248
7249 (defsubst js2-exit-loop ()
7250 (pop js2-loop-set)
7251 (pop js2-loop-and-switch-set)
7252 (js2-pop-scope))
7253
7254 (defsubst js2-enter-switch (switch-node)
7255 (push switch-node js2-loop-and-switch-set))
7256
7257 (defsubst js2-exit-switch ()
7258 (pop js2-loop-and-switch-set))
7259
7260 (defun js2-parse (&optional buf cb)
7261 "Tells the js2 parser to parse a region of JavaScript.
7262
7263 BUF is a buffer or buffer name containing the code to parse.
7264 Call `narrow-to-region' first to parse only part of the buffer.
7265
7266 The returned AST root node is given some additional properties:
7267 `node-count' - total number of nodes in the AST
7268 `buffer' - BUF. The buffer it refers to may change or be killed,
7269 so the value is not necessarily reliable.
7270
7271 An optional callback CB can be specified to report parsing
7272 progress. If `(functionp CB)' returns t, it will be called with
7273 the current line number once before parsing begins, then again
7274 each time the lexer reaches a new line number.
7275
7276 CB can also be a list of the form `(symbol cb ...)' to specify
7277 multiple callbacks with different criteria. Each symbol is a
7278 criterion keyword, and the following element is the callback to
7279 call
7280
7281 :line - called whenever the line number changes
7282 :token - called for each new token consumed
7283
7284 The list of criteria could be extended to include entering or
7285 leaving a statement, an expression, or a function definition."
7286 (if (and cb (not (functionp cb)))
7287 (error "criteria callbacks not yet implemented"))
7288 (let ((inhibit-point-motion-hooks t)
7289 (js2-compiler-xml-available (>= js2-language-version 160))
7290 ;; This is a recursive-descent parser, so give it a big stack.
7291 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7292 (max-specpdl-size (max max-specpdl-size 3000))
7293 (case-fold-search nil)
7294 ast)
7295 (or buf (setq buf (current-buffer)))
7296 (message nil) ; clear any error message from previous parse
7297 (save-excursion
7298 (set-buffer buf)
7299 (setq js2-scanned-comments nil
7300 js2-parsed-errors nil
7301 js2-parsed-warnings nil
7302 js2-imenu-recorder nil
7303 js2-imenu-function-map nil
7304 js2-label-set nil)
7305 (js2-init-scanner)
7306 (setq ast (js2-with-unmodifying-text-property-changes
7307 (js2-do-parse)))
7308 (unless js2-ts-hit-eof
7309 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7310 (setf (js2-ast-root-errors ast) js2-parsed-errors
7311 (js2-ast-root-warnings ast) js2-parsed-warnings)
7312 ;; if we didn't find any declarations, put a dummy in this list so we
7313 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7314 (unless js2-imenu-recorder
7315 (setq js2-imenu-recorder 'empty))
7316 (run-hooks 'js2-parse-finished-hook)
7317 ast)))
7318
7319 ;; Corresponds to Rhino's Parser.parse() method.
7320 (defun js2-do-parse ()
7321 "Parse current buffer starting from current point.
7322 Scanner should be initialized."
7323 (let ((pos js2-ts-cursor)
7324 (end js2-ts-cursor) ; in case file is empty
7325 root n tt)
7326 ;; initialize buffer-local parsing vars
7327 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7328 js2-current-script-or-fn root
7329 js2-current-scope root
7330 js2-current-flagged-token js2-EOF
7331 js2-nesting-of-function 0
7332 js2-labeled-stmt nil
7333 js2-recorded-assignments nil) ; for js2-highlight
7334 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7335 (if (= tt js2-FUNCTION)
7336 (progn
7337 (js2-consume-token)
7338 (setq n (js2-parse-function (if js2-called-by-compile-function
7339 'FUNCTION_EXPRESSION
7340 'FUNCTION_STATEMENT)))
7341 (js2-record-imenu-functions n))
7342 ;; not a function - parse a statement
7343 (setq n (js2-parse-statement)))
7344 ;; add function or statement to script
7345 (setq end (js2-node-end n))
7346 (js2-block-node-push root n))
7347 ;; add comments to root in lexical order
7348 (when js2-scanned-comments
7349 ;; if we find a comment beyond end of normal kids, use its end
7350 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7351 (dolist (comment js2-scanned-comments)
7352 (push comment (js2-ast-root-comments root))
7353 (js2-node-add-children root comment)))
7354 (setf (js2-node-len root) (- end pos))
7355 ;; Give extensions a chance to muck with things before highlighting starts.
7356 (dolist (callback js2-post-parse-callbacks)
7357 (funcall callback))
7358 (js2-highlight-undeclared-vars)
7359 root))
7360
7361 (defun js2-function-parser ()
7362 (js2-consume-token)
7363 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7364
7365 (defun js2-parse-function-closure-body (fn-node)
7366 "Parse a JavaScript 1.8 function closure body."
7367 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7368 (if js2-ts-hit-eof
7369 (js2-report-error "msg.no.brace.body" nil
7370 (js2-node-pos fn-node)
7371 (- js2-ts-cursor (js2-node-pos fn-node)))
7372 (js2-node-add-children fn-node
7373 (setf (js2-function-node-body fn-node)
7374 (js2-parse-expr t))))))
7375
7376 (defun js2-parse-function-body (fn-node)
7377 (js2-must-match js2-LC "msg.no.brace.body"
7378 (js2-node-pos fn-node)
7379 (- js2-ts-cursor (js2-node-pos fn-node)))
7380 (let ((pos js2-token-beg) ; LC position
7381 (pn (make-js2-block-node)) ; starts at LC position
7382 tt
7383 end)
7384 (incf js2-nesting-of-function)
7385 (unwind-protect
7386 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7387 (= tt js2-EOF)
7388 (= tt js2-RC)))
7389 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7390 (js2-parse-statement)
7391 (js2-consume-token)
7392 (js2-parse-function 'FUNCTION_STATEMENT))))
7393 (decf js2-nesting-of-function))
7394 (setq end js2-token-end) ; assume no curly and leave at current token
7395 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7396 (setq end js2-token-end))
7397 (setf (js2-node-pos pn) pos
7398 (js2-node-len pn) (- end pos))
7399 (setf (js2-function-node-body fn-node) pn)
7400 (js2-node-add-children fn-node pn)
7401 pn))
7402
7403 (defun js2-parse-function-params (fn-node pos)
7404 (if (js2-match-token js2-RP)
7405 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7406 (let (params len param)
7407 (loop for tt = (js2-peek-token)
7408 do
7409 (cond
7410 ;; destructuring param
7411 ((or (= tt js2-LB) (= tt js2-LC))
7412 (push (js2-parse-primary-expr-lhs) params))
7413 ;; simple name
7414 (t
7415 (js2-must-match js2-NAME "msg.no.parm")
7416 (js2-record-face 'js2-function-param-face)
7417 (setq param (js2-create-name-node))
7418 (js2-define-symbol js2-LP js2-ts-string param)
7419 (push param params)))
7420 while
7421 (js2-match-token js2-COMMA))
7422 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7423 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7424 (dolist (p params)
7425 (js2-node-add-children fn-node p)
7426 (push p (js2-function-node-params fn-node))))))
7427
7428 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7429 "Possibly show inconsistent-return warning.
7430 Last token scanned is the close-curly for the function body."
7431 (when (and js2-mode-show-strict-warnings
7432 js2-strict-inconsistent-return-warning
7433 (not (js2-has-consistent-return-usage
7434 (js2-function-node-body fn-node))))
7435 ;; Have it extend from close-curly to bol or beginning of block.
7436 (let ((pos (save-excursion
7437 (goto-char js2-token-end)
7438 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7439 (point-at-bol))))
7440 (end js2-token-end))
7441 (if (plusp (js2-name-node-length name))
7442 (js2-add-strict-warning "msg.no.return.value"
7443 (js2-name-node-name name) pos end)
7444 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7445
7446 (defun js2-parse-function (function-type)
7447 "Function parser. FUNCTION-TYPE is a symbol."
7448 (let ((pos js2-token-beg) ; start of 'function' keyword
7449 name
7450 name-beg
7451 name-end
7452 fn-node
7453 lp
7454 (synthetic-type function-type)
7455 member-expr-node)
7456 ;; parse function name, expression, or non-name (anonymous)
7457 (cond
7458 ;; function foo(...)
7459 ((js2-match-token js2-NAME)
7460 (setq name (js2-create-name-node t)
7461 name-beg js2-token-beg
7462 name-end js2-token-end)
7463 (unless (js2-match-token js2-LP)
7464 (when js2-allow-member-expr-as-function-name
7465 ;; function foo.bar(...)
7466 (setq member-expr-node name
7467 name nil
7468 member-expr-node (js2-parse-member-expr-tail
7469 nil member-expr-node)))
7470 (js2-must-match js2-LP "msg.no.paren.parms")))
7471 ((js2-match-token js2-LP)
7472 nil) ; anonymous function: leave name as null
7473 (t
7474 ;; function random-member-expr(...)
7475 (when js2-allow-member-expr-as-function-name
7476 ;; Note that memberExpr can not start with '(' like
7477 ;; in function (1+2).toString(), because 'function (' already
7478 ;; processed as anonymous function
7479 (setq member-expr-node (js2-parse-member-expr)))
7480 (js2-must-match js2-LP "msg.no.paren.parms")))
7481 (if (= js2-current-token js2-LP) ; eventually matched LP?
7482 (setq lp js2-token-beg))
7483 (if member-expr-node
7484 (progn
7485 (setq synthetic-type 'FUNCTION_EXPRESSION)
7486 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7487 (if name
7488 (js2-set-face name-beg name-end
7489 'font-lock-function-name-face 'record)))
7490 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7491 (plusp (js2-name-node-length name)))
7492 ;; Function statements define a symbol in the enclosing scope
7493 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7494 (setf fn-node (make-js2-function-node :pos pos
7495 :name name
7496 :form function-type
7497 :lp (if lp (- lp pos))))
7498 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7499 ;; 1. Nested functions are not affected by the dynamic scope flag
7500 ;; as dynamic scope is already a parent of their scope.
7501 ;; 2. Functions defined under the with statement also immune to
7502 ;; this setup, in which case dynamic scope is ignored in favor
7503 ;; of the with object.
7504 (setf (js2-function-node-ignore-dynamic fn-node) t))
7505 ;; dynamically bind all the per-function variables
7506 (let ((js2-current-script-or-fn fn-node)
7507 (js2-current-scope fn-node)
7508 (js2-nesting-of-with 0)
7509 (js2-end-flags 0)
7510 js2-label-set
7511 js2-loop-set
7512 js2-loop-and-switch-set)
7513 (js2-parse-function-params fn-node pos)
7514 (if (and (>= js2-language-version 180)
7515 (/= (js2-peek-token) js2-LC))
7516 (js2-parse-function-closure-body fn-node)
7517 (js2-parse-function-body fn-node))
7518 (if name
7519 (js2-node-add-children fn-node name))
7520 (js2-check-inconsistent-return-warning fn-node name)
7521 ;; Function expressions define a name only in the body of the
7522 ;; function, and only if not hidden by a parameter name
7523 (if (and name
7524 (eq synthetic-type 'FUNCTION_EXPRESSION)
7525 (null (js2-scope-get-symbol js2-current-scope
7526 (js2-name-node-name name))))
7527 (js2-define-symbol js2-FUNCTION
7528 (js2-name-node-name name)
7529 fn-node))
7530 (if (and name
7531 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7532 (js2-record-imenu-functions fn-node)))
7533 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7534 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7535 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7536 ;; We wait until after parsing the function to set its parent scope,
7537 ;; since `js2-define-symbol' needs the defining-scope check to stop
7538 ;; at the function boundary when checking for redeclarations.
7539 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7540 fn-node))
7541
7542 (defun js2-parse-statements (&optional parent)
7543 "Parse a statement list. Last token consumed must be js2-LC.
7544
7545 PARENT can be a `js2-block-node', in which case the statements are
7546 appended to PARENT. Otherwise a new `js2-block-node' is created
7547 and returned.
7548
7549 This function does not match the closing js2-RC: the caller
7550 matches the RC so it can provide a suitable error message if not
7551 matched. This means it's up to the caller to set the length of
7552 the node to include the closing RC. The node start pos is set to
7553 the absolute buffer start position, and the caller should fix it
7554 up to be relative to the parent node. All children of this block
7555 node are given relative start positions and correct lengths."
7556 (let ((pn (or parent (make-js2-block-node)))
7557 tt)
7558 (setf (js2-node-pos pn) js2-token-beg)
7559 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7560 (/= tt js2-RC))
7561 (js2-block-node-push pn (js2-parse-statement)))
7562 pn))
7563
7564 (defun js2-parse-statement ()
7565 (let (tt pn beg end)
7566 ;; coarse-grained user-interrupt check - needs work
7567 (and js2-parse-interruptable-p
7568 (zerop (% (incf js2-parse-stmt-count)
7569 js2-statements-per-pause))
7570 (input-pending-p)
7571 (throw 'interrupted t))
7572 (setq pn (js2-statement-helper))
7573 ;; no-side-effects warning check
7574 (unless (js2-node-has-side-effects pn)
7575 (setq end (js2-node-end pn))
7576 (save-excursion
7577 (goto-char end)
7578 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7579 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7580 pn))
7581
7582 ;; These correspond to the switch cases in Parser.statementHelper
7583 (defconst js2-parsers
7584 (let ((parsers (make-vector js2-num-tokens
7585 #'js2-parse-expr-stmt)))
7586 (aset parsers js2-BREAK #'js2-parse-break)
7587 (aset parsers js2-CONST #'js2-parse-const-var)
7588 (aset parsers js2-CONTINUE #'js2-parse-continue)
7589 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7590 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7591 (aset parsers js2-DO #'js2-parse-do)
7592 (aset parsers js2-FOR #'js2-parse-for)
7593 (aset parsers js2-FUNCTION #'js2-function-parser)
7594 (aset parsers js2-IF #'js2-parse-if)
7595 (aset parsers js2-LC #'js2-parse-block)
7596 (aset parsers js2-LET #'js2-parse-let-stmt)
7597 (aset parsers js2-NAME #'js2-parse-name-or-label)
7598 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7599 (aset parsers js2-SEMI #'js2-parse-semi)
7600 (aset parsers js2-SWITCH #'js2-parse-switch)
7601 (aset parsers js2-THROW #'js2-parse-throw)
7602 (aset parsers js2-TRY #'js2-parse-try)
7603 (aset parsers js2-VAR #'js2-parse-const-var)
7604 (aset parsers js2-WHILE #'js2-parse-while)
7605 (aset parsers js2-WITH #'js2-parse-with)
7606 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7607 parsers)
7608 "A vector mapping token types to parser functions.")
7609
7610 (defsubst js2-parse-warn-missing-semi (beg end)
7611 (and js2-mode-show-strict-warnings
7612 js2-strict-missing-semi-warning
7613 (js2-add-strict-warning
7614 "msg.missing.semi" nil
7615 ;; back up to beginning of statement or line
7616 (max beg (save-excursion
7617 (goto-char end)
7618 (point-at-bol)))
7619 end)))
7620
7621 (defconst js2-no-semi-insertion
7622 (list js2-IF
7623 js2-SWITCH
7624 js2-WHILE
7625 js2-DO
7626 js2-FOR
7627 js2-TRY
7628 js2-WITH
7629 js2-LC
7630 js2-ERROR
7631 js2-SEMI
7632 js2-FUNCTION)
7633 "List of tokens that don't do automatic semicolon insertion.")
7634
7635 (defconst js2-autoinsert-semi-and-warn
7636 (list js2-ERROR js2-EOF js2-RC))
7637
7638 (defun js2-statement-helper ()
7639 (let* ((tt (js2-peek-token))
7640 (first-tt tt)
7641 (beg js2-token-beg)
7642 (parser (if (= tt js2-ERROR)
7643 #'js2-parse-semi
7644 (aref js2-parsers tt)))
7645 pn
7646 tt-flagged)
7647 ;; If the statement is set, then it's been told its label by now.
7648 (and js2-labeled-stmt
7649 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7650 (setq js2-labeled-stmt nil))
7651 (setq pn (funcall parser))
7652 ;; Don't do auto semi insertion for certain statement types.
7653 (unless (or (memq first-tt js2-no-semi-insertion)
7654 (js2-labeled-stmt-node-p pn))
7655 (js2-auto-insert-semicolon pn))
7656 pn))
7657
7658 (defun js2-auto-insert-semicolon (pn)
7659 (let* ((tt-flagged (js2-peek-flagged-token))
7660 (tt (logand tt-flagged js2-clear-ti-mask))
7661 (pos (js2-node-pos pn)))
7662 (cond
7663 ((= tt js2-SEMI)
7664 ;; Consume ';' as a part of expression
7665 (js2-consume-token)
7666 ;; extend the node bounds to include the semicolon.
7667 (setf (js2-node-len pn) (- js2-token-end pos)))
7668 ((memq tt js2-autoinsert-semi-and-warn)
7669 ;; Autoinsert ;
7670 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7671 (t
7672 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7673 ;; Report error if no EOL or autoinsert ';' otherwise
7674 (js2-report-error "msg.no.semi.stmt")
7675 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7676
7677 (defun js2-parse-condition ()
7678 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7679 The parens are discarded and the expression node is returned.
7680 The `pos' field of the return value is set to an absolute position
7681 that must be fixed up by the caller.
7682 Return value is a list (EXPR LP RP), with absolute paren positions."
7683 (let (pn lp rp)
7684 (if (js2-must-match js2-LP "msg.no.paren.cond")
7685 (setq lp js2-token-beg))
7686 (setq pn (js2-parse-expr))
7687 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7688 (setq rp js2-token-beg))
7689 ;; Report strict warning on code like "if (a = 7) ..."
7690 (if (and js2-strict-cond-assign-warning
7691 (js2-assign-node-p pn))
7692 (js2-add-strict-warning "msg.equal.as.assign" nil
7693 (js2-node-pos pn)
7694 (+ (js2-node-pos pn)
7695 (js2-node-len pn))))
7696 (list pn lp rp)))
7697
7698 (defun js2-parse-if ()
7699 "Parser for if-statement. Last matched token must be js2-IF."
7700 (let ((pos js2-token-beg)
7701 cond
7702 if-true
7703 if-false
7704 else-pos
7705 end
7706 pn)
7707 (js2-consume-token)
7708 (setq cond (js2-parse-condition)
7709 if-true (js2-parse-statement)
7710 if-false (if (js2-match-token js2-ELSE)
7711 (progn
7712 (setq else-pos (- js2-token-beg pos))
7713 (js2-parse-statement)))
7714 end (js2-node-end (or if-false if-true))
7715 pn (make-js2-if-node :pos pos
7716 :len (- end pos)
7717 :condition (car cond)
7718 :then-part if-true
7719 :else-part if-false
7720 :else-pos else-pos
7721 :lp (js2-relpos (second cond) pos)
7722 :rp (js2-relpos (third cond) pos)))
7723 (js2-node-add-children pn (car cond) if-true if-false)
7724 pn))
7725
7726 (defun js2-parse-switch ()
7727 "Parser for if-statement. Last matched token must be js2-SWITCH."
7728 (let ((pos js2-token-beg)
7729 tt
7730 pn
7731 discriminant
7732 has-default
7733 case-expr
7734 case-node
7735 case-pos
7736 cases
7737 stmt
7738 lp
7739 rp)
7740 (js2-consume-token)
7741 (if (js2-must-match js2-LP "msg.no.paren.switch")
7742 (setq lp js2-token-beg))
7743 (setq discriminant (js2-parse-expr)
7744 pn (make-js2-switch-node :discriminant discriminant
7745 :pos pos
7746 :lp (js2-relpos lp pos)))
7747 (js2-node-add-children pn discriminant)
7748 (js2-enter-switch pn)
7749 (unwind-protect
7750 (progn
7751 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7752 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7753 (js2-must-match js2-LC "msg.no.brace.switch")
7754 (catch 'break
7755 (while t
7756 (setq tt (js2-next-token)
7757 case-pos js2-token-beg)
7758 (cond
7759 ((= tt js2-RC)
7760 (setf (js2-node-len pn) (- js2-token-end pos))
7761 (throw 'break nil)) ; done
7762 ((= tt js2-CASE)
7763 (setq case-expr (js2-parse-expr))
7764 (js2-must-match js2-COLON "msg.no.colon.case"))
7765 ((= tt js2-DEFAULT)
7766 (if has-default
7767 (js2-report-error "msg.double.switch.default"))
7768 (setq has-default t
7769 case-expr nil)
7770 (js2-must-match js2-COLON "msg.no.colon.case"))
7771 (t
7772 (js2-report-error "msg.bad.switch")
7773 (throw 'break nil)))
7774 (setq case-node (make-js2-case-node :pos case-pos
7775 :len (- js2-token-end case-pos)
7776 :expr case-expr))
7777 (js2-node-add-children case-node case-expr)
7778 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7779 (/= tt js2-CASE)
7780 (/= tt js2-DEFAULT)
7781 (/= tt js2-EOF))
7782 (setf stmt (js2-parse-statement)
7783 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7784 (js2-block-node-push case-node stmt))
7785 (push case-node cases)))
7786 ;; add cases last, as pushing reverses the order to be correct
7787 (dolist (kid cases)
7788 (js2-node-add-children pn kid)
7789 (push kid (js2-switch-node-cases pn)))
7790 pn) ; return value
7791 (js2-exit-switch))))
7792
7793 (defun js2-parse-while ()
7794 "Parser for while-statement. Last matched token must be js2-WHILE."
7795 (let ((pos js2-token-beg)
7796 (pn (make-js2-while-node))
7797 cond
7798 body)
7799 (js2-consume-token)
7800 (js2-enter-loop pn)
7801 (unwind-protect
7802 (progn
7803 (setf cond (js2-parse-condition)
7804 (js2-while-node-condition pn) (car cond)
7805 body (js2-parse-statement)
7806 (js2-while-node-body pn) body
7807 (js2-node-len pn) (- (js2-node-end body) pos)
7808 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7809 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7810 (js2-node-add-children pn body (car cond)))
7811 (js2-exit-loop))
7812 pn))
7813
7814 (defun js2-parse-do ()
7815 "Parser for do-statement. Last matched token must be js2-DO."
7816 (let ((pos js2-token-beg)
7817 (pn (make-js2-do-node))
7818 cond
7819 body
7820 end)
7821 (js2-consume-token)
7822 (js2-enter-loop pn)
7823 (unwind-protect
7824 (progn
7825 (setq body (js2-parse-statement))
7826 (js2-must-match js2-WHILE "msg.no.while.do")
7827 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7828 cond (js2-parse-condition)
7829 (js2-do-node-condition pn) (car cond)
7830 (js2-do-node-body pn) body
7831 end js2-ts-cursor
7832 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7833 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7834 (js2-node-add-children pn (car cond) body))
7835 (js2-exit-loop))
7836 ;; Always auto-insert semicolon to follow SpiderMonkey:
7837 ;; It is required by ECMAScript but is ignored by the rest of
7838 ;; world; see bug 238945
7839 (if (js2-match-token js2-SEMI)
7840 (setq end js2-ts-cursor))
7841 (setf (js2-node-len pn) (- end pos))
7842 pn))
7843
7844 (defun js2-parse-for ()
7845 "Parser for for-statement. Last matched token must be js2-FOR.
7846 Parses for, for-in, and for each-in statements."
7847 (let ((for-pos js2-token-beg)
7848 pn
7849 is-for-each
7850 is-for-in
7851 in-pos
7852 each-pos
7853 tmp-pos
7854 init ; Node init is also foo in 'foo in object'
7855 cond ; Node cond is also object in 'foo in object'
7856 incr ; 3rd section of for-loop initializer
7857 body
7858 tt
7859 lp
7860 rp)
7861 (js2-consume-token)
7862 ;; See if this is a for each () instead of just a for ()
7863 (when (js2-match-token js2-NAME)
7864 (if (string= "each" js2-ts-string)
7865 (progn
7866 (setq is-for-each t
7867 each-pos (- js2-token-beg for-pos)) ; relative
7868 (js2-record-face 'font-lock-keyword-face))
7869 (js2-report-error "msg.no.paren.for")))
7870 (if (js2-must-match js2-LP "msg.no.paren.for")
7871 (setq lp (- js2-token-beg for-pos)))
7872 (setq tt (js2-peek-token))
7873 ;; parse init clause
7874 (let ((js2-in-for-init t)) ; set as dynamic variable
7875 (cond
7876 ((= tt js2-SEMI)
7877 (setq init (make-js2-empty-expr-node)))
7878 ((or (= tt js2-VAR) (= tt js2-LET))
7879 (js2-consume-token)
7880 (setq init (js2-parse-variables tt js2-token-beg)))
7881 (t
7882 (setq init (js2-parse-expr)))))
7883 (if (js2-match-token js2-IN)
7884 (setq is-for-in t
7885 in-pos (- js2-token-beg for-pos)
7886 cond (js2-parse-expr)) ; object over which we're iterating
7887 ;; else ordinary for loop - parse cond and incr
7888 (js2-must-match js2-SEMI "msg.no.semi.for")
7889 (setq cond (if (= (js2-peek-token) js2-SEMI)
7890 (make-js2-empty-expr-node) ; no loop condition
7891 (js2-parse-expr)))
7892 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7893 (setq tmp-pos js2-token-end
7894 incr (if (= (js2-peek-token) js2-RP)
7895 (make-js2-empty-expr-node :pos tmp-pos)
7896 (js2-parse-expr))))
7897 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7898 (setq rp (- js2-token-beg for-pos)))
7899 (if (not is-for-in)
7900 (setq pn (make-js2-for-node :init init
7901 :condition cond
7902 :update incr
7903 :lp lp
7904 :rp rp))
7905 ;; cond could be null if 'in obj' got eaten by the init node.
7906 (if (js2-infix-node-p init)
7907 ;; it was (foo in bar) instead of (var foo in bar)
7908 (setq cond (js2-infix-node-right init)
7909 init (js2-infix-node-left init))
7910 (if (and (js2-var-decl-node-p init)
7911 (> (length (js2-var-decl-node-kids init)) 1))
7912 (js2-report-error "msg.mult.index")))
7913 (setq pn (make-js2-for-in-node :iterator init
7914 :object cond
7915 :in-pos in-pos
7916 :foreach-p is-for-each
7917 :each-pos each-pos
7918 :lp lp
7919 :rp rp)))
7920 (unwind-protect
7921 (progn
7922 (js2-enter-loop pn)
7923 ;; We have to parse the body -after- creating the loop node,
7924 ;; so that the loop node appears in the js2-loop-set, allowing
7925 ;; break/continue statements to find the enclosing loop.
7926 (setf body (js2-parse-statement)
7927 (js2-loop-node-body pn) body
7928 (js2-node-pos pn) for-pos
7929 (js2-node-len pn) (- (js2-node-end body) for-pos))
7930 (js2-node-add-children pn init cond incr body))
7931 ;; finally
7932 (js2-exit-loop))
7933 pn))
7934
7935 (defun js2-parse-try ()
7936 "Parser for try-statement. Last matched token must be js2-TRY."
7937 (let ((try-pos js2-token-beg)
7938 try-end
7939 try-block
7940 catch-blocks
7941 finally-block
7942 saw-default-catch
7943 peek
7944 var-name
7945 catch-cond
7946 catch-node
7947 guard-kwd
7948 catch-pos
7949 finally-pos
7950 pn
7951 block
7952 lp
7953 rp)
7954 (js2-consume-token)
7955 (if (/= (js2-peek-token) js2-LC)
7956 (js2-report-error "msg.no.brace.try"))
7957 (setq try-block (js2-parse-statement)
7958 try-end (js2-node-end try-block)
7959 peek (js2-peek-token))
7960 (cond
7961 ((= peek js2-CATCH)
7962 (while (js2-match-token js2-CATCH)
7963 (setq catch-pos js2-token-beg
7964 guard-kwd nil
7965 catch-cond nil
7966 lp nil
7967 rp nil)
7968 (if saw-default-catch
7969 (js2-report-error "msg.catch.unreachable"))
7970 (if (js2-must-match js2-LP "msg.no.paren.catch")
7971 (setq lp (- js2-token-beg catch-pos)))
7972 (js2-must-match js2-NAME "msg.bad.catchcond")
7973 (setq var-name (js2-create-name-node))
7974 (if (js2-match-token js2-IF)
7975 (setq guard-kwd (- js2-token-beg catch-pos)
7976 catch-cond (js2-parse-expr))
7977 (setq saw-default-catch t))
7978 (if (js2-must-match js2-RP "msg.bad.catchcond")
7979 (setq rp (- js2-token-beg catch-pos)))
7980 (js2-must-match js2-LC "msg.no.brace.catchblock")
7981 (setq block (js2-parse-statements)
7982 try-end (js2-node-end block)
7983 catch-node (make-js2-catch-node :pos catch-pos
7984 :var-name var-name
7985 :guard-expr catch-cond
7986 :guard-kwd guard-kwd
7987 :block block
7988 :lp lp
7989 :rp rp))
7990 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7991 (setq try-end js2-token-beg))
7992 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7993 (js2-node-len catch-node) (- try-end catch-pos))
7994 (js2-node-add-children catch-node var-name catch-cond block)
7995 (push catch-node catch-blocks)))
7996 ((/= peek js2-FINALLY)
7997 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7998 (js2-node-pos try-block)
7999 (- (setq try-end (js2-node-end try-block))
8000 (js2-node-pos try-block)))))
8001 (when (js2-match-token js2-FINALLY)
8002 (setq finally-pos js2-token-beg
8003 block (js2-parse-statement)
8004 try-end (js2-node-end block)
8005 finally-block (make-js2-finally-node :pos finally-pos
8006 :len (- try-end finally-pos)
8007 :body block))
8008 (js2-node-add-children finally-block block))
8009 (setq pn (make-js2-try-node :pos try-pos
8010 :len (- try-end try-pos)
8011 :try-block try-block
8012 :finally-block finally-block))
8013 (js2-node-add-children pn try-block finally-block)
8014 ;; push them onto the try-node, which reverses and corrects their order
8015 (dolist (cb catch-blocks)
8016 (js2-node-add-children pn cb)
8017 (push cb (js2-try-node-catch-clauses pn)))
8018 pn))
8019
8020 (defun js2-parse-throw ()
8021 "Parser for throw-statement. Last matched token must be js2-THROW."
8022 (let ((pos js2-token-beg)
8023 expr
8024 pn)
8025 (js2-consume-token)
8026 (if (= (js2-peek-token-or-eol) js2-EOL)
8027 ;; ECMAScript does not allow new lines before throw expression,
8028 ;; see bug 256617
8029 (js2-report-error "msg.bad.throw.eol"))
8030 (setq expr (js2-parse-expr)
8031 pn (make-js2-throw-node :pos pos
8032 :len (- (js2-node-end expr) pos)
8033 :expr expr))
8034 (js2-node-add-children pn expr)
8035 pn))
8036
8037 (defsubst js2-match-jump-label-name (label-name)
8038 "If break/continue specified a label, return that label's labeled stmt.
8039 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8040 does not match an existing label, reports an error and returns nil."
8041 (let ((bundle (cdr (assoc label-name js2-label-set))))
8042 (if (null bundle)
8043 (js2-report-error "msg.undef.label"))
8044 bundle))
8045
8046 (defun js2-parse-break ()
8047 "Parser for break-statement. Last matched token must be js2-BREAK."
8048 (let ((pos js2-token-beg)
8049 (end js2-token-end)
8050 break-target ; statement to break from
8051 break-label ; in "break foo", name-node representing the foo
8052 labels ; matching labeled statement to break to
8053 pn)
8054 (js2-consume-token) ; `break'
8055 (when (eq (js2-peek-token-or-eol) js2-NAME)
8056 (js2-consume-token)
8057 (setq break-label (js2-create-name-node)
8058 end (js2-node-end break-label)
8059 ;; matchJumpLabelName only matches if there is one
8060 labels (js2-match-jump-label-name js2-ts-string)
8061 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8062 (unless (or break-target break-label)
8063 ;; no break target specified - try for innermost enclosing loop/switch
8064 (if (null js2-loop-and-switch-set)
8065 (unless break-label
8066 (js2-report-error "msg.bad.break" nil pos (length "break")))
8067 (setq break-target (car js2-loop-and-switch-set))))
8068 (setq pn (make-js2-break-node :pos pos
8069 :len (- end pos)
8070 :label break-label
8071 :target break-target))
8072 (js2-node-add-children pn break-label) ; but not break-target
8073 pn))
8074
8075 (defun js2-parse-continue ()
8076 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8077 (let ((pos js2-token-beg)
8078 (end js2-token-end)
8079 label ; optional user-specified label, a `js2-name-node'
8080 labels ; current matching labeled stmt, if any
8081 target ; the `js2-loop-node' target of this continue stmt
8082 pn)
8083 (js2-consume-token) ; `continue'
8084 (when (= (js2-peek-token-or-eol) js2-NAME)
8085 (js2-consume-token)
8086 (setq label (js2-create-name-node)
8087 end (js2-node-end label)
8088 ;; matchJumpLabelName only matches if there is one
8089 labels (js2-match-jump-label-name js2-ts-string)))
8090 (cond
8091 ((null labels) ; no current label to go to
8092 (if (null js2-loop-set) ; no loop to continue to
8093 (js2-report-error "msg.continue.outside" nil pos
8094 (length "continue"))
8095 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8096 (t
8097 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8098 (setq target (js2-labeled-stmt-node-stmt labels))
8099 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8100 (setq pn (make-js2-continue-node :pos pos
8101 :len (- end pos)
8102 :label label
8103 :target target))
8104 (js2-node-add-children pn label) ; but not target - it's not our child
8105 pn))
8106
8107 (defun js2-parse-with ()
8108 "Parser for with-statement. Last matched token must be js2-WITH."
8109 (js2-consume-token)
8110 (let ((pos js2-token-beg)
8111 obj body pn lp rp)
8112 (if (js2-must-match js2-LP "msg.no.paren.with")
8113 (setq lp js2-token-beg))
8114 (setq obj (js2-parse-expr))
8115 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8116 (setq rp js2-token-beg))
8117 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8118 (setq body (js2-parse-statement)))
8119 (setq pn (make-js2-with-node :pos pos
8120 :len (- (js2-node-end body) pos)
8121 :object obj
8122 :body body
8123 :lp (js2-relpos lp pos)
8124 :rp (js2-relpos rp pos)))
8125 (js2-node-add-children pn obj body)
8126 pn))
8127
8128 (defun js2-parse-const-var ()
8129 "Parser for var- or const-statement.
8130 Last matched token must be js2-CONST or js2-VAR."
8131 (let ((tt (js2-peek-token))
8132 (pos js2-token-beg)
8133 expr
8134 pn)
8135 (js2-consume-token)
8136 (setq expr (js2-parse-variables tt js2-token-beg)
8137 pn (make-js2-expr-stmt-node :pos pos
8138 :len (- (js2-node-end expr) pos)
8139 :expr expr))
8140 (js2-node-add-children pn expr)
8141 pn))
8142
8143 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8144 (let ((pn (make-js2-expr-stmt-node :pos pos
8145 :len (js2-node-len expr)
8146 :type (if (js2-inside-function)
8147 js2-EXPR_VOID
8148 js2-EXPR_RESULT)
8149 :expr expr)))
8150 (if add-child
8151 (js2-node-add-children pn expr))
8152 pn))
8153
8154 (defun js2-parse-let-stmt ()
8155 "Parser for let-statement. Last matched token must be js2-LET."
8156 (js2-consume-token)
8157 (let ((pos js2-token-beg)
8158 expr
8159 pn)
8160 (if (= (js2-peek-token) js2-LP)
8161 ;; let expression in statement context
8162 (setq expr (js2-parse-let pos 'statement)
8163 pn (js2-wrap-with-expr-stmt pos expr t))
8164 ;; else we're looking at a statement like let x=6, y=7;
8165 (setf expr (js2-parse-variables js2-LET pos)
8166 pn (js2-wrap-with-expr-stmt pos expr t)
8167 (js2-node-type pn) js2-EXPR_RESULT))
8168 pn))
8169
8170 (defun js2-parse-ret-yield ()
8171 (js2-parse-return-or-yield (js2-peek-token) nil))
8172
8173 (defconst js2-parse-return-stmt-enders
8174 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8175
8176 (defsubst js2-now-all-set (before after mask)
8177 "Return whether or not the bits in the mask have changed to all set.
8178 BEFORE is bits before change, AFTER is bits after change, and MASK is
8179 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8180 but not BEFORE."
8181 (and (/= (logand before mask) mask)
8182 (= (logand after mask) mask)))
8183
8184 (defun js2-parse-return-or-yield (tt expr-context)
8185 (let ((pos js2-token-beg)
8186 (end js2-token-end)
8187 (before js2-end-flags)
8188 (inside-function (js2-inside-function))
8189 e
8190 ret
8191 name)
8192 (unless inside-function
8193 (js2-report-error (if (eq tt js2-RETURN)
8194 "msg.bad.return"
8195 "msg.bad.yield")))
8196 (js2-consume-token)
8197 ;; This is ugly, but we don't want to require a semicolon.
8198 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8199 (setq e (js2-parse-expr)
8200 end (js2-node-end e)))
8201 (cond
8202 ((eq tt js2-RETURN)
8203 (js2-set-flag js2-end-flags (if (null e)
8204 js2-end-returns
8205 js2-end-returns-value))
8206 (setq ret (make-js2-return-node :pos pos
8207 :len (- end pos)
8208 :retval e))
8209 (js2-node-add-children ret e)
8210 ;; See if we need a strict mode warning.
8211 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8212 ;; more thorough and accurate than this before/after flag check.
8213 ;; E.g. if there's a finally-block that always returns, we shouldn't
8214 ;; show a warning generated by inconsistent returns in the catch blocks.
8215 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8216 ;; so we know which returns/yields to highlight, and we should get rid of
8217 ;; all the checking in `js2-parse-return-or-yield'.
8218 (if (and js2-strict-inconsistent-return-warning
8219 (js2-now-all-set before js2-end-flags
8220 (logior js2-end-returns js2-end-returns-value)))
8221 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8222 (t
8223 (unless (js2-inside-function)
8224 (js2-report-error "msg.bad.yield"))
8225 (js2-set-flag js2-end-flags js2-end-yields)
8226 (setq ret (make-js2-yield-node :pos pos
8227 :len (- end pos)
8228 :value e))
8229 (js2-node-add-children ret e)
8230 (unless expr-context
8231 (setq e ret
8232 ret (js2-wrap-with-expr-stmt pos e t))
8233 (js2-set-requires-activation)
8234 (js2-set-is-generator))))
8235 ;; see if we are mixing yields and value returns.
8236 (when (and inside-function
8237 (js2-now-all-set before js2-end-flags
8238 (logior js2-end-yields js2-end-returns-value)))
8239 (setq name (js2-function-name js2-current-script-or-fn))
8240 (if (zerop (length name))
8241 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8242 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8243 ret))
8244
8245 (defun js2-parse-debugger ()
8246 (js2-consume-token)
8247 (make-js2-keyword-node :type js2-DEBUGGER))
8248
8249 (defun js2-parse-block ()
8250 "Parser for a curly-delimited statement block.
8251 Last token matched must be js2-LC."
8252 (let ((pos js2-token-beg)
8253 (pn (make-js2-scope)))
8254 (js2-consume-token)
8255 (js2-push-scope pn)
8256 (unwind-protect
8257 (progn
8258 (js2-parse-statements pn)
8259 (js2-must-match js2-RC "msg.no.brace.block")
8260 (setf (js2-node-len pn) (- js2-token-end pos)))
8261 (js2-pop-scope))
8262 pn))
8263
8264 ;; for js2-ERROR too, to have a node for error recovery to work on
8265 (defun js2-parse-semi ()
8266 "Parse a statement or handle an error.
8267 Last matched token is js-SEMI or js-ERROR."
8268 (let ((tt (js2-peek-token)) pos len)
8269 (js2-consume-token)
8270 (if (eq tt js2-SEMI)
8271 (make-js2-empty-expr-node :len 1)
8272 (setq pos js2-token-beg
8273 len (- js2-token-beg pos))
8274 (js2-report-error "msg.syntax" nil pos len)
8275 (make-js2-error-node :pos pos :len len))))
8276
8277 (defun js2-parse-default-xml-namespace ()
8278 "Parse a `default xml namespace = <expr>' e4x statement."
8279 (let ((pos js2-token-beg)
8280 end len expr unary es)
8281 (js2-consume-token)
8282 (js2-must-have-xml)
8283 (js2-set-requires-activation)
8284 (setq len (- js2-ts-cursor pos))
8285 (unless (and (js2-match-token js2-NAME)
8286 (string= js2-ts-string "xml"))
8287 (js2-report-error "msg.bad.namespace" nil pos len))
8288 (unless (and (js2-match-token js2-NAME)
8289 (string= js2-ts-string "namespace"))
8290 (js2-report-error "msg.bad.namespace" nil pos len))
8291 (unless (js2-match-token js2-ASSIGN)
8292 (js2-report-error "msg.bad.namespace" nil pos len))
8293 (setq expr (js2-parse-expr)
8294 end (js2-node-end expr)
8295 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8296 :pos pos
8297 :len (- end pos)
8298 :operand expr))
8299 (js2-node-add-children unary expr)
8300 (make-js2-expr-stmt-node :pos pos
8301 :len (- end pos)
8302 :expr unary)))
8303
8304 (defun js2-record-label (label bundle)
8305 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8306 (js2-consume-token)
8307 (let ((name (js2-label-node-name label))
8308 labeled-stmt
8309 dup)
8310 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8311 ;; flag both labels if possible when used in editing mode
8312 (if (and js2-parse-ide-mode
8313 (setq dup (js2-get-label-by-name labeled-stmt name)))
8314 (js2-report-error "msg.dup.label" nil
8315 (js2-node-abs-pos dup) (js2-node-len dup)))
8316 (js2-report-error "msg.dup.label" nil
8317 (js2-node-pos label) (js2-node-len label)))
8318 (js2-labeled-stmt-node-add-label bundle label)
8319 (js2-node-add-children bundle label)
8320 ;; Add one reference to the bundle per label in `js2-label-set'
8321 (push (cons name bundle) js2-label-set)))
8322
8323 (defun js2-parse-name-or-label ()
8324 "Parser for identifier or label. Last token matched must be js2-NAME.
8325 Called when we found a name in a statement context. If it's a label, we gather
8326 up any following labels and the next non-label statement into a
8327 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8328 expression and return it wrapped in a `js2-expr-stmt-node'."
8329 (let ((pos js2-token-beg)
8330 (end js2-token-end)
8331 expr
8332 stmt
8333 pn
8334 bundle
8335 (continue t))
8336 ;; set check for label and call down to `js2-parse-primary-expr'
8337 (js2-set-check-for-label)
8338 (setq expr (js2-parse-expr))
8339 (if (/= (js2-node-type expr) js2-LABEL)
8340 ;; Parsed non-label expression - wrap with expression stmt.
8341 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8342 ;; else parsed a label
8343 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8344 (js2-record-label expr bundle)
8345 ;; look for more labels
8346 (while (and continue (= (js2-peek-token) js2-NAME))
8347 (js2-set-check-for-label)
8348 (setq expr (js2-parse-expr))
8349 (if (/= (js2-node-type expr) js2-LABEL)
8350 (progn
8351 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8352 continue nil)
8353 (js2-auto-insert-semicolon stmt))
8354 (js2-record-label expr bundle)))
8355 ;; no more labels; now parse the labeled statement
8356 (unwind-protect
8357 (unless stmt
8358 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8359 (setq stmt (js2-statement-helper))))
8360 ;; remove the labels for this statement from the global set
8361 (dolist (label (js2-labeled-stmt-node-labels bundle))
8362 (setq js2-label-set (remove label js2-label-set))))
8363 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8364 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8365 (js2-node-add-children bundle stmt)
8366 bundle)))
8367
8368 (defun js2-parse-expr-stmt ()
8369 "Default parser in statement context, if no recognized statement found."
8370 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8371
8372 (defun js2-parse-variables (decl-type pos)
8373 "Parse a comma-separated list of variable declarations.
8374 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8375
8376 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8377 For 'var' or 'const', the keyword should be the token last scanned.
8378
8379 POS is the position where the node should start. It's sometimes the
8380 var/const/let keyword, and other times the beginning of the first token
8381 in the first variable declaration.
8382
8383 Returns the parsed `js2-var-decl-node' expression node."
8384 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8385 :pos pos))
8386 destructuring
8387 kid-pos
8388 tt
8389 init
8390 name
8391 end
8392 nbeg nend
8393 vi
8394 (continue t))
8395 ;; Example:
8396 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8397 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8398 ;; var {a, b} = baz;
8399 (while continue
8400 (setq destructuring nil
8401 name nil
8402 tt (js2-peek-token)
8403 kid-pos js2-token-beg
8404 end js2-token-end
8405 init nil)
8406 (if (or (= tt js2-LB) (= tt js2-LC))
8407 ;; Destructuring assignment, e.g., var [a, b] = ...
8408 (setq destructuring (js2-parse-primary-expr-lhs)
8409 end (js2-node-end destructuring))
8410 ;; Simple variable name
8411 (when (js2-must-match js2-NAME "msg.bad.var")
8412 (setq name (js2-create-name-node)
8413 nbeg js2-token-beg
8414 nend js2-token-end
8415 end nend)
8416 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8417 (when (js2-match-token js2-ASSIGN)
8418 (setq init (js2-parse-assign-expr)
8419 end (js2-node-end init))
8420 (if (and js2-parse-ide-mode
8421 (or (js2-object-node-p init)
8422 (js2-function-node-p init)))
8423 (js2-record-imenu-functions init name)))
8424 (when name
8425 (js2-set-face nbeg nend (if (js2-function-node-p init)
8426 'font-lock-function-name-face
8427 'font-lock-variable-name-face)
8428 'record))
8429 (setq vi (make-js2-var-init-node :pos kid-pos
8430 :len (- end kid-pos)
8431 :type decl-type))
8432 (if destructuring
8433 (progn
8434 (if (and (null init) (not js2-in-for-init))
8435 (js2-report-error "msg.destruct.assign.no.init"))
8436 (setf (js2-var-init-node-target vi) destructuring))
8437 (setf (js2-var-init-node-target vi) name))
8438 (setf (js2-var-init-node-initializer vi) init)
8439 (js2-node-add-children vi name destructuring init)
8440 (js2-block-node-push result vi)
8441 (unless (js2-match-token js2-COMMA)
8442 (setq continue nil)))
8443 (setf (js2-node-len result) (- end pos))
8444 result))
8445
8446 (defun js2-parse-let (pos &optional stmt-p)
8447 "Parse a let expression or statement.
8448 A let-expression is of the form `let (vars) expr'.
8449 A let-statment is of the form `let (vars) {statements}'.
8450 The third form of let is a variable declaration list, handled
8451 by `js2-parse-variables'."
8452 (let ((pn (make-js2-let-node :pos pos))
8453 beg vars body)
8454 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8455 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8456 (js2-push-scope pn)
8457 (unwind-protect
8458 (progn
8459 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8460 (if (js2-must-match js2-RP "msg.no.paren.let")
8461 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8462 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8463 ;; let statement
8464 (progn
8465 (js2-consume-token)
8466 (setf beg js2-token-beg ; position stmt at LC
8467 body (js2-parse-statements))
8468 (js2-must-match js2-RC "msg.no.curly.let")
8469 (setf (js2-node-len body) (- js2-token-end beg)
8470 (js2-node-len pn) (- js2-token-end pos)
8471 (js2-let-node-body pn) body
8472 (js2-node-type pn) js2-LET))
8473 ;; let expression
8474 (setf body (js2-parse-expr)
8475 (js2-node-len pn) (- (js2-node-end body) pos)
8476 (js2-let-node-body pn) body))
8477 (js2-node-add-children pn vars body))
8478 (js2-pop-scope))
8479 pn))
8480
8481 (defsubst js2-define-new-symbol (decl-type name node)
8482 (js2-scope-put-symbol js2-current-scope
8483 name
8484 (make-js2-symbol decl-type name node)))
8485
8486 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8487 "Define a symbol in the current scope.
8488 If NODE is non-nil, it is the AST node associated with the symbol."
8489 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8490 (symbol (if defining-scope
8491 (js2-scope-get-symbol defining-scope name)))
8492 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8493 (cond
8494 ((and symbol ; already defined
8495 (or (= sdt js2-CONST) ; old version is const
8496 (= decl-type js2-CONST) ; new version is const
8497 ;; two let-bound vars in this block have same name
8498 (and (= sdt js2-LET)
8499 (eq defining-scope js2-current-scope))))
8500 (js2-report-error
8501 (cond
8502 ((= sdt js2-CONST) "msg.const.redecl")
8503 ((= sdt js2-LET) "msg.let.redecl")
8504 ((= sdt js2-VAR) "msg.var.redecl")
8505 ((= sdt js2-FUNCTION) "msg.function.redecl")
8506 (t "msg.parm.redecl"))
8507 name))
8508 ((= decl-type js2-LET)
8509 (if (and (not ignore-not-in-block)
8510 (or (= (js2-node-type js2-current-scope) js2-IF)
8511 (js2-loop-node-p js2-current-scope)))
8512 (js2-report-error "msg.let.decl.not.in.block")
8513 (js2-define-new-symbol decl-type name node)))
8514 ((or (= decl-type js2-VAR)
8515 (= decl-type js2-CONST)
8516 (= decl-type js2-FUNCTION))
8517 (if symbol
8518 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8519 (js2-add-strict-warning "msg.var.redecl" name)
8520 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8521 (js2-add-strict-warning "msg.var.hides.arg" name)))
8522 (js2-define-new-symbol decl-type name node)))
8523 ((= decl-type js2-LP)
8524 (if symbol
8525 ;; must be duplicate parameter. Second parameter hides the
8526 ;; first, so go ahead and add the second pararameter
8527 (js2-report-warning "msg.dup.parms" name))
8528 (js2-define-new-symbol decl-type name node))
8529 (t (js2-code-bug)))))
8530
8531 (defun js2-parse-expr (&optional oneshot)
8532 (let* ((pn (js2-parse-assign-expr))
8533 (pos (js2-node-pos pn))
8534 left
8535 right
8536 op-pos)
8537 (while (and (not oneshot)
8538 (js2-match-token js2-COMMA))
8539 (setq op-pos (- js2-token-beg pos)) ; relative
8540 (if (= (js2-peek-token) js2-YIELD)
8541 (js2-report-error "msg.yield.parenthesized"))
8542 (setq right (js2-parse-assign-expr)
8543 left pn
8544 pn (make-js2-infix-node :type js2-COMMA
8545 :pos pos
8546 :len (- js2-ts-cursor pos)
8547 :op-pos op-pos
8548 :left left
8549 :right right))
8550 (js2-node-add-children pn left right))
8551 pn))
8552
8553 (defun js2-parse-assign-expr ()
8554 (let ((tt (js2-peek-token))
8555 (pos js2-token-beg)
8556 pn
8557 left
8558 right
8559 op-pos)
8560 (if (= tt js2-YIELD)
8561 (js2-parse-return-or-yield tt t)
8562 ;; not yield - parse assignment expression
8563 (setq pn (js2-parse-cond-expr)
8564 tt (js2-peek-token))
8565 (when (and (<= js2-first-assign tt)
8566 (<= tt js2-last-assign))
8567 ;; tt express assignment (=, |=, ^=, ..., %=)
8568 (js2-consume-token)
8569 (setq op-pos (- js2-token-beg pos) ; relative
8570 left pn
8571 right (js2-parse-assign-expr)
8572 pn (make-js2-assign-node :type tt
8573 :pos pos
8574 :len (- (js2-node-end right) pos)
8575 :op-pos op-pos
8576 :left left
8577 :right right))
8578 (when js2-parse-ide-mode
8579 (js2-highlight-assign-targets pn left right)
8580 (if (or (js2-function-node-p right)
8581 (js2-object-node-p right))
8582 (js2-record-imenu-functions right left)))
8583 ;; do this last so ide checks above can use absolute positions
8584 (js2-node-add-children pn left right))
8585 pn)))
8586
8587 (defun js2-parse-cond-expr ()
8588 (let ((pos js2-token-beg)
8589 (pn (js2-parse-or-expr))
8590 test-expr
8591 if-true
8592 if-false
8593 q-pos
8594 c-pos)
8595 (when (js2-match-token js2-HOOK)
8596 (setq q-pos (- js2-token-beg pos)
8597 if-true (js2-parse-assign-expr))
8598 (js2-must-match js2-COLON "msg.no.colon.cond")
8599 (setq c-pos (- js2-token-beg pos)
8600 if-false (js2-parse-assign-expr)
8601 test-expr pn
8602 pn (make-js2-cond-node :pos pos
8603 :len (- (js2-node-end if-false) pos)
8604 :test-expr test-expr
8605 :true-expr if-true
8606 :false-expr if-false
8607 :q-pos q-pos
8608 :c-pos c-pos))
8609 (js2-node-add-children pn test-expr if-true if-false))
8610 pn))
8611
8612 (defun js2-make-binary (type left parser)
8613 "Helper for constructing a binary-operator AST node.
8614 LEFT is the left-side-expression, already parsed, and the
8615 binary operator should have just been matched.
8616 PARSER is a function to call to parse the right operand,
8617 or a `js2-node' struct if it has already been parsed."
8618 (let* ((pos (js2-node-pos left))
8619 (op-pos (- js2-token-beg pos))
8620 (right (if (js2-node-p parser)
8621 parser
8622 (funcall parser)))
8623 (pn (make-js2-infix-node :type type
8624 :pos pos
8625 :len (- (js2-node-end right) pos)
8626 :op-pos op-pos
8627 :left left
8628 :right right)))
8629 (js2-node-add-children pn left right)
8630 pn))
8631
8632 (defun js2-parse-or-expr ()
8633 (let ((pn (js2-parse-and-expr)))
8634 (when (js2-match-token js2-OR)
8635 (setq pn (js2-make-binary js2-OR
8636 pn
8637 'js2-parse-or-expr)))
8638 pn))
8639
8640 (defun js2-parse-and-expr ()
8641 (let ((pn (js2-parse-bit-or-expr)))
8642 (when (js2-match-token js2-AND)
8643 (setq pn (js2-make-binary js2-AND
8644 pn
8645 'js2-parse-and-expr)))
8646 pn))
8647
8648 (defun js2-parse-bit-or-expr ()
8649 (let ((pn (js2-parse-bit-xor-expr)))
8650 (while (js2-match-token js2-BITOR)
8651 (setq pn (js2-make-binary js2-BITOR
8652 pn
8653 'js2-parse-bit-xor-expr)))
8654 pn))
8655
8656 (defun js2-parse-bit-xor-expr ()
8657 (let ((pn (js2-parse-bit-and-expr)))
8658 (while (js2-match-token js2-BITXOR)
8659 (setq pn (js2-make-binary js2-BITXOR
8660 pn
8661 'js2-parse-bit-and-expr)))
8662 pn))
8663
8664 (defun js2-parse-bit-and-expr ()
8665 (let ((pn (js2-parse-eq-expr)))
8666 (while (js2-match-token js2-BITAND)
8667 (setq pn (js2-make-binary js2-BITAND
8668 pn
8669 'js2-parse-eq-expr)))
8670 pn))
8671
8672 (defconst js2-parse-eq-ops
8673 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8674
8675 (defun js2-parse-eq-expr ()
8676 (let ((pn (js2-parse-rel-expr))
8677 tt)
8678 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8679 (js2-consume-token)
8680 (setq pn (js2-make-binary tt
8681 pn
8682 'js2-parse-rel-expr)))
8683 pn))
8684
8685 (defconst js2-parse-rel-ops
8686 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8687
8688 (defun js2-parse-rel-expr ()
8689 (let ((pn (js2-parse-shift-expr))
8690 (continue t)
8691 tt)
8692 (while continue
8693 (setq tt (js2-peek-token))
8694 (cond
8695 ((and js2-in-for-init (= tt js2-IN))
8696 (setq continue nil))
8697 ((memq tt js2-parse-rel-ops)
8698 (js2-consume-token)
8699 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8700 (t
8701 (setq continue nil))))
8702 pn))
8703
8704 (defconst js2-parse-shift-ops
8705 (list js2-LSH js2-URSH js2-RSH))
8706
8707 (defun js2-parse-shift-expr ()
8708 (let ((pn (js2-parse-add-expr))
8709 tt
8710 (continue t))
8711 (while continue
8712 (setq tt (js2-peek-token))
8713 (if (memq tt js2-parse-shift-ops)
8714 (progn
8715 (js2-consume-token)
8716 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8717 (setq continue nil)))
8718 pn))
8719
8720 (defun js2-parse-add-expr ()
8721 (let ((pn (js2-parse-mul-expr))
8722 tt
8723 (continue t))
8724 (while continue
8725 (setq tt (js2-peek-token))
8726 (if (or (= tt js2-ADD) (= tt js2-SUB))
8727 (progn
8728 (js2-consume-token)
8729 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8730 (setq continue nil)))
8731 pn))
8732
8733 (defconst js2-parse-mul-ops
8734 (list js2-MUL js2-DIV js2-MOD))
8735
8736 (defun js2-parse-mul-expr ()
8737 (let ((pn (js2-parse-unary-expr))
8738 tt
8739 (continue t))
8740 (while continue
8741 (setq tt (js2-peek-token))
8742 (if (memq tt js2-parse-mul-ops)
8743 (progn
8744 (js2-consume-token)
8745 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8746 (setq continue nil)))
8747 pn))
8748
8749 (defsubst js2-make-unary (type parser &rest args)
8750 "Make a unary node of type TYPE.
8751 PARSER is either a node (for postfix operators) or a function to call
8752 to parse the operand (for prefix operators)."
8753 (let* ((pos js2-token-beg)
8754 (postfix (js2-node-p parser))
8755 (expr (if postfix
8756 parser
8757 (apply parser args)))
8758 end
8759 pn)
8760 (if postfix ; e.g. i++
8761 (setq pos (js2-node-pos expr)
8762 end js2-token-end)
8763 (setq end (js2-node-end expr)))
8764 (setq pn (make-js2-unary-node :type type
8765 :pos pos
8766 :len (- end pos)
8767 :operand expr))
8768 (js2-node-add-children pn expr)
8769 pn))
8770
8771 (defconst js2-incrementable-node-types
8772 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8773 "Node types that can be the operand of a ++ or -- operator.")
8774
8775 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8776 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8777 js2-incrementable-node-types)
8778 (js2-report-error (if (= tt js2-INC)
8779 "msg.bad.incr"
8780 "msg.bad.decr")
8781 nil beg (- end beg))))
8782
8783 (defun js2-parse-unary-expr ()
8784 (let ((tt (js2-peek-token))
8785 pn expr beg end)
8786 (cond
8787 ((or (= tt js2-VOID)
8788 (= tt js2-NOT)
8789 (= tt js2-BITNOT)
8790 (= tt js2-TYPEOF))
8791 (js2-consume-token)
8792 (js2-make-unary tt 'js2-parse-unary-expr))
8793 ((= tt js2-ADD)
8794 (js2-consume-token)
8795 ;; Convert to special POS token in decompiler and parse tree
8796 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8797 ((= tt js2-SUB)
8798 (js2-consume-token)
8799 ;; Convert to special NEG token in decompiler and parse tree
8800 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8801 ((or (= tt js2-INC)
8802 (= tt js2-DEC))
8803 (js2-consume-token)
8804 (prog1
8805 (setq beg js2-token-beg
8806 end js2-token-end
8807 expr (js2-make-unary tt 'js2-parse-member-expr t))
8808 (js2-check-bad-inc-dec tt beg end expr)))
8809 ((= tt js2-DELPROP)
8810 (js2-consume-token)
8811 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8812 ((= tt js2-ERROR)
8813 (js2-consume-token)
8814 (make-js2-error-node)) ; try to continue
8815 ((and (= tt js2-LT)
8816 js2-compiler-xml-available)
8817 ;; XML stream encountered in expression.
8818 (js2-consume-token)
8819 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8820 (t
8821 (setq pn (js2-parse-member-expr t)
8822 ;; Don't look across a newline boundary for a postfix incop.
8823 tt (js2-peek-token-or-eol))
8824 (when (or (= tt js2-INC) (= tt js2-DEC))
8825 (js2-consume-token)
8826 (setf expr pn
8827 pn (js2-make-unary tt expr))
8828 (js2-node-set-prop pn 'postfix t)
8829 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8830 pn))))
8831
8832 (defun js2-parse-xml-initializer ()
8833 "Parse an E4X XML initializer.
8834 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8835 Then I'll postprocess the result, depending on whether we're in IDE
8836 mode or codegen mode, and generate the appropriate rewritten AST.
8837 IDE mode uses a rich AST that models the XML structure. Codegen mode
8838 just concatenates everything and makes a new XML or XMLList out of it."
8839 (let ((tt (js2-get-first-xml-token))
8840 pn-xml
8841 pn
8842 expr
8843 kids
8844 expr-pos
8845 (continue t)
8846 (first-token t))
8847 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8848 (js2-report-error "msg.syntax"))
8849 (setq pn-xml (make-js2-xml-node))
8850 (while continue
8851 (if first-token
8852 (setq first-token nil)
8853 (setq tt (js2-get-next-xml-token)))
8854 (cond
8855 ;; js2-XML means we found a {expr} in the XML stream.
8856 ;; The js2-ts-string is the XML up to the left-curly.
8857 ((= tt js2-XML)
8858 (push (make-js2-string-node :pos js2-token-beg
8859 :len (- js2-ts-cursor js2-token-beg))
8860 kids)
8861 (js2-must-match js2-LC "msg.syntax")
8862 (setq expr-pos js2-ts-cursor
8863 expr (if (eq (js2-peek-token) js2-RC)
8864 (make-js2-empty-expr-node :pos expr-pos)
8865 (js2-parse-expr)))
8866 (js2-must-match js2-RC "msg.syntax")
8867 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8868 :len (js2-node-len expr)
8869 :expr expr))
8870 (js2-node-add-children pn expr)
8871 (push pn kids))
8872 ;; a js2-XMLEND token means we hit the final close-tag.
8873 ((= tt js2-XMLEND)
8874 (push (make-js2-string-node :pos js2-token-beg
8875 :len (- js2-ts-cursor js2-token-beg))
8876 kids)
8877 (dolist (kid (nreverse kids))
8878 (js2-block-node-push pn-xml kid))
8879 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8880 (js2-node-pos pn-xml))
8881 continue nil))
8882 (t
8883 (js2-report-error "msg.syntax")
8884 (setq continue nil))))
8885 pn-xml))
8886
8887
8888 (defun js2-parse-argument-list ()
8889 "Parse an argument list and return it as a lisp list of nodes.
8890 Returns the list in reverse order. Consumes the right-paren token."
8891 (let (result)
8892 (unless (js2-match-token js2-RP)
8893 (loop do
8894 (if (= (js2-peek-token) js2-YIELD)
8895 (js2-report-error "msg.yield.parenthesized"))
8896 (push (js2-parse-assign-expr) result)
8897 while
8898 (js2-match-token js2-COMMA))
8899 (js2-must-match js2-RP "msg.no.paren.arg")
8900 result)))
8901
8902 (defun js2-parse-member-expr (&optional allow-call-syntax)
8903 (let ((tt (js2-peek-token))
8904 pn
8905 pos
8906 target
8907 args
8908 beg
8909 end
8910 init
8911 tail)
8912 (if (/= tt js2-NEW)
8913 (setq pn (js2-parse-primary-expr))
8914 ;; parse a 'new' expression
8915 (js2-consume-token)
8916 (setq pos js2-token-beg
8917 beg pos
8918 target (js2-parse-member-expr)
8919 end (js2-node-end target)
8920 pn (make-js2-new-node :pos pos
8921 :target target
8922 :len (- end pos)))
8923 (js2-node-add-children pn target)
8924 (when (js2-match-token js2-LP)
8925 ;; Add the arguments to pn, if any are supplied.
8926 (setf beg pos ; start of "new" keyword
8927 pos js2-token-beg
8928 args (nreverse (js2-parse-argument-list))
8929 (js2-new-node-args pn) args
8930 end js2-token-end
8931 (js2-new-node-lp pn) (- pos beg)
8932 (js2-new-node-rp pn) (- end 1 beg))
8933 (apply #'js2-node-add-children pn args))
8934 (when (and js2-allow-rhino-new-expr-initializer
8935 (js2-match-token js2-LC))
8936 (setf init (js2-parse-object-literal)
8937 end (js2-node-end init)
8938 (js2-new-node-initializer pn) init)
8939 (js2-node-add-children pn init))
8940 (setf (js2-node-len pn) (- end beg))) ; end outer if
8941 (js2-parse-member-expr-tail allow-call-syntax pn)))
8942
8943 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8944 "Parse a chain of property/array accesses or function calls.
8945 Includes parsing for E4X operators like `..' and `.@'.
8946 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8947 Returns an expression tree that includes PN, the parent node."
8948 (let ((beg (js2-node-pos pn))
8949 tt
8950 (continue t))
8951 (while continue
8952 (setq tt (js2-peek-token))
8953 (cond
8954 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8955 (setq pn (js2-parse-property-access tt pn)))
8956 ((= tt js2-DOTQUERY)
8957 (setq pn (js2-parse-dot-query pn)))
8958 ((= tt js2-LB)
8959 (setq pn (js2-parse-element-get pn)))
8960 ((= tt js2-LP)
8961 (if allow-call-syntax
8962 (setq pn (js2-parse-function-call pn))
8963 (setq continue nil)))
8964 (t
8965 (setq continue nil))))
8966 (if (>= js2-highlight-level 2)
8967 (js2-parse-highlight-member-expr-node pn))
8968 pn))
8969
8970 (defun js2-parse-dot-query (pn)
8971 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8972 Last token parsed must be `js2-DOTQUERY'."
8973 (let ((pos (js2-node-pos pn))
8974 op-pos
8975 expr
8976 end)
8977 (js2-consume-token)
8978 (js2-must-have-xml)
8979 (js2-set-requires-activation)
8980 (setq op-pos js2-token-beg
8981 expr (js2-parse-expr)
8982 end (js2-node-end expr)
8983 pn (make-js2-xml-dot-query-node :left pn
8984 :pos pos
8985 :op-pos op-pos
8986 :right expr))
8987 (js2-node-add-children pn
8988 (js2-xml-dot-query-node-left pn)
8989 (js2-xml-dot-query-node-right pn))
8990 (if (js2-must-match js2-RP "msg.no.paren")
8991 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8992 end js2-token-end))
8993 (setf (js2-node-len pn) (- end pos))
8994 pn))
8995
8996 (defun js2-parse-element-get (pn)
8997 "Parse an element-get expression, e.g. foo[bar].
8998 Last token parsed must be `js2-RB'."
8999 (let ((lb js2-token-beg)
9000 (pos (js2-node-pos pn))
9001 rb
9002 expr)
9003 (js2-consume-token)
9004 (setq expr (js2-parse-expr))
9005 (if (js2-must-match js2-RB "msg.no.bracket.index")
9006 (setq rb js2-token-beg))
9007 (setq pn (make-js2-elem-get-node :target pn
9008 :pos pos
9009 :element expr
9010 :lb (js2-relpos lb pos)
9011 :rb (js2-relpos rb pos)
9012 :len (- js2-token-end pos)))
9013 (js2-node-add-children pn
9014 (js2-elem-get-node-target pn)
9015 (js2-elem-get-node-element pn))
9016 pn))
9017
9018 (defun js2-parse-function-call (pn)
9019 (let (args
9020 (pos (js2-node-pos pn)))
9021 (js2-consume-token)
9022 (setq pn (make-js2-call-node :pos pos
9023 :target pn
9024 :lp (- js2-token-beg pos)))
9025 (js2-node-add-children pn (js2-call-node-target pn))
9026 ;; Add the arguments to pn, if any are supplied.
9027 (setf args (nreverse (js2-parse-argument-list))
9028 (js2-call-node-rp pn) (- js2-token-beg pos)
9029 (js2-call-node-args pn) args)
9030 (apply #'js2-node-add-children pn args)
9031 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9032 pn))
9033
9034 (defun js2-parse-property-access (tt pn)
9035 "Parse a property access, XML descendants access, or XML attr access."
9036 (let ((member-type-flags 0)
9037 (dot-pos js2-token-beg)
9038 (dot-len (if (= tt js2-DOTDOT) 2 1))
9039 name
9040 ref ; right side of . or .. operator
9041 result)
9042 (js2-consume-token)
9043 (when (= tt js2-DOTDOT)
9044 (js2-must-have-xml)
9045 (setq member-type-flags js2-descendants-flag))
9046 (if (not js2-compiler-xml-available)
9047 (progn
9048 (js2-must-match-prop-name "msg.no.name.after.dot")
9049 (setq name (js2-create-name-node t js2-GETPROP)
9050 result (make-js2-prop-get-node :left pn
9051 :pos js2-token-beg
9052 :right name
9053 :len (- js2-token-end
9054 js2-token-beg)))
9055 (js2-node-add-children result pn name)
9056 result)
9057 ;; otherwise look for XML operators
9058 (setf result (if (= tt js2-DOT)
9059 (make-js2-prop-get-node)
9060 (make-js2-infix-node :type js2-DOTDOT))
9061 (js2-node-pos result) (js2-node-pos pn)
9062 (js2-infix-node-op-pos result) dot-pos
9063 (js2-infix-node-left result) pn ; do this after setting position
9064 tt (js2-next-token))
9065 (cond
9066 ;; needed for generator.throw()
9067 ((= tt js2-THROW)
9068 (js2-save-name-token-data js2-token-beg "throw")
9069 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9070 ;; handles: name, ns::name, ns::*, ns::[expr]
9071 ((js2-valid-prop-name-token tt)
9072 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9073 ;; handles: *, *::name, *::*, *::[expr]
9074 ((= tt js2-MUL)
9075 (js2-save-name-token-data js2-token-beg "*")
9076 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9077 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9078 ((= tt js2-XMLATTR)
9079 (setq result (js2-parse-attribute-access)))
9080 (t
9081 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9082 (if ref
9083 (setf (js2-node-len result) (- (js2-node-end ref)
9084 (js2-node-pos result))
9085 (js2-infix-node-right result) ref))
9086 (if (js2-infix-node-p result)
9087 (js2-node-add-children result
9088 (js2-infix-node-left result)
9089 (js2-infix-node-right result)))
9090 result)))
9091
9092 (defun js2-parse-attribute-access ()
9093 "Parse an E4X XML attribute expression.
9094 This includes expressions of the forms:
9095
9096 @attr @ns::attr @ns::*
9097 @* @*::attr @*::*
9098 @[expr] @*::[expr] @ns::[expr]
9099
9100 Called if we peeked an '@' token."
9101 (let ((tt (js2-next-token))
9102 (at-pos js2-token-beg))
9103 (cond
9104 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9105 ((js2-valid-prop-name-token tt)
9106 (js2-parse-property-name at-pos js2-ts-string 0))
9107 ;; handles: @*, @*::name, @*::*, @*::[expr]
9108 ((= tt js2-MUL)
9109 (js2-save-name-token-data js2-token-beg "*")
9110 (js2-parse-property-name js2-token-beg "*" 0))
9111 ;; handles @[expr]
9112 ((= tt js2-LB)
9113 (js2-parse-xml-elem-ref at-pos))
9114 (t
9115 (js2-report-error "msg.no.name.after.xmlAttr")
9116 ;; Avoid cascaded errors that happen if we make an error node here.
9117 (js2-save-name-token-data js2-token-beg "")
9118 (js2-parse-property-name js2-token-beg "" 0)))))
9119
9120 (defun js2-parse-property-name (at-pos s member-type-flags)
9121 "Check if :: follows name in which case it becomes qualified name.
9122
9123 AT-POS is a natural number if we just read an '@' token, else nil.
9124 S is the name or string that was matched: an identifier, 'throw' or '*'.
9125 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9126
9127 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9128 operator, or the name is followed by ::. For a plain name, returns a
9129 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9130 (let ((pos (or at-pos js2-token-beg))
9131 colon-pos
9132 (name (js2-create-name-node t js2-current-token))
9133 ns
9134 tt
9135 ref
9136 pn)
9137 (catch 'return
9138 (when (js2-match-token js2-COLONCOLON)
9139 (setq ns name
9140 colon-pos js2-token-beg
9141 tt (js2-next-token))
9142 (cond
9143 ;; handles name::name
9144 ((js2-valid-prop-name-token tt)
9145 (setq name (js2-create-name-node)))
9146 ;; handles name::*
9147 ((= tt js2-MUL)
9148 (js2-save-name-token-data js2-token-beg "*")
9149 (setq name (js2-create-name-node)))
9150 ;; handles name::[expr]
9151 ((= tt js2-LB)
9152 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9153 (t
9154 (js2-report-error "msg.no.name.after.coloncolon"))))
9155 (if (and (null ns) (zerop member-type-flags))
9156 name
9157 (prog1
9158 (setq pn
9159 (make-js2-xml-prop-ref-node :pos pos
9160 :len (- (js2-node-end name) pos)
9161 :at-pos at-pos
9162 :colon-pos colon-pos
9163 :propname name))
9164 (js2-node-add-children pn name))))))
9165
9166 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9167 "Parse the [expr] portion of an xml element reference.
9168 For instance, @[expr], @*::[expr], or ns::[expr]."
9169 (let* ((lb js2-token-beg)
9170 (pos (or at-pos lb))
9171 rb
9172 (expr (js2-parse-expr))
9173 (end (js2-node-end expr))
9174 pn)
9175 (if (js2-must-match js2-RB "msg.no.bracket.index")
9176 (setq rb js2-token-beg
9177 end js2-token-end))
9178 (prog1
9179 (setq pn
9180 (make-js2-xml-elem-ref-node :pos pos
9181 :len (- end pos)
9182 :namespace namespace
9183 :colon-pos colon-pos
9184 :at-pos at-pos
9185 :expr expr
9186 :lb (js2-relpos lb pos)
9187 :rb (js2-relpos rb pos)))
9188 (js2-node-add-children pn namespace expr))))
9189
9190 (defsubst js2-parse-primary-expr-lhs ()
9191 (let ((js2-is-in-lhs t))
9192 (js2-parse-primary-expr)))
9193
9194 (defun js2-parse-primary-expr ()
9195 "Parses a literal (leaf) expression of some sort.
9196 Includes complex literals such as functions, object-literals,
9197 array-literals, array comprehensions and regular expressions."
9198 (let ((tt-flagged (js2-next-flagged-token))
9199 pn ; parent node (usually return value)
9200 tt
9201 px-pos ; paren-expr pos
9202 len
9203 flags ; regexp flags
9204 expr)
9205 (setq tt js2-current-token)
9206 (cond
9207 ((= tt js2-FUNCTION)
9208 (js2-parse-function 'FUNCTION_EXPRESSION))
9209 ((= tt js2-LB)
9210 (js2-parse-array-literal))
9211 ((= tt js2-LC)
9212 (js2-parse-object-literal))
9213 ((= tt js2-LET)
9214 (js2-parse-let js2-token-beg))
9215 ((= tt js2-LP)
9216 (setq px-pos js2-token-beg
9217 expr (js2-parse-expr))
9218 (js2-must-match js2-RP "msg.no.paren")
9219 (setq pn (make-js2-paren-node :pos px-pos
9220 :expr expr
9221 :len (- js2-token-end px-pos)))
9222 (js2-node-add-children pn (js2-paren-node-expr pn))
9223 pn)
9224 ((= tt js2-XMLATTR)
9225 (js2-must-have-xml)
9226 (js2-parse-attribute-access))
9227 ((= tt js2-NAME)
9228 (js2-parse-name tt-flagged tt))
9229 ((= tt js2-NUMBER)
9230 (make-js2-number-node))
9231 ((= tt js2-STRING)
9232 (prog1
9233 (make-js2-string-node)
9234 (js2-record-face 'font-lock-string-face)))
9235 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9236 ;; Got / or /= which in this context means a regexp literal
9237 (setq px-pos js2-token-beg)
9238 (js2-read-regexp tt)
9239 (setq flags js2-ts-regexp-flags
9240 js2-ts-regexp-flags nil)
9241 (prog1
9242 (make-js2-regexp-node :pos px-pos
9243 :len (- js2-ts-cursor px-pos)
9244 :value js2-ts-string
9245 :flags flags)
9246 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9247 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9248 ((or (= tt js2-NULL)
9249 (= tt js2-THIS)
9250 (= tt js2-FALSE)
9251 (= tt js2-TRUE))
9252 (make-js2-keyword-node :type tt))
9253 ((= tt js2-RESERVED)
9254 (js2-report-error "msg.reserved.id")
9255 (make-js2-name-node))
9256 ((= tt js2-ERROR)
9257 ;; the scanner or one of its subroutines reported the error.
9258 (make-js2-error-node))
9259 ((= tt js2-EOF)
9260 (setq px-pos (point-at-bol)
9261 len (- js2-ts-cursor px-pos))
9262 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9263 (make-js2-error-node :pos px-pos :len len))
9264 (t
9265 (js2-report-error "msg.syntax")
9266 (make-js2-error-node)))))
9267
9268 (defun js2-parse-name (tt-flagged tt)
9269 (let ((name js2-ts-string)
9270 (name-pos js2-token-beg))
9271 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9272 (= (js2-peek-token) js2-COLON))
9273 (prog1
9274 ;; Do not consume colon, it is used as unwind indicator
9275 ;; to return to statementHelper.
9276 (make-js2-label-node :pos name-pos
9277 :len (- js2-token-end name-pos)
9278 :name name)
9279 (js2-set-face name-pos
9280 js2-token-end
9281 'font-lock-variable-name-face 'record))
9282 ;; Otherwise not a label, just a name. Unfortunately peeking
9283 ;; the next token to check for a colon has biffed js2-token-beg
9284 ;; and js2-token-end. We store the name's bounds in buffer vars
9285 ;; and `js2-create-name-node' uses them.
9286 (js2-save-name-token-data name-pos name)
9287 (if js2-compiler-xml-available
9288 (js2-parse-property-name nil name 0)
9289 (js2-create-name-node 'check-activation)))))
9290
9291 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9292 (js2-add-strict-warning
9293 msg nil
9294 ;; back up from comma to beginning of line or array/objlit
9295 (max (if elems
9296 (js2-node-pos (car elems))
9297 pos)
9298 (save-excursion
9299 (goto-char comma-pos)
9300 (back-to-indentation)
9301 (point)))
9302 comma-pos))
9303
9304 (defun js2-parse-array-literal ()
9305 (let ((pos js2-token-beg)
9306 (end js2-token-end)
9307 (after-lb-or-comma t)
9308 after-comma
9309 tt
9310 elems
9311 pn
9312 (continue t))
9313 (while continue
9314 (setq tt (js2-peek-token))
9315 (cond
9316 ;; comma
9317 ((= tt js2-COMMA)
9318 (js2-consume-token)
9319 (setq after-comma js2-token-end)
9320 (if (not after-lb-or-comma)
9321 (setq after-lb-or-comma t)
9322 (push nil elems)))
9323 ;; end of array
9324 ((or (= tt js2-RB)
9325 (= tt js2-EOF)) ; prevent infinite loop
9326 (if (= tt js2-EOF)
9327 (js2-report-error "msg.no.bracket.arg" nil pos)
9328 (js2-consume-token))
9329 (setq continue nil
9330 end js2-token-end
9331 pn (make-js2-array-node :pos pos
9332 :len (- js2-ts-cursor pos)
9333 :elems (nreverse elems)))
9334 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9335 (when after-comma
9336 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9337 pos elems after-comma)))
9338 ;; destructuring binding
9339 (js2-is-in-lhs
9340 (push (if (or (= tt js2-LC)
9341 (= tt js2-LB)
9342 (= tt js2-NAME))
9343 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9344 (js2-parse-primary-expr-lhs)
9345 ;; invalid pattern
9346 (js2-consume-token)
9347 (js2-report-error "msg.bad.var")
9348 (make-js2-error-node))
9349 elems)
9350 (setq after-lb-or-comma nil
9351 after-comma nil))
9352 ;; array comp
9353 ((and (>= js2-language-version 170)
9354 (= tt js2-FOR) ; check for array comprehension
9355 (not after-lb-or-comma) ; "for" can't follow a comma
9356 elems ; must have at least 1 element
9357 (not (cdr elems))) ; but no 2nd element
9358 (setf continue nil
9359 pn (js2-parse-array-comprehension (car elems) pos)))
9360
9361 ;; another element
9362 (t
9363 (unless after-lb-or-comma
9364 (js2-report-error "msg.no.bracket.arg"))
9365 (push (js2-parse-assign-expr) elems)
9366 (setq after-lb-or-comma nil
9367 after-comma nil))))
9368 pn))
9369
9370 (defun js2-parse-array-comprehension (expr pos)
9371 "Parse a JavaScript 1.7 Array Comprehension.
9372 EXPR is the first expression after the opening left-bracket.
9373 POS is the beginning of the LB token preceding EXPR.
9374 We should have just parsed the 'for' keyword before calling this function."
9375 (let (loops
9376 filter
9377 if-pos
9378 result)
9379 (while (= (js2-peek-token) js2-FOR)
9380 (push (js2-parse-array-comp-loop) loops))
9381 (when (= (js2-peek-token) js2-IF)
9382 (js2-consume-token)
9383 (setq if-pos (- js2-token-beg pos) ; relative
9384 filter (js2-parse-condition)))
9385 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9386 (setq result (make-js2-array-comp-node :pos pos
9387 :len (- js2-ts-cursor pos)
9388 :result expr
9389 :loops (nreverse loops)
9390 :filter (car filter)
9391 :lp (js2-relpos (second filter) pos)
9392 :rp (js2-relpos (third filter) pos)
9393 :if-pos if-pos))
9394 (apply #'js2-node-add-children result expr (car filter)
9395 (js2-array-comp-node-loops result))
9396 result))
9397
9398 (defun js2-parse-array-comp-loop ()
9399 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9400 Last token peeked should be the initial FOR."
9401 (let ((pos js2-token-beg)
9402 (pn (make-js2-array-comp-loop-node))
9403 tt
9404 iter
9405 obj
9406 foreach-p
9407 in-pos
9408 each-pos
9409 lp
9410 rp)
9411 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9412 (js2-push-scope pn)
9413 (unwind-protect
9414 (progn
9415 (when (js2-match-token js2-NAME)
9416 (if (string= js2-ts-string "each")
9417 (progn
9418 (setq foreach-p t
9419 each-pos (- js2-token-beg pos)) ; relative
9420 (js2-record-face 'font-lock-keyword-face))
9421 (js2-report-error "msg.no.paren.for")))
9422 (if (js2-must-match js2-LP "msg.no.paren.for")
9423 (setq lp (- js2-token-beg pos)))
9424 (setq tt (js2-peek-token))
9425 (cond
9426 ((or (= tt js2-LB)
9427 (= tt js2-LC))
9428 ;; handle destructuring assignment
9429 (setq iter (js2-parse-primary-expr-lhs)))
9430 ((js2-valid-prop-name-token tt)
9431 (js2-consume-token)
9432 (setq iter (js2-create-name-node)))
9433 (t
9434 (js2-report-error "msg.bad.var")))
9435 ;; Define as a let since we want the scope of the variable to
9436 ;; be restricted to the array comprehension
9437 (if (js2-name-node-p iter)
9438 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9439 (if (js2-must-match js2-IN "msg.in.after.for.name")
9440 (setq in-pos (- js2-token-beg pos)))
9441 (setq obj (js2-parse-expr))
9442 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9443 (setq rp (- js2-token-beg pos)))
9444 (setf (js2-node-pos pn) pos
9445 (js2-node-len pn) (- js2-ts-cursor pos)
9446 (js2-array-comp-loop-node-iterator pn) iter
9447 (js2-array-comp-loop-node-object pn) obj
9448 (js2-array-comp-loop-node-in-pos pn) in-pos
9449 (js2-array-comp-loop-node-each-pos pn) each-pos
9450 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9451 (js2-array-comp-loop-node-lp pn) lp
9452 (js2-array-comp-loop-node-rp pn) rp)
9453 (js2-node-add-children pn iter obj))
9454 (js2-pop-scope))
9455 pn))
9456
9457 (defun js2-parse-object-literal ()
9458 (let ((pos js2-token-beg)
9459 tt
9460 elems
9461 result
9462 after-comma
9463 (continue t))
9464 (while continue
9465 (setq tt (js2-peek-token))
9466 (cond
9467 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9468 ((or (js2-valid-prop-name-token tt)
9469 (= tt js2-STRING))
9470 (setq after-comma nil
9471 result (js2-parse-named-prop tt))
9472 (if (and (null result)
9473 (not js2-recover-from-parse-errors))
9474 (setq continue nil)
9475 (push result elems)))
9476 ;; {12: x} or {10.7: x}
9477 ((= tt js2-NUMBER)
9478 (js2-consume-token)
9479 (setq after-comma nil)
9480 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9481 ;; trailing comma
9482 ((= tt js2-RC)
9483 (setq continue nil)
9484 (if after-comma
9485 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9486 pos elems after-comma)))
9487 (t
9488 (js2-report-error "msg.bad.prop")
9489 (unless js2-recover-from-parse-errors
9490 (setq continue nil)))) ; end switch
9491 (if (js2-match-token js2-COMMA)
9492 (setq after-comma js2-token-end)
9493 (setq continue nil))) ; end loop
9494 (js2-must-match js2-RC "msg.no.brace.prop")
9495 (setq result (make-js2-object-node :pos pos
9496 :len (- js2-ts-cursor pos)
9497 :elems (nreverse elems)))
9498 (apply #'js2-node-add-children result (js2-object-node-elems result))
9499 result))
9500
9501 (defun js2-parse-named-prop (tt)
9502 "Parse a name, string, or getter/setter object property.
9503 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9504 (js2-consume-token)
9505 (let ((string-prop (and (= tt js2-STRING)
9506 (make-js2-string-node)))
9507 expr
9508 (ppos js2-token-beg)
9509 (pend js2-token-end)
9510 (name (js2-create-name-node))
9511 (prop js2-ts-string))
9512 (cond
9513 ;; getter/setter prop
9514 ((and (= tt js2-NAME)
9515 (= (js2-peek-token) js2-NAME)
9516 (or (string= prop "get")
9517 (string= prop "set")))
9518 (progn
9519 (js2-consume-token)
9520 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9521 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9522 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9523 (js2-parse-getter-setter-prop ppos name (string= prop "get"))))
9524 ;; abbreviated destructuring bind e.g., {a, b} = c;
9525 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9526 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9527 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9528 ;; assignment but it's difficult because it requires looking ahead of expression.
9529 ((and js2-is-in-lhs
9530 (= tt js2-NAME)
9531 (let ((ctk (js2-peek-token)))
9532 (or (= ctk js2-COMMA)
9533 (= ctk js2-RC)
9534 (js2-valid-prop-name-token ctk))))
9535 (js2-set-face ppos pend 'font-lock-variable-name-face 'record)
9536 name)
9537 ;; regular prop
9538 (t
9539 (prog1
9540 (setq expr (js2-parse-plain-property (or string-prop name)))
9541 (js2-set-face ppos pend
9542 (if (js2-function-node-p
9543 (js2-object-prop-node-right expr))
9544 'font-lock-function-name-face
9545 'font-lock-variable-name-face)
9546 'record))))))
9547
9548 (defun js2-parse-plain-property (prop)
9549 "Parse a non-getter/setter property in an object literal.
9550 PROP is the node representing the property: a number, name or string."
9551 (js2-must-match js2-COLON "msg.no.colon.prop")
9552 (let* ((pos (js2-node-pos prop))
9553 (colon (- js2-token-beg pos))
9554 (expr (js2-parse-assign-expr))
9555 (result (make-js2-object-prop-node
9556 :pos pos
9557 ;; don't include last consumed token in length
9558 :len (- (+ (js2-node-pos expr)
9559 (js2-node-len expr))
9560 pos)
9561 :left prop
9562 :right expr
9563 :op-pos colon)))
9564 (js2-node-add-children result prop expr)
9565 result))
9566
9567 (defun js2-parse-getter-setter-prop (pos prop get-p)
9568 "Parse getter or setter property in an object literal.
9569 JavaScript syntax is:
9570
9571 { get foo() {...}, set foo(x) {...} }
9572
9573 and expression closure style is also supported
9574
9575 { get foo() x, set foo(x) _x = x }
9576
9577 POS is the start position of the `get' or `set' keyword.
9578 PROP is the `js2-name-node' representing the property name.
9579 GET-P is non-nil if the keyword was `get'."
9580 (let ((type (if get-p js2-GET js2-SET))
9581 result
9582 end
9583 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9584 ;; it has to be an anonymous function, as we already parsed the name
9585 (if (/= (js2-node-type fn) js2-FUNCTION)
9586 (js2-report-error "msg.bad.prop")
9587 (if (plusp (length (js2-function-name fn)))
9588 (js2-report-error "msg.bad.prop")))
9589 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9590 (setq end (js2-node-end fn)
9591 result (make-js2-getter-setter-node :type type
9592 :pos pos
9593 :len (- end pos)
9594 :left prop
9595 :right fn))
9596 (js2-node-add-children result prop fn)
9597 result))
9598
9599 (defun js2-create-name-node (&optional check-activation-p token)
9600 "Create a name node using the token info from last scanned name.
9601 In some cases we need to either synthesize a name node, or we lost
9602 the name token information by peeking. If the TOKEN parameter is
9603 not `js2-NAME', then we use the token info saved in instance vars."
9604 (let ((beg js2-token-beg)
9605 (s js2-ts-string)
9606 name)
9607 (when (/= js2-current-token js2-NAME)
9608 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9609 s js2-prev-name-token-string
9610 js2-prev-name-token-start nil
9611 js2-prev-name-token-string nil))
9612 (setq name (make-js2-name-node :pos beg
9613 :name s
9614 :len (length s)))
9615 (if check-activation-p
9616 (js2-check-activation-name s (or token js2-NAME)))
9617 name))
9618
9619 ;;; Indentation support
9620
9621 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9622 ;; Karl cleverly deduces that the desired indentation level is often a
9623 ;; function of paren/bracket/brace nesting depth, which can be determined
9624 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9625 ;; then does some equally clever checks to see if we're in the context of a
9626 ;; substatement of a possibly braceless statement keyword such as if, while,
9627 ;; or finally. This approach yields pretty good results.
9628
9629 ;; The indenter is often "wrong", however, and needs to be overridden.
9630 ;; The right long-term solution is probably to emulate (or integrate
9631 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9632 ;; parse tree from `js2-parse' is present, which is not true at the
9633 ;; moment the user is typing, computing indentation is still thousands
9634 ;; of lines of code to handle every possible syntactic edge case.
9635
9636 ;; In the meantime, the compromise solution is that we offer a "bounce
9637 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9638 ;; current line indent among various likely guess points. This approach
9639 ;; is far from perfect, but should at least make it slightly easier to
9640 ;; move the line towards its desired indentation when manually
9641 ;; overriding Karl's heuristic nesting guesser.
9642
9643 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9644 ;; extensions such as `let' and Array comprehensions. Major kudos to
9645 ;; Karl for coming up with the initial approach, which packs a lot of
9646 ;; punch for so little code.
9647
9648 (defconst js-possibly-braceless-keyword-re
9649 (regexp-opt
9650 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9651 'words)
9652 "Regular expression matching keywords that are optionally
9653 followed by an opening brace.")
9654
9655 (defconst js-possibly-braceless-keywords-re
9656 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9657 "Regular expression which matches the keywords which are consist of more than 2 words
9658 like 'if else' and 'for each', and optionally followed by an opening brace.")
9659
9660 (defconst js-indent-operator-re
9661 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9662 (regexp-opt '("in" "instanceof") 'words))
9663 "Regular expression matching operators that affect indentation
9664 of continued expressions.")
9665
9666 ;; This function has horrible results if you're typing an array
9667 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9668 ;; in conjunction with electric-indent, so just disabling it.
9669 (defsubst js2-code-at-bol-p ()
9670 "Return t if the first character on line is non-whitespace."
9671 nil)
9672
9673 (defun js2-insert-and-indent (key)
9674 "Run command bound to key and indent current line. Runs the command
9675 bound to KEY in the global keymap and indents the current line."
9676 (interactive (list (this-command-keys)))
9677 (let ((cmd (lookup-key (current-global-map) key)))
9678 (if (commandp cmd)
9679 (call-interactively cmd)))
9680 ;; don't do the electric keys inside comments or strings,
9681 ;; and don't do bounce-indent with them.
9682 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9683 (js2-bounce-indent-p (js2-code-at-bol-p)))
9684 (unless (or (nth 3 parse-state)
9685 (nth 4 parse-state))
9686 (indent-according-to-mode))))
9687
9688 (defun js-re-search-forward-inner (regexp &optional bound count)
9689 "Auxiliary function for `js-re-search-forward'."
9690 (let ((parse)
9691 (saved-point (point-min)))
9692 (while (> count 0)
9693 (re-search-forward regexp bound)
9694 (setq parse (parse-partial-sexp saved-point (point)))
9695 (cond ((nth 3 parse)
9696 (re-search-forward
9697 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9698 (save-excursion (end-of-line) (point)) t))
9699 ((nth 7 parse)
9700 (forward-line))
9701 ((or (nth 4 parse)
9702 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9703 (re-search-forward "\\*/"))
9704 (t
9705 (setq count (1- count))))
9706 (setq saved-point (point))))
9707 (point))
9708
9709 (defun js-re-search-forward (regexp &optional bound noerror count)
9710 "Search forward but ignore strings and comments. Invokes
9711 `re-search-forward' but treats the buffer as if strings and
9712 comments have been removed."
9713 (let ((saved-point (point))
9714 (search-expr
9715 (cond ((null count)
9716 '(js-re-search-forward-inner regexp bound 1))
9717 ((< count 0)
9718 '(js-re-search-backward-inner regexp bound (- count)))
9719 ((> count 0)
9720 '(js-re-search-forward-inner regexp bound count)))))
9721 (condition-case err
9722 (eval search-expr)
9723 (search-failed
9724 (goto-char saved-point)
9725 (unless noerror
9726 (error (error-message-string err)))))))
9727
9728 (defun js-re-search-backward-inner (regexp &optional bound count)
9729 "Auxiliary function for `js-re-search-backward'."
9730 (let ((parse)
9731 (saved-point (point-min)))
9732 (while (> count 0)
9733 (re-search-backward regexp bound)
9734 (setq parse (parse-partial-sexp saved-point (point)))
9735 (cond ((nth 3 parse)
9736 (re-search-backward
9737 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9738 (save-excursion (beginning-of-line) (point)) t))
9739 ((nth 7 parse)
9740 (goto-char (nth 8 parse)))
9741 ((or (nth 4 parse)
9742 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9743 (re-search-backward "/\\*"))
9744 (t
9745 (setq count (1- count))))))
9746 (point))
9747
9748 (defun js-re-search-backward (regexp &optional bound noerror count)
9749 "Search backward but ignore strings and comments. Invokes
9750 `re-search-backward' but treats the buffer as if strings and
9751 comments have been removed."
9752 (let ((saved-point (point))
9753 (search-expr
9754 (cond ((null count)
9755 '(js-re-search-backward-inner regexp bound 1))
9756 ((< count 0)
9757 '(js-re-search-forward-inner regexp bound (- count)))
9758 ((> count 0)
9759 '(js-re-search-backward-inner regexp bound count)))))
9760 (condition-case err
9761 (eval search-expr)
9762 (search-failed
9763 (goto-char saved-point)
9764 (unless noerror
9765 (error (error-message-string err)))))))
9766
9767 (defun js-looking-at-operator-p ()
9768 "Return non-nil if text after point is an operator (that is not
9769 a comma)."
9770 (save-match-data
9771 (and (looking-at js-indent-operator-re)
9772 (or (not (looking-at ":"))
9773 (save-excursion
9774 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9775 (looking-at "?")))))))
9776
9777 (defun js-continued-expression-p ()
9778 "Returns non-nil if the current line continues an expression."
9779 (save-excursion
9780 (back-to-indentation)
9781 (or (js-looking-at-operator-p)
9782 ;; comment
9783 (and (js-re-search-backward "\n" nil t)
9784 (progn
9785 (skip-chars-backward " \t")
9786 (backward-char)
9787 (and (js-looking-at-operator-p)
9788 (and (progn (backward-char)
9789 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9790
9791 (defun js-end-of-do-while-loop-p ()
9792 "Returns non-nil if word after point is `while' of a do-while
9793 statement, else returns nil. A braceless do-while statement
9794 spanning several lines requires that the start of the loop is
9795 indented to the same column as the current line."
9796 (interactive)
9797 (save-excursion
9798 (save-match-data
9799 (when (looking-at "\\s-*\\<while\\>")
9800 (if (save-excursion
9801 (skip-chars-backward "[ \t\n]*}")
9802 (looking-at "[ \t\n]*}"))
9803 (save-excursion
9804 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9805 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9806 (or (looking-at "\\<do\\>")
9807 (let ((saved-indent (current-indentation)))
9808 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9809 (/= (current-indentation) saved-indent)))
9810 (and (looking-at "[ \t]*\\<do\\>")
9811 (not (js-re-search-forward
9812 "\\<while\\>" (point-at-eol) t))
9813 (= (current-indentation) saved-indent)))))))))
9814
9815 (defun js-get-multiline-declaration-offset ()
9816 "Returns offset (> 0) if the current line is part of
9817 multi-line variable declaration like below example, and
9818 returns 0 otherwise.
9819
9820 var a = 10,
9821 b = 20,
9822 c = 30;
9823
9824 "
9825 (let* ((node (js2-node-at-point))
9826 (pnode (and node (js2-node-parent node)))
9827 (pnode-type (and pnode (js2-node-type pnode))))
9828 (if (and node
9829 (= js2-NAME (js2-node-type node))
9830 (or
9831 (= js2-VAR pnode-type)
9832 (= js2-LET pnode-type)
9833 (= js2-CONST pnode-type)))
9834 (if (= js2-CONST pnode-type)
9835 6
9836 4)
9837 0)))
9838
9839 (defun js-ctrl-statement-indentation ()
9840 "Returns the proper indentation of the current line if it
9841 starts the body of a control statement without braces, else
9842 returns nil."
9843 (let (forward-sexp-function) ; temporarily unbind it
9844 (save-excursion
9845 (back-to-indentation)
9846 (when (save-excursion
9847 (and (not (js2-same-line (point-min)))
9848 (not (looking-at "{"))
9849 (js-re-search-backward "[[:graph:]]" nil t)
9850 (not (looking-at "[{([]"))
9851 (progn
9852 (forward-char)
9853 ;; scan-sexps sometimes throws an error
9854 (ignore-errors (backward-sexp))
9855 (when (looking-at "(") (backward-word 1))
9856 (and (save-excursion
9857 (skip-chars-backward " \t}" (point-at-bol))
9858 (or (bolp)
9859 (and (backward-word 1)
9860 (skip-chars-backward " \t}" (point-at-bol))
9861 (bolp)
9862 (looking-at js-possibly-braceless-keywords-re))))
9863 (looking-at js-possibly-braceless-keyword-re)
9864 (not (js-end-of-do-while-loop-p))))))
9865 (save-excursion
9866 (goto-char (match-beginning 0))
9867 (+ (current-indentation) js2-basic-offset))))))
9868
9869 (defun js2-indent-in-array-comp (parse-status)
9870 "Return non-nil if we think we're in an array comprehension.
9871 In particular, return the buffer position of the first `for' kwd."
9872 (let ((end (point)))
9873 (when (nth 1 parse-status)
9874 (save-excursion
9875 (goto-char (nth 1 parse-status))
9876 (when (looking-at "\\[")
9877 (forward-char 1)
9878 (js2-forward-sws)
9879 (if (looking-at "[[{]")
9880 (let (forward-sexp-function) ; use lisp version
9881 (forward-sexp) ; skip destructuring form
9882 (js2-forward-sws)
9883 (if (and (/= (char-after) ?,) ; regular array
9884 (looking-at "for"))
9885 (match-beginning 0)))
9886 ;; to skip arbitrary expressions we need the parser,
9887 ;; so we'll just guess at it.
9888 (if (re-search-forward "[^,]* \\(for\\) " end t)
9889 (match-beginning 1))))))))
9890
9891 (defun js2-array-comp-indentation (parse-status for-kwd)
9892 (if (js2-same-line for-kwd)
9893 ;; first continuation line
9894 (save-excursion
9895 (goto-char (nth 1 parse-status))
9896 (forward-char 1)
9897 (skip-chars-forward " \t")
9898 (current-column))
9899 (save-excursion
9900 (goto-char for-kwd)
9901 (current-column))))
9902
9903 (defun js-proper-indentation (parse-status)
9904 "Return the proper indentation for the current line."
9905 (save-excursion
9906 (back-to-indentation)
9907 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9908 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9909 (continued-expr-p (js-continued-expression-p))
9910 (multiline-declaration-offset (or (and js2-use-ast-for-indentation-p
9911 (js-get-multiline-declaration-offset))
9912 0))
9913 (bracket (nth 1 parse-status))
9914 beg)
9915 (cond
9916 ;; indent array comprehension continuation lines specially
9917 ((and bracket
9918 (not (js2-same-line bracket))
9919 (setq beg (js2-indent-in-array-comp parse-status))
9920 (>= (point) (save-excursion
9921 (goto-char beg)
9922 (point-at-bol)))) ; at or after first loop?
9923 (js2-array-comp-indentation parse-status beg))
9924
9925 (ctrl-stmt-indent)
9926
9927 (bracket
9928 (goto-char bracket)
9929 (cond
9930 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9931 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9932 (when (save-excursion (skip-chars-backward " \t)")
9933 (looking-at ")"))
9934 (backward-list))
9935 (if (and (nth 1 p)
9936 (not js2-consistent-level-indent-inner-bracket-p))
9937 (progn (goto-char (1+ (nth 1 p)))
9938 (skip-chars-forward " \t"))
9939 (back-to-indentation))
9940 (cond (same-indent-p
9941 (current-column))
9942 (continued-expr-p
9943 (+ (current-column) (* 2 js2-basic-offset)))
9944 ((> multiline-declaration-offset 0)
9945 (+ (current-column) js2-basic-offset multiline-declaration-offset))
9946 (t
9947 (+ (current-column) js2-basic-offset)))))
9948 (t
9949 (unless same-indent-p
9950 (forward-char)
9951 (skip-chars-forward " \t"))
9952 (current-column))))
9953
9954 (continued-expr-p js2-basic-offset)
9955
9956 ((> multiline-declaration-offset 0)
9957 (+ multiline-declaration-offset))
9958
9959 (t 0)))))
9960
9961 (defun js2-lineup-comment (parse-status)
9962 "Indent a multi-line block comment continuation line."
9963 (let* ((beg (nth 8 parse-status))
9964 (first-line (js2-same-line beg))
9965 (offset (save-excursion
9966 (goto-char beg)
9967 (if (looking-at "/\\*")
9968 (+ 1 (current-column))
9969 0))))
9970 (unless first-line
9971 (indent-line-to offset))))
9972
9973 (defun js2-backward-sws ()
9974 "Move backward through whitespace and comments."
9975 (interactive)
9976 (while (forward-comment -1)))
9977
9978 (defun js2-forward-sws ()
9979 "Move forward through whitespace and comments."
9980 (interactive)
9981 (while (forward-comment 1)))
9982
9983 (defsubst js2-current-indent (&optional pos)
9984 "Return column of indentation on current line.
9985 If POS is non-nil, go to that point and return indentation for that line."
9986 (save-excursion
9987 (if pos
9988 (goto-char pos))
9989 (back-to-indentation)
9990 (current-column)))
9991
9992 (defsubst js2-arglist-close ()
9993 "Return non-nil if we're on a line beginning with a close-paren/brace."
9994 (save-match-data
9995 (save-excursion
9996 (goto-char (point-at-bol))
9997 (js2-forward-sws)
9998 (looking-at "[])}]"))))
9999
10000 (defsubst js2-indent-looks-like-label-p ()
10001 (goto-char (point-at-bol))
10002 (js2-forward-sws)
10003 (looking-at (concat js2-mode-identifier-re ":")))
10004
10005 (defun js2-indent-in-objlit-p (parse-status)
10006 "Return non-nil if this looks like an object-literal entry."
10007 (let ((start (nth 1 parse-status)))
10008 (and
10009 start
10010 (save-excursion
10011 (and (zerop (forward-line -1))
10012 (not (< (point) start)) ; crossed a {} boundary
10013 (js2-indent-looks-like-label-p)))
10014 (save-excursion
10015 (js2-indent-looks-like-label-p)))))
10016
10017 ;; if prev line looks like foobar({ then we're passing an object
10018 ;; literal to a function call, and people pretty much always want to
10019 ;; de-dent back to the previous line, so move the 'basic-offset'
10020 ;; position to the front.
10021 (defsubst js2-indent-objlit-arg-p (parse-status)
10022 (save-excursion
10023 (back-to-indentation)
10024 (js2-backward-sws)
10025 (and (eq (1- (point)) (nth 1 parse-status))
10026 (eq (char-before) ?{)
10027 (progn
10028 (forward-char -1)
10029 (skip-chars-backward " \t")
10030 (eq (char-before) ?\()))))
10031
10032 (defsubst js2-indent-case-block-p ()
10033 (save-excursion
10034 (back-to-indentation)
10035 (js2-backward-sws)
10036 (goto-char (point-at-bol))
10037 (skip-chars-forward " \t")
10038 (save-match-data
10039 (looking-at "case\\s-.+:"))))
10040
10041 (defsubst js2-syntax-bol ()
10042 "Return the point at the first non-whitespace char on the line.
10043 Returns `point-at-bol' if the line is empty."
10044 (save-excursion
10045 (beginning-of-line)
10046 (skip-chars-forward " \t")
10047 (point)))
10048
10049 (defun js2-bounce-indent (normal-col parse-status)
10050 "Cycle among alternate computed indentation positions.
10051 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10052 of the buffer to the current point. NORMAL-COL is the indentation
10053 column computed by the heuristic guesser based on current paren,
10054 bracket, brace and statement nesting."
10055 (let ((cur-indent (js2-current-indent))
10056 (old-buffer-undo-list buffer-undo-list)
10057 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10058 (current-line (save-excursion
10059 (forward-line 0) ; move to bol
10060 (1+ (count-lines (point-min) (point)))))
10061 positions
10062 pos
10063 anchor
10064 arglist-cont
10065 same-indent
10066 prev-line-col
10067 basic-offset
10068 computed-pos)
10069 ;; temporarily don't record undo info, if user requested this
10070 (if js2-mode-indent-inhibit-undo
10071 (setq buffer-undo-list t))
10072 (unwind-protect
10073 (progn
10074 ;; first likely point: indent from beginning of previous code line
10075 (push (setq basic-offset
10076 (+ (save-excursion
10077 (back-to-indentation)
10078 (js2-backward-sws)
10079 (back-to-indentation)
10080 (setq prev-line-col (current-column)))
10081 js2-basic-offset))
10082 positions)
10083
10084 ;; (first + epsilon) likely point: indent 2x from beginning of
10085 ;; previous code line. Some companies like this approach. Ahem.
10086 ;; Seriously, though -- 4-space indent for expression continuation
10087 ;; lines isn't a bad idea. We should eventually implement it
10088 ;; that way.
10089 (push (setq basic-offset
10090 (+ (save-excursion
10091 (back-to-indentation)
10092 (js2-backward-sws)
10093 (back-to-indentation)
10094 (setq prev-line-col (current-column)))
10095 (* 2 js2-basic-offset)))
10096 positions)
10097
10098 ;; second likely point: indent from assign-expr RHS. This
10099 ;; is just a crude guess based on finding " = " on the previous
10100 ;; line containing actual code.
10101 (setq pos (save-excursion
10102 (save-match-data
10103 (forward-line -1)
10104 (goto-char (point-at-bol))
10105 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10106 (point-at-eol) t)
10107 (goto-char (match-end 1))
10108 (skip-chars-forward " \t\r\n")
10109 (current-column)))))
10110 (when pos
10111 (incf pos js2-basic-offset)
10112 (unless (member pos positions)
10113 (push pos positions)))
10114
10115 ;; third likely point: same indent as previous line of code.
10116 ;; Make it the first likely point if we're not on an
10117 ;; arglist-close line and previous line ends in a comma, or
10118 ;; both this line and prev line look like object-literal
10119 ;; elements.
10120 (setq pos (save-excursion
10121 (goto-char (point-at-bol))
10122 (js2-backward-sws)
10123 (back-to-indentation)
10124 (prog1
10125 (current-column)
10126 ;; while we're here, look for trailing comma
10127 (if (save-excursion
10128 (goto-char (point-at-eol))
10129 (js2-backward-sws)
10130 (eq (char-before) ?,))
10131 (setq arglist-cont (1- (point)))))))
10132 (when pos
10133 (if (and (or arglist-cont
10134 (js2-indent-in-objlit-p parse-status))
10135 (not (js2-arglist-close)))
10136 (setq same-indent pos))
10137 (unless (member pos positions)
10138 (push pos positions)))
10139
10140 ;; fourth likely point: first preceding code with less indentation
10141 ;; than the immediately preceding code line.
10142 (setq pos (save-excursion
10143 (js2-backward-sws)
10144 (back-to-indentation)
10145 (setq anchor (current-column))
10146 (while (and (zerop (forward-line -1))
10147 (>= (progn
10148 (back-to-indentation)
10149 (current-column))
10150 anchor)))
10151 (setq pos (current-column))))
10152 (unless (member pos positions)
10153 (push pos positions))
10154
10155 ;; put nesting-heuristic position first in list, sort rest
10156 (setq positions (nreverse (sort positions '<)))
10157 (setq positions (cons normal-col (delete normal-col positions)))
10158
10159 ;; comma-list continuation lines: prev line indent takes precedence
10160 (if same-indent
10161 (setq positions
10162 (cons same-indent
10163 (sort (delete same-indent positions) '<))))
10164
10165 ;; common special cases where we want to indent in from previous line
10166 (if (or (js2-indent-case-block-p)
10167 (js2-indent-objlit-arg-p parse-status))
10168 (setq positions
10169 (cons basic-offset
10170 (delete basic-offset positions))))
10171
10172 ;; record whether we're already sitting on one of the alternatives
10173 (setq pos (member cur-indent positions))
10174 (cond
10175 ;; case 0: we're one one of the alternatives and this is the
10176 ;; first time they've pressed TAB on this line (best-guess).
10177 ((and js2-mode-indent-ignore-first-tab
10178 pos
10179 ;; first time pressing TAB on this line?
10180 (not (eq js2-mode-last-indented-line current-line)))
10181 ;; do nothing
10182 (setq computed-pos nil))
10183 ;; case 1: only one computed position => use it
10184 ((null (cdr positions))
10185 (setq computed-pos 0))
10186 ;; case 2: not on any of the computed spots => use main spot
10187 ((not pos)
10188 (setq computed-pos 0))
10189 ;; case 3: on last position: cycle to first position
10190 ((null (cdr pos))
10191 (setq computed-pos 0))
10192 ;; case 4: on intermediate position: cycle to next position
10193 (t
10194 (setq computed-pos (js2-position (second pos) positions))))
10195
10196 ;; see if any hooks want to indent; otherwise we do it
10197 (loop with result = nil
10198 for hook in js2-indent-hook
10199 while (null result)
10200 do
10201 (setq result (funcall hook positions computed-pos))
10202 finally do
10203 (unless (or result (null computed-pos))
10204 (indent-line-to (nth computed-pos positions)))))
10205
10206 ;; finally
10207 (if js2-mode-indent-inhibit-undo
10208 (setq buffer-undo-list old-buffer-undo-list))
10209 ;; see commentary for `js2-mode-last-indented-line'
10210 (setq js2-mode-last-indented-line current-line))))
10211
10212 (defsubst js2-1-line-comment-continuation-p ()
10213 "Return t if we're in a 1-line comment continuation.
10214 If so, we don't ever want to use bounce-indent."
10215 (save-excursion
10216 (save-match-data
10217 (and (progn
10218 (forward-line 0)
10219 (looking-at "\\s-*//"))
10220 (progn
10221 (forward-line -1)
10222 (forward-line 0)
10223 (when (looking-at "\\s-*$")
10224 (js2-backward-sws)
10225 (forward-line 0))
10226 (looking-at "\\s-*//"))))))
10227
10228 (defun js2-indent-line ()
10229 "Indent the current line as JavaScript source text."
10230 (interactive)
10231 (when js2-use-ast-for-indentation-p
10232 (js2-reparse))
10233 (let (parse-status
10234 current-indent
10235 offset
10236 indent-col
10237 moved
10238 ;; don't whine about errors/warnings when we're indenting.
10239 ;; This has to be set before calling parse-partial-sexp below.
10240 (inhibit-point-motion-hooks t))
10241 (setq parse-status (save-excursion
10242 (parse-partial-sexp (point-min)
10243 (point-at-bol)))
10244 offset (- (point) (save-excursion
10245 (back-to-indentation)
10246 (setq current-indent (current-column))
10247 (point))))
10248 (js2-with-underscore-as-word-syntax
10249 (if (nth 4 parse-status)
10250 (js2-lineup-comment parse-status)
10251 (setq indent-col (js-proper-indentation parse-status))
10252 ;; see comments below about js2-mode-last-indented-line
10253 (when
10254 (cond
10255 ;; bounce-indenting is disabled during electric-key indent.
10256 ;; It doesn't work well on first line of buffer.
10257 ((and js2-bounce-indent-p
10258 (not (js2-same-line (point-min)))
10259 (not (js2-1-line-comment-continuation-p)))
10260 (js2-bounce-indent indent-col parse-status)
10261 (setq moved t))
10262 ;; just indent to the guesser's likely spot
10263 ((/= current-indent indent-col)
10264 (indent-line-to indent-col)
10265 (setq moved t)))
10266 (when (and moved (plusp offset))
10267 (forward-char offset)))))))
10268
10269 (defun js2-indent-region (start end)
10270 "Indent the region, but don't use bounce indenting."
10271 (let ((js2-bounce-indent-p nil)
10272 (indent-region-function nil))
10273 (indent-region start end nil))) ; nil for byte-compiler
10274
10275 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10276
10277 ;;;###autoload
10278 (defun js2-mode ()
10279 "Major mode for editing JavaScript code."
10280 (interactive)
10281 (kill-all-local-variables)
10282 (set-syntax-table js2-mode-syntax-table)
10283 (use-local-map js2-mode-map)
10284 (setq major-mode 'js2-mode
10285 mode-name "JavaScript-IDE"
10286 comment-start "//" ; used by comment-region; don't change it
10287 comment-end "")
10288 (setq local-abbrev-table js2-mode-abbrev-table)
10289 (set (make-local-variable 'max-lisp-eval-depth)
10290 (max max-lisp-eval-depth 3000))
10291 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10292 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10293
10294 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10295 ;; on most platforms other than the one I originally wrote it on. So it's
10296 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10297 ;; with our binding of the RET key inside comments: short lines stay short.
10298 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10299
10300 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10301 (set (make-local-variable 'next-error-function) #'js2-next-error)
10302 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10303 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10304 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10305 ;; for characters inside regexp literals.
10306 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10307 ;; this is necessary to make `show-paren-function' work properly
10308 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10309 ;; needed for M-x rgrep, among other things
10310 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10311
10312 ;; some variables needed by cc-engine for paragraph-fill, etc.
10313 (setq c-buffer-is-cc-mode t
10314 c-comment-prefix-regexp js2-comment-prefix-regexp
10315 c-comment-start-regexp "/[*/]\\|\\s|"
10316 c-paragraph-start js2-paragraph-start
10317 c-paragraph-separate "$"
10318 comment-start-skip js2-comment-start-skip
10319 c-syntactic-ws-start js2-syntactic-ws-start
10320 c-syntactic-ws-end js2-syntactic-ws-end
10321 c-syntactic-eol js2-syntactic-eol)
10322
10323 (setq js2-default-externs
10324 (append js2-ecma-262-externs
10325 (if js2-include-browser-externs
10326 js2-browser-externs)
10327 (if js2-include-gears-externs
10328 js2-gears-externs)
10329 (if js2-include-rhino-externs
10330 js2-rhino-externs)))
10331
10332 ;; We do our own syntax highlighting based on the parse tree.
10333 ;; However, we want minor modes that add keywords to highlight properly
10334 ;; (examples: doxymacs, column-marker). We do this by not letting
10335 ;; font-lock unfontify anything, and telling it to fontify after we
10336 ;; re-parse and re-highlight the buffer. (We currently don't do any
10337 ;; work with regions other than the whole buffer.)
10338 (dolist (var '(font-lock-unfontify-buffer-function
10339 font-lock-unfontify-region-function))
10340 (set (make-local-variable var) (lambda (&rest args) t)))
10341
10342 ;; Don't let font-lock do syntactic (string/comment) fontification.
10343 (set (make-local-variable #'font-lock-syntactic-face-function)
10344 (lambda (state) nil))
10345
10346 ;; Experiment: make reparse-delay longer for longer files.
10347 (if (plusp js2-dynamic-idle-timer-adjust)
10348 (setq js2-idle-timer-delay
10349 (* js2-idle-timer-delay
10350 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10351
10352 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10353 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10354 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10355 (imenu-add-to-menubar (concat "IM-" mode-name))
10356 (when js2-mirror-mode
10357 (js2-enter-mirror-mode))
10358 (add-to-invisibility-spec '(js2-outline . t))
10359 (set (make-local-variable 'line-move-ignore-invisible) t)
10360 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10361 (setq js2-mode-functions-hidden nil
10362 js2-mode-comments-hidden nil
10363 js2-mode-buffer-dirty-p t
10364 js2-mode-parsing nil)
10365 (js2-reparse)
10366 (run-hooks 'js2-mode-hook))
10367
10368 (defun js2-mode-exit ()
10369 "Exit `js2-mode' and clean up."
10370 (interactive)
10371 (when js2-mode-node-overlay
10372 (delete-overlay js2-mode-node-overlay)
10373 (setq js2-mode-node-overlay nil))
10374 (js2-remove-overlays)
10375 (setq js2-mode-ast nil)
10376 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10377 (remove-from-invisibility-spec '(js2-outline . t))
10378 (js2-mode-show-all)
10379 (js2-with-unmodifying-text-property-changes
10380 (js2-clear-face (point-min) (point-max))))
10381
10382 (defun js2-before-save ()
10383 "Clean up whitespace before saving file.
10384 You can disable this by customizing `js2-cleanup-whitespace'."
10385 (when js2-cleanup-whitespace
10386 (let ((col (current-column)))
10387 (delete-trailing-whitespace)
10388 ;; don't change trailing whitespace on current line
10389 (unless (eq (current-column) col)
10390 (indent-to col)))))
10391
10392 (defsubst js2-mode-reset-timer ()
10393 "Cancel any existing parse timer and schedule a new one."
10394 (if js2-mode-parse-timer
10395 (cancel-timer js2-mode-parse-timer))
10396 (setq js2-mode-parsing nil)
10397 (setq js2-mode-parse-timer
10398 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10399
10400 (defun js2-mode-edit (beg end len)
10401 "Schedule a new parse after buffer is edited.
10402 Buffer edit spans from BEG to END and is of length LEN.
10403 Also clears the `js2-magic' bit on autoinserted parens/brackets
10404 if the edit occurred on a line different from the magic paren."
10405 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10406 (line (if magic-pos (line-number-at-pos magic-pos))))
10407 (and line
10408 (or (/= (line-number-at-pos beg) line)
10409 (and (> 0 len)
10410 (/= (line-number-at-pos end) line)))
10411 (js2-mode-mundanify-parens)))
10412 (setq js2-mode-buffer-dirty-p t)
10413 (js2-mode-hide-overlay)
10414 (js2-mode-reset-timer))
10415
10416 (defun js2-mode-run-font-lock ()
10417 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10418 This is intended to allow modes that install their own font-lock keywords
10419 to work with js2-mode. In practice it never seems to work for long.
10420 Hopefully the Emacs maintainers can help figure out a way to make it work."
10421 (when (and (boundp 'font-lock-keywords)
10422 font-lock-keywords
10423 (boundp 'font-lock-mode)
10424 font-lock-mode)
10425 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10426 ;; play nicely with js2-mode. They go out of their way to fail to
10427 ;; provide any option for saying "look, fontify the farging buffer
10428 ;; with just the keywords already". Argh.
10429 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10430 (let (font-lock-verbose)
10431 (font-lock-fontify-buffer))))
10432
10433 (defun js2-reparse (&optional force)
10434 "Re-parse current buffer after user finishes some data entry.
10435 If we get any user input while parsing, including cursor motion,
10436 we discard the parse and reschedule it. If FORCE is nil, then the
10437 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10438 (let (time
10439 interrupted-p
10440 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10441 (unless js2-mode-parsing
10442 (setq js2-mode-parsing t)
10443 (unwind-protect
10444 (when (or js2-mode-buffer-dirty-p force)
10445 (js2-remove-overlays)
10446 (js2-with-unmodifying-text-property-changes
10447 (remove-text-properties (point-min) (point-max) '(syntax-table))
10448 (setq js2-mode-buffer-dirty-p nil
10449 js2-mode-fontifications nil
10450 js2-mode-deferred-properties nil
10451 js2-additional-externs nil)
10452 (if js2-mode-verbose-parse-p
10453 (message "parsing..."))
10454 (setq time
10455 (js2-time
10456 (setq interrupted-p
10457 (catch 'interrupted
10458 (setq js2-mode-ast (js2-parse))
10459 (when (plusp js2-highlight-level)
10460 (js2-mode-fontify-regions))
10461 (js2-mode-remove-suppressed-warnings)
10462 (js2-mode-show-warnings)
10463 (js2-mode-show-errors)
10464 (js2-mode-run-font-lock) ; note: doesn't work
10465 (js2-mode-highlight-magic-parens)
10466 (if (>= js2-highlight-level 1)
10467 (js2-highlight-jsdoc js2-mode-ast))
10468 nil))))
10469 (if interrupted-p
10470 (progn
10471 ;; unfinished parse => try again
10472 (setq js2-mode-buffer-dirty-p t)
10473 (js2-mode-reset-timer))
10474 (if js2-mode-verbose-parse-p
10475 (message "Parse time: %s" time)))))
10476 (setq js2-mode-parsing nil)
10477 (unless interrupted-p
10478 (setq js2-mode-parse-timer nil))))))
10479
10480 (defun js2-mode-show-node ()
10481 "Debugging aid: highlight selected AST node on mouse click."
10482 (interactive)
10483 (let ((node (js2-node-at-point))
10484 beg
10485 end)
10486 (when js2-mode-show-overlay
10487 (if (null node)
10488 (message "No node found at location %s" (point))
10489 (setq beg (js2-node-abs-pos node)
10490 end (+ beg (js2-node-len node)))
10491 (if js2-mode-node-overlay
10492 (move-overlay js2-mode-node-overlay beg end)
10493 (setq js2-mode-node-overlay (make-overlay beg end))
10494 (overlay-put js2-mode-node-overlay 'face 'highlight))
10495 (js2-with-unmodifying-text-property-changes
10496 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10497 (message "%s, parent: %s"
10498 (js2-node-short-name node)
10499 (if (js2-node-parent node)
10500 (js2-node-short-name (js2-node-parent node))
10501 "nil"))))))
10502
10503 (defun js2-mode-hide-overlay (&optional p1 p2)
10504 "Remove the debugging overlay when the point moves.
10505 P1 and P2 are the old and new values of point, respectively."
10506 (when js2-mode-node-overlay
10507 (let ((beg (overlay-start js2-mode-node-overlay))
10508 (end (overlay-end js2-mode-node-overlay)))
10509 ;; Sometimes we're called spuriously.
10510 (unless (and p2
10511 (>= p2 beg)
10512 (<= p2 end))
10513 (js2-with-unmodifying-text-property-changes
10514 (remove-text-properties beg end '(point-left nil)))
10515 (delete-overlay js2-mode-node-overlay)
10516 (setq js2-mode-node-overlay nil)))))
10517
10518 (defun js2-mode-reset ()
10519 "Debugging helper: reset everything."
10520 (interactive)
10521 (js2-mode-exit)
10522 (js2-mode))
10523
10524 (defsubst js2-mode-show-warn-or-err (e face)
10525 "Highlight a warning or error E with FACE.
10526 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10527 (let* ((key (first e))
10528 (beg (second e))
10529 (end (+ beg (third e)))
10530 ;; Don't inadvertently go out of bounds.
10531 (beg (max (point-min) (min beg (point-max))))
10532 (end (max (point-min) (min end (point-max))))
10533 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10534 (ovl (make-overlay beg end)))
10535 (overlay-put ovl 'face face)
10536 (overlay-put ovl 'js2-error t)
10537 (put-text-property beg end 'help-echo (js2-get-msg key))
10538 (put-text-property beg end 'point-entered #'js2-echo-error)))
10539
10540 (defun js2-remove-overlays ()
10541 "Remove overlays from buffer that have a `js2-error' property."
10542 (let ((beg (point-min))
10543 (end (point-max)))
10544 (save-excursion
10545 (dolist (o (overlays-in beg end))
10546 (when (overlay-get o 'js2-error)
10547 (delete-overlay o))))))
10548
10549 (defun js2-error-at-point (&optional pos)
10550 "Return non-nil if there's an error overlay at POS.
10551 Defaults to point."
10552 (loop with pos = (or pos (point))
10553 for o in (overlays-at pos)
10554 thereis (overlay-get o 'js2-error)))
10555
10556 (defun js2-mode-fontify-regions ()
10557 "Apply fontifications recorded during parsing."
10558 ;; We defer clearing faces as long as possible to eliminate flashing.
10559 (js2-clear-face (point-min) (point-max))
10560 ;; have to reverse the recorded fontifications so that errors and
10561 ;; warnings overwrite the normal fontifications
10562 (dolist (f (nreverse js2-mode-fontifications))
10563 (put-text-property (first f) (second f) 'face (third f)))
10564 (setq js2-mode-fontifications nil)
10565 (dolist (p js2-mode-deferred-properties)
10566 (apply #'put-text-property p))
10567 (setq js2-mode-deferred-properties nil))
10568
10569 (defun js2-mode-show-errors ()
10570 "Highlight syntax errors."
10571 (when js2-mode-show-parse-errors
10572 (dolist (e (js2-ast-root-errors js2-mode-ast))
10573 (js2-mode-show-warn-or-err e 'js2-error-face))))
10574
10575 (defun js2-mode-remove-suppressed-warnings ()
10576 "Take suppressed warnings out of the AST warnings list.
10577 This ensures that the counts and `next-error' are correct."
10578 (setf (js2-ast-root-warnings js2-mode-ast)
10579 (js2-delete-if
10580 (lambda (e)
10581 (let ((key (caar e)))
10582 (or
10583 (and (not js2-strict-trailing-comma-warning)
10584 (string-match "trailing\\.comma" key))
10585 (and (not js2-strict-cond-assign-warning)
10586 (string= key "msg.equal.as.assign"))
10587 (and js2-missing-semi-one-line-override
10588 (string= key "msg.missing.semi")
10589 (let* ((beg (second e))
10590 (node (js2-node-at-point beg))
10591 (fn (js2-mode-find-parent-fn node))
10592 (body (and fn (js2-function-node-body fn)))
10593 (lc (and body (js2-node-abs-pos body)))
10594 (rc (and lc (+ lc (js2-node-len body)))))
10595 (and fn
10596 (or (null body)
10597 (save-excursion
10598 (goto-char beg)
10599 (and (js2-same-line lc)
10600 (js2-same-line rc))))))))))
10601 (js2-ast-root-warnings js2-mode-ast))))
10602
10603 (defun js2-mode-show-warnings ()
10604 "Highlight strict-mode warnings."
10605 (when js2-mode-show-strict-warnings
10606 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10607 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10608
10609 (defun js2-echo-error (old-point new-point)
10610 "Called by point-motion hooks."
10611 (let ((msg (get-text-property new-point 'help-echo)))
10612 (if msg
10613 (message msg))))
10614
10615 (defalias #'js2-echo-help #'js2-echo-error)
10616
10617 (defun js2-enter-key ()
10618 "Handle user pressing the Enter key."
10619 (interactive)
10620 (let ((parse-status (save-excursion
10621 (parse-partial-sexp (point-min) (point)))))
10622 (cond
10623 ;; check if we're inside a string
10624 ((nth 3 parse-status)
10625 (js2-mode-split-string parse-status))
10626 ;; check if inside a block comment
10627 ((nth 4 parse-status)
10628 (js2-mode-extend-comment))
10629 (t
10630 ;; should probably figure out what the mode-map says we should do
10631 (if js2-indent-on-enter-key
10632 (let ((js2-bounce-indent-p nil))
10633 (js2-indent-line)))
10634 (insert "\n")
10635 (if js2-enter-indents-newline
10636 (let ((js2-bounce-indent-p nil))
10637 (js2-indent-line)))))))
10638
10639 (defun js2-mode-split-string (parse-status)
10640 "Turn a newline in mid-string into a string concatenation.
10641 PARSE-STATUS is as documented in `parse-partial-sexp'."
10642 (let* ((col (current-column))
10643 (quote-char (nth 3 parse-status))
10644 (quote-string (string quote-char))
10645 (string-beg (nth 8 parse-status))
10646 (indent (save-match-data
10647 (or
10648 (save-excursion
10649 (back-to-indentation)
10650 (if (looking-at "\\+")
10651 (current-column)))
10652 (save-excursion
10653 (goto-char string-beg)
10654 (if (looking-back "\\+\\s-+")
10655 (goto-char (match-beginning 0)))
10656 (current-column))))))
10657 (insert quote-char "\n")
10658 (indent-to indent)
10659 (insert "+ " quote-string)
10660 (when (eolp)
10661 (insert quote-string)
10662 (backward-char 1))))
10663
10664 (defun js2-mode-extend-comment ()
10665 "When inside a comment block, add comment prefix."
10666 (let (star single col first-line needs-close)
10667 (save-excursion
10668 (back-to-indentation)
10669 (cond
10670 ((looking-at "\\*[^/]")
10671 (setq star t
10672 col (current-column)))
10673 ((looking-at "/\\*")
10674 (setq star t
10675 first-line t
10676 col (1+ (current-column))))
10677 ((looking-at "//")
10678 (setq single t
10679 col (current-column)))))
10680 ;; Heuristic for whether we need to close the comment:
10681 ;; if we've got a parse error here, assume it's an unterminated
10682 ;; comment.
10683 (setq needs-close
10684 (or
10685 (eq (get-text-property (1- (point)) 'point-entered)
10686 'js2-echo-error)
10687 ;; The heuristic above doesn't work well when we're
10688 ;; creating a comment and there's another one downstream,
10689 ;; as our parser thinks this one ends at the end of the
10690 ;; next one. (You can have a /* inside a js block comment.)
10691 ;; So just close it if the next non-ws char isn't a *.
10692 (and first-line
10693 (eolp)
10694 (save-excursion
10695 (skip-chars-forward " \t\r\n")
10696 (not (eq (char-after) ?*))))))
10697 (insert "\n")
10698 (cond
10699 (star
10700 (indent-to col)
10701 (insert "* ")
10702 (if (and first-line needs-close)
10703 (save-excursion
10704 (insert "\n")
10705 (indent-to col)
10706 (insert "*/"))))
10707 (single
10708 (when (save-excursion
10709 (and (zerop (forward-line 1))
10710 (looking-at "\\s-*//")))
10711 (indent-to col)
10712 (insert "// "))))))
10713
10714 (defun js2-beginning-of-line ()
10715 "Toggles point between bol and first non-whitespace char in line.
10716 Also moves past comment delimiters when inside comments."
10717 (interactive)
10718 (let (node beg)
10719 (cond
10720 ((bolp)
10721 (back-to-indentation))
10722 ((looking-at "//")
10723 (skip-chars-forward "/ \t"))
10724 ((and (eq (char-after) ?*)
10725 (setq node (js2-comment-at-point))
10726 (memq (js2-comment-node-format node) '(jsdoc block))
10727 (save-excursion
10728 (skip-chars-backward " \t")
10729 (bolp)))
10730 (skip-chars-forward "\* \t"))
10731 (t
10732 (goto-char (point-at-bol))))))
10733
10734 (defun js2-end-of-line ()
10735 "Toggles point between eol and last non-whitespace char in line."
10736 (interactive)
10737 (if (eolp)
10738 (skip-chars-backward " \t")
10739 (goto-char (point-at-eol))))
10740
10741 (defun js2-enter-mirror-mode()
10742 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10743 on insertion."
10744 (interactive)
10745 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10746 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10747 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10748 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10749 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10750 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10751 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10752 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10753
10754 (defun js2-leave-mirror-mode()
10755 "Turns off mirror mode."
10756 (interactive)
10757 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10758 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10759
10760 (defsubst js2-mode-inside-string ()
10761 "Return non-nil if inside a string.
10762 Actually returns the quote character that begins the string."
10763 (let ((parse-state (save-excursion
10764 (parse-partial-sexp (point-min) (point)))))
10765 (nth 3 parse-state)))
10766
10767 (defsubst js2-mode-inside-comment-or-string ()
10768 "Return non-nil if inside a comment or string."
10769 (or
10770 (let ((comment-start
10771 (save-excursion
10772 (goto-char (point-at-bol))
10773 (if (re-search-forward "//" (point-at-eol) t)
10774 (match-beginning 0)))))
10775 (and comment-start
10776 (<= comment-start (point))))
10777 (let ((parse-state (save-excursion
10778 (parse-partial-sexp (point-min) (point)))))
10779 (or (nth 3 parse-state)
10780 (nth 4 parse-state)))))
10781
10782 (defsubst js2-make-magic-delimiter (delim &optional pos)
10783 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10784 Sets value of `js2-magic' text property to line number at POS."
10785 (propertize delim
10786 'js2-magic (line-number-at-pos pos)
10787 'face 'js2-magic-paren-face))
10788
10789 (defun js2-mode-match-delimiter (open close)
10790 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10791 The rule we use, which as far as we can tell is how Eclipse works,
10792 is that we insert the match if we're not in a comment or string,
10793 and the next non-whitespace character is either punctuation or
10794 occurs on another line."
10795 (insert open)
10796 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10797 (not (js2-mode-inside-comment-or-string)))
10798 (save-excursion
10799 (insert (js2-make-magic-delimiter close)))
10800 (when js2-auto-indent-p
10801 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10802 (js2-indent-line)))))
10803
10804 (defun js2-mode-match-bracket ()
10805 "Insert matching bracket."
10806 (interactive)
10807 (js2-mode-match-delimiter "[" "]"))
10808
10809 (defun js2-mode-match-paren ()
10810 "Insert matching paren unless already inserted."
10811 (interactive)
10812 (js2-mode-match-delimiter "(" ")"))
10813
10814 (defun js2-mode-match-curly (arg)
10815 "Insert matching curly-brace.
10816 With prefix arg, no formatting or indentation will occur -- the close-brace
10817 is simply inserted directly at the point."
10818 (interactive "p")
10819 (let (try-pos)
10820 (cond
10821 (current-prefix-arg
10822 (js2-mode-match-delimiter "{" "}"))
10823 ((and js2-auto-insert-catch-block
10824 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10825 (point-at-bol))
10826 (match-beginning 1))))
10827 (js2-insert-catch-skel try-pos))
10828 (t
10829 ;; Otherwise try to do something smarter.
10830 (insert "{")
10831 (unless (or (not (looking-at "\\s-*$"))
10832 (save-excursion
10833 (skip-chars-forward " \t\r\n")
10834 (and (looking-at "}")
10835 (js2-error-at-point)))
10836 (js2-mode-inside-comment-or-string))
10837 (undo-boundary)
10838 ;; absolutely mystifying bug: when inserting the next "\n",
10839 ;; the buffer-undo-list is given two new entries: the inserted range,
10840 ;; and the incorrect position of the point. It's recorded incorrectly
10841 ;; as being before the opening "{", not after it. But it's recorded
10842 ;; as the correct value if you're debugging `js2-mode-match-curly'
10843 ;; in edebug. I have no idea why it's doing this, but incrementing
10844 ;; the inserted position fixes the problem, so that the undo takes us
10845 ;; back to just after the user-inserted "{".
10846 (insert "\n")
10847 (ignore-errors
10848 (incf (cadr buffer-undo-list)))
10849 (js2-indent-line)
10850 (save-excursion
10851 (insert "\n}")
10852 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10853 (js2-indent-line))))))))
10854
10855 (defun js2-insert-catch-skel (try-pos)
10856 "Complete a try/catch block after inserting a { following a try keyword.
10857 Rationale is that a try always needs a catch or a finally, and the catch is
10858 the more likely of the two.
10859
10860 TRY-POS is the buffer position of the try keyword. The open-curly should
10861 already have been inserted."
10862 (insert "{")
10863 (let ((try-col (save-excursion
10864 (goto-char try-pos)
10865 (current-column))))
10866 (insert "\n")
10867 (undo-boundary)
10868 (js2-indent-line) ;; indent the blank line where cursor will end up
10869 (save-excursion
10870 (insert "\n")
10871 (indent-to try-col)
10872 (insert "} catch (x) {\n\n")
10873 (indent-to try-col)
10874 (insert "}"))))
10875
10876 (defun js2-mode-highlight-magic-parens ()
10877 "Re-highlight magic parens after parsing nukes the 'face prop."
10878 (let ((beg (point-min))
10879 end)
10880 (while (setq beg (next-single-property-change beg 'js2-magic))
10881 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10882 (if (get-text-property beg 'js2-magic)
10883 (js2-with-unmodifying-text-property-changes
10884 (put-text-property beg (or end (1+ beg))
10885 'face 'js2-magic-paren-face))))))
10886
10887 (defun js2-mode-mundanify-parens ()
10888 "Clear all magic parens and brackets."
10889 (let ((beg (point-min))
10890 end)
10891 (while (setq beg (next-single-property-change beg 'js2-magic))
10892 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10893 (remove-text-properties beg (or end (1+ beg))
10894 '(js2-magic face)))))
10895
10896 (defsubst js2-match-quote (quote-string)
10897 (let ((start-quote (js2-mode-inside-string)))
10898 (cond
10899 ;; inside a comment - don't do quote-matching, since we can't
10900 ;; reliably figure out if we're in a string inside the comment
10901 ((js2-comment-at-point)
10902 (insert quote-string))
10903 ((not start-quote)
10904 ;; not in string => insert matched quotes
10905 (insert quote-string)
10906 ;; exception: if we're just before a word, don't double it.
10907 (unless (looking-at "[^ \t\r\n]")
10908 (save-excursion
10909 (insert quote-string))))
10910 ((looking-at quote-string)
10911 (if (looking-back "[^\\]\\\\")
10912 (insert quote-string)
10913 (forward-char 1)))
10914 ((and js2-mode-escape-quotes
10915 (save-excursion
10916 (save-match-data
10917 (re-search-forward quote-string (point-at-eol) t))))
10918 ;; inside terminated string, escape quote (unless already escaped)
10919 (insert (if (looking-back "[^\\]\\\\")
10920 quote-string
10921 (concat "\\" quote-string))))
10922 (t
10923 (insert quote-string))))) ; else terminate the string
10924
10925 (defun js2-mode-match-single-quote ()
10926 "Insert matching single-quote."
10927 (interactive)
10928 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10929 ;; don't match inside comments, since apostrophe is more common
10930 (if (nth 4 parse-status)
10931 (insert "'")
10932 (js2-match-quote "'"))))
10933
10934 (defun js2-mode-match-double-quote ()
10935 "Insert matching double-quote."
10936 (interactive)
10937 (js2-match-quote "\""))
10938
10939 ;; Eclipse works as follows:
10940 ;; * type an open-paren and it auto-inserts close-paren
10941 ;; - auto-inserted paren gets a green bracket
10942 ;; - green bracket means typing close-paren there will skip it
10943 ;; * if you insert any text on a different line, it turns off
10944 (defun js2-mode-magic-close-paren ()
10945 "Skip over close-paren rather than inserting, where appropriate."
10946 (interactive)
10947 (let* ((here (point))
10948 (parse-status (parse-partial-sexp (point-min) here))
10949 (open-pos (nth 1 parse-status))
10950 (close last-input-event)
10951 (open (cond
10952 ((eq close ?\))
10953 ?\()
10954 ((eq close ?\])
10955 ?\[)
10956 ((eq close ?})
10957 ?{)
10958 (t nil))))
10959 (if (and (eq (char-after) close)
10960 (eq open (char-after open-pos))
10961 (js2-same-line open-pos)
10962 (get-text-property here 'js2-magic))
10963 (progn
10964 (remove-text-properties here (1+ here) '(js2-magic face))
10965 (forward-char 1))
10966 (insert-char close 1))
10967 (blink-matching-open)))
10968
10969 (defun js2-mode-wait-for-parse (callback)
10970 "Invoke CALLBACK when parsing is finished.
10971 If parsing is already finished, calls CALLBACK immediately."
10972 (if (not js2-mode-buffer-dirty-p)
10973 (funcall callback)
10974 (push callback js2-mode-pending-parse-callbacks)
10975 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10976
10977 (defun js2-mode-parse-finished ()
10978 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10979 ;; We can't let errors propagate up, since it prevents the
10980 ;; `js2-parse' method from completing normally and returning
10981 ;; the ast, which makes things mysteriously not work right.
10982 (unwind-protect
10983 (dolist (cb js2-mode-pending-parse-callbacks)
10984 (condition-case err
10985 (funcall cb)
10986 (error (message "%s" err))))
10987 (setq js2-mode-pending-parse-callbacks nil)))
10988
10989 (defun js2-mode-flag-region (from to flag)
10990 "Hide or show text from FROM to TO, according to FLAG.
10991 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10992 Returns the created overlay if FLAG is non-nil."
10993 (remove-overlays from to 'invisible 'js2-outline)
10994 (when flag
10995 (let ((o (make-overlay from to)))
10996 (overlay-put o 'invisible 'js2-outline)
10997 (overlay-put o 'isearch-open-invisible
10998 'js2-isearch-open-invisible)
10999 o)))
11000
11001 ;; Function to be set as an outline-isearch-open-invisible' property
11002 ;; to the overlay that makes the outline invisible (see
11003 ;; `js2-mode-flag-region').
11004 (defun js2-isearch-open-invisible (overlay)
11005 ;; We rely on the fact that isearch places point on the matched text.
11006 (js2-mode-show-element))
11007
11008 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11009 "Return cons cell of bounds of folding overlay at POS.
11010 Returns nil if not found."
11011 (let ((overlays (overlays-at (or pos (point))))
11012 o)
11013 (while (and overlays
11014 (not o))
11015 (if (overlay-get (car overlays) 'invisible)
11016 (setq o (car overlays))
11017 (setq overlays (cdr overlays))))
11018 (if o
11019 (cons (overlay-start o) (overlay-end o)))))
11020
11021 (defun js2-mode-function-at-point (&optional pos)
11022 "Return the innermost function node enclosing current point.
11023 Returns nil if point is not in a function."
11024 (let ((node (js2-node-at-point pos)))
11025 (while (and node (not (js2-function-node-p node)))
11026 (setq node (js2-node-parent node)))
11027 (if (js2-function-node-p node)
11028 node)))
11029
11030 (defun js2-mode-toggle-element ()
11031 "Hide or show the foldable element at the point."
11032 (interactive)
11033 (let (comment fn pos)
11034 (save-excursion
11035 (save-match-data
11036 (cond
11037 ;; /* ... */ comment?
11038 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11039 (if (js2-mode-invisible-overlay-bounds
11040 (setq pos (+ 3 (js2-node-abs-pos comment))))
11041 (progn
11042 (goto-char pos)
11043 (js2-mode-show-element))
11044 (js2-mode-hide-element)))
11045 ;; //-comment?
11046 ((save-excursion
11047 (back-to-indentation)
11048 (looking-at js2-mode-//-comment-re))
11049 (js2-mode-toggle-//-comment))
11050 ;; function?
11051 ((setq fn (js2-mode-function-at-point))
11052 (setq pos (and (js2-function-node-body fn)
11053 (js2-node-abs-pos (js2-function-node-body fn))))
11054 (goto-char (1+ pos))
11055 (if (js2-mode-invisible-overlay-bounds)
11056 (js2-mode-show-element)
11057 (js2-mode-hide-element)))
11058 (t
11059 (message "Nothing at point to hide or show")))))))
11060
11061 (defun js2-mode-hide-element ()
11062 "Fold/hide contents of a block, showing ellipses.
11063 Show the hidden text with \\[js2-mode-show-element]."
11064 (interactive)
11065 (if js2-mode-buffer-dirty-p
11066 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11067 (let (node body beg end)
11068 (cond
11069 ((js2-mode-invisible-overlay-bounds)
11070 (message "already hidden"))
11071 (t
11072 (setq node (js2-node-at-point))
11073 (cond
11074 ((js2-block-comment-p node)
11075 (js2-mode-hide-comment node))
11076 (t
11077 (while (and node (not (js2-function-node-p node)))
11078 (setq node (js2-node-parent node)))
11079 (if (and node
11080 (setq body (js2-function-node-body node)))
11081 (progn
11082 (setq beg (js2-node-abs-pos body)
11083 end (+ beg (js2-node-len body)))
11084 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11085 (message "No collapsable element found at point"))))))))
11086
11087 (defun js2-mode-show-element ()
11088 "Show the hidden element at current point."
11089 (interactive)
11090 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11091 (if bounds
11092 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11093 (message "Nothing to un-hide"))))
11094
11095 (defun js2-mode-show-all ()
11096 "Show all of the text in the buffer."
11097 (interactive)
11098 (js2-mode-flag-region (point-min) (point-max) nil))
11099
11100 (defun js2-mode-toggle-hide-functions ()
11101 (interactive)
11102 (if js2-mode-functions-hidden
11103 (js2-mode-show-functions)
11104 (js2-mode-hide-functions)))
11105
11106 (defun js2-mode-hide-functions ()
11107 "Hides all non-nested function bodies in the buffer.
11108 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11109 to open an individual entry."
11110 (interactive)
11111 (if js2-mode-buffer-dirty-p
11112 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11113 (if (null js2-mode-ast)
11114 (message "Oops - parsing failed")
11115 (setq js2-mode-functions-hidden t)
11116 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11117
11118 (defun js2-mode-function-hider (n endp)
11119 (when (not endp)
11120 (let ((tt (js2-node-type n))
11121 body beg end)
11122 (cond
11123 ((and (= tt js2-FUNCTION)
11124 (setq body (js2-function-node-body n)))
11125 (setq beg (js2-node-abs-pos body)
11126 end (+ beg (js2-node-len body)))
11127 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11128 nil) ; don't process children of function
11129 (t
11130 t))))) ; keep processing other AST nodes
11131
11132 (defun js2-mode-show-functions ()
11133 "Un-hide any folded function bodies in the buffer."
11134 (interactive)
11135 (setq js2-mode-functions-hidden nil)
11136 (save-excursion
11137 (goto-char (point-min))
11138 (while (/= (goto-char (next-overlay-change (point)))
11139 (point-max))
11140 (dolist (o (overlays-at (point)))
11141 (when (and (overlay-get o 'invisible)
11142 (not (overlay-get o 'comment)))
11143 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11144
11145 (defun js2-mode-hide-comment (n)
11146 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11147 3 ; /**
11148 2)) ; /*
11149 (beg (+ (js2-node-abs-pos n) head))
11150 (end (- (+ beg (js2-node-len n)) head 2))
11151 (o (js2-mode-flag-region beg end 'hide)))
11152 (overlay-put o 'comment t)))
11153
11154 (defun js2-mode-toggle-hide-comments ()
11155 "Folds all block comments in the buffer.
11156 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11157 to open an individual entry."
11158 (interactive)
11159 (if js2-mode-comments-hidden
11160 (js2-mode-show-comments)
11161 (js2-mode-hide-comments)))
11162
11163 (defun js2-mode-hide-comments ()
11164 (interactive)
11165 (if js2-mode-buffer-dirty-p
11166 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11167 (if (null js2-mode-ast)
11168 (message "Oops - parsing failed")
11169 (setq js2-mode-comments-hidden t)
11170 (dolist (n (js2-ast-root-comments js2-mode-ast))
11171 (let ((format (js2-comment-node-format n)))
11172 (when (js2-block-comment-p n)
11173 (js2-mode-hide-comment n))))
11174 (js2-mode-hide-//-comments)))
11175
11176 (defsubst js2-mode-extend-//-comment (direction)
11177 "Find start or end of a block of similar //-comment lines.
11178 DIRECTION is -1 to look back, 1 to look forward.
11179 INDENT is the indentation level to match.
11180 Returns the end-of-line position of the furthest adjacent
11181 //-comment line with the same indentation as the current line.
11182 If there is no such matching line, returns current end of line."
11183 (let ((pos (point-at-eol))
11184 (indent (current-indentation)))
11185 (save-excursion
11186 (save-match-data
11187 (while (and (zerop (forward-line direction))
11188 (looking-at js2-mode-//-comment-re)
11189 (eq indent (length (match-string 1))))
11190 (setq pos (point-at-eol)))
11191 pos))))
11192
11193 (defun js2-mode-hide-//-comments ()
11194 "Fold adjacent 1-line comments, showing only snippet of first one."
11195 (let (beg end)
11196 (save-excursion
11197 (save-match-data
11198 (goto-char (point-min))
11199 (while (re-search-forward js2-mode-//-comment-re nil t)
11200 (setq beg (point)
11201 end (js2-mode-extend-//-comment 1))
11202 (unless (eq beg end)
11203 (overlay-put (js2-mode-flag-region beg end 'hide)
11204 'comment t))
11205 (goto-char end)
11206 (forward-char 1))))))
11207
11208 (defun js2-mode-toggle-//-comment ()
11209 "Fold or un-fold any multi-line //-comment at point.
11210 Caller should have determined that this line starts with a //-comment."
11211 (let* ((beg (point-at-eol))
11212 (end beg))
11213 (save-excursion
11214 (goto-char end)
11215 (if (js2-mode-invisible-overlay-bounds)
11216 (js2-mode-show-element)
11217 ;; else hide the comment
11218 (setq beg (js2-mode-extend-//-comment -1)
11219 end (js2-mode-extend-//-comment 1))
11220 (unless (eq beg end)
11221 (overlay-put (js2-mode-flag-region beg end 'hide)
11222 'comment t))))))
11223
11224 (defun js2-mode-show-comments ()
11225 "Un-hide any hidden comments, leaving other hidden elements alone."
11226 (interactive)
11227 (setq js2-mode-comments-hidden nil)
11228 (save-excursion
11229 (goto-char (point-min))
11230 (while (/= (goto-char (next-overlay-change (point)))
11231 (point-max))
11232 (dolist (o (overlays-at (point)))
11233 (when (overlay-get o 'comment)
11234 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11235
11236 (defun js2-mode-display-warnings-and-errors ()
11237 "Turn on display of warnings and errors."
11238 (interactive)
11239 (setq js2-mode-show-parse-errors t
11240 js2-mode-show-strict-warnings t)
11241 (js2-reparse 'force))
11242
11243 (defun js2-mode-hide-warnings-and-errors ()
11244 "Turn off display of warnings and errors."
11245 (interactive)
11246 (setq js2-mode-show-parse-errors nil
11247 js2-mode-show-strict-warnings nil)
11248 (js2-reparse 'force))
11249
11250 (defun js2-mode-toggle-warnings-and-errors ()
11251 "Toggle the display of warnings and errors.
11252 Some users don't like having warnings/errors reported while they type."
11253 (interactive)
11254 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11255 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11256 (if (interactive-p)
11257 (message "warnings and errors %s"
11258 (if js2-mode-show-parse-errors
11259 "enabled"
11260 "disabled")))
11261 (js2-reparse 'force))
11262
11263 (defun js2-mode-customize ()
11264 (interactive)
11265 (customize-group 'js2-mode))
11266
11267 (defun js2-mode-forward-sexp (&optional arg)
11268 "Move forward across one statement or balanced expression.
11269 With ARG, do it that many times. Negative arg -N means
11270 move backward across N balanced expressions."
11271 (interactive "p")
11272 (setq arg (or arg 1))
11273 (if js2-mode-buffer-dirty-p
11274 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11275 (let (node end (start (point)))
11276 (cond
11277 ;; backward-sexp
11278 ;; could probably make this better for some cases:
11279 ;; - if in statement block (e.g. function body), go to parent
11280 ;; - infix exprs like (foo in bar) - maybe go to beginning
11281 ;; of infix expr if in the right-side expression?
11282 ((and arg (minusp arg))
11283 (dotimes (i (- arg))
11284 (js2-backward-sws)
11285 (forward-char -1) ; enter the node we backed up to
11286 (setq node (js2-node-at-point (point) t))
11287 (goto-char (if node
11288 (js2-node-abs-pos node)
11289 (point-min)))))
11290 (t
11291 ;; forward-sexp
11292 (js2-forward-sws)
11293 (dotimes (i arg)
11294 (js2-forward-sws)
11295 (setq node (js2-node-at-point (point) t)
11296 end (if node (+ (js2-node-abs-pos node)
11297 (js2-node-len node))))
11298 (goto-char (or end (point-max))))))))
11299
11300 (defun js2-next-error (&optional arg reset)
11301 "Move to next parse error.
11302 Typically invoked via \\[next-error].
11303 ARG is the number of errors, forward or backward, to move.
11304 RESET means start over from the beginning."
11305 (interactive "p")
11306 (if (or (null js2-mode-ast)
11307 (and (null (js2-ast-root-errors js2-mode-ast))
11308 (null (js2-ast-root-warnings js2-mode-ast))))
11309 (message "No errors")
11310 (when reset
11311 (goto-char (point-min)))
11312 (let* ((errs (copy-sequence
11313 (append (js2-ast-root-errors js2-mode-ast)
11314 (js2-ast-root-warnings js2-mode-ast))))
11315 (continue t)
11316 (start (point))
11317 (count (or arg 1))
11318 (backward (minusp count))
11319 (sorter (if backward '> '<))
11320 (stopper (if backward '< '>))
11321 (count (abs count))
11322 all-errs
11323 err)
11324 ;; sort by start position
11325 (setq errs (sort errs (lambda (e1 e2)
11326 (funcall sorter (second e1) (second e2))))
11327 all-errs errs)
11328 ;; find nth error with pos > start
11329 (while (and errs continue)
11330 (when (funcall stopper (cadar errs) start)
11331 (setq err (car errs))
11332 (if (zerop (decf count))
11333 (setq continue nil)))
11334 (setq errs (cdr errs)))
11335 (if err
11336 (goto-char (second err))
11337 ;; wrap around to first error
11338 (goto-char (second (car all-errs)))
11339 ;; if we were already on it, echo msg again
11340 (if (= (point) start)
11341 (js2-echo-error (point) (point)))))))
11342
11343 (defun js2-down-mouse-3 ()
11344 "Make right-click move the point to the click location.
11345 This makes right-click context menu operations a bit more intuitive.
11346 The point will not move if the region is active, however, to avoid
11347 destroying the region selection."
11348 (interactive)
11349 (when (and js2-move-point-on-right-click
11350 (not mark-active))
11351 (let ((e last-input-event))
11352 (ignore-errors
11353 (goto-char (cadadr e))))))
11354
11355 (defun js2-mode-create-imenu-index ()
11356 "Return an alist for `imenu--index-alist'."
11357 ;; This is built up in `js2-parse-record-imenu' during parsing.
11358 (when js2-mode-ast
11359 ;; if we have an ast but no recorder, they're requesting a rescan
11360 (unless js2-imenu-recorder
11361 (js2-reparse 'force))
11362 (prog1
11363 (js2-build-imenu-index)
11364 (setq js2-imenu-recorder nil
11365 js2-imenu-function-map nil))))
11366
11367 (defun js2-mode-find-tag ()
11368 "Replacement for `find-tag-default'.
11369 `find-tag-default' returns a ridiculous answer inside comments."
11370 (let (beg end)
11371 (js2-with-underscore-as-word-syntax
11372 (save-excursion
11373 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11374 (looking-back "[A-Za-z0-9_$]"))
11375 (setq beg (progn (forward-word -1) (point))
11376 end (progn (forward-word 1) (point)))
11377 (setq beg (progn (forward-word 1) (point))
11378 end (progn (forward-word -1) (point))))
11379 (replace-regexp-in-string
11380 "[\"']" ""
11381 (buffer-substring-no-properties beg end))))))
11382
11383 (defun js2-mode-forward-sibling ()
11384 "Move to the end of the sibling following point in parent.
11385 Returns non-nil if successful, or nil if there was no following sibling."
11386 (let* ((node (js2-node-at-point))
11387 (parent (js2-mode-find-enclosing-fn node))
11388 sib)
11389 (when (setq sib (js2-node-find-child-after (point) parent))
11390 (goto-char (+ (js2-node-abs-pos sib)
11391 (js2-node-len sib))))))
11392
11393 (defun js2-mode-backward-sibling ()
11394 "Move to the beginning of the sibling node preceding point in parent.
11395 Parent is defined as the enclosing script or function."
11396 (let* ((node (js2-node-at-point))
11397 (parent (js2-mode-find-enclosing-fn node))
11398 sib)
11399 (when (setq sib (js2-node-find-child-before (point) parent))
11400 (goto-char (js2-node-abs-pos sib)))))
11401
11402 (defun js2-beginning-of-defun ()
11403 "Go to line on which current function starts, and return non-nil.
11404 If we're not in a function, go to beginning of previous script-level element."
11405 (interactive)
11406 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11407 pos sib)
11408 (cond
11409 ((and (js2-function-node-p parent)
11410 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11411 (goto-char pos))
11412 (t
11413 (js2-mode-backward-sibling)))))
11414
11415 (defun js2-end-of-defun ()
11416 "Go to the char after the last position of the current function.
11417 If we're not in a function, skips over the next script-level element."
11418 (interactive)
11419 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11420 (if (not (js2-function-node-p parent))
11421 ;; punt: skip over next script-level element beyond point
11422 (js2-mode-forward-sibling)
11423 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11424 (js2-node-len parent)))))))
11425
11426 (defun js2-mark-defun (&optional allow-extend)
11427 "Put mark at end of this function, point at beginning.
11428 The function marked is the one that contains point.
11429
11430 Interactively, if this command is repeated,
11431 or (in Transient Mark mode) if the mark is active,
11432 it marks the next defun after the ones already marked."
11433 (interactive "p")
11434 (let (extended)
11435 (when (and allow-extend
11436 (or (and (eq last-command this-command) (mark t))
11437 (and transient-mark-mode mark-active)))
11438 (let ((sib (save-excursion
11439 (goto-char (mark))
11440 (if (js2-mode-forward-sibling)
11441 (point))))
11442 node)
11443 (if sib
11444 (progn
11445 (set-mark sib)
11446 (setq extended t))
11447 ;; no more siblings - try extending to enclosing node
11448 (goto-char (mark t)))))
11449 (when (not extended)
11450 (let ((node (js2-node-at-point (point) t)) ; skip comments
11451 ast fn stmt parent beg end)
11452 (when (js2-ast-root-p node)
11453 (setq ast node
11454 node (or (js2-node-find-child-after (point) node)
11455 (js2-node-find-child-before (point) node))))
11456 ;; only mark whole buffer if we can't find any children
11457 (if (null node)
11458 (setq node ast))
11459 (if (js2-function-node-p node)
11460 (setq parent node)
11461 (setq fn (js2-mode-find-enclosing-fn node)
11462 stmt (if (or (null fn)
11463 (js2-ast-root-p fn))
11464 (js2-mode-find-first-stmt node))
11465 parent (or stmt fn)))
11466 (setq beg (js2-node-abs-pos parent)
11467 end (+ beg (js2-node-len parent)))
11468 (push-mark beg)
11469 (goto-char end)
11470 (exchange-point-and-mark)))))
11471
11472 (defun js2-narrow-to-defun ()
11473 "Narrow to the function enclosing point."
11474 (interactive)
11475 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11476 (fn (if (js2-script-node-p node)
11477 node
11478 (js2-mode-find-enclosing-fn node)))
11479 (beg (js2-node-abs-pos fn)))
11480 (unless (js2-ast-root-p fn)
11481 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11482
11483 (provide 'js2-mode)
11484
11485 ;;; js2-mode.el ends here