]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
make multiline string concatenation optional
[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-concat-multiline-strings t
309 "Non-nil to automatically turn a newline in mid-string
310 into a string concatenation."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-squeeze-spaces t
315 "Non-nil to normalize whitespace when filling in comments.
316 Multiple runs of spaces are converted to a single space."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-parse-errors t
321 "True to highlight parse errors."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-mode-show-strict-warnings t
326 "Non-nil to emit Ecma strict-mode warnings.
327 Some of the warnings can be individually disabled by other flags,
328 even if this flag is non-nil."
329 :type 'boolean
330 :group 'js2-mode)
331
332 (defcustom js2-strict-trailing-comma-warning t
333 "Non-nil to warn about trailing commas in array literals.
334 Ecma-262 forbids them, but many browsers permit them. IE is the
335 big exception, and can produce bugs if you have trailing commas."
336 :type 'boolean
337 :group 'js2-mode)
338
339 (defcustom js2-strict-missing-semi-warning t
340 "Non-nil to warn about semicolon auto-insertion after statement.
341 Technically this is legal per Ecma-262, but some style guides disallow
342 depending on it."
343 :type 'boolean
344 :group 'js2-mode)
345
346 (defcustom js2-missing-semi-one-line-override nil
347 "Non-nil to permit missing semicolons in one-line functions.
348 In one-liner functions such as `function identity(x) {return x}'
349 people often omit the semicolon for a cleaner look. If you are
350 such a person, you can suppress the missing-semicolon warning
351 by setting this variable to t."
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-inconsistent-return-warning t
356 "Non-nil to warn about mixing returns with value-returns.
357 It's perfectly legal to have a `return' and a `return foo' in the
358 same function, but it's often an indicator of a bug, and it also
359 interferes with type inference (in systems that support it.)"
360 :type 'boolean
361 :group 'js2-mode)
362
363 (defcustom js2-strict-cond-assign-warning t
364 "Non-nil to warn about expressions like if (a = b).
365 This often should have been '==' instead of '='. If the warning
366 is enabled, you can suppress it on a per-expression basis by
367 parenthesizing the expression, e.g. if ((a = b)) ..."
368 :type 'boolean
369 :group 'js2-mode)
370
371 (defcustom js2-strict-cond-assign-warning t
372 "Non-nil to warn about expressions like if (a = b).
373 This often should have been '==' instead of '='. If the warning
374 is enabled, you can suppress it on a per-expression basis by
375 parenthesizing the expression, e.g. if ((a = b)) ..."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-strict-var-redeclaration-warning t
380 "Non-nil to warn about redeclaring variables in a script or function."
381 :type 'boolean
382 :group 'js2-mode)
383
384 (defcustom js2-strict-var-hides-function-arg-warning t
385 "Non-nil to warn about a var decl hiding a function argument."
386 :type 'boolean
387 :group 'js2-mode)
388
389 (defcustom js2-skip-preprocessor-directives nil
390 "Non-nil to treat lines beginning with # as comments.
391 Useful for viewing Mozilla JavaScript source code."
392 :type 'boolean
393 :group 'js2-mode)
394
395 (defcustom js2-language-version 180
396 "Configures what JavaScript language version to recognize.
397 Currently versions 150, 160, 170 and 180 are supported, corresponding
398 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
399 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
400 and 1.8 adds function closures."
401 :type 'integer
402 :group 'js2-mode)
403
404 (defcustom js2-allow-keywords-as-property-names t
405 "If non-nil, you can use JavaScript keywords as object property names.
406 Examples:
407
408 var foo = {int: 5, while: 6, continue: 7};
409 foo.return = 8;
410
411 Ecma-262 forbids this syntax, but many browsers support it."
412 :type 'boolean
413 :group 'js2-mode)
414
415 (defcustom js2-instanceof-has-side-effects nil
416 "If non-nil, treats the instanceof operator as having side effects.
417 This is useful for xulrunner apps."
418 :type 'boolean
419 :group 'js2-mode)
420
421 (defcustom js2-cleanup-whitespace nil
422 "Non-nil to invoke `delete-trailing-whitespace' before saves."
423 :type 'boolean
424 :group 'js2-mode)
425
426 (defcustom js2-move-point-on-right-click t
427 "Non-nil to move insertion point when you right-click.
428 This makes right-click context menu behavior a bit more intuitive,
429 since menu operations generally apply to the point. The exception
430 is if there is a region selection, in which case the point does -not-
431 move, so cut/copy/paste etc. can work properly.
432
433 Note that IntelliJ moves the point, and Eclipse leaves it alone,
434 so this behavior is customizable."
435 :group 'js2-mode
436 :type 'boolean)
437
438 (defcustom js2-allow-rhino-new-expr-initializer t
439 "Non-nil to support a Rhino's experimental syntactic construct.
440
441 Rhino supports the ability to follow a `new' expression with an object
442 literal, which is used to set additional properties on the new object
443 after calling its constructor. Syntax:
444
445 new <expr> [ ( arglist ) ] [initializer]
446
447 Hence, this expression:
448
449 new Object {a: 1, b: 2}
450
451 results in an Object with properties a=1 and b=2. This syntax is
452 apparently not configurable in Rhino - it's currently always enabled,
453 as of Rhino version 1.7R2."
454 :type 'boolean
455 :group 'js2-mode)
456
457 (defcustom js2-allow-member-expr-as-function-name nil
458 "Non-nil to support experimental Rhino syntax for function names.
459
460 Rhino supports an experimental syntax configured via the Rhino Context
461 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
462
463 function <member-expr> ( [ arg-list ] ) { <body> }
464
465 Where member-expr is a non-parenthesized 'member expression', which
466 is anything at the grammar level of a new-expression or lower, meaning
467 any expression that does not involve infix or unary operators.
468
469 When <member-expr> is not a simple identifier, then it is syntactic
470 sugar for assigning the anonymous function to the <member-expr>. Hence,
471 this code:
472
473 function a.b().c[2] (x, y) { ... }
474
475 is rewritten as:
476
477 a.b().c[2] = function(x, y) {...}
478
479 which doesn't seem particularly useful, but Rhino permits it."
480 :type 'boolean
481 :group 'js2-mode)
482
483 (defvar js2-mode-version 20101228
484 "Release number for `js2-mode'.")
485
486 ;; scanner variables
487
488 (defmacro js2-deflocal (name value &optional comment)
489 "Define a buffer-local variable NAME with VALUE and COMMENT."
490 `(progn
491 (defvar ,name ,value ,comment)
492 (make-variable-buffer-local ',name)))
493
494 ;; We record the start and end position of each token.
495 (js2-deflocal js2-token-beg 1)
496 (js2-deflocal js2-token-end -1)
497
498 (defvar js2-EOF_CHAR -1
499 "Represents end of stream. Distinct from js2-EOF token type.")
500
501 ;; I originally used symbols to represent tokens, but Rhino uses
502 ;; ints and then sets various flag bits in them, so ints it is.
503 ;; The upshot is that we need a `js2-' prefix in front of each name.
504 (defvar js2-ERROR -1)
505 (defvar js2-EOF 0)
506 (defvar js2-EOL 1)
507 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
508 (defvar js2-LEAVEWITH 3)
509 (defvar js2-RETURN 4)
510 (defvar js2-GOTO 5)
511 (defvar js2-IFEQ 6)
512 (defvar js2-IFNE 7)
513 (defvar js2-SETNAME 8)
514 (defvar js2-BITOR 9)
515 (defvar js2-BITXOR 10)
516 (defvar js2-BITAND 11)
517 (defvar js2-EQ 12)
518 (defvar js2-NE 13)
519 (defvar js2-LT 14)
520 (defvar js2-LE 15)
521 (defvar js2-GT 16)
522 (defvar js2-GE 17)
523 (defvar js2-LSH 18)
524 (defvar js2-RSH 19)
525 (defvar js2-URSH 20)
526 (defvar js2-ADD 21) ; infix plus
527 (defvar js2-SUB 22) ; infix minus
528 (defvar js2-MUL 23)
529 (defvar js2-DIV 24)
530 (defvar js2-MOD 25)
531 (defvar js2-NOT 26)
532 (defvar js2-BITNOT 27)
533 (defvar js2-POS 28) ; unary plus
534 (defvar js2-NEG 29) ; unary minus
535 (defvar js2-NEW 30)
536 (defvar js2-DELPROP 31)
537 (defvar js2-TYPEOF 32)
538 (defvar js2-GETPROP 33)
539 (defvar js2-GETPROPNOWARN 34)
540 (defvar js2-SETPROP 35)
541 (defvar js2-GETELEM 36)
542 (defvar js2-SETELEM 37)
543 (defvar js2-CALL 38)
544 (defvar js2-NAME 39) ; an identifier
545 (defvar js2-NUMBER 40)
546 (defvar js2-STRING 41)
547 (defvar js2-NULL 42)
548 (defvar js2-THIS 43)
549 (defvar js2-FALSE 44)
550 (defvar js2-TRUE 45)
551 (defvar js2-SHEQ 46) ; shallow equality (===)
552 (defvar js2-SHNE 47) ; shallow inequality (!==)
553 (defvar js2-REGEXP 48)
554 (defvar js2-BINDNAME 49)
555 (defvar js2-THROW 50)
556 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
557 (defvar js2-IN 52)
558 (defvar js2-INSTANCEOF 53)
559 (defvar js2-LOCAL_LOAD 54)
560 (defvar js2-GETVAR 55)
561 (defvar js2-SETVAR 56)
562 (defvar js2-CATCH_SCOPE 57)
563 (defvar js2-ENUM_INIT_KEYS 58)
564 (defvar js2-ENUM_INIT_VALUES 59)
565 (defvar js2-ENUM_INIT_ARRAY 60)
566 (defvar js2-ENUM_NEXT 61)
567 (defvar js2-ENUM_ID 62)
568 (defvar js2-THISFN 63)
569 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
570 (defvar js2-ARRAYLIT 65) ; array literal
571 (defvar js2-OBJECTLIT 66) ; object literal
572 (defvar js2-GET_REF 67) ; *reference
573 (defvar js2-SET_REF 68) ; *reference = something
574 (defvar js2-DEL_REF 69) ; delete reference
575 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
576 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
577 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
578
579 ;; XML support
580 (defvar js2-DEFAULTNAMESPACE 73)
581 (defvar js2-ESCXMLATTR 74)
582 (defvar js2-ESCXMLTEXT 75)
583 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
584 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
585 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
586 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
587
588 (defvar js2-first-bytecode js2-ENTERWITH)
589 (defvar js2-last-bytecode js2-REF_NS_NAME)
590
591 (defvar js2-TRY 80)
592 (defvar js2-SEMI 81) ; semicolon
593 (defvar js2-LB 82) ; left and right brackets
594 (defvar js2-RB 83)
595 (defvar js2-LC 84) ; left and right curly-braces
596 (defvar js2-RC 85)
597 (defvar js2-LP 86) ; left and right parens
598 (defvar js2-RP 87)
599 (defvar js2-COMMA 88) ; comma operator
600
601 (defvar js2-ASSIGN 89) ; simple assignment (=)
602 (defvar js2-ASSIGN_BITOR 90) ; |=
603 (defvar js2-ASSIGN_BITXOR 91) ; ^=
604 (defvar js2-ASSIGN_BITAND 92) ; &=
605 (defvar js2-ASSIGN_LSH 93) ; <<=
606 (defvar js2-ASSIGN_RSH 94) ; >>=
607 (defvar js2-ASSIGN_URSH 95) ; >>>=
608 (defvar js2-ASSIGN_ADD 96) ; +=
609 (defvar js2-ASSIGN_SUB 97) ; -=
610 (defvar js2-ASSIGN_MUL 98) ; *=
611 (defvar js2-ASSIGN_DIV 99) ; /=
612 (defvar js2-ASSIGN_MOD 100) ; %=
613
614 (defvar js2-first-assign js2-ASSIGN)
615 (defvar js2-last-assign js2-ASSIGN_MOD)
616
617 (defvar js2-HOOK 101) ; conditional (?:)
618 (defvar js2-COLON 102)
619 (defvar js2-OR 103) ; logical or (||)
620 (defvar js2-AND 104) ; logical and (&&)
621 (defvar js2-INC 105) ; increment/decrement (++ --)
622 (defvar js2-DEC 106)
623 (defvar js2-DOT 107) ; member operator (.)
624 (defvar js2-FUNCTION 108) ; function keyword
625 (defvar js2-EXPORT 109) ; export keyword
626 (defvar js2-IMPORT 110) ; import keyword
627 (defvar js2-IF 111) ; if keyword
628 (defvar js2-ELSE 112) ; else keyword
629 (defvar js2-SWITCH 113) ; switch keyword
630 (defvar js2-CASE 114) ; case keyword
631 (defvar js2-DEFAULT 115) ; default keyword
632 (defvar js2-WHILE 116) ; while keyword
633 (defvar js2-DO 117) ; do keyword
634 (defvar js2-FOR 118) ; for keyword
635 (defvar js2-BREAK 119) ; break keyword
636 (defvar js2-CONTINUE 120) ; continue keyword
637 (defvar js2-VAR 121) ; var keyword
638 (defvar js2-WITH 122) ; with keyword
639 (defvar js2-CATCH 123) ; catch keyword
640 (defvar js2-FINALLY 124) ; finally keyword
641 (defvar js2-VOID 125) ; void keyword
642 (defvar js2-RESERVED 126) ; reserved keywords
643
644 (defvar js2-EMPTY 127)
645
646 ;; Types used for the parse tree - never returned by scanner.
647
648 (defvar js2-BLOCK 128) ; statement block
649 (defvar js2-LABEL 129) ; label
650 (defvar js2-TARGET 130)
651 (defvar js2-LOOP 131)
652 (defvar js2-EXPR_VOID 132) ; expression statement in functions
653 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
654 (defvar js2-JSR 134)
655 (defvar js2-SCRIPT 135) ; top-level node for entire script
656 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
657 (defvar js2-USE_STACK 137)
658 (defvar js2-SETPROP_OP 138) ; x.y op= something
659 (defvar js2-SETELEM_OP 139) ; x[y] op= something
660 (defvar js2-LOCAL_BLOCK 140)
661 (defvar js2-SET_REF_OP 141) ; *reference op= something
662
663 ;; For XML support:
664 (defvar js2-DOTDOT 142) ; member operator (..)
665 (defvar js2-COLONCOLON 143) ; namespace::name
666 (defvar js2-XML 144) ; XML type
667 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
668 (defvar js2-XMLATTR 146) ; @
669 (defvar js2-XMLEND 147)
670
671 ;; Optimizer-only tokens
672 (defvar js2-TO_OBJECT 148)
673 (defvar js2-TO_DOUBLE 149)
674
675 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
676 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
677 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
678 (defvar js2-CONST 153)
679 (defvar js2-SETCONST 154)
680 (defvar js2-SETCONSTVAR 155)
681 (defvar js2-ARRAYCOMP 156)
682 (defvar js2-LETEXPR 157)
683 (defvar js2-WITHEXPR 158)
684 (defvar js2-DEBUGGER 159)
685
686 (defvar js2-COMMENT 160)
687 (defvar js2-ENUM 161) ; for "enum" reserved word
688
689 (defconst js2-num-tokens (1+ js2-ENUM))
690
691 (defconst js2-debug-print-trees nil)
692
693 ;; Rhino accepts any string or stream as input. Emacs character
694 ;; processing works best in buffers, so we'll assume the input is a
695 ;; buffer. JavaScript strings can be copied into temp buffers before
696 ;; scanning them.
697
698 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
699 ;; They're the Emacs equivalent of instance variables, more or less.
700
701 (js2-deflocal js2-ts-dirty-line nil
702 "Token stream buffer-local variable.
703 Indicates stuff other than whitespace since start of line.")
704
705 (js2-deflocal js2-ts-regexp-flags nil
706 "Token stream buffer-local variable.")
707
708 (js2-deflocal js2-ts-string ""
709 "Token stream buffer-local variable.
710 Last string scanned.")
711
712 (js2-deflocal js2-ts-number nil
713 "Token stream buffer-local variable.
714 Last literal number scanned.")
715
716 (js2-deflocal js2-ts-hit-eof nil
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-line-start 0
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-lineno 1
723 "Token stream buffer-local variable.")
724
725 (js2-deflocal js2-ts-line-end-char -1
726 "Token stream buffer-local variable.")
727
728 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
729 "Token stream buffer-local variable.
730 Current scan position.")
731
732 (js2-deflocal js2-ts-is-xml-attribute nil
733 "Token stream buffer-local variable.")
734
735 (js2-deflocal js2-ts-xml-is-tag-content nil
736 "Token stream buffer-local variable.")
737
738 (js2-deflocal js2-ts-xml-open-tags-count 0
739 "Token stream buffer-local variable.")
740
741 (js2-deflocal js2-ts-string-buffer nil
742 "Token stream buffer-local variable.
743 List of chars built up while scanning various tokens.")
744
745 (js2-deflocal js2-ts-comment-type nil
746 "Token stream buffer-local variable.")
747
748 ;;; Parser variables
749
750 (js2-deflocal js2-parsed-errors nil
751 "List of errors produced during scanning/parsing.")
752
753 (js2-deflocal js2-parsed-warnings nil
754 "List of warnings produced during scanning/parsing.")
755
756 (js2-deflocal js2-recover-from-parse-errors t
757 "Non-nil to continue parsing after a syntax error.
758
759 In recovery mode, the AST will be built in full, and any error
760 nodes will be flagged with appropriate error information. If
761 this flag is nil, a syntax error will result in an error being
762 signaled.
763
764 The variable is automatically buffer-local, because different
765 modes that use the parser will need different settings.")
766
767 (js2-deflocal js2-parse-hook nil
768 "List of callbacks for receiving parsing progress.")
769
770 (defvar js2-parse-finished-hook nil
771 "List of callbacks to notify when parsing finishes.
772 Not called if parsing was interrupted.")
773
774 (js2-deflocal js2-is-eval-code nil
775 "True if we're evaluating code in a string.
776 If non-nil, the tokenizer will record the token text, and the AST nodes
777 will record their source text. Off by default for IDE modes, since the
778 text is available in the buffer.")
779
780 (defvar js2-parse-ide-mode t
781 "Non-nil if the parser is being used for `js2-mode'.
782 If non-nil, the parser will set text properties for fontification
783 and the syntax table. The value should be nil when using the
784 parser as a frontend to an interpreter or byte compiler.")
785
786 ;;; Parser instance variables (buffer-local vars for js2-parse)
787
788 (defconst js2-clear-ti-mask #xFFFF
789 "Mask to clear token information bits.")
790
791 (defconst js2-ti-after-eol (lsh 1 16)
792 "Flag: first token of the source line.")
793
794 (defconst js2-ti-check-label (lsh 1 17)
795 "Flag: indicates to check for label.")
796
797 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
798
799 (js2-deflocal js2-compiler-generate-debug-info t)
800 (js2-deflocal js2-compiler-use-dynamic-scope nil)
801 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
802 (js2-deflocal js2-compiler-xml-available t)
803 (js2-deflocal js2-compiler-optimization-level 0)
804 (js2-deflocal js2-compiler-generating-source t)
805 (js2-deflocal js2-compiler-strict-mode nil)
806 (js2-deflocal js2-compiler-report-warning-as-error nil)
807 (js2-deflocal js2-compiler-generate-observer-count nil)
808 (js2-deflocal js2-compiler-activation-names nil)
809
810 ;; SKIP: sourceURI
811
812 ;; There's a compileFunction method in Context.java - may need it.
813 (js2-deflocal js2-called-by-compile-function nil
814 "True if `js2-parse' was called by `js2-compile-function'.
815 Will only be used when we finish implementing the interpreter.")
816
817 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
818
819 (js2-deflocal js2-current-flagged-token js2-EOF)
820 (js2-deflocal js2-current-token js2-EOF)
821
822 ;; SKIP: node factory - we're going to just call functions directly,
823 ;; and eventually go to a unified AST format.
824
825 (js2-deflocal js2-nesting-of-function 0)
826
827 (js2-deflocal js2-recorded-identifiers nil
828 "Tracks identifiers found during parsing.")
829
830 (defmacro js2-in-lhs (body)
831 `(let ((js2-is-in-lhs t))
832 ,body))
833
834 (defmacro js2-in-rhs (body)
835 `(let ((js2-is-in-lhs nil))
836 ,body))
837
838 (js2-deflocal js2-is-in-lhs nil
839 "True while parsing lhs statement")
840
841 (defcustom js2-global-externs nil
842 "A list of any extern names you'd like to consider always declared.
843 This list is global and is used by all js2-mode files.
844 You can create buffer-local externs list using `js2-additional-externs'.
845
846 There is also a buffer-local variable `js2-default-externs',
847 which is initialized by default to include the Ecma-262 externs
848 and the standard browser externs. The three lists are all
849 checked during highlighting."
850 :type 'list
851 :group 'js2-mode)
852
853 (js2-deflocal js2-default-externs nil
854 "Default external declarations.
855
856 These are currently only used for highlighting undeclared variables,
857 which only worries about top-level (unqualified) references.
858 As js2-mode's processing improves, we will flesh out this list.
859
860 The initial value is set to `js2-ecma-262-externs', unless you
861 have set `js2-include-browser-externs', in which case the browser
862 externs are also included.
863
864 See `js2-additional-externs' for more information.")
865
866 (defcustom js2-include-browser-externs t
867 "Non-nil to include browser externs in the master externs list.
868 If you work on JavaScript files that are not intended for browsers,
869 such as Mozilla Rhino server-side JavaScript, set this to nil.
870 You can always include them on a per-file basis by calling
871 `js2-add-browser-externs' from a function on `js2-mode-hook'.
872
873 See `js2-additional-externs' for more information about externs."
874 :type 'boolean
875 :group 'js2-mode)
876
877 (defcustom js2-include-rhino-externs t
878 "Non-nil to include Mozilla Rhino 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 (defcustom js2-include-gears-externs t
884 "Non-nil to include Google Gears externs in the master externs list.
885 See `js2-additional-externs' for more information about externs."
886 :type 'boolean
887 :group 'js2-mode)
888
889 (js2-deflocal js2-additional-externs nil
890 "A buffer-local list of additional external declarations.
891 It is used to decide whether variables are considered undeclared
892 for purposes of highlighting.
893
894 Each entry is a lisp string. The string should be the fully qualified
895 name of an external entity. All externs should be added to this list,
896 so that as js2-mode's processing improves it can take advantage of them.
897
898 You may want to declare your externs in three ways.
899 First, you can add externs that are valid for all your JavaScript files.
900 You should probably do this by adding them to `js2-global-externs', which
901 is a global list used for all js2-mode files.
902
903 Next, you can add a function to `js2-mode-hook' that adds additional
904 externs appropriate for the specific file, perhaps based on its path.
905 These should go in `js2-additional-externs', which is buffer-local.
906
907 Finally, you can add a function to `js2-post-parse-callbacks',
908 which is called after parsing completes, and `root' is bound to
909 the root of the parse tree. At this stage you can set up an AST
910 node visitor using `js2-visit-ast' and examine the parse tree
911 for specific import patterns that may imply the existence of
912 other externs, possibly tied to your build system. These should also
913 be added to `js2-additional-externs'.
914
915 Your post-parse callback may of course also use the simpler and
916 faster (but perhaps less robust) approach of simply scanning the
917 buffer text for your imports, using regular expressions.")
918
919 ;; SKIP: decompiler
920 ;; SKIP: encoded-source
921
922 ;;; The following variables are per-function and should be saved/restored
923 ;;; during function parsing...
924
925 (js2-deflocal js2-current-script-or-fn nil)
926 (js2-deflocal js2-current-scope nil)
927 (js2-deflocal js2-nesting-of-with 0)
928 (js2-deflocal js2-label-set nil
929 "An alist mapping label names to nodes.")
930
931 (js2-deflocal js2-loop-set nil)
932 (js2-deflocal js2-loop-and-switch-set nil)
933 (js2-deflocal js2-has-return-value nil)
934 (js2-deflocal js2-end-flags 0)
935
936 ;;; ...end of per function variables
937
938 ;; Without 2-token lookahead, labels are a problem.
939 ;; These vars store the token info of the last matched name,
940 ;; iff it wasn't the last matched token. Only valid in some contexts.
941 (defvar js2-prev-name-token-start nil)
942 (defvar js2-prev-name-token-string nil)
943
944 (defsubst js2-save-name-token-data (pos name)
945 (setq js2-prev-name-token-start pos
946 js2-prev-name-token-string name))
947
948 ;; These flags enumerate the possible ways a statement/function can
949 ;; terminate. These flags are used by endCheck() and by the Parser to
950 ;; detect inconsistent return usage.
951 ;;
952 ;; END_UNREACHED is reserved for code paths that are assumed to always be
953 ;; able to execute (example: throw, continue)
954 ;;
955 ;; END_DROPS_OFF indicates if the statement can transfer control to the
956 ;; next one. Statement such as return dont. A compound statement may have
957 ;; some branch that drops off control to the next statement.
958 ;;
959 ;; END_RETURNS indicates that the statement can return (without arguments)
960 ;; END_RETURNS_VALUE indicates that the statement can return a value.
961 ;;
962 ;; A compound statement such as
963 ;; if (condition) {
964 ;; return value;
965 ;; }
966 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
967
968 (defconst js2-end-unreached #x0)
969 (defconst js2-end-drops-off #x1)
970 (defconst js2-end-returns #x2)
971 (defconst js2-end-returns-value #x4)
972 (defconst js2-end-yields #x8)
973
974 ;; Rhino awkwardly passes a statementLabel parameter to the
975 ;; statementHelper() function, the main statement parser, which
976 ;; is then used by quite a few of the sub-parsers. We just make
977 ;; it a buffer-local variable and make sure it's cleaned up properly.
978 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
979
980 ;; Similarly, Rhino passes an inForInit boolean through about half
981 ;; the expression parsers. We use a dynamically-scoped variable,
982 ;; which makes it easier to funcall the parsers individually without
983 ;; worrying about whether they take the parameter or not.
984 (js2-deflocal js2-in-for-init nil)
985 (js2-deflocal js2-temp-name-counter 0)
986 (js2-deflocal js2-parse-stmt-count 0)
987
988 (defsubst js2-get-next-temp-name ()
989 (format "$%d" (incf js2-temp-name-counter)))
990
991 (defvar js2-parse-interruptable-p t
992 "Set this to nil to force parse to continue until finished.
993 This will mostly be useful for interpreters.")
994
995 (defvar js2-statements-per-pause 50
996 "Pause after this many statements to check for user input.
997 If user input is pending, stop the parse and discard the tree.
998 This makes for a smoother user experience for large files.
999 You may have to wait a second or two before the highlighting
1000 and error-reporting appear, but you can always type ahead if
1001 you wish. This appears to be more or less how Eclipse, IntelliJ
1002 and other editors work.")
1003
1004 (js2-deflocal js2-record-comments t
1005 "Instructs the scanner to record comments in `js2-scanned-comments'.")
1006
1007 (js2-deflocal js2-scanned-comments nil
1008 "List of all comments from the current parse.")
1009
1010 (defcustom js2-mode-indent-inhibit-undo nil
1011 "Non-nil to disable collection of Undo information when indenting lines.
1012 Some users have requested this behavior. It's nil by default because
1013 other Emacs modes don't work this way."
1014 :type 'boolean
1015 :group 'js2-mode)
1016
1017 (defcustom js2-mode-indent-ignore-first-tab nil
1018 "If non-nil, ignore first TAB keypress if we look indented properly.
1019 It's fairly common for users to navigate to an already-indented line
1020 and press TAB for reassurance that it's been indented. For this class
1021 of users, we want the first TAB press on a line to be ignored if the
1022 line is already indented to one of the precomputed alternatives.
1023
1024 This behavior is only partly implemented. If you TAB-indent a line,
1025 navigate to another line, and then navigate back, it fails to clear
1026 the last-indented variable, so it thinks you've already hit TAB once,
1027 and performs the indent. A full solution would involve getting on the
1028 point-motion hooks for the entire buffer. If we come across another
1029 use cases that requires watching point motion, I'll consider doing it.
1030
1031 If you set this variable to nil, then the TAB key will always change
1032 the indentation of the current line, if more than one alternative
1033 indentation spot exists."
1034 :type 'boolean
1035 :group 'js2-mode)
1036
1037 (defvar js2-indent-hook nil
1038 "A hook for user-defined indentation rules.
1039
1040 Functions on this hook should expect two arguments: (LIST INDEX)
1041 The LIST argument is the list of computed indentation points for
1042 the current line. INDEX is the list index of the indentation point
1043 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1044 indent function is not going to change the current line indentation.
1045
1046 If a hook function on this list returns a non-nil value, then
1047 `js2-bounce-indent' assumes the hook function has performed its own
1048 indentation, and will do nothing. If all hook functions on the list
1049 return nil, then `js2-bounce-indent' will use its computed indentation
1050 and reindent the line.
1051
1052 When hook functions on this hook list are called, the variable
1053 `js2-mode-ast' may or may not be set, depending on whether the
1054 parse tree is available. If the variable is nil, you can pass a
1055 callback to `js2-mode-wait-for-parse', and your callback will be
1056 called after the new parse tree is built. This can take some time
1057 in large files.")
1058
1059 (defface js2-warning-face
1060 `((((class color) (background light))
1061 (:underline "orange"))
1062 (((class color) (background dark))
1063 (:underline "orange"))
1064 (t (:underline t)))
1065 "Face for JavaScript warnings."
1066 :group 'js2-mode)
1067
1068 (defface js2-error-face
1069 `((((class color) (background light))
1070 (:foreground "red"))
1071 (((class color) (background dark))
1072 (:foreground "red"))
1073 (t (:foreground "red")))
1074 "Face for JavaScript errors."
1075 :group 'js2-mode)
1076
1077 (defface js2-jsdoc-tag-face
1078 '((t :foreground "SlateGray"))
1079 "Face used to highlight @whatever tags in jsdoc comments."
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-type-face
1083 '((t :foreground "SteelBlue"))
1084 "Face used to highlight {FooBar} types in jsdoc comments."
1085 :group 'js2-mode)
1086
1087 (defface js2-jsdoc-value-face
1088 '((t :foreground "PeachPuff3"))
1089 "Face used to highlight tag values in jsdoc comments."
1090 :group 'js2-mode)
1091
1092 (defface js2-function-param-face
1093 '((t :foreground "SeaGreen"))
1094 "Face used to highlight function parameters in javascript."
1095 :group 'js2-mode)
1096
1097 (defface js2-instance-member-face
1098 '((t :foreground "DarkOrchid"))
1099 "Face used to highlight instance variables in javascript.
1100 Not currently used."
1101 :group 'js2-mode)
1102
1103 (defface js2-private-member-face
1104 '((t :foreground "PeachPuff3"))
1105 "Face used to highlight calls to private methods in javascript.
1106 Not currently used."
1107 :group 'js2-mode)
1108
1109 (defface js2-private-function-call-face
1110 '((t :foreground "goldenrod"))
1111 "Face used to highlight calls to private functions in javascript.
1112 Not currently used."
1113 :group 'js2-mode)
1114
1115 (defface js2-jsdoc-html-tag-name-face
1116 (if js2-emacs22
1117 '((((class color) (min-colors 88) (background light))
1118 (:foreground "rosybrown"))
1119 (((class color) (min-colors 8) (background dark))
1120 (:foreground "yellow"))
1121 (((class color) (min-colors 8) (background light))
1122 (:foreground "magenta")))
1123 '((((type tty pc) (class color) (background light))
1124 (:foreground "magenta"))
1125 (((type tty pc) (class color) (background dark))
1126 (:foreground "yellow"))
1127 (t (:foreground "RosyBrown"))))
1128 "Face used to highlight jsdoc html tag names"
1129 :group 'js2-mode)
1130
1131 (defface js2-jsdoc-html-tag-delimiter-face
1132 (if js2-emacs22
1133 '((((class color) (min-colors 88) (background light))
1134 (:foreground "dark khaki"))
1135 (((class color) (min-colors 8) (background dark))
1136 (:foreground "green"))
1137 (((class color) (min-colors 8) (background light))
1138 (:foreground "green")))
1139 '((((type tty pc) (class color) (background light))
1140 (:foreground "green"))
1141 (((type tty pc) (class color) (background dark))
1142 (:foreground "green"))
1143 (t (:foreground "dark khaki"))))
1144 "Face used to highlight brackets in jsdoc html tags."
1145 :group 'js2-mode)
1146
1147 (defface js2-magic-paren-face
1148 '((t :underline t))
1149 "Face used to color parens that will be auto-overwritten."
1150 :group 'js2-mode)
1151
1152 (defcustom js2-post-parse-callbacks nil
1153 "A list of callback functions invoked after parsing finishes.
1154 Currently, the main use for this function is to add synthetic
1155 declarations to `js2-recorded-identifiers', which see."
1156 :type 'list
1157 :group 'js2-mode)
1158
1159 (defface js2-external-variable-face
1160 '((t :foreground "orange"))
1161 "Face used to highlight undeclared variable identifiers.
1162 An undeclared variable is any variable not declared with var or let
1163 in the current scope or any lexically enclosing scope. If you use
1164 such a variable, then you are either expecting it to originate from
1165 another file, or you've got a potential bug."
1166 :group 'js2-mode)
1167
1168 (defcustom js2-highlight-external-variables t
1169 "Non-nil to highlight undeclared variable identifiers."
1170 :type 'boolean
1171 :group 'js2-mode)
1172
1173 (defcustom js2-auto-insert-catch-block t
1174 "Non-nil to insert matching catch block on open-curly after `try'."
1175 :type 'boolean
1176 :group 'js2-mode)
1177
1178 (defvar js2-mode-map
1179 (let ((map (make-sparse-keymap))
1180 keys)
1181 (define-key map [mouse-1] #'js2-mode-show-node)
1182 (define-key map (kbd "C-m") #'js2-enter-key)
1183 (when js2-rebind-eol-bol-keys
1184 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1185 (define-key map (kbd "C-e") #'js2-end-of-line))
1186 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1187 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1188 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1189 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1190 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1191 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1192 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1193 (define-key map (kbd "C-c C-`") #'js2-next-error)
1194 ;; also define user's preference for next-error, if available
1195 (if (setq keys (where-is-internal #'next-error))
1196 (define-key map (car keys) #'js2-next-error))
1197 (define-key map (or (car (where-is-internal #'mark-defun))
1198 (kbd "M-C-h"))
1199 #'js2-mark-defun)
1200 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1201 (kbd "C-x nd"))
1202 #'js2-narrow-to-defun)
1203 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1204 (when js2-auto-indent-p
1205 (mapc (lambda (key)
1206 (define-key map key #'js2-insert-and-indent))
1207 js2-electric-keys))
1208 (when js2-bounce-indent-p
1209 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1210
1211 (define-key map [menu-bar javascript]
1212 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1213
1214 (define-key map [menu-bar javascript customize-js2-mode]
1215 '(menu-item "Customize js2-mode" js2-mode-customize
1216 :help "Customize the behavior of this mode"))
1217
1218 (define-key map [menu-bar javascript js2-force-refresh]
1219 '(menu-item "Force buffer refresh" js2-mode-reset
1220 :help "Re-parse the buffer from scratch"))
1221
1222 (define-key map [menu-bar javascript separator-2]
1223 '("--"))
1224
1225 (define-key map [menu-bar javascript next-error]
1226 '(menu-item "Next warning or error" js2-next-error
1227 :enabled (and js2-mode-ast
1228 (or (js2-ast-root-errors js2-mode-ast)
1229 (js2-ast-root-warnings js2-mode-ast)))
1230 :help "Move to next warning or error"))
1231
1232 (define-key map [menu-bar javascript display-errors]
1233 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1234 :visible (not js2-mode-show-parse-errors)
1235 :help "Turn on display of warnings and errors"))
1236
1237 (define-key map [menu-bar javascript hide-errors]
1238 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1239 :visible js2-mode-show-parse-errors
1240 :help "Turn off display of warnings and errors"))
1241
1242 (define-key map [menu-bar javascript separator-1]
1243 '("--"))
1244
1245 (define-key map [menu-bar javascript js2-toggle-function]
1246 '(menu-item "Show/collapse element" js2-mode-toggle-element
1247 :help "Hide or show function body or comment"))
1248
1249 (define-key map [menu-bar javascript show-comments]
1250 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1251 :visible js2-mode-comments-hidden
1252 :help "Expand all hidden block comments"))
1253
1254 (define-key map [menu-bar javascript hide-comments]
1255 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1256 :visible (not js2-mode-comments-hidden)
1257 :help "Show block comments as /*...*/"))
1258
1259 (define-key map [menu-bar javascript show-all-functions]
1260 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1261 :visible js2-mode-functions-hidden
1262 :help "Expand all hidden function bodies"))
1263
1264 (define-key map [menu-bar javascript hide-all-functions]
1265 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1266 :visible (not js2-mode-functions-hidden)
1267 :help "Show {...} for all top-level function bodies"))
1268
1269 map)
1270 "Keymap used in `js2-mode' buffers.")
1271
1272 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1273
1274 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1275 "Matches a //-comment line. Must be first non-whitespace on line.
1276 First match-group is the leading whitespace.")
1277
1278 (defvar js2-mode-hook nil)
1279
1280 (js2-deflocal js2-mode-ast nil "Private variable.")
1281 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1282 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1283 (js2-deflocal js2-mode-parsing nil "Private variable.")
1284 (js2-deflocal js2-mode-node-overlay nil)
1285
1286 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1287 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1288
1289 (js2-deflocal js2-mode-fontifications nil "Private variable")
1290 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1291 (js2-deflocal js2-imenu-recorder nil "Private variable")
1292 (js2-deflocal js2-imenu-function-map nil "Private variable")
1293
1294 (defvar js2-paragraph-start
1295 "\\(@[a-zA-Z]+\\>\\|$\\)")
1296
1297 ;; Note that we also set a 'c-in-sws text property in html comments,
1298 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1299 (defvar js2-syntactic-ws-start
1300 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1301
1302 (defvar js2-syntactic-ws-end
1303 "\\s \\|[\n\r/]\\|\\s!")
1304
1305 (defvar js2-syntactic-eol
1306 (concat "\\s *\\(/\\*[^*\n\r]*"
1307 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1308 "\\*+/\\s *\\)*"
1309 "\\(//\\|/\\*[^*\n\r]*"
1310 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1311 "\\|\\\\$\\|$\\)")
1312 "Copied from `java-mode'. Needed for some cc-engine functions.")
1313
1314 (defvar js2-comment-prefix-regexp
1315 "//+\\|\\**")
1316
1317 (defvar js2-comment-start-skip
1318 "\\(//+\\|/\\*+\\)\\s *")
1319
1320 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1321 "Non-nil to emit status messages during parsing.")
1322
1323 (defvar js2-mode-functions-hidden nil "private variable")
1324 (defvar js2-mode-comments-hidden nil "private variable")
1325
1326 (defvar js2-mode-syntax-table
1327 (let ((table (make-syntax-table)))
1328 (c-populate-syntax-table table)
1329 table)
1330 "Syntax table used in js2-mode buffers.")
1331
1332 (defvar js2-mode-abbrev-table nil
1333 "Abbrev table in use in `js2-mode' buffers.")
1334 (define-abbrev-table 'js2-mode-abbrev-table ())
1335
1336 (defvar js2-mode-pending-parse-callbacks nil
1337 "List of functions waiting to be notified that parse is finished.")
1338
1339 (defvar js2-mode-last-indented-line -1)
1340
1341 ;;; Localizable error and warning messages
1342
1343 ;; Messages are copied from Rhino's Messages.properties.
1344 ;; Many of the Java-specific messages have been elided.
1345 ;; Add any js2-specific ones at the end, so we can keep
1346 ;; this file synced with changes to Rhino's.
1347
1348 (defvar js2-message-table
1349 (make-hash-table :test 'equal :size 250)
1350 "Contains localized messages for js2-mode.")
1351
1352 ;; TODO(stevey): construct this table at compile-time.
1353 (defmacro js2-msg (key &rest strings)
1354 `(puthash ,key (funcall #'concat ,@strings)
1355 js2-message-table))
1356
1357 (defun js2-get-msg (msg-key)
1358 "Look up a localized message.
1359 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1360 the correct number of ARGS must be provided."
1361 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1362 (args (if (listp msg-key) (cdr msg-key)))
1363 (msg (gethash key js2-message-table)))
1364 (if msg
1365 (apply #'format msg args)
1366 key))) ; default to showing the key
1367
1368 (js2-msg "msg.dup.parms"
1369 "Duplicate parameter name '%s'.")
1370
1371 (js2-msg "msg.too.big.jump"
1372 "Program too complex: jump offset too big.")
1373
1374 (js2-msg "msg.too.big.index"
1375 "Program too complex: internal index exceeds 64K limit.")
1376
1377 (js2-msg "msg.while.compiling.fn"
1378 "Encountered code generation error while compiling function '%s': %s")
1379
1380 (js2-msg "msg.while.compiling.script"
1381 "Encountered code generation error while compiling script: %s")
1382
1383 ;; Context
1384 (js2-msg "msg.ctor.not.found"
1385 "Constructor for '%s' not found.")
1386
1387 (js2-msg "msg.not.ctor"
1388 "'%s' is not a constructor.")
1389
1390 ;; FunctionObject
1391 (js2-msg "msg.varargs.ctor"
1392 "Method or constructor '%s' must be static "
1393 "with the signature (Context cx, Object[] args, "
1394 "Function ctorObj, boolean inNewExpr) "
1395 "to define a variable arguments constructor.")
1396
1397 (js2-msg "msg.varargs.fun"
1398 "Method '%s' must be static with the signature "
1399 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1400 "to define a variable arguments function.")
1401
1402 (js2-msg "msg.incompat.call"
1403 "Method '%s' called on incompatible object.")
1404
1405 (js2-msg "msg.bad.parms"
1406 "Unsupported parameter type '%s' in method '%s'.")
1407
1408 (js2-msg "msg.bad.method.return"
1409 "Unsupported return type '%s' in method '%s'.")
1410
1411 (js2-msg "msg.bad.ctor.return"
1412 "Construction of objects of type '%s' is not supported.")
1413
1414 (js2-msg "msg.no.overload"
1415 "Method '%s' occurs multiple times in class '%s'.")
1416
1417 (js2-msg "msg.method.not.found"
1418 "Method '%s' not found in '%s'.")
1419
1420 ;; IRFactory
1421
1422 (js2-msg "msg.bad.for.in.lhs"
1423 "Invalid left-hand side of for..in loop.")
1424
1425 (js2-msg "msg.mult.index"
1426 "Only one variable allowed in for..in loop.")
1427
1428 (js2-msg "msg.bad.for.in.destruct"
1429 "Left hand side of for..in loop must be an array of "
1430 "length 2 to accept key/value pair.")
1431
1432 (js2-msg "msg.cant.convert"
1433 "Can't convert to type '%s'.")
1434
1435 (js2-msg "msg.bad.assign.left"
1436 "Invalid assignment left-hand side.")
1437
1438 (js2-msg "msg.bad.decr"
1439 "Invalid decerement operand.")
1440
1441 (js2-msg "msg.bad.incr"
1442 "Invalid increment operand.")
1443
1444 (js2-msg "msg.bad.yield"
1445 "yield must be in a function.")
1446
1447 (js2-msg "msg.yield.parenthesized"
1448 "yield expression must be parenthesized.")
1449
1450 ;; NativeGlobal
1451 (js2-msg "msg.cant.call.indirect"
1452 "Function '%s' must be called directly, and not by way of a "
1453 "function of another name.")
1454
1455 (js2-msg "msg.eval.nonstring"
1456 "Calling eval() with anything other than a primitive "
1457 "string value will simply return the value. "
1458 "Is this what you intended?")
1459
1460 (js2-msg "msg.eval.nonstring.strict"
1461 "Calling eval() with anything other than a primitive "
1462 "string value is not allowed in strict mode.")
1463
1464 (js2-msg "msg.bad.destruct.op"
1465 "Invalid destructuring assignment operator")
1466
1467 ;; NativeCall
1468 (js2-msg "msg.only.from.new"
1469 "'%s' may only be invoked from a `new' expression.")
1470
1471 (js2-msg "msg.deprec.ctor"
1472 "The '%s' constructor is deprecated.")
1473
1474 ;; NativeFunction
1475 (js2-msg "msg.no.function.ref.found"
1476 "no source found to decompile function reference %s")
1477
1478 (js2-msg "msg.arg.isnt.array"
1479 "second argument to Function.prototype.apply must be an array")
1480
1481 ;; NativeGlobal
1482 (js2-msg "msg.bad.esc.mask"
1483 "invalid string escape mask")
1484
1485 ;; NativeRegExp
1486 (js2-msg "msg.bad.quant"
1487 "Invalid quantifier %s")
1488
1489 (js2-msg "msg.overlarge.backref"
1490 "Overly large back reference %s")
1491
1492 (js2-msg "msg.overlarge.min"
1493 "Overly large minimum %s")
1494
1495 (js2-msg "msg.overlarge.max"
1496 "Overly large maximum %s")
1497
1498 (js2-msg "msg.zero.quant"
1499 "Zero quantifier %s")
1500
1501 (js2-msg "msg.max.lt.min"
1502 "Maximum %s less than minimum")
1503
1504 (js2-msg "msg.unterm.quant"
1505 "Unterminated quantifier %s")
1506
1507 (js2-msg "msg.unterm.paren"
1508 "Unterminated parenthetical %s")
1509
1510 (js2-msg "msg.unterm.class"
1511 "Unterminated character class %s")
1512
1513 (js2-msg "msg.bad.range"
1514 "Invalid range in character class.")
1515
1516 (js2-msg "msg.trail.backslash"
1517 "Trailing \\ in regular expression.")
1518
1519 (js2-msg "msg.re.unmatched.right.paren"
1520 "unmatched ) in regular expression.")
1521
1522 (js2-msg "msg.no.regexp"
1523 "Regular expressions are not available.")
1524
1525 (js2-msg "msg.bad.backref"
1526 "back-reference exceeds number of capturing parentheses.")
1527
1528 (js2-msg "msg.bad.regexp.compile"
1529 "Only one argument may be specified if the first "
1530 "argument to RegExp.prototype.compile is a RegExp object.")
1531
1532 ;; Parser
1533 (js2-msg "msg.got.syntax.errors"
1534 "Compilation produced %s syntax errors.")
1535
1536 (js2-msg "msg.var.redecl"
1537 "TypeError: redeclaration of var %s.")
1538
1539 (js2-msg "msg.const.redecl"
1540 "TypeError: redeclaration of const %s.")
1541
1542 (js2-msg "msg.let.redecl"
1543 "TypeError: redeclaration of variable %s.")
1544
1545 (js2-msg "msg.parm.redecl"
1546 "TypeError: redeclaration of formal parameter %s.")
1547
1548 (js2-msg "msg.fn.redecl"
1549 "TypeError: redeclaration of function %s.")
1550
1551 (js2-msg "msg.let.decl.not.in.block"
1552 "SyntaxError: let declaration not directly within block")
1553
1554 ;; NodeTransformer
1555 (js2-msg "msg.dup.label"
1556 "duplicated label")
1557
1558 (js2-msg "msg.undef.label"
1559 "undefined label")
1560
1561 (js2-msg "msg.bad.break"
1562 "unlabelled break must be inside loop or switch")
1563
1564 (js2-msg "msg.continue.outside"
1565 "continue must be inside loop")
1566
1567 (js2-msg "msg.continue.nonloop"
1568 "continue can only use labels of iteration statements")
1569
1570 (js2-msg "msg.bad.throw.eol"
1571 "Line terminator is not allowed between the throw "
1572 "keyword and throw expression.")
1573
1574 (js2-msg "msg.no.paren.parms"
1575 "missing ( before function parameters.")
1576
1577 (js2-msg "msg.no.parm"
1578 "missing formal parameter")
1579
1580 (js2-msg "msg.no.paren.after.parms"
1581 "missing ) after formal parameters")
1582
1583 (js2-msg "msg.no.brace.body"
1584 "missing '{' before function body")
1585
1586 (js2-msg "msg.no.brace.after.body"
1587 "missing } after function body")
1588
1589 (js2-msg "msg.no.paren.cond"
1590 "missing ( before condition")
1591
1592 (js2-msg "msg.no.paren.after.cond"
1593 "missing ) after condition")
1594
1595 (js2-msg "msg.no.semi.stmt"
1596 "missing ; before statement")
1597
1598 (js2-msg "msg.missing.semi"
1599 "missing ; after statement")
1600
1601 (js2-msg "msg.no.name.after.dot"
1602 "missing name after . operator")
1603
1604 (js2-msg "msg.no.name.after.coloncolon"
1605 "missing name after :: operator")
1606
1607 (js2-msg "msg.no.name.after.dotdot"
1608 "missing name after .. operator")
1609
1610 (js2-msg "msg.no.name.after.xmlAttr"
1611 "missing name after .@")
1612
1613 (js2-msg "msg.no.bracket.index"
1614 "missing ] in index expression")
1615
1616 (js2-msg "msg.no.paren.switch"
1617 "missing ( before switch expression")
1618
1619 (js2-msg "msg.no.paren.after.switch"
1620 "missing ) after switch expression")
1621
1622 (js2-msg "msg.no.brace.switch"
1623 "missing '{' before switch body")
1624
1625 (js2-msg "msg.bad.switch"
1626 "invalid switch statement")
1627
1628 (js2-msg "msg.no.colon.case"
1629 "missing : after case expression")
1630
1631 (js2-msg "msg.double.switch.default"
1632 "double default label in the switch statement")
1633
1634 (js2-msg "msg.no.while.do"
1635 "missing while after do-loop body")
1636
1637 (js2-msg "msg.no.paren.for"
1638 "missing ( after for")
1639
1640 (js2-msg "msg.no.semi.for"
1641 "missing ; after for-loop initializer")
1642
1643 (js2-msg "msg.no.semi.for.cond"
1644 "missing ; after for-loop condition")
1645
1646 (js2-msg "msg.in.after.for.name"
1647 "missing in after for")
1648
1649 (js2-msg "msg.no.paren.for.ctrl"
1650 "missing ) after for-loop control")
1651
1652 (js2-msg "msg.no.paren.with"
1653 "missing ( before with-statement object")
1654
1655 (js2-msg "msg.no.paren.after.with"
1656 "missing ) after with-statement object")
1657
1658 (js2-msg "msg.no.paren.after.let"
1659 "missing ( after let")
1660
1661 (js2-msg "msg.no.paren.let"
1662 "missing ) after variable list")
1663
1664 (js2-msg "msg.no.curly.let"
1665 "missing } after let statement")
1666
1667 (js2-msg "msg.bad.return"
1668 "invalid return")
1669
1670 (js2-msg "msg.no.brace.block"
1671 "missing } in compound statement")
1672
1673 (js2-msg "msg.bad.label"
1674 "invalid label")
1675
1676 (js2-msg "msg.bad.var"
1677 "missing variable name")
1678
1679 (js2-msg "msg.bad.var.init"
1680 "invalid variable initialization")
1681
1682 (js2-msg "msg.no.colon.cond"
1683 "missing : in conditional expression")
1684
1685 (js2-msg "msg.no.paren.arg"
1686 "missing ) after argument list")
1687
1688 (js2-msg "msg.no.bracket.arg"
1689 "missing ] after element list")
1690
1691 (js2-msg "msg.bad.prop"
1692 "invalid property id")
1693
1694 (js2-msg "msg.no.colon.prop"
1695 "missing : after property id")
1696
1697 (js2-msg "msg.no.brace.prop"
1698 "missing } after property list")
1699
1700 (js2-msg "msg.no.paren"
1701 "missing ) in parenthetical")
1702
1703 (js2-msg "msg.reserved.id"
1704 "identifier is a reserved word")
1705
1706 (js2-msg "msg.no.paren.catch"
1707 "missing ( before catch-block condition")
1708
1709 (js2-msg "msg.bad.catchcond"
1710 "invalid catch block condition")
1711
1712 (js2-msg "msg.catch.unreachable"
1713 "any catch clauses following an unqualified catch are unreachable")
1714
1715 (js2-msg "msg.no.brace.try"
1716 "missing '{' before try block")
1717
1718 (js2-msg "msg.no.brace.catchblock"
1719 "missing '{' before catch-block body")
1720
1721 (js2-msg "msg.try.no.catchfinally"
1722 "'try' without 'catch' or 'finally'")
1723
1724 (js2-msg "msg.no.return.value"
1725 "function %s does not always return a value")
1726
1727 (js2-msg "msg.anon.no.return.value"
1728 "anonymous function does not always return a value")
1729
1730 (js2-msg "msg.return.inconsistent"
1731 "return statement is inconsistent with previous usage")
1732
1733 (js2-msg "msg.generator.returns"
1734 "TypeError: generator function '%s' returns a value")
1735
1736 (js2-msg "msg.anon.generator.returns"
1737 "TypeError: anonymous generator function returns a value")
1738
1739 (js2-msg "msg.syntax"
1740 "syntax error")
1741
1742 (js2-msg "msg.unexpected.eof"
1743 "Unexpected end of file")
1744
1745 (js2-msg "msg.XML.bad.form"
1746 "illegally formed XML syntax")
1747
1748 (js2-msg "msg.XML.not.available"
1749 "XML runtime not available")
1750
1751 (js2-msg "msg.too.deep.parser.recursion"
1752 "Too deep recursion while parsing")
1753
1754 (js2-msg "msg.no.side.effects"
1755 "Code has no side effects")
1756
1757 (js2-msg "msg.extra.trailing.comma"
1758 "Trailing comma is not legal in an ECMA-262 object initializer")
1759
1760 (js2-msg "msg.array.trailing.comma"
1761 "Trailing comma yields different behavior across browsers")
1762
1763 (js2-msg "msg.equal.as.assign"
1764 (concat "Test for equality (==) mistyped as assignment (=)?"
1765 " (parenthesize to suppress warning)"))
1766
1767 (js2-msg "msg.var.hides.arg"
1768 "Variable %s hides argument")
1769
1770 (js2-msg "msg.destruct.assign.no.init"
1771 "Missing = in destructuring declaration")
1772
1773 ;; ScriptRuntime
1774 (js2-msg "msg.no.properties"
1775 "%s has no properties.")
1776
1777 (js2-msg "msg.invalid.iterator"
1778 "Invalid iterator value")
1779
1780 (js2-msg "msg.iterator.primitive"
1781 "__iterator__ returned a primitive value")
1782
1783 (js2-msg "msg.assn.create.strict"
1784 "Assignment to undeclared variable %s")
1785
1786 (js2-msg "msg.ref.undefined.prop"
1787 "Reference to undefined property '%s'")
1788
1789 (js2-msg "msg.prop.not.found"
1790 "Property %s not found.")
1791
1792 (js2-msg "msg.invalid.type"
1793 "Invalid JavaScript value of type %s")
1794
1795 (js2-msg "msg.primitive.expected"
1796 "Primitive type expected (had %s instead)")
1797
1798 (js2-msg "msg.namespace.expected"
1799 "Namespace object expected to left of :: (found %s instead)")
1800
1801 (js2-msg "msg.null.to.object"
1802 "Cannot convert null to an object.")
1803
1804 (js2-msg "msg.undef.to.object"
1805 "Cannot convert undefined to an object.")
1806
1807 (js2-msg "msg.cyclic.value"
1808 "Cyclic %s value not allowed.")
1809
1810 (js2-msg "msg.is.not.defined"
1811 "'%s' is not defined.")
1812
1813 (js2-msg "msg.undef.prop.read"
1814 "Cannot read property '%s' from %s")
1815
1816 (js2-msg "msg.undef.prop.write"
1817 "Cannot set property '%s' of %s to '%s'")
1818
1819 (js2-msg "msg.undef.prop.delete"
1820 "Cannot delete property '%s' of %s")
1821
1822 (js2-msg "msg.undef.method.call"
1823 "Cannot call method '%s' of %s")
1824
1825 (js2-msg "msg.undef.with"
1826 "Cannot apply 'with' to %s")
1827
1828 (js2-msg "msg.isnt.function"
1829 "%s is not a function, it is %s.")
1830
1831 (js2-msg "msg.isnt.function.in"
1832 "Cannot call property %s in object %s. "
1833 "It is not a function, it is '%s'.")
1834
1835 (js2-msg "msg.function.not.found"
1836 "Cannot find function %s.")
1837
1838 (js2-msg "msg.function.not.found.in"
1839 "Cannot find function %s in object %s.")
1840
1841 (js2-msg "msg.isnt.xml.object"
1842 "%s is not an xml object.")
1843
1844 (js2-msg "msg.no.ref.to.get"
1845 "%s is not a reference to read reference value.")
1846
1847 (js2-msg "msg.no.ref.to.set"
1848 "%s is not a reference to set reference value to %s.")
1849
1850 (js2-msg "msg.no.ref.from.function"
1851 "Function %s can not be used as the left-hand "
1852 "side of assignment or as an operand of ++ or -- operator.")
1853
1854 (js2-msg "msg.bad.default.value"
1855 "Object's getDefaultValue() method returned an object.")
1856
1857 (js2-msg "msg.instanceof.not.object"
1858 "Can't use instanceof on a non-object.")
1859
1860 (js2-msg "msg.instanceof.bad.prototype"
1861 "'prototype' property of %s is not an object.")
1862
1863 (js2-msg "msg.bad.radix"
1864 "illegal radix %s.")
1865
1866 ;; ScriptableObject
1867 (js2-msg "msg.default.value"
1868 "Cannot find default value for object.")
1869
1870 (js2-msg "msg.zero.arg.ctor"
1871 "Cannot load class '%s' which has no zero-parameter constructor.")
1872
1873 (js2-msg "msg.ctor.multiple.parms"
1874 "Can't define constructor or class %s since more than "
1875 "one constructor has multiple parameters.")
1876
1877 (js2-msg "msg.extend.scriptable"
1878 "%s must extend ScriptableObject in order to define property %s.")
1879
1880 (js2-msg "msg.bad.getter.parms"
1881 "In order to define a property, getter %s must have zero "
1882 "parameters or a single ScriptableObject parameter.")
1883
1884 (js2-msg "msg.obj.getter.parms"
1885 "Expected static or delegated getter %s to take "
1886 "a ScriptableObject parameter.")
1887
1888 (js2-msg "msg.getter.static"
1889 "Getter and setter must both be static or neither be static.")
1890
1891 (js2-msg "msg.setter.return"
1892 "Setter must have void return type: %s")
1893
1894 (js2-msg "msg.setter2.parms"
1895 "Two-parameter setter must take a ScriptableObject as "
1896 "its first parameter.")
1897
1898 (js2-msg "msg.setter1.parms"
1899 "Expected single parameter setter for %s")
1900
1901 (js2-msg "msg.setter2.expected"
1902 "Expected static or delegated setter %s to take two parameters.")
1903
1904 (js2-msg "msg.setter.parms"
1905 "Expected either one or two parameters for setter.")
1906
1907 (js2-msg "msg.setter.bad.type"
1908 "Unsupported parameter type '%s' in setter '%s'.")
1909
1910 (js2-msg "msg.add.sealed"
1911 "Cannot add a property to a sealed object: %s.")
1912
1913 (js2-msg "msg.remove.sealed"
1914 "Cannot remove a property from a sealed object: %s.")
1915
1916 (js2-msg "msg.modify.sealed"
1917 "Cannot modify a property of a sealed object: %s.")
1918
1919 (js2-msg "msg.modify.readonly"
1920 "Cannot modify readonly property: %s.")
1921
1922 ;; TokenStream
1923 (js2-msg "msg.missing.exponent"
1924 "missing exponent")
1925
1926 (js2-msg "msg.caught.nfe"
1927 "number format error")
1928
1929 (js2-msg "msg.unterminated.string.lit"
1930 "unterminated string literal")
1931
1932 (js2-msg "msg.unterminated.comment"
1933 "unterminated comment")
1934
1935 (js2-msg "msg.unterminated.re.lit"
1936 "unterminated regular expression literal")
1937
1938 (js2-msg "msg.invalid.re.flag"
1939 "invalid flag after regular expression")
1940
1941 (js2-msg "msg.no.re.input.for"
1942 "no input for %s")
1943
1944 (js2-msg "msg.illegal.character"
1945 "illegal character")
1946
1947 (js2-msg "msg.invalid.escape"
1948 "invalid Unicode escape sequence")
1949
1950 (js2-msg "msg.bad.namespace"
1951 "not a valid default namespace statement. "
1952 "Syntax is: default xml namespace = EXPRESSION;")
1953
1954 ;; TokensStream warnings
1955 (js2-msg "msg.bad.octal.literal"
1956 "illegal octal literal digit %s; "
1957 "interpreting it as a decimal digit")
1958
1959 (js2-msg "msg.reserved.keyword"
1960 "illegal usage of future reserved keyword %s; "
1961 "interpreting it as ordinary identifier")
1962
1963 (js2-msg "msg.script.is.not.constructor"
1964 "Script objects are not constructors.")
1965
1966 ;; Arrays
1967 (js2-msg "msg.arraylength.bad"
1968 "Inappropriate array length.")
1969
1970 ;; Arrays
1971 (js2-msg "msg.arraylength.too.big"
1972 "Array length %s exceeds supported capacity limit.")
1973
1974 ;; URI
1975 (js2-msg "msg.bad.uri"
1976 "Malformed URI sequence.")
1977
1978 ;; Number
1979 (js2-msg "msg.bad.precision"
1980 "Precision %s out of range.")
1981
1982 ;; NativeGenerator
1983 (js2-msg "msg.send.newborn"
1984 "Attempt to send value to newborn generator")
1985
1986 (js2-msg "msg.already.exec.gen"
1987 "Already executing generator")
1988
1989 (js2-msg "msg.StopIteration.invalid"
1990 "StopIteration may not be changed to an arbitrary object.")
1991
1992 ;; Interpreter
1993 (js2-msg "msg.yield.closing"
1994 "Yield from closing generator")
1995
1996 ;;; Utilities
1997
1998 (defun js2-delete-if (predicate list)
1999 "Remove all items satisfying PREDICATE in LIST."
2000 (loop for item in list
2001 if (not (funcall predicate item))
2002 collect item))
2003
2004 (defun js2-position (element list)
2005 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2006 Returns nil if element is not found in the list."
2007 (let ((count 0)
2008 found)
2009 (while (and list (not found))
2010 (if (eq element (car list))
2011 (setq found t)
2012 (setq count (1+ count)
2013 list (cdr list))))
2014 (if found count)))
2015
2016 (defun js2-find-if (predicate list)
2017 "Find first item satisfying PREDICATE in LIST."
2018 (let (result)
2019 (while (and list (not result))
2020 (if (funcall predicate (car list))
2021 (setq result (car list)))
2022 (setq list (cdr list)))
2023 result))
2024
2025 (defmacro js2-time (form)
2026 "Evaluate FORM, discard result, and return elapsed time in sec"
2027 (declare (debug t))
2028 (let ((beg (make-symbol "--js2-time-beg--"))
2029 (delta (make-symbol "--js2-time-end--")))
2030 `(let ((,beg (current-time))
2031 ,delta)
2032 ,form
2033 (/ (truncate (* (- (float-time (current-time))
2034 (float-time ,beg))
2035 10000))
2036 10000.0))))
2037
2038 (defsubst js2-same-line (pos)
2039 "Return t if POS is on the same line as current point."
2040 (and (>= pos (point-at-bol))
2041 (<= pos (point-at-eol))))
2042
2043 (defsubst js2-same-line-2 (p1 p2)
2044 "Return t if p1 is on the same line as p2."
2045 (save-excursion
2046 (goto-char p1)
2047 (js2-same-line p2)))
2048
2049 (defun js2-code-bug ()
2050 "Signal an error when we encounter an unexpected code path."
2051 (error "failed assertion"))
2052
2053 (defsubst js2-record-text-property (beg end prop value)
2054 "Record a text property to set when parsing finishes."
2055 (push (list beg end prop value) js2-mode-deferred-properties))
2056
2057 ;; I'd like to associate errors with nodes, but for now the
2058 ;; easiest thing to do is get the context info from the last token.
2059 (defsubst js2-record-parse-error (msg &optional arg pos len)
2060 (push (list (list msg arg)
2061 (or pos js2-token-beg)
2062 (or len (- js2-token-end js2-token-beg)))
2063 js2-parsed-errors))
2064
2065 (defsubst js2-report-error (msg &optional msg-arg pos len)
2066 "Signal a syntax error or record a parse error."
2067 (if js2-recover-from-parse-errors
2068 (js2-record-parse-error msg msg-arg pos len)
2069 (signal 'js2-syntax-error
2070 (list msg
2071 js2-ts-lineno
2072 (save-excursion
2073 (goto-char js2-ts-cursor)
2074 (current-column))
2075 js2-ts-hit-eof))))
2076
2077 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2078 (if js2-compiler-report-warning-as-error
2079 (js2-report-error msg msg-arg pos len)
2080 (push (list (list msg msg-arg)
2081 (or pos js2-token-beg)
2082 (or len (- js2-token-end js2-token-beg)))
2083 js2-parsed-warnings)))
2084
2085 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2086 (if js2-compiler-strict-mode
2087 (js2-report-warning msg-id msg-arg beg
2088 (and beg end (- end beg)))))
2089
2090 (put 'js2-syntax-error 'error-conditions
2091 '(error syntax-error js2-syntax-error))
2092 (put 'js2-syntax-error 'error-message "Syntax error")
2093
2094 (put 'js2-parse-error 'error-conditions
2095 '(error parse-error js2-parse-error))
2096 (put 'js2-parse-error 'error-message "Parse error")
2097
2098 (defmacro js2-clear-flag (flags flag)
2099 `(setq ,flags (logand ,flags (lognot ,flag))))
2100
2101 (defmacro js2-set-flag (flags flag)
2102 "Logical-or FLAG into FLAGS."
2103 `(setq ,flags (logior ,flags ,flag)))
2104
2105 (defsubst js2-flag-set-p (flags flag)
2106 (/= 0 (logand flags flag)))
2107
2108 (defsubst js2-flag-not-set-p (flags flag)
2109 (zerop (logand flags flag)))
2110
2111 ;; Stolen shamelessly from James Clark's nxml-mode.
2112 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2113 "Evaluate BODY without any text property changes modifying the buffer.
2114 Any text properties changes happen as usual but the changes are not treated as
2115 modifications to the buffer."
2116 (declare (indent 0) (debug t))
2117 (let ((modified (make-symbol "modified")))
2118 `(let ((,modified (buffer-modified-p))
2119 (inhibit-read-only t)
2120 (inhibit-modification-hooks t)
2121 (buffer-undo-list t)
2122 (deactivate-mark nil)
2123 ;; Apparently these avoid file locking problems.
2124 (buffer-file-name nil)
2125 (buffer-file-truename nil))
2126 (unwind-protect
2127 (progn ,@body)
2128 (unless ,modified
2129 (restore-buffer-modified-p nil))))))
2130
2131 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2132 "Evaluate BODY with the _ character set to be word-syntax."
2133 (declare (indent 0) (debug t))
2134 (let ((old-syntax (make-symbol "old-syntax")))
2135 `(let ((,old-syntax (string (char-syntax ?_))))
2136 (unwind-protect
2137 (progn
2138 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2139 ,@body)
2140 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2141
2142 (defsubst js2-char-uppercase-p (c)
2143 "Return t if C is an uppercase character.
2144 Handles unicode and latin chars properly."
2145 (/= c (downcase c)))
2146
2147 (defsubst js2-char-lowercase-p (c)
2148 "Return t if C is an uppercase character.
2149 Handles unicode and latin chars properly."
2150 (/= c (upcase c)))
2151
2152 ;;; AST struct and function definitions
2153
2154 ;; flags for ast node property 'member-type (used for e4x operators)
2155 (defvar js2-property-flag #x1 "property access: element is valid name")
2156 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2157 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2158
2159 (defsubst js2-relpos (pos anchor)
2160 "Convert POS to be relative to ANCHOR.
2161 If POS is nil, returns nil."
2162 (and pos (- pos anchor)))
2163
2164 (defsubst js2-make-pad (indent)
2165 (if (zerop indent)
2166 ""
2167 (make-string (* indent js2-basic-offset) ? )))
2168
2169 (defsubst js2-visit-ast (node callback)
2170 "Visit every node in ast NODE with visitor CALLBACK.
2171
2172 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2173 called twice: once to visit the node, and again after all the node's
2174 children have been processed. The END-P argument is nil on the first
2175 call and non-nil on the second call. The return value of the callback
2176 affects the traversal: if non-nil, the children of NODE are processed.
2177 If the callback returns nil, or if the node has no children, then the
2178 callback is called immediately with a non-nil END-P argument.
2179
2180 The node traversal is approximately lexical-order, although there
2181 are currently no guarantees around this."
2182 (if node
2183 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2184 ;; visit the node
2185 (when (funcall callback node nil)
2186 ;; visit the kids
2187 (cond
2188 ((eq vfunc 'js2-visit-none)
2189 nil) ; don't even bother calling it
2190 ;; Each AST node type has to define a `js2-visitor' function
2191 ;; that takes a node and a callback, and calls `js2-visit-ast'
2192 ;; on each child of the node.
2193 (vfunc
2194 (funcall vfunc node callback))
2195 (t
2196 (error "%s does not define a visitor-traversal function"
2197 (aref node 0)))))
2198 ;; call the end-visit
2199 (funcall callback node t))))
2200
2201 (defstruct (js2-node
2202 (:constructor nil)) ; abstract
2203 "Base AST node type."
2204 (type -1) ; token type
2205 (pos -1) ; start position of this AST node in parsed input
2206 (len 1) ; num characters spanned by the node
2207 props ; optional node property list (an alist)
2208 parent) ; link to parent node; null for root
2209
2210 (defsubst js2-node-get-prop (node prop &optional default)
2211 (or (cadr (assoc prop (js2-node-props node))) default))
2212
2213 (defsubst js2-node-set-prop (node prop value)
2214 (setf (js2-node-props node)
2215 (cons (list prop value) (js2-node-props node))))
2216
2217 (defsubst js2-fixup-starts (n nodes)
2218 "Adjust the start positions of NODES to be relative to N.
2219 Any node in the list may be nil, for convenience."
2220 (dolist (node nodes)
2221 (when node
2222 (setf (js2-node-pos node) (- (js2-node-pos node)
2223 (js2-node-pos n))))))
2224
2225 (defsubst js2-node-add-children (parent &rest nodes)
2226 "Set parent node of NODES to PARENT, and return PARENT.
2227 Does nothing if we're not recording parent links.
2228 If any given node in NODES is nil, doesn't record that link."
2229 (js2-fixup-starts parent nodes)
2230 (dolist (node nodes)
2231 (and node
2232 (setf (js2-node-parent node) parent))))
2233
2234 ;; Non-recursive since it's called a frightening number of times.
2235 (defsubst js2-node-abs-pos (n)
2236 (let ((pos (js2-node-pos n)))
2237 (while (setq n (js2-node-parent n))
2238 (setq pos (+ pos (js2-node-pos n))))
2239 pos))
2240
2241 (defsubst js2-node-abs-end (n)
2242 "Return absolute buffer position of end of N."
2243 (+ (js2-node-abs-pos n) (js2-node-len n)))
2244
2245 ;; It's important to make sure block nodes have a lisp list for the
2246 ;; child nodes, to limit printing recursion depth in an AST that
2247 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2248 ;; a sufficiently large vector tree.
2249
2250 (defstruct (js2-block-node
2251 (:include js2-node)
2252 (:constructor nil)
2253 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2254 (pos js2-token-beg)
2255 len
2256 props
2257 kids)))
2258 "A block of statements."
2259 kids) ; a lisp list of the child statement nodes
2260
2261 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2262 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2263
2264 (defsubst js2-visit-block (ast callback)
2265 "Visit the `js2-block-node' children of AST."
2266 (dolist (kid (js2-block-node-kids ast))
2267 (js2-visit-ast kid callback)))
2268
2269 (defun js2-print-block (n i)
2270 (let ((pad (js2-make-pad i)))
2271 (insert pad "{\n")
2272 (dolist (kid (js2-block-node-kids n))
2273 (js2-print-ast kid (1+ i)))
2274 (insert pad "}")))
2275
2276 (defstruct (js2-scope
2277 (:include js2-block-node)
2278 (:constructor nil)
2279 (:constructor make-js2-scope (&key (type js2-BLOCK)
2280 (pos js2-token-beg)
2281 len
2282 kids)))
2283 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2284 ;; I don't have one of those handy, so I'll use an alist for now.
2285 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2286 ;; and is much lighter-weight to construct (both CPU and mem).
2287 ;; The keys are interned strings (symbols) for faster lookup.
2288 ;; Should switch to hybrid alist/hashtable eventually.
2289 symbol-table ; an alist of (symbol . js2-symbol)
2290 parent-scope ; a `js2-scope'
2291 top) ; top-level `js2-scope' (script/function)
2292
2293 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2294 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2295
2296 (defun js2-scope-set-parent-scope (scope parent)
2297 (setf (js2-scope-parent-scope scope) parent
2298 (js2-scope-top scope) (if (null parent)
2299 scope
2300 (js2-scope-top parent))))
2301
2302 (defun js2-node-get-enclosing-scope (node)
2303 "Return the innermost `js2-scope' node surrounding NODE.
2304 Returns nil if there is no enclosing scope node."
2305 (let ((parent (js2-node-parent node)))
2306 (while (not (js2-scope-p parent))
2307 (setq parent (js2-node-parent parent)))
2308 parent))
2309
2310 (defun js2-get-defining-scope (scope name)
2311 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2312 Returns `js2-scope' in which NAME is defined, or nil if not found."
2313 (let ((sym (if (symbolp name)
2314 name
2315 (intern name)))
2316 table
2317 result
2318 (continue t))
2319 (while (and scope continue)
2320 (if (and (setq table (js2-scope-symbol-table scope))
2321 (assq sym table))
2322 (setq continue nil
2323 result scope)
2324 (setq scope (js2-scope-parent-scope scope))))
2325 result))
2326
2327 (defsubst js2-scope-get-symbol (scope name)
2328 "Return symbol table entry for NAME in SCOPE.
2329 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2330 (and (js2-scope-symbol-table scope)
2331 (cdr (assq (if (symbolp name)
2332 name
2333 (intern name))
2334 (js2-scope-symbol-table scope)))))
2335
2336 (defsubst js2-scope-put-symbol (scope name symbol)
2337 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2338 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2339 (let* ((table (js2-scope-symbol-table scope))
2340 (sym (if (symbolp name) name (intern name)))
2341 (entry (assq sym table)))
2342 (if entry
2343 (setcdr entry symbol)
2344 (push (cons sym symbol)
2345 (js2-scope-symbol-table scope)))))
2346
2347 (defstruct (js2-symbol
2348 (:constructor nil)
2349 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2350 "A symbol table entry."
2351 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2352 ;; js2-LET, or js2-CONST
2353 decl-type
2354 name ; string
2355 ast-node) ; a `js2-node'
2356
2357 (defstruct (js2-error-node
2358 (:include js2-node)
2359 (:constructor nil) ; silence emacs21 byte-compiler
2360 (:constructor make-js2-error-node (&key (type js2-ERROR)
2361 (pos js2-token-beg)
2362 len)))
2363 "AST node representing a parse error.")
2364
2365 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2366 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2367
2368 (defstruct (js2-script-node
2369 (:include js2-scope)
2370 (:constructor nil)
2371 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2372 (pos js2-token-beg)
2373 len
2374 var-decls
2375 fun-decls)))
2376 functions ; lisp list of nested functions
2377 regexps ; lisp list of (string . flags)
2378 symbols ; alist (every symbol gets unique index)
2379 (param-count 0)
2380 var-names ; vector of string names
2381 consts ; bool-vector matching var-decls
2382 (temp-number 0)) ; for generating temp variables
2383
2384 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2385 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2386
2387 (defun js2-print-script (node indent)
2388 (dolist (kid (js2-block-node-kids node))
2389 (js2-print-ast kid indent)))
2390
2391 (defstruct (js2-ast-root
2392 (:include js2-script-node)
2393 (:constructor nil)
2394 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2395 (pos js2-token-beg)
2396 len
2397 buffer)))
2398 "The root node of a js2 AST."
2399 buffer ; the source buffer from which the code was parsed
2400 comments ; a lisp list of comments, ordered by start position
2401 errors ; a lisp list of errors found during parsing
2402 warnings ; a lisp list of warnings found during parsing
2403 node-count) ; number of nodes in the tree, including the root
2404
2405 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2406 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2407
2408 (defun js2-visit-ast-root (ast callback)
2409 (dolist (kid (js2-ast-root-kids ast))
2410 (js2-visit-ast kid callback))
2411 (dolist (comment (js2-ast-root-comments ast))
2412 (js2-visit-ast comment callback)))
2413
2414 (defstruct (js2-comment-node
2415 (:include js2-node)
2416 (:constructor nil)
2417 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2418 (pos js2-token-beg)
2419 len
2420 (format js2-ts-comment-type))))
2421 format) ; 'line, 'block, 'jsdoc or 'html
2422
2423 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2424 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2425
2426 (defun js2-print-comment (n i)
2427 ;; We really ought to link end-of-line comments to their nodes.
2428 ;; Or maybe we could add a new comment type, 'endline.
2429 (insert (js2-make-pad i)
2430 (js2-node-string n)))
2431
2432 (defstruct (js2-expr-stmt-node
2433 (:include js2-node)
2434 (:constructor nil)
2435 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2436 (pos js2-ts-cursor)
2437 len
2438 expr)))
2439 "An expression statement."
2440 expr)
2441
2442 (defsubst js2-expr-stmt-node-set-has-result (node)
2443 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2444 (setf (js2-node-type node) js2-EXPR_RESULT))
2445
2446 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2447 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2448
2449 (defun js2-visit-expr-stmt-node (n v)
2450 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2451
2452 (defun js2-print-expr-stmt-node (n indent)
2453 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2454 (insert ";\n"))
2455
2456 (defstruct (js2-loop-node
2457 (:include js2-scope)
2458 (:constructor nil))
2459 "Abstract supertype of loop nodes."
2460 body ; a `js2-block-node'
2461 lp ; position of left-paren, nil if omitted
2462 rp) ; position of right-paren, nil if omitted
2463
2464 (defstruct (js2-do-node
2465 (:include js2-loop-node)
2466 (:constructor nil)
2467 (:constructor make-js2-do-node (&key (type js2-DO)
2468 (pos js2-token-beg)
2469 len
2470 body
2471 condition
2472 while-pos
2473 lp
2474 rp)))
2475 "AST node for do-loop."
2476 condition ; while (expression)
2477 while-pos) ; buffer position of 'while' keyword
2478
2479 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2480 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2481
2482 (defun js2-visit-do-node (n v)
2483 (js2-visit-ast (js2-do-node-body n) v)
2484 (js2-visit-ast (js2-do-node-condition n) v))
2485
2486 (defun js2-print-do-node (n i)
2487 (let ((pad (js2-make-pad i)))
2488 (insert pad "do {\n")
2489 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2490 (js2-print-ast kid (1+ i)))
2491 (insert pad "} while (")
2492 (js2-print-ast (js2-do-node-condition n) 0)
2493 (insert ");\n")))
2494
2495 (defstruct (js2-while-node
2496 (:include js2-loop-node)
2497 (:constructor nil)
2498 (:constructor make-js2-while-node (&key (type js2-WHILE)
2499 (pos js2-token-beg)
2500 len
2501 body
2502 condition
2503 lp
2504 rp)))
2505 "AST node for while-loop."
2506 condition) ; while-condition
2507
2508 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2509 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2510
2511 (defun js2-visit-while-node (n v)
2512 (js2-visit-ast (js2-while-node-condition n) v)
2513 (js2-visit-ast (js2-while-node-body n) v))
2514
2515 (defun js2-print-while-node (n i)
2516 (let ((pad (js2-make-pad i)))
2517 (insert pad "while (")
2518 (js2-print-ast (js2-while-node-condition n) 0)
2519 (insert ") {\n")
2520 (js2-print-body (js2-while-node-body n) (1+ i))
2521 (insert pad "}\n")))
2522
2523 (defstruct (js2-for-node
2524 (:include js2-loop-node)
2525 (:constructor nil)
2526 (:constructor make-js2-for-node (&key (type js2-FOR)
2527 (pos js2-ts-cursor)
2528 len
2529 body
2530 init
2531 condition
2532 update
2533 lp
2534 rp)))
2535 "AST node for a C-style for-loop."
2536 init ; initialization expression
2537 condition ; loop condition
2538 update) ; update clause
2539
2540 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2541 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2542
2543 (defun js2-visit-for-node (n v)
2544 (js2-visit-ast (js2-for-node-init n) v)
2545 (js2-visit-ast (js2-for-node-condition n) v)
2546 (js2-visit-ast (js2-for-node-update n) v)
2547 (js2-visit-ast (js2-for-node-body n) v))
2548
2549 (defun js2-print-for-node (n i)
2550 (let ((pad (js2-make-pad i)))
2551 (insert pad "for (")
2552 (js2-print-ast (js2-for-node-init n) 0)
2553 (insert "; ")
2554 (js2-print-ast (js2-for-node-condition n) 0)
2555 (insert "; ")
2556 (js2-print-ast (js2-for-node-update n) 0)
2557 (insert ") {\n")
2558 (js2-print-body (js2-for-node-body n) (1+ i))
2559 (insert pad "}\n")))
2560
2561 (defstruct (js2-for-in-node
2562 (:include js2-loop-node)
2563 (:constructor nil)
2564 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2565 (pos js2-ts-cursor)
2566 len
2567 body
2568 iterator
2569 object
2570 in-pos
2571 each-pos
2572 foreach-p
2573 lp
2574 rp)))
2575 "AST node for a for..in loop."
2576 iterator ; [var] foo in ...
2577 object ; object over which we're iterating
2578 in-pos ; buffer position of 'in' keyword
2579 each-pos ; buffer position of 'each' keyword, if foreach-p
2580 foreach-p) ; t if it's a for-each loop
2581
2582 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2583 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2584
2585 (defun js2-visit-for-in-node (n v)
2586 (js2-visit-ast (js2-for-in-node-iterator n) v)
2587 (js2-visit-ast (js2-for-in-node-object n) v)
2588 (js2-visit-ast (js2-for-in-node-body n) v))
2589
2590 (defun js2-print-for-in-node (n i)
2591 (let ((pad (js2-make-pad i))
2592 (foreach (js2-for-in-node-foreach-p n)))
2593 (insert pad "for ")
2594 (if foreach
2595 (insert "each "))
2596 (insert "(")
2597 (js2-print-ast (js2-for-in-node-iterator n) 0)
2598 (insert " in ")
2599 (js2-print-ast (js2-for-in-node-object n) 0)
2600 (insert ") {\n")
2601 (js2-print-body (js2-for-in-node-body n) (1+ i))
2602 (insert pad "}\n")))
2603
2604 (defstruct (js2-return-node
2605 (:include js2-node)
2606 (:constructor nil)
2607 (:constructor make-js2-return-node (&key (type js2-RETURN)
2608 (pos js2-ts-cursor)
2609 len
2610 retval)))
2611 "AST node for a return statement."
2612 retval) ; expression to return, or 'undefined
2613
2614 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2615 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2616
2617 (defun js2-visit-return-node (n v)
2618 (js2-visit-ast (js2-return-node-retval n) v))
2619
2620 (defun js2-print-return-node (n i)
2621 (insert (js2-make-pad i) "return")
2622 (when (js2-return-node-retval n)
2623 (insert " ")
2624 (js2-print-ast (js2-return-node-retval n) 0))
2625 (insert ";\n"))
2626
2627 (defstruct (js2-if-node
2628 (:include js2-node)
2629 (:constructor nil)
2630 (:constructor make-js2-if-node (&key (type js2-IF)
2631 (pos js2-ts-cursor)
2632 len
2633 condition
2634 then-part
2635 else-pos
2636 else-part
2637 lp
2638 rp)))
2639 "AST node for an if-statement."
2640 condition ; expression
2641 then-part ; statement or block
2642 else-pos ; optional buffer position of 'else' keyword
2643 else-part ; optional statement or block
2644 lp ; position of left-paren, nil if omitted
2645 rp) ; position of right-paren, nil if omitted
2646
2647 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2648 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2649
2650 (defun js2-visit-if-node (n v)
2651 (js2-visit-ast (js2-if-node-condition n) v)
2652 (js2-visit-ast (js2-if-node-then-part n) v)
2653 (js2-visit-ast (js2-if-node-else-part n) v))
2654
2655 (defun js2-print-if-node (n i)
2656 (let ((pad (js2-make-pad i))
2657 (then-part (js2-if-node-then-part n))
2658 (else-part (js2-if-node-else-part n)))
2659 (insert pad "if (")
2660 (js2-print-ast (js2-if-node-condition n) 0)
2661 (insert ") {\n")
2662 (js2-print-body then-part (1+ i))
2663 (insert pad "}")
2664 (cond
2665 ((not else-part)
2666 (insert "\n"))
2667 ((js2-if-node-p else-part)
2668 (insert " else ")
2669 (js2-print-body else-part i))
2670 (t
2671 (insert " else {\n")
2672 (js2-print-body else-part (1+ i))
2673 (insert pad "}\n")))))
2674
2675 (defstruct (js2-try-node
2676 (:include js2-node)
2677 (:constructor nil)
2678 (:constructor make-js2-try-node (&key (type js2-TRY)
2679 (pos js2-ts-cursor)
2680 len
2681 try-block
2682 catch-clauses
2683 finally-block)))
2684 "AST node for a try-statement."
2685 try-block
2686 catch-clauses ; a lisp list of `js2-catch-node'
2687 finally-block) ; a `js2-finally-node'
2688
2689 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2690 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2691
2692 (defun js2-visit-try-node (n v)
2693 (js2-visit-ast (js2-try-node-try-block n) v)
2694 (dolist (clause (js2-try-node-catch-clauses n))
2695 (js2-visit-ast clause v))
2696 (js2-visit-ast (js2-try-node-finally-block n) v))
2697
2698 (defun js2-print-try-node (n i)
2699 (let ((pad (js2-make-pad i))
2700 (catches (js2-try-node-catch-clauses n))
2701 (finally (js2-try-node-finally-block n)))
2702 (insert pad "try {\n")
2703 (js2-print-body (js2-try-node-try-block n) (1+ i))
2704 (insert pad "}")
2705 (when catches
2706 (dolist (catch catches)
2707 (js2-print-ast catch i)))
2708 (if finally
2709 (js2-print-ast finally i)
2710 (insert "\n"))))
2711
2712 (defstruct (js2-catch-node
2713 (:include js2-node)
2714 (:constructor nil)
2715 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2716 (pos js2-ts-cursor)
2717 len
2718 param
2719 guard-kwd
2720 guard-expr
2721 block
2722 lp
2723 rp)))
2724 "AST node for a catch clause."
2725 param ; destructuring form or simple name node
2726 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2727 guard-expr ; catch condition, a `js2-node'
2728 block ; statements, a `js2-block-node'
2729 lp ; buffer position of left-paren, nil if omitted
2730 rp) ; buffer position of right-paren, nil if omitted
2731
2732 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2733 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2734
2735 (defun js2-visit-catch-node (n v)
2736 (js2-visit-ast (js2-catch-node-param n) v)
2737 (when (js2-catch-node-guard-kwd n)
2738 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2739 (js2-visit-ast (js2-catch-node-block n) v))
2740
2741 (defun js2-print-catch-node (n i)
2742 (let ((pad (js2-make-pad i))
2743 (guard-kwd (js2-catch-node-guard-kwd n))
2744 (guard-expr (js2-catch-node-guard-expr n)))
2745 (insert " catch (")
2746 (js2-print-ast (js2-catch-node-param n) 0)
2747 (when guard-kwd
2748 (insert " if ")
2749 (js2-print-ast guard-expr 0))
2750 (insert ") {\n")
2751 (js2-print-body (js2-catch-node-block n) (1+ i))
2752 (insert pad "}")))
2753
2754 (defstruct (js2-finally-node
2755 (:include js2-node)
2756 (:constructor nil)
2757 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2758 (pos js2-ts-cursor)
2759 len
2760 body)))
2761 "AST node for a finally clause."
2762 body) ; a `js2-node', often but not always a block node
2763
2764 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2765 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2766
2767 (defun js2-visit-finally-node (n v)
2768 (js2-visit-ast (js2-finally-node-body n) v))
2769
2770 (defun js2-print-finally-node (n i)
2771 (let ((pad (js2-make-pad i)))
2772 (insert " finally {\n")
2773 (js2-print-body (js2-finally-node-body n) (1+ i))
2774 (insert pad "}\n")))
2775
2776 (defstruct (js2-switch-node
2777 (:include js2-node)
2778 (:constructor nil)
2779 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2780 (pos js2-ts-cursor)
2781 len
2782 discriminant
2783 cases
2784 lp
2785 rp)))
2786 "AST node for a switch statement."
2787 discriminant ; a `js2-node' (switch expression)
2788 cases ; a lisp list of `js2-case-node'
2789 lp ; position of open-paren for discriminant, nil if omitted
2790 rp) ; position of close-paren for discriminant, nil if omitted
2791
2792 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2793 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2794
2795 (defun js2-visit-switch-node (n v)
2796 (js2-visit-ast (js2-switch-node-discriminant n) v)
2797 (dolist (c (js2-switch-node-cases n))
2798 (js2-visit-ast c v)))
2799
2800 (defun js2-print-switch-node (n i)
2801 (let ((pad (js2-make-pad i))
2802 (cases (js2-switch-node-cases n)))
2803 (insert pad "switch (")
2804 (js2-print-ast (js2-switch-node-discriminant n) 0)
2805 (insert ") {\n")
2806 (dolist (case cases)
2807 (js2-print-ast case i))
2808 (insert pad "}\n")))
2809
2810 (defstruct (js2-case-node
2811 (:include js2-block-node)
2812 (:constructor nil)
2813 (:constructor make-js2-case-node (&key (type js2-CASE)
2814 (pos js2-ts-cursor)
2815 len
2816 kids
2817 expr)))
2818 "AST node for a case clause of a switch statement."
2819 expr) ; the case expression (nil for default)
2820
2821 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2822 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2823
2824 (defun js2-visit-case-node (n v)
2825 (js2-visit-ast (js2-case-node-expr n) v)
2826 (js2-visit-block n v))
2827
2828 (defun js2-print-case-node (n i)
2829 (let ((pad (js2-make-pad i))
2830 (expr (js2-case-node-expr n)))
2831 (insert pad)
2832 (if (null expr)
2833 (insert "default:\n")
2834 (insert "case ")
2835 (js2-print-ast expr 0)
2836 (insert ":\n"))
2837 (dolist (kid (js2-case-node-kids n))
2838 (js2-print-ast kid (1+ i)))))
2839
2840 (defstruct (js2-throw-node
2841 (:include js2-node)
2842 (:constructor nil)
2843 (:constructor make-js2-throw-node (&key (type js2-THROW)
2844 (pos js2-ts-cursor)
2845 len
2846 expr)))
2847 "AST node for a throw statement."
2848 expr) ; the expression to throw
2849
2850 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2851 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2852
2853 (defun js2-visit-throw-node (n v)
2854 (js2-visit-ast (js2-throw-node-expr n) v))
2855
2856 (defun js2-print-throw-node (n i)
2857 (insert (js2-make-pad i) "throw ")
2858 (js2-print-ast (js2-throw-node-expr n) 0)
2859 (insert ";\n"))
2860
2861 (defstruct (js2-with-node
2862 (:include js2-node)
2863 (:constructor nil)
2864 (:constructor make-js2-with-node (&key (type js2-WITH)
2865 (pos js2-ts-cursor)
2866 len
2867 object
2868 body
2869 lp
2870 rp)))
2871 "AST node for a with-statement."
2872 object
2873 body
2874 lp ; buffer position of left-paren around object, nil if omitted
2875 rp) ; buffer position of right-paren around object, nil if omitted
2876
2877 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2878 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2879
2880 (defun js2-visit-with-node (n v)
2881 (js2-visit-ast (js2-with-node-object n) v)
2882 (js2-visit-ast (js2-with-node-body n) v))
2883
2884 (defun js2-print-with-node (n i)
2885 (let ((pad (js2-make-pad i)))
2886 (insert pad "with (")
2887 (js2-print-ast (js2-with-node-object n) 0)
2888 (insert ") {\n")
2889 (js2-print-body (js2-with-node-body n) (1+ i))
2890 (insert pad "}\n")))
2891
2892 (defstruct (js2-label-node
2893 (:include js2-node)
2894 (:constructor nil)
2895 (:constructor make-js2-label-node (&key (type js2-LABEL)
2896 (pos js2-ts-cursor)
2897 len
2898 name)))
2899 "AST node for a statement label or case label."
2900 name ; a string
2901 loop) ; for validating and code-generating continue-to-label
2902
2903 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2904 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2905
2906 (defun js2-print-label (n i)
2907 (insert (js2-make-pad i)
2908 (js2-label-node-name n)
2909 ":\n"))
2910
2911 (defstruct (js2-labeled-stmt-node
2912 (:include js2-node)
2913 (:constructor nil)
2914 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2915 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2916 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2917 (pos js2-ts-cursor)
2918 len
2919 labels
2920 stmt)))
2921 "AST node for a statement with one or more labels.
2922 Multiple labels for a statement are collapsed into the labels field."
2923 labels ; lisp list of `js2-label-node'
2924 stmt) ; the statement these labels are for
2925
2926 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2927 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2928
2929 (defun js2-get-label-by-name (lbl-stmt name)
2930 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2931 Returns nil if no such label is in the list."
2932 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2933 result)
2934 (while (and label-list (not result))
2935 (if (string= (js2-label-node-name (car label-list)) name)
2936 (setq result (car label-list))
2937 (setq label-list (cdr label-list))))
2938 result))
2939
2940 (defun js2-visit-labeled-stmt (n v)
2941 (dolist (label (js2-labeled-stmt-node-labels n))
2942 (js2-visit-ast label v))
2943 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2944
2945 (defun js2-print-labeled-stmt (n i)
2946 (dolist (label (js2-labeled-stmt-node-labels n))
2947 (js2-print-ast label i))
2948 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2949
2950 (defun js2-labeled-stmt-node-contains (node label)
2951 "Return t if NODE contains LABEL in its label set.
2952 NODE is a `js2-labels-node'. LABEL is an identifier."
2953 (loop for nl in (js2-labeled-stmt-node-labels node)
2954 if (string= label (js2-label-node-name nl))
2955 return t
2956 finally return nil))
2957
2958 (defsubst js2-labeled-stmt-node-add-label (node label)
2959 "Add a `js2-label-node' to the label set for this statement."
2960 (setf (js2-labeled-stmt-node-labels node)
2961 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2962
2963 (defstruct (js2-jump-node
2964 (:include js2-node)
2965 (:constructor nil))
2966 "Abstract supertype of break and continue nodes."
2967 label ; `js2-name-node' for location of label identifier, if present
2968 target) ; target js2-labels-node or loop/switch statement
2969
2970 (defun js2-visit-jump-node (n v)
2971 (js2-visit-ast (js2-jump-node-label n) v))
2972
2973 (defstruct (js2-break-node
2974 (:include js2-jump-node)
2975 (:constructor nil)
2976 (:constructor make-js2-break-node (&key (type js2-BREAK)
2977 (pos js2-ts-cursor)
2978 len
2979 label
2980 target)))
2981 "AST node for a break statement.
2982 The label field is a `js2-name-node', possibly nil, for the named label
2983 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2984 is the target of the break - a label node or enclosing loop/switch statement.")
2985
2986 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2987 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2988
2989 (defun js2-print-break-node (n i)
2990 (insert (js2-make-pad i) "break")
2991 (when (js2-break-node-label n)
2992 (insert " ")
2993 (js2-print-ast (js2-break-node-label n) 0))
2994 (insert ";\n"))
2995
2996 (defstruct (js2-continue-node
2997 (:include js2-jump-node)
2998 (:constructor nil)
2999 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3000 (pos js2-ts-cursor)
3001 len
3002 label
3003 target)))
3004 "AST node for a continue statement.
3005 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3006 It is nil if continue specifies no label. The target field is the jump target:
3007 a `js2-label-node' or the innermost enclosing loop.")
3008
3009 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3010 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3011
3012 (defun js2-print-continue-node (n i)
3013 (insert (js2-make-pad i) "continue")
3014 (when (js2-continue-node-label n)
3015 (insert " ")
3016 (js2-print-ast (js2-continue-node-label n) 0))
3017 (insert ";\n"))
3018
3019 (defstruct (js2-function-node
3020 (:include js2-script-node)
3021 (:constructor nil)
3022 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3023 (pos js2-ts-cursor)
3024 len
3025 (ftype 'FUNCTION)
3026 (form 'FUNCTION_STATEMENT)
3027 (name "")
3028 params
3029 body
3030 lp
3031 rp)))
3032 "AST node for a function declaration.
3033 The `params' field is a lisp list of nodes. Each node is either a simple
3034 `js2-name-node', or if it's a destructuring-assignment parameter, a
3035 `js2-array-node' or `js2-object-node'."
3036 ftype ; FUNCTION, GETTER or SETTER
3037 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3038 name ; function name (a `js2-name-node', or nil if anonymous)
3039 params ; a lisp list of destructuring forms or simple name nodes
3040 body ; a `js2-block-node' or expression node (1.8 only)
3041 lp ; position of arg-list open-paren, or nil if omitted
3042 rp ; position of arg-list close-paren, or nil if omitted
3043 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3044 needs-activation ; t if we need an activation object for this frame
3045 is-generator ; t if this function contains a yield
3046 member-expr) ; nonstandard Ecma extension from Rhino
3047
3048 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3049 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3050
3051 (defun js2-visit-function-node (n v)
3052 (js2-visit-ast (js2-function-node-name n) v)
3053 (dolist (p (js2-function-node-params n))
3054 (js2-visit-ast p v))
3055 (js2-visit-ast (js2-function-node-body n) v))
3056
3057 (defun js2-print-function-node (n i)
3058 (let ((pad (js2-make-pad i))
3059 (getter (js2-node-get-prop n 'GETTER_SETTER))
3060 (name (js2-function-node-name n))
3061 (params (js2-function-node-params n))
3062 (body (js2-function-node-body n))
3063 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3064 (unless getter
3065 (insert pad "function"))
3066 (when name
3067 (insert " ")
3068 (js2-print-ast name 0))
3069 (insert "(")
3070 (loop with len = (length params)
3071 for param in params
3072 for count from 1
3073 do
3074 (js2-print-ast param 0)
3075 (if (< count len)
3076 (insert ", ")))
3077 (insert ") {")
3078 (unless expr
3079 (insert "\n"))
3080 ;; TODO: fix this to be smarter about indenting, etc.
3081 (js2-print-body body (1+ i))
3082 (insert pad "}")
3083 (unless expr
3084 (insert "\n"))))
3085
3086 (defsubst js2-function-name (node)
3087 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3088 (and (js2-function-node-name node)
3089 (js2-name-node-name (js2-function-node-name node))))
3090
3091 ;; Having this be an expression node makes it more flexible.
3092 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3093 ;; that work better if you assume it's an expression. Whenever we have
3094 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3095 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3096 (defstruct (js2-var-decl-node
3097 (:include js2-node)
3098 (:constructor nil)
3099 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3100 (pos js2-token-beg)
3101 len
3102 kids
3103 decl-type)))
3104 "AST node for a variable declaration list (VAR, CONST or LET).
3105 The node bounds differ depending on the declaration type. For VAR or
3106 CONST declarations, the bounds include the var/const keyword. For LET
3107 declarations, the node begins at the position of the first child."
3108 kids ; a lisp list of `js2-var-init-node' structs.
3109 decl-type) ; js2-VAR, js2-CONST or js2-LET
3110
3111 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3112 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3113
3114 (defun js2-visit-var-decl (n v)
3115 (dolist (kid (js2-var-decl-node-kids n))
3116 (js2-visit-ast kid v)))
3117
3118 (defun js2-print-var-decl (n i)
3119 (let ((pad (js2-make-pad i))
3120 (tt (js2-var-decl-node-decl-type n)))
3121 (insert pad)
3122 (insert (cond
3123 ((= tt js2-VAR) "var ")
3124 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3125 ((= tt js2-CONST) "const ")
3126 (t
3127 (error "malformed var-decl node"))))
3128 (loop with kids = (js2-var-decl-node-kids n)
3129 with len = (length kids)
3130 for kid in kids
3131 for count from 1
3132 do
3133 (js2-print-ast kid 0)
3134 (if (< count len)
3135 (insert ", ")))))
3136
3137 (defstruct (js2-var-init-node
3138 (:include js2-node)
3139 (:constructor nil)
3140 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3141 (pos js2-ts-cursor)
3142 len
3143 target
3144 initializer)))
3145 "AST node for a variable declaration.
3146 The type field will be js2-CONST for a const decl."
3147 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3148 initializer) ; initializer expression, a `js2-node'
3149
3150 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3151 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3152
3153 (defun js2-visit-var-init-node (n v)
3154 (js2-visit-ast (js2-var-init-node-target n) v)
3155 (js2-visit-ast (js2-var-init-node-initializer n) v))
3156
3157 (defun js2-print-var-init-node (n i)
3158 (let ((pad (js2-make-pad i))
3159 (name (js2-var-init-node-target n))
3160 (init (js2-var-init-node-initializer n)))
3161 (insert pad)
3162 (js2-print-ast name 0)
3163 (when init
3164 (insert " = ")
3165 (js2-print-ast init 0))))
3166
3167 (defstruct (js2-cond-node
3168 (:include js2-node)
3169 (:constructor nil)
3170 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3171 (pos js2-ts-cursor)
3172 len
3173 test-expr
3174 true-expr
3175 false-expr
3176 q-pos
3177 c-pos)))
3178 "AST node for the ternary operator"
3179 test-expr
3180 true-expr
3181 false-expr
3182 q-pos ; buffer position of ?
3183 c-pos) ; buffer position of :
3184
3185 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3186 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3187
3188 (defun js2-visit-cond-node (n v)
3189 (js2-visit-ast (js2-cond-node-test-expr n) v)
3190 (js2-visit-ast (js2-cond-node-true-expr n) v)
3191 (js2-visit-ast (js2-cond-node-false-expr n) v))
3192
3193 (defun js2-print-cond-node (n i)
3194 (let ((pad (js2-make-pad i)))
3195 (insert pad)
3196 (js2-print-ast (js2-cond-node-test-expr n) 0)
3197 (insert " ? ")
3198 (js2-print-ast (js2-cond-node-true-expr n) 0)
3199 (insert " : ")
3200 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3201
3202 (defstruct (js2-infix-node
3203 (:include js2-node)
3204 (:constructor nil)
3205 (:constructor make-js2-infix-node (&key type
3206 (pos js2-ts-cursor)
3207 len
3208 op-pos
3209 left
3210 right)))
3211 "Represents infix expressions.
3212 Includes assignment ops like `|=', and the comma operator.
3213 The type field inherited from `js2-node' holds the operator."
3214 op-pos ; buffer position where operator begins
3215 left ; any `js2-node'
3216 right) ; any `js2-node'
3217
3218 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3219 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3220
3221 (defun js2-visit-infix-node (n v)
3222 (js2-visit-ast (js2-infix-node-left n) v)
3223 (js2-visit-ast (js2-infix-node-right n) v))
3224
3225 (defconst js2-operator-tokens
3226 (let ((table (make-hash-table :test 'eq))
3227 (tokens
3228 (list (cons js2-IN "in")
3229 (cons js2-TYPEOF "typeof")
3230 (cons js2-INSTANCEOF "instanceof")
3231 (cons js2-DELPROP "delete")
3232 (cons js2-COMMA ",")
3233 (cons js2-COLON ":")
3234 (cons js2-OR "||")
3235 (cons js2-AND "&&")
3236 (cons js2-INC "++")
3237 (cons js2-DEC "--")
3238 (cons js2-BITOR "|")
3239 (cons js2-BITXOR "^")
3240 (cons js2-BITAND "&")
3241 (cons js2-EQ "==")
3242 (cons js2-NE "!=")
3243 (cons js2-LT "<")
3244 (cons js2-LE "<=")
3245 (cons js2-GT ">")
3246 (cons js2-GE ">=")
3247 (cons js2-LSH "<<")
3248 (cons js2-RSH ">>")
3249 (cons js2-URSH ">>>")
3250 (cons js2-ADD "+") ; infix plus
3251 (cons js2-SUB "-") ; infix minus
3252 (cons js2-MUL "*")
3253 (cons js2-DIV "/")
3254 (cons js2-MOD "%")
3255 (cons js2-NOT "!")
3256 (cons js2-BITNOT "~")
3257 (cons js2-POS "+") ; unary plus
3258 (cons js2-NEG "-") ; unary minus
3259 (cons js2-SHEQ "===") ; shallow equality
3260 (cons js2-SHNE "!==") ; shallow inequality
3261 (cons js2-ASSIGN "=")
3262 (cons js2-ASSIGN_BITOR "|=")
3263 (cons js2-ASSIGN_BITXOR "^=")
3264 (cons js2-ASSIGN_BITAND "&=")
3265 (cons js2-ASSIGN_LSH "<<=")
3266 (cons js2-ASSIGN_RSH ">>=")
3267 (cons js2-ASSIGN_URSH ">>>=")
3268 (cons js2-ASSIGN_ADD "+=")
3269 (cons js2-ASSIGN_SUB "-=")
3270 (cons js2-ASSIGN_MUL "*=")
3271 (cons js2-ASSIGN_DIV "/=")
3272 (cons js2-ASSIGN_MOD "%="))))
3273 (loop for (k . v) in tokens do
3274 (puthash k v table))
3275 table))
3276
3277 (defun js2-print-infix-node (n i)
3278 (let* ((tt (js2-node-type n))
3279 (op (gethash tt js2-operator-tokens)))
3280 (unless op
3281 (error "unrecognized infix operator %s" (js2-node-type n)))
3282 (insert (js2-make-pad i))
3283 (js2-print-ast (js2-infix-node-left n) 0)
3284 (unless (= tt js2-COMMA)
3285 (insert " "))
3286 (insert op)
3287 (insert " ")
3288 (js2-print-ast (js2-infix-node-right n) 0)))
3289
3290 (defstruct (js2-assign-node
3291 (:include js2-infix-node)
3292 (:constructor nil)
3293 (:constructor make-js2-assign-node (&key type
3294 (pos js2-ts-cursor)
3295 len
3296 op-pos
3297 left
3298 right)))
3299 "Represents any assignment.
3300 The type field holds the actual assignment operator.")
3301
3302 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3303 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3304
3305 (defstruct (js2-unary-node
3306 (:include js2-node)
3307 (:constructor nil)
3308 (:constructor make-js2-unary-node (&key type ; required
3309 (pos js2-ts-cursor)
3310 len
3311 operand)))
3312 "AST node type for unary operator nodes.
3313 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3314 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3315 property is added if the operator follows the operand."
3316 operand) ; a `js2-node' expression
3317
3318 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3319 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3320
3321 (defun js2-visit-unary-node (n v)
3322 (js2-visit-ast (js2-unary-node-operand n) v))
3323
3324 (defun js2-print-unary-node (n i)
3325 (let* ((tt (js2-node-type n))
3326 (op (gethash tt js2-operator-tokens))
3327 (postfix (js2-node-get-prop n 'postfix)))
3328 (unless op
3329 (error "unrecognized unary operator %s" tt))
3330 (insert (js2-make-pad i))
3331 (unless postfix
3332 (insert op))
3333 (if (or (= tt js2-TYPEOF)
3334 (= tt js2-DELPROP))
3335 (insert " "))
3336 (js2-print-ast (js2-unary-node-operand n) 0)
3337 (when postfix
3338 (insert op))))
3339
3340 (defstruct (js2-let-node
3341 (:include js2-scope)
3342 (:constructor nil)
3343 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3344 (pos js2-token-beg)
3345 len
3346 vars
3347 body
3348 lp
3349 rp)))
3350 "AST node for a let expression or a let statement.
3351 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3352 vars ; a `js2-var-decl-node'
3353 body ; a `js2-node' representing the expression or body block
3354 lp
3355 rp)
3356
3357 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3358 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3359
3360 (defun js2-visit-let-node (n v)
3361 (js2-visit-ast (js2-let-node-vars n) v)
3362 (js2-visit-ast (js2-let-node-body n) v))
3363
3364 (defun js2-print-let-node (n i)
3365 (insert (js2-make-pad i) "let (")
3366 (js2-print-ast (js2-let-node-vars n) 0)
3367 (insert ") ")
3368 (js2-print-ast (js2-let-node-body n) i))
3369
3370 (defstruct (js2-keyword-node
3371 (:include js2-node)
3372 (:constructor nil)
3373 (:constructor make-js2-keyword-node (&key type
3374 (pos js2-token-beg)
3375 (len (- js2-ts-cursor pos)))))
3376 "AST node representing a literal keyword such as `null'.
3377 Used for `null', `this', `true', `false' and `debugger'.
3378 The node type is set to js2-NULL, js2-THIS, etc.")
3379
3380 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3381 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3382
3383 (defun js2-print-keyword-node (n i)
3384 (insert (js2-make-pad i)
3385 (let ((tt (js2-node-type n)))
3386 (cond
3387 ((= tt js2-THIS) "this")
3388 ((= tt js2-NULL) "null")
3389 ((= tt js2-TRUE) "true")
3390 ((= tt js2-FALSE) "false")
3391 ((= tt js2-DEBUGGER) "debugger")
3392 (t (error "Invalid keyword literal type: %d" tt))))))
3393
3394 (defsubst js2-this-node-p (node)
3395 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3396 (eq (js2-node-type node) js2-THIS))
3397
3398 (defstruct (js2-new-node
3399 (:include js2-node)
3400 (:constructor nil)
3401 (:constructor make-js2-new-node (&key (type js2-NEW)
3402 (pos js2-token-beg)
3403 len
3404 target
3405 args
3406 initializer
3407 lp
3408 rp)))
3409 "AST node for new-expression such as new Foo()."
3410 target ; an identifier or reference
3411 args ; a lisp list of argument nodes
3412 lp ; position of left-paren, nil if omitted
3413 rp ; position of right-paren, nil if omitted
3414 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3415
3416 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3417 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3418
3419 (defun js2-visit-new-node (n v)
3420 (js2-visit-ast (js2-new-node-target n) v)
3421 (dolist (arg (js2-new-node-args n))
3422 (js2-visit-ast arg v))
3423 (js2-visit-ast (js2-new-node-initializer n) v))
3424
3425 (defun js2-print-new-node (n i)
3426 (insert (js2-make-pad i) "new ")
3427 (js2-print-ast (js2-new-node-target n))
3428 (insert "(")
3429 (js2-print-list (js2-new-node-args n))
3430 (insert ")")
3431 (when (js2-new-node-initializer n)
3432 (insert " ")
3433 (js2-print-ast (js2-new-node-initializer n))))
3434
3435 (defstruct (js2-name-node
3436 (:include js2-node)
3437 (:constructor nil)
3438 (:constructor make-js2-name-node (&key (type js2-NAME)
3439 (pos js2-token-beg)
3440 (len (- js2-ts-cursor
3441 js2-token-beg))
3442 (name js2-ts-string))))
3443 "AST node for a JavaScript identifier"
3444 name ; a string
3445 scope) ; a `js2-scope' (optional, used for codegen)
3446
3447 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3448 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3449
3450 (defun js2-print-name-node (n i)
3451 (insert (js2-make-pad i)
3452 (js2-name-node-name n)))
3453
3454 (defsubst js2-name-node-length (node)
3455 "Return identifier length of NODE, a `js2-name-node'.
3456 Returns 0 if NODE is nil or its identifier field is nil."
3457 (if node
3458 (length (js2-name-node-name node))
3459 0))
3460
3461 (defstruct (js2-number-node
3462 (:include js2-node)
3463 (:constructor nil)
3464 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3465 (pos js2-token-beg)
3466 (len (- js2-ts-cursor
3467 js2-token-beg))
3468 (value js2-ts-string)
3469 (num-value js2-ts-number))))
3470 "AST node for a number literal."
3471 value ; the original string, e.g. "6.02e23"
3472 num-value) ; the parsed number value
3473
3474 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3475 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3476
3477 (defun js2-print-number-node (n i)
3478 (insert (js2-make-pad i)
3479 (number-to-string (js2-number-node-num-value n))))
3480
3481 (defstruct (js2-regexp-node
3482 (:include js2-node)
3483 (:constructor nil)
3484 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3485 (pos js2-token-beg)
3486 (len (- js2-ts-cursor
3487 js2-token-beg))
3488 value
3489 flags)))
3490 "AST node for a regular expression literal."
3491 value ; the regexp string, without // delimiters
3492 flags) ; a string of flags, e.g. `mi'.
3493
3494 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3495 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3496
3497 (defun js2-print-regexp (n i)
3498 (insert (js2-make-pad i)
3499 "/"
3500 (js2-regexp-node-value n)
3501 "/")
3502 (if (js2-regexp-node-flags n)
3503 (insert (js2-regexp-node-flags n))))
3504
3505 (defstruct (js2-string-node
3506 (:include js2-node)
3507 (:constructor nil)
3508 (:constructor make-js2-string-node (&key (type js2-STRING)
3509 (pos js2-token-beg)
3510 (len (- js2-ts-cursor
3511 js2-token-beg))
3512 (value js2-ts-string))))
3513 "String literal.
3514 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3515 You can tell the quote type by looking at the first character."
3516 value) ; the characters of the string, including the quotes
3517
3518 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3519 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3520
3521 (defun js2-print-string-node (n i)
3522 (insert (js2-make-pad i)
3523 (js2-node-string n)))
3524
3525 (defstruct (js2-array-node
3526 (:include js2-node)
3527 (:constructor nil)
3528 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3529 (pos js2-ts-cursor)
3530 len
3531 elems)))
3532 "AST node for an array literal."
3533 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3534
3535 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3536 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3537
3538 (defun js2-visit-array-node (n v)
3539 (dolist (e (js2-array-node-elems n))
3540 (js2-visit-ast e v)))
3541
3542 (defun js2-print-array-node (n i)
3543 (insert (js2-make-pad i) "[")
3544 (js2-print-list (js2-array-node-elems n))
3545 (insert "]"))
3546
3547 (defstruct (js2-object-node
3548 (:include js2-node)
3549 (:constructor nil)
3550 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3551 (pos js2-ts-cursor)
3552 len
3553 elems)))
3554 "AST node for an object literal expression.
3555 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3556 the latter represents abbreviation in destructuring expressions."
3557 elems)
3558
3559 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3560 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3561
3562 (defun js2-visit-object-node (n v)
3563 (dolist (e (js2-object-node-elems n))
3564 (js2-visit-ast e v)))
3565
3566 (defun js2-print-object-node (n i)
3567 (insert (js2-make-pad i) "{")
3568 (js2-print-list (js2-object-node-elems n))
3569 (insert "}"))
3570
3571 (defstruct (js2-object-prop-node
3572 (:include js2-infix-node)
3573 (:constructor nil)
3574 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3575 (pos js2-ts-cursor)
3576 len
3577 left
3578 right
3579 op-pos)))
3580 "AST node for an object literal prop:value entry.
3581 The `left' field is the property: a name node, string node or number node.
3582 The `right' field is a `js2-node' representing the initializer value.")
3583
3584 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3585 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3586
3587 (defun js2-print-object-prop-node (n i)
3588 (insert (js2-make-pad i))
3589 (js2-print-ast (js2-object-prop-node-left n) 0)
3590 (insert ":")
3591 (js2-print-ast (js2-object-prop-node-right n) 0))
3592
3593 (defstruct (js2-getter-setter-node
3594 (:include js2-infix-node)
3595 (:constructor nil)
3596 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3597 (pos js2-ts-cursor)
3598 len
3599 left
3600 right)))
3601 "AST node for a getter/setter property in an object literal.
3602 The `left' field is the `js2-name-node' naming the getter/setter prop.
3603 The `right' field is always an anonymous `js2-function-node' with a node
3604 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3605
3606 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3607 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3608
3609 (defun js2-print-getter-setter (n i)
3610 (let ((pad (js2-make-pad i))
3611 (left (js2-getter-setter-node-left n))
3612 (right (js2-getter-setter-node-right n)))
3613 (insert pad)
3614 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3615 (js2-print-ast left 0)
3616 (js2-print-ast right 0)))
3617
3618 (defstruct (js2-prop-get-node
3619 (:include js2-infix-node)
3620 (:constructor nil)
3621 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3622 (pos js2-ts-cursor)
3623 len
3624 left
3625 right)))
3626 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3627
3628 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3629 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3630
3631 (defun js2-visit-prop-get-node (n v)
3632 (js2-visit-ast (js2-prop-get-node-left n) v)
3633 (js2-visit-ast (js2-prop-get-node-right n) v))
3634
3635 (defun js2-print-prop-get-node (n i)
3636 (insert (js2-make-pad i))
3637 (js2-print-ast (js2-prop-get-node-left n) 0)
3638 (insert ".")
3639 (js2-print-ast (js2-prop-get-node-right n) 0))
3640
3641 (defstruct (js2-elem-get-node
3642 (:include js2-node)
3643 (:constructor nil)
3644 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3645 (pos js2-ts-cursor)
3646 len
3647 target
3648 element
3649 lb
3650 rb)))
3651 "AST node for an array index expression such as foo[bar]."
3652 target ; a `js2-node' - the expression preceding the "."
3653 element ; a `js2-node' - the expression in brackets
3654 lb ; position of left-bracket, nil if omitted
3655 rb) ; position of right-bracket, nil if omitted
3656
3657 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3658 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3659
3660 (defun js2-visit-elem-get-node (n v)
3661 (js2-visit-ast (js2-elem-get-node-target n) v)
3662 (js2-visit-ast (js2-elem-get-node-element n) v))
3663
3664 (defun js2-print-elem-get-node (n i)
3665 (insert (js2-make-pad i))
3666 (js2-print-ast (js2-elem-get-node-target n) 0)
3667 (insert "[")
3668 (js2-print-ast (js2-elem-get-node-element n) 0)
3669 (insert "]"))
3670
3671 (defstruct (js2-call-node
3672 (:include js2-node)
3673 (:constructor nil)
3674 (:constructor make-js2-call-node (&key (type js2-CALL)
3675 (pos js2-ts-cursor)
3676 len
3677 target
3678 args
3679 lp
3680 rp)))
3681 "AST node for a JavaScript function call."
3682 target ; a `js2-node' evaluating to the function to call
3683 args ; a lisp list of `js2-node' arguments
3684 lp ; position of open-paren, or nil if missing
3685 rp) ; position of close-paren, or nil if missing
3686
3687 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3688 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3689
3690 (defun js2-visit-call-node (n v)
3691 (js2-visit-ast (js2-call-node-target n) v)
3692 (dolist (arg (js2-call-node-args n))
3693 (js2-visit-ast arg v)))
3694
3695 (defun js2-print-call-node (n i)
3696 (insert (js2-make-pad i))
3697 (js2-print-ast (js2-call-node-target n) 0)
3698 (insert "(")
3699 (js2-print-list (js2-call-node-args n))
3700 (insert ")"))
3701
3702 (defstruct (js2-yield-node
3703 (:include js2-node)
3704 (:constructor nil)
3705 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3706 (pos js2-ts-cursor)
3707 len
3708 value)))
3709 "AST node for yield statement or expression."
3710 value) ; optional: value to be yielded
3711
3712 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3713 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3714
3715 (defun js2-visit-yield-node (n v)
3716 (js2-visit-ast (js2-yield-node-value n) v))
3717
3718 (defun js2-print-yield-node (n i)
3719 (insert (js2-make-pad i))
3720 (insert "yield")
3721 (when (js2-yield-node-value n)
3722 (insert " ")
3723 (js2-print-ast (js2-yield-node-value n) 0)))
3724
3725 (defstruct (js2-paren-node
3726 (:include js2-node)
3727 (:constructor nil)
3728 (:constructor make-js2-paren-node (&key (type js2-LP)
3729 (pos js2-ts-cursor)
3730 len
3731 expr)))
3732 "AST node for a parenthesized expression.
3733 In particular, used when the parens are syntactically optional,
3734 as opposed to required parens such as those enclosing an if-conditional."
3735 expr) ; `js2-node'
3736
3737 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3738 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3739
3740 (defun js2-visit-paren-node (n v)
3741 (js2-visit-ast (js2-paren-node-expr n) v))
3742
3743 (defun js2-print-paren-node (n i)
3744 (insert (js2-make-pad i))
3745 (insert "(")
3746 (js2-print-ast (js2-paren-node-expr n) 0)
3747 (insert ")"))
3748
3749 (defstruct (js2-array-comp-node
3750 (:include js2-scope)
3751 (:constructor nil)
3752 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3753 (pos js2-ts-cursor)
3754 len
3755 result
3756 loops
3757 filter
3758 if-pos
3759 lp
3760 rp)))
3761 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3762 result ; result expression (just after left-bracket)
3763 loops ; a lisp list of `js2-array-comp-loop-node'
3764 filter ; guard/filter expression
3765 if-pos ; buffer pos of 'if' keyword, if present, else nil
3766 lp ; buffer position of if-guard left-paren, or nil if not present
3767 rp) ; buffer position of if-guard right-paren, or nil if not present
3768
3769 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3770 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3771
3772 (defun js2-visit-array-comp-node (n v)
3773 (js2-visit-ast (js2-array-comp-node-result n) v)
3774 (dolist (l (js2-array-comp-node-loops n))
3775 (js2-visit-ast l v))
3776 (js2-visit-ast (js2-array-comp-node-filter n) v))
3777
3778 (defun js2-print-array-comp-node (n i)
3779 (let ((pad (js2-make-pad i))
3780 (result (js2-array-comp-node-result n))
3781 (loops (js2-array-comp-node-loops n))
3782 (filter (js2-array-comp-node-filter n)))
3783 (insert pad "[")
3784 (js2-print-ast result 0)
3785 (dolist (l loops)
3786 (insert " ")
3787 (js2-print-ast l 0))
3788 (when filter
3789 (insert " if (")
3790 (js2-print-ast filter 0))
3791 (insert ")]")))
3792
3793 (defstruct (js2-array-comp-loop-node
3794 (:include js2-for-in-node)
3795 (:constructor nil)
3796 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3797 (pos js2-ts-cursor)
3798 len
3799 iterator
3800 object
3801 in-pos
3802 foreach-p
3803 each-pos
3804 lp
3805 rp)))
3806 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3807
3808 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3809 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3810
3811 (defun js2-visit-array-comp-loop (n v)
3812 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3813 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3814
3815 (defun js2-print-array-comp-loop (n i)
3816 (insert "for (")
3817 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3818 (insert " in ")
3819 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3820 (insert ")"))
3821
3822 (defstruct (js2-empty-expr-node
3823 (:include js2-node)
3824 (:constructor nil)
3825 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3826 (pos js2-token-beg)
3827 len)))
3828 "AST node for an empty expression.")
3829
3830 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3831 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3832
3833 (defstruct (js2-xml-node
3834 (:include js2-block-node)
3835 (:constructor nil)
3836 (:constructor make-js2-xml-node (&key (type js2-XML)
3837 (pos js2-token-beg)
3838 len
3839 kids)))
3840 "AST node for initial parse of E4X literals.
3841 The kids field is a list of XML fragments, each a `js2-string-node' or
3842 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3843
3844 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3845 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3846
3847 (defun js2-print-xml-node (n i)
3848 (dolist (kid (js2-xml-node-kids n))
3849 (js2-print-ast kid i)))
3850
3851 (defstruct (js2-xml-js-expr-node
3852 (:include js2-xml-node)
3853 (:constructor nil)
3854 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3855 (pos js2-ts-cursor)
3856 len
3857 expr)))
3858 "AST node for an embedded JavaScript {expression} in an E4X literal.
3859 The start and end fields correspond to the curly-braces."
3860 expr) ; a `js2-expr-node' of some sort
3861
3862 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3863 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3864
3865 (defun js2-visit-xml-js-expr (n v)
3866 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3867
3868 (defun js2-print-xml-js-expr (n i)
3869 (insert (js2-make-pad i))
3870 (insert "{")
3871 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3872 (insert "}"))
3873
3874 (defstruct (js2-xml-dot-query-node
3875 (:include js2-infix-node)
3876 (:constructor nil)
3877 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3878 (pos js2-ts-cursor)
3879 op-pos
3880 len
3881 left
3882 right
3883 rp)))
3884 "AST node for an E4X foo.(bar) filter expression.
3885 Note that the left-paren is automatically the character immediately
3886 following the dot (.) in the operator. No whitespace is permitted
3887 between the dot and the lp by the scanner."
3888 rp)
3889
3890 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3891 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3892
3893 (defun js2-print-xml-dot-query (n i)
3894 (insert (js2-make-pad i))
3895 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3896 (insert ".(")
3897 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3898 (insert ")"))
3899
3900 (defstruct (js2-xml-ref-node
3901 (:include js2-node)
3902 (:constructor nil)) ; abstract
3903 "Base type for E4X XML attribute-access or property-get expressions.
3904 Such expressions can take a variety of forms. The general syntax has
3905 three parts:
3906
3907 - (optional) an @ (specifying an attribute access)
3908 - (optional) a namespace (a `js2-name-node') and double-colon
3909 - (required) either a `js2-name-node' or a bracketed [expression]
3910
3911 The property-name expressions (examples: ns::name, @name) are
3912 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3913 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3914
3915 This node type (or more specifically, its subclasses) will sometimes
3916 be the right-hand child of a `js2-prop-get-node' or a
3917 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3918 The `js2-xml-ref-node' may also be a standalone primary expression with
3919 no explicit target, which is valid in certain expression contexts such as
3920
3921 company..employee.(@id < 100)
3922
3923 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3924 expression whose parent is a `js2-xml-dot-query-node'."
3925 namespace
3926 at-pos
3927 colon-pos)
3928
3929 (defsubst js2-xml-ref-node-attr-access-p (node)
3930 "Return non-nil if this expression began with an @-token."
3931 (and (numberp (js2-xml-ref-node-at-pos node))
3932 (plusp (js2-xml-ref-node-at-pos node))))
3933
3934 (defstruct (js2-xml-prop-ref-node
3935 (:include js2-xml-ref-node)
3936 (:constructor nil)
3937 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3938 (pos js2-token-beg)
3939 len
3940 propname
3941 namespace
3942 at-pos
3943 colon-pos)))
3944 "AST node for an E4X XML [expr] property-ref expression.
3945 The JavaScript syntax is an optional @, an optional ns::, and a name.
3946
3947 [ '@' ] [ name '::' ] name
3948
3949 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3950 @ns::*, @*::attr, @*::*, and @*.
3951
3952 The node starts at the @ token, if present. Otherwise it starts at the
3953 namespace name. The node bounds extend through the closing right-bracket,
3954 or if it is missing due to a syntax error, through the end of the index
3955 expression."
3956 propname)
3957
3958 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3959 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3960
3961 (defun js2-visit-xml-prop-ref-node (n v)
3962 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3963 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3964
3965 (defun js2-print-xml-prop-ref-node (n i)
3966 (insert (js2-make-pad i))
3967 (if (js2-xml-ref-node-attr-access-p n)
3968 (insert "@"))
3969 (when (js2-xml-prop-ref-node-namespace n)
3970 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3971 (insert "::"))
3972 (if (js2-xml-prop-ref-node-propname n)
3973 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3974
3975 (defstruct (js2-xml-elem-ref-node
3976 (:include js2-xml-ref-node)
3977 (:constructor nil)
3978 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3979 (pos js2-token-beg)
3980 len
3981 expr
3982 lb
3983 rb
3984 namespace
3985 at-pos
3986 colon-pos)))
3987 "AST node for an E4X XML [expr] member-ref expression.
3988 Syntax:
3989
3990 [ '@' ] [ name '::' ] '[' expr ']'
3991
3992 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3993
3994 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3995 is not a legal E4X XML element-ref expression, since it's already used
3996 for standard JavaScript element-get array indexing. Hence, a
3997 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3998 non-nil namespace node, or both.
3999
4000 The node starts at the @ token, if present. Otherwise it starts
4001 at the namespace name. The node bounds extend through the closing
4002 right-bracket, or if it is missing due to a syntax error, through the
4003 end of the index expression."
4004 expr ; the bracketed index expression
4005 lb
4006 rb)
4007
4008 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4009 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4010
4011 (defun js2-visit-xml-elem-ref-node (n v)
4012 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4013 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4014
4015 (defun js2-print-xml-elem-ref-node (n i)
4016 (insert (js2-make-pad i))
4017 (if (js2-xml-ref-node-attr-access-p n)
4018 (insert "@"))
4019 (when (js2-xml-elem-ref-node-namespace n)
4020 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4021 (insert "::"))
4022 (insert "[")
4023 (if (js2-xml-elem-ref-node-expr n)
4024 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4025 (insert "]"))
4026
4027 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4028
4029 (defstruct (js2-xml-start-tag-node
4030 (:include js2-xml-node)
4031 (:constructor nil)
4032 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4033 (pos js2-ts-cursor)
4034 len
4035 name
4036 attrs
4037 kids
4038 empty-p)))
4039 "AST node for an XML start-tag. Not currently used.
4040 The `kids' field is a lisp list of child content nodes."
4041 name ; a `js2-xml-name-node'
4042 attrs ; a lisp list of `js2-xml-attr-node'
4043 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4044
4045 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4046 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4047
4048 (defun js2-visit-xml-start-tag (n v)
4049 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4050 (dolist (attr (js2-xml-start-tag-node-attrs n))
4051 (js2-visit-ast attr v))
4052 (js2-visit-block n v))
4053
4054 (defun js2-print-xml-start-tag (n i)
4055 (insert (js2-make-pad i) "<")
4056 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4057 (when (js2-xml-start-tag-node-attrs n)
4058 (insert " ")
4059 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4060 (insert ">"))
4061
4062 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4063 ;; and add the end-tag to the kids list of the parent as well.
4064 (defstruct (js2-xml-end-tag-node
4065 (:include js2-xml-node)
4066 (:constructor nil)
4067 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4068 (pos js2-ts-cursor)
4069 len
4070 name)))
4071 "AST node for an XML end-tag. Not currently used."
4072 name) ; a `js2-xml-name-node'
4073
4074 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4075 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4076
4077 (defun js2-visit-xml-end-tag (n v)
4078 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4079
4080 (defun js2-print-xml-end-tag (n i)
4081 (insert (js2-make-pad i))
4082 (insert "</")
4083 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4084 (insert ">"))
4085
4086 (defstruct (js2-xml-name-node
4087 (:include js2-xml-node)
4088 (:constructor nil)
4089 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4090 (pos js2-ts-cursor)
4091 len
4092 namespace
4093 kids)))
4094 "AST node for an E4X XML name. Not currently used.
4095 Any XML name can be qualified with a namespace, hence the namespace field.
4096 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4097 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4098 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4099 namespace) ; a `js2-string-node'
4100
4101 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4102 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4103
4104 (defun js2-visit-xml-name-node (n v)
4105 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4106
4107 (defun js2-print-xml-name-node (n i)
4108 (insert (js2-make-pad i))
4109 (when (js2-xml-name-node-namespace n)
4110 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4111 (insert "::"))
4112 (dolist (kid (js2-xml-name-node-kids n))
4113 (js2-print-ast kid 0)))
4114
4115 (defstruct (js2-xml-pi-node
4116 (:include js2-xml-node)
4117 (:constructor nil)
4118 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4119 (pos js2-ts-cursor)
4120 len
4121 name
4122 attrs)))
4123 "AST node for an E4X XML processing instruction. Not currently used."
4124 name ; a `js2-xml-name-node'
4125 attrs) ; a list of `js2-xml-attr-node'
4126
4127 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4128 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4129
4130 (defun js2-visit-xml-pi-node (n v)
4131 (js2-visit-ast (js2-xml-pi-node-name n) v)
4132 (dolist (attr (js2-xml-pi-node-attrs n))
4133 (js2-visit-ast attr v)))
4134
4135 (defun js2-print-xml-pi-node (n i)
4136 (insert (js2-make-pad i) "<?")
4137 (js2-print-ast (js2-xml-pi-node-name n))
4138 (when (js2-xml-pi-node-attrs n)
4139 (insert " ")
4140 (js2-print-list (js2-xml-pi-node-attrs n)))
4141 (insert "?>"))
4142
4143 (defstruct (js2-xml-cdata-node
4144 (:include js2-xml-node)
4145 (:constructor nil)
4146 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4147 (pos js2-ts-cursor)
4148 len
4149 content)))
4150 "AST node for a CDATA escape section. Not currently used."
4151 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4152
4153 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4154 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4155
4156 (defun js2-visit-xml-cdata-node (n v)
4157 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4158
4159 (defun js2-print-xml-cdata-node (n i)
4160 (insert (js2-make-pad i))
4161 (js2-print-ast (js2-xml-cdata-node-content n)))
4162
4163 (defstruct (js2-xml-attr-node
4164 (:include js2-xml-node)
4165 (:constructor nil)
4166 (:constructor make-js2-attr-node (&key (type js2-XML)
4167 (pos js2-ts-cursor)
4168 len
4169 name
4170 value
4171 eq-pos
4172 quote-type)))
4173 "AST node representing a foo='bar' XML attribute value. Not yet used."
4174 name ; a `js2-xml-name-node'
4175 value ; a `js2-xml-name-node'
4176 eq-pos ; buffer position of "=" sign
4177 quote-type) ; 'single or 'double
4178
4179 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4180 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4181
4182 (defun js2-visit-xml-attr-node (n v)
4183 (js2-visit-ast (js2-xml-attr-node-name n) v)
4184 (js2-visit-ast (js2-xml-attr-node-value n) v))
4185
4186 (defun js2-print-xml-attr-node (n i)
4187 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4188 "'"
4189 "\"")))
4190 (insert (js2-make-pad i))
4191 (js2-print-ast (js2-xml-attr-node-name n) 0)
4192 (insert "=" quote)
4193 (js2-print-ast (js2-xml-attr-node-value n) 0)
4194 (insert quote)))
4195
4196 (defstruct (js2-xml-text-node
4197 (:include js2-xml-node)
4198 (:constructor nil)
4199 (:constructor make-js2-text-node (&key (type js2-XML)
4200 (pos js2-ts-cursor)
4201 len
4202 content)))
4203 "AST node for an E4X XML text node. Not currently used."
4204 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4205
4206 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4207 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4208
4209 (defun js2-visit-xml-text-node (n v)
4210 (js2-visit-ast (js2-xml-text-node-content n) v))
4211
4212 (defun js2-print-xml-text-node (n i)
4213 (insert (js2-make-pad i))
4214 (dolist (kid (js2-xml-text-node-content n))
4215 (js2-print-ast kid)))
4216
4217 (defstruct (js2-xml-comment-node
4218 (:include js2-xml-node)
4219 (:constructor nil)
4220 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4221 (pos js2-ts-cursor)
4222 len)))
4223 "AST node for E4X XML comment. Not currently used.")
4224
4225 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4226 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4227
4228 (defun js2-print-xml-comment (n i)
4229 (insert (js2-make-pad i)
4230 (js2-node-string n)))
4231
4232 ;;; Node utilities
4233
4234 (defsubst js2-node-line (n)
4235 "Fetch the source line number at the start of node N.
4236 This is O(n) in the length of the source buffer; use prudently."
4237 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4238
4239 (defsubst js2-block-node-kid (n i)
4240 "Return child I of node N, or nil if there aren't that many."
4241 (nth i (js2-block-node-kids n)))
4242
4243 (defsubst js2-block-node-first (n)
4244 "Return first child of block node N, or nil if there is none."
4245 (first (js2-block-node-kids n)))
4246
4247 (defun js2-node-root (n)
4248 "Return the root of the AST containing N.
4249 If N has no parent pointer, returns N."
4250 (let ((parent (js2-node-parent n)))
4251 (if parent
4252 (js2-node-root parent)
4253 n)))
4254
4255 (defun js2-node-position-in-parent (node &optional parent)
4256 "Return the position of NODE in parent's block-kids list.
4257 PARENT can be supplied if known. Positioned returned is zero-indexed.
4258 Returns 0 if NODE is not a child of a block statement, or if NODE
4259 is not a statement node."
4260 (let ((p (or parent (js2-node-parent node)))
4261 (i 0))
4262 (if (not (js2-block-node-p p))
4263 i
4264 (or (js2-position node (js2-block-node-kids p))
4265 0))))
4266
4267 (defsubst js2-node-short-name (n)
4268 "Return the short name of node N as a string, e.g. `js2-if-node'."
4269 (substring (symbol-name (aref n 0))
4270 (length "cl-struct-")))
4271
4272 (defsubst js2-node-child-list (node)
4273 "Return the child list for NODE, a lisp list of nodes.
4274 Works for block nodes, array nodes, obj literals, funarg lists,
4275 var decls and try nodes (for catch clauses). Note that you should call
4276 `js2-block-node-kids' on the function body for the body statements.
4277 Returns nil for zero-length child lists or unsupported nodes."
4278 (cond
4279 ((js2-function-node-p node)
4280 (js2-function-node-params node))
4281 ((js2-block-node-p node)
4282 (js2-block-node-kids node))
4283 ((js2-try-node-p node)
4284 (js2-try-node-catch-clauses node))
4285 ((js2-array-node-p node)
4286 (js2-array-node-elems node))
4287 ((js2-object-node-p node)
4288 (js2-object-node-elems node))
4289 ((js2-call-node-p node)
4290 (js2-call-node-args node))
4291 ((js2-new-node-p node)
4292 (js2-new-node-args node))
4293 ((js2-var-decl-node-p node)
4294 (js2-var-decl-node-kids node))
4295 (t
4296 nil)))
4297
4298 (defsubst js2-node-set-child-list (node kids)
4299 "Set the child list for NODE to KIDS."
4300 (cond
4301 ((js2-function-node-p node)
4302 (setf (js2-function-node-params node) kids))
4303 ((js2-block-node-p node)
4304 (setf (js2-block-node-kids node) kids))
4305 ((js2-try-node-p node)
4306 (setf (js2-try-node-catch-clauses node) kids))
4307 ((js2-array-node-p node)
4308 (setf (js2-array-node-elems node) kids))
4309 ((js2-object-node-p node)
4310 (setf (js2-object-node-elems node) kids))
4311 ((js2-call-node-p node)
4312 (setf (js2-call-node-args node) kids))
4313 ((js2-new-node-p node)
4314 (setf (js2-new-node-args node) kids))
4315 ((js2-var-decl-node-p node)
4316 (setf (js2-var-decl-node-kids node) kids))
4317 (t
4318 (error "Unsupported node type: %s" (js2-node-short-name node))))
4319 kids)
4320
4321 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4322 (defconst js2-paren-expr-nodes
4323 '(cl-struct-js2-array-comp-loop-node
4324 cl-struct-js2-array-comp-node
4325 cl-struct-js2-call-node
4326 cl-struct-js2-catch-node
4327 cl-struct-js2-do-node
4328 cl-struct-js2-elem-get-node
4329 cl-struct-js2-for-in-node
4330 cl-struct-js2-for-node
4331 cl-struct-js2-function-node
4332 cl-struct-js2-if-node
4333 cl-struct-js2-let-node
4334 cl-struct-js2-new-node
4335 cl-struct-js2-paren-node
4336 cl-struct-js2-switch-node
4337 cl-struct-js2-while-node
4338 cl-struct-js2-with-node
4339 cl-struct-js2-xml-dot-query-node)
4340 "Node types that can have a parenthesized child expression.
4341 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4342
4343 (defsubst js2-paren-expr-node-p (node)
4344 "Return t for nodes that typically have a parenthesized child expression.
4345 Useful for computing the indentation anchors for arg-lists and conditions.
4346 Note that it may return a false positive, for instance when NODE is
4347 a `js2-new-node' and there are no arguments or parentheses."
4348 (memq (aref node 0) js2-paren-expr-nodes))
4349
4350 ;; Fake polymorphism... yech.
4351 (defsubst js2-node-lp (node)
4352 "Return relative left-paren position for NODE, if applicable.
4353 For `js2-elem-get-node' structs, returns left-bracket position.
4354 Note that the position may be nil in the case of a parse error."
4355 (cond
4356 ((js2-elem-get-node-p node)
4357 (js2-elem-get-node-lb node))
4358 ((js2-loop-node-p node)
4359 (js2-loop-node-lp node))
4360 ((js2-function-node-p node)
4361 (js2-function-node-lp node))
4362 ((js2-if-node-p node)
4363 (js2-if-node-lp node))
4364 ((js2-new-node-p node)
4365 (js2-new-node-lp node))
4366 ((js2-call-node-p node)
4367 (js2-call-node-lp node))
4368 ((js2-paren-node-p node)
4369 (js2-node-pos node))
4370 ((js2-switch-node-p node)
4371 (js2-switch-node-lp node))
4372 ((js2-catch-node-p node)
4373 (js2-catch-node-lp node))
4374 ((js2-let-node-p node)
4375 (js2-let-node-lp node))
4376 ((js2-array-comp-node-p node)
4377 (js2-array-comp-node-lp node))
4378 ((js2-with-node-p node)
4379 (js2-with-node-lp node))
4380 ((js2-xml-dot-query-node-p node)
4381 (1+ (js2-infix-node-op-pos node)))
4382 (t
4383 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4384
4385 ;; Fake polymorphism... blech.
4386 (defsubst js2-node-rp (node)
4387 "Return relative right-paren position for NODE, if applicable.
4388 For `js2-elem-get-node' structs, returns right-bracket position.
4389 Note that the position may be nil in the case of a parse error."
4390 (cond
4391 ((js2-elem-get-node-p node)
4392 (js2-elem-get-node-lb node))
4393 ((js2-loop-node-p node)
4394 (js2-loop-node-rp node))
4395 ((js2-function-node-p node)
4396 (js2-function-node-rp node))
4397 ((js2-if-node-p node)
4398 (js2-if-node-rp node))
4399 ((js2-new-node-p node)
4400 (js2-new-node-rp node))
4401 ((js2-call-node-p node)
4402 (js2-call-node-rp node))
4403 ((js2-paren-node-p node)
4404 (+ (js2-node-pos node) (js2-node-len node)))
4405 ((js2-switch-node-p node)
4406 (js2-switch-node-rp node))
4407 ((js2-catch-node-p node)
4408 (js2-catch-node-rp node))
4409 ((js2-let-node-p node)
4410 (js2-let-node-rp node))
4411 ((js2-array-comp-node-p node)
4412 (js2-array-comp-node-rp node))
4413 ((js2-with-node-p node)
4414 (js2-with-node-rp node))
4415 ((js2-xml-dot-query-node-p node)
4416 (1+ (js2-xml-dot-query-node-rp node)))
4417 (t
4418 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4419
4420 (defsubst js2-node-first-child (node)
4421 "Returns the first element of `js2-node-child-list' for NODE."
4422 (car (js2-node-child-list node)))
4423
4424 (defsubst js2-node-last-child (node)
4425 "Returns the last element of `js2-node-last-child' for NODE."
4426 (car (last (js2-node-child-list node))))
4427
4428 (defun js2-node-prev-sibling (node)
4429 "Return the previous statement in parent.
4430 Works for parents supported by `js2-node-child-list'.
4431 Returns nil if NODE is not in the parent, or PARENT is
4432 not a supported node, or if NODE is the first child."
4433 (let* ((p (js2-node-parent node))
4434 (kids (js2-node-child-list p))
4435 (sib (car kids)))
4436 (while (and kids
4437 (not (eq node (cadr kids))))
4438 (setq kids (cdr kids)
4439 sib (car kids)))
4440 sib))
4441
4442 (defun js2-node-next-sibling (node)
4443 "Return the next statement in parent block.
4444 Returns nil if NODE is not in the block, or PARENT is not
4445 a block node, or if NODE is the last statement."
4446 (let* ((p (js2-node-parent node))
4447 (kids (js2-node-child-list p)))
4448 (while (and kids
4449 (not (eq node (car kids))))
4450 (setq kids (cdr kids)))
4451 (cadr kids)))
4452
4453 (defun js2-node-find-child-before (pos parent &optional after)
4454 "Find the last child that starts before POS in parent.
4455 If AFTER is non-nil, returns first child starting after POS.
4456 POS is an absolute buffer position. PARENT is any node
4457 supported by `js2-node-child-list'.
4458 Returns nil if no applicable child is found."
4459 (let ((kids (if (js2-function-node-p parent)
4460 (js2-block-node-kids (js2-function-node-body parent))
4461 (js2-node-child-list parent)))
4462 (beg (if (js2-function-node-p parent)
4463 (js2-node-abs-pos (js2-function-node-body parent))
4464 (js2-node-abs-pos parent)))
4465 kid
4466 result
4467 fn
4468 (continue t))
4469 (setq fn (if after '>= '<))
4470 (while (and kids continue)
4471 (setq kid (car kids))
4472 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4473 (setq result kid
4474 continue (if after nil t))
4475 (setq continue (if after t nil)))
4476 (setq kids (cdr kids)))
4477 result))
4478
4479 (defun js2-node-find-child-after (pos parent)
4480 "Find first child that starts after POS in parent.
4481 POS is an absolute buffer position. PARENT is any node
4482 supported by `js2-node-child-list'.
4483 Returns nil if no applicable child is found."
4484 (js2-node-find-child-before pos parent 'after))
4485
4486 (defun js2-node-replace-child (pos parent new-node)
4487 "Replace node at index POS in PARENT with NEW-NODE.
4488 Only works for parents supported by `js2-node-child-list'."
4489 (let ((kids (js2-node-child-list parent))
4490 (i 0))
4491 (while (< i pos)
4492 (setq kids (cdr kids)
4493 i (1+ i)))
4494 (setcar kids new-node)
4495 (js2-node-add-children parent new-node)))
4496
4497 (defun js2-node-buffer (n)
4498 "Return the buffer associated with AST N.
4499 Returns nil if the buffer is not set as a property on the root
4500 node, or if parent links were not recorded during parsing."
4501 (let ((root (js2-node-root n)))
4502 (and root
4503 (js2-ast-root-p root)
4504 (js2-ast-root-buffer root))))
4505
4506 (defsubst js2-block-node-push (n kid)
4507 "Push js2-node KID onto the end of js2-block-node N's child list.
4508 KID is always added to the -end- of the kids list.
4509 Function also calls `js2-node-add-children' to add the parent link."
4510 (let ((kids (js2-node-child-list n)))
4511 (if kids
4512 (setcdr kids (nconc (cdr kids) (list kid)))
4513 (js2-node-set-child-list n (list kid)))
4514 (js2-node-add-children n kid)))
4515
4516 (defun js2-node-string (node)
4517 (let ((buf (js2-node-buffer node))
4518 pos)
4519 (unless buf
4520 (error "No buffer available for node %s" node))
4521 (with-current-buffer buf
4522 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4523 (+ pos (js2-node-len node))))))
4524
4525 ;; Container for storing the node we're looking for in a traversal.
4526 (js2-deflocal js2-discovered-node nil)
4527
4528 ;; Keep track of absolute node position during traversals.
4529 (js2-deflocal js2-visitor-offset nil)
4530
4531 (js2-deflocal js2-node-search-point nil)
4532
4533 (when js2-mode-dev-mode-p
4534 (defun js2-find-node-at-point ()
4535 (interactive)
4536 (let ((node (js2-node-at-point)))
4537 (message "%s" (or node "No node found at point"))))
4538 (defun js2-node-name-at-point ()
4539 (interactive)
4540 (let ((node (js2-node-at-point)))
4541 (message "%s" (if node
4542 (js2-node-short-name node)
4543 "No node found at point.")))))
4544
4545 (defun js2-node-at-point (&optional pos skip-comments)
4546 "Return AST node at POS, a buffer position, defaulting to current point.
4547 The `js2-mode-ast' variable must be set to the current parse tree.
4548 Signals an error if the AST (`js2-mode-ast') is nil.
4549 Always returns a node - if it can't find one, it returns the root.
4550 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4551 (let ((ast js2-mode-ast)
4552 result)
4553 (unless ast
4554 (error "No JavaScript AST available"))
4555 ;; Look through comments first, since they may be inside nodes that
4556 ;; would otherwise report a match.
4557 (setq pos (or pos (point))
4558 result (if (> pos (js2-node-abs-end ast))
4559 ast
4560 (if (not skip-comments)
4561 (js2-comment-at-point pos))))
4562 (unless result
4563 (setq js2-discovered-node nil
4564 js2-visitor-offset 0
4565 js2-node-search-point pos)
4566 (unwind-protect
4567 (catch 'js2-visit-done
4568 (js2-visit-ast ast #'js2-node-at-point-visitor))
4569 (setq js2-visitor-offset nil
4570 js2-node-search-point nil))
4571 (setq result js2-discovered-node))
4572 ;; may have found a comment beyond end of last child node,
4573 ;; since visiting the ast-root looks at the comment-list last.
4574 (if (and skip-comments
4575 (js2-comment-node-p result))
4576 (setq result nil))
4577 (or result js2-mode-ast)))
4578
4579 (defun js2-node-at-point-visitor (node end-p)
4580 (let ((rel-pos (js2-node-pos node))
4581 abs-pos
4582 abs-end
4583 (point js2-node-search-point))
4584 (cond
4585 (end-p
4586 ;; this evaluates to a non-nil return value, even if it's zero
4587 (decf js2-visitor-offset rel-pos))
4588 ;; we already looked for comments before visiting, and don't want them now
4589 ((js2-comment-node-p node)
4590 nil)
4591 (t
4592 (setq abs-pos (incf js2-visitor-offset rel-pos)
4593 ;; we only want to use the node if the point is before
4594 ;; the last character position in the node, so we decrement
4595 ;; the absolute end by 1.
4596 abs-end (+ abs-pos (js2-node-len node) -1))
4597 (cond
4598 ;; If this node starts after search-point, stop the search.
4599 ((> abs-pos point)
4600 (throw 'js2-visit-done nil))
4601 ;; If this node ends before the search-point, don't check kids.
4602 ((> point abs-end)
4603 nil)
4604 (t
4605 ;; Otherwise point is within this node, possibly in a child.
4606 (setq js2-discovered-node node)
4607 t)))))) ; keep processing kids to look for more specific match
4608
4609 (defsubst js2-block-comment-p (node)
4610 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4611 (and (js2-comment-node-p node)
4612 (memq (js2-comment-node-format node) '(jsdoc block))))
4613
4614 ;; TODO: put the comments in a vector and binary-search them instead
4615 (defun js2-comment-at-point (&optional pos)
4616 "Look through scanned comment nodes for one containing POS.
4617 POS is a buffer position that defaults to current point.
4618 Function returns nil if POS was not in any comment node."
4619 (let ((ast js2-mode-ast)
4620 (x (or pos (point)))
4621 beg
4622 end)
4623 (unless ast
4624 (error "No JavaScript AST available"))
4625 (catch 'done
4626 ;; Comments are stored in lexical order.
4627 (dolist (comment (js2-ast-root-comments ast) nil)
4628 (setq beg (js2-node-abs-pos comment)
4629 end (+ beg (js2-node-len comment)))
4630 (if (and (>= x beg)
4631 (<= x end))
4632 (throw 'done comment))))))
4633
4634 (defun js2-mode-find-parent-fn (node)
4635 "Find function enclosing NODE.
4636 Returns nil if NODE is not inside a function."
4637 (setq node (js2-node-parent node))
4638 (while (and node (not (js2-function-node-p node)))
4639 (setq node (js2-node-parent node)))
4640 (and (js2-function-node-p node) node))
4641
4642 (defun js2-mode-find-enclosing-fn (node)
4643 "Find function or root enclosing NODE."
4644 (if (js2-ast-root-p node)
4645 node
4646 (setq node (js2-node-parent node))
4647 (while (not (or (js2-ast-root-p node)
4648 (js2-function-node-p node)))
4649 (setq node (js2-node-parent node)))
4650 node))
4651
4652 (defun js2-mode-find-enclosing-node (beg end)
4653 "Find script or function fully enclosing BEG and END."
4654 (let ((node (js2-node-at-point beg))
4655 pos
4656 (continue t))
4657 (while continue
4658 (if (or (js2-ast-root-p node)
4659 (and (js2-function-node-p node)
4660 (<= (setq pos (js2-node-abs-pos node)) beg)
4661 (>= (+ pos (js2-node-len node)) end)))
4662 (setq continue nil)
4663 (setq node (js2-node-parent node))))
4664 node))
4665
4666 (defun js2-node-parent-script-or-fn (node)
4667 "Find script or function immediately enclosing NODE.
4668 If NODE is the ast-root, returns nil."
4669 (if (js2-ast-root-p node)
4670 nil
4671 (setq node (js2-node-parent node))
4672 (while (and node (not (or (js2-function-node-p node)
4673 (js2-script-node-p node))))
4674 (setq node (js2-node-parent node)))
4675 node))
4676
4677 (defsubst js2-nested-function-p (node)
4678 "Return t if NODE is a nested function, or is inside a nested function."
4679 (unless (js2-ast-root-p node)
4680 (js2-function-node-p (if (js2-function-node-p node)
4681 (js2-node-parent-script-or-fn node)
4682 (js2-node-parent-script-or-fn
4683 (js2-node-parent-script-or-fn node))))))
4684
4685 (defsubst js2-function-param-node-p (node)
4686 "Return non-nil if NODE is a param node of a `js2-function-node'."
4687 (let ((parent (js2-node-parent node)))
4688 (and parent
4689 (js2-function-node-p parent)
4690 (memq node (js2-function-node-params parent)))))
4691
4692 (defsubst js2-mode-shift-kids (kids start offset)
4693 (dolist (kid kids)
4694 (if (> (js2-node-pos kid) start)
4695 (incf (js2-node-pos kid) offset))))
4696
4697 (defsubst js2-mode-shift-children (parent start offset)
4698 "Update start-positions of all children of PARENT beyond START."
4699 (let ((root (js2-node-root parent)))
4700 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4701 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4702
4703 (defsubst js2-node-is-descendant (node ancestor)
4704 "Return t if NODE is a descendant of ANCESTOR."
4705 (while (and node
4706 (not (eq node ancestor)))
4707 (setq node (js2-node-parent node)))
4708 node)
4709
4710 ;;; visitor infrastructure
4711
4712 (defun js2-visit-none (node callback)
4713 "Visitor for AST node that have no node children."
4714 nil)
4715
4716 (defun js2-print-none (node indent)
4717 "Visitor for AST node with no printed representation.")
4718
4719 (defun js2-print-body (node indent)
4720 "Print a statement, or a block without braces."
4721 (if (js2-block-node-p node)
4722 (dolist (kid (js2-block-node-kids node))
4723 (js2-print-ast kid indent))
4724 (js2-print-ast node indent)))
4725
4726 (defun js2-print-list (args &optional delimiter)
4727 (loop with len = (length args)
4728 for arg in args
4729 for count from 1
4730 do
4731 (js2-print-ast arg 0)
4732 (if (< count len)
4733 (insert (or delimiter ", ")))))
4734
4735 (defun js2-print-tree (ast)
4736 "Prints an AST to the current buffer.
4737 Makes `js2-ast-parent-nodes' available to the printer functions."
4738 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4739 (js2-print-ast ast)))
4740
4741 (defun js2-print-ast (node &optional indent)
4742 "Helper function for printing AST nodes.
4743 Requires `js2-ast-parent-nodes' to be non-nil.
4744 You should use `js2-print-tree' instead of this function."
4745 (let ((printer (get (aref node 0) 'js2-printer))
4746 (i (or indent 0))
4747 (pos (js2-node-abs-pos node)))
4748 ;; TODO: wedge comments in here somewhere
4749 (if printer
4750 (funcall printer node i))))
4751
4752 (defconst js2-side-effecting-tokens
4753 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4754 (dolist (tt (list js2-ASSIGN
4755 js2-ASSIGN_ADD
4756 js2-ASSIGN_BITAND
4757 js2-ASSIGN_BITOR
4758 js2-ASSIGN_BITXOR
4759 js2-ASSIGN_DIV
4760 js2-ASSIGN_LSH
4761 js2-ASSIGN_MOD
4762 js2-ASSIGN_MUL
4763 js2-ASSIGN_RSH
4764 js2-ASSIGN_SUB
4765 js2-ASSIGN_URSH
4766 js2-BLOCK
4767 js2-BREAK
4768 js2-CALL
4769 js2-CATCH
4770 js2-CATCH_SCOPE
4771 js2-CONST
4772 js2-CONTINUE
4773 js2-DEBUGGER
4774 js2-DEC
4775 js2-DELPROP
4776 js2-DEL_REF
4777 js2-DO
4778 js2-ELSE
4779 js2-EMPTY
4780 js2-ENTERWITH
4781 js2-EXPORT
4782 js2-EXPR_RESULT
4783 js2-FINALLY
4784 js2-FOR
4785 js2-FUNCTION
4786 js2-GOTO
4787 js2-IF
4788 js2-IFEQ
4789 js2-IFNE
4790 js2-IMPORT
4791 js2-INC
4792 js2-JSR
4793 js2-LABEL
4794 js2-LEAVEWITH
4795 js2-LET
4796 js2-LETEXPR
4797 js2-LOCAL_BLOCK
4798 js2-LOOP
4799 js2-NEW
4800 js2-REF_CALL
4801 js2-RETHROW
4802 js2-RETURN
4803 js2-RETURN_RESULT
4804 js2-SEMI
4805 js2-SETELEM
4806 js2-SETELEM_OP
4807 js2-SETNAME
4808 js2-SETPROP
4809 js2-SETPROP_OP
4810 js2-SETVAR
4811 js2-SET_REF
4812 js2-SET_REF_OP
4813 js2-SWITCH
4814 js2-TARGET
4815 js2-THROW
4816 js2-TRY
4817 js2-VAR
4818 js2-WHILE
4819 js2-WITH
4820 js2-WITHEXPR
4821 js2-YIELD))
4822 (aset tokens tt t))
4823 (if js2-instanceof-has-side-effects
4824 (aset tokens js2-INSTANCEOF t))
4825 tokens))
4826
4827 (defun js2-node-has-side-effects (node)
4828 "Return t if NODE has side effects."
4829 (when node ; makes it easier to handle malformed expressions
4830 (let ((tt (js2-node-type node)))
4831 (cond
4832 ;; This doubtless needs some work, since EXPR_VOID is used
4833 ;; in several ways in Rhino, and I may not have caught them all.
4834 ;; I'll wait for people to notice incorrect warnings.
4835 ((and (= tt js2-EXPR_VOID)
4836 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4837 (let ((expr (js2-expr-stmt-node-expr node)))
4838 (or (js2-node-has-side-effects expr)
4839 (when (js2-string-node-p expr)
4840 (string= "use strict" (js2-string-node-value expr))))))
4841 ((= tt js2-COMMA)
4842 (js2-node-has-side-effects (js2-infix-node-right node)))
4843 ((or (= tt js2-AND)
4844 (= tt js2-OR))
4845 (or (js2-node-has-side-effects (js2-infix-node-right node))
4846 (js2-node-has-side-effects (js2-infix-node-left node))))
4847 ((= tt js2-HOOK)
4848 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4849 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4850 ((js2-paren-node-p node)
4851 (js2-node-has-side-effects (js2-paren-node-expr node)))
4852 ((= tt js2-ERROR) ; avoid cascaded error messages
4853 nil)
4854 (t
4855 (aref js2-side-effecting-tokens tt))))))
4856
4857 (defun js2-member-expr-leftmost-name (node)
4858 "For an expr such as foo.bar.baz, return leftmost node foo.
4859 NODE is any `js2-node' object. If it represents a member expression,
4860 which is any sequence of property gets, element-gets, function calls,
4861 or xml descendants/filter operators, then we look at the lexically
4862 leftmost (first) node in the chain. If it is a name-node we return it.
4863 Note that NODE can be a raw name-node and it will be returned as well.
4864 If NODE is not a name-node or member expression, or if it is a member
4865 expression whose leftmost target is not a name node, returns nil."
4866 (let ((continue t)
4867 result)
4868 (while (and continue (not result))
4869 (cond
4870 ((js2-name-node-p node)
4871 (setq result node))
4872 ((js2-prop-get-node-p node)
4873 (setq node (js2-prop-get-node-left node)))
4874 ;; TODO: handle call-nodes, xml-nodes, others?
4875 (t
4876 (setq continue nil))))
4877 result))
4878
4879 (defconst js2-stmt-node-types
4880 (list js2-BLOCK
4881 js2-BREAK
4882 js2-CONTINUE
4883 js2-DEFAULT ; e4x "default xml namespace" statement
4884 js2-DO
4885 js2-EXPR_RESULT
4886 js2-EXPR_VOID
4887 js2-FOR
4888 js2-IF
4889 js2-RETURN
4890 js2-SWITCH
4891 js2-THROW
4892 js2-TRY
4893 js2-WHILE
4894 js2-WITH)
4895 "Node types that only appear in statement contexts.
4896 The list does not include nodes that always appear as the child
4897 of another specific statement type, such as switch-cases,
4898 catch and finally blocks, and else-clauses. The list also excludes
4899 nodes like yield, let and var, which may appear in either expression
4900 or statement context, and in the latter context always have a
4901 `js2-expr-stmt-node' parent. Finally, the list does not include
4902 functions or scripts, which are treated separately from statements
4903 by the JavaScript parser and runtime.")
4904
4905 (defun js2-stmt-node-p (node)
4906 "Heuristic for figuring out if NODE is a statement.
4907 Some node types can appear in either an expression context or a
4908 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4909 For these node types in a statement context, the parent will be a
4910 `js2-expr-stmt-node'.
4911 Functions aren't included in the check."
4912 (memq (js2-node-type node) js2-stmt-node-types))
4913
4914 (defsubst js2-mode-find-first-stmt (node)
4915 "Search upward starting from NODE looking for a statement.
4916 For purposes of this function, a `js2-function-node' counts."
4917 (while (not (or (js2-stmt-node-p node)
4918 (js2-function-node-p node)))
4919 (setq node (js2-node-parent node)))
4920 node)
4921
4922 (defun js2-node-parent-stmt (node)
4923 "Return the node's first ancestor that is a statement.
4924 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4925 appearing in a statement context will have a parent that is a
4926 `js2-expr-stmt-node' that will be returned by this function."
4927 (let ((parent (js2-node-parent node)))
4928 (if (or (null parent)
4929 (js2-stmt-node-p parent)
4930 (and (js2-function-node-p parent)
4931 (not (eq (js2-function-node-form parent)
4932 'FUNCTION_EXPRESSION))))
4933 parent
4934 (js2-node-parent-stmt parent))))
4935
4936 ;; In the Mozilla Rhino sources, Roshan James writes:
4937 ;; Does consistent-return analysis on the function body when strict mode is
4938 ;; enabled.
4939 ;;
4940 ;; function (x) { return (x+1) }
4941 ;;
4942 ;; is ok, but
4943 ;;
4944 ;; function (x) { if (x < 0) return (x+1); }
4945 ;;
4946 ;; is not because the function can potentially return a value when the
4947 ;; condition is satisfied and if not, the function does not explicitly
4948 ;; return a value.
4949 ;;
4950 ;; This extends to checking mismatches such as "return" and "return <value>"
4951 ;; used in the same function. Warnings are not emitted if inconsistent
4952 ;; returns exist in code that can be statically shown to be unreachable.
4953 ;; Ex.
4954 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4955 ;;
4956 ;; emits no warning. However if the loop had a break statement, then a
4957 ;; warning would be emitted.
4958 ;;
4959 ;; The consistency analysis looks at control structures such as loops, ifs,
4960 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4961 ;; warns the user about an inconsistent set of termination possibilities.
4962 ;;
4963 ;; These flags enumerate the possible ways a statement/function can
4964 ;; terminate. These flags are used by endCheck() and by the Parser to
4965 ;; detect inconsistent return usage.
4966 ;;
4967 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4968 ;; able to execute (example: throw, continue)
4969 ;;
4970 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4971 ;; next one. Statement such as return dont. A compound statement may have
4972 ;; some branch that drops off control to the next statement.
4973 ;;
4974 ;; END_RETURNS indicates that the statement can return with no value.
4975 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4976 ;;
4977 ;; A compound statement such as
4978 ;; if (condition) {
4979 ;; return value;
4980 ;; }
4981 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4982
4983 (defconst js2-END_UNREACHED 0)
4984 (defconst js2-END_DROPS_OFF 1)
4985 (defconst js2-END_RETURNS 2)
4986 (defconst js2-END_RETURNS_VALUE 4)
4987 (defconst js2-END_YIELDS 8)
4988
4989 (defun js2-has-consistent-return-usage (node)
4990 "Check that every return usage in a function body is consistent.
4991 Returns t if the function satisfies strict mode requirement."
4992 (let ((n (js2-end-check node)))
4993 ;; either it doesn't return a value in any branch...
4994 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4995 ;; or it returns a value (or is unreached) at every branch
4996 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4997 js2-END_RETURNS
4998 js2-END_YIELDS)))))
4999
5000 (defun js2-end-check-if (node)
5001 "Returns in the then and else blocks must be consistent with each other.
5002 If there is no else block, then the return statement can fall through.
5003 Returns logical OR of END_* flags"
5004 (let ((th (js2-if-node-then-part node))
5005 (el (js2-if-node-else-part node)))
5006 (if (null th)
5007 js2-END_UNREACHED
5008 (logior (js2-end-check th) (if el
5009 (js2-end-check el)
5010 js2-END_DROPS_OFF)))))
5011
5012 (defun js2-end-check-switch (node)
5013 "Consistency of return statements is checked between the case statements.
5014 If there is no default, then the switch can fall through. If there is a
5015 default, we check to see if all code paths in the default return or if
5016 there is a code path that can fall through.
5017 Returns logical OR of END_* flags."
5018 (let ((rv js2-END_UNREACHED)
5019 default-case)
5020 ;; examine the cases
5021 (catch 'break
5022 (dolist (c (js2-switch-node-cases node))
5023 (if (js2-case-node-expr c)
5024 (js2-set-flag rv (js2-end-check-block c))
5025 (setq default-case c)
5026 (throw 'break nil))))
5027 ;; we don't care how the cases drop into each other
5028 (js2-clear-flag rv js2-END_DROPS_OFF)
5029 ;; examine the default
5030 (js2-set-flag rv (if default-case
5031 (js2-end-check default-case)
5032 js2-END_DROPS_OFF))
5033 rv))
5034
5035 (defun js2-end-check-try (node)
5036 "If the block has a finally, return consistency is checked in the
5037 finally block. If all code paths in the finally return, then the
5038 returns in the try-catch blocks don't matter. If there is a code path
5039 that does not return or if there is no finally block, the returns
5040 of the try and catch blocks are checked for mismatch.
5041 Returns logical OR of END_* flags."
5042 (let ((finally (js2-try-node-finally-block node))
5043 rv)
5044 ;; check the finally if it exists
5045 (setq rv (if finally
5046 (js2-end-check (js2-finally-node-body finally))
5047 js2-END_DROPS_OFF))
5048 ;; If the finally block always returns, then none of the returns
5049 ;; in the try or catch blocks matter.
5050 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5051 (js2-clear-flag rv js2-END_DROPS_OFF)
5052 ;; examine the try block
5053 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5054 ;; check each catch block
5055 (dolist (cb (js2-try-node-catch-clauses node))
5056 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5057 rv))
5058
5059 (defun js2-end-check-loop (node)
5060 "Return statement in the loop body must be consistent. The default
5061 assumption for any kind of a loop is that it will eventually terminate.
5062 The only exception is a loop with a constant true condition. Code that
5063 follows such a loop is examined only if one can statically determine
5064 that there is a break out of the loop.
5065
5066 for(... ; ... ; ...) {}
5067 for(... in ... ) {}
5068 while(...) { }
5069 do { } while(...)
5070
5071 Returns logical OR of END_* flags."
5072 (let ((rv (js2-end-check (js2-loop-node-body node)))
5073 (condition (cond
5074 ((js2-while-node-p node)
5075 (js2-while-node-condition node))
5076 ((js2-do-node-p node)
5077 (js2-do-node-condition node))
5078 ((js2-for-node-p node)
5079 (js2-for-node-condition node)))))
5080
5081 ;; check to see if the loop condition is always true
5082 (if (and condition
5083 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5084 (js2-clear-flag rv js2-END_DROPS_OFF))
5085
5086 ;; look for effect of breaks
5087 (js2-set-flag rv (js2-node-get-prop node
5088 'CONTROL_BLOCK_PROP
5089 js2-END_UNREACHED))
5090 rv))
5091
5092 (defun js2-end-check-block (node)
5093 "A general block of code is examined statement by statement.
5094 If any statement (even a compound one) returns in all branches, then
5095 subsequent statements are not examined.
5096 Returns logical OR of END_* flags."
5097 (let* ((rv js2-END_DROPS_OFF)
5098 (kids (js2-block-node-kids node))
5099 (n (car kids)))
5100 ;; Check each statment. If the statement can continue onto the next
5101 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5102 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5103 (js2-clear-flag rv js2-END_DROPS_OFF)
5104 (js2-set-flag rv (js2-end-check n))
5105 (setq kids (cdr kids)
5106 n (car kids)))
5107 rv))
5108
5109 (defun js2-end-check-label (node)
5110 "A labeled statement implies that there may be a break to the label.
5111 The function processes the labeled statement and then checks the
5112 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5113 particular label.
5114 Returns logical OR of END_* flags."
5115 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5116 (logior rv (js2-node-get-prop node
5117 'CONTROL_BLOCK_PROP
5118 js2-END_UNREACHED))))
5119
5120 (defun js2-end-check-break (node)
5121 "When a break is encountered annotate the statement being broken
5122 out of by setting its CONTROL_BLOCK_PROP property.
5123 Returns logical OR of END_* flags."
5124 (and (js2-break-node-target node)
5125 (js2-node-set-prop (js2-break-node-target node)
5126 'CONTROL_BLOCK_PROP
5127 js2-END_DROPS_OFF))
5128 js2-END_UNREACHED)
5129
5130 (defun js2-end-check (node)
5131 "Examine the body of a function, doing a basic reachability analysis.
5132 Returns a combination of flags END_* flags that indicate
5133 how the function execution can terminate. These constitute only the
5134 pessimistic set of termination conditions. It is possible that at
5135 runtime certain code paths will never be actually taken. Hence this
5136 analysis will flag errors in cases where there may not be errors.
5137 Returns logical OR of END_* flags"
5138 (let (kid)
5139 (cond
5140 ((js2-break-node-p node)
5141 (js2-end-check-break node))
5142 ((js2-expr-stmt-node-p node)
5143 (if (setq kid (js2-expr-stmt-node-expr node))
5144 (js2-end-check kid)
5145 js2-END_DROPS_OFF))
5146 ((or (js2-continue-node-p node)
5147 (js2-throw-node-p node))
5148 js2-END_UNREACHED)
5149 ((js2-return-node-p node)
5150 (if (setq kid (js2-return-node-retval node))
5151 js2-END_RETURNS_VALUE
5152 js2-END_RETURNS))
5153 ((js2-loop-node-p node)
5154 (js2-end-check-loop node))
5155 ((js2-switch-node-p node)
5156 (js2-end-check-switch node))
5157 ((js2-labeled-stmt-node-p node)
5158 (js2-end-check-label node))
5159 ((js2-if-node-p node)
5160 (js2-end-check-if node))
5161 ((js2-try-node-p node)
5162 (js2-end-check-try node))
5163 ((js2-block-node-p node)
5164 (if (null (js2-block-node-kids node))
5165 js2-END_DROPS_OFF
5166 (js2-end-check-block node)))
5167 ((js2-yield-node-p node)
5168 js2-END_YIELDS)
5169 (t
5170 js2-END_DROPS_OFF))))
5171
5172 (defun js2-always-defined-boolean-p (node)
5173 "Check if NODE always evaluates to true or false in boolean context.
5174 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5175 nor always false."
5176 (let ((tt (js2-node-type node))
5177 num)
5178 (cond
5179 ((or (= tt js2-FALSE) (= tt js2-NULL))
5180 'ALWAYS_FALSE)
5181 ((= tt js2-TRUE)
5182 'ALWAYS_TRUE)
5183 ((= tt js2-NUMBER)
5184 (setq num (js2-number-node-num-value node))
5185 (if (and (not (eq num 0.0e+NaN))
5186 (not (zerop num)))
5187 'ALWAYS_TRUE
5188 'ALWAYS_FALSE))
5189 (t
5190 nil))))
5191
5192 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5193 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5194
5195 (defvar js2-tokens nil
5196 "List of all defined token names.") ; initialized in `js2-token-names'
5197
5198 (defconst js2-token-names
5199 (let* ((names (make-vector js2-num-tokens -1))
5200 (case-fold-search nil) ; only match js2-UPPER_CASE
5201 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5202 (loop for sym in syms
5203 for i from 0
5204 do
5205 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5206 (not (boundp sym)))
5207 (aset names (symbol-value sym) ; code, e.g. 152
5208 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5209 (push sym js2-tokens)))
5210 names)
5211 "Vector mapping int values to token string names, sans `js2-' prefix.")
5212
5213 (defun js2-token-name (tok)
5214 "Return a string name for TOK, a token symbol or code.
5215 Signals an error if it's not a recognized token."
5216 (let ((code tok))
5217 (if (symbolp tok)
5218 (setq code (symbol-value tok)))
5219 (if (eq code -1)
5220 "ERROR"
5221 (if (and (numberp code)
5222 (not (minusp code))
5223 (< code js2-num-tokens))
5224 (aref js2-token-names code)
5225 (error "Invalid token: %s" code)))))
5226
5227 (defsubst js2-token-sym (tok)
5228 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5229 (intern (js2-token-name tok)))
5230
5231 (defconst js2-token-codes
5232 (let ((table (make-hash-table :test 'eq :size 256)))
5233 (loop for name across js2-token-names
5234 for sym = (intern (concat "js2-" name))
5235 do
5236 (puthash sym (symbol-value sym) table))
5237 ;; clean up a few that are "wrong" in Rhino's token codes
5238 (puthash 'js2-DELETE js2-DELPROP table)
5239 table)
5240 "Hashtable mapping token symbols to their bytecodes.")
5241
5242 (defsubst js2-token-code (sym)
5243 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5244 (or (gethash sym js2-token-codes)
5245 (error "Invalid token symbol: %s " sym))) ; signal code bug
5246
5247 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5248 (setq js2-token-end js2-ts-cursor)
5249 (js2-report-error msg nil
5250 (or beg js2-token-beg)
5251 (or len (- js2-token-end js2-token-beg)))
5252 (unless no-throw
5253 (throw 'return js2-ERROR)))
5254
5255 (defsubst js2-get-string-from-buffer ()
5256 "Reverse the char accumulator and return it as a string."
5257 (setq js2-token-end js2-ts-cursor)
5258 (if js2-ts-string-buffer
5259 (apply #'string (nreverse js2-ts-string-buffer))
5260 ""))
5261
5262 ;; TODO: could potentially avoid a lot of consing by allocating a
5263 ;; char buffer the way Rhino does.
5264 (defsubst js2-add-to-string (c)
5265 (push c js2-ts-string-buffer))
5266
5267 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5268 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5269 ;; any other character: when it's not part of the current token, we
5270 ;; unget it, allowing it to be read again by the following call.
5271 (defsubst js2-unget-char ()
5272 (decf js2-ts-cursor))
5273
5274 ;; Rhino distinguishes \r and \n line endings. We don't need to
5275 ;; because we only scan from Emacs buffers, which always use \n.
5276 (defsubst js2-get-char ()
5277 "Read and return the next character from the input buffer.
5278 Increments `js2-ts-lineno' if the return value is a newline char.
5279 Updates `js2-ts-cursor' to the point after the returned char.
5280 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5281 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5282 (let (c)
5283 ;; check for end of buffer
5284 (if (>= js2-ts-cursor (point-max))
5285 (setq js2-ts-hit-eof t
5286 js2-ts-cursor (1+ js2-ts-cursor)
5287 c js2-EOF_CHAR) ; return value
5288 ;; otherwise read next char
5289 (setq c (char-before (incf js2-ts-cursor)))
5290 ;; if we read a newline, update counters
5291 (if (= c ?\n)
5292 (setq js2-ts-line-start js2-ts-cursor
5293 js2-ts-lineno (1+ js2-ts-lineno)))
5294 ;; TODO: skip over format characters
5295 c)))
5296
5297 (defsubst js2-read-unicode-escape ()
5298 "Read a \\uNNNN sequence from the input.
5299 Assumes the ?\ and ?u have already been read.
5300 Returns the unicode character, or nil if it wasn't a valid character.
5301 Doesn't change the values of any scanner variables."
5302 ;; I really wish I knew a better way to do this, but I can't
5303 ;; find the Emacs function that takes a 16-bit int and converts
5304 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5305 ;; Have to first check that it's 4 hex characters or it may stop
5306 ;; the read early.
5307 (ignore-errors
5308 (let ((s (buffer-substring-no-properties js2-ts-cursor
5309 (+ 4 js2-ts-cursor))))
5310 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5311 (read (concat "?\\u" s))))))
5312
5313 (defsubst js2-match-char (test)
5314 "Consume and return next character if it matches TEST, a character.
5315 Returns nil and consumes nothing if TEST is not the next character."
5316 (let ((c (js2-get-char)))
5317 (if (eq c test)
5318 t
5319 (js2-unget-char)
5320 nil)))
5321
5322 (defsubst js2-peek-char ()
5323 (prog1
5324 (js2-get-char)
5325 (js2-unget-char)))
5326
5327 (defsubst js2-java-identifier-start-p (c)
5328 (or
5329 (memq c '(?$ ?_))
5330 (js2-char-uppercase-p c)
5331 (js2-char-lowercase-p c)))
5332
5333 (defsubst js2-java-identifier-part-p (c)
5334 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5335 ;; TODO: make me Unicode-friendly. See comments above.
5336 (or
5337 (memq c '(?$ ?_))
5338 (js2-char-uppercase-p c)
5339 (js2-char-lowercase-p c)
5340 (and (>= c ?0) (<= c ?9))))
5341
5342 (defsubst js2-alpha-p (c)
5343 (cond ((and (<= ?A c) (<= c ?Z)) t)
5344 ((and (<= ?a c) (<= c ?z)) t)
5345 (t nil)))
5346
5347 (defsubst js2-digit-p (c)
5348 (and (<= ?0 c) (<= c ?9)))
5349
5350 (defsubst js2-js-space-p (c)
5351 (if (<= c 127)
5352 (memq c '(#x20 #x9 #xB #xC #xD))
5353 (or
5354 (eq c #xA0)
5355 ;; TODO: change this nil to check for Unicode space character
5356 nil)))
5357
5358 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5359
5360 (defsubst js2-skip-line ()
5361 "Skip to end of line"
5362 (let (c)
5363 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5364 (js2-unget-char)
5365 (setq js2-token-end js2-ts-cursor)))
5366
5367 (defun js2-init-scanner (&optional buf line)
5368 "Create token stream for BUF starting on LINE.
5369 BUF defaults to current-buffer and line defaults to 1.
5370
5371 A buffer can only have one scanner active at a time, which yields
5372 dramatically simpler code than using a defstruct. If you need to
5373 have simultaneous scanners in a buffer, copy the regions to scan
5374 into temp buffers."
5375 (save-excursion
5376 (when buf
5377 (set-buffer buf))
5378 (setq js2-ts-dirty-line nil
5379 js2-ts-regexp-flags nil
5380 js2-ts-string ""
5381 js2-ts-number nil
5382 js2-ts-hit-eof nil
5383 js2-ts-line-start 0
5384 js2-ts-lineno (or line 1)
5385 js2-ts-line-end-char -1
5386 js2-ts-cursor (point-min)
5387 js2-ts-is-xml-attribute nil
5388 js2-ts-xml-is-tag-content nil
5389 js2-ts-xml-open-tags-count 0
5390 js2-ts-string-buffer nil)))
5391
5392 ;; This function uses the cached op, string and number fields in
5393 ;; TokenStream; if getToken has been called since the passed token
5394 ;; was scanned, the op or string printed may be incorrect.
5395 (defun js2-token-to-string (token)
5396 ;; Not sure where this function is used in Rhino. Not tested.
5397 (if (not js2-debug-print-trees)
5398 ""
5399 (let ((name (js2-token-name token)))
5400 (cond
5401 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5402 (concat name " `" js2-ts-string "'"))
5403 ((eq token js2-NUMBER)
5404 (format "NUMBER %g" js2-ts-number))
5405 (t
5406 name)))))
5407
5408 (defconst js2-keywords
5409 '(break
5410 case catch const continue
5411 debugger default delete do
5412 else enum
5413 false finally for function
5414 if in instanceof import
5415 let
5416 new null
5417 return
5418 switch
5419 this throw true try typeof
5420 var void
5421 while with
5422 yield))
5423
5424 ;; Token names aren't exactly the same as the keywords, unfortunately.
5425 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5426 (defconst js2-kwd-tokens
5427 (let ((table (make-vector js2-num-tokens nil))
5428 (tokens
5429 (list js2-BREAK
5430 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5431 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5432 js2-ELSE
5433 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5434 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5435 js2-LET
5436 js2-NEW js2-NULL
5437 js2-RETURN
5438 js2-SWITCH
5439 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5440 js2-VAR
5441 js2-WHILE js2-WITH
5442 js2-YIELD)))
5443 (dolist (i tokens)
5444 (aset table i 'font-lock-keyword-face))
5445 (aset table js2-STRING 'font-lock-string-face)
5446 (aset table js2-REGEXP 'font-lock-string-face)
5447 (aset table js2-COMMENT 'font-lock-comment-face)
5448 (aset table js2-THIS 'font-lock-builtin-face)
5449 (aset table js2-VOID 'font-lock-constant-face)
5450 (aset table js2-NULL 'font-lock-constant-face)
5451 (aset table js2-TRUE 'font-lock-constant-face)
5452 (aset table js2-FALSE 'font-lock-constant-face)
5453 table)
5454 "Vector whose values are non-nil for tokens that are keywords.
5455 The values are default faces to use for highlighting the keywords.")
5456
5457 (defconst js2-reserved-words
5458 '(abstract
5459 boolean byte
5460 char class
5461 double
5462 enum export extends
5463 final float
5464 goto
5465 implements import int interface
5466 long
5467 native
5468 package private protected public
5469 short static super synchronized
5470 throws transient
5471 volatile))
5472
5473 (defconst js2-keyword-names
5474 (let ((table (make-hash-table :test 'equal)))
5475 (loop for k in js2-keywords
5476 do (puthash
5477 (symbol-name k) ; instanceof
5478 (intern (concat "js2-"
5479 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5480 table))
5481 table)
5482 "JavaScript keywords by name, mapped to their symbols.")
5483
5484 (defconst js2-reserved-word-names
5485 (let ((table (make-hash-table :test 'equal)))
5486 (loop for k in js2-reserved-words
5487 do
5488 (puthash (symbol-name k) 'js2-RESERVED table))
5489 table)
5490 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5491
5492 (defsubst js2-collect-string (buf)
5493 "Convert BUF, a list of chars, to a string.
5494 Reverses BUF before converting."
5495 (cond
5496 ((stringp buf)
5497 buf)
5498 ((null buf) ; for emacs21 compat
5499 "")
5500 (t
5501 (if buf
5502 (apply #'string (nreverse buf))
5503 ""))))
5504
5505 (defun js2-string-to-keyword (s)
5506 "Return token for S, a string, if S is a keyword or reserved word.
5507 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5508 (or (gethash s js2-keyword-names)
5509 (gethash s js2-reserved-word-names)))
5510
5511 (defsubst js2-ts-set-char-token-bounds ()
5512 "Used when next token is one character."
5513 (setq js2-token-beg (1- js2-ts-cursor)
5514 js2-token-end js2-ts-cursor))
5515
5516 (defsubst js2-ts-return (token)
5517 "Return an N-character TOKEN from `js2-get-token'.
5518 Updates `js2-token-end' accordingly."
5519 (setq js2-token-end js2-ts-cursor)
5520 (throw 'return token))
5521
5522 (defsubst js2-x-digit-to-int (c accumulator)
5523 "Build up a hex number.
5524 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5525 corresponding number. Otherwise return -1."
5526 (catch 'return
5527 (catch 'check
5528 ;; Use 0..9 < A..Z < a..z
5529 (cond
5530 ((<= c ?9)
5531 (decf c ?0)
5532 (if (<= 0 c)
5533 (throw 'check nil)))
5534 ((<= c ?F)
5535 (when (<= ?A c)
5536 (decf c (- ?A 10))
5537 (throw 'check nil)))
5538 ((<= c ?f)
5539 (when (<= ?a c)
5540 (decf c (- ?a 10))
5541 (throw 'check nil))))
5542 (throw 'return -1))
5543 (logior c (lsh accumulator 4))))
5544
5545 (defun js2-get-token ()
5546 "Return next JavaScript token, an int such as js2-RETURN."
5547 (let (c
5548 c1
5549 identifier-start
5550 is-unicode-escape-start
5551 contains-escape
5552 escape-val
5553 escape-start
5554 str
5555 result
5556 base
5557 is-integer
5558 quote-char
5559 val
5560 look-for-slash
5561 continue)
5562 (catch 'return
5563 (while t
5564 ;; Eat whitespace, possibly sensitive to newlines.
5565 (setq continue t)
5566 (while continue
5567 (setq c (js2-get-char))
5568 (cond
5569 ((eq c js2-EOF_CHAR)
5570 (js2-ts-set-char-token-bounds)
5571 (throw 'return js2-EOF))
5572 ((eq c ?\n)
5573 (js2-ts-set-char-token-bounds)
5574 (setq js2-ts-dirty-line nil)
5575 (throw 'return js2-EOL))
5576 ((not (js2-js-space-p c))
5577 (if (/= c ?-) ; in case end of HTML comment
5578 (setq js2-ts-dirty-line t))
5579 (setq continue nil))))
5580 ;; Assume the token will be 1 char - fixed up below.
5581 (js2-ts-set-char-token-bounds)
5582 (when (eq c ?@)
5583 (throw 'return js2-XMLATTR))
5584 ;; identifier/keyword/instanceof?
5585 ;; watch out for starting with a <backslash>
5586 (cond
5587 ((eq c ?\\)
5588 (setq c (js2-get-char))
5589 (if (eq c ?u)
5590 (setq identifier-start t
5591 is-unicode-escape-start t
5592 js2-ts-string-buffer nil)
5593 (setq identifier-start nil)
5594 (js2-unget-char)
5595 (setq c ?\\)))
5596 (t
5597 (when (setq identifier-start (js2-java-identifier-start-p c))
5598 (setq js2-ts-string-buffer nil)
5599 (js2-add-to-string c))))
5600 (when identifier-start
5601 (setq contains-escape is-unicode-escape-start)
5602 (catch 'break
5603 (while t
5604 (if is-unicode-escape-start
5605 ;; strictly speaking we should probably push-back
5606 ;; all the bad characters if the <backslash>uXXXX
5607 ;; sequence is malformed. But since there isn't a
5608 ;; correct context(is there?) for a bad Unicode
5609 ;; escape sequence in an identifier, we can report
5610 ;; an error here.
5611 (progn
5612 (setq escape-val 0)
5613 (dotimes (i 4)
5614 (setq c (js2-get-char)
5615 escape-val (js2-x-digit-to-int c escape-val))
5616 ;; Next check takes care of c < 0 and bad escape
5617 (if (minusp escape-val)
5618 (throw 'break nil)))
5619 (if (minusp escape-val)
5620 (js2-report-scan-error "msg.invalid.escape" t))
5621 (js2-add-to-string escape-val)
5622 (setq is-unicode-escape-start nil))
5623 (setq c (js2-get-char))
5624 (cond
5625 ((eq c ?\\)
5626 (setq c (js2-get-char))
5627 (if (eq c ?u)
5628 (setq is-unicode-escape-start t
5629 contains-escape t)
5630 (js2-report-scan-error "msg.illegal.character" t)))
5631 (t
5632 (if (or (eq c js2-EOF_CHAR)
5633 (not (js2-java-identifier-part-p c)))
5634 (throw 'break nil))
5635 (js2-add-to-string c))))))
5636 (js2-unget-char)
5637 (setq str (js2-get-string-from-buffer))
5638 (unless contains-escape
5639 ;; OPT we shouldn't have to make a string (object!) to
5640 ;; check if it's a keyword.
5641 ;; Return the corresponding token if it's a keyword
5642 (when (setq result (js2-string-to-keyword str))
5643 (if (and (< js2-language-version 170)
5644 (memq result '(js2-LET js2-YIELD)))
5645 ;; LET and YIELD are tokens only in 1.7 and later
5646 (setq result 'js2-NAME))
5647 (if (not (eq result 'js2-RESERVED))
5648 (throw 'return (js2-token-code result)))
5649 (js2-report-warning "msg.reserved.keyword" str)))
5650 ;; If we want to intern these as Rhino does, just use (intern str)
5651 (setq js2-ts-string str)
5652 (throw 'return js2-NAME)) ; end identifier/kwd check
5653 ;; is it a number?
5654 (when (or (js2-digit-p c)
5655 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5656 (setq js2-ts-string-buffer nil
5657 base 10)
5658 (when (eq c ?0)
5659 (setq c (js2-get-char))
5660 (cond
5661 ((or (eq c ?x) (eq c ?X))
5662 (setq base 16)
5663 (setq c (js2-get-char)))
5664 ((js2-digit-p c)
5665 (setq base 8))
5666 (t
5667 (js2-add-to-string ?0))))
5668 (if (eq base 16)
5669 (while (<= 0 (js2-x-digit-to-int c 0))
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char)))
5672 (while (and (<= ?0 c) (<= c ?9))
5673 ;; We permit 08 and 09 as decimal numbers, which
5674 ;; makes our behavior a superset of the ECMA
5675 ;; numeric grammar. We might not always be so
5676 ;; permissive, so we warn about it.
5677 (when (and (eq base 8) (>= c ?8))
5678 (js2-report-warning "msg.bad.octal.literal"
5679 (if (eq c ?8) "8" "9"))
5680 (setq base 10))
5681 (js2-add-to-string c)
5682 (setq c (js2-get-char))))
5683 (setq is-integer t)
5684 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5685 (setq is-integer nil)
5686 (when (eq c ?.)
5687 (loop do
5688 (js2-add-to-string c)
5689 (setq c (js2-get-char))
5690 while (js2-digit-p c)))
5691 (when (memq c '(?e ?E))
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 (when (memq c '(?+ ?-))
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char)))
5697 (unless (js2-digit-p c)
5698 (js2-report-scan-error "msg.missing.exponent" t))
5699 (loop do
5700 (js2-add-to-string c)
5701 (setq c (js2-get-char))
5702 while (js2-digit-p c))))
5703 (js2-unget-char)
5704 (setq js2-ts-string (js2-get-string-from-buffer)
5705 js2-ts-number
5706 (if (and (eq base 10) (not is-integer))
5707 (string-to-number js2-ts-string)
5708 ;; TODO: call runtime number-parser. Some of it is in
5709 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5710 (string-to-number js2-ts-string)))
5711 (throw 'return js2-NUMBER))
5712 ;; is it a string?
5713 (when (memq c '(?\" ?\'))
5714 ;; We attempt to accumulate a string the fast way, by
5715 ;; building it directly out of the reader. But if there
5716 ;; are any escaped characters in the string, we revert to
5717 ;; building it out of a string buffer.
5718 (setq quote-char c
5719 js2-ts-string-buffer nil
5720 c (js2-get-char))
5721 (catch 'break
5722 (while (/= c quote-char)
5723 (catch 'continue
5724 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5725 (js2-unget-char)
5726 (setq js2-token-end js2-ts-cursor)
5727 (js2-report-error "msg.unterminated.string.lit")
5728 (throw 'return js2-STRING))
5729 (when (eq c ?\\)
5730 ;; We've hit an escaped character
5731 (setq c (js2-get-char))
5732 (case c
5733 (?b (setq c ?\b))
5734 (?f (setq c ?\f))
5735 (?n (setq c ?\n))
5736 (?r (setq c ?\r))
5737 (?t (setq c ?\t))
5738 (?v (setq c ?\v))
5739 (?u
5740 (setq c1 (js2-read-unicode-escape))
5741 (if js2-parse-ide-mode
5742 (if c1
5743 (progn
5744 ;; just copy the string in IDE-mode
5745 (js2-add-to-string ?\\)
5746 (js2-add-to-string ?u)
5747 (dotimes (i 3)
5748 (js2-add-to-string (js2-get-char)))
5749 (setq c (js2-get-char))) ; added at end of loop
5750 ;; flag it as an invalid escape
5751 (js2-report-warning "msg.invalid.escape"
5752 nil (- js2-ts-cursor 2) 6))
5753 ;; Get 4 hex digits; if the u escape is not
5754 ;; followed by 4 hex digits, use 'u' + the
5755 ;; literal character sequence that follows.
5756 (js2-add-to-string ?u)
5757 (setq escape-val 0)
5758 (dotimes (i 4)
5759 (setq c (js2-get-char)
5760 escape-val (js2-x-digit-to-int c escape-val))
5761 (if (minusp escape-val)
5762 (throw 'continue nil))
5763 (js2-add-to-string c))
5764 ;; prepare for replace of stored 'u' sequence by escape value
5765 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5766 c escape-val)))
5767 (?x
5768 ;; Get 2 hex digits, defaulting to 'x'+literal
5769 ;; sequence, as above.
5770 (setq c (js2-get-char)
5771 escape-val (js2-x-digit-to-int c 0))
5772 (if (minusp escape-val)
5773 (progn
5774 (js2-add-to-string ?x)
5775 (throw 'continue nil))
5776 (setq c1 c
5777 c (js2-get-char)
5778 escape-val (js2-x-digit-to-int c escape-val))
5779 (if (minusp escape-val)
5780 (progn
5781 (js2-add-to-string ?x)
5782 (js2-add-to-string c1)
5783 (throw 'continue nil))
5784 ;; got 2 hex digits
5785 (setq c escape-val))))
5786 (?\n
5787 ;; Remove line terminator after escape to follow
5788 ;; SpiderMonkey and C/C++
5789 (setq c (js2-get-char))
5790 (throw 'continue nil))
5791 (t
5792 (when (and (<= ?0 c) (< c ?8))
5793 (setq val (- c ?0)
5794 c (js2-get-char))
5795 (when (and (<= ?0 c) (< c ?8))
5796 (setq val (- (+ (* 8 val) c) ?0)
5797 c (js2-get-char))
5798 (when (and (<= ?0 c)
5799 (< c ?8)
5800 (< val #o37))
5801 ;; c is 3rd char of octal sequence only
5802 ;; if the resulting val <= 0377
5803 (setq val (- (+ (* 8 val) c) ?0)
5804 c (js2-get-char))))
5805 (js2-unget-char)
5806 (setq c val)))))
5807 (js2-add-to-string c)
5808 (setq c (js2-get-char)))))
5809 (setq js2-ts-string (js2-get-string-from-buffer))
5810 (throw 'return js2-STRING))
5811 (case c
5812 (?\;
5813 (throw 'return js2-SEMI))
5814 (?\[
5815 (throw 'return js2-LB))
5816 (?\]
5817 (throw 'return js2-RB))
5818 (?{
5819 (throw 'return js2-LC))
5820 (?}
5821 (throw 'return js2-RC))
5822 (?\(
5823 (throw 'return js2-LP))
5824 (?\)
5825 (throw 'return js2-RP))
5826 (?,
5827 (throw 'return js2-COMMA))
5828 (??
5829 (throw 'return js2-HOOK))
5830 (?:
5831 (if (js2-match-char ?:)
5832 (js2-ts-return js2-COLONCOLON)
5833 (throw 'return js2-COLON)))
5834 (?.
5835 (if (js2-match-char ?.)
5836 (js2-ts-return js2-DOTDOT)
5837 (if (js2-match-char ?\()
5838 (js2-ts-return js2-DOTQUERY)
5839 (throw 'return js2-DOT))))
5840 (?|
5841 (if (js2-match-char ?|)
5842 (throw 'return js2-OR)
5843 (if (js2-match-char ?=)
5844 (js2-ts-return js2-ASSIGN_BITOR)
5845 (throw 'return js2-BITOR))))
5846 (?^
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-ASSIGN_BITOR)
5849 (throw 'return js2-BITXOR)))
5850 (?&
5851 (if (js2-match-char ?&)
5852 (throw 'return js2-AND)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-ASSIGN_BITAND)
5855 (throw 'return js2-BITAND))))
5856 (?=
5857 (if (js2-match-char ?=)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-SHEQ)
5860 (throw 'return js2-EQ))
5861 (throw 'return js2-ASSIGN)))
5862 (?!
5863 (if (js2-match-char ?=)
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-SHNE)
5866 (js2-ts-return js2-NE))
5867 (throw 'return js2-NOT)))
5868 (?<
5869 ;; NB:treat HTML begin-comment as comment-till-eol
5870 (when (js2-match-char ?!)
5871 (when (js2-match-char ?-)
5872 (when (js2-match-char ?-)
5873 (js2-skip-line)
5874 (setq js2-ts-comment-type 'html)
5875 (throw 'return js2-COMMENT)))
5876 (js2-unget-char))
5877 (if (js2-match-char ?<)
5878 (if (js2-match-char ?=)
5879 (js2-ts-return js2-ASSIGN_LSH)
5880 (js2-ts-return js2-LSH))
5881 (if (js2-match-char ?=)
5882 (js2-ts-return js2-LE)
5883 (throw 'return js2-LT))))
5884 (?>
5885 (if (js2-match-char ?>)
5886 (if (js2-match-char ?>)
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-ASSIGN_URSH)
5889 (js2-ts-return js2-URSH))
5890 (if (js2-match-char ?=)
5891 (js2-ts-return js2-ASSIGN_RSH)
5892 (js2-ts-return js2-RSH)))
5893 (if (js2-match-char ?=)
5894 (js2-ts-return js2-GE)
5895 (throw 'return js2-GT))))
5896 (?*
5897 (if (js2-match-char ?=)
5898 (js2-ts-return js2-ASSIGN_MUL)
5899 (throw 'return js2-MUL)))
5900 (?/
5901 ;; is it a // comment?
5902 (when (js2-match-char ?/)
5903 (setq js2-token-beg (- js2-ts-cursor 2))
5904 (js2-skip-line)
5905 (setq js2-ts-comment-type 'line)
5906 ;; include newline so highlighting goes to end of window
5907 (incf js2-token-end)
5908 (throw 'return js2-COMMENT))
5909 ;; is it a /* comment?
5910 (when (js2-match-char ?*)
5911 (setq look-for-slash nil
5912 js2-token-beg (- js2-ts-cursor 2)
5913 js2-ts-comment-type
5914 (if (js2-match-char ?*)
5915 (progn
5916 (setq look-for-slash t)
5917 'jsdoc)
5918 'block))
5919 (while t
5920 (setq c (js2-get-char))
5921 (cond
5922 ((eq c js2-EOF_CHAR)
5923 (setq js2-token-end (1- js2-ts-cursor))
5924 (js2-report-error "msg.unterminated.comment")
5925 (throw 'return js2-COMMENT))
5926 ((eq c ?*)
5927 (setq look-for-slash t))
5928 ((eq c ?/)
5929 (if look-for-slash
5930 (js2-ts-return js2-COMMENT)))
5931 (t
5932 (setq look-for-slash nil
5933 js2-token-end js2-ts-cursor)))))
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_DIV)
5936 (throw 'return js2-DIV)))
5937 (?#
5938 (when js2-skip-preprocessor-directives
5939 (js2-skip-line)
5940 (setq js2-ts-comment-type 'preprocessor
5941 js2-token-end js2-ts-cursor)
5942 (throw 'return js2-COMMENT))
5943 (throw 'return js2-ERROR))
5944 (?%
5945 (if (js2-match-char ?=)
5946 (js2-ts-return js2-ASSIGN_MOD)
5947 (throw 'return js2-MOD)))
5948 (?~
5949 (throw 'return js2-BITNOT))
5950 (?+
5951 (if (js2-match-char ?=)
5952 (js2-ts-return js2-ASSIGN_ADD)
5953 (if (js2-match-char ?+)
5954 (js2-ts-return js2-INC)
5955 (throw 'return js2-ADD))))
5956 (?-
5957 (cond
5958 ((js2-match-char ?=)
5959 (setq c js2-ASSIGN_SUB))
5960 ((js2-match-char ?-)
5961 (unless js2-ts-dirty-line
5962 ;; treat HTML end-comment after possible whitespace
5963 ;; after line start as comment-until-eol
5964 (when (js2-match-char ?>)
5965 (js2-skip-line)
5966 (setq js2-ts-comment-type 'html)
5967 (throw 'return js2-COMMENT)))
5968 (setq c js2-DEC))
5969 (t
5970 (setq c js2-SUB)))
5971 (setq js2-ts-dirty-line t)
5972 (js2-ts-return c))
5973 (otherwise
5974 (js2-report-scan-error "msg.illegal.character")))))))
5975
5976 (defun js2-read-regexp (start-token)
5977 "Called by parser when it gets / or /= in literal context."
5978 (let (c
5979 err
5980 in-class ; inside a '[' .. ']' character-class
5981 flags
5982 (continue t))
5983 (setq js2-token-beg js2-ts-cursor
5984 js2-ts-string-buffer nil
5985 js2-ts-regexp-flags nil)
5986 (if (eq start-token js2-ASSIGN_DIV)
5987 ;; mis-scanned /=
5988 (js2-add-to-string ?=)
5989 (if (not (eq start-token js2-DIV))
5990 (error "failed assertion")))
5991 (while (and (not err)
5992 (or (/= (setq c (js2-get-char)) ?/)
5993 in-class))
5994 (cond
5995 ((or (= c ?\n)
5996 (= c js2-EOF_CHAR))
5997 (setq js2-token-end (1- js2-ts-cursor)
5998 err t
5999 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6000 (js2-report-error "msg.unterminated.re.lit"))
6001 (t (cond
6002 ((= c ?\\)
6003 (js2-add-to-string c)
6004 (setq c (js2-get-char)))
6005 ((= c ?\[)
6006 (setq in-class t))
6007 ((= c ?\])
6008 (setq in-class nil)))
6009 (js2-add-to-string c))))
6010 (unless err
6011 (while continue
6012 (cond
6013 ((js2-match-char ?g)
6014 (push ?g flags))
6015 ((js2-match-char ?i)
6016 (push ?i flags))
6017 ((js2-match-char ?m)
6018 (push ?m flags))
6019 (t
6020 (setq continue nil))))
6021 (if (js2-alpha-p (js2-peek-char))
6022 (js2-report-scan-error "msg.invalid.re.flag" t
6023 js2-ts-cursor 1))
6024 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6025 js2-ts-regexp-flags (js2-collect-string flags)
6026 js2-token-end js2-ts-cursor)
6027 ;; tell `parse-partial-sexp' to ignore this range of chars
6028 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6029
6030 (defun js2-get-first-xml-token ()
6031 (setq js2-ts-xml-open-tags-count 0
6032 js2-ts-is-xml-attribute nil
6033 js2-ts-xml-is-tag-content nil)
6034 (js2-unget-char)
6035 (js2-get-next-xml-token))
6036
6037 (defsubst js2-xml-discard-string ()
6038 "Throw away the string in progress and flag an XML parse error."
6039 (setq js2-ts-string-buffer nil
6040 js2-ts-string nil)
6041 (js2-report-scan-error "msg.XML.bad.form" t))
6042
6043 (defun js2-get-next-xml-token ()
6044 (setq js2-ts-string-buffer nil ; for recording the XML
6045 js2-token-beg js2-ts-cursor)
6046 (let (c result)
6047 (setq result
6048 (catch 'return
6049 (while t
6050 (setq c (js2-get-char))
6051 (cond
6052 ((= c js2-EOF_CHAR)
6053 (throw 'return js2-ERROR))
6054 (js2-ts-xml-is-tag-content
6055 (case c
6056 (?>
6057 (js2-add-to-string c)
6058 (setq js2-ts-xml-is-tag-content nil
6059 js2-ts-is-xml-attribute nil))
6060 (?/
6061 (js2-add-to-string c)
6062 (when (eq ?> (js2-peek-char))
6063 (setq c (js2-get-char))
6064 (js2-add-to-string c)
6065 (setq js2-ts-xml-is-tag-content nil)
6066 (decf js2-ts-xml-open-tags-count)))
6067 (?{
6068 (js2-unget-char)
6069 (setq js2-ts-string (js2-get-string-from-buffer))
6070 (throw 'return js2-XML))
6071 ((?\' ?\")
6072 (js2-add-to-string c)
6073 (unless (js2-read-quoted-string c)
6074 (throw 'return js2-ERROR)))
6075 (?=
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute t))
6078 ((? ?\t ?\r ?\n)
6079 (js2-add-to-string c))
6080 (t
6081 (js2-add-to-string c)
6082 (setq js2-ts-is-xml-attribute nil)))
6083 (when (and (not js2-ts-xml-is-tag-content)
6084 (zerop js2-ts-xml-open-tags-count))
6085 (setq js2-ts-string (js2-get-string-from-buffer))
6086 (throw 'return js2-XMLEND)))
6087 (t
6088 ;; else not tag content
6089 (case c
6090 (?<
6091 (js2-add-to-string c)
6092 (setq c (js2-peek-char))
6093 (case c
6094 (?!
6095 (setq c (js2-get-char)) ;; skip !
6096 (js2-add-to-string c)
6097 (setq c (js2-peek-char))
6098 (case c
6099 (?-
6100 (setq c (js2-get-char)) ;; skip -
6101 (js2-add-to-string c)
6102 (if (eq c ?-)
6103 (progn
6104 (js2-add-to-string c)
6105 (unless (js2-read-xml-comment)
6106 (throw 'return js2-ERROR)))
6107 (js2-xml-discard-string)
6108 (throw 'return js2-ERROR)))
6109 (?\[
6110 (setq c (js2-get-char)) ;; skip [
6111 (js2-add-to-string c)
6112 (if (and (= (js2-get-char) ?C)
6113 (= (js2-get-char) ?D)
6114 (= (js2-get-char) ?A)
6115 (= (js2-get-char) ?T)
6116 (= (js2-get-char) ?A)
6117 (= (js2-get-char) ?\[))
6118 (progn
6119 (js2-add-to-string ?C)
6120 (js2-add-to-string ?D)
6121 (js2-add-to-string ?A)
6122 (js2-add-to-string ?T)
6123 (js2-add-to-string ?A)
6124 (js2-add-to-string ?\[)
6125 (unless (js2-read-cdata)
6126 (throw 'return js2-ERROR)))
6127 (js2-xml-discard-string)
6128 (throw 'return js2-ERROR)))
6129 (t
6130 (unless (js2-read-entity)
6131 (throw 'return js2-ERROR))))
6132 ;; allow bare CDATA section
6133 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6134 (when (zerop js2-ts-xml-open-tags-count)
6135 (throw 'return js2-XMLEND)))
6136 (??
6137 (setq c (js2-get-char)) ;; skip ?
6138 (js2-add-to-string c)
6139 (unless (js2-read-PI)
6140 (throw 'return js2-ERROR)))
6141 (?/
6142 ;; end tag
6143 (setq c (js2-get-char)) ;; skip /
6144 (js2-add-to-string c)
6145 (when (zerop js2-ts-xml-open-tags-count)
6146 (js2-xml-discard-string)
6147 (throw 'return js2-ERROR))
6148 (setq js2-ts-xml-is-tag-content t)
6149 (decf js2-ts-xml-open-tags-count))
6150 (t
6151 ;; start tag
6152 (setq js2-ts-xml-is-tag-content t)
6153 (incf js2-ts-xml-open-tags-count))))
6154 (?{
6155 (js2-unget-char)
6156 (setq js2-ts-string (js2-get-string-from-buffer))
6157 (throw 'return js2-XML))
6158 (t
6159 (js2-add-to-string c))))))))
6160 (setq js2-token-end js2-ts-cursor)
6161 result))
6162
6163 (defun js2-read-quoted-string (quote)
6164 (let (c)
6165 (catch 'return
6166 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6167 (js2-add-to-string c)
6168 (if (eq c quote)
6169 (throw 'return t)))
6170 (js2-xml-discard-string) ;; throw away string in progress
6171 nil)))
6172
6173 (defun js2-read-xml-comment ()
6174 (let ((c (js2-get-char)))
6175 (catch 'return
6176 (while (/= c js2-EOF_CHAR)
6177 (catch 'continue
6178 (js2-add-to-string c)
6179 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6180 (setq c (js2-get-char))
6181 (js2-add-to-string c)
6182 (if (eq (js2-peek-char) ?>)
6183 (progn
6184 (setq c (js2-get-char)) ;; skip >
6185 (js2-add-to-string c)
6186 (throw 'return t))
6187 (throw 'continue nil)))
6188 (setq c (js2-get-char))))
6189 (js2-xml-discard-string)
6190 nil)))
6191
6192 (defun js2-read-cdata ()
6193 (let ((c (js2-get-char)))
6194 (catch 'return
6195 (while (/= c js2-EOF_CHAR)
6196 (catch 'continue
6197 (js2-add-to-string c)
6198 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6199 (setq c (js2-get-char))
6200 (js2-add-to-string c)
6201 (if (eq (js2-peek-char) ?>)
6202 (progn
6203 (setq c (js2-get-char)) ;; Skip >
6204 (js2-add-to-string c)
6205 (throw 'return t))
6206 (throw 'continue nil)))
6207 (setq c (js2-get-char))))
6208 (js2-xml-discard-string)
6209 nil)))
6210
6211 (defun js2-read-entity ()
6212 (let ((decl-tags 1)
6213 c)
6214 (catch 'return
6215 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6216 (js2-add-to-string c)
6217 (case c
6218 (?<
6219 (incf decl-tags))
6220 (?>
6221 (decf decl-tags)
6222 (if (zerop decl-tags)
6223 (throw 'return t)))))
6224 (js2-xml-discard-string)
6225 nil)))
6226
6227 (defun js2-read-PI ()
6228 "Scan an XML processing instruction."
6229 (let (c)
6230 (catch 'return
6231 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6232 (js2-add-to-string c)
6233 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6234 (setq c (js2-get-char)) ;; Skip >
6235 (js2-add-to-string c)
6236 (throw 'return t)))
6237 (js2-xml-discard-string)
6238 nil)))
6239
6240 (defun js2-scanner-get-line ()
6241 "Return the text of the current scan line."
6242 (buffer-substring (point-at-bol) (point-at-eol)))
6243
6244 ;;; Highlighting
6245
6246 (defsubst js2-set-face (beg end face &optional record)
6247 "Fontify a region. If RECORD is non-nil, record for later."
6248 (when (plusp js2-highlight-level)
6249 (setq beg (min (point-max) beg)
6250 beg (max (point-min) beg)
6251 end (min (point-max) end)
6252 end (max (point-min) end))
6253 (if record
6254 (push (list beg end face) js2-mode-fontifications)
6255 (put-text-property beg end 'font-lock-face face))))
6256
6257 (defsubst js2-set-kid-face (pos kid len face)
6258 "Set-face on a child node.
6259 POS is absolute buffer position of parent.
6260 KID is the child node.
6261 LEN is the length to fontify.
6262 FACE is the face to fontify with."
6263 (js2-set-face (+ pos (js2-node-pos kid))
6264 (+ pos (js2-node-pos kid) (js2-node-len kid))
6265 face))
6266
6267 (defsubst js2-fontify-kwd (start length)
6268 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6269
6270 (defsubst js2-clear-face (beg end)
6271 (remove-text-properties beg end '(font-lock-face nil
6272 help-echo nil
6273 point-entered nil
6274 c-in-sws nil)))
6275
6276 (defconst js2-ecma-global-props
6277 (concat "^"
6278 (regexp-opt
6279 '("Infinity" "NaN" "undefined" "arguments") t)
6280 "$")
6281 "Value properties of the Ecma-262 Global Object.
6282 Shown at or above `js2-highlight-level' 2.")
6283
6284 ;; might want to add the name "arguments" to this list?
6285 (defconst js2-ecma-object-props
6286 (concat "^"
6287 (regexp-opt
6288 '("prototype" "__proto__" "__parent__") t)
6289 "$")
6290 "Value properties of the Ecma-262 Object constructor.
6291 Shown at or above `js2-highlight-level' 2.")
6292
6293 (defconst js2-ecma-global-funcs
6294 (concat
6295 "^"
6296 (regexp-opt
6297 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6298 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6299 "$")
6300 "Function properties of the Ecma-262 Global object.
6301 Shown at or above `js2-highlight-level' 2.")
6302
6303 (defconst js2-ecma-number-props
6304 (concat "^"
6305 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6306 "NEGATIVE_INFINITY"
6307 "POSITIVE_INFINITY") t)
6308 "$")
6309 "Properties of the Ecma-262 Number constructor.
6310 Shown at or above `js2-highlight-level' 2.")
6311
6312 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6313 "Properties of the Ecma-262 Date constructor.
6314 Shown at or above `js2-highlight-level' 2.")
6315
6316 (defconst js2-ecma-math-props
6317 (concat "^"
6318 (regexp-opt
6319 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6320 t)
6321 "$")
6322 "Properties of the Ecma-262 Math object.
6323 Shown at or above `js2-highlight-level' 2.")
6324
6325 (defconst js2-ecma-math-funcs
6326 (concat "^"
6327 (regexp-opt
6328 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6329 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6330 "$")
6331 "Function properties of the Ecma-262 Math object.
6332 Shown at or above `js2-highlight-level' 2.")
6333
6334 (defconst js2-ecma-function-props
6335 (concat
6336 "^"
6337 (regexp-opt
6338 '(;; properties of the Object prototype object
6339 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6340 "toLocaleString" "toString" "valueOf"
6341 ;; properties of the Function prototype object
6342 "apply" "call"
6343 ;; properties of the Array prototype object
6344 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6345 "splice" "unshift"
6346 ;; properties of the String prototype object
6347 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6348 "localeCompare" "match" "replace" "search" "split" "substring"
6349 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6350 "toUpperCase"
6351 ;; properties of the Number prototype object
6352 "toExponential" "toFixed" "toPrecision"
6353 ;; properties of the Date prototype object
6354 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6355 "getMinutes" "getMonth" "getSeconds" "getTime"
6356 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6357 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6358 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6359 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6360 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6361 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6362 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6363 "toTimeString" "toUTCString"
6364 ;; properties of the RegExp prototype object
6365 "exec" "test"
6366 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6367 "toSource" "__defineGetter__" "__defineSetter__"
6368 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6369 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6370 t)
6371 "$")
6372 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6373 Shown at or above `js2-highlight-level' 3.")
6374
6375 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6376 (let ((target-name (and target
6377 (js2-name-node-p target)
6378 (js2-name-node-name target)))
6379 (prop-name (if prop (js2-name-node-name prop)))
6380 (level1 (>= js2-highlight-level 1))
6381 (level2 (>= js2-highlight-level 2))
6382 (level3 (>= js2-highlight-level 3))
6383 pos
6384 face)
6385 (when level2
6386 (if call-p
6387 (cond
6388 ((and target prop)
6389 (cond
6390 ((and level3 (string-match js2-ecma-function-props prop-name))
6391 (setq face 'font-lock-builtin-face))
6392 ((and target-name prop)
6393 (cond
6394 ((string= target-name "Date")
6395 (if (string-match js2-ecma-date-props prop-name)
6396 (setq face 'font-lock-builtin-face)))
6397 ((string= target-name "Math")
6398 (if (string-match js2-ecma-math-funcs prop-name)
6399 (setq face 'font-lock-builtin-face)))))))
6400 (prop
6401 (if (string-match js2-ecma-global-funcs prop-name)
6402 (setq face 'font-lock-builtin-face))))
6403 (cond
6404 ((and target prop)
6405 (cond
6406 ((string= target-name "Number")
6407 (if (string-match js2-ecma-number-props prop-name)
6408 (setq face 'font-lock-constant-face)))
6409 ((string= target-name "Math")
6410 (if (string-match js2-ecma-math-props prop-name)
6411 (setq face 'font-lock-constant-face)))))
6412 (prop
6413 (if (string-match js2-ecma-object-props prop-name)
6414 (setq face 'font-lock-constant-face)))))
6415 (when face
6416 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6417 (js2-node-pos prop))) ; relative
6418 (+ pos (js2-node-len prop))
6419 face)))))
6420
6421 (defun js2-parse-highlight-member-expr-node (node)
6422 "Perform syntax highlighting of EcmaScript built-in properties.
6423 The variable `js2-highlight-level' governs this highighting."
6424 (let (face target prop name pos end parent call-p callee)
6425 (cond
6426 ;; case 1: simple name, e.g. foo
6427 ((js2-name-node-p node)
6428 (setq name (js2-name-node-name node))
6429 ;; possible for name to be nil in rare cases - saw it when
6430 ;; running js2-mode on an elisp buffer. Might as well try to
6431 ;; make it so js2-mode never barfs.
6432 (when name
6433 (setq face (if (string-match js2-ecma-global-props name)
6434 'font-lock-constant-face))
6435 (when face
6436 (setq pos (js2-node-pos node)
6437 end (+ pos (js2-node-len node)))
6438 (js2-set-face pos end face))))
6439 ;; case 2: property access or function call
6440 ((or (js2-prop-get-node-p node)
6441 ;; highlight function call if expr is a prop-get node
6442 ;; or a plain name (i.e. unqualified function call)
6443 (and (setq call-p (js2-call-node-p node))
6444 (setq callee (js2-call-node-target node)) ; separate setq!
6445 (or (js2-prop-get-node-p callee)
6446 (js2-name-node-p callee))))
6447 (setq parent node
6448 node (if call-p callee node))
6449 (if (and call-p (js2-name-node-p callee))
6450 (setq prop callee)
6451 (setq target (js2-prop-get-node-left node)
6452 prop (js2-prop-get-node-right node)))
6453 (cond
6454 ((js2-name-node-p target)
6455 (if (js2-name-node-p prop)
6456 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6457 (js2-parse-highlight-prop-get parent target prop call-p)
6458 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6459 (js2-parse-highlight-prop-get parent target nil call-p)))
6460 ((js2-name-node-p prop)
6461 ;; case 2c: complex target, simple name, e.g. x[y].bar
6462 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6463
6464 (defun js2-parse-highlight-member-expr-fn-name (expr)
6465 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6466 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6467 We currently only handle the case where the last component is a prop-get
6468 of a simple name. Called before EXPR has a parent node."
6469 (let (pos
6470 (name (and (js2-prop-get-node-p expr)
6471 (js2-prop-get-node-right expr))))
6472 (when (js2-name-node-p name)
6473 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6474 (js2-node-pos name)))
6475 (+ pos (js2-node-len name))
6476 'font-lock-function-name-face
6477 'record))))
6478
6479 ;; source: http://jsdoc.sourceforge.net/
6480 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6481 ;; allows type specifications, and needs work before entering the wild.
6482
6483 (defconst js2-jsdoc-param-tag-regexp
6484 (concat "^\\s-*\\*+\\s-*\\(@"
6485 "\\(?:param\\|argument\\)"
6486 "\\)"
6487 "\\s-*\\({[^}]+}\\)?" ; optional type
6488 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6489 "\\>")
6490 "Matches jsdoc tags with optional type and optional param name.")
6491
6492 (defconst js2-jsdoc-typed-tag-regexp
6493 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6494 (regexp-opt
6495 '("enum"
6496 "extends"
6497 "field"
6498 "id"
6499 "implements"
6500 "lends"
6501 "mods"
6502 "requires"
6503 "return"
6504 "returns"
6505 "throw"
6506 "throws"))
6507 "\\)\\)\\s-*\\({[^}]+}\\)?")
6508 "Matches jsdoc tags with optional type.")
6509
6510 (defconst js2-jsdoc-arg-tag-regexp
6511 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6512 (regexp-opt
6513 '("alias"
6514 "augments"
6515 "borrows"
6516 "bug"
6517 "base"
6518 "config"
6519 "default"
6520 "define"
6521 "exception"
6522 "function"
6523 "member"
6524 "memberOf"
6525 "name"
6526 "namespace"
6527 "property"
6528 "since"
6529 "suppress"
6530 "this"
6531 "throws"
6532 "type"
6533 "version"))
6534 "\\)\\)\\s-+\\([^ \t]+\\)")
6535 "Matches jsdoc tags with a single argument.")
6536
6537 (defconst js2-jsdoc-empty-tag-regexp
6538 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6539 (regexp-opt
6540 '("addon"
6541 "author"
6542 "class"
6543 "const"
6544 "constant"
6545 "constructor"
6546 "constructs"
6547 "deprecated"
6548 "desc"
6549 "description"
6550 "event"
6551 "example"
6552 "exec"
6553 "export"
6554 "fileoverview"
6555 "final"
6556 "function"
6557 "hidden"
6558 "ignore"
6559 "implicitCast"
6560 "inheritDoc"
6561 "inner"
6562 "interface"
6563 "license"
6564 "noalias"
6565 "noshadow"
6566 "notypecheck"
6567 "override"
6568 "owner"
6569 "preserve"
6570 "preserveTry"
6571 "private"
6572 "protected"
6573 "public"
6574 "static"
6575 "supported"
6576 ))
6577 "\\)\\)\\s-*")
6578 "Matches empty jsdoc tags.")
6579
6580 (defconst js2-jsdoc-link-tag-regexp
6581 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6582 "Matches a jsdoc link or code tag.")
6583
6584 (defconst js2-jsdoc-see-tag-regexp
6585 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6586 "Matches a jsdoc @see tag.")
6587
6588 (defconst js2-jsdoc-html-tag-regexp
6589 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6590 "Matches a simple (no attributes) html start- or end-tag.")
6591
6592 (defsubst js2-jsdoc-highlight-helper ()
6593 (js2-set-face (match-beginning 1)
6594 (match-end 1)
6595 'js2-jsdoc-tag-face)
6596 (if (match-beginning 2)
6597 (if (save-excursion
6598 (goto-char (match-beginning 2))
6599 (= (char-after) ?{))
6600 (js2-set-face (1+ (match-beginning 2))
6601 (1- (match-end 2))
6602 'js2-jsdoc-type-face)
6603 (js2-set-face (match-beginning 2)
6604 (match-end 2)
6605 'js2-jsdoc-value-face)))
6606 (if (match-beginning 3)
6607 (js2-set-face (match-beginning 3)
6608 (match-end 3)
6609 'js2-jsdoc-value-face)))
6610
6611 (defun js2-highlight-jsdoc (ast)
6612 "Highlight doc comment tags."
6613 (let ((comments (js2-ast-root-comments ast))
6614 beg end)
6615 (save-excursion
6616 (dolist (node comments)
6617 (when (eq (js2-comment-node-format node) 'jsdoc)
6618 (setq beg (js2-node-abs-pos node)
6619 end (+ beg (js2-node-len node)))
6620 (save-restriction
6621 (narrow-to-region beg end)
6622 (dolist (re (list js2-jsdoc-param-tag-regexp
6623 js2-jsdoc-typed-tag-regexp
6624 js2-jsdoc-arg-tag-regexp
6625 js2-jsdoc-link-tag-regexp
6626 js2-jsdoc-see-tag-regexp
6627 js2-jsdoc-empty-tag-regexp))
6628 (goto-char beg)
6629 (while (re-search-forward re nil t)
6630 (js2-jsdoc-highlight-helper)))
6631 ;; simple highlighting for html tags
6632 (goto-char beg)
6633 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6634 (js2-set-face (match-beginning 1)
6635 (match-end 1)
6636 'js2-jsdoc-html-tag-delimiter-face)
6637 (js2-set-face (match-beginning 2)
6638 (match-end 2)
6639 'js2-jsdoc-html-tag-name-face)
6640 (js2-set-face (match-beginning 3)
6641 (match-end 3)
6642 'js2-jsdoc-html-tag-delimiter-face))))))))
6643
6644 (defun js2-highlight-assign-targets (node left right)
6645 "Highlight function properties and external variables."
6646 (let (leftpos end name)
6647 ;; highlight vars and props assigned function values
6648 (when (js2-function-node-p right)
6649 (cond
6650 ;; var foo = function() {...}
6651 ((js2-name-node-p left)
6652 (setq name left))
6653 ;; foo.bar.baz = function() {...}
6654 ((and (js2-prop-get-node-p left)
6655 (js2-name-node-p (js2-prop-get-node-right left)))
6656 (setq name (js2-prop-get-node-right left))))
6657 (when name
6658 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6659 (+ leftpos (js2-node-len name))
6660 'font-lock-function-name-face
6661 'record)))))
6662
6663 (defun js2-record-name-node (node)
6664 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6665 later. NODE must be a name node."
6666 (let (leftpos end)
6667 (push (list node js2-current-scope
6668 (setq leftpos (js2-node-abs-pos node))
6669 (setq end (+ leftpos (js2-node-len node))))
6670 js2-recorded-identifiers)))
6671
6672 (defun js2-highlight-undeclared-vars ()
6673 "After entire parse is finished, look for undeclared variable references.
6674 We have to wait until entire buffer is parsed, since JavaScript permits var
6675 decls to occur after they're used.
6676
6677 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6678 it is considered declared."
6679 (let (name)
6680 (dolist (entry js2-recorded-identifiers)
6681 (destructuring-bind (name-node scope pos end) entry
6682 (setq name (js2-name-node-name name-node))
6683 (unless (or (member name js2-global-externs)
6684 (member name js2-default-externs)
6685 (member name js2-additional-externs)
6686 (js2-get-defining-scope scope name))
6687 (js2-set-face pos end 'js2-external-variable-face 'record)
6688 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6689 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6690 (setq js2-recorded-identifiers nil)))
6691
6692 ;;; IMenu support
6693
6694 ;; We currently only support imenu, but eventually should support speedbar and
6695 ;; possibly other browsing mechanisms.
6696
6697 ;; The basic strategy is to identify function assignment targets of the form
6698 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6699 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6700 ;; for imenu after parsing is finished.
6701
6702 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6703 ;; JavaScript, and the general problem is undecidable. However, several forms
6704 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6705 ;; include:
6706
6707 ;; function foo() -- function declaration
6708 ;; foo = function() -- function expression assigned to variable
6709 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6710 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6711 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6712 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6713 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6714 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6715 ;; function foo() {function bar() {...}} -- nested function
6716 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6717
6718 ;; This list boils down to a few forms that can be combined recursively.
6719 ;; Top-level named function declarations include both the left-hand (name)
6720 ;; and the right-hand (function value) expressions needed to produce an imenu
6721 ;; entry. The other "right-hand" forms we need to look for are:
6722 ;; - functions declared as props/getters/setters in object literals
6723 ;; - nested named function declarations
6724 ;; The "left-hand" expressions that functions can be assigned to include:
6725 ;; - local/global variables
6726 ;; - nested property-get expressions like a.b.c.d
6727 ;; - element gets like foo[10] or foo['bar'] where the index
6728 ;; expression can be trivially converted to a property name. They
6729 ;; effectively then become property gets.
6730
6731 ;; All the different definition types are canonicalized into the form
6732 ;; foo.bar.baz = position-of-function-keyword
6733
6734 ;; We need to build a trie-like structure for imenu. As an example,
6735 ;; consider the following JavaScript code:
6736
6737 ;; a = function() {...} // function at position 5
6738 ;; b = function() {...} // function at position 25
6739 ;; foo = function() {...} // function at position 100
6740 ;; foo.bar = function() {...} // function at position 200
6741 ;; foo.bar.baz = function() {...} // function at position 300
6742 ;; foo.bar.zab = function() {...} // function at position 400
6743
6744 ;; During parsing we accumulate an entry for each definition in
6745 ;; the variable `js2-imenu-recorder', like so:
6746
6747 ;; '((fn a 5)
6748 ;; (fn b 25)
6749 ;; (fn foo 100)
6750 ;; (fn foo bar 200)
6751 ;; (fn foo bar baz 300)
6752 ;; (fn foo bar zab 400))
6753
6754 ;; Where 'fn' is the respective function node.
6755 ;; After parsing these entries are merged into this alist-trie:
6756
6757 ;; '((a . 1)
6758 ;; (b . 2)
6759 ;; (foo (<definition> . 3)
6760 ;; (bar (<definition> . 6)
6761 ;; (baz . 100)
6762 ;; (zab . 200))))
6763
6764 ;; Note the wacky need for a <definition> name. The token can be anything
6765 ;; that isn't a valid JavaScript identifier, because you might make foo
6766 ;; a function and then start setting properties on it that are also functions.
6767
6768 (defsubst js2-prop-node-name (node)
6769 "Return the name of a node that may be a property-get/property-name.
6770 If NODE is not a valid name-node, string-node or integral number-node,
6771 returns nil. Otherwise returns the string name/value of the node."
6772 (cond
6773 ((js2-name-node-p node)
6774 (js2-name-node-name node))
6775 ((js2-string-node-p node)
6776 (js2-string-node-value node))
6777 ((and (js2-number-node-p node)
6778 (string-match "^[0-9]+$" (js2-number-node-value node)))
6779 (js2-number-node-value node))
6780 ((js2-this-node-p node)
6781 "this")))
6782
6783 (defsubst js2-node-qname-component (node)
6784 "Return the name of this node, if it contributes to a qname.
6785 Returns nil if the node doesn't contribute."
6786 (copy-sequence
6787 (or (js2-prop-node-name node)
6788 (if (and (js2-function-node-p node)
6789 (js2-function-node-name node))
6790 (js2-name-node-name (js2-function-node-name node))))))
6791
6792 (defsubst js2-record-imenu-entry (fn-node qname pos)
6793 "Add an entry to `js2-imenu-recorder'.
6794 FN-NODE should be the current item's function node.
6795
6796 Associate FN-NODE with its QNAME for later lookup.
6797 This is used in postprocessing the chain list. For each chain, we find
6798 the parent function, look up its qname, then prepend a copy of it to the chain."
6799 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6800 (unless js2-imenu-function-map
6801 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6802 (puthash fn-node qname js2-imenu-function-map))
6803
6804 (defun js2-record-imenu-functions (node &optional var)
6805 "Record function definitions for imenu.
6806 NODE is a function node or an object literal.
6807 VAR, if non-nil, is the expression that NODE is being assigned to."
6808 (when js2-parse-ide-mode
6809 (let ((fun-p (js2-function-node-p node))
6810 qname left fname-node pos)
6811 (cond
6812 ;; non-anonymous function declaration?
6813 ((and fun-p
6814 (not var)
6815 (setq fname-node (js2-function-node-name node)))
6816 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6817 ;; for remaining forms, compute left-side tree branch first
6818 ((and var (setq qname (js2-compute-nested-prop-get var)))
6819 (cond
6820 ;; foo.bar.baz = function
6821 (fun-p
6822 (js2-record-imenu-entry node qname (js2-node-pos node)))
6823 ;; foo.bar.baz = object-literal
6824 ;; look for nested functions: {a: {b: function() {...} }}
6825 ((js2-object-node-p node)
6826 ;; Node position here is still absolute, since the parser
6827 ;; passes the assignment target and value expressions
6828 ;; to us before they are added as children of the assignment node.
6829 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6830
6831 (defun js2-compute-nested-prop-get (node)
6832 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6833 component nodes as a list. Otherwise return nil. Element-gets are treated
6834 as property-gets if the index expression is a string, or a positive integer."
6835 (let (left right head)
6836 (cond
6837 ((or (js2-name-node-p node)
6838 (js2-this-node-p node))
6839 (list node))
6840 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6841 ((js2-prop-get-node-p node) ; foo.bar
6842 (setq left (js2-prop-get-node-left node)
6843 right (js2-prop-get-node-right node))
6844 (if (setq head (js2-compute-nested-prop-get left))
6845 (nconc head (list right))))
6846 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6847 (setq left (js2-elem-get-node-target node)
6848 right (js2-elem-get-node-element node))
6849 (if (or (js2-string-node-p right) ; ['bar']
6850 (and (js2-number-node-p right) ; [10]
6851 (string-match "^[0-9]+$"
6852 (js2-number-node-value right))))
6853 (if (setq head (js2-compute-nested-prop-get left))
6854 (nconc head (list right))))))))
6855
6856 (defun js2-record-object-literal (node qname pos)
6857 "Recursively process an object literal looking for functions.
6858 NODE is an object literal that is the right-hand child of an assignment
6859 expression. QNAME is a list of nodes representing the assignment target,
6860 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6861 POS is the absolute position of the node.
6862 We do a depth-first traversal of NODE. For any functions we find,
6863 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6864 (let (left right prop-qname)
6865 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6866 (let ((left (js2-infix-node-left e))
6867 ;; Element positions are relative to the parent position.
6868 (pos (+ pos (js2-node-pos e))))
6869 (cond
6870 ;; foo: function() {...}
6871 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6872 (when (js2-prop-node-name left)
6873 ;; As a policy decision, we record the position of the property,
6874 ;; not the position of the `function' keyword, since the property
6875 ;; is effectively the name of the function.
6876 (js2-record-imenu-entry right (append qname (list left)) pos)))
6877 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6878 ((js2-object-node-p right)
6879 (js2-record-object-literal right
6880 (append qname (list (js2-infix-node-left e)))
6881 (+ pos (js2-node-pos right)))))))))
6882
6883 (defsubst js2-node-top-level-decl-p (node)
6884 "Return t if NODE's name is defined in the top-level scope.
6885 Also returns t if NODE's name is not defined in any scope, since it implies
6886 that it's an external variable, which must also be in the top-level scope."
6887 (let* ((name (js2-prop-node-name node))
6888 (this-scope (js2-node-get-enclosing-scope node))
6889 defining-scope)
6890 (cond
6891 ((js2-this-node-p node)
6892 nil)
6893 ((null this-scope)
6894 t)
6895 ((setq defining-scope (js2-get-defining-scope this-scope name))
6896 (js2-ast-root-p defining-scope))
6897 (t t))))
6898
6899 (defsubst js2-wrapper-function-p (node)
6900 "Returns t if NODE is a function expression that's immediately invoked.
6901 NODE must be `js2-function-node'."
6902 (let ((parent (js2-node-parent node)))
6903 (or
6904 ;; function(){...}();
6905 (js2-call-node-p parent)
6906 (and (js2-paren-node-p parent)
6907 ;; (function(){...})();
6908 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6909 ;; (function(){...}).call(this);
6910 (and (js2-prop-get-node-p parent)
6911 (member (js2-name-node-name (js2-prop-get-node-right parent))
6912 '("call" "apply"))
6913 (js2-call-node-p (js2-node-parent parent))))))))
6914
6915 (defun js2-browse-postprocess-chains (entries)
6916 "Modify function-declaration name chains after parsing finishes.
6917 Some of the information is only available after the parse tree is complete.
6918 For instance, processing a nested scope requires a parent function node."
6919 (let (result head fn current-fn parent-qname qname p elem)
6920 (dolist (entry entries)
6921 ;; function node goes first
6922 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6923 ;; examine its defining scope;
6924 ;; if top-level/external, keep as-is
6925 (if (js2-node-top-level-decl-p head)
6926 (push chain result)
6927 (when (js2-this-node-p head)
6928 (setq chain (cdr chain))) ; discard this-node
6929 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6930 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6931 (when (eq parent-qname 'not-found)
6932 ;; anonymous function expressions are not recorded
6933 ;; during the parse, so we need to handle this case here
6934 (setq parent-qname
6935 (if (js2-wrapper-function-p fn)
6936 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6937 (if (js2-ast-root-p grandparent)
6938 nil
6939 (gethash grandparent js2-imenu-function-map 'skip)))
6940 'skip))
6941 (puthash fn parent-qname js2-imenu-function-map))
6942 (unless (eq parent-qname 'skip)
6943 ;; prefix parent fn qname to this chain.
6944 (let ((qname (append parent-qname chain)))
6945 (puthash current-fn (butlast qname) js2-imenu-function-map)
6946 (push qname result)))))))
6947 ;; finally replace each node in each chain with its name.
6948 (dolist (chain result)
6949 (setq p chain)
6950 (while p
6951 (if (js2-node-p (setq elem (car p)))
6952 (setcar p (js2-node-qname-component elem)))
6953 (setq p (cdr p))))
6954 result))
6955
6956 ;; Merge name chains into a trie-like tree structure of nested lists.
6957 ;; To simplify construction of the trie, we first build it out using the rule
6958 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6959 ;; [key, num-or-list]. The second element can be a number; if so, this key
6960 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6961 ;; associated with the key at this level.) Otherwise the second element is
6962 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6963 ;; a simple recursive formulation.
6964 ;;
6965 ;; js2-mode is building the data structure for imenu. The imenu documentation
6966 ;; claims that it's the structure above, but in practice it wants the children
6967 ;; at the same list level as the key for that level, which is how I've drawn
6968 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6969 ;; list wrapper around the children at each level.
6970 ;;
6971 ;; A completed nested imenu-alist entry looks like this:
6972 ;; '(("foo"
6973 ;; ("<definition>" . 7)
6974 ;; ("bar"
6975 ;; ("a" . 40)
6976 ;; ("b" . 60))))
6977 ;;
6978 ;; In particular, the documentation for `imenu--index-alist' says that
6979 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6980 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6981
6982 (defun js2-treeify (lst)
6983 "Convert (a b c d) to (a ((b ((c d)))))"
6984 (if (null (cddr lst)) ; list length <= 2
6985 lst
6986 (list (car lst) (list (js2-treeify (cdr lst))))))
6987
6988 (defun js2-build-alist-trie (chains trie)
6989 "Merge declaration name chains into a trie-like alist structure for imenu.
6990 CHAINS is the qname chain list produced during parsing. TRIE is a
6991 list of elements built up so far."
6992 (let (head tail pos branch kids)
6993 (dolist (chain chains)
6994 (setq head (car chain)
6995 tail (cdr chain)
6996 pos (if (numberp (car tail)) (car tail))
6997 branch (js2-find-if (lambda (n)
6998 (string= (car n) head))
6999 trie)
7000 kids (second branch))
7001 (cond
7002 ;; case 1: this key isn't in the trie yet
7003 ((null branch)
7004 (if trie
7005 (setcdr (last trie) (list (js2-treeify chain)))
7006 (setq trie (list (js2-treeify chain)))))
7007 ;; case 2: key is present with a single number entry: replace w/ list
7008 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7009 ;; ("<definition>" 20)))
7010 ((numberp kids)
7011 (setcar (cdr branch)
7012 (list (list "<definition-1>" kids)
7013 (if pos
7014 (list "<definition-2>" pos)
7015 (js2-treeify tail)))))
7016 ;; case 3: key is there (with kids), and we're a number entry
7017 (pos
7018 (setcdr (last kids)
7019 (list
7020 (list (format "<definition-%d>"
7021 (1+ (loop for kid in kids
7022 count (eq ?< (aref (car kid) 0)))))
7023 pos))))
7024 ;; case 4: key is there with kids, need to merge in our chain
7025 (t
7026 (js2-build-alist-trie (list tail) kids))))
7027 trie))
7028
7029 (defun js2-flatten-trie (trie)
7030 "Convert TRIE to imenu-format.
7031 Recurses through nodes, and for each one whose second element is a list,
7032 appends the list's flattened elements to the current element. Also
7033 changes the tails into conses. For instance, this pre-flattened trie
7034
7035 '(a ((b 20)
7036 (c ((d 30)
7037 (e 40)))))
7038
7039 becomes
7040
7041 '(a (b . 20)
7042 (c (d . 30)
7043 (e . 40)))
7044
7045 Note that the root of the trie has no key, just a list of chains.
7046 This is also true for the value of any key with multiple children,
7047 e.g. key 'c' in the example above."
7048 (cond
7049 ((listp (car trie))
7050 (mapcar #'js2-flatten-trie trie))
7051 (t
7052 (if (numberp (second trie))
7053 (cons (car trie) (second trie))
7054 ;; else pop list and append its kids
7055 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7056
7057 (defun js2-build-imenu-index ()
7058 "Turn `js2-imenu-recorder' into an imenu data structure."
7059 (unless (eq js2-imenu-recorder 'empty)
7060 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7061 (result (js2-build-alist-trie chains nil)))
7062 (js2-flatten-trie result))))
7063
7064 (defun js2-test-print-chains (chains)
7065 "Print a list of qname chains.
7066 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7067 i.e. one or more nodes, and an integer position as the list tail."
7068 (mapconcat (lambda (chain)
7069 (concat "("
7070 (mapconcat (lambda (elem)
7071 (if (js2-node-p elem)
7072 (or (js2-node-qname-component elem)
7073 "nil")
7074 (number-to-string elem)))
7075 chain
7076 " ")
7077 ")"))
7078 chains
7079 "\n"))
7080
7081 ;;; Parser
7082
7083 (defconst js2-version "1.8.0"
7084 "Version of JavaScript supported, plus minor js2 version.")
7085
7086 (defmacro js2-record-face (face)
7087 "Record a style run of FACE for the current token."
7088 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7089
7090 (defsubst js2-node-end (n)
7091 "Computes the absolute end of node N.
7092 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7093 is only true until the node is added to its parent; i.e., while parsing."
7094 (+ (js2-node-pos n)
7095 (js2-node-len n)))
7096
7097 (defsubst js2-record-comment ()
7098 "Record a comment in `js2-scanned-comments'."
7099 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7100 :format js2-ts-comment-type)
7101 js2-scanned-comments)
7102 (when js2-parse-ide-mode
7103 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7104 'font-lock-doc-face
7105 'font-lock-comment-face))
7106 (when (memq js2-ts-comment-type '(html preprocessor))
7107 ;; Tell cc-engine the bounds of the comment.
7108 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7109
7110 ;; This function is called depressingly often, so it should be fast.
7111 ;; Most of the time it's looking at the same token it peeked before.
7112 (defsubst js2-peek-token ()
7113 "Returns the next token without consuming it.
7114 If previous token was consumed, calls scanner to get new token.
7115 If previous token was -not- consumed, returns it (idempotent).
7116
7117 This function will not return a newline (js2-EOL) - instead, it
7118 gobbles newlines until it finds a non-newline token, and flags
7119 that token as appearing just after a newline.
7120
7121 This function will also not return a js2-COMMENT. Instead, it
7122 records comments found in `js2-scanned-comments'. If the token
7123 returned by this function immediately follows a jsdoc comment,
7124 the token is flagged as such.
7125
7126 Note that this function always returned the un-flagged token!
7127 The flags, if any, are saved in `js2-current-flagged-token'."
7128 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7129 js2-current-token ; most common case - return already-peeked token
7130 (let ((tt (js2-get-token)) ; call scanner
7131 saw-eol
7132 face)
7133 ;; process comments and whitespace
7134 (while (or (= tt js2-EOL)
7135 (= tt js2-COMMENT))
7136 (if (= tt js2-EOL)
7137 (setq saw-eol t)
7138 (setq saw-eol nil)
7139 (if js2-record-comments
7140 (js2-record-comment)))
7141 (setq tt (js2-get-token))) ; call scanner
7142 (setq js2-current-token tt
7143 js2-current-flagged-token (if saw-eol
7144 (logior tt js2-ti-after-eol)
7145 tt))
7146 ;; perform lexical fontification as soon as token is scanned
7147 (when js2-parse-ide-mode
7148 (cond
7149 ((minusp tt)
7150 (js2-record-face 'js2-error-face))
7151 ((setq face (aref js2-kwd-tokens tt))
7152 (js2-record-face face))
7153 ((and (= tt js2-NAME)
7154 (equal js2-ts-string "undefined"))
7155 (js2-record-face 'font-lock-constant-face))))
7156 tt))) ; return unflagged token
7157
7158 (defsubst js2-peek-flagged-token ()
7159 "Returns the current token along with any flags set for it."
7160 (js2-peek-token)
7161 js2-current-flagged-token)
7162
7163 (defsubst js2-consume-token ()
7164 (setq js2-current-flagged-token js2-EOF))
7165
7166 (defsubst js2-next-token ()
7167 (prog1
7168 (js2-peek-token)
7169 (js2-consume-token)))
7170
7171 (defsubst js2-next-flagged-token ()
7172 (js2-peek-token)
7173 (prog1 js2-current-flagged-token
7174 (js2-consume-token)))
7175
7176 (defsubst js2-match-token (match)
7177 "Consume and return t if next token matches MATCH, a bytecode.
7178 Returns nil and consumes nothing if MATCH is not the next token."
7179 (if (/= (js2-peek-token) match)
7180 nil
7181 (js2-consume-token)
7182 t))
7183
7184 (defsubst js2-valid-prop-name-token (tt)
7185 (or (= tt js2-NAME)
7186 (and js2-allow-keywords-as-property-names
7187 (plusp tt)
7188 (aref js2-kwd-tokens tt))))
7189
7190 (defsubst js2-match-prop-name ()
7191 "Consume token and return t if next token is a valid property name.
7192 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7193 is non-nil and it's a keyword token."
7194 (if (js2-valid-prop-name-token (js2-peek-token))
7195 (progn
7196 (js2-consume-token)
7197 t)
7198 nil))
7199
7200 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7201 (if (js2-match-prop-name)
7202 t
7203 (js2-report-error msg-id nil pos len)
7204 nil))
7205
7206 (defsubst js2-peek-token-or-eol ()
7207 "Return js2-EOL if the current token immediately follows a newline.
7208 Else returns the current token. Used in situations where we don't
7209 consider certain token types valid if they are preceded by a newline.
7210 One example is the postfix ++ or -- operator, which has to be on the
7211 same line as its operand."
7212 (let ((tt (js2-peek-token)))
7213 ;; Check for last peeked token flags
7214 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7215 js2-EOL
7216 tt)))
7217
7218 (defsubst js2-set-check-for-label ()
7219 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7220 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7221
7222 (defsubst js2-must-match (token msg-id &optional pos len)
7223 "Match next token to token code TOKEN, or record a syntax error.
7224 MSG-ID is the error message to report if the match fails.
7225 Returns t on match, nil if no match."
7226 (if (js2-match-token token)
7227 t
7228 (js2-report-error msg-id nil pos len)
7229 nil))
7230
7231 (defsubst js2-inside-function ()
7232 (plusp js2-nesting-of-function))
7233
7234 (defsubst js2-set-requires-activation ()
7235 (if (js2-function-node-p js2-current-script-or-fn)
7236 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7237
7238 (defsubst js2-check-activation-name (name token)
7239 (when (js2-inside-function)
7240 ;; skip language-version 1.2 check from Rhino
7241 (if (or (string= "arguments" name)
7242 (and js2-compiler-activation-names ; only used in codegen
7243 (gethash name js2-compiler-activation-names)))
7244 (js2-set-requires-activation))))
7245
7246 (defsubst js2-set-is-generator ()
7247 (if (js2-function-node-p js2-current-script-or-fn)
7248 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7249
7250 (defsubst js2-must-have-xml ()
7251 (unless js2-compiler-xml-available
7252 (js2-report-error "msg.XML.not.available")))
7253
7254 (defsubst js2-push-scope (scope)
7255 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7256 (assert (js2-scope-p scope))
7257 (assert (null (js2-scope-parent-scope scope)))
7258 (assert (not (eq js2-current-scope scope)))
7259 (setf (js2-scope-parent-scope scope) js2-current-scope
7260 js2-current-scope scope))
7261
7262 (defsubst js2-pop-scope ()
7263 (setq js2-current-scope
7264 (js2-scope-parent-scope js2-current-scope)))
7265
7266 (defsubst js2-enter-loop (loop-node)
7267 (push loop-node js2-loop-set)
7268 (push loop-node js2-loop-and-switch-set)
7269 (js2-push-scope loop-node)
7270 ;; Tell the current labeled statement (if any) its statement,
7271 ;; and set the jump target of the first label to the loop.
7272 ;; These are used in `js2-parse-continue' to verify that the
7273 ;; continue target is an actual labeled loop. (And for codegen.)
7274 (when js2-labeled-stmt
7275 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7276 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7277 js2-labeled-stmt))) loop-node)))
7278
7279 (defsubst js2-exit-loop ()
7280 (pop js2-loop-set)
7281 (pop js2-loop-and-switch-set)
7282 (js2-pop-scope))
7283
7284 (defsubst js2-enter-switch (switch-node)
7285 (push switch-node js2-loop-and-switch-set))
7286
7287 (defsubst js2-exit-switch ()
7288 (pop js2-loop-and-switch-set))
7289
7290 (defun js2-parse (&optional buf cb)
7291 "Tells the js2 parser to parse a region of JavaScript.
7292
7293 BUF is a buffer or buffer name containing the code to parse.
7294 Call `narrow-to-region' first to parse only part of the buffer.
7295
7296 The returned AST root node is given some additional properties:
7297 `node-count' - total number of nodes in the AST
7298 `buffer' - BUF. The buffer it refers to may change or be killed,
7299 so the value is not necessarily reliable.
7300
7301 An optional callback CB can be specified to report parsing
7302 progress. If `(functionp CB)' returns t, it will be called with
7303 the current line number once before parsing begins, then again
7304 each time the lexer reaches a new line number.
7305
7306 CB can also be a list of the form `(symbol cb ...)' to specify
7307 multiple callbacks with different criteria. Each symbol is a
7308 criterion keyword, and the following element is the callback to
7309 call
7310
7311 :line - called whenever the line number changes
7312 :token - called for each new token consumed
7313
7314 The list of criteria could be extended to include entering or
7315 leaving a statement, an expression, or a function definition."
7316 (if (and cb (not (functionp cb)))
7317 (error "criteria callbacks not yet implemented"))
7318 (let ((inhibit-point-motion-hooks t)
7319 (js2-compiler-xml-available (>= js2-language-version 160))
7320 ;; This is a recursive-descent parser, so give it a big stack.
7321 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7322 (max-specpdl-size (max max-specpdl-size 3000))
7323 (case-fold-search nil)
7324 ast)
7325 (message nil) ; clear any error message from previous parse
7326 (save-excursion
7327 (when buf (set-buffer buf))
7328 (setq js2-scanned-comments nil
7329 js2-parsed-errors nil
7330 js2-parsed-warnings nil
7331 js2-imenu-recorder nil
7332 js2-imenu-function-map nil
7333 js2-label-set nil)
7334 (js2-init-scanner)
7335 (setq ast (js2-with-unmodifying-text-property-changes
7336 (js2-do-parse)))
7337 (unless js2-ts-hit-eof
7338 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7339 (setf (js2-ast-root-errors ast) js2-parsed-errors
7340 (js2-ast-root-warnings ast) js2-parsed-warnings)
7341 ;; if we didn't find any declarations, put a dummy in this list so we
7342 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7343 (unless js2-imenu-recorder
7344 (setq js2-imenu-recorder 'empty))
7345 (run-hooks 'js2-parse-finished-hook)
7346 ast)))
7347
7348 ;; Corresponds to Rhino's Parser.parse() method.
7349 (defun js2-do-parse ()
7350 "Parse current buffer starting from current point.
7351 Scanner should be initialized."
7352 (let ((pos js2-ts-cursor)
7353 (end js2-ts-cursor) ; in case file is empty
7354 root n tt)
7355 ;; initialize buffer-local parsing vars
7356 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7357 js2-current-script-or-fn root
7358 js2-current-scope root
7359 js2-current-flagged-token js2-EOF
7360 js2-nesting-of-function 0
7361 js2-labeled-stmt nil
7362 js2-recorded-identifiers nil) ; for js2-highlight
7363 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7364 (if (= tt js2-FUNCTION)
7365 (progn
7366 (js2-consume-token)
7367 (setq n (js2-parse-function (if js2-called-by-compile-function
7368 'FUNCTION_EXPRESSION
7369 'FUNCTION_STATEMENT))))
7370 ;; not a function - parse a statement
7371 (setq n (js2-parse-statement)))
7372 ;; add function or statement to script
7373 (setq end (js2-node-end n))
7374 (js2-block-node-push root n))
7375 ;; add comments to root in lexical order
7376 (when js2-scanned-comments
7377 ;; if we find a comment beyond end of normal kids, use its end
7378 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7379 (dolist (comment js2-scanned-comments)
7380 (push comment (js2-ast-root-comments root))
7381 (js2-node-add-children root comment)))
7382 (setf (js2-node-len root) (- end pos))
7383 ;; Give extensions a chance to muck with things before highlighting starts.
7384 (let ((js2-additional-externs js2-additional-externs))
7385 (dolist (callback js2-post-parse-callbacks)
7386 (funcall callback))
7387 (js2-highlight-undeclared-vars))
7388 root))
7389
7390 (defun js2-function-parser ()
7391 (js2-consume-token)
7392 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7393
7394 (defun js2-parse-function-closure-body (fn-node)
7395 "Parse a JavaScript 1.8 function closure body."
7396 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7397 (if js2-ts-hit-eof
7398 (js2-report-error "msg.no.brace.body" nil
7399 (js2-node-pos fn-node)
7400 (- js2-ts-cursor (js2-node-pos fn-node)))
7401 (js2-node-add-children fn-node
7402 (setf (js2-function-node-body fn-node)
7403 (js2-parse-expr t))))))
7404
7405 (defun js2-parse-function-body (fn-node)
7406 (js2-must-match js2-LC "msg.no.brace.body"
7407 (js2-node-pos fn-node)
7408 (- js2-ts-cursor (js2-node-pos fn-node)))
7409 (let ((pos js2-token-beg) ; LC position
7410 (pn (make-js2-block-node)) ; starts at LC position
7411 tt
7412 end)
7413 (incf js2-nesting-of-function)
7414 (unwind-protect
7415 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7416 (= tt js2-EOF)
7417 (= tt js2-RC)))
7418 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7419 (js2-parse-statement)
7420 (js2-consume-token)
7421 (js2-parse-function 'FUNCTION_STATEMENT))))
7422 (decf js2-nesting-of-function))
7423 (setq end js2-token-end) ; assume no curly and leave at current token
7424 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7425 (setq end js2-token-end))
7426 (setf (js2-node-pos pn) pos
7427 (js2-node-len pn) (- end pos))
7428 (setf (js2-function-node-body fn-node) pn)
7429 (js2-node-add-children fn-node pn)
7430 pn))
7431
7432 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7433 "Declare and fontify destructuring parameters inside NODE.
7434 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7435 (cond
7436 ((js2-name-node-p node)
7437 (let (leftpos)
7438 (js2-define-symbol decl-type (js2-name-node-name node)
7439 node ignore-not-in-block)
7440 (when face
7441 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7442 (+ leftpos (js2-node-len node))
7443 face 'record))))
7444 ((js2-object-node-p node)
7445 (dolist (elem (js2-object-node-elems node))
7446 (js2-define-destruct-symbols
7447 (if (js2-object-prop-node-p elem)
7448 (js2-object-prop-node-right elem)
7449 ;; abbreviated destructuring {a, b}
7450 elem)
7451 decl-type face ignore-not-in-block)))
7452 ((js2-array-node-p node)
7453 (dolist (elem (js2-array-node-elems node))
7454 (when elem
7455 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7456 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7457 (js2-node-len node)))))
7458
7459 (defun js2-parse-function-params (fn-node pos)
7460 (if (js2-match-token js2-RP)
7461 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7462 (let (params len param)
7463 (loop for tt = (js2-peek-token)
7464 do
7465 (cond
7466 ;; destructuring param
7467 ((or (= tt js2-LB) (= tt js2-LC))
7468 (setq param (js2-parse-primary-expr-lhs))
7469 (js2-define-destruct-symbols param
7470 js2-LP
7471 'js2-function-param-face)
7472 (push param params))
7473 ;; simple name
7474 (t
7475 (js2-must-match js2-NAME "msg.no.parm")
7476 (js2-record-face 'js2-function-param-face)
7477 (setq param (js2-create-name-node))
7478 (js2-define-symbol js2-LP js2-ts-string param)
7479 (push param params)))
7480 while
7481 (js2-match-token js2-COMMA))
7482 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7483 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7484 (dolist (p params)
7485 (js2-node-add-children fn-node p)
7486 (push p (js2-function-node-params fn-node))))))
7487
7488 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7489 "Possibly show inconsistent-return warning.
7490 Last token scanned is the close-curly for the function body."
7491 (when (and js2-mode-show-strict-warnings
7492 js2-strict-inconsistent-return-warning
7493 (not (js2-has-consistent-return-usage
7494 (js2-function-node-body fn-node))))
7495 ;; Have it extend from close-curly to bol or beginning of block.
7496 (let ((pos (save-excursion
7497 (goto-char js2-token-end)
7498 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7499 (point-at-bol))))
7500 (end js2-token-end))
7501 (if (plusp (js2-name-node-length name))
7502 (js2-add-strict-warning "msg.no.return.value"
7503 (js2-name-node-name name) pos end)
7504 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7505
7506 (defun js2-parse-function (function-type)
7507 "Function parser. FUNCTION-TYPE is a symbol."
7508 (let ((pos js2-token-beg) ; start of 'function' keyword
7509 name
7510 name-beg
7511 name-end
7512 fn-node
7513 lp
7514 (synthetic-type function-type)
7515 member-expr-node)
7516 ;; parse function name, expression, or non-name (anonymous)
7517 (cond
7518 ;; function foo(...)
7519 ((js2-match-token js2-NAME)
7520 (setq name (js2-create-name-node t)
7521 name-beg js2-token-beg
7522 name-end js2-token-end)
7523 (unless (js2-match-token js2-LP)
7524 (when js2-allow-member-expr-as-function-name
7525 ;; function foo.bar(...)
7526 (setq member-expr-node name
7527 name nil
7528 member-expr-node (js2-parse-member-expr-tail
7529 nil member-expr-node)))
7530 (js2-must-match js2-LP "msg.no.paren.parms")))
7531 ((js2-match-token js2-LP)
7532 nil) ; anonymous function: leave name as null
7533 (t
7534 ;; function random-member-expr(...)
7535 (when js2-allow-member-expr-as-function-name
7536 ;; Note that memberExpr can not start with '(' like
7537 ;; in function (1+2).toString(), because 'function (' already
7538 ;; processed as anonymous function
7539 (setq member-expr-node (js2-parse-member-expr)))
7540 (js2-must-match js2-LP "msg.no.paren.parms")))
7541 (if (= js2-current-token js2-LP) ; eventually matched LP?
7542 (setq lp js2-token-beg))
7543 (if member-expr-node
7544 (progn
7545 (setq synthetic-type 'FUNCTION_EXPRESSION)
7546 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7547 (if name
7548 (js2-set-face name-beg name-end
7549 'font-lock-function-name-face 'record)))
7550 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7551 (plusp (js2-name-node-length name)))
7552 ;; Function statements define a symbol in the enclosing scope
7553 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7554 (setf fn-node (make-js2-function-node :pos pos
7555 :name name
7556 :form function-type
7557 :lp (if lp (- lp pos))))
7558 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7559 ;; 1. Nested functions are not affected by the dynamic scope flag
7560 ;; as dynamic scope is already a parent of their scope.
7561 ;; 2. Functions defined under the with statement also immune to
7562 ;; this setup, in which case dynamic scope is ignored in favor
7563 ;; of the with object.
7564 (setf (js2-function-node-ignore-dynamic fn-node) t))
7565 ;; dynamically bind all the per-function variables
7566 (let ((js2-current-script-or-fn fn-node)
7567 (js2-current-scope fn-node)
7568 (js2-nesting-of-with 0)
7569 (js2-end-flags 0)
7570 js2-label-set
7571 js2-loop-set
7572 js2-loop-and-switch-set)
7573 (js2-parse-function-params fn-node pos)
7574 (if (and (>= js2-language-version 180)
7575 (/= (js2-peek-token) js2-LC))
7576 (js2-parse-function-closure-body fn-node)
7577 (js2-parse-function-body fn-node))
7578 (if name
7579 (js2-node-add-children fn-node name))
7580 (js2-check-inconsistent-return-warning fn-node name)
7581 ;; Function expressions define a name only in the body of the
7582 ;; function, and only if not hidden by a parameter name
7583 (if (and name
7584 (eq synthetic-type 'FUNCTION_EXPRESSION)
7585 (null (js2-scope-get-symbol js2-current-scope
7586 (js2-name-node-name name))))
7587 (js2-define-symbol js2-FUNCTION
7588 (js2-name-node-name name)
7589 fn-node))
7590 (if (and name
7591 (not (eq function-type 'FUNCTION_EXPRESSION)))
7592 (js2-record-imenu-functions fn-node)))
7593 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7594 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7595 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7596 ;; We wait until after parsing the function to set its parent scope,
7597 ;; since `js2-define-symbol' needs the defining-scope check to stop
7598 ;; at the function boundary when checking for redeclarations.
7599 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7600 fn-node))
7601
7602 (defun js2-parse-statements (&optional parent)
7603 "Parse a statement list. Last token consumed must be js2-LC.
7604
7605 PARENT can be a `js2-block-node', in which case the statements are
7606 appended to PARENT. Otherwise a new `js2-block-node' is created
7607 and returned.
7608
7609 This function does not match the closing js2-RC: the caller
7610 matches the RC so it can provide a suitable error message if not
7611 matched. This means it's up to the caller to set the length of
7612 the node to include the closing RC. The node start pos is set to
7613 the absolute buffer start position, and the caller should fix it
7614 up to be relative to the parent node. All children of this block
7615 node are given relative start positions and correct lengths."
7616 (let ((pn (or parent (make-js2-block-node)))
7617 tt)
7618 (setf (js2-node-pos pn) js2-token-beg)
7619 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7620 (/= tt js2-RC))
7621 (js2-block-node-push pn (js2-parse-statement)))
7622 pn))
7623
7624 (defun js2-parse-statement ()
7625 (let (tt pn beg end)
7626 ;; coarse-grained user-interrupt check - needs work
7627 (and js2-parse-interruptable-p
7628 (zerop (% (incf js2-parse-stmt-count)
7629 js2-statements-per-pause))
7630 (input-pending-p)
7631 (throw 'interrupted t))
7632 (setq pn (js2-statement-helper))
7633 ;; no-side-effects warning check
7634 (unless (js2-node-has-side-effects pn)
7635 (setq end (js2-node-end pn))
7636 (save-excursion
7637 (goto-char end)
7638 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7639 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7640 pn))
7641
7642 ;; These correspond to the switch cases in Parser.statementHelper
7643 (defconst js2-parsers
7644 (let ((parsers (make-vector js2-num-tokens
7645 #'js2-parse-expr-stmt)))
7646 (aset parsers js2-BREAK #'js2-parse-break)
7647 (aset parsers js2-CONST #'js2-parse-const-var)
7648 (aset parsers js2-CONTINUE #'js2-parse-continue)
7649 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7650 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7651 (aset parsers js2-DO #'js2-parse-do)
7652 (aset parsers js2-FOR #'js2-parse-for)
7653 (aset parsers js2-FUNCTION #'js2-function-parser)
7654 (aset parsers js2-IF #'js2-parse-if)
7655 (aset parsers js2-LC #'js2-parse-block)
7656 (aset parsers js2-LET #'js2-parse-let-stmt)
7657 (aset parsers js2-NAME #'js2-parse-name-or-label)
7658 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7659 (aset parsers js2-SEMI #'js2-parse-semi)
7660 (aset parsers js2-SWITCH #'js2-parse-switch)
7661 (aset parsers js2-THROW #'js2-parse-throw)
7662 (aset parsers js2-TRY #'js2-parse-try)
7663 (aset parsers js2-VAR #'js2-parse-const-var)
7664 (aset parsers js2-WHILE #'js2-parse-while)
7665 (aset parsers js2-WITH #'js2-parse-with)
7666 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7667 parsers)
7668 "A vector mapping token types to parser functions.")
7669
7670 (defsubst js2-parse-warn-missing-semi (beg end)
7671 (and js2-mode-show-strict-warnings
7672 js2-strict-missing-semi-warning
7673 (js2-add-strict-warning
7674 "msg.missing.semi" nil
7675 ;; back up to beginning of statement or line
7676 (max beg (save-excursion
7677 (goto-char end)
7678 (point-at-bol)))
7679 end)))
7680
7681 (defconst js2-no-semi-insertion
7682 (list js2-IF
7683 js2-SWITCH
7684 js2-WHILE
7685 js2-DO
7686 js2-FOR
7687 js2-TRY
7688 js2-WITH
7689 js2-LC
7690 js2-ERROR
7691 js2-SEMI
7692 js2-FUNCTION)
7693 "List of tokens that don't do automatic semicolon insertion.")
7694
7695 (defconst js2-autoinsert-semi-and-warn
7696 (list js2-ERROR js2-EOF js2-RC))
7697
7698 (defun js2-statement-helper ()
7699 (let* ((tt (js2-peek-token))
7700 (first-tt tt)
7701 (beg js2-token-beg)
7702 (parser (if (= tt js2-ERROR)
7703 #'js2-parse-semi
7704 (aref js2-parsers tt)))
7705 pn
7706 tt-flagged)
7707 ;; If the statement is set, then it's been told its label by now.
7708 (and js2-labeled-stmt
7709 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7710 (setq js2-labeled-stmt nil))
7711 (setq pn (funcall parser))
7712 ;; Don't do auto semi insertion for certain statement types.
7713 (unless (or (memq first-tt js2-no-semi-insertion)
7714 (js2-labeled-stmt-node-p pn))
7715 (js2-auto-insert-semicolon pn))
7716 pn))
7717
7718 (defun js2-auto-insert-semicolon (pn)
7719 (let* ((tt-flagged (js2-peek-flagged-token))
7720 (tt (logand tt-flagged js2-clear-ti-mask))
7721 (pos (js2-node-pos pn)))
7722 (cond
7723 ((= tt js2-SEMI)
7724 ;; Consume ';' as a part of expression
7725 (js2-consume-token)
7726 ;; extend the node bounds to include the semicolon.
7727 (setf (js2-node-len pn) (- js2-token-end pos)))
7728 ((memq tt js2-autoinsert-semi-and-warn)
7729 ;; Autoinsert ;
7730 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7731 (t
7732 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7733 ;; Report error if no EOL or autoinsert ';' otherwise
7734 (js2-report-error "msg.no.semi.stmt")
7735 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7736
7737 (defun js2-parse-condition ()
7738 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7739 The parens are discarded and the expression node is returned.
7740 The `pos' field of the return value is set to an absolute position
7741 that must be fixed up by the caller.
7742 Return value is a list (EXPR LP RP), with absolute paren positions."
7743 (let (pn lp rp)
7744 (if (js2-must-match js2-LP "msg.no.paren.cond")
7745 (setq lp js2-token-beg))
7746 (setq pn (js2-parse-expr))
7747 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7748 (setq rp js2-token-beg))
7749 ;; Report strict warning on code like "if (a = 7) ..."
7750 (if (and js2-strict-cond-assign-warning
7751 (js2-assign-node-p pn))
7752 (js2-add-strict-warning "msg.equal.as.assign" nil
7753 (js2-node-pos pn)
7754 (+ (js2-node-pos pn)
7755 (js2-node-len pn))))
7756 (list pn lp rp)))
7757
7758 (defun js2-parse-if ()
7759 "Parser for if-statement. Last matched token must be js2-IF."
7760 (let ((pos js2-token-beg)
7761 cond
7762 if-true
7763 if-false
7764 else-pos
7765 end
7766 pn)
7767 (js2-consume-token)
7768 (setq cond (js2-parse-condition)
7769 if-true (js2-parse-statement)
7770 if-false (if (js2-match-token js2-ELSE)
7771 (progn
7772 (setq else-pos (- js2-token-beg pos))
7773 (js2-parse-statement)))
7774 end (js2-node-end (or if-false if-true))
7775 pn (make-js2-if-node :pos pos
7776 :len (- end pos)
7777 :condition (car cond)
7778 :then-part if-true
7779 :else-part if-false
7780 :else-pos else-pos
7781 :lp (js2-relpos (second cond) pos)
7782 :rp (js2-relpos (third cond) pos)))
7783 (js2-node-add-children pn (car cond) if-true if-false)
7784 pn))
7785
7786 (defun js2-parse-switch ()
7787 "Parser for if-statement. Last matched token must be js2-SWITCH."
7788 (let ((pos js2-token-beg)
7789 tt
7790 pn
7791 discriminant
7792 has-default
7793 case-expr
7794 case-node
7795 case-pos
7796 cases
7797 stmt
7798 lp
7799 rp)
7800 (js2-consume-token)
7801 (if (js2-must-match js2-LP "msg.no.paren.switch")
7802 (setq lp js2-token-beg))
7803 (setq discriminant (js2-parse-expr)
7804 pn (make-js2-switch-node :discriminant discriminant
7805 :pos pos
7806 :lp (js2-relpos lp pos)))
7807 (js2-node-add-children pn discriminant)
7808 (js2-enter-switch pn)
7809 (unwind-protect
7810 (progn
7811 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7812 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7813 (js2-must-match js2-LC "msg.no.brace.switch")
7814 (catch 'break
7815 (while t
7816 (setq tt (js2-next-token)
7817 case-pos js2-token-beg)
7818 (cond
7819 ((= tt js2-RC)
7820 (setf (js2-node-len pn) (- js2-token-end pos))
7821 (throw 'break nil)) ; done
7822 ((= tt js2-CASE)
7823 (setq case-expr (js2-parse-expr))
7824 (js2-must-match js2-COLON "msg.no.colon.case"))
7825 ((= tt js2-DEFAULT)
7826 (if has-default
7827 (js2-report-error "msg.double.switch.default"))
7828 (setq has-default t
7829 case-expr nil)
7830 (js2-must-match js2-COLON "msg.no.colon.case"))
7831 (t
7832 (js2-report-error "msg.bad.switch")
7833 (throw 'break nil)))
7834 (setq case-node (make-js2-case-node :pos case-pos
7835 :len (- js2-token-end case-pos)
7836 :expr case-expr))
7837 (js2-node-add-children case-node case-expr)
7838 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7839 (/= tt js2-CASE)
7840 (/= tt js2-DEFAULT)
7841 (/= tt js2-EOF))
7842 (setf stmt (js2-parse-statement)
7843 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7844 (js2-block-node-push case-node stmt))
7845 (push case-node cases)))
7846 ;; add cases last, as pushing reverses the order to be correct
7847 (dolist (kid cases)
7848 (js2-node-add-children pn kid)
7849 (push kid (js2-switch-node-cases pn)))
7850 pn) ; return value
7851 (js2-exit-switch))))
7852
7853 (defun js2-parse-while ()
7854 "Parser for while-statement. Last matched token must be js2-WHILE."
7855 (let ((pos js2-token-beg)
7856 (pn (make-js2-while-node))
7857 cond
7858 body)
7859 (js2-consume-token)
7860 (js2-enter-loop pn)
7861 (unwind-protect
7862 (progn
7863 (setf cond (js2-parse-condition)
7864 (js2-while-node-condition pn) (car cond)
7865 body (js2-parse-statement)
7866 (js2-while-node-body pn) body
7867 (js2-node-len pn) (- (js2-node-end body) pos)
7868 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7869 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7870 (js2-node-add-children pn body (car cond)))
7871 (js2-exit-loop))
7872 pn))
7873
7874 (defun js2-parse-do ()
7875 "Parser for do-statement. Last matched token must be js2-DO."
7876 (let ((pos js2-token-beg)
7877 (pn (make-js2-do-node))
7878 cond
7879 body
7880 end)
7881 (js2-consume-token)
7882 (js2-enter-loop pn)
7883 (unwind-protect
7884 (progn
7885 (setq body (js2-parse-statement))
7886 (js2-must-match js2-WHILE "msg.no.while.do")
7887 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7888 cond (js2-parse-condition)
7889 (js2-do-node-condition pn) (car cond)
7890 (js2-do-node-body pn) body
7891 end js2-ts-cursor
7892 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7893 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7894 (js2-node-add-children pn (car cond) body))
7895 (js2-exit-loop))
7896 ;; Always auto-insert semicolon to follow SpiderMonkey:
7897 ;; It is required by ECMAScript but is ignored by the rest of
7898 ;; world; see bug 238945
7899 (if (js2-match-token js2-SEMI)
7900 (setq end js2-ts-cursor))
7901 (setf (js2-node-len pn) (- end pos))
7902 pn))
7903
7904 (defun js2-parse-for ()
7905 "Parser for for-statement. Last matched token must be js2-FOR.
7906 Parses for, for-in, and for each-in statements."
7907 (let ((for-pos js2-token-beg)
7908 pn
7909 is-for-each
7910 is-for-in
7911 in-pos
7912 each-pos
7913 tmp-pos
7914 init ; Node init is also foo in 'foo in object'
7915 cond ; Node cond is also object in 'foo in object'
7916 incr ; 3rd section of for-loop initializer
7917 body
7918 tt
7919 lp
7920 rp)
7921 (js2-consume-token)
7922 ;; See if this is a for each () instead of just a for ()
7923 (when (js2-match-token js2-NAME)
7924 (if (string= "each" js2-ts-string)
7925 (progn
7926 (setq is-for-each t
7927 each-pos (- js2-token-beg for-pos)) ; relative
7928 (js2-record-face 'font-lock-keyword-face))
7929 (js2-report-error "msg.no.paren.for")))
7930 (if (js2-must-match js2-LP "msg.no.paren.for")
7931 (setq lp (- js2-token-beg for-pos)))
7932 (setq tt (js2-peek-token))
7933 ;; 'for' makes local scope
7934 (js2-push-scope (make-js2-scope))
7935 (unwind-protect
7936 ;; parse init clause
7937 (let ((js2-in-for-init t)) ; set as dynamic variable
7938 (cond
7939 ((= tt js2-SEMI)
7940 (setq init (make-js2-empty-expr-node)))
7941 ((or (= tt js2-VAR) (= tt js2-LET))
7942 (js2-consume-token)
7943 (setq init (js2-parse-variables tt js2-token-beg)))
7944 (t
7945 (setq init (js2-parse-expr)))))
7946 (if (js2-match-token js2-IN)
7947 (setq is-for-in t
7948 in-pos (- js2-token-beg for-pos)
7949 ;; scope of iteration target object is not the scope we've created above.
7950 ;; stash current scope temporary.
7951 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7952 (js2-parse-expr))) ; object over which we're iterating
7953 ;; else ordinary for loop - parse cond and incr
7954 (js2-must-match js2-SEMI "msg.no.semi.for")
7955 (setq cond (if (= (js2-peek-token) js2-SEMI)
7956 (make-js2-empty-expr-node) ; no loop condition
7957 (js2-parse-expr)))
7958 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7959 (setq tmp-pos js2-token-end
7960 incr (if (= (js2-peek-token) js2-RP)
7961 (make-js2-empty-expr-node :pos tmp-pos)
7962 (js2-parse-expr))))
7963 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7964 (setq rp (- js2-token-beg for-pos)))
7965 (if (not is-for-in)
7966 (setq pn (make-js2-for-node :init init
7967 :condition cond
7968 :update incr
7969 :lp lp
7970 :rp rp))
7971 ;; cond could be null if 'in obj' got eaten by the init node.
7972 (if (js2-infix-node-p init)
7973 ;; it was (foo in bar) instead of (var foo in bar)
7974 (setq cond (js2-infix-node-right init)
7975 init (js2-infix-node-left init))
7976 (if (and (js2-var-decl-node-p init)
7977 (> (length (js2-var-decl-node-kids init)) 1))
7978 (js2-report-error "msg.mult.index")))
7979 (setq pn (make-js2-for-in-node :iterator init
7980 :object cond
7981 :in-pos in-pos
7982 :foreach-p is-for-each
7983 :each-pos each-pos
7984 :lp lp
7985 :rp rp)))
7986 (unwind-protect
7987 (progn
7988 (js2-enter-loop pn)
7989 ;; We have to parse the body -after- creating the loop node,
7990 ;; so that the loop node appears in the js2-loop-set, allowing
7991 ;; break/continue statements to find the enclosing loop.
7992 (setf body (js2-parse-statement)
7993 (js2-loop-node-body pn) body
7994 (js2-node-pos pn) for-pos
7995 (js2-node-len pn) (- (js2-node-end body) for-pos))
7996 (js2-node-add-children pn init cond incr body))
7997 ;; finally
7998 (js2-exit-loop))
7999 (js2-pop-scope))
8000 pn))
8001
8002 (defun js2-parse-try ()
8003 "Parser for try-statement. Last matched token must be js2-TRY."
8004 (let ((try-pos js2-token-beg)
8005 try-end
8006 try-block
8007 catch-blocks
8008 finally-block
8009 saw-default-catch
8010 peek
8011 param
8012 catch-cond
8013 catch-node
8014 guard-kwd
8015 catch-pos
8016 finally-pos
8017 pn
8018 block
8019 lp
8020 rp)
8021 (js2-consume-token)
8022 (if (/= (js2-peek-token) js2-LC)
8023 (js2-report-error "msg.no.brace.try"))
8024 (setq try-block (js2-parse-statement)
8025 try-end (js2-node-end try-block)
8026 peek (js2-peek-token))
8027 (cond
8028 ((= peek js2-CATCH)
8029 (while (js2-match-token js2-CATCH)
8030 (setq catch-pos js2-token-beg
8031 guard-kwd nil
8032 catch-cond nil
8033 lp nil
8034 rp nil)
8035 (if saw-default-catch
8036 (js2-report-error "msg.catch.unreachable"))
8037 (if (js2-must-match js2-LP "msg.no.paren.catch")
8038 (setq lp (- js2-token-beg catch-pos)))
8039 (js2-push-scope (make-js2-scope))
8040 (let ((tt (js2-peek-token)))
8041 (cond
8042 ;; destructuring pattern
8043 ;; catch ({ message, file }) { ... }
8044 ((or (= tt js2-LB) (= tt js2-LC))
8045 (setq param
8046 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8047 js2-LET nil)))
8048 ;; simple name
8049 (t
8050 (js2-must-match js2-NAME "msg.bad.catchcond")
8051 (setq param (js2-create-name-node))
8052 (js2-define-symbol js2-LET js2-ts-string param))))
8053 ;; pattern guard
8054 (if (js2-match-token js2-IF)
8055 (setq guard-kwd (- js2-token-beg catch-pos)
8056 catch-cond (js2-parse-expr))
8057 (setq saw-default-catch t))
8058 (if (js2-must-match js2-RP "msg.bad.catchcond")
8059 (setq rp (- js2-token-beg catch-pos)))
8060 (js2-must-match js2-LC "msg.no.brace.catchblock")
8061 (setq block (js2-parse-statements)
8062 try-end (js2-node-end block)
8063 catch-node (make-js2-catch-node :pos catch-pos
8064 :param param
8065 :guard-expr catch-cond
8066 :guard-kwd guard-kwd
8067 :block block
8068 :lp lp
8069 :rp rp))
8070 (js2-pop-scope)
8071 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8072 (setq try-end js2-token-beg))
8073 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8074 (js2-node-len catch-node) (- try-end catch-pos))
8075 (js2-node-add-children catch-node param catch-cond block)
8076 (push catch-node catch-blocks)))
8077 ((/= peek js2-FINALLY)
8078 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8079 (js2-node-pos try-block)
8080 (- (setq try-end (js2-node-end try-block))
8081 (js2-node-pos try-block)))))
8082 (when (js2-match-token js2-FINALLY)
8083 (setq finally-pos js2-token-beg
8084 block (js2-parse-statement)
8085 try-end (js2-node-end block)
8086 finally-block (make-js2-finally-node :pos finally-pos
8087 :len (- try-end finally-pos)
8088 :body block))
8089 (js2-node-add-children finally-block block))
8090 (setq pn (make-js2-try-node :pos try-pos
8091 :len (- try-end try-pos)
8092 :try-block try-block
8093 :finally-block finally-block))
8094 (js2-node-add-children pn try-block finally-block)
8095 ;; push them onto the try-node, which reverses and corrects their order
8096 (dolist (cb catch-blocks)
8097 (js2-node-add-children pn cb)
8098 (push cb (js2-try-node-catch-clauses pn)))
8099 pn))
8100
8101 (defun js2-parse-throw ()
8102 "Parser for throw-statement. Last matched token must be js2-THROW."
8103 (let ((pos js2-token-beg)
8104 expr
8105 pn)
8106 (js2-consume-token)
8107 (if (= (js2-peek-token-or-eol) js2-EOL)
8108 ;; ECMAScript does not allow new lines before throw expression,
8109 ;; see bug 256617
8110 (js2-report-error "msg.bad.throw.eol"))
8111 (setq expr (js2-parse-expr)
8112 pn (make-js2-throw-node :pos pos
8113 :len (- (js2-node-end expr) pos)
8114 :expr expr))
8115 (js2-node-add-children pn expr)
8116 pn))
8117
8118 (defsubst js2-match-jump-label-name (label-name)
8119 "If break/continue specified a label, return that label's labeled stmt.
8120 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8121 does not match an existing label, reports an error and returns nil."
8122 (let ((bundle (cdr (assoc label-name js2-label-set))))
8123 (if (null bundle)
8124 (js2-report-error "msg.undef.label"))
8125 bundle))
8126
8127 (defun js2-parse-break ()
8128 "Parser for break-statement. Last matched token must be js2-BREAK."
8129 (let ((pos js2-token-beg)
8130 (end js2-token-end)
8131 break-target ; statement to break from
8132 break-label ; in "break foo", name-node representing the foo
8133 labels ; matching labeled statement to break to
8134 pn)
8135 (js2-consume-token) ; `break'
8136 (when (eq (js2-peek-token-or-eol) js2-NAME)
8137 (js2-consume-token)
8138 (setq break-label (js2-create-name-node)
8139 end (js2-node-end break-label)
8140 ;; matchJumpLabelName only matches if there is one
8141 labels (js2-match-jump-label-name js2-ts-string)
8142 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8143 (unless (or break-target break-label)
8144 ;; no break target specified - try for innermost enclosing loop/switch
8145 (if (null js2-loop-and-switch-set)
8146 (unless break-label
8147 (js2-report-error "msg.bad.break" nil pos (length "break")))
8148 (setq break-target (car js2-loop-and-switch-set))))
8149 (setq pn (make-js2-break-node :pos pos
8150 :len (- end pos)
8151 :label break-label
8152 :target break-target))
8153 (js2-node-add-children pn break-label) ; but not break-target
8154 pn))
8155
8156 (defun js2-parse-continue ()
8157 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8158 (let ((pos js2-token-beg)
8159 (end js2-token-end)
8160 label ; optional user-specified label, a `js2-name-node'
8161 labels ; current matching labeled stmt, if any
8162 target ; the `js2-loop-node' target of this continue stmt
8163 pn)
8164 (js2-consume-token) ; `continue'
8165 (when (= (js2-peek-token-or-eol) js2-NAME)
8166 (js2-consume-token)
8167 (setq label (js2-create-name-node)
8168 end (js2-node-end label)
8169 ;; matchJumpLabelName only matches if there is one
8170 labels (js2-match-jump-label-name js2-ts-string)))
8171 (cond
8172 ((null labels) ; no current label to go to
8173 (if (null js2-loop-set) ; no loop to continue to
8174 (js2-report-error "msg.continue.outside" nil pos
8175 (length "continue"))
8176 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8177 (t
8178 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8179 (setq target (js2-labeled-stmt-node-stmt labels))
8180 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8181 (setq pn (make-js2-continue-node :pos pos
8182 :len (- end pos)
8183 :label label
8184 :target target))
8185 (js2-node-add-children pn label) ; but not target - it's not our child
8186 pn))
8187
8188 (defun js2-parse-with ()
8189 "Parser for with-statement. Last matched token must be js2-WITH."
8190 (js2-consume-token)
8191 (let ((pos js2-token-beg)
8192 obj body pn lp rp)
8193 (if (js2-must-match js2-LP "msg.no.paren.with")
8194 (setq lp js2-token-beg))
8195 (setq obj (js2-parse-expr))
8196 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8197 (setq rp js2-token-beg))
8198 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8199 (setq body (js2-parse-statement)))
8200 (setq pn (make-js2-with-node :pos pos
8201 :len (- (js2-node-end body) pos)
8202 :object obj
8203 :body body
8204 :lp (js2-relpos lp pos)
8205 :rp (js2-relpos rp pos)))
8206 (js2-node-add-children pn obj body)
8207 pn))
8208
8209 (defun js2-parse-const-var ()
8210 "Parser for var- or const-statement.
8211 Last matched token must be js2-CONST or js2-VAR."
8212 (let ((tt (js2-peek-token))
8213 (pos js2-token-beg)
8214 expr
8215 pn)
8216 (js2-consume-token)
8217 (setq expr (js2-parse-variables tt js2-token-beg)
8218 pn (make-js2-expr-stmt-node :pos pos
8219 :len (- (js2-node-end expr) pos)
8220 :expr expr))
8221 (js2-node-add-children pn expr)
8222 pn))
8223
8224 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8225 (let ((pn (make-js2-expr-stmt-node :pos pos
8226 :len (js2-node-len expr)
8227 :type (if (js2-inside-function)
8228 js2-EXPR_VOID
8229 js2-EXPR_RESULT)
8230 :expr expr)))
8231 (if add-child
8232 (js2-node-add-children pn expr))
8233 pn))
8234
8235 (defun js2-parse-let-stmt ()
8236 "Parser for let-statement. Last matched token must be js2-LET."
8237 (js2-consume-token)
8238 (let ((pos js2-token-beg)
8239 expr
8240 pn)
8241 (if (= (js2-peek-token) js2-LP)
8242 ;; let expression in statement context
8243 (setq expr (js2-parse-let pos 'statement)
8244 pn (js2-wrap-with-expr-stmt pos expr t))
8245 ;; else we're looking at a statement like let x=6, y=7;
8246 (setf expr (js2-parse-variables js2-LET pos)
8247 pn (js2-wrap-with-expr-stmt pos expr t)
8248 (js2-node-type pn) js2-EXPR_RESULT))
8249 pn))
8250
8251 (defun js2-parse-ret-yield ()
8252 (js2-parse-return-or-yield (js2-peek-token) nil))
8253
8254 (defconst js2-parse-return-stmt-enders
8255 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8256
8257 (defsubst js2-now-all-set (before after mask)
8258 "Return whether or not the bits in the mask have changed to all set.
8259 BEFORE is bits before change, AFTER is bits after change, and MASK is
8260 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8261 but not BEFORE."
8262 (and (/= (logand before mask) mask)
8263 (= (logand after mask) mask)))
8264
8265 (defun js2-parse-return-or-yield (tt expr-context)
8266 (let ((pos js2-token-beg)
8267 (end js2-token-end)
8268 (before js2-end-flags)
8269 (inside-function (js2-inside-function))
8270 e
8271 ret
8272 name)
8273 (unless inside-function
8274 (js2-report-error (if (eq tt js2-RETURN)
8275 "msg.bad.return"
8276 "msg.bad.yield")))
8277 (js2-consume-token)
8278 ;; This is ugly, but we don't want to require a semicolon.
8279 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8280 (setq e (js2-parse-expr)
8281 end (js2-node-end e)))
8282 (cond
8283 ((eq tt js2-RETURN)
8284 (js2-set-flag js2-end-flags (if (null e)
8285 js2-end-returns
8286 js2-end-returns-value))
8287 (setq ret (make-js2-return-node :pos pos
8288 :len (- end pos)
8289 :retval e))
8290 (js2-node-add-children ret e)
8291 ;; See if we need a strict mode warning.
8292 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8293 ;; more thorough and accurate than this before/after flag check.
8294 ;; E.g. if there's a finally-block that always returns, we shouldn't
8295 ;; show a warning generated by inconsistent returns in the catch blocks.
8296 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8297 ;; so we know which returns/yields to highlight, and we should get rid of
8298 ;; all the checking in `js2-parse-return-or-yield'.
8299 (if (and js2-strict-inconsistent-return-warning
8300 (js2-now-all-set before js2-end-flags
8301 (logior js2-end-returns js2-end-returns-value)))
8302 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8303 (t
8304 (unless (js2-inside-function)
8305 (js2-report-error "msg.bad.yield"))
8306 (js2-set-flag js2-end-flags js2-end-yields)
8307 (setq ret (make-js2-yield-node :pos pos
8308 :len (- end pos)
8309 :value e))
8310 (js2-node-add-children ret e)
8311 (unless expr-context
8312 (setq e ret
8313 ret (js2-wrap-with-expr-stmt pos e t))
8314 (js2-set-requires-activation)
8315 (js2-set-is-generator))))
8316 ;; see if we are mixing yields and value returns.
8317 (when (and inside-function
8318 (js2-now-all-set before js2-end-flags
8319 (logior js2-end-yields js2-end-returns-value)))
8320 (setq name (js2-function-name js2-current-script-or-fn))
8321 (if (zerop (length name))
8322 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8323 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8324 ret))
8325
8326 (defun js2-parse-debugger ()
8327 (js2-consume-token)
8328 (make-js2-keyword-node :type js2-DEBUGGER))
8329
8330 (defun js2-parse-block ()
8331 "Parser for a curly-delimited statement block.
8332 Last token matched must be js2-LC."
8333 (let ((pos js2-token-beg)
8334 (pn (make-js2-scope)))
8335 (js2-consume-token)
8336 (js2-push-scope pn)
8337 (unwind-protect
8338 (progn
8339 (js2-parse-statements pn)
8340 (js2-must-match js2-RC "msg.no.brace.block")
8341 (setf (js2-node-len pn) (- js2-token-end pos)))
8342 (js2-pop-scope))
8343 pn))
8344
8345 ;; for js2-ERROR too, to have a node for error recovery to work on
8346 (defun js2-parse-semi ()
8347 "Parse a statement or handle an error.
8348 Last matched token is js-SEMI or js-ERROR."
8349 (let ((tt (js2-peek-token)) pos len)
8350 (js2-consume-token)
8351 (if (eq tt js2-SEMI)
8352 (make-js2-empty-expr-node :len 1)
8353 (setq pos js2-token-beg
8354 len (- js2-token-beg pos))
8355 (js2-report-error "msg.syntax" nil pos len)
8356 (make-js2-error-node :pos pos :len len))))
8357
8358 (defun js2-parse-default-xml-namespace ()
8359 "Parse a `default xml namespace = <expr>' e4x statement."
8360 (let ((pos js2-token-beg)
8361 end len expr unary es)
8362 (js2-consume-token)
8363 (js2-must-have-xml)
8364 (js2-set-requires-activation)
8365 (setq len (- js2-ts-cursor pos))
8366 (unless (and (js2-match-token js2-NAME)
8367 (string= js2-ts-string "xml"))
8368 (js2-report-error "msg.bad.namespace" nil pos len))
8369 (unless (and (js2-match-token js2-NAME)
8370 (string= js2-ts-string "namespace"))
8371 (js2-report-error "msg.bad.namespace" nil pos len))
8372 (unless (js2-match-token js2-ASSIGN)
8373 (js2-report-error "msg.bad.namespace" nil pos len))
8374 (setq expr (js2-parse-expr)
8375 end (js2-node-end expr)
8376 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8377 :pos pos
8378 :len (- end pos)
8379 :operand expr))
8380 (js2-node-add-children unary expr)
8381 (make-js2-expr-stmt-node :pos pos
8382 :len (- end pos)
8383 :expr unary)))
8384
8385 (defun js2-record-label (label bundle)
8386 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8387 (js2-consume-token)
8388 (let ((name (js2-label-node-name label))
8389 labeled-stmt
8390 dup)
8391 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8392 ;; flag both labels if possible when used in editing mode
8393 (if (and js2-parse-ide-mode
8394 (setq dup (js2-get-label-by-name labeled-stmt name)))
8395 (js2-report-error "msg.dup.label" nil
8396 (js2-node-abs-pos dup) (js2-node-len dup)))
8397 (js2-report-error "msg.dup.label" nil
8398 (js2-node-pos label) (js2-node-len label)))
8399 (js2-labeled-stmt-node-add-label bundle label)
8400 (js2-node-add-children bundle label)
8401 ;; Add one reference to the bundle per label in `js2-label-set'
8402 (push (cons name bundle) js2-label-set)))
8403
8404 (defun js2-parse-name-or-label ()
8405 "Parser for identifier or label. Last token matched must be js2-NAME.
8406 Called when we found a name in a statement context. If it's a label, we gather
8407 up any following labels and the next non-label statement into a
8408 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8409 expression and return it wrapped in a `js2-expr-stmt-node'."
8410 (let ((pos js2-token-beg)
8411 (end js2-token-end)
8412 expr
8413 stmt
8414 pn
8415 bundle
8416 (continue t))
8417 ;; set check for label and call down to `js2-parse-primary-expr'
8418 (js2-set-check-for-label)
8419 (setq expr (js2-parse-expr))
8420 (if (/= (js2-node-type expr) js2-LABEL)
8421 ;; Parsed non-label expression - wrap with expression stmt.
8422 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8423 ;; else parsed a label
8424 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8425 (js2-record-label expr bundle)
8426 ;; look for more labels
8427 (while (and continue (= (js2-peek-token) js2-NAME))
8428 (js2-set-check-for-label)
8429 (setq expr (js2-parse-expr))
8430 (if (/= (js2-node-type expr) js2-LABEL)
8431 (progn
8432 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8433 continue nil)
8434 (js2-auto-insert-semicolon stmt))
8435 (js2-record-label expr bundle)))
8436 ;; no more labels; now parse the labeled statement
8437 (unwind-protect
8438 (unless stmt
8439 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8440 (setq stmt (js2-statement-helper))))
8441 ;; remove the labels for this statement from the global set
8442 (dolist (label (js2-labeled-stmt-node-labels bundle))
8443 (setq js2-label-set (remove label js2-label-set))))
8444 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8445 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8446 (js2-node-add-children bundle stmt)
8447 bundle)))
8448
8449 (defun js2-parse-expr-stmt ()
8450 "Default parser in statement context, if no recognized statement found."
8451 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8452
8453 (defun js2-parse-variables (decl-type pos)
8454 "Parse a comma-separated list of variable declarations.
8455 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8456
8457 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8458 For 'var' or 'const', the keyword should be the token last scanned.
8459
8460 POS is the position where the node should start. It's sometimes the
8461 var/const/let keyword, and other times the beginning of the first token
8462 in the first variable declaration.
8463
8464 Returns the parsed `js2-var-decl-node' expression node."
8465 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8466 :pos pos))
8467 destructuring
8468 kid-pos
8469 tt
8470 init
8471 name
8472 end
8473 nbeg nend
8474 vi
8475 (continue t))
8476 ;; Example:
8477 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8478 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8479 ;; var {a, b} = baz;
8480 (while continue
8481 (setq destructuring nil
8482 name nil
8483 tt (js2-peek-token)
8484 kid-pos js2-token-beg
8485 end js2-token-end
8486 init nil)
8487 (if (or (= tt js2-LB) (= tt js2-LC))
8488 ;; Destructuring assignment, e.g., var [a, b] = ...
8489 (setq destructuring (js2-parse-primary-expr-lhs)
8490 end (js2-node-end destructuring))
8491 ;; Simple variable name
8492 (when (js2-must-match js2-NAME "msg.bad.var")
8493 (setq name (js2-create-name-node)
8494 nbeg js2-token-beg
8495 nend js2-token-end
8496 end nend)
8497 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8498 (when (js2-match-token js2-ASSIGN)
8499 (setq init (js2-parse-assign-expr)
8500 end (js2-node-end init))
8501 (if (and js2-parse-ide-mode
8502 (or (js2-object-node-p init)
8503 (js2-function-node-p init)))
8504 (js2-record-imenu-functions init name)))
8505 (when name
8506 (js2-set-face nbeg nend (if (js2-function-node-p init)
8507 'font-lock-function-name-face
8508 'font-lock-variable-name-face)
8509 'record))
8510 (setq vi (make-js2-var-init-node :pos kid-pos
8511 :len (- end kid-pos)
8512 :type decl-type))
8513 (if destructuring
8514 (progn
8515 (if (and (null init) (not js2-in-for-init))
8516 (js2-report-error "msg.destruct.assign.no.init"))
8517 (js2-define-destruct-symbols destructuring
8518 decl-type
8519 'font-lock-variable-name-face)
8520 (setf (js2-var-init-node-target vi) destructuring))
8521 (setf (js2-var-init-node-target vi) name))
8522 (setf (js2-var-init-node-initializer vi) init)
8523 (js2-node-add-children vi name destructuring init)
8524 (js2-block-node-push result vi)
8525 (unless (js2-match-token js2-COMMA)
8526 (setq continue nil)))
8527 (setf (js2-node-len result) (- end pos))
8528 result))
8529
8530 (defun js2-parse-let (pos &optional stmt-p)
8531 "Parse a let expression or statement.
8532 A let-expression is of the form `let (vars) expr'.
8533 A let-statment is of the form `let (vars) {statements}'.
8534 The third form of let is a variable declaration list, handled
8535 by `js2-parse-variables'."
8536 (let ((pn (make-js2-let-node :pos pos))
8537 beg vars body)
8538 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8539 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8540 (js2-push-scope pn)
8541 (unwind-protect
8542 (progn
8543 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8544 (if (js2-must-match js2-RP "msg.no.paren.let")
8545 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8546 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8547 ;; let statement
8548 (progn
8549 (js2-consume-token)
8550 (setf beg js2-token-beg ; position stmt at LC
8551 body (js2-parse-statements))
8552 (js2-must-match js2-RC "msg.no.curly.let")
8553 (setf (js2-node-len body) (- js2-token-end beg)
8554 (js2-node-len pn) (- js2-token-end pos)
8555 (js2-let-node-body pn) body
8556 (js2-node-type pn) js2-LET))
8557 ;; let expression
8558 (setf body (js2-parse-expr)
8559 (js2-node-len pn) (- (js2-node-end body) pos)
8560 (js2-let-node-body pn) body))
8561 (js2-node-add-children pn vars body))
8562 (js2-pop-scope))
8563 pn))
8564
8565 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8566 (js2-scope-put-symbol (or scope js2-current-scope)
8567 name
8568 (make-js2-symbol decl-type name node)))
8569
8570 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8571 "Define a symbol in the current scope.
8572 If NODE is non-nil, it is the AST node associated with the symbol."
8573 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8574 (symbol (if defining-scope
8575 (js2-scope-get-symbol defining-scope name)))
8576 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8577 (cond
8578 ((and symbol ; already defined
8579 (or (= sdt js2-CONST) ; old version is const
8580 (= decl-type js2-CONST) ; new version is const
8581 ;; two let-bound vars in this block have same name
8582 (and (= sdt js2-LET)
8583 (eq defining-scope js2-current-scope))))
8584 (js2-report-error
8585 (cond
8586 ((= sdt js2-CONST) "msg.const.redecl")
8587 ((= sdt js2-LET) "msg.let.redecl")
8588 ((= sdt js2-VAR) "msg.var.redecl")
8589 ((= sdt js2-FUNCTION) "msg.function.redecl")
8590 (t "msg.parm.redecl"))
8591 name))
8592 ((= decl-type js2-LET)
8593 (if (and (not ignore-not-in-block)
8594 (or (= (js2-node-type js2-current-scope) js2-IF)
8595 (js2-loop-node-p js2-current-scope)))
8596 (js2-report-error "msg.let.decl.not.in.block")
8597 (js2-define-new-symbol decl-type name node)))
8598 ((or (= decl-type js2-VAR)
8599 (= decl-type js2-CONST)
8600 (= decl-type js2-FUNCTION))
8601 (if symbol
8602 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8603 (js2-add-strict-warning "msg.var.redecl" name)
8604 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8605 (js2-add-strict-warning "msg.var.hides.arg" name)))
8606 (js2-define-new-symbol decl-type name node
8607 js2-current-script-or-fn)))
8608 ((= decl-type js2-LP)
8609 (if symbol
8610 ;; must be duplicate parameter. Second parameter hides the
8611 ;; first, so go ahead and add the second pararameter
8612 (js2-report-warning "msg.dup.parms" name))
8613 (js2-define-new-symbol decl-type name node))
8614 (t (js2-code-bug)))))
8615
8616 (defun js2-parse-expr (&optional oneshot)
8617 (let* ((pn (js2-parse-assign-expr))
8618 (pos (js2-node-pos pn))
8619 left
8620 right
8621 op-pos)
8622 (while (and (not oneshot)
8623 (js2-match-token js2-COMMA))
8624 (setq op-pos (- js2-token-beg pos)) ; relative
8625 (if (= (js2-peek-token) js2-YIELD)
8626 (js2-report-error "msg.yield.parenthesized"))
8627 (setq right (js2-parse-assign-expr)
8628 left pn
8629 pn (make-js2-infix-node :type js2-COMMA
8630 :pos pos
8631 :len (- js2-ts-cursor pos)
8632 :op-pos op-pos
8633 :left left
8634 :right right))
8635 (js2-node-add-children pn left right))
8636 pn))
8637
8638 (defun js2-parse-assign-expr ()
8639 (let ((tt (js2-peek-token))
8640 (pos js2-token-beg)
8641 pn
8642 left
8643 right
8644 op-pos)
8645 (if (= tt js2-YIELD)
8646 (js2-parse-return-or-yield tt t)
8647 ;; not yield - parse assignment expression
8648 (setq pn (js2-parse-cond-expr)
8649 tt (js2-peek-token))
8650 (when (and (<= js2-first-assign tt)
8651 (<= tt js2-last-assign))
8652 ;; tt express assignment (=, |=, ^=, ..., %=)
8653 (js2-consume-token)
8654 (setq op-pos (- js2-token-beg pos) ; relative
8655 left pn
8656 right (js2-parse-assign-expr)
8657 pn (make-js2-assign-node :type tt
8658 :pos pos
8659 :len (- (js2-node-end right) pos)
8660 :op-pos op-pos
8661 :left left
8662 :right right))
8663 (when js2-parse-ide-mode
8664 (js2-highlight-assign-targets pn left right)
8665 (if (or (js2-function-node-p right)
8666 (js2-object-node-p right))
8667 (js2-record-imenu-functions right left)))
8668 ;; do this last so ide checks above can use absolute positions
8669 (js2-node-add-children pn left right))
8670 pn)))
8671
8672 (defun js2-parse-cond-expr ()
8673 (let ((pos js2-token-beg)
8674 (pn (js2-parse-or-expr))
8675 test-expr
8676 if-true
8677 if-false
8678 q-pos
8679 c-pos)
8680 (when (js2-match-token js2-HOOK)
8681 (setq q-pos (- js2-token-beg pos)
8682 if-true (js2-parse-assign-expr))
8683 (js2-must-match js2-COLON "msg.no.colon.cond")
8684 (setq c-pos (- js2-token-beg pos)
8685 if-false (js2-parse-assign-expr)
8686 test-expr pn
8687 pn (make-js2-cond-node :pos pos
8688 :len (- (js2-node-end if-false) pos)
8689 :test-expr test-expr
8690 :true-expr if-true
8691 :false-expr if-false
8692 :q-pos q-pos
8693 :c-pos c-pos))
8694 (js2-node-add-children pn test-expr if-true if-false))
8695 pn))
8696
8697 (defun js2-make-binary (type left parser)
8698 "Helper for constructing a binary-operator AST node.
8699 LEFT is the left-side-expression, already parsed, and the
8700 binary operator should have just been matched.
8701 PARSER is a function to call to parse the right operand,
8702 or a `js2-node' struct if it has already been parsed."
8703 (let* ((pos (js2-node-pos left))
8704 (op-pos (- js2-token-beg pos))
8705 (right (if (js2-node-p parser)
8706 parser
8707 (funcall parser)))
8708 (pn (make-js2-infix-node :type type
8709 :pos pos
8710 :len (- (js2-node-end right) pos)
8711 :op-pos op-pos
8712 :left left
8713 :right right)))
8714 (js2-node-add-children pn left right)
8715 pn))
8716
8717 (defun js2-parse-or-expr ()
8718 (let ((pn (js2-parse-and-expr)))
8719 (when (js2-match-token js2-OR)
8720 (setq pn (js2-make-binary js2-OR
8721 pn
8722 'js2-parse-or-expr)))
8723 pn))
8724
8725 (defun js2-parse-and-expr ()
8726 (let ((pn (js2-parse-bit-or-expr)))
8727 (when (js2-match-token js2-AND)
8728 (setq pn (js2-make-binary js2-AND
8729 pn
8730 'js2-parse-and-expr)))
8731 pn))
8732
8733 (defun js2-parse-bit-or-expr ()
8734 (let ((pn (js2-parse-bit-xor-expr)))
8735 (while (js2-match-token js2-BITOR)
8736 (setq pn (js2-make-binary js2-BITOR
8737 pn
8738 'js2-parse-bit-xor-expr)))
8739 pn))
8740
8741 (defun js2-parse-bit-xor-expr ()
8742 (let ((pn (js2-parse-bit-and-expr)))
8743 (while (js2-match-token js2-BITXOR)
8744 (setq pn (js2-make-binary js2-BITXOR
8745 pn
8746 'js2-parse-bit-and-expr)))
8747 pn))
8748
8749 (defun js2-parse-bit-and-expr ()
8750 (let ((pn (js2-parse-eq-expr)))
8751 (while (js2-match-token js2-BITAND)
8752 (setq pn (js2-make-binary js2-BITAND
8753 pn
8754 'js2-parse-eq-expr)))
8755 pn))
8756
8757 (defconst js2-parse-eq-ops
8758 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8759
8760 (defun js2-parse-eq-expr ()
8761 (let ((pn (js2-parse-rel-expr))
8762 tt)
8763 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8764 (js2-consume-token)
8765 (setq pn (js2-make-binary tt
8766 pn
8767 'js2-parse-rel-expr)))
8768 pn))
8769
8770 (defconst js2-parse-rel-ops
8771 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8772
8773 (defun js2-parse-rel-expr ()
8774 (let ((pn (js2-parse-shift-expr))
8775 (continue t)
8776 tt)
8777 (while continue
8778 (setq tt (js2-peek-token))
8779 (cond
8780 ((and js2-in-for-init (= tt js2-IN))
8781 (setq continue nil))
8782 ((memq tt js2-parse-rel-ops)
8783 (js2-consume-token)
8784 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8785 (t
8786 (setq continue nil))))
8787 pn))
8788
8789 (defconst js2-parse-shift-ops
8790 (list js2-LSH js2-URSH js2-RSH))
8791
8792 (defun js2-parse-shift-expr ()
8793 (let ((pn (js2-parse-add-expr))
8794 tt
8795 (continue t))
8796 (while continue
8797 (setq tt (js2-peek-token))
8798 (if (memq tt js2-parse-shift-ops)
8799 (progn
8800 (js2-consume-token)
8801 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8802 (setq continue nil)))
8803 pn))
8804
8805 (defun js2-parse-add-expr ()
8806 (let ((pn (js2-parse-mul-expr))
8807 tt
8808 (continue t))
8809 (while continue
8810 (setq tt (js2-peek-token))
8811 (if (or (= tt js2-ADD) (= tt js2-SUB))
8812 (progn
8813 (js2-consume-token)
8814 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8815 (setq continue nil)))
8816 pn))
8817
8818 (defconst js2-parse-mul-ops
8819 (list js2-MUL js2-DIV js2-MOD))
8820
8821 (defun js2-parse-mul-expr ()
8822 (let ((pn (js2-parse-unary-expr))
8823 tt
8824 (continue t))
8825 (while continue
8826 (setq tt (js2-peek-token))
8827 (if (memq tt js2-parse-mul-ops)
8828 (progn
8829 (js2-consume-token)
8830 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8831 (setq continue nil)))
8832 pn))
8833
8834 (defsubst js2-make-unary (type parser &rest args)
8835 "Make a unary node of type TYPE.
8836 PARSER is either a node (for postfix operators) or a function to call
8837 to parse the operand (for prefix operators)."
8838 (let* ((pos js2-token-beg)
8839 (postfix (js2-node-p parser))
8840 (expr (if postfix
8841 parser
8842 (apply parser args)))
8843 end
8844 pn)
8845 (if postfix ; e.g. i++
8846 (setq pos (js2-node-pos expr)
8847 end js2-token-end)
8848 (setq end (js2-node-end expr)))
8849 (setq pn (make-js2-unary-node :type type
8850 :pos pos
8851 :len (- end pos)
8852 :operand expr))
8853 (js2-node-add-children pn expr)
8854 pn))
8855
8856 (defconst js2-incrementable-node-types
8857 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8858 "Node types that can be the operand of a ++ or -- operator.")
8859
8860 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8861 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8862 js2-incrementable-node-types)
8863 (js2-report-error (if (= tt js2-INC)
8864 "msg.bad.incr"
8865 "msg.bad.decr")
8866 nil beg (- end beg))))
8867
8868 (defun js2-parse-unary-expr ()
8869 (let ((tt (js2-peek-token))
8870 pn expr beg end)
8871 (cond
8872 ((or (= tt js2-VOID)
8873 (= tt js2-NOT)
8874 (= tt js2-BITNOT)
8875 (= tt js2-TYPEOF))
8876 (js2-consume-token)
8877 (js2-make-unary tt 'js2-parse-unary-expr))
8878 ((= tt js2-ADD)
8879 (js2-consume-token)
8880 ;; Convert to special POS token in decompiler and parse tree
8881 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8882 ((= tt js2-SUB)
8883 (js2-consume-token)
8884 ;; Convert to special NEG token in decompiler and parse tree
8885 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8886 ((or (= tt js2-INC)
8887 (= tt js2-DEC))
8888 (js2-consume-token)
8889 (prog1
8890 (setq beg js2-token-beg
8891 end js2-token-end
8892 expr (js2-make-unary tt 'js2-parse-member-expr t))
8893 (js2-check-bad-inc-dec tt beg end expr)))
8894 ((= tt js2-DELPROP)
8895 (js2-consume-token)
8896 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8897 ((= tt js2-ERROR)
8898 (js2-consume-token)
8899 (make-js2-error-node)) ; try to continue
8900 ((and (= tt js2-LT)
8901 js2-compiler-xml-available)
8902 ;; XML stream encountered in expression.
8903 (js2-consume-token)
8904 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8905 (t
8906 (setq pn (js2-parse-member-expr t)
8907 ;; Don't look across a newline boundary for a postfix incop.
8908 tt (js2-peek-token-or-eol))
8909 (when (or (= tt js2-INC) (= tt js2-DEC))
8910 (js2-consume-token)
8911 (setf expr pn
8912 pn (js2-make-unary tt expr))
8913 (js2-node-set-prop pn 'postfix t)
8914 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8915 pn))))
8916
8917 (defun js2-parse-xml-initializer ()
8918 "Parse an E4X XML initializer.
8919 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8920 Then I'll postprocess the result, depending on whether we're in IDE
8921 mode or codegen mode, and generate the appropriate rewritten AST.
8922 IDE mode uses a rich AST that models the XML structure. Codegen mode
8923 just concatenates everything and makes a new XML or XMLList out of it."
8924 (let ((tt (js2-get-first-xml-token))
8925 pn-xml
8926 pn
8927 expr
8928 kids
8929 expr-pos
8930 (continue t)
8931 (first-token t))
8932 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8933 (js2-report-error "msg.syntax"))
8934 (setq pn-xml (make-js2-xml-node))
8935 (while continue
8936 (if first-token
8937 (setq first-token nil)
8938 (setq tt (js2-get-next-xml-token)))
8939 (cond
8940 ;; js2-XML means we found a {expr} in the XML stream.
8941 ;; The js2-ts-string is the XML up to the left-curly.
8942 ((= tt js2-XML)
8943 (push (make-js2-string-node :pos js2-token-beg
8944 :len (- js2-ts-cursor js2-token-beg))
8945 kids)
8946 (js2-must-match js2-LC "msg.syntax")
8947 (setq expr-pos js2-ts-cursor
8948 expr (if (eq (js2-peek-token) js2-RC)
8949 (make-js2-empty-expr-node :pos expr-pos)
8950 (js2-parse-expr)))
8951 (js2-must-match js2-RC "msg.syntax")
8952 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8953 :len (js2-node-len expr)
8954 :expr expr))
8955 (js2-node-add-children pn expr)
8956 (push pn kids))
8957 ;; a js2-XMLEND token means we hit the final close-tag.
8958 ((= tt js2-XMLEND)
8959 (push (make-js2-string-node :pos js2-token-beg
8960 :len (- js2-ts-cursor js2-token-beg))
8961 kids)
8962 (dolist (kid (nreverse kids))
8963 (js2-block-node-push pn-xml kid))
8964 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8965 (js2-node-pos pn-xml))
8966 continue nil))
8967 (t
8968 (js2-report-error "msg.syntax")
8969 (setq continue nil))))
8970 pn-xml))
8971
8972
8973 (defun js2-parse-argument-list ()
8974 "Parse an argument list and return it as a lisp list of nodes.
8975 Returns the list in reverse order. Consumes the right-paren token."
8976 (let (result)
8977 (unless (js2-match-token js2-RP)
8978 (loop do
8979 (if (= (js2-peek-token) js2-YIELD)
8980 (js2-report-error "msg.yield.parenthesized"))
8981 (push (js2-parse-assign-expr) result)
8982 while
8983 (js2-match-token js2-COMMA))
8984 (js2-must-match js2-RP "msg.no.paren.arg")
8985 result)))
8986
8987 (defun js2-parse-member-expr (&optional allow-call-syntax)
8988 (let ((tt (js2-peek-token))
8989 pn
8990 pos
8991 target
8992 args
8993 beg
8994 end
8995 init
8996 tail)
8997 (if (/= tt js2-NEW)
8998 (setq pn (js2-parse-primary-expr))
8999 ;; parse a 'new' expression
9000 (js2-consume-token)
9001 (setq pos js2-token-beg
9002 beg pos
9003 target (js2-parse-member-expr)
9004 end (js2-node-end target)
9005 pn (make-js2-new-node :pos pos
9006 :target target
9007 :len (- end pos)))
9008 (js2-node-add-children pn target)
9009 (when (js2-match-token js2-LP)
9010 ;; Add the arguments to pn, if any are supplied.
9011 (setf beg pos ; start of "new" keyword
9012 pos js2-token-beg
9013 args (nreverse (js2-parse-argument-list))
9014 (js2-new-node-args pn) args
9015 end js2-token-end
9016 (js2-new-node-lp pn) (- pos beg)
9017 (js2-new-node-rp pn) (- end 1 beg))
9018 (apply #'js2-node-add-children pn args))
9019 (when (and js2-allow-rhino-new-expr-initializer
9020 (js2-match-token js2-LC))
9021 (setf init (js2-parse-object-literal)
9022 end (js2-node-end init)
9023 (js2-new-node-initializer pn) init)
9024 (js2-node-add-children pn init))
9025 (setf (js2-node-len pn) (- end beg))) ; end outer if
9026 (js2-parse-member-expr-tail allow-call-syntax pn)))
9027
9028 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9029 "Parse a chain of property/array accesses or function calls.
9030 Includes parsing for E4X operators like `..' and `.@'.
9031 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9032 Returns an expression tree that includes PN, the parent node."
9033 (let ((beg (js2-node-pos pn))
9034 tt
9035 (continue t))
9036 (while continue
9037 (setq tt (js2-peek-token))
9038 (cond
9039 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9040 (setq pn (js2-parse-property-access tt pn)))
9041 ((= tt js2-DOTQUERY)
9042 (setq pn (js2-parse-dot-query pn)))
9043 ((= tt js2-LB)
9044 (setq pn (js2-parse-element-get pn)))
9045 ((= tt js2-LP)
9046 (if allow-call-syntax
9047 (setq pn (js2-parse-function-call pn))
9048 (setq continue nil)))
9049 (t
9050 (setq continue nil))))
9051 (if (>= js2-highlight-level 2)
9052 (js2-parse-highlight-member-expr-node pn))
9053 pn))
9054
9055 (defun js2-parse-dot-query (pn)
9056 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9057 Last token parsed must be `js2-DOTQUERY'."
9058 (let ((pos (js2-node-pos pn))
9059 op-pos
9060 expr
9061 end)
9062 (js2-consume-token)
9063 (js2-must-have-xml)
9064 (js2-set-requires-activation)
9065 (setq op-pos js2-token-beg
9066 expr (js2-parse-expr)
9067 end (js2-node-end expr)
9068 pn (make-js2-xml-dot-query-node :left pn
9069 :pos pos
9070 :op-pos op-pos
9071 :right expr))
9072 (js2-node-add-children pn
9073 (js2-xml-dot-query-node-left pn)
9074 (js2-xml-dot-query-node-right pn))
9075 (if (js2-must-match js2-RP "msg.no.paren")
9076 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9077 end js2-token-end))
9078 (setf (js2-node-len pn) (- end pos))
9079 pn))
9080
9081 (defun js2-parse-element-get (pn)
9082 "Parse an element-get expression, e.g. foo[bar].
9083 Last token parsed must be `js2-RB'."
9084 (let ((lb js2-token-beg)
9085 (pos (js2-node-pos pn))
9086 rb
9087 expr)
9088 (js2-consume-token)
9089 (setq expr (js2-parse-expr))
9090 (if (js2-must-match js2-RB "msg.no.bracket.index")
9091 (setq rb js2-token-beg))
9092 (setq pn (make-js2-elem-get-node :target pn
9093 :pos pos
9094 :element expr
9095 :lb (js2-relpos lb pos)
9096 :rb (js2-relpos rb pos)
9097 :len (- js2-token-end pos)))
9098 (js2-node-add-children pn
9099 (js2-elem-get-node-target pn)
9100 (js2-elem-get-node-element pn))
9101 pn))
9102
9103 (defun js2-parse-function-call (pn)
9104 (let (args
9105 (pos (js2-node-pos pn)))
9106 (js2-consume-token)
9107 (setq pn (make-js2-call-node :pos pos
9108 :target pn
9109 :lp (- js2-token-beg pos)))
9110 (js2-node-add-children pn (js2-call-node-target pn))
9111 ;; Add the arguments to pn, if any are supplied.
9112 (setf args (nreverse (js2-parse-argument-list))
9113 (js2-call-node-rp pn) (- js2-token-beg pos)
9114 (js2-call-node-args pn) args)
9115 (apply #'js2-node-add-children pn args)
9116 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9117 pn))
9118
9119 (defun js2-parse-property-access (tt pn)
9120 "Parse a property access, XML descendants access, or XML attr access."
9121 (let ((member-type-flags 0)
9122 (dot-pos js2-token-beg)
9123 (dot-len (if (= tt js2-DOTDOT) 2 1))
9124 name
9125 ref ; right side of . or .. operator
9126 result)
9127 (js2-consume-token)
9128 (when (= tt js2-DOTDOT)
9129 (js2-must-have-xml)
9130 (setq member-type-flags js2-descendants-flag))
9131 (if (not js2-compiler-xml-available)
9132 (progn
9133 (js2-must-match-prop-name "msg.no.name.after.dot")
9134 (setq name (js2-create-name-node t js2-GETPROP)
9135 result (make-js2-prop-get-node :left pn
9136 :pos js2-token-beg
9137 :right name
9138 :len (- js2-token-end
9139 js2-token-beg)))
9140 (js2-node-add-children result pn name)
9141 result)
9142 ;; otherwise look for XML operators
9143 (setf result (if (= tt js2-DOT)
9144 (make-js2-prop-get-node)
9145 (make-js2-infix-node :type js2-DOTDOT))
9146 (js2-node-pos result) (js2-node-pos pn)
9147 (js2-infix-node-op-pos result) dot-pos
9148 (js2-infix-node-left result) pn ; do this after setting position
9149 tt (js2-next-token))
9150 (cond
9151 ;; needed for generator.throw()
9152 ((= tt js2-THROW)
9153 (js2-save-name-token-data js2-token-beg "throw")
9154 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9155 ;; handles: name, ns::name, ns::*, ns::[expr]
9156 ((js2-valid-prop-name-token tt)
9157 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9158 ;; handles: *, *::name, *::*, *::[expr]
9159 ((= tt js2-MUL)
9160 (js2-save-name-token-data js2-token-beg "*")
9161 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9162 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9163 ((= tt js2-XMLATTR)
9164 (setq result (js2-parse-attribute-access)))
9165 (t
9166 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9167 (if ref
9168 (setf (js2-node-len result) (- (js2-node-end ref)
9169 (js2-node-pos result))
9170 (js2-infix-node-right result) ref))
9171 (if (js2-infix-node-p result)
9172 (js2-node-add-children result
9173 (js2-infix-node-left result)
9174 (js2-infix-node-right result)))
9175 result)))
9176
9177 (defun js2-parse-attribute-access ()
9178 "Parse an E4X XML attribute expression.
9179 This includes expressions of the forms:
9180
9181 @attr @ns::attr @ns::*
9182 @* @*::attr @*::*
9183 @[expr] @*::[expr] @ns::[expr]
9184
9185 Called if we peeked an '@' token."
9186 (let ((tt (js2-next-token))
9187 (at-pos js2-token-beg))
9188 (cond
9189 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9190 ((js2-valid-prop-name-token tt)
9191 (js2-parse-property-name at-pos js2-ts-string 0))
9192 ;; handles: @*, @*::name, @*::*, @*::[expr]
9193 ((= tt js2-MUL)
9194 (js2-save-name-token-data js2-token-beg "*")
9195 (js2-parse-property-name js2-token-beg "*" 0))
9196 ;; handles @[expr]
9197 ((= tt js2-LB)
9198 (js2-parse-xml-elem-ref at-pos))
9199 (t
9200 (js2-report-error "msg.no.name.after.xmlAttr")
9201 ;; Avoid cascaded errors that happen if we make an error node here.
9202 (js2-save-name-token-data js2-token-beg "")
9203 (js2-parse-property-name js2-token-beg "" 0)))))
9204
9205 (defun js2-parse-property-name (at-pos s member-type-flags)
9206 "Check if :: follows name in which case it becomes qualified name.
9207
9208 AT-POS is a natural number if we just read an '@' token, else nil.
9209 S is the name or string that was matched: an identifier, 'throw' or '*'.
9210 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9211
9212 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9213 operator, or the name is followed by ::. For a plain name, returns a
9214 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9215 (let ((pos (or at-pos js2-token-beg))
9216 colon-pos
9217 (name (js2-create-name-node t js2-current-token))
9218 ns
9219 tt
9220 ref
9221 pn)
9222 (catch 'return
9223 (when (js2-match-token js2-COLONCOLON)
9224 (setq ns name
9225 colon-pos js2-token-beg
9226 tt (js2-next-token))
9227 (cond
9228 ;; handles name::name
9229 ((js2-valid-prop-name-token tt)
9230 (setq name (js2-create-name-node)))
9231 ;; handles name::*
9232 ((= tt js2-MUL)
9233 (js2-save-name-token-data js2-token-beg "*")
9234 (setq name (js2-create-name-node)))
9235 ;; handles name::[expr]
9236 ((= tt js2-LB)
9237 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9238 (t
9239 (js2-report-error "msg.no.name.after.coloncolon"))))
9240 (if (and (null ns) (zerop member-type-flags))
9241 name
9242 (prog1
9243 (setq pn
9244 (make-js2-xml-prop-ref-node :pos pos
9245 :len (- (js2-node-end name) pos)
9246 :at-pos at-pos
9247 :colon-pos colon-pos
9248 :propname name))
9249 (js2-node-add-children pn name))))))
9250
9251 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9252 "Parse the [expr] portion of an xml element reference.
9253 For instance, @[expr], @*::[expr], or ns::[expr]."
9254 (let* ((lb js2-token-beg)
9255 (pos (or at-pos lb))
9256 rb
9257 (expr (js2-parse-expr))
9258 (end (js2-node-end expr))
9259 pn)
9260 (if (js2-must-match js2-RB "msg.no.bracket.index")
9261 (setq rb js2-token-beg
9262 end js2-token-end))
9263 (prog1
9264 (setq pn
9265 (make-js2-xml-elem-ref-node :pos pos
9266 :len (- end pos)
9267 :namespace namespace
9268 :colon-pos colon-pos
9269 :at-pos at-pos
9270 :expr expr
9271 :lb (js2-relpos lb pos)
9272 :rb (js2-relpos rb pos)))
9273 (js2-node-add-children pn namespace expr))))
9274
9275 (defsubst js2-parse-primary-expr-lhs ()
9276 (let ((js2-is-in-lhs t))
9277 (js2-parse-primary-expr)))
9278
9279 (defun js2-parse-primary-expr ()
9280 "Parses a literal (leaf) expression of some sort.
9281 Includes complex literals such as functions, object-literals,
9282 array-literals, array comprehensions and regular expressions."
9283 (let ((tt-flagged (js2-next-flagged-token))
9284 pn ; parent node (usually return value)
9285 tt
9286 px-pos ; paren-expr pos
9287 len
9288 flags ; regexp flags
9289 expr)
9290 (setq tt js2-current-token)
9291 (cond
9292 ((= tt js2-FUNCTION)
9293 (js2-parse-function 'FUNCTION_EXPRESSION))
9294 ((= tt js2-LB)
9295 (js2-parse-array-literal))
9296 ((= tt js2-LC)
9297 (js2-parse-object-literal))
9298 ((= tt js2-LET)
9299 (js2-parse-let js2-token-beg))
9300 ((= tt js2-LP)
9301 (setq px-pos js2-token-beg
9302 expr (js2-parse-expr))
9303 (js2-must-match js2-RP "msg.no.paren")
9304 (setq pn (make-js2-paren-node :pos px-pos
9305 :expr expr
9306 :len (- js2-token-end px-pos)))
9307 (js2-node-add-children pn (js2-paren-node-expr pn))
9308 pn)
9309 ((= tt js2-XMLATTR)
9310 (js2-must-have-xml)
9311 (js2-parse-attribute-access))
9312 ((= tt js2-NAME)
9313 (js2-parse-name tt-flagged tt))
9314 ((= tt js2-NUMBER)
9315 (make-js2-number-node))
9316 ((= tt js2-STRING)
9317 (prog1
9318 (make-js2-string-node)
9319 (js2-record-face 'font-lock-string-face)))
9320 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9321 ;; Got / or /= which in this context means a regexp literal
9322 (setq px-pos js2-token-beg)
9323 (js2-read-regexp tt)
9324 (setq flags js2-ts-regexp-flags
9325 js2-ts-regexp-flags nil)
9326 (prog1
9327 (make-js2-regexp-node :pos px-pos
9328 :len (- js2-ts-cursor px-pos)
9329 :value js2-ts-string
9330 :flags flags)
9331 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9332 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9333 ((or (= tt js2-NULL)
9334 (= tt js2-THIS)
9335 (= tt js2-FALSE)
9336 (= tt js2-TRUE))
9337 (make-js2-keyword-node :type tt))
9338 ((= tt js2-RESERVED)
9339 (js2-report-error "msg.reserved.id")
9340 (make-js2-name-node))
9341 ((= tt js2-ERROR)
9342 ;; the scanner or one of its subroutines reported the error.
9343 (make-js2-error-node))
9344 ((= tt js2-EOF)
9345 (setq px-pos (point-at-bol)
9346 len (- js2-ts-cursor px-pos))
9347 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9348 (make-js2-error-node :pos px-pos :len len))
9349 (t
9350 (js2-report-error "msg.syntax")
9351 (make-js2-error-node)))))
9352
9353 (defun js2-parse-name (tt-flagged tt)
9354 (let ((name js2-ts-string)
9355 (name-pos js2-token-beg)
9356 node)
9357 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9358 (= (js2-peek-token) js2-COLON))
9359 (prog1
9360 ;; Do not consume colon, it is used as unwind indicator
9361 ;; to return to statementHelper.
9362 (make-js2-label-node :pos name-pos
9363 :len (- js2-token-end name-pos)
9364 :name name)
9365 (js2-set-face name-pos
9366 js2-token-end
9367 'font-lock-variable-name-face 'record))
9368 ;; Otherwise not a label, just a name. Unfortunately peeking
9369 ;; the next token to check for a colon has biffed js2-token-beg
9370 ;; and js2-token-end. We store the name's bounds in buffer vars
9371 ;; and `js2-create-name-node' uses them.
9372 (js2-save-name-token-data name-pos name)
9373 (setq node (if js2-compiler-xml-available
9374 (js2-parse-property-name nil name 0)
9375 (js2-create-name-node 'check-activation)))
9376 (if js2-highlight-external-variables
9377 (js2-record-name-node node))
9378 node)))
9379
9380 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9381 (js2-add-strict-warning
9382 msg nil
9383 ;; back up from comma to beginning of line or array/objlit
9384 (max (if elems
9385 (js2-node-pos (car elems))
9386 pos)
9387 (save-excursion
9388 (goto-char comma-pos)
9389 (back-to-indentation)
9390 (point)))
9391 comma-pos))
9392
9393 (defun js2-parse-array-literal ()
9394 (let ((pos js2-token-beg)
9395 (end js2-token-end)
9396 (after-lb-or-comma t)
9397 after-comma
9398 tt
9399 elems
9400 pn
9401 (continue t))
9402 (unless js2-is-in-lhs
9403 (js2-push-scope (make-js2-scope))) ; for array comp
9404 (while continue
9405 (setq tt (js2-peek-token))
9406 (cond
9407 ;; comma
9408 ((= tt js2-COMMA)
9409 (js2-consume-token)
9410 (setq after-comma js2-token-end)
9411 (if (not after-lb-or-comma)
9412 (setq after-lb-or-comma t)
9413 (push nil elems)))
9414 ;; end of array
9415 ((or (= tt js2-RB)
9416 (= tt js2-EOF)) ; prevent infinite loop
9417 (if (= tt js2-EOF)
9418 (js2-report-error "msg.no.bracket.arg" nil pos)
9419 (js2-consume-token))
9420 (setq continue nil
9421 end js2-token-end
9422 pn (make-js2-array-node :pos pos
9423 :len (- js2-ts-cursor pos)
9424 :elems (nreverse elems)))
9425 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9426 (when (and after-comma (not js2-is-in-lhs))
9427 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9428 pos elems after-comma)))
9429 ;; destructuring binding
9430 (js2-is-in-lhs
9431 (push (if (or (= tt js2-LC)
9432 (= tt js2-LB)
9433 (= tt js2-NAME))
9434 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9435 (js2-parse-primary-expr-lhs)
9436 ;; invalid pattern
9437 (js2-consume-token)
9438 (js2-report-error "msg.bad.var")
9439 (make-js2-error-node))
9440 elems)
9441 (setq after-lb-or-comma nil
9442 after-comma nil))
9443 ;; array comp
9444 ((and (>= js2-language-version 170)
9445 (= tt js2-FOR) ; check for array comprehension
9446 (not after-lb-or-comma) ; "for" can't follow a comma
9447 elems ; must have at least 1 element
9448 (not (cdr elems))) ; but no 2nd element
9449 (setf continue nil
9450 pn (js2-parse-array-comprehension (car elems) pos)))
9451
9452 ;; another element
9453 (t
9454 (unless after-lb-or-comma
9455 (js2-report-error "msg.no.bracket.arg"))
9456 (push (js2-parse-assign-expr) elems)
9457 (setq after-lb-or-comma nil
9458 after-comma nil))))
9459 (unless js2-is-in-lhs
9460 (js2-pop-scope))
9461 pn))
9462
9463 (defun js2-parse-array-comprehension (expr pos)
9464 "Parse a JavaScript 1.7 Array Comprehension.
9465 EXPR is the first expression after the opening left-bracket.
9466 POS is the beginning of the LB token preceding EXPR.
9467 We should have just parsed the 'for' keyword before calling this function."
9468 (let (loops
9469 loop
9470 first
9471 prev
9472 filter
9473 if-pos
9474 result)
9475 (while (= (js2-peek-token) js2-FOR)
9476 (let ((prev (car loops))) ; rearrange scope chain
9477 (push (setq loop (js2-parse-array-comp-loop)) loops)
9478 (if prev ; each loop is parent scope to the next one
9479 (setf (js2-scope-parent-scope loop) prev)
9480 ; first loop takes expr scope's parent
9481 (setf (js2-scope-parent-scope (setq first loop))
9482 (js2-scope-parent-scope js2-current-scope)))))
9483 ;; set expr scope's parent to the last loop
9484 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9485 (when (= (js2-peek-token) js2-IF)
9486 (js2-consume-token)
9487 (setq if-pos (- js2-token-beg pos) ; relative
9488 filter (js2-parse-condition)))
9489 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9490 (setq result (make-js2-array-comp-node :pos pos
9491 :len (- js2-ts-cursor pos)
9492 :result expr
9493 :loops (nreverse loops)
9494 :filter (car filter)
9495 :lp (js2-relpos (second filter) pos)
9496 :rp (js2-relpos (third filter) pos)
9497 :if-pos if-pos))
9498 (apply #'js2-node-add-children result expr (car filter)
9499 (js2-array-comp-node-loops result))
9500 (setq js2-current-scope first) ; pop to the first loop
9501 result))
9502
9503 (defun js2-parse-array-comp-loop ()
9504 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9505 Last token peeked should be the initial FOR."
9506 (let ((pos js2-token-beg)
9507 (pn (make-js2-array-comp-loop-node))
9508 tt
9509 iter
9510 obj
9511 foreach-p
9512 in-pos
9513 each-pos
9514 lp
9515 rp)
9516 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9517 (js2-push-scope pn)
9518 (unwind-protect
9519 (progn
9520 (when (js2-match-token js2-NAME)
9521 (if (string= js2-ts-string "each")
9522 (progn
9523 (setq foreach-p t
9524 each-pos (- js2-token-beg pos)) ; relative
9525 (js2-record-face 'font-lock-keyword-face))
9526 (js2-report-error "msg.no.paren.for")))
9527 (if (js2-must-match js2-LP "msg.no.paren.for")
9528 (setq lp (- js2-token-beg pos)))
9529 (setq tt (js2-peek-token))
9530 (cond
9531 ((or (= tt js2-LB)
9532 (= tt js2-LC))
9533 ;; handle destructuring assignment
9534 (setq iter (js2-parse-primary-expr-lhs))
9535 (js2-define-destruct-symbols iter js2-LET
9536 'font-lock-variable-name-face t))
9537 ((js2-valid-prop-name-token tt)
9538 (js2-consume-token)
9539 (setq iter (js2-create-name-node)))
9540 (t
9541 (js2-report-error "msg.bad.var")))
9542 ;; Define as a let since we want the scope of the variable to
9543 ;; be restricted to the array comprehension
9544 (if (js2-name-node-p iter)
9545 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9546 (if (js2-must-match js2-IN "msg.in.after.for.name")
9547 (setq in-pos (- js2-token-beg pos)))
9548 (setq obj (js2-parse-expr))
9549 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9550 (setq rp (- js2-token-beg pos)))
9551 (setf (js2-node-pos pn) pos
9552 (js2-node-len pn) (- js2-ts-cursor pos)
9553 (js2-array-comp-loop-node-iterator pn) iter
9554 (js2-array-comp-loop-node-object pn) obj
9555 (js2-array-comp-loop-node-in-pos pn) in-pos
9556 (js2-array-comp-loop-node-each-pos pn) each-pos
9557 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9558 (js2-array-comp-loop-node-lp pn) lp
9559 (js2-array-comp-loop-node-rp pn) rp)
9560 (js2-node-add-children pn iter obj))
9561 (js2-pop-scope))
9562 pn))
9563
9564 (defun js2-parse-object-literal ()
9565 (let ((pos js2-token-beg)
9566 tt
9567 elems
9568 result
9569 after-comma
9570 (continue t))
9571 (while continue
9572 (setq tt (js2-peek-token))
9573 (cond
9574 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9575 ((or (js2-valid-prop-name-token tt)
9576 (= tt js2-STRING))
9577 (setq after-comma nil
9578 result (js2-parse-named-prop tt))
9579 (if (and (null result)
9580 (not js2-recover-from-parse-errors))
9581 (setq continue nil)
9582 (push result elems)))
9583 ;; {12: x} or {10.7: x}
9584 ((= tt js2-NUMBER)
9585 (js2-consume-token)
9586 (setq after-comma nil)
9587 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9588 ;; trailing comma
9589 ((= tt js2-RC)
9590 (setq continue nil)
9591 (if after-comma
9592 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9593 pos elems after-comma)))
9594 (t
9595 (js2-report-error "msg.bad.prop")
9596 (unless js2-recover-from-parse-errors
9597 (setq continue nil)))) ; end switch
9598 (if (js2-match-token js2-COMMA)
9599 (setq after-comma js2-token-end)
9600 (setq continue nil))) ; end loop
9601 (js2-must-match js2-RC "msg.no.brace.prop")
9602 (setq result (make-js2-object-node :pos pos
9603 :len (- js2-ts-cursor pos)
9604 :elems (nreverse elems)))
9605 (apply #'js2-node-add-children result (js2-object-node-elems result))
9606 result))
9607
9608 (defun js2-parse-named-prop (tt)
9609 "Parse a name, string, or getter/setter object property.
9610 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9611 (js2-consume-token)
9612 (let ((string-prop (and (= tt js2-STRING)
9613 (make-js2-string-node)))
9614 expr
9615 (ppos js2-token-beg)
9616 (pend js2-token-end)
9617 (name (js2-create-name-node))
9618 (prop js2-ts-string))
9619 (cond
9620 ;; getter/setter prop
9621 ((and (= tt js2-NAME)
9622 (= (js2-peek-token) js2-NAME)
9623 (or (string= prop "get")
9624 (string= prop "set")))
9625 (js2-consume-token)
9626 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9627 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9628 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9629 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9630 ;; abbreviated destructuring bind e.g., {a, b} = c;
9631 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9632 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9633 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9634 ;; assignment but it's difficult because it requires looking ahead of expression.
9635 ((and js2-is-in-lhs
9636 (= tt js2-NAME)
9637 (let ((ctk (js2-peek-token)))
9638 (or (= ctk js2-COMMA)
9639 (= ctk js2-RC)
9640 (js2-valid-prop-name-token ctk))))
9641 name)
9642 ;; regular prop
9643 (t
9644 (prog1
9645 (setq expr (js2-parse-plain-property (or string-prop name)))
9646 (js2-set-face ppos pend
9647 (if (js2-function-node-p
9648 (js2-object-prop-node-right expr))
9649 'font-lock-function-name-face
9650 'font-lock-variable-name-face)
9651 'record))))))
9652
9653 (defun js2-parse-plain-property (prop)
9654 "Parse a non-getter/setter property in an object literal.
9655 PROP is the node representing the property: a number, name or string."
9656 (js2-must-match js2-COLON "msg.no.colon.prop")
9657 (let* ((pos (js2-node-pos prop))
9658 (colon (- js2-token-beg pos))
9659 (expr (js2-parse-assign-expr))
9660 (result (make-js2-object-prop-node
9661 :pos pos
9662 ;; don't include last consumed token in length
9663 :len (- (+ (js2-node-pos expr)
9664 (js2-node-len expr))
9665 pos)
9666 :left prop
9667 :right expr
9668 :op-pos colon)))
9669 (js2-node-add-children result prop expr)
9670 result))
9671
9672 (defun js2-parse-getter-setter-prop (pos prop get-p)
9673 "Parse getter or setter property in an object literal.
9674 JavaScript syntax is:
9675
9676 { get foo() {...}, set foo(x) {...} }
9677
9678 and expression closure style is also supported
9679
9680 { get foo() x, set foo(x) _x = x }
9681
9682 POS is the start position of the `get' or `set' keyword.
9683 PROP is the `js2-name-node' representing the property name.
9684 GET-P is non-nil if the keyword was `get'."
9685 (let ((type (if get-p js2-GET js2-SET))
9686 result
9687 end
9688 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9689 ;; it has to be an anonymous function, as we already parsed the name
9690 (if (/= (js2-node-type fn) js2-FUNCTION)
9691 (js2-report-error "msg.bad.prop")
9692 (if (plusp (length (js2-function-name fn)))
9693 (js2-report-error "msg.bad.prop")))
9694 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9695 (setq end (js2-node-end fn)
9696 result (make-js2-getter-setter-node :type type
9697 :pos pos
9698 :len (- end pos)
9699 :left prop
9700 :right fn))
9701 (js2-node-add-children result prop fn)
9702 result))
9703
9704 (defun js2-create-name-node (&optional check-activation-p token)
9705 "Create a name node using the token info from last scanned name.
9706 In some cases we need to either synthesize a name node, or we lost
9707 the name token information by peeking. If the TOKEN parameter is
9708 not `js2-NAME', then we use the token info saved in instance vars."
9709 (let ((beg js2-token-beg)
9710 (s js2-ts-string)
9711 name)
9712 (when (/= js2-current-token js2-NAME)
9713 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9714 s js2-prev-name-token-string
9715 js2-prev-name-token-start nil
9716 js2-prev-name-token-string nil))
9717 (setq name (make-js2-name-node :pos beg
9718 :name s
9719 :len (length s)))
9720 (if check-activation-p
9721 (js2-check-activation-name s (or token js2-NAME)))
9722 name))
9723
9724 ;;; Indentation support
9725
9726 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9727 ;; Karl cleverly deduces that the desired indentation level is often a
9728 ;; function of paren/bracket/brace nesting depth, which can be determined
9729 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9730 ;; then does some equally clever checks to see if we're in the context of a
9731 ;; substatement of a possibly braceless statement keyword such as if, while,
9732 ;; or finally. This approach yields pretty good results.
9733
9734 ;; The indenter is often "wrong", however, and needs to be overridden.
9735 ;; The right long-term solution is probably to emulate (or integrate
9736 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9737 ;; parse tree from `js2-parse' is present, which is not true at the
9738 ;; moment the user is typing, computing indentation is still thousands
9739 ;; of lines of code to handle every possible syntactic edge case.
9740
9741 ;; In the meantime, the compromise solution is that we offer a "bounce
9742 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9743 ;; current line indent among various likely guess points. This approach
9744 ;; is far from perfect, but should at least make it slightly easier to
9745 ;; move the line towards its desired indentation when manually
9746 ;; overriding Karl's heuristic nesting guesser.
9747
9748 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9749 ;; extensions such as `let' and Array comprehensions. Major kudos to
9750 ;; Karl for coming up with the initial approach, which packs a lot of
9751 ;; punch for so little code.
9752
9753 (defconst js-possibly-braceless-keywords-re
9754 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9755 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9756 "try" "while" "with" "let")))
9757 "Regular expression matching keywords that are optionally
9758 followed by an opening brace.")
9759
9760 (defconst js-indent-operator-re
9761 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9762 (regexp-opt '("in" "instanceof") 'words))
9763 "Regular expression matching operators that affect indentation
9764 of continued expressions.")
9765
9766 (defconst js-declaration-keyword-re
9767 (regexp-opt '("var" "let" "const") 'words)
9768 "Regular expression matching variable declaration keywords.")
9769
9770 ;; This function has horrible results if you're typing an array
9771 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9772 ;; in conjunction with electric-indent, so just disabling it.
9773 (defsubst js2-code-at-bol-p ()
9774 "Return t if the first character on line is non-whitespace."
9775 nil)
9776
9777 (defun js2-insert-and-indent (key)
9778 "Run command bound to key and indent current line. Runs the command
9779 bound to KEY in the global keymap and indents the current line."
9780 (interactive (list (this-command-keys)))
9781 (let ((cmd (lookup-key (current-global-map) key)))
9782 (if (commandp cmd)
9783 (call-interactively cmd)))
9784 ;; don't do the electric keys inside comments or strings,
9785 ;; and don't do bounce-indent with them.
9786 (let ((parse-state (syntax-ppss (point)))
9787 (js2-bounce-indent-p (js2-code-at-bol-p)))
9788 (unless (or (nth 3 parse-state)
9789 (nth 4 parse-state))
9790 (indent-according-to-mode))))
9791
9792 (defun js-re-search-forward-inner (regexp &optional bound count)
9793 "Auxiliary function for `js-re-search-forward'."
9794 (let (parse saved-point)
9795 (while (> count 0)
9796 (re-search-forward regexp bound)
9797 (setq parse (if saved-point
9798 (parse-partial-sexp saved-point (point))
9799 (syntax-ppss (point))))
9800 (cond ((nth 3 parse)
9801 (re-search-forward
9802 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9803 (save-excursion (end-of-line) (point)) t))
9804 ((nth 7 parse)
9805 (forward-line))
9806 ((or (nth 4 parse)
9807 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9808 (re-search-forward "\\*/"))
9809 (t
9810 (setq count (1- count))))
9811 (setq saved-point (point))))
9812 (point))
9813
9814 (defun js-re-search-forward (regexp &optional bound noerror count)
9815 "Search forward but ignore strings and comments. Invokes
9816 `re-search-forward' but treats the buffer as if strings and
9817 comments have been removed."
9818 (let ((saved-point (point))
9819 (search-expr
9820 (cond ((null count)
9821 '(js-re-search-forward-inner regexp bound 1))
9822 ((< count 0)
9823 '(js-re-search-backward-inner regexp bound (- count)))
9824 ((> count 0)
9825 '(js-re-search-forward-inner regexp bound count)))))
9826 (condition-case err
9827 (eval search-expr)
9828 (search-failed
9829 (goto-char saved-point)
9830 (unless noerror
9831 (error (error-message-string err)))))))
9832
9833 (defun js-re-search-backward-inner (regexp &optional bound count)
9834 "Auxiliary function for `js-re-search-backward'."
9835 (let (parse saved-point)
9836 (while (> count 0)
9837 (re-search-backward regexp bound)
9838 (setq parse (if saved-point
9839 (parse-partial-sexp saved-point (point))
9840 (syntax-ppss (point))))
9841 (cond ((nth 3 parse)
9842 (re-search-backward
9843 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9844 (save-excursion (beginning-of-line) (point)) t))
9845 ((nth 7 parse)
9846 (goto-char (nth 8 parse)))
9847 ((or (nth 4 parse)
9848 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9849 (re-search-backward "/\\*"))
9850 (t
9851 (setq count (1- count))))))
9852 (point))
9853
9854 (defun js-re-search-backward (regexp &optional bound noerror count)
9855 "Search backward but ignore strings and comments. Invokes
9856 `re-search-backward' but treats the buffer as if strings and
9857 comments have been removed."
9858 (let ((saved-point (point))
9859 (search-expr
9860 (cond ((null count)
9861 '(js-re-search-backward-inner regexp bound 1))
9862 ((< count 0)
9863 '(js-re-search-forward-inner regexp bound (- count)))
9864 ((> count 0)
9865 '(js-re-search-backward-inner regexp bound count)))))
9866 (condition-case err
9867 (eval search-expr)
9868 (search-failed
9869 (goto-char saved-point)
9870 (unless noerror
9871 (error (error-message-string err)))))))
9872
9873 (defun js-looking-at-operator-p ()
9874 "Return non-nil if text after point is an operator (that is not
9875 a comma)."
9876 (save-match-data
9877 (and (looking-at js-indent-operator-re)
9878 (or (not (looking-at ":"))
9879 (save-excursion
9880 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9881 (looking-at "?")))))))
9882
9883 (defun js-continued-expression-p ()
9884 "Returns non-nil if the current line continues an expression."
9885 (save-excursion
9886 (back-to-indentation)
9887 (or (js-looking-at-operator-p)
9888 ;; comment
9889 (and (js-re-search-backward "\n" nil t)
9890 (progn
9891 (skip-chars-backward " \t")
9892 (unless (bolp)
9893 (backward-char)
9894 (and (js-looking-at-operator-p)
9895 (and (progn
9896 (backward-char)
9897 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9898
9899 (defun js-end-of-do-while-loop-p ()
9900 "Returns non-nil if word after point is `while' of a do-while
9901 statement, else returns nil. A braceless do-while statement
9902 spanning several lines requires that the start of the loop is
9903 indented to the same column as the current line."
9904 (interactive)
9905 (save-excursion
9906 (save-match-data
9907 (when (looking-at "\\s-*\\<while\\>")
9908 (if (save-excursion
9909 (skip-chars-backward "[ \t\n]*}")
9910 (looking-at "[ \t\n]*}"))
9911 (save-excursion
9912 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9913 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9914 (or (looking-at "\\<do\\>")
9915 (let ((saved-indent (current-indentation)))
9916 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9917 (/= (current-indentation) saved-indent)))
9918 (and (looking-at "[ \t]*\\<do\\>")
9919 (not (js-re-search-forward
9920 "\\<while\\>" (point-at-eol) t))
9921 (= (current-indentation) saved-indent)))))))))
9922
9923 (defun js-multiline-decl-indentation ()
9924 "Returns the declaration indentation column if the current line belongs
9925 to a multiline declaration statement. All declarations are lined up vertically:
9926
9927 var a = 10,
9928 b = 20,
9929 c = 30;
9930
9931 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9932 assigned expression is a function or array/object literal, it will be indented
9933 differently:
9934
9935 var o = { var bar = 2,
9936 foo: 3 o = {
9937 }, foo: 3
9938 bar = 2; };
9939 "
9940 (let (forward-sexp-function ; use lisp version
9941 at-opening-bracket)
9942 (save-excursion
9943 (back-to-indentation)
9944 (when (not (looking-at js-declaration-keyword-re))
9945 (when (looking-at js-indent-operator-re)
9946 (goto-char (match-end 0))) ; continued expressions are ok
9947 (while (and (not at-opening-bracket)
9948 (not (bobp))
9949 (let ((pos (point)))
9950 (save-excursion
9951 (js2-backward-sws)
9952 (or (eq (char-before) ?,)
9953 (and (not (eq (char-before) ?\;))
9954 (and
9955 (prog2 (skip-chars-backward "[[:punct:]]")
9956 (looking-at js-indent-operator-re)
9957 (js2-backward-sws))
9958 (not (eq (char-before) ?\;))))
9959 (js2-same-line pos)))))
9960 (condition-case err
9961 (backward-sexp)
9962 (scan-error (setq at-opening-bracket t))))
9963 (when (looking-at js-declaration-keyword-re)
9964 (- (1+ (match-end 0)) (point-at-bol)))))))
9965
9966 (defun js-ctrl-statement-indentation ()
9967 "Returns the proper indentation of the current line if it
9968 starts the body of a control statement without braces, else
9969 returns nil."
9970 (let (forward-sexp-function) ; temporarily unbind it
9971 (save-excursion
9972 (back-to-indentation)
9973 (when (and (not (js2-same-line (point-min)))
9974 (not (looking-at "{"))
9975 (js-re-search-backward "[[:graph:]]" nil t)
9976 (not (looking-at "[{([]"))
9977 (progn
9978 (forward-char)
9979 (when (= (char-before) ?\))
9980 ;; scan-sexps sometimes throws an error
9981 (ignore-errors (backward-sexp))
9982 (skip-chars-backward " \t" (point-at-bol)))
9983 (let ((pt (point)))
9984 (back-to-indentation)
9985 (and (looking-at js-possibly-braceless-keywords-re)
9986 (= (match-end 0) pt)
9987 (not (js-end-of-do-while-loop-p))))))
9988 (+ (current-indentation) js2-basic-offset)))))
9989
9990 (defun js2-indent-in-array-comp (parse-status)
9991 "Return non-nil if we think we're in an array comprehension.
9992 In particular, return the buffer position of the first `for' kwd."
9993 (let ((bracket (nth 1 parse-status))
9994 (end (point)))
9995 (when bracket
9996 (save-excursion
9997 (goto-char bracket)
9998 (when (looking-at "\\[")
9999 (forward-char 1)
10000 (js2-forward-sws)
10001 (if (looking-at "[[{]")
10002 (let (forward-sexp-function) ; use lisp version
10003 (forward-sexp) ; skip destructuring form
10004 (js2-forward-sws)
10005 (if (and (/= (char-after) ?,) ; regular array
10006 (looking-at "for"))
10007 (match-beginning 0)))
10008 ;; to skip arbitrary expressions we need the parser,
10009 ;; so we'll just guess at it.
10010 (if (and (> end (point)) ; not empty literal
10011 (re-search-forward "[^,]]* \\(for\\) " end t)
10012 ;; not inside comment or string literal
10013 (let ((state (parse-partial-sexp bracket (point))))
10014 (not (or (nth 3 state) (nth 4 state)))))
10015 (match-beginning 1))))))))
10016
10017 (defun js2-array-comp-indentation (parse-status for-kwd)
10018 (if (js2-same-line for-kwd)
10019 ;; first continuation line
10020 (save-excursion
10021 (goto-char (nth 1 parse-status))
10022 (forward-char 1)
10023 (skip-chars-forward " \t")
10024 (current-column))
10025 (save-excursion
10026 (goto-char for-kwd)
10027 (current-column))))
10028
10029 (defun js-proper-indentation (parse-status)
10030 "Return the proper indentation for the current line."
10031 (save-excursion
10032 (back-to-indentation)
10033 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10034 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10035 (continued-expr-p (js-continued-expression-p))
10036 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10037 (js-multiline-decl-indentation)))
10038 (bracket (nth 1 parse-status))
10039 beg)
10040 (cond
10041 ;; indent array comprehension continuation lines specially
10042 ((and bracket
10043 (>= js2-language-version 170)
10044 (not (js2-same-line bracket))
10045 (setq beg (js2-indent-in-array-comp parse-status))
10046 (>= (point) (save-excursion
10047 (goto-char beg)
10048 (point-at-bol)))) ; at or after first loop?
10049 (js2-array-comp-indentation parse-status beg))
10050
10051 (ctrl-stmt-indent)
10052
10053 ((and declaration-indent continued-expr-p)
10054 (+ declaration-indent js2-basic-offset))
10055
10056 (declaration-indent)
10057
10058 (bracket
10059 (goto-char bracket)
10060 (cond
10061 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10062 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10063 (when (save-excursion (skip-chars-backward " \t)")
10064 (looking-at ")"))
10065 (backward-list))
10066 (if (and (nth 1 p)
10067 (not js2-consistent-level-indent-inner-bracket-p))
10068 (progn (goto-char (1+ (nth 1 p)))
10069 (skip-chars-forward " \t"))
10070 (back-to-indentation)
10071 (when (and js2-pretty-multiline-decl-indentation-p
10072 js2-always-indent-assigned-expr-in-decls-p
10073 (looking-at js-declaration-keyword-re))
10074 (goto-char (1+ (match-end 0)))))
10075 (cond (same-indent-p
10076 (current-column))
10077 (continued-expr-p
10078 (+ (current-column) (* 2 js2-basic-offset)))
10079 (t
10080 (+ (current-column) js2-basic-offset)))))
10081 (t
10082 (unless same-indent-p
10083 (forward-char)
10084 (skip-chars-forward " \t"))
10085 (current-column))))
10086
10087 (continued-expr-p js2-basic-offset)
10088
10089 (t 0)))))
10090
10091 (defun js2-lineup-comment (parse-status)
10092 "Indent a multi-line block comment continuation line."
10093 (let* ((beg (nth 8 parse-status))
10094 (first-line (js2-same-line beg))
10095 (offset (save-excursion
10096 (goto-char beg)
10097 (if (looking-at "/\\*")
10098 (+ 1 (current-column))
10099 0))))
10100 (unless first-line
10101 (indent-line-to offset))))
10102
10103 (defun js2-backward-sws ()
10104 "Move backward through whitespace and comments."
10105 (interactive)
10106 (while (forward-comment -1)))
10107
10108 (defun js2-forward-sws ()
10109 "Move forward through whitespace and comments."
10110 (interactive)
10111 (while (forward-comment 1)))
10112
10113 (defsubst js2-current-indent (&optional pos)
10114 "Return column of indentation on current line.
10115 If POS is non-nil, go to that point and return indentation for that line."
10116 (save-excursion
10117 (if pos
10118 (goto-char pos))
10119 (back-to-indentation)
10120 (current-column)))
10121
10122 (defsubst js2-arglist-close ()
10123 "Return non-nil if we're on a line beginning with a close-paren/brace."
10124 (save-match-data
10125 (save-excursion
10126 (goto-char (point-at-bol))
10127 (js2-forward-sws)
10128 (looking-at "[])}]"))))
10129
10130 (defsubst js2-indent-looks-like-label-p ()
10131 (goto-char (point-at-bol))
10132 (js2-forward-sws)
10133 (looking-at (concat js2-mode-identifier-re ":")))
10134
10135 (defun js2-indent-in-objlit-p (parse-status)
10136 "Return non-nil if this looks like an object-literal entry."
10137 (let ((start (nth 1 parse-status)))
10138 (and
10139 start
10140 (save-excursion
10141 (and (zerop (forward-line -1))
10142 (not (< (point) start)) ; crossed a {} boundary
10143 (js2-indent-looks-like-label-p)))
10144 (save-excursion
10145 (js2-indent-looks-like-label-p)))))
10146
10147 ;; if prev line looks like foobar({ then we're passing an object
10148 ;; literal to a function call, and people pretty much always want to
10149 ;; de-dent back to the previous line, so move the 'basic-offset'
10150 ;; position to the front.
10151 (defsubst js2-indent-objlit-arg-p (parse-status)
10152 (save-excursion
10153 (back-to-indentation)
10154 (js2-backward-sws)
10155 (and (eq (1- (point)) (nth 1 parse-status))
10156 (eq (char-before) ?{)
10157 (progn
10158 (forward-char -1)
10159 (skip-chars-backward " \t")
10160 (eq (char-before) ?\()))))
10161
10162 (defsubst js2-indent-case-block-p ()
10163 (save-excursion
10164 (back-to-indentation)
10165 (js2-backward-sws)
10166 (goto-char (point-at-bol))
10167 (skip-chars-forward " \t")
10168 (save-match-data
10169 (looking-at "case\\s-.+:"))))
10170
10171 (defsubst js2-syntax-bol ()
10172 "Return the point at the first non-whitespace char on the line.
10173 Returns `point-at-bol' if the line is empty."
10174 (save-excursion
10175 (beginning-of-line)
10176 (skip-chars-forward " \t")
10177 (point)))
10178
10179 (defun js2-bounce-indent (normal-col parse-status backwards)
10180 "Cycle among alternate computed indentation positions.
10181 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10182 of the buffer to the current point. NORMAL-COL is the indentation
10183 column computed by the heuristic guesser based on current paren,
10184 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10185 in reverse."
10186 (let ((cur-indent (js2-current-indent))
10187 (old-buffer-undo-list buffer-undo-list)
10188 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10189 (current-line (save-excursion
10190 (forward-line 0) ; move to bol
10191 (1+ (count-lines (point-min) (point)))))
10192 positions
10193 pos
10194 main-pos
10195 anchor
10196 arglist-cont
10197 same-indent
10198 prev-line-col
10199 basic-offset
10200 computed-pos)
10201 ;; temporarily don't record undo info, if user requested this
10202 (if js2-mode-indent-inhibit-undo
10203 (setq buffer-undo-list t))
10204 (unwind-protect
10205 (progn
10206 ;; first likely point: indent from beginning of previous code line
10207 (push (setq basic-offset
10208 (+ (save-excursion
10209 (back-to-indentation)
10210 (js2-backward-sws)
10211 (back-to-indentation)
10212 (setq prev-line-col (current-column)))
10213 js2-basic-offset))
10214 positions)
10215
10216 ;; (first + epsilon) likely point: indent 2x from beginning of
10217 ;; previous code line. Some companies like this approach. Ahem.
10218 ;; Seriously, though -- 4-space indent for expression continuation
10219 ;; lines isn't a bad idea. We should eventually implement it
10220 ;; that way.
10221 (push (setq basic-offset
10222 (+ (save-excursion
10223 (back-to-indentation)
10224 (js2-backward-sws)
10225 (back-to-indentation)
10226 (setq prev-line-col (current-column)))
10227 (* 2 js2-basic-offset)))
10228 positions)
10229
10230 ;; second likely point: indent from assign-expr RHS. This
10231 ;; is just a crude guess based on finding " = " on the previous
10232 ;; line containing actual code.
10233 (setq pos (save-excursion
10234 (save-match-data
10235 (forward-line -1)
10236 (goto-char (point-at-bol))
10237 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10238 (point-at-eol) t)
10239 (goto-char (match-end 1))
10240 (skip-chars-forward " \t\r\n")
10241 (current-column)))))
10242 (when pos
10243 (incf pos js2-basic-offset)
10244 (push pos positions))
10245
10246 ;; third likely point: same indent as previous line of code.
10247 ;; Make it the first likely point if we're not on an
10248 ;; arglist-close line and previous line ends in a comma, or
10249 ;; both this line and prev line look like object-literal
10250 ;; elements.
10251 (setq pos (save-excursion
10252 (goto-char (point-at-bol))
10253 (js2-backward-sws)
10254 (back-to-indentation)
10255 (prog1
10256 (current-column)
10257 ;; while we're here, look for trailing comma
10258 (if (save-excursion
10259 (goto-char (point-at-eol))
10260 (js2-backward-sws)
10261 (eq (char-before) ?,))
10262 (setq arglist-cont (1- (point)))))))
10263 (when pos
10264 (if (and (or arglist-cont
10265 (js2-indent-in-objlit-p parse-status))
10266 (not (js2-arglist-close)))
10267 (setq same-indent pos))
10268 (push pos positions))
10269
10270 ;; fourth likely point: first preceding code with less indentation
10271 ;; than the immediately preceding code line.
10272 (setq pos (save-excursion
10273 (back-to-indentation)
10274 (js2-backward-sws)
10275 (back-to-indentation)
10276 (setq anchor (current-column))
10277 (while (and (zerop (forward-line -1))
10278 (>= (progn
10279 (back-to-indentation)
10280 (current-column))
10281 anchor)))
10282 (setq pos (current-column))))
10283 (push pos positions)
10284
10285 ;; nesting-heuristic position, main by default
10286 (push (setq main-pos normal-col) positions)
10287
10288 ;; delete duplicates and sort positions list
10289 (setq positions (sort (delete-dups positions) '<))
10290
10291 ;; comma-list continuation lines: prev line indent takes precedence
10292 (if same-indent
10293 (setq main-pos same-indent))
10294
10295 ;; common special cases where we want to indent in from previous line
10296 (if (or (js2-indent-case-block-p)
10297 (js2-indent-objlit-arg-p parse-status))
10298 (setq main-pos basic-offset))
10299
10300 ;; if bouncing backwards, reverse positions list
10301 (if backwards
10302 (setq positions (reverse positions)))
10303
10304 ;; record whether we're already sitting on one of the alternatives
10305 (setq pos (member cur-indent positions))
10306
10307 (cond
10308 ;; case 0: we're one one of the alternatives and this is the
10309 ;; first time they've pressed TAB on this line (best-guess).
10310 ((and js2-mode-indent-ignore-first-tab
10311 pos
10312 ;; first time pressing TAB on this line?
10313 (not (eq js2-mode-last-indented-line current-line)))
10314 ;; do nothing
10315 (setq computed-pos nil))
10316 ;; case 1: only one computed position => use it
10317 ((null (cdr positions))
10318 (setq computed-pos 0))
10319 ;; case 2: not on any of the computed spots => use main spot
10320 ((not pos)
10321 (setq computed-pos (js2-position main-pos positions)))
10322 ;; case 3: on last position: cycle to first position
10323 ((null (cdr pos))
10324 (setq computed-pos 0))
10325 ;; case 4: on intermediate position: cycle to next position
10326 (t
10327 (setq computed-pos (js2-position (second pos) positions))))
10328
10329 ;; see if any hooks want to indent; otherwise we do it
10330 (loop with result = nil
10331 for hook in js2-indent-hook
10332 while (null result)
10333 do
10334 (setq result (funcall hook positions computed-pos))
10335 finally do
10336 (unless (or result (null computed-pos))
10337 (indent-line-to (nth computed-pos positions)))))
10338
10339 ;; finally
10340 (if js2-mode-indent-inhibit-undo
10341 (setq buffer-undo-list old-buffer-undo-list))
10342 ;; see commentary for `js2-mode-last-indented-line'
10343 (setq js2-mode-last-indented-line current-line))))
10344
10345 (defun js2-indent-bounce-backwards ()
10346 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10347 cycles between the computed indentation positions in reverse order."
10348 (interactive)
10349 (js2-indent-line t))
10350
10351 (defsubst js2-1-line-comment-continuation-p ()
10352 "Return t if we're in a 1-line comment continuation.
10353 If so, we don't ever want to use bounce-indent."
10354 (save-excursion
10355 (save-match-data
10356 (and (progn
10357 (forward-line 0)
10358 (looking-at "\\s-*//"))
10359 (progn
10360 (forward-line -1)
10361 (forward-line 0)
10362 (when (looking-at "\\s-*$")
10363 (js2-backward-sws)
10364 (forward-line 0))
10365 (looking-at "\\s-*//"))))))
10366
10367 (defun js2-indent-line (&optional bounce-backwards)
10368 "Indent the current line as JavaScript source text."
10369 (interactive)
10370 (let (parse-status
10371 offset
10372 indent-col
10373 moved
10374 ;; don't whine about errors/warnings when we're indenting.
10375 ;; This has to be set before calling parse-partial-sexp below.
10376 (inhibit-point-motion-hooks t))
10377 (setq parse-status (save-excursion
10378 (syntax-ppss (point-at-bol)))
10379 offset (- (point) (save-excursion
10380 (back-to-indentation)
10381 (point))))
10382 (js2-with-underscore-as-word-syntax
10383 (if (nth 4 parse-status)
10384 (js2-lineup-comment parse-status)
10385 (setq indent-col (js-proper-indentation parse-status))
10386 ;; see comments below about js2-mode-last-indented-line
10387 (cond
10388 ;; bounce-indenting is disabled during electric-key indent.
10389 ;; It doesn't work well on first line of buffer.
10390 ((and js2-bounce-indent-p
10391 (not (js2-same-line (point-min)))
10392 (not (js2-1-line-comment-continuation-p)))
10393 (js2-bounce-indent indent-col parse-status bounce-backwards))
10394 ;; just indent to the guesser's likely spot
10395 (t (indent-line-to indent-col)))
10396 (when (plusp offset)
10397 (forward-char offset))))))
10398
10399 (defun js2-indent-region (start end)
10400 "Indent the region, but don't use bounce indenting."
10401 (let ((js2-bounce-indent-p nil)
10402 (indent-region-function nil)
10403 (after-change-functions (remq 'js2-mode-edit
10404 after-change-functions)))
10405 (indent-region start end nil) ; nil for byte-compiler
10406 (js2-mode-edit start end (- end start))))
10407
10408 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10409
10410 ;;;###autoload
10411 (defun js2-mode ()
10412 "Major mode for editing JavaScript code."
10413 (interactive)
10414 (kill-all-local-variables)
10415 (set-syntax-table js2-mode-syntax-table)
10416 (use-local-map js2-mode-map)
10417 (make-local-variable 'comment-start)
10418 (make-local-variable 'comment-end)
10419 (make-local-variable 'comment-start-skip)
10420 (setq major-mode 'js2-mode
10421 mode-name "JavaScript-IDE"
10422 comment-start "//" ; used by comment-region; don't change it
10423 comment-end "")
10424 (setq local-abbrev-table js2-mode-abbrev-table)
10425 (set (make-local-variable 'max-lisp-eval-depth)
10426 (max max-lisp-eval-depth 3000))
10427 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10428 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10429
10430 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10431 ;; on most platforms other than the one I originally wrote it on.
10432 ;; So it's back to `c-fill-paragraph'.
10433 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10434
10435 (add-hook 'before-save-hook #'js2-before-save nil t)
10436 (set (make-local-variable 'next-error-function) #'js2-next-error)
10437 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10438 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10439 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10440 ;; for characters inside regexp literals.
10441 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10442 ;; this is necessary to make `show-paren-function' work properly
10443 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10444 ;; needed for M-x rgrep, among other things
10445 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10446
10447 ;; some variables needed by cc-engine for paragraph-fill, etc.
10448 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10449 c-comment-start-regexp "/[*/]\\|\\s|"
10450 c-line-comment-starter "//"
10451 c-paragraph-start js2-paragraph-start
10452 c-paragraph-separate "$"
10453 comment-start-skip js2-comment-start-skip
10454 c-syntactic-ws-start js2-syntactic-ws-start
10455 c-syntactic-ws-end js2-syntactic-ws-end
10456 c-syntactic-eol js2-syntactic-eol)
10457
10458 (let ((c-buffer-is-cc-mode t))
10459 ;; Copied from `js-mode'. Also see Bug#6071.
10460 (make-local-variable 'paragraph-start)
10461 (make-local-variable 'paragraph-separate)
10462 (make-local-variable 'paragraph-ignore-fill-prefix)
10463 (make-local-variable 'adaptive-fill-mode)
10464 (make-local-variable 'adaptive-fill-regexp)
10465 (c-setup-paragraph-variables))
10466
10467 (setq js2-default-externs
10468 (append js2-ecma-262-externs
10469 (if js2-include-browser-externs
10470 js2-browser-externs)
10471 (if js2-include-gears-externs
10472 js2-gears-externs)
10473 (if js2-include-rhino-externs
10474 js2-rhino-externs)))
10475
10476 ;; We do our own syntax highlighting based on the parse tree.
10477 ;; However, we want minor modes that add keywords to highlight properly
10478 ;; (examples: doxymacs, column-marker).
10479 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10480 (setq font-lock-defaults '(nil t))
10481
10482 ;; Experiment: make reparse-delay longer for longer files.
10483 (if (plusp js2-dynamic-idle-timer-adjust)
10484 (setq js2-idle-timer-delay
10485 (* js2-idle-timer-delay
10486 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10487
10488 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10489 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10490 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10491 (imenu-add-to-menubar (concat "IM-" mode-name))
10492 (when js2-mirror-mode
10493 (js2-enter-mirror-mode))
10494 (add-to-invisibility-spec '(js2-outline . t))
10495 (set (make-local-variable 'line-move-ignore-invisible) t)
10496 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10497
10498 (if (fboundp 'run-mode-hooks)
10499 (run-mode-hooks 'js2-mode-hook)
10500 (run-hooks 'js2-mode-hook))
10501
10502 (setq js2-mode-functions-hidden nil
10503 js2-mode-comments-hidden nil
10504 js2-mode-buffer-dirty-p t
10505 js2-mode-parsing nil)
10506 (js2-reparse))
10507
10508 (defun js2-mode-exit ()
10509 "Exit `js2-mode' and clean up."
10510 (interactive)
10511 (when js2-mode-node-overlay
10512 (delete-overlay js2-mode-node-overlay)
10513 (setq js2-mode-node-overlay nil))
10514 (js2-remove-overlays)
10515 (setq js2-mode-ast nil)
10516 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10517 (remove-from-invisibility-spec '(js2-outline . t))
10518 (js2-mode-show-all)
10519 (js2-with-unmodifying-text-property-changes
10520 (js2-clear-face (point-min) (point-max))))
10521
10522 (defun js2-before-save ()
10523 "Clean up whitespace before saving file.
10524 You can disable this by customizing `js2-cleanup-whitespace'."
10525 (when js2-cleanup-whitespace
10526 (let ((col (current-column)))
10527 (delete-trailing-whitespace)
10528 ;; don't change trailing whitespace on current line
10529 (unless (eq (current-column) col)
10530 (indent-to col)))))
10531
10532 (defsubst js2-mode-reset-timer ()
10533 "Cancel any existing parse timer and schedule a new one."
10534 (if js2-mode-parse-timer
10535 (cancel-timer js2-mode-parse-timer))
10536 (setq js2-mode-parsing nil)
10537 (setq js2-mode-parse-timer
10538 (run-with-idle-timer js2-idle-timer-delay nil
10539 #'js2-mode-idle-reparse (current-buffer))))
10540
10541 (defun js2-mode-idle-reparse (buffer)
10542 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10543 it to be reparsed when the buffer is selected."
10544 (if (eq buffer (current-buffer))
10545 (js2-reparse)
10546 ;; reparse when the buffer is selected again
10547 (with-current-buffer buffer
10548 (add-hook 'window-configuration-change-hook
10549 #'js2-mode-idle-reparse-inner
10550 nil t))))
10551
10552 (defun js2-mode-idle-reparse-inner ()
10553 (remove-hook 'window-configuration-change-hook
10554 #'js2-mode-idle-reparse-inner
10555 t)
10556 (js2-reparse))
10557
10558 (defun js2-mode-edit (beg end len)
10559 "Schedule a new parse after buffer is edited.
10560 Buffer edit spans from BEG to END and is of length LEN.
10561 Also clears the `js2-magic' bit on autoinserted parens/brackets
10562 if the edit occurred on a line different from the magic paren."
10563 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10564 (line (if magic-pos (line-number-at-pos magic-pos))))
10565 (and line
10566 (or (/= (line-number-at-pos beg) line)
10567 (and (> 0 len)
10568 (/= (line-number-at-pos end) line)))
10569 (js2-mode-mundanify-parens)))
10570 (setq js2-mode-buffer-dirty-p t)
10571 (js2-mode-hide-overlay)
10572 (js2-mode-reset-timer))
10573
10574 (defun js2-reparse (&optional force)
10575 "Re-parse current buffer after user finishes some data entry.
10576 If we get any user input while parsing, including cursor motion,
10577 we discard the parse and reschedule it. If FORCE is nil, then the
10578 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10579 (let (time
10580 interrupted-p
10581 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10582 (unless js2-mode-parsing
10583 (setq js2-mode-parsing t)
10584 (unwind-protect
10585 (when (or js2-mode-buffer-dirty-p force)
10586 (js2-remove-overlays)
10587 (js2-with-unmodifying-text-property-changes
10588 (setq js2-mode-buffer-dirty-p nil
10589 js2-mode-fontifications nil
10590 js2-mode-deferred-properties nil)
10591 (if js2-mode-verbose-parse-p
10592 (message "parsing..."))
10593 (setq time
10594 (js2-time
10595 (setq interrupted-p
10596 (catch 'interrupted
10597 (setq js2-mode-ast (js2-parse))
10598 ;; if parsing is interrupted, comments and regex
10599 ;; literals stay ignored by `parse-partial-sexp'
10600 (remove-text-properties (point-min) (point-max)
10601 '(syntax-table))
10602 (js2-mode-apply-deferred-properties)
10603 (js2-mode-remove-suppressed-warnings)
10604 (js2-mode-show-warnings)
10605 (js2-mode-show-errors)
10606 (js2-mode-highlight-magic-parens)
10607 (if (>= js2-highlight-level 1)
10608 (js2-highlight-jsdoc js2-mode-ast))
10609 nil))))
10610 (if interrupted-p
10611 (progn
10612 ;; unfinished parse => try again
10613 (setq js2-mode-buffer-dirty-p t)
10614 (js2-mode-reset-timer))
10615 (if js2-mode-verbose-parse-p
10616 (message "Parse time: %s" time)))))
10617 (setq js2-mode-parsing nil)
10618 (unless interrupted-p
10619 (setq js2-mode-parse-timer nil))))))
10620
10621 (defun js2-mode-show-node ()
10622 "Debugging aid: highlight selected AST node on mouse click."
10623 (interactive)
10624 (let ((node (js2-node-at-point))
10625 beg
10626 end)
10627 (when js2-mode-show-overlay
10628 (if (null node)
10629 (message "No node found at location %s" (point))
10630 (setq beg (js2-node-abs-pos node)
10631 end (+ beg (js2-node-len node)))
10632 (if js2-mode-node-overlay
10633 (move-overlay js2-mode-node-overlay beg end)
10634 (setq js2-mode-node-overlay (make-overlay beg end))
10635 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10636 (js2-with-unmodifying-text-property-changes
10637 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10638 (message "%s, parent: %s"
10639 (js2-node-short-name node)
10640 (if (js2-node-parent node)
10641 (js2-node-short-name (js2-node-parent node))
10642 "nil"))))))
10643
10644 (defun js2-mode-hide-overlay (&optional p1 p2)
10645 "Remove the debugging overlay when the point moves.
10646 P1 and P2 are the old and new values of point, respectively."
10647 (when js2-mode-node-overlay
10648 (let ((beg (overlay-start js2-mode-node-overlay))
10649 (end (overlay-end js2-mode-node-overlay)))
10650 ;; Sometimes we're called spuriously.
10651 (unless (and p2
10652 (>= p2 beg)
10653 (<= p2 end))
10654 (js2-with-unmodifying-text-property-changes
10655 (remove-text-properties beg end '(point-left nil)))
10656 (delete-overlay js2-mode-node-overlay)
10657 (setq js2-mode-node-overlay nil)))))
10658
10659 (defun js2-mode-reset ()
10660 "Debugging helper: reset everything."
10661 (interactive)
10662 (js2-mode-exit)
10663 (js2-mode))
10664
10665 (defsubst js2-mode-show-warn-or-err (e face)
10666 "Highlight a warning or error E with FACE.
10667 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10668 (let* ((key (first e))
10669 (beg (second e))
10670 (end (+ beg (third e)))
10671 ;; Don't inadvertently go out of bounds.
10672 (beg (max (point-min) (min beg (point-max))))
10673 (end (max (point-min) (min end (point-max))))
10674 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10675 (ovl (make-overlay beg end)))
10676 (overlay-put ovl 'font-lock-face face)
10677 (overlay-put ovl 'js2-error t)
10678 (put-text-property beg end 'help-echo (js2-get-msg key))
10679 (put-text-property beg end 'point-entered #'js2-echo-error)))
10680
10681 (defun js2-remove-overlays ()
10682 "Remove overlays from buffer that have a `js2-error' property."
10683 (let ((beg (point-min))
10684 (end (point-max)))
10685 (save-excursion
10686 (dolist (o (overlays-in beg end))
10687 (when (overlay-get o 'js2-error)
10688 (delete-overlay o))))))
10689
10690 (defun js2-error-at-point (&optional pos)
10691 "Return non-nil if there's an error overlay at POS.
10692 Defaults to point."
10693 (loop with pos = (or pos (point))
10694 for o in (overlays-at pos)
10695 thereis (overlay-get o 'js2-error)))
10696
10697 (defun js2-mode-apply-deferred-properties ()
10698 "Apply fontifications and other text properties recorded during parsing."
10699 (when (plusp js2-highlight-level)
10700 ;; We defer clearing faces as long as possible to eliminate flashing.
10701 (js2-clear-face (point-min) (point-max))
10702 ;; Have to reverse the recorded fontifications list so that errors
10703 ;; and warnings overwrite the normal fontifications.
10704 (dolist (f (nreverse js2-mode-fontifications))
10705 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10706 (setq js2-mode-fontifications nil))
10707 (dolist (p js2-mode-deferred-properties)
10708 (apply #'put-text-property p))
10709 (setq js2-mode-deferred-properties nil))
10710
10711 (defun js2-mode-show-errors ()
10712 "Highlight syntax errors."
10713 (when js2-mode-show-parse-errors
10714 (dolist (e (js2-ast-root-errors js2-mode-ast))
10715 (js2-mode-show-warn-or-err e 'js2-error-face))))
10716
10717 (defun js2-mode-remove-suppressed-warnings ()
10718 "Take suppressed warnings out of the AST warnings list.
10719 This ensures that the counts and `next-error' are correct."
10720 (setf (js2-ast-root-warnings js2-mode-ast)
10721 (js2-delete-if
10722 (lambda (e)
10723 (let ((key (caar e)))
10724 (or
10725 (and (not js2-strict-trailing-comma-warning)
10726 (string-match "trailing\\.comma" key))
10727 (and (not js2-strict-cond-assign-warning)
10728 (string= key "msg.equal.as.assign"))
10729 (and js2-missing-semi-one-line-override
10730 (string= key "msg.missing.semi")
10731 (let* ((beg (second e))
10732 (node (js2-node-at-point beg))
10733 (fn (js2-mode-find-parent-fn node))
10734 (body (and fn (js2-function-node-body fn)))
10735 (lc (and body (js2-node-abs-pos body)))
10736 (rc (and lc (+ lc (js2-node-len body)))))
10737 (and fn
10738 (or (null body)
10739 (save-excursion
10740 (goto-char beg)
10741 (and (js2-same-line lc)
10742 (js2-same-line rc))))))))))
10743 (js2-ast-root-warnings js2-mode-ast))))
10744
10745 (defun js2-mode-show-warnings ()
10746 "Highlight strict-mode warnings."
10747 (when js2-mode-show-strict-warnings
10748 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10749 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10750
10751 (defun js2-echo-error (old-point new-point)
10752 "Called by point-motion hooks."
10753 (let ((msg (get-text-property new-point 'help-echo)))
10754 (if (and msg (or (not (current-message))
10755 (string= (current-message) "Quit")))
10756 (message msg))))
10757
10758 (defalias #'js2-echo-help #'js2-echo-error)
10759
10760 (defun js2-enter-key ()
10761 "Handle user pressing the Enter key."
10762 (interactive)
10763 (let ((parse-status (save-excursion
10764 (syntax-ppss (point))))
10765 (js2-bounce-indent-p nil))
10766 (cond
10767 ;; check if we're inside a string
10768 ((nth 3 parse-status)
10769 (if js2-concat-multiline-strings
10770 (js2-mode-split-string parse-status)
10771 (insert "\n")))
10772 ;; check if inside a block comment
10773 ((nth 4 parse-status)
10774 (js2-mode-extend-comment))
10775 (t
10776 ;; should probably figure out what the mode-map says we should do
10777 (if js2-indent-on-enter-key
10778 (js2-indent-line))
10779 (insert "\n")
10780 (if js2-enter-indents-newline
10781 (js2-indent-line))))))
10782
10783 (defun js2-mode-split-string (parse-status)
10784 "Turn a newline in mid-string into a string concatenation.
10785 PARSE-STATUS is as documented in `parse-partial-sexp'."
10786 (let* ((col (current-column))
10787 (quote-char (nth 3 parse-status))
10788 (quote-string (string quote-char))
10789 (string-beg (nth 8 parse-status))
10790 (indent (save-match-data
10791 (or
10792 (save-excursion
10793 (back-to-indentation)
10794 (if (looking-at "\\+")
10795 (current-column)))
10796 (save-excursion
10797 (goto-char string-beg)
10798 (if (looking-back "\\+\\s-+")
10799 (goto-char (match-beginning 0)))
10800 (current-column))))))
10801 (insert quote-char "\n")
10802 (indent-to indent)
10803 (insert "+ " quote-string)
10804 (when (eolp)
10805 (insert quote-string)
10806 (backward-char 1))))
10807
10808 (defun js2-mode-extend-comment ()
10809 "Indent the line and, when inside a comment block, add comment prefix."
10810 (let (star single col first-line needs-close)
10811 (save-excursion
10812 (back-to-indentation)
10813 (cond
10814 ((looking-at "\\*[^/]")
10815 (setq star t
10816 col (current-column)))
10817 ((looking-at "/\\*")
10818 (setq star t
10819 first-line t
10820 col (1+ (current-column))))
10821 ((looking-at "//")
10822 (setq single t
10823 col (current-column)))))
10824 ;; Heuristic for whether we need to close the comment:
10825 ;; if we've got a parse error here, assume it's an unterminated
10826 ;; comment.
10827 (setq needs-close
10828 (or
10829 (eq (get-text-property (1- (point)) 'point-entered)
10830 'js2-echo-error)
10831 ;; The heuristic above doesn't work well when we're
10832 ;; creating a comment and there's another one downstream,
10833 ;; as our parser thinks this one ends at the end of the
10834 ;; next one. (You can have a /* inside a js block comment.)
10835 ;; So just close it if the next non-ws char isn't a *.
10836 (and first-line
10837 (eolp)
10838 (save-excursion
10839 (skip-chars-forward " \t\r\n")
10840 (not (eq (char-after) ?*))))))
10841 (insert "\n")
10842 (cond
10843 (star
10844 (indent-to col)
10845 (insert "* ")
10846 (if (and first-line needs-close)
10847 (save-excursion
10848 (insert "\n")
10849 (indent-to col)
10850 (insert "*/"))))
10851 ((and single
10852 (save-excursion
10853 (and (zerop (forward-line 1))
10854 (looking-at "\\s-*//"))))
10855 (indent-to col)
10856 (insert "// "))
10857 ;; don't need to extend the comment after all
10858 (js2-enter-indents-newline
10859 (js2-indent-line)))))
10860
10861 (defun js2-beginning-of-line ()
10862 "Toggles point between bol and first non-whitespace char in line.
10863 Also moves past comment delimiters when inside comments."
10864 (interactive)
10865 (let (node beg)
10866 (cond
10867 ((bolp)
10868 (back-to-indentation))
10869 ((looking-at "//")
10870 (skip-chars-forward "/ \t"))
10871 ((and (eq (char-after) ?*)
10872 (setq node (js2-comment-at-point))
10873 (memq (js2-comment-node-format node) '(jsdoc block))
10874 (save-excursion
10875 (skip-chars-backward " \t")
10876 (bolp)))
10877 (skip-chars-forward "\* \t"))
10878 (t
10879 (goto-char (point-at-bol))))))
10880
10881 (defun js2-end-of-line ()
10882 "Toggles point between eol and last non-whitespace char in line."
10883 (interactive)
10884 (if (eolp)
10885 (skip-chars-backward " \t")
10886 (goto-char (point-at-eol))))
10887
10888 (defun js2-enter-mirror-mode()
10889 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10890 on insertion."
10891 (interactive)
10892 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10893 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10894 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10895 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10896 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10897 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10898 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10899 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10900
10901 (defun js2-leave-mirror-mode()
10902 "Turns off mirror mode."
10903 (interactive)
10904 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10905 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10906
10907 (defsubst js2-mode-inside-string ()
10908 "Return non-nil if inside a string.
10909 Actually returns the quote character that begins the string."
10910 (let ((parse-state (save-excursion
10911 (syntax-ppss (point)))))
10912 (nth 3 parse-state)))
10913
10914 (defsubst js2-mode-inside-comment-or-string ()
10915 "Return non-nil if inside a comment or string."
10916 (or
10917 (let ((comment-start
10918 (save-excursion
10919 (goto-char (point-at-bol))
10920 (if (re-search-forward "//" (point-at-eol) t)
10921 (match-beginning 0)))))
10922 (and comment-start
10923 (<= comment-start (point))))
10924 (let ((parse-state (save-excursion
10925 (syntax-ppss (point)))))
10926 (or (nth 3 parse-state)
10927 (nth 4 parse-state)))))
10928
10929 (defsubst js2-make-magic-delimiter (delim &optional pos)
10930 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10931 Sets value of `js2-magic' text property to line number at POS."
10932 (propertize delim
10933 'js2-magic (line-number-at-pos pos)
10934 'font-lock-face 'js2-magic-paren-face))
10935
10936 (defun js2-mode-match-delimiter (open close)
10937 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10938 The rule we use, which as far as we can tell is how Eclipse works,
10939 is that we insert the match if we're not in a comment or string,
10940 and the next non-whitespace character is either punctuation or
10941 occurs on another line."
10942 (insert open)
10943 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10944 (not (js2-mode-inside-comment-or-string)))
10945 (save-excursion
10946 (insert (js2-make-magic-delimiter close)))
10947 (when js2-auto-indent-p
10948 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10949 (js2-indent-line)))))
10950
10951 (defun js2-mode-match-bracket ()
10952 "Insert matching bracket."
10953 (interactive)
10954 (js2-mode-match-delimiter "[" "]"))
10955
10956 (defun js2-mode-match-paren ()
10957 "Insert matching paren unless already inserted."
10958 (interactive)
10959 (js2-mode-match-delimiter "(" ")"))
10960
10961 (defun js2-mode-match-curly (arg)
10962 "Insert matching curly-brace.
10963 With prefix arg, no formatting or indentation will occur -- the close-brace
10964 is simply inserted directly at the point."
10965 (interactive "p")
10966 (let (try-pos)
10967 (cond
10968 (current-prefix-arg
10969 (js2-mode-match-delimiter "{" "}"))
10970 ((and js2-auto-insert-catch-block
10971 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10972 (point-at-bol))
10973 (match-beginning 1))))
10974 (js2-insert-catch-skel try-pos))
10975 (t
10976 ;; Otherwise try to do something smarter.
10977 (insert "{")
10978 (unless (or (not (looking-at "\\s-*$"))
10979 (save-excursion
10980 (skip-chars-forward " \t\r\n")
10981 (and (looking-at "}")
10982 (js2-error-at-point)))
10983 (js2-mode-inside-comment-or-string))
10984 (undo-boundary)
10985 ;; absolutely mystifying bug: when inserting the next "\n",
10986 ;; the buffer-undo-list is given two new entries: the inserted range,
10987 ;; and the incorrect position of the point. It's recorded incorrectly
10988 ;; as being before the opening "{", not after it. But it's recorded
10989 ;; as the correct value if you're debugging `js2-mode-match-curly'
10990 ;; in edebug. I have no idea why it's doing this, but incrementing
10991 ;; the inserted position fixes the problem, so that the undo takes us
10992 ;; back to just after the user-inserted "{".
10993 (insert "\n")
10994 (ignore-errors
10995 (incf (cadr buffer-undo-list)))
10996 (js2-indent-line)
10997 (save-excursion
10998 (insert "\n}")
10999 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11000 (js2-indent-line))))))))
11001
11002 (defun js2-insert-catch-skel (try-pos)
11003 "Complete a try/catch block after inserting a { following a try keyword.
11004 Rationale is that a try always needs a catch or a finally, and the catch is
11005 the more likely of the two.
11006
11007 TRY-POS is the buffer position of the try keyword. The open-curly should
11008 already have been inserted."
11009 (insert "{")
11010 (let ((try-col (save-excursion
11011 (goto-char try-pos)
11012 (current-column))))
11013 (insert "\n")
11014 (undo-boundary)
11015 (js2-indent-line) ;; indent the blank line where cursor will end up
11016 (save-excursion
11017 (insert "\n")
11018 (indent-to try-col)
11019 (insert "} catch (x) {\n\n")
11020 (indent-to try-col)
11021 (insert "}"))))
11022
11023 (defun js2-mode-highlight-magic-parens ()
11024 "Re-highlight magic parens after parsing nukes the 'face prop."
11025 (let ((beg (point-min))
11026 end)
11027 (while (setq beg (next-single-property-change beg 'js2-magic))
11028 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11029 (if (get-text-property beg 'js2-magic)
11030 (js2-with-unmodifying-text-property-changes
11031 (put-text-property beg (or end (1+ beg))
11032 'font-lock-face 'js2-magic-paren-face))))))
11033
11034 (defun js2-mode-mundanify-parens ()
11035 "Clear all magic parens and brackets."
11036 (let ((beg (point-min))
11037 end)
11038 (while (setq beg (next-single-property-change beg 'js2-magic))
11039 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11040 (remove-text-properties beg (or end (1+ beg))
11041 '(js2-magic face)))))
11042
11043 (defsubst js2-match-quote (quote-string)
11044 (let ((start-quote (js2-mode-inside-string)))
11045 (cond
11046 ;; inside a comment - don't do quote-matching, since we can't
11047 ;; reliably figure out if we're in a string inside the comment
11048 ((js2-comment-at-point)
11049 (insert quote-string))
11050 ((not start-quote)
11051 ;; not in string => insert matched quotes
11052 (insert quote-string)
11053 ;; exception: if we're just before a word, don't double it.
11054 (unless (looking-at "[^ \t\r\n]")
11055 (save-excursion
11056 (insert quote-string))))
11057 ((looking-at quote-string)
11058 (if (looking-back "[^\\]\\\\")
11059 (insert quote-string)
11060 (forward-char 1)))
11061 ((and js2-mode-escape-quotes
11062 (save-excursion
11063 (save-match-data
11064 (re-search-forward quote-string (point-at-eol) t))))
11065 ;; inside terminated string, escape quote (unless already escaped)
11066 (insert (if (looking-back "[^\\]\\\\")
11067 quote-string
11068 (concat "\\" quote-string))))
11069 (t
11070 (insert quote-string))))) ; else terminate the string
11071
11072 (defun js2-mode-match-single-quote ()
11073 "Insert matching single-quote."
11074 (interactive)
11075 (let ((parse-status (syntax-ppss (point))))
11076 ;; don't match inside comments, since apostrophe is more common
11077 (if (nth 4 parse-status)
11078 (insert "'")
11079 (js2-match-quote "'"))))
11080
11081 (defun js2-mode-match-double-quote ()
11082 "Insert matching double-quote."
11083 (interactive)
11084 (js2-match-quote "\""))
11085
11086 ;; Eclipse works as follows:
11087 ;; * type an open-paren and it auto-inserts close-paren
11088 ;; - auto-inserted paren gets a green bracket
11089 ;; - green bracket means typing close-paren there will skip it
11090 ;; * if you insert any text on a different line, it turns off
11091 (defun js2-mode-magic-close-paren ()
11092 "Skip over close-paren rather than inserting, where appropriate."
11093 (interactive)
11094 (let* ((here (point))
11095 (parse-status (syntax-ppss here))
11096 (open-pos (nth 1 parse-status))
11097 (close last-input-event)
11098 (open (cond
11099 ((eq close ?\))
11100 ?\()
11101 ((eq close ?\])
11102 ?\[)
11103 ((eq close ?})
11104 ?{)
11105 (t nil))))
11106 (if (and (eq (char-after) close)
11107 (eq open (char-after open-pos))
11108 (js2-same-line open-pos)
11109 (get-text-property here 'js2-magic))
11110 (progn
11111 (remove-text-properties here (1+ here) '(js2-magic face))
11112 (forward-char 1))
11113 (insert-char close 1))
11114 (blink-matching-open)))
11115
11116 (defun js2-mode-wait-for-parse (callback)
11117 "Invoke CALLBACK when parsing is finished.
11118 If parsing is already finished, calls CALLBACK immediately."
11119 (if (not js2-mode-buffer-dirty-p)
11120 (funcall callback)
11121 (push callback js2-mode-pending-parse-callbacks)
11122 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11123
11124 (defun js2-mode-parse-finished ()
11125 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11126 ;; We can't let errors propagate up, since it prevents the
11127 ;; `js2-parse' method from completing normally and returning
11128 ;; the ast, which makes things mysteriously not work right.
11129 (unwind-protect
11130 (dolist (cb js2-mode-pending-parse-callbacks)
11131 (condition-case err
11132 (funcall cb)
11133 (error (message "%s" err))))
11134 (setq js2-mode-pending-parse-callbacks nil)))
11135
11136 (defun js2-mode-flag-region (from to flag)
11137 "Hide or show text from FROM to TO, according to FLAG.
11138 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11139 Returns the created overlay if FLAG is non-nil."
11140 (remove-overlays from to 'invisible 'js2-outline)
11141 (when flag
11142 (let ((o (make-overlay from to)))
11143 (overlay-put o 'invisible 'js2-outline)
11144 (overlay-put o 'isearch-open-invisible
11145 'js2-isearch-open-invisible)
11146 o)))
11147
11148 ;; Function to be set as an outline-isearch-open-invisible' property
11149 ;; to the overlay that makes the outline invisible (see
11150 ;; `js2-mode-flag-region').
11151 (defun js2-isearch-open-invisible (overlay)
11152 ;; We rely on the fact that isearch places point on the matched text.
11153 (js2-mode-show-element))
11154
11155 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11156 "Return cons cell of bounds of folding overlay at POS.
11157 Returns nil if not found."
11158 (let ((overlays (overlays-at (or pos (point))))
11159 o)
11160 (while (and overlays
11161 (not o))
11162 (if (overlay-get (car overlays) 'invisible)
11163 (setq o (car overlays))
11164 (setq overlays (cdr overlays))))
11165 (if o
11166 (cons (overlay-start o) (overlay-end o)))))
11167
11168 (defun js2-mode-function-at-point (&optional pos)
11169 "Return the innermost function node enclosing current point.
11170 Returns nil if point is not in a function."
11171 (let ((node (js2-node-at-point pos)))
11172 (while (and node (not (js2-function-node-p node)))
11173 (setq node (js2-node-parent node)))
11174 (if (js2-function-node-p node)
11175 node)))
11176
11177 (defun js2-mode-toggle-element ()
11178 "Hide or show the foldable element at the point."
11179 (interactive)
11180 (let (comment fn pos)
11181 (save-excursion
11182 (save-match-data
11183 (cond
11184 ;; /* ... */ comment?
11185 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11186 (if (js2-mode-invisible-overlay-bounds
11187 (setq pos (+ 3 (js2-node-abs-pos comment))))
11188 (progn
11189 (goto-char pos)
11190 (js2-mode-show-element))
11191 (js2-mode-hide-element)))
11192 ;; //-comment?
11193 ((save-excursion
11194 (back-to-indentation)
11195 (looking-at js2-mode-//-comment-re))
11196 (js2-mode-toggle-//-comment))
11197 ;; function?
11198 ((setq fn (js2-mode-function-at-point))
11199 (setq pos (and (js2-function-node-body fn)
11200 (js2-node-abs-pos (js2-function-node-body fn))))
11201 (goto-char (1+ pos))
11202 (if (js2-mode-invisible-overlay-bounds)
11203 (js2-mode-show-element)
11204 (js2-mode-hide-element)))
11205 (t
11206 (message "Nothing at point to hide or show")))))))
11207
11208 (defun js2-mode-hide-element ()
11209 "Fold/hide contents of a block, showing ellipses.
11210 Show the hidden text with \\[js2-mode-show-element]."
11211 (interactive)
11212 (if js2-mode-buffer-dirty-p
11213 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11214 (let (node body beg end)
11215 (cond
11216 ((js2-mode-invisible-overlay-bounds)
11217 (message "already hidden"))
11218 (t
11219 (setq node (js2-node-at-point))
11220 (cond
11221 ((js2-block-comment-p node)
11222 (js2-mode-hide-comment node))
11223 (t
11224 (while (and node (not (js2-function-node-p node)))
11225 (setq node (js2-node-parent node)))
11226 (if (and node
11227 (setq body (js2-function-node-body node)))
11228 (progn
11229 (setq beg (js2-node-abs-pos body)
11230 end (+ beg (js2-node-len body)))
11231 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11232 (message "No collapsable element found at point"))))))))
11233
11234 (defun js2-mode-show-element ()
11235 "Show the hidden element at current point."
11236 (interactive)
11237 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11238 (if bounds
11239 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11240 (message "Nothing to un-hide"))))
11241
11242 (defun js2-mode-show-all ()
11243 "Show all of the text in the buffer."
11244 (interactive)
11245 (js2-mode-flag-region (point-min) (point-max) nil))
11246
11247 (defun js2-mode-toggle-hide-functions ()
11248 (interactive)
11249 (if js2-mode-functions-hidden
11250 (js2-mode-show-functions)
11251 (js2-mode-hide-functions)))
11252
11253 (defun js2-mode-hide-functions ()
11254 "Hides all non-nested function bodies in the buffer.
11255 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11256 to open an individual entry."
11257 (interactive)
11258 (if js2-mode-buffer-dirty-p
11259 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11260 (if (null js2-mode-ast)
11261 (message "Oops - parsing failed")
11262 (setq js2-mode-functions-hidden t)
11263 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11264
11265 (defun js2-mode-function-hider (n endp)
11266 (when (not endp)
11267 (let ((tt (js2-node-type n))
11268 body beg end)
11269 (cond
11270 ((and (= tt js2-FUNCTION)
11271 (setq body (js2-function-node-body n)))
11272 (setq beg (js2-node-abs-pos body)
11273 end (+ beg (js2-node-len body)))
11274 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11275 nil) ; don't process children of function
11276 (t
11277 t))))) ; keep processing other AST nodes
11278
11279 (defun js2-mode-show-functions ()
11280 "Un-hide any folded function bodies in the buffer."
11281 (interactive)
11282 (setq js2-mode-functions-hidden nil)
11283 (save-excursion
11284 (goto-char (point-min))
11285 (while (/= (goto-char (next-overlay-change (point)))
11286 (point-max))
11287 (dolist (o (overlays-at (point)))
11288 (when (and (overlay-get o 'invisible)
11289 (not (overlay-get o 'comment)))
11290 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11291
11292 (defun js2-mode-hide-comment (n)
11293 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11294 3 ; /**
11295 2)) ; /*
11296 (beg (+ (js2-node-abs-pos n) head))
11297 (end (- (+ beg (js2-node-len n)) head 2))
11298 (o (js2-mode-flag-region beg end 'hide)))
11299 (overlay-put o 'comment t)))
11300
11301 (defun js2-mode-toggle-hide-comments ()
11302 "Folds all block comments in the buffer.
11303 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11304 to open an individual entry."
11305 (interactive)
11306 (if js2-mode-comments-hidden
11307 (js2-mode-show-comments)
11308 (js2-mode-hide-comments)))
11309
11310 (defun js2-mode-hide-comments ()
11311 (interactive)
11312 (if js2-mode-buffer-dirty-p
11313 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11314 (if (null js2-mode-ast)
11315 (message "Oops - parsing failed")
11316 (setq js2-mode-comments-hidden t)
11317 (dolist (n (js2-ast-root-comments js2-mode-ast))
11318 (let ((format (js2-comment-node-format n)))
11319 (when (js2-block-comment-p n)
11320 (js2-mode-hide-comment n))))
11321 (js2-mode-hide-//-comments)))
11322
11323 (defsubst js2-mode-extend-//-comment (direction)
11324 "Find start or end of a block of similar //-comment lines.
11325 DIRECTION is -1 to look back, 1 to look forward.
11326 INDENT is the indentation level to match.
11327 Returns the end-of-line position of the furthest adjacent
11328 //-comment line with the same indentation as the current line.
11329 If there is no such matching line, returns current end of line."
11330 (let ((pos (point-at-eol))
11331 (indent (current-indentation)))
11332 (save-excursion
11333 (save-match-data
11334 (while (and (zerop (forward-line direction))
11335 (looking-at js2-mode-//-comment-re)
11336 (eq indent (length (match-string 1))))
11337 (setq pos (point-at-eol)))
11338 pos))))
11339
11340 (defun js2-mode-hide-//-comments ()
11341 "Fold adjacent 1-line comments, showing only snippet of first one."
11342 (let (beg end)
11343 (save-excursion
11344 (save-match-data
11345 (goto-char (point-min))
11346 (while (re-search-forward js2-mode-//-comment-re nil t)
11347 (setq beg (point)
11348 end (js2-mode-extend-//-comment 1))
11349 (unless (eq beg end)
11350 (overlay-put (js2-mode-flag-region beg end 'hide)
11351 'comment t))
11352 (goto-char end)
11353 (forward-char 1))))))
11354
11355 (defun js2-mode-toggle-//-comment ()
11356 "Fold or un-fold any multi-line //-comment at point.
11357 Caller should have determined that this line starts with a //-comment."
11358 (let* ((beg (point-at-eol))
11359 (end beg))
11360 (save-excursion
11361 (goto-char end)
11362 (if (js2-mode-invisible-overlay-bounds)
11363 (js2-mode-show-element)
11364 ;; else hide the comment
11365 (setq beg (js2-mode-extend-//-comment -1)
11366 end (js2-mode-extend-//-comment 1))
11367 (unless (eq beg end)
11368 (overlay-put (js2-mode-flag-region beg end 'hide)
11369 'comment t))))))
11370
11371 (defun js2-mode-show-comments ()
11372 "Un-hide any hidden comments, leaving other hidden elements alone."
11373 (interactive)
11374 (setq js2-mode-comments-hidden nil)
11375 (save-excursion
11376 (goto-char (point-min))
11377 (while (/= (goto-char (next-overlay-change (point)))
11378 (point-max))
11379 (dolist (o (overlays-at (point)))
11380 (when (overlay-get o 'comment)
11381 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11382
11383 (defun js2-mode-display-warnings-and-errors ()
11384 "Turn on display of warnings and errors."
11385 (interactive)
11386 (setq js2-mode-show-parse-errors t
11387 js2-mode-show-strict-warnings t)
11388 (js2-reparse 'force))
11389
11390 (defun js2-mode-hide-warnings-and-errors ()
11391 "Turn off display of warnings and errors."
11392 (interactive)
11393 (setq js2-mode-show-parse-errors nil
11394 js2-mode-show-strict-warnings nil)
11395 (js2-reparse 'force))
11396
11397 (defun js2-mode-toggle-warnings-and-errors ()
11398 "Toggle the display of warnings and errors.
11399 Some users don't like having warnings/errors reported while they type."
11400 (interactive)
11401 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11402 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11403 (if (interactive-p)
11404 (message "warnings and errors %s"
11405 (if js2-mode-show-parse-errors
11406 "enabled"
11407 "disabled")))
11408 (js2-reparse 'force))
11409
11410 (defun js2-mode-customize ()
11411 (interactive)
11412 (customize-group 'js2-mode))
11413
11414 (defun js2-mode-forward-sexp (&optional arg)
11415 "Move forward across one statement or balanced expression.
11416 With ARG, do it that many times. Negative arg -N means
11417 move backward across N balanced expressions."
11418 (interactive "p")
11419 (setq arg (or arg 1))
11420 (if js2-mode-buffer-dirty-p
11421 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11422 (let (node end (start (point)))
11423 (cond
11424 ;; backward-sexp
11425 ;; could probably make this better for some cases:
11426 ;; - if in statement block (e.g. function body), go to parent
11427 ;; - infix exprs like (foo in bar) - maybe go to beginning
11428 ;; of infix expr if in the right-side expression?
11429 ((and arg (minusp arg))
11430 (dotimes (i (- arg))
11431 (js2-backward-sws)
11432 (forward-char -1) ; enter the node we backed up to
11433 (setq node (js2-node-at-point (point) t))
11434 (goto-char (if node
11435 (js2-node-abs-pos node)
11436 (point-min)))))
11437 (t
11438 ;; forward-sexp
11439 (js2-forward-sws)
11440 (dotimes (i arg)
11441 (js2-forward-sws)
11442 (setq node (js2-node-at-point (point) t)
11443 end (if node (+ (js2-node-abs-pos node)
11444 (js2-node-len node))))
11445 (goto-char (or end (point-max))))))))
11446
11447 (defun js2-next-error (&optional arg reset)
11448 "Move to next parse error.
11449 Typically invoked via \\[next-error].
11450 ARG is the number of errors, forward or backward, to move.
11451 RESET means start over from the beginning."
11452 (interactive "p")
11453 (if (or (null js2-mode-ast)
11454 (and (null (js2-ast-root-errors js2-mode-ast))
11455 (null (js2-ast-root-warnings js2-mode-ast))))
11456 (message "No errors")
11457 (when reset
11458 (goto-char (point-min)))
11459 (let* ((errs (copy-sequence
11460 (append (js2-ast-root-errors js2-mode-ast)
11461 (js2-ast-root-warnings js2-mode-ast))))
11462 (continue t)
11463 (start (point))
11464 (count (or arg 1))
11465 (backward (minusp count))
11466 (sorter (if backward '> '<))
11467 (stopper (if backward '< '>))
11468 (count (abs count))
11469 all-errs
11470 err)
11471 ;; sort by start position
11472 (setq errs (sort errs (lambda (e1 e2)
11473 (funcall sorter (second e1) (second e2))))
11474 all-errs errs)
11475 ;; find nth error with pos > start
11476 (while (and errs continue)
11477 (when (funcall stopper (cadar errs) start)
11478 (setq err (car errs))
11479 (if (zerop (decf count))
11480 (setq continue nil)))
11481 (setq errs (cdr errs)))
11482 (if err
11483 (goto-char (second err))
11484 ;; wrap around to first error
11485 (goto-char (second (car all-errs)))
11486 ;; if we were already on it, echo msg again
11487 (if (= (point) start)
11488 (js2-echo-error (point) (point)))))))
11489
11490 (defun js2-down-mouse-3 ()
11491 "Make right-click move the point to the click location.
11492 This makes right-click context menu operations a bit more intuitive.
11493 The point will not move if the region is active, however, to avoid
11494 destroying the region selection."
11495 (interactive)
11496 (when (and js2-move-point-on-right-click
11497 (not mark-active))
11498 (let ((e last-input-event))
11499 (ignore-errors
11500 (goto-char (cadadr e))))))
11501
11502 (defun js2-mode-create-imenu-index ()
11503 "Return an alist for `imenu--index-alist'."
11504 ;; This is built up in `js2-parse-record-imenu' during parsing.
11505 (when js2-mode-ast
11506 ;; if we have an ast but no recorder, they're requesting a rescan
11507 (unless js2-imenu-recorder
11508 (js2-reparse 'force))
11509 (prog1
11510 (js2-build-imenu-index)
11511 (setq js2-imenu-recorder nil
11512 js2-imenu-function-map nil))))
11513
11514 (defun js2-mode-find-tag ()
11515 "Replacement for `find-tag-default'.
11516 `find-tag-default' returns a ridiculous answer inside comments."
11517 (let (beg end)
11518 (js2-with-underscore-as-word-syntax
11519 (save-excursion
11520 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11521 (looking-back "[A-Za-z0-9_$]"))
11522 (setq beg (progn (forward-word -1) (point))
11523 end (progn (forward-word 1) (point)))
11524 (setq beg (progn (forward-word 1) (point))
11525 end (progn (forward-word -1) (point))))
11526 (replace-regexp-in-string
11527 "[\"']" ""
11528 (buffer-substring-no-properties beg end))))))
11529
11530 (defun js2-mode-forward-sibling ()
11531 "Move to the end of the sibling following point in parent.
11532 Returns non-nil if successful, or nil if there was no following sibling."
11533 (let* ((node (js2-node-at-point))
11534 (parent (js2-mode-find-enclosing-fn node))
11535 sib)
11536 (when (setq sib (js2-node-find-child-after (point) parent))
11537 (goto-char (+ (js2-node-abs-pos sib)
11538 (js2-node-len sib))))))
11539
11540 (defun js2-mode-backward-sibling ()
11541 "Move to the beginning of the sibling node preceding point in parent.
11542 Parent is defined as the enclosing script or function."
11543 (let* ((node (js2-node-at-point))
11544 (parent (js2-mode-find-enclosing-fn node))
11545 sib)
11546 (when (setq sib (js2-node-find-child-before (point) parent))
11547 (goto-char (js2-node-abs-pos sib)))))
11548
11549 (defun js2-beginning-of-defun (&optional arg)
11550 "Go to line on which current function starts, and return t on success.
11551 If we're not in a function or already at the beginning of one, go
11552 to beginning of previous script-level element.
11553 With ARG N, do that N times. If N is negative, move forward."
11554 (setq arg (or arg 1))
11555 (if (plusp arg)
11556 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11557 (when (cond
11558 ((js2-function-node-p parent)
11559 (goto-char (js2-node-abs-pos parent)))
11560 (t
11561 (js2-mode-backward-sibling)))
11562 (if (> arg 1)
11563 (js2-beginning-of-defun (1- arg))
11564 t)))
11565 (when (js2-end-of-defun)
11566 (if (>= arg -1)
11567 (js2-beginning-of-defun 1)
11568 (js2-beginning-of-defun (1+ arg))))))
11569
11570 (defun js2-end-of-defun ()
11571 "Go to the char after the last position of the current function
11572 or script-level element."
11573 (let* ((node (js2-node-at-point))
11574 (parent (or (and (js2-function-node-p node) node)
11575 (js2-node-parent-script-or-fn node)))
11576 script)
11577 (unless (js2-function-node-p parent)
11578 ;; use current script-level node, or, if none, the next one
11579 (setq script (or parent node))
11580 (setq parent (js2-node-find-child-before (point) script))
11581 (when (or (null parent)
11582 (>= (point) (+ (js2-node-abs-pos parent)
11583 (js2-node-len parent))))
11584 (setq parent (js2-node-find-child-after (point) script))))
11585 (when parent
11586 (goto-char (+ (js2-node-abs-pos parent)
11587 (js2-node-len parent))))))
11588
11589 (defun js2-mark-defun (&optional allow-extend)
11590 "Put mark at end of this function, point at beginning.
11591 The function marked is the one that contains point.
11592
11593 Interactively, if this command is repeated,
11594 or (in Transient Mark mode) if the mark is active,
11595 it marks the next defun after the ones already marked."
11596 (interactive "p")
11597 (let (extended)
11598 (when (and allow-extend
11599 (or (and (eq last-command this-command) (mark t))
11600 (and transient-mark-mode mark-active)))
11601 (let ((sib (save-excursion
11602 (goto-char (mark))
11603 (if (js2-mode-forward-sibling)
11604 (point))))
11605 node)
11606 (if sib
11607 (progn
11608 (set-mark sib)
11609 (setq extended t))
11610 ;; no more siblings - try extending to enclosing node
11611 (goto-char (mark t)))))
11612 (when (not extended)
11613 (let ((node (js2-node-at-point (point) t)) ; skip comments
11614 ast fn stmt parent beg end)
11615 (when (js2-ast-root-p node)
11616 (setq ast node
11617 node (or (js2-node-find-child-after (point) node)
11618 (js2-node-find-child-before (point) node))))
11619 ;; only mark whole buffer if we can't find any children
11620 (if (null node)
11621 (setq node ast))
11622 (if (js2-function-node-p node)
11623 (setq parent node)
11624 (setq fn (js2-mode-find-enclosing-fn node)
11625 stmt (if (or (null fn)
11626 (js2-ast-root-p fn))
11627 (js2-mode-find-first-stmt node))
11628 parent (or stmt fn)))
11629 (setq beg (js2-node-abs-pos parent)
11630 end (+ beg (js2-node-len parent)))
11631 (push-mark beg)
11632 (goto-char end)
11633 (exchange-point-and-mark)))))
11634
11635 (defun js2-narrow-to-defun ()
11636 "Narrow to the function enclosing point."
11637 (interactive)
11638 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11639 (fn (if (js2-script-node-p node)
11640 node
11641 (js2-mode-find-enclosing-fn node)))
11642 (beg (js2-node-abs-pos fn)))
11643 (unless (js2-ast-root-p fn)
11644 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11645
11646 (provide 'js2-mode)
11647
11648 ;;; js2-mode.el ends here