]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Handle unlimited function nesting in imenu index
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
180
181 (defvar js2-emacs22 (>= emacs-major-version 22))
182
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
189 :group 'js2-mode
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
194
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
197
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
200 :group 'languages)
201
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
204 c-basic-offset
205 4)
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
208 :group 'js2-mode
209 :type 'integer)
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
211
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-consistent-level-indent-inner-bracket-p t
238 "Non-nil to make indentation level inner bracket consistent,
239 regardless of the beginning bracket position."
240 :group 'js2-mode
241 :type 'boolean)
242 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
243
244 (defcustom js2-pretty-multiline-decl-indentation-p t
245 "Non-nil to line up multiline declarations vertically. See the
246 function `js-multiline-decl-indentation' for details."
247 :group 'js2-mode
248 :type 'boolean)
249 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
250
251 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
252 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
253 always additionally indent function expression or array/object literal
254 assigned in a declaration, even when only one var is declared."
255 :group 'js2-mode
256 :type 'boolean)
257 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
258
259 (defcustom js2-indent-on-enter-key nil
260 "Non-nil to have Enter/Return key indent the line.
261 This is unusual for Emacs modes but common in IDEs like Eclipse."
262 :type 'boolean
263 :group 'js2-mode)
264
265 (defcustom js2-enter-indents-newline nil
266 "Non-nil to have Enter/Return key indent the newly-inserted line.
267 This is unusual for Emacs modes but common in IDEs like Eclipse."
268 :type 'boolean
269 :group 'js2-mode)
270
271 (defcustom js2-rebind-eol-bol-keys t
272 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
273 If non-nil, bounce between bol/eol and first/last non-whitespace char."
274 :group 'js2-mode
275 :type 'boolean)
276
277 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
278 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
279 Each value in the list is passed to `define-key'."
280 :type 'list
281 :group 'js2-mode)
282
283 (defcustom js2-idle-timer-delay 0.2
284 "Delay in secs before re-parsing after user makes changes.
285 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
286 :type 'number
287 :group 'js2-mode)
288 (make-variable-buffer-local 'js2-idle-timer-delay)
289
290 (defcustom js2-dynamic-idle-timer-adjust 0
291 "Positive to adjust `js2-idle-timer-delay' based on file size.
292 The idea is that for short files, parsing is faster so we can be
293 more responsive to user edits without interfering with editing.
294 The buffer length in characters (typically bytes) is divided by
295 this value and used to multiply `js2-idle-timer-delay' for the
296 buffer. For example, a 21k file and 10k adjust yields 21k/10k
297 == 2, so js2-idle-timer-delay is multiplied by 2.
298 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
299 `js2-idle-timer-delay' is not dependent on the file size."
300 :type 'number
301 :group 'js2-mode)
302
303 (defcustom js2-mode-escape-quotes t
304 "Non-nil to disable automatic quote-escaping inside strings."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-mode-squeeze-spaces t
309 "Non-nil to normalize whitespace when filling in comments.
310 Multiple runs of spaces are converted to a single space."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-parse-errors t
315 "True to highlight parse errors."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-mode-show-strict-warnings t
320 "Non-nil to emit Ecma strict-mode warnings.
321 Some of the warnings can be individually disabled by other flags,
322 even if this flag is non-nil."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-strict-trailing-comma-warning t
327 "Non-nil to warn about trailing commas in array literals.
328 Ecma-262 forbids them, but many browsers permit them. IE is the
329 big exception, and can produce bugs if you have trailing commas."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-cond-assign-warning t
366 "Non-nil to warn about expressions like if (a = b).
367 This often should have been '==' instead of '='. If the warning
368 is enabled, you can suppress it on a per-expression basis by
369 parenthesizing the expression, e.g. if ((a = b)) ..."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-strict-var-redeclaration-warning t
374 "Non-nil to warn about redeclaring variables in a script or function."
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-strict-var-hides-function-arg-warning t
379 "Non-nil to warn about a var decl hiding a function argument."
380 :type 'boolean
381 :group 'js2-mode)
382
383 (defcustom js2-skip-preprocessor-directives nil
384 "Non-nil to treat lines beginning with # as comments.
385 Useful for viewing Mozilla JavaScript source code."
386 :type 'boolean
387 :group 'js2-mode)
388
389 (defcustom js2-language-version 180
390 "Configures what JavaScript language version to recognize.
391 Currently versions 150, 160, 170 and 180 are supported, corresponding
392 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
393 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
394 and 1.8 adds function closures."
395 :type 'integer
396 :group 'js2-mode)
397
398 (defcustom js2-allow-keywords-as-property-names t
399 "If non-nil, you can use JavaScript keywords as object property names.
400 Examples:
401
402 var foo = {int: 5, while: 6, continue: 7};
403 foo.return = 8;
404
405 Ecma-262 forbids this syntax, but many browsers support it."
406 :type 'boolean
407 :group 'js2-mode)
408
409 (defcustom js2-instanceof-has-side-effects nil
410 "If non-nil, treats the instanceof operator as having side effects.
411 This is useful for xulrunner apps."
412 :type 'boolean
413 :group 'js2-mode)
414
415 (defcustom js2-cleanup-whitespace nil
416 "Non-nil to invoke `delete-trailing-whitespace' before saves."
417 :type 'boolean
418 :group 'js2-mode)
419
420 (defcustom js2-move-point-on-right-click t
421 "Non-nil to move insertion point when you right-click.
422 This makes right-click context menu behavior a bit more intuitive,
423 since menu operations generally apply to the point. The exception
424 is if there is a region selection, in which case the point does -not-
425 move, so cut/copy/paste etc. can work properly.
426
427 Note that IntelliJ moves the point, and Eclipse leaves it alone,
428 so this behavior is customizable."
429 :group 'js2-mode
430 :type 'boolean)
431
432 (defcustom js2-allow-rhino-new-expr-initializer t
433 "Non-nil to support a Rhino's experimental syntactic construct.
434
435 Rhino supports the ability to follow a `new' expression with an object
436 literal, which is used to set additional properties on the new object
437 after calling its constructor. Syntax:
438
439 new <expr> [ ( arglist ) ] [initializer]
440
441 Hence, this expression:
442
443 new Object {a: 1, b: 2}
444
445 results in an Object with properties a=1 and b=2. This syntax is
446 apparently not configurable in Rhino - it's currently always enabled,
447 as of Rhino version 1.7R2."
448 :type 'boolean
449 :group 'js2-mode)
450
451 (defcustom js2-allow-member-expr-as-function-name nil
452 "Non-nil to support experimental Rhino syntax for function names.
453
454 Rhino supports an experimental syntax configured via the Rhino Context
455 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
456
457 function <member-expr> ( [ arg-list ] ) { <body> }
458
459 Where member-expr is a non-parenthesized 'member expression', which
460 is anything at the grammar level of a new-expression or lower, meaning
461 any expression that does not involve infix or unary operators.
462
463 When <member-expr> is not a simple identifier, then it is syntactic
464 sugar for assigning the anonymous function to the <member-expr>. Hence,
465 this code:
466
467 function a.b().c[2] (x, y) { ... }
468
469 is rewritten as:
470
471 a.b().c[2] = function(x, y) {...}
472
473 which doesn't seem particularly useful, but Rhino permits it."
474 :type 'boolean
475 :group 'js2-mode)
476
477 (defvar js2-mode-version 20101228
478 "Release number for `js2-mode'.")
479
480 ;; scanner variables
481
482 (defmacro js2-deflocal (name value &optional comment)
483 "Define a buffer-local variable NAME with VALUE and COMMENT."
484 `(progn
485 (defvar ,name ,value ,comment)
486 (make-variable-buffer-local ',name)))
487
488 ;; We record the start and end position of each token.
489 (js2-deflocal js2-token-beg 1)
490 (js2-deflocal js2-token-end -1)
491
492 (defvar js2-EOF_CHAR -1
493 "Represents end of stream. Distinct from js2-EOF token type.")
494
495 ;; I originally used symbols to represent tokens, but Rhino uses
496 ;; ints and then sets various flag bits in them, so ints it is.
497 ;; The upshot is that we need a `js2-' prefix in front of each name.
498 (defvar js2-ERROR -1)
499 (defvar js2-EOF 0)
500 (defvar js2-EOL 1)
501 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
502 (defvar js2-LEAVEWITH 3)
503 (defvar js2-RETURN 4)
504 (defvar js2-GOTO 5)
505 (defvar js2-IFEQ 6)
506 (defvar js2-IFNE 7)
507 (defvar js2-SETNAME 8)
508 (defvar js2-BITOR 9)
509 (defvar js2-BITXOR 10)
510 (defvar js2-BITAND 11)
511 (defvar js2-EQ 12)
512 (defvar js2-NE 13)
513 (defvar js2-LT 14)
514 (defvar js2-LE 15)
515 (defvar js2-GT 16)
516 (defvar js2-GE 17)
517 (defvar js2-LSH 18)
518 (defvar js2-RSH 19)
519 (defvar js2-URSH 20)
520 (defvar js2-ADD 21) ; infix plus
521 (defvar js2-SUB 22) ; infix minus
522 (defvar js2-MUL 23)
523 (defvar js2-DIV 24)
524 (defvar js2-MOD 25)
525 (defvar js2-NOT 26)
526 (defvar js2-BITNOT 27)
527 (defvar js2-POS 28) ; unary plus
528 (defvar js2-NEG 29) ; unary minus
529 (defvar js2-NEW 30)
530 (defvar js2-DELPROP 31)
531 (defvar js2-TYPEOF 32)
532 (defvar js2-GETPROP 33)
533 (defvar js2-GETPROPNOWARN 34)
534 (defvar js2-SETPROP 35)
535 (defvar js2-GETELEM 36)
536 (defvar js2-SETELEM 37)
537 (defvar js2-CALL 38)
538 (defvar js2-NAME 39) ; an identifier
539 (defvar js2-NUMBER 40)
540 (defvar js2-STRING 41)
541 (defvar js2-NULL 42)
542 (defvar js2-THIS 43)
543 (defvar js2-FALSE 44)
544 (defvar js2-TRUE 45)
545 (defvar js2-SHEQ 46) ; shallow equality (===)
546 (defvar js2-SHNE 47) ; shallow inequality (!==)
547 (defvar js2-REGEXP 48)
548 (defvar js2-BINDNAME 49)
549 (defvar js2-THROW 50)
550 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
551 (defvar js2-IN 52)
552 (defvar js2-INSTANCEOF 53)
553 (defvar js2-LOCAL_LOAD 54)
554 (defvar js2-GETVAR 55)
555 (defvar js2-SETVAR 56)
556 (defvar js2-CATCH_SCOPE 57)
557 (defvar js2-ENUM_INIT_KEYS 58)
558 (defvar js2-ENUM_INIT_VALUES 59)
559 (defvar js2-ENUM_INIT_ARRAY 60)
560 (defvar js2-ENUM_NEXT 61)
561 (defvar js2-ENUM_ID 62)
562 (defvar js2-THISFN 63)
563 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
564 (defvar js2-ARRAYLIT 65) ; array literal
565 (defvar js2-OBJECTLIT 66) ; object literal
566 (defvar js2-GET_REF 67) ; *reference
567 (defvar js2-SET_REF 68) ; *reference = something
568 (defvar js2-DEL_REF 69) ; delete reference
569 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
570 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
571 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
572
573 ;; XML support
574 (defvar js2-DEFAULTNAMESPACE 73)
575 (defvar js2-ESCXMLATTR 74)
576 (defvar js2-ESCXMLTEXT 75)
577 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
578 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
579 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
580 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
581
582 (defvar js2-first-bytecode js2-ENTERWITH)
583 (defvar js2-last-bytecode js2-REF_NS_NAME)
584
585 (defvar js2-TRY 80)
586 (defvar js2-SEMI 81) ; semicolon
587 (defvar js2-LB 82) ; left and right brackets
588 (defvar js2-RB 83)
589 (defvar js2-LC 84) ; left and right curly-braces
590 (defvar js2-RC 85)
591 (defvar js2-LP 86) ; left and right parens
592 (defvar js2-RP 87)
593 (defvar js2-COMMA 88) ; comma operator
594
595 (defvar js2-ASSIGN 89) ; simple assignment (=)
596 (defvar js2-ASSIGN_BITOR 90) ; |=
597 (defvar js2-ASSIGN_BITXOR 91) ; ^=
598 (defvar js2-ASSIGN_BITAND 92) ; &=
599 (defvar js2-ASSIGN_LSH 93) ; <<=
600 (defvar js2-ASSIGN_RSH 94) ; >>=
601 (defvar js2-ASSIGN_URSH 95) ; >>>=
602 (defvar js2-ASSIGN_ADD 96) ; +=
603 (defvar js2-ASSIGN_SUB 97) ; -=
604 (defvar js2-ASSIGN_MUL 98) ; *=
605 (defvar js2-ASSIGN_DIV 99) ; /=
606 (defvar js2-ASSIGN_MOD 100) ; %=
607
608 (defvar js2-first-assign js2-ASSIGN)
609 (defvar js2-last-assign js2-ASSIGN_MOD)
610
611 (defvar js2-HOOK 101) ; conditional (?:)
612 (defvar js2-COLON 102)
613 (defvar js2-OR 103) ; logical or (||)
614 (defvar js2-AND 104) ; logical and (&&)
615 (defvar js2-INC 105) ; increment/decrement (++ --)
616 (defvar js2-DEC 106)
617 (defvar js2-DOT 107) ; member operator (.)
618 (defvar js2-FUNCTION 108) ; function keyword
619 (defvar js2-EXPORT 109) ; export keyword
620 (defvar js2-IMPORT 110) ; import keyword
621 (defvar js2-IF 111) ; if keyword
622 (defvar js2-ELSE 112) ; else keyword
623 (defvar js2-SWITCH 113) ; switch keyword
624 (defvar js2-CASE 114) ; case keyword
625 (defvar js2-DEFAULT 115) ; default keyword
626 (defvar js2-WHILE 116) ; while keyword
627 (defvar js2-DO 117) ; do keyword
628 (defvar js2-FOR 118) ; for keyword
629 (defvar js2-BREAK 119) ; break keyword
630 (defvar js2-CONTINUE 120) ; continue keyword
631 (defvar js2-VAR 121) ; var keyword
632 (defvar js2-WITH 122) ; with keyword
633 (defvar js2-CATCH 123) ; catch keyword
634 (defvar js2-FINALLY 124) ; finally keyword
635 (defvar js2-VOID 125) ; void keyword
636 (defvar js2-RESERVED 126) ; reserved keywords
637
638 (defvar js2-EMPTY 127)
639
640 ;; Types used for the parse tree - never returned by scanner.
641
642 (defvar js2-BLOCK 128) ; statement block
643 (defvar js2-LABEL 129) ; label
644 (defvar js2-TARGET 130)
645 (defvar js2-LOOP 131)
646 (defvar js2-EXPR_VOID 132) ; expression statement in functions
647 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
648 (defvar js2-JSR 134)
649 (defvar js2-SCRIPT 135) ; top-level node for entire script
650 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
651 (defvar js2-USE_STACK 137)
652 (defvar js2-SETPROP_OP 138) ; x.y op= something
653 (defvar js2-SETELEM_OP 139) ; x[y] op= something
654 (defvar js2-LOCAL_BLOCK 140)
655 (defvar js2-SET_REF_OP 141) ; *reference op= something
656
657 ;; For XML support:
658 (defvar js2-DOTDOT 142) ; member operator (..)
659 (defvar js2-COLONCOLON 143) ; namespace::name
660 (defvar js2-XML 144) ; XML type
661 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
662 (defvar js2-XMLATTR 146) ; @
663 (defvar js2-XMLEND 147)
664
665 ;; Optimizer-only tokens
666 (defvar js2-TO_OBJECT 148)
667 (defvar js2-TO_DOUBLE 149)
668
669 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
670 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
671 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
672 (defvar js2-CONST 153)
673 (defvar js2-SETCONST 154)
674 (defvar js2-SETCONSTVAR 155)
675 (defvar js2-ARRAYCOMP 156)
676 (defvar js2-LETEXPR 157)
677 (defvar js2-WITHEXPR 158)
678 (defvar js2-DEBUGGER 159)
679
680 (defvar js2-COMMENT 160)
681 (defvar js2-ENUM 161) ; for "enum" reserved word
682
683 (defconst js2-num-tokens (1+ js2-ENUM))
684
685 (defconst js2-debug-print-trees nil)
686
687 ;; Rhino accepts any string or stream as input. Emacs character
688 ;; processing works best in buffers, so we'll assume the input is a
689 ;; buffer. JavaScript strings can be copied into temp buffers before
690 ;; scanning them.
691
692 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
693 ;; They're the Emacs equivalent of instance variables, more or less.
694
695 (js2-deflocal js2-ts-dirty-line nil
696 "Token stream buffer-local variable.
697 Indicates stuff other than whitespace since start of line.")
698
699 (js2-deflocal js2-ts-regexp-flags nil
700 "Token stream buffer-local variable.")
701
702 (js2-deflocal js2-ts-string ""
703 "Token stream buffer-local variable.
704 Last string scanned.")
705
706 (js2-deflocal js2-ts-number nil
707 "Token stream buffer-local variable.
708 Last literal number scanned.")
709
710 (js2-deflocal js2-ts-hit-eof nil
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-line-start 0
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-lineno 1
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-line-end-char -1
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
723 "Token stream buffer-local variable.
724 Current scan position.")
725
726 (js2-deflocal js2-ts-is-xml-attribute nil
727 "Token stream buffer-local variable.")
728
729 (js2-deflocal js2-ts-xml-is-tag-content nil
730 "Token stream buffer-local variable.")
731
732 (js2-deflocal js2-ts-xml-open-tags-count 0
733 "Token stream buffer-local variable.")
734
735 (js2-deflocal js2-ts-string-buffer nil
736 "Token stream buffer-local variable.
737 List of chars built up while scanning various tokens.")
738
739 (js2-deflocal js2-ts-comment-type nil
740 "Token stream buffer-local variable.")
741
742 ;;; Parser variables
743
744 (js2-deflocal js2-parsed-errors nil
745 "List of errors produced during scanning/parsing.")
746
747 (js2-deflocal js2-parsed-warnings nil
748 "List of warnings produced during scanning/parsing.")
749
750 (js2-deflocal js2-recover-from-parse-errors t
751 "Non-nil to continue parsing after a syntax error.
752
753 In recovery mode, the AST will be built in full, and any error
754 nodes will be flagged with appropriate error information. If
755 this flag is nil, a syntax error will result in an error being
756 signaled.
757
758 The variable is automatically buffer-local, because different
759 modes that use the parser will need different settings.")
760
761 (js2-deflocal js2-parse-hook nil
762 "List of callbacks for receiving parsing progress.")
763
764 (defvar js2-parse-finished-hook nil
765 "List of callbacks to notify when parsing finishes.
766 Not called if parsing was interrupted.")
767
768 (js2-deflocal js2-is-eval-code nil
769 "True if we're evaluating code in a string.
770 If non-nil, the tokenizer will record the token text, and the AST nodes
771 will record their source text. Off by default for IDE modes, since the
772 text is available in the buffer.")
773
774 (defvar js2-parse-ide-mode t
775 "Non-nil if the parser is being used for `js2-mode'.
776 If non-nil, the parser will set text properties for fontification
777 and the syntax table. The value should be nil when using the
778 parser as a frontend to an interpreter or byte compiler.")
779
780 ;;; Parser instance variables (buffer-local vars for js2-parse)
781
782 (defconst js2-clear-ti-mask #xFFFF
783 "Mask to clear token information bits.")
784
785 (defconst js2-ti-after-eol (lsh 1 16)
786 "Flag: first token of the source line.")
787
788 (defconst js2-ti-check-label (lsh 1 17)
789 "Flag: indicates to check for label.")
790
791 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
792
793 (js2-deflocal js2-compiler-generate-debug-info t)
794 (js2-deflocal js2-compiler-use-dynamic-scope nil)
795 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
796 (js2-deflocal js2-compiler-xml-available t)
797 (js2-deflocal js2-compiler-optimization-level 0)
798 (js2-deflocal js2-compiler-generating-source t)
799 (js2-deflocal js2-compiler-strict-mode nil)
800 (js2-deflocal js2-compiler-report-warning-as-error nil)
801 (js2-deflocal js2-compiler-generate-observer-count nil)
802 (js2-deflocal js2-compiler-activation-names nil)
803
804 ;; SKIP: sourceURI
805
806 ;; There's a compileFunction method in Context.java - may need it.
807 (js2-deflocal js2-called-by-compile-function nil
808 "True if `js2-parse' was called by `js2-compile-function'.
809 Will only be used when we finish implementing the interpreter.")
810
811 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
812
813 (js2-deflocal js2-current-flagged-token js2-EOF)
814 (js2-deflocal js2-current-token js2-EOF)
815
816 ;; SKIP: node factory - we're going to just call functions directly,
817 ;; and eventually go to a unified AST format.
818
819 (js2-deflocal js2-nesting-of-function 0)
820
821 (js2-deflocal js2-recorded-identifiers nil
822 "Tracks identifiers found during parsing.")
823
824 (defmacro js2-in-lhs (body)
825 `(let ((js2-is-in-lhs t))
826 ,body))
827
828 (defmacro js2-in-rhs (body)
829 `(let ((js2-is-in-lhs nil))
830 ,body))
831
832 (js2-deflocal js2-is-in-lhs nil
833 "True while parsing lhs statement")
834
835 (defcustom js2-global-externs nil
836 "A list of any extern names you'd like to consider always declared.
837 This list is global and is used by all js2-mode files.
838 You can create buffer-local externs list using `js2-additional-externs'.
839
840 There is also a buffer-local variable `js2-default-externs',
841 which is initialized by default to include the Ecma-262 externs
842 and the standard browser externs. The three lists are all
843 checked during highlighting."
844 :type 'list
845 :group 'js2-mode)
846
847 (js2-deflocal js2-default-externs nil
848 "Default external declarations.
849
850 These are currently only used for highlighting undeclared variables,
851 which only worries about top-level (unqualified) references.
852 As js2-mode's processing improves, we will flesh out this list.
853
854 The initial value is set to `js2-ecma-262-externs', unless you
855 have set `js2-include-browser-externs', in which case the browser
856 externs are also included.
857
858 See `js2-additional-externs' for more information.")
859
860 (defcustom js2-include-browser-externs t
861 "Non-nil to include browser externs in the master externs list.
862 If you work on JavaScript files that are not intended for browsers,
863 such as Mozilla Rhino server-side JavaScript, set this to nil.
864 You can always include them on a per-file basis by calling
865 `js2-add-browser-externs' from a function on `js2-mode-hook'.
866
867 See `js2-additional-externs' for more information about externs."
868 :type 'boolean
869 :group 'js2-mode)
870
871 (defcustom js2-include-rhino-externs t
872 "Non-nil to include Mozilla Rhino externs in the master externs list.
873 See `js2-additional-externs' for more information about externs."
874 :type 'boolean
875 :group 'js2-mode)
876
877 (defcustom js2-include-gears-externs t
878 "Non-nil to include Google Gears externs in the master externs list.
879 See `js2-additional-externs' for more information about externs."
880 :type 'boolean
881 :group 'js2-mode)
882
883 (js2-deflocal js2-additional-externs nil
884 "A buffer-local list of additional external declarations.
885 It is used to decide whether variables are considered undeclared
886 for purposes of highlighting.
887
888 Each entry is a lisp string. The string should be the fully qualified
889 name of an external entity. All externs should be added to this list,
890 so that as js2-mode's processing improves it can take advantage of them.
891
892 You may want to declare your externs in three ways.
893 First, you can add externs that are valid for all your JavaScript files.
894 You should probably do this by adding them to `js2-global-externs', which
895 is a global list used for all js2-mode files.
896
897 Next, you can add a function to `js2-mode-hook' that adds additional
898 externs appropriate for the specific file, perhaps based on its path.
899 These should go in `js2-additional-externs', which is buffer-local.
900
901 Finally, you can add a function to `js2-post-parse-callbacks',
902 which is called after parsing completes, and `root' is bound to
903 the root of the parse tree. At this stage you can set up an AST
904 node visitor using `js2-visit-ast' and examine the parse tree
905 for specific import patterns that may imply the existence of
906 other externs, possibly tied to your build system. These should also
907 be added to `js2-additional-externs'.
908
909 Your post-parse callback may of course also use the simpler and
910 faster (but perhaps less robust) approach of simply scanning the
911 buffer text for your imports, using regular expressions.")
912
913 ;; SKIP: decompiler
914 ;; SKIP: encoded-source
915
916 ;;; The following variables are per-function and should be saved/restored
917 ;;; during function parsing...
918
919 (js2-deflocal js2-current-script-or-fn nil)
920 (js2-deflocal js2-current-scope nil)
921 (js2-deflocal js2-nesting-of-with 0)
922 (js2-deflocal js2-label-set nil
923 "An alist mapping label names to nodes.")
924
925 (js2-deflocal js2-loop-set nil)
926 (js2-deflocal js2-loop-and-switch-set nil)
927 (js2-deflocal js2-has-return-value nil)
928 (js2-deflocal js2-end-flags 0)
929
930 ;;; ...end of per function variables
931
932 ;; Without 2-token lookahead, labels are a problem.
933 ;; These vars store the token info of the last matched name,
934 ;; iff it wasn't the last matched token. Only valid in some contexts.
935 (defvar js2-prev-name-token-start nil)
936 (defvar js2-prev-name-token-string nil)
937
938 (defsubst js2-save-name-token-data (pos name)
939 (setq js2-prev-name-token-start pos
940 js2-prev-name-token-string name))
941
942 ;; These flags enumerate the possible ways a statement/function can
943 ;; terminate. These flags are used by endCheck() and by the Parser to
944 ;; detect inconsistent return usage.
945 ;;
946 ;; END_UNREACHED is reserved for code paths that are assumed to always be
947 ;; able to execute (example: throw, continue)
948 ;;
949 ;; END_DROPS_OFF indicates if the statement can transfer control to the
950 ;; next one. Statement such as return dont. A compound statement may have
951 ;; some branch that drops off control to the next statement.
952 ;;
953 ;; END_RETURNS indicates that the statement can return (without arguments)
954 ;; END_RETURNS_VALUE indicates that the statement can return a value.
955 ;;
956 ;; A compound statement such as
957 ;; if (condition) {
958 ;; return value;
959 ;; }
960 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
961
962 (defconst js2-end-unreached #x0)
963 (defconst js2-end-drops-off #x1)
964 (defconst js2-end-returns #x2)
965 (defconst js2-end-returns-value #x4)
966 (defconst js2-end-yields #x8)
967
968 ;; Rhino awkwardly passes a statementLabel parameter to the
969 ;; statementHelper() function, the main statement parser, which
970 ;; is then used by quite a few of the sub-parsers. We just make
971 ;; it a buffer-local variable and make sure it's cleaned up properly.
972 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
973
974 ;; Similarly, Rhino passes an inForInit boolean through about half
975 ;; the expression parsers. We use a dynamically-scoped variable,
976 ;; which makes it easier to funcall the parsers individually without
977 ;; worrying about whether they take the parameter or not.
978 (js2-deflocal js2-in-for-init nil)
979 (js2-deflocal js2-temp-name-counter 0)
980 (js2-deflocal js2-parse-stmt-count 0)
981
982 (defsubst js2-get-next-temp-name ()
983 (format "$%d" (incf js2-temp-name-counter)))
984
985 (defvar js2-parse-interruptable-p t
986 "Set this to nil to force parse to continue until finished.
987 This will mostly be useful for interpreters.")
988
989 (defvar js2-statements-per-pause 50
990 "Pause after this many statements to check for user input.
991 If user input is pending, stop the parse and discard the tree.
992 This makes for a smoother user experience for large files.
993 You may have to wait a second or two before the highlighting
994 and error-reporting appear, but you can always type ahead if
995 you wish. This appears to be more or less how Eclipse, IntelliJ
996 and other editors work.")
997
998 (js2-deflocal js2-record-comments t
999 "Instructs the scanner to record comments in `js2-scanned-comments'.")
1000
1001 (js2-deflocal js2-scanned-comments nil
1002 "List of all comments from the current parse.")
1003
1004 (defcustom js2-mode-indent-inhibit-undo nil
1005 "Non-nil to disable collection of Undo information when indenting lines.
1006 Some users have requested this behavior. It's nil by default because
1007 other Emacs modes don't work this way."
1008 :type 'boolean
1009 :group 'js2-mode)
1010
1011 (defcustom js2-mode-indent-ignore-first-tab nil
1012 "If non-nil, ignore first TAB keypress if we look indented properly.
1013 It's fairly common for users to navigate to an already-indented line
1014 and press TAB for reassurance that it's been indented. For this class
1015 of users, we want the first TAB press on a line to be ignored if the
1016 line is already indented to one of the precomputed alternatives.
1017
1018 This behavior is only partly implemented. If you TAB-indent a line,
1019 navigate to another line, and then navigate back, it fails to clear
1020 the last-indented variable, so it thinks you've already hit TAB once,
1021 and performs the indent. A full solution would involve getting on the
1022 point-motion hooks for the entire buffer. If we come across another
1023 use cases that requires watching point motion, I'll consider doing it.
1024
1025 If you set this variable to nil, then the TAB key will always change
1026 the indentation of the current line, if more than one alternative
1027 indentation spot exists."
1028 :type 'boolean
1029 :group 'js2-mode)
1030
1031 (defvar js2-indent-hook nil
1032 "A hook for user-defined indentation rules.
1033
1034 Functions on this hook should expect two arguments: (LIST INDEX)
1035 The LIST argument is the list of computed indentation points for
1036 the current line. INDEX is the list index of the indentation point
1037 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1038 indent function is not going to change the current line indentation.
1039
1040 If a hook function on this list returns a non-nil value, then
1041 `js2-bounce-indent' assumes the hook function has performed its own
1042 indentation, and will do nothing. If all hook functions on the list
1043 return nil, then `js2-bounce-indent' will use its computed indentation
1044 and reindent the line.
1045
1046 When hook functions on this hook list are called, the variable
1047 `js2-mode-ast' may or may not be set, depending on whether the
1048 parse tree is available. If the variable is nil, you can pass a
1049 callback to `js2-mode-wait-for-parse', and your callback will be
1050 called after the new parse tree is built. This can take some time
1051 in large files.")
1052
1053 (defface js2-warning-face
1054 `((((class color) (background light))
1055 (:underline "orange"))
1056 (((class color) (background dark))
1057 (:underline "orange"))
1058 (t (:underline t)))
1059 "Face for JavaScript warnings."
1060 :group 'js2-mode)
1061
1062 (defface js2-error-face
1063 `((((class color) (background light))
1064 (:foreground "red"))
1065 (((class color) (background dark))
1066 (:foreground "red"))
1067 (t (:foreground "red")))
1068 "Face for JavaScript errors."
1069 :group 'js2-mode)
1070
1071 (defface js2-jsdoc-tag-face
1072 '((t :foreground "SlateGray"))
1073 "Face used to highlight @whatever tags in jsdoc comments."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-type-face
1077 '((t :foreground "SteelBlue"))
1078 "Face used to highlight {FooBar} types in jsdoc comments."
1079 :group 'js2-mode)
1080
1081 (defface js2-jsdoc-value-face
1082 '((t :foreground "PeachPuff3"))
1083 "Face used to highlight tag values in jsdoc comments."
1084 :group 'js2-mode)
1085
1086 (defface js2-function-param-face
1087 '((t :foreground "SeaGreen"))
1088 "Face used to highlight function parameters in javascript."
1089 :group 'js2-mode)
1090
1091 (defface js2-instance-member-face
1092 '((t :foreground "DarkOrchid"))
1093 "Face used to highlight instance variables in javascript.
1094 Not currently used."
1095 :group 'js2-mode)
1096
1097 (defface js2-private-member-face
1098 '((t :foreground "PeachPuff3"))
1099 "Face used to highlight calls to private methods in javascript.
1100 Not currently used."
1101 :group 'js2-mode)
1102
1103 (defface js2-private-function-call-face
1104 '((t :foreground "goldenrod"))
1105 "Face used to highlight calls to private functions in javascript.
1106 Not currently used."
1107 :group 'js2-mode)
1108
1109 (defface js2-jsdoc-html-tag-name-face
1110 (if js2-emacs22
1111 '((((class color) (min-colors 88) (background light))
1112 (:foreground "rosybrown"))
1113 (((class color) (min-colors 8) (background dark))
1114 (:foreground "yellow"))
1115 (((class color) (min-colors 8) (background light))
1116 (:foreground "magenta")))
1117 '((((type tty pc) (class color) (background light))
1118 (:foreground "magenta"))
1119 (((type tty pc) (class color) (background dark))
1120 (:foreground "yellow"))
1121 (t (:foreground "RosyBrown"))))
1122 "Face used to highlight jsdoc html tag names"
1123 :group 'js2-mode)
1124
1125 (defface js2-jsdoc-html-tag-delimiter-face
1126 (if js2-emacs22
1127 '((((class color) (min-colors 88) (background light))
1128 (:foreground "dark khaki"))
1129 (((class color) (min-colors 8) (background dark))
1130 (:foreground "green"))
1131 (((class color) (min-colors 8) (background light))
1132 (:foreground "green")))
1133 '((((type tty pc) (class color) (background light))
1134 (:foreground "green"))
1135 (((type tty pc) (class color) (background dark))
1136 (:foreground "green"))
1137 (t (:foreground "dark khaki"))))
1138 "Face used to highlight brackets in jsdoc html tags."
1139 :group 'js2-mode)
1140
1141 (defface js2-magic-paren-face
1142 '((t :underline t))
1143 "Face used to color parens that will be auto-overwritten."
1144 :group 'js2-mode)
1145
1146 (defcustom js2-post-parse-callbacks nil
1147 "A list of callback functions invoked after parsing finishes.
1148 Currently, the main use for this function is to add synthetic
1149 declarations to `js2-recorded-identifiers', which see."
1150 :type 'list
1151 :group 'js2-mode)
1152
1153 (defface js2-external-variable-face
1154 '((t :foreground "orange"))
1155 "Face used to highlight undeclared variable identifiers.
1156 An undeclared variable is any variable not declared with var or let
1157 in the current scope or any lexically enclosing scope. If you use
1158 such a variable, then you are either expecting it to originate from
1159 another file, or you've got a potential bug."
1160 :group 'js2-mode)
1161
1162 (defcustom js2-highlight-external-variables t
1163 "Non-nil to highlight undeclared variable identifiers."
1164 :type 'boolean
1165 :group 'js2-mode)
1166
1167 (defcustom js2-auto-insert-catch-block t
1168 "Non-nil to insert matching catch block on open-curly after `try'."
1169 :type 'boolean
1170 :group 'js2-mode)
1171
1172 (defvar js2-mode-map
1173 (let ((map (make-sparse-keymap))
1174 keys)
1175 (define-key map [mouse-1] #'js2-mode-show-node)
1176 (define-key map (kbd "C-m") #'js2-enter-key)
1177 (when js2-rebind-eol-bol-keys
1178 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1179 (define-key map (kbd "C-e") #'js2-end-of-line))
1180 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1181 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1182 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1183 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1184 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1185 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1186 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1187 (define-key map (kbd "C-c C-`") #'js2-next-error)
1188 ;; also define user's preference for next-error, if available
1189 (if (setq keys (where-is-internal #'next-error))
1190 (define-key map (car keys) #'js2-next-error))
1191 (define-key map (or (car (where-is-internal #'mark-defun))
1192 (kbd "M-C-h"))
1193 #'js2-mark-defun)
1194 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1195 (kbd "C-x nd"))
1196 #'js2-narrow-to-defun)
1197 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1198 (when js2-auto-indent-p
1199 (mapc (lambda (key)
1200 (define-key map key #'js2-insert-and-indent))
1201 js2-electric-keys))
1202 (when js2-bounce-indent-p
1203 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1204
1205 (define-key map [menu-bar javascript]
1206 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1207
1208 (define-key map [menu-bar javascript customize-js2-mode]
1209 '(menu-item "Customize js2-mode" js2-mode-customize
1210 :help "Customize the behavior of this mode"))
1211
1212 (define-key map [menu-bar javascript js2-force-refresh]
1213 '(menu-item "Force buffer refresh" js2-mode-reset
1214 :help "Re-parse the buffer from scratch"))
1215
1216 (define-key map [menu-bar javascript separator-2]
1217 '("--"))
1218
1219 (define-key map [menu-bar javascript next-error]
1220 '(menu-item "Next warning or error" js2-next-error
1221 :enabled (and js2-mode-ast
1222 (or (js2-ast-root-errors js2-mode-ast)
1223 (js2-ast-root-warnings js2-mode-ast)))
1224 :help "Move to next warning or error"))
1225
1226 (define-key map [menu-bar javascript display-errors]
1227 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1228 :visible (not js2-mode-show-parse-errors)
1229 :help "Turn on display of warnings and errors"))
1230
1231 (define-key map [menu-bar javascript hide-errors]
1232 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1233 :visible js2-mode-show-parse-errors
1234 :help "Turn off display of warnings and errors"))
1235
1236 (define-key map [menu-bar javascript separator-1]
1237 '("--"))
1238
1239 (define-key map [menu-bar javascript js2-toggle-function]
1240 '(menu-item "Show/collapse element" js2-mode-toggle-element
1241 :help "Hide or show function body or comment"))
1242
1243 (define-key map [menu-bar javascript show-comments]
1244 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1245 :visible js2-mode-comments-hidden
1246 :help "Expand all hidden block comments"))
1247
1248 (define-key map [menu-bar javascript hide-comments]
1249 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1250 :visible (not js2-mode-comments-hidden)
1251 :help "Show block comments as /*...*/"))
1252
1253 (define-key map [menu-bar javascript show-all-functions]
1254 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1255 :visible js2-mode-functions-hidden
1256 :help "Expand all hidden function bodies"))
1257
1258 (define-key map [menu-bar javascript hide-all-functions]
1259 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1260 :visible (not js2-mode-functions-hidden)
1261 :help "Show {...} for all top-level function bodies"))
1262
1263 map)
1264 "Keymap used in `js2-mode' buffers.")
1265
1266 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1267
1268 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1269 "Matches a //-comment line. Must be first non-whitespace on line.
1270 First match-group is the leading whitespace.")
1271
1272 (defvar js2-mode-hook nil)
1273
1274 (js2-deflocal js2-mode-ast nil "Private variable.")
1275 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1276 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1277 (js2-deflocal js2-mode-parsing nil "Private variable.")
1278 (js2-deflocal js2-mode-node-overlay nil)
1279
1280 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1281 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1282
1283 (js2-deflocal js2-mode-fontifications nil "Private variable")
1284 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1285 (js2-deflocal js2-imenu-recorder nil "Private variable")
1286 (js2-deflocal js2-imenu-function-map nil "Private variable")
1287
1288 (defvar js2-paragraph-start
1289 "\\(@[a-zA-Z]+\\>\\|$\\)")
1290
1291 ;; Note that we also set a 'c-in-sws text property in html comments,
1292 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1293 (defvar js2-syntactic-ws-start
1294 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1295
1296 (defvar js2-syntactic-ws-end
1297 "\\s \\|[\n\r/]\\|\\s!")
1298
1299 (defvar js2-syntactic-eol
1300 (concat "\\s *\\(/\\*[^*\n\r]*"
1301 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1302 "\\*+/\\s *\\)*"
1303 "\\(//\\|/\\*[^*\n\r]*"
1304 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1305 "\\|\\\\$\\|$\\)")
1306 "Copied from `java-mode'. Needed for some cc-engine functions.")
1307
1308 (defvar js2-comment-prefix-regexp
1309 "//+\\|\\**")
1310
1311 (defvar js2-comment-start-skip
1312 "\\(//+\\|/\\*+\\)\\s *")
1313
1314 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1315 "Non-nil to emit status messages during parsing.")
1316
1317 (defvar js2-mode-functions-hidden nil "private variable")
1318 (defvar js2-mode-comments-hidden nil "private variable")
1319
1320 (defvar js2-mode-syntax-table
1321 (let ((table (make-syntax-table)))
1322 (c-populate-syntax-table table)
1323 table)
1324 "Syntax table used in js2-mode buffers.")
1325
1326 (defvar js2-mode-abbrev-table nil
1327 "Abbrev table in use in `js2-mode' buffers.")
1328 (define-abbrev-table 'js2-mode-abbrev-table ())
1329
1330 (defvar js2-mode-pending-parse-callbacks nil
1331 "List of functions waiting to be notified that parse is finished.")
1332
1333 (defvar js2-mode-last-indented-line -1)
1334
1335 ;;; Localizable error and warning messages
1336
1337 ;; Messages are copied from Rhino's Messages.properties.
1338 ;; Many of the Java-specific messages have been elided.
1339 ;; Add any js2-specific ones at the end, so we can keep
1340 ;; this file synced with changes to Rhino's.
1341
1342 (defvar js2-message-table
1343 (make-hash-table :test 'equal :size 250)
1344 "Contains localized messages for js2-mode.")
1345
1346 ;; TODO(stevey): construct this table at compile-time.
1347 (defmacro js2-msg (key &rest strings)
1348 `(puthash ,key (funcall #'concat ,@strings)
1349 js2-message-table))
1350
1351 (defun js2-get-msg (msg-key)
1352 "Look up a localized message.
1353 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1354 the correct number of ARGS must be provided."
1355 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1356 (args (if (listp msg-key) (cdr msg-key)))
1357 (msg (gethash key js2-message-table)))
1358 (if msg
1359 (apply #'format msg args)
1360 key))) ; default to showing the key
1361
1362 (js2-msg "msg.dup.parms"
1363 "Duplicate parameter name '%s'.")
1364
1365 (js2-msg "msg.too.big.jump"
1366 "Program too complex: jump offset too big.")
1367
1368 (js2-msg "msg.too.big.index"
1369 "Program too complex: internal index exceeds 64K limit.")
1370
1371 (js2-msg "msg.while.compiling.fn"
1372 "Encountered code generation error while compiling function '%s': %s")
1373
1374 (js2-msg "msg.while.compiling.script"
1375 "Encountered code generation error while compiling script: %s")
1376
1377 ;; Context
1378 (js2-msg "msg.ctor.not.found"
1379 "Constructor for '%s' not found.")
1380
1381 (js2-msg "msg.not.ctor"
1382 "'%s' is not a constructor.")
1383
1384 ;; FunctionObject
1385 (js2-msg "msg.varargs.ctor"
1386 "Method or constructor '%s' must be static "
1387 "with the signature (Context cx, Object[] args, "
1388 "Function ctorObj, boolean inNewExpr) "
1389 "to define a variable arguments constructor.")
1390
1391 (js2-msg "msg.varargs.fun"
1392 "Method '%s' must be static with the signature "
1393 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1394 "to define a variable arguments function.")
1395
1396 (js2-msg "msg.incompat.call"
1397 "Method '%s' called on incompatible object.")
1398
1399 (js2-msg "msg.bad.parms"
1400 "Unsupported parameter type '%s' in method '%s'.")
1401
1402 (js2-msg "msg.bad.method.return"
1403 "Unsupported return type '%s' in method '%s'.")
1404
1405 (js2-msg "msg.bad.ctor.return"
1406 "Construction of objects of type '%s' is not supported.")
1407
1408 (js2-msg "msg.no.overload"
1409 "Method '%s' occurs multiple times in class '%s'.")
1410
1411 (js2-msg "msg.method.not.found"
1412 "Method '%s' not found in '%s'.")
1413
1414 ;; IRFactory
1415
1416 (js2-msg "msg.bad.for.in.lhs"
1417 "Invalid left-hand side of for..in loop.")
1418
1419 (js2-msg "msg.mult.index"
1420 "Only one variable allowed in for..in loop.")
1421
1422 (js2-msg "msg.bad.for.in.destruct"
1423 "Left hand side of for..in loop must be an array of "
1424 "length 2 to accept key/value pair.")
1425
1426 (js2-msg "msg.cant.convert"
1427 "Can't convert to type '%s'.")
1428
1429 (js2-msg "msg.bad.assign.left"
1430 "Invalid assignment left-hand side.")
1431
1432 (js2-msg "msg.bad.decr"
1433 "Invalid decerement operand.")
1434
1435 (js2-msg "msg.bad.incr"
1436 "Invalid increment operand.")
1437
1438 (js2-msg "msg.bad.yield"
1439 "yield must be in a function.")
1440
1441 (js2-msg "msg.yield.parenthesized"
1442 "yield expression must be parenthesized.")
1443
1444 ;; NativeGlobal
1445 (js2-msg "msg.cant.call.indirect"
1446 "Function '%s' must be called directly, and not by way of a "
1447 "function of another name.")
1448
1449 (js2-msg "msg.eval.nonstring"
1450 "Calling eval() with anything other than a primitive "
1451 "string value will simply return the value. "
1452 "Is this what you intended?")
1453
1454 (js2-msg "msg.eval.nonstring.strict"
1455 "Calling eval() with anything other than a primitive "
1456 "string value is not allowed in strict mode.")
1457
1458 (js2-msg "msg.bad.destruct.op"
1459 "Invalid destructuring assignment operator")
1460
1461 ;; NativeCall
1462 (js2-msg "msg.only.from.new"
1463 "'%s' may only be invoked from a `new' expression.")
1464
1465 (js2-msg "msg.deprec.ctor"
1466 "The '%s' constructor is deprecated.")
1467
1468 ;; NativeFunction
1469 (js2-msg "msg.no.function.ref.found"
1470 "no source found to decompile function reference %s")
1471
1472 (js2-msg "msg.arg.isnt.array"
1473 "second argument to Function.prototype.apply must be an array")
1474
1475 ;; NativeGlobal
1476 (js2-msg "msg.bad.esc.mask"
1477 "invalid string escape mask")
1478
1479 ;; NativeRegExp
1480 (js2-msg "msg.bad.quant"
1481 "Invalid quantifier %s")
1482
1483 (js2-msg "msg.overlarge.backref"
1484 "Overly large back reference %s")
1485
1486 (js2-msg "msg.overlarge.min"
1487 "Overly large minimum %s")
1488
1489 (js2-msg "msg.overlarge.max"
1490 "Overly large maximum %s")
1491
1492 (js2-msg "msg.zero.quant"
1493 "Zero quantifier %s")
1494
1495 (js2-msg "msg.max.lt.min"
1496 "Maximum %s less than minimum")
1497
1498 (js2-msg "msg.unterm.quant"
1499 "Unterminated quantifier %s")
1500
1501 (js2-msg "msg.unterm.paren"
1502 "Unterminated parenthetical %s")
1503
1504 (js2-msg "msg.unterm.class"
1505 "Unterminated character class %s")
1506
1507 (js2-msg "msg.bad.range"
1508 "Invalid range in character class.")
1509
1510 (js2-msg "msg.trail.backslash"
1511 "Trailing \\ in regular expression.")
1512
1513 (js2-msg "msg.re.unmatched.right.paren"
1514 "unmatched ) in regular expression.")
1515
1516 (js2-msg "msg.no.regexp"
1517 "Regular expressions are not available.")
1518
1519 (js2-msg "msg.bad.backref"
1520 "back-reference exceeds number of capturing parentheses.")
1521
1522 (js2-msg "msg.bad.regexp.compile"
1523 "Only one argument may be specified if the first "
1524 "argument to RegExp.prototype.compile is a RegExp object.")
1525
1526 ;; Parser
1527 (js2-msg "msg.got.syntax.errors"
1528 "Compilation produced %s syntax errors.")
1529
1530 (js2-msg "msg.var.redecl"
1531 "TypeError: redeclaration of var %s.")
1532
1533 (js2-msg "msg.const.redecl"
1534 "TypeError: redeclaration of const %s.")
1535
1536 (js2-msg "msg.let.redecl"
1537 "TypeError: redeclaration of variable %s.")
1538
1539 (js2-msg "msg.parm.redecl"
1540 "TypeError: redeclaration of formal parameter %s.")
1541
1542 (js2-msg "msg.fn.redecl"
1543 "TypeError: redeclaration of function %s.")
1544
1545 (js2-msg "msg.let.decl.not.in.block"
1546 "SyntaxError: let declaration not directly within block")
1547
1548 ;; NodeTransformer
1549 (js2-msg "msg.dup.label"
1550 "duplicated label")
1551
1552 (js2-msg "msg.undef.label"
1553 "undefined label")
1554
1555 (js2-msg "msg.bad.break"
1556 "unlabelled break must be inside loop or switch")
1557
1558 (js2-msg "msg.continue.outside"
1559 "continue must be inside loop")
1560
1561 (js2-msg "msg.continue.nonloop"
1562 "continue can only use labels of iteration statements")
1563
1564 (js2-msg "msg.bad.throw.eol"
1565 "Line terminator is not allowed between the throw "
1566 "keyword and throw expression.")
1567
1568 (js2-msg "msg.no.paren.parms"
1569 "missing ( before function parameters.")
1570
1571 (js2-msg "msg.no.parm"
1572 "missing formal parameter")
1573
1574 (js2-msg "msg.no.paren.after.parms"
1575 "missing ) after formal parameters")
1576
1577 (js2-msg "msg.no.brace.body"
1578 "missing '{' before function body")
1579
1580 (js2-msg "msg.no.brace.after.body"
1581 "missing } after function body")
1582
1583 (js2-msg "msg.no.paren.cond"
1584 "missing ( before condition")
1585
1586 (js2-msg "msg.no.paren.after.cond"
1587 "missing ) after condition")
1588
1589 (js2-msg "msg.no.semi.stmt"
1590 "missing ; before statement")
1591
1592 (js2-msg "msg.missing.semi"
1593 "missing ; after statement")
1594
1595 (js2-msg "msg.no.name.after.dot"
1596 "missing name after . operator")
1597
1598 (js2-msg "msg.no.name.after.coloncolon"
1599 "missing name after :: operator")
1600
1601 (js2-msg "msg.no.name.after.dotdot"
1602 "missing name after .. operator")
1603
1604 (js2-msg "msg.no.name.after.xmlAttr"
1605 "missing name after .@")
1606
1607 (js2-msg "msg.no.bracket.index"
1608 "missing ] in index expression")
1609
1610 (js2-msg "msg.no.paren.switch"
1611 "missing ( before switch expression")
1612
1613 (js2-msg "msg.no.paren.after.switch"
1614 "missing ) after switch expression")
1615
1616 (js2-msg "msg.no.brace.switch"
1617 "missing '{' before switch body")
1618
1619 (js2-msg "msg.bad.switch"
1620 "invalid switch statement")
1621
1622 (js2-msg "msg.no.colon.case"
1623 "missing : after case expression")
1624
1625 (js2-msg "msg.double.switch.default"
1626 "double default label in the switch statement")
1627
1628 (js2-msg "msg.no.while.do"
1629 "missing while after do-loop body")
1630
1631 (js2-msg "msg.no.paren.for"
1632 "missing ( after for")
1633
1634 (js2-msg "msg.no.semi.for"
1635 "missing ; after for-loop initializer")
1636
1637 (js2-msg "msg.no.semi.for.cond"
1638 "missing ; after for-loop condition")
1639
1640 (js2-msg "msg.in.after.for.name"
1641 "missing in after for")
1642
1643 (js2-msg "msg.no.paren.for.ctrl"
1644 "missing ) after for-loop control")
1645
1646 (js2-msg "msg.no.paren.with"
1647 "missing ( before with-statement object")
1648
1649 (js2-msg "msg.no.paren.after.with"
1650 "missing ) after with-statement object")
1651
1652 (js2-msg "msg.no.paren.after.let"
1653 "missing ( after let")
1654
1655 (js2-msg "msg.no.paren.let"
1656 "missing ) after variable list")
1657
1658 (js2-msg "msg.no.curly.let"
1659 "missing } after let statement")
1660
1661 (js2-msg "msg.bad.return"
1662 "invalid return")
1663
1664 (js2-msg "msg.no.brace.block"
1665 "missing } in compound statement")
1666
1667 (js2-msg "msg.bad.label"
1668 "invalid label")
1669
1670 (js2-msg "msg.bad.var"
1671 "missing variable name")
1672
1673 (js2-msg "msg.bad.var.init"
1674 "invalid variable initialization")
1675
1676 (js2-msg "msg.no.colon.cond"
1677 "missing : in conditional expression")
1678
1679 (js2-msg "msg.no.paren.arg"
1680 "missing ) after argument list")
1681
1682 (js2-msg "msg.no.bracket.arg"
1683 "missing ] after element list")
1684
1685 (js2-msg "msg.bad.prop"
1686 "invalid property id")
1687
1688 (js2-msg "msg.no.colon.prop"
1689 "missing : after property id")
1690
1691 (js2-msg "msg.no.brace.prop"
1692 "missing } after property list")
1693
1694 (js2-msg "msg.no.paren"
1695 "missing ) in parenthetical")
1696
1697 (js2-msg "msg.reserved.id"
1698 "identifier is a reserved word")
1699
1700 (js2-msg "msg.no.paren.catch"
1701 "missing ( before catch-block condition")
1702
1703 (js2-msg "msg.bad.catchcond"
1704 "invalid catch block condition")
1705
1706 (js2-msg "msg.catch.unreachable"
1707 "any catch clauses following an unqualified catch are unreachable")
1708
1709 (js2-msg "msg.no.brace.try"
1710 "missing '{' before try block")
1711
1712 (js2-msg "msg.no.brace.catchblock"
1713 "missing '{' before catch-block body")
1714
1715 (js2-msg "msg.try.no.catchfinally"
1716 "'try' without 'catch' or 'finally'")
1717
1718 (js2-msg "msg.no.return.value"
1719 "function %s does not always return a value")
1720
1721 (js2-msg "msg.anon.no.return.value"
1722 "anonymous function does not always return a value")
1723
1724 (js2-msg "msg.return.inconsistent"
1725 "return statement is inconsistent with previous usage")
1726
1727 (js2-msg "msg.generator.returns"
1728 "TypeError: generator function '%s' returns a value")
1729
1730 (js2-msg "msg.anon.generator.returns"
1731 "TypeError: anonymous generator function returns a value")
1732
1733 (js2-msg "msg.syntax"
1734 "syntax error")
1735
1736 (js2-msg "msg.unexpected.eof"
1737 "Unexpected end of file")
1738
1739 (js2-msg "msg.XML.bad.form"
1740 "illegally formed XML syntax")
1741
1742 (js2-msg "msg.XML.not.available"
1743 "XML runtime not available")
1744
1745 (js2-msg "msg.too.deep.parser.recursion"
1746 "Too deep recursion while parsing")
1747
1748 (js2-msg "msg.no.side.effects"
1749 "Code has no side effects")
1750
1751 (js2-msg "msg.extra.trailing.comma"
1752 "Trailing comma is not legal in an ECMA-262 object initializer")
1753
1754 (js2-msg "msg.array.trailing.comma"
1755 "Trailing comma yields different behavior across browsers")
1756
1757 (js2-msg "msg.equal.as.assign"
1758 (concat "Test for equality (==) mistyped as assignment (=)?"
1759 " (parenthesize to suppress warning)"))
1760
1761 (js2-msg "msg.var.hides.arg"
1762 "Variable %s hides argument")
1763
1764 (js2-msg "msg.destruct.assign.no.init"
1765 "Missing = in destructuring declaration")
1766
1767 ;; ScriptRuntime
1768 (js2-msg "msg.no.properties"
1769 "%s has no properties.")
1770
1771 (js2-msg "msg.invalid.iterator"
1772 "Invalid iterator value")
1773
1774 (js2-msg "msg.iterator.primitive"
1775 "__iterator__ returned a primitive value")
1776
1777 (js2-msg "msg.assn.create.strict"
1778 "Assignment to undeclared variable %s")
1779
1780 (js2-msg "msg.ref.undefined.prop"
1781 "Reference to undefined property '%s'")
1782
1783 (js2-msg "msg.prop.not.found"
1784 "Property %s not found.")
1785
1786 (js2-msg "msg.invalid.type"
1787 "Invalid JavaScript value of type %s")
1788
1789 (js2-msg "msg.primitive.expected"
1790 "Primitive type expected (had %s instead)")
1791
1792 (js2-msg "msg.namespace.expected"
1793 "Namespace object expected to left of :: (found %s instead)")
1794
1795 (js2-msg "msg.null.to.object"
1796 "Cannot convert null to an object.")
1797
1798 (js2-msg "msg.undef.to.object"
1799 "Cannot convert undefined to an object.")
1800
1801 (js2-msg "msg.cyclic.value"
1802 "Cyclic %s value not allowed.")
1803
1804 (js2-msg "msg.is.not.defined"
1805 "'%s' is not defined.")
1806
1807 (js2-msg "msg.undef.prop.read"
1808 "Cannot read property '%s' from %s")
1809
1810 (js2-msg "msg.undef.prop.write"
1811 "Cannot set property '%s' of %s to '%s'")
1812
1813 (js2-msg "msg.undef.prop.delete"
1814 "Cannot delete property '%s' of %s")
1815
1816 (js2-msg "msg.undef.method.call"
1817 "Cannot call method '%s' of %s")
1818
1819 (js2-msg "msg.undef.with"
1820 "Cannot apply 'with' to %s")
1821
1822 (js2-msg "msg.isnt.function"
1823 "%s is not a function, it is %s.")
1824
1825 (js2-msg "msg.isnt.function.in"
1826 "Cannot call property %s in object %s. "
1827 "It is not a function, it is '%s'.")
1828
1829 (js2-msg "msg.function.not.found"
1830 "Cannot find function %s.")
1831
1832 (js2-msg "msg.function.not.found.in"
1833 "Cannot find function %s in object %s.")
1834
1835 (js2-msg "msg.isnt.xml.object"
1836 "%s is not an xml object.")
1837
1838 (js2-msg "msg.no.ref.to.get"
1839 "%s is not a reference to read reference value.")
1840
1841 (js2-msg "msg.no.ref.to.set"
1842 "%s is not a reference to set reference value to %s.")
1843
1844 (js2-msg "msg.no.ref.from.function"
1845 "Function %s can not be used as the left-hand "
1846 "side of assignment or as an operand of ++ or -- operator.")
1847
1848 (js2-msg "msg.bad.default.value"
1849 "Object's getDefaultValue() method returned an object.")
1850
1851 (js2-msg "msg.instanceof.not.object"
1852 "Can't use instanceof on a non-object.")
1853
1854 (js2-msg "msg.instanceof.bad.prototype"
1855 "'prototype' property of %s is not an object.")
1856
1857 (js2-msg "msg.bad.radix"
1858 "illegal radix %s.")
1859
1860 ;; ScriptableObject
1861 (js2-msg "msg.default.value"
1862 "Cannot find default value for object.")
1863
1864 (js2-msg "msg.zero.arg.ctor"
1865 "Cannot load class '%s' which has no zero-parameter constructor.")
1866
1867 (js2-msg "msg.ctor.multiple.parms"
1868 "Can't define constructor or class %s since more than "
1869 "one constructor has multiple parameters.")
1870
1871 (js2-msg "msg.extend.scriptable"
1872 "%s must extend ScriptableObject in order to define property %s.")
1873
1874 (js2-msg "msg.bad.getter.parms"
1875 "In order to define a property, getter %s must have zero "
1876 "parameters or a single ScriptableObject parameter.")
1877
1878 (js2-msg "msg.obj.getter.parms"
1879 "Expected static or delegated getter %s to take "
1880 "a ScriptableObject parameter.")
1881
1882 (js2-msg "msg.getter.static"
1883 "Getter and setter must both be static or neither be static.")
1884
1885 (js2-msg "msg.setter.return"
1886 "Setter must have void return type: %s")
1887
1888 (js2-msg "msg.setter2.parms"
1889 "Two-parameter setter must take a ScriptableObject as "
1890 "its first parameter.")
1891
1892 (js2-msg "msg.setter1.parms"
1893 "Expected single parameter setter for %s")
1894
1895 (js2-msg "msg.setter2.expected"
1896 "Expected static or delegated setter %s to take two parameters.")
1897
1898 (js2-msg "msg.setter.parms"
1899 "Expected either one or two parameters for setter.")
1900
1901 (js2-msg "msg.setter.bad.type"
1902 "Unsupported parameter type '%s' in setter '%s'.")
1903
1904 (js2-msg "msg.add.sealed"
1905 "Cannot add a property to a sealed object: %s.")
1906
1907 (js2-msg "msg.remove.sealed"
1908 "Cannot remove a property from a sealed object: %s.")
1909
1910 (js2-msg "msg.modify.sealed"
1911 "Cannot modify a property of a sealed object: %s.")
1912
1913 (js2-msg "msg.modify.readonly"
1914 "Cannot modify readonly property: %s.")
1915
1916 ;; TokenStream
1917 (js2-msg "msg.missing.exponent"
1918 "missing exponent")
1919
1920 (js2-msg "msg.caught.nfe"
1921 "number format error")
1922
1923 (js2-msg "msg.unterminated.string.lit"
1924 "unterminated string literal")
1925
1926 (js2-msg "msg.unterminated.comment"
1927 "unterminated comment")
1928
1929 (js2-msg "msg.unterminated.re.lit"
1930 "unterminated regular expression literal")
1931
1932 (js2-msg "msg.invalid.re.flag"
1933 "invalid flag after regular expression")
1934
1935 (js2-msg "msg.no.re.input.for"
1936 "no input for %s")
1937
1938 (js2-msg "msg.illegal.character"
1939 "illegal character")
1940
1941 (js2-msg "msg.invalid.escape"
1942 "invalid Unicode escape sequence")
1943
1944 (js2-msg "msg.bad.namespace"
1945 "not a valid default namespace statement. "
1946 "Syntax is: default xml namespace = EXPRESSION;")
1947
1948 ;; TokensStream warnings
1949 (js2-msg "msg.bad.octal.literal"
1950 "illegal octal literal digit %s; "
1951 "interpreting it as a decimal digit")
1952
1953 (js2-msg "msg.reserved.keyword"
1954 "illegal usage of future reserved keyword %s; "
1955 "interpreting it as ordinary identifier")
1956
1957 (js2-msg "msg.script.is.not.constructor"
1958 "Script objects are not constructors.")
1959
1960 ;; Arrays
1961 (js2-msg "msg.arraylength.bad"
1962 "Inappropriate array length.")
1963
1964 ;; Arrays
1965 (js2-msg "msg.arraylength.too.big"
1966 "Array length %s exceeds supported capacity limit.")
1967
1968 ;; URI
1969 (js2-msg "msg.bad.uri"
1970 "Malformed URI sequence.")
1971
1972 ;; Number
1973 (js2-msg "msg.bad.precision"
1974 "Precision %s out of range.")
1975
1976 ;; NativeGenerator
1977 (js2-msg "msg.send.newborn"
1978 "Attempt to send value to newborn generator")
1979
1980 (js2-msg "msg.already.exec.gen"
1981 "Already executing generator")
1982
1983 (js2-msg "msg.StopIteration.invalid"
1984 "StopIteration may not be changed to an arbitrary object.")
1985
1986 ;; Interpreter
1987 (js2-msg "msg.yield.closing"
1988 "Yield from closing generator")
1989
1990 ;;; Utilities
1991
1992 (defun js2-delete-if (predicate list)
1993 "Remove all items satisfying PREDICATE in LIST."
1994 (loop for item in list
1995 if (not (funcall predicate item))
1996 collect item))
1997
1998 (defun js2-position (element list)
1999 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2000 Returns nil if element is not found in the list."
2001 (let ((count 0)
2002 found)
2003 (while (and list (not found))
2004 (if (eq element (car list))
2005 (setq found t)
2006 (setq count (1+ count)
2007 list (cdr list))))
2008 (if found count)))
2009
2010 (defun js2-find-if (predicate list)
2011 "Find first item satisfying PREDICATE in LIST."
2012 (let (result)
2013 (while (and list (not result))
2014 (if (funcall predicate (car list))
2015 (setq result (car list)))
2016 (setq list (cdr list)))
2017 result))
2018
2019 (defmacro js2-time (form)
2020 "Evaluate FORM, discard result, and return elapsed time in sec"
2021 (declare (debug t))
2022 (let ((beg (make-symbol "--js2-time-beg--"))
2023 (delta (make-symbol "--js2-time-end--")))
2024 `(let ((,beg (current-time))
2025 ,delta)
2026 ,form
2027 (/ (truncate (* (- (float-time (current-time))
2028 (float-time ,beg))
2029 10000))
2030 10000.0))))
2031
2032 (defsubst js2-same-line (pos)
2033 "Return t if POS is on the same line as current point."
2034 (and (>= pos (point-at-bol))
2035 (<= pos (point-at-eol))))
2036
2037 (defsubst js2-same-line-2 (p1 p2)
2038 "Return t if p1 is on the same line as p2."
2039 (save-excursion
2040 (goto-char p1)
2041 (js2-same-line p2)))
2042
2043 (defun js2-code-bug ()
2044 "Signal an error when we encounter an unexpected code path."
2045 (error "failed assertion"))
2046
2047 (defsubst js2-record-text-property (beg end prop value)
2048 "Record a text property to set when parsing finishes."
2049 (push (list beg end prop value) js2-mode-deferred-properties))
2050
2051 ;; I'd like to associate errors with nodes, but for now the
2052 ;; easiest thing to do is get the context info from the last token.
2053 (defsubst js2-record-parse-error (msg &optional arg pos len)
2054 (push (list (list msg arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2057 js2-parsed-errors))
2058
2059 (defsubst js2-report-error (msg &optional msg-arg pos len)
2060 "Signal a syntax error or record a parse error."
2061 (if js2-recover-from-parse-errors
2062 (js2-record-parse-error msg msg-arg pos len)
2063 (signal 'js2-syntax-error
2064 (list msg
2065 js2-ts-lineno
2066 (save-excursion
2067 (goto-char js2-ts-cursor)
2068 (current-column))
2069 js2-ts-hit-eof))))
2070
2071 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2072 (if js2-compiler-report-warning-as-error
2073 (js2-report-error msg msg-arg pos len)
2074 (push (list (list msg msg-arg)
2075 (or pos js2-token-beg)
2076 (or len (- js2-token-end js2-token-beg)))
2077 js2-parsed-warnings)))
2078
2079 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2080 (if js2-compiler-strict-mode
2081 (js2-report-warning msg-id msg-arg beg
2082 (and beg end (- end beg)))))
2083
2084 (put 'js2-syntax-error 'error-conditions
2085 '(error syntax-error js2-syntax-error))
2086 (put 'js2-syntax-error 'error-message "Syntax error")
2087
2088 (put 'js2-parse-error 'error-conditions
2089 '(error parse-error js2-parse-error))
2090 (put 'js2-parse-error 'error-message "Parse error")
2091
2092 (defmacro js2-clear-flag (flags flag)
2093 `(setq ,flags (logand ,flags (lognot ,flag))))
2094
2095 (defmacro js2-set-flag (flags flag)
2096 "Logical-or FLAG into FLAGS."
2097 `(setq ,flags (logior ,flags ,flag)))
2098
2099 (defsubst js2-flag-set-p (flags flag)
2100 (/= 0 (logand flags flag)))
2101
2102 (defsubst js2-flag-not-set-p (flags flag)
2103 (zerop (logand flags flag)))
2104
2105 ;; Stolen shamelessly from James Clark's nxml-mode.
2106 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2107 "Evaluate BODY without any text property changes modifying the buffer.
2108 Any text properties changes happen as usual but the changes are not treated as
2109 modifications to the buffer."
2110 (declare (indent 0) (debug t))
2111 (let ((modified (make-symbol "modified")))
2112 `(let ((,modified (buffer-modified-p))
2113 (inhibit-read-only t)
2114 (inhibit-modification-hooks t)
2115 (buffer-undo-list t)
2116 (deactivate-mark nil)
2117 ;; Apparently these avoid file locking problems.
2118 (buffer-file-name nil)
2119 (buffer-file-truename nil))
2120 (unwind-protect
2121 (progn ,@body)
2122 (unless ,modified
2123 (restore-buffer-modified-p nil))))))
2124
2125 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2126 "Evaluate BODY with the _ character set to be word-syntax."
2127 (declare (indent 0) (debug t))
2128 (let ((old-syntax (make-symbol "old-syntax")))
2129 `(let ((,old-syntax (string (char-syntax ?_))))
2130 (unwind-protect
2131 (progn
2132 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2133 ,@body)
2134 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2135
2136 (defsubst js2-char-uppercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2139 (/= c (downcase c)))
2140
2141 (defsubst js2-char-lowercase-p (c)
2142 "Return t if C is an uppercase character.
2143 Handles unicode and latin chars properly."
2144 (/= c (upcase c)))
2145
2146 ;;; AST struct and function definitions
2147
2148 ;; flags for ast node property 'member-type (used for e4x operators)
2149 (defvar js2-property-flag #x1 "property access: element is valid name")
2150 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2151 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2152
2153 (defsubst js2-relpos (pos anchor)
2154 "Convert POS to be relative to ANCHOR.
2155 If POS is nil, returns nil."
2156 (and pos (- pos anchor)))
2157
2158 (defsubst js2-make-pad (indent)
2159 (if (zerop indent)
2160 ""
2161 (make-string (* indent js2-basic-offset) ? )))
2162
2163 (defsubst js2-visit-ast (node callback)
2164 "Visit every node in ast NODE with visitor CALLBACK.
2165
2166 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2167 called twice: once to visit the node, and again after all the node's
2168 children have been processed. The END-P argument is nil on the first
2169 call and non-nil on the second call. The return value of the callback
2170 affects the traversal: if non-nil, the children of NODE are processed.
2171 If the callback returns nil, or if the node has no children, then the
2172 callback is called immediately with a non-nil END-P argument.
2173
2174 The node traversal is approximately lexical-order, although there
2175 are currently no guarantees around this."
2176 (if node
2177 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2178 ;; visit the node
2179 (when (funcall callback node nil)
2180 ;; visit the kids
2181 (cond
2182 ((eq vfunc 'js2-visit-none)
2183 nil) ; don't even bother calling it
2184 ;; Each AST node type has to define a `js2-visitor' function
2185 ;; that takes a node and a callback, and calls `js2-visit-ast'
2186 ;; on each child of the node.
2187 (vfunc
2188 (funcall vfunc node callback))
2189 (t
2190 (error "%s does not define a visitor-traversal function"
2191 (aref node 0)))))
2192 ;; call the end-visit
2193 (funcall callback node t))))
2194
2195 (defstruct (js2-node
2196 (:constructor nil)) ; abstract
2197 "Base AST node type."
2198 (type -1) ; token type
2199 (pos -1) ; start position of this AST node in parsed input
2200 (len 1) ; num characters spanned by the node
2201 props ; optional node property list (an alist)
2202 parent) ; link to parent node; null for root
2203
2204 (defsubst js2-node-get-prop (node prop &optional default)
2205 (or (cadr (assoc prop (js2-node-props node))) default))
2206
2207 (defsubst js2-node-set-prop (node prop value)
2208 (setf (js2-node-props node)
2209 (cons (list prop value) (js2-node-props node))))
2210
2211 (defsubst js2-fixup-starts (n nodes)
2212 "Adjust the start positions of NODES to be relative to N.
2213 Any node in the list may be nil, for convenience."
2214 (dolist (node nodes)
2215 (when node
2216 (setf (js2-node-pos node) (- (js2-node-pos node)
2217 (js2-node-pos n))))))
2218
2219 (defsubst js2-node-add-children (parent &rest nodes)
2220 "Set parent node of NODES to PARENT, and return PARENT.
2221 Does nothing if we're not recording parent links.
2222 If any given node in NODES is nil, doesn't record that link."
2223 (js2-fixup-starts parent nodes)
2224 (dolist (node nodes)
2225 (and node
2226 (setf (js2-node-parent node) parent))))
2227
2228 ;; Non-recursive since it's called a frightening number of times.
2229 (defsubst js2-node-abs-pos (n)
2230 (let ((pos (js2-node-pos n)))
2231 (while (setq n (js2-node-parent n))
2232 (setq pos (+ pos (js2-node-pos n))))
2233 pos))
2234
2235 (defsubst js2-node-abs-end (n)
2236 "Return absolute buffer position of end of N."
2237 (+ (js2-node-abs-pos n) (js2-node-len n)))
2238
2239 ;; It's important to make sure block nodes have a lisp list for the
2240 ;; child nodes, to limit printing recursion depth in an AST that
2241 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2242 ;; a sufficiently large vector tree.
2243
2244 (defstruct (js2-block-node
2245 (:include js2-node)
2246 (:constructor nil)
2247 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2248 (pos js2-token-beg)
2249 len
2250 props
2251 kids)))
2252 "A block of statements."
2253 kids) ; a lisp list of the child statement nodes
2254
2255 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2256 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2257
2258 (defsubst js2-visit-block (ast callback)
2259 "Visit the `js2-block-node' children of AST."
2260 (dolist (kid (js2-block-node-kids ast))
2261 (js2-visit-ast kid callback)))
2262
2263 (defun js2-print-block (n i)
2264 (let ((pad (js2-make-pad i)))
2265 (insert pad "{\n")
2266 (dolist (kid (js2-block-node-kids n))
2267 (js2-print-ast kid (1+ i)))
2268 (insert pad "}")))
2269
2270 (defstruct (js2-scope
2271 (:include js2-block-node)
2272 (:constructor nil)
2273 (:constructor make-js2-scope (&key (type js2-BLOCK)
2274 (pos js2-token-beg)
2275 len
2276 kids)))
2277 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2278 ;; I don't have one of those handy, so I'll use an alist for now.
2279 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2280 ;; and is much lighter-weight to construct (both CPU and mem).
2281 ;; The keys are interned strings (symbols) for faster lookup.
2282 ;; Should switch to hybrid alist/hashtable eventually.
2283 symbol-table ; an alist of (symbol . js2-symbol)
2284 parent-scope ; a `js2-scope'
2285 top) ; top-level `js2-scope' (script/function)
2286
2287 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2288 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2289
2290 (defun js2-scope-set-parent-scope (scope parent)
2291 (setf (js2-scope-parent-scope scope) parent
2292 (js2-scope-top scope) (if (null parent)
2293 scope
2294 (js2-scope-top parent))))
2295
2296 (defun js2-node-get-enclosing-scope (node)
2297 "Return the innermost `js2-scope' node surrounding NODE.
2298 Returns nil if there is no enclosing scope node."
2299 (let ((parent (js2-node-parent node)))
2300 (while (not (js2-scope-p parent))
2301 (setq parent (js2-node-parent parent)))
2302 parent))
2303
2304 (defun js2-get-defining-scope (scope name)
2305 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2306 Returns `js2-scope' in which NAME is defined, or nil if not found."
2307 (let ((sym (if (symbolp name)
2308 name
2309 (intern name)))
2310 table
2311 result
2312 (continue t))
2313 (while (and scope continue)
2314 (if (and (setq table (js2-scope-symbol-table scope))
2315 (assq sym table))
2316 (setq continue nil
2317 result scope)
2318 (setq scope (js2-scope-parent-scope scope))))
2319 result))
2320
2321 (defsubst js2-scope-get-symbol (scope name)
2322 "Return symbol table entry for NAME in SCOPE.
2323 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2324 (and (js2-scope-symbol-table scope)
2325 (cdr (assq (if (symbolp name)
2326 name
2327 (intern name))
2328 (js2-scope-symbol-table scope)))))
2329
2330 (defsubst js2-scope-put-symbol (scope name symbol)
2331 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2332 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2333 (let* ((table (js2-scope-symbol-table scope))
2334 (sym (if (symbolp name) name (intern name)))
2335 (entry (assq sym table)))
2336 (if entry
2337 (setcdr entry symbol)
2338 (push (cons sym symbol)
2339 (js2-scope-symbol-table scope)))))
2340
2341 (defstruct (js2-symbol
2342 (:constructor nil)
2343 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2344 "A symbol table entry."
2345 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2346 ;; js2-LET, or js2-CONST
2347 decl-type
2348 name ; string
2349 ast-node) ; a `js2-node'
2350
2351 (defstruct (js2-error-node
2352 (:include js2-node)
2353 (:constructor nil) ; silence emacs21 byte-compiler
2354 (:constructor make-js2-error-node (&key (type js2-ERROR)
2355 (pos js2-token-beg)
2356 len)))
2357 "AST node representing a parse error.")
2358
2359 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2360 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2361
2362 (defstruct (js2-script-node
2363 (:include js2-scope)
2364 (:constructor nil)
2365 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2366 (pos js2-token-beg)
2367 len
2368 var-decls
2369 fun-decls)))
2370 functions ; lisp list of nested functions
2371 regexps ; lisp list of (string . flags)
2372 symbols ; alist (every symbol gets unique index)
2373 (param-count 0)
2374 var-names ; vector of string names
2375 consts ; bool-vector matching var-decls
2376 (temp-number 0)) ; for generating temp variables
2377
2378 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2379 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2380
2381 (defun js2-print-script (node indent)
2382 (dolist (kid (js2-block-node-kids node))
2383 (js2-print-ast kid indent)))
2384
2385 (defstruct (js2-ast-root
2386 (:include js2-script-node)
2387 (:constructor nil)
2388 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2389 (pos js2-token-beg)
2390 len
2391 buffer)))
2392 "The root node of a js2 AST."
2393 buffer ; the source buffer from which the code was parsed
2394 comments ; a lisp list of comments, ordered by start position
2395 errors ; a lisp list of errors found during parsing
2396 warnings ; a lisp list of warnings found during parsing
2397 node-count) ; number of nodes in the tree, including the root
2398
2399 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2400 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2401
2402 (defun js2-visit-ast-root (ast callback)
2403 (dolist (kid (js2-ast-root-kids ast))
2404 (js2-visit-ast kid callback))
2405 (dolist (comment (js2-ast-root-comments ast))
2406 (js2-visit-ast comment callback)))
2407
2408 (defstruct (js2-comment-node
2409 (:include js2-node)
2410 (:constructor nil)
2411 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2412 (pos js2-token-beg)
2413 len
2414 (format js2-ts-comment-type))))
2415 format) ; 'line, 'block, 'jsdoc or 'html
2416
2417 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2418 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2419
2420 (defun js2-print-comment (n i)
2421 ;; We really ought to link end-of-line comments to their nodes.
2422 ;; Or maybe we could add a new comment type, 'endline.
2423 (insert (js2-make-pad i)
2424 (js2-node-string n)))
2425
2426 (defstruct (js2-expr-stmt-node
2427 (:include js2-node)
2428 (:constructor nil)
2429 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2430 (pos js2-ts-cursor)
2431 len
2432 expr)))
2433 "An expression statement."
2434 expr)
2435
2436 (defsubst js2-expr-stmt-node-set-has-result (node)
2437 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2438 (setf (js2-node-type node) js2-EXPR_RESULT))
2439
2440 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2441 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2442
2443 (defun js2-visit-expr-stmt-node (n v)
2444 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2445
2446 (defun js2-print-expr-stmt-node (n indent)
2447 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2448 (insert ";\n"))
2449
2450 (defstruct (js2-loop-node
2451 (:include js2-scope)
2452 (:constructor nil))
2453 "Abstract supertype of loop nodes."
2454 body ; a `js2-block-node'
2455 lp ; position of left-paren, nil if omitted
2456 rp) ; position of right-paren, nil if omitted
2457
2458 (defstruct (js2-do-node
2459 (:include js2-loop-node)
2460 (:constructor nil)
2461 (:constructor make-js2-do-node (&key (type js2-DO)
2462 (pos js2-token-beg)
2463 len
2464 body
2465 condition
2466 while-pos
2467 lp
2468 rp)))
2469 "AST node for do-loop."
2470 condition ; while (expression)
2471 while-pos) ; buffer position of 'while' keyword
2472
2473 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2474 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2475
2476 (defun js2-visit-do-node (n v)
2477 (js2-visit-ast (js2-do-node-body n) v)
2478 (js2-visit-ast (js2-do-node-condition n) v))
2479
2480 (defun js2-print-do-node (n i)
2481 (let ((pad (js2-make-pad i)))
2482 (insert pad "do {\n")
2483 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2484 (js2-print-ast kid (1+ i)))
2485 (insert pad "} while (")
2486 (js2-print-ast (js2-do-node-condition n) 0)
2487 (insert ");\n")))
2488
2489 (defstruct (js2-while-node
2490 (:include js2-loop-node)
2491 (:constructor nil)
2492 (:constructor make-js2-while-node (&key (type js2-WHILE)
2493 (pos js2-token-beg)
2494 len
2495 body
2496 condition
2497 lp
2498 rp)))
2499 "AST node for while-loop."
2500 condition) ; while-condition
2501
2502 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2503 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2504
2505 (defun js2-visit-while-node (n v)
2506 (js2-visit-ast (js2-while-node-condition n) v)
2507 (js2-visit-ast (js2-while-node-body n) v))
2508
2509 (defun js2-print-while-node (n i)
2510 (let ((pad (js2-make-pad i)))
2511 (insert pad "while (")
2512 (js2-print-ast (js2-while-node-condition n) 0)
2513 (insert ") {\n")
2514 (js2-print-body (js2-while-node-body n) (1+ i))
2515 (insert pad "}\n")))
2516
2517 (defstruct (js2-for-node
2518 (:include js2-loop-node)
2519 (:constructor nil)
2520 (:constructor make-js2-for-node (&key (type js2-FOR)
2521 (pos js2-ts-cursor)
2522 len
2523 body
2524 init
2525 condition
2526 update
2527 lp
2528 rp)))
2529 "AST node for a C-style for-loop."
2530 init ; initialization expression
2531 condition ; loop condition
2532 update) ; update clause
2533
2534 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2535 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2536
2537 (defun js2-visit-for-node (n v)
2538 (js2-visit-ast (js2-for-node-init n) v)
2539 (js2-visit-ast (js2-for-node-condition n) v)
2540 (js2-visit-ast (js2-for-node-update n) v)
2541 (js2-visit-ast (js2-for-node-body n) v))
2542
2543 (defun js2-print-for-node (n i)
2544 (let ((pad (js2-make-pad i)))
2545 (insert pad "for (")
2546 (js2-print-ast (js2-for-node-init n) 0)
2547 (insert "; ")
2548 (js2-print-ast (js2-for-node-condition n) 0)
2549 (insert "; ")
2550 (js2-print-ast (js2-for-node-update n) 0)
2551 (insert ") {\n")
2552 (js2-print-body (js2-for-node-body n) (1+ i))
2553 (insert pad "}\n")))
2554
2555 (defstruct (js2-for-in-node
2556 (:include js2-loop-node)
2557 (:constructor nil)
2558 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2559 (pos js2-ts-cursor)
2560 len
2561 body
2562 iterator
2563 object
2564 in-pos
2565 each-pos
2566 foreach-p
2567 lp
2568 rp)))
2569 "AST node for a for..in loop."
2570 iterator ; [var] foo in ...
2571 object ; object over which we're iterating
2572 in-pos ; buffer position of 'in' keyword
2573 each-pos ; buffer position of 'each' keyword, if foreach-p
2574 foreach-p) ; t if it's a for-each loop
2575
2576 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2577 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2578
2579 (defun js2-visit-for-in-node (n v)
2580 (js2-visit-ast (js2-for-in-node-iterator n) v)
2581 (js2-visit-ast (js2-for-in-node-object n) v)
2582 (js2-visit-ast (js2-for-in-node-body n) v))
2583
2584 (defun js2-print-for-in-node (n i)
2585 (let ((pad (js2-make-pad i))
2586 (foreach (js2-for-in-node-foreach-p n)))
2587 (insert pad "for ")
2588 (if foreach
2589 (insert "each "))
2590 (insert "(")
2591 (js2-print-ast (js2-for-in-node-iterator n) 0)
2592 (insert " in ")
2593 (js2-print-ast (js2-for-in-node-object n) 0)
2594 (insert ") {\n")
2595 (js2-print-body (js2-for-in-node-body n) (1+ i))
2596 (insert pad "}\n")))
2597
2598 (defstruct (js2-return-node
2599 (:include js2-node)
2600 (:constructor nil)
2601 (:constructor make-js2-return-node (&key (type js2-RETURN)
2602 (pos js2-ts-cursor)
2603 len
2604 retval)))
2605 "AST node for a return statement."
2606 retval) ; expression to return, or 'undefined
2607
2608 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2609 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2610
2611 (defun js2-visit-return-node (n v)
2612 (js2-visit-ast (js2-return-node-retval n) v))
2613
2614 (defun js2-print-return-node (n i)
2615 (insert (js2-make-pad i) "return")
2616 (when (js2-return-node-retval n)
2617 (insert " ")
2618 (js2-print-ast (js2-return-node-retval n) 0))
2619 (insert ";\n"))
2620
2621 (defstruct (js2-if-node
2622 (:include js2-node)
2623 (:constructor nil)
2624 (:constructor make-js2-if-node (&key (type js2-IF)
2625 (pos js2-ts-cursor)
2626 len
2627 condition
2628 then-part
2629 else-pos
2630 else-part
2631 lp
2632 rp)))
2633 "AST node for an if-statement."
2634 condition ; expression
2635 then-part ; statement or block
2636 else-pos ; optional buffer position of 'else' keyword
2637 else-part ; optional statement or block
2638 lp ; position of left-paren, nil if omitted
2639 rp) ; position of right-paren, nil if omitted
2640
2641 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2642 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2643
2644 (defun js2-visit-if-node (n v)
2645 (js2-visit-ast (js2-if-node-condition n) v)
2646 (js2-visit-ast (js2-if-node-then-part n) v)
2647 (js2-visit-ast (js2-if-node-else-part n) v))
2648
2649 (defun js2-print-if-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (then-part (js2-if-node-then-part n))
2652 (else-part (js2-if-node-else-part n)))
2653 (insert pad "if (")
2654 (js2-print-ast (js2-if-node-condition n) 0)
2655 (insert ") {\n")
2656 (js2-print-body then-part (1+ i))
2657 (insert pad "}")
2658 (cond
2659 ((not else-part)
2660 (insert "\n"))
2661 ((js2-if-node-p else-part)
2662 (insert " else ")
2663 (js2-print-body else-part i))
2664 (t
2665 (insert " else {\n")
2666 (js2-print-body else-part (1+ i))
2667 (insert pad "}\n")))))
2668
2669 (defstruct (js2-try-node
2670 (:include js2-node)
2671 (:constructor nil)
2672 (:constructor make-js2-try-node (&key (type js2-TRY)
2673 (pos js2-ts-cursor)
2674 len
2675 try-block
2676 catch-clauses
2677 finally-block)))
2678 "AST node for a try-statement."
2679 try-block
2680 catch-clauses ; a lisp list of `js2-catch-node'
2681 finally-block) ; a `js2-finally-node'
2682
2683 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2684 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2685
2686 (defun js2-visit-try-node (n v)
2687 (js2-visit-ast (js2-try-node-try-block n) v)
2688 (dolist (clause (js2-try-node-catch-clauses n))
2689 (js2-visit-ast clause v))
2690 (js2-visit-ast (js2-try-node-finally-block n) v))
2691
2692 (defun js2-print-try-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (catches (js2-try-node-catch-clauses n))
2695 (finally (js2-try-node-finally-block n)))
2696 (insert pad "try {\n")
2697 (js2-print-body (js2-try-node-try-block n) (1+ i))
2698 (insert pad "}")
2699 (when catches
2700 (dolist (catch catches)
2701 (js2-print-ast catch i)))
2702 (if finally
2703 (js2-print-ast finally i)
2704 (insert "\n"))))
2705
2706 (defstruct (js2-catch-node
2707 (:include js2-node)
2708 (:constructor nil)
2709 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2710 (pos js2-ts-cursor)
2711 len
2712 param
2713 guard-kwd
2714 guard-expr
2715 block
2716 lp
2717 rp)))
2718 "AST node for a catch clause."
2719 param ; destructuring form or simple name node
2720 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2721 guard-expr ; catch condition, a `js2-node'
2722 block ; statements, a `js2-block-node'
2723 lp ; buffer position of left-paren, nil if omitted
2724 rp) ; buffer position of right-paren, nil if omitted
2725
2726 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2727 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2728
2729 (defun js2-visit-catch-node (n v)
2730 (js2-visit-ast (js2-catch-node-param n) v)
2731 (when (js2-catch-node-guard-kwd n)
2732 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2733 (js2-visit-ast (js2-catch-node-block n) v))
2734
2735 (defun js2-print-catch-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (guard-kwd (js2-catch-node-guard-kwd n))
2738 (guard-expr (js2-catch-node-guard-expr n)))
2739 (insert " catch (")
2740 (js2-print-ast (js2-catch-node-param n) 0)
2741 (when guard-kwd
2742 (insert " if ")
2743 (js2-print-ast guard-expr 0))
2744 (insert ") {\n")
2745 (js2-print-body (js2-catch-node-block n) (1+ i))
2746 (insert pad "}")))
2747
2748 (defstruct (js2-finally-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2752 (pos js2-ts-cursor)
2753 len
2754 body)))
2755 "AST node for a finally clause."
2756 body) ; a `js2-node', often but not always a block node
2757
2758 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2759 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2760
2761 (defun js2-visit-finally-node (n v)
2762 (js2-visit-ast (js2-finally-node-body n) v))
2763
2764 (defun js2-print-finally-node (n i)
2765 (let ((pad (js2-make-pad i)))
2766 (insert " finally {\n")
2767 (js2-print-body (js2-finally-node-body n) (1+ i))
2768 (insert pad "}\n")))
2769
2770 (defstruct (js2-switch-node
2771 (:include js2-node)
2772 (:constructor nil)
2773 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2774 (pos js2-ts-cursor)
2775 len
2776 discriminant
2777 cases
2778 lp
2779 rp)))
2780 "AST node for a switch statement."
2781 discriminant ; a `js2-node' (switch expression)
2782 cases ; a lisp list of `js2-case-node'
2783 lp ; position of open-paren for discriminant, nil if omitted
2784 rp) ; position of close-paren for discriminant, nil if omitted
2785
2786 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2787 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2788
2789 (defun js2-visit-switch-node (n v)
2790 (js2-visit-ast (js2-switch-node-discriminant n) v)
2791 (dolist (c (js2-switch-node-cases n))
2792 (js2-visit-ast c v)))
2793
2794 (defun js2-print-switch-node (n i)
2795 (let ((pad (js2-make-pad i))
2796 (cases (js2-switch-node-cases n)))
2797 (insert pad "switch (")
2798 (js2-print-ast (js2-switch-node-discriminant n) 0)
2799 (insert ") {\n")
2800 (dolist (case cases)
2801 (js2-print-ast case i))
2802 (insert pad "}\n")))
2803
2804 (defstruct (js2-case-node
2805 (:include js2-block-node)
2806 (:constructor nil)
2807 (:constructor make-js2-case-node (&key (type js2-CASE)
2808 (pos js2-ts-cursor)
2809 len
2810 kids
2811 expr)))
2812 "AST node for a case clause of a switch statement."
2813 expr) ; the case expression (nil for default)
2814
2815 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2816 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2817
2818 (defun js2-visit-case-node (n v)
2819 (js2-visit-ast (js2-case-node-expr n) v)
2820 (js2-visit-block n v))
2821
2822 (defun js2-print-case-node (n i)
2823 (let ((pad (js2-make-pad i))
2824 (expr (js2-case-node-expr n)))
2825 (insert pad)
2826 (if (null expr)
2827 (insert "default:\n")
2828 (insert "case ")
2829 (js2-print-ast expr 0)
2830 (insert ":\n"))
2831 (dolist (kid (js2-case-node-kids n))
2832 (js2-print-ast kid (1+ i)))))
2833
2834 (defstruct (js2-throw-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-throw-node (&key (type js2-THROW)
2838 (pos js2-ts-cursor)
2839 len
2840 expr)))
2841 "AST node for a throw statement."
2842 expr) ; the expression to throw
2843
2844 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2845 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2846
2847 (defun js2-visit-throw-node (n v)
2848 (js2-visit-ast (js2-throw-node-expr n) v))
2849
2850 (defun js2-print-throw-node (n i)
2851 (insert (js2-make-pad i) "throw ")
2852 (js2-print-ast (js2-throw-node-expr n) 0)
2853 (insert ";\n"))
2854
2855 (defstruct (js2-with-node
2856 (:include js2-node)
2857 (:constructor nil)
2858 (:constructor make-js2-with-node (&key (type js2-WITH)
2859 (pos js2-ts-cursor)
2860 len
2861 object
2862 body
2863 lp
2864 rp)))
2865 "AST node for a with-statement."
2866 object
2867 body
2868 lp ; buffer position of left-paren around object, nil if omitted
2869 rp) ; buffer position of right-paren around object, nil if omitted
2870
2871 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2872 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2873
2874 (defun js2-visit-with-node (n v)
2875 (js2-visit-ast (js2-with-node-object n) v)
2876 (js2-visit-ast (js2-with-node-body n) v))
2877
2878 (defun js2-print-with-node (n i)
2879 (let ((pad (js2-make-pad i)))
2880 (insert pad "with (")
2881 (js2-print-ast (js2-with-node-object n) 0)
2882 (insert ") {\n")
2883 (js2-print-body (js2-with-node-body n) (1+ i))
2884 (insert pad "}\n")))
2885
2886 (defstruct (js2-label-node
2887 (:include js2-node)
2888 (:constructor nil)
2889 (:constructor make-js2-label-node (&key (type js2-LABEL)
2890 (pos js2-ts-cursor)
2891 len
2892 name)))
2893 "AST node for a statement label or case label."
2894 name ; a string
2895 loop) ; for validating and code-generating continue-to-label
2896
2897 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2898 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2899
2900 (defun js2-print-label (n i)
2901 (insert (js2-make-pad i)
2902 (js2-label-node-name n)
2903 ":\n"))
2904
2905 (defstruct (js2-labeled-stmt-node
2906 (:include js2-node)
2907 (:constructor nil)
2908 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2909 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2910 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2911 (pos js2-ts-cursor)
2912 len
2913 labels
2914 stmt)))
2915 "AST node for a statement with one or more labels.
2916 Multiple labels for a statement are collapsed into the labels field."
2917 labels ; lisp list of `js2-label-node'
2918 stmt) ; the statement these labels are for
2919
2920 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2922
2923 (defun js2-get-label-by-name (lbl-stmt name)
2924 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2925 Returns nil if no such label is in the list."
2926 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2927 result)
2928 (while (and label-list (not result))
2929 (if (string= (js2-label-node-name (car label-list)) name)
2930 (setq result (car label-list))
2931 (setq label-list (cdr label-list))))
2932 result))
2933
2934 (defun js2-visit-labeled-stmt (n v)
2935 (dolist (label (js2-labeled-stmt-node-labels n))
2936 (js2-visit-ast label v))
2937 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2938
2939 (defun js2-print-labeled-stmt (n i)
2940 (dolist (label (js2-labeled-stmt-node-labels n))
2941 (js2-print-ast label i))
2942 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2943
2944 (defun js2-labeled-stmt-node-contains (node label)
2945 "Return t if NODE contains LABEL in its label set.
2946 NODE is a `js2-labels-node'. LABEL is an identifier."
2947 (loop for nl in (js2-labeled-stmt-node-labels node)
2948 if (string= label (js2-label-node-name nl))
2949 return t
2950 finally return nil))
2951
2952 (defsubst js2-labeled-stmt-node-add-label (node label)
2953 "Add a `js2-label-node' to the label set for this statement."
2954 (setf (js2-labeled-stmt-node-labels node)
2955 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2956
2957 (defstruct (js2-jump-node
2958 (:include js2-node)
2959 (:constructor nil))
2960 "Abstract supertype of break and continue nodes."
2961 label ; `js2-name-node' for location of label identifier, if present
2962 target) ; target js2-labels-node or loop/switch statement
2963
2964 (defun js2-visit-jump-node (n v)
2965 (js2-visit-ast (js2-jump-node-label n) v))
2966
2967 (defstruct (js2-break-node
2968 (:include js2-jump-node)
2969 (:constructor nil)
2970 (:constructor make-js2-break-node (&key (type js2-BREAK)
2971 (pos js2-ts-cursor)
2972 len
2973 label
2974 target)))
2975 "AST node for a break statement.
2976 The label field is a `js2-name-node', possibly nil, for the named label
2977 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2978 is the target of the break - a label node or enclosing loop/switch statement.")
2979
2980 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2981 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2982
2983 (defun js2-print-break-node (n i)
2984 (insert (js2-make-pad i) "break")
2985 (when (js2-break-node-label n)
2986 (insert " ")
2987 (js2-print-ast (js2-break-node-label n) 0))
2988 (insert ";\n"))
2989
2990 (defstruct (js2-continue-node
2991 (:include js2-jump-node)
2992 (:constructor nil)
2993 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2994 (pos js2-ts-cursor)
2995 len
2996 label
2997 target)))
2998 "AST node for a continue statement.
2999 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3000 It is nil if continue specifies no label. The target field is the jump target:
3001 a `js2-label-node' or the innermost enclosing loop.")
3002
3003 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3004 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3005
3006 (defun js2-print-continue-node (n i)
3007 (insert (js2-make-pad i) "continue")
3008 (when (js2-continue-node-label n)
3009 (insert " ")
3010 (js2-print-ast (js2-continue-node-label n) 0))
3011 (insert ";\n"))
3012
3013 (defstruct (js2-function-node
3014 (:include js2-script-node)
3015 (:constructor nil)
3016 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3017 (pos js2-ts-cursor)
3018 len
3019 (ftype 'FUNCTION)
3020 (form 'FUNCTION_STATEMENT)
3021 (name "")
3022 params
3023 body
3024 lp
3025 rp)))
3026 "AST node for a function declaration.
3027 The `params' field is a lisp list of nodes. Each node is either a simple
3028 `js2-name-node', or if it's a destructuring-assignment parameter, a
3029 `js2-array-node' or `js2-object-node'."
3030 ftype ; FUNCTION, GETTER or SETTER
3031 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3032 name ; function name (a `js2-name-node', or nil if anonymous)
3033 params ; a lisp list of destructuring forms or simple name nodes
3034 body ; a `js2-block-node' or expression node (1.8 only)
3035 lp ; position of arg-list open-paren, or nil if omitted
3036 rp ; position of arg-list close-paren, or nil if omitted
3037 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3038 needs-activation ; t if we need an activation object for this frame
3039 is-generator ; t if this function contains a yield
3040 member-expr) ; nonstandard Ecma extension from Rhino
3041
3042 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3043 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3044
3045 (defun js2-visit-function-node (n v)
3046 (js2-visit-ast (js2-function-node-name n) v)
3047 (dolist (p (js2-function-node-params n))
3048 (js2-visit-ast p v))
3049 (js2-visit-ast (js2-function-node-body n) v))
3050
3051 (defun js2-print-function-node (n i)
3052 (let ((pad (js2-make-pad i))
3053 (getter (js2-node-get-prop n 'GETTER_SETTER))
3054 (name (js2-function-node-name n))
3055 (params (js2-function-node-params n))
3056 (body (js2-function-node-body n))
3057 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3058 (unless getter
3059 (insert pad "function"))
3060 (when name
3061 (insert " ")
3062 (js2-print-ast name 0))
3063 (insert "(")
3064 (loop with len = (length params)
3065 for param in params
3066 for count from 1
3067 do
3068 (js2-print-ast param 0)
3069 (if (< count len)
3070 (insert ", ")))
3071 (insert ") {")
3072 (unless expr
3073 (insert "\n"))
3074 ;; TODO: fix this to be smarter about indenting, etc.
3075 (js2-print-body body (1+ i))
3076 (insert pad "}")
3077 (unless expr
3078 (insert "\n"))))
3079
3080 (defsubst js2-function-name (node)
3081 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3082 (and (js2-function-node-name node)
3083 (js2-name-node-name (js2-function-node-name node))))
3084
3085 ;; Having this be an expression node makes it more flexible.
3086 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3087 ;; that work better if you assume it's an expression. Whenever we have
3088 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3089 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3090 (defstruct (js2-var-decl-node
3091 (:include js2-node)
3092 (:constructor nil)
3093 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3094 (pos js2-token-beg)
3095 len
3096 kids
3097 decl-type)))
3098 "AST node for a variable declaration list (VAR, CONST or LET).
3099 The node bounds differ depending on the declaration type. For VAR or
3100 CONST declarations, the bounds include the var/const keyword. For LET
3101 declarations, the node begins at the position of the first child."
3102 kids ; a lisp list of `js2-var-init-node' structs.
3103 decl-type) ; js2-VAR, js2-CONST or js2-LET
3104
3105 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3106 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3107
3108 (defun js2-visit-var-decl (n v)
3109 (dolist (kid (js2-var-decl-node-kids n))
3110 (js2-visit-ast kid v)))
3111
3112 (defun js2-print-var-decl (n i)
3113 (let ((pad (js2-make-pad i))
3114 (tt (js2-var-decl-node-decl-type n)))
3115 (insert pad)
3116 (insert (cond
3117 ((= tt js2-VAR) "var ")
3118 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3119 ((= tt js2-CONST) "const ")
3120 (t
3121 (error "malformed var-decl node"))))
3122 (loop with kids = (js2-var-decl-node-kids n)
3123 with len = (length kids)
3124 for kid in kids
3125 for count from 1
3126 do
3127 (js2-print-ast kid 0)
3128 (if (< count len)
3129 (insert ", ")))))
3130
3131 (defstruct (js2-var-init-node
3132 (:include js2-node)
3133 (:constructor nil)
3134 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3135 (pos js2-ts-cursor)
3136 len
3137 target
3138 initializer)))
3139 "AST node for a variable declaration.
3140 The type field will be js2-CONST for a const decl."
3141 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3142 initializer) ; initializer expression, a `js2-node'
3143
3144 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3145 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3146
3147 (defun js2-visit-var-init-node (n v)
3148 (js2-visit-ast (js2-var-init-node-target n) v)
3149 (js2-visit-ast (js2-var-init-node-initializer n) v))
3150
3151 (defun js2-print-var-init-node (n i)
3152 (let ((pad (js2-make-pad i))
3153 (name (js2-var-init-node-target n))
3154 (init (js2-var-init-node-initializer n)))
3155 (insert pad)
3156 (js2-print-ast name 0)
3157 (when init
3158 (insert " = ")
3159 (js2-print-ast init 0))))
3160
3161 (defstruct (js2-cond-node
3162 (:include js2-node)
3163 (:constructor nil)
3164 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3165 (pos js2-ts-cursor)
3166 len
3167 test-expr
3168 true-expr
3169 false-expr
3170 q-pos
3171 c-pos)))
3172 "AST node for the ternary operator"
3173 test-expr
3174 true-expr
3175 false-expr
3176 q-pos ; buffer position of ?
3177 c-pos) ; buffer position of :
3178
3179 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3180 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3181
3182 (defun js2-visit-cond-node (n v)
3183 (js2-visit-ast (js2-cond-node-test-expr n) v)
3184 (js2-visit-ast (js2-cond-node-true-expr n) v)
3185 (js2-visit-ast (js2-cond-node-false-expr n) v))
3186
3187 (defun js2-print-cond-node (n i)
3188 (let ((pad (js2-make-pad i)))
3189 (insert pad)
3190 (js2-print-ast (js2-cond-node-test-expr n) 0)
3191 (insert " ? ")
3192 (js2-print-ast (js2-cond-node-true-expr n) 0)
3193 (insert " : ")
3194 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3195
3196 (defstruct (js2-infix-node
3197 (:include js2-node)
3198 (:constructor nil)
3199 (:constructor make-js2-infix-node (&key type
3200 (pos js2-ts-cursor)
3201 len
3202 op-pos
3203 left
3204 right)))
3205 "Represents infix expressions.
3206 Includes assignment ops like `|=', and the comma operator.
3207 The type field inherited from `js2-node' holds the operator."
3208 op-pos ; buffer position where operator begins
3209 left ; any `js2-node'
3210 right) ; any `js2-node'
3211
3212 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3213 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3214
3215 (defun js2-visit-infix-node (n v)
3216 (js2-visit-ast (js2-infix-node-left n) v)
3217 (js2-visit-ast (js2-infix-node-right n) v))
3218
3219 (defconst js2-operator-tokens
3220 (let ((table (make-hash-table :test 'eq))
3221 (tokens
3222 (list (cons js2-IN "in")
3223 (cons js2-TYPEOF "typeof")
3224 (cons js2-INSTANCEOF "instanceof")
3225 (cons js2-DELPROP "delete")
3226 (cons js2-COMMA ",")
3227 (cons js2-COLON ":")
3228 (cons js2-OR "||")
3229 (cons js2-AND "&&")
3230 (cons js2-INC "++")
3231 (cons js2-DEC "--")
3232 (cons js2-BITOR "|")
3233 (cons js2-BITXOR "^")
3234 (cons js2-BITAND "&")
3235 (cons js2-EQ "==")
3236 (cons js2-NE "!=")
3237 (cons js2-LT "<")
3238 (cons js2-LE "<=")
3239 (cons js2-GT ">")
3240 (cons js2-GE ">=")
3241 (cons js2-LSH "<<")
3242 (cons js2-RSH ">>")
3243 (cons js2-URSH ">>>")
3244 (cons js2-ADD "+") ; infix plus
3245 (cons js2-SUB "-") ; infix minus
3246 (cons js2-MUL "*")
3247 (cons js2-DIV "/")
3248 (cons js2-MOD "%")
3249 (cons js2-NOT "!")
3250 (cons js2-BITNOT "~")
3251 (cons js2-POS "+") ; unary plus
3252 (cons js2-NEG "-") ; unary minus
3253 (cons js2-SHEQ "===") ; shallow equality
3254 (cons js2-SHNE "!==") ; shallow inequality
3255 (cons js2-ASSIGN "=")
3256 (cons js2-ASSIGN_BITOR "|=")
3257 (cons js2-ASSIGN_BITXOR "^=")
3258 (cons js2-ASSIGN_BITAND "&=")
3259 (cons js2-ASSIGN_LSH "<<=")
3260 (cons js2-ASSIGN_RSH ">>=")
3261 (cons js2-ASSIGN_URSH ">>>=")
3262 (cons js2-ASSIGN_ADD "+=")
3263 (cons js2-ASSIGN_SUB "-=")
3264 (cons js2-ASSIGN_MUL "*=")
3265 (cons js2-ASSIGN_DIV "/=")
3266 (cons js2-ASSIGN_MOD "%="))))
3267 (loop for (k . v) in tokens do
3268 (puthash k v table))
3269 table))
3270
3271 (defun js2-print-infix-node (n i)
3272 (let* ((tt (js2-node-type n))
3273 (op (gethash tt js2-operator-tokens)))
3274 (unless op
3275 (error "unrecognized infix operator %s" (js2-node-type n)))
3276 (insert (js2-make-pad i))
3277 (js2-print-ast (js2-infix-node-left n) 0)
3278 (unless (= tt js2-COMMA)
3279 (insert " "))
3280 (insert op)
3281 (insert " ")
3282 (js2-print-ast (js2-infix-node-right n) 0)))
3283
3284 (defstruct (js2-assign-node
3285 (:include js2-infix-node)
3286 (:constructor nil)
3287 (:constructor make-js2-assign-node (&key type
3288 (pos js2-ts-cursor)
3289 len
3290 op-pos
3291 left
3292 right)))
3293 "Represents any assignment.
3294 The type field holds the actual assignment operator.")
3295
3296 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3297 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3298
3299 (defstruct (js2-unary-node
3300 (:include js2-node)
3301 (:constructor nil)
3302 (:constructor make-js2-unary-node (&key type ; required
3303 (pos js2-ts-cursor)
3304 len
3305 operand)))
3306 "AST node type for unary operator nodes.
3307 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3308 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3309 property is added if the operator follows the operand."
3310 operand) ; a `js2-node' expression
3311
3312 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3313 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3314
3315 (defun js2-visit-unary-node (n v)
3316 (js2-visit-ast (js2-unary-node-operand n) v))
3317
3318 (defun js2-print-unary-node (n i)
3319 (let* ((tt (js2-node-type n))
3320 (op (gethash tt js2-operator-tokens))
3321 (postfix (js2-node-get-prop n 'postfix)))
3322 (unless op
3323 (error "unrecognized unary operator %s" tt))
3324 (insert (js2-make-pad i))
3325 (unless postfix
3326 (insert op))
3327 (if (or (= tt js2-TYPEOF)
3328 (= tt js2-DELPROP))
3329 (insert " "))
3330 (js2-print-ast (js2-unary-node-operand n) 0)
3331 (when postfix
3332 (insert op))))
3333
3334 (defstruct (js2-let-node
3335 (:include js2-scope)
3336 (:constructor nil)
3337 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3338 (pos js2-token-beg)
3339 len
3340 vars
3341 body
3342 lp
3343 rp)))
3344 "AST node for a let expression or a let statement.
3345 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3346 vars ; a `js2-var-decl-node'
3347 body ; a `js2-node' representing the expression or body block
3348 lp
3349 rp)
3350
3351 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3352 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3353
3354 (defun js2-visit-let-node (n v)
3355 (js2-visit-ast (js2-let-node-vars n) v)
3356 (js2-visit-ast (js2-let-node-body n) v))
3357
3358 (defun js2-print-let-node (n i)
3359 (insert (js2-make-pad i) "let (")
3360 (js2-print-ast (js2-let-node-vars n) 0)
3361 (insert ") ")
3362 (js2-print-ast (js2-let-node-body n) i))
3363
3364 (defstruct (js2-keyword-node
3365 (:include js2-node)
3366 (:constructor nil)
3367 (:constructor make-js2-keyword-node (&key type
3368 (pos js2-token-beg)
3369 (len (- js2-ts-cursor pos)))))
3370 "AST node representing a literal keyword such as `null'.
3371 Used for `null', `this', `true', `false' and `debugger'.
3372 The node type is set to js2-NULL, js2-THIS, etc.")
3373
3374 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3376
3377 (defun js2-print-keyword-node (n i)
3378 (insert (js2-make-pad i)
3379 (let ((tt (js2-node-type n)))
3380 (cond
3381 ((= tt js2-THIS) "this")
3382 ((= tt js2-NULL) "null")
3383 ((= tt js2-TRUE) "true")
3384 ((= tt js2-FALSE) "false")
3385 ((= tt js2-DEBUGGER) "debugger")
3386 (t (error "Invalid keyword literal type: %d" tt))))))
3387
3388 (defsubst js2-this-node-p (node)
3389 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3390 (eq (js2-node-type node) js2-THIS))
3391
3392 (defstruct (js2-new-node
3393 (:include js2-node)
3394 (:constructor nil)
3395 (:constructor make-js2-new-node (&key (type js2-NEW)
3396 (pos js2-token-beg)
3397 len
3398 target
3399 args
3400 initializer
3401 lp
3402 rp)))
3403 "AST node for new-expression such as new Foo()."
3404 target ; an identifier or reference
3405 args ; a lisp list of argument nodes
3406 lp ; position of left-paren, nil if omitted
3407 rp ; position of right-paren, nil if omitted
3408 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3409
3410 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3411 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3412
3413 (defun js2-visit-new-node (n v)
3414 (js2-visit-ast (js2-new-node-target n) v)
3415 (dolist (arg (js2-new-node-args n))
3416 (js2-visit-ast arg v))
3417 (js2-visit-ast (js2-new-node-initializer n) v))
3418
3419 (defun js2-print-new-node (n i)
3420 (insert (js2-make-pad i) "new ")
3421 (js2-print-ast (js2-new-node-target n))
3422 (insert "(")
3423 (js2-print-list (js2-new-node-args n))
3424 (insert ")")
3425 (when (js2-new-node-initializer n)
3426 (insert " ")
3427 (js2-print-ast (js2-new-node-initializer n))))
3428
3429 (defstruct (js2-name-node
3430 (:include js2-node)
3431 (:constructor nil)
3432 (:constructor make-js2-name-node (&key (type js2-NAME)
3433 (pos js2-token-beg)
3434 (len (- js2-ts-cursor
3435 js2-token-beg))
3436 (name js2-ts-string))))
3437 "AST node for a JavaScript identifier"
3438 name ; a string
3439 scope) ; a `js2-scope' (optional, used for codegen)
3440
3441 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3442 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3443
3444 (defun js2-print-name-node (n i)
3445 (insert (js2-make-pad i)
3446 (js2-name-node-name n)))
3447
3448 (defsubst js2-name-node-length (node)
3449 "Return identifier length of NODE, a `js2-name-node'.
3450 Returns 0 if NODE is nil or its identifier field is nil."
3451 (if node
3452 (length (js2-name-node-name node))
3453 0))
3454
3455 (defstruct (js2-number-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3459 (pos js2-token-beg)
3460 (len (- js2-ts-cursor
3461 js2-token-beg))
3462 (value js2-ts-string)
3463 (num-value js2-ts-number))))
3464 "AST node for a number literal."
3465 value ; the original string, e.g. "6.02e23"
3466 num-value) ; the parsed number value
3467
3468 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3470
3471 (defun js2-print-number-node (n i)
3472 (insert (js2-make-pad i)
3473 (number-to-string (js2-number-node-num-value n))))
3474
3475 (defstruct (js2-regexp-node
3476 (:include js2-node)
3477 (:constructor nil)
3478 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3479 (pos js2-token-beg)
3480 (len (- js2-ts-cursor
3481 js2-token-beg))
3482 value
3483 flags)))
3484 "AST node for a regular expression literal."
3485 value ; the regexp string, without // delimiters
3486 flags) ; a string of flags, e.g. `mi'.
3487
3488 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3489 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3490
3491 (defun js2-print-regexp (n i)
3492 (insert (js2-make-pad i)
3493 "/"
3494 (js2-regexp-node-value n)
3495 "/")
3496 (if (js2-regexp-node-flags n)
3497 (insert (js2-regexp-node-flags n))))
3498
3499 (defstruct (js2-string-node
3500 (:include js2-node)
3501 (:constructor nil)
3502 (:constructor make-js2-string-node (&key (type js2-STRING)
3503 (pos js2-token-beg)
3504 (len (- js2-ts-cursor
3505 js2-token-beg))
3506 (value js2-ts-string))))
3507 "String literal.
3508 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3509 You can tell the quote type by looking at the first character."
3510 value) ; the characters of the string, including the quotes
3511
3512 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3513 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3514
3515 (defun js2-print-string-node (n i)
3516 (insert (js2-make-pad i)
3517 (js2-node-string n)))
3518
3519 (defstruct (js2-array-node
3520 (:include js2-node)
3521 (:constructor nil)
3522 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3523 (pos js2-ts-cursor)
3524 len
3525 elems)))
3526 "AST node for an array literal."
3527 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3528
3529 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3530 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3531
3532 (defun js2-visit-array-node (n v)
3533 (dolist (e (js2-array-node-elems n))
3534 (js2-visit-ast e v)))
3535
3536 (defun js2-print-array-node (n i)
3537 (insert (js2-make-pad i) "[")
3538 (js2-print-list (js2-array-node-elems n))
3539 (insert "]"))
3540
3541 (defstruct (js2-object-node
3542 (:include js2-node)
3543 (:constructor nil)
3544 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3545 (pos js2-ts-cursor)
3546 len
3547 elems)))
3548 "AST node for an object literal expression.
3549 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3550 the latter represents abbreviation in destructuring expressions."
3551 elems)
3552
3553 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3554 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3555
3556 (defun js2-visit-object-node (n v)
3557 (dolist (e (js2-object-node-elems n))
3558 (js2-visit-ast e v)))
3559
3560 (defun js2-print-object-node (n i)
3561 (insert (js2-make-pad i) "{")
3562 (js2-print-list (js2-object-node-elems n))
3563 (insert "}"))
3564
3565 (defstruct (js2-object-prop-node
3566 (:include js2-infix-node)
3567 (:constructor nil)
3568 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3569 (pos js2-ts-cursor)
3570 len
3571 left
3572 right
3573 op-pos)))
3574 "AST node for an object literal prop:value entry.
3575 The `left' field is the property: a name node, string node or number node.
3576 The `right' field is a `js2-node' representing the initializer value.")
3577
3578 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3579 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3580
3581 (defun js2-print-object-prop-node (n i)
3582 (insert (js2-make-pad i))
3583 (js2-print-ast (js2-object-prop-node-left n) 0)
3584 (insert ":")
3585 (js2-print-ast (js2-object-prop-node-right n) 0))
3586
3587 (defstruct (js2-getter-setter-node
3588 (:include js2-infix-node)
3589 (:constructor nil)
3590 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3591 (pos js2-ts-cursor)
3592 len
3593 left
3594 right)))
3595 "AST node for a getter/setter property in an object literal.
3596 The `left' field is the `js2-name-node' naming the getter/setter prop.
3597 The `right' field is always an anonymous `js2-function-node' with a node
3598 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3599
3600 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3601 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3602
3603 (defun js2-print-getter-setter (n i)
3604 (let ((pad (js2-make-pad i))
3605 (left (js2-getter-setter-node-left n))
3606 (right (js2-getter-setter-node-right n)))
3607 (insert pad)
3608 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3609 (js2-print-ast left 0)
3610 (js2-print-ast right 0)))
3611
3612 (defstruct (js2-prop-get-node
3613 (:include js2-infix-node)
3614 (:constructor nil)
3615 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3616 (pos js2-ts-cursor)
3617 len
3618 left
3619 right)))
3620 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3621
3622 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3623 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3624
3625 (defun js2-visit-prop-get-node (n v)
3626 (js2-visit-ast (js2-prop-get-node-left n) v)
3627 (js2-visit-ast (js2-prop-get-node-right n) v))
3628
3629 (defun js2-print-prop-get-node (n i)
3630 (insert (js2-make-pad i))
3631 (js2-print-ast (js2-prop-get-node-left n) 0)
3632 (insert ".")
3633 (js2-print-ast (js2-prop-get-node-right n) 0))
3634
3635 (defstruct (js2-elem-get-node
3636 (:include js2-node)
3637 (:constructor nil)
3638 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3639 (pos js2-ts-cursor)
3640 len
3641 target
3642 element
3643 lb
3644 rb)))
3645 "AST node for an array index expression such as foo[bar]."
3646 target ; a `js2-node' - the expression preceding the "."
3647 element ; a `js2-node' - the expression in brackets
3648 lb ; position of left-bracket, nil if omitted
3649 rb) ; position of right-bracket, nil if omitted
3650
3651 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3652 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3653
3654 (defun js2-visit-elem-get-node (n v)
3655 (js2-visit-ast (js2-elem-get-node-target n) v)
3656 (js2-visit-ast (js2-elem-get-node-element n) v))
3657
3658 (defun js2-print-elem-get-node (n i)
3659 (insert (js2-make-pad i))
3660 (js2-print-ast (js2-elem-get-node-target n) 0)
3661 (insert "[")
3662 (js2-print-ast (js2-elem-get-node-element n) 0)
3663 (insert "]"))
3664
3665 (defstruct (js2-call-node
3666 (:include js2-node)
3667 (:constructor nil)
3668 (:constructor make-js2-call-node (&key (type js2-CALL)
3669 (pos js2-ts-cursor)
3670 len
3671 target
3672 args
3673 lp
3674 rp)))
3675 "AST node for a JavaScript function call."
3676 target ; a `js2-node' evaluating to the function to call
3677 args ; a lisp list of `js2-node' arguments
3678 lp ; position of open-paren, or nil if missing
3679 rp) ; position of close-paren, or nil if missing
3680
3681 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3682 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3683
3684 (defun js2-visit-call-node (n v)
3685 (js2-visit-ast (js2-call-node-target n) v)
3686 (dolist (arg (js2-call-node-args n))
3687 (js2-visit-ast arg v)))
3688
3689 (defun js2-print-call-node (n i)
3690 (insert (js2-make-pad i))
3691 (js2-print-ast (js2-call-node-target n) 0)
3692 (insert "(")
3693 (js2-print-list (js2-call-node-args n))
3694 (insert ")"))
3695
3696 (defstruct (js2-yield-node
3697 (:include js2-node)
3698 (:constructor nil)
3699 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3700 (pos js2-ts-cursor)
3701 len
3702 value)))
3703 "AST node for yield statement or expression."
3704 value) ; optional: value to be yielded
3705
3706 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3707 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3708
3709 (defun js2-visit-yield-node (n v)
3710 (js2-visit-ast (js2-yield-node-value n) v))
3711
3712 (defun js2-print-yield-node (n i)
3713 (insert (js2-make-pad i))
3714 (insert "yield")
3715 (when (js2-yield-node-value n)
3716 (insert " ")
3717 (js2-print-ast (js2-yield-node-value n) 0)))
3718
3719 (defstruct (js2-paren-node
3720 (:include js2-node)
3721 (:constructor nil)
3722 (:constructor make-js2-paren-node (&key (type js2-LP)
3723 (pos js2-ts-cursor)
3724 len
3725 expr)))
3726 "AST node for a parenthesized expression.
3727 In particular, used when the parens are syntactically optional,
3728 as opposed to required parens such as those enclosing an if-conditional."
3729 expr) ; `js2-node'
3730
3731 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3732 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3733
3734 (defun js2-visit-paren-node (n v)
3735 (js2-visit-ast (js2-paren-node-expr n) v))
3736
3737 (defun js2-print-paren-node (n i)
3738 (insert (js2-make-pad i))
3739 (insert "(")
3740 (js2-print-ast (js2-paren-node-expr n) 0)
3741 (insert ")"))
3742
3743 (defstruct (js2-array-comp-node
3744 (:include js2-scope)
3745 (:constructor nil)
3746 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3747 (pos js2-ts-cursor)
3748 len
3749 result
3750 loops
3751 filter
3752 if-pos
3753 lp
3754 rp)))
3755 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3756 result ; result expression (just after left-bracket)
3757 loops ; a lisp list of `js2-array-comp-loop-node'
3758 filter ; guard/filter expression
3759 if-pos ; buffer pos of 'if' keyword, if present, else nil
3760 lp ; buffer position of if-guard left-paren, or nil if not present
3761 rp) ; buffer position of if-guard right-paren, or nil if not present
3762
3763 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3764 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3765
3766 (defun js2-visit-array-comp-node (n v)
3767 (js2-visit-ast (js2-array-comp-node-result n) v)
3768 (dolist (l (js2-array-comp-node-loops n))
3769 (js2-visit-ast l v))
3770 (js2-visit-ast (js2-array-comp-node-filter n) v))
3771
3772 (defun js2-print-array-comp-node (n i)
3773 (let ((pad (js2-make-pad i))
3774 (result (js2-array-comp-node-result n))
3775 (loops (js2-array-comp-node-loops n))
3776 (filter (js2-array-comp-node-filter n)))
3777 (insert pad "[")
3778 (js2-print-ast result 0)
3779 (dolist (l loops)
3780 (insert " ")
3781 (js2-print-ast l 0))
3782 (when filter
3783 (insert " if (")
3784 (js2-print-ast filter 0))
3785 (insert ")]")))
3786
3787 (defstruct (js2-array-comp-loop-node
3788 (:include js2-for-in-node)
3789 (:constructor nil)
3790 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3791 (pos js2-ts-cursor)
3792 len
3793 iterator
3794 object
3795 in-pos
3796 foreach-p
3797 each-pos
3798 lp
3799 rp)))
3800 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3801
3802 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3803 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3804
3805 (defun js2-visit-array-comp-loop (n v)
3806 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3807 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3808
3809 (defun js2-print-array-comp-loop (n i)
3810 (insert "for (")
3811 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3812 (insert " in ")
3813 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3814 (insert ")"))
3815
3816 (defstruct (js2-empty-expr-node
3817 (:include js2-node)
3818 (:constructor nil)
3819 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3820 (pos js2-token-beg)
3821 len)))
3822 "AST node for an empty expression.")
3823
3824 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3825 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3826
3827 (defstruct (js2-xml-node
3828 (:include js2-block-node)
3829 (:constructor nil)
3830 (:constructor make-js2-xml-node (&key (type js2-XML)
3831 (pos js2-token-beg)
3832 len
3833 kids)))
3834 "AST node for initial parse of E4X literals.
3835 The kids field is a list of XML fragments, each a `js2-string-node' or
3836 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3837
3838 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3839 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3840
3841 (defun js2-print-xml-node (n i)
3842 (dolist (kid (js2-xml-node-kids n))
3843 (js2-print-ast kid i)))
3844
3845 (defstruct (js2-xml-js-expr-node
3846 (:include js2-xml-node)
3847 (:constructor nil)
3848 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3849 (pos js2-ts-cursor)
3850 len
3851 expr)))
3852 "AST node for an embedded JavaScript {expression} in an E4X literal.
3853 The start and end fields correspond to the curly-braces."
3854 expr) ; a `js2-expr-node' of some sort
3855
3856 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3857 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3858
3859 (defun js2-visit-xml-js-expr (n v)
3860 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3861
3862 (defun js2-print-xml-js-expr (n i)
3863 (insert (js2-make-pad i))
3864 (insert "{")
3865 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3866 (insert "}"))
3867
3868 (defstruct (js2-xml-dot-query-node
3869 (:include js2-infix-node)
3870 (:constructor nil)
3871 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3872 (pos js2-ts-cursor)
3873 op-pos
3874 len
3875 left
3876 right
3877 rp)))
3878 "AST node for an E4X foo.(bar) filter expression.
3879 Note that the left-paren is automatically the character immediately
3880 following the dot (.) in the operator. No whitespace is permitted
3881 between the dot and the lp by the scanner."
3882 rp)
3883
3884 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3885 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3886
3887 (defun js2-print-xml-dot-query (n i)
3888 (insert (js2-make-pad i))
3889 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3890 (insert ".(")
3891 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3892 (insert ")"))
3893
3894 (defstruct (js2-xml-ref-node
3895 (:include js2-node)
3896 (:constructor nil)) ; abstract
3897 "Base type for E4X XML attribute-access or property-get expressions.
3898 Such expressions can take a variety of forms. The general syntax has
3899 three parts:
3900
3901 - (optional) an @ (specifying an attribute access)
3902 - (optional) a namespace (a `js2-name-node') and double-colon
3903 - (required) either a `js2-name-node' or a bracketed [expression]
3904
3905 The property-name expressions (examples: ns::name, @name) are
3906 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3907 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3908
3909 This node type (or more specifically, its subclasses) will sometimes
3910 be the right-hand child of a `js2-prop-get-node' or a
3911 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3912 The `js2-xml-ref-node' may also be a standalone primary expression with
3913 no explicit target, which is valid in certain expression contexts such as
3914
3915 company..employee.(@id < 100)
3916
3917 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3918 expression whose parent is a `js2-xml-dot-query-node'."
3919 namespace
3920 at-pos
3921 colon-pos)
3922
3923 (defsubst js2-xml-ref-node-attr-access-p (node)
3924 "Return non-nil if this expression began with an @-token."
3925 (and (numberp (js2-xml-ref-node-at-pos node))
3926 (plusp (js2-xml-ref-node-at-pos node))))
3927
3928 (defstruct (js2-xml-prop-ref-node
3929 (:include js2-xml-ref-node)
3930 (:constructor nil)
3931 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3932 (pos js2-token-beg)
3933 len
3934 propname
3935 namespace
3936 at-pos
3937 colon-pos)))
3938 "AST node for an E4X XML [expr] property-ref expression.
3939 The JavaScript syntax is an optional @, an optional ns::, and a name.
3940
3941 [ '@' ] [ name '::' ] name
3942
3943 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3944 @ns::*, @*::attr, @*::*, and @*.
3945
3946 The node starts at the @ token, if present. Otherwise it starts at the
3947 namespace name. The node bounds extend through the closing right-bracket,
3948 or if it is missing due to a syntax error, through the end of the index
3949 expression."
3950 propname)
3951
3952 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3953 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3954
3955 (defun js2-visit-xml-prop-ref-node (n v)
3956 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3957 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3958
3959 (defun js2-print-xml-prop-ref-node (n i)
3960 (insert (js2-make-pad i))
3961 (if (js2-xml-ref-node-attr-access-p n)
3962 (insert "@"))
3963 (when (js2-xml-prop-ref-node-namespace n)
3964 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3965 (insert "::"))
3966 (if (js2-xml-prop-ref-node-propname n)
3967 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3968
3969 (defstruct (js2-xml-elem-ref-node
3970 (:include js2-xml-ref-node)
3971 (:constructor nil)
3972 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3973 (pos js2-token-beg)
3974 len
3975 expr
3976 lb
3977 rb
3978 namespace
3979 at-pos
3980 colon-pos)))
3981 "AST node for an E4X XML [expr] member-ref expression.
3982 Syntax:
3983
3984 [ '@' ] [ name '::' ] '[' expr ']'
3985
3986 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3987
3988 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3989 is not a legal E4X XML element-ref expression, since it's already used
3990 for standard JavaScript element-get array indexing. Hence, a
3991 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3992 non-nil namespace node, or both.
3993
3994 The node starts at the @ token, if present. Otherwise it starts
3995 at the namespace name. The node bounds extend through the closing
3996 right-bracket, or if it is missing due to a syntax error, through the
3997 end of the index expression."
3998 expr ; the bracketed index expression
3999 lb
4000 rb)
4001
4002 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4003 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4004
4005 (defun js2-visit-xml-elem-ref-node (n v)
4006 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4007 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4008
4009 (defun js2-print-xml-elem-ref-node (n i)
4010 (insert (js2-make-pad i))
4011 (if (js2-xml-ref-node-attr-access-p n)
4012 (insert "@"))
4013 (when (js2-xml-elem-ref-node-namespace n)
4014 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4015 (insert "::"))
4016 (insert "[")
4017 (if (js2-xml-elem-ref-node-expr n)
4018 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4019 (insert "]"))
4020
4021 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4022
4023 (defstruct (js2-xml-start-tag-node
4024 (:include js2-xml-node)
4025 (:constructor nil)
4026 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4027 (pos js2-ts-cursor)
4028 len
4029 name
4030 attrs
4031 kids
4032 empty-p)))
4033 "AST node for an XML start-tag. Not currently used.
4034 The `kids' field is a lisp list of child content nodes."
4035 name ; a `js2-xml-name-node'
4036 attrs ; a lisp list of `js2-xml-attr-node'
4037 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4038
4039 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4040 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4041
4042 (defun js2-visit-xml-start-tag (n v)
4043 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4044 (dolist (attr (js2-xml-start-tag-node-attrs n))
4045 (js2-visit-ast attr v))
4046 (js2-visit-block n v))
4047
4048 (defun js2-print-xml-start-tag (n i)
4049 (insert (js2-make-pad i) "<")
4050 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4051 (when (js2-xml-start-tag-node-attrs n)
4052 (insert " ")
4053 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4054 (insert ">"))
4055
4056 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4057 ;; and add the end-tag to the kids list of the parent as well.
4058 (defstruct (js2-xml-end-tag-node
4059 (:include js2-xml-node)
4060 (:constructor nil)
4061 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4062 (pos js2-ts-cursor)
4063 len
4064 name)))
4065 "AST node for an XML end-tag. Not currently used."
4066 name) ; a `js2-xml-name-node'
4067
4068 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4069 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4070
4071 (defun js2-visit-xml-end-tag (n v)
4072 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4073
4074 (defun js2-print-xml-end-tag (n i)
4075 (insert (js2-make-pad i))
4076 (insert "</")
4077 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4078 (insert ">"))
4079
4080 (defstruct (js2-xml-name-node
4081 (:include js2-xml-node)
4082 (:constructor nil)
4083 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4084 (pos js2-ts-cursor)
4085 len
4086 namespace
4087 kids)))
4088 "AST node for an E4X XML name. Not currently used.
4089 Any XML name can be qualified with a namespace, hence the namespace field.
4090 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4091 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4092 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4093 namespace) ; a `js2-string-node'
4094
4095 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4096 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4097
4098 (defun js2-visit-xml-name-node (n v)
4099 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4100
4101 (defun js2-print-xml-name-node (n i)
4102 (insert (js2-make-pad i))
4103 (when (js2-xml-name-node-namespace n)
4104 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4105 (insert "::"))
4106 (dolist (kid (js2-xml-name-node-kids n))
4107 (js2-print-ast kid 0)))
4108
4109 (defstruct (js2-xml-pi-node
4110 (:include js2-xml-node)
4111 (:constructor nil)
4112 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4113 (pos js2-ts-cursor)
4114 len
4115 name
4116 attrs)))
4117 "AST node for an E4X XML processing instruction. Not currently used."
4118 name ; a `js2-xml-name-node'
4119 attrs) ; a list of `js2-xml-attr-node'
4120
4121 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4122 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4123
4124 (defun js2-visit-xml-pi-node (n v)
4125 (js2-visit-ast (js2-xml-pi-node-name n) v)
4126 (dolist (attr (js2-xml-pi-node-attrs n))
4127 (js2-visit-ast attr v)))
4128
4129 (defun js2-print-xml-pi-node (n i)
4130 (insert (js2-make-pad i) "<?")
4131 (js2-print-ast (js2-xml-pi-node-name n))
4132 (when (js2-xml-pi-node-attrs n)
4133 (insert " ")
4134 (js2-print-list (js2-xml-pi-node-attrs n)))
4135 (insert "?>"))
4136
4137 (defstruct (js2-xml-cdata-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 content)))
4144 "AST node for a CDATA escape section. Not currently used."
4145 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4146
4147 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4148 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4149
4150 (defun js2-visit-xml-cdata-node (n v)
4151 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4152
4153 (defun js2-print-xml-cdata-node (n i)
4154 (insert (js2-make-pad i))
4155 (js2-print-ast (js2-xml-cdata-node-content n)))
4156
4157 (defstruct (js2-xml-attr-node
4158 (:include js2-xml-node)
4159 (:constructor nil)
4160 (:constructor make-js2-attr-node (&key (type js2-XML)
4161 (pos js2-ts-cursor)
4162 len
4163 name
4164 value
4165 eq-pos
4166 quote-type)))
4167 "AST node representing a foo='bar' XML attribute value. Not yet used."
4168 name ; a `js2-xml-name-node'
4169 value ; a `js2-xml-name-node'
4170 eq-pos ; buffer position of "=" sign
4171 quote-type) ; 'single or 'double
4172
4173 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4174 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4175
4176 (defun js2-visit-xml-attr-node (n v)
4177 (js2-visit-ast (js2-xml-attr-node-name n) v)
4178 (js2-visit-ast (js2-xml-attr-node-value n) v))
4179
4180 (defun js2-print-xml-attr-node (n i)
4181 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4182 "'"
4183 "\"")))
4184 (insert (js2-make-pad i))
4185 (js2-print-ast (js2-xml-attr-node-name n) 0)
4186 (insert "=" quote)
4187 (js2-print-ast (js2-xml-attr-node-value n) 0)
4188 (insert quote)))
4189
4190 (defstruct (js2-xml-text-node
4191 (:include js2-xml-node)
4192 (:constructor nil)
4193 (:constructor make-js2-text-node (&key (type js2-XML)
4194 (pos js2-ts-cursor)
4195 len
4196 content)))
4197 "AST node for an E4X XML text node. Not currently used."
4198 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4199
4200 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4201 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4202
4203 (defun js2-visit-xml-text-node (n v)
4204 (js2-visit-ast (js2-xml-text-node-content n) v))
4205
4206 (defun js2-print-xml-text-node (n i)
4207 (insert (js2-make-pad i))
4208 (dolist (kid (js2-xml-text-node-content n))
4209 (js2-print-ast kid)))
4210
4211 (defstruct (js2-xml-comment-node
4212 (:include js2-xml-node)
4213 (:constructor nil)
4214 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4215 (pos js2-ts-cursor)
4216 len)))
4217 "AST node for E4X XML comment. Not currently used.")
4218
4219 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4221
4222 (defun js2-print-xml-comment (n i)
4223 (insert (js2-make-pad i)
4224 (js2-node-string n)))
4225
4226 ;;; Node utilities
4227
4228 (defsubst js2-node-line (n)
4229 "Fetch the source line number at the start of node N.
4230 This is O(n) in the length of the source buffer; use prudently."
4231 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4232
4233 (defsubst js2-block-node-kid (n i)
4234 "Return child I of node N, or nil if there aren't that many."
4235 (nth i (js2-block-node-kids n)))
4236
4237 (defsubst js2-block-node-first (n)
4238 "Return first child of block node N, or nil if there is none."
4239 (first (js2-block-node-kids n)))
4240
4241 (defun js2-node-root (n)
4242 "Return the root of the AST containing N.
4243 If N has no parent pointer, returns N."
4244 (let ((parent (js2-node-parent n)))
4245 (if parent
4246 (js2-node-root parent)
4247 n)))
4248
4249 (defun js2-node-position-in-parent (node &optional parent)
4250 "Return the position of NODE in parent's block-kids list.
4251 PARENT can be supplied if known. Positioned returned is zero-indexed.
4252 Returns 0 if NODE is not a child of a block statement, or if NODE
4253 is not a statement node."
4254 (let ((p (or parent (js2-node-parent node)))
4255 (i 0))
4256 (if (not (js2-block-node-p p))
4257 i
4258 (or (js2-position node (js2-block-node-kids p))
4259 0))))
4260
4261 (defsubst js2-node-short-name (n)
4262 "Return the short name of node N as a string, e.g. `js2-if-node'."
4263 (substring (symbol-name (aref n 0))
4264 (length "cl-struct-")))
4265
4266 (defsubst js2-node-child-list (node)
4267 "Return the child list for NODE, a lisp list of nodes.
4268 Works for block nodes, array nodes, obj literals, funarg lists,
4269 var decls and try nodes (for catch clauses). Note that you should call
4270 `js2-block-node-kids' on the function body for the body statements.
4271 Returns nil for zero-length child lists or unsupported nodes."
4272 (cond
4273 ((js2-function-node-p node)
4274 (js2-function-node-params node))
4275 ((js2-block-node-p node)
4276 (js2-block-node-kids node))
4277 ((js2-try-node-p node)
4278 (js2-try-node-catch-clauses node))
4279 ((js2-array-node-p node)
4280 (js2-array-node-elems node))
4281 ((js2-object-node-p node)
4282 (js2-object-node-elems node))
4283 ((js2-call-node-p node)
4284 (js2-call-node-args node))
4285 ((js2-new-node-p node)
4286 (js2-new-node-args node))
4287 ((js2-var-decl-node-p node)
4288 (js2-var-decl-node-kids node))
4289 (t
4290 nil)))
4291
4292 (defsubst js2-node-set-child-list (node kids)
4293 "Set the child list for NODE to KIDS."
4294 (cond
4295 ((js2-function-node-p node)
4296 (setf (js2-function-node-params node) kids))
4297 ((js2-block-node-p node)
4298 (setf (js2-block-node-kids node) kids))
4299 ((js2-try-node-p node)
4300 (setf (js2-try-node-catch-clauses node) kids))
4301 ((js2-array-node-p node)
4302 (setf (js2-array-node-elems node) kids))
4303 ((js2-object-node-p node)
4304 (setf (js2-object-node-elems node) kids))
4305 ((js2-call-node-p node)
4306 (setf (js2-call-node-args node) kids))
4307 ((js2-new-node-p node)
4308 (setf (js2-new-node-args node) kids))
4309 ((js2-var-decl-node-p node)
4310 (setf (js2-var-decl-node-kids node) kids))
4311 (t
4312 (error "Unsupported node type: %s" (js2-node-short-name node))))
4313 kids)
4314
4315 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4316 (defconst js2-paren-expr-nodes
4317 '(cl-struct-js2-array-comp-loop-node
4318 cl-struct-js2-array-comp-node
4319 cl-struct-js2-call-node
4320 cl-struct-js2-catch-node
4321 cl-struct-js2-do-node
4322 cl-struct-js2-elem-get-node
4323 cl-struct-js2-for-in-node
4324 cl-struct-js2-for-node
4325 cl-struct-js2-function-node
4326 cl-struct-js2-if-node
4327 cl-struct-js2-let-node
4328 cl-struct-js2-new-node
4329 cl-struct-js2-paren-node
4330 cl-struct-js2-switch-node
4331 cl-struct-js2-while-node
4332 cl-struct-js2-with-node
4333 cl-struct-js2-xml-dot-query-node)
4334 "Node types that can have a parenthesized child expression.
4335 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4336
4337 (defsubst js2-paren-expr-node-p (node)
4338 "Return t for nodes that typically have a parenthesized child expression.
4339 Useful for computing the indentation anchors for arg-lists and conditions.
4340 Note that it may return a false positive, for instance when NODE is
4341 a `js2-new-node' and there are no arguments or parentheses."
4342 (memq (aref node 0) js2-paren-expr-nodes))
4343
4344 ;; Fake polymorphism... yech.
4345 (defsubst js2-node-lp (node)
4346 "Return relative left-paren position for NODE, if applicable.
4347 For `js2-elem-get-node' structs, returns left-bracket position.
4348 Note that the position may be nil in the case of a parse error."
4349 (cond
4350 ((js2-elem-get-node-p node)
4351 (js2-elem-get-node-lb node))
4352 ((js2-loop-node-p node)
4353 (js2-loop-node-lp node))
4354 ((js2-function-node-p node)
4355 (js2-function-node-lp node))
4356 ((js2-if-node-p node)
4357 (js2-if-node-lp node))
4358 ((js2-new-node-p node)
4359 (js2-new-node-lp node))
4360 ((js2-call-node-p node)
4361 (js2-call-node-lp node))
4362 ((js2-paren-node-p node)
4363 (js2-node-pos node))
4364 ((js2-switch-node-p node)
4365 (js2-switch-node-lp node))
4366 ((js2-catch-node-p node)
4367 (js2-catch-node-lp node))
4368 ((js2-let-node-p node)
4369 (js2-let-node-lp node))
4370 ((js2-array-comp-node-p node)
4371 (js2-array-comp-node-lp node))
4372 ((js2-with-node-p node)
4373 (js2-with-node-lp node))
4374 ((js2-xml-dot-query-node-p node)
4375 (1+ (js2-infix-node-op-pos node)))
4376 (t
4377 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4378
4379 ;; Fake polymorphism... blech.
4380 (defsubst js2-node-rp (node)
4381 "Return relative right-paren position for NODE, if applicable.
4382 For `js2-elem-get-node' structs, returns right-bracket position.
4383 Note that the position may be nil in the case of a parse error."
4384 (cond
4385 ((js2-elem-get-node-p node)
4386 (js2-elem-get-node-lb node))
4387 ((js2-loop-node-p node)
4388 (js2-loop-node-rp node))
4389 ((js2-function-node-p node)
4390 (js2-function-node-rp node))
4391 ((js2-if-node-p node)
4392 (js2-if-node-rp node))
4393 ((js2-new-node-p node)
4394 (js2-new-node-rp node))
4395 ((js2-call-node-p node)
4396 (js2-call-node-rp node))
4397 ((js2-paren-node-p node)
4398 (+ (js2-node-pos node) (js2-node-len node)))
4399 ((js2-switch-node-p node)
4400 (js2-switch-node-rp node))
4401 ((js2-catch-node-p node)
4402 (js2-catch-node-rp node))
4403 ((js2-let-node-p node)
4404 (js2-let-node-rp node))
4405 ((js2-array-comp-node-p node)
4406 (js2-array-comp-node-rp node))
4407 ((js2-with-node-p node)
4408 (js2-with-node-rp node))
4409 ((js2-xml-dot-query-node-p node)
4410 (1+ (js2-xml-dot-query-node-rp node)))
4411 (t
4412 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4413
4414 (defsubst js2-node-first-child (node)
4415 "Returns the first element of `js2-node-child-list' for NODE."
4416 (car (js2-node-child-list node)))
4417
4418 (defsubst js2-node-last-child (node)
4419 "Returns the last element of `js2-node-last-child' for NODE."
4420 (car (last (js2-node-child-list node))))
4421
4422 (defun js2-node-prev-sibling (node)
4423 "Return the previous statement in parent.
4424 Works for parents supported by `js2-node-child-list'.
4425 Returns nil if NODE is not in the parent, or PARENT is
4426 not a supported node, or if NODE is the first child."
4427 (let* ((p (js2-node-parent node))
4428 (kids (js2-node-child-list p))
4429 (sib (car kids)))
4430 (while (and kids
4431 (not (eq node (cadr kids))))
4432 (setq kids (cdr kids)
4433 sib (car kids)))
4434 sib))
4435
4436 (defun js2-node-next-sibling (node)
4437 "Return the next statement in parent block.
4438 Returns nil if NODE is not in the block, or PARENT is not
4439 a block node, or if NODE is the last statement."
4440 (let* ((p (js2-node-parent node))
4441 (kids (js2-node-child-list p)))
4442 (while (and kids
4443 (not (eq node (car kids))))
4444 (setq kids (cdr kids)))
4445 (cadr kids)))
4446
4447 (defun js2-node-find-child-before (pos parent &optional after)
4448 "Find the last child that starts before POS in parent.
4449 If AFTER is non-nil, returns first child starting after POS.
4450 POS is an absolute buffer position. PARENT is any node
4451 supported by `js2-node-child-list'.
4452 Returns nil if no applicable child is found."
4453 (let ((kids (if (js2-function-node-p parent)
4454 (js2-block-node-kids (js2-function-node-body parent))
4455 (js2-node-child-list parent)))
4456 (beg (if (js2-function-node-p parent)
4457 (js2-node-abs-pos (js2-function-node-body parent))
4458 (js2-node-abs-pos parent)))
4459 kid
4460 result
4461 fn
4462 (continue t))
4463 (setq fn (if after '> '<))
4464 (while (and kids continue)
4465 (setq kid (car kids))
4466 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4467 (setq result kid
4468 continue (if after nil t))
4469 (setq continue (if after t nil)))
4470 (setq kids (cdr kids)))
4471 result))
4472
4473 (defun js2-node-find-child-after (pos parent)
4474 "Find first child that starts after POS in parent.
4475 POS is an absolute buffer position. PARENT is any node
4476 supported by `js2-node-child-list'.
4477 Returns nil if no applicable child is found."
4478 (js2-node-find-child-before pos parent 'after))
4479
4480 (defun js2-node-replace-child (pos parent new-node)
4481 "Replace node at index POS in PARENT with NEW-NODE.
4482 Only works for parents supported by `js2-node-child-list'."
4483 (let ((kids (js2-node-child-list parent))
4484 (i 0))
4485 (while (< i pos)
4486 (setq kids (cdr kids)
4487 i (1+ i)))
4488 (setcar kids new-node)
4489 (js2-node-add-children parent new-node)))
4490
4491 (defun js2-node-buffer (n)
4492 "Return the buffer associated with AST N.
4493 Returns nil if the buffer is not set as a property on the root
4494 node, or if parent links were not recorded during parsing."
4495 (let ((root (js2-node-root n)))
4496 (and root
4497 (js2-ast-root-p root)
4498 (js2-ast-root-buffer root))))
4499
4500 (defsubst js2-block-node-push (n kid)
4501 "Push js2-node KID onto the end of js2-block-node N's child list.
4502 KID is always added to the -end- of the kids list.
4503 Function also calls `js2-node-add-children' to add the parent link."
4504 (let ((kids (js2-node-child-list n)))
4505 (if kids
4506 (setcdr kids (nconc (cdr kids) (list kid)))
4507 (js2-node-set-child-list n (list kid)))
4508 (js2-node-add-children n kid)))
4509
4510 (defun js2-node-string (node)
4511 (let ((buf (js2-node-buffer node))
4512 pos)
4513 (unless buf
4514 (error "No buffer available for node %s" node))
4515 (save-excursion
4516 (set-buffer buf)
4517 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4518 (+ pos (js2-node-len node))))))
4519
4520 ;; Container for storing the node we're looking for in a traversal.
4521 (js2-deflocal js2-discovered-node nil)
4522
4523 ;; Keep track of absolute node position during traversals.
4524 (js2-deflocal js2-visitor-offset nil)
4525
4526 (js2-deflocal js2-node-search-point nil)
4527
4528 (when js2-mode-dev-mode-p
4529 (defun js2-find-node-at-point ()
4530 (interactive)
4531 (let ((node (js2-node-at-point)))
4532 (message "%s" (or node "No node found at point"))))
4533 (defun js2-node-name-at-point ()
4534 (interactive)
4535 (let ((node (js2-node-at-point)))
4536 (message "%s" (if node
4537 (js2-node-short-name node)
4538 "No node found at point.")))))
4539
4540 (defun js2-node-at-point (&optional pos skip-comments)
4541 "Return AST node at POS, a buffer position, defaulting to current point.
4542 The `js2-mode-ast' variable must be set to the current parse tree.
4543 Signals an error if the AST (`js2-mode-ast') is nil.
4544 Always returns a node - if it can't find one, it returns the root.
4545 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4546 (let ((ast js2-mode-ast)
4547 result)
4548 (unless ast
4549 (error "No JavaScript AST available"))
4550 ;; Look through comments first, since they may be inside nodes that
4551 ;; would otherwise report a match.
4552 (setq pos (or pos (point))
4553 result (if (> pos (js2-node-abs-end ast))
4554 ast
4555 (if (not skip-comments)
4556 (js2-comment-at-point pos))))
4557 (unless result
4558 (setq js2-discovered-node nil
4559 js2-visitor-offset 0
4560 js2-node-search-point pos)
4561 (unwind-protect
4562 (catch 'js2-visit-done
4563 (js2-visit-ast ast #'js2-node-at-point-visitor))
4564 (setq js2-visitor-offset nil
4565 js2-node-search-point nil))
4566 (setq result js2-discovered-node))
4567 ;; may have found a comment beyond end of last child node,
4568 ;; since visiting the ast-root looks at the comment-list last.
4569 (if (and skip-comments
4570 (js2-comment-node-p result))
4571 (setq result nil))
4572 (or result js2-mode-ast)))
4573
4574 (defun js2-node-at-point-visitor (node end-p)
4575 (let ((rel-pos (js2-node-pos node))
4576 abs-pos
4577 abs-end
4578 (point js2-node-search-point))
4579 (cond
4580 (end-p
4581 ;; this evaluates to a non-nil return value, even if it's zero
4582 (decf js2-visitor-offset rel-pos))
4583 ;; we already looked for comments before visiting, and don't want them now
4584 ((js2-comment-node-p node)
4585 nil)
4586 (t
4587 (setq abs-pos (incf js2-visitor-offset rel-pos)
4588 ;; we only want to use the node if the point is before
4589 ;; the last character position in the node, so we decrement
4590 ;; the absolute end by 1.
4591 abs-end (+ abs-pos (js2-node-len node) -1))
4592 (cond
4593 ;; If this node starts after search-point, stop the search.
4594 ((> abs-pos point)
4595 (throw 'js2-visit-done nil))
4596 ;; If this node ends before the search-point, don't check kids.
4597 ((> point abs-end)
4598 nil)
4599 (t
4600 ;; Otherwise point is within this node, possibly in a child.
4601 (setq js2-discovered-node node)
4602 t)))))) ; keep processing kids to look for more specific match
4603
4604 (defsubst js2-block-comment-p (node)
4605 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4606 (and (js2-comment-node-p node)
4607 (memq (js2-comment-node-format node) '(jsdoc block))))
4608
4609 ;; TODO: put the comments in a vector and binary-search them instead
4610 (defun js2-comment-at-point (&optional pos)
4611 "Look through scanned comment nodes for one containing POS.
4612 POS is a buffer position that defaults to current point.
4613 Function returns nil if POS was not in any comment node."
4614 (let ((ast js2-mode-ast)
4615 (x (or pos (point)))
4616 beg
4617 end)
4618 (unless ast
4619 (error "No JavaScript AST available"))
4620 (catch 'done
4621 ;; Comments are stored in lexical order.
4622 (dolist (comment (js2-ast-root-comments ast) nil)
4623 (setq beg (js2-node-abs-pos comment)
4624 end (+ beg (js2-node-len comment)))
4625 (if (and (>= x beg)
4626 (<= x end))
4627 (throw 'done comment))))))
4628
4629 (defun js2-mode-find-parent-fn (node)
4630 "Find function enclosing NODE.
4631 Returns nil if NODE is not inside a function."
4632 (setq node (js2-node-parent node))
4633 (while (and node (not (js2-function-node-p node)))
4634 (setq node (js2-node-parent node)))
4635 (and (js2-function-node-p node) node))
4636
4637 (defun js2-mode-find-enclosing-fn (node)
4638 "Find function or root enclosing NODE."
4639 (if (js2-ast-root-p node)
4640 node
4641 (setq node (js2-node-parent node))
4642 (while (not (or (js2-ast-root-p node)
4643 (js2-function-node-p node)))
4644 (setq node (js2-node-parent node)))
4645 node))
4646
4647 (defun js2-mode-find-enclosing-node (beg end)
4648 "Find script or function fully enclosing BEG and END."
4649 (let ((node (js2-node-at-point beg))
4650 pos
4651 (continue t))
4652 (while continue
4653 (if (or (js2-ast-root-p node)
4654 (and (js2-function-node-p node)
4655 (<= (setq pos (js2-node-abs-pos node)) beg)
4656 (>= (+ pos (js2-node-len node)) end)))
4657 (setq continue nil)
4658 (setq node (js2-node-parent node))))
4659 node))
4660
4661 (defun js2-node-parent-script-or-fn (node)
4662 "Find script or function immediately enclosing NODE.
4663 If NODE is the ast-root, returns nil."
4664 (if (js2-ast-root-p node)
4665 nil
4666 (setq node (js2-node-parent node))
4667 (while (and node (not (or (js2-function-node-p node)
4668 (js2-script-node-p node))))
4669 (setq node (js2-node-parent node)))
4670 node))
4671
4672 (defsubst js2-nested-function-p (node)
4673 "Return t if NODE is a nested function, or is inside a nested function."
4674 (unless (js2-ast-root-p node)
4675 (js2-function-node-p (if (js2-function-node-p node)
4676 (js2-node-parent-script-or-fn node)
4677 (js2-node-parent-script-or-fn
4678 (js2-node-parent-script-or-fn node))))))
4679
4680 (defsubst js2-function-param-node-p (node)
4681 "Return non-nil if NODE is a param node of a `js2-function-node'."
4682 (let ((parent (js2-node-parent node)))
4683 (and parent
4684 (js2-function-node-p parent)
4685 (memq node (js2-function-node-params parent)))))
4686
4687 (defsubst js2-mode-shift-kids (kids start offset)
4688 (dolist (kid kids)
4689 (if (> (js2-node-pos kid) start)
4690 (incf (js2-node-pos kid) offset))))
4691
4692 (defsubst js2-mode-shift-children (parent start offset)
4693 "Update start-positions of all children of PARENT beyond START."
4694 (let ((root (js2-node-root parent)))
4695 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4696 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4697
4698 (defsubst js2-node-is-descendant (node ancestor)
4699 "Return t if NODE is a descendant of ANCESTOR."
4700 (while (and node
4701 (not (eq node ancestor)))
4702 (setq node (js2-node-parent node)))
4703 node)
4704
4705 ;;; visitor infrastructure
4706
4707 (defun js2-visit-none (node callback)
4708 "Visitor for AST node that have no node children."
4709 nil)
4710
4711 (defun js2-print-none (node indent)
4712 "Visitor for AST node with no printed representation.")
4713
4714 (defun js2-print-body (node indent)
4715 "Print a statement, or a block without braces."
4716 (if (js2-block-node-p node)
4717 (dolist (kid (js2-block-node-kids node))
4718 (js2-print-ast kid indent))
4719 (js2-print-ast node indent)))
4720
4721 (defun js2-print-list (args &optional delimiter)
4722 (loop with len = (length args)
4723 for arg in args
4724 for count from 1
4725 do
4726 (js2-print-ast arg 0)
4727 (if (< count len)
4728 (insert (or delimiter ", ")))))
4729
4730 (defun js2-print-tree (ast)
4731 "Prints an AST to the current buffer.
4732 Makes `js2-ast-parent-nodes' available to the printer functions."
4733 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4734 (js2-print-ast ast)))
4735
4736 (defun js2-print-ast (node &optional indent)
4737 "Helper function for printing AST nodes.
4738 Requires `js2-ast-parent-nodes' to be non-nil.
4739 You should use `js2-print-tree' instead of this function."
4740 (let ((printer (get (aref node 0) 'js2-printer))
4741 (i (or indent 0))
4742 (pos (js2-node-abs-pos node)))
4743 ;; TODO: wedge comments in here somewhere
4744 (if printer
4745 (funcall printer node i))))
4746
4747 (defconst js2-side-effecting-tokens
4748 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4749 (dolist (tt (list js2-ASSIGN
4750 js2-ASSIGN_ADD
4751 js2-ASSIGN_BITAND
4752 js2-ASSIGN_BITOR
4753 js2-ASSIGN_BITXOR
4754 js2-ASSIGN_DIV
4755 js2-ASSIGN_LSH
4756 js2-ASSIGN_MOD
4757 js2-ASSIGN_MUL
4758 js2-ASSIGN_RSH
4759 js2-ASSIGN_SUB
4760 js2-ASSIGN_URSH
4761 js2-BLOCK
4762 js2-BREAK
4763 js2-CALL
4764 js2-CATCH
4765 js2-CATCH_SCOPE
4766 js2-CONST
4767 js2-CONTINUE
4768 js2-DEBUGGER
4769 js2-DEC
4770 js2-DELPROP
4771 js2-DEL_REF
4772 js2-DO
4773 js2-ELSE
4774 js2-EMPTY
4775 js2-ENTERWITH
4776 js2-EXPORT
4777 js2-EXPR_RESULT
4778 js2-FINALLY
4779 js2-FOR
4780 js2-FUNCTION
4781 js2-GOTO
4782 js2-IF
4783 js2-IFEQ
4784 js2-IFNE
4785 js2-IMPORT
4786 js2-INC
4787 js2-JSR
4788 js2-LABEL
4789 js2-LEAVEWITH
4790 js2-LET
4791 js2-LETEXPR
4792 js2-LOCAL_BLOCK
4793 js2-LOOP
4794 js2-NEW
4795 js2-REF_CALL
4796 js2-RETHROW
4797 js2-RETURN
4798 js2-RETURN_RESULT
4799 js2-SEMI
4800 js2-SETELEM
4801 js2-SETELEM_OP
4802 js2-SETNAME
4803 js2-SETPROP
4804 js2-SETPROP_OP
4805 js2-SETVAR
4806 js2-SET_REF
4807 js2-SET_REF_OP
4808 js2-SWITCH
4809 js2-TARGET
4810 js2-THROW
4811 js2-TRY
4812 js2-VAR
4813 js2-WHILE
4814 js2-WITH
4815 js2-WITHEXPR
4816 js2-YIELD))
4817 (aset tokens tt t))
4818 (if js2-instanceof-has-side-effects
4819 (aset tokens js2-INSTANCEOF t))
4820 tokens))
4821
4822 (defun js2-node-has-side-effects (node)
4823 "Return t if NODE has side effects."
4824 (when node ; makes it easier to handle malformed expressions
4825 (let ((tt (js2-node-type node)))
4826 (cond
4827 ;; This doubtless needs some work, since EXPR_VOID is used
4828 ;; in several ways in Rhino, and I may not have caught them all.
4829 ;; I'll wait for people to notice incorrect warnings.
4830 ((and (= tt js2-EXPR_VOID)
4831 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4832 (let ((expr (js2-expr-stmt-node-expr node)))
4833 (or (js2-node-has-side-effects expr)
4834 (when (js2-string-node-p expr)
4835 (string= "use strict" (js2-string-node-value expr))))))
4836 ((= tt js2-COMMA)
4837 (js2-node-has-side-effects (js2-infix-node-right node)))
4838 ((or (= tt js2-AND)
4839 (= tt js2-OR))
4840 (or (js2-node-has-side-effects (js2-infix-node-right node))
4841 (js2-node-has-side-effects (js2-infix-node-left node))))
4842 ((= tt js2-HOOK)
4843 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4844 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4845 ((js2-paren-node-p node)
4846 (js2-node-has-side-effects (js2-paren-node-expr node)))
4847 ((= tt js2-ERROR) ; avoid cascaded error messages
4848 nil)
4849 (t
4850 (aref js2-side-effecting-tokens tt))))))
4851
4852 (defun js2-member-expr-leftmost-name (node)
4853 "For an expr such as foo.bar.baz, return leftmost node foo.
4854 NODE is any `js2-node' object. If it represents a member expression,
4855 which is any sequence of property gets, element-gets, function calls,
4856 or xml descendants/filter operators, then we look at the lexically
4857 leftmost (first) node in the chain. If it is a name-node we return it.
4858 Note that NODE can be a raw name-node and it will be returned as well.
4859 If NODE is not a name-node or member expression, or if it is a member
4860 expression whose leftmost target is not a name node, returns nil."
4861 (let ((continue t)
4862 result)
4863 (while (and continue (not result))
4864 (cond
4865 ((js2-name-node-p node)
4866 (setq result node))
4867 ((js2-prop-get-node-p node)
4868 (setq node (js2-prop-get-node-left node)))
4869 ;; TODO: handle call-nodes, xml-nodes, others?
4870 (t
4871 (setq continue nil))))
4872 result))
4873
4874 (defconst js2-stmt-node-types
4875 (list js2-BLOCK
4876 js2-BREAK
4877 js2-CONTINUE
4878 js2-DEFAULT ; e4x "default xml namespace" statement
4879 js2-DO
4880 js2-EXPR_RESULT
4881 js2-EXPR_VOID
4882 js2-FOR
4883 js2-IF
4884 js2-RETURN
4885 js2-SWITCH
4886 js2-THROW
4887 js2-TRY
4888 js2-WHILE
4889 js2-WITH)
4890 "Node types that only appear in statement contexts.
4891 The list does not include nodes that always appear as the child
4892 of another specific statement type, such as switch-cases,
4893 catch and finally blocks, and else-clauses. The list also excludes
4894 nodes like yield, let and var, which may appear in either expression
4895 or statement context, and in the latter context always have a
4896 `js2-expr-stmt-node' parent. Finally, the list does not include
4897 functions or scripts, which are treated separately from statements
4898 by the JavaScript parser and runtime.")
4899
4900 (defun js2-stmt-node-p (node)
4901 "Heuristic for figuring out if NODE is a statement.
4902 Some node types can appear in either an expression context or a
4903 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4904 For these node types in a statement context, the parent will be a
4905 `js2-expr-stmt-node'.
4906 Functions aren't included in the check."
4907 (memq (js2-node-type node) js2-stmt-node-types))
4908
4909 (defsubst js2-mode-find-first-stmt (node)
4910 "Search upward starting from NODE looking for a statement.
4911 For purposes of this function, a `js2-function-node' counts."
4912 (while (not (or (js2-stmt-node-p node)
4913 (js2-function-node-p node)))
4914 (setq node (js2-node-parent node)))
4915 node)
4916
4917 (defun js2-node-parent-stmt (node)
4918 "Return the node's first ancestor that is a statement.
4919 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4920 appearing in a statement context will have a parent that is a
4921 `js2-expr-stmt-node' that will be returned by this function."
4922 (let ((parent (js2-node-parent node)))
4923 (if (or (null parent)
4924 (js2-stmt-node-p parent)
4925 (and (js2-function-node-p parent)
4926 (not (eq (js2-function-node-form parent)
4927 'FUNCTION_EXPRESSION))))
4928 parent
4929 (js2-node-parent-stmt parent))))
4930
4931 ;; In the Mozilla Rhino sources, Roshan James writes:
4932 ;; Does consistent-return analysis on the function body when strict mode is
4933 ;; enabled.
4934 ;;
4935 ;; function (x) { return (x+1) }
4936 ;;
4937 ;; is ok, but
4938 ;;
4939 ;; function (x) { if (x < 0) return (x+1); }
4940 ;;
4941 ;; is not because the function can potentially return a value when the
4942 ;; condition is satisfied and if not, the function does not explicitly
4943 ;; return a value.
4944 ;;
4945 ;; This extends to checking mismatches such as "return" and "return <value>"
4946 ;; used in the same function. Warnings are not emitted if inconsistent
4947 ;; returns exist in code that can be statically shown to be unreachable.
4948 ;; Ex.
4949 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4950 ;;
4951 ;; emits no warning. However if the loop had a break statement, then a
4952 ;; warning would be emitted.
4953 ;;
4954 ;; The consistency analysis looks at control structures such as loops, ifs,
4955 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4956 ;; warns the user about an inconsistent set of termination possibilities.
4957 ;;
4958 ;; These flags enumerate the possible ways a statement/function can
4959 ;; terminate. These flags are used by endCheck() and by the Parser to
4960 ;; detect inconsistent return usage.
4961 ;;
4962 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4963 ;; able to execute (example: throw, continue)
4964 ;;
4965 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4966 ;; next one. Statement such as return dont. A compound statement may have
4967 ;; some branch that drops off control to the next statement.
4968 ;;
4969 ;; END_RETURNS indicates that the statement can return with no value.
4970 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4971 ;;
4972 ;; A compound statement such as
4973 ;; if (condition) {
4974 ;; return value;
4975 ;; }
4976 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4977
4978 (defconst js2-END_UNREACHED 0)
4979 (defconst js2-END_DROPS_OFF 1)
4980 (defconst js2-END_RETURNS 2)
4981 (defconst js2-END_RETURNS_VALUE 4)
4982 (defconst js2-END_YIELDS 8)
4983
4984 (defun js2-has-consistent-return-usage (node)
4985 "Check that every return usage in a function body is consistent.
4986 Returns t if the function satisfies strict mode requirement."
4987 (let ((n (js2-end-check node)))
4988 ;; either it doesn't return a value in any branch...
4989 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4990 ;; or it returns a value (or is unreached) at every branch
4991 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4992 js2-END_RETURNS
4993 js2-END_YIELDS)))))
4994
4995 (defun js2-end-check-if (node)
4996 "Returns in the then and else blocks must be consistent with each other.
4997 If there is no else block, then the return statement can fall through.
4998 Returns logical OR of END_* flags"
4999 (let ((th (js2-if-node-then-part node))
5000 (el (js2-if-node-else-part node)))
5001 (if (null th)
5002 js2-END_UNREACHED
5003 (logior (js2-end-check th) (if el
5004 (js2-end-check el)
5005 js2-END_DROPS_OFF)))))
5006
5007 (defun js2-end-check-switch (node)
5008 "Consistency of return statements is checked between the case statements.
5009 If there is no default, then the switch can fall through. If there is a
5010 default, we check to see if all code paths in the default return or if
5011 there is a code path that can fall through.
5012 Returns logical OR of END_* flags."
5013 (let ((rv js2-END_UNREACHED)
5014 default-case)
5015 ;; examine the cases
5016 (catch 'break
5017 (dolist (c (js2-switch-node-cases node))
5018 (if (js2-case-node-expr c)
5019 (js2-set-flag rv (js2-end-check-block c))
5020 (setq default-case c)
5021 (throw 'break nil))))
5022 ;; we don't care how the cases drop into each other
5023 (js2-clear-flag rv js2-END_DROPS_OFF)
5024 ;; examine the default
5025 (js2-set-flag rv (if default-case
5026 (js2-end-check default-case)
5027 js2-END_DROPS_OFF))
5028 rv))
5029
5030 (defun js2-end-check-try (node)
5031 "If the block has a finally, return consistency is checked in the
5032 finally block. If all code paths in the finally return, then the
5033 returns in the try-catch blocks don't matter. If there is a code path
5034 that does not return or if there is no finally block, the returns
5035 of the try and catch blocks are checked for mismatch.
5036 Returns logical OR of END_* flags."
5037 (let ((finally (js2-try-node-finally-block node))
5038 rv)
5039 ;; check the finally if it exists
5040 (setq rv (if finally
5041 (js2-end-check (js2-finally-node-body finally))
5042 js2-END_DROPS_OFF))
5043 ;; If the finally block always returns, then none of the returns
5044 ;; in the try or catch blocks matter.
5045 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5046 (js2-clear-flag rv js2-END_DROPS_OFF)
5047 ;; examine the try block
5048 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5049 ;; check each catch block
5050 (dolist (cb (js2-try-node-catch-clauses node))
5051 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5052 rv))
5053
5054 (defun js2-end-check-loop (node)
5055 "Return statement in the loop body must be consistent. The default
5056 assumption for any kind of a loop is that it will eventually terminate.
5057 The only exception is a loop with a constant true condition. Code that
5058 follows such a loop is examined only if one can statically determine
5059 that there is a break out of the loop.
5060
5061 for(... ; ... ; ...) {}
5062 for(... in ... ) {}
5063 while(...) { }
5064 do { } while(...)
5065
5066 Returns logical OR of END_* flags."
5067 (let ((rv (js2-end-check (js2-loop-node-body node)))
5068 (condition (cond
5069 ((js2-while-node-p node)
5070 (js2-while-node-condition node))
5071 ((js2-do-node-p node)
5072 (js2-do-node-condition node))
5073 ((js2-for-node-p node)
5074 (js2-for-node-condition node)))))
5075
5076 ;; check to see if the loop condition is always true
5077 (if (and condition
5078 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5079 (js2-clear-flag rv js2-END_DROPS_OFF))
5080
5081 ;; look for effect of breaks
5082 (js2-set-flag rv (js2-node-get-prop node
5083 'CONTROL_BLOCK_PROP
5084 js2-END_UNREACHED))
5085 rv))
5086
5087 (defun js2-end-check-block (node)
5088 "A general block of code is examined statement by statement.
5089 If any statement (even a compound one) returns in all branches, then
5090 subsequent statements are not examined.
5091 Returns logical OR of END_* flags."
5092 (let* ((rv js2-END_DROPS_OFF)
5093 (kids (js2-block-node-kids node))
5094 (n (car kids)))
5095 ;; Check each statment. If the statement can continue onto the next
5096 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5097 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5098 (js2-clear-flag rv js2-END_DROPS_OFF)
5099 (js2-set-flag rv (js2-end-check n))
5100 (setq kids (cdr kids)
5101 n (car kids)))
5102 rv))
5103
5104 (defun js2-end-check-label (node)
5105 "A labeled statement implies that there may be a break to the label.
5106 The function processes the labeled statement and then checks the
5107 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5108 particular label.
5109 Returns logical OR of END_* flags."
5110 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5111 (logior rv (js2-node-get-prop node
5112 'CONTROL_BLOCK_PROP
5113 js2-END_UNREACHED))))
5114
5115 (defun js2-end-check-break (node)
5116 "When a break is encountered annotate the statement being broken
5117 out of by setting its CONTROL_BLOCK_PROP property.
5118 Returns logical OR of END_* flags."
5119 (and (js2-break-node-target node)
5120 (js2-node-set-prop (js2-break-node-target node)
5121 'CONTROL_BLOCK_PROP
5122 js2-END_DROPS_OFF))
5123 js2-END_UNREACHED)
5124
5125 (defun js2-end-check (node)
5126 "Examine the body of a function, doing a basic reachability analysis.
5127 Returns a combination of flags END_* flags that indicate
5128 how the function execution can terminate. These constitute only the
5129 pessimistic set of termination conditions. It is possible that at
5130 runtime certain code paths will never be actually taken. Hence this
5131 analysis will flag errors in cases where there may not be errors.
5132 Returns logical OR of END_* flags"
5133 (let (kid)
5134 (cond
5135 ((js2-break-node-p node)
5136 (js2-end-check-break node))
5137 ((js2-expr-stmt-node-p node)
5138 (if (setq kid (js2-expr-stmt-node-expr node))
5139 (js2-end-check kid)
5140 js2-END_DROPS_OFF))
5141 ((or (js2-continue-node-p node)
5142 (js2-throw-node-p node))
5143 js2-END_UNREACHED)
5144 ((js2-return-node-p node)
5145 (if (setq kid (js2-return-node-retval node))
5146 js2-END_RETURNS_VALUE
5147 js2-END_RETURNS))
5148 ((js2-loop-node-p node)
5149 (js2-end-check-loop node))
5150 ((js2-switch-node-p node)
5151 (js2-end-check-switch node))
5152 ((js2-labeled-stmt-node-p node)
5153 (js2-end-check-label node))
5154 ((js2-if-node-p node)
5155 (js2-end-check-if node))
5156 ((js2-try-node-p node)
5157 (js2-end-check-try node))
5158 ((js2-block-node-p node)
5159 (if (null (js2-block-node-kids node))
5160 js2-END_DROPS_OFF
5161 (js2-end-check-block node)))
5162 ((js2-yield-node-p node)
5163 js2-END_YIELDS)
5164 (t
5165 js2-END_DROPS_OFF))))
5166
5167 (defun js2-always-defined-boolean-p (node)
5168 "Check if NODE always evaluates to true or false in boolean context.
5169 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5170 nor always false."
5171 (let ((tt (js2-node-type node))
5172 num)
5173 (cond
5174 ((or (= tt js2-FALSE) (= tt js2-NULL))
5175 'ALWAYS_FALSE)
5176 ((= tt js2-TRUE)
5177 'ALWAYS_TRUE)
5178 ((= tt js2-NUMBER)
5179 (setq num (js2-number-node-num-value node))
5180 (if (and (not (eq num 0.0e+NaN))
5181 (not (zerop num)))
5182 'ALWAYS_TRUE
5183 'ALWAYS_FALSE))
5184 (t
5185 nil))))
5186
5187 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5188 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5189
5190 (defvar js2-tokens nil
5191 "List of all defined token names.") ; initialized in `js2-token-names'
5192
5193 (defconst js2-token-names
5194 (let* ((names (make-vector js2-num-tokens -1))
5195 (case-fold-search nil) ; only match js2-UPPER_CASE
5196 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5197 (loop for sym in syms
5198 for i from 0
5199 do
5200 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5201 (not (boundp sym)))
5202 (aset names (symbol-value sym) ; code, e.g. 152
5203 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5204 (push sym js2-tokens)))
5205 names)
5206 "Vector mapping int values to token string names, sans `js2-' prefix.")
5207
5208 (defun js2-token-name (tok)
5209 "Return a string name for TOK, a token symbol or code.
5210 Signals an error if it's not a recognized token."
5211 (let ((code tok))
5212 (if (symbolp tok)
5213 (setq code (symbol-value tok)))
5214 (if (eq code -1)
5215 "ERROR"
5216 (if (and (numberp code)
5217 (not (minusp code))
5218 (< code js2-num-tokens))
5219 (aref js2-token-names code)
5220 (error "Invalid token: %s" code)))))
5221
5222 (defsubst js2-token-sym (tok)
5223 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5224 (intern (js2-token-name tok)))
5225
5226 (defconst js2-token-codes
5227 (let ((table (make-hash-table :test 'eq :size 256)))
5228 (loop for name across js2-token-names
5229 for sym = (intern (concat "js2-" name))
5230 do
5231 (puthash sym (symbol-value sym) table))
5232 ;; clean up a few that are "wrong" in Rhino's token codes
5233 (puthash 'js2-DELETE js2-DELPROP table)
5234 table)
5235 "Hashtable mapping token symbols to their bytecodes.")
5236
5237 (defsubst js2-token-code (sym)
5238 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5239 (or (gethash sym js2-token-codes)
5240 (error "Invalid token symbol: %s " sym))) ; signal code bug
5241
5242 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5243 (setq js2-token-end js2-ts-cursor)
5244 (js2-report-error msg nil
5245 (or beg js2-token-beg)
5246 (or len (- js2-token-end js2-token-beg)))
5247 (unless no-throw
5248 (throw 'return js2-ERROR)))
5249
5250 (defsubst js2-get-string-from-buffer ()
5251 "Reverse the char accumulator and return it as a string."
5252 (setq js2-token-end js2-ts-cursor)
5253 (if js2-ts-string-buffer
5254 (apply #'string (nreverse js2-ts-string-buffer))
5255 ""))
5256
5257 ;; TODO: could potentially avoid a lot of consing by allocating a
5258 ;; char buffer the way Rhino does.
5259 (defsubst js2-add-to-string (c)
5260 (push c js2-ts-string-buffer))
5261
5262 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5263 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5264 ;; any other character: when it's not part of the current token, we
5265 ;; unget it, allowing it to be read again by the following call.
5266 (defsubst js2-unget-char ()
5267 (decf js2-ts-cursor))
5268
5269 ;; Rhino distinguishes \r and \n line endings. We don't need to
5270 ;; because we only scan from Emacs buffers, which always use \n.
5271 (defsubst js2-get-char ()
5272 "Read and return the next character from the input buffer.
5273 Increments `js2-ts-lineno' if the return value is a newline char.
5274 Updates `js2-ts-cursor' to the point after the returned char.
5275 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5276 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5277 (let (c)
5278 ;; check for end of buffer
5279 (if (>= js2-ts-cursor (point-max))
5280 (setq js2-ts-hit-eof t
5281 js2-ts-cursor (1+ js2-ts-cursor)
5282 c js2-EOF_CHAR) ; return value
5283 ;; otherwise read next char
5284 (setq c (char-before (incf js2-ts-cursor)))
5285 ;; if we read a newline, update counters
5286 (if (= c ?\n)
5287 (setq js2-ts-line-start js2-ts-cursor
5288 js2-ts-lineno (1+ js2-ts-lineno)))
5289 ;; TODO: skip over format characters
5290 c)))
5291
5292 (defsubst js2-read-unicode-escape ()
5293 "Read a \\uNNNN sequence from the input.
5294 Assumes the ?\ and ?u have already been read.
5295 Returns the unicode character, or nil if it wasn't a valid character.
5296 Doesn't change the values of any scanner variables."
5297 ;; I really wish I knew a better way to do this, but I can't
5298 ;; find the Emacs function that takes a 16-bit int and converts
5299 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5300 ;; Have to first check that it's 4 hex characters or it may stop
5301 ;; the read early.
5302 (ignore-errors
5303 (let ((s (buffer-substring-no-properties js2-ts-cursor
5304 (+ 4 js2-ts-cursor))))
5305 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5306 (read (concat "?\\u" s))))))
5307
5308 (defsubst js2-match-char (test)
5309 "Consume and return next character if it matches TEST, a character.
5310 Returns nil and consumes nothing if TEST is not the next character."
5311 (let ((c (js2-get-char)))
5312 (if (eq c test)
5313 t
5314 (js2-unget-char)
5315 nil)))
5316
5317 (defsubst js2-peek-char ()
5318 (prog1
5319 (js2-get-char)
5320 (js2-unget-char)))
5321
5322 (defsubst js2-java-identifier-start-p (c)
5323 (or
5324 (memq c '(?$ ?_))
5325 (js2-char-uppercase-p c)
5326 (js2-char-lowercase-p c)))
5327
5328 (defsubst js2-java-identifier-part-p (c)
5329 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5330 ;; TODO: make me Unicode-friendly. See comments above.
5331 (or
5332 (memq c '(?$ ?_))
5333 (js2-char-uppercase-p c)
5334 (js2-char-lowercase-p c)
5335 (and (>= c ?0) (<= c ?9))))
5336
5337 (defsubst js2-alpha-p (c)
5338 (cond ((and (<= ?A c) (<= c ?Z)) t)
5339 ((and (<= ?a c) (<= c ?z)) t)
5340 (t nil)))
5341
5342 (defsubst js2-digit-p (c)
5343 (and (<= ?0 c) (<= c ?9)))
5344
5345 (defsubst js2-js-space-p (c)
5346 (if (<= c 127)
5347 (memq c '(#x20 #x9 #xB #xC #xD))
5348 (or
5349 (eq c #xA0)
5350 ;; TODO: change this nil to check for Unicode space character
5351 nil)))
5352
5353 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5354
5355 (defsubst js2-skip-line ()
5356 "Skip to end of line"
5357 (let (c)
5358 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5359 (js2-unget-char)
5360 (setq js2-token-end js2-ts-cursor)))
5361
5362 (defun js2-init-scanner (&optional buf line)
5363 "Create token stream for BUF starting on LINE.
5364 BUF defaults to current-buffer and line defaults to 1.
5365
5366 A buffer can only have one scanner active at a time, which yields
5367 dramatically simpler code than using a defstruct. If you need to
5368 have simultaneous scanners in a buffer, copy the regions to scan
5369 into temp buffers."
5370 (save-excursion
5371 (when buf
5372 (set-buffer buf))
5373 (setq js2-ts-dirty-line nil
5374 js2-ts-regexp-flags nil
5375 js2-ts-string ""
5376 js2-ts-number nil
5377 js2-ts-hit-eof nil
5378 js2-ts-line-start 0
5379 js2-ts-lineno (or line 1)
5380 js2-ts-line-end-char -1
5381 js2-ts-cursor (point-min)
5382 js2-ts-is-xml-attribute nil
5383 js2-ts-xml-is-tag-content nil
5384 js2-ts-xml-open-tags-count 0
5385 js2-ts-string-buffer nil)))
5386
5387 ;; This function uses the cached op, string and number fields in
5388 ;; TokenStream; if getToken has been called since the passed token
5389 ;; was scanned, the op or string printed may be incorrect.
5390 (defun js2-token-to-string (token)
5391 ;; Not sure where this function is used in Rhino. Not tested.
5392 (if (not js2-debug-print-trees)
5393 ""
5394 (let ((name (js2-token-name token)))
5395 (cond
5396 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5397 (concat name " `" js2-ts-string "'"))
5398 ((eq token js2-NUMBER)
5399 (format "NUMBER %g" js2-ts-number))
5400 (t
5401 name)))))
5402
5403 (defconst js2-keywords
5404 '(break
5405 case catch const continue
5406 debugger default delete do
5407 else enum
5408 false finally for function
5409 if in instanceof import
5410 let
5411 new null
5412 return
5413 switch
5414 this throw true try typeof
5415 var void
5416 while with
5417 yield))
5418
5419 ;; Token names aren't exactly the same as the keywords, unfortunately.
5420 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5421 (defconst js2-kwd-tokens
5422 (let ((table (make-vector js2-num-tokens nil))
5423 (tokens
5424 (list js2-BREAK
5425 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5426 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5427 js2-ELSE
5428 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5429 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5430 js2-LET
5431 js2-NEW js2-NULL
5432 js2-RETURN
5433 js2-SWITCH
5434 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5435 js2-VAR
5436 js2-WHILE js2-WITH
5437 js2-YIELD)))
5438 (dolist (i tokens)
5439 (aset table i 'font-lock-keyword-face))
5440 (aset table js2-STRING 'font-lock-string-face)
5441 (aset table js2-REGEXP 'font-lock-string-face)
5442 (aset table js2-COMMENT 'font-lock-comment-face)
5443 (aset table js2-THIS 'font-lock-builtin-face)
5444 (aset table js2-VOID 'font-lock-constant-face)
5445 (aset table js2-NULL 'font-lock-constant-face)
5446 (aset table js2-TRUE 'font-lock-constant-face)
5447 (aset table js2-FALSE 'font-lock-constant-face)
5448 table)
5449 "Vector whose values are non-nil for tokens that are keywords.
5450 The values are default faces to use for highlighting the keywords.")
5451
5452 (defconst js2-reserved-words
5453 '(abstract
5454 boolean byte
5455 char class
5456 double
5457 enum export extends
5458 final float
5459 goto
5460 implements import int interface
5461 long
5462 native
5463 package private protected public
5464 short static super synchronized
5465 throws transient
5466 volatile))
5467
5468 (defconst js2-keyword-names
5469 (let ((table (make-hash-table :test 'equal)))
5470 (loop for k in js2-keywords
5471 do (puthash
5472 (symbol-name k) ; instanceof
5473 (intern (concat "js2-"
5474 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5475 table))
5476 table)
5477 "JavaScript keywords by name, mapped to their symbols.")
5478
5479 (defconst js2-reserved-word-names
5480 (let ((table (make-hash-table :test 'equal)))
5481 (loop for k in js2-reserved-words
5482 do
5483 (puthash (symbol-name k) 'js2-RESERVED table))
5484 table)
5485 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5486
5487 (defsubst js2-collect-string (buf)
5488 "Convert BUF, a list of chars, to a string.
5489 Reverses BUF before converting."
5490 (cond
5491 ((stringp buf)
5492 buf)
5493 ((null buf) ; for emacs21 compat
5494 "")
5495 (t
5496 (if buf
5497 (apply #'string (nreverse buf))
5498 ""))))
5499
5500 (defun js2-string-to-keyword (s)
5501 "Return token for S, a string, if S is a keyword or reserved word.
5502 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5503 (or (gethash s js2-keyword-names)
5504 (gethash s js2-reserved-word-names)))
5505
5506 (defsubst js2-ts-set-char-token-bounds ()
5507 "Used when next token is one character."
5508 (setq js2-token-beg (1- js2-ts-cursor)
5509 js2-token-end js2-ts-cursor))
5510
5511 (defsubst js2-ts-return (token)
5512 "Return an N-character TOKEN from `js2-get-token'.
5513 Updates `js2-token-end' accordingly."
5514 (setq js2-token-end js2-ts-cursor)
5515 (throw 'return token))
5516
5517 (defsubst js2-x-digit-to-int (c accumulator)
5518 "Build up a hex number.
5519 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5520 corresponding number. Otherwise return -1."
5521 (catch 'return
5522 (catch 'check
5523 ;; Use 0..9 < A..Z < a..z
5524 (cond
5525 ((<= c ?9)
5526 (decf c ?0)
5527 (if (<= 0 c)
5528 (throw 'check nil)))
5529 ((<= c ?F)
5530 (when (<= ?A c)
5531 (decf c (- ?A 10))
5532 (throw 'check nil)))
5533 ((<= c ?f)
5534 (when (<= ?a c)
5535 (decf c (- ?a 10))
5536 (throw 'check nil))))
5537 (throw 'return -1))
5538 (logior c (lsh accumulator 4))))
5539
5540 (defun js2-get-token ()
5541 "Return next JavaScript token, an int such as js2-RETURN."
5542 (let (c
5543 c1
5544 identifier-start
5545 is-unicode-escape-start
5546 contains-escape
5547 escape-val
5548 escape-start
5549 str
5550 result
5551 base
5552 is-integer
5553 quote-char
5554 val
5555 look-for-slash
5556 continue)
5557 (catch 'return
5558 (while t
5559 ;; Eat whitespace, possibly sensitive to newlines.
5560 (setq continue t)
5561 (while continue
5562 (setq c (js2-get-char))
5563 (cond
5564 ((eq c js2-EOF_CHAR)
5565 (js2-ts-set-char-token-bounds)
5566 (throw 'return js2-EOF))
5567 ((eq c ?\n)
5568 (js2-ts-set-char-token-bounds)
5569 (setq js2-ts-dirty-line nil)
5570 (throw 'return js2-EOL))
5571 ((not (js2-js-space-p c))
5572 (if (/= c ?-) ; in case end of HTML comment
5573 (setq js2-ts-dirty-line t))
5574 (setq continue nil))))
5575 ;; Assume the token will be 1 char - fixed up below.
5576 (js2-ts-set-char-token-bounds)
5577 (when (eq c ?@)
5578 (throw 'return js2-XMLATTR))
5579 ;; identifier/keyword/instanceof?
5580 ;; watch out for starting with a <backslash>
5581 (cond
5582 ((eq c ?\\)
5583 (setq c (js2-get-char))
5584 (if (eq c ?u)
5585 (setq identifier-start t
5586 is-unicode-escape-start t
5587 js2-ts-string-buffer nil)
5588 (setq identifier-start nil)
5589 (js2-unget-char)
5590 (setq c ?\\)))
5591 (t
5592 (when (setq identifier-start (js2-java-identifier-start-p c))
5593 (setq js2-ts-string-buffer nil)
5594 (js2-add-to-string c))))
5595 (when identifier-start
5596 (setq contains-escape is-unicode-escape-start)
5597 (catch 'break
5598 (while t
5599 (if is-unicode-escape-start
5600 ;; strictly speaking we should probably push-back
5601 ;; all the bad characters if the <backslash>uXXXX
5602 ;; sequence is malformed. But since there isn't a
5603 ;; correct context(is there?) for a bad Unicode
5604 ;; escape sequence in an identifier, we can report
5605 ;; an error here.
5606 (progn
5607 (setq escape-val 0)
5608 (dotimes (i 4)
5609 (setq c (js2-get-char)
5610 escape-val (js2-x-digit-to-int c escape-val))
5611 ;; Next check takes care of c < 0 and bad escape
5612 (if (minusp escape-val)
5613 (throw 'break nil)))
5614 (if (minusp escape-val)
5615 (js2-report-scan-error "msg.invalid.escape" t))
5616 (js2-add-to-string escape-val)
5617 (setq is-unicode-escape-start nil))
5618 (setq c (js2-get-char))
5619 (cond
5620 ((eq c ?\\)
5621 (setq c (js2-get-char))
5622 (if (eq c ?u)
5623 (setq is-unicode-escape-start t
5624 contains-escape t)
5625 (js2-report-scan-error "msg.illegal.character" t)))
5626 (t
5627 (if (or (eq c js2-EOF_CHAR)
5628 (not (js2-java-identifier-part-p c)))
5629 (throw 'break nil))
5630 (js2-add-to-string c))))))
5631 (js2-unget-char)
5632 (setq str (js2-get-string-from-buffer))
5633 (unless contains-escape
5634 ;; OPT we shouldn't have to make a string (object!) to
5635 ;; check if it's a keyword.
5636 ;; Return the corresponding token if it's a keyword
5637 (when (setq result (js2-string-to-keyword str))
5638 (if (and (< js2-language-version 170)
5639 (memq result '(js2-LET js2-YIELD)))
5640 ;; LET and YIELD are tokens only in 1.7 and later
5641 (setq result 'js2-NAME))
5642 (if (not (eq result 'js2-RESERVED))
5643 (throw 'return (js2-token-code result)))
5644 (js2-report-warning "msg.reserved.keyword" str)))
5645 ;; If we want to intern these as Rhino does, just use (intern str)
5646 (setq js2-ts-string str)
5647 (throw 'return js2-NAME)) ; end identifier/kwd check
5648 ;; is it a number?
5649 (when (or (js2-digit-p c)
5650 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5651 (setq js2-ts-string-buffer nil
5652 base 10)
5653 (when (eq c ?0)
5654 (setq c (js2-get-char))
5655 (cond
5656 ((or (eq c ?x) (eq c ?X))
5657 (setq base 16)
5658 (setq c (js2-get-char)))
5659 ((js2-digit-p c)
5660 (setq base 8))
5661 (t
5662 (js2-add-to-string ?0))))
5663 (if (eq base 16)
5664 (while (<= 0 (js2-x-digit-to-int c 0))
5665 (js2-add-to-string c)
5666 (setq c (js2-get-char)))
5667 (while (and (<= ?0 c) (<= c ?9))
5668 ;; We permit 08 and 09 as decimal numbers, which
5669 ;; makes our behavior a superset of the ECMA
5670 ;; numeric grammar. We might not always be so
5671 ;; permissive, so we warn about it.
5672 (when (and (eq base 8) (>= c ?8))
5673 (js2-report-warning "msg.bad.octal.literal"
5674 (if (eq c ?8) "8" "9"))
5675 (setq base 10))
5676 (js2-add-to-string c)
5677 (setq c (js2-get-char))))
5678 (setq is-integer t)
5679 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5680 (setq is-integer nil)
5681 (when (eq c ?.)
5682 (loop do
5683 (js2-add-to-string c)
5684 (setq c (js2-get-char))
5685 while (js2-digit-p c)))
5686 (when (memq c '(?e ?E))
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 (when (memq c '(?+ ?-))
5690 (js2-add-to-string c)
5691 (setq c (js2-get-char)))
5692 (unless (js2-digit-p c)
5693 (js2-report-scan-error "msg.missing.exponent" t))
5694 (loop do
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char))
5697 while (js2-digit-p c))))
5698 (js2-unget-char)
5699 (setq js2-ts-string (js2-get-string-from-buffer)
5700 js2-ts-number
5701 (if (and (eq base 10) (not is-integer))
5702 (string-to-number js2-ts-string)
5703 ;; TODO: call runtime number-parser. Some of it is in
5704 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5705 (string-to-number js2-ts-string)))
5706 (throw 'return js2-NUMBER))
5707 ;; is it a string?
5708 (when (memq c '(?\" ?\'))
5709 ;; We attempt to accumulate a string the fast way, by
5710 ;; building it directly out of the reader. But if there
5711 ;; are any escaped characters in the string, we revert to
5712 ;; building it out of a string buffer.
5713 (setq quote-char c
5714 js2-ts-string-buffer nil
5715 c (js2-get-char))
5716 (catch 'break
5717 (while (/= c quote-char)
5718 (catch 'continue
5719 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5720 (js2-unget-char)
5721 (setq js2-token-end js2-ts-cursor)
5722 (js2-report-error "msg.unterminated.string.lit")
5723 (throw 'return js2-STRING))
5724 (when (eq c ?\\)
5725 ;; We've hit an escaped character
5726 (setq c (js2-get-char))
5727 (case c
5728 (?b (setq c ?\b))
5729 (?f (setq c ?\f))
5730 (?n (setq c ?\n))
5731 (?r (setq c ?\r))
5732 (?t (setq c ?\t))
5733 (?v (setq c ?\v))
5734 (?u
5735 (setq c1 (js2-read-unicode-escape))
5736 (if js2-parse-ide-mode
5737 (if c1
5738 (progn
5739 ;; just copy the string in IDE-mode
5740 (js2-add-to-string ?\\)
5741 (js2-add-to-string ?u)
5742 (dotimes (i 3)
5743 (js2-add-to-string (js2-get-char)))
5744 (setq c (js2-get-char))) ; added at end of loop
5745 ;; flag it as an invalid escape
5746 (js2-report-warning "msg.invalid.escape"
5747 nil (- js2-ts-cursor 2) 6))
5748 ;; Get 4 hex digits; if the u escape is not
5749 ;; followed by 4 hex digits, use 'u' + the
5750 ;; literal character sequence that follows.
5751 (js2-add-to-string ?u)
5752 (setq escape-val 0)
5753 (dotimes (i 4)
5754 (setq c (js2-get-char)
5755 escape-val (js2-x-digit-to-int c escape-val))
5756 (if (minusp escape-val)
5757 (throw 'continue nil))
5758 (js2-add-to-string c))
5759 ;; prepare for replace of stored 'u' sequence by escape value
5760 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5761 c escape-val)))
5762 (?x
5763 ;; Get 2 hex digits, defaulting to 'x'+literal
5764 ;; sequence, as above.
5765 (setq c (js2-get-char)
5766 escape-val (js2-x-digit-to-int c 0))
5767 (if (minusp escape-val)
5768 (progn
5769 (js2-add-to-string ?x)
5770 (throw 'continue nil))
5771 (setq c1 c
5772 c (js2-get-char)
5773 escape-val (js2-x-digit-to-int c escape-val))
5774 (if (minusp escape-val)
5775 (progn
5776 (js2-add-to-string ?x)
5777 (js2-add-to-string c1)
5778 (throw 'continue nil))
5779 ;; got 2 hex digits
5780 (setq c escape-val))))
5781 (?\n
5782 ;; Remove line terminator after escape to follow
5783 ;; SpiderMonkey and C/C++
5784 (setq c (js2-get-char))
5785 (throw 'continue nil))
5786 (t
5787 (when (and (<= ?0 c) (< c ?8))
5788 (setq val (- c ?0)
5789 c (js2-get-char))
5790 (when (and (<= ?0 c) (< c ?8))
5791 (setq val (- (+ (* 8 val) c) ?0)
5792 c (js2-get-char))
5793 (when (and (<= ?0 c)
5794 (< c ?8)
5795 (< val #o37))
5796 ;; c is 3rd char of octal sequence only
5797 ;; if the resulting val <= 0377
5798 (setq val (- (+ (* 8 val) c) ?0)
5799 c (js2-get-char))))
5800 (js2-unget-char)
5801 (setq c val)))))
5802 (js2-add-to-string c)
5803 (setq c (js2-get-char)))))
5804 (setq js2-ts-string (js2-get-string-from-buffer))
5805 (throw 'return js2-STRING))
5806 (case c
5807 (?\;
5808 (throw 'return js2-SEMI))
5809 (?\[
5810 (throw 'return js2-LB))
5811 (?\]
5812 (throw 'return js2-RB))
5813 (?{
5814 (throw 'return js2-LC))
5815 (?}
5816 (throw 'return js2-RC))
5817 (?\(
5818 (throw 'return js2-LP))
5819 (?\)
5820 (throw 'return js2-RP))
5821 (?,
5822 (throw 'return js2-COMMA))
5823 (??
5824 (throw 'return js2-HOOK))
5825 (?:
5826 (if (js2-match-char ?:)
5827 (js2-ts-return js2-COLONCOLON)
5828 (throw 'return js2-COLON)))
5829 (?.
5830 (if (js2-match-char ?.)
5831 (js2-ts-return js2-DOTDOT)
5832 (if (js2-match-char ?\()
5833 (js2-ts-return js2-DOTQUERY)
5834 (throw 'return js2-DOT))))
5835 (?|
5836 (if (js2-match-char ?|)
5837 (throw 'return js2-OR)
5838 (if (js2-match-char ?=)
5839 (js2-ts-return js2-ASSIGN_BITOR)
5840 (throw 'return js2-BITOR))))
5841 (?^
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_BITOR)
5844 (throw 'return js2-BITXOR)))
5845 (?&
5846 (if (js2-match-char ?&)
5847 (throw 'return js2-AND)
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-ASSIGN_BITAND)
5850 (throw 'return js2-BITAND))))
5851 (?=
5852 (if (js2-match-char ?=)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-SHEQ)
5855 (throw 'return js2-EQ))
5856 (throw 'return js2-ASSIGN)))
5857 (?!
5858 (if (js2-match-char ?=)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-SHNE)
5861 (js2-ts-return js2-NE))
5862 (throw 'return js2-NOT)))
5863 (?<
5864 ;; NB:treat HTML begin-comment as comment-till-eol
5865 (when (js2-match-char ?!)
5866 (when (js2-match-char ?-)
5867 (when (js2-match-char ?-)
5868 (js2-skip-line)
5869 (setq js2-ts-comment-type 'html)
5870 (throw 'return js2-COMMENT)))
5871 (js2-unget-char))
5872 (if (js2-match-char ?<)
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_LSH)
5875 (js2-ts-return js2-LSH))
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-LE)
5878 (throw 'return js2-LT))))
5879 (?>
5880 (if (js2-match-char ?>)
5881 (if (js2-match-char ?>)
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-ASSIGN_URSH)
5884 (js2-ts-return js2-URSH))
5885 (if (js2-match-char ?=)
5886 (js2-ts-return js2-ASSIGN_RSH)
5887 (js2-ts-return js2-RSH)))
5888 (if (js2-match-char ?=)
5889 (js2-ts-return js2-GE)
5890 (throw 'return js2-GT))))
5891 (?*
5892 (if (js2-match-char ?=)
5893 (js2-ts-return js2-ASSIGN_MUL)
5894 (throw 'return js2-MUL)))
5895 (?/
5896 ;; is it a // comment?
5897 (when (js2-match-char ?/)
5898 (setq js2-token-beg (- js2-ts-cursor 2))
5899 (js2-skip-line)
5900 (setq js2-ts-comment-type 'line)
5901 ;; include newline so highlighting goes to end of window
5902 (incf js2-token-end)
5903 (throw 'return js2-COMMENT))
5904 ;; is it a /* comment?
5905 (when (js2-match-char ?*)
5906 (setq look-for-slash nil
5907 js2-token-beg (- js2-ts-cursor 2)
5908 js2-ts-comment-type
5909 (if (js2-match-char ?*)
5910 (progn
5911 (setq look-for-slash t)
5912 'jsdoc)
5913 'block))
5914 (while t
5915 (setq c (js2-get-char))
5916 (cond
5917 ((eq c js2-EOF_CHAR)
5918 (setq js2-token-end (1- js2-ts-cursor))
5919 (js2-report-error "msg.unterminated.comment")
5920 (throw 'return js2-COMMENT))
5921 ((eq c ?*)
5922 (setq look-for-slash t))
5923 ((eq c ?/)
5924 (if look-for-slash
5925 (js2-ts-return js2-COMMENT)))
5926 (t
5927 (setq look-for-slash nil
5928 js2-token-end js2-ts-cursor)))))
5929 (if (js2-match-char ?=)
5930 (js2-ts-return js2-ASSIGN_DIV)
5931 (throw 'return js2-DIV)))
5932 (?#
5933 (when js2-skip-preprocessor-directives
5934 (js2-skip-line)
5935 (setq js2-ts-comment-type 'preprocessor
5936 js2-token-end js2-ts-cursor)
5937 (throw 'return js2-COMMENT))
5938 (throw 'return js2-ERROR))
5939 (?%
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_MOD)
5942 (throw 'return js2-MOD)))
5943 (?~
5944 (throw 'return js2-BITNOT))
5945 (?+
5946 (if (js2-match-char ?=)
5947 (js2-ts-return js2-ASSIGN_ADD)
5948 (if (js2-match-char ?+)
5949 (js2-ts-return js2-INC)
5950 (throw 'return js2-ADD))))
5951 (?-
5952 (cond
5953 ((js2-match-char ?=)
5954 (setq c js2-ASSIGN_SUB))
5955 ((js2-match-char ?-)
5956 (unless js2-ts-dirty-line
5957 ;; treat HTML end-comment after possible whitespace
5958 ;; after line start as comment-until-eol
5959 (when (js2-match-char ?>)
5960 (js2-skip-line)
5961 (setq js2-ts-comment-type 'html)
5962 (throw 'return js2-COMMENT)))
5963 (setq c js2-DEC))
5964 (t
5965 (setq c js2-SUB)))
5966 (setq js2-ts-dirty-line t)
5967 (js2-ts-return c))
5968 (otherwise
5969 (js2-report-scan-error "msg.illegal.character")))))))
5970
5971 (defun js2-read-regexp (start-token)
5972 "Called by parser when it gets / or /= in literal context."
5973 (let (c
5974 err
5975 in-class ; inside a '[' .. ']' character-class
5976 flags
5977 (continue t))
5978 (setq js2-token-beg js2-ts-cursor
5979 js2-ts-string-buffer nil
5980 js2-ts-regexp-flags nil)
5981 (if (eq start-token js2-ASSIGN_DIV)
5982 ;; mis-scanned /=
5983 (js2-add-to-string ?=)
5984 (if (not (eq start-token js2-DIV))
5985 (error "failed assertion")))
5986 (while (and (not err)
5987 (or (/= (setq c (js2-get-char)) ?/)
5988 in-class))
5989 (cond
5990 ((or (= c ?\n)
5991 (= c js2-EOF_CHAR))
5992 (setq js2-token-end (1- js2-ts-cursor)
5993 err t
5994 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5995 (js2-report-error "msg.unterminated.re.lit"))
5996 (t (cond
5997 ((= c ?\\)
5998 (js2-add-to-string c)
5999 (setq c (js2-get-char)))
6000 ((= c ?\[)
6001 (setq in-class t))
6002 ((= c ?\])
6003 (setq in-class nil)))
6004 (js2-add-to-string c))))
6005 (unless err
6006 (while continue
6007 (cond
6008 ((js2-match-char ?g)
6009 (push ?g flags))
6010 ((js2-match-char ?i)
6011 (push ?i flags))
6012 ((js2-match-char ?m)
6013 (push ?m flags))
6014 (t
6015 (setq continue nil))))
6016 (if (js2-alpha-p (js2-peek-char))
6017 (js2-report-scan-error "msg.invalid.re.flag" t
6018 js2-ts-cursor 1))
6019 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6020 js2-ts-regexp-flags (js2-collect-string flags)
6021 js2-token-end js2-ts-cursor)
6022 ;; tell `parse-partial-sexp' to ignore this range of chars
6023 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6024
6025 (defun js2-get-first-xml-token ()
6026 (setq js2-ts-xml-open-tags-count 0
6027 js2-ts-is-xml-attribute nil
6028 js2-ts-xml-is-tag-content nil)
6029 (js2-unget-char)
6030 (js2-get-next-xml-token))
6031
6032 (defsubst js2-xml-discard-string ()
6033 "Throw away the string in progress and flag an XML parse error."
6034 (setq js2-ts-string-buffer nil
6035 js2-ts-string nil)
6036 (js2-report-scan-error "msg.XML.bad.form" t))
6037
6038 (defun js2-get-next-xml-token ()
6039 (setq js2-ts-string-buffer nil ; for recording the XML
6040 js2-token-beg js2-ts-cursor)
6041 (let (c result)
6042 (setq result
6043 (catch 'return
6044 (while t
6045 (setq c (js2-get-char))
6046 (cond
6047 ((= c js2-EOF_CHAR)
6048 (throw 'return js2-ERROR))
6049 (js2-ts-xml-is-tag-content
6050 (case c
6051 (?>
6052 (js2-add-to-string c)
6053 (setq js2-ts-xml-is-tag-content nil
6054 js2-ts-is-xml-attribute nil))
6055 (?/
6056 (js2-add-to-string c)
6057 (when (eq ?> (js2-peek-char))
6058 (setq c (js2-get-char))
6059 (js2-add-to-string c)
6060 (setq js2-ts-xml-is-tag-content nil)
6061 (decf js2-ts-xml-open-tags-count)))
6062 (?{
6063 (js2-unget-char)
6064 (setq js2-ts-string (js2-get-string-from-buffer))
6065 (throw 'return js2-XML))
6066 ((?\' ?\")
6067 (js2-add-to-string c)
6068 (unless (js2-read-quoted-string c)
6069 (throw 'return js2-ERROR)))
6070 (?=
6071 (js2-add-to-string c)
6072 (setq js2-ts-is-xml-attribute t))
6073 ((? ?\t ?\r ?\n)
6074 (js2-add-to-string c))
6075 (t
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute nil)))
6078 (when (and (not js2-ts-xml-is-tag-content)
6079 (zerop js2-ts-xml-open-tags-count))
6080 (setq js2-ts-string (js2-get-string-from-buffer))
6081 (throw 'return js2-XMLEND)))
6082 (t
6083 ;; else not tag content
6084 (case c
6085 (?<
6086 (js2-add-to-string c)
6087 (setq c (js2-peek-char))
6088 (case c
6089 (?!
6090 (setq c (js2-get-char)) ;; skip !
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 (if (eq c ?-)
6098 (progn
6099 (js2-add-to-string c)
6100 (unless (js2-read-xml-comment)
6101 (throw 'return js2-ERROR)))
6102 (js2-xml-discard-string)
6103 (throw 'return js2-ERROR)))
6104 (?\[
6105 (setq c (js2-get-char)) ;; skip [
6106 (js2-add-to-string c)
6107 (if (and (= (js2-get-char) ?C)
6108 (= (js2-get-char) ?D)
6109 (= (js2-get-char) ?A)
6110 (= (js2-get-char) ?T)
6111 (= (js2-get-char) ?A)
6112 (= (js2-get-char) ?\[))
6113 (progn
6114 (js2-add-to-string ?C)
6115 (js2-add-to-string ?D)
6116 (js2-add-to-string ?A)
6117 (js2-add-to-string ?T)
6118 (js2-add-to-string ?A)
6119 (js2-add-to-string ?\[)
6120 (unless (js2-read-cdata)
6121 (throw 'return js2-ERROR)))
6122 (js2-xml-discard-string)
6123 (throw 'return js2-ERROR)))
6124 (t
6125 (unless (js2-read-entity)
6126 (throw 'return js2-ERROR))))
6127 ;; allow bare CDATA section
6128 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6129 (when (zerop js2-ts-xml-open-tags-count)
6130 (throw 'return js2-XMLEND)))
6131 (??
6132 (setq c (js2-get-char)) ;; skip ?
6133 (js2-add-to-string c)
6134 (unless (js2-read-PI)
6135 (throw 'return js2-ERROR)))
6136 (?/
6137 ;; end tag
6138 (setq c (js2-get-char)) ;; skip /
6139 (js2-add-to-string c)
6140 (when (zerop js2-ts-xml-open-tags-count)
6141 (js2-xml-discard-string)
6142 (throw 'return js2-ERROR))
6143 (setq js2-ts-xml-is-tag-content t)
6144 (decf js2-ts-xml-open-tags-count))
6145 (t
6146 ;; start tag
6147 (setq js2-ts-xml-is-tag-content t)
6148 (incf js2-ts-xml-open-tags-count))))
6149 (?{
6150 (js2-unget-char)
6151 (setq js2-ts-string (js2-get-string-from-buffer))
6152 (throw 'return js2-XML))
6153 (t
6154 (js2-add-to-string c))))))))
6155 (setq js2-token-end js2-ts-cursor)
6156 result))
6157
6158 (defun js2-read-quoted-string (quote)
6159 (let (c)
6160 (catch 'return
6161 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6162 (js2-add-to-string c)
6163 (if (eq c quote)
6164 (throw 'return t)))
6165 (js2-xml-discard-string) ;; throw away string in progress
6166 nil)))
6167
6168 (defun js2-read-xml-comment ()
6169 (let ((c (js2-get-char)))
6170 (catch 'return
6171 (while (/= c js2-EOF_CHAR)
6172 (catch 'continue
6173 (js2-add-to-string c)
6174 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6175 (setq c (js2-get-char))
6176 (js2-add-to-string c)
6177 (if (eq (js2-peek-char) ?>)
6178 (progn
6179 (setq c (js2-get-char)) ;; skip >
6180 (js2-add-to-string c)
6181 (throw 'return t))
6182 (throw 'continue nil)))
6183 (setq c (js2-get-char))))
6184 (js2-xml-discard-string)
6185 nil)))
6186
6187 (defun js2-read-cdata ()
6188 (let ((c (js2-get-char)))
6189 (catch 'return
6190 (while (/= c js2-EOF_CHAR)
6191 (catch 'continue
6192 (js2-add-to-string c)
6193 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6194 (setq c (js2-get-char))
6195 (js2-add-to-string c)
6196 (if (eq (js2-peek-char) ?>)
6197 (progn
6198 (setq c (js2-get-char)) ;; Skip >
6199 (js2-add-to-string c)
6200 (throw 'return t))
6201 (throw 'continue nil)))
6202 (setq c (js2-get-char))))
6203 (js2-xml-discard-string)
6204 nil)))
6205
6206 (defun js2-read-entity ()
6207 (let ((decl-tags 1)
6208 c)
6209 (catch 'return
6210 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6211 (js2-add-to-string c)
6212 (case c
6213 (?<
6214 (incf decl-tags))
6215 (?>
6216 (decf decl-tags)
6217 (if (zerop decl-tags)
6218 (throw 'return t)))))
6219 (js2-xml-discard-string)
6220 nil)))
6221
6222 (defun js2-read-PI ()
6223 "Scan an XML processing instruction."
6224 (let (c)
6225 (catch 'return
6226 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6227 (js2-add-to-string c)
6228 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6229 (setq c (js2-get-char)) ;; Skip >
6230 (js2-add-to-string c)
6231 (throw 'return t)))
6232 (js2-xml-discard-string)
6233 nil)))
6234
6235 (defun js2-scanner-get-line ()
6236 "Return the text of the current scan line."
6237 (buffer-substring (point-at-bol) (point-at-eol)))
6238
6239 ;;; Highlighting
6240
6241 (defsubst js2-set-face (beg end face &optional record)
6242 "Fontify a region. If RECORD is non-nil, record for later."
6243 (when (plusp js2-highlight-level)
6244 (setq beg (min (point-max) beg)
6245 beg (max (point-min) beg)
6246 end (min (point-max) end)
6247 end (max (point-min) end))
6248 (if record
6249 (push (list beg end face) js2-mode-fontifications)
6250 (put-text-property beg end 'face face))))
6251
6252 (defsubst js2-set-kid-face (pos kid len face)
6253 "Set-face on a child node.
6254 POS is absolute buffer position of parent.
6255 KID is the child node.
6256 LEN is the length to fontify.
6257 FACE is the face to fontify with."
6258 (js2-set-face (+ pos (js2-node-pos kid))
6259 (+ pos (js2-node-pos kid) (js2-node-len kid))
6260 face))
6261
6262 (defsubst js2-fontify-kwd (start length)
6263 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6264
6265 (defsubst js2-clear-face (beg end)
6266 (remove-text-properties beg end '(face nil
6267 help-echo nil
6268 point-entered nil
6269 c-in-sws nil)))
6270
6271 (defconst js2-ecma-global-props
6272 (concat "^"
6273 (regexp-opt
6274 '("Infinity" "NaN" "undefined" "arguments") t)
6275 "$")
6276 "Value properties of the Ecma-262 Global Object.
6277 Shown at or above `js2-highlight-level' 2.")
6278
6279 ;; might want to add the name "arguments" to this list?
6280 (defconst js2-ecma-object-props
6281 (concat "^"
6282 (regexp-opt
6283 '("prototype" "__proto__" "__parent__") t)
6284 "$")
6285 "Value properties of the Ecma-262 Object constructor.
6286 Shown at or above `js2-highlight-level' 2.")
6287
6288 (defconst js2-ecma-global-funcs
6289 (concat
6290 "^"
6291 (regexp-opt
6292 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6293 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6294 "$")
6295 "Function properties of the Ecma-262 Global object.
6296 Shown at or above `js2-highlight-level' 2.")
6297
6298 (defconst js2-ecma-number-props
6299 (concat "^"
6300 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6301 "NEGATIVE_INFINITY"
6302 "POSITIVE_INFINITY") t)
6303 "$")
6304 "Properties of the Ecma-262 Number constructor.
6305 Shown at or above `js2-highlight-level' 2.")
6306
6307 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6308 "Properties of the Ecma-262 Date constructor.
6309 Shown at or above `js2-highlight-level' 2.")
6310
6311 (defconst js2-ecma-math-props
6312 (concat "^"
6313 (regexp-opt
6314 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6315 t)
6316 "$")
6317 "Properties of the Ecma-262 Math object.
6318 Shown at or above `js2-highlight-level' 2.")
6319
6320 (defconst js2-ecma-math-funcs
6321 (concat "^"
6322 (regexp-opt
6323 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6324 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6325 "$")
6326 "Function properties of the Ecma-262 Math object.
6327 Shown at or above `js2-highlight-level' 2.")
6328
6329 (defconst js2-ecma-function-props
6330 (concat
6331 "^"
6332 (regexp-opt
6333 '(;; properties of the Object prototype object
6334 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6335 "toLocaleString" "toString" "valueOf"
6336 ;; properties of the Function prototype object
6337 "apply" "call"
6338 ;; properties of the Array prototype object
6339 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6340 "splice" "unshift"
6341 ;; properties of the String prototype object
6342 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6343 "localeCompare" "match" "replace" "search" "split" "substring"
6344 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6345 "toUpperCase"
6346 ;; properties of the Number prototype object
6347 "toExponential" "toFixed" "toPrecision"
6348 ;; properties of the Date prototype object
6349 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6350 "getMinutes" "getMonth" "getSeconds" "getTime"
6351 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6352 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6353 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6354 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6355 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6356 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6357 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6358 "toTimeString" "toUTCString"
6359 ;; properties of the RegExp prototype object
6360 "exec" "test"
6361 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6362 "toSource" "__defineGetter__" "__defineSetter__"
6363 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6364 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6365 t)
6366 "$")
6367 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6368 Shown at or above `js2-highlight-level' 3.")
6369
6370 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6371 (let ((target-name (and target
6372 (js2-name-node-p target)
6373 (js2-name-node-name target)))
6374 (prop-name (if prop (js2-name-node-name prop)))
6375 (level1 (>= js2-highlight-level 1))
6376 (level2 (>= js2-highlight-level 2))
6377 (level3 (>= js2-highlight-level 3))
6378 pos
6379 face)
6380 (when level2
6381 (if call-p
6382 (cond
6383 ((and target prop)
6384 (cond
6385 ((and level3 (string-match js2-ecma-function-props prop-name))
6386 (setq face 'font-lock-builtin-face))
6387 ((and target-name prop)
6388 (cond
6389 ((string= target-name "Date")
6390 (if (string-match js2-ecma-date-props prop-name)
6391 (setq face 'font-lock-builtin-face)))
6392 ((string= target-name "Math")
6393 (if (string-match js2-ecma-math-funcs prop-name)
6394 (setq face 'font-lock-builtin-face)))))))
6395 (prop
6396 (if (string-match js2-ecma-global-funcs prop-name)
6397 (setq face 'font-lock-builtin-face))))
6398 (cond
6399 ((and target prop)
6400 (cond
6401 ((string= target-name "Number")
6402 (if (string-match js2-ecma-number-props prop-name)
6403 (setq face 'font-lock-constant-face)))
6404 ((string= target-name "Math")
6405 (if (string-match js2-ecma-math-props prop-name)
6406 (setq face 'font-lock-constant-face)))))
6407 (prop
6408 (if (string-match js2-ecma-object-props prop-name)
6409 (setq face 'font-lock-constant-face)))))
6410 (when face
6411 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6412 (js2-node-pos prop))) ; relative
6413 (+ pos (js2-node-len prop))
6414 face)))))
6415
6416 (defun js2-parse-highlight-member-expr-node (node)
6417 "Perform syntax highlighting of EcmaScript built-in properties.
6418 The variable `js2-highlight-level' governs this highighting."
6419 (let (face target prop name pos end parent call-p callee)
6420 (cond
6421 ;; case 1: simple name, e.g. foo
6422 ((js2-name-node-p node)
6423 (setq name (js2-name-node-name node))
6424 ;; possible for name to be nil in rare cases - saw it when
6425 ;; running js2-mode on an elisp buffer. Might as well try to
6426 ;; make it so js2-mode never barfs.
6427 (when name
6428 (setq face (if (string-match js2-ecma-global-props name)
6429 'font-lock-constant-face))
6430 (when face
6431 (setq pos (js2-node-pos node)
6432 end (+ pos (js2-node-len node)))
6433 (js2-set-face pos end face))))
6434 ;; case 2: property access or function call
6435 ((or (js2-prop-get-node-p node)
6436 ;; highlight function call if expr is a prop-get node
6437 ;; or a plain name (i.e. unqualified function call)
6438 (and (setq call-p (js2-call-node-p node))
6439 (setq callee (js2-call-node-target node)) ; separate setq!
6440 (or (js2-prop-get-node-p callee)
6441 (js2-name-node-p callee))))
6442 (setq parent node
6443 node (if call-p callee node))
6444 (if (and call-p (js2-name-node-p callee))
6445 (setq prop callee)
6446 (setq target (js2-prop-get-node-left node)
6447 prop (js2-prop-get-node-right node)))
6448 (cond
6449 ((js2-name-node-p target)
6450 (if (js2-name-node-p prop)
6451 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6452 (js2-parse-highlight-prop-get parent target prop call-p)
6453 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6454 (js2-parse-highlight-prop-get parent target nil call-p)))
6455 ((js2-name-node-p prop)
6456 ;; case 2c: complex target, simple name, e.g. x[y].bar
6457 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6458
6459 (defun js2-parse-highlight-member-expr-fn-name (expr)
6460 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6461 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6462 We currently only handle the case where the last component is a prop-get
6463 of a simple name. Called before EXPR has a parent node."
6464 (let (pos
6465 (name (and (js2-prop-get-node-p expr)
6466 (js2-prop-get-node-right expr))))
6467 (when (js2-name-node-p name)
6468 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6469 (js2-node-pos name)))
6470 (+ pos (js2-node-len name))
6471 'font-lock-function-name-face
6472 'record))))
6473
6474 ;; source: http://jsdoc.sourceforge.net/
6475 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6476 ;; allows type specifications, and needs work before entering the wild.
6477
6478 (defconst js2-jsdoc-param-tag-regexp
6479 (concat "^\\s-*\\*+\\s-*\\(@"
6480 "\\(?:param\\|argument\\)"
6481 "\\)"
6482 "\\s-*\\({[^}]+}\\)?" ; optional type
6483 "\\s-*\\[?\\([a-zA-Z0-9_$]+\\)?\\]?" ; name
6484 "\\>")
6485 "Matches jsdoc tags with optional type and optional param name.")
6486
6487 (defconst js2-jsdoc-typed-tag-regexp
6488 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6489 (regexp-opt
6490 '("enum"
6491 "extends"
6492 "field"
6493 "id"
6494 "implements"
6495 "lends"
6496 "mods"
6497 "requires"
6498 "return"
6499 "returns"
6500 "throw"
6501 "throws"))
6502 "\\)\\)\\s-*\\({[^}]+}\\)?")
6503 "Matches jsdoc tags with optional type.")
6504
6505 (defconst js2-jsdoc-arg-tag-regexp
6506 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6507 (regexp-opt
6508 '("alias"
6509 "augments"
6510 "borrows"
6511 "bug"
6512 "base"
6513 "config"
6514 "default"
6515 "define"
6516 "exception"
6517 "function"
6518 "member"
6519 "memberOf"
6520 "name"
6521 "namespace"
6522 "property"
6523 "since"
6524 "suppress"
6525 "this"
6526 "throws"
6527 "type"
6528 "version"))
6529 "\\)\\)\\s-+\\([^ \t]+\\)")
6530 "Matches jsdoc tags with a single argument.")
6531
6532 (defconst js2-jsdoc-empty-tag-regexp
6533 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6534 (regexp-opt
6535 '("addon"
6536 "author"
6537 "class"
6538 "const"
6539 "constant"
6540 "constructor"
6541 "constructs"
6542 "deprecated"
6543 "desc"
6544 "description"
6545 "event"
6546 "example"
6547 "exec"
6548 "export"
6549 "fileoverview"
6550 "final"
6551 "function"
6552 "hidden"
6553 "ignore"
6554 "implicitCast"
6555 "inheritDoc"
6556 "inner"
6557 "interface"
6558 "license"
6559 "noalias"
6560 "noshadow"
6561 "notypecheck"
6562 "override"
6563 "owner"
6564 "preserve"
6565 "preserveTry"
6566 "private"
6567 "protected"
6568 "public"
6569 "static"
6570 "supported"
6571 ))
6572 "\\)\\)\\s-*")
6573 "Matches empty jsdoc tags.")
6574
6575 (defconst js2-jsdoc-link-tag-regexp
6576 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6577 "Matches a jsdoc link or code tag.")
6578
6579 (defconst js2-jsdoc-see-tag-regexp
6580 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6581 "Matches a jsdoc @see tag.")
6582
6583 (defconst js2-jsdoc-html-tag-regexp
6584 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6585 "Matches a simple (no attributes) html start- or end-tag.")
6586
6587 (defsubst js2-jsdoc-highlight-helper ()
6588 (js2-set-face (match-beginning 1)
6589 (match-end 1)
6590 'js2-jsdoc-tag-face)
6591 (if (match-beginning 2)
6592 (if (save-excursion
6593 (goto-char (match-beginning 2))
6594 (= (char-after) ?{))
6595 (js2-set-face (1+ (match-beginning 2))
6596 (1- (match-end 2))
6597 'js2-jsdoc-type-face)
6598 (js2-set-face (match-beginning 2)
6599 (match-end 2)
6600 'js2-jsdoc-value-face)))
6601 (if (match-beginning 3)
6602 (js2-set-face (match-beginning 3)
6603 (match-end 3)
6604 'js2-jsdoc-value-face)))
6605
6606 (defun js2-highlight-jsdoc (ast)
6607 "Highlight doc comment tags."
6608 (let ((comments (js2-ast-root-comments ast))
6609 beg end)
6610 (save-excursion
6611 (dolist (node comments)
6612 (when (eq (js2-comment-node-format node) 'jsdoc)
6613 (setq beg (js2-node-abs-pos node)
6614 end (+ beg (js2-node-len node)))
6615 (save-restriction
6616 (narrow-to-region beg end)
6617 (dolist (re (list js2-jsdoc-param-tag-regexp
6618 js2-jsdoc-typed-tag-regexp
6619 js2-jsdoc-arg-tag-regexp
6620 js2-jsdoc-link-tag-regexp
6621 js2-jsdoc-see-tag-regexp
6622 js2-jsdoc-empty-tag-regexp))
6623 (goto-char beg)
6624 (while (re-search-forward re nil t)
6625 (js2-jsdoc-highlight-helper)))
6626 ;; simple highlighting for html tags
6627 (goto-char beg)
6628 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6629 (js2-set-face (match-beginning 1)
6630 (match-end 1)
6631 'js2-jsdoc-html-tag-delimiter-face)
6632 (js2-set-face (match-beginning 2)
6633 (match-end 2)
6634 'js2-jsdoc-html-tag-name-face)
6635 (js2-set-face (match-beginning 3)
6636 (match-end 3)
6637 'js2-jsdoc-html-tag-delimiter-face))))))))
6638
6639 (defun js2-highlight-assign-targets (node left right)
6640 "Highlight function properties and external variables."
6641 (let (leftpos end name)
6642 ;; highlight vars and props assigned function values
6643 (when (js2-function-node-p right)
6644 (cond
6645 ;; var foo = function() {...}
6646 ((js2-name-node-p left)
6647 (setq name left))
6648 ;; foo.bar.baz = function() {...}
6649 ((and (js2-prop-get-node-p left)
6650 (js2-name-node-p (js2-prop-get-node-right left)))
6651 (setq name (js2-prop-get-node-right left))))
6652 (when name
6653 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6654 (+ leftpos (js2-node-len name))
6655 'font-lock-function-name-face
6656 'record)))))
6657
6658 (defun js2-record-name-node (node)
6659 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6660 later. NODE must be a name node."
6661 (let (leftpos end)
6662 (push (list node js2-current-scope
6663 (setq leftpos (js2-node-abs-pos node))
6664 (setq end (+ leftpos (js2-node-len node))))
6665 js2-recorded-identifiers)))
6666
6667 (defun js2-highlight-undeclared-vars ()
6668 "After entire parse is finished, look for undeclared variable references.
6669 We have to wait until entire buffer is parsed, since JavaScript permits var
6670 decls to occur after they're used.
6671
6672 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6673 it is considered declared."
6674 (let (name)
6675 (dolist (entry js2-recorded-identifiers)
6676 (destructuring-bind (name-node scope pos end) entry
6677 (setq name (js2-name-node-name name-node))
6678 (unless (or (member name js2-global-externs)
6679 (member name js2-default-externs)
6680 (member name js2-additional-externs)
6681 (js2-get-defining-scope scope name))
6682 (js2-set-face pos end 'js2-external-variable-face 'record)
6683 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6684 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6685 (setq js2-recorded-identifiers nil)))
6686
6687 ;;; IMenu support
6688
6689 ;; We currently only support imenu, but eventually should support speedbar and
6690 ;; possibly other browsing mechanisms.
6691
6692 ;; The basic strategy is to identify function assignment targets of the form
6693 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6694 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6695 ;; for imenu after parsing is finished.
6696
6697 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6698 ;; JavaScript, and the general problem is undecidable. However, several forms
6699 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6700 ;; include:
6701
6702 ;; function foo() -- function declaration
6703 ;; foo = function() -- function expression assigned to variable
6704 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6705 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6706 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6707 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6708 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6709 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6710 ;; function foo() {function bar() {...}} -- nested function
6711 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6712
6713 ;; This list boils down to a few forms that can be combined recursively.
6714 ;; Top-level named function declarations include both the left-hand (name)
6715 ;; and the right-hand (function value) expressions needed to produce an imenu
6716 ;; entry. The other "right-hand" forms we need to look for are:
6717 ;; - functions declared as props/getters/setters in object literals
6718 ;; - nested named function declarations
6719 ;; The "left-hand" expressions that functions can be assigned to include:
6720 ;; - local/global variables
6721 ;; - nested property-get expressions like a.b.c.d
6722 ;; - element gets like foo[10] or foo['bar'] where the index
6723 ;; expression can be trivially converted to a property name. They
6724 ;; effectively then become property gets.
6725
6726 ;; All the different definition types are canonicalized into the form
6727 ;; foo.bar.baz = position-of-function-keyword
6728
6729 ;; We need to build a trie-like structure for imenu. As an example,
6730 ;; consider the following JavaScript code:
6731
6732 ;; a = function() {...} // function at position 5
6733 ;; b = function() {...} // function at position 25
6734 ;; foo = function() {...} // function at position 100
6735 ;; foo.bar = function() {...} // function at position 200
6736 ;; foo.bar.baz = function() {...} // function at position 300
6737 ;; foo.bar.zab = function() {...} // function at position 400
6738
6739 ;; During parsing we accumulate an entry for each definition in
6740 ;; the variable `js2-imenu-recorder', like so:
6741
6742 ;; '((fn a 5)
6743 ;; (fn b 25)
6744 ;; (fn foo 100)
6745 ;; (fn foo bar 200)
6746 ;; (fn foo bar baz 300)
6747 ;; (fn foo bar zab 400))
6748
6749 ;; Where 'fn' is the respective function node.
6750 ;; After parsing these entries are merged into this alist-trie:
6751
6752 ;; '((a . 1)
6753 ;; (b . 2)
6754 ;; (foo (<definition> . 3)
6755 ;; (bar (<definition> . 6)
6756 ;; (baz . 100)
6757 ;; (zab . 200))))
6758
6759 ;; Note the wacky need for a <definition> name. The token can be anything
6760 ;; that isn't a valid JavaScript identifier, because you might make foo
6761 ;; a function and then start setting properties on it that are also functions.
6762
6763 (defsubst js2-prop-node-name (node)
6764 "Return the name of a node that may be a property-get/property-name.
6765 If NODE is not a valid name-node, string-node or integral number-node,
6766 returns nil. Otherwise returns the string name/value of the node."
6767 (cond
6768 ((js2-name-node-p node)
6769 (js2-name-node-name node))
6770 ((js2-string-node-p node)
6771 (js2-string-node-value node))
6772 ((and (js2-number-node-p node)
6773 (string-match "^[0-9]+$" (js2-number-node-value node)))
6774 (js2-number-node-value node))
6775 ((js2-this-node-p node)
6776 "this")))
6777
6778 (defsubst js2-node-qname-component (node)
6779 "Return the name of this node, if it contributes to a qname.
6780 Returns nil if the node doesn't contribute."
6781 (copy-sequence
6782 (or (js2-prop-node-name node)
6783 (if (and (js2-function-node-p node)
6784 (js2-function-node-name node))
6785 (js2-name-node-name (js2-function-node-name node))))))
6786
6787 (defsubst js2-record-imenu-entry (fn-node qname pos)
6788 "Add an entry to `js2-imenu-recorder'.
6789 FN-NODE should be the current item's function node.
6790
6791 Associate FN-NODE with its QNAME for later lookup.
6792 This is used in postprocessing the chain list. For each chain, we find
6793 the parent function, look up its qname, then prepend a copy of it to the chain."
6794 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6795 (unless js2-imenu-function-map
6796 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6797 (puthash fn-node qname js2-imenu-function-map))
6798
6799 (defun js2-record-imenu-functions (node &optional var)
6800 "Record function definitions for imenu.
6801 NODE is a function node or an object literal.
6802 VAR, if non-nil, is the expression that NODE is being assigned to."
6803 (when js2-parse-ide-mode
6804 (let ((fun-p (js2-function-node-p node))
6805 qname left fname-node pos)
6806 (cond
6807 ;; non-anonymous function declaration?
6808 ((and fun-p
6809 (not var)
6810 (setq fname-node (js2-function-node-name node)))
6811 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6812 ;; for remaining forms, compute left-side tree branch first
6813 ((and var (setq qname (js2-compute-nested-prop-get var)))
6814 (cond
6815 ;; foo.bar.baz = function
6816 (fun-p
6817 (js2-record-imenu-entry node qname (js2-node-pos node)))
6818 ;; foo.bar.baz = object-literal
6819 ;; look for nested functions: {a: {b: function() {...} }}
6820 ((js2-object-node-p node)
6821 ;; Node position here is still absolute, since the parser
6822 ;; passes the assignment target and value expressions
6823 ;; to us before they are added as children of the assignment node.
6824 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6825
6826 (defun js2-compute-nested-prop-get (node)
6827 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6828 component nodes as a list. Otherwise return nil. Element-gets are treated
6829 as property-gets if the index expression is a string, or a positive integer."
6830 (let (left right head)
6831 (cond
6832 ((or (js2-name-node-p node)
6833 (js2-this-node-p node))
6834 (list node))
6835 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6836 ((js2-prop-get-node-p node) ; foo.bar
6837 (setq left (js2-prop-get-node-left node)
6838 right (js2-prop-get-node-right node))
6839 (if (setq head (js2-compute-nested-prop-get left))
6840 (nconc head (list right))))
6841 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6842 (setq left (js2-elem-get-node-target node)
6843 right (js2-elem-get-node-element node))
6844 (if (or (js2-string-node-p right) ; ['bar']
6845 (and (js2-number-node-p right) ; [10]
6846 (string-match "^[0-9]+$"
6847 (js2-number-node-value right))))
6848 (if (setq head (js2-compute-nested-prop-get left))
6849 (nconc head (list right))))))))
6850
6851 (defun js2-record-object-literal (node qname pos)
6852 "Recursively process an object literal looking for functions.
6853 NODE is an object literal that is the right-hand child of an assignment
6854 expression. QNAME is a list of nodes representing the assignment target,
6855 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6856 POS is the absolute position of the node.
6857 We do a depth-first traversal of NODE. For any functions we find,
6858 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6859 (let (left right prop-qname)
6860 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6861 (let ((left (js2-infix-node-left e))
6862 ;; Element positions are relative to the parent position.
6863 (pos (+ pos (js2-node-pos e))))
6864 (cond
6865 ;; foo: function() {...}
6866 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6867 (when (js2-prop-node-name left)
6868 ;; As a policy decision, we record the position of the property,
6869 ;; not the position of the `function' keyword, since the property
6870 ;; is effectively the name of the function.
6871 (js2-record-imenu-entry right (append qname (list left)) pos)))
6872 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6873 ((js2-object-node-p right)
6874 (js2-record-object-literal right
6875 (append qname (list (js2-infix-node-left e)))
6876 (+ pos (js2-node-pos right)))))))))
6877
6878 (defsubst js2-node-top-level-decl-p (node)
6879 "Return t if NODE's name is defined in the top-level scope.
6880 Also returns t if NODE's name is not defined in any scope, since it implies
6881 that it's an external variable, which must also be in the top-level scope."
6882 (let* ((name (js2-prop-node-name node))
6883 (this-scope (js2-node-get-enclosing-scope node))
6884 defining-scope)
6885 (cond
6886 ((js2-this-node-p node)
6887 nil)
6888 ((null this-scope)
6889 t)
6890 ((setq defining-scope (js2-get-defining-scope this-scope name))
6891 (js2-ast-root-p defining-scope))
6892 (t t))))
6893
6894 (defsubst js2-wrapper-function-p (node)
6895 "Returns t if NODE is a function expression that's immediately invoked.
6896 NODE must be `js2-function-node'."
6897 (let ((parent (js2-node-parent node)))
6898 (or
6899 ;; function(){...}();
6900 (js2-call-node-p parent)
6901 (and (js2-paren-node-p parent)
6902 ;; (function(){...})();
6903 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6904 ;; (function(){...}).call(this);
6905 (and (js2-prop-get-node-p parent)
6906 (member (js2-name-node-name (js2-prop-get-node-right parent))
6907 '("call" "apply"))
6908 (js2-call-node-p (js2-node-parent parent))))))))
6909
6910 (defun js2-browse-postprocess-chains (entries)
6911 "Modify function-declaration name chains after parsing finishes.
6912 Some of the information is only available after the parse tree is complete.
6913 For instance, processing a nested scope requires a parent function node."
6914 (let (result head fn current-fn parent-qname qname p elem)
6915 (dolist (entry entries)
6916 ;; function node goes first
6917 (destructuring-bind (current-fn &rest chain) entry
6918 ;; examine its defining scope;
6919 ;; if top-level/external, keep as-is
6920 (if (js2-node-top-level-decl-p (car chain))
6921 (push chain result)
6922 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6923 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6924 (when (eq parent-qname 'not-found)
6925 ;; anonymous function expressions are not recorded
6926 ;; during the parse, so we need to handle this case here
6927 (setq parent-qname
6928 (if (js2-wrapper-function-p fn)
6929 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6930 (if (js2-ast-root-p grandparent)
6931 nil
6932 (gethash grandparent js2-imenu-function-map 'skip)))
6933 'skip))
6934 (puthash fn parent-qname js2-imenu-function-map))
6935 (unless (eq parent-qname 'skip)
6936 ;; prefix parent fn qname to this chain.
6937 (let ((qname (append parent-qname chain)))
6938 (puthash current-fn (butlast qname) js2-imenu-function-map)
6939 (push qname result)))))))
6940 ;; finally replace each node in each chain with its name.
6941 (dolist (chain result)
6942 (setq p chain)
6943 (while p
6944 (if (js2-node-p (setq elem (car p)))
6945 (setcar p (js2-node-qname-component elem)))
6946 (setq p (cdr p))))
6947 result))
6948
6949 ;; Merge name chains into a trie-like tree structure of nested lists.
6950 ;; To simplify construction of the trie, we first build it out using the rule
6951 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6952 ;; [key, num-or-list]. The second element can be a number; if so, this key
6953 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6954 ;; associated with the key at this level.) Otherwise the second element is
6955 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6956 ;; a simple recursive formulation.
6957 ;;
6958 ;; js2-mode is building the data structure for imenu. The imenu documentation
6959 ;; claims that it's the structure above, but in practice it wants the children
6960 ;; at the same list level as the key for that level, which is how I've drawn
6961 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6962 ;; list wrapper around the children at each level.
6963 ;;
6964 ;; A completed nested imenu-alist entry looks like this:
6965 ;; '(("foo"
6966 ;; ("<definition>" . 7)
6967 ;; ("bar"
6968 ;; ("a" . 40)
6969 ;; ("b" . 60))))
6970 ;;
6971 ;; In particular, the documentation for `imenu--index-alist' says that
6972 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6973 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6974
6975 (defsubst js2-treeify (lst)
6976 "Convert (a b c d) to (a ((b ((c d)))))"
6977 (if (null (cddr lst)) ; list length <= 2
6978 lst
6979 (list (car lst) (list (js2-treeify (cdr lst))))))
6980
6981 (defun js2-build-alist-trie (chains trie)
6982 "Merge declaration name chains into a trie-like alist structure for imenu.
6983 CHAINS is the qname chain list produced during parsing. TRIE is a
6984 list of elements built up so far."
6985 (let (head tail pos branch kids)
6986 (dolist (chain chains)
6987 (setq head (car chain)
6988 tail (cdr chain)
6989 pos (if (numberp (car tail)) (car tail))
6990 branch (js2-find-if (lambda (n)
6991 (string= (car n) head))
6992 trie)
6993 kids (second branch))
6994 (cond
6995 ;; case 1: this key isn't in the trie yet
6996 ((null branch)
6997 (if trie
6998 (setcdr (last trie) (list (js2-treeify chain)))
6999 (setq trie (list (js2-treeify chain)))))
7000 ;; case 2: key is present with a single number entry: replace w/ list
7001 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7002 ;; ("<definition>" 20)))
7003 ((numberp kids)
7004 (setcar (cdr branch)
7005 (list (list "<definition-1>" kids)
7006 (if pos
7007 (list "<definition-2>" pos)
7008 (js2-treeify tail)))))
7009 ;; case 3: key is there (with kids), and we're a number entry
7010 (pos
7011 (setcdr (last kids)
7012 (list
7013 (list (format "<definition-%d>"
7014 (1+ (loop for kid in kids
7015 count (eq ?< (aref (car kid) 0)))))
7016 pos))))
7017 ;; case 4: key is there with kids, need to merge in our chain
7018 (t
7019 (js2-build-alist-trie (list tail) kids))))
7020 trie))
7021
7022 (defun js2-flatten-trie (trie)
7023 "Convert TRIE to imenu-format.
7024 Recurses through nodes, and for each one whose second element is a list,
7025 appends the list's flattened elements to the current element. Also
7026 changes the tails into conses. For instance, this pre-flattened trie
7027
7028 '(a ((b 20)
7029 (c ((d 30)
7030 (e 40)))))
7031
7032 becomes
7033
7034 '(a (b . 20)
7035 (c (d . 30)
7036 (e . 40)))
7037
7038 Note that the root of the trie has no key, just a list of chains.
7039 This is also true for the value of any key with multiple children,
7040 e.g. key 'c' in the example above."
7041 (cond
7042 ((listp (car trie))
7043 (mapcar #'js2-flatten-trie trie))
7044 (t
7045 (if (numberp (second trie))
7046 (cons (car trie) (second trie))
7047 ;; else pop list and append its kids
7048 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7049
7050 (defun js2-build-imenu-index ()
7051 "Turn `js2-imenu-recorder' into an imenu data structure."
7052 (unless (eq js2-imenu-recorder 'empty)
7053 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7054 (result (js2-build-alist-trie chains nil)))
7055 (js2-flatten-trie result))))
7056
7057 (defun js2-test-print-chains (chains)
7058 "Print a list of qname chains.
7059 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7060 i.e. one or more nodes, and an integer position as the list tail."
7061 (mapconcat (lambda (chain)
7062 (concat "("
7063 (mapconcat (lambda (elem)
7064 (if (js2-node-p elem)
7065 (or (js2-node-qname-component elem)
7066 "nil")
7067 (number-to-string elem)))
7068 chain
7069 " ")
7070 ")"))
7071 chains
7072 "\n"))
7073
7074 ;;; Parser
7075
7076 (defconst js2-version "1.8.0"
7077 "Version of JavaScript supported, plus minor js2 version.")
7078
7079 (defmacro js2-record-face (face)
7080 "Record a style run of FACE for the current token."
7081 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7082
7083 (defsubst js2-node-end (n)
7084 "Computes the absolute end of node N.
7085 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7086 is only true until the node is added to its parent; i.e., while parsing."
7087 (+ (js2-node-pos n)
7088 (js2-node-len n)))
7089
7090 (defsubst js2-record-comment ()
7091 "Record a comment in `js2-scanned-comments'."
7092 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7093 :format js2-ts-comment-type)
7094 js2-scanned-comments)
7095 (when js2-parse-ide-mode
7096 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7097 'font-lock-doc-face
7098 'font-lock-comment-face))
7099 (when (memq js2-ts-comment-type '(html preprocessor))
7100 ;; Tell cc-engine the bounds of the comment.
7101 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7102
7103 ;; This function is called depressingly often, so it should be fast.
7104 ;; Most of the time it's looking at the same token it peeked before.
7105 (defsubst js2-peek-token ()
7106 "Returns the next token without consuming it.
7107 If previous token was consumed, calls scanner to get new token.
7108 If previous token was -not- consumed, returns it (idempotent).
7109
7110 This function will not return a newline (js2-EOL) - instead, it
7111 gobbles newlines until it finds a non-newline token, and flags
7112 that token as appearing just after a newline.
7113
7114 This function will also not return a js2-COMMENT. Instead, it
7115 records comments found in `js2-scanned-comments'. If the token
7116 returned by this function immediately follows a jsdoc comment,
7117 the token is flagged as such.
7118
7119 Note that this function always returned the un-flagged token!
7120 The flags, if any, are saved in `js2-current-flagged-token'."
7121 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7122 js2-current-token ; most common case - return already-peeked token
7123 (let ((tt (js2-get-token)) ; call scanner
7124 saw-eol
7125 face)
7126 ;; process comments and whitespace
7127 (while (or (= tt js2-EOL)
7128 (= tt js2-COMMENT))
7129 (if (= tt js2-EOL)
7130 (setq saw-eol t)
7131 (setq saw-eol nil)
7132 (if js2-record-comments
7133 (js2-record-comment)))
7134 (setq tt (js2-get-token))) ; call scanner
7135 (setq js2-current-token tt
7136 js2-current-flagged-token (if saw-eol
7137 (logior tt js2-ti-after-eol)
7138 tt))
7139 ;; perform lexical fontification as soon as token is scanned
7140 (when js2-parse-ide-mode
7141 (cond
7142 ((minusp tt)
7143 (js2-record-face 'js2-error-face))
7144 ((setq face (aref js2-kwd-tokens tt))
7145 (js2-record-face face))
7146 ((and (= tt js2-NAME)
7147 (equal js2-ts-string "undefined"))
7148 (js2-record-face 'font-lock-constant-face))))
7149 tt))) ; return unflagged token
7150
7151 (defsubst js2-peek-flagged-token ()
7152 "Returns the current token along with any flags set for it."
7153 (js2-peek-token)
7154 js2-current-flagged-token)
7155
7156 (defsubst js2-consume-token ()
7157 (setq js2-current-flagged-token js2-EOF))
7158
7159 (defsubst js2-next-token ()
7160 (prog1
7161 (js2-peek-token)
7162 (js2-consume-token)))
7163
7164 (defsubst js2-next-flagged-token ()
7165 (js2-peek-token)
7166 (prog1 js2-current-flagged-token
7167 (js2-consume-token)))
7168
7169 (defsubst js2-match-token (match)
7170 "Consume and return t if next token matches MATCH, a bytecode.
7171 Returns nil and consumes nothing if MATCH is not the next token."
7172 (if (/= (js2-peek-token) match)
7173 nil
7174 (js2-consume-token)
7175 t))
7176
7177 (defsubst js2-valid-prop-name-token (tt)
7178 (or (= tt js2-NAME)
7179 (and js2-allow-keywords-as-property-names
7180 (plusp tt)
7181 (aref js2-kwd-tokens tt))))
7182
7183 (defsubst js2-match-prop-name ()
7184 "Consume token and return t if next token is a valid property name.
7185 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7186 is non-nil and it's a keyword token."
7187 (if (js2-valid-prop-name-token (js2-peek-token))
7188 (progn
7189 (js2-consume-token)
7190 t)
7191 nil))
7192
7193 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7194 (if (js2-match-prop-name)
7195 t
7196 (js2-report-error msg-id nil pos len)
7197 nil))
7198
7199 (defsubst js2-peek-token-or-eol ()
7200 "Return js2-EOL if the current token immediately follows a newline.
7201 Else returns the current token. Used in situations where we don't
7202 consider certain token types valid if they are preceded by a newline.
7203 One example is the postfix ++ or -- operator, which has to be on the
7204 same line as its operand."
7205 (let ((tt (js2-peek-token)))
7206 ;; Check for last peeked token flags
7207 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7208 js2-EOL
7209 tt)))
7210
7211 (defsubst js2-set-check-for-label ()
7212 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7213 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7214
7215 (defsubst js2-must-match (token msg-id &optional pos len)
7216 "Match next token to token code TOKEN, or record a syntax error.
7217 MSG-ID is the error message to report if the match fails.
7218 Returns t on match, nil if no match."
7219 (if (js2-match-token token)
7220 t
7221 (js2-report-error msg-id nil pos len)
7222 nil))
7223
7224 (defsubst js2-inside-function ()
7225 (plusp js2-nesting-of-function))
7226
7227 (defsubst js2-set-requires-activation ()
7228 (if (js2-function-node-p js2-current-script-or-fn)
7229 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7230
7231 (defsubst js2-check-activation-name (name token)
7232 (when (js2-inside-function)
7233 ;; skip language-version 1.2 check from Rhino
7234 (if (or (string= "arguments" name)
7235 (and js2-compiler-activation-names ; only used in codegen
7236 (gethash name js2-compiler-activation-names)))
7237 (js2-set-requires-activation))))
7238
7239 (defsubst js2-set-is-generator ()
7240 (if (js2-function-node-p js2-current-script-or-fn)
7241 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7242
7243 (defsubst js2-must-have-xml ()
7244 (unless js2-compiler-xml-available
7245 (js2-report-error "msg.XML.not.available")))
7246
7247 (defsubst js2-push-scope (scope)
7248 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7249 (assert (js2-scope-p scope))
7250 (assert (null (js2-scope-parent-scope scope)))
7251 (assert (not (eq js2-current-scope scope)))
7252 (setf (js2-scope-parent-scope scope) js2-current-scope
7253 js2-current-scope scope))
7254
7255 (defsubst js2-pop-scope ()
7256 (setq js2-current-scope
7257 (js2-scope-parent-scope js2-current-scope)))
7258
7259 (defsubst js2-enter-loop (loop-node)
7260 (push loop-node js2-loop-set)
7261 (push loop-node js2-loop-and-switch-set)
7262 (js2-push-scope loop-node)
7263 ;; Tell the current labeled statement (if any) its statement,
7264 ;; and set the jump target of the first label to the loop.
7265 ;; These are used in `js2-parse-continue' to verify that the
7266 ;; continue target is an actual labeled loop. (And for codegen.)
7267 (when js2-labeled-stmt
7268 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7269 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7270 js2-labeled-stmt))) loop-node)))
7271
7272 (defsubst js2-exit-loop ()
7273 (pop js2-loop-set)
7274 (pop js2-loop-and-switch-set)
7275 (js2-pop-scope))
7276
7277 (defsubst js2-enter-switch (switch-node)
7278 (push switch-node js2-loop-and-switch-set))
7279
7280 (defsubst js2-exit-switch ()
7281 (pop js2-loop-and-switch-set))
7282
7283 (defun js2-parse (&optional buf cb)
7284 "Tells the js2 parser to parse a region of JavaScript.
7285
7286 BUF is a buffer or buffer name containing the code to parse.
7287 Call `narrow-to-region' first to parse only part of the buffer.
7288
7289 The returned AST root node is given some additional properties:
7290 `node-count' - total number of nodes in the AST
7291 `buffer' - BUF. The buffer it refers to may change or be killed,
7292 so the value is not necessarily reliable.
7293
7294 An optional callback CB can be specified to report parsing
7295 progress. If `(functionp CB)' returns t, it will be called with
7296 the current line number once before parsing begins, then again
7297 each time the lexer reaches a new line number.
7298
7299 CB can also be a list of the form `(symbol cb ...)' to specify
7300 multiple callbacks with different criteria. Each symbol is a
7301 criterion keyword, and the following element is the callback to
7302 call
7303
7304 :line - called whenever the line number changes
7305 :token - called for each new token consumed
7306
7307 The list of criteria could be extended to include entering or
7308 leaving a statement, an expression, or a function definition."
7309 (if (and cb (not (functionp cb)))
7310 (error "criteria callbacks not yet implemented"))
7311 (let ((inhibit-point-motion-hooks t)
7312 (js2-compiler-xml-available (>= js2-language-version 160))
7313 ;; This is a recursive-descent parser, so give it a big stack.
7314 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7315 (max-specpdl-size (max max-specpdl-size 3000))
7316 (case-fold-search nil)
7317 ast)
7318 (or buf (setq buf (current-buffer)))
7319 (message nil) ; clear any error message from previous parse
7320 (save-excursion
7321 (set-buffer buf)
7322 (setq js2-scanned-comments nil
7323 js2-parsed-errors nil
7324 js2-parsed-warnings nil
7325 js2-imenu-recorder nil
7326 js2-imenu-function-map nil
7327 js2-label-set nil)
7328 (js2-init-scanner)
7329 (setq ast (js2-with-unmodifying-text-property-changes
7330 (js2-do-parse)))
7331 (unless js2-ts-hit-eof
7332 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7333 (setf (js2-ast-root-errors ast) js2-parsed-errors
7334 (js2-ast-root-warnings ast) js2-parsed-warnings)
7335 ;; if we didn't find any declarations, put a dummy in this list so we
7336 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7337 (unless js2-imenu-recorder
7338 (setq js2-imenu-recorder 'empty))
7339 (run-hooks 'js2-parse-finished-hook)
7340 ast)))
7341
7342 ;; Corresponds to Rhino's Parser.parse() method.
7343 (defun js2-do-parse ()
7344 "Parse current buffer starting from current point.
7345 Scanner should be initialized."
7346 (let ((pos js2-ts-cursor)
7347 (end js2-ts-cursor) ; in case file is empty
7348 root n tt)
7349 ;; initialize buffer-local parsing vars
7350 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7351 js2-current-script-or-fn root
7352 js2-current-scope root
7353 js2-current-flagged-token js2-EOF
7354 js2-nesting-of-function 0
7355 js2-labeled-stmt nil
7356 js2-recorded-identifiers nil) ; for js2-highlight
7357 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7358 (if (= tt js2-FUNCTION)
7359 (progn
7360 (js2-consume-token)
7361 (setq n (js2-parse-function (if js2-called-by-compile-function
7362 'FUNCTION_EXPRESSION
7363 'FUNCTION_STATEMENT))))
7364 ;; not a function - parse a statement
7365 (setq n (js2-parse-statement)))
7366 ;; add function or statement to script
7367 (setq end (js2-node-end n))
7368 (js2-block-node-push root n))
7369 ;; add comments to root in lexical order
7370 (when js2-scanned-comments
7371 ;; if we find a comment beyond end of normal kids, use its end
7372 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7373 (dolist (comment js2-scanned-comments)
7374 (push comment (js2-ast-root-comments root))
7375 (js2-node-add-children root comment)))
7376 (setf (js2-node-len root) (- end pos))
7377 ;; Give extensions a chance to muck with things before highlighting starts.
7378 (let ((js2-additional-externs js2-additional-externs))
7379 (dolist (callback js2-post-parse-callbacks)
7380 (funcall callback))
7381 (js2-highlight-undeclared-vars))
7382 root))
7383
7384 (defun js2-function-parser ()
7385 (js2-consume-token)
7386 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7387
7388 (defun js2-parse-function-closure-body (fn-node)
7389 "Parse a JavaScript 1.8 function closure body."
7390 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7391 (if js2-ts-hit-eof
7392 (js2-report-error "msg.no.brace.body" nil
7393 (js2-node-pos fn-node)
7394 (- js2-ts-cursor (js2-node-pos fn-node)))
7395 (js2-node-add-children fn-node
7396 (setf (js2-function-node-body fn-node)
7397 (js2-parse-expr t))))))
7398
7399 (defun js2-parse-function-body (fn-node)
7400 (js2-must-match js2-LC "msg.no.brace.body"
7401 (js2-node-pos fn-node)
7402 (- js2-ts-cursor (js2-node-pos fn-node)))
7403 (let ((pos js2-token-beg) ; LC position
7404 (pn (make-js2-block-node)) ; starts at LC position
7405 tt
7406 end)
7407 (incf js2-nesting-of-function)
7408 (unwind-protect
7409 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7410 (= tt js2-EOF)
7411 (= tt js2-RC)))
7412 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7413 (js2-parse-statement)
7414 (js2-consume-token)
7415 (js2-parse-function 'FUNCTION_STATEMENT))))
7416 (decf js2-nesting-of-function))
7417 (setq end js2-token-end) ; assume no curly and leave at current token
7418 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7419 (setq end js2-token-end))
7420 (setf (js2-node-pos pn) pos
7421 (js2-node-len pn) (- end pos))
7422 (setf (js2-function-node-body fn-node) pn)
7423 (js2-node-add-children fn-node pn)
7424 pn))
7425
7426 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7427 "Declare and fontify destructuring parameters inside NODE.
7428 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7429 (cond
7430 ((js2-name-node-p node)
7431 (let (leftpos)
7432 (js2-define-symbol decl-type (js2-name-node-name node)
7433 node ignore-not-in-block)
7434 (when face
7435 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7436 (+ leftpos (js2-node-len node))
7437 face 'record))))
7438 ((js2-object-node-p node)
7439 (dolist (elem (js2-object-node-elems node))
7440 (js2-define-destruct-symbols
7441 (if (js2-object-prop-node-p elem)
7442 (js2-object-prop-node-right elem)
7443 ;; abbreviated destructuring {a, b}
7444 elem)
7445 decl-type face ignore-not-in-block)))
7446 ((js2-array-node-p node)
7447 (dolist (elem (js2-array-node-elems node))
7448 (when elem
7449 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7450 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7451 (js2-node-len node)))))
7452
7453 (defun js2-parse-function-params (fn-node pos)
7454 (if (js2-match-token js2-RP)
7455 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7456 (let (params len param)
7457 (loop for tt = (js2-peek-token)
7458 do
7459 (cond
7460 ;; destructuring param
7461 ((or (= tt js2-LB) (= tt js2-LC))
7462 (setq param (js2-parse-primary-expr-lhs))
7463 (js2-define-destruct-symbols param
7464 js2-LP
7465 'js2-function-param-face)
7466 (push param params))
7467 ;; simple name
7468 (t
7469 (js2-must-match js2-NAME "msg.no.parm")
7470 (js2-record-face 'js2-function-param-face)
7471 (setq param (js2-create-name-node))
7472 (js2-define-symbol js2-LP js2-ts-string param)
7473 (push param params)))
7474 while
7475 (js2-match-token js2-COMMA))
7476 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7477 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7478 (dolist (p params)
7479 (js2-node-add-children fn-node p)
7480 (push p (js2-function-node-params fn-node))))))
7481
7482 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7483 "Possibly show inconsistent-return warning.
7484 Last token scanned is the close-curly for the function body."
7485 (when (and js2-mode-show-strict-warnings
7486 js2-strict-inconsistent-return-warning
7487 (not (js2-has-consistent-return-usage
7488 (js2-function-node-body fn-node))))
7489 ;; Have it extend from close-curly to bol or beginning of block.
7490 (let ((pos (save-excursion
7491 (goto-char js2-token-end)
7492 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7493 (point-at-bol))))
7494 (end js2-token-end))
7495 (if (plusp (js2-name-node-length name))
7496 (js2-add-strict-warning "msg.no.return.value"
7497 (js2-name-node-name name) pos end)
7498 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7499
7500 (defun js2-parse-function (function-type)
7501 "Function parser. FUNCTION-TYPE is a symbol."
7502 (let ((pos js2-token-beg) ; start of 'function' keyword
7503 name
7504 name-beg
7505 name-end
7506 fn-node
7507 lp
7508 (synthetic-type function-type)
7509 member-expr-node)
7510 ;; parse function name, expression, or non-name (anonymous)
7511 (cond
7512 ;; function foo(...)
7513 ((js2-match-token js2-NAME)
7514 (setq name (js2-create-name-node t)
7515 name-beg js2-token-beg
7516 name-end js2-token-end)
7517 (unless (js2-match-token js2-LP)
7518 (when js2-allow-member-expr-as-function-name
7519 ;; function foo.bar(...)
7520 (setq member-expr-node name
7521 name nil
7522 member-expr-node (js2-parse-member-expr-tail
7523 nil member-expr-node)))
7524 (js2-must-match js2-LP "msg.no.paren.parms")))
7525 ((js2-match-token js2-LP)
7526 nil) ; anonymous function: leave name as null
7527 (t
7528 ;; function random-member-expr(...)
7529 (when js2-allow-member-expr-as-function-name
7530 ;; Note that memberExpr can not start with '(' like
7531 ;; in function (1+2).toString(), because 'function (' already
7532 ;; processed as anonymous function
7533 (setq member-expr-node (js2-parse-member-expr)))
7534 (js2-must-match js2-LP "msg.no.paren.parms")))
7535 (if (= js2-current-token js2-LP) ; eventually matched LP?
7536 (setq lp js2-token-beg))
7537 (if member-expr-node
7538 (progn
7539 (setq synthetic-type 'FUNCTION_EXPRESSION)
7540 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7541 (if name
7542 (js2-set-face name-beg name-end
7543 'font-lock-function-name-face 'record)))
7544 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7545 (plusp (js2-name-node-length name)))
7546 ;; Function statements define a symbol in the enclosing scope
7547 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7548 (setf fn-node (make-js2-function-node :pos pos
7549 :name name
7550 :form function-type
7551 :lp (if lp (- lp pos))))
7552 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7553 ;; 1. Nested functions are not affected by the dynamic scope flag
7554 ;; as dynamic scope is already a parent of their scope.
7555 ;; 2. Functions defined under the with statement also immune to
7556 ;; this setup, in which case dynamic scope is ignored in favor
7557 ;; of the with object.
7558 (setf (js2-function-node-ignore-dynamic fn-node) t))
7559 ;; dynamically bind all the per-function variables
7560 (let ((js2-current-script-or-fn fn-node)
7561 (js2-current-scope fn-node)
7562 (js2-nesting-of-with 0)
7563 (js2-end-flags 0)
7564 js2-label-set
7565 js2-loop-set
7566 js2-loop-and-switch-set)
7567 (js2-parse-function-params fn-node pos)
7568 (if (and (>= js2-language-version 180)
7569 (/= (js2-peek-token) js2-LC))
7570 (js2-parse-function-closure-body fn-node)
7571 (js2-parse-function-body fn-node))
7572 (if name
7573 (js2-node-add-children fn-node name))
7574 (js2-check-inconsistent-return-warning fn-node name)
7575 ;; Function expressions define a name only in the body of the
7576 ;; function, and only if not hidden by a parameter name
7577 (if (and name
7578 (eq synthetic-type 'FUNCTION_EXPRESSION)
7579 (null (js2-scope-get-symbol js2-current-scope
7580 (js2-name-node-name name))))
7581 (js2-define-symbol js2-FUNCTION
7582 (js2-name-node-name name)
7583 fn-node))
7584 (if (and name
7585 (not (eq function-type 'FUNCTION_EXPRESSION)))
7586 (js2-record-imenu-functions fn-node)))
7587 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7588 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7589 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7590 ;; We wait until after parsing the function to set its parent scope,
7591 ;; since `js2-define-symbol' needs the defining-scope check to stop
7592 ;; at the function boundary when checking for redeclarations.
7593 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7594 fn-node))
7595
7596 (defun js2-parse-statements (&optional parent)
7597 "Parse a statement list. Last token consumed must be js2-LC.
7598
7599 PARENT can be a `js2-block-node', in which case the statements are
7600 appended to PARENT. Otherwise a new `js2-block-node' is created
7601 and returned.
7602
7603 This function does not match the closing js2-RC: the caller
7604 matches the RC so it can provide a suitable error message if not
7605 matched. This means it's up to the caller to set the length of
7606 the node to include the closing RC. The node start pos is set to
7607 the absolute buffer start position, and the caller should fix it
7608 up to be relative to the parent node. All children of this block
7609 node are given relative start positions and correct lengths."
7610 (let ((pn (or parent (make-js2-block-node)))
7611 tt)
7612 (setf (js2-node-pos pn) js2-token-beg)
7613 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7614 (/= tt js2-RC))
7615 (js2-block-node-push pn (js2-parse-statement)))
7616 pn))
7617
7618 (defun js2-parse-statement ()
7619 (let (tt pn beg end)
7620 ;; coarse-grained user-interrupt check - needs work
7621 (and js2-parse-interruptable-p
7622 (zerop (% (incf js2-parse-stmt-count)
7623 js2-statements-per-pause))
7624 (input-pending-p)
7625 (throw 'interrupted t))
7626 (setq pn (js2-statement-helper))
7627 ;; no-side-effects warning check
7628 (unless (js2-node-has-side-effects pn)
7629 (setq end (js2-node-end pn))
7630 (save-excursion
7631 (goto-char end)
7632 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7633 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7634 pn))
7635
7636 ;; These correspond to the switch cases in Parser.statementHelper
7637 (defconst js2-parsers
7638 (let ((parsers (make-vector js2-num-tokens
7639 #'js2-parse-expr-stmt)))
7640 (aset parsers js2-BREAK #'js2-parse-break)
7641 (aset parsers js2-CONST #'js2-parse-const-var)
7642 (aset parsers js2-CONTINUE #'js2-parse-continue)
7643 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7644 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7645 (aset parsers js2-DO #'js2-parse-do)
7646 (aset parsers js2-FOR #'js2-parse-for)
7647 (aset parsers js2-FUNCTION #'js2-function-parser)
7648 (aset parsers js2-IF #'js2-parse-if)
7649 (aset parsers js2-LC #'js2-parse-block)
7650 (aset parsers js2-LET #'js2-parse-let-stmt)
7651 (aset parsers js2-NAME #'js2-parse-name-or-label)
7652 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7653 (aset parsers js2-SEMI #'js2-parse-semi)
7654 (aset parsers js2-SWITCH #'js2-parse-switch)
7655 (aset parsers js2-THROW #'js2-parse-throw)
7656 (aset parsers js2-TRY #'js2-parse-try)
7657 (aset parsers js2-VAR #'js2-parse-const-var)
7658 (aset parsers js2-WHILE #'js2-parse-while)
7659 (aset parsers js2-WITH #'js2-parse-with)
7660 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7661 parsers)
7662 "A vector mapping token types to parser functions.")
7663
7664 (defsubst js2-parse-warn-missing-semi (beg end)
7665 (and js2-mode-show-strict-warnings
7666 js2-strict-missing-semi-warning
7667 (js2-add-strict-warning
7668 "msg.missing.semi" nil
7669 ;; back up to beginning of statement or line
7670 (max beg (save-excursion
7671 (goto-char end)
7672 (point-at-bol)))
7673 end)))
7674
7675 (defconst js2-no-semi-insertion
7676 (list js2-IF
7677 js2-SWITCH
7678 js2-WHILE
7679 js2-DO
7680 js2-FOR
7681 js2-TRY
7682 js2-WITH
7683 js2-LC
7684 js2-ERROR
7685 js2-SEMI
7686 js2-FUNCTION)
7687 "List of tokens that don't do automatic semicolon insertion.")
7688
7689 (defconst js2-autoinsert-semi-and-warn
7690 (list js2-ERROR js2-EOF js2-RC))
7691
7692 (defun js2-statement-helper ()
7693 (let* ((tt (js2-peek-token))
7694 (first-tt tt)
7695 (beg js2-token-beg)
7696 (parser (if (= tt js2-ERROR)
7697 #'js2-parse-semi
7698 (aref js2-parsers tt)))
7699 pn
7700 tt-flagged)
7701 ;; If the statement is set, then it's been told its label by now.
7702 (and js2-labeled-stmt
7703 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7704 (setq js2-labeled-stmt nil))
7705 (setq pn (funcall parser))
7706 ;; Don't do auto semi insertion for certain statement types.
7707 (unless (or (memq first-tt js2-no-semi-insertion)
7708 (js2-labeled-stmt-node-p pn))
7709 (js2-auto-insert-semicolon pn))
7710 pn))
7711
7712 (defun js2-auto-insert-semicolon (pn)
7713 (let* ((tt-flagged (js2-peek-flagged-token))
7714 (tt (logand tt-flagged js2-clear-ti-mask))
7715 (pos (js2-node-pos pn)))
7716 (cond
7717 ((= tt js2-SEMI)
7718 ;; Consume ';' as a part of expression
7719 (js2-consume-token)
7720 ;; extend the node bounds to include the semicolon.
7721 (setf (js2-node-len pn) (- js2-token-end pos)))
7722 ((memq tt js2-autoinsert-semi-and-warn)
7723 ;; Autoinsert ;
7724 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7725 (t
7726 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7727 ;; Report error if no EOL or autoinsert ';' otherwise
7728 (js2-report-error "msg.no.semi.stmt")
7729 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7730
7731 (defun js2-parse-condition ()
7732 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7733 The parens are discarded and the expression node is returned.
7734 The `pos' field of the return value is set to an absolute position
7735 that must be fixed up by the caller.
7736 Return value is a list (EXPR LP RP), with absolute paren positions."
7737 (let (pn lp rp)
7738 (if (js2-must-match js2-LP "msg.no.paren.cond")
7739 (setq lp js2-token-beg))
7740 (setq pn (js2-parse-expr))
7741 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7742 (setq rp js2-token-beg))
7743 ;; Report strict warning on code like "if (a = 7) ..."
7744 (if (and js2-strict-cond-assign-warning
7745 (js2-assign-node-p pn))
7746 (js2-add-strict-warning "msg.equal.as.assign" nil
7747 (js2-node-pos pn)
7748 (+ (js2-node-pos pn)
7749 (js2-node-len pn))))
7750 (list pn lp rp)))
7751
7752 (defun js2-parse-if ()
7753 "Parser for if-statement. Last matched token must be js2-IF."
7754 (let ((pos js2-token-beg)
7755 cond
7756 if-true
7757 if-false
7758 else-pos
7759 end
7760 pn)
7761 (js2-consume-token)
7762 (setq cond (js2-parse-condition)
7763 if-true (js2-parse-statement)
7764 if-false (if (js2-match-token js2-ELSE)
7765 (progn
7766 (setq else-pos (- js2-token-beg pos))
7767 (js2-parse-statement)))
7768 end (js2-node-end (or if-false if-true))
7769 pn (make-js2-if-node :pos pos
7770 :len (- end pos)
7771 :condition (car cond)
7772 :then-part if-true
7773 :else-part if-false
7774 :else-pos else-pos
7775 :lp (js2-relpos (second cond) pos)
7776 :rp (js2-relpos (third cond) pos)))
7777 (js2-node-add-children pn (car cond) if-true if-false)
7778 pn))
7779
7780 (defun js2-parse-switch ()
7781 "Parser for if-statement. Last matched token must be js2-SWITCH."
7782 (let ((pos js2-token-beg)
7783 tt
7784 pn
7785 discriminant
7786 has-default
7787 case-expr
7788 case-node
7789 case-pos
7790 cases
7791 stmt
7792 lp
7793 rp)
7794 (js2-consume-token)
7795 (if (js2-must-match js2-LP "msg.no.paren.switch")
7796 (setq lp js2-token-beg))
7797 (setq discriminant (js2-parse-expr)
7798 pn (make-js2-switch-node :discriminant discriminant
7799 :pos pos
7800 :lp (js2-relpos lp pos)))
7801 (js2-node-add-children pn discriminant)
7802 (js2-enter-switch pn)
7803 (unwind-protect
7804 (progn
7805 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7806 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7807 (js2-must-match js2-LC "msg.no.brace.switch")
7808 (catch 'break
7809 (while t
7810 (setq tt (js2-next-token)
7811 case-pos js2-token-beg)
7812 (cond
7813 ((= tt js2-RC)
7814 (setf (js2-node-len pn) (- js2-token-end pos))
7815 (throw 'break nil)) ; done
7816 ((= tt js2-CASE)
7817 (setq case-expr (js2-parse-expr))
7818 (js2-must-match js2-COLON "msg.no.colon.case"))
7819 ((= tt js2-DEFAULT)
7820 (if has-default
7821 (js2-report-error "msg.double.switch.default"))
7822 (setq has-default t
7823 case-expr nil)
7824 (js2-must-match js2-COLON "msg.no.colon.case"))
7825 (t
7826 (js2-report-error "msg.bad.switch")
7827 (throw 'break nil)))
7828 (setq case-node (make-js2-case-node :pos case-pos
7829 :len (- js2-token-end case-pos)
7830 :expr case-expr))
7831 (js2-node-add-children case-node case-expr)
7832 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7833 (/= tt js2-CASE)
7834 (/= tt js2-DEFAULT)
7835 (/= tt js2-EOF))
7836 (setf stmt (js2-parse-statement)
7837 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7838 (js2-block-node-push case-node stmt))
7839 (push case-node cases)))
7840 ;; add cases last, as pushing reverses the order to be correct
7841 (dolist (kid cases)
7842 (js2-node-add-children pn kid)
7843 (push kid (js2-switch-node-cases pn)))
7844 pn) ; return value
7845 (js2-exit-switch))))
7846
7847 (defun js2-parse-while ()
7848 "Parser for while-statement. Last matched token must be js2-WHILE."
7849 (let ((pos js2-token-beg)
7850 (pn (make-js2-while-node))
7851 cond
7852 body)
7853 (js2-consume-token)
7854 (js2-enter-loop pn)
7855 (unwind-protect
7856 (progn
7857 (setf cond (js2-parse-condition)
7858 (js2-while-node-condition pn) (car cond)
7859 body (js2-parse-statement)
7860 (js2-while-node-body pn) body
7861 (js2-node-len pn) (- (js2-node-end body) pos)
7862 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7863 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7864 (js2-node-add-children pn body (car cond)))
7865 (js2-exit-loop))
7866 pn))
7867
7868 (defun js2-parse-do ()
7869 "Parser for do-statement. Last matched token must be js2-DO."
7870 (let ((pos js2-token-beg)
7871 (pn (make-js2-do-node))
7872 cond
7873 body
7874 end)
7875 (js2-consume-token)
7876 (js2-enter-loop pn)
7877 (unwind-protect
7878 (progn
7879 (setq body (js2-parse-statement))
7880 (js2-must-match js2-WHILE "msg.no.while.do")
7881 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7882 cond (js2-parse-condition)
7883 (js2-do-node-condition pn) (car cond)
7884 (js2-do-node-body pn) body
7885 end js2-ts-cursor
7886 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7887 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7888 (js2-node-add-children pn (car cond) body))
7889 (js2-exit-loop))
7890 ;; Always auto-insert semicolon to follow SpiderMonkey:
7891 ;; It is required by ECMAScript but is ignored by the rest of
7892 ;; world; see bug 238945
7893 (if (js2-match-token js2-SEMI)
7894 (setq end js2-ts-cursor))
7895 (setf (js2-node-len pn) (- end pos))
7896 pn))
7897
7898 (defun js2-parse-for ()
7899 "Parser for for-statement. Last matched token must be js2-FOR.
7900 Parses for, for-in, and for each-in statements."
7901 (let ((for-pos js2-token-beg)
7902 pn
7903 is-for-each
7904 is-for-in
7905 in-pos
7906 each-pos
7907 tmp-pos
7908 init ; Node init is also foo in 'foo in object'
7909 cond ; Node cond is also object in 'foo in object'
7910 incr ; 3rd section of for-loop initializer
7911 body
7912 tt
7913 lp
7914 rp)
7915 (js2-consume-token)
7916 ;; See if this is a for each () instead of just a for ()
7917 (when (js2-match-token js2-NAME)
7918 (if (string= "each" js2-ts-string)
7919 (progn
7920 (setq is-for-each t
7921 each-pos (- js2-token-beg for-pos)) ; relative
7922 (js2-record-face 'font-lock-keyword-face))
7923 (js2-report-error "msg.no.paren.for")))
7924 (if (js2-must-match js2-LP "msg.no.paren.for")
7925 (setq lp (- js2-token-beg for-pos)))
7926 (setq tt (js2-peek-token))
7927 ;; 'for' makes local scope
7928 (js2-push-scope (make-js2-scope))
7929 (unwind-protect
7930 ;; parse init clause
7931 (let ((js2-in-for-init t)) ; set as dynamic variable
7932 (cond
7933 ((= tt js2-SEMI)
7934 (setq init (make-js2-empty-expr-node)))
7935 ((or (= tt js2-VAR) (= tt js2-LET))
7936 (js2-consume-token)
7937 (setq init (js2-parse-variables tt js2-token-beg)))
7938 (t
7939 (setq init (js2-parse-expr)))))
7940 (if (js2-match-token js2-IN)
7941 (setq is-for-in t
7942 in-pos (- js2-token-beg for-pos)
7943 ;; scope of iteration target object is not the scope we've created above.
7944 ;; stash current scope temporary.
7945 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7946 (js2-parse-expr))) ; object over which we're iterating
7947 ;; else ordinary for loop - parse cond and incr
7948 (js2-must-match js2-SEMI "msg.no.semi.for")
7949 (setq cond (if (= (js2-peek-token) js2-SEMI)
7950 (make-js2-empty-expr-node) ; no loop condition
7951 (js2-parse-expr)))
7952 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7953 (setq tmp-pos js2-token-end
7954 incr (if (= (js2-peek-token) js2-RP)
7955 (make-js2-empty-expr-node :pos tmp-pos)
7956 (js2-parse-expr))))
7957 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7958 (setq rp (- js2-token-beg for-pos)))
7959 (if (not is-for-in)
7960 (setq pn (make-js2-for-node :init init
7961 :condition cond
7962 :update incr
7963 :lp lp
7964 :rp rp))
7965 ;; cond could be null if 'in obj' got eaten by the init node.
7966 (if (js2-infix-node-p init)
7967 ;; it was (foo in bar) instead of (var foo in bar)
7968 (setq cond (js2-infix-node-right init)
7969 init (js2-infix-node-left init))
7970 (if (and (js2-var-decl-node-p init)
7971 (> (length (js2-var-decl-node-kids init)) 1))
7972 (js2-report-error "msg.mult.index")))
7973 (setq pn (make-js2-for-in-node :iterator init
7974 :object cond
7975 :in-pos in-pos
7976 :foreach-p is-for-each
7977 :each-pos each-pos
7978 :lp lp
7979 :rp rp)))
7980 (unwind-protect
7981 (progn
7982 (js2-enter-loop pn)
7983 ;; We have to parse the body -after- creating the loop node,
7984 ;; so that the loop node appears in the js2-loop-set, allowing
7985 ;; break/continue statements to find the enclosing loop.
7986 (setf body (js2-parse-statement)
7987 (js2-loop-node-body pn) body
7988 (js2-node-pos pn) for-pos
7989 (js2-node-len pn) (- (js2-node-end body) for-pos))
7990 (js2-node-add-children pn init cond incr body))
7991 ;; finally
7992 (js2-exit-loop))
7993 (js2-pop-scope))
7994 pn))
7995
7996 (defun js2-parse-try ()
7997 "Parser for try-statement. Last matched token must be js2-TRY."
7998 (let ((try-pos js2-token-beg)
7999 try-end
8000 try-block
8001 catch-blocks
8002 finally-block
8003 saw-default-catch
8004 peek
8005 param
8006 catch-cond
8007 catch-node
8008 guard-kwd
8009 catch-pos
8010 finally-pos
8011 pn
8012 block
8013 lp
8014 rp)
8015 (js2-consume-token)
8016 (if (/= (js2-peek-token) js2-LC)
8017 (js2-report-error "msg.no.brace.try"))
8018 (setq try-block (js2-parse-statement)
8019 try-end (js2-node-end try-block)
8020 peek (js2-peek-token))
8021 (cond
8022 ((= peek js2-CATCH)
8023 (while (js2-match-token js2-CATCH)
8024 (setq catch-pos js2-token-beg
8025 guard-kwd nil
8026 catch-cond nil
8027 lp nil
8028 rp nil)
8029 (if saw-default-catch
8030 (js2-report-error "msg.catch.unreachable"))
8031 (if (js2-must-match js2-LP "msg.no.paren.catch")
8032 (setq lp (- js2-token-beg catch-pos)))
8033 (js2-push-scope (make-js2-scope))
8034 (let ((tt (js2-peek-token)))
8035 (cond
8036 ;; destructuring pattern
8037 ;; catch ({ message, file }) { ... }
8038 ((or (= tt js2-LB) (= tt js2-LC))
8039 (setq param
8040 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8041 js2-LET nil)))
8042 ;; simple name
8043 (t
8044 (js2-must-match js2-NAME "msg.bad.catchcond")
8045 (setq param (js2-create-name-node))
8046 (js2-define-symbol js2-LET js2-ts-string param))))
8047 ;; pattern guard
8048 (if (js2-match-token js2-IF)
8049 (setq guard-kwd (- js2-token-beg catch-pos)
8050 catch-cond (js2-parse-expr))
8051 (setq saw-default-catch t))
8052 (if (js2-must-match js2-RP "msg.bad.catchcond")
8053 (setq rp (- js2-token-beg catch-pos)))
8054 (js2-must-match js2-LC "msg.no.brace.catchblock")
8055 (setq block (js2-parse-statements)
8056 try-end (js2-node-end block)
8057 catch-node (make-js2-catch-node :pos catch-pos
8058 :param param
8059 :guard-expr catch-cond
8060 :guard-kwd guard-kwd
8061 :block block
8062 :lp lp
8063 :rp rp))
8064 (js2-pop-scope)
8065 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8066 (setq try-end js2-token-beg))
8067 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8068 (js2-node-len catch-node) (- try-end catch-pos))
8069 (js2-node-add-children catch-node param catch-cond block)
8070 (push catch-node catch-blocks)))
8071 ((/= peek js2-FINALLY)
8072 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8073 (js2-node-pos try-block)
8074 (- (setq try-end (js2-node-end try-block))
8075 (js2-node-pos try-block)))))
8076 (when (js2-match-token js2-FINALLY)
8077 (setq finally-pos js2-token-beg
8078 block (js2-parse-statement)
8079 try-end (js2-node-end block)
8080 finally-block (make-js2-finally-node :pos finally-pos
8081 :len (- try-end finally-pos)
8082 :body block))
8083 (js2-node-add-children finally-block block))
8084 (setq pn (make-js2-try-node :pos try-pos
8085 :len (- try-end try-pos)
8086 :try-block try-block
8087 :finally-block finally-block))
8088 (js2-node-add-children pn try-block finally-block)
8089 ;; push them onto the try-node, which reverses and corrects their order
8090 (dolist (cb catch-blocks)
8091 (js2-node-add-children pn cb)
8092 (push cb (js2-try-node-catch-clauses pn)))
8093 pn))
8094
8095 (defun js2-parse-throw ()
8096 "Parser for throw-statement. Last matched token must be js2-THROW."
8097 (let ((pos js2-token-beg)
8098 expr
8099 pn)
8100 (js2-consume-token)
8101 (if (= (js2-peek-token-or-eol) js2-EOL)
8102 ;; ECMAScript does not allow new lines before throw expression,
8103 ;; see bug 256617
8104 (js2-report-error "msg.bad.throw.eol"))
8105 (setq expr (js2-parse-expr)
8106 pn (make-js2-throw-node :pos pos
8107 :len (- (js2-node-end expr) pos)
8108 :expr expr))
8109 (js2-node-add-children pn expr)
8110 pn))
8111
8112 (defsubst js2-match-jump-label-name (label-name)
8113 "If break/continue specified a label, return that label's labeled stmt.
8114 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8115 does not match an existing label, reports an error and returns nil."
8116 (let ((bundle (cdr (assoc label-name js2-label-set))))
8117 (if (null bundle)
8118 (js2-report-error "msg.undef.label"))
8119 bundle))
8120
8121 (defun js2-parse-break ()
8122 "Parser for break-statement. Last matched token must be js2-BREAK."
8123 (let ((pos js2-token-beg)
8124 (end js2-token-end)
8125 break-target ; statement to break from
8126 break-label ; in "break foo", name-node representing the foo
8127 labels ; matching labeled statement to break to
8128 pn)
8129 (js2-consume-token) ; `break'
8130 (when (eq (js2-peek-token-or-eol) js2-NAME)
8131 (js2-consume-token)
8132 (setq break-label (js2-create-name-node)
8133 end (js2-node-end break-label)
8134 ;; matchJumpLabelName only matches if there is one
8135 labels (js2-match-jump-label-name js2-ts-string)
8136 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8137 (unless (or break-target break-label)
8138 ;; no break target specified - try for innermost enclosing loop/switch
8139 (if (null js2-loop-and-switch-set)
8140 (unless break-label
8141 (js2-report-error "msg.bad.break" nil pos (length "break")))
8142 (setq break-target (car js2-loop-and-switch-set))))
8143 (setq pn (make-js2-break-node :pos pos
8144 :len (- end pos)
8145 :label break-label
8146 :target break-target))
8147 (js2-node-add-children pn break-label) ; but not break-target
8148 pn))
8149
8150 (defun js2-parse-continue ()
8151 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8152 (let ((pos js2-token-beg)
8153 (end js2-token-end)
8154 label ; optional user-specified label, a `js2-name-node'
8155 labels ; current matching labeled stmt, if any
8156 target ; the `js2-loop-node' target of this continue stmt
8157 pn)
8158 (js2-consume-token) ; `continue'
8159 (when (= (js2-peek-token-or-eol) js2-NAME)
8160 (js2-consume-token)
8161 (setq label (js2-create-name-node)
8162 end (js2-node-end label)
8163 ;; matchJumpLabelName only matches if there is one
8164 labels (js2-match-jump-label-name js2-ts-string)))
8165 (cond
8166 ((null labels) ; no current label to go to
8167 (if (null js2-loop-set) ; no loop to continue to
8168 (js2-report-error "msg.continue.outside" nil pos
8169 (length "continue"))
8170 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8171 (t
8172 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8173 (setq target (js2-labeled-stmt-node-stmt labels))
8174 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8175 (setq pn (make-js2-continue-node :pos pos
8176 :len (- end pos)
8177 :label label
8178 :target target))
8179 (js2-node-add-children pn label) ; but not target - it's not our child
8180 pn))
8181
8182 (defun js2-parse-with ()
8183 "Parser for with-statement. Last matched token must be js2-WITH."
8184 (js2-consume-token)
8185 (let ((pos js2-token-beg)
8186 obj body pn lp rp)
8187 (if (js2-must-match js2-LP "msg.no.paren.with")
8188 (setq lp js2-token-beg))
8189 (setq obj (js2-parse-expr))
8190 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8191 (setq rp js2-token-beg))
8192 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8193 (setq body (js2-parse-statement)))
8194 (setq pn (make-js2-with-node :pos pos
8195 :len (- (js2-node-end body) pos)
8196 :object obj
8197 :body body
8198 :lp (js2-relpos lp pos)
8199 :rp (js2-relpos rp pos)))
8200 (js2-node-add-children pn obj body)
8201 pn))
8202
8203 (defun js2-parse-const-var ()
8204 "Parser for var- or const-statement.
8205 Last matched token must be js2-CONST or js2-VAR."
8206 (let ((tt (js2-peek-token))
8207 (pos js2-token-beg)
8208 expr
8209 pn)
8210 (js2-consume-token)
8211 (setq expr (js2-parse-variables tt js2-token-beg)
8212 pn (make-js2-expr-stmt-node :pos pos
8213 :len (- (js2-node-end expr) pos)
8214 :expr expr))
8215 (js2-node-add-children pn expr)
8216 pn))
8217
8218 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8219 (let ((pn (make-js2-expr-stmt-node :pos pos
8220 :len (js2-node-len expr)
8221 :type (if (js2-inside-function)
8222 js2-EXPR_VOID
8223 js2-EXPR_RESULT)
8224 :expr expr)))
8225 (if add-child
8226 (js2-node-add-children pn expr))
8227 pn))
8228
8229 (defun js2-parse-let-stmt ()
8230 "Parser for let-statement. Last matched token must be js2-LET."
8231 (js2-consume-token)
8232 (let ((pos js2-token-beg)
8233 expr
8234 pn)
8235 (if (= (js2-peek-token) js2-LP)
8236 ;; let expression in statement context
8237 (setq expr (js2-parse-let pos 'statement)
8238 pn (js2-wrap-with-expr-stmt pos expr t))
8239 ;; else we're looking at a statement like let x=6, y=7;
8240 (setf expr (js2-parse-variables js2-LET pos)
8241 pn (js2-wrap-with-expr-stmt pos expr t)
8242 (js2-node-type pn) js2-EXPR_RESULT))
8243 pn))
8244
8245 (defun js2-parse-ret-yield ()
8246 (js2-parse-return-or-yield (js2-peek-token) nil))
8247
8248 (defconst js2-parse-return-stmt-enders
8249 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8250
8251 (defsubst js2-now-all-set (before after mask)
8252 "Return whether or not the bits in the mask have changed to all set.
8253 BEFORE is bits before change, AFTER is bits after change, and MASK is
8254 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8255 but not BEFORE."
8256 (and (/= (logand before mask) mask)
8257 (= (logand after mask) mask)))
8258
8259 (defun js2-parse-return-or-yield (tt expr-context)
8260 (let ((pos js2-token-beg)
8261 (end js2-token-end)
8262 (before js2-end-flags)
8263 (inside-function (js2-inside-function))
8264 e
8265 ret
8266 name)
8267 (unless inside-function
8268 (js2-report-error (if (eq tt js2-RETURN)
8269 "msg.bad.return"
8270 "msg.bad.yield")))
8271 (js2-consume-token)
8272 ;; This is ugly, but we don't want to require a semicolon.
8273 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8274 (setq e (js2-parse-expr)
8275 end (js2-node-end e)))
8276 (cond
8277 ((eq tt js2-RETURN)
8278 (js2-set-flag js2-end-flags (if (null e)
8279 js2-end-returns
8280 js2-end-returns-value))
8281 (setq ret (make-js2-return-node :pos pos
8282 :len (- end pos)
8283 :retval e))
8284 (js2-node-add-children ret e)
8285 ;; See if we need a strict mode warning.
8286 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8287 ;; more thorough and accurate than this before/after flag check.
8288 ;; E.g. if there's a finally-block that always returns, we shouldn't
8289 ;; show a warning generated by inconsistent returns in the catch blocks.
8290 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8291 ;; so we know which returns/yields to highlight, and we should get rid of
8292 ;; all the checking in `js2-parse-return-or-yield'.
8293 (if (and js2-strict-inconsistent-return-warning
8294 (js2-now-all-set before js2-end-flags
8295 (logior js2-end-returns js2-end-returns-value)))
8296 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8297 (t
8298 (unless (js2-inside-function)
8299 (js2-report-error "msg.bad.yield"))
8300 (js2-set-flag js2-end-flags js2-end-yields)
8301 (setq ret (make-js2-yield-node :pos pos
8302 :len (- end pos)
8303 :value e))
8304 (js2-node-add-children ret e)
8305 (unless expr-context
8306 (setq e ret
8307 ret (js2-wrap-with-expr-stmt pos e t))
8308 (js2-set-requires-activation)
8309 (js2-set-is-generator))))
8310 ;; see if we are mixing yields and value returns.
8311 (when (and inside-function
8312 (js2-now-all-set before js2-end-flags
8313 (logior js2-end-yields js2-end-returns-value)))
8314 (setq name (js2-function-name js2-current-script-or-fn))
8315 (if (zerop (length name))
8316 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8317 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8318 ret))
8319
8320 (defun js2-parse-debugger ()
8321 (js2-consume-token)
8322 (make-js2-keyword-node :type js2-DEBUGGER))
8323
8324 (defun js2-parse-block ()
8325 "Parser for a curly-delimited statement block.
8326 Last token matched must be js2-LC."
8327 (let ((pos js2-token-beg)
8328 (pn (make-js2-scope)))
8329 (js2-consume-token)
8330 (js2-push-scope pn)
8331 (unwind-protect
8332 (progn
8333 (js2-parse-statements pn)
8334 (js2-must-match js2-RC "msg.no.brace.block")
8335 (setf (js2-node-len pn) (- js2-token-end pos)))
8336 (js2-pop-scope))
8337 pn))
8338
8339 ;; for js2-ERROR too, to have a node for error recovery to work on
8340 (defun js2-parse-semi ()
8341 "Parse a statement or handle an error.
8342 Last matched token is js-SEMI or js-ERROR."
8343 (let ((tt (js2-peek-token)) pos len)
8344 (js2-consume-token)
8345 (if (eq tt js2-SEMI)
8346 (make-js2-empty-expr-node :len 1)
8347 (setq pos js2-token-beg
8348 len (- js2-token-beg pos))
8349 (js2-report-error "msg.syntax" nil pos len)
8350 (make-js2-error-node :pos pos :len len))))
8351
8352 (defun js2-parse-default-xml-namespace ()
8353 "Parse a `default xml namespace = <expr>' e4x statement."
8354 (let ((pos js2-token-beg)
8355 end len expr unary es)
8356 (js2-consume-token)
8357 (js2-must-have-xml)
8358 (js2-set-requires-activation)
8359 (setq len (- js2-ts-cursor pos))
8360 (unless (and (js2-match-token js2-NAME)
8361 (string= js2-ts-string "xml"))
8362 (js2-report-error "msg.bad.namespace" nil pos len))
8363 (unless (and (js2-match-token js2-NAME)
8364 (string= js2-ts-string "namespace"))
8365 (js2-report-error "msg.bad.namespace" nil pos len))
8366 (unless (js2-match-token js2-ASSIGN)
8367 (js2-report-error "msg.bad.namespace" nil pos len))
8368 (setq expr (js2-parse-expr)
8369 end (js2-node-end expr)
8370 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8371 :pos pos
8372 :len (- end pos)
8373 :operand expr))
8374 (js2-node-add-children unary expr)
8375 (make-js2-expr-stmt-node :pos pos
8376 :len (- end pos)
8377 :expr unary)))
8378
8379 (defun js2-record-label (label bundle)
8380 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8381 (js2-consume-token)
8382 (let ((name (js2-label-node-name label))
8383 labeled-stmt
8384 dup)
8385 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8386 ;; flag both labels if possible when used in editing mode
8387 (if (and js2-parse-ide-mode
8388 (setq dup (js2-get-label-by-name labeled-stmt name)))
8389 (js2-report-error "msg.dup.label" nil
8390 (js2-node-abs-pos dup) (js2-node-len dup)))
8391 (js2-report-error "msg.dup.label" nil
8392 (js2-node-pos label) (js2-node-len label)))
8393 (js2-labeled-stmt-node-add-label bundle label)
8394 (js2-node-add-children bundle label)
8395 ;; Add one reference to the bundle per label in `js2-label-set'
8396 (push (cons name bundle) js2-label-set)))
8397
8398 (defun js2-parse-name-or-label ()
8399 "Parser for identifier or label. Last token matched must be js2-NAME.
8400 Called when we found a name in a statement context. If it's a label, we gather
8401 up any following labels and the next non-label statement into a
8402 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8403 expression and return it wrapped in a `js2-expr-stmt-node'."
8404 (let ((pos js2-token-beg)
8405 (end js2-token-end)
8406 expr
8407 stmt
8408 pn
8409 bundle
8410 (continue t))
8411 ;; set check for label and call down to `js2-parse-primary-expr'
8412 (js2-set-check-for-label)
8413 (setq expr (js2-parse-expr))
8414 (if (/= (js2-node-type expr) js2-LABEL)
8415 ;; Parsed non-label expression - wrap with expression stmt.
8416 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8417 ;; else parsed a label
8418 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8419 (js2-record-label expr bundle)
8420 ;; look for more labels
8421 (while (and continue (= (js2-peek-token) js2-NAME))
8422 (js2-set-check-for-label)
8423 (setq expr (js2-parse-expr))
8424 (if (/= (js2-node-type expr) js2-LABEL)
8425 (progn
8426 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8427 continue nil)
8428 (js2-auto-insert-semicolon stmt))
8429 (js2-record-label expr bundle)))
8430 ;; no more labels; now parse the labeled statement
8431 (unwind-protect
8432 (unless stmt
8433 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8434 (setq stmt (js2-statement-helper))))
8435 ;; remove the labels for this statement from the global set
8436 (dolist (label (js2-labeled-stmt-node-labels bundle))
8437 (setq js2-label-set (remove label js2-label-set))))
8438 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8439 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8440 (js2-node-add-children bundle stmt)
8441 bundle)))
8442
8443 (defun js2-parse-expr-stmt ()
8444 "Default parser in statement context, if no recognized statement found."
8445 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8446
8447 (defun js2-parse-variables (decl-type pos)
8448 "Parse a comma-separated list of variable declarations.
8449 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8450
8451 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8452 For 'var' or 'const', the keyword should be the token last scanned.
8453
8454 POS is the position where the node should start. It's sometimes the
8455 var/const/let keyword, and other times the beginning of the first token
8456 in the first variable declaration.
8457
8458 Returns the parsed `js2-var-decl-node' expression node."
8459 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8460 :pos pos))
8461 destructuring
8462 kid-pos
8463 tt
8464 init
8465 name
8466 end
8467 nbeg nend
8468 vi
8469 (continue t))
8470 ;; Example:
8471 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8472 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8473 ;; var {a, b} = baz;
8474 (while continue
8475 (setq destructuring nil
8476 name nil
8477 tt (js2-peek-token)
8478 kid-pos js2-token-beg
8479 end js2-token-end
8480 init nil)
8481 (if (or (= tt js2-LB) (= tt js2-LC))
8482 ;; Destructuring assignment, e.g., var [a, b] = ...
8483 (setq destructuring (js2-parse-primary-expr-lhs)
8484 end (js2-node-end destructuring))
8485 ;; Simple variable name
8486 (when (js2-must-match js2-NAME "msg.bad.var")
8487 (setq name (js2-create-name-node)
8488 nbeg js2-token-beg
8489 nend js2-token-end
8490 end nend)
8491 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8492 (when (js2-match-token js2-ASSIGN)
8493 (setq init (js2-parse-assign-expr)
8494 end (js2-node-end init))
8495 (if (and js2-parse-ide-mode
8496 (or (js2-object-node-p init)
8497 (js2-function-node-p init)))
8498 (js2-record-imenu-functions init name)))
8499 (when name
8500 (js2-set-face nbeg nend (if (js2-function-node-p init)
8501 'font-lock-function-name-face
8502 'font-lock-variable-name-face)
8503 'record))
8504 (setq vi (make-js2-var-init-node :pos kid-pos
8505 :len (- end kid-pos)
8506 :type decl-type))
8507 (if destructuring
8508 (progn
8509 (if (and (null init) (not js2-in-for-init))
8510 (js2-report-error "msg.destruct.assign.no.init"))
8511 (js2-define-destruct-symbols destructuring
8512 decl-type
8513 'font-lock-variable-name-face)
8514 (setf (js2-var-init-node-target vi) destructuring))
8515 (setf (js2-var-init-node-target vi) name))
8516 (setf (js2-var-init-node-initializer vi) init)
8517 (js2-node-add-children vi name destructuring init)
8518 (js2-block-node-push result vi)
8519 (unless (js2-match-token js2-COMMA)
8520 (setq continue nil)))
8521 (setf (js2-node-len result) (- end pos))
8522 result))
8523
8524 (defun js2-parse-let (pos &optional stmt-p)
8525 "Parse a let expression or statement.
8526 A let-expression is of the form `let (vars) expr'.
8527 A let-statment is of the form `let (vars) {statements}'.
8528 The third form of let is a variable declaration list, handled
8529 by `js2-parse-variables'."
8530 (let ((pn (make-js2-let-node :pos pos))
8531 beg vars body)
8532 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8533 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8534 (js2-push-scope pn)
8535 (unwind-protect
8536 (progn
8537 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8538 (if (js2-must-match js2-RP "msg.no.paren.let")
8539 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8540 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8541 ;; let statement
8542 (progn
8543 (js2-consume-token)
8544 (setf beg js2-token-beg ; position stmt at LC
8545 body (js2-parse-statements))
8546 (js2-must-match js2-RC "msg.no.curly.let")
8547 (setf (js2-node-len body) (- js2-token-end beg)
8548 (js2-node-len pn) (- js2-token-end pos)
8549 (js2-let-node-body pn) body
8550 (js2-node-type pn) js2-LET))
8551 ;; let expression
8552 (setf body (js2-parse-expr)
8553 (js2-node-len pn) (- (js2-node-end body) pos)
8554 (js2-let-node-body pn) body))
8555 (js2-node-add-children pn vars body))
8556 (js2-pop-scope))
8557 pn))
8558
8559 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8560 (js2-scope-put-symbol (or scope js2-current-scope)
8561 name
8562 (make-js2-symbol decl-type name node)))
8563
8564 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8565 "Define a symbol in the current scope.
8566 If NODE is non-nil, it is the AST node associated with the symbol."
8567 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8568 (symbol (if defining-scope
8569 (js2-scope-get-symbol defining-scope name)))
8570 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8571 (cond
8572 ((and symbol ; already defined
8573 (or (= sdt js2-CONST) ; old version is const
8574 (= decl-type js2-CONST) ; new version is const
8575 ;; two let-bound vars in this block have same name
8576 (and (= sdt js2-LET)
8577 (eq defining-scope js2-current-scope))))
8578 (js2-report-error
8579 (cond
8580 ((= sdt js2-CONST) "msg.const.redecl")
8581 ((= sdt js2-LET) "msg.let.redecl")
8582 ((= sdt js2-VAR) "msg.var.redecl")
8583 ((= sdt js2-FUNCTION) "msg.function.redecl")
8584 (t "msg.parm.redecl"))
8585 name))
8586 ((= decl-type js2-LET)
8587 (if (and (not ignore-not-in-block)
8588 (or (= (js2-node-type js2-current-scope) js2-IF)
8589 (js2-loop-node-p js2-current-scope)))
8590 (js2-report-error "msg.let.decl.not.in.block")
8591 (js2-define-new-symbol decl-type name node)))
8592 ((or (= decl-type js2-VAR)
8593 (= decl-type js2-CONST)
8594 (= decl-type js2-FUNCTION))
8595 (if symbol
8596 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8597 (js2-add-strict-warning "msg.var.redecl" name)
8598 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8599 (js2-add-strict-warning "msg.var.hides.arg" name)))
8600 (js2-define-new-symbol decl-type name node
8601 js2-current-script-or-fn)))
8602 ((= decl-type js2-LP)
8603 (if symbol
8604 ;; must be duplicate parameter. Second parameter hides the
8605 ;; first, so go ahead and add the second pararameter
8606 (js2-report-warning "msg.dup.parms" name))
8607 (js2-define-new-symbol decl-type name node))
8608 (t (js2-code-bug)))))
8609
8610 (defun js2-parse-expr (&optional oneshot)
8611 (let* ((pn (js2-parse-assign-expr))
8612 (pos (js2-node-pos pn))
8613 left
8614 right
8615 op-pos)
8616 (while (and (not oneshot)
8617 (js2-match-token js2-COMMA))
8618 (setq op-pos (- js2-token-beg pos)) ; relative
8619 (if (= (js2-peek-token) js2-YIELD)
8620 (js2-report-error "msg.yield.parenthesized"))
8621 (setq right (js2-parse-assign-expr)
8622 left pn
8623 pn (make-js2-infix-node :type js2-COMMA
8624 :pos pos
8625 :len (- js2-ts-cursor pos)
8626 :op-pos op-pos
8627 :left left
8628 :right right))
8629 (js2-node-add-children pn left right))
8630 pn))
8631
8632 (defun js2-parse-assign-expr ()
8633 (let ((tt (js2-peek-token))
8634 (pos js2-token-beg)
8635 pn
8636 left
8637 right
8638 op-pos)
8639 (if (= tt js2-YIELD)
8640 (js2-parse-return-or-yield tt t)
8641 ;; not yield - parse assignment expression
8642 (setq pn (js2-parse-cond-expr)
8643 tt (js2-peek-token))
8644 (when (and (<= js2-first-assign tt)
8645 (<= tt js2-last-assign))
8646 ;; tt express assignment (=, |=, ^=, ..., %=)
8647 (js2-consume-token)
8648 (setq op-pos (- js2-token-beg pos) ; relative
8649 left pn
8650 right (js2-parse-assign-expr)
8651 pn (make-js2-assign-node :type tt
8652 :pos pos
8653 :len (- (js2-node-end right) pos)
8654 :op-pos op-pos
8655 :left left
8656 :right right))
8657 (when js2-parse-ide-mode
8658 (js2-highlight-assign-targets pn left right)
8659 (if (or (js2-function-node-p right)
8660 (js2-object-node-p right))
8661 (js2-record-imenu-functions right left)))
8662 ;; do this last so ide checks above can use absolute positions
8663 (js2-node-add-children pn left right))
8664 pn)))
8665
8666 (defun js2-parse-cond-expr ()
8667 (let ((pos js2-token-beg)
8668 (pn (js2-parse-or-expr))
8669 test-expr
8670 if-true
8671 if-false
8672 q-pos
8673 c-pos)
8674 (when (js2-match-token js2-HOOK)
8675 (setq q-pos (- js2-token-beg pos)
8676 if-true (js2-parse-assign-expr))
8677 (js2-must-match js2-COLON "msg.no.colon.cond")
8678 (setq c-pos (- js2-token-beg pos)
8679 if-false (js2-parse-assign-expr)
8680 test-expr pn
8681 pn (make-js2-cond-node :pos pos
8682 :len (- (js2-node-end if-false) pos)
8683 :test-expr test-expr
8684 :true-expr if-true
8685 :false-expr if-false
8686 :q-pos q-pos
8687 :c-pos c-pos))
8688 (js2-node-add-children pn test-expr if-true if-false))
8689 pn))
8690
8691 (defun js2-make-binary (type left parser)
8692 "Helper for constructing a binary-operator AST node.
8693 LEFT is the left-side-expression, already parsed, and the
8694 binary operator should have just been matched.
8695 PARSER is a function to call to parse the right operand,
8696 or a `js2-node' struct if it has already been parsed."
8697 (let* ((pos (js2-node-pos left))
8698 (op-pos (- js2-token-beg pos))
8699 (right (if (js2-node-p parser)
8700 parser
8701 (funcall parser)))
8702 (pn (make-js2-infix-node :type type
8703 :pos pos
8704 :len (- (js2-node-end right) pos)
8705 :op-pos op-pos
8706 :left left
8707 :right right)))
8708 (js2-node-add-children pn left right)
8709 pn))
8710
8711 (defun js2-parse-or-expr ()
8712 (let ((pn (js2-parse-and-expr)))
8713 (when (js2-match-token js2-OR)
8714 (setq pn (js2-make-binary js2-OR
8715 pn
8716 'js2-parse-or-expr)))
8717 pn))
8718
8719 (defun js2-parse-and-expr ()
8720 (let ((pn (js2-parse-bit-or-expr)))
8721 (when (js2-match-token js2-AND)
8722 (setq pn (js2-make-binary js2-AND
8723 pn
8724 'js2-parse-and-expr)))
8725 pn))
8726
8727 (defun js2-parse-bit-or-expr ()
8728 (let ((pn (js2-parse-bit-xor-expr)))
8729 (while (js2-match-token js2-BITOR)
8730 (setq pn (js2-make-binary js2-BITOR
8731 pn
8732 'js2-parse-bit-xor-expr)))
8733 pn))
8734
8735 (defun js2-parse-bit-xor-expr ()
8736 (let ((pn (js2-parse-bit-and-expr)))
8737 (while (js2-match-token js2-BITXOR)
8738 (setq pn (js2-make-binary js2-BITXOR
8739 pn
8740 'js2-parse-bit-and-expr)))
8741 pn))
8742
8743 (defun js2-parse-bit-and-expr ()
8744 (let ((pn (js2-parse-eq-expr)))
8745 (while (js2-match-token js2-BITAND)
8746 (setq pn (js2-make-binary js2-BITAND
8747 pn
8748 'js2-parse-eq-expr)))
8749 pn))
8750
8751 (defconst js2-parse-eq-ops
8752 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8753
8754 (defun js2-parse-eq-expr ()
8755 (let ((pn (js2-parse-rel-expr))
8756 tt)
8757 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8758 (js2-consume-token)
8759 (setq pn (js2-make-binary tt
8760 pn
8761 'js2-parse-rel-expr)))
8762 pn))
8763
8764 (defconst js2-parse-rel-ops
8765 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8766
8767 (defun js2-parse-rel-expr ()
8768 (let ((pn (js2-parse-shift-expr))
8769 (continue t)
8770 tt)
8771 (while continue
8772 (setq tt (js2-peek-token))
8773 (cond
8774 ((and js2-in-for-init (= tt js2-IN))
8775 (setq continue nil))
8776 ((memq tt js2-parse-rel-ops)
8777 (js2-consume-token)
8778 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8779 (t
8780 (setq continue nil))))
8781 pn))
8782
8783 (defconst js2-parse-shift-ops
8784 (list js2-LSH js2-URSH js2-RSH))
8785
8786 (defun js2-parse-shift-expr ()
8787 (let ((pn (js2-parse-add-expr))
8788 tt
8789 (continue t))
8790 (while continue
8791 (setq tt (js2-peek-token))
8792 (if (memq tt js2-parse-shift-ops)
8793 (progn
8794 (js2-consume-token)
8795 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8796 (setq continue nil)))
8797 pn))
8798
8799 (defun js2-parse-add-expr ()
8800 (let ((pn (js2-parse-mul-expr))
8801 tt
8802 (continue t))
8803 (while continue
8804 (setq tt (js2-peek-token))
8805 (if (or (= tt js2-ADD) (= tt js2-SUB))
8806 (progn
8807 (js2-consume-token)
8808 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8809 (setq continue nil)))
8810 pn))
8811
8812 (defconst js2-parse-mul-ops
8813 (list js2-MUL js2-DIV js2-MOD))
8814
8815 (defun js2-parse-mul-expr ()
8816 (let ((pn (js2-parse-unary-expr))
8817 tt
8818 (continue t))
8819 (while continue
8820 (setq tt (js2-peek-token))
8821 (if (memq tt js2-parse-mul-ops)
8822 (progn
8823 (js2-consume-token)
8824 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8825 (setq continue nil)))
8826 pn))
8827
8828 (defsubst js2-make-unary (type parser &rest args)
8829 "Make a unary node of type TYPE.
8830 PARSER is either a node (for postfix operators) or a function to call
8831 to parse the operand (for prefix operators)."
8832 (let* ((pos js2-token-beg)
8833 (postfix (js2-node-p parser))
8834 (expr (if postfix
8835 parser
8836 (apply parser args)))
8837 end
8838 pn)
8839 (if postfix ; e.g. i++
8840 (setq pos (js2-node-pos expr)
8841 end js2-token-end)
8842 (setq end (js2-node-end expr)))
8843 (setq pn (make-js2-unary-node :type type
8844 :pos pos
8845 :len (- end pos)
8846 :operand expr))
8847 (js2-node-add-children pn expr)
8848 pn))
8849
8850 (defconst js2-incrementable-node-types
8851 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8852 "Node types that can be the operand of a ++ or -- operator.")
8853
8854 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8855 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8856 js2-incrementable-node-types)
8857 (js2-report-error (if (= tt js2-INC)
8858 "msg.bad.incr"
8859 "msg.bad.decr")
8860 nil beg (- end beg))))
8861
8862 (defun js2-parse-unary-expr ()
8863 (let ((tt (js2-peek-token))
8864 pn expr beg end)
8865 (cond
8866 ((or (= tt js2-VOID)
8867 (= tt js2-NOT)
8868 (= tt js2-BITNOT)
8869 (= tt js2-TYPEOF))
8870 (js2-consume-token)
8871 (js2-make-unary tt 'js2-parse-unary-expr))
8872 ((= tt js2-ADD)
8873 (js2-consume-token)
8874 ;; Convert to special POS token in decompiler and parse tree
8875 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8876 ((= tt js2-SUB)
8877 (js2-consume-token)
8878 ;; Convert to special NEG token in decompiler and parse tree
8879 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8880 ((or (= tt js2-INC)
8881 (= tt js2-DEC))
8882 (js2-consume-token)
8883 (prog1
8884 (setq beg js2-token-beg
8885 end js2-token-end
8886 expr (js2-make-unary tt 'js2-parse-member-expr t))
8887 (js2-check-bad-inc-dec tt beg end expr)))
8888 ((= tt js2-DELPROP)
8889 (js2-consume-token)
8890 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8891 ((= tt js2-ERROR)
8892 (js2-consume-token)
8893 (make-js2-error-node)) ; try to continue
8894 ((and (= tt js2-LT)
8895 js2-compiler-xml-available)
8896 ;; XML stream encountered in expression.
8897 (js2-consume-token)
8898 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8899 (t
8900 (setq pn (js2-parse-member-expr t)
8901 ;; Don't look across a newline boundary for a postfix incop.
8902 tt (js2-peek-token-or-eol))
8903 (when (or (= tt js2-INC) (= tt js2-DEC))
8904 (js2-consume-token)
8905 (setf expr pn
8906 pn (js2-make-unary tt expr))
8907 (js2-node-set-prop pn 'postfix t)
8908 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8909 pn))))
8910
8911 (defun js2-parse-xml-initializer ()
8912 "Parse an E4X XML initializer.
8913 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8914 Then I'll postprocess the result, depending on whether we're in IDE
8915 mode or codegen mode, and generate the appropriate rewritten AST.
8916 IDE mode uses a rich AST that models the XML structure. Codegen mode
8917 just concatenates everything and makes a new XML or XMLList out of it."
8918 (let ((tt (js2-get-first-xml-token))
8919 pn-xml
8920 pn
8921 expr
8922 kids
8923 expr-pos
8924 (continue t)
8925 (first-token t))
8926 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8927 (js2-report-error "msg.syntax"))
8928 (setq pn-xml (make-js2-xml-node))
8929 (while continue
8930 (if first-token
8931 (setq first-token nil)
8932 (setq tt (js2-get-next-xml-token)))
8933 (cond
8934 ;; js2-XML means we found a {expr} in the XML stream.
8935 ;; The js2-ts-string is the XML up to the left-curly.
8936 ((= tt js2-XML)
8937 (push (make-js2-string-node :pos js2-token-beg
8938 :len (- js2-ts-cursor js2-token-beg))
8939 kids)
8940 (js2-must-match js2-LC "msg.syntax")
8941 (setq expr-pos js2-ts-cursor
8942 expr (if (eq (js2-peek-token) js2-RC)
8943 (make-js2-empty-expr-node :pos expr-pos)
8944 (js2-parse-expr)))
8945 (js2-must-match js2-RC "msg.syntax")
8946 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8947 :len (js2-node-len expr)
8948 :expr expr))
8949 (js2-node-add-children pn expr)
8950 (push pn kids))
8951 ;; a js2-XMLEND token means we hit the final close-tag.
8952 ((= tt js2-XMLEND)
8953 (push (make-js2-string-node :pos js2-token-beg
8954 :len (- js2-ts-cursor js2-token-beg))
8955 kids)
8956 (dolist (kid (nreverse kids))
8957 (js2-block-node-push pn-xml kid))
8958 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8959 (js2-node-pos pn-xml))
8960 continue nil))
8961 (t
8962 (js2-report-error "msg.syntax")
8963 (setq continue nil))))
8964 pn-xml))
8965
8966
8967 (defun js2-parse-argument-list ()
8968 "Parse an argument list and return it as a lisp list of nodes.
8969 Returns the list in reverse order. Consumes the right-paren token."
8970 (let (result)
8971 (unless (js2-match-token js2-RP)
8972 (loop do
8973 (if (= (js2-peek-token) js2-YIELD)
8974 (js2-report-error "msg.yield.parenthesized"))
8975 (push (js2-parse-assign-expr) result)
8976 while
8977 (js2-match-token js2-COMMA))
8978 (js2-must-match js2-RP "msg.no.paren.arg")
8979 result)))
8980
8981 (defun js2-parse-member-expr (&optional allow-call-syntax)
8982 (let ((tt (js2-peek-token))
8983 pn
8984 pos
8985 target
8986 args
8987 beg
8988 end
8989 init
8990 tail)
8991 (if (/= tt js2-NEW)
8992 (setq pn (js2-parse-primary-expr))
8993 ;; parse a 'new' expression
8994 (js2-consume-token)
8995 (setq pos js2-token-beg
8996 beg pos
8997 target (js2-parse-member-expr)
8998 end (js2-node-end target)
8999 pn (make-js2-new-node :pos pos
9000 :target target
9001 :len (- end pos)))
9002 (js2-node-add-children pn target)
9003 (when (js2-match-token js2-LP)
9004 ;; Add the arguments to pn, if any are supplied.
9005 (setf beg pos ; start of "new" keyword
9006 pos js2-token-beg
9007 args (nreverse (js2-parse-argument-list))
9008 (js2-new-node-args pn) args
9009 end js2-token-end
9010 (js2-new-node-lp pn) (- pos beg)
9011 (js2-new-node-rp pn) (- end 1 beg))
9012 (apply #'js2-node-add-children pn args))
9013 (when (and js2-allow-rhino-new-expr-initializer
9014 (js2-match-token js2-LC))
9015 (setf init (js2-parse-object-literal)
9016 end (js2-node-end init)
9017 (js2-new-node-initializer pn) init)
9018 (js2-node-add-children pn init))
9019 (setf (js2-node-len pn) (- end beg))) ; end outer if
9020 (js2-parse-member-expr-tail allow-call-syntax pn)))
9021
9022 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9023 "Parse a chain of property/array accesses or function calls.
9024 Includes parsing for E4X operators like `..' and `.@'.
9025 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9026 Returns an expression tree that includes PN, the parent node."
9027 (let ((beg (js2-node-pos pn))
9028 tt
9029 (continue t))
9030 (while continue
9031 (setq tt (js2-peek-token))
9032 (cond
9033 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9034 (setq pn (js2-parse-property-access tt pn)))
9035 ((= tt js2-DOTQUERY)
9036 (setq pn (js2-parse-dot-query pn)))
9037 ((= tt js2-LB)
9038 (setq pn (js2-parse-element-get pn)))
9039 ((= tt js2-LP)
9040 (if allow-call-syntax
9041 (setq pn (js2-parse-function-call pn))
9042 (setq continue nil)))
9043 (t
9044 (setq continue nil))))
9045 (if (>= js2-highlight-level 2)
9046 (js2-parse-highlight-member-expr-node pn))
9047 pn))
9048
9049 (defun js2-parse-dot-query (pn)
9050 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9051 Last token parsed must be `js2-DOTQUERY'."
9052 (let ((pos (js2-node-pos pn))
9053 op-pos
9054 expr
9055 end)
9056 (js2-consume-token)
9057 (js2-must-have-xml)
9058 (js2-set-requires-activation)
9059 (setq op-pos js2-token-beg
9060 expr (js2-parse-expr)
9061 end (js2-node-end expr)
9062 pn (make-js2-xml-dot-query-node :left pn
9063 :pos pos
9064 :op-pos op-pos
9065 :right expr))
9066 (js2-node-add-children pn
9067 (js2-xml-dot-query-node-left pn)
9068 (js2-xml-dot-query-node-right pn))
9069 (if (js2-must-match js2-RP "msg.no.paren")
9070 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9071 end js2-token-end))
9072 (setf (js2-node-len pn) (- end pos))
9073 pn))
9074
9075 (defun js2-parse-element-get (pn)
9076 "Parse an element-get expression, e.g. foo[bar].
9077 Last token parsed must be `js2-RB'."
9078 (let ((lb js2-token-beg)
9079 (pos (js2-node-pos pn))
9080 rb
9081 expr)
9082 (js2-consume-token)
9083 (setq expr (js2-parse-expr))
9084 (if (js2-must-match js2-RB "msg.no.bracket.index")
9085 (setq rb js2-token-beg))
9086 (setq pn (make-js2-elem-get-node :target pn
9087 :pos pos
9088 :element expr
9089 :lb (js2-relpos lb pos)
9090 :rb (js2-relpos rb pos)
9091 :len (- js2-token-end pos)))
9092 (js2-node-add-children pn
9093 (js2-elem-get-node-target pn)
9094 (js2-elem-get-node-element pn))
9095 pn))
9096
9097 (defun js2-parse-function-call (pn)
9098 (let (args
9099 (pos (js2-node-pos pn)))
9100 (js2-consume-token)
9101 (setq pn (make-js2-call-node :pos pos
9102 :target pn
9103 :lp (- js2-token-beg pos)))
9104 (js2-node-add-children pn (js2-call-node-target pn))
9105 ;; Add the arguments to pn, if any are supplied.
9106 (setf args (nreverse (js2-parse-argument-list))
9107 (js2-call-node-rp pn) (- js2-token-beg pos)
9108 (js2-call-node-args pn) args)
9109 (apply #'js2-node-add-children pn args)
9110 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9111 pn))
9112
9113 (defun js2-parse-property-access (tt pn)
9114 "Parse a property access, XML descendants access, or XML attr access."
9115 (let ((member-type-flags 0)
9116 (dot-pos js2-token-beg)
9117 (dot-len (if (= tt js2-DOTDOT) 2 1))
9118 name
9119 ref ; right side of . or .. operator
9120 result)
9121 (js2-consume-token)
9122 (when (= tt js2-DOTDOT)
9123 (js2-must-have-xml)
9124 (setq member-type-flags js2-descendants-flag))
9125 (if (not js2-compiler-xml-available)
9126 (progn
9127 (js2-must-match-prop-name "msg.no.name.after.dot")
9128 (setq name (js2-create-name-node t js2-GETPROP)
9129 result (make-js2-prop-get-node :left pn
9130 :pos js2-token-beg
9131 :right name
9132 :len (- js2-token-end
9133 js2-token-beg)))
9134 (js2-node-add-children result pn name)
9135 result)
9136 ;; otherwise look for XML operators
9137 (setf result (if (= tt js2-DOT)
9138 (make-js2-prop-get-node)
9139 (make-js2-infix-node :type js2-DOTDOT))
9140 (js2-node-pos result) (js2-node-pos pn)
9141 (js2-infix-node-op-pos result) dot-pos
9142 (js2-infix-node-left result) pn ; do this after setting position
9143 tt (js2-next-token))
9144 (cond
9145 ;; needed for generator.throw()
9146 ((= tt js2-THROW)
9147 (js2-save-name-token-data js2-token-beg "throw")
9148 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9149 ;; handles: name, ns::name, ns::*, ns::[expr]
9150 ((js2-valid-prop-name-token tt)
9151 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9152 ;; handles: *, *::name, *::*, *::[expr]
9153 ((= tt js2-MUL)
9154 (js2-save-name-token-data js2-token-beg "*")
9155 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9156 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9157 ((= tt js2-XMLATTR)
9158 (setq result (js2-parse-attribute-access)))
9159 (t
9160 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9161 (if ref
9162 (setf (js2-node-len result) (- (js2-node-end ref)
9163 (js2-node-pos result))
9164 (js2-infix-node-right result) ref))
9165 (if (js2-infix-node-p result)
9166 (js2-node-add-children result
9167 (js2-infix-node-left result)
9168 (js2-infix-node-right result)))
9169 result)))
9170
9171 (defun js2-parse-attribute-access ()
9172 "Parse an E4X XML attribute expression.
9173 This includes expressions of the forms:
9174
9175 @attr @ns::attr @ns::*
9176 @* @*::attr @*::*
9177 @[expr] @*::[expr] @ns::[expr]
9178
9179 Called if we peeked an '@' token."
9180 (let ((tt (js2-next-token))
9181 (at-pos js2-token-beg))
9182 (cond
9183 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9184 ((js2-valid-prop-name-token tt)
9185 (js2-parse-property-name at-pos js2-ts-string 0))
9186 ;; handles: @*, @*::name, @*::*, @*::[expr]
9187 ((= tt js2-MUL)
9188 (js2-save-name-token-data js2-token-beg "*")
9189 (js2-parse-property-name js2-token-beg "*" 0))
9190 ;; handles @[expr]
9191 ((= tt js2-LB)
9192 (js2-parse-xml-elem-ref at-pos))
9193 (t
9194 (js2-report-error "msg.no.name.after.xmlAttr")
9195 ;; Avoid cascaded errors that happen if we make an error node here.
9196 (js2-save-name-token-data js2-token-beg "")
9197 (js2-parse-property-name js2-token-beg "" 0)))))
9198
9199 (defun js2-parse-property-name (at-pos s member-type-flags)
9200 "Check if :: follows name in which case it becomes qualified name.
9201
9202 AT-POS is a natural number if we just read an '@' token, else nil.
9203 S is the name or string that was matched: an identifier, 'throw' or '*'.
9204 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9205
9206 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9207 operator, or the name is followed by ::. For a plain name, returns a
9208 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9209 (let ((pos (or at-pos js2-token-beg))
9210 colon-pos
9211 (name (js2-create-name-node t js2-current-token))
9212 ns
9213 tt
9214 ref
9215 pn)
9216 (catch 'return
9217 (when (js2-match-token js2-COLONCOLON)
9218 (setq ns name
9219 colon-pos js2-token-beg
9220 tt (js2-next-token))
9221 (cond
9222 ;; handles name::name
9223 ((js2-valid-prop-name-token tt)
9224 (setq name (js2-create-name-node)))
9225 ;; handles name::*
9226 ((= tt js2-MUL)
9227 (js2-save-name-token-data js2-token-beg "*")
9228 (setq name (js2-create-name-node)))
9229 ;; handles name::[expr]
9230 ((= tt js2-LB)
9231 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9232 (t
9233 (js2-report-error "msg.no.name.after.coloncolon"))))
9234 (if (and (null ns) (zerop member-type-flags))
9235 name
9236 (prog1
9237 (setq pn
9238 (make-js2-xml-prop-ref-node :pos pos
9239 :len (- (js2-node-end name) pos)
9240 :at-pos at-pos
9241 :colon-pos colon-pos
9242 :propname name))
9243 (js2-node-add-children pn name))))))
9244
9245 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9246 "Parse the [expr] portion of an xml element reference.
9247 For instance, @[expr], @*::[expr], or ns::[expr]."
9248 (let* ((lb js2-token-beg)
9249 (pos (or at-pos lb))
9250 rb
9251 (expr (js2-parse-expr))
9252 (end (js2-node-end expr))
9253 pn)
9254 (if (js2-must-match js2-RB "msg.no.bracket.index")
9255 (setq rb js2-token-beg
9256 end js2-token-end))
9257 (prog1
9258 (setq pn
9259 (make-js2-xml-elem-ref-node :pos pos
9260 :len (- end pos)
9261 :namespace namespace
9262 :colon-pos colon-pos
9263 :at-pos at-pos
9264 :expr expr
9265 :lb (js2-relpos lb pos)
9266 :rb (js2-relpos rb pos)))
9267 (js2-node-add-children pn namespace expr))))
9268
9269 (defsubst js2-parse-primary-expr-lhs ()
9270 (let ((js2-is-in-lhs t))
9271 (js2-parse-primary-expr)))
9272
9273 (defun js2-parse-primary-expr ()
9274 "Parses a literal (leaf) expression of some sort.
9275 Includes complex literals such as functions, object-literals,
9276 array-literals, array comprehensions and regular expressions."
9277 (let ((tt-flagged (js2-next-flagged-token))
9278 pn ; parent node (usually return value)
9279 tt
9280 px-pos ; paren-expr pos
9281 len
9282 flags ; regexp flags
9283 expr)
9284 (setq tt js2-current-token)
9285 (cond
9286 ((= tt js2-FUNCTION)
9287 (js2-parse-function 'FUNCTION_EXPRESSION))
9288 ((= tt js2-LB)
9289 (js2-parse-array-literal))
9290 ((= tt js2-LC)
9291 (js2-parse-object-literal))
9292 ((= tt js2-LET)
9293 (js2-parse-let js2-token-beg))
9294 ((= tt js2-LP)
9295 (setq px-pos js2-token-beg
9296 expr (js2-parse-expr))
9297 (js2-must-match js2-RP "msg.no.paren")
9298 (setq pn (make-js2-paren-node :pos px-pos
9299 :expr expr
9300 :len (- js2-token-end px-pos)))
9301 (js2-node-add-children pn (js2-paren-node-expr pn))
9302 pn)
9303 ((= tt js2-XMLATTR)
9304 (js2-must-have-xml)
9305 (js2-parse-attribute-access))
9306 ((= tt js2-NAME)
9307 (js2-parse-name tt-flagged tt))
9308 ((= tt js2-NUMBER)
9309 (make-js2-number-node))
9310 ((= tt js2-STRING)
9311 (prog1
9312 (make-js2-string-node)
9313 (js2-record-face 'font-lock-string-face)))
9314 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9315 ;; Got / or /= which in this context means a regexp literal
9316 (setq px-pos js2-token-beg)
9317 (js2-read-regexp tt)
9318 (setq flags js2-ts-regexp-flags
9319 js2-ts-regexp-flags nil)
9320 (prog1
9321 (make-js2-regexp-node :pos px-pos
9322 :len (- js2-ts-cursor px-pos)
9323 :value js2-ts-string
9324 :flags flags)
9325 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9326 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9327 ((or (= tt js2-NULL)
9328 (= tt js2-THIS)
9329 (= tt js2-FALSE)
9330 (= tt js2-TRUE))
9331 (make-js2-keyword-node :type tt))
9332 ((= tt js2-RESERVED)
9333 (js2-report-error "msg.reserved.id")
9334 (make-js2-name-node))
9335 ((= tt js2-ERROR)
9336 ;; the scanner or one of its subroutines reported the error.
9337 (make-js2-error-node))
9338 ((= tt js2-EOF)
9339 (setq px-pos (point-at-bol)
9340 len (- js2-ts-cursor px-pos))
9341 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9342 (make-js2-error-node :pos px-pos :len len))
9343 (t
9344 (js2-report-error "msg.syntax")
9345 (make-js2-error-node)))))
9346
9347 (defun js2-parse-name (tt-flagged tt)
9348 (let ((name js2-ts-string)
9349 (name-pos js2-token-beg)
9350 node)
9351 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9352 (= (js2-peek-token) js2-COLON))
9353 (prog1
9354 ;; Do not consume colon, it is used as unwind indicator
9355 ;; to return to statementHelper.
9356 (make-js2-label-node :pos name-pos
9357 :len (- js2-token-end name-pos)
9358 :name name)
9359 (js2-set-face name-pos
9360 js2-token-end
9361 'font-lock-variable-name-face 'record))
9362 ;; Otherwise not a label, just a name. Unfortunately peeking
9363 ;; the next token to check for a colon has biffed js2-token-beg
9364 ;; and js2-token-end. We store the name's bounds in buffer vars
9365 ;; and `js2-create-name-node' uses them.
9366 (js2-save-name-token-data name-pos name)
9367 (setq node (if js2-compiler-xml-available
9368 (js2-parse-property-name nil name 0)
9369 (js2-create-name-node 'check-activation)))
9370 (if js2-highlight-external-variables
9371 (js2-record-name-node node))
9372 node)))
9373
9374 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9375 (js2-add-strict-warning
9376 msg nil
9377 ;; back up from comma to beginning of line or array/objlit
9378 (max (if elems
9379 (js2-node-pos (car elems))
9380 pos)
9381 (save-excursion
9382 (goto-char comma-pos)
9383 (back-to-indentation)
9384 (point)))
9385 comma-pos))
9386
9387 (defun js2-parse-array-literal ()
9388 (let ((pos js2-token-beg)
9389 (end js2-token-end)
9390 (after-lb-or-comma t)
9391 after-comma
9392 tt
9393 elems
9394 pn
9395 (continue t))
9396 (unless js2-is-in-lhs
9397 (js2-push-scope (make-js2-scope))) ; for array comp
9398 (while continue
9399 (setq tt (js2-peek-token))
9400 (cond
9401 ;; comma
9402 ((= tt js2-COMMA)
9403 (js2-consume-token)
9404 (setq after-comma js2-token-end)
9405 (if (not after-lb-or-comma)
9406 (setq after-lb-or-comma t)
9407 (push nil elems)))
9408 ;; end of array
9409 ((or (= tt js2-RB)
9410 (= tt js2-EOF)) ; prevent infinite loop
9411 (if (= tt js2-EOF)
9412 (js2-report-error "msg.no.bracket.arg" nil pos)
9413 (js2-consume-token))
9414 (setq continue nil
9415 end js2-token-end
9416 pn (make-js2-array-node :pos pos
9417 :len (- js2-ts-cursor pos)
9418 :elems (nreverse elems)))
9419 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9420 (when (and after-comma (not js2-is-in-lhs))
9421 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9422 pos elems after-comma)))
9423 ;; destructuring binding
9424 (js2-is-in-lhs
9425 (push (if (or (= tt js2-LC)
9426 (= tt js2-LB)
9427 (= tt js2-NAME))
9428 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9429 (js2-parse-primary-expr-lhs)
9430 ;; invalid pattern
9431 (js2-consume-token)
9432 (js2-report-error "msg.bad.var")
9433 (make-js2-error-node))
9434 elems)
9435 (setq after-lb-or-comma nil
9436 after-comma nil))
9437 ;; array comp
9438 ((and (>= js2-language-version 170)
9439 (= tt js2-FOR) ; check for array comprehension
9440 (not after-lb-or-comma) ; "for" can't follow a comma
9441 elems ; must have at least 1 element
9442 (not (cdr elems))) ; but no 2nd element
9443 (setf continue nil
9444 pn (js2-parse-array-comprehension (car elems) pos)))
9445
9446 ;; another element
9447 (t
9448 (unless after-lb-or-comma
9449 (js2-report-error "msg.no.bracket.arg"))
9450 (push (js2-parse-assign-expr) elems)
9451 (setq after-lb-or-comma nil
9452 after-comma nil))))
9453 (unless js2-is-in-lhs
9454 (js2-pop-scope))
9455 pn))
9456
9457 (defun js2-parse-array-comprehension (expr pos)
9458 "Parse a JavaScript 1.7 Array Comprehension.
9459 EXPR is the first expression after the opening left-bracket.
9460 POS is the beginning of the LB token preceding EXPR.
9461 We should have just parsed the 'for' keyword before calling this function."
9462 (let (loops
9463 loop
9464 first
9465 prev
9466 filter
9467 if-pos
9468 result)
9469 (while (= (js2-peek-token) js2-FOR)
9470 (let ((prev (car loops))) ; rearrange scope chain
9471 (push (setq loop (js2-parse-array-comp-loop)) loops)
9472 (if prev ; each loop is parent scope to the next one
9473 (setf (js2-scope-parent-scope loop) prev)
9474 ; first loop takes expr scope's parent
9475 (setf (js2-scope-parent-scope (setq first loop))
9476 (js2-scope-parent-scope js2-current-scope)))))
9477 ;; set expr scope's parent to the last loop
9478 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9479 (when (= (js2-peek-token) js2-IF)
9480 (js2-consume-token)
9481 (setq if-pos (- js2-token-beg pos) ; relative
9482 filter (js2-parse-condition)))
9483 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9484 (setq result (make-js2-array-comp-node :pos pos
9485 :len (- js2-ts-cursor pos)
9486 :result expr
9487 :loops (nreverse loops)
9488 :filter (car filter)
9489 :lp (js2-relpos (second filter) pos)
9490 :rp (js2-relpos (third filter) pos)
9491 :if-pos if-pos))
9492 (apply #'js2-node-add-children result expr (car filter)
9493 (js2-array-comp-node-loops result))
9494 (setq js2-current-scope first) ; pop to the first loop
9495 result))
9496
9497 (defun js2-parse-array-comp-loop ()
9498 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9499 Last token peeked should be the initial FOR."
9500 (let ((pos js2-token-beg)
9501 (pn (make-js2-array-comp-loop-node))
9502 tt
9503 iter
9504 obj
9505 foreach-p
9506 in-pos
9507 each-pos
9508 lp
9509 rp)
9510 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9511 (js2-push-scope pn)
9512 (unwind-protect
9513 (progn
9514 (when (js2-match-token js2-NAME)
9515 (if (string= js2-ts-string "each")
9516 (progn
9517 (setq foreach-p t
9518 each-pos (- js2-token-beg pos)) ; relative
9519 (js2-record-face 'font-lock-keyword-face))
9520 (js2-report-error "msg.no.paren.for")))
9521 (if (js2-must-match js2-LP "msg.no.paren.for")
9522 (setq lp (- js2-token-beg pos)))
9523 (setq tt (js2-peek-token))
9524 (cond
9525 ((or (= tt js2-LB)
9526 (= tt js2-LC))
9527 ;; handle destructuring assignment
9528 (setq iter (js2-parse-primary-expr-lhs))
9529 (js2-define-destruct-symbols iter js2-LET
9530 'font-lock-variable-name-face t))
9531 ((js2-valid-prop-name-token tt)
9532 (js2-consume-token)
9533 (setq iter (js2-create-name-node)))
9534 (t
9535 (js2-report-error "msg.bad.var")))
9536 ;; Define as a let since we want the scope of the variable to
9537 ;; be restricted to the array comprehension
9538 (if (js2-name-node-p iter)
9539 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9540 (if (js2-must-match js2-IN "msg.in.after.for.name")
9541 (setq in-pos (- js2-token-beg pos)))
9542 (setq obj (js2-parse-expr))
9543 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9544 (setq rp (- js2-token-beg pos)))
9545 (setf (js2-node-pos pn) pos
9546 (js2-node-len pn) (- js2-ts-cursor pos)
9547 (js2-array-comp-loop-node-iterator pn) iter
9548 (js2-array-comp-loop-node-object pn) obj
9549 (js2-array-comp-loop-node-in-pos pn) in-pos
9550 (js2-array-comp-loop-node-each-pos pn) each-pos
9551 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9552 (js2-array-comp-loop-node-lp pn) lp
9553 (js2-array-comp-loop-node-rp pn) rp)
9554 (js2-node-add-children pn iter obj))
9555 (js2-pop-scope))
9556 pn))
9557
9558 (defun js2-parse-object-literal ()
9559 (let ((pos js2-token-beg)
9560 tt
9561 elems
9562 result
9563 after-comma
9564 (continue t))
9565 (while continue
9566 (setq tt (js2-peek-token))
9567 (cond
9568 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9569 ((or (js2-valid-prop-name-token tt)
9570 (= tt js2-STRING))
9571 (setq after-comma nil
9572 result (js2-parse-named-prop tt))
9573 (if (and (null result)
9574 (not js2-recover-from-parse-errors))
9575 (setq continue nil)
9576 (push result elems)))
9577 ;; {12: x} or {10.7: x}
9578 ((= tt js2-NUMBER)
9579 (js2-consume-token)
9580 (setq after-comma nil)
9581 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9582 ;; trailing comma
9583 ((= tt js2-RC)
9584 (setq continue nil)
9585 (if after-comma
9586 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9587 pos elems after-comma)))
9588 (t
9589 (js2-report-error "msg.bad.prop")
9590 (unless js2-recover-from-parse-errors
9591 (setq continue nil)))) ; end switch
9592 (if (js2-match-token js2-COMMA)
9593 (setq after-comma js2-token-end)
9594 (setq continue nil))) ; end loop
9595 (js2-must-match js2-RC "msg.no.brace.prop")
9596 (setq result (make-js2-object-node :pos pos
9597 :len (- js2-ts-cursor pos)
9598 :elems (nreverse elems)))
9599 (apply #'js2-node-add-children result (js2-object-node-elems result))
9600 result))
9601
9602 (defun js2-parse-named-prop (tt)
9603 "Parse a name, string, or getter/setter object property.
9604 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9605 (js2-consume-token)
9606 (let ((string-prop (and (= tt js2-STRING)
9607 (make-js2-string-node)))
9608 expr
9609 (ppos js2-token-beg)
9610 (pend js2-token-end)
9611 (name (js2-create-name-node))
9612 (prop js2-ts-string))
9613 (cond
9614 ;; getter/setter prop
9615 ((and (= tt js2-NAME)
9616 (= (js2-peek-token) js2-NAME)
9617 (or (string= prop "get")
9618 (string= prop "set")))
9619 (js2-consume-token)
9620 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9621 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9622 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9623 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9624 ;; abbreviated destructuring bind e.g., {a, b} = c;
9625 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9626 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9627 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9628 ;; assignment but it's difficult because it requires looking ahead of expression.
9629 ((and js2-is-in-lhs
9630 (= tt js2-NAME)
9631 (let ((ctk (js2-peek-token)))
9632 (or (= ctk js2-COMMA)
9633 (= ctk js2-RC)
9634 (js2-valid-prop-name-token ctk))))
9635 name)
9636 ;; regular prop
9637 (t
9638 (prog1
9639 (setq expr (js2-parse-plain-property (or string-prop name)))
9640 (js2-set-face ppos pend
9641 (if (js2-function-node-p
9642 (js2-object-prop-node-right expr))
9643 'font-lock-function-name-face
9644 'font-lock-variable-name-face)
9645 'record))))))
9646
9647 (defun js2-parse-plain-property (prop)
9648 "Parse a non-getter/setter property in an object literal.
9649 PROP is the node representing the property: a number, name or string."
9650 (js2-must-match js2-COLON "msg.no.colon.prop")
9651 (let* ((pos (js2-node-pos prop))
9652 (colon (- js2-token-beg pos))
9653 (expr (js2-parse-assign-expr))
9654 (result (make-js2-object-prop-node
9655 :pos pos
9656 ;; don't include last consumed token in length
9657 :len (- (+ (js2-node-pos expr)
9658 (js2-node-len expr))
9659 pos)
9660 :left prop
9661 :right expr
9662 :op-pos colon)))
9663 (js2-node-add-children result prop expr)
9664 result))
9665
9666 (defun js2-parse-getter-setter-prop (pos prop get-p)
9667 "Parse getter or setter property in an object literal.
9668 JavaScript syntax is:
9669
9670 { get foo() {...}, set foo(x) {...} }
9671
9672 and expression closure style is also supported
9673
9674 { get foo() x, set foo(x) _x = x }
9675
9676 POS is the start position of the `get' or `set' keyword.
9677 PROP is the `js2-name-node' representing the property name.
9678 GET-P is non-nil if the keyword was `get'."
9679 (let ((type (if get-p js2-GET js2-SET))
9680 result
9681 end
9682 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9683 ;; it has to be an anonymous function, as we already parsed the name
9684 (if (/= (js2-node-type fn) js2-FUNCTION)
9685 (js2-report-error "msg.bad.prop")
9686 (if (plusp (length (js2-function-name fn)))
9687 (js2-report-error "msg.bad.prop")))
9688 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9689 (setq end (js2-node-end fn)
9690 result (make-js2-getter-setter-node :type type
9691 :pos pos
9692 :len (- end pos)
9693 :left prop
9694 :right fn))
9695 (js2-node-add-children result prop fn)
9696 result))
9697
9698 (defun js2-create-name-node (&optional check-activation-p token)
9699 "Create a name node using the token info from last scanned name.
9700 In some cases we need to either synthesize a name node, or we lost
9701 the name token information by peeking. If the TOKEN parameter is
9702 not `js2-NAME', then we use the token info saved in instance vars."
9703 (let ((beg js2-token-beg)
9704 (s js2-ts-string)
9705 name)
9706 (when (/= js2-current-token js2-NAME)
9707 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9708 s js2-prev-name-token-string
9709 js2-prev-name-token-start nil
9710 js2-prev-name-token-string nil))
9711 (setq name (make-js2-name-node :pos beg
9712 :name s
9713 :len (length s)))
9714 (if check-activation-p
9715 (js2-check-activation-name s (or token js2-NAME)))
9716 name))
9717
9718 ;;; Indentation support
9719
9720 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9721 ;; Karl cleverly deduces that the desired indentation level is often a
9722 ;; function of paren/bracket/brace nesting depth, which can be determined
9723 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9724 ;; then does some equally clever checks to see if we're in the context of a
9725 ;; substatement of a possibly braceless statement keyword such as if, while,
9726 ;; or finally. This approach yields pretty good results.
9727
9728 ;; The indenter is often "wrong", however, and needs to be overridden.
9729 ;; The right long-term solution is probably to emulate (or integrate
9730 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9731 ;; parse tree from `js2-parse' is present, which is not true at the
9732 ;; moment the user is typing, computing indentation is still thousands
9733 ;; of lines of code to handle every possible syntactic edge case.
9734
9735 ;; In the meantime, the compromise solution is that we offer a "bounce
9736 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9737 ;; current line indent among various likely guess points. This approach
9738 ;; is far from perfect, but should at least make it slightly easier to
9739 ;; move the line towards its desired indentation when manually
9740 ;; overriding Karl's heuristic nesting guesser.
9741
9742 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9743 ;; extensions such as `let' and Array comprehensions. Major kudos to
9744 ;; Karl for coming up with the initial approach, which packs a lot of
9745 ;; punch for so little code.
9746
9747 (defconst js-possibly-braceless-keywords-re
9748 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9749 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9750 "try" "while" "with" "let")))
9751 "Regular expression matching keywords that are optionally
9752 followed by an opening brace.")
9753
9754 (defconst js-indent-operator-re
9755 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9756 (regexp-opt '("in" "instanceof") 'words))
9757 "Regular expression matching operators that affect indentation
9758 of continued expressions.")
9759
9760 (defconst js-declaration-keyword-re
9761 (regexp-opt '("var" "let" "const") 'words)
9762 "Regular expression matching variable declaration keywords.")
9763
9764 ;; This function has horrible results if you're typing an array
9765 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9766 ;; in conjunction with electric-indent, so just disabling it.
9767 (defsubst js2-code-at-bol-p ()
9768 "Return t if the first character on line is non-whitespace."
9769 nil)
9770
9771 (defun js2-insert-and-indent (key)
9772 "Run command bound to key and indent current line. Runs the command
9773 bound to KEY in the global keymap and indents the current line."
9774 (interactive (list (this-command-keys)))
9775 (let ((cmd (lookup-key (current-global-map) key)))
9776 (if (commandp cmd)
9777 (call-interactively cmd)))
9778 ;; don't do the electric keys inside comments or strings,
9779 ;; and don't do bounce-indent with them.
9780 (let ((parse-state (syntax-ppss (point)))
9781 (js2-bounce-indent-p (js2-code-at-bol-p)))
9782 (unless (or (nth 3 parse-state)
9783 (nth 4 parse-state))
9784 (indent-according-to-mode))))
9785
9786 (defun js-re-search-forward-inner (regexp &optional bound count)
9787 "Auxiliary function for `js-re-search-forward'."
9788 (let (parse saved-point)
9789 (while (> count 0)
9790 (re-search-forward regexp bound)
9791 (setq parse (if saved-point
9792 (parse-partial-sexp saved-point (point))
9793 (syntax-ppss (point))))
9794 (cond ((nth 3 parse)
9795 (re-search-forward
9796 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9797 (save-excursion (end-of-line) (point)) t))
9798 ((nth 7 parse)
9799 (forward-line))
9800 ((or (nth 4 parse)
9801 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9802 (re-search-forward "\\*/"))
9803 (t
9804 (setq count (1- count))))
9805 (setq saved-point (point))))
9806 (point))
9807
9808 (defun js-re-search-forward (regexp &optional bound noerror count)
9809 "Search forward but ignore strings and comments. Invokes
9810 `re-search-forward' but treats the buffer as if strings and
9811 comments have been removed."
9812 (let ((saved-point (point))
9813 (search-expr
9814 (cond ((null count)
9815 '(js-re-search-forward-inner regexp bound 1))
9816 ((< count 0)
9817 '(js-re-search-backward-inner regexp bound (- count)))
9818 ((> count 0)
9819 '(js-re-search-forward-inner regexp bound count)))))
9820 (condition-case err
9821 (eval search-expr)
9822 (search-failed
9823 (goto-char saved-point)
9824 (unless noerror
9825 (error (error-message-string err)))))))
9826
9827 (defun js-re-search-backward-inner (regexp &optional bound count)
9828 "Auxiliary function for `js-re-search-backward'."
9829 (let (parse saved-point)
9830 (while (> count 0)
9831 (re-search-backward regexp bound)
9832 (setq parse (if saved-point
9833 (parse-partial-sexp saved-point (point))
9834 (syntax-ppss (point))))
9835 (cond ((nth 3 parse)
9836 (re-search-backward
9837 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9838 (save-excursion (beginning-of-line) (point)) t))
9839 ((nth 7 parse)
9840 (goto-char (nth 8 parse)))
9841 ((or (nth 4 parse)
9842 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9843 (re-search-backward "/\\*"))
9844 (t
9845 (setq count (1- count))))))
9846 (point))
9847
9848 (defun js-re-search-backward (regexp &optional bound noerror count)
9849 "Search backward but ignore strings and comments. Invokes
9850 `re-search-backward' but treats the buffer as if strings and
9851 comments have been removed."
9852 (let ((saved-point (point))
9853 (search-expr
9854 (cond ((null count)
9855 '(js-re-search-backward-inner regexp bound 1))
9856 ((< count 0)
9857 '(js-re-search-forward-inner regexp bound (- count)))
9858 ((> count 0)
9859 '(js-re-search-backward-inner regexp bound count)))))
9860 (condition-case err
9861 (eval search-expr)
9862 (search-failed
9863 (goto-char saved-point)
9864 (unless noerror
9865 (error (error-message-string err)))))))
9866
9867 (defun js-looking-at-operator-p ()
9868 "Return non-nil if text after point is an operator (that is not
9869 a comma)."
9870 (save-match-data
9871 (and (looking-at js-indent-operator-re)
9872 (or (not (looking-at ":"))
9873 (save-excursion
9874 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9875 (looking-at "?")))))))
9876
9877 (defun js-continued-expression-p ()
9878 "Returns non-nil if the current line continues an expression."
9879 (save-excursion
9880 (back-to-indentation)
9881 (or (js-looking-at-operator-p)
9882 ;; comment
9883 (and (js-re-search-backward "\n" nil t)
9884 (progn
9885 (skip-chars-backward " \t")
9886 (unless (bolp)
9887 (backward-char)
9888 (and (js-looking-at-operator-p)
9889 (and (progn
9890 (backward-char)
9891 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9892
9893 (defun js-end-of-do-while-loop-p ()
9894 "Returns non-nil if word after point is `while' of a do-while
9895 statement, else returns nil. A braceless do-while statement
9896 spanning several lines requires that the start of the loop is
9897 indented to the same column as the current line."
9898 (interactive)
9899 (save-excursion
9900 (save-match-data
9901 (when (looking-at "\\s-*\\<while\\>")
9902 (if (save-excursion
9903 (skip-chars-backward "[ \t\n]*}")
9904 (looking-at "[ \t\n]*}"))
9905 (save-excursion
9906 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9907 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9908 (or (looking-at "\\<do\\>")
9909 (let ((saved-indent (current-indentation)))
9910 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9911 (/= (current-indentation) saved-indent)))
9912 (and (looking-at "[ \t]*\\<do\\>")
9913 (not (js-re-search-forward
9914 "\\<while\\>" (point-at-eol) t))
9915 (= (current-indentation) saved-indent)))))))))
9916
9917 (defun js-multiline-decl-indentation ()
9918 "Returns the declaration indentation column if the current line belongs
9919 to a multiline declaration statement. All declarations are lined up vertically:
9920
9921 var a = 10,
9922 b = 20,
9923 c = 30;
9924
9925 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9926 assigned expression is a function or array/object literal, it will be indented
9927 differently:
9928
9929 var o = { var bar = 2,
9930 foo: 3 o = {
9931 }, foo: 3
9932 bar = 2; };
9933 "
9934 (let (forward-sexp-function ; use lisp version
9935 at-opening-bracket)
9936 (save-excursion
9937 (back-to-indentation)
9938 (when (not (looking-at js-declaration-keyword-re))
9939 (when (looking-at js-indent-operator-re)
9940 (goto-char (match-end 0))) ; continued expressions are ok
9941 (while (and (not at-opening-bracket)
9942 (not (bobp))
9943 (let ((pos (point)))
9944 (save-excursion
9945 (js2-backward-sws)
9946 (or (eq (char-before) ?,)
9947 (and (not (eq (char-before) ?\;))
9948 (and
9949 (prog2 (skip-chars-backward "[[:punct:]]")
9950 (looking-at js-indent-operator-re)
9951 (js2-backward-sws))
9952 (not (eq (char-before) ?\;))))
9953 (js2-same-line pos)))))
9954 (condition-case err
9955 (backward-sexp)
9956 (scan-error (setq at-opening-bracket t))))
9957 (when (looking-at js-declaration-keyword-re)
9958 (- (1+ (match-end 0)) (point-at-bol)))))))
9959
9960 (defun js-ctrl-statement-indentation ()
9961 "Returns the proper indentation of the current line if it
9962 starts the body of a control statement without braces, else
9963 returns nil."
9964 (let (forward-sexp-function) ; temporarily unbind it
9965 (save-excursion
9966 (back-to-indentation)
9967 (when (and (not (js2-same-line (point-min)))
9968 (not (looking-at "{"))
9969 (js-re-search-backward "[[:graph:]]" nil t)
9970 (not (looking-at "[{([]"))
9971 (progn
9972 (forward-char)
9973 (when (= (char-before) ?\))
9974 ;; scan-sexps sometimes throws an error
9975 (ignore-errors (backward-sexp))
9976 (skip-chars-backward " \t" (point-at-bol)))
9977 (let ((pt (point)))
9978 (back-to-indentation)
9979 (and (looking-at js-possibly-braceless-keywords-re)
9980 (= (match-end 0) pt)
9981 (not (js-end-of-do-while-loop-p))))))
9982 (+ (current-indentation) js2-basic-offset)))))
9983
9984 (defun js2-indent-in-array-comp (parse-status)
9985 "Return non-nil if we think we're in an array comprehension.
9986 In particular, return the buffer position of the first `for' kwd."
9987 (let ((end (point)))
9988 (when (nth 1 parse-status)
9989 (save-excursion
9990 (goto-char (nth 1 parse-status))
9991 (when (looking-at "\\[")
9992 (forward-char 1)
9993 (js2-forward-sws)
9994 (if (looking-at "[[{]")
9995 (let (forward-sexp-function) ; use lisp version
9996 (forward-sexp) ; skip destructuring form
9997 (js2-forward-sws)
9998 (if (and (/= (char-after) ?,) ; regular array
9999 (looking-at "for"))
10000 (match-beginning 0)))
10001 ;; to skip arbitrary expressions we need the parser,
10002 ;; so we'll just guess at it.
10003 (if (and (> end (point)) ; not empty literal
10004 (re-search-forward "[^,]]* \\(for\\) " end t))
10005 (match-beginning 1))))))))
10006
10007 (defun js2-array-comp-indentation (parse-status for-kwd)
10008 (if (js2-same-line for-kwd)
10009 ;; first continuation line
10010 (save-excursion
10011 (goto-char (nth 1 parse-status))
10012 (forward-char 1)
10013 (skip-chars-forward " \t")
10014 (current-column))
10015 (save-excursion
10016 (goto-char for-kwd)
10017 (current-column))))
10018
10019 (defun js-proper-indentation (parse-status)
10020 "Return the proper indentation for the current line."
10021 (save-excursion
10022 (back-to-indentation)
10023 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10024 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10025 (continued-expr-p (js-continued-expression-p))
10026 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10027 (js-multiline-decl-indentation)))
10028 (bracket (nth 1 parse-status))
10029 beg)
10030 (cond
10031 ;; indent array comprehension continuation lines specially
10032 ((and bracket
10033 (not (js2-same-line bracket))
10034 (setq beg (js2-indent-in-array-comp parse-status))
10035 (>= (point) (save-excursion
10036 (goto-char beg)
10037 (point-at-bol)))) ; at or after first loop?
10038 (js2-array-comp-indentation parse-status beg))
10039
10040 (ctrl-stmt-indent)
10041
10042 ((and declaration-indent continued-expr-p)
10043 (+ declaration-indent js2-basic-offset))
10044
10045 (declaration-indent)
10046
10047 (bracket
10048 (goto-char bracket)
10049 (cond
10050 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10051 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10052 (when (save-excursion (skip-chars-backward " \t)")
10053 (looking-at ")"))
10054 (backward-list))
10055 (if (and (nth 1 p)
10056 (not js2-consistent-level-indent-inner-bracket-p))
10057 (progn (goto-char (1+ (nth 1 p)))
10058 (skip-chars-forward " \t"))
10059 (back-to-indentation)
10060 (when (and js2-pretty-multiline-decl-indentation-p
10061 js2-always-indent-assigned-expr-in-decls-p
10062 (looking-at js-declaration-keyword-re))
10063 (goto-char (1+ (match-end 0)))))
10064 (cond (same-indent-p
10065 (current-column))
10066 (continued-expr-p
10067 (+ (current-column) (* 2 js2-basic-offset)))
10068 (t
10069 (+ (current-column) js2-basic-offset)))))
10070 (t
10071 (unless same-indent-p
10072 (forward-char)
10073 (skip-chars-forward " \t"))
10074 (current-column))))
10075
10076 (continued-expr-p js2-basic-offset)
10077
10078 (t 0)))))
10079
10080 (defun js2-lineup-comment (parse-status)
10081 "Indent a multi-line block comment continuation line."
10082 (let* ((beg (nth 8 parse-status))
10083 (first-line (js2-same-line beg))
10084 (offset (save-excursion
10085 (goto-char beg)
10086 (if (looking-at "/\\*")
10087 (+ 1 (current-column))
10088 0))))
10089 (unless first-line
10090 (indent-line-to offset))))
10091
10092 (defun js2-backward-sws ()
10093 "Move backward through whitespace and comments."
10094 (interactive)
10095 (while (forward-comment -1)))
10096
10097 (defun js2-forward-sws ()
10098 "Move forward through whitespace and comments."
10099 (interactive)
10100 (while (forward-comment 1)))
10101
10102 (defsubst js2-current-indent (&optional pos)
10103 "Return column of indentation on current line.
10104 If POS is non-nil, go to that point and return indentation for that line."
10105 (save-excursion
10106 (if pos
10107 (goto-char pos))
10108 (back-to-indentation)
10109 (current-column)))
10110
10111 (defsubst js2-arglist-close ()
10112 "Return non-nil if we're on a line beginning with a close-paren/brace."
10113 (save-match-data
10114 (save-excursion
10115 (goto-char (point-at-bol))
10116 (js2-forward-sws)
10117 (looking-at "[])}]"))))
10118
10119 (defsubst js2-indent-looks-like-label-p ()
10120 (goto-char (point-at-bol))
10121 (js2-forward-sws)
10122 (looking-at (concat js2-mode-identifier-re ":")))
10123
10124 (defun js2-indent-in-objlit-p (parse-status)
10125 "Return non-nil if this looks like an object-literal entry."
10126 (let ((start (nth 1 parse-status)))
10127 (and
10128 start
10129 (save-excursion
10130 (and (zerop (forward-line -1))
10131 (not (< (point) start)) ; crossed a {} boundary
10132 (js2-indent-looks-like-label-p)))
10133 (save-excursion
10134 (js2-indent-looks-like-label-p)))))
10135
10136 ;; if prev line looks like foobar({ then we're passing an object
10137 ;; literal to a function call, and people pretty much always want to
10138 ;; de-dent back to the previous line, so move the 'basic-offset'
10139 ;; position to the front.
10140 (defsubst js2-indent-objlit-arg-p (parse-status)
10141 (save-excursion
10142 (back-to-indentation)
10143 (js2-backward-sws)
10144 (and (eq (1- (point)) (nth 1 parse-status))
10145 (eq (char-before) ?{)
10146 (progn
10147 (forward-char -1)
10148 (skip-chars-backward " \t")
10149 (eq (char-before) ?\()))))
10150
10151 (defsubst js2-indent-case-block-p ()
10152 (save-excursion
10153 (back-to-indentation)
10154 (js2-backward-sws)
10155 (goto-char (point-at-bol))
10156 (skip-chars-forward " \t")
10157 (save-match-data
10158 (looking-at "case\\s-.+:"))))
10159
10160 (defsubst js2-syntax-bol ()
10161 "Return the point at the first non-whitespace char on the line.
10162 Returns `point-at-bol' if the line is empty."
10163 (save-excursion
10164 (beginning-of-line)
10165 (skip-chars-forward " \t")
10166 (point)))
10167
10168 (defun js2-bounce-indent (normal-col parse-status backwards)
10169 "Cycle among alternate computed indentation positions.
10170 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10171 of the buffer to the current point. NORMAL-COL is the indentation
10172 column computed by the heuristic guesser based on current paren,
10173 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10174 in reverse."
10175 (let ((cur-indent (js2-current-indent))
10176 (old-buffer-undo-list buffer-undo-list)
10177 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10178 (current-line (save-excursion
10179 (forward-line 0) ; move to bol
10180 (1+ (count-lines (point-min) (point)))))
10181 positions
10182 pos
10183 main-pos
10184 anchor
10185 arglist-cont
10186 same-indent
10187 prev-line-col
10188 basic-offset
10189 computed-pos)
10190 ;; temporarily don't record undo info, if user requested this
10191 (if js2-mode-indent-inhibit-undo
10192 (setq buffer-undo-list t))
10193 (unwind-protect
10194 (progn
10195 ;; first likely point: indent from beginning of previous code line
10196 (push (setq basic-offset
10197 (+ (save-excursion
10198 (back-to-indentation)
10199 (js2-backward-sws)
10200 (back-to-indentation)
10201 (setq prev-line-col (current-column)))
10202 js2-basic-offset))
10203 positions)
10204
10205 ;; (first + epsilon) likely point: indent 2x from beginning of
10206 ;; previous code line. Some companies like this approach. Ahem.
10207 ;; Seriously, though -- 4-space indent for expression continuation
10208 ;; lines isn't a bad idea. We should eventually implement it
10209 ;; that way.
10210 (push (setq basic-offset
10211 (+ (save-excursion
10212 (back-to-indentation)
10213 (js2-backward-sws)
10214 (back-to-indentation)
10215 (setq prev-line-col (current-column)))
10216 (* 2 js2-basic-offset)))
10217 positions)
10218
10219 ;; second likely point: indent from assign-expr RHS. This
10220 ;; is just a crude guess based on finding " = " on the previous
10221 ;; line containing actual code.
10222 (setq pos (save-excursion
10223 (save-match-data
10224 (forward-line -1)
10225 (goto-char (point-at-bol))
10226 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10227 (point-at-eol) t)
10228 (goto-char (match-end 1))
10229 (skip-chars-forward " \t\r\n")
10230 (current-column)))))
10231 (when pos
10232 (incf pos js2-basic-offset)
10233 (push pos positions))
10234
10235 ;; third likely point: same indent as previous line of code.
10236 ;; Make it the first likely point if we're not on an
10237 ;; arglist-close line and previous line ends in a comma, or
10238 ;; both this line and prev line look like object-literal
10239 ;; elements.
10240 (setq pos (save-excursion
10241 (goto-char (point-at-bol))
10242 (js2-backward-sws)
10243 (back-to-indentation)
10244 (prog1
10245 (current-column)
10246 ;; while we're here, look for trailing comma
10247 (if (save-excursion
10248 (goto-char (point-at-eol))
10249 (js2-backward-sws)
10250 (eq (char-before) ?,))
10251 (setq arglist-cont (1- (point)))))))
10252 (when pos
10253 (if (and (or arglist-cont
10254 (js2-indent-in-objlit-p parse-status))
10255 (not (js2-arglist-close)))
10256 (setq same-indent pos))
10257 (push pos positions))
10258
10259 ;; fourth likely point: first preceding code with less indentation
10260 ;; than the immediately preceding code line.
10261 (setq pos (save-excursion
10262 (back-to-indentation)
10263 (js2-backward-sws)
10264 (back-to-indentation)
10265 (setq anchor (current-column))
10266 (while (and (zerop (forward-line -1))
10267 (>= (progn
10268 (back-to-indentation)
10269 (current-column))
10270 anchor)))
10271 (setq pos (current-column))))
10272 (push pos positions)
10273
10274 ;; nesting-heuristic position, main by default
10275 (push (setq main-pos normal-col) positions)
10276
10277 ;; delete duplicates and sort positions list
10278 (setq positions (sort (delete-dups positions) '<))
10279
10280 ;; comma-list continuation lines: prev line indent takes precedence
10281 (if same-indent
10282 (setq main-pos same-indent))
10283
10284 ;; common special cases where we want to indent in from previous line
10285 (if (or (js2-indent-case-block-p)
10286 (js2-indent-objlit-arg-p parse-status))
10287 (setq main-pos basic-offset))
10288
10289 ;; if bouncing backwards, reverse positions list
10290 (if backwards
10291 (setq positions (reverse positions)))
10292
10293 ;; record whether we're already sitting on one of the alternatives
10294 (setq pos (member cur-indent positions))
10295
10296 (cond
10297 ;; case 0: we're one one of the alternatives and this is the
10298 ;; first time they've pressed TAB on this line (best-guess).
10299 ((and js2-mode-indent-ignore-first-tab
10300 pos
10301 ;; first time pressing TAB on this line?
10302 (not (eq js2-mode-last-indented-line current-line)))
10303 ;; do nothing
10304 (setq computed-pos nil))
10305 ;; case 1: only one computed position => use it
10306 ((null (cdr positions))
10307 (setq computed-pos 0))
10308 ;; case 2: not on any of the computed spots => use main spot
10309 ((not pos)
10310 (setq computed-pos (js2-position main-pos positions)))
10311 ;; case 3: on last position: cycle to first position
10312 ((null (cdr pos))
10313 (setq computed-pos 0))
10314 ;; case 4: on intermediate position: cycle to next position
10315 (t
10316 (setq computed-pos (js2-position (second pos) positions))))
10317
10318 ;; see if any hooks want to indent; otherwise we do it
10319 (loop with result = nil
10320 for hook in js2-indent-hook
10321 while (null result)
10322 do
10323 (setq result (funcall hook positions computed-pos))
10324 finally do
10325 (unless (or result (null computed-pos))
10326 (indent-line-to (nth computed-pos positions)))))
10327
10328 ;; finally
10329 (if js2-mode-indent-inhibit-undo
10330 (setq buffer-undo-list old-buffer-undo-list))
10331 ;; see commentary for `js2-mode-last-indented-line'
10332 (setq js2-mode-last-indented-line current-line))))
10333
10334 (defun js2-indent-bounce-backwards ()
10335 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10336 cycles between the computed indentation positions in reverse order."
10337 (interactive)
10338 (js2-indent-line t))
10339
10340 (defsubst js2-1-line-comment-continuation-p ()
10341 "Return t if we're in a 1-line comment continuation.
10342 If so, we don't ever want to use bounce-indent."
10343 (save-excursion
10344 (save-match-data
10345 (and (progn
10346 (forward-line 0)
10347 (looking-at "\\s-*//"))
10348 (progn
10349 (forward-line -1)
10350 (forward-line 0)
10351 (when (looking-at "\\s-*$")
10352 (js2-backward-sws)
10353 (forward-line 0))
10354 (looking-at "\\s-*//"))))))
10355
10356 (defun js2-indent-line (&optional bounce-backwards)
10357 "Indent the current line as JavaScript source text."
10358 (interactive)
10359 (let (parse-status
10360 offset
10361 indent-col
10362 moved
10363 ;; don't whine about errors/warnings when we're indenting.
10364 ;; This has to be set before calling parse-partial-sexp below.
10365 (inhibit-point-motion-hooks t))
10366 (setq parse-status (save-excursion
10367 (syntax-ppss (point-at-bol)))
10368 offset (- (point) (save-excursion
10369 (back-to-indentation)
10370 (point))))
10371 (js2-with-underscore-as-word-syntax
10372 (if (nth 4 parse-status)
10373 (js2-lineup-comment parse-status)
10374 (setq indent-col (js-proper-indentation parse-status))
10375 ;; see comments below about js2-mode-last-indented-line
10376 (cond
10377 ;; bounce-indenting is disabled during electric-key indent.
10378 ;; It doesn't work well on first line of buffer.
10379 ((and js2-bounce-indent-p
10380 (not (js2-same-line (point-min)))
10381 (not (js2-1-line-comment-continuation-p)))
10382 (js2-bounce-indent indent-col parse-status bounce-backwards))
10383 ;; just indent to the guesser's likely spot
10384 (t (indent-line-to indent-col)))
10385 (when (plusp offset)
10386 (forward-char offset))))))
10387
10388 (defun js2-indent-region (start end)
10389 "Indent the region, but don't use bounce indenting."
10390 (let ((js2-bounce-indent-p nil)
10391 (indent-region-function nil)
10392 (after-change-functions (remq 'js2-mode-edit
10393 after-change-functions)))
10394 (indent-region start end nil) ; nil for byte-compiler
10395 (js2-mode-edit start end (- end start))))
10396
10397 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10398
10399 ;;;###autoload
10400 (defun js2-mode ()
10401 "Major mode for editing JavaScript code."
10402 (interactive)
10403 (kill-all-local-variables)
10404 (set-syntax-table js2-mode-syntax-table)
10405 (use-local-map js2-mode-map)
10406 (make-local-variable 'comment-start)
10407 (make-local-variable 'comment-end)
10408 (make-local-variable 'comment-start-skip)
10409 (setq major-mode 'js2-mode
10410 mode-name "JavaScript-IDE"
10411 comment-start "//" ; used by comment-region; don't change it
10412 comment-end "")
10413 (setq local-abbrev-table js2-mode-abbrev-table)
10414 (set (make-local-variable 'max-lisp-eval-depth)
10415 (max max-lisp-eval-depth 3000))
10416 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10417 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10418
10419 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10420 ;; on most platforms other than the one I originally wrote it on. So it's
10421 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10422 ;; with our binding of the RET key inside comments: short lines stay short.
10423 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10424
10425 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10426 (set (make-local-variable 'next-error-function) #'js2-next-error)
10427 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10428 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10429 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10430 ;; for characters inside regexp literals.
10431 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10432 ;; this is necessary to make `show-paren-function' work properly
10433 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10434 ;; needed for M-x rgrep, among other things
10435 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10436
10437 ;; some variables needed by cc-engine for paragraph-fill, etc.
10438 (setq c-buffer-is-cc-mode t
10439 c-comment-prefix-regexp js2-comment-prefix-regexp
10440 c-comment-start-regexp "/[*/]\\|\\s|"
10441 c-paragraph-start js2-paragraph-start
10442 c-paragraph-separate "$"
10443 comment-start-skip js2-comment-start-skip
10444 c-syntactic-ws-start js2-syntactic-ws-start
10445 c-syntactic-ws-end js2-syntactic-ws-end
10446 c-syntactic-eol js2-syntactic-eol)
10447
10448 (setq js2-default-externs
10449 (append js2-ecma-262-externs
10450 (if js2-include-browser-externs
10451 js2-browser-externs)
10452 (if js2-include-gears-externs
10453 js2-gears-externs)
10454 (if js2-include-rhino-externs
10455 js2-rhino-externs)))
10456
10457 ;; We do our own syntax highlighting based on the parse tree.
10458 ;; However, we want minor modes that add keywords to highlight properly
10459 ;; (examples: doxymacs, column-marker). We do this by not letting
10460 ;; font-lock unfontify anything, and telling it to fontify after we
10461 ;; re-parse and re-highlight the buffer. (We currently don't do any
10462 ;; work with regions other than the whole buffer.)
10463 (dolist (var '(font-lock-unfontify-buffer-function
10464 font-lock-unfontify-region-function))
10465 (set (make-local-variable var) (lambda (&rest args) t)))
10466
10467 ;; Don't let font-lock do syntactic (string/comment) fontification.
10468 (set (make-local-variable #'font-lock-syntactic-face-function)
10469 (lambda (state) nil))
10470
10471 ;; Experiment: make reparse-delay longer for longer files.
10472 (if (plusp js2-dynamic-idle-timer-adjust)
10473 (setq js2-idle-timer-delay
10474 (* js2-idle-timer-delay
10475 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10476
10477 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10478 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10479 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10480 (imenu-add-to-menubar (concat "IM-" mode-name))
10481 (when js2-mirror-mode
10482 (js2-enter-mirror-mode))
10483 (add-to-invisibility-spec '(js2-outline . t))
10484 (set (make-local-variable 'line-move-ignore-invisible) t)
10485 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10486
10487 (if (fboundp 'run-mode-hooks)
10488 (run-mode-hooks 'js2-mode-hook)
10489 (run-hooks 'js2-mode-hook))
10490
10491 (setq js2-mode-functions-hidden nil
10492 js2-mode-comments-hidden nil
10493 js2-mode-buffer-dirty-p t
10494 js2-mode-parsing nil)
10495 (js2-reparse))
10496
10497 (defun js2-mode-exit ()
10498 "Exit `js2-mode' and clean up."
10499 (interactive)
10500 (when js2-mode-node-overlay
10501 (delete-overlay js2-mode-node-overlay)
10502 (setq js2-mode-node-overlay nil))
10503 (js2-remove-overlays)
10504 (setq js2-mode-ast nil)
10505 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10506 (remove-from-invisibility-spec '(js2-outline . t))
10507 (js2-mode-show-all)
10508 (js2-with-unmodifying-text-property-changes
10509 (js2-clear-face (point-min) (point-max))))
10510
10511 (defun js2-before-save ()
10512 "Clean up whitespace before saving file.
10513 You can disable this by customizing `js2-cleanup-whitespace'."
10514 (when js2-cleanup-whitespace
10515 (let ((col (current-column)))
10516 (delete-trailing-whitespace)
10517 ;; don't change trailing whitespace on current line
10518 (unless (eq (current-column) col)
10519 (indent-to col)))))
10520
10521 (defsubst js2-mode-reset-timer ()
10522 "Cancel any existing parse timer and schedule a new one."
10523 (if js2-mode-parse-timer
10524 (cancel-timer js2-mode-parse-timer))
10525 (setq js2-mode-parsing nil)
10526 (setq js2-mode-parse-timer
10527 (run-with-idle-timer js2-idle-timer-delay nil
10528 #'js2-mode-idle-reparse (current-buffer))))
10529
10530 (defun js2-mode-idle-reparse (buffer)
10531 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10532 it to be reparsed when the buffer is selected."
10533 (if (eq buffer (current-buffer))
10534 (js2-reparse)
10535 ;; reparse when the buffer is selected again
10536 (with-current-buffer buffer
10537 (add-hook 'window-configuration-change-hook
10538 #'js2-mode-idle-reparse-inner
10539 t))))
10540
10541 (defun js2-mode-idle-reparse-inner ()
10542 (remove-hook 'window-configuration-change-hook
10543 #'js2-mode-idle-reparse-inner
10544 t)
10545 (js2-reparse))
10546
10547 (defun js2-mode-edit (beg end len)
10548 "Schedule a new parse after buffer is edited.
10549 Buffer edit spans from BEG to END and is of length LEN.
10550 Also clears the `js2-magic' bit on autoinserted parens/brackets
10551 if the edit occurred on a line different from the magic paren."
10552 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10553 (line (if magic-pos (line-number-at-pos magic-pos))))
10554 (and line
10555 (or (/= (line-number-at-pos beg) line)
10556 (and (> 0 len)
10557 (/= (line-number-at-pos end) line)))
10558 (js2-mode-mundanify-parens)))
10559 (setq js2-mode-buffer-dirty-p t)
10560 (js2-mode-hide-overlay)
10561 (js2-mode-reset-timer))
10562
10563 (defun js2-mode-run-font-lock ()
10564 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10565 This is intended to allow modes that install their own font-lock keywords
10566 to work with js2-mode. In practice it never seems to work for long.
10567 Hopefully the Emacs maintainers can help figure out a way to make it work."
10568 (when (and (boundp 'font-lock-keywords)
10569 font-lock-keywords
10570 (boundp 'font-lock-mode)
10571 font-lock-mode)
10572 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10573 ;; play nicely with js2-mode. They go out of their way to fail to
10574 ;; provide any option for saying "look, fontify the farging buffer
10575 ;; with just the keywords already". Argh.
10576 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10577 (let (font-lock-verbose)
10578 (font-lock-fontify-buffer))))
10579
10580 (defun js2-reparse (&optional force)
10581 "Re-parse current buffer after user finishes some data entry.
10582 If we get any user input while parsing, including cursor motion,
10583 we discard the parse and reschedule it. If FORCE is nil, then the
10584 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10585 (let (time
10586 interrupted-p
10587 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10588 (unless js2-mode-parsing
10589 (setq js2-mode-parsing t)
10590 (unwind-protect
10591 (when (or js2-mode-buffer-dirty-p force)
10592 (js2-remove-overlays)
10593 (js2-with-unmodifying-text-property-changes
10594 (setq js2-mode-buffer-dirty-p nil
10595 js2-mode-fontifications nil
10596 js2-mode-deferred-properties nil)
10597 (if js2-mode-verbose-parse-p
10598 (message "parsing..."))
10599 (setq time
10600 (js2-time
10601 (setq interrupted-p
10602 (catch 'interrupted
10603 (setq js2-mode-ast (js2-parse))
10604 ;; if parsing is interrupted, comments and regex
10605 ;; literals stay ignored by `parse-partial-sexp'
10606 (remove-text-properties (point-min) (point-max)
10607 '(syntax-table))
10608 (js2-mode-apply-deferred-properties)
10609 (js2-mode-remove-suppressed-warnings)
10610 (js2-mode-show-warnings)
10611 (js2-mode-show-errors)
10612 (js2-mode-run-font-lock) ; note: doesn't work
10613 (js2-mode-highlight-magic-parens)
10614 (if (>= js2-highlight-level 1)
10615 (js2-highlight-jsdoc js2-mode-ast))
10616 nil))))
10617 (if interrupted-p
10618 (progn
10619 ;; unfinished parse => try again
10620 (setq js2-mode-buffer-dirty-p t)
10621 (js2-mode-reset-timer))
10622 (if js2-mode-verbose-parse-p
10623 (message "Parse time: %s" time)))))
10624 (setq js2-mode-parsing nil)
10625 (unless interrupted-p
10626 (setq js2-mode-parse-timer nil))))))
10627
10628 (defun js2-mode-show-node ()
10629 "Debugging aid: highlight selected AST node on mouse click."
10630 (interactive)
10631 (let ((node (js2-node-at-point))
10632 beg
10633 end)
10634 (when js2-mode-show-overlay
10635 (if (null node)
10636 (message "No node found at location %s" (point))
10637 (setq beg (js2-node-abs-pos node)
10638 end (+ beg (js2-node-len node)))
10639 (if js2-mode-node-overlay
10640 (move-overlay js2-mode-node-overlay beg end)
10641 (setq js2-mode-node-overlay (make-overlay beg end))
10642 (overlay-put js2-mode-node-overlay 'face 'highlight))
10643 (js2-with-unmodifying-text-property-changes
10644 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10645 (message "%s, parent: %s"
10646 (js2-node-short-name node)
10647 (if (js2-node-parent node)
10648 (js2-node-short-name (js2-node-parent node))
10649 "nil"))))))
10650
10651 (defun js2-mode-hide-overlay (&optional p1 p2)
10652 "Remove the debugging overlay when the point moves.
10653 P1 and P2 are the old and new values of point, respectively."
10654 (when js2-mode-node-overlay
10655 (let ((beg (overlay-start js2-mode-node-overlay))
10656 (end (overlay-end js2-mode-node-overlay)))
10657 ;; Sometimes we're called spuriously.
10658 (unless (and p2
10659 (>= p2 beg)
10660 (<= p2 end))
10661 (js2-with-unmodifying-text-property-changes
10662 (remove-text-properties beg end '(point-left nil)))
10663 (delete-overlay js2-mode-node-overlay)
10664 (setq js2-mode-node-overlay nil)))))
10665
10666 (defun js2-mode-reset ()
10667 "Debugging helper: reset everything."
10668 (interactive)
10669 (js2-mode-exit)
10670 (js2-mode))
10671
10672 (defsubst js2-mode-show-warn-or-err (e face)
10673 "Highlight a warning or error E with FACE.
10674 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10675 (let* ((key (first e))
10676 (beg (second e))
10677 (end (+ beg (third e)))
10678 ;; Don't inadvertently go out of bounds.
10679 (beg (max (point-min) (min beg (point-max))))
10680 (end (max (point-min) (min end (point-max))))
10681 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10682 (ovl (make-overlay beg end)))
10683 (overlay-put ovl 'face face)
10684 (overlay-put ovl 'js2-error t)
10685 (put-text-property beg end 'help-echo (js2-get-msg key))
10686 (put-text-property beg end 'point-entered #'js2-echo-error)))
10687
10688 (defun js2-remove-overlays ()
10689 "Remove overlays from buffer that have a `js2-error' property."
10690 (let ((beg (point-min))
10691 (end (point-max)))
10692 (save-excursion
10693 (dolist (o (overlays-in beg end))
10694 (when (overlay-get o 'js2-error)
10695 (delete-overlay o))))))
10696
10697 (defun js2-error-at-point (&optional pos)
10698 "Return non-nil if there's an error overlay at POS.
10699 Defaults to point."
10700 (loop with pos = (or pos (point))
10701 for o in (overlays-at pos)
10702 thereis (overlay-get o 'js2-error)))
10703
10704 (defun js2-mode-apply-deferred-properties ()
10705 "Apply fontifications and other text properties recorded during parsing."
10706 (when (plusp js2-highlight-level)
10707 ;; We defer clearing faces as long as possible to eliminate flashing.
10708 (js2-clear-face (point-min) (point-max))
10709 ;; Have to reverse the recorded fontifications list so that errors
10710 ;; and warnings overwrite the normal fontifications.
10711 (dolist (f (nreverse js2-mode-fontifications))
10712 (put-text-property (first f) (second f) 'face (third f)))
10713 (setq js2-mode-fontifications nil))
10714 (dolist (p js2-mode-deferred-properties)
10715 (apply #'put-text-property p))
10716 (setq js2-mode-deferred-properties nil))
10717
10718 (defun js2-mode-show-errors ()
10719 "Highlight syntax errors."
10720 (when js2-mode-show-parse-errors
10721 (dolist (e (js2-ast-root-errors js2-mode-ast))
10722 (js2-mode-show-warn-or-err e 'js2-error-face))))
10723
10724 (defun js2-mode-remove-suppressed-warnings ()
10725 "Take suppressed warnings out of the AST warnings list.
10726 This ensures that the counts and `next-error' are correct."
10727 (setf (js2-ast-root-warnings js2-mode-ast)
10728 (js2-delete-if
10729 (lambda (e)
10730 (let ((key (caar e)))
10731 (or
10732 (and (not js2-strict-trailing-comma-warning)
10733 (string-match "trailing\\.comma" key))
10734 (and (not js2-strict-cond-assign-warning)
10735 (string= key "msg.equal.as.assign"))
10736 (and js2-missing-semi-one-line-override
10737 (string= key "msg.missing.semi")
10738 (let* ((beg (second e))
10739 (node (js2-node-at-point beg))
10740 (fn (js2-mode-find-parent-fn node))
10741 (body (and fn (js2-function-node-body fn)))
10742 (lc (and body (js2-node-abs-pos body)))
10743 (rc (and lc (+ lc (js2-node-len body)))))
10744 (and fn
10745 (or (null body)
10746 (save-excursion
10747 (goto-char beg)
10748 (and (js2-same-line lc)
10749 (js2-same-line rc))))))))))
10750 (js2-ast-root-warnings js2-mode-ast))))
10751
10752 (defun js2-mode-show-warnings ()
10753 "Highlight strict-mode warnings."
10754 (when js2-mode-show-strict-warnings
10755 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10756 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10757
10758 (defun js2-echo-error (old-point new-point)
10759 "Called by point-motion hooks."
10760 (let ((msg (get-text-property new-point 'help-echo)))
10761 (if (and msg (or (not (current-message))
10762 (string= (current-message) "Quit")))
10763 (message msg))))
10764
10765 (defalias #'js2-echo-help #'js2-echo-error)
10766
10767 (defun js2-enter-key ()
10768 "Handle user pressing the Enter key."
10769 (interactive)
10770 (let ((parse-status (save-excursion
10771 (syntax-ppss (point))))
10772 (js2-bounce-indent-p nil))
10773 (cond
10774 ;; check if we're inside a string
10775 ((nth 3 parse-status)
10776 (js2-mode-split-string parse-status))
10777 ;; check if inside a block comment
10778 ((nth 4 parse-status)
10779 (js2-mode-extend-comment))
10780 (t
10781 ;; should probably figure out what the mode-map says we should do
10782 (if js2-indent-on-enter-key
10783 (js2-indent-line))
10784 (insert "\n")
10785 (if js2-enter-indents-newline
10786 (js2-indent-line))))))
10787
10788 (defun js2-mode-split-string (parse-status)
10789 "Turn a newline in mid-string into a string concatenation.
10790 PARSE-STATUS is as documented in `parse-partial-sexp'."
10791 (let* ((col (current-column))
10792 (quote-char (nth 3 parse-status))
10793 (quote-string (string quote-char))
10794 (string-beg (nth 8 parse-status))
10795 (indent (save-match-data
10796 (or
10797 (save-excursion
10798 (back-to-indentation)
10799 (if (looking-at "\\+")
10800 (current-column)))
10801 (save-excursion
10802 (goto-char string-beg)
10803 (if (looking-back "\\+\\s-+")
10804 (goto-char (match-beginning 0)))
10805 (current-column))))))
10806 (insert quote-char "\n")
10807 (indent-to indent)
10808 (insert "+ " quote-string)
10809 (when (eolp)
10810 (insert quote-string)
10811 (backward-char 1))))
10812
10813 (defun js2-mode-extend-comment ()
10814 "Indent the line and, when inside a comment block, add comment prefix."
10815 (let (star single col first-line needs-close)
10816 (save-excursion
10817 (back-to-indentation)
10818 (cond
10819 ((looking-at "\\*[^/]")
10820 (setq star t
10821 col (current-column)))
10822 ((looking-at "/\\*")
10823 (setq star t
10824 first-line t
10825 col (1+ (current-column))))
10826 ((looking-at "//")
10827 (setq single t
10828 col (current-column)))))
10829 ;; Heuristic for whether we need to close the comment:
10830 ;; if we've got a parse error here, assume it's an unterminated
10831 ;; comment.
10832 (setq needs-close
10833 (or
10834 (eq (get-text-property (1- (point)) 'point-entered)
10835 'js2-echo-error)
10836 ;; The heuristic above doesn't work well when we're
10837 ;; creating a comment and there's another one downstream,
10838 ;; as our parser thinks this one ends at the end of the
10839 ;; next one. (You can have a /* inside a js block comment.)
10840 ;; So just close it if the next non-ws char isn't a *.
10841 (and first-line
10842 (eolp)
10843 (save-excursion
10844 (skip-chars-forward " \t\r\n")
10845 (not (eq (char-after) ?*))))))
10846 (insert "\n")
10847 (cond
10848 (star
10849 (indent-to col)
10850 (insert "* ")
10851 (if (and first-line needs-close)
10852 (save-excursion
10853 (insert "\n")
10854 (indent-to col)
10855 (insert "*/"))))
10856 ((and single
10857 (save-excursion
10858 (and (zerop (forward-line 1))
10859 (looking-at "\\s-*//"))))
10860 (indent-to col)
10861 (insert "// "))
10862 ;; don't need to extend the comment after all
10863 (js2-enter-indents-newline
10864 (js2-indent-line)))))
10865
10866 (defun js2-beginning-of-line ()
10867 "Toggles point between bol and first non-whitespace char in line.
10868 Also moves past comment delimiters when inside comments."
10869 (interactive)
10870 (let (node beg)
10871 (cond
10872 ((bolp)
10873 (back-to-indentation))
10874 ((looking-at "//")
10875 (skip-chars-forward "/ \t"))
10876 ((and (eq (char-after) ?*)
10877 (setq node (js2-comment-at-point))
10878 (memq (js2-comment-node-format node) '(jsdoc block))
10879 (save-excursion
10880 (skip-chars-backward " \t")
10881 (bolp)))
10882 (skip-chars-forward "\* \t"))
10883 (t
10884 (goto-char (point-at-bol))))))
10885
10886 (defun js2-end-of-line ()
10887 "Toggles point between eol and last non-whitespace char in line."
10888 (interactive)
10889 (if (eolp)
10890 (skip-chars-backward " \t")
10891 (goto-char (point-at-eol))))
10892
10893 (defun js2-enter-mirror-mode()
10894 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10895 on insertion."
10896 (interactive)
10897 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10898 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10899 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10900 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10901 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10902 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10903 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10904 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10905
10906 (defun js2-leave-mirror-mode()
10907 "Turns off mirror mode."
10908 (interactive)
10909 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10910 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10911
10912 (defsubst js2-mode-inside-string ()
10913 "Return non-nil if inside a string.
10914 Actually returns the quote character that begins the string."
10915 (let ((parse-state (save-excursion
10916 (syntax-ppss (point)))))
10917 (nth 3 parse-state)))
10918
10919 (defsubst js2-mode-inside-comment-or-string ()
10920 "Return non-nil if inside a comment or string."
10921 (or
10922 (let ((comment-start
10923 (save-excursion
10924 (goto-char (point-at-bol))
10925 (if (re-search-forward "//" (point-at-eol) t)
10926 (match-beginning 0)))))
10927 (and comment-start
10928 (<= comment-start (point))))
10929 (let ((parse-state (save-excursion
10930 (syntax-ppss (point)))))
10931 (or (nth 3 parse-state)
10932 (nth 4 parse-state)))))
10933
10934 (defsubst js2-make-magic-delimiter (delim &optional pos)
10935 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10936 Sets value of `js2-magic' text property to line number at POS."
10937 (propertize delim
10938 'js2-magic (line-number-at-pos pos)
10939 'face 'js2-magic-paren-face))
10940
10941 (defun js2-mode-match-delimiter (open close)
10942 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10943 The rule we use, which as far as we can tell is how Eclipse works,
10944 is that we insert the match if we're not in a comment or string,
10945 and the next non-whitespace character is either punctuation or
10946 occurs on another line."
10947 (insert open)
10948 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10949 (not (js2-mode-inside-comment-or-string)))
10950 (save-excursion
10951 (insert (js2-make-magic-delimiter close)))
10952 (when js2-auto-indent-p
10953 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10954 (js2-indent-line)))))
10955
10956 (defun js2-mode-match-bracket ()
10957 "Insert matching bracket."
10958 (interactive)
10959 (js2-mode-match-delimiter "[" "]"))
10960
10961 (defun js2-mode-match-paren ()
10962 "Insert matching paren unless already inserted."
10963 (interactive)
10964 (js2-mode-match-delimiter "(" ")"))
10965
10966 (defun js2-mode-match-curly (arg)
10967 "Insert matching curly-brace.
10968 With prefix arg, no formatting or indentation will occur -- the close-brace
10969 is simply inserted directly at the point."
10970 (interactive "p")
10971 (let (try-pos)
10972 (cond
10973 (current-prefix-arg
10974 (js2-mode-match-delimiter "{" "}"))
10975 ((and js2-auto-insert-catch-block
10976 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10977 (point-at-bol))
10978 (match-beginning 1))))
10979 (js2-insert-catch-skel try-pos))
10980 (t
10981 ;; Otherwise try to do something smarter.
10982 (insert "{")
10983 (unless (or (not (looking-at "\\s-*$"))
10984 (save-excursion
10985 (skip-chars-forward " \t\r\n")
10986 (and (looking-at "}")
10987 (js2-error-at-point)))
10988 (js2-mode-inside-comment-or-string))
10989 (undo-boundary)
10990 ;; absolutely mystifying bug: when inserting the next "\n",
10991 ;; the buffer-undo-list is given two new entries: the inserted range,
10992 ;; and the incorrect position of the point. It's recorded incorrectly
10993 ;; as being before the opening "{", not after it. But it's recorded
10994 ;; as the correct value if you're debugging `js2-mode-match-curly'
10995 ;; in edebug. I have no idea why it's doing this, but incrementing
10996 ;; the inserted position fixes the problem, so that the undo takes us
10997 ;; back to just after the user-inserted "{".
10998 (insert "\n")
10999 (ignore-errors
11000 (incf (cadr buffer-undo-list)))
11001 (js2-indent-line)
11002 (save-excursion
11003 (insert "\n}")
11004 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11005 (js2-indent-line))))))))
11006
11007 (defun js2-insert-catch-skel (try-pos)
11008 "Complete a try/catch block after inserting a { following a try keyword.
11009 Rationale is that a try always needs a catch or a finally, and the catch is
11010 the more likely of the two.
11011
11012 TRY-POS is the buffer position of the try keyword. The open-curly should
11013 already have been inserted."
11014 (insert "{")
11015 (let ((try-col (save-excursion
11016 (goto-char try-pos)
11017 (current-column))))
11018 (insert "\n")
11019 (undo-boundary)
11020 (js2-indent-line) ;; indent the blank line where cursor will end up
11021 (save-excursion
11022 (insert "\n")
11023 (indent-to try-col)
11024 (insert "} catch (x) {\n\n")
11025 (indent-to try-col)
11026 (insert "}"))))
11027
11028 (defun js2-mode-highlight-magic-parens ()
11029 "Re-highlight magic parens after parsing nukes the 'face prop."
11030 (let ((beg (point-min))
11031 end)
11032 (while (setq beg (next-single-property-change beg 'js2-magic))
11033 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11034 (if (get-text-property beg 'js2-magic)
11035 (js2-with-unmodifying-text-property-changes
11036 (put-text-property beg (or end (1+ beg))
11037 'face 'js2-magic-paren-face))))))
11038
11039 (defun js2-mode-mundanify-parens ()
11040 "Clear all magic parens and brackets."
11041 (let ((beg (point-min))
11042 end)
11043 (while (setq beg (next-single-property-change beg 'js2-magic))
11044 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11045 (remove-text-properties beg (or end (1+ beg))
11046 '(js2-magic face)))))
11047
11048 (defsubst js2-match-quote (quote-string)
11049 (let ((start-quote (js2-mode-inside-string)))
11050 (cond
11051 ;; inside a comment - don't do quote-matching, since we can't
11052 ;; reliably figure out if we're in a string inside the comment
11053 ((js2-comment-at-point)
11054 (insert quote-string))
11055 ((not start-quote)
11056 ;; not in string => insert matched quotes
11057 (insert quote-string)
11058 ;; exception: if we're just before a word, don't double it.
11059 (unless (looking-at "[^ \t\r\n]")
11060 (save-excursion
11061 (insert quote-string))))
11062 ((looking-at quote-string)
11063 (if (looking-back "[^\\]\\\\")
11064 (insert quote-string)
11065 (forward-char 1)))
11066 ((and js2-mode-escape-quotes
11067 (save-excursion
11068 (save-match-data
11069 (re-search-forward quote-string (point-at-eol) t))))
11070 ;; inside terminated string, escape quote (unless already escaped)
11071 (insert (if (looking-back "[^\\]\\\\")
11072 quote-string
11073 (concat "\\" quote-string))))
11074 (t
11075 (insert quote-string))))) ; else terminate the string
11076
11077 (defun js2-mode-match-single-quote ()
11078 "Insert matching single-quote."
11079 (interactive)
11080 (let ((parse-status (syntax-ppss (point))))
11081 ;; don't match inside comments, since apostrophe is more common
11082 (if (nth 4 parse-status)
11083 (insert "'")
11084 (js2-match-quote "'"))))
11085
11086 (defun js2-mode-match-double-quote ()
11087 "Insert matching double-quote."
11088 (interactive)
11089 (js2-match-quote "\""))
11090
11091 ;; Eclipse works as follows:
11092 ;; * type an open-paren and it auto-inserts close-paren
11093 ;; - auto-inserted paren gets a green bracket
11094 ;; - green bracket means typing close-paren there will skip it
11095 ;; * if you insert any text on a different line, it turns off
11096 (defun js2-mode-magic-close-paren ()
11097 "Skip over close-paren rather than inserting, where appropriate."
11098 (interactive)
11099 (let* ((here (point))
11100 (parse-status (syntax-ppss here))
11101 (open-pos (nth 1 parse-status))
11102 (close last-input-event)
11103 (open (cond
11104 ((eq close ?\))
11105 ?\()
11106 ((eq close ?\])
11107 ?\[)
11108 ((eq close ?})
11109 ?{)
11110 (t nil))))
11111 (if (and (eq (char-after) close)
11112 (eq open (char-after open-pos))
11113 (js2-same-line open-pos)
11114 (get-text-property here 'js2-magic))
11115 (progn
11116 (remove-text-properties here (1+ here) '(js2-magic face))
11117 (forward-char 1))
11118 (insert-char close 1))
11119 (blink-matching-open)))
11120
11121 (defun js2-mode-wait-for-parse (callback)
11122 "Invoke CALLBACK when parsing is finished.
11123 If parsing is already finished, calls CALLBACK immediately."
11124 (if (not js2-mode-buffer-dirty-p)
11125 (funcall callback)
11126 (push callback js2-mode-pending-parse-callbacks)
11127 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11128
11129 (defun js2-mode-parse-finished ()
11130 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11131 ;; We can't let errors propagate up, since it prevents the
11132 ;; `js2-parse' method from completing normally and returning
11133 ;; the ast, which makes things mysteriously not work right.
11134 (unwind-protect
11135 (dolist (cb js2-mode-pending-parse-callbacks)
11136 (condition-case err
11137 (funcall cb)
11138 (error (message "%s" err))))
11139 (setq js2-mode-pending-parse-callbacks nil)))
11140
11141 (defun js2-mode-flag-region (from to flag)
11142 "Hide or show text from FROM to TO, according to FLAG.
11143 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11144 Returns the created overlay if FLAG is non-nil."
11145 (remove-overlays from to 'invisible 'js2-outline)
11146 (when flag
11147 (let ((o (make-overlay from to)))
11148 (overlay-put o 'invisible 'js2-outline)
11149 (overlay-put o 'isearch-open-invisible
11150 'js2-isearch-open-invisible)
11151 o)))
11152
11153 ;; Function to be set as an outline-isearch-open-invisible' property
11154 ;; to the overlay that makes the outline invisible (see
11155 ;; `js2-mode-flag-region').
11156 (defun js2-isearch-open-invisible (overlay)
11157 ;; We rely on the fact that isearch places point on the matched text.
11158 (js2-mode-show-element))
11159
11160 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11161 "Return cons cell of bounds of folding overlay at POS.
11162 Returns nil if not found."
11163 (let ((overlays (overlays-at (or pos (point))))
11164 o)
11165 (while (and overlays
11166 (not o))
11167 (if (overlay-get (car overlays) 'invisible)
11168 (setq o (car overlays))
11169 (setq overlays (cdr overlays))))
11170 (if o
11171 (cons (overlay-start o) (overlay-end o)))))
11172
11173 (defun js2-mode-function-at-point (&optional pos)
11174 "Return the innermost function node enclosing current point.
11175 Returns nil if point is not in a function."
11176 (let ((node (js2-node-at-point pos)))
11177 (while (and node (not (js2-function-node-p node)))
11178 (setq node (js2-node-parent node)))
11179 (if (js2-function-node-p node)
11180 node)))
11181
11182 (defun js2-mode-toggle-element ()
11183 "Hide or show the foldable element at the point."
11184 (interactive)
11185 (let (comment fn pos)
11186 (save-excursion
11187 (save-match-data
11188 (cond
11189 ;; /* ... */ comment?
11190 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11191 (if (js2-mode-invisible-overlay-bounds
11192 (setq pos (+ 3 (js2-node-abs-pos comment))))
11193 (progn
11194 (goto-char pos)
11195 (js2-mode-show-element))
11196 (js2-mode-hide-element)))
11197 ;; //-comment?
11198 ((save-excursion
11199 (back-to-indentation)
11200 (looking-at js2-mode-//-comment-re))
11201 (js2-mode-toggle-//-comment))
11202 ;; function?
11203 ((setq fn (js2-mode-function-at-point))
11204 (setq pos (and (js2-function-node-body fn)
11205 (js2-node-abs-pos (js2-function-node-body fn))))
11206 (goto-char (1+ pos))
11207 (if (js2-mode-invisible-overlay-bounds)
11208 (js2-mode-show-element)
11209 (js2-mode-hide-element)))
11210 (t
11211 (message "Nothing at point to hide or show")))))))
11212
11213 (defun js2-mode-hide-element ()
11214 "Fold/hide contents of a block, showing ellipses.
11215 Show the hidden text with \\[js2-mode-show-element]."
11216 (interactive)
11217 (if js2-mode-buffer-dirty-p
11218 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11219 (let (node body beg end)
11220 (cond
11221 ((js2-mode-invisible-overlay-bounds)
11222 (message "already hidden"))
11223 (t
11224 (setq node (js2-node-at-point))
11225 (cond
11226 ((js2-block-comment-p node)
11227 (js2-mode-hide-comment node))
11228 (t
11229 (while (and node (not (js2-function-node-p node)))
11230 (setq node (js2-node-parent node)))
11231 (if (and node
11232 (setq body (js2-function-node-body node)))
11233 (progn
11234 (setq beg (js2-node-abs-pos body)
11235 end (+ beg (js2-node-len body)))
11236 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11237 (message "No collapsable element found at point"))))))))
11238
11239 (defun js2-mode-show-element ()
11240 "Show the hidden element at current point."
11241 (interactive)
11242 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11243 (if bounds
11244 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11245 (message "Nothing to un-hide"))))
11246
11247 (defun js2-mode-show-all ()
11248 "Show all of the text in the buffer."
11249 (interactive)
11250 (js2-mode-flag-region (point-min) (point-max) nil))
11251
11252 (defun js2-mode-toggle-hide-functions ()
11253 (interactive)
11254 (if js2-mode-functions-hidden
11255 (js2-mode-show-functions)
11256 (js2-mode-hide-functions)))
11257
11258 (defun js2-mode-hide-functions ()
11259 "Hides all non-nested function bodies in the buffer.
11260 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11261 to open an individual entry."
11262 (interactive)
11263 (if js2-mode-buffer-dirty-p
11264 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11265 (if (null js2-mode-ast)
11266 (message "Oops - parsing failed")
11267 (setq js2-mode-functions-hidden t)
11268 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11269
11270 (defun js2-mode-function-hider (n endp)
11271 (when (not endp)
11272 (let ((tt (js2-node-type n))
11273 body beg end)
11274 (cond
11275 ((and (= tt js2-FUNCTION)
11276 (setq body (js2-function-node-body n)))
11277 (setq beg (js2-node-abs-pos body)
11278 end (+ beg (js2-node-len body)))
11279 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11280 nil) ; don't process children of function
11281 (t
11282 t))))) ; keep processing other AST nodes
11283
11284 (defun js2-mode-show-functions ()
11285 "Un-hide any folded function bodies in the buffer."
11286 (interactive)
11287 (setq js2-mode-functions-hidden nil)
11288 (save-excursion
11289 (goto-char (point-min))
11290 (while (/= (goto-char (next-overlay-change (point)))
11291 (point-max))
11292 (dolist (o (overlays-at (point)))
11293 (when (and (overlay-get o 'invisible)
11294 (not (overlay-get o 'comment)))
11295 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11296
11297 (defun js2-mode-hide-comment (n)
11298 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11299 3 ; /**
11300 2)) ; /*
11301 (beg (+ (js2-node-abs-pos n) head))
11302 (end (- (+ beg (js2-node-len n)) head 2))
11303 (o (js2-mode-flag-region beg end 'hide)))
11304 (overlay-put o 'comment t)))
11305
11306 (defun js2-mode-toggle-hide-comments ()
11307 "Folds all block comments in the buffer.
11308 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11309 to open an individual entry."
11310 (interactive)
11311 (if js2-mode-comments-hidden
11312 (js2-mode-show-comments)
11313 (js2-mode-hide-comments)))
11314
11315 (defun js2-mode-hide-comments ()
11316 (interactive)
11317 (if js2-mode-buffer-dirty-p
11318 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11319 (if (null js2-mode-ast)
11320 (message "Oops - parsing failed")
11321 (setq js2-mode-comments-hidden t)
11322 (dolist (n (js2-ast-root-comments js2-mode-ast))
11323 (let ((format (js2-comment-node-format n)))
11324 (when (js2-block-comment-p n)
11325 (js2-mode-hide-comment n))))
11326 (js2-mode-hide-//-comments)))
11327
11328 (defsubst js2-mode-extend-//-comment (direction)
11329 "Find start or end of a block of similar //-comment lines.
11330 DIRECTION is -1 to look back, 1 to look forward.
11331 INDENT is the indentation level to match.
11332 Returns the end-of-line position of the furthest adjacent
11333 //-comment line with the same indentation as the current line.
11334 If there is no such matching line, returns current end of line."
11335 (let ((pos (point-at-eol))
11336 (indent (current-indentation)))
11337 (save-excursion
11338 (save-match-data
11339 (while (and (zerop (forward-line direction))
11340 (looking-at js2-mode-//-comment-re)
11341 (eq indent (length (match-string 1))))
11342 (setq pos (point-at-eol)))
11343 pos))))
11344
11345 (defun js2-mode-hide-//-comments ()
11346 "Fold adjacent 1-line comments, showing only snippet of first one."
11347 (let (beg end)
11348 (save-excursion
11349 (save-match-data
11350 (goto-char (point-min))
11351 (while (re-search-forward js2-mode-//-comment-re nil t)
11352 (setq beg (point)
11353 end (js2-mode-extend-//-comment 1))
11354 (unless (eq beg end)
11355 (overlay-put (js2-mode-flag-region beg end 'hide)
11356 'comment t))
11357 (goto-char end)
11358 (forward-char 1))))))
11359
11360 (defun js2-mode-toggle-//-comment ()
11361 "Fold or un-fold any multi-line //-comment at point.
11362 Caller should have determined that this line starts with a //-comment."
11363 (let* ((beg (point-at-eol))
11364 (end beg))
11365 (save-excursion
11366 (goto-char end)
11367 (if (js2-mode-invisible-overlay-bounds)
11368 (js2-mode-show-element)
11369 ;; else hide the comment
11370 (setq beg (js2-mode-extend-//-comment -1)
11371 end (js2-mode-extend-//-comment 1))
11372 (unless (eq beg end)
11373 (overlay-put (js2-mode-flag-region beg end 'hide)
11374 'comment t))))))
11375
11376 (defun js2-mode-show-comments ()
11377 "Un-hide any hidden comments, leaving other hidden elements alone."
11378 (interactive)
11379 (setq js2-mode-comments-hidden nil)
11380 (save-excursion
11381 (goto-char (point-min))
11382 (while (/= (goto-char (next-overlay-change (point)))
11383 (point-max))
11384 (dolist (o (overlays-at (point)))
11385 (when (overlay-get o 'comment)
11386 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11387
11388 (defun js2-mode-display-warnings-and-errors ()
11389 "Turn on display of warnings and errors."
11390 (interactive)
11391 (setq js2-mode-show-parse-errors t
11392 js2-mode-show-strict-warnings t)
11393 (js2-reparse 'force))
11394
11395 (defun js2-mode-hide-warnings-and-errors ()
11396 "Turn off display of warnings and errors."
11397 (interactive)
11398 (setq js2-mode-show-parse-errors nil
11399 js2-mode-show-strict-warnings nil)
11400 (js2-reparse 'force))
11401
11402 (defun js2-mode-toggle-warnings-and-errors ()
11403 "Toggle the display of warnings and errors.
11404 Some users don't like having warnings/errors reported while they type."
11405 (interactive)
11406 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11407 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11408 (if (interactive-p)
11409 (message "warnings and errors %s"
11410 (if js2-mode-show-parse-errors
11411 "enabled"
11412 "disabled")))
11413 (js2-reparse 'force))
11414
11415 (defun js2-mode-customize ()
11416 (interactive)
11417 (customize-group 'js2-mode))
11418
11419 (defun js2-mode-forward-sexp (&optional arg)
11420 "Move forward across one statement or balanced expression.
11421 With ARG, do it that many times. Negative arg -N means
11422 move backward across N balanced expressions."
11423 (interactive "p")
11424 (setq arg (or arg 1))
11425 (if js2-mode-buffer-dirty-p
11426 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11427 (let (node end (start (point)))
11428 (cond
11429 ;; backward-sexp
11430 ;; could probably make this better for some cases:
11431 ;; - if in statement block (e.g. function body), go to parent
11432 ;; - infix exprs like (foo in bar) - maybe go to beginning
11433 ;; of infix expr if in the right-side expression?
11434 ((and arg (minusp arg))
11435 (dotimes (i (- arg))
11436 (js2-backward-sws)
11437 (forward-char -1) ; enter the node we backed up to
11438 (setq node (js2-node-at-point (point) t))
11439 (goto-char (if node
11440 (js2-node-abs-pos node)
11441 (point-min)))))
11442 (t
11443 ;; forward-sexp
11444 (js2-forward-sws)
11445 (dotimes (i arg)
11446 (js2-forward-sws)
11447 (setq node (js2-node-at-point (point) t)
11448 end (if node (+ (js2-node-abs-pos node)
11449 (js2-node-len node))))
11450 (goto-char (or end (point-max))))))))
11451
11452 (defun js2-next-error (&optional arg reset)
11453 "Move to next parse error.
11454 Typically invoked via \\[next-error].
11455 ARG is the number of errors, forward or backward, to move.
11456 RESET means start over from the beginning."
11457 (interactive "p")
11458 (if (or (null js2-mode-ast)
11459 (and (null (js2-ast-root-errors js2-mode-ast))
11460 (null (js2-ast-root-warnings js2-mode-ast))))
11461 (message "No errors")
11462 (when reset
11463 (goto-char (point-min)))
11464 (let* ((errs (copy-sequence
11465 (append (js2-ast-root-errors js2-mode-ast)
11466 (js2-ast-root-warnings js2-mode-ast))))
11467 (continue t)
11468 (start (point))
11469 (count (or arg 1))
11470 (backward (minusp count))
11471 (sorter (if backward '> '<))
11472 (stopper (if backward '< '>))
11473 (count (abs count))
11474 all-errs
11475 err)
11476 ;; sort by start position
11477 (setq errs (sort errs (lambda (e1 e2)
11478 (funcall sorter (second e1) (second e2))))
11479 all-errs errs)
11480 ;; find nth error with pos > start
11481 (while (and errs continue)
11482 (when (funcall stopper (cadar errs) start)
11483 (setq err (car errs))
11484 (if (zerop (decf count))
11485 (setq continue nil)))
11486 (setq errs (cdr errs)))
11487 (if err
11488 (goto-char (second err))
11489 ;; wrap around to first error
11490 (goto-char (second (car all-errs)))
11491 ;; if we were already on it, echo msg again
11492 (if (= (point) start)
11493 (js2-echo-error (point) (point)))))))
11494
11495 (defun js2-down-mouse-3 ()
11496 "Make right-click move the point to the click location.
11497 This makes right-click context menu operations a bit more intuitive.
11498 The point will not move if the region is active, however, to avoid
11499 destroying the region selection."
11500 (interactive)
11501 (when (and js2-move-point-on-right-click
11502 (not mark-active))
11503 (let ((e last-input-event))
11504 (ignore-errors
11505 (goto-char (cadadr e))))))
11506
11507 (defun js2-mode-create-imenu-index ()
11508 "Return an alist for `imenu--index-alist'."
11509 ;; This is built up in `js2-parse-record-imenu' during parsing.
11510 (when js2-mode-ast
11511 ;; if we have an ast but no recorder, they're requesting a rescan
11512 (unless js2-imenu-recorder
11513 (js2-reparse 'force))
11514 (prog1
11515 (js2-build-imenu-index)
11516 (setq js2-imenu-recorder nil
11517 js2-imenu-function-map nil))))
11518
11519 (defun js2-mode-find-tag ()
11520 "Replacement for `find-tag-default'.
11521 `find-tag-default' returns a ridiculous answer inside comments."
11522 (let (beg end)
11523 (js2-with-underscore-as-word-syntax
11524 (save-excursion
11525 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11526 (looking-back "[A-Za-z0-9_$]"))
11527 (setq beg (progn (forward-word -1) (point))
11528 end (progn (forward-word 1) (point)))
11529 (setq beg (progn (forward-word 1) (point))
11530 end (progn (forward-word -1) (point))))
11531 (replace-regexp-in-string
11532 "[\"']" ""
11533 (buffer-substring-no-properties beg end))))))
11534
11535 (defun js2-mode-forward-sibling ()
11536 "Move to the end of the sibling following point in parent.
11537 Returns non-nil if successful, or nil if there was no following sibling."
11538 (let* ((node (js2-node-at-point))
11539 (parent (js2-mode-find-enclosing-fn node))
11540 sib)
11541 (when (setq sib (js2-node-find-child-after (point) parent))
11542 (goto-char (+ (js2-node-abs-pos sib)
11543 (js2-node-len sib))))))
11544
11545 (defun js2-mode-backward-sibling ()
11546 "Move to the beginning of the sibling node preceding point in parent.
11547 Parent is defined as the enclosing script or function."
11548 (let* ((node (js2-node-at-point))
11549 (parent (js2-mode-find-enclosing-fn node))
11550 sib)
11551 (when (setq sib (js2-node-find-child-before (point) parent))
11552 (goto-char (js2-node-abs-pos sib)))))
11553
11554 (defun js2-beginning-of-defun ()
11555 "Go to line on which current function starts, and return non-nil.
11556 If we're not in a function, go to beginning of previous script-level element."
11557 (interactive)
11558 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11559 pos sib)
11560 (cond
11561 ((and (js2-function-node-p parent)
11562 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11563 (goto-char pos))
11564 (t
11565 (js2-mode-backward-sibling)))))
11566
11567 (defun js2-end-of-defun ()
11568 "Go to the char after the last position of the current function.
11569 If we're not in a function, skips over the next script-level element."
11570 (interactive)
11571 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11572 (if (not (js2-function-node-p parent))
11573 ;; punt: skip over next script-level element beyond point
11574 (js2-mode-forward-sibling)
11575 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11576 (js2-node-len parent)))))))
11577
11578 (defun js2-mark-defun (&optional allow-extend)
11579 "Put mark at end of this function, point at beginning.
11580 The function marked is the one that contains point.
11581
11582 Interactively, if this command is repeated,
11583 or (in Transient Mark mode) if the mark is active,
11584 it marks the next defun after the ones already marked."
11585 (interactive "p")
11586 (let (extended)
11587 (when (and allow-extend
11588 (or (and (eq last-command this-command) (mark t))
11589 (and transient-mark-mode mark-active)))
11590 (let ((sib (save-excursion
11591 (goto-char (mark))
11592 (if (js2-mode-forward-sibling)
11593 (point))))
11594 node)
11595 (if sib
11596 (progn
11597 (set-mark sib)
11598 (setq extended t))
11599 ;; no more siblings - try extending to enclosing node
11600 (goto-char (mark t)))))
11601 (when (not extended)
11602 (let ((node (js2-node-at-point (point) t)) ; skip comments
11603 ast fn stmt parent beg end)
11604 (when (js2-ast-root-p node)
11605 (setq ast node
11606 node (or (js2-node-find-child-after (point) node)
11607 (js2-node-find-child-before (point) node))))
11608 ;; only mark whole buffer if we can't find any children
11609 (if (null node)
11610 (setq node ast))
11611 (if (js2-function-node-p node)
11612 (setq parent node)
11613 (setq fn (js2-mode-find-enclosing-fn node)
11614 stmt (if (or (null fn)
11615 (js2-ast-root-p fn))
11616 (js2-mode-find-first-stmt node))
11617 parent (or stmt fn)))
11618 (setq beg (js2-node-abs-pos parent)
11619 end (+ beg (js2-node-len parent)))
11620 (push-mark beg)
11621 (goto-char end)
11622 (exchange-point-and-mark)))))
11623
11624 (defun js2-narrow-to-defun ()
11625 "Narrow to the function enclosing point."
11626 (interactive)
11627 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11628 (fn (if (js2-script-node-p node)
11629 node
11630 (js2-mode-find-enclosing-fn node)))
11631 (beg (js2-node-abs-pos fn)))
11632 (unless (js2-ast-root-p fn)
11633 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11634
11635 (provide 'js2-mode)
11636
11637 ;;; js2-mode.el ends here