]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Trailing comma is legal ecma-262-5.1
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011, 2012 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: 1.1
9 ;; Keywords: languages, javascript
10 ;; Package-Requires: ((emacs "24.1"))
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; This JavaScript editing mode supports:
30
31 ;; - strict recognition of the Ecma-262 language standard
32 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
33 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
34 ;; - accurate syntax highlighting using a recursive-descent parser
35 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
36 ;; - undeclared-variable warnings using a configurable externs framework
37 ;; - "bouncing" line indentation to choose among alternate indentation points
38 ;; - smart line-wrapping within comments and strings
39 ;; - code folding:
40 ;; - show some or all function bodies as {...}
41 ;; - show some or all block comments as /*...*/
42 ;; - context-sensitive menu bar and popup menus
43 ;; - code browsing using the `imenu' package
44 ;; - many customization options
45
46 ;; Installation:
47 ;;
48 ;; To install it as your major mode for JavaScript editing:
49
50 ;; (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
51
52 ;; Alternately, to install it as a minor mode just for JavaScript linting,
53 ;; you must add it to the appropriate major-mode hook. Normally this would be:
54
55 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
56
57 ;; To customize how it works:
58 ;; M-x customize-group RET js2-mode RET
59
60 ;; Notes:
61
62 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
63 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
64 ;; `js2-mode' current as the EcmaScript language standard evolves.
65
66 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
67 ;; customizable. It is a surprising amount of work to support customizable
68 ;; indentation. The current compromise is that the tab key lets you cycle among
69 ;; various likely indentation points, similar to the behavior of python-mode.
70
71 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
72 ;; and `mumamo', although it could be made to do so with some effort.
73 ;; This means that `js2-mode' is currently only useful for editing JavaScript
74 ;; files, and not for editing JavaScript within <script> tags or templates.
75
76 ;;; Code:
77
78 (eval-when-compile
79 (require 'cl))
80
81 (require 'imenu)
82 (require 'cc-cmds) ; for `c-fill-paragraph'
83
84 (eval-and-compile
85 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
86 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
87
88 (defvar electric-layout-rules)
89
90 ;;; Externs (variables presumed to be defined by the host system)
91
92 (defvar js2-ecma-262-externs
93 (mapcar 'symbol-name
94 '(Array Boolean Date Error EvalError Function Infinity JSON
95 Math NaN Number Object RangeError ReferenceError RegExp
96 String SyntaxError TypeError URIError arguments
97 decodeURI decodeURIComponent encodeURI
98 encodeURIComponent escape eval isFinite isNaN
99 parseFloat parseInt undefined unescape))
100 "Ecma-262 externs. Included in `js2-externs' by default.")
101
102 (defvar js2-browser-externs
103 (mapcar 'symbol-name
104 '(;; DOM level 1
105 Attr CDATASection CharacterData Comment DOMException
106 DOMImplementation Document DocumentFragment
107 DocumentType Element Entity EntityReference
108 ExceptionCode NamedNodeMap Node NodeList Notation
109 ProcessingInstruction Text
110
111 ;; DOM level 2
112 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
113 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
114 HTMLBodyElement HTMLButtonElement HTMLCollection
115 HTMLDListElement HTMLDirectoryElement HTMLDivElement
116 HTMLDocument HTMLElement HTMLFieldSetElement
117 HTMLFontElement HTMLFormElement HTMLFrameElement
118 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
119 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
120 HTMLImageElement HTMLInputElement HTMLIsIndexElement
121 HTMLLIElement HTMLLabelElement HTMLLegendElement
122 HTMLLinkElement HTMLMapElement HTMLMenuElement
123 HTMLMetaElement HTMLModElement HTMLOListElement
124 HTMLObjectElement HTMLOptGroupElement
125 HTMLOptionElement HTMLOptionsCollection
126 HTMLParagraphElement HTMLParamElement HTMLPreElement
127 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
128 HTMLStyleElement HTMLTableCaptionElement
129 HTMLTableCellElement HTMLTableColElement
130 HTMLTableElement HTMLTableRowElement
131 HTMLTableSectionElement HTMLTextAreaElement
132 HTMLTitleElement HTMLUListElement
133
134 ;; DOM level 3
135 DOMConfiguration DOMError DOMException
136 DOMImplementationList DOMImplementationSource
137 DOMLocator DOMStringList NameList TypeInfo
138 UserDataHandler
139
140 ;; Window
141 window alert confirm document java navigator prompt screen
142 self top
143
144 ;; W3C CSS
145 CSSCharsetRule CSSFontFace CSSFontFaceRule
146 CSSImportRule CSSMediaRule CSSPageRule
147 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
148 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
149 CSSValue CSSValueList Counter DOMImplementationCSS
150 DocumentCSS DocumentStyle ElementCSSInlineStyle
151 LinkStyle MediaList RGBColor Rect StyleSheet
152 StyleSheetList ViewCSS
153
154 ;; W3C Event
155 EventListener EventTarget Event DocumentEvent UIEvent
156 MouseEvent MutationEvent KeyboardEvent
157
158 ;; W3C Range
159 DocumentRange Range RangeException
160
161 ;; W3C XML
162 XPathResult XMLHttpRequest))
163 "Browser externs.
164 You can cause these to be included or excluded with the custom
165 variable `js2-include-browser-externs'.")
166
167 (defvar js2-rhino-externs
168 (mapcar 'symbol-name
169 '(Packages importClass importPackage com org java
170 ;; Global object (shell) externs.
171 defineClass deserialize doctest gc help load
172 loadClass print quit readFile readUrl runCommand seal
173 serialize spawn sync toint32 version))
174 "Mozilla Rhino externs.
175 Set `js2-include-rhino-externs' to t to include them.")
176
177 (defvar js2-gears-externs
178 (mapcar 'symbol-name
179 '(
180 ;; TODO(stevey): add these
181 ))
182 "Google Gears externs.
183 Set `js2-include-gears-externs' to t to include them.")
184
185 ;;; Variables
186
187 (defun js2-mark-safe-local (name pred)
188 "Make the variable NAME buffer-local and mark it as safe file-local
189 variable with predicate PRED."
190 (make-variable-buffer-local name)
191 (put name 'safe-local-variable pred))
192
193 (defcustom js2-highlight-level 2
194 "Amount of syntax highlighting to perform.
195 0 or a negative value means none.
196 1 adds basic syntax highlighting.
197 2 adds highlighting of some Ecma built-in properties.
198 3 adds highlighting of many Ecma built-in functions."
199 :group 'js2-mode
200 :type '(choice (const :tag "None" 0)
201 (const :tag "Basic" 1)
202 (const :tag "Include Properties" 2)
203 (const :tag "Include Functions" 3)))
204
205 (defvar js2-mode-dev-mode-p nil
206 "Non-nil if running in development mode. Normally nil.")
207
208 (defgroup js2-mode nil
209 "An improved JavaScript mode."
210 :group 'languages)
211
212 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
213 (numberp c-basic-offset))
214 c-basic-offset
215 4)
216 "Number of spaces to indent nested statements.
217 Similar to `c-basic-offset'."
218 :group 'js2-mode
219 :type 'integer)
220 (js2-mark-safe-local 'js2-basic-offset 'integerp)
221
222
223 (defcustom js2-bounce-indent-p nil
224 "Non-nil to have indent-line function choose among alternatives.
225 If nil, the indent-line function will indent to a predetermined column
226 based on heuristic guessing. If non-nil, then if the current line is
227 already indented to that predetermined column, indenting will choose
228 another likely column and indent to that spot. Repeated invocation of
229 the indent-line function will cycle among the computed alternatives.
230 See the function `js2-bounce-indent' for details. When it is non-nil,
231 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
232 :type 'boolean
233 :group 'js2-mode)
234
235 (defcustom js2-pretty-multiline-declarations t
236 "Non-nil to line up multiline declarations vertically:
237
238 var a = 10,
239 b = 20,
240 c = 30;
241
242 If the value is not `all', and the first assigned value in
243 declaration is a function/array/object literal spanning several
244 lines, it won't be indented additionally:
245
246 var o = { var bar = 2,
247 foo: 3 vs. o = {
248 }, foo: 3
249 bar = 2; };"
250 :group 'js2-mode
251 :type 'symbol)
252 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
253
254 (defcustom js2-idle-timer-delay 0.2
255 "Delay in secs before re-parsing after user makes changes.
256 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
257 :type 'number
258 :group 'js2-mode)
259 (make-variable-buffer-local 'js2-idle-timer-delay)
260
261 (defcustom js2-dynamic-idle-timer-adjust 0
262 "Positive to adjust `js2-idle-timer-delay' based on file size.
263 The idea is that for short files, parsing is faster so we can be
264 more responsive to user edits without interfering with editing.
265 The buffer length in characters (typically bytes) is divided by
266 this value and used to multiply `js2-idle-timer-delay' for the
267 buffer. For example, a 21k file and 10k adjust yields 21k/10k
268 == 2, so js2-idle-timer-delay is multiplied by 2.
269 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
270 `js2-idle-timer-delay' is not dependent on the file size."
271 :type 'number
272 :group 'js2-mode)
273
274 (defcustom js2-concat-multiline-strings t
275 "Non-nil to automatically turn a newline in mid-string into a
276 string concatenation. When `eol', the '+' will be inserted at the
277 end of the line, otherwise, at the beginning of the next line."
278 :type '(choice (const t) (const eol) (const nil))
279 :group 'js2-mode)
280
281 (defcustom js2-mode-show-parse-errors t
282 "True to highlight parse errors."
283 :type 'boolean
284 :group 'js2-mode)
285
286 (defcustom js2-mode-show-strict-warnings t
287 "Non-nil to emit Ecma strict-mode warnings.
288 Some of the warnings can be individually disabled by other flags,
289 even if this flag is non-nil."
290 :type 'boolean
291 :group 'js2-mode)
292
293 (defcustom js2-strict-trailing-comma-warning t
294 "Non-nil to warn about trailing commas in array literals.
295 Ecma-262-5.1 allows them, but older versions of IE raise an error."
296 :type 'boolean
297 :group 'js2-mode)
298
299 (defcustom js2-strict-missing-semi-warning t
300 "Non-nil to warn about semicolon auto-insertion after statement.
301 Technically this is legal per Ecma-262, but some style guides disallow
302 depending on it."
303 :type 'boolean
304 :group 'js2-mode)
305
306 (defcustom js2-missing-semi-one-line-override nil
307 "Non-nil to permit missing semicolons in one-line functions.
308 In one-liner functions such as `function identity(x) {return x}'
309 people often omit the semicolon for a cleaner look. If you are
310 such a person, you can suppress the missing-semicolon warning
311 by setting this variable to t."
312 :type 'boolean
313 :group 'js2-mode)
314
315 (defcustom js2-strict-inconsistent-return-warning t
316 "Non-nil to warn about mixing returns with value-returns.
317 It's perfectly legal to have a `return' and a `return foo' in the
318 same function, but it's often an indicator of a bug, and it also
319 interferes with type inference (in systems that support it.)"
320 :type 'boolean
321 :group 'js2-mode)
322
323 (defcustom js2-strict-cond-assign-warning t
324 "Non-nil to warn about expressions like if (a = b).
325 This often should have been '==' instead of '='. If the warning
326 is enabled, you can suppress it on a per-expression basis by
327 parenthesizing the expression, e.g. if ((a = b)) ..."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-var-redeclaration-warning t
332 "Non-nil to warn about redeclaring variables in a script or function."
333 :type 'boolean
334 :group 'js2-mode)
335
336 (defcustom js2-strict-var-hides-function-arg-warning t
337 "Non-nil to warn about a var decl hiding a function argument."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-skip-preprocessor-directives nil
342 "Non-nil to treat lines beginning with # as comments.
343 Useful for viewing Mozilla JavaScript source code."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-language-version 200
348 "Configures what JavaScript language version to recognize.
349 Currently versions 150, 160, 170, 180 and 200 are supported,
350 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
351 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
352 yield, and Array comprehensions, and 1.8 adds function closures."
353 :type 'integer
354 :group 'js2-mode)
355
356 (defcustom js2-allow-keywords-as-property-names t
357 "If non-nil, you can use JavaScript keywords as object property names.
358 Examples:
359
360 var foo = {int: 5, while: 6, continue: 7};
361 foo.return = 8;
362
363 Ecma-262 forbids this syntax, but many browsers support it."
364 :type 'boolean
365 :group 'js2-mode)
366
367 (defcustom js2-instanceof-has-side-effects nil
368 "If non-nil, treats the instanceof operator as having side effects.
369 This is useful for xulrunner apps."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-move-point-on-right-click t
374 "Non-nil to move insertion point when you right-click.
375 This makes right-click context menu behavior a bit more intuitive,
376 since menu operations generally apply to the point. The exception
377 is if there is a region selection, in which case the point does -not-
378 move, so cut/copy/paste can work properly.
379
380 Note that IntelliJ moves the point, and Eclipse leaves it alone,
381 so this behavior is customizable."
382 :group 'js2-mode
383 :type 'boolean)
384
385 (defcustom js2-allow-rhino-new-expr-initializer t
386 "Non-nil to support a Rhino's experimental syntactic construct.
387
388 Rhino supports the ability to follow a `new' expression with an object
389 literal, which is used to set additional properties on the new object
390 after calling its constructor. Syntax:
391
392 new <expr> [ ( arglist ) ] [initializer]
393
394 Hence, this expression:
395
396 new Object {a: 1, b: 2}
397
398 results in an Object with properties a=1 and b=2. This syntax is
399 apparently not configurable in Rhino - it's currently always enabled,
400 as of Rhino version 1.7R2."
401 :type 'boolean
402 :group 'js2-mode)
403
404 (defcustom js2-allow-member-expr-as-function-name nil
405 "Non-nil to support experimental Rhino syntax for function names.
406
407 Rhino supports an experimental syntax configured via the Rhino Context
408 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
409
410 function <member-expr> ( [ arg-list ] ) { <body> }
411
412 Where member-expr is a non-parenthesized 'member expression', which
413 is anything at the grammar level of a new-expression or lower, meaning
414 any expression that does not involve infix or unary operators.
415
416 When <member-expr> is not a simple identifier, then it is syntactic
417 sugar for assigning the anonymous function to the <member-expr>. Hence,
418 this code:
419
420 function a.b().c[2] (x, y) { ... }
421
422 is rewritten as:
423
424 a.b().c[2] = function(x, y) {...}
425
426 which doesn't seem particularly useful, but Rhino permits it."
427 :type 'boolean
428 :group 'js2-mode)
429
430 ;; scanner variables
431
432 (defmacro js2-deflocal (name value &optional comment)
433 "Define a buffer-local variable NAME with VALUE and COMMENT."
434 `(progn
435 (defvar ,name ,value ,comment)
436 (make-variable-buffer-local ',name)))
437
438 ;; We record the start and end position of each token.
439 (js2-deflocal js2-token-beg 1)
440 (js2-deflocal js2-token-end -1)
441
442 (defvar js2-EOF_CHAR -1
443 "Represents end of stream. Distinct from js2-EOF token type.")
444
445 ;; I originally used symbols to represent tokens, but Rhino uses
446 ;; ints and then sets various flag bits in them, so ints it is.
447 ;; The upshot is that we need a `js2-' prefix in front of each name.
448 (defvar js2-ERROR -1)
449 (defvar js2-EOF 0)
450 (defvar js2-EOL 1)
451 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
452 (defvar js2-LEAVEWITH 3)
453 (defvar js2-RETURN 4)
454 (defvar js2-GOTO 5)
455 (defvar js2-IFEQ 6)
456 (defvar js2-IFNE 7)
457 (defvar js2-SETNAME 8)
458 (defvar js2-BITOR 9)
459 (defvar js2-BITXOR 10)
460 (defvar js2-BITAND 11)
461 (defvar js2-EQ 12)
462 (defvar js2-NE 13)
463 (defvar js2-LT 14)
464 (defvar js2-LE 15)
465 (defvar js2-GT 16)
466 (defvar js2-GE 17)
467 (defvar js2-LSH 18)
468 (defvar js2-RSH 19)
469 (defvar js2-URSH 20)
470 (defvar js2-ADD 21) ; infix plus
471 (defvar js2-SUB 22) ; infix minus
472 (defvar js2-MUL 23)
473 (defvar js2-DIV 24)
474 (defvar js2-MOD 25)
475 (defvar js2-NOT 26)
476 (defvar js2-BITNOT 27)
477 (defvar js2-POS 28) ; unary plus
478 (defvar js2-NEG 29) ; unary minus
479 (defvar js2-NEW 30)
480 (defvar js2-DELPROP 31)
481 (defvar js2-TYPEOF 32)
482 (defvar js2-GETPROP 33)
483 (defvar js2-GETPROPNOWARN 34)
484 (defvar js2-SETPROP 35)
485 (defvar js2-GETELEM 36)
486 (defvar js2-SETELEM 37)
487 (defvar js2-CALL 38)
488 (defvar js2-NAME 39) ; an identifier
489 (defvar js2-NUMBER 40)
490 (defvar js2-STRING 41)
491 (defvar js2-NULL 42)
492 (defvar js2-THIS 43)
493 (defvar js2-FALSE 44)
494 (defvar js2-TRUE 45)
495 (defvar js2-SHEQ 46) ; shallow equality (===)
496 (defvar js2-SHNE 47) ; shallow inequality (!==)
497 (defvar js2-REGEXP 48)
498 (defvar js2-BINDNAME 49)
499 (defvar js2-THROW 50)
500 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
501 (defvar js2-IN 52)
502 (defvar js2-INSTANCEOF 53)
503 (defvar js2-LOCAL_LOAD 54)
504 (defvar js2-GETVAR 55)
505 (defvar js2-SETVAR 56)
506 (defvar js2-CATCH_SCOPE 57)
507 (defvar js2-ENUM_INIT_KEYS 58)
508 (defvar js2-ENUM_INIT_VALUES 59)
509 (defvar js2-ENUM_INIT_ARRAY 60)
510 (defvar js2-ENUM_NEXT 61)
511 (defvar js2-ENUM_ID 62)
512 (defvar js2-THISFN 63)
513 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
514 (defvar js2-ARRAYLIT 65) ; array literal
515 (defvar js2-OBJECTLIT 66) ; object literal
516 (defvar js2-GET_REF 67) ; *reference
517 (defvar js2-SET_REF 68) ; *reference = something
518 (defvar js2-DEL_REF 69) ; delete reference
519 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
520 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
521 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
522
523 ;; XML support
524 (defvar js2-DEFAULTNAMESPACE 73)
525 (defvar js2-ESCXMLATTR 74)
526 (defvar js2-ESCXMLTEXT 75)
527 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
528 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
529 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
530 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
531
532 (defvar js2-first-bytecode js2-ENTERWITH)
533 (defvar js2-last-bytecode js2-REF_NS_NAME)
534
535 (defvar js2-TRY 80)
536 (defvar js2-SEMI 81) ; semicolon
537 (defvar js2-LB 82) ; left and right brackets
538 (defvar js2-RB 83)
539 (defvar js2-LC 84) ; left and right curly-braces
540 (defvar js2-RC 85)
541 (defvar js2-LP 86) ; left and right parens
542 (defvar js2-RP 87)
543 (defvar js2-COMMA 88) ; comma operator
544
545 (defvar js2-ASSIGN 89) ; simple assignment (=)
546 (defvar js2-ASSIGN_BITOR 90) ; |=
547 (defvar js2-ASSIGN_BITXOR 91) ; ^=
548 (defvar js2-ASSIGN_BITAND 92) ; &=
549 (defvar js2-ASSIGN_LSH 93) ; <<=
550 (defvar js2-ASSIGN_RSH 94) ; >>=
551 (defvar js2-ASSIGN_URSH 95) ; >>>=
552 (defvar js2-ASSIGN_ADD 96) ; +=
553 (defvar js2-ASSIGN_SUB 97) ; -=
554 (defvar js2-ASSIGN_MUL 98) ; *=
555 (defvar js2-ASSIGN_DIV 99) ; /=
556 (defvar js2-ASSIGN_MOD 100) ; %=
557
558 (defvar js2-first-assign js2-ASSIGN)
559 (defvar js2-last-assign js2-ASSIGN_MOD)
560
561 (defvar js2-HOOK 101) ; conditional (?:)
562 (defvar js2-COLON 102)
563 (defvar js2-OR 103) ; logical or (||)
564 (defvar js2-AND 104) ; logical and (&&)
565 (defvar js2-INC 105) ; increment/decrement (++ --)
566 (defvar js2-DEC 106)
567 (defvar js2-DOT 107) ; member operator (.)
568 (defvar js2-FUNCTION 108) ; function keyword
569 (defvar js2-EXPORT 109) ; export keyword
570 (defvar js2-IMPORT 110) ; import keyword
571 (defvar js2-IF 111) ; if keyword
572 (defvar js2-ELSE 112) ; else keyword
573 (defvar js2-SWITCH 113) ; switch keyword
574 (defvar js2-CASE 114) ; case keyword
575 (defvar js2-DEFAULT 115) ; default keyword
576 (defvar js2-WHILE 116) ; while keyword
577 (defvar js2-DO 117) ; do keyword
578 (defvar js2-FOR 118) ; for keyword
579 (defvar js2-BREAK 119) ; break keyword
580 (defvar js2-CONTINUE 120) ; continue keyword
581 (defvar js2-VAR 121) ; var keyword
582 (defvar js2-WITH 122) ; with keyword
583 (defvar js2-CATCH 123) ; catch keyword
584 (defvar js2-FINALLY 124) ; finally keyword
585 (defvar js2-VOID 125) ; void keyword
586 (defvar js2-RESERVED 126) ; reserved keywords
587
588 (defvar js2-EMPTY 127)
589
590 ;; Types used for the parse tree - never returned by scanner.
591
592 (defvar js2-BLOCK 128) ; statement block
593 (defvar js2-LABEL 129) ; label
594 (defvar js2-TARGET 130)
595 (defvar js2-LOOP 131)
596 (defvar js2-EXPR_VOID 132) ; expression statement in functions
597 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
598 (defvar js2-JSR 134)
599 (defvar js2-SCRIPT 135) ; top-level node for entire script
600 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
601 (defvar js2-USE_STACK 137)
602 (defvar js2-SETPROP_OP 138) ; x.y op= something
603 (defvar js2-SETELEM_OP 139) ; x[y] op= something
604 (defvar js2-LOCAL_BLOCK 140)
605 (defvar js2-SET_REF_OP 141) ; *reference op= something
606
607 ;; For XML support:
608 (defvar js2-DOTDOT 142) ; member operator (..)
609 (defvar js2-COLONCOLON 143) ; namespace::name
610 (defvar js2-XML 144) ; XML type
611 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
612 (defvar js2-XMLATTR 146) ; @
613 (defvar js2-XMLEND 147)
614
615 ;; Optimizer-only tokens
616 (defvar js2-TO_OBJECT 148)
617 (defvar js2-TO_DOUBLE 149)
618
619 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
620 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
621 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
622 (defvar js2-CONST 153)
623 (defvar js2-SETCONST 154)
624 (defvar js2-SETCONSTVAR 155)
625 (defvar js2-ARRAYCOMP 156)
626 (defvar js2-LETEXPR 157)
627 (defvar js2-WITHEXPR 158)
628 (defvar js2-DEBUGGER 159)
629
630 (defvar js2-COMMENT 160)
631 (defvar js2-ENUM 161) ; for "enum" reserved word
632 (defvar js2-TRIPLEDOT 162) ; for rest parameter
633
634 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
635
636 (defconst js2-debug-print-trees nil)
637
638 ;; Rhino accepts any string or stream as input. Emacs character
639 ;; processing works best in buffers, so we'll assume the input is a
640 ;; buffer. JavaScript strings can be copied into temp buffers before
641 ;; scanning them.
642
643 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
644 ;; They're the Emacs equivalent of instance variables, more or less.
645
646 (js2-deflocal js2-ts-dirty-line nil
647 "Token stream buffer-local variable.
648 Indicates stuff other than whitespace since start of line.")
649
650 (js2-deflocal js2-ts-regexp-flags nil
651 "Token stream buffer-local variable.")
652
653 (js2-deflocal js2-ts-string ""
654 "Token stream buffer-local variable.
655 Last string scanned.")
656
657 (js2-deflocal js2-ts-number nil
658 "Token stream buffer-local variable.
659 Last literal number scanned.")
660
661 (js2-deflocal js2-ts-hit-eof nil
662 "Token stream buffer-local variable.")
663
664 (js2-deflocal js2-ts-line-start 0
665 "Token stream buffer-local variable.")
666
667 (js2-deflocal js2-ts-lineno 1
668 "Token stream buffer-local variable.")
669
670 (js2-deflocal js2-ts-line-end-char -1
671 "Token stream buffer-local variable.")
672
673 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
674 "Token stream buffer-local variable.
675 Current scan position.")
676
677 (js2-deflocal js2-ts-is-xml-attribute nil
678 "Token stream buffer-local variable.")
679
680 (js2-deflocal js2-ts-xml-is-tag-content nil
681 "Token stream buffer-local variable.")
682
683 (js2-deflocal js2-ts-xml-open-tags-count 0
684 "Token stream buffer-local variable.")
685
686 (js2-deflocal js2-ts-string-buffer nil
687 "Token stream buffer-local variable.
688 List of chars built up while scanning various tokens.")
689
690 (js2-deflocal js2-ts-comment-type nil
691 "Token stream buffer-local variable.")
692
693 ;;; Parser variables
694
695 (js2-deflocal js2-parsed-errors nil
696 "List of errors produced during scanning/parsing.")
697
698 (js2-deflocal js2-parsed-warnings nil
699 "List of warnings produced during scanning/parsing.")
700
701 (js2-deflocal js2-recover-from-parse-errors t
702 "Non-nil to continue parsing after a syntax error.
703
704 In recovery mode, the AST will be built in full, and any error
705 nodes will be flagged with appropriate error information. If
706 this flag is nil, a syntax error will result in an error being
707 signaled.
708
709 The variable is automatically buffer-local, because different
710 modes that use the parser will need different settings.")
711
712 (js2-deflocal js2-parse-hook nil
713 "List of callbacks for receiving parsing progress.")
714
715 (defvar js2-parse-finished-hook nil
716 "List of callbacks to notify when parsing finishes.
717 Not called if parsing was interrupted.")
718
719 (js2-deflocal js2-is-eval-code nil
720 "True if we're evaluating code in a string.
721 If non-nil, the tokenizer will record the token text, and the AST nodes
722 will record their source text. Off by default for IDE modes, since the
723 text is available in the buffer.")
724
725 (defvar js2-parse-ide-mode t
726 "Non-nil if the parser is being used for `js2-mode'.
727 If non-nil, the parser will set text properties for fontification
728 and the syntax table. The value should be nil when using the
729 parser as a frontend to an interpreter or byte compiler.")
730
731 ;;; Parser instance variables (buffer-local vars for js2-parse)
732
733 (defconst js2-clear-ti-mask #xFFFF
734 "Mask to clear token information bits.")
735
736 (defconst js2-ti-after-eol (lsh 1 16)
737 "Flag: first token of the source line.")
738
739 (defconst js2-ti-check-label (lsh 1 17)
740 "Flag: indicates to check for label.")
741
742 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
743
744 (js2-deflocal js2-compiler-generate-debug-info t)
745 (js2-deflocal js2-compiler-use-dynamic-scope nil)
746 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
747 (js2-deflocal js2-compiler-xml-available t)
748 (js2-deflocal js2-compiler-optimization-level 0)
749 (js2-deflocal js2-compiler-generating-source t)
750 (js2-deflocal js2-compiler-strict-mode nil)
751 (js2-deflocal js2-compiler-report-warning-as-error nil)
752 (js2-deflocal js2-compiler-generate-observer-count nil)
753 (js2-deflocal js2-compiler-activation-names nil)
754
755 ;; SKIP: sourceURI
756
757 ;; There's a compileFunction method in Context.java - may need it.
758 (js2-deflocal js2-called-by-compile-function nil
759 "True if `js2-parse' was called by `js2-compile-function'.
760 Will only be used when we finish implementing the interpreter.")
761
762 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
763
764 (js2-deflocal js2-current-flagged-token js2-EOF)
765 (js2-deflocal js2-current-token js2-EOF)
766
767 ;; SKIP: node factory - we're going to just call functions directly,
768 ;; and eventually go to a unified AST format.
769
770 (js2-deflocal js2-nesting-of-function 0)
771
772 (js2-deflocal js2-recorded-identifiers nil
773 "Tracks identifiers found during parsing.")
774
775 (js2-deflocal js2-is-in-destructuring nil
776 "True while parsing destructuring expression.")
777
778 (defcustom js2-global-externs nil
779 "A list of any extern names you'd like to consider always declared.
780 This list is global and is used by all `js2-mode' files.
781 You can create buffer-local externs list using `js2-additional-externs'.
782
783 There is also a buffer-local variable `js2-default-externs',
784 which is initialized by default to include the Ecma-262 externs
785 and the standard browser externs. The three lists are all
786 checked during highlighting."
787 :type 'list
788 :group 'js2-mode)
789
790 (js2-deflocal js2-default-externs nil
791 "Default external declarations.
792
793 These are currently only used for highlighting undeclared variables,
794 which only worries about top-level (unqualified) references.
795 As js2-mode's processing improves, we will flesh out this list.
796
797 The initial value is set to `js2-ecma-262-externs', unless you
798 have set `js2-include-browser-externs', in which case the browser
799 externs are also included.
800
801 See `js2-additional-externs' for more information.")
802
803 (defcustom js2-include-browser-externs t
804 "Non-nil to include browser externs in the master externs list.
805 If you work on JavaScript files that are not intended for browsers,
806 such as Mozilla Rhino server-side JavaScript, set this to nil.
807 You can always include them on a per-file basis by calling
808 `js2-add-browser-externs' from a function on `js2-mode-hook'.
809
810 See `js2-additional-externs' for more information about externs."
811 :type 'boolean
812 :group 'js2-mode)
813
814 (defcustom js2-include-rhino-externs t
815 "Non-nil to include Mozilla Rhino externs in the master externs list.
816 See `js2-additional-externs' for more information about externs."
817 :type 'boolean
818 :group 'js2-mode)
819
820 (defcustom js2-include-gears-externs t
821 "Non-nil to include Google Gears externs in the master externs list.
822 See `js2-additional-externs' for more information about externs."
823 :type 'boolean
824 :group 'js2-mode)
825
826 (js2-deflocal js2-additional-externs nil
827 "A buffer-local list of additional external declarations.
828 It is used to decide whether variables are considered undeclared
829 for purposes of highlighting.
830
831 Each entry is a Lisp string. The string should be the fully qualified
832 name of an external entity. All externs should be added to this list,
833 so that as js2-mode's processing improves it can take advantage of them.
834
835 You may want to declare your externs in three ways.
836 First, you can add externs that are valid for all your JavaScript files.
837 You should probably do this by adding them to `js2-global-externs', which
838 is a global list used for all js2-mode files.
839
840 Next, you can add a function to `js2-mode-hook' that adds additional
841 externs appropriate for the specific file, perhaps based on its path.
842 These should go in `js2-additional-externs', which is buffer-local.
843
844 Finally, you can add a function to `js2-post-parse-callbacks',
845 which is called after parsing completes, and `js2-mode-ast' is bound to
846 the root of the parse tree. At this stage you can set up an AST
847 node visitor using `js2-visit-ast' and examine the parse tree
848 for specific import patterns that may imply the existence of
849 other externs, possibly tied to your build system. These should also
850 be added to `js2-additional-externs'.
851
852 Your post-parse callback may of course also use the simpler and
853 faster (but perhaps less robust) approach of simply scanning the
854 buffer text for your imports, using regular expressions.")
855
856 ;; SKIP: decompiler
857 ;; SKIP: encoded-source
858
859 ;;; The following variables are per-function and should be saved/restored
860 ;;; during function parsing...
861
862 (js2-deflocal js2-current-script-or-fn nil)
863 (js2-deflocal js2-current-scope nil)
864 (js2-deflocal js2-nesting-of-with 0)
865 (js2-deflocal js2-label-set nil
866 "An alist mapping label names to nodes.")
867
868 (js2-deflocal js2-loop-set nil)
869 (js2-deflocal js2-loop-and-switch-set nil)
870 (js2-deflocal js2-has-return-value nil)
871 (js2-deflocal js2-end-flags 0)
872
873 ;;; ...end of per function variables
874
875 ;; Without 2-token lookahead, labels are a problem.
876 ;; These vars store the token info of the last matched name,
877 ;; iff it wasn't the last matched token. Only valid in some contexts.
878 (defvar js2-prev-name-token-start nil)
879 (defvar js2-prev-name-token-string nil)
880
881 (defsubst js2-save-name-token-data (pos name)
882 (setq js2-prev-name-token-start pos
883 js2-prev-name-token-string name))
884
885 ;; These flags enumerate the possible ways a statement/function can
886 ;; terminate. These flags are used by endCheck() and by the Parser to
887 ;; detect inconsistent return usage.
888 ;;
889 ;; END_UNREACHED is reserved for code paths that are assumed to always be
890 ;; able to execute (example: throw, continue)
891 ;;
892 ;; END_DROPS_OFF indicates if the statement can transfer control to the
893 ;; next one. Statement such as return dont. A compound statement may have
894 ;; some branch that drops off control to the next statement.
895 ;;
896 ;; END_RETURNS indicates that the statement can return (without arguments)
897 ;; END_RETURNS_VALUE indicates that the statement can return a value.
898 ;;
899 ;; A compound statement such as
900 ;; if (condition) {
901 ;; return value;
902 ;; }
903 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
904
905 (defconst js2-end-unreached #x0)
906 (defconst js2-end-drops-off #x1)
907 (defconst js2-end-returns #x2)
908 (defconst js2-end-returns-value #x4)
909 (defconst js2-end-yields #x8)
910
911 ;; Rhino awkwardly passes a statementLabel parameter to the
912 ;; statementHelper() function, the main statement parser, which
913 ;; is then used by quite a few of the sub-parsers. We just make
914 ;; it a buffer-local variable and make sure it's cleaned up properly.
915 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
916
917 ;; Similarly, Rhino passes an inForInit boolean through about half
918 ;; the expression parsers. We use a dynamically-scoped variable,
919 ;; which makes it easier to funcall the parsers individually without
920 ;; worrying about whether they take the parameter or not.
921 (js2-deflocal js2-in-for-init nil)
922 (js2-deflocal js2-temp-name-counter 0)
923 (js2-deflocal js2-parse-stmt-count 0)
924
925 (defsubst js2-get-next-temp-name ()
926 (format "$%d" (incf js2-temp-name-counter)))
927
928 (defvar js2-parse-interruptable-p t
929 "Set this to nil to force parse to continue until finished.
930 This will mostly be useful for interpreters.")
931
932 (defvar js2-statements-per-pause 50
933 "Pause after this many statements to check for user input.
934 If user input is pending, stop the parse and discard the tree.
935 This makes for a smoother user experience for large files.
936 You may have to wait a second or two before the highlighting
937 and error-reporting appear, but you can always type ahead if
938 you wish. This appears to be more or less how Eclipse, IntelliJ
939 and other editors work.")
940
941 (js2-deflocal js2-record-comments t
942 "Instructs the scanner to record comments in `js2-scanned-comments'.")
943
944 (js2-deflocal js2-scanned-comments nil
945 "List of all comments from the current parse.")
946
947 (defcustom js2-mode-indent-inhibit-undo nil
948 "Non-nil to disable collection of Undo information when indenting lines.
949 Some users have requested this behavior. It's nil by default because
950 other Emacs modes don't work this way."
951 :type 'boolean
952 :group 'js2-mode)
953
954 (defcustom js2-mode-indent-ignore-first-tab nil
955 "If non-nil, ignore first TAB keypress if we look indented properly.
956 It's fairly common for users to navigate to an already-indented line
957 and press TAB for reassurance that it's been indented. For this class
958 of users, we want the first TAB press on a line to be ignored if the
959 line is already indented to one of the precomputed alternatives.
960
961 This behavior is only partly implemented. If you TAB-indent a line,
962 navigate to another line, and then navigate back, it fails to clear
963 the last-indented variable, so it thinks you've already hit TAB once,
964 and performs the indent. A full solution would involve getting on the
965 point-motion hooks for the entire buffer. If we come across another
966 use cases that requires watching point motion, I'll consider doing it.
967
968 If you set this variable to nil, then the TAB key will always change
969 the indentation of the current line, if more than one alternative
970 indentation spot exists."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defvar js2-indent-hook nil
975 "A hook for user-defined indentation rules.
976
977 Functions on this hook should expect two arguments: (LIST INDEX)
978 The LIST argument is the list of computed indentation points for
979 the current line. INDEX is the list index of the indentation point
980 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
981 indent function is not going to change the current line indentation.
982
983 If a hook function on this list returns a non-nil value, then
984 `js2-bounce-indent' assumes the hook function has performed its own
985 indentation, and will do nothing. If all hook functions on the list
986 return nil, then `js2-bounce-indent' will use its computed indentation
987 and reindent the line.
988
989 When hook functions on this hook list are called, the variable
990 `js2-mode-ast' may or may not be set, depending on whether the
991 parse tree is available. If the variable is nil, you can pass a
992 callback to `js2-mode-wait-for-parse', and your callback will be
993 called after the new parse tree is built. This can take some time
994 in large files.")
995
996 (defface js2-warning
997 `((((class color) (background light))
998 (:underline "orange"))
999 (((class color) (background dark))
1000 (:underline "orange"))
1001 (t (:underline t)))
1002 "Face for JavaScript warnings."
1003 :group 'js2-mode)
1004
1005 (defface js2-error
1006 `((((class color) (background light))
1007 (:foreground "red"))
1008 (((class color) (background dark))
1009 (:foreground "red"))
1010 (t (:foreground "red")))
1011 "Face for JavaScript errors."
1012 :group 'js2-mode)
1013
1014 (defface js2-jsdoc-tag
1015 '((t :foreground "SlateGray"))
1016 "Face used to highlight @whatever tags in jsdoc comments."
1017 :group 'js2-mode)
1018
1019 (defface js2-jsdoc-type
1020 '((t :foreground "SteelBlue"))
1021 "Face used to highlight {FooBar} types in jsdoc comments."
1022 :group 'js2-mode)
1023
1024 (defface js2-jsdoc-value
1025 '((t :foreground "PeachPuff3"))
1026 "Face used to highlight tag values in jsdoc comments."
1027 :group 'js2-mode)
1028
1029 (defface js2-function-param
1030 '((t :foreground "SeaGreen"))
1031 "Face used to highlight function parameters in javascript."
1032 :group 'js2-mode)
1033
1034 (defface js2-instance-member
1035 '((t :foreground "DarkOrchid"))
1036 "Face used to highlight instance variables in javascript.
1037 Not currently used."
1038 :group 'js2-mode)
1039
1040 (defface js2-private-member
1041 '((t :foreground "PeachPuff3"))
1042 "Face used to highlight calls to private methods in javascript.
1043 Not currently used."
1044 :group 'js2-mode)
1045
1046 (defface js2-private-function-call
1047 '((t :foreground "goldenrod"))
1048 "Face used to highlight calls to private functions in javascript.
1049 Not currently used."
1050 :group 'js2-mode)
1051
1052 (defface js2-jsdoc-html-tag-name
1053 '((((class color) (min-colors 88) (background light))
1054 (:foreground "rosybrown"))
1055 (((class color) (min-colors 8) (background dark))
1056 (:foreground "yellow"))
1057 (((class color) (min-colors 8) (background light))
1058 (:foreground "magenta")))
1059 "Face used to highlight jsdoc html tag names"
1060 :group 'js2-mode)
1061
1062 (defface js2-jsdoc-html-tag-delimiter
1063 '((((class color) (min-colors 88) (background light))
1064 (:foreground "dark khaki"))
1065 (((class color) (min-colors 8) (background dark))
1066 (:foreground "green"))
1067 (((class color) (min-colors 8) (background light))
1068 (:foreground "green")))
1069 "Face used to highlight brackets in jsdoc html tags."
1070 :group 'js2-mode)
1071
1072 (defface js2-external-variable
1073 '((t :foreground "orange"))
1074 "Face used to highlight undeclared variable identifiers.")
1075
1076 (defcustom js2-post-parse-callbacks nil
1077 "A list of callback functions invoked after parsing finishes.
1078 Currently, the main use for this function is to add synthetic
1079 declarations to `js2-recorded-identifiers', which see."
1080 :type 'list
1081 :group 'js2-mode)
1082
1083 (defcustom js2-highlight-external-variables t
1084 "Non-nil to highlight undeclared variable identifiers.
1085 An undeclared variable is any variable not declared with var or let
1086 in the current scope or any lexically enclosing scope. If you use
1087 such a variable, then you are either expecting it to originate from
1088 another file, or you've got a potential bug."
1089 :type 'boolean
1090 :group 'js2-mode)
1091
1092 (defcustom js2-auto-insert-catch-block t
1093 "Non-nil to insert matching catch block on open-curly after `try'."
1094 :type 'boolean
1095 :group 'js2-mode)
1096
1097 (defvar js2-mode-map
1098 (let ((map (make-sparse-keymap))
1099 keys)
1100 (define-key map [mouse-1] #'js2-mode-show-node)
1101 (define-key map (kbd "M-j") #'js2-line-break)
1102 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1103 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1104 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1105 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1106 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1107 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1108 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1109 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1110 (when js2-bounce-indent-p
1111 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1112
1113 (define-key map [menu-bar javascript]
1114 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1115
1116 (define-key map [menu-bar javascript customize-js2-mode]
1117 '(menu-item "Customize js2-mode" js2-mode-customize
1118 :help "Customize the behavior of this mode"))
1119
1120 (define-key map [menu-bar javascript js2-force-refresh]
1121 '(menu-item "Force buffer refresh" js2-mode-reset
1122 :help "Re-parse the buffer from scratch"))
1123
1124 (define-key map [menu-bar javascript separator-2]
1125 '("--"))
1126
1127 (define-key map [menu-bar javascript next-error]
1128 '(menu-item "Next warning or error" next-error
1129 :enabled (and js2-mode-ast
1130 (or (js2-ast-root-errors js2-mode-ast)
1131 (js2-ast-root-warnings js2-mode-ast)))
1132 :help "Move to next warning or error"))
1133
1134 (define-key map [menu-bar javascript display-errors]
1135 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1136 :visible (not js2-mode-show-parse-errors)
1137 :help "Turn on display of warnings and errors"))
1138
1139 (define-key map [menu-bar javascript hide-errors]
1140 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1141 :visible js2-mode-show-parse-errors
1142 :help "Turn off display of warnings and errors"))
1143
1144 (define-key map [menu-bar javascript separator-1]
1145 '("--"))
1146
1147 (define-key map [menu-bar javascript js2-toggle-function]
1148 '(menu-item "Show/collapse element" js2-mode-toggle-element
1149 :help "Hide or show function body or comment"))
1150
1151 (define-key map [menu-bar javascript show-comments]
1152 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1153 :visible js2-mode-comments-hidden
1154 :help "Expand all hidden block comments"))
1155
1156 (define-key map [menu-bar javascript hide-comments]
1157 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1158 :visible (not js2-mode-comments-hidden)
1159 :help "Show block comments as /*...*/"))
1160
1161 (define-key map [menu-bar javascript show-all-functions]
1162 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1163 :visible js2-mode-functions-hidden
1164 :help "Expand all hidden function bodies"))
1165
1166 (define-key map [menu-bar javascript hide-all-functions]
1167 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1168 :visible (not js2-mode-functions-hidden)
1169 :help "Show {...} for all top-level function bodies"))
1170
1171 map)
1172 "Keymap used in `js2-mode' buffers.")
1173
1174 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1175
1176 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1177 "Matches a //-comment line. Must be first non-whitespace on line.
1178 First match-group is the leading whitespace.")
1179
1180 (defvar js2-mode-hook nil)
1181
1182 (js2-deflocal js2-mode-ast nil "Private variable.")
1183 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1184 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1185 (js2-deflocal js2-mode-parsing nil "Private variable.")
1186 (js2-deflocal js2-mode-node-overlay nil)
1187
1188 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1189 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1190
1191 (js2-deflocal js2-mode-fontifications nil "Private variable")
1192 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1193 (js2-deflocal js2-imenu-recorder nil "Private variable")
1194 (js2-deflocal js2-imenu-function-map nil "Private variable")
1195
1196 (defvar js2-paragraph-start
1197 "\\(@[a-zA-Z]+\\>\\|$\\)")
1198
1199 ;; Note that we also set a 'c-in-sws text property in html comments,
1200 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1201 (defvar js2-syntactic-ws-start
1202 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1203
1204 (defvar js2-syntactic-ws-end
1205 "\\s \\|[\n\r/]\\|\\s!")
1206
1207 (defvar js2-syntactic-eol
1208 (concat "\\s *\\(/\\*[^*\n\r]*"
1209 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1210 "\\*+/\\s *\\)*"
1211 "\\(//\\|/\\*[^*\n\r]*"
1212 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1213 "\\|\\\\$\\|$\\)")
1214 "Copied from `java-mode'. Needed for some cc-engine functions.")
1215
1216 (defvar js2-comment-prefix-regexp
1217 "//+\\|\\**")
1218
1219 (defvar js2-comment-start-skip
1220 "\\(//+\\|/\\*+\\)\\s *")
1221
1222 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1223 "Non-nil to emit status messages during parsing.")
1224
1225 (defvar js2-mode-functions-hidden nil "Private variable.")
1226 (defvar js2-mode-comments-hidden nil "Private variable.")
1227
1228 (defvar js2-mode-syntax-table
1229 (let ((table (make-syntax-table)))
1230 (c-populate-syntax-table table)
1231 table)
1232 "Syntax table used in `js2-mode' buffers.")
1233
1234 (defvar js2-mode-abbrev-table nil
1235 "Abbrev table in use in `js2-mode' buffers.")
1236 (define-abbrev-table 'js2-mode-abbrev-table ())
1237
1238 (defvar js2-mode-pending-parse-callbacks nil
1239 "List of functions waiting to be notified that parse is finished.")
1240
1241 (defvar js2-mode-last-indented-line -1)
1242
1243 ;;; Localizable error and warning messages
1244
1245 ;; Messages are copied from Rhino's Messages.properties.
1246 ;; Many of the Java-specific messages have been elided.
1247 ;; Add any js2-specific ones at the end, so we can keep
1248 ;; this file synced with changes to Rhino's.
1249
1250 (defvar js2-message-table
1251 (make-hash-table :test 'equal :size 250)
1252 "Contains localized messages for `js2-mode'.")
1253
1254 ;; TODO(stevey): construct this table at compile-time.
1255 (defmacro js2-msg (key &rest strings)
1256 `(puthash ,key (concat ,@strings)
1257 js2-message-table))
1258
1259 (defun js2-get-msg (msg-key)
1260 "Look up a localized message.
1261 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1262 the correct number of ARGS must be provided."
1263 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1264 (args (if (listp msg-key) (cdr msg-key)))
1265 (msg (gethash key js2-message-table)))
1266 (if msg
1267 (apply #'format msg args)
1268 key))) ; default to showing the key
1269
1270 (js2-msg "msg.dup.parms"
1271 "Duplicate parameter name '%s'.")
1272
1273 (js2-msg "msg.too.big.jump"
1274 "Program too complex: jump offset too big.")
1275
1276 (js2-msg "msg.too.big.index"
1277 "Program too complex: internal index exceeds 64K limit.")
1278
1279 (js2-msg "msg.while.compiling.fn"
1280 "Encountered code generation error while compiling function '%s': %s")
1281
1282 (js2-msg "msg.while.compiling.script"
1283 "Encountered code generation error while compiling script: %s")
1284
1285 ;; Context
1286 (js2-msg "msg.ctor.not.found"
1287 "Constructor for '%s' not found.")
1288
1289 (js2-msg "msg.not.ctor"
1290 "'%s' is not a constructor.")
1291
1292 ;; FunctionObject
1293 (js2-msg "msg.varargs.ctor"
1294 "Method or constructor '%s' must be static "
1295 "with the signature (Context cx, Object[] args, "
1296 "Function ctorObj, boolean inNewExpr) "
1297 "to define a variable arguments constructor.")
1298
1299 (js2-msg "msg.varargs.fun"
1300 "Method '%s' must be static with the signature "
1301 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1302 "to define a variable arguments function.")
1303
1304 (js2-msg "msg.incompat.call"
1305 "Method '%s' called on incompatible object.")
1306
1307 (js2-msg "msg.bad.parms"
1308 "Unsupported parameter type '%s' in method '%s'.")
1309
1310 (js2-msg "msg.bad.method.return"
1311 "Unsupported return type '%s' in method '%s'.")
1312
1313 (js2-msg "msg.bad.ctor.return"
1314 "Construction of objects of type '%s' is not supported.")
1315
1316 (js2-msg "msg.no.overload"
1317 "Method '%s' occurs multiple times in class '%s'.")
1318
1319 (js2-msg "msg.method.not.found"
1320 "Method '%s' not found in '%s'.")
1321
1322 ;; IRFactory
1323
1324 (js2-msg "msg.bad.for.in.lhs"
1325 "Invalid left-hand side of for..in loop.")
1326
1327 (js2-msg "msg.mult.index"
1328 "Only one variable allowed in for..in loop.")
1329
1330 (js2-msg "msg.bad.for.in.destruct"
1331 "Left hand side of for..in loop must be an array of "
1332 "length 2 to accept key/value pair.")
1333
1334 (js2-msg "msg.cant.convert"
1335 "Can't convert to type '%s'.")
1336
1337 (js2-msg "msg.bad.assign.left"
1338 "Invalid assignment left-hand side.")
1339
1340 (js2-msg "msg.bad.decr"
1341 "Invalid decerement operand.")
1342
1343 (js2-msg "msg.bad.incr"
1344 "Invalid increment operand.")
1345
1346 (js2-msg "msg.bad.yield"
1347 "yield must be in a function.")
1348
1349 (js2-msg "msg.yield.parenthesized"
1350 "yield expression must be parenthesized.")
1351
1352 ;; NativeGlobal
1353 (js2-msg "msg.cant.call.indirect"
1354 "Function '%s' must be called directly, and not by way of a "
1355 "function of another name.")
1356
1357 (js2-msg "msg.eval.nonstring"
1358 "Calling eval() with anything other than a primitive "
1359 "string value will simply return the value. "
1360 "Is this what you intended?")
1361
1362 (js2-msg "msg.eval.nonstring.strict"
1363 "Calling eval() with anything other than a primitive "
1364 "string value is not allowed in strict mode.")
1365
1366 (js2-msg "msg.bad.destruct.op"
1367 "Invalid destructuring assignment operator")
1368
1369 ;; NativeCall
1370 (js2-msg "msg.only.from.new"
1371 "'%s' may only be invoked from a `new' expression.")
1372
1373 (js2-msg "msg.deprec.ctor"
1374 "The '%s' constructor is deprecated.")
1375
1376 ;; NativeFunction
1377 (js2-msg "msg.no.function.ref.found"
1378 "no source found to decompile function reference %s")
1379
1380 (js2-msg "msg.arg.isnt.array"
1381 "second argument to Function.prototype.apply must be an array")
1382
1383 ;; NativeGlobal
1384 (js2-msg "msg.bad.esc.mask"
1385 "invalid string escape mask")
1386
1387 ;; NativeRegExp
1388 (js2-msg "msg.bad.quant"
1389 "Invalid quantifier %s")
1390
1391 (js2-msg "msg.overlarge.backref"
1392 "Overly large back reference %s")
1393
1394 (js2-msg "msg.overlarge.min"
1395 "Overly large minimum %s")
1396
1397 (js2-msg "msg.overlarge.max"
1398 "Overly large maximum %s")
1399
1400 (js2-msg "msg.zero.quant"
1401 "Zero quantifier %s")
1402
1403 (js2-msg "msg.max.lt.min"
1404 "Maximum %s less than minimum")
1405
1406 (js2-msg "msg.unterm.quant"
1407 "Unterminated quantifier %s")
1408
1409 (js2-msg "msg.unterm.paren"
1410 "Unterminated parenthetical %s")
1411
1412 (js2-msg "msg.unterm.class"
1413 "Unterminated character class %s")
1414
1415 (js2-msg "msg.bad.range"
1416 "Invalid range in character class.")
1417
1418 (js2-msg "msg.trail.backslash"
1419 "Trailing \\ in regular expression.")
1420
1421 (js2-msg "msg.re.unmatched.right.paren"
1422 "unmatched ) in regular expression.")
1423
1424 (js2-msg "msg.no.regexp"
1425 "Regular expressions are not available.")
1426
1427 (js2-msg "msg.bad.backref"
1428 "back-reference exceeds number of capturing parentheses.")
1429
1430 (js2-msg "msg.bad.regexp.compile"
1431 "Only one argument may be specified if the first "
1432 "argument to RegExp.prototype.compile is a RegExp object.")
1433
1434 ;; Parser
1435 (js2-msg "msg.got.syntax.errors"
1436 "Compilation produced %s syntax errors.")
1437
1438 (js2-msg "msg.var.redecl"
1439 "TypeError: redeclaration of var %s.")
1440
1441 (js2-msg "msg.const.redecl"
1442 "TypeError: redeclaration of const %s.")
1443
1444 (js2-msg "msg.let.redecl"
1445 "TypeError: redeclaration of variable %s.")
1446
1447 (js2-msg "msg.parm.redecl"
1448 "TypeError: redeclaration of formal parameter %s.")
1449
1450 (js2-msg "msg.fn.redecl"
1451 "TypeError: redeclaration of function %s.")
1452
1453 (js2-msg "msg.let.decl.not.in.block"
1454 "SyntaxError: let declaration not directly within block")
1455
1456 ;; NodeTransformer
1457 (js2-msg "msg.dup.label"
1458 "duplicated label")
1459
1460 (js2-msg "msg.undef.label"
1461 "undefined label")
1462
1463 (js2-msg "msg.bad.break"
1464 "unlabelled break must be inside loop or switch")
1465
1466 (js2-msg "msg.continue.outside"
1467 "continue must be inside loop")
1468
1469 (js2-msg "msg.continue.nonloop"
1470 "continue can only use labels of iteration statements")
1471
1472 (js2-msg "msg.bad.throw.eol"
1473 "Line terminator is not allowed between the throw "
1474 "keyword and throw expression.")
1475
1476 (js2-msg "msg.no.paren.parms"
1477 "missing ( before function parameters.")
1478
1479 (js2-msg "msg.no.parm"
1480 "missing formal parameter")
1481
1482 (js2-msg "msg.no.paren.after.parms"
1483 "missing ) after formal parameters")
1484
1485 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1486 "parameter without default follows parameter with default")
1487
1488 (js2-msg "msg.param.after.rest" ; added by js2-mode
1489 "parameter after rest parameter")
1490
1491 (js2-msg "msg.no.brace.body"
1492 "missing '{' before function body")
1493
1494 (js2-msg "msg.no.brace.after.body"
1495 "missing } after function body")
1496
1497 (js2-msg "msg.no.paren.cond"
1498 "missing ( before condition")
1499
1500 (js2-msg "msg.no.paren.after.cond"
1501 "missing ) after condition")
1502
1503 (js2-msg "msg.no.semi.stmt"
1504 "missing ; before statement")
1505
1506 (js2-msg "msg.missing.semi"
1507 "missing ; after statement")
1508
1509 (js2-msg "msg.no.name.after.dot"
1510 "missing name after . operator")
1511
1512 (js2-msg "msg.no.name.after.coloncolon"
1513 "missing name after :: operator")
1514
1515 (js2-msg "msg.no.name.after.dotdot"
1516 "missing name after .. operator")
1517
1518 (js2-msg "msg.no.name.after.xmlAttr"
1519 "missing name after .@")
1520
1521 (js2-msg "msg.no.bracket.index"
1522 "missing ] in index expression")
1523
1524 (js2-msg "msg.no.paren.switch"
1525 "missing ( before switch expression")
1526
1527 (js2-msg "msg.no.paren.after.switch"
1528 "missing ) after switch expression")
1529
1530 (js2-msg "msg.no.brace.switch"
1531 "missing '{' before switch body")
1532
1533 (js2-msg "msg.bad.switch"
1534 "invalid switch statement")
1535
1536 (js2-msg "msg.no.colon.case"
1537 "missing : after case expression")
1538
1539 (js2-msg "msg.double.switch.default"
1540 "double default label in the switch statement")
1541
1542 (js2-msg "msg.no.while.do"
1543 "missing while after do-loop body")
1544
1545 (js2-msg "msg.no.paren.for"
1546 "missing ( after for")
1547
1548 (js2-msg "msg.no.semi.for"
1549 "missing ; after for-loop initializer")
1550
1551 (js2-msg "msg.no.semi.for.cond"
1552 "missing ; after for-loop condition")
1553
1554 (js2-msg "msg.in.after.for.name"
1555 "missing in or of after for")
1556
1557 (js2-msg "msg.no.paren.for.ctrl"
1558 "missing ) after for-loop control")
1559
1560 (js2-msg "msg.no.paren.with"
1561 "missing ( before with-statement object")
1562
1563 (js2-msg "msg.no.paren.after.with"
1564 "missing ) after with-statement object")
1565
1566 (js2-msg "msg.no.paren.after.let"
1567 "missing ( after let")
1568
1569 (js2-msg "msg.no.paren.let"
1570 "missing ) after variable list")
1571
1572 (js2-msg "msg.no.curly.let"
1573 "missing } after let statement")
1574
1575 (js2-msg "msg.bad.return"
1576 "invalid return")
1577
1578 (js2-msg "msg.no.brace.block"
1579 "missing } in compound statement")
1580
1581 (js2-msg "msg.bad.label"
1582 "invalid label")
1583
1584 (js2-msg "msg.bad.var"
1585 "missing variable name")
1586
1587 (js2-msg "msg.bad.var.init"
1588 "invalid variable initialization")
1589
1590 (js2-msg "msg.no.colon.cond"
1591 "missing : in conditional expression")
1592
1593 (js2-msg "msg.no.paren.arg"
1594 "missing ) after argument list")
1595
1596 (js2-msg "msg.no.bracket.arg"
1597 "missing ] after element list")
1598
1599 (js2-msg "msg.bad.prop"
1600 "invalid property id")
1601
1602 (js2-msg "msg.no.colon.prop"
1603 "missing : after property id")
1604
1605 (js2-msg "msg.no.brace.prop"
1606 "missing } after property list")
1607
1608 (js2-msg "msg.no.paren"
1609 "missing ) in parenthetical")
1610
1611 (js2-msg "msg.reserved.id"
1612 "identifier is a reserved word")
1613
1614 (js2-msg "msg.no.paren.catch"
1615 "missing ( before catch-block condition")
1616
1617 (js2-msg "msg.bad.catchcond"
1618 "invalid catch block condition")
1619
1620 (js2-msg "msg.catch.unreachable"
1621 "any catch clauses following an unqualified catch are unreachable")
1622
1623 (js2-msg "msg.no.brace.try"
1624 "missing '{' before try block")
1625
1626 (js2-msg "msg.no.brace.catchblock"
1627 "missing '{' before catch-block body")
1628
1629 (js2-msg "msg.try.no.catchfinally"
1630 "'try' without 'catch' or 'finally'")
1631
1632 (js2-msg "msg.no.return.value"
1633 "function %s does not always return a value")
1634
1635 (js2-msg "msg.anon.no.return.value"
1636 "anonymous function does not always return a value")
1637
1638 (js2-msg "msg.return.inconsistent"
1639 "return statement is inconsistent with previous usage")
1640
1641 (js2-msg "msg.generator.returns"
1642 "TypeError: generator function '%s' returns a value")
1643
1644 (js2-msg "msg.anon.generator.returns"
1645 "TypeError: anonymous generator function returns a value")
1646
1647 (js2-msg "msg.syntax"
1648 "syntax error")
1649
1650 (js2-msg "msg.unexpected.eof"
1651 "Unexpected end of file")
1652
1653 (js2-msg "msg.XML.bad.form"
1654 "illegally formed XML syntax")
1655
1656 (js2-msg "msg.XML.not.available"
1657 "XML runtime not available")
1658
1659 (js2-msg "msg.too.deep.parser.recursion"
1660 "Too deep recursion while parsing")
1661
1662 (js2-msg "msg.no.side.effects"
1663 "Code has no side effects")
1664
1665 (js2-msg "msg.extra.trailing.comma"
1666 "Trailing comma is not supported in some browsers")
1667
1668 (js2-msg "msg.array.trailing.comma"
1669 "Trailing comma yields different behavior across browsers")
1670
1671 (js2-msg "msg.equal.as.assign"
1672 (concat "Test for equality (==) mistyped as assignment (=)?"
1673 " (parenthesize to suppress warning)"))
1674
1675 (js2-msg "msg.var.hides.arg"
1676 "Variable %s hides argument")
1677
1678 (js2-msg "msg.destruct.assign.no.init"
1679 "Missing = in destructuring declaration")
1680
1681 ;; ScriptRuntime
1682 (js2-msg "msg.no.properties"
1683 "%s has no properties.")
1684
1685 (js2-msg "msg.invalid.iterator"
1686 "Invalid iterator value")
1687
1688 (js2-msg "msg.iterator.primitive"
1689 "__iterator__ returned a primitive value")
1690
1691 (js2-msg "msg.assn.create.strict"
1692 "Assignment to undeclared variable %s")
1693
1694 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1695 "Undeclared variable or function '%s'")
1696
1697 (js2-msg "msg.ref.undefined.prop"
1698 "Reference to undefined property '%s'")
1699
1700 (js2-msg "msg.prop.not.found"
1701 "Property %s not found.")
1702
1703 (js2-msg "msg.invalid.type"
1704 "Invalid JavaScript value of type %s")
1705
1706 (js2-msg "msg.primitive.expected"
1707 "Primitive type expected (had %s instead)")
1708
1709 (js2-msg "msg.namespace.expected"
1710 "Namespace object expected to left of :: (found %s instead)")
1711
1712 (js2-msg "msg.null.to.object"
1713 "Cannot convert null to an object.")
1714
1715 (js2-msg "msg.undef.to.object"
1716 "Cannot convert undefined to an object.")
1717
1718 (js2-msg "msg.cyclic.value"
1719 "Cyclic %s value not allowed.")
1720
1721 (js2-msg "msg.is.not.defined"
1722 "'%s' is not defined.")
1723
1724 (js2-msg "msg.undef.prop.read"
1725 "Cannot read property '%s' from %s")
1726
1727 (js2-msg "msg.undef.prop.write"
1728 "Cannot set property '%s' of %s to '%s'")
1729
1730 (js2-msg "msg.undef.prop.delete"
1731 "Cannot delete property '%s' of %s")
1732
1733 (js2-msg "msg.undef.method.call"
1734 "Cannot call method '%s' of %s")
1735
1736 (js2-msg "msg.undef.with"
1737 "Cannot apply 'with' to %s")
1738
1739 (js2-msg "msg.isnt.function"
1740 "%s is not a function, it is %s.")
1741
1742 (js2-msg "msg.isnt.function.in"
1743 "Cannot call property %s in object %s. "
1744 "It is not a function, it is '%s'.")
1745
1746 (js2-msg "msg.function.not.found"
1747 "Cannot find function %s.")
1748
1749 (js2-msg "msg.function.not.found.in"
1750 "Cannot find function %s in object %s.")
1751
1752 (js2-msg "msg.isnt.xml.object"
1753 "%s is not an xml object.")
1754
1755 (js2-msg "msg.no.ref.to.get"
1756 "%s is not a reference to read reference value.")
1757
1758 (js2-msg "msg.no.ref.to.set"
1759 "%s is not a reference to set reference value to %s.")
1760
1761 (js2-msg "msg.no.ref.from.function"
1762 "Function %s can not be used as the left-hand "
1763 "side of assignment or as an operand of ++ or -- operator.")
1764
1765 (js2-msg "msg.bad.default.value"
1766 "Object's getDefaultValue() method returned an object.")
1767
1768 (js2-msg "msg.instanceof.not.object"
1769 "Can't use instanceof on a non-object.")
1770
1771 (js2-msg "msg.instanceof.bad.prototype"
1772 "'prototype' property of %s is not an object.")
1773
1774 (js2-msg "msg.bad.radix"
1775 "illegal radix %s.")
1776
1777 ;; ScriptableObject
1778 (js2-msg "msg.default.value"
1779 "Cannot find default value for object.")
1780
1781 (js2-msg "msg.zero.arg.ctor"
1782 "Cannot load class '%s' which has no zero-parameter constructor.")
1783
1784 (js2-msg "msg.ctor.multiple.parms"
1785 "Can't define constructor or class %s since more than "
1786 "one constructor has multiple parameters.")
1787
1788 (js2-msg "msg.extend.scriptable"
1789 "%s must extend ScriptableObject in order to define property %s.")
1790
1791 (js2-msg "msg.bad.getter.parms"
1792 "In order to define a property, getter %s must have zero "
1793 "parameters or a single ScriptableObject parameter.")
1794
1795 (js2-msg "msg.obj.getter.parms"
1796 "Expected static or delegated getter %s to take "
1797 "a ScriptableObject parameter.")
1798
1799 (js2-msg "msg.getter.static"
1800 "Getter and setter must both be static or neither be static.")
1801
1802 (js2-msg "msg.setter.return"
1803 "Setter must have void return type: %s")
1804
1805 (js2-msg "msg.setter2.parms"
1806 "Two-parameter setter must take a ScriptableObject as "
1807 "its first parameter.")
1808
1809 (js2-msg "msg.setter1.parms"
1810 "Expected single parameter setter for %s")
1811
1812 (js2-msg "msg.setter2.expected"
1813 "Expected static or delegated setter %s to take two parameters.")
1814
1815 (js2-msg "msg.setter.parms"
1816 "Expected either one or two parameters for setter.")
1817
1818 (js2-msg "msg.setter.bad.type"
1819 "Unsupported parameter type '%s' in setter '%s'.")
1820
1821 (js2-msg "msg.add.sealed"
1822 "Cannot add a property to a sealed object: %s.")
1823
1824 (js2-msg "msg.remove.sealed"
1825 "Cannot remove a property from a sealed object: %s.")
1826
1827 (js2-msg "msg.modify.sealed"
1828 "Cannot modify a property of a sealed object: %s.")
1829
1830 (js2-msg "msg.modify.readonly"
1831 "Cannot modify readonly property: %s.")
1832
1833 ;; TokenStream
1834 (js2-msg "msg.missing.exponent"
1835 "missing exponent")
1836
1837 (js2-msg "msg.caught.nfe"
1838 "number format error")
1839
1840 (js2-msg "msg.unterminated.string.lit"
1841 "unterminated string literal")
1842
1843 (js2-msg "msg.unterminated.comment"
1844 "unterminated comment")
1845
1846 (js2-msg "msg.unterminated.re.lit"
1847 "unterminated regular expression literal")
1848
1849 (js2-msg "msg.invalid.re.flag"
1850 "invalid flag after regular expression")
1851
1852 (js2-msg "msg.no.re.input.for"
1853 "no input for %s")
1854
1855 (js2-msg "msg.illegal.character"
1856 "illegal character")
1857
1858 (js2-msg "msg.invalid.escape"
1859 "invalid Unicode escape sequence")
1860
1861 (js2-msg "msg.bad.namespace"
1862 "not a valid default namespace statement. "
1863 "Syntax is: default xml namespace = EXPRESSION;")
1864
1865 ;; TokensStream warnings
1866 (js2-msg "msg.bad.octal.literal"
1867 "illegal octal literal digit %s; "
1868 "interpreting it as a decimal digit")
1869
1870 (js2-msg "msg.reserved.keyword"
1871 "illegal usage of future reserved keyword %s; "
1872 "interpreting it as ordinary identifier")
1873
1874 (js2-msg "msg.script.is.not.constructor"
1875 "Script objects are not constructors.")
1876
1877 ;; Arrays
1878 (js2-msg "msg.arraylength.bad"
1879 "Inappropriate array length.")
1880
1881 ;; Arrays
1882 (js2-msg "msg.arraylength.too.big"
1883 "Array length %s exceeds supported capacity limit.")
1884
1885 ;; URI
1886 (js2-msg "msg.bad.uri"
1887 "Malformed URI sequence.")
1888
1889 ;; Number
1890 (js2-msg "msg.bad.precision"
1891 "Precision %s out of range.")
1892
1893 ;; NativeGenerator
1894 (js2-msg "msg.send.newborn"
1895 "Attempt to send value to newborn generator")
1896
1897 (js2-msg "msg.already.exec.gen"
1898 "Already executing generator")
1899
1900 (js2-msg "msg.StopIteration.invalid"
1901 "StopIteration may not be changed to an arbitrary object.")
1902
1903 ;; Interpreter
1904 (js2-msg "msg.yield.closing"
1905 "Yield from closing generator")
1906
1907 ;;; Utilities
1908
1909 (defun js2-delete-if (predicate list)
1910 "Remove all items satisfying PREDICATE in LIST."
1911 (loop for item in list
1912 if (not (funcall predicate item))
1913 collect item))
1914
1915 (defun js2-position (element list)
1916 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1917 Returns nil if element is not found in the list."
1918 (let ((count 0)
1919 found)
1920 (while (and list (not found))
1921 (if (eq element (car list))
1922 (setq found t)
1923 (setq count (1+ count)
1924 list (cdr list))))
1925 (if found count)))
1926
1927 (defun js2-find-if (predicate list)
1928 "Find first item satisfying PREDICATE in LIST."
1929 (let (result)
1930 (while (and list (not result))
1931 (if (funcall predicate (car list))
1932 (setq result (car list)))
1933 (setq list (cdr list)))
1934 result))
1935
1936 (defmacro js2-time (form)
1937 "Evaluate FORM, discard result, and return elapsed time in sec."
1938 (declare (debug t))
1939 (let ((beg (make-symbol "--js2-time-beg--"))
1940 (delta (make-symbol "--js2-time-end--")))
1941 `(let ((,beg (current-time))
1942 ,delta)
1943 ,form
1944 (/ (truncate (* (- (float-time (current-time))
1945 (float-time ,beg))
1946 10000))
1947 10000.0))))
1948
1949 (defsubst js2-same-line (pos)
1950 "Return t if POS is on the same line as current point."
1951 (and (>= pos (point-at-bol))
1952 (<= pos (point-at-eol))))
1953
1954 (defun js2-same-line-2 (p1 p2)
1955 "Return t if P1 is on the same line as P2."
1956 (save-excursion
1957 (goto-char p1)
1958 (js2-same-line p2)))
1959
1960 (defun js2-code-bug ()
1961 "Signal an error when we encounter an unexpected code path."
1962 (error "failed assertion"))
1963
1964 (defsubst js2-record-text-property (beg end prop value)
1965 "Record a text property to set when parsing finishes."
1966 (push (list beg end prop value) js2-mode-deferred-properties))
1967
1968 ;; I'd like to associate errors with nodes, but for now the
1969 ;; easiest thing to do is get the context info from the last token.
1970 (defun js2-record-parse-error (msg &optional arg pos len)
1971 (push (list (list msg arg)
1972 (or pos js2-token-beg)
1973 (or len (- js2-token-end js2-token-beg)))
1974 js2-parsed-errors))
1975
1976 (defun js2-report-error (msg &optional msg-arg pos len)
1977 "Signal a syntax error or record a parse error."
1978 (if js2-recover-from-parse-errors
1979 (js2-record-parse-error msg msg-arg pos len)
1980 (signal 'js2-syntax-error
1981 (list msg
1982 js2-ts-lineno
1983 (save-excursion
1984 (goto-char js2-ts-cursor)
1985 (current-column))
1986 js2-ts-hit-eof))))
1987
1988 (defun js2-report-warning (msg &optional msg-arg pos len face)
1989 (if js2-compiler-report-warning-as-error
1990 (js2-report-error msg msg-arg pos len)
1991 (push (list (list msg msg-arg)
1992 (or pos js2-token-beg)
1993 (or len (- js2-token-end js2-token-beg))
1994 face)
1995 js2-parsed-warnings)))
1996
1997 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
1998 (if js2-compiler-strict-mode
1999 (js2-report-warning msg-id msg-arg beg
2000 (and beg end (- end beg)))))
2001
2002 (put 'js2-syntax-error 'error-conditions
2003 '(error syntax-error js2-syntax-error))
2004 (put 'js2-syntax-error 'error-message "Syntax error")
2005
2006 (put 'js2-parse-error 'error-conditions
2007 '(error parse-error js2-parse-error))
2008 (put 'js2-parse-error 'error-message "Parse error")
2009
2010 (defmacro js2-clear-flag (flags flag)
2011 `(setq ,flags (logand ,flags (lognot ,flag))))
2012
2013 (defmacro js2-set-flag (flags flag)
2014 "Logical-or FLAG into FLAGS."
2015 `(setq ,flags (logior ,flags ,flag)))
2016
2017 (defsubst js2-flag-set-p (flags flag)
2018 (/= 0 (logand flags flag)))
2019
2020 (defsubst js2-flag-not-set-p (flags flag)
2021 (zerop (logand flags flag)))
2022
2023 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2024 "Evaluate BODY with the _ character set to be word-syntax."
2025 (declare (indent 0) (debug t))
2026 (let ((old-syntax (make-symbol "old-syntax")))
2027 `(let ((,old-syntax (string (char-syntax ?_))))
2028 (unwind-protect
2029 (progn
2030 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2031 ,@body)
2032 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2033
2034 (defsubst js2-char-uppercase-p (c)
2035 "Return t if C is an uppercase character.
2036 Handles unicode and latin chars properly."
2037 (/= c (downcase c)))
2038
2039 (defsubst js2-char-lowercase-p (c)
2040 "Return t if C is an uppercase character.
2041 Handles unicode and latin chars properly."
2042 (/= c (upcase c)))
2043
2044 ;;; AST struct and function definitions
2045
2046 ;; flags for ast node property 'member-type (used for e4x operators)
2047 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2048 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2049 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2050
2051 (defsubst js2-relpos (pos anchor)
2052 "Convert POS to be relative to ANCHOR.
2053 If POS is nil, returns nil."
2054 (and pos (- pos anchor)))
2055
2056 (defun js2-make-pad (indent)
2057 (if (zerop indent)
2058 ""
2059 (make-string (* indent js2-basic-offset) ? )))
2060
2061 (defun js2-visit-ast (node callback)
2062 "Visit every node in ast NODE with visitor CALLBACK.
2063
2064 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2065 called twice: once to visit the node, and again after all the node's
2066 children have been processed. The END-P argument is nil on the first
2067 call and non-nil on the second call. The return value of the callback
2068 affects the traversal: if non-nil, the children of NODE are processed.
2069 If the callback returns nil, or if the node has no children, then the
2070 callback is called immediately with a non-nil END-P argument.
2071
2072 The node traversal is approximately lexical-order, although there
2073 are currently no guarantees around this."
2074 (when node
2075 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2076 ;; visit the node
2077 (when (funcall callback node nil)
2078 ;; visit the kids
2079 (cond
2080 ((eq vfunc 'js2-visit-none)
2081 nil) ; don't even bother calling it
2082 ;; Each AST node type has to define a `js2-visitor' function
2083 ;; that takes a node and a callback, and calls `js2-visit-ast'
2084 ;; on each child of the node.
2085 (vfunc
2086 (funcall vfunc node callback))
2087 (t
2088 (error "%s does not define a visitor-traversal function"
2089 (aref node 0)))))
2090 ;; call the end-visit
2091 (funcall callback node t))))
2092
2093 (defstruct (js2-node
2094 (:constructor nil)) ; abstract
2095 "Base AST node type."
2096 (type -1) ; token type
2097 (pos -1) ; start position of this AST node in parsed input
2098 (len 1) ; num characters spanned by the node
2099 props ; optional node property list (an alist)
2100 parent) ; link to parent node; null for root
2101
2102 (defsubst js2-node-get-prop (node prop &optional default)
2103 (or (cadr (assoc prop (js2-node-props node))) default))
2104
2105 (defsubst js2-node-set-prop (node prop value)
2106 (setf (js2-node-props node)
2107 (cons (list prop value) (js2-node-props node))))
2108
2109 (defun js2-fixup-starts (n nodes)
2110 "Adjust the start positions of NODES to be relative to N.
2111 Any node in the list may be nil, for convenience."
2112 (dolist (node nodes)
2113 (when node
2114 (setf (js2-node-pos node) (- (js2-node-pos node)
2115 (js2-node-pos n))))))
2116
2117 (defun js2-node-add-children (parent &rest nodes)
2118 "Set parent node of NODES to PARENT, and return PARENT.
2119 Does nothing if we're not recording parent links.
2120 If any given node in NODES is nil, doesn't record that link."
2121 (js2-fixup-starts parent nodes)
2122 (dolist (node nodes)
2123 (and node
2124 (setf (js2-node-parent node) parent))))
2125
2126 ;; Non-recursive since it's called a frightening number of times.
2127 (defun js2-node-abs-pos (n)
2128 (let ((pos (js2-node-pos n)))
2129 (while (setq n (js2-node-parent n))
2130 (setq pos (+ pos (js2-node-pos n))))
2131 pos))
2132
2133 (defsubst js2-node-abs-end (n)
2134 "Return absolute buffer position of end of N."
2135 (+ (js2-node-abs-pos n) (js2-node-len n)))
2136
2137 ;; It's important to make sure block nodes have a Lisp list for the
2138 ;; child nodes, to limit printing recursion depth in an AST that
2139 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2140 ;; a sufficiently large vector tree.
2141
2142 (defstruct (js2-block-node
2143 (:include js2-node)
2144 (:constructor nil)
2145 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2146 (pos js2-token-beg)
2147 len
2148 props
2149 kids)))
2150 "A block of statements."
2151 kids) ; a Lisp list of the child statement nodes
2152
2153 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2154 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2155
2156 (defun js2-visit-block (ast callback)
2157 "Visit the `js2-block-node' children of AST."
2158 (dolist (kid (js2-block-node-kids ast))
2159 (js2-visit-ast kid callback)))
2160
2161 (defun js2-print-block (n i)
2162 (let ((pad (js2-make-pad i)))
2163 (insert pad "{\n")
2164 (dolist (kid (js2-block-node-kids n))
2165 (js2-print-ast kid (1+ i)))
2166 (insert pad "}")))
2167
2168 (defstruct (js2-scope
2169 (:include js2-block-node)
2170 (:constructor nil)
2171 (:constructor make-js2-scope (&key (type js2-BLOCK)
2172 (pos js2-token-beg)
2173 len
2174 kids)))
2175 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2176 ;; I don't have one of those handy, so I'll use an alist for now.
2177 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2178 ;; and is much lighter-weight to construct (both CPU and mem).
2179 ;; The keys are interned strings (symbols) for faster lookup.
2180 ;; Should switch to hybrid alist/hashtable eventually.
2181 symbol-table ; an alist of (symbol . js2-symbol)
2182 parent-scope ; a `js2-scope'
2183 top) ; top-level `js2-scope' (script/function)
2184
2185 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2186 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2187
2188 (defun js2-scope-set-parent-scope (scope parent)
2189 (setf (js2-scope-parent-scope scope) parent
2190 (js2-scope-top scope) (if (null parent)
2191 scope
2192 (js2-scope-top parent))))
2193
2194 (defun js2-node-get-enclosing-scope (node)
2195 "Return the innermost `js2-scope' node surrounding NODE.
2196 Returns nil if there is no enclosing scope node."
2197 (let ((parent (js2-node-parent node)))
2198 (while (not (js2-scope-p parent))
2199 (setq parent (js2-node-parent parent)))
2200 parent))
2201
2202 (defun js2-get-defining-scope (scope name)
2203 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2204 Returns `js2-scope' in which NAME is defined, or nil if not found."
2205 (let ((sym (if (symbolp name)
2206 name
2207 (intern name)))
2208 table
2209 result
2210 (continue t))
2211 (while (and scope continue)
2212 (if (and (setq table (js2-scope-symbol-table scope))
2213 (assq sym table))
2214 (setq continue nil
2215 result scope)
2216 (setq scope (js2-scope-parent-scope scope))))
2217 result))
2218
2219 (defun js2-scope-get-symbol (scope name)
2220 "Return symbol table entry for NAME in SCOPE.
2221 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2222 (and (js2-scope-symbol-table scope)
2223 (cdr (assq (if (symbolp name)
2224 name
2225 (intern name))
2226 (js2-scope-symbol-table scope)))))
2227
2228 (defun js2-scope-put-symbol (scope name symbol)
2229 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2230 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2231 (let* ((table (js2-scope-symbol-table scope))
2232 (sym (if (symbolp name) name (intern name)))
2233 (entry (assq sym table)))
2234 (if entry
2235 (setcdr entry symbol)
2236 (push (cons sym symbol)
2237 (js2-scope-symbol-table scope)))))
2238
2239 (defstruct (js2-symbol
2240 (:constructor nil)
2241 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2242 "A symbol table entry."
2243 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2244 ;; js2-LET, or js2-CONST
2245 decl-type
2246 name ; string
2247 ast-node) ; a `js2-node'
2248
2249 (defstruct (js2-error-node
2250 (:include js2-node)
2251 (:constructor nil) ; silence emacs21 byte-compiler
2252 (:constructor make-js2-error-node (&key (type js2-ERROR)
2253 (pos js2-token-beg)
2254 len)))
2255 "AST node representing a parse error.")
2256
2257 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2258 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2259
2260 (defstruct (js2-script-node
2261 (:include js2-scope)
2262 (:constructor nil)
2263 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2264 (pos js2-token-beg)
2265 len
2266 var-decls
2267 fun-decls)))
2268 functions ; Lisp list of nested functions
2269 regexps ; Lisp list of (string . flags)
2270 symbols ; alist (every symbol gets unique index)
2271 (param-count 0)
2272 var-names ; vector of string names
2273 consts ; bool-vector matching var-decls
2274 (temp-number 0)) ; for generating temp variables
2275
2276 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2277 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2278
2279 (defun js2-print-script (node indent)
2280 (dolist (kid (js2-block-node-kids node))
2281 (js2-print-ast kid indent)))
2282
2283 (defstruct (js2-ast-root
2284 (:include js2-script-node)
2285 (:constructor nil)
2286 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2287 (pos js2-token-beg)
2288 len
2289 buffer)))
2290 "The root node of a js2 AST."
2291 buffer ; the source buffer from which the code was parsed
2292 comments ; a Lisp list of comments, ordered by start position
2293 errors ; a Lisp list of errors found during parsing
2294 warnings ; a Lisp list of warnings found during parsing
2295 node-count) ; number of nodes in the tree, including the root
2296
2297 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2298 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2299
2300 (defun js2-visit-ast-root (ast callback)
2301 (dolist (kid (js2-ast-root-kids ast))
2302 (js2-visit-ast kid callback))
2303 (dolist (comment (js2-ast-root-comments ast))
2304 (js2-visit-ast comment callback)))
2305
2306 (defstruct (js2-comment-node
2307 (:include js2-node)
2308 (:constructor nil)
2309 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2310 (pos js2-token-beg)
2311 len
2312 (format js2-ts-comment-type))))
2313 format) ; 'line, 'block, 'jsdoc or 'html
2314
2315 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2316 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2317
2318 (defun js2-print-comment (n i)
2319 ;; We really ought to link end-of-line comments to their nodes.
2320 ;; Or maybe we could add a new comment type, 'endline.
2321 (insert (js2-make-pad i)
2322 (js2-node-string n)))
2323
2324 (defstruct (js2-expr-stmt-node
2325 (:include js2-node)
2326 (:constructor nil)
2327 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2328 (pos js2-ts-cursor)
2329 len
2330 expr)))
2331 "An expression statement."
2332 expr)
2333
2334 (defsubst js2-expr-stmt-node-set-has-result (node)
2335 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2336 (setf (js2-node-type node) js2-EXPR_RESULT))
2337
2338 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2339 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2340
2341 (defun js2-visit-expr-stmt-node (n v)
2342 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2343
2344 (defun js2-print-expr-stmt-node (n indent)
2345 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2346 (insert ";\n"))
2347
2348 (defstruct (js2-loop-node
2349 (:include js2-scope)
2350 (:constructor nil))
2351 "Abstract supertype of loop nodes."
2352 body ; a `js2-block-node'
2353 lp ; position of left-paren, nil if omitted
2354 rp) ; position of right-paren, nil if omitted
2355
2356 (defstruct (js2-do-node
2357 (:include js2-loop-node)
2358 (:constructor nil)
2359 (:constructor make-js2-do-node (&key (type js2-DO)
2360 (pos js2-token-beg)
2361 len
2362 body
2363 condition
2364 while-pos
2365 lp
2366 rp)))
2367 "AST node for do-loop."
2368 condition ; while (expression)
2369 while-pos) ; buffer position of 'while' keyword
2370
2371 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2372 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2373
2374 (defun js2-visit-do-node (n v)
2375 (js2-visit-ast (js2-do-node-body n) v)
2376 (js2-visit-ast (js2-do-node-condition n) v))
2377
2378 (defun js2-print-do-node (n i)
2379 (let ((pad (js2-make-pad i)))
2380 (insert pad "do {\n")
2381 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2382 (js2-print-ast kid (1+ i)))
2383 (insert pad "} while (")
2384 (js2-print-ast (js2-do-node-condition n) 0)
2385 (insert ");\n")))
2386
2387 (defstruct (js2-while-node
2388 (:include js2-loop-node)
2389 (:constructor nil)
2390 (:constructor make-js2-while-node (&key (type js2-WHILE)
2391 (pos js2-token-beg)
2392 len body
2393 condition lp
2394 rp)))
2395 "AST node for while-loop."
2396 condition) ; while-condition
2397
2398 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2399 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2400
2401 (defun js2-visit-while-node (n v)
2402 (js2-visit-ast (js2-while-node-condition n) v)
2403 (js2-visit-ast (js2-while-node-body n) v))
2404
2405 (defun js2-print-while-node (n i)
2406 (let ((pad (js2-make-pad i)))
2407 (insert pad "while (")
2408 (js2-print-ast (js2-while-node-condition n) 0)
2409 (insert ") {\n")
2410 (js2-print-body (js2-while-node-body n) (1+ i))
2411 (insert pad "}\n")))
2412
2413 (defstruct (js2-for-node
2414 (:include js2-loop-node)
2415 (:constructor nil)
2416 (:constructor make-js2-for-node (&key (type js2-FOR)
2417 (pos js2-ts-cursor)
2418 len body init
2419 condition
2420 update lp rp)))
2421 "AST node for a C-style for-loop."
2422 init ; initialization expression
2423 condition ; loop condition
2424 update) ; update clause
2425
2426 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2427 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2428
2429 (defun js2-visit-for-node (n v)
2430 (js2-visit-ast (js2-for-node-init n) v)
2431 (js2-visit-ast (js2-for-node-condition n) v)
2432 (js2-visit-ast (js2-for-node-update n) v)
2433 (js2-visit-ast (js2-for-node-body n) v))
2434
2435 (defun js2-print-for-node (n i)
2436 (let ((pad (js2-make-pad i)))
2437 (insert pad "for (")
2438 (js2-print-ast (js2-for-node-init n) 0)
2439 (insert "; ")
2440 (js2-print-ast (js2-for-node-condition n) 0)
2441 (insert "; ")
2442 (js2-print-ast (js2-for-node-update n) 0)
2443 (insert ") {\n")
2444 (js2-print-body (js2-for-node-body n) (1+ i))
2445 (insert pad "}\n")))
2446
2447 (defstruct (js2-for-in-node
2448 (:include js2-loop-node)
2449 (:constructor nil)
2450 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2451 (pos js2-ts-cursor)
2452 len body
2453 iterator
2454 object
2455 in-pos
2456 each-pos
2457 foreach-p forof-p
2458 lp rp)))
2459 "AST node for a for..in loop."
2460 iterator ; [var] foo in ...
2461 object ; object over which we're iterating
2462 in-pos ; buffer position of 'in' keyword
2463 each-pos ; buffer position of 'each' keyword, if foreach-p
2464 foreach-p ; t if it's a for-each loop
2465 forof-p) ; t if it's a for-of loop
2466
2467 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2468 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2469
2470 (defun js2-visit-for-in-node (n v)
2471 (js2-visit-ast (js2-for-in-node-iterator n) v)
2472 (js2-visit-ast (js2-for-in-node-object n) v)
2473 (js2-visit-ast (js2-for-in-node-body n) v))
2474
2475 (defun js2-print-for-in-node (n i)
2476 (let ((pad (js2-make-pad i))
2477 (foreach (js2-for-in-node-foreach-p n))
2478 (forof (js2-for-in-node-forof-p n)))
2479 (insert pad "for ")
2480 (if foreach
2481 (insert "each "))
2482 (insert "(")
2483 (js2-print-ast (js2-for-in-node-iterator n) 0)
2484 (if forof
2485 (insert " of ")
2486 (insert " in "))
2487 (js2-print-ast (js2-for-in-node-object n) 0)
2488 (insert ") {\n")
2489 (js2-print-body (js2-for-in-node-body n) (1+ i))
2490 (insert pad "}\n")))
2491
2492 (defstruct (js2-return-node
2493 (:include js2-node)
2494 (:constructor nil)
2495 (:constructor make-js2-return-node (&key (type js2-RETURN)
2496 (pos js2-ts-cursor)
2497 len
2498 retval)))
2499 "AST node for a return statement."
2500 retval) ; expression to return, or 'undefined
2501
2502 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2503 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2504
2505 (defun js2-visit-return-node (n v)
2506 (js2-visit-ast (js2-return-node-retval n) v))
2507
2508 (defun js2-print-return-node (n i)
2509 (insert (js2-make-pad i) "return")
2510 (when (js2-return-node-retval n)
2511 (insert " ")
2512 (js2-print-ast (js2-return-node-retval n) 0))
2513 (insert ";\n"))
2514
2515 (defstruct (js2-if-node
2516 (:include js2-node)
2517 (:constructor nil)
2518 (:constructor make-js2-if-node (&key (type js2-IF)
2519 (pos js2-ts-cursor)
2520 len condition
2521 then-part
2522 else-pos
2523 else-part lp
2524 rp)))
2525 "AST node for an if-statement."
2526 condition ; expression
2527 then-part ; statement or block
2528 else-pos ; optional buffer position of 'else' keyword
2529 else-part ; optional statement or block
2530 lp ; position of left-paren, nil if omitted
2531 rp) ; position of right-paren, nil if omitted
2532
2533 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2534 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2535
2536 (defun js2-visit-if-node (n v)
2537 (js2-visit-ast (js2-if-node-condition n) v)
2538 (js2-visit-ast (js2-if-node-then-part n) v)
2539 (js2-visit-ast (js2-if-node-else-part n) v))
2540
2541 (defun js2-print-if-node (n i)
2542 (let ((pad (js2-make-pad i))
2543 (then-part (js2-if-node-then-part n))
2544 (else-part (js2-if-node-else-part n)))
2545 (insert pad "if (")
2546 (js2-print-ast (js2-if-node-condition n) 0)
2547 (insert ") {\n")
2548 (js2-print-body then-part (1+ i))
2549 (insert pad "}")
2550 (cond
2551 ((not else-part)
2552 (insert "\n"))
2553 ((js2-if-node-p else-part)
2554 (insert " else ")
2555 (js2-print-body else-part i))
2556 (t
2557 (insert " else {\n")
2558 (js2-print-body else-part (1+ i))
2559 (insert pad "}\n")))))
2560
2561 (defstruct (js2-try-node
2562 (:include js2-node)
2563 (:constructor nil)
2564 (:constructor make-js2-try-node (&key (type js2-TRY)
2565 (pos js2-ts-cursor)
2566 len
2567 try-block
2568 catch-clauses
2569 finally-block)))
2570 "AST node for a try-statement."
2571 try-block
2572 catch-clauses ; a Lisp list of `js2-catch-node'
2573 finally-block) ; a `js2-finally-node'
2574
2575 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2576 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2577
2578 (defun js2-visit-try-node (n v)
2579 (js2-visit-ast (js2-try-node-try-block n) v)
2580 (dolist (clause (js2-try-node-catch-clauses n))
2581 (js2-visit-ast clause v))
2582 (js2-visit-ast (js2-try-node-finally-block n) v))
2583
2584 (defun js2-print-try-node (n i)
2585 (let ((pad (js2-make-pad i))
2586 (catches (js2-try-node-catch-clauses n))
2587 (finally (js2-try-node-finally-block n)))
2588 (insert pad "try {\n")
2589 (js2-print-body (js2-try-node-try-block n) (1+ i))
2590 (insert pad "}")
2591 (when catches
2592 (dolist (catch catches)
2593 (js2-print-ast catch i)))
2594 (if finally
2595 (js2-print-ast finally i)
2596 (insert "\n"))))
2597
2598 (defstruct (js2-catch-node
2599 (:include js2-node)
2600 (:constructor nil)
2601 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2602 (pos js2-ts-cursor)
2603 len
2604 param
2605 guard-kwd
2606 guard-expr
2607 block lp
2608 rp)))
2609 "AST node for a catch clause."
2610 param ; destructuring form or simple name node
2611 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2612 guard-expr ; catch condition, a `js2-node'
2613 block ; statements, a `js2-block-node'
2614 lp ; buffer position of left-paren, nil if omitted
2615 rp) ; buffer position of right-paren, nil if omitted
2616
2617 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2618 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2619
2620 (defun js2-visit-catch-node (n v)
2621 (js2-visit-ast (js2-catch-node-param n) v)
2622 (when (js2-catch-node-guard-kwd n)
2623 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2624 (js2-visit-ast (js2-catch-node-block n) v))
2625
2626 (defun js2-print-catch-node (n i)
2627 (let ((pad (js2-make-pad i))
2628 (guard-kwd (js2-catch-node-guard-kwd n))
2629 (guard-expr (js2-catch-node-guard-expr n)))
2630 (insert " catch (")
2631 (js2-print-ast (js2-catch-node-param n) 0)
2632 (when guard-kwd
2633 (insert " if ")
2634 (js2-print-ast guard-expr 0))
2635 (insert ") {\n")
2636 (js2-print-body (js2-catch-node-block n) (1+ i))
2637 (insert pad "}")))
2638
2639 (defstruct (js2-finally-node
2640 (:include js2-node)
2641 (:constructor nil)
2642 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2643 (pos js2-ts-cursor)
2644 len body)))
2645 "AST node for a finally clause."
2646 body) ; a `js2-node', often but not always a block node
2647
2648 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2649 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2650
2651 (defun js2-visit-finally-node (n v)
2652 (js2-visit-ast (js2-finally-node-body n) v))
2653
2654 (defun js2-print-finally-node (n i)
2655 (let ((pad (js2-make-pad i)))
2656 (insert " finally {\n")
2657 (js2-print-body (js2-finally-node-body n) (1+ i))
2658 (insert pad "}\n")))
2659
2660 (defstruct (js2-switch-node
2661 (:include js2-node)
2662 (:constructor nil)
2663 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2664 (pos js2-ts-cursor)
2665 len
2666 discriminant
2667 cases lp
2668 rp)))
2669 "AST node for a switch statement."
2670 discriminant ; a `js2-node' (switch expression)
2671 cases ; a Lisp list of `js2-case-node'
2672 lp ; position of open-paren for discriminant, nil if omitted
2673 rp) ; position of close-paren for discriminant, nil if omitted
2674
2675 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2676 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2677
2678 (defun js2-visit-switch-node (n v)
2679 (js2-visit-ast (js2-switch-node-discriminant n) v)
2680 (dolist (c (js2-switch-node-cases n))
2681 (js2-visit-ast c v)))
2682
2683 (defun js2-print-switch-node (n i)
2684 (let ((pad (js2-make-pad i))
2685 (cases (js2-switch-node-cases n)))
2686 (insert pad "switch (")
2687 (js2-print-ast (js2-switch-node-discriminant n) 0)
2688 (insert ") {\n")
2689 (dolist (case cases)
2690 (js2-print-ast case i))
2691 (insert pad "}\n")))
2692
2693 (defstruct (js2-case-node
2694 (:include js2-block-node)
2695 (:constructor nil)
2696 (:constructor make-js2-case-node (&key (type js2-CASE)
2697 (pos js2-ts-cursor)
2698 len kids expr)))
2699 "AST node for a case clause of a switch statement."
2700 expr) ; the case expression (nil for default)
2701
2702 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2703 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2704
2705 (defun js2-visit-case-node (n v)
2706 (js2-visit-ast (js2-case-node-expr n) v)
2707 (js2-visit-block n v))
2708
2709 (defun js2-print-case-node (n i)
2710 (let ((pad (js2-make-pad i))
2711 (expr (js2-case-node-expr n)))
2712 (insert pad)
2713 (if (null expr)
2714 (insert "default:\n")
2715 (insert "case ")
2716 (js2-print-ast expr 0)
2717 (insert ":\n"))
2718 (dolist (kid (js2-case-node-kids n))
2719 (js2-print-ast kid (1+ i)))))
2720
2721 (defstruct (js2-throw-node
2722 (:include js2-node)
2723 (:constructor nil)
2724 (:constructor make-js2-throw-node (&key (type js2-THROW)
2725 (pos js2-ts-cursor)
2726 len expr)))
2727 "AST node for a throw statement."
2728 expr) ; the expression to throw
2729
2730 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2731 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2732
2733 (defun js2-visit-throw-node (n v)
2734 (js2-visit-ast (js2-throw-node-expr n) v))
2735
2736 (defun js2-print-throw-node (n i)
2737 (insert (js2-make-pad i) "throw ")
2738 (js2-print-ast (js2-throw-node-expr n) 0)
2739 (insert ";\n"))
2740
2741 (defstruct (js2-with-node
2742 (:include js2-node)
2743 (:constructor nil)
2744 (:constructor make-js2-with-node (&key (type js2-WITH)
2745 (pos js2-ts-cursor)
2746 len object
2747 body lp rp)))
2748 "AST node for a with-statement."
2749 object
2750 body
2751 lp ; buffer position of left-paren around object, nil if omitted
2752 rp) ; buffer position of right-paren around object, nil if omitted
2753
2754 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2755 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2756
2757 (defun js2-visit-with-node (n v)
2758 (js2-visit-ast (js2-with-node-object n) v)
2759 (js2-visit-ast (js2-with-node-body n) v))
2760
2761 (defun js2-print-with-node (n i)
2762 (let ((pad (js2-make-pad i)))
2763 (insert pad "with (")
2764 (js2-print-ast (js2-with-node-object n) 0)
2765 (insert ") {\n")
2766 (js2-print-body (js2-with-node-body n) (1+ i))
2767 (insert pad "}\n")))
2768
2769 (defstruct (js2-label-node
2770 (:include js2-node)
2771 (:constructor nil)
2772 (:constructor make-js2-label-node (&key (type js2-LABEL)
2773 (pos js2-ts-cursor)
2774 len name)))
2775 "AST node for a statement label or case label."
2776 name ; a string
2777 loop) ; for validating and code-generating continue-to-label
2778
2779 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2780 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2781
2782 (defun js2-print-label (n i)
2783 (insert (js2-make-pad i)
2784 (js2-label-node-name n)
2785 ":\n"))
2786
2787 (defstruct (js2-labeled-stmt-node
2788 (:include js2-node)
2789 (:constructor nil)
2790 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2791 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2792 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2793 (pos js2-ts-cursor)
2794 len labels stmt)))
2795 "AST node for a statement with one or more labels.
2796 Multiple labels for a statement are collapsed into the labels field."
2797 labels ; Lisp list of `js2-label-node'
2798 stmt) ; the statement these labels are for
2799
2800 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2801 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2802
2803 (defun js2-get-label-by-name (lbl-stmt name)
2804 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2805 Returns nil if no such label is in the list."
2806 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2807 result)
2808 (while (and label-list (not result))
2809 (if (string= (js2-label-node-name (car label-list)) name)
2810 (setq result (car label-list))
2811 (setq label-list (cdr label-list))))
2812 result))
2813
2814 (defun js2-visit-labeled-stmt (n v)
2815 (dolist (label (js2-labeled-stmt-node-labels n))
2816 (js2-visit-ast label v))
2817 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2818
2819 (defun js2-print-labeled-stmt (n i)
2820 (dolist (label (js2-labeled-stmt-node-labels n))
2821 (js2-print-ast label i))
2822 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2823
2824 (defun js2-labeled-stmt-node-contains (node label)
2825 "Return t if NODE contains LABEL in its label set.
2826 NODE is a `js2-labels-node'. LABEL is an identifier."
2827 (loop for nl in (js2-labeled-stmt-node-labels node)
2828 if (string= label (js2-label-node-name nl))
2829 return t
2830 finally return nil))
2831
2832 (defsubst js2-labeled-stmt-node-add-label (node label)
2833 "Add a `js2-label-node' to the label set for this statement."
2834 (setf (js2-labeled-stmt-node-labels node)
2835 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2836
2837 (defstruct (js2-jump-node
2838 (:include js2-node)
2839 (:constructor nil))
2840 "Abstract supertype of break and continue nodes."
2841 label ; `js2-name-node' for location of label identifier, if present
2842 target) ; target js2-labels-node or loop/switch statement
2843
2844 (defun js2-visit-jump-node (n v)
2845 ;; We don't visit the target, since it's a back-link.
2846 (js2-visit-ast (js2-jump-node-label n) v))
2847
2848 (defstruct (js2-break-node
2849 (:include js2-jump-node)
2850 (:constructor nil)
2851 (:constructor make-js2-break-node (&key (type js2-BREAK)
2852 (pos js2-ts-cursor)
2853 len label target)))
2854 "AST node for a break statement.
2855 The label field is a `js2-name-node', possibly nil, for the named label
2856 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2857 is the target of the break - a label node or enclosing loop/switch statement.")
2858
2859 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2860 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2861
2862 (defun js2-print-break-node (n i)
2863 (insert (js2-make-pad i) "break")
2864 (when (js2-break-node-label n)
2865 (insert " ")
2866 (js2-print-ast (js2-break-node-label n) 0))
2867 (insert ";\n"))
2868
2869 (defstruct (js2-continue-node
2870 (:include js2-jump-node)
2871 (:constructor nil)
2872 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2873 (pos js2-ts-cursor)
2874 len label target)))
2875 "AST node for a continue statement.
2876 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2877 It is nil if continue specifies no label. The target field is the jump target:
2878 a `js2-label-node' or the innermost enclosing loop.")
2879
2880 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2881 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2882
2883 (defun js2-print-continue-node (n i)
2884 (insert (js2-make-pad i) "continue")
2885 (when (js2-continue-node-label n)
2886 (insert " ")
2887 (js2-print-ast (js2-continue-node-label n) 0))
2888 (insert ";\n"))
2889
2890 (defstruct (js2-function-node
2891 (:include js2-script-node)
2892 (:constructor nil)
2893 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2894 (pos js2-ts-cursor)
2895 len
2896 (ftype 'FUNCTION)
2897 (form 'FUNCTION_STATEMENT)
2898 (name "")
2899 params rest-p
2900 body
2901 lp rp)))
2902 "AST node for a function declaration.
2903 The `params' field is a Lisp list of nodes. Each node is either a simple
2904 `js2-name-node', or if it's a destructuring-assignment parameter, a
2905 `js2-array-node' or `js2-object-node'."
2906 ftype ; FUNCTION, GETTER or SETTER
2907 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2908 name ; function name (a `js2-name-node', or nil if anonymous)
2909 params ; a Lisp list of destructuring forms or simple name nodes
2910 rest-p ; if t, the last parameter is rest parameter
2911 body ; a `js2-block-node' or expression node (1.8 only)
2912 lp ; position of arg-list open-paren, or nil if omitted
2913 rp ; position of arg-list close-paren, or nil if omitted
2914 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2915 needs-activation ; t if we need an activation object for this frame
2916 is-generator ; t if this function contains a yield
2917 member-expr) ; nonstandard Ecma extension from Rhino
2918
2919 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2920 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2921
2922 (defun js2-visit-function-node (n v)
2923 (js2-visit-ast (js2-function-node-name n) v)
2924 (dolist (p (js2-function-node-params n))
2925 (js2-visit-ast p v))
2926 (js2-visit-ast (js2-function-node-body n) v))
2927
2928 (defun js2-print-function-node (n i)
2929 (let ((pad (js2-make-pad i))
2930 (getter (js2-node-get-prop n 'GETTER_SETTER))
2931 (name (js2-function-node-name n))
2932 (params (js2-function-node-params n))
2933 (rest-p (js2-function-node-rest-p n))
2934 (body (js2-function-node-body n))
2935 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2936 (unless getter
2937 (insert pad "function"))
2938 (when name
2939 (insert " ")
2940 (js2-print-ast name 0))
2941 (insert "(")
2942 (loop with len = (length params)
2943 for param in params
2944 for count from 1
2945 do
2946 (when (and rest-p (= count len))
2947 (insert "..."))
2948 (js2-print-ast param 0)
2949 (when (< count len)
2950 (insert ", ")))
2951 (insert ") {")
2952 (unless expr
2953 (insert "\n"))
2954 ;; TODO: fix this to be smarter about indenting, etc.
2955 (js2-print-body body (1+ i))
2956 (insert pad "}")
2957 (unless expr
2958 (insert "\n"))))
2959
2960 (defun js2-function-name (node)
2961 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2962 (and (js2-function-node-name node)
2963 (js2-name-node-name (js2-function-node-name node))))
2964
2965 ;; Having this be an expression node makes it more flexible.
2966 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2967 ;; that work better if you assume it's an expression. Whenever we have
2968 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2969 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2970 (defstruct (js2-var-decl-node
2971 (:include js2-node)
2972 (:constructor nil)
2973 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2974 (pos js2-token-beg)
2975 len kids
2976 decl-type)))
2977 "AST node for a variable declaration list (VAR, CONST or LET).
2978 The node bounds differ depending on the declaration type. For VAR or
2979 CONST declarations, the bounds include the var/const keyword. For LET
2980 declarations, the node begins at the position of the first child."
2981 kids ; a Lisp list of `js2-var-init-node' structs.
2982 decl-type) ; js2-VAR, js2-CONST or js2-LET
2983
2984 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2985 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2986
2987 (defun js2-visit-var-decl (n v)
2988 (dolist (kid (js2-var-decl-node-kids n))
2989 (js2-visit-ast kid v)))
2990
2991 (defun js2-print-var-decl (n i)
2992 (let ((pad (js2-make-pad i))
2993 (tt (js2-var-decl-node-decl-type n)))
2994 (insert pad)
2995 (insert (cond
2996 ((= tt js2-VAR) "var ")
2997 ((= tt js2-LET) "let ")
2998 ((= tt js2-CONST) "const ")
2999 (t
3000 (error "malformed var-decl node"))))
3001 (loop with kids = (js2-var-decl-node-kids n)
3002 with len = (length kids)
3003 for kid in kids
3004 for count from 1
3005 do
3006 (js2-print-ast kid 0)
3007 (if (< count len)
3008 (insert ", ")))))
3009
3010 (defstruct (js2-var-init-node
3011 (:include js2-node)
3012 (:constructor nil)
3013 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3014 (pos js2-ts-cursor)
3015 len target
3016 initializer)))
3017 "AST node for a variable declaration.
3018 The type field will be js2-CONST for a const decl."
3019 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3020 initializer) ; initializer expression, a `js2-node'
3021
3022 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3023 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3024
3025 (defun js2-visit-var-init-node (n v)
3026 (js2-visit-ast (js2-var-init-node-target n) v)
3027 (js2-visit-ast (js2-var-init-node-initializer n) v))
3028
3029 (defun js2-print-var-init-node (n i)
3030 (let ((pad (js2-make-pad i))
3031 (name (js2-var-init-node-target n))
3032 (init (js2-var-init-node-initializer n)))
3033 (insert pad)
3034 (js2-print-ast name 0)
3035 (when init
3036 (insert " = ")
3037 (js2-print-ast init 0))))
3038
3039 (defstruct (js2-cond-node
3040 (:include js2-node)
3041 (:constructor nil)
3042 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3043 (pos js2-ts-cursor)
3044 len
3045 test-expr
3046 true-expr
3047 false-expr
3048 q-pos c-pos)))
3049 "AST node for the ternary operator"
3050 test-expr
3051 true-expr
3052 false-expr
3053 q-pos ; buffer position of ?
3054 c-pos) ; buffer position of :
3055
3056 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3057 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3058
3059 (defun js2-visit-cond-node (n v)
3060 (js2-visit-ast (js2-cond-node-test-expr n) v)
3061 (js2-visit-ast (js2-cond-node-true-expr n) v)
3062 (js2-visit-ast (js2-cond-node-false-expr n) v))
3063
3064 (defun js2-print-cond-node (n i)
3065 (let ((pad (js2-make-pad i)))
3066 (insert pad)
3067 (js2-print-ast (js2-cond-node-test-expr n) 0)
3068 (insert " ? ")
3069 (js2-print-ast (js2-cond-node-true-expr n) 0)
3070 (insert " : ")
3071 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3072
3073 (defstruct (js2-infix-node
3074 (:include js2-node)
3075 (:constructor nil)
3076 (:constructor make-js2-infix-node (&key type
3077 (pos js2-ts-cursor)
3078 len op-pos
3079 left right)))
3080 "Represents infix expressions.
3081 Includes assignment ops like `|=', and the comma operator.
3082 The type field inherited from `js2-node' holds the operator."
3083 op-pos ; buffer position where operator begins
3084 left ; any `js2-node'
3085 right) ; any `js2-node'
3086
3087 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3088 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3089
3090 (defun js2-visit-infix-node (n v)
3091 (js2-visit-ast (js2-infix-node-left n) v)
3092 (js2-visit-ast (js2-infix-node-right n) v))
3093
3094 (defconst js2-operator-tokens
3095 (let ((table (make-hash-table :test 'eq))
3096 (tokens
3097 (list (cons js2-IN "in")
3098 (cons js2-TYPEOF "typeof")
3099 (cons js2-INSTANCEOF "instanceof")
3100 (cons js2-DELPROP "delete")
3101 (cons js2-COMMA ",")
3102 (cons js2-COLON ":")
3103 (cons js2-OR "||")
3104 (cons js2-AND "&&")
3105 (cons js2-INC "++")
3106 (cons js2-DEC "--")
3107 (cons js2-BITOR "|")
3108 (cons js2-BITXOR "^")
3109 (cons js2-BITAND "&")
3110 (cons js2-EQ "==")
3111 (cons js2-NE "!=")
3112 (cons js2-LT "<")
3113 (cons js2-LE "<=")
3114 (cons js2-GT ">")
3115 (cons js2-GE ">=")
3116 (cons js2-LSH "<<")
3117 (cons js2-RSH ">>")
3118 (cons js2-URSH ">>>")
3119 (cons js2-ADD "+") ; infix plus
3120 (cons js2-SUB "-") ; infix minus
3121 (cons js2-MUL "*")
3122 (cons js2-DIV "/")
3123 (cons js2-MOD "%")
3124 (cons js2-NOT "!")
3125 (cons js2-BITNOT "~")
3126 (cons js2-POS "+") ; unary plus
3127 (cons js2-NEG "-") ; unary minus
3128 (cons js2-SHEQ "===") ; shallow equality
3129 (cons js2-SHNE "!==") ; shallow inequality
3130 (cons js2-ASSIGN "=")
3131 (cons js2-ASSIGN_BITOR "|=")
3132 (cons js2-ASSIGN_BITXOR "^=")
3133 (cons js2-ASSIGN_BITAND "&=")
3134 (cons js2-ASSIGN_LSH "<<=")
3135 (cons js2-ASSIGN_RSH ">>=")
3136 (cons js2-ASSIGN_URSH ">>>=")
3137 (cons js2-ASSIGN_ADD "+=")
3138 (cons js2-ASSIGN_SUB "-=")
3139 (cons js2-ASSIGN_MUL "*=")
3140 (cons js2-ASSIGN_DIV "/=")
3141 (cons js2-ASSIGN_MOD "%="))))
3142 (loop for (k . v) in tokens do
3143 (puthash k v table))
3144 table))
3145
3146 (defun js2-print-infix-node (n i)
3147 (let* ((tt (js2-node-type n))
3148 (op (gethash tt js2-operator-tokens)))
3149 (unless op
3150 (error "unrecognized infix operator %s" (js2-node-type n)))
3151 (insert (js2-make-pad i))
3152 (js2-print-ast (js2-infix-node-left n) 0)
3153 (unless (= tt js2-COMMA)
3154 (insert " "))
3155 (insert op)
3156 (insert " ")
3157 (js2-print-ast (js2-infix-node-right n) 0)))
3158
3159 (defstruct (js2-assign-node
3160 (:include js2-infix-node)
3161 (:constructor nil)
3162 (:constructor make-js2-assign-node (&key type
3163 (pos js2-ts-cursor)
3164 len op-pos
3165 left right)))
3166 "Represents any assignment.
3167 The type field holds the actual assignment operator.")
3168
3169 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3170 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3171
3172 (defstruct (js2-unary-node
3173 (:include js2-node)
3174 (:constructor nil)
3175 (:constructor make-js2-unary-node (&key type ; required
3176 (pos js2-ts-cursor)
3177 len operand)))
3178 "AST node type for unary operator nodes.
3179 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3180 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3181 property is added if the operator follows the operand."
3182 operand) ; a `js2-node' expression
3183
3184 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3185 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3186
3187 (defun js2-visit-unary-node (n v)
3188 (js2-visit-ast (js2-unary-node-operand n) v))
3189
3190 (defun js2-print-unary-node (n i)
3191 (let* ((tt (js2-node-type n))
3192 (op (gethash tt js2-operator-tokens))
3193 (postfix (js2-node-get-prop n 'postfix)))
3194 (unless op
3195 (error "unrecognized unary operator %s" tt))
3196 (insert (js2-make-pad i))
3197 (unless postfix
3198 (insert op))
3199 (if (or (= tt js2-TYPEOF)
3200 (= tt js2-DELPROP))
3201 (insert " "))
3202 (js2-print-ast (js2-unary-node-operand n) 0)
3203 (when postfix
3204 (insert op))))
3205
3206 (defstruct (js2-let-node
3207 (:include js2-scope)
3208 (:constructor nil)
3209 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3210 (pos js2-token-beg)
3211 len vars body
3212 lp rp)))
3213 "AST node for a let expression or a let statement.
3214 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3215 vars ; a `js2-var-decl-node'
3216 body ; a `js2-node' representing the expression or body block
3217 lp
3218 rp)
3219
3220 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3221 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3222
3223 (defun js2-visit-let-node (n v)
3224 (js2-visit-ast (js2-let-node-vars n) v)
3225 (js2-visit-ast (js2-let-node-body n) v))
3226
3227 (defun js2-print-let-node (n i)
3228 (insert (js2-make-pad i) "let (")
3229 (js2-print-ast (js2-let-node-vars n) 0)
3230 (insert ") ")
3231 (js2-print-ast (js2-let-node-body n) i))
3232
3233 (defstruct (js2-keyword-node
3234 (:include js2-node)
3235 (:constructor nil)
3236 (:constructor make-js2-keyword-node (&key type
3237 (pos js2-token-beg)
3238 (len (- js2-ts-cursor pos)))))
3239 "AST node representing a literal keyword such as `null'.
3240 Used for `null', `this', `true', `false' and `debugger'.
3241 The node type is set to js2-NULL, js2-THIS, etc.")
3242
3243 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3244 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3245
3246 (defun js2-print-keyword-node (n i)
3247 (insert (js2-make-pad i)
3248 (let ((tt (js2-node-type n)))
3249 (cond
3250 ((= tt js2-THIS) "this")
3251 ((= tt js2-NULL) "null")
3252 ((= tt js2-TRUE) "true")
3253 ((= tt js2-FALSE) "false")
3254 ((= tt js2-DEBUGGER) "debugger")
3255 (t (error "Invalid keyword literal type: %d" tt))))))
3256
3257 (defsubst js2-this-node-p (node)
3258 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3259 (eq (js2-node-type node) js2-THIS))
3260
3261 (defstruct (js2-new-node
3262 (:include js2-node)
3263 (:constructor nil)
3264 (:constructor make-js2-new-node (&key (type js2-NEW)
3265 (pos js2-token-beg)
3266 len target
3267 args initializer
3268 lp rp)))
3269 "AST node for new-expression such as new Foo()."
3270 target ; an identifier or reference
3271 args ; a Lisp list of argument nodes
3272 lp ; position of left-paren, nil if omitted
3273 rp ; position of right-paren, nil if omitted
3274 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3275
3276 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3277 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3278
3279 (defun js2-visit-new-node (n v)
3280 (js2-visit-ast (js2-new-node-target n) v)
3281 (dolist (arg (js2-new-node-args n))
3282 (js2-visit-ast arg v))
3283 (js2-visit-ast (js2-new-node-initializer n) v))
3284
3285 (defun js2-print-new-node (n i)
3286 (insert (js2-make-pad i) "new ")
3287 (js2-print-ast (js2-new-node-target n))
3288 (insert "(")
3289 (js2-print-list (js2-new-node-args n))
3290 (insert ")")
3291 (when (js2-new-node-initializer n)
3292 (insert " ")
3293 (js2-print-ast (js2-new-node-initializer n))))
3294
3295 (defstruct (js2-name-node
3296 (:include js2-node)
3297 (:constructor nil)
3298 (:constructor make-js2-name-node (&key (type js2-NAME)
3299 (pos js2-token-beg)
3300 (len (- js2-ts-cursor
3301 js2-token-beg))
3302 (name js2-ts-string))))
3303 "AST node for a JavaScript identifier"
3304 name ; a string
3305 scope) ; a `js2-scope' (optional, used for codegen)
3306
3307 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3308 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3309
3310 (defun js2-print-name-node (n i)
3311 (insert (js2-make-pad i)
3312 (js2-name-node-name n)))
3313
3314 (defsubst js2-name-node-length (node)
3315 "Return identifier length of NODE, a `js2-name-node'.
3316 Returns 0 if NODE is nil or its identifier field is nil."
3317 (if node
3318 (length (js2-name-node-name node))
3319 0))
3320
3321 (defstruct (js2-number-node
3322 (:include js2-node)
3323 (:constructor nil)
3324 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3325 (pos js2-token-beg)
3326 (len (- js2-ts-cursor
3327 js2-token-beg))
3328 (value js2-ts-string)
3329 (num-value js2-ts-number))))
3330 "AST node for a number literal."
3331 value ; the original string, e.g. "6.02e23"
3332 num-value) ; the parsed number value
3333
3334 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3335 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3336
3337 (defun js2-print-number-node (n i)
3338 (insert (js2-make-pad i)
3339 (number-to-string (js2-number-node-num-value n))))
3340
3341 (defstruct (js2-regexp-node
3342 (:include js2-node)
3343 (:constructor nil)
3344 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3345 (pos js2-token-beg)
3346 (len (- js2-ts-cursor
3347 js2-token-beg))
3348 value flags)))
3349 "AST node for a regular expression literal."
3350 value ; the regexp string, without // delimiters
3351 flags) ; a string of flags, e.g. `mi'.
3352
3353 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3354 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3355
3356 (defun js2-print-regexp (n i)
3357 (insert (js2-make-pad i)
3358 "/"
3359 (js2-regexp-node-value n)
3360 "/")
3361 (if (js2-regexp-node-flags n)
3362 (insert (js2-regexp-node-flags n))))
3363
3364 (defstruct (js2-string-node
3365 (:include js2-node)
3366 (:constructor nil)
3367 (:constructor make-js2-string-node (&key (type js2-STRING)
3368 (pos js2-token-beg)
3369 (len (- js2-ts-cursor
3370 js2-token-beg))
3371 (value js2-ts-string))))
3372 "String literal.
3373 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3374 You can tell the quote type by looking at the first character."
3375 value) ; the characters of the string, including the quotes
3376
3377 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3378 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3379
3380 (defun js2-print-string-node (n i)
3381 (insert (js2-make-pad i)
3382 (js2-node-string n)))
3383
3384 (defstruct (js2-array-node
3385 (:include js2-node)
3386 (:constructor nil)
3387 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3388 (pos js2-ts-cursor)
3389 len elems)))
3390 "AST node for an array literal."
3391 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3392
3393 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3394 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3395
3396 (defun js2-visit-array-node (n v)
3397 (dolist (e (js2-array-node-elems n))
3398 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3399
3400 (defun js2-print-array-node (n i)
3401 (insert (js2-make-pad i) "[")
3402 (js2-print-list (js2-array-node-elems n))
3403 (insert "]"))
3404
3405 (defstruct (js2-object-node
3406 (:include js2-node)
3407 (:constructor nil)
3408 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3409 (pos js2-ts-cursor)
3410 len
3411 elems)))
3412 "AST node for an object literal expression.
3413 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3414 The latter represents abbreviation in destructuring expressions."
3415 elems)
3416
3417 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3418 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3419
3420 (defun js2-visit-object-node (n v)
3421 (dolist (e (js2-object-node-elems n))
3422 (js2-visit-ast e v)))
3423
3424 (defun js2-print-object-node (n i)
3425 (insert (js2-make-pad i) "{")
3426 (js2-print-list (js2-object-node-elems n))
3427 (insert "}"))
3428
3429 (defstruct (js2-object-prop-node
3430 (:include js2-infix-node)
3431 (:constructor nil)
3432 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3433 (pos js2-ts-cursor)
3434 len left
3435 right op-pos)))
3436 "AST node for an object literal prop:value entry.
3437 The `left' field is the property: a name node, string node or number node.
3438 The `right' field is a `js2-node' representing the initializer value.")
3439
3440 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3441 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3442
3443 (defun js2-print-object-prop-node (n i)
3444 (insert (js2-make-pad i))
3445 (js2-print-ast (js2-object-prop-node-left n) 0)
3446 (insert ": ")
3447 (js2-print-ast (js2-object-prop-node-right n) 0))
3448
3449 (defstruct (js2-getter-setter-node
3450 (:include js2-infix-node)
3451 (:constructor nil)
3452 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3453 (pos js2-ts-cursor)
3454 len left right)))
3455 "AST node for a getter/setter property in an object literal.
3456 The `left' field is the `js2-name-node' naming the getter/setter prop.
3457 The `right' field is always an anonymous `js2-function-node' with a node
3458 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3459
3460 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3461 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3462
3463 (defun js2-print-getter-setter (n i)
3464 (let ((pad (js2-make-pad i))
3465 (left (js2-getter-setter-node-left n))
3466 (right (js2-getter-setter-node-right n)))
3467 (insert pad)
3468 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3469 (js2-print-ast left 0)
3470 (js2-print-ast right 0)))
3471
3472 (defstruct (js2-prop-get-node
3473 (:include js2-infix-node)
3474 (:constructor nil)
3475 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3476 (pos js2-ts-cursor)
3477 len left right)))
3478 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3479
3480 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3481 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3482
3483 (defun js2-visit-prop-get-node (n v)
3484 (js2-visit-ast (js2-prop-get-node-left n) v)
3485 (js2-visit-ast (js2-prop-get-node-right n) v))
3486
3487 (defun js2-print-prop-get-node (n i)
3488 (insert (js2-make-pad i))
3489 (js2-print-ast (js2-prop-get-node-left n) 0)
3490 (insert ".")
3491 (js2-print-ast (js2-prop-get-node-right n) 0))
3492
3493 (defstruct (js2-elem-get-node
3494 (:include js2-node)
3495 (:constructor nil)
3496 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3497 (pos js2-ts-cursor)
3498 len target element
3499 lb rb)))
3500 "AST node for an array index expression such as foo[bar]."
3501 target ; a `js2-node' - the expression preceding the "."
3502 element ; a `js2-node' - the expression in brackets
3503 lb ; position of left-bracket, nil if omitted
3504 rb) ; position of right-bracket, nil if omitted
3505
3506 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3507 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3508
3509 (defun js2-visit-elem-get-node (n v)
3510 (js2-visit-ast (js2-elem-get-node-target n) v)
3511 (js2-visit-ast (js2-elem-get-node-element n) v))
3512
3513 (defun js2-print-elem-get-node (n i)
3514 (insert (js2-make-pad i))
3515 (js2-print-ast (js2-elem-get-node-target n) 0)
3516 (insert "[")
3517 (js2-print-ast (js2-elem-get-node-element n) 0)
3518 (insert "]"))
3519
3520 (defstruct (js2-call-node
3521 (:include js2-node)
3522 (:constructor nil)
3523 (:constructor make-js2-call-node (&key (type js2-CALL)
3524 (pos js2-ts-cursor)
3525 len target args
3526 lp rp)))
3527 "AST node for a JavaScript function call."
3528 target ; a `js2-node' evaluating to the function to call
3529 args ; a Lisp list of `js2-node' arguments
3530 lp ; position of open-paren, or nil if missing
3531 rp) ; position of close-paren, or nil if missing
3532
3533 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3534 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3535
3536 (defun js2-visit-call-node (n v)
3537 (js2-visit-ast (js2-call-node-target n) v)
3538 (dolist (arg (js2-call-node-args n))
3539 (js2-visit-ast arg v)))
3540
3541 (defun js2-print-call-node (n i)
3542 (insert (js2-make-pad i))
3543 (js2-print-ast (js2-call-node-target n) 0)
3544 (insert "(")
3545 (js2-print-list (js2-call-node-args n))
3546 (insert ")"))
3547
3548 (defstruct (js2-yield-node
3549 (:include js2-node)
3550 (:constructor nil)
3551 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3552 (pos js2-ts-cursor)
3553 len value)))
3554 "AST node for yield statement or expression."
3555 value) ; optional: value to be yielded
3556
3557 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3558 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3559
3560 (defun js2-visit-yield-node (n v)
3561 (js2-visit-ast (js2-yield-node-value n) v))
3562
3563 (defun js2-print-yield-node (n i)
3564 (insert (js2-make-pad i))
3565 (insert "yield")
3566 (when (js2-yield-node-value n)
3567 (insert " ")
3568 (js2-print-ast (js2-yield-node-value n) 0)))
3569
3570 (defstruct (js2-paren-node
3571 (:include js2-node)
3572 (:constructor nil)
3573 (:constructor make-js2-paren-node (&key (type js2-LP)
3574 (pos js2-ts-cursor)
3575 len expr)))
3576 "AST node for a parenthesized expression.
3577 In particular, used when the parens are syntactically optional,
3578 as opposed to required parens such as those enclosing an if-conditional."
3579 expr) ; `js2-node'
3580
3581 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3582 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3583
3584 (defun js2-visit-paren-node (n v)
3585 (js2-visit-ast (js2-paren-node-expr n) v))
3586
3587 (defun js2-print-paren-node (n i)
3588 (insert (js2-make-pad i))
3589 (insert "(")
3590 (js2-print-ast (js2-paren-node-expr n) 0)
3591 (insert ")"))
3592
3593 (defstruct (js2-array-comp-node
3594 (:include js2-scope)
3595 (:constructor nil)
3596 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3597 (pos js2-ts-cursor)
3598 len result
3599 loops filter
3600 if-pos lp rp)))
3601 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3602 result ; result expression (just after left-bracket)
3603 loops ; a Lisp list of `js2-array-comp-loop-node'
3604 filter ; guard/filter expression
3605 if-pos ; buffer pos of 'if' keyword, if present, else nil
3606 lp ; buffer position of if-guard left-paren, or nil if not present
3607 rp) ; buffer position of if-guard right-paren, or nil if not present
3608
3609 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3610 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3611
3612 (defun js2-visit-array-comp-node (n v)
3613 (js2-visit-ast (js2-array-comp-node-result n) v)
3614 (dolist (l (js2-array-comp-node-loops n))
3615 (js2-visit-ast l v))
3616 (js2-visit-ast (js2-array-comp-node-filter n) v))
3617
3618 (defun js2-print-array-comp-node (n i)
3619 (let ((pad (js2-make-pad i))
3620 (result (js2-array-comp-node-result n))
3621 (loops (js2-array-comp-node-loops n))
3622 (filter (js2-array-comp-node-filter n)))
3623 (insert pad "[")
3624 (js2-print-ast result 0)
3625 (dolist (l loops)
3626 (insert " ")
3627 (js2-print-ast l 0))
3628 (when filter
3629 (insert " if (")
3630 (js2-print-ast filter 0)
3631 (insert ")"))
3632 (insert "]")))
3633
3634 (defstruct (js2-array-comp-loop-node
3635 (:include js2-for-in-node)
3636 (:constructor nil)
3637 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3638 (pos js2-ts-cursor)
3639 len iterator
3640 object in-pos
3641 foreach-p
3642 each-pos
3643 forof-p
3644 lp rp)))
3645 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3646
3647 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3648 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3649
3650 (defun js2-visit-array-comp-loop (n v)
3651 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3652 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3653
3654 (defun js2-print-array-comp-loop (n i)
3655 (insert "for ")
3656 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3657 (insert "(")
3658 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3659 (if (js2-array-comp-loop-node-forof-p n)
3660 (insert " of ")
3661 (insert " in "))
3662 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3663 (insert ")"))
3664
3665 (defstruct (js2-empty-expr-node
3666 (:include js2-node)
3667 (:constructor nil)
3668 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3669 (pos js2-token-beg)
3670 len)))
3671 "AST node for an empty expression.")
3672
3673 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3674 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3675
3676 (defstruct (js2-xml-node
3677 (:include js2-block-node)
3678 (:constructor nil)
3679 (:constructor make-js2-xml-node (&key (type js2-XML)
3680 (pos js2-token-beg)
3681 len kids)))
3682 "AST node for initial parse of E4X literals.
3683 The kids field is a list of XML fragments, each a `js2-string-node' or
3684 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3685
3686 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3687 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3688
3689 (defun js2-print-xml-node (n i)
3690 (dolist (kid (js2-xml-node-kids n))
3691 (js2-print-ast kid i)))
3692
3693 (defstruct (js2-xml-js-expr-node
3694 (:include js2-xml-node)
3695 (:constructor nil)
3696 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3697 (pos js2-ts-cursor)
3698 len expr)))
3699 "AST node for an embedded JavaScript {expression} in an E4X literal.
3700 The start and end fields correspond to the curly-braces."
3701 expr) ; a `js2-expr-node' of some sort
3702
3703 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3704 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3705
3706 (defun js2-visit-xml-js-expr (n v)
3707 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3708
3709 (defun js2-print-xml-js-expr (n i)
3710 (insert (js2-make-pad i))
3711 (insert "{")
3712 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3713 (insert "}"))
3714
3715 (defstruct (js2-xml-dot-query-node
3716 (:include js2-infix-node)
3717 (:constructor nil)
3718 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3719 (pos js2-ts-cursor)
3720 op-pos len left
3721 right rp)))
3722 "AST node for an E4X foo.(bar) filter expression.
3723 Note that the left-paren is automatically the character immediately
3724 following the dot (.) in the operator. No whitespace is permitted
3725 between the dot and the lp by the scanner."
3726 rp)
3727
3728 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3729 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3730
3731 (defun js2-print-xml-dot-query (n i)
3732 (insert (js2-make-pad i))
3733 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3734 (insert ".(")
3735 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3736 (insert ")"))
3737
3738 (defstruct (js2-xml-ref-node
3739 (:include js2-node)
3740 (:constructor nil)) ; abstract
3741 "Base type for E4X XML attribute-access or property-get expressions.
3742 Such expressions can take a variety of forms. The general syntax has
3743 three parts:
3744
3745 - (optional) an @ (specifying an attribute access)
3746 - (optional) a namespace (a `js2-name-node') and double-colon
3747 - (required) either a `js2-name-node' or a bracketed [expression]
3748
3749 The property-name expressions (examples: ns::name, @name) are
3750 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3751 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3752
3753 This node type (or more specifically, its subclasses) will sometimes
3754 be the right-hand child of a `js2-prop-get-node' or a
3755 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3756 The `js2-xml-ref-node' may also be a standalone primary expression with
3757 no explicit target, which is valid in certain expression contexts such as
3758
3759 company..employee.(@id < 100)
3760
3761 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3762 expression whose parent is a `js2-xml-dot-query-node'."
3763 namespace
3764 at-pos
3765 colon-pos)
3766
3767 (defsubst js2-xml-ref-node-attr-access-p (node)
3768 "Return non-nil if this expression began with an @-token."
3769 (and (numberp (js2-xml-ref-node-at-pos node))
3770 (plusp (js2-xml-ref-node-at-pos node))))
3771
3772 (defstruct (js2-xml-prop-ref-node
3773 (:include js2-xml-ref-node)
3774 (:constructor nil)
3775 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3776 (pos js2-token-beg)
3777 len propname
3778 namespace at-pos
3779 colon-pos)))
3780 "AST node for an E4X XML [expr] property-ref expression.
3781 The JavaScript syntax is an optional @, an optional ns::, and a name.
3782
3783 [ '@' ] [ name '::' ] name
3784
3785 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3786 @ns::*, @*::attr, @*::*, and @*.
3787
3788 The node starts at the @ token, if present. Otherwise it starts at the
3789 namespace name. The node bounds extend through the closing right-bracket,
3790 or if it is missing due to a syntax error, through the end of the index
3791 expression."
3792 propname)
3793
3794 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3795 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3796
3797 (defun js2-visit-xml-prop-ref-node (n v)
3798 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3799 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3800
3801 (defun js2-print-xml-prop-ref-node (n i)
3802 (insert (js2-make-pad i))
3803 (if (js2-xml-ref-node-attr-access-p n)
3804 (insert "@"))
3805 (when (js2-xml-prop-ref-node-namespace n)
3806 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3807 (insert "::"))
3808 (if (js2-xml-prop-ref-node-propname n)
3809 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3810
3811 (defstruct (js2-xml-elem-ref-node
3812 (:include js2-xml-ref-node)
3813 (:constructor nil)
3814 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3815 (pos js2-token-beg)
3816 len expr lb rb
3817 namespace at-pos
3818 colon-pos)))
3819 "AST node for an E4X XML [expr] member-ref expression.
3820 Syntax:
3821
3822 [ '@' ] [ name '::' ] '[' expr ']'
3823
3824 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3825
3826 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3827 is not a legal E4X XML element-ref expression, since it's already used
3828 for standard JavaScript element-get array indexing. Hence, a
3829 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3830 non-nil namespace node, or both.
3831
3832 The node starts at the @ token, if present. Otherwise it starts
3833 at the namespace name. The node bounds extend through the closing
3834 right-bracket, or if it is missing due to a syntax error, through the
3835 end of the index expression."
3836 expr ; the bracketed index expression
3837 lb
3838 rb)
3839
3840 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3841 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3842
3843 (defun js2-visit-xml-elem-ref-node (n v)
3844 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3845 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3846
3847 (defun js2-print-xml-elem-ref-node (n i)
3848 (insert (js2-make-pad i))
3849 (if (js2-xml-ref-node-attr-access-p n)
3850 (insert "@"))
3851 (when (js2-xml-elem-ref-node-namespace n)
3852 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3853 (insert "::"))
3854 (insert "[")
3855 (if (js2-xml-elem-ref-node-expr n)
3856 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3857 (insert "]"))
3858
3859 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3860
3861 (defstruct (js2-xml-start-tag-node
3862 (:include js2-xml-node)
3863 (:constructor nil)
3864 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3865 (pos js2-ts-cursor)
3866 len name attrs kids
3867 empty-p)))
3868 "AST node for an XML start-tag. Not currently used.
3869 The `kids' field is a Lisp list of child content nodes."
3870 name ; a `js2-xml-name-node'
3871 attrs ; a Lisp list of `js2-xml-attr-node'
3872 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3873
3874 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3875 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3876
3877 (defun js2-visit-xml-start-tag (n v)
3878 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3879 (dolist (attr (js2-xml-start-tag-node-attrs n))
3880 (js2-visit-ast attr v))
3881 (js2-visit-block n v))
3882
3883 (defun js2-print-xml-start-tag (n i)
3884 (insert (js2-make-pad i) "<")
3885 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3886 (when (js2-xml-start-tag-node-attrs n)
3887 (insert " ")
3888 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3889 (insert ">"))
3890
3891 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3892 ;; and add the end-tag to the kids list of the parent as well.
3893 (defstruct (js2-xml-end-tag-node
3894 (:include js2-xml-node)
3895 (:constructor nil)
3896 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3897 (pos js2-ts-cursor)
3898 len name)))
3899 "AST node for an XML end-tag. Not currently used."
3900 name) ; a `js2-xml-name-node'
3901
3902 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3903 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3904
3905 (defun js2-visit-xml-end-tag (n v)
3906 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3907
3908 (defun js2-print-xml-end-tag (n i)
3909 (insert (js2-make-pad i))
3910 (insert "</")
3911 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3912 (insert ">"))
3913
3914 (defstruct (js2-xml-name-node
3915 (:include js2-xml-node)
3916 (:constructor nil)
3917 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3918 (pos js2-ts-cursor)
3919 len namespace kids)))
3920 "AST node for an E4X XML name. Not currently used.
3921 Any XML name can be qualified with a namespace, hence the namespace field.
3922 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3923 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3924 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3925 namespace) ; a `js2-string-node'
3926
3927 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3928 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3929
3930 (defun js2-visit-xml-name-node (n v)
3931 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3932
3933 (defun js2-print-xml-name-node (n i)
3934 (insert (js2-make-pad i))
3935 (when (js2-xml-name-node-namespace n)
3936 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3937 (insert "::"))
3938 (dolist (kid (js2-xml-name-node-kids n))
3939 (js2-print-ast kid 0)))
3940
3941 (defstruct (js2-xml-pi-node
3942 (:include js2-xml-node)
3943 (:constructor nil)
3944 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3945 (pos js2-ts-cursor)
3946 len name attrs)))
3947 "AST node for an E4X XML processing instruction. Not currently used."
3948 name ; a `js2-xml-name-node'
3949 attrs) ; a list of `js2-xml-attr-node'
3950
3951 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3952 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3953
3954 (defun js2-visit-xml-pi-node (n v)
3955 (js2-visit-ast (js2-xml-pi-node-name n) v)
3956 (dolist (attr (js2-xml-pi-node-attrs n))
3957 (js2-visit-ast attr v)))
3958
3959 (defun js2-print-xml-pi-node (n i)
3960 (insert (js2-make-pad i) "<?")
3961 (js2-print-ast (js2-xml-pi-node-name n))
3962 (when (js2-xml-pi-node-attrs n)
3963 (insert " ")
3964 (js2-print-list (js2-xml-pi-node-attrs n)))
3965 (insert "?>"))
3966
3967 (defstruct (js2-xml-cdata-node
3968 (:include js2-xml-node)
3969 (:constructor nil)
3970 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3971 (pos js2-ts-cursor)
3972 len content)))
3973 "AST node for a CDATA escape section. Not currently used."
3974 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3975
3976 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3977 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3978
3979 (defun js2-visit-xml-cdata-node (n v)
3980 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3981
3982 (defun js2-print-xml-cdata-node (n i)
3983 (insert (js2-make-pad i))
3984 (js2-print-ast (js2-xml-cdata-node-content n)))
3985
3986 (defstruct (js2-xml-attr-node
3987 (:include js2-xml-node)
3988 (:constructor nil)
3989 (:constructor make-js2-attr-node (&key (type js2-XML)
3990 (pos js2-ts-cursor)
3991 len name value
3992 eq-pos quote-type)))
3993 "AST node representing a foo='bar' XML attribute value. Not yet used."
3994 name ; a `js2-xml-name-node'
3995 value ; a `js2-xml-name-node'
3996 eq-pos ; buffer position of "=" sign
3997 quote-type) ; 'single or 'double
3998
3999 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4000 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4001
4002 (defun js2-visit-xml-attr-node (n v)
4003 (js2-visit-ast (js2-xml-attr-node-name n) v)
4004 (js2-visit-ast (js2-xml-attr-node-value n) v))
4005
4006 (defun js2-print-xml-attr-node (n i)
4007 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4008 "'"
4009 "\"")))
4010 (insert (js2-make-pad i))
4011 (js2-print-ast (js2-xml-attr-node-name n) 0)
4012 (insert "=" quote)
4013 (js2-print-ast (js2-xml-attr-node-value n) 0)
4014 (insert quote)))
4015
4016 (defstruct (js2-xml-text-node
4017 (:include js2-xml-node)
4018 (:constructor nil)
4019 (:constructor make-js2-text-node (&key (type js2-XML)
4020 (pos js2-ts-cursor)
4021 len content)))
4022 "AST node for an E4X XML text node. Not currently used."
4023 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4024
4025 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4026 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4027
4028 (defun js2-visit-xml-text-node (n v)
4029 (js2-visit-ast (js2-xml-text-node-content n) v))
4030
4031 (defun js2-print-xml-text-node (n i)
4032 (insert (js2-make-pad i))
4033 (dolist (kid (js2-xml-text-node-content n))
4034 (js2-print-ast kid)))
4035
4036 (defstruct (js2-xml-comment-node
4037 (:include js2-xml-node)
4038 (:constructor nil)
4039 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4040 (pos js2-ts-cursor)
4041 len)))
4042 "AST node for E4X XML comment. Not currently used.")
4043
4044 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4045 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4046
4047 (defun js2-print-xml-comment (n i)
4048 (insert (js2-make-pad i)
4049 (js2-node-string n)))
4050
4051 ;;; Node utilities
4052
4053 (defsubst js2-node-line (n)
4054 "Fetch the source line number at the start of node N.
4055 This is O(n) in the length of the source buffer; use prudently."
4056 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4057
4058 (defsubst js2-block-node-kid (n i)
4059 "Return child I of node N, or nil if there aren't that many."
4060 (nth i (js2-block-node-kids n)))
4061
4062 (defsubst js2-block-node-first (n)
4063 "Return first child of block node N, or nil if there is none."
4064 (first (js2-block-node-kids n)))
4065
4066 (defun js2-node-root (n)
4067 "Return the root of the AST containing N.
4068 If N has no parent pointer, returns N."
4069 (let ((parent (js2-node-parent n)))
4070 (if parent
4071 (js2-node-root parent)
4072 n)))
4073
4074 (defun js2-node-position-in-parent (node &optional parent)
4075 "Return the position of NODE in parent's block-kids list.
4076 PARENT can be supplied if known. Positioned returned is zero-indexed.
4077 Returns 0 if NODE is not a child of a block statement, or if NODE
4078 is not a statement node."
4079 (let ((p (or parent (js2-node-parent node)))
4080 (i 0))
4081 (if (not (js2-block-node-p p))
4082 i
4083 (or (js2-position node (js2-block-node-kids p))
4084 0))))
4085
4086 (defsubst js2-node-short-name (n)
4087 "Return the short name of node N as a string, e.g. `js2-if-node'."
4088 (substring (symbol-name (aref n 0))
4089 (length "cl-struct-")))
4090
4091 (defun js2-node-child-list (node)
4092 "Return the child list for NODE, a Lisp list of nodes.
4093 Works for block nodes, array nodes, obj literals, funarg lists,
4094 var decls and try nodes (for catch clauses). Note that you should call
4095 `js2-block-node-kids' on the function body for the body statements.
4096 Returns nil for zero-length child lists or unsupported nodes."
4097 (cond
4098 ((js2-function-node-p node)
4099 (js2-function-node-params node))
4100 ((js2-block-node-p node)
4101 (js2-block-node-kids node))
4102 ((js2-try-node-p node)
4103 (js2-try-node-catch-clauses node))
4104 ((js2-array-node-p node)
4105 (js2-array-node-elems node))
4106 ((js2-object-node-p node)
4107 (js2-object-node-elems node))
4108 ((js2-call-node-p node)
4109 (js2-call-node-args node))
4110 ((js2-new-node-p node)
4111 (js2-new-node-args node))
4112 ((js2-var-decl-node-p node)
4113 (js2-var-decl-node-kids node))
4114 (t
4115 nil)))
4116
4117 (defun js2-node-set-child-list (node kids)
4118 "Set the child list for NODE to KIDS."
4119 (cond
4120 ((js2-function-node-p node)
4121 (setf (js2-function-node-params node) kids))
4122 ((js2-block-node-p node)
4123 (setf (js2-block-node-kids node) kids))
4124 ((js2-try-node-p node)
4125 (setf (js2-try-node-catch-clauses node) kids))
4126 ((js2-array-node-p node)
4127 (setf (js2-array-node-elems node) kids))
4128 ((js2-object-node-p node)
4129 (setf (js2-object-node-elems node) kids))
4130 ((js2-call-node-p node)
4131 (setf (js2-call-node-args node) kids))
4132 ((js2-new-node-p node)
4133 (setf (js2-new-node-args node) kids))
4134 ((js2-var-decl-node-p node)
4135 (setf (js2-var-decl-node-kids node) kids))
4136 (t
4137 (error "Unsupported node type: %s" (js2-node-short-name node))))
4138 kids)
4139
4140 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4141 (defconst js2-paren-expr-nodes
4142 '(cl-struct-js2-array-comp-loop-node
4143 cl-struct-js2-array-comp-node
4144 cl-struct-js2-call-node
4145 cl-struct-js2-catch-node
4146 cl-struct-js2-do-node
4147 cl-struct-js2-elem-get-node
4148 cl-struct-js2-for-in-node
4149 cl-struct-js2-for-node
4150 cl-struct-js2-function-node
4151 cl-struct-js2-if-node
4152 cl-struct-js2-let-node
4153 cl-struct-js2-new-node
4154 cl-struct-js2-paren-node
4155 cl-struct-js2-switch-node
4156 cl-struct-js2-while-node
4157 cl-struct-js2-with-node
4158 cl-struct-js2-xml-dot-query-node)
4159 "Node types that can have a parenthesized child expression.
4160 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4161
4162 (defsubst js2-paren-expr-node-p (node)
4163 "Return t for nodes that typically have a parenthesized child expression.
4164 Useful for computing the indentation anchors for arg-lists and conditions.
4165 Note that it may return a false positive, for instance when NODE is
4166 a `js2-new-node' and there are no arguments or parentheses."
4167 (memq (aref node 0) js2-paren-expr-nodes))
4168
4169 ;; Fake polymorphism... yech.
4170 (defun js2-node-lp (node)
4171 "Return relative left-paren position for NODE, if applicable.
4172 For `js2-elem-get-node' structs, returns left-bracket position.
4173 Note that the position may be nil in the case of a parse error."
4174 (cond
4175 ((js2-elem-get-node-p node)
4176 (js2-elem-get-node-lb node))
4177 ((js2-loop-node-p node)
4178 (js2-loop-node-lp node))
4179 ((js2-function-node-p node)
4180 (js2-function-node-lp node))
4181 ((js2-if-node-p node)
4182 (js2-if-node-lp node))
4183 ((js2-new-node-p node)
4184 (js2-new-node-lp node))
4185 ((js2-call-node-p node)
4186 (js2-call-node-lp node))
4187 ((js2-paren-node-p node)
4188 (js2-node-pos node))
4189 ((js2-switch-node-p node)
4190 (js2-switch-node-lp node))
4191 ((js2-catch-node-p node)
4192 (js2-catch-node-lp node))
4193 ((js2-let-node-p node)
4194 (js2-let-node-lp node))
4195 ((js2-array-comp-node-p node)
4196 (js2-array-comp-node-lp node))
4197 ((js2-with-node-p node)
4198 (js2-with-node-lp node))
4199 ((js2-xml-dot-query-node-p node)
4200 (1+ (js2-infix-node-op-pos node)))
4201 (t
4202 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4203
4204 ;; Fake polymorphism... blech.
4205 (defun js2-node-rp (node)
4206 "Return relative right-paren position for NODE, if applicable.
4207 For `js2-elem-get-node' structs, returns right-bracket position.
4208 Note that the position may be nil in the case of a parse error."
4209 (cond
4210 ((js2-elem-get-node-p node)
4211 (js2-elem-get-node-rb node))
4212 ((js2-loop-node-p node)
4213 (js2-loop-node-rp node))
4214 ((js2-function-node-p node)
4215 (js2-function-node-rp node))
4216 ((js2-if-node-p node)
4217 (js2-if-node-rp node))
4218 ((js2-new-node-p node)
4219 (js2-new-node-rp node))
4220 ((js2-call-node-p node)
4221 (js2-call-node-rp node))
4222 ((js2-paren-node-p node)
4223 (+ (js2-node-pos node) (js2-node-len node)))
4224 ((js2-switch-node-p node)
4225 (js2-switch-node-rp node))
4226 ((js2-catch-node-p node)
4227 (js2-catch-node-rp node))
4228 ((js2-let-node-p node)
4229 (js2-let-node-rp node))
4230 ((js2-array-comp-node-p node)
4231 (js2-array-comp-node-rp node))
4232 ((js2-with-node-p node)
4233 (js2-with-node-rp node))
4234 ((js2-xml-dot-query-node-p node)
4235 (1+ (js2-xml-dot-query-node-rp node)))
4236 (t
4237 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4238
4239 (defsubst js2-node-first-child (node)
4240 "Return the first element of `js2-node-child-list' for NODE."
4241 (car (js2-node-child-list node)))
4242
4243 (defsubst js2-node-last-child (node)
4244 "Return the last element of `js2-node-last-child' for NODE."
4245 (car (last (js2-node-child-list node))))
4246
4247 (defun js2-node-prev-sibling (node)
4248 "Return the previous statement in parent.
4249 Works for parents supported by `js2-node-child-list'.
4250 Returns nil if NODE is not in the parent, or PARENT is
4251 not a supported node, or if NODE is the first child."
4252 (let* ((p (js2-node-parent node))
4253 (kids (js2-node-child-list p))
4254 (sib (car kids)))
4255 (while (and kids
4256 (not (eq node (cadr kids))))
4257 (setq kids (cdr kids)
4258 sib (car kids)))
4259 sib))
4260
4261 (defun js2-node-next-sibling (node)
4262 "Return the next statement in parent block.
4263 Returns nil if NODE is not in the block, or PARENT is not
4264 a block node, or if NODE is the last statement."
4265 (let* ((p (js2-node-parent node))
4266 (kids (js2-node-child-list p)))
4267 (while (and kids
4268 (not (eq node (car kids))))
4269 (setq kids (cdr kids)))
4270 (cadr kids)))
4271
4272 (defun js2-node-find-child-before (pos parent &optional after)
4273 "Find the last child that starts before POS in parent.
4274 If AFTER is non-nil, returns first child starting after POS.
4275 POS is an absolute buffer position. PARENT is any node
4276 supported by `js2-node-child-list'.
4277 Returns nil if no applicable child is found."
4278 (let ((kids (if (js2-function-node-p parent)
4279 (js2-block-node-kids (js2-function-node-body parent))
4280 (js2-node-child-list parent)))
4281 (beg (if (js2-function-node-p parent)
4282 (js2-node-abs-pos (js2-function-node-body parent))
4283 (js2-node-abs-pos parent)))
4284 kid result fn
4285 (continue t))
4286 (setq fn (if after '>= '<))
4287 (while (and kids continue)
4288 (setq kid (car kids))
4289 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4290 (setq result kid
4291 continue (if after nil t))
4292 (setq continue (if after t nil)))
4293 (setq kids (cdr kids)))
4294 result))
4295
4296 (defun js2-node-find-child-after (pos parent)
4297 "Find first child that starts after POS in parent.
4298 POS is an absolute buffer position. PARENT is any node
4299 supported by `js2-node-child-list'.
4300 Returns nil if no applicable child is found."
4301 (js2-node-find-child-before pos parent 'after))
4302
4303 (defun js2-node-replace-child (pos parent new-node)
4304 "Replace node at index POS in PARENT with NEW-NODE.
4305 Only works for parents supported by `js2-node-child-list'."
4306 (let ((kids (js2-node-child-list parent))
4307 (i 0))
4308 (while (< i pos)
4309 (setq kids (cdr kids)
4310 i (1+ i)))
4311 (setcar kids new-node)
4312 (js2-node-add-children parent new-node)))
4313
4314 (defun js2-node-buffer (n)
4315 "Return the buffer associated with AST N.
4316 Returns nil if the buffer is not set as a property on the root
4317 node, or if parent links were not recorded during parsing."
4318 (let ((root (js2-node-root n)))
4319 (and root
4320 (js2-ast-root-p root)
4321 (js2-ast-root-buffer root))))
4322
4323 (defun js2-block-node-push (n kid)
4324 "Push js2-node KID onto the end of js2-block-node N's child list.
4325 KID is always added to the -end- of the kids list.
4326 Function also calls `js2-node-add-children' to add the parent link."
4327 (let ((kids (js2-node-child-list n)))
4328 (if kids
4329 (setcdr kids (nconc (cdr kids) (list kid)))
4330 (js2-node-set-child-list n (list kid)))
4331 (js2-node-add-children n kid)))
4332
4333 (defun js2-node-string (node)
4334 (with-current-buffer (or (js2-node-buffer node)
4335 (error "No buffer available for node %s" node))
4336 (let ((pos (js2-node-abs-pos node)))
4337 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4338
4339 ;; Container for storing the node we're looking for in a traversal.
4340 (js2-deflocal js2-discovered-node nil)
4341
4342 ;; Keep track of absolute node position during traversals.
4343 (js2-deflocal js2-visitor-offset nil)
4344
4345 (js2-deflocal js2-node-search-point nil)
4346
4347 (when js2-mode-dev-mode-p
4348 (defun js2-find-node-at-point ()
4349 (interactive)
4350 (let ((node (js2-node-at-point)))
4351 (message "%s" (or node "No node found at point"))))
4352 (defun js2-node-name-at-point ()
4353 (interactive)
4354 (let ((node (js2-node-at-point)))
4355 (message "%s" (if node
4356 (js2-node-short-name node)
4357 "No node found at point.")))))
4358
4359 (defun js2-node-at-point (&optional pos skip-comments)
4360 "Return AST node at POS, a buffer position, defaulting to current point.
4361 The `js2-mode-ast' variable must be set to the current parse tree.
4362 Signals an error if the AST (`js2-mode-ast') is nil.
4363 Always returns a node - if it can't find one, it returns the root.
4364 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4365 (let ((ast js2-mode-ast)
4366 result)
4367 (unless ast
4368 (error "No JavaScript AST available"))
4369 ;; Look through comments first, since they may be inside nodes that
4370 ;; would otherwise report a match.
4371 (setq pos (or pos (point))
4372 result (if (> pos (js2-node-abs-end ast))
4373 ast
4374 (if (not skip-comments)
4375 (js2-comment-at-point pos))))
4376 (unless result
4377 (setq js2-discovered-node nil
4378 js2-visitor-offset 0
4379 js2-node-search-point pos)
4380 (unwind-protect
4381 (catch 'js2-visit-done
4382 (js2-visit-ast ast #'js2-node-at-point-visitor))
4383 (setq js2-visitor-offset nil
4384 js2-node-search-point nil))
4385 (setq result js2-discovered-node))
4386 ;; may have found a comment beyond end of last child node,
4387 ;; since visiting the ast-root looks at the comment-list last.
4388 (if (and skip-comments
4389 (js2-comment-node-p result))
4390 (setq result nil))
4391 (or result js2-mode-ast)))
4392
4393 (defun js2-node-at-point-visitor (node end-p)
4394 (let ((rel-pos (js2-node-pos node))
4395 abs-pos
4396 abs-end
4397 (point js2-node-search-point))
4398 (cond
4399 (end-p
4400 ;; this evaluates to a non-nil return value, even if it's zero
4401 (decf js2-visitor-offset rel-pos))
4402 ;; we already looked for comments before visiting, and don't want them now
4403 ((js2-comment-node-p node)
4404 nil)
4405 (t
4406 (setq abs-pos (incf js2-visitor-offset rel-pos)
4407 ;; we only want to use the node if the point is before
4408 ;; the last character position in the node, so we decrement
4409 ;; the absolute end by 1.
4410 abs-end (+ abs-pos (js2-node-len node) -1))
4411 (cond
4412 ;; If this node starts after search-point, stop the search.
4413 ((> abs-pos point)
4414 (throw 'js2-visit-done nil))
4415 ;; If this node ends before the search-point, don't check kids.
4416 ((> point abs-end)
4417 nil)
4418 (t
4419 ;; Otherwise point is within this node, possibly in a child.
4420 (setq js2-discovered-node node)
4421 t)))))) ; keep processing kids to look for more specific match
4422
4423 (defsubst js2-block-comment-p (node)
4424 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4425 (and (js2-comment-node-p node)
4426 (memq (js2-comment-node-format node) '(jsdoc block))))
4427
4428 ;; TODO: put the comments in a vector and binary-search them instead
4429 (defun js2-comment-at-point (&optional pos)
4430 "Look through scanned comment nodes for one containing POS.
4431 POS is a buffer position that defaults to current point.
4432 Function returns nil if POS was not in any comment node."
4433 (let ((ast js2-mode-ast)
4434 (x (or pos (point)))
4435 beg end)
4436 (unless ast
4437 (error "No JavaScript AST available"))
4438 (catch 'done
4439 ;; Comments are stored in lexical order.
4440 (dolist (comment (js2-ast-root-comments ast) nil)
4441 (setq beg (js2-node-abs-pos comment)
4442 end (+ beg (js2-node-len comment)))
4443 (if (and (>= x beg)
4444 (<= x end))
4445 (throw 'done comment))))))
4446
4447 (defun js2-mode-find-parent-fn (node)
4448 "Find function enclosing NODE.
4449 Returns nil if NODE is not inside a function."
4450 (setq node (js2-node-parent node))
4451 (while (and node (not (js2-function-node-p node)))
4452 (setq node (js2-node-parent node)))
4453 (and (js2-function-node-p node) node))
4454
4455 (defun js2-mode-find-enclosing-fn (node)
4456 "Find function or root enclosing NODE."
4457 (if (js2-ast-root-p node)
4458 node
4459 (setq node (js2-node-parent node))
4460 (while (not (or (js2-ast-root-p node)
4461 (js2-function-node-p node)))
4462 (setq node (js2-node-parent node)))
4463 node))
4464
4465 (defun js2-mode-find-enclosing-node (beg end)
4466 "Find script or function fully enclosing BEG and END."
4467 (let ((node (js2-node-at-point beg))
4468 pos
4469 (continue t))
4470 (while continue
4471 (if (or (js2-ast-root-p node)
4472 (and (js2-function-node-p node)
4473 (<= (setq pos (js2-node-abs-pos node)) beg)
4474 (>= (+ pos (js2-node-len node)) end)))
4475 (setq continue nil)
4476 (setq node (js2-node-parent node))))
4477 node))
4478
4479 (defun js2-node-parent-script-or-fn (node)
4480 "Find script or function immediately enclosing NODE.
4481 If NODE is the ast-root, returns nil."
4482 (if (js2-ast-root-p node)
4483 nil
4484 (setq node (js2-node-parent node))
4485 (while (and node (not (or (js2-function-node-p node)
4486 (js2-script-node-p node))))
4487 (setq node (js2-node-parent node)))
4488 node))
4489
4490 (defun js2-nested-function-p (node)
4491 "Return t if NODE is a nested function, or is inside a nested function."
4492 (unless (js2-ast-root-p node)
4493 (js2-function-node-p (if (js2-function-node-p node)
4494 (js2-node-parent-script-or-fn node)
4495 (js2-node-parent-script-or-fn
4496 (js2-node-parent-script-or-fn node))))))
4497
4498 (defun js2-mode-shift-kids (kids start offset)
4499 (dolist (kid kids)
4500 (if (> (js2-node-pos kid) start)
4501 (incf (js2-node-pos kid) offset))))
4502
4503 (defun js2-mode-shift-children (parent start offset)
4504 "Update start-positions of all children of PARENT beyond START."
4505 (let ((root (js2-node-root parent)))
4506 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4507 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4508
4509 (defun js2-node-is-descendant (node ancestor)
4510 "Return t if NODE is a descendant of ANCESTOR."
4511 (while (and node
4512 (not (eq node ancestor)))
4513 (setq node (js2-node-parent node)))
4514 node)
4515
4516 ;;; visitor infrastructure
4517
4518 (defun js2-visit-none (node callback)
4519 "Visitor for AST node that have no node children."
4520 nil)
4521
4522 (defun js2-print-none (node indent)
4523 "Visitor for AST node with no printed representation.")
4524
4525 (defun js2-print-body (node indent)
4526 "Print a statement, or a block without braces."
4527 (if (js2-block-node-p node)
4528 (dolist (kid (js2-block-node-kids node))
4529 (js2-print-ast kid indent))
4530 (js2-print-ast node indent)))
4531
4532 (defun js2-print-list (args &optional delimiter)
4533 (loop with len = (length args)
4534 for arg in args
4535 for count from 1
4536 do
4537 (when arg (js2-print-ast arg 0))
4538 (if (< count len)
4539 (insert (or delimiter ", ")))))
4540
4541 (defun js2-print-tree (ast)
4542 "Prints an AST to the current buffer.
4543 Makes `js2-ast-parent-nodes' available to the printer functions."
4544 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4545 (js2-print-ast ast)))
4546
4547 (defun js2-print-ast (node &optional indent)
4548 "Helper function for printing AST nodes.
4549 Requires `js2-ast-parent-nodes' to be non-nil.
4550 You should use `js2-print-tree' instead of this function."
4551 (let ((printer (get (aref node 0) 'js2-printer))
4552 (i (or indent 0))
4553 (pos (js2-node-abs-pos node)))
4554 ;; TODO: wedge comments in here somewhere
4555 (if printer
4556 (funcall printer node i))))
4557
4558 (defconst js2-side-effecting-tokens
4559 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4560 (dolist (tt (list js2-ASSIGN
4561 js2-ASSIGN_ADD
4562 js2-ASSIGN_BITAND
4563 js2-ASSIGN_BITOR
4564 js2-ASSIGN_BITXOR
4565 js2-ASSIGN_DIV
4566 js2-ASSIGN_LSH
4567 js2-ASSIGN_MOD
4568 js2-ASSIGN_MUL
4569 js2-ASSIGN_RSH
4570 js2-ASSIGN_SUB
4571 js2-ASSIGN_URSH
4572 js2-BLOCK
4573 js2-BREAK
4574 js2-CALL
4575 js2-CATCH
4576 js2-CATCH_SCOPE
4577 js2-CONST
4578 js2-CONTINUE
4579 js2-DEBUGGER
4580 js2-DEC
4581 js2-DELPROP
4582 js2-DEL_REF
4583 js2-DO
4584 js2-ELSE
4585 js2-EMPTY
4586 js2-ENTERWITH
4587 js2-EXPORT
4588 js2-EXPR_RESULT
4589 js2-FINALLY
4590 js2-FOR
4591 js2-FUNCTION
4592 js2-GOTO
4593 js2-IF
4594 js2-IFEQ
4595 js2-IFNE
4596 js2-IMPORT
4597 js2-INC
4598 js2-JSR
4599 js2-LABEL
4600 js2-LEAVEWITH
4601 js2-LET
4602 js2-LETEXPR
4603 js2-LOCAL_BLOCK
4604 js2-LOOP
4605 js2-NEW
4606 js2-REF_CALL
4607 js2-RETHROW
4608 js2-RETURN
4609 js2-RETURN_RESULT
4610 js2-SEMI
4611 js2-SETELEM
4612 js2-SETELEM_OP
4613 js2-SETNAME
4614 js2-SETPROP
4615 js2-SETPROP_OP
4616 js2-SETVAR
4617 js2-SET_REF
4618 js2-SET_REF_OP
4619 js2-SWITCH
4620 js2-TARGET
4621 js2-THROW
4622 js2-TRY
4623 js2-VAR
4624 js2-WHILE
4625 js2-WITH
4626 js2-WITHEXPR
4627 js2-YIELD))
4628 (aset tokens tt t))
4629 (if js2-instanceof-has-side-effects
4630 (aset tokens js2-INSTANCEOF t))
4631 tokens))
4632
4633 (defun js2-node-has-side-effects (node)
4634 "Return t if NODE has side effects."
4635 (when node ; makes it easier to handle malformed expressions
4636 (let ((tt (js2-node-type node)))
4637 (cond
4638 ;; This doubtless needs some work, since EXPR_VOID is used
4639 ;; in several ways in Rhino and I may not have caught them all.
4640 ;; I'll wait for people to notice incorrect warnings.
4641 ((and (= tt js2-EXPR_VOID)
4642 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4643 (let ((expr (js2-expr-stmt-node-expr node)))
4644 (or (js2-node-has-side-effects expr)
4645 (when (js2-string-node-p expr)
4646 (string= "use strict" (js2-string-node-value expr))))))
4647 ((= tt js2-COMMA)
4648 (js2-node-has-side-effects (js2-infix-node-right node)))
4649 ((or (= tt js2-AND)
4650 (= tt js2-OR))
4651 (or (js2-node-has-side-effects (js2-infix-node-right node))
4652 (js2-node-has-side-effects (js2-infix-node-left node))))
4653 ((= tt js2-HOOK)
4654 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4655 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4656 ((js2-paren-node-p node)
4657 (js2-node-has-side-effects (js2-paren-node-expr node)))
4658 ((= tt js2-ERROR) ; avoid cascaded error messages
4659 nil)
4660 (t
4661 (aref js2-side-effecting-tokens tt))))))
4662
4663 (defun js2-member-expr-leftmost-name (node)
4664 "For an expr such as foo.bar.baz, return leftmost node foo.
4665 NODE is any `js2-node' object. If it represents a member expression,
4666 which is any sequence of property gets, element-gets, function calls,
4667 or xml descendants/filter operators, then we look at the lexically
4668 leftmost (first) node in the chain. If it is a name-node we return it.
4669 Note that NODE can be a raw name-node and it will be returned as well.
4670 If NODE is not a name-node or member expression, or if it is a member
4671 expression whose leftmost target is not a name node, returns nil."
4672 (let ((continue t)
4673 result)
4674 (while (and continue (not result))
4675 (cond
4676 ((js2-name-node-p node)
4677 (setq result node))
4678 ((js2-prop-get-node-p node)
4679 (setq node (js2-prop-get-node-left node)))
4680 ;; TODO: handle call-nodes, xml-nodes, others?
4681 (t
4682 (setq continue nil))))
4683 result))
4684
4685 (defconst js2-stmt-node-types
4686 (list js2-BLOCK
4687 js2-BREAK
4688 js2-CONTINUE
4689 js2-DEFAULT ; e4x "default xml namespace" statement
4690 js2-DO
4691 js2-EXPR_RESULT
4692 js2-EXPR_VOID
4693 js2-FOR
4694 js2-IF
4695 js2-RETURN
4696 js2-SWITCH
4697 js2-THROW
4698 js2-TRY
4699 js2-WHILE
4700 js2-WITH)
4701 "Node types that only appear in statement contexts.
4702 The list does not include nodes that always appear as the child
4703 of another specific statement type, such as switch-cases,
4704 catch and finally blocks, and else-clauses. The list also excludes
4705 nodes like yield, let and var, which may appear in either expression
4706 or statement context, and in the latter context always have a
4707 `js2-expr-stmt-node' parent. Finally, the list does not include
4708 functions or scripts, which are treated separately from statements
4709 by the JavaScript parser and runtime.")
4710
4711 (defun js2-stmt-node-p (node)
4712 "Heuristic for figuring out if NODE is a statement.
4713 Some node types can appear in either an expression context or a
4714 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4715 For these node types in a statement context, the parent will be a
4716 `js2-expr-stmt-node'.
4717 Functions aren't included in the check."
4718 (memq (js2-node-type node) js2-stmt-node-types))
4719
4720 (defun js2-mode-find-first-stmt (node)
4721 "Search upward starting from NODE looking for a statement.
4722 For purposes of this function, a `js2-function-node' counts."
4723 (while (not (or (js2-stmt-node-p node)
4724 (js2-function-node-p node)))
4725 (setq node (js2-node-parent node)))
4726 node)
4727
4728 (defun js2-node-parent-stmt (node)
4729 "Return the node's first ancestor that is a statement.
4730 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4731 appearing in a statement context will have a parent that is a
4732 `js2-expr-stmt-node' that will be returned by this function."
4733 (let ((parent (js2-node-parent node)))
4734 (if (or (null parent)
4735 (js2-stmt-node-p parent)
4736 (and (js2-function-node-p parent)
4737 (not (eq (js2-function-node-form parent)
4738 'FUNCTION_EXPRESSION))))
4739 parent
4740 (js2-node-parent-stmt parent))))
4741
4742 ;; In the Mozilla Rhino sources, Roshan James writes:
4743 ;; Does consistent-return analysis on the function body when strict mode is
4744 ;; enabled.
4745 ;;
4746 ;; function (x) { return (x+1) }
4747 ;;
4748 ;; is ok, but
4749 ;;
4750 ;; function (x) { if (x < 0) return (x+1); }
4751 ;;
4752 ;; is not because the function can potentially return a value when the
4753 ;; condition is satisfied and if not, the function does not explicitly
4754 ;; return a value.
4755 ;;
4756 ;; This extends to checking mismatches such as "return" and "return <value>"
4757 ;; used in the same function. Warnings are not emitted if inconsistent
4758 ;; returns exist in code that can be statically shown to be unreachable.
4759 ;; Ex.
4760 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4761 ;;
4762 ;; emits no warning. However if the loop had a break statement, then a
4763 ;; warning would be emitted.
4764 ;;
4765 ;; The consistency analysis looks at control structures such as loops, ifs,
4766 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4767 ;; warns the user about an inconsistent set of termination possibilities.
4768 ;;
4769 ;; These flags enumerate the possible ways a statement/function can
4770 ;; terminate. These flags are used by endCheck() and by the Parser to
4771 ;; detect inconsistent return usage.
4772 ;;
4773 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4774 ;; able to execute (example: throw, continue)
4775 ;;
4776 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4777 ;; next one. Statement such as return dont. A compound statement may have
4778 ;; some branch that drops off control to the next statement.
4779 ;;
4780 ;; END_RETURNS indicates that the statement can return with no value.
4781 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4782 ;;
4783 ;; A compound statement such as
4784 ;; if (condition) {
4785 ;; return value;
4786 ;; }
4787 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4788
4789 (defconst js2-END_UNREACHED 0)
4790 (defconst js2-END_DROPS_OFF 1)
4791 (defconst js2-END_RETURNS 2)
4792 (defconst js2-END_RETURNS_VALUE 4)
4793 (defconst js2-END_YIELDS 8)
4794
4795 (defun js2-has-consistent-return-usage (node)
4796 "Check that every return usage in a function body is consistent.
4797 Returns t if the function satisfies strict mode requirement."
4798 (let ((n (js2-end-check node)))
4799 ;; either it doesn't return a value in any branch...
4800 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4801 ;; or it returns a value (or is unreached) at every branch
4802 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4803 js2-END_RETURNS
4804 js2-END_YIELDS)))))
4805
4806 (defun js2-end-check-if (node)
4807 "Ensure that return usage in then/else blocks is consistent.
4808 If there is no else block, then the return statement can fall through.
4809 Returns logical OR of END_* flags"
4810 (let ((th (js2-if-node-then-part node))
4811 (el (js2-if-node-else-part node)))
4812 (if (null th)
4813 js2-END_UNREACHED
4814 (logior (js2-end-check th) (if el
4815 (js2-end-check el)
4816 js2-END_DROPS_OFF)))))
4817
4818 (defun js2-end-check-switch (node)
4819 "Consistency of return statements is checked between the case statements.
4820 If there is no default, then the switch can fall through. If there is a
4821 default, we check to see if all code paths in the default return or if
4822 there is a code path that can fall through.
4823 Returns logical OR of END_* flags."
4824 (let ((rv js2-END_UNREACHED)
4825 default-case)
4826 ;; examine the cases
4827 (catch 'break
4828 (dolist (c (js2-switch-node-cases node))
4829 (if (js2-case-node-expr c)
4830 (js2-set-flag rv (js2-end-check-block c))
4831 (setq default-case c)
4832 (throw 'break nil))))
4833 ;; we don't care how the cases drop into each other
4834 (js2-clear-flag rv js2-END_DROPS_OFF)
4835 ;; examine the default
4836 (js2-set-flag rv (if default-case
4837 (js2-end-check default-case)
4838 js2-END_DROPS_OFF))
4839 rv))
4840
4841 (defun js2-end-check-try (node)
4842 "If the block has a finally, return consistency is checked in the
4843 finally block. If all code paths in the finally return, then the
4844 returns in the try-catch blocks don't matter. If there is a code path
4845 that does not return or if there is no finally block, the returns
4846 of the try and catch blocks are checked for mismatch.
4847 Returns logical OR of END_* flags."
4848 (let ((finally (js2-try-node-finally-block node))
4849 rv)
4850 ;; check the finally if it exists
4851 (setq rv (if finally
4852 (js2-end-check (js2-finally-node-body finally))
4853 js2-END_DROPS_OFF))
4854 ;; If the finally block always returns, then none of the returns
4855 ;; in the try or catch blocks matter.
4856 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4857 (js2-clear-flag rv js2-END_DROPS_OFF)
4858 ;; examine the try block
4859 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4860 ;; check each catch block
4861 (dolist (cb (js2-try-node-catch-clauses node))
4862 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4863 rv))
4864
4865 (defun js2-end-check-loop (node)
4866 "Return statement in the loop body must be consistent.
4867 The default assumption for any kind of a loop is that it will eventually
4868 terminate. The only exception is a loop with a constant true condition.
4869 Code that follows such a loop is examined only if one can determine
4870 statically that there is a break out of the loop.
4871
4872 for(... ; ... ; ...) {}
4873 for(... in ... ) {}
4874 while(...) { }
4875 do { } while(...)
4876
4877 Returns logical OR of END_* flags."
4878 (let ((rv (js2-end-check (js2-loop-node-body node)))
4879 (condition (cond
4880 ((js2-while-node-p node)
4881 (js2-while-node-condition node))
4882 ((js2-do-node-p node)
4883 (js2-do-node-condition node))
4884 ((js2-for-node-p node)
4885 (js2-for-node-condition node)))))
4886
4887 ;; check to see if the loop condition is always true
4888 (if (and condition
4889 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4890 (js2-clear-flag rv js2-END_DROPS_OFF))
4891
4892 ;; look for effect of breaks
4893 (js2-set-flag rv (js2-node-get-prop node
4894 'CONTROL_BLOCK_PROP
4895 js2-END_UNREACHED))
4896 rv))
4897
4898 (defun js2-end-check-block (node)
4899 "A general block of code is examined statement by statement.
4900 If any statement (even a compound one) returns in all branches, then
4901 subsequent statements are not examined.
4902 Returns logical OR of END_* flags."
4903 (let* ((rv js2-END_DROPS_OFF)
4904 (kids (js2-block-node-kids node))
4905 (n (car kids)))
4906 ;; Check each statment. If the statement can continue onto the next
4907 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4908 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4909 (js2-clear-flag rv js2-END_DROPS_OFF)
4910 (js2-set-flag rv (js2-end-check n))
4911 (setq kids (cdr kids)
4912 n (car kids)))
4913 rv))
4914
4915 (defun js2-end-check-label (node)
4916 "A labeled statement implies that there may be a break to the label.
4917 The function processes the labeled statement and then checks the
4918 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4919 particular label.
4920 Returns logical OR of END_* flags."
4921 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4922 (logior rv (js2-node-get-prop node
4923 'CONTROL_BLOCK_PROP
4924 js2-END_UNREACHED))))
4925
4926 (defun js2-end-check-break (node)
4927 "When a break is encountered annotate the statement being broken
4928 out of by setting its CONTROL_BLOCK_PROP property.
4929 Returns logical OR of END_* flags."
4930 (and (js2-break-node-target node)
4931 (js2-node-set-prop (js2-break-node-target node)
4932 'CONTROL_BLOCK_PROP
4933 js2-END_DROPS_OFF))
4934 js2-END_UNREACHED)
4935
4936 (defun js2-end-check (node)
4937 "Examine the body of a function, doing a basic reachability analysis.
4938 Returns a combination of flags END_* flags that indicate
4939 how the function execution can terminate. These constitute only the
4940 pessimistic set of termination conditions. It is possible that at
4941 runtime certain code paths will never be actually taken. Hence this
4942 analysis will flag errors in cases where there may not be errors.
4943 Returns logical OR of END_* flags"
4944 (let (kid)
4945 (cond
4946 ((js2-break-node-p node)
4947 (js2-end-check-break node))
4948 ((js2-expr-stmt-node-p node)
4949 (if (setq kid (js2-expr-stmt-node-expr node))
4950 (js2-end-check kid)
4951 js2-END_DROPS_OFF))
4952 ((or (js2-continue-node-p node)
4953 (js2-throw-node-p node))
4954 js2-END_UNREACHED)
4955 ((js2-return-node-p node)
4956 (if (setq kid (js2-return-node-retval node))
4957 js2-END_RETURNS_VALUE
4958 js2-END_RETURNS))
4959 ((js2-loop-node-p node)
4960 (js2-end-check-loop node))
4961 ((js2-switch-node-p node)
4962 (js2-end-check-switch node))
4963 ((js2-labeled-stmt-node-p node)
4964 (js2-end-check-label node))
4965 ((js2-if-node-p node)
4966 (js2-end-check-if node))
4967 ((js2-try-node-p node)
4968 (js2-end-check-try node))
4969 ((js2-block-node-p node)
4970 (if (null (js2-block-node-kids node))
4971 js2-END_DROPS_OFF
4972 (js2-end-check-block node)))
4973 ((js2-yield-node-p node)
4974 js2-END_YIELDS)
4975 (t
4976 js2-END_DROPS_OFF))))
4977
4978 (defun js2-always-defined-boolean-p (node)
4979 "Check if NODE always evaluates to true or false in boolean context.
4980 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4981 nor always false."
4982 (let ((tt (js2-node-type node))
4983 num)
4984 (cond
4985 ((or (= tt js2-FALSE) (= tt js2-NULL))
4986 'ALWAYS_FALSE)
4987 ((= tt js2-TRUE)
4988 'ALWAYS_TRUE)
4989 ((= tt js2-NUMBER)
4990 (setq num (js2-number-node-num-value node))
4991 (if (and (not (eq num 0.0e+NaN))
4992 (not (zerop num)))
4993 'ALWAYS_TRUE
4994 'ALWAYS_FALSE))
4995 (t
4996 nil))))
4997
4998 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4999 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5000
5001 (defvar js2-tokens nil
5002 "List of all defined token names.") ; initialized in `js2-token-names'
5003
5004 (defconst js2-token-names
5005 (let* ((names (make-vector js2-num-tokens -1))
5006 (case-fold-search nil) ; only match js2-UPPER_CASE
5007 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5008 (loop for sym in syms
5009 for i from 0
5010 do
5011 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5012 (not (boundp sym)))
5013 (aset names (symbol-value sym) ; code, e.g. 152
5014 (downcase
5015 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5016 (push sym js2-tokens)))
5017 names)
5018 "Vector mapping int values to token string names, sans `js2-' prefix.")
5019
5020 (defun js2-token-name (tok)
5021 "Return a string name for TOK, a token symbol or code.
5022 Signals an error if it's not a recognized token."
5023 (let ((code tok))
5024 (if (symbolp tok)
5025 (setq code (symbol-value tok)))
5026 (if (eq code -1)
5027 "ERROR"
5028 (if (and (numberp code)
5029 (not (minusp code))
5030 (< code js2-num-tokens))
5031 (aref js2-token-names code)
5032 (error "Invalid token: %s" code)))))
5033
5034 (defsubst js2-token-sym (tok)
5035 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5036 (intern (js2-token-name tok)))
5037
5038 (defconst js2-token-codes
5039 (let ((table (make-hash-table :test 'eq :size 256)))
5040 (loop for name across js2-token-names
5041 for sym = (intern (concat "js2-" (upcase name)))
5042 do
5043 (puthash sym (symbol-value sym) table))
5044 ;; clean up a few that are "wrong" in Rhino's token codes
5045 (puthash 'js2-DELETE js2-DELPROP table)
5046 table)
5047 "Hashtable mapping token symbols to their bytecodes.")
5048
5049 (defsubst js2-token-code (sym)
5050 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5051 (or (gethash sym js2-token-codes)
5052 (error "Invalid token symbol: %s " sym))) ; signal code bug
5053
5054 (defun js2-report-scan-error (msg &optional no-throw beg len)
5055 (setq js2-token-end js2-ts-cursor)
5056 (js2-report-error msg nil
5057 (or beg js2-token-beg)
5058 (or len (- js2-token-end js2-token-beg)))
5059 (unless no-throw
5060 (throw 'return js2-ERROR)))
5061
5062 (defun js2-get-string-from-buffer ()
5063 "Reverse the char accumulator and return it as a string."
5064 (setq js2-token-end js2-ts-cursor)
5065 (if js2-ts-string-buffer
5066 (apply #'string (nreverse js2-ts-string-buffer))
5067 ""))
5068
5069 ;; TODO: could potentially avoid a lot of consing by allocating a
5070 ;; char buffer the way Rhino does.
5071 (defsubst js2-add-to-string (c)
5072 (push c js2-ts-string-buffer))
5073
5074 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5075 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5076 ;; any other character: when it's not part of the current token, we
5077 ;; unget it, allowing it to be read again by the following call.
5078 (defsubst js2-unget-char ()
5079 (decf js2-ts-cursor))
5080
5081 ;; Rhino distinguishes \r and \n line endings. We don't need to
5082 ;; because we only scan from Emacs buffers, which always use \n.
5083 (defun js2-get-char ()
5084 "Read and return the next character from the input buffer.
5085 Increments `js2-ts-lineno' if the return value is a newline char.
5086 Updates `js2-ts-cursor' to the point after the returned char.
5087 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5088 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5089 (let (c)
5090 ;; check for end of buffer
5091 (if (>= js2-ts-cursor (point-max))
5092 (setq js2-ts-hit-eof t
5093 js2-ts-cursor (1+ js2-ts-cursor)
5094 c js2-EOF_CHAR) ; return value
5095 ;; otherwise read next char
5096 (setq c (char-before (incf js2-ts-cursor)))
5097 ;; if we read a newline, update counters
5098 (if (= c ?\n)
5099 (setq js2-ts-line-start js2-ts-cursor
5100 js2-ts-lineno (1+ js2-ts-lineno)))
5101 ;; TODO: skip over format characters
5102 c)))
5103
5104 (defun js2-read-unicode-escape ()
5105 "Read a \\uNNNN sequence from the input.
5106 Assumes the ?\ and ?u have already been read.
5107 Returns the unicode character, or nil if it wasn't a valid character.
5108 Doesn't change the values of any scanner variables."
5109 ;; I really wish I knew a better way to do this, but I can't
5110 ;; find the Emacs function that takes a 16-bit int and converts
5111 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5112 ;; Have to first check that it's 4 hex characters or it may stop
5113 ;; the read early.
5114 (ignore-errors
5115 (let ((s (buffer-substring-no-properties js2-ts-cursor
5116 (+ 4 js2-ts-cursor))))
5117 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5118 (read (concat "?\\u" s))))))
5119
5120 (defun js2-match-char (test)
5121 "Consume and return next character if it matches TEST, a character.
5122 Returns nil and consumes nothing if TEST is not the next character."
5123 (let ((c (js2-get-char)))
5124 (if (eq c test)
5125 t
5126 (js2-unget-char)
5127 nil)))
5128
5129 (defun js2-peek-char ()
5130 (prog1
5131 (js2-get-char)
5132 (js2-unget-char)))
5133
5134 (defun js2-java-identifier-start-p (c)
5135 (or
5136 (memq c '(?$ ?_))
5137 (js2-char-uppercase-p c)
5138 (js2-char-lowercase-p c)))
5139
5140 (defun js2-java-identifier-part-p (c)
5141 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5142 ;; TODO: make me Unicode-friendly. See comments above.
5143 (or
5144 (memq c '(?$ ?_))
5145 (js2-char-uppercase-p c)
5146 (js2-char-lowercase-p c)
5147 (and (>= c ?0) (<= c ?9))))
5148
5149 (defun js2-alpha-p (c)
5150 (cond ((and (<= ?A c) (<= c ?Z)) t)
5151 ((and (<= ?a c) (<= c ?z)) t)
5152 (t nil)))
5153
5154 (defsubst js2-digit-p (c)
5155 (and (<= ?0 c) (<= c ?9)))
5156
5157 (defun js2-js-space-p (c)
5158 (if (<= c 127)
5159 (memq c '(#x20 #x9 #xB #xC #xD))
5160 (or
5161 (eq c #xA0)
5162 ;; TODO: change this nil to check for Unicode space character
5163 nil)))
5164
5165 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5166
5167 (defun js2-skip-line ()
5168 "Skip to end of line."
5169 (let (c)
5170 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5171 (js2-unget-char)
5172 (setq js2-token-end js2-ts-cursor)))
5173
5174 (defun js2-init-scanner (&optional buf line)
5175 "Create token stream for BUF starting on LINE.
5176 BUF defaults to `current-buffer' and LINE defaults to 1.
5177
5178 A buffer can only have one scanner active at a time, which yields
5179 dramatically simpler code than using a defstruct. If you need to
5180 have simultaneous scanners in a buffer, copy the regions to scan
5181 into temp buffers."
5182 (with-current-buffer (or buf (current-buffer))
5183 (setq js2-ts-dirty-line nil
5184 js2-ts-regexp-flags nil
5185 js2-ts-string ""
5186 js2-ts-number nil
5187 js2-ts-hit-eof nil
5188 js2-ts-line-start 0
5189 js2-ts-lineno (or line 1)
5190 js2-ts-line-end-char -1
5191 js2-ts-cursor (point-min)
5192 js2-ts-is-xml-attribute nil
5193 js2-ts-xml-is-tag-content nil
5194 js2-ts-xml-open-tags-count 0
5195 js2-ts-string-buffer nil)))
5196
5197 ;; This function uses the cached op, string and number fields in
5198 ;; TokenStream; if getToken has been called since the passed token
5199 ;; was scanned, the op or string printed may be incorrect.
5200 (defun js2-token-to-string (token)
5201 ;; Not sure where this function is used in Rhino. Not tested.
5202 (if (not js2-debug-print-trees)
5203 ""
5204 (let ((name (js2-token-name token)))
5205 (cond
5206 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5207 (concat name " `" js2-ts-string "'"))
5208 ((eq token js2-NUMBER)
5209 (format "NUMBER %g" js2-ts-number))
5210 (t
5211 name)))))
5212
5213 (defconst js2-keywords
5214 '(break
5215 case catch const continue
5216 debugger default delete do
5217 else enum
5218 false finally for function
5219 if in instanceof import
5220 let
5221 new null
5222 return
5223 switch
5224 this throw true try typeof
5225 var void
5226 while with
5227 yield))
5228
5229 ;; Token names aren't exactly the same as the keywords, unfortunately.
5230 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5231 (defconst js2-kwd-tokens
5232 (let ((table (make-vector js2-num-tokens nil))
5233 (tokens
5234 (list js2-BREAK
5235 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5236 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5237 js2-ELSE
5238 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5239 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5240 js2-LET
5241 js2-NEW js2-NULL
5242 js2-RETURN
5243 js2-SWITCH
5244 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5245 js2-VAR
5246 js2-WHILE js2-WITH
5247 js2-YIELD)))
5248 (dolist (i tokens)
5249 (aset table i 'font-lock-keyword-face))
5250 (aset table js2-STRING 'font-lock-string-face)
5251 (aset table js2-REGEXP 'font-lock-string-face)
5252 (aset table js2-COMMENT 'font-lock-comment-face)
5253 (aset table js2-THIS 'font-lock-builtin-face)
5254 (aset table js2-VOID 'font-lock-constant-face)
5255 (aset table js2-NULL 'font-lock-constant-face)
5256 (aset table js2-TRUE 'font-lock-constant-face)
5257 (aset table js2-FALSE 'font-lock-constant-face)
5258 table)
5259 "Vector whose values are non-nil for tokens that are keywords.
5260 The values are default faces to use for highlighting the keywords.")
5261
5262 (defconst js2-reserved-words
5263 '(abstract
5264 boolean byte
5265 char class
5266 double
5267 enum export extends
5268 final float
5269 goto
5270 implements import int interface
5271 long
5272 native
5273 package private protected public
5274 short static super synchronized
5275 throws transient
5276 volatile))
5277
5278 (defconst js2-keyword-names
5279 (let ((table (make-hash-table :test 'equal)))
5280 (loop for k in js2-keywords
5281 do (puthash
5282 (symbol-name k) ; instanceof
5283 (intern (concat "js2-"
5284 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5285 table))
5286 table)
5287 "JavaScript keywords by name, mapped to their symbols.")
5288
5289 (defconst js2-reserved-word-names
5290 (let ((table (make-hash-table :test 'equal)))
5291 (loop for k in js2-reserved-words
5292 do
5293 (puthash (symbol-name k) 'js2-RESERVED table))
5294 table)
5295 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5296
5297 (defun js2-collect-string (buf)
5298 "Convert BUF, a list of chars, to a string.
5299 Reverses BUF before converting."
5300 (cond
5301 ((stringp buf)
5302 buf)
5303 ((null buf) ; for emacs21 compat
5304 "")
5305 (t
5306 (if buf
5307 (apply #'string (nreverse buf))
5308 ""))))
5309
5310 (defun js2-string-to-keyword (s)
5311 "Return token for S, a string, if S is a keyword or reserved word.
5312 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5313 (or (gethash s js2-keyword-names)
5314 (gethash s js2-reserved-word-names)))
5315
5316 (defsubst js2-ts-set-char-token-bounds ()
5317 "Used when next token is one character."
5318 (setq js2-token-beg (1- js2-ts-cursor)
5319 js2-token-end js2-ts-cursor))
5320
5321 (defsubst js2-ts-return (token)
5322 "Return an N-character TOKEN from `js2-get-token'.
5323 Updates `js2-token-end' accordingly."
5324 (setq js2-token-end js2-ts-cursor)
5325 (throw 'return token))
5326
5327 (defun js2-x-digit-to-int (c accumulator)
5328 "Build up a hex number.
5329 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5330 corresponding number. Otherwise return -1."
5331 (catch 'return
5332 (catch 'check
5333 ;; Use 0..9 < A..Z < a..z
5334 (cond
5335 ((<= c ?9)
5336 (decf c ?0)
5337 (if (<= 0 c)
5338 (throw 'check nil)))
5339 ((<= c ?F)
5340 (when (<= ?A c)
5341 (decf c (- ?A 10))
5342 (throw 'check nil)))
5343 ((<= c ?f)
5344 (when (<= ?a c)
5345 (decf c (- ?a 10))
5346 (throw 'check nil))))
5347 (throw 'return -1))
5348 (logior c (lsh accumulator 4))))
5349
5350 (defun js2-get-token ()
5351 "Return next JavaScript token, an int such as js2-RETURN."
5352 (let (c c1 identifier-start is-unicode-escape-start
5353 contains-escape escape-val escape-start str result base
5354 is-integer quote-char val look-for-slash continue)
5355 (catch 'return
5356 (while t
5357 ;; Eat whitespace, possibly sensitive to newlines.
5358 (setq continue t)
5359 (while continue
5360 (setq c (js2-get-char))
5361 (cond
5362 ((eq c js2-EOF_CHAR)
5363 (js2-ts-set-char-token-bounds)
5364 (throw 'return js2-EOF))
5365 ((eq c ?\n)
5366 (js2-ts-set-char-token-bounds)
5367 (setq js2-ts-dirty-line nil)
5368 (throw 'return js2-EOL))
5369 ((not (js2-js-space-p c))
5370 (if (/= c ?-) ; in case end of HTML comment
5371 (setq js2-ts-dirty-line t))
5372 (setq continue nil))))
5373 ;; Assume the token will be 1 char - fixed up below.
5374 (js2-ts-set-char-token-bounds)
5375 (when (eq c ?@)
5376 (throw 'return js2-XMLATTR))
5377 ;; identifier/keyword/instanceof?
5378 ;; watch out for starting with a <backslash>
5379 (cond
5380 ((eq c ?\\)
5381 (setq c (js2-get-char))
5382 (if (eq c ?u)
5383 (setq identifier-start t
5384 is-unicode-escape-start t
5385 js2-ts-string-buffer nil)
5386 (setq identifier-start nil)
5387 (js2-unget-char)
5388 (setq c ?\\)))
5389 (t
5390 (when (setq identifier-start (js2-java-identifier-start-p c))
5391 (setq js2-ts-string-buffer nil)
5392 (js2-add-to-string c))))
5393 (when identifier-start
5394 (setq contains-escape is-unicode-escape-start)
5395 (catch 'break
5396 (while t
5397 (if is-unicode-escape-start
5398 ;; strictly speaking we should probably push-back
5399 ;; all the bad characters if the <backslash>uXXXX
5400 ;; sequence is malformed. But since there isn't a
5401 ;; correct context(is there?) for a bad Unicode
5402 ;; escape sequence in an identifier, we can report
5403 ;; an error here.
5404 (progn
5405 (setq escape-val 0)
5406 (dotimes (i 4)
5407 (setq c (js2-get-char)
5408 escape-val (js2-x-digit-to-int c escape-val))
5409 ;; Next check takes care of c < 0 and bad escape
5410 (if (minusp escape-val)
5411 (throw 'break nil)))
5412 (if (minusp escape-val)
5413 (js2-report-scan-error "msg.invalid.escape" t))
5414 (js2-add-to-string escape-val)
5415 (setq is-unicode-escape-start nil))
5416 (setq c (js2-get-char))
5417 (cond
5418 ((eq c ?\\)
5419 (setq c (js2-get-char))
5420 (if (eq c ?u)
5421 (setq is-unicode-escape-start t
5422 contains-escape t)
5423 (js2-report-scan-error "msg.illegal.character" t)))
5424 (t
5425 (if (or (eq c js2-EOF_CHAR)
5426 (not (js2-java-identifier-part-p c)))
5427 (throw 'break nil))
5428 (js2-add-to-string c))))))
5429 (js2-unget-char)
5430 (setq str (js2-get-string-from-buffer))
5431 (unless contains-escape
5432 ;; OPT we shouldn't have to make a string (object!) to
5433 ;; check if it's a keyword.
5434 ;; Return the corresponding token if it's a keyword
5435 (when (setq result (js2-string-to-keyword str))
5436 (if (and (< js2-language-version 170)
5437 (memq result '(js2-LET js2-YIELD)))
5438 ;; LET and YIELD are tokens only in 1.7 and later
5439 (setq result 'js2-NAME))
5440 (if (not (eq result 'js2-RESERVED))
5441 (throw 'return (js2-token-code result)))
5442 (js2-report-warning "msg.reserved.keyword" str)))
5443 ;; If we want to intern these as Rhino does, just use (intern str)
5444 (setq js2-ts-string str)
5445 (throw 'return js2-NAME)) ; end identifier/kwd check
5446 ;; is it a number?
5447 (when (or (js2-digit-p c)
5448 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5449 (setq js2-ts-string-buffer nil
5450 base 10)
5451 (when (eq c ?0)
5452 (setq c (js2-get-char))
5453 (cond
5454 ((or (eq c ?x) (eq c ?X))
5455 (setq base 16)
5456 (setq c (js2-get-char)))
5457 ((js2-digit-p c)
5458 (setq base 8))
5459 (t
5460 (js2-add-to-string ?0))))
5461 (if (eq base 16)
5462 (while (<= 0 (js2-x-digit-to-int c 0))
5463 (js2-add-to-string c)
5464 (setq c (js2-get-char)))
5465 (while (and (<= ?0 c) (<= c ?9))
5466 ;; We permit 08 and 09 as decimal numbers, which
5467 ;; makes our behavior a superset of the ECMA
5468 ;; numeric grammar. We might not always be so
5469 ;; permissive, so we warn about it.
5470 (when (and (eq base 8) (>= c ?8))
5471 (js2-report-warning "msg.bad.octal.literal"
5472 (if (eq c ?8) "8" "9"))
5473 (setq base 10))
5474 (js2-add-to-string c)
5475 (setq c (js2-get-char))))
5476 (setq is-integer t)
5477 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5478 (setq is-integer nil)
5479 (when (eq c ?.)
5480 (loop do
5481 (js2-add-to-string c)
5482 (setq c (js2-get-char))
5483 while (js2-digit-p c)))
5484 (when (memq c '(?e ?E))
5485 (js2-add-to-string c)
5486 (setq c (js2-get-char))
5487 (when (memq c '(?+ ?-))
5488 (js2-add-to-string c)
5489 (setq c (js2-get-char)))
5490 (unless (js2-digit-p c)
5491 (js2-report-scan-error "msg.missing.exponent" t))
5492 (loop do
5493 (js2-add-to-string c)
5494 (setq c (js2-get-char))
5495 while (js2-digit-p c))))
5496 (js2-unget-char)
5497 (setq js2-ts-string (js2-get-string-from-buffer)
5498 js2-ts-number
5499 (if (and (eq base 10) (not is-integer))
5500 (string-to-number js2-ts-string)
5501 ;; TODO: call runtime number-parser. Some of it is in
5502 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5503 (string-to-number js2-ts-string)))
5504 (throw 'return js2-NUMBER))
5505 ;; is it a string?
5506 (when (memq c '(?\" ?\'))
5507 ;; We attempt to accumulate a string the fast way, by
5508 ;; building it directly out of the reader. But if there
5509 ;; are any escaped characters in the string, we revert to
5510 ;; building it out of a string buffer.
5511 (setq quote-char c
5512 js2-ts-string-buffer nil
5513 c (js2-get-char))
5514 (catch 'break
5515 (while (/= c quote-char)
5516 (catch 'continue
5517 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5518 (js2-unget-char)
5519 (setq js2-token-end js2-ts-cursor)
5520 (js2-report-error "msg.unterminated.string.lit")
5521 (throw 'return js2-STRING))
5522 (when (eq c ?\\)
5523 ;; We've hit an escaped character
5524 (setq c (js2-get-char))
5525 (case c
5526 (?b (setq c ?\b))
5527 (?f (setq c ?\f))
5528 (?n (setq c ?\n))
5529 (?r (setq c ?\r))
5530 (?t (setq c ?\t))
5531 (?v (setq c ?\v))
5532 (?u
5533 (setq c1 (js2-read-unicode-escape))
5534 (if js2-parse-ide-mode
5535 (if c1
5536 (progn
5537 ;; just copy the string in IDE-mode
5538 (js2-add-to-string ?\\)
5539 (js2-add-to-string ?u)
5540 (dotimes (i 3)
5541 (js2-add-to-string (js2-get-char)))
5542 (setq c (js2-get-char))) ; added at end of loop
5543 ;; flag it as an invalid escape
5544 (js2-report-warning "msg.invalid.escape"
5545 nil (- js2-ts-cursor 2) 6))
5546 ;; Get 4 hex digits; if the u escape is not
5547 ;; followed by 4 hex digits, use 'u' + the
5548 ;; literal character sequence that follows.
5549 (js2-add-to-string ?u)
5550 (setq escape-val 0)
5551 (dotimes (i 4)
5552 (setq c (js2-get-char)
5553 escape-val (js2-x-digit-to-int c escape-val))
5554 (if (minusp escape-val)
5555 (throw 'continue nil))
5556 (js2-add-to-string c))
5557 ;; prepare for replace of stored 'u' sequence by escape value
5558 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5559 c escape-val)))
5560 (?x
5561 ;; Get 2 hex digits, defaulting to 'x'+literal
5562 ;; sequence, as above.
5563 (setq c (js2-get-char)
5564 escape-val (js2-x-digit-to-int c 0))
5565 (if (minusp escape-val)
5566 (progn
5567 (js2-add-to-string ?x)
5568 (throw 'continue nil))
5569 (setq c1 c
5570 c (js2-get-char)
5571 escape-val (js2-x-digit-to-int c escape-val))
5572 (if (minusp escape-val)
5573 (progn
5574 (js2-add-to-string ?x)
5575 (js2-add-to-string c1)
5576 (throw 'continue nil))
5577 ;; got 2 hex digits
5578 (setq c escape-val))))
5579 (?\n
5580 ;; Remove line terminator after escape to follow
5581 ;; SpiderMonkey and C/C++
5582 (setq c (js2-get-char))
5583 (throw 'continue nil))
5584 (t
5585 (when (and (<= ?0 c) (< c ?8))
5586 (setq val (- c ?0)
5587 c (js2-get-char))
5588 (when (and (<= ?0 c) (< c ?8))
5589 (setq val (- (+ (* 8 val) c) ?0)
5590 c (js2-get-char))
5591 (when (and (<= ?0 c)
5592 (< c ?8)
5593 (< val #o37))
5594 ;; c is 3rd char of octal sequence only
5595 ;; if the resulting val <= 0377
5596 (setq val (- (+ (* 8 val) c) ?0)
5597 c (js2-get-char))))
5598 (js2-unget-char)
5599 (setq c val)))))
5600 (js2-add-to-string c)
5601 (setq c (js2-get-char)))))
5602 (setq js2-ts-string (js2-get-string-from-buffer))
5603 (throw 'return js2-STRING))
5604 (case c
5605 (?\;
5606 (throw 'return js2-SEMI))
5607 (?\[
5608 (throw 'return js2-LB))
5609 (?\]
5610 (throw 'return js2-RB))
5611 (?{
5612 (throw 'return js2-LC))
5613 (?}
5614 (throw 'return js2-RC))
5615 (?\(
5616 (throw 'return js2-LP))
5617 (?\)
5618 (throw 'return js2-RP))
5619 (?,
5620 (throw 'return js2-COMMA))
5621 (??
5622 (throw 'return js2-HOOK))
5623 (?:
5624 (if (js2-match-char ?:)
5625 (js2-ts-return js2-COLONCOLON)
5626 (throw 'return js2-COLON)))
5627 (?.
5628 (if (js2-match-char ?.)
5629 (if (js2-match-char ?.)
5630 (js2-ts-return js2-TRIPLEDOT)
5631 (js2-ts-return js2-DOTDOT))
5632 (if (js2-match-char ?\()
5633 (js2-ts-return js2-DOTQUERY)
5634 (throw 'return js2-DOT))))
5635 (?|
5636 (if (js2-match-char ?|)
5637 (throw 'return js2-OR)
5638 (if (js2-match-char ?=)
5639 (js2-ts-return js2-ASSIGN_BITOR)
5640 (throw 'return js2-BITOR))))
5641 (?^
5642 (if (js2-match-char ?=)
5643 (js2-ts-return js2-ASSIGN_BITOR)
5644 (throw 'return js2-BITXOR)))
5645 (?&
5646 (if (js2-match-char ?&)
5647 (throw 'return js2-AND)
5648 (if (js2-match-char ?=)
5649 (js2-ts-return js2-ASSIGN_BITAND)
5650 (throw 'return js2-BITAND))))
5651 (?=
5652 (if (js2-match-char ?=)
5653 (if (js2-match-char ?=)
5654 (js2-ts-return js2-SHEQ)
5655 (throw 'return js2-EQ))
5656 (throw 'return js2-ASSIGN)))
5657 (?!
5658 (if (js2-match-char ?=)
5659 (if (js2-match-char ?=)
5660 (js2-ts-return js2-SHNE)
5661 (js2-ts-return js2-NE))
5662 (throw 'return js2-NOT)))
5663 (?<
5664 ;; NB:treat HTML begin-comment as comment-till-eol
5665 (when (js2-match-char ?!)
5666 (when (js2-match-char ?-)
5667 (when (js2-match-char ?-)
5668 (js2-skip-line)
5669 (setq js2-ts-comment-type 'html)
5670 (throw 'return js2-COMMENT)))
5671 (js2-unget-char))
5672 (if (js2-match-char ?<)
5673 (if (js2-match-char ?=)
5674 (js2-ts-return js2-ASSIGN_LSH)
5675 (js2-ts-return js2-LSH))
5676 (if (js2-match-char ?=)
5677 (js2-ts-return js2-LE)
5678 (throw 'return js2-LT))))
5679 (?>
5680 (if (js2-match-char ?>)
5681 (if (js2-match-char ?>)
5682 (if (js2-match-char ?=)
5683 (js2-ts-return js2-ASSIGN_URSH)
5684 (js2-ts-return js2-URSH))
5685 (if (js2-match-char ?=)
5686 (js2-ts-return js2-ASSIGN_RSH)
5687 (js2-ts-return js2-RSH)))
5688 (if (js2-match-char ?=)
5689 (js2-ts-return js2-GE)
5690 (throw 'return js2-GT))))
5691 (?*
5692 (if (js2-match-char ?=)
5693 (js2-ts-return js2-ASSIGN_MUL)
5694 (throw 'return js2-MUL)))
5695 (?/
5696 ;; is it a // comment?
5697 (when (js2-match-char ?/)
5698 (setq js2-token-beg (- js2-ts-cursor 2))
5699 (js2-skip-line)
5700 (setq js2-ts-comment-type 'line)
5701 ;; include newline so highlighting goes to end of window
5702 (incf js2-token-end)
5703 (throw 'return js2-COMMENT))
5704 ;; is it a /* comment?
5705 (when (js2-match-char ?*)
5706 (setq look-for-slash nil
5707 js2-token-beg (- js2-ts-cursor 2)
5708 js2-ts-comment-type
5709 (if (js2-match-char ?*)
5710 (progn
5711 (setq look-for-slash t)
5712 'jsdoc)
5713 'block))
5714 (while t
5715 (setq c (js2-get-char))
5716 (cond
5717 ((eq c js2-EOF_CHAR)
5718 (setq js2-token-end (1- js2-ts-cursor))
5719 (js2-report-error "msg.unterminated.comment")
5720 (throw 'return js2-COMMENT))
5721 ((eq c ?*)
5722 (setq look-for-slash t))
5723 ((eq c ?/)
5724 (if look-for-slash
5725 (js2-ts-return js2-COMMENT)))
5726 (t
5727 (setq look-for-slash nil
5728 js2-token-end js2-ts-cursor)))))
5729 (if (js2-match-char ?=)
5730 (js2-ts-return js2-ASSIGN_DIV)
5731 (throw 'return js2-DIV)))
5732 (?#
5733 (when js2-skip-preprocessor-directives
5734 (js2-skip-line)
5735 (setq js2-ts-comment-type 'preprocessor
5736 js2-token-end js2-ts-cursor)
5737 (throw 'return js2-COMMENT))
5738 (throw 'return js2-ERROR))
5739 (?%
5740 (if (js2-match-char ?=)
5741 (js2-ts-return js2-ASSIGN_MOD)
5742 (throw 'return js2-MOD)))
5743 (?~
5744 (throw 'return js2-BITNOT))
5745 (?+
5746 (if (js2-match-char ?=)
5747 (js2-ts-return js2-ASSIGN_ADD)
5748 (if (js2-match-char ?+)
5749 (js2-ts-return js2-INC)
5750 (throw 'return js2-ADD))))
5751 (?-
5752 (cond
5753 ((js2-match-char ?=)
5754 (setq c js2-ASSIGN_SUB))
5755 ((js2-match-char ?-)
5756 (unless js2-ts-dirty-line
5757 ;; treat HTML end-comment after possible whitespace
5758 ;; after line start as comment-until-eol
5759 (when (js2-match-char ?>)
5760 (js2-skip-line)
5761 (setq js2-ts-comment-type 'html)
5762 (throw 'return js2-COMMENT)))
5763 (setq c js2-DEC))
5764 (t
5765 (setq c js2-SUB)))
5766 (setq js2-ts-dirty-line t)
5767 (js2-ts-return c))
5768 (otherwise
5769 (js2-report-scan-error "msg.illegal.character")))))))
5770
5771 (defun js2-read-regexp (start-token)
5772 "Called by parser when it gets / or /= in literal context."
5773 (let (c err
5774 in-class ; inside a '[' .. ']' character-class
5775 flags
5776 (continue t))
5777 (setq js2-token-beg js2-ts-cursor
5778 js2-ts-string-buffer nil
5779 js2-ts-regexp-flags nil)
5780 (if (eq start-token js2-ASSIGN_DIV)
5781 ;; mis-scanned /=
5782 (js2-add-to-string ?=)
5783 (if (not (eq start-token js2-DIV))
5784 (error "failed assertion")))
5785 (while (and (not err)
5786 (or (/= (setq c (js2-get-char)) ?/)
5787 in-class))
5788 (cond
5789 ((or (= c ?\n)
5790 (= c js2-EOF_CHAR))
5791 (setq js2-token-end (1- js2-ts-cursor)
5792 err t
5793 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5794 (js2-report-error "msg.unterminated.re.lit"))
5795 (t (cond
5796 ((= c ?\\)
5797 (js2-add-to-string c)
5798 (setq c (js2-get-char)))
5799 ((= c ?\[)
5800 (setq in-class t))
5801 ((= c ?\])
5802 (setq in-class nil)))
5803 (js2-add-to-string c))))
5804 (unless err
5805 (while continue
5806 (cond
5807 ((js2-match-char ?g)
5808 (push ?g flags))
5809 ((js2-match-char ?i)
5810 (push ?i flags))
5811 ((js2-match-char ?m)
5812 (push ?m flags))
5813 (t
5814 (setq continue nil))))
5815 (if (js2-alpha-p (js2-peek-char))
5816 (js2-report-scan-error "msg.invalid.re.flag" t
5817 js2-ts-cursor 1))
5818 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5819 js2-ts-regexp-flags (js2-collect-string flags)
5820 js2-token-end js2-ts-cursor)
5821 ;; tell `parse-partial-sexp' to ignore this range of chars
5822 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5823
5824 (defun js2-get-first-xml-token ()
5825 (setq js2-ts-xml-open-tags-count 0
5826 js2-ts-is-xml-attribute nil
5827 js2-ts-xml-is-tag-content nil)
5828 (js2-unget-char)
5829 (js2-get-next-xml-token))
5830
5831 (defun js2-xml-discard-string ()
5832 "Throw away the string in progress and flag an XML parse error."
5833 (setq js2-ts-string-buffer nil
5834 js2-ts-string nil)
5835 (js2-report-scan-error "msg.XML.bad.form" t))
5836
5837 (defun js2-get-next-xml-token ()
5838 (setq js2-ts-string-buffer nil ; for recording the XML
5839 js2-token-beg js2-ts-cursor)
5840 (let (c result)
5841 (setq result
5842 (catch 'return
5843 (while t
5844 (setq c (js2-get-char))
5845 (cond
5846 ((= c js2-EOF_CHAR)
5847 (throw 'return js2-ERROR))
5848 (js2-ts-xml-is-tag-content
5849 (case c
5850 (?>
5851 (js2-add-to-string c)
5852 (setq js2-ts-xml-is-tag-content nil
5853 js2-ts-is-xml-attribute nil))
5854 (?/
5855 (js2-add-to-string c)
5856 (when (eq ?> (js2-peek-char))
5857 (setq c (js2-get-char))
5858 (js2-add-to-string c)
5859 (setq js2-ts-xml-is-tag-content nil)
5860 (decf js2-ts-xml-open-tags-count)))
5861 (?{
5862 (js2-unget-char)
5863 (setq js2-ts-string (js2-get-string-from-buffer))
5864 (throw 'return js2-XML))
5865 ((?\' ?\")
5866 (js2-add-to-string c)
5867 (unless (js2-read-quoted-string c)
5868 (throw 'return js2-ERROR)))
5869 (?=
5870 (js2-add-to-string c)
5871 (setq js2-ts-is-xml-attribute t))
5872 ((? ?\t ?\r ?\n)
5873 (js2-add-to-string c))
5874 (t
5875 (js2-add-to-string c)
5876 (setq js2-ts-is-xml-attribute nil)))
5877 (when (and (not js2-ts-xml-is-tag-content)
5878 (zerop js2-ts-xml-open-tags-count))
5879 (setq js2-ts-string (js2-get-string-from-buffer))
5880 (throw 'return js2-XMLEND)))
5881 (t
5882 ;; else not tag content
5883 (case c
5884 (?<
5885 (js2-add-to-string c)
5886 (setq c (js2-peek-char))
5887 (case c
5888 (?!
5889 (setq c (js2-get-char)) ;; skip !
5890 (js2-add-to-string c)
5891 (setq c (js2-peek-char))
5892 (case c
5893 (?-
5894 (setq c (js2-get-char)) ;; skip -
5895 (js2-add-to-string c)
5896 (if (eq c ?-)
5897 (progn
5898 (js2-add-to-string c)
5899 (unless (js2-read-xml-comment)
5900 (throw 'return js2-ERROR)))
5901 (js2-xml-discard-string)
5902 (throw 'return js2-ERROR)))
5903 (?\[
5904 (setq c (js2-get-char)) ;; skip [
5905 (js2-add-to-string c)
5906 (if (and (= (js2-get-char) ?C)
5907 (= (js2-get-char) ?D)
5908 (= (js2-get-char) ?A)
5909 (= (js2-get-char) ?T)
5910 (= (js2-get-char) ?A)
5911 (= (js2-get-char) ?\[))
5912 (progn
5913 (js2-add-to-string ?C)
5914 (js2-add-to-string ?D)
5915 (js2-add-to-string ?A)
5916 (js2-add-to-string ?T)
5917 (js2-add-to-string ?A)
5918 (js2-add-to-string ?\[)
5919 (unless (js2-read-cdata)
5920 (throw 'return js2-ERROR)))
5921 (js2-xml-discard-string)
5922 (throw 'return js2-ERROR)))
5923 (t
5924 (unless (js2-read-entity)
5925 (throw 'return js2-ERROR))))
5926 ;; Allow bare CDATA section, e.g.:
5927 ;; let xml = <![CDATA[ foo bar baz ]]>;
5928 (when (zerop js2-ts-xml-open-tags-count)
5929 (throw 'return js2-XMLEND)))
5930 (??
5931 (setq c (js2-get-char)) ;; skip ?
5932 (js2-add-to-string c)
5933 (unless (js2-read-PI)
5934 (throw 'return js2-ERROR)))
5935 (?/
5936 ;; end tag
5937 (setq c (js2-get-char)) ;; skip /
5938 (js2-add-to-string c)
5939 (when (zerop js2-ts-xml-open-tags-count)
5940 (js2-xml-discard-string)
5941 (throw 'return js2-ERROR))
5942 (setq js2-ts-xml-is-tag-content t)
5943 (decf js2-ts-xml-open-tags-count))
5944 (t
5945 ;; start tag
5946 (setq js2-ts-xml-is-tag-content t)
5947 (incf js2-ts-xml-open-tags-count))))
5948 (?{
5949 (js2-unget-char)
5950 (setq js2-ts-string (js2-get-string-from-buffer))
5951 (throw 'return js2-XML))
5952 (t
5953 (js2-add-to-string c))))))))
5954 (setq js2-token-end js2-ts-cursor)
5955 result))
5956
5957 (defun js2-read-quoted-string (quote)
5958 (let (c)
5959 (catch 'return
5960 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5961 (js2-add-to-string c)
5962 (if (eq c quote)
5963 (throw 'return t)))
5964 (js2-xml-discard-string) ;; throw away string in progress
5965 nil)))
5966
5967 (defun js2-read-xml-comment ()
5968 (let ((c (js2-get-char)))
5969 (catch 'return
5970 (while (/= c js2-EOF_CHAR)
5971 (catch 'continue
5972 (js2-add-to-string c)
5973 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5974 (setq c (js2-get-char))
5975 (js2-add-to-string c)
5976 (if (eq (js2-peek-char) ?>)
5977 (progn
5978 (setq c (js2-get-char)) ;; skip >
5979 (js2-add-to-string c)
5980 (throw 'return t))
5981 (throw 'continue nil)))
5982 (setq c (js2-get-char))))
5983 (js2-xml-discard-string)
5984 nil)))
5985
5986 (defun js2-read-cdata ()
5987 (let ((c (js2-get-char)))
5988 (catch 'return
5989 (while (/= c js2-EOF_CHAR)
5990 (catch 'continue
5991 (js2-add-to-string c)
5992 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5993 (setq c (js2-get-char))
5994 (js2-add-to-string c)
5995 (if (eq (js2-peek-char) ?>)
5996 (progn
5997 (setq c (js2-get-char)) ;; Skip >
5998 (js2-add-to-string c)
5999 (throw 'return t))
6000 (throw 'continue nil)))
6001 (setq c (js2-get-char))))
6002 (js2-xml-discard-string)
6003 nil)))
6004
6005 (defun js2-read-entity ()
6006 (let ((decl-tags 1)
6007 c)
6008 (catch 'return
6009 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6010 (js2-add-to-string c)
6011 (case c
6012 (?<
6013 (incf decl-tags))
6014 (?>
6015 (decf decl-tags)
6016 (if (zerop decl-tags)
6017 (throw 'return t)))))
6018 (js2-xml-discard-string)
6019 nil)))
6020
6021 (defun js2-read-PI ()
6022 "Scan an XML processing instruction."
6023 (let (c)
6024 (catch 'return
6025 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6026 (js2-add-to-string c)
6027 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6028 (setq c (js2-get-char)) ;; Skip >
6029 (js2-add-to-string c)
6030 (throw 'return t)))
6031 (js2-xml-discard-string)
6032 nil)))
6033
6034 (defun js2-scanner-get-line ()
6035 "Return the text of the current scan line."
6036 (buffer-substring (point-at-bol) (point-at-eol)))
6037
6038 ;;; Highlighting
6039
6040 (defun js2-set-face (beg end face &optional record)
6041 "Fontify a region. If RECORD is non-nil, record for later."
6042 (when (plusp js2-highlight-level)
6043 (setq beg (min (point-max) beg)
6044 beg (max (point-min) beg)
6045 end (min (point-max) end)
6046 end (max (point-min) end))
6047 (if record
6048 (push (list beg end face) js2-mode-fontifications)
6049 (put-text-property beg end 'font-lock-face face))))
6050
6051 (defun js2-set-kid-face (pos kid len face)
6052 "Set-face on a child node.
6053 POS is absolute buffer position of parent.
6054 KID is the child node.
6055 LEN is the length to fontify.
6056 FACE is the face to fontify with."
6057 (js2-set-face (+ pos (js2-node-pos kid))
6058 (+ pos (js2-node-pos kid) (js2-node-len kid))
6059 face))
6060
6061 (defsubst js2-fontify-kwd (start length)
6062 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6063
6064 (defsubst js2-clear-face (beg end)
6065 (remove-text-properties beg end '(font-lock-face nil
6066 help-echo nil
6067 point-entered nil
6068 c-in-sws nil)))
6069
6070 (defconst js2-ecma-global-props
6071 (concat "^"
6072 (regexp-opt
6073 '("Infinity" "NaN" "undefined" "arguments") t)
6074 "$")
6075 "Value properties of the Ecma-262 Global Object.
6076 Shown at or above `js2-highlight-level' 2.")
6077
6078 ;; might want to add the name "arguments" to this list?
6079 (defconst js2-ecma-object-props
6080 (concat "^"
6081 (regexp-opt
6082 '("prototype" "__proto__" "__parent__") t)
6083 "$")
6084 "Value properties of the Ecma-262 Object constructor.
6085 Shown at or above `js2-highlight-level' 2.")
6086
6087 (defconst js2-ecma-global-funcs
6088 (concat
6089 "^"
6090 (regexp-opt
6091 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6092 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6093 "$")
6094 "Function properties of the Ecma-262 Global object.
6095 Shown at or above `js2-highlight-level' 2.")
6096
6097 (defconst js2-ecma-number-props
6098 (concat "^"
6099 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6100 "NEGATIVE_INFINITY"
6101 "POSITIVE_INFINITY") t)
6102 "$")
6103 "Properties of the Ecma-262 Number constructor.
6104 Shown at or above `js2-highlight-level' 2.")
6105
6106 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6107 "Properties of the Ecma-262 Date constructor.
6108 Shown at or above `js2-highlight-level' 2.")
6109
6110 (defconst js2-ecma-math-props
6111 (concat "^"
6112 (regexp-opt
6113 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6114 t)
6115 "$")
6116 "Properties of the Ecma-262 Math object.
6117 Shown at or above `js2-highlight-level' 2.")
6118
6119 (defconst js2-ecma-math-funcs
6120 (concat "^"
6121 (regexp-opt
6122 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6123 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6124 "$")
6125 "Function properties of the Ecma-262 Math object.
6126 Shown at or above `js2-highlight-level' 2.")
6127
6128 (defconst js2-ecma-function-props
6129 (concat
6130 "^"
6131 (regexp-opt
6132 '(;; properties of the Object prototype object
6133 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6134 "toLocaleString" "toString" "valueOf"
6135 ;; properties of the Function prototype object
6136 "apply" "call"
6137 ;; properties of the Array prototype object
6138 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6139 "splice" "unshift"
6140 ;; properties of the String prototype object
6141 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6142 "localeCompare" "match" "replace" "search" "split" "substring"
6143 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6144 "toUpperCase"
6145 ;; properties of the Number prototype object
6146 "toExponential" "toFixed" "toPrecision"
6147 ;; properties of the Date prototype object
6148 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6149 "getMinutes" "getMonth" "getSeconds" "getTime"
6150 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6151 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6152 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6153 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6154 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6155 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6156 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6157 "toTimeString" "toUTCString"
6158 ;; properties of the RegExp prototype object
6159 "exec" "test"
6160 ;; properties of the JSON prototype object
6161 "parse" "stringify"
6162 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6163 "toSource" "__defineGetter__" "__defineSetter__"
6164 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6165 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6166 t)
6167 "$")
6168 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6169 Shown at or above `js2-highlight-level' 3.")
6170
6171 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6172 (let ((target-name (and target
6173 (js2-name-node-p target)
6174 (js2-name-node-name target)))
6175 (prop-name (if prop (js2-name-node-name prop)))
6176 (level1 (>= js2-highlight-level 1))
6177 (level2 (>= js2-highlight-level 2))
6178 (level3 (>= js2-highlight-level 3))
6179 pos face)
6180 (when level2
6181 (if call-p
6182 (cond
6183 ((and target prop)
6184 (cond
6185 ((and level3 (string-match js2-ecma-function-props prop-name))
6186 (setq face 'font-lock-builtin-face))
6187 ((and target-name prop)
6188 (cond
6189 ((string= target-name "Date")
6190 (if (string-match js2-ecma-date-props prop-name)
6191 (setq face 'font-lock-builtin-face)))
6192 ((string= target-name "Math")
6193 (if (string-match js2-ecma-math-funcs prop-name)
6194 (setq face 'font-lock-builtin-face)))))))
6195 (prop
6196 (if (string-match js2-ecma-global-funcs prop-name)
6197 (setq face 'font-lock-builtin-face))))
6198 (cond
6199 ((and target prop)
6200 (cond
6201 ((string= target-name "Number")
6202 (if (string-match js2-ecma-number-props prop-name)
6203 (setq face 'font-lock-constant-face)))
6204 ((string= target-name "Math")
6205 (if (string-match js2-ecma-math-props prop-name)
6206 (setq face 'font-lock-constant-face)))))
6207 (prop
6208 (if (string-match js2-ecma-object-props prop-name)
6209 (setq face 'font-lock-constant-face)))))
6210 (when face
6211 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6212 (js2-node-pos prop))) ; relative
6213 (+ pos (js2-node-len prop))
6214 face 'record)))))
6215
6216 (defun js2-parse-highlight-member-expr-node (node)
6217 "Perform syntax highlighting of EcmaScript built-in properties.
6218 The variable `js2-highlight-level' governs this highighting."
6219 (let (face target prop name pos end parent call-p callee)
6220 (cond
6221 ;; case 1: simple name, e.g. foo
6222 ((js2-name-node-p node)
6223 (setq name (js2-name-node-name node))
6224 ;; possible for name to be nil in rare cases - saw it when
6225 ;; running js2-mode on an elisp buffer. Might as well try to
6226 ;; make it so js2-mode never barfs.
6227 (when name
6228 (setq face (if (string-match js2-ecma-global-props name)
6229 'font-lock-constant-face))
6230 (when face
6231 (setq pos (js2-node-pos node)
6232 end (+ pos (js2-node-len node)))
6233 (js2-set-face pos end face 'record))))
6234 ;; case 2: property access or function call
6235 ((or (js2-prop-get-node-p node)
6236 ;; highlight function call if expr is a prop-get node
6237 ;; or a plain name (i.e. unqualified function call)
6238 (and (setq call-p (js2-call-node-p node))
6239 (setq callee (js2-call-node-target node)) ; separate setq!
6240 (or (js2-prop-get-node-p callee)
6241 (js2-name-node-p callee))))
6242 (setq parent node
6243 node (if call-p callee node))
6244 (if (and call-p (js2-name-node-p callee))
6245 (setq prop callee)
6246 (setq target (js2-prop-get-node-left node)
6247 prop (js2-prop-get-node-right node)))
6248 (cond
6249 ((js2-name-node-p target)
6250 (if (js2-name-node-p prop)
6251 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6252 (js2-parse-highlight-prop-get parent target prop call-p)
6253 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6254 (js2-parse-highlight-prop-get parent target nil call-p)))
6255 ((js2-name-node-p prop)
6256 ;; case 2c: complex target, simple name, e.g. x[y].bar
6257 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6258
6259 (defun js2-parse-highlight-member-expr-fn-name (expr)
6260 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6261 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6262 We currently only handle the case where the last component is a prop-get
6263 of a simple name. Called before EXPR has a parent node."
6264 (let (pos
6265 (name (and (js2-prop-get-node-p expr)
6266 (js2-prop-get-node-right expr))))
6267 (when (js2-name-node-p name)
6268 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6269 (js2-node-pos name)))
6270 (+ pos (js2-node-len name))
6271 'font-lock-function-name-face
6272 'record))))
6273
6274 ;; source: http://jsdoc.sourceforge.net/
6275 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6276 ;; allows type specifications, and needs work before entering the wild.
6277
6278 (defconst js2-jsdoc-param-tag-regexp
6279 (concat "^\\s-*\\*+\\s-*\\(@"
6280 "\\(?:param\\|argument\\)"
6281 "\\)"
6282 "\\s-*\\({[^}]+}\\)?" ; optional type
6283 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6284 "\\>")
6285 "Matches jsdoc tags with optional type and optional param name.")
6286
6287 (defconst js2-jsdoc-typed-tag-regexp
6288 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6289 (regexp-opt
6290 '("enum"
6291 "extends"
6292 "field"
6293 "id"
6294 "implements"
6295 "lends"
6296 "mods"
6297 "requires"
6298 "return"
6299 "returns"
6300 "throw"
6301 "throws"))
6302 "\\)\\)\\s-*\\({[^}]+}\\)?")
6303 "Matches jsdoc tags with optional type.")
6304
6305 (defconst js2-jsdoc-arg-tag-regexp
6306 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6307 (regexp-opt
6308 '("alias"
6309 "augments"
6310 "borrows"
6311 "bug"
6312 "base"
6313 "config"
6314 "default"
6315 "define"
6316 "exception"
6317 "function"
6318 "member"
6319 "memberOf"
6320 "name"
6321 "namespace"
6322 "property"
6323 "since"
6324 "suppress"
6325 "this"
6326 "throws"
6327 "type"
6328 "version"))
6329 "\\)\\)\\s-+\\([^ \t]+\\)")
6330 "Matches jsdoc tags with a single argument.")
6331
6332 (defconst js2-jsdoc-empty-tag-regexp
6333 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6334 (regexp-opt
6335 '("addon"
6336 "author"
6337 "class"
6338 "const"
6339 "constant"
6340 "constructor"
6341 "constructs"
6342 "deprecated"
6343 "desc"
6344 "description"
6345 "event"
6346 "example"
6347 "exec"
6348 "export"
6349 "fileoverview"
6350 "final"
6351 "function"
6352 "hidden"
6353 "ignore"
6354 "implicitCast"
6355 "inheritDoc"
6356 "inner"
6357 "interface"
6358 "license"
6359 "noalias"
6360 "noshadow"
6361 "notypecheck"
6362 "override"
6363 "owner"
6364 "preserve"
6365 "preserveTry"
6366 "private"
6367 "protected"
6368 "public"
6369 "static"
6370 "supported"
6371 ))
6372 "\\)\\)\\s-*")
6373 "Matches empty jsdoc tags.")
6374
6375 (defconst js2-jsdoc-link-tag-regexp
6376 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6377 "Matches a jsdoc link or code tag.")
6378
6379 (defconst js2-jsdoc-see-tag-regexp
6380 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6381 "Matches a jsdoc @see tag.")
6382
6383 (defconst js2-jsdoc-html-tag-regexp
6384 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6385 "Matches a simple (no attributes) html start- or end-tag.")
6386
6387 (defun js2-jsdoc-highlight-helper ()
6388 (js2-set-face (match-beginning 1)
6389 (match-end 1)
6390 'js2-jsdoc-tag)
6391 (if (match-beginning 2)
6392 (if (save-excursion
6393 (goto-char (match-beginning 2))
6394 (= (char-after) ?{))
6395 (js2-set-face (1+ (match-beginning 2))
6396 (1- (match-end 2))
6397 'js2-jsdoc-type)
6398 (js2-set-face (match-beginning 2)
6399 (match-end 2)
6400 'js2-jsdoc-value)))
6401 (if (match-beginning 3)
6402 (js2-set-face (match-beginning 3)
6403 (match-end 3)
6404 'js2-jsdoc-value)))
6405
6406 (defun js2-highlight-jsdoc (ast)
6407 "Highlight doc comment tags."
6408 (let ((comments (js2-ast-root-comments ast))
6409 beg end)
6410 (save-excursion
6411 (dolist (node comments)
6412 (when (eq (js2-comment-node-format node) 'jsdoc)
6413 (setq beg (js2-node-abs-pos node)
6414 end (+ beg (js2-node-len node)))
6415 (save-restriction
6416 (narrow-to-region beg end)
6417 (dolist (re (list js2-jsdoc-param-tag-regexp
6418 js2-jsdoc-typed-tag-regexp
6419 js2-jsdoc-arg-tag-regexp
6420 js2-jsdoc-link-tag-regexp
6421 js2-jsdoc-see-tag-regexp
6422 js2-jsdoc-empty-tag-regexp))
6423 (goto-char beg)
6424 (while (re-search-forward re nil t)
6425 (js2-jsdoc-highlight-helper)))
6426 ;; simple highlighting for html tags
6427 (goto-char beg)
6428 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6429 (js2-set-face (match-beginning 1)
6430 (match-end 1)
6431 'js2-jsdoc-html-tag-delimiter)
6432 (js2-set-face (match-beginning 2)
6433 (match-end 2)
6434 'js2-jsdoc-html-tag-name)
6435 (js2-set-face (match-beginning 3)
6436 (match-end 3)
6437 'js2-jsdoc-html-tag-delimiter))))))))
6438
6439 (defun js2-highlight-assign-targets (node left right)
6440 "Highlight function properties and external variables."
6441 (let (leftpos end name)
6442 ;; highlight vars and props assigned function values
6443 (when (js2-function-node-p right)
6444 (cond
6445 ;; var foo = function() {...}
6446 ((js2-name-node-p left)
6447 (setq name left))
6448 ;; foo.bar.baz = function() {...}
6449 ((and (js2-prop-get-node-p left)
6450 (js2-name-node-p (js2-prop-get-node-right left)))
6451 (setq name (js2-prop-get-node-right left))))
6452 (when name
6453 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6454 (+ leftpos (js2-node-len name))
6455 'font-lock-function-name-face
6456 'record)))))
6457
6458 (defun js2-record-name-node (node)
6459 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6460 later. NODE must be a name node."
6461 (let (leftpos end)
6462 (push (list node js2-current-scope
6463 (setq leftpos (js2-node-abs-pos node))
6464 (setq end (+ leftpos (js2-node-len node))))
6465 js2-recorded-identifiers)))
6466
6467 (defun js2-highlight-undeclared-vars ()
6468 "After entire parse is finished, look for undeclared variable references.
6469 We have to wait until entire buffer is parsed, since JavaScript permits var
6470 decls to occur after they're used.
6471
6472 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6473 it is considered declared."
6474 (let (name)
6475 (dolist (entry js2-recorded-identifiers)
6476 (destructuring-bind (name-node scope pos end) entry
6477 (setq name (js2-name-node-name name-node))
6478 (unless (or (member name js2-global-externs)
6479 (member name js2-default-externs)
6480 (member name js2-additional-externs)
6481 (js2-get-defining-scope scope name))
6482 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6483 'js2-external-variable))))
6484 (setq js2-recorded-identifiers nil)))
6485
6486 ;;; IMenu support
6487
6488 ;; We currently only support imenu, but eventually should support speedbar and
6489 ;; possibly other browsing mechanisms.
6490
6491 ;; The basic strategy is to identify function assignment targets of the form
6492 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6493 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6494 ;; for imenu after parsing is finished.
6495
6496 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6497 ;; JavaScript, and the general problem is undecidable. However, several forms
6498 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6499 ;; include:
6500
6501 ;; function foo() -- function declaration
6502 ;; foo = function() -- function expression assigned to variable
6503 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6504 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6505 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6506 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6507 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6508 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6509 ;; function foo() {function bar() {...}} -- nested function
6510 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6511
6512 ;; This list boils down to a few forms that can be combined recursively.
6513 ;; Top-level named function declarations include both the left-hand (name)
6514 ;; and the right-hand (function value) expressions needed to produce an imenu
6515 ;; entry. The other "right-hand" forms we need to look for are:
6516 ;; - functions declared as props/getters/setters in object literals
6517 ;; - nested named function declarations
6518 ;; The "left-hand" expressions that functions can be assigned to include:
6519 ;; - local/global variables
6520 ;; - nested property-get expressions like a.b.c.d
6521 ;; - element gets like foo[10] or foo['bar'] where the index
6522 ;; expression can be trivially converted to a property name. They
6523 ;; effectively then become property gets.
6524
6525 ;; All the different definition types are canonicalized into the form
6526 ;; foo.bar.baz = position-of-function-keyword
6527
6528 ;; We need to build a trie-like structure for imenu. As an example,
6529 ;; consider the following JavaScript code:
6530
6531 ;; a = function() {...} // function at position 5
6532 ;; b = function() {...} // function at position 25
6533 ;; foo = function() {...} // function at position 100
6534 ;; foo.bar = function() {...} // function at position 200
6535 ;; foo.bar.baz = function() {...} // function at position 300
6536 ;; foo.bar.zab = function() {...} // function at position 400
6537
6538 ;; During parsing we accumulate an entry for each definition in
6539 ;; the variable `js2-imenu-recorder', like so:
6540
6541 ;; '((fn a 5)
6542 ;; (fn b 25)
6543 ;; (fn foo 100)
6544 ;; (fn foo bar 200)
6545 ;; (fn foo bar baz 300)
6546 ;; (fn foo bar zab 400))
6547
6548 ;; Where 'fn' is the respective function node.
6549 ;; After parsing these entries are merged into this alist-trie:
6550
6551 ;; '((a . 1)
6552 ;; (b . 2)
6553 ;; (foo (<definition> . 3)
6554 ;; (bar (<definition> . 6)
6555 ;; (baz . 100)
6556 ;; (zab . 200))))
6557
6558 ;; Note the wacky need for a <definition> name. The token can be anything
6559 ;; that isn't a valid JavaScript identifier, because you might make foo
6560 ;; a function and then start setting properties on it that are also functions.
6561
6562 (defun js2-prop-node-name (node)
6563 "Return the name of a node that may be a property-get/property-name.
6564 If NODE is not a valid name-node, string-node or integral number-node,
6565 returns nil. Otherwise returns the string name/value of the node."
6566 (cond
6567 ((js2-name-node-p node)
6568 (js2-name-node-name node))
6569 ((js2-string-node-p node)
6570 (js2-string-node-value node))
6571 ((and (js2-number-node-p node)
6572 (string-match "^[0-9]+$" (js2-number-node-value node)))
6573 (js2-number-node-value node))
6574 ((js2-this-node-p node)
6575 "this")))
6576
6577 (defun js2-node-qname-component (node)
6578 "Return the name of this node, if it contributes to a qname.
6579 Returns nil if the node doesn't contribute."
6580 (copy-sequence
6581 (or (js2-prop-node-name node)
6582 (if (and (js2-function-node-p node)
6583 (js2-function-node-name node))
6584 (js2-name-node-name (js2-function-node-name node))))))
6585
6586 (defun js2-record-imenu-entry (fn-node qname pos)
6587 "Add an entry to `js2-imenu-recorder'.
6588 FN-NODE should be the current item's function node.
6589
6590 Associate FN-NODE with its QNAME for later lookup.
6591 This is used in postprocessing the chain list. For each chain, we find
6592 the parent function, look up its qname, then prepend a copy of it to the chain."
6593 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6594 (unless js2-imenu-function-map
6595 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6596 (puthash fn-node qname js2-imenu-function-map))
6597
6598 (defun js2-record-imenu-functions (node &optional var)
6599 "Record function definitions for imenu.
6600 NODE is a function node or an object literal.
6601 VAR, if non-nil, is the expression that NODE is being assigned to.
6602 When passed arguments of wrong type, does nothing."
6603 (when js2-parse-ide-mode
6604 (let ((fun-p (js2-function-node-p node))
6605 qname left fname-node pos)
6606 (cond
6607 ;; non-anonymous function declaration?
6608 ((and fun-p
6609 (not var)
6610 (setq fname-node (js2-function-node-name node)))
6611 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6612 ;; for remaining forms, compute left-side tree branch first
6613 ((and var (setq qname (js2-compute-nested-prop-get var)))
6614 (cond
6615 ;; foo.bar.baz = function
6616 (fun-p
6617 (js2-record-imenu-entry node qname (js2-node-pos node)))
6618 ;; foo.bar.baz = object-literal
6619 ;; look for nested functions: {a: {b: function() {...} }}
6620 ((js2-object-node-p node)
6621 ;; Node position here is still absolute, since the parser
6622 ;; passes the assignment target and value expressions
6623 ;; to us before they are added as children of the assignment node.
6624 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6625
6626 (defun js2-compute-nested-prop-get (node)
6627 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6628 component nodes as a list. Otherwise return nil. Element-gets are treated
6629 as property-gets if the index expression is a string, or a positive integer."
6630 (let (left right head)
6631 (cond
6632 ((or (js2-name-node-p node)
6633 (js2-this-node-p node))
6634 (list node))
6635 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6636 ((js2-prop-get-node-p node) ; foo.bar
6637 (setq left (js2-prop-get-node-left node)
6638 right (js2-prop-get-node-right node))
6639 (if (setq head (js2-compute-nested-prop-get left))
6640 (nconc head (list right))))
6641 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6642 (setq left (js2-elem-get-node-target node)
6643 right (js2-elem-get-node-element node))
6644 (if (or (js2-string-node-p right) ; ['bar']
6645 (and (js2-number-node-p right) ; [10]
6646 (string-match "^[0-9]+$"
6647 (js2-number-node-value right))))
6648 (if (setq head (js2-compute-nested-prop-get left))
6649 (nconc head (list right))))))))
6650
6651 (defun js2-record-object-literal (node qname pos)
6652 "Recursively process an object literal looking for functions.
6653 NODE is an object literal that is the right-hand child of an assignment
6654 expression. QNAME is a list of nodes representing the assignment target,
6655 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6656 POS is the absolute position of the node.
6657 We do a depth-first traversal of NODE. For any functions we find,
6658 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6659 (let (left right prop-qname)
6660 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6661 (let ((left (js2-infix-node-left e))
6662 ;; Element positions are relative to the parent position.
6663 (pos (+ pos (js2-node-pos e))))
6664 (cond
6665 ;; foo: function() {...}
6666 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6667 (when (js2-prop-node-name left)
6668 ;; As a policy decision, we record the position of the property,
6669 ;; not the position of the `function' keyword, since the property
6670 ;; is effectively the name of the function.
6671 (js2-record-imenu-entry right (append qname (list left)) pos)))
6672 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6673 ((js2-object-node-p right)
6674 (js2-record-object-literal right
6675 (append qname (list (js2-infix-node-left e)))
6676 (+ pos (js2-node-pos right)))))))))
6677
6678 (defun js2-node-top-level-decl-p (node)
6679 "Return t if NODE's name is defined in the top-level scope.
6680 Also returns t if NODE's name is not defined in any scope, since it implies
6681 that it's an external variable, which must also be in the top-level scope."
6682 (let* ((name (js2-prop-node-name node))
6683 (this-scope (js2-node-get-enclosing-scope node))
6684 defining-scope)
6685 (cond
6686 ((js2-this-node-p node)
6687 nil)
6688 ((null this-scope)
6689 t)
6690 ((setq defining-scope (js2-get-defining-scope this-scope name))
6691 (js2-ast-root-p defining-scope))
6692 (t t))))
6693
6694 (defun js2-wrapper-function-p (node)
6695 "Return t if NODE is a function expression that's immediately invoked.
6696 NODE must be `js2-function-node'."
6697 (let ((parent (js2-node-parent node)))
6698 (or
6699 ;; function(){...}();
6700 (js2-call-node-p parent)
6701 (and (js2-paren-node-p parent)
6702 ;; (function(){...})();
6703 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6704 ;; (function(){...}).call(this);
6705 (and (js2-prop-get-node-p parent)
6706 (member (js2-name-node-name (js2-prop-get-node-right parent))
6707 '("call" "apply"))
6708 (js2-call-node-p (js2-node-parent parent))))))))
6709
6710 (defun js2-browse-postprocess-chains (entries)
6711 "Modify function-declaration name chains after parsing finishes.
6712 Some of the information is only available after the parse tree is complete.
6713 For instance, processing a nested scope requires a parent function node."
6714 (let (result head fn current-fn parent-qname qname p elem)
6715 (dolist (entry entries)
6716 ;; function node goes first
6717 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6718 ;; Examine head's defining scope:
6719 ;; Pre-processed chain, or top-level/external, keep as-is.
6720 (if (or (stringp head) (js2-node-top-level-decl-p head))
6721 (push chain result)
6722 (when (js2-this-node-p head)
6723 (setq chain (cdr chain))) ; discard this-node
6724 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6725 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6726 (when (eq parent-qname 'not-found)
6727 ;; anonymous function expressions are not recorded
6728 ;; during the parse, so we need to handle this case here
6729 (setq parent-qname
6730 (if (js2-wrapper-function-p fn)
6731 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6732 (if (js2-ast-root-p grandparent)
6733 nil
6734 (gethash grandparent js2-imenu-function-map 'skip)))
6735 'skip))
6736 (puthash fn parent-qname js2-imenu-function-map))
6737 (unless (eq parent-qname 'skip)
6738 ;; prefix parent fn qname to this chain.
6739 (let ((qname (append parent-qname chain)))
6740 (puthash current-fn (butlast qname) js2-imenu-function-map)
6741 (push qname result)))))))
6742 ;; finally replace each node in each chain with its name.
6743 (dolist (chain result)
6744 (setq p chain)
6745 (while p
6746 (if (js2-node-p (setq elem (car p)))
6747 (setcar p (js2-node-qname-component elem)))
6748 (setq p (cdr p))))
6749 result))
6750
6751 ;; Merge name chains into a trie-like tree structure of nested lists.
6752 ;; To simplify construction of the trie, we first build it out using the rule
6753 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6754 ;; [key, num-or-list]. The second element can be a number; if so, this key
6755 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6756 ;; associated with the key at this level.) Otherwise the second element is
6757 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6758 ;; a simple recursive formulation.
6759 ;;
6760 ;; js2-mode is building the data structure for imenu. The imenu documentation
6761 ;; claims that it's the structure above, but in practice it wants the children
6762 ;; at the same list level as the key for that level, which is how I've drawn
6763 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6764 ;; list wrapper around the children at each level.
6765 ;;
6766 ;; A completed nested imenu-alist entry looks like this:
6767 ;; '(("foo"
6768 ;; ("<definition>" . 7)
6769 ;; ("bar"
6770 ;; ("a" . 40)
6771 ;; ("b" . 60))))
6772 ;;
6773 ;; In particular, the documentation for `imenu--index-alist' says that
6774 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6775 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6776
6777 (defun js2-treeify (lst)
6778 "Convert (a b c d) to (a ((b ((c d)))))."
6779 (if (null (cddr lst)) ; list length <= 2
6780 lst
6781 (list (car lst) (list (js2-treeify (cdr lst))))))
6782
6783 (defun js2-build-alist-trie (chains trie)
6784 "Merge declaration name chains into a trie-like alist structure for imenu.
6785 CHAINS is the qname chain list produced during parsing. TRIE is a
6786 list of elements built up so far."
6787 (let (head tail pos branch kids)
6788 (dolist (chain chains)
6789 (setq head (car chain)
6790 tail (cdr chain)
6791 pos (if (numberp (car tail)) (car tail))
6792 branch (js2-find-if (lambda (n)
6793 (string= (car n) head))
6794 trie)
6795 kids (second branch))
6796 (cond
6797 ;; case 1: this key isn't in the trie yet
6798 ((null branch)
6799 (if trie
6800 (setcdr (last trie) (list (js2-treeify chain)))
6801 (setq trie (list (js2-treeify chain)))))
6802 ;; case 2: key is present with a single number entry: replace w/ list
6803 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6804 ;; ("<definition>" 20)))
6805 ((numberp kids)
6806 (setcar (cdr branch)
6807 (list (list "<definition-1>" kids)
6808 (if pos
6809 (list "<definition-2>" pos)
6810 (js2-treeify tail)))))
6811 ;; case 3: key is there (with kids), and we're a number entry
6812 (pos
6813 (setcdr (last kids)
6814 (list
6815 (list (format "<definition-%d>"
6816 (1+ (loop for kid in kids
6817 count (eq ?< (aref (car kid) 0)))))
6818 pos))))
6819 ;; case 4: key is there with kids, need to merge in our chain
6820 (t
6821 (js2-build-alist-trie (list tail) kids))))
6822 trie))
6823
6824 (defun js2-flatten-trie (trie)
6825 "Convert TRIE to imenu-format.
6826 Recurses through nodes, and for each one whose second element is a list,
6827 appends the list's flattened elements to the current element. Also
6828 changes the tails into conses. For instance, this pre-flattened trie
6829
6830 '(a ((b 20)
6831 (c ((d 30)
6832 (e 40)))))
6833
6834 becomes
6835
6836 '(a (b . 20)
6837 (c (d . 30)
6838 (e . 40)))
6839
6840 Note that the root of the trie has no key, just a list of chains.
6841 This is also true for the value of any key with multiple children,
6842 e.g. key 'c' in the example above."
6843 (cond
6844 ((listp (car trie))
6845 (mapcar #'js2-flatten-trie trie))
6846 (t
6847 (if (numberp (second trie))
6848 (cons (car trie) (second trie))
6849 ;; else pop list and append its kids
6850 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6851
6852 (defun js2-build-imenu-index ()
6853 "Turn `js2-imenu-recorder' into an imenu data structure."
6854 (unless (eq js2-imenu-recorder 'empty)
6855 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6856 (result (js2-build-alist-trie chains nil)))
6857 (js2-flatten-trie result))))
6858
6859 (defun js2-test-print-chains (chains)
6860 "Print a list of qname chains.
6861 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6862 i.e. one or more nodes, and an integer position as the list tail."
6863 (mapconcat (lambda (chain)
6864 (concat "("
6865 (mapconcat (lambda (elem)
6866 (if (js2-node-p elem)
6867 (or (js2-node-qname-component elem)
6868 "nil")
6869 (number-to-string elem)))
6870 chain
6871 " ")
6872 ")"))
6873 chains
6874 "\n"))
6875
6876 ;;; Parser
6877
6878 (defconst js2-version "1.8.5"
6879 "Version of JavaScript supported.")
6880
6881 (defmacro js2-record-face (face)
6882 "Record a style run of FACE for the current token."
6883 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6884
6885 (defsubst js2-node-end (n)
6886 "Computes the absolute end of node N.
6887 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6888 is only true until the node is added to its parent; i.e., while parsing."
6889 (+ (js2-node-pos n)
6890 (js2-node-len n)))
6891
6892 (defun js2-record-comment ()
6893 "Record a comment in `js2-scanned-comments'."
6894 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6895 :format js2-ts-comment-type)
6896 js2-scanned-comments)
6897 (when js2-parse-ide-mode
6898 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6899 'font-lock-doc-face
6900 'font-lock-comment-face))
6901 (when (memq js2-ts-comment-type '(html preprocessor))
6902 ;; Tell cc-engine the bounds of the comment.
6903 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6904
6905 ;; This function is called depressingly often, so it should be fast.
6906 ;; Most of the time it's looking at the same token it peeked before.
6907 (defun js2-peek-token ()
6908 "Return the next token without consuming it.
6909 If previous token was consumed, calls scanner to get new token.
6910 If previous token was -not- consumed, returns it (idempotent).
6911
6912 This function will not return a newline (js2-EOL) - instead, it
6913 gobbles newlines until it finds a non-newline token, and flags
6914 that token as appearing just after a newline.
6915
6916 This function will also not return a js2-COMMENT. Instead, it
6917 records comments found in `js2-scanned-comments'. If the token
6918 returned by this function immediately follows a jsdoc comment,
6919 the token is flagged as such.
6920
6921 Note that this function always returned the un-flagged token!
6922 The flags, if any, are saved in `js2-current-flagged-token'."
6923 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6924 js2-current-token ; most common case - return already-peeked token
6925 (let ((tt (js2-get-token)) ; call scanner
6926 saw-eol
6927 face)
6928 ;; process comments and whitespace
6929 (while (or (= tt js2-EOL)
6930 (= tt js2-COMMENT))
6931 (if (= tt js2-EOL)
6932 (setq saw-eol t)
6933 (setq saw-eol nil)
6934 (if js2-record-comments
6935 (js2-record-comment)))
6936 (setq tt (js2-get-token))) ; call scanner
6937 (setq js2-current-token tt
6938 js2-current-flagged-token (if saw-eol
6939 (logior tt js2-ti-after-eol)
6940 tt))
6941 ;; perform lexical fontification as soon as token is scanned
6942 (when js2-parse-ide-mode
6943 (cond
6944 ((minusp tt)
6945 (js2-record-face 'js2-error))
6946 ((setq face (aref js2-kwd-tokens tt))
6947 (js2-record-face face))
6948 ((and (= tt js2-NAME)
6949 (equal js2-ts-string "undefined"))
6950 (js2-record-face 'font-lock-constant-face))))
6951 tt))) ; return unflagged token
6952
6953 (defun js2-peek-flagged-token ()
6954 "Return the current token along with any flags set for it."
6955 (js2-peek-token)
6956 js2-current-flagged-token)
6957
6958 (defsubst js2-consume-token ()
6959 (setq js2-current-flagged-token js2-EOF))
6960
6961 (defun js2-next-token ()
6962 (prog1
6963 (js2-peek-token)
6964 (js2-consume-token)))
6965
6966 (defun js2-next-flagged-token ()
6967 (js2-peek-token)
6968 (prog1 js2-current-flagged-token
6969 (js2-consume-token)))
6970
6971 (defun js2-match-token (match)
6972 "Consume and return t if next token matches MATCH, a bytecode.
6973 Returns nil and consumes nothing if MATCH is not the next token."
6974 (if (/= (js2-peek-token) match)
6975 nil
6976 (js2-consume-token)
6977 t))
6978
6979 (defun js2-match-contextual-kwd (name)
6980 "Consume and return t if next token is `js2-NAME', and its
6981 string is NAME. Returns nil and does nothing otherwise."
6982 (if (or (/= (js2-peek-token) js2-NAME)
6983 (not (string= js2-ts-string name)))
6984 nil
6985 (js2-consume-token)
6986 (js2-record-face 'font-lock-keyword-face)
6987 t))
6988
6989 (defun js2-valid-prop-name-token (tt)
6990 (or (= tt js2-NAME)
6991 (when (and js2-allow-keywords-as-property-names
6992 (plusp tt)
6993 (aref js2-kwd-tokens tt))
6994 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6995 t)))
6996
6997 (defun js2-match-prop-name ()
6998 "Consume token and return t if next token is a valid property name.
6999 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7000 is non-nil and it's a keyword token."
7001 (if (js2-valid-prop-name-token (js2-peek-token))
7002 (progn
7003 (js2-consume-token)
7004 t)
7005 nil))
7006
7007 (defun js2-must-match-prop-name (msg-id &optional pos len)
7008 (if (js2-match-prop-name)
7009 t
7010 (js2-report-error msg-id nil pos len)
7011 nil))
7012
7013 (defun js2-peek-token-or-eol ()
7014 "Return js2-EOL if the current token immediately follows a newline.
7015 Else returns the current token. Used in situations where we don't
7016 consider certain token types valid if they are preceded by a newline.
7017 One example is the postfix ++ or -- operator, which has to be on the
7018 same line as its operand."
7019 (let ((tt (js2-peek-token)))
7020 ;; Check for last peeked token flags
7021 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7022 js2-EOL
7023 tt)))
7024
7025 (defun js2-set-check-for-label ()
7026 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7027 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7028
7029 (defun js2-must-match (token msg-id &optional pos len)
7030 "Match next token to token code TOKEN, or record a syntax error.
7031 MSG-ID is the error message to report if the match fails.
7032 Returns t on match, nil if no match."
7033 (if (js2-match-token token)
7034 t
7035 (js2-report-error msg-id nil pos len)
7036 nil))
7037
7038 (defsubst js2-inside-function ()
7039 (plusp js2-nesting-of-function))
7040
7041 (defun js2-set-requires-activation ()
7042 (if (js2-function-node-p js2-current-script-or-fn)
7043 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7044
7045 (defun js2-check-activation-name (name token)
7046 (when (js2-inside-function)
7047 ;; skip language-version 1.2 check from Rhino
7048 (if (or (string= "arguments" name)
7049 (and js2-compiler-activation-names ; only used in codegen
7050 (gethash name js2-compiler-activation-names)))
7051 (js2-set-requires-activation))))
7052
7053 (defun js2-set-is-generator ()
7054 (if (js2-function-node-p js2-current-script-or-fn)
7055 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7056
7057 (defun js2-must-have-xml ()
7058 (unless js2-compiler-xml-available
7059 (js2-report-error "msg.XML.not.available")))
7060
7061 (defun js2-push-scope (scope)
7062 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7063 (assert (js2-scope-p scope))
7064 (assert (null (js2-scope-parent-scope scope)))
7065 (assert (not (eq js2-current-scope scope)))
7066 (setf (js2-scope-parent-scope scope) js2-current-scope
7067 js2-current-scope scope))
7068
7069 (defsubst js2-pop-scope ()
7070 (setq js2-current-scope
7071 (js2-scope-parent-scope js2-current-scope)))
7072
7073 (defun js2-enter-loop (loop-node)
7074 (push loop-node js2-loop-set)
7075 (push loop-node js2-loop-and-switch-set)
7076 (js2-push-scope loop-node)
7077 ;; Tell the current labeled statement (if any) its statement,
7078 ;; and set the jump target of the first label to the loop.
7079 ;; These are used in `js2-parse-continue' to verify that the
7080 ;; continue target is an actual labeled loop. (And for codegen.)
7081 (when js2-labeled-stmt
7082 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7083 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7084 js2-labeled-stmt))) loop-node)))
7085
7086 (defun js2-exit-loop ()
7087 (pop js2-loop-set)
7088 (pop js2-loop-and-switch-set)
7089 (js2-pop-scope))
7090
7091 (defsubst js2-enter-switch (switch-node)
7092 (push switch-node js2-loop-and-switch-set))
7093
7094 (defsubst js2-exit-switch ()
7095 (pop js2-loop-and-switch-set))
7096
7097 (defun js2-parse (&optional buf cb)
7098 "Tell the js2 parser to parse a region of JavaScript.
7099
7100 BUF is a buffer or buffer name containing the code to parse.
7101 Call `narrow-to-region' first to parse only part of the buffer.
7102
7103 The returned AST root node is given some additional properties:
7104 `node-count' - total number of nodes in the AST
7105 `buffer' - BUF. The buffer it refers to may change or be killed,
7106 so the value is not necessarily reliable.
7107
7108 An optional callback CB can be specified to report parsing
7109 progress. If `(functionp CB)' returns t, it will be called with
7110 the current line number once before parsing begins, then again
7111 each time the lexer reaches a new line number.
7112
7113 CB can also be a list of the form `(symbol cb ...)' to specify
7114 multiple callbacks with different criteria. Each symbol is a
7115 criterion keyword, and the following element is the callback to
7116 call
7117
7118 :line - called whenever the line number changes
7119 :token - called for each new token consumed
7120
7121 The list of criteria could be extended to include entering or
7122 leaving a statement, an expression, or a function definition."
7123 (if (and cb (not (functionp cb)))
7124 (error "criteria callbacks not yet implemented"))
7125 (let ((inhibit-point-motion-hooks t)
7126 (js2-compiler-xml-available (>= js2-language-version 160))
7127 ;; This is a recursive-descent parser, so give it a big stack.
7128 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7129 (max-specpdl-size (max max-specpdl-size 3000))
7130 (case-fold-search nil)
7131 ast)
7132 (message nil) ; clear any error message from previous parse
7133 (with-current-buffer (or buf (current-buffer))
7134 (setq js2-scanned-comments nil
7135 js2-parsed-errors nil
7136 js2-parsed-warnings nil
7137 js2-imenu-recorder nil
7138 js2-imenu-function-map nil
7139 js2-label-set nil)
7140 (js2-init-scanner)
7141 (setq ast (with-silent-modifications
7142 (js2-do-parse)))
7143 (unless js2-ts-hit-eof
7144 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7145 (setf (js2-ast-root-errors ast) js2-parsed-errors
7146 (js2-ast-root-warnings ast) js2-parsed-warnings)
7147 ;; if we didn't find any declarations, put a dummy in this list so we
7148 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7149 (unless js2-imenu-recorder
7150 (setq js2-imenu-recorder 'empty))
7151 (run-hooks 'js2-parse-finished-hook)
7152 ast)))
7153
7154 ;; Corresponds to Rhino's Parser.parse() method.
7155 (defun js2-do-parse ()
7156 "Parse current buffer starting from current point.
7157 Scanner should be initialized."
7158 (let ((pos js2-ts-cursor)
7159 (end js2-ts-cursor) ; in case file is empty
7160 root n tt)
7161 ;; initialize buffer-local parsing vars
7162 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7163 js2-current-script-or-fn root
7164 js2-current-scope root
7165 js2-current-flagged-token js2-EOF
7166 js2-nesting-of-function 0
7167 js2-labeled-stmt nil
7168 js2-recorded-identifiers nil) ; for js2-highlight
7169 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7170 (if (= tt js2-FUNCTION)
7171 (progn
7172 (js2-consume-token)
7173 (setq n (js2-parse-function (if js2-called-by-compile-function
7174 'FUNCTION_EXPRESSION
7175 'FUNCTION_STATEMENT))))
7176 ;; not a function - parse a statement
7177 (setq n (js2-parse-statement)))
7178 ;; add function or statement to script
7179 (setq end (js2-node-end n))
7180 (js2-block-node-push root n))
7181 ;; add comments to root in lexical order
7182 (when js2-scanned-comments
7183 ;; if we find a comment beyond end of normal kids, use its end
7184 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7185 (dolist (comment js2-scanned-comments)
7186 (push comment (js2-ast-root-comments root))
7187 (js2-node-add-children root comment)))
7188 (setf (js2-node-len root) (- end pos))
7189 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7190 ;; Give extensions a chance to muck with things before highlighting starts.
7191 (let ((js2-additional-externs js2-additional-externs))
7192 (save-excursion
7193 (dolist (callback js2-post-parse-callbacks)
7194 (funcall callback)))
7195 (js2-highlight-undeclared-vars))
7196 root))
7197
7198 (defun js2-function-parser ()
7199 (js2-consume-token)
7200 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7201
7202 (defun js2-parse-function-closure-body (fn-node)
7203 "Parse a JavaScript 1.8 function closure body."
7204 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7205 (if js2-ts-hit-eof
7206 (js2-report-error "msg.no.brace.body" nil
7207 (js2-node-pos fn-node)
7208 (- js2-ts-cursor (js2-node-pos fn-node)))
7209 (js2-node-add-children fn-node
7210 (setf (js2-function-node-body fn-node)
7211 (js2-parse-expr t))))))
7212
7213 (defun js2-parse-function-body (fn-node)
7214 (js2-must-match js2-LC "msg.no.brace.body"
7215 (js2-node-pos fn-node)
7216 (- js2-ts-cursor (js2-node-pos fn-node)))
7217 (let ((pos js2-token-beg) ; LC position
7218 (pn (make-js2-block-node)) ; starts at LC position
7219 tt
7220 end)
7221 (incf js2-nesting-of-function)
7222 (unwind-protect
7223 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7224 (= tt js2-EOF)
7225 (= tt js2-RC)))
7226 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7227 (js2-parse-statement)
7228 (js2-consume-token)
7229 (js2-parse-function 'FUNCTION_STATEMENT))))
7230 (decf js2-nesting-of-function))
7231 (setq end js2-token-end) ; assume no curly and leave at current token
7232 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7233 (setq end js2-token-end))
7234 (setf (js2-node-pos pn) pos
7235 (js2-node-len pn) (- end pos))
7236 (setf (js2-function-node-body fn-node) pn)
7237 (js2-node-add-children fn-node pn)
7238 pn))
7239
7240 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7241 "Declare and fontify destructuring parameters inside NODE.
7242 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7243 (cond
7244 ((js2-name-node-p node)
7245 (let (leftpos)
7246 (js2-define-symbol decl-type (js2-name-node-name node)
7247 node ignore-not-in-block)
7248 (when face
7249 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7250 (+ leftpos (js2-node-len node))
7251 face 'record))))
7252 ((js2-object-node-p node)
7253 (dolist (elem (js2-object-node-elems node))
7254 (js2-define-destruct-symbols
7255 (if (js2-object-prop-node-p elem)
7256 (js2-object-prop-node-right elem)
7257 ;; abbreviated destructuring {a, b}
7258 elem)
7259 decl-type face ignore-not-in-block)))
7260 ((js2-array-node-p node)
7261 (dolist (elem (js2-array-node-elems node))
7262 (when elem
7263 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7264 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7265 (js2-node-len node)))))
7266
7267 (defun js2-parse-function-params (fn-node pos)
7268 (if (js2-match-token js2-RP)
7269 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7270 (let (params len param default-found rest-param-at)
7271 (loop for tt = (js2-peek-token)
7272 do
7273 (cond
7274 ;; destructuring param
7275 ((or (= tt js2-LB) (= tt js2-LC))
7276 (when default-found
7277 (js2-report-error "msg.no.default.after.default.param"))
7278 (setq param (js2-parse-destruct-primary-expr))
7279 (js2-define-destruct-symbols param
7280 js2-LP
7281 'js2-function-param)
7282 (push param params))
7283 ;; variable name
7284 (t
7285 (when (and (>= js2-language-version 200)
7286 (js2-match-token js2-TRIPLEDOT)
7287 (not rest-param-at))
7288 ;; to report errors if there are more parameters
7289 (setq rest-param-at (length params)))
7290 (js2-must-match js2-NAME "msg.no.parm")
7291 (js2-record-face 'js2-function-param)
7292 (setq param (js2-create-name-node))
7293 (js2-define-symbol js2-LP js2-ts-string param)
7294 ;; default parameter value
7295 (when (or (and default-found
7296 (not rest-param-at)
7297 (js2-must-match js2-ASSIGN
7298 "msg.no.default.after.default.param"
7299 (js2-node-pos param)
7300 (js2-node-len param)))
7301 (and (>= js2-language-version 200)
7302 (js2-match-token js2-ASSIGN)))
7303 (let* ((pos (js2-node-pos param))
7304 (tt js2-current-token)
7305 (op-pos (- js2-token-beg pos))
7306 (left param)
7307 (right (js2-parse-assign-expr))
7308 (len (- (js2-node-end right) pos)))
7309 (setq param (make-js2-assign-node
7310 :type tt :pos pos :len len :op-pos op-pos
7311 :left left :right right)
7312 default-found t)
7313 (js2-node-add-children param left right)))
7314 (push param params)))
7315 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7316 (js2-report-error "msg.param.after.rest" nil
7317 (js2-node-pos param) (js2-node-len param)))
7318 while
7319 (js2-match-token js2-COMMA))
7320 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7321 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7322 (when rest-param-at
7323 (setf (js2-function-node-rest-p fn-node) t))
7324 (dolist (p params)
7325 (js2-node-add-children fn-node p)
7326 (push p (js2-function-node-params fn-node))))))
7327
7328 (defun js2-check-inconsistent-return-warning (fn-node name)
7329 "Possibly show inconsistent-return warning.
7330 Last token scanned is the close-curly for the function body."
7331 (when (and js2-mode-show-strict-warnings
7332 js2-strict-inconsistent-return-warning
7333 (not (js2-has-consistent-return-usage
7334 (js2-function-node-body fn-node))))
7335 ;; Have it extend from close-curly to bol or beginning of block.
7336 (let ((pos (save-excursion
7337 (goto-char js2-token-end)
7338 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7339 (point-at-bol))))
7340 (end js2-token-end))
7341 (if (plusp (js2-name-node-length name))
7342 (js2-add-strict-warning "msg.no.return.value"
7343 (js2-name-node-name name) pos end)
7344 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7345
7346 (defun js2-parse-function (function-type)
7347 "Function parser. FUNCTION-TYPE is a symbol."
7348 (let ((pos js2-token-beg) ; start of 'function' keyword
7349 name name-beg name-end fn-node lp
7350 (synthetic-type function-type)
7351 member-expr-node)
7352 ;; parse function name, expression, or non-name (anonymous)
7353 (cond
7354 ;; function foo(...)
7355 ((js2-match-token js2-NAME)
7356 (setq name (js2-create-name-node t)
7357 name-beg js2-token-beg
7358 name-end js2-token-end)
7359 (unless (js2-match-token js2-LP)
7360 (when js2-allow-member-expr-as-function-name
7361 ;; function foo.bar(...)
7362 (setq member-expr-node name
7363 name nil
7364 member-expr-node (js2-parse-member-expr-tail
7365 nil member-expr-node)))
7366 (js2-must-match js2-LP "msg.no.paren.parms")))
7367 ((js2-match-token js2-LP)
7368 nil) ; anonymous function: leave name as null
7369 (t
7370 ;; function random-member-expr(...)
7371 (when js2-allow-member-expr-as-function-name
7372 ;; Note that memberExpr can not start with '(' like
7373 ;; in function (1+2).toString(), because 'function (' already
7374 ;; processed as anonymous function
7375 (setq member-expr-node (js2-parse-member-expr)))
7376 (js2-must-match js2-LP "msg.no.paren.parms")))
7377 (if (= js2-current-token js2-LP) ; eventually matched LP?
7378 (setq lp js2-token-beg))
7379 (if member-expr-node
7380 (progn
7381 (setq synthetic-type 'FUNCTION_EXPRESSION)
7382 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7383 (if name
7384 (js2-set-face name-beg name-end
7385 'font-lock-function-name-face 'record)))
7386 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7387 (plusp (js2-name-node-length name)))
7388 ;; Function statements define a symbol in the enclosing scope
7389 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7390 (setf fn-node (make-js2-function-node :pos pos
7391 :name name
7392 :form function-type
7393 :lp (if lp (- lp pos))))
7394 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7395 ;; 1. Nested functions are not affected by the dynamic scope flag
7396 ;; as dynamic scope is already a parent of their scope.
7397 ;; 2. Functions defined under the with statement also immune to
7398 ;; this setup, in which case dynamic scope is ignored in favor
7399 ;; of the with object.
7400 (setf (js2-function-node-ignore-dynamic fn-node) t))
7401 ;; dynamically bind all the per-function variables
7402 (let ((js2-current-script-or-fn fn-node)
7403 (js2-current-scope fn-node)
7404 (js2-nesting-of-with 0)
7405 (js2-end-flags 0)
7406 js2-label-set
7407 js2-loop-set
7408 js2-loop-and-switch-set)
7409 (js2-parse-function-params fn-node pos)
7410 (if (and (>= js2-language-version 180)
7411 (/= (js2-peek-token) js2-LC))
7412 (js2-parse-function-closure-body fn-node)
7413 (js2-parse-function-body fn-node))
7414 (if name
7415 (js2-node-add-children fn-node name))
7416 (js2-check-inconsistent-return-warning fn-node name)
7417 ;; Function expressions define a name only in the body of the
7418 ;; function, and only if not hidden by a parameter name
7419 (if (and name
7420 (eq synthetic-type 'FUNCTION_EXPRESSION)
7421 (null (js2-scope-get-symbol js2-current-scope
7422 (js2-name-node-name name))))
7423 (js2-define-symbol js2-FUNCTION
7424 (js2-name-node-name name)
7425 fn-node))
7426 (if (and name
7427 (not (eq function-type 'FUNCTION_EXPRESSION)))
7428 (js2-record-imenu-functions fn-node)))
7429 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7430 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7431 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7432 ;; We wait until after parsing the function to set its parent scope,
7433 ;; since `js2-define-symbol' needs the defining-scope check to stop
7434 ;; at the function boundary when checking for redeclarations.
7435 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7436 fn-node))
7437
7438 (defun js2-parse-statements (&optional parent)
7439 "Parse a statement list. Last token consumed must be js2-LC.
7440
7441 PARENT can be a `js2-block-node', in which case the statements are
7442 appended to PARENT. Otherwise a new `js2-block-node' is created
7443 and returned.
7444
7445 This function does not match the closing js2-RC: the caller
7446 matches the RC so it can provide a suitable error message if not
7447 matched. This means it's up to the caller to set the length of
7448 the node to include the closing RC. The node start pos is set to
7449 the absolute buffer start position, and the caller should fix it
7450 up to be relative to the parent node. All children of this block
7451 node are given relative start positions and correct lengths."
7452 (let ((pn (or parent (make-js2-block-node)))
7453 tt)
7454 (setf (js2-node-pos pn) js2-token-beg)
7455 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7456 (/= tt js2-RC))
7457 (js2-block-node-push pn (js2-parse-statement)))
7458 pn))
7459
7460 (defun js2-parse-statement ()
7461 (let (tt pn beg end)
7462 ;; coarse-grained user-interrupt check - needs work
7463 (and js2-parse-interruptable-p
7464 (zerop (% (incf js2-parse-stmt-count)
7465 js2-statements-per-pause))
7466 (input-pending-p)
7467 (throw 'interrupted t))
7468 (setq pn (js2-statement-helper))
7469 ;; no-side-effects warning check
7470 (unless (js2-node-has-side-effects pn)
7471 (setq end (js2-node-end pn))
7472 (save-excursion
7473 (goto-char end)
7474 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7475 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7476 pn))
7477
7478 ;; These correspond to the switch cases in Parser.statementHelper
7479 (defconst js2-parsers
7480 (let ((parsers (make-vector js2-num-tokens
7481 #'js2-parse-expr-stmt)))
7482 (aset parsers js2-BREAK #'js2-parse-break)
7483 (aset parsers js2-CONST #'js2-parse-const-var)
7484 (aset parsers js2-CONTINUE #'js2-parse-continue)
7485 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7486 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7487 (aset parsers js2-DO #'js2-parse-do)
7488 (aset parsers js2-FOR #'js2-parse-for)
7489 (aset parsers js2-FUNCTION #'js2-function-parser)
7490 (aset parsers js2-IF #'js2-parse-if)
7491 (aset parsers js2-LC #'js2-parse-block)
7492 (aset parsers js2-LET #'js2-parse-let-stmt)
7493 (aset parsers js2-NAME #'js2-parse-name-or-label)
7494 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7495 (aset parsers js2-SEMI #'js2-parse-semi)
7496 (aset parsers js2-SWITCH #'js2-parse-switch)
7497 (aset parsers js2-THROW #'js2-parse-throw)
7498 (aset parsers js2-TRY #'js2-parse-try)
7499 (aset parsers js2-VAR #'js2-parse-const-var)
7500 (aset parsers js2-WHILE #'js2-parse-while)
7501 (aset parsers js2-WITH #'js2-parse-with)
7502 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7503 parsers)
7504 "A vector mapping token types to parser functions.")
7505
7506 (defun js2-parse-warn-missing-semi (beg end)
7507 (and js2-mode-show-strict-warnings
7508 js2-strict-missing-semi-warning
7509 (js2-add-strict-warning
7510 "msg.missing.semi" nil
7511 ;; back up to beginning of statement or line
7512 (max beg (save-excursion
7513 (goto-char end)
7514 (point-at-bol)))
7515 end)))
7516
7517 (defconst js2-no-semi-insertion
7518 (list js2-IF
7519 js2-SWITCH
7520 js2-WHILE
7521 js2-DO
7522 js2-FOR
7523 js2-TRY
7524 js2-WITH
7525 js2-LC
7526 js2-ERROR
7527 js2-SEMI
7528 js2-FUNCTION)
7529 "List of tokens that don't do automatic semicolon insertion.")
7530
7531 (defconst js2-autoinsert-semi-and-warn
7532 (list js2-ERROR js2-EOF js2-RC))
7533
7534 (defun js2-statement-helper ()
7535 (let* ((tt (js2-peek-token))
7536 (first-tt tt)
7537 (beg js2-token-beg)
7538 (parser (if (= tt js2-ERROR)
7539 #'js2-parse-semi
7540 (aref js2-parsers tt)))
7541 pn
7542 tt-flagged)
7543 ;; If the statement is set, then it's been told its label by now.
7544 (and js2-labeled-stmt
7545 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7546 (setq js2-labeled-stmt nil))
7547 (setq pn (funcall parser))
7548 ;; Don't do auto semi insertion for certain statement types.
7549 (unless (or (memq first-tt js2-no-semi-insertion)
7550 (js2-labeled-stmt-node-p pn))
7551 (js2-auto-insert-semicolon pn))
7552 pn))
7553
7554 (defun js2-auto-insert-semicolon (pn)
7555 (let* ((tt-flagged (js2-peek-flagged-token))
7556 (tt (logand tt-flagged js2-clear-ti-mask))
7557 (pos (js2-node-pos pn)))
7558 (cond
7559 ((= tt js2-SEMI)
7560 ;; Consume ';' as a part of expression
7561 (js2-consume-token)
7562 ;; extend the node bounds to include the semicolon.
7563 (setf (js2-node-len pn) (- js2-token-end pos)))
7564 ((memq tt js2-autoinsert-semi-and-warn)
7565 ;; Autoinsert ;
7566 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7567 (t
7568 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7569 ;; Report error if no EOL or autoinsert ';' otherwise
7570 (js2-report-error "msg.no.semi.stmt")
7571 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7572
7573 (defun js2-parse-condition ()
7574 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7575 The parens are discarded and the expression node is returned.
7576 The `pos' field of the return value is set to an absolute position
7577 that must be fixed up by the caller.
7578 Return value is a list (EXPR LP RP), with absolute paren positions."
7579 (let (pn lp rp)
7580 (if (js2-must-match js2-LP "msg.no.paren.cond")
7581 (setq lp js2-token-beg))
7582 (setq pn (js2-parse-expr))
7583 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7584 (setq rp js2-token-beg))
7585 ;; Report strict warning on code like "if (a = 7) ..."
7586 (if (and js2-strict-cond-assign-warning
7587 (js2-assign-node-p pn))
7588 (js2-add-strict-warning "msg.equal.as.assign" nil
7589 (js2-node-pos pn)
7590 (+ (js2-node-pos pn)
7591 (js2-node-len pn))))
7592 (list pn lp rp)))
7593
7594 (defun js2-parse-if ()
7595 "Parser for if-statement. Last matched token must be js2-IF."
7596 (let ((pos js2-token-beg)
7597 cond if-true if-false else-pos end pn)
7598 (js2-consume-token)
7599 (setq cond (js2-parse-condition)
7600 if-true (js2-parse-statement)
7601 if-false (if (js2-match-token js2-ELSE)
7602 (progn
7603 (setq else-pos (- js2-token-beg pos))
7604 (js2-parse-statement)))
7605 end (js2-node-end (or if-false if-true))
7606 pn (make-js2-if-node :pos pos
7607 :len (- end pos)
7608 :condition (car cond)
7609 :then-part if-true
7610 :else-part if-false
7611 :else-pos else-pos
7612 :lp (js2-relpos (second cond) pos)
7613 :rp (js2-relpos (third cond) pos)))
7614 (js2-node-add-children pn (car cond) if-true if-false)
7615 pn))
7616
7617 (defun js2-parse-switch ()
7618 "Parser for if-statement. Last matched token must be js2-SWITCH."
7619 (let ((pos js2-token-beg)
7620 tt pn discriminant has-default case-expr case-node
7621 case-pos cases stmt lp rp)
7622 (js2-consume-token)
7623 (if (js2-must-match js2-LP "msg.no.paren.switch")
7624 (setq lp js2-token-beg))
7625 (setq discriminant (js2-parse-expr)
7626 pn (make-js2-switch-node :discriminant discriminant
7627 :pos pos
7628 :lp (js2-relpos lp pos)))
7629 (js2-node-add-children pn discriminant)
7630 (js2-enter-switch pn)
7631 (unwind-protect
7632 (progn
7633 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7634 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7635 (js2-must-match js2-LC "msg.no.brace.switch")
7636 (catch 'break
7637 (while t
7638 (setq tt (js2-next-token)
7639 case-pos js2-token-beg)
7640 (cond
7641 ((= tt js2-RC)
7642 (setf (js2-node-len pn) (- js2-token-end pos))
7643 (throw 'break nil)) ; done
7644 ((= tt js2-CASE)
7645 (setq case-expr (js2-parse-expr))
7646 (js2-must-match js2-COLON "msg.no.colon.case"))
7647 ((= tt js2-DEFAULT)
7648 (if has-default
7649 (js2-report-error "msg.double.switch.default"))
7650 (setq has-default t
7651 case-expr nil)
7652 (js2-must-match js2-COLON "msg.no.colon.case"))
7653 (t
7654 (js2-report-error "msg.bad.switch")
7655 (throw 'break nil)))
7656 (setq case-node (make-js2-case-node :pos case-pos
7657 :len (- js2-token-end case-pos)
7658 :expr case-expr))
7659 (js2-node-add-children case-node case-expr)
7660 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7661 (/= tt js2-CASE)
7662 (/= tt js2-DEFAULT)
7663 (/= tt js2-EOF))
7664 (setf stmt (js2-parse-statement)
7665 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7666 (js2-block-node-push case-node stmt))
7667 (push case-node cases)))
7668 ;; add cases last, as pushing reverses the order to be correct
7669 (dolist (kid cases)
7670 (js2-node-add-children pn kid)
7671 (push kid (js2-switch-node-cases pn)))
7672 pn) ; return value
7673 (js2-exit-switch))))
7674
7675 (defun js2-parse-while ()
7676 "Parser for while-statement. Last matched token must be js2-WHILE."
7677 (let ((pos js2-token-beg)
7678 (pn (make-js2-while-node))
7679 cond body)
7680 (js2-consume-token)
7681 (js2-enter-loop pn)
7682 (unwind-protect
7683 (progn
7684 (setf cond (js2-parse-condition)
7685 (js2-while-node-condition pn) (car cond)
7686 body (js2-parse-statement)
7687 (js2-while-node-body pn) body
7688 (js2-node-len pn) (- (js2-node-end body) pos)
7689 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7690 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7691 (js2-node-add-children pn body (car cond)))
7692 (js2-exit-loop))
7693 pn))
7694
7695 (defun js2-parse-do ()
7696 "Parser for do-statement. Last matched token must be js2-DO."
7697 (let ((pos js2-token-beg)
7698 (pn (make-js2-do-node))
7699 cond body end)
7700 (js2-consume-token)
7701 (js2-enter-loop pn)
7702 (unwind-protect
7703 (progn
7704 (setq body (js2-parse-statement))
7705 (js2-must-match js2-WHILE "msg.no.while.do")
7706 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7707 cond (js2-parse-condition)
7708 (js2-do-node-condition pn) (car cond)
7709 (js2-do-node-body pn) body
7710 end js2-ts-cursor
7711 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7712 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7713 (js2-node-add-children pn (car cond) body))
7714 (js2-exit-loop))
7715 ;; Always auto-insert semicolon to follow SpiderMonkey:
7716 ;; It is required by ECMAScript but is ignored by the rest of
7717 ;; world; see bug 238945
7718 (if (js2-match-token js2-SEMI)
7719 (setq end js2-ts-cursor))
7720 (setf (js2-node-len pn) (- end pos))
7721 pn))
7722
7723 (defun js2-parse-for ()
7724 "Parser for for-statement. Last matched token must be js2-FOR.
7725 Parses for, for-in, and for each-in statements."
7726 (let ((for-pos js2-token-beg)
7727 pn is-for-each is-for-in-or-of is-for-of
7728 in-pos each-pos tmp-pos
7729 init ; Node init is also foo in 'foo in object'
7730 cond ; Node cond is also object in 'foo in object'
7731 incr ; 3rd section of for-loop initializer
7732 body tt lp rp)
7733 (js2-consume-token)
7734 ;; See if this is a for each () instead of just a for ()
7735 (when (js2-match-token js2-NAME)
7736 (if (string= "each" js2-ts-string)
7737 (progn
7738 (setq is-for-each t
7739 each-pos (- js2-token-beg for-pos)) ; relative
7740 (js2-record-face 'font-lock-keyword-face))
7741 (js2-report-error "msg.no.paren.for")))
7742 (if (js2-must-match js2-LP "msg.no.paren.for")
7743 (setq lp (- js2-token-beg for-pos)))
7744 (setq tt (js2-peek-token))
7745 ;; 'for' makes local scope
7746 (js2-push-scope (make-js2-scope))
7747 (unwind-protect
7748 ;; parse init clause
7749 (let ((js2-in-for-init t)) ; set as dynamic variable
7750 (cond
7751 ((= tt js2-SEMI)
7752 (setq init (make-js2-empty-expr-node)))
7753 ((or (= tt js2-VAR) (= tt js2-LET))
7754 (js2-consume-token)
7755 (setq init (js2-parse-variables tt js2-token-beg)))
7756 (t
7757 (setq init (js2-parse-expr)))))
7758 (if (or (js2-match-token js2-IN)
7759 (and (>= js2-language-version 200)
7760 (js2-match-contextual-kwd "of")
7761 (setq is-for-of t)))
7762 (setq is-for-in-or-of t
7763 in-pos (- js2-token-beg for-pos)
7764 ;; scope of iteration target object is not the scope we've created above.
7765 ;; stash current scope temporary.
7766 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7767 (js2-parse-expr))) ; object over which we're iterating
7768 ;; else ordinary for loop - parse cond and incr
7769 (js2-must-match js2-SEMI "msg.no.semi.for")
7770 (setq cond (if (= (js2-peek-token) js2-SEMI)
7771 (make-js2-empty-expr-node) ; no loop condition
7772 (js2-parse-expr)))
7773 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7774 (setq tmp-pos js2-token-end
7775 incr (if (= (js2-peek-token) js2-RP)
7776 (make-js2-empty-expr-node :pos tmp-pos)
7777 (js2-parse-expr))))
7778 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7779 (setq rp (- js2-token-beg for-pos)))
7780 (if (not is-for-in-or-of)
7781 (setq pn (make-js2-for-node :init init
7782 :condition cond
7783 :update incr
7784 :lp lp
7785 :rp rp))
7786 ;; cond could be null if 'in obj' got eaten by the init node.
7787 (if (js2-infix-node-p init)
7788 ;; it was (foo in bar) instead of (var foo in bar)
7789 (setq cond (js2-infix-node-right init)
7790 init (js2-infix-node-left init))
7791 (if (and (js2-var-decl-node-p init)
7792 (> (length (js2-var-decl-node-kids init)) 1))
7793 (js2-report-error "msg.mult.index")))
7794 (setq pn (make-js2-for-in-node :iterator init
7795 :object cond
7796 :in-pos in-pos
7797 :foreach-p is-for-each
7798 :each-pos each-pos
7799 :forof-p is-for-of
7800 :lp lp
7801 :rp rp)))
7802 (unwind-protect
7803 (progn
7804 (js2-enter-loop pn)
7805 ;; We have to parse the body -after- creating the loop node,
7806 ;; so that the loop node appears in the js2-loop-set, allowing
7807 ;; break/continue statements to find the enclosing loop.
7808 (setf body (js2-parse-statement)
7809 (js2-loop-node-body pn) body
7810 (js2-node-pos pn) for-pos
7811 (js2-node-len pn) (- (js2-node-end body) for-pos))
7812 (js2-node-add-children pn init cond incr body))
7813 ;; finally
7814 (js2-exit-loop))
7815 (js2-pop-scope))
7816 pn))
7817
7818 (defun js2-parse-try ()
7819 "Parser for try-statement. Last matched token must be js2-TRY."
7820 (let ((try-pos js2-token-beg)
7821 try-end
7822 try-block
7823 catch-blocks
7824 finally-block
7825 saw-default-catch
7826 peek
7827 param
7828 catch-cond
7829 catch-node
7830 guard-kwd
7831 catch-pos
7832 finally-pos
7833 pn
7834 block
7835 lp
7836 rp)
7837 (js2-consume-token)
7838 (if (/= (js2-peek-token) js2-LC)
7839 (js2-report-error "msg.no.brace.try"))
7840 (setq try-block (js2-parse-statement)
7841 try-end (js2-node-end try-block)
7842 peek (js2-peek-token))
7843 (cond
7844 ((= peek js2-CATCH)
7845 (while (js2-match-token js2-CATCH)
7846 (setq catch-pos js2-token-beg
7847 guard-kwd nil
7848 catch-cond nil
7849 lp nil
7850 rp nil)
7851 (if saw-default-catch
7852 (js2-report-error "msg.catch.unreachable"))
7853 (if (js2-must-match js2-LP "msg.no.paren.catch")
7854 (setq lp (- js2-token-beg catch-pos)))
7855 (js2-push-scope (make-js2-scope))
7856 (let ((tt (js2-peek-token)))
7857 (cond
7858 ;; destructuring pattern
7859 ;; catch ({ message, file }) { ... }
7860 ((or (= tt js2-LB) (= tt js2-LC))
7861 (setq param (js2-parse-destruct-primary-expr))
7862 (js2-define-destruct-symbols param js2-LET nil))
7863 ;; simple name
7864 (t
7865 (js2-must-match js2-NAME "msg.bad.catchcond")
7866 (setq param (js2-create-name-node))
7867 (js2-define-symbol js2-LET js2-ts-string param))))
7868 ;; pattern guard
7869 (if (js2-match-token js2-IF)
7870 (setq guard-kwd (- js2-token-beg catch-pos)
7871 catch-cond (js2-parse-expr))
7872 (setq saw-default-catch t))
7873 (if (js2-must-match js2-RP "msg.bad.catchcond")
7874 (setq rp (- js2-token-beg catch-pos)))
7875 (js2-must-match js2-LC "msg.no.brace.catchblock")
7876 (setq block (js2-parse-statements)
7877 try-end (js2-node-end block)
7878 catch-node (make-js2-catch-node :pos catch-pos
7879 :param param
7880 :guard-expr catch-cond
7881 :guard-kwd guard-kwd
7882 :block block
7883 :lp lp
7884 :rp rp))
7885 (js2-pop-scope)
7886 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7887 (setq try-end js2-token-beg))
7888 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7889 (js2-node-len catch-node) (- try-end catch-pos))
7890 (js2-node-add-children catch-node param catch-cond block)
7891 (push catch-node catch-blocks)))
7892 ((/= peek js2-FINALLY)
7893 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7894 (js2-node-pos try-block)
7895 (- (setq try-end (js2-node-end try-block))
7896 (js2-node-pos try-block)))))
7897 (when (js2-match-token js2-FINALLY)
7898 (setq finally-pos js2-token-beg
7899 block (js2-parse-statement)
7900 try-end (js2-node-end block)
7901 finally-block (make-js2-finally-node :pos finally-pos
7902 :len (- try-end finally-pos)
7903 :body block))
7904 (js2-node-add-children finally-block block))
7905 (setq pn (make-js2-try-node :pos try-pos
7906 :len (- try-end try-pos)
7907 :try-block try-block
7908 :finally-block finally-block))
7909 (js2-node-add-children pn try-block finally-block)
7910 ;; push them onto the try-node, which reverses and corrects their order
7911 (dolist (cb catch-blocks)
7912 (js2-node-add-children pn cb)
7913 (push cb (js2-try-node-catch-clauses pn)))
7914 pn))
7915
7916 (defun js2-parse-throw ()
7917 "Parser for throw-statement. Last matched token must be js2-THROW."
7918 (let ((pos js2-token-beg)
7919 expr pn)
7920 (js2-consume-token)
7921 (if (= (js2-peek-token-or-eol) js2-EOL)
7922 ;; ECMAScript does not allow new lines before throw expression,
7923 ;; see bug 256617
7924 (js2-report-error "msg.bad.throw.eol"))
7925 (setq expr (js2-parse-expr)
7926 pn (make-js2-throw-node :pos pos
7927 :len (- (js2-node-end expr) pos)
7928 :expr expr))
7929 (js2-node-add-children pn expr)
7930 pn))
7931
7932 (defun js2-match-jump-label-name (label-name)
7933 "If break/continue specified a label, return that label's labeled stmt.
7934 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7935 does not match an existing label, reports an error and returns nil."
7936 (let ((bundle (cdr (assoc label-name js2-label-set))))
7937 (if (null bundle)
7938 (js2-report-error "msg.undef.label"))
7939 bundle))
7940
7941 (defun js2-parse-break ()
7942 "Parser for break-statement. Last matched token must be js2-BREAK."
7943 (let ((pos js2-token-beg)
7944 (end js2-token-end)
7945 break-target ; statement to break from
7946 break-label ; in "break foo", name-node representing the foo
7947 labels ; matching labeled statement to break to
7948 pn)
7949 (js2-consume-token) ; `break'
7950 (when (eq (js2-peek-token-or-eol) js2-NAME)
7951 (js2-consume-token)
7952 (setq break-label (js2-create-name-node)
7953 end (js2-node-end break-label)
7954 ;; matchJumpLabelName only matches if there is one
7955 labels (js2-match-jump-label-name js2-ts-string)
7956 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7957 (unless (or break-target break-label)
7958 ;; no break target specified - try for innermost enclosing loop/switch
7959 (if (null js2-loop-and-switch-set)
7960 (unless break-label
7961 (js2-report-error "msg.bad.break" nil pos (length "break")))
7962 (setq break-target (car js2-loop-and-switch-set))))
7963 (setq pn (make-js2-break-node :pos pos
7964 :len (- end pos)
7965 :label break-label
7966 :target break-target))
7967 (js2-node-add-children pn break-label) ; but not break-target
7968 pn))
7969
7970 (defun js2-parse-continue ()
7971 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7972 (let ((pos js2-token-beg)
7973 (end js2-token-end)
7974 label ; optional user-specified label, a `js2-name-node'
7975 labels ; current matching labeled stmt, if any
7976 target ; the `js2-loop-node' target of this continue stmt
7977 pn)
7978 (js2-consume-token) ; `continue'
7979 (when (= (js2-peek-token-or-eol) js2-NAME)
7980 (js2-consume-token)
7981 (setq label (js2-create-name-node)
7982 end (js2-node-end label)
7983 ;; matchJumpLabelName only matches if there is one
7984 labels (js2-match-jump-label-name js2-ts-string)))
7985 (cond
7986 ((null labels) ; no current label to go to
7987 (if (null js2-loop-set) ; no loop to continue to
7988 (js2-report-error "msg.continue.outside" nil pos
7989 (length "continue"))
7990 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7991 (t
7992 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7993 (setq target (js2-labeled-stmt-node-stmt labels))
7994 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7995 (setq pn (make-js2-continue-node :pos pos
7996 :len (- end pos)
7997 :label label
7998 :target target))
7999 (js2-node-add-children pn label) ; but not target - it's not our child
8000 pn))
8001
8002 (defun js2-parse-with ()
8003 "Parser for with-statement. Last matched token must be js2-WITH."
8004 (js2-consume-token)
8005 (let ((pos js2-token-beg)
8006 obj body pn lp rp)
8007 (if (js2-must-match js2-LP "msg.no.paren.with")
8008 (setq lp js2-token-beg))
8009 (setq obj (js2-parse-expr))
8010 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8011 (setq rp js2-token-beg))
8012 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8013 (setq body (js2-parse-statement)))
8014 (setq pn (make-js2-with-node :pos pos
8015 :len (- (js2-node-end body) pos)
8016 :object obj
8017 :body body
8018 :lp (js2-relpos lp pos)
8019 :rp (js2-relpos rp pos)))
8020 (js2-node-add-children pn obj body)
8021 pn))
8022
8023 (defun js2-parse-const-var ()
8024 "Parser for var- or const-statement.
8025 Last matched token must be js2-CONST or js2-VAR."
8026 (let ((tt (js2-peek-token))
8027 (pos js2-token-beg)
8028 expr pn)
8029 (js2-consume-token)
8030 (setq expr (js2-parse-variables tt js2-token-beg)
8031 pn (make-js2-expr-stmt-node :pos pos
8032 :len (- (js2-node-end expr) pos)
8033 :expr expr))
8034 (js2-node-add-children pn expr)
8035 pn))
8036
8037 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8038 (let ((pn (make-js2-expr-stmt-node :pos pos
8039 :len (js2-node-len expr)
8040 :type (if (js2-inside-function)
8041 js2-EXPR_VOID
8042 js2-EXPR_RESULT)
8043 :expr expr)))
8044 (if add-child
8045 (js2-node-add-children pn expr))
8046 pn))
8047
8048 (defun js2-parse-let-stmt ()
8049 "Parser for let-statement. Last matched token must be js2-LET."
8050 (js2-consume-token)
8051 (let ((pos js2-token-beg)
8052 expr pn)
8053 (if (= (js2-peek-token) js2-LP)
8054 ;; let expression in statement context
8055 (setq expr (js2-parse-let pos 'statement)
8056 pn (js2-wrap-with-expr-stmt pos expr t))
8057 ;; else we're looking at a statement like let x=6, y=7;
8058 (setf expr (js2-parse-variables js2-LET pos)
8059 pn (js2-wrap-with-expr-stmt pos expr t)
8060 (js2-node-type pn) js2-EXPR_RESULT))
8061 pn))
8062
8063 (defun js2-parse-ret-yield ()
8064 (js2-parse-return-or-yield (js2-peek-token) nil))
8065
8066 (defconst js2-parse-return-stmt-enders
8067 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8068
8069 (defsubst js2-now-all-set (before after mask)
8070 "Return whether or not the bits in the mask have changed to all set.
8071 BEFORE is bits before change, AFTER is bits after change, and MASK is
8072 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8073 but not BEFORE."
8074 (and (/= (logand before mask) mask)
8075 (= (logand after mask) mask)))
8076
8077 (defun js2-parse-return-or-yield (tt expr-context)
8078 (let ((pos js2-token-beg)
8079 (end js2-token-end)
8080 (before js2-end-flags)
8081 (inside-function (js2-inside-function))
8082 e ret name)
8083 (unless inside-function
8084 (js2-report-error (if (eq tt js2-RETURN)
8085 "msg.bad.return"
8086 "msg.bad.yield")))
8087 (js2-consume-token)
8088 ;; This is ugly, but we don't want to require a semicolon.
8089 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8090 (setq e (js2-parse-expr)
8091 end (js2-node-end e)))
8092 (cond
8093 ((eq tt js2-RETURN)
8094 (js2-set-flag js2-end-flags (if (null e)
8095 js2-end-returns
8096 js2-end-returns-value))
8097 (setq ret (make-js2-return-node :pos pos
8098 :len (- end pos)
8099 :retval e))
8100 (js2-node-add-children ret e)
8101 ;; See if we need a strict mode warning.
8102 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8103 ;; more thorough and accurate than this before/after flag check.
8104 ;; E.g. if there's a finally-block that always returns, we shouldn't
8105 ;; show a warning generated by inconsistent returns in the catch blocks.
8106 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8107 ;; so we know which returns/yields to highlight, and we should get rid of
8108 ;; all the checking in `js2-parse-return-or-yield'.
8109 (if (and js2-strict-inconsistent-return-warning
8110 (js2-now-all-set before js2-end-flags
8111 (logior js2-end-returns js2-end-returns-value)))
8112 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8113 (t
8114 (unless (js2-inside-function)
8115 (js2-report-error "msg.bad.yield"))
8116 (js2-set-flag js2-end-flags js2-end-yields)
8117 (setq ret (make-js2-yield-node :pos pos
8118 :len (- end pos)
8119 :value e))
8120 (js2-node-add-children ret e)
8121 (unless expr-context
8122 (setq e ret
8123 ret (js2-wrap-with-expr-stmt pos e t))
8124 (js2-set-requires-activation)
8125 (js2-set-is-generator))))
8126 ;; see if we are mixing yields and value returns.
8127 (when (and inside-function
8128 (js2-now-all-set before js2-end-flags
8129 (logior js2-end-yields js2-end-returns-value)))
8130 (setq name (js2-function-name js2-current-script-or-fn))
8131 (if (zerop (length name))
8132 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8133 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8134 ret))
8135
8136 (defun js2-parse-debugger ()
8137 (js2-consume-token)
8138 (make-js2-keyword-node :type js2-DEBUGGER))
8139
8140 (defun js2-parse-block ()
8141 "Parser for a curly-delimited statement block.
8142 Last token matched must be `js2-LC'."
8143 (let ((pos js2-token-beg)
8144 (pn (make-js2-scope)))
8145 (js2-consume-token)
8146 (js2-push-scope pn)
8147 (unwind-protect
8148 (progn
8149 (js2-parse-statements pn)
8150 (js2-must-match js2-RC "msg.no.brace.block")
8151 (setf (js2-node-len pn) (- js2-token-end pos)))
8152 (js2-pop-scope))
8153 pn))
8154
8155 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8156 (defun js2-parse-semi ()
8157 "Parse a statement or handle an error.
8158 Last matched token is `js2-SEMI' or `js2-ERROR'."
8159 (let ((tt (js2-peek-token)) pos len)
8160 (js2-consume-token)
8161 (if (eq tt js2-SEMI)
8162 (make-js2-empty-expr-node :len 1)
8163 (setq pos js2-token-beg
8164 len (- js2-token-beg pos))
8165 (js2-report-error "msg.syntax" nil pos len)
8166 (make-js2-error-node :pos pos :len len))))
8167
8168 (defun js2-parse-default-xml-namespace ()
8169 "Parse a `default xml namespace = <expr>' e4x statement."
8170 (let ((pos js2-token-beg)
8171 end len expr unary es)
8172 (js2-consume-token)
8173 (js2-must-have-xml)
8174 (js2-set-requires-activation)
8175 (setq len (- js2-ts-cursor pos))
8176 (unless (and (js2-match-token js2-NAME)
8177 (string= js2-ts-string "xml"))
8178 (js2-report-error "msg.bad.namespace" nil pos len))
8179 (unless (and (js2-match-token js2-NAME)
8180 (string= js2-ts-string "namespace"))
8181 (js2-report-error "msg.bad.namespace" nil pos len))
8182 (unless (js2-match-token js2-ASSIGN)
8183 (js2-report-error "msg.bad.namespace" nil pos len))
8184 (setq expr (js2-parse-expr)
8185 end (js2-node-end expr)
8186 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8187 :pos pos
8188 :len (- end pos)
8189 :operand expr))
8190 (js2-node-add-children unary expr)
8191 (make-js2-expr-stmt-node :pos pos
8192 :len (- end pos)
8193 :expr unary)))
8194
8195 (defun js2-record-label (label bundle)
8196 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8197 (js2-consume-token)
8198 (let ((name (js2-label-node-name label))
8199 labeled-stmt
8200 dup)
8201 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8202 ;; flag both labels if possible when used in editing mode
8203 (if (and js2-parse-ide-mode
8204 (setq dup (js2-get-label-by-name labeled-stmt name)))
8205 (js2-report-error "msg.dup.label" nil
8206 (js2-node-abs-pos dup) (js2-node-len dup)))
8207 (js2-report-error "msg.dup.label" nil
8208 (js2-node-pos label) (js2-node-len label)))
8209 (js2-labeled-stmt-node-add-label bundle label)
8210 (js2-node-add-children bundle label)
8211 ;; Add one reference to the bundle per label in `js2-label-set'
8212 (push (cons name bundle) js2-label-set)))
8213
8214 (defun js2-parse-name-or-label ()
8215 "Parser for identifier or label. Last token matched must be js2-NAME.
8216 Called when we found a name in a statement context. If it's a label, we gather
8217 up any following labels and the next non-label statement into a
8218 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8219 expression and return it wrapped in a `js2-expr-stmt-node'."
8220 (let ((pos js2-token-beg)
8221 (end js2-token-end)
8222 expr stmt pn bundle
8223 (continue t))
8224 ;; set check for label and call down to `js2-parse-primary-expr'
8225 (js2-set-check-for-label)
8226 (setq expr (js2-parse-expr))
8227 (if (/= (js2-node-type expr) js2-LABEL)
8228 ;; Parsed non-label expression - wrap with expression stmt.
8229 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8230 ;; else parsed a label
8231 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8232 (js2-record-label expr bundle)
8233 ;; look for more labels
8234 (while (and continue (= (js2-peek-token) js2-NAME))
8235 (js2-set-check-for-label)
8236 (setq expr (js2-parse-expr))
8237 (if (/= (js2-node-type expr) js2-LABEL)
8238 (progn
8239 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8240 continue nil)
8241 (js2-auto-insert-semicolon stmt))
8242 (js2-record-label expr bundle)))
8243 ;; no more labels; now parse the labeled statement
8244 (unwind-protect
8245 (unless stmt
8246 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8247 (setq stmt (js2-statement-helper))))
8248 ;; remove the labels for this statement from the global set
8249 (dolist (label (js2-labeled-stmt-node-labels bundle))
8250 (setq js2-label-set (remove label js2-label-set))))
8251 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8252 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8253 (js2-node-add-children bundle stmt)
8254 bundle)))
8255
8256 (defun js2-parse-expr-stmt ()
8257 "Default parser in statement context, if no recognized statement found."
8258 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8259
8260 (defun js2-parse-variables (decl-type pos)
8261 "Parse a comma-separated list of variable declarations.
8262 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8263
8264 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8265 For 'var' or 'const', the keyword should be the token last scanned.
8266
8267 POS is the position where the node should start. It's sometimes the
8268 var/const/let keyword, and other times the beginning of the first token
8269 in the first variable declaration.
8270
8271 Returns the parsed `js2-var-decl-node' expression node."
8272 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8273 :pos pos))
8274 destructuring kid-pos tt init name end nbeg nend vi
8275 (continue t))
8276 ;; Example:
8277 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8278 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8279 ;; var {a, b} = baz;
8280 (while continue
8281 (setq destructuring nil
8282 name nil
8283 tt (js2-peek-token)
8284 kid-pos js2-token-beg
8285 end js2-token-end
8286 init nil)
8287 (if (or (= tt js2-LB) (= tt js2-LC))
8288 ;; Destructuring assignment, e.g., var [a, b] = ...
8289 (setq destructuring (js2-parse-destruct-primary-expr)
8290 end (js2-node-end destructuring))
8291 ;; Simple variable name
8292 (when (js2-must-match js2-NAME "msg.bad.var")
8293 (setq name (js2-create-name-node)
8294 nbeg js2-token-beg
8295 nend js2-token-end
8296 end nend)
8297 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8298 (when (js2-match-token js2-ASSIGN)
8299 (setq init (js2-parse-assign-expr)
8300 end (js2-node-end init))
8301 (js2-record-imenu-functions init name))
8302 (when name
8303 (js2-set-face nbeg nend (if (js2-function-node-p init)
8304 'font-lock-function-name-face
8305 'font-lock-variable-name-face)
8306 'record))
8307 (setq vi (make-js2-var-init-node :pos kid-pos
8308 :len (- end kid-pos)
8309 :type decl-type))
8310 (if destructuring
8311 (progn
8312 (if (and (null init) (not js2-in-for-init))
8313 (js2-report-error "msg.destruct.assign.no.init"))
8314 (js2-define-destruct-symbols destructuring
8315 decl-type
8316 'font-lock-variable-name-face)
8317 (setf (js2-var-init-node-target vi) destructuring))
8318 (setf (js2-var-init-node-target vi) name))
8319 (setf (js2-var-init-node-initializer vi) init)
8320 (js2-node-add-children vi name destructuring init)
8321 (js2-block-node-push result vi)
8322 (unless (js2-match-token js2-COMMA)
8323 (setq continue nil)))
8324 (setf (js2-node-len result) (- end pos))
8325 result))
8326
8327 (defun js2-parse-let (pos &optional stmt-p)
8328 "Parse a let expression or statement.
8329 A let-expression is of the form `let (vars) expr'.
8330 A let-statment is of the form `let (vars) {statements}'.
8331 The third form of let is a variable declaration list, handled
8332 by `js2-parse-variables'."
8333 (let ((pn (make-js2-let-node :pos pos))
8334 beg vars body)
8335 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8336 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8337 (js2-push-scope pn)
8338 (unwind-protect
8339 (progn
8340 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8341 (if (js2-must-match js2-RP "msg.no.paren.let")
8342 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8343 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8344 ;; let statement
8345 (progn
8346 (js2-consume-token)
8347 (setf beg js2-token-beg ; position stmt at LC
8348 body (js2-parse-statements))
8349 (js2-must-match js2-RC "msg.no.curly.let")
8350 (setf (js2-node-len body) (- js2-token-end beg)
8351 (js2-node-len pn) (- js2-token-end pos)
8352 (js2-let-node-body pn) body
8353 (js2-node-type pn) js2-LET))
8354 ;; let expression
8355 (setf body (js2-parse-expr)
8356 (js2-node-len pn) (- (js2-node-end body) pos)
8357 (js2-let-node-body pn) body))
8358 (js2-node-add-children pn vars body))
8359 (js2-pop-scope))
8360 pn))
8361
8362 (defun js2-define-new-symbol (decl-type name node &optional scope)
8363 (js2-scope-put-symbol (or scope js2-current-scope)
8364 name
8365 (make-js2-symbol decl-type name node)))
8366
8367 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8368 "Define a symbol in the current scope.
8369 If NODE is non-nil, it is the AST node associated with the symbol."
8370 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8371 (symbol (if defining-scope
8372 (js2-scope-get-symbol defining-scope name)))
8373 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8374 (cond
8375 ((and symbol ; already defined
8376 (or (= sdt js2-CONST) ; old version is const
8377 (= decl-type js2-CONST) ; new version is const
8378 ;; two let-bound vars in this block have same name
8379 (and (= sdt js2-LET)
8380 (eq defining-scope js2-current-scope))))
8381 (js2-report-error
8382 (cond
8383 ((= sdt js2-CONST) "msg.const.redecl")
8384 ((= sdt js2-LET) "msg.let.redecl")
8385 ((= sdt js2-VAR) "msg.var.redecl")
8386 ((= sdt js2-FUNCTION) "msg.function.redecl")
8387 (t "msg.parm.redecl"))
8388 name))
8389 ((= decl-type js2-LET)
8390 (if (and (not ignore-not-in-block)
8391 (or (= (js2-node-type js2-current-scope) js2-IF)
8392 (js2-loop-node-p js2-current-scope)))
8393 (js2-report-error "msg.let.decl.not.in.block")
8394 (js2-define-new-symbol decl-type name node)))
8395 ((or (= decl-type js2-VAR)
8396 (= decl-type js2-CONST)
8397 (= decl-type js2-FUNCTION))
8398 (if symbol
8399 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8400 (js2-add-strict-warning "msg.var.redecl" name)
8401 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8402 (js2-add-strict-warning "msg.var.hides.arg" name)))
8403 (js2-define-new-symbol decl-type name node
8404 js2-current-script-or-fn)))
8405 ((= decl-type js2-LP)
8406 (if symbol
8407 ;; must be duplicate parameter. Second parameter hides the
8408 ;; first, so go ahead and add the second pararameter
8409 (js2-report-warning "msg.dup.parms" name))
8410 (js2-define-new-symbol decl-type name node))
8411 (t (js2-code-bug)))))
8412
8413 (defun js2-parse-expr (&optional oneshot)
8414 (let* ((pn (js2-parse-assign-expr))
8415 (pos (js2-node-pos pn))
8416 left
8417 right
8418 op-pos)
8419 (while (and (not oneshot)
8420 (js2-match-token js2-COMMA))
8421 (setq op-pos (- js2-token-beg pos)) ; relative
8422 (if (= (js2-peek-token) js2-YIELD)
8423 (js2-report-error "msg.yield.parenthesized"))
8424 (setq right (js2-parse-assign-expr)
8425 left pn
8426 pn (make-js2-infix-node :type js2-COMMA
8427 :pos pos
8428 :len (- js2-ts-cursor pos)
8429 :op-pos op-pos
8430 :left left
8431 :right right))
8432 (js2-node-add-children pn left right))
8433 pn))
8434
8435 (defun js2-parse-assign-expr ()
8436 (let ((tt (js2-peek-token))
8437 (pos js2-token-beg)
8438 pn left right op-pos)
8439 (if (= tt js2-YIELD)
8440 (js2-parse-return-or-yield tt t)
8441 ;; not yield - parse assignment expression
8442 (setq pn (js2-parse-cond-expr)
8443 tt (js2-peek-token))
8444 (when (and (<= js2-first-assign tt)
8445 (<= tt js2-last-assign))
8446 ;; tt express assignment (=, |=, ^=, ..., %=)
8447 (js2-consume-token)
8448 (setq op-pos (- js2-token-beg pos) ; relative
8449 left pn
8450 right (js2-parse-assign-expr)
8451 pn (make-js2-assign-node :type tt
8452 :pos pos
8453 :len (- (js2-node-end right) pos)
8454 :op-pos op-pos
8455 :left left
8456 :right right))
8457 (when js2-parse-ide-mode
8458 (js2-highlight-assign-targets pn left right)
8459 (js2-record-imenu-functions right left))
8460 ;; do this last so ide checks above can use absolute positions
8461 (js2-node-add-children pn left right))
8462 pn)))
8463
8464 (defun js2-parse-cond-expr ()
8465 (let ((pos js2-token-beg)
8466 (pn (js2-parse-or-expr))
8467 test-expr
8468 if-true
8469 if-false
8470 q-pos
8471 c-pos)
8472 (when (js2-match-token js2-HOOK)
8473 (setq q-pos (- js2-token-beg pos)
8474 if-true (js2-parse-assign-expr))
8475 (js2-must-match js2-COLON "msg.no.colon.cond")
8476 (setq c-pos (- js2-token-beg pos)
8477 if-false (js2-parse-assign-expr)
8478 test-expr pn
8479 pn (make-js2-cond-node :pos pos
8480 :len (- (js2-node-end if-false) pos)
8481 :test-expr test-expr
8482 :true-expr if-true
8483 :false-expr if-false
8484 :q-pos q-pos
8485 :c-pos c-pos))
8486 (js2-node-add-children pn test-expr if-true if-false))
8487 pn))
8488
8489 (defun js2-make-binary (type left parser)
8490 "Helper for constructing a binary-operator AST node.
8491 LEFT is the left-side-expression, already parsed, and the
8492 binary operator should have just been matched.
8493 PARSER is a function to call to parse the right operand,
8494 or a `js2-node' struct if it has already been parsed."
8495 (let* ((pos (js2-node-pos left))
8496 (op-pos (- js2-token-beg pos))
8497 (right (if (js2-node-p parser)
8498 parser
8499 (funcall parser)))
8500 (pn (make-js2-infix-node :type type
8501 :pos pos
8502 :len (- (js2-node-end right) pos)
8503 :op-pos op-pos
8504 :left left
8505 :right right)))
8506 (js2-node-add-children pn left right)
8507 pn))
8508
8509 (defun js2-parse-or-expr ()
8510 (let ((pn (js2-parse-and-expr)))
8511 (when (js2-match-token js2-OR)
8512 (setq pn (js2-make-binary js2-OR
8513 pn
8514 'js2-parse-or-expr)))
8515 pn))
8516
8517 (defun js2-parse-and-expr ()
8518 (let ((pn (js2-parse-bit-or-expr)))
8519 (when (js2-match-token js2-AND)
8520 (setq pn (js2-make-binary js2-AND
8521 pn
8522 'js2-parse-and-expr)))
8523 pn))
8524
8525 (defun js2-parse-bit-or-expr ()
8526 (let ((pn (js2-parse-bit-xor-expr)))
8527 (while (js2-match-token js2-BITOR)
8528 (setq pn (js2-make-binary js2-BITOR
8529 pn
8530 'js2-parse-bit-xor-expr)))
8531 pn))
8532
8533 (defun js2-parse-bit-xor-expr ()
8534 (let ((pn (js2-parse-bit-and-expr)))
8535 (while (js2-match-token js2-BITXOR)
8536 (setq pn (js2-make-binary js2-BITXOR
8537 pn
8538 'js2-parse-bit-and-expr)))
8539 pn))
8540
8541 (defun js2-parse-bit-and-expr ()
8542 (let ((pn (js2-parse-eq-expr)))
8543 (while (js2-match-token js2-BITAND)
8544 (setq pn (js2-make-binary js2-BITAND
8545 pn
8546 'js2-parse-eq-expr)))
8547 pn))
8548
8549 (defconst js2-parse-eq-ops
8550 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8551
8552 (defun js2-parse-eq-expr ()
8553 (let ((pn (js2-parse-rel-expr))
8554 tt)
8555 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8556 (js2-consume-token)
8557 (setq pn (js2-make-binary tt
8558 pn
8559 'js2-parse-rel-expr)))
8560 pn))
8561
8562 (defconst js2-parse-rel-ops
8563 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8564
8565 (defun js2-parse-rel-expr ()
8566 (let ((pn (js2-parse-shift-expr))
8567 (continue t)
8568 tt)
8569 (while continue
8570 (setq tt (js2-peek-token))
8571 (cond
8572 ((and js2-in-for-init (= tt js2-IN))
8573 (setq continue nil))
8574 ((memq tt js2-parse-rel-ops)
8575 (js2-consume-token)
8576 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8577 (t
8578 (setq continue nil))))
8579 pn))
8580
8581 (defconst js2-parse-shift-ops
8582 (list js2-LSH js2-URSH js2-RSH))
8583
8584 (defun js2-parse-shift-expr ()
8585 (let ((pn (js2-parse-add-expr))
8586 tt
8587 (continue t))
8588 (while continue
8589 (setq tt (js2-peek-token))
8590 (if (memq tt js2-parse-shift-ops)
8591 (progn
8592 (js2-consume-token)
8593 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8594 (setq continue nil)))
8595 pn))
8596
8597 (defun js2-parse-add-expr ()
8598 (let ((pn (js2-parse-mul-expr))
8599 tt
8600 (continue t))
8601 (while continue
8602 (setq tt (js2-peek-token))
8603 (if (or (= tt js2-ADD) (= tt js2-SUB))
8604 (progn
8605 (js2-consume-token)
8606 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8607 (setq continue nil)))
8608 pn))
8609
8610 (defconst js2-parse-mul-ops
8611 (list js2-MUL js2-DIV js2-MOD))
8612
8613 (defun js2-parse-mul-expr ()
8614 (let ((pn (js2-parse-unary-expr))
8615 tt
8616 (continue t))
8617 (while continue
8618 (setq tt (js2-peek-token))
8619 (if (memq tt js2-parse-mul-ops)
8620 (progn
8621 (js2-consume-token)
8622 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8623 (setq continue nil)))
8624 pn))
8625
8626 (defun js2-make-unary (type parser &rest args)
8627 "Make a unary node of type TYPE.
8628 PARSER is either a node (for postfix operators) or a function to call
8629 to parse the operand (for prefix operators)."
8630 (let* ((pos js2-token-beg)
8631 (postfix (js2-node-p parser))
8632 (expr (if postfix
8633 parser
8634 (apply parser args)))
8635 end
8636 pn)
8637 (if postfix ; e.g. i++
8638 (setq pos (js2-node-pos expr)
8639 end js2-token-end)
8640 (setq end (js2-node-end expr)))
8641 (setq pn (make-js2-unary-node :type type
8642 :pos pos
8643 :len (- end pos)
8644 :operand expr))
8645 (js2-node-add-children pn expr)
8646 pn))
8647
8648 (defconst js2-incrementable-node-types
8649 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8650 "Node types that can be the operand of a ++ or -- operator.")
8651
8652 (defun js2-check-bad-inc-dec (tt beg end unary)
8653 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8654 js2-incrementable-node-types)
8655 (js2-report-error (if (= tt js2-INC)
8656 "msg.bad.incr"
8657 "msg.bad.decr")
8658 nil beg (- end beg))))
8659
8660 (defun js2-parse-unary-expr ()
8661 (let ((tt (js2-peek-token))
8662 pn expr beg end)
8663 (cond
8664 ((or (= tt js2-VOID)
8665 (= tt js2-NOT)
8666 (= tt js2-BITNOT)
8667 (= tt js2-TYPEOF))
8668 (js2-consume-token)
8669 (js2-make-unary tt 'js2-parse-unary-expr))
8670 ((= tt js2-ADD)
8671 (js2-consume-token)
8672 ;; Convert to special POS token in decompiler and parse tree
8673 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8674 ((= tt js2-SUB)
8675 (js2-consume-token)
8676 ;; Convert to special NEG token in decompiler and parse tree
8677 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8678 ((or (= tt js2-INC)
8679 (= tt js2-DEC))
8680 (js2-consume-token)
8681 (prog1
8682 (setq beg js2-token-beg
8683 end js2-token-end
8684 expr (js2-make-unary tt 'js2-parse-member-expr t))
8685 (js2-check-bad-inc-dec tt beg end expr)))
8686 ((= tt js2-DELPROP)
8687 (js2-consume-token)
8688 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8689 ((= tt js2-ERROR)
8690 (js2-consume-token)
8691 (make-js2-error-node)) ; try to continue
8692 ((and (= tt js2-LT)
8693 js2-compiler-xml-available)
8694 ;; XML stream encountered in expression.
8695 (js2-consume-token)
8696 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8697 (t
8698 (setq pn (js2-parse-member-expr t)
8699 ;; Don't look across a newline boundary for a postfix incop.
8700 tt (js2-peek-token-or-eol))
8701 (when (or (= tt js2-INC) (= tt js2-DEC))
8702 (js2-consume-token)
8703 (setf expr pn
8704 pn (js2-make-unary tt expr))
8705 (js2-node-set-prop pn 'postfix t)
8706 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8707 pn))))
8708
8709 (defun js2-parse-xml-initializer ()
8710 "Parse an E4X XML initializer.
8711 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8712 Then I'll postprocess the result, depending on whether we're in IDE
8713 mode or codegen mode, and generate the appropriate rewritten AST.
8714 IDE mode uses a rich AST that models the XML structure. Codegen mode
8715 just concatenates everything and makes a new XML or XMLList out of it."
8716 (let ((tt (js2-get-first-xml-token))
8717 pn-xml pn expr kids expr-pos
8718 (continue t)
8719 (first-token t))
8720 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8721 (js2-report-error "msg.syntax"))
8722 (setq pn-xml (make-js2-xml-node))
8723 (while continue
8724 (if first-token
8725 (setq first-token nil)
8726 (setq tt (js2-get-next-xml-token)))
8727 (cond
8728 ;; js2-XML means we found a {expr} in the XML stream.
8729 ;; The js2-ts-string is the XML up to the left-curly.
8730 ((= tt js2-XML)
8731 (push (make-js2-string-node :pos js2-token-beg
8732 :len (- js2-ts-cursor js2-token-beg))
8733 kids)
8734 (js2-must-match js2-LC "msg.syntax")
8735 (setq expr-pos js2-ts-cursor
8736 expr (if (eq (js2-peek-token) js2-RC)
8737 (make-js2-empty-expr-node :pos expr-pos)
8738 (js2-parse-expr)))
8739 (js2-must-match js2-RC "msg.syntax")
8740 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8741 :len (js2-node-len expr)
8742 :expr expr))
8743 (js2-node-add-children pn expr)
8744 (push pn kids))
8745 ;; a js2-XMLEND token means we hit the final close-tag.
8746 ((= tt js2-XMLEND)
8747 (push (make-js2-string-node :pos js2-token-beg
8748 :len (- js2-ts-cursor js2-token-beg))
8749 kids)
8750 (dolist (kid (nreverse kids))
8751 (js2-block-node-push pn-xml kid))
8752 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8753 (js2-node-pos pn-xml))
8754 continue nil))
8755 (t
8756 (js2-report-error "msg.syntax")
8757 (setq continue nil))))
8758 pn-xml))
8759
8760
8761 (defun js2-parse-argument-list ()
8762 "Parse an argument list and return it as a Lisp list of nodes.
8763 Returns the list in reverse order. Consumes the right-paren token."
8764 (let (result)
8765 (unless (js2-match-token js2-RP)
8766 (loop do
8767 (if (= (js2-peek-token) js2-YIELD)
8768 (js2-report-error "msg.yield.parenthesized"))
8769 (push (js2-parse-assign-expr) result)
8770 while
8771 (js2-match-token js2-COMMA))
8772 (js2-must-match js2-RP "msg.no.paren.arg")
8773 result)))
8774
8775 (defun js2-parse-member-expr (&optional allow-call-syntax)
8776 (let ((tt (js2-peek-token))
8777 pn pos target args beg end init tail)
8778 (if (/= tt js2-NEW)
8779 (setq pn (js2-parse-primary-expr))
8780 ;; parse a 'new' expression
8781 (js2-consume-token)
8782 (setq pos js2-token-beg
8783 beg pos
8784 target (js2-parse-member-expr)
8785 end (js2-node-end target)
8786 pn (make-js2-new-node :pos pos
8787 :target target
8788 :len (- end pos)))
8789 (js2-node-add-children pn target)
8790 (when (js2-match-token js2-LP)
8791 ;; Add the arguments to pn, if any are supplied.
8792 (setf beg pos ; start of "new" keyword
8793 pos js2-token-beg
8794 args (nreverse (js2-parse-argument-list))
8795 (js2-new-node-args pn) args
8796 end js2-token-end
8797 (js2-new-node-lp pn) (- pos beg)
8798 (js2-new-node-rp pn) (- end 1 beg))
8799 (apply #'js2-node-add-children pn args))
8800 (when (and js2-allow-rhino-new-expr-initializer
8801 (js2-match-token js2-LC))
8802 (setf init (js2-parse-object-literal)
8803 end (js2-node-end init)
8804 (js2-new-node-initializer pn) init)
8805 (js2-node-add-children pn init))
8806 (setf (js2-node-len pn) (- end beg))) ; end outer if
8807 (js2-parse-member-expr-tail allow-call-syntax pn)))
8808
8809 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8810 "Parse a chain of property/array accesses or function calls.
8811 Includes parsing for E4X operators like `..' and `.@'.
8812 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8813 Returns an expression tree that includes PN, the parent node."
8814 (let ((beg (js2-node-pos pn))
8815 tt
8816 (continue t))
8817 (while continue
8818 (setq tt (js2-peek-token))
8819 (cond
8820 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8821 (setq pn (js2-parse-property-access tt pn)))
8822 ((= tt js2-DOTQUERY)
8823 (setq pn (js2-parse-dot-query pn)))
8824 ((= tt js2-LB)
8825 (setq pn (js2-parse-element-get pn)))
8826 ((= tt js2-LP)
8827 (if allow-call-syntax
8828 (setq pn (js2-parse-function-call pn))
8829 (setq continue nil)))
8830 (t
8831 (setq continue nil))))
8832 (if (>= js2-highlight-level 2)
8833 (js2-parse-highlight-member-expr-node pn))
8834 pn))
8835
8836 (defun js2-parse-dot-query (pn)
8837 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8838 Last token parsed must be `js2-DOTQUERY'."
8839 (let ((pos (js2-node-pos pn))
8840 op-pos expr end)
8841 (js2-consume-token)
8842 (js2-must-have-xml)
8843 (js2-set-requires-activation)
8844 (setq op-pos js2-token-beg
8845 expr (js2-parse-expr)
8846 end (js2-node-end expr)
8847 pn (make-js2-xml-dot-query-node :left pn
8848 :pos pos
8849 :op-pos op-pos
8850 :right expr))
8851 (js2-node-add-children pn
8852 (js2-xml-dot-query-node-left pn)
8853 (js2-xml-dot-query-node-right pn))
8854 (if (js2-must-match js2-RP "msg.no.paren")
8855 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8856 end js2-token-end))
8857 (setf (js2-node-len pn) (- end pos))
8858 pn))
8859
8860 (defun js2-parse-element-get (pn)
8861 "Parse an element-get expression, e.g. foo[bar].
8862 Last token parsed must be `js2-RB'."
8863 (let ((lb js2-token-beg)
8864 (pos (js2-node-pos pn))
8865 rb expr)
8866 (js2-consume-token)
8867 (setq expr (js2-parse-expr))
8868 (if (js2-must-match js2-RB "msg.no.bracket.index")
8869 (setq rb js2-token-beg))
8870 (setq pn (make-js2-elem-get-node :target pn
8871 :pos pos
8872 :element expr
8873 :lb (js2-relpos lb pos)
8874 :rb (js2-relpos rb pos)
8875 :len (- js2-token-end pos)))
8876 (js2-node-add-children pn
8877 (js2-elem-get-node-target pn)
8878 (js2-elem-get-node-element pn))
8879 pn))
8880
8881 (defun js2-parse-function-call (pn)
8882 (let (args
8883 (pos (js2-node-pos pn)))
8884 (js2-consume-token)
8885 (setq pn (make-js2-call-node :pos pos
8886 :target pn
8887 :lp (- js2-token-beg pos)))
8888 (js2-node-add-children pn (js2-call-node-target pn))
8889 ;; Add the arguments to pn, if any are supplied.
8890 (setf args (nreverse (js2-parse-argument-list))
8891 (js2-call-node-rp pn) (- js2-token-beg pos)
8892 (js2-call-node-args pn) args)
8893 (apply #'js2-node-add-children pn args)
8894 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8895 pn))
8896
8897 (defun js2-parse-property-access (tt pn)
8898 "Parse a property access, XML descendants access, or XML attr access."
8899 (let ((member-type-flags 0)
8900 (dot-pos js2-token-beg)
8901 (dot-len (if (= tt js2-DOTDOT) 2 1))
8902 name
8903 ref ; right side of . or .. operator
8904 result)
8905 (js2-consume-token)
8906 (when (= tt js2-DOTDOT)
8907 (js2-must-have-xml)
8908 (setq member-type-flags js2-descendants-flag))
8909 (if (not js2-compiler-xml-available)
8910 (progn
8911 (js2-must-match-prop-name "msg.no.name.after.dot")
8912 (setq name (js2-create-name-node t js2-GETPROP)
8913 result (make-js2-prop-get-node :left pn
8914 :pos js2-token-beg
8915 :right name
8916 :len (- js2-token-end
8917 js2-token-beg)))
8918 (js2-node-add-children result pn name)
8919 result)
8920 ;; otherwise look for XML operators
8921 (setf result (if (= tt js2-DOT)
8922 (make-js2-prop-get-node)
8923 (make-js2-infix-node :type js2-DOTDOT))
8924 (js2-node-pos result) (js2-node-pos pn)
8925 (js2-infix-node-op-pos result) dot-pos
8926 (js2-infix-node-left result) pn ; do this after setting position
8927 tt (js2-next-token))
8928 (cond
8929 ;; needed for generator.throw()
8930 ((= tt js2-THROW)
8931 (js2-save-name-token-data js2-token-beg "throw")
8932 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8933 ;; handles: name, ns::name, ns::*, ns::[expr]
8934 ((js2-valid-prop-name-token tt)
8935 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8936 ;; handles: *, *::name, *::*, *::[expr]
8937 ((= tt js2-MUL)
8938 (js2-save-name-token-data js2-token-beg "*")
8939 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8940 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8941 ((= tt js2-XMLATTR)
8942 (setq result (js2-parse-attribute-access)))
8943 (t
8944 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8945 (if ref
8946 (setf (js2-node-len result) (- (js2-node-end ref)
8947 (js2-node-pos result))
8948 (js2-infix-node-right result) ref))
8949 (if (js2-infix-node-p result)
8950 (js2-node-add-children result
8951 (js2-infix-node-left result)
8952 (js2-infix-node-right result)))
8953 result)))
8954
8955 (defun js2-parse-attribute-access ()
8956 "Parse an E4X XML attribute expression.
8957 This includes expressions of the forms:
8958
8959 @attr @ns::attr @ns::*
8960 @* @*::attr @*::*
8961 @[expr] @*::[expr] @ns::[expr]
8962
8963 Called if we peeked an '@' token."
8964 (let ((tt (js2-next-token))
8965 (at-pos js2-token-beg))
8966 (cond
8967 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8968 ((js2-valid-prop-name-token tt)
8969 (js2-parse-property-name at-pos js2-ts-string 0))
8970 ;; handles: @*, @*::name, @*::*, @*::[expr]
8971 ((= tt js2-MUL)
8972 (js2-save-name-token-data js2-token-beg "*")
8973 (js2-parse-property-name js2-token-beg "*" 0))
8974 ;; handles @[expr]
8975 ((= tt js2-LB)
8976 (js2-parse-xml-elem-ref at-pos))
8977 (t
8978 (js2-report-error "msg.no.name.after.xmlAttr")
8979 ;; Avoid cascaded errors that happen if we make an error node here.
8980 (js2-save-name-token-data js2-token-beg "")
8981 (js2-parse-property-name js2-token-beg "" 0)))))
8982
8983 (defun js2-parse-property-name (at-pos s member-type-flags)
8984 "Check if :: follows name in which case it becomes qualified name.
8985
8986 AT-POS is a natural number if we just read an '@' token, else nil.
8987 S is the name or string that was matched: an identifier, 'throw' or '*'.
8988 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8989
8990 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8991 operator, or the name is followed by ::. For a plain name, returns a
8992 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8993 (let ((pos (or at-pos js2-token-beg))
8994 colon-pos
8995 (name (js2-create-name-node t js2-current-token))
8996 ns tt ref pn)
8997 (catch 'return
8998 (when (js2-match-token js2-COLONCOLON)
8999 (setq ns name
9000 colon-pos js2-token-beg
9001 tt (js2-next-token))
9002 (cond
9003 ;; handles name::name
9004 ((js2-valid-prop-name-token tt)
9005 (setq name (js2-create-name-node)))
9006 ;; handles name::*
9007 ((= tt js2-MUL)
9008 (js2-save-name-token-data js2-token-beg "*")
9009 (setq name (js2-create-name-node)))
9010 ;; handles name::[expr]
9011 ((= tt js2-LB)
9012 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9013 (t
9014 (js2-report-error "msg.no.name.after.coloncolon"))))
9015 (if (and (null ns) (zerop member-type-flags))
9016 name
9017 (prog1
9018 (setq pn
9019 (make-js2-xml-prop-ref-node :pos pos
9020 :len (- (js2-node-end name) pos)
9021 :at-pos at-pos
9022 :colon-pos colon-pos
9023 :propname name))
9024 (js2-node-add-children pn name))))))
9025
9026 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9027 "Parse the [expr] portion of an xml element reference.
9028 For instance, @[expr], @*::[expr], or ns::[expr]."
9029 (let* ((lb js2-token-beg)
9030 (pos (or at-pos lb))
9031 rb
9032 (expr (js2-parse-expr))
9033 (end (js2-node-end expr))
9034 pn)
9035 (if (js2-must-match js2-RB "msg.no.bracket.index")
9036 (setq rb js2-token-beg
9037 end js2-token-end))
9038 (prog1
9039 (setq pn
9040 (make-js2-xml-elem-ref-node :pos pos
9041 :len (- end pos)
9042 :namespace namespace
9043 :colon-pos colon-pos
9044 :at-pos at-pos
9045 :expr expr
9046 :lb (js2-relpos lb pos)
9047 :rb (js2-relpos rb pos)))
9048 (js2-node-add-children pn namespace expr))))
9049
9050 (defun js2-parse-destruct-primary-expr ()
9051 (let ((js2-is-in-destructuring t))
9052 (js2-parse-primary-expr)))
9053
9054 (defun js2-parse-primary-expr ()
9055 "Parse a literal (leaf) expression of some sort.
9056 Includes complex literals such as functions, object-literals,
9057 array-literals, array comprehensions and regular expressions."
9058 (let ((tt-flagged (js2-next-flagged-token))
9059 pn ; parent node (usually return value)
9060 tt
9061 px-pos ; paren-expr pos
9062 len
9063 flags ; regexp flags
9064 expr)
9065 (setq tt js2-current-token)
9066 (cond
9067 ((= tt js2-FUNCTION)
9068 (js2-parse-function 'FUNCTION_EXPRESSION))
9069 ((= tt js2-LB)
9070 (js2-parse-array-literal))
9071 ((= tt js2-LC)
9072 (js2-parse-object-literal))
9073 ((= tt js2-LET)
9074 (js2-parse-let js2-token-beg))
9075 ((= tt js2-LP)
9076 (setq px-pos js2-token-beg
9077 expr (js2-parse-expr))
9078 (js2-must-match js2-RP "msg.no.paren")
9079 (setq pn (make-js2-paren-node :pos px-pos
9080 :expr expr
9081 :len (- js2-token-end px-pos)))
9082 (js2-node-add-children pn (js2-paren-node-expr pn))
9083 pn)
9084 ((= tt js2-XMLATTR)
9085 (js2-must-have-xml)
9086 (js2-parse-attribute-access))
9087 ((= tt js2-NAME)
9088 (js2-parse-name tt-flagged tt))
9089 ((= tt js2-NUMBER)
9090 (make-js2-number-node))
9091 ((= tt js2-STRING)
9092 (prog1
9093 (make-js2-string-node)
9094 (js2-record-face 'font-lock-string-face)))
9095 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9096 ;; Got / or /= which in this context means a regexp literal
9097 (setq px-pos js2-token-beg)
9098 (js2-read-regexp tt)
9099 (setq flags js2-ts-regexp-flags
9100 js2-ts-regexp-flags nil)
9101 (prog1
9102 (make-js2-regexp-node :pos px-pos
9103 :len (- js2-ts-cursor px-pos)
9104 :value js2-ts-string
9105 :flags flags)
9106 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9107 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9108 ((or (= tt js2-NULL)
9109 (= tt js2-THIS)
9110 (= tt js2-FALSE)
9111 (= tt js2-TRUE))
9112 (make-js2-keyword-node :type tt))
9113 ((= tt js2-RESERVED)
9114 (js2-report-error "msg.reserved.id")
9115 (make-js2-name-node))
9116 ((= tt js2-ERROR)
9117 ;; the scanner or one of its subroutines reported the error.
9118 (make-js2-error-node))
9119 ((= tt js2-EOF)
9120 (setq px-pos (point-at-bol)
9121 len (- js2-ts-cursor px-pos))
9122 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9123 (make-js2-error-node :pos px-pos :len len))
9124 (t
9125 (js2-report-error "msg.syntax")
9126 (make-js2-error-node)))))
9127
9128 (defun js2-parse-name (tt-flagged tt)
9129 (let ((name js2-ts-string)
9130 (name-pos js2-token-beg)
9131 node)
9132 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9133 (= (js2-peek-token) js2-COLON))
9134 (prog1
9135 ;; Do not consume colon, it is used as unwind indicator
9136 ;; to return to statementHelper.
9137 (make-js2-label-node :pos name-pos
9138 :len (- js2-token-end name-pos)
9139 :name name)
9140 (js2-set-face name-pos
9141 js2-token-end
9142 'font-lock-variable-name-face 'record))
9143 ;; Otherwise not a label, just a name. Unfortunately peeking
9144 ;; the next token to check for a colon has biffed js2-token-beg
9145 ;; and js2-token-end. We store the name's bounds in buffer vars
9146 ;; and `js2-create-name-node' uses them.
9147 (js2-save-name-token-data name-pos name)
9148 (setq node (if js2-compiler-xml-available
9149 (js2-parse-property-name nil name 0)
9150 (js2-create-name-node 'check-activation)))
9151 (if js2-highlight-external-variables
9152 (js2-record-name-node node))
9153 node)))
9154
9155 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9156 (js2-add-strict-warning
9157 msg nil
9158 ;; back up from comma to beginning of line or array/objlit
9159 (max (if elems
9160 (js2-node-pos (car elems))
9161 pos)
9162 (save-excursion
9163 (goto-char comma-pos)
9164 (back-to-indentation)
9165 (point)))
9166 comma-pos))
9167
9168 (defun js2-parse-array-literal ()
9169 (let ((pos js2-token-beg)
9170 (end js2-token-end)
9171 (after-lb-or-comma t)
9172 after-comma tt elems pn
9173 (continue t))
9174 (unless js2-is-in-destructuring
9175 (js2-push-scope (make-js2-scope))) ; for array comp
9176 (while continue
9177 (setq tt (js2-peek-token))
9178 (cond
9179 ;; comma
9180 ((= tt js2-COMMA)
9181 (js2-consume-token)
9182 (setq after-comma js2-token-end)
9183 (if (not after-lb-or-comma)
9184 (setq after-lb-or-comma t)
9185 (push nil elems)))
9186 ;; end of array
9187 ((or (= tt js2-RB)
9188 (= tt js2-EOF)) ; prevent infinite loop
9189 (if (= tt js2-EOF)
9190 (js2-report-error "msg.no.bracket.arg" nil pos)
9191 (js2-consume-token))
9192 (setq continue nil
9193 end js2-token-end
9194 pn (make-js2-array-node :pos pos
9195 :len (- js2-ts-cursor pos)
9196 :elems (nreverse elems)))
9197 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9198 (when (and after-comma (not js2-is-in-destructuring))
9199 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9200 pos elems after-comma)))
9201 ;; destructuring binding
9202 (js2-is-in-destructuring
9203 (push (if (or (= tt js2-LC)
9204 (= tt js2-LB)
9205 (= tt js2-NAME))
9206 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9207 (js2-parse-destruct-primary-expr)
9208 ;; invalid pattern
9209 (js2-consume-token)
9210 (js2-report-error "msg.bad.var")
9211 (make-js2-error-node))
9212 elems)
9213 (setq after-lb-or-comma nil
9214 after-comma nil))
9215 ;; array comp
9216 ((and (>= js2-language-version 170)
9217 (= tt js2-FOR) ; check for array comprehension
9218 (not after-lb-or-comma) ; "for" can't follow a comma
9219 elems ; must have at least 1 element
9220 (not (cdr elems))) ; but no 2nd element
9221 (setf continue nil
9222 pn (js2-parse-array-comprehension (car elems) pos)))
9223
9224 ;; another element
9225 (t
9226 (unless after-lb-or-comma
9227 (js2-report-error "msg.no.bracket.arg"))
9228 (push (js2-parse-assign-expr) elems)
9229 (setq after-lb-or-comma nil
9230 after-comma nil))))
9231 (unless js2-is-in-destructuring
9232 (js2-pop-scope))
9233 pn))
9234
9235 (defun js2-parse-array-comprehension (expr pos)
9236 "Parse a JavaScript 1.7 Array Comprehension.
9237 EXPR is the first expression after the opening left-bracket.
9238 POS is the beginning of the LB token preceding EXPR.
9239 We should have just parsed the 'for' keyword before calling this function."
9240 (let (loops loop first prev filter if-pos result)
9241 (while (= (js2-peek-token) js2-FOR)
9242 (let ((prev (car loops))) ; rearrange scope chain
9243 (push (setq loop (js2-parse-array-comp-loop)) loops)
9244 (if prev ; each loop is parent scope to the next one
9245 (setf (js2-scope-parent-scope loop) prev)
9246 ; first loop takes expr scope's parent
9247 (setf (js2-scope-parent-scope (setq first loop))
9248 (js2-scope-parent-scope js2-current-scope)))))
9249 ;; set expr scope's parent to the last loop
9250 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9251 (when (= (js2-peek-token) js2-IF)
9252 (js2-consume-token)
9253 (setq if-pos (- js2-token-beg pos) ; relative
9254 filter (js2-parse-condition)))
9255 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9256 (setq result (make-js2-array-comp-node :pos pos
9257 :len (- js2-ts-cursor pos)
9258 :result expr
9259 :loops (nreverse loops)
9260 :filter (car filter)
9261 :lp (js2-relpos (second filter) pos)
9262 :rp (js2-relpos (third filter) pos)
9263 :if-pos if-pos))
9264 (apply #'js2-node-add-children result expr (car filter)
9265 (js2-array-comp-node-loops result))
9266 (setq js2-current-scope first) ; pop to the first loop
9267 result))
9268
9269 (defun js2-parse-array-comp-loop ()
9270 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9271 Last token peeked should be the initial FOR."
9272 (let ((pos js2-token-beg)
9273 (pn (make-js2-array-comp-loop-node))
9274 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9275 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9276 (js2-push-scope pn)
9277 (unwind-protect
9278 (progn
9279 (when (js2-match-token js2-NAME)
9280 (if (string= js2-ts-string "each")
9281 (progn
9282 (setq foreach-p t
9283 each-pos (- js2-token-beg pos)) ; relative
9284 (js2-record-face 'font-lock-keyword-face))
9285 (js2-report-error "msg.no.paren.for")))
9286 (if (js2-must-match js2-LP "msg.no.paren.for")
9287 (setq lp (- js2-token-beg pos)))
9288 (setq tt (js2-peek-token))
9289 (cond
9290 ((or (= tt js2-LB)
9291 (= tt js2-LC))
9292 (setq iter (js2-parse-destruct-primary-expr))
9293 (js2-define-destruct-symbols iter js2-LET
9294 'font-lock-variable-name-face t))
9295 ((js2-match-token js2-NAME)
9296 (setq iter (js2-create-name-node)))
9297 (t
9298 (js2-report-error "msg.bad.var")))
9299 ;; Define as a let since we want the scope of the variable to
9300 ;; be restricted to the array comprehension
9301 (if (js2-name-node-p iter)
9302 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9303 (if (or (js2-match-token js2-IN)
9304 (and (>= js2-language-version 200)
9305 (js2-match-contextual-kwd "of")
9306 (setq forof-p t)))
9307 (setq in-pos (- js2-token-beg pos))
9308 (js2-report-error "msg.in.after.for.name"))
9309 (setq obj (js2-parse-expr))
9310 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9311 (setq rp (- js2-token-beg pos)))
9312 (setf (js2-node-pos pn) pos
9313 (js2-node-len pn) (- js2-ts-cursor pos)
9314 (js2-array-comp-loop-node-iterator pn) iter
9315 (js2-array-comp-loop-node-object pn) obj
9316 (js2-array-comp-loop-node-in-pos pn) in-pos
9317 (js2-array-comp-loop-node-each-pos pn) each-pos
9318 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9319 (js2-array-comp-loop-node-forof-p pn) forof-p
9320 (js2-array-comp-loop-node-lp pn) lp
9321 (js2-array-comp-loop-node-rp pn) rp)
9322 (js2-node-add-children pn iter obj))
9323 (js2-pop-scope))
9324 pn))
9325
9326 (defun js2-parse-object-literal ()
9327 (let ((pos js2-token-beg)
9328 tt elems result after-comma
9329 (continue t))
9330 (while continue
9331 (setq tt (js2-peek-token))
9332 (cond
9333 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9334 ;; {get foo() {...}}, or {set foo(x) {...}}
9335 ((or (js2-valid-prop-name-token tt)
9336 (= tt js2-STRING))
9337 (setq after-comma nil
9338 result (js2-parse-named-prop tt))
9339 (if (and (null result)
9340 (not js2-recover-from-parse-errors))
9341 (setq continue nil)
9342 (push result elems)))
9343 ;; {12: x} or {10.7: x}
9344 ((= tt js2-NUMBER)
9345 (js2-consume-token)
9346 (setq after-comma nil)
9347 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9348 ;; trailing comma
9349 ((= tt js2-RC)
9350 (setq continue nil)
9351 (if after-comma
9352 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9353 pos elems after-comma)))
9354 (t
9355 (js2-report-error "msg.bad.prop")
9356 (unless js2-recover-from-parse-errors
9357 (setq continue nil)))) ; end switch
9358 (if (js2-match-token js2-COMMA)
9359 (setq after-comma js2-token-end)
9360 (setq continue nil))) ; end loop
9361 (js2-must-match js2-RC "msg.no.brace.prop")
9362 (setq result (make-js2-object-node :pos pos
9363 :len (- js2-ts-cursor pos)
9364 :elems (nreverse elems)))
9365 (apply #'js2-node-add-children result (js2-object-node-elems result))
9366 result))
9367
9368 (defun js2-parse-named-prop (tt)
9369 "Parse a name, string, or getter/setter object property.
9370 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9371 (js2-consume-token)
9372 (let ((string-prop (and (= tt js2-STRING)
9373 (make-js2-string-node)))
9374 expr
9375 (ppos js2-token-beg)
9376 (pend js2-token-end)
9377 (name (js2-create-name-node))
9378 (prop js2-ts-string))
9379 (cond
9380 ;; getter/setter prop
9381 ((and (= tt js2-NAME)
9382 (= (js2-peek-token) js2-NAME)
9383 (or (string= prop "get")
9384 (string= prop "set")))
9385 (js2-consume-token)
9386 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9387 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9388 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9389 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9390 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9391 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9392 ;; when patterns are used in variable declarations, function parameters,
9393 ;; catch-clause, and iterators.
9394 ;; We have to set `js2-is-in-destructuring' to t when the current
9395 ;; expressions are on the left side of any assignment, but it's difficult
9396 ;; because it requires looking ahead of expression.
9397 ((and js2-is-in-destructuring
9398 (= tt js2-NAME)
9399 (let ((ctk (js2-peek-token)))
9400 (or (= ctk js2-COMMA)
9401 (= ctk js2-RC)
9402 (js2-valid-prop-name-token ctk))))
9403 name)
9404 ;; regular prop
9405 (t
9406 (prog1
9407 (setq expr (js2-parse-plain-property (or string-prop name)))
9408 (js2-set-face ppos pend
9409 (if (js2-function-node-p
9410 (js2-object-prop-node-right expr))
9411 'font-lock-function-name-face
9412 'font-lock-variable-name-face)
9413 'record))))))
9414
9415 (defun js2-parse-plain-property (prop)
9416 "Parse a non-getter/setter property in an object literal.
9417 PROP is the node representing the property: a number, name or string."
9418 (js2-must-match js2-COLON "msg.no.colon.prop")
9419 (let* ((pos (js2-node-pos prop))
9420 (colon (- js2-token-beg pos))
9421 (expr (js2-parse-assign-expr))
9422 (result (make-js2-object-prop-node
9423 :pos pos
9424 ;; don't include last consumed token in length
9425 :len (- (+ (js2-node-pos expr)
9426 (js2-node-len expr))
9427 pos)
9428 :left prop
9429 :right expr
9430 :op-pos colon)))
9431 (js2-node-add-children result prop expr)
9432 result))
9433
9434 (defun js2-parse-getter-setter-prop (pos prop get-p)
9435 "Parse getter or setter property in an object literal.
9436 JavaScript syntax is:
9437
9438 { get foo() {...}, set foo(x) {...} }
9439
9440 and expression closure style is also supported
9441
9442 { get foo() x, set foo(x) _x = x }
9443
9444 POS is the start position of the `get' or `set' keyword.
9445 PROP is the `js2-name-node' representing the property name.
9446 GET-P is non-nil if the keyword was `get'."
9447 (let ((type (if get-p js2-GET js2-SET))
9448 result end
9449 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9450 ;; it has to be an anonymous function, as we already parsed the name
9451 (if (/= (js2-node-type fn) js2-FUNCTION)
9452 (js2-report-error "msg.bad.prop")
9453 (if (plusp (length (js2-function-name fn)))
9454 (js2-report-error "msg.bad.prop")))
9455 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9456 (setq end (js2-node-end fn)
9457 result (make-js2-getter-setter-node :type type
9458 :pos pos
9459 :len (- end pos)
9460 :left prop
9461 :right fn))
9462 (js2-node-add-children result prop fn)
9463 result))
9464
9465 (defun js2-create-name-node (&optional check-activation-p token)
9466 "Create a name node using the token info from last scanned name.
9467 In some cases we need to either synthesize a name node, or we lost
9468 the name token information by peeking. If the TOKEN parameter is
9469 not `js2-NAME', then we use the token info saved in instance vars."
9470 (let ((beg js2-token-beg)
9471 (s js2-ts-string)
9472 name)
9473 (when (/= js2-current-token js2-NAME)
9474 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9475 s js2-prev-name-token-string
9476 js2-prev-name-token-start nil
9477 js2-prev-name-token-string nil))
9478 (setq name (make-js2-name-node :pos beg
9479 :name s
9480 :len (length s)))
9481 (if check-activation-p
9482 (js2-check-activation-name s (or token js2-NAME)))
9483 name))
9484
9485 ;;; Indentation support
9486
9487 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9488 ;; Karl cleverly deduces that the desired indentation level is often a
9489 ;; function of paren/bracket/brace nesting depth, which can be determined
9490 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9491 ;; then does some equally clever checks to see if we're in the context of a
9492 ;; substatement of a possibly braceless statement keyword such as if, while,
9493 ;; or finally. This approach yields pretty good results.
9494
9495 ;; The indenter is often "wrong", however, and needs to be overridden.
9496 ;; The right long-term solution is probably to emulate (or integrate
9497 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9498 ;; parse tree from `js2-parse' is present, which is not true at the
9499 ;; moment the user is typing, computing indentation is still thousands
9500 ;; of lines of code to handle every possible syntactic edge case.
9501
9502 ;; In the meantime, the compromise solution is that we offer a "bounce
9503 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9504 ;; current line indent among various likely guess points. This approach
9505 ;; is far from perfect, but should at least make it slightly easier to
9506 ;; move the line towards its desired indentation when manually
9507 ;; overriding Karl's heuristic nesting guesser.
9508
9509 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9510 ;; extensions such as `let' and Array comprehensions. Major kudos to
9511 ;; Karl for coming up with the initial approach, which packs a lot of
9512 ;; punch for so little code.
9513
9514 (defconst js2-possibly-braceless-keywords-re
9515 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9516 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9517 "try" "while" "with" "let")))
9518 "Regular expression matching keywords that are optionally
9519 followed by an opening brace.")
9520
9521 (defconst js2-indent-operator-re
9522 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9523 (regexp-opt '("in" "instanceof") 'words))
9524 "Regular expression matching operators that affect indentation
9525 of continued expressions.")
9526
9527 (defconst js2-declaration-keyword-re
9528 (regexp-opt '("var" "let" "const") 'words)
9529 "Regular expression matching variable declaration keywords.")
9530
9531 ;; This function has horrible results if you're typing an array
9532 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9533 ;; in conjunction with electric-indent, so just disabling it.
9534 (defsubst js2-code-at-bol-p ()
9535 "Return t if the first character on line is non-whitespace."
9536 nil)
9537
9538 (defun js2-insert-and-indent (key)
9539 "Run command bound to KEY and indent current line.
9540 Runs the command bound to KEY in the global keymap and indents
9541 the current line."
9542 (interactive (list (this-command-keys)))
9543 (let ((cmd (lookup-key (current-global-map) key)))
9544 (if (commandp cmd)
9545 (call-interactively cmd)))
9546 ;; don't do the electric keys inside comments or strings,
9547 ;; and don't do bounce-indent with them.
9548 (let ((parse-state (syntax-ppss (point)))
9549 (js2-bounce-indent-p (js2-code-at-bol-p)))
9550 (unless (or (nth 3 parse-state)
9551 (nth 4 parse-state))
9552 (indent-according-to-mode))))
9553
9554 (defun js2-re-search-forward-inner (regexp &optional bound count)
9555 "Auxiliary function for `js2-re-search-forward'."
9556 (let (parse saved-point)
9557 (while (> count 0)
9558 (re-search-forward regexp bound)
9559 (setq parse (if saved-point
9560 (parse-partial-sexp saved-point (point))
9561 (syntax-ppss (point))))
9562 (cond ((nth 3 parse)
9563 (re-search-forward
9564 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9565 (save-excursion (end-of-line) (point)) t))
9566 ((nth 7 parse)
9567 (forward-line))
9568 ((or (nth 4 parse)
9569 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9570 (re-search-forward "\\*/"))
9571 (t
9572 (setq count (1- count))))
9573 (setq saved-point (point))))
9574 (point))
9575
9576 (defun js2-re-search-forward (regexp &optional bound noerror count)
9577 "Search forward but ignore strings and comments.
9578 Invokes `re-search-forward' but treats the buffer as if strings
9579 and comments have been removed."
9580 (let ((saved-point (point))
9581 (search-expr
9582 (cond ((null count)
9583 '(js2-re-search-forward-inner regexp bound 1))
9584 ((< count 0)
9585 '(js2-re-search-backward-inner regexp bound (- count)))
9586 ((> count 0)
9587 '(js2-re-search-forward-inner regexp bound count)))))
9588 (condition-case err
9589 (eval search-expr)
9590 (search-failed
9591 (goto-char saved-point)
9592 (unless noerror
9593 (error (error-message-string err)))))))
9594
9595 (defun js2-re-search-backward-inner (regexp &optional bound count)
9596 "Auxiliary function for `js2-re-search-backward'."
9597 (let (parse)
9598 (while (> count 0)
9599 (re-search-backward regexp bound)
9600 (setq parse (syntax-ppss (point)))
9601 (cond ((nth 3 parse)
9602 (re-search-backward
9603 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9604 (line-beginning-position) t))
9605 ((nth 7 parse)
9606 (goto-char (nth 8 parse)))
9607 ((or (nth 4 parse)
9608 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9609 (re-search-backward "/\\*"))
9610 (t
9611 (setq count (1- count))))))
9612 (point))
9613
9614 (defun js2-re-search-backward (regexp &optional bound noerror count)
9615 "Search backward but ignore strings and comments.
9616 Invokes `re-search-backward' but treats the buffer as if strings
9617 and comments have been removed."
9618 (let ((saved-point (point))
9619 (search-expr
9620 (cond ((null count)
9621 '(js2-re-search-backward-inner regexp bound 1))
9622 ((< count 0)
9623 '(js2-re-search-forward-inner regexp bound (- count)))
9624 ((> count 0)
9625 '(js2-re-search-backward-inner regexp bound count)))))
9626 (condition-case err
9627 (eval search-expr)
9628 (search-failed
9629 (goto-char saved-point)
9630 (unless noerror
9631 (error (error-message-string err)))))))
9632
9633 (defun js2-looking-at-operator-p ()
9634 "Return non-nil if text after point is a non-comma operator."
9635 (and (looking-at js2-indent-operator-re)
9636 (or (not (looking-at ":"))
9637 (save-excursion
9638 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9639 (looking-at "?"))))))
9640
9641 (defun js2-continued-expression-p ()
9642 "Return non-nil if the current line continues an expression."
9643 (save-excursion
9644 (back-to-indentation)
9645 (or (js2-looking-at-operator-p)
9646 (when (catch 'found
9647 (while (and (re-search-backward "\n" nil t)
9648 (let ((state (syntax-ppss)))
9649 (when (nth 4 state)
9650 (goto-char (nth 8 state))) ;; skip comments
9651 (skip-chars-backward " \t")
9652 (if (bolp)
9653 t
9654 (throw 'found t))))))
9655 (backward-char)
9656 (when (js2-looking-at-operator-p)
9657 (backward-char)
9658 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9659
9660 (defun js2-end-of-do-while-loop-p ()
9661 "Return non-nil if word after point is `while' of a do-while
9662 statement, else returns nil. A braceless do-while statement
9663 spanning several lines requires that the start of the loop is
9664 indented to the same column as the current line."
9665 (interactive)
9666 (save-excursion
9667 (when (looking-at "\\s-*\\<while\\>")
9668 (if (save-excursion
9669 (skip-chars-backward "[ \t\n]*}")
9670 (looking-at "[ \t\n]*}"))
9671 (save-excursion
9672 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9673 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9674 (or (looking-at "\\<do\\>")
9675 (let ((saved-indent (current-indentation)))
9676 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9677 (/= (current-indentation) saved-indent)))
9678 (and (looking-at "[ \t]*\\<do\\>")
9679 (not (js2-re-search-forward
9680 "\\<while\\>" (point-at-eol) t))
9681 (= (current-indentation) saved-indent))))))))
9682
9683 (defun js2-multiline-decl-indentation ()
9684 "Return the declaration indentation column if the current line belongs
9685 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9686 (let (forward-sexp-function ; use Lisp version
9687 at-opening-bracket)
9688 (save-excursion
9689 (back-to-indentation)
9690 (when (not (looking-at js2-declaration-keyword-re))
9691 (when (looking-at js2-indent-operator-re)
9692 (goto-char (match-end 0))) ; continued expressions are ok
9693 (while (and (not at-opening-bracket)
9694 (not (bobp))
9695 (let ((pos (point)))
9696 (save-excursion
9697 (js2-backward-sws)
9698 (or (eq (char-before) ?,)
9699 (and (not (eq (char-before) ?\;))
9700 (and
9701 (prog2 (skip-chars-backward "[[:punct:]]")
9702 (looking-at js2-indent-operator-re)
9703 (js2-backward-sws))
9704 (not (eq (char-before) ?\;))))
9705 (js2-same-line pos)))))
9706 (condition-case err
9707 (backward-sexp)
9708 (scan-error (setq at-opening-bracket t))))
9709 (when (looking-at js2-declaration-keyword-re)
9710 (goto-char (match-end 0))
9711 (1+ (current-column)))))))
9712
9713 (defun js2-ctrl-statement-indentation ()
9714 "Return the proper indentation of current line if it is a control statement.
9715 Returns an indentation if this line starts the body of a control
9716 statement without braces, else returns nil."
9717 (let (forward-sexp-function)
9718 (save-excursion
9719 (back-to-indentation)
9720 (when (and (not (js2-same-line (point-min)))
9721 (not (looking-at "{"))
9722 (js2-re-search-backward "[[:graph:]]" nil t)
9723 (not (looking-at "[{([]"))
9724 (progn
9725 (forward-char)
9726 (when (= (char-before) ?\))
9727 ;; scan-sexps sometimes throws an error
9728 (ignore-errors (backward-sexp))
9729 (skip-chars-backward " \t" (point-at-bol)))
9730 (let ((pt (point)))
9731 (back-to-indentation)
9732 (and (looking-at js2-possibly-braceless-keywords-re)
9733 (= (match-end 0) pt)
9734 (not (js2-end-of-do-while-loop-p))))))
9735 (+ (current-indentation) js2-basic-offset)))))
9736
9737 (defun js2-indent-in-array-comp (parse-status)
9738 "Return non-nil if we think we're in an array comprehension.
9739 In particular, return the buffer position of the first `for' kwd."
9740 (let ((bracket (nth 1 parse-status))
9741 (end (point)))
9742 (when bracket
9743 (save-excursion
9744 (goto-char bracket)
9745 (when (looking-at "\\[")
9746 (forward-char 1)
9747 (js2-forward-sws)
9748 (if (looking-at "[[{]")
9749 (let (forward-sexp-function) ; use Lisp version
9750 (forward-sexp) ; skip destructuring form
9751 (js2-forward-sws)
9752 (if (and (/= (char-after) ?,) ; regular array
9753 (looking-at "for"))
9754 (match-beginning 0)))
9755 ;; to skip arbitrary expressions we need the parser,
9756 ;; so we'll just guess at it.
9757 (if (and (> end (point)) ; not empty literal
9758 (re-search-forward "[^,]]* \\(for\\) " end t)
9759 ;; not inside comment or string literal
9760 (let ((state (parse-partial-sexp bracket (point))))
9761 (not (or (nth 3 state) (nth 4 state)))))
9762 (match-beginning 1))))))))
9763
9764 (defun js2-array-comp-indentation (parse-status for-kwd)
9765 (if (js2-same-line for-kwd)
9766 ;; first continuation line
9767 (save-excursion
9768 (goto-char (nth 1 parse-status))
9769 (forward-char 1)
9770 (skip-chars-forward " \t")
9771 (current-column))
9772 (save-excursion
9773 (goto-char for-kwd)
9774 (current-column))))
9775
9776 (defun js2-proper-indentation (parse-status)
9777 "Return the proper indentation for the current line."
9778 (save-excursion
9779 (back-to-indentation)
9780 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9781 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9782 (continued-expr-p (js2-continued-expression-p))
9783 (declaration-indent (and js2-pretty-multiline-declarations
9784 (js2-multiline-decl-indentation)))
9785 (bracket (nth 1 parse-status))
9786 beg)
9787 (cond
9788 ;; indent array comprehension continuation lines specially
9789 ((and bracket
9790 (>= js2-language-version 170)
9791 (not (js2-same-line bracket))
9792 (setq beg (js2-indent-in-array-comp parse-status))
9793 (>= (point) (save-excursion
9794 (goto-char beg)
9795 (point-at-bol)))) ; at or after first loop?
9796 (js2-array-comp-indentation parse-status beg))
9797
9798 (ctrl-stmt-indent)
9799
9800 ((and declaration-indent continued-expr-p)
9801 (+ declaration-indent js2-basic-offset))
9802
9803 (declaration-indent)
9804
9805 (bracket
9806 (goto-char bracket)
9807 (cond
9808 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9809 (when (save-excursion (skip-chars-backward " \t)")
9810 (looking-at ")"))
9811 (backward-list))
9812 (back-to-indentation)
9813 (and (eq js2-pretty-multiline-declarations 'all)
9814 (looking-at js2-declaration-keyword-re)
9815 (goto-char (1+ (match-end 0))))
9816 (cond (same-indent-p
9817 (current-column))
9818 (continued-expr-p
9819 (+ (current-column) (* 2 js2-basic-offset)))
9820 (t
9821 (+ (current-column) js2-basic-offset))))
9822 (t
9823 (unless same-indent-p
9824 (forward-char)
9825 (skip-chars-forward " \t"))
9826 (current-column))))
9827
9828 (continued-expr-p js2-basic-offset)
9829
9830 (t 0)))))
9831
9832 (defun js2-lineup-comment (parse-status)
9833 "Indent a multi-line block comment continuation line."
9834 (let* ((beg (nth 8 parse-status))
9835 (first-line (js2-same-line beg))
9836 (offset (save-excursion
9837 (goto-char beg)
9838 (if (looking-at "/\\*")
9839 (+ 1 (current-column))
9840 0))))
9841 (unless first-line
9842 (indent-line-to offset))))
9843
9844 (defun js2-backward-sws ()
9845 "Move backward through whitespace and comments."
9846 (interactive)
9847 (while (forward-comment -1)))
9848
9849 (defun js2-forward-sws ()
9850 "Move forward through whitespace and comments."
9851 (interactive)
9852 (while (forward-comment 1)))
9853
9854 (defun js2-current-indent (&optional pos)
9855 "Return column of indentation on current line.
9856 If POS is non-nil, go to that point and return indentation for that line."
9857 (save-excursion
9858 (if pos
9859 (goto-char pos))
9860 (back-to-indentation)
9861 (current-column)))
9862
9863 (defun js2-arglist-close ()
9864 "Return non-nil if we're on a line beginning with a close-paren/brace."
9865 (save-excursion
9866 (goto-char (point-at-bol))
9867 (js2-forward-sws)
9868 (looking-at "[])}]")))
9869
9870 (defun js2-indent-looks-like-label-p ()
9871 (goto-char (point-at-bol))
9872 (js2-forward-sws)
9873 (looking-at (concat js2-mode-identifier-re ":")))
9874
9875 (defun js2-indent-in-objlit-p (parse-status)
9876 "Return non-nil if this looks like an object-literal entry."
9877 (let ((start (nth 1 parse-status)))
9878 (and
9879 start
9880 (save-excursion
9881 (and (zerop (forward-line -1))
9882 (not (< (point) start)) ; crossed a {} boundary
9883 (js2-indent-looks-like-label-p)))
9884 (save-excursion
9885 (js2-indent-looks-like-label-p)))))
9886
9887 ;; If prev line looks like foobar({ then we're passing an object
9888 ;; literal to a function call, and people pretty much always want to
9889 ;; de-dent back to the previous line, so move the 'basic-offset'
9890 ;; position to the front.
9891 (defun js2-indent-objlit-arg-p (parse-status)
9892 (save-excursion
9893 (back-to-indentation)
9894 (js2-backward-sws)
9895 (and (eq (1- (point)) (nth 1 parse-status))
9896 (eq (char-before) ?{)
9897 (progn
9898 (forward-char -1)
9899 (skip-chars-backward " \t")
9900 (eq (char-before) ?\()))))
9901
9902 (defun js2-indent-case-block-p ()
9903 (save-excursion
9904 (back-to-indentation)
9905 (js2-backward-sws)
9906 (goto-char (point-at-bol))
9907 (skip-chars-forward " \t")
9908 (looking-at "case\\s-.+:")))
9909
9910 (defun js2-syntax-bol ()
9911 "Return the point at the first non-whitespace char on the line.
9912 Returns `point-at-bol' if the line is empty."
9913 (save-excursion
9914 (beginning-of-line)
9915 (skip-chars-forward " \t")
9916 (point)))
9917
9918 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9919 "Cycle among alternate computed indentation positions.
9920 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9921 of the buffer to the current point. NORMAL-COL is the indentation
9922 column computed by the heuristic guesser based on current paren,
9923 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9924 in reverse."
9925 (let ((cur-indent (js2-current-indent))
9926 (old-buffer-undo-list buffer-undo-list)
9927 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9928 (current-line (save-excursion
9929 (forward-line 0) ; move to bol
9930 (1+ (count-lines (point-min) (point)))))
9931 positions pos main-pos anchor arglist-cont same-indent
9932 prev-line-col basic-offset computed-pos)
9933 ;; temporarily don't record undo info, if user requested this
9934 (when js2-mode-indent-inhibit-undo
9935 (setq buffer-undo-list t))
9936 (unwind-protect
9937 (progn
9938 ;; First likely point: indent from beginning of previous code line
9939 (push (setq basic-offset
9940 (+ (save-excursion
9941 (back-to-indentation)
9942 (js2-backward-sws)
9943 (back-to-indentation)
9944 (setq prev-line-col (current-column)))
9945 js2-basic-offset))
9946 positions)
9947
9948 ;; (First + epsilon) likely point: indent 2x from beginning of
9949 ;; previous code line. Google does it this way.
9950 (push (setq basic-offset
9951 (+ (save-excursion
9952 (back-to-indentation)
9953 (js2-backward-sws)
9954 (back-to-indentation)
9955 (setq prev-line-col (current-column)))
9956 (* 2 js2-basic-offset)))
9957 positions)
9958
9959 ;; Second likely point: indent from assign-expr RHS. This
9960 ;; is just a crude guess based on finding " = " on the previous
9961 ;; line containing actual code.
9962 (setq pos (save-excursion
9963 (forward-line -1)
9964 (goto-char (point-at-bol))
9965 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9966 (point-at-eol) t)
9967 (goto-char (match-end 1))
9968 (skip-chars-forward " \t\r\n")
9969 (current-column))))
9970 (when pos
9971 (incf pos js2-basic-offset)
9972 (push pos positions))
9973
9974 ;; Third likely point: same indent as previous line of code.
9975 ;; Make it the first likely point if we're not on an
9976 ;; arglist-close line and previous line ends in a comma, or
9977 ;; both this line and prev line look like object-literal
9978 ;; elements.
9979 (setq pos (save-excursion
9980 (goto-char (point-at-bol))
9981 (js2-backward-sws)
9982 (back-to-indentation)
9983 (prog1
9984 (current-column)
9985 ;; while we're here, look for trailing comma
9986 (if (save-excursion
9987 (goto-char (point-at-eol))
9988 (js2-backward-sws)
9989 (eq (char-before) ?,))
9990 (setq arglist-cont (1- (point)))))))
9991 (when pos
9992 (if (and (or arglist-cont
9993 (js2-indent-in-objlit-p parse-status))
9994 (not (js2-arglist-close)))
9995 (setq same-indent pos))
9996 (push pos positions))
9997
9998 ;; Fourth likely point: first preceding code with less indentation.
9999 ;; than the immediately preceding code line.
10000 (setq pos (save-excursion
10001 (back-to-indentation)
10002 (js2-backward-sws)
10003 (back-to-indentation)
10004 (setq anchor (current-column))
10005 (while (and (zerop (forward-line -1))
10006 (>= (progn
10007 (back-to-indentation)
10008 (current-column))
10009 anchor)))
10010 (setq pos (current-column))))
10011 (push pos positions)
10012
10013 ;; nesting-heuristic position, main by default
10014 (push (setq main-pos normal-col) positions)
10015
10016 ;; delete duplicates and sort positions list
10017 (setq positions (sort (delete-dups positions) '<))
10018
10019 ;; comma-list continuation lines: prev line indent takes precedence
10020 (if same-indent
10021 (setq main-pos same-indent))
10022
10023 ;; common special cases where we want to indent in from previous line
10024 (if (or (js2-indent-case-block-p)
10025 (js2-indent-objlit-arg-p parse-status))
10026 (setq main-pos basic-offset))
10027
10028 ;; if bouncing backwards, reverse positions list
10029 (if backwards
10030 (setq positions (reverse positions)))
10031
10032 ;; record whether we're already sitting on one of the alternatives
10033 (setq pos (member cur-indent positions))
10034
10035 (cond
10036 ;; case 0: we're one one of the alternatives and this is the
10037 ;; first time they've pressed TAB on this line (best-guess).
10038 ((and js2-mode-indent-ignore-first-tab
10039 pos
10040 ;; first time pressing TAB on this line?
10041 (not (eq js2-mode-last-indented-line current-line)))
10042 ;; do nothing
10043 (setq computed-pos nil))
10044 ;; case 1: only one computed position => use it
10045 ((null (cdr positions))
10046 (setq computed-pos 0))
10047 ;; case 2: not on any of the computed spots => use main spot
10048 ((not pos)
10049 (setq computed-pos (js2-position main-pos positions)))
10050 ;; case 3: on last position: cycle to first position
10051 ((null (cdr pos))
10052 (setq computed-pos 0))
10053 ;; case 4: on intermediate position: cycle to next position
10054 (t
10055 (setq computed-pos (js2-position (second pos) positions))))
10056
10057 ;; see if any hooks want to indent; otherwise we do it
10058 (loop with result = nil
10059 for hook in js2-indent-hook
10060 while (null result)
10061 do
10062 (setq result (funcall hook positions computed-pos))
10063 finally do
10064 (unless (or result (null computed-pos))
10065 (indent-line-to (nth computed-pos positions)))))
10066
10067 ;; finally
10068 (if js2-mode-indent-inhibit-undo
10069 (setq buffer-undo-list old-buffer-undo-list))
10070 ;; see commentary for `js2-mode-last-indented-line'
10071 (setq js2-mode-last-indented-line current-line))))
10072
10073 (defun js2-indent-bounce-backwards ()
10074 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10075 cycles between the computed indentation positions in reverse order."
10076 (interactive)
10077 (js2-indent-line t))
10078
10079 (defun js2-1-line-comment-continuation-p ()
10080 "Return t if we're in a 1-line comment continuation.
10081 If so, we don't ever want to use bounce-indent."
10082 (save-excursion
10083 (and (progn
10084 (forward-line 0)
10085 (looking-at "\\s-*//"))
10086 (progn
10087 (forward-line -1)
10088 (forward-line 0)
10089 (when (looking-at "\\s-*$")
10090 (js2-backward-sws)
10091 (forward-line 0))
10092 (looking-at "\\s-*//")))))
10093
10094 (defun js2-indent-line (&optional bounce-backwards)
10095 "Indent the current line as JavaScript source text."
10096 (interactive)
10097 (let (parse-status current-indent offset indent-col moved
10098 ;; Don't whine about errors/warnings when we're indenting.
10099 ;; This has to be set before calling parse-partial-sexp below.
10100 (inhibit-point-motion-hooks t))
10101 (setq parse-status (save-excursion
10102 (syntax-ppss (point-at-bol)))
10103 offset (- (point) (save-excursion
10104 (back-to-indentation)
10105 (point))))
10106 (js2-with-underscore-as-word-syntax
10107 (if (nth 4 parse-status)
10108 (js2-lineup-comment parse-status)
10109 (setq indent-col (js2-proper-indentation parse-status))
10110 ;; See comments below about `js2-mode-last-indented-line'.
10111 (cond
10112 ;; bounce-indenting is disabled during electric-key indent.
10113 ;; It doesn't work well on first line of buffer.
10114 ((and js2-bounce-indent-p
10115 (not (js2-same-line (point-min)))
10116 (not (js2-1-line-comment-continuation-p)))
10117 (js2-bounce-indent indent-col parse-status bounce-backwards))
10118 ;; just indent to the guesser's likely spot
10119 (t (indent-line-to indent-col))))
10120 (when (plusp offset)
10121 (forward-char offset)))))
10122
10123 (defun js2-indent-region (start end)
10124 "Indent the region, but don't use bounce indenting."
10125 (let ((js2-bounce-indent-p nil)
10126 (indent-region-function nil)
10127 (after-change-functions (remq 'js2-mode-edit
10128 after-change-functions)))
10129 (indent-region start end nil) ; nil for byte-compiler
10130 (js2-mode-edit start end (- end start))))
10131
10132 (defvar js2-minor-mode-map
10133 (let ((map (make-sparse-keymap)))
10134 (define-key map (kbd "C-c C-`") #'js2-next-error)
10135 (define-key map [mouse-1] #'js2-mode-show-node)
10136 map)
10137 "Keymap used when `js2-minor-mode' is active.")
10138
10139 ;;;###autoload
10140 (define-minor-mode js2-minor-mode
10141 "Minor mode for running js2 as a background linter.
10142 This allows you to use a different major mode for JavaScript editing,
10143 such as `espresso-mode', while retaining the asynchronous error/warning
10144 highlighting features of `js2-mode'."
10145 :group 'js2-mode
10146 :lighter " js-lint"
10147 (if js2-minor-mode
10148 (js2-minor-mode-enter)
10149 (js2-minor-mode-exit)))
10150
10151 (defun js2-minor-mode-enter ()
10152 "Initialization for `js2-minor-mode'."
10153 (set (make-local-variable 'max-lisp-eval-depth)
10154 (max max-lisp-eval-depth 3000))
10155 (setq next-error-function #'js2-next-error)
10156 (setq js2-default-externs
10157 (append js2-ecma-262-externs
10158 (if js2-include-browser-externs js2-browser-externs)
10159 (if js2-include-gears-externs js2-gears-externs)
10160 (if js2-include-rhino-externs js2-rhino-externs)))
10161 ;; Experiment: make reparse-delay longer for longer files.
10162 (if (plusp js2-dynamic-idle-timer-adjust)
10163 (setq js2-idle-timer-delay
10164 (* js2-idle-timer-delay
10165 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10166 (setq js2-mode-buffer-dirty-p t
10167 js2-mode-parsing nil)
10168 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10169 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10170 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10171 (js2-reparse))
10172
10173 (defun js2-minor-mode-exit ()
10174 "Turn off `js2-minor-mode'."
10175 (setq next-error-function nil)
10176 (remove-hook 'after-change-functions #'js2-mode-edit t)
10177 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10178 (when js2-mode-node-overlay
10179 (delete-overlay js2-mode-node-overlay)
10180 (setq js2-mode-node-overlay nil))
10181 (js2-remove-overlays)
10182 (setq js2-mode-ast nil))
10183
10184 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10185 (make-variable-buffer-local 'js2-source-buffer)
10186
10187 (defun* js2-display-error-list ()
10188 "Display a navigable buffer listing parse errors/warnings."
10189 (interactive)
10190 (unless (js2-have-errors-p)
10191 (message "No errors")
10192 (return-from js2-display-error-list))
10193 (labels ((annotate-list
10194 (lst type)
10195 "Add diagnostic TYPE and line number to errs list"
10196 (mapcar (lambda (err)
10197 (list err type (line-number-at-pos (nth 1 err))))
10198 lst)))
10199 (let* ((srcbuf (current-buffer))
10200 (errbuf (get-buffer-create "*js-lint*"))
10201 (errors (annotate-list
10202 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10203 'js2-error)) ; must be a valid face name
10204 (warnings (annotate-list
10205 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10206 'js2-warning)) ; must be a valid face name
10207 (all-errs (sort (append errors warnings)
10208 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10209 (with-current-buffer errbuf
10210 (let ((inhibit-read-only t))
10211 (erase-buffer)
10212 (dolist (err all-errs)
10213 (destructuring-bind ((msg-key beg end &rest) type line) err
10214 (insert-text-button
10215 (format "line %d: %s" line (js2-get-msg msg-key))
10216 'face type
10217 'follow-link "\C-m"
10218 'action 'js2-error-buffer-jump
10219 'js2-msg (js2-get-msg msg-key)
10220 'js2-pos beg)
10221 (insert "\n"))))
10222 (js2-error-buffer-mode)
10223 (setq js2-source-buffer srcbuf)
10224 (pop-to-buffer errbuf)
10225 (goto-char (point-min))
10226 (unless (eobp)
10227 (js2-error-buffer-view))))))
10228
10229 (defvar js2-error-buffer-mode-map
10230 (let ((map (make-sparse-keymap)))
10231 (define-key map "n" #'js2-error-buffer-next)
10232 (define-key map "p" #'js2-error-buffer-prev)
10233 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10234 (define-key map "o" #'js2-error-buffer-view)
10235 (define-key map "q" #'js2-error-buffer-quit)
10236 map)
10237 "Keymap used for js2 diagnostics buffers.")
10238
10239 (defun js2-error-buffer-mode ()
10240 "Major mode for js2 diagnostics buffers.
10241 Selecting an error will jump it to the corresponding source-buffer error.
10242 \\{js2-error-buffer-mode-map}"
10243 (interactive)
10244 (setq major-mode 'js2-error-buffer-mode
10245 mode-name "JS Lint Diagnostics")
10246 (use-local-map js2-error-buffer-mode-map)
10247 (setq truncate-lines t)
10248 (set-buffer-modified-p nil)
10249 (setq buffer-read-only t)
10250 (run-hooks 'js2-error-buffer-mode-hook))
10251
10252 (defun js2-error-buffer-next ()
10253 "Move to next error and view it."
10254 (interactive)
10255 (when (zerop (forward-line 1))
10256 (js2-error-buffer-view)))
10257
10258 (defun js2-error-buffer-prev ()
10259 "Move to previous error and view it."
10260 (interactive)
10261 (when (zerop (forward-line -1))
10262 (js2-error-buffer-view)))
10263
10264 (defun js2-error-buffer-quit ()
10265 "Kill the current buffer."
10266 (interactive)
10267 (kill-buffer))
10268
10269 (defun js2-error-buffer-jump (&rest ignored)
10270 "Jump cursor to current error in source buffer."
10271 (interactive)
10272 (when (js2-error-buffer-view)
10273 (pop-to-buffer js2-source-buffer)))
10274
10275 (defun js2-error-buffer-view ()
10276 "Scroll source buffer to show error at current line."
10277 (interactive)
10278 (cond
10279 ((not (eq major-mode 'js2-error-buffer-mode))
10280 (message "Not in a js2 errors buffer"))
10281 ((not (buffer-live-p js2-source-buffer))
10282 (message "Source buffer has been killed"))
10283 ((not (wholenump (get-text-property (point) 'js2-pos)))
10284 (message "There does not seem to be an error here"))
10285 (t
10286 (let ((pos (get-text-property (point) 'js2-pos))
10287 (msg (get-text-property (point) 'js2-msg)))
10288 (save-selected-window
10289 (pop-to-buffer js2-source-buffer)
10290 (goto-char pos)
10291 (message msg))))))
10292
10293 ;;;###autoload
10294 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10295 ;; FIXME: Should derive from js-mode.
10296 "Major mode for editing JavaScript code."
10297 (setq comment-start "//" ; used by comment-region; don't change it
10298 comment-end "")
10299 (set (make-local-variable 'max-lisp-eval-depth)
10300 (max max-lisp-eval-depth 3000))
10301 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10302 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10303 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10304 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10305 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10306 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10307 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10308 ;; for characters inside regexp literals.
10309 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10310 ;; this is necessary to make `show-paren-function' work properly
10311 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10312 ;; needed for M-x rgrep, among other things
10313 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10314
10315 (set (make-local-variable 'electric-indent-chars)
10316 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10317 electric-indent-chars))
10318 (set (make-local-variable 'electric-layout-rules)
10319 '((?\; . after) (?\{ . after) (?\} . before)))
10320
10321 ;; some variables needed by cc-engine for paragraph-fill, etc.
10322 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10323 c-comment-start-regexp "/[*/]\\|\\s|"
10324 c-line-comment-starter "//"
10325 c-paragraph-start js2-paragraph-start
10326 c-paragraph-separate "$"
10327 comment-start-skip js2-comment-start-skip
10328 c-syntactic-ws-start js2-syntactic-ws-start
10329 c-syntactic-ws-end js2-syntactic-ws-end
10330 c-syntactic-eol js2-syntactic-eol)
10331
10332 (let ((c-buffer-is-cc-mode t))
10333 ;; Copied from `js-mode'. Also see Bug#6071.
10334 (make-local-variable 'paragraph-start)
10335 (make-local-variable 'paragraph-separate)
10336 (make-local-variable 'paragraph-ignore-fill-prefix)
10337 (make-local-variable 'adaptive-fill-mode)
10338 (make-local-variable 'adaptive-fill-regexp)
10339 (c-setup-paragraph-variables))
10340
10341 (setq js2-default-externs
10342 (append js2-ecma-262-externs
10343 (if js2-include-browser-externs js2-browser-externs)
10344 (if js2-include-gears-externs js2-gears-externs)
10345 (if js2-include-rhino-externs js2-rhino-externs)))
10346
10347 (setq font-lock-defaults '(nil t))
10348
10349 ;; Experiment: make reparse-delay longer for longer files.
10350 (when (plusp js2-dynamic-idle-timer-adjust)
10351 (setq js2-idle-timer-delay
10352 (* js2-idle-timer-delay
10353 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10354
10355 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10356 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10357 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10358 (setq next-error-function #'js2-next-error)
10359 (imenu-add-to-menubar (concat "IM-" mode-name))
10360 (add-to-invisibility-spec '(js2-outline . t))
10361 (set (make-local-variable 'line-move-ignore-invisible) t)
10362 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10363
10364 (setq js2-mode-functions-hidden nil
10365 js2-mode-comments-hidden nil
10366 js2-mode-buffer-dirty-p t
10367 js2-mode-parsing nil)
10368 (js2-reparse))
10369
10370 (defun js2-mode-exit ()
10371 "Exit `js2-mode' and clean up."
10372 (interactive)
10373 (when js2-mode-node-overlay
10374 (delete-overlay js2-mode-node-overlay)
10375 (setq js2-mode-node-overlay nil))
10376 (js2-remove-overlays)
10377 (setq js2-mode-ast nil)
10378 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10379 (remove-from-invisibility-spec '(js2-outline . t))
10380 (js2-mode-show-all)
10381 (with-silent-modifications
10382 (js2-clear-face (point-min) (point-max))))
10383
10384 (defun js2-mode-reset-timer ()
10385 "Cancel any existing parse timer and schedule a new one."
10386 (if js2-mode-parse-timer
10387 (cancel-timer js2-mode-parse-timer))
10388 (setq js2-mode-parsing nil)
10389 (let ((timer (timer-create)))
10390 (setq js2-mode-parse-timer timer)
10391 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10392 (timer-set-idle-time timer js2-idle-timer-delay)
10393 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10394 (timer-activate-when-idle timer nil)))
10395
10396 (defun js2-mode-idle-reparse (buffer)
10397 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10398 it to be reparsed when the buffer is selected."
10399 (if (eq buffer (current-buffer))
10400 (js2-reparse)
10401 ;; reparse when the buffer is selected again
10402 (with-current-buffer buffer
10403 (add-hook 'window-configuration-change-hook
10404 #'js2-mode-idle-reparse-inner
10405 nil t))))
10406
10407 (defun js2-mode-idle-reparse-inner ()
10408 (remove-hook 'window-configuration-change-hook
10409 #'js2-mode-idle-reparse-inner
10410 t)
10411 (js2-reparse))
10412
10413 (defun js2-mode-edit (beg end len)
10414 "Schedule a new parse after buffer is edited.
10415 Buffer edit spans from BEG to END and is of length LEN."
10416 (setq js2-mode-buffer-dirty-p t)
10417 (js2-mode-hide-overlay)
10418 (js2-mode-reset-timer))
10419
10420 (defun js2-minor-mode-edit (beg end len)
10421 "Callback for buffer edits in `js2-mode'.
10422 Schedules a new parse after buffer is edited.
10423 Buffer edit spans from BEG to END and is of length LEN."
10424 (setq js2-mode-buffer-dirty-p t)
10425 (js2-mode-hide-overlay)
10426 (js2-mode-reset-timer))
10427
10428 (defun js2-reparse (&optional force)
10429 "Re-parse current buffer after user finishes some data entry.
10430 If we get any user input while parsing, including cursor motion,
10431 we discard the parse and reschedule it. If FORCE is nil, then the
10432 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10433 (let (time
10434 interrupted-p
10435 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10436 (unless js2-mode-parsing
10437 (setq js2-mode-parsing t)
10438 (unwind-protect
10439 (when (or js2-mode-buffer-dirty-p force)
10440 (js2-remove-overlays)
10441 (with-silent-modifications
10442 (setq js2-mode-buffer-dirty-p nil
10443 js2-mode-fontifications nil
10444 js2-mode-deferred-properties nil)
10445 (if js2-mode-verbose-parse-p
10446 (message "parsing..."))
10447 (setq time
10448 (js2-time
10449 (setq interrupted-p
10450 (catch 'interrupted
10451 (js2-parse)
10452 ;; if parsing is interrupted, comments and regex
10453 ;; literals stay ignored by `parse-partial-sexp'
10454 (remove-text-properties (point-min) (point-max)
10455 '(syntax-table))
10456 (js2-mode-apply-deferred-properties)
10457 (js2-mode-remove-suppressed-warnings)
10458 (js2-mode-show-warnings)
10459 (js2-mode-show-errors)
10460 (if (>= js2-highlight-level 1)
10461 (js2-highlight-jsdoc js2-mode-ast))
10462 nil))))
10463 (if interrupted-p
10464 (progn
10465 ;; unfinished parse => try again
10466 (setq js2-mode-buffer-dirty-p t)
10467 (js2-mode-reset-timer))
10468 (if js2-mode-verbose-parse-p
10469 (message "Parse time: %s" time)))))
10470 (setq js2-mode-parsing nil)
10471 (unless interrupted-p
10472 (setq js2-mode-parse-timer nil))))))
10473
10474 (defun js2-mode-show-node (event)
10475 "Debugging aid: highlight selected AST node on mouse click."
10476 (interactive "e")
10477 (mouse-set-point event)
10478 (setq deactivate-mark t)
10479 (when js2-mode-show-overlay
10480 (let ((node (js2-node-at-point))
10481 beg end)
10482 (if (null node)
10483 (message "No node found at location %s" (point))
10484 (setq beg (js2-node-abs-pos node)
10485 end (+ beg (js2-node-len node)))
10486 (if js2-mode-node-overlay
10487 (move-overlay js2-mode-node-overlay beg end)
10488 (setq js2-mode-node-overlay (make-overlay beg end))
10489 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10490 (with-silent-modifications
10491 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10492 (message "%s, parent: %s"
10493 (js2-node-short-name node)
10494 (if (js2-node-parent node)
10495 (js2-node-short-name (js2-node-parent node))
10496 "nil"))))))
10497
10498 (defun js2-mode-hide-overlay (&optional p1 p2)
10499 "Remove the debugging overlay when the point moves.
10500 P1 and P2 are the old and new values of point, respectively."
10501 (when js2-mode-node-overlay
10502 (let ((beg (overlay-start js2-mode-node-overlay))
10503 (end (overlay-end js2-mode-node-overlay)))
10504 ;; Sometimes we're called spuriously.
10505 (unless (and p2
10506 (>= p2 beg)
10507 (<= p2 end))
10508 (with-silent-modifications
10509 (remove-text-properties beg end '(point-left nil)))
10510 (delete-overlay js2-mode-node-overlay)
10511 (setq js2-mode-node-overlay nil)))))
10512
10513 (defun js2-mode-reset ()
10514 "Debugging helper: reset everything."
10515 (interactive)
10516 (js2-mode-exit)
10517 (js2-mode))
10518
10519 (defun js2-mode-show-warn-or-err (e face)
10520 "Highlight a warning or error E with FACE.
10521 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10522 The last element is optional. When present, use instead of FACE."
10523 (let* ((key (first e))
10524 (beg (second e))
10525 (end (+ beg (third e)))
10526 ;; Don't inadvertently go out of bounds.
10527 (beg (max (point-min) (min beg (point-max))))
10528 (end (max (point-min) (min end (point-max))))
10529 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10530 (ovl (make-overlay beg end)))
10531 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10532 (overlay-put ovl 'js2-error t)
10533 (put-text-property beg end 'help-echo (js2-get-msg key))
10534 (put-text-property beg end 'point-entered #'js2-echo-error)))
10535
10536 (defun js2-remove-overlays ()
10537 "Remove overlays from buffer that have a `js2-error' property."
10538 (let ((beg (point-min))
10539 (end (point-max)))
10540 (save-excursion
10541 (dolist (o (overlays-in beg end))
10542 (when (overlay-get o 'js2-error)
10543 (delete-overlay o))))))
10544
10545 (defun js2-error-at-point (&optional pos)
10546 "Return non-nil if there's an error overlay at POS.
10547 Defaults to point."
10548 (loop with pos = (or pos (point))
10549 for o in (overlays-at pos)
10550 thereis (overlay-get o 'js2-error)))
10551
10552 (defun js2-mode-apply-deferred-properties ()
10553 "Apply fontifications and other text properties recorded during parsing."
10554 (when (plusp js2-highlight-level)
10555 ;; We defer clearing faces as long as possible to eliminate flashing.
10556 (js2-clear-face (point-min) (point-max))
10557 ;; Have to reverse the recorded fontifications list so that errors
10558 ;; and warnings overwrite the normal fontifications.
10559 (dolist (f (nreverse js2-mode-fontifications))
10560 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10561 (setq js2-mode-fontifications nil))
10562 (dolist (p js2-mode-deferred-properties)
10563 (apply #'put-text-property p))
10564 (setq js2-mode-deferred-properties nil))
10565
10566 (defun js2-mode-show-errors ()
10567 "Highlight syntax errors."
10568 (when js2-mode-show-parse-errors
10569 (dolist (e (js2-ast-root-errors js2-mode-ast))
10570 (js2-mode-show-warn-or-err e 'js2-error))))
10571
10572 (defun js2-mode-remove-suppressed-warnings ()
10573 "Take suppressed warnings out of the AST warnings list.
10574 This ensures that the counts and `next-error' are correct."
10575 (setf (js2-ast-root-warnings js2-mode-ast)
10576 (js2-delete-if
10577 (lambda (e)
10578 (let ((key (caar e)))
10579 (or
10580 (and (not js2-strict-trailing-comma-warning)
10581 (string-match "trailing\\.comma" key))
10582 (and (not js2-strict-cond-assign-warning)
10583 (string= key "msg.equal.as.assign"))
10584 (and js2-missing-semi-one-line-override
10585 (string= key "msg.missing.semi")
10586 (let* ((beg (second e))
10587 (node (js2-node-at-point beg))
10588 (fn (js2-mode-find-parent-fn node))
10589 (body (and fn (js2-function-node-body fn)))
10590 (lc (and body (js2-node-abs-pos body)))
10591 (rc (and lc (+ lc (js2-node-len body)))))
10592 (and fn
10593 (or (null body)
10594 (save-excursion
10595 (goto-char beg)
10596 (and (js2-same-line lc)
10597 (js2-same-line rc))))))))))
10598 (js2-ast-root-warnings js2-mode-ast))))
10599
10600 (defun js2-mode-show-warnings ()
10601 "Highlight strict-mode warnings."
10602 (when js2-mode-show-strict-warnings
10603 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10604 (js2-mode-show-warn-or-err e 'js2-warning))))
10605
10606 (defun js2-echo-error (old-point new-point)
10607 "Called by point-motion hooks."
10608 (let ((msg (get-text-property new-point 'help-echo)))
10609 (when (and (stringp msg) (or (not (current-message))
10610 (string= (current-message) "Quit")))
10611 (message msg))))
10612
10613 (defalias #'js2-echo-help #'js2-echo-error)
10614
10615 (defun js2-line-break (&optional soft)
10616 "Break line at point and indent, continuing comment if within one.
10617 If inside a string, and `js2-concat-multiline-strings' is not
10618 nil, turn it into concatenation."
10619 (interactive)
10620 (let ((parse-status (syntax-ppss)))
10621 (cond
10622 ;; Check if we're inside a string.
10623 ((nth 3 parse-status)
10624 (if js2-concat-multiline-strings
10625 (js2-mode-split-string parse-status)
10626 (insert "\n")))
10627 ;; Check if inside a block comment.
10628 ((nth 4 parse-status)
10629 (js2-mode-extend-comment (nth 8 parse-status)))
10630 (t
10631 (newline-and-indent)))))
10632
10633 (defun js2-mode-split-string (parse-status)
10634 "Turn a newline in mid-string into a string concatenation.
10635 PARSE-STATUS is as documented in `parse-partial-sexp'."
10636 (let* ((col (current-column))
10637 (quote-char (nth 3 parse-status))
10638 (string-beg (nth 8 parse-status))
10639 (at-eol (eq js2-concat-multiline-strings 'eol)))
10640 (insert quote-char)
10641 (if at-eol
10642 (insert " +\n")
10643 (insert "\n"))
10644 (unless at-eol
10645 (insert "+ "))
10646 (js2-indent-line)
10647 (insert quote-char)
10648 (when (eolp)
10649 (insert quote-char)
10650 (backward-char 1))))
10651
10652 (defun js2-mode-extend-comment (start-pos)
10653 "Indent the line and, when inside a comment block, add comment prefix."
10654 (let (star single col first-line needs-close)
10655 (save-excursion
10656 (back-to-indentation)
10657 (when (< (point) start-pos)
10658 (goto-char start-pos))
10659 (cond
10660 ((looking-at "\\*[^/]")
10661 (setq star t
10662 col (current-column)))
10663 ((looking-at "/\\*")
10664 (setq star t
10665 first-line t
10666 col (1+ (current-column))))
10667 ((looking-at "//")
10668 (setq single t
10669 col (current-column)))))
10670 ;; Heuristic for whether we need to close the comment:
10671 ;; if we've got a parse error here, assume it's an unterminated
10672 ;; comment.
10673 (setq needs-close
10674 (or
10675 (eq (get-text-property (1- (point)) 'point-entered)
10676 'js2-echo-error)
10677 ;; The heuristic above doesn't work well when we're
10678 ;; creating a comment and there's another one downstream,
10679 ;; as our parser thinks this one ends at the end of the
10680 ;; next one. (You can have a /* inside a js block comment.)
10681 ;; So just close it if the next non-ws char isn't a *.
10682 (and first-line
10683 (eolp)
10684 (save-excursion
10685 (skip-chars-forward " \t\r\n")
10686 (not (eq (char-after) ?*))))))
10687 (delete-horizontal-space)
10688 (insert "\n")
10689 (cond
10690 (star
10691 (indent-to col)
10692 (insert "* ")
10693 (if (and first-line needs-close)
10694 (save-excursion
10695 (insert "\n")
10696 (indent-to col)
10697 (insert "*/"))))
10698 ((and single
10699 (save-excursion
10700 (and (zerop (forward-line 1))
10701 (looking-at "\\s-*//"))))
10702 (indent-to col)
10703 (insert "// ")))
10704 ;; Don't need to extend the comment after all.
10705 (js2-indent-line)))
10706
10707 (defun js2-beginning-of-line ()
10708 "Toggle point between bol and first non-whitespace char in line.
10709 Also moves past comment delimiters when inside comments."
10710 (interactive)
10711 (let (node beg)
10712 (cond
10713 ((bolp)
10714 (back-to-indentation))
10715 ((looking-at "//")
10716 (skip-chars-forward "/ \t"))
10717 ((and (eq (char-after) ?*)
10718 (setq node (js2-comment-at-point))
10719 (memq (js2-comment-node-format node) '(jsdoc block))
10720 (save-excursion
10721 (skip-chars-backward " \t")
10722 (bolp)))
10723 (skip-chars-forward "\* \t"))
10724 (t
10725 (goto-char (point-at-bol))))))
10726
10727 (defun js2-end-of-line ()
10728 "Toggle point between eol and last non-whitespace char in line."
10729 (interactive)
10730 (if (eolp)
10731 (skip-chars-backward " \t")
10732 (goto-char (point-at-eol))))
10733
10734 (defsubst js2-mode-inside-string ()
10735 "Return non-nil if inside a string.
10736 Actually returns the quote character that begins the string."
10737 (nth 3 (syntax-ppss)))
10738
10739 (defun js2-mode-inside-comment-or-string ()
10740 "Return non-nil if inside a comment or string."
10741 (or
10742 (let ((comment-start
10743 (save-excursion
10744 (goto-char (point-at-bol))
10745 (if (re-search-forward "//" (point-at-eol) t)
10746 (match-beginning 0)))))
10747 (and comment-start
10748 (<= comment-start (point))))
10749 (let ((parse-state (syntax-ppss)))
10750 (or (nth 3 parse-state)
10751 (nth 4 parse-state)))))
10752
10753
10754 (defun js2-insert-catch-skel (try-pos)
10755 "Complete a try/catch block after inserting a { following a try keyword.
10756 Rationale is that a try always needs a catch or a finally, and the catch is
10757 the more likely of the two.
10758
10759 TRY-POS is the buffer position of the try keyword. The open-curly should
10760 already have been inserted."
10761 (insert "{")
10762 (let ((try-col (save-excursion
10763 (goto-char try-pos)
10764 (current-column))))
10765 (insert "\n")
10766 (undo-boundary)
10767 (js2-indent-line) ;; indent the blank line where cursor will end up
10768 (save-excursion
10769 (insert "\n")
10770 (indent-to try-col)
10771 (insert "} catch (x) {\n\n")
10772 (indent-to try-col)
10773 (insert "}"))))
10774
10775
10776 (defun js2-mode-wait-for-parse (callback)
10777 "Invoke CALLBACK when parsing is finished.
10778 If parsing is already finished, calls CALLBACK immediately."
10779 (if (not js2-mode-buffer-dirty-p)
10780 (funcall callback)
10781 (push callback js2-mode-pending-parse-callbacks)
10782 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10783
10784 (defun js2-mode-parse-finished ()
10785 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10786 ;; We can't let errors propagate up, since it prevents the
10787 ;; `js2-parse' method from completing normally and returning
10788 ;; the ast, which makes things mysteriously not work right.
10789 (unwind-protect
10790 (dolist (cb js2-mode-pending-parse-callbacks)
10791 (condition-case err
10792 (funcall cb)
10793 (error (message "%s" err))))
10794 (setq js2-mode-pending-parse-callbacks nil)))
10795
10796 (defun js2-mode-flag-region (from to flag)
10797 "Hide or show text from FROM to TO, according to FLAG.
10798 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10799 Returns the created overlay if FLAG is non-nil."
10800 (remove-overlays from to 'invisible 'js2-outline)
10801 (when flag
10802 (let ((o (make-overlay from to)))
10803 (overlay-put o 'invisible 'js2-outline)
10804 (overlay-put o 'isearch-open-invisible
10805 'js2-isearch-open-invisible)
10806 o)))
10807
10808 ;; Function to be set as an outline-isearch-open-invisible' property
10809 ;; to the overlay that makes the outline invisible (see
10810 ;; `js2-mode-flag-region').
10811 (defun js2-isearch-open-invisible (overlay)
10812 ;; We rely on the fact that isearch places point on the matched text.
10813 (js2-mode-show-element))
10814
10815 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10816 "Return cons cell of bounds of folding overlay at POS.
10817 Returns nil if not found."
10818 (let ((overlays (overlays-at (or pos (point))))
10819 o)
10820 (while (and overlays
10821 (not o))
10822 (if (overlay-get (car overlays) 'invisible)
10823 (setq o (car overlays))
10824 (setq overlays (cdr overlays))))
10825 (if o
10826 (cons (overlay-start o) (overlay-end o)))))
10827
10828 (defun js2-mode-function-at-point (&optional pos)
10829 "Return the innermost function node enclosing current point.
10830 Returns nil if point is not in a function."
10831 (let ((node (js2-node-at-point pos)))
10832 (while (and node (not (js2-function-node-p node)))
10833 (setq node (js2-node-parent node)))
10834 (if (js2-function-node-p node)
10835 node)))
10836
10837 (defun js2-mode-toggle-element ()
10838 "Hide or show the foldable element at the point."
10839 (interactive)
10840 (let (comment fn pos)
10841 (save-excursion
10842 (cond
10843 ;; /* ... */ comment?
10844 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10845 (if (js2-mode-invisible-overlay-bounds
10846 (setq pos (+ 3 (js2-node-abs-pos comment))))
10847 (progn
10848 (goto-char pos)
10849 (js2-mode-show-element))
10850 (js2-mode-hide-element)))
10851 ;; //-comment?
10852 ((save-excursion
10853 (back-to-indentation)
10854 (looking-at js2-mode-//-comment-re))
10855 (js2-mode-toggle-//-comment))
10856 ;; function?
10857 ((setq fn (js2-mode-function-at-point))
10858 (setq pos (and (js2-function-node-body fn)
10859 (js2-node-abs-pos (js2-function-node-body fn))))
10860 (goto-char (1+ pos))
10861 (if (js2-mode-invisible-overlay-bounds)
10862 (js2-mode-show-element)
10863 (js2-mode-hide-element)))
10864 (t
10865 (message "Nothing at point to hide or show"))))))
10866
10867 (defun js2-mode-hide-element ()
10868 "Fold/hide contents of a block, showing ellipses.
10869 Show the hidden text with \\[js2-mode-show-element]."
10870 (interactive)
10871 (if js2-mode-buffer-dirty-p
10872 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10873 (let (node body beg end)
10874 (cond
10875 ((js2-mode-invisible-overlay-bounds)
10876 (message "already hidden"))
10877 (t
10878 (setq node (js2-node-at-point))
10879 (cond
10880 ((js2-block-comment-p node)
10881 (js2-mode-hide-comment node))
10882 (t
10883 (while (and node (not (js2-function-node-p node)))
10884 (setq node (js2-node-parent node)))
10885 (if (and node
10886 (setq body (js2-function-node-body node)))
10887 (progn
10888 (setq beg (js2-node-abs-pos body)
10889 end (+ beg (js2-node-len body)))
10890 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10891 (message "No collapsable element found at point"))))))))
10892
10893 (defun js2-mode-show-element ()
10894 "Show the hidden element at current point."
10895 (interactive)
10896 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10897 (if bounds
10898 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10899 (message "Nothing to un-hide"))))
10900
10901 (defun js2-mode-show-all ()
10902 "Show all of the text in the buffer."
10903 (interactive)
10904 (js2-mode-flag-region (point-min) (point-max) nil))
10905
10906 (defun js2-mode-toggle-hide-functions ()
10907 (interactive)
10908 (if js2-mode-functions-hidden
10909 (js2-mode-show-functions)
10910 (js2-mode-hide-functions)))
10911
10912 (defun js2-mode-hide-functions ()
10913 "Hides all non-nested function bodies in the buffer.
10914 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10915 to open an individual entry."
10916 (interactive)
10917 (if js2-mode-buffer-dirty-p
10918 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10919 (if (null js2-mode-ast)
10920 (message "Oops - parsing failed")
10921 (setq js2-mode-functions-hidden t)
10922 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10923
10924 (defun js2-mode-function-hider (n endp)
10925 (when (not endp)
10926 (let ((tt (js2-node-type n))
10927 body beg end)
10928 (cond
10929 ((and (= tt js2-FUNCTION)
10930 (setq body (js2-function-node-body n)))
10931 (setq beg (js2-node-abs-pos body)
10932 end (+ beg (js2-node-len body)))
10933 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10934 nil) ; don't process children of function
10935 (t
10936 t))))) ; keep processing other AST nodes
10937
10938 (defun js2-mode-show-functions ()
10939 "Un-hide any folded function bodies in the buffer."
10940 (interactive)
10941 (setq js2-mode-functions-hidden nil)
10942 (save-excursion
10943 (goto-char (point-min))
10944 (while (/= (goto-char (next-overlay-change (point)))
10945 (point-max))
10946 (dolist (o (overlays-at (point)))
10947 (when (and (overlay-get o 'invisible)
10948 (not (overlay-get o 'comment)))
10949 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10950
10951 (defun js2-mode-hide-comment (n)
10952 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10953 3 ; /**
10954 2)) ; /*
10955 (beg (+ (js2-node-abs-pos n) head))
10956 (end (- (+ beg (js2-node-len n)) head 2))
10957 (o (js2-mode-flag-region beg end 'hide)))
10958 (overlay-put o 'comment t)))
10959
10960 (defun js2-mode-toggle-hide-comments ()
10961 "Folds all block comments in the buffer.
10962 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10963 to open an individual entry."
10964 (interactive)
10965 (if js2-mode-comments-hidden
10966 (js2-mode-show-comments)
10967 (js2-mode-hide-comments)))
10968
10969 (defun js2-mode-hide-comments ()
10970 (interactive)
10971 (if js2-mode-buffer-dirty-p
10972 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10973 (if (null js2-mode-ast)
10974 (message "Oops - parsing failed")
10975 (setq js2-mode-comments-hidden t)
10976 (dolist (n (js2-ast-root-comments js2-mode-ast))
10977 (let ((format (js2-comment-node-format n)))
10978 (when (js2-block-comment-p n)
10979 (js2-mode-hide-comment n))))
10980 (js2-mode-hide-//-comments)))
10981
10982 (defun js2-mode-extend-//-comment (direction)
10983 "Find start or end of a block of similar //-comment lines.
10984 DIRECTION is -1 to look back, 1 to look forward.
10985 INDENT is the indentation level to match.
10986 Returns the end-of-line position of the furthest adjacent
10987 //-comment line with the same indentation as the current line.
10988 If there is no such matching line, returns current end of line."
10989 (let ((pos (point-at-eol))
10990 (indent (current-indentation)))
10991 (save-excursion
10992 (while (and (zerop (forward-line direction))
10993 (looking-at js2-mode-//-comment-re)
10994 (eq indent (length (match-string 1))))
10995 (setq pos (point-at-eol))
10996 pos))))
10997
10998 (defun js2-mode-hide-//-comments ()
10999 "Fold adjacent 1-line comments, showing only snippet of first one."
11000 (let (beg end)
11001 (save-excursion
11002 (goto-char (point-min))
11003 (while (re-search-forward js2-mode-//-comment-re nil t)
11004 (setq beg (point)
11005 end (js2-mode-extend-//-comment 1))
11006 (unless (eq beg end)
11007 (overlay-put (js2-mode-flag-region beg end 'hide)
11008 'comment t))
11009 (goto-char end)
11010 (forward-char 1)))))
11011
11012 (defun js2-mode-toggle-//-comment ()
11013 "Fold or un-fold any multi-line //-comment at point.
11014 Caller should have determined that this line starts with a //-comment."
11015 (let* ((beg (point-at-eol))
11016 (end beg))
11017 (save-excursion
11018 (goto-char end)
11019 (if (js2-mode-invisible-overlay-bounds)
11020 (js2-mode-show-element)
11021 ;; else hide the comment
11022 (setq beg (js2-mode-extend-//-comment -1)
11023 end (js2-mode-extend-//-comment 1))
11024 (unless (eq beg end)
11025 (overlay-put (js2-mode-flag-region beg end 'hide)
11026 'comment t))))))
11027
11028 (defun js2-mode-show-comments ()
11029 "Un-hide any hidden comments, leaving other hidden elements alone."
11030 (interactive)
11031 (setq js2-mode-comments-hidden nil)
11032 (save-excursion
11033 (goto-char (point-min))
11034 (while (/= (goto-char (next-overlay-change (point)))
11035 (point-max))
11036 (dolist (o (overlays-at (point)))
11037 (when (overlay-get o 'comment)
11038 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11039
11040 (defun js2-mode-display-warnings-and-errors ()
11041 "Turn on display of warnings and errors."
11042 (interactive)
11043 (setq js2-mode-show-parse-errors t
11044 js2-mode-show-strict-warnings t)
11045 (js2-reparse 'force))
11046
11047 (defun js2-mode-hide-warnings-and-errors ()
11048 "Turn off display of warnings and errors."
11049 (interactive)
11050 (setq js2-mode-show-parse-errors nil
11051 js2-mode-show-strict-warnings nil)
11052 (js2-reparse 'force))
11053
11054 (defun js2-mode-toggle-warnings-and-errors ()
11055 "Toggle the display of warnings and errors.
11056 Some users don't like having warnings/errors reported while they type."
11057 (interactive)
11058 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11059 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11060 (if (called-interactively-p 'any)
11061 (message "warnings and errors %s"
11062 (if js2-mode-show-parse-errors
11063 "enabled"
11064 "disabled")))
11065 (js2-reparse 'force))
11066
11067 (defun js2-mode-customize ()
11068 (interactive)
11069 (customize-group 'js2-mode))
11070
11071 (defun js2-mode-forward-sexp (&optional arg)
11072 "Move forward across one statement or balanced expression.
11073 With ARG, do it that many times. Negative arg -N means
11074 move backward across N balanced expressions."
11075 (interactive "p")
11076 (setq arg (or arg 1))
11077 (save-restriction
11078 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11079 (js2-reparse))
11080 (let ((scan-msg "Containing expression ends prematurely")
11081 node (start (point)) pos lp rp child)
11082 (cond
11083 ;; backward-sexp
11084 ;; could probably make this better for some cases:
11085 ;; - if in statement block (e.g. function body), go to parent
11086 ;; - infix exprs like (foo in bar) - maybe go to beginning
11087 ;; of infix expr if in the right-side expression?
11088 ((and arg (minusp arg))
11089 (dotimes (i (- arg))
11090 (js2-backward-sws)
11091 (forward-char -1) ; enter the node we backed up to
11092 (when (setq node (js2-node-at-point (point) t))
11093 (setq pos (js2-node-abs-pos node))
11094 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11095 (setq lp (car parens)
11096 rp (cdr parens))))
11097 (goto-char
11098 (or (when (and lp (> start lp))
11099 (if (and rp (<= start rp))
11100 (if (setq child (js2-node-closest-child node (point) lp t))
11101 (js2-node-abs-pos child)
11102 (goto-char start)
11103 (signal 'scan-error (list scan-msg lp lp)))
11104 lp))
11105 pos
11106 (point-min)))))
11107 (t
11108 ;; forward-sexp
11109 (js2-forward-sws)
11110 (dotimes (i arg)
11111 (js2-forward-sws)
11112 (when (setq node (js2-node-at-point (point) t))
11113 (setq pos (js2-node-abs-pos node))
11114 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11115 (setq lp (car parens)
11116 rp (cdr parens))))
11117 (goto-char
11118 (or (when (and rp (<= start rp))
11119 (if (> start lp)
11120 (if (setq child (js2-node-closest-child node (point) rp))
11121 (js2-node-abs-end child)
11122 (goto-char start)
11123 (signal 'scan-error (list scan-msg rp (1+ rp))))
11124 (1+ rp)))
11125 (and pos
11126 (+ pos
11127 (js2-node-len
11128 (if (js2-expr-stmt-node-p (js2-node-parent node))
11129 ;; stop after the semicolon
11130 (js2-node-parent node)
11131 node))))
11132 (point-max))))))))
11133
11134 (defun js2-mode-forward-sexp-parens (node abs-pos)
11135 (cond
11136 ((or (js2-array-node-p node)
11137 (js2-object-node-p node)
11138 (js2-array-comp-node-p node)
11139 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11140 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11141 ((js2-paren-expr-node-p node)
11142 (let ((lp (js2-node-lp node))
11143 (rp (js2-node-rp node)))
11144 (cons (when lp (+ abs-pos lp))
11145 (when rp (+ abs-pos rp)))))))
11146
11147 (defun js2-node-closest-child (parent point limit &optional before)
11148 (let* ((parent-pos (js2-node-abs-pos parent))
11149 (rpoint (- point parent-pos))
11150 (rlimit (- limit parent-pos))
11151 (min (min rpoint rlimit))
11152 (max (max rpoint rlimit))
11153 found)
11154 (catch 'done
11155 (js2-visit-ast
11156 parent
11157 (lambda (node end-p)
11158 (if (eq node parent)
11159 t
11160 (let ((pos (js2-node-pos node)) ;; Both relative values.
11161 (end (+ (js2-node-pos node) (js2-node-len node))))
11162 (when (and (>= pos min) (<= end max)
11163 (if before (< pos rpoint) (> end rpoint)))
11164 (setq found node))
11165 (when (> end rpoint)
11166 (throw 'done nil)))
11167 nil))))
11168 found))
11169
11170 (defun js2-errors ()
11171 "Return a list of errors found."
11172 (and js2-mode-ast
11173 (js2-ast-root-errors js2-mode-ast)))
11174
11175 (defun js2-warnings ()
11176 "Return a list of warnings found."
11177 (and js2-mode-ast
11178 (js2-ast-root-warnings js2-mode-ast)))
11179
11180 (defun js2-have-errors-p ()
11181 "Return non-nil if any parse errors or warnings were found."
11182 (or (js2-errors) (js2-warnings)))
11183
11184 (defun js2-errors-and-warnings ()
11185 "Return a copy of the concatenated errors and warnings lists.
11186 They are appended: first the errors, then the warnings.
11187 Entries are of the form (MSG BEG END)."
11188 (when js2-mode-ast
11189 (append (js2-ast-root-errors js2-mode-ast)
11190 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11191
11192 (defun js2-next-error (&optional arg reset)
11193 "Move to next parse error.
11194 Typically invoked via \\[next-error].
11195 ARG is the number of errors, forward or backward, to move.
11196 RESET means start over from the beginning."
11197 (interactive "p")
11198 (if (not (or (js2-errors) (js2-warnings)))
11199 (message "No errors")
11200 (when reset
11201 (goto-char (point-min)))
11202 (let* ((errs (js2-errors-and-warnings))
11203 (continue t)
11204 (start (point))
11205 (count (or arg 1))
11206 (backward (minusp count))
11207 (sorter (if backward '> '<))
11208 (stopper (if backward '< '>))
11209 (count (abs count))
11210 all-errs err)
11211 ;; Sort by start position.
11212 (setq errs (sort errs (lambda (e1 e2)
11213 (funcall sorter (second e1) (second e2))))
11214 all-errs errs)
11215 ;; Find nth error with pos > start.
11216 (while (and errs continue)
11217 (when (funcall stopper (cadar errs) start)
11218 (setq err (car errs))
11219 (if (zerop (decf count))
11220 (setq continue nil)))
11221 (setq errs (cdr errs)))
11222 (if err
11223 (goto-char (second err))
11224 ;; Wrap around to first error.
11225 (goto-char (second (car all-errs)))
11226 ;; If we were already on it, echo msg again.
11227 (if (= (point) start)
11228 (js2-echo-error (point) (point)))))))
11229
11230 (defun js2-down-mouse-3 ()
11231 "Make right-click move the point to the click location.
11232 This makes right-click context menu operations a bit more intuitive.
11233 The point will not move if the region is active, however, to avoid
11234 destroying the region selection."
11235 (interactive)
11236 (when (and js2-move-point-on-right-click
11237 (not mark-active))
11238 (let ((e last-input-event))
11239 (ignore-errors
11240 (goto-char (cadadr e))))))
11241
11242 (defun js2-mode-create-imenu-index ()
11243 "Return an alist for `imenu--index-alist'."
11244 ;; This is built up in `js2-parse-record-imenu' during parsing.
11245 (when js2-mode-ast
11246 ;; if we have an ast but no recorder, they're requesting a rescan
11247 (unless js2-imenu-recorder
11248 (js2-reparse 'force))
11249 (prog1
11250 (js2-build-imenu-index)
11251 (setq js2-imenu-recorder nil
11252 js2-imenu-function-map nil))))
11253
11254 (defun js2-mode-find-tag ()
11255 "Replacement for `find-tag-default'.
11256 `find-tag-default' returns a ridiculous answer inside comments."
11257 (let (beg end)
11258 (js2-with-underscore-as-word-syntax
11259 (save-excursion
11260 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11261 (looking-back "[A-Za-z0-9_$]"))
11262 (setq beg (progn (forward-word -1) (point))
11263 end (progn (forward-word 1) (point)))
11264 (setq beg (progn (forward-word 1) (point))
11265 end (progn (forward-word -1) (point))))
11266 (replace-regexp-in-string
11267 "[\"']" ""
11268 (buffer-substring-no-properties beg end))))))
11269
11270 (defun js2-mode-forward-sibling ()
11271 "Move to the end of the sibling following point in parent.
11272 Returns non-nil if successful, or nil if there was no following sibling."
11273 (let* ((node (js2-node-at-point))
11274 (parent (js2-mode-find-enclosing-fn node))
11275 sib)
11276 (when (setq sib (js2-node-find-child-after (point) parent))
11277 (goto-char (+ (js2-node-abs-pos sib)
11278 (js2-node-len sib))))))
11279
11280 (defun js2-mode-backward-sibling ()
11281 "Move to the beginning of the sibling node preceding point in parent.
11282 Parent is defined as the enclosing script or function."
11283 (let* ((node (js2-node-at-point))
11284 (parent (js2-mode-find-enclosing-fn node))
11285 sib)
11286 (when (setq sib (js2-node-find-child-before (point) parent))
11287 (goto-char (js2-node-abs-pos sib)))))
11288
11289 (defun js2-beginning-of-defun (&optional arg)
11290 "Go to line on which current function starts, and return t on success.
11291 If we're not in a function or already at the beginning of one, go
11292 to beginning of previous script-level element.
11293 With ARG N, do that N times. If N is negative, move forward."
11294 (setq arg (or arg 1))
11295 (if (plusp arg)
11296 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11297 (when (cond
11298 ((js2-function-node-p parent)
11299 (goto-char (js2-node-abs-pos parent)))
11300 (t
11301 (js2-mode-backward-sibling)))
11302 (if (> arg 1)
11303 (js2-beginning-of-defun (1- arg))
11304 t)))
11305 (when (js2-end-of-defun)
11306 (if (>= arg -1)
11307 (js2-beginning-of-defun 1)
11308 (js2-beginning-of-defun (1+ arg))))))
11309
11310 (defun js2-end-of-defun ()
11311 "Go to the char after the last position of the current function
11312 or script-level element."
11313 (let* ((node (js2-node-at-point))
11314 (parent (or (and (js2-function-node-p node) node)
11315 (js2-node-parent-script-or-fn node)))
11316 script)
11317 (unless (js2-function-node-p parent)
11318 ;; Use current script-level node, or, if none, the next one.
11319 (setq script (or parent node)
11320 parent (js2-node-find-child-before (point) script))
11321 (when (or (null parent)
11322 (>= (point) (+ (js2-node-abs-pos parent)
11323 (js2-node-len parent))))
11324 (setq parent (js2-node-find-child-after (point) script))))
11325 (when parent
11326 (goto-char (+ (js2-node-abs-pos parent)
11327 (js2-node-len parent))))))
11328
11329 (defun js2-mark-defun (&optional allow-extend)
11330 "Put mark at end of this function, point at beginning.
11331 The function marked is the one that contains point.
11332
11333 Interactively, if this command is repeated,
11334 or (in Transient Mark mode) if the mark is active,
11335 it marks the next defun after the ones already marked."
11336 (interactive "p")
11337 (let (extended)
11338 (when (and allow-extend
11339 (or (and (eq last-command this-command) (mark t))
11340 (and transient-mark-mode mark-active)))
11341 (let ((sib (save-excursion
11342 (goto-char (mark))
11343 (if (js2-mode-forward-sibling)
11344 (point))))
11345 node)
11346 (if sib
11347 (progn
11348 (set-mark sib)
11349 (setq extended t))
11350 ;; no more siblings - try extending to enclosing node
11351 (goto-char (mark t)))))
11352 (when (not extended)
11353 (let ((node (js2-node-at-point (point) t)) ; skip comments
11354 ast fn stmt parent beg end)
11355 (when (js2-ast-root-p node)
11356 (setq ast node
11357 node (or (js2-node-find-child-after (point) node)
11358 (js2-node-find-child-before (point) node))))
11359 ;; only mark whole buffer if we can't find any children
11360 (if (null node)
11361 (setq node ast))
11362 (if (js2-function-node-p node)
11363 (setq parent node)
11364 (setq fn (js2-mode-find-enclosing-fn node)
11365 stmt (if (or (null fn)
11366 (js2-ast-root-p fn))
11367 (js2-mode-find-first-stmt node))
11368 parent (or stmt fn)))
11369 (setq beg (js2-node-abs-pos parent)
11370 end (+ beg (js2-node-len parent)))
11371 (push-mark beg)
11372 (goto-char end)
11373 (exchange-point-and-mark)))))
11374
11375 (defun js2-narrow-to-defun ()
11376 "Narrow to the function enclosing point."
11377 (interactive)
11378 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11379 (fn (if (js2-script-node-p node)
11380 node
11381 (js2-mode-find-enclosing-fn node)))
11382 (beg (js2-node-abs-pos fn)))
11383 (unless (js2-ast-root-p fn)
11384 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11385
11386 (provide 'js2-mode)
11387
11388 ;;; js2-mode.el ends here