]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode-20090814.el
3e4d6b7e8a1ff20ebfa79b1e4db461f48b901d36
[gnu-emacs-elpa] / packages / js2-mode-20090814.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Version: 20090814
7 ;; Keywords: languages, javascript
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This JavaScript editing mode supports:
27
28 ;; - strict recognition of the Ecma-262 language standard
29 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
30 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
31 ;; - accurate syntax highlighting using a recursive-descent parser
32 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
33 ;; - undeclared-variable warnings using a configurable externs framework
34 ;; - "bouncing" line indentation to choose among alternate indentation points
35 ;; - smart line-wrapping within comments and strings
36 ;; - code folding:
37 ;; - show some or all function bodies as {...}
38 ;; - show some or all block comments as /*...*/
39 ;; - context-sensitive menu bar and popup menus
40 ;; - code browsing using the `imenu' package
41 ;; - typing helpers such as automatic insertion of matching braces/parens
42 ;; - many customization options
43
44 ;; To customize how it works:
45 ;; M-x customize-group RET js2-mode RET
46
47 ;; Notes:
48
49 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
50 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
51 ;; `js2-mode' current as the EcmaScript language standard evolves.
52
53 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
54 ;; customizable. It is a surprising amount of work to support customizable
55 ;; indentation. The current compromise is that the tab key lets you cycle among
56 ;; various likely indentation points, similar to the behavior of python-mode.
57
58 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
59 ;; and `mumamo', although it could be made to do so with some effort.
60 ;; This means that `js2-mode' is currently only useful for editing JavaScript
61 ;; files, and not for editing JavaScript within <script> tags or templates.
62
63 ;;; Code:
64
65 (eval-when-compile
66 (require 'cl))
67
68 (require 'imenu)
69 (require 'cc-cmds) ; for `c-fill-paragraph'
70
71 (eval-and-compile
72 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
73 (require 'cc-langs) ; it's here in Emacs 21...
74 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
75
76 ;;; Externs (variables presumed to be defined by the host system)
77
78 (defvar js2-ecma-262-externs
79 (mapcar 'symbol-name
80 '(Array Boolean Date Error EvalError Function Infinity
81 Math NaN Number Object RangeError ReferenceError RegExp
82 String SyntaxError TypeError URIError arguments
83 decodeURI decodeURIComponent encodeURI
84 encodeURIComponent escape eval isFinite isNaN
85 parseFloat parseInt undefined unescape))
86 "Ecma-262 externs. Included in `js2-externs' by default.")
87
88 (defvar js2-browser-externs
89 (mapcar 'symbol-name
90 '(;; DOM level 1
91 Attr CDATASection CharacterData Comment DOMException
92 DOMImplementation Document DocumentFragment
93 DocumentType Element Entity EntityReference
94 ExceptionCode NamedNodeMap Node NodeList Notation
95 ProcessingInstruction Text
96
97 ;; DOM level 2
98 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
99 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
100 HTMLBodyElement HTMLButtonElement HTMLCollection
101 HTMLDListElement HTMLDirectoryElement HTMLDivElement
102 HTMLDocument HTMLElement HTMLFieldSetElement
103 HTMLFontElement HTMLFormElement HTMLFrameElement
104 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
105 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
106 HTMLImageElement HTMLInputElement HTMLIsIndexElement
107 HTMLLIElement HTMLLabelElement HTMLLegendElement
108 HTMLLinkElement HTMLMapElement HTMLMenuElement
109 HTMLMetaElement HTMLModElement HTMLOListElement
110 HTMLObjectElement HTMLOptGroupElement
111 HTMLOptionElement HTMLOptionsCollection
112 HTMLParagraphElement HTMLParamElement HTMLPreElement
113 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
114 HTMLStyleElement HTMLTableCaptionElement
115 HTMLTableCellElement HTMLTableColElement
116 HTMLTableElement HTMLTableRowElement
117 HTMLTableSectionElement HTMLTextAreaElement
118 HTMLTitleElement HTMLUListElement
119
120 ;; DOM level 3
121 DOMConfiguration DOMError DOMException
122 DOMImplementationList DOMImplementationSource
123 DOMLocator DOMStringList NameList TypeInfo
124 UserDataHandler
125
126 ;; Window
127 alert confirm document java navigator prompt screen
128 self top
129
130 ;; W3C CSS
131 CSSCharsetRule CSSFontFace CSSFontFaceRule
132 CSSImportRule CSSMediaRule CSSPageRule
133 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
134 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
135 CSSValue CSSValueList Counter DOMImplementationCSS
136 DocumentCSS DocumentStyle ElementCSSInlineStyle
137 LinkStyle MediaList RGBColor Rect StyleSheet
138 StyleSheetList ViewCSS
139
140 ;; W3C Event
141 EventListener EventTarget Event DocumentEvent UIEvent
142 MouseEvent MutationEvent KeyboardEvent
143
144 ;; W3C Range
145 DocumentRange Range RangeException
146
147 ;; W3C XML
148 XPathResult XMLHttpRequest))
149 "Browser externs.
150 You can cause these to be included or excluded with the custom
151 variable `js2-include-browser-externs'.")
152
153 (defvar js2-rhino-externs
154 (mapcar 'symbol-name
155 '(Packages importClass importPackage com org java
156 ;; Global object (shell) externs
157 defineClass deserialize doctest gc help load
158 loadClass print quit readFile readUrl runCommand seal
159 serialize spawn sync toint32 version))
160 "Mozilla Rhino externs.
161 Set `js2-include-rhino-externs' to t to include them.")
162
163 (defvar js2-gears-externs
164 (mapcar 'symbol-name
165 '(
166 ;; TODO(stevey): add these
167 ))
168 "Google Gears externs.
169 Set `js2-include-gears-externs' to t to include them.")
170
171 ;;; Variables
172
173 (defvar js2-emacs22 (>= emacs-major-version 22))
174
175 (defcustom js2-highlight-level 2
176 "Amount of syntax highlighting to perform.
177 nil, zero or negative means none.
178 1 adds basic syntax highlighting.
179 2 adds highlighting of some Ecma built-in properties.
180 3 adds highlighting of many Ecma built-in functions."
181 :group 'js2-mode
182 :type '(choice (const :tag "None" nil)
183 (const :tag "Basic" 1)
184 (const :tag "Include Properties" 2)
185 (const :tag "Include Functions" 3)))
186
187 (defvar js2-mode-dev-mode-p nil
188 "Non-nil if running in development mode. Normally nil.")
189
190 (defgroup js2-mode nil
191 "An improved JavaScript mode."
192 :group 'languages)
193
194 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
195 (numberp c-basic-offset))
196 c-basic-offset
197 4)
198 "Number of spaces to indent nested statements.
199 Similar to `c-basic-offset'."
200 :group 'js2-mode
201 :type 'integer)
202 (make-variable-buffer-local 'js2-basic-offset)
203
204 (defcustom js2-mirror-mode t
205 "Non-nil to insert closing brackets, parens, etc. automatically."
206 :group 'js2-mode
207 :type 'boolean)
208
209 (defcustom js2-auto-indent-p nil
210 "Automatic indentation with punctuation characters.
211 If non-nil, the current line is indented when certain punctuations
212 are inserted."
213 :group 'js2-mode
214 :type 'boolean)
215
216 (defcustom js2-bounce-indent-p nil
217 "Non-nil to have indent-line function choose among alternatives.
218 If nil, the indent-line function will indent to a predetermined column
219 based on heuristic guessing. If non-nil, then if the current line is
220 already indented to that predetermined column, indenting will choose
221 another likely column and indent to that spot. Repeated invocation of
222 the indent-line function will cycle among the computed alternatives.
223 See the function `js2-bounce-indent' for details."
224 :type 'boolean
225 :group 'js2-mode)
226
227 (defcustom js2-indent-on-enter-key nil
228 "Non-nil to have Enter/Return key indent the line.
229 This is unusual for Emacs modes but common in IDEs like Eclipse."
230 :type 'boolean
231 :group 'js2-mode)
232
233 (defcustom js2-enter-indents-newline nil
234 "Non-nil to have Enter/Return key indent the newly-inserted line.
235 This is unusual for Emacs modes but common in IDEs like Eclipse."
236 :type 'boolean
237 :group 'js2-mode)
238
239 (defcustom js2-rebind-eol-bol-keys t
240 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
241 If non-nil, bounce between bol/eol and first/last non-whitespace char."
242 :group 'js2-mode
243 :type 'boolean)
244
245 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
246 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
247 Each value in the list is passed to `define-key'."
248 :type 'list
249 :group 'js2-mode)
250
251 (defcustom js2-idle-timer-delay 0.2
252 "Delay in secs before re-parsing after user makes changes.
253 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
254 :type 'number
255 :group 'js2-mode)
256 (make-variable-buffer-local 'js2-idle-timer-delay)
257
258 (defcustom js2-dynamic-idle-timer-adjust 0
259 "Positive to adjust `js2-idle-timer-delay' based on file size.
260 The idea is that for short files, parsing is faster so we can be
261 more responsive to user edits without interfering with editing.
262 The buffer length in characters (typically bytes) is divided by
263 this value and used to multiply `js2-idle-timer-delay' for the
264 buffer. For example, a 21k file and 10k adjust yields 21k/10k
265 == 2, so js2-idle-timer-delay is multiplied by 2.
266 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
267 `js2-idle-timer-delay' is not dependent on the file size."
268 :type 'number
269 :group 'js2-mode)
270
271 (defcustom js2-mode-escape-quotes t
272 "Non-nil to disable automatic quote-escaping inside strings."
273 :type 'boolean
274 :group 'js2-mode)
275
276 (defcustom js2-mode-squeeze-spaces t
277 "Non-nil to normalize whitespace when filling in comments.
278 Multiple runs of spaces are converted to a single space."
279 :type 'boolean
280 :group 'js2-mode)
281
282 (defcustom js2-mode-show-parse-errors t
283 "True to highlight parse errors."
284 :type 'boolean
285 :group 'js2-mode)
286
287 (defcustom js2-mode-show-strict-warnings t
288 "Non-nil to emit Ecma strict-mode warnings.
289 Some of the warnings can be individually disabled by other flags,
290 even if this flag is non-nil."
291 :type 'boolean
292 :group 'js2-mode)
293
294 (defcustom js2-strict-trailing-comma-warning t
295 "Non-nil to warn about trailing commas in array literals.
296 Ecma-262 forbids them, but many browsers permit them. IE is the
297 big exception, and can produce bugs if you have trailing commas."
298 :type 'boolean
299 :group 'js2-mode)
300
301 (defcustom js2-strict-missing-semi-warning t
302 "Non-nil to warn about semicolon auto-insertion after statement.
303 Technically this is legal per Ecma-262, but some style guides disallow
304 depending on it."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-missing-semi-one-line-override nil
309 "Non-nil to permit missing semicolons in one-line functions.
310 In one-liner functions such as `function identity(x) {return x}'
311 people often omit the semicolon for a cleaner look. If you are
312 such a person, you can suppress the missing-semicolon warning
313 by setting this variable to t."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-inconsistent-return-warning t
318 "Non-nil to warn about mixing returns with value-returns.
319 It's perfectly legal to have a `return' and a `return foo' in the
320 same function, but it's often an indicator of a bug, and it also
321 interferes with type inference (in systems that support it.)"
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-cond-assign-warning t
326 "Non-nil to warn about expressions like if (a = b).
327 This often should have been '==' instead of '='. If the warning
328 is enabled, you can suppress it on a per-expression basis by
329 parenthesizing the expression, e.g. if ((a = b)) ..."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-cond-assign-warning t
334 "Non-nil to warn about expressions like if (a = b).
335 This often should have been '==' instead of '='. If the warning
336 is enabled, you can suppress it on a per-expression basis by
337 parenthesizing the expression, e.g. if ((a = b)) ..."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-strict-var-redeclaration-warning t
342 "Non-nil to warn about redeclaring variables in a script or function."
343 :type 'boolean
344 :group 'js2-mode)
345
346 (defcustom js2-strict-var-hides-function-arg-warning t
347 "Non-nil to warn about a var decl hiding a function argument."
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-skip-preprocessor-directives nil
352 "Non-nil to treat lines beginning with # as comments.
353 Useful for viewing Mozilla JavaScript source code."
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-language-version 180
358 "Configures what JavaScript language version to recognize.
359 Currently versions 150, 160, 170 and 180 are supported, corresponding
360 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
361 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
362 and 1.8 adds function closures."
363 :type 'integer
364 :group 'js2-mode)
365
366 (defcustom js2-allow-keywords-as-property-names t
367 "If non-nil, you can use JavaScript keywords as object property names.
368 Examples:
369
370 var foo = {int: 5, while: 6, continue: 7};
371 foo.return = 8;
372
373 Ecma-262 forbids this syntax, but many browsers support it."
374 :type 'boolean
375 :group 'js2-mode)
376
377 (defcustom js2-instanceof-has-side-effects nil
378 "If non-nil, treats the instanceof operator as having side effects.
379 This is useful for xulrunner apps."
380 :type 'boolean
381 :group 'js2-mode)
382
383 (defcustom js2-cleanup-whitespace nil
384 "Non-nil to invoke `delete-trailing-whitespace' before saves."
385 :type 'boolean
386 :group 'js2-mode)
387
388 (defcustom js2-move-point-on-right-click t
389 "Non-nil to move insertion point when you right-click.
390 This makes right-click context menu behavior a bit more intuitive,
391 since menu operations generally apply to the point. The exception
392 is if there is a region selection, in which case the point does -not-
393 move, so cut/copy/paste etc. can work properly.
394
395 Note that IntelliJ moves the point, and Eclipse leaves it alone,
396 so this behavior is customizable."
397 :group 'js2-mode
398 :type 'boolean)
399
400 (defcustom js2-allow-rhino-new-expr-initializer t
401 "Non-nil to support a Rhino's experimental syntactic construct.
402
403 Rhino supports the ability to follow a `new' expression with an object
404 literal, which is used to set additional properties on the new object
405 after calling its constructor. Syntax:
406
407 new <expr> [ ( arglist ) ] [initializer]
408
409 Hence, this expression:
410
411 new Object {a: 1, b: 2}
412
413 results in an Object with properties a=1 and b=2. This syntax is
414 apparently not configurable in Rhino - it's currently always enabled,
415 as of Rhino version 1.7R2."
416 :type 'boolean
417 :group 'js2-mode)
418
419 (defcustom js2-allow-member-expr-as-function-name nil
420 "Non-nil to support experimental Rhino syntax for function names.
421
422 Rhino supports an experimental syntax configured via the Rhino Context
423 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
424
425 function <member-expr> ( [ arg-list ] ) { <body> }
426
427 Where member-expr is a non-parenthesized 'member expression', which
428 is anything at the grammar level of a new-expression or lower, meaning
429 any expression that does not involve infix or unary operators.
430
431 When <member-expr> is not a simple identifier, then it is syntactic
432 sugar for assigning the anonymous function to the <member-expr>. Hence,
433 this code:
434
435 function a.b().c[2] (x, y) { ... }
436
437 is rewritten as:
438
439 a.b().c[2] = function(x, y) {...}
440
441 which doesn't seem particularly useful, but Rhino permits it."
442 :type 'boolean
443 :group 'js2-mode)
444
445 (defvar js2-mode-version 20090727
446 "Release number for `js2-mode'.")
447
448 ;; scanner variables
449
450 (defmacro js2-deflocal (name value &optional comment)
451 "Define a buffer-local variable NAME with VALUE and COMMENT."
452 `(progn
453 (defvar ,name ,value ,comment)
454 (make-variable-buffer-local ',name)))
455
456 ;; We record the start and end position of each token.
457 (js2-deflocal js2-token-beg 1)
458 (js2-deflocal js2-token-end -1)
459
460 (defvar js2-EOF_CHAR -1
461 "Represents end of stream. Distinct from js2-EOF token type.")
462
463 ;; I originally used symbols to represent tokens, but Rhino uses
464 ;; ints and then sets various flag bits in them, so ints it is.
465 ;; The upshot is that we need a `js2-' prefix in front of each name.
466 (defvar js2-ERROR -1)
467 (defvar js2-EOF 0)
468 (defvar js2-EOL 1)
469 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
470 (defvar js2-LEAVEWITH 3)
471 (defvar js2-RETURN 4)
472 (defvar js2-GOTO 5)
473 (defvar js2-IFEQ 6)
474 (defvar js2-IFNE 7)
475 (defvar js2-SETNAME 8)
476 (defvar js2-BITOR 9)
477 (defvar js2-BITXOR 10)
478 (defvar js2-BITAND 11)
479 (defvar js2-EQ 12)
480 (defvar js2-NE 13)
481 (defvar js2-LT 14)
482 (defvar js2-LE 15)
483 (defvar js2-GT 16)
484 (defvar js2-GE 17)
485 (defvar js2-LSH 18)
486 (defvar js2-RSH 19)
487 (defvar js2-URSH 20)
488 (defvar js2-ADD 21) ; infix plus
489 (defvar js2-SUB 22) ; infix minus
490 (defvar js2-MUL 23)
491 (defvar js2-DIV 24)
492 (defvar js2-MOD 25)
493 (defvar js2-NOT 26)
494 (defvar js2-BITNOT 27)
495 (defvar js2-POS 28) ; unary plus
496 (defvar js2-NEG 29) ; unary minus
497 (defvar js2-NEW 30)
498 (defvar js2-DELPROP 31)
499 (defvar js2-TYPEOF 32)
500 (defvar js2-GETPROP 33)
501 (defvar js2-GETPROPNOWARN 34)
502 (defvar js2-SETPROP 35)
503 (defvar js2-GETELEM 36)
504 (defvar js2-SETELEM 37)
505 (defvar js2-CALL 38)
506 (defvar js2-NAME 39) ; an identifier
507 (defvar js2-NUMBER 40)
508 (defvar js2-STRING 41)
509 (defvar js2-NULL 42)
510 (defvar js2-THIS 43)
511 (defvar js2-FALSE 44)
512 (defvar js2-TRUE 45)
513 (defvar js2-SHEQ 46) ; shallow equality (===)
514 (defvar js2-SHNE 47) ; shallow inequality (!==)
515 (defvar js2-REGEXP 48)
516 (defvar js2-BINDNAME 49)
517 (defvar js2-THROW 50)
518 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
519 (defvar js2-IN 52)
520 (defvar js2-INSTANCEOF 53)
521 (defvar js2-LOCAL_LOAD 54)
522 (defvar js2-GETVAR 55)
523 (defvar js2-SETVAR 56)
524 (defvar js2-CATCH_SCOPE 57)
525 (defvar js2-ENUM_INIT_KEYS 58)
526 (defvar js2-ENUM_INIT_VALUES 59)
527 (defvar js2-ENUM_INIT_ARRAY 60)
528 (defvar js2-ENUM_NEXT 61)
529 (defvar js2-ENUM_ID 62)
530 (defvar js2-THISFN 63)
531 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
532 (defvar js2-ARRAYLIT 65) ; array literal
533 (defvar js2-OBJECTLIT 66) ; object literal
534 (defvar js2-GET_REF 67) ; *reference
535 (defvar js2-SET_REF 68) ; *reference = something
536 (defvar js2-DEL_REF 69) ; delete reference
537 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
538 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
539 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
540
541 ;; XML support
542 (defvar js2-DEFAULTNAMESPACE 73)
543 (defvar js2-ESCXMLATTR 74)
544 (defvar js2-ESCXMLTEXT 75)
545 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
546 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
547 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
548 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
549
550 (defvar js2-first-bytecode js2-ENTERWITH)
551 (defvar js2-last-bytecode js2-REF_NS_NAME)
552
553 (defvar js2-TRY 80)
554 (defvar js2-SEMI 81) ; semicolon
555 (defvar js2-LB 82) ; left and right brackets
556 (defvar js2-RB 83)
557 (defvar js2-LC 84) ; left and right curly-braces
558 (defvar js2-RC 85)
559 (defvar js2-LP 86) ; left and right parens
560 (defvar js2-RP 87)
561 (defvar js2-COMMA 88) ; comma operator
562
563 (defvar js2-ASSIGN 89) ; simple assignment (=)
564 (defvar js2-ASSIGN_BITOR 90) ; |=
565 (defvar js2-ASSIGN_BITXOR 91) ; ^=
566 (defvar js2-ASSIGN_BITAND 92) ; &=
567 (defvar js2-ASSIGN_LSH 93) ; <<=
568 (defvar js2-ASSIGN_RSH 94) ; >>=
569 (defvar js2-ASSIGN_URSH 95) ; >>>=
570 (defvar js2-ASSIGN_ADD 96) ; +=
571 (defvar js2-ASSIGN_SUB 97) ; -=
572 (defvar js2-ASSIGN_MUL 98) ; *=
573 (defvar js2-ASSIGN_DIV 99) ; /=
574 (defvar js2-ASSIGN_MOD 100) ; %=
575
576 (defvar js2-first-assign js2-ASSIGN)
577 (defvar js2-last-assign js2-ASSIGN_MOD)
578
579 (defvar js2-HOOK 101) ; conditional (?:)
580 (defvar js2-COLON 102)
581 (defvar js2-OR 103) ; logical or (||)
582 (defvar js2-AND 104) ; logical and (&&)
583 (defvar js2-INC 105) ; increment/decrement (++ --)
584 (defvar js2-DEC 106)
585 (defvar js2-DOT 107) ; member operator (.)
586 (defvar js2-FUNCTION 108) ; function keyword
587 (defvar js2-EXPORT 109) ; export keyword
588 (defvar js2-IMPORT 110) ; import keyword
589 (defvar js2-IF 111) ; if keyword
590 (defvar js2-ELSE 112) ; else keyword
591 (defvar js2-SWITCH 113) ; switch keyword
592 (defvar js2-CASE 114) ; case keyword
593 (defvar js2-DEFAULT 115) ; default keyword
594 (defvar js2-WHILE 116) ; while keyword
595 (defvar js2-DO 117) ; do keyword
596 (defvar js2-FOR 118) ; for keyword
597 (defvar js2-BREAK 119) ; break keyword
598 (defvar js2-CONTINUE 120) ; continue keyword
599 (defvar js2-VAR 121) ; var keyword
600 (defvar js2-WITH 122) ; with keyword
601 (defvar js2-CATCH 123) ; catch keyword
602 (defvar js2-FINALLY 124) ; finally keyword
603 (defvar js2-VOID 125) ; void keyword
604 (defvar js2-RESERVED 126) ; reserved keywords
605
606 (defvar js2-EMPTY 127)
607
608 ;; Types used for the parse tree - never returned by scanner.
609
610 (defvar js2-BLOCK 128) ; statement block
611 (defvar js2-LABEL 129) ; label
612 (defvar js2-TARGET 130)
613 (defvar js2-LOOP 131)
614 (defvar js2-EXPR_VOID 132) ; expression statement in functions
615 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
616 (defvar js2-JSR 134)
617 (defvar js2-SCRIPT 135) ; top-level node for entire script
618 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
619 (defvar js2-USE_STACK 137)
620 (defvar js2-SETPROP_OP 138) ; x.y op= something
621 (defvar js2-SETELEM_OP 139) ; x[y] op= something
622 (defvar js2-LOCAL_BLOCK 140)
623 (defvar js2-SET_REF_OP 141) ; *reference op= something
624
625 ;; For XML support:
626 (defvar js2-DOTDOT 142) ; member operator (..)
627 (defvar js2-COLONCOLON 143) ; namespace::name
628 (defvar js2-XML 144) ; XML type
629 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
630 (defvar js2-XMLATTR 146) ; @
631 (defvar js2-XMLEND 147)
632
633 ;; Optimizer-only tokens
634 (defvar js2-TO_OBJECT 148)
635 (defvar js2-TO_DOUBLE 149)
636
637 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
638 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
639 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
640 (defvar js2-CONST 153)
641 (defvar js2-SETCONST 154)
642 (defvar js2-SETCONSTVAR 155)
643 (defvar js2-ARRAYCOMP 156)
644 (defvar js2-LETEXPR 157)
645 (defvar js2-WITHEXPR 158)
646 (defvar js2-DEBUGGER 159)
647
648 (defvar js2-COMMENT 160)
649 (defvar js2-ENUM 161) ; for "enum" reserved word
650
651 (defconst js2-num-tokens (1+ js2-ENUM))
652
653 (defconst js2-debug-print-trees nil)
654
655 ;; Rhino accepts any string or stream as input. Emacs character
656 ;; processing works best in buffers, so we'll assume the input is a
657 ;; buffer. JavaScript strings can be copied into temp buffers before
658 ;; scanning them.
659
660 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
661 ;; They're the Emacs equivalent of instance variables, more or less.
662
663 (js2-deflocal js2-ts-dirty-line nil
664 "Token stream buffer-local variable.
665 Indicates stuff other than whitespace since start of line.")
666
667 (js2-deflocal js2-ts-regexp-flags nil
668 "Token stream buffer-local variable.")
669
670 (js2-deflocal js2-ts-string ""
671 "Token stream buffer-local variable.
672 Last string scanned.")
673
674 (js2-deflocal js2-ts-number nil
675 "Token stream buffer-local variable.
676 Last literal number scanned.")
677
678 (js2-deflocal js2-ts-hit-eof nil
679 "Token stream buffer-local variable.")
680
681 (js2-deflocal js2-ts-line-start 0
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-lineno 1
685 "Token stream buffer-local variable.")
686
687 (js2-deflocal js2-ts-line-end-char -1
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
691 "Token stream buffer-local variable.
692 Current scan position.")
693
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (js2-deflocal js2-ts-comment-type nil
708 "Token stream buffer-local variable.")
709
710 ;;; Parser variables
711
712 (js2-deflocal js2-parsed-errors nil
713 "List of errors produced during scanning/parsing.")
714
715 (js2-deflocal js2-parsed-warnings nil
716 "List of warnings produced during scanning/parsing.")
717
718 (js2-deflocal js2-recover-from-parse-errors t
719 "Non-nil to continue parsing after a syntax error.
720
721 In recovery mode, the AST will be built in full, and any error
722 nodes will be flagged with appropriate error information. If
723 this flag is nil, a syntax error will result in an error being
724 signaled.
725
726 The variable is automatically buffer-local, because different
727 modes that use the parser will need different settings.")
728
729 (js2-deflocal js2-parse-hook nil
730 "List of callbacks for receiving parsing progress.")
731
732 (defvar js2-parse-finished-hook nil
733 "List of callbacks to notify when parsing finishes.
734 Not called if parsing was interrupted.")
735
736 (js2-deflocal js2-is-eval-code nil
737 "True if we're evaluating code in a string.
738 If non-nil, the tokenizer will record the token text, and the AST nodes
739 will record their source text. Off by default for IDE modes, since the
740 text is available in the buffer.")
741
742 (defvar js2-parse-ide-mode t
743 "Non-nil if the parser is being used for `js2-mode'.
744 If non-nil, the parser will set text properties for fontification
745 and the syntax table. The value should be nil when using the
746 parser as a frontend to an interpreter or byte compiler.")
747
748 ;;; Parser instance variables (buffer-local vars for js2-parse)
749
750 (defconst js2-clear-ti-mask #xFFFF
751 "Mask to clear token information bits.")
752
753 (defconst js2-ti-after-eol (lsh 1 16)
754 "Flag: first token of the source line.")
755
756 (defconst js2-ti-check-label (lsh 1 17)
757 "Flag: indicates to check for label.")
758
759 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
760
761 (js2-deflocal js2-compiler-generate-debug-info t)
762 (js2-deflocal js2-compiler-use-dynamic-scope nil)
763 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
764 (js2-deflocal js2-compiler-xml-available t)
765 (js2-deflocal js2-compiler-optimization-level 0)
766 (js2-deflocal js2-compiler-generating-source t)
767 (js2-deflocal js2-compiler-strict-mode nil)
768 (js2-deflocal js2-compiler-report-warning-as-error nil)
769 (js2-deflocal js2-compiler-generate-observer-count nil)
770 (js2-deflocal js2-compiler-activation-names nil)
771
772 ;; SKIP: sourceURI
773
774 ;; There's a compileFunction method in Context.java - may need it.
775 (js2-deflocal js2-called-by-compile-function nil
776 "True if `js2-parse' was called by `js2-compile-function'.
777 Will only be used when we finish implementing the interpreter.")
778
779 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
780
781 (js2-deflocal js2-current-flagged-token js2-EOF)
782 (js2-deflocal js2-current-token js2-EOF)
783
784 ;; SKIP: node factory - we're going to just call functions directly,
785 ;; and eventually go to a unified AST format.
786
787 (js2-deflocal js2-nesting-of-function 0)
788
789 (js2-deflocal js2-recorded-assignments nil
790 "Tracks assignments found during parsing.")
791
792 (defcustom js2-global-externs nil
793 "A list of any extern names you'd like to consider always declared.
794 This list is global and is used by all js2-mode files.
795 You can create buffer-local externs list using `js2-additional-externs'.
796
797 There is also a buffer-local variable `js2-default-externs',
798 which is initialized by default to include the Ecma-262 externs
799 and the standard browser externs. The three lists are all
800 checked during highlighting."
801 :type 'list
802 :group 'js2-mode)
803
804 (js2-deflocal js2-default-externs nil
805 "Default external declarations.
806
807 These are currently only used for highlighting undeclared variables,
808 which only worries about top-level (unqualified) references.
809 As js2-mode's processing improves, we will flesh out this list.
810
811 The initial value is set to `js2-ecma-262-externs', unless you
812 have set `js2-include-browser-externs', in which case the browser
813 externs are also included.
814
815 See `js2-additional-externs' for more information.")
816
817 (defcustom js2-include-browser-externs t
818 "Non-nil to include browser externs in the master externs list.
819 If you work on JavaScript files that are not intended for browsers,
820 such as Mozilla Rhino server-side JavaScript, set this to nil.
821 You can always include them on a per-file basis by calling
822 `js2-add-browser-externs' from a function on `js2-mode-hook'.
823
824 See `js2-additional-externs' for more information about externs."
825 :type 'boolean
826 :group 'js2-mode)
827
828 (defcustom js2-include-rhino-externs t
829 "Non-nil to include Mozilla Rhino externs in the master externs list.
830 See `js2-additional-externs' for more information about externs."
831 :type 'boolean
832 :group 'js2-mode)
833
834 (defcustom js2-include-gears-externs t
835 "Non-nil to include Google Gears externs in the master externs list.
836 See `js2-additional-externs' for more information about externs."
837 :type 'boolean
838 :group 'js2-mode)
839
840 (js2-deflocal js2-additional-externs nil
841 "A buffer-local list of additional external declarations.
842 It is used to decide whether variables are considered undeclared
843 for purposes of highlighting.
844
845 Each entry is a lisp string. The string should be the fully qualified
846 name of an external entity. All externs should be added to this list,
847 so that as js2-mode's processing improves it can take advantage of them.
848
849 You may want to declare your externs in three ways.
850 First, you can add externs that are valid for all your JavaScript files.
851 You should probably do this by adding them to `js2-global-externs', which
852 is a global list used for all js2-mode files.
853
854 Next, you can add a function to `js2-mode-hook' that adds additional
855 externs appropriate for the specific file, perhaps based on its path.
856 These should go in `js2-additional-externs', which is buffer-local.
857
858 Finally, you can add a function to `js2-post-parse-callbacks',
859 which is called after parsing completes, and `root' is bound to
860 the root of the parse tree. At this stage you can set up an AST
861 node visitor using `js2-visit-ast' and examine the parse tree
862 for specific import patterns that may imply the existence of
863 other externs, possibly tied to your build system. These should also
864 be added to `js2-additional-externs'.
865
866 Your post-parse callback may of course also use the simpler and
867 faster (but perhaps less robust) approach of simply scanning the
868 buffer text for your imports, using regular expressions.")
869
870 ;; SKIP: decompiler
871 ;; SKIP: encoded-source
872
873 ;;; The following variables are per-function and should be saved/restored
874 ;;; during function parsing...
875
876 (js2-deflocal js2-current-script-or-fn nil)
877 (js2-deflocal js2-current-scope nil)
878 (js2-deflocal js2-nesting-of-with 0)
879 (js2-deflocal js2-label-set nil
880 "An alist mapping label names to nodes.")
881
882 (js2-deflocal js2-loop-set nil)
883 (js2-deflocal js2-loop-and-switch-set nil)
884 (js2-deflocal js2-has-return-value nil)
885 (js2-deflocal js2-end-flags 0)
886
887 ;;; ...end of per function variables
888
889 ;; Without 2-token lookahead, labels are a problem.
890 ;; These vars store the token info of the last matched name,
891 ;; iff it wasn't the last matched token. Only valid in some contexts.
892 (defvar js2-prev-name-token-start nil)
893 (defvar js2-prev-name-token-string nil)
894
895 (defsubst js2-save-name-token-data (pos name)
896 (setq js2-prev-name-token-start pos
897 js2-prev-name-token-string name))
898
899 ;; These flags enumerate the possible ways a statement/function can
900 ;; terminate. These flags are used by endCheck() and by the Parser to
901 ;; detect inconsistent return usage.
902 ;;
903 ;; END_UNREACHED is reserved for code paths that are assumed to always be
904 ;; able to execute (example: throw, continue)
905 ;;
906 ;; END_DROPS_OFF indicates if the statement can transfer control to the
907 ;; next one. Statement such as return dont. A compound statement may have
908 ;; some branch that drops off control to the next statement.
909 ;;
910 ;; END_RETURNS indicates that the statement can return (without arguments)
911 ;; END_RETURNS_VALUE indicates that the statement can return a value.
912 ;;
913 ;; A compound statement such as
914 ;; if (condition) {
915 ;; return value;
916 ;; }
917 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
918
919 (defconst js2-end-unreached #x0)
920 (defconst js2-end-drops-off #x1)
921 (defconst js2-end-returns #x2)
922 (defconst js2-end-returns-value #x4)
923 (defconst js2-end-yields #x8)
924
925 ;; Rhino awkwardly passes a statementLabel parameter to the
926 ;; statementHelper() function, the main statement parser, which
927 ;; is then used by quite a few of the sub-parsers. We just make
928 ;; it a buffer-local variable and make sure it's cleaned up properly.
929 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
930
931 ;; Similarly, Rhino passes an inForInit boolean through about half
932 ;; the expression parsers. We use a dynamically-scoped variable,
933 ;; which makes it easier to funcall the parsers individually without
934 ;; worrying about whether they take the parameter or not.
935 (js2-deflocal js2-in-for-init nil)
936 (js2-deflocal js2-temp-name-counter 0)
937 (js2-deflocal js2-parse-stmt-count 0)
938
939 (defsubst js2-get-next-temp-name ()
940 (format "$%d" (incf js2-temp-name-counter)))
941
942 (defvar js2-parse-interruptable-p t
943 "Set this to nil to force parse to continue until finished.
944 This will mostly be useful for interpreters.")
945
946 (defvar js2-statements-per-pause 50
947 "Pause after this many statements to check for user input.
948 If user input is pending, stop the parse and discard the tree.
949 This makes for a smoother user experience for large files.
950 You may have to wait a second or two before the highlighting
951 and error-reporting appear, but you can always type ahead if
952 you wish. This appears to be more or less how Eclipse, IntelliJ
953 and other editors work.")
954
955 (js2-deflocal js2-record-comments t
956 "Instructs the scanner to record comments in `js2-scanned-comments'.")
957
958 (js2-deflocal js2-scanned-comments nil
959 "List of all comments from the current parse.")
960
961 (defcustom js2-mode-indent-inhibit-undo nil
962 "Non-nil to disable collection of Undo information when indenting lines.
963 Some users have requested this behavior. It's nil by default because
964 other Emacs modes don't work this way."
965 :type 'boolean
966 :group 'js2-mode)
967
968 (defcustom js2-mode-indent-ignore-first-tab nil
969 "If non-nil, ignore first TAB keypress if we look indented properly.
970 It's fairly common for users to navigate to an already-indented line
971 and press TAB for reassurance that it's been indented. For this class
972 of users, we want the first TAB press on a line to be ignored if the
973 line is already indented to one of the precomputed alternatives.
974
975 This behavior is only partly implemented. If you TAB-indent a line,
976 navigate to another line, and then navigate back, it fails to clear
977 the last-indented variable, so it thinks you've already hit TAB once,
978 and performs the indent. A full solution would involve getting on the
979 point-motion hooks for the entire buffer. If we come across another
980 use cases that requires watching point motion, I'll consider doing it.
981
982 If you set this variable to nil, then the TAB key will always change
983 the indentation of the current line, if more than one alternative
984 indentation spot exists."
985 :type 'boolean
986 :group 'js2-mode)
987
988 (defvar js2-indent-hook nil
989 "A hook for user-defined indentation rules.
990
991 Functions on this hook should expect two arguments: (LIST INDEX)
992 The LIST argument is the list of computed indentation points for
993 the current line. INDEX is the list index of the indentation point
994 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
995 indent function is not going to change the current line indentation.
996
997 If a hook function on this list returns a non-nil value, then
998 `js2-bounce-indent' assumes the hook function has performed its own
999 indentation, and will do nothing. If all hook functions on the list
1000 return nil, then `js2-bounce-indent' will use its computed indentation
1001 and reindent the line.
1002
1003 When hook functions on this hook list are called, the variable
1004 `js2-mode-ast' may or may not be set, depending on whether the
1005 parse tree is available. If the variable is nil, you can pass a
1006 callback to `js2-mode-wait-for-parse', and your callback will be
1007 called after the new parse tree is built. This can take some time
1008 in large files.")
1009
1010 (defface js2-warning
1011 `((((class color) (background light))
1012 (:underline "orange"))
1013 (((class color) (background dark))
1014 (:underline "orange"))
1015 (t (:underline t)))
1016 "Face for JavaScript warnings."
1017 :group 'js2-mode)
1018
1019 (defface js2-error
1020 `((((class color) (background light))
1021 (:foreground "red"))
1022 (((class color) (background dark))
1023 (:foreground "red"))
1024 (t (:foreground "red")))
1025 "Face for JavaScript errors."
1026 :group 'js2-mode)
1027
1028 (defface js2-jsdoc-tag
1029 '((t :foreground "SlateGray"))
1030 "Face used to highlight @whatever tags in jsdoc comments."
1031 :group 'js2-mode)
1032
1033 (defface js2-jsdoc-type
1034 '((t :foreground "SteelBlue"))
1035 "Face used to highlight {FooBar} types in jsdoc comments."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-value
1039 '((t :foreground "PeachPuff3"))
1040 "Face used to highlight tag values in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-function-param
1044 '((t :foreground "SeaGreen"))
1045 "Face used to highlight function parameters in javascript."
1046 :group 'js2-mode)
1047
1048 (defface js2-instance-member
1049 '((t :foreground "DarkOrchid"))
1050 "Face used to highlight instance variables in javascript.
1051 Not currently used."
1052 :group 'js2-mode)
1053
1054 (defface js2-private-member
1055 '((t :foreground "PeachPuff3"))
1056 "Face used to highlight calls to private methods in javascript.
1057 Not currently used."
1058 :group 'js2-mode)
1059
1060 (defface js2-private-function-call
1061 '((t :foreground "goldenrod"))
1062 "Face used to highlight calls to private functions in javascript.
1063 Not currently used."
1064 :group 'js2-mode)
1065
1066 (defface js2-jsdoc-html-tag-name
1067 (if js2-emacs22
1068 '((((class color) (min-colors 88) (background light))
1069 (:foreground "rosybrown"))
1070 (((class color) (min-colors 8) (background dark))
1071 (:foreground "yellow"))
1072 (((class color) (min-colors 8) (background light))
1073 (:foreground "magenta")))
1074 '((((type tty pc) (class color) (background light))
1075 (:foreground "magenta"))
1076 (((type tty pc) (class color) (background dark))
1077 (:foreground "yellow"))
1078 (t (:foreground "RosyBrown"))))
1079 "Face used to highlight jsdoc html tag names"
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-html-tag-delimiter
1083 (if js2-emacs22
1084 '((((class color) (min-colors 88) (background light))
1085 (:foreground "dark khaki"))
1086 (((class color) (min-colors 8) (background dark))
1087 (:foreground "green"))
1088 (((class color) (min-colors 8) (background light))
1089 (:foreground "green")))
1090 '((((type tty pc) (class color) (background light))
1091 (:foreground "green"))
1092 (((type tty pc) (class color) (background dark))
1093 (:foreground "green"))
1094 (t (:foreground "dark khaki"))))
1095 "Face used to highlight brackets in jsdoc html tags."
1096 :group 'js2-mode)
1097
1098 (defface js2-magic-paren
1099 '((t :underline t))
1100 "Face used to color parens that will be auto-overwritten."
1101 :group 'js2-mode)
1102
1103 (defcustom js2-post-parse-callbacks nil
1104 "A list of callback functions invoked after parsing finishes.
1105 Currently, the main use for this function is to add synthetic
1106 declarations to `js2-recorded-assignments', which see."
1107 :type 'list
1108 :group 'js2-mode)
1109
1110 (defface js2-external-variable
1111 '((t :foreground "orange"))
1112 "Face used to highlight assignments to undeclared variables.
1113 An undeclared variable is any variable not declared with var or let
1114 in the current scope or any lexically enclosing scope. If you assign
1115 to such a variable, then you are either expecting it to originate from
1116 another file, or you've got a potential bug."
1117 :group 'js2-mode)
1118
1119 (defcustom js2-highlight-external-variables t
1120 "Non-nil to higlight assignments to undeclared variables."
1121 :type 'boolean
1122 :group 'js2-mode)
1123
1124 (defcustom js2-auto-insert-catch-block t
1125 "Non-nil to insert matching catch block on open-curly after `try'."
1126 :type 'boolean
1127 :group 'js2-mode)
1128
1129 (defvar js2-mode-map
1130 (let ((map (make-sparse-keymap))
1131 keys)
1132 (define-key map [mouse-1] #'js2-mode-show-node)
1133 (define-key map (kbd "C-m") #'js2-enter-key)
1134 (when js2-rebind-eol-bol-keys
1135 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1136 (define-key map (kbd "C-e") #'js2-end-of-line))
1137 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1138 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1139 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1140 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1141 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1142 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1143 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1144 (define-key map (kbd "C-c C-`") #'js2-next-error)
1145 ;; also define user's preference for next-error, if available
1146 (if (setq keys (where-is-internal #'next-error))
1147 (define-key map (car keys) #'js2-next-error))
1148 (define-key map (or (car (where-is-internal #'mark-defun))
1149 (kbd "M-C-h"))
1150 #'js2-mark-defun)
1151 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1152 (kbd "C-x nd"))
1153 #'js2-narrow-to-defun)
1154 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1155 (when js2-auto-indent-p
1156 (mapc (lambda (key)
1157 (define-key map key #'js2-insert-and-indent))
1158 js2-electric-keys))
1159
1160 (define-key map [menu-bar javascript]
1161 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1162
1163 (define-key map [menu-bar javascript customize-js2-mode]
1164 '(menu-item "Customize js2-mode" js2-mode-customize
1165 :help "Customize the behavior of this mode"))
1166
1167 (define-key map [menu-bar javascript js2-force-refresh]
1168 '(menu-item "Force buffer refresh" js2-mode-reset
1169 :help "Re-parse the buffer from scratch"))
1170
1171 (define-key map [menu-bar javascript separator-2]
1172 '("--"))
1173
1174 (define-key map [menu-bar javascript next-error]
1175 '(menu-item "Next warning or error" js2-next-error
1176 :enabled (and js2-mode-ast
1177 (or (js2-ast-root-errors js2-mode-ast)
1178 (js2-ast-root-warnings js2-mode-ast)))
1179 :help "Move to next warning or error"))
1180
1181 (define-key map [menu-bar javascript display-errors]
1182 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1183 :visible (not js2-mode-show-parse-errors)
1184 :help "Turn on display of warnings and errors"))
1185
1186 (define-key map [menu-bar javascript hide-errors]
1187 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1188 :visible js2-mode-show-parse-errors
1189 :help "Turn off display of warnings and errors"))
1190
1191 (define-key map [menu-bar javascript separator-1]
1192 '("--"))
1193
1194 (define-key map [menu-bar javascript js2-toggle-function]
1195 '(menu-item "Show/collapse element" js2-mode-toggle-element
1196 :help "Hide or show function body or comment"))
1197
1198 (define-key map [menu-bar javascript show-comments]
1199 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1200 :visible js2-mode-comments-hidden
1201 :help "Expand all hidden block comments"))
1202
1203 (define-key map [menu-bar javascript hide-comments]
1204 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1205 :visible (not js2-mode-comments-hidden)
1206 :help "Show block comments as /*...*/"))
1207
1208 (define-key map [menu-bar javascript show-all-functions]
1209 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1210 :visible js2-mode-functions-hidden
1211 :help "Expand all hidden function bodies"))
1212
1213 (define-key map [menu-bar javascript hide-all-functions]
1214 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1215 :visible (not js2-mode-functions-hidden)
1216 :help "Show {...} for all top-level function bodies"))
1217
1218 map)
1219 "Keymap used in `js2-mode' buffers.")
1220
1221 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1222
1223 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1224 "Matches a //-comment line. Must be first non-whitespace on line.
1225 First match-group is the leading whitespace.")
1226
1227 (defvar js2-mode-hook nil)
1228
1229 (js2-deflocal js2-mode-ast nil "Private variable.")
1230 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1231 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1232 (js2-deflocal js2-mode-parsing nil "Private variable.")
1233 (js2-deflocal js2-mode-node-overlay nil)
1234
1235 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1236 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1237
1238 (js2-deflocal js2-mode-fontifications nil "Private variable")
1239 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1240 (js2-deflocal js2-imenu-recorder nil "Private variable")
1241 (js2-deflocal js2-imenu-function-map nil "Private variable")
1242
1243 (defvar js2-paragraph-start
1244 "\\(@[a-zA-Z]+\\>\\|$\\)")
1245
1246 ;; Note that we also set a 'c-in-sws text property in html comments,
1247 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1248 (defvar js2-syntactic-ws-start
1249 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1250
1251 (defvar js2-syntactic-ws-end
1252 "\\s \\|[\n\r/]\\|\\s!")
1253
1254 (defvar js2-syntactic-eol
1255 (concat "\\s *\\(/\\*[^*\n\r]*"
1256 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1257 "\\*+/\\s *\\)*"
1258 "\\(//\\|/\\*[^*\n\r]*"
1259 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1260 "\\|\\\\$\\|$\\)")
1261 "Copied from `java-mode'. Needed for some cc-engine functions.")
1262
1263 (defvar js2-comment-prefix-regexp
1264 "//+\\|\\**")
1265
1266 (defvar js2-comment-start-skip
1267 "\\(//+\\|/\\*+\\)\\s *")
1268
1269 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1270 "Non-nil to emit status messages during parsing.")
1271
1272 (defvar js2-mode-functions-hidden nil "private variable")
1273 (defvar js2-mode-comments-hidden nil "private variable")
1274
1275 (defvar js2-mode-syntax-table
1276 (let ((table (make-syntax-table)))
1277 (c-populate-syntax-table table)
1278 table)
1279 "Syntax table used in js2-mode buffers.")
1280
1281 (defvar js2-mode-abbrev-table nil
1282 "Abbrev table in use in `js2-mode' buffers.")
1283 (define-abbrev-table 'js2-mode-abbrev-table ())
1284
1285 (defvar js2-mode-pending-parse-callbacks nil
1286 "List of functions waiting to be notified that parse is finished.")
1287
1288 (defvar js2-mode-last-indented-line -1)
1289
1290 ;;; Localizable error and warning messages
1291
1292 ;; Messages are copied from Rhino's Messages.properties.
1293 ;; Many of the Java-specific messages have been elided.
1294 ;; Add any js2-specific ones at the end, so we can keep
1295 ;; this file synced with changes to Rhino's.
1296
1297 (defvar js2-message-table
1298 (make-hash-table :test 'equal :size 250)
1299 "Contains localized messages for js2-mode.")
1300
1301 ;; TODO(stevey): construct this table at compile-time.
1302 (defmacro js2-msg (key &rest strings)
1303 `(puthash ,key (funcall #'concat ,@strings)
1304 js2-message-table))
1305
1306 (defun js2-get-msg (msg-key)
1307 "Look up a localized message.
1308 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1309 the correct number of ARGS must be provided."
1310 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1311 (args (if (listp msg-key) (cdr msg-key)))
1312 (msg (gethash key js2-message-table)))
1313 (if msg
1314 (apply #'format msg args)
1315 key))) ; default to showing the key
1316
1317 (js2-msg "msg.dup.parms"
1318 "Duplicate parameter name '%s'.")
1319
1320 (js2-msg "msg.too.big.jump"
1321 "Program too complex: jump offset too big.")
1322
1323 (js2-msg "msg.too.big.index"
1324 "Program too complex: internal index exceeds 64K limit.")
1325
1326 (js2-msg "msg.while.compiling.fn"
1327 "Encountered code generation error while compiling function '%s': %s")
1328
1329 (js2-msg "msg.while.compiling.script"
1330 "Encountered code generation error while compiling script: %s")
1331
1332 ;; Context
1333 (js2-msg "msg.ctor.not.found"
1334 "Constructor for '%s' not found.")
1335
1336 (js2-msg "msg.not.ctor"
1337 "'%s' is not a constructor.")
1338
1339 ;; FunctionObject
1340 (js2-msg "msg.varargs.ctor"
1341 "Method or constructor '%s' must be static "
1342 "with the signature (Context cx, Object[] args, "
1343 "Function ctorObj, boolean inNewExpr) "
1344 "to define a variable arguments constructor.")
1345
1346 (js2-msg "msg.varargs.fun"
1347 "Method '%s' must be static with the signature "
1348 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1349 "to define a variable arguments function.")
1350
1351 (js2-msg "msg.incompat.call"
1352 "Method '%s' called on incompatible object.")
1353
1354 (js2-msg "msg.bad.parms"
1355 "Unsupported parameter type '%s' in method '%s'.")
1356
1357 (js2-msg "msg.bad.method.return"
1358 "Unsupported return type '%s' in method '%s'.")
1359
1360 (js2-msg "msg.bad.ctor.return"
1361 "Construction of objects of type '%s' is not supported.")
1362
1363 (js2-msg "msg.no.overload"
1364 "Method '%s' occurs multiple times in class '%s'.")
1365
1366 (js2-msg "msg.method.not.found"
1367 "Method '%s' not found in '%s'.")
1368
1369 ;; IRFactory
1370
1371 (js2-msg "msg.bad.for.in.lhs"
1372 "Invalid left-hand side of for..in loop.")
1373
1374 (js2-msg "msg.mult.index"
1375 "Only one variable allowed in for..in loop.")
1376
1377 (js2-msg "msg.bad.for.in.destruct"
1378 "Left hand side of for..in loop must be an array of "
1379 "length 2 to accept key/value pair.")
1380
1381 (js2-msg "msg.cant.convert"
1382 "Can't convert to type '%s'.")
1383
1384 (js2-msg "msg.bad.assign.left"
1385 "Invalid assignment left-hand side.")
1386
1387 (js2-msg "msg.bad.decr"
1388 "Invalid decerement operand.")
1389
1390 (js2-msg "msg.bad.incr"
1391 "Invalid increment operand.")
1392
1393 (js2-msg "msg.bad.yield"
1394 "yield must be in a function.")
1395
1396 (js2-msg "msg.yield.parenthesized"
1397 "yield expression must be parenthesized.")
1398
1399 ;; NativeGlobal
1400 (js2-msg "msg.cant.call.indirect"
1401 "Function '%s' must be called directly, and not by way of a "
1402 "function of another name.")
1403
1404 (js2-msg "msg.eval.nonstring"
1405 "Calling eval() with anything other than a primitive "
1406 "string value will simply return the value. "
1407 "Is this what you intended?")
1408
1409 (js2-msg "msg.eval.nonstring.strict"
1410 "Calling eval() with anything other than a primitive "
1411 "string value is not allowed in strict mode.")
1412
1413 (js2-msg "msg.bad.destruct.op"
1414 "Invalid destructuring assignment operator")
1415
1416 ;; NativeCall
1417 (js2-msg "msg.only.from.new"
1418 "'%s' may only be invoked from a `new' expression.")
1419
1420 (js2-msg "msg.deprec.ctor"
1421 "The '%s' constructor is deprecated.")
1422
1423 ;; NativeFunction
1424 (js2-msg "msg.no.function.ref.found"
1425 "no source found to decompile function reference %s")
1426
1427 (js2-msg "msg.arg.isnt.array"
1428 "second argument to Function.prototype.apply must be an array")
1429
1430 ;; NativeGlobal
1431 (js2-msg "msg.bad.esc.mask"
1432 "invalid string escape mask")
1433
1434 ;; NativeRegExp
1435 (js2-msg "msg.bad.quant"
1436 "Invalid quantifier %s")
1437
1438 (js2-msg "msg.overlarge.backref"
1439 "Overly large back reference %s")
1440
1441 (js2-msg "msg.overlarge.min"
1442 "Overly large minimum %s")
1443
1444 (js2-msg "msg.overlarge.max"
1445 "Overly large maximum %s")
1446
1447 (js2-msg "msg.zero.quant"
1448 "Zero quantifier %s")
1449
1450 (js2-msg "msg.max.lt.min"
1451 "Maximum %s less than minimum")
1452
1453 (js2-msg "msg.unterm.quant"
1454 "Unterminated quantifier %s")
1455
1456 (js2-msg "msg.unterm.paren"
1457 "Unterminated parenthetical %s")
1458
1459 (js2-msg "msg.unterm.class"
1460 "Unterminated character class %s")
1461
1462 (js2-msg "msg.bad.range"
1463 "Invalid range in character class.")
1464
1465 (js2-msg "msg.trail.backslash"
1466 "Trailing \\ in regular expression.")
1467
1468 (js2-msg "msg.re.unmatched.right.paren"
1469 "unmatched ) in regular expression.")
1470
1471 (js2-msg "msg.no.regexp"
1472 "Regular expressions are not available.")
1473
1474 (js2-msg "msg.bad.backref"
1475 "back-reference exceeds number of capturing parentheses.")
1476
1477 (js2-msg "msg.bad.regexp.compile"
1478 "Only one argument may be specified if the first "
1479 "argument to RegExp.prototype.compile is a RegExp object.")
1480
1481 ;; Parser
1482 (js2-msg "msg.got.syntax.errors"
1483 "Compilation produced %s syntax errors.")
1484
1485 (js2-msg "msg.var.redecl"
1486 "TypeError: redeclaration of var %s.")
1487
1488 (js2-msg "msg.const.redecl"
1489 "TypeError: redeclaration of const %s.")
1490
1491 (js2-msg "msg.let.redecl"
1492 "TypeError: redeclaration of variable %s.")
1493
1494 (js2-msg "msg.parm.redecl"
1495 "TypeError: redeclaration of formal parameter %s.")
1496
1497 (js2-msg "msg.fn.redecl"
1498 "TypeError: redeclaration of function %s.")
1499
1500 (js2-msg "msg.let.decl.not.in.block"
1501 "SyntaxError: let declaration not directly within block")
1502
1503 ;; NodeTransformer
1504 (js2-msg "msg.dup.label"
1505 "duplicated label")
1506
1507 (js2-msg "msg.undef.label"
1508 "undefined label")
1509
1510 (js2-msg "msg.bad.break"
1511 "unlabelled break must be inside loop or switch")
1512
1513 (js2-msg "msg.continue.outside"
1514 "continue must be inside loop")
1515
1516 (js2-msg "msg.continue.nonloop"
1517 "continue can only use labels of iteration statements")
1518
1519 (js2-msg "msg.bad.throw.eol"
1520 "Line terminator is not allowed between the throw "
1521 "keyword and throw expression.")
1522
1523 (js2-msg "msg.no.paren.parms"
1524 "missing ( before function parameters.")
1525
1526 (js2-msg "msg.no.parm"
1527 "missing formal parameter")
1528
1529 (js2-msg "msg.no.paren.after.parms"
1530 "missing ) after formal parameters")
1531
1532 (js2-msg "msg.no.brace.body"
1533 "missing '{' before function body")
1534
1535 (js2-msg "msg.no.brace.after.body"
1536 "missing } after function body")
1537
1538 (js2-msg "msg.no.paren.cond"
1539 "missing ( before condition")
1540
1541 (js2-msg "msg.no.paren.after.cond"
1542 "missing ) after condition")
1543
1544 (js2-msg "msg.no.semi.stmt"
1545 "missing ; before statement")
1546
1547 (js2-msg "msg.missing.semi"
1548 "missing ; after statement")
1549
1550 (js2-msg "msg.no.name.after.dot"
1551 "missing name after . operator")
1552
1553 (js2-msg "msg.no.name.after.coloncolon"
1554 "missing name after :: operator")
1555
1556 (js2-msg "msg.no.name.after.dotdot"
1557 "missing name after .. operator")
1558
1559 (js2-msg "msg.no.name.after.xmlAttr"
1560 "missing name after .@")
1561
1562 (js2-msg "msg.no.bracket.index"
1563 "missing ] in index expression")
1564
1565 (js2-msg "msg.no.paren.switch"
1566 "missing ( before switch expression")
1567
1568 (js2-msg "msg.no.paren.after.switch"
1569 "missing ) after switch expression")
1570
1571 (js2-msg "msg.no.brace.switch"
1572 "missing '{' before switch body")
1573
1574 (js2-msg "msg.bad.switch"
1575 "invalid switch statement")
1576
1577 (js2-msg "msg.no.colon.case"
1578 "missing : after case expression")
1579
1580 (js2-msg "msg.double.switch.default"
1581 "double default label in the switch statement")
1582
1583 (js2-msg "msg.no.while.do"
1584 "missing while after do-loop body")
1585
1586 (js2-msg "msg.no.paren.for"
1587 "missing ( after for")
1588
1589 (js2-msg "msg.no.semi.for"
1590 "missing ; after for-loop initializer")
1591
1592 (js2-msg "msg.no.semi.for.cond"
1593 "missing ; after for-loop condition")
1594
1595 (js2-msg "msg.in.after.for.name"
1596 "missing in after for")
1597
1598 (js2-msg "msg.no.paren.for.ctrl"
1599 "missing ) after for-loop control")
1600
1601 (js2-msg "msg.no.paren.with"
1602 "missing ( before with-statement object")
1603
1604 (js2-msg "msg.no.paren.after.with"
1605 "missing ) after with-statement object")
1606
1607 (js2-msg "msg.no.paren.after.let"
1608 "missing ( after let")
1609
1610 (js2-msg "msg.no.paren.let"
1611 "missing ) after variable list")
1612
1613 (js2-msg "msg.no.curly.let"
1614 "missing } after let statement")
1615
1616 (js2-msg "msg.bad.return"
1617 "invalid return")
1618
1619 (js2-msg "msg.no.brace.block"
1620 "missing } in compound statement")
1621
1622 (js2-msg "msg.bad.label"
1623 "invalid label")
1624
1625 (js2-msg "msg.bad.var"
1626 "missing variable name")
1627
1628 (js2-msg "msg.bad.var.init"
1629 "invalid variable initialization")
1630
1631 (js2-msg "msg.no.colon.cond"
1632 "missing : in conditional expression")
1633
1634 (js2-msg "msg.no.paren.arg"
1635 "missing ) after argument list")
1636
1637 (js2-msg "msg.no.bracket.arg"
1638 "missing ] after element list")
1639
1640 (js2-msg "msg.bad.prop"
1641 "invalid property id")
1642
1643 (js2-msg "msg.no.colon.prop"
1644 "missing : after property id")
1645
1646 (js2-msg "msg.no.brace.prop"
1647 "missing } after property list")
1648
1649 (js2-msg "msg.no.paren"
1650 "missing ) in parenthetical")
1651
1652 (js2-msg "msg.reserved.id"
1653 "identifier is a reserved word")
1654
1655 (js2-msg "msg.no.paren.catch"
1656 "missing ( before catch-block condition")
1657
1658 (js2-msg "msg.bad.catchcond"
1659 "invalid catch block condition")
1660
1661 (js2-msg "msg.catch.unreachable"
1662 "any catch clauses following an unqualified catch are unreachable")
1663
1664 (js2-msg "msg.no.brace.try"
1665 "missing '{' before try block")
1666
1667 (js2-msg "msg.no.brace.catchblock"
1668 "missing '{' before catch-block body")
1669
1670 (js2-msg "msg.try.no.catchfinally"
1671 "'try' without 'catch' or 'finally'")
1672
1673 (js2-msg "msg.no.return.value"
1674 "function %s does not always return a value")
1675
1676 (js2-msg "msg.anon.no.return.value"
1677 "anonymous function does not always return a value")
1678
1679 (js2-msg "msg.return.inconsistent"
1680 "return statement is inconsistent with previous usage")
1681
1682 (js2-msg "msg.generator.returns"
1683 "TypeError: generator function '%s' returns a value")
1684
1685 (js2-msg "msg.anon.generator.returns"
1686 "TypeError: anonymous generator function returns a value")
1687
1688 (js2-msg "msg.syntax"
1689 "syntax error")
1690
1691 (js2-msg "msg.unexpected.eof"
1692 "Unexpected end of file")
1693
1694 (js2-msg "msg.XML.bad.form"
1695 "illegally formed XML syntax")
1696
1697 (js2-msg "msg.XML.not.available"
1698 "XML runtime not available")
1699
1700 (js2-msg "msg.too.deep.parser.recursion"
1701 "Too deep recursion while parsing")
1702
1703 (js2-msg "msg.no.side.effects"
1704 "Code has no side effects")
1705
1706 (js2-msg "msg.extra.trailing.comma"
1707 "Trailing comma is not legal in an ECMA-262 object initializer")
1708
1709 (js2-msg "msg.array.trailing.comma"
1710 "Trailing comma yields different behavior across browsers")
1711
1712 (js2-msg "msg.equal.as.assign"
1713 (concat "Test for equality (==) mistyped as assignment (=)?"
1714 " (parenthesize to suppress warning)"))
1715
1716 (js2-msg "msg.var.hides.arg"
1717 "Variable %s hides argument")
1718
1719 (js2-msg "msg.destruct.assign.no.init"
1720 "Missing = in destructuring declaration")
1721
1722 ;; ScriptRuntime
1723 (js2-msg "msg.no.properties"
1724 "%s has no properties.")
1725
1726 (js2-msg "msg.invalid.iterator"
1727 "Invalid iterator value")
1728
1729 (js2-msg "msg.iterator.primitive"
1730 "__iterator__ returned a primitive value")
1731
1732 (js2-msg "msg.assn.create.strict"
1733 "Assignment to undeclared variable %s")
1734
1735 (js2-msg "msg.ref.undefined.prop"
1736 "Reference to undefined property '%s'")
1737
1738 (js2-msg "msg.prop.not.found"
1739 "Property %s not found.")
1740
1741 (js2-msg "msg.invalid.type"
1742 "Invalid JavaScript value of type %s")
1743
1744 (js2-msg "msg.primitive.expected"
1745 "Primitive type expected (had %s instead)")
1746
1747 (js2-msg "msg.namespace.expected"
1748 "Namespace object expected to left of :: (found %s instead)")
1749
1750 (js2-msg "msg.null.to.object"
1751 "Cannot convert null to an object.")
1752
1753 (js2-msg "msg.undef.to.object"
1754 "Cannot convert undefined to an object.")
1755
1756 (js2-msg "msg.cyclic.value"
1757 "Cyclic %s value not allowed.")
1758
1759 (js2-msg "msg.is.not.defined"
1760 "'%s' is not defined.")
1761
1762 (js2-msg "msg.undef.prop.read"
1763 "Cannot read property '%s' from %s")
1764
1765 (js2-msg "msg.undef.prop.write"
1766 "Cannot set property '%s' of %s to '%s'")
1767
1768 (js2-msg "msg.undef.prop.delete"
1769 "Cannot delete property '%s' of %s")
1770
1771 (js2-msg "msg.undef.method.call"
1772 "Cannot call method '%s' of %s")
1773
1774 (js2-msg "msg.undef.with"
1775 "Cannot apply 'with' to %s")
1776
1777 (js2-msg "msg.isnt.function"
1778 "%s is not a function, it is %s.")
1779
1780 (js2-msg "msg.isnt.function.in"
1781 "Cannot call property %s in object %s. "
1782 "It is not a function, it is '%s'.")
1783
1784 (js2-msg "msg.function.not.found"
1785 "Cannot find function %s.")
1786
1787 (js2-msg "msg.function.not.found.in"
1788 "Cannot find function %s in object %s.")
1789
1790 (js2-msg "msg.isnt.xml.object"
1791 "%s is not an xml object.")
1792
1793 (js2-msg "msg.no.ref.to.get"
1794 "%s is not a reference to read reference value.")
1795
1796 (js2-msg "msg.no.ref.to.set"
1797 "%s is not a reference to set reference value to %s.")
1798
1799 (js2-msg "msg.no.ref.from.function"
1800 "Function %s can not be used as the left-hand "
1801 "side of assignment or as an operand of ++ or -- operator.")
1802
1803 (js2-msg "msg.bad.default.value"
1804 "Object's getDefaultValue() method returned an object.")
1805
1806 (js2-msg "msg.instanceof.not.object"
1807 "Can't use instanceof on a non-object.")
1808
1809 (js2-msg "msg.instanceof.bad.prototype"
1810 "'prototype' property of %s is not an object.")
1811
1812 (js2-msg "msg.bad.radix"
1813 "illegal radix %s.")
1814
1815 ;; ScriptableObject
1816 (js2-msg "msg.default.value"
1817 "Cannot find default value for object.")
1818
1819 (js2-msg "msg.zero.arg.ctor"
1820 "Cannot load class '%s' which has no zero-parameter constructor.")
1821
1822 (js2-msg "msg.ctor.multiple.parms"
1823 "Can't define constructor or class %s since more than "
1824 "one constructor has multiple parameters.")
1825
1826 (js2-msg "msg.extend.scriptable"
1827 "%s must extend ScriptableObject in order to define property %s.")
1828
1829 (js2-msg "msg.bad.getter.parms"
1830 "In order to define a property, getter %s must have zero "
1831 "parameters or a single ScriptableObject parameter.")
1832
1833 (js2-msg "msg.obj.getter.parms"
1834 "Expected static or delegated getter %s to take "
1835 "a ScriptableObject parameter.")
1836
1837 (js2-msg "msg.getter.static"
1838 "Getter and setter must both be static or neither be static.")
1839
1840 (js2-msg "msg.setter.return"
1841 "Setter must have void return type: %s")
1842
1843 (js2-msg "msg.setter2.parms"
1844 "Two-parameter setter must take a ScriptableObject as "
1845 "its first parameter.")
1846
1847 (js2-msg "msg.setter1.parms"
1848 "Expected single parameter setter for %s")
1849
1850 (js2-msg "msg.setter2.expected"
1851 "Expected static or delegated setter %s to take two parameters.")
1852
1853 (js2-msg "msg.setter.parms"
1854 "Expected either one or two parameters for setter.")
1855
1856 (js2-msg "msg.setter.bad.type"
1857 "Unsupported parameter type '%s' in setter '%s'.")
1858
1859 (js2-msg "msg.add.sealed"
1860 "Cannot add a property to a sealed object: %s.")
1861
1862 (js2-msg "msg.remove.sealed"
1863 "Cannot remove a property from a sealed object: %s.")
1864
1865 (js2-msg "msg.modify.sealed"
1866 "Cannot modify a property of a sealed object: %s.")
1867
1868 (js2-msg "msg.modify.readonly"
1869 "Cannot modify readonly property: %s.")
1870
1871 ;; TokenStream
1872 (js2-msg "msg.missing.exponent"
1873 "missing exponent")
1874
1875 (js2-msg "msg.caught.nfe"
1876 "number format error")
1877
1878 (js2-msg "msg.unterminated.string.lit"
1879 "unterminated string literal")
1880
1881 (js2-msg "msg.unterminated.comment"
1882 "unterminated comment")
1883
1884 (js2-msg "msg.unterminated.re.lit"
1885 "unterminated regular expression literal")
1886
1887 (js2-msg "msg.invalid.re.flag"
1888 "invalid flag after regular expression")
1889
1890 (js2-msg "msg.no.re.input.for"
1891 "no input for %s")
1892
1893 (js2-msg "msg.illegal.character"
1894 "illegal character")
1895
1896 (js2-msg "msg.invalid.escape"
1897 "invalid Unicode escape sequence")
1898
1899 (js2-msg "msg.bad.namespace"
1900 "not a valid default namespace statement. "
1901 "Syntax is: default xml namespace = EXPRESSION;")
1902
1903 ;; TokensStream warnings
1904 (js2-msg "msg.bad.octal.literal"
1905 "illegal octal literal digit %s; "
1906 "interpreting it as a decimal digit")
1907
1908 (js2-msg "msg.reserved.keyword"
1909 "illegal usage of future reserved keyword %s; "
1910 "interpreting it as ordinary identifier")
1911
1912 (js2-msg "msg.script.is.not.constructor"
1913 "Script objects are not constructors.")
1914
1915 ;; Arrays
1916 (js2-msg "msg.arraylength.bad"
1917 "Inappropriate array length.")
1918
1919 ;; Arrays
1920 (js2-msg "msg.arraylength.too.big"
1921 "Array length %s exceeds supported capacity limit.")
1922
1923 ;; URI
1924 (js2-msg "msg.bad.uri"
1925 "Malformed URI sequence.")
1926
1927 ;; Number
1928 (js2-msg "msg.bad.precision"
1929 "Precision %s out of range.")
1930
1931 ;; NativeGenerator
1932 (js2-msg "msg.send.newborn"
1933 "Attempt to send value to newborn generator")
1934
1935 (js2-msg "msg.already.exec.gen"
1936 "Already executing generator")
1937
1938 (js2-msg "msg.StopIteration.invalid"
1939 "StopIteration may not be changed to an arbitrary object.")
1940
1941 ;; Interpreter
1942 (js2-msg "msg.yield.closing"
1943 "Yield from closing generator")
1944
1945 ;;; Utilities
1946
1947 (defun js2-delete-if (predicate list)
1948 "Remove all items satisfying PREDICATE in LIST."
1949 (loop for item in list
1950 if (not (funcall predicate item))
1951 collect item))
1952
1953 (defun js2-position (element list)
1954 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1955 Returns nil if element is not found in the list."
1956 (let ((count 0)
1957 found)
1958 (while (and list (not found))
1959 (if (eq element (car list))
1960 (setq found t)
1961 (setq count (1+ count)
1962 list (cdr list))))
1963 (if found count)))
1964
1965 (defun js2-find-if (predicate list)
1966 "Find first item satisfying PREDICATE in LIST."
1967 (let (result)
1968 (while (and list (not result))
1969 (if (funcall predicate (car list))
1970 (setq result (car list)))
1971 (setq list (cdr list)))
1972 result))
1973
1974 (defmacro js2-time (form)
1975 "Evaluate FORM, discard result, and return elapsed time in sec"
1976 (declare (debug t))
1977 (let ((beg (make-symbol "--js2-time-beg--"))
1978 (delta (make-symbol "--js2-time-end--")))
1979 `(let ((,beg (current-time))
1980 ,delta)
1981 ,form
1982 (/ (truncate (* (- (float-time (current-time))
1983 (float-time ,beg)))
1984 10000)
1985 10000.0))))
1986
1987 (defsubst js2-same-line (pos)
1988 "Return t if POS is on the same line as current point."
1989 (and (>= pos (point-at-bol))
1990 (<= pos (point-at-eol))))
1991
1992 (defsubst js2-same-line-2 (p1 p2)
1993 "Return t if p1 is on the same line as p2."
1994 (save-excursion
1995 (goto-char p1)
1996 (js2-same-line p2)))
1997
1998 (defun js2-code-bug ()
1999 "Signal an error when we encounter an unexpected code path."
2000 (error "failed assertion"))
2001
2002 ;; I'd like to associate errors with nodes, but for now the
2003 ;; easiest thing to do is get the context info from the last token.
2004 (defsubst js2-record-parse-error (msg &optional arg pos len)
2005 (push (list (list msg arg)
2006 (or pos js2-token-beg)
2007 (or len (- js2-token-end js2-token-beg)))
2008 js2-parsed-errors))
2009
2010 (defsubst js2-report-error (msg &optional msg-arg pos len)
2011 "Signal a syntax error or record a parse error."
2012 (if js2-recover-from-parse-errors
2013 (js2-record-parse-error msg msg-arg pos len)
2014 (signal 'js2-syntax-error
2015 (list msg
2016 js2-ts-lineno
2017 (save-excursion
2018 (goto-char js2-ts-cursor)
2019 (current-column))
2020 js2-ts-hit-eof))))
2021
2022 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2023 (if js2-compiler-report-warning-as-error
2024 (js2-report-error msg msg-arg pos len)
2025 (push (list (list msg msg-arg)
2026 (or pos js2-token-beg)
2027 (or len (- js2-token-end js2-token-beg)))
2028 js2-parsed-warnings)))
2029
2030 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2031 (if js2-compiler-strict-mode
2032 (js2-report-warning msg-id msg-arg beg
2033 (and beg end (- end beg)))))
2034
2035 (put 'js2-syntax-error 'error-conditions
2036 '(error syntax-error js2-syntax-error))
2037 (put 'js2-syntax-error 'error-message "Syntax error")
2038
2039 (put 'js2-parse-error 'error-conditions
2040 '(error parse-error js2-parse-error))
2041 (put 'js2-parse-error 'error-message "Parse error")
2042
2043 (defmacro js2-clear-flag (flags flag)
2044 `(setq ,flags (logand ,flags (lognot ,flag))))
2045
2046 (defmacro js2-set-flag (flags flag)
2047 "Logical-or FLAG into FLAGS."
2048 `(setq ,flags (logior ,flags ,flag)))
2049
2050 (defsubst js2-flag-set-p (flags flag)
2051 (/= 0 (logand flags flag)))
2052
2053 (defsubst js2-flag-not-set-p (flags flag)
2054 (zerop (logand flags flag)))
2055
2056 ;; Stolen shamelessly from James Clark's nxml-mode.
2057 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2058 "Evaluate BODY without any text property changes modifying the buffer.
2059 Any text properties changes happen as usual but the changes are not treated as
2060 modifications to the buffer."
2061 (declare (indent 0) (debug t))
2062 (let ((modified (make-symbol "modified")))
2063 `(let ((,modified (buffer-modified-p))
2064 (inhibit-read-only t)
2065 (inhibit-modification-hooks t)
2066 (buffer-undo-list t)
2067 (deactivate-mark nil)
2068 ;; Apparently these avoid file locking problems.
2069 (buffer-file-name nil)
2070 (buffer-file-truename nil))
2071 (unwind-protect
2072 (progn ,@body)
2073 (unless ,modified
2074 (restore-buffer-modified-p nil))))))
2075
2076 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2077 "Evaluate BODY with the _ character set to be word-syntax."
2078 (declare (indent 0) (debug t))
2079 (let ((old-syntax (make-symbol "old-syntax")))
2080 `(let ((,old-syntax (string (char-syntax ?_))))
2081 (unwind-protect
2082 (progn
2083 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2084 ,@body)
2085 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2086
2087 (defsubst js2-char-uppercase-p (c)
2088 "Return t if C is an uppercase character.
2089 Handles unicode and latin chars properly."
2090 (/= c (downcase c)))
2091
2092 (defsubst js2-char-lowercase-p (c)
2093 "Return t if C is an uppercase character.
2094 Handles unicode and latin chars properly."
2095 (/= c (upcase c)))
2096
2097 ;;; AST struct and function definitions
2098
2099 ;; flags for ast node property 'member-type (used for e4x operators)
2100 (defvar js2-property-flag #x1 "property access: element is valid name")
2101 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2102 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2103
2104 (defsubst js2-relpos (pos anchor)
2105 "Convert POS to be relative to ANCHOR.
2106 If POS is nil, returns nil."
2107 (and pos (- pos anchor)))
2108
2109 (defsubst js2-make-pad (indent)
2110 (if (zerop indent)
2111 ""
2112 (make-string (* indent js2-basic-offset) ? )))
2113
2114 (defsubst js2-visit-ast (node callback)
2115 "Visit every node in ast NODE with visitor CALLBACK.
2116
2117 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2118 called twice: once to visit the node, and again after all the node's
2119 children have been processed. The END-P argument is nil on the first
2120 call and non-nil on the second call. The return value of the callback
2121 affects the traversal: if non-nil, the children of NODE are processed.
2122 If the callback returns nil, or if the node has no children, then the
2123 callback is called immediately with a non-nil END-P argument.
2124
2125 The node traversal is approximately lexical-order, although there
2126 are currently no guarantees around this."
2127 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2128 ;; visit the node
2129 (when (funcall callback node nil)
2130 ;; visit the kids
2131 (cond
2132 ((eq vfunc 'js2-visit-none)
2133 nil) ; don't even bother calling it
2134 ;; Each AST node type has to define a `js2-visitor' function
2135 ;; that takes a node and a callback, and calls `js2-visit-ast'
2136 ;; on each child of the node.
2137 (vfunc
2138 (funcall vfunc node callback))
2139 (t
2140 (error "%s does not define a visitor-traversal function"
2141 (aref node 0)))))
2142 ;; call the end-visit
2143 (funcall callback node t)))
2144
2145 (defstruct (js2-node
2146 (:constructor nil)) ; abstract
2147 "Base AST node type."
2148 (type -1) ; token type
2149 (pos -1) ; start position of this AST node in parsed input
2150 (len 1) ; num characters spanned by the node
2151 props ; optional node property list (an alist)
2152 parent) ; link to parent node; null for root
2153
2154 (defsubst js2-node-get-prop (node prop &optional default)
2155 (or (cadr (assoc prop (js2-node-props node))) default))
2156
2157 (defsubst js2-node-set-prop (node prop value)
2158 (setf (js2-node-props node)
2159 (cons (list prop value) (js2-node-props node))))
2160
2161 (defsubst js2-fixup-starts (n nodes)
2162 "Adjust the start positions of NODES to be relative to N.
2163 Any node in the list may be nil, for convenience."
2164 (dolist (node nodes)
2165 (when node
2166 (setf (js2-node-pos node) (- (js2-node-pos node)
2167 (js2-node-pos n))))))
2168
2169 (defsubst js2-node-add-children (parent &rest nodes)
2170 "Set parent node of NODES to PARENT, and return PARENT.
2171 Does nothing if we're not recording parent links.
2172 If any given node in NODES is nil, doesn't record that link."
2173 (js2-fixup-starts parent nodes)
2174 (dolist (node nodes)
2175 (and node
2176 (setf (js2-node-parent node) parent))))
2177
2178 ;; Non-recursive since it's called a frightening number of times.
2179 (defsubst js2-node-abs-pos (n)
2180 (let ((pos (js2-node-pos n)))
2181 (while (setq n (js2-node-parent n))
2182 (setq pos (+ pos (js2-node-pos n))))
2183 pos))
2184
2185 (defsubst js2-node-abs-end (n)
2186 "Return absolute buffer position of end of N."
2187 (+ (js2-node-abs-pos n) (js2-node-len n)))
2188
2189 ;; It's important to make sure block nodes have a lisp list for the
2190 ;; child nodes, to limit printing recursion depth in an AST that
2191 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2192 ;; a sufficiently large vector tree.
2193
2194 (defstruct (js2-block-node
2195 (:include js2-node)
2196 (:constructor nil)
2197 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2198 (pos js2-token-beg)
2199 len
2200 props
2201 kids)))
2202 "A block of statements."
2203 kids) ; a lisp list of the child statement nodes
2204
2205 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2206 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2207
2208 (defsubst js2-visit-block (ast callback)
2209 "Visit the `js2-block-node' children of AST."
2210 (dolist (kid (js2-block-node-kids ast))
2211 (js2-visit-ast kid callback)))
2212
2213 (defun js2-print-block (n i)
2214 (let ((pad (js2-make-pad i)))
2215 (insert pad "{\n")
2216 (dolist (kid (js2-block-node-kids n))
2217 (js2-print-ast kid (1+ i)))
2218 (insert pad "}")))
2219
2220 (defstruct (js2-scope
2221 (:include js2-block-node)
2222 (:constructor nil)
2223 (:constructor make-js2-scope (&key (type js2-BLOCK)
2224 (pos js2-token-beg)
2225 len
2226 kids)))
2227 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2228 ;; I don't have one of those handy, so I'll use an alist for now.
2229 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2230 ;; and is much lighter-weight to construct (both CPU and mem).
2231 ;; The keys are interned strings (symbols) for faster lookup.
2232 ;; Should switch to hybrid alist/hashtable eventually.
2233 symbol-table ; an alist of (symbol . js2-symbol)
2234 parent-scope ; a `js2-scope'
2235 top) ; top-level `js2-scope' (script/function)
2236
2237 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-none)
2238 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2239
2240 (defun js2-scope-set-parent-scope (scope parent)
2241 (setf (js2-scope-parent-scope scope) parent
2242 (js2-scope-top scope) (if (null parent)
2243 scope
2244 (js2-scope-top parent))))
2245
2246 (defun js2-node-get-enclosing-scope (node)
2247 "Return the innermost `js2-scope' node surrounding NODE.
2248 Returns nil if there is no enclosing scope node."
2249 (let ((parent (js2-node-parent node)))
2250 (while (not (js2-scope-p parent))
2251 (setq parent (js2-node-parent parent)))
2252 parent))
2253
2254 (defun js2-get-defining-scope (scope name)
2255 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2256 Returns `js2-scope' in which NAME is defined, or nil if not found."
2257 (let ((sym (if (symbolp name)
2258 name
2259 (intern name)))
2260 table
2261 result
2262 (continue t))
2263 (while (and scope continue)
2264 (if (and (setq table (js2-scope-symbol-table scope))
2265 (assq sym table))
2266 (setq continue nil
2267 result scope)
2268 (setq scope (js2-scope-parent-scope scope))))
2269 result))
2270
2271 (defsubst js2-scope-get-symbol (scope name)
2272 "Return symbol table entry for NAME in SCOPE.
2273 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2274 (and (js2-scope-symbol-table scope)
2275 (cdr (assq (if (symbolp name)
2276 name
2277 (intern name))
2278 (js2-scope-symbol-table scope)))))
2279
2280 (defsubst js2-scope-put-symbol (scope name symbol)
2281 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2282 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2283 (let* ((table (js2-scope-symbol-table scope))
2284 (sym (if (symbolp name) name (intern name)))
2285 (entry (assq sym table)))
2286 (if entry
2287 (setcdr entry symbol)
2288 (push (cons sym symbol)
2289 (js2-scope-symbol-table scope)))))
2290
2291 (defstruct (js2-symbol
2292 (:constructor nil)
2293 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2294 "A symbol table entry."
2295 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2296 ;; js2-LET, or js2-CONST
2297 decl-type
2298 name ; string
2299 ast-node) ; a `js2-node'
2300
2301 (defstruct (js2-error-node
2302 (:include js2-node)
2303 (:constructor nil) ; silence emacs21 byte-compiler
2304 (:constructor make-js2-error-node (&key (type js2-ERROR)
2305 (pos js2-token-beg)
2306 len)))
2307 "AST node representing a parse error.")
2308
2309 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2310 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2311
2312 (defstruct (js2-script-node
2313 (:include js2-scope)
2314 (:constructor nil)
2315 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2316 (pos js2-token-beg)
2317 len
2318 var-decls
2319 fun-decls)))
2320 functions ; lisp list of nested functions
2321 regexps ; lisp list of (string . flags)
2322 symbols ; alist (every symbol gets unique index)
2323 (param-count 0)
2324 var-names ; vector of string names
2325 consts ; bool-vector matching var-decls
2326 (temp-number 0)) ; for generating temp variables
2327
2328 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2329 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2330
2331 (defun js2-print-script (node indent)
2332 (dolist (kid (js2-block-node-kids node))
2333 (js2-print-ast kid indent)))
2334
2335 (defstruct (js2-ast-root
2336 (:include js2-script-node)
2337 (:constructor nil)
2338 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2339 (pos js2-token-beg)
2340 len
2341 buffer)))
2342 "The root node of a js2 AST."
2343 buffer ; the source buffer from which the code was parsed
2344 comments ; a lisp list of comments, ordered by start position
2345 errors ; a lisp list of errors found during parsing
2346 warnings ; a lisp list of warnings found during parsing
2347 node-count) ; number of nodes in the tree, including the root
2348
2349 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2350 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2351
2352 (defun js2-visit-ast-root (ast callback)
2353 (dolist (kid (js2-ast-root-kids ast))
2354 (js2-visit-ast kid callback))
2355 (dolist (comment (js2-ast-root-comments ast))
2356 (js2-visit-ast comment callback)))
2357
2358 (defstruct (js2-comment-node
2359 (:include js2-node)
2360 (:constructor nil)
2361 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2362 (pos js2-token-beg)
2363 len
2364 (format js2-ts-comment-type))))
2365 format) ; 'line, 'block, 'jsdoc or 'html
2366
2367 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2368 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2369
2370 (defun js2-print-comment (n i)
2371 ;; We really ought to link end-of-line comments to their nodes.
2372 ;; Or maybe we could add a new comment type, 'endline.
2373 (insert (js2-make-pad i)
2374 (js2-node-string n)))
2375
2376 (defstruct (js2-expr-stmt-node
2377 (:include js2-node)
2378 (:constructor nil)
2379 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2380 (pos js2-ts-cursor)
2381 len
2382 expr)))
2383 "An expression statement."
2384 expr)
2385
2386 (defsubst js2-expr-stmt-node-set-has-result (node)
2387 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2388 (setf (js2-node-type node) js2-EXPR_RESULT))
2389
2390 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2391 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2392
2393 (defun js2-visit-expr-stmt-node (n v)
2394 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2395
2396 (defun js2-print-expr-stmt-node (n indent)
2397 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2398 (insert ";\n"))
2399
2400 (defstruct (js2-loop-node
2401 (:include js2-scope)
2402 (:constructor nil))
2403 "Abstract supertype of loop nodes."
2404 body ; a `js2-block-node'
2405 lp ; position of left-paren, nil if omitted
2406 rp) ; position of right-paren, nil if omitted
2407
2408 (defstruct (js2-do-node
2409 (:include js2-loop-node)
2410 (:constructor nil)
2411 (:constructor make-js2-do-node (&key (type js2-DO)
2412 (pos js2-token-beg)
2413 len
2414 body
2415 condition
2416 while-pos
2417 lp
2418 rp)))
2419 "AST node for do-loop."
2420 condition ; while (expression)
2421 while-pos) ; buffer position of 'while' keyword
2422
2423 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2424 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2425
2426 (defun js2-visit-do-node (n v)
2427 (js2-visit-ast (js2-do-node-body n) v)
2428 (js2-visit-ast (js2-do-node-condition n) v))
2429
2430 (defun js2-print-do-node (n i)
2431 (let ((pad (js2-make-pad i)))
2432 (insert pad "do {\n")
2433 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2434 (js2-print-ast kid (1+ i)))
2435 (insert pad "} while (")
2436 (js2-print-ast (js2-do-node-condition n) 0)
2437 (insert ");\n")))
2438
2439 (defstruct (js2-while-node
2440 (:include js2-loop-node)
2441 (:constructor nil)
2442 (:constructor make-js2-while-node (&key (type js2-WHILE)
2443 (pos js2-token-beg)
2444 len
2445 body
2446 condition
2447 lp
2448 rp)))
2449 "AST node for while-loop."
2450 condition) ; while-condition
2451
2452 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2453 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2454
2455 (defun js2-visit-while-node (n v)
2456 (js2-visit-ast (js2-while-node-condition n) v)
2457 (js2-visit-ast (js2-while-node-body n) v))
2458
2459 (defun js2-print-while-node (n i)
2460 (let ((pad (js2-make-pad i)))
2461 (insert pad "while (")
2462 (js2-print-ast (js2-while-node-condition n) 0)
2463 (insert ") {\n")
2464 (js2-print-body (js2-while-node-body n) (1+ i))
2465 (insert pad "}\n")))
2466
2467 (defstruct (js2-for-node
2468 (:include js2-loop-node)
2469 (:constructor nil)
2470 (:constructor make-js2-for-node (&key (type js2-FOR)
2471 (pos js2-ts-cursor)
2472 len
2473 body
2474 init
2475 condition
2476 update
2477 lp
2478 rp)))
2479 "AST node for a C-style for-loop."
2480 init ; initialization expression
2481 condition ; loop condition
2482 update) ; update clause
2483
2484 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2485 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2486
2487 (defun js2-visit-for-node (n v)
2488 (js2-visit-ast (js2-for-node-init n) v)
2489 (js2-visit-ast (js2-for-node-condition n) v)
2490 (js2-visit-ast (js2-for-node-update n) v)
2491 (js2-visit-ast (js2-for-node-body n) v))
2492
2493 (defun js2-print-for-node (n i)
2494 (let ((pad (js2-make-pad i)))
2495 (insert pad "for (")
2496 (js2-print-ast (js2-for-node-init n) 0)
2497 (insert "; ")
2498 (js2-print-ast (js2-for-node-condition n) 0)
2499 (insert "; ")
2500 (js2-print-ast (js2-for-node-update n) 0)
2501 (insert ") {\n")
2502 (js2-print-body (js2-for-node-body n) (1+ i))
2503 (insert pad "}\n")))
2504
2505 (defstruct (js2-for-in-node
2506 (:include js2-loop-node)
2507 (:constructor nil)
2508 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2509 (pos js2-ts-cursor)
2510 len
2511 body
2512 iterator
2513 object
2514 in-pos
2515 each-pos
2516 foreach-p
2517 lp
2518 rp)))
2519 "AST node for a for..in loop."
2520 iterator ; [var] foo in ...
2521 object ; object over which we're iterating
2522 in-pos ; buffer position of 'in' keyword
2523 each-pos ; buffer position of 'each' keyword, if foreach-p
2524 foreach-p) ; t if it's a for-each loop
2525
2526 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2527 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2528
2529 (defun js2-visit-for-in-node (n v)
2530 (js2-visit-ast (js2-for-in-node-iterator n) v)
2531 (js2-visit-ast (js2-for-in-node-object n) v)
2532 (js2-visit-ast (js2-for-in-node-body n) v))
2533
2534 (defun js2-print-for-in-node (n i)
2535 (let ((pad (js2-make-pad i))
2536 (foreach (js2-for-in-node-foreach-p n)))
2537 (insert pad "for ")
2538 (if foreach
2539 (insert "each "))
2540 (insert "(")
2541 (js2-print-ast (js2-for-in-node-iterator n) 0)
2542 (insert " in ")
2543 (js2-print-ast (js2-for-in-node-object n) 0)
2544 (insert ") {\n")
2545 (js2-print-body (js2-for-in-node-body n) (1+ i))
2546 (insert pad "}\n")))
2547
2548 (defstruct (js2-return-node
2549 (:include js2-node)
2550 (:constructor nil)
2551 (:constructor make-js2-return-node (&key (type js2-RETURN)
2552 (pos js2-ts-cursor)
2553 len
2554 retval)))
2555 "AST node for a return statement."
2556 retval) ; expression to return, or 'undefined
2557
2558 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2559 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2560
2561 (defun js2-visit-return-node (n v)
2562 (if (js2-return-node-retval n)
2563 (js2-visit-ast (js2-return-node-retval n) v)))
2564
2565 (defun js2-print-return-node (n i)
2566 (insert (js2-make-pad i) "return")
2567 (when (js2-return-node-retval n)
2568 (insert " ")
2569 (js2-print-ast (js2-return-node-retval n) 0))
2570 (insert ";\n"))
2571
2572 (defstruct (js2-if-node
2573 (:include js2-node)
2574 (:constructor nil)
2575 (:constructor make-js2-if-node (&key (type js2-IF)
2576 (pos js2-ts-cursor)
2577 len
2578 condition
2579 then-part
2580 else-pos
2581 else-part
2582 lp
2583 rp)))
2584 "AST node for an if-statement."
2585 condition ; expression
2586 then-part ; statement or block
2587 else-pos ; optional buffer position of 'else' keyword
2588 else-part ; optional statement or block
2589 lp ; position of left-paren, nil if omitted
2590 rp) ; position of right-paren, nil if omitted
2591
2592 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2593 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2594
2595 (defun js2-visit-if-node (n v)
2596 (js2-visit-ast (js2-if-node-condition n) v)
2597 (js2-visit-ast (js2-if-node-then-part n) v)
2598 (if (js2-if-node-else-part n)
2599 (js2-visit-ast (js2-if-node-else-part n) v)))
2600
2601 (defun js2-print-if-node (n i)
2602 (let ((pad (js2-make-pad i))
2603 (then-part (js2-if-node-then-part n))
2604 (else-part (js2-if-node-else-part n)))
2605 (insert pad "if (")
2606 (js2-print-ast (js2-if-node-condition n) 0)
2607 (insert ") {\n")
2608 (js2-print-body then-part (1+ i))
2609 (insert pad "}")
2610 (cond
2611 ((not else-part)
2612 (insert "\n"))
2613 ((js2-if-node-p else-part)
2614 (insert " else ")
2615 (js2-print-body else-part i))
2616 (t
2617 (insert " else {\n")
2618 (js2-print-body else-part (1+ i))
2619 (insert pad "}\n")))))
2620
2621 (defstruct (js2-try-node
2622 (:include js2-node)
2623 (:constructor nil)
2624 (:constructor make-js2-try-node (&key (type js2-TRY)
2625 (pos js2-ts-cursor)
2626 len
2627 try-block
2628 catch-clauses
2629 finally-block)))
2630 "AST node for a try-statement."
2631 try-block
2632 catch-clauses ; a lisp list of `js2-catch-node'
2633 finally-block) ; a `js2-finally-node'
2634
2635 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2636 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2637
2638 (defun js2-visit-try-node (n v)
2639 (js2-visit-ast (js2-try-node-try-block n) v)
2640 (dolist (clause (js2-try-node-catch-clauses n))
2641 (js2-visit-ast clause v))
2642 (if (js2-try-node-finally-block n)
2643 (js2-visit-ast (js2-try-node-finally-block n) v)))
2644
2645 (defun js2-print-try-node (n i)
2646 (let ((pad (js2-make-pad i))
2647 (catches (js2-try-node-catch-clauses n))
2648 (finally (js2-try-node-finally-block n)))
2649 (insert pad "try {\n")
2650 (js2-print-body (js2-try-node-try-block n) (1+ i))
2651 (insert pad "}")
2652 (when catches
2653 (dolist (catch catches)
2654 (js2-print-ast catch i)))
2655 (if finally
2656 (js2-print-ast finally i)
2657 (insert "\n"))))
2658
2659 (defstruct (js2-catch-node
2660 (:include js2-node)
2661 (:constructor nil)
2662 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2663 (pos js2-ts-cursor)
2664 len
2665 var-name
2666 guard-kwd
2667 guard-expr
2668 block
2669 lp
2670 rp)))
2671 "AST node for a catch clause."
2672 var-name ; a `js2-name-node'
2673 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2674 guard-expr ; catch condition, a `js2-node'
2675 block ; statements, a `js2-block-node'
2676 lp ; buffer position of left-paren, nil if omitted
2677 rp) ; buffer position of right-paren, nil if omitted
2678
2679 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2680 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2681
2682 (defun js2-visit-catch-node (n v)
2683 (js2-visit-ast (js2-catch-node-var-name n) v)
2684 (when (js2-catch-node-guard-kwd n)
2685 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2686 (js2-visit-ast (js2-catch-node-block n) v))
2687
2688 (defun js2-print-catch-node (n i)
2689 (let ((pad (js2-make-pad i))
2690 (guard-kwd (js2-catch-node-guard-kwd n))
2691 (guard-expr (js2-catch-node-guard-expr n)))
2692 (insert " catch (")
2693 (js2-print-ast (js2-catch-node-var-name n) 0)
2694 (when guard-kwd
2695 (insert " if ")
2696 (js2-print-ast guard-expr 0))
2697 (insert ") {\n")
2698 (js2-print-body (js2-catch-node-block n) (1+ i))
2699 (insert pad "}")))
2700
2701 (defstruct (js2-finally-node
2702 (:include js2-node)
2703 (:constructor nil)
2704 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2705 (pos js2-ts-cursor)
2706 len
2707 body)))
2708 "AST node for a finally clause."
2709 body) ; a `js2-node', often but not always a block node
2710
2711 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2712 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2713
2714 (defun js2-visit-finally-node (n v)
2715 (js2-visit-ast (js2-finally-node-body n) v))
2716
2717 (defun js2-print-finally-node (n i)
2718 (let ((pad (js2-make-pad i)))
2719 (insert " finally {\n")
2720 (js2-print-body (js2-finally-node-body n) (1+ i))
2721 (insert pad "}\n")))
2722
2723 (defstruct (js2-switch-node
2724 (:include js2-node)
2725 (:constructor nil)
2726 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2727 (pos js2-ts-cursor)
2728 len
2729 discriminant
2730 cases
2731 lp
2732 rp)))
2733 "AST node for a switch statement."
2734 discriminant ; a `js2-node' (switch expression)
2735 cases ; a lisp list of `js2-case-node'
2736 lp ; position of open-paren for discriminant, nil if omitted
2737 rp) ; position of close-paren for discriminant, nil if omitted
2738
2739 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2740 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2741
2742 (defun js2-visit-switch-node (n v)
2743 (js2-visit-ast (js2-switch-node-discriminant n) v)
2744 (dolist (c (js2-switch-node-cases n))
2745 (js2-visit-ast c v)))
2746
2747 (defun js2-print-switch-node (n i)
2748 (let ((pad (js2-make-pad i))
2749 (cases (js2-switch-node-cases n)))
2750 (insert pad "switch (")
2751 (js2-print-ast (js2-switch-node-discriminant n) 0)
2752 (insert ") {\n")
2753 (dolist (case cases)
2754 (js2-print-ast case i))
2755 (insert pad "}\n")))
2756
2757 (defstruct (js2-case-node
2758 (:include js2-block-node)
2759 (:constructor nil)
2760 (:constructor make-js2-case-node (&key (type js2-CASE)
2761 (pos js2-ts-cursor)
2762 len
2763 kids
2764 expr)))
2765 "AST node for a case clause of a switch statement."
2766 expr) ; the case expression (nil for default)
2767
2768 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2769 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2770
2771 (defun js2-visit-case-node (n v)
2772 (if (js2-case-node-expr n) ; nil for default: case
2773 (js2-visit-ast (js2-case-node-expr n) v))
2774 (js2-visit-block n v))
2775
2776 (defun js2-print-case-node (n i)
2777 (let ((pad (js2-make-pad i))
2778 (expr (js2-case-node-expr n)))
2779 (insert pad)
2780 (if (null expr)
2781 (insert "default:\n")
2782 (insert "case ")
2783 (js2-print-ast expr 0)
2784 (insert ":\n"))
2785 (dolist (kid (js2-case-node-kids n))
2786 (js2-print-ast kid (1+ i)))))
2787
2788 (defstruct (js2-throw-node
2789 (:include js2-node)
2790 (:constructor nil)
2791 (:constructor make-js2-throw-node (&key (type js2-THROW)
2792 (pos js2-ts-cursor)
2793 len
2794 expr)))
2795 "AST node for a throw statement."
2796 expr) ; the expression to throw
2797
2798 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2799 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2800
2801 (defun js2-visit-throw-node (n v)
2802 (js2-visit-ast (js2-throw-node-expr n) v))
2803
2804 (defun js2-print-throw-node (n i)
2805 (insert (js2-make-pad i) "throw ")
2806 (js2-print-ast (js2-throw-node-expr n) 0)
2807 (insert ";\n"))
2808
2809 (defstruct (js2-with-node
2810 (:include js2-node)
2811 (:constructor nil)
2812 (:constructor make-js2-with-node (&key (type js2-WITH)
2813 (pos js2-ts-cursor)
2814 len
2815 object
2816 body
2817 lp
2818 rp)))
2819 "AST node for a with-statement."
2820 object
2821 body
2822 lp ; buffer position of left-paren around object, nil if omitted
2823 rp) ; buffer position of right-paren around object, nil if omitted
2824
2825 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2826 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2827
2828 (defun js2-visit-with-node (n v)
2829 (js2-visit-ast (js2-with-node-object n) v)
2830 (js2-visit-ast (js2-with-node-body n) v))
2831
2832 (defun js2-print-with-node (n i)
2833 (let ((pad (js2-make-pad i)))
2834 (insert pad "with (")
2835 (js2-print-ast (js2-with-node-object n) 0)
2836 (insert ") {\n")
2837 (js2-print-body (js2-with-node-body n) (1+ i))
2838 (insert pad "}\n")))
2839
2840 (defstruct (js2-label-node
2841 (:include js2-node)
2842 (:constructor nil)
2843 (:constructor make-js2-label-node (&key (type js2-LABEL)
2844 (pos js2-ts-cursor)
2845 len
2846 name)))
2847 "AST node for a statement label or case label."
2848 name ; a string
2849 loop) ; for validating and code-generating continue-to-label
2850
2851 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2852 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2853
2854 (defun js2-print-label (n i)
2855 (insert (js2-make-pad i)
2856 (js2-label-node-name n)
2857 ":\n"))
2858
2859 (defstruct (js2-labeled-stmt-node
2860 (:include js2-node)
2861 (:constructor nil)
2862 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2863 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2864 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2865 (pos js2-ts-cursor)
2866 len
2867 labels
2868 stmt)))
2869 "AST node for a statement with one or more labels.
2870 Multiple labels for a statement are collapsed into the labels field."
2871 labels ; lisp list of `js2-label-node'
2872 stmt) ; the statement these labels are for
2873
2874 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2875 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2876
2877 (defun js2-get-label-by-name (lbl-stmt name)
2878 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2879 Returns nil if no such label is in the list."
2880 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2881 result)
2882 (while (and label-list (not result))
2883 (if (string= (js2-label-node-name (car label-list)) name)
2884 (setq result (car label-list))
2885 (setq label-list (cdr label-list))))
2886 result))
2887
2888 (defun js2-visit-labeled-stmt (n v)
2889 (dolist (label (js2-labeled-stmt-node-labels n))
2890 (js2-visit-ast label v))
2891 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2892
2893 (defun js2-print-labeled-stmt (n i)
2894 (dolist (label (js2-labeled-stmt-node-labels n))
2895 (js2-print-ast label i))
2896 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2897
2898 (defun js2-labeled-stmt-node-contains (node label)
2899 "Return t if NODE contains LABEL in its label set.
2900 NODE is a `js2-labels-node'. LABEL is an identifier."
2901 (loop for nl in (js2-labeled-stmt-node-labels node)
2902 if (string= label (js2-label-node-name nl))
2903 return t
2904 finally return nil))
2905
2906 (defsubst js2-labeled-stmt-node-add-label (node label)
2907 "Add a `js2-label-node' to the label set for this statement."
2908 (setf (js2-labeled-stmt-node-labels node)
2909 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2910
2911 (defstruct (js2-jump-node
2912 (:include js2-node)
2913 (:constructor nil))
2914 "Abstract supertype of break and continue nodes."
2915 label ; `js2-name-node' for location of label identifier, if present
2916 target) ; target js2-labels-node or loop/switch statement
2917
2918 (defun js2-visit-jump-node (n v)
2919 ;; we don't visit the target, since it's a back-link
2920 (if (js2-jump-node-label n)
2921 (js2-visit-ast (js2-jump-node-label n) v)))
2922
2923 (defstruct (js2-break-node
2924 (:include js2-jump-node)
2925 (:constructor nil)
2926 (:constructor make-js2-break-node (&key (type js2-BREAK)
2927 (pos js2-ts-cursor)
2928 len
2929 label
2930 target)))
2931 "AST node for a break statement.
2932 The label field is a `js2-name-node', possibly nil, for the named label
2933 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2934 is the target of the break - a label node or enclosing loop/switch statement.")
2935
2936 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2937 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2938
2939 (defun js2-print-break-node (n i)
2940 (insert (js2-make-pad i) "break")
2941 (when (js2-break-node-label n)
2942 (insert " ")
2943 (js2-print-ast (js2-break-node-label n) 0))
2944 (insert ";\n"))
2945
2946 (defstruct (js2-continue-node
2947 (:include js2-jump-node)
2948 (:constructor nil)
2949 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2950 (pos js2-ts-cursor)
2951 len
2952 label
2953 target)))
2954 "AST node for a continue statement.
2955 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2956 It is nil if continue specifies no label. The target field is the jump target:
2957 a `js2-label-node' or the innermost enclosing loop.")
2958
2959 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2960 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2961
2962 (defun js2-print-continue-node (n i)
2963 (insert (js2-make-pad i) "continue")
2964 (when (js2-continue-node-label n)
2965 (insert " ")
2966 (js2-print-ast (js2-continue-node-label n) 0))
2967 (insert ";\n"))
2968
2969 (defstruct (js2-function-node
2970 (:include js2-script-node)
2971 (:constructor nil)
2972 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2973 (pos js2-ts-cursor)
2974 len
2975 (ftype 'FUNCTION)
2976 (form 'FUNCTION_STATEMENT)
2977 (name "")
2978 params
2979 body
2980 lp
2981 rp)))
2982 "AST node for a function declaration.
2983 The `params' field is a lisp list of nodes. Each node is either a simple
2984 `js2-name-node', or if it's a destructuring-assignment parameter, a
2985 `js2-array-node' or `js2-object-node'."
2986 ftype ; FUNCTION, GETTER or SETTER
2987 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2988 name ; function name (a `js2-name-node', or nil if anonymous)
2989 params ; a lisp list of destructuring forms or simple name nodes
2990 body ; a `js2-block-node' or expression node (1.8 only)
2991 lp ; position of arg-list open-paren, or nil if omitted
2992 rp ; position of arg-list close-paren, or nil if omitted
2993 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2994 needs-activation ; t if we need an activation object for this frame
2995 is-generator ; t if this function contains a yield
2996 member-expr) ; nonstandard Ecma extension from Rhino
2997
2998 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2999 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3000
3001 (defun js2-visit-function-node (n v)
3002 (if (js2-function-node-name n)
3003 (js2-visit-ast (js2-function-node-name n) v))
3004 (dolist (p (js2-function-node-params n))
3005 (js2-visit-ast p v))
3006 (js2-visit-ast (js2-function-node-body n) v))
3007
3008 (defun js2-print-function-node (n i)
3009 (let ((pad (js2-make-pad i))
3010 (getter (js2-node-get-prop n 'GETTER_SETTER))
3011 (name (js2-function-node-name n))
3012 (params (js2-function-node-params n))
3013 (body (js2-function-node-body n))
3014 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3015 (unless getter
3016 (insert pad "function"))
3017 (when name
3018 (insert " ")
3019 (js2-print-ast name 0))
3020 (insert "(")
3021 (loop with len = (length params)
3022 for param in params
3023 for count from 1
3024 do
3025 (js2-print-ast param 0)
3026 (if (< count len)
3027 (insert ", ")))
3028 (insert ") {")
3029 (unless expr
3030 (insert "\n"))
3031 ;; TODO: fix this to be smarter about indenting, etc.
3032 (js2-print-body body (1+ i))
3033 (insert pad "}")
3034 (unless expr
3035 (insert "\n"))))
3036
3037 (defsubst js2-function-name (node)
3038 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3039 (and (js2-function-node-name node)
3040 (js2-name-node-name (js2-function-node-name node))))
3041
3042 ;; Having this be an expression node makes it more flexible.
3043 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3044 ;; that work better if you assume it's an expression. Whenever we have
3045 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3046 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3047 (defstruct (js2-var-decl-node
3048 (:include js2-node)
3049 (:constructor nil)
3050 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3051 (pos js2-token-beg)
3052 len
3053 kids
3054 decl-type)))
3055 "AST node for a variable declaration list (VAR, CONST or LET).
3056 The node bounds differ depending on the declaration type. For VAR or
3057 CONST declarations, the bounds include the var/const keyword. For LET
3058 declarations, the node begins at the position of the first child."
3059 kids ; a lisp list of `js2-var-init-node' structs.
3060 decl-type) ; js2-VAR, js2-CONST or js2-LET
3061
3062 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3063 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3064
3065 (defun js2-visit-var-decl (n v)
3066 (dolist (kid (js2-var-decl-node-kids n))
3067 (js2-visit-ast kid v)))
3068
3069 (defun js2-print-var-decl (n i)
3070 (let ((pad (js2-make-pad i))
3071 (tt (js2-var-decl-node-decl-type n)))
3072 (insert pad)
3073 (insert (cond
3074 ((= tt js2-VAR) "var ")
3075 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3076 ((= tt js2-CONST) "const ")
3077 (t
3078 (error "malformed var-decl node"))))
3079 (loop with kids = (js2-var-decl-node-kids n)
3080 with len = (length kids)
3081 for kid in kids
3082 for count from 1
3083 do
3084 (js2-print-ast kid 0)
3085 (if (< count len)
3086 (insert ", ")))))
3087
3088 (defstruct (js2-var-init-node
3089 (:include js2-node)
3090 (:constructor nil)
3091 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3092 (pos js2-ts-cursor)
3093 len
3094 target
3095 initializer)))
3096 "AST node for a variable declaration.
3097 The type field will be js2-CONST for a const decl."
3098 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3099 initializer) ; initializer expression, a `js2-node'
3100
3101 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3102 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3103
3104 (defun js2-visit-var-init-node (n v)
3105 (js2-visit-ast (js2-var-init-node-target n) v)
3106 (if (js2-var-init-node-initializer n)
3107 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3108
3109 (defun js2-print-var-init-node (n i)
3110 (let ((pad (js2-make-pad i))
3111 (name (js2-var-init-node-target n))
3112 (init (js2-var-init-node-initializer n)))
3113 (insert pad)
3114 (js2-print-ast name 0)
3115 (when init
3116 (insert " = ")
3117 (js2-print-ast init 0))))
3118
3119 (defstruct (js2-cond-node
3120 (:include js2-node)
3121 (:constructor nil)
3122 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3123 (pos js2-ts-cursor)
3124 len
3125 test-expr
3126 true-expr
3127 false-expr
3128 q-pos
3129 c-pos)))
3130 "AST node for the ternary operator"
3131 test-expr
3132 true-expr
3133 false-expr
3134 q-pos ; buffer position of ?
3135 c-pos) ; buffer position of :
3136
3137 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3138 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3139
3140 (defun js2-visit-cond-node (n v)
3141 (js2-visit-ast (js2-cond-node-test-expr n) v)
3142 (js2-visit-ast (js2-cond-node-true-expr n) v)
3143 (js2-visit-ast (js2-cond-node-false-expr n) v))
3144
3145 (defun js2-print-cond-node (n i)
3146 (let ((pad (js2-make-pad i)))
3147 (insert pad)
3148 (js2-print-ast (js2-cond-node-test-expr n) 0)
3149 (insert " ? ")
3150 (js2-print-ast (js2-cond-node-true-expr n) 0)
3151 (insert " : ")
3152 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3153
3154 (defstruct (js2-infix-node
3155 (:include js2-node)
3156 (:constructor nil)
3157 (:constructor make-js2-infix-node (&key type
3158 (pos js2-ts-cursor)
3159 len
3160 op-pos
3161 left
3162 right)))
3163 "Represents infix expressions.
3164 Includes assignment ops like `|=', and the comma operator.
3165 The type field inherited from `js2-node' holds the operator."
3166 op-pos ; buffer position where operator begins
3167 left ; any `js2-node'
3168 right) ; any `js2-node'
3169
3170 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3171 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3172
3173 (defun js2-visit-infix-node (n v)
3174 (when (js2-infix-node-left n)
3175 (js2-visit-ast (js2-infix-node-left n) v))
3176 (when (js2-infix-node-right n)
3177 (js2-visit-ast (js2-infix-node-right n) v)))
3178
3179 (defconst js2-operator-tokens
3180 (let ((table (make-hash-table :test 'eq))
3181 (tokens
3182 (list (cons js2-IN "in")
3183 (cons js2-TYPEOF "typeof")
3184 (cons js2-INSTANCEOF "instanceof")
3185 (cons js2-DELPROP "delete")
3186 (cons js2-COMMA ",")
3187 (cons js2-COLON ":")
3188 (cons js2-OR "||")
3189 (cons js2-AND "&&")
3190 (cons js2-INC "++")
3191 (cons js2-DEC "--")
3192 (cons js2-BITOR "|")
3193 (cons js2-BITXOR "^")
3194 (cons js2-BITAND "&")
3195 (cons js2-EQ "==")
3196 (cons js2-NE "!=")
3197 (cons js2-LT "<")
3198 (cons js2-LE "<=")
3199 (cons js2-GT ">")
3200 (cons js2-GE ">=")
3201 (cons js2-LSH "<<")
3202 (cons js2-RSH ">>")
3203 (cons js2-URSH ">>>")
3204 (cons js2-ADD "+") ; infix plus
3205 (cons js2-SUB "-") ; infix minus
3206 (cons js2-MUL "*")
3207 (cons js2-DIV "/")
3208 (cons js2-MOD "%")
3209 (cons js2-NOT "!")
3210 (cons js2-BITNOT "~")
3211 (cons js2-POS "+") ; unary plus
3212 (cons js2-NEG "-") ; unary minus
3213 (cons js2-SHEQ "===") ; shallow equality
3214 (cons js2-SHNE "!==") ; shallow inequality
3215 (cons js2-ASSIGN "=")
3216 (cons js2-ASSIGN_BITOR "|=")
3217 (cons js2-ASSIGN_BITXOR "^=")
3218 (cons js2-ASSIGN_BITAND "&=")
3219 (cons js2-ASSIGN_LSH "<<=")
3220 (cons js2-ASSIGN_RSH ">>=")
3221 (cons js2-ASSIGN_URSH ">>>=")
3222 (cons js2-ASSIGN_ADD "+=")
3223 (cons js2-ASSIGN_SUB "-=")
3224 (cons js2-ASSIGN_MUL "*=")
3225 (cons js2-ASSIGN_DIV "/=")
3226 (cons js2-ASSIGN_MOD "%="))))
3227 (loop for (k . v) in tokens do
3228 (puthash k v table))
3229 table))
3230
3231 (defun js2-print-infix-node (n i)
3232 (let* ((tt (js2-node-type n))
3233 (op (gethash tt js2-operator-tokens)))
3234 (unless op
3235 (error "unrecognized infix operator %s" (js2-node-type n)))
3236 (insert (js2-make-pad i))
3237 (js2-print-ast (js2-infix-node-left n) 0)
3238 (unless (= tt js2-COMMA)
3239 (insert " "))
3240 (insert op)
3241 (insert " ")
3242 (js2-print-ast (js2-infix-node-right n) 0)))
3243
3244 (defstruct (js2-assign-node
3245 (:include js2-infix-node)
3246 (:constructor nil)
3247 (:constructor make-js2-assign-node (&key type
3248 (pos js2-ts-cursor)
3249 len
3250 op-pos
3251 left
3252 right)))
3253 "Represents any assignment.
3254 The type field holds the actual assignment operator.")
3255
3256 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3257 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3258
3259 (defstruct (js2-unary-node
3260 (:include js2-node)
3261 (:constructor nil)
3262 (:constructor make-js2-unary-node (&key type ; required
3263 (pos js2-ts-cursor)
3264 len
3265 operand)))
3266 "AST node type for unary operator nodes.
3267 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3268 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3269 property is added if the operator follows the operand."
3270 operand) ; a `js2-node' expression
3271
3272 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3273 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3274
3275 (defun js2-visit-unary-node (n v)
3276 (js2-visit-ast (js2-unary-node-operand n) v))
3277
3278 (defun js2-print-unary-node (n i)
3279 (let* ((tt (js2-node-type n))
3280 (op (gethash tt js2-operator-tokens))
3281 (postfix (js2-node-get-prop n 'postfix)))
3282 (unless op
3283 (error "unrecognized unary operator %s" tt))
3284 (insert (js2-make-pad i))
3285 (unless postfix
3286 (insert op))
3287 (if (or (= tt js2-TYPEOF)
3288 (= tt js2-DELPROP))
3289 (insert " "))
3290 (js2-print-ast (js2-unary-node-operand n) 0)
3291 (when postfix
3292 (insert op))))
3293
3294 (defstruct (js2-let-node
3295 (:include js2-scope)
3296 (:constructor nil)
3297 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3298 (pos js2-token-beg)
3299 len
3300 vars
3301 body
3302 lp
3303 rp)))
3304 "AST node for a let expression or a let statement.
3305 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3306 vars ; a `js2-var-decl-node'
3307 body ; a `js2-node' representing the expression or body block
3308 lp
3309 rp)
3310
3311 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3312 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3313
3314 (defun js2-visit-let-node (n v)
3315 (when (js2-let-node-vars n)
3316 (js2-visit-ast (js2-let-node-vars n) v))
3317 (when (js2-let-node-body n)
3318 (js2-visit-ast (js2-let-node-body n) v)))
3319
3320 (defun js2-print-let-node (n i)
3321 (insert (js2-make-pad i) "let (")
3322 (js2-print-ast (js2-let-node-vars n) 0)
3323 (insert ") ")
3324 (js2-print-ast (js2-let-node-body n) i))
3325
3326 (defstruct (js2-keyword-node
3327 (:include js2-node)
3328 (:constructor nil)
3329 (:constructor make-js2-keyword-node (&key type
3330 (pos js2-token-beg)
3331 (len (- js2-ts-cursor pos)))))
3332 "AST node representing a literal keyword such as `null'.
3333 Used for `null', `this', `true', `false' and `debugger'.
3334 The node type is set to js2-NULL, js2-THIS, etc.")
3335
3336 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3337 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3338
3339 (defun js2-print-keyword-node (n i)
3340 (insert (js2-make-pad i)
3341 (let ((tt (js2-node-type n)))
3342 (cond
3343 ((= tt 'js2-THIS) "this")
3344 ((= tt 'js2-NULL) "null")
3345 ((= tt 'js2-TRUE) "true")
3346 ((= tt 'js2-FALSE) "false")
3347 ((= tt 'js2-DEBUGGER) "debugger")
3348 (t (error "Invalid keyword literal type: %d" tt))))))
3349
3350 (defsubst js2-this-node-p (node)
3351 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3352 (eq (js2-node-type node) js2-THIS))
3353
3354 (defstruct (js2-new-node
3355 (:include js2-node)
3356 (:constructor nil)
3357 (:constructor make-js2-new-node (&key (type js2-NEW)
3358 (pos js2-token-beg)
3359 len
3360 target
3361 args
3362 initializer
3363 lp
3364 rp)))
3365 "AST node for new-expression such as new Foo()."
3366 target ; an identifier or reference
3367 args ; a lisp list of argument nodes
3368 lp ; position of left-paren, nil if omitted
3369 rp ; position of right-paren, nil if omitted
3370 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3371
3372 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3373 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3374
3375 (defun js2-visit-new-node (n v)
3376 (js2-visit-ast (js2-new-node-target n) v)
3377 (dolist (arg (js2-new-node-args n))
3378 (js2-visit-ast arg v))
3379 (when (js2-new-node-initializer n)
3380 (js2-visit-ast (js2-new-node-initializer n) v)))
3381
3382 (defun js2-print-new-node (n i)
3383 (insert (js2-make-pad i) "new ")
3384 (js2-print-ast (js2-new-node-target n))
3385 (insert "(")
3386 (js2-print-list (js2-new-node-args n))
3387 (insert ")")
3388 (when (js2-new-node-initializer n)
3389 (insert " ")
3390 (js2-print-ast (js2-new-node-initializer n))))
3391
3392 (defstruct (js2-name-node
3393 (:include js2-node)
3394 (:constructor nil)
3395 (:constructor make-js2-name-node (&key (type js2-NAME)
3396 (pos js2-token-beg)
3397 (len (- js2-ts-cursor
3398 js2-token-beg))
3399 (name js2-ts-string))))
3400 "AST node for a JavaScript identifier"
3401 name ; a string
3402 scope) ; a `js2-scope' (optional, used for codegen)
3403
3404 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3405 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3406
3407 (defun js2-print-name-node (n i)
3408 (insert (js2-make-pad i)
3409 (js2-name-node-name n)))
3410
3411 (defsubst js2-name-node-length (node)
3412 "Return identifier length of NODE, a `js2-name-node'.
3413 Returns 0 if NODE is nil or its identifier field is nil."
3414 (if node
3415 (length (js2-name-node-name node))
3416 0))
3417
3418 (defstruct (js2-number-node
3419 (:include js2-node)
3420 (:constructor nil)
3421 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3422 (pos js2-token-beg)
3423 (len (- js2-ts-cursor
3424 js2-token-beg))
3425 (value js2-ts-string)
3426 (num-value js2-ts-number))))
3427 "AST node for a number literal."
3428 value ; the original string, e.g. "6.02e23"
3429 num-value) ; the parsed number value
3430
3431 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3432 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3433
3434 (defun js2-print-number-node (n i)
3435 (insert (js2-make-pad i)
3436 (number-to-string (js2-number-node-value n))))
3437
3438 (defstruct (js2-regexp-node
3439 (:include js2-node)
3440 (:constructor nil)
3441 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3442 (pos js2-token-beg)
3443 (len (- js2-ts-cursor
3444 js2-token-beg))
3445 value
3446 flags)))
3447 "AST node for a regular expression literal."
3448 value ; the regexp string, without // delimiters
3449 flags) ; a string of flags, e.g. `mi'.
3450
3451 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3452 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3453
3454 (defun js2-print-regexp (n i)
3455 (insert (js2-make-pad i)
3456 "/"
3457 (js2-regexp-node-value n)
3458 "/")
3459 (if (js2-regexp-node-flags n)
3460 (insert (js2-regexp-node-flags n))))
3461
3462 (defstruct (js2-string-node
3463 (:include js2-node)
3464 (:constructor nil)
3465 (:constructor make-js2-string-node (&key (type js2-STRING)
3466 (pos js2-token-beg)
3467 (len (- js2-ts-cursor
3468 js2-token-beg))
3469 (value js2-ts-string))))
3470 "String literal.
3471 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3472 You can tell the quote type by looking at the first character."
3473 value) ; the characters of the string, including the quotes
3474
3475 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3476 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3477
3478 (defun js2-print-string-node (n i)
3479 (insert (js2-make-pad i)
3480 (js2-node-string n)))
3481
3482 (defstruct (js2-array-node
3483 (:include js2-node)
3484 (:constructor nil)
3485 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3486 (pos js2-ts-cursor)
3487 len
3488 elems)))
3489 "AST node for an array literal."
3490 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3491
3492 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3493 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3494
3495 (defun js2-visit-array-node (n v)
3496 (dolist (e (js2-array-node-elems n))
3497 (when e ; can be nil, e.g. [a, ,b]
3498 (js2-visit-ast e v))))
3499
3500 (defun js2-print-array-node (n i)
3501 (insert (js2-make-pad i) "[")
3502 (js2-print-list (js2-array-node-elems n))
3503 (insert "]"))
3504
3505 (defstruct (js2-object-node
3506 (:include js2-node)
3507 (:constructor nil)
3508 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3509 (pos js2-ts-cursor)
3510 len
3511 elems)))
3512 "AST node for an object literal expression."
3513 elems) ; a lisp list of `js2-object-prop-node'
3514
3515 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3516 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3517
3518 (defun js2-visit-object-node (n v)
3519 (dolist (e (js2-object-node-elems n))
3520 (js2-visit-ast e v)))
3521
3522 (defun js2-print-object-node (n i)
3523 (insert (js2-make-pad i) "{")
3524 (js2-print-list (js2-object-node-elems n))
3525 (insert "}"))
3526
3527 (defstruct (js2-object-prop-node
3528 (:include js2-infix-node)
3529 (:constructor nil)
3530 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3531 (pos js2-ts-cursor)
3532 len
3533 left
3534 right
3535 op-pos)))
3536 "AST node for an object literal prop:value entry.
3537 The `left' field is the property: a name node, string node or number node.
3538 The `right' field is a `js2-node' representing the initializer value.")
3539
3540 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3541 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3542
3543 (defun js2-print-object-prop-node (n i)
3544 (insert (js2-make-pad i))
3545 (js2-print-ast (js2-object-prop-node-left n) 0)
3546 (insert ":")
3547 (js2-print-ast (js2-object-prop-node-right n) 0))
3548
3549 (defstruct (js2-getter-setter-node
3550 (:include js2-infix-node)
3551 (:constructor nil)
3552 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3553 (pos js2-ts-cursor)
3554 len
3555 left
3556 right)))
3557 "AST node for a getter/setter property in an object literal.
3558 The `left' field is the `js2-name-node' naming the getter/setter prop.
3559 The `right' field is always an anonymous `js2-function-node' with a node
3560 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3561
3562 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3563 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3564
3565 (defun js2-print-getter-setter (n i)
3566 (let ((pad (js2-make-pad i))
3567 (left (js2-getter-setter-node-left n))
3568 (right (js2-getter-setter-node-right n)))
3569 (insert pad)
3570 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3571 (js2-print-ast left 0)
3572 (js2-print-ast right 0)))
3573
3574 (defstruct (js2-prop-get-node
3575 (:include js2-infix-node)
3576 (:constructor nil)
3577 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3578 (pos js2-ts-cursor)
3579 len
3580 left
3581 right)))
3582 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3583
3584 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3585 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3586
3587 (defun js2-visit-prop-get-node (n v)
3588 (when (js2-prop-get-node-left n)
3589 (js2-visit-ast (js2-prop-get-node-left n) v))
3590 (when (js2-prop-get-node-right n)
3591 (js2-visit-ast (js2-prop-get-node-right n) v)))
3592
3593 (defun js2-print-prop-get-node (n i)
3594 (insert (js2-make-pad i))
3595 (js2-print-ast (js2-prop-get-node-left n) 0)
3596 (insert ".")
3597 (js2-print-ast (js2-prop-get-node-right n) 0))
3598
3599 (defstruct (js2-elem-get-node
3600 (:include js2-node)
3601 (:constructor nil)
3602 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3603 (pos js2-ts-cursor)
3604 len
3605 target
3606 element
3607 lb
3608 rb)))
3609 "AST node for an array index expression such as foo[bar]."
3610 target ; a `js2-node' - the expression preceding the "."
3611 element ; a `js2-node' - the expression in brackets
3612 lb ; position of left-bracket, nil if omitted
3613 rb) ; position of right-bracket, nil if omitted
3614
3615 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3616 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3617
3618 (defun js2-visit-elem-get-node (n v)
3619 (when (js2-elem-get-node-target n)
3620 (js2-visit-ast (js2-elem-get-node-target n) v))
3621 (when (js2-elem-get-node-element n)
3622 (js2-visit-ast (js2-elem-get-node-element n) v)))
3623
3624 (defun js2-print-elem-get-node (n i)
3625 (insert (js2-make-pad i))
3626 (js2-print-ast (js2-elem-get-node-target n) 0)
3627 (insert "[")
3628 (js2-print-ast (js2-elem-get-node-element n) 0)
3629 (insert "]"))
3630
3631 (defstruct (js2-call-node
3632 (:include js2-node)
3633 (:constructor nil)
3634 (:constructor make-js2-call-node (&key (type js2-CALL)
3635 (pos js2-ts-cursor)
3636 len
3637 target
3638 args
3639 lp
3640 rp)))
3641 "AST node for a JavaScript function call."
3642 target ; a `js2-node' evaluating to the function to call
3643 args ; a lisp list of `js2-node' arguments
3644 lp ; position of open-paren, or nil if missing
3645 rp) ; position of close-paren, or nil if missing
3646
3647 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3648 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3649
3650 (defun js2-visit-call-node (n v)
3651 (js2-visit-ast (js2-call-node-target n) v)
3652 (dolist (arg (js2-call-node-args n))
3653 (js2-visit-ast arg v)))
3654
3655 (defun js2-print-call-node (n i)
3656 (insert (js2-make-pad i))
3657 (js2-print-ast (js2-call-node-target n) 0)
3658 (insert "(")
3659 (js2-print-list (js2-call-node-args n))
3660 (insert ")"))
3661
3662 (defstruct (js2-yield-node
3663 (:include js2-node)
3664 (:constructor nil)
3665 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3666 (pos js2-ts-cursor)
3667 len
3668 value)))
3669 "AST node for yield statement or expression."
3670 value) ; optional: value to be yielded
3671
3672 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3673 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3674
3675 (defun js2-visit-yield-node (n v)
3676 (js2-visit-ast (js2-yield-node-value n) v))
3677
3678 (defun js2-print-yield-node (n i)
3679 (insert (js2-make-pad i))
3680 (insert "yield")
3681 (when (js2-yield-node-value n)
3682 (insert " ")
3683 (js2-print-ast (js2-yield-node-value n) 0)))
3684
3685 (defstruct (js2-paren-node
3686 (:include js2-node)
3687 (:constructor nil)
3688 (:constructor make-js2-paren-node (&key (type js2-LP)
3689 (pos js2-ts-cursor)
3690 len
3691 expr)))
3692 "AST node for a parenthesized expression.
3693 In particular, used when the parens are syntactically optional,
3694 as opposed to required parens such as those enclosing an if-conditional."
3695 expr) ; `js2-node'
3696
3697 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3698 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3699
3700 (defun js2-visit-paren-node (n v)
3701 (js2-visit-ast (js2-paren-node-expr n) v))
3702
3703 (defun js2-print-paren-node (n i)
3704 (insert (js2-make-pad i))
3705 (insert "(")
3706 (js2-print-ast (js2-paren-node-expr n) 0)
3707 (insert ")"))
3708
3709 (defstruct (js2-array-comp-node
3710 (:include js2-scope)
3711 (:constructor nil)
3712 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3713 (pos js2-ts-cursor)
3714 len
3715 result
3716 loops
3717 filter
3718 if-pos
3719 lp
3720 rp)))
3721 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3722 result ; result expression (just after left-bracket)
3723 loops ; a lisp list of `js2-array-comp-loop-node'
3724 filter ; guard/filter expression
3725 if-pos ; buffer pos of 'if' keyword, if present, else nil
3726 lp ; buffer position of if-guard left-paren, or nil if not present
3727 rp) ; buffer position of if-guard right-paren, or nil if not present
3728
3729 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3730 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3731
3732 (defun js2-visit-array-comp-node (n v)
3733 (js2-visit-ast (js2-array-comp-node-result n) v)
3734 (dolist (l (js2-array-comp-node-loops n))
3735 (js2-visit-ast l v))
3736 (if (js2-array-comp-node-filter n)
3737 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3738
3739 (defun js2-print-array-comp-node (n i)
3740 (let ((pad (js2-make-pad i))
3741 (result (js2-array-comp-node-result n))
3742 (loops (js2-array-comp-node-loops n))
3743 (filter (js2-array-comp-node-filter n)))
3744 (insert pad "[")
3745 (js2-print-ast result 0)
3746 (dolist (l loops)
3747 (insert " ")
3748 (js2-print-ast l 0))
3749 (when filter
3750 (insert " if (")
3751 (js2-print-ast filter 0))
3752 (insert ")]")))
3753
3754 (defstruct (js2-array-comp-loop-node
3755 (:include js2-for-in-node)
3756 (:constructor nil)
3757 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3758 (pos js2-ts-cursor)
3759 len
3760 iterator
3761 object
3762 in-pos
3763 foreach-p
3764 each-pos
3765 lp
3766 rp)))
3767 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3768
3769 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3770 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3771
3772 (defun js2-visit-array-comp-loop (n v)
3773 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3774 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3775
3776 (defun js2-print-array-comp-loop (n i)
3777 (insert "for (")
3778 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3779 (insert " in ")
3780 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3781 (insert ")"))
3782
3783 (defstruct (js2-empty-expr-node
3784 (:include js2-node)
3785 (:constructor nil)
3786 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3787 (pos js2-token-beg)
3788 len)))
3789 "AST node for an empty expression.")
3790
3791 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3792 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3793
3794 (defstruct (js2-xml-node
3795 (:include js2-block-node)
3796 (:constructor nil)
3797 (:constructor make-js2-xml-node (&key (type js2-XML)
3798 (pos js2-token-beg)
3799 len
3800 kids)))
3801 "AST node for initial parse of E4X literals.
3802 The kids field is a list of XML fragments, each a `js2-string-node' or
3803 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3804
3805 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3806 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3807
3808 (defun js2-print-xml-node (n i)
3809 (dolist (kid (js2-xml-node-kids n))
3810 (js2-print-ast kid i)))
3811
3812 (defstruct (js2-xml-js-expr-node
3813 (:include js2-xml-node)
3814 (:constructor nil)
3815 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3816 (pos js2-ts-cursor)
3817 len
3818 expr)))
3819 "AST node for an embedded JavaScript {expression} in an E4X literal.
3820 The start and end fields correspond to the curly-braces."
3821 expr) ; a `js2-expr-node' of some sort
3822
3823 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3824 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3825
3826 (defun js2-visit-xml-js-expr (n v)
3827 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3828
3829 (defun js2-print-xml-js-expr (n i)
3830 (insert (js2-make-pad i))
3831 (insert "{")
3832 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3833 (insert "}"))
3834
3835 (defstruct (js2-xml-dot-query-node
3836 (:include js2-infix-node)
3837 (:constructor nil)
3838 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3839 (pos js2-ts-cursor)
3840 op-pos
3841 len
3842 left
3843 right
3844 rp)))
3845 "AST node for an E4X foo.(bar) filter expression.
3846 Note that the left-paren is automatically the character immediately
3847 following the dot (.) in the operator. No whitespace is permitted
3848 between the dot and the lp by the scanner."
3849 rp)
3850
3851 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3852 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3853
3854 (defun js2-print-xml-dot-query (n i)
3855 (insert (js2-make-pad i))
3856 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3857 (insert ".(")
3858 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3859 (insert ")"))
3860
3861 (defstruct (js2-xml-ref-node
3862 (:include js2-node)
3863 (:constructor nil)) ; abstract
3864 "Base type for E4X XML attribute-access or property-get expressions.
3865 Such expressions can take a variety of forms. The general syntax has
3866 three parts:
3867
3868 - (optional) an @ (specifying an attribute access)
3869 - (optional) a namespace (a `js2-name-node') and double-colon
3870 - (required) either a `js2-name-node' or a bracketed [expression]
3871
3872 The property-name expressions (examples: ns::name, @name) are
3873 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3874 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3875
3876 This node type (or more specifically, its subclasses) will sometimes
3877 be the right-hand child of a `js2-prop-get-node' or a
3878 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3879 The `js2-xml-ref-node' may also be a standalone primary expression with
3880 no explicit target, which is valid in certain expression contexts such as
3881
3882 company..employee.(@id < 100)
3883
3884 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3885 expression whose parent is a `js2-xml-dot-query-node'."
3886 namespace
3887 at-pos
3888 colon-pos)
3889
3890 (defsubst js2-xml-ref-node-attr-access-p (node)
3891 "Return non-nil if this expression began with an @-token."
3892 (and (numberp (js2-xml-ref-node-at-pos node))
3893 (plusp (js2-xml-ref-node-at-pos node))))
3894
3895 (defstruct (js2-xml-prop-ref-node
3896 (:include js2-xml-ref-node)
3897 (:constructor nil)
3898 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3899 (pos js2-token-beg)
3900 len
3901 propname
3902 namespace
3903 at-pos
3904 colon-pos)))
3905 "AST node for an E4X XML [expr] property-ref expression.
3906 The JavaScript syntax is an optional @, an optional ns::, and a name.
3907
3908 [ '@' ] [ name '::' ] name
3909
3910 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3911 @ns::*, @*::attr, @*::*, and @*.
3912
3913 The node starts at the @ token, if present. Otherwise it starts at the
3914 namespace name. The node bounds extend through the closing right-bracket,
3915 or if it is missing due to a syntax error, through the end of the index
3916 expression."
3917 propname)
3918
3919 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3920 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3921
3922 (defun js2-visit-xml-prop-ref-node (n v)
3923 (if (js2-xml-prop-ref-node-namespace n)
3924 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3925 (if (js2-xml-prop-ref-node-propname n)
3926 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3927
3928 (defun js2-print-xml-prop-ref-node (n i)
3929 (insert (js2-make-pad i))
3930 (if (js2-xml-ref-node-attr-access-p n)
3931 (insert "@"))
3932 (when (js2-xml-prop-ref-node-namespace n)
3933 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3934 (insert "::"))
3935 (if (js2-xml-prop-ref-node-propname n)
3936 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3937
3938 (defstruct (js2-xml-elem-ref-node
3939 (:include js2-xml-ref-node)
3940 (:constructor nil)
3941 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3942 (pos js2-token-beg)
3943 len
3944 expr
3945 lb
3946 rb
3947 namespace
3948 at-pos
3949 colon-pos)))
3950 "AST node for an E4X XML [expr] member-ref expression.
3951 Syntax:
3952
3953 [ '@' ] [ name '::' ] '[' expr ']'
3954
3955 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3956
3957 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3958 is not a legal E4X XML element-ref expression, since it's already used
3959 for standard JavaScript element-get array indexing. Hence, a
3960 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3961 non-nil namespace node, or both.
3962
3963 The node starts at the @ token, if present. Otherwise it starts
3964 at the namespace name. The node bounds extend through the closing
3965 right-bracket, or if it is missing due to a syntax error, through the
3966 end of the index expression."
3967 expr ; the bracketed index expression
3968 lb
3969 rb)
3970
3971 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3972 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3973
3974 (defun js2-visit-xml-elem-ref-node (n v)
3975 (if (js2-xml-elem-ref-node-namespace n)
3976 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
3977 (if (js2-xml-elem-ref-node-expr n)
3978 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
3979
3980 (defun js2-print-xml-elem-ref-node (n i)
3981 (insert (js2-make-pad i))
3982 (if (js2-xml-ref-node-attr-access-p n)
3983 (insert "@"))
3984 (when (js2-xml-elem-ref-node-namespace n)
3985 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3986 (insert "::"))
3987 (insert "[")
3988 (if (js2-xml-elem-ref-node-expr n)
3989 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3990 (insert "]"))
3991
3992 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3993
3994 (defstruct (js2-xml-start-tag-node
3995 (:include js2-xml-node)
3996 (:constructor nil)
3997 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3998 (pos js2-ts-cursor)
3999 len
4000 name
4001 attrs
4002 kids
4003 empty-p)))
4004 "AST node for an XML start-tag. Not currently used.
4005 The `kids' field is a lisp list of child content nodes."
4006 name ; a `js2-xml-name-node'
4007 attrs ; a lisp list of `js2-xml-attr-node'
4008 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4009
4010 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4011 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4012
4013 (defun js2-visit-xml-start-tag (n v)
4014 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4015 (dolist (attr (js2-xml-start-tag-node-attrs n))
4016 (js2-visit-ast attr v))
4017 (js2-visit-block n v))
4018
4019 (defun js2-print-xml-start-tag (n i)
4020 (insert (js2-make-pad i) "<")
4021 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4022 (when (js2-xml-start-tag-node-attrs n)
4023 (insert " ")
4024 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4025 (insert ">"))
4026
4027 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4028 ;; and add the end-tag to the kids list of the parent as well.
4029 (defstruct (js2-xml-end-tag-node
4030 (:include js2-xml-node)
4031 (:constructor nil)
4032 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4033 (pos js2-ts-cursor)
4034 len
4035 name)))
4036 "AST node for an XML end-tag. Not currently used."
4037 name) ; a `js2-xml-name-node'
4038
4039 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4040 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4041
4042 (defun js2-visit-xml-end-tag (n v)
4043 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4044
4045 (defun js2-print-xml-end-tag (n i)
4046 (insert (js2-make-pad i))
4047 (insert "</")
4048 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4049 (insert ">"))
4050
4051 (defstruct (js2-xml-name-node
4052 (:include js2-xml-node)
4053 (:constructor nil)
4054 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4055 (pos js2-ts-cursor)
4056 len
4057 namespace
4058 kids)))
4059 "AST node for an E4X XML name. Not currently used.
4060 Any XML name can be qualified with a namespace, hence the namespace field.
4061 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4062 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4063 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4064 namespace) ; a `js2-string-node'
4065
4066 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4067 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4068
4069 (defun js2-visit-xml-name-node (n v)
4070 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4071
4072 (defun js2-print-xml-name-node (n i)
4073 (insert (js2-make-pad i))
4074 (when (js2-xml-name-node-namespace n)
4075 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4076 (insert "::"))
4077 (dolist (kid (js2-xml-name-node-kids n))
4078 (js2-print-ast kid 0)))
4079
4080 (defstruct (js2-xml-pi-node
4081 (:include js2-xml-node)
4082 (:constructor nil)
4083 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4084 (pos js2-ts-cursor)
4085 len
4086 name
4087 attrs)))
4088 "AST node for an E4X XML processing instruction. Not currently used."
4089 name ; a `js2-xml-name-node'
4090 attrs) ; a list of `js2-xml-attr-node'
4091
4092 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4093 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4094
4095 (defun js2-visit-xml-pi-node (n v)
4096 (js2-visit-ast (js2-xml-pi-node-name n) v)
4097 (dolist (attr (js2-xml-pi-node-attrs n))
4098 (js2-visit-ast attr v)))
4099
4100 (defun js2-print-xml-pi-node (n i)
4101 (insert (js2-make-pad i) "<?")
4102 (js2-print-ast (js2-xml-pi-node-name n))
4103 (when (js2-xml-pi-node-attrs n)
4104 (insert " ")
4105 (js2-print-list (js2-xml-pi-node-attrs n)))
4106 (insert "?>"))
4107
4108 (defstruct (js2-xml-cdata-node
4109 (:include js2-xml-node)
4110 (:constructor nil)
4111 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4112 (pos js2-ts-cursor)
4113 len
4114 content)))
4115 "AST node for a CDATA escape section. Not currently used."
4116 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4117
4118 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4119 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4120
4121 (defun js2-visit-xml-cdata-node (n v)
4122 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4123
4124 (defun js2-print-xml-cdata-node (n i)
4125 (insert (js2-make-pad i))
4126 (js2-print-ast (js2-xml-cdata-node-content n)))
4127
4128 (defstruct (js2-xml-attr-node
4129 (:include js2-xml-node)
4130 (:constructor nil)
4131 (:constructor make-js2-attr-node (&key (type js2-XML)
4132 (pos js2-ts-cursor)
4133 len
4134 name
4135 value
4136 eq-pos
4137 quote-type)))
4138 "AST node representing a foo='bar' XML attribute value. Not yet used."
4139 name ; a `js2-xml-name-node'
4140 value ; a `js2-xml-name-node'
4141 eq-pos ; buffer position of "=" sign
4142 quote-type) ; 'single or 'double
4143
4144 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4145 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4146
4147 (defun js2-visit-xml-attr-node (n v)
4148 (js2-visit-ast (js2-xml-attr-node-name n) v)
4149 (js2-visit-ast (js2-xml-attr-node-value n) v))
4150
4151 (defun js2-print-xml-attr-node (n i)
4152 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4153 "'"
4154 "\"")))
4155 (insert (js2-make-pad i))
4156 (js2-print-ast (js2-xml-attr-node-name n) 0)
4157 (insert "=" quote)
4158 (js2-print-ast (js2-xml-attr-node-value n) 0)
4159 (insert quote)))
4160
4161 (defstruct (js2-xml-text-node
4162 (:include js2-xml-node)
4163 (:constructor nil)
4164 (:constructor make-js2-text-node (&key (type js2-XML)
4165 (pos js2-ts-cursor)
4166 len
4167 content)))
4168 "AST node for an E4X XML text node. Not currently used."
4169 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4170
4171 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4172 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4173
4174 (defun js2-visit-xml-text-node (n v)
4175 (js2-visit-ast (js2-xml-text-node-content n) v))
4176
4177 (defun js2-print-xml-text-node (n i)
4178 (insert (js2-make-pad i))
4179 (dolist (kid (js2-xml-text-node-content n))
4180 (js2-print-ast kid)))
4181
4182 (defstruct (js2-xml-comment-node
4183 (:include js2-xml-node)
4184 (:constructor nil)
4185 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4186 (pos js2-ts-cursor)
4187 len)))
4188 "AST node for E4X XML comment. Not currently used.")
4189
4190 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4191 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4192
4193 (defun js2-print-xml-comment (n i)
4194 (insert (js2-make-pad i)
4195 (js2-node-string n)))
4196
4197 ;;; Node utilities
4198
4199 (defsubst js2-node-line (n)
4200 "Fetch the source line number at the start of node N.
4201 This is O(n) in the length of the source buffer; use prudently."
4202 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4203
4204 (defsubst js2-block-node-kid (n i)
4205 "Return child I of node N, or nil if there aren't that many."
4206 (nth i (js2-block-node-kids n)))
4207
4208 (defsubst js2-block-node-first (n)
4209 "Return first child of block node N, or nil if there is none."
4210 (first (js2-block-node-kids n)))
4211
4212 (defun js2-node-root (n)
4213 "Return the root of the AST containing N.
4214 If N has no parent pointer, returns N."
4215 (let ((parent (js2-node-parent n)))
4216 (if parent
4217 (js2-node-root parent)
4218 n)))
4219
4220 (defun js2-node-position-in-parent (node &optional parent)
4221 "Return the position of NODE in parent's block-kids list.
4222 PARENT can be supplied if known. Positioned returned is zero-indexed.
4223 Returns 0 if NODE is not a child of a block statement, or if NODE
4224 is not a statement node."
4225 (let ((p (or parent (js2-node-parent node)))
4226 (i 0))
4227 (if (not (js2-block-node-p p))
4228 i
4229 (or (js2-position node (js2-block-node-kids p))
4230 0))))
4231
4232 (defsubst js2-node-short-name (n)
4233 "Return the short name of node N as a string, e.g. `js2-if-node'."
4234 (substring (symbol-name (aref n 0))
4235 (length "cl-struct-")))
4236
4237 (defsubst js2-node-child-list (node)
4238 "Return the child list for NODE, a lisp list of nodes.
4239 Works for block nodes, array nodes, obj literals, funarg lists,
4240 var decls and try nodes (for catch clauses). Note that you should call
4241 `js2-block-node-kids' on the function body for the body statements.
4242 Returns nil for zero-length child lists or unsupported nodes."
4243 (cond
4244 ((js2-function-node-p node)
4245 (js2-function-node-params node))
4246 ((js2-block-node-p node)
4247 (js2-block-node-kids node))
4248 ((js2-try-node-p node)
4249 (js2-try-node-catch-clauses node))
4250 ((js2-array-node-p node)
4251 (js2-array-node-elems node))
4252 ((js2-object-node-p node)
4253 (js2-object-node-elems node))
4254 ((js2-call-node-p node)
4255 (js2-call-node-args node))
4256 ((js2-new-node-p node)
4257 (js2-new-node-args node))
4258 ((js2-var-decl-node-p node)
4259 (js2-var-decl-node-kids node))
4260 (t
4261 nil)))
4262
4263 (defsubst js2-node-set-child-list (node kids)
4264 "Set the child list for NODE to KIDS."
4265 (cond
4266 ((js2-function-node-p node)
4267 (setf (js2-function-node-params node) kids))
4268 ((js2-block-node-p node)
4269 (setf (js2-block-node-kids node) kids))
4270 ((js2-try-node-p node)
4271 (setf (js2-try-node-catch-clauses node) kids))
4272 ((js2-array-node-p node)
4273 (setf (js2-array-node-elems node) kids))
4274 ((js2-object-node-p node)
4275 (setf (js2-object-node-elems node) kids))
4276 ((js2-call-node-p node)
4277 (setf (js2-call-node-args node) kids))
4278 ((js2-new-node-p node)
4279 (setf (js2-new-node-args node) kids))
4280 ((js2-var-decl-node-p node)
4281 (setf (js2-var-decl-node-kids node) kids))
4282 (t
4283 (error "Unsupported node type: %s" (js2-node-short-name node))))
4284 kids)
4285
4286 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4287 (defconst js2-paren-expr-nodes
4288 '(cl-struct-js2-array-comp-loop-node
4289 cl-struct-js2-array-comp-node
4290 cl-struct-js2-call-node
4291 cl-struct-js2-catch-node
4292 cl-struct-js2-do-node
4293 cl-struct-js2-elem-get-node
4294 cl-struct-js2-for-in-node
4295 cl-struct-js2-for-node
4296 cl-struct-js2-function-node
4297 cl-struct-js2-if-node
4298 cl-struct-js2-let-node
4299 cl-struct-js2-new-node
4300 cl-struct-js2-paren-node
4301 cl-struct-js2-switch-node
4302 cl-struct-js2-while-node
4303 cl-struct-js2-with-node
4304 cl-struct-js2-xml-dot-query-node)
4305 "Node types that can have a parenthesized child expression.
4306 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4307
4308 (defsubst js2-paren-expr-node-p (node)
4309 "Return t for nodes that typically have a parenthesized child expression.
4310 Useful for computing the indentation anchors for arg-lists and conditions.
4311 Note that it may return a false positive, for instance when NODE is
4312 a `js2-new-node' and there are no arguments or parentheses."
4313 (memq (aref node 0) js2-paren-expr-nodes))
4314
4315 ;; Fake polymorphism... yech.
4316 (defsubst js2-node-lp (node)
4317 "Return relative left-paren position for NODE, if applicable.
4318 For `js2-elem-get-node' structs, returns left-bracket position.
4319 Note that the position may be nil in the case of a parse error."
4320 (cond
4321 ((js2-elem-get-node-p node)
4322 (js2-elem-get-node-lb node))
4323 ((js2-loop-node-p node)
4324 (js2-loop-node-lp node))
4325 ((js2-function-node-p node)
4326 (js2-function-node-lp node))
4327 ((js2-if-node-p node)
4328 (js2-if-node-lp node))
4329 ((js2-new-node-p node)
4330 (js2-new-node-lp node))
4331 ((js2-call-node-p node)
4332 (js2-call-node-lp node))
4333 ((js2-paren-node-p node)
4334 (js2-node-pos node))
4335 ((js2-switch-node-p node)
4336 (js2-switch-node-lp node))
4337 ((js2-catch-node-p node)
4338 (js2-catch-node-lp node))
4339 ((js2-let-node-p node)
4340 (js2-let-node-lp node))
4341 ((js2-array-comp-node-p node)
4342 (js2-array-comp-node-lp node))
4343 ((js2-with-node-p node)
4344 (js2-with-node-lp node))
4345 ((js2-xml-dot-query-node-p node)
4346 (1+ (js2-infix-node-op-pos node)))
4347 (t
4348 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4349
4350 ;; Fake polymorphism... blech.
4351 (defsubst js2-node-rp (node)
4352 "Return relative right-paren position for NODE, if applicable.
4353 For `js2-elem-get-node' structs, returns right-bracket position.
4354 Note that the position may be nil in the case of a parse error."
4355 (cond
4356 ((js2-elem-get-node-p node)
4357 (js2-elem-get-node-lb node))
4358 ((js2-loop-node-p node)
4359 (js2-loop-node-rp node))
4360 ((js2-function-node-p node)
4361 (js2-function-node-rp node))
4362 ((js2-if-node-p node)
4363 (js2-if-node-rp node))
4364 ((js2-new-node-p node)
4365 (js2-new-node-rp node))
4366 ((js2-call-node-p node)
4367 (js2-call-node-rp node))
4368 ((js2-paren-node-p node)
4369 (+ (js2-node-pos node) (js2-node-len node)))
4370 ((js2-switch-node-p node)
4371 (js2-switch-node-rp node))
4372 ((js2-catch-node-p node)
4373 (js2-catch-node-rp node))
4374 ((js2-let-node-p node)
4375 (js2-let-node-rp node))
4376 ((js2-array-comp-node-p node)
4377 (js2-array-comp-node-rp node))
4378 ((js2-with-node-p node)
4379 (js2-with-node-rp node))
4380 ((js2-xml-dot-query-node-p node)
4381 (1+ (js2-xml-dot-query-node-rp node)))
4382 (t
4383 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4384
4385 (defsubst js2-node-first-child (node)
4386 "Returns the first element of `js2-node-child-list' for NODE."
4387 (car (js2-node-child-list node)))
4388
4389 (defsubst js2-node-last-child (node)
4390 "Returns the last element of `js2-node-last-child' for NODE."
4391 (car (last (js2-node-child-list node))))
4392
4393 (defun js2-node-prev-sibling (node)
4394 "Return the previous statement in parent.
4395 Works for parents supported by `js2-node-child-list'.
4396 Returns nil if NODE is not in the parent, or PARENT is
4397 not a supported node, or if NODE is the first child."
4398 (let* ((p (js2-node-parent node))
4399 (kids (js2-node-child-list p))
4400 (sib (car kids)))
4401 (while (and kids
4402 (not (eq node (cadr kids))))
4403 (setq kids (cdr kids)
4404 sib (car kids)))
4405 sib))
4406
4407 (defun js2-node-next-sibling (node)
4408 "Return the next statement in parent block.
4409 Returns nil if NODE is not in the block, or PARENT is not
4410 a block node, or if NODE is the last statement."
4411 (let* ((p (js2-node-parent node))
4412 (kids (js2-node-child-list p)))
4413 (while (and kids
4414 (not (eq node (car kids))))
4415 (setq kids (cdr kids)))
4416 (cadr kids)))
4417
4418 (defun js2-node-find-child-before (pos parent &optional after)
4419 "Find the last child that starts before POS in parent.
4420 If AFTER is non-nil, returns first child starting after POS.
4421 POS is an absolute buffer position. PARENT is any node
4422 supported by `js2-node-child-list'.
4423 Returns nil if no applicable child is found."
4424 (let ((kids (if (js2-function-node-p parent)
4425 (js2-block-node-kids (js2-function-node-body parent))
4426 (js2-node-child-list parent)))
4427 (beg (if (js2-function-node-p parent)
4428 (js2-node-abs-pos (js2-function-node-body parent))
4429 (js2-node-abs-pos parent)))
4430 kid
4431 result
4432 fn
4433 (continue t))
4434 (setq fn (if after '> '<))
4435 (while (and kids continue)
4436 (setq kid (car kids))
4437 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4438 (setq result kid
4439 continue (if after nil t))
4440 (setq continue (if after t nil)))
4441 (setq kids (cdr kids)))
4442 result))
4443
4444 (defun js2-node-find-child-after (pos parent)
4445 "Find first child that starts after POS in parent.
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 (js2-node-find-child-before pos parent 'after))
4450
4451 (defun js2-node-replace-child (pos parent new-node)
4452 "Replace node at index POS in PARENT with NEW-NODE.
4453 Only works for parents supported by `js2-node-child-list'."
4454 (let ((kids (js2-node-child-list parent))
4455 (i 0))
4456 (while (< i pos)
4457 (setq kids (cdr kids)
4458 i (1+ i)))
4459 (setcar kids new-node)
4460 (js2-node-add-children parent new-node)))
4461
4462 (defun js2-node-buffer (n)
4463 "Return the buffer associated with AST N.
4464 Returns nil if the buffer is not set as a property on the root
4465 node, or if parent links were not recorded during parsing."
4466 (let ((root (js2-node-root n)))
4467 (and root
4468 (js2-ast-root-p root)
4469 (js2-ast-root-buffer root))))
4470
4471 (defsubst js2-block-node-push (n kid)
4472 "Push js2-node KID onto the end of js2-block-node N's child list.
4473 KID is always added to the -end- of the kids list.
4474 Function also calls `js2-node-add-children' to add the parent link."
4475 (let ((kids (js2-node-child-list n)))
4476 (if kids
4477 (setcdr kids (nconc (cdr kids) (list kid)))
4478 (js2-node-set-child-list n (list kid)))
4479 (js2-node-add-children n kid)))
4480
4481 (defun js2-node-string (node)
4482 (let ((buf (js2-node-buffer node))
4483 pos)
4484 (unless buf
4485 (error "No buffer available for node %s" node))
4486 (save-excursion
4487 (set-buffer buf)
4488 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4489 (+ pos (js2-node-len node))))))
4490
4491 ;; Container for storing the node we're looking for in a traversal.
4492 (js2-deflocal js2-discovered-node nil)
4493
4494 ;; Keep track of absolute node position during traversals.
4495 (js2-deflocal js2-visitor-offset nil)
4496
4497 (js2-deflocal js2-node-search-point nil)
4498
4499 (when js2-mode-dev-mode-p
4500 (defun js2-find-node-at-point ()
4501 (interactive)
4502 (let ((node (js2-node-at-point)))
4503 (message "%s" (or node "No node found at point"))))
4504 (defun js2-node-name-at-point ()
4505 (interactive)
4506 (let ((node (js2-node-at-point)))
4507 (message "%s" (if node
4508 (js2-node-short-name node)
4509 "No node found at point.")))))
4510
4511 (defun js2-node-at-point (&optional pos skip-comments)
4512 "Return AST node at POS, a buffer position, defaulting to current point.
4513 The `js2-mode-ast' variable must be set to the current parse tree.
4514 Signals an error if the AST (`js2-mode-ast') is nil.
4515 Always returns a node - if it can't find one, it returns the root.
4516 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4517 (let ((ast js2-mode-ast)
4518 result)
4519 (unless ast
4520 (error "No JavaScript AST available"))
4521 ;; Look through comments first, since they may be inside nodes that
4522 ;; would otherwise report a match.
4523 (setq pos (or pos (point))
4524 result (if (> pos (js2-node-abs-end ast))
4525 ast
4526 (if (not skip-comments)
4527 (js2-comment-at-point pos))))
4528 (unless result
4529 (setq js2-discovered-node nil
4530 js2-visitor-offset 0
4531 js2-node-search-point pos)
4532 (unwind-protect
4533 (catch 'js2-visit-done
4534 (js2-visit-ast ast #'js2-node-at-point-visitor))
4535 (setq js2-visitor-offset nil
4536 js2-node-search-point nil))
4537 (setq result js2-discovered-node))
4538 ;; may have found a comment beyond end of last child node,
4539 ;; since visiting the ast-root looks at the comment-list last.
4540 (if (and skip-comments
4541 (js2-comment-node-p result))
4542 (setq result nil))
4543 (or result js2-mode-ast)))
4544
4545 (defun js2-node-at-point-visitor (node end-p)
4546 (let ((rel-pos (js2-node-pos node))
4547 abs-pos
4548 abs-end
4549 (point js2-node-search-point))
4550 (cond
4551 (end-p
4552 ;; this evaluates to a non-nil return value, even if it's zero
4553 (decf js2-visitor-offset rel-pos))
4554 ;; we already looked for comments before visiting, and don't want them now
4555 ((js2-comment-node-p node)
4556 nil)
4557 (t
4558 (setq abs-pos (incf js2-visitor-offset rel-pos)
4559 ;; we only want to use the node if the point is before
4560 ;; the last character position in the node, so we decrement
4561 ;; the absolute end by 1.
4562 abs-end (+ abs-pos (js2-node-len node) -1))
4563 (cond
4564 ;; If this node starts after search-point, stop the search.
4565 ((> abs-pos point)
4566 (throw 'js2-visit-done nil))
4567 ;; If this node ends before the search-point, don't check kids.
4568 ((> point abs-end)
4569 nil)
4570 (t
4571 ;; Otherwise point is within this node, possibly in a child.
4572 (setq js2-discovered-node node)
4573 t)))))) ; keep processing kids to look for more specific match
4574
4575 (defsubst js2-block-comment-p (node)
4576 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4577 (and (js2-comment-node-p node)
4578 (memq (js2-comment-node-format node) '(jsdoc block))))
4579
4580 ;; TODO: put the comments in a vector and binary-search them instead
4581 (defun js2-comment-at-point (&optional pos)
4582 "Look through scanned comment nodes for one containing POS.
4583 POS is a buffer position that defaults to current point.
4584 Function returns nil if POS was not in any comment node."
4585 (let ((ast js2-mode-ast)
4586 (x (or pos (point)))
4587 beg
4588 end)
4589 (unless ast
4590 (error "No JavaScript AST available"))
4591 (catch 'done
4592 ;; Comments are stored in lexical order.
4593 (dolist (comment (js2-ast-root-comments ast) nil)
4594 (setq beg (js2-node-abs-pos comment)
4595 end (+ beg (js2-node-len comment)))
4596 (if (and (>= x beg)
4597 (<= x end))
4598 (throw 'done comment))))))
4599
4600 (defun js2-mode-find-parent-fn (node)
4601 "Find function enclosing NODE.
4602 Returns nil if NODE is not inside a function."
4603 (setq node (js2-node-parent node))
4604 (while (and node (not (js2-function-node-p node)))
4605 (setq node (js2-node-parent node)))
4606 (and (js2-function-node-p node) node))
4607
4608 (defun js2-mode-find-enclosing-fn (node)
4609 "Find function or root enclosing NODE."
4610 (if (js2-ast-root-p node)
4611 node
4612 (setq node (js2-node-parent node))
4613 (while (not (or (js2-ast-root-p node)
4614 (js2-function-node-p node)))
4615 (setq node (js2-node-parent node)))
4616 node))
4617
4618 (defun js2-mode-find-enclosing-node (beg end)
4619 "Find script or function fully enclosing BEG and END."
4620 (let ((node (js2-node-at-point beg))
4621 pos
4622 (continue t))
4623 (while continue
4624 (if (or (js2-ast-root-p node)
4625 (and (js2-function-node-p node)
4626 (<= (setq pos (js2-node-abs-pos node)) beg)
4627 (>= (+ pos (js2-node-len node)) end)))
4628 (setq continue nil)
4629 (setq node (js2-node-parent node))))
4630 node))
4631
4632 (defun js2-node-parent-script-or-fn (node)
4633 "Find script or function immediately enclosing NODE.
4634 If NODE is the ast-root, returns nil."
4635 (if (js2-ast-root-p node)
4636 nil
4637 (setq node (js2-node-parent node))
4638 (while (and node (not (or (js2-function-node-p node)
4639 (js2-script-node-p node))))
4640 (setq node (js2-node-parent node)))
4641 node))
4642
4643 (defsubst js2-nested-function-p (node)
4644 "Return t if NODE is a nested function, or is inside a nested function."
4645 (js2-function-node-p (if (js2-function-node-p node)
4646 (js2-node-parent-script-or-fn node)
4647 (js2-node-parent-script-or-fn
4648 (js2-node-parent-script-or-fn node)))))
4649
4650 (defsubst js2-mode-shift-kids (kids start offset)
4651 (dolist (kid kids)
4652 (if (> (js2-node-pos kid) start)
4653 (incf (js2-node-pos kid) offset))))
4654
4655 (defsubst js2-mode-shift-children (parent start offset)
4656 "Update start-positions of all children of PARENT beyond START."
4657 (let ((root (js2-node-root parent)))
4658 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4659 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4660
4661 (defsubst js2-node-is-descendant (node ancestor)
4662 "Return t if NODE is a descendant of ANCESTOR."
4663 (while (and node
4664 (not (eq node ancestor)))
4665 (setq node (js2-node-parent node)))
4666 node)
4667
4668 ;;; visitor infrastructure
4669
4670 (defun js2-visit-none (node callback)
4671 "Visitor for AST node that have no node children."
4672 nil)
4673
4674 (defun js2-print-none (node indent)
4675 "Visitor for AST node with no printed representation.")
4676
4677 (defun js2-print-body (node indent)
4678 "Print a statement, or a block without braces."
4679 (if (js2-block-node-p node)
4680 (dolist (kid (js2-block-node-kids node))
4681 (js2-print-ast kid indent))
4682 (js2-print-ast node indent)))
4683
4684 (defun js2-print-list (args &optional delimiter)
4685 (loop with len = (length args)
4686 for arg in args
4687 for count from 1
4688 do
4689 (js2-print-ast arg 0)
4690 (if (< count len)
4691 (insert (or delimiter ", ")))))
4692
4693 (defun js2-print-tree (ast)
4694 "Prints an AST to the current buffer.
4695 Makes `js2-ast-parent-nodes' available to the printer functions."
4696 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4697 (js2-print-ast ast)))
4698
4699 (defun js2-print-ast (node &optional indent)
4700 "Helper function for printing AST nodes.
4701 Requires `js2-ast-parent-nodes' to be non-nil.
4702 You should use `js2-print-tree' instead of this function."
4703 (let ((printer (get (aref node 0) 'js2-printer))
4704 (i (or indent 0))
4705 (pos (js2-node-abs-pos node)))
4706 ;; TODO: wedge comments in here somewhere
4707 (if printer
4708 (funcall printer node i))))
4709
4710 (defconst js2-side-effecting-tokens
4711 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4712 (dolist (tt (list js2-ASSIGN
4713 js2-ASSIGN_ADD
4714 js2-ASSIGN_BITAND
4715 js2-ASSIGN_BITOR
4716 js2-ASSIGN_BITXOR
4717 js2-ASSIGN_DIV
4718 js2-ASSIGN_LSH
4719 js2-ASSIGN_MOD
4720 js2-ASSIGN_MUL
4721 js2-ASSIGN_RSH
4722 js2-ASSIGN_SUB
4723 js2-ASSIGN_URSH
4724 js2-BLOCK
4725 js2-BREAK
4726 js2-CALL
4727 js2-CATCH
4728 js2-CATCH_SCOPE
4729 js2-CONST
4730 js2-CONTINUE
4731 js2-DEBUGGER
4732 js2-DEC
4733 js2-DELPROP
4734 js2-DEL_REF
4735 js2-DO
4736 js2-ELSE
4737 js2-EMPTY
4738 js2-ENTERWITH
4739 js2-EXPORT
4740 js2-EXPR_RESULT
4741 js2-FINALLY
4742 js2-FOR
4743 js2-FUNCTION
4744 js2-GOTO
4745 js2-IF
4746 js2-IFEQ
4747 js2-IFNE
4748 js2-IMPORT
4749 js2-INC
4750 js2-JSR
4751 js2-LABEL
4752 js2-LEAVEWITH
4753 js2-LET
4754 js2-LETEXPR
4755 js2-LOCAL_BLOCK
4756 js2-LOOP
4757 js2-NEW
4758 js2-REF_CALL
4759 js2-RETHROW
4760 js2-RETURN
4761 js2-RETURN_RESULT
4762 js2-SEMI
4763 js2-SETELEM
4764 js2-SETELEM_OP
4765 js2-SETNAME
4766 js2-SETPROP
4767 js2-SETPROP_OP
4768 js2-SETVAR
4769 js2-SET_REF
4770 js2-SET_REF_OP
4771 js2-SWITCH
4772 js2-TARGET
4773 js2-THROW
4774 js2-TRY
4775 js2-VAR
4776 js2-WHILE
4777 js2-WITH
4778 js2-WITHEXPR
4779 js2-YIELD))
4780 (aset tokens tt t))
4781 (if js2-instanceof-has-side-effects
4782 (aset tokens js2-INSTANCEOF t))
4783 tokens))
4784
4785 (defun js2-node-has-side-effects (node)
4786 "Return t if NODE has side effects."
4787 (when node ; makes it easier to handle malformed expressions
4788 (let ((tt (js2-node-type node)))
4789 (cond
4790 ;; This doubtless needs some work, since EXPR_VOID is used
4791 ;; in several ways in Rhino, and I may not have caught them all.
4792 ;; I'll wait for people to notice incorrect warnings.
4793 ((and (= tt js2-EXPR_VOID)
4794 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4795 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4796 ((= tt js2-COMMA)
4797 (js2-node-has-side-effects (js2-infix-node-right node)))
4798 ((or (= tt js2-AND)
4799 (= tt js2-OR))
4800 (or (js2-node-has-side-effects (js2-infix-node-right node))
4801 (js2-node-has-side-effects (js2-infix-node-left node))))
4802 ((= tt js2-HOOK)
4803 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4804 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4805 ((js2-paren-node-p node)
4806 (js2-node-has-side-effects (js2-paren-node-expr node)))
4807 ((= tt js2-ERROR) ; avoid cascaded error messages
4808 nil)
4809 (t
4810 (aref js2-side-effecting-tokens tt))))))
4811
4812 (defun js2-member-expr-leftmost-name (node)
4813 "For an expr such as foo.bar.baz, return leftmost node foo.
4814 NODE is any `js2-node' object. If it represents a member expression,
4815 which is any sequence of property gets, element-gets, function calls,
4816 or xml descendants/filter operators, then we look at the lexically
4817 leftmost (first) node in the chain. If it is a name-node we return it.
4818 Note that NODE can be a raw name-node and it will be returned as well.
4819 If NODE is not a name-node or member expression, or if it is a member
4820 expression whose leftmost target is not a name node, returns nil."
4821 (let ((continue t)
4822 result)
4823 (while (and continue (not result))
4824 (cond
4825 ((js2-name-node-p node)
4826 (setq result node))
4827 ((js2-prop-get-node-p node)
4828 (setq node (js2-prop-get-node-left node)))
4829 ;; TODO: handle call-nodes, xml-nodes, others?
4830 (t
4831 (setq continue nil))))
4832 result))
4833
4834 (defconst js2-stmt-node-types
4835 (list js2-BLOCK
4836 js2-BREAK
4837 js2-CONTINUE
4838 js2-DEFAULT ; e4x "default xml namespace" statement
4839 js2-DO
4840 js2-EXPR_RESULT
4841 js2-EXPR_VOID
4842 js2-FOR
4843 js2-IF
4844 js2-RETURN
4845 js2-SWITCH
4846 js2-THROW
4847 js2-TRY
4848 js2-WHILE
4849 js2-WITH)
4850 "Node types that only appear in statement contexts.
4851 The list does not include nodes that always appear as the child
4852 of another specific statement type, such as switch-cases,
4853 catch and finally blocks, and else-clauses. The list also excludes
4854 nodes like yield, let and var, which may appear in either expression
4855 or statement context, and in the latter context always have a
4856 `js2-expr-stmt-node' parent. Finally, the list does not include
4857 functions or scripts, which are treated separately from statements
4858 by the JavaScript parser and runtime.")
4859
4860 (defun js2-stmt-node-p (node)
4861 "Heuristic for figuring out if NODE is a statement.
4862 Some node types can appear in either an expression context or a
4863 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4864 For these node types in a statement context, the parent will be a
4865 `js2-expr-stmt-node'.
4866 Functions aren't included in the check."
4867 (memq (js2-node-type node) js2-stmt-node-types))
4868
4869 (defsubst js2-mode-find-first-stmt (node)
4870 "Search upward starting from NODE looking for a statement.
4871 For purposes of this function, a `js2-function-node' counts."
4872 (while (not (or (js2-stmt-node-p node)
4873 (js2-function-node-p node)))
4874 (setq node (js2-node-parent node)))
4875 node)
4876
4877 (defun js2-node-parent-stmt (node)
4878 "Return the node's first ancestor that is a statement.
4879 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4880 appearing in a statement context will have a parent that is a
4881 `js2-expr-stmt-node' that will be returned by this function."
4882 (let ((parent (js2-node-parent node)))
4883 (if (or (null parent)
4884 (js2-stmt-node-p parent)
4885 (and (js2-function-node-p parent)
4886 (not (eq (js2-function-node-form parent)
4887 'FUNCTION_EXPRESSION))))
4888 parent
4889 (js2-node-parent-stmt parent))))
4890
4891 ;; In the Mozilla Rhino sources, Roshan James writes:
4892 ;; Does consistent-return analysis on the function body when strict mode is
4893 ;; enabled.
4894 ;;
4895 ;; function (x) { return (x+1) }
4896 ;;
4897 ;; is ok, but
4898 ;;
4899 ;; function (x) { if (x < 0) return (x+1); }
4900 ;;
4901 ;; is not because the function can potentially return a value when the
4902 ;; condition is satisfied and if not, the function does not explicitly
4903 ;; return a value.
4904 ;;
4905 ;; This extends to checking mismatches such as "return" and "return <value>"
4906 ;; used in the same function. Warnings are not emitted if inconsistent
4907 ;; returns exist in code that can be statically shown to be unreachable.
4908 ;; Ex.
4909 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4910 ;;
4911 ;; emits no warning. However if the loop had a break statement, then a
4912 ;; warning would be emitted.
4913 ;;
4914 ;; The consistency analysis looks at control structures such as loops, ifs,
4915 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4916 ;; warns the user about an inconsistent set of termination possibilities.
4917 ;;
4918 ;; These flags enumerate the possible ways a statement/function can
4919 ;; terminate. These flags are used by endCheck() and by the Parser to
4920 ;; detect inconsistent return usage.
4921 ;;
4922 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4923 ;; able to execute (example: throw, continue)
4924 ;;
4925 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4926 ;; next one. Statement such as return dont. A compound statement may have
4927 ;; some branch that drops off control to the next statement.
4928 ;;
4929 ;; END_RETURNS indicates that the statement can return with no value.
4930 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4931 ;;
4932 ;; A compound statement such as
4933 ;; if (condition) {
4934 ;; return value;
4935 ;; }
4936 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4937
4938 (defconst js2-END_UNREACHED 0)
4939 (defconst js2-END_DROPS_OFF 1)
4940 (defconst js2-END_RETURNS 2)
4941 (defconst js2-END_RETURNS_VALUE 4)
4942 (defconst js2-END_YIELDS 8)
4943
4944 (defun js2-has-consistent-return-usage (node)
4945 "Check that every return usage in a function body is consistent.
4946 Returns t if the function satisfies strict mode requirement."
4947 (let ((n (js2-end-check node)))
4948 ;; either it doesn't return a value in any branch...
4949 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4950 ;; or it returns a value (or is unreached) at every branch
4951 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4952 js2-END_RETURNS
4953 js2-END_YIELDS)))))
4954
4955 (defun js2-end-check-if (node)
4956 "Returns in the then and else blocks must be consistent with each other.
4957 If there is no else block, then the return statement can fall through.
4958 Returns logical OR of END_* flags"
4959 (let ((th (js2-if-node-then-part node))
4960 (el (js2-if-node-else-part node)))
4961 (if (null th)
4962 js2-END_UNREACHED
4963 (logior (js2-end-check th) (if el
4964 (js2-end-check el)
4965 js2-END_DROPS_OFF)))))
4966
4967 (defun js2-end-check-switch (node)
4968 "Consistency of return statements is checked between the case statements.
4969 If there is no default, then the switch can fall through. If there is a
4970 default, we check to see if all code paths in the default return or if
4971 there is a code path that can fall through.
4972 Returns logical OR of END_* flags."
4973 (let ((rv js2-END_UNREACHED)
4974 default-case)
4975 ;; examine the cases
4976 (catch 'break
4977 (dolist (c (js2-switch-node-cases node))
4978 (if (js2-case-node-expr c)
4979 (js2-set-flag rv (js2-end-check-block c))
4980 (setq default-case c)
4981 (throw 'break nil))))
4982 ;; we don't care how the cases drop into each other
4983 (js2-clear-flag rv js2-END_DROPS_OFF)
4984 ;; examine the default
4985 (js2-set-flag rv (if default-case
4986 (js2-end-check default-case)
4987 js2-END_DROPS_OFF))
4988 rv))
4989
4990 (defun js2-end-check-try (node)
4991 "If the block has a finally, return consistency is checked in the
4992 finally block. If all code paths in the finally return, then the
4993 returns in the try-catch blocks don't matter. If there is a code path
4994 that does not return or if there is no finally block, the returns
4995 of the try and catch blocks are checked for mismatch.
4996 Returns logical OR of END_* flags."
4997 (let ((finally (js2-try-node-finally-block node))
4998 rv)
4999 ;; check the finally if it exists
5000 (setq rv (if finally
5001 (js2-end-check (js2-finally-node-body finally))
5002 js2-END_DROPS_OFF))
5003 ;; If the finally block always returns, then none of the returns
5004 ;; in the try or catch blocks matter.
5005 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5006 (js2-clear-flag rv js2-END_DROPS_OFF)
5007 ;; examine the try block
5008 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5009 ;; check each catch block
5010 (dolist (cb (js2-try-node-catch-clauses node))
5011 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5012 rv))
5013
5014 (defun js2-end-check-loop (node)
5015 "Return statement in the loop body must be consistent. The default
5016 assumption for any kind of a loop is that it will eventually terminate.
5017 The only exception is a loop with a constant true condition. Code that
5018 follows such a loop is examined only if one can statically determine
5019 that there is a break out of the loop.
5020
5021 for(... ; ... ; ...) {}
5022 for(... in ... ) {}
5023 while(...) { }
5024 do { } while(...)
5025
5026 Returns logical OR of END_* flags."
5027 (let ((rv (js2-end-check (js2-loop-node-body node)))
5028 (condition (cond
5029 ((js2-while-node-p node)
5030 (js2-while-node-condition node))
5031 ((js2-do-node-p node)
5032 (js2-do-node-condition node))
5033 ((js2-for-node-p node)
5034 (js2-for-node-condition node)))))
5035
5036 ;; check to see if the loop condition is always true
5037 (if (and condition
5038 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5039 (js2-clear-flag rv js2-END_DROPS_OFF))
5040
5041 ;; look for effect of breaks
5042 (js2-set-flag rv (js2-node-get-prop node
5043 'CONTROL_BLOCK_PROP
5044 js2-END_UNREACHED))
5045 rv))
5046
5047 (defun js2-end-check-block (node)
5048 "A general block of code is examined statement by statement.
5049 If any statement (even a compound one) returns in all branches, then
5050 subsequent statements are not examined.
5051 Returns logical OR of END_* flags."
5052 (let* ((rv js2-END_DROPS_OFF)
5053 (kids (js2-block-node-kids node))
5054 (n (car kids)))
5055 ;; Check each statment. If the statement can continue onto the next
5056 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5057 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5058 (js2-clear-flag rv js2-END_DROPS_OFF)
5059 (js2-set-flag rv (js2-end-check n))
5060 (setq kids (cdr kids)
5061 n (car kids)))
5062 rv))
5063
5064 (defun js2-end-check-label (node)
5065 "A labeled statement implies that there may be a break to the label.
5066 The function processes the labeled statement and then checks the
5067 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5068 particular label.
5069 Returns logical OR of END_* flags."
5070 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5071 (logior rv (js2-node-get-prop node
5072 'CONTROL_BLOCK_PROP
5073 js2-END_UNREACHED))))
5074
5075 (defun js2-end-check-break (node)
5076 "When a break is encountered annotate the statement being broken
5077 out of by setting its CONTROL_BLOCK_PROP property.
5078 Returns logical OR of END_* flags."
5079 (and (js2-break-node-target node)
5080 (js2-node-set-prop (js2-break-node-target node)
5081 'CONTROL_BLOCK_PROP
5082 js2-END_DROPS_OFF))
5083 js2-END_UNREACHED)
5084
5085 (defun js2-end-check (node)
5086 "Examine the body of a function, doing a basic reachability analysis.
5087 Returns a combination of flags END_* flags that indicate
5088 how the function execution can terminate. These constitute only the
5089 pessimistic set of termination conditions. It is possible that at
5090 runtime certain code paths will never be actually taken. Hence this
5091 analysis will flag errors in cases where there may not be errors.
5092 Returns logical OR of END_* flags"
5093 (let (kid)
5094 (cond
5095 ((js2-break-node-p node)
5096 (js2-end-check-break node))
5097 ((js2-expr-stmt-node-p node)
5098 (if (setq kid (js2-expr-stmt-node-expr node))
5099 (js2-end-check kid)
5100 js2-END_DROPS_OFF))
5101 ((or (js2-continue-node-p node)
5102 (js2-throw-node-p node))
5103 js2-END_UNREACHED)
5104 ((js2-return-node-p node)
5105 (if (setq kid (js2-return-node-retval node))
5106 js2-END_RETURNS_VALUE
5107 js2-END_RETURNS))
5108 ((js2-loop-node-p node)
5109 (js2-end-check-loop node))
5110 ((js2-switch-node-p node)
5111 (js2-end-check-switch node))
5112 ((js2-labeled-stmt-node-p node)
5113 (js2-end-check-label node))
5114 ((js2-if-node-p node)
5115 (js2-end-check-if node))
5116 ((js2-try-node-p node)
5117 (js2-end-check-try node))
5118 ((js2-block-node-p node)
5119 (if (null (js2-block-node-kids node))
5120 js2-END_DROPS_OFF
5121 (js2-end-check-block node)))
5122 ((js2-yield-node-p node)
5123 js2-END_YIELDS)
5124 (t
5125 js2-END_DROPS_OFF))))
5126
5127 (defun js2-always-defined-boolean-p (node)
5128 "Check if NODE always evaluates to true or false in boolean context.
5129 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5130 nor always false."
5131 (let ((tt (js2-node-type node))
5132 num)
5133 (cond
5134 ((or (= tt js2-FALSE) (= tt js2-NULL))
5135 'ALWAYS_FALSE)
5136 ((= tt js2-TRUE)
5137 'ALWAYS_TRUE)
5138 ((= tt js2-NUMBER)
5139 (setq num (js2-number-node-num-value node))
5140 (if (and (not (eq num 0.0e+NaN))
5141 (not (zerop num)))
5142 'ALWAYS_TRUE
5143 'ALWAYS_FALSE))
5144 (t
5145 nil))))
5146
5147 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5148 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5149
5150 (defvar js2-tokens nil
5151 "List of all defined token names.") ; initialized in `js2-token-names'
5152
5153 (defconst js2-token-names
5154 (let* ((names (make-vector js2-num-tokens -1))
5155 (case-fold-search nil) ; only match js2-UPPER_CASE
5156 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5157 (loop for sym in syms
5158 for i from 0
5159 do
5160 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5161 (not (boundp sym)))
5162 (aset names (symbol-value sym) ; code, e.g. 152
5163 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5164 (push sym js2-tokens)))
5165 names)
5166 "Vector mapping int values to token string names, sans `js2-' prefix.")
5167
5168 (defun js2-token-name (tok)
5169 "Return a string name for TOK, a token symbol or code.
5170 Signals an error if it's not a recognized token."
5171 (let ((code tok))
5172 (if (symbolp tok)
5173 (setq code (symbol-value tok)))
5174 (if (eq code -1)
5175 "ERROR"
5176 (if (and (numberp code)
5177 (not (minusp code))
5178 (< code js2-num-tokens))
5179 (aref js2-token-names code)
5180 (error "Invalid token: %s" code)))))
5181
5182 (defsubst js2-token-sym (tok)
5183 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5184 (intern (js2-token-name tok)))
5185
5186 (defconst js2-token-codes
5187 (let ((table (make-hash-table :test 'eq :size 256)))
5188 (loop for name across js2-token-names
5189 for sym = (intern (concat "js2-" name))
5190 do
5191 (puthash sym (symbol-value sym) table))
5192 ;; clean up a few that are "wrong" in Rhino's token codes
5193 (puthash 'js2-DELETE js2-DELPROP table)
5194 table)
5195 "Hashtable mapping token symbols to their bytecodes.")
5196
5197 (defsubst js2-token-code (sym)
5198 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5199 (or (gethash sym js2-token-codes)
5200 (error "Invalid token symbol: %s " sym))) ; signal code bug
5201
5202 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5203 (setq js2-token-end js2-ts-cursor)
5204 (js2-report-error msg nil
5205 (or beg js2-token-beg)
5206 (or len (- js2-token-end js2-token-beg)))
5207 (unless no-throw
5208 (throw 'return js2-ERROR)))
5209
5210 (defsubst js2-get-string-from-buffer ()
5211 "Reverse the char accumulator and return it as a string."
5212 (setq js2-token-end js2-ts-cursor)
5213 (if js2-ts-string-buffer
5214 (apply #'string (nreverse js2-ts-string-buffer))
5215 ""))
5216
5217 ;; TODO: could potentially avoid a lot of consing by allocating a
5218 ;; char buffer the way Rhino does.
5219 (defsubst js2-add-to-string (c)
5220 (push c js2-ts-string-buffer))
5221
5222 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5223 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5224 ;; any other character: when it's not part of the current token, we
5225 ;; unget it, allowing it to be read again by the following call.
5226 (defsubst js2-unget-char ()
5227 (decf js2-ts-cursor))
5228
5229 ;; Rhino distinguishes \r and \n line endings. We don't need to
5230 ;; because we only scan from Emacs buffers, which always use \n.
5231 (defsubst js2-get-char ()
5232 "Read and return the next character from the input buffer.
5233 Increments `js2-ts-lineno' if the return value is a newline char.
5234 Updates `js2-ts-cursor' to the point after the returned char.
5235 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5236 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5237 (let (c)
5238 ;; check for end of buffer
5239 (if (>= js2-ts-cursor (point-max))
5240 (setq js2-ts-hit-eof t
5241 js2-ts-cursor (1+ js2-ts-cursor)
5242 c js2-EOF_CHAR) ; return value
5243 ;; otherwise read next char
5244 (setq c (char-before (incf js2-ts-cursor)))
5245 ;; if we read a newline, update counters
5246 (if (= c ?\n)
5247 (setq js2-ts-line-start js2-ts-cursor
5248 js2-ts-lineno (1+ js2-ts-lineno)))
5249 ;; TODO: skip over format characters
5250 c)))
5251
5252 (defsubst js2-read-unicode-escape ()
5253 "Read a \\uNNNN sequence from the input.
5254 Assumes the ?\ and ?u have already been read.
5255 Returns the unicode character, or nil if it wasn't a valid character.
5256 Doesn't change the values of any scanner variables."
5257 ;; I really wish I knew a better way to do this, but I can't
5258 ;; find the Emacs function that takes a 16-bit int and converts
5259 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5260 ;; Have to first check that it's 4 hex characters or it may stop
5261 ;; the read early.
5262 (ignore-errors
5263 (let ((s (buffer-substring-no-properties js2-ts-cursor
5264 (+ 4 js2-ts-cursor))))
5265 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5266 (read (concat "?\\u" s))))))
5267
5268 (defsubst js2-match-char (test)
5269 "Consume and return next character if it matches TEST, a character.
5270 Returns nil and consumes nothing if TEST is not the next character."
5271 (let ((c (js2-get-char)))
5272 (if (eq c test)
5273 t
5274 (js2-unget-char)
5275 nil)))
5276
5277 (defsubst js2-peek-char ()
5278 (prog1
5279 (js2-get-char)
5280 (js2-unget-char)))
5281
5282 (defsubst js2-java-identifier-start-p (c)
5283 (or
5284 (memq c '(?$ ?_))
5285 (js2-char-uppercase-p c)
5286 (js2-char-lowercase-p c)))
5287
5288 (defsubst js2-java-identifier-part-p (c)
5289 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5290 ;; TODO: make me Unicode-friendly. See comments above.
5291 (or
5292 (memq c '(?$ ?_))
5293 (js2-char-uppercase-p c)
5294 (js2-char-lowercase-p c)
5295 (and (>= c ?0) (<= c ?9))))
5296
5297 (defsubst js2-alpha-p (c)
5298 (cond ((and (<= ?A c) (<= c ?Z)) t)
5299 ((and (<= ?a c) (<= c ?z)) t)
5300 (t nil)))
5301
5302 (defsubst js2-digit-p (c)
5303 (and (<= ?0 c) (<= c ?9)))
5304
5305 (defsubst js2-js-space-p (c)
5306 (if (<= c 127)
5307 (memq c '(#x20 #x9 #xB #xC #xD))
5308 (or
5309 (eq c #xA0)
5310 ;; TODO: change this nil to check for Unicode space character
5311 nil)))
5312
5313 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5314
5315 (defsubst js2-skip-line ()
5316 "Skip to end of line"
5317 (let (c)
5318 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5319 (js2-unget-char)
5320 (setq js2-token-end js2-ts-cursor)))
5321
5322 (defun js2-init-scanner (&optional buf line)
5323 "Create token stream for BUF starting on LINE.
5324 BUF defaults to current-buffer and line defaults to 1.
5325
5326 A buffer can only have one scanner active at a time, which yields
5327 dramatically simpler code than using a defstruct. If you need to
5328 have simultaneous scanners in a buffer, copy the regions to scan
5329 into temp buffers."
5330 (save-excursion
5331 (when buf
5332 (set-buffer buf))
5333 (setq js2-ts-dirty-line nil
5334 js2-ts-regexp-flags nil
5335 js2-ts-string ""
5336 js2-ts-number nil
5337 js2-ts-hit-eof nil
5338 js2-ts-line-start 0
5339 js2-ts-lineno (or line 1)
5340 js2-ts-line-end-char -1
5341 js2-ts-cursor (point-min)
5342 js2-ts-is-xml-attribute nil
5343 js2-ts-xml-is-tag-content nil
5344 js2-ts-xml-open-tags-count 0
5345 js2-ts-string-buffer nil)))
5346
5347 ;; This function uses the cached op, string and number fields in
5348 ;; TokenStream; if getToken has been called since the passed token
5349 ;; was scanned, the op or string printed may be incorrect.
5350 (defun js2-token-to-string (token)
5351 ;; Not sure where this function is used in Rhino. Not tested.
5352 (if (not js2-debug-print-trees)
5353 ""
5354 (let ((name (js2-token-name token)))
5355 (cond
5356 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5357 (concat name " `" js2-ts-string "'"))
5358 ((eq token js2-NUMBER)
5359 (format "NUMBER %g" js2-ts-number))
5360 (t
5361 name)))))
5362
5363 (defconst js2-keywords
5364 '(break
5365 case catch const continue
5366 debugger default delete do
5367 else enum
5368 false finally for function
5369 if in instanceof import
5370 let
5371 new null
5372 return
5373 switch
5374 this throw true try typeof
5375 var void
5376 while with
5377 yield))
5378
5379 ;; Token names aren't exactly the same as the keywords, unfortunately.
5380 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5381 (defconst js2-kwd-tokens
5382 (let ((table (make-vector js2-num-tokens nil))
5383 (tokens
5384 (list js2-BREAK
5385 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5386 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5387 js2-ELSE
5388 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5389 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5390 js2-LET
5391 js2-NEW js2-NULL
5392 js2-RETURN
5393 js2-SWITCH
5394 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5395 js2-VAR
5396 js2-WHILE js2-WITH
5397 js2-YIELD)))
5398 (dolist (i tokens)
5399 (aset table i 'font-lock-keyword-face))
5400 (aset table js2-STRING 'font-lock-string-face)
5401 (aset table js2-REGEXP 'font-lock-string-face)
5402 (aset table js2-COMMENT 'font-lock-comment-face)
5403 (aset table js2-THIS 'font-lock-builtin-face)
5404 (aset table js2-VOID 'font-lock-constant-face)
5405 (aset table js2-NULL 'font-lock-constant-face)
5406 (aset table js2-TRUE 'font-lock-constant-face)
5407 (aset table js2-FALSE 'font-lock-constant-face)
5408 table)
5409 "Vector whose values are non-nil for tokens that are keywords.
5410 The values are default faces to use for highlighting the keywords.")
5411
5412 (defconst js2-reserved-words
5413 '(abstract
5414 boolean byte
5415 char class
5416 double
5417 enum export extends
5418 final float
5419 goto
5420 implements import int interface
5421 long
5422 native
5423 package private protected public
5424 short static super synchronized
5425 throws transient
5426 volatile))
5427
5428 (defconst js2-keyword-names
5429 (let ((table (make-hash-table :test 'equal)))
5430 (loop for k in js2-keywords
5431 do (puthash
5432 (symbol-name k) ; instanceof
5433 (intern (concat "js2-"
5434 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5435 table))
5436 table)
5437 "JavaScript keywords by name, mapped to their symbols.")
5438
5439 (defconst js2-reserved-word-names
5440 (let ((table (make-hash-table :test 'equal)))
5441 (loop for k in js2-reserved-words
5442 do
5443 (puthash (symbol-name k) 'js2-RESERVED table))
5444 table)
5445 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5446
5447 (defsubst js2-collect-string (buf)
5448 "Convert BUF, a list of chars, to a string.
5449 Reverses BUF before converting."
5450 (cond
5451 ((stringp buf)
5452 buf)
5453 ((null buf) ; for emacs21 compat
5454 "")
5455 (t
5456 (if buf
5457 (apply #'string (nreverse buf))
5458 ""))))
5459
5460 (defun js2-string-to-keyword (s)
5461 "Return token for S, a string, if S is a keyword or reserved word.
5462 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5463 (or (gethash s js2-keyword-names)
5464 (gethash s js2-reserved-word-names)))
5465
5466 (defsubst js2-ts-set-char-token-bounds ()
5467 "Used when next token is one character."
5468 (setq js2-token-beg (1- js2-ts-cursor)
5469 js2-token-end js2-ts-cursor))
5470
5471 (defsubst js2-ts-return (token)
5472 "Return an N-character TOKEN from `js2-get-token'.
5473 Updates `js2-token-end' accordingly."
5474 (setq js2-token-end js2-ts-cursor)
5475 (throw 'return token))
5476
5477 (defsubst js2-x-digit-to-int (c accumulator)
5478 "Build up a hex number.
5479 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5480 corresponding number. Otherwise return -1."
5481 (catch 'return
5482 (catch 'check
5483 ;; Use 0..9 < A..Z < a..z
5484 (cond
5485 ((<= c ?9)
5486 (decf c ?0)
5487 (if (<= 0 c)
5488 (throw 'check nil)))
5489 ((<= c ?F)
5490 (when (<= ?A c)
5491 (decf c (- ?A 10))
5492 (throw 'check nil)))
5493 ((<= c ?f)
5494 (when (<= ?a c)
5495 (decf c (- ?a 10))
5496 (throw 'check nil))))
5497 (throw 'return -1))
5498 (logior c (lsh accumulator 4))))
5499
5500 (defun js2-get-token ()
5501 "Return next JavaScript token, an int such as js2-RETURN."
5502 (let (c
5503 c1
5504 identifier-start
5505 is-unicode-escape-start
5506 contains-escape
5507 escape-val
5508 escape-start
5509 str
5510 result
5511 base
5512 is-integer
5513 quote-char
5514 val
5515 look-for-slash
5516 continue)
5517 (catch 'return
5518 (while t
5519 ;; Eat whitespace, possibly sensitive to newlines.
5520 (setq continue t)
5521 (while continue
5522 (setq c (js2-get-char))
5523 (cond
5524 ((eq c js2-EOF_CHAR)
5525 (js2-ts-set-char-token-bounds)
5526 (throw 'return js2-EOF))
5527 ((eq c ?\n)
5528 (js2-ts-set-char-token-bounds)
5529 (setq js2-ts-dirty-line nil)
5530 (throw 'return js2-EOL))
5531 ((not (js2-js-space-p c))
5532 (if (/= c ?-) ; in case end of HTML comment
5533 (setq js2-ts-dirty-line t))
5534 (setq continue nil))))
5535 ;; Assume the token will be 1 char - fixed up below.
5536 (js2-ts-set-char-token-bounds)
5537 (when (eq c ?@)
5538 (throw 'return js2-XMLATTR))
5539 ;; identifier/keyword/instanceof?
5540 ;; watch out for starting with a <backslash>
5541 (cond
5542 ((eq c ?\\)
5543 (setq c (js2-get-char))
5544 (if (eq c ?u)
5545 (setq identifier-start t
5546 is-unicode-escape-start t
5547 js2-ts-string-buffer nil)
5548 (setq identifier-start nil)
5549 (js2-unget-char)
5550 (setq c ?\\)))
5551 (t
5552 (when (setq identifier-start (js2-java-identifier-start-p c))
5553 (setq js2-ts-string-buffer nil)
5554 (js2-add-to-string c))))
5555 (when identifier-start
5556 (setq contains-escape is-unicode-escape-start)
5557 (catch 'break
5558 (while t
5559 (if is-unicode-escape-start
5560 ;; strictly speaking we should probably push-back
5561 ;; all the bad characters if the <backslash>uXXXX
5562 ;; sequence is malformed. But since there isn't a
5563 ;; correct context(is there?) for a bad Unicode
5564 ;; escape sequence in an identifier, we can report
5565 ;; an error here.
5566 (progn
5567 (setq escape-val 0)
5568 (dotimes (i 4)
5569 (setq c (js2-get-char)
5570 escape-val (js2-x-digit-to-int c escape-val))
5571 ;; Next check takes care of c < 0 and bad escape
5572 (if (minusp escape-val)
5573 (throw 'break nil)))
5574 (if (minusp escape-val)
5575 (js2-report-scan-error "msg.invalid.escape" t))
5576 (js2-add-to-string escape-val)
5577 (setq is-unicode-escape-start nil))
5578 (setq c (js2-get-char))
5579 (cond
5580 ((eq c ?\\)
5581 (setq c (js2-get-char))
5582 (if (eq c ?u)
5583 (setq is-unicode-escape-start t
5584 contains-escape t)
5585 (js2-report-scan-error "msg.illegal.character" t)))
5586 (t
5587 (if (or (eq c js2-EOF_CHAR)
5588 (not (js2-java-identifier-part-p c)))
5589 (throw 'break nil))
5590 (js2-add-to-string c))))))
5591 (js2-unget-char)
5592 (setq str (js2-get-string-from-buffer))
5593 (unless contains-escape
5594 ;; OPT we shouldn't have to make a string (object!) to
5595 ;; check if it's a keyword.
5596 ;; Return the corresponding token if it's a keyword
5597 (when (setq result (js2-string-to-keyword str))
5598 (if (and (< js2-language-version 170)
5599 (memq result '(js2-LET js2-YIELD)))
5600 ;; LET and YIELD are tokens only in 1.7 and later
5601 (setq result 'js2-NAME))
5602 (if (not (eq result js2-RESERVED))
5603 (throw 'return (js2-token-code result)))
5604 (js2-report-warning "msg.reserved.keyword" str)))
5605 ;; If we want to intern these as Rhino does, just use (intern str)
5606 (setq js2-ts-string str)
5607 (throw 'return js2-NAME)) ; end identifier/kwd check
5608 ;; is it a number?
5609 (when (or (js2-digit-p c)
5610 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5611 (setq js2-ts-string-buffer nil
5612 base 10)
5613 (when (eq c ?0)
5614 (setq c (js2-get-char))
5615 (cond
5616 ((or (eq c ?x) (eq c ?X))
5617 (setq base 16)
5618 (setq c (js2-get-char)))
5619 ((js2-digit-p c)
5620 (setq base 8))
5621 (t
5622 (js2-add-to-string ?0))))
5623 (if (eq base 16)
5624 (while (<= 0 (js2-x-digit-to-int c 0))
5625 (js2-add-to-string c)
5626 (setq c (js2-get-char)))
5627 (while (and (<= ?0 c) (<= c ?9))
5628 ;; We permit 08 and 09 as decimal numbers, which
5629 ;; makes our behavior a superset of the ECMA
5630 ;; numeric grammar. We might not always be so
5631 ;; permissive, so we warn about it.
5632 (when (and (eq base 8) (>= c ?8))
5633 (js2-report-warning "msg.bad.octal.literal"
5634 (if (eq c ?8) "8" "9"))
5635 (setq base 10))
5636 (js2-add-to-string c)
5637 (setq c (js2-get-char))))
5638 (setq is-integer t)
5639 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5640 (setq is-integer nil)
5641 (when (eq c ?.)
5642 (loop do
5643 (js2-add-to-string c)
5644 (setq c (js2-get-char))
5645 while (js2-digit-p c)))
5646 (when (memq c '(?e ?E))
5647 (js2-add-to-string c)
5648 (setq c (js2-get-char))
5649 (when (memq c '(?+ ?-))
5650 (js2-add-to-string c)
5651 (setq c (js2-get-char)))
5652 (unless (js2-digit-p c)
5653 (js2-report-scan-error "msg.missing.exponent" t))
5654 (loop do
5655 (js2-add-to-string c)
5656 (setq c (js2-get-char))
5657 while (js2-digit-p c))))
5658 (js2-unget-char)
5659 (setq js2-ts-string (js2-get-string-from-buffer)
5660 js2-ts-number
5661 (if (and (eq base 10) (not is-integer))
5662 (string-to-number js2-ts-string)
5663 ;; TODO: call runtime number-parser. Some of it is in
5664 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5665 (string-to-number js2-ts-string)))
5666 (throw 'return js2-NUMBER))
5667 ;; is it a string?
5668 (when (memq c '(?\" ?\'))
5669 ;; We attempt to accumulate a string the fast way, by
5670 ;; building it directly out of the reader. But if there
5671 ;; are any escaped characters in the string, we revert to
5672 ;; building it out of a string buffer.
5673 (setq quote-char c
5674 js2-ts-string-buffer nil
5675 c (js2-get-char))
5676 (catch 'break
5677 (while (/= c quote-char)
5678 (catch 'continue
5679 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5680 (js2-unget-char)
5681 (setq js2-token-end js2-ts-cursor)
5682 (js2-report-error "msg.unterminated.string.lit")
5683 (throw 'return js2-STRING))
5684 (when (eq c ?\\)
5685 ;; We've hit an escaped character
5686 (setq c (js2-get-char))
5687 (case c
5688 (?b (setq c ?\b))
5689 (?f (setq c ?\f))
5690 (?n (setq c ?\n))
5691 (?r (setq c ?\r))
5692 (?t (setq c ?\t))
5693 (?v (setq c ?\v))
5694 (?u
5695 (setq c1 (js2-read-unicode-escape))
5696 (if js2-parse-ide-mode
5697 (if c1
5698 (progn
5699 ;; just copy the string in IDE-mode
5700 (js2-add-to-string ?\\)
5701 (js2-add-to-string ?u)
5702 (dotimes (i 3)
5703 (js2-add-to-string (js2-get-char)))
5704 (setq c (js2-get-char))) ; added at end of loop
5705 ;; flag it as an invalid escape
5706 (js2-report-warning "msg.invalid.escape"
5707 nil (- js2-ts-cursor 2) 6))
5708 ;; Get 4 hex digits; if the u escape is not
5709 ;; followed by 4 hex digits, use 'u' + the
5710 ;; literal character sequence that follows.
5711 (js2-add-to-string ?u)
5712 (setq escape-val 0)
5713 (dotimes (i 4)
5714 (setq c (js2-get-char)
5715 escape-val (js2-x-digit-to-int c escape-val))
5716 (if (minusp escape-val)
5717 (throw 'continue nil))
5718 (js2-add-to-string c))
5719 ;; prepare for replace of stored 'u' sequence by escape value
5720 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5721 c escape-val)))
5722 (?x
5723 ;; Get 2 hex digits, defaulting to 'x'+literal
5724 ;; sequence, as above.
5725 (setq c (js2-get-char)
5726 escape-val (js2-x-digit-to-int c 0))
5727 (if (minusp escape-val)
5728 (progn
5729 (js2-add-to-string ?x)
5730 (throw 'continue nil))
5731 (setq c1 c
5732 c (js2-get-char)
5733 escape-val (js2-x-digit-to-int c escape-val))
5734 (if (minusp escape-val)
5735 (progn
5736 (js2-add-to-string ?x)
5737 (js2-add-to-string c1)
5738 (throw 'continue nil))
5739 ;; got 2 hex digits
5740 (setq c escape-val))))
5741 (?\n
5742 ;; Remove line terminator after escape to follow
5743 ;; SpiderMonkey and C/C++
5744 (setq c (js2-get-char))
5745 (throw 'continue nil))
5746 (t
5747 (when (and (<= ?0 c) (< c ?8))
5748 (setq val (- c ?0)
5749 c (js2-get-char))
5750 (when (and (<= ?0 c) (< c ?8))
5751 (setq val (- (+ (* 8 val) c) ?0)
5752 c (js2-get-char))
5753 (when (and (<= ?0 c)
5754 (< c ?8)
5755 (< val #o37))
5756 ;; c is 3rd char of octal sequence only
5757 ;; if the resulting val <= 0377
5758 (setq val (- (+ (* 8 val) c) ?0)
5759 c (js2-get-char))))
5760 (js2-unget-char)
5761 (setq c val)))))
5762 (js2-add-to-string c)
5763 (setq c (js2-get-char)))))
5764 (setq js2-ts-string (js2-get-string-from-buffer))
5765 (throw 'return js2-STRING))
5766 (case c
5767 (?\;
5768 (throw 'return js2-SEMI))
5769 (?\[
5770 (throw 'return js2-LB))
5771 (?\]
5772 (throw 'return js2-RB))
5773 (?{
5774 (throw 'return js2-LC))
5775 (?}
5776 (throw 'return js2-RC))
5777 (?\(
5778 (throw 'return js2-LP))
5779 (?\)
5780 (throw 'return js2-RP))
5781 (?,
5782 (throw 'return js2-COMMA))
5783 (??
5784 (throw 'return js2-HOOK))
5785 (?:
5786 (if (js2-match-char ?:)
5787 (js2-ts-return js2-COLONCOLON)
5788 (throw 'return js2-COLON)))
5789 (?.
5790 (if (js2-match-char ?.)
5791 (js2-ts-return js2-DOTDOT)
5792 (if (js2-match-char ?\()
5793 (js2-ts-return js2-DOTQUERY)
5794 (throw 'return js2-DOT))))
5795 (?|
5796 (if (js2-match-char ?|)
5797 (throw 'return js2-OR)
5798 (if (js2-match-char ?=)
5799 (js2-ts-return js2-ASSIGN_BITOR)
5800 (throw 'return js2-BITOR))))
5801 (?^
5802 (if (js2-match-char ?=)
5803 (js2-ts-return js2-ASSIGN_BITOR)
5804 (throw 'return js2-BITXOR)))
5805 (?&
5806 (if (js2-match-char ?&)
5807 (throw 'return js2-AND)
5808 (if (js2-match-char ?=)
5809 (js2-ts-return js2-ASSIGN_BITAND)
5810 (throw 'return js2-BITAND))))
5811 (?=
5812 (if (js2-match-char ?=)
5813 (if (js2-match-char ?=)
5814 (js2-ts-return js2-SHEQ)
5815 (throw 'return js2-EQ))
5816 (throw 'return js2-ASSIGN)))
5817 (?!
5818 (if (js2-match-char ?=)
5819 (if (js2-match-char ?=)
5820 (js2-ts-return js2-SHNE)
5821 (js2-ts-return js2-NE))
5822 (throw 'return js2-NOT)))
5823 (?<
5824 ;; NB:treat HTML begin-comment as comment-till-eol
5825 (when (js2-match-char ?!)
5826 (when (js2-match-char ?-)
5827 (when (js2-match-char ?-)
5828 (js2-skip-line)
5829 (setq js2-ts-comment-type 'html)
5830 (throw 'return js2-COMMENT)))
5831 (js2-unget-char))
5832 (if (js2-match-char ?<)
5833 (if (js2-match-char ?=)
5834 (js2-ts-return js2-ASSIGN_LSH)
5835 (js2-ts-return js2-LSH))
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-LE)
5838 (throw 'return js2-LT))))
5839 (?>
5840 (if (js2-match-char ?>)
5841 (if (js2-match-char ?>)
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_URSH)
5844 (js2-ts-return js2-URSH))
5845 (if (js2-match-char ?=)
5846 (js2-ts-return js2-ASSIGN_RSH)
5847 (js2-ts-return js2-RSH)))
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-GE)
5850 (throw 'return js2-GT))))
5851 (?*
5852 (if (js2-match-char ?=)
5853 (js2-ts-return js2-ASSIGN_MUL)
5854 (throw 'return js2-MUL)))
5855 (?/
5856 ;; is it a // comment?
5857 (when (js2-match-char ?/)
5858 (setq js2-token-beg (- js2-ts-cursor 2))
5859 (js2-skip-line)
5860 (setq js2-ts-comment-type 'line)
5861 ;; include newline so highlighting goes to end of window
5862 (incf js2-token-end)
5863 (throw 'return js2-COMMENT))
5864 ;; is it a /* comment?
5865 (when (js2-match-char ?*)
5866 (setq look-for-slash nil
5867 js2-token-beg (- js2-ts-cursor 2)
5868 js2-ts-comment-type
5869 (if (js2-match-char ?*)
5870 (progn
5871 (setq look-for-slash t)
5872 'jsdoc)
5873 'block))
5874 (while t
5875 (setq c (js2-get-char))
5876 (cond
5877 ((eq c js2-EOF_CHAR)
5878 (setq js2-token-end (1- js2-ts-cursor))
5879 (js2-report-error "msg.unterminated.comment")
5880 (throw 'return js2-COMMENT))
5881 ((eq c ?*)
5882 (setq look-for-slash t))
5883 ((eq c ?/)
5884 (if look-for-slash
5885 (js2-ts-return js2-COMMENT)))
5886 (t
5887 (setq look-for-slash nil
5888 js2-token-end js2-ts-cursor)))))
5889 (if (js2-match-char ?=)
5890 (js2-ts-return js2-ASSIGN_DIV)
5891 (throw 'return js2-DIV)))
5892 (?#
5893 (when js2-skip-preprocessor-directives
5894 (js2-skip-line)
5895 (setq js2-ts-comment-type 'preprocessor
5896 js2-token-end js2-ts-cursor)
5897 (throw 'return js2-COMMENT))
5898 (throw 'return js2-ERROR))
5899 (?%
5900 (if (js2-match-char ?=)
5901 (js2-ts-return js2-ASSIGN_MOD)
5902 (throw 'return js2-MOD)))
5903 (?~
5904 (throw 'return js2-BITNOT))
5905 (?+
5906 (if (js2-match-char ?=)
5907 (js2-ts-return js2-ASSIGN_ADD)
5908 (if (js2-match-char ?+)
5909 (js2-ts-return js2-INC)
5910 (throw 'return js2-ADD))))
5911 (?-
5912 (cond
5913 ((js2-match-char ?=)
5914 (setq c js2-ASSIGN_SUB))
5915 ((js2-match-char ?-)
5916 (unless js2-ts-dirty-line
5917 ;; treat HTML end-comment after possible whitespace
5918 ;; after line start as comment-until-eol
5919 (when (js2-match-char ?>)
5920 (js2-skip-line)
5921 (setq js2-ts-comment-type 'html)
5922 (throw 'return js2-COMMENT)))
5923 (setq c js2-DEC))
5924 (t
5925 (setq c js2-SUB)))
5926 (setq js2-ts-dirty-line t)
5927 (js2-ts-return c))
5928 (otherwise
5929 (js2-report-scan-error "msg.illegal.character")))))))
5930
5931 (defun js2-read-regexp (start-token)
5932 "Called by parser when it gets / or /= in literal context."
5933 (let (c
5934 err
5935 in-class ; inside a '[' .. ']' character-class
5936 flags
5937 (continue t))
5938 (setq js2-token-beg js2-ts-cursor
5939 js2-ts-string-buffer nil
5940 js2-ts-regexp-flags nil)
5941 (if (eq start-token js2-ASSIGN_DIV)
5942 ;; mis-scanned /=
5943 (js2-add-to-string ?=)
5944 (if (not (eq start-token js2-DIV))
5945 (error "failed assertion")))
5946 (while (and (not err)
5947 (or (/= (setq c (js2-get-char)) ?/)
5948 in-class))
5949 (cond
5950 ((or (= c ?\n)
5951 (= c js2-EOF_CHAR))
5952 (setq js2-token-end (1- js2-ts-cursor)
5953 err t
5954 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5955 (js2-report-error "msg.unterminated.re.lit"))
5956 (t (cond
5957 ((= c ?\\)
5958 (js2-add-to-string c)
5959 (setq c (js2-get-char)))
5960 ((= c ?\[)
5961 (setq in-class t))
5962 ((= c ?\])
5963 (setq in-class nil)))
5964 (js2-add-to-string c))))
5965 (unless err
5966 (while continue
5967 (cond
5968 ((js2-match-char ?g)
5969 (push ?g flags))
5970 ((js2-match-char ?i)
5971 (push ?i flags))
5972 ((js2-match-char ?m)
5973 (push ?m flags))
5974 (t
5975 (setq continue nil))))
5976 (if (js2-alpha-p (js2-peek-char))
5977 (js2-report-scan-error "msg.invalid.re.flag" t
5978 js2-ts-cursor 1))
5979 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5980 js2-ts-regexp-flags (js2-collect-string flags)
5981 js2-token-end js2-ts-cursor)
5982 ;; tell `parse-partial-sexp' to ignore this range of chars
5983 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5984
5985 (defun js2-get-first-xml-token ()
5986 (setq js2-ts-xml-open-tags-count 0
5987 js2-ts-is-xml-attribute nil
5988 js2-ts-xml-is-tag-content nil)
5989 (js2-unget-char)
5990 (js2-get-next-xml-token))
5991
5992 (defsubst js2-xml-discard-string ()
5993 "Throw away the string in progress and flag an XML parse error."
5994 (setq js2-ts-string-buffer nil
5995 js2-ts-string nil)
5996 (js2-report-scan-error "msg.XML.bad.form" t))
5997
5998 (defun js2-get-next-xml-token ()
5999 (setq js2-ts-string-buffer nil ; for recording the XML
6000 js2-token-beg js2-ts-cursor)
6001 (let (c result)
6002 (setq result
6003 (catch 'return
6004 (while t
6005 (setq c (js2-get-char))
6006 (cond
6007 ((= c js2-EOF_CHAR)
6008 (throw 'return js2-ERROR))
6009 (js2-ts-xml-is-tag-content
6010 (case c
6011 (?>
6012 (js2-add-to-string c)
6013 (setq js2-ts-xml-is-tag-content nil
6014 js2-ts-is-xml-attribute nil))
6015 (?/
6016 (js2-add-to-string c)
6017 (when (eq ?> (js2-peek-char))
6018 (setq c (js2-get-char))
6019 (js2-add-to-string c)
6020 (setq js2-ts-xml-is-tag-content nil)
6021 (decf js2-ts-xml-open-tags-count)))
6022 (?{
6023 (js2-unget-char)
6024 (setq js2-ts-string (js2-get-string-from-buffer))
6025 (throw 'return js2-XML))
6026 ((?\' ?\")
6027 (js2-add-to-string c)
6028 (unless (js2-read-quoted-string c)
6029 (throw 'return js2-ERROR)))
6030 (?=
6031 (js2-add-to-string c)
6032 (setq js2-ts-is-xml-attribute t))
6033 ((? ?\t ?\r ?\n)
6034 (js2-add-to-string c))
6035 (t
6036 (js2-add-to-string c)
6037 (setq js2-ts-is-xml-attribute nil)))
6038 (when (and (not js2-ts-xml-is-tag-content)
6039 (zerop js2-ts-xml-open-tags-count))
6040 (setq js2-ts-string (js2-get-string-from-buffer))
6041 (throw 'return js2-XMLEND)))
6042 (t
6043 ;; else not tag content
6044 (case c
6045 (?<
6046 (js2-add-to-string c)
6047 (setq c (js2-peek-char))
6048 (case c
6049 (?!
6050 (setq c (js2-get-char)) ;; skip !
6051 (js2-add-to-string c)
6052 (setq c (js2-peek-char))
6053 (case c
6054 (?-
6055 (setq c (js2-get-char)) ;; skip -
6056 (js2-add-to-string c)
6057 (if (eq c ?-)
6058 (progn
6059 (js2-add-to-string c)
6060 (unless (js2-read-xml-comment)
6061 (throw 'return js2-ERROR)))
6062 (js2-xml-discard-string)
6063 (throw 'return js2-ERROR)))
6064 (?\[
6065 (setq c (js2-get-char)) ;; skip [
6066 (js2-add-to-string c)
6067 (if (and (= (js2-get-char) ?C)
6068 (= (js2-get-char) ?D)
6069 (= (js2-get-char) ?A)
6070 (= (js2-get-char) ?T)
6071 (= (js2-get-char) ?A)
6072 (= (js2-get-char) ?\[))
6073 (progn
6074 (js2-add-to-string ?C)
6075 (js2-add-to-string ?D)
6076 (js2-add-to-string ?A)
6077 (js2-add-to-string ?T)
6078 (js2-add-to-string ?A)
6079 (js2-add-to-string ?\[)
6080 (unless (js2-read-cdata)
6081 (throw 'return js2-ERROR)))
6082 (js2-xml-discard-string)
6083 (throw 'return js2-ERROR)))
6084 (t
6085 (unless (js2-read-entity)
6086 (throw 'return js2-ERROR)))))
6087 (??
6088 (setq c (js2-get-char)) ;; skip ?
6089 (js2-add-to-string c)
6090 (unless (js2-read-PI)
6091 (throw 'return js2-ERROR)))
6092 (?/
6093 ;; end tag
6094 (setq c (js2-get-char)) ;; skip /
6095 (js2-add-to-string c)
6096 (when (zerop js2-ts-xml-open-tags-count)
6097 (js2-xml-discard-string)
6098 (throw 'return js2-ERROR))
6099 (setq js2-ts-xml-is-tag-content t)
6100 (decf js2-ts-xml-open-tags-count))
6101 (t
6102 ;; start tag
6103 (setq js2-ts-xml-is-tag-content t)
6104 (incf js2-ts-xml-open-tags-count))))
6105 (?{
6106 (js2-unget-char)
6107 (setq js2-ts-string (js2-get-string-from-buffer))
6108 (throw 'return js2-XML))
6109 (t
6110 (js2-add-to-string c))))))))
6111 (setq js2-token-end js2-ts-cursor)
6112 result))
6113
6114 (defun js2-read-quoted-string (quote)
6115 (let (c)
6116 (catch 'return
6117 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6118 (js2-add-to-string c)
6119 (if (eq c quote)
6120 (throw 'return t)))
6121 (js2-xml-discard-string) ;; throw away string in progress
6122 nil)))
6123
6124 (defun js2-read-xml-comment ()
6125 (let ((c (js2-get-char)))
6126 (catch 'return
6127 (while (/= c js2-EOF_CHAR)
6128 (catch 'continue
6129 (js2-add-to-string c)
6130 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6131 (setq c (js2-get-char))
6132 (js2-add-to-string c)
6133 (if (eq (js2-peek-char) ?>)
6134 (progn
6135 (setq c (js2-get-char)) ;; skip >
6136 (js2-add-to-string c)
6137 (throw 'return t))
6138 (throw 'continue nil)))
6139 (setq c (js2-get-char))))
6140 (js2-xml-discard-string)
6141 nil)))
6142
6143 (defun js2-read-cdata ()
6144 (let ((c (js2-get-char)))
6145 (catch 'return
6146 (while (/= c js2-EOF_CHAR)
6147 (catch 'continue
6148 (js2-add-to-string c)
6149 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6150 (setq c (js2-get-char))
6151 (js2-add-to-string c)
6152 (if (eq (js2-peek-char) ?>)
6153 (progn
6154 (setq c (js2-get-char)) ;; Skip >
6155 (js2-add-to-string c)
6156 (throw 'return t))
6157 (throw 'continue nil)))
6158 (setq c (js2-get-char))))
6159 (js2-xml-discard-string)
6160 nil)))
6161
6162 (defun js2-read-entity ()
6163 (let ((decl-tags 1)
6164 c)
6165 (catch 'return
6166 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6167 (js2-add-to-string c)
6168 (case c
6169 (?<
6170 (incf decl-tags))
6171 (?>
6172 (decf decl-tags)
6173 (if (zerop decl-tags)
6174 (throw 'return t)))))
6175 (js2-xml-discard-string)
6176 nil)))
6177
6178 (defun js2-read-PI ()
6179 "Scan an XML processing instruction."
6180 (let (c)
6181 (catch 'return
6182 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6183 (js2-add-to-string c)
6184 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6185 (setq c (js2-get-char)) ;; Skip >
6186 (js2-add-to-string c)
6187 (throw 'return t)))
6188 (js2-xml-discard-string)
6189 nil)))
6190
6191 (defun js2-scanner-get-line ()
6192 "Return the text of the current scan line."
6193 (buffer-substring (point-at-bol) (point-at-eol)))
6194
6195 ;;; Highlighting
6196
6197 (defsubst js2-set-face (beg end face &optional record)
6198 "Fontify a region. If RECORD is non-nil, record for later."
6199 (when (plusp js2-highlight-level)
6200 (setq beg (min (point-max) beg)
6201 beg (max (point-min) beg)
6202 end (min (point-max) end)
6203 end (max (point-min) end))
6204 (if record
6205 (push (list beg end face) js2-mode-fontifications)
6206 (put-text-property beg end 'face face))))
6207
6208 (defsubst js2-set-kid-face (pos kid len face)
6209 "Set-face on a child node.
6210 POS is absolute buffer position of parent.
6211 KID is the child node.
6212 LEN is the length to fontify.
6213 FACE is the face to fontify with."
6214 (js2-set-face (+ pos (js2-node-pos kid))
6215 (+ pos (js2-node-pos kid) (js2-node-len kid))
6216 face))
6217
6218 (defsubst js2-fontify-kwd (start length)
6219 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6220
6221 (defsubst js2-clear-face (beg end)
6222 (remove-text-properties beg end '(face nil
6223 help-echo nil
6224 point-entered nil
6225 c-in-sws nil)))
6226
6227 (defsubst js2-record-text-property (beg end prop value)
6228 "Record a text property to set when parsing finishes."
6229 (push (list beg end prop value) js2-mode-deferred-properties))
6230
6231 (defconst js2-ecma-global-props
6232 (concat "^"
6233 (regexp-opt
6234 '("Infinity" "NaN" "undefined" "arguments") t)
6235 "$")
6236 "Value properties of the Ecma-262 Global Object.
6237 Shown at or above `js2-highlight-level' 2.")
6238
6239 ;; might want to add the name "arguments" to this list?
6240 (defconst js2-ecma-object-props
6241 (concat "^"
6242 (regexp-opt
6243 '("prototype" "__proto__" "__parent__") t)
6244 "$")
6245 "Value properties of the Ecma-262 Object constructor.
6246 Shown at or above `js2-highlight-level' 2.")
6247
6248 (defconst js2-ecma-global-funcs
6249 (concat
6250 "^"
6251 (regexp-opt
6252 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6253 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6254 "$")
6255 "Function properties of the Ecma-262 Global object.
6256 Shown at or above `js2-highlight-level' 2.")
6257
6258 (defconst js2-ecma-number-props
6259 (concat "^"
6260 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6261 "NEGATIVE_INFINITY"
6262 "POSITIVE_INFINITY") t)
6263 "$")
6264 "Properties of the Ecma-262 Number constructor.
6265 Shown at or above `js2-highlight-level' 2.")
6266
6267 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6268 "Properties of the Ecma-262 Date constructor.
6269 Shown at or above `js2-highlight-level' 2.")
6270
6271 (defconst js2-ecma-math-props
6272 (concat "^"
6273 (regexp-opt
6274 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6275 t)
6276 "$")
6277 "Properties of the Ecma-262 Math object.
6278 Shown at or above `js2-highlight-level' 2.")
6279
6280 (defconst js2-ecma-math-funcs
6281 (concat "^"
6282 (regexp-opt
6283 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6284 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6285 "$")
6286 "Function properties of the Ecma-262 Math object.
6287 Shown at or above `js2-highlight-level' 2.")
6288
6289 (defconst js2-ecma-function-props
6290 (concat
6291 "^"
6292 (regexp-opt
6293 '(;; properties of the Object prototype object
6294 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6295 "toLocaleString" "toString" "valueOf"
6296 ;; properties of the Function prototype object
6297 "apply" "call"
6298 ;; properties of the Array prototype object
6299 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6300 "splice" "unshift"
6301 ;; properties of the String prototype object
6302 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6303 "localeCompare" "match" "replace" "search" "split" "substring"
6304 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6305 "toUpperCase"
6306 ;; properties of the Number prototype object
6307 "toExponential" "toFixed" "toPrecision"
6308 ;; properties of the Date prototype object
6309 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6310 "getMinutes" "getMonth" "getSeconds" "getTime"
6311 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6312 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6313 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6314 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6315 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6316 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6317 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6318 "toTimeString" "toUTCString"
6319 ;; properties of the RegExp prototype object
6320 "exec" "test"
6321 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6322 "toSource" "__defineGetter__" "__defineSetter__"
6323 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6324 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6325 t)
6326 "$")
6327 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6328 Shown at or above `js2-highlight-level' 3.")
6329
6330 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6331 (let ((target-name (and target
6332 (js2-name-node-p target)
6333 (js2-name-node-name target)))
6334 (prop-name (if prop (js2-name-node-name prop)))
6335 (level1 (>= js2-highlight-level 1))
6336 (level2 (>= js2-highlight-level 2))
6337 (level3 (>= js2-highlight-level 3))
6338 pos
6339 face)
6340 (when level2
6341 (if call-p
6342 (cond
6343 ((and target prop)
6344 (cond
6345 ((and level3 (string-match js2-ecma-function-props prop-name))
6346 (setq face 'font-lock-builtin-face))
6347 ((and target-name prop)
6348 (cond
6349 ((string= target-name "Date")
6350 (if (string-match js2-ecma-date-props prop-name)
6351 (setq face 'font-lock-builtin-face)))
6352 ((string= target-name "Math")
6353 (if (string-match js2-ecma-math-funcs prop-name)
6354 (setq face 'font-lock-builtin-face)))))))
6355 (prop
6356 (if (string-match js2-ecma-global-funcs prop-name)
6357 (setq face 'font-lock-builtin-face))))
6358 (cond
6359 ((and target prop)
6360 (cond
6361 ((string= target-name "Number")
6362 (if (string-match js2-ecma-number-props prop-name)
6363 (setq face 'font-lock-constant-face)))
6364 ((string= target-name "Math")
6365 (if (string-match js2-ecma-math-props prop-name)
6366 (setq face 'font-lock-constant-face)))))
6367 (prop
6368 (if (string-match js2-ecma-object-props prop-name)
6369 (setq face 'font-lock-constant-face)))))
6370 (when face
6371 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6372 (js2-node-pos prop))) ; relative
6373 (+ pos (js2-node-len prop))
6374 face)))))
6375
6376 (defun js2-parse-highlight-member-expr-node (node)
6377 "Perform syntax highlighting of EcmaScript built-in properties.
6378 The variable `js2-highlight-level' governs this highighting."
6379 (let (face target prop name pos end parent call-p callee)
6380 (cond
6381 ;; case 1: simple name, e.g. foo
6382 ((js2-name-node-p node)
6383 (setq name (js2-name-node-name node))
6384 ;; possible for name to be nil in rare cases - saw it when
6385 ;; running js2-mode on an elisp buffer. Might as well try to
6386 ;; make it so js2-mode never barfs.
6387 (when name
6388 (setq face (if (string-match js2-ecma-global-props name)
6389 'font-lock-constant-face))
6390 (when face
6391 (setq pos (js2-node-pos node)
6392 end (+ pos (js2-node-len node)))
6393 (js2-set-face pos end face))))
6394 ;; case 2: property access or function call
6395 ((or (js2-prop-get-node-p node)
6396 ;; highlight function call if expr is a prop-get node
6397 ;; or a plain name (i.e. unqualified function call)
6398 (and (setq call-p (js2-call-node-p node))
6399 (setq callee (js2-call-node-target node)) ; separate setq!
6400 (or (js2-prop-get-node-p callee)
6401 (js2-name-node-p callee))))
6402 (setq parent node
6403 node (if call-p callee node))
6404 (if (and call-p (js2-name-node-p callee))
6405 (setq prop callee)
6406 (setq target (js2-prop-get-node-left node)
6407 prop (js2-prop-get-node-right node)))
6408 (cond
6409 ((js2-name-node-p target)
6410 (if (js2-name-node-p prop)
6411 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6412 (js2-parse-highlight-prop-get parent target prop call-p)
6413 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6414 (js2-parse-highlight-prop-get parent target nil call-p)))
6415 ((js2-name-node-p prop)
6416 ;; case 2c: complex target, simple name, e.g. x[y].bar
6417 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6418
6419 (defun js2-parse-highlight-member-expr-fn-name (expr)
6420 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6421 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6422 We currently only handle the case where the last component is a prop-get
6423 of a simple name. Called before EXPR has a parent node."
6424 (let (pos
6425 (name (and (js2-prop-get-node-p expr)
6426 (js2-prop-get-node-right expr))))
6427 (when (js2-name-node-p name)
6428 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6429 (js2-node-pos name)))
6430 (+ pos (js2-node-len name))
6431 'font-lock-function-name-face
6432 'record))))
6433
6434 ;; source: http://jsdoc.sourceforge.net/
6435 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6436 ;; allows type specifications, and needs work before entering the wild.
6437
6438 (defconst js2-jsdoc-param-tag-regexp
6439 (concat "^\\s-*\\*+\\s-*\\(@"
6440 "\\(?:param\\|argument\\)"
6441 "\\)"
6442 "\\s-*\\({[^}]+}\\)?" ; optional type
6443 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6444 "\\>")
6445 "Matches jsdoc tags with optional type and optional param name.")
6446
6447 (defconst js2-jsdoc-typed-tag-regexp
6448 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6449 (regexp-opt
6450 '("enum"
6451 "extends"
6452 "field"
6453 "id"
6454 "implements"
6455 "lends"
6456 "mods"
6457 "requires"
6458 "return"
6459 "returns"
6460 "throw"
6461 "throws"))
6462 "\\)\\)\\s-*\\({[^}]+}\\)?")
6463 "Matches jsdoc tags with optional type.")
6464
6465 (defconst js2-jsdoc-arg-tag-regexp
6466 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6467 (regexp-opt
6468 '("alias"
6469 "augments"
6470 "borrows"
6471 "bug"
6472 "base"
6473 "config"
6474 "default"
6475 "define"
6476 "exception"
6477 "function"
6478 "member"
6479 "memberOf"
6480 "name"
6481 "namespace"
6482 "property"
6483 "since"
6484 "suppress"
6485 "this"
6486 "throws"
6487 "type"
6488 "version"))
6489 "\\)\\)\\s-+\\([^ \t]+\\)")
6490 "Matches jsdoc tags with a single argument.")
6491
6492 (defconst js2-jsdoc-empty-tag-regexp
6493 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6494 (regexp-opt
6495 '("addon"
6496 "author"
6497 "class"
6498 "const"
6499 "constant"
6500 "constructor"
6501 "constructs"
6502 "deprecated"
6503 "desc"
6504 "description"
6505 "event"
6506 "example"
6507 "exec"
6508 "export"
6509 "fileoverview"
6510 "final"
6511 "function"
6512 "hidden"
6513 "ignore"
6514 "implicitCast"
6515 "inheritDoc"
6516 "inner"
6517 "interface"
6518 "license"
6519 "noalias"
6520 "noshadow"
6521 "notypecheck"
6522 "override"
6523 "owner"
6524 "preserve"
6525 "preserveTry"
6526 "private"
6527 "protected"
6528 "public"
6529 "static"
6530 "supported"
6531 ))
6532 "\\)\\)\\s-*")
6533 "Matches empty jsdoc tags.")
6534
6535 (defconst js2-jsdoc-link-tag-regexp
6536 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6537 "Matches a jsdoc link or code tag.")
6538
6539 (defconst js2-jsdoc-see-tag-regexp
6540 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6541 "Matches a jsdoc @see tag.")
6542
6543 (defconst js2-jsdoc-html-tag-regexp
6544 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6545 "Matches a simple (no attributes) html start- or end-tag.")
6546
6547 (defsubst js2-jsdoc-highlight-helper ()
6548 (js2-set-face (match-beginning 1)
6549 (match-end 1)
6550 'js2-jsdoc-tag)
6551 (if (match-beginning 2)
6552 (if (save-excursion
6553 (goto-char (match-beginning 2))
6554 (= (char-after) ?{))
6555 (js2-set-face (1+ (match-beginning 2))
6556 (1- (match-end 2))
6557 'js2-jsdoc-type)
6558 (js2-set-face (match-beginning 2)
6559 (match-end 2)
6560 'js2-jsdoc-value)))
6561 (if (match-beginning 3)
6562 (js2-set-face (match-beginning 3)
6563 (match-end 3)
6564 'js2-jsdoc-value)))
6565
6566 (defun js2-highlight-jsdoc (ast)
6567 "Highlight doc comment tags."
6568 (let ((comments (js2-ast-root-comments ast))
6569 beg end)
6570 (save-excursion
6571 (dolist (node comments)
6572 (when (eq (js2-comment-node-format node) 'jsdoc)
6573 (setq beg (js2-node-abs-pos node)
6574 end (+ beg (js2-node-len node)))
6575 (save-restriction
6576 (narrow-to-region beg end)
6577 (dolist (re (list js2-jsdoc-param-tag-regexp
6578 js2-jsdoc-typed-tag-regexp
6579 js2-jsdoc-arg-tag-regexp
6580 js2-jsdoc-link-tag-regexp
6581 js2-jsdoc-see-tag-regexp
6582 js2-jsdoc-empty-tag-regexp))
6583 (goto-char beg)
6584 (while (re-search-forward re nil t)
6585 (js2-jsdoc-highlight-helper)))
6586 ;; simple highlighting for html tags
6587 (goto-char beg)
6588 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6589 (js2-set-face (match-beginning 1)
6590 (match-end 1)
6591 'js2-jsdoc-html-tag-delimiter)
6592 (js2-set-face (match-beginning 2)
6593 (match-end 2)
6594 'js2-jsdoc-html-tag-name)
6595 (js2-set-face (match-beginning 3)
6596 (match-end 3)
6597 'js2-jsdoc-html-tag-delimiter))))))))
6598
6599 (defun js2-highlight-assign-targets (node left right)
6600 "Highlight function properties and external variables."
6601 (let (leftpos end name)
6602 ;; highlight vars and props assigned function values
6603 (when (js2-function-node-p right)
6604 (cond
6605 ;; var foo = function() {...}
6606 ((js2-name-node-p left)
6607 (setq name left))
6608 ;; foo.bar.baz = function() {...}
6609 ((and (js2-prop-get-node-p left)
6610 (js2-name-node-p (js2-prop-get-node-right left)))
6611 (setq name (js2-prop-get-node-right left))))
6612 (when name
6613 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6614 (+ leftpos (js2-node-len name))
6615 'font-lock-function-name-face
6616 'record)))
6617 ;; save variable assignments so we can check for undeclared later
6618 ;; (can't do it here since var decls can come at end of script)
6619 (when (and js2-highlight-external-variables
6620 (setq name (js2-member-expr-leftmost-name left)))
6621 (push (list name js2-current-scope
6622 (setq leftpos (js2-node-abs-pos name))
6623 (setq end (+ leftpos (js2-node-len name))))
6624 js2-recorded-assignments))))
6625
6626 (defun js2-highlight-undeclared-vars ()
6627 "After entire parse is finished, look for undeclared variable assignments.
6628 We have to wait until entire buffer is parsed, since JavaScript permits var
6629 decls to occur after they're used.
6630
6631 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6632 it is considered declared."
6633 (let (name)
6634 (dolist (entry js2-recorded-assignments)
6635 (destructuring-bind (name-node scope pos end) entry
6636 (setq name (js2-name-node-name name-node))
6637 (unless (or (member name js2-global-externs)
6638 (member name js2-default-externs)
6639 (member name js2-additional-externs)
6640 (js2-get-defining-scope scope name))
6641 (js2-set-face pos end 'js2-external-variable 'record)
6642 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6643 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6644 (setq js2-recorded-assignments nil)))
6645
6646 ;;; IMenu support
6647
6648 ;; We currently only support imenu, but eventually should support speedbar and
6649 ;; possibly other browsing mechanisms.
6650
6651 ;; The basic strategy is to identify function assignment targets of the form
6652 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6653 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6654 ;; for imenu after parsing is finished.
6655
6656 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6657 ;; JavaScript, and the general problem is undecidable. However, several forms
6658 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6659 ;; include:
6660
6661 ;; function foo() -- function declaration
6662 ;; foo = function() -- function expression assigned to variable
6663 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6664 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6665 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6666 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6667 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6668 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6669 ;; function foo() {function bar() {...}} -- nested function
6670 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6671
6672 ;; This list boils down to a few forms that can be combined recursively.
6673 ;; Top-level named function declarations include both the left-hand (name)
6674 ;; and the right-hand (function value) expressions needed to produce an imenu
6675 ;; entry. The other "right-hand" forms we need to look for are:
6676 ;; - functions declared as props/getters/setters in object literals
6677 ;; - nested named function declarations
6678 ;; The "left-hand" expressions that functions can be assigned to include:
6679 ;; - local/global variables
6680 ;; - nested property-get expressions like a.b.c.d
6681 ;; - element gets like foo[10] or foo['bar'] where the index
6682 ;; expression can be trivially converted to a property name. They
6683 ;; effectively then become property gets.
6684
6685 ;; All the different definition types are canonicalized into the form
6686 ;; foo.bar.baz = position-of-function-keyword
6687
6688 ;; We need to build a trie-like structure for imenu. As an example,
6689 ;; consider the following JavaScript code:
6690
6691 ;; a = function() {...} // function at position 5
6692 ;; b = function() {...} // function at position 25
6693 ;; foo = function() {...} // function at position 100
6694 ;; foo.bar = function() {...} // function at position 200
6695 ;; foo.bar.baz = function() {...} // function at position 300
6696 ;; foo.bar.zab = function() {...} // function at position 400
6697
6698 ;; During parsing we accumulate an entry for each definition in
6699 ;; the variable `js2-imenu-recorder', like so:
6700
6701 ;; '((a 5)
6702 ;; (b 25)
6703 ;; (foo 100)
6704 ;; (foo bar 200)
6705 ;; (foo bar baz 300)
6706 ;; (foo bar zab 400))
6707
6708 ;; After parsing these entries are merged into this alist-trie:
6709
6710 ;; '((a . 1)
6711 ;; (b . 2)
6712 ;; (foo (<definition> . 3)
6713 ;; (bar (<definition> . 6)
6714 ;; (baz . 100)
6715 ;; (zab . 200))))
6716
6717 ;; Note the wacky need for a <definition> name. The token can be anything
6718 ;; that isn't a valid JavaScript identifier, because you might make foo
6719 ;; a function and then start setting properties on it that are also functions.
6720
6721 (defsubst js2-prop-node-name (node)
6722 "Return the name of a node that may be a property-get/property-name.
6723 If NODE is not a valid name-node, string-node or integral number-node,
6724 returns nil. Otherwise returns the string name/value of the node."
6725 (cond
6726 ((js2-name-node-p node)
6727 (js2-name-node-name node))
6728 ((js2-string-node-p node)
6729 (js2-string-node-value node))
6730 ((and (js2-number-node-p node)
6731 (string-match "^[0-9]+$" (js2-number-node-value node)))
6732 (js2-number-node-value node))
6733 ((js2-this-node-p node)
6734 "this")))
6735
6736 (defsubst js2-node-qname-component (node)
6737 "Test function: return the name of this node, if it contributes to a qname.
6738 Returns nil if the node doesn't contribute."
6739 (copy-sequence
6740 (or (js2-prop-node-name node)
6741 (if (and (js2-function-node-p node)
6742 (js2-function-node-name node))
6743 (js2-name-node-name (js2-function-node-name node))))))
6744
6745 (defsubst js2-record-function-qname (fn-node qname)
6746 "Associate FN-NODE with its QNAME for later lookup.
6747 This is used in postprocessing the chain list. When we find a chain
6748 whose first element is a js2-THIS keyword node, we look up the parent
6749 function and see (using this map) whether it is the tail of a chain.
6750 If so, we replace the this-node with a copy of the parent's qname."
6751 (unless js2-imenu-function-map
6752 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6753 (puthash fn-node qname js2-imenu-function-map))
6754
6755 (defun js2-record-imenu-functions (node &optional var)
6756 "Record function definitions for imenu.
6757 NODE is a function node or an object literal.
6758 VAR, if non-nil, is the expression that NODE is being assigned to."
6759 (when js2-parse-ide-mode
6760 (let ((fun-p (js2-function-node-p node))
6761 qname left fname-node pos)
6762 (cond
6763 ;; non-anonymous function declaration?
6764 ((and fun-p
6765 (not var)
6766 (setq fname-node (js2-function-node-name node)))
6767 (push (setq qname (list fname-node (js2-node-pos node)))
6768 js2-imenu-recorder)
6769 (js2-record-function-qname node qname))
6770 ;; for remaining forms, compute left-side tree branch first
6771 ((and var (setq qname (js2-compute-nested-prop-get var)))
6772 (cond
6773 ;; foo.bar.baz = function
6774 (fun-p
6775 (push (nconc qname (list (js2-node-pos node)))
6776 js2-imenu-recorder)
6777 (js2-record-function-qname node qname))
6778 ;; foo.bar.baz = object-literal
6779 ;; look for nested functions: {a: {b: function() {...} }}
6780 ((js2-object-node-p node)
6781 (js2-record-object-literal node qname))))))))
6782
6783 (defun js2-compute-nested-prop-get (node)
6784 "If NODE is of form foo.bar.baz, return component nodes as a list.
6785 Otherwise returns nil. Element-gets can be treated as property-gets
6786 if the index expression is a name, a string, or a positive integer."
6787 (let (left right head)
6788 (cond
6789 ((or (js2-name-node-p node)
6790 (js2-this-node-p node))
6791 (list node))
6792 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6793 ((js2-prop-get-node-p node) ; includes elem-get nodes
6794 (setq left (js2-prop-get-node-left node)
6795 right (js2-prop-get-node-right node))
6796 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6797 (js2-name-node-p left)
6798 (js2-this-node-p left)) ; or left == foo
6799 (or (js2-name-node-p right) ; .bar
6800 (js2-string-node-p right) ; ['bar']
6801 (and (js2-number-node-p right) ; [10]
6802 (string-match "^[0-9]+$"
6803 (js2-number-node-value right)))))
6804 (if (setq head (js2-compute-nested-prop-get left))
6805 (nconc head (list right))))))))
6806
6807 (defun js2-record-object-literal (node qname)
6808 "Recursively process an object literal looking for functions.
6809 NODE is an object literal that is the right-hand child of an assignment
6810 expression. QNAME is a list of nodes representing the assignment target,
6811 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6812 We do a depth-first traversal of NODE. Any functions we find are prefixed
6813 with QNAME plus the property name of the function and appended to the
6814 variable `js2-imenu-recorder'."
6815 ;; Elements are relative to parent position, which is still absolute,
6816 ;; since the parser passes the assignment target and value expressions
6817 ;; to us before they are added as children of the assignment node.
6818 (let ((pos (js2-node-pos node))
6819 left right)
6820 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6821 (setq left (js2-infix-node-left e))
6822 (cond
6823 ;; foo: function() {...}
6824 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6825 (when (js2-prop-node-name left)
6826 ;; As a policy decision, we record the position of the property,
6827 ;; not the position of the `function' keyword, since the property
6828 ;; is effectively the name of the function.
6829 (push (append qname (list left) (list (+ pos (js2-node-pos e))))
6830 js2-imenu-recorder)
6831 (js2-record-function-qname right qname)))
6832 ;; foo: {object-literal} -- add foo to qname and recurse
6833 ((js2-object-node-p right)
6834 (js2-record-object-literal right
6835 (append qname (list (js2-infix-node-left e)))))))))
6836
6837 (defsubst js2-node-top-level-decl-p (node)
6838 "Return t if NODE's name is defined in the top-level scope.
6839 Also returns t if NODE's name is not defined in any scope, since it implies
6840 that it's an external variable, which must also be in the top-level scope."
6841 (let* ((name (js2-prop-node-name node))
6842 (this-scope (js2-node-get-enclosing-scope node))
6843 defining-scope)
6844 (cond
6845 ((js2-this-node-p node)
6846 nil)
6847 ((null this-scope)
6848 t)
6849 ((setq defining-scope (js2-get-defining-scope this-scope name))
6850 (js2-ast-root-p defining-scope))
6851 (t t))))
6852
6853 (defun js2-browse-postprocess-chains (chains)
6854 "Modify function-declaration name chains after parsing finishes.
6855 Some of the information is only available after the parse tree is complete.
6856 For instance, following a 'this' reference requires a parent function node."
6857 (let (result head fn parent-chain p elem)
6858 (dolist (chain chains)
6859 ;; examine the head of each node to get its defining scope
6860 (setq head (car chain))
6861 (cond
6862 ;; if top-level/external, keep as-is
6863 ((js2-node-top-level-decl-p head)
6864 (push chain result))
6865 ;; check for a this-reference
6866 ((eq (js2-node-type head) js2-THIS)
6867 (setq fn (js2-node-parent-script-or-fn head))
6868 ;; if there is no parent function, or if the parent function
6869 ;; is nested, discard the head node and keep the rest of the chain.
6870 (if (or (null fn) (js2-nested-function-p fn))
6871 (push (cdr chain) result)
6872 ;; else look up parent in function-map. If not found, discard chain.
6873 (when (setq parent-chain (and js2-imenu-function-map
6874 (gethash fn js2-imenu-function-map)))
6875 ;; else discard head node and prefix parent fn qname, which is
6876 ;; the parent-chain sans tail, to this chain.
6877 (push (append (butlast parent-chain) (cdr chain)) result))))))
6878 ;; finally replace each node in each chain with its name.
6879 (dolist (chain result)
6880 (setq p chain)
6881 (while p
6882 (if (js2-node-p (setq elem (car p)))
6883 (setcar p (js2-node-qname-component elem)))
6884 (setq p (cdr p))))
6885 result))
6886
6887 ;; Merge name chains into a trie-like tree structure of nested lists.
6888 ;; To simplify construction of the trie, we first build it out using the rule
6889 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6890 ;; [key, num-or-list]. The second element can be a number; if so, this key
6891 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6892 ;; associated with the key at this level.) Otherwise the second element is
6893 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6894 ;; a simple recursive formulation.
6895 ;;
6896 ;; js2-mode is building the data structure for imenu. The imenu documentation
6897 ;; claims that it's the structure above, but in practice it wants the children
6898 ;; at the same list level as the key for that level, which is how I've drawn
6899 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6900 ;; list wrapper around the children at each level.
6901 ;;
6902 ;; A completed nested imenu-alist entry looks like this:
6903 ;; '(("foo"
6904 ;; ("<definition>" . 7)
6905 ;; ("bar"
6906 ;; ("a" . 40)
6907 ;; ("b" . 60))))
6908 ;;
6909 ;; In particular, the documentation for `imenu--index-alist' says that
6910 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6911 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6912
6913 (defsubst js2-treeify (lst)
6914 "Convert (a b c d) to (a ((b ((c d)))))"
6915 (if (null (cddr lst)) ; list length <= 2
6916 lst
6917 (list (car lst) (list (js2-treeify (cdr lst))))))
6918
6919 (defun js2-build-alist-trie (chains trie)
6920 "Merge declaration name chains into a trie-like alist structure for imenu.
6921 CHAINS is the qname chain list produced during parsing. TRIE is a
6922 list of elements built up so far."
6923 (let (head tail pos branch kids)
6924 (dolist (chain chains)
6925 (setq head (car chain)
6926 tail (cdr chain)
6927 pos (if (numberp (car tail)) (car tail))
6928 branch (js2-find-if (lambda (n)
6929 (string= (car n) head))
6930 trie)
6931 kids (second branch))
6932 (cond
6933 ;; case 1: this key isn't in the trie yet
6934 ((null branch)
6935 (if trie
6936 (setcdr (last trie) (list (js2-treeify chain)))
6937 (setq trie (list (js2-treeify chain)))))
6938 ;; case 2: key is present with a single number entry: replace w/ list
6939 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6940 ;; ("<definition>" 20)))
6941 ((numberp kids)
6942 (setcar (cdr branch)
6943 (list (list "<definition-1>" kids)
6944 (if pos
6945 (list "<definition-2>" pos)
6946 (js2-treeify tail)))))
6947 ;; case 3: key is there (with kids), and we're a number entry
6948 (pos
6949 (setcdr (last kids)
6950 (list
6951 (list (format "<definition-%d>"
6952 (1+ (loop for kid in kids
6953 count (eq ?< (aref (car kid) 0)))))
6954 pos))))
6955
6956 ;; case 4: key is there with kids, need to merge in our chain
6957 (t
6958 (js2-build-alist-trie (list tail) kids))))
6959 trie))
6960
6961 (defun js2-flatten-trie (trie)
6962 "Convert TRIE to imenu-format.
6963 Recurses through nodes, and for each one whose second element is a list,
6964 appends the list's flattened elements to the current element. Also
6965 changes the tails into conses. For instance, this pre-flattened trie
6966
6967 '(a ((b 20)
6968 (c ((d 30)
6969 (e 40)))))
6970
6971 becomes
6972
6973 '(a (b . 20)
6974 (c (d . 30)
6975 (e . 40)))
6976
6977 Note that the root of the trie has no key, just a list of chains.
6978 This is also true for the value of any key with multiple children,
6979 e.g. key 'c' in the example above."
6980 (cond
6981 ((listp (car trie))
6982 (mapcar #'js2-flatten-trie trie))
6983 (t
6984 (if (numberp (second trie))
6985 (cons (car trie) (second trie))
6986 ;; else pop list and append its kids
6987 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6988
6989 (defun js2-build-imenu-index ()
6990 "Turn `js2-imenu-recorder' into an imenu data structure."
6991 (unless (eq js2-imenu-recorder 'empty)
6992 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6993 (result (js2-build-alist-trie chains nil)))
6994 (js2-flatten-trie result))))
6995
6996 (defun js2-test-print-chains (chains)
6997 "Print a list of qname chains.
6998 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6999 i.e. one or more nodes, and an integer position as the list tail."
7000 (mapconcat (lambda (chain)
7001 (concat "("
7002 (mapconcat (lambda (elem)
7003 (if (js2-node-p elem)
7004 (or (js2-node-qname-component elem)
7005 "nil")
7006 (number-to-string elem)))
7007 chain
7008 " ")
7009 ")"))
7010 chains
7011 "\n"))
7012
7013 ;;; Parser
7014
7015 (defconst js2-version "1.8.0"
7016 "Version of JavaScript supported, plus minor js2 version.")
7017
7018 (defmacro js2-record-face (face)
7019 "Record a style run of FACE for the current token."
7020 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7021
7022 (defsubst js2-node-end (n)
7023 "Computes the absolute end of node N.
7024 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7025 is only true until the node is added to its parent; i.e., while parsing."
7026 (+ (js2-node-pos n)
7027 (js2-node-len n)))
7028
7029 (defsubst js2-record-comment ()
7030 "Record a comment in `js2-scanned-comments'."
7031 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7032 :format js2-ts-comment-type)
7033 js2-scanned-comments)
7034 (when js2-parse-ide-mode
7035 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7036 'font-lock-doc-face
7037 'font-lock-comment-face))
7038 (when (memq js2-ts-comment-type '(html preprocessor))
7039 ;; Tell cc-engine the bounds of the comment.
7040 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7041
7042 ;; This function is called depressingly often, so it should be fast.
7043 ;; Most of the time it's looking at the same token it peeked before.
7044 (defsubst js2-peek-token ()
7045 "Returns the next token without consuming it.
7046 If previous token was consumed, calls scanner to get new token.
7047 If previous token was -not- consumed, returns it (idempotent).
7048
7049 This function will not return a newline (js2-EOL) - instead, it
7050 gobbles newlines until it finds a non-newline token, and flags
7051 that token as appearing just after a newline.
7052
7053 This function will also not return a js2-COMMENT. Instead, it
7054 records comments found in `js2-scanned-comments'. If the token
7055 returned by this function immediately follows a jsdoc comment,
7056 the token is flagged as such.
7057
7058 Note that this function always returned the un-flagged token!
7059 The flags, if any, are saved in `js2-current-flagged-token'."
7060 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7061 js2-current-token ; most common case - return already-peeked token
7062 (let ((tt (js2-get-token)) ; call scanner
7063 saw-eol
7064 face)
7065 ;; process comments and whitespace
7066 (while (or (= tt js2-EOL)
7067 (= tt js2-COMMENT))
7068 (if (= tt js2-EOL)
7069 (setq saw-eol t)
7070 (setq saw-eol nil)
7071 (if js2-record-comments
7072 (js2-record-comment)))
7073 (setq tt (js2-get-token))) ; call scanner
7074 (setq js2-current-token tt
7075 js2-current-flagged-token (if saw-eol
7076 (logior tt js2-ti-after-eol)
7077 tt))
7078 ;; perform lexical fontification as soon as token is scanned
7079 (when js2-parse-ide-mode
7080 (cond
7081 ((minusp tt)
7082 (js2-record-face 'js2-error))
7083 ((setq face (aref js2-kwd-tokens tt))
7084 (js2-record-face face))
7085 ((and (= tt js2-NAME)
7086 (equal js2-ts-string "undefined"))
7087 (js2-record-face 'font-lock-constant-face))))
7088 tt))) ; return unflagged token
7089
7090 (defsubst js2-peek-flagged-token ()
7091 "Returns the current token along with any flags set for it."
7092 (js2-peek-token)
7093 js2-current-flagged-token)
7094
7095 (defsubst js2-consume-token ()
7096 (setq js2-current-flagged-token js2-EOF))
7097
7098 (defsubst js2-next-token ()
7099 (prog1
7100 (js2-peek-token)
7101 (js2-consume-token)))
7102
7103 (defsubst js2-next-flagged-token ()
7104 (js2-peek-token)
7105 (prog1 js2-current-flagged-token
7106 (js2-consume-token)))
7107
7108 (defsubst js2-match-token (match)
7109 "Consume and return t if next token matches MATCH, a bytecode.
7110 Returns nil and consumes nothing if MATCH is not the next token."
7111 (if (/= (js2-peek-token) match)
7112 nil
7113 (js2-consume-token)
7114 t))
7115
7116 (defsubst js2-valid-prop-name-token (tt)
7117 (or (= tt js2-NAME)
7118 (and js2-allow-keywords-as-property-names
7119 (plusp tt)
7120 (aref js2-kwd-tokens tt))))
7121
7122 (defsubst js2-match-prop-name ()
7123 "Consume token and return t if next token is a valid property name.
7124 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7125 is non-nil and it's a keyword token."
7126 (if (js2-valid-prop-name-token (js2-peek-token))
7127 (progn
7128 (js2-consume-token)
7129 t)
7130 nil))
7131
7132 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7133 (if (js2-match-prop-name)
7134 t
7135 (js2-report-error msg-id nil pos len)
7136 nil))
7137
7138 (defsubst js2-peek-token-or-eol ()
7139 "Return js2-EOL if the current token immediately follows a newline.
7140 Else returns the current token. Used in situations where we don't
7141 consider certain token types valid if they are preceded by a newline.
7142 One example is the postfix ++ or -- operator, which has to be on the
7143 same line as its operand."
7144 (let ((tt (js2-peek-token)))
7145 ;; Check for last peeked token flags
7146 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7147 js2-EOL
7148 tt)))
7149
7150 (defsubst js2-set-check-for-label ()
7151 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7152 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7153
7154 (defsubst js2-must-match (token msg-id &optional pos len)
7155 "Match next token to token code TOKEN, or record a syntax error.
7156 MSG-ID is the error message to report if the match fails.
7157 Returns t on match, nil if no match."
7158 (if (js2-match-token token)
7159 t
7160 (js2-report-error msg-id nil pos len)
7161 nil))
7162
7163 (defsubst js2-inside-function ()
7164 (plusp js2-nesting-of-function))
7165
7166 (defsubst js2-set-requires-activation ()
7167 (if (js2-function-node-p js2-current-script-or-fn)
7168 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7169
7170 (defsubst js2-check-activation-name (name token)
7171 (when (js2-inside-function)
7172 ;; skip language-version 1.2 check from Rhino
7173 (if (or (string= "arguments" name)
7174 (and js2-compiler-activation-names ; only used in codegen
7175 (gethash name js2-compiler-activation-names)))
7176 (js2-set-requires-activation))))
7177
7178 (defsubst js2-set-is-generator ()
7179 (if (js2-function-node-p js2-current-script-or-fn)
7180 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7181
7182 (defsubst js2-must-have-xml ()
7183 (unless js2-compiler-xml-available
7184 (js2-report-error "msg.XML.not.available")))
7185
7186 (defsubst js2-push-scope (scope)
7187 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7188 (assert (js2-scope-p scope))
7189 (assert (null (js2-scope-parent-scope scope)))
7190 (assert (not (eq js2-current-scope scope)))
7191 (setf (js2-scope-parent-scope scope) js2-current-scope
7192 js2-current-scope scope))
7193
7194 (defsubst js2-pop-scope ()
7195 (setq js2-current-scope
7196 (js2-scope-parent-scope js2-current-scope)))
7197
7198 (defsubst js2-enter-loop (loop-node)
7199 (push loop-node js2-loop-set)
7200 (push loop-node js2-loop-and-switch-set)
7201 (js2-push-scope loop-node)
7202 ;; Tell the current labeled statement (if any) its statement,
7203 ;; and set the jump target of the first label to the loop.
7204 ;; These are used in `js2-parse-continue' to verify that the
7205 ;; continue target is an actual labeled loop. (And for codegen.)
7206 (when js2-labeled-stmt
7207 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7208 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7209 js2-labeled-stmt))) loop-node)))
7210
7211 (defsubst js2-exit-loop ()
7212 (pop js2-loop-set)
7213 (pop js2-loop-and-switch-set)
7214 (js2-pop-scope))
7215
7216 (defsubst js2-enter-switch (switch-node)
7217 (push switch-node js2-loop-and-switch-set))
7218
7219 (defsubst js2-exit-switch ()
7220 (pop js2-loop-and-switch-set))
7221
7222 (defun js2-parse (&optional buf cb)
7223 "Tells the js2 parser to parse a region of JavaScript.
7224
7225 BUF is a buffer or buffer name containing the code to parse.
7226 Call `narrow-to-region' first to parse only part of the buffer.
7227
7228 The returned AST root node is given some additional properties:
7229 `node-count' - total number of nodes in the AST
7230 `buffer' - BUF. The buffer it refers to may change or be killed,
7231 so the value is not necessarily reliable.
7232
7233 An optional callback CB can be specified to report parsing
7234 progress. If `(functionp CB)' returns t, it will be called with
7235 the current line number once before parsing begins, then again
7236 each time the lexer reaches a new line number.
7237
7238 CB can also be a list of the form `(symbol cb ...)' to specify
7239 multiple callbacks with different criteria. Each symbol is a
7240 criterion keyword, and the following element is the callback to
7241 call
7242
7243 :line - called whenever the line number changes
7244 :token - called for each new token consumed
7245
7246 The list of criteria could be extended to include entering or
7247 leaving a statement, an expression, or a function definition."
7248 (if (and cb (not (functionp cb)))
7249 (error "criteria callbacks not yet implemented"))
7250 (let ((inhibit-point-motion-hooks t)
7251 (js2-compiler-xml-available (>= js2-language-version 160))
7252 ;; This is a recursive-descent parser, so give it a big stack.
7253 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7254 (max-specpdl-size (max max-specpdl-size 3000))
7255 (case-fold-search nil)
7256 ast)
7257 (or buf (setq buf (current-buffer)))
7258 (message nil) ; clear any error message from previous parse
7259 (save-excursion
7260 (set-buffer buf)
7261 (setq js2-scanned-comments nil
7262 js2-parsed-errors nil
7263 js2-parsed-warnings nil
7264 js2-imenu-recorder nil
7265 js2-imenu-function-map nil
7266 js2-label-set nil)
7267 (js2-init-scanner)
7268 (setq ast (js2-with-unmodifying-text-property-changes
7269 (js2-do-parse)))
7270 (unless js2-ts-hit-eof
7271 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7272 (setf (js2-ast-root-errors ast) js2-parsed-errors
7273 (js2-ast-root-warnings ast) js2-parsed-warnings)
7274 ;; if we didn't find any declarations, put a dummy in this list so we
7275 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7276 (unless js2-imenu-recorder
7277 (setq js2-imenu-recorder 'empty))
7278 (run-hooks 'js2-parse-finished-hook)
7279 ast)))
7280
7281 ;; Corresponds to Rhino's Parser.parse() method.
7282 (defun js2-do-parse ()
7283 "Parse current buffer starting from current point.
7284 Scanner should be initialized."
7285 (let ((pos js2-ts-cursor)
7286 (end js2-ts-cursor) ; in case file is empty
7287 root n tt)
7288 ;; initialize buffer-local parsing vars
7289 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7290 js2-current-script-or-fn root
7291 js2-current-scope root
7292 js2-current-flagged-token js2-EOF
7293 js2-nesting-of-function 0
7294 js2-labeled-stmt nil
7295 js2-recorded-assignments nil) ; for js2-highlight
7296 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7297 (if (= tt js2-FUNCTION)
7298 (progn
7299 (js2-consume-token)
7300 (setq n (js2-parse-function (if js2-called-by-compile-function
7301 'FUNCTION_EXPRESSION
7302 'FUNCTION_STATEMENT)))
7303 (js2-record-imenu-functions n))
7304 ;; not a function - parse a statement
7305 (setq n (js2-parse-statement)))
7306 ;; add function or statement to script
7307 (setq end (js2-node-end n))
7308 (js2-block-node-push root n))
7309 ;; add comments to root in lexical order
7310 (when js2-scanned-comments
7311 ;; if we find a comment beyond end of normal kids, use its end
7312 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7313 (dolist (comment js2-scanned-comments)
7314 (push comment (js2-ast-root-comments root))
7315 (js2-node-add-children root comment)))
7316 (setf (js2-node-len root) (- end pos))
7317 ;; Give extensions a chance to muck with things before highlighting starts.
7318 (dolist (callback js2-post-parse-callbacks)
7319 (funcall callback))
7320 (js2-highlight-undeclared-vars)
7321 root))
7322
7323 (defun js2-function-parser ()
7324 (js2-consume-token)
7325 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7326
7327 (defun js2-parse-function-closure-body (fn-node)
7328 "Parse a JavaScript 1.8 function closure body."
7329 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7330 (if js2-ts-hit-eof
7331 (js2-report-error "msg.no.brace.body" nil
7332 (js2-node-pos fn-node)
7333 (- js2-ts-cursor (js2-node-pos fn-node)))
7334 (js2-node-add-children fn-node
7335 (setf (js2-function-node-body fn-node)
7336 (js2-parse-expr))))))
7337
7338 (defun js2-parse-function-body (fn-node)
7339 (js2-must-match js2-LC "msg.no.brace.body"
7340 (js2-node-pos fn-node)
7341 (- js2-ts-cursor (js2-node-pos fn-node)))
7342 (let ((pos js2-token-beg) ; LC position
7343 (pn (make-js2-block-node)) ; starts at LC position
7344 tt
7345 end)
7346 (incf js2-nesting-of-function)
7347 (unwind-protect
7348 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7349 (= tt js2-EOF)
7350 (= tt js2-RC)))
7351 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7352 (js2-parse-statement)
7353 (js2-consume-token)
7354 (js2-parse-function 'FUNCTION_STATEMENT))))
7355 (decf js2-nesting-of-function))
7356 (setq end js2-token-end) ; assume no curly and leave at current token
7357 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7358 (setq end js2-token-end))
7359 (setf (js2-node-pos pn) pos
7360 (js2-node-len pn) (- end pos))
7361 (setf (js2-function-node-body fn-node) pn)
7362 (js2-node-add-children fn-node pn)
7363 pn))
7364
7365 (defun js2-parse-function-params (fn-node pos)
7366 (if (js2-match-token js2-RP)
7367 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7368 (let (params len param)
7369 (loop for tt = (js2-peek-token)
7370 do
7371 (cond
7372 ;; destructuring param
7373 ((or (= tt js2-LB) (= tt js2-LC))
7374 (push (js2-parse-primary-expr) params))
7375 ;; simple name
7376 (t
7377 (js2-must-match js2-NAME "msg.no.parm")
7378 (js2-record-face 'js2-function-param)
7379 (setq param (js2-create-name-node))
7380 (js2-define-symbol js2-LP js2-ts-string param)
7381 (push param params)))
7382 while
7383 (js2-match-token js2-COMMA))
7384 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7385 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7386 (dolist (p params)
7387 (js2-node-add-children fn-node p)
7388 (push p (js2-function-node-params fn-node))))))
7389
7390 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7391 "Possibly show inconsistent-return warning.
7392 Last token scanned is the close-curly for the function body."
7393 (when (and js2-mode-show-strict-warnings
7394 js2-strict-inconsistent-return-warning
7395 (not (js2-has-consistent-return-usage
7396 (js2-function-node-body fn-node))))
7397 ;; Have it extend from close-curly to bol or beginning of block.
7398 (let ((pos (save-excursion
7399 (goto-char js2-token-end)
7400 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7401 (point-at-bol))))
7402 (end js2-token-end))
7403 (if (plusp (js2-name-node-length name))
7404 (js2-add-strict-warning "msg.no.return.value"
7405 (js2-name-node-name name) pos end)
7406 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7407
7408 (defun js2-parse-function (function-type)
7409 "Function parser. FUNCTION-TYPE is a symbol."
7410 (let ((pos js2-token-beg) ; start of 'function' keyword
7411 name
7412 name-beg
7413 name-end
7414 fn-node
7415 lp
7416 (synthetic-type function-type)
7417 member-expr-node)
7418 ;; parse function name, expression, or non-name (anonymous)
7419 (cond
7420 ;; function foo(...)
7421 ((js2-match-token js2-NAME)
7422 (setq name (js2-create-name-node t)
7423 name-beg js2-token-beg
7424 name-end js2-token-end)
7425 (unless (js2-match-token js2-LP)
7426 (when js2-allow-member-expr-as-function-name
7427 ;; function foo.bar(...)
7428 (setq member-expr-node name
7429 name nil
7430 member-expr-node (js2-parse-member-expr-tail
7431 nil member-expr-node)))
7432 (js2-must-match js2-LP "msg.no.paren.parms")))
7433 ((js2-match-token js2-LP)
7434 nil) ; anonymous function: leave name as null
7435 (t
7436 ;; function random-member-expr(...)
7437 (when js2-allow-member-expr-as-function-name
7438 ;; Note that memberExpr can not start with '(' like
7439 ;; in function (1+2).toString(), because 'function (' already
7440 ;; processed as anonymous function
7441 (setq member-expr-node (js2-parse-member-expr)))
7442 (js2-must-match js2-LP "msg.no.paren.parms")))
7443 (if (= js2-current-token js2-LP) ; eventually matched LP?
7444 (setq lp js2-token-beg))
7445 (if member-expr-node
7446 (progn
7447 (setq synthetic-type 'FUNCTION_EXPRESSION)
7448 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7449 (if name
7450 (js2-set-face name-beg name-end
7451 'font-lock-function-name-face 'record)))
7452 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7453 (plusp (js2-name-node-length name)))
7454 ;; Function statements define a symbol in the enclosing scope
7455 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7456 (setf fn-node (make-js2-function-node :pos pos
7457 :name name
7458 :form function-type
7459 :lp (if lp (- lp pos))))
7460 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7461 ;; 1. Nested functions are not affected by the dynamic scope flag
7462 ;; as dynamic scope is already a parent of their scope.
7463 ;; 2. Functions defined under the with statement also immune to
7464 ;; this setup, in which case dynamic scope is ignored in favor
7465 ;; of the with object.
7466 (setf (js2-function-node-ignore-dynamic fn-node) t))
7467 ;; dynamically bind all the per-function variables
7468 (let ((js2-current-script-or-fn fn-node)
7469 (js2-current-scope fn-node)
7470 (js2-nesting-of-with 0)
7471 (js2-end-flags 0)
7472 js2-label-set
7473 js2-loop-set
7474 js2-loop-and-switch-set)
7475 (js2-parse-function-params fn-node pos)
7476 (if (and (>= js2-language-version 180)
7477 (/= (js2-peek-token) js2-LC))
7478 (js2-parse-function-closure-body fn-node)
7479 (js2-parse-function-body fn-node))
7480 (if name
7481 (js2-node-add-children fn-node name))
7482 (js2-check-inconsistent-return-warning fn-node name)
7483 ;; Function expressions define a name only in the body of the
7484 ;; function, and only if not hidden by a parameter name
7485 (if (and name
7486 (eq synthetic-type 'FUNCTION_EXPRESSION)
7487 (null (js2-scope-get-symbol js2-current-scope
7488 (js2-name-node-name name))))
7489 (js2-define-symbol js2-FUNCTION
7490 (js2-name-node-name name)
7491 fn-node))
7492 (if (and name
7493 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7494 (js2-record-imenu-functions fn-node)))
7495 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7496 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7497 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7498 ;; We wait until after parsing the function to set its parent scope,
7499 ;; since `js2-define-symbol' needs the defining-scope check to stop
7500 ;; at the function boundary when checking for redeclarations.
7501 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7502 fn-node))
7503
7504 (defun js2-parse-statements (&optional parent)
7505 "Parse a statement list. Last token consumed must be js2-LC.
7506
7507 PARENT can be a `js2-block-node', in which case the statements are
7508 appended to PARENT. Otherwise a new `js2-block-node' is created
7509 and returned.
7510
7511 This function does not match the closing js2-RC: the caller
7512 matches the RC so it can provide a suitable error message if not
7513 matched. This means it's up to the caller to set the length of
7514 the node to include the closing RC. The node start pos is set to
7515 the absolute buffer start position, and the caller should fix it
7516 up to be relative to the parent node. All children of this block
7517 node are given relative start positions and correct lengths."
7518 (let ((pn (or parent (make-js2-block-node)))
7519 tt)
7520 (setf (js2-node-pos pn) js2-token-beg)
7521 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7522 (/= tt js2-RC))
7523 (js2-block-node-push pn (js2-parse-statement)))
7524 pn))
7525
7526 (defun js2-parse-statement ()
7527 (let (tt pn beg end)
7528 ;; coarse-grained user-interrupt check - needs work
7529 (and js2-parse-interruptable-p
7530 (zerop (% (incf js2-parse-stmt-count)
7531 js2-statements-per-pause))
7532 (input-pending-p)
7533 (throw 'interrupted t))
7534 (setq pn (js2-statement-helper))
7535 ;; no-side-effects warning check
7536 (unless (js2-node-has-side-effects pn)
7537 (setq end (js2-node-end pn))
7538 (save-excursion
7539 (goto-char end)
7540 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7541 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7542 pn))
7543
7544 ;; These correspond to the switch cases in Parser.statementHelper
7545 (defconst js2-parsers
7546 (let ((parsers (make-vector js2-num-tokens
7547 #'js2-parse-expr-stmt)))
7548 (aset parsers js2-BREAK #'js2-parse-break)
7549 (aset parsers js2-CONST #'js2-parse-const-var)
7550 (aset parsers js2-CONTINUE #'js2-parse-continue)
7551 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7552 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7553 (aset parsers js2-DO #'js2-parse-do)
7554 (aset parsers js2-FOR #'js2-parse-for)
7555 (aset parsers js2-FUNCTION #'js2-function-parser)
7556 (aset parsers js2-IF #'js2-parse-if)
7557 (aset parsers js2-LC #'js2-parse-block)
7558 (aset parsers js2-LET #'js2-parse-let-stmt)
7559 (aset parsers js2-NAME #'js2-parse-name-or-label)
7560 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7561 (aset parsers js2-SEMI #'js2-parse-semi)
7562 (aset parsers js2-SWITCH #'js2-parse-switch)
7563 (aset parsers js2-THROW #'js2-parse-throw)
7564 (aset parsers js2-TRY #'js2-parse-try)
7565 (aset parsers js2-VAR #'js2-parse-const-var)
7566 (aset parsers js2-WHILE #'js2-parse-while)
7567 (aset parsers js2-WITH #'js2-parse-with)
7568 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7569 parsers)
7570 "A vector mapping token types to parser functions.")
7571
7572 (defsubst js2-parse-warn-missing-semi (beg end)
7573 (and js2-mode-show-strict-warnings
7574 js2-strict-missing-semi-warning
7575 (js2-add-strict-warning
7576 "msg.missing.semi" nil
7577 ;; back up to beginning of statement or line
7578 (max beg (save-excursion
7579 (goto-char end)
7580 (point-at-bol)))
7581 end)))
7582
7583 (defconst js2-no-semi-insertion
7584 (list js2-IF
7585 js2-SWITCH
7586 js2-WHILE
7587 js2-DO
7588 js2-FOR
7589 js2-TRY
7590 js2-WITH
7591 js2-LC
7592 js2-ERROR
7593 js2-SEMI
7594 js2-FUNCTION)
7595 "List of tokens that don't do automatic semicolon insertion.")
7596
7597 (defconst js2-autoinsert-semi-and-warn
7598 (list js2-ERROR js2-EOF js2-RC))
7599
7600 (defun js2-statement-helper ()
7601 (let* ((tt (js2-peek-token))
7602 (first-tt tt)
7603 (beg js2-token-beg)
7604 (parser (if (= tt js2-ERROR)
7605 #'js2-parse-semi
7606 (aref js2-parsers tt)))
7607 pn
7608 tt-flagged)
7609 ;; If the statement is set, then it's been told its label by now.
7610 (and js2-labeled-stmt
7611 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7612 (setq js2-labeled-stmt nil))
7613 (setq pn (funcall parser))
7614 ;; Don't do auto semi insertion for certain statement types.
7615 (unless (or (memq first-tt js2-no-semi-insertion)
7616 (js2-labeled-stmt-node-p pn))
7617 (js2-auto-insert-semicolon pn))
7618 pn))
7619
7620 (defun js2-auto-insert-semicolon (pn)
7621 (let* ((tt-flagged (js2-peek-flagged-token))
7622 (tt (logand tt-flagged js2-clear-ti-mask))
7623 (pos (js2-node-pos pn)))
7624 (cond
7625 ((= tt js2-SEMI)
7626 ;; Consume ';' as a part of expression
7627 (js2-consume-token)
7628 ;; extend the node bounds to include the semicolon.
7629 (setf (js2-node-len pn) (- js2-token-end pos)))
7630 ((memq tt js2-autoinsert-semi-and-warn)
7631 ;; Autoinsert ;
7632 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7633 (t
7634 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7635 ;; Report error if no EOL or autoinsert ';' otherwise
7636 (js2-report-error "msg.no.semi.stmt")
7637 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7638
7639 (defun js2-parse-condition ()
7640 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7641 The parens are discarded and the expression node is returned.
7642 The `pos' field of the return value is set to an absolute position
7643 that must be fixed up by the caller.
7644 Return value is a list (EXPR LP RP), with absolute paren positions."
7645 (let (pn lp rp)
7646 (if (js2-must-match js2-LP "msg.no.paren.cond")
7647 (setq lp js2-token-beg))
7648 (setq pn (js2-parse-expr))
7649 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7650 (setq rp js2-token-beg))
7651 ;; Report strict warning on code like "if (a = 7) ..."
7652 (if (and js2-strict-cond-assign-warning
7653 (js2-assign-node-p pn))
7654 (js2-add-strict-warning "msg.equal.as.assign" nil
7655 (js2-node-pos pn)
7656 (+ (js2-node-pos pn)
7657 (js2-node-len pn))))
7658 (list pn lp rp)))
7659
7660 (defun js2-parse-if ()
7661 "Parser for if-statement. Last matched token must be js2-IF."
7662 (let ((pos js2-token-beg)
7663 cond
7664 if-true
7665 if-false
7666 else-pos
7667 end
7668 pn)
7669 (js2-consume-token)
7670 (setq cond (js2-parse-condition)
7671 if-true (js2-parse-statement)
7672 if-false (if (js2-match-token js2-ELSE)
7673 (progn
7674 (setq else-pos (- js2-token-beg pos))
7675 (js2-parse-statement)))
7676 end (js2-node-end (or if-false if-true))
7677 pn (make-js2-if-node :pos pos
7678 :len (- end pos)
7679 :condition (car cond)
7680 :then-part if-true
7681 :else-part if-false
7682 :else-pos else-pos
7683 :lp (js2-relpos (second cond) pos)
7684 :rp (js2-relpos (third cond) pos)))
7685 (js2-node-add-children pn (car cond) if-true if-false)
7686 pn))
7687
7688 (defun js2-parse-switch ()
7689 "Parser for if-statement. Last matched token must be js2-SWITCH."
7690 (let ((pos js2-token-beg)
7691 tt
7692 pn
7693 discriminant
7694 has-default
7695 case-expr
7696 case-node
7697 case-pos
7698 cases
7699 stmt
7700 lp
7701 rp)
7702 (js2-consume-token)
7703 (if (js2-must-match js2-LP "msg.no.paren.switch")
7704 (setq lp js2-token-beg))
7705 (setq discriminant (js2-parse-expr)
7706 pn (make-js2-switch-node :discriminant discriminant
7707 :pos pos
7708 :lp (js2-relpos lp pos)))
7709 (js2-node-add-children pn discriminant)
7710 (js2-enter-switch pn)
7711 (unwind-protect
7712 (progn
7713 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7714 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7715 (js2-must-match js2-LC "msg.no.brace.switch")
7716 (catch 'break
7717 (while t
7718 (setq tt (js2-next-token)
7719 case-pos js2-token-beg)
7720 (cond
7721 ((= tt js2-RC)
7722 (setf (js2-node-len pn) (- js2-token-end pos))
7723 (throw 'break nil)) ; done
7724 ((= tt js2-CASE)
7725 (setq case-expr (js2-parse-expr))
7726 (js2-must-match js2-COLON "msg.no.colon.case"))
7727 ((= tt js2-DEFAULT)
7728 (if has-default
7729 (js2-report-error "msg.double.switch.default"))
7730 (setq has-default t
7731 case-expr nil)
7732 (js2-must-match js2-COLON "msg.no.colon.case"))
7733 (t
7734 (js2-report-error "msg.bad.switch")
7735 (throw 'break nil)))
7736 (setq case-node (make-js2-case-node :pos case-pos
7737 :len (- js2-token-end case-pos)
7738 :expr case-expr))
7739 (js2-node-add-children case-node case-expr)
7740 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7741 (/= tt js2-CASE)
7742 (/= tt js2-DEFAULT)
7743 (/= tt js2-EOF))
7744 (setf stmt (js2-parse-statement)
7745 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7746 (js2-block-node-push case-node stmt))
7747 (push case-node cases)))
7748 ;; add cases last, as pushing reverses the order to be correct
7749 (dolist (kid cases)
7750 (js2-node-add-children pn kid)
7751 (push kid (js2-switch-node-cases pn)))
7752 pn) ; return value
7753 (js2-exit-switch))))
7754
7755 (defun js2-parse-while ()
7756 "Parser for while-statement. Last matched token must be js2-WHILE."
7757 (let ((pos js2-token-beg)
7758 (pn (make-js2-while-node))
7759 cond
7760 body)
7761 (js2-consume-token)
7762 (js2-enter-loop pn)
7763 (unwind-protect
7764 (progn
7765 (setf cond (js2-parse-condition)
7766 (js2-while-node-condition pn) (car cond)
7767 body (js2-parse-statement)
7768 (js2-while-node-body pn) body
7769 (js2-node-len pn) (- (js2-node-end body) pos)
7770 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7771 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7772 (js2-node-add-children pn body (car cond)))
7773 (js2-exit-loop))
7774 pn))
7775
7776 (defun js2-parse-do ()
7777 "Parser for do-statement. Last matched token must be js2-DO."
7778 (let ((pos js2-token-beg)
7779 (pn (make-js2-do-node))
7780 cond
7781 body
7782 end)
7783 (js2-consume-token)
7784 (js2-enter-loop pn)
7785 (unwind-protect
7786 (progn
7787 (setq body (js2-parse-statement))
7788 (js2-must-match js2-WHILE "msg.no.while.do")
7789 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7790 cond (js2-parse-condition)
7791 (js2-do-node-condition pn) (car cond)
7792 (js2-do-node-body pn) body
7793 end js2-ts-cursor
7794 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7795 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7796 (js2-node-add-children pn (car cond) body))
7797 (js2-exit-loop))
7798 ;; Always auto-insert semicolon to follow SpiderMonkey:
7799 ;; It is required by ECMAScript but is ignored by the rest of
7800 ;; world; see bug 238945
7801 (if (js2-match-token js2-SEMI)
7802 (setq end js2-ts-cursor))
7803 (setf (js2-node-len pn) (- end pos))
7804 pn))
7805
7806 (defun js2-parse-for ()
7807 "Parser for for-statement. Last matched token must be js2-FOR.
7808 Parses for, for-in, and for each-in statements."
7809 (let ((for-pos js2-token-beg)
7810 pn
7811 is-for-each
7812 is-for-in
7813 in-pos
7814 each-pos
7815 tmp-pos
7816 init ; Node init is also foo in 'foo in object'
7817 cond ; Node cond is also object in 'foo in object'
7818 incr ; 3rd section of for-loop initializer
7819 body
7820 tt
7821 lp
7822 rp)
7823 (js2-consume-token)
7824 ;; See if this is a for each () instead of just a for ()
7825 (when (js2-match-token js2-NAME)
7826 (if (string= "each" js2-ts-string)
7827 (progn
7828 (setq is-for-each t
7829 each-pos (- js2-token-beg for-pos)) ; relative
7830 (js2-record-face 'font-lock-keyword-face))
7831 (js2-report-error "msg.no.paren.for")))
7832 (if (js2-must-match js2-LP "msg.no.paren.for")
7833 (setq lp (- js2-token-beg for-pos)))
7834 (setq tt (js2-peek-token))
7835 ;; parse init clause
7836 (let ((js2-in-for-init t)) ; set as dynamic variable
7837 (cond
7838 ((= tt js2-SEMI)
7839 (setq init (make-js2-empty-expr-node)))
7840 ((or (= tt js2-VAR) (= tt js2-LET))
7841 (js2-consume-token)
7842 (setq init (js2-parse-variables tt js2-token-beg)))
7843 (t
7844 (setq init (js2-parse-expr)))))
7845 (if (js2-match-token js2-IN)
7846 (setq is-for-in t
7847 in-pos (- js2-token-beg for-pos)
7848 cond (js2-parse-expr)) ; object over which we're iterating
7849 ;; else ordinary for loop - parse cond and incr
7850 (js2-must-match js2-SEMI "msg.no.semi.for")
7851 (setq cond (if (= (js2-peek-token) js2-SEMI)
7852 (make-js2-empty-expr-node) ; no loop condition
7853 (js2-parse-expr)))
7854 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7855 (setq tmp-pos js2-token-end
7856 incr (if (= (js2-peek-token) js2-RP)
7857 (make-js2-empty-expr-node :pos tmp-pos)
7858 (js2-parse-expr))))
7859 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7860 (setq rp (- js2-token-beg for-pos)))
7861 (if (not is-for-in)
7862 (setq pn (make-js2-for-node :init init
7863 :condition cond
7864 :update incr
7865 :lp lp
7866 :rp rp))
7867 ;; cond could be null if 'in obj' got eaten by the init node.
7868 (if (js2-infix-node-p init)
7869 ;; it was (foo in bar) instead of (var foo in bar)
7870 (setq cond (js2-infix-node-right init)
7871 init (js2-infix-node-left init))
7872 (if (and (js2-var-decl-node-p init)
7873 (> (length (js2-var-decl-node-kids init)) 1))
7874 (js2-report-error "msg.mult.index")))
7875 (setq pn (make-js2-for-in-node :iterator init
7876 :object cond
7877 :in-pos in-pos
7878 :foreach-p is-for-each
7879 :each-pos each-pos
7880 :lp lp
7881 :rp rp)))
7882 (unwind-protect
7883 (progn
7884 (js2-enter-loop pn)
7885 ;; We have to parse the body -after- creating the loop node,
7886 ;; so that the loop node appears in the js2-loop-set, allowing
7887 ;; break/continue statements to find the enclosing loop.
7888 (setf body (js2-parse-statement)
7889 (js2-loop-node-body pn) body
7890 (js2-node-pos pn) for-pos
7891 (js2-node-len pn) (- (js2-node-end body) for-pos))
7892 (js2-node-add-children pn init cond incr body))
7893 ;; finally
7894 (js2-exit-loop))
7895 pn))
7896
7897 (defun js2-parse-try ()
7898 "Parser for try-statement. Last matched token must be js2-TRY."
7899 (let ((try-pos js2-token-beg)
7900 try-end
7901 try-block
7902 catch-blocks
7903 finally-block
7904 saw-default-catch
7905 peek
7906 var-name
7907 catch-cond
7908 catch-node
7909 guard-kwd
7910 catch-pos
7911 finally-pos
7912 pn
7913 block
7914 lp
7915 rp)
7916 (js2-consume-token)
7917 (if (/= (js2-peek-token) js2-LC)
7918 (js2-report-error "msg.no.brace.try"))
7919 (setq try-block (js2-parse-statement)
7920 try-end (js2-node-end try-block)
7921 peek (js2-peek-token))
7922 (cond
7923 ((= peek js2-CATCH)
7924 (while (js2-match-token js2-CATCH)
7925 (setq catch-pos js2-token-beg
7926 guard-kwd nil
7927 catch-cond nil
7928 lp nil
7929 rp nil)
7930 (if saw-default-catch
7931 (js2-report-error "msg.catch.unreachable"))
7932 (if (js2-must-match js2-LP "msg.no.paren.catch")
7933 (setq lp (- js2-token-beg catch-pos)))
7934 (js2-must-match js2-NAME "msg.bad.catchcond")
7935 (setq var-name (js2-create-name-node))
7936 (if (js2-match-token js2-IF)
7937 (setq guard-kwd (- js2-token-beg catch-pos)
7938 catch-cond (js2-parse-expr))
7939 (setq saw-default-catch t))
7940 (if (js2-must-match js2-RP "msg.bad.catchcond")
7941 (setq rp (- js2-token-beg catch-pos)))
7942 (js2-must-match js2-LC "msg.no.brace.catchblock")
7943 (setq block (js2-parse-statements)
7944 try-end (js2-node-end block)
7945 catch-node (make-js2-catch-node :pos catch-pos
7946 :var-name var-name
7947 :guard-expr catch-cond
7948 :guard-kwd guard-kwd
7949 :block block
7950 :lp lp
7951 :rp rp))
7952 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7953 (setq try-end js2-token-beg))
7954 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7955 (js2-node-len catch-node) (- try-end catch-pos))
7956 (js2-node-add-children catch-node var-name catch-cond block)
7957 (push catch-node catch-blocks)))
7958 ((/= peek js2-FINALLY)
7959 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7960 (js2-node-pos try-block)
7961 (- (setq try-end (js2-node-end try-block))
7962 (js2-node-pos try-block)))))
7963 (when (js2-match-token js2-FINALLY)
7964 (setq finally-pos js2-token-beg
7965 block (js2-parse-statement)
7966 try-end (js2-node-end block)
7967 finally-block (make-js2-finally-node :pos finally-pos
7968 :len (- try-end finally-pos)
7969 :body block))
7970 (js2-node-add-children finally-block block))
7971 (setq pn (make-js2-try-node :pos try-pos
7972 :len (- try-end try-pos)
7973 :try-block try-block
7974 :finally-block finally-block))
7975 (js2-node-add-children pn try-block finally-block)
7976 ;; push them onto the try-node, which reverses and corrects their order
7977 (dolist (cb catch-blocks)
7978 (js2-node-add-children pn cb)
7979 (push cb (js2-try-node-catch-clauses pn)))
7980 pn))
7981
7982 (defun js2-parse-throw ()
7983 "Parser for throw-statement. Last matched token must be js2-THROW."
7984 (let ((pos js2-token-beg)
7985 expr
7986 pn)
7987 (js2-consume-token)
7988 (if (= (js2-peek-token-or-eol) js2-EOL)
7989 ;; ECMAScript does not allow new lines before throw expression,
7990 ;; see bug 256617
7991 (js2-report-error "msg.bad.throw.eol"))
7992 (setq expr (js2-parse-expr)
7993 pn (make-js2-throw-node :pos pos
7994 :len (- (js2-node-end expr) pos)
7995 :expr expr))
7996 (js2-node-add-children pn expr)
7997 pn))
7998
7999 (defsubst js2-match-jump-label-name (label-name)
8000 "If break/continue specified a label, return that label's labeled stmt.
8001 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8002 does not match an existing label, reports an error and returns nil."
8003 (let ((bundle (cdr (assoc label-name js2-label-set))))
8004 (if (null bundle)
8005 (js2-report-error "msg.undef.label"))
8006 bundle))
8007
8008 (defun js2-parse-break ()
8009 "Parser for break-statement. Last matched token must be js2-BREAK."
8010 (let ((pos js2-token-beg)
8011 (end js2-token-end)
8012 break-target ; statement to break from
8013 break-label ; in "break foo", name-node representing the foo
8014 labels ; matching labeled statement to break to
8015 pn)
8016 (js2-consume-token) ; `break'
8017 (when (eq (js2-peek-token-or-eol) js2-NAME)
8018 (js2-consume-token)
8019 (setq break-label (js2-create-name-node)
8020 end (js2-node-end break-label)
8021 ;; matchJumpLabelName only matches if there is one
8022 labels (js2-match-jump-label-name js2-ts-string)
8023 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8024 (unless (or break-target break-label)
8025 ;; no break target specified - try for innermost enclosing loop/switch
8026 (if (null js2-loop-and-switch-set)
8027 (unless break-label
8028 (js2-report-error "msg.bad.break" nil pos (length "break")))
8029 (setq break-target (car js2-loop-and-switch-set))))
8030 (setq pn (make-js2-break-node :pos pos
8031 :len (- end pos)
8032 :label break-label
8033 :target break-target))
8034 (js2-node-add-children pn break-label) ; but not break-target
8035 pn))
8036
8037 (defun js2-parse-continue ()
8038 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8039 (let ((pos js2-token-beg)
8040 (end js2-token-end)
8041 label ; optional user-specified label, a `js2-name-node'
8042 labels ; current matching labeled stmt, if any
8043 target ; the `js2-loop-node' target of this continue stmt
8044 pn)
8045 (js2-consume-token) ; `continue'
8046 (when (= (js2-peek-token-or-eol) js2-NAME)
8047 (js2-consume-token)
8048 (setq label (js2-create-name-node)
8049 end (js2-node-end label)
8050 ;; matchJumpLabelName only matches if there is one
8051 labels (js2-match-jump-label-name js2-ts-string)))
8052 (cond
8053 ((null labels) ; no current label to go to
8054 (if (null js2-loop-set) ; no loop to continue to
8055 (js2-report-error "msg.continue.outside" nil pos
8056 (length "continue"))
8057 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8058 (t
8059 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8060 (setq target (js2-labeled-stmt-node-stmt labels))
8061 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8062 (setq pn (make-js2-continue-node :pos pos
8063 :len (- end pos)
8064 :label label
8065 :target target))
8066 (js2-node-add-children pn label) ; but not target - it's not our child
8067 pn))
8068
8069 (defun js2-parse-with ()
8070 "Parser for with-statement. Last matched token must be js2-WITH."
8071 (js2-consume-token)
8072 (let ((pos js2-token-beg)
8073 obj body pn lp rp)
8074 (if (js2-must-match js2-LP "msg.no.paren.with")
8075 (setq lp js2-token-beg))
8076 (setq obj (js2-parse-expr))
8077 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8078 (setq rp js2-token-beg))
8079 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8080 (setq body (js2-parse-statement)))
8081 (setq pn (make-js2-with-node :pos pos
8082 :len (- (js2-node-end body) pos)
8083 :object obj
8084 :body body
8085 :lp (js2-relpos lp pos)
8086 :rp (js2-relpos rp pos)))
8087 (js2-node-add-children pn obj body)
8088 pn))
8089
8090 (defun js2-parse-const-var ()
8091 "Parser for var- or const-statement.
8092 Last matched token must be js2-CONST or js2-VAR."
8093 (let ((tt (js2-peek-token))
8094 (pos js2-token-beg)
8095 expr
8096 pn)
8097 (js2-consume-token)
8098 (setq expr (js2-parse-variables tt js2-token-beg)
8099 pn (make-js2-expr-stmt-node :pos pos
8100 :len (- (js2-node-end expr) pos)
8101 :expr expr))
8102 (js2-node-add-children pn expr)
8103 pn))
8104
8105 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8106 (let ((pn (make-js2-expr-stmt-node :pos pos
8107 :len (js2-node-len expr)
8108 :type (if (js2-inside-function)
8109 js2-EXPR_VOID
8110 js2-EXPR_RESULT)
8111 :expr expr)))
8112 (if add-child
8113 (js2-node-add-children pn expr))
8114 pn))
8115
8116 (defun js2-parse-let-stmt ()
8117 "Parser for let-statement. Last matched token must be js2-LET."
8118 (js2-consume-token)
8119 (let ((pos js2-token-beg)
8120 expr
8121 pn)
8122 (if (= (js2-peek-token) js2-LP)
8123 ;; let expression in statement context
8124 (setq expr (js2-parse-let pos 'statement)
8125 pn (js2-wrap-with-expr-stmt pos expr t))
8126 ;; else we're looking at a statement like let x=6, y=7;
8127 (setf expr (js2-parse-variables js2-LET pos)
8128 pn (js2-wrap-with-expr-stmt pos expr t)
8129 (js2-node-type pn) js2-EXPR_RESULT))
8130 pn))
8131
8132 (defun js2-parse-ret-yield ()
8133 (js2-parse-return-or-yield (js2-peek-token) nil))
8134
8135 (defconst js2-parse-return-stmt-enders
8136 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8137
8138 (defsubst js2-now-all-set (before after mask)
8139 "Return whether or not the bits in the mask have changed to all set.
8140 BEFORE is bits before change, AFTER is bits after change, and MASK is
8141 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8142 but not BEFORE."
8143 (and (/= (logand before mask) mask)
8144 (= (logand after mask) mask)))
8145
8146 (defun js2-parse-return-or-yield (tt expr-context)
8147 (let ((pos js2-token-beg)
8148 (end js2-token-end)
8149 (before js2-end-flags)
8150 (inside-function (js2-inside-function))
8151 e
8152 ret
8153 name)
8154 (unless inside-function
8155 (js2-report-error (if (eq tt js2-RETURN)
8156 "msg.bad.return"
8157 "msg.bad.yield")))
8158 (js2-consume-token)
8159 ;; This is ugly, but we don't want to require a semicolon.
8160 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8161 (setq e (js2-parse-expr)
8162 end (js2-node-end e)))
8163 (cond
8164 ((eq tt js2-RETURN)
8165 (js2-set-flag js2-end-flags (if (null e)
8166 js2-end-returns
8167 js2-end-returns-value))
8168 (setq ret (make-js2-return-node :pos pos
8169 :len (- end pos)
8170 :retval e))
8171 (js2-node-add-children ret e)
8172 ;; See if we need a strict mode warning.
8173 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8174 ;; more thorough and accurate than this before/after flag check.
8175 ;; E.g. if there's a finally-block that always returns, we shouldn't
8176 ;; show a warning generated by inconsistent returns in the catch blocks.
8177 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8178 ;; so we know which returns/yields to highlight, and we should get rid of
8179 ;; all the checking in `js2-parse-return-or-yield'.
8180 (if (and js2-strict-inconsistent-return-warning
8181 (js2-now-all-set before js2-end-flags
8182 (logior js2-end-returns js2-end-returns-value)))
8183 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8184 (t
8185 (unless (js2-inside-function)
8186 (js2-report-error "msg.bad.yield"))
8187 (js2-set-flag js2-end-flags js2-end-yields)
8188 (setq ret (make-js2-yield-node :pos pos
8189 :len (- end pos)
8190 :value e))
8191 (js2-node-add-children ret e)
8192 (unless expr-context
8193 (setq e ret
8194 ret (js2-wrap-with-expr-stmt pos e t))
8195 (js2-set-requires-activation)
8196 (js2-set-is-generator))))
8197 ;; see if we are mixing yields and value returns.
8198 (when (and inside-function
8199 (js2-now-all-set before js2-end-flags
8200 (logior js2-end-yields js2-end-returns-value)))
8201 (setq name (js2-function-name js2-current-script-or-fn))
8202 (if (zerop (length name))
8203 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8204 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8205 ret))
8206
8207 (defun js2-parse-debugger ()
8208 (js2-consume-token)
8209 (make-js2-keyword-node :type js2-DEBUGGER))
8210
8211 (defun js2-parse-block ()
8212 "Parser for a curly-delimited statement block.
8213 Last token matched must be js2-LC."
8214 (let ((pos js2-token-beg)
8215 (pn (make-js2-scope)))
8216 (js2-consume-token)
8217 (js2-push-scope pn)
8218 (unwind-protect
8219 (progn
8220 (js2-parse-statements pn)
8221 (js2-must-match js2-RC "msg.no.brace.block")
8222 (setf (js2-node-len pn) (- js2-token-end pos)))
8223 (js2-pop-scope))
8224 pn))
8225
8226 ;; for js2-ERROR too, to have a node for error recovery to work on
8227 (defun js2-parse-semi ()
8228 "Parse a statement or handle an error.
8229 Last matched token is js-SEMI or js-ERROR."
8230 (let ((tt (js2-peek-token)) pos len)
8231 (js2-consume-token)
8232 (if (eq tt js2-SEMI)
8233 (make-js2-empty-expr-node :len 1)
8234 (setq pos js2-token-beg
8235 len (- js2-token-beg pos))
8236 (js2-report-error "msg.syntax" nil pos len)
8237 (make-js2-error-node :pos pos :len len))))
8238
8239 (defun js2-parse-default-xml-namespace ()
8240 "Parse a `default xml namespace = <expr>' e4x statement."
8241 (let ((pos js2-token-beg)
8242 end len expr unary es)
8243 (js2-consume-token)
8244 (js2-must-have-xml)
8245 (js2-set-requires-activation)
8246 (setq len (- js2-ts-cursor pos))
8247 (unless (and (js2-match-token js2-NAME)
8248 (string= js2-ts-string "xml"))
8249 (js2-report-error "msg.bad.namespace" nil pos len))
8250 (unless (and (js2-match-token js2-NAME)
8251 (string= js2-ts-string "namespace"))
8252 (js2-report-error "msg.bad.namespace" nil pos len))
8253 (unless (js2-match-token js2-ASSIGN)
8254 (js2-report-error "msg.bad.namespace" nil pos len))
8255 (setq expr (js2-parse-expr)
8256 end (js2-node-end expr)
8257 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8258 :pos pos
8259 :len (- end pos)
8260 :operand expr))
8261 (js2-node-add-children unary expr)
8262 (make-js2-expr-stmt-node :pos pos
8263 :len (- end pos)
8264 :expr unary)))
8265
8266 (defun js2-record-label (label bundle)
8267 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8268 (js2-consume-token)
8269 (let ((name (js2-label-node-name label))
8270 labeled-stmt
8271 dup)
8272 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8273 ;; flag both labels if possible when used in editing mode
8274 (if (and js2-parse-ide-mode
8275 (setq dup (js2-get-label-by-name labeled-stmt name)))
8276 (js2-report-error "msg.dup.label" nil
8277 (js2-node-abs-pos dup) (js2-node-len dup)))
8278 (js2-report-error "msg.dup.label" nil
8279 (js2-node-pos label) (js2-node-len label)))
8280 (js2-labeled-stmt-node-add-label bundle label)
8281 (js2-node-add-children bundle label)
8282 ;; Add one reference to the bundle per label in `js2-label-set'
8283 (push (cons name bundle) js2-label-set)))
8284
8285 (defun js2-parse-name-or-label ()
8286 "Parser for identifier or label. Last token matched must be js2-NAME.
8287 Called when we found a name in a statement context. If it's a label, we gather
8288 up any following labels and the next non-label statement into a
8289 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8290 expression and return it wrapped in a `js2-expr-stmt-node'."
8291 (let ((pos js2-token-beg)
8292 (end js2-token-end)
8293 expr
8294 stmt
8295 pn
8296 bundle
8297 (continue t))
8298 ;; set check for label and call down to `js2-parse-primary-expr'
8299 (js2-set-check-for-label)
8300 (setq expr (js2-parse-expr))
8301 (if (/= (js2-node-type expr) js2-LABEL)
8302 ;; Parsed non-label expression - wrap with expression stmt.
8303 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8304 ;; else parsed a label
8305 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8306 (js2-record-label expr bundle)
8307 ;; look for more labels
8308 (while (and continue (= (js2-peek-token) js2-NAME))
8309 (js2-set-check-for-label)
8310 (setq expr (js2-parse-expr))
8311 (if (/= (js2-node-type expr) js2-LABEL)
8312 (progn
8313 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8314 continue nil)
8315 (js2-auto-insert-semicolon stmt))
8316 (js2-record-label expr bundle)))
8317 ;; no more labels; now parse the labeled statement
8318 (unwind-protect
8319 (unless stmt
8320 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8321 (setq stmt (js2-statement-helper))))
8322 ;; remove the labels for this statement from the global set
8323 (dolist (label (js2-labeled-stmt-node-labels bundle))
8324 (setq js2-label-set (remove label js2-label-set))))
8325 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8326 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8327 (js2-node-add-children bundle stmt)
8328 bundle)))
8329
8330 (defun js2-parse-expr-stmt ()
8331 "Default parser in statement context, if no recognized statement found."
8332 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8333
8334 (defun js2-parse-variables (decl-type pos)
8335 "Parse a comma-separated list of variable declarations.
8336 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8337
8338 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8339 For 'var' or 'const', the keyword should be the token last scanned.
8340
8341 POS is the position where the node should start. It's sometimes the
8342 var/const/let keyword, and other times the beginning of the first token
8343 in the first variable declaration.
8344
8345 Returns the parsed `js2-var-decl-node' expression node."
8346 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8347 :pos pos))
8348 destructuring
8349 kid-pos
8350 tt
8351 init
8352 name
8353 end
8354 nbeg nend
8355 vi
8356 (continue t))
8357 ;; Example:
8358 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8359 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8360 (while continue
8361 (setq destructuring nil
8362 name nil
8363 tt (js2-peek-token)
8364 kid-pos js2-token-beg
8365 end js2-token-end
8366 init nil)
8367 (if (or (= tt js2-LB) (= tt js2-LC))
8368 ;; Destructuring assignment, e.g., var [a, b] = ...
8369 (setq destructuring (js2-parse-primary-expr)
8370 end (js2-node-end destructuring))
8371 ;; Simple variable name
8372 (when (js2-must-match js2-NAME "msg.bad.var")
8373 (setq name (js2-create-name-node)
8374 nbeg js2-token-beg
8375 nend js2-token-end
8376 end nend)
8377 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8378 (when (js2-match-token js2-ASSIGN)
8379 (setq init (js2-parse-assign-expr)
8380 end (js2-node-end init))
8381 (if (and js2-parse-ide-mode
8382 (or (js2-object-node-p init)
8383 (js2-function-node-p init)))
8384 (js2-record-imenu-functions init name)))
8385 (when name
8386 (js2-set-face nbeg nend (if (js2-function-node-p init)
8387 'font-lock-function-name-face
8388 'font-lock-variable-name-face)
8389 'record))
8390 (setq vi (make-js2-var-init-node :pos kid-pos
8391 :len (- end kid-pos)
8392 :type decl-type))
8393 (if destructuring
8394 (progn
8395 (if (and (null init) (not js2-in-for-init))
8396 (js2-report-error "msg.destruct.assign.no.init"))
8397 (setf (js2-var-init-node-target vi) destructuring))
8398 (setf (js2-var-init-node-target vi) name))
8399 (setf (js2-var-init-node-initializer vi) init)
8400 (js2-node-add-children vi name destructuring init)
8401 (js2-block-node-push result vi)
8402 (unless (js2-match-token js2-COMMA)
8403 (setq continue nil)))
8404 (setf (js2-node-len result) (- end pos))
8405 result))
8406
8407 (defun js2-parse-let (pos &optional stmt-p)
8408 "Parse a let expression or statement.
8409 A let-expression is of the form `let (vars) expr'.
8410 A let-statment is of the form `let (vars) {statements}'.
8411 The third form of let is a variable declaration list, handled
8412 by `js2-parse-variables'."
8413 (let ((pn (make-js2-let-node :pos pos))
8414 beg vars body)
8415 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8416 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8417 (js2-push-scope pn)
8418 (unwind-protect
8419 (progn
8420 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8421 (if (js2-must-match js2-RP "msg.no.paren.let")
8422 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8423 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8424 ;; let statement
8425 (progn
8426 (js2-consume-token)
8427 (setf beg js2-token-beg ; position stmt at LC
8428 body (js2-parse-statements))
8429 (js2-must-match js2-RC "msg.no.curly.let")
8430 (setf (js2-node-len body) (- js2-token-end beg)
8431 (js2-node-len pn) (- js2-token-end pos)
8432 (js2-let-node-body pn) body
8433 (js2-node-type pn) js2-LET))
8434 ;; let expression
8435 (setf body (js2-parse-expr)
8436 (js2-node-len pn) (- (js2-node-end body) pos)
8437 (js2-let-node-body pn) body))
8438 (js2-node-add-children pn vars body))
8439 (js2-pop-scope))
8440 pn))
8441
8442 (defsubst js2-define-new-symbol (decl-type name node)
8443 (js2-scope-put-symbol js2-current-scope
8444 name
8445 (make-js2-symbol decl-type name node)))
8446
8447 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8448 "Define a symbol in the current scope.
8449 If NODE is non-nil, it is the AST node associated with the symbol."
8450 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8451 (symbol (if defining-scope
8452 (js2-scope-get-symbol defining-scope name)))
8453 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8454 (cond
8455 ((and symbol ; already defined
8456 (or (= sdt js2-CONST) ; old version is const
8457 (= decl-type js2-CONST) ; new version is const
8458 ;; two let-bound vars in this block have same name
8459 (and (= sdt js2-LET)
8460 (eq defining-scope js2-current-scope))))
8461 (js2-report-error
8462 (cond
8463 ((= sdt js2-CONST) "msg.const.redecl")
8464 ((= sdt js2-LET) "msg.let.redecl")
8465 ((= sdt js2-VAR) "msg.var.redecl")
8466 ((= sdt js2-FUNCTION) "msg.function.redecl")
8467 (t "msg.parm.redecl"))
8468 name))
8469 ((= decl-type js2-LET)
8470 (if (and (not ignore-not-in-block)
8471 (or (= (js2-node-type js2-current-scope) js2-IF)
8472 (js2-loop-node-p js2-current-scope)))
8473 (js2-report-error "msg.let.decl.not.in.block")
8474 (js2-define-new-symbol decl-type name node)))
8475 ((or (= decl-type js2-VAR)
8476 (= decl-type js2-CONST)
8477 (= decl-type js2-FUNCTION))
8478 (if symbol
8479 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8480 (js2-add-strict-warning "msg.var.redecl" name)
8481 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8482 (js2-add-strict-warning "msg.var.hides.arg" name)))
8483 (js2-define-new-symbol decl-type name node)))
8484 ((= decl-type js2-LP)
8485 (if symbol
8486 ;; must be duplicate parameter. Second parameter hides the
8487 ;; first, so go ahead and add the second pararameter
8488 (js2-report-warning "msg.dup.parms" name))
8489 (js2-define-new-symbol decl-type name node))
8490 (t (js2-code-bug)))))
8491
8492 (defun js2-parse-expr ()
8493 (let* ((pn (js2-parse-assign-expr))
8494 (pos (js2-node-pos pn))
8495 left
8496 right
8497 op-pos)
8498 (while (js2-match-token js2-COMMA)
8499 (setq op-pos (- js2-token-beg pos)) ; relative
8500 (if (= (js2-peek-token) js2-YIELD)
8501 (js2-report-error "msg.yield.parenthesized"))
8502 (setq right (js2-parse-assign-expr)
8503 left pn
8504 pn (make-js2-infix-node :type js2-COMMA
8505 :pos pos
8506 :len (- js2-ts-cursor pos)
8507 :op-pos op-pos
8508 :left left
8509 :right right))
8510 (js2-node-add-children pn left right))
8511 pn))
8512
8513 (defun js2-parse-assign-expr ()
8514 (let ((tt (js2-peek-token))
8515 (pos js2-token-beg)
8516 pn
8517 left
8518 right
8519 op-pos)
8520 (if (= tt js2-YIELD)
8521 (js2-parse-return-or-yield tt t)
8522 ;; not yield - parse assignment expression
8523 (setq pn (js2-parse-cond-expr)
8524 tt (js2-peek-token))
8525 (when (and (<= js2-first-assign tt)
8526 (<= tt js2-last-assign))
8527 (js2-consume-token)
8528 (setq op-pos (- js2-token-beg pos) ; relative
8529 left pn
8530 right (js2-parse-assign-expr)
8531 pn (make-js2-assign-node :type tt
8532 :pos pos
8533 :len (- (js2-node-end right) pos)
8534 :op-pos op-pos
8535 :left left
8536 :right right))
8537 (when js2-parse-ide-mode
8538 (js2-highlight-assign-targets pn left right)
8539 (if (or (js2-function-node-p right)
8540 (js2-object-node-p right))
8541 (js2-record-imenu-functions right left)))
8542 ;; do this last so ide checks above can use absolute positions
8543 (js2-node-add-children pn left right))
8544 pn)))
8545
8546 (defun js2-parse-cond-expr ()
8547 (let ((pos js2-token-beg)
8548 (pn (js2-parse-or-expr))
8549 test-expr
8550 if-true
8551 if-false
8552 q-pos
8553 c-pos)
8554 (when (js2-match-token js2-HOOK)
8555 (setq q-pos (- js2-token-beg pos)
8556 if-true (js2-parse-assign-expr))
8557 (js2-must-match js2-COLON "msg.no.colon.cond")
8558 (setq c-pos (- js2-token-beg pos)
8559 if-false (js2-parse-assign-expr)
8560 test-expr pn
8561 pn (make-js2-cond-node :pos pos
8562 :len (- (js2-node-end if-false) pos)
8563 :test-expr test-expr
8564 :true-expr if-true
8565 :false-expr if-false
8566 :q-pos q-pos
8567 :c-pos c-pos))
8568 (js2-node-add-children pn test-expr if-true if-false))
8569 pn))
8570
8571 (defun js2-make-binary (type left parser)
8572 "Helper for constructing a binary-operator AST node.
8573 LEFT is the left-side-expression, already parsed, and the
8574 binary operator should have just been matched.
8575 PARSER is a function to call to parse the right operand,
8576 or a `js2-node' struct if it has already been parsed."
8577 (let* ((pos (js2-node-pos left))
8578 (op-pos (- js2-token-beg pos))
8579 (right (if (js2-node-p parser)
8580 parser
8581 (funcall parser)))
8582 (pn (make-js2-infix-node :type type
8583 :pos pos
8584 :len (- (js2-node-end right) pos)
8585 :op-pos op-pos
8586 :left left
8587 :right right)))
8588 (js2-node-add-children pn left right)
8589 pn))
8590
8591 (defun js2-parse-or-expr ()
8592 (let ((pn (js2-parse-and-expr)))
8593 (when (js2-match-token js2-OR)
8594 (setq pn (js2-make-binary js2-OR
8595 pn
8596 'js2-parse-or-expr)))
8597 pn))
8598
8599 (defun js2-parse-and-expr ()
8600 (let ((pn (js2-parse-bit-or-expr)))
8601 (when (js2-match-token js2-AND)
8602 (setq pn (js2-make-binary js2-AND
8603 pn
8604 'js2-parse-and-expr)))
8605 pn))
8606
8607 (defun js2-parse-bit-or-expr ()
8608 (let ((pn (js2-parse-bit-xor-expr)))
8609 (while (js2-match-token js2-BITOR)
8610 (setq pn (js2-make-binary js2-BITOR
8611 pn
8612 'js2-parse-bit-xor-expr)))
8613 pn))
8614
8615 (defun js2-parse-bit-xor-expr ()
8616 (let ((pn (js2-parse-bit-and-expr)))
8617 (while (js2-match-token js2-BITXOR)
8618 (setq pn (js2-make-binary js2-BITXOR
8619 pn
8620 'js2-parse-bit-and-expr)))
8621 pn))
8622
8623 (defun js2-parse-bit-and-expr ()
8624 (let ((pn (js2-parse-eq-expr)))
8625 (while (js2-match-token js2-BITAND)
8626 (setq pn (js2-make-binary js2-BITAND
8627 pn
8628 'js2-parse-eq-expr)))
8629 pn))
8630
8631 (defconst js2-parse-eq-ops
8632 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8633
8634 (defun js2-parse-eq-expr ()
8635 (let ((pn (js2-parse-rel-expr))
8636 tt)
8637 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8638 (js2-consume-token)
8639 (setq pn (js2-make-binary tt
8640 pn
8641 'js2-parse-rel-expr)))
8642 pn))
8643
8644 (defconst js2-parse-rel-ops
8645 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8646
8647 (defun js2-parse-rel-expr ()
8648 (let ((pn (js2-parse-shift-expr))
8649 (continue t)
8650 tt)
8651 (while continue
8652 (setq tt (js2-peek-token))
8653 (cond
8654 ((and js2-in-for-init (= tt js2-IN))
8655 (setq continue nil))
8656 ((memq tt js2-parse-rel-ops)
8657 (js2-consume-token)
8658 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8659 (t
8660 (setq continue nil))))
8661 pn))
8662
8663 (defconst js2-parse-shift-ops
8664 (list js2-LSH js2-URSH js2-RSH))
8665
8666 (defun js2-parse-shift-expr ()
8667 (let ((pn (js2-parse-add-expr))
8668 tt
8669 (continue t))
8670 (while continue
8671 (setq tt (js2-peek-token))
8672 (if (memq tt js2-parse-shift-ops)
8673 (progn
8674 (js2-consume-token)
8675 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8676 (setq continue nil)))
8677 pn))
8678
8679 (defun js2-parse-add-expr ()
8680 (let ((pn (js2-parse-mul-expr))
8681 tt
8682 (continue t))
8683 (while continue
8684 (setq tt (js2-peek-token))
8685 (if (or (= tt js2-ADD) (= tt js2-SUB))
8686 (progn
8687 (js2-consume-token)
8688 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8689 (setq continue nil)))
8690 pn))
8691
8692 (defconst js2-parse-mul-ops
8693 (list js2-MUL js2-DIV js2-MOD))
8694
8695 (defun js2-parse-mul-expr ()
8696 (let ((pn (js2-parse-unary-expr))
8697 tt
8698 (continue t))
8699 (while continue
8700 (setq tt (js2-peek-token))
8701 (if (memq tt js2-parse-mul-ops)
8702 (progn
8703 (js2-consume-token)
8704 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8705 (setq continue nil)))
8706 pn))
8707
8708 (defsubst js2-make-unary (type parser &rest args)
8709 "Make a unary node of type TYPE.
8710 PARSER is either a node (for postfix operators) or a function to call
8711 to parse the operand (for prefix operators)."
8712 (let* ((pos js2-token-beg)
8713 (postfix (js2-node-p parser))
8714 (expr (if postfix
8715 parser
8716 (apply parser args)))
8717 end
8718 pn)
8719 (if postfix ; e.g. i++
8720 (setq pos (js2-node-pos expr)
8721 end js2-token-end)
8722 (setq end (js2-node-end expr)))
8723 (setq pn (make-js2-unary-node :type type
8724 :pos pos
8725 :len (- end pos)
8726 :operand expr))
8727 (js2-node-add-children pn expr)
8728 pn))
8729
8730 (defconst js2-incrementable-node-types
8731 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8732 "Node types that can be the operand of a ++ or -- operator.")
8733
8734 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8735 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8736 js2-incrementable-node-types)
8737 (js2-report-error (if (= tt js2-INC)
8738 "msg.bad.incr"
8739 "msg.bad.decr")
8740 nil beg (- end beg))))
8741
8742 (defun js2-parse-unary-expr ()
8743 (let ((tt (js2-peek-token))
8744 pn expr beg end)
8745 (cond
8746 ((or (= tt js2-VOID)
8747 (= tt js2-NOT)
8748 (= tt js2-BITNOT)
8749 (= tt js2-TYPEOF))
8750 (js2-consume-token)
8751 (js2-make-unary tt 'js2-parse-unary-expr))
8752 ((= tt js2-ADD)
8753 (js2-consume-token)
8754 ;; Convert to special POS token in decompiler and parse tree
8755 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8756 ((= tt js2-SUB)
8757 (js2-consume-token)
8758 ;; Convert to special NEG token in decompiler and parse tree
8759 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8760 ((or (= tt js2-INC)
8761 (= tt js2-DEC))
8762 (js2-consume-token)
8763 (prog1
8764 (setq beg js2-token-beg
8765 end js2-token-end
8766 expr (js2-make-unary tt 'js2-parse-member-expr t))
8767 (js2-check-bad-inc-dec tt beg end expr)))
8768 ((= tt js2-DELPROP)
8769 (js2-consume-token)
8770 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8771 ((= tt js2-ERROR)
8772 (js2-consume-token)
8773 (make-js2-error-node)) ; try to continue
8774 ((and (= tt js2-LT)
8775 js2-compiler-xml-available)
8776 ;; XML stream encountered in expression.
8777 (js2-consume-token)
8778 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8779 (t
8780 (setq pn (js2-parse-member-expr t)
8781 ;; Don't look across a newline boundary for a postfix incop.
8782 tt (js2-peek-token-or-eol))
8783 (when (or (= tt js2-INC) (= tt js2-DEC))
8784 (js2-consume-token)
8785 (setf expr pn
8786 pn (js2-make-unary tt expr))
8787 (js2-node-set-prop pn 'postfix t)
8788 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8789 pn))))
8790
8791 (defun js2-parse-xml-initializer ()
8792 "Parse an E4X XML initializer.
8793 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8794 Then I'll postprocess the result, depending on whether we're in IDE
8795 mode or codegen mode, and generate the appropriate rewritten AST.
8796 IDE mode uses a rich AST that models the XML structure. Codegen mode
8797 just concatenates everything and makes a new XML or XMLList out of it."
8798 (let ((tt (js2-get-first-xml-token))
8799 pn-xml
8800 pn
8801 expr
8802 kids
8803 expr-pos
8804 (continue t)
8805 (first-token t))
8806 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8807 (js2-report-error "msg.syntax"))
8808 (setq pn-xml (make-js2-xml-node))
8809 (while continue
8810 (if first-token
8811 (setq first-token nil)
8812 (setq tt (js2-get-next-xml-token)))
8813 (cond
8814 ;; js2-XML means we found a {expr} in the XML stream.
8815 ;; The js2-ts-string is the XML up to the left-curly.
8816 ((= tt js2-XML)
8817 (push (make-js2-string-node :pos js2-token-beg
8818 :len (- js2-ts-cursor js2-token-beg))
8819 kids)
8820 (js2-must-match js2-LC "msg.syntax")
8821 (setq expr-pos js2-ts-cursor
8822 expr (if (eq (js2-peek-token) js2-RC)
8823 (make-js2-empty-expr-node :pos expr-pos)
8824 (js2-parse-expr)))
8825 (js2-must-match js2-RC "msg.syntax")
8826 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8827 :len (js2-node-len expr)
8828 :expr expr))
8829 (js2-node-add-children pn expr)
8830 (push pn kids))
8831 ;; a js2-XMLEND token means we hit the final close-tag.
8832 ((= tt js2-XMLEND)
8833 (push (make-js2-string-node :pos js2-token-beg
8834 :len (- js2-ts-cursor js2-token-beg))
8835 kids)
8836 (dolist (kid (nreverse kids))
8837 (js2-block-node-push pn-xml kid))
8838 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8839 (js2-node-pos pn-xml))
8840 continue nil))
8841 (t
8842 (js2-report-error "msg.syntax")
8843 (setq continue nil))))
8844 pn-xml))
8845
8846
8847 (defun js2-parse-argument-list ()
8848 "Parse an argument list and return it as a lisp list of nodes.
8849 Returns the list in reverse order. Consumes the right-paren token."
8850 (let (result)
8851 (unless (js2-match-token js2-RP)
8852 (loop do
8853 (if (= (js2-peek-token) js2-YIELD)
8854 (js2-report-error "msg.yield.parenthesized"))
8855 (push (js2-parse-assign-expr) result)
8856 while
8857 (js2-match-token js2-COMMA))
8858 (js2-must-match js2-RP "msg.no.paren.arg")
8859 result)))
8860
8861 (defun js2-parse-member-expr (&optional allow-call-syntax)
8862 (let ((tt (js2-peek-token))
8863 pn
8864 pos
8865 target
8866 args
8867 beg
8868 end
8869 init
8870 tail)
8871 (if (/= tt js2-NEW)
8872 (setq pn (js2-parse-primary-expr))
8873 ;; parse a 'new' expression
8874 (js2-consume-token)
8875 (setq pos js2-token-beg
8876 beg pos
8877 target (js2-parse-member-expr)
8878 end (js2-node-end target)
8879 pn (make-js2-new-node :pos pos
8880 :target target
8881 :len (- end pos)))
8882 (js2-node-add-children pn target)
8883 (when (js2-match-token js2-LP)
8884 ;; Add the arguments to pn, if any are supplied.
8885 (setf beg pos ; start of "new" keyword
8886 pos js2-token-beg
8887 args (nreverse (js2-parse-argument-list))
8888 (js2-new-node-args pn) args
8889 end js2-token-end
8890 (js2-new-node-lp pn) (- pos beg)
8891 (js2-new-node-rp pn) (- end 1 beg))
8892 (apply #'js2-node-add-children pn args))
8893 (when (and js2-allow-rhino-new-expr-initializer
8894 (js2-match-token js2-LC))
8895 (setf init (js2-parse-object-literal)
8896 end (js2-node-end init)
8897 (js2-new-node-initializer pn) init)
8898 (js2-node-add-children pn init))
8899 (setf (js2-node-len pn) (- beg pos))) ; end outer if
8900 (js2-parse-member-expr-tail allow-call-syntax pn)))
8901
8902 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8903 "Parse a chain of property/array accesses or function calls.
8904 Includes parsing for E4X operators like `..' and `.@'.
8905 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8906 Returns an expression tree that includes PN, the parent node."
8907 (let ((beg (js2-node-pos pn))
8908 tt
8909 (continue t))
8910 (while continue
8911 (setq tt (js2-peek-token))
8912 (cond
8913 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8914 (setq pn (js2-parse-property-access tt pn)))
8915 ((= tt js2-DOTQUERY)
8916 (setq pn (js2-parse-dot-query pn)))
8917 ((= tt js2-LB)
8918 (setq pn (js2-parse-element-get pn)))
8919 ((= tt js2-LP)
8920 (if allow-call-syntax
8921 (setq pn (js2-parse-function-call pn))
8922 (setq continue nil)))
8923 (t
8924 (setq continue nil))))
8925 (if (>= js2-highlight-level 2)
8926 (js2-parse-highlight-member-expr-node pn))
8927 pn))
8928
8929 (defun js2-parse-dot-query (pn)
8930 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8931 Last token parsed must be `js2-DOTQUERY'."
8932 (let ((pos (js2-node-pos pn))
8933 op-pos
8934 expr
8935 end)
8936 (js2-consume-token)
8937 (js2-must-have-xml)
8938 (js2-set-requires-activation)
8939 (setq op-pos js2-token-beg
8940 expr (js2-parse-expr)
8941 end (js2-node-end expr)
8942 pn (make-js2-xml-dot-query-node :left pn
8943 :pos pos
8944 :op-pos op-pos
8945 :right expr))
8946 (js2-node-add-children pn
8947 (js2-xml-dot-query-node-left pn)
8948 (js2-xml-dot-query-node-right pn))
8949 (if (js2-must-match js2-RP "msg.no.paren")
8950 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8951 end js2-token-end))
8952 (setf (js2-node-len pn) (- end pos))
8953 pn))
8954
8955 (defun js2-parse-element-get (pn)
8956 "Parse an element-get expression, e.g. foo[bar].
8957 Last token parsed must be `js2-RB'."
8958 (let ((lb js2-token-beg)
8959 (pos (js2-node-pos pn))
8960 rb
8961 expr)
8962 (js2-consume-token)
8963 (setq expr (js2-parse-expr))
8964 (if (js2-must-match js2-RB "msg.no.bracket.index")
8965 (setq rb js2-token-beg))
8966 (setq pn (make-js2-elem-get-node :target pn
8967 :pos pos
8968 :element expr
8969 :lb (js2-relpos lb pos)
8970 :rb (js2-relpos rb pos)
8971 :len (- js2-token-end pos)))
8972 (js2-node-add-children pn
8973 (js2-elem-get-node-target pn)
8974 (js2-elem-get-node-element pn))
8975 pn))
8976
8977 (defun js2-parse-function-call (pn)
8978 (let (args
8979 (pos (js2-node-pos pn)))
8980 (js2-consume-token)
8981 (setq pn (make-js2-call-node :pos pos
8982 :target pn
8983 :lp (- js2-token-beg pos)))
8984 (js2-node-add-children pn (js2-call-node-target pn))
8985 ;; Add the arguments to pn, if any are supplied.
8986 (setf args (nreverse (js2-parse-argument-list))
8987 (js2-call-node-rp pn) (- js2-token-beg pos)
8988 (js2-call-node-args pn) args)
8989 (apply #'js2-node-add-children pn args)
8990 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8991 pn))
8992
8993 (defun js2-parse-property-access (tt pn)
8994 "Parse a property access, XML descendants access, or XML attr access."
8995 (let ((member-type-flags 0)
8996 (dot-pos js2-token-beg)
8997 (dot-len (if (= tt js2-DOTDOT) 2 1))
8998 name
8999 ref ; right side of . or .. operator
9000 result)
9001 (js2-consume-token)
9002 (when (= tt js2-DOTDOT)
9003 (js2-must-have-xml)
9004 (setq member-type-flags js2-descendants-flag))
9005 (if (not js2-compiler-xml-available)
9006 (progn
9007 (js2-must-match-prop-name "msg.no.name.after.dot")
9008 (setq name (js2-create-name-node t js2-GETPROP)
9009 result (make-js2-prop-get-node :left pn
9010 :pos js2-token-beg
9011 :right name
9012 :len (- js2-token-end
9013 js2-token-beg)))
9014 (js2-node-add-children result pn name)
9015 result)
9016 ;; otherwise look for XML operators
9017 (setf result (if (= tt js2-DOT)
9018 (make-js2-prop-get-node)
9019 (make-js2-infix-node :type js2-DOTDOT))
9020 (js2-node-pos result) (js2-node-pos pn)
9021 (js2-infix-node-op-pos result) dot-pos
9022 (js2-infix-node-left result) pn ; do this after setting position
9023 tt (js2-next-token))
9024 (cond
9025 ;; needed for generator.throw()
9026 ((= tt js2-THROW)
9027 (js2-save-name-token-data js2-token-beg "throw")
9028 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9029 ;; handles: name, ns::name, ns::*, ns::[expr]
9030 ((js2-valid-prop-name-token tt)
9031 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9032 ;; handles: *, *::name, *::*, *::[expr]
9033 ((= tt js2-MUL)
9034 (js2-save-name-token-data js2-token-beg "*")
9035 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9036 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9037 ((= tt js2-XMLATTR)
9038 (setq result (js2-parse-attribute-access)))
9039 (t
9040 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9041 (if ref
9042 (setf (js2-node-len result) (- (js2-node-end ref)
9043 (js2-node-pos result))
9044 (js2-infix-node-right result) ref))
9045 (if (js2-infix-node-p result)
9046 (js2-node-add-children result
9047 (js2-infix-node-left result)
9048 (js2-infix-node-right result)))
9049 result)))
9050
9051 (defun js2-parse-attribute-access ()
9052 "Parse an E4X XML attribute expression.
9053 This includes expressions of the forms:
9054
9055 @attr @ns::attr @ns::*
9056 @* @*::attr @*::*
9057 @[expr] @*::[expr] @ns::[expr]
9058
9059 Called if we peeked an '@' token."
9060 (let ((tt (js2-next-token))
9061 (at-pos js2-token-beg))
9062 (cond
9063 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9064 ((js2-valid-prop-name-token tt)
9065 (js2-parse-property-name at-pos js2-ts-string 0))
9066 ;; handles: @*, @*::name, @*::*, @*::[expr]
9067 ((= tt js2-MUL)
9068 (js2-save-name-token-data js2-token-beg "*")
9069 (js2-parse-property-name js2-token-beg "*" 0))
9070 ;; handles @[expr]
9071 ((= tt js2-LB)
9072 (js2-parse-xml-elem-ref at-pos))
9073 (t
9074 (js2-report-error "msg.no.name.after.xmlAttr")
9075 ;; Avoid cascaded errors that happen if we make an error node here.
9076 (js2-save-name-token-data js2-token-beg "")
9077 (js2-parse-property-name js2-token-beg "" 0)))))
9078
9079 (defun js2-parse-property-name (at-pos s member-type-flags)
9080 "Check if :: follows name in which case it becomes qualified name.
9081
9082 AT-POS is a natural number if we just read an '@' token, else nil.
9083 S is the name or string that was matched: an identifier, 'throw' or '*'.
9084 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9085
9086 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9087 operator, or the name is followed by ::. For a plain name, returns a
9088 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9089 (let ((pos (or at-pos js2-token-beg))
9090 colon-pos
9091 (name (js2-create-name-node t js2-current-token))
9092 ns
9093 tt
9094 ref
9095 pn)
9096 (catch 'return
9097 (when (js2-match-token js2-COLONCOLON)
9098 (setq ns name
9099 colon-pos js2-token-beg
9100 tt (js2-next-token))
9101 (cond
9102 ;; handles name::name
9103 ((js2-valid-prop-name-token tt)
9104 (setq name (js2-create-name-node)))
9105 ;; handles name::*
9106 ((= tt js2-MUL)
9107 (js2-save-name-token-data js2-token-beg "*")
9108 (setq name (js2-create-name-node)))
9109 ;; handles name::[expr]
9110 ((= tt js2-LB)
9111 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9112 (t
9113 (js2-report-error "msg.no.name.after.coloncolon"))))
9114 (if (and (null ns) (zerop member-type-flags))
9115 name
9116 (prog1
9117 (setq pn
9118 (make-js2-xml-prop-ref-node :pos pos
9119 :len (- (js2-node-end name) pos)
9120 :at-pos at-pos
9121 :colon-pos colon-pos
9122 :propname name))
9123 (js2-node-add-children pn name))))))
9124
9125 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9126 "Parse the [expr] portion of an xml element reference.
9127 For instance, @[expr], @*::[expr], or ns::[expr]."
9128 (let* ((lb js2-token-beg)
9129 (pos (or at-pos lb))
9130 rb
9131 (expr (js2-parse-expr))
9132 (end (js2-node-end expr))
9133 pn)
9134 (if (js2-must-match js2-RB "msg.no.bracket.index")
9135 (setq rb js2-token-beg
9136 end js2-token-end))
9137 (prog1
9138 (setq pn
9139 (make-js2-xml-elem-ref-node :pos pos
9140 :len (- end pos)
9141 :namespace namespace
9142 :colon-pos colon-pos
9143 :at-pos at-pos
9144 :expr expr
9145 :lb (js2-relpos lb pos)
9146 :rb (js2-relpos rb pos)))
9147 (js2-node-add-children pn namespace expr))))
9148
9149 (defun js2-parse-primary-expr ()
9150 "Parses a literal (leaf) expression of some sort.
9151 Includes complex literals such as functions, object-literals,
9152 array-literals, array comprehensions and regular expressions."
9153 (let ((tt-flagged (js2-next-flagged-token))
9154 pn ; parent node (usually return value)
9155 tt
9156 px-pos ; paren-expr pos
9157 len
9158 flags ; regexp flags
9159 expr)
9160 (setq tt js2-current-token)
9161 (cond
9162 ((= tt js2-FUNCTION)
9163 (js2-parse-function 'FUNCTION_EXPRESSION))
9164 ((= tt js2-LB)
9165 (js2-parse-array-literal))
9166 ((= tt js2-LC)
9167 (js2-parse-object-literal))
9168 ((= tt js2-LET)
9169 (js2-parse-let js2-token-beg))
9170 ((= tt js2-LP)
9171 (setq px-pos js2-token-beg
9172 expr (js2-parse-expr))
9173 (js2-must-match js2-RP "msg.no.paren")
9174 (setq pn (make-js2-paren-node :pos px-pos
9175 :expr expr
9176 :len (- js2-token-end px-pos)))
9177 (js2-node-add-children pn (js2-paren-node-expr pn))
9178 pn)
9179 ((= tt js2-XMLATTR)
9180 (js2-must-have-xml)
9181 (js2-parse-attribute-access))
9182 ((= tt js2-NAME)
9183 (js2-parse-name tt-flagged tt))
9184 ((= tt js2-NUMBER)
9185 (make-js2-number-node))
9186 ((= tt js2-STRING)
9187 (prog1
9188 (make-js2-string-node)
9189 (js2-record-face 'font-lock-string-face)))
9190 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9191 ;; Got / or /= which in this context means a regexp literal
9192 (setq px-pos js2-token-beg)
9193 (js2-read-regexp tt)
9194 (setq flags js2-ts-regexp-flags
9195 js2-ts-regexp-flags nil)
9196 (prog1
9197 (make-js2-regexp-node :pos px-pos
9198 :len (- js2-ts-cursor px-pos)
9199 :value js2-ts-string
9200 :flags flags)
9201 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9202 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9203 ((or (= tt js2-NULL)
9204 (= tt js2-THIS)
9205 (= tt js2-FALSE)
9206 (= tt js2-TRUE))
9207 (make-js2-keyword-node :type tt))
9208 ((= tt js2-RESERVED)
9209 (js2-report-error "msg.reserved.id")
9210 (make-js2-name-node))
9211 ((= tt js2-ERROR)
9212 ;; the scanner or one of its subroutines reported the error.
9213 (make-js2-error-node))
9214 ((= tt js2-EOF)
9215 (setq px-pos (point-at-bol)
9216 len (- js2-ts-cursor px-pos))
9217 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9218 (make-js2-error-node :pos px-pos :len len))
9219 (t
9220 (js2-report-error "msg.syntax")
9221 (make-js2-error-node)))))
9222
9223 (defun js2-parse-name (tt-flagged tt)
9224 (let ((name js2-ts-string)
9225 (name-pos js2-token-beg))
9226 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9227 (= (js2-peek-token) js2-COLON))
9228 (prog1
9229 ;; Do not consume colon, it is used as unwind indicator
9230 ;; to return to statementHelper.
9231 (make-js2-label-node :pos name-pos
9232 :len (- js2-token-end name-pos)
9233 :name name)
9234 (js2-set-face name-pos
9235 js2-token-end
9236 'font-lock-variable-name-face 'record))
9237 ;; Otherwise not a label, just a name. Unfortunately peeking
9238 ;; the next token to check for a colon has biffed js2-token-beg
9239 ;; and js2-token-end. We store the name's bounds in buffer vars
9240 ;; and `js2-create-name-node' uses them.
9241 (js2-save-name-token-data name-pos name)
9242 (if js2-compiler-xml-available
9243 (js2-parse-property-name nil name 0)
9244 (js2-create-name-node 'check-activation)))))
9245
9246 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9247 (js2-add-strict-warning
9248 msg nil
9249 ;; back up from comma to beginning of line or array/objlit
9250 (max (if elems
9251 (js2-node-pos (car elems))
9252 pos)
9253 (save-excursion
9254 (goto-char comma-pos)
9255 (back-to-indentation)
9256 (point)))
9257 comma-pos))
9258
9259 (defun js2-parse-array-literal ()
9260 (let ((pos js2-token-beg)
9261 (end js2-token-end)
9262 (after-lb-or-comma t)
9263 after-comma
9264 tt
9265 elems
9266 pn
9267 (continue t))
9268 (while continue
9269 (setq tt (js2-peek-token))
9270 (cond
9271 ;; comma
9272 ((= tt js2-COMMA)
9273 (js2-consume-token)
9274 (setq after-comma js2-token-end)
9275 (if (not after-lb-or-comma)
9276 (setq after-lb-or-comma t)
9277 (push nil elems)))
9278 ;; end of array
9279 ((or (= tt js2-RB)
9280 (= tt js2-EOF)) ; prevent infinite loop
9281 (if (= tt js2-EOF)
9282 (js2-report-error "msg.no.bracket.arg" nil pos)
9283 (js2-consume-token))
9284 (setq continue nil
9285 end js2-token-end
9286 pn (make-js2-array-node :pos pos
9287 :len (- js2-ts-cursor pos)
9288 :elems (nreverse elems)))
9289 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9290 (when after-comma
9291 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9292 pos elems after-comma)))
9293 ;; array comp
9294 ((and (>= js2-language-version 170)
9295 (= tt js2-FOR) ; check for array comprehension
9296 (not after-lb-or-comma) ; "for" can't follow a comma
9297 elems ; must have at least 1 element
9298 (not (cdr elems))) ; but no 2nd element
9299 (setf continue nil
9300 pn (js2-parse-array-comprehension (car elems) pos)))
9301 ;; another element
9302 (t
9303 (unless after-lb-or-comma
9304 (js2-report-error "msg.no.bracket.arg"))
9305 (push (js2-parse-assign-expr) elems)
9306 (setq after-lb-or-comma nil
9307 after-comma nil))))
9308 pn))
9309
9310 (defun js2-parse-array-comprehension (expr pos)
9311 "Parse a JavaScript 1.7 Array Comprehension.
9312 EXPR is the first expression after the opening left-bracket.
9313 POS is the beginning of the LB token preceding EXPR.
9314 We should have just parsed the 'for' keyword before calling this function."
9315 (let (loops
9316 filter
9317 if-pos
9318 result)
9319 (while (= (js2-peek-token) js2-FOR)
9320 (push (js2-parse-array-comp-loop) loops))
9321 (when (= (js2-peek-token) js2-IF)
9322 (js2-consume-token)
9323 (setq if-pos (- js2-token-beg pos) ; relative
9324 filter (js2-parse-condition)))
9325 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9326 (setq result (make-js2-array-comp-node :pos pos
9327 :len (- js2-ts-cursor pos)
9328 :result expr
9329 :loops (nreverse loops)
9330 :filter (car filter)
9331 :lp (js2-relpos (second filter) pos)
9332 :rp (js2-relpos (third filter) pos)
9333 :if-pos if-pos))
9334 (apply #'js2-node-add-children result expr (car filter)
9335 (js2-array-comp-node-loops result))
9336 result))
9337
9338 (defun js2-parse-array-comp-loop ()
9339 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9340 Last token peeked should be the initial FOR."
9341 (let ((pos js2-token-beg)
9342 (pn (make-js2-array-comp-loop-node))
9343 tt
9344 iter
9345 obj
9346 foreach-p
9347 in-pos
9348 each-pos
9349 lp
9350 rp)
9351 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9352 (js2-push-scope pn)
9353 (unwind-protect
9354 (progn
9355 (when (js2-match-token js2-NAME)
9356 (if (string= js2-ts-string "each")
9357 (progn
9358 (setq foreach-p t
9359 each-pos (- js2-token-beg pos)) ; relative
9360 (js2-record-face 'font-lock-keyword-face))
9361 (js2-report-error "msg.no.paren.for")))
9362 (if (js2-must-match js2-LP "msg.no.paren.for")
9363 (setq lp (- js2-token-beg pos)))
9364 (setq tt (js2-peek-token))
9365 (cond
9366 ((or (= tt js2-LB)
9367 (= tt js2-LC))
9368 ;; handle destructuring assignment
9369 (setq iter (js2-parse-primary-expr)))
9370 ((js2-valid-prop-name-token tt)
9371 (js2-consume-token)
9372 (setq iter (js2-create-name-node)))
9373 (t
9374 (js2-report-error "msg.bad.var")))
9375 ;; Define as a let since we want the scope of the variable to
9376 ;; be restricted to the array comprehension
9377 (if (js2-name-node-p iter)
9378 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9379 (if (js2-must-match js2-IN "msg.in.after.for.name")
9380 (setq in-pos (- js2-token-beg pos)))
9381 (setq obj (js2-parse-expr))
9382 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9383 (setq rp (- js2-token-beg pos)))
9384 (setf (js2-node-pos pn) pos
9385 (js2-node-len pn) (- js2-ts-cursor pos)
9386 (js2-array-comp-loop-node-iterator pn) iter
9387 (js2-array-comp-loop-node-object pn) obj
9388 (js2-array-comp-loop-node-in-pos pn) in-pos
9389 (js2-array-comp-loop-node-each-pos pn) each-pos
9390 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9391 (js2-array-comp-loop-node-lp pn) lp
9392 (js2-array-comp-loop-node-rp pn) rp)
9393 (js2-node-add-children pn iter obj))
9394 (js2-pop-scope))
9395 pn))
9396
9397 (defun js2-parse-object-literal ()
9398 (let ((pos js2-token-beg)
9399 tt
9400 elems
9401 result
9402 after-comma
9403 (continue t))
9404 (while continue
9405 (setq tt (js2-peek-token))
9406 (cond
9407 ;; {foo: ...}, {'foo': ...}, {get foo() {...}}, or {set foo(x) {...}}
9408 ((or (js2-valid-prop-name-token tt)
9409 (= tt js2-STRING))
9410 (setq after-comma nil
9411 result (js2-parse-named-prop tt))
9412 (if (and (null result)
9413 (not js2-recover-from-parse-errors))
9414 (setq continue nil)
9415 (push result elems)))
9416 ;; {12: x} or {10.7: x}
9417 ((= tt js2-NUMBER)
9418 (js2-consume-token)
9419 (setq after-comma nil)
9420 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9421 ;; trailing comma
9422 ((= tt js2-RC)
9423 (setq continue nil)
9424 (if after-comma
9425 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9426 pos elems after-comma)))
9427 (t
9428 (js2-report-error "msg.bad.prop")
9429 (unless js2-recover-from-parse-errors
9430 (setq continue nil)))) ; end switch
9431 (if (js2-match-token js2-COMMA)
9432 (setq after-comma js2-token-end)
9433 (setq continue nil))) ; end loop
9434 (js2-must-match js2-RC "msg.no.brace.prop")
9435 (setq result (make-js2-object-node :pos pos
9436 :len (- js2-ts-cursor pos)
9437 :elems (nreverse elems)))
9438 (apply #'js2-node-add-children result (js2-object-node-elems result))
9439 result))
9440
9441 (defun js2-parse-named-prop (tt)
9442 "Parse a name, string, or getter/setter object property."
9443 (js2-consume-token)
9444 (let ((string-prop (and (= tt js2-STRING)
9445 (make-js2-string-node)))
9446 expr
9447 (ppos js2-token-beg)
9448 (pend js2-token-end)
9449 (name (js2-create-name-node))
9450 (prop js2-ts-string))
9451 (if (and (= tt js2-NAME)
9452 (= (js2-peek-token) js2-NAME)
9453 (or (string= prop "get")
9454 (string= prop "set")))
9455 (progn
9456 ;; getter/setter prop
9457 (js2-consume-token)
9458 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9459 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9460 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9461 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9462 ;; regular prop
9463 (prog1
9464 (setq expr (js2-parse-plain-property (or string-prop name)))
9465 (js2-set-face ppos pend
9466 (if (js2-function-node-p
9467 (js2-object-prop-node-right expr))
9468 'font-lock-function-name-face
9469 'font-lock-variable-name-face)
9470 'record)))))
9471
9472 (defun js2-parse-plain-property (prop)
9473 "Parse a non-getter/setter property in an object literal.
9474 PROP is the node representing the property: a number, name or string."
9475 (js2-must-match js2-COLON "msg.no.colon.prop")
9476 (let* ((pos (js2-node-pos prop))
9477 (colon (- js2-token-beg pos))
9478 (expr (js2-parse-assign-expr))
9479 (result (make-js2-object-prop-node
9480 :pos pos
9481 ;; don't include last consumed token in length
9482 :len (- (+ (js2-node-pos expr)
9483 (js2-node-len expr))
9484 pos)
9485 :left prop
9486 :right expr
9487 :op-pos colon)))
9488 (js2-node-add-children result prop expr)
9489 result))
9490
9491 (defun js2-parse-getter-setter-prop (pos prop get-p)
9492 "Parse getter or setter property in an object literal.
9493 JavaScript syntax is:
9494
9495 { get foo() {...}, set foo(x) {...} }
9496
9497 POS is the start position of the `get' or `set' keyword.
9498 PROP is the `js2-name-node' representing the property name.
9499 GET-P is non-nil if the keyword was `get'."
9500 (let ((type (if get-p js2-GET js2-SET))
9501 result
9502 end
9503 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9504 ;; it has to be an anonymous function, as we already parsed the name
9505 (if (/= (js2-node-type fn) js2-FUNCTION)
9506 (js2-report-error "msg.bad.prop")
9507 (if (plusp (length (js2-function-name fn)))
9508 (js2-report-error "msg.bad.prop")))
9509 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9510 (setq end (js2-node-end fn)
9511 result (make-js2-getter-setter-node :type type
9512 :pos pos
9513 :len (- end pos)
9514 :left prop
9515 :right fn))
9516 (js2-node-add-children result prop fn)
9517 result))
9518
9519 (defun js2-create-name-node (&optional check-activation-p token)
9520 "Create a name node using the token info from last scanned name.
9521 In some cases we need to either synthesize a name node, or we lost
9522 the name token information by peeking. If the TOKEN parameter is
9523 not `js2-NAME', then we use the token info saved in instance vars."
9524 (let ((beg js2-token-beg)
9525 (s js2-ts-string)
9526 name)
9527 (when (/= js2-current-token js2-NAME)
9528 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9529 s js2-prev-name-token-string
9530 js2-prev-name-token-start nil
9531 js2-prev-name-token-string nil))
9532 (setq name (make-js2-name-node :pos beg
9533 :name s
9534 :len (length s)))
9535 (if check-activation-p
9536 (js2-check-activation-name s (or token js2-NAME)))
9537 name))
9538
9539 ;;; Indentation support
9540
9541 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9542 ;; Karl cleverly deduces that the desired indentation level is often a
9543 ;; function of paren/bracket/brace nesting depth, which can be determined
9544 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9545 ;; then does some equally clever checks to see if we're in the context of a
9546 ;; substatement of a possibly braceless statement keyword such as if, while,
9547 ;; or finally. This approach yields pretty good results.
9548
9549 ;; The indenter is often "wrong", however, and needs to be overridden.
9550 ;; The right long-term solution is probably to emulate (or integrate
9551 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9552 ;; parse tree from `js2-parse' is present, which is not true at the
9553 ;; moment the user is typing, computing indentation is still thousands
9554 ;; of lines of code to handle every possible syntactic edge case.
9555
9556 ;; In the meantime, the compromise solution is that we offer a "bounce
9557 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9558 ;; current line indent among various likely guess points. This approach
9559 ;; is far from perfect, but should at least make it slightly easier to
9560 ;; move the line towards its desired indentation when manually
9561 ;; overriding Karl's heuristic nesting guesser.
9562
9563 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9564 ;; extensions such as `let' and Array comprehensions. Major kudos to
9565 ;; Karl for coming up with the initial approach, which packs a lot of
9566 ;; punch for so little code.
9567
9568 (defconst js-possibly-braceless-keyword-re
9569 (regexp-opt
9570 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with" "let")
9571 'words)
9572 "Regular expression matching keywords that are optionally
9573 followed by an opening brace.")
9574
9575 (defconst js-indent-operator-re
9576 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9577 (regexp-opt '("in" "instanceof") 'words))
9578 "Regular expression matching operators that affect indentation
9579 of continued expressions.")
9580
9581 ;; This function has horrible results if you're typing an array
9582 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9583 ;; in conjunction with electric-indent, so just disabling it.
9584 (defsubst js2-code-at-bol-p ()
9585 "Return t if the first character on line is non-whitespace."
9586 nil)
9587
9588 (defun js2-insert-and-indent (key)
9589 "Run command bound to key and indent current line. Runs the command
9590 bound to KEY in the global keymap and indents the current line."
9591 (interactive (list (this-command-keys)))
9592 (let ((cmd (lookup-key (current-global-map) key)))
9593 (if (commandp cmd)
9594 (call-interactively cmd)))
9595 ;; don't do the electric keys inside comments or strings,
9596 ;; and don't do bounce-indent with them.
9597 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9598 (js2-bounce-indent-p (js2-code-at-bol-p)))
9599 (unless (or (nth 3 parse-state)
9600 (nth 4 parse-state))
9601 (indent-according-to-mode))))
9602
9603 (defun js-re-search-forward-inner (regexp &optional bound count)
9604 "Auxiliary function for `js-re-search-forward'."
9605 (let ((parse)
9606 (saved-point (point-min)))
9607 (while (> count 0)
9608 (re-search-forward regexp bound)
9609 (setq parse (parse-partial-sexp saved-point (point)))
9610 (cond ((nth 3 parse)
9611 (re-search-forward
9612 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9613 (save-excursion (end-of-line) (point)) t))
9614 ((nth 7 parse)
9615 (forward-line))
9616 ((or (nth 4 parse)
9617 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9618 (re-search-forward "\\*/"))
9619 (t
9620 (setq count (1- count))))
9621 (setq saved-point (point))))
9622 (point))
9623
9624 (defun js-re-search-forward (regexp &optional bound noerror count)
9625 "Search forward but ignore strings and comments. Invokes
9626 `re-search-forward' but treats the buffer as if strings and
9627 comments have been removed."
9628 (let ((saved-point (point))
9629 (search-expr
9630 (cond ((null count)
9631 '(js-re-search-forward-inner regexp bound 1))
9632 ((< count 0)
9633 '(js-re-search-backward-inner regexp bound (- count)))
9634 ((> count 0)
9635 '(js-re-search-forward-inner regexp bound count)))))
9636 (condition-case err
9637 (eval search-expr)
9638 (search-failed
9639 (goto-char saved-point)
9640 (unless noerror
9641 (error (error-message-string err)))))))
9642
9643 (defun js-re-search-backward-inner (regexp &optional bound count)
9644 "Auxiliary function for `js-re-search-backward'."
9645 (let ((parse)
9646 (saved-point (point-min)))
9647 (while (> count 0)
9648 (re-search-backward regexp bound)
9649 (setq parse (parse-partial-sexp saved-point (point)))
9650 (cond ((nth 3 parse)
9651 (re-search-backward
9652 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9653 (save-excursion (beginning-of-line) (point)) t))
9654 ((nth 7 parse)
9655 (goto-char (nth 8 parse)))
9656 ((or (nth 4 parse)
9657 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9658 (re-search-backward "/\\*"))
9659 (t
9660 (setq count (1- count))))))
9661 (point))
9662
9663 (defun js-re-search-backward (regexp &optional bound noerror count)
9664 "Search backward but ignore strings and comments. Invokes
9665 `re-search-backward' but treats the buffer as if strings and
9666 comments have been removed."
9667 (let ((saved-point (point))
9668 (search-expr
9669 (cond ((null count)
9670 '(js-re-search-backward-inner regexp bound 1))
9671 ((< count 0)
9672 '(js-re-search-forward-inner regexp bound (- count)))
9673 ((> count 0)
9674 '(js-re-search-backward-inner regexp bound count)))))
9675 (condition-case err
9676 (eval search-expr)
9677 (search-failed
9678 (goto-char saved-point)
9679 (unless noerror
9680 (error (error-message-string err)))))))
9681
9682 (defun js-looking-at-operator-p ()
9683 "Return non-nil if text after point is an operator (that is not
9684 a comma)."
9685 (save-match-data
9686 (and (looking-at js-indent-operator-re)
9687 (or (not (looking-at ":"))
9688 (save-excursion
9689 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9690 (looking-at "?")))))))
9691
9692 (defun js-continued-expression-p ()
9693 "Returns non-nil if the current line continues an expression."
9694 (save-excursion
9695 (back-to-indentation)
9696 (or (js-looking-at-operator-p)
9697 (and (js-re-search-backward "\n" nil t)
9698 (progn
9699 (skip-chars-backward " \t")
9700 (backward-char)
9701 (and (js-looking-at-operator-p)
9702 (and (progn (backward-char)
9703 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9704
9705 (defun js-end-of-do-while-loop-p ()
9706 "Returns non-nil if word after point is `while' of a do-while
9707 statement, else returns nil. A braceless do-while statement
9708 spanning several lines requires that the start of the loop is
9709 indented to the same column as the current line."
9710 (interactive)
9711 (save-excursion
9712 (save-match-data
9713 (when (looking-at "\\s-*\\<while\\>")
9714 (if (save-excursion
9715 (skip-chars-backward "[ \t\n]*}")
9716 (looking-at "[ \t\n]*}"))
9717 (save-excursion
9718 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9719 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9720 (or (looking-at "\\<do\\>")
9721 (let ((saved-indent (current-indentation)))
9722 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9723 (/= (current-indentation) saved-indent)))
9724 (and (looking-at "[ \t]*\\<do\\>")
9725 (not (js-re-search-forward
9726 "\\<while\\>" (point-at-eol) t))
9727 (= (current-indentation) saved-indent)))))))))
9728
9729 (defun js-ctrl-statement-indentation ()
9730 "Returns the proper indentation of the current line if it
9731 starts the body of a control statement without braces, else
9732 returns nil."
9733 (let (forward-sexp-function) ; temporarily unbind it
9734 (save-excursion
9735 (back-to-indentation)
9736 (when (save-excursion
9737 (and (not (js2-same-line (point-min)))
9738 (not (looking-at "{"))
9739 (js-re-search-backward "[[:graph:]]" nil t)
9740 (not (looking-at "[{([]"))
9741 (progn
9742 (forward-char)
9743 ;; scan-sexps sometimes throws an error
9744 (ignore-errors (backward-sexp))
9745 (when (looking-at "(") (backward-word 1))
9746 (and (save-excursion
9747 (skip-chars-backward " \t}" (point-at-bol))
9748 (bolp))
9749 (looking-at js-possibly-braceless-keyword-re)
9750 (not (js-end-of-do-while-loop-p))))))
9751 (save-excursion
9752 (goto-char (match-beginning 0))
9753 (+ (current-indentation) js2-basic-offset))))))
9754
9755 (defun js2-indent-in-array-comp (parse-status)
9756 "Return non-nil if we think we're in an array comprehension.
9757 In particular, return the buffer position of the first `for' kwd."
9758 (let ((end (point)))
9759 (when (nth 1 parse-status)
9760 (save-excursion
9761 (goto-char (nth 1 parse-status))
9762 (when (looking-at "\\[")
9763 (forward-char 1)
9764 (js2-forward-sws)
9765 (if (looking-at "[[{]")
9766 (let (forward-sexp-function) ; use lisp version
9767 (forward-sexp) ; skip destructuring form
9768 (js2-forward-sws)
9769 (if (and (/= (char-after) ?,) ; regular array
9770 (looking-at "for"))
9771 (match-beginning 0)))
9772 ;; to skip arbitrary expressions we need the parser,
9773 ;; so we'll just guess at it.
9774 (if (re-search-forward "[^,]* \\(for\\) " end t)
9775 (match-beginning 1))))))))
9776
9777 (defun js2-array-comp-indentation (parse-status for-kwd)
9778 (if (js2-same-line for-kwd)
9779 ;; first continuation line
9780 (save-excursion
9781 (goto-char (nth 1 parse-status))
9782 (forward-char 1)
9783 (skip-chars-forward " \t")
9784 (current-column))
9785 (save-excursion
9786 (goto-char for-kwd)
9787 (current-column))))
9788
9789 (defun js-proper-indentation (parse-status)
9790 "Return the proper indentation for the current line."
9791 (save-excursion
9792 (back-to-indentation)
9793 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9794 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9795 (continued-expr-p (js-continued-expression-p))
9796 (bracket (nth 1 parse-status))
9797 beg)
9798 (cond
9799 ;; indent array comprehension continuation lines specially
9800 ((and bracket
9801 (not (js2-same-line bracket))
9802 (setq beg (js2-indent-in-array-comp parse-status))
9803 (>= (point) (save-excursion
9804 (goto-char beg)
9805 (point-at-bol)))) ; at or after first loop?
9806 (js2-array-comp-indentation parse-status beg))
9807
9808 (ctrl-stmt-indent)
9809
9810 (bracket
9811 (goto-char bracket)
9812 (cond
9813 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9814 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9815 (when (save-excursion (skip-chars-backward " \t)")
9816 (looking-at ")"))
9817 (backward-list))
9818 (if (nth 1 p)
9819 (progn (goto-char (1+ (nth 1 p)))
9820 (skip-chars-forward " \t"))
9821 (back-to-indentation))
9822 (cond (same-indent-p
9823 (current-column))
9824 (continued-expr-p
9825 (+ (current-column) (* 2 js2-basic-offset)))
9826 (t
9827 (+ (current-column) js2-basic-offset)))))
9828 (t
9829 (unless same-indent-p
9830 (forward-char)
9831 (skip-chars-forward " \t"))
9832 (current-column))))
9833
9834 (continued-expr-p js2-basic-offset)
9835 (t 0)))))
9836
9837 (defun js2-lineup-comment (parse-status)
9838 "Indent a multi-line block comment continuation line."
9839 (let* ((beg (nth 8 parse-status))
9840 (first-line (js2-same-line beg))
9841 (offset (save-excursion
9842 (goto-char beg)
9843 (if (looking-at "/\\*")
9844 (+ 1 (current-column))
9845 0))))
9846 (unless first-line
9847 (indent-line-to offset))))
9848
9849 (defun js2-backward-sws ()
9850 "Move backward through whitespace and comments."
9851 (interactive)
9852 (while (forward-comment -1)))
9853
9854 (defun js2-forward-sws ()
9855 "Move forward through whitespace and comments."
9856 (interactive)
9857 (while (forward-comment 1)))
9858
9859 (defsubst js2-current-indent (&optional pos)
9860 "Return column of indentation on current line.
9861 If POS is non-nil, go to that point and return indentation for that line."
9862 (save-excursion
9863 (if pos
9864 (goto-char pos))
9865 (back-to-indentation)
9866 (current-column)))
9867
9868 (defsubst js2-arglist-close ()
9869 "Return non-nil if we're on a line beginning with a close-paren/brace."
9870 (save-match-data
9871 (save-excursion
9872 (goto-char (point-at-bol))
9873 (js2-forward-sws)
9874 (looking-at "[])}]"))))
9875
9876 (defsubst js2-indent-looks-like-label-p ()
9877 (goto-char (point-at-bol))
9878 (js2-forward-sws)
9879 (looking-at (concat js2-mode-identifier-re ":")))
9880
9881 (defun js2-indent-in-objlit-p (parse-status)
9882 "Return non-nil if this looks like an object-literal entry."
9883 (let ((start (nth 1 parse-status)))
9884 (and
9885 start
9886 (save-excursion
9887 (and (zerop (forward-line -1))
9888 (not (< (point) start)) ; crossed a {} boundary
9889 (js2-indent-looks-like-label-p)))
9890 (save-excursion
9891 (js2-indent-looks-like-label-p)))))
9892
9893 ;; if prev line looks like foobar({ then we're passing an object
9894 ;; literal to a function call, and people pretty much always want to
9895 ;; de-dent back to the previous line, so move the 'basic-offset'
9896 ;; position to the front.
9897 (defsubst js2-indent-objlit-arg-p (parse-status)
9898 (save-excursion
9899 (back-to-indentation)
9900 (js2-backward-sws)
9901 (and (eq (1- (point)) (nth 1 parse-status))
9902 (eq (char-before) ?{)
9903 (progn
9904 (forward-char -1)
9905 (skip-chars-backward " \t")
9906 (eq (char-before) ?\()))))
9907
9908 (defsubst js2-indent-case-block-p ()
9909 (save-excursion
9910 (back-to-indentation)
9911 (js2-backward-sws)
9912 (goto-char (point-at-bol))
9913 (skip-chars-forward " \t")
9914 (save-match-data
9915 (looking-at "case\\s-.+:"))))
9916
9917 (defsubst js2-syntax-bol ()
9918 "Return the point at the first non-whitespace char on the line.
9919 Returns `point-at-bol' if the line is empty."
9920 (save-excursion
9921 (beginning-of-line)
9922 (skip-chars-forward " \t")
9923 (point)))
9924
9925 (defun js2-bounce-indent (normal-col parse-status)
9926 "Cycle among alternate computed indentation positions.
9927 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9928 of the buffer to the current point. NORMAL-COL is the indentation
9929 column computed by the heuristic guesser based on current paren,
9930 bracket, brace and statement nesting."
9931 (let ((cur-indent (js2-current-indent))
9932 (old-buffer-undo-list buffer-undo-list)
9933 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9934 (current-line (save-excursion
9935 (forward-line 0) ; move to bol
9936 (1+ (count-lines (point-min) (point)))))
9937 positions
9938 pos
9939 anchor
9940 arglist-cont
9941 same-indent
9942 prev-line-col
9943 basic-offset
9944 computed-pos)
9945 ;; temporarily don't record undo info, if user requested this
9946 (if js2-mode-indent-inhibit-undo
9947 (setq buffer-undo-list t))
9948 (unwind-protect
9949 (progn
9950 ;; first likely point: indent from beginning of previous code line
9951 (push (setq basic-offset
9952 (+ (save-excursion
9953 (back-to-indentation)
9954 (js2-backward-sws)
9955 (back-to-indentation)
9956 (setq prev-line-col (current-column)))
9957 js2-basic-offset))
9958 positions)
9959
9960 ;; (first + epsilon) likely point: indent 2x from beginning of
9961 ;; previous code line. Some companies like this approach. Ahem.
9962 ;; Seriously, though -- 4-space indent for expression continuation
9963 ;; lines isn't a bad idea. We should eventually implement it
9964 ;; that way.
9965 (push (setq basic-offset
9966 (+ (save-excursion
9967 (back-to-indentation)
9968 (js2-backward-sws)
9969 (back-to-indentation)
9970 (setq prev-line-col (current-column)))
9971 (* 2 js2-basic-offset)))
9972 positions)
9973
9974 ;; second likely point: indent from assign-expr RHS. This
9975 ;; is just a crude guess based on finding " = " on the previous
9976 ;; line containing actual code.
9977 (setq pos (save-excursion
9978 (save-match-data
9979 (forward-line -1)
9980 (goto-char (point-at-bol))
9981 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9982 (point-at-eol) t)
9983 (goto-char (match-end 1))
9984 (skip-chars-forward " \t\r\n")
9985 (current-column)))))
9986 (when pos
9987 (incf pos js2-basic-offset)
9988 (unless (member pos positions)
9989 (push pos positions)))
9990
9991 ;; third likely point: same indent as previous line of code.
9992 ;; Make it the first likely point if we're not on an
9993 ;; arglist-close line and previous line ends in a comma, or
9994 ;; both this line and prev line look like object-literal
9995 ;; elements.
9996 (setq pos (save-excursion
9997 (goto-char (point-at-bol))
9998 (js2-backward-sws)
9999 (back-to-indentation)
10000 (prog1
10001 (current-column)
10002 ;; while we're here, look for trailing comma
10003 (if (save-excursion
10004 (goto-char (point-at-eol))
10005 (js2-backward-sws)
10006 (eq (char-before) ?,))
10007 (setq arglist-cont (1- (point)))))))
10008 (when pos
10009 (if (and (or arglist-cont
10010 (js2-indent-in-objlit-p parse-status))
10011 (not (js2-arglist-close)))
10012 (setq same-indent pos))
10013 (unless (member pos positions)
10014 (push pos positions)))
10015
10016 ;; fourth likely point: first preceding code with less indentation
10017 ;; than the immediately preceding code line.
10018 (setq pos (save-excursion
10019 (js2-backward-sws)
10020 (back-to-indentation)
10021 (setq anchor (current-column))
10022 (while (and (zerop (forward-line -1))
10023 (>= (progn
10024 (back-to-indentation)
10025 (current-column))
10026 anchor)))
10027 (setq pos (current-column))))
10028 (unless (member pos positions)
10029 (push pos positions))
10030
10031 ;; put nesting-heuristic position first in list, sort rest
10032 (setq positions (nreverse (sort positions '<)))
10033 (setq positions (cons normal-col (delete normal-col positions)))
10034
10035 ;; comma-list continuation lines: prev line indent takes precedence
10036 (if same-indent
10037 (setq positions
10038 (cons same-indent
10039 (sort (delete same-indent positions) '<))))
10040
10041 ;; common special cases where we want to indent in from previous line
10042 (if (or (js2-indent-case-block-p)
10043 (js2-indent-objlit-arg-p parse-status))
10044 (setq positions
10045 (cons basic-offset
10046 (delete basic-offset positions))))
10047
10048 ;; record whether we're already sitting on one of the alternatives
10049 (setq pos (member cur-indent positions))
10050 (cond
10051 ;; case 0: we're one one of the alternatives and this is the
10052 ;; first time they've pressed TAB on this line (best-guess).
10053 ((and js2-mode-indent-ignore-first-tab
10054 pos
10055 ;; first time pressing TAB on this line?
10056 (not (eq js2-mode-last-indented-line current-line)))
10057 ;; do nothing
10058 (setq computed-pos nil))
10059 ;; case 1: only one computed position => use it
10060 ((null (cdr positions))
10061 (setq computed-pos 0))
10062 ;; case 2: not on any of the computed spots => use main spot
10063 ((not pos)
10064 (setq computed-pos 0))
10065 ;; case 3: on last position: cycle to first position
10066 ((null (cdr pos))
10067 (setq computed-pos 0))
10068 ;; case 4: on intermediate position: cycle to next position
10069 (t
10070 (setq computed-pos (js2-position (second pos) positions))))
10071
10072 ;; see if any hooks want to indent; otherwise we do it
10073 (loop with result = nil
10074 for hook in js2-indent-hook
10075 while (null result)
10076 do
10077 (setq result (funcall hook positions computed-pos))
10078 finally do
10079 (unless (or result (null computed-pos))
10080 (indent-line-to (nth computed-pos positions)))))
10081
10082 ;; finally
10083 (if js2-mode-indent-inhibit-undo
10084 (setq buffer-undo-list old-buffer-undo-list))
10085 ;; see commentary for `js2-mode-last-indented-line'
10086 (setq js2-mode-last-indented-line current-line))))
10087
10088 (defsubst js2-1-line-comment-continuation-p ()
10089 "Return t if we're in a 1-line comment continuation.
10090 If so, we don't ever want to use bounce-indent."
10091 (save-excursion
10092 (save-match-data
10093 (and (progn
10094 (forward-line 0)
10095 (looking-at "\\s-*//"))
10096 (progn
10097 (forward-line -1)
10098 (forward-line 0)
10099 (when (looking-at "\\s-*$")
10100 (js2-backward-sws)
10101 (forward-line 0))
10102 (looking-at "\\s-*//"))))))
10103
10104 (defun js2-indent-line ()
10105 "Indent the current line as JavaScript source text."
10106 (interactive)
10107 (let (parse-status
10108 current-indent
10109 offset
10110 indent-col
10111 moved
10112 ;; don't whine about errors/warnings when we're indenting.
10113 ;; This has to be set before calling parse-partial-sexp below.
10114 (inhibit-point-motion-hooks t))
10115 (setq parse-status (save-excursion
10116 (parse-partial-sexp (point-min)
10117 (point-at-bol)))
10118 offset (- (point) (save-excursion
10119 (back-to-indentation)
10120 (setq current-indent (current-column))
10121 (point))))
10122 (js2-with-underscore-as-word-syntax
10123 (if (nth 4 parse-status)
10124 (js2-lineup-comment parse-status)
10125 (setq indent-col (js-proper-indentation parse-status))
10126 ;; see comments below about js2-mode-last-indented-line
10127 (when
10128 (cond
10129 ;; bounce-indenting is disabled during electric-key indent.
10130 ;; It doesn't work well on first line of buffer.
10131 ((and js2-bounce-indent-p
10132 (not (js2-same-line (point-min)))
10133 (not (js2-1-line-comment-continuation-p)))
10134 (js2-bounce-indent indent-col parse-status)
10135 (setq moved t))
10136 ;; just indent to the guesser's likely spot
10137 ((/= current-indent indent-col)
10138 (indent-line-to indent-col)
10139 (setq moved t)))
10140 (when (and moved (plusp offset))
10141 (forward-char offset)))))))
10142
10143 (defun js2-indent-region (start end)
10144 "Indent the region, but don't use bounce indenting."
10145 (let ((js2-bounce-indent-p nil)
10146 (indent-region-function nil))
10147 (indent-region start end nil))) ; nil for byte-compiler
10148
10149 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10150
10151 ;;;###autoload
10152 (defun js2-mode ()
10153 "Major mode for editing JavaScript code."
10154 (interactive)
10155 (kill-all-local-variables)
10156 (set-syntax-table js2-mode-syntax-table)
10157 (use-local-map js2-mode-map)
10158 (setq major-mode 'js2-mode
10159 mode-name "JavaScript-IDE"
10160 comment-start "//" ; used by comment-region; don't change it
10161 comment-end "")
10162 (setq local-abbrev-table js2-mode-abbrev-table)
10163 (set (make-local-variable 'max-lisp-eval-depth)
10164 (max max-lisp-eval-depth 3000))
10165 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10166 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10167
10168 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10169 ;; on most platforms other than the one I originally wrote it on. So it's
10170 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10171 ;; with our binding of the RET key inside comments: short lines stay short.
10172 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10173
10174 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10175 (set (make-local-variable 'next-error-function) #'js2-next-error)
10176 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10177 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10178 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10179 ;; for characters inside regexp literals.
10180 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10181 ;; this is necessary to make `show-paren-function' work properly
10182 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10183 ;; needed for M-x rgrep, among other things
10184 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10185
10186 ;; some variables needed by cc-engine for paragraph-fill, etc.
10187 (setq c-buffer-is-cc-mode t
10188 c-comment-prefix-regexp js2-comment-prefix-regexp
10189 c-comment-start-regexp "/[*/]\\|\\s|"
10190 c-paragraph-start js2-paragraph-start
10191 c-paragraph-separate "$"
10192 comment-start-skip js2-comment-start-skip
10193 c-syntactic-ws-start js2-syntactic-ws-start
10194 c-syntactic-ws-end js2-syntactic-ws-end
10195 c-syntactic-eol js2-syntactic-eol)
10196
10197 (setq js2-default-externs
10198 (append js2-ecma-262-externs
10199 (if js2-include-browser-externs
10200 js2-browser-externs)
10201 (if js2-include-gears-externs
10202 js2-gears-externs)
10203 (if js2-include-rhino-externs
10204 js2-rhino-externs)))
10205
10206 ;; We do our own syntax highlighting based on the parse tree.
10207 ;; However, we want minor modes that add keywords to highlight properly
10208 ;; (examples: doxymacs, column-marker). We do this by not letting
10209 ;; font-lock unfontify anything, and telling it to fontify after we
10210 ;; re-parse and re-highlight the buffer. (We currently don't do any
10211 ;; work with regions other than the whole buffer.)
10212 (dolist (var '(font-lock-unfontify-buffer-function
10213 font-lock-unfontify-region-function))
10214 (set (make-local-variable var) (lambda (&rest args) t)))
10215
10216 ;; Don't let font-lock do syntactic (string/comment) fontification.
10217 (set (make-local-variable #'font-lock-syntactic-face-function)
10218 (lambda (state) nil))
10219
10220 ;; Experiment: make reparse-delay longer for longer files.
10221 (if (plusp js2-dynamic-idle-timer-adjust)
10222 (setq js2-idle-timer-delay
10223 (* js2-idle-timer-delay
10224 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10225
10226 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10227 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10228 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10229 (imenu-add-to-menubar (concat "IM-" mode-name))
10230 (when js2-mirror-mode
10231 (js2-enter-mirror-mode))
10232 (add-to-invisibility-spec '(js2-outline . t))
10233 (set (make-local-variable 'line-move-ignore-invisible) t)
10234 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10235 (setq js2-mode-functions-hidden nil
10236 js2-mode-comments-hidden nil
10237 js2-mode-buffer-dirty-p t
10238 js2-mode-parsing nil)
10239 (js2-reparse)
10240 (run-hooks 'js2-mode-hook))
10241
10242 (defun js2-mode-exit ()
10243 "Exit `js2-mode' and clean up."
10244 (interactive)
10245 (when js2-mode-node-overlay
10246 (delete-overlay js2-mode-node-overlay)
10247 (setq js2-mode-node-overlay nil))
10248 (js2-remove-overlays)
10249 (setq js2-mode-ast nil)
10250 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10251 (remove-from-invisibility-spec '(js2-outline . t))
10252 (js2-mode-show-all)
10253 (js2-with-unmodifying-text-property-changes
10254 (js2-clear-face (point-min) (point-max))))
10255
10256 (defun js2-before-save ()
10257 "Clean up whitespace before saving file.
10258 You can disable this by customizing `js2-cleanup-whitespace'."
10259 (when js2-cleanup-whitespace
10260 (let ((col (current-column)))
10261 (delete-trailing-whitespace)
10262 ;; don't change trailing whitespace on current line
10263 (unless (eq (current-column) col)
10264 (indent-to col)))))
10265
10266 (defsubst js2-mode-reset-timer ()
10267 "Cancel any existing parse timer and schedule a new one."
10268 (if js2-mode-parse-timer
10269 (cancel-timer js2-mode-parse-timer))
10270 (setq js2-mode-parsing nil)
10271 (setq js2-mode-parse-timer
10272 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10273
10274 (defun js2-mode-edit (beg end len)
10275 "Schedule a new parse after buffer is edited.
10276 Buffer edit spans from BEG to END and is of length LEN.
10277 Also clears the `js2-magic' bit on autoinserted parens/brackets
10278 if the edit occurred on a line different from the magic paren."
10279 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10280 (line (if magic-pos (line-number-at-pos magic-pos))))
10281 (and line
10282 (or (/= (line-number-at-pos beg) line)
10283 (and (> 0 len)
10284 (/= (line-number-at-pos end) line)))
10285 (js2-mode-mundanify-parens)))
10286 (setq js2-mode-buffer-dirty-p t)
10287 (js2-mode-hide-overlay)
10288 (js2-mode-reset-timer))
10289
10290 (defun js2-mode-run-font-lock ()
10291 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10292 This is intended to allow modes that install their own font-lock keywords
10293 to work with js2-mode. In practice it never seems to work for long.
10294 Hopefully the Emacs maintainers can help figure out a way to make it work."
10295 (when (and (boundp 'font-lock-keywords)
10296 font-lock-keywords
10297 (boundp 'font-lock-mode)
10298 font-lock-mode)
10299 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10300 ;; play nicely with js2-mode. They go out of their way to fail to
10301 ;; provide any option for saying "look, fontify the farging buffer
10302 ;; with just the keywords already". Argh.
10303 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10304 (let (font-lock-verbose)
10305 (font-lock-default-fontify-buffer))))
10306
10307 (defun js2-reparse (&optional force)
10308 "Re-parse current buffer after user finishes some data entry.
10309 If we get any user input while parsing, including cursor motion,
10310 we discard the parse and reschedule it. If FORCE is nil, then the
10311 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10312 (let (time
10313 interrupted-p
10314 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10315 (unless js2-mode-parsing
10316 (setq js2-mode-parsing t)
10317 (unwind-protect
10318 (when (or js2-mode-buffer-dirty-p force)
10319 (js2-remove-overlays)
10320 (js2-with-unmodifying-text-property-changes
10321 (remove-text-properties (point-min) (point-max) '(syntax-table))
10322 (setq js2-mode-buffer-dirty-p nil
10323 js2-mode-fontifications nil
10324 js2-mode-deferred-properties nil
10325 js2-additional-externs nil)
10326 (if js2-mode-verbose-parse-p
10327 (message "parsing..."))
10328 (setq time
10329 (js2-time
10330 (setq interrupted-p
10331 (catch 'interrupted
10332 (setq js2-mode-ast (js2-parse))
10333 (js2-mode-fontify-regions)
10334 (js2-mode-remove-suppressed-warnings)
10335 (js2-mode-show-warnings)
10336 (js2-mode-show-errors)
10337 (js2-mode-run-font-lock) ; note: doesn't work
10338 (js2-mode-highlight-magic-parens)
10339 (if (>= js2-highlight-level 1)
10340 (js2-highlight-jsdoc js2-mode-ast))
10341 nil))))
10342 (if interrupted-p
10343 (progn
10344 ;; unfinished parse => try again
10345 (setq js2-mode-buffer-dirty-p t)
10346 (js2-mode-reset-timer))
10347 (if js2-mode-verbose-parse-p
10348 (message "Parse time: %s" time)))))
10349 (setq js2-mode-parsing nil)
10350 (unless interrupted-p
10351 (setq js2-mode-parse-timer nil))))))
10352
10353 (defun js2-mode-show-node ()
10354 "Debugging aid: highlight selected AST node on mouse click."
10355 (interactive)
10356 (let ((node (js2-node-at-point))
10357 beg
10358 end)
10359 (when js2-mode-show-overlay
10360 (if (null node)
10361 (message "No node found at location %s" (point))
10362 (setq beg (js2-node-abs-pos node)
10363 end (+ beg (js2-node-len node)))
10364 (if js2-mode-node-overlay
10365 (move-overlay js2-mode-node-overlay beg end)
10366 (setq js2-mode-node-overlay (make-overlay beg end))
10367 (overlay-put js2-mode-node-overlay 'face 'highlight))
10368 (js2-with-unmodifying-text-property-changes
10369 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10370 (message "%s, parent: %s"
10371 (js2-node-short-name node)
10372 (if (js2-node-parent node)
10373 (js2-node-short-name (js2-node-parent node))
10374 "nil"))))))
10375
10376 (defun js2-mode-hide-overlay (&optional p1 p2)
10377 "Remove the debugging overlay when the point moves.
10378 P1 and P2 are the old and new values of point, respectively."
10379 (when js2-mode-node-overlay
10380 (let ((beg (overlay-start js2-mode-node-overlay))
10381 (end (overlay-end js2-mode-node-overlay)))
10382 ;; Sometimes we're called spuriously.
10383 (unless (and p2
10384 (>= p2 beg)
10385 (<= p2 end))
10386 (js2-with-unmodifying-text-property-changes
10387 (remove-text-properties beg end '(point-left nil)))
10388 (delete-overlay js2-mode-node-overlay)
10389 (setq js2-mode-node-overlay nil)))))
10390
10391 (defun js2-mode-reset ()
10392 "Debugging helper: reset everything."
10393 (interactive)
10394 (js2-mode-exit)
10395 (js2-mode))
10396
10397 (defsubst js2-mode-show-warn-or-err (e face)
10398 "Highlight a warning or error E with FACE.
10399 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10400 (let* ((key (first e))
10401 (beg (second e))
10402 (end (+ beg (third e)))
10403 ;; Don't inadvertently go out of bounds.
10404 (beg (max (point-min) (min beg (point-max))))
10405 (end (max (point-min) (min end (point-max))))
10406 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10407 (ovl (make-overlay beg end)))
10408 (overlay-put ovl 'face face)
10409 (overlay-put ovl 'js2-error t)
10410 (put-text-property beg end 'help-echo (js2-get-msg key))
10411 (put-text-property beg end 'point-entered #'js2-echo-error)))
10412
10413 (defun js2-remove-overlays ()
10414 "Remove overlays from buffer that have a `js2-error' property."
10415 (let ((beg (point-min))
10416 (end (point-max)))
10417 (save-excursion
10418 (dolist (o (overlays-in beg end))
10419 (when (overlay-get o 'js2-error)
10420 (delete-overlay o))))))
10421
10422 (defun js2-error-at-point (&optional pos)
10423 "Return non-nil if there's an error overlay at POS.
10424 Defaults to point."
10425 (loop with pos = (or pos (point))
10426 for o in (overlays-at pos)
10427 thereis (overlay-get o 'js2-error)))
10428
10429 (defun js2-mode-fontify-regions ()
10430 "Apply fontifications recorded during parsing."
10431 ;; We defer clearing faces as long as possible to eliminate flashing.
10432 (js2-clear-face (point-min) (point-max))
10433 ;; have to reverse the recorded fontifications so that errors and
10434 ;; warnings overwrite the normal fontifications
10435 (dolist (f (nreverse js2-mode-fontifications))
10436 (put-text-property (first f) (second f) 'face (third f)))
10437 (setq js2-mode-fontifications nil)
10438 (dolist (p js2-mode-deferred-properties)
10439 (apply #'put-text-property p))
10440 (setq js2-mode-deferred-properties nil))
10441
10442 (defun js2-mode-show-errors ()
10443 "Highlight syntax errors."
10444 (when js2-mode-show-parse-errors
10445 (dolist (e (js2-ast-root-errors js2-mode-ast))
10446 (js2-mode-show-warn-or-err e 'js2-error))))
10447
10448 (defun js2-mode-remove-suppressed-warnings ()
10449 "Take suppressed warnings out of the AST warnings list.
10450 This ensures that the counts and `next-error' are correct."
10451 (setf (js2-ast-root-warnings js2-mode-ast)
10452 (js2-delete-if
10453 (lambda (e)
10454 (let ((key (caar e)))
10455 (or
10456 (and (not js2-strict-trailing-comma-warning)
10457 (string-match "trailing\\.comma" key))
10458 (and (not js2-strict-cond-assign-warning)
10459 (string= key "msg.equal.as.assign"))
10460 (and js2-missing-semi-one-line-override
10461 (string= key "msg.missing.semi")
10462 (let* ((beg (second e))
10463 (node (js2-node-at-point beg))
10464 (fn (js2-mode-find-parent-fn node))
10465 (body (and fn (js2-function-node-body fn)))
10466 (lc (and body (js2-node-abs-pos body)))
10467 (rc (and lc (+ lc (js2-node-len body)))))
10468 (and fn
10469 (or (null body)
10470 (save-excursion
10471 (goto-char beg)
10472 (and (js2-same-line lc)
10473 (js2-same-line rc))))))))))
10474 (js2-ast-root-warnings js2-mode-ast))))
10475
10476 (defun js2-mode-show-warnings ()
10477 "Highlight strict-mode warnings."
10478 (when js2-mode-show-strict-warnings
10479 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10480 (js2-mode-show-warn-or-err e 'js2-warning))))
10481
10482 (defun js2-echo-error (old-point new-point)
10483 "Called by point-motion hooks."
10484 (let ((msg (get-text-property new-point 'help-echo)))
10485 (if msg
10486 (message msg))))
10487
10488 (defalias #'js2-echo-help #'js2-echo-error)
10489
10490 (defun js2-enter-key ()
10491 "Handle user pressing the Enter key."
10492 (interactive)
10493 (let ((parse-status (save-excursion
10494 (parse-partial-sexp (point-min) (point)))))
10495 (cond
10496 ;; check if we're inside a string
10497 ((nth 3 parse-status)
10498 (js2-mode-split-string parse-status))
10499 ;; check if inside a block comment
10500 ((nth 4 parse-status)
10501 (js2-mode-extend-comment))
10502 (t
10503 ;; should probably figure out what the mode-map says we should do
10504 (if js2-indent-on-enter-key
10505 (let ((js2-bounce-indent-p nil))
10506 (js2-indent-line)))
10507 (insert "\n")
10508 (if js2-enter-indents-newline
10509 (let ((js2-bounce-indent-p nil))
10510 (js2-indent-line)))))))
10511
10512 (defun js2-mode-split-string (parse-status)
10513 "Turn a newline in mid-string into a string concatenation.
10514 PARSE-STATUS is as documented in `parse-partial-sexp'."
10515 (let* ((col (current-column))
10516 (quote-char (nth 3 parse-status))
10517 (quote-string (string quote-char))
10518 (string-beg (nth 8 parse-status))
10519 (indent (save-match-data
10520 (or
10521 (save-excursion
10522 (back-to-indentation)
10523 (if (looking-at "\\+")
10524 (current-column)))
10525 (save-excursion
10526 (goto-char string-beg)
10527 (if (looking-back "\\+\\s-+")
10528 (goto-char (match-beginning 0)))
10529 (current-column))))))
10530 (insert quote-char "\n")
10531 (indent-to indent)
10532 (insert "+ " quote-string)
10533 (when (eolp)
10534 (insert quote-string)
10535 (backward-char 1))))
10536
10537 (defun js2-mode-extend-comment ()
10538 "When inside a comment block, add comment prefix."
10539 (let (star single col first-line needs-close)
10540 (save-excursion
10541 (back-to-indentation)
10542 (cond
10543 ((looking-at "\\*[^/]")
10544 (setq star t
10545 col (current-column)))
10546 ((looking-at "/\\*")
10547 (setq star t
10548 first-line t
10549 col (1+ (current-column))))
10550 ((looking-at "//")
10551 (setq single t
10552 col (current-column)))))
10553 ;; Heuristic for whether we need to close the comment:
10554 ;; if we've got a parse error here, assume it's an unterminated
10555 ;; comment.
10556 (setq needs-close
10557 (or
10558 (eq (get-text-property (1- (point)) 'point-entered)
10559 'js2-echo-error)
10560 ;; The heuristic above doesn't work well when we're
10561 ;; creating a comment and there's another one downstream,
10562 ;; as our parser thinks this one ends at the end of the
10563 ;; next one. (You can have a /* inside a js block comment.)
10564 ;; So just close it if the next non-ws char isn't a *.
10565 (and first-line
10566 (eolp)
10567 (save-excursion
10568 (skip-chars-forward " \t\r\n")
10569 (not (eq (char-after) ?*))))))
10570 (insert "\n")
10571 (cond
10572 (star
10573 (indent-to col)
10574 (insert "* ")
10575 (if (and first-line needs-close)
10576 (save-excursion
10577 (insert "\n")
10578 (indent-to col)
10579 (insert "*/"))))
10580 (single
10581 (when (save-excursion
10582 (and (zerop (forward-line 1))
10583 (looking-at "\\s-*//")))
10584 (indent-to col)
10585 (insert "// "))))))
10586
10587 (defun js2-beginning-of-line ()
10588 "Toggles point between bol and first non-whitespace char in line.
10589 Also moves past comment delimiters when inside comments."
10590 (interactive)
10591 (let (node beg)
10592 (cond
10593 ((bolp)
10594 (back-to-indentation))
10595 ((looking-at "//")
10596 (skip-chars-forward "/ \t"))
10597 ((and (eq (char-after) ?*)
10598 (setq node (js2-comment-at-point))
10599 (memq (js2-comment-node-format node) '(jsdoc block))
10600 (save-excursion
10601 (skip-chars-backward " \t")
10602 (bolp)))
10603 (skip-chars-forward "\* \t"))
10604 (t
10605 (goto-char (point-at-bol))))))
10606
10607 (defun js2-end-of-line ()
10608 "Toggles point between eol and last non-whitespace char in line."
10609 (interactive)
10610 (if (eolp)
10611 (skip-chars-backward " \t")
10612 (goto-char (point-at-eol))))
10613
10614 (defun js2-enter-mirror-mode()
10615 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10616 on insertion."
10617 (interactive)
10618 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10619 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10620 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10621 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10622 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10623 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10624 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10625 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10626
10627 (defun js2-leave-mirror-mode()
10628 "Turns off mirror mode."
10629 (interactive)
10630 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10631 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10632
10633 (defsubst js2-mode-inside-string ()
10634 "Return non-nil if inside a string.
10635 Actually returns the quote character that begins the string."
10636 (let ((parse-state (save-excursion
10637 (parse-partial-sexp (point-min) (point)))))
10638 (nth 3 parse-state)))
10639
10640 (defsubst js2-mode-inside-comment-or-string ()
10641 "Return non-nil if inside a comment or string."
10642 (or
10643 (let ((comment-start
10644 (save-excursion
10645 (goto-char (point-at-bol))
10646 (if (re-search-forward "//" (point-at-eol) t)
10647 (match-beginning 0)))))
10648 (and comment-start
10649 (<= comment-start (point))))
10650 (let ((parse-state (save-excursion
10651 (parse-partial-sexp (point-min) (point)))))
10652 (or (nth 3 parse-state)
10653 (nth 4 parse-state)))))
10654
10655 (defsubst js2-make-magic-delimiter (delim &optional pos)
10656 "Add `js2-magic' and `js2-magic-paren' to DELIM, a string.
10657 Sets value of `js2-magic' text property to line number at POS."
10658 (propertize delim
10659 'js2-magic (line-number-at-pos pos)
10660 'face 'js2-magic-paren))
10661
10662 (defun js2-mode-match-delimiter (open close)
10663 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10664 The rule we use, which as far as we can tell is how Eclipse works,
10665 is that we insert the match if we're not in a comment or string,
10666 and the next non-whitespace character is either punctuation or
10667 occurs on another line."
10668 (insert open)
10669 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10670 (not (js2-mode-inside-comment-or-string)))
10671 (save-excursion
10672 (insert (js2-make-magic-delimiter close)))
10673 (when js2-auto-indent-p
10674 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10675 (js2-indent-line)))))
10676
10677 (defun js2-mode-match-bracket ()
10678 "Insert matching bracket."
10679 (interactive)
10680 (js2-mode-match-delimiter "[" "]"))
10681
10682 (defun js2-mode-match-paren ()
10683 "Insert matching paren unless already inserted."
10684 (interactive)
10685 (js2-mode-match-delimiter "(" ")"))
10686
10687 (defun js2-mode-match-curly (arg)
10688 "Insert matching curly-brace.
10689 With prefix arg, no formatting or indentation will occur -- the close-brace
10690 is simply inserted directly at the point."
10691 (interactive "p")
10692 (let (try-pos)
10693 (cond
10694 (current-prefix-arg
10695 (js2-mode-match-delimiter "{" "}"))
10696 ((and js2-auto-insert-catch-block
10697 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10698 (point-at-bol))
10699 (match-beginning 1))))
10700 (js2-insert-catch-skel try-pos))
10701 (t
10702 ;; Otherwise try to do something smarter.
10703 (insert "{")
10704 (unless (or (not (looking-at "\\s-*$"))
10705 (save-excursion
10706 (skip-chars-forward " \t\r\n")
10707 (and (looking-at "}")
10708 (js2-error-at-point)))
10709 (js2-mode-inside-comment-or-string))
10710 (undo-boundary)
10711 ;; absolutely mystifying bug: when inserting the next "\n",
10712 ;; the buffer-undo-list is given two new entries: the inserted range,
10713 ;; and the incorrect position of the point. It's recorded incorrectly
10714 ;; as being before the opening "{", not after it. But it's recorded
10715 ;; as the correct value if you're debugging `js2-mode-match-curly'
10716 ;; in edebug. I have no idea why it's doing this, but incrementing
10717 ;; the inserted position fixes the problem, so that the undo takes us
10718 ;; back to just after the user-inserted "{".
10719 (insert "\n")
10720 (ignore-errors
10721 (incf (cadr buffer-undo-list)))
10722 (js2-indent-line)
10723 (save-excursion
10724 (insert "\n}")
10725 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10726 (js2-indent-line))))))))
10727
10728 (defun js2-insert-catch-skel (try-pos)
10729 "Complete a try/catch block after inserting a { following a try keyword.
10730 Rationale is that a try always needs a catch or a finally, and the catch is
10731 the more likely of the two.
10732
10733 TRY-POS is the buffer position of the try keyword. The open-curly should
10734 already have been inserted."
10735 (insert "{")
10736 (let ((try-col (save-excursion
10737 (goto-char try-pos)
10738 (current-column))))
10739 (insert "\n")
10740 (undo-boundary)
10741 (js2-indent-line) ;; indent the blank line where cursor will end up
10742 (save-excursion
10743 (insert "\n")
10744 (indent-to try-col)
10745 (insert "} catch (x) {\n\n")
10746 (indent-to try-col)
10747 (insert "}"))))
10748
10749 (defun js2-mode-highlight-magic-parens ()
10750 "Re-highlight magic parens after parsing nukes the 'face prop."
10751 (let ((beg (point-min))
10752 end)
10753 (while (setq beg (next-single-property-change beg 'js2-magic))
10754 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10755 (if (get-text-property beg 'js2-magic)
10756 (js2-with-unmodifying-text-property-changes
10757 (put-text-property beg (or end (1+ beg))
10758 'face 'js2-magic-paren))))))
10759
10760 (defun js2-mode-mundanify-parens ()
10761 "Clear all magic parens and brackets."
10762 (let ((beg (point-min))
10763 end)
10764 (while (setq beg (next-single-property-change beg 'js2-magic))
10765 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10766 (remove-text-properties beg (or end (1+ beg))
10767 '(js2-magic face)))))
10768
10769 (defsubst js2-match-quote (quote-string)
10770 (let ((start-quote (js2-mode-inside-string)))
10771 (cond
10772 ;; inside a comment - don't do quote-matching, since we can't
10773 ;; reliably figure out if we're in a string inside the comment
10774 ((js2-comment-at-point)
10775 (insert quote-string))
10776 ((not start-quote)
10777 ;; not in string => insert matched quotes
10778 (insert quote-string)
10779 ;; exception: if we're just before a word, don't double it.
10780 (unless (looking-at "[^ \t\r\n]")
10781 (save-excursion
10782 (insert quote-string))))
10783 ((looking-at quote-string)
10784 (if (looking-back "[^\\]\\\\")
10785 (insert quote-string)
10786 (forward-char 1)))
10787 ((and js2-mode-escape-quotes
10788 (save-excursion
10789 (save-match-data
10790 (re-search-forward quote-string (point-at-eol) t))))
10791 ;; inside terminated string, escape quote (unless already escaped)
10792 (insert (if (looking-back "[^\\]\\\\")
10793 quote-string
10794 (concat "\\" quote-string))))
10795 (t
10796 (insert quote-string))))) ; else terminate the string
10797
10798 (defun js2-mode-match-single-quote ()
10799 "Insert matching single-quote."
10800 (interactive)
10801 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10802 ;; don't match inside comments, since apostrophe is more common
10803 (if (nth 4 parse-status)
10804 (insert "'")
10805 (js2-match-quote "'"))))
10806
10807 (defun js2-mode-match-double-quote ()
10808 "Insert matching double-quote."
10809 (interactive)
10810 (js2-match-quote "\""))
10811
10812 ;; Eclipse works as follows:
10813 ;; * type an open-paren and it auto-inserts close-paren
10814 ;; - auto-inserted paren gets a green bracket
10815 ;; - green bracket means typing close-paren there will skip it
10816 ;; * if you insert any text on a different line, it turns off
10817 (defun js2-mode-magic-close-paren ()
10818 "Skip over close-paren rather than inserting, where appropriate."
10819 (interactive)
10820 (let* ((here (point))
10821 (parse-status (parse-partial-sexp (point-min) here))
10822 (open-pos (nth 1 parse-status))
10823 (close last-input-event)
10824 (open (cond
10825 ((eq close ?\))
10826 ?\()
10827 ((eq close ?\])
10828 ?\[)
10829 ((eq close ?})
10830 ?{)
10831 (t nil))))
10832 (if (and (eq (char-after) close)
10833 (eq open (char-after open-pos))
10834 (js2-same-line open-pos)
10835 (get-text-property here 'js2-magic))
10836 (progn
10837 (remove-text-properties here (1+ here) '(js2-magic face))
10838 (forward-char 1))
10839 (insert-char close 1))
10840 (blink-matching-open)))
10841
10842 (defun js2-mode-wait-for-parse (callback)
10843 "Invoke CALLBACK when parsing is finished.
10844 If parsing is already finished, calls CALLBACK immediately."
10845 (if (not js2-mode-buffer-dirty-p)
10846 (funcall callback)
10847 (push callback js2-mode-pending-parse-callbacks)
10848 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10849
10850 (defun js2-mode-parse-finished ()
10851 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10852 ;; We can't let errors propagate up, since it prevents the
10853 ;; `js2-parse' method from completing normally and returning
10854 ;; the ast, which makes things mysteriously not work right.
10855 (unwind-protect
10856 (dolist (cb js2-mode-pending-parse-callbacks)
10857 (condition-case err
10858 (funcall cb)
10859 (error (message "%s" err))))
10860 (setq js2-mode-pending-parse-callbacks nil)))
10861
10862 (defun js2-mode-flag-region (from to flag)
10863 "Hide or show text from FROM to TO, according to FLAG.
10864 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10865 Returns the created overlay if FLAG is non-nil."
10866 (remove-overlays from to 'invisible 'js2-outline)
10867 (when flag
10868 (let ((o (make-overlay from to)))
10869 (overlay-put o 'invisible 'js2-outline)
10870 (overlay-put o 'isearch-open-invisible
10871 'js2-isearch-open-invisible)
10872 o)))
10873
10874 ;; Function to be set as an outline-isearch-open-invisible' property
10875 ;; to the overlay that makes the outline invisible (see
10876 ;; `js2-mode-flag-region').
10877 (defun js2-isearch-open-invisible (overlay)
10878 ;; We rely on the fact that isearch places point on the matched text.
10879 (js2-mode-show-element))
10880
10881 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10882 "Return cons cell of bounds of folding overlay at POS.
10883 Returns nil if not found."
10884 (let ((overlays (overlays-at (or pos (point))))
10885 o)
10886 (while (and overlays
10887 (not o))
10888 (if (overlay-get (car overlays) 'invisible)
10889 (setq o (car overlays))
10890 (setq overlays (cdr overlays))))
10891 (if o
10892 (cons (overlay-start o) (overlay-end o)))))
10893
10894 (defun js2-mode-function-at-point (&optional pos)
10895 "Return the innermost function node enclosing current point.
10896 Returns nil if point is not in a function."
10897 (let ((node (js2-node-at-point pos)))
10898 (while (and node (not (js2-function-node-p node)))
10899 (setq node (js2-node-parent node)))
10900 (if (js2-function-node-p node)
10901 node)))
10902
10903 (defun js2-mode-toggle-element ()
10904 "Hide or show the foldable element at the point."
10905 (interactive)
10906 (let (comment fn pos)
10907 (save-excursion
10908 (save-match-data
10909 (cond
10910 ;; /* ... */ comment?
10911 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10912 (if (js2-mode-invisible-overlay-bounds
10913 (setq pos (+ 3 (js2-node-abs-pos comment))))
10914 (progn
10915 (goto-char pos)
10916 (js2-mode-show-element))
10917 (js2-mode-hide-element)))
10918 ;; //-comment?
10919 ((save-excursion
10920 (back-to-indentation)
10921 (looking-at js2-mode-//-comment-re))
10922 (js2-mode-toggle-//-comment))
10923 ;; function?
10924 ((setq fn (js2-mode-function-at-point))
10925 (setq pos (and (js2-function-node-body fn)
10926 (js2-node-abs-pos (js2-function-node-body fn))))
10927 (goto-char (1+ pos))
10928 (if (js2-mode-invisible-overlay-bounds)
10929 (js2-mode-show-element)
10930 (js2-mode-hide-element)))
10931 (t
10932 (message "Nothing at point to hide or show")))))))
10933
10934 (defun js2-mode-hide-element ()
10935 "Fold/hide contents of a block, showing ellipses.
10936 Show the hidden text with \\[js2-mode-show-element]."
10937 (interactive)
10938 (if js2-mode-buffer-dirty-p
10939 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10940 (let (node body beg end)
10941 (cond
10942 ((js2-mode-invisible-overlay-bounds)
10943 (message "already hidden"))
10944 (t
10945 (setq node (js2-node-at-point))
10946 (cond
10947 ((js2-block-comment-p node)
10948 (js2-mode-hide-comment node))
10949 (t
10950 (while (and node (not (js2-function-node-p node)))
10951 (setq node (js2-node-parent node)))
10952 (if (and node
10953 (setq body (js2-function-node-body node)))
10954 (progn
10955 (setq beg (js2-node-abs-pos body)
10956 end (+ beg (js2-node-len body)))
10957 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10958 (message "No collapsable element found at point"))))))))
10959
10960 (defun js2-mode-show-element ()
10961 "Show the hidden element at current point."
10962 (interactive)
10963 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10964 (if bounds
10965 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10966 (message "Nothing to un-hide"))))
10967
10968 (defun js2-mode-show-all ()
10969 "Show all of the text in the buffer."
10970 (interactive)
10971 (js2-mode-flag-region (point-min) (point-max) nil))
10972
10973 (defun js2-mode-toggle-hide-functions ()
10974 (interactive)
10975 (if js2-mode-functions-hidden
10976 (js2-mode-show-functions)
10977 (js2-mode-hide-functions)))
10978
10979 (defun js2-mode-hide-functions ()
10980 "Hides all non-nested function bodies in the buffer.
10981 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10982 to open an individual entry."
10983 (interactive)
10984 (if js2-mode-buffer-dirty-p
10985 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10986 (if (null js2-mode-ast)
10987 (message "Oops - parsing failed")
10988 (setq js2-mode-functions-hidden t)
10989 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10990
10991 (defun js2-mode-function-hider (n endp)
10992 (when (not endp)
10993 (let ((tt (js2-node-type n))
10994 body beg end)
10995 (cond
10996 ((and (= tt js2-FUNCTION)
10997 (setq body (js2-function-node-body n)))
10998 (setq beg (js2-node-abs-pos body)
10999 end (+ beg (js2-node-len body)))
11000 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11001 nil) ; don't process children of function
11002 (t
11003 t))))) ; keep processing other AST nodes
11004
11005 (defun js2-mode-show-functions ()
11006 "Un-hide any folded function bodies in the buffer."
11007 (interactive)
11008 (setq js2-mode-functions-hidden nil)
11009 (save-excursion
11010 (goto-char (point-min))
11011 (while (/= (goto-char (next-overlay-change (point)))
11012 (point-max))
11013 (dolist (o (overlays-at (point)))
11014 (when (and (overlay-get o 'invisible)
11015 (not (overlay-get o 'comment)))
11016 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11017
11018 (defun js2-mode-hide-comment (n)
11019 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11020 3 ; /**
11021 2)) ; /*
11022 (beg (+ (js2-node-abs-pos n) head))
11023 (end (- (+ beg (js2-node-len n)) head 2))
11024 (o (js2-mode-flag-region beg end 'hide)))
11025 (overlay-put o 'comment t)))
11026
11027 (defun js2-mode-toggle-hide-comments ()
11028 "Folds all block comments in the buffer.
11029 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11030 to open an individual entry."
11031 (interactive)
11032 (if js2-mode-comments-hidden
11033 (js2-mode-show-comments)
11034 (js2-mode-hide-comments)))
11035
11036 (defun js2-mode-hide-comments ()
11037 (interactive)
11038 (if js2-mode-buffer-dirty-p
11039 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11040 (if (null js2-mode-ast)
11041 (message "Oops - parsing failed")
11042 (setq js2-mode-comments-hidden t)
11043 (dolist (n (js2-ast-root-comments js2-mode-ast))
11044 (let ((format (js2-comment-node-format n)))
11045 (when (js2-block-comment-p n)
11046 (js2-mode-hide-comment n))))
11047 (js2-mode-hide-//-comments)))
11048
11049 (defsubst js2-mode-extend-//-comment (direction)
11050 "Find start or end of a block of similar //-comment lines.
11051 DIRECTION is -1 to look back, 1 to look forward.
11052 INDENT is the indentation level to match.
11053 Returns the end-of-line position of the furthest adjacent
11054 //-comment line with the same indentation as the current line.
11055 If there is no such matching line, returns current end of line."
11056 (let ((pos (point-at-eol))
11057 (indent (current-indentation)))
11058 (save-excursion
11059 (save-match-data
11060 (while (and (zerop (forward-line direction))
11061 (looking-at js2-mode-//-comment-re)
11062 (eq indent (length (match-string 1))))
11063 (setq pos (point-at-eol)))
11064 pos))))
11065
11066 (defun js2-mode-hide-//-comments ()
11067 "Fold adjacent 1-line comments, showing only snippet of first one."
11068 (let (beg end)
11069 (save-excursion
11070 (save-match-data
11071 (goto-char (point-min))
11072 (while (re-search-forward js2-mode-//-comment-re nil t)
11073 (setq beg (point)
11074 end (js2-mode-extend-//-comment 1))
11075 (unless (eq beg end)
11076 (overlay-put (js2-mode-flag-region beg end 'hide)
11077 'comment t))
11078 (goto-char end)
11079 (forward-char 1))))))
11080
11081 (defun js2-mode-toggle-//-comment ()
11082 "Fold or un-fold any multi-line //-comment at point.
11083 Caller should have determined that this line starts with a //-comment."
11084 (let* ((beg (point-at-eol))
11085 (end beg))
11086 (save-excursion
11087 (goto-char end)
11088 (if (js2-mode-invisible-overlay-bounds)
11089 (js2-mode-show-element)
11090 ;; else hide the comment
11091 (setq beg (js2-mode-extend-//-comment -1)
11092 end (js2-mode-extend-//-comment 1))
11093 (unless (eq beg end)
11094 (overlay-put (js2-mode-flag-region beg end 'hide)
11095 'comment t))))))
11096
11097 (defun js2-mode-show-comments ()
11098 "Un-hide any hidden comments, leaving other hidden elements alone."
11099 (interactive)
11100 (setq js2-mode-comments-hidden nil)
11101 (save-excursion
11102 (goto-char (point-min))
11103 (while (/= (goto-char (next-overlay-change (point)))
11104 (point-max))
11105 (dolist (o (overlays-at (point)))
11106 (when (overlay-get o 'comment)
11107 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11108
11109 (defun js2-mode-display-warnings-and-errors ()
11110 "Turn on display of warnings and errors."
11111 (interactive)
11112 (setq js2-mode-show-parse-errors t
11113 js2-mode-show-strict-warnings t)
11114 (js2-reparse 'force))
11115
11116 (defun js2-mode-hide-warnings-and-errors ()
11117 "Turn off display of warnings and errors."
11118 (interactive)
11119 (setq js2-mode-show-parse-errors nil
11120 js2-mode-show-strict-warnings nil)
11121 (js2-reparse 'force))
11122
11123 (defun js2-mode-toggle-warnings-and-errors ()
11124 "Toggle the display of warnings and errors.
11125 Some users don't like having warnings/errors reported while they type."
11126 (interactive)
11127 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11128 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11129 (if (interactive-p)
11130 (message "warnings and errors %s"
11131 (if js2-mode-show-parse-errors
11132 "enabled"
11133 "disabled")))
11134 (js2-reparse 'force))
11135
11136 (defun js2-mode-customize ()
11137 (interactive)
11138 (customize-group 'js2-mode))
11139
11140 (defun js2-mode-forward-sexp (&optional arg)
11141 "Move forward across one statement or balanced expression.
11142 With ARG, do it that many times. Negative arg -N means
11143 move backward across N balanced expressions."
11144 (interactive "p")
11145 (setq arg (or arg 1))
11146 (if js2-mode-buffer-dirty-p
11147 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11148 (let (node end (start (point)))
11149 (cond
11150 ;; backward-sexp
11151 ;; could probably make this better for some cases:
11152 ;; - if in statement block (e.g. function body), go to parent
11153 ;; - infix exprs like (foo in bar) - maybe go to beginning
11154 ;; of infix expr if in the right-side expression?
11155 ((and arg (minusp arg))
11156 (dotimes (i (- arg))
11157 (js2-backward-sws)
11158 (forward-char -1) ; enter the node we backed up to
11159 (setq node (js2-node-at-point (point) t))
11160 (goto-char (if node
11161 (js2-node-abs-pos node)
11162 (point-min)))))
11163 (t
11164 ;; forward-sexp
11165 (js2-forward-sws)
11166 (dotimes (i arg)
11167 (js2-forward-sws)
11168 (setq node (js2-node-at-point (point) t)
11169 end (if node (+ (js2-node-abs-pos node)
11170 (js2-node-len node))))
11171 (goto-char (or end (point-max))))))))
11172
11173 (defun js2-next-error (&optional arg reset)
11174 "Move to next parse error.
11175 Typically invoked via \\[next-error].
11176 ARG is the number of errors, forward or backward, to move.
11177 RESET means start over from the beginning."
11178 (interactive "p")
11179 (if (or (null js2-mode-ast)
11180 (and (null (js2-ast-root-errors js2-mode-ast))
11181 (null (js2-ast-root-warnings js2-mode-ast))))
11182 (message "No errors")
11183 (when reset
11184 (goto-char (point-min)))
11185 (let* ((errs (copy-sequence
11186 (append (js2-ast-root-errors js2-mode-ast)
11187 (js2-ast-root-warnings js2-mode-ast))))
11188 (continue t)
11189 (start (point))
11190 (count (or arg 1))
11191 (backward (minusp count))
11192 (sorter (if backward '> '<))
11193 (stopper (if backward '< '>))
11194 (count (abs count))
11195 all-errs
11196 err)
11197 ;; sort by start position
11198 (setq errs (sort errs (lambda (e1 e2)
11199 (funcall sorter (second e1) (second e2))))
11200 all-errs errs)
11201 ;; find nth error with pos > start
11202 (while (and errs continue)
11203 (when (funcall stopper (cadar errs) start)
11204 (setq err (car errs))
11205 (if (zerop (decf count))
11206 (setq continue nil)))
11207 (setq errs (cdr errs)))
11208 (if err
11209 (goto-char (second err))
11210 ;; wrap around to first error
11211 (goto-char (second (car all-errs)))
11212 ;; if we were already on it, echo msg again
11213 (if (= (point) start)
11214 (js2-echo-error (point) (point)))))))
11215
11216 (defun js2-down-mouse-3 ()
11217 "Make right-click move the point to the click location.
11218 This makes right-click context menu operations a bit more intuitive.
11219 The point will not move if the region is active, however, to avoid
11220 destroying the region selection."
11221 (interactive)
11222 (when (and js2-move-point-on-right-click
11223 (not mark-active))
11224 (let ((e last-input-event))
11225 (ignore-errors
11226 (goto-char (cadadr e))))))
11227
11228 (defun js2-mode-create-imenu-index ()
11229 "Return an alist for `imenu--index-alist'."
11230 ;; This is built up in `js2-parse-record-imenu' during parsing.
11231 (when js2-mode-ast
11232 ;; if we have an ast but no recorder, they're requesting a rescan
11233 (unless js2-imenu-recorder
11234 (js2-reparse 'force))
11235 (prog1
11236 (js2-build-imenu-index)
11237 (setq js2-imenu-recorder nil
11238 js2-imenu-function-map nil))))
11239
11240 (defun js2-mode-find-tag ()
11241 "Replacement for `find-tag-default'.
11242 `find-tag-default' returns a ridiculous answer inside comments."
11243 (let (beg end)
11244 (js2-with-underscore-as-word-syntax
11245 (save-excursion
11246 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11247 (looking-back "[A-Za-z0-9_$]"))
11248 (setq beg (progn (forward-word -1) (point))
11249 end (progn (forward-word 1) (point)))
11250 (setq beg (progn (forward-word 1) (point))
11251 end (progn (forward-word -1) (point))))
11252 (replace-regexp-in-string
11253 "[\"']" ""
11254 (buffer-substring-no-properties beg end))))))
11255
11256 (defun js2-mode-forward-sibling ()
11257 "Move to the end of the sibling following point in parent.
11258 Returns non-nil if successful, or nil if there was no following sibling."
11259 (let* ((node (js2-node-at-point))
11260 (parent (js2-mode-find-enclosing-fn node))
11261 sib)
11262 (when (setq sib (js2-node-find-child-after (point) parent))
11263 (goto-char (+ (js2-node-abs-pos sib)
11264 (js2-node-len sib))))))
11265
11266 (defun js2-mode-backward-sibling ()
11267 "Move to the beginning of the sibling node preceding point in parent.
11268 Parent is defined as the enclosing script or function."
11269 (let* ((node (js2-node-at-point))
11270 (parent (js2-mode-find-enclosing-fn node))
11271 sib)
11272 (when (setq sib (js2-node-find-child-before (point) parent))
11273 (goto-char (js2-node-abs-pos sib)))))
11274
11275 (defun js2-beginning-of-defun ()
11276 "Go to line on which current function starts, and return non-nil.
11277 If we're not in a function, go to beginning of previous script-level element."
11278 (interactive)
11279 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11280 pos sib)
11281 (cond
11282 ((and (js2-function-node-p parent)
11283 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11284 (goto-char pos))
11285 (t
11286 (js2-mode-backward-sibling)))))
11287
11288 (defun js2-end-of-defun ()
11289 "Go to the char after the last position of the current function.
11290 If we're not in a function, skips over the next script-level element."
11291 (interactive)
11292 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11293 (if (not (js2-function-node-p parent))
11294 ;; punt: skip over next script-level element beyond point
11295 (js2-mode-forward-sibling)
11296 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11297 (js2-node-len parent)))))))
11298
11299 (defun js2-mark-defun (&optional allow-extend)
11300 "Put mark at end of this function, point at beginning.
11301 The function marked is the one that contains point.
11302
11303 Interactively, if this command is repeated,
11304 or (in Transient Mark mode) if the mark is active,
11305 it marks the next defun after the ones already marked."
11306 (interactive "p")
11307 (let (extended)
11308 (when (and allow-extend
11309 (or (and (eq last-command this-command) (mark t))
11310 (and transient-mark-mode mark-active)))
11311 (let ((sib (save-excursion
11312 (goto-char (mark))
11313 (if (js2-mode-forward-sibling)
11314 (point))))
11315 node)
11316 (if sib
11317 (progn
11318 (set-mark sib)
11319 (setq extended t))
11320 ;; no more siblings - try extending to enclosing node
11321 (goto-char (mark t)))))
11322 (when (not extended)
11323 (let ((node (js2-node-at-point (point) t)) ; skip comments
11324 ast fn stmt parent beg end)
11325 (when (js2-ast-root-p node)
11326 (setq ast node
11327 node (or (js2-node-find-child-after (point) node)
11328 (js2-node-find-child-before (point) node))))
11329 ;; only mark whole buffer if we can't find any children
11330 (if (null node)
11331 (setq node ast))
11332 (if (js2-function-node-p node)
11333 (setq parent node)
11334 (setq fn (js2-mode-find-enclosing-fn node)
11335 stmt (if (or (null fn)
11336 (js2-ast-root-p fn))
11337 (js2-mode-find-first-stmt node))
11338 parent (or stmt fn)))
11339 (setq beg (js2-node-abs-pos parent)
11340 end (+ beg (js2-node-len parent)))
11341 (push-mark beg)
11342 (goto-char end)
11343 (exchange-point-and-mark)))))
11344
11345 (defun js2-narrow-to-defun ()
11346 "Narrow to the function enclosing point."
11347 (interactive)
11348 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11349 (fn (if (js2-script-node-p node)
11350 node
11351 (js2-mode-find-enclosing-fn node)))
11352 (beg (js2-node-abs-pos fn)))
11353 (unless (js2-ast-root-p fn)
11354 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11355
11356 (provide 'js2-mode)
11357
11358 ;; arch-tag: 1dd56864-a3ef-4682-a63f-6341f6a42738
11359 ;;; js2-mode.el ends here