]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Support chains with string elements in `js2-imenu-recorder`
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
180
181 (defvar js2-emacs22 (>= emacs-major-version 22))
182
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
189 :group 'js2-mode
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
194
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
197
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
200 :group 'languages)
201
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
204 c-basic-offset
205 4)
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
208 :group 'js2-mode
209 :type 'integer)
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
211
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-consistent-level-indent-inner-bracket-p t
238 "Non-nil to make indentation level inner bracket consistent,
239 regardless of the beginning bracket position."
240 :group 'js2-mode
241 :type 'boolean)
242 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
243
244 (defcustom js2-pretty-multiline-decl-indentation-p t
245 "Non-nil to line up multiline declarations vertically. See the
246 function `js-multiline-decl-indentation' for details."
247 :group 'js2-mode
248 :type 'boolean)
249 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
250
251 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
252 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
253 always additionally indent function expression or array/object literal
254 assigned in a declaration, even when only one var is declared."
255 :group 'js2-mode
256 :type 'boolean)
257 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
258
259 (defcustom js2-indent-on-enter-key nil
260 "Non-nil to have Enter/Return key indent the line.
261 This is unusual for Emacs modes but common in IDEs like Eclipse."
262 :type 'boolean
263 :group 'js2-mode)
264
265 (defcustom js2-enter-indents-newline nil
266 "Non-nil to have Enter/Return key indent the newly-inserted line.
267 This is unusual for Emacs modes but common in IDEs like Eclipse."
268 :type 'boolean
269 :group 'js2-mode)
270
271 (defcustom js2-rebind-eol-bol-keys t
272 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
273 If non-nil, bounce between bol/eol and first/last non-whitespace char."
274 :group 'js2-mode
275 :type 'boolean)
276
277 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
278 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
279 Each value in the list is passed to `define-key'."
280 :type 'list
281 :group 'js2-mode)
282
283 (defcustom js2-idle-timer-delay 0.2
284 "Delay in secs before re-parsing after user makes changes.
285 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
286 :type 'number
287 :group 'js2-mode)
288 (make-variable-buffer-local 'js2-idle-timer-delay)
289
290 (defcustom js2-dynamic-idle-timer-adjust 0
291 "Positive to adjust `js2-idle-timer-delay' based on file size.
292 The idea is that for short files, parsing is faster so we can be
293 more responsive to user edits without interfering with editing.
294 The buffer length in characters (typically bytes) is divided by
295 this value and used to multiply `js2-idle-timer-delay' for the
296 buffer. For example, a 21k file and 10k adjust yields 21k/10k
297 == 2, so js2-idle-timer-delay is multiplied by 2.
298 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
299 `js2-idle-timer-delay' is not dependent on the file size."
300 :type 'number
301 :group 'js2-mode)
302
303 (defcustom js2-mode-escape-quotes t
304 "Non-nil to disable automatic quote-escaping inside strings."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-mode-squeeze-spaces t
309 "Non-nil to normalize whitespace when filling in comments.
310 Multiple runs of spaces are converted to a single space."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-parse-errors t
315 "True to highlight parse errors."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-mode-show-strict-warnings t
320 "Non-nil to emit Ecma strict-mode warnings.
321 Some of the warnings can be individually disabled by other flags,
322 even if this flag is non-nil."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-strict-trailing-comma-warning t
327 "Non-nil to warn about trailing commas in array literals.
328 Ecma-262 forbids them, but many browsers permit them. IE is the
329 big exception, and can produce bugs if you have trailing commas."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-cond-assign-warning t
366 "Non-nil to warn about expressions like if (a = b).
367 This often should have been '==' instead of '='. If the warning
368 is enabled, you can suppress it on a per-expression basis by
369 parenthesizing the expression, e.g. if ((a = b)) ..."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-strict-var-redeclaration-warning t
374 "Non-nil to warn about redeclaring variables in a script or function."
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-strict-var-hides-function-arg-warning t
379 "Non-nil to warn about a var decl hiding a function argument."
380 :type 'boolean
381 :group 'js2-mode)
382
383 (defcustom js2-skip-preprocessor-directives nil
384 "Non-nil to treat lines beginning with # as comments.
385 Useful for viewing Mozilla JavaScript source code."
386 :type 'boolean
387 :group 'js2-mode)
388
389 (defcustom js2-language-version 180
390 "Configures what JavaScript language version to recognize.
391 Currently versions 150, 160, 170 and 180 are supported, corresponding
392 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
393 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
394 and 1.8 adds function closures."
395 :type 'integer
396 :group 'js2-mode)
397
398 (defcustom js2-allow-keywords-as-property-names t
399 "If non-nil, you can use JavaScript keywords as object property names.
400 Examples:
401
402 var foo = {int: 5, while: 6, continue: 7};
403 foo.return = 8;
404
405 Ecma-262 forbids this syntax, but many browsers support it."
406 :type 'boolean
407 :group 'js2-mode)
408
409 (defcustom js2-instanceof-has-side-effects nil
410 "If non-nil, treats the instanceof operator as having side effects.
411 This is useful for xulrunner apps."
412 :type 'boolean
413 :group 'js2-mode)
414
415 (defcustom js2-cleanup-whitespace nil
416 "Non-nil to invoke `delete-trailing-whitespace' before saves."
417 :type 'boolean
418 :group 'js2-mode)
419
420 (defcustom js2-move-point-on-right-click t
421 "Non-nil to move insertion point when you right-click.
422 This makes right-click context menu behavior a bit more intuitive,
423 since menu operations generally apply to the point. The exception
424 is if there is a region selection, in which case the point does -not-
425 move, so cut/copy/paste etc. can work properly.
426
427 Note that IntelliJ moves the point, and Eclipse leaves it alone,
428 so this behavior is customizable."
429 :group 'js2-mode
430 :type 'boolean)
431
432 (defcustom js2-allow-rhino-new-expr-initializer t
433 "Non-nil to support a Rhino's experimental syntactic construct.
434
435 Rhino supports the ability to follow a `new' expression with an object
436 literal, which is used to set additional properties on the new object
437 after calling its constructor. Syntax:
438
439 new <expr> [ ( arglist ) ] [initializer]
440
441 Hence, this expression:
442
443 new Object {a: 1, b: 2}
444
445 results in an Object with properties a=1 and b=2. This syntax is
446 apparently not configurable in Rhino - it's currently always enabled,
447 as of Rhino version 1.7R2."
448 :type 'boolean
449 :group 'js2-mode)
450
451 (defcustom js2-allow-member-expr-as-function-name nil
452 "Non-nil to support experimental Rhino syntax for function names.
453
454 Rhino supports an experimental syntax configured via the Rhino Context
455 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
456
457 function <member-expr> ( [ arg-list ] ) { <body> }
458
459 Where member-expr is a non-parenthesized 'member expression', which
460 is anything at the grammar level of a new-expression or lower, meaning
461 any expression that does not involve infix or unary operators.
462
463 When <member-expr> is not a simple identifier, then it is syntactic
464 sugar for assigning the anonymous function to the <member-expr>. Hence,
465 this code:
466
467 function a.b().c[2] (x, y) { ... }
468
469 is rewritten as:
470
471 a.b().c[2] = function(x, y) {...}
472
473 which doesn't seem particularly useful, but Rhino permits it."
474 :type 'boolean
475 :group 'js2-mode)
476
477 (defvar js2-mode-version 20101228
478 "Release number for `js2-mode'.")
479
480 ;; scanner variables
481
482 (defmacro js2-deflocal (name value &optional comment)
483 "Define a buffer-local variable NAME with VALUE and COMMENT."
484 `(progn
485 (defvar ,name ,value ,comment)
486 (make-variable-buffer-local ',name)))
487
488 ;; We record the start and end position of each token.
489 (js2-deflocal js2-token-beg 1)
490 (js2-deflocal js2-token-end -1)
491
492 (defvar js2-EOF_CHAR -1
493 "Represents end of stream. Distinct from js2-EOF token type.")
494
495 ;; I originally used symbols to represent tokens, but Rhino uses
496 ;; ints and then sets various flag bits in them, so ints it is.
497 ;; The upshot is that we need a `js2-' prefix in front of each name.
498 (defvar js2-ERROR -1)
499 (defvar js2-EOF 0)
500 (defvar js2-EOL 1)
501 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
502 (defvar js2-LEAVEWITH 3)
503 (defvar js2-RETURN 4)
504 (defvar js2-GOTO 5)
505 (defvar js2-IFEQ 6)
506 (defvar js2-IFNE 7)
507 (defvar js2-SETNAME 8)
508 (defvar js2-BITOR 9)
509 (defvar js2-BITXOR 10)
510 (defvar js2-BITAND 11)
511 (defvar js2-EQ 12)
512 (defvar js2-NE 13)
513 (defvar js2-LT 14)
514 (defvar js2-LE 15)
515 (defvar js2-GT 16)
516 (defvar js2-GE 17)
517 (defvar js2-LSH 18)
518 (defvar js2-RSH 19)
519 (defvar js2-URSH 20)
520 (defvar js2-ADD 21) ; infix plus
521 (defvar js2-SUB 22) ; infix minus
522 (defvar js2-MUL 23)
523 (defvar js2-DIV 24)
524 (defvar js2-MOD 25)
525 (defvar js2-NOT 26)
526 (defvar js2-BITNOT 27)
527 (defvar js2-POS 28) ; unary plus
528 (defvar js2-NEG 29) ; unary minus
529 (defvar js2-NEW 30)
530 (defvar js2-DELPROP 31)
531 (defvar js2-TYPEOF 32)
532 (defvar js2-GETPROP 33)
533 (defvar js2-GETPROPNOWARN 34)
534 (defvar js2-SETPROP 35)
535 (defvar js2-GETELEM 36)
536 (defvar js2-SETELEM 37)
537 (defvar js2-CALL 38)
538 (defvar js2-NAME 39) ; an identifier
539 (defvar js2-NUMBER 40)
540 (defvar js2-STRING 41)
541 (defvar js2-NULL 42)
542 (defvar js2-THIS 43)
543 (defvar js2-FALSE 44)
544 (defvar js2-TRUE 45)
545 (defvar js2-SHEQ 46) ; shallow equality (===)
546 (defvar js2-SHNE 47) ; shallow inequality (!==)
547 (defvar js2-REGEXP 48)
548 (defvar js2-BINDNAME 49)
549 (defvar js2-THROW 50)
550 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
551 (defvar js2-IN 52)
552 (defvar js2-INSTANCEOF 53)
553 (defvar js2-LOCAL_LOAD 54)
554 (defvar js2-GETVAR 55)
555 (defvar js2-SETVAR 56)
556 (defvar js2-CATCH_SCOPE 57)
557 (defvar js2-ENUM_INIT_KEYS 58)
558 (defvar js2-ENUM_INIT_VALUES 59)
559 (defvar js2-ENUM_INIT_ARRAY 60)
560 (defvar js2-ENUM_NEXT 61)
561 (defvar js2-ENUM_ID 62)
562 (defvar js2-THISFN 63)
563 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
564 (defvar js2-ARRAYLIT 65) ; array literal
565 (defvar js2-OBJECTLIT 66) ; object literal
566 (defvar js2-GET_REF 67) ; *reference
567 (defvar js2-SET_REF 68) ; *reference = something
568 (defvar js2-DEL_REF 69) ; delete reference
569 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
570 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
571 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
572
573 ;; XML support
574 (defvar js2-DEFAULTNAMESPACE 73)
575 (defvar js2-ESCXMLATTR 74)
576 (defvar js2-ESCXMLTEXT 75)
577 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
578 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
579 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
580 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
581
582 (defvar js2-first-bytecode js2-ENTERWITH)
583 (defvar js2-last-bytecode js2-REF_NS_NAME)
584
585 (defvar js2-TRY 80)
586 (defvar js2-SEMI 81) ; semicolon
587 (defvar js2-LB 82) ; left and right brackets
588 (defvar js2-RB 83)
589 (defvar js2-LC 84) ; left and right curly-braces
590 (defvar js2-RC 85)
591 (defvar js2-LP 86) ; left and right parens
592 (defvar js2-RP 87)
593 (defvar js2-COMMA 88) ; comma operator
594
595 (defvar js2-ASSIGN 89) ; simple assignment (=)
596 (defvar js2-ASSIGN_BITOR 90) ; |=
597 (defvar js2-ASSIGN_BITXOR 91) ; ^=
598 (defvar js2-ASSIGN_BITAND 92) ; &=
599 (defvar js2-ASSIGN_LSH 93) ; <<=
600 (defvar js2-ASSIGN_RSH 94) ; >>=
601 (defvar js2-ASSIGN_URSH 95) ; >>>=
602 (defvar js2-ASSIGN_ADD 96) ; +=
603 (defvar js2-ASSIGN_SUB 97) ; -=
604 (defvar js2-ASSIGN_MUL 98) ; *=
605 (defvar js2-ASSIGN_DIV 99) ; /=
606 (defvar js2-ASSIGN_MOD 100) ; %=
607
608 (defvar js2-first-assign js2-ASSIGN)
609 (defvar js2-last-assign js2-ASSIGN_MOD)
610
611 (defvar js2-HOOK 101) ; conditional (?:)
612 (defvar js2-COLON 102)
613 (defvar js2-OR 103) ; logical or (||)
614 (defvar js2-AND 104) ; logical and (&&)
615 (defvar js2-INC 105) ; increment/decrement (++ --)
616 (defvar js2-DEC 106)
617 (defvar js2-DOT 107) ; member operator (.)
618 (defvar js2-FUNCTION 108) ; function keyword
619 (defvar js2-EXPORT 109) ; export keyword
620 (defvar js2-IMPORT 110) ; import keyword
621 (defvar js2-IF 111) ; if keyword
622 (defvar js2-ELSE 112) ; else keyword
623 (defvar js2-SWITCH 113) ; switch keyword
624 (defvar js2-CASE 114) ; case keyword
625 (defvar js2-DEFAULT 115) ; default keyword
626 (defvar js2-WHILE 116) ; while keyword
627 (defvar js2-DO 117) ; do keyword
628 (defvar js2-FOR 118) ; for keyword
629 (defvar js2-BREAK 119) ; break keyword
630 (defvar js2-CONTINUE 120) ; continue keyword
631 (defvar js2-VAR 121) ; var keyword
632 (defvar js2-WITH 122) ; with keyword
633 (defvar js2-CATCH 123) ; catch keyword
634 (defvar js2-FINALLY 124) ; finally keyword
635 (defvar js2-VOID 125) ; void keyword
636 (defvar js2-RESERVED 126) ; reserved keywords
637
638 (defvar js2-EMPTY 127)
639
640 ;; Types used for the parse tree - never returned by scanner.
641
642 (defvar js2-BLOCK 128) ; statement block
643 (defvar js2-LABEL 129) ; label
644 (defvar js2-TARGET 130)
645 (defvar js2-LOOP 131)
646 (defvar js2-EXPR_VOID 132) ; expression statement in functions
647 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
648 (defvar js2-JSR 134)
649 (defvar js2-SCRIPT 135) ; top-level node for entire script
650 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
651 (defvar js2-USE_STACK 137)
652 (defvar js2-SETPROP_OP 138) ; x.y op= something
653 (defvar js2-SETELEM_OP 139) ; x[y] op= something
654 (defvar js2-LOCAL_BLOCK 140)
655 (defvar js2-SET_REF_OP 141) ; *reference op= something
656
657 ;; For XML support:
658 (defvar js2-DOTDOT 142) ; member operator (..)
659 (defvar js2-COLONCOLON 143) ; namespace::name
660 (defvar js2-XML 144) ; XML type
661 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
662 (defvar js2-XMLATTR 146) ; @
663 (defvar js2-XMLEND 147)
664
665 ;; Optimizer-only tokens
666 (defvar js2-TO_OBJECT 148)
667 (defvar js2-TO_DOUBLE 149)
668
669 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
670 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
671 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
672 (defvar js2-CONST 153)
673 (defvar js2-SETCONST 154)
674 (defvar js2-SETCONSTVAR 155)
675 (defvar js2-ARRAYCOMP 156)
676 (defvar js2-LETEXPR 157)
677 (defvar js2-WITHEXPR 158)
678 (defvar js2-DEBUGGER 159)
679
680 (defvar js2-COMMENT 160)
681 (defvar js2-ENUM 161) ; for "enum" reserved word
682
683 (defconst js2-num-tokens (1+ js2-ENUM))
684
685 (defconst js2-debug-print-trees nil)
686
687 ;; Rhino accepts any string or stream as input. Emacs character
688 ;; processing works best in buffers, so we'll assume the input is a
689 ;; buffer. JavaScript strings can be copied into temp buffers before
690 ;; scanning them.
691
692 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
693 ;; They're the Emacs equivalent of instance variables, more or less.
694
695 (js2-deflocal js2-ts-dirty-line nil
696 "Token stream buffer-local variable.
697 Indicates stuff other than whitespace since start of line.")
698
699 (js2-deflocal js2-ts-regexp-flags nil
700 "Token stream buffer-local variable.")
701
702 (js2-deflocal js2-ts-string ""
703 "Token stream buffer-local variable.
704 Last string scanned.")
705
706 (js2-deflocal js2-ts-number nil
707 "Token stream buffer-local variable.
708 Last literal number scanned.")
709
710 (js2-deflocal js2-ts-hit-eof nil
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-line-start 0
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-lineno 1
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-line-end-char -1
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
723 "Token stream buffer-local variable.
724 Current scan position.")
725
726 (js2-deflocal js2-ts-is-xml-attribute nil
727 "Token stream buffer-local variable.")
728
729 (js2-deflocal js2-ts-xml-is-tag-content nil
730 "Token stream buffer-local variable.")
731
732 (js2-deflocal js2-ts-xml-open-tags-count 0
733 "Token stream buffer-local variable.")
734
735 (js2-deflocal js2-ts-string-buffer nil
736 "Token stream buffer-local variable.
737 List of chars built up while scanning various tokens.")
738
739 (js2-deflocal js2-ts-comment-type nil
740 "Token stream buffer-local variable.")
741
742 ;;; Parser variables
743
744 (js2-deflocal js2-parsed-errors nil
745 "List of errors produced during scanning/parsing.")
746
747 (js2-deflocal js2-parsed-warnings nil
748 "List of warnings produced during scanning/parsing.")
749
750 (js2-deflocal js2-recover-from-parse-errors t
751 "Non-nil to continue parsing after a syntax error.
752
753 In recovery mode, the AST will be built in full, and any error
754 nodes will be flagged with appropriate error information. If
755 this flag is nil, a syntax error will result in an error being
756 signaled.
757
758 The variable is automatically buffer-local, because different
759 modes that use the parser will need different settings.")
760
761 (js2-deflocal js2-parse-hook nil
762 "List of callbacks for receiving parsing progress.")
763
764 (defvar js2-parse-finished-hook nil
765 "List of callbacks to notify when parsing finishes.
766 Not called if parsing was interrupted.")
767
768 (js2-deflocal js2-is-eval-code nil
769 "True if we're evaluating code in a string.
770 If non-nil, the tokenizer will record the token text, and the AST nodes
771 will record their source text. Off by default for IDE modes, since the
772 text is available in the buffer.")
773
774 (defvar js2-parse-ide-mode t
775 "Non-nil if the parser is being used for `js2-mode'.
776 If non-nil, the parser will set text properties for fontification
777 and the syntax table. The value should be nil when using the
778 parser as a frontend to an interpreter or byte compiler.")
779
780 ;;; Parser instance variables (buffer-local vars for js2-parse)
781
782 (defconst js2-clear-ti-mask #xFFFF
783 "Mask to clear token information bits.")
784
785 (defconst js2-ti-after-eol (lsh 1 16)
786 "Flag: first token of the source line.")
787
788 (defconst js2-ti-check-label (lsh 1 17)
789 "Flag: indicates to check for label.")
790
791 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
792
793 (js2-deflocal js2-compiler-generate-debug-info t)
794 (js2-deflocal js2-compiler-use-dynamic-scope nil)
795 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
796 (js2-deflocal js2-compiler-xml-available t)
797 (js2-deflocal js2-compiler-optimization-level 0)
798 (js2-deflocal js2-compiler-generating-source t)
799 (js2-deflocal js2-compiler-strict-mode nil)
800 (js2-deflocal js2-compiler-report-warning-as-error nil)
801 (js2-deflocal js2-compiler-generate-observer-count nil)
802 (js2-deflocal js2-compiler-activation-names nil)
803
804 ;; SKIP: sourceURI
805
806 ;; There's a compileFunction method in Context.java - may need it.
807 (js2-deflocal js2-called-by-compile-function nil
808 "True if `js2-parse' was called by `js2-compile-function'.
809 Will only be used when we finish implementing the interpreter.")
810
811 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
812
813 (js2-deflocal js2-current-flagged-token js2-EOF)
814 (js2-deflocal js2-current-token js2-EOF)
815
816 ;; SKIP: node factory - we're going to just call functions directly,
817 ;; and eventually go to a unified AST format.
818
819 (js2-deflocal js2-nesting-of-function 0)
820
821 (js2-deflocal js2-recorded-identifiers nil
822 "Tracks identifiers found during parsing.")
823
824 (defmacro js2-in-lhs (body)
825 `(let ((js2-is-in-lhs t))
826 ,body))
827
828 (defmacro js2-in-rhs (body)
829 `(let ((js2-is-in-lhs nil))
830 ,body))
831
832 (js2-deflocal js2-is-in-lhs nil
833 "True while parsing lhs statement")
834
835 (defcustom js2-global-externs nil
836 "A list of any extern names you'd like to consider always declared.
837 This list is global and is used by all js2-mode files.
838 You can create buffer-local externs list using `js2-additional-externs'.
839
840 There is also a buffer-local variable `js2-default-externs',
841 which is initialized by default to include the Ecma-262 externs
842 and the standard browser externs. The three lists are all
843 checked during highlighting."
844 :type 'list
845 :group 'js2-mode)
846
847 (js2-deflocal js2-default-externs nil
848 "Default external declarations.
849
850 These are currently only used for highlighting undeclared variables,
851 which only worries about top-level (unqualified) references.
852 As js2-mode's processing improves, we will flesh out this list.
853
854 The initial value is set to `js2-ecma-262-externs', unless you
855 have set `js2-include-browser-externs', in which case the browser
856 externs are also included.
857
858 See `js2-additional-externs' for more information.")
859
860 (defcustom js2-include-browser-externs t
861 "Non-nil to include browser externs in the master externs list.
862 If you work on JavaScript files that are not intended for browsers,
863 such as Mozilla Rhino server-side JavaScript, set this to nil.
864 You can always include them on a per-file basis by calling
865 `js2-add-browser-externs' from a function on `js2-mode-hook'.
866
867 See `js2-additional-externs' for more information about externs."
868 :type 'boolean
869 :group 'js2-mode)
870
871 (defcustom js2-include-rhino-externs t
872 "Non-nil to include Mozilla Rhino externs in the master externs list.
873 See `js2-additional-externs' for more information about externs."
874 :type 'boolean
875 :group 'js2-mode)
876
877 (defcustom js2-include-gears-externs t
878 "Non-nil to include Google Gears externs in the master externs list.
879 See `js2-additional-externs' for more information about externs."
880 :type 'boolean
881 :group 'js2-mode)
882
883 (js2-deflocal js2-additional-externs nil
884 "A buffer-local list of additional external declarations.
885 It is used to decide whether variables are considered undeclared
886 for purposes of highlighting.
887
888 Each entry is a lisp string. The string should be the fully qualified
889 name of an external entity. All externs should be added to this list,
890 so that as js2-mode's processing improves it can take advantage of them.
891
892 You may want to declare your externs in three ways.
893 First, you can add externs that are valid for all your JavaScript files.
894 You should probably do this by adding them to `js2-global-externs', which
895 is a global list used for all js2-mode files.
896
897 Next, you can add a function to `js2-mode-hook' that adds additional
898 externs appropriate for the specific file, perhaps based on its path.
899 These should go in `js2-additional-externs', which is buffer-local.
900
901 Finally, you can add a function to `js2-post-parse-callbacks',
902 which is called after parsing completes, and `root' is bound to
903 the root of the parse tree. At this stage you can set up an AST
904 node visitor using `js2-visit-ast' and examine the parse tree
905 for specific import patterns that may imply the existence of
906 other externs, possibly tied to your build system. These should also
907 be added to `js2-additional-externs'.
908
909 Your post-parse callback may of course also use the simpler and
910 faster (but perhaps less robust) approach of simply scanning the
911 buffer text for your imports, using regular expressions.")
912
913 ;; SKIP: decompiler
914 ;; SKIP: encoded-source
915
916 ;;; The following variables are per-function and should be saved/restored
917 ;;; during function parsing...
918
919 (js2-deflocal js2-current-script-or-fn nil)
920 (js2-deflocal js2-current-scope nil)
921 (js2-deflocal js2-nesting-of-with 0)
922 (js2-deflocal js2-label-set nil
923 "An alist mapping label names to nodes.")
924
925 (js2-deflocal js2-loop-set nil)
926 (js2-deflocal js2-loop-and-switch-set nil)
927 (js2-deflocal js2-has-return-value nil)
928 (js2-deflocal js2-end-flags 0)
929
930 ;;; ...end of per function variables
931
932 ;; Without 2-token lookahead, labels are a problem.
933 ;; These vars store the token info of the last matched name,
934 ;; iff it wasn't the last matched token. Only valid in some contexts.
935 (defvar js2-prev-name-token-start nil)
936 (defvar js2-prev-name-token-string nil)
937
938 (defsubst js2-save-name-token-data (pos name)
939 (setq js2-prev-name-token-start pos
940 js2-prev-name-token-string name))
941
942 ;; These flags enumerate the possible ways a statement/function can
943 ;; terminate. These flags are used by endCheck() and by the Parser to
944 ;; detect inconsistent return usage.
945 ;;
946 ;; END_UNREACHED is reserved for code paths that are assumed to always be
947 ;; able to execute (example: throw, continue)
948 ;;
949 ;; END_DROPS_OFF indicates if the statement can transfer control to the
950 ;; next one. Statement such as return dont. A compound statement may have
951 ;; some branch that drops off control to the next statement.
952 ;;
953 ;; END_RETURNS indicates that the statement can return (without arguments)
954 ;; END_RETURNS_VALUE indicates that the statement can return a value.
955 ;;
956 ;; A compound statement such as
957 ;; if (condition) {
958 ;; return value;
959 ;; }
960 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
961
962 (defconst js2-end-unreached #x0)
963 (defconst js2-end-drops-off #x1)
964 (defconst js2-end-returns #x2)
965 (defconst js2-end-returns-value #x4)
966 (defconst js2-end-yields #x8)
967
968 ;; Rhino awkwardly passes a statementLabel parameter to the
969 ;; statementHelper() function, the main statement parser, which
970 ;; is then used by quite a few of the sub-parsers. We just make
971 ;; it a buffer-local variable and make sure it's cleaned up properly.
972 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
973
974 ;; Similarly, Rhino passes an inForInit boolean through about half
975 ;; the expression parsers. We use a dynamically-scoped variable,
976 ;; which makes it easier to funcall the parsers individually without
977 ;; worrying about whether they take the parameter or not.
978 (js2-deflocal js2-in-for-init nil)
979 (js2-deflocal js2-temp-name-counter 0)
980 (js2-deflocal js2-parse-stmt-count 0)
981
982 (defsubst js2-get-next-temp-name ()
983 (format "$%d" (incf js2-temp-name-counter)))
984
985 (defvar js2-parse-interruptable-p t
986 "Set this to nil to force parse to continue until finished.
987 This will mostly be useful for interpreters.")
988
989 (defvar js2-statements-per-pause 50
990 "Pause after this many statements to check for user input.
991 If user input is pending, stop the parse and discard the tree.
992 This makes for a smoother user experience for large files.
993 You may have to wait a second or two before the highlighting
994 and error-reporting appear, but you can always type ahead if
995 you wish. This appears to be more or less how Eclipse, IntelliJ
996 and other editors work.")
997
998 (js2-deflocal js2-record-comments t
999 "Instructs the scanner to record comments in `js2-scanned-comments'.")
1000
1001 (js2-deflocal js2-scanned-comments nil
1002 "List of all comments from the current parse.")
1003
1004 (defcustom js2-mode-indent-inhibit-undo nil
1005 "Non-nil to disable collection of Undo information when indenting lines.
1006 Some users have requested this behavior. It's nil by default because
1007 other Emacs modes don't work this way."
1008 :type 'boolean
1009 :group 'js2-mode)
1010
1011 (defcustom js2-mode-indent-ignore-first-tab nil
1012 "If non-nil, ignore first TAB keypress if we look indented properly.
1013 It's fairly common for users to navigate to an already-indented line
1014 and press TAB for reassurance that it's been indented. For this class
1015 of users, we want the first TAB press on a line to be ignored if the
1016 line is already indented to one of the precomputed alternatives.
1017
1018 This behavior is only partly implemented. If you TAB-indent a line,
1019 navigate to another line, and then navigate back, it fails to clear
1020 the last-indented variable, so it thinks you've already hit TAB once,
1021 and performs the indent. A full solution would involve getting on the
1022 point-motion hooks for the entire buffer. If we come across another
1023 use cases that requires watching point motion, I'll consider doing it.
1024
1025 If you set this variable to nil, then the TAB key will always change
1026 the indentation of the current line, if more than one alternative
1027 indentation spot exists."
1028 :type 'boolean
1029 :group 'js2-mode)
1030
1031 (defvar js2-indent-hook nil
1032 "A hook for user-defined indentation rules.
1033
1034 Functions on this hook should expect two arguments: (LIST INDEX)
1035 The LIST argument is the list of computed indentation points for
1036 the current line. INDEX is the list index of the indentation point
1037 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1038 indent function is not going to change the current line indentation.
1039
1040 If a hook function on this list returns a non-nil value, then
1041 `js2-bounce-indent' assumes the hook function has performed its own
1042 indentation, and will do nothing. If all hook functions on the list
1043 return nil, then `js2-bounce-indent' will use its computed indentation
1044 and reindent the line.
1045
1046 When hook functions on this hook list are called, the variable
1047 `js2-mode-ast' may or may not be set, depending on whether the
1048 parse tree is available. If the variable is nil, you can pass a
1049 callback to `js2-mode-wait-for-parse', and your callback will be
1050 called after the new parse tree is built. This can take some time
1051 in large files.")
1052
1053 (defface js2-warning-face
1054 `((((class color) (background light))
1055 (:underline "orange"))
1056 (((class color) (background dark))
1057 (:underline "orange"))
1058 (t (:underline t)))
1059 "Face for JavaScript warnings."
1060 :group 'js2-mode)
1061
1062 (defface js2-error-face
1063 `((((class color) (background light))
1064 (:foreground "red"))
1065 (((class color) (background dark))
1066 (:foreground "red"))
1067 (t (:foreground "red")))
1068 "Face for JavaScript errors."
1069 :group 'js2-mode)
1070
1071 (defface js2-jsdoc-tag-face
1072 '((t :foreground "SlateGray"))
1073 "Face used to highlight @whatever tags in jsdoc comments."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-type-face
1077 '((t :foreground "SteelBlue"))
1078 "Face used to highlight {FooBar} types in jsdoc comments."
1079 :group 'js2-mode)
1080
1081 (defface js2-jsdoc-value-face
1082 '((t :foreground "PeachPuff3"))
1083 "Face used to highlight tag values in jsdoc comments."
1084 :group 'js2-mode)
1085
1086 (defface js2-function-param-face
1087 '((t :foreground "SeaGreen"))
1088 "Face used to highlight function parameters in javascript."
1089 :group 'js2-mode)
1090
1091 (defface js2-instance-member-face
1092 '((t :foreground "DarkOrchid"))
1093 "Face used to highlight instance variables in javascript.
1094 Not currently used."
1095 :group 'js2-mode)
1096
1097 (defface js2-private-member-face
1098 '((t :foreground "PeachPuff3"))
1099 "Face used to highlight calls to private methods in javascript.
1100 Not currently used."
1101 :group 'js2-mode)
1102
1103 (defface js2-private-function-call-face
1104 '((t :foreground "goldenrod"))
1105 "Face used to highlight calls to private functions in javascript.
1106 Not currently used."
1107 :group 'js2-mode)
1108
1109 (defface js2-jsdoc-html-tag-name-face
1110 (if js2-emacs22
1111 '((((class color) (min-colors 88) (background light))
1112 (:foreground "rosybrown"))
1113 (((class color) (min-colors 8) (background dark))
1114 (:foreground "yellow"))
1115 (((class color) (min-colors 8) (background light))
1116 (:foreground "magenta")))
1117 '((((type tty pc) (class color) (background light))
1118 (:foreground "magenta"))
1119 (((type tty pc) (class color) (background dark))
1120 (:foreground "yellow"))
1121 (t (:foreground "RosyBrown"))))
1122 "Face used to highlight jsdoc html tag names"
1123 :group 'js2-mode)
1124
1125 (defface js2-jsdoc-html-tag-delimiter-face
1126 (if js2-emacs22
1127 '((((class color) (min-colors 88) (background light))
1128 (:foreground "dark khaki"))
1129 (((class color) (min-colors 8) (background dark))
1130 (:foreground "green"))
1131 (((class color) (min-colors 8) (background light))
1132 (:foreground "green")))
1133 '((((type tty pc) (class color) (background light))
1134 (:foreground "green"))
1135 (((type tty pc) (class color) (background dark))
1136 (:foreground "green"))
1137 (t (:foreground "dark khaki"))))
1138 "Face used to highlight brackets in jsdoc html tags."
1139 :group 'js2-mode)
1140
1141 (defface js2-magic-paren-face
1142 '((t :underline t))
1143 "Face used to color parens that will be auto-overwritten."
1144 :group 'js2-mode)
1145
1146 (defcustom js2-post-parse-callbacks nil
1147 "A list of callback functions invoked after parsing finishes.
1148 Currently, the main use for this function is to add synthetic
1149 declarations to `js2-recorded-identifiers', which see."
1150 :type 'list
1151 :group 'js2-mode)
1152
1153 (defface js2-external-variable-face
1154 '((t :foreground "orange"))
1155 "Face used to highlight undeclared variable identifiers.
1156 An undeclared variable is any variable not declared with var or let
1157 in the current scope or any lexically enclosing scope. If you use
1158 such a variable, then you are either expecting it to originate from
1159 another file, or you've got a potential bug."
1160 :group 'js2-mode)
1161
1162 (defcustom js2-highlight-external-variables t
1163 "Non-nil to highlight undeclared variable identifiers."
1164 :type 'boolean
1165 :group 'js2-mode)
1166
1167 (defcustom js2-auto-insert-catch-block t
1168 "Non-nil to insert matching catch block on open-curly after `try'."
1169 :type 'boolean
1170 :group 'js2-mode)
1171
1172 (defvar js2-mode-map
1173 (let ((map (make-sparse-keymap))
1174 keys)
1175 (define-key map [mouse-1] #'js2-mode-show-node)
1176 (define-key map (kbd "C-m") #'js2-enter-key)
1177 (when js2-rebind-eol-bol-keys
1178 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1179 (define-key map (kbd "C-e") #'js2-end-of-line))
1180 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1181 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1182 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1183 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1184 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1185 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1186 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1187 (define-key map (kbd "C-c C-`") #'js2-next-error)
1188 ;; also define user's preference for next-error, if available
1189 (if (setq keys (where-is-internal #'next-error))
1190 (define-key map (car keys) #'js2-next-error))
1191 (define-key map (or (car (where-is-internal #'mark-defun))
1192 (kbd "M-C-h"))
1193 #'js2-mark-defun)
1194 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1195 (kbd "C-x nd"))
1196 #'js2-narrow-to-defun)
1197 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1198 (when js2-auto-indent-p
1199 (mapc (lambda (key)
1200 (define-key map key #'js2-insert-and-indent))
1201 js2-electric-keys))
1202 (when js2-bounce-indent-p
1203 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1204
1205 (define-key map [menu-bar javascript]
1206 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1207
1208 (define-key map [menu-bar javascript customize-js2-mode]
1209 '(menu-item "Customize js2-mode" js2-mode-customize
1210 :help "Customize the behavior of this mode"))
1211
1212 (define-key map [menu-bar javascript js2-force-refresh]
1213 '(menu-item "Force buffer refresh" js2-mode-reset
1214 :help "Re-parse the buffer from scratch"))
1215
1216 (define-key map [menu-bar javascript separator-2]
1217 '("--"))
1218
1219 (define-key map [menu-bar javascript next-error]
1220 '(menu-item "Next warning or error" js2-next-error
1221 :enabled (and js2-mode-ast
1222 (or (js2-ast-root-errors js2-mode-ast)
1223 (js2-ast-root-warnings js2-mode-ast)))
1224 :help "Move to next warning or error"))
1225
1226 (define-key map [menu-bar javascript display-errors]
1227 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1228 :visible (not js2-mode-show-parse-errors)
1229 :help "Turn on display of warnings and errors"))
1230
1231 (define-key map [menu-bar javascript hide-errors]
1232 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1233 :visible js2-mode-show-parse-errors
1234 :help "Turn off display of warnings and errors"))
1235
1236 (define-key map [menu-bar javascript separator-1]
1237 '("--"))
1238
1239 (define-key map [menu-bar javascript js2-toggle-function]
1240 '(menu-item "Show/collapse element" js2-mode-toggle-element
1241 :help "Hide or show function body or comment"))
1242
1243 (define-key map [menu-bar javascript show-comments]
1244 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1245 :visible js2-mode-comments-hidden
1246 :help "Expand all hidden block comments"))
1247
1248 (define-key map [menu-bar javascript hide-comments]
1249 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1250 :visible (not js2-mode-comments-hidden)
1251 :help "Show block comments as /*...*/"))
1252
1253 (define-key map [menu-bar javascript show-all-functions]
1254 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1255 :visible js2-mode-functions-hidden
1256 :help "Expand all hidden function bodies"))
1257
1258 (define-key map [menu-bar javascript hide-all-functions]
1259 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1260 :visible (not js2-mode-functions-hidden)
1261 :help "Show {...} for all top-level function bodies"))
1262
1263 map)
1264 "Keymap used in `js2-mode' buffers.")
1265
1266 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1267
1268 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1269 "Matches a //-comment line. Must be first non-whitespace on line.
1270 First match-group is the leading whitespace.")
1271
1272 (defvar js2-mode-hook nil)
1273
1274 (js2-deflocal js2-mode-ast nil "Private variable.")
1275 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1276 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1277 (js2-deflocal js2-mode-parsing nil "Private variable.")
1278 (js2-deflocal js2-mode-node-overlay nil)
1279
1280 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1281 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1282
1283 (js2-deflocal js2-mode-fontifications nil "Private variable")
1284 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1285 (js2-deflocal js2-imenu-recorder nil "Private variable")
1286 (js2-deflocal js2-imenu-function-map nil "Private variable")
1287
1288 (defvar js2-paragraph-start
1289 "\\(@[a-zA-Z]+\\>\\|$\\)")
1290
1291 ;; Note that we also set a 'c-in-sws text property in html comments,
1292 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1293 (defvar js2-syntactic-ws-start
1294 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1295
1296 (defvar js2-syntactic-ws-end
1297 "\\s \\|[\n\r/]\\|\\s!")
1298
1299 (defvar js2-syntactic-eol
1300 (concat "\\s *\\(/\\*[^*\n\r]*"
1301 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1302 "\\*+/\\s *\\)*"
1303 "\\(//\\|/\\*[^*\n\r]*"
1304 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1305 "\\|\\\\$\\|$\\)")
1306 "Copied from `java-mode'. Needed for some cc-engine functions.")
1307
1308 (defvar js2-comment-prefix-regexp
1309 "//+\\|\\**")
1310
1311 (defvar js2-comment-start-skip
1312 "\\(//+\\|/\\*+\\)\\s *")
1313
1314 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1315 "Non-nil to emit status messages during parsing.")
1316
1317 (defvar js2-mode-functions-hidden nil "private variable")
1318 (defvar js2-mode-comments-hidden nil "private variable")
1319
1320 (defvar js2-mode-syntax-table
1321 (let ((table (make-syntax-table)))
1322 (c-populate-syntax-table table)
1323 table)
1324 "Syntax table used in js2-mode buffers.")
1325
1326 (defvar js2-mode-abbrev-table nil
1327 "Abbrev table in use in `js2-mode' buffers.")
1328 (define-abbrev-table 'js2-mode-abbrev-table ())
1329
1330 (defvar js2-mode-pending-parse-callbacks nil
1331 "List of functions waiting to be notified that parse is finished.")
1332
1333 (defvar js2-mode-last-indented-line -1)
1334
1335 ;;; Localizable error and warning messages
1336
1337 ;; Messages are copied from Rhino's Messages.properties.
1338 ;; Many of the Java-specific messages have been elided.
1339 ;; Add any js2-specific ones at the end, so we can keep
1340 ;; this file synced with changes to Rhino's.
1341
1342 (defvar js2-message-table
1343 (make-hash-table :test 'equal :size 250)
1344 "Contains localized messages for js2-mode.")
1345
1346 ;; TODO(stevey): construct this table at compile-time.
1347 (defmacro js2-msg (key &rest strings)
1348 `(puthash ,key (funcall #'concat ,@strings)
1349 js2-message-table))
1350
1351 (defun js2-get-msg (msg-key)
1352 "Look up a localized message.
1353 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1354 the correct number of ARGS must be provided."
1355 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1356 (args (if (listp msg-key) (cdr msg-key)))
1357 (msg (gethash key js2-message-table)))
1358 (if msg
1359 (apply #'format msg args)
1360 key))) ; default to showing the key
1361
1362 (js2-msg "msg.dup.parms"
1363 "Duplicate parameter name '%s'.")
1364
1365 (js2-msg "msg.too.big.jump"
1366 "Program too complex: jump offset too big.")
1367
1368 (js2-msg "msg.too.big.index"
1369 "Program too complex: internal index exceeds 64K limit.")
1370
1371 (js2-msg "msg.while.compiling.fn"
1372 "Encountered code generation error while compiling function '%s': %s")
1373
1374 (js2-msg "msg.while.compiling.script"
1375 "Encountered code generation error while compiling script: %s")
1376
1377 ;; Context
1378 (js2-msg "msg.ctor.not.found"
1379 "Constructor for '%s' not found.")
1380
1381 (js2-msg "msg.not.ctor"
1382 "'%s' is not a constructor.")
1383
1384 ;; FunctionObject
1385 (js2-msg "msg.varargs.ctor"
1386 "Method or constructor '%s' must be static "
1387 "with the signature (Context cx, Object[] args, "
1388 "Function ctorObj, boolean inNewExpr) "
1389 "to define a variable arguments constructor.")
1390
1391 (js2-msg "msg.varargs.fun"
1392 "Method '%s' must be static with the signature "
1393 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1394 "to define a variable arguments function.")
1395
1396 (js2-msg "msg.incompat.call"
1397 "Method '%s' called on incompatible object.")
1398
1399 (js2-msg "msg.bad.parms"
1400 "Unsupported parameter type '%s' in method '%s'.")
1401
1402 (js2-msg "msg.bad.method.return"
1403 "Unsupported return type '%s' in method '%s'.")
1404
1405 (js2-msg "msg.bad.ctor.return"
1406 "Construction of objects of type '%s' is not supported.")
1407
1408 (js2-msg "msg.no.overload"
1409 "Method '%s' occurs multiple times in class '%s'.")
1410
1411 (js2-msg "msg.method.not.found"
1412 "Method '%s' not found in '%s'.")
1413
1414 ;; IRFactory
1415
1416 (js2-msg "msg.bad.for.in.lhs"
1417 "Invalid left-hand side of for..in loop.")
1418
1419 (js2-msg "msg.mult.index"
1420 "Only one variable allowed in for..in loop.")
1421
1422 (js2-msg "msg.bad.for.in.destruct"
1423 "Left hand side of for..in loop must be an array of "
1424 "length 2 to accept key/value pair.")
1425
1426 (js2-msg "msg.cant.convert"
1427 "Can't convert to type '%s'.")
1428
1429 (js2-msg "msg.bad.assign.left"
1430 "Invalid assignment left-hand side.")
1431
1432 (js2-msg "msg.bad.decr"
1433 "Invalid decerement operand.")
1434
1435 (js2-msg "msg.bad.incr"
1436 "Invalid increment operand.")
1437
1438 (js2-msg "msg.bad.yield"
1439 "yield must be in a function.")
1440
1441 (js2-msg "msg.yield.parenthesized"
1442 "yield expression must be parenthesized.")
1443
1444 ;; NativeGlobal
1445 (js2-msg "msg.cant.call.indirect"
1446 "Function '%s' must be called directly, and not by way of a "
1447 "function of another name.")
1448
1449 (js2-msg "msg.eval.nonstring"
1450 "Calling eval() with anything other than a primitive "
1451 "string value will simply return the value. "
1452 "Is this what you intended?")
1453
1454 (js2-msg "msg.eval.nonstring.strict"
1455 "Calling eval() with anything other than a primitive "
1456 "string value is not allowed in strict mode.")
1457
1458 (js2-msg "msg.bad.destruct.op"
1459 "Invalid destructuring assignment operator")
1460
1461 ;; NativeCall
1462 (js2-msg "msg.only.from.new"
1463 "'%s' may only be invoked from a `new' expression.")
1464
1465 (js2-msg "msg.deprec.ctor"
1466 "The '%s' constructor is deprecated.")
1467
1468 ;; NativeFunction
1469 (js2-msg "msg.no.function.ref.found"
1470 "no source found to decompile function reference %s")
1471
1472 (js2-msg "msg.arg.isnt.array"
1473 "second argument to Function.prototype.apply must be an array")
1474
1475 ;; NativeGlobal
1476 (js2-msg "msg.bad.esc.mask"
1477 "invalid string escape mask")
1478
1479 ;; NativeRegExp
1480 (js2-msg "msg.bad.quant"
1481 "Invalid quantifier %s")
1482
1483 (js2-msg "msg.overlarge.backref"
1484 "Overly large back reference %s")
1485
1486 (js2-msg "msg.overlarge.min"
1487 "Overly large minimum %s")
1488
1489 (js2-msg "msg.overlarge.max"
1490 "Overly large maximum %s")
1491
1492 (js2-msg "msg.zero.quant"
1493 "Zero quantifier %s")
1494
1495 (js2-msg "msg.max.lt.min"
1496 "Maximum %s less than minimum")
1497
1498 (js2-msg "msg.unterm.quant"
1499 "Unterminated quantifier %s")
1500
1501 (js2-msg "msg.unterm.paren"
1502 "Unterminated parenthetical %s")
1503
1504 (js2-msg "msg.unterm.class"
1505 "Unterminated character class %s")
1506
1507 (js2-msg "msg.bad.range"
1508 "Invalid range in character class.")
1509
1510 (js2-msg "msg.trail.backslash"
1511 "Trailing \\ in regular expression.")
1512
1513 (js2-msg "msg.re.unmatched.right.paren"
1514 "unmatched ) in regular expression.")
1515
1516 (js2-msg "msg.no.regexp"
1517 "Regular expressions are not available.")
1518
1519 (js2-msg "msg.bad.backref"
1520 "back-reference exceeds number of capturing parentheses.")
1521
1522 (js2-msg "msg.bad.regexp.compile"
1523 "Only one argument may be specified if the first "
1524 "argument to RegExp.prototype.compile is a RegExp object.")
1525
1526 ;; Parser
1527 (js2-msg "msg.got.syntax.errors"
1528 "Compilation produced %s syntax errors.")
1529
1530 (js2-msg "msg.var.redecl"
1531 "TypeError: redeclaration of var %s.")
1532
1533 (js2-msg "msg.const.redecl"
1534 "TypeError: redeclaration of const %s.")
1535
1536 (js2-msg "msg.let.redecl"
1537 "TypeError: redeclaration of variable %s.")
1538
1539 (js2-msg "msg.parm.redecl"
1540 "TypeError: redeclaration of formal parameter %s.")
1541
1542 (js2-msg "msg.fn.redecl"
1543 "TypeError: redeclaration of function %s.")
1544
1545 (js2-msg "msg.let.decl.not.in.block"
1546 "SyntaxError: let declaration not directly within block")
1547
1548 ;; NodeTransformer
1549 (js2-msg "msg.dup.label"
1550 "duplicated label")
1551
1552 (js2-msg "msg.undef.label"
1553 "undefined label")
1554
1555 (js2-msg "msg.bad.break"
1556 "unlabelled break must be inside loop or switch")
1557
1558 (js2-msg "msg.continue.outside"
1559 "continue must be inside loop")
1560
1561 (js2-msg "msg.continue.nonloop"
1562 "continue can only use labels of iteration statements")
1563
1564 (js2-msg "msg.bad.throw.eol"
1565 "Line terminator is not allowed between the throw "
1566 "keyword and throw expression.")
1567
1568 (js2-msg "msg.no.paren.parms"
1569 "missing ( before function parameters.")
1570
1571 (js2-msg "msg.no.parm"
1572 "missing formal parameter")
1573
1574 (js2-msg "msg.no.paren.after.parms"
1575 "missing ) after formal parameters")
1576
1577 (js2-msg "msg.no.brace.body"
1578 "missing '{' before function body")
1579
1580 (js2-msg "msg.no.brace.after.body"
1581 "missing } after function body")
1582
1583 (js2-msg "msg.no.paren.cond"
1584 "missing ( before condition")
1585
1586 (js2-msg "msg.no.paren.after.cond"
1587 "missing ) after condition")
1588
1589 (js2-msg "msg.no.semi.stmt"
1590 "missing ; before statement")
1591
1592 (js2-msg "msg.missing.semi"
1593 "missing ; after statement")
1594
1595 (js2-msg "msg.no.name.after.dot"
1596 "missing name after . operator")
1597
1598 (js2-msg "msg.no.name.after.coloncolon"
1599 "missing name after :: operator")
1600
1601 (js2-msg "msg.no.name.after.dotdot"
1602 "missing name after .. operator")
1603
1604 (js2-msg "msg.no.name.after.xmlAttr"
1605 "missing name after .@")
1606
1607 (js2-msg "msg.no.bracket.index"
1608 "missing ] in index expression")
1609
1610 (js2-msg "msg.no.paren.switch"
1611 "missing ( before switch expression")
1612
1613 (js2-msg "msg.no.paren.after.switch"
1614 "missing ) after switch expression")
1615
1616 (js2-msg "msg.no.brace.switch"
1617 "missing '{' before switch body")
1618
1619 (js2-msg "msg.bad.switch"
1620 "invalid switch statement")
1621
1622 (js2-msg "msg.no.colon.case"
1623 "missing : after case expression")
1624
1625 (js2-msg "msg.double.switch.default"
1626 "double default label in the switch statement")
1627
1628 (js2-msg "msg.no.while.do"
1629 "missing while after do-loop body")
1630
1631 (js2-msg "msg.no.paren.for"
1632 "missing ( after for")
1633
1634 (js2-msg "msg.no.semi.for"
1635 "missing ; after for-loop initializer")
1636
1637 (js2-msg "msg.no.semi.for.cond"
1638 "missing ; after for-loop condition")
1639
1640 (js2-msg "msg.in.after.for.name"
1641 "missing in after for")
1642
1643 (js2-msg "msg.no.paren.for.ctrl"
1644 "missing ) after for-loop control")
1645
1646 (js2-msg "msg.no.paren.with"
1647 "missing ( before with-statement object")
1648
1649 (js2-msg "msg.no.paren.after.with"
1650 "missing ) after with-statement object")
1651
1652 (js2-msg "msg.no.paren.after.let"
1653 "missing ( after let")
1654
1655 (js2-msg "msg.no.paren.let"
1656 "missing ) after variable list")
1657
1658 (js2-msg "msg.no.curly.let"
1659 "missing } after let statement")
1660
1661 (js2-msg "msg.bad.return"
1662 "invalid return")
1663
1664 (js2-msg "msg.no.brace.block"
1665 "missing } in compound statement")
1666
1667 (js2-msg "msg.bad.label"
1668 "invalid label")
1669
1670 (js2-msg "msg.bad.var"
1671 "missing variable name")
1672
1673 (js2-msg "msg.bad.var.init"
1674 "invalid variable initialization")
1675
1676 (js2-msg "msg.no.colon.cond"
1677 "missing : in conditional expression")
1678
1679 (js2-msg "msg.no.paren.arg"
1680 "missing ) after argument list")
1681
1682 (js2-msg "msg.no.bracket.arg"
1683 "missing ] after element list")
1684
1685 (js2-msg "msg.bad.prop"
1686 "invalid property id")
1687
1688 (js2-msg "msg.no.colon.prop"
1689 "missing : after property id")
1690
1691 (js2-msg "msg.no.brace.prop"
1692 "missing } after property list")
1693
1694 (js2-msg "msg.no.paren"
1695 "missing ) in parenthetical")
1696
1697 (js2-msg "msg.reserved.id"
1698 "identifier is a reserved word")
1699
1700 (js2-msg "msg.no.paren.catch"
1701 "missing ( before catch-block condition")
1702
1703 (js2-msg "msg.bad.catchcond"
1704 "invalid catch block condition")
1705
1706 (js2-msg "msg.catch.unreachable"
1707 "any catch clauses following an unqualified catch are unreachable")
1708
1709 (js2-msg "msg.no.brace.try"
1710 "missing '{' before try block")
1711
1712 (js2-msg "msg.no.brace.catchblock"
1713 "missing '{' before catch-block body")
1714
1715 (js2-msg "msg.try.no.catchfinally"
1716 "'try' without 'catch' or 'finally'")
1717
1718 (js2-msg "msg.no.return.value"
1719 "function %s does not always return a value")
1720
1721 (js2-msg "msg.anon.no.return.value"
1722 "anonymous function does not always return a value")
1723
1724 (js2-msg "msg.return.inconsistent"
1725 "return statement is inconsistent with previous usage")
1726
1727 (js2-msg "msg.generator.returns"
1728 "TypeError: generator function '%s' returns a value")
1729
1730 (js2-msg "msg.anon.generator.returns"
1731 "TypeError: anonymous generator function returns a value")
1732
1733 (js2-msg "msg.syntax"
1734 "syntax error")
1735
1736 (js2-msg "msg.unexpected.eof"
1737 "Unexpected end of file")
1738
1739 (js2-msg "msg.XML.bad.form"
1740 "illegally formed XML syntax")
1741
1742 (js2-msg "msg.XML.not.available"
1743 "XML runtime not available")
1744
1745 (js2-msg "msg.too.deep.parser.recursion"
1746 "Too deep recursion while parsing")
1747
1748 (js2-msg "msg.no.side.effects"
1749 "Code has no side effects")
1750
1751 (js2-msg "msg.extra.trailing.comma"
1752 "Trailing comma is not legal in an ECMA-262 object initializer")
1753
1754 (js2-msg "msg.array.trailing.comma"
1755 "Trailing comma yields different behavior across browsers")
1756
1757 (js2-msg "msg.equal.as.assign"
1758 (concat "Test for equality (==) mistyped as assignment (=)?"
1759 " (parenthesize to suppress warning)"))
1760
1761 (js2-msg "msg.var.hides.arg"
1762 "Variable %s hides argument")
1763
1764 (js2-msg "msg.destruct.assign.no.init"
1765 "Missing = in destructuring declaration")
1766
1767 ;; ScriptRuntime
1768 (js2-msg "msg.no.properties"
1769 "%s has no properties.")
1770
1771 (js2-msg "msg.invalid.iterator"
1772 "Invalid iterator value")
1773
1774 (js2-msg "msg.iterator.primitive"
1775 "__iterator__ returned a primitive value")
1776
1777 (js2-msg "msg.assn.create.strict"
1778 "Assignment to undeclared variable %s")
1779
1780 (js2-msg "msg.ref.undefined.prop"
1781 "Reference to undefined property '%s'")
1782
1783 (js2-msg "msg.prop.not.found"
1784 "Property %s not found.")
1785
1786 (js2-msg "msg.invalid.type"
1787 "Invalid JavaScript value of type %s")
1788
1789 (js2-msg "msg.primitive.expected"
1790 "Primitive type expected (had %s instead)")
1791
1792 (js2-msg "msg.namespace.expected"
1793 "Namespace object expected to left of :: (found %s instead)")
1794
1795 (js2-msg "msg.null.to.object"
1796 "Cannot convert null to an object.")
1797
1798 (js2-msg "msg.undef.to.object"
1799 "Cannot convert undefined to an object.")
1800
1801 (js2-msg "msg.cyclic.value"
1802 "Cyclic %s value not allowed.")
1803
1804 (js2-msg "msg.is.not.defined"
1805 "'%s' is not defined.")
1806
1807 (js2-msg "msg.undef.prop.read"
1808 "Cannot read property '%s' from %s")
1809
1810 (js2-msg "msg.undef.prop.write"
1811 "Cannot set property '%s' of %s to '%s'")
1812
1813 (js2-msg "msg.undef.prop.delete"
1814 "Cannot delete property '%s' of %s")
1815
1816 (js2-msg "msg.undef.method.call"
1817 "Cannot call method '%s' of %s")
1818
1819 (js2-msg "msg.undef.with"
1820 "Cannot apply 'with' to %s")
1821
1822 (js2-msg "msg.isnt.function"
1823 "%s is not a function, it is %s.")
1824
1825 (js2-msg "msg.isnt.function.in"
1826 "Cannot call property %s in object %s. "
1827 "It is not a function, it is '%s'.")
1828
1829 (js2-msg "msg.function.not.found"
1830 "Cannot find function %s.")
1831
1832 (js2-msg "msg.function.not.found.in"
1833 "Cannot find function %s in object %s.")
1834
1835 (js2-msg "msg.isnt.xml.object"
1836 "%s is not an xml object.")
1837
1838 (js2-msg "msg.no.ref.to.get"
1839 "%s is not a reference to read reference value.")
1840
1841 (js2-msg "msg.no.ref.to.set"
1842 "%s is not a reference to set reference value to %s.")
1843
1844 (js2-msg "msg.no.ref.from.function"
1845 "Function %s can not be used as the left-hand "
1846 "side of assignment or as an operand of ++ or -- operator.")
1847
1848 (js2-msg "msg.bad.default.value"
1849 "Object's getDefaultValue() method returned an object.")
1850
1851 (js2-msg "msg.instanceof.not.object"
1852 "Can't use instanceof on a non-object.")
1853
1854 (js2-msg "msg.instanceof.bad.prototype"
1855 "'prototype' property of %s is not an object.")
1856
1857 (js2-msg "msg.bad.radix"
1858 "illegal radix %s.")
1859
1860 ;; ScriptableObject
1861 (js2-msg "msg.default.value"
1862 "Cannot find default value for object.")
1863
1864 (js2-msg "msg.zero.arg.ctor"
1865 "Cannot load class '%s' which has no zero-parameter constructor.")
1866
1867 (js2-msg "msg.ctor.multiple.parms"
1868 "Can't define constructor or class %s since more than "
1869 "one constructor has multiple parameters.")
1870
1871 (js2-msg "msg.extend.scriptable"
1872 "%s must extend ScriptableObject in order to define property %s.")
1873
1874 (js2-msg "msg.bad.getter.parms"
1875 "In order to define a property, getter %s must have zero "
1876 "parameters or a single ScriptableObject parameter.")
1877
1878 (js2-msg "msg.obj.getter.parms"
1879 "Expected static or delegated getter %s to take "
1880 "a ScriptableObject parameter.")
1881
1882 (js2-msg "msg.getter.static"
1883 "Getter and setter must both be static or neither be static.")
1884
1885 (js2-msg "msg.setter.return"
1886 "Setter must have void return type: %s")
1887
1888 (js2-msg "msg.setter2.parms"
1889 "Two-parameter setter must take a ScriptableObject as "
1890 "its first parameter.")
1891
1892 (js2-msg "msg.setter1.parms"
1893 "Expected single parameter setter for %s")
1894
1895 (js2-msg "msg.setter2.expected"
1896 "Expected static or delegated setter %s to take two parameters.")
1897
1898 (js2-msg "msg.setter.parms"
1899 "Expected either one or two parameters for setter.")
1900
1901 (js2-msg "msg.setter.bad.type"
1902 "Unsupported parameter type '%s' in setter '%s'.")
1903
1904 (js2-msg "msg.add.sealed"
1905 "Cannot add a property to a sealed object: %s.")
1906
1907 (js2-msg "msg.remove.sealed"
1908 "Cannot remove a property from a sealed object: %s.")
1909
1910 (js2-msg "msg.modify.sealed"
1911 "Cannot modify a property of a sealed object: %s.")
1912
1913 (js2-msg "msg.modify.readonly"
1914 "Cannot modify readonly property: %s.")
1915
1916 ;; TokenStream
1917 (js2-msg "msg.missing.exponent"
1918 "missing exponent")
1919
1920 (js2-msg "msg.caught.nfe"
1921 "number format error")
1922
1923 (js2-msg "msg.unterminated.string.lit"
1924 "unterminated string literal")
1925
1926 (js2-msg "msg.unterminated.comment"
1927 "unterminated comment")
1928
1929 (js2-msg "msg.unterminated.re.lit"
1930 "unterminated regular expression literal")
1931
1932 (js2-msg "msg.invalid.re.flag"
1933 "invalid flag after regular expression")
1934
1935 (js2-msg "msg.no.re.input.for"
1936 "no input for %s")
1937
1938 (js2-msg "msg.illegal.character"
1939 "illegal character")
1940
1941 (js2-msg "msg.invalid.escape"
1942 "invalid Unicode escape sequence")
1943
1944 (js2-msg "msg.bad.namespace"
1945 "not a valid default namespace statement. "
1946 "Syntax is: default xml namespace = EXPRESSION;")
1947
1948 ;; TokensStream warnings
1949 (js2-msg "msg.bad.octal.literal"
1950 "illegal octal literal digit %s; "
1951 "interpreting it as a decimal digit")
1952
1953 (js2-msg "msg.reserved.keyword"
1954 "illegal usage of future reserved keyword %s; "
1955 "interpreting it as ordinary identifier")
1956
1957 (js2-msg "msg.script.is.not.constructor"
1958 "Script objects are not constructors.")
1959
1960 ;; Arrays
1961 (js2-msg "msg.arraylength.bad"
1962 "Inappropriate array length.")
1963
1964 ;; Arrays
1965 (js2-msg "msg.arraylength.too.big"
1966 "Array length %s exceeds supported capacity limit.")
1967
1968 ;; URI
1969 (js2-msg "msg.bad.uri"
1970 "Malformed URI sequence.")
1971
1972 ;; Number
1973 (js2-msg "msg.bad.precision"
1974 "Precision %s out of range.")
1975
1976 ;; NativeGenerator
1977 (js2-msg "msg.send.newborn"
1978 "Attempt to send value to newborn generator")
1979
1980 (js2-msg "msg.already.exec.gen"
1981 "Already executing generator")
1982
1983 (js2-msg "msg.StopIteration.invalid"
1984 "StopIteration may not be changed to an arbitrary object.")
1985
1986 ;; Interpreter
1987 (js2-msg "msg.yield.closing"
1988 "Yield from closing generator")
1989
1990 ;;; Utilities
1991
1992 (defun js2-delete-if (predicate list)
1993 "Remove all items satisfying PREDICATE in LIST."
1994 (loop for item in list
1995 if (not (funcall predicate item))
1996 collect item))
1997
1998 (defun js2-position (element list)
1999 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2000 Returns nil if element is not found in the list."
2001 (let ((count 0)
2002 found)
2003 (while (and list (not found))
2004 (if (eq element (car list))
2005 (setq found t)
2006 (setq count (1+ count)
2007 list (cdr list))))
2008 (if found count)))
2009
2010 (defun js2-find-if (predicate list)
2011 "Find first item satisfying PREDICATE in LIST."
2012 (let (result)
2013 (while (and list (not result))
2014 (if (funcall predicate (car list))
2015 (setq result (car list)))
2016 (setq list (cdr list)))
2017 result))
2018
2019 (defmacro js2-time (form)
2020 "Evaluate FORM, discard result, and return elapsed time in sec"
2021 (declare (debug t))
2022 (let ((beg (make-symbol "--js2-time-beg--"))
2023 (delta (make-symbol "--js2-time-end--")))
2024 `(let ((,beg (current-time))
2025 ,delta)
2026 ,form
2027 (/ (truncate (* (- (float-time (current-time))
2028 (float-time ,beg))
2029 10000))
2030 10000.0))))
2031
2032 (defsubst js2-same-line (pos)
2033 "Return t if POS is on the same line as current point."
2034 (and (>= pos (point-at-bol))
2035 (<= pos (point-at-eol))))
2036
2037 (defsubst js2-same-line-2 (p1 p2)
2038 "Return t if p1 is on the same line as p2."
2039 (save-excursion
2040 (goto-char p1)
2041 (js2-same-line p2)))
2042
2043 (defun js2-code-bug ()
2044 "Signal an error when we encounter an unexpected code path."
2045 (error "failed assertion"))
2046
2047 (defsubst js2-record-text-property (beg end prop value)
2048 "Record a text property to set when parsing finishes."
2049 (push (list beg end prop value) js2-mode-deferred-properties))
2050
2051 ;; I'd like to associate errors with nodes, but for now the
2052 ;; easiest thing to do is get the context info from the last token.
2053 (defsubst js2-record-parse-error (msg &optional arg pos len)
2054 (push (list (list msg arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2057 js2-parsed-errors))
2058
2059 (defsubst js2-report-error (msg &optional msg-arg pos len)
2060 "Signal a syntax error or record a parse error."
2061 (if js2-recover-from-parse-errors
2062 (js2-record-parse-error msg msg-arg pos len)
2063 (signal 'js2-syntax-error
2064 (list msg
2065 js2-ts-lineno
2066 (save-excursion
2067 (goto-char js2-ts-cursor)
2068 (current-column))
2069 js2-ts-hit-eof))))
2070
2071 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2072 (if js2-compiler-report-warning-as-error
2073 (js2-report-error msg msg-arg pos len)
2074 (push (list (list msg msg-arg)
2075 (or pos js2-token-beg)
2076 (or len (- js2-token-end js2-token-beg)))
2077 js2-parsed-warnings)))
2078
2079 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2080 (if js2-compiler-strict-mode
2081 (js2-report-warning msg-id msg-arg beg
2082 (and beg end (- end beg)))))
2083
2084 (put 'js2-syntax-error 'error-conditions
2085 '(error syntax-error js2-syntax-error))
2086 (put 'js2-syntax-error 'error-message "Syntax error")
2087
2088 (put 'js2-parse-error 'error-conditions
2089 '(error parse-error js2-parse-error))
2090 (put 'js2-parse-error 'error-message "Parse error")
2091
2092 (defmacro js2-clear-flag (flags flag)
2093 `(setq ,flags (logand ,flags (lognot ,flag))))
2094
2095 (defmacro js2-set-flag (flags flag)
2096 "Logical-or FLAG into FLAGS."
2097 `(setq ,flags (logior ,flags ,flag)))
2098
2099 (defsubst js2-flag-set-p (flags flag)
2100 (/= 0 (logand flags flag)))
2101
2102 (defsubst js2-flag-not-set-p (flags flag)
2103 (zerop (logand flags flag)))
2104
2105 ;; Stolen shamelessly from James Clark's nxml-mode.
2106 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2107 "Evaluate BODY without any text property changes modifying the buffer.
2108 Any text properties changes happen as usual but the changes are not treated as
2109 modifications to the buffer."
2110 (declare (indent 0) (debug t))
2111 (let ((modified (make-symbol "modified")))
2112 `(let ((,modified (buffer-modified-p))
2113 (inhibit-read-only t)
2114 (inhibit-modification-hooks t)
2115 (buffer-undo-list t)
2116 (deactivate-mark nil)
2117 ;; Apparently these avoid file locking problems.
2118 (buffer-file-name nil)
2119 (buffer-file-truename nil))
2120 (unwind-protect
2121 (progn ,@body)
2122 (unless ,modified
2123 (restore-buffer-modified-p nil))))))
2124
2125 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2126 "Evaluate BODY with the _ character set to be word-syntax."
2127 (declare (indent 0) (debug t))
2128 (let ((old-syntax (make-symbol "old-syntax")))
2129 `(let ((,old-syntax (string (char-syntax ?_))))
2130 (unwind-protect
2131 (progn
2132 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2133 ,@body)
2134 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2135
2136 (defsubst js2-char-uppercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2139 (/= c (downcase c)))
2140
2141 (defsubst js2-char-lowercase-p (c)
2142 "Return t if C is an uppercase character.
2143 Handles unicode and latin chars properly."
2144 (/= c (upcase c)))
2145
2146 ;;; AST struct and function definitions
2147
2148 ;; flags for ast node property 'member-type (used for e4x operators)
2149 (defvar js2-property-flag #x1 "property access: element is valid name")
2150 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2151 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2152
2153 (defsubst js2-relpos (pos anchor)
2154 "Convert POS to be relative to ANCHOR.
2155 If POS is nil, returns nil."
2156 (and pos (- pos anchor)))
2157
2158 (defsubst js2-make-pad (indent)
2159 (if (zerop indent)
2160 ""
2161 (make-string (* indent js2-basic-offset) ? )))
2162
2163 (defsubst js2-visit-ast (node callback)
2164 "Visit every node in ast NODE with visitor CALLBACK.
2165
2166 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2167 called twice: once to visit the node, and again after all the node's
2168 children have been processed. The END-P argument is nil on the first
2169 call and non-nil on the second call. The return value of the callback
2170 affects the traversal: if non-nil, the children of NODE are processed.
2171 If the callback returns nil, or if the node has no children, then the
2172 callback is called immediately with a non-nil END-P argument.
2173
2174 The node traversal is approximately lexical-order, although there
2175 are currently no guarantees around this."
2176 (if node
2177 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2178 ;; visit the node
2179 (when (funcall callback node nil)
2180 ;; visit the kids
2181 (cond
2182 ((eq vfunc 'js2-visit-none)
2183 nil) ; don't even bother calling it
2184 ;; Each AST node type has to define a `js2-visitor' function
2185 ;; that takes a node and a callback, and calls `js2-visit-ast'
2186 ;; on each child of the node.
2187 (vfunc
2188 (funcall vfunc node callback))
2189 (t
2190 (error "%s does not define a visitor-traversal function"
2191 (aref node 0)))))
2192 ;; call the end-visit
2193 (funcall callback node t))))
2194
2195 (defstruct (js2-node
2196 (:constructor nil)) ; abstract
2197 "Base AST node type."
2198 (type -1) ; token type
2199 (pos -1) ; start position of this AST node in parsed input
2200 (len 1) ; num characters spanned by the node
2201 props ; optional node property list (an alist)
2202 parent) ; link to parent node; null for root
2203
2204 (defsubst js2-node-get-prop (node prop &optional default)
2205 (or (cadr (assoc prop (js2-node-props node))) default))
2206
2207 (defsubst js2-node-set-prop (node prop value)
2208 (setf (js2-node-props node)
2209 (cons (list prop value) (js2-node-props node))))
2210
2211 (defsubst js2-fixup-starts (n nodes)
2212 "Adjust the start positions of NODES to be relative to N.
2213 Any node in the list may be nil, for convenience."
2214 (dolist (node nodes)
2215 (when node
2216 (setf (js2-node-pos node) (- (js2-node-pos node)
2217 (js2-node-pos n))))))
2218
2219 (defsubst js2-node-add-children (parent &rest nodes)
2220 "Set parent node of NODES to PARENT, and return PARENT.
2221 Does nothing if we're not recording parent links.
2222 If any given node in NODES is nil, doesn't record that link."
2223 (js2-fixup-starts parent nodes)
2224 (dolist (node nodes)
2225 (and node
2226 (setf (js2-node-parent node) parent))))
2227
2228 ;; Non-recursive since it's called a frightening number of times.
2229 (defsubst js2-node-abs-pos (n)
2230 (let ((pos (js2-node-pos n)))
2231 (while (setq n (js2-node-parent n))
2232 (setq pos (+ pos (js2-node-pos n))))
2233 pos))
2234
2235 (defsubst js2-node-abs-end (n)
2236 "Return absolute buffer position of end of N."
2237 (+ (js2-node-abs-pos n) (js2-node-len n)))
2238
2239 ;; It's important to make sure block nodes have a lisp list for the
2240 ;; child nodes, to limit printing recursion depth in an AST that
2241 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2242 ;; a sufficiently large vector tree.
2243
2244 (defstruct (js2-block-node
2245 (:include js2-node)
2246 (:constructor nil)
2247 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2248 (pos js2-token-beg)
2249 len
2250 props
2251 kids)))
2252 "A block of statements."
2253 kids) ; a lisp list of the child statement nodes
2254
2255 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2256 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2257
2258 (defsubst js2-visit-block (ast callback)
2259 "Visit the `js2-block-node' children of AST."
2260 (dolist (kid (js2-block-node-kids ast))
2261 (js2-visit-ast kid callback)))
2262
2263 (defun js2-print-block (n i)
2264 (let ((pad (js2-make-pad i)))
2265 (insert pad "{\n")
2266 (dolist (kid (js2-block-node-kids n))
2267 (js2-print-ast kid (1+ i)))
2268 (insert pad "}")))
2269
2270 (defstruct (js2-scope
2271 (:include js2-block-node)
2272 (:constructor nil)
2273 (:constructor make-js2-scope (&key (type js2-BLOCK)
2274 (pos js2-token-beg)
2275 len
2276 kids)))
2277 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2278 ;; I don't have one of those handy, so I'll use an alist for now.
2279 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2280 ;; and is much lighter-weight to construct (both CPU and mem).
2281 ;; The keys are interned strings (symbols) for faster lookup.
2282 ;; Should switch to hybrid alist/hashtable eventually.
2283 symbol-table ; an alist of (symbol . js2-symbol)
2284 parent-scope ; a `js2-scope'
2285 top) ; top-level `js2-scope' (script/function)
2286
2287 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2288 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2289
2290 (defun js2-scope-set-parent-scope (scope parent)
2291 (setf (js2-scope-parent-scope scope) parent
2292 (js2-scope-top scope) (if (null parent)
2293 scope
2294 (js2-scope-top parent))))
2295
2296 (defun js2-node-get-enclosing-scope (node)
2297 "Return the innermost `js2-scope' node surrounding NODE.
2298 Returns nil if there is no enclosing scope node."
2299 (let ((parent (js2-node-parent node)))
2300 (while (not (js2-scope-p parent))
2301 (setq parent (js2-node-parent parent)))
2302 parent))
2303
2304 (defun js2-get-defining-scope (scope name)
2305 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2306 Returns `js2-scope' in which NAME is defined, or nil if not found."
2307 (let ((sym (if (symbolp name)
2308 name
2309 (intern name)))
2310 table
2311 result
2312 (continue t))
2313 (while (and scope continue)
2314 (if (and (setq table (js2-scope-symbol-table scope))
2315 (assq sym table))
2316 (setq continue nil
2317 result scope)
2318 (setq scope (js2-scope-parent-scope scope))))
2319 result))
2320
2321 (defsubst js2-scope-get-symbol (scope name)
2322 "Return symbol table entry for NAME in SCOPE.
2323 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2324 (and (js2-scope-symbol-table scope)
2325 (cdr (assq (if (symbolp name)
2326 name
2327 (intern name))
2328 (js2-scope-symbol-table scope)))))
2329
2330 (defsubst js2-scope-put-symbol (scope name symbol)
2331 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2332 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2333 (let* ((table (js2-scope-symbol-table scope))
2334 (sym (if (symbolp name) name (intern name)))
2335 (entry (assq sym table)))
2336 (if entry
2337 (setcdr entry symbol)
2338 (push (cons sym symbol)
2339 (js2-scope-symbol-table scope)))))
2340
2341 (defstruct (js2-symbol
2342 (:constructor nil)
2343 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2344 "A symbol table entry."
2345 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2346 ;; js2-LET, or js2-CONST
2347 decl-type
2348 name ; string
2349 ast-node) ; a `js2-node'
2350
2351 (defstruct (js2-error-node
2352 (:include js2-node)
2353 (:constructor nil) ; silence emacs21 byte-compiler
2354 (:constructor make-js2-error-node (&key (type js2-ERROR)
2355 (pos js2-token-beg)
2356 len)))
2357 "AST node representing a parse error.")
2358
2359 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2360 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2361
2362 (defstruct (js2-script-node
2363 (:include js2-scope)
2364 (:constructor nil)
2365 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2366 (pos js2-token-beg)
2367 len
2368 var-decls
2369 fun-decls)))
2370 functions ; lisp list of nested functions
2371 regexps ; lisp list of (string . flags)
2372 symbols ; alist (every symbol gets unique index)
2373 (param-count 0)
2374 var-names ; vector of string names
2375 consts ; bool-vector matching var-decls
2376 (temp-number 0)) ; for generating temp variables
2377
2378 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2379 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2380
2381 (defun js2-print-script (node indent)
2382 (dolist (kid (js2-block-node-kids node))
2383 (js2-print-ast kid indent)))
2384
2385 (defstruct (js2-ast-root
2386 (:include js2-script-node)
2387 (:constructor nil)
2388 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2389 (pos js2-token-beg)
2390 len
2391 buffer)))
2392 "The root node of a js2 AST."
2393 buffer ; the source buffer from which the code was parsed
2394 comments ; a lisp list of comments, ordered by start position
2395 errors ; a lisp list of errors found during parsing
2396 warnings ; a lisp list of warnings found during parsing
2397 node-count) ; number of nodes in the tree, including the root
2398
2399 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2400 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2401
2402 (defun js2-visit-ast-root (ast callback)
2403 (dolist (kid (js2-ast-root-kids ast))
2404 (js2-visit-ast kid callback))
2405 (dolist (comment (js2-ast-root-comments ast))
2406 (js2-visit-ast comment callback)))
2407
2408 (defstruct (js2-comment-node
2409 (:include js2-node)
2410 (:constructor nil)
2411 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2412 (pos js2-token-beg)
2413 len
2414 (format js2-ts-comment-type))))
2415 format) ; 'line, 'block, 'jsdoc or 'html
2416
2417 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2418 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2419
2420 (defun js2-print-comment (n i)
2421 ;; We really ought to link end-of-line comments to their nodes.
2422 ;; Or maybe we could add a new comment type, 'endline.
2423 (insert (js2-make-pad i)
2424 (js2-node-string n)))
2425
2426 (defstruct (js2-expr-stmt-node
2427 (:include js2-node)
2428 (:constructor nil)
2429 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2430 (pos js2-ts-cursor)
2431 len
2432 expr)))
2433 "An expression statement."
2434 expr)
2435
2436 (defsubst js2-expr-stmt-node-set-has-result (node)
2437 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2438 (setf (js2-node-type node) js2-EXPR_RESULT))
2439
2440 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2441 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2442
2443 (defun js2-visit-expr-stmt-node (n v)
2444 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2445
2446 (defun js2-print-expr-stmt-node (n indent)
2447 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2448 (insert ";\n"))
2449
2450 (defstruct (js2-loop-node
2451 (:include js2-scope)
2452 (:constructor nil))
2453 "Abstract supertype of loop nodes."
2454 body ; a `js2-block-node'
2455 lp ; position of left-paren, nil if omitted
2456 rp) ; position of right-paren, nil if omitted
2457
2458 (defstruct (js2-do-node
2459 (:include js2-loop-node)
2460 (:constructor nil)
2461 (:constructor make-js2-do-node (&key (type js2-DO)
2462 (pos js2-token-beg)
2463 len
2464 body
2465 condition
2466 while-pos
2467 lp
2468 rp)))
2469 "AST node for do-loop."
2470 condition ; while (expression)
2471 while-pos) ; buffer position of 'while' keyword
2472
2473 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2474 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2475
2476 (defun js2-visit-do-node (n v)
2477 (js2-visit-ast (js2-do-node-body n) v)
2478 (js2-visit-ast (js2-do-node-condition n) v))
2479
2480 (defun js2-print-do-node (n i)
2481 (let ((pad (js2-make-pad i)))
2482 (insert pad "do {\n")
2483 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2484 (js2-print-ast kid (1+ i)))
2485 (insert pad "} while (")
2486 (js2-print-ast (js2-do-node-condition n) 0)
2487 (insert ");\n")))
2488
2489 (defstruct (js2-while-node
2490 (:include js2-loop-node)
2491 (:constructor nil)
2492 (:constructor make-js2-while-node (&key (type js2-WHILE)
2493 (pos js2-token-beg)
2494 len
2495 body
2496 condition
2497 lp
2498 rp)))
2499 "AST node for while-loop."
2500 condition) ; while-condition
2501
2502 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2503 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2504
2505 (defun js2-visit-while-node (n v)
2506 (js2-visit-ast (js2-while-node-condition n) v)
2507 (js2-visit-ast (js2-while-node-body n) v))
2508
2509 (defun js2-print-while-node (n i)
2510 (let ((pad (js2-make-pad i)))
2511 (insert pad "while (")
2512 (js2-print-ast (js2-while-node-condition n) 0)
2513 (insert ") {\n")
2514 (js2-print-body (js2-while-node-body n) (1+ i))
2515 (insert pad "}\n")))
2516
2517 (defstruct (js2-for-node
2518 (:include js2-loop-node)
2519 (:constructor nil)
2520 (:constructor make-js2-for-node (&key (type js2-FOR)
2521 (pos js2-ts-cursor)
2522 len
2523 body
2524 init
2525 condition
2526 update
2527 lp
2528 rp)))
2529 "AST node for a C-style for-loop."
2530 init ; initialization expression
2531 condition ; loop condition
2532 update) ; update clause
2533
2534 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2535 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2536
2537 (defun js2-visit-for-node (n v)
2538 (js2-visit-ast (js2-for-node-init n) v)
2539 (js2-visit-ast (js2-for-node-condition n) v)
2540 (js2-visit-ast (js2-for-node-update n) v)
2541 (js2-visit-ast (js2-for-node-body n) v))
2542
2543 (defun js2-print-for-node (n i)
2544 (let ((pad (js2-make-pad i)))
2545 (insert pad "for (")
2546 (js2-print-ast (js2-for-node-init n) 0)
2547 (insert "; ")
2548 (js2-print-ast (js2-for-node-condition n) 0)
2549 (insert "; ")
2550 (js2-print-ast (js2-for-node-update n) 0)
2551 (insert ") {\n")
2552 (js2-print-body (js2-for-node-body n) (1+ i))
2553 (insert pad "}\n")))
2554
2555 (defstruct (js2-for-in-node
2556 (:include js2-loop-node)
2557 (:constructor nil)
2558 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2559 (pos js2-ts-cursor)
2560 len
2561 body
2562 iterator
2563 object
2564 in-pos
2565 each-pos
2566 foreach-p
2567 lp
2568 rp)))
2569 "AST node for a for..in loop."
2570 iterator ; [var] foo in ...
2571 object ; object over which we're iterating
2572 in-pos ; buffer position of 'in' keyword
2573 each-pos ; buffer position of 'each' keyword, if foreach-p
2574 foreach-p) ; t if it's a for-each loop
2575
2576 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2577 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2578
2579 (defun js2-visit-for-in-node (n v)
2580 (js2-visit-ast (js2-for-in-node-iterator n) v)
2581 (js2-visit-ast (js2-for-in-node-object n) v)
2582 (js2-visit-ast (js2-for-in-node-body n) v))
2583
2584 (defun js2-print-for-in-node (n i)
2585 (let ((pad (js2-make-pad i))
2586 (foreach (js2-for-in-node-foreach-p n)))
2587 (insert pad "for ")
2588 (if foreach
2589 (insert "each "))
2590 (insert "(")
2591 (js2-print-ast (js2-for-in-node-iterator n) 0)
2592 (insert " in ")
2593 (js2-print-ast (js2-for-in-node-object n) 0)
2594 (insert ") {\n")
2595 (js2-print-body (js2-for-in-node-body n) (1+ i))
2596 (insert pad "}\n")))
2597
2598 (defstruct (js2-return-node
2599 (:include js2-node)
2600 (:constructor nil)
2601 (:constructor make-js2-return-node (&key (type js2-RETURN)
2602 (pos js2-ts-cursor)
2603 len
2604 retval)))
2605 "AST node for a return statement."
2606 retval) ; expression to return, or 'undefined
2607
2608 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2609 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2610
2611 (defun js2-visit-return-node (n v)
2612 (js2-visit-ast (js2-return-node-retval n) v))
2613
2614 (defun js2-print-return-node (n i)
2615 (insert (js2-make-pad i) "return")
2616 (when (js2-return-node-retval n)
2617 (insert " ")
2618 (js2-print-ast (js2-return-node-retval n) 0))
2619 (insert ";\n"))
2620
2621 (defstruct (js2-if-node
2622 (:include js2-node)
2623 (:constructor nil)
2624 (:constructor make-js2-if-node (&key (type js2-IF)
2625 (pos js2-ts-cursor)
2626 len
2627 condition
2628 then-part
2629 else-pos
2630 else-part
2631 lp
2632 rp)))
2633 "AST node for an if-statement."
2634 condition ; expression
2635 then-part ; statement or block
2636 else-pos ; optional buffer position of 'else' keyword
2637 else-part ; optional statement or block
2638 lp ; position of left-paren, nil if omitted
2639 rp) ; position of right-paren, nil if omitted
2640
2641 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2642 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2643
2644 (defun js2-visit-if-node (n v)
2645 (js2-visit-ast (js2-if-node-condition n) v)
2646 (js2-visit-ast (js2-if-node-then-part n) v)
2647 (js2-visit-ast (js2-if-node-else-part n) v))
2648
2649 (defun js2-print-if-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (then-part (js2-if-node-then-part n))
2652 (else-part (js2-if-node-else-part n)))
2653 (insert pad "if (")
2654 (js2-print-ast (js2-if-node-condition n) 0)
2655 (insert ") {\n")
2656 (js2-print-body then-part (1+ i))
2657 (insert pad "}")
2658 (cond
2659 ((not else-part)
2660 (insert "\n"))
2661 ((js2-if-node-p else-part)
2662 (insert " else ")
2663 (js2-print-body else-part i))
2664 (t
2665 (insert " else {\n")
2666 (js2-print-body else-part (1+ i))
2667 (insert pad "}\n")))))
2668
2669 (defstruct (js2-try-node
2670 (:include js2-node)
2671 (:constructor nil)
2672 (:constructor make-js2-try-node (&key (type js2-TRY)
2673 (pos js2-ts-cursor)
2674 len
2675 try-block
2676 catch-clauses
2677 finally-block)))
2678 "AST node for a try-statement."
2679 try-block
2680 catch-clauses ; a lisp list of `js2-catch-node'
2681 finally-block) ; a `js2-finally-node'
2682
2683 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2684 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2685
2686 (defun js2-visit-try-node (n v)
2687 (js2-visit-ast (js2-try-node-try-block n) v)
2688 (dolist (clause (js2-try-node-catch-clauses n))
2689 (js2-visit-ast clause v))
2690 (js2-visit-ast (js2-try-node-finally-block n) v))
2691
2692 (defun js2-print-try-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (catches (js2-try-node-catch-clauses n))
2695 (finally (js2-try-node-finally-block n)))
2696 (insert pad "try {\n")
2697 (js2-print-body (js2-try-node-try-block n) (1+ i))
2698 (insert pad "}")
2699 (when catches
2700 (dolist (catch catches)
2701 (js2-print-ast catch i)))
2702 (if finally
2703 (js2-print-ast finally i)
2704 (insert "\n"))))
2705
2706 (defstruct (js2-catch-node
2707 (:include js2-node)
2708 (:constructor nil)
2709 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2710 (pos js2-ts-cursor)
2711 len
2712 param
2713 guard-kwd
2714 guard-expr
2715 block
2716 lp
2717 rp)))
2718 "AST node for a catch clause."
2719 param ; destructuring form or simple name node
2720 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2721 guard-expr ; catch condition, a `js2-node'
2722 block ; statements, a `js2-block-node'
2723 lp ; buffer position of left-paren, nil if omitted
2724 rp) ; buffer position of right-paren, nil if omitted
2725
2726 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2727 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2728
2729 (defun js2-visit-catch-node (n v)
2730 (js2-visit-ast (js2-catch-node-param n) v)
2731 (when (js2-catch-node-guard-kwd n)
2732 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2733 (js2-visit-ast (js2-catch-node-block n) v))
2734
2735 (defun js2-print-catch-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (guard-kwd (js2-catch-node-guard-kwd n))
2738 (guard-expr (js2-catch-node-guard-expr n)))
2739 (insert " catch (")
2740 (js2-print-ast (js2-catch-node-param n) 0)
2741 (when guard-kwd
2742 (insert " if ")
2743 (js2-print-ast guard-expr 0))
2744 (insert ") {\n")
2745 (js2-print-body (js2-catch-node-block n) (1+ i))
2746 (insert pad "}")))
2747
2748 (defstruct (js2-finally-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2752 (pos js2-ts-cursor)
2753 len
2754 body)))
2755 "AST node for a finally clause."
2756 body) ; a `js2-node', often but not always a block node
2757
2758 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2759 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2760
2761 (defun js2-visit-finally-node (n v)
2762 (js2-visit-ast (js2-finally-node-body n) v))
2763
2764 (defun js2-print-finally-node (n i)
2765 (let ((pad (js2-make-pad i)))
2766 (insert " finally {\n")
2767 (js2-print-body (js2-finally-node-body n) (1+ i))
2768 (insert pad "}\n")))
2769
2770 (defstruct (js2-switch-node
2771 (:include js2-node)
2772 (:constructor nil)
2773 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2774 (pos js2-ts-cursor)
2775 len
2776 discriminant
2777 cases
2778 lp
2779 rp)))
2780 "AST node for a switch statement."
2781 discriminant ; a `js2-node' (switch expression)
2782 cases ; a lisp list of `js2-case-node'
2783 lp ; position of open-paren for discriminant, nil if omitted
2784 rp) ; position of close-paren for discriminant, nil if omitted
2785
2786 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2787 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2788
2789 (defun js2-visit-switch-node (n v)
2790 (js2-visit-ast (js2-switch-node-discriminant n) v)
2791 (dolist (c (js2-switch-node-cases n))
2792 (js2-visit-ast c v)))
2793
2794 (defun js2-print-switch-node (n i)
2795 (let ((pad (js2-make-pad i))
2796 (cases (js2-switch-node-cases n)))
2797 (insert pad "switch (")
2798 (js2-print-ast (js2-switch-node-discriminant n) 0)
2799 (insert ") {\n")
2800 (dolist (case cases)
2801 (js2-print-ast case i))
2802 (insert pad "}\n")))
2803
2804 (defstruct (js2-case-node
2805 (:include js2-block-node)
2806 (:constructor nil)
2807 (:constructor make-js2-case-node (&key (type js2-CASE)
2808 (pos js2-ts-cursor)
2809 len
2810 kids
2811 expr)))
2812 "AST node for a case clause of a switch statement."
2813 expr) ; the case expression (nil for default)
2814
2815 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2816 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2817
2818 (defun js2-visit-case-node (n v)
2819 (js2-visit-ast (js2-case-node-expr n) v)
2820 (js2-visit-block n v))
2821
2822 (defun js2-print-case-node (n i)
2823 (let ((pad (js2-make-pad i))
2824 (expr (js2-case-node-expr n)))
2825 (insert pad)
2826 (if (null expr)
2827 (insert "default:\n")
2828 (insert "case ")
2829 (js2-print-ast expr 0)
2830 (insert ":\n"))
2831 (dolist (kid (js2-case-node-kids n))
2832 (js2-print-ast kid (1+ i)))))
2833
2834 (defstruct (js2-throw-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-throw-node (&key (type js2-THROW)
2838 (pos js2-ts-cursor)
2839 len
2840 expr)))
2841 "AST node for a throw statement."
2842 expr) ; the expression to throw
2843
2844 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2845 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2846
2847 (defun js2-visit-throw-node (n v)
2848 (js2-visit-ast (js2-throw-node-expr n) v))
2849
2850 (defun js2-print-throw-node (n i)
2851 (insert (js2-make-pad i) "throw ")
2852 (js2-print-ast (js2-throw-node-expr n) 0)
2853 (insert ";\n"))
2854
2855 (defstruct (js2-with-node
2856 (:include js2-node)
2857 (:constructor nil)
2858 (:constructor make-js2-with-node (&key (type js2-WITH)
2859 (pos js2-ts-cursor)
2860 len
2861 object
2862 body
2863 lp
2864 rp)))
2865 "AST node for a with-statement."
2866 object
2867 body
2868 lp ; buffer position of left-paren around object, nil if omitted
2869 rp) ; buffer position of right-paren around object, nil if omitted
2870
2871 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2872 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2873
2874 (defun js2-visit-with-node (n v)
2875 (js2-visit-ast (js2-with-node-object n) v)
2876 (js2-visit-ast (js2-with-node-body n) v))
2877
2878 (defun js2-print-with-node (n i)
2879 (let ((pad (js2-make-pad i)))
2880 (insert pad "with (")
2881 (js2-print-ast (js2-with-node-object n) 0)
2882 (insert ") {\n")
2883 (js2-print-body (js2-with-node-body n) (1+ i))
2884 (insert pad "}\n")))
2885
2886 (defstruct (js2-label-node
2887 (:include js2-node)
2888 (:constructor nil)
2889 (:constructor make-js2-label-node (&key (type js2-LABEL)
2890 (pos js2-ts-cursor)
2891 len
2892 name)))
2893 "AST node for a statement label or case label."
2894 name ; a string
2895 loop) ; for validating and code-generating continue-to-label
2896
2897 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2898 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2899
2900 (defun js2-print-label (n i)
2901 (insert (js2-make-pad i)
2902 (js2-label-node-name n)
2903 ":\n"))
2904
2905 (defstruct (js2-labeled-stmt-node
2906 (:include js2-node)
2907 (:constructor nil)
2908 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2909 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2910 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2911 (pos js2-ts-cursor)
2912 len
2913 labels
2914 stmt)))
2915 "AST node for a statement with one or more labels.
2916 Multiple labels for a statement are collapsed into the labels field."
2917 labels ; lisp list of `js2-label-node'
2918 stmt) ; the statement these labels are for
2919
2920 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2922
2923 (defun js2-get-label-by-name (lbl-stmt name)
2924 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2925 Returns nil if no such label is in the list."
2926 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2927 result)
2928 (while (and label-list (not result))
2929 (if (string= (js2-label-node-name (car label-list)) name)
2930 (setq result (car label-list))
2931 (setq label-list (cdr label-list))))
2932 result))
2933
2934 (defun js2-visit-labeled-stmt (n v)
2935 (dolist (label (js2-labeled-stmt-node-labels n))
2936 (js2-visit-ast label v))
2937 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2938
2939 (defun js2-print-labeled-stmt (n i)
2940 (dolist (label (js2-labeled-stmt-node-labels n))
2941 (js2-print-ast label i))
2942 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2943
2944 (defun js2-labeled-stmt-node-contains (node label)
2945 "Return t if NODE contains LABEL in its label set.
2946 NODE is a `js2-labels-node'. LABEL is an identifier."
2947 (loop for nl in (js2-labeled-stmt-node-labels node)
2948 if (string= label (js2-label-node-name nl))
2949 return t
2950 finally return nil))
2951
2952 (defsubst js2-labeled-stmt-node-add-label (node label)
2953 "Add a `js2-label-node' to the label set for this statement."
2954 (setf (js2-labeled-stmt-node-labels node)
2955 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2956
2957 (defstruct (js2-jump-node
2958 (:include js2-node)
2959 (:constructor nil))
2960 "Abstract supertype of break and continue nodes."
2961 label ; `js2-name-node' for location of label identifier, if present
2962 target) ; target js2-labels-node or loop/switch statement
2963
2964 (defun js2-visit-jump-node (n v)
2965 (js2-visit-ast (js2-jump-node-label n) v))
2966
2967 (defstruct (js2-break-node
2968 (:include js2-jump-node)
2969 (:constructor nil)
2970 (:constructor make-js2-break-node (&key (type js2-BREAK)
2971 (pos js2-ts-cursor)
2972 len
2973 label
2974 target)))
2975 "AST node for a break statement.
2976 The label field is a `js2-name-node', possibly nil, for the named label
2977 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2978 is the target of the break - a label node or enclosing loop/switch statement.")
2979
2980 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2981 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2982
2983 (defun js2-print-break-node (n i)
2984 (insert (js2-make-pad i) "break")
2985 (when (js2-break-node-label n)
2986 (insert " ")
2987 (js2-print-ast (js2-break-node-label n) 0))
2988 (insert ";\n"))
2989
2990 (defstruct (js2-continue-node
2991 (:include js2-jump-node)
2992 (:constructor nil)
2993 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2994 (pos js2-ts-cursor)
2995 len
2996 label
2997 target)))
2998 "AST node for a continue statement.
2999 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3000 It is nil if continue specifies no label. The target field is the jump target:
3001 a `js2-label-node' or the innermost enclosing loop.")
3002
3003 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3004 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3005
3006 (defun js2-print-continue-node (n i)
3007 (insert (js2-make-pad i) "continue")
3008 (when (js2-continue-node-label n)
3009 (insert " ")
3010 (js2-print-ast (js2-continue-node-label n) 0))
3011 (insert ";\n"))
3012
3013 (defstruct (js2-function-node
3014 (:include js2-script-node)
3015 (:constructor nil)
3016 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3017 (pos js2-ts-cursor)
3018 len
3019 (ftype 'FUNCTION)
3020 (form 'FUNCTION_STATEMENT)
3021 (name "")
3022 params
3023 body
3024 lp
3025 rp)))
3026 "AST node for a function declaration.
3027 The `params' field is a lisp list of nodes. Each node is either a simple
3028 `js2-name-node', or if it's a destructuring-assignment parameter, a
3029 `js2-array-node' or `js2-object-node'."
3030 ftype ; FUNCTION, GETTER or SETTER
3031 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3032 name ; function name (a `js2-name-node', or nil if anonymous)
3033 params ; a lisp list of destructuring forms or simple name nodes
3034 body ; a `js2-block-node' or expression node (1.8 only)
3035 lp ; position of arg-list open-paren, or nil if omitted
3036 rp ; position of arg-list close-paren, or nil if omitted
3037 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3038 needs-activation ; t if we need an activation object for this frame
3039 is-generator ; t if this function contains a yield
3040 member-expr) ; nonstandard Ecma extension from Rhino
3041
3042 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3043 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3044
3045 (defun js2-visit-function-node (n v)
3046 (js2-visit-ast (js2-function-node-name n) v)
3047 (dolist (p (js2-function-node-params n))
3048 (js2-visit-ast p v))
3049 (js2-visit-ast (js2-function-node-body n) v))
3050
3051 (defun js2-print-function-node (n i)
3052 (let ((pad (js2-make-pad i))
3053 (getter (js2-node-get-prop n 'GETTER_SETTER))
3054 (name (js2-function-node-name n))
3055 (params (js2-function-node-params n))
3056 (body (js2-function-node-body n))
3057 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3058 (unless getter
3059 (insert pad "function"))
3060 (when name
3061 (insert " ")
3062 (js2-print-ast name 0))
3063 (insert "(")
3064 (loop with len = (length params)
3065 for param in params
3066 for count from 1
3067 do
3068 (js2-print-ast param 0)
3069 (if (< count len)
3070 (insert ", ")))
3071 (insert ") {")
3072 (unless expr
3073 (insert "\n"))
3074 ;; TODO: fix this to be smarter about indenting, etc.
3075 (js2-print-body body (1+ i))
3076 (insert pad "}")
3077 (unless expr
3078 (insert "\n"))))
3079
3080 (defsubst js2-function-name (node)
3081 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3082 (and (js2-function-node-name node)
3083 (js2-name-node-name (js2-function-node-name node))))
3084
3085 ;; Having this be an expression node makes it more flexible.
3086 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3087 ;; that work better if you assume it's an expression. Whenever we have
3088 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3089 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3090 (defstruct (js2-var-decl-node
3091 (:include js2-node)
3092 (:constructor nil)
3093 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3094 (pos js2-token-beg)
3095 len
3096 kids
3097 decl-type)))
3098 "AST node for a variable declaration list (VAR, CONST or LET).
3099 The node bounds differ depending on the declaration type. For VAR or
3100 CONST declarations, the bounds include the var/const keyword. For LET
3101 declarations, the node begins at the position of the first child."
3102 kids ; a lisp list of `js2-var-init-node' structs.
3103 decl-type) ; js2-VAR, js2-CONST or js2-LET
3104
3105 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3106 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3107
3108 (defun js2-visit-var-decl (n v)
3109 (dolist (kid (js2-var-decl-node-kids n))
3110 (js2-visit-ast kid v)))
3111
3112 (defun js2-print-var-decl (n i)
3113 (let ((pad (js2-make-pad i))
3114 (tt (js2-var-decl-node-decl-type n)))
3115 (insert pad)
3116 (insert (cond
3117 ((= tt js2-VAR) "var ")
3118 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3119 ((= tt js2-CONST) "const ")
3120 (t
3121 (error "malformed var-decl node"))))
3122 (loop with kids = (js2-var-decl-node-kids n)
3123 with len = (length kids)
3124 for kid in kids
3125 for count from 1
3126 do
3127 (js2-print-ast kid 0)
3128 (if (< count len)
3129 (insert ", ")))))
3130
3131 (defstruct (js2-var-init-node
3132 (:include js2-node)
3133 (:constructor nil)
3134 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3135 (pos js2-ts-cursor)
3136 len
3137 target
3138 initializer)))
3139 "AST node for a variable declaration.
3140 The type field will be js2-CONST for a const decl."
3141 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3142 initializer) ; initializer expression, a `js2-node'
3143
3144 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3145 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3146
3147 (defun js2-visit-var-init-node (n v)
3148 (js2-visit-ast (js2-var-init-node-target n) v)
3149 (js2-visit-ast (js2-var-init-node-initializer n) v))
3150
3151 (defun js2-print-var-init-node (n i)
3152 (let ((pad (js2-make-pad i))
3153 (name (js2-var-init-node-target n))
3154 (init (js2-var-init-node-initializer n)))
3155 (insert pad)
3156 (js2-print-ast name 0)
3157 (when init
3158 (insert " = ")
3159 (js2-print-ast init 0))))
3160
3161 (defstruct (js2-cond-node
3162 (:include js2-node)
3163 (:constructor nil)
3164 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3165 (pos js2-ts-cursor)
3166 len
3167 test-expr
3168 true-expr
3169 false-expr
3170 q-pos
3171 c-pos)))
3172 "AST node for the ternary operator"
3173 test-expr
3174 true-expr
3175 false-expr
3176 q-pos ; buffer position of ?
3177 c-pos) ; buffer position of :
3178
3179 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3180 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3181
3182 (defun js2-visit-cond-node (n v)
3183 (js2-visit-ast (js2-cond-node-test-expr n) v)
3184 (js2-visit-ast (js2-cond-node-true-expr n) v)
3185 (js2-visit-ast (js2-cond-node-false-expr n) v))
3186
3187 (defun js2-print-cond-node (n i)
3188 (let ((pad (js2-make-pad i)))
3189 (insert pad)
3190 (js2-print-ast (js2-cond-node-test-expr n) 0)
3191 (insert " ? ")
3192 (js2-print-ast (js2-cond-node-true-expr n) 0)
3193 (insert " : ")
3194 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3195
3196 (defstruct (js2-infix-node
3197 (:include js2-node)
3198 (:constructor nil)
3199 (:constructor make-js2-infix-node (&key type
3200 (pos js2-ts-cursor)
3201 len
3202 op-pos
3203 left
3204 right)))
3205 "Represents infix expressions.
3206 Includes assignment ops like `|=', and the comma operator.
3207 The type field inherited from `js2-node' holds the operator."
3208 op-pos ; buffer position where operator begins
3209 left ; any `js2-node'
3210 right) ; any `js2-node'
3211
3212 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3213 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3214
3215 (defun js2-visit-infix-node (n v)
3216 (js2-visit-ast (js2-infix-node-left n) v)
3217 (js2-visit-ast (js2-infix-node-right n) v))
3218
3219 (defconst js2-operator-tokens
3220 (let ((table (make-hash-table :test 'eq))
3221 (tokens
3222 (list (cons js2-IN "in")
3223 (cons js2-TYPEOF "typeof")
3224 (cons js2-INSTANCEOF "instanceof")
3225 (cons js2-DELPROP "delete")
3226 (cons js2-COMMA ",")
3227 (cons js2-COLON ":")
3228 (cons js2-OR "||")
3229 (cons js2-AND "&&")
3230 (cons js2-INC "++")
3231 (cons js2-DEC "--")
3232 (cons js2-BITOR "|")
3233 (cons js2-BITXOR "^")
3234 (cons js2-BITAND "&")
3235 (cons js2-EQ "==")
3236 (cons js2-NE "!=")
3237 (cons js2-LT "<")
3238 (cons js2-LE "<=")
3239 (cons js2-GT ">")
3240 (cons js2-GE ">=")
3241 (cons js2-LSH "<<")
3242 (cons js2-RSH ">>")
3243 (cons js2-URSH ">>>")
3244 (cons js2-ADD "+") ; infix plus
3245 (cons js2-SUB "-") ; infix minus
3246 (cons js2-MUL "*")
3247 (cons js2-DIV "/")
3248 (cons js2-MOD "%")
3249 (cons js2-NOT "!")
3250 (cons js2-BITNOT "~")
3251 (cons js2-POS "+") ; unary plus
3252 (cons js2-NEG "-") ; unary minus
3253 (cons js2-SHEQ "===") ; shallow equality
3254 (cons js2-SHNE "!==") ; shallow inequality
3255 (cons js2-ASSIGN "=")
3256 (cons js2-ASSIGN_BITOR "|=")
3257 (cons js2-ASSIGN_BITXOR "^=")
3258 (cons js2-ASSIGN_BITAND "&=")
3259 (cons js2-ASSIGN_LSH "<<=")
3260 (cons js2-ASSIGN_RSH ">>=")
3261 (cons js2-ASSIGN_URSH ">>>=")
3262 (cons js2-ASSIGN_ADD "+=")
3263 (cons js2-ASSIGN_SUB "-=")
3264 (cons js2-ASSIGN_MUL "*=")
3265 (cons js2-ASSIGN_DIV "/=")
3266 (cons js2-ASSIGN_MOD "%="))))
3267 (loop for (k . v) in tokens do
3268 (puthash k v table))
3269 table))
3270
3271 (defun js2-print-infix-node (n i)
3272 (let* ((tt (js2-node-type n))
3273 (op (gethash tt js2-operator-tokens)))
3274 (unless op
3275 (error "unrecognized infix operator %s" (js2-node-type n)))
3276 (insert (js2-make-pad i))
3277 (js2-print-ast (js2-infix-node-left n) 0)
3278 (unless (= tt js2-COMMA)
3279 (insert " "))
3280 (insert op)
3281 (insert " ")
3282 (js2-print-ast (js2-infix-node-right n) 0)))
3283
3284 (defstruct (js2-assign-node
3285 (:include js2-infix-node)
3286 (:constructor nil)
3287 (:constructor make-js2-assign-node (&key type
3288 (pos js2-ts-cursor)
3289 len
3290 op-pos
3291 left
3292 right)))
3293 "Represents any assignment.
3294 The type field holds the actual assignment operator.")
3295
3296 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3297 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3298
3299 (defstruct (js2-unary-node
3300 (:include js2-node)
3301 (:constructor nil)
3302 (:constructor make-js2-unary-node (&key type ; required
3303 (pos js2-ts-cursor)
3304 len
3305 operand)))
3306 "AST node type for unary operator nodes.
3307 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3308 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3309 property is added if the operator follows the operand."
3310 operand) ; a `js2-node' expression
3311
3312 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3313 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3314
3315 (defun js2-visit-unary-node (n v)
3316 (js2-visit-ast (js2-unary-node-operand n) v))
3317
3318 (defun js2-print-unary-node (n i)
3319 (let* ((tt (js2-node-type n))
3320 (op (gethash tt js2-operator-tokens))
3321 (postfix (js2-node-get-prop n 'postfix)))
3322 (unless op
3323 (error "unrecognized unary operator %s" tt))
3324 (insert (js2-make-pad i))
3325 (unless postfix
3326 (insert op))
3327 (if (or (= tt js2-TYPEOF)
3328 (= tt js2-DELPROP))
3329 (insert " "))
3330 (js2-print-ast (js2-unary-node-operand n) 0)
3331 (when postfix
3332 (insert op))))
3333
3334 (defstruct (js2-let-node
3335 (:include js2-scope)
3336 (:constructor nil)
3337 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3338 (pos js2-token-beg)
3339 len
3340 vars
3341 body
3342 lp
3343 rp)))
3344 "AST node for a let expression or a let statement.
3345 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3346 vars ; a `js2-var-decl-node'
3347 body ; a `js2-node' representing the expression or body block
3348 lp
3349 rp)
3350
3351 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3352 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3353
3354 (defun js2-visit-let-node (n v)
3355 (js2-visit-ast (js2-let-node-vars n) v)
3356 (js2-visit-ast (js2-let-node-body n) v))
3357
3358 (defun js2-print-let-node (n i)
3359 (insert (js2-make-pad i) "let (")
3360 (js2-print-ast (js2-let-node-vars n) 0)
3361 (insert ") ")
3362 (js2-print-ast (js2-let-node-body n) i))
3363
3364 (defstruct (js2-keyword-node
3365 (:include js2-node)
3366 (:constructor nil)
3367 (:constructor make-js2-keyword-node (&key type
3368 (pos js2-token-beg)
3369 (len (- js2-ts-cursor pos)))))
3370 "AST node representing a literal keyword such as `null'.
3371 Used for `null', `this', `true', `false' and `debugger'.
3372 The node type is set to js2-NULL, js2-THIS, etc.")
3373
3374 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3376
3377 (defun js2-print-keyword-node (n i)
3378 (insert (js2-make-pad i)
3379 (let ((tt (js2-node-type n)))
3380 (cond
3381 ((= tt js2-THIS) "this")
3382 ((= tt js2-NULL) "null")
3383 ((= tt js2-TRUE) "true")
3384 ((= tt js2-FALSE) "false")
3385 ((= tt js2-DEBUGGER) "debugger")
3386 (t (error "Invalid keyword literal type: %d" tt))))))
3387
3388 (defsubst js2-this-node-p (node)
3389 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3390 (eq (js2-node-type node) js2-THIS))
3391
3392 (defstruct (js2-new-node
3393 (:include js2-node)
3394 (:constructor nil)
3395 (:constructor make-js2-new-node (&key (type js2-NEW)
3396 (pos js2-token-beg)
3397 len
3398 target
3399 args
3400 initializer
3401 lp
3402 rp)))
3403 "AST node for new-expression such as new Foo()."
3404 target ; an identifier or reference
3405 args ; a lisp list of argument nodes
3406 lp ; position of left-paren, nil if omitted
3407 rp ; position of right-paren, nil if omitted
3408 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3409
3410 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3411 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3412
3413 (defun js2-visit-new-node (n v)
3414 (js2-visit-ast (js2-new-node-target n) v)
3415 (dolist (arg (js2-new-node-args n))
3416 (js2-visit-ast arg v))
3417 (js2-visit-ast (js2-new-node-initializer n) v))
3418
3419 (defun js2-print-new-node (n i)
3420 (insert (js2-make-pad i) "new ")
3421 (js2-print-ast (js2-new-node-target n))
3422 (insert "(")
3423 (js2-print-list (js2-new-node-args n))
3424 (insert ")")
3425 (when (js2-new-node-initializer n)
3426 (insert " ")
3427 (js2-print-ast (js2-new-node-initializer n))))
3428
3429 (defstruct (js2-name-node
3430 (:include js2-node)
3431 (:constructor nil)
3432 (:constructor make-js2-name-node (&key (type js2-NAME)
3433 (pos js2-token-beg)
3434 (len (- js2-ts-cursor
3435 js2-token-beg))
3436 (name js2-ts-string))))
3437 "AST node for a JavaScript identifier"
3438 name ; a string
3439 scope) ; a `js2-scope' (optional, used for codegen)
3440
3441 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3442 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3443
3444 (defun js2-print-name-node (n i)
3445 (insert (js2-make-pad i)
3446 (js2-name-node-name n)))
3447
3448 (defsubst js2-name-node-length (node)
3449 "Return identifier length of NODE, a `js2-name-node'.
3450 Returns 0 if NODE is nil or its identifier field is nil."
3451 (if node
3452 (length (js2-name-node-name node))
3453 0))
3454
3455 (defstruct (js2-number-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3459 (pos js2-token-beg)
3460 (len (- js2-ts-cursor
3461 js2-token-beg))
3462 (value js2-ts-string)
3463 (num-value js2-ts-number))))
3464 "AST node for a number literal."
3465 value ; the original string, e.g. "6.02e23"
3466 num-value) ; the parsed number value
3467
3468 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3470
3471 (defun js2-print-number-node (n i)
3472 (insert (js2-make-pad i)
3473 (number-to-string (js2-number-node-num-value n))))
3474
3475 (defstruct (js2-regexp-node
3476 (:include js2-node)
3477 (:constructor nil)
3478 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3479 (pos js2-token-beg)
3480 (len (- js2-ts-cursor
3481 js2-token-beg))
3482 value
3483 flags)))
3484 "AST node for a regular expression literal."
3485 value ; the regexp string, without // delimiters
3486 flags) ; a string of flags, e.g. `mi'.
3487
3488 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3489 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3490
3491 (defun js2-print-regexp (n i)
3492 (insert (js2-make-pad i)
3493 "/"
3494 (js2-regexp-node-value n)
3495 "/")
3496 (if (js2-regexp-node-flags n)
3497 (insert (js2-regexp-node-flags n))))
3498
3499 (defstruct (js2-string-node
3500 (:include js2-node)
3501 (:constructor nil)
3502 (:constructor make-js2-string-node (&key (type js2-STRING)
3503 (pos js2-token-beg)
3504 (len (- js2-ts-cursor
3505 js2-token-beg))
3506 (value js2-ts-string))))
3507 "String literal.
3508 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3509 You can tell the quote type by looking at the first character."
3510 value) ; the characters of the string, including the quotes
3511
3512 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3513 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3514
3515 (defun js2-print-string-node (n i)
3516 (insert (js2-make-pad i)
3517 (js2-node-string n)))
3518
3519 (defstruct (js2-array-node
3520 (:include js2-node)
3521 (:constructor nil)
3522 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3523 (pos js2-ts-cursor)
3524 len
3525 elems)))
3526 "AST node for an array literal."
3527 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3528
3529 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3530 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3531
3532 (defun js2-visit-array-node (n v)
3533 (dolist (e (js2-array-node-elems n))
3534 (js2-visit-ast e v)))
3535
3536 (defun js2-print-array-node (n i)
3537 (insert (js2-make-pad i) "[")
3538 (js2-print-list (js2-array-node-elems n))
3539 (insert "]"))
3540
3541 (defstruct (js2-object-node
3542 (:include js2-node)
3543 (:constructor nil)
3544 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3545 (pos js2-ts-cursor)
3546 len
3547 elems)))
3548 "AST node for an object literal expression.
3549 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3550 the latter represents abbreviation in destructuring expressions."
3551 elems)
3552
3553 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3554 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3555
3556 (defun js2-visit-object-node (n v)
3557 (dolist (e (js2-object-node-elems n))
3558 (js2-visit-ast e v)))
3559
3560 (defun js2-print-object-node (n i)
3561 (insert (js2-make-pad i) "{")
3562 (js2-print-list (js2-object-node-elems n))
3563 (insert "}"))
3564
3565 (defstruct (js2-object-prop-node
3566 (:include js2-infix-node)
3567 (:constructor nil)
3568 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3569 (pos js2-ts-cursor)
3570 len
3571 left
3572 right
3573 op-pos)))
3574 "AST node for an object literal prop:value entry.
3575 The `left' field is the property: a name node, string node or number node.
3576 The `right' field is a `js2-node' representing the initializer value.")
3577
3578 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3579 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3580
3581 (defun js2-print-object-prop-node (n i)
3582 (insert (js2-make-pad i))
3583 (js2-print-ast (js2-object-prop-node-left n) 0)
3584 (insert ":")
3585 (js2-print-ast (js2-object-prop-node-right n) 0))
3586
3587 (defstruct (js2-getter-setter-node
3588 (:include js2-infix-node)
3589 (:constructor nil)
3590 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3591 (pos js2-ts-cursor)
3592 len
3593 left
3594 right)))
3595 "AST node for a getter/setter property in an object literal.
3596 The `left' field is the `js2-name-node' naming the getter/setter prop.
3597 The `right' field is always an anonymous `js2-function-node' with a node
3598 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3599
3600 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3601 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3602
3603 (defun js2-print-getter-setter (n i)
3604 (let ((pad (js2-make-pad i))
3605 (left (js2-getter-setter-node-left n))
3606 (right (js2-getter-setter-node-right n)))
3607 (insert pad)
3608 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3609 (js2-print-ast left 0)
3610 (js2-print-ast right 0)))
3611
3612 (defstruct (js2-prop-get-node
3613 (:include js2-infix-node)
3614 (:constructor nil)
3615 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3616 (pos js2-ts-cursor)
3617 len
3618 left
3619 right)))
3620 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3621
3622 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3623 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3624
3625 (defun js2-visit-prop-get-node (n v)
3626 (js2-visit-ast (js2-prop-get-node-left n) v)
3627 (js2-visit-ast (js2-prop-get-node-right n) v))
3628
3629 (defun js2-print-prop-get-node (n i)
3630 (insert (js2-make-pad i))
3631 (js2-print-ast (js2-prop-get-node-left n) 0)
3632 (insert ".")
3633 (js2-print-ast (js2-prop-get-node-right n) 0))
3634
3635 (defstruct (js2-elem-get-node
3636 (:include js2-node)
3637 (:constructor nil)
3638 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3639 (pos js2-ts-cursor)
3640 len
3641 target
3642 element
3643 lb
3644 rb)))
3645 "AST node for an array index expression such as foo[bar]."
3646 target ; a `js2-node' - the expression preceding the "."
3647 element ; a `js2-node' - the expression in brackets
3648 lb ; position of left-bracket, nil if omitted
3649 rb) ; position of right-bracket, nil if omitted
3650
3651 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3652 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3653
3654 (defun js2-visit-elem-get-node (n v)
3655 (js2-visit-ast (js2-elem-get-node-target n) v)
3656 (js2-visit-ast (js2-elem-get-node-element n) v))
3657
3658 (defun js2-print-elem-get-node (n i)
3659 (insert (js2-make-pad i))
3660 (js2-print-ast (js2-elem-get-node-target n) 0)
3661 (insert "[")
3662 (js2-print-ast (js2-elem-get-node-element n) 0)
3663 (insert "]"))
3664
3665 (defstruct (js2-call-node
3666 (:include js2-node)
3667 (:constructor nil)
3668 (:constructor make-js2-call-node (&key (type js2-CALL)
3669 (pos js2-ts-cursor)
3670 len
3671 target
3672 args
3673 lp
3674 rp)))
3675 "AST node for a JavaScript function call."
3676 target ; a `js2-node' evaluating to the function to call
3677 args ; a lisp list of `js2-node' arguments
3678 lp ; position of open-paren, or nil if missing
3679 rp) ; position of close-paren, or nil if missing
3680
3681 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3682 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3683
3684 (defun js2-visit-call-node (n v)
3685 (js2-visit-ast (js2-call-node-target n) v)
3686 (dolist (arg (js2-call-node-args n))
3687 (js2-visit-ast arg v)))
3688
3689 (defun js2-print-call-node (n i)
3690 (insert (js2-make-pad i))
3691 (js2-print-ast (js2-call-node-target n) 0)
3692 (insert "(")
3693 (js2-print-list (js2-call-node-args n))
3694 (insert ")"))
3695
3696 (defstruct (js2-yield-node
3697 (:include js2-node)
3698 (:constructor nil)
3699 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3700 (pos js2-ts-cursor)
3701 len
3702 value)))
3703 "AST node for yield statement or expression."
3704 value) ; optional: value to be yielded
3705
3706 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3707 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3708
3709 (defun js2-visit-yield-node (n v)
3710 (js2-visit-ast (js2-yield-node-value n) v))
3711
3712 (defun js2-print-yield-node (n i)
3713 (insert (js2-make-pad i))
3714 (insert "yield")
3715 (when (js2-yield-node-value n)
3716 (insert " ")
3717 (js2-print-ast (js2-yield-node-value n) 0)))
3718
3719 (defstruct (js2-paren-node
3720 (:include js2-node)
3721 (:constructor nil)
3722 (:constructor make-js2-paren-node (&key (type js2-LP)
3723 (pos js2-ts-cursor)
3724 len
3725 expr)))
3726 "AST node for a parenthesized expression.
3727 In particular, used when the parens are syntactically optional,
3728 as opposed to required parens such as those enclosing an if-conditional."
3729 expr) ; `js2-node'
3730
3731 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3732 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3733
3734 (defun js2-visit-paren-node (n v)
3735 (js2-visit-ast (js2-paren-node-expr n) v))
3736
3737 (defun js2-print-paren-node (n i)
3738 (insert (js2-make-pad i))
3739 (insert "(")
3740 (js2-print-ast (js2-paren-node-expr n) 0)
3741 (insert ")"))
3742
3743 (defstruct (js2-array-comp-node
3744 (:include js2-scope)
3745 (:constructor nil)
3746 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3747 (pos js2-ts-cursor)
3748 len
3749 result
3750 loops
3751 filter
3752 if-pos
3753 lp
3754 rp)))
3755 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3756 result ; result expression (just after left-bracket)
3757 loops ; a lisp list of `js2-array-comp-loop-node'
3758 filter ; guard/filter expression
3759 if-pos ; buffer pos of 'if' keyword, if present, else nil
3760 lp ; buffer position of if-guard left-paren, or nil if not present
3761 rp) ; buffer position of if-guard right-paren, or nil if not present
3762
3763 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3764 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3765
3766 (defun js2-visit-array-comp-node (n v)
3767 (js2-visit-ast (js2-array-comp-node-result n) v)
3768 (dolist (l (js2-array-comp-node-loops n))
3769 (js2-visit-ast l v))
3770 (js2-visit-ast (js2-array-comp-node-filter n) v))
3771
3772 (defun js2-print-array-comp-node (n i)
3773 (let ((pad (js2-make-pad i))
3774 (result (js2-array-comp-node-result n))
3775 (loops (js2-array-comp-node-loops n))
3776 (filter (js2-array-comp-node-filter n)))
3777 (insert pad "[")
3778 (js2-print-ast result 0)
3779 (dolist (l loops)
3780 (insert " ")
3781 (js2-print-ast l 0))
3782 (when filter
3783 (insert " if (")
3784 (js2-print-ast filter 0))
3785 (insert ")]")))
3786
3787 (defstruct (js2-array-comp-loop-node
3788 (:include js2-for-in-node)
3789 (:constructor nil)
3790 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3791 (pos js2-ts-cursor)
3792 len
3793 iterator
3794 object
3795 in-pos
3796 foreach-p
3797 each-pos
3798 lp
3799 rp)))
3800 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3801
3802 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3803 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3804
3805 (defun js2-visit-array-comp-loop (n v)
3806 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3807 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3808
3809 (defun js2-print-array-comp-loop (n i)
3810 (insert "for (")
3811 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3812 (insert " in ")
3813 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3814 (insert ")"))
3815
3816 (defstruct (js2-empty-expr-node
3817 (:include js2-node)
3818 (:constructor nil)
3819 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3820 (pos js2-token-beg)
3821 len)))
3822 "AST node for an empty expression.")
3823
3824 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3825 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3826
3827 (defstruct (js2-xml-node
3828 (:include js2-block-node)
3829 (:constructor nil)
3830 (:constructor make-js2-xml-node (&key (type js2-XML)
3831 (pos js2-token-beg)
3832 len
3833 kids)))
3834 "AST node for initial parse of E4X literals.
3835 The kids field is a list of XML fragments, each a `js2-string-node' or
3836 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3837
3838 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3839 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3840
3841 (defun js2-print-xml-node (n i)
3842 (dolist (kid (js2-xml-node-kids n))
3843 (js2-print-ast kid i)))
3844
3845 (defstruct (js2-xml-js-expr-node
3846 (:include js2-xml-node)
3847 (:constructor nil)
3848 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3849 (pos js2-ts-cursor)
3850 len
3851 expr)))
3852 "AST node for an embedded JavaScript {expression} in an E4X literal.
3853 The start and end fields correspond to the curly-braces."
3854 expr) ; a `js2-expr-node' of some sort
3855
3856 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3857 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3858
3859 (defun js2-visit-xml-js-expr (n v)
3860 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3861
3862 (defun js2-print-xml-js-expr (n i)
3863 (insert (js2-make-pad i))
3864 (insert "{")
3865 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3866 (insert "}"))
3867
3868 (defstruct (js2-xml-dot-query-node
3869 (:include js2-infix-node)
3870 (:constructor nil)
3871 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3872 (pos js2-ts-cursor)
3873 op-pos
3874 len
3875 left
3876 right
3877 rp)))
3878 "AST node for an E4X foo.(bar) filter expression.
3879 Note that the left-paren is automatically the character immediately
3880 following the dot (.) in the operator. No whitespace is permitted
3881 between the dot and the lp by the scanner."
3882 rp)
3883
3884 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3885 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3886
3887 (defun js2-print-xml-dot-query (n i)
3888 (insert (js2-make-pad i))
3889 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3890 (insert ".(")
3891 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3892 (insert ")"))
3893
3894 (defstruct (js2-xml-ref-node
3895 (:include js2-node)
3896 (:constructor nil)) ; abstract
3897 "Base type for E4X XML attribute-access or property-get expressions.
3898 Such expressions can take a variety of forms. The general syntax has
3899 three parts:
3900
3901 - (optional) an @ (specifying an attribute access)
3902 - (optional) a namespace (a `js2-name-node') and double-colon
3903 - (required) either a `js2-name-node' or a bracketed [expression]
3904
3905 The property-name expressions (examples: ns::name, @name) are
3906 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3907 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3908
3909 This node type (or more specifically, its subclasses) will sometimes
3910 be the right-hand child of a `js2-prop-get-node' or a
3911 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3912 The `js2-xml-ref-node' may also be a standalone primary expression with
3913 no explicit target, which is valid in certain expression contexts such as
3914
3915 company..employee.(@id < 100)
3916
3917 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3918 expression whose parent is a `js2-xml-dot-query-node'."
3919 namespace
3920 at-pos
3921 colon-pos)
3922
3923 (defsubst js2-xml-ref-node-attr-access-p (node)
3924 "Return non-nil if this expression began with an @-token."
3925 (and (numberp (js2-xml-ref-node-at-pos node))
3926 (plusp (js2-xml-ref-node-at-pos node))))
3927
3928 (defstruct (js2-xml-prop-ref-node
3929 (:include js2-xml-ref-node)
3930 (:constructor nil)
3931 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3932 (pos js2-token-beg)
3933 len
3934 propname
3935 namespace
3936 at-pos
3937 colon-pos)))
3938 "AST node for an E4X XML [expr] property-ref expression.
3939 The JavaScript syntax is an optional @, an optional ns::, and a name.
3940
3941 [ '@' ] [ name '::' ] name
3942
3943 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3944 @ns::*, @*::attr, @*::*, and @*.
3945
3946 The node starts at the @ token, if present. Otherwise it starts at the
3947 namespace name. The node bounds extend through the closing right-bracket,
3948 or if it is missing due to a syntax error, through the end of the index
3949 expression."
3950 propname)
3951
3952 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3953 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3954
3955 (defun js2-visit-xml-prop-ref-node (n v)
3956 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3957 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3958
3959 (defun js2-print-xml-prop-ref-node (n i)
3960 (insert (js2-make-pad i))
3961 (if (js2-xml-ref-node-attr-access-p n)
3962 (insert "@"))
3963 (when (js2-xml-prop-ref-node-namespace n)
3964 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3965 (insert "::"))
3966 (if (js2-xml-prop-ref-node-propname n)
3967 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3968
3969 (defstruct (js2-xml-elem-ref-node
3970 (:include js2-xml-ref-node)
3971 (:constructor nil)
3972 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3973 (pos js2-token-beg)
3974 len
3975 expr
3976 lb
3977 rb
3978 namespace
3979 at-pos
3980 colon-pos)))
3981 "AST node for an E4X XML [expr] member-ref expression.
3982 Syntax:
3983
3984 [ '@' ] [ name '::' ] '[' expr ']'
3985
3986 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3987
3988 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3989 is not a legal E4X XML element-ref expression, since it's already used
3990 for standard JavaScript element-get array indexing. Hence, a
3991 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3992 non-nil namespace node, or both.
3993
3994 The node starts at the @ token, if present. Otherwise it starts
3995 at the namespace name. The node bounds extend through the closing
3996 right-bracket, or if it is missing due to a syntax error, through the
3997 end of the index expression."
3998 expr ; the bracketed index expression
3999 lb
4000 rb)
4001
4002 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4003 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4004
4005 (defun js2-visit-xml-elem-ref-node (n v)
4006 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4007 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4008
4009 (defun js2-print-xml-elem-ref-node (n i)
4010 (insert (js2-make-pad i))
4011 (if (js2-xml-ref-node-attr-access-p n)
4012 (insert "@"))
4013 (when (js2-xml-elem-ref-node-namespace n)
4014 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4015 (insert "::"))
4016 (insert "[")
4017 (if (js2-xml-elem-ref-node-expr n)
4018 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4019 (insert "]"))
4020
4021 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4022
4023 (defstruct (js2-xml-start-tag-node
4024 (:include js2-xml-node)
4025 (:constructor nil)
4026 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4027 (pos js2-ts-cursor)
4028 len
4029 name
4030 attrs
4031 kids
4032 empty-p)))
4033 "AST node for an XML start-tag. Not currently used.
4034 The `kids' field is a lisp list of child content nodes."
4035 name ; a `js2-xml-name-node'
4036 attrs ; a lisp list of `js2-xml-attr-node'
4037 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4038
4039 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4040 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4041
4042 (defun js2-visit-xml-start-tag (n v)
4043 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4044 (dolist (attr (js2-xml-start-tag-node-attrs n))
4045 (js2-visit-ast attr v))
4046 (js2-visit-block n v))
4047
4048 (defun js2-print-xml-start-tag (n i)
4049 (insert (js2-make-pad i) "<")
4050 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4051 (when (js2-xml-start-tag-node-attrs n)
4052 (insert " ")
4053 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4054 (insert ">"))
4055
4056 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4057 ;; and add the end-tag to the kids list of the parent as well.
4058 (defstruct (js2-xml-end-tag-node
4059 (:include js2-xml-node)
4060 (:constructor nil)
4061 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4062 (pos js2-ts-cursor)
4063 len
4064 name)))
4065 "AST node for an XML end-tag. Not currently used."
4066 name) ; a `js2-xml-name-node'
4067
4068 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4069 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4070
4071 (defun js2-visit-xml-end-tag (n v)
4072 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4073
4074 (defun js2-print-xml-end-tag (n i)
4075 (insert (js2-make-pad i))
4076 (insert "</")
4077 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4078 (insert ">"))
4079
4080 (defstruct (js2-xml-name-node
4081 (:include js2-xml-node)
4082 (:constructor nil)
4083 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4084 (pos js2-ts-cursor)
4085 len
4086 namespace
4087 kids)))
4088 "AST node for an E4X XML name. Not currently used.
4089 Any XML name can be qualified with a namespace, hence the namespace field.
4090 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4091 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4092 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4093 namespace) ; a `js2-string-node'
4094
4095 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4096 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4097
4098 (defun js2-visit-xml-name-node (n v)
4099 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4100
4101 (defun js2-print-xml-name-node (n i)
4102 (insert (js2-make-pad i))
4103 (when (js2-xml-name-node-namespace n)
4104 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4105 (insert "::"))
4106 (dolist (kid (js2-xml-name-node-kids n))
4107 (js2-print-ast kid 0)))
4108
4109 (defstruct (js2-xml-pi-node
4110 (:include js2-xml-node)
4111 (:constructor nil)
4112 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4113 (pos js2-ts-cursor)
4114 len
4115 name
4116 attrs)))
4117 "AST node for an E4X XML processing instruction. Not currently used."
4118 name ; a `js2-xml-name-node'
4119 attrs) ; a list of `js2-xml-attr-node'
4120
4121 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4122 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4123
4124 (defun js2-visit-xml-pi-node (n v)
4125 (js2-visit-ast (js2-xml-pi-node-name n) v)
4126 (dolist (attr (js2-xml-pi-node-attrs n))
4127 (js2-visit-ast attr v)))
4128
4129 (defun js2-print-xml-pi-node (n i)
4130 (insert (js2-make-pad i) "<?")
4131 (js2-print-ast (js2-xml-pi-node-name n))
4132 (when (js2-xml-pi-node-attrs n)
4133 (insert " ")
4134 (js2-print-list (js2-xml-pi-node-attrs n)))
4135 (insert "?>"))
4136
4137 (defstruct (js2-xml-cdata-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 content)))
4144 "AST node for a CDATA escape section. Not currently used."
4145 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4146
4147 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4148 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4149
4150 (defun js2-visit-xml-cdata-node (n v)
4151 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4152
4153 (defun js2-print-xml-cdata-node (n i)
4154 (insert (js2-make-pad i))
4155 (js2-print-ast (js2-xml-cdata-node-content n)))
4156
4157 (defstruct (js2-xml-attr-node
4158 (:include js2-xml-node)
4159 (:constructor nil)
4160 (:constructor make-js2-attr-node (&key (type js2-XML)
4161 (pos js2-ts-cursor)
4162 len
4163 name
4164 value
4165 eq-pos
4166 quote-type)))
4167 "AST node representing a foo='bar' XML attribute value. Not yet used."
4168 name ; a `js2-xml-name-node'
4169 value ; a `js2-xml-name-node'
4170 eq-pos ; buffer position of "=" sign
4171 quote-type) ; 'single or 'double
4172
4173 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4174 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4175
4176 (defun js2-visit-xml-attr-node (n v)
4177 (js2-visit-ast (js2-xml-attr-node-name n) v)
4178 (js2-visit-ast (js2-xml-attr-node-value n) v))
4179
4180 (defun js2-print-xml-attr-node (n i)
4181 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4182 "'"
4183 "\"")))
4184 (insert (js2-make-pad i))
4185 (js2-print-ast (js2-xml-attr-node-name n) 0)
4186 (insert "=" quote)
4187 (js2-print-ast (js2-xml-attr-node-value n) 0)
4188 (insert quote)))
4189
4190 (defstruct (js2-xml-text-node
4191 (:include js2-xml-node)
4192 (:constructor nil)
4193 (:constructor make-js2-text-node (&key (type js2-XML)
4194 (pos js2-ts-cursor)
4195 len
4196 content)))
4197 "AST node for an E4X XML text node. Not currently used."
4198 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4199
4200 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4201 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4202
4203 (defun js2-visit-xml-text-node (n v)
4204 (js2-visit-ast (js2-xml-text-node-content n) v))
4205
4206 (defun js2-print-xml-text-node (n i)
4207 (insert (js2-make-pad i))
4208 (dolist (kid (js2-xml-text-node-content n))
4209 (js2-print-ast kid)))
4210
4211 (defstruct (js2-xml-comment-node
4212 (:include js2-xml-node)
4213 (:constructor nil)
4214 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4215 (pos js2-ts-cursor)
4216 len)))
4217 "AST node for E4X XML comment. Not currently used.")
4218
4219 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4221
4222 (defun js2-print-xml-comment (n i)
4223 (insert (js2-make-pad i)
4224 (js2-node-string n)))
4225
4226 ;;; Node utilities
4227
4228 (defsubst js2-node-line (n)
4229 "Fetch the source line number at the start of node N.
4230 This is O(n) in the length of the source buffer; use prudently."
4231 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4232
4233 (defsubst js2-block-node-kid (n i)
4234 "Return child I of node N, or nil if there aren't that many."
4235 (nth i (js2-block-node-kids n)))
4236
4237 (defsubst js2-block-node-first (n)
4238 "Return first child of block node N, or nil if there is none."
4239 (first (js2-block-node-kids n)))
4240
4241 (defun js2-node-root (n)
4242 "Return the root of the AST containing N.
4243 If N has no parent pointer, returns N."
4244 (let ((parent (js2-node-parent n)))
4245 (if parent
4246 (js2-node-root parent)
4247 n)))
4248
4249 (defun js2-node-position-in-parent (node &optional parent)
4250 "Return the position of NODE in parent's block-kids list.
4251 PARENT can be supplied if known. Positioned returned is zero-indexed.
4252 Returns 0 if NODE is not a child of a block statement, or if NODE
4253 is not a statement node."
4254 (let ((p (or parent (js2-node-parent node)))
4255 (i 0))
4256 (if (not (js2-block-node-p p))
4257 i
4258 (or (js2-position node (js2-block-node-kids p))
4259 0))))
4260
4261 (defsubst js2-node-short-name (n)
4262 "Return the short name of node N as a string, e.g. `js2-if-node'."
4263 (substring (symbol-name (aref n 0))
4264 (length "cl-struct-")))
4265
4266 (defsubst js2-node-child-list (node)
4267 "Return the child list for NODE, a lisp list of nodes.
4268 Works for block nodes, array nodes, obj literals, funarg lists,
4269 var decls and try nodes (for catch clauses). Note that you should call
4270 `js2-block-node-kids' on the function body for the body statements.
4271 Returns nil for zero-length child lists or unsupported nodes."
4272 (cond
4273 ((js2-function-node-p node)
4274 (js2-function-node-params node))
4275 ((js2-block-node-p node)
4276 (js2-block-node-kids node))
4277 ((js2-try-node-p node)
4278 (js2-try-node-catch-clauses node))
4279 ((js2-array-node-p node)
4280 (js2-array-node-elems node))
4281 ((js2-object-node-p node)
4282 (js2-object-node-elems node))
4283 ((js2-call-node-p node)
4284 (js2-call-node-args node))
4285 ((js2-new-node-p node)
4286 (js2-new-node-args node))
4287 ((js2-var-decl-node-p node)
4288 (js2-var-decl-node-kids node))
4289 (t
4290 nil)))
4291
4292 (defsubst js2-node-set-child-list (node kids)
4293 "Set the child list for NODE to KIDS."
4294 (cond
4295 ((js2-function-node-p node)
4296 (setf (js2-function-node-params node) kids))
4297 ((js2-block-node-p node)
4298 (setf (js2-block-node-kids node) kids))
4299 ((js2-try-node-p node)
4300 (setf (js2-try-node-catch-clauses node) kids))
4301 ((js2-array-node-p node)
4302 (setf (js2-array-node-elems node) kids))
4303 ((js2-object-node-p node)
4304 (setf (js2-object-node-elems node) kids))
4305 ((js2-call-node-p node)
4306 (setf (js2-call-node-args node) kids))
4307 ((js2-new-node-p node)
4308 (setf (js2-new-node-args node) kids))
4309 ((js2-var-decl-node-p node)
4310 (setf (js2-var-decl-node-kids node) kids))
4311 (t
4312 (error "Unsupported node type: %s" (js2-node-short-name node))))
4313 kids)
4314
4315 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4316 (defconst js2-paren-expr-nodes
4317 '(cl-struct-js2-array-comp-loop-node
4318 cl-struct-js2-array-comp-node
4319 cl-struct-js2-call-node
4320 cl-struct-js2-catch-node
4321 cl-struct-js2-do-node
4322 cl-struct-js2-elem-get-node
4323 cl-struct-js2-for-in-node
4324 cl-struct-js2-for-node
4325 cl-struct-js2-function-node
4326 cl-struct-js2-if-node
4327 cl-struct-js2-let-node
4328 cl-struct-js2-new-node
4329 cl-struct-js2-paren-node
4330 cl-struct-js2-switch-node
4331 cl-struct-js2-while-node
4332 cl-struct-js2-with-node
4333 cl-struct-js2-xml-dot-query-node)
4334 "Node types that can have a parenthesized child expression.
4335 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4336
4337 (defsubst js2-paren-expr-node-p (node)
4338 "Return t for nodes that typically have a parenthesized child expression.
4339 Useful for computing the indentation anchors for arg-lists and conditions.
4340 Note that it may return a false positive, for instance when NODE is
4341 a `js2-new-node' and there are no arguments or parentheses."
4342 (memq (aref node 0) js2-paren-expr-nodes))
4343
4344 ;; Fake polymorphism... yech.
4345 (defsubst js2-node-lp (node)
4346 "Return relative left-paren position for NODE, if applicable.
4347 For `js2-elem-get-node' structs, returns left-bracket position.
4348 Note that the position may be nil in the case of a parse error."
4349 (cond
4350 ((js2-elem-get-node-p node)
4351 (js2-elem-get-node-lb node))
4352 ((js2-loop-node-p node)
4353 (js2-loop-node-lp node))
4354 ((js2-function-node-p node)
4355 (js2-function-node-lp node))
4356 ((js2-if-node-p node)
4357 (js2-if-node-lp node))
4358 ((js2-new-node-p node)
4359 (js2-new-node-lp node))
4360 ((js2-call-node-p node)
4361 (js2-call-node-lp node))
4362 ((js2-paren-node-p node)
4363 (js2-node-pos node))
4364 ((js2-switch-node-p node)
4365 (js2-switch-node-lp node))
4366 ((js2-catch-node-p node)
4367 (js2-catch-node-lp node))
4368 ((js2-let-node-p node)
4369 (js2-let-node-lp node))
4370 ((js2-array-comp-node-p node)
4371 (js2-array-comp-node-lp node))
4372 ((js2-with-node-p node)
4373 (js2-with-node-lp node))
4374 ((js2-xml-dot-query-node-p node)
4375 (1+ (js2-infix-node-op-pos node)))
4376 (t
4377 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4378
4379 ;; Fake polymorphism... blech.
4380 (defsubst js2-node-rp (node)
4381 "Return relative right-paren position for NODE, if applicable.
4382 For `js2-elem-get-node' structs, returns right-bracket position.
4383 Note that the position may be nil in the case of a parse error."
4384 (cond
4385 ((js2-elem-get-node-p node)
4386 (js2-elem-get-node-lb node))
4387 ((js2-loop-node-p node)
4388 (js2-loop-node-rp node))
4389 ((js2-function-node-p node)
4390 (js2-function-node-rp node))
4391 ((js2-if-node-p node)
4392 (js2-if-node-rp node))
4393 ((js2-new-node-p node)
4394 (js2-new-node-rp node))
4395 ((js2-call-node-p node)
4396 (js2-call-node-rp node))
4397 ((js2-paren-node-p node)
4398 (+ (js2-node-pos node) (js2-node-len node)))
4399 ((js2-switch-node-p node)
4400 (js2-switch-node-rp node))
4401 ((js2-catch-node-p node)
4402 (js2-catch-node-rp node))
4403 ((js2-let-node-p node)
4404 (js2-let-node-rp node))
4405 ((js2-array-comp-node-p node)
4406 (js2-array-comp-node-rp node))
4407 ((js2-with-node-p node)
4408 (js2-with-node-rp node))
4409 ((js2-xml-dot-query-node-p node)
4410 (1+ (js2-xml-dot-query-node-rp node)))
4411 (t
4412 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4413
4414 (defsubst js2-node-first-child (node)
4415 "Returns the first element of `js2-node-child-list' for NODE."
4416 (car (js2-node-child-list node)))
4417
4418 (defsubst js2-node-last-child (node)
4419 "Returns the last element of `js2-node-last-child' for NODE."
4420 (car (last (js2-node-child-list node))))
4421
4422 (defun js2-node-prev-sibling (node)
4423 "Return the previous statement in parent.
4424 Works for parents supported by `js2-node-child-list'.
4425 Returns nil if NODE is not in the parent, or PARENT is
4426 not a supported node, or if NODE is the first child."
4427 (let* ((p (js2-node-parent node))
4428 (kids (js2-node-child-list p))
4429 (sib (car kids)))
4430 (while (and kids
4431 (not (eq node (cadr kids))))
4432 (setq kids (cdr kids)
4433 sib (car kids)))
4434 sib))
4435
4436 (defun js2-node-next-sibling (node)
4437 "Return the next statement in parent block.
4438 Returns nil if NODE is not in the block, or PARENT is not
4439 a block node, or if NODE is the last statement."
4440 (let* ((p (js2-node-parent node))
4441 (kids (js2-node-child-list p)))
4442 (while (and kids
4443 (not (eq node (car kids))))
4444 (setq kids (cdr kids)))
4445 (cadr kids)))
4446
4447 (defun js2-node-find-child-before (pos parent &optional after)
4448 "Find the last child that starts before POS in parent.
4449 If AFTER is non-nil, returns first child starting after POS.
4450 POS is an absolute buffer position. PARENT is any node
4451 supported by `js2-node-child-list'.
4452 Returns nil if no applicable child is found."
4453 (let ((kids (if (js2-function-node-p parent)
4454 (js2-block-node-kids (js2-function-node-body parent))
4455 (js2-node-child-list parent)))
4456 (beg (if (js2-function-node-p parent)
4457 (js2-node-abs-pos (js2-function-node-body parent))
4458 (js2-node-abs-pos parent)))
4459 kid
4460 result
4461 fn
4462 (continue t))
4463 (setq fn (if after '>= '<))
4464 (while (and kids continue)
4465 (setq kid (car kids))
4466 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4467 (setq result kid
4468 continue (if after nil t))
4469 (setq continue (if after t nil)))
4470 (setq kids (cdr kids)))
4471 result))
4472
4473 (defun js2-node-find-child-after (pos parent)
4474 "Find first child that starts after POS in parent.
4475 POS is an absolute buffer position. PARENT is any node
4476 supported by `js2-node-child-list'.
4477 Returns nil if no applicable child is found."
4478 (js2-node-find-child-before pos parent 'after))
4479
4480 (defun js2-node-replace-child (pos parent new-node)
4481 "Replace node at index POS in PARENT with NEW-NODE.
4482 Only works for parents supported by `js2-node-child-list'."
4483 (let ((kids (js2-node-child-list parent))
4484 (i 0))
4485 (while (< i pos)
4486 (setq kids (cdr kids)
4487 i (1+ i)))
4488 (setcar kids new-node)
4489 (js2-node-add-children parent new-node)))
4490
4491 (defun js2-node-buffer (n)
4492 "Return the buffer associated with AST N.
4493 Returns nil if the buffer is not set as a property on the root
4494 node, or if parent links were not recorded during parsing."
4495 (let ((root (js2-node-root n)))
4496 (and root
4497 (js2-ast-root-p root)
4498 (js2-ast-root-buffer root))))
4499
4500 (defsubst js2-block-node-push (n kid)
4501 "Push js2-node KID onto the end of js2-block-node N's child list.
4502 KID is always added to the -end- of the kids list.
4503 Function also calls `js2-node-add-children' to add the parent link."
4504 (let ((kids (js2-node-child-list n)))
4505 (if kids
4506 (setcdr kids (nconc (cdr kids) (list kid)))
4507 (js2-node-set-child-list n (list kid)))
4508 (js2-node-add-children n kid)))
4509
4510 (defun js2-node-string (node)
4511 (let ((buf (js2-node-buffer node))
4512 pos)
4513 (unless buf
4514 (error "No buffer available for node %s" node))
4515 (with-current-buffer buf
4516 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4517 (+ pos (js2-node-len node))))))
4518
4519 ;; Container for storing the node we're looking for in a traversal.
4520 (js2-deflocal js2-discovered-node nil)
4521
4522 ;; Keep track of absolute node position during traversals.
4523 (js2-deflocal js2-visitor-offset nil)
4524
4525 (js2-deflocal js2-node-search-point nil)
4526
4527 (when js2-mode-dev-mode-p
4528 (defun js2-find-node-at-point ()
4529 (interactive)
4530 (let ((node (js2-node-at-point)))
4531 (message "%s" (or node "No node found at point"))))
4532 (defun js2-node-name-at-point ()
4533 (interactive)
4534 (let ((node (js2-node-at-point)))
4535 (message "%s" (if node
4536 (js2-node-short-name node)
4537 "No node found at point.")))))
4538
4539 (defun js2-node-at-point (&optional pos skip-comments)
4540 "Return AST node at POS, a buffer position, defaulting to current point.
4541 The `js2-mode-ast' variable must be set to the current parse tree.
4542 Signals an error if the AST (`js2-mode-ast') is nil.
4543 Always returns a node - if it can't find one, it returns the root.
4544 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4545 (let ((ast js2-mode-ast)
4546 result)
4547 (unless ast
4548 (error "No JavaScript AST available"))
4549 ;; Look through comments first, since they may be inside nodes that
4550 ;; would otherwise report a match.
4551 (setq pos (or pos (point))
4552 result (if (> pos (js2-node-abs-end ast))
4553 ast
4554 (if (not skip-comments)
4555 (js2-comment-at-point pos))))
4556 (unless result
4557 (setq js2-discovered-node nil
4558 js2-visitor-offset 0
4559 js2-node-search-point pos)
4560 (unwind-protect
4561 (catch 'js2-visit-done
4562 (js2-visit-ast ast #'js2-node-at-point-visitor))
4563 (setq js2-visitor-offset nil
4564 js2-node-search-point nil))
4565 (setq result js2-discovered-node))
4566 ;; may have found a comment beyond end of last child node,
4567 ;; since visiting the ast-root looks at the comment-list last.
4568 (if (and skip-comments
4569 (js2-comment-node-p result))
4570 (setq result nil))
4571 (or result js2-mode-ast)))
4572
4573 (defun js2-node-at-point-visitor (node end-p)
4574 (let ((rel-pos (js2-node-pos node))
4575 abs-pos
4576 abs-end
4577 (point js2-node-search-point))
4578 (cond
4579 (end-p
4580 ;; this evaluates to a non-nil return value, even if it's zero
4581 (decf js2-visitor-offset rel-pos))
4582 ;; we already looked for comments before visiting, and don't want them now
4583 ((js2-comment-node-p node)
4584 nil)
4585 (t
4586 (setq abs-pos (incf js2-visitor-offset rel-pos)
4587 ;; we only want to use the node if the point is before
4588 ;; the last character position in the node, so we decrement
4589 ;; the absolute end by 1.
4590 abs-end (+ abs-pos (js2-node-len node) -1))
4591 (cond
4592 ;; If this node starts after search-point, stop the search.
4593 ((> abs-pos point)
4594 (throw 'js2-visit-done nil))
4595 ;; If this node ends before the search-point, don't check kids.
4596 ((> point abs-end)
4597 nil)
4598 (t
4599 ;; Otherwise point is within this node, possibly in a child.
4600 (setq js2-discovered-node node)
4601 t)))))) ; keep processing kids to look for more specific match
4602
4603 (defsubst js2-block-comment-p (node)
4604 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4605 (and (js2-comment-node-p node)
4606 (memq (js2-comment-node-format node) '(jsdoc block))))
4607
4608 ;; TODO: put the comments in a vector and binary-search them instead
4609 (defun js2-comment-at-point (&optional pos)
4610 "Look through scanned comment nodes for one containing POS.
4611 POS is a buffer position that defaults to current point.
4612 Function returns nil if POS was not in any comment node."
4613 (let ((ast js2-mode-ast)
4614 (x (or pos (point)))
4615 beg
4616 end)
4617 (unless ast
4618 (error "No JavaScript AST available"))
4619 (catch 'done
4620 ;; Comments are stored in lexical order.
4621 (dolist (comment (js2-ast-root-comments ast) nil)
4622 (setq beg (js2-node-abs-pos comment)
4623 end (+ beg (js2-node-len comment)))
4624 (if (and (>= x beg)
4625 (<= x end))
4626 (throw 'done comment))))))
4627
4628 (defun js2-mode-find-parent-fn (node)
4629 "Find function enclosing NODE.
4630 Returns nil if NODE is not inside a function."
4631 (setq node (js2-node-parent node))
4632 (while (and node (not (js2-function-node-p node)))
4633 (setq node (js2-node-parent node)))
4634 (and (js2-function-node-p node) node))
4635
4636 (defun js2-mode-find-enclosing-fn (node)
4637 "Find function or root enclosing NODE."
4638 (if (js2-ast-root-p node)
4639 node
4640 (setq node (js2-node-parent node))
4641 (while (not (or (js2-ast-root-p node)
4642 (js2-function-node-p node)))
4643 (setq node (js2-node-parent node)))
4644 node))
4645
4646 (defun js2-mode-find-enclosing-node (beg end)
4647 "Find script or function fully enclosing BEG and END."
4648 (let ((node (js2-node-at-point beg))
4649 pos
4650 (continue t))
4651 (while continue
4652 (if (or (js2-ast-root-p node)
4653 (and (js2-function-node-p node)
4654 (<= (setq pos (js2-node-abs-pos node)) beg)
4655 (>= (+ pos (js2-node-len node)) end)))
4656 (setq continue nil)
4657 (setq node (js2-node-parent node))))
4658 node))
4659
4660 (defun js2-node-parent-script-or-fn (node)
4661 "Find script or function immediately enclosing NODE.
4662 If NODE is the ast-root, returns nil."
4663 (if (js2-ast-root-p node)
4664 nil
4665 (setq node (js2-node-parent node))
4666 (while (and node (not (or (js2-function-node-p node)
4667 (js2-script-node-p node))))
4668 (setq node (js2-node-parent node)))
4669 node))
4670
4671 (defsubst js2-nested-function-p (node)
4672 "Return t if NODE is a nested function, or is inside a nested function."
4673 (unless (js2-ast-root-p node)
4674 (js2-function-node-p (if (js2-function-node-p node)
4675 (js2-node-parent-script-or-fn node)
4676 (js2-node-parent-script-or-fn
4677 (js2-node-parent-script-or-fn node))))))
4678
4679 (defsubst js2-function-param-node-p (node)
4680 "Return non-nil if NODE is a param node of a `js2-function-node'."
4681 (let ((parent (js2-node-parent node)))
4682 (and parent
4683 (js2-function-node-p parent)
4684 (memq node (js2-function-node-params parent)))))
4685
4686 (defsubst js2-mode-shift-kids (kids start offset)
4687 (dolist (kid kids)
4688 (if (> (js2-node-pos kid) start)
4689 (incf (js2-node-pos kid) offset))))
4690
4691 (defsubst js2-mode-shift-children (parent start offset)
4692 "Update start-positions of all children of PARENT beyond START."
4693 (let ((root (js2-node-root parent)))
4694 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4695 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4696
4697 (defsubst js2-node-is-descendant (node ancestor)
4698 "Return t if NODE is a descendant of ANCESTOR."
4699 (while (and node
4700 (not (eq node ancestor)))
4701 (setq node (js2-node-parent node)))
4702 node)
4703
4704 ;;; visitor infrastructure
4705
4706 (defun js2-visit-none (node callback)
4707 "Visitor for AST node that have no node children."
4708 nil)
4709
4710 (defun js2-print-none (node indent)
4711 "Visitor for AST node with no printed representation.")
4712
4713 (defun js2-print-body (node indent)
4714 "Print a statement, or a block without braces."
4715 (if (js2-block-node-p node)
4716 (dolist (kid (js2-block-node-kids node))
4717 (js2-print-ast kid indent))
4718 (js2-print-ast node indent)))
4719
4720 (defun js2-print-list (args &optional delimiter)
4721 (loop with len = (length args)
4722 for arg in args
4723 for count from 1
4724 do
4725 (js2-print-ast arg 0)
4726 (if (< count len)
4727 (insert (or delimiter ", ")))))
4728
4729 (defun js2-print-tree (ast)
4730 "Prints an AST to the current buffer.
4731 Makes `js2-ast-parent-nodes' available to the printer functions."
4732 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4733 (js2-print-ast ast)))
4734
4735 (defun js2-print-ast (node &optional indent)
4736 "Helper function for printing AST nodes.
4737 Requires `js2-ast-parent-nodes' to be non-nil.
4738 You should use `js2-print-tree' instead of this function."
4739 (let ((printer (get (aref node 0) 'js2-printer))
4740 (i (or indent 0))
4741 (pos (js2-node-abs-pos node)))
4742 ;; TODO: wedge comments in here somewhere
4743 (if printer
4744 (funcall printer node i))))
4745
4746 (defconst js2-side-effecting-tokens
4747 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4748 (dolist (tt (list js2-ASSIGN
4749 js2-ASSIGN_ADD
4750 js2-ASSIGN_BITAND
4751 js2-ASSIGN_BITOR
4752 js2-ASSIGN_BITXOR
4753 js2-ASSIGN_DIV
4754 js2-ASSIGN_LSH
4755 js2-ASSIGN_MOD
4756 js2-ASSIGN_MUL
4757 js2-ASSIGN_RSH
4758 js2-ASSIGN_SUB
4759 js2-ASSIGN_URSH
4760 js2-BLOCK
4761 js2-BREAK
4762 js2-CALL
4763 js2-CATCH
4764 js2-CATCH_SCOPE
4765 js2-CONST
4766 js2-CONTINUE
4767 js2-DEBUGGER
4768 js2-DEC
4769 js2-DELPROP
4770 js2-DEL_REF
4771 js2-DO
4772 js2-ELSE
4773 js2-EMPTY
4774 js2-ENTERWITH
4775 js2-EXPORT
4776 js2-EXPR_RESULT
4777 js2-FINALLY
4778 js2-FOR
4779 js2-FUNCTION
4780 js2-GOTO
4781 js2-IF
4782 js2-IFEQ
4783 js2-IFNE
4784 js2-IMPORT
4785 js2-INC
4786 js2-JSR
4787 js2-LABEL
4788 js2-LEAVEWITH
4789 js2-LET
4790 js2-LETEXPR
4791 js2-LOCAL_BLOCK
4792 js2-LOOP
4793 js2-NEW
4794 js2-REF_CALL
4795 js2-RETHROW
4796 js2-RETURN
4797 js2-RETURN_RESULT
4798 js2-SEMI
4799 js2-SETELEM
4800 js2-SETELEM_OP
4801 js2-SETNAME
4802 js2-SETPROP
4803 js2-SETPROP_OP
4804 js2-SETVAR
4805 js2-SET_REF
4806 js2-SET_REF_OP
4807 js2-SWITCH
4808 js2-TARGET
4809 js2-THROW
4810 js2-TRY
4811 js2-VAR
4812 js2-WHILE
4813 js2-WITH
4814 js2-WITHEXPR
4815 js2-YIELD))
4816 (aset tokens tt t))
4817 (if js2-instanceof-has-side-effects
4818 (aset tokens js2-INSTANCEOF t))
4819 tokens))
4820
4821 (defun js2-node-has-side-effects (node)
4822 "Return t if NODE has side effects."
4823 (when node ; makes it easier to handle malformed expressions
4824 (let ((tt (js2-node-type node)))
4825 (cond
4826 ;; This doubtless needs some work, since EXPR_VOID is used
4827 ;; in several ways in Rhino, and I may not have caught them all.
4828 ;; I'll wait for people to notice incorrect warnings.
4829 ((and (= tt js2-EXPR_VOID)
4830 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4831 (let ((expr (js2-expr-stmt-node-expr node)))
4832 (or (js2-node-has-side-effects expr)
4833 (when (js2-string-node-p expr)
4834 (string= "use strict" (js2-string-node-value expr))))))
4835 ((= tt js2-COMMA)
4836 (js2-node-has-side-effects (js2-infix-node-right node)))
4837 ((or (= tt js2-AND)
4838 (= tt js2-OR))
4839 (or (js2-node-has-side-effects (js2-infix-node-right node))
4840 (js2-node-has-side-effects (js2-infix-node-left node))))
4841 ((= tt js2-HOOK)
4842 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4843 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4844 ((js2-paren-node-p node)
4845 (js2-node-has-side-effects (js2-paren-node-expr node)))
4846 ((= tt js2-ERROR) ; avoid cascaded error messages
4847 nil)
4848 (t
4849 (aref js2-side-effecting-tokens tt))))))
4850
4851 (defun js2-member-expr-leftmost-name (node)
4852 "For an expr such as foo.bar.baz, return leftmost node foo.
4853 NODE is any `js2-node' object. If it represents a member expression,
4854 which is any sequence of property gets, element-gets, function calls,
4855 or xml descendants/filter operators, then we look at the lexically
4856 leftmost (first) node in the chain. If it is a name-node we return it.
4857 Note that NODE can be a raw name-node and it will be returned as well.
4858 If NODE is not a name-node or member expression, or if it is a member
4859 expression whose leftmost target is not a name node, returns nil."
4860 (let ((continue t)
4861 result)
4862 (while (and continue (not result))
4863 (cond
4864 ((js2-name-node-p node)
4865 (setq result node))
4866 ((js2-prop-get-node-p node)
4867 (setq node (js2-prop-get-node-left node)))
4868 ;; TODO: handle call-nodes, xml-nodes, others?
4869 (t
4870 (setq continue nil))))
4871 result))
4872
4873 (defconst js2-stmt-node-types
4874 (list js2-BLOCK
4875 js2-BREAK
4876 js2-CONTINUE
4877 js2-DEFAULT ; e4x "default xml namespace" statement
4878 js2-DO
4879 js2-EXPR_RESULT
4880 js2-EXPR_VOID
4881 js2-FOR
4882 js2-IF
4883 js2-RETURN
4884 js2-SWITCH
4885 js2-THROW
4886 js2-TRY
4887 js2-WHILE
4888 js2-WITH)
4889 "Node types that only appear in statement contexts.
4890 The list does not include nodes that always appear as the child
4891 of another specific statement type, such as switch-cases,
4892 catch and finally blocks, and else-clauses. The list also excludes
4893 nodes like yield, let and var, which may appear in either expression
4894 or statement context, and in the latter context always have a
4895 `js2-expr-stmt-node' parent. Finally, the list does not include
4896 functions or scripts, which are treated separately from statements
4897 by the JavaScript parser and runtime.")
4898
4899 (defun js2-stmt-node-p (node)
4900 "Heuristic for figuring out if NODE is a statement.
4901 Some node types can appear in either an expression context or a
4902 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4903 For these node types in a statement context, the parent will be a
4904 `js2-expr-stmt-node'.
4905 Functions aren't included in the check."
4906 (memq (js2-node-type node) js2-stmt-node-types))
4907
4908 (defsubst js2-mode-find-first-stmt (node)
4909 "Search upward starting from NODE looking for a statement.
4910 For purposes of this function, a `js2-function-node' counts."
4911 (while (not (or (js2-stmt-node-p node)
4912 (js2-function-node-p node)))
4913 (setq node (js2-node-parent node)))
4914 node)
4915
4916 (defun js2-node-parent-stmt (node)
4917 "Return the node's first ancestor that is a statement.
4918 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4919 appearing in a statement context will have a parent that is a
4920 `js2-expr-stmt-node' that will be returned by this function."
4921 (let ((parent (js2-node-parent node)))
4922 (if (or (null parent)
4923 (js2-stmt-node-p parent)
4924 (and (js2-function-node-p parent)
4925 (not (eq (js2-function-node-form parent)
4926 'FUNCTION_EXPRESSION))))
4927 parent
4928 (js2-node-parent-stmt parent))))
4929
4930 ;; In the Mozilla Rhino sources, Roshan James writes:
4931 ;; Does consistent-return analysis on the function body when strict mode is
4932 ;; enabled.
4933 ;;
4934 ;; function (x) { return (x+1) }
4935 ;;
4936 ;; is ok, but
4937 ;;
4938 ;; function (x) { if (x < 0) return (x+1); }
4939 ;;
4940 ;; is not because the function can potentially return a value when the
4941 ;; condition is satisfied and if not, the function does not explicitly
4942 ;; return a value.
4943 ;;
4944 ;; This extends to checking mismatches such as "return" and "return <value>"
4945 ;; used in the same function. Warnings are not emitted if inconsistent
4946 ;; returns exist in code that can be statically shown to be unreachable.
4947 ;; Ex.
4948 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4949 ;;
4950 ;; emits no warning. However if the loop had a break statement, then a
4951 ;; warning would be emitted.
4952 ;;
4953 ;; The consistency analysis looks at control structures such as loops, ifs,
4954 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4955 ;; warns the user about an inconsistent set of termination possibilities.
4956 ;;
4957 ;; These flags enumerate the possible ways a statement/function can
4958 ;; terminate. These flags are used by endCheck() and by the Parser to
4959 ;; detect inconsistent return usage.
4960 ;;
4961 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4962 ;; able to execute (example: throw, continue)
4963 ;;
4964 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4965 ;; next one. Statement such as return dont. A compound statement may have
4966 ;; some branch that drops off control to the next statement.
4967 ;;
4968 ;; END_RETURNS indicates that the statement can return with no value.
4969 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4970 ;;
4971 ;; A compound statement such as
4972 ;; if (condition) {
4973 ;; return value;
4974 ;; }
4975 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4976
4977 (defconst js2-END_UNREACHED 0)
4978 (defconst js2-END_DROPS_OFF 1)
4979 (defconst js2-END_RETURNS 2)
4980 (defconst js2-END_RETURNS_VALUE 4)
4981 (defconst js2-END_YIELDS 8)
4982
4983 (defun js2-has-consistent-return-usage (node)
4984 "Check that every return usage in a function body is consistent.
4985 Returns t if the function satisfies strict mode requirement."
4986 (let ((n (js2-end-check node)))
4987 ;; either it doesn't return a value in any branch...
4988 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4989 ;; or it returns a value (or is unreached) at every branch
4990 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4991 js2-END_RETURNS
4992 js2-END_YIELDS)))))
4993
4994 (defun js2-end-check-if (node)
4995 "Returns in the then and else blocks must be consistent with each other.
4996 If there is no else block, then the return statement can fall through.
4997 Returns logical OR of END_* flags"
4998 (let ((th (js2-if-node-then-part node))
4999 (el (js2-if-node-else-part node)))
5000 (if (null th)
5001 js2-END_UNREACHED
5002 (logior (js2-end-check th) (if el
5003 (js2-end-check el)
5004 js2-END_DROPS_OFF)))))
5005
5006 (defun js2-end-check-switch (node)
5007 "Consistency of return statements is checked between the case statements.
5008 If there is no default, then the switch can fall through. If there is a
5009 default, we check to see if all code paths in the default return or if
5010 there is a code path that can fall through.
5011 Returns logical OR of END_* flags."
5012 (let ((rv js2-END_UNREACHED)
5013 default-case)
5014 ;; examine the cases
5015 (catch 'break
5016 (dolist (c (js2-switch-node-cases node))
5017 (if (js2-case-node-expr c)
5018 (js2-set-flag rv (js2-end-check-block c))
5019 (setq default-case c)
5020 (throw 'break nil))))
5021 ;; we don't care how the cases drop into each other
5022 (js2-clear-flag rv js2-END_DROPS_OFF)
5023 ;; examine the default
5024 (js2-set-flag rv (if default-case
5025 (js2-end-check default-case)
5026 js2-END_DROPS_OFF))
5027 rv))
5028
5029 (defun js2-end-check-try (node)
5030 "If the block has a finally, return consistency is checked in the
5031 finally block. If all code paths in the finally return, then the
5032 returns in the try-catch blocks don't matter. If there is a code path
5033 that does not return or if there is no finally block, the returns
5034 of the try and catch blocks are checked for mismatch.
5035 Returns logical OR of END_* flags."
5036 (let ((finally (js2-try-node-finally-block node))
5037 rv)
5038 ;; check the finally if it exists
5039 (setq rv (if finally
5040 (js2-end-check (js2-finally-node-body finally))
5041 js2-END_DROPS_OFF))
5042 ;; If the finally block always returns, then none of the returns
5043 ;; in the try or catch blocks matter.
5044 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5045 (js2-clear-flag rv js2-END_DROPS_OFF)
5046 ;; examine the try block
5047 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5048 ;; check each catch block
5049 (dolist (cb (js2-try-node-catch-clauses node))
5050 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5051 rv))
5052
5053 (defun js2-end-check-loop (node)
5054 "Return statement in the loop body must be consistent. The default
5055 assumption for any kind of a loop is that it will eventually terminate.
5056 The only exception is a loop with a constant true condition. Code that
5057 follows such a loop is examined only if one can statically determine
5058 that there is a break out of the loop.
5059
5060 for(... ; ... ; ...) {}
5061 for(... in ... ) {}
5062 while(...) { }
5063 do { } while(...)
5064
5065 Returns logical OR of END_* flags."
5066 (let ((rv (js2-end-check (js2-loop-node-body node)))
5067 (condition (cond
5068 ((js2-while-node-p node)
5069 (js2-while-node-condition node))
5070 ((js2-do-node-p node)
5071 (js2-do-node-condition node))
5072 ((js2-for-node-p node)
5073 (js2-for-node-condition node)))))
5074
5075 ;; check to see if the loop condition is always true
5076 (if (and condition
5077 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5078 (js2-clear-flag rv js2-END_DROPS_OFF))
5079
5080 ;; look for effect of breaks
5081 (js2-set-flag rv (js2-node-get-prop node
5082 'CONTROL_BLOCK_PROP
5083 js2-END_UNREACHED))
5084 rv))
5085
5086 (defun js2-end-check-block (node)
5087 "A general block of code is examined statement by statement.
5088 If any statement (even a compound one) returns in all branches, then
5089 subsequent statements are not examined.
5090 Returns logical OR of END_* flags."
5091 (let* ((rv js2-END_DROPS_OFF)
5092 (kids (js2-block-node-kids node))
5093 (n (car kids)))
5094 ;; Check each statment. If the statement can continue onto the next
5095 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5096 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5097 (js2-clear-flag rv js2-END_DROPS_OFF)
5098 (js2-set-flag rv (js2-end-check n))
5099 (setq kids (cdr kids)
5100 n (car kids)))
5101 rv))
5102
5103 (defun js2-end-check-label (node)
5104 "A labeled statement implies that there may be a break to the label.
5105 The function processes the labeled statement and then checks the
5106 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5107 particular label.
5108 Returns logical OR of END_* flags."
5109 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5110 (logior rv (js2-node-get-prop node
5111 'CONTROL_BLOCK_PROP
5112 js2-END_UNREACHED))))
5113
5114 (defun js2-end-check-break (node)
5115 "When a break is encountered annotate the statement being broken
5116 out of by setting its CONTROL_BLOCK_PROP property.
5117 Returns logical OR of END_* flags."
5118 (and (js2-break-node-target node)
5119 (js2-node-set-prop (js2-break-node-target node)
5120 'CONTROL_BLOCK_PROP
5121 js2-END_DROPS_OFF))
5122 js2-END_UNREACHED)
5123
5124 (defun js2-end-check (node)
5125 "Examine the body of a function, doing a basic reachability analysis.
5126 Returns a combination of flags END_* flags that indicate
5127 how the function execution can terminate. These constitute only the
5128 pessimistic set of termination conditions. It is possible that at
5129 runtime certain code paths will never be actually taken. Hence this
5130 analysis will flag errors in cases where there may not be errors.
5131 Returns logical OR of END_* flags"
5132 (let (kid)
5133 (cond
5134 ((js2-break-node-p node)
5135 (js2-end-check-break node))
5136 ((js2-expr-stmt-node-p node)
5137 (if (setq kid (js2-expr-stmt-node-expr node))
5138 (js2-end-check kid)
5139 js2-END_DROPS_OFF))
5140 ((or (js2-continue-node-p node)
5141 (js2-throw-node-p node))
5142 js2-END_UNREACHED)
5143 ((js2-return-node-p node)
5144 (if (setq kid (js2-return-node-retval node))
5145 js2-END_RETURNS_VALUE
5146 js2-END_RETURNS))
5147 ((js2-loop-node-p node)
5148 (js2-end-check-loop node))
5149 ((js2-switch-node-p node)
5150 (js2-end-check-switch node))
5151 ((js2-labeled-stmt-node-p node)
5152 (js2-end-check-label node))
5153 ((js2-if-node-p node)
5154 (js2-end-check-if node))
5155 ((js2-try-node-p node)
5156 (js2-end-check-try node))
5157 ((js2-block-node-p node)
5158 (if (null (js2-block-node-kids node))
5159 js2-END_DROPS_OFF
5160 (js2-end-check-block node)))
5161 ((js2-yield-node-p node)
5162 js2-END_YIELDS)
5163 (t
5164 js2-END_DROPS_OFF))))
5165
5166 (defun js2-always-defined-boolean-p (node)
5167 "Check if NODE always evaluates to true or false in boolean context.
5168 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5169 nor always false."
5170 (let ((tt (js2-node-type node))
5171 num)
5172 (cond
5173 ((or (= tt js2-FALSE) (= tt js2-NULL))
5174 'ALWAYS_FALSE)
5175 ((= tt js2-TRUE)
5176 'ALWAYS_TRUE)
5177 ((= tt js2-NUMBER)
5178 (setq num (js2-number-node-num-value node))
5179 (if (and (not (eq num 0.0e+NaN))
5180 (not (zerop num)))
5181 'ALWAYS_TRUE
5182 'ALWAYS_FALSE))
5183 (t
5184 nil))))
5185
5186 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5187 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5188
5189 (defvar js2-tokens nil
5190 "List of all defined token names.") ; initialized in `js2-token-names'
5191
5192 (defconst js2-token-names
5193 (let* ((names (make-vector js2-num-tokens -1))
5194 (case-fold-search nil) ; only match js2-UPPER_CASE
5195 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5196 (loop for sym in syms
5197 for i from 0
5198 do
5199 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5200 (not (boundp sym)))
5201 (aset names (symbol-value sym) ; code, e.g. 152
5202 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5203 (push sym js2-tokens)))
5204 names)
5205 "Vector mapping int values to token string names, sans `js2-' prefix.")
5206
5207 (defun js2-token-name (tok)
5208 "Return a string name for TOK, a token symbol or code.
5209 Signals an error if it's not a recognized token."
5210 (let ((code tok))
5211 (if (symbolp tok)
5212 (setq code (symbol-value tok)))
5213 (if (eq code -1)
5214 "ERROR"
5215 (if (and (numberp code)
5216 (not (minusp code))
5217 (< code js2-num-tokens))
5218 (aref js2-token-names code)
5219 (error "Invalid token: %s" code)))))
5220
5221 (defsubst js2-token-sym (tok)
5222 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5223 (intern (js2-token-name tok)))
5224
5225 (defconst js2-token-codes
5226 (let ((table (make-hash-table :test 'eq :size 256)))
5227 (loop for name across js2-token-names
5228 for sym = (intern (concat "js2-" name))
5229 do
5230 (puthash sym (symbol-value sym) table))
5231 ;; clean up a few that are "wrong" in Rhino's token codes
5232 (puthash 'js2-DELETE js2-DELPROP table)
5233 table)
5234 "Hashtable mapping token symbols to their bytecodes.")
5235
5236 (defsubst js2-token-code (sym)
5237 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5238 (or (gethash sym js2-token-codes)
5239 (error "Invalid token symbol: %s " sym))) ; signal code bug
5240
5241 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5242 (setq js2-token-end js2-ts-cursor)
5243 (js2-report-error msg nil
5244 (or beg js2-token-beg)
5245 (or len (- js2-token-end js2-token-beg)))
5246 (unless no-throw
5247 (throw 'return js2-ERROR)))
5248
5249 (defsubst js2-get-string-from-buffer ()
5250 "Reverse the char accumulator and return it as a string."
5251 (setq js2-token-end js2-ts-cursor)
5252 (if js2-ts-string-buffer
5253 (apply #'string (nreverse js2-ts-string-buffer))
5254 ""))
5255
5256 ;; TODO: could potentially avoid a lot of consing by allocating a
5257 ;; char buffer the way Rhino does.
5258 (defsubst js2-add-to-string (c)
5259 (push c js2-ts-string-buffer))
5260
5261 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5262 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5263 ;; any other character: when it's not part of the current token, we
5264 ;; unget it, allowing it to be read again by the following call.
5265 (defsubst js2-unget-char ()
5266 (decf js2-ts-cursor))
5267
5268 ;; Rhino distinguishes \r and \n line endings. We don't need to
5269 ;; because we only scan from Emacs buffers, which always use \n.
5270 (defsubst js2-get-char ()
5271 "Read and return the next character from the input buffer.
5272 Increments `js2-ts-lineno' if the return value is a newline char.
5273 Updates `js2-ts-cursor' to the point after the returned char.
5274 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5275 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5276 (let (c)
5277 ;; check for end of buffer
5278 (if (>= js2-ts-cursor (point-max))
5279 (setq js2-ts-hit-eof t
5280 js2-ts-cursor (1+ js2-ts-cursor)
5281 c js2-EOF_CHAR) ; return value
5282 ;; otherwise read next char
5283 (setq c (char-before (incf js2-ts-cursor)))
5284 ;; if we read a newline, update counters
5285 (if (= c ?\n)
5286 (setq js2-ts-line-start js2-ts-cursor
5287 js2-ts-lineno (1+ js2-ts-lineno)))
5288 ;; TODO: skip over format characters
5289 c)))
5290
5291 (defsubst js2-read-unicode-escape ()
5292 "Read a \\uNNNN sequence from the input.
5293 Assumes the ?\ and ?u have already been read.
5294 Returns the unicode character, or nil if it wasn't a valid character.
5295 Doesn't change the values of any scanner variables."
5296 ;; I really wish I knew a better way to do this, but I can't
5297 ;; find the Emacs function that takes a 16-bit int and converts
5298 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5299 ;; Have to first check that it's 4 hex characters or it may stop
5300 ;; the read early.
5301 (ignore-errors
5302 (let ((s (buffer-substring-no-properties js2-ts-cursor
5303 (+ 4 js2-ts-cursor))))
5304 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5305 (read (concat "?\\u" s))))))
5306
5307 (defsubst js2-match-char (test)
5308 "Consume and return next character if it matches TEST, a character.
5309 Returns nil and consumes nothing if TEST is not the next character."
5310 (let ((c (js2-get-char)))
5311 (if (eq c test)
5312 t
5313 (js2-unget-char)
5314 nil)))
5315
5316 (defsubst js2-peek-char ()
5317 (prog1
5318 (js2-get-char)
5319 (js2-unget-char)))
5320
5321 (defsubst js2-java-identifier-start-p (c)
5322 (or
5323 (memq c '(?$ ?_))
5324 (js2-char-uppercase-p c)
5325 (js2-char-lowercase-p c)))
5326
5327 (defsubst js2-java-identifier-part-p (c)
5328 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5329 ;; TODO: make me Unicode-friendly. See comments above.
5330 (or
5331 (memq c '(?$ ?_))
5332 (js2-char-uppercase-p c)
5333 (js2-char-lowercase-p c)
5334 (and (>= c ?0) (<= c ?9))))
5335
5336 (defsubst js2-alpha-p (c)
5337 (cond ((and (<= ?A c) (<= c ?Z)) t)
5338 ((and (<= ?a c) (<= c ?z)) t)
5339 (t nil)))
5340
5341 (defsubst js2-digit-p (c)
5342 (and (<= ?0 c) (<= c ?9)))
5343
5344 (defsubst js2-js-space-p (c)
5345 (if (<= c 127)
5346 (memq c '(#x20 #x9 #xB #xC #xD))
5347 (or
5348 (eq c #xA0)
5349 ;; TODO: change this nil to check for Unicode space character
5350 nil)))
5351
5352 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5353
5354 (defsubst js2-skip-line ()
5355 "Skip to end of line"
5356 (let (c)
5357 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5358 (js2-unget-char)
5359 (setq js2-token-end js2-ts-cursor)))
5360
5361 (defun js2-init-scanner (&optional buf line)
5362 "Create token stream for BUF starting on LINE.
5363 BUF defaults to current-buffer and line defaults to 1.
5364
5365 A buffer can only have one scanner active at a time, which yields
5366 dramatically simpler code than using a defstruct. If you need to
5367 have simultaneous scanners in a buffer, copy the regions to scan
5368 into temp buffers."
5369 (save-excursion
5370 (when buf
5371 (set-buffer buf))
5372 (setq js2-ts-dirty-line nil
5373 js2-ts-regexp-flags nil
5374 js2-ts-string ""
5375 js2-ts-number nil
5376 js2-ts-hit-eof nil
5377 js2-ts-line-start 0
5378 js2-ts-lineno (or line 1)
5379 js2-ts-line-end-char -1
5380 js2-ts-cursor (point-min)
5381 js2-ts-is-xml-attribute nil
5382 js2-ts-xml-is-tag-content nil
5383 js2-ts-xml-open-tags-count 0
5384 js2-ts-string-buffer nil)))
5385
5386 ;; This function uses the cached op, string and number fields in
5387 ;; TokenStream; if getToken has been called since the passed token
5388 ;; was scanned, the op or string printed may be incorrect.
5389 (defun js2-token-to-string (token)
5390 ;; Not sure where this function is used in Rhino. Not tested.
5391 (if (not js2-debug-print-trees)
5392 ""
5393 (let ((name (js2-token-name token)))
5394 (cond
5395 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5396 (concat name " `" js2-ts-string "'"))
5397 ((eq token js2-NUMBER)
5398 (format "NUMBER %g" js2-ts-number))
5399 (t
5400 name)))))
5401
5402 (defconst js2-keywords
5403 '(break
5404 case catch const continue
5405 debugger default delete do
5406 else enum
5407 false finally for function
5408 if in instanceof import
5409 let
5410 new null
5411 return
5412 switch
5413 this throw true try typeof
5414 var void
5415 while with
5416 yield))
5417
5418 ;; Token names aren't exactly the same as the keywords, unfortunately.
5419 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5420 (defconst js2-kwd-tokens
5421 (let ((table (make-vector js2-num-tokens nil))
5422 (tokens
5423 (list js2-BREAK
5424 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5425 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5426 js2-ELSE
5427 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5428 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5429 js2-LET
5430 js2-NEW js2-NULL
5431 js2-RETURN
5432 js2-SWITCH
5433 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5434 js2-VAR
5435 js2-WHILE js2-WITH
5436 js2-YIELD)))
5437 (dolist (i tokens)
5438 (aset table i 'font-lock-keyword-face))
5439 (aset table js2-STRING 'font-lock-string-face)
5440 (aset table js2-REGEXP 'font-lock-string-face)
5441 (aset table js2-COMMENT 'font-lock-comment-face)
5442 (aset table js2-THIS 'font-lock-builtin-face)
5443 (aset table js2-VOID 'font-lock-constant-face)
5444 (aset table js2-NULL 'font-lock-constant-face)
5445 (aset table js2-TRUE 'font-lock-constant-face)
5446 (aset table js2-FALSE 'font-lock-constant-face)
5447 table)
5448 "Vector whose values are non-nil for tokens that are keywords.
5449 The values are default faces to use for highlighting the keywords.")
5450
5451 (defconst js2-reserved-words
5452 '(abstract
5453 boolean byte
5454 char class
5455 double
5456 enum export extends
5457 final float
5458 goto
5459 implements import int interface
5460 long
5461 native
5462 package private protected public
5463 short static super synchronized
5464 throws transient
5465 volatile))
5466
5467 (defconst js2-keyword-names
5468 (let ((table (make-hash-table :test 'equal)))
5469 (loop for k in js2-keywords
5470 do (puthash
5471 (symbol-name k) ; instanceof
5472 (intern (concat "js2-"
5473 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5474 table))
5475 table)
5476 "JavaScript keywords by name, mapped to their symbols.")
5477
5478 (defconst js2-reserved-word-names
5479 (let ((table (make-hash-table :test 'equal)))
5480 (loop for k in js2-reserved-words
5481 do
5482 (puthash (symbol-name k) 'js2-RESERVED table))
5483 table)
5484 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5485
5486 (defsubst js2-collect-string (buf)
5487 "Convert BUF, a list of chars, to a string.
5488 Reverses BUF before converting."
5489 (cond
5490 ((stringp buf)
5491 buf)
5492 ((null buf) ; for emacs21 compat
5493 "")
5494 (t
5495 (if buf
5496 (apply #'string (nreverse buf))
5497 ""))))
5498
5499 (defun js2-string-to-keyword (s)
5500 "Return token for S, a string, if S is a keyword or reserved word.
5501 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5502 (or (gethash s js2-keyword-names)
5503 (gethash s js2-reserved-word-names)))
5504
5505 (defsubst js2-ts-set-char-token-bounds ()
5506 "Used when next token is one character."
5507 (setq js2-token-beg (1- js2-ts-cursor)
5508 js2-token-end js2-ts-cursor))
5509
5510 (defsubst js2-ts-return (token)
5511 "Return an N-character TOKEN from `js2-get-token'.
5512 Updates `js2-token-end' accordingly."
5513 (setq js2-token-end js2-ts-cursor)
5514 (throw 'return token))
5515
5516 (defsubst js2-x-digit-to-int (c accumulator)
5517 "Build up a hex number.
5518 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5519 corresponding number. Otherwise return -1."
5520 (catch 'return
5521 (catch 'check
5522 ;; Use 0..9 < A..Z < a..z
5523 (cond
5524 ((<= c ?9)
5525 (decf c ?0)
5526 (if (<= 0 c)
5527 (throw 'check nil)))
5528 ((<= c ?F)
5529 (when (<= ?A c)
5530 (decf c (- ?A 10))
5531 (throw 'check nil)))
5532 ((<= c ?f)
5533 (when (<= ?a c)
5534 (decf c (- ?a 10))
5535 (throw 'check nil))))
5536 (throw 'return -1))
5537 (logior c (lsh accumulator 4))))
5538
5539 (defun js2-get-token ()
5540 "Return next JavaScript token, an int such as js2-RETURN."
5541 (let (c
5542 c1
5543 identifier-start
5544 is-unicode-escape-start
5545 contains-escape
5546 escape-val
5547 escape-start
5548 str
5549 result
5550 base
5551 is-integer
5552 quote-char
5553 val
5554 look-for-slash
5555 continue)
5556 (catch 'return
5557 (while t
5558 ;; Eat whitespace, possibly sensitive to newlines.
5559 (setq continue t)
5560 (while continue
5561 (setq c (js2-get-char))
5562 (cond
5563 ((eq c js2-EOF_CHAR)
5564 (js2-ts-set-char-token-bounds)
5565 (throw 'return js2-EOF))
5566 ((eq c ?\n)
5567 (js2-ts-set-char-token-bounds)
5568 (setq js2-ts-dirty-line nil)
5569 (throw 'return js2-EOL))
5570 ((not (js2-js-space-p c))
5571 (if (/= c ?-) ; in case end of HTML comment
5572 (setq js2-ts-dirty-line t))
5573 (setq continue nil))))
5574 ;; Assume the token will be 1 char - fixed up below.
5575 (js2-ts-set-char-token-bounds)
5576 (when (eq c ?@)
5577 (throw 'return js2-XMLATTR))
5578 ;; identifier/keyword/instanceof?
5579 ;; watch out for starting with a <backslash>
5580 (cond
5581 ((eq c ?\\)
5582 (setq c (js2-get-char))
5583 (if (eq c ?u)
5584 (setq identifier-start t
5585 is-unicode-escape-start t
5586 js2-ts-string-buffer nil)
5587 (setq identifier-start nil)
5588 (js2-unget-char)
5589 (setq c ?\\)))
5590 (t
5591 (when (setq identifier-start (js2-java-identifier-start-p c))
5592 (setq js2-ts-string-buffer nil)
5593 (js2-add-to-string c))))
5594 (when identifier-start
5595 (setq contains-escape is-unicode-escape-start)
5596 (catch 'break
5597 (while t
5598 (if is-unicode-escape-start
5599 ;; strictly speaking we should probably push-back
5600 ;; all the bad characters if the <backslash>uXXXX
5601 ;; sequence is malformed. But since there isn't a
5602 ;; correct context(is there?) for a bad Unicode
5603 ;; escape sequence in an identifier, we can report
5604 ;; an error here.
5605 (progn
5606 (setq escape-val 0)
5607 (dotimes (i 4)
5608 (setq c (js2-get-char)
5609 escape-val (js2-x-digit-to-int c escape-val))
5610 ;; Next check takes care of c < 0 and bad escape
5611 (if (minusp escape-val)
5612 (throw 'break nil)))
5613 (if (minusp escape-val)
5614 (js2-report-scan-error "msg.invalid.escape" t))
5615 (js2-add-to-string escape-val)
5616 (setq is-unicode-escape-start nil))
5617 (setq c (js2-get-char))
5618 (cond
5619 ((eq c ?\\)
5620 (setq c (js2-get-char))
5621 (if (eq c ?u)
5622 (setq is-unicode-escape-start t
5623 contains-escape t)
5624 (js2-report-scan-error "msg.illegal.character" t)))
5625 (t
5626 (if (or (eq c js2-EOF_CHAR)
5627 (not (js2-java-identifier-part-p c)))
5628 (throw 'break nil))
5629 (js2-add-to-string c))))))
5630 (js2-unget-char)
5631 (setq str (js2-get-string-from-buffer))
5632 (unless contains-escape
5633 ;; OPT we shouldn't have to make a string (object!) to
5634 ;; check if it's a keyword.
5635 ;; Return the corresponding token if it's a keyword
5636 (when (setq result (js2-string-to-keyword str))
5637 (if (and (< js2-language-version 170)
5638 (memq result '(js2-LET js2-YIELD)))
5639 ;; LET and YIELD are tokens only in 1.7 and later
5640 (setq result 'js2-NAME))
5641 (if (not (eq result 'js2-RESERVED))
5642 (throw 'return (js2-token-code result)))
5643 (js2-report-warning "msg.reserved.keyword" str)))
5644 ;; If we want to intern these as Rhino does, just use (intern str)
5645 (setq js2-ts-string str)
5646 (throw 'return js2-NAME)) ; end identifier/kwd check
5647 ;; is it a number?
5648 (when (or (js2-digit-p c)
5649 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5650 (setq js2-ts-string-buffer nil
5651 base 10)
5652 (when (eq c ?0)
5653 (setq c (js2-get-char))
5654 (cond
5655 ((or (eq c ?x) (eq c ?X))
5656 (setq base 16)
5657 (setq c (js2-get-char)))
5658 ((js2-digit-p c)
5659 (setq base 8))
5660 (t
5661 (js2-add-to-string ?0))))
5662 (if (eq base 16)
5663 (while (<= 0 (js2-x-digit-to-int c 0))
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char)))
5666 (while (and (<= ?0 c) (<= c ?9))
5667 ;; We permit 08 and 09 as decimal numbers, which
5668 ;; makes our behavior a superset of the ECMA
5669 ;; numeric grammar. We might not always be so
5670 ;; permissive, so we warn about it.
5671 (when (and (eq base 8) (>= c ?8))
5672 (js2-report-warning "msg.bad.octal.literal"
5673 (if (eq c ?8) "8" "9"))
5674 (setq base 10))
5675 (js2-add-to-string c)
5676 (setq c (js2-get-char))))
5677 (setq is-integer t)
5678 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5679 (setq is-integer nil)
5680 (when (eq c ?.)
5681 (loop do
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char))
5684 while (js2-digit-p c)))
5685 (when (memq c '(?e ?E))
5686 (js2-add-to-string c)
5687 (setq c (js2-get-char))
5688 (when (memq c '(?+ ?-))
5689 (js2-add-to-string c)
5690 (setq c (js2-get-char)))
5691 (unless (js2-digit-p c)
5692 (js2-report-scan-error "msg.missing.exponent" t))
5693 (loop do
5694 (js2-add-to-string c)
5695 (setq c (js2-get-char))
5696 while (js2-digit-p c))))
5697 (js2-unget-char)
5698 (setq js2-ts-string (js2-get-string-from-buffer)
5699 js2-ts-number
5700 (if (and (eq base 10) (not is-integer))
5701 (string-to-number js2-ts-string)
5702 ;; TODO: call runtime number-parser. Some of it is in
5703 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5704 (string-to-number js2-ts-string)))
5705 (throw 'return js2-NUMBER))
5706 ;; is it a string?
5707 (when (memq c '(?\" ?\'))
5708 ;; We attempt to accumulate a string the fast way, by
5709 ;; building it directly out of the reader. But if there
5710 ;; are any escaped characters in the string, we revert to
5711 ;; building it out of a string buffer.
5712 (setq quote-char c
5713 js2-ts-string-buffer nil
5714 c (js2-get-char))
5715 (catch 'break
5716 (while (/= c quote-char)
5717 (catch 'continue
5718 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5719 (js2-unget-char)
5720 (setq js2-token-end js2-ts-cursor)
5721 (js2-report-error "msg.unterminated.string.lit")
5722 (throw 'return js2-STRING))
5723 (when (eq c ?\\)
5724 ;; We've hit an escaped character
5725 (setq c (js2-get-char))
5726 (case c
5727 (?b (setq c ?\b))
5728 (?f (setq c ?\f))
5729 (?n (setq c ?\n))
5730 (?r (setq c ?\r))
5731 (?t (setq c ?\t))
5732 (?v (setq c ?\v))
5733 (?u
5734 (setq c1 (js2-read-unicode-escape))
5735 (if js2-parse-ide-mode
5736 (if c1
5737 (progn
5738 ;; just copy the string in IDE-mode
5739 (js2-add-to-string ?\\)
5740 (js2-add-to-string ?u)
5741 (dotimes (i 3)
5742 (js2-add-to-string (js2-get-char)))
5743 (setq c (js2-get-char))) ; added at end of loop
5744 ;; flag it as an invalid escape
5745 (js2-report-warning "msg.invalid.escape"
5746 nil (- js2-ts-cursor 2) 6))
5747 ;; Get 4 hex digits; if the u escape is not
5748 ;; followed by 4 hex digits, use 'u' + the
5749 ;; literal character sequence that follows.
5750 (js2-add-to-string ?u)
5751 (setq escape-val 0)
5752 (dotimes (i 4)
5753 (setq c (js2-get-char)
5754 escape-val (js2-x-digit-to-int c escape-val))
5755 (if (minusp escape-val)
5756 (throw 'continue nil))
5757 (js2-add-to-string c))
5758 ;; prepare for replace of stored 'u' sequence by escape value
5759 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5760 c escape-val)))
5761 (?x
5762 ;; Get 2 hex digits, defaulting to 'x'+literal
5763 ;; sequence, as above.
5764 (setq c (js2-get-char)
5765 escape-val (js2-x-digit-to-int c 0))
5766 (if (minusp escape-val)
5767 (progn
5768 (js2-add-to-string ?x)
5769 (throw 'continue nil))
5770 (setq c1 c
5771 c (js2-get-char)
5772 escape-val (js2-x-digit-to-int c escape-val))
5773 (if (minusp escape-val)
5774 (progn
5775 (js2-add-to-string ?x)
5776 (js2-add-to-string c1)
5777 (throw 'continue nil))
5778 ;; got 2 hex digits
5779 (setq c escape-val))))
5780 (?\n
5781 ;; Remove line terminator after escape to follow
5782 ;; SpiderMonkey and C/C++
5783 (setq c (js2-get-char))
5784 (throw 'continue nil))
5785 (t
5786 (when (and (<= ?0 c) (< c ?8))
5787 (setq val (- c ?0)
5788 c (js2-get-char))
5789 (when (and (<= ?0 c) (< c ?8))
5790 (setq val (- (+ (* 8 val) c) ?0)
5791 c (js2-get-char))
5792 (when (and (<= ?0 c)
5793 (< c ?8)
5794 (< val #o37))
5795 ;; c is 3rd char of octal sequence only
5796 ;; if the resulting val <= 0377
5797 (setq val (- (+ (* 8 val) c) ?0)
5798 c (js2-get-char))))
5799 (js2-unget-char)
5800 (setq c val)))))
5801 (js2-add-to-string c)
5802 (setq c (js2-get-char)))))
5803 (setq js2-ts-string (js2-get-string-from-buffer))
5804 (throw 'return js2-STRING))
5805 (case c
5806 (?\;
5807 (throw 'return js2-SEMI))
5808 (?\[
5809 (throw 'return js2-LB))
5810 (?\]
5811 (throw 'return js2-RB))
5812 (?{
5813 (throw 'return js2-LC))
5814 (?}
5815 (throw 'return js2-RC))
5816 (?\(
5817 (throw 'return js2-LP))
5818 (?\)
5819 (throw 'return js2-RP))
5820 (?,
5821 (throw 'return js2-COMMA))
5822 (??
5823 (throw 'return js2-HOOK))
5824 (?:
5825 (if (js2-match-char ?:)
5826 (js2-ts-return js2-COLONCOLON)
5827 (throw 'return js2-COLON)))
5828 (?.
5829 (if (js2-match-char ?.)
5830 (js2-ts-return js2-DOTDOT)
5831 (if (js2-match-char ?\()
5832 (js2-ts-return js2-DOTQUERY)
5833 (throw 'return js2-DOT))))
5834 (?|
5835 (if (js2-match-char ?|)
5836 (throw 'return js2-OR)
5837 (if (js2-match-char ?=)
5838 (js2-ts-return js2-ASSIGN_BITOR)
5839 (throw 'return js2-BITOR))))
5840 (?^
5841 (if (js2-match-char ?=)
5842 (js2-ts-return js2-ASSIGN_BITOR)
5843 (throw 'return js2-BITXOR)))
5844 (?&
5845 (if (js2-match-char ?&)
5846 (throw 'return js2-AND)
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-ASSIGN_BITAND)
5849 (throw 'return js2-BITAND))))
5850 (?=
5851 (if (js2-match-char ?=)
5852 (if (js2-match-char ?=)
5853 (js2-ts-return js2-SHEQ)
5854 (throw 'return js2-EQ))
5855 (throw 'return js2-ASSIGN)))
5856 (?!
5857 (if (js2-match-char ?=)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-SHNE)
5860 (js2-ts-return js2-NE))
5861 (throw 'return js2-NOT)))
5862 (?<
5863 ;; NB:treat HTML begin-comment as comment-till-eol
5864 (when (js2-match-char ?!)
5865 (when (js2-match-char ?-)
5866 (when (js2-match-char ?-)
5867 (js2-skip-line)
5868 (setq js2-ts-comment-type 'html)
5869 (throw 'return js2-COMMENT)))
5870 (js2-unget-char))
5871 (if (js2-match-char ?<)
5872 (if (js2-match-char ?=)
5873 (js2-ts-return js2-ASSIGN_LSH)
5874 (js2-ts-return js2-LSH))
5875 (if (js2-match-char ?=)
5876 (js2-ts-return js2-LE)
5877 (throw 'return js2-LT))))
5878 (?>
5879 (if (js2-match-char ?>)
5880 (if (js2-match-char ?>)
5881 (if (js2-match-char ?=)
5882 (js2-ts-return js2-ASSIGN_URSH)
5883 (js2-ts-return js2-URSH))
5884 (if (js2-match-char ?=)
5885 (js2-ts-return js2-ASSIGN_RSH)
5886 (js2-ts-return js2-RSH)))
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-GE)
5889 (throw 'return js2-GT))))
5890 (?*
5891 (if (js2-match-char ?=)
5892 (js2-ts-return js2-ASSIGN_MUL)
5893 (throw 'return js2-MUL)))
5894 (?/
5895 ;; is it a // comment?
5896 (when (js2-match-char ?/)
5897 (setq js2-token-beg (- js2-ts-cursor 2))
5898 (js2-skip-line)
5899 (setq js2-ts-comment-type 'line)
5900 ;; include newline so highlighting goes to end of window
5901 (incf js2-token-end)
5902 (throw 'return js2-COMMENT))
5903 ;; is it a /* comment?
5904 (when (js2-match-char ?*)
5905 (setq look-for-slash nil
5906 js2-token-beg (- js2-ts-cursor 2)
5907 js2-ts-comment-type
5908 (if (js2-match-char ?*)
5909 (progn
5910 (setq look-for-slash t)
5911 'jsdoc)
5912 'block))
5913 (while t
5914 (setq c (js2-get-char))
5915 (cond
5916 ((eq c js2-EOF_CHAR)
5917 (setq js2-token-end (1- js2-ts-cursor))
5918 (js2-report-error "msg.unterminated.comment")
5919 (throw 'return js2-COMMENT))
5920 ((eq c ?*)
5921 (setq look-for-slash t))
5922 ((eq c ?/)
5923 (if look-for-slash
5924 (js2-ts-return js2-COMMENT)))
5925 (t
5926 (setq look-for-slash nil
5927 js2-token-end js2-ts-cursor)))))
5928 (if (js2-match-char ?=)
5929 (js2-ts-return js2-ASSIGN_DIV)
5930 (throw 'return js2-DIV)))
5931 (?#
5932 (when js2-skip-preprocessor-directives
5933 (js2-skip-line)
5934 (setq js2-ts-comment-type 'preprocessor
5935 js2-token-end js2-ts-cursor)
5936 (throw 'return js2-COMMENT))
5937 (throw 'return js2-ERROR))
5938 (?%
5939 (if (js2-match-char ?=)
5940 (js2-ts-return js2-ASSIGN_MOD)
5941 (throw 'return js2-MOD)))
5942 (?~
5943 (throw 'return js2-BITNOT))
5944 (?+
5945 (if (js2-match-char ?=)
5946 (js2-ts-return js2-ASSIGN_ADD)
5947 (if (js2-match-char ?+)
5948 (js2-ts-return js2-INC)
5949 (throw 'return js2-ADD))))
5950 (?-
5951 (cond
5952 ((js2-match-char ?=)
5953 (setq c js2-ASSIGN_SUB))
5954 ((js2-match-char ?-)
5955 (unless js2-ts-dirty-line
5956 ;; treat HTML end-comment after possible whitespace
5957 ;; after line start as comment-until-eol
5958 (when (js2-match-char ?>)
5959 (js2-skip-line)
5960 (setq js2-ts-comment-type 'html)
5961 (throw 'return js2-COMMENT)))
5962 (setq c js2-DEC))
5963 (t
5964 (setq c js2-SUB)))
5965 (setq js2-ts-dirty-line t)
5966 (js2-ts-return c))
5967 (otherwise
5968 (js2-report-scan-error "msg.illegal.character")))))))
5969
5970 (defun js2-read-regexp (start-token)
5971 "Called by parser when it gets / or /= in literal context."
5972 (let (c
5973 err
5974 in-class ; inside a '[' .. ']' character-class
5975 flags
5976 (continue t))
5977 (setq js2-token-beg js2-ts-cursor
5978 js2-ts-string-buffer nil
5979 js2-ts-regexp-flags nil)
5980 (if (eq start-token js2-ASSIGN_DIV)
5981 ;; mis-scanned /=
5982 (js2-add-to-string ?=)
5983 (if (not (eq start-token js2-DIV))
5984 (error "failed assertion")))
5985 (while (and (not err)
5986 (or (/= (setq c (js2-get-char)) ?/)
5987 in-class))
5988 (cond
5989 ((or (= c ?\n)
5990 (= c js2-EOF_CHAR))
5991 (setq js2-token-end (1- js2-ts-cursor)
5992 err t
5993 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5994 (js2-report-error "msg.unterminated.re.lit"))
5995 (t (cond
5996 ((= c ?\\)
5997 (js2-add-to-string c)
5998 (setq c (js2-get-char)))
5999 ((= c ?\[)
6000 (setq in-class t))
6001 ((= c ?\])
6002 (setq in-class nil)))
6003 (js2-add-to-string c))))
6004 (unless err
6005 (while continue
6006 (cond
6007 ((js2-match-char ?g)
6008 (push ?g flags))
6009 ((js2-match-char ?i)
6010 (push ?i flags))
6011 ((js2-match-char ?m)
6012 (push ?m flags))
6013 (t
6014 (setq continue nil))))
6015 (if (js2-alpha-p (js2-peek-char))
6016 (js2-report-scan-error "msg.invalid.re.flag" t
6017 js2-ts-cursor 1))
6018 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6019 js2-ts-regexp-flags (js2-collect-string flags)
6020 js2-token-end js2-ts-cursor)
6021 ;; tell `parse-partial-sexp' to ignore this range of chars
6022 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6023
6024 (defun js2-get-first-xml-token ()
6025 (setq js2-ts-xml-open-tags-count 0
6026 js2-ts-is-xml-attribute nil
6027 js2-ts-xml-is-tag-content nil)
6028 (js2-unget-char)
6029 (js2-get-next-xml-token))
6030
6031 (defsubst js2-xml-discard-string ()
6032 "Throw away the string in progress and flag an XML parse error."
6033 (setq js2-ts-string-buffer nil
6034 js2-ts-string nil)
6035 (js2-report-scan-error "msg.XML.bad.form" t))
6036
6037 (defun js2-get-next-xml-token ()
6038 (setq js2-ts-string-buffer nil ; for recording the XML
6039 js2-token-beg js2-ts-cursor)
6040 (let (c result)
6041 (setq result
6042 (catch 'return
6043 (while t
6044 (setq c (js2-get-char))
6045 (cond
6046 ((= c js2-EOF_CHAR)
6047 (throw 'return js2-ERROR))
6048 (js2-ts-xml-is-tag-content
6049 (case c
6050 (?>
6051 (js2-add-to-string c)
6052 (setq js2-ts-xml-is-tag-content nil
6053 js2-ts-is-xml-attribute nil))
6054 (?/
6055 (js2-add-to-string c)
6056 (when (eq ?> (js2-peek-char))
6057 (setq c (js2-get-char))
6058 (js2-add-to-string c)
6059 (setq js2-ts-xml-is-tag-content nil)
6060 (decf js2-ts-xml-open-tags-count)))
6061 (?{
6062 (js2-unget-char)
6063 (setq js2-ts-string (js2-get-string-from-buffer))
6064 (throw 'return js2-XML))
6065 ((?\' ?\")
6066 (js2-add-to-string c)
6067 (unless (js2-read-quoted-string c)
6068 (throw 'return js2-ERROR)))
6069 (?=
6070 (js2-add-to-string c)
6071 (setq js2-ts-is-xml-attribute t))
6072 ((? ?\t ?\r ?\n)
6073 (js2-add-to-string c))
6074 (t
6075 (js2-add-to-string c)
6076 (setq js2-ts-is-xml-attribute nil)))
6077 (when (and (not js2-ts-xml-is-tag-content)
6078 (zerop js2-ts-xml-open-tags-count))
6079 (setq js2-ts-string (js2-get-string-from-buffer))
6080 (throw 'return js2-XMLEND)))
6081 (t
6082 ;; else not tag content
6083 (case c
6084 (?<
6085 (js2-add-to-string c)
6086 (setq c (js2-peek-char))
6087 (case c
6088 (?!
6089 (setq c (js2-get-char)) ;; skip !
6090 (js2-add-to-string c)
6091 (setq c (js2-peek-char))
6092 (case c
6093 (?-
6094 (setq c (js2-get-char)) ;; skip -
6095 (js2-add-to-string c)
6096 (if (eq c ?-)
6097 (progn
6098 (js2-add-to-string c)
6099 (unless (js2-read-xml-comment)
6100 (throw 'return js2-ERROR)))
6101 (js2-xml-discard-string)
6102 (throw 'return js2-ERROR)))
6103 (?\[
6104 (setq c (js2-get-char)) ;; skip [
6105 (js2-add-to-string c)
6106 (if (and (= (js2-get-char) ?C)
6107 (= (js2-get-char) ?D)
6108 (= (js2-get-char) ?A)
6109 (= (js2-get-char) ?T)
6110 (= (js2-get-char) ?A)
6111 (= (js2-get-char) ?\[))
6112 (progn
6113 (js2-add-to-string ?C)
6114 (js2-add-to-string ?D)
6115 (js2-add-to-string ?A)
6116 (js2-add-to-string ?T)
6117 (js2-add-to-string ?A)
6118 (js2-add-to-string ?\[)
6119 (unless (js2-read-cdata)
6120 (throw 'return js2-ERROR)))
6121 (js2-xml-discard-string)
6122 (throw 'return js2-ERROR)))
6123 (t
6124 (unless (js2-read-entity)
6125 (throw 'return js2-ERROR))))
6126 ;; allow bare CDATA section
6127 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6128 (when (zerop js2-ts-xml-open-tags-count)
6129 (throw 'return js2-XMLEND)))
6130 (??
6131 (setq c (js2-get-char)) ;; skip ?
6132 (js2-add-to-string c)
6133 (unless (js2-read-PI)
6134 (throw 'return js2-ERROR)))
6135 (?/
6136 ;; end tag
6137 (setq c (js2-get-char)) ;; skip /
6138 (js2-add-to-string c)
6139 (when (zerop js2-ts-xml-open-tags-count)
6140 (js2-xml-discard-string)
6141 (throw 'return js2-ERROR))
6142 (setq js2-ts-xml-is-tag-content t)
6143 (decf js2-ts-xml-open-tags-count))
6144 (t
6145 ;; start tag
6146 (setq js2-ts-xml-is-tag-content t)
6147 (incf js2-ts-xml-open-tags-count))))
6148 (?{
6149 (js2-unget-char)
6150 (setq js2-ts-string (js2-get-string-from-buffer))
6151 (throw 'return js2-XML))
6152 (t
6153 (js2-add-to-string c))))))))
6154 (setq js2-token-end js2-ts-cursor)
6155 result))
6156
6157 (defun js2-read-quoted-string (quote)
6158 (let (c)
6159 (catch 'return
6160 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6161 (js2-add-to-string c)
6162 (if (eq c quote)
6163 (throw 'return t)))
6164 (js2-xml-discard-string) ;; throw away string in progress
6165 nil)))
6166
6167 (defun js2-read-xml-comment ()
6168 (let ((c (js2-get-char)))
6169 (catch 'return
6170 (while (/= c js2-EOF_CHAR)
6171 (catch 'continue
6172 (js2-add-to-string c)
6173 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6174 (setq c (js2-get-char))
6175 (js2-add-to-string c)
6176 (if (eq (js2-peek-char) ?>)
6177 (progn
6178 (setq c (js2-get-char)) ;; skip >
6179 (js2-add-to-string c)
6180 (throw 'return t))
6181 (throw 'continue nil)))
6182 (setq c (js2-get-char))))
6183 (js2-xml-discard-string)
6184 nil)))
6185
6186 (defun js2-read-cdata ()
6187 (let ((c (js2-get-char)))
6188 (catch 'return
6189 (while (/= c js2-EOF_CHAR)
6190 (catch 'continue
6191 (js2-add-to-string c)
6192 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6193 (setq c (js2-get-char))
6194 (js2-add-to-string c)
6195 (if (eq (js2-peek-char) ?>)
6196 (progn
6197 (setq c (js2-get-char)) ;; Skip >
6198 (js2-add-to-string c)
6199 (throw 'return t))
6200 (throw 'continue nil)))
6201 (setq c (js2-get-char))))
6202 (js2-xml-discard-string)
6203 nil)))
6204
6205 (defun js2-read-entity ()
6206 (let ((decl-tags 1)
6207 c)
6208 (catch 'return
6209 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6210 (js2-add-to-string c)
6211 (case c
6212 (?<
6213 (incf decl-tags))
6214 (?>
6215 (decf decl-tags)
6216 (if (zerop decl-tags)
6217 (throw 'return t)))))
6218 (js2-xml-discard-string)
6219 nil)))
6220
6221 (defun js2-read-PI ()
6222 "Scan an XML processing instruction."
6223 (let (c)
6224 (catch 'return
6225 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6226 (js2-add-to-string c)
6227 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6228 (setq c (js2-get-char)) ;; Skip >
6229 (js2-add-to-string c)
6230 (throw 'return t)))
6231 (js2-xml-discard-string)
6232 nil)))
6233
6234 (defun js2-scanner-get-line ()
6235 "Return the text of the current scan line."
6236 (buffer-substring (point-at-bol) (point-at-eol)))
6237
6238 ;;; Highlighting
6239
6240 (defsubst js2-set-face (beg end face &optional record)
6241 "Fontify a region. If RECORD is non-nil, record for later."
6242 (when (plusp js2-highlight-level)
6243 (setq beg (min (point-max) beg)
6244 beg (max (point-min) beg)
6245 end (min (point-max) end)
6246 end (max (point-min) end))
6247 (if record
6248 (push (list beg end face) js2-mode-fontifications)
6249 (put-text-property beg end 'font-lock-face face))))
6250
6251 (defsubst js2-set-kid-face (pos kid len face)
6252 "Set-face on a child node.
6253 POS is absolute buffer position of parent.
6254 KID is the child node.
6255 LEN is the length to fontify.
6256 FACE is the face to fontify with."
6257 (js2-set-face (+ pos (js2-node-pos kid))
6258 (+ pos (js2-node-pos kid) (js2-node-len kid))
6259 face))
6260
6261 (defsubst js2-fontify-kwd (start length)
6262 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6263
6264 (defsubst js2-clear-face (beg end)
6265 (remove-text-properties beg end '(font-lock-face nil
6266 help-echo nil
6267 point-entered nil
6268 c-in-sws nil)))
6269
6270 (defconst js2-ecma-global-props
6271 (concat "^"
6272 (regexp-opt
6273 '("Infinity" "NaN" "undefined" "arguments") t)
6274 "$")
6275 "Value properties of the Ecma-262 Global Object.
6276 Shown at or above `js2-highlight-level' 2.")
6277
6278 ;; might want to add the name "arguments" to this list?
6279 (defconst js2-ecma-object-props
6280 (concat "^"
6281 (regexp-opt
6282 '("prototype" "__proto__" "__parent__") t)
6283 "$")
6284 "Value properties of the Ecma-262 Object constructor.
6285 Shown at or above `js2-highlight-level' 2.")
6286
6287 (defconst js2-ecma-global-funcs
6288 (concat
6289 "^"
6290 (regexp-opt
6291 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6292 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6293 "$")
6294 "Function properties of the Ecma-262 Global object.
6295 Shown at or above `js2-highlight-level' 2.")
6296
6297 (defconst js2-ecma-number-props
6298 (concat "^"
6299 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6300 "NEGATIVE_INFINITY"
6301 "POSITIVE_INFINITY") t)
6302 "$")
6303 "Properties of the Ecma-262 Number constructor.
6304 Shown at or above `js2-highlight-level' 2.")
6305
6306 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6307 "Properties of the Ecma-262 Date constructor.
6308 Shown at or above `js2-highlight-level' 2.")
6309
6310 (defconst js2-ecma-math-props
6311 (concat "^"
6312 (regexp-opt
6313 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6314 t)
6315 "$")
6316 "Properties of the Ecma-262 Math object.
6317 Shown at or above `js2-highlight-level' 2.")
6318
6319 (defconst js2-ecma-math-funcs
6320 (concat "^"
6321 (regexp-opt
6322 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6323 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6324 "$")
6325 "Function properties of the Ecma-262 Math object.
6326 Shown at or above `js2-highlight-level' 2.")
6327
6328 (defconst js2-ecma-function-props
6329 (concat
6330 "^"
6331 (regexp-opt
6332 '(;; properties of the Object prototype object
6333 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6334 "toLocaleString" "toString" "valueOf"
6335 ;; properties of the Function prototype object
6336 "apply" "call"
6337 ;; properties of the Array prototype object
6338 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6339 "splice" "unshift"
6340 ;; properties of the String prototype object
6341 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6342 "localeCompare" "match" "replace" "search" "split" "substring"
6343 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6344 "toUpperCase"
6345 ;; properties of the Number prototype object
6346 "toExponential" "toFixed" "toPrecision"
6347 ;; properties of the Date prototype object
6348 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6349 "getMinutes" "getMonth" "getSeconds" "getTime"
6350 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6351 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6352 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6353 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6354 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6355 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6356 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6357 "toTimeString" "toUTCString"
6358 ;; properties of the RegExp prototype object
6359 "exec" "test"
6360 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6361 "toSource" "__defineGetter__" "__defineSetter__"
6362 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6363 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6364 t)
6365 "$")
6366 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6367 Shown at or above `js2-highlight-level' 3.")
6368
6369 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6370 (let ((target-name (and target
6371 (js2-name-node-p target)
6372 (js2-name-node-name target)))
6373 (prop-name (if prop (js2-name-node-name prop)))
6374 (level1 (>= js2-highlight-level 1))
6375 (level2 (>= js2-highlight-level 2))
6376 (level3 (>= js2-highlight-level 3))
6377 pos
6378 face)
6379 (when level2
6380 (if call-p
6381 (cond
6382 ((and target prop)
6383 (cond
6384 ((and level3 (string-match js2-ecma-function-props prop-name))
6385 (setq face 'font-lock-builtin-face))
6386 ((and target-name prop)
6387 (cond
6388 ((string= target-name "Date")
6389 (if (string-match js2-ecma-date-props prop-name)
6390 (setq face 'font-lock-builtin-face)))
6391 ((string= target-name "Math")
6392 (if (string-match js2-ecma-math-funcs prop-name)
6393 (setq face 'font-lock-builtin-face)))))))
6394 (prop
6395 (if (string-match js2-ecma-global-funcs prop-name)
6396 (setq face 'font-lock-builtin-face))))
6397 (cond
6398 ((and target prop)
6399 (cond
6400 ((string= target-name "Number")
6401 (if (string-match js2-ecma-number-props prop-name)
6402 (setq face 'font-lock-constant-face)))
6403 ((string= target-name "Math")
6404 (if (string-match js2-ecma-math-props prop-name)
6405 (setq face 'font-lock-constant-face)))))
6406 (prop
6407 (if (string-match js2-ecma-object-props prop-name)
6408 (setq face 'font-lock-constant-face)))))
6409 (when face
6410 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6411 (js2-node-pos prop))) ; relative
6412 (+ pos (js2-node-len prop))
6413 face)))))
6414
6415 (defun js2-parse-highlight-member-expr-node (node)
6416 "Perform syntax highlighting of EcmaScript built-in properties.
6417 The variable `js2-highlight-level' governs this highighting."
6418 (let (face target prop name pos end parent call-p callee)
6419 (cond
6420 ;; case 1: simple name, e.g. foo
6421 ((js2-name-node-p node)
6422 (setq name (js2-name-node-name node))
6423 ;; possible for name to be nil in rare cases - saw it when
6424 ;; running js2-mode on an elisp buffer. Might as well try to
6425 ;; make it so js2-mode never barfs.
6426 (when name
6427 (setq face (if (string-match js2-ecma-global-props name)
6428 'font-lock-constant-face))
6429 (when face
6430 (setq pos (js2-node-pos node)
6431 end (+ pos (js2-node-len node)))
6432 (js2-set-face pos end face))))
6433 ;; case 2: property access or function call
6434 ((or (js2-prop-get-node-p node)
6435 ;; highlight function call if expr is a prop-get node
6436 ;; or a plain name (i.e. unqualified function call)
6437 (and (setq call-p (js2-call-node-p node))
6438 (setq callee (js2-call-node-target node)) ; separate setq!
6439 (or (js2-prop-get-node-p callee)
6440 (js2-name-node-p callee))))
6441 (setq parent node
6442 node (if call-p callee node))
6443 (if (and call-p (js2-name-node-p callee))
6444 (setq prop callee)
6445 (setq target (js2-prop-get-node-left node)
6446 prop (js2-prop-get-node-right node)))
6447 (cond
6448 ((js2-name-node-p target)
6449 (if (js2-name-node-p prop)
6450 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6451 (js2-parse-highlight-prop-get parent target prop call-p)
6452 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6453 (js2-parse-highlight-prop-get parent target nil call-p)))
6454 ((js2-name-node-p prop)
6455 ;; case 2c: complex target, simple name, e.g. x[y].bar
6456 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6457
6458 (defun js2-parse-highlight-member-expr-fn-name (expr)
6459 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6460 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6461 We currently only handle the case where the last component is a prop-get
6462 of a simple name. Called before EXPR has a parent node."
6463 (let (pos
6464 (name (and (js2-prop-get-node-p expr)
6465 (js2-prop-get-node-right expr))))
6466 (when (js2-name-node-p name)
6467 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6468 (js2-node-pos name)))
6469 (+ pos (js2-node-len name))
6470 'font-lock-function-name-face
6471 'record))))
6472
6473 ;; source: http://jsdoc.sourceforge.net/
6474 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6475 ;; allows type specifications, and needs work before entering the wild.
6476
6477 (defconst js2-jsdoc-param-tag-regexp
6478 (concat "^\\s-*\\*+\\s-*\\(@"
6479 "\\(?:param\\|argument\\)"
6480 "\\)"
6481 "\\s-*\\({[^}]+}\\)?" ; optional type
6482 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6483 "\\>")
6484 "Matches jsdoc tags with optional type and optional param name.")
6485
6486 (defconst js2-jsdoc-typed-tag-regexp
6487 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6488 (regexp-opt
6489 '("enum"
6490 "extends"
6491 "field"
6492 "id"
6493 "implements"
6494 "lends"
6495 "mods"
6496 "requires"
6497 "return"
6498 "returns"
6499 "throw"
6500 "throws"))
6501 "\\)\\)\\s-*\\({[^}]+}\\)?")
6502 "Matches jsdoc tags with optional type.")
6503
6504 (defconst js2-jsdoc-arg-tag-regexp
6505 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6506 (regexp-opt
6507 '("alias"
6508 "augments"
6509 "borrows"
6510 "bug"
6511 "base"
6512 "config"
6513 "default"
6514 "define"
6515 "exception"
6516 "function"
6517 "member"
6518 "memberOf"
6519 "name"
6520 "namespace"
6521 "property"
6522 "since"
6523 "suppress"
6524 "this"
6525 "throws"
6526 "type"
6527 "version"))
6528 "\\)\\)\\s-+\\([^ \t]+\\)")
6529 "Matches jsdoc tags with a single argument.")
6530
6531 (defconst js2-jsdoc-empty-tag-regexp
6532 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6533 (regexp-opt
6534 '("addon"
6535 "author"
6536 "class"
6537 "const"
6538 "constant"
6539 "constructor"
6540 "constructs"
6541 "deprecated"
6542 "desc"
6543 "description"
6544 "event"
6545 "example"
6546 "exec"
6547 "export"
6548 "fileoverview"
6549 "final"
6550 "function"
6551 "hidden"
6552 "ignore"
6553 "implicitCast"
6554 "inheritDoc"
6555 "inner"
6556 "interface"
6557 "license"
6558 "noalias"
6559 "noshadow"
6560 "notypecheck"
6561 "override"
6562 "owner"
6563 "preserve"
6564 "preserveTry"
6565 "private"
6566 "protected"
6567 "public"
6568 "static"
6569 "supported"
6570 ))
6571 "\\)\\)\\s-*")
6572 "Matches empty jsdoc tags.")
6573
6574 (defconst js2-jsdoc-link-tag-regexp
6575 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6576 "Matches a jsdoc link or code tag.")
6577
6578 (defconst js2-jsdoc-see-tag-regexp
6579 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6580 "Matches a jsdoc @see tag.")
6581
6582 (defconst js2-jsdoc-html-tag-regexp
6583 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6584 "Matches a simple (no attributes) html start- or end-tag.")
6585
6586 (defsubst js2-jsdoc-highlight-helper ()
6587 (js2-set-face (match-beginning 1)
6588 (match-end 1)
6589 'js2-jsdoc-tag-face)
6590 (if (match-beginning 2)
6591 (if (save-excursion
6592 (goto-char (match-beginning 2))
6593 (= (char-after) ?{))
6594 (js2-set-face (1+ (match-beginning 2))
6595 (1- (match-end 2))
6596 'js2-jsdoc-type-face)
6597 (js2-set-face (match-beginning 2)
6598 (match-end 2)
6599 'js2-jsdoc-value-face)))
6600 (if (match-beginning 3)
6601 (js2-set-face (match-beginning 3)
6602 (match-end 3)
6603 'js2-jsdoc-value-face)))
6604
6605 (defun js2-highlight-jsdoc (ast)
6606 "Highlight doc comment tags."
6607 (let ((comments (js2-ast-root-comments ast))
6608 beg end)
6609 (save-excursion
6610 (dolist (node comments)
6611 (when (eq (js2-comment-node-format node) 'jsdoc)
6612 (setq beg (js2-node-abs-pos node)
6613 end (+ beg (js2-node-len node)))
6614 (save-restriction
6615 (narrow-to-region beg end)
6616 (dolist (re (list js2-jsdoc-param-tag-regexp
6617 js2-jsdoc-typed-tag-regexp
6618 js2-jsdoc-arg-tag-regexp
6619 js2-jsdoc-link-tag-regexp
6620 js2-jsdoc-see-tag-regexp
6621 js2-jsdoc-empty-tag-regexp))
6622 (goto-char beg)
6623 (while (re-search-forward re nil t)
6624 (js2-jsdoc-highlight-helper)))
6625 ;; simple highlighting for html tags
6626 (goto-char beg)
6627 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6628 (js2-set-face (match-beginning 1)
6629 (match-end 1)
6630 'js2-jsdoc-html-tag-delimiter-face)
6631 (js2-set-face (match-beginning 2)
6632 (match-end 2)
6633 'js2-jsdoc-html-tag-name-face)
6634 (js2-set-face (match-beginning 3)
6635 (match-end 3)
6636 'js2-jsdoc-html-tag-delimiter-face))))))))
6637
6638 (defun js2-highlight-assign-targets (node left right)
6639 "Highlight function properties and external variables."
6640 (let (leftpos end name)
6641 ;; highlight vars and props assigned function values
6642 (when (js2-function-node-p right)
6643 (cond
6644 ;; var foo = function() {...}
6645 ((js2-name-node-p left)
6646 (setq name left))
6647 ;; foo.bar.baz = function() {...}
6648 ((and (js2-prop-get-node-p left)
6649 (js2-name-node-p (js2-prop-get-node-right left)))
6650 (setq name (js2-prop-get-node-right left))))
6651 (when name
6652 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6653 (+ leftpos (js2-node-len name))
6654 'font-lock-function-name-face
6655 'record)))))
6656
6657 (defun js2-record-name-node (node)
6658 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6659 later. NODE must be a name node."
6660 (let (leftpos end)
6661 (push (list node js2-current-scope
6662 (setq leftpos (js2-node-abs-pos node))
6663 (setq end (+ leftpos (js2-node-len node))))
6664 js2-recorded-identifiers)))
6665
6666 (defun js2-highlight-undeclared-vars ()
6667 "After entire parse is finished, look for undeclared variable references.
6668 We have to wait until entire buffer is parsed, since JavaScript permits var
6669 decls to occur after they're used.
6670
6671 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6672 it is considered declared."
6673 (let (name)
6674 (dolist (entry js2-recorded-identifiers)
6675 (destructuring-bind (name-node scope pos end) entry
6676 (setq name (js2-name-node-name name-node))
6677 (unless (or (member name js2-global-externs)
6678 (member name js2-default-externs)
6679 (member name js2-additional-externs)
6680 (js2-get-defining-scope scope name))
6681 (js2-set-face pos end 'js2-external-variable-face 'record)
6682 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6683 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6684 (setq js2-recorded-identifiers nil)))
6685
6686 ;;; IMenu support
6687
6688 ;; We currently only support imenu, but eventually should support speedbar and
6689 ;; possibly other browsing mechanisms.
6690
6691 ;; The basic strategy is to identify function assignment targets of the form
6692 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6693 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6694 ;; for imenu after parsing is finished.
6695
6696 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6697 ;; JavaScript, and the general problem is undecidable. However, several forms
6698 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6699 ;; include:
6700
6701 ;; function foo() -- function declaration
6702 ;; foo = function() -- function expression assigned to variable
6703 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6704 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6705 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6706 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6707 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6708 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6709 ;; function foo() {function bar() {...}} -- nested function
6710 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6711
6712 ;; This list boils down to a few forms that can be combined recursively.
6713 ;; Top-level named function declarations include both the left-hand (name)
6714 ;; and the right-hand (function value) expressions needed to produce an imenu
6715 ;; entry. The other "right-hand" forms we need to look for are:
6716 ;; - functions declared as props/getters/setters in object literals
6717 ;; - nested named function declarations
6718 ;; The "left-hand" expressions that functions can be assigned to include:
6719 ;; - local/global variables
6720 ;; - nested property-get expressions like a.b.c.d
6721 ;; - element gets like foo[10] or foo['bar'] where the index
6722 ;; expression can be trivially converted to a property name. They
6723 ;; effectively then become property gets.
6724
6725 ;; All the different definition types are canonicalized into the form
6726 ;; foo.bar.baz = position-of-function-keyword
6727
6728 ;; We need to build a trie-like structure for imenu. As an example,
6729 ;; consider the following JavaScript code:
6730
6731 ;; a = function() {...} // function at position 5
6732 ;; b = function() {...} // function at position 25
6733 ;; foo = function() {...} // function at position 100
6734 ;; foo.bar = function() {...} // function at position 200
6735 ;; foo.bar.baz = function() {...} // function at position 300
6736 ;; foo.bar.zab = function() {...} // function at position 400
6737
6738 ;; During parsing we accumulate an entry for each definition in
6739 ;; the variable `js2-imenu-recorder', like so:
6740
6741 ;; '((fn a 5)
6742 ;; (fn b 25)
6743 ;; (fn foo 100)
6744 ;; (fn foo bar 200)
6745 ;; (fn foo bar baz 300)
6746 ;; (fn foo bar zab 400))
6747
6748 ;; Where 'fn' is the respective function node.
6749 ;; After parsing these entries are merged into this alist-trie:
6750
6751 ;; '((a . 1)
6752 ;; (b . 2)
6753 ;; (foo (<definition> . 3)
6754 ;; (bar (<definition> . 6)
6755 ;; (baz . 100)
6756 ;; (zab . 200))))
6757
6758 ;; Note the wacky need for a <definition> name. The token can be anything
6759 ;; that isn't a valid JavaScript identifier, because you might make foo
6760 ;; a function and then start setting properties on it that are also functions.
6761
6762 (defsubst js2-prop-node-name (node)
6763 "Return the name of a node that may be a property-get/property-name.
6764 If NODE is not a valid name-node, string-node or integral number-node,
6765 returns nil. Otherwise returns the string name/value of the node."
6766 (cond
6767 ((js2-name-node-p node)
6768 (js2-name-node-name node))
6769 ((js2-string-node-p node)
6770 (js2-string-node-value node))
6771 ((and (js2-number-node-p node)
6772 (string-match "^[0-9]+$" (js2-number-node-value node)))
6773 (js2-number-node-value node))
6774 ((js2-this-node-p node)
6775 "this")))
6776
6777 (defsubst js2-node-qname-component (node)
6778 "Return the name of this node, if it contributes to a qname.
6779 Returns nil if the node doesn't contribute."
6780 (copy-sequence
6781 (or (js2-prop-node-name node)
6782 (if (and (js2-function-node-p node)
6783 (js2-function-node-name node))
6784 (js2-name-node-name (js2-function-node-name node))))))
6785
6786 (defsubst js2-record-imenu-entry (fn-node qname pos)
6787 "Add an entry to `js2-imenu-recorder'.
6788 FN-NODE should be the current item's function node.
6789
6790 Associate FN-NODE with its QNAME for later lookup.
6791 This is used in postprocessing the chain list. For each chain, we find
6792 the parent function, look up its qname, then prepend a copy of it to the chain."
6793 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6794 (unless js2-imenu-function-map
6795 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6796 (puthash fn-node qname js2-imenu-function-map))
6797
6798 (defun js2-record-imenu-functions (node &optional var)
6799 "Record function definitions for imenu.
6800 NODE is a function node or an object literal.
6801 VAR, if non-nil, is the expression that NODE is being assigned to."
6802 (when js2-parse-ide-mode
6803 (let ((fun-p (js2-function-node-p node))
6804 qname left fname-node pos)
6805 (cond
6806 ;; non-anonymous function declaration?
6807 ((and fun-p
6808 (not var)
6809 (setq fname-node (js2-function-node-name node)))
6810 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6811 ;; for remaining forms, compute left-side tree branch first
6812 ((and var (setq qname (js2-compute-nested-prop-get var)))
6813 (cond
6814 ;; foo.bar.baz = function
6815 (fun-p
6816 (js2-record-imenu-entry node qname (js2-node-pos node)))
6817 ;; foo.bar.baz = object-literal
6818 ;; look for nested functions: {a: {b: function() {...} }}
6819 ((js2-object-node-p node)
6820 ;; Node position here is still absolute, since the parser
6821 ;; passes the assignment target and value expressions
6822 ;; to us before they are added as children of the assignment node.
6823 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6824
6825 (defun js2-compute-nested-prop-get (node)
6826 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6827 component nodes as a list. Otherwise return nil. Element-gets are treated
6828 as property-gets if the index expression is a string, or a positive integer."
6829 (let (left right head)
6830 (cond
6831 ((or (js2-name-node-p node)
6832 (js2-this-node-p node))
6833 (list node))
6834 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6835 ((js2-prop-get-node-p node) ; foo.bar
6836 (setq left (js2-prop-get-node-left node)
6837 right (js2-prop-get-node-right node))
6838 (if (setq head (js2-compute-nested-prop-get left))
6839 (nconc head (list right))))
6840 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6841 (setq left (js2-elem-get-node-target node)
6842 right (js2-elem-get-node-element node))
6843 (if (or (js2-string-node-p right) ; ['bar']
6844 (and (js2-number-node-p right) ; [10]
6845 (string-match "^[0-9]+$"
6846 (js2-number-node-value right))))
6847 (if (setq head (js2-compute-nested-prop-get left))
6848 (nconc head (list right))))))))
6849
6850 (defun js2-record-object-literal (node qname pos)
6851 "Recursively process an object literal looking for functions.
6852 NODE is an object literal that is the right-hand child of an assignment
6853 expression. QNAME is a list of nodes representing the assignment target,
6854 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6855 POS is the absolute position of the node.
6856 We do a depth-first traversal of NODE. For any functions we find,
6857 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6858 (let (left right prop-qname)
6859 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6860 (let ((left (js2-infix-node-left e))
6861 ;; Element positions are relative to the parent position.
6862 (pos (+ pos (js2-node-pos e))))
6863 (cond
6864 ;; foo: function() {...}
6865 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6866 (when (js2-prop-node-name left)
6867 ;; As a policy decision, we record the position of the property,
6868 ;; not the position of the `function' keyword, since the property
6869 ;; is effectively the name of the function.
6870 (js2-record-imenu-entry right (append qname (list left)) pos)))
6871 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6872 ((js2-object-node-p right)
6873 (js2-record-object-literal right
6874 (append qname (list (js2-infix-node-left e)))
6875 (+ pos (js2-node-pos right)))))))))
6876
6877 (defun js2-record-assign-functions (init target)
6878 "Record the functions involved in the assignment for imenu.
6879 TARGET is the target node, INIT is the value node."
6880 (cond
6881 ((or (js2-object-node-p init)
6882 (js2-function-node-p init))
6883 (js2-record-imenu-functions init target))
6884 ((js2-call-node-p init)
6885 ;; Module pattern: var foobs = (function(a) {return {fib: fun...}})(b);
6886 ;; We record the returned hash as belonging to the named module, and prefix
6887 ;; any functions defined inside IIFE with the module name.
6888 (let ((callt (js2-call-node-target init)))
6889 ;; Just basic call form: (function() {...})();
6890 ;; TODO: Handle variations without duplicating `js2-wrapper-function-p'?
6891 (when (and (js2-paren-node-p callt)
6892 (js2-function-node-p (js2-paren-node-expr callt)))
6893 (let* ((fn (js2-paren-node-expr callt))
6894 (blk (js2-function-node-body fn))
6895 (ret (car (last (js2-block-node-kids blk)))))
6896 (when (and (js2-return-node-p ret)
6897 (js2-object-node-p (js2-return-node-retval ret)))
6898 ;; TODO: Map function names when revealing module pattern is used.
6899 (let ((retval (js2-return-node-retval ret)))
6900 (js2-record-object-literal retval
6901 (js2-compute-nested-prop-get target)
6902 (js2-node-abs-pos retval)))
6903 (js2-record-imenu-functions fn target))))))))
6904
6905 (defsubst js2-node-top-level-decl-p (node)
6906 "Return t if NODE's name is defined in the top-level scope.
6907 Also returns t if NODE's name is not defined in any scope, since it implies
6908 that it's an external variable, which must also be in the top-level scope."
6909 (let* ((name (js2-prop-node-name node))
6910 (this-scope (js2-node-get-enclosing-scope node))
6911 defining-scope)
6912 (cond
6913 ((js2-this-node-p node)
6914 nil)
6915 ((null this-scope)
6916 t)
6917 ((setq defining-scope (js2-get-defining-scope this-scope name))
6918 (js2-ast-root-p defining-scope))
6919 (t t))))
6920
6921 (defsubst js2-wrapper-function-p (node)
6922 "Returns t if NODE is a function expression that's immediately invoked.
6923 NODE must be `js2-function-node'."
6924 (let ((parent (js2-node-parent node)))
6925 (or
6926 ;; function(){...}();
6927 (js2-call-node-p parent)
6928 (and (js2-paren-node-p parent)
6929 ;; (function(){...})();
6930 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6931 ;; (function(){...}).call(this);
6932 (and (js2-prop-get-node-p parent)
6933 (member (js2-name-node-name (js2-prop-get-node-right parent))
6934 '("call" "apply"))
6935 (js2-call-node-p (js2-node-parent parent))))))))
6936
6937 (defun js2-browse-postprocess-chains (entries)
6938 "Modify function-declaration name chains after parsing finishes.
6939 Some of the information is only available after the parse tree is complete.
6940 For instance, processing a nested scope requires a parent function node."
6941 (let (result head fn current-fn parent-qname qname p elem)
6942 (dolist (entry entries)
6943 ;; function node goes first
6944 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6945 ;; Examine head's defining scope:
6946 ;; Pre-processed chain, or top-level/external, keep as-is.
6947 (if (or (stringp head) (js2-node-top-level-decl-p head))
6948 (push chain result)
6949 (when (js2-this-node-p head)
6950 (setq chain (cdr chain))) ; discard this-node
6951 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6952 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6953 (when (eq parent-qname 'not-found)
6954 ;; anonymous function expressions are not recorded
6955 ;; during the parse, so we need to handle this case here
6956 (setq parent-qname
6957 (if (js2-wrapper-function-p fn)
6958 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6959 (if (js2-ast-root-p grandparent)
6960 nil
6961 (gethash grandparent js2-imenu-function-map 'skip)))
6962 'skip))
6963 (puthash fn parent-qname js2-imenu-function-map))
6964 (unless (eq parent-qname 'skip)
6965 ;; prefix parent fn qname to this chain.
6966 (let ((qname (append parent-qname chain)))
6967 (puthash current-fn (butlast qname) js2-imenu-function-map)
6968 (push qname result)))))))
6969 ;; finally replace each node in each chain with its name.
6970 (dolist (chain result)
6971 (setq p chain)
6972 (while p
6973 (if (js2-node-p (setq elem (car p)))
6974 (setcar p (js2-node-qname-component elem)))
6975 (setq p (cdr p))))
6976 result))
6977
6978 ;; Merge name chains into a trie-like tree structure of nested lists.
6979 ;; To simplify construction of the trie, we first build it out using the rule
6980 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6981 ;; [key, num-or-list]. The second element can be a number; if so, this key
6982 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6983 ;; associated with the key at this level.) Otherwise the second element is
6984 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6985 ;; a simple recursive formulation.
6986 ;;
6987 ;; js2-mode is building the data structure for imenu. The imenu documentation
6988 ;; claims that it's the structure above, but in practice it wants the children
6989 ;; at the same list level as the key for that level, which is how I've drawn
6990 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6991 ;; list wrapper around the children at each level.
6992 ;;
6993 ;; A completed nested imenu-alist entry looks like this:
6994 ;; '(("foo"
6995 ;; ("<definition>" . 7)
6996 ;; ("bar"
6997 ;; ("a" . 40)
6998 ;; ("b" . 60))))
6999 ;;
7000 ;; In particular, the documentation for `imenu--index-alist' says that
7001 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7002 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7003
7004 (defun js2-treeify (lst)
7005 "Convert (a b c d) to (a ((b ((c d)))))"
7006 (if (null (cddr lst)) ; list length <= 2
7007 lst
7008 (list (car lst) (list (js2-treeify (cdr lst))))))
7009
7010 (defun js2-build-alist-trie (chains trie)
7011 "Merge declaration name chains into a trie-like alist structure for imenu.
7012 CHAINS is the qname chain list produced during parsing. TRIE is a
7013 list of elements built up so far."
7014 (let (head tail pos branch kids)
7015 (dolist (chain chains)
7016 (setq head (car chain)
7017 tail (cdr chain)
7018 pos (if (numberp (car tail)) (car tail))
7019 branch (js2-find-if (lambda (n)
7020 (string= (car n) head))
7021 trie)
7022 kids (second branch))
7023 (cond
7024 ;; case 1: this key isn't in the trie yet
7025 ((null branch)
7026 (if trie
7027 (setcdr (last trie) (list (js2-treeify chain)))
7028 (setq trie (list (js2-treeify chain)))))
7029 ;; case 2: key is present with a single number entry: replace w/ list
7030 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7031 ;; ("<definition>" 20)))
7032 ((numberp kids)
7033 (setcar (cdr branch)
7034 (list (list "<definition-1>" kids)
7035 (if pos
7036 (list "<definition-2>" pos)
7037 (js2-treeify tail)))))
7038 ;; case 3: key is there (with kids), and we're a number entry
7039 (pos
7040 (setcdr (last kids)
7041 (list
7042 (list (format "<definition-%d>"
7043 (1+ (loop for kid in kids
7044 count (eq ?< (aref (car kid) 0)))))
7045 pos))))
7046 ;; case 4: key is there with kids, need to merge in our chain
7047 (t
7048 (js2-build-alist-trie (list tail) kids))))
7049 trie))
7050
7051 (defun js2-flatten-trie (trie)
7052 "Convert TRIE to imenu-format.
7053 Recurses through nodes, and for each one whose second element is a list,
7054 appends the list's flattened elements to the current element. Also
7055 changes the tails into conses. For instance, this pre-flattened trie
7056
7057 '(a ((b 20)
7058 (c ((d 30)
7059 (e 40)))))
7060
7061 becomes
7062
7063 '(a (b . 20)
7064 (c (d . 30)
7065 (e . 40)))
7066
7067 Note that the root of the trie has no key, just a list of chains.
7068 This is also true for the value of any key with multiple children,
7069 e.g. key 'c' in the example above."
7070 (cond
7071 ((listp (car trie))
7072 (mapcar #'js2-flatten-trie trie))
7073 (t
7074 (if (numberp (second trie))
7075 (cons (car trie) (second trie))
7076 ;; else pop list and append its kids
7077 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7078
7079 (defun js2-build-imenu-index ()
7080 "Turn `js2-imenu-recorder' into an imenu data structure."
7081 (unless (eq js2-imenu-recorder 'empty)
7082 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7083 (result (js2-build-alist-trie chains nil)))
7084 (js2-flatten-trie result))))
7085
7086 (defun js2-test-print-chains (chains)
7087 "Print a list of qname chains.
7088 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7089 i.e. one or more nodes, and an integer position as the list tail."
7090 (mapconcat (lambda (chain)
7091 (concat "("
7092 (mapconcat (lambda (elem)
7093 (if (js2-node-p elem)
7094 (or (js2-node-qname-component elem)
7095 "nil")
7096 (number-to-string elem)))
7097 chain
7098 " ")
7099 ")"))
7100 chains
7101 "\n"))
7102
7103 ;;; Parser
7104
7105 (defconst js2-version "1.8.0"
7106 "Version of JavaScript supported, plus minor js2 version.")
7107
7108 (defmacro js2-record-face (face)
7109 "Record a style run of FACE for the current token."
7110 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7111
7112 (defsubst js2-node-end (n)
7113 "Computes the absolute end of node N.
7114 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7115 is only true until the node is added to its parent; i.e., while parsing."
7116 (+ (js2-node-pos n)
7117 (js2-node-len n)))
7118
7119 (defsubst js2-record-comment ()
7120 "Record a comment in `js2-scanned-comments'."
7121 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7122 :format js2-ts-comment-type)
7123 js2-scanned-comments)
7124 (when js2-parse-ide-mode
7125 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7126 'font-lock-doc-face
7127 'font-lock-comment-face))
7128 (when (memq js2-ts-comment-type '(html preprocessor))
7129 ;; Tell cc-engine the bounds of the comment.
7130 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7131
7132 ;; This function is called depressingly often, so it should be fast.
7133 ;; Most of the time it's looking at the same token it peeked before.
7134 (defsubst js2-peek-token ()
7135 "Returns the next token without consuming it.
7136 If previous token was consumed, calls scanner to get new token.
7137 If previous token was -not- consumed, returns it (idempotent).
7138
7139 This function will not return a newline (js2-EOL) - instead, it
7140 gobbles newlines until it finds a non-newline token, and flags
7141 that token as appearing just after a newline.
7142
7143 This function will also not return a js2-COMMENT. Instead, it
7144 records comments found in `js2-scanned-comments'. If the token
7145 returned by this function immediately follows a jsdoc comment,
7146 the token is flagged as such.
7147
7148 Note that this function always returned the un-flagged token!
7149 The flags, if any, are saved in `js2-current-flagged-token'."
7150 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7151 js2-current-token ; most common case - return already-peeked token
7152 (let ((tt (js2-get-token)) ; call scanner
7153 saw-eol
7154 face)
7155 ;; process comments and whitespace
7156 (while (or (= tt js2-EOL)
7157 (= tt js2-COMMENT))
7158 (if (= tt js2-EOL)
7159 (setq saw-eol t)
7160 (setq saw-eol nil)
7161 (if js2-record-comments
7162 (js2-record-comment)))
7163 (setq tt (js2-get-token))) ; call scanner
7164 (setq js2-current-token tt
7165 js2-current-flagged-token (if saw-eol
7166 (logior tt js2-ti-after-eol)
7167 tt))
7168 ;; perform lexical fontification as soon as token is scanned
7169 (when js2-parse-ide-mode
7170 (cond
7171 ((minusp tt)
7172 (js2-record-face 'js2-error-face))
7173 ((setq face (aref js2-kwd-tokens tt))
7174 (js2-record-face face))
7175 ((and (= tt js2-NAME)
7176 (equal js2-ts-string "undefined"))
7177 (js2-record-face 'font-lock-constant-face))))
7178 tt))) ; return unflagged token
7179
7180 (defsubst js2-peek-flagged-token ()
7181 "Returns the current token along with any flags set for it."
7182 (js2-peek-token)
7183 js2-current-flagged-token)
7184
7185 (defsubst js2-consume-token ()
7186 (setq js2-current-flagged-token js2-EOF))
7187
7188 (defsubst js2-next-token ()
7189 (prog1
7190 (js2-peek-token)
7191 (js2-consume-token)))
7192
7193 (defsubst js2-next-flagged-token ()
7194 (js2-peek-token)
7195 (prog1 js2-current-flagged-token
7196 (js2-consume-token)))
7197
7198 (defsubst js2-match-token (match)
7199 "Consume and return t if next token matches MATCH, a bytecode.
7200 Returns nil and consumes nothing if MATCH is not the next token."
7201 (if (/= (js2-peek-token) match)
7202 nil
7203 (js2-consume-token)
7204 t))
7205
7206 (defsubst js2-valid-prop-name-token (tt)
7207 (or (= tt js2-NAME)
7208 (and js2-allow-keywords-as-property-names
7209 (plusp tt)
7210 (aref js2-kwd-tokens tt))))
7211
7212 (defsubst js2-match-prop-name ()
7213 "Consume token and return t if next token is a valid property name.
7214 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7215 is non-nil and it's a keyword token."
7216 (if (js2-valid-prop-name-token (js2-peek-token))
7217 (progn
7218 (js2-consume-token)
7219 t)
7220 nil))
7221
7222 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7223 (if (js2-match-prop-name)
7224 t
7225 (js2-report-error msg-id nil pos len)
7226 nil))
7227
7228 (defsubst js2-peek-token-or-eol ()
7229 "Return js2-EOL if the current token immediately follows a newline.
7230 Else returns the current token. Used in situations where we don't
7231 consider certain token types valid if they are preceded by a newline.
7232 One example is the postfix ++ or -- operator, which has to be on the
7233 same line as its operand."
7234 (let ((tt (js2-peek-token)))
7235 ;; Check for last peeked token flags
7236 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7237 js2-EOL
7238 tt)))
7239
7240 (defsubst js2-set-check-for-label ()
7241 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7242 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7243
7244 (defsubst js2-must-match (token msg-id &optional pos len)
7245 "Match next token to token code TOKEN, or record a syntax error.
7246 MSG-ID is the error message to report if the match fails.
7247 Returns t on match, nil if no match."
7248 (if (js2-match-token token)
7249 t
7250 (js2-report-error msg-id nil pos len)
7251 nil))
7252
7253 (defsubst js2-inside-function ()
7254 (plusp js2-nesting-of-function))
7255
7256 (defsubst js2-set-requires-activation ()
7257 (if (js2-function-node-p js2-current-script-or-fn)
7258 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7259
7260 (defsubst js2-check-activation-name (name token)
7261 (when (js2-inside-function)
7262 ;; skip language-version 1.2 check from Rhino
7263 (if (or (string= "arguments" name)
7264 (and js2-compiler-activation-names ; only used in codegen
7265 (gethash name js2-compiler-activation-names)))
7266 (js2-set-requires-activation))))
7267
7268 (defsubst js2-set-is-generator ()
7269 (if (js2-function-node-p js2-current-script-or-fn)
7270 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7271
7272 (defsubst js2-must-have-xml ()
7273 (unless js2-compiler-xml-available
7274 (js2-report-error "msg.XML.not.available")))
7275
7276 (defsubst js2-push-scope (scope)
7277 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7278 (assert (js2-scope-p scope))
7279 (assert (null (js2-scope-parent-scope scope)))
7280 (assert (not (eq js2-current-scope scope)))
7281 (setf (js2-scope-parent-scope scope) js2-current-scope
7282 js2-current-scope scope))
7283
7284 (defsubst js2-pop-scope ()
7285 (setq js2-current-scope
7286 (js2-scope-parent-scope js2-current-scope)))
7287
7288 (defsubst js2-enter-loop (loop-node)
7289 (push loop-node js2-loop-set)
7290 (push loop-node js2-loop-and-switch-set)
7291 (js2-push-scope loop-node)
7292 ;; Tell the current labeled statement (if any) its statement,
7293 ;; and set the jump target of the first label to the loop.
7294 ;; These are used in `js2-parse-continue' to verify that the
7295 ;; continue target is an actual labeled loop. (And for codegen.)
7296 (when js2-labeled-stmt
7297 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7298 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7299 js2-labeled-stmt))) loop-node)))
7300
7301 (defsubst js2-exit-loop ()
7302 (pop js2-loop-set)
7303 (pop js2-loop-and-switch-set)
7304 (js2-pop-scope))
7305
7306 (defsubst js2-enter-switch (switch-node)
7307 (push switch-node js2-loop-and-switch-set))
7308
7309 (defsubst js2-exit-switch ()
7310 (pop js2-loop-and-switch-set))
7311
7312 (defun js2-parse (&optional buf cb)
7313 "Tells the js2 parser to parse a region of JavaScript.
7314
7315 BUF is a buffer or buffer name containing the code to parse.
7316 Call `narrow-to-region' first to parse only part of the buffer.
7317
7318 The returned AST root node is given some additional properties:
7319 `node-count' - total number of nodes in the AST
7320 `buffer' - BUF. The buffer it refers to may change or be killed,
7321 so the value is not necessarily reliable.
7322
7323 An optional callback CB can be specified to report parsing
7324 progress. If `(functionp CB)' returns t, it will be called with
7325 the current line number once before parsing begins, then again
7326 each time the lexer reaches a new line number.
7327
7328 CB can also be a list of the form `(symbol cb ...)' to specify
7329 multiple callbacks with different criteria. Each symbol is a
7330 criterion keyword, and the following element is the callback to
7331 call
7332
7333 :line - called whenever the line number changes
7334 :token - called for each new token consumed
7335
7336 The list of criteria could be extended to include entering or
7337 leaving a statement, an expression, or a function definition."
7338 (if (and cb (not (functionp cb)))
7339 (error "criteria callbacks not yet implemented"))
7340 (let ((inhibit-point-motion-hooks t)
7341 (js2-compiler-xml-available (>= js2-language-version 160))
7342 ;; This is a recursive-descent parser, so give it a big stack.
7343 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7344 (max-specpdl-size (max max-specpdl-size 3000))
7345 (case-fold-search nil)
7346 ast)
7347 (message nil) ; clear any error message from previous parse
7348 (save-excursion
7349 (when buf (set-buffer buf))
7350 (setq js2-scanned-comments nil
7351 js2-parsed-errors nil
7352 js2-parsed-warnings nil
7353 js2-imenu-recorder nil
7354 js2-imenu-function-map nil
7355 js2-label-set nil)
7356 (js2-init-scanner)
7357 (setq ast (js2-with-unmodifying-text-property-changes
7358 (js2-do-parse)))
7359 (unless js2-ts-hit-eof
7360 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7361 (setf (js2-ast-root-errors ast) js2-parsed-errors
7362 (js2-ast-root-warnings ast) js2-parsed-warnings)
7363 ;; if we didn't find any declarations, put a dummy in this list so we
7364 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7365 (unless js2-imenu-recorder
7366 (setq js2-imenu-recorder 'empty))
7367 (run-hooks 'js2-parse-finished-hook)
7368 ast)))
7369
7370 ;; Corresponds to Rhino's Parser.parse() method.
7371 (defun js2-do-parse ()
7372 "Parse current buffer starting from current point.
7373 Scanner should be initialized."
7374 (let ((pos js2-ts-cursor)
7375 (end js2-ts-cursor) ; in case file is empty
7376 root n tt)
7377 ;; initialize buffer-local parsing vars
7378 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7379 js2-current-script-or-fn root
7380 js2-current-scope root
7381 js2-current-flagged-token js2-EOF
7382 js2-nesting-of-function 0
7383 js2-labeled-stmt nil
7384 js2-recorded-identifiers nil) ; for js2-highlight
7385 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7386 (if (= tt js2-FUNCTION)
7387 (progn
7388 (js2-consume-token)
7389 (setq n (js2-parse-function (if js2-called-by-compile-function
7390 'FUNCTION_EXPRESSION
7391 'FUNCTION_STATEMENT))))
7392 ;; not a function - parse a statement
7393 (setq n (js2-parse-statement)))
7394 ;; add function or statement to script
7395 (setq end (js2-node-end n))
7396 (js2-block-node-push root n))
7397 ;; add comments to root in lexical order
7398 (when js2-scanned-comments
7399 ;; if we find a comment beyond end of normal kids, use its end
7400 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7401 (dolist (comment js2-scanned-comments)
7402 (push comment (js2-ast-root-comments root))
7403 (js2-node-add-children root comment)))
7404 (setf (js2-node-len root) (- end pos))
7405 ;; Give extensions a chance to muck with things before highlighting starts.
7406 (let ((js2-additional-externs js2-additional-externs))
7407 (dolist (callback js2-post-parse-callbacks)
7408 (funcall callback))
7409 (js2-highlight-undeclared-vars))
7410 root))
7411
7412 (defun js2-function-parser ()
7413 (js2-consume-token)
7414 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7415
7416 (defun js2-parse-function-closure-body (fn-node)
7417 "Parse a JavaScript 1.8 function closure body."
7418 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7419 (if js2-ts-hit-eof
7420 (js2-report-error "msg.no.brace.body" nil
7421 (js2-node-pos fn-node)
7422 (- js2-ts-cursor (js2-node-pos fn-node)))
7423 (js2-node-add-children fn-node
7424 (setf (js2-function-node-body fn-node)
7425 (js2-parse-expr t))))))
7426
7427 (defun js2-parse-function-body (fn-node)
7428 (js2-must-match js2-LC "msg.no.brace.body"
7429 (js2-node-pos fn-node)
7430 (- js2-ts-cursor (js2-node-pos fn-node)))
7431 (let ((pos js2-token-beg) ; LC position
7432 (pn (make-js2-block-node)) ; starts at LC position
7433 tt
7434 end)
7435 (incf js2-nesting-of-function)
7436 (unwind-protect
7437 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7438 (= tt js2-EOF)
7439 (= tt js2-RC)))
7440 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7441 (js2-parse-statement)
7442 (js2-consume-token)
7443 (js2-parse-function 'FUNCTION_STATEMENT))))
7444 (decf js2-nesting-of-function))
7445 (setq end js2-token-end) ; assume no curly and leave at current token
7446 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7447 (setq end js2-token-end))
7448 (setf (js2-node-pos pn) pos
7449 (js2-node-len pn) (- end pos))
7450 (setf (js2-function-node-body fn-node) pn)
7451 (js2-node-add-children fn-node pn)
7452 pn))
7453
7454 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7455 "Declare and fontify destructuring parameters inside NODE.
7456 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7457 (cond
7458 ((js2-name-node-p node)
7459 (let (leftpos)
7460 (js2-define-symbol decl-type (js2-name-node-name node)
7461 node ignore-not-in-block)
7462 (when face
7463 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7464 (+ leftpos (js2-node-len node))
7465 face 'record))))
7466 ((js2-object-node-p node)
7467 (dolist (elem (js2-object-node-elems node))
7468 (js2-define-destruct-symbols
7469 (if (js2-object-prop-node-p elem)
7470 (js2-object-prop-node-right elem)
7471 ;; abbreviated destructuring {a, b}
7472 elem)
7473 decl-type face ignore-not-in-block)))
7474 ((js2-array-node-p node)
7475 (dolist (elem (js2-array-node-elems node))
7476 (when elem
7477 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7478 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7479 (js2-node-len node)))))
7480
7481 (defun js2-parse-function-params (fn-node pos)
7482 (if (js2-match-token js2-RP)
7483 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7484 (let (params len param)
7485 (loop for tt = (js2-peek-token)
7486 do
7487 (cond
7488 ;; destructuring param
7489 ((or (= tt js2-LB) (= tt js2-LC))
7490 (setq param (js2-parse-primary-expr-lhs))
7491 (js2-define-destruct-symbols param
7492 js2-LP
7493 'js2-function-param-face)
7494 (push param params))
7495 ;; simple name
7496 (t
7497 (js2-must-match js2-NAME "msg.no.parm")
7498 (js2-record-face 'js2-function-param-face)
7499 (setq param (js2-create-name-node))
7500 (js2-define-symbol js2-LP js2-ts-string param)
7501 (push param params)))
7502 while
7503 (js2-match-token js2-COMMA))
7504 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7505 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7506 (dolist (p params)
7507 (js2-node-add-children fn-node p)
7508 (push p (js2-function-node-params fn-node))))))
7509
7510 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7511 "Possibly show inconsistent-return warning.
7512 Last token scanned is the close-curly for the function body."
7513 (when (and js2-mode-show-strict-warnings
7514 js2-strict-inconsistent-return-warning
7515 (not (js2-has-consistent-return-usage
7516 (js2-function-node-body fn-node))))
7517 ;; Have it extend from close-curly to bol or beginning of block.
7518 (let ((pos (save-excursion
7519 (goto-char js2-token-end)
7520 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7521 (point-at-bol))))
7522 (end js2-token-end))
7523 (if (plusp (js2-name-node-length name))
7524 (js2-add-strict-warning "msg.no.return.value"
7525 (js2-name-node-name name) pos end)
7526 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7527
7528 (defun js2-parse-function (function-type)
7529 "Function parser. FUNCTION-TYPE is a symbol."
7530 (let ((pos js2-token-beg) ; start of 'function' keyword
7531 name
7532 name-beg
7533 name-end
7534 fn-node
7535 lp
7536 (synthetic-type function-type)
7537 member-expr-node)
7538 ;; parse function name, expression, or non-name (anonymous)
7539 (cond
7540 ;; function foo(...)
7541 ((js2-match-token js2-NAME)
7542 (setq name (js2-create-name-node t)
7543 name-beg js2-token-beg
7544 name-end js2-token-end)
7545 (unless (js2-match-token js2-LP)
7546 (when js2-allow-member-expr-as-function-name
7547 ;; function foo.bar(...)
7548 (setq member-expr-node name
7549 name nil
7550 member-expr-node (js2-parse-member-expr-tail
7551 nil member-expr-node)))
7552 (js2-must-match js2-LP "msg.no.paren.parms")))
7553 ((js2-match-token js2-LP)
7554 nil) ; anonymous function: leave name as null
7555 (t
7556 ;; function random-member-expr(...)
7557 (when js2-allow-member-expr-as-function-name
7558 ;; Note that memberExpr can not start with '(' like
7559 ;; in function (1+2).toString(), because 'function (' already
7560 ;; processed as anonymous function
7561 (setq member-expr-node (js2-parse-member-expr)))
7562 (js2-must-match js2-LP "msg.no.paren.parms")))
7563 (if (= js2-current-token js2-LP) ; eventually matched LP?
7564 (setq lp js2-token-beg))
7565 (if member-expr-node
7566 (progn
7567 (setq synthetic-type 'FUNCTION_EXPRESSION)
7568 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7569 (if name
7570 (js2-set-face name-beg name-end
7571 'font-lock-function-name-face 'record)))
7572 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7573 (plusp (js2-name-node-length name)))
7574 ;; Function statements define a symbol in the enclosing scope
7575 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7576 (setf fn-node (make-js2-function-node :pos pos
7577 :name name
7578 :form function-type
7579 :lp (if lp (- lp pos))))
7580 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7581 ;; 1. Nested functions are not affected by the dynamic scope flag
7582 ;; as dynamic scope is already a parent of their scope.
7583 ;; 2. Functions defined under the with statement also immune to
7584 ;; this setup, in which case dynamic scope is ignored in favor
7585 ;; of the with object.
7586 (setf (js2-function-node-ignore-dynamic fn-node) t))
7587 ;; dynamically bind all the per-function variables
7588 (let ((js2-current-script-or-fn fn-node)
7589 (js2-current-scope fn-node)
7590 (js2-nesting-of-with 0)
7591 (js2-end-flags 0)
7592 js2-label-set
7593 js2-loop-set
7594 js2-loop-and-switch-set)
7595 (js2-parse-function-params fn-node pos)
7596 (if (and (>= js2-language-version 180)
7597 (/= (js2-peek-token) js2-LC))
7598 (js2-parse-function-closure-body fn-node)
7599 (js2-parse-function-body fn-node))
7600 (if name
7601 (js2-node-add-children fn-node name))
7602 (js2-check-inconsistent-return-warning fn-node name)
7603 ;; Function expressions define a name only in the body of the
7604 ;; function, and only if not hidden by a parameter name
7605 (if (and name
7606 (eq synthetic-type 'FUNCTION_EXPRESSION)
7607 (null (js2-scope-get-symbol js2-current-scope
7608 (js2-name-node-name name))))
7609 (js2-define-symbol js2-FUNCTION
7610 (js2-name-node-name name)
7611 fn-node))
7612 (if (and name
7613 (not (eq function-type 'FUNCTION_EXPRESSION)))
7614 (js2-record-imenu-functions fn-node)))
7615 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7616 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7617 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7618 ;; We wait until after parsing the function to set its parent scope,
7619 ;; since `js2-define-symbol' needs the defining-scope check to stop
7620 ;; at the function boundary when checking for redeclarations.
7621 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7622 fn-node))
7623
7624 (defun js2-parse-statements (&optional parent)
7625 "Parse a statement list. Last token consumed must be js2-LC.
7626
7627 PARENT can be a `js2-block-node', in which case the statements are
7628 appended to PARENT. Otherwise a new `js2-block-node' is created
7629 and returned.
7630
7631 This function does not match the closing js2-RC: the caller
7632 matches the RC so it can provide a suitable error message if not
7633 matched. This means it's up to the caller to set the length of
7634 the node to include the closing RC. The node start pos is set to
7635 the absolute buffer start position, and the caller should fix it
7636 up to be relative to the parent node. All children of this block
7637 node are given relative start positions and correct lengths."
7638 (let ((pn (or parent (make-js2-block-node)))
7639 tt)
7640 (setf (js2-node-pos pn) js2-token-beg)
7641 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7642 (/= tt js2-RC))
7643 (js2-block-node-push pn (js2-parse-statement)))
7644 pn))
7645
7646 (defun js2-parse-statement ()
7647 (let (tt pn beg end)
7648 ;; coarse-grained user-interrupt check - needs work
7649 (and js2-parse-interruptable-p
7650 (zerop (% (incf js2-parse-stmt-count)
7651 js2-statements-per-pause))
7652 (input-pending-p)
7653 (throw 'interrupted t))
7654 (setq pn (js2-statement-helper))
7655 ;; no-side-effects warning check
7656 (unless (js2-node-has-side-effects pn)
7657 (setq end (js2-node-end pn))
7658 (save-excursion
7659 (goto-char end)
7660 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7661 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7662 pn))
7663
7664 ;; These correspond to the switch cases in Parser.statementHelper
7665 (defconst js2-parsers
7666 (let ((parsers (make-vector js2-num-tokens
7667 #'js2-parse-expr-stmt)))
7668 (aset parsers js2-BREAK #'js2-parse-break)
7669 (aset parsers js2-CONST #'js2-parse-const-var)
7670 (aset parsers js2-CONTINUE #'js2-parse-continue)
7671 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7672 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7673 (aset parsers js2-DO #'js2-parse-do)
7674 (aset parsers js2-FOR #'js2-parse-for)
7675 (aset parsers js2-FUNCTION #'js2-function-parser)
7676 (aset parsers js2-IF #'js2-parse-if)
7677 (aset parsers js2-LC #'js2-parse-block)
7678 (aset parsers js2-LET #'js2-parse-let-stmt)
7679 (aset parsers js2-NAME #'js2-parse-name-or-label)
7680 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7681 (aset parsers js2-SEMI #'js2-parse-semi)
7682 (aset parsers js2-SWITCH #'js2-parse-switch)
7683 (aset parsers js2-THROW #'js2-parse-throw)
7684 (aset parsers js2-TRY #'js2-parse-try)
7685 (aset parsers js2-VAR #'js2-parse-const-var)
7686 (aset parsers js2-WHILE #'js2-parse-while)
7687 (aset parsers js2-WITH #'js2-parse-with)
7688 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7689 parsers)
7690 "A vector mapping token types to parser functions.")
7691
7692 (defsubst js2-parse-warn-missing-semi (beg end)
7693 (and js2-mode-show-strict-warnings
7694 js2-strict-missing-semi-warning
7695 (js2-add-strict-warning
7696 "msg.missing.semi" nil
7697 ;; back up to beginning of statement or line
7698 (max beg (save-excursion
7699 (goto-char end)
7700 (point-at-bol)))
7701 end)))
7702
7703 (defconst js2-no-semi-insertion
7704 (list js2-IF
7705 js2-SWITCH
7706 js2-WHILE
7707 js2-DO
7708 js2-FOR
7709 js2-TRY
7710 js2-WITH
7711 js2-LC
7712 js2-ERROR
7713 js2-SEMI
7714 js2-FUNCTION)
7715 "List of tokens that don't do automatic semicolon insertion.")
7716
7717 (defconst js2-autoinsert-semi-and-warn
7718 (list js2-ERROR js2-EOF js2-RC))
7719
7720 (defun js2-statement-helper ()
7721 (let* ((tt (js2-peek-token))
7722 (first-tt tt)
7723 (beg js2-token-beg)
7724 (parser (if (= tt js2-ERROR)
7725 #'js2-parse-semi
7726 (aref js2-parsers tt)))
7727 pn
7728 tt-flagged)
7729 ;; If the statement is set, then it's been told its label by now.
7730 (and js2-labeled-stmt
7731 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7732 (setq js2-labeled-stmt nil))
7733 (setq pn (funcall parser))
7734 ;; Don't do auto semi insertion for certain statement types.
7735 (unless (or (memq first-tt js2-no-semi-insertion)
7736 (js2-labeled-stmt-node-p pn))
7737 (js2-auto-insert-semicolon pn))
7738 pn))
7739
7740 (defun js2-auto-insert-semicolon (pn)
7741 (let* ((tt-flagged (js2-peek-flagged-token))
7742 (tt (logand tt-flagged js2-clear-ti-mask))
7743 (pos (js2-node-pos pn)))
7744 (cond
7745 ((= tt js2-SEMI)
7746 ;; Consume ';' as a part of expression
7747 (js2-consume-token)
7748 ;; extend the node bounds to include the semicolon.
7749 (setf (js2-node-len pn) (- js2-token-end pos)))
7750 ((memq tt js2-autoinsert-semi-and-warn)
7751 ;; Autoinsert ;
7752 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7753 (t
7754 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7755 ;; Report error if no EOL or autoinsert ';' otherwise
7756 (js2-report-error "msg.no.semi.stmt")
7757 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7758
7759 (defun js2-parse-condition ()
7760 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7761 The parens are discarded and the expression node is returned.
7762 The `pos' field of the return value is set to an absolute position
7763 that must be fixed up by the caller.
7764 Return value is a list (EXPR LP RP), with absolute paren positions."
7765 (let (pn lp rp)
7766 (if (js2-must-match js2-LP "msg.no.paren.cond")
7767 (setq lp js2-token-beg))
7768 (setq pn (js2-parse-expr))
7769 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7770 (setq rp js2-token-beg))
7771 ;; Report strict warning on code like "if (a = 7) ..."
7772 (if (and js2-strict-cond-assign-warning
7773 (js2-assign-node-p pn))
7774 (js2-add-strict-warning "msg.equal.as.assign" nil
7775 (js2-node-pos pn)
7776 (+ (js2-node-pos pn)
7777 (js2-node-len pn))))
7778 (list pn lp rp)))
7779
7780 (defun js2-parse-if ()
7781 "Parser for if-statement. Last matched token must be js2-IF."
7782 (let ((pos js2-token-beg)
7783 cond
7784 if-true
7785 if-false
7786 else-pos
7787 end
7788 pn)
7789 (js2-consume-token)
7790 (setq cond (js2-parse-condition)
7791 if-true (js2-parse-statement)
7792 if-false (if (js2-match-token js2-ELSE)
7793 (progn
7794 (setq else-pos (- js2-token-beg pos))
7795 (js2-parse-statement)))
7796 end (js2-node-end (or if-false if-true))
7797 pn (make-js2-if-node :pos pos
7798 :len (- end pos)
7799 :condition (car cond)
7800 :then-part if-true
7801 :else-part if-false
7802 :else-pos else-pos
7803 :lp (js2-relpos (second cond) pos)
7804 :rp (js2-relpos (third cond) pos)))
7805 (js2-node-add-children pn (car cond) if-true if-false)
7806 pn))
7807
7808 (defun js2-parse-switch ()
7809 "Parser for if-statement. Last matched token must be js2-SWITCH."
7810 (let ((pos js2-token-beg)
7811 tt
7812 pn
7813 discriminant
7814 has-default
7815 case-expr
7816 case-node
7817 case-pos
7818 cases
7819 stmt
7820 lp
7821 rp)
7822 (js2-consume-token)
7823 (if (js2-must-match js2-LP "msg.no.paren.switch")
7824 (setq lp js2-token-beg))
7825 (setq discriminant (js2-parse-expr)
7826 pn (make-js2-switch-node :discriminant discriminant
7827 :pos pos
7828 :lp (js2-relpos lp pos)))
7829 (js2-node-add-children pn discriminant)
7830 (js2-enter-switch pn)
7831 (unwind-protect
7832 (progn
7833 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7834 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7835 (js2-must-match js2-LC "msg.no.brace.switch")
7836 (catch 'break
7837 (while t
7838 (setq tt (js2-next-token)
7839 case-pos js2-token-beg)
7840 (cond
7841 ((= tt js2-RC)
7842 (setf (js2-node-len pn) (- js2-token-end pos))
7843 (throw 'break nil)) ; done
7844 ((= tt js2-CASE)
7845 (setq case-expr (js2-parse-expr))
7846 (js2-must-match js2-COLON "msg.no.colon.case"))
7847 ((= tt js2-DEFAULT)
7848 (if has-default
7849 (js2-report-error "msg.double.switch.default"))
7850 (setq has-default t
7851 case-expr nil)
7852 (js2-must-match js2-COLON "msg.no.colon.case"))
7853 (t
7854 (js2-report-error "msg.bad.switch")
7855 (throw 'break nil)))
7856 (setq case-node (make-js2-case-node :pos case-pos
7857 :len (- js2-token-end case-pos)
7858 :expr case-expr))
7859 (js2-node-add-children case-node case-expr)
7860 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7861 (/= tt js2-CASE)
7862 (/= tt js2-DEFAULT)
7863 (/= tt js2-EOF))
7864 (setf stmt (js2-parse-statement)
7865 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7866 (js2-block-node-push case-node stmt))
7867 (push case-node cases)))
7868 ;; add cases last, as pushing reverses the order to be correct
7869 (dolist (kid cases)
7870 (js2-node-add-children pn kid)
7871 (push kid (js2-switch-node-cases pn)))
7872 pn) ; return value
7873 (js2-exit-switch))))
7874
7875 (defun js2-parse-while ()
7876 "Parser for while-statement. Last matched token must be js2-WHILE."
7877 (let ((pos js2-token-beg)
7878 (pn (make-js2-while-node))
7879 cond
7880 body)
7881 (js2-consume-token)
7882 (js2-enter-loop pn)
7883 (unwind-protect
7884 (progn
7885 (setf cond (js2-parse-condition)
7886 (js2-while-node-condition pn) (car cond)
7887 body (js2-parse-statement)
7888 (js2-while-node-body pn) body
7889 (js2-node-len pn) (- (js2-node-end body) pos)
7890 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7891 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7892 (js2-node-add-children pn body (car cond)))
7893 (js2-exit-loop))
7894 pn))
7895
7896 (defun js2-parse-do ()
7897 "Parser for do-statement. Last matched token must be js2-DO."
7898 (let ((pos js2-token-beg)
7899 (pn (make-js2-do-node))
7900 cond
7901 body
7902 end)
7903 (js2-consume-token)
7904 (js2-enter-loop pn)
7905 (unwind-protect
7906 (progn
7907 (setq body (js2-parse-statement))
7908 (js2-must-match js2-WHILE "msg.no.while.do")
7909 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7910 cond (js2-parse-condition)
7911 (js2-do-node-condition pn) (car cond)
7912 (js2-do-node-body pn) body
7913 end js2-ts-cursor
7914 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7915 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7916 (js2-node-add-children pn (car cond) body))
7917 (js2-exit-loop))
7918 ;; Always auto-insert semicolon to follow SpiderMonkey:
7919 ;; It is required by ECMAScript but is ignored by the rest of
7920 ;; world; see bug 238945
7921 (if (js2-match-token js2-SEMI)
7922 (setq end js2-ts-cursor))
7923 (setf (js2-node-len pn) (- end pos))
7924 pn))
7925
7926 (defun js2-parse-for ()
7927 "Parser for for-statement. Last matched token must be js2-FOR.
7928 Parses for, for-in, and for each-in statements."
7929 (let ((for-pos js2-token-beg)
7930 pn
7931 is-for-each
7932 is-for-in
7933 in-pos
7934 each-pos
7935 tmp-pos
7936 init ; Node init is also foo in 'foo in object'
7937 cond ; Node cond is also object in 'foo in object'
7938 incr ; 3rd section of for-loop initializer
7939 body
7940 tt
7941 lp
7942 rp)
7943 (js2-consume-token)
7944 ;; See if this is a for each () instead of just a for ()
7945 (when (js2-match-token js2-NAME)
7946 (if (string= "each" js2-ts-string)
7947 (progn
7948 (setq is-for-each t
7949 each-pos (- js2-token-beg for-pos)) ; relative
7950 (js2-record-face 'font-lock-keyword-face))
7951 (js2-report-error "msg.no.paren.for")))
7952 (if (js2-must-match js2-LP "msg.no.paren.for")
7953 (setq lp (- js2-token-beg for-pos)))
7954 (setq tt (js2-peek-token))
7955 ;; 'for' makes local scope
7956 (js2-push-scope (make-js2-scope))
7957 (unwind-protect
7958 ;; parse init clause
7959 (let ((js2-in-for-init t)) ; set as dynamic variable
7960 (cond
7961 ((= tt js2-SEMI)
7962 (setq init (make-js2-empty-expr-node)))
7963 ((or (= tt js2-VAR) (= tt js2-LET))
7964 (js2-consume-token)
7965 (setq init (js2-parse-variables tt js2-token-beg)))
7966 (t
7967 (setq init (js2-parse-expr)))))
7968 (if (js2-match-token js2-IN)
7969 (setq is-for-in t
7970 in-pos (- js2-token-beg for-pos)
7971 ;; scope of iteration target object is not the scope we've created above.
7972 ;; stash current scope temporary.
7973 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7974 (js2-parse-expr))) ; object over which we're iterating
7975 ;; else ordinary for loop - parse cond and incr
7976 (js2-must-match js2-SEMI "msg.no.semi.for")
7977 (setq cond (if (= (js2-peek-token) js2-SEMI)
7978 (make-js2-empty-expr-node) ; no loop condition
7979 (js2-parse-expr)))
7980 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7981 (setq tmp-pos js2-token-end
7982 incr (if (= (js2-peek-token) js2-RP)
7983 (make-js2-empty-expr-node :pos tmp-pos)
7984 (js2-parse-expr))))
7985 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7986 (setq rp (- js2-token-beg for-pos)))
7987 (if (not is-for-in)
7988 (setq pn (make-js2-for-node :init init
7989 :condition cond
7990 :update incr
7991 :lp lp
7992 :rp rp))
7993 ;; cond could be null if 'in obj' got eaten by the init node.
7994 (if (js2-infix-node-p init)
7995 ;; it was (foo in bar) instead of (var foo in bar)
7996 (setq cond (js2-infix-node-right init)
7997 init (js2-infix-node-left init))
7998 (if (and (js2-var-decl-node-p init)
7999 (> (length (js2-var-decl-node-kids init)) 1))
8000 (js2-report-error "msg.mult.index")))
8001 (setq pn (make-js2-for-in-node :iterator init
8002 :object cond
8003 :in-pos in-pos
8004 :foreach-p is-for-each
8005 :each-pos each-pos
8006 :lp lp
8007 :rp rp)))
8008 (unwind-protect
8009 (progn
8010 (js2-enter-loop pn)
8011 ;; We have to parse the body -after- creating the loop node,
8012 ;; so that the loop node appears in the js2-loop-set, allowing
8013 ;; break/continue statements to find the enclosing loop.
8014 (setf body (js2-parse-statement)
8015 (js2-loop-node-body pn) body
8016 (js2-node-pos pn) for-pos
8017 (js2-node-len pn) (- (js2-node-end body) for-pos))
8018 (js2-node-add-children pn init cond incr body))
8019 ;; finally
8020 (js2-exit-loop))
8021 (js2-pop-scope))
8022 pn))
8023
8024 (defun js2-parse-try ()
8025 "Parser for try-statement. Last matched token must be js2-TRY."
8026 (let ((try-pos js2-token-beg)
8027 try-end
8028 try-block
8029 catch-blocks
8030 finally-block
8031 saw-default-catch
8032 peek
8033 param
8034 catch-cond
8035 catch-node
8036 guard-kwd
8037 catch-pos
8038 finally-pos
8039 pn
8040 block
8041 lp
8042 rp)
8043 (js2-consume-token)
8044 (if (/= (js2-peek-token) js2-LC)
8045 (js2-report-error "msg.no.brace.try"))
8046 (setq try-block (js2-parse-statement)
8047 try-end (js2-node-end try-block)
8048 peek (js2-peek-token))
8049 (cond
8050 ((= peek js2-CATCH)
8051 (while (js2-match-token js2-CATCH)
8052 (setq catch-pos js2-token-beg
8053 guard-kwd nil
8054 catch-cond nil
8055 lp nil
8056 rp nil)
8057 (if saw-default-catch
8058 (js2-report-error "msg.catch.unreachable"))
8059 (if (js2-must-match js2-LP "msg.no.paren.catch")
8060 (setq lp (- js2-token-beg catch-pos)))
8061 (js2-push-scope (make-js2-scope))
8062 (let ((tt (js2-peek-token)))
8063 (cond
8064 ;; destructuring pattern
8065 ;; catch ({ message, file }) { ... }
8066 ((or (= tt js2-LB) (= tt js2-LC))
8067 (setq param
8068 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8069 js2-LET nil)))
8070 ;; simple name
8071 (t
8072 (js2-must-match js2-NAME "msg.bad.catchcond")
8073 (setq param (js2-create-name-node))
8074 (js2-define-symbol js2-LET js2-ts-string param))))
8075 ;; pattern guard
8076 (if (js2-match-token js2-IF)
8077 (setq guard-kwd (- js2-token-beg catch-pos)
8078 catch-cond (js2-parse-expr))
8079 (setq saw-default-catch t))
8080 (if (js2-must-match js2-RP "msg.bad.catchcond")
8081 (setq rp (- js2-token-beg catch-pos)))
8082 (js2-must-match js2-LC "msg.no.brace.catchblock")
8083 (setq block (js2-parse-statements)
8084 try-end (js2-node-end block)
8085 catch-node (make-js2-catch-node :pos catch-pos
8086 :param param
8087 :guard-expr catch-cond
8088 :guard-kwd guard-kwd
8089 :block block
8090 :lp lp
8091 :rp rp))
8092 (js2-pop-scope)
8093 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8094 (setq try-end js2-token-beg))
8095 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8096 (js2-node-len catch-node) (- try-end catch-pos))
8097 (js2-node-add-children catch-node param catch-cond block)
8098 (push catch-node catch-blocks)))
8099 ((/= peek js2-FINALLY)
8100 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8101 (js2-node-pos try-block)
8102 (- (setq try-end (js2-node-end try-block))
8103 (js2-node-pos try-block)))))
8104 (when (js2-match-token js2-FINALLY)
8105 (setq finally-pos js2-token-beg
8106 block (js2-parse-statement)
8107 try-end (js2-node-end block)
8108 finally-block (make-js2-finally-node :pos finally-pos
8109 :len (- try-end finally-pos)
8110 :body block))
8111 (js2-node-add-children finally-block block))
8112 (setq pn (make-js2-try-node :pos try-pos
8113 :len (- try-end try-pos)
8114 :try-block try-block
8115 :finally-block finally-block))
8116 (js2-node-add-children pn try-block finally-block)
8117 ;; push them onto the try-node, which reverses and corrects their order
8118 (dolist (cb catch-blocks)
8119 (js2-node-add-children pn cb)
8120 (push cb (js2-try-node-catch-clauses pn)))
8121 pn))
8122
8123 (defun js2-parse-throw ()
8124 "Parser for throw-statement. Last matched token must be js2-THROW."
8125 (let ((pos js2-token-beg)
8126 expr
8127 pn)
8128 (js2-consume-token)
8129 (if (= (js2-peek-token-or-eol) js2-EOL)
8130 ;; ECMAScript does not allow new lines before throw expression,
8131 ;; see bug 256617
8132 (js2-report-error "msg.bad.throw.eol"))
8133 (setq expr (js2-parse-expr)
8134 pn (make-js2-throw-node :pos pos
8135 :len (- (js2-node-end expr) pos)
8136 :expr expr))
8137 (js2-node-add-children pn expr)
8138 pn))
8139
8140 (defsubst js2-match-jump-label-name (label-name)
8141 "If break/continue specified a label, return that label's labeled stmt.
8142 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8143 does not match an existing label, reports an error and returns nil."
8144 (let ((bundle (cdr (assoc label-name js2-label-set))))
8145 (if (null bundle)
8146 (js2-report-error "msg.undef.label"))
8147 bundle))
8148
8149 (defun js2-parse-break ()
8150 "Parser for break-statement. Last matched token must be js2-BREAK."
8151 (let ((pos js2-token-beg)
8152 (end js2-token-end)
8153 break-target ; statement to break from
8154 break-label ; in "break foo", name-node representing the foo
8155 labels ; matching labeled statement to break to
8156 pn)
8157 (js2-consume-token) ; `break'
8158 (when (eq (js2-peek-token-or-eol) js2-NAME)
8159 (js2-consume-token)
8160 (setq break-label (js2-create-name-node)
8161 end (js2-node-end break-label)
8162 ;; matchJumpLabelName only matches if there is one
8163 labels (js2-match-jump-label-name js2-ts-string)
8164 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8165 (unless (or break-target break-label)
8166 ;; no break target specified - try for innermost enclosing loop/switch
8167 (if (null js2-loop-and-switch-set)
8168 (unless break-label
8169 (js2-report-error "msg.bad.break" nil pos (length "break")))
8170 (setq break-target (car js2-loop-and-switch-set))))
8171 (setq pn (make-js2-break-node :pos pos
8172 :len (- end pos)
8173 :label break-label
8174 :target break-target))
8175 (js2-node-add-children pn break-label) ; but not break-target
8176 pn))
8177
8178 (defun js2-parse-continue ()
8179 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8180 (let ((pos js2-token-beg)
8181 (end js2-token-end)
8182 label ; optional user-specified label, a `js2-name-node'
8183 labels ; current matching labeled stmt, if any
8184 target ; the `js2-loop-node' target of this continue stmt
8185 pn)
8186 (js2-consume-token) ; `continue'
8187 (when (= (js2-peek-token-or-eol) js2-NAME)
8188 (js2-consume-token)
8189 (setq label (js2-create-name-node)
8190 end (js2-node-end label)
8191 ;; matchJumpLabelName only matches if there is one
8192 labels (js2-match-jump-label-name js2-ts-string)))
8193 (cond
8194 ((null labels) ; no current label to go to
8195 (if (null js2-loop-set) ; no loop to continue to
8196 (js2-report-error "msg.continue.outside" nil pos
8197 (length "continue"))
8198 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8199 (t
8200 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8201 (setq target (js2-labeled-stmt-node-stmt labels))
8202 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8203 (setq pn (make-js2-continue-node :pos pos
8204 :len (- end pos)
8205 :label label
8206 :target target))
8207 (js2-node-add-children pn label) ; but not target - it's not our child
8208 pn))
8209
8210 (defun js2-parse-with ()
8211 "Parser for with-statement. Last matched token must be js2-WITH."
8212 (js2-consume-token)
8213 (let ((pos js2-token-beg)
8214 obj body pn lp rp)
8215 (if (js2-must-match js2-LP "msg.no.paren.with")
8216 (setq lp js2-token-beg))
8217 (setq obj (js2-parse-expr))
8218 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8219 (setq rp js2-token-beg))
8220 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8221 (setq body (js2-parse-statement)))
8222 (setq pn (make-js2-with-node :pos pos
8223 :len (- (js2-node-end body) pos)
8224 :object obj
8225 :body body
8226 :lp (js2-relpos lp pos)
8227 :rp (js2-relpos rp pos)))
8228 (js2-node-add-children pn obj body)
8229 pn))
8230
8231 (defun js2-parse-const-var ()
8232 "Parser for var- or const-statement.
8233 Last matched token must be js2-CONST or js2-VAR."
8234 (let ((tt (js2-peek-token))
8235 (pos js2-token-beg)
8236 expr
8237 pn)
8238 (js2-consume-token)
8239 (setq expr (js2-parse-variables tt js2-token-beg)
8240 pn (make-js2-expr-stmt-node :pos pos
8241 :len (- (js2-node-end expr) pos)
8242 :expr expr))
8243 (js2-node-add-children pn expr)
8244 pn))
8245
8246 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8247 (let ((pn (make-js2-expr-stmt-node :pos pos
8248 :len (js2-node-len expr)
8249 :type (if (js2-inside-function)
8250 js2-EXPR_VOID
8251 js2-EXPR_RESULT)
8252 :expr expr)))
8253 (if add-child
8254 (js2-node-add-children pn expr))
8255 pn))
8256
8257 (defun js2-parse-let-stmt ()
8258 "Parser for let-statement. Last matched token must be js2-LET."
8259 (js2-consume-token)
8260 (let ((pos js2-token-beg)
8261 expr
8262 pn)
8263 (if (= (js2-peek-token) js2-LP)
8264 ;; let expression in statement context
8265 (setq expr (js2-parse-let pos 'statement)
8266 pn (js2-wrap-with-expr-stmt pos expr t))
8267 ;; else we're looking at a statement like let x=6, y=7;
8268 (setf expr (js2-parse-variables js2-LET pos)
8269 pn (js2-wrap-with-expr-stmt pos expr t)
8270 (js2-node-type pn) js2-EXPR_RESULT))
8271 pn))
8272
8273 (defun js2-parse-ret-yield ()
8274 (js2-parse-return-or-yield (js2-peek-token) nil))
8275
8276 (defconst js2-parse-return-stmt-enders
8277 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8278
8279 (defsubst js2-now-all-set (before after mask)
8280 "Return whether or not the bits in the mask have changed to all set.
8281 BEFORE is bits before change, AFTER is bits after change, and MASK is
8282 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8283 but not BEFORE."
8284 (and (/= (logand before mask) mask)
8285 (= (logand after mask) mask)))
8286
8287 (defun js2-parse-return-or-yield (tt expr-context)
8288 (let ((pos js2-token-beg)
8289 (end js2-token-end)
8290 (before js2-end-flags)
8291 (inside-function (js2-inside-function))
8292 e
8293 ret
8294 name)
8295 (unless inside-function
8296 (js2-report-error (if (eq tt js2-RETURN)
8297 "msg.bad.return"
8298 "msg.bad.yield")))
8299 (js2-consume-token)
8300 ;; This is ugly, but we don't want to require a semicolon.
8301 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8302 (setq e (js2-parse-expr)
8303 end (js2-node-end e)))
8304 (cond
8305 ((eq tt js2-RETURN)
8306 (js2-set-flag js2-end-flags (if (null e)
8307 js2-end-returns
8308 js2-end-returns-value))
8309 (setq ret (make-js2-return-node :pos pos
8310 :len (- end pos)
8311 :retval e))
8312 (js2-node-add-children ret e)
8313 ;; See if we need a strict mode warning.
8314 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8315 ;; more thorough and accurate than this before/after flag check.
8316 ;; E.g. if there's a finally-block that always returns, we shouldn't
8317 ;; show a warning generated by inconsistent returns in the catch blocks.
8318 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8319 ;; so we know which returns/yields to highlight, and we should get rid of
8320 ;; all the checking in `js2-parse-return-or-yield'.
8321 (if (and js2-strict-inconsistent-return-warning
8322 (js2-now-all-set before js2-end-flags
8323 (logior js2-end-returns js2-end-returns-value)))
8324 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8325 (t
8326 (unless (js2-inside-function)
8327 (js2-report-error "msg.bad.yield"))
8328 (js2-set-flag js2-end-flags js2-end-yields)
8329 (setq ret (make-js2-yield-node :pos pos
8330 :len (- end pos)
8331 :value e))
8332 (js2-node-add-children ret e)
8333 (unless expr-context
8334 (setq e ret
8335 ret (js2-wrap-with-expr-stmt pos e t))
8336 (js2-set-requires-activation)
8337 (js2-set-is-generator))))
8338 ;; see if we are mixing yields and value returns.
8339 (when (and inside-function
8340 (js2-now-all-set before js2-end-flags
8341 (logior js2-end-yields js2-end-returns-value)))
8342 (setq name (js2-function-name js2-current-script-or-fn))
8343 (if (zerop (length name))
8344 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8345 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8346 ret))
8347
8348 (defun js2-parse-debugger ()
8349 (js2-consume-token)
8350 (make-js2-keyword-node :type js2-DEBUGGER))
8351
8352 (defun js2-parse-block ()
8353 "Parser for a curly-delimited statement block.
8354 Last token matched must be js2-LC."
8355 (let ((pos js2-token-beg)
8356 (pn (make-js2-scope)))
8357 (js2-consume-token)
8358 (js2-push-scope pn)
8359 (unwind-protect
8360 (progn
8361 (js2-parse-statements pn)
8362 (js2-must-match js2-RC "msg.no.brace.block")
8363 (setf (js2-node-len pn) (- js2-token-end pos)))
8364 (js2-pop-scope))
8365 pn))
8366
8367 ;; for js2-ERROR too, to have a node for error recovery to work on
8368 (defun js2-parse-semi ()
8369 "Parse a statement or handle an error.
8370 Last matched token is js-SEMI or js-ERROR."
8371 (let ((tt (js2-peek-token)) pos len)
8372 (js2-consume-token)
8373 (if (eq tt js2-SEMI)
8374 (make-js2-empty-expr-node :len 1)
8375 (setq pos js2-token-beg
8376 len (- js2-token-beg pos))
8377 (js2-report-error "msg.syntax" nil pos len)
8378 (make-js2-error-node :pos pos :len len))))
8379
8380 (defun js2-parse-default-xml-namespace ()
8381 "Parse a `default xml namespace = <expr>' e4x statement."
8382 (let ((pos js2-token-beg)
8383 end len expr unary es)
8384 (js2-consume-token)
8385 (js2-must-have-xml)
8386 (js2-set-requires-activation)
8387 (setq len (- js2-ts-cursor pos))
8388 (unless (and (js2-match-token js2-NAME)
8389 (string= js2-ts-string "xml"))
8390 (js2-report-error "msg.bad.namespace" nil pos len))
8391 (unless (and (js2-match-token js2-NAME)
8392 (string= js2-ts-string "namespace"))
8393 (js2-report-error "msg.bad.namespace" nil pos len))
8394 (unless (js2-match-token js2-ASSIGN)
8395 (js2-report-error "msg.bad.namespace" nil pos len))
8396 (setq expr (js2-parse-expr)
8397 end (js2-node-end expr)
8398 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8399 :pos pos
8400 :len (- end pos)
8401 :operand expr))
8402 (js2-node-add-children unary expr)
8403 (make-js2-expr-stmt-node :pos pos
8404 :len (- end pos)
8405 :expr unary)))
8406
8407 (defun js2-record-label (label bundle)
8408 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8409 (js2-consume-token)
8410 (let ((name (js2-label-node-name label))
8411 labeled-stmt
8412 dup)
8413 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8414 ;; flag both labels if possible when used in editing mode
8415 (if (and js2-parse-ide-mode
8416 (setq dup (js2-get-label-by-name labeled-stmt name)))
8417 (js2-report-error "msg.dup.label" nil
8418 (js2-node-abs-pos dup) (js2-node-len dup)))
8419 (js2-report-error "msg.dup.label" nil
8420 (js2-node-pos label) (js2-node-len label)))
8421 (js2-labeled-stmt-node-add-label bundle label)
8422 (js2-node-add-children bundle label)
8423 ;; Add one reference to the bundle per label in `js2-label-set'
8424 (push (cons name bundle) js2-label-set)))
8425
8426 (defun js2-parse-name-or-label ()
8427 "Parser for identifier or label. Last token matched must be js2-NAME.
8428 Called when we found a name in a statement context. If it's a label, we gather
8429 up any following labels and the next non-label statement into a
8430 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8431 expression and return it wrapped in a `js2-expr-stmt-node'."
8432 (let ((pos js2-token-beg)
8433 (end js2-token-end)
8434 expr
8435 stmt
8436 pn
8437 bundle
8438 (continue t))
8439 ;; set check for label and call down to `js2-parse-primary-expr'
8440 (js2-set-check-for-label)
8441 (setq expr (js2-parse-expr))
8442 (if (/= (js2-node-type expr) js2-LABEL)
8443 ;; Parsed non-label expression - wrap with expression stmt.
8444 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8445 ;; else parsed a label
8446 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8447 (js2-record-label expr bundle)
8448 ;; look for more labels
8449 (while (and continue (= (js2-peek-token) js2-NAME))
8450 (js2-set-check-for-label)
8451 (setq expr (js2-parse-expr))
8452 (if (/= (js2-node-type expr) js2-LABEL)
8453 (progn
8454 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8455 continue nil)
8456 (js2-auto-insert-semicolon stmt))
8457 (js2-record-label expr bundle)))
8458 ;; no more labels; now parse the labeled statement
8459 (unwind-protect
8460 (unless stmt
8461 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8462 (setq stmt (js2-statement-helper))))
8463 ;; remove the labels for this statement from the global set
8464 (dolist (label (js2-labeled-stmt-node-labels bundle))
8465 (setq js2-label-set (remove label js2-label-set))))
8466 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8467 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8468 (js2-node-add-children bundle stmt)
8469 bundle)))
8470
8471 (defun js2-parse-expr-stmt ()
8472 "Default parser in statement context, if no recognized statement found."
8473 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8474
8475 (defun js2-parse-variables (decl-type pos)
8476 "Parse a comma-separated list of variable declarations.
8477 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8478
8479 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8480 For 'var' or 'const', the keyword should be the token last scanned.
8481
8482 POS is the position where the node should start. It's sometimes the
8483 var/const/let keyword, and other times the beginning of the first token
8484 in the first variable declaration.
8485
8486 Returns the parsed `js2-var-decl-node' expression node."
8487 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8488 :pos pos))
8489 destructuring
8490 kid-pos
8491 tt
8492 init
8493 name
8494 end
8495 nbeg nend
8496 vi
8497 (continue t))
8498 ;; Example:
8499 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8500 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8501 ;; var {a, b} = baz;
8502 (while continue
8503 (setq destructuring nil
8504 name nil
8505 tt (js2-peek-token)
8506 kid-pos js2-token-beg
8507 end js2-token-end
8508 init nil)
8509 (if (or (= tt js2-LB) (= tt js2-LC))
8510 ;; Destructuring assignment, e.g., var [a, b] = ...
8511 (setq destructuring (js2-parse-primary-expr-lhs)
8512 end (js2-node-end destructuring))
8513 ;; Simple variable name
8514 (when (js2-must-match js2-NAME "msg.bad.var")
8515 (setq name (js2-create-name-node)
8516 nbeg js2-token-beg
8517 nend js2-token-end
8518 end nend)
8519 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8520 (when (js2-match-token js2-ASSIGN)
8521 (setq init (js2-parse-assign-expr)
8522 end (js2-node-end init))
8523 (when js2-parse-ide-mode
8524 (js2-record-assign-functions init name)))
8525 (when name
8526 (js2-set-face nbeg nend (if (js2-function-node-p init)
8527 'font-lock-function-name-face
8528 'font-lock-variable-name-face)
8529 'record))
8530 (setq vi (make-js2-var-init-node :pos kid-pos
8531 :len (- end kid-pos)
8532 :type decl-type))
8533 (if destructuring
8534 (progn
8535 (if (and (null init) (not js2-in-for-init))
8536 (js2-report-error "msg.destruct.assign.no.init"))
8537 (js2-define-destruct-symbols destructuring
8538 decl-type
8539 'font-lock-variable-name-face)
8540 (setf (js2-var-init-node-target vi) destructuring))
8541 (setf (js2-var-init-node-target vi) name))
8542 (setf (js2-var-init-node-initializer vi) init)
8543 (js2-node-add-children vi name destructuring init)
8544 (js2-block-node-push result vi)
8545 (unless (js2-match-token js2-COMMA)
8546 (setq continue nil)))
8547 (setf (js2-node-len result) (- end pos))
8548 result))
8549
8550 (defun js2-parse-let (pos &optional stmt-p)
8551 "Parse a let expression or statement.
8552 A let-expression is of the form `let (vars) expr'.
8553 A let-statment is of the form `let (vars) {statements}'.
8554 The third form of let is a variable declaration list, handled
8555 by `js2-parse-variables'."
8556 (let ((pn (make-js2-let-node :pos pos))
8557 beg vars body)
8558 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8559 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8560 (js2-push-scope pn)
8561 (unwind-protect
8562 (progn
8563 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8564 (if (js2-must-match js2-RP "msg.no.paren.let")
8565 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8566 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8567 ;; let statement
8568 (progn
8569 (js2-consume-token)
8570 (setf beg js2-token-beg ; position stmt at LC
8571 body (js2-parse-statements))
8572 (js2-must-match js2-RC "msg.no.curly.let")
8573 (setf (js2-node-len body) (- js2-token-end beg)
8574 (js2-node-len pn) (- js2-token-end pos)
8575 (js2-let-node-body pn) body
8576 (js2-node-type pn) js2-LET))
8577 ;; let expression
8578 (setf body (js2-parse-expr)
8579 (js2-node-len pn) (- (js2-node-end body) pos)
8580 (js2-let-node-body pn) body))
8581 (js2-node-add-children pn vars body))
8582 (js2-pop-scope))
8583 pn))
8584
8585 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8586 (js2-scope-put-symbol (or scope js2-current-scope)
8587 name
8588 (make-js2-symbol decl-type name node)))
8589
8590 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8591 "Define a symbol in the current scope.
8592 If NODE is non-nil, it is the AST node associated with the symbol."
8593 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8594 (symbol (if defining-scope
8595 (js2-scope-get-symbol defining-scope name)))
8596 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8597 (cond
8598 ((and symbol ; already defined
8599 (or (= sdt js2-CONST) ; old version is const
8600 (= decl-type js2-CONST) ; new version is const
8601 ;; two let-bound vars in this block have same name
8602 (and (= sdt js2-LET)
8603 (eq defining-scope js2-current-scope))))
8604 (js2-report-error
8605 (cond
8606 ((= sdt js2-CONST) "msg.const.redecl")
8607 ((= sdt js2-LET) "msg.let.redecl")
8608 ((= sdt js2-VAR) "msg.var.redecl")
8609 ((= sdt js2-FUNCTION) "msg.function.redecl")
8610 (t "msg.parm.redecl"))
8611 name))
8612 ((= decl-type js2-LET)
8613 (if (and (not ignore-not-in-block)
8614 (or (= (js2-node-type js2-current-scope) js2-IF)
8615 (js2-loop-node-p js2-current-scope)))
8616 (js2-report-error "msg.let.decl.not.in.block")
8617 (js2-define-new-symbol decl-type name node)))
8618 ((or (= decl-type js2-VAR)
8619 (= decl-type js2-CONST)
8620 (= decl-type js2-FUNCTION))
8621 (if symbol
8622 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8623 (js2-add-strict-warning "msg.var.redecl" name)
8624 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8625 (js2-add-strict-warning "msg.var.hides.arg" name)))
8626 (js2-define-new-symbol decl-type name node
8627 js2-current-script-or-fn)))
8628 ((= decl-type js2-LP)
8629 (if symbol
8630 ;; must be duplicate parameter. Second parameter hides the
8631 ;; first, so go ahead and add the second pararameter
8632 (js2-report-warning "msg.dup.parms" name))
8633 (js2-define-new-symbol decl-type name node))
8634 (t (js2-code-bug)))))
8635
8636 (defun js2-parse-expr (&optional oneshot)
8637 (let* ((pn (js2-parse-assign-expr))
8638 (pos (js2-node-pos pn))
8639 left
8640 right
8641 op-pos)
8642 (while (and (not oneshot)
8643 (js2-match-token js2-COMMA))
8644 (setq op-pos (- js2-token-beg pos)) ; relative
8645 (if (= (js2-peek-token) js2-YIELD)
8646 (js2-report-error "msg.yield.parenthesized"))
8647 (setq right (js2-parse-assign-expr)
8648 left pn
8649 pn (make-js2-infix-node :type js2-COMMA
8650 :pos pos
8651 :len (- js2-ts-cursor pos)
8652 :op-pos op-pos
8653 :left left
8654 :right right))
8655 (js2-node-add-children pn left right))
8656 pn))
8657
8658 (defun js2-parse-assign-expr ()
8659 (let ((tt (js2-peek-token))
8660 (pos js2-token-beg)
8661 pn
8662 left
8663 right
8664 op-pos)
8665 (if (= tt js2-YIELD)
8666 (js2-parse-return-or-yield tt t)
8667 ;; not yield - parse assignment expression
8668 (setq pn (js2-parse-cond-expr)
8669 tt (js2-peek-token))
8670 (when (and (<= js2-first-assign tt)
8671 (<= tt js2-last-assign))
8672 ;; tt express assignment (=, |=, ^=, ..., %=)
8673 (js2-consume-token)
8674 (setq op-pos (- js2-token-beg pos) ; relative
8675 left pn
8676 right (js2-parse-assign-expr)
8677 pn (make-js2-assign-node :type tt
8678 :pos pos
8679 :len (- (js2-node-end right) pos)
8680 :op-pos op-pos
8681 :left left
8682 :right right))
8683 (when js2-parse-ide-mode
8684 (js2-highlight-assign-targets pn left right)
8685 (js2-record-assign-functions right left))
8686 ;; do this last so ide checks above can use absolute positions
8687 (js2-node-add-children pn left right))
8688 pn)))
8689
8690 (defun js2-parse-cond-expr ()
8691 (let ((pos js2-token-beg)
8692 (pn (js2-parse-or-expr))
8693 test-expr
8694 if-true
8695 if-false
8696 q-pos
8697 c-pos)
8698 (when (js2-match-token js2-HOOK)
8699 (setq q-pos (- js2-token-beg pos)
8700 if-true (js2-parse-assign-expr))
8701 (js2-must-match js2-COLON "msg.no.colon.cond")
8702 (setq c-pos (- js2-token-beg pos)
8703 if-false (js2-parse-assign-expr)
8704 test-expr pn
8705 pn (make-js2-cond-node :pos pos
8706 :len (- (js2-node-end if-false) pos)
8707 :test-expr test-expr
8708 :true-expr if-true
8709 :false-expr if-false
8710 :q-pos q-pos
8711 :c-pos c-pos))
8712 (js2-node-add-children pn test-expr if-true if-false))
8713 pn))
8714
8715 (defun js2-make-binary (type left parser)
8716 "Helper for constructing a binary-operator AST node.
8717 LEFT is the left-side-expression, already parsed, and the
8718 binary operator should have just been matched.
8719 PARSER is a function to call to parse the right operand,
8720 or a `js2-node' struct if it has already been parsed."
8721 (let* ((pos (js2-node-pos left))
8722 (op-pos (- js2-token-beg pos))
8723 (right (if (js2-node-p parser)
8724 parser
8725 (funcall parser)))
8726 (pn (make-js2-infix-node :type type
8727 :pos pos
8728 :len (- (js2-node-end right) pos)
8729 :op-pos op-pos
8730 :left left
8731 :right right)))
8732 (js2-node-add-children pn left right)
8733 pn))
8734
8735 (defun js2-parse-or-expr ()
8736 (let ((pn (js2-parse-and-expr)))
8737 (when (js2-match-token js2-OR)
8738 (setq pn (js2-make-binary js2-OR
8739 pn
8740 'js2-parse-or-expr)))
8741 pn))
8742
8743 (defun js2-parse-and-expr ()
8744 (let ((pn (js2-parse-bit-or-expr)))
8745 (when (js2-match-token js2-AND)
8746 (setq pn (js2-make-binary js2-AND
8747 pn
8748 'js2-parse-and-expr)))
8749 pn))
8750
8751 (defun js2-parse-bit-or-expr ()
8752 (let ((pn (js2-parse-bit-xor-expr)))
8753 (while (js2-match-token js2-BITOR)
8754 (setq pn (js2-make-binary js2-BITOR
8755 pn
8756 'js2-parse-bit-xor-expr)))
8757 pn))
8758
8759 (defun js2-parse-bit-xor-expr ()
8760 (let ((pn (js2-parse-bit-and-expr)))
8761 (while (js2-match-token js2-BITXOR)
8762 (setq pn (js2-make-binary js2-BITXOR
8763 pn
8764 'js2-parse-bit-and-expr)))
8765 pn))
8766
8767 (defun js2-parse-bit-and-expr ()
8768 (let ((pn (js2-parse-eq-expr)))
8769 (while (js2-match-token js2-BITAND)
8770 (setq pn (js2-make-binary js2-BITAND
8771 pn
8772 'js2-parse-eq-expr)))
8773 pn))
8774
8775 (defconst js2-parse-eq-ops
8776 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8777
8778 (defun js2-parse-eq-expr ()
8779 (let ((pn (js2-parse-rel-expr))
8780 tt)
8781 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8782 (js2-consume-token)
8783 (setq pn (js2-make-binary tt
8784 pn
8785 'js2-parse-rel-expr)))
8786 pn))
8787
8788 (defconst js2-parse-rel-ops
8789 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8790
8791 (defun js2-parse-rel-expr ()
8792 (let ((pn (js2-parse-shift-expr))
8793 (continue t)
8794 tt)
8795 (while continue
8796 (setq tt (js2-peek-token))
8797 (cond
8798 ((and js2-in-for-init (= tt js2-IN))
8799 (setq continue nil))
8800 ((memq tt js2-parse-rel-ops)
8801 (js2-consume-token)
8802 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8803 (t
8804 (setq continue nil))))
8805 pn))
8806
8807 (defconst js2-parse-shift-ops
8808 (list js2-LSH js2-URSH js2-RSH))
8809
8810 (defun js2-parse-shift-expr ()
8811 (let ((pn (js2-parse-add-expr))
8812 tt
8813 (continue t))
8814 (while continue
8815 (setq tt (js2-peek-token))
8816 (if (memq tt js2-parse-shift-ops)
8817 (progn
8818 (js2-consume-token)
8819 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8820 (setq continue nil)))
8821 pn))
8822
8823 (defun js2-parse-add-expr ()
8824 (let ((pn (js2-parse-mul-expr))
8825 tt
8826 (continue t))
8827 (while continue
8828 (setq tt (js2-peek-token))
8829 (if (or (= tt js2-ADD) (= tt js2-SUB))
8830 (progn
8831 (js2-consume-token)
8832 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8833 (setq continue nil)))
8834 pn))
8835
8836 (defconst js2-parse-mul-ops
8837 (list js2-MUL js2-DIV js2-MOD))
8838
8839 (defun js2-parse-mul-expr ()
8840 (let ((pn (js2-parse-unary-expr))
8841 tt
8842 (continue t))
8843 (while continue
8844 (setq tt (js2-peek-token))
8845 (if (memq tt js2-parse-mul-ops)
8846 (progn
8847 (js2-consume-token)
8848 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8849 (setq continue nil)))
8850 pn))
8851
8852 (defsubst js2-make-unary (type parser &rest args)
8853 "Make a unary node of type TYPE.
8854 PARSER is either a node (for postfix operators) or a function to call
8855 to parse the operand (for prefix operators)."
8856 (let* ((pos js2-token-beg)
8857 (postfix (js2-node-p parser))
8858 (expr (if postfix
8859 parser
8860 (apply parser args)))
8861 end
8862 pn)
8863 (if postfix ; e.g. i++
8864 (setq pos (js2-node-pos expr)
8865 end js2-token-end)
8866 (setq end (js2-node-end expr)))
8867 (setq pn (make-js2-unary-node :type type
8868 :pos pos
8869 :len (- end pos)
8870 :operand expr))
8871 (js2-node-add-children pn expr)
8872 pn))
8873
8874 (defconst js2-incrementable-node-types
8875 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8876 "Node types that can be the operand of a ++ or -- operator.")
8877
8878 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8879 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8880 js2-incrementable-node-types)
8881 (js2-report-error (if (= tt js2-INC)
8882 "msg.bad.incr"
8883 "msg.bad.decr")
8884 nil beg (- end beg))))
8885
8886 (defun js2-parse-unary-expr ()
8887 (let ((tt (js2-peek-token))
8888 pn expr beg end)
8889 (cond
8890 ((or (= tt js2-VOID)
8891 (= tt js2-NOT)
8892 (= tt js2-BITNOT)
8893 (= tt js2-TYPEOF))
8894 (js2-consume-token)
8895 (js2-make-unary tt 'js2-parse-unary-expr))
8896 ((= tt js2-ADD)
8897 (js2-consume-token)
8898 ;; Convert to special POS token in decompiler and parse tree
8899 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8900 ((= tt js2-SUB)
8901 (js2-consume-token)
8902 ;; Convert to special NEG token in decompiler and parse tree
8903 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8904 ((or (= tt js2-INC)
8905 (= tt js2-DEC))
8906 (js2-consume-token)
8907 (prog1
8908 (setq beg js2-token-beg
8909 end js2-token-end
8910 expr (js2-make-unary tt 'js2-parse-member-expr t))
8911 (js2-check-bad-inc-dec tt beg end expr)))
8912 ((= tt js2-DELPROP)
8913 (js2-consume-token)
8914 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8915 ((= tt js2-ERROR)
8916 (js2-consume-token)
8917 (make-js2-error-node)) ; try to continue
8918 ((and (= tt js2-LT)
8919 js2-compiler-xml-available)
8920 ;; XML stream encountered in expression.
8921 (js2-consume-token)
8922 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8923 (t
8924 (setq pn (js2-parse-member-expr t)
8925 ;; Don't look across a newline boundary for a postfix incop.
8926 tt (js2-peek-token-or-eol))
8927 (when (or (= tt js2-INC) (= tt js2-DEC))
8928 (js2-consume-token)
8929 (setf expr pn
8930 pn (js2-make-unary tt expr))
8931 (js2-node-set-prop pn 'postfix t)
8932 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8933 pn))))
8934
8935 (defun js2-parse-xml-initializer ()
8936 "Parse an E4X XML initializer.
8937 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8938 Then I'll postprocess the result, depending on whether we're in IDE
8939 mode or codegen mode, and generate the appropriate rewritten AST.
8940 IDE mode uses a rich AST that models the XML structure. Codegen mode
8941 just concatenates everything and makes a new XML or XMLList out of it."
8942 (let ((tt (js2-get-first-xml-token))
8943 pn-xml
8944 pn
8945 expr
8946 kids
8947 expr-pos
8948 (continue t)
8949 (first-token t))
8950 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8951 (js2-report-error "msg.syntax"))
8952 (setq pn-xml (make-js2-xml-node))
8953 (while continue
8954 (if first-token
8955 (setq first-token nil)
8956 (setq tt (js2-get-next-xml-token)))
8957 (cond
8958 ;; js2-XML means we found a {expr} in the XML stream.
8959 ;; The js2-ts-string is the XML up to the left-curly.
8960 ((= tt js2-XML)
8961 (push (make-js2-string-node :pos js2-token-beg
8962 :len (- js2-ts-cursor js2-token-beg))
8963 kids)
8964 (js2-must-match js2-LC "msg.syntax")
8965 (setq expr-pos js2-ts-cursor
8966 expr (if (eq (js2-peek-token) js2-RC)
8967 (make-js2-empty-expr-node :pos expr-pos)
8968 (js2-parse-expr)))
8969 (js2-must-match js2-RC "msg.syntax")
8970 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8971 :len (js2-node-len expr)
8972 :expr expr))
8973 (js2-node-add-children pn expr)
8974 (push pn kids))
8975 ;; a js2-XMLEND token means we hit the final close-tag.
8976 ((= tt js2-XMLEND)
8977 (push (make-js2-string-node :pos js2-token-beg
8978 :len (- js2-ts-cursor js2-token-beg))
8979 kids)
8980 (dolist (kid (nreverse kids))
8981 (js2-block-node-push pn-xml kid))
8982 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8983 (js2-node-pos pn-xml))
8984 continue nil))
8985 (t
8986 (js2-report-error "msg.syntax")
8987 (setq continue nil))))
8988 pn-xml))
8989
8990
8991 (defun js2-parse-argument-list ()
8992 "Parse an argument list and return it as a lisp list of nodes.
8993 Returns the list in reverse order. Consumes the right-paren token."
8994 (let (result)
8995 (unless (js2-match-token js2-RP)
8996 (loop do
8997 (if (= (js2-peek-token) js2-YIELD)
8998 (js2-report-error "msg.yield.parenthesized"))
8999 (push (js2-parse-assign-expr) result)
9000 while
9001 (js2-match-token js2-COMMA))
9002 (js2-must-match js2-RP "msg.no.paren.arg")
9003 result)))
9004
9005 (defun js2-parse-member-expr (&optional allow-call-syntax)
9006 (let ((tt (js2-peek-token))
9007 pn
9008 pos
9009 target
9010 args
9011 beg
9012 end
9013 init
9014 tail)
9015 (if (/= tt js2-NEW)
9016 (setq pn (js2-parse-primary-expr))
9017 ;; parse a 'new' expression
9018 (js2-consume-token)
9019 (setq pos js2-token-beg
9020 beg pos
9021 target (js2-parse-member-expr)
9022 end (js2-node-end target)
9023 pn (make-js2-new-node :pos pos
9024 :target target
9025 :len (- end pos)))
9026 (js2-node-add-children pn target)
9027 (when (js2-match-token js2-LP)
9028 ;; Add the arguments to pn, if any are supplied.
9029 (setf beg pos ; start of "new" keyword
9030 pos js2-token-beg
9031 args (nreverse (js2-parse-argument-list))
9032 (js2-new-node-args pn) args
9033 end js2-token-end
9034 (js2-new-node-lp pn) (- pos beg)
9035 (js2-new-node-rp pn) (- end 1 beg))
9036 (apply #'js2-node-add-children pn args))
9037 (when (and js2-allow-rhino-new-expr-initializer
9038 (js2-match-token js2-LC))
9039 (setf init (js2-parse-object-literal)
9040 end (js2-node-end init)
9041 (js2-new-node-initializer pn) init)
9042 (js2-node-add-children pn init))
9043 (setf (js2-node-len pn) (- end beg))) ; end outer if
9044 (js2-parse-member-expr-tail allow-call-syntax pn)))
9045
9046 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9047 "Parse a chain of property/array accesses or function calls.
9048 Includes parsing for E4X operators like `..' and `.@'.
9049 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9050 Returns an expression tree that includes PN, the parent node."
9051 (let ((beg (js2-node-pos pn))
9052 tt
9053 (continue t))
9054 (while continue
9055 (setq tt (js2-peek-token))
9056 (cond
9057 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9058 (setq pn (js2-parse-property-access tt pn)))
9059 ((= tt js2-DOTQUERY)
9060 (setq pn (js2-parse-dot-query pn)))
9061 ((= tt js2-LB)
9062 (setq pn (js2-parse-element-get pn)))
9063 ((= tt js2-LP)
9064 (if allow-call-syntax
9065 (setq pn (js2-parse-function-call pn))
9066 (setq continue nil)))
9067 (t
9068 (setq continue nil))))
9069 (if (>= js2-highlight-level 2)
9070 (js2-parse-highlight-member-expr-node pn))
9071 pn))
9072
9073 (defun js2-parse-dot-query (pn)
9074 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9075 Last token parsed must be `js2-DOTQUERY'."
9076 (let ((pos (js2-node-pos pn))
9077 op-pos
9078 expr
9079 end)
9080 (js2-consume-token)
9081 (js2-must-have-xml)
9082 (js2-set-requires-activation)
9083 (setq op-pos js2-token-beg
9084 expr (js2-parse-expr)
9085 end (js2-node-end expr)
9086 pn (make-js2-xml-dot-query-node :left pn
9087 :pos pos
9088 :op-pos op-pos
9089 :right expr))
9090 (js2-node-add-children pn
9091 (js2-xml-dot-query-node-left pn)
9092 (js2-xml-dot-query-node-right pn))
9093 (if (js2-must-match js2-RP "msg.no.paren")
9094 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9095 end js2-token-end))
9096 (setf (js2-node-len pn) (- end pos))
9097 pn))
9098
9099 (defun js2-parse-element-get (pn)
9100 "Parse an element-get expression, e.g. foo[bar].
9101 Last token parsed must be `js2-RB'."
9102 (let ((lb js2-token-beg)
9103 (pos (js2-node-pos pn))
9104 rb
9105 expr)
9106 (js2-consume-token)
9107 (setq expr (js2-parse-expr))
9108 (if (js2-must-match js2-RB "msg.no.bracket.index")
9109 (setq rb js2-token-beg))
9110 (setq pn (make-js2-elem-get-node :target pn
9111 :pos pos
9112 :element expr
9113 :lb (js2-relpos lb pos)
9114 :rb (js2-relpos rb pos)
9115 :len (- js2-token-end pos)))
9116 (js2-node-add-children pn
9117 (js2-elem-get-node-target pn)
9118 (js2-elem-get-node-element pn))
9119 pn))
9120
9121 (defun js2-parse-function-call (pn)
9122 (let (args
9123 (pos (js2-node-pos pn)))
9124 (js2-consume-token)
9125 (setq pn (make-js2-call-node :pos pos
9126 :target pn
9127 :lp (- js2-token-beg pos)))
9128 (js2-node-add-children pn (js2-call-node-target pn))
9129 ;; Add the arguments to pn, if any are supplied.
9130 (setf args (nreverse (js2-parse-argument-list))
9131 (js2-call-node-rp pn) (- js2-token-beg pos)
9132 (js2-call-node-args pn) args)
9133 (apply #'js2-node-add-children pn args)
9134 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9135 pn))
9136
9137 (defun js2-parse-property-access (tt pn)
9138 "Parse a property access, XML descendants access, or XML attr access."
9139 (let ((member-type-flags 0)
9140 (dot-pos js2-token-beg)
9141 (dot-len (if (= tt js2-DOTDOT) 2 1))
9142 name
9143 ref ; right side of . or .. operator
9144 result)
9145 (js2-consume-token)
9146 (when (= tt js2-DOTDOT)
9147 (js2-must-have-xml)
9148 (setq member-type-flags js2-descendants-flag))
9149 (if (not js2-compiler-xml-available)
9150 (progn
9151 (js2-must-match-prop-name "msg.no.name.after.dot")
9152 (setq name (js2-create-name-node t js2-GETPROP)
9153 result (make-js2-prop-get-node :left pn
9154 :pos js2-token-beg
9155 :right name
9156 :len (- js2-token-end
9157 js2-token-beg)))
9158 (js2-node-add-children result pn name)
9159 result)
9160 ;; otherwise look for XML operators
9161 (setf result (if (= tt js2-DOT)
9162 (make-js2-prop-get-node)
9163 (make-js2-infix-node :type js2-DOTDOT))
9164 (js2-node-pos result) (js2-node-pos pn)
9165 (js2-infix-node-op-pos result) dot-pos
9166 (js2-infix-node-left result) pn ; do this after setting position
9167 tt (js2-next-token))
9168 (cond
9169 ;; needed for generator.throw()
9170 ((= tt js2-THROW)
9171 (js2-save-name-token-data js2-token-beg "throw")
9172 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9173 ;; handles: name, ns::name, ns::*, ns::[expr]
9174 ((js2-valid-prop-name-token tt)
9175 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9176 ;; handles: *, *::name, *::*, *::[expr]
9177 ((= tt js2-MUL)
9178 (js2-save-name-token-data js2-token-beg "*")
9179 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9180 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9181 ((= tt js2-XMLATTR)
9182 (setq result (js2-parse-attribute-access)))
9183 (t
9184 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9185 (if ref
9186 (setf (js2-node-len result) (- (js2-node-end ref)
9187 (js2-node-pos result))
9188 (js2-infix-node-right result) ref))
9189 (if (js2-infix-node-p result)
9190 (js2-node-add-children result
9191 (js2-infix-node-left result)
9192 (js2-infix-node-right result)))
9193 result)))
9194
9195 (defun js2-parse-attribute-access ()
9196 "Parse an E4X XML attribute expression.
9197 This includes expressions of the forms:
9198
9199 @attr @ns::attr @ns::*
9200 @* @*::attr @*::*
9201 @[expr] @*::[expr] @ns::[expr]
9202
9203 Called if we peeked an '@' token."
9204 (let ((tt (js2-next-token))
9205 (at-pos js2-token-beg))
9206 (cond
9207 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9208 ((js2-valid-prop-name-token tt)
9209 (js2-parse-property-name at-pos js2-ts-string 0))
9210 ;; handles: @*, @*::name, @*::*, @*::[expr]
9211 ((= tt js2-MUL)
9212 (js2-save-name-token-data js2-token-beg "*")
9213 (js2-parse-property-name js2-token-beg "*" 0))
9214 ;; handles @[expr]
9215 ((= tt js2-LB)
9216 (js2-parse-xml-elem-ref at-pos))
9217 (t
9218 (js2-report-error "msg.no.name.after.xmlAttr")
9219 ;; Avoid cascaded errors that happen if we make an error node here.
9220 (js2-save-name-token-data js2-token-beg "")
9221 (js2-parse-property-name js2-token-beg "" 0)))))
9222
9223 (defun js2-parse-property-name (at-pos s member-type-flags)
9224 "Check if :: follows name in which case it becomes qualified name.
9225
9226 AT-POS is a natural number if we just read an '@' token, else nil.
9227 S is the name or string that was matched: an identifier, 'throw' or '*'.
9228 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9229
9230 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9231 operator, or the name is followed by ::. For a plain name, returns a
9232 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9233 (let ((pos (or at-pos js2-token-beg))
9234 colon-pos
9235 (name (js2-create-name-node t js2-current-token))
9236 ns
9237 tt
9238 ref
9239 pn)
9240 (catch 'return
9241 (when (js2-match-token js2-COLONCOLON)
9242 (setq ns name
9243 colon-pos js2-token-beg
9244 tt (js2-next-token))
9245 (cond
9246 ;; handles name::name
9247 ((js2-valid-prop-name-token tt)
9248 (setq name (js2-create-name-node)))
9249 ;; handles name::*
9250 ((= tt js2-MUL)
9251 (js2-save-name-token-data js2-token-beg "*")
9252 (setq name (js2-create-name-node)))
9253 ;; handles name::[expr]
9254 ((= tt js2-LB)
9255 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9256 (t
9257 (js2-report-error "msg.no.name.after.coloncolon"))))
9258 (if (and (null ns) (zerop member-type-flags))
9259 name
9260 (prog1
9261 (setq pn
9262 (make-js2-xml-prop-ref-node :pos pos
9263 :len (- (js2-node-end name) pos)
9264 :at-pos at-pos
9265 :colon-pos colon-pos
9266 :propname name))
9267 (js2-node-add-children pn name))))))
9268
9269 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9270 "Parse the [expr] portion of an xml element reference.
9271 For instance, @[expr], @*::[expr], or ns::[expr]."
9272 (let* ((lb js2-token-beg)
9273 (pos (or at-pos lb))
9274 rb
9275 (expr (js2-parse-expr))
9276 (end (js2-node-end expr))
9277 pn)
9278 (if (js2-must-match js2-RB "msg.no.bracket.index")
9279 (setq rb js2-token-beg
9280 end js2-token-end))
9281 (prog1
9282 (setq pn
9283 (make-js2-xml-elem-ref-node :pos pos
9284 :len (- end pos)
9285 :namespace namespace
9286 :colon-pos colon-pos
9287 :at-pos at-pos
9288 :expr expr
9289 :lb (js2-relpos lb pos)
9290 :rb (js2-relpos rb pos)))
9291 (js2-node-add-children pn namespace expr))))
9292
9293 (defsubst js2-parse-primary-expr-lhs ()
9294 (let ((js2-is-in-lhs t))
9295 (js2-parse-primary-expr)))
9296
9297 (defun js2-parse-primary-expr ()
9298 "Parses a literal (leaf) expression of some sort.
9299 Includes complex literals such as functions, object-literals,
9300 array-literals, array comprehensions and regular expressions."
9301 (let ((tt-flagged (js2-next-flagged-token))
9302 pn ; parent node (usually return value)
9303 tt
9304 px-pos ; paren-expr pos
9305 len
9306 flags ; regexp flags
9307 expr)
9308 (setq tt js2-current-token)
9309 (cond
9310 ((= tt js2-FUNCTION)
9311 (js2-parse-function 'FUNCTION_EXPRESSION))
9312 ((= tt js2-LB)
9313 (js2-parse-array-literal))
9314 ((= tt js2-LC)
9315 (js2-parse-object-literal))
9316 ((= tt js2-LET)
9317 (js2-parse-let js2-token-beg))
9318 ((= tt js2-LP)
9319 (setq px-pos js2-token-beg
9320 expr (js2-parse-expr))
9321 (js2-must-match js2-RP "msg.no.paren")
9322 (setq pn (make-js2-paren-node :pos px-pos
9323 :expr expr
9324 :len (- js2-token-end px-pos)))
9325 (js2-node-add-children pn (js2-paren-node-expr pn))
9326 pn)
9327 ((= tt js2-XMLATTR)
9328 (js2-must-have-xml)
9329 (js2-parse-attribute-access))
9330 ((= tt js2-NAME)
9331 (js2-parse-name tt-flagged tt))
9332 ((= tt js2-NUMBER)
9333 (make-js2-number-node))
9334 ((= tt js2-STRING)
9335 (prog1
9336 (make-js2-string-node)
9337 (js2-record-face 'font-lock-string-face)))
9338 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9339 ;; Got / or /= which in this context means a regexp literal
9340 (setq px-pos js2-token-beg)
9341 (js2-read-regexp tt)
9342 (setq flags js2-ts-regexp-flags
9343 js2-ts-regexp-flags nil)
9344 (prog1
9345 (make-js2-regexp-node :pos px-pos
9346 :len (- js2-ts-cursor px-pos)
9347 :value js2-ts-string
9348 :flags flags)
9349 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9350 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9351 ((or (= tt js2-NULL)
9352 (= tt js2-THIS)
9353 (= tt js2-FALSE)
9354 (= tt js2-TRUE))
9355 (make-js2-keyword-node :type tt))
9356 ((= tt js2-RESERVED)
9357 (js2-report-error "msg.reserved.id")
9358 (make-js2-name-node))
9359 ((= tt js2-ERROR)
9360 ;; the scanner or one of its subroutines reported the error.
9361 (make-js2-error-node))
9362 ((= tt js2-EOF)
9363 (setq px-pos (point-at-bol)
9364 len (- js2-ts-cursor px-pos))
9365 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9366 (make-js2-error-node :pos px-pos :len len))
9367 (t
9368 (js2-report-error "msg.syntax")
9369 (make-js2-error-node)))))
9370
9371 (defun js2-parse-name (tt-flagged tt)
9372 (let ((name js2-ts-string)
9373 (name-pos js2-token-beg)
9374 node)
9375 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9376 (= (js2-peek-token) js2-COLON))
9377 (prog1
9378 ;; Do not consume colon, it is used as unwind indicator
9379 ;; to return to statementHelper.
9380 (make-js2-label-node :pos name-pos
9381 :len (- js2-token-end name-pos)
9382 :name name)
9383 (js2-set-face name-pos
9384 js2-token-end
9385 'font-lock-variable-name-face 'record))
9386 ;; Otherwise not a label, just a name. Unfortunately peeking
9387 ;; the next token to check for a colon has biffed js2-token-beg
9388 ;; and js2-token-end. We store the name's bounds in buffer vars
9389 ;; and `js2-create-name-node' uses them.
9390 (js2-save-name-token-data name-pos name)
9391 (setq node (if js2-compiler-xml-available
9392 (js2-parse-property-name nil name 0)
9393 (js2-create-name-node 'check-activation)))
9394 (if js2-highlight-external-variables
9395 (js2-record-name-node node))
9396 node)))
9397
9398 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9399 (js2-add-strict-warning
9400 msg nil
9401 ;; back up from comma to beginning of line or array/objlit
9402 (max (if elems
9403 (js2-node-pos (car elems))
9404 pos)
9405 (save-excursion
9406 (goto-char comma-pos)
9407 (back-to-indentation)
9408 (point)))
9409 comma-pos))
9410
9411 (defun js2-parse-array-literal ()
9412 (let ((pos js2-token-beg)
9413 (end js2-token-end)
9414 (after-lb-or-comma t)
9415 after-comma
9416 tt
9417 elems
9418 pn
9419 (continue t))
9420 (unless js2-is-in-lhs
9421 (js2-push-scope (make-js2-scope))) ; for array comp
9422 (while continue
9423 (setq tt (js2-peek-token))
9424 (cond
9425 ;; comma
9426 ((= tt js2-COMMA)
9427 (js2-consume-token)
9428 (setq after-comma js2-token-end)
9429 (if (not after-lb-or-comma)
9430 (setq after-lb-or-comma t)
9431 (push nil elems)))
9432 ;; end of array
9433 ((or (= tt js2-RB)
9434 (= tt js2-EOF)) ; prevent infinite loop
9435 (if (= tt js2-EOF)
9436 (js2-report-error "msg.no.bracket.arg" nil pos)
9437 (js2-consume-token))
9438 (setq continue nil
9439 end js2-token-end
9440 pn (make-js2-array-node :pos pos
9441 :len (- js2-ts-cursor pos)
9442 :elems (nreverse elems)))
9443 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9444 (when (and after-comma (not js2-is-in-lhs))
9445 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9446 pos elems after-comma)))
9447 ;; destructuring binding
9448 (js2-is-in-lhs
9449 (push (if (or (= tt js2-LC)
9450 (= tt js2-LB)
9451 (= tt js2-NAME))
9452 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9453 (js2-parse-primary-expr-lhs)
9454 ;; invalid pattern
9455 (js2-consume-token)
9456 (js2-report-error "msg.bad.var")
9457 (make-js2-error-node))
9458 elems)
9459 (setq after-lb-or-comma nil
9460 after-comma nil))
9461 ;; array comp
9462 ((and (>= js2-language-version 170)
9463 (= tt js2-FOR) ; check for array comprehension
9464 (not after-lb-or-comma) ; "for" can't follow a comma
9465 elems ; must have at least 1 element
9466 (not (cdr elems))) ; but no 2nd element
9467 (setf continue nil
9468 pn (js2-parse-array-comprehension (car elems) pos)))
9469
9470 ;; another element
9471 (t
9472 (unless after-lb-or-comma
9473 (js2-report-error "msg.no.bracket.arg"))
9474 (push (js2-parse-assign-expr) elems)
9475 (setq after-lb-or-comma nil
9476 after-comma nil))))
9477 (unless js2-is-in-lhs
9478 (js2-pop-scope))
9479 pn))
9480
9481 (defun js2-parse-array-comprehension (expr pos)
9482 "Parse a JavaScript 1.7 Array Comprehension.
9483 EXPR is the first expression after the opening left-bracket.
9484 POS is the beginning of the LB token preceding EXPR.
9485 We should have just parsed the 'for' keyword before calling this function."
9486 (let (loops
9487 loop
9488 first
9489 prev
9490 filter
9491 if-pos
9492 result)
9493 (while (= (js2-peek-token) js2-FOR)
9494 (let ((prev (car loops))) ; rearrange scope chain
9495 (push (setq loop (js2-parse-array-comp-loop)) loops)
9496 (if prev ; each loop is parent scope to the next one
9497 (setf (js2-scope-parent-scope loop) prev)
9498 ; first loop takes expr scope's parent
9499 (setf (js2-scope-parent-scope (setq first loop))
9500 (js2-scope-parent-scope js2-current-scope)))))
9501 ;; set expr scope's parent to the last loop
9502 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9503 (when (= (js2-peek-token) js2-IF)
9504 (js2-consume-token)
9505 (setq if-pos (- js2-token-beg pos) ; relative
9506 filter (js2-parse-condition)))
9507 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9508 (setq result (make-js2-array-comp-node :pos pos
9509 :len (- js2-ts-cursor pos)
9510 :result expr
9511 :loops (nreverse loops)
9512 :filter (car filter)
9513 :lp (js2-relpos (second filter) pos)
9514 :rp (js2-relpos (third filter) pos)
9515 :if-pos if-pos))
9516 (apply #'js2-node-add-children result expr (car filter)
9517 (js2-array-comp-node-loops result))
9518 (setq js2-current-scope first) ; pop to the first loop
9519 result))
9520
9521 (defun js2-parse-array-comp-loop ()
9522 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9523 Last token peeked should be the initial FOR."
9524 (let ((pos js2-token-beg)
9525 (pn (make-js2-array-comp-loop-node))
9526 tt
9527 iter
9528 obj
9529 foreach-p
9530 in-pos
9531 each-pos
9532 lp
9533 rp)
9534 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9535 (js2-push-scope pn)
9536 (unwind-protect
9537 (progn
9538 (when (js2-match-token js2-NAME)
9539 (if (string= js2-ts-string "each")
9540 (progn
9541 (setq foreach-p t
9542 each-pos (- js2-token-beg pos)) ; relative
9543 (js2-record-face 'font-lock-keyword-face))
9544 (js2-report-error "msg.no.paren.for")))
9545 (if (js2-must-match js2-LP "msg.no.paren.for")
9546 (setq lp (- js2-token-beg pos)))
9547 (setq tt (js2-peek-token))
9548 (cond
9549 ((or (= tt js2-LB)
9550 (= tt js2-LC))
9551 ;; handle destructuring assignment
9552 (setq iter (js2-parse-primary-expr-lhs))
9553 (js2-define-destruct-symbols iter js2-LET
9554 'font-lock-variable-name-face t))
9555 ((js2-valid-prop-name-token tt)
9556 (js2-consume-token)
9557 (setq iter (js2-create-name-node)))
9558 (t
9559 (js2-report-error "msg.bad.var")))
9560 ;; Define as a let since we want the scope of the variable to
9561 ;; be restricted to the array comprehension
9562 (if (js2-name-node-p iter)
9563 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9564 (if (js2-must-match js2-IN "msg.in.after.for.name")
9565 (setq in-pos (- js2-token-beg pos)))
9566 (setq obj (js2-parse-expr))
9567 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9568 (setq rp (- js2-token-beg pos)))
9569 (setf (js2-node-pos pn) pos
9570 (js2-node-len pn) (- js2-ts-cursor pos)
9571 (js2-array-comp-loop-node-iterator pn) iter
9572 (js2-array-comp-loop-node-object pn) obj
9573 (js2-array-comp-loop-node-in-pos pn) in-pos
9574 (js2-array-comp-loop-node-each-pos pn) each-pos
9575 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9576 (js2-array-comp-loop-node-lp pn) lp
9577 (js2-array-comp-loop-node-rp pn) rp)
9578 (js2-node-add-children pn iter obj))
9579 (js2-pop-scope))
9580 pn))
9581
9582 (defun js2-parse-object-literal ()
9583 (let ((pos js2-token-beg)
9584 tt
9585 elems
9586 result
9587 after-comma
9588 (continue t))
9589 (while continue
9590 (setq tt (js2-peek-token))
9591 (cond
9592 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9593 ((or (js2-valid-prop-name-token tt)
9594 (= tt js2-STRING))
9595 (setq after-comma nil
9596 result (js2-parse-named-prop tt))
9597 (if (and (null result)
9598 (not js2-recover-from-parse-errors))
9599 (setq continue nil)
9600 (push result elems)))
9601 ;; {12: x} or {10.7: x}
9602 ((= tt js2-NUMBER)
9603 (js2-consume-token)
9604 (setq after-comma nil)
9605 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9606 ;; trailing comma
9607 ((= tt js2-RC)
9608 (setq continue nil)
9609 (if after-comma
9610 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9611 pos elems after-comma)))
9612 (t
9613 (js2-report-error "msg.bad.prop")
9614 (unless js2-recover-from-parse-errors
9615 (setq continue nil)))) ; end switch
9616 (if (js2-match-token js2-COMMA)
9617 (setq after-comma js2-token-end)
9618 (setq continue nil))) ; end loop
9619 (js2-must-match js2-RC "msg.no.brace.prop")
9620 (setq result (make-js2-object-node :pos pos
9621 :len (- js2-ts-cursor pos)
9622 :elems (nreverse elems)))
9623 (apply #'js2-node-add-children result (js2-object-node-elems result))
9624 result))
9625
9626 (defun js2-parse-named-prop (tt)
9627 "Parse a name, string, or getter/setter object property.
9628 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9629 (js2-consume-token)
9630 (let ((string-prop (and (= tt js2-STRING)
9631 (make-js2-string-node)))
9632 expr
9633 (ppos js2-token-beg)
9634 (pend js2-token-end)
9635 (name (js2-create-name-node))
9636 (prop js2-ts-string))
9637 (cond
9638 ;; getter/setter prop
9639 ((and (= tt js2-NAME)
9640 (= (js2-peek-token) js2-NAME)
9641 (or (string= prop "get")
9642 (string= prop "set")))
9643 (js2-consume-token)
9644 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9645 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9646 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9647 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9648 ;; abbreviated destructuring bind e.g., {a, b} = c;
9649 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9650 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9651 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9652 ;; assignment but it's difficult because it requires looking ahead of expression.
9653 ((and js2-is-in-lhs
9654 (= tt js2-NAME)
9655 (let ((ctk (js2-peek-token)))
9656 (or (= ctk js2-COMMA)
9657 (= ctk js2-RC)
9658 (js2-valid-prop-name-token ctk))))
9659 name)
9660 ;; regular prop
9661 (t
9662 (prog1
9663 (setq expr (js2-parse-plain-property (or string-prop name)))
9664 (js2-set-face ppos pend
9665 (if (js2-function-node-p
9666 (js2-object-prop-node-right expr))
9667 'font-lock-function-name-face
9668 'font-lock-variable-name-face)
9669 'record))))))
9670
9671 (defun js2-parse-plain-property (prop)
9672 "Parse a non-getter/setter property in an object literal.
9673 PROP is the node representing the property: a number, name or string."
9674 (js2-must-match js2-COLON "msg.no.colon.prop")
9675 (let* ((pos (js2-node-pos prop))
9676 (colon (- js2-token-beg pos))
9677 (expr (js2-parse-assign-expr))
9678 (result (make-js2-object-prop-node
9679 :pos pos
9680 ;; don't include last consumed token in length
9681 :len (- (+ (js2-node-pos expr)
9682 (js2-node-len expr))
9683 pos)
9684 :left prop
9685 :right expr
9686 :op-pos colon)))
9687 (js2-node-add-children result prop expr)
9688 result))
9689
9690 (defun js2-parse-getter-setter-prop (pos prop get-p)
9691 "Parse getter or setter property in an object literal.
9692 JavaScript syntax is:
9693
9694 { get foo() {...}, set foo(x) {...} }
9695
9696 and expression closure style is also supported
9697
9698 { get foo() x, set foo(x) _x = x }
9699
9700 POS is the start position of the `get' or `set' keyword.
9701 PROP is the `js2-name-node' representing the property name.
9702 GET-P is non-nil if the keyword was `get'."
9703 (let ((type (if get-p js2-GET js2-SET))
9704 result
9705 end
9706 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9707 ;; it has to be an anonymous function, as we already parsed the name
9708 (if (/= (js2-node-type fn) js2-FUNCTION)
9709 (js2-report-error "msg.bad.prop")
9710 (if (plusp (length (js2-function-name fn)))
9711 (js2-report-error "msg.bad.prop")))
9712 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9713 (setq end (js2-node-end fn)
9714 result (make-js2-getter-setter-node :type type
9715 :pos pos
9716 :len (- end pos)
9717 :left prop
9718 :right fn))
9719 (js2-node-add-children result prop fn)
9720 result))
9721
9722 (defun js2-create-name-node (&optional check-activation-p token)
9723 "Create a name node using the token info from last scanned name.
9724 In some cases we need to either synthesize a name node, or we lost
9725 the name token information by peeking. If the TOKEN parameter is
9726 not `js2-NAME', then we use the token info saved in instance vars."
9727 (let ((beg js2-token-beg)
9728 (s js2-ts-string)
9729 name)
9730 (when (/= js2-current-token js2-NAME)
9731 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9732 s js2-prev-name-token-string
9733 js2-prev-name-token-start nil
9734 js2-prev-name-token-string nil))
9735 (setq name (make-js2-name-node :pos beg
9736 :name s
9737 :len (length s)))
9738 (if check-activation-p
9739 (js2-check-activation-name s (or token js2-NAME)))
9740 name))
9741
9742 ;;; Indentation support
9743
9744 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9745 ;; Karl cleverly deduces that the desired indentation level is often a
9746 ;; function of paren/bracket/brace nesting depth, which can be determined
9747 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9748 ;; then does some equally clever checks to see if we're in the context of a
9749 ;; substatement of a possibly braceless statement keyword such as if, while,
9750 ;; or finally. This approach yields pretty good results.
9751
9752 ;; The indenter is often "wrong", however, and needs to be overridden.
9753 ;; The right long-term solution is probably to emulate (or integrate
9754 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9755 ;; parse tree from `js2-parse' is present, which is not true at the
9756 ;; moment the user is typing, computing indentation is still thousands
9757 ;; of lines of code to handle every possible syntactic edge case.
9758
9759 ;; In the meantime, the compromise solution is that we offer a "bounce
9760 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9761 ;; current line indent among various likely guess points. This approach
9762 ;; is far from perfect, but should at least make it slightly easier to
9763 ;; move the line towards its desired indentation when manually
9764 ;; overriding Karl's heuristic nesting guesser.
9765
9766 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9767 ;; extensions such as `let' and Array comprehensions. Major kudos to
9768 ;; Karl for coming up with the initial approach, which packs a lot of
9769 ;; punch for so little code.
9770
9771 (defconst js-possibly-braceless-keywords-re
9772 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9773 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9774 "try" "while" "with" "let")))
9775 "Regular expression matching keywords that are optionally
9776 followed by an opening brace.")
9777
9778 (defconst js-indent-operator-re
9779 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9780 (regexp-opt '("in" "instanceof") 'words))
9781 "Regular expression matching operators that affect indentation
9782 of continued expressions.")
9783
9784 (defconst js-declaration-keyword-re
9785 (regexp-opt '("var" "let" "const") 'words)
9786 "Regular expression matching variable declaration keywords.")
9787
9788 ;; This function has horrible results if you're typing an array
9789 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9790 ;; in conjunction with electric-indent, so just disabling it.
9791 (defsubst js2-code-at-bol-p ()
9792 "Return t if the first character on line is non-whitespace."
9793 nil)
9794
9795 (defun js2-insert-and-indent (key)
9796 "Run command bound to key and indent current line. Runs the command
9797 bound to KEY in the global keymap and indents the current line."
9798 (interactive (list (this-command-keys)))
9799 (let ((cmd (lookup-key (current-global-map) key)))
9800 (if (commandp cmd)
9801 (call-interactively cmd)))
9802 ;; don't do the electric keys inside comments or strings,
9803 ;; and don't do bounce-indent with them.
9804 (let ((parse-state (syntax-ppss (point)))
9805 (js2-bounce-indent-p (js2-code-at-bol-p)))
9806 (unless (or (nth 3 parse-state)
9807 (nth 4 parse-state))
9808 (indent-according-to-mode))))
9809
9810 (defun js-re-search-forward-inner (regexp &optional bound count)
9811 "Auxiliary function for `js-re-search-forward'."
9812 (let (parse saved-point)
9813 (while (> count 0)
9814 (re-search-forward regexp bound)
9815 (setq parse (if saved-point
9816 (parse-partial-sexp saved-point (point))
9817 (syntax-ppss (point))))
9818 (cond ((nth 3 parse)
9819 (re-search-forward
9820 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9821 (save-excursion (end-of-line) (point)) t))
9822 ((nth 7 parse)
9823 (forward-line))
9824 ((or (nth 4 parse)
9825 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9826 (re-search-forward "\\*/"))
9827 (t
9828 (setq count (1- count))))
9829 (setq saved-point (point))))
9830 (point))
9831
9832 (defun js-re-search-forward (regexp &optional bound noerror count)
9833 "Search forward but ignore strings and comments. Invokes
9834 `re-search-forward' but treats the buffer as if strings and
9835 comments have been removed."
9836 (let ((saved-point (point))
9837 (search-expr
9838 (cond ((null count)
9839 '(js-re-search-forward-inner regexp bound 1))
9840 ((< count 0)
9841 '(js-re-search-backward-inner regexp bound (- count)))
9842 ((> count 0)
9843 '(js-re-search-forward-inner regexp bound count)))))
9844 (condition-case err
9845 (eval search-expr)
9846 (search-failed
9847 (goto-char saved-point)
9848 (unless noerror
9849 (error (error-message-string err)))))))
9850
9851 (defun js-re-search-backward-inner (regexp &optional bound count)
9852 "Auxiliary function for `js-re-search-backward'."
9853 (let (parse saved-point)
9854 (while (> count 0)
9855 (re-search-backward regexp bound)
9856 (setq parse (if saved-point
9857 (parse-partial-sexp saved-point (point))
9858 (syntax-ppss (point))))
9859 (cond ((nth 3 parse)
9860 (re-search-backward
9861 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9862 (save-excursion (beginning-of-line) (point)) t))
9863 ((nth 7 parse)
9864 (goto-char (nth 8 parse)))
9865 ((or (nth 4 parse)
9866 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9867 (re-search-backward "/\\*"))
9868 (t
9869 (setq count (1- count))))))
9870 (point))
9871
9872 (defun js-re-search-backward (regexp &optional bound noerror count)
9873 "Search backward but ignore strings and comments. Invokes
9874 `re-search-backward' but treats the buffer as if strings and
9875 comments have been removed."
9876 (let ((saved-point (point))
9877 (search-expr
9878 (cond ((null count)
9879 '(js-re-search-backward-inner regexp bound 1))
9880 ((< count 0)
9881 '(js-re-search-forward-inner regexp bound (- count)))
9882 ((> count 0)
9883 '(js-re-search-backward-inner regexp bound count)))))
9884 (condition-case err
9885 (eval search-expr)
9886 (search-failed
9887 (goto-char saved-point)
9888 (unless noerror
9889 (error (error-message-string err)))))))
9890
9891 (defun js-looking-at-operator-p ()
9892 "Return non-nil if text after point is an operator (that is not
9893 a comma)."
9894 (save-match-data
9895 (and (looking-at js-indent-operator-re)
9896 (or (not (looking-at ":"))
9897 (save-excursion
9898 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9899 (looking-at "?")))))))
9900
9901 (defun js-continued-expression-p ()
9902 "Returns non-nil if the current line continues an expression."
9903 (save-excursion
9904 (back-to-indentation)
9905 (or (js-looking-at-operator-p)
9906 ;; comment
9907 (and (js-re-search-backward "\n" nil t)
9908 (progn
9909 (skip-chars-backward " \t")
9910 (unless (bolp)
9911 (backward-char)
9912 (and (js-looking-at-operator-p)
9913 (and (progn
9914 (backward-char)
9915 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9916
9917 (defun js-end-of-do-while-loop-p ()
9918 "Returns non-nil if word after point is `while' of a do-while
9919 statement, else returns nil. A braceless do-while statement
9920 spanning several lines requires that the start of the loop is
9921 indented to the same column as the current line."
9922 (interactive)
9923 (save-excursion
9924 (save-match-data
9925 (when (looking-at "\\s-*\\<while\\>")
9926 (if (save-excursion
9927 (skip-chars-backward "[ \t\n]*}")
9928 (looking-at "[ \t\n]*}"))
9929 (save-excursion
9930 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9931 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9932 (or (looking-at "\\<do\\>")
9933 (let ((saved-indent (current-indentation)))
9934 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9935 (/= (current-indentation) saved-indent)))
9936 (and (looking-at "[ \t]*\\<do\\>")
9937 (not (js-re-search-forward
9938 "\\<while\\>" (point-at-eol) t))
9939 (= (current-indentation) saved-indent)))))))))
9940
9941 (defun js-multiline-decl-indentation ()
9942 "Returns the declaration indentation column if the current line belongs
9943 to a multiline declaration statement. All declarations are lined up vertically:
9944
9945 var a = 10,
9946 b = 20,
9947 c = 30;
9948
9949 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9950 assigned expression is a function or array/object literal, it will be indented
9951 differently:
9952
9953 var o = { var bar = 2,
9954 foo: 3 o = {
9955 }, foo: 3
9956 bar = 2; };
9957 "
9958 (let (forward-sexp-function ; use lisp version
9959 at-opening-bracket)
9960 (save-excursion
9961 (back-to-indentation)
9962 (when (not (looking-at js-declaration-keyword-re))
9963 (when (looking-at js-indent-operator-re)
9964 (goto-char (match-end 0))) ; continued expressions are ok
9965 (while (and (not at-opening-bracket)
9966 (not (bobp))
9967 (let ((pos (point)))
9968 (save-excursion
9969 (js2-backward-sws)
9970 (or (eq (char-before) ?,)
9971 (and (not (eq (char-before) ?\;))
9972 (and
9973 (prog2 (skip-chars-backward "[[:punct:]]")
9974 (looking-at js-indent-operator-re)
9975 (js2-backward-sws))
9976 (not (eq (char-before) ?\;))))
9977 (js2-same-line pos)))))
9978 (condition-case err
9979 (backward-sexp)
9980 (scan-error (setq at-opening-bracket t))))
9981 (when (looking-at js-declaration-keyword-re)
9982 (- (1+ (match-end 0)) (point-at-bol)))))))
9983
9984 (defun js-ctrl-statement-indentation ()
9985 "Returns the proper indentation of the current line if it
9986 starts the body of a control statement without braces, else
9987 returns nil."
9988 (let (forward-sexp-function) ; temporarily unbind it
9989 (save-excursion
9990 (back-to-indentation)
9991 (when (and (not (js2-same-line (point-min)))
9992 (not (looking-at "{"))
9993 (js-re-search-backward "[[:graph:]]" nil t)
9994 (not (looking-at "[{([]"))
9995 (progn
9996 (forward-char)
9997 (when (= (char-before) ?\))
9998 ;; scan-sexps sometimes throws an error
9999 (ignore-errors (backward-sexp))
10000 (skip-chars-backward " \t" (point-at-bol)))
10001 (let ((pt (point)))
10002 (back-to-indentation)
10003 (and (looking-at js-possibly-braceless-keywords-re)
10004 (= (match-end 0) pt)
10005 (not (js-end-of-do-while-loop-p))))))
10006 (+ (current-indentation) js2-basic-offset)))))
10007
10008 (defun js2-indent-in-array-comp (parse-status)
10009 "Return non-nil if we think we're in an array comprehension.
10010 In particular, return the buffer position of the first `for' kwd."
10011 (let ((bracket (nth 1 parse-status))
10012 (end (point)))
10013 (when bracket
10014 (save-excursion
10015 (goto-char bracket)
10016 (when (looking-at "\\[")
10017 (forward-char 1)
10018 (js2-forward-sws)
10019 (if (looking-at "[[{]")
10020 (let (forward-sexp-function) ; use lisp version
10021 (forward-sexp) ; skip destructuring form
10022 (js2-forward-sws)
10023 (if (and (/= (char-after) ?,) ; regular array
10024 (looking-at "for"))
10025 (match-beginning 0)))
10026 ;; to skip arbitrary expressions we need the parser,
10027 ;; so we'll just guess at it.
10028 (if (and (> end (point)) ; not empty literal
10029 (re-search-forward "[^,]]* \\(for\\) " end t)
10030 ;; not inside comment or string literal
10031 (let ((state (parse-partial-sexp bracket (point))))
10032 (not (or (nth 3 state) (nth 4 state)))))
10033 (match-beginning 1))))))))
10034
10035 (defun js2-array-comp-indentation (parse-status for-kwd)
10036 (if (js2-same-line for-kwd)
10037 ;; first continuation line
10038 (save-excursion
10039 (goto-char (nth 1 parse-status))
10040 (forward-char 1)
10041 (skip-chars-forward " \t")
10042 (current-column))
10043 (save-excursion
10044 (goto-char for-kwd)
10045 (current-column))))
10046
10047 (defun js-proper-indentation (parse-status)
10048 "Return the proper indentation for the current line."
10049 (save-excursion
10050 (back-to-indentation)
10051 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10052 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10053 (continued-expr-p (js-continued-expression-p))
10054 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10055 (js-multiline-decl-indentation)))
10056 (bracket (nth 1 parse-status))
10057 beg)
10058 (cond
10059 ;; indent array comprehension continuation lines specially
10060 ((and bracket
10061 (>= js2-language-version 170)
10062 (not (js2-same-line bracket))
10063 (setq beg (js2-indent-in-array-comp parse-status))
10064 (>= (point) (save-excursion
10065 (goto-char beg)
10066 (point-at-bol)))) ; at or after first loop?
10067 (js2-array-comp-indentation parse-status beg))
10068
10069 (ctrl-stmt-indent)
10070
10071 ((and declaration-indent continued-expr-p)
10072 (+ declaration-indent js2-basic-offset))
10073
10074 (declaration-indent)
10075
10076 (bracket
10077 (goto-char bracket)
10078 (cond
10079 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10080 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10081 (when (save-excursion (skip-chars-backward " \t)")
10082 (looking-at ")"))
10083 (backward-list))
10084 (if (and (nth 1 p)
10085 (not js2-consistent-level-indent-inner-bracket-p))
10086 (progn (goto-char (1+ (nth 1 p)))
10087 (skip-chars-forward " \t"))
10088 (back-to-indentation)
10089 (when (and js2-pretty-multiline-decl-indentation-p
10090 js2-always-indent-assigned-expr-in-decls-p
10091 (looking-at js-declaration-keyword-re))
10092 (goto-char (1+ (match-end 0)))))
10093 (cond (same-indent-p
10094 (current-column))
10095 (continued-expr-p
10096 (+ (current-column) (* 2 js2-basic-offset)))
10097 (t
10098 (+ (current-column) js2-basic-offset)))))
10099 (t
10100 (unless same-indent-p
10101 (forward-char)
10102 (skip-chars-forward " \t"))
10103 (current-column))))
10104
10105 (continued-expr-p js2-basic-offset)
10106
10107 (t 0)))))
10108
10109 (defun js2-lineup-comment (parse-status)
10110 "Indent a multi-line block comment continuation line."
10111 (let* ((beg (nth 8 parse-status))
10112 (first-line (js2-same-line beg))
10113 (offset (save-excursion
10114 (goto-char beg)
10115 (if (looking-at "/\\*")
10116 (+ 1 (current-column))
10117 0))))
10118 (unless first-line
10119 (indent-line-to offset))))
10120
10121 (defun js2-backward-sws ()
10122 "Move backward through whitespace and comments."
10123 (interactive)
10124 (while (forward-comment -1)))
10125
10126 (defun js2-forward-sws ()
10127 "Move forward through whitespace and comments."
10128 (interactive)
10129 (while (forward-comment 1)))
10130
10131 (defsubst js2-current-indent (&optional pos)
10132 "Return column of indentation on current line.
10133 If POS is non-nil, go to that point and return indentation for that line."
10134 (save-excursion
10135 (if pos
10136 (goto-char pos))
10137 (back-to-indentation)
10138 (current-column)))
10139
10140 (defsubst js2-arglist-close ()
10141 "Return non-nil if we're on a line beginning with a close-paren/brace."
10142 (save-match-data
10143 (save-excursion
10144 (goto-char (point-at-bol))
10145 (js2-forward-sws)
10146 (looking-at "[])}]"))))
10147
10148 (defsubst js2-indent-looks-like-label-p ()
10149 (goto-char (point-at-bol))
10150 (js2-forward-sws)
10151 (looking-at (concat js2-mode-identifier-re ":")))
10152
10153 (defun js2-indent-in-objlit-p (parse-status)
10154 "Return non-nil if this looks like an object-literal entry."
10155 (let ((start (nth 1 parse-status)))
10156 (and
10157 start
10158 (save-excursion
10159 (and (zerop (forward-line -1))
10160 (not (< (point) start)) ; crossed a {} boundary
10161 (js2-indent-looks-like-label-p)))
10162 (save-excursion
10163 (js2-indent-looks-like-label-p)))))
10164
10165 ;; if prev line looks like foobar({ then we're passing an object
10166 ;; literal to a function call, and people pretty much always want to
10167 ;; de-dent back to the previous line, so move the 'basic-offset'
10168 ;; position to the front.
10169 (defsubst js2-indent-objlit-arg-p (parse-status)
10170 (save-excursion
10171 (back-to-indentation)
10172 (js2-backward-sws)
10173 (and (eq (1- (point)) (nth 1 parse-status))
10174 (eq (char-before) ?{)
10175 (progn
10176 (forward-char -1)
10177 (skip-chars-backward " \t")
10178 (eq (char-before) ?\()))))
10179
10180 (defsubst js2-indent-case-block-p ()
10181 (save-excursion
10182 (back-to-indentation)
10183 (js2-backward-sws)
10184 (goto-char (point-at-bol))
10185 (skip-chars-forward " \t")
10186 (save-match-data
10187 (looking-at "case\\s-.+:"))))
10188
10189 (defsubst js2-syntax-bol ()
10190 "Return the point at the first non-whitespace char on the line.
10191 Returns `point-at-bol' if the line is empty."
10192 (save-excursion
10193 (beginning-of-line)
10194 (skip-chars-forward " \t")
10195 (point)))
10196
10197 (defun js2-bounce-indent (normal-col parse-status backwards)
10198 "Cycle among alternate computed indentation positions.
10199 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10200 of the buffer to the current point. NORMAL-COL is the indentation
10201 column computed by the heuristic guesser based on current paren,
10202 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10203 in reverse."
10204 (let ((cur-indent (js2-current-indent))
10205 (old-buffer-undo-list buffer-undo-list)
10206 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10207 (current-line (save-excursion
10208 (forward-line 0) ; move to bol
10209 (1+ (count-lines (point-min) (point)))))
10210 positions
10211 pos
10212 main-pos
10213 anchor
10214 arglist-cont
10215 same-indent
10216 prev-line-col
10217 basic-offset
10218 computed-pos)
10219 ;; temporarily don't record undo info, if user requested this
10220 (if js2-mode-indent-inhibit-undo
10221 (setq buffer-undo-list t))
10222 (unwind-protect
10223 (progn
10224 ;; first likely point: indent from beginning of previous code line
10225 (push (setq basic-offset
10226 (+ (save-excursion
10227 (back-to-indentation)
10228 (js2-backward-sws)
10229 (back-to-indentation)
10230 (setq prev-line-col (current-column)))
10231 js2-basic-offset))
10232 positions)
10233
10234 ;; (first + epsilon) likely point: indent 2x from beginning of
10235 ;; previous code line. Some companies like this approach. Ahem.
10236 ;; Seriously, though -- 4-space indent for expression continuation
10237 ;; lines isn't a bad idea. We should eventually implement it
10238 ;; that way.
10239 (push (setq basic-offset
10240 (+ (save-excursion
10241 (back-to-indentation)
10242 (js2-backward-sws)
10243 (back-to-indentation)
10244 (setq prev-line-col (current-column)))
10245 (* 2 js2-basic-offset)))
10246 positions)
10247
10248 ;; second likely point: indent from assign-expr RHS. This
10249 ;; is just a crude guess based on finding " = " on the previous
10250 ;; line containing actual code.
10251 (setq pos (save-excursion
10252 (save-match-data
10253 (forward-line -1)
10254 (goto-char (point-at-bol))
10255 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10256 (point-at-eol) t)
10257 (goto-char (match-end 1))
10258 (skip-chars-forward " \t\r\n")
10259 (current-column)))))
10260 (when pos
10261 (incf pos js2-basic-offset)
10262 (push pos positions))
10263
10264 ;; third likely point: same indent as previous line of code.
10265 ;; Make it the first likely point if we're not on an
10266 ;; arglist-close line and previous line ends in a comma, or
10267 ;; both this line and prev line look like object-literal
10268 ;; elements.
10269 (setq pos (save-excursion
10270 (goto-char (point-at-bol))
10271 (js2-backward-sws)
10272 (back-to-indentation)
10273 (prog1
10274 (current-column)
10275 ;; while we're here, look for trailing comma
10276 (if (save-excursion
10277 (goto-char (point-at-eol))
10278 (js2-backward-sws)
10279 (eq (char-before) ?,))
10280 (setq arglist-cont (1- (point)))))))
10281 (when pos
10282 (if (and (or arglist-cont
10283 (js2-indent-in-objlit-p parse-status))
10284 (not (js2-arglist-close)))
10285 (setq same-indent pos))
10286 (push pos positions))
10287
10288 ;; fourth likely point: first preceding code with less indentation
10289 ;; than the immediately preceding code line.
10290 (setq pos (save-excursion
10291 (back-to-indentation)
10292 (js2-backward-sws)
10293 (back-to-indentation)
10294 (setq anchor (current-column))
10295 (while (and (zerop (forward-line -1))
10296 (>= (progn
10297 (back-to-indentation)
10298 (current-column))
10299 anchor)))
10300 (setq pos (current-column))))
10301 (push pos positions)
10302
10303 ;; nesting-heuristic position, main by default
10304 (push (setq main-pos normal-col) positions)
10305
10306 ;; delete duplicates and sort positions list
10307 (setq positions (sort (delete-dups positions) '<))
10308
10309 ;; comma-list continuation lines: prev line indent takes precedence
10310 (if same-indent
10311 (setq main-pos same-indent))
10312
10313 ;; common special cases where we want to indent in from previous line
10314 (if (or (js2-indent-case-block-p)
10315 (js2-indent-objlit-arg-p parse-status))
10316 (setq main-pos basic-offset))
10317
10318 ;; if bouncing backwards, reverse positions list
10319 (if backwards
10320 (setq positions (reverse positions)))
10321
10322 ;; record whether we're already sitting on one of the alternatives
10323 (setq pos (member cur-indent positions))
10324
10325 (cond
10326 ;; case 0: we're one one of the alternatives and this is the
10327 ;; first time they've pressed TAB on this line (best-guess).
10328 ((and js2-mode-indent-ignore-first-tab
10329 pos
10330 ;; first time pressing TAB on this line?
10331 (not (eq js2-mode-last-indented-line current-line)))
10332 ;; do nothing
10333 (setq computed-pos nil))
10334 ;; case 1: only one computed position => use it
10335 ((null (cdr positions))
10336 (setq computed-pos 0))
10337 ;; case 2: not on any of the computed spots => use main spot
10338 ((not pos)
10339 (setq computed-pos (js2-position main-pos positions)))
10340 ;; case 3: on last position: cycle to first position
10341 ((null (cdr pos))
10342 (setq computed-pos 0))
10343 ;; case 4: on intermediate position: cycle to next position
10344 (t
10345 (setq computed-pos (js2-position (second pos) positions))))
10346
10347 ;; see if any hooks want to indent; otherwise we do it
10348 (loop with result = nil
10349 for hook in js2-indent-hook
10350 while (null result)
10351 do
10352 (setq result (funcall hook positions computed-pos))
10353 finally do
10354 (unless (or result (null computed-pos))
10355 (indent-line-to (nth computed-pos positions)))))
10356
10357 ;; finally
10358 (if js2-mode-indent-inhibit-undo
10359 (setq buffer-undo-list old-buffer-undo-list))
10360 ;; see commentary for `js2-mode-last-indented-line'
10361 (setq js2-mode-last-indented-line current-line))))
10362
10363 (defun js2-indent-bounce-backwards ()
10364 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10365 cycles between the computed indentation positions in reverse order."
10366 (interactive)
10367 (js2-indent-line t))
10368
10369 (defsubst js2-1-line-comment-continuation-p ()
10370 "Return t if we're in a 1-line comment continuation.
10371 If so, we don't ever want to use bounce-indent."
10372 (save-excursion
10373 (save-match-data
10374 (and (progn
10375 (forward-line 0)
10376 (looking-at "\\s-*//"))
10377 (progn
10378 (forward-line -1)
10379 (forward-line 0)
10380 (when (looking-at "\\s-*$")
10381 (js2-backward-sws)
10382 (forward-line 0))
10383 (looking-at "\\s-*//"))))))
10384
10385 (defun js2-indent-line (&optional bounce-backwards)
10386 "Indent the current line as JavaScript source text."
10387 (interactive)
10388 (let (parse-status
10389 offset
10390 indent-col
10391 moved
10392 ;; don't whine about errors/warnings when we're indenting.
10393 ;; This has to be set before calling parse-partial-sexp below.
10394 (inhibit-point-motion-hooks t))
10395 (setq parse-status (save-excursion
10396 (syntax-ppss (point-at-bol)))
10397 offset (- (point) (save-excursion
10398 (back-to-indentation)
10399 (point))))
10400 (js2-with-underscore-as-word-syntax
10401 (if (nth 4 parse-status)
10402 (js2-lineup-comment parse-status)
10403 (setq indent-col (js-proper-indentation parse-status))
10404 ;; see comments below about js2-mode-last-indented-line
10405 (cond
10406 ;; bounce-indenting is disabled during electric-key indent.
10407 ;; It doesn't work well on first line of buffer.
10408 ((and js2-bounce-indent-p
10409 (not (js2-same-line (point-min)))
10410 (not (js2-1-line-comment-continuation-p)))
10411 (js2-bounce-indent indent-col parse-status bounce-backwards))
10412 ;; just indent to the guesser's likely spot
10413 (t (indent-line-to indent-col)))
10414 (when (plusp offset)
10415 (forward-char offset))))))
10416
10417 (defun js2-indent-region (start end)
10418 "Indent the region, but don't use bounce indenting."
10419 (let ((js2-bounce-indent-p nil)
10420 (indent-region-function nil)
10421 (after-change-functions (remq 'js2-mode-edit
10422 after-change-functions)))
10423 (indent-region start end nil) ; nil for byte-compiler
10424 (js2-mode-edit start end (- end start))))
10425
10426 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10427
10428 ;;;###autoload
10429 (defun js2-mode ()
10430 "Major mode for editing JavaScript code."
10431 (interactive)
10432 (kill-all-local-variables)
10433 (set-syntax-table js2-mode-syntax-table)
10434 (use-local-map js2-mode-map)
10435 (make-local-variable 'comment-start)
10436 (make-local-variable 'comment-end)
10437 (make-local-variable 'comment-start-skip)
10438 (setq major-mode 'js2-mode
10439 mode-name "JavaScript-IDE"
10440 comment-start "//" ; used by comment-region; don't change it
10441 comment-end "")
10442 (setq local-abbrev-table js2-mode-abbrev-table)
10443 (set (make-local-variable 'max-lisp-eval-depth)
10444 (max max-lisp-eval-depth 3000))
10445 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10446 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10447
10448 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10449 ;; on most platforms other than the one I originally wrote it on.
10450 ;; So it's back to `c-fill-paragraph'.
10451 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10452
10453 (add-hook 'before-save-hook #'js2-before-save nil t)
10454 (set (make-local-variable 'next-error-function) #'js2-next-error)
10455 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10456 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10457 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10458 ;; for characters inside regexp literals.
10459 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10460 ;; this is necessary to make `show-paren-function' work properly
10461 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10462 ;; needed for M-x rgrep, among other things
10463 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10464
10465 ;; some variables needed by cc-engine for paragraph-fill, etc.
10466 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10467 c-comment-start-regexp "/[*/]\\|\\s|"
10468 c-line-comment-starter "//"
10469 c-paragraph-start js2-paragraph-start
10470 c-paragraph-separate "$"
10471 comment-start-skip js2-comment-start-skip
10472 c-syntactic-ws-start js2-syntactic-ws-start
10473 c-syntactic-ws-end js2-syntactic-ws-end
10474 c-syntactic-eol js2-syntactic-eol)
10475
10476 (let ((c-buffer-is-cc-mode t))
10477 ;; Copied from `js-mode'. Also see Bug#6071.
10478 (make-local-variable 'paragraph-start)
10479 (make-local-variable 'paragraph-separate)
10480 (make-local-variable 'paragraph-ignore-fill-prefix)
10481 (make-local-variable 'adaptive-fill-mode)
10482 (make-local-variable 'adaptive-fill-regexp)
10483 (c-setup-paragraph-variables))
10484
10485 (setq js2-default-externs
10486 (append js2-ecma-262-externs
10487 (if js2-include-browser-externs
10488 js2-browser-externs)
10489 (if js2-include-gears-externs
10490 js2-gears-externs)
10491 (if js2-include-rhino-externs
10492 js2-rhino-externs)))
10493
10494 ;; We do our own syntax highlighting based on the parse tree.
10495 ;; However, we want minor modes that add keywords to highlight properly
10496 ;; (examples: doxymacs, column-marker).
10497 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10498 (setq font-lock-defaults '(nil t))
10499
10500 ;; Experiment: make reparse-delay longer for longer files.
10501 (if (plusp js2-dynamic-idle-timer-adjust)
10502 (setq js2-idle-timer-delay
10503 (* js2-idle-timer-delay
10504 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10505
10506 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10507 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10508 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10509 (imenu-add-to-menubar (concat "IM-" mode-name))
10510 (when js2-mirror-mode
10511 (js2-enter-mirror-mode))
10512 (add-to-invisibility-spec '(js2-outline . t))
10513 (set (make-local-variable 'line-move-ignore-invisible) t)
10514 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10515
10516 (if (fboundp 'run-mode-hooks)
10517 (run-mode-hooks 'js2-mode-hook)
10518 (run-hooks 'js2-mode-hook))
10519
10520 (setq js2-mode-functions-hidden nil
10521 js2-mode-comments-hidden nil
10522 js2-mode-buffer-dirty-p t
10523 js2-mode-parsing nil)
10524 (js2-reparse))
10525
10526 (defun js2-mode-exit ()
10527 "Exit `js2-mode' and clean up."
10528 (interactive)
10529 (when js2-mode-node-overlay
10530 (delete-overlay js2-mode-node-overlay)
10531 (setq js2-mode-node-overlay nil))
10532 (js2-remove-overlays)
10533 (setq js2-mode-ast nil)
10534 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10535 (remove-from-invisibility-spec '(js2-outline . t))
10536 (js2-mode-show-all)
10537 (js2-with-unmodifying-text-property-changes
10538 (js2-clear-face (point-min) (point-max))))
10539
10540 (defun js2-before-save ()
10541 "Clean up whitespace before saving file.
10542 You can disable this by customizing `js2-cleanup-whitespace'."
10543 (when js2-cleanup-whitespace
10544 (let ((col (current-column)))
10545 (delete-trailing-whitespace)
10546 ;; don't change trailing whitespace on current line
10547 (unless (eq (current-column) col)
10548 (indent-to col)))))
10549
10550 (defsubst js2-mode-reset-timer ()
10551 "Cancel any existing parse timer and schedule a new one."
10552 (if js2-mode-parse-timer
10553 (cancel-timer js2-mode-parse-timer))
10554 (setq js2-mode-parsing nil)
10555 (setq js2-mode-parse-timer
10556 (run-with-idle-timer js2-idle-timer-delay nil
10557 #'js2-mode-idle-reparse (current-buffer))))
10558
10559 (defun js2-mode-idle-reparse (buffer)
10560 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10561 it to be reparsed when the buffer is selected."
10562 (if (eq buffer (current-buffer))
10563 (js2-reparse)
10564 ;; reparse when the buffer is selected again
10565 (with-current-buffer buffer
10566 (add-hook 'window-configuration-change-hook
10567 #'js2-mode-idle-reparse-inner
10568 nil t))))
10569
10570 (defun js2-mode-idle-reparse-inner ()
10571 (remove-hook 'window-configuration-change-hook
10572 #'js2-mode-idle-reparse-inner
10573 t)
10574 (js2-reparse))
10575
10576 (defun js2-mode-edit (beg end len)
10577 "Schedule a new parse after buffer is edited.
10578 Buffer edit spans from BEG to END and is of length LEN.
10579 Also clears the `js2-magic' bit on autoinserted parens/brackets
10580 if the edit occurred on a line different from the magic paren."
10581 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10582 (line (if magic-pos (line-number-at-pos magic-pos))))
10583 (and line
10584 (or (/= (line-number-at-pos beg) line)
10585 (and (> 0 len)
10586 (/= (line-number-at-pos end) line)))
10587 (js2-mode-mundanify-parens)))
10588 (setq js2-mode-buffer-dirty-p t)
10589 (js2-mode-hide-overlay)
10590 (js2-mode-reset-timer))
10591
10592 (defun js2-reparse (&optional force)
10593 "Re-parse current buffer after user finishes some data entry.
10594 If we get any user input while parsing, including cursor motion,
10595 we discard the parse and reschedule it. If FORCE is nil, then the
10596 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10597 (let (time
10598 interrupted-p
10599 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10600 (unless js2-mode-parsing
10601 (setq js2-mode-parsing t)
10602 (unwind-protect
10603 (when (or js2-mode-buffer-dirty-p force)
10604 (js2-remove-overlays)
10605 (js2-with-unmodifying-text-property-changes
10606 (setq js2-mode-buffer-dirty-p nil
10607 js2-mode-fontifications nil
10608 js2-mode-deferred-properties nil)
10609 (if js2-mode-verbose-parse-p
10610 (message "parsing..."))
10611 (setq time
10612 (js2-time
10613 (setq interrupted-p
10614 (catch 'interrupted
10615 (setq js2-mode-ast (js2-parse))
10616 ;; if parsing is interrupted, comments and regex
10617 ;; literals stay ignored by `parse-partial-sexp'
10618 (remove-text-properties (point-min) (point-max)
10619 '(syntax-table))
10620 (js2-mode-apply-deferred-properties)
10621 (js2-mode-remove-suppressed-warnings)
10622 (js2-mode-show-warnings)
10623 (js2-mode-show-errors)
10624 (js2-mode-highlight-magic-parens)
10625 (if (>= js2-highlight-level 1)
10626 (js2-highlight-jsdoc js2-mode-ast))
10627 nil))))
10628 (if interrupted-p
10629 (progn
10630 ;; unfinished parse => try again
10631 (setq js2-mode-buffer-dirty-p t)
10632 (js2-mode-reset-timer))
10633 (if js2-mode-verbose-parse-p
10634 (message "Parse time: %s" time)))))
10635 (setq js2-mode-parsing nil)
10636 (unless interrupted-p
10637 (setq js2-mode-parse-timer nil))))))
10638
10639 (defun js2-mode-show-node ()
10640 "Debugging aid: highlight selected AST node on mouse click."
10641 (interactive)
10642 (let ((node (js2-node-at-point))
10643 beg
10644 end)
10645 (when js2-mode-show-overlay
10646 (if (null node)
10647 (message "No node found at location %s" (point))
10648 (setq beg (js2-node-abs-pos node)
10649 end (+ beg (js2-node-len node)))
10650 (if js2-mode-node-overlay
10651 (move-overlay js2-mode-node-overlay beg end)
10652 (setq js2-mode-node-overlay (make-overlay beg end))
10653 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10654 (js2-with-unmodifying-text-property-changes
10655 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10656 (message "%s, parent: %s"
10657 (js2-node-short-name node)
10658 (if (js2-node-parent node)
10659 (js2-node-short-name (js2-node-parent node))
10660 "nil"))))))
10661
10662 (defun js2-mode-hide-overlay (&optional p1 p2)
10663 "Remove the debugging overlay when the point moves.
10664 P1 and P2 are the old and new values of point, respectively."
10665 (when js2-mode-node-overlay
10666 (let ((beg (overlay-start js2-mode-node-overlay))
10667 (end (overlay-end js2-mode-node-overlay)))
10668 ;; Sometimes we're called spuriously.
10669 (unless (and p2
10670 (>= p2 beg)
10671 (<= p2 end))
10672 (js2-with-unmodifying-text-property-changes
10673 (remove-text-properties beg end '(point-left nil)))
10674 (delete-overlay js2-mode-node-overlay)
10675 (setq js2-mode-node-overlay nil)))))
10676
10677 (defun js2-mode-reset ()
10678 "Debugging helper: reset everything."
10679 (interactive)
10680 (js2-mode-exit)
10681 (js2-mode))
10682
10683 (defsubst js2-mode-show-warn-or-err (e face)
10684 "Highlight a warning or error E with FACE.
10685 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10686 (let* ((key (first e))
10687 (beg (second e))
10688 (end (+ beg (third e)))
10689 ;; Don't inadvertently go out of bounds.
10690 (beg (max (point-min) (min beg (point-max))))
10691 (end (max (point-min) (min end (point-max))))
10692 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10693 (ovl (make-overlay beg end)))
10694 (overlay-put ovl 'font-lock-face face)
10695 (overlay-put ovl 'js2-error t)
10696 (put-text-property beg end 'help-echo (js2-get-msg key))
10697 (put-text-property beg end 'point-entered #'js2-echo-error)))
10698
10699 (defun js2-remove-overlays ()
10700 "Remove overlays from buffer that have a `js2-error' property."
10701 (let ((beg (point-min))
10702 (end (point-max)))
10703 (save-excursion
10704 (dolist (o (overlays-in beg end))
10705 (when (overlay-get o 'js2-error)
10706 (delete-overlay o))))))
10707
10708 (defun js2-error-at-point (&optional pos)
10709 "Return non-nil if there's an error overlay at POS.
10710 Defaults to point."
10711 (loop with pos = (or pos (point))
10712 for o in (overlays-at pos)
10713 thereis (overlay-get o 'js2-error)))
10714
10715 (defun js2-mode-apply-deferred-properties ()
10716 "Apply fontifications and other text properties recorded during parsing."
10717 (when (plusp js2-highlight-level)
10718 ;; We defer clearing faces as long as possible to eliminate flashing.
10719 (js2-clear-face (point-min) (point-max))
10720 ;; Have to reverse the recorded fontifications list so that errors
10721 ;; and warnings overwrite the normal fontifications.
10722 (dolist (f (nreverse js2-mode-fontifications))
10723 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10724 (setq js2-mode-fontifications nil))
10725 (dolist (p js2-mode-deferred-properties)
10726 (apply #'put-text-property p))
10727 (setq js2-mode-deferred-properties nil))
10728
10729 (defun js2-mode-show-errors ()
10730 "Highlight syntax errors."
10731 (when js2-mode-show-parse-errors
10732 (dolist (e (js2-ast-root-errors js2-mode-ast))
10733 (js2-mode-show-warn-or-err e 'js2-error-face))))
10734
10735 (defun js2-mode-remove-suppressed-warnings ()
10736 "Take suppressed warnings out of the AST warnings list.
10737 This ensures that the counts and `next-error' are correct."
10738 (setf (js2-ast-root-warnings js2-mode-ast)
10739 (js2-delete-if
10740 (lambda (e)
10741 (let ((key (caar e)))
10742 (or
10743 (and (not js2-strict-trailing-comma-warning)
10744 (string-match "trailing\\.comma" key))
10745 (and (not js2-strict-cond-assign-warning)
10746 (string= key "msg.equal.as.assign"))
10747 (and js2-missing-semi-one-line-override
10748 (string= key "msg.missing.semi")
10749 (let* ((beg (second e))
10750 (node (js2-node-at-point beg))
10751 (fn (js2-mode-find-parent-fn node))
10752 (body (and fn (js2-function-node-body fn)))
10753 (lc (and body (js2-node-abs-pos body)))
10754 (rc (and lc (+ lc (js2-node-len body)))))
10755 (and fn
10756 (or (null body)
10757 (save-excursion
10758 (goto-char beg)
10759 (and (js2-same-line lc)
10760 (js2-same-line rc))))))))))
10761 (js2-ast-root-warnings js2-mode-ast))))
10762
10763 (defun js2-mode-show-warnings ()
10764 "Highlight strict-mode warnings."
10765 (when js2-mode-show-strict-warnings
10766 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10767 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10768
10769 (defun js2-echo-error (old-point new-point)
10770 "Called by point-motion hooks."
10771 (let ((msg (get-text-property new-point 'help-echo)))
10772 (if (and msg (or (not (current-message))
10773 (string= (current-message) "Quit")))
10774 (message msg))))
10775
10776 (defalias #'js2-echo-help #'js2-echo-error)
10777
10778 (defun js2-enter-key ()
10779 "Handle user pressing the Enter key."
10780 (interactive)
10781 (let ((parse-status (save-excursion
10782 (syntax-ppss (point))))
10783 (js2-bounce-indent-p nil))
10784 (cond
10785 ;; check if we're inside a string
10786 ((nth 3 parse-status)
10787 (js2-mode-split-string parse-status))
10788 ;; check if inside a block comment
10789 ((nth 4 parse-status)
10790 (js2-mode-extend-comment))
10791 (t
10792 ;; should probably figure out what the mode-map says we should do
10793 (if js2-indent-on-enter-key
10794 (js2-indent-line))
10795 (insert "\n")
10796 (if js2-enter-indents-newline
10797 (js2-indent-line))))))
10798
10799 (defun js2-mode-split-string (parse-status)
10800 "Turn a newline in mid-string into a string concatenation.
10801 PARSE-STATUS is as documented in `parse-partial-sexp'."
10802 (let* ((col (current-column))
10803 (quote-char (nth 3 parse-status))
10804 (quote-string (string quote-char))
10805 (string-beg (nth 8 parse-status))
10806 (indent (save-match-data
10807 (or
10808 (save-excursion
10809 (back-to-indentation)
10810 (if (looking-at "\\+")
10811 (current-column)))
10812 (save-excursion
10813 (goto-char string-beg)
10814 (if (looking-back "\\+\\s-+")
10815 (goto-char (match-beginning 0)))
10816 (current-column))))))
10817 (insert quote-char "\n")
10818 (indent-to indent)
10819 (insert "+ " quote-string)
10820 (when (eolp)
10821 (insert quote-string)
10822 (backward-char 1))))
10823
10824 (defun js2-mode-extend-comment ()
10825 "Indent the line and, when inside a comment block, add comment prefix."
10826 (let (star single col first-line needs-close)
10827 (save-excursion
10828 (back-to-indentation)
10829 (cond
10830 ((looking-at "\\*[^/]")
10831 (setq star t
10832 col (current-column)))
10833 ((looking-at "/\\*")
10834 (setq star t
10835 first-line t
10836 col (1+ (current-column))))
10837 ((looking-at "//")
10838 (setq single t
10839 col (current-column)))))
10840 ;; Heuristic for whether we need to close the comment:
10841 ;; if we've got a parse error here, assume it's an unterminated
10842 ;; comment.
10843 (setq needs-close
10844 (or
10845 (eq (get-text-property (1- (point)) 'point-entered)
10846 'js2-echo-error)
10847 ;; The heuristic above doesn't work well when we're
10848 ;; creating a comment and there's another one downstream,
10849 ;; as our parser thinks this one ends at the end of the
10850 ;; next one. (You can have a /* inside a js block comment.)
10851 ;; So just close it if the next non-ws char isn't a *.
10852 (and first-line
10853 (eolp)
10854 (save-excursion
10855 (skip-chars-forward " \t\r\n")
10856 (not (eq (char-after) ?*))))))
10857 (insert "\n")
10858 (cond
10859 (star
10860 (indent-to col)
10861 (insert "* ")
10862 (if (and first-line needs-close)
10863 (save-excursion
10864 (insert "\n")
10865 (indent-to col)
10866 (insert "*/"))))
10867 ((and single
10868 (save-excursion
10869 (and (zerop (forward-line 1))
10870 (looking-at "\\s-*//"))))
10871 (indent-to col)
10872 (insert "// "))
10873 ;; don't need to extend the comment after all
10874 (js2-enter-indents-newline
10875 (js2-indent-line)))))
10876
10877 (defun js2-beginning-of-line ()
10878 "Toggles point between bol and first non-whitespace char in line.
10879 Also moves past comment delimiters when inside comments."
10880 (interactive)
10881 (let (node beg)
10882 (cond
10883 ((bolp)
10884 (back-to-indentation))
10885 ((looking-at "//")
10886 (skip-chars-forward "/ \t"))
10887 ((and (eq (char-after) ?*)
10888 (setq node (js2-comment-at-point))
10889 (memq (js2-comment-node-format node) '(jsdoc block))
10890 (save-excursion
10891 (skip-chars-backward " \t")
10892 (bolp)))
10893 (skip-chars-forward "\* \t"))
10894 (t
10895 (goto-char (point-at-bol))))))
10896
10897 (defun js2-end-of-line ()
10898 "Toggles point between eol and last non-whitespace char in line."
10899 (interactive)
10900 (if (eolp)
10901 (skip-chars-backward " \t")
10902 (goto-char (point-at-eol))))
10903
10904 (defun js2-enter-mirror-mode()
10905 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10906 on insertion."
10907 (interactive)
10908 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10909 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10910 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10911 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10912 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10913 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10914 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10915 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10916
10917 (defun js2-leave-mirror-mode()
10918 "Turns off mirror mode."
10919 (interactive)
10920 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10921 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10922
10923 (defsubst js2-mode-inside-string ()
10924 "Return non-nil if inside a string.
10925 Actually returns the quote character that begins the string."
10926 (let ((parse-state (save-excursion
10927 (syntax-ppss (point)))))
10928 (nth 3 parse-state)))
10929
10930 (defsubst js2-mode-inside-comment-or-string ()
10931 "Return non-nil if inside a comment or string."
10932 (or
10933 (let ((comment-start
10934 (save-excursion
10935 (goto-char (point-at-bol))
10936 (if (re-search-forward "//" (point-at-eol) t)
10937 (match-beginning 0)))))
10938 (and comment-start
10939 (<= comment-start (point))))
10940 (let ((parse-state (save-excursion
10941 (syntax-ppss (point)))))
10942 (or (nth 3 parse-state)
10943 (nth 4 parse-state)))))
10944
10945 (defsubst js2-make-magic-delimiter (delim &optional pos)
10946 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10947 Sets value of `js2-magic' text property to line number at POS."
10948 (propertize delim
10949 'js2-magic (line-number-at-pos pos)
10950 'font-lock-face 'js2-magic-paren-face))
10951
10952 (defun js2-mode-match-delimiter (open close)
10953 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10954 The rule we use, which as far as we can tell is how Eclipse works,
10955 is that we insert the match if we're not in a comment or string,
10956 and the next non-whitespace character is either punctuation or
10957 occurs on another line."
10958 (insert open)
10959 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10960 (not (js2-mode-inside-comment-or-string)))
10961 (save-excursion
10962 (insert (js2-make-magic-delimiter close)))
10963 (when js2-auto-indent-p
10964 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10965 (js2-indent-line)))))
10966
10967 (defun js2-mode-match-bracket ()
10968 "Insert matching bracket."
10969 (interactive)
10970 (js2-mode-match-delimiter "[" "]"))
10971
10972 (defun js2-mode-match-paren ()
10973 "Insert matching paren unless already inserted."
10974 (interactive)
10975 (js2-mode-match-delimiter "(" ")"))
10976
10977 (defun js2-mode-match-curly (arg)
10978 "Insert matching curly-brace.
10979 With prefix arg, no formatting or indentation will occur -- the close-brace
10980 is simply inserted directly at the point."
10981 (interactive "p")
10982 (let (try-pos)
10983 (cond
10984 (current-prefix-arg
10985 (js2-mode-match-delimiter "{" "}"))
10986 ((and js2-auto-insert-catch-block
10987 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10988 (point-at-bol))
10989 (match-beginning 1))))
10990 (js2-insert-catch-skel try-pos))
10991 (t
10992 ;; Otherwise try to do something smarter.
10993 (insert "{")
10994 (unless (or (not (looking-at "\\s-*$"))
10995 (save-excursion
10996 (skip-chars-forward " \t\r\n")
10997 (and (looking-at "}")
10998 (js2-error-at-point)))
10999 (js2-mode-inside-comment-or-string))
11000 (undo-boundary)
11001 ;; absolutely mystifying bug: when inserting the next "\n",
11002 ;; the buffer-undo-list is given two new entries: the inserted range,
11003 ;; and the incorrect position of the point. It's recorded incorrectly
11004 ;; as being before the opening "{", not after it. But it's recorded
11005 ;; as the correct value if you're debugging `js2-mode-match-curly'
11006 ;; in edebug. I have no idea why it's doing this, but incrementing
11007 ;; the inserted position fixes the problem, so that the undo takes us
11008 ;; back to just after the user-inserted "{".
11009 (insert "\n")
11010 (ignore-errors
11011 (incf (cadr buffer-undo-list)))
11012 (js2-indent-line)
11013 (save-excursion
11014 (insert "\n}")
11015 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11016 (js2-indent-line))))))))
11017
11018 (defun js2-insert-catch-skel (try-pos)
11019 "Complete a try/catch block after inserting a { following a try keyword.
11020 Rationale is that a try always needs a catch or a finally, and the catch is
11021 the more likely of the two.
11022
11023 TRY-POS is the buffer position of the try keyword. The open-curly should
11024 already have been inserted."
11025 (insert "{")
11026 (let ((try-col (save-excursion
11027 (goto-char try-pos)
11028 (current-column))))
11029 (insert "\n")
11030 (undo-boundary)
11031 (js2-indent-line) ;; indent the blank line where cursor will end up
11032 (save-excursion
11033 (insert "\n")
11034 (indent-to try-col)
11035 (insert "} catch (x) {\n\n")
11036 (indent-to try-col)
11037 (insert "}"))))
11038
11039 (defun js2-mode-highlight-magic-parens ()
11040 "Re-highlight magic parens after parsing nukes the 'face prop."
11041 (let ((beg (point-min))
11042 end)
11043 (while (setq beg (next-single-property-change beg 'js2-magic))
11044 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11045 (if (get-text-property beg 'js2-magic)
11046 (js2-with-unmodifying-text-property-changes
11047 (put-text-property beg (or end (1+ beg))
11048 'font-lock-face 'js2-magic-paren-face))))))
11049
11050 (defun js2-mode-mundanify-parens ()
11051 "Clear all magic parens and brackets."
11052 (let ((beg (point-min))
11053 end)
11054 (while (setq beg (next-single-property-change beg 'js2-magic))
11055 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11056 (remove-text-properties beg (or end (1+ beg))
11057 '(js2-magic face)))))
11058
11059 (defsubst js2-match-quote (quote-string)
11060 (let ((start-quote (js2-mode-inside-string)))
11061 (cond
11062 ;; inside a comment - don't do quote-matching, since we can't
11063 ;; reliably figure out if we're in a string inside the comment
11064 ((js2-comment-at-point)
11065 (insert quote-string))
11066 ((not start-quote)
11067 ;; not in string => insert matched quotes
11068 (insert quote-string)
11069 ;; exception: if we're just before a word, don't double it.
11070 (unless (looking-at "[^ \t\r\n]")
11071 (save-excursion
11072 (insert quote-string))))
11073 ((looking-at quote-string)
11074 (if (looking-back "[^\\]\\\\")
11075 (insert quote-string)
11076 (forward-char 1)))
11077 ((and js2-mode-escape-quotes
11078 (save-excursion
11079 (save-match-data
11080 (re-search-forward quote-string (point-at-eol) t))))
11081 ;; inside terminated string, escape quote (unless already escaped)
11082 (insert (if (looking-back "[^\\]\\\\")
11083 quote-string
11084 (concat "\\" quote-string))))
11085 (t
11086 (insert quote-string))))) ; else terminate the string
11087
11088 (defun js2-mode-match-single-quote ()
11089 "Insert matching single-quote."
11090 (interactive)
11091 (let ((parse-status (syntax-ppss (point))))
11092 ;; don't match inside comments, since apostrophe is more common
11093 (if (nth 4 parse-status)
11094 (insert "'")
11095 (js2-match-quote "'"))))
11096
11097 (defun js2-mode-match-double-quote ()
11098 "Insert matching double-quote."
11099 (interactive)
11100 (js2-match-quote "\""))
11101
11102 ;; Eclipse works as follows:
11103 ;; * type an open-paren and it auto-inserts close-paren
11104 ;; - auto-inserted paren gets a green bracket
11105 ;; - green bracket means typing close-paren there will skip it
11106 ;; * if you insert any text on a different line, it turns off
11107 (defun js2-mode-magic-close-paren ()
11108 "Skip over close-paren rather than inserting, where appropriate."
11109 (interactive)
11110 (let* ((here (point))
11111 (parse-status (syntax-ppss here))
11112 (open-pos (nth 1 parse-status))
11113 (close last-input-event)
11114 (open (cond
11115 ((eq close ?\))
11116 ?\()
11117 ((eq close ?\])
11118 ?\[)
11119 ((eq close ?})
11120 ?{)
11121 (t nil))))
11122 (if (and (eq (char-after) close)
11123 (eq open (char-after open-pos))
11124 (js2-same-line open-pos)
11125 (get-text-property here 'js2-magic))
11126 (progn
11127 (remove-text-properties here (1+ here) '(js2-magic face))
11128 (forward-char 1))
11129 (insert-char close 1))
11130 (blink-matching-open)))
11131
11132 (defun js2-mode-wait-for-parse (callback)
11133 "Invoke CALLBACK when parsing is finished.
11134 If parsing is already finished, calls CALLBACK immediately."
11135 (if (not js2-mode-buffer-dirty-p)
11136 (funcall callback)
11137 (push callback js2-mode-pending-parse-callbacks)
11138 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11139
11140 (defun js2-mode-parse-finished ()
11141 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11142 ;; We can't let errors propagate up, since it prevents the
11143 ;; `js2-parse' method from completing normally and returning
11144 ;; the ast, which makes things mysteriously not work right.
11145 (unwind-protect
11146 (dolist (cb js2-mode-pending-parse-callbacks)
11147 (condition-case err
11148 (funcall cb)
11149 (error (message "%s" err))))
11150 (setq js2-mode-pending-parse-callbacks nil)))
11151
11152 (defun js2-mode-flag-region (from to flag)
11153 "Hide or show text from FROM to TO, according to FLAG.
11154 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11155 Returns the created overlay if FLAG is non-nil."
11156 (remove-overlays from to 'invisible 'js2-outline)
11157 (when flag
11158 (let ((o (make-overlay from to)))
11159 (overlay-put o 'invisible 'js2-outline)
11160 (overlay-put o 'isearch-open-invisible
11161 'js2-isearch-open-invisible)
11162 o)))
11163
11164 ;; Function to be set as an outline-isearch-open-invisible' property
11165 ;; to the overlay that makes the outline invisible (see
11166 ;; `js2-mode-flag-region').
11167 (defun js2-isearch-open-invisible (overlay)
11168 ;; We rely on the fact that isearch places point on the matched text.
11169 (js2-mode-show-element))
11170
11171 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11172 "Return cons cell of bounds of folding overlay at POS.
11173 Returns nil if not found."
11174 (let ((overlays (overlays-at (or pos (point))))
11175 o)
11176 (while (and overlays
11177 (not o))
11178 (if (overlay-get (car overlays) 'invisible)
11179 (setq o (car overlays))
11180 (setq overlays (cdr overlays))))
11181 (if o
11182 (cons (overlay-start o) (overlay-end o)))))
11183
11184 (defun js2-mode-function-at-point (&optional pos)
11185 "Return the innermost function node enclosing current point.
11186 Returns nil if point is not in a function."
11187 (let ((node (js2-node-at-point pos)))
11188 (while (and node (not (js2-function-node-p node)))
11189 (setq node (js2-node-parent node)))
11190 (if (js2-function-node-p node)
11191 node)))
11192
11193 (defun js2-mode-toggle-element ()
11194 "Hide or show the foldable element at the point."
11195 (interactive)
11196 (let (comment fn pos)
11197 (save-excursion
11198 (save-match-data
11199 (cond
11200 ;; /* ... */ comment?
11201 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11202 (if (js2-mode-invisible-overlay-bounds
11203 (setq pos (+ 3 (js2-node-abs-pos comment))))
11204 (progn
11205 (goto-char pos)
11206 (js2-mode-show-element))
11207 (js2-mode-hide-element)))
11208 ;; //-comment?
11209 ((save-excursion
11210 (back-to-indentation)
11211 (looking-at js2-mode-//-comment-re))
11212 (js2-mode-toggle-//-comment))
11213 ;; function?
11214 ((setq fn (js2-mode-function-at-point))
11215 (setq pos (and (js2-function-node-body fn)
11216 (js2-node-abs-pos (js2-function-node-body fn))))
11217 (goto-char (1+ pos))
11218 (if (js2-mode-invisible-overlay-bounds)
11219 (js2-mode-show-element)
11220 (js2-mode-hide-element)))
11221 (t
11222 (message "Nothing at point to hide or show")))))))
11223
11224 (defun js2-mode-hide-element ()
11225 "Fold/hide contents of a block, showing ellipses.
11226 Show the hidden text with \\[js2-mode-show-element]."
11227 (interactive)
11228 (if js2-mode-buffer-dirty-p
11229 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11230 (let (node body beg end)
11231 (cond
11232 ((js2-mode-invisible-overlay-bounds)
11233 (message "already hidden"))
11234 (t
11235 (setq node (js2-node-at-point))
11236 (cond
11237 ((js2-block-comment-p node)
11238 (js2-mode-hide-comment node))
11239 (t
11240 (while (and node (not (js2-function-node-p node)))
11241 (setq node (js2-node-parent node)))
11242 (if (and node
11243 (setq body (js2-function-node-body node)))
11244 (progn
11245 (setq beg (js2-node-abs-pos body)
11246 end (+ beg (js2-node-len body)))
11247 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11248 (message "No collapsable element found at point"))))))))
11249
11250 (defun js2-mode-show-element ()
11251 "Show the hidden element at current point."
11252 (interactive)
11253 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11254 (if bounds
11255 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11256 (message "Nothing to un-hide"))))
11257
11258 (defun js2-mode-show-all ()
11259 "Show all of the text in the buffer."
11260 (interactive)
11261 (js2-mode-flag-region (point-min) (point-max) nil))
11262
11263 (defun js2-mode-toggle-hide-functions ()
11264 (interactive)
11265 (if js2-mode-functions-hidden
11266 (js2-mode-show-functions)
11267 (js2-mode-hide-functions)))
11268
11269 (defun js2-mode-hide-functions ()
11270 "Hides all non-nested function bodies in the buffer.
11271 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11272 to open an individual entry."
11273 (interactive)
11274 (if js2-mode-buffer-dirty-p
11275 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11276 (if (null js2-mode-ast)
11277 (message "Oops - parsing failed")
11278 (setq js2-mode-functions-hidden t)
11279 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11280
11281 (defun js2-mode-function-hider (n endp)
11282 (when (not endp)
11283 (let ((tt (js2-node-type n))
11284 body beg end)
11285 (cond
11286 ((and (= tt js2-FUNCTION)
11287 (setq body (js2-function-node-body n)))
11288 (setq beg (js2-node-abs-pos body)
11289 end (+ beg (js2-node-len body)))
11290 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11291 nil) ; don't process children of function
11292 (t
11293 t))))) ; keep processing other AST nodes
11294
11295 (defun js2-mode-show-functions ()
11296 "Un-hide any folded function bodies in the buffer."
11297 (interactive)
11298 (setq js2-mode-functions-hidden nil)
11299 (save-excursion
11300 (goto-char (point-min))
11301 (while (/= (goto-char (next-overlay-change (point)))
11302 (point-max))
11303 (dolist (o (overlays-at (point)))
11304 (when (and (overlay-get o 'invisible)
11305 (not (overlay-get o 'comment)))
11306 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11307
11308 (defun js2-mode-hide-comment (n)
11309 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11310 3 ; /**
11311 2)) ; /*
11312 (beg (+ (js2-node-abs-pos n) head))
11313 (end (- (+ beg (js2-node-len n)) head 2))
11314 (o (js2-mode-flag-region beg end 'hide)))
11315 (overlay-put o 'comment t)))
11316
11317 (defun js2-mode-toggle-hide-comments ()
11318 "Folds all block comments in the buffer.
11319 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11320 to open an individual entry."
11321 (interactive)
11322 (if js2-mode-comments-hidden
11323 (js2-mode-show-comments)
11324 (js2-mode-hide-comments)))
11325
11326 (defun js2-mode-hide-comments ()
11327 (interactive)
11328 (if js2-mode-buffer-dirty-p
11329 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11330 (if (null js2-mode-ast)
11331 (message "Oops - parsing failed")
11332 (setq js2-mode-comments-hidden t)
11333 (dolist (n (js2-ast-root-comments js2-mode-ast))
11334 (let ((format (js2-comment-node-format n)))
11335 (when (js2-block-comment-p n)
11336 (js2-mode-hide-comment n))))
11337 (js2-mode-hide-//-comments)))
11338
11339 (defsubst js2-mode-extend-//-comment (direction)
11340 "Find start or end of a block of similar //-comment lines.
11341 DIRECTION is -1 to look back, 1 to look forward.
11342 INDENT is the indentation level to match.
11343 Returns the end-of-line position of the furthest adjacent
11344 //-comment line with the same indentation as the current line.
11345 If there is no such matching line, returns current end of line."
11346 (let ((pos (point-at-eol))
11347 (indent (current-indentation)))
11348 (save-excursion
11349 (save-match-data
11350 (while (and (zerop (forward-line direction))
11351 (looking-at js2-mode-//-comment-re)
11352 (eq indent (length (match-string 1))))
11353 (setq pos (point-at-eol)))
11354 pos))))
11355
11356 (defun js2-mode-hide-//-comments ()
11357 "Fold adjacent 1-line comments, showing only snippet of first one."
11358 (let (beg end)
11359 (save-excursion
11360 (save-match-data
11361 (goto-char (point-min))
11362 (while (re-search-forward js2-mode-//-comment-re nil t)
11363 (setq beg (point)
11364 end (js2-mode-extend-//-comment 1))
11365 (unless (eq beg end)
11366 (overlay-put (js2-mode-flag-region beg end 'hide)
11367 'comment t))
11368 (goto-char end)
11369 (forward-char 1))))))
11370
11371 (defun js2-mode-toggle-//-comment ()
11372 "Fold or un-fold any multi-line //-comment at point.
11373 Caller should have determined that this line starts with a //-comment."
11374 (let* ((beg (point-at-eol))
11375 (end beg))
11376 (save-excursion
11377 (goto-char end)
11378 (if (js2-mode-invisible-overlay-bounds)
11379 (js2-mode-show-element)
11380 ;; else hide the comment
11381 (setq beg (js2-mode-extend-//-comment -1)
11382 end (js2-mode-extend-//-comment 1))
11383 (unless (eq beg end)
11384 (overlay-put (js2-mode-flag-region beg end 'hide)
11385 'comment t))))))
11386
11387 (defun js2-mode-show-comments ()
11388 "Un-hide any hidden comments, leaving other hidden elements alone."
11389 (interactive)
11390 (setq js2-mode-comments-hidden nil)
11391 (save-excursion
11392 (goto-char (point-min))
11393 (while (/= (goto-char (next-overlay-change (point)))
11394 (point-max))
11395 (dolist (o (overlays-at (point)))
11396 (when (overlay-get o 'comment)
11397 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11398
11399 (defun js2-mode-display-warnings-and-errors ()
11400 "Turn on display of warnings and errors."
11401 (interactive)
11402 (setq js2-mode-show-parse-errors t
11403 js2-mode-show-strict-warnings t)
11404 (js2-reparse 'force))
11405
11406 (defun js2-mode-hide-warnings-and-errors ()
11407 "Turn off display of warnings and errors."
11408 (interactive)
11409 (setq js2-mode-show-parse-errors nil
11410 js2-mode-show-strict-warnings nil)
11411 (js2-reparse 'force))
11412
11413 (defun js2-mode-toggle-warnings-and-errors ()
11414 "Toggle the display of warnings and errors.
11415 Some users don't like having warnings/errors reported while they type."
11416 (interactive)
11417 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11418 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11419 (if (interactive-p)
11420 (message "warnings and errors %s"
11421 (if js2-mode-show-parse-errors
11422 "enabled"
11423 "disabled")))
11424 (js2-reparse 'force))
11425
11426 (defun js2-mode-customize ()
11427 (interactive)
11428 (customize-group 'js2-mode))
11429
11430 (defun js2-mode-forward-sexp (&optional arg)
11431 "Move forward across one statement or balanced expression.
11432 With ARG, do it that many times. Negative arg -N means
11433 move backward across N balanced expressions."
11434 (interactive "p")
11435 (setq arg (or arg 1))
11436 (if js2-mode-buffer-dirty-p
11437 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11438 (let (node end (start (point)))
11439 (cond
11440 ;; backward-sexp
11441 ;; could probably make this better for some cases:
11442 ;; - if in statement block (e.g. function body), go to parent
11443 ;; - infix exprs like (foo in bar) - maybe go to beginning
11444 ;; of infix expr if in the right-side expression?
11445 ((and arg (minusp arg))
11446 (dotimes (i (- arg))
11447 (js2-backward-sws)
11448 (forward-char -1) ; enter the node we backed up to
11449 (setq node (js2-node-at-point (point) t))
11450 (goto-char (if node
11451 (js2-node-abs-pos node)
11452 (point-min)))))
11453 (t
11454 ;; forward-sexp
11455 (js2-forward-sws)
11456 (dotimes (i arg)
11457 (js2-forward-sws)
11458 (setq node (js2-node-at-point (point) t)
11459 end (if node (+ (js2-node-abs-pos node)
11460 (js2-node-len node))))
11461 (goto-char (or end (point-max))))))))
11462
11463 (defun js2-next-error (&optional arg reset)
11464 "Move to next parse error.
11465 Typically invoked via \\[next-error].
11466 ARG is the number of errors, forward or backward, to move.
11467 RESET means start over from the beginning."
11468 (interactive "p")
11469 (if (or (null js2-mode-ast)
11470 (and (null (js2-ast-root-errors js2-mode-ast))
11471 (null (js2-ast-root-warnings js2-mode-ast))))
11472 (message "No errors")
11473 (when reset
11474 (goto-char (point-min)))
11475 (let* ((errs (copy-sequence
11476 (append (js2-ast-root-errors js2-mode-ast)
11477 (js2-ast-root-warnings js2-mode-ast))))
11478 (continue t)
11479 (start (point))
11480 (count (or arg 1))
11481 (backward (minusp count))
11482 (sorter (if backward '> '<))
11483 (stopper (if backward '< '>))
11484 (count (abs count))
11485 all-errs
11486 err)
11487 ;; sort by start position
11488 (setq errs (sort errs (lambda (e1 e2)
11489 (funcall sorter (second e1) (second e2))))
11490 all-errs errs)
11491 ;; find nth error with pos > start
11492 (while (and errs continue)
11493 (when (funcall stopper (cadar errs) start)
11494 (setq err (car errs))
11495 (if (zerop (decf count))
11496 (setq continue nil)))
11497 (setq errs (cdr errs)))
11498 (if err
11499 (goto-char (second err))
11500 ;; wrap around to first error
11501 (goto-char (second (car all-errs)))
11502 ;; if we were already on it, echo msg again
11503 (if (= (point) start)
11504 (js2-echo-error (point) (point)))))))
11505
11506 (defun js2-down-mouse-3 ()
11507 "Make right-click move the point to the click location.
11508 This makes right-click context menu operations a bit more intuitive.
11509 The point will not move if the region is active, however, to avoid
11510 destroying the region selection."
11511 (interactive)
11512 (when (and js2-move-point-on-right-click
11513 (not mark-active))
11514 (let ((e last-input-event))
11515 (ignore-errors
11516 (goto-char (cadadr e))))))
11517
11518 (defun js2-mode-create-imenu-index ()
11519 "Return an alist for `imenu--index-alist'."
11520 ;; This is built up in `js2-parse-record-imenu' during parsing.
11521 (when js2-mode-ast
11522 ;; if we have an ast but no recorder, they're requesting a rescan
11523 (unless js2-imenu-recorder
11524 (js2-reparse 'force))
11525 (prog1
11526 (js2-build-imenu-index)
11527 (setq js2-imenu-recorder nil
11528 js2-imenu-function-map nil))))
11529
11530 (defun js2-mode-find-tag ()
11531 "Replacement for `find-tag-default'.
11532 `find-tag-default' returns a ridiculous answer inside comments."
11533 (let (beg end)
11534 (js2-with-underscore-as-word-syntax
11535 (save-excursion
11536 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11537 (looking-back "[A-Za-z0-9_$]"))
11538 (setq beg (progn (forward-word -1) (point))
11539 end (progn (forward-word 1) (point)))
11540 (setq beg (progn (forward-word 1) (point))
11541 end (progn (forward-word -1) (point))))
11542 (replace-regexp-in-string
11543 "[\"']" ""
11544 (buffer-substring-no-properties beg end))))))
11545
11546 (defun js2-mode-forward-sibling ()
11547 "Move to the end of the sibling following point in parent.
11548 Returns non-nil if successful, or nil if there was no following sibling."
11549 (let* ((node (js2-node-at-point))
11550 (parent (js2-mode-find-enclosing-fn node))
11551 sib)
11552 (when (setq sib (js2-node-find-child-after (point) parent))
11553 (goto-char (+ (js2-node-abs-pos sib)
11554 (js2-node-len sib))))))
11555
11556 (defun js2-mode-backward-sibling ()
11557 "Move to the beginning of the sibling node preceding point in parent.
11558 Parent is defined as the enclosing script or function."
11559 (let* ((node (js2-node-at-point))
11560 (parent (js2-mode-find-enclosing-fn node))
11561 sib)
11562 (when (setq sib (js2-node-find-child-before (point) parent))
11563 (goto-char (js2-node-abs-pos sib)))))
11564
11565 (defun js2-beginning-of-defun (&optional arg)
11566 "Go to line on which current function starts, and return t on success.
11567 If we're not in a function or already at the beginning of one, go
11568 to beginning of previous script-level element.
11569 With ARG N, do that N times. If N is negative, move forward."
11570 (setq arg (or arg 1))
11571 (if (plusp arg)
11572 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11573 (when (cond
11574 ((js2-function-node-p parent)
11575 (goto-char (js2-node-abs-pos parent)))
11576 (t
11577 (js2-mode-backward-sibling)))
11578 (if (> arg 1)
11579 (js2-beginning-of-defun (1- arg))
11580 t)))
11581 (when (js2-end-of-defun)
11582 (if (>= arg -1)
11583 (js2-beginning-of-defun 1)
11584 (js2-beginning-of-defun (1+ arg))))))
11585
11586 (defun js2-end-of-defun ()
11587 "Go to the char after the last position of the current function
11588 or script-level element."
11589 (let* ((node (js2-node-at-point))
11590 (parent (or (and (js2-function-node-p node) node)
11591 (js2-node-parent-script-or-fn node)))
11592 script)
11593 (unless (js2-function-node-p parent)
11594 ;; use current script-level node, or, if none, the next one
11595 (setq script (or parent node))
11596 (setq parent (js2-node-find-child-before (point) script))
11597 (when (or (null parent)
11598 (>= (point) (+ (js2-node-abs-pos parent)
11599 (js2-node-len parent))))
11600 (setq parent (js2-node-find-child-after (point) script))))
11601 (when parent
11602 (goto-char (+ (js2-node-abs-pos parent)
11603 (js2-node-len parent))))))
11604
11605 (defun js2-mark-defun (&optional allow-extend)
11606 "Put mark at end of this function, point at beginning.
11607 The function marked is the one that contains point.
11608
11609 Interactively, if this command is repeated,
11610 or (in Transient Mark mode) if the mark is active,
11611 it marks the next defun after the ones already marked."
11612 (interactive "p")
11613 (let (extended)
11614 (when (and allow-extend
11615 (or (and (eq last-command this-command) (mark t))
11616 (and transient-mark-mode mark-active)))
11617 (let ((sib (save-excursion
11618 (goto-char (mark))
11619 (if (js2-mode-forward-sibling)
11620 (point))))
11621 node)
11622 (if sib
11623 (progn
11624 (set-mark sib)
11625 (setq extended t))
11626 ;; no more siblings - try extending to enclosing node
11627 (goto-char (mark t)))))
11628 (when (not extended)
11629 (let ((node (js2-node-at-point (point) t)) ; skip comments
11630 ast fn stmt parent beg end)
11631 (when (js2-ast-root-p node)
11632 (setq ast node
11633 node (or (js2-node-find-child-after (point) node)
11634 (js2-node-find-child-before (point) node))))
11635 ;; only mark whole buffer if we can't find any children
11636 (if (null node)
11637 (setq node ast))
11638 (if (js2-function-node-p node)
11639 (setq parent node)
11640 (setq fn (js2-mode-find-enclosing-fn node)
11641 stmt (if (or (null fn)
11642 (js2-ast-root-p fn))
11643 (js2-mode-find-first-stmt node))
11644 parent (or stmt fn)))
11645 (setq beg (js2-node-abs-pos parent)
11646 end (+ beg (js2-node-len parent)))
11647 (push-mark beg)
11648 (goto-char end)
11649 (exchange-point-and-mark)))))
11650
11651 (defun js2-narrow-to-defun ()
11652 "Narrow to the function enclosing point."
11653 (interactive)
11654 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11655 (fn (if (js2-script-node-p node)
11656 node
11657 (js2-mode-find-enclosing-fn node)))
11658 (beg (js2-node-abs-pos fn)))
11659 (unless (js2-ast-root-p fn)
11660 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11661
11662 (provide 'js2-mode)
11663
11664 ;;; js2-mode.el ends here