]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Close #11 indent-for-tab-command: jump to indentation when inside it
[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 (defvar js2-emacs22 (>= emacs-major-version 22))
176
177 (defcustom js2-highlight-level 2
178 "Amount of syntax highlighting to perform.
179 0 or a negative value means do no highlighting.
180 1 adds basic syntax highlighting.
181 2 adds highlighting of some Ecma built-in properties.
182 3 adds highlighting of many Ecma built-in functions."
183 :group 'js2-mode
184 :type '(choice (const :tag "None" 0)
185 (const :tag "Basic" 1)
186 (const :tag "Include Properties" 2)
187 (const :tag "Include Functions" 3)))
188
189 (defvar js2-mode-dev-mode-p nil
190 "Non-nil if running in development mode. Normally nil.")
191
192 (defgroup js2-mode nil
193 "An improved JavaScript mode."
194 :group 'languages)
195
196 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
197 (numberp c-basic-offset))
198 c-basic-offset
199 4)
200 "Number of spaces to indent nested statements.
201 Similar to `c-basic-offset'."
202 :group 'js2-mode
203 :type 'integer)
204 (make-variable-buffer-local 'js2-basic-offset)
205
206 ;; TODO(stevey): move this code into a separate minor mode.
207 (defcustom js2-mirror-mode nil
208 "Non-nil to insert closing brackets, parens, etc. automatically."
209 :group 'js2-mode
210 :type 'boolean)
211
212 (defcustom js2-auto-indent-p nil
213 "Automatic indentation with punctuation characters.
214 If non-nil, the current line is indented when certain punctuations
215 are inserted."
216 :group 'js2-mode
217 :type 'boolean)
218
219 (defcustom js2-bounce-indent-p nil
220 "Non-nil to have indent-line function choose among alternatives.
221 If nil, the indent-line function will indent to a predetermined column
222 based on heuristic guessing. If non-nil, then if the current line is
223 already indented to that predetermined column, indenting will choose
224 another likely column and indent to that spot. Repeated invocation of
225 the indent-line function will cycle among the computed alternatives.
226 See the function `js2-bounce-indent' for details. When it is non-nil,
227 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
228 :type 'boolean
229 :group 'js2-mode)
230
231 (defcustom js2-consistent-level-indent-inner-bracket-p t
232 "Non-nil to make indentation level inner bracket consistent,
233 regardless of the beginning bracket position."
234 :group 'js2-mode
235 :type 'boolean)
236
237 (defcustom js2-pretty-multiline-decl-indentation-p t
238 "Non-nil to line up multiline declarations vertically. See the
239 function `js-multiline-decl-indentation' for details."
240 :group 'js2-mode
241 :type 'boolean)
242
243 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
244 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
245 always additionally indent function expression or array/object literal
246 assigned in a declaration, even when only one var is declared."
247 :group 'js2-mode
248 :type 'boolean)
249
250 (defcustom js2-indent-on-enter-key nil
251 "Non-nil to have Enter/Return key indent the line.
252 This is unusual for Emacs modes but common in IDEs like Eclipse."
253 :type 'boolean
254 :group 'js2-mode)
255
256 (defcustom js2-enter-indents-newline nil
257 "Non-nil to have Enter/Return key indent the newly-inserted line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
259 :type 'boolean
260 :group 'js2-mode)
261
262 (defcustom js2-rebind-eol-bol-keys t
263 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
264 If non-nil, bounce between bol/eol and first/last non-whitespace char."
265 :group 'js2-mode
266 :type 'boolean)
267
268 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
269 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
270 Each value in the list is passed to `define-key'."
271 :type 'list
272 :group 'js2-mode)
273
274 (defcustom js2-idle-timer-delay 0.2
275 "Delay in secs before re-parsing after user makes changes.
276 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
277 :type 'number
278 :group 'js2-mode)
279 (make-variable-buffer-local 'js2-idle-timer-delay)
280
281 (defcustom js2-dynamic-idle-timer-adjust 0
282 "Positive to adjust `js2-idle-timer-delay' based on file size.
283 The idea is that for short files, parsing is faster so we can be
284 more responsive to user edits without interfering with editing.
285 The buffer length in characters (typically bytes) is divided by
286 this value and used to multiply `js2-idle-timer-delay' for the
287 buffer. For example, a 21k file and 10k adjust yields 21k/10k
288 == 2, so js2-idle-timer-delay is multiplied by 2.
289 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
290 `js2-idle-timer-delay' is not dependent on the file size."
291 :type 'number
292 :group 'js2-mode)
293
294 (defcustom js2-mode-escape-quotes t
295 "Non-nil to disable automatic quote-escaping inside strings."
296 :type 'boolean
297 :group 'js2-mode)
298
299 (defcustom js2-mode-squeeze-spaces t
300 "Non-nil to normalize whitespace when filling in comments.
301 Multiple runs of spaces are converted to a single space."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-mode-show-parse-errors t
306 "True to highlight parse errors."
307 :type 'boolean
308 :group 'js2-mode)
309
310 (defcustom js2-mode-show-strict-warnings t
311 "Non-nil to emit Ecma strict-mode warnings.
312 Some of the warnings can be individually disabled by other flags,
313 even if this flag is non-nil."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-trailing-comma-warning t
318 "Non-nil to warn about trailing commas in array literals.
319 Ecma-262 forbids them, but many browsers permit them. IE is the
320 big exception, and can produce bugs if you have trailing commas."
321 :type 'boolean
322 :group 'js2-mode)
323
324 (defcustom js2-strict-missing-semi-warning t
325 "Non-nil to warn about semicolon auto-insertion after statement.
326 Technically this is legal per Ecma-262, but some style guides disallow
327 depending on it."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-missing-semi-one-line-override nil
332 "Non-nil to permit missing semicolons in one-line functions.
333 In one-liner functions such as `function identity(x) {return x}'
334 people often omit the semicolon for a cleaner look. If you are
335 such a person, you can suppress the missing-semicolon warning
336 by setting this variable to t."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-strict-inconsistent-return-warning t
341 "Non-nil to warn about mixing returns with value-returns.
342 It's perfectly legal to have a `return' and a `return foo' in the
343 same function, but it's often an indicator of a bug, and it also
344 interferes with type inference (in systems that support it.)"
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-strict-cond-assign-warning t
349 "Non-nil to warn about expressions like if (a = b).
350 This often should have been '==' instead of '='. If the warning
351 is enabled, you can suppress it on a per-expression basis by
352 parenthesizing the expression, e.g. if ((a = b)) ..."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-strict-cond-assign-warning t
357 "Non-nil to warn about expressions like if (a = b).
358 This often should have been '==' instead of '='. If the warning
359 is enabled, you can suppress it on a per-expression basis by
360 parenthesizing the expression, e.g. if ((a = b)) ..."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-strict-var-redeclaration-warning t
365 "Non-nil to warn about redeclaring variables in a script or function."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-strict-var-hides-function-arg-warning t
370 "Non-nil to warn about a var decl hiding a function argument."
371 :type 'boolean
372 :group 'js2-mode)
373
374 (defcustom js2-skip-preprocessor-directives nil
375 "Non-nil to treat lines beginning with # as comments.
376 Useful for viewing Mozilla JavaScript source code."
377 :type 'boolean
378 :group 'js2-mode)
379
380 (defcustom js2-language-version 180
381 "Configures what JavaScript language version to recognize.
382 Currently versions 150, 160, 170 and 180 are supported, corresponding
383 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
384 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
385 and 1.8 adds function closures."
386 :type 'integer
387 :group 'js2-mode)
388
389 (defcustom js2-allow-keywords-as-property-names t
390 "If non-nil, you can use JavaScript keywords as object property names.
391 Examples:
392
393 var foo = {int: 5, while: 6, continue: 7};
394 foo.return = 8;
395
396 Ecma-262 forbids this syntax, but many browsers support it."
397 :type 'boolean
398 :group 'js2-mode)
399
400 (defcustom js2-instanceof-has-side-effects nil
401 "If non-nil, treats the instanceof operator as having side effects.
402 This is useful for xulrunner apps."
403 :type 'boolean
404 :group 'js2-mode)
405
406 (defcustom js2-cleanup-whitespace nil
407 "Non-nil to invoke `delete-trailing-whitespace' before saves."
408 :type 'boolean
409 :group 'js2-mode)
410
411 (defcustom js2-move-point-on-right-click t
412 "Non-nil to move insertion point when you right-click.
413 This makes right-click context menu behavior a bit more intuitive,
414 since menu operations generally apply to the point. The exception
415 is if there is a region selection, in which case the point does -not-
416 move, so cut/copy/paste etc. can work properly.
417
418 Note that IntelliJ moves the point, and Eclipse leaves it alone,
419 so this behavior is customizable."
420 :group 'js2-mode
421 :type 'boolean)
422
423 (defcustom js2-allow-rhino-new-expr-initializer t
424 "Non-nil to support a Rhino's experimental syntactic construct.
425
426 Rhino supports the ability to follow a `new' expression with an object
427 literal, which is used to set additional properties on the new object
428 after calling its constructor. Syntax:
429
430 new <expr> [ ( arglist ) ] [initializer]
431
432 Hence, this expression:
433
434 new Object {a: 1, b: 2}
435
436 results in an Object with properties a=1 and b=2. This syntax is
437 apparently not configurable in Rhino - it's currently always enabled,
438 as of Rhino version 1.7R2."
439 :type 'boolean
440 :group 'js2-mode)
441
442 (defcustom js2-allow-member-expr-as-function-name nil
443 "Non-nil to support experimental Rhino syntax for function names.
444
445 Rhino supports an experimental syntax configured via the Rhino Context
446 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
447
448 function <member-expr> ( [ arg-list ] ) { <body> }
449
450 Where member-expr is a non-parenthesized 'member expression', which
451 is anything at the grammar level of a new-expression or lower, meaning
452 any expression that does not involve infix or unary operators.
453
454 When <member-expr> is not a simple identifier, then it is syntactic
455 sugar for assigning the anonymous function to the <member-expr>. Hence,
456 this code:
457
458 function a.b().c[2] (x, y) { ... }
459
460 is rewritten as:
461
462 a.b().c[2] = function(x, y) {...}
463
464 which doesn't seem particularly useful, but Rhino permits it."
465 :type 'boolean
466 :group 'js2-mode)
467
468 (defvar js2-mode-version 20101228
469 "Release number for `js2-mode'.")
470
471 ;; scanner variables
472
473 (defmacro js2-deflocal (name value &optional comment)
474 "Define a buffer-local variable NAME with VALUE and COMMENT."
475 `(progn
476 (defvar ,name ,value ,comment)
477 (make-variable-buffer-local ',name)))
478
479 ;; We record the start and end position of each token.
480 (js2-deflocal js2-token-beg 1)
481 (js2-deflocal js2-token-end -1)
482
483 (defvar js2-EOF_CHAR -1
484 "Represents end of stream. Distinct from js2-EOF token type.")
485
486 ;; I originally used symbols to represent tokens, but Rhino uses
487 ;; ints and then sets various flag bits in them, so ints it is.
488 ;; The upshot is that we need a `js2-' prefix in front of each name.
489 (defvar js2-ERROR -1)
490 (defvar js2-EOF 0)
491 (defvar js2-EOL 1)
492 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
493 (defvar js2-LEAVEWITH 3)
494 (defvar js2-RETURN 4)
495 (defvar js2-GOTO 5)
496 (defvar js2-IFEQ 6)
497 (defvar js2-IFNE 7)
498 (defvar js2-SETNAME 8)
499 (defvar js2-BITOR 9)
500 (defvar js2-BITXOR 10)
501 (defvar js2-BITAND 11)
502 (defvar js2-EQ 12)
503 (defvar js2-NE 13)
504 (defvar js2-LT 14)
505 (defvar js2-LE 15)
506 (defvar js2-GT 16)
507 (defvar js2-GE 17)
508 (defvar js2-LSH 18)
509 (defvar js2-RSH 19)
510 (defvar js2-URSH 20)
511 (defvar js2-ADD 21) ; infix plus
512 (defvar js2-SUB 22) ; infix minus
513 (defvar js2-MUL 23)
514 (defvar js2-DIV 24)
515 (defvar js2-MOD 25)
516 (defvar js2-NOT 26)
517 (defvar js2-BITNOT 27)
518 (defvar js2-POS 28) ; unary plus
519 (defvar js2-NEG 29) ; unary minus
520 (defvar js2-NEW 30)
521 (defvar js2-DELPROP 31)
522 (defvar js2-TYPEOF 32)
523 (defvar js2-GETPROP 33)
524 (defvar js2-GETPROPNOWARN 34)
525 (defvar js2-SETPROP 35)
526 (defvar js2-GETELEM 36)
527 (defvar js2-SETELEM 37)
528 (defvar js2-CALL 38)
529 (defvar js2-NAME 39) ; an identifier
530 (defvar js2-NUMBER 40)
531 (defvar js2-STRING 41)
532 (defvar js2-NULL 42)
533 (defvar js2-THIS 43)
534 (defvar js2-FALSE 44)
535 (defvar js2-TRUE 45)
536 (defvar js2-SHEQ 46) ; shallow equality (===)
537 (defvar js2-SHNE 47) ; shallow inequality (!==)
538 (defvar js2-REGEXP 48)
539 (defvar js2-BINDNAME 49)
540 (defvar js2-THROW 50)
541 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
542 (defvar js2-IN 52)
543 (defvar js2-INSTANCEOF 53)
544 (defvar js2-LOCAL_LOAD 54)
545 (defvar js2-GETVAR 55)
546 (defvar js2-SETVAR 56)
547 (defvar js2-CATCH_SCOPE 57)
548 (defvar js2-ENUM_INIT_KEYS 58)
549 (defvar js2-ENUM_INIT_VALUES 59)
550 (defvar js2-ENUM_INIT_ARRAY 60)
551 (defvar js2-ENUM_NEXT 61)
552 (defvar js2-ENUM_ID 62)
553 (defvar js2-THISFN 63)
554 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
555 (defvar js2-ARRAYLIT 65) ; array literal
556 (defvar js2-OBJECTLIT 66) ; object literal
557 (defvar js2-GET_REF 67) ; *reference
558 (defvar js2-SET_REF 68) ; *reference = something
559 (defvar js2-DEL_REF 69) ; delete reference
560 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
561 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
562 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
563
564 ;; XML support
565 (defvar js2-DEFAULTNAMESPACE 73)
566 (defvar js2-ESCXMLATTR 74)
567 (defvar js2-ESCXMLTEXT 75)
568 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
569 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
570 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
571 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
572
573 (defvar js2-first-bytecode js2-ENTERWITH)
574 (defvar js2-last-bytecode js2-REF_NS_NAME)
575
576 (defvar js2-TRY 80)
577 (defvar js2-SEMI 81) ; semicolon
578 (defvar js2-LB 82) ; left and right brackets
579 (defvar js2-RB 83)
580 (defvar js2-LC 84) ; left and right curly-braces
581 (defvar js2-RC 85)
582 (defvar js2-LP 86) ; left and right parens
583 (defvar js2-RP 87)
584 (defvar js2-COMMA 88) ; comma operator
585
586 (defvar js2-ASSIGN 89) ; simple assignment (=)
587 (defvar js2-ASSIGN_BITOR 90) ; |=
588 (defvar js2-ASSIGN_BITXOR 91) ; ^=
589 (defvar js2-ASSIGN_BITAND 92) ; &=
590 (defvar js2-ASSIGN_LSH 93) ; <<=
591 (defvar js2-ASSIGN_RSH 94) ; >>=
592 (defvar js2-ASSIGN_URSH 95) ; >>>=
593 (defvar js2-ASSIGN_ADD 96) ; +=
594 (defvar js2-ASSIGN_SUB 97) ; -=
595 (defvar js2-ASSIGN_MUL 98) ; *=
596 (defvar js2-ASSIGN_DIV 99) ; /=
597 (defvar js2-ASSIGN_MOD 100) ; %=
598
599 (defvar js2-first-assign js2-ASSIGN)
600 (defvar js2-last-assign js2-ASSIGN_MOD)
601
602 (defvar js2-HOOK 101) ; conditional (?:)
603 (defvar js2-COLON 102)
604 (defvar js2-OR 103) ; logical or (||)
605 (defvar js2-AND 104) ; logical and (&&)
606 (defvar js2-INC 105) ; increment/decrement (++ --)
607 (defvar js2-DEC 106)
608 (defvar js2-DOT 107) ; member operator (.)
609 (defvar js2-FUNCTION 108) ; function keyword
610 (defvar js2-EXPORT 109) ; export keyword
611 (defvar js2-IMPORT 110) ; import keyword
612 (defvar js2-IF 111) ; if keyword
613 (defvar js2-ELSE 112) ; else keyword
614 (defvar js2-SWITCH 113) ; switch keyword
615 (defvar js2-CASE 114) ; case keyword
616 (defvar js2-DEFAULT 115) ; default keyword
617 (defvar js2-WHILE 116) ; while keyword
618 (defvar js2-DO 117) ; do keyword
619 (defvar js2-FOR 118) ; for keyword
620 (defvar js2-BREAK 119) ; break keyword
621 (defvar js2-CONTINUE 120) ; continue keyword
622 (defvar js2-VAR 121) ; var keyword
623 (defvar js2-WITH 122) ; with keyword
624 (defvar js2-CATCH 123) ; catch keyword
625 (defvar js2-FINALLY 124) ; finally keyword
626 (defvar js2-VOID 125) ; void keyword
627 (defvar js2-RESERVED 126) ; reserved keywords
628
629 (defvar js2-EMPTY 127)
630
631 ;; Types used for the parse tree - never returned by scanner.
632
633 (defvar js2-BLOCK 128) ; statement block
634 (defvar js2-LABEL 129) ; label
635 (defvar js2-TARGET 130)
636 (defvar js2-LOOP 131)
637 (defvar js2-EXPR_VOID 132) ; expression statement in functions
638 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
639 (defvar js2-JSR 134)
640 (defvar js2-SCRIPT 135) ; top-level node for entire script
641 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
642 (defvar js2-USE_STACK 137)
643 (defvar js2-SETPROP_OP 138) ; x.y op= something
644 (defvar js2-SETELEM_OP 139) ; x[y] op= something
645 (defvar js2-LOCAL_BLOCK 140)
646 (defvar js2-SET_REF_OP 141) ; *reference op= something
647
648 ;; For XML support:
649 (defvar js2-DOTDOT 142) ; member operator (..)
650 (defvar js2-COLONCOLON 143) ; namespace::name
651 (defvar js2-XML 144) ; XML type
652 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
653 (defvar js2-XMLATTR 146) ; @
654 (defvar js2-XMLEND 147)
655
656 ;; Optimizer-only tokens
657 (defvar js2-TO_OBJECT 148)
658 (defvar js2-TO_DOUBLE 149)
659
660 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
661 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
662 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
663 (defvar js2-CONST 153)
664 (defvar js2-SETCONST 154)
665 (defvar js2-SETCONSTVAR 155)
666 (defvar js2-ARRAYCOMP 156)
667 (defvar js2-LETEXPR 157)
668 (defvar js2-WITHEXPR 158)
669 (defvar js2-DEBUGGER 159)
670
671 (defvar js2-COMMENT 160)
672 (defvar js2-ENUM 161) ; for "enum" reserved word
673
674 (defconst js2-num-tokens (1+ js2-ENUM))
675
676 (defconst js2-debug-print-trees nil)
677
678 ;; Rhino accepts any string or stream as input. Emacs character
679 ;; processing works best in buffers, so we'll assume the input is a
680 ;; buffer. JavaScript strings can be copied into temp buffers before
681 ;; scanning them.
682
683 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
684 ;; They're the Emacs equivalent of instance variables, more or less.
685
686 (js2-deflocal js2-ts-dirty-line nil
687 "Token stream buffer-local variable.
688 Indicates stuff other than whitespace since start of line.")
689
690 (js2-deflocal js2-ts-regexp-flags nil
691 "Token stream buffer-local variable.")
692
693 (js2-deflocal js2-ts-string ""
694 "Token stream buffer-local variable.
695 Last string scanned.")
696
697 (js2-deflocal js2-ts-number nil
698 "Token stream buffer-local variable.
699 Last literal number scanned.")
700
701 (js2-deflocal js2-ts-hit-eof nil
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-line-start 0
705 "Token stream buffer-local variable.")
706
707 (js2-deflocal js2-ts-lineno 1
708 "Token stream buffer-local variable.")
709
710 (js2-deflocal js2-ts-line-end-char -1
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
714 "Token stream buffer-local variable.
715 Current scan position.")
716
717 (js2-deflocal js2-ts-is-xml-attribute nil
718 "Token stream buffer-local variable.")
719
720 (js2-deflocal js2-ts-xml-is-tag-content nil
721 "Token stream buffer-local variable.")
722
723 (js2-deflocal js2-ts-xml-open-tags-count 0
724 "Token stream buffer-local variable.")
725
726 (js2-deflocal js2-ts-string-buffer nil
727 "Token stream buffer-local variable.
728 List of chars built up while scanning various tokens.")
729
730 (js2-deflocal js2-ts-comment-type nil
731 "Token stream buffer-local variable.")
732
733 ;;; Parser variables
734
735 (js2-deflocal js2-parsed-errors nil
736 "List of errors produced during scanning/parsing.")
737
738 (js2-deflocal js2-parsed-warnings nil
739 "List of warnings produced during scanning/parsing.")
740
741 (js2-deflocal js2-recover-from-parse-errors t
742 "Non-nil to continue parsing after a syntax error.
743
744 In recovery mode, the AST will be built in full, and any error
745 nodes will be flagged with appropriate error information. If
746 this flag is nil, a syntax error will result in an error being
747 signaled.
748
749 The variable is automatically buffer-local, because different
750 modes that use the parser will need different settings.")
751
752 (js2-deflocal js2-parse-hook nil
753 "List of callbacks for receiving parsing progress.")
754
755 (defvar js2-parse-finished-hook nil
756 "List of callbacks to notify when parsing finishes.
757 Not called if parsing was interrupted.")
758
759 (js2-deflocal js2-is-eval-code nil
760 "True if we're evaluating code in a string.
761 If non-nil, the tokenizer will record the token text, and the AST nodes
762 will record their source text. Off by default for IDE modes, since the
763 text is available in the buffer.")
764
765 (defvar js2-parse-ide-mode t
766 "Non-nil if the parser is being used for `js2-mode'.
767 If non-nil, the parser will set text properties for fontification
768 and the syntax table. The value should be nil when using the
769 parser as a frontend to an interpreter or byte compiler.")
770
771 ;;; Parser instance variables (buffer-local vars for js2-parse)
772
773 (defconst js2-clear-ti-mask #xFFFF
774 "Mask to clear token information bits.")
775
776 (defconst js2-ti-after-eol (lsh 1 16)
777 "Flag: first token of the source line.")
778
779 (defconst js2-ti-check-label (lsh 1 17)
780 "Flag: indicates to check for label.")
781
782 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
783
784 (js2-deflocal js2-compiler-generate-debug-info t)
785 (js2-deflocal js2-compiler-use-dynamic-scope nil)
786 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
787 (js2-deflocal js2-compiler-xml-available t)
788 (js2-deflocal js2-compiler-optimization-level 0)
789 (js2-deflocal js2-compiler-generating-source t)
790 (js2-deflocal js2-compiler-strict-mode nil)
791 (js2-deflocal js2-compiler-report-warning-as-error nil)
792 (js2-deflocal js2-compiler-generate-observer-count nil)
793 (js2-deflocal js2-compiler-activation-names nil)
794
795 ;; SKIP: sourceURI
796
797 ;; There's a compileFunction method in Context.java - may need it.
798 (js2-deflocal js2-called-by-compile-function nil
799 "True if `js2-parse' was called by `js2-compile-function'.
800 Will only be used when we finish implementing the interpreter.")
801
802 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
803
804 (js2-deflocal js2-current-flagged-token js2-EOF)
805 (js2-deflocal js2-current-token js2-EOF)
806
807 ;; SKIP: node factory - we're going to just call functions directly,
808 ;; and eventually go to a unified AST format.
809
810 (js2-deflocal js2-nesting-of-function 0)
811
812 (js2-deflocal js2-recorded-identifiers nil
813 "Tracks identifiers found during parsing.")
814
815 (defmacro js2-in-lhs (body)
816 `(let ((js2-is-in-lhs t))
817 ,body))
818
819 (defmacro js2-in-rhs (body)
820 `(let ((js2-is-in-lhs nil))
821 ,body))
822
823 (js2-deflocal js2-is-in-lhs nil
824 "True while parsing lhs statement")
825
826 (defcustom js2-global-externs nil
827 "A list of any extern names you'd like to consider always declared.
828 This list is global and is used by all js2-mode files.
829 You can create buffer-local externs list using `js2-additional-externs'.
830
831 There is also a buffer-local variable `js2-default-externs',
832 which is initialized by default to include the Ecma-262 externs
833 and the standard browser externs. The three lists are all
834 checked during highlighting."
835 :type 'list
836 :group 'js2-mode)
837
838 (js2-deflocal js2-default-externs nil
839 "Default external declarations.
840
841 These are currently only used for highlighting undeclared variables,
842 which only worries about top-level (unqualified) references.
843 As js2-mode's processing improves, we will flesh out this list.
844
845 The initial value is set to `js2-ecma-262-externs', unless you
846 have set `js2-include-browser-externs', in which case the browser
847 externs are also included.
848
849 See `js2-additional-externs' for more information.")
850
851 (defcustom js2-include-browser-externs t
852 "Non-nil to include browser externs in the master externs list.
853 If you work on JavaScript files that are not intended for browsers,
854 such as Mozilla Rhino server-side JavaScript, set this to nil.
855 You can always include them on a per-file basis by calling
856 `js2-add-browser-externs' from a function on `js2-mode-hook'.
857
858 See `js2-additional-externs' for more information about externs."
859 :type 'boolean
860 :group 'js2-mode)
861
862 (defcustom js2-include-rhino-externs t
863 "Non-nil to include Mozilla Rhino externs in the master externs list.
864 See `js2-additional-externs' for more information about externs."
865 :type 'boolean
866 :group 'js2-mode)
867
868 (defcustom js2-include-gears-externs t
869 "Non-nil to include Google Gears externs in the master externs list.
870 See `js2-additional-externs' for more information about externs."
871 :type 'boolean
872 :group 'js2-mode)
873
874 (js2-deflocal js2-additional-externs nil
875 "A buffer-local list of additional external declarations.
876 It is used to decide whether variables are considered undeclared
877 for purposes of highlighting.
878
879 Each entry is a lisp string. The string should be the fully qualified
880 name of an external entity. All externs should be added to this list,
881 so that as js2-mode's processing improves it can take advantage of them.
882
883 You may want to declare your externs in three ways.
884 First, you can add externs that are valid for all your JavaScript files.
885 You should probably do this by adding them to `js2-global-externs', which
886 is a global list used for all js2-mode files.
887
888 Next, you can add a function to `js2-mode-hook' that adds additional
889 externs appropriate for the specific file, perhaps based on its path.
890 These should go in `js2-additional-externs', which is buffer-local.
891
892 Finally, you can add a function to `js2-post-parse-callbacks',
893 which is called after parsing completes, and `root' is bound to
894 the root of the parse tree. At this stage you can set up an AST
895 node visitor using `js2-visit-ast' and examine the parse tree
896 for specific import patterns that may imply the existence of
897 other externs, possibly tied to your build system. These should also
898 be added to `js2-additional-externs'.
899
900 Your post-parse callback may of course also use the simpler and
901 faster (but perhaps less robust) approach of simply scanning the
902 buffer text for your imports, using regular expressions.")
903
904 ;; SKIP: decompiler
905 ;; SKIP: encoded-source
906
907 ;;; The following variables are per-function and should be saved/restored
908 ;;; during function parsing...
909
910 (js2-deflocal js2-current-script-or-fn nil)
911 (js2-deflocal js2-current-scope nil)
912 (js2-deflocal js2-nesting-of-with 0)
913 (js2-deflocal js2-label-set nil
914 "An alist mapping label names to nodes.")
915
916 (js2-deflocal js2-loop-set nil)
917 (js2-deflocal js2-loop-and-switch-set nil)
918 (js2-deflocal js2-has-return-value nil)
919 (js2-deflocal js2-end-flags 0)
920
921 ;;; ...end of per function variables
922
923 ;; Without 2-token lookahead, labels are a problem.
924 ;; These vars store the token info of the last matched name,
925 ;; iff it wasn't the last matched token. Only valid in some contexts.
926 (defvar js2-prev-name-token-start nil)
927 (defvar js2-prev-name-token-string nil)
928
929 (defsubst js2-save-name-token-data (pos name)
930 (setq js2-prev-name-token-start pos
931 js2-prev-name-token-string name))
932
933 ;; These flags enumerate the possible ways a statement/function can
934 ;; terminate. These flags are used by endCheck() and by the Parser to
935 ;; detect inconsistent return usage.
936 ;;
937 ;; END_UNREACHED is reserved for code paths that are assumed to always be
938 ;; able to execute (example: throw, continue)
939 ;;
940 ;; END_DROPS_OFF indicates if the statement can transfer control to the
941 ;; next one. Statement such as return dont. A compound statement may have
942 ;; some branch that drops off control to the next statement.
943 ;;
944 ;; END_RETURNS indicates that the statement can return (without arguments)
945 ;; END_RETURNS_VALUE indicates that the statement can return a value.
946 ;;
947 ;; A compound statement such as
948 ;; if (condition) {
949 ;; return value;
950 ;; }
951 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
952
953 (defconst js2-end-unreached #x0)
954 (defconst js2-end-drops-off #x1)
955 (defconst js2-end-returns #x2)
956 (defconst js2-end-returns-value #x4)
957 (defconst js2-end-yields #x8)
958
959 ;; Rhino awkwardly passes a statementLabel parameter to the
960 ;; statementHelper() function, the main statement parser, which
961 ;; is then used by quite a few of the sub-parsers. We just make
962 ;; it a buffer-local variable and make sure it's cleaned up properly.
963 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
964
965 ;; Similarly, Rhino passes an inForInit boolean through about half
966 ;; the expression parsers. We use a dynamically-scoped variable,
967 ;; which makes it easier to funcall the parsers individually without
968 ;; worrying about whether they take the parameter or not.
969 (js2-deflocal js2-in-for-init nil)
970 (js2-deflocal js2-temp-name-counter 0)
971 (js2-deflocal js2-parse-stmt-count 0)
972
973 (defsubst js2-get-next-temp-name ()
974 (format "$%d" (incf js2-temp-name-counter)))
975
976 (defvar js2-parse-interruptable-p t
977 "Set this to nil to force parse to continue until finished.
978 This will mostly be useful for interpreters.")
979
980 (defvar js2-statements-per-pause 50
981 "Pause after this many statements to check for user input.
982 If user input is pending, stop the parse and discard the tree.
983 This makes for a smoother user experience for large files.
984 You may have to wait a second or two before the highlighting
985 and error-reporting appear, but you can always type ahead if
986 you wish. This appears to be more or less how Eclipse, IntelliJ
987 and other editors work.")
988
989 (js2-deflocal js2-record-comments t
990 "Instructs the scanner to record comments in `js2-scanned-comments'.")
991
992 (js2-deflocal js2-scanned-comments nil
993 "List of all comments from the current parse.")
994
995 (defcustom js2-mode-indent-inhibit-undo nil
996 "Non-nil to disable collection of Undo information when indenting lines.
997 Some users have requested this behavior. It's nil by default because
998 other Emacs modes don't work this way."
999 :type 'boolean
1000 :group 'js2-mode)
1001
1002 (defcustom js2-mode-indent-ignore-first-tab nil
1003 "If non-nil, ignore first TAB keypress if we look indented properly.
1004 It's fairly common for users to navigate to an already-indented line
1005 and press TAB for reassurance that it's been indented. For this class
1006 of users, we want the first TAB press on a line to be ignored if the
1007 line is already indented to one of the precomputed alternatives.
1008
1009 This behavior is only partly implemented. If you TAB-indent a line,
1010 navigate to another line, and then navigate back, it fails to clear
1011 the last-indented variable, so it thinks you've already hit TAB once,
1012 and performs the indent. A full solution would involve getting on the
1013 point-motion hooks for the entire buffer. If we come across another
1014 use cases that requires watching point motion, I'll consider doing it.
1015
1016 If you set this variable to nil, then the TAB key will always change
1017 the indentation of the current line, if more than one alternative
1018 indentation spot exists."
1019 :type 'boolean
1020 :group 'js2-mode)
1021
1022 (defvar js2-indent-hook nil
1023 "A hook for user-defined indentation rules.
1024
1025 Functions on this hook should expect two arguments: (LIST INDEX)
1026 The LIST argument is the list of computed indentation points for
1027 the current line. INDEX is the list index of the indentation point
1028 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1029 indent function is not going to change the current line indentation.
1030
1031 If a hook function on this list returns a non-nil value, then
1032 `js2-bounce-indent' assumes the hook function has performed its own
1033 indentation, and will do nothing. If all hook functions on the list
1034 return nil, then `js2-bounce-indent' will use its computed indentation
1035 and reindent the line.
1036
1037 When hook functions on this hook list are called, the variable
1038 `js2-mode-ast' may or may not be set, depending on whether the
1039 parse tree is available. If the variable is nil, you can pass a
1040 callback to `js2-mode-wait-for-parse', and your callback will be
1041 called after the new parse tree is built. This can take some time
1042 in large files.")
1043
1044 (defface js2-warning-face
1045 `((((class color) (background light))
1046 (:underline "orange"))
1047 (((class color) (background dark))
1048 (:underline "orange"))
1049 (t (:underline t)))
1050 "Face for JavaScript warnings."
1051 :group 'js2-mode)
1052
1053 (defface js2-error-face
1054 `((((class color) (background light))
1055 (:foreground "red"))
1056 (((class color) (background dark))
1057 (:foreground "red"))
1058 (t (:foreground "red")))
1059 "Face for JavaScript errors."
1060 :group 'js2-mode)
1061
1062 (defface js2-jsdoc-tag-face
1063 '((t :foreground "SlateGray"))
1064 "Face used to highlight @whatever tags in jsdoc comments."
1065 :group 'js2-mode)
1066
1067 (defface js2-jsdoc-type-face
1068 '((t :foreground "SteelBlue"))
1069 "Face used to highlight {FooBar} types in jsdoc comments."
1070 :group 'js2-mode)
1071
1072 (defface js2-jsdoc-value-face
1073 '((t :foreground "PeachPuff3"))
1074 "Face used to highlight tag values in jsdoc comments."
1075 :group 'js2-mode)
1076
1077 (defface js2-function-param-face
1078 '((t :foreground "SeaGreen"))
1079 "Face used to highlight function parameters in javascript."
1080 :group 'js2-mode)
1081
1082 (defface js2-instance-member-face
1083 '((t :foreground "DarkOrchid"))
1084 "Face used to highlight instance variables in javascript.
1085 Not currently used."
1086 :group 'js2-mode)
1087
1088 (defface js2-private-member-face
1089 '((t :foreground "PeachPuff3"))
1090 "Face used to highlight calls to private methods in javascript.
1091 Not currently used."
1092 :group 'js2-mode)
1093
1094 (defface js2-private-function-call-face
1095 '((t :foreground "goldenrod"))
1096 "Face used to highlight calls to private functions in javascript.
1097 Not currently used."
1098 :group 'js2-mode)
1099
1100 (defface js2-jsdoc-html-tag-name-face
1101 (if js2-emacs22
1102 '((((class color) (min-colors 88) (background light))
1103 (:foreground "rosybrown"))
1104 (((class color) (min-colors 8) (background dark))
1105 (:foreground "yellow"))
1106 (((class color) (min-colors 8) (background light))
1107 (:foreground "magenta")))
1108 '((((type tty pc) (class color) (background light))
1109 (:foreground "magenta"))
1110 (((type tty pc) (class color) (background dark))
1111 (:foreground "yellow"))
1112 (t (:foreground "RosyBrown"))))
1113 "Face used to highlight jsdoc html tag names"
1114 :group 'js2-mode)
1115
1116 (defface js2-jsdoc-html-tag-delimiter-face
1117 (if js2-emacs22
1118 '((((class color) (min-colors 88) (background light))
1119 (:foreground "dark khaki"))
1120 (((class color) (min-colors 8) (background dark))
1121 (:foreground "green"))
1122 (((class color) (min-colors 8) (background light))
1123 (:foreground "green")))
1124 '((((type tty pc) (class color) (background light))
1125 (:foreground "green"))
1126 (((type tty pc) (class color) (background dark))
1127 (:foreground "green"))
1128 (t (:foreground "dark khaki"))))
1129 "Face used to highlight brackets in jsdoc html tags."
1130 :group 'js2-mode)
1131
1132 (defface js2-magic-paren-face
1133 '((t :underline t))
1134 "Face used to color parens that will be auto-overwritten."
1135 :group 'js2-mode)
1136
1137 (defcustom js2-post-parse-callbacks nil
1138 "A list of callback functions invoked after parsing finishes.
1139 Currently, the main use for this function is to add synthetic
1140 declarations to `js2-recorded-identifiers', which see."
1141 :type 'list
1142 :group 'js2-mode)
1143
1144 (defface js2-external-variable-face
1145 '((t :foreground "orange"))
1146 "Face used to highlight undeclared variable identifiers.
1147 An undeclared variable is any variable not declared with var or let
1148 in the current scope or any lexically enclosing scope. If you use
1149 such a variable, then you are either expecting it to originate from
1150 another file, or you've got a potential bug."
1151 :group 'js2-mode)
1152
1153 (defcustom js2-highlight-external-variables t
1154 "Non-nil to highlight undeclared variable identifiers."
1155 :type 'boolean
1156 :group 'js2-mode)
1157
1158 (defcustom js2-auto-insert-catch-block t
1159 "Non-nil to insert matching catch block on open-curly after `try'."
1160 :type 'boolean
1161 :group 'js2-mode)
1162
1163 (defvar js2-mode-map
1164 (let ((map (make-sparse-keymap))
1165 keys)
1166 (define-key map [mouse-1] #'js2-mode-show-node)
1167 (define-key map (kbd "C-m") #'js2-enter-key)
1168 (when js2-rebind-eol-bol-keys
1169 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1170 (define-key map (kbd "C-e") #'js2-end-of-line))
1171 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1172 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1173 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1174 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1175 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1176 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1177 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1178 (define-key map (kbd "C-c C-`") #'js2-next-error)
1179 ;; also define user's preference for next-error, if available
1180 (if (setq keys (where-is-internal #'next-error))
1181 (define-key map (car keys) #'js2-next-error))
1182 (define-key map (or (car (where-is-internal #'mark-defun))
1183 (kbd "M-C-h"))
1184 #'js2-mark-defun)
1185 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1186 (kbd "C-x nd"))
1187 #'js2-narrow-to-defun)
1188 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1189 (when js2-auto-indent-p
1190 (mapc (lambda (key)
1191 (define-key map key #'js2-insert-and-indent))
1192 js2-electric-keys))
1193 (when js2-bounce-indent-p
1194 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1195
1196 (define-key map [menu-bar javascript]
1197 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1198
1199 (define-key map [menu-bar javascript customize-js2-mode]
1200 '(menu-item "Customize js2-mode" js2-mode-customize
1201 :help "Customize the behavior of this mode"))
1202
1203 (define-key map [menu-bar javascript js2-force-refresh]
1204 '(menu-item "Force buffer refresh" js2-mode-reset
1205 :help "Re-parse the buffer from scratch"))
1206
1207 (define-key map [menu-bar javascript separator-2]
1208 '("--"))
1209
1210 (define-key map [menu-bar javascript next-error]
1211 '(menu-item "Next warning or error" js2-next-error
1212 :enabled (and js2-mode-ast
1213 (or (js2-ast-root-errors js2-mode-ast)
1214 (js2-ast-root-warnings js2-mode-ast)))
1215 :help "Move to next warning or error"))
1216
1217 (define-key map [menu-bar javascript display-errors]
1218 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1219 :visible (not js2-mode-show-parse-errors)
1220 :help "Turn on display of warnings and errors"))
1221
1222 (define-key map [menu-bar javascript hide-errors]
1223 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1224 :visible js2-mode-show-parse-errors
1225 :help "Turn off display of warnings and errors"))
1226
1227 (define-key map [menu-bar javascript separator-1]
1228 '("--"))
1229
1230 (define-key map [menu-bar javascript js2-toggle-function]
1231 '(menu-item "Show/collapse element" js2-mode-toggle-element
1232 :help "Hide or show function body or comment"))
1233
1234 (define-key map [menu-bar javascript show-comments]
1235 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1236 :visible js2-mode-comments-hidden
1237 :help "Expand all hidden block comments"))
1238
1239 (define-key map [menu-bar javascript hide-comments]
1240 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1241 :visible (not js2-mode-comments-hidden)
1242 :help "Show block comments as /*...*/"))
1243
1244 (define-key map [menu-bar javascript show-all-functions]
1245 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1246 :visible js2-mode-functions-hidden
1247 :help "Expand all hidden function bodies"))
1248
1249 (define-key map [menu-bar javascript hide-all-functions]
1250 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1251 :visible (not js2-mode-functions-hidden)
1252 :help "Show {...} for all top-level function bodies"))
1253
1254 map)
1255 "Keymap used in `js2-mode' buffers.")
1256
1257 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1258
1259 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1260 "Matches a //-comment line. Must be first non-whitespace on line.
1261 First match-group is the leading whitespace.")
1262
1263 (defvar js2-mode-hook nil)
1264
1265 (js2-deflocal js2-mode-ast nil "Private variable.")
1266 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1267 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1268 (js2-deflocal js2-mode-parsing nil "Private variable.")
1269 (js2-deflocal js2-mode-node-overlay nil)
1270
1271 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1272 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1273
1274 (js2-deflocal js2-mode-fontifications nil "Private variable")
1275 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1276 (js2-deflocal js2-imenu-recorder nil "Private variable")
1277 (js2-deflocal js2-imenu-function-map nil "Private variable")
1278
1279 (defvar js2-paragraph-start
1280 "\\(@[a-zA-Z]+\\>\\|$\\)")
1281
1282 ;; Note that we also set a 'c-in-sws text property in html comments,
1283 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1284 (defvar js2-syntactic-ws-start
1285 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1286
1287 (defvar js2-syntactic-ws-end
1288 "\\s \\|[\n\r/]\\|\\s!")
1289
1290 (defvar js2-syntactic-eol
1291 (concat "\\s *\\(/\\*[^*\n\r]*"
1292 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1293 "\\*+/\\s *\\)*"
1294 "\\(//\\|/\\*[^*\n\r]*"
1295 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1296 "\\|\\\\$\\|$\\)")
1297 "Copied from `java-mode'. Needed for some cc-engine functions.")
1298
1299 (defvar js2-comment-prefix-regexp
1300 "//+\\|\\**")
1301
1302 (defvar js2-comment-start-skip
1303 "\\(//+\\|/\\*+\\)\\s *")
1304
1305 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1306 "Non-nil to emit status messages during parsing.")
1307
1308 (defvar js2-mode-functions-hidden nil "private variable")
1309 (defvar js2-mode-comments-hidden nil "private variable")
1310
1311 (defvar js2-mode-syntax-table
1312 (let ((table (make-syntax-table)))
1313 (c-populate-syntax-table table)
1314 table)
1315 "Syntax table used in js2-mode buffers.")
1316
1317 (defvar js2-mode-abbrev-table nil
1318 "Abbrev table in use in `js2-mode' buffers.")
1319 (define-abbrev-table 'js2-mode-abbrev-table ())
1320
1321 (defvar js2-mode-pending-parse-callbacks nil
1322 "List of functions waiting to be notified that parse is finished.")
1323
1324 (defvar js2-mode-last-indented-line -1)
1325
1326 ;;; Localizable error and warning messages
1327
1328 ;; Messages are copied from Rhino's Messages.properties.
1329 ;; Many of the Java-specific messages have been elided.
1330 ;; Add any js2-specific ones at the end, so we can keep
1331 ;; this file synced with changes to Rhino's.
1332
1333 (defvar js2-message-table
1334 (make-hash-table :test 'equal :size 250)
1335 "Contains localized messages for js2-mode.")
1336
1337 ;; TODO(stevey): construct this table at compile-time.
1338 (defmacro js2-msg (key &rest strings)
1339 `(puthash ,key (funcall #'concat ,@strings)
1340 js2-message-table))
1341
1342 (defun js2-get-msg (msg-key)
1343 "Look up a localized message.
1344 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1345 the correct number of ARGS must be provided."
1346 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1347 (args (if (listp msg-key) (cdr msg-key)))
1348 (msg (gethash key js2-message-table)))
1349 (if msg
1350 (apply #'format msg args)
1351 key))) ; default to showing the key
1352
1353 (js2-msg "msg.dup.parms"
1354 "Duplicate parameter name '%s'.")
1355
1356 (js2-msg "msg.too.big.jump"
1357 "Program too complex: jump offset too big.")
1358
1359 (js2-msg "msg.too.big.index"
1360 "Program too complex: internal index exceeds 64K limit.")
1361
1362 (js2-msg "msg.while.compiling.fn"
1363 "Encountered code generation error while compiling function '%s': %s")
1364
1365 (js2-msg "msg.while.compiling.script"
1366 "Encountered code generation error while compiling script: %s")
1367
1368 ;; Context
1369 (js2-msg "msg.ctor.not.found"
1370 "Constructor for '%s' not found.")
1371
1372 (js2-msg "msg.not.ctor"
1373 "'%s' is not a constructor.")
1374
1375 ;; FunctionObject
1376 (js2-msg "msg.varargs.ctor"
1377 "Method or constructor '%s' must be static "
1378 "with the signature (Context cx, Object[] args, "
1379 "Function ctorObj, boolean inNewExpr) "
1380 "to define a variable arguments constructor.")
1381
1382 (js2-msg "msg.varargs.fun"
1383 "Method '%s' must be static with the signature "
1384 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1385 "to define a variable arguments function.")
1386
1387 (js2-msg "msg.incompat.call"
1388 "Method '%s' called on incompatible object.")
1389
1390 (js2-msg "msg.bad.parms"
1391 "Unsupported parameter type '%s' in method '%s'.")
1392
1393 (js2-msg "msg.bad.method.return"
1394 "Unsupported return type '%s' in method '%s'.")
1395
1396 (js2-msg "msg.bad.ctor.return"
1397 "Construction of objects of type '%s' is not supported.")
1398
1399 (js2-msg "msg.no.overload"
1400 "Method '%s' occurs multiple times in class '%s'.")
1401
1402 (js2-msg "msg.method.not.found"
1403 "Method '%s' not found in '%s'.")
1404
1405 ;; IRFactory
1406
1407 (js2-msg "msg.bad.for.in.lhs"
1408 "Invalid left-hand side of for..in loop.")
1409
1410 (js2-msg "msg.mult.index"
1411 "Only one variable allowed in for..in loop.")
1412
1413 (js2-msg "msg.bad.for.in.destruct"
1414 "Left hand side of for..in loop must be an array of "
1415 "length 2 to accept key/value pair.")
1416
1417 (js2-msg "msg.cant.convert"
1418 "Can't convert to type '%s'.")
1419
1420 (js2-msg "msg.bad.assign.left"
1421 "Invalid assignment left-hand side.")
1422
1423 (js2-msg "msg.bad.decr"
1424 "Invalid decerement operand.")
1425
1426 (js2-msg "msg.bad.incr"
1427 "Invalid increment operand.")
1428
1429 (js2-msg "msg.bad.yield"
1430 "yield must be in a function.")
1431
1432 (js2-msg "msg.yield.parenthesized"
1433 "yield expression must be parenthesized.")
1434
1435 ;; NativeGlobal
1436 (js2-msg "msg.cant.call.indirect"
1437 "Function '%s' must be called directly, and not by way of a "
1438 "function of another name.")
1439
1440 (js2-msg "msg.eval.nonstring"
1441 "Calling eval() with anything other than a primitive "
1442 "string value will simply return the value. "
1443 "Is this what you intended?")
1444
1445 (js2-msg "msg.eval.nonstring.strict"
1446 "Calling eval() with anything other than a primitive "
1447 "string value is not allowed in strict mode.")
1448
1449 (js2-msg "msg.bad.destruct.op"
1450 "Invalid destructuring assignment operator")
1451
1452 ;; NativeCall
1453 (js2-msg "msg.only.from.new"
1454 "'%s' may only be invoked from a `new' expression.")
1455
1456 (js2-msg "msg.deprec.ctor"
1457 "The '%s' constructor is deprecated.")
1458
1459 ;; NativeFunction
1460 (js2-msg "msg.no.function.ref.found"
1461 "no source found to decompile function reference %s")
1462
1463 (js2-msg "msg.arg.isnt.array"
1464 "second argument to Function.prototype.apply must be an array")
1465
1466 ;; NativeGlobal
1467 (js2-msg "msg.bad.esc.mask"
1468 "invalid string escape mask")
1469
1470 ;; NativeRegExp
1471 (js2-msg "msg.bad.quant"
1472 "Invalid quantifier %s")
1473
1474 (js2-msg "msg.overlarge.backref"
1475 "Overly large back reference %s")
1476
1477 (js2-msg "msg.overlarge.min"
1478 "Overly large minimum %s")
1479
1480 (js2-msg "msg.overlarge.max"
1481 "Overly large maximum %s")
1482
1483 (js2-msg "msg.zero.quant"
1484 "Zero quantifier %s")
1485
1486 (js2-msg "msg.max.lt.min"
1487 "Maximum %s less than minimum")
1488
1489 (js2-msg "msg.unterm.quant"
1490 "Unterminated quantifier %s")
1491
1492 (js2-msg "msg.unterm.paren"
1493 "Unterminated parenthetical %s")
1494
1495 (js2-msg "msg.unterm.class"
1496 "Unterminated character class %s")
1497
1498 (js2-msg "msg.bad.range"
1499 "Invalid range in character class.")
1500
1501 (js2-msg "msg.trail.backslash"
1502 "Trailing \\ in regular expression.")
1503
1504 (js2-msg "msg.re.unmatched.right.paren"
1505 "unmatched ) in regular expression.")
1506
1507 (js2-msg "msg.no.regexp"
1508 "Regular expressions are not available.")
1509
1510 (js2-msg "msg.bad.backref"
1511 "back-reference exceeds number of capturing parentheses.")
1512
1513 (js2-msg "msg.bad.regexp.compile"
1514 "Only one argument may be specified if the first "
1515 "argument to RegExp.prototype.compile is a RegExp object.")
1516
1517 ;; Parser
1518 (js2-msg "msg.got.syntax.errors"
1519 "Compilation produced %s syntax errors.")
1520
1521 (js2-msg "msg.var.redecl"
1522 "TypeError: redeclaration of var %s.")
1523
1524 (js2-msg "msg.const.redecl"
1525 "TypeError: redeclaration of const %s.")
1526
1527 (js2-msg "msg.let.redecl"
1528 "TypeError: redeclaration of variable %s.")
1529
1530 (js2-msg "msg.parm.redecl"
1531 "TypeError: redeclaration of formal parameter %s.")
1532
1533 (js2-msg "msg.fn.redecl"
1534 "TypeError: redeclaration of function %s.")
1535
1536 (js2-msg "msg.let.decl.not.in.block"
1537 "SyntaxError: let declaration not directly within block")
1538
1539 ;; NodeTransformer
1540 (js2-msg "msg.dup.label"
1541 "duplicated label")
1542
1543 (js2-msg "msg.undef.label"
1544 "undefined label")
1545
1546 (js2-msg "msg.bad.break"
1547 "unlabelled break must be inside loop or switch")
1548
1549 (js2-msg "msg.continue.outside"
1550 "continue must be inside loop")
1551
1552 (js2-msg "msg.continue.nonloop"
1553 "continue can only use labels of iteration statements")
1554
1555 (js2-msg "msg.bad.throw.eol"
1556 "Line terminator is not allowed between the throw "
1557 "keyword and throw expression.")
1558
1559 (js2-msg "msg.no.paren.parms"
1560 "missing ( before function parameters.")
1561
1562 (js2-msg "msg.no.parm"
1563 "missing formal parameter")
1564
1565 (js2-msg "msg.no.paren.after.parms"
1566 "missing ) after formal parameters")
1567
1568 (js2-msg "msg.no.brace.body"
1569 "missing '{' before function body")
1570
1571 (js2-msg "msg.no.brace.after.body"
1572 "missing } after function body")
1573
1574 (js2-msg "msg.no.paren.cond"
1575 "missing ( before condition")
1576
1577 (js2-msg "msg.no.paren.after.cond"
1578 "missing ) after condition")
1579
1580 (js2-msg "msg.no.semi.stmt"
1581 "missing ; before statement")
1582
1583 (js2-msg "msg.missing.semi"
1584 "missing ; after statement")
1585
1586 (js2-msg "msg.no.name.after.dot"
1587 "missing name after . operator")
1588
1589 (js2-msg "msg.no.name.after.coloncolon"
1590 "missing name after :: operator")
1591
1592 (js2-msg "msg.no.name.after.dotdot"
1593 "missing name after .. operator")
1594
1595 (js2-msg "msg.no.name.after.xmlAttr"
1596 "missing name after .@")
1597
1598 (js2-msg "msg.no.bracket.index"
1599 "missing ] in index expression")
1600
1601 (js2-msg "msg.no.paren.switch"
1602 "missing ( before switch expression")
1603
1604 (js2-msg "msg.no.paren.after.switch"
1605 "missing ) after switch expression")
1606
1607 (js2-msg "msg.no.brace.switch"
1608 "missing '{' before switch body")
1609
1610 (js2-msg "msg.bad.switch"
1611 "invalid switch statement")
1612
1613 (js2-msg "msg.no.colon.case"
1614 "missing : after case expression")
1615
1616 (js2-msg "msg.double.switch.default"
1617 "double default label in the switch statement")
1618
1619 (js2-msg "msg.no.while.do"
1620 "missing while after do-loop body")
1621
1622 (js2-msg "msg.no.paren.for"
1623 "missing ( after for")
1624
1625 (js2-msg "msg.no.semi.for"
1626 "missing ; after for-loop initializer")
1627
1628 (js2-msg "msg.no.semi.for.cond"
1629 "missing ; after for-loop condition")
1630
1631 (js2-msg "msg.in.after.for.name"
1632 "missing in after for")
1633
1634 (js2-msg "msg.no.paren.for.ctrl"
1635 "missing ) after for-loop control")
1636
1637 (js2-msg "msg.no.paren.with"
1638 "missing ( before with-statement object")
1639
1640 (js2-msg "msg.no.paren.after.with"
1641 "missing ) after with-statement object")
1642
1643 (js2-msg "msg.no.paren.after.let"
1644 "missing ( after let")
1645
1646 (js2-msg "msg.no.paren.let"
1647 "missing ) after variable list")
1648
1649 (js2-msg "msg.no.curly.let"
1650 "missing } after let statement")
1651
1652 (js2-msg "msg.bad.return"
1653 "invalid return")
1654
1655 (js2-msg "msg.no.brace.block"
1656 "missing } in compound statement")
1657
1658 (js2-msg "msg.bad.label"
1659 "invalid label")
1660
1661 (js2-msg "msg.bad.var"
1662 "missing variable name")
1663
1664 (js2-msg "msg.bad.var.init"
1665 "invalid variable initialization")
1666
1667 (js2-msg "msg.no.colon.cond"
1668 "missing : in conditional expression")
1669
1670 (js2-msg "msg.no.paren.arg"
1671 "missing ) after argument list")
1672
1673 (js2-msg "msg.no.bracket.arg"
1674 "missing ] after element list")
1675
1676 (js2-msg "msg.bad.prop"
1677 "invalid property id")
1678
1679 (js2-msg "msg.no.colon.prop"
1680 "missing : after property id")
1681
1682 (js2-msg "msg.no.brace.prop"
1683 "missing } after property list")
1684
1685 (js2-msg "msg.no.paren"
1686 "missing ) in parenthetical")
1687
1688 (js2-msg "msg.reserved.id"
1689 "identifier is a reserved word")
1690
1691 (js2-msg "msg.no.paren.catch"
1692 "missing ( before catch-block condition")
1693
1694 (js2-msg "msg.bad.catchcond"
1695 "invalid catch block condition")
1696
1697 (js2-msg "msg.catch.unreachable"
1698 "any catch clauses following an unqualified catch are unreachable")
1699
1700 (js2-msg "msg.no.brace.try"
1701 "missing '{' before try block")
1702
1703 (js2-msg "msg.no.brace.catchblock"
1704 "missing '{' before catch-block body")
1705
1706 (js2-msg "msg.try.no.catchfinally"
1707 "'try' without 'catch' or 'finally'")
1708
1709 (js2-msg "msg.no.return.value"
1710 "function %s does not always return a value")
1711
1712 (js2-msg "msg.anon.no.return.value"
1713 "anonymous function does not always return a value")
1714
1715 (js2-msg "msg.return.inconsistent"
1716 "return statement is inconsistent with previous usage")
1717
1718 (js2-msg "msg.generator.returns"
1719 "TypeError: generator function '%s' returns a value")
1720
1721 (js2-msg "msg.anon.generator.returns"
1722 "TypeError: anonymous generator function returns a value")
1723
1724 (js2-msg "msg.syntax"
1725 "syntax error")
1726
1727 (js2-msg "msg.unexpected.eof"
1728 "Unexpected end of file")
1729
1730 (js2-msg "msg.XML.bad.form"
1731 "illegally formed XML syntax")
1732
1733 (js2-msg "msg.XML.not.available"
1734 "XML runtime not available")
1735
1736 (js2-msg "msg.too.deep.parser.recursion"
1737 "Too deep recursion while parsing")
1738
1739 (js2-msg "msg.no.side.effects"
1740 "Code has no side effects")
1741
1742 (js2-msg "msg.extra.trailing.comma"
1743 "Trailing comma is not legal in an ECMA-262 object initializer")
1744
1745 (js2-msg "msg.array.trailing.comma"
1746 "Trailing comma yields different behavior across browsers")
1747
1748 (js2-msg "msg.equal.as.assign"
1749 (concat "Test for equality (==) mistyped as assignment (=)?"
1750 " (parenthesize to suppress warning)"))
1751
1752 (js2-msg "msg.var.hides.arg"
1753 "Variable %s hides argument")
1754
1755 (js2-msg "msg.destruct.assign.no.init"
1756 "Missing = in destructuring declaration")
1757
1758 ;; ScriptRuntime
1759 (js2-msg "msg.no.properties"
1760 "%s has no properties.")
1761
1762 (js2-msg "msg.invalid.iterator"
1763 "Invalid iterator value")
1764
1765 (js2-msg "msg.iterator.primitive"
1766 "__iterator__ returned a primitive value")
1767
1768 (js2-msg "msg.assn.create.strict"
1769 "Assignment to undeclared variable %s")
1770
1771 (js2-msg "msg.ref.undefined.prop"
1772 "Reference to undefined property '%s'")
1773
1774 (js2-msg "msg.prop.not.found"
1775 "Property %s not found.")
1776
1777 (js2-msg "msg.invalid.type"
1778 "Invalid JavaScript value of type %s")
1779
1780 (js2-msg "msg.primitive.expected"
1781 "Primitive type expected (had %s instead)")
1782
1783 (js2-msg "msg.namespace.expected"
1784 "Namespace object expected to left of :: (found %s instead)")
1785
1786 (js2-msg "msg.null.to.object"
1787 "Cannot convert null to an object.")
1788
1789 (js2-msg "msg.undef.to.object"
1790 "Cannot convert undefined to an object.")
1791
1792 (js2-msg "msg.cyclic.value"
1793 "Cyclic %s value not allowed.")
1794
1795 (js2-msg "msg.is.not.defined"
1796 "'%s' is not defined.")
1797
1798 (js2-msg "msg.undef.prop.read"
1799 "Cannot read property '%s' from %s")
1800
1801 (js2-msg "msg.undef.prop.write"
1802 "Cannot set property '%s' of %s to '%s'")
1803
1804 (js2-msg "msg.undef.prop.delete"
1805 "Cannot delete property '%s' of %s")
1806
1807 (js2-msg "msg.undef.method.call"
1808 "Cannot call method '%s' of %s")
1809
1810 (js2-msg "msg.undef.with"
1811 "Cannot apply 'with' to %s")
1812
1813 (js2-msg "msg.isnt.function"
1814 "%s is not a function, it is %s.")
1815
1816 (js2-msg "msg.isnt.function.in"
1817 "Cannot call property %s in object %s. "
1818 "It is not a function, it is '%s'.")
1819
1820 (js2-msg "msg.function.not.found"
1821 "Cannot find function %s.")
1822
1823 (js2-msg "msg.function.not.found.in"
1824 "Cannot find function %s in object %s.")
1825
1826 (js2-msg "msg.isnt.xml.object"
1827 "%s is not an xml object.")
1828
1829 (js2-msg "msg.no.ref.to.get"
1830 "%s is not a reference to read reference value.")
1831
1832 (js2-msg "msg.no.ref.to.set"
1833 "%s is not a reference to set reference value to %s.")
1834
1835 (js2-msg "msg.no.ref.from.function"
1836 "Function %s can not be used as the left-hand "
1837 "side of assignment or as an operand of ++ or -- operator.")
1838
1839 (js2-msg "msg.bad.default.value"
1840 "Object's getDefaultValue() method returned an object.")
1841
1842 (js2-msg "msg.instanceof.not.object"
1843 "Can't use instanceof on a non-object.")
1844
1845 (js2-msg "msg.instanceof.bad.prototype"
1846 "'prototype' property of %s is not an object.")
1847
1848 (js2-msg "msg.bad.radix"
1849 "illegal radix %s.")
1850
1851 ;; ScriptableObject
1852 (js2-msg "msg.default.value"
1853 "Cannot find default value for object.")
1854
1855 (js2-msg "msg.zero.arg.ctor"
1856 "Cannot load class '%s' which has no zero-parameter constructor.")
1857
1858 (js2-msg "msg.ctor.multiple.parms"
1859 "Can't define constructor or class %s since more than "
1860 "one constructor has multiple parameters.")
1861
1862 (js2-msg "msg.extend.scriptable"
1863 "%s must extend ScriptableObject in order to define property %s.")
1864
1865 (js2-msg "msg.bad.getter.parms"
1866 "In order to define a property, getter %s must have zero "
1867 "parameters or a single ScriptableObject parameter.")
1868
1869 (js2-msg "msg.obj.getter.parms"
1870 "Expected static or delegated getter %s to take "
1871 "a ScriptableObject parameter.")
1872
1873 (js2-msg "msg.getter.static"
1874 "Getter and setter must both be static or neither be static.")
1875
1876 (js2-msg "msg.setter.return"
1877 "Setter must have void return type: %s")
1878
1879 (js2-msg "msg.setter2.parms"
1880 "Two-parameter setter must take a ScriptableObject as "
1881 "its first parameter.")
1882
1883 (js2-msg "msg.setter1.parms"
1884 "Expected single parameter setter for %s")
1885
1886 (js2-msg "msg.setter2.expected"
1887 "Expected static or delegated setter %s to take two parameters.")
1888
1889 (js2-msg "msg.setter.parms"
1890 "Expected either one or two parameters for setter.")
1891
1892 (js2-msg "msg.setter.bad.type"
1893 "Unsupported parameter type '%s' in setter '%s'.")
1894
1895 (js2-msg "msg.add.sealed"
1896 "Cannot add a property to a sealed object: %s.")
1897
1898 (js2-msg "msg.remove.sealed"
1899 "Cannot remove a property from a sealed object: %s.")
1900
1901 (js2-msg "msg.modify.sealed"
1902 "Cannot modify a property of a sealed object: %s.")
1903
1904 (js2-msg "msg.modify.readonly"
1905 "Cannot modify readonly property: %s.")
1906
1907 ;; TokenStream
1908 (js2-msg "msg.missing.exponent"
1909 "missing exponent")
1910
1911 (js2-msg "msg.caught.nfe"
1912 "number format error")
1913
1914 (js2-msg "msg.unterminated.string.lit"
1915 "unterminated string literal")
1916
1917 (js2-msg "msg.unterminated.comment"
1918 "unterminated comment")
1919
1920 (js2-msg "msg.unterminated.re.lit"
1921 "unterminated regular expression literal")
1922
1923 (js2-msg "msg.invalid.re.flag"
1924 "invalid flag after regular expression")
1925
1926 (js2-msg "msg.no.re.input.for"
1927 "no input for %s")
1928
1929 (js2-msg "msg.illegal.character"
1930 "illegal character")
1931
1932 (js2-msg "msg.invalid.escape"
1933 "invalid Unicode escape sequence")
1934
1935 (js2-msg "msg.bad.namespace"
1936 "not a valid default namespace statement. "
1937 "Syntax is: default xml namespace = EXPRESSION;")
1938
1939 ;; TokensStream warnings
1940 (js2-msg "msg.bad.octal.literal"
1941 "illegal octal literal digit %s; "
1942 "interpreting it as a decimal digit")
1943
1944 (js2-msg "msg.reserved.keyword"
1945 "illegal usage of future reserved keyword %s; "
1946 "interpreting it as ordinary identifier")
1947
1948 (js2-msg "msg.script.is.not.constructor"
1949 "Script objects are not constructors.")
1950
1951 ;; Arrays
1952 (js2-msg "msg.arraylength.bad"
1953 "Inappropriate array length.")
1954
1955 ;; Arrays
1956 (js2-msg "msg.arraylength.too.big"
1957 "Array length %s exceeds supported capacity limit.")
1958
1959 ;; URI
1960 (js2-msg "msg.bad.uri"
1961 "Malformed URI sequence.")
1962
1963 ;; Number
1964 (js2-msg "msg.bad.precision"
1965 "Precision %s out of range.")
1966
1967 ;; NativeGenerator
1968 (js2-msg "msg.send.newborn"
1969 "Attempt to send value to newborn generator")
1970
1971 (js2-msg "msg.already.exec.gen"
1972 "Already executing generator")
1973
1974 (js2-msg "msg.StopIteration.invalid"
1975 "StopIteration may not be changed to an arbitrary object.")
1976
1977 ;; Interpreter
1978 (js2-msg "msg.yield.closing"
1979 "Yield from closing generator")
1980
1981 ;;; Utilities
1982
1983 (defun js2-delete-if (predicate list)
1984 "Remove all items satisfying PREDICATE in LIST."
1985 (loop for item in list
1986 if (not (funcall predicate item))
1987 collect item))
1988
1989 (defun js2-position (element list)
1990 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1991 Returns nil if element is not found in the list."
1992 (let ((count 0)
1993 found)
1994 (while (and list (not found))
1995 (if (eq element (car list))
1996 (setq found t)
1997 (setq count (1+ count)
1998 list (cdr list))))
1999 (if found count)))
2000
2001 (defun js2-find-if (predicate list)
2002 "Find first item satisfying PREDICATE in LIST."
2003 (let (result)
2004 (while (and list (not result))
2005 (if (funcall predicate (car list))
2006 (setq result (car list)))
2007 (setq list (cdr list)))
2008 result))
2009
2010 (defmacro js2-time (form)
2011 "Evaluate FORM, discard result, and return elapsed time in sec"
2012 (declare (debug t))
2013 (let ((beg (make-symbol "--js2-time-beg--"))
2014 (delta (make-symbol "--js2-time-end--")))
2015 `(let ((,beg (current-time))
2016 ,delta)
2017 ,form
2018 (/ (truncate (* (- (float-time (current-time))
2019 (float-time ,beg))
2020 10000))
2021 10000.0))))
2022
2023 (defsubst js2-same-line (pos)
2024 "Return t if POS is on the same line as current point."
2025 (and (>= pos (point-at-bol))
2026 (<= pos (point-at-eol))))
2027
2028 (defsubst js2-same-line-2 (p1 p2)
2029 "Return t if p1 is on the same line as p2."
2030 (save-excursion
2031 (goto-char p1)
2032 (js2-same-line p2)))
2033
2034 (defun js2-code-bug ()
2035 "Signal an error when we encounter an unexpected code path."
2036 (error "failed assertion"))
2037
2038 (defsubst js2-record-text-property (beg end prop value)
2039 "Record a text property to set when parsing finishes."
2040 (push (list beg end prop value) js2-mode-deferred-properties))
2041
2042 ;; I'd like to associate errors with nodes, but for now the
2043 ;; easiest thing to do is get the context info from the last token.
2044 (defsubst js2-record-parse-error (msg &optional arg pos len)
2045 (push (list (list msg arg)
2046 (or pos js2-token-beg)
2047 (or len (- js2-token-end js2-token-beg)))
2048 js2-parsed-errors))
2049
2050 (defsubst js2-report-error (msg &optional msg-arg pos len)
2051 "Signal a syntax error or record a parse error."
2052 (if js2-recover-from-parse-errors
2053 (js2-record-parse-error msg msg-arg pos len)
2054 (signal 'js2-syntax-error
2055 (list msg
2056 js2-ts-lineno
2057 (save-excursion
2058 (goto-char js2-ts-cursor)
2059 (current-column))
2060 js2-ts-hit-eof))))
2061
2062 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2063 (if js2-compiler-report-warning-as-error
2064 (js2-report-error msg msg-arg pos len)
2065 (push (list (list msg msg-arg)
2066 (or pos js2-token-beg)
2067 (or len (- js2-token-end js2-token-beg)))
2068 js2-parsed-warnings)))
2069
2070 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2071 (if js2-compiler-strict-mode
2072 (js2-report-warning msg-id msg-arg beg
2073 (and beg end (- end beg)))))
2074
2075 (put 'js2-syntax-error 'error-conditions
2076 '(error syntax-error js2-syntax-error))
2077 (put 'js2-syntax-error 'error-message "Syntax error")
2078
2079 (put 'js2-parse-error 'error-conditions
2080 '(error parse-error js2-parse-error))
2081 (put 'js2-parse-error 'error-message "Parse error")
2082
2083 (defmacro js2-clear-flag (flags flag)
2084 `(setq ,flags (logand ,flags (lognot ,flag))))
2085
2086 (defmacro js2-set-flag (flags flag)
2087 "Logical-or FLAG into FLAGS."
2088 `(setq ,flags (logior ,flags ,flag)))
2089
2090 (defsubst js2-flag-set-p (flags flag)
2091 (/= 0 (logand flags flag)))
2092
2093 (defsubst js2-flag-not-set-p (flags flag)
2094 (zerop (logand flags flag)))
2095
2096 ;; Stolen shamelessly from James Clark's nxml-mode.
2097 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2098 "Evaluate BODY without any text property changes modifying the buffer.
2099 Any text properties changes happen as usual but the changes are not treated as
2100 modifications to the buffer."
2101 (declare (indent 0) (debug t))
2102 (let ((modified (make-symbol "modified")))
2103 `(let ((,modified (buffer-modified-p))
2104 (inhibit-read-only t)
2105 (inhibit-modification-hooks t)
2106 (buffer-undo-list t)
2107 (deactivate-mark nil)
2108 ;; Apparently these avoid file locking problems.
2109 (buffer-file-name nil)
2110 (buffer-file-truename nil))
2111 (unwind-protect
2112 (progn ,@body)
2113 (unless ,modified
2114 (restore-buffer-modified-p nil))))))
2115
2116 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2117 "Evaluate BODY with the _ character set to be word-syntax."
2118 (declare (indent 0) (debug t))
2119 (let ((old-syntax (make-symbol "old-syntax")))
2120 `(let ((,old-syntax (string (char-syntax ?_))))
2121 (unwind-protect
2122 (progn
2123 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2124 ,@body)
2125 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2126
2127 (defsubst js2-char-uppercase-p (c)
2128 "Return t if C is an uppercase character.
2129 Handles unicode and latin chars properly."
2130 (/= c (downcase c)))
2131
2132 (defsubst js2-char-lowercase-p (c)
2133 "Return t if C is an uppercase character.
2134 Handles unicode and latin chars properly."
2135 (/= c (upcase c)))
2136
2137 ;;; AST struct and function definitions
2138
2139 ;; flags for ast node property 'member-type (used for e4x operators)
2140 (defvar js2-property-flag #x1 "property access: element is valid name")
2141 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2142 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2143
2144 (defsubst js2-relpos (pos anchor)
2145 "Convert POS to be relative to ANCHOR.
2146 If POS is nil, returns nil."
2147 (and pos (- pos anchor)))
2148
2149 (defsubst js2-make-pad (indent)
2150 (if (zerop indent)
2151 ""
2152 (make-string (* indent js2-basic-offset) ? )))
2153
2154 (defsubst js2-visit-ast (node callback)
2155 "Visit every node in ast NODE with visitor CALLBACK.
2156
2157 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2158 called twice: once to visit the node, and again after all the node's
2159 children have been processed. The END-P argument is nil on the first
2160 call and non-nil on the second call. The return value of the callback
2161 affects the traversal: if non-nil, the children of NODE are processed.
2162 If the callback returns nil, or if the node has no children, then the
2163 callback is called immediately with a non-nil END-P argument.
2164
2165 The node traversal is approximately lexical-order, although there
2166 are currently no guarantees around this."
2167 (if node
2168 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2169 ;; visit the node
2170 (when (funcall callback node nil)
2171 ;; visit the kids
2172 (cond
2173 ((eq vfunc 'js2-visit-none)
2174 nil) ; don't even bother calling it
2175 ;; Each AST node type has to define a `js2-visitor' function
2176 ;; that takes a node and a callback, and calls `js2-visit-ast'
2177 ;; on each child of the node.
2178 (vfunc
2179 (funcall vfunc node callback))
2180 (t
2181 (error "%s does not define a visitor-traversal function"
2182 (aref node 0)))))
2183 ;; call the end-visit
2184 (funcall callback node t))))
2185
2186 (defstruct (js2-node
2187 (:constructor nil)) ; abstract
2188 "Base AST node type."
2189 (type -1) ; token type
2190 (pos -1) ; start position of this AST node in parsed input
2191 (len 1) ; num characters spanned by the node
2192 props ; optional node property list (an alist)
2193 parent) ; link to parent node; null for root
2194
2195 (defsubst js2-node-get-prop (node prop &optional default)
2196 (or (cadr (assoc prop (js2-node-props node))) default))
2197
2198 (defsubst js2-node-set-prop (node prop value)
2199 (setf (js2-node-props node)
2200 (cons (list prop value) (js2-node-props node))))
2201
2202 (defsubst js2-fixup-starts (n nodes)
2203 "Adjust the start positions of NODES to be relative to N.
2204 Any node in the list may be nil, for convenience."
2205 (dolist (node nodes)
2206 (when node
2207 (setf (js2-node-pos node) (- (js2-node-pos node)
2208 (js2-node-pos n))))))
2209
2210 (defsubst js2-node-add-children (parent &rest nodes)
2211 "Set parent node of NODES to PARENT, and return PARENT.
2212 Does nothing if we're not recording parent links.
2213 If any given node in NODES is nil, doesn't record that link."
2214 (js2-fixup-starts parent nodes)
2215 (dolist (node nodes)
2216 (and node
2217 (setf (js2-node-parent node) parent))))
2218
2219 ;; Non-recursive since it's called a frightening number of times.
2220 (defsubst js2-node-abs-pos (n)
2221 (let ((pos (js2-node-pos n)))
2222 (while (setq n (js2-node-parent n))
2223 (setq pos (+ pos (js2-node-pos n))))
2224 pos))
2225
2226 (defsubst js2-node-abs-end (n)
2227 "Return absolute buffer position of end of N."
2228 (+ (js2-node-abs-pos n) (js2-node-len n)))
2229
2230 ;; It's important to make sure block nodes have a lisp list for the
2231 ;; child nodes, to limit printing recursion depth in an AST that
2232 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2233 ;; a sufficiently large vector tree.
2234
2235 (defstruct (js2-block-node
2236 (:include js2-node)
2237 (:constructor nil)
2238 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2239 (pos js2-token-beg)
2240 len
2241 props
2242 kids)))
2243 "A block of statements."
2244 kids) ; a lisp list of the child statement nodes
2245
2246 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2247 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2248
2249 (defsubst js2-visit-block (ast callback)
2250 "Visit the `js2-block-node' children of AST."
2251 (dolist (kid (js2-block-node-kids ast))
2252 (js2-visit-ast kid callback)))
2253
2254 (defun js2-print-block (n i)
2255 (let ((pad (js2-make-pad i)))
2256 (insert pad "{\n")
2257 (dolist (kid (js2-block-node-kids n))
2258 (js2-print-ast kid (1+ i)))
2259 (insert pad "}")))
2260
2261 (defstruct (js2-scope
2262 (:include js2-block-node)
2263 (:constructor nil)
2264 (:constructor make-js2-scope (&key (type js2-BLOCK)
2265 (pos js2-token-beg)
2266 len
2267 kids)))
2268 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2269 ;; I don't have one of those handy, so I'll use an alist for now.
2270 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2271 ;; and is much lighter-weight to construct (both CPU and mem).
2272 ;; The keys are interned strings (symbols) for faster lookup.
2273 ;; Should switch to hybrid alist/hashtable eventually.
2274 symbol-table ; an alist of (symbol . js2-symbol)
2275 parent-scope ; a `js2-scope'
2276 top) ; top-level `js2-scope' (script/function)
2277
2278 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2279 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2280
2281 (defun js2-scope-set-parent-scope (scope parent)
2282 (setf (js2-scope-parent-scope scope) parent
2283 (js2-scope-top scope) (if (null parent)
2284 scope
2285 (js2-scope-top parent))))
2286
2287 (defun js2-node-get-enclosing-scope (node)
2288 "Return the innermost `js2-scope' node surrounding NODE.
2289 Returns nil if there is no enclosing scope node."
2290 (let ((parent (js2-node-parent node)))
2291 (while (not (js2-scope-p parent))
2292 (setq parent (js2-node-parent parent)))
2293 parent))
2294
2295 (defun js2-get-defining-scope (scope name)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found."
2298 (let ((sym (if (symbolp name)
2299 name
2300 (intern name)))
2301 table
2302 result
2303 (continue t))
2304 (while (and scope continue)
2305 (if (and (setq table (js2-scope-symbol-table scope))
2306 (assq sym table))
2307 (setq continue nil
2308 result scope)
2309 (setq scope (js2-scope-parent-scope scope))))
2310 result))
2311
2312 (defsubst js2-scope-get-symbol (scope name)
2313 "Return symbol table entry for NAME in SCOPE.
2314 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2315 (and (js2-scope-symbol-table scope)
2316 (cdr (assq (if (symbolp name)
2317 name
2318 (intern name))
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defsubst js2-scope-put-symbol (scope name symbol)
2322 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2323 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2324 (let* ((table (js2-scope-symbol-table scope))
2325 (sym (if (symbolp name) name (intern name)))
2326 (entry (assq sym table)))
2327 (if entry
2328 (setcdr entry symbol)
2329 (push (cons sym symbol)
2330 (js2-scope-symbol-table scope)))))
2331
2332 (defstruct (js2-symbol
2333 (:constructor nil)
2334 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2335 "A symbol table entry."
2336 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2337 ;; js2-LET, or js2-CONST
2338 decl-type
2339 name ; string
2340 ast-node) ; a `js2-node'
2341
2342 (defstruct (js2-error-node
2343 (:include js2-node)
2344 (:constructor nil) ; silence emacs21 byte-compiler
2345 (:constructor make-js2-error-node (&key (type js2-ERROR)
2346 (pos js2-token-beg)
2347 len)))
2348 "AST node representing a parse error.")
2349
2350 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2351 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2352
2353 (defstruct (js2-script-node
2354 (:include js2-scope)
2355 (:constructor nil)
2356 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2357 (pos js2-token-beg)
2358 len
2359 var-decls
2360 fun-decls)))
2361 functions ; lisp list of nested functions
2362 regexps ; lisp list of (string . flags)
2363 symbols ; alist (every symbol gets unique index)
2364 (param-count 0)
2365 var-names ; vector of string names
2366 consts ; bool-vector matching var-decls
2367 (temp-number 0)) ; for generating temp variables
2368
2369 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2370 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2371
2372 (defun js2-print-script (node indent)
2373 (dolist (kid (js2-block-node-kids node))
2374 (js2-print-ast kid indent)))
2375
2376 (defstruct (js2-ast-root
2377 (:include js2-script-node)
2378 (:constructor nil)
2379 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2380 (pos js2-token-beg)
2381 len
2382 buffer)))
2383 "The root node of a js2 AST."
2384 buffer ; the source buffer from which the code was parsed
2385 comments ; a lisp list of comments, ordered by start position
2386 errors ; a lisp list of errors found during parsing
2387 warnings ; a lisp list of warnings found during parsing
2388 node-count) ; number of nodes in the tree, including the root
2389
2390 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2391 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2392
2393 (defun js2-visit-ast-root (ast callback)
2394 (dolist (kid (js2-ast-root-kids ast))
2395 (js2-visit-ast kid callback))
2396 (dolist (comment (js2-ast-root-comments ast))
2397 (js2-visit-ast comment callback)))
2398
2399 (defstruct (js2-comment-node
2400 (:include js2-node)
2401 (:constructor nil)
2402 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2403 (pos js2-token-beg)
2404 len
2405 (format js2-ts-comment-type))))
2406 format) ; 'line, 'block, 'jsdoc or 'html
2407
2408 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2409 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2410
2411 (defun js2-print-comment (n i)
2412 ;; We really ought to link end-of-line comments to their nodes.
2413 ;; Or maybe we could add a new comment type, 'endline.
2414 (insert (js2-make-pad i)
2415 (js2-node-string n)))
2416
2417 (defstruct (js2-expr-stmt-node
2418 (:include js2-node)
2419 (:constructor nil)
2420 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2421 (pos js2-ts-cursor)
2422 len
2423 expr)))
2424 "An expression statement."
2425 expr)
2426
2427 (defsubst js2-expr-stmt-node-set-has-result (node)
2428 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2429 (setf (js2-node-type node) js2-EXPR_RESULT))
2430
2431 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2433
2434 (defun js2-visit-expr-stmt-node (n v)
2435 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2436
2437 (defun js2-print-expr-stmt-node (n indent)
2438 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2439 (insert ";\n"))
2440
2441 (defstruct (js2-loop-node
2442 (:include js2-scope)
2443 (:constructor nil))
2444 "Abstract supertype of loop nodes."
2445 body ; a `js2-block-node'
2446 lp ; position of left-paren, nil if omitted
2447 rp) ; position of right-paren, nil if omitted
2448
2449 (defstruct (js2-do-node
2450 (:include js2-loop-node)
2451 (:constructor nil)
2452 (:constructor make-js2-do-node (&key (type js2-DO)
2453 (pos js2-token-beg)
2454 len
2455 body
2456 condition
2457 while-pos
2458 lp
2459 rp)))
2460 "AST node for do-loop."
2461 condition ; while (expression)
2462 while-pos) ; buffer position of 'while' keyword
2463
2464 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2465 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2466
2467 (defun js2-visit-do-node (n v)
2468 (js2-visit-ast (js2-do-node-body n) v)
2469 (js2-visit-ast (js2-do-node-condition n) v))
2470
2471 (defun js2-print-do-node (n i)
2472 (let ((pad (js2-make-pad i)))
2473 (insert pad "do {\n")
2474 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2475 (js2-print-ast kid (1+ i)))
2476 (insert pad "} while (")
2477 (js2-print-ast (js2-do-node-condition n) 0)
2478 (insert ");\n")))
2479
2480 (defstruct (js2-while-node
2481 (:include js2-loop-node)
2482 (:constructor nil)
2483 (:constructor make-js2-while-node (&key (type js2-WHILE)
2484 (pos js2-token-beg)
2485 len
2486 body
2487 condition
2488 lp
2489 rp)))
2490 "AST node for while-loop."
2491 condition) ; while-condition
2492
2493 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2494 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2495
2496 (defun js2-visit-while-node (n v)
2497 (js2-visit-ast (js2-while-node-condition n) v)
2498 (js2-visit-ast (js2-while-node-body n) v))
2499
2500 (defun js2-print-while-node (n i)
2501 (let ((pad (js2-make-pad i)))
2502 (insert pad "while (")
2503 (js2-print-ast (js2-while-node-condition n) 0)
2504 (insert ") {\n")
2505 (js2-print-body (js2-while-node-body n) (1+ i))
2506 (insert pad "}\n")))
2507
2508 (defstruct (js2-for-node
2509 (:include js2-loop-node)
2510 (:constructor nil)
2511 (:constructor make-js2-for-node (&key (type js2-FOR)
2512 (pos js2-ts-cursor)
2513 len
2514 body
2515 init
2516 condition
2517 update
2518 lp
2519 rp)))
2520 "AST node for a C-style for-loop."
2521 init ; initialization expression
2522 condition ; loop condition
2523 update) ; update clause
2524
2525 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2526 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2527
2528 (defun js2-visit-for-node (n v)
2529 (js2-visit-ast (js2-for-node-init n) v)
2530 (js2-visit-ast (js2-for-node-condition n) v)
2531 (js2-visit-ast (js2-for-node-update n) v)
2532 (js2-visit-ast (js2-for-node-body n) v))
2533
2534 (defun js2-print-for-node (n i)
2535 (let ((pad (js2-make-pad i)))
2536 (insert pad "for (")
2537 (js2-print-ast (js2-for-node-init n) 0)
2538 (insert "; ")
2539 (js2-print-ast (js2-for-node-condition n) 0)
2540 (insert "; ")
2541 (js2-print-ast (js2-for-node-update n) 0)
2542 (insert ") {\n")
2543 (js2-print-body (js2-for-node-body n) (1+ i))
2544 (insert pad "}\n")))
2545
2546 (defstruct (js2-for-in-node
2547 (:include js2-loop-node)
2548 (:constructor nil)
2549 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2550 (pos js2-ts-cursor)
2551 len
2552 body
2553 iterator
2554 object
2555 in-pos
2556 each-pos
2557 foreach-p
2558 lp
2559 rp)))
2560 "AST node for a for..in loop."
2561 iterator ; [var] foo in ...
2562 object ; object over which we're iterating
2563 in-pos ; buffer position of 'in' keyword
2564 each-pos ; buffer position of 'each' keyword, if foreach-p
2565 foreach-p) ; t if it's a for-each loop
2566
2567 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2568 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2569
2570 (defun js2-visit-for-in-node (n v)
2571 (js2-visit-ast (js2-for-in-node-iterator n) v)
2572 (js2-visit-ast (js2-for-in-node-object n) v)
2573 (js2-visit-ast (js2-for-in-node-body n) v))
2574
2575 (defun js2-print-for-in-node (n i)
2576 (let ((pad (js2-make-pad i))
2577 (foreach (js2-for-in-node-foreach-p n)))
2578 (insert pad "for ")
2579 (if foreach
2580 (insert "each "))
2581 (insert "(")
2582 (js2-print-ast (js2-for-in-node-iterator n) 0)
2583 (insert " in ")
2584 (js2-print-ast (js2-for-in-node-object n) 0)
2585 (insert ") {\n")
2586 (js2-print-body (js2-for-in-node-body n) (1+ i))
2587 (insert pad "}\n")))
2588
2589 (defstruct (js2-return-node
2590 (:include js2-node)
2591 (:constructor nil)
2592 (:constructor make-js2-return-node (&key (type js2-RETURN)
2593 (pos js2-ts-cursor)
2594 len
2595 retval)))
2596 "AST node for a return statement."
2597 retval) ; expression to return, or 'undefined
2598
2599 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2600 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2601
2602 (defun js2-visit-return-node (n v)
2603 (js2-visit-ast (js2-return-node-retval n) v))
2604
2605 (defun js2-print-return-node (n i)
2606 (insert (js2-make-pad i) "return")
2607 (when (js2-return-node-retval n)
2608 (insert " ")
2609 (js2-print-ast (js2-return-node-retval n) 0))
2610 (insert ";\n"))
2611
2612 (defstruct (js2-if-node
2613 (:include js2-node)
2614 (:constructor nil)
2615 (:constructor make-js2-if-node (&key (type js2-IF)
2616 (pos js2-ts-cursor)
2617 len
2618 condition
2619 then-part
2620 else-pos
2621 else-part
2622 lp
2623 rp)))
2624 "AST node for an if-statement."
2625 condition ; expression
2626 then-part ; statement or block
2627 else-pos ; optional buffer position of 'else' keyword
2628 else-part ; optional statement or block
2629 lp ; position of left-paren, nil if omitted
2630 rp) ; position of right-paren, nil if omitted
2631
2632 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2633 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2634
2635 (defun js2-visit-if-node (n v)
2636 (js2-visit-ast (js2-if-node-condition n) v)
2637 (js2-visit-ast (js2-if-node-then-part n) v)
2638 (js2-visit-ast (js2-if-node-else-part n) v))
2639
2640 (defun js2-print-if-node (n i)
2641 (let ((pad (js2-make-pad i))
2642 (then-part (js2-if-node-then-part n))
2643 (else-part (js2-if-node-else-part n)))
2644 (insert pad "if (")
2645 (js2-print-ast (js2-if-node-condition n) 0)
2646 (insert ") {\n")
2647 (js2-print-body then-part (1+ i))
2648 (insert pad "}")
2649 (cond
2650 ((not else-part)
2651 (insert "\n"))
2652 ((js2-if-node-p else-part)
2653 (insert " else ")
2654 (js2-print-body else-part i))
2655 (t
2656 (insert " else {\n")
2657 (js2-print-body else-part (1+ i))
2658 (insert pad "}\n")))))
2659
2660 (defstruct (js2-try-node
2661 (:include js2-node)
2662 (:constructor nil)
2663 (:constructor make-js2-try-node (&key (type js2-TRY)
2664 (pos js2-ts-cursor)
2665 len
2666 try-block
2667 catch-clauses
2668 finally-block)))
2669 "AST node for a try-statement."
2670 try-block
2671 catch-clauses ; a lisp list of `js2-catch-node'
2672 finally-block) ; a `js2-finally-node'
2673
2674 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2675 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2676
2677 (defun js2-visit-try-node (n v)
2678 (js2-visit-ast (js2-try-node-try-block n) v)
2679 (dolist (clause (js2-try-node-catch-clauses n))
2680 (js2-visit-ast clause v))
2681 (js2-visit-ast (js2-try-node-finally-block n) v))
2682
2683 (defun js2-print-try-node (n i)
2684 (let ((pad (js2-make-pad i))
2685 (catches (js2-try-node-catch-clauses n))
2686 (finally (js2-try-node-finally-block n)))
2687 (insert pad "try {\n")
2688 (js2-print-body (js2-try-node-try-block n) (1+ i))
2689 (insert pad "}")
2690 (when catches
2691 (dolist (catch catches)
2692 (js2-print-ast catch i)))
2693 (if finally
2694 (js2-print-ast finally i)
2695 (insert "\n"))))
2696
2697 (defstruct (js2-catch-node
2698 (:include js2-node)
2699 (:constructor nil)
2700 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2701 (pos js2-ts-cursor)
2702 len
2703 param
2704 guard-kwd
2705 guard-expr
2706 block
2707 lp
2708 rp)))
2709 "AST node for a catch clause."
2710 param ; destructuring form or simple name node
2711 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2712 guard-expr ; catch condition, a `js2-node'
2713 block ; statements, a `js2-block-node'
2714 lp ; buffer position of left-paren, nil if omitted
2715 rp) ; buffer position of right-paren, nil if omitted
2716
2717 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2718 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2719
2720 (defun js2-visit-catch-node (n v)
2721 (js2-visit-ast (js2-catch-node-param n) v)
2722 (when (js2-catch-node-guard-kwd n)
2723 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2724 (js2-visit-ast (js2-catch-node-block n) v))
2725
2726 (defun js2-print-catch-node (n i)
2727 (let ((pad (js2-make-pad i))
2728 (guard-kwd (js2-catch-node-guard-kwd n))
2729 (guard-expr (js2-catch-node-guard-expr n)))
2730 (insert " catch (")
2731 (js2-print-ast (js2-catch-node-param n) 0)
2732 (when guard-kwd
2733 (insert " if ")
2734 (js2-print-ast guard-expr 0))
2735 (insert ") {\n")
2736 (js2-print-body (js2-catch-node-block n) (1+ i))
2737 (insert pad "}")))
2738
2739 (defstruct (js2-finally-node
2740 (:include js2-node)
2741 (:constructor nil)
2742 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2743 (pos js2-ts-cursor)
2744 len
2745 body)))
2746 "AST node for a finally clause."
2747 body) ; a `js2-node', often but not always a block node
2748
2749 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2750 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2751
2752 (defun js2-visit-finally-node (n v)
2753 (js2-visit-ast (js2-finally-node-body n) v))
2754
2755 (defun js2-print-finally-node (n i)
2756 (let ((pad (js2-make-pad i)))
2757 (insert " finally {\n")
2758 (js2-print-body (js2-finally-node-body n) (1+ i))
2759 (insert pad "}\n")))
2760
2761 (defstruct (js2-switch-node
2762 (:include js2-node)
2763 (:constructor nil)
2764 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2765 (pos js2-ts-cursor)
2766 len
2767 discriminant
2768 cases
2769 lp
2770 rp)))
2771 "AST node for a switch statement."
2772 discriminant ; a `js2-node' (switch expression)
2773 cases ; a lisp list of `js2-case-node'
2774 lp ; position of open-paren for discriminant, nil if omitted
2775 rp) ; position of close-paren for discriminant, nil if omitted
2776
2777 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2778 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2779
2780 (defun js2-visit-switch-node (n v)
2781 (js2-visit-ast (js2-switch-node-discriminant n) v)
2782 (dolist (c (js2-switch-node-cases n))
2783 (js2-visit-ast c v)))
2784
2785 (defun js2-print-switch-node (n i)
2786 (let ((pad (js2-make-pad i))
2787 (cases (js2-switch-node-cases n)))
2788 (insert pad "switch (")
2789 (js2-print-ast (js2-switch-node-discriminant n) 0)
2790 (insert ") {\n")
2791 (dolist (case cases)
2792 (js2-print-ast case i))
2793 (insert pad "}\n")))
2794
2795 (defstruct (js2-case-node
2796 (:include js2-block-node)
2797 (:constructor nil)
2798 (:constructor make-js2-case-node (&key (type js2-CASE)
2799 (pos js2-ts-cursor)
2800 len
2801 kids
2802 expr)))
2803 "AST node for a case clause of a switch statement."
2804 expr) ; the case expression (nil for default)
2805
2806 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2807 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2808
2809 (defun js2-visit-case-node (n v)
2810 (js2-visit-ast (js2-case-node-expr n) v)
2811 (js2-visit-block n v))
2812
2813 (defun js2-print-case-node (n i)
2814 (let ((pad (js2-make-pad i))
2815 (expr (js2-case-node-expr n)))
2816 (insert pad)
2817 (if (null expr)
2818 (insert "default:\n")
2819 (insert "case ")
2820 (js2-print-ast expr 0)
2821 (insert ":\n"))
2822 (dolist (kid (js2-case-node-kids n))
2823 (js2-print-ast kid (1+ i)))))
2824
2825 (defstruct (js2-throw-node
2826 (:include js2-node)
2827 (:constructor nil)
2828 (:constructor make-js2-throw-node (&key (type js2-THROW)
2829 (pos js2-ts-cursor)
2830 len
2831 expr)))
2832 "AST node for a throw statement."
2833 expr) ; the expression to throw
2834
2835 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2836 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2837
2838 (defun js2-visit-throw-node (n v)
2839 (js2-visit-ast (js2-throw-node-expr n) v))
2840
2841 (defun js2-print-throw-node (n i)
2842 (insert (js2-make-pad i) "throw ")
2843 (js2-print-ast (js2-throw-node-expr n) 0)
2844 (insert ";\n"))
2845
2846 (defstruct (js2-with-node
2847 (:include js2-node)
2848 (:constructor nil)
2849 (:constructor make-js2-with-node (&key (type js2-WITH)
2850 (pos js2-ts-cursor)
2851 len
2852 object
2853 body
2854 lp
2855 rp)))
2856 "AST node for a with-statement."
2857 object
2858 body
2859 lp ; buffer position of left-paren around object, nil if omitted
2860 rp) ; buffer position of right-paren around object, nil if omitted
2861
2862 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2863 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2864
2865 (defun js2-visit-with-node (n v)
2866 (js2-visit-ast (js2-with-node-object n) v)
2867 (js2-visit-ast (js2-with-node-body n) v))
2868
2869 (defun js2-print-with-node (n i)
2870 (let ((pad (js2-make-pad i)))
2871 (insert pad "with (")
2872 (js2-print-ast (js2-with-node-object n) 0)
2873 (insert ") {\n")
2874 (js2-print-body (js2-with-node-body n) (1+ i))
2875 (insert pad "}\n")))
2876
2877 (defstruct (js2-label-node
2878 (:include js2-node)
2879 (:constructor nil)
2880 (:constructor make-js2-label-node (&key (type js2-LABEL)
2881 (pos js2-ts-cursor)
2882 len
2883 name)))
2884 "AST node for a statement label or case label."
2885 name ; a string
2886 loop) ; for validating and code-generating continue-to-label
2887
2888 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2889 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2890
2891 (defun js2-print-label (n i)
2892 (insert (js2-make-pad i)
2893 (js2-label-node-name n)
2894 ":\n"))
2895
2896 (defstruct (js2-labeled-stmt-node
2897 (:include js2-node)
2898 (:constructor nil)
2899 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2900 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2901 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2902 (pos js2-ts-cursor)
2903 len
2904 labels
2905 stmt)))
2906 "AST node for a statement with one or more labels.
2907 Multiple labels for a statement are collapsed into the labels field."
2908 labels ; lisp list of `js2-label-node'
2909 stmt) ; the statement these labels are for
2910
2911 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2912 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2913
2914 (defun js2-get-label-by-name (lbl-stmt name)
2915 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2916 Returns nil if no such label is in the list."
2917 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2918 result)
2919 (while (and label-list (not result))
2920 (if (string= (js2-label-node-name (car label-list)) name)
2921 (setq result (car label-list))
2922 (setq label-list (cdr label-list))))
2923 result))
2924
2925 (defun js2-visit-labeled-stmt (n v)
2926 (dolist (label (js2-labeled-stmt-node-labels n))
2927 (js2-visit-ast label v))
2928 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2929
2930 (defun js2-print-labeled-stmt (n i)
2931 (dolist (label (js2-labeled-stmt-node-labels n))
2932 (js2-print-ast label i))
2933 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2934
2935 (defun js2-labeled-stmt-node-contains (node label)
2936 "Return t if NODE contains LABEL in its label set.
2937 NODE is a `js2-labels-node'. LABEL is an identifier."
2938 (loop for nl in (js2-labeled-stmt-node-labels node)
2939 if (string= label (js2-label-node-name nl))
2940 return t
2941 finally return nil))
2942
2943 (defsubst js2-labeled-stmt-node-add-label (node label)
2944 "Add a `js2-label-node' to the label set for this statement."
2945 (setf (js2-labeled-stmt-node-labels node)
2946 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2947
2948 (defstruct (js2-jump-node
2949 (:include js2-node)
2950 (:constructor nil))
2951 "Abstract supertype of break and continue nodes."
2952 label ; `js2-name-node' for location of label identifier, if present
2953 target) ; target js2-labels-node or loop/switch statement
2954
2955 (defun js2-visit-jump-node (n v)
2956 (js2-visit-ast (js2-jump-node-label n) v))
2957
2958 (defstruct (js2-break-node
2959 (:include js2-jump-node)
2960 (:constructor nil)
2961 (:constructor make-js2-break-node (&key (type js2-BREAK)
2962 (pos js2-ts-cursor)
2963 len
2964 label
2965 target)))
2966 "AST node for a break statement.
2967 The label field is a `js2-name-node', possibly nil, for the named label
2968 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2969 is the target of the break - a label node or enclosing loop/switch statement.")
2970
2971 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2972 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2973
2974 (defun js2-print-break-node (n i)
2975 (insert (js2-make-pad i) "break")
2976 (when (js2-break-node-label n)
2977 (insert " ")
2978 (js2-print-ast (js2-break-node-label n) 0))
2979 (insert ";\n"))
2980
2981 (defstruct (js2-continue-node
2982 (:include js2-jump-node)
2983 (:constructor nil)
2984 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2985 (pos js2-ts-cursor)
2986 len
2987 label
2988 target)))
2989 "AST node for a continue statement.
2990 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2991 It is nil if continue specifies no label. The target field is the jump target:
2992 a `js2-label-node' or the innermost enclosing loop.")
2993
2994 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2995 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2996
2997 (defun js2-print-continue-node (n i)
2998 (insert (js2-make-pad i) "continue")
2999 (when (js2-continue-node-label n)
3000 (insert " ")
3001 (js2-print-ast (js2-continue-node-label n) 0))
3002 (insert ";\n"))
3003
3004 (defstruct (js2-function-node
3005 (:include js2-script-node)
3006 (:constructor nil)
3007 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3008 (pos js2-ts-cursor)
3009 len
3010 (ftype 'FUNCTION)
3011 (form 'FUNCTION_STATEMENT)
3012 (name "")
3013 params
3014 body
3015 lp
3016 rp)))
3017 "AST node for a function declaration.
3018 The `params' field is a lisp list of nodes. Each node is either a simple
3019 `js2-name-node', or if it's a destructuring-assignment parameter, a
3020 `js2-array-node' or `js2-object-node'."
3021 ftype ; FUNCTION, GETTER or SETTER
3022 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3023 name ; function name (a `js2-name-node', or nil if anonymous)
3024 params ; a lisp list of destructuring forms or simple name nodes
3025 body ; a `js2-block-node' or expression node (1.8 only)
3026 lp ; position of arg-list open-paren, or nil if omitted
3027 rp ; position of arg-list close-paren, or nil if omitted
3028 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3029 needs-activation ; t if we need an activation object for this frame
3030 is-generator ; t if this function contains a yield
3031 member-expr) ; nonstandard Ecma extension from Rhino
3032
3033 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3034 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3035
3036 (defun js2-visit-function-node (n v)
3037 (js2-visit-ast (js2-function-node-name n) v)
3038 (dolist (p (js2-function-node-params n))
3039 (js2-visit-ast p v))
3040 (js2-visit-ast (js2-function-node-body n) v))
3041
3042 (defun js2-print-function-node (n i)
3043 (let ((pad (js2-make-pad i))
3044 (getter (js2-node-get-prop n 'GETTER_SETTER))
3045 (name (js2-function-node-name n))
3046 (params (js2-function-node-params n))
3047 (body (js2-function-node-body n))
3048 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3049 (unless getter
3050 (insert pad "function"))
3051 (when name
3052 (insert " ")
3053 (js2-print-ast name 0))
3054 (insert "(")
3055 (loop with len = (length params)
3056 for param in params
3057 for count from 1
3058 do
3059 (js2-print-ast param 0)
3060 (if (< count len)
3061 (insert ", ")))
3062 (insert ") {")
3063 (unless expr
3064 (insert "\n"))
3065 ;; TODO: fix this to be smarter about indenting, etc.
3066 (js2-print-body body (1+ i))
3067 (insert pad "}")
3068 (unless expr
3069 (insert "\n"))))
3070
3071 (defsubst js2-function-name (node)
3072 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3073 (and (js2-function-node-name node)
3074 (js2-name-node-name (js2-function-node-name node))))
3075
3076 ;; Having this be an expression node makes it more flexible.
3077 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3078 ;; that work better if you assume it's an expression. Whenever we have
3079 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3080 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3081 (defstruct (js2-var-decl-node
3082 (:include js2-node)
3083 (:constructor nil)
3084 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3085 (pos js2-token-beg)
3086 len
3087 kids
3088 decl-type)))
3089 "AST node for a variable declaration list (VAR, CONST or LET).
3090 The node bounds differ depending on the declaration type. For VAR or
3091 CONST declarations, the bounds include the var/const keyword. For LET
3092 declarations, the node begins at the position of the first child."
3093 kids ; a lisp list of `js2-var-init-node' structs.
3094 decl-type) ; js2-VAR, js2-CONST or js2-LET
3095
3096 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3097 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3098
3099 (defun js2-visit-var-decl (n v)
3100 (dolist (kid (js2-var-decl-node-kids n))
3101 (js2-visit-ast kid v)))
3102
3103 (defun js2-print-var-decl (n i)
3104 (let ((pad (js2-make-pad i))
3105 (tt (js2-var-decl-node-decl-type n)))
3106 (insert pad)
3107 (insert (cond
3108 ((= tt js2-VAR) "var ")
3109 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3110 ((= tt js2-CONST) "const ")
3111 (t
3112 (error "malformed var-decl node"))))
3113 (loop with kids = (js2-var-decl-node-kids n)
3114 with len = (length kids)
3115 for kid in kids
3116 for count from 1
3117 do
3118 (js2-print-ast kid 0)
3119 (if (< count len)
3120 (insert ", ")))))
3121
3122 (defstruct (js2-var-init-node
3123 (:include js2-node)
3124 (:constructor nil)
3125 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3126 (pos js2-ts-cursor)
3127 len
3128 target
3129 initializer)))
3130 "AST node for a variable declaration.
3131 The type field will be js2-CONST for a const decl."
3132 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3133 initializer) ; initializer expression, a `js2-node'
3134
3135 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3136 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3137
3138 (defun js2-visit-var-init-node (n v)
3139 (js2-visit-ast (js2-var-init-node-target n) v)
3140 (js2-visit-ast (js2-var-init-node-initializer n) v))
3141
3142 (defun js2-print-var-init-node (n i)
3143 (let ((pad (js2-make-pad i))
3144 (name (js2-var-init-node-target n))
3145 (init (js2-var-init-node-initializer n)))
3146 (insert pad)
3147 (js2-print-ast name 0)
3148 (when init
3149 (insert " = ")
3150 (js2-print-ast init 0))))
3151
3152 (defstruct (js2-cond-node
3153 (:include js2-node)
3154 (:constructor nil)
3155 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3156 (pos js2-ts-cursor)
3157 len
3158 test-expr
3159 true-expr
3160 false-expr
3161 q-pos
3162 c-pos)))
3163 "AST node for the ternary operator"
3164 test-expr
3165 true-expr
3166 false-expr
3167 q-pos ; buffer position of ?
3168 c-pos) ; buffer position of :
3169
3170 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3171 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3172
3173 (defun js2-visit-cond-node (n v)
3174 (js2-visit-ast (js2-cond-node-test-expr n) v)
3175 (js2-visit-ast (js2-cond-node-true-expr n) v)
3176 (js2-visit-ast (js2-cond-node-false-expr n) v))
3177
3178 (defun js2-print-cond-node (n i)
3179 (let ((pad (js2-make-pad i)))
3180 (insert pad)
3181 (js2-print-ast (js2-cond-node-test-expr n) 0)
3182 (insert " ? ")
3183 (js2-print-ast (js2-cond-node-true-expr n) 0)
3184 (insert " : ")
3185 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3186
3187 (defstruct (js2-infix-node
3188 (:include js2-node)
3189 (:constructor nil)
3190 (:constructor make-js2-infix-node (&key type
3191 (pos js2-ts-cursor)
3192 len
3193 op-pos
3194 left
3195 right)))
3196 "Represents infix expressions.
3197 Includes assignment ops like `|=', and the comma operator.
3198 The type field inherited from `js2-node' holds the operator."
3199 op-pos ; buffer position where operator begins
3200 left ; any `js2-node'
3201 right) ; any `js2-node'
3202
3203 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3204 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3205
3206 (defun js2-visit-infix-node (n v)
3207 (js2-visit-ast (js2-infix-node-left n) v)
3208 (js2-visit-ast (js2-infix-node-right n) v))
3209
3210 (defconst js2-operator-tokens
3211 (let ((table (make-hash-table :test 'eq))
3212 (tokens
3213 (list (cons js2-IN "in")
3214 (cons js2-TYPEOF "typeof")
3215 (cons js2-INSTANCEOF "instanceof")
3216 (cons js2-DELPROP "delete")
3217 (cons js2-COMMA ",")
3218 (cons js2-COLON ":")
3219 (cons js2-OR "||")
3220 (cons js2-AND "&&")
3221 (cons js2-INC "++")
3222 (cons js2-DEC "--")
3223 (cons js2-BITOR "|")
3224 (cons js2-BITXOR "^")
3225 (cons js2-BITAND "&")
3226 (cons js2-EQ "==")
3227 (cons js2-NE "!=")
3228 (cons js2-LT "<")
3229 (cons js2-LE "<=")
3230 (cons js2-GT ">")
3231 (cons js2-GE ">=")
3232 (cons js2-LSH "<<")
3233 (cons js2-RSH ">>")
3234 (cons js2-URSH ">>>")
3235 (cons js2-ADD "+") ; infix plus
3236 (cons js2-SUB "-") ; infix minus
3237 (cons js2-MUL "*")
3238 (cons js2-DIV "/")
3239 (cons js2-MOD "%")
3240 (cons js2-NOT "!")
3241 (cons js2-BITNOT "~")
3242 (cons js2-POS "+") ; unary plus
3243 (cons js2-NEG "-") ; unary minus
3244 (cons js2-SHEQ "===") ; shallow equality
3245 (cons js2-SHNE "!==") ; shallow inequality
3246 (cons js2-ASSIGN "=")
3247 (cons js2-ASSIGN_BITOR "|=")
3248 (cons js2-ASSIGN_BITXOR "^=")
3249 (cons js2-ASSIGN_BITAND "&=")
3250 (cons js2-ASSIGN_LSH "<<=")
3251 (cons js2-ASSIGN_RSH ">>=")
3252 (cons js2-ASSIGN_URSH ">>>=")
3253 (cons js2-ASSIGN_ADD "+=")
3254 (cons js2-ASSIGN_SUB "-=")
3255 (cons js2-ASSIGN_MUL "*=")
3256 (cons js2-ASSIGN_DIV "/=")
3257 (cons js2-ASSIGN_MOD "%="))))
3258 (loop for (k . v) in tokens do
3259 (puthash k v table))
3260 table))
3261
3262 (defun js2-print-infix-node (n i)
3263 (let* ((tt (js2-node-type n))
3264 (op (gethash tt js2-operator-tokens)))
3265 (unless op
3266 (error "unrecognized infix operator %s" (js2-node-type n)))
3267 (insert (js2-make-pad i))
3268 (js2-print-ast (js2-infix-node-left n) 0)
3269 (unless (= tt js2-COMMA)
3270 (insert " "))
3271 (insert op)
3272 (insert " ")
3273 (js2-print-ast (js2-infix-node-right n) 0)))
3274
3275 (defstruct (js2-assign-node
3276 (:include js2-infix-node)
3277 (:constructor nil)
3278 (:constructor make-js2-assign-node (&key type
3279 (pos js2-ts-cursor)
3280 len
3281 op-pos
3282 left
3283 right)))
3284 "Represents any assignment.
3285 The type field holds the actual assignment operator.")
3286
3287 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3288 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3289
3290 (defstruct (js2-unary-node
3291 (:include js2-node)
3292 (:constructor nil)
3293 (:constructor make-js2-unary-node (&key type ; required
3294 (pos js2-ts-cursor)
3295 len
3296 operand)))
3297 "AST node type for unary operator nodes.
3298 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3299 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3300 property is added if the operator follows the operand."
3301 operand) ; a `js2-node' expression
3302
3303 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3304 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3305
3306 (defun js2-visit-unary-node (n v)
3307 (js2-visit-ast (js2-unary-node-operand n) v))
3308
3309 (defun js2-print-unary-node (n i)
3310 (let* ((tt (js2-node-type n))
3311 (op (gethash tt js2-operator-tokens))
3312 (postfix (js2-node-get-prop n 'postfix)))
3313 (unless op
3314 (error "unrecognized unary operator %s" tt))
3315 (insert (js2-make-pad i))
3316 (unless postfix
3317 (insert op))
3318 (if (or (= tt js2-TYPEOF)
3319 (= tt js2-DELPROP))
3320 (insert " "))
3321 (js2-print-ast (js2-unary-node-operand n) 0)
3322 (when postfix
3323 (insert op))))
3324
3325 (defstruct (js2-let-node
3326 (:include js2-scope)
3327 (:constructor nil)
3328 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3329 (pos js2-token-beg)
3330 len
3331 vars
3332 body
3333 lp
3334 rp)))
3335 "AST node for a let expression or a let statement.
3336 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3337 vars ; a `js2-var-decl-node'
3338 body ; a `js2-node' representing the expression or body block
3339 lp
3340 rp)
3341
3342 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3343 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3344
3345 (defun js2-visit-let-node (n v)
3346 (js2-visit-ast (js2-let-node-vars n) v)
3347 (js2-visit-ast (js2-let-node-body n) v))
3348
3349 (defun js2-print-let-node (n i)
3350 (insert (js2-make-pad i) "let (")
3351 (js2-print-ast (js2-let-node-vars n) 0)
3352 (insert ") ")
3353 (js2-print-ast (js2-let-node-body n) i))
3354
3355 (defstruct (js2-keyword-node
3356 (:include js2-node)
3357 (:constructor nil)
3358 (:constructor make-js2-keyword-node (&key type
3359 (pos js2-token-beg)
3360 (len (- js2-ts-cursor pos)))))
3361 "AST node representing a literal keyword such as `null'.
3362 Used for `null', `this', `true', `false' and `debugger'.
3363 The node type is set to js2-NULL, js2-THIS, etc.")
3364
3365 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3366 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3367
3368 (defun js2-print-keyword-node (n i)
3369 (insert (js2-make-pad i)
3370 (let ((tt (js2-node-type n)))
3371 (cond
3372 ((= tt js2-THIS) "this")
3373 ((= tt js2-NULL) "null")
3374 ((= tt js2-TRUE) "true")
3375 ((= tt js2-FALSE) "false")
3376 ((= tt js2-DEBUGGER) "debugger")
3377 (t (error "Invalid keyword literal type: %d" tt))))))
3378
3379 (defsubst js2-this-node-p (node)
3380 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3381 (eq (js2-node-type node) js2-THIS))
3382
3383 (defstruct (js2-new-node
3384 (:include js2-node)
3385 (:constructor nil)
3386 (:constructor make-js2-new-node (&key (type js2-NEW)
3387 (pos js2-token-beg)
3388 len
3389 target
3390 args
3391 initializer
3392 lp
3393 rp)))
3394 "AST node for new-expression such as new Foo()."
3395 target ; an identifier or reference
3396 args ; a lisp list of argument nodes
3397 lp ; position of left-paren, nil if omitted
3398 rp ; position of right-paren, nil if omitted
3399 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3400
3401 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3402 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3403
3404 (defun js2-visit-new-node (n v)
3405 (js2-visit-ast (js2-new-node-target n) v)
3406 (dolist (arg (js2-new-node-args n))
3407 (js2-visit-ast arg v))
3408 (js2-visit-ast (js2-new-node-initializer n) v))
3409
3410 (defun js2-print-new-node (n i)
3411 (insert (js2-make-pad i) "new ")
3412 (js2-print-ast (js2-new-node-target n))
3413 (insert "(")
3414 (js2-print-list (js2-new-node-args n))
3415 (insert ")")
3416 (when (js2-new-node-initializer n)
3417 (insert " ")
3418 (js2-print-ast (js2-new-node-initializer n))))
3419
3420 (defstruct (js2-name-node
3421 (:include js2-node)
3422 (:constructor nil)
3423 (:constructor make-js2-name-node (&key (type js2-NAME)
3424 (pos js2-token-beg)
3425 (len (- js2-ts-cursor
3426 js2-token-beg))
3427 (name js2-ts-string))))
3428 "AST node for a JavaScript identifier"
3429 name ; a string
3430 scope) ; a `js2-scope' (optional, used for codegen)
3431
3432 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3433 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3434
3435 (defun js2-print-name-node (n i)
3436 (insert (js2-make-pad i)
3437 (js2-name-node-name n)))
3438
3439 (defsubst js2-name-node-length (node)
3440 "Return identifier length of NODE, a `js2-name-node'.
3441 Returns 0 if NODE is nil or its identifier field is nil."
3442 (if node
3443 (length (js2-name-node-name node))
3444 0))
3445
3446 (defstruct (js2-number-node
3447 (:include js2-node)
3448 (:constructor nil)
3449 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3450 (pos js2-token-beg)
3451 (len (- js2-ts-cursor
3452 js2-token-beg))
3453 (value js2-ts-string)
3454 (num-value js2-ts-number))))
3455 "AST node for a number literal."
3456 value ; the original string, e.g. "6.02e23"
3457 num-value) ; the parsed number value
3458
3459 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3460 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3461
3462 (defun js2-print-number-node (n i)
3463 (insert (js2-make-pad i)
3464 (number-to-string (js2-number-node-num-value n))))
3465
3466 (defstruct (js2-regexp-node
3467 (:include js2-node)
3468 (:constructor nil)
3469 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3470 (pos js2-token-beg)
3471 (len (- js2-ts-cursor
3472 js2-token-beg))
3473 value
3474 flags)))
3475 "AST node for a regular expression literal."
3476 value ; the regexp string, without // delimiters
3477 flags) ; a string of flags, e.g. `mi'.
3478
3479 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3480 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3481
3482 (defun js2-print-regexp (n i)
3483 (insert (js2-make-pad i)
3484 "/"
3485 (js2-regexp-node-value n)
3486 "/")
3487 (if (js2-regexp-node-flags n)
3488 (insert (js2-regexp-node-flags n))))
3489
3490 (defstruct (js2-string-node
3491 (:include js2-node)
3492 (:constructor nil)
3493 (:constructor make-js2-string-node (&key (type js2-STRING)
3494 (pos js2-token-beg)
3495 (len (- js2-ts-cursor
3496 js2-token-beg))
3497 (value js2-ts-string))))
3498 "String literal.
3499 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3500 You can tell the quote type by looking at the first character."
3501 value) ; the characters of the string, including the quotes
3502
3503 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3504 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3505
3506 (defun js2-print-string-node (n i)
3507 (insert (js2-make-pad i)
3508 (js2-node-string n)))
3509
3510 (defstruct (js2-array-node
3511 (:include js2-node)
3512 (:constructor nil)
3513 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3514 (pos js2-ts-cursor)
3515 len
3516 elems)))
3517 "AST node for an array literal."
3518 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3519
3520 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3521 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3522
3523 (defun js2-visit-array-node (n v)
3524 (dolist (e (js2-array-node-elems n))
3525 (js2-visit-ast e v)))
3526
3527 (defun js2-print-array-node (n i)
3528 (insert (js2-make-pad i) "[")
3529 (js2-print-list (js2-array-node-elems n))
3530 (insert "]"))
3531
3532 (defstruct (js2-object-node
3533 (:include js2-node)
3534 (:constructor nil)
3535 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3536 (pos js2-ts-cursor)
3537 len
3538 elems)))
3539 "AST node for an object literal expression.
3540 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3541 the latter represents abbreviation in destructuring expressions."
3542 elems)
3543
3544 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3545 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3546
3547 (defun js2-visit-object-node (n v)
3548 (dolist (e (js2-object-node-elems n))
3549 (js2-visit-ast e v)))
3550
3551 (defun js2-print-object-node (n i)
3552 (insert (js2-make-pad i) "{")
3553 (js2-print-list (js2-object-node-elems n))
3554 (insert "}"))
3555
3556 (defstruct (js2-object-prop-node
3557 (:include js2-infix-node)
3558 (:constructor nil)
3559 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3560 (pos js2-ts-cursor)
3561 len
3562 left
3563 right
3564 op-pos)))
3565 "AST node for an object literal prop:value entry.
3566 The `left' field is the property: a name node, string node or number node.
3567 The `right' field is a `js2-node' representing the initializer value.")
3568
3569 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3570 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3571
3572 (defun js2-print-object-prop-node (n i)
3573 (insert (js2-make-pad i))
3574 (js2-print-ast (js2-object-prop-node-left n) 0)
3575 (insert ":")
3576 (js2-print-ast (js2-object-prop-node-right n) 0))
3577
3578 (defstruct (js2-getter-setter-node
3579 (:include js2-infix-node)
3580 (:constructor nil)
3581 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3582 (pos js2-ts-cursor)
3583 len
3584 left
3585 right)))
3586 "AST node for a getter/setter property in an object literal.
3587 The `left' field is the `js2-name-node' naming the getter/setter prop.
3588 The `right' field is always an anonymous `js2-function-node' with a node
3589 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3590
3591 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3592 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3593
3594 (defun js2-print-getter-setter (n i)
3595 (let ((pad (js2-make-pad i))
3596 (left (js2-getter-setter-node-left n))
3597 (right (js2-getter-setter-node-right n)))
3598 (insert pad)
3599 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3600 (js2-print-ast left 0)
3601 (js2-print-ast right 0)))
3602
3603 (defstruct (js2-prop-get-node
3604 (:include js2-infix-node)
3605 (:constructor nil)
3606 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3607 (pos js2-ts-cursor)
3608 len
3609 left
3610 right)))
3611 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3612
3613 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3614 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3615
3616 (defun js2-visit-prop-get-node (n v)
3617 (js2-visit-ast (js2-prop-get-node-left n) v)
3618 (js2-visit-ast (js2-prop-get-node-right n) v))
3619
3620 (defun js2-print-prop-get-node (n i)
3621 (insert (js2-make-pad i))
3622 (js2-print-ast (js2-prop-get-node-left n) 0)
3623 (insert ".")
3624 (js2-print-ast (js2-prop-get-node-right n) 0))
3625
3626 (defstruct (js2-elem-get-node
3627 (:include js2-node)
3628 (:constructor nil)
3629 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3630 (pos js2-ts-cursor)
3631 len
3632 target
3633 element
3634 lb
3635 rb)))
3636 "AST node for an array index expression such as foo[bar]."
3637 target ; a `js2-node' - the expression preceding the "."
3638 element ; a `js2-node' - the expression in brackets
3639 lb ; position of left-bracket, nil if omitted
3640 rb) ; position of right-bracket, nil if omitted
3641
3642 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3643 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3644
3645 (defun js2-visit-elem-get-node (n v)
3646 (js2-visit-ast (js2-elem-get-node-target n) v)
3647 (js2-visit-ast (js2-elem-get-node-element n) v))
3648
3649 (defun js2-print-elem-get-node (n i)
3650 (insert (js2-make-pad i))
3651 (js2-print-ast (js2-elem-get-node-target n) 0)
3652 (insert "[")
3653 (js2-print-ast (js2-elem-get-node-element n) 0)
3654 (insert "]"))
3655
3656 (defstruct (js2-call-node
3657 (:include js2-node)
3658 (:constructor nil)
3659 (:constructor make-js2-call-node (&key (type js2-CALL)
3660 (pos js2-ts-cursor)
3661 len
3662 target
3663 args
3664 lp
3665 rp)))
3666 "AST node for a JavaScript function call."
3667 target ; a `js2-node' evaluating to the function to call
3668 args ; a lisp list of `js2-node' arguments
3669 lp ; position of open-paren, or nil if missing
3670 rp) ; position of close-paren, or nil if missing
3671
3672 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3673 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3674
3675 (defun js2-visit-call-node (n v)
3676 (js2-visit-ast (js2-call-node-target n) v)
3677 (dolist (arg (js2-call-node-args n))
3678 (js2-visit-ast arg v)))
3679
3680 (defun js2-print-call-node (n i)
3681 (insert (js2-make-pad i))
3682 (js2-print-ast (js2-call-node-target n) 0)
3683 (insert "(")
3684 (js2-print-list (js2-call-node-args n))
3685 (insert ")"))
3686
3687 (defstruct (js2-yield-node
3688 (:include js2-node)
3689 (:constructor nil)
3690 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3691 (pos js2-ts-cursor)
3692 len
3693 value)))
3694 "AST node for yield statement or expression."
3695 value) ; optional: value to be yielded
3696
3697 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3698 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3699
3700 (defun js2-visit-yield-node (n v)
3701 (js2-visit-ast (js2-yield-node-value n) v))
3702
3703 (defun js2-print-yield-node (n i)
3704 (insert (js2-make-pad i))
3705 (insert "yield")
3706 (when (js2-yield-node-value n)
3707 (insert " ")
3708 (js2-print-ast (js2-yield-node-value n) 0)))
3709
3710 (defstruct (js2-paren-node
3711 (:include js2-node)
3712 (:constructor nil)
3713 (:constructor make-js2-paren-node (&key (type js2-LP)
3714 (pos js2-ts-cursor)
3715 len
3716 expr)))
3717 "AST node for a parenthesized expression.
3718 In particular, used when the parens are syntactically optional,
3719 as opposed to required parens such as those enclosing an if-conditional."
3720 expr) ; `js2-node'
3721
3722 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3723 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3724
3725 (defun js2-visit-paren-node (n v)
3726 (js2-visit-ast (js2-paren-node-expr n) v))
3727
3728 (defun js2-print-paren-node (n i)
3729 (insert (js2-make-pad i))
3730 (insert "(")
3731 (js2-print-ast (js2-paren-node-expr n) 0)
3732 (insert ")"))
3733
3734 (defstruct (js2-array-comp-node
3735 (:include js2-scope)
3736 (:constructor nil)
3737 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3738 (pos js2-ts-cursor)
3739 len
3740 result
3741 loops
3742 filter
3743 if-pos
3744 lp
3745 rp)))
3746 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3747 result ; result expression (just after left-bracket)
3748 loops ; a lisp list of `js2-array-comp-loop-node'
3749 filter ; guard/filter expression
3750 if-pos ; buffer pos of 'if' keyword, if present, else nil
3751 lp ; buffer position of if-guard left-paren, or nil if not present
3752 rp) ; buffer position of if-guard right-paren, or nil if not present
3753
3754 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3755 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3756
3757 (defun js2-visit-array-comp-node (n v)
3758 (js2-visit-ast (js2-array-comp-node-result n) v)
3759 (dolist (l (js2-array-comp-node-loops n))
3760 (js2-visit-ast l v))
3761 (js2-visit-ast (js2-array-comp-node-filter n) v))
3762
3763 (defun js2-print-array-comp-node (n i)
3764 (let ((pad (js2-make-pad i))
3765 (result (js2-array-comp-node-result n))
3766 (loops (js2-array-comp-node-loops n))
3767 (filter (js2-array-comp-node-filter n)))
3768 (insert pad "[")
3769 (js2-print-ast result 0)
3770 (dolist (l loops)
3771 (insert " ")
3772 (js2-print-ast l 0))
3773 (when filter
3774 (insert " if (")
3775 (js2-print-ast filter 0))
3776 (insert ")]")))
3777
3778 (defstruct (js2-array-comp-loop-node
3779 (:include js2-for-in-node)
3780 (:constructor nil)
3781 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3782 (pos js2-ts-cursor)
3783 len
3784 iterator
3785 object
3786 in-pos
3787 foreach-p
3788 each-pos
3789 lp
3790 rp)))
3791 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3792
3793 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3794 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3795
3796 (defun js2-visit-array-comp-loop (n v)
3797 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3798 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3799
3800 (defun js2-print-array-comp-loop (n i)
3801 (insert "for (")
3802 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3803 (insert " in ")
3804 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3805 (insert ")"))
3806
3807 (defstruct (js2-empty-expr-node
3808 (:include js2-node)
3809 (:constructor nil)
3810 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3811 (pos js2-token-beg)
3812 len)))
3813 "AST node for an empty expression.")
3814
3815 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3816 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3817
3818 (defstruct (js2-xml-node
3819 (:include js2-block-node)
3820 (:constructor nil)
3821 (:constructor make-js2-xml-node (&key (type js2-XML)
3822 (pos js2-token-beg)
3823 len
3824 kids)))
3825 "AST node for initial parse of E4X literals.
3826 The kids field is a list of XML fragments, each a `js2-string-node' or
3827 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3828
3829 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3830 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3831
3832 (defun js2-print-xml-node (n i)
3833 (dolist (kid (js2-xml-node-kids n))
3834 (js2-print-ast kid i)))
3835
3836 (defstruct (js2-xml-js-expr-node
3837 (:include js2-xml-node)
3838 (:constructor nil)
3839 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3840 (pos js2-ts-cursor)
3841 len
3842 expr)))
3843 "AST node for an embedded JavaScript {expression} in an E4X literal.
3844 The start and end fields correspond to the curly-braces."
3845 expr) ; a `js2-expr-node' of some sort
3846
3847 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3848 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3849
3850 (defun js2-visit-xml-js-expr (n v)
3851 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3852
3853 (defun js2-print-xml-js-expr (n i)
3854 (insert (js2-make-pad i))
3855 (insert "{")
3856 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3857 (insert "}"))
3858
3859 (defstruct (js2-xml-dot-query-node
3860 (:include js2-infix-node)
3861 (:constructor nil)
3862 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3863 (pos js2-ts-cursor)
3864 op-pos
3865 len
3866 left
3867 right
3868 rp)))
3869 "AST node for an E4X foo.(bar) filter expression.
3870 Note that the left-paren is automatically the character immediately
3871 following the dot (.) in the operator. No whitespace is permitted
3872 between the dot and the lp by the scanner."
3873 rp)
3874
3875 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3876 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3877
3878 (defun js2-print-xml-dot-query (n i)
3879 (insert (js2-make-pad i))
3880 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3881 (insert ".(")
3882 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3883 (insert ")"))
3884
3885 (defstruct (js2-xml-ref-node
3886 (:include js2-node)
3887 (:constructor nil)) ; abstract
3888 "Base type for E4X XML attribute-access or property-get expressions.
3889 Such expressions can take a variety of forms. The general syntax has
3890 three parts:
3891
3892 - (optional) an @ (specifying an attribute access)
3893 - (optional) a namespace (a `js2-name-node') and double-colon
3894 - (required) either a `js2-name-node' or a bracketed [expression]
3895
3896 The property-name expressions (examples: ns::name, @name) are
3897 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3898 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3899
3900 This node type (or more specifically, its subclasses) will sometimes
3901 be the right-hand child of a `js2-prop-get-node' or a
3902 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3903 The `js2-xml-ref-node' may also be a standalone primary expression with
3904 no explicit target, which is valid in certain expression contexts such as
3905
3906 company..employee.(@id < 100)
3907
3908 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3909 expression whose parent is a `js2-xml-dot-query-node'."
3910 namespace
3911 at-pos
3912 colon-pos)
3913
3914 (defsubst js2-xml-ref-node-attr-access-p (node)
3915 "Return non-nil if this expression began with an @-token."
3916 (and (numberp (js2-xml-ref-node-at-pos node))
3917 (plusp (js2-xml-ref-node-at-pos node))))
3918
3919 (defstruct (js2-xml-prop-ref-node
3920 (:include js2-xml-ref-node)
3921 (:constructor nil)
3922 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3923 (pos js2-token-beg)
3924 len
3925 propname
3926 namespace
3927 at-pos
3928 colon-pos)))
3929 "AST node for an E4X XML [expr] property-ref expression.
3930 The JavaScript syntax is an optional @, an optional ns::, and a name.
3931
3932 [ '@' ] [ name '::' ] name
3933
3934 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3935 @ns::*, @*::attr, @*::*, and @*.
3936
3937 The node starts at the @ token, if present. Otherwise it starts at the
3938 namespace name. The node bounds extend through the closing right-bracket,
3939 or if it is missing due to a syntax error, through the end of the index
3940 expression."
3941 propname)
3942
3943 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3944 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3945
3946 (defun js2-visit-xml-prop-ref-node (n v)
3947 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3948 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3949
3950 (defun js2-print-xml-prop-ref-node (n i)
3951 (insert (js2-make-pad i))
3952 (if (js2-xml-ref-node-attr-access-p n)
3953 (insert "@"))
3954 (when (js2-xml-prop-ref-node-namespace n)
3955 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3956 (insert "::"))
3957 (if (js2-xml-prop-ref-node-propname n)
3958 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3959
3960 (defstruct (js2-xml-elem-ref-node
3961 (:include js2-xml-ref-node)
3962 (:constructor nil)
3963 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3964 (pos js2-token-beg)
3965 len
3966 expr
3967 lb
3968 rb
3969 namespace
3970 at-pos
3971 colon-pos)))
3972 "AST node for an E4X XML [expr] member-ref expression.
3973 Syntax:
3974
3975 [ '@' ] [ name '::' ] '[' expr ']'
3976
3977 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3978
3979 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3980 is not a legal E4X XML element-ref expression, since it's already used
3981 for standard JavaScript element-get array indexing. Hence, a
3982 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3983 non-nil namespace node, or both.
3984
3985 The node starts at the @ token, if present. Otherwise it starts
3986 at the namespace name. The node bounds extend through the closing
3987 right-bracket, or if it is missing due to a syntax error, through the
3988 end of the index expression."
3989 expr ; the bracketed index expression
3990 lb
3991 rb)
3992
3993 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3994 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3995
3996 (defun js2-visit-xml-elem-ref-node (n v)
3997 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3998 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3999
4000 (defun js2-print-xml-elem-ref-node (n i)
4001 (insert (js2-make-pad i))
4002 (if (js2-xml-ref-node-attr-access-p n)
4003 (insert "@"))
4004 (when (js2-xml-elem-ref-node-namespace n)
4005 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4006 (insert "::"))
4007 (insert "[")
4008 (if (js2-xml-elem-ref-node-expr n)
4009 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4010 (insert "]"))
4011
4012 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4013
4014 (defstruct (js2-xml-start-tag-node
4015 (:include js2-xml-node)
4016 (:constructor nil)
4017 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4018 (pos js2-ts-cursor)
4019 len
4020 name
4021 attrs
4022 kids
4023 empty-p)))
4024 "AST node for an XML start-tag. Not currently used.
4025 The `kids' field is a lisp list of child content nodes."
4026 name ; a `js2-xml-name-node'
4027 attrs ; a lisp list of `js2-xml-attr-node'
4028 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4029
4030 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4031 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4032
4033 (defun js2-visit-xml-start-tag (n v)
4034 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4035 (dolist (attr (js2-xml-start-tag-node-attrs n))
4036 (js2-visit-ast attr v))
4037 (js2-visit-block n v))
4038
4039 (defun js2-print-xml-start-tag (n i)
4040 (insert (js2-make-pad i) "<")
4041 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4042 (when (js2-xml-start-tag-node-attrs n)
4043 (insert " ")
4044 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4045 (insert ">"))
4046
4047 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4048 ;; and add the end-tag to the kids list of the parent as well.
4049 (defstruct (js2-xml-end-tag-node
4050 (:include js2-xml-node)
4051 (:constructor nil)
4052 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4053 (pos js2-ts-cursor)
4054 len
4055 name)))
4056 "AST node for an XML end-tag. Not currently used."
4057 name) ; a `js2-xml-name-node'
4058
4059 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4060 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4061
4062 (defun js2-visit-xml-end-tag (n v)
4063 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4064
4065 (defun js2-print-xml-end-tag (n i)
4066 (insert (js2-make-pad i))
4067 (insert "</")
4068 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4069 (insert ">"))
4070
4071 (defstruct (js2-xml-name-node
4072 (:include js2-xml-node)
4073 (:constructor nil)
4074 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4075 (pos js2-ts-cursor)
4076 len
4077 namespace
4078 kids)))
4079 "AST node for an E4X XML name. Not currently used.
4080 Any XML name can be qualified with a namespace, hence the namespace field.
4081 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4082 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4083 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4084 namespace) ; a `js2-string-node'
4085
4086 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4087 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4088
4089 (defun js2-visit-xml-name-node (n v)
4090 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4091
4092 (defun js2-print-xml-name-node (n i)
4093 (insert (js2-make-pad i))
4094 (when (js2-xml-name-node-namespace n)
4095 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4096 (insert "::"))
4097 (dolist (kid (js2-xml-name-node-kids n))
4098 (js2-print-ast kid 0)))
4099
4100 (defstruct (js2-xml-pi-node
4101 (:include js2-xml-node)
4102 (:constructor nil)
4103 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4104 (pos js2-ts-cursor)
4105 len
4106 name
4107 attrs)))
4108 "AST node for an E4X XML processing instruction. Not currently used."
4109 name ; a `js2-xml-name-node'
4110 attrs) ; a list of `js2-xml-attr-node'
4111
4112 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4113 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4114
4115 (defun js2-visit-xml-pi-node (n v)
4116 (js2-visit-ast (js2-xml-pi-node-name n) v)
4117 (dolist (attr (js2-xml-pi-node-attrs n))
4118 (js2-visit-ast attr v)))
4119
4120 (defun js2-print-xml-pi-node (n i)
4121 (insert (js2-make-pad i) "<?")
4122 (js2-print-ast (js2-xml-pi-node-name n))
4123 (when (js2-xml-pi-node-attrs n)
4124 (insert " ")
4125 (js2-print-list (js2-xml-pi-node-attrs n)))
4126 (insert "?>"))
4127
4128 (defstruct (js2-xml-cdata-node
4129 (:include js2-xml-node)
4130 (:constructor nil)
4131 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4132 (pos js2-ts-cursor)
4133 len
4134 content)))
4135 "AST node for a CDATA escape section. Not currently used."
4136 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4137
4138 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4139 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4140
4141 (defun js2-visit-xml-cdata-node (n v)
4142 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4143
4144 (defun js2-print-xml-cdata-node (n i)
4145 (insert (js2-make-pad i))
4146 (js2-print-ast (js2-xml-cdata-node-content n)))
4147
4148 (defstruct (js2-xml-attr-node
4149 (:include js2-xml-node)
4150 (:constructor nil)
4151 (:constructor make-js2-attr-node (&key (type js2-XML)
4152 (pos js2-ts-cursor)
4153 len
4154 name
4155 value
4156 eq-pos
4157 quote-type)))
4158 "AST node representing a foo='bar' XML attribute value. Not yet used."
4159 name ; a `js2-xml-name-node'
4160 value ; a `js2-xml-name-node'
4161 eq-pos ; buffer position of "=" sign
4162 quote-type) ; 'single or 'double
4163
4164 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4165 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4166
4167 (defun js2-visit-xml-attr-node (n v)
4168 (js2-visit-ast (js2-xml-attr-node-name n) v)
4169 (js2-visit-ast (js2-xml-attr-node-value n) v))
4170
4171 (defun js2-print-xml-attr-node (n i)
4172 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4173 "'"
4174 "\"")))
4175 (insert (js2-make-pad i))
4176 (js2-print-ast (js2-xml-attr-node-name n) 0)
4177 (insert "=" quote)
4178 (js2-print-ast (js2-xml-attr-node-value n) 0)
4179 (insert quote)))
4180
4181 (defstruct (js2-xml-text-node
4182 (:include js2-xml-node)
4183 (:constructor nil)
4184 (:constructor make-js2-text-node (&key (type js2-XML)
4185 (pos js2-ts-cursor)
4186 len
4187 content)))
4188 "AST node for an E4X XML text node. Not currently used."
4189 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4190
4191 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4192 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4193
4194 (defun js2-visit-xml-text-node (n v)
4195 (js2-visit-ast (js2-xml-text-node-content n) v))
4196
4197 (defun js2-print-xml-text-node (n i)
4198 (insert (js2-make-pad i))
4199 (dolist (kid (js2-xml-text-node-content n))
4200 (js2-print-ast kid)))
4201
4202 (defstruct (js2-xml-comment-node
4203 (:include js2-xml-node)
4204 (:constructor nil)
4205 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4206 (pos js2-ts-cursor)
4207 len)))
4208 "AST node for E4X XML comment. Not currently used.")
4209
4210 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4211 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4212
4213 (defun js2-print-xml-comment (n i)
4214 (insert (js2-make-pad i)
4215 (js2-node-string n)))
4216
4217 ;;; Node utilities
4218
4219 (defsubst js2-node-line (n)
4220 "Fetch the source line number at the start of node N.
4221 This is O(n) in the length of the source buffer; use prudently."
4222 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4223
4224 (defsubst js2-block-node-kid (n i)
4225 "Return child I of node N, or nil if there aren't that many."
4226 (nth i (js2-block-node-kids n)))
4227
4228 (defsubst js2-block-node-first (n)
4229 "Return first child of block node N, or nil if there is none."
4230 (first (js2-block-node-kids n)))
4231
4232 (defun js2-node-root (n)
4233 "Return the root of the AST containing N.
4234 If N has no parent pointer, returns N."
4235 (let ((parent (js2-node-parent n)))
4236 (if parent
4237 (js2-node-root parent)
4238 n)))
4239
4240 (defun js2-node-position-in-parent (node &optional parent)
4241 "Return the position of NODE in parent's block-kids list.
4242 PARENT can be supplied if known. Positioned returned is zero-indexed.
4243 Returns 0 if NODE is not a child of a block statement, or if NODE
4244 is not a statement node."
4245 (let ((p (or parent (js2-node-parent node)))
4246 (i 0))
4247 (if (not (js2-block-node-p p))
4248 i
4249 (or (js2-position node (js2-block-node-kids p))
4250 0))))
4251
4252 (defsubst js2-node-short-name (n)
4253 "Return the short name of node N as a string, e.g. `js2-if-node'."
4254 (substring (symbol-name (aref n 0))
4255 (length "cl-struct-")))
4256
4257 (defsubst js2-node-child-list (node)
4258 "Return the child list for NODE, a lisp list of nodes.
4259 Works for block nodes, array nodes, obj literals, funarg lists,
4260 var decls and try nodes (for catch clauses). Note that you should call
4261 `js2-block-node-kids' on the function body for the body statements.
4262 Returns nil for zero-length child lists or unsupported nodes."
4263 (cond
4264 ((js2-function-node-p node)
4265 (js2-function-node-params node))
4266 ((js2-block-node-p node)
4267 (js2-block-node-kids node))
4268 ((js2-try-node-p node)
4269 (js2-try-node-catch-clauses node))
4270 ((js2-array-node-p node)
4271 (js2-array-node-elems node))
4272 ((js2-object-node-p node)
4273 (js2-object-node-elems node))
4274 ((js2-call-node-p node)
4275 (js2-call-node-args node))
4276 ((js2-new-node-p node)
4277 (js2-new-node-args node))
4278 ((js2-var-decl-node-p node)
4279 (js2-var-decl-node-kids node))
4280 (t
4281 nil)))
4282
4283 (defsubst js2-node-set-child-list (node kids)
4284 "Set the child list for NODE to KIDS."
4285 (cond
4286 ((js2-function-node-p node)
4287 (setf (js2-function-node-params node) kids))
4288 ((js2-block-node-p node)
4289 (setf (js2-block-node-kids node) kids))
4290 ((js2-try-node-p node)
4291 (setf (js2-try-node-catch-clauses node) kids))
4292 ((js2-array-node-p node)
4293 (setf (js2-array-node-elems node) kids))
4294 ((js2-object-node-p node)
4295 (setf (js2-object-node-elems node) kids))
4296 ((js2-call-node-p node)
4297 (setf (js2-call-node-args node) kids))
4298 ((js2-new-node-p node)
4299 (setf (js2-new-node-args node) kids))
4300 ((js2-var-decl-node-p node)
4301 (setf (js2-var-decl-node-kids node) kids))
4302 (t
4303 (error "Unsupported node type: %s" (js2-node-short-name node))))
4304 kids)
4305
4306 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4307 (defconst js2-paren-expr-nodes
4308 '(cl-struct-js2-array-comp-loop-node
4309 cl-struct-js2-array-comp-node
4310 cl-struct-js2-call-node
4311 cl-struct-js2-catch-node
4312 cl-struct-js2-do-node
4313 cl-struct-js2-elem-get-node
4314 cl-struct-js2-for-in-node
4315 cl-struct-js2-for-node
4316 cl-struct-js2-function-node
4317 cl-struct-js2-if-node
4318 cl-struct-js2-let-node
4319 cl-struct-js2-new-node
4320 cl-struct-js2-paren-node
4321 cl-struct-js2-switch-node
4322 cl-struct-js2-while-node
4323 cl-struct-js2-with-node
4324 cl-struct-js2-xml-dot-query-node)
4325 "Node types that can have a parenthesized child expression.
4326 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4327
4328 (defsubst js2-paren-expr-node-p (node)
4329 "Return t for nodes that typically have a parenthesized child expression.
4330 Useful for computing the indentation anchors for arg-lists and conditions.
4331 Note that it may return a false positive, for instance when NODE is
4332 a `js2-new-node' and there are no arguments or parentheses."
4333 (memq (aref node 0) js2-paren-expr-nodes))
4334
4335 ;; Fake polymorphism... yech.
4336 (defsubst js2-node-lp (node)
4337 "Return relative left-paren position for NODE, if applicable.
4338 For `js2-elem-get-node' structs, returns left-bracket position.
4339 Note that the position may be nil in the case of a parse error."
4340 (cond
4341 ((js2-elem-get-node-p node)
4342 (js2-elem-get-node-lb node))
4343 ((js2-loop-node-p node)
4344 (js2-loop-node-lp node))
4345 ((js2-function-node-p node)
4346 (js2-function-node-lp node))
4347 ((js2-if-node-p node)
4348 (js2-if-node-lp node))
4349 ((js2-new-node-p node)
4350 (js2-new-node-lp node))
4351 ((js2-call-node-p node)
4352 (js2-call-node-lp node))
4353 ((js2-paren-node-p node)
4354 (js2-node-pos node))
4355 ((js2-switch-node-p node)
4356 (js2-switch-node-lp node))
4357 ((js2-catch-node-p node)
4358 (js2-catch-node-lp node))
4359 ((js2-let-node-p node)
4360 (js2-let-node-lp node))
4361 ((js2-array-comp-node-p node)
4362 (js2-array-comp-node-lp node))
4363 ((js2-with-node-p node)
4364 (js2-with-node-lp node))
4365 ((js2-xml-dot-query-node-p node)
4366 (1+ (js2-infix-node-op-pos node)))
4367 (t
4368 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4369
4370 ;; Fake polymorphism... blech.
4371 (defsubst js2-node-rp (node)
4372 "Return relative right-paren position for NODE, if applicable.
4373 For `js2-elem-get-node' structs, returns right-bracket position.
4374 Note that the position may be nil in the case of a parse error."
4375 (cond
4376 ((js2-elem-get-node-p node)
4377 (js2-elem-get-node-lb node))
4378 ((js2-loop-node-p node)
4379 (js2-loop-node-rp node))
4380 ((js2-function-node-p node)
4381 (js2-function-node-rp node))
4382 ((js2-if-node-p node)
4383 (js2-if-node-rp node))
4384 ((js2-new-node-p node)
4385 (js2-new-node-rp node))
4386 ((js2-call-node-p node)
4387 (js2-call-node-rp node))
4388 ((js2-paren-node-p node)
4389 (+ (js2-node-pos node) (js2-node-len node)))
4390 ((js2-switch-node-p node)
4391 (js2-switch-node-rp node))
4392 ((js2-catch-node-p node)
4393 (js2-catch-node-rp node))
4394 ((js2-let-node-p node)
4395 (js2-let-node-rp node))
4396 ((js2-array-comp-node-p node)
4397 (js2-array-comp-node-rp node))
4398 ((js2-with-node-p node)
4399 (js2-with-node-rp node))
4400 ((js2-xml-dot-query-node-p node)
4401 (1+ (js2-xml-dot-query-node-rp node)))
4402 (t
4403 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4404
4405 (defsubst js2-node-first-child (node)
4406 "Returns the first element of `js2-node-child-list' for NODE."
4407 (car (js2-node-child-list node)))
4408
4409 (defsubst js2-node-last-child (node)
4410 "Returns the last element of `js2-node-last-child' for NODE."
4411 (car (last (js2-node-child-list node))))
4412
4413 (defun js2-node-prev-sibling (node)
4414 "Return the previous statement in parent.
4415 Works for parents supported by `js2-node-child-list'.
4416 Returns nil if NODE is not in the parent, or PARENT is
4417 not a supported node, or if NODE is the first child."
4418 (let* ((p (js2-node-parent node))
4419 (kids (js2-node-child-list p))
4420 (sib (car kids)))
4421 (while (and kids
4422 (not (eq node (cadr kids))))
4423 (setq kids (cdr kids)
4424 sib (car kids)))
4425 sib))
4426
4427 (defun js2-node-next-sibling (node)
4428 "Return the next statement in parent block.
4429 Returns nil if NODE is not in the block, or PARENT is not
4430 a block node, or if NODE is the last statement."
4431 (let* ((p (js2-node-parent node))
4432 (kids (js2-node-child-list p)))
4433 (while (and kids
4434 (not (eq node (car kids))))
4435 (setq kids (cdr kids)))
4436 (cadr kids)))
4437
4438 (defun js2-node-find-child-before (pos parent &optional after)
4439 "Find the last child that starts before POS in parent.
4440 If AFTER is non-nil, returns first child starting after POS.
4441 POS is an absolute buffer position. PARENT is any node
4442 supported by `js2-node-child-list'.
4443 Returns nil if no applicable child is found."
4444 (let ((kids (if (js2-function-node-p parent)
4445 (js2-block-node-kids (js2-function-node-body parent))
4446 (js2-node-child-list parent)))
4447 (beg (if (js2-function-node-p parent)
4448 (js2-node-abs-pos (js2-function-node-body parent))
4449 (js2-node-abs-pos parent)))
4450 kid
4451 result
4452 fn
4453 (continue t))
4454 (setq fn (if after '> '<))
4455 (while (and kids continue)
4456 (setq kid (car kids))
4457 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4458 (setq result kid
4459 continue (if after nil t))
4460 (setq continue (if after t nil)))
4461 (setq kids (cdr kids)))
4462 result))
4463
4464 (defun js2-node-find-child-after (pos parent)
4465 "Find first child that starts after POS in parent.
4466 POS is an absolute buffer position. PARENT is any node
4467 supported by `js2-node-child-list'.
4468 Returns nil if no applicable child is found."
4469 (js2-node-find-child-before pos parent 'after))
4470
4471 (defun js2-node-replace-child (pos parent new-node)
4472 "Replace node at index POS in PARENT with NEW-NODE.
4473 Only works for parents supported by `js2-node-child-list'."
4474 (let ((kids (js2-node-child-list parent))
4475 (i 0))
4476 (while (< i pos)
4477 (setq kids (cdr kids)
4478 i (1+ i)))
4479 (setcar kids new-node)
4480 (js2-node-add-children parent new-node)))
4481
4482 (defun js2-node-buffer (n)
4483 "Return the buffer associated with AST N.
4484 Returns nil if the buffer is not set as a property on the root
4485 node, or if parent links were not recorded during parsing."
4486 (let ((root (js2-node-root n)))
4487 (and root
4488 (js2-ast-root-p root)
4489 (js2-ast-root-buffer root))))
4490
4491 (defsubst js2-block-node-push (n kid)
4492 "Push js2-node KID onto the end of js2-block-node N's child list.
4493 KID is always added to the -end- of the kids list.
4494 Function also calls `js2-node-add-children' to add the parent link."
4495 (let ((kids (js2-node-child-list n)))
4496 (if kids
4497 (setcdr kids (nconc (cdr kids) (list kid)))
4498 (js2-node-set-child-list n (list kid)))
4499 (js2-node-add-children n kid)))
4500
4501 (defun js2-node-string (node)
4502 (let ((buf (js2-node-buffer node))
4503 pos)
4504 (unless buf
4505 (error "No buffer available for node %s" node))
4506 (save-excursion
4507 (set-buffer buf)
4508 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4509 (+ pos (js2-node-len node))))))
4510
4511 ;; Container for storing the node we're looking for in a traversal.
4512 (js2-deflocal js2-discovered-node nil)
4513
4514 ;; Keep track of absolute node position during traversals.
4515 (js2-deflocal js2-visitor-offset nil)
4516
4517 (js2-deflocal js2-node-search-point nil)
4518
4519 (when js2-mode-dev-mode-p
4520 (defun js2-find-node-at-point ()
4521 (interactive)
4522 (let ((node (js2-node-at-point)))
4523 (message "%s" (or node "No node found at point"))))
4524 (defun js2-node-name-at-point ()
4525 (interactive)
4526 (let ((node (js2-node-at-point)))
4527 (message "%s" (if node
4528 (js2-node-short-name node)
4529 "No node found at point.")))))
4530
4531 (defun js2-node-at-point (&optional pos skip-comments)
4532 "Return AST node at POS, a buffer position, defaulting to current point.
4533 The `js2-mode-ast' variable must be set to the current parse tree.
4534 Signals an error if the AST (`js2-mode-ast') is nil.
4535 Always returns a node - if it can't find one, it returns the root.
4536 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4537 (let ((ast js2-mode-ast)
4538 result)
4539 (unless ast
4540 (error "No JavaScript AST available"))
4541 ;; Look through comments first, since they may be inside nodes that
4542 ;; would otherwise report a match.
4543 (setq pos (or pos (point))
4544 result (if (> pos (js2-node-abs-end ast))
4545 ast
4546 (if (not skip-comments)
4547 (js2-comment-at-point pos))))
4548 (unless result
4549 (setq js2-discovered-node nil
4550 js2-visitor-offset 0
4551 js2-node-search-point pos)
4552 (unwind-protect
4553 (catch 'js2-visit-done
4554 (js2-visit-ast ast #'js2-node-at-point-visitor))
4555 (setq js2-visitor-offset nil
4556 js2-node-search-point nil))
4557 (setq result js2-discovered-node))
4558 ;; may have found a comment beyond end of last child node,
4559 ;; since visiting the ast-root looks at the comment-list last.
4560 (if (and skip-comments
4561 (js2-comment-node-p result))
4562 (setq result nil))
4563 (or result js2-mode-ast)))
4564
4565 (defun js2-node-at-point-visitor (node end-p)
4566 (let ((rel-pos (js2-node-pos node))
4567 abs-pos
4568 abs-end
4569 (point js2-node-search-point))
4570 (cond
4571 (end-p
4572 ;; this evaluates to a non-nil return value, even if it's zero
4573 (decf js2-visitor-offset rel-pos))
4574 ;; we already looked for comments before visiting, and don't want them now
4575 ((js2-comment-node-p node)
4576 nil)
4577 (t
4578 (setq abs-pos (incf js2-visitor-offset rel-pos)
4579 ;; we only want to use the node if the point is before
4580 ;; the last character position in the node, so we decrement
4581 ;; the absolute end by 1.
4582 abs-end (+ abs-pos (js2-node-len node) -1))
4583 (cond
4584 ;; If this node starts after search-point, stop the search.
4585 ((> abs-pos point)
4586 (throw 'js2-visit-done nil))
4587 ;; If this node ends before the search-point, don't check kids.
4588 ((> point abs-end)
4589 nil)
4590 (t
4591 ;; Otherwise point is within this node, possibly in a child.
4592 (setq js2-discovered-node node)
4593 t)))))) ; keep processing kids to look for more specific match
4594
4595 (defsubst js2-block-comment-p (node)
4596 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4597 (and (js2-comment-node-p node)
4598 (memq (js2-comment-node-format node) '(jsdoc block))))
4599
4600 ;; TODO: put the comments in a vector and binary-search them instead
4601 (defun js2-comment-at-point (&optional pos)
4602 "Look through scanned comment nodes for one containing POS.
4603 POS is a buffer position that defaults to current point.
4604 Function returns nil if POS was not in any comment node."
4605 (let ((ast js2-mode-ast)
4606 (x (or pos (point)))
4607 beg
4608 end)
4609 (unless ast
4610 (error "No JavaScript AST available"))
4611 (catch 'done
4612 ;; Comments are stored in lexical order.
4613 (dolist (comment (js2-ast-root-comments ast) nil)
4614 (setq beg (js2-node-abs-pos comment)
4615 end (+ beg (js2-node-len comment)))
4616 (if (and (>= x beg)
4617 (<= x end))
4618 (throw 'done comment))))))
4619
4620 (defun js2-mode-find-parent-fn (node)
4621 "Find function enclosing NODE.
4622 Returns nil if NODE is not inside a function."
4623 (setq node (js2-node-parent node))
4624 (while (and node (not (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 (and (js2-function-node-p node) node))
4627
4628 (defun js2-mode-find-enclosing-fn (node)
4629 "Find function or root enclosing NODE."
4630 (if (js2-ast-root-p node)
4631 node
4632 (setq node (js2-node-parent node))
4633 (while (not (or (js2-ast-root-p node)
4634 (js2-function-node-p node)))
4635 (setq node (js2-node-parent node)))
4636 node))
4637
4638 (defun js2-mode-find-enclosing-node (beg end)
4639 "Find script or function fully enclosing BEG and END."
4640 (let ((node (js2-node-at-point beg))
4641 pos
4642 (continue t))
4643 (while continue
4644 (if (or (js2-ast-root-p node)
4645 (and (js2-function-node-p node)
4646 (<= (setq pos (js2-node-abs-pos node)) beg)
4647 (>= (+ pos (js2-node-len node)) end)))
4648 (setq continue nil)
4649 (setq node (js2-node-parent node))))
4650 node))
4651
4652 (defun js2-node-parent-script-or-fn (node)
4653 "Find script or function immediately enclosing NODE.
4654 If NODE is the ast-root, returns nil."
4655 (if (js2-ast-root-p node)
4656 nil
4657 (setq node (js2-node-parent node))
4658 (while (and node (not (or (js2-function-node-p node)
4659 (js2-script-node-p node))))
4660 (setq node (js2-node-parent node)))
4661 node))
4662
4663 (defsubst js2-nested-function-p (node)
4664 "Return t if NODE is a nested function, or is inside a nested function."
4665 (unless (js2-ast-root-p node)
4666 (js2-function-node-p (if (js2-function-node-p node)
4667 (js2-node-parent-script-or-fn node)
4668 (js2-node-parent-script-or-fn
4669 (js2-node-parent-script-or-fn node))))))
4670
4671 (defsubst js2-function-param-node-p (node)
4672 "Return non-nil if NODE is a param node of a `js2-function-node'."
4673 (let ((parent (js2-node-parent node)))
4674 (and parent
4675 (js2-function-node-p parent)
4676 (memq node (js2-function-node-params parent)))))
4677
4678 (defsubst js2-mode-shift-kids (kids start offset)
4679 (dolist (kid kids)
4680 (if (> (js2-node-pos kid) start)
4681 (incf (js2-node-pos kid) offset))))
4682
4683 (defsubst js2-mode-shift-children (parent start offset)
4684 "Update start-positions of all children of PARENT beyond START."
4685 (let ((root (js2-node-root parent)))
4686 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4687 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4688
4689 (defsubst js2-node-is-descendant (node ancestor)
4690 "Return t if NODE is a descendant of ANCESTOR."
4691 (while (and node
4692 (not (eq node ancestor)))
4693 (setq node (js2-node-parent node)))
4694 node)
4695
4696 ;;; visitor infrastructure
4697
4698 (defun js2-visit-none (node callback)
4699 "Visitor for AST node that have no node children."
4700 nil)
4701
4702 (defun js2-print-none (node indent)
4703 "Visitor for AST node with no printed representation.")
4704
4705 (defun js2-print-body (node indent)
4706 "Print a statement, or a block without braces."
4707 (if (js2-block-node-p node)
4708 (dolist (kid (js2-block-node-kids node))
4709 (js2-print-ast kid indent))
4710 (js2-print-ast node indent)))
4711
4712 (defun js2-print-list (args &optional delimiter)
4713 (loop with len = (length args)
4714 for arg in args
4715 for count from 1
4716 do
4717 (js2-print-ast arg 0)
4718 (if (< count len)
4719 (insert (or delimiter ", ")))))
4720
4721 (defun js2-print-tree (ast)
4722 "Prints an AST to the current buffer.
4723 Makes `js2-ast-parent-nodes' available to the printer functions."
4724 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4725 (js2-print-ast ast)))
4726
4727 (defun js2-print-ast (node &optional indent)
4728 "Helper function for printing AST nodes.
4729 Requires `js2-ast-parent-nodes' to be non-nil.
4730 You should use `js2-print-tree' instead of this function."
4731 (let ((printer (get (aref node 0) 'js2-printer))
4732 (i (or indent 0))
4733 (pos (js2-node-abs-pos node)))
4734 ;; TODO: wedge comments in here somewhere
4735 (if printer
4736 (funcall printer node i))))
4737
4738 (defconst js2-side-effecting-tokens
4739 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4740 (dolist (tt (list js2-ASSIGN
4741 js2-ASSIGN_ADD
4742 js2-ASSIGN_BITAND
4743 js2-ASSIGN_BITOR
4744 js2-ASSIGN_BITXOR
4745 js2-ASSIGN_DIV
4746 js2-ASSIGN_LSH
4747 js2-ASSIGN_MOD
4748 js2-ASSIGN_MUL
4749 js2-ASSIGN_RSH
4750 js2-ASSIGN_SUB
4751 js2-ASSIGN_URSH
4752 js2-BLOCK
4753 js2-BREAK
4754 js2-CALL
4755 js2-CATCH
4756 js2-CATCH_SCOPE
4757 js2-CONST
4758 js2-CONTINUE
4759 js2-DEBUGGER
4760 js2-DEC
4761 js2-DELPROP
4762 js2-DEL_REF
4763 js2-DO
4764 js2-ELSE
4765 js2-EMPTY
4766 js2-ENTERWITH
4767 js2-EXPORT
4768 js2-EXPR_RESULT
4769 js2-FINALLY
4770 js2-FOR
4771 js2-FUNCTION
4772 js2-GOTO
4773 js2-IF
4774 js2-IFEQ
4775 js2-IFNE
4776 js2-IMPORT
4777 js2-INC
4778 js2-JSR
4779 js2-LABEL
4780 js2-LEAVEWITH
4781 js2-LET
4782 js2-LETEXPR
4783 js2-LOCAL_BLOCK
4784 js2-LOOP
4785 js2-NEW
4786 js2-REF_CALL
4787 js2-RETHROW
4788 js2-RETURN
4789 js2-RETURN_RESULT
4790 js2-SEMI
4791 js2-SETELEM
4792 js2-SETELEM_OP
4793 js2-SETNAME
4794 js2-SETPROP
4795 js2-SETPROP_OP
4796 js2-SETVAR
4797 js2-SET_REF
4798 js2-SET_REF_OP
4799 js2-SWITCH
4800 js2-TARGET
4801 js2-THROW
4802 js2-TRY
4803 js2-VAR
4804 js2-WHILE
4805 js2-WITH
4806 js2-WITHEXPR
4807 js2-YIELD))
4808 (aset tokens tt t))
4809 (if js2-instanceof-has-side-effects
4810 (aset tokens js2-INSTANCEOF t))
4811 tokens))
4812
4813 (defun js2-node-has-side-effects (node)
4814 "Return t if NODE has side effects."
4815 (when node ; makes it easier to handle malformed expressions
4816 (let ((tt (js2-node-type node)))
4817 (cond
4818 ;; This doubtless needs some work, since EXPR_VOID is used
4819 ;; in several ways in Rhino, and I may not have caught them all.
4820 ;; I'll wait for people to notice incorrect warnings.
4821 ((and (= tt js2-EXPR_VOID)
4822 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4823 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4824 ((= tt js2-COMMA)
4825 (js2-node-has-side-effects (js2-infix-node-right node)))
4826 ((or (= tt js2-AND)
4827 (= tt js2-OR))
4828 (or (js2-node-has-side-effects (js2-infix-node-right node))
4829 (js2-node-has-side-effects (js2-infix-node-left node))))
4830 ((= tt js2-HOOK)
4831 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4832 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4833 ((js2-paren-node-p node)
4834 (js2-node-has-side-effects (js2-paren-node-expr node)))
4835 ((= tt js2-ERROR) ; avoid cascaded error messages
4836 nil)
4837 (t
4838 (aref js2-side-effecting-tokens tt))))))
4839
4840 (defun js2-member-expr-leftmost-name (node)
4841 "For an expr such as foo.bar.baz, return leftmost node foo.
4842 NODE is any `js2-node' object. If it represents a member expression,
4843 which is any sequence of property gets, element-gets, function calls,
4844 or xml descendants/filter operators, then we look at the lexically
4845 leftmost (first) node in the chain. If it is a name-node we return it.
4846 Note that NODE can be a raw name-node and it will be returned as well.
4847 If NODE is not a name-node or member expression, or if it is a member
4848 expression whose leftmost target is not a name node, returns nil."
4849 (let ((continue t)
4850 result)
4851 (while (and continue (not result))
4852 (cond
4853 ((js2-name-node-p node)
4854 (setq result node))
4855 ((js2-prop-get-node-p node)
4856 (setq node (js2-prop-get-node-left node)))
4857 ;; TODO: handle call-nodes, xml-nodes, others?
4858 (t
4859 (setq continue nil))))
4860 result))
4861
4862 (defconst js2-stmt-node-types
4863 (list js2-BLOCK
4864 js2-BREAK
4865 js2-CONTINUE
4866 js2-DEFAULT ; e4x "default xml namespace" statement
4867 js2-DO
4868 js2-EXPR_RESULT
4869 js2-EXPR_VOID
4870 js2-FOR
4871 js2-IF
4872 js2-RETURN
4873 js2-SWITCH
4874 js2-THROW
4875 js2-TRY
4876 js2-WHILE
4877 js2-WITH)
4878 "Node types that only appear in statement contexts.
4879 The list does not include nodes that always appear as the child
4880 of another specific statement type, such as switch-cases,
4881 catch and finally blocks, and else-clauses. The list also excludes
4882 nodes like yield, let and var, which may appear in either expression
4883 or statement context, and in the latter context always have a
4884 `js2-expr-stmt-node' parent. Finally, the list does not include
4885 functions or scripts, which are treated separately from statements
4886 by the JavaScript parser and runtime.")
4887
4888 (defun js2-stmt-node-p (node)
4889 "Heuristic for figuring out if NODE is a statement.
4890 Some node types can appear in either an expression context or a
4891 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4892 For these node types in a statement context, the parent will be a
4893 `js2-expr-stmt-node'.
4894 Functions aren't included in the check."
4895 (memq (js2-node-type node) js2-stmt-node-types))
4896
4897 (defsubst js2-mode-find-first-stmt (node)
4898 "Search upward starting from NODE looking for a statement.
4899 For purposes of this function, a `js2-function-node' counts."
4900 (while (not (or (js2-stmt-node-p node)
4901 (js2-function-node-p node)))
4902 (setq node (js2-node-parent node)))
4903 node)
4904
4905 (defun js2-node-parent-stmt (node)
4906 "Return the node's first ancestor that is a statement.
4907 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4908 appearing in a statement context will have a parent that is a
4909 `js2-expr-stmt-node' that will be returned by this function."
4910 (let ((parent (js2-node-parent node)))
4911 (if (or (null parent)
4912 (js2-stmt-node-p parent)
4913 (and (js2-function-node-p parent)
4914 (not (eq (js2-function-node-form parent)
4915 'FUNCTION_EXPRESSION))))
4916 parent
4917 (js2-node-parent-stmt parent))))
4918
4919 ;; In the Mozilla Rhino sources, Roshan James writes:
4920 ;; Does consistent-return analysis on the function body when strict mode is
4921 ;; enabled.
4922 ;;
4923 ;; function (x) { return (x+1) }
4924 ;;
4925 ;; is ok, but
4926 ;;
4927 ;; function (x) { if (x < 0) return (x+1); }
4928 ;;
4929 ;; is not because the function can potentially return a value when the
4930 ;; condition is satisfied and if not, the function does not explicitly
4931 ;; return a value.
4932 ;;
4933 ;; This extends to checking mismatches such as "return" and "return <value>"
4934 ;; used in the same function. Warnings are not emitted if inconsistent
4935 ;; returns exist in code that can be statically shown to be unreachable.
4936 ;; Ex.
4937 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4938 ;;
4939 ;; emits no warning. However if the loop had a break statement, then a
4940 ;; warning would be emitted.
4941 ;;
4942 ;; The consistency analysis looks at control structures such as loops, ifs,
4943 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4944 ;; warns the user about an inconsistent set of termination possibilities.
4945 ;;
4946 ;; These flags enumerate the possible ways a statement/function can
4947 ;; terminate. These flags are used by endCheck() and by the Parser to
4948 ;; detect inconsistent return usage.
4949 ;;
4950 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4951 ;; able to execute (example: throw, continue)
4952 ;;
4953 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4954 ;; next one. Statement such as return dont. A compound statement may have
4955 ;; some branch that drops off control to the next statement.
4956 ;;
4957 ;; END_RETURNS indicates that the statement can return with no value.
4958 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4959 ;;
4960 ;; A compound statement such as
4961 ;; if (condition) {
4962 ;; return value;
4963 ;; }
4964 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4965
4966 (defconst js2-END_UNREACHED 0)
4967 (defconst js2-END_DROPS_OFF 1)
4968 (defconst js2-END_RETURNS 2)
4969 (defconst js2-END_RETURNS_VALUE 4)
4970 (defconst js2-END_YIELDS 8)
4971
4972 (defun js2-has-consistent-return-usage (node)
4973 "Check that every return usage in a function body is consistent.
4974 Returns t if the function satisfies strict mode requirement."
4975 (let ((n (js2-end-check node)))
4976 ;; either it doesn't return a value in any branch...
4977 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4978 ;; or it returns a value (or is unreached) at every branch
4979 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4980 js2-END_RETURNS
4981 js2-END_YIELDS)))))
4982
4983 (defun js2-end-check-if (node)
4984 "Returns in the then and else blocks must be consistent with each other.
4985 If there is no else block, then the return statement can fall through.
4986 Returns logical OR of END_* flags"
4987 (let ((th (js2-if-node-then-part node))
4988 (el (js2-if-node-else-part node)))
4989 (if (null th)
4990 js2-END_UNREACHED
4991 (logior (js2-end-check th) (if el
4992 (js2-end-check el)
4993 js2-END_DROPS_OFF)))))
4994
4995 (defun js2-end-check-switch (node)
4996 "Consistency of return statements is checked between the case statements.
4997 If there is no default, then the switch can fall through. If there is a
4998 default, we check to see if all code paths in the default return or if
4999 there is a code path that can fall through.
5000 Returns logical OR of END_* flags."
5001 (let ((rv js2-END_UNREACHED)
5002 default-case)
5003 ;; examine the cases
5004 (catch 'break
5005 (dolist (c (js2-switch-node-cases node))
5006 (if (js2-case-node-expr c)
5007 (js2-set-flag rv (js2-end-check-block c))
5008 (setq default-case c)
5009 (throw 'break nil))))
5010 ;; we don't care how the cases drop into each other
5011 (js2-clear-flag rv js2-END_DROPS_OFF)
5012 ;; examine the default
5013 (js2-set-flag rv (if default-case
5014 (js2-end-check default-case)
5015 js2-END_DROPS_OFF))
5016 rv))
5017
5018 (defun js2-end-check-try (node)
5019 "If the block has a finally, return consistency is checked in the
5020 finally block. If all code paths in the finally return, then the
5021 returns in the try-catch blocks don't matter. If there is a code path
5022 that does not return or if there is no finally block, the returns
5023 of the try and catch blocks are checked for mismatch.
5024 Returns logical OR of END_* flags."
5025 (let ((finally (js2-try-node-finally-block node))
5026 rv)
5027 ;; check the finally if it exists
5028 (setq rv (if finally
5029 (js2-end-check (js2-finally-node-body finally))
5030 js2-END_DROPS_OFF))
5031 ;; If the finally block always returns, then none of the returns
5032 ;; in the try or catch blocks matter.
5033 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5034 (js2-clear-flag rv js2-END_DROPS_OFF)
5035 ;; examine the try block
5036 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5037 ;; check each catch block
5038 (dolist (cb (js2-try-node-catch-clauses node))
5039 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5040 rv))
5041
5042 (defun js2-end-check-loop (node)
5043 "Return statement in the loop body must be consistent. The default
5044 assumption for any kind of a loop is that it will eventually terminate.
5045 The only exception is a loop with a constant true condition. Code that
5046 follows such a loop is examined only if one can statically determine
5047 that there is a break out of the loop.
5048
5049 for(... ; ... ; ...) {}
5050 for(... in ... ) {}
5051 while(...) { }
5052 do { } while(...)
5053
5054 Returns logical OR of END_* flags."
5055 (let ((rv (js2-end-check (js2-loop-node-body node)))
5056 (condition (cond
5057 ((js2-while-node-p node)
5058 (js2-while-node-condition node))
5059 ((js2-do-node-p node)
5060 (js2-do-node-condition node))
5061 ((js2-for-node-p node)
5062 (js2-for-node-condition node)))))
5063
5064 ;; check to see if the loop condition is always true
5065 (if (and condition
5066 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5067 (js2-clear-flag rv js2-END_DROPS_OFF))
5068
5069 ;; look for effect of breaks
5070 (js2-set-flag rv (js2-node-get-prop node
5071 'CONTROL_BLOCK_PROP
5072 js2-END_UNREACHED))
5073 rv))
5074
5075 (defun js2-end-check-block (node)
5076 "A general block of code is examined statement by statement.
5077 If any statement (even a compound one) returns in all branches, then
5078 subsequent statements are not examined.
5079 Returns logical OR of END_* flags."
5080 (let* ((rv js2-END_DROPS_OFF)
5081 (kids (js2-block-node-kids node))
5082 (n (car kids)))
5083 ;; Check each statment. If the statement can continue onto the next
5084 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5085 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5086 (js2-clear-flag rv js2-END_DROPS_OFF)
5087 (js2-set-flag rv (js2-end-check n))
5088 (setq kids (cdr kids)
5089 n (car kids)))
5090 rv))
5091
5092 (defun js2-end-check-label (node)
5093 "A labeled statement implies that there may be a break to the label.
5094 The function processes the labeled statement and then checks the
5095 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5096 particular label.
5097 Returns logical OR of END_* flags."
5098 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5099 (logior rv (js2-node-get-prop node
5100 'CONTROL_BLOCK_PROP
5101 js2-END_UNREACHED))))
5102
5103 (defun js2-end-check-break (node)
5104 "When a break is encountered annotate the statement being broken
5105 out of by setting its CONTROL_BLOCK_PROP property.
5106 Returns logical OR of END_* flags."
5107 (and (js2-break-node-target node)
5108 (js2-node-set-prop (js2-break-node-target node)
5109 'CONTROL_BLOCK_PROP
5110 js2-END_DROPS_OFF))
5111 js2-END_UNREACHED)
5112
5113 (defun js2-end-check (node)
5114 "Examine the body of a function, doing a basic reachability analysis.
5115 Returns a combination of flags END_* flags that indicate
5116 how the function execution can terminate. These constitute only the
5117 pessimistic set of termination conditions. It is possible that at
5118 runtime certain code paths will never be actually taken. Hence this
5119 analysis will flag errors in cases where there may not be errors.
5120 Returns logical OR of END_* flags"
5121 (let (kid)
5122 (cond
5123 ((js2-break-node-p node)
5124 (js2-end-check-break node))
5125 ((js2-expr-stmt-node-p node)
5126 (if (setq kid (js2-expr-stmt-node-expr node))
5127 (js2-end-check kid)
5128 js2-END_DROPS_OFF))
5129 ((or (js2-continue-node-p node)
5130 (js2-throw-node-p node))
5131 js2-END_UNREACHED)
5132 ((js2-return-node-p node)
5133 (if (setq kid (js2-return-node-retval node))
5134 js2-END_RETURNS_VALUE
5135 js2-END_RETURNS))
5136 ((js2-loop-node-p node)
5137 (js2-end-check-loop node))
5138 ((js2-switch-node-p node)
5139 (js2-end-check-switch node))
5140 ((js2-labeled-stmt-node-p node)
5141 (js2-end-check-label node))
5142 ((js2-if-node-p node)
5143 (js2-end-check-if node))
5144 ((js2-try-node-p node)
5145 (js2-end-check-try node))
5146 ((js2-block-node-p node)
5147 (if (null (js2-block-node-kids node))
5148 js2-END_DROPS_OFF
5149 (js2-end-check-block node)))
5150 ((js2-yield-node-p node)
5151 js2-END_YIELDS)
5152 (t
5153 js2-END_DROPS_OFF))))
5154
5155 (defun js2-always-defined-boolean-p (node)
5156 "Check if NODE always evaluates to true or false in boolean context.
5157 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5158 nor always false."
5159 (let ((tt (js2-node-type node))
5160 num)
5161 (cond
5162 ((or (= tt js2-FALSE) (= tt js2-NULL))
5163 'ALWAYS_FALSE)
5164 ((= tt js2-TRUE)
5165 'ALWAYS_TRUE)
5166 ((= tt js2-NUMBER)
5167 (setq num (js2-number-node-num-value node))
5168 (if (and (not (eq num 0.0e+NaN))
5169 (not (zerop num)))
5170 'ALWAYS_TRUE
5171 'ALWAYS_FALSE))
5172 (t
5173 nil))))
5174
5175 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5176 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5177
5178 (defvar js2-tokens nil
5179 "List of all defined token names.") ; initialized in `js2-token-names'
5180
5181 (defconst js2-token-names
5182 (let* ((names (make-vector js2-num-tokens -1))
5183 (case-fold-search nil) ; only match js2-UPPER_CASE
5184 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5185 (loop for sym in syms
5186 for i from 0
5187 do
5188 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5189 (not (boundp sym)))
5190 (aset names (symbol-value sym) ; code, e.g. 152
5191 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5192 (push sym js2-tokens)))
5193 names)
5194 "Vector mapping int values to token string names, sans `js2-' prefix.")
5195
5196 (defun js2-token-name (tok)
5197 "Return a string name for TOK, a token symbol or code.
5198 Signals an error if it's not a recognized token."
5199 (let ((code tok))
5200 (if (symbolp tok)
5201 (setq code (symbol-value tok)))
5202 (if (eq code -1)
5203 "ERROR"
5204 (if (and (numberp code)
5205 (not (minusp code))
5206 (< code js2-num-tokens))
5207 (aref js2-token-names code)
5208 (error "Invalid token: %s" code)))))
5209
5210 (defsubst js2-token-sym (tok)
5211 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5212 (intern (js2-token-name tok)))
5213
5214 (defconst js2-token-codes
5215 (let ((table (make-hash-table :test 'eq :size 256)))
5216 (loop for name across js2-token-names
5217 for sym = (intern (concat "js2-" name))
5218 do
5219 (puthash sym (symbol-value sym) table))
5220 ;; clean up a few that are "wrong" in Rhino's token codes
5221 (puthash 'js2-DELETE js2-DELPROP table)
5222 table)
5223 "Hashtable mapping token symbols to their bytecodes.")
5224
5225 (defsubst js2-token-code (sym)
5226 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5227 (or (gethash sym js2-token-codes)
5228 (error "Invalid token symbol: %s " sym))) ; signal code bug
5229
5230 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5231 (setq js2-token-end js2-ts-cursor)
5232 (js2-report-error msg nil
5233 (or beg js2-token-beg)
5234 (or len (- js2-token-end js2-token-beg)))
5235 (unless no-throw
5236 (throw 'return js2-ERROR)))
5237
5238 (defsubst js2-get-string-from-buffer ()
5239 "Reverse the char accumulator and return it as a string."
5240 (setq js2-token-end js2-ts-cursor)
5241 (if js2-ts-string-buffer
5242 (apply #'string (nreverse js2-ts-string-buffer))
5243 ""))
5244
5245 ;; TODO: could potentially avoid a lot of consing by allocating a
5246 ;; char buffer the way Rhino does.
5247 (defsubst js2-add-to-string (c)
5248 (push c js2-ts-string-buffer))
5249
5250 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5251 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5252 ;; any other character: when it's not part of the current token, we
5253 ;; unget it, allowing it to be read again by the following call.
5254 (defsubst js2-unget-char ()
5255 (decf js2-ts-cursor))
5256
5257 ;; Rhino distinguishes \r and \n line endings. We don't need to
5258 ;; because we only scan from Emacs buffers, which always use \n.
5259 (defsubst js2-get-char ()
5260 "Read and return the next character from the input buffer.
5261 Increments `js2-ts-lineno' if the return value is a newline char.
5262 Updates `js2-ts-cursor' to the point after the returned char.
5263 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5264 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5265 (let (c)
5266 ;; check for end of buffer
5267 (if (>= js2-ts-cursor (point-max))
5268 (setq js2-ts-hit-eof t
5269 js2-ts-cursor (1+ js2-ts-cursor)
5270 c js2-EOF_CHAR) ; return value
5271 ;; otherwise read next char
5272 (setq c (char-before (incf js2-ts-cursor)))
5273 ;; if we read a newline, update counters
5274 (if (= c ?\n)
5275 (setq js2-ts-line-start js2-ts-cursor
5276 js2-ts-lineno (1+ js2-ts-lineno)))
5277 ;; TODO: skip over format characters
5278 c)))
5279
5280 (defsubst js2-read-unicode-escape ()
5281 "Read a \\uNNNN sequence from the input.
5282 Assumes the ?\ and ?u have already been read.
5283 Returns the unicode character, or nil if it wasn't a valid character.
5284 Doesn't change the values of any scanner variables."
5285 ;; I really wish I knew a better way to do this, but I can't
5286 ;; find the Emacs function that takes a 16-bit int and converts
5287 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5288 ;; Have to first check that it's 4 hex characters or it may stop
5289 ;; the read early.
5290 (ignore-errors
5291 (let ((s (buffer-substring-no-properties js2-ts-cursor
5292 (+ 4 js2-ts-cursor))))
5293 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5294 (read (concat "?\\u" s))))))
5295
5296 (defsubst js2-match-char (test)
5297 "Consume and return next character if it matches TEST, a character.
5298 Returns nil and consumes nothing if TEST is not the next character."
5299 (let ((c (js2-get-char)))
5300 (if (eq c test)
5301 t
5302 (js2-unget-char)
5303 nil)))
5304
5305 (defsubst js2-peek-char ()
5306 (prog1
5307 (js2-get-char)
5308 (js2-unget-char)))
5309
5310 (defsubst js2-java-identifier-start-p (c)
5311 (or
5312 (memq c '(?$ ?_))
5313 (js2-char-uppercase-p c)
5314 (js2-char-lowercase-p c)))
5315
5316 (defsubst js2-java-identifier-part-p (c)
5317 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5318 ;; TODO: make me Unicode-friendly. See comments above.
5319 (or
5320 (memq c '(?$ ?_))
5321 (js2-char-uppercase-p c)
5322 (js2-char-lowercase-p c)
5323 (and (>= c ?0) (<= c ?9))))
5324
5325 (defsubst js2-alpha-p (c)
5326 (cond ((and (<= ?A c) (<= c ?Z)) t)
5327 ((and (<= ?a c) (<= c ?z)) t)
5328 (t nil)))
5329
5330 (defsubst js2-digit-p (c)
5331 (and (<= ?0 c) (<= c ?9)))
5332
5333 (defsubst js2-js-space-p (c)
5334 (if (<= c 127)
5335 (memq c '(#x20 #x9 #xB #xC #xD))
5336 (or
5337 (eq c #xA0)
5338 ;; TODO: change this nil to check for Unicode space character
5339 nil)))
5340
5341 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5342
5343 (defsubst js2-skip-line ()
5344 "Skip to end of line"
5345 (let (c)
5346 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5347 (js2-unget-char)
5348 (setq js2-token-end js2-ts-cursor)))
5349
5350 (defun js2-init-scanner (&optional buf line)
5351 "Create token stream for BUF starting on LINE.
5352 BUF defaults to current-buffer and line defaults to 1.
5353
5354 A buffer can only have one scanner active at a time, which yields
5355 dramatically simpler code than using a defstruct. If you need to
5356 have simultaneous scanners in a buffer, copy the regions to scan
5357 into temp buffers."
5358 (save-excursion
5359 (when buf
5360 (set-buffer buf))
5361 (setq js2-ts-dirty-line nil
5362 js2-ts-regexp-flags nil
5363 js2-ts-string ""
5364 js2-ts-number nil
5365 js2-ts-hit-eof nil
5366 js2-ts-line-start 0
5367 js2-ts-lineno (or line 1)
5368 js2-ts-line-end-char -1
5369 js2-ts-cursor (point-min)
5370 js2-ts-is-xml-attribute nil
5371 js2-ts-xml-is-tag-content nil
5372 js2-ts-xml-open-tags-count 0
5373 js2-ts-string-buffer nil)))
5374
5375 ;; This function uses the cached op, string and number fields in
5376 ;; TokenStream; if getToken has been called since the passed token
5377 ;; was scanned, the op or string printed may be incorrect.
5378 (defun js2-token-to-string (token)
5379 ;; Not sure where this function is used in Rhino. Not tested.
5380 (if (not js2-debug-print-trees)
5381 ""
5382 (let ((name (js2-token-name token)))
5383 (cond
5384 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5385 (concat name " `" js2-ts-string "'"))
5386 ((eq token js2-NUMBER)
5387 (format "NUMBER %g" js2-ts-number))
5388 (t
5389 name)))))
5390
5391 (defconst js2-keywords
5392 '(break
5393 case catch const continue
5394 debugger default delete do
5395 else enum
5396 false finally for function
5397 if in instanceof import
5398 let
5399 new null
5400 return
5401 switch
5402 this throw true try typeof
5403 var void
5404 while with
5405 yield))
5406
5407 ;; Token names aren't exactly the same as the keywords, unfortunately.
5408 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5409 (defconst js2-kwd-tokens
5410 (let ((table (make-vector js2-num-tokens nil))
5411 (tokens
5412 (list js2-BREAK
5413 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5414 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5415 js2-ELSE
5416 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5417 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5418 js2-LET
5419 js2-NEW js2-NULL
5420 js2-RETURN
5421 js2-SWITCH
5422 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5423 js2-VAR
5424 js2-WHILE js2-WITH
5425 js2-YIELD)))
5426 (dolist (i tokens)
5427 (aset table i 'font-lock-keyword-face))
5428 (aset table js2-STRING 'font-lock-string-face)
5429 (aset table js2-REGEXP 'font-lock-string-face)
5430 (aset table js2-COMMENT 'font-lock-comment-face)
5431 (aset table js2-THIS 'font-lock-builtin-face)
5432 (aset table js2-VOID 'font-lock-constant-face)
5433 (aset table js2-NULL 'font-lock-constant-face)
5434 (aset table js2-TRUE 'font-lock-constant-face)
5435 (aset table js2-FALSE 'font-lock-constant-face)
5436 table)
5437 "Vector whose values are non-nil for tokens that are keywords.
5438 The values are default faces to use for highlighting the keywords.")
5439
5440 (defconst js2-reserved-words
5441 '(abstract
5442 boolean byte
5443 char class
5444 double
5445 enum export extends
5446 final float
5447 goto
5448 implements import int interface
5449 long
5450 native
5451 package private protected public
5452 short static super synchronized
5453 throws transient
5454 volatile))
5455
5456 (defconst js2-keyword-names
5457 (let ((table (make-hash-table :test 'equal)))
5458 (loop for k in js2-keywords
5459 do (puthash
5460 (symbol-name k) ; instanceof
5461 (intern (concat "js2-"
5462 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5463 table))
5464 table)
5465 "JavaScript keywords by name, mapped to their symbols.")
5466
5467 (defconst js2-reserved-word-names
5468 (let ((table (make-hash-table :test 'equal)))
5469 (loop for k in js2-reserved-words
5470 do
5471 (puthash (symbol-name k) 'js2-RESERVED table))
5472 table)
5473 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5474
5475 (defsubst js2-collect-string (buf)
5476 "Convert BUF, a list of chars, to a string.
5477 Reverses BUF before converting."
5478 (cond
5479 ((stringp buf)
5480 buf)
5481 ((null buf) ; for emacs21 compat
5482 "")
5483 (t
5484 (if buf
5485 (apply #'string (nreverse buf))
5486 ""))))
5487
5488 (defun js2-string-to-keyword (s)
5489 "Return token for S, a string, if S is a keyword or reserved word.
5490 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5491 (or (gethash s js2-keyword-names)
5492 (gethash s js2-reserved-word-names)))
5493
5494 (defsubst js2-ts-set-char-token-bounds ()
5495 "Used when next token is one character."
5496 (setq js2-token-beg (1- js2-ts-cursor)
5497 js2-token-end js2-ts-cursor))
5498
5499 (defsubst js2-ts-return (token)
5500 "Return an N-character TOKEN from `js2-get-token'.
5501 Updates `js2-token-end' accordingly."
5502 (setq js2-token-end js2-ts-cursor)
5503 (throw 'return token))
5504
5505 (defsubst js2-x-digit-to-int (c accumulator)
5506 "Build up a hex number.
5507 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5508 corresponding number. Otherwise return -1."
5509 (catch 'return
5510 (catch 'check
5511 ;; Use 0..9 < A..Z < a..z
5512 (cond
5513 ((<= c ?9)
5514 (decf c ?0)
5515 (if (<= 0 c)
5516 (throw 'check nil)))
5517 ((<= c ?F)
5518 (when (<= ?A c)
5519 (decf c (- ?A 10))
5520 (throw 'check nil)))
5521 ((<= c ?f)
5522 (when (<= ?a c)
5523 (decf c (- ?a 10))
5524 (throw 'check nil))))
5525 (throw 'return -1))
5526 (logior c (lsh accumulator 4))))
5527
5528 (defun js2-get-token ()
5529 "Return next JavaScript token, an int such as js2-RETURN."
5530 (let (c
5531 c1
5532 identifier-start
5533 is-unicode-escape-start
5534 contains-escape
5535 escape-val
5536 escape-start
5537 str
5538 result
5539 base
5540 is-integer
5541 quote-char
5542 val
5543 look-for-slash
5544 continue)
5545 (catch 'return
5546 (while t
5547 ;; Eat whitespace, possibly sensitive to newlines.
5548 (setq continue t)
5549 (while continue
5550 (setq c (js2-get-char))
5551 (cond
5552 ((eq c js2-EOF_CHAR)
5553 (js2-ts-set-char-token-bounds)
5554 (throw 'return js2-EOF))
5555 ((eq c ?\n)
5556 (js2-ts-set-char-token-bounds)
5557 (setq js2-ts-dirty-line nil)
5558 (throw 'return js2-EOL))
5559 ((not (js2-js-space-p c))
5560 (if (/= c ?-) ; in case end of HTML comment
5561 (setq js2-ts-dirty-line t))
5562 (setq continue nil))))
5563 ;; Assume the token will be 1 char - fixed up below.
5564 (js2-ts-set-char-token-bounds)
5565 (when (eq c ?@)
5566 (throw 'return js2-XMLATTR))
5567 ;; identifier/keyword/instanceof?
5568 ;; watch out for starting with a <backslash>
5569 (cond
5570 ((eq c ?\\)
5571 (setq c (js2-get-char))
5572 (if (eq c ?u)
5573 (setq identifier-start t
5574 is-unicode-escape-start t
5575 js2-ts-string-buffer nil)
5576 (setq identifier-start nil)
5577 (js2-unget-char)
5578 (setq c ?\\)))
5579 (t
5580 (when (setq identifier-start (js2-java-identifier-start-p c))
5581 (setq js2-ts-string-buffer nil)
5582 (js2-add-to-string c))))
5583 (when identifier-start
5584 (setq contains-escape is-unicode-escape-start)
5585 (catch 'break
5586 (while t
5587 (if is-unicode-escape-start
5588 ;; strictly speaking we should probably push-back
5589 ;; all the bad characters if the <backslash>uXXXX
5590 ;; sequence is malformed. But since there isn't a
5591 ;; correct context(is there?) for a bad Unicode
5592 ;; escape sequence in an identifier, we can report
5593 ;; an error here.
5594 (progn
5595 (setq escape-val 0)
5596 (dotimes (i 4)
5597 (setq c (js2-get-char)
5598 escape-val (js2-x-digit-to-int c escape-val))
5599 ;; Next check takes care of c < 0 and bad escape
5600 (if (minusp escape-val)
5601 (throw 'break nil)))
5602 (if (minusp escape-val)
5603 (js2-report-scan-error "msg.invalid.escape" t))
5604 (js2-add-to-string escape-val)
5605 (setq is-unicode-escape-start nil))
5606 (setq c (js2-get-char))
5607 (cond
5608 ((eq c ?\\)
5609 (setq c (js2-get-char))
5610 (if (eq c ?u)
5611 (setq is-unicode-escape-start t
5612 contains-escape t)
5613 (js2-report-scan-error "msg.illegal.character" t)))
5614 (t
5615 (if (or (eq c js2-EOF_CHAR)
5616 (not (js2-java-identifier-part-p c)))
5617 (throw 'break nil))
5618 (js2-add-to-string c))))))
5619 (js2-unget-char)
5620 (setq str (js2-get-string-from-buffer))
5621 (unless contains-escape
5622 ;; OPT we shouldn't have to make a string (object!) to
5623 ;; check if it's a keyword.
5624 ;; Return the corresponding token if it's a keyword
5625 (when (setq result (js2-string-to-keyword str))
5626 (if (and (< js2-language-version 170)
5627 (memq result '(js2-LET js2-YIELD)))
5628 ;; LET and YIELD are tokens only in 1.7 and later
5629 (setq result 'js2-NAME))
5630 (if (not (eq result 'js2-RESERVED))
5631 (throw 'return (js2-token-code result)))
5632 (js2-report-warning "msg.reserved.keyword" str)))
5633 ;; If we want to intern these as Rhino does, just use (intern str)
5634 (setq js2-ts-string str)
5635 (throw 'return js2-NAME)) ; end identifier/kwd check
5636 ;; is it a number?
5637 (when (or (js2-digit-p c)
5638 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5639 (setq js2-ts-string-buffer nil
5640 base 10)
5641 (when (eq c ?0)
5642 (setq c (js2-get-char))
5643 (cond
5644 ((or (eq c ?x) (eq c ?X))
5645 (setq base 16)
5646 (setq c (js2-get-char)))
5647 ((js2-digit-p c)
5648 (setq base 8))
5649 (t
5650 (js2-add-to-string ?0))))
5651 (if (eq base 16)
5652 (while (<= 0 (js2-x-digit-to-int c 0))
5653 (js2-add-to-string c)
5654 (setq c (js2-get-char)))
5655 (while (and (<= ?0 c) (<= c ?9))
5656 ;; We permit 08 and 09 as decimal numbers, which
5657 ;; makes our behavior a superset of the ECMA
5658 ;; numeric grammar. We might not always be so
5659 ;; permissive, so we warn about it.
5660 (when (and (eq base 8) (>= c ?8))
5661 (js2-report-warning "msg.bad.octal.literal"
5662 (if (eq c ?8) "8" "9"))
5663 (setq base 10))
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))))
5666 (setq is-integer t)
5667 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5668 (setq is-integer nil)
5669 (when (eq c ?.)
5670 (loop do
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char))
5673 while (js2-digit-p c)))
5674 (when (memq c '(?e ?E))
5675 (js2-add-to-string c)
5676 (setq c (js2-get-char))
5677 (when (memq c '(?+ ?-))
5678 (js2-add-to-string c)
5679 (setq c (js2-get-char)))
5680 (unless (js2-digit-p c)
5681 (js2-report-scan-error "msg.missing.exponent" t))
5682 (loop do
5683 (js2-add-to-string c)
5684 (setq c (js2-get-char))
5685 while (js2-digit-p c))))
5686 (js2-unget-char)
5687 (setq js2-ts-string (js2-get-string-from-buffer)
5688 js2-ts-number
5689 (if (and (eq base 10) (not is-integer))
5690 (string-to-number js2-ts-string)
5691 ;; TODO: call runtime number-parser. Some of it is in
5692 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5693 (string-to-number js2-ts-string)))
5694 (throw 'return js2-NUMBER))
5695 ;; is it a string?
5696 (when (memq c '(?\" ?\'))
5697 ;; We attempt to accumulate a string the fast way, by
5698 ;; building it directly out of the reader. But if there
5699 ;; are any escaped characters in the string, we revert to
5700 ;; building it out of a string buffer.
5701 (setq quote-char c
5702 js2-ts-string-buffer nil
5703 c (js2-get-char))
5704 (catch 'break
5705 (while (/= c quote-char)
5706 (catch 'continue
5707 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5708 (js2-unget-char)
5709 (setq js2-token-end js2-ts-cursor)
5710 (js2-report-error "msg.unterminated.string.lit")
5711 (throw 'return js2-STRING))
5712 (when (eq c ?\\)
5713 ;; We've hit an escaped character
5714 (setq c (js2-get-char))
5715 (case c
5716 (?b (setq c ?\b))
5717 (?f (setq c ?\f))
5718 (?n (setq c ?\n))
5719 (?r (setq c ?\r))
5720 (?t (setq c ?\t))
5721 (?v (setq c ?\v))
5722 (?u
5723 (setq c1 (js2-read-unicode-escape))
5724 (if js2-parse-ide-mode
5725 (if c1
5726 (progn
5727 ;; just copy the string in IDE-mode
5728 (js2-add-to-string ?\\)
5729 (js2-add-to-string ?u)
5730 (dotimes (i 3)
5731 (js2-add-to-string (js2-get-char)))
5732 (setq c (js2-get-char))) ; added at end of loop
5733 ;; flag it as an invalid escape
5734 (js2-report-warning "msg.invalid.escape"
5735 nil (- js2-ts-cursor 2) 6))
5736 ;; Get 4 hex digits; if the u escape is not
5737 ;; followed by 4 hex digits, use 'u' + the
5738 ;; literal character sequence that follows.
5739 (js2-add-to-string ?u)
5740 (setq escape-val 0)
5741 (dotimes (i 4)
5742 (setq c (js2-get-char)
5743 escape-val (js2-x-digit-to-int c escape-val))
5744 (if (minusp escape-val)
5745 (throw 'continue nil))
5746 (js2-add-to-string c))
5747 ;; prepare for replace of stored 'u' sequence by escape value
5748 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5749 c escape-val)))
5750 (?x
5751 ;; Get 2 hex digits, defaulting to 'x'+literal
5752 ;; sequence, as above.
5753 (setq c (js2-get-char)
5754 escape-val (js2-x-digit-to-int c 0))
5755 (if (minusp escape-val)
5756 (progn
5757 (js2-add-to-string ?x)
5758 (throw 'continue nil))
5759 (setq c1 c
5760 c (js2-get-char)
5761 escape-val (js2-x-digit-to-int c escape-val))
5762 (if (minusp escape-val)
5763 (progn
5764 (js2-add-to-string ?x)
5765 (js2-add-to-string c1)
5766 (throw 'continue nil))
5767 ;; got 2 hex digits
5768 (setq c escape-val))))
5769 (?\n
5770 ;; Remove line terminator after escape to follow
5771 ;; SpiderMonkey and C/C++
5772 (setq c (js2-get-char))
5773 (throw 'continue nil))
5774 (t
5775 (when (and (<= ?0 c) (< c ?8))
5776 (setq val (- c ?0)
5777 c (js2-get-char))
5778 (when (and (<= ?0 c) (< c ?8))
5779 (setq val (- (+ (* 8 val) c) ?0)
5780 c (js2-get-char))
5781 (when (and (<= ?0 c)
5782 (< c ?8)
5783 (< val #o37))
5784 ;; c is 3rd char of octal sequence only
5785 ;; if the resulting val <= 0377
5786 (setq val (- (+ (* 8 val) c) ?0)
5787 c (js2-get-char))))
5788 (js2-unget-char)
5789 (setq c val)))))
5790 (js2-add-to-string c)
5791 (setq c (js2-get-char)))))
5792 (setq js2-ts-string (js2-get-string-from-buffer))
5793 (throw 'return js2-STRING))
5794 (case c
5795 (?\;
5796 (throw 'return js2-SEMI))
5797 (?\[
5798 (throw 'return js2-LB))
5799 (?\]
5800 (throw 'return js2-RB))
5801 (?{
5802 (throw 'return js2-LC))
5803 (?}
5804 (throw 'return js2-RC))
5805 (?\(
5806 (throw 'return js2-LP))
5807 (?\)
5808 (throw 'return js2-RP))
5809 (?,
5810 (throw 'return js2-COMMA))
5811 (??
5812 (throw 'return js2-HOOK))
5813 (?:
5814 (if (js2-match-char ?:)
5815 (js2-ts-return js2-COLONCOLON)
5816 (throw 'return js2-COLON)))
5817 (?.
5818 (if (js2-match-char ?.)
5819 (js2-ts-return js2-DOTDOT)
5820 (if (js2-match-char ?\()
5821 (js2-ts-return js2-DOTQUERY)
5822 (throw 'return js2-DOT))))
5823 (?|
5824 (if (js2-match-char ?|)
5825 (throw 'return js2-OR)
5826 (if (js2-match-char ?=)
5827 (js2-ts-return js2-ASSIGN_BITOR)
5828 (throw 'return js2-BITOR))))
5829 (?^
5830 (if (js2-match-char ?=)
5831 (js2-ts-return js2-ASSIGN_BITOR)
5832 (throw 'return js2-BITXOR)))
5833 (?&
5834 (if (js2-match-char ?&)
5835 (throw 'return js2-AND)
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-ASSIGN_BITAND)
5838 (throw 'return js2-BITAND))))
5839 (?=
5840 (if (js2-match-char ?=)
5841 (if (js2-match-char ?=)
5842 (js2-ts-return js2-SHEQ)
5843 (throw 'return js2-EQ))
5844 (throw 'return js2-ASSIGN)))
5845 (?!
5846 (if (js2-match-char ?=)
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-SHNE)
5849 (js2-ts-return js2-NE))
5850 (throw 'return js2-NOT)))
5851 (?<
5852 ;; NB:treat HTML begin-comment as comment-till-eol
5853 (when (js2-match-char ?!)
5854 (when (js2-match-char ?-)
5855 (when (js2-match-char ?-)
5856 (js2-skip-line)
5857 (setq js2-ts-comment-type 'html)
5858 (throw 'return js2-COMMENT)))
5859 (js2-unget-char))
5860 (if (js2-match-char ?<)
5861 (if (js2-match-char ?=)
5862 (js2-ts-return js2-ASSIGN_LSH)
5863 (js2-ts-return js2-LSH))
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-LE)
5866 (throw 'return js2-LT))))
5867 (?>
5868 (if (js2-match-char ?>)
5869 (if (js2-match-char ?>)
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-ASSIGN_URSH)
5872 (js2-ts-return js2-URSH))
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_RSH)
5875 (js2-ts-return js2-RSH)))
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-GE)
5878 (throw 'return js2-GT))))
5879 (?*
5880 (if (js2-match-char ?=)
5881 (js2-ts-return js2-ASSIGN_MUL)
5882 (throw 'return js2-MUL)))
5883 (?/
5884 ;; is it a // comment?
5885 (when (js2-match-char ?/)
5886 (setq js2-token-beg (- js2-ts-cursor 2))
5887 (js2-skip-line)
5888 (setq js2-ts-comment-type 'line)
5889 ;; include newline so highlighting goes to end of window
5890 (incf js2-token-end)
5891 (throw 'return js2-COMMENT))
5892 ;; is it a /* comment?
5893 (when (js2-match-char ?*)
5894 (setq look-for-slash nil
5895 js2-token-beg (- js2-ts-cursor 2)
5896 js2-ts-comment-type
5897 (if (js2-match-char ?*)
5898 (progn
5899 (setq look-for-slash t)
5900 'jsdoc)
5901 'block))
5902 (while t
5903 (setq c (js2-get-char))
5904 (cond
5905 ((eq c js2-EOF_CHAR)
5906 (setq js2-token-end (1- js2-ts-cursor))
5907 (js2-report-error "msg.unterminated.comment")
5908 (throw 'return js2-COMMENT))
5909 ((eq c ?*)
5910 (setq look-for-slash t))
5911 ((eq c ?/)
5912 (if look-for-slash
5913 (js2-ts-return js2-COMMENT)))
5914 (t
5915 (setq look-for-slash nil
5916 js2-token-end js2-ts-cursor)))))
5917 (if (js2-match-char ?=)
5918 (js2-ts-return js2-ASSIGN_DIV)
5919 (throw 'return js2-DIV)))
5920 (?#
5921 (when js2-skip-preprocessor-directives
5922 (js2-skip-line)
5923 (setq js2-ts-comment-type 'preprocessor
5924 js2-token-end js2-ts-cursor)
5925 (throw 'return js2-COMMENT))
5926 (throw 'return js2-ERROR))
5927 (?%
5928 (if (js2-match-char ?=)
5929 (js2-ts-return js2-ASSIGN_MOD)
5930 (throw 'return js2-MOD)))
5931 (?~
5932 (throw 'return js2-BITNOT))
5933 (?+
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_ADD)
5936 (if (js2-match-char ?+)
5937 (js2-ts-return js2-INC)
5938 (throw 'return js2-ADD))))
5939 (?-
5940 (cond
5941 ((js2-match-char ?=)
5942 (setq c js2-ASSIGN_SUB))
5943 ((js2-match-char ?-)
5944 (unless js2-ts-dirty-line
5945 ;; treat HTML end-comment after possible whitespace
5946 ;; after line start as comment-until-eol
5947 (when (js2-match-char ?>)
5948 (js2-skip-line)
5949 (setq js2-ts-comment-type 'html)
5950 (throw 'return js2-COMMENT)))
5951 (setq c js2-DEC))
5952 (t
5953 (setq c js2-SUB)))
5954 (setq js2-ts-dirty-line t)
5955 (js2-ts-return c))
5956 (otherwise
5957 (js2-report-scan-error "msg.illegal.character")))))))
5958
5959 (defun js2-read-regexp (start-token)
5960 "Called by parser when it gets / or /= in literal context."
5961 (let (c
5962 err
5963 in-class ; inside a '[' .. ']' character-class
5964 flags
5965 (continue t))
5966 (setq js2-token-beg js2-ts-cursor
5967 js2-ts-string-buffer nil
5968 js2-ts-regexp-flags nil)
5969 (if (eq start-token js2-ASSIGN_DIV)
5970 ;; mis-scanned /=
5971 (js2-add-to-string ?=)
5972 (if (not (eq start-token js2-DIV))
5973 (error "failed assertion")))
5974 (while (and (not err)
5975 (or (/= (setq c (js2-get-char)) ?/)
5976 in-class))
5977 (cond
5978 ((or (= c ?\n)
5979 (= c js2-EOF_CHAR))
5980 (setq js2-token-end (1- js2-ts-cursor)
5981 err t
5982 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5983 (js2-report-error "msg.unterminated.re.lit"))
5984 (t (cond
5985 ((= c ?\\)
5986 (js2-add-to-string c)
5987 (setq c (js2-get-char)))
5988 ((= c ?\[)
5989 (setq in-class t))
5990 ((= c ?\])
5991 (setq in-class nil)))
5992 (js2-add-to-string c))))
5993 (unless err
5994 (while continue
5995 (cond
5996 ((js2-match-char ?g)
5997 (push ?g flags))
5998 ((js2-match-char ?i)
5999 (push ?i flags))
6000 ((js2-match-char ?m)
6001 (push ?m flags))
6002 (t
6003 (setq continue nil))))
6004 (if (js2-alpha-p (js2-peek-char))
6005 (js2-report-scan-error "msg.invalid.re.flag" t
6006 js2-ts-cursor 1))
6007 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6008 js2-ts-regexp-flags (js2-collect-string flags)
6009 js2-token-end js2-ts-cursor)
6010 ;; tell `parse-partial-sexp' to ignore this range of chars
6011 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6012
6013 (defun js2-get-first-xml-token ()
6014 (setq js2-ts-xml-open-tags-count 0
6015 js2-ts-is-xml-attribute nil
6016 js2-ts-xml-is-tag-content nil)
6017 (js2-unget-char)
6018 (js2-get-next-xml-token))
6019
6020 (defsubst js2-xml-discard-string ()
6021 "Throw away the string in progress and flag an XML parse error."
6022 (setq js2-ts-string-buffer nil
6023 js2-ts-string nil)
6024 (js2-report-scan-error "msg.XML.bad.form" t))
6025
6026 (defun js2-get-next-xml-token ()
6027 (setq js2-ts-string-buffer nil ; for recording the XML
6028 js2-token-beg js2-ts-cursor)
6029 (let (c result)
6030 (setq result
6031 (catch 'return
6032 (while t
6033 (setq c (js2-get-char))
6034 (cond
6035 ((= c js2-EOF_CHAR)
6036 (throw 'return js2-ERROR))
6037 (js2-ts-xml-is-tag-content
6038 (case c
6039 (?>
6040 (js2-add-to-string c)
6041 (setq js2-ts-xml-is-tag-content nil
6042 js2-ts-is-xml-attribute nil))
6043 (?/
6044 (js2-add-to-string c)
6045 (when (eq ?> (js2-peek-char))
6046 (setq c (js2-get-char))
6047 (js2-add-to-string c)
6048 (setq js2-ts-xml-is-tag-content nil)
6049 (decf js2-ts-xml-open-tags-count)))
6050 (?{
6051 (js2-unget-char)
6052 (setq js2-ts-string (js2-get-string-from-buffer))
6053 (throw 'return js2-XML))
6054 ((?\' ?\")
6055 (js2-add-to-string c)
6056 (unless (js2-read-quoted-string c)
6057 (throw 'return js2-ERROR)))
6058 (?=
6059 (js2-add-to-string c)
6060 (setq js2-ts-is-xml-attribute t))
6061 ((? ?\t ?\r ?\n)
6062 (js2-add-to-string c))
6063 (t
6064 (js2-add-to-string c)
6065 (setq js2-ts-is-xml-attribute nil)))
6066 (when (and (not js2-ts-xml-is-tag-content)
6067 (zerop js2-ts-xml-open-tags-count))
6068 (setq js2-ts-string (js2-get-string-from-buffer))
6069 (throw 'return js2-XMLEND)))
6070 (t
6071 ;; else not tag content
6072 (case c
6073 (?<
6074 (js2-add-to-string c)
6075 (setq c (js2-peek-char))
6076 (case c
6077 (?!
6078 (setq c (js2-get-char)) ;; skip !
6079 (js2-add-to-string c)
6080 (setq c (js2-peek-char))
6081 (case c
6082 (?-
6083 (setq c (js2-get-char)) ;; skip -
6084 (js2-add-to-string c)
6085 (if (eq c ?-)
6086 (progn
6087 (js2-add-to-string c)
6088 (unless (js2-read-xml-comment)
6089 (throw 'return js2-ERROR)))
6090 (js2-xml-discard-string)
6091 (throw 'return js2-ERROR)))
6092 (?\[
6093 (setq c (js2-get-char)) ;; skip [
6094 (js2-add-to-string c)
6095 (if (and (= (js2-get-char) ?C)
6096 (= (js2-get-char) ?D)
6097 (= (js2-get-char) ?A)
6098 (= (js2-get-char) ?T)
6099 (= (js2-get-char) ?A)
6100 (= (js2-get-char) ?\[))
6101 (progn
6102 (js2-add-to-string ?C)
6103 (js2-add-to-string ?D)
6104 (js2-add-to-string ?A)
6105 (js2-add-to-string ?T)
6106 (js2-add-to-string ?A)
6107 (js2-add-to-string ?\[)
6108 (unless (js2-read-cdata)
6109 (throw 'return js2-ERROR)))
6110 (js2-xml-discard-string)
6111 (throw 'return js2-ERROR)))
6112 (t
6113 (unless (js2-read-entity)
6114 (throw 'return js2-ERROR))))
6115 ;; allow bare CDATA section
6116 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6117 (when (zerop js2-ts-xml-open-tags-count)
6118 (throw 'return js2-XMLEND)))
6119 (??
6120 (setq c (js2-get-char)) ;; skip ?
6121 (js2-add-to-string c)
6122 (unless (js2-read-PI)
6123 (throw 'return js2-ERROR)))
6124 (?/
6125 ;; end tag
6126 (setq c (js2-get-char)) ;; skip /
6127 (js2-add-to-string c)
6128 (when (zerop js2-ts-xml-open-tags-count)
6129 (js2-xml-discard-string)
6130 (throw 'return js2-ERROR))
6131 (setq js2-ts-xml-is-tag-content t)
6132 (decf js2-ts-xml-open-tags-count))
6133 (t
6134 ;; start tag
6135 (setq js2-ts-xml-is-tag-content t)
6136 (incf js2-ts-xml-open-tags-count))))
6137 (?{
6138 (js2-unget-char)
6139 (setq js2-ts-string (js2-get-string-from-buffer))
6140 (throw 'return js2-XML))
6141 (t
6142 (js2-add-to-string c))))))))
6143 (setq js2-token-end js2-ts-cursor)
6144 result))
6145
6146 (defun js2-read-quoted-string (quote)
6147 (let (c)
6148 (catch 'return
6149 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6150 (js2-add-to-string c)
6151 (if (eq c quote)
6152 (throw 'return t)))
6153 (js2-xml-discard-string) ;; throw away string in progress
6154 nil)))
6155
6156 (defun js2-read-xml-comment ()
6157 (let ((c (js2-get-char)))
6158 (catch 'return
6159 (while (/= c js2-EOF_CHAR)
6160 (catch 'continue
6161 (js2-add-to-string c)
6162 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6163 (setq c (js2-get-char))
6164 (js2-add-to-string c)
6165 (if (eq (js2-peek-char) ?>)
6166 (progn
6167 (setq c (js2-get-char)) ;; skip >
6168 (js2-add-to-string c)
6169 (throw 'return t))
6170 (throw 'continue nil)))
6171 (setq c (js2-get-char))))
6172 (js2-xml-discard-string)
6173 nil)))
6174
6175 (defun js2-read-cdata ()
6176 (let ((c (js2-get-char)))
6177 (catch 'return
6178 (while (/= c js2-EOF_CHAR)
6179 (catch 'continue
6180 (js2-add-to-string c)
6181 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6182 (setq c (js2-get-char))
6183 (js2-add-to-string c)
6184 (if (eq (js2-peek-char) ?>)
6185 (progn
6186 (setq c (js2-get-char)) ;; Skip >
6187 (js2-add-to-string c)
6188 (throw 'return t))
6189 (throw 'continue nil)))
6190 (setq c (js2-get-char))))
6191 (js2-xml-discard-string)
6192 nil)))
6193
6194 (defun js2-read-entity ()
6195 (let ((decl-tags 1)
6196 c)
6197 (catch 'return
6198 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6199 (js2-add-to-string c)
6200 (case c
6201 (?<
6202 (incf decl-tags))
6203 (?>
6204 (decf decl-tags)
6205 (if (zerop decl-tags)
6206 (throw 'return t)))))
6207 (js2-xml-discard-string)
6208 nil)))
6209
6210 (defun js2-read-PI ()
6211 "Scan an XML processing instruction."
6212 (let (c)
6213 (catch 'return
6214 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6215 (js2-add-to-string c)
6216 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6217 (setq c (js2-get-char)) ;; Skip >
6218 (js2-add-to-string c)
6219 (throw 'return t)))
6220 (js2-xml-discard-string)
6221 nil)))
6222
6223 (defun js2-scanner-get-line ()
6224 "Return the text of the current scan line."
6225 (buffer-substring (point-at-bol) (point-at-eol)))
6226
6227 ;;; Highlighting
6228
6229 (defsubst js2-set-face (beg end face &optional record)
6230 "Fontify a region. If RECORD is non-nil, record for later."
6231 (when (plusp js2-highlight-level)
6232 (setq beg (min (point-max) beg)
6233 beg (max (point-min) beg)
6234 end (min (point-max) end)
6235 end (max (point-min) end))
6236 (if record
6237 (push (list beg end face) js2-mode-fontifications)
6238 (put-text-property beg end 'face face))))
6239
6240 (defsubst js2-set-kid-face (pos kid len face)
6241 "Set-face on a child node.
6242 POS is absolute buffer position of parent.
6243 KID is the child node.
6244 LEN is the length to fontify.
6245 FACE is the face to fontify with."
6246 (js2-set-face (+ pos (js2-node-pos kid))
6247 (+ pos (js2-node-pos kid) (js2-node-len kid))
6248 face))
6249
6250 (defsubst js2-fontify-kwd (start length)
6251 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6252
6253 (defsubst js2-clear-face (beg end)
6254 (remove-text-properties beg end '(face nil
6255 help-echo nil
6256 point-entered nil
6257 c-in-sws nil)))
6258
6259 (defconst js2-ecma-global-props
6260 (concat "^"
6261 (regexp-opt
6262 '("Infinity" "NaN" "undefined" "arguments") t)
6263 "$")
6264 "Value properties of the Ecma-262 Global Object.
6265 Shown at or above `js2-highlight-level' 2.")
6266
6267 ;; might want to add the name "arguments" to this list?
6268 (defconst js2-ecma-object-props
6269 (concat "^"
6270 (regexp-opt
6271 '("prototype" "__proto__" "__parent__") t)
6272 "$")
6273 "Value properties of the Ecma-262 Object constructor.
6274 Shown at or above `js2-highlight-level' 2.")
6275
6276 (defconst js2-ecma-global-funcs
6277 (concat
6278 "^"
6279 (regexp-opt
6280 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6281 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6282 "$")
6283 "Function properties of the Ecma-262 Global object.
6284 Shown at or above `js2-highlight-level' 2.")
6285
6286 (defconst js2-ecma-number-props
6287 (concat "^"
6288 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6289 "NEGATIVE_INFINITY"
6290 "POSITIVE_INFINITY") t)
6291 "$")
6292 "Properties of the Ecma-262 Number constructor.
6293 Shown at or above `js2-highlight-level' 2.")
6294
6295 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6296 "Properties of the Ecma-262 Date constructor.
6297 Shown at or above `js2-highlight-level' 2.")
6298
6299 (defconst js2-ecma-math-props
6300 (concat "^"
6301 (regexp-opt
6302 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6303 t)
6304 "$")
6305 "Properties of the Ecma-262 Math object.
6306 Shown at or above `js2-highlight-level' 2.")
6307
6308 (defconst js2-ecma-math-funcs
6309 (concat "^"
6310 (regexp-opt
6311 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6312 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6313 "$")
6314 "Function properties of the Ecma-262 Math object.
6315 Shown at or above `js2-highlight-level' 2.")
6316
6317 (defconst js2-ecma-function-props
6318 (concat
6319 "^"
6320 (regexp-opt
6321 '(;; properties of the Object prototype object
6322 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6323 "toLocaleString" "toString" "valueOf"
6324 ;; properties of the Function prototype object
6325 "apply" "call"
6326 ;; properties of the Array prototype object
6327 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6328 "splice" "unshift"
6329 ;; properties of the String prototype object
6330 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6331 "localeCompare" "match" "replace" "search" "split" "substring"
6332 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6333 "toUpperCase"
6334 ;; properties of the Number prototype object
6335 "toExponential" "toFixed" "toPrecision"
6336 ;; properties of the Date prototype object
6337 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6338 "getMinutes" "getMonth" "getSeconds" "getTime"
6339 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6340 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6341 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6342 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6343 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6344 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6345 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6346 "toTimeString" "toUTCString"
6347 ;; properties of the RegExp prototype object
6348 "exec" "test"
6349 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6350 "toSource" "__defineGetter__" "__defineSetter__"
6351 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6352 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6353 t)
6354 "$")
6355 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6356 Shown at or above `js2-highlight-level' 3.")
6357
6358 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6359 (let ((target-name (and target
6360 (js2-name-node-p target)
6361 (js2-name-node-name target)))
6362 (prop-name (if prop (js2-name-node-name prop)))
6363 (level1 (>= js2-highlight-level 1))
6364 (level2 (>= js2-highlight-level 2))
6365 (level3 (>= js2-highlight-level 3))
6366 pos
6367 face)
6368 (when level2
6369 (if call-p
6370 (cond
6371 ((and target prop)
6372 (cond
6373 ((and level3 (string-match js2-ecma-function-props prop-name))
6374 (setq face 'font-lock-builtin-face))
6375 ((and target-name prop)
6376 (cond
6377 ((string= target-name "Date")
6378 (if (string-match js2-ecma-date-props prop-name)
6379 (setq face 'font-lock-builtin-face)))
6380 ((string= target-name "Math")
6381 (if (string-match js2-ecma-math-funcs prop-name)
6382 (setq face 'font-lock-builtin-face)))))))
6383 (prop
6384 (if (string-match js2-ecma-global-funcs prop-name)
6385 (setq face 'font-lock-builtin-face))))
6386 (cond
6387 ((and target prop)
6388 (cond
6389 ((string= target-name "Number")
6390 (if (string-match js2-ecma-number-props prop-name)
6391 (setq face 'font-lock-constant-face)))
6392 ((string= target-name "Math")
6393 (if (string-match js2-ecma-math-props prop-name)
6394 (setq face 'font-lock-constant-face)))))
6395 (prop
6396 (if (string-match js2-ecma-object-props prop-name)
6397 (setq face 'font-lock-constant-face)))))
6398 (when face
6399 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6400 (js2-node-pos prop))) ; relative
6401 (+ pos (js2-node-len prop))
6402 face)))))
6403
6404 (defun js2-parse-highlight-member-expr-node (node)
6405 "Perform syntax highlighting of EcmaScript built-in properties.
6406 The variable `js2-highlight-level' governs this highighting."
6407 (let (face target prop name pos end parent call-p callee)
6408 (cond
6409 ;; case 1: simple name, e.g. foo
6410 ((js2-name-node-p node)
6411 (setq name (js2-name-node-name node))
6412 ;; possible for name to be nil in rare cases - saw it when
6413 ;; running js2-mode on an elisp buffer. Might as well try to
6414 ;; make it so js2-mode never barfs.
6415 (when name
6416 (setq face (if (string-match js2-ecma-global-props name)
6417 'font-lock-constant-face))
6418 (when face
6419 (setq pos (js2-node-pos node)
6420 end (+ pos (js2-node-len node)))
6421 (js2-set-face pos end face))))
6422 ;; case 2: property access or function call
6423 ((or (js2-prop-get-node-p node)
6424 ;; highlight function call if expr is a prop-get node
6425 ;; or a plain name (i.e. unqualified function call)
6426 (and (setq call-p (js2-call-node-p node))
6427 (setq callee (js2-call-node-target node)) ; separate setq!
6428 (or (js2-prop-get-node-p callee)
6429 (js2-name-node-p callee))))
6430 (setq parent node
6431 node (if call-p callee node))
6432 (if (and call-p (js2-name-node-p callee))
6433 (setq prop callee)
6434 (setq target (js2-prop-get-node-left node)
6435 prop (js2-prop-get-node-right node)))
6436 (cond
6437 ((js2-name-node-p target)
6438 (if (js2-name-node-p prop)
6439 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6440 (js2-parse-highlight-prop-get parent target prop call-p)
6441 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6442 (js2-parse-highlight-prop-get parent target nil call-p)))
6443 ((js2-name-node-p prop)
6444 ;; case 2c: complex target, simple name, e.g. x[y].bar
6445 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6446
6447 (defun js2-parse-highlight-member-expr-fn-name (expr)
6448 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6449 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6450 We currently only handle the case where the last component is a prop-get
6451 of a simple name. Called before EXPR has a parent node."
6452 (let (pos
6453 (name (and (js2-prop-get-node-p expr)
6454 (js2-prop-get-node-right expr))))
6455 (when (js2-name-node-p name)
6456 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6457 (js2-node-pos name)))
6458 (+ pos (js2-node-len name))
6459 'font-lock-function-name-face
6460 'record))))
6461
6462 ;; source: http://jsdoc.sourceforge.net/
6463 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6464 ;; allows type specifications, and needs work before entering the wild.
6465
6466 (defconst js2-jsdoc-param-tag-regexp
6467 (concat "^\\s-*\\*+\\s-*\\(@"
6468 "\\(?:param\\|argument\\)"
6469 "\\)"
6470 "\\s-*\\({[^}]+}\\)?" ; optional type
6471 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6472 "\\>")
6473 "Matches jsdoc tags with optional type and optional param name.")
6474
6475 (defconst js2-jsdoc-typed-tag-regexp
6476 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6477 (regexp-opt
6478 '("enum"
6479 "extends"
6480 "field"
6481 "id"
6482 "implements"
6483 "lends"
6484 "mods"
6485 "requires"
6486 "return"
6487 "returns"
6488 "throw"
6489 "throws"))
6490 "\\)\\)\\s-*\\({[^}]+}\\)?")
6491 "Matches jsdoc tags with optional type.")
6492
6493 (defconst js2-jsdoc-arg-tag-regexp
6494 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6495 (regexp-opt
6496 '("alias"
6497 "augments"
6498 "borrows"
6499 "bug"
6500 "base"
6501 "config"
6502 "default"
6503 "define"
6504 "exception"
6505 "function"
6506 "member"
6507 "memberOf"
6508 "name"
6509 "namespace"
6510 "property"
6511 "since"
6512 "suppress"
6513 "this"
6514 "throws"
6515 "type"
6516 "version"))
6517 "\\)\\)\\s-+\\([^ \t]+\\)")
6518 "Matches jsdoc tags with a single argument.")
6519
6520 (defconst js2-jsdoc-empty-tag-regexp
6521 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6522 (regexp-opt
6523 '("addon"
6524 "author"
6525 "class"
6526 "const"
6527 "constant"
6528 "constructor"
6529 "constructs"
6530 "deprecated"
6531 "desc"
6532 "description"
6533 "event"
6534 "example"
6535 "exec"
6536 "export"
6537 "fileoverview"
6538 "final"
6539 "function"
6540 "hidden"
6541 "ignore"
6542 "implicitCast"
6543 "inheritDoc"
6544 "inner"
6545 "interface"
6546 "license"
6547 "noalias"
6548 "noshadow"
6549 "notypecheck"
6550 "override"
6551 "owner"
6552 "preserve"
6553 "preserveTry"
6554 "private"
6555 "protected"
6556 "public"
6557 "static"
6558 "supported"
6559 ))
6560 "\\)\\)\\s-*")
6561 "Matches empty jsdoc tags.")
6562
6563 (defconst js2-jsdoc-link-tag-regexp
6564 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6565 "Matches a jsdoc link or code tag.")
6566
6567 (defconst js2-jsdoc-see-tag-regexp
6568 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6569 "Matches a jsdoc @see tag.")
6570
6571 (defconst js2-jsdoc-html-tag-regexp
6572 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6573 "Matches a simple (no attributes) html start- or end-tag.")
6574
6575 (defsubst js2-jsdoc-highlight-helper ()
6576 (js2-set-face (match-beginning 1)
6577 (match-end 1)
6578 'js2-jsdoc-tag-face)
6579 (if (match-beginning 2)
6580 (if (save-excursion
6581 (goto-char (match-beginning 2))
6582 (= (char-after) ?{))
6583 (js2-set-face (1+ (match-beginning 2))
6584 (1- (match-end 2))
6585 'js2-jsdoc-type-face)
6586 (js2-set-face (match-beginning 2)
6587 (match-end 2)
6588 'js2-jsdoc-value-face)))
6589 (if (match-beginning 3)
6590 (js2-set-face (match-beginning 3)
6591 (match-end 3)
6592 'js2-jsdoc-value-face)))
6593
6594 (defun js2-highlight-jsdoc (ast)
6595 "Highlight doc comment tags."
6596 (let ((comments (js2-ast-root-comments ast))
6597 beg end)
6598 (save-excursion
6599 (dolist (node comments)
6600 (when (eq (js2-comment-node-format node) 'jsdoc)
6601 (setq beg (js2-node-abs-pos node)
6602 end (+ beg (js2-node-len node)))
6603 (save-restriction
6604 (narrow-to-region beg end)
6605 (dolist (re (list js2-jsdoc-param-tag-regexp
6606 js2-jsdoc-typed-tag-regexp
6607 js2-jsdoc-arg-tag-regexp
6608 js2-jsdoc-link-tag-regexp
6609 js2-jsdoc-see-tag-regexp
6610 js2-jsdoc-empty-tag-regexp))
6611 (goto-char beg)
6612 (while (re-search-forward re nil t)
6613 (js2-jsdoc-highlight-helper)))
6614 ;; simple highlighting for html tags
6615 (goto-char beg)
6616 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6617 (js2-set-face (match-beginning 1)
6618 (match-end 1)
6619 'js2-jsdoc-html-tag-delimiter-face)
6620 (js2-set-face (match-beginning 2)
6621 (match-end 2)
6622 'js2-jsdoc-html-tag-name-face)
6623 (js2-set-face (match-beginning 3)
6624 (match-end 3)
6625 'js2-jsdoc-html-tag-delimiter-face))))))))
6626
6627 (defun js2-highlight-assign-targets (node left right)
6628 "Highlight function properties and external variables."
6629 (let (leftpos end name)
6630 ;; highlight vars and props assigned function values
6631 (when (js2-function-node-p right)
6632 (cond
6633 ;; var foo = function() {...}
6634 ((js2-name-node-p left)
6635 (setq name left))
6636 ;; foo.bar.baz = function() {...}
6637 ((and (js2-prop-get-node-p left)
6638 (js2-name-node-p (js2-prop-get-node-right left)))
6639 (setq name (js2-prop-get-node-right left))))
6640 (when name
6641 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6642 (+ leftpos (js2-node-len name))
6643 'font-lock-function-name-face
6644 'record)))))
6645
6646 (defun js2-record-name-node (node)
6647 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6648 later. NODE must be a name node."
6649 (let (leftpos end)
6650 (push (list node js2-current-scope
6651 (setq leftpos (js2-node-abs-pos node))
6652 (setq end (+ leftpos (js2-node-len node))))
6653 js2-recorded-identifiers)))
6654
6655 (defun js2-highlight-undeclared-vars ()
6656 "After entire parse is finished, look for undeclared variable references.
6657 We have to wait until entire buffer is parsed, since JavaScript permits var
6658 decls to occur after they're used.
6659
6660 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6661 it is considered declared."
6662 (let (name)
6663 (dolist (entry js2-recorded-identifiers)
6664 (destructuring-bind (name-node scope pos end) entry
6665 (setq name (js2-name-node-name name-node))
6666 (unless (or (member name js2-global-externs)
6667 (member name js2-default-externs)
6668 (member name js2-additional-externs)
6669 (js2-get-defining-scope scope name))
6670 (js2-set-face pos end 'js2-external-variable-face 'record)
6671 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6672 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6673 (setq js2-recorded-identifiers nil)))
6674
6675 ;;; IMenu support
6676
6677 ;; We currently only support imenu, but eventually should support speedbar and
6678 ;; possibly other browsing mechanisms.
6679
6680 ;; The basic strategy is to identify function assignment targets of the form
6681 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6682 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6683 ;; for imenu after parsing is finished.
6684
6685 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6686 ;; JavaScript, and the general problem is undecidable. However, several forms
6687 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6688 ;; include:
6689
6690 ;; function foo() -- function declaration
6691 ;; foo = function() -- function expression assigned to variable
6692 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6693 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6694 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6695 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6696 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6697 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6698 ;; function foo() {function bar() {...}} -- nested function
6699 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6700
6701 ;; This list boils down to a few forms that can be combined recursively.
6702 ;; Top-level named function declarations include both the left-hand (name)
6703 ;; and the right-hand (function value) expressions needed to produce an imenu
6704 ;; entry. The other "right-hand" forms we need to look for are:
6705 ;; - functions declared as props/getters/setters in object literals
6706 ;; - nested named function declarations
6707 ;; The "left-hand" expressions that functions can be assigned to include:
6708 ;; - local/global variables
6709 ;; - nested property-get expressions like a.b.c.d
6710 ;; - element gets like foo[10] or foo['bar'] where the index
6711 ;; expression can be trivially converted to a property name. They
6712 ;; effectively then become property gets.
6713
6714 ;; All the different definition types are canonicalized into the form
6715 ;; foo.bar.baz = position-of-function-keyword
6716
6717 ;; We need to build a trie-like structure for imenu. As an example,
6718 ;; consider the following JavaScript code:
6719
6720 ;; a = function() {...} // function at position 5
6721 ;; b = function() {...} // function at position 25
6722 ;; foo = function() {...} // function at position 100
6723 ;; foo.bar = function() {...} // function at position 200
6724 ;; foo.bar.baz = function() {...} // function at position 300
6725 ;; foo.bar.zab = function() {...} // function at position 400
6726
6727 ;; During parsing we accumulate an entry for each definition in
6728 ;; the variable `js2-imenu-recorder', like so:
6729
6730 ;; '((a 5)
6731 ;; (b 25)
6732 ;; (foo 100)
6733 ;; (foo bar 200)
6734 ;; (foo bar baz 300)
6735 ;; (foo bar zab 400))
6736
6737 ;; After parsing these entries are merged into this alist-trie:
6738
6739 ;; '((a . 1)
6740 ;; (b . 2)
6741 ;; (foo (<definition> . 3)
6742 ;; (bar (<definition> . 6)
6743 ;; (baz . 100)
6744 ;; (zab . 200))))
6745
6746 ;; Note the wacky need for a <definition> name. The token can be anything
6747 ;; that isn't a valid JavaScript identifier, because you might make foo
6748 ;; a function and then start setting properties on it that are also functions.
6749
6750 (defsubst js2-prop-node-name (node)
6751 "Return the name of a node that may be a property-get/property-name.
6752 If NODE is not a valid name-node, string-node or integral number-node,
6753 returns nil. Otherwise returns the string name/value of the node."
6754 (cond
6755 ((js2-name-node-p node)
6756 (js2-name-node-name node))
6757 ((js2-string-node-p node)
6758 (js2-string-node-value node))
6759 ((and (js2-number-node-p node)
6760 (string-match "^[0-9]+$" (js2-number-node-value node)))
6761 (js2-number-node-value node))
6762 ((js2-this-node-p node)
6763 "this")))
6764
6765 (defsubst js2-node-qname-component (node)
6766 "Test function: return the name of this node, if it contributes to a qname.
6767 Returns nil if the node doesn't contribute."
6768 (copy-sequence
6769 (or (js2-prop-node-name node)
6770 (if (and (js2-function-node-p node)
6771 (js2-function-node-name node))
6772 (js2-name-node-name (js2-function-node-name node))))))
6773
6774 (defsubst js2-record-function-qname (fn-node qname)
6775 "Associate FN-NODE with its QNAME for later lookup.
6776 This is used in postprocessing the chain list. When we find a chain
6777 whose first element is a js2-THIS keyword node, we look up the parent
6778 function and see (using this map) whether it is the tail of a chain.
6779 If so, we replace the this-node with a copy of the parent's qname."
6780 (unless js2-imenu-function-map
6781 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6782 (puthash fn-node qname js2-imenu-function-map))
6783
6784 (defun js2-record-imenu-functions (node &optional var)
6785 "Record function definitions for imenu.
6786 NODE is a function node or an object literal.
6787 VAR, if non-nil, is the expression that NODE is being assigned to."
6788 (when js2-parse-ide-mode
6789 (let ((fun-p (js2-function-node-p node))
6790 qname left fname-node pos)
6791 (cond
6792 ;; non-anonymous function declaration?
6793 ((and fun-p
6794 (not var)
6795 (setq fname-node (js2-function-node-name node)))
6796 (push (setq qname (list fname-node (js2-node-pos node)))
6797 js2-imenu-recorder)
6798 (js2-record-function-qname node qname))
6799 ;; for remaining forms, compute left-side tree branch first
6800 ((and var (setq qname (js2-compute-nested-prop-get var)))
6801 (cond
6802 ;; foo.bar.baz = function
6803 (fun-p
6804 (push (nconc qname (list (js2-node-pos node)))
6805 js2-imenu-recorder)
6806 (js2-record-function-qname node qname))
6807 ;; foo.bar.baz = object-literal
6808 ;; look for nested functions: {a: {b: function() {...} }}
6809 ((js2-object-node-p node)
6810 ;; Node position here is still absolute, since the parser
6811 ;; passes the assignment target and value expressions
6812 ;; to us before they are added as children of the assignment node.
6813 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6814
6815 (defun js2-compute-nested-prop-get (node)
6816 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6817 component nodes as a list. Otherwise return nil. Element-gets are treated
6818 as property-gets if the index expression is a string, or a positive integer."
6819 (let (left right head)
6820 (cond
6821 ((or (js2-name-node-p node)
6822 (js2-this-node-p node))
6823 (list node))
6824 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6825 ((js2-prop-get-node-p node) ; foo.bar
6826 (setq left (js2-prop-get-node-left node)
6827 right (js2-prop-get-node-right node))
6828 (if (setq head (js2-compute-nested-prop-get left))
6829 (nconc head (list right))))
6830 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6831 (setq left (js2-elem-get-node-target node)
6832 right (js2-elem-get-node-element node))
6833 (if (or (js2-string-node-p right) ; ['bar']
6834 (and (js2-number-node-p right) ; [10]
6835 (string-match "^[0-9]+$"
6836 (js2-number-node-value right))))
6837 (if (setq head (js2-compute-nested-prop-get left))
6838 (nconc head (list right))))))))
6839
6840 (defun js2-record-object-literal (node qname pos)
6841 "Recursively process an object literal looking for functions.
6842 NODE is an object literal that is the right-hand child of an assignment
6843 expression. QNAME is a list of nodes representing the assignment target,
6844 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6845 POS is the absolute position of the node.
6846 We do a depth-first traversal of NODE. Any functions we find are prefixed
6847 with QNAME plus the property name of the function and appended to the
6848 variable `js2-imenu-recorder'."
6849 (let (left right)
6850 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6851 (let ((left (js2-infix-node-left e))
6852 ;; Element positions are relative to the parent position.
6853 (pos (+ pos (js2-node-pos e))))
6854 (cond
6855 ;; foo: function() {...}
6856 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6857 (when (js2-prop-node-name left)
6858 ;; As a policy decision, we record the position of the property,
6859 ;; not the position of the `function' keyword, since the property
6860 ;; is effectively the name of the function.
6861 (push (append qname (list left pos))
6862 js2-imenu-recorder)
6863 (js2-record-function-qname right qname)))
6864 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6865 ((js2-object-node-p right)
6866 (js2-record-object-literal right
6867 (append qname (list (js2-infix-node-left e)))
6868 (+ pos (js2-node-pos right)))))))))
6869
6870 (defsubst js2-node-top-level-decl-p (node)
6871 "Return t if NODE's name is defined in the top-level scope.
6872 Also returns t if NODE's name is not defined in any scope, since it implies
6873 that it's an external variable, which must also be in the top-level scope."
6874 (let* ((name (js2-prop-node-name node))
6875 (this-scope (js2-node-get-enclosing-scope node))
6876 defining-scope)
6877 (cond
6878 ((js2-this-node-p node)
6879 nil)
6880 ((null this-scope)
6881 t)
6882 ((setq defining-scope (js2-get-defining-scope this-scope name))
6883 (js2-ast-root-p defining-scope))
6884 (t t))))
6885
6886 (defsubst js2-wrapper-function-p (node)
6887 "Returns t if NODE is a function expression that's immediately invoked.
6888 NODE must be `js2-function-node'."
6889 (let ((parent (js2-node-parent node)))
6890 (or
6891 ;; function(){...}();
6892 (js2-call-node-p parent)
6893 (and (js2-paren-node-p parent)
6894 ;; (function(){...})();
6895 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6896 ;; (function(){...}).call(this);
6897 (and (js2-prop-get-node-p parent)
6898 (member (js2-name-node-name (js2-prop-get-node-right parent))
6899 '("call" "apply"))
6900 (js2-call-node-p (js2-node-parent parent))))))))
6901
6902 (defun js2-browse-postprocess-chains (chains)
6903 "Modify function-declaration name chains after parsing finishes.
6904 Some of the information is only available after the parse tree is complete.
6905 For instance, following a 'this' reference requires a parent function node."
6906 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6907 result head fn fn-type parent-chain p elem parent)
6908 (dolist (chain chains)
6909 ;; examine the head of each node to get its defining scope
6910 (setq head (car chain))
6911 ;; if top-level/external, keep as-is
6912 (if (js2-node-top-level-decl-p head)
6913 (push chain result)
6914 (cond
6915 ;; starts with this-reference
6916 ((js2-this-node-p head)
6917 (setq fn (js2-node-parent-script-or-fn head)
6918 chain (cdr chain))) ; discard this-node
6919 ;; nested named function
6920 ((js2-function-node-p (setq parent (js2-node-parent head)))
6921 (setq fn (js2-node-parent-script-or-fn parent)))
6922 ;; variable assigned a function expression
6923 (t (setq fn (js2-node-parent-script-or-fn head))))
6924 (when fn
6925 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6926 (unless fn-type
6927 (setq fn-type
6928 (cond ((js2-nested-function-p fn) 'skip)
6929 ((setq parent-chain
6930 (gethash fn js2-imenu-function-map))
6931 'named)
6932 ((js2-wrapper-function-p fn) 'anon)
6933 (t 'skip)))
6934 (puthash fn fn-type js2-imenu-fn-type-map))
6935 (case fn-type
6936 ('anon (push chain result)) ; anonymous top-level wrapper
6937 ('named ; top-level named function
6938 ;; prefix parent fn qname, which is
6939 ;; parent-chain sans last elem, to this chain.
6940 (push (append (butlast parent-chain) chain) result))))))
6941 ;; finally replace each node in each chain with its name.
6942 (dolist (chain result)
6943 (setq p chain)
6944 (while p
6945 (if (js2-node-p (setq elem (car p)))
6946 (setcar p (js2-node-qname-component elem)))
6947 (setq p (cdr p))))
6948 result))
6949
6950 ;; Merge name chains into a trie-like tree structure of nested lists.
6951 ;; To simplify construction of the trie, we first build it out using the rule
6952 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6953 ;; [key, num-or-list]. The second element can be a number; if so, this key
6954 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6955 ;; associated with the key at this level.) Otherwise the second element is
6956 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6957 ;; a simple recursive formulation.
6958 ;;
6959 ;; js2-mode is building the data structure for imenu. The imenu documentation
6960 ;; claims that it's the structure above, but in practice it wants the children
6961 ;; at the same list level as the key for that level, which is how I've drawn
6962 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6963 ;; list wrapper around the children at each level.
6964 ;;
6965 ;; A completed nested imenu-alist entry looks like this:
6966 ;; '(("foo"
6967 ;; ("<definition>" . 7)
6968 ;; ("bar"
6969 ;; ("a" . 40)
6970 ;; ("b" . 60))))
6971 ;;
6972 ;; In particular, the documentation for `imenu--index-alist' says that
6973 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6974 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6975
6976 (defsubst js2-treeify (lst)
6977 "Convert (a b c d) to (a ((b ((c d)))))"
6978 (if (null (cddr lst)) ; list length <= 2
6979 lst
6980 (list (car lst) (list (js2-treeify (cdr lst))))))
6981
6982 (defun js2-build-alist-trie (chains trie)
6983 "Merge declaration name chains into a trie-like alist structure for imenu.
6984 CHAINS is the qname chain list produced during parsing. TRIE is a
6985 list of elements built up so far."
6986 (let (head tail pos branch kids)
6987 (dolist (chain chains)
6988 (setq head (car chain)
6989 tail (cdr chain)
6990 pos (if (numberp (car tail)) (car tail))
6991 branch (js2-find-if (lambda (n)
6992 (string= (car n) head))
6993 trie)
6994 kids (second branch))
6995 (cond
6996 ;; case 1: this key isn't in the trie yet
6997 ((null branch)
6998 (if trie
6999 (setcdr (last trie) (list (js2-treeify chain)))
7000 (setq trie (list (js2-treeify chain)))))
7001 ;; case 2: key is present with a single number entry: replace w/ list
7002 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7003 ;; ("<definition>" 20)))
7004 ((numberp kids)
7005 (setcar (cdr branch)
7006 (list (list "<definition-1>" kids)
7007 (if pos
7008 (list "<definition-2>" pos)
7009 (js2-treeify tail)))))
7010 ;; case 3: key is there (with kids), and we're a number entry
7011 (pos
7012 (setcdr (last kids)
7013 (list
7014 (list (format "<definition-%d>"
7015 (1+ (loop for kid in kids
7016 count (eq ?< (aref (car kid) 0)))))
7017 pos))))
7018 ;; case 4: key is there with kids, need to merge in our chain
7019 (t
7020 (js2-build-alist-trie (list tail) kids))))
7021 trie))
7022
7023 (defun js2-flatten-trie (trie)
7024 "Convert TRIE to imenu-format.
7025 Recurses through nodes, and for each one whose second element is a list,
7026 appends the list's flattened elements to the current element. Also
7027 changes the tails into conses. For instance, this pre-flattened trie
7028
7029 '(a ((b 20)
7030 (c ((d 30)
7031 (e 40)))))
7032
7033 becomes
7034
7035 '(a (b . 20)
7036 (c (d . 30)
7037 (e . 40)))
7038
7039 Note that the root of the trie has no key, just a list of chains.
7040 This is also true for the value of any key with multiple children,
7041 e.g. key 'c' in the example above."
7042 (cond
7043 ((listp (car trie))
7044 (mapcar #'js2-flatten-trie trie))
7045 (t
7046 (if (numberp (second trie))
7047 (cons (car trie) (second trie))
7048 ;; else pop list and append its kids
7049 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7050
7051 (defun js2-build-imenu-index ()
7052 "Turn `js2-imenu-recorder' into an imenu data structure."
7053 (unless (eq js2-imenu-recorder 'empty)
7054 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7055 (result (js2-build-alist-trie chains nil)))
7056 (js2-flatten-trie result))))
7057
7058 (defun js2-test-print-chains (chains)
7059 "Print a list of qname chains.
7060 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7061 i.e. one or more nodes, and an integer position as the list tail."
7062 (mapconcat (lambda (chain)
7063 (concat "("
7064 (mapconcat (lambda (elem)
7065 (if (js2-node-p elem)
7066 (or (js2-node-qname-component elem)
7067 "nil")
7068 (number-to-string elem)))
7069 chain
7070 " ")
7071 ")"))
7072 chains
7073 "\n"))
7074
7075 ;;; Parser
7076
7077 (defconst js2-version "1.8.0"
7078 "Version of JavaScript supported, plus minor js2 version.")
7079
7080 (defmacro js2-record-face (face)
7081 "Record a style run of FACE for the current token."
7082 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7083
7084 (defsubst js2-node-end (n)
7085 "Computes the absolute end of node N.
7086 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7087 is only true until the node is added to its parent; i.e., while parsing."
7088 (+ (js2-node-pos n)
7089 (js2-node-len n)))
7090
7091 (defsubst js2-record-comment ()
7092 "Record a comment in `js2-scanned-comments'."
7093 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7094 :format js2-ts-comment-type)
7095 js2-scanned-comments)
7096 (when js2-parse-ide-mode
7097 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7098 'font-lock-doc-face
7099 'font-lock-comment-face))
7100 (when (memq js2-ts-comment-type '(html preprocessor))
7101 ;; Tell cc-engine the bounds of the comment.
7102 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7103
7104 ;; This function is called depressingly often, so it should be fast.
7105 ;; Most of the time it's looking at the same token it peeked before.
7106 (defsubst js2-peek-token ()
7107 "Returns the next token without consuming it.
7108 If previous token was consumed, calls scanner to get new token.
7109 If previous token was -not- consumed, returns it (idempotent).
7110
7111 This function will not return a newline (js2-EOL) - instead, it
7112 gobbles newlines until it finds a non-newline token, and flags
7113 that token as appearing just after a newline.
7114
7115 This function will also not return a js2-COMMENT. Instead, it
7116 records comments found in `js2-scanned-comments'. If the token
7117 returned by this function immediately follows a jsdoc comment,
7118 the token is flagged as such.
7119
7120 Note that this function always returned the un-flagged token!
7121 The flags, if any, are saved in `js2-current-flagged-token'."
7122 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7123 js2-current-token ; most common case - return already-peeked token
7124 (let ((tt (js2-get-token)) ; call scanner
7125 saw-eol
7126 face)
7127 ;; process comments and whitespace
7128 (while (or (= tt js2-EOL)
7129 (= tt js2-COMMENT))
7130 (if (= tt js2-EOL)
7131 (setq saw-eol t)
7132 (setq saw-eol nil)
7133 (if js2-record-comments
7134 (js2-record-comment)))
7135 (setq tt (js2-get-token))) ; call scanner
7136 (setq js2-current-token tt
7137 js2-current-flagged-token (if saw-eol
7138 (logior tt js2-ti-after-eol)
7139 tt))
7140 ;; perform lexical fontification as soon as token is scanned
7141 (when js2-parse-ide-mode
7142 (cond
7143 ((minusp tt)
7144 (js2-record-face 'js2-error-face))
7145 ((setq face (aref js2-kwd-tokens tt))
7146 (js2-record-face face))
7147 ((and (= tt js2-NAME)
7148 (equal js2-ts-string "undefined"))
7149 (js2-record-face 'font-lock-constant-face))))
7150 tt))) ; return unflagged token
7151
7152 (defsubst js2-peek-flagged-token ()
7153 "Returns the current token along with any flags set for it."
7154 (js2-peek-token)
7155 js2-current-flagged-token)
7156
7157 (defsubst js2-consume-token ()
7158 (setq js2-current-flagged-token js2-EOF))
7159
7160 (defsubst js2-next-token ()
7161 (prog1
7162 (js2-peek-token)
7163 (js2-consume-token)))
7164
7165 (defsubst js2-next-flagged-token ()
7166 (js2-peek-token)
7167 (prog1 js2-current-flagged-token
7168 (js2-consume-token)))
7169
7170 (defsubst js2-match-token (match)
7171 "Consume and return t if next token matches MATCH, a bytecode.
7172 Returns nil and consumes nothing if MATCH is not the next token."
7173 (if (/= (js2-peek-token) match)
7174 nil
7175 (js2-consume-token)
7176 t))
7177
7178 (defsubst js2-valid-prop-name-token (tt)
7179 (or (= tt js2-NAME)
7180 (and js2-allow-keywords-as-property-names
7181 (plusp tt)
7182 (aref js2-kwd-tokens tt))))
7183
7184 (defsubst js2-match-prop-name ()
7185 "Consume token and return t if next token is a valid property name.
7186 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7187 is non-nil and it's a keyword token."
7188 (if (js2-valid-prop-name-token (js2-peek-token))
7189 (progn
7190 (js2-consume-token)
7191 t)
7192 nil))
7193
7194 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7195 (if (js2-match-prop-name)
7196 t
7197 (js2-report-error msg-id nil pos len)
7198 nil))
7199
7200 (defsubst js2-peek-token-or-eol ()
7201 "Return js2-EOL if the current token immediately follows a newline.
7202 Else returns the current token. Used in situations where we don't
7203 consider certain token types valid if they are preceded by a newline.
7204 One example is the postfix ++ or -- operator, which has to be on the
7205 same line as its operand."
7206 (let ((tt (js2-peek-token)))
7207 ;; Check for last peeked token flags
7208 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7209 js2-EOL
7210 tt)))
7211
7212 (defsubst js2-set-check-for-label ()
7213 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7214 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7215
7216 (defsubst js2-must-match (token msg-id &optional pos len)
7217 "Match next token to token code TOKEN, or record a syntax error.
7218 MSG-ID is the error message to report if the match fails.
7219 Returns t on match, nil if no match."
7220 (if (js2-match-token token)
7221 t
7222 (js2-report-error msg-id nil pos len)
7223 nil))
7224
7225 (defsubst js2-inside-function ()
7226 (plusp js2-nesting-of-function))
7227
7228 (defsubst js2-set-requires-activation ()
7229 (if (js2-function-node-p js2-current-script-or-fn)
7230 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7231
7232 (defsubst js2-check-activation-name (name token)
7233 (when (js2-inside-function)
7234 ;; skip language-version 1.2 check from Rhino
7235 (if (or (string= "arguments" name)
7236 (and js2-compiler-activation-names ; only used in codegen
7237 (gethash name js2-compiler-activation-names)))
7238 (js2-set-requires-activation))))
7239
7240 (defsubst js2-set-is-generator ()
7241 (if (js2-function-node-p js2-current-script-or-fn)
7242 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7243
7244 (defsubst js2-must-have-xml ()
7245 (unless js2-compiler-xml-available
7246 (js2-report-error "msg.XML.not.available")))
7247
7248 (defsubst js2-push-scope (scope)
7249 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7250 (assert (js2-scope-p scope))
7251 (assert (null (js2-scope-parent-scope scope)))
7252 (assert (not (eq js2-current-scope scope)))
7253 (setf (js2-scope-parent-scope scope) js2-current-scope
7254 js2-current-scope scope))
7255
7256 (defsubst js2-pop-scope ()
7257 (setq js2-current-scope
7258 (js2-scope-parent-scope js2-current-scope)))
7259
7260 (defsubst js2-enter-loop (loop-node)
7261 (push loop-node js2-loop-set)
7262 (push loop-node js2-loop-and-switch-set)
7263 (js2-push-scope loop-node)
7264 ;; Tell the current labeled statement (if any) its statement,
7265 ;; and set the jump target of the first label to the loop.
7266 ;; These are used in `js2-parse-continue' to verify that the
7267 ;; continue target is an actual labeled loop. (And for codegen.)
7268 (when js2-labeled-stmt
7269 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7270 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7271 js2-labeled-stmt))) loop-node)))
7272
7273 (defsubst js2-exit-loop ()
7274 (pop js2-loop-set)
7275 (pop js2-loop-and-switch-set)
7276 (js2-pop-scope))
7277
7278 (defsubst js2-enter-switch (switch-node)
7279 (push switch-node js2-loop-and-switch-set))
7280
7281 (defsubst js2-exit-switch ()
7282 (pop js2-loop-and-switch-set))
7283
7284 (defun js2-parse (&optional buf cb)
7285 "Tells the js2 parser to parse a region of JavaScript.
7286
7287 BUF is a buffer or buffer name containing the code to parse.
7288 Call `narrow-to-region' first to parse only part of the buffer.
7289
7290 The returned AST root node is given some additional properties:
7291 `node-count' - total number of nodes in the AST
7292 `buffer' - BUF. The buffer it refers to may change or be killed,
7293 so the value is not necessarily reliable.
7294
7295 An optional callback CB can be specified to report parsing
7296 progress. If `(functionp CB)' returns t, it will be called with
7297 the current line number once before parsing begins, then again
7298 each time the lexer reaches a new line number.
7299
7300 CB can also be a list of the form `(symbol cb ...)' to specify
7301 multiple callbacks with different criteria. Each symbol is a
7302 criterion keyword, and the following element is the callback to
7303 call
7304
7305 :line - called whenever the line number changes
7306 :token - called for each new token consumed
7307
7308 The list of criteria could be extended to include entering or
7309 leaving a statement, an expression, or a function definition."
7310 (if (and cb (not (functionp cb)))
7311 (error "criteria callbacks not yet implemented"))
7312 (let ((inhibit-point-motion-hooks t)
7313 (js2-compiler-xml-available (>= js2-language-version 160))
7314 ;; This is a recursive-descent parser, so give it a big stack.
7315 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7316 (max-specpdl-size (max max-specpdl-size 3000))
7317 (case-fold-search nil)
7318 ast)
7319 (or buf (setq buf (current-buffer)))
7320 (message nil) ; clear any error message from previous parse
7321 (save-excursion
7322 (set-buffer buf)
7323 (setq js2-scanned-comments nil
7324 js2-parsed-errors nil
7325 js2-parsed-warnings nil
7326 js2-imenu-recorder nil
7327 js2-imenu-function-map nil
7328 js2-label-set nil)
7329 (js2-init-scanner)
7330 (setq ast (js2-with-unmodifying-text-property-changes
7331 (js2-do-parse)))
7332 (unless js2-ts-hit-eof
7333 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7334 (setf (js2-ast-root-errors ast) js2-parsed-errors
7335 (js2-ast-root-warnings ast) js2-parsed-warnings)
7336 ;; if we didn't find any declarations, put a dummy in this list so we
7337 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7338 (unless js2-imenu-recorder
7339 (setq js2-imenu-recorder 'empty))
7340 (run-hooks 'js2-parse-finished-hook)
7341 ast)))
7342
7343 ;; Corresponds to Rhino's Parser.parse() method.
7344 (defun js2-do-parse ()
7345 "Parse current buffer starting from current point.
7346 Scanner should be initialized."
7347 (let ((pos js2-ts-cursor)
7348 (end js2-ts-cursor) ; in case file is empty
7349 root n tt)
7350 ;; initialize buffer-local parsing vars
7351 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7352 js2-current-script-or-fn root
7353 js2-current-scope root
7354 js2-current-flagged-token js2-EOF
7355 js2-nesting-of-function 0
7356 js2-labeled-stmt nil
7357 js2-recorded-identifiers nil) ; for js2-highlight
7358 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7359 (if (= tt js2-FUNCTION)
7360 (progn
7361 (js2-consume-token)
7362 (setq n (js2-parse-function (if js2-called-by-compile-function
7363 'FUNCTION_EXPRESSION
7364 'FUNCTION_STATEMENT))))
7365 ;; not a function - parse a statement
7366 (setq n (js2-parse-statement)))
7367 ;; add function or statement to script
7368 (setq end (js2-node-end n))
7369 (js2-block-node-push root n))
7370 ;; add comments to root in lexical order
7371 (when js2-scanned-comments
7372 ;; if we find a comment beyond end of normal kids, use its end
7373 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7374 (dolist (comment js2-scanned-comments)
7375 (push comment (js2-ast-root-comments root))
7376 (js2-node-add-children root comment)))
7377 (setf (js2-node-len root) (- end pos))
7378 ;; Give extensions a chance to muck with things before highlighting starts.
7379 (let ((js2-additional-externs js2-additional-externs))
7380 (dolist (callback js2-post-parse-callbacks)
7381 (funcall callback))
7382 (js2-highlight-undeclared-vars))
7383 root))
7384
7385 (defun js2-function-parser ()
7386 (js2-consume-token)
7387 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7388
7389 (defun js2-parse-function-closure-body (fn-node)
7390 "Parse a JavaScript 1.8 function closure body."
7391 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7392 (if js2-ts-hit-eof
7393 (js2-report-error "msg.no.brace.body" nil
7394 (js2-node-pos fn-node)
7395 (- js2-ts-cursor (js2-node-pos fn-node)))
7396 (js2-node-add-children fn-node
7397 (setf (js2-function-node-body fn-node)
7398 (js2-parse-expr t))))))
7399
7400 (defun js2-parse-function-body (fn-node)
7401 (js2-must-match js2-LC "msg.no.brace.body"
7402 (js2-node-pos fn-node)
7403 (- js2-ts-cursor (js2-node-pos fn-node)))
7404 (let ((pos js2-token-beg) ; LC position
7405 (pn (make-js2-block-node)) ; starts at LC position
7406 tt
7407 end)
7408 (incf js2-nesting-of-function)
7409 (unwind-protect
7410 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7411 (= tt js2-EOF)
7412 (= tt js2-RC)))
7413 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7414 (js2-parse-statement)
7415 (js2-consume-token)
7416 (js2-parse-function 'FUNCTION_STATEMENT))))
7417 (decf js2-nesting-of-function))
7418 (setq end js2-token-end) ; assume no curly and leave at current token
7419 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7420 (setq end js2-token-end))
7421 (setf (js2-node-pos pn) pos
7422 (js2-node-len pn) (- end pos))
7423 (setf (js2-function-node-body fn-node) pn)
7424 (js2-node-add-children fn-node pn)
7425 pn))
7426
7427 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7428 "Declare and fontify destructuring parameters inside NODE.
7429 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7430 (cond
7431 ((js2-name-node-p node)
7432 (let (leftpos)
7433 (js2-define-symbol decl-type (js2-name-node-name node)
7434 node ignore-not-in-block)
7435 (when face
7436 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7437 (+ leftpos (js2-node-len node))
7438 face 'record))))
7439 ((js2-object-node-p node)
7440 (dolist (elem (js2-object-node-elems node))
7441 (js2-define-destruct-symbols
7442 (if (js2-object-prop-node-p elem)
7443 (js2-object-prop-node-right elem)
7444 ;; abbreviated destructuring {a, b}
7445 elem)
7446 decl-type face ignore-not-in-block)))
7447 ((js2-array-node-p node)
7448 (dolist (elem (js2-array-node-elems node))
7449 (when elem
7450 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7451 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7452 (js2-node-len node)))))
7453
7454 (defun js2-parse-function-params (fn-node pos)
7455 (if (js2-match-token js2-RP)
7456 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7457 (let (params len param)
7458 (loop for tt = (js2-peek-token)
7459 do
7460 (cond
7461 ;; destructuring param
7462 ((or (= tt js2-LB) (= tt js2-LC))
7463 (setq param (js2-parse-primary-expr-lhs))
7464 (js2-define-destruct-symbols param
7465 js2-LP
7466 'js2-function-param-face)
7467 (push param params))
7468 ;; simple name
7469 (t
7470 (js2-must-match js2-NAME "msg.no.parm")
7471 (js2-record-face 'js2-function-param-face)
7472 (setq param (js2-create-name-node))
7473 (js2-define-symbol js2-LP js2-ts-string param)
7474 (push param params)))
7475 while
7476 (js2-match-token js2-COMMA))
7477 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7478 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7479 (dolist (p params)
7480 (js2-node-add-children fn-node p)
7481 (push p (js2-function-node-params fn-node))))))
7482
7483 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7484 "Possibly show inconsistent-return warning.
7485 Last token scanned is the close-curly for the function body."
7486 (when (and js2-mode-show-strict-warnings
7487 js2-strict-inconsistent-return-warning
7488 (not (js2-has-consistent-return-usage
7489 (js2-function-node-body fn-node))))
7490 ;; Have it extend from close-curly to bol or beginning of block.
7491 (let ((pos (save-excursion
7492 (goto-char js2-token-end)
7493 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7494 (point-at-bol))))
7495 (end js2-token-end))
7496 (if (plusp (js2-name-node-length name))
7497 (js2-add-strict-warning "msg.no.return.value"
7498 (js2-name-node-name name) pos end)
7499 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7500
7501 (defun js2-parse-function (function-type)
7502 "Function parser. FUNCTION-TYPE is a symbol."
7503 (let ((pos js2-token-beg) ; start of 'function' keyword
7504 name
7505 name-beg
7506 name-end
7507 fn-node
7508 lp
7509 (synthetic-type function-type)
7510 member-expr-node)
7511 ;; parse function name, expression, or non-name (anonymous)
7512 (cond
7513 ;; function foo(...)
7514 ((js2-match-token js2-NAME)
7515 (setq name (js2-create-name-node t)
7516 name-beg js2-token-beg
7517 name-end js2-token-end)
7518 (unless (js2-match-token js2-LP)
7519 (when js2-allow-member-expr-as-function-name
7520 ;; function foo.bar(...)
7521 (setq member-expr-node name
7522 name nil
7523 member-expr-node (js2-parse-member-expr-tail
7524 nil member-expr-node)))
7525 (js2-must-match js2-LP "msg.no.paren.parms")))
7526 ((js2-match-token js2-LP)
7527 nil) ; anonymous function: leave name as null
7528 (t
7529 ;; function random-member-expr(...)
7530 (when js2-allow-member-expr-as-function-name
7531 ;; Note that memberExpr can not start with '(' like
7532 ;; in function (1+2).toString(), because 'function (' already
7533 ;; processed as anonymous function
7534 (setq member-expr-node (js2-parse-member-expr)))
7535 (js2-must-match js2-LP "msg.no.paren.parms")))
7536 (if (= js2-current-token js2-LP) ; eventually matched LP?
7537 (setq lp js2-token-beg))
7538 (if member-expr-node
7539 (progn
7540 (setq synthetic-type 'FUNCTION_EXPRESSION)
7541 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7542 (if name
7543 (js2-set-face name-beg name-end
7544 'font-lock-function-name-face 'record)))
7545 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7546 (plusp (js2-name-node-length name)))
7547 ;; Function statements define a symbol in the enclosing scope
7548 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7549 (setf fn-node (make-js2-function-node :pos pos
7550 :name name
7551 :form function-type
7552 :lp (if lp (- lp pos))))
7553 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7554 ;; 1. Nested functions are not affected by the dynamic scope flag
7555 ;; as dynamic scope is already a parent of their scope.
7556 ;; 2. Functions defined under the with statement also immune to
7557 ;; this setup, in which case dynamic scope is ignored in favor
7558 ;; of the with object.
7559 (setf (js2-function-node-ignore-dynamic fn-node) t))
7560 ;; dynamically bind all the per-function variables
7561 (let ((js2-current-script-or-fn fn-node)
7562 (js2-current-scope fn-node)
7563 (js2-nesting-of-with 0)
7564 (js2-end-flags 0)
7565 js2-label-set
7566 js2-loop-set
7567 js2-loop-and-switch-set)
7568 (js2-parse-function-params fn-node pos)
7569 (if (and (>= js2-language-version 180)
7570 (/= (js2-peek-token) js2-LC))
7571 (js2-parse-function-closure-body fn-node)
7572 (js2-parse-function-body fn-node))
7573 (if name
7574 (js2-node-add-children fn-node name))
7575 (js2-check-inconsistent-return-warning fn-node name)
7576 ;; Function expressions define a name only in the body of the
7577 ;; function, and only if not hidden by a parameter name
7578 (if (and name
7579 (eq synthetic-type 'FUNCTION_EXPRESSION)
7580 (null (js2-scope-get-symbol js2-current-scope
7581 (js2-name-node-name name))))
7582 (js2-define-symbol js2-FUNCTION
7583 (js2-name-node-name name)
7584 fn-node))
7585 (if (and name
7586 (not (eq function-type 'FUNCTION_EXPRESSION)))
7587 (js2-record-imenu-functions fn-node)))
7588 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7589 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7590 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7591 ;; We wait until after parsing the function to set its parent scope,
7592 ;; since `js2-define-symbol' needs the defining-scope check to stop
7593 ;; at the function boundary when checking for redeclarations.
7594 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7595 fn-node))
7596
7597 (defun js2-parse-statements (&optional parent)
7598 "Parse a statement list. Last token consumed must be js2-LC.
7599
7600 PARENT can be a `js2-block-node', in which case the statements are
7601 appended to PARENT. Otherwise a new `js2-block-node' is created
7602 and returned.
7603
7604 This function does not match the closing js2-RC: the caller
7605 matches the RC so it can provide a suitable error message if not
7606 matched. This means it's up to the caller to set the length of
7607 the node to include the closing RC. The node start pos is set to
7608 the absolute buffer start position, and the caller should fix it
7609 up to be relative to the parent node. All children of this block
7610 node are given relative start positions and correct lengths."
7611 (let ((pn (or parent (make-js2-block-node)))
7612 tt)
7613 (setf (js2-node-pos pn) js2-token-beg)
7614 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7615 (/= tt js2-RC))
7616 (js2-block-node-push pn (js2-parse-statement)))
7617 pn))
7618
7619 (defun js2-parse-statement ()
7620 (let (tt pn beg end)
7621 ;; coarse-grained user-interrupt check - needs work
7622 (and js2-parse-interruptable-p
7623 (zerop (% (incf js2-parse-stmt-count)
7624 js2-statements-per-pause))
7625 (input-pending-p)
7626 (throw 'interrupted t))
7627 (setq pn (js2-statement-helper))
7628 ;; no-side-effects warning check
7629 (unless (js2-node-has-side-effects pn)
7630 (setq end (js2-node-end pn))
7631 (save-excursion
7632 (goto-char end)
7633 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7634 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7635 pn))
7636
7637 ;; These correspond to the switch cases in Parser.statementHelper
7638 (defconst js2-parsers
7639 (let ((parsers (make-vector js2-num-tokens
7640 #'js2-parse-expr-stmt)))
7641 (aset parsers js2-BREAK #'js2-parse-break)
7642 (aset parsers js2-CONST #'js2-parse-const-var)
7643 (aset parsers js2-CONTINUE #'js2-parse-continue)
7644 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7645 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7646 (aset parsers js2-DO #'js2-parse-do)
7647 (aset parsers js2-FOR #'js2-parse-for)
7648 (aset parsers js2-FUNCTION #'js2-function-parser)
7649 (aset parsers js2-IF #'js2-parse-if)
7650 (aset parsers js2-LC #'js2-parse-block)
7651 (aset parsers js2-LET #'js2-parse-let-stmt)
7652 (aset parsers js2-NAME #'js2-parse-name-or-label)
7653 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7654 (aset parsers js2-SEMI #'js2-parse-semi)
7655 (aset parsers js2-SWITCH #'js2-parse-switch)
7656 (aset parsers js2-THROW #'js2-parse-throw)
7657 (aset parsers js2-TRY #'js2-parse-try)
7658 (aset parsers js2-VAR #'js2-parse-const-var)
7659 (aset parsers js2-WHILE #'js2-parse-while)
7660 (aset parsers js2-WITH #'js2-parse-with)
7661 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7662 parsers)
7663 "A vector mapping token types to parser functions.")
7664
7665 (defsubst js2-parse-warn-missing-semi (beg end)
7666 (and js2-mode-show-strict-warnings
7667 js2-strict-missing-semi-warning
7668 (js2-add-strict-warning
7669 "msg.missing.semi" nil
7670 ;; back up to beginning of statement or line
7671 (max beg (save-excursion
7672 (goto-char end)
7673 (point-at-bol)))
7674 end)))
7675
7676 (defconst js2-no-semi-insertion
7677 (list js2-IF
7678 js2-SWITCH
7679 js2-WHILE
7680 js2-DO
7681 js2-FOR
7682 js2-TRY
7683 js2-WITH
7684 js2-LC
7685 js2-ERROR
7686 js2-SEMI
7687 js2-FUNCTION)
7688 "List of tokens that don't do automatic semicolon insertion.")
7689
7690 (defconst js2-autoinsert-semi-and-warn
7691 (list js2-ERROR js2-EOF js2-RC))
7692
7693 (defun js2-statement-helper ()
7694 (let* ((tt (js2-peek-token))
7695 (first-tt tt)
7696 (beg js2-token-beg)
7697 (parser (if (= tt js2-ERROR)
7698 #'js2-parse-semi
7699 (aref js2-parsers tt)))
7700 pn
7701 tt-flagged)
7702 ;; If the statement is set, then it's been told its label by now.
7703 (and js2-labeled-stmt
7704 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7705 (setq js2-labeled-stmt nil))
7706 (setq pn (funcall parser))
7707 ;; Don't do auto semi insertion for certain statement types.
7708 (unless (or (memq first-tt js2-no-semi-insertion)
7709 (js2-labeled-stmt-node-p pn))
7710 (js2-auto-insert-semicolon pn))
7711 pn))
7712
7713 (defun js2-auto-insert-semicolon (pn)
7714 (let* ((tt-flagged (js2-peek-flagged-token))
7715 (tt (logand tt-flagged js2-clear-ti-mask))
7716 (pos (js2-node-pos pn)))
7717 (cond
7718 ((= tt js2-SEMI)
7719 ;; Consume ';' as a part of expression
7720 (js2-consume-token)
7721 ;; extend the node bounds to include the semicolon.
7722 (setf (js2-node-len pn) (- js2-token-end pos)))
7723 ((memq tt js2-autoinsert-semi-and-warn)
7724 ;; Autoinsert ;
7725 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7726 (t
7727 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7728 ;; Report error if no EOL or autoinsert ';' otherwise
7729 (js2-report-error "msg.no.semi.stmt")
7730 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7731
7732 (defun js2-parse-condition ()
7733 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7734 The parens are discarded and the expression node is returned.
7735 The `pos' field of the return value is set to an absolute position
7736 that must be fixed up by the caller.
7737 Return value is a list (EXPR LP RP), with absolute paren positions."
7738 (let (pn lp rp)
7739 (if (js2-must-match js2-LP "msg.no.paren.cond")
7740 (setq lp js2-token-beg))
7741 (setq pn (js2-parse-expr))
7742 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7743 (setq rp js2-token-beg))
7744 ;; Report strict warning on code like "if (a = 7) ..."
7745 (if (and js2-strict-cond-assign-warning
7746 (js2-assign-node-p pn))
7747 (js2-add-strict-warning "msg.equal.as.assign" nil
7748 (js2-node-pos pn)
7749 (+ (js2-node-pos pn)
7750 (js2-node-len pn))))
7751 (list pn lp rp)))
7752
7753 (defun js2-parse-if ()
7754 "Parser for if-statement. Last matched token must be js2-IF."
7755 (let ((pos js2-token-beg)
7756 cond
7757 if-true
7758 if-false
7759 else-pos
7760 end
7761 pn)
7762 (js2-consume-token)
7763 (setq cond (js2-parse-condition)
7764 if-true (js2-parse-statement)
7765 if-false (if (js2-match-token js2-ELSE)
7766 (progn
7767 (setq else-pos (- js2-token-beg pos))
7768 (js2-parse-statement)))
7769 end (js2-node-end (or if-false if-true))
7770 pn (make-js2-if-node :pos pos
7771 :len (- end pos)
7772 :condition (car cond)
7773 :then-part if-true
7774 :else-part if-false
7775 :else-pos else-pos
7776 :lp (js2-relpos (second cond) pos)
7777 :rp (js2-relpos (third cond) pos)))
7778 (js2-node-add-children pn (car cond) if-true if-false)
7779 pn))
7780
7781 (defun js2-parse-switch ()
7782 "Parser for if-statement. Last matched token must be js2-SWITCH."
7783 (let ((pos js2-token-beg)
7784 tt
7785 pn
7786 discriminant
7787 has-default
7788 case-expr
7789 case-node
7790 case-pos
7791 cases
7792 stmt
7793 lp
7794 rp)
7795 (js2-consume-token)
7796 (if (js2-must-match js2-LP "msg.no.paren.switch")
7797 (setq lp js2-token-beg))
7798 (setq discriminant (js2-parse-expr)
7799 pn (make-js2-switch-node :discriminant discriminant
7800 :pos pos
7801 :lp (js2-relpos lp pos)))
7802 (js2-node-add-children pn discriminant)
7803 (js2-enter-switch pn)
7804 (unwind-protect
7805 (progn
7806 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7807 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7808 (js2-must-match js2-LC "msg.no.brace.switch")
7809 (catch 'break
7810 (while t
7811 (setq tt (js2-next-token)
7812 case-pos js2-token-beg)
7813 (cond
7814 ((= tt js2-RC)
7815 (setf (js2-node-len pn) (- js2-token-end pos))
7816 (throw 'break nil)) ; done
7817 ((= tt js2-CASE)
7818 (setq case-expr (js2-parse-expr))
7819 (js2-must-match js2-COLON "msg.no.colon.case"))
7820 ((= tt js2-DEFAULT)
7821 (if has-default
7822 (js2-report-error "msg.double.switch.default"))
7823 (setq has-default t
7824 case-expr nil)
7825 (js2-must-match js2-COLON "msg.no.colon.case"))
7826 (t
7827 (js2-report-error "msg.bad.switch")
7828 (throw 'break nil)))
7829 (setq case-node (make-js2-case-node :pos case-pos
7830 :len (- js2-token-end case-pos)
7831 :expr case-expr))
7832 (js2-node-add-children case-node case-expr)
7833 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7834 (/= tt js2-CASE)
7835 (/= tt js2-DEFAULT)
7836 (/= tt js2-EOF))
7837 (setf stmt (js2-parse-statement)
7838 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7839 (js2-block-node-push case-node stmt))
7840 (push case-node cases)))
7841 ;; add cases last, as pushing reverses the order to be correct
7842 (dolist (kid cases)
7843 (js2-node-add-children pn kid)
7844 (push kid (js2-switch-node-cases pn)))
7845 pn) ; return value
7846 (js2-exit-switch))))
7847
7848 (defun js2-parse-while ()
7849 "Parser for while-statement. Last matched token must be js2-WHILE."
7850 (let ((pos js2-token-beg)
7851 (pn (make-js2-while-node))
7852 cond
7853 body)
7854 (js2-consume-token)
7855 (js2-enter-loop pn)
7856 (unwind-protect
7857 (progn
7858 (setf cond (js2-parse-condition)
7859 (js2-while-node-condition pn) (car cond)
7860 body (js2-parse-statement)
7861 (js2-while-node-body pn) body
7862 (js2-node-len pn) (- (js2-node-end body) pos)
7863 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7864 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7865 (js2-node-add-children pn body (car cond)))
7866 (js2-exit-loop))
7867 pn))
7868
7869 (defun js2-parse-do ()
7870 "Parser for do-statement. Last matched token must be js2-DO."
7871 (let ((pos js2-token-beg)
7872 (pn (make-js2-do-node))
7873 cond
7874 body
7875 end)
7876 (js2-consume-token)
7877 (js2-enter-loop pn)
7878 (unwind-protect
7879 (progn
7880 (setq body (js2-parse-statement))
7881 (js2-must-match js2-WHILE "msg.no.while.do")
7882 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7883 cond (js2-parse-condition)
7884 (js2-do-node-condition pn) (car cond)
7885 (js2-do-node-body pn) body
7886 end js2-ts-cursor
7887 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7888 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7889 (js2-node-add-children pn (car cond) body))
7890 (js2-exit-loop))
7891 ;; Always auto-insert semicolon to follow SpiderMonkey:
7892 ;; It is required by ECMAScript but is ignored by the rest of
7893 ;; world; see bug 238945
7894 (if (js2-match-token js2-SEMI)
7895 (setq end js2-ts-cursor))
7896 (setf (js2-node-len pn) (- end pos))
7897 pn))
7898
7899 (defun js2-parse-for ()
7900 "Parser for for-statement. Last matched token must be js2-FOR.
7901 Parses for, for-in, and for each-in statements."
7902 (let ((for-pos js2-token-beg)
7903 pn
7904 is-for-each
7905 is-for-in
7906 in-pos
7907 each-pos
7908 tmp-pos
7909 init ; Node init is also foo in 'foo in object'
7910 cond ; Node cond is also object in 'foo in object'
7911 incr ; 3rd section of for-loop initializer
7912 body
7913 tt
7914 lp
7915 rp)
7916 (js2-consume-token)
7917 ;; See if this is a for each () instead of just a for ()
7918 (when (js2-match-token js2-NAME)
7919 (if (string= "each" js2-ts-string)
7920 (progn
7921 (setq is-for-each t
7922 each-pos (- js2-token-beg for-pos)) ; relative
7923 (js2-record-face 'font-lock-keyword-face))
7924 (js2-report-error "msg.no.paren.for")))
7925 (if (js2-must-match js2-LP "msg.no.paren.for")
7926 (setq lp (- js2-token-beg for-pos)))
7927 (setq tt (js2-peek-token))
7928 ;; 'for' makes local scope
7929 (js2-push-scope (make-js2-scope))
7930 (unwind-protect
7931 ;; parse init clause
7932 (let ((js2-in-for-init t)) ; set as dynamic variable
7933 (cond
7934 ((= tt js2-SEMI)
7935 (setq init (make-js2-empty-expr-node)))
7936 ((or (= tt js2-VAR) (= tt js2-LET))
7937 (js2-consume-token)
7938 (setq init (js2-parse-variables tt js2-token-beg)))
7939 (t
7940 (setq init (js2-parse-expr)))))
7941 (if (js2-match-token js2-IN)
7942 (setq is-for-in t
7943 in-pos (- js2-token-beg for-pos)
7944 ;; scope of iteration target object is not the scope we've created above.
7945 ;; stash current scope temporary.
7946 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7947 (js2-parse-expr))) ; object over which we're iterating
7948 ;; else ordinary for loop - parse cond and incr
7949 (js2-must-match js2-SEMI "msg.no.semi.for")
7950 (setq cond (if (= (js2-peek-token) js2-SEMI)
7951 (make-js2-empty-expr-node) ; no loop condition
7952 (js2-parse-expr)))
7953 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7954 (setq tmp-pos js2-token-end
7955 incr (if (= (js2-peek-token) js2-RP)
7956 (make-js2-empty-expr-node :pos tmp-pos)
7957 (js2-parse-expr))))
7958 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7959 (setq rp (- js2-token-beg for-pos)))
7960 (if (not is-for-in)
7961 (setq pn (make-js2-for-node :init init
7962 :condition cond
7963 :update incr
7964 :lp lp
7965 :rp rp))
7966 ;; cond could be null if 'in obj' got eaten by the init node.
7967 (if (js2-infix-node-p init)
7968 ;; it was (foo in bar) instead of (var foo in bar)
7969 (setq cond (js2-infix-node-right init)
7970 init (js2-infix-node-left init))
7971 (if (and (js2-var-decl-node-p init)
7972 (> (length (js2-var-decl-node-kids init)) 1))
7973 (js2-report-error "msg.mult.index")))
7974 (setq pn (make-js2-for-in-node :iterator init
7975 :object cond
7976 :in-pos in-pos
7977 :foreach-p is-for-each
7978 :each-pos each-pos
7979 :lp lp
7980 :rp rp)))
7981 (unwind-protect
7982 (progn
7983 (js2-enter-loop pn)
7984 ;; We have to parse the body -after- creating the loop node,
7985 ;; so that the loop node appears in the js2-loop-set, allowing
7986 ;; break/continue statements to find the enclosing loop.
7987 (setf body (js2-parse-statement)
7988 (js2-loop-node-body pn) body
7989 (js2-node-pos pn) for-pos
7990 (js2-node-len pn) (- (js2-node-end body) for-pos))
7991 (js2-node-add-children pn init cond incr body))
7992 ;; finally
7993 (js2-exit-loop))
7994 (js2-pop-scope))
7995 pn))
7996
7997 (defun js2-parse-try ()
7998 "Parser for try-statement. Last matched token must be js2-TRY."
7999 (let ((try-pos js2-token-beg)
8000 try-end
8001 try-block
8002 catch-blocks
8003 finally-block
8004 saw-default-catch
8005 peek
8006 param
8007 catch-cond
8008 catch-node
8009 guard-kwd
8010 catch-pos
8011 finally-pos
8012 pn
8013 block
8014 lp
8015 rp)
8016 (js2-consume-token)
8017 (if (/= (js2-peek-token) js2-LC)
8018 (js2-report-error "msg.no.brace.try"))
8019 (setq try-block (js2-parse-statement)
8020 try-end (js2-node-end try-block)
8021 peek (js2-peek-token))
8022 (cond
8023 ((= peek js2-CATCH)
8024 (while (js2-match-token js2-CATCH)
8025 (setq catch-pos js2-token-beg
8026 guard-kwd nil
8027 catch-cond nil
8028 lp nil
8029 rp nil)
8030 (if saw-default-catch
8031 (js2-report-error "msg.catch.unreachable"))
8032 (if (js2-must-match js2-LP "msg.no.paren.catch")
8033 (setq lp (- js2-token-beg catch-pos)))
8034 (js2-push-scope (make-js2-scope))
8035 (let ((tt (js2-peek-token)))
8036 (cond
8037 ;; destructuring pattern
8038 ;; catch ({ message, file }) { ... }
8039 ((or (= tt js2-LB) (= tt js2-LC))
8040 (setq param
8041 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8042 js2-LET nil)))
8043 ;; simple name
8044 (t
8045 (js2-must-match js2-NAME "msg.bad.catchcond")
8046 (setq param (js2-create-name-node))
8047 (js2-define-symbol js2-LET js2-ts-string param))))
8048 ;; pattern guard
8049 (if (js2-match-token js2-IF)
8050 (setq guard-kwd (- js2-token-beg catch-pos)
8051 catch-cond (js2-parse-expr))
8052 (setq saw-default-catch t))
8053 (if (js2-must-match js2-RP "msg.bad.catchcond")
8054 (setq rp (- js2-token-beg catch-pos)))
8055 (js2-must-match js2-LC "msg.no.brace.catchblock")
8056 (setq block (js2-parse-statements)
8057 try-end (js2-node-end block)
8058 catch-node (make-js2-catch-node :pos catch-pos
8059 :param param
8060 :guard-expr catch-cond
8061 :guard-kwd guard-kwd
8062 :block block
8063 :lp lp
8064 :rp rp))
8065 (js2-pop-scope)
8066 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8067 (setq try-end js2-token-beg))
8068 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8069 (js2-node-len catch-node) (- try-end catch-pos))
8070 (js2-node-add-children catch-node param catch-cond block)
8071 (push catch-node catch-blocks)))
8072 ((/= peek js2-FINALLY)
8073 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8074 (js2-node-pos try-block)
8075 (- (setq try-end (js2-node-end try-block))
8076 (js2-node-pos try-block)))))
8077 (when (js2-match-token js2-FINALLY)
8078 (setq finally-pos js2-token-beg
8079 block (js2-parse-statement)
8080 try-end (js2-node-end block)
8081 finally-block (make-js2-finally-node :pos finally-pos
8082 :len (- try-end finally-pos)
8083 :body block))
8084 (js2-node-add-children finally-block block))
8085 (setq pn (make-js2-try-node :pos try-pos
8086 :len (- try-end try-pos)
8087 :try-block try-block
8088 :finally-block finally-block))
8089 (js2-node-add-children pn try-block finally-block)
8090 ;; push them onto the try-node, which reverses and corrects their order
8091 (dolist (cb catch-blocks)
8092 (js2-node-add-children pn cb)
8093 (push cb (js2-try-node-catch-clauses pn)))
8094 pn))
8095
8096 (defun js2-parse-throw ()
8097 "Parser for throw-statement. Last matched token must be js2-THROW."
8098 (let ((pos js2-token-beg)
8099 expr
8100 pn)
8101 (js2-consume-token)
8102 (if (= (js2-peek-token-or-eol) js2-EOL)
8103 ;; ECMAScript does not allow new lines before throw expression,
8104 ;; see bug 256617
8105 (js2-report-error "msg.bad.throw.eol"))
8106 (setq expr (js2-parse-expr)
8107 pn (make-js2-throw-node :pos pos
8108 :len (- (js2-node-end expr) pos)
8109 :expr expr))
8110 (js2-node-add-children pn expr)
8111 pn))
8112
8113 (defsubst js2-match-jump-label-name (label-name)
8114 "If break/continue specified a label, return that label's labeled stmt.
8115 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8116 does not match an existing label, reports an error and returns nil."
8117 (let ((bundle (cdr (assoc label-name js2-label-set))))
8118 (if (null bundle)
8119 (js2-report-error "msg.undef.label"))
8120 bundle))
8121
8122 (defun js2-parse-break ()
8123 "Parser for break-statement. Last matched token must be js2-BREAK."
8124 (let ((pos js2-token-beg)
8125 (end js2-token-end)
8126 break-target ; statement to break from
8127 break-label ; in "break foo", name-node representing the foo
8128 labels ; matching labeled statement to break to
8129 pn)
8130 (js2-consume-token) ; `break'
8131 (when (eq (js2-peek-token-or-eol) js2-NAME)
8132 (js2-consume-token)
8133 (setq break-label (js2-create-name-node)
8134 end (js2-node-end break-label)
8135 ;; matchJumpLabelName only matches if there is one
8136 labels (js2-match-jump-label-name js2-ts-string)
8137 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8138 (unless (or break-target break-label)
8139 ;; no break target specified - try for innermost enclosing loop/switch
8140 (if (null js2-loop-and-switch-set)
8141 (unless break-label
8142 (js2-report-error "msg.bad.break" nil pos (length "break")))
8143 (setq break-target (car js2-loop-and-switch-set))))
8144 (setq pn (make-js2-break-node :pos pos
8145 :len (- end pos)
8146 :label break-label
8147 :target break-target))
8148 (js2-node-add-children pn break-label) ; but not break-target
8149 pn))
8150
8151 (defun js2-parse-continue ()
8152 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8153 (let ((pos js2-token-beg)
8154 (end js2-token-end)
8155 label ; optional user-specified label, a `js2-name-node'
8156 labels ; current matching labeled stmt, if any
8157 target ; the `js2-loop-node' target of this continue stmt
8158 pn)
8159 (js2-consume-token) ; `continue'
8160 (when (= (js2-peek-token-or-eol) js2-NAME)
8161 (js2-consume-token)
8162 (setq label (js2-create-name-node)
8163 end (js2-node-end label)
8164 ;; matchJumpLabelName only matches if there is one
8165 labels (js2-match-jump-label-name js2-ts-string)))
8166 (cond
8167 ((null labels) ; no current label to go to
8168 (if (null js2-loop-set) ; no loop to continue to
8169 (js2-report-error "msg.continue.outside" nil pos
8170 (length "continue"))
8171 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8172 (t
8173 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8174 (setq target (js2-labeled-stmt-node-stmt labels))
8175 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8176 (setq pn (make-js2-continue-node :pos pos
8177 :len (- end pos)
8178 :label label
8179 :target target))
8180 (js2-node-add-children pn label) ; but not target - it's not our child
8181 pn))
8182
8183 (defun js2-parse-with ()
8184 "Parser for with-statement. Last matched token must be js2-WITH."
8185 (js2-consume-token)
8186 (let ((pos js2-token-beg)
8187 obj body pn lp rp)
8188 (if (js2-must-match js2-LP "msg.no.paren.with")
8189 (setq lp js2-token-beg))
8190 (setq obj (js2-parse-expr))
8191 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8192 (setq rp js2-token-beg))
8193 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8194 (setq body (js2-parse-statement)))
8195 (setq pn (make-js2-with-node :pos pos
8196 :len (- (js2-node-end body) pos)
8197 :object obj
8198 :body body
8199 :lp (js2-relpos lp pos)
8200 :rp (js2-relpos rp pos)))
8201 (js2-node-add-children pn obj body)
8202 pn))
8203
8204 (defun js2-parse-const-var ()
8205 "Parser for var- or const-statement.
8206 Last matched token must be js2-CONST or js2-VAR."
8207 (let ((tt (js2-peek-token))
8208 (pos js2-token-beg)
8209 expr
8210 pn)
8211 (js2-consume-token)
8212 (setq expr (js2-parse-variables tt js2-token-beg)
8213 pn (make-js2-expr-stmt-node :pos pos
8214 :len (- (js2-node-end expr) pos)
8215 :expr expr))
8216 (js2-node-add-children pn expr)
8217 pn))
8218
8219 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8220 (let ((pn (make-js2-expr-stmt-node :pos pos
8221 :len (js2-node-len expr)
8222 :type (if (js2-inside-function)
8223 js2-EXPR_VOID
8224 js2-EXPR_RESULT)
8225 :expr expr)))
8226 (if add-child
8227 (js2-node-add-children pn expr))
8228 pn))
8229
8230 (defun js2-parse-let-stmt ()
8231 "Parser for let-statement. Last matched token must be js2-LET."
8232 (js2-consume-token)
8233 (let ((pos js2-token-beg)
8234 expr
8235 pn)
8236 (if (= (js2-peek-token) js2-LP)
8237 ;; let expression in statement context
8238 (setq expr (js2-parse-let pos 'statement)
8239 pn (js2-wrap-with-expr-stmt pos expr t))
8240 ;; else we're looking at a statement like let x=6, y=7;
8241 (setf expr (js2-parse-variables js2-LET pos)
8242 pn (js2-wrap-with-expr-stmt pos expr t)
8243 (js2-node-type pn) js2-EXPR_RESULT))
8244 pn))
8245
8246 (defun js2-parse-ret-yield ()
8247 (js2-parse-return-or-yield (js2-peek-token) nil))
8248
8249 (defconst js2-parse-return-stmt-enders
8250 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8251
8252 (defsubst js2-now-all-set (before after mask)
8253 "Return whether or not the bits in the mask have changed to all set.
8254 BEFORE is bits before change, AFTER is bits after change, and MASK is
8255 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8256 but not BEFORE."
8257 (and (/= (logand before mask) mask)
8258 (= (logand after mask) mask)))
8259
8260 (defun js2-parse-return-or-yield (tt expr-context)
8261 (let ((pos js2-token-beg)
8262 (end js2-token-end)
8263 (before js2-end-flags)
8264 (inside-function (js2-inside-function))
8265 e
8266 ret
8267 name)
8268 (unless inside-function
8269 (js2-report-error (if (eq tt js2-RETURN)
8270 "msg.bad.return"
8271 "msg.bad.yield")))
8272 (js2-consume-token)
8273 ;; This is ugly, but we don't want to require a semicolon.
8274 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8275 (setq e (js2-parse-expr)
8276 end (js2-node-end e)))
8277 (cond
8278 ((eq tt js2-RETURN)
8279 (js2-set-flag js2-end-flags (if (null e)
8280 js2-end-returns
8281 js2-end-returns-value))
8282 (setq ret (make-js2-return-node :pos pos
8283 :len (- end pos)
8284 :retval e))
8285 (js2-node-add-children ret e)
8286 ;; See if we need a strict mode warning.
8287 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8288 ;; more thorough and accurate than this before/after flag check.
8289 ;; E.g. if there's a finally-block that always returns, we shouldn't
8290 ;; show a warning generated by inconsistent returns in the catch blocks.
8291 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8292 ;; so we know which returns/yields to highlight, and we should get rid of
8293 ;; all the checking in `js2-parse-return-or-yield'.
8294 (if (and js2-strict-inconsistent-return-warning
8295 (js2-now-all-set before js2-end-flags
8296 (logior js2-end-returns js2-end-returns-value)))
8297 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8298 (t
8299 (unless (js2-inside-function)
8300 (js2-report-error "msg.bad.yield"))
8301 (js2-set-flag js2-end-flags js2-end-yields)
8302 (setq ret (make-js2-yield-node :pos pos
8303 :len (- end pos)
8304 :value e))
8305 (js2-node-add-children ret e)
8306 (unless expr-context
8307 (setq e ret
8308 ret (js2-wrap-with-expr-stmt pos e t))
8309 (js2-set-requires-activation)
8310 (js2-set-is-generator))))
8311 ;; see if we are mixing yields and value returns.
8312 (when (and inside-function
8313 (js2-now-all-set before js2-end-flags
8314 (logior js2-end-yields js2-end-returns-value)))
8315 (setq name (js2-function-name js2-current-script-or-fn))
8316 (if (zerop (length name))
8317 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8318 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8319 ret))
8320
8321 (defun js2-parse-debugger ()
8322 (js2-consume-token)
8323 (make-js2-keyword-node :type js2-DEBUGGER))
8324
8325 (defun js2-parse-block ()
8326 "Parser for a curly-delimited statement block.
8327 Last token matched must be js2-LC."
8328 (let ((pos js2-token-beg)
8329 (pn (make-js2-scope)))
8330 (js2-consume-token)
8331 (js2-push-scope pn)
8332 (unwind-protect
8333 (progn
8334 (js2-parse-statements pn)
8335 (js2-must-match js2-RC "msg.no.brace.block")
8336 (setf (js2-node-len pn) (- js2-token-end pos)))
8337 (js2-pop-scope))
8338 pn))
8339
8340 ;; for js2-ERROR too, to have a node for error recovery to work on
8341 (defun js2-parse-semi ()
8342 "Parse a statement or handle an error.
8343 Last matched token is js-SEMI or js-ERROR."
8344 (let ((tt (js2-peek-token)) pos len)
8345 (js2-consume-token)
8346 (if (eq tt js2-SEMI)
8347 (make-js2-empty-expr-node :len 1)
8348 (setq pos js2-token-beg
8349 len (- js2-token-beg pos))
8350 (js2-report-error "msg.syntax" nil pos len)
8351 (make-js2-error-node :pos pos :len len))))
8352
8353 (defun js2-parse-default-xml-namespace ()
8354 "Parse a `default xml namespace = <expr>' e4x statement."
8355 (let ((pos js2-token-beg)
8356 end len expr unary es)
8357 (js2-consume-token)
8358 (js2-must-have-xml)
8359 (js2-set-requires-activation)
8360 (setq len (- js2-ts-cursor pos))
8361 (unless (and (js2-match-token js2-NAME)
8362 (string= js2-ts-string "xml"))
8363 (js2-report-error "msg.bad.namespace" nil pos len))
8364 (unless (and (js2-match-token js2-NAME)
8365 (string= js2-ts-string "namespace"))
8366 (js2-report-error "msg.bad.namespace" nil pos len))
8367 (unless (js2-match-token js2-ASSIGN)
8368 (js2-report-error "msg.bad.namespace" nil pos len))
8369 (setq expr (js2-parse-expr)
8370 end (js2-node-end expr)
8371 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8372 :pos pos
8373 :len (- end pos)
8374 :operand expr))
8375 (js2-node-add-children unary expr)
8376 (make-js2-expr-stmt-node :pos pos
8377 :len (- end pos)
8378 :expr unary)))
8379
8380 (defun js2-record-label (label bundle)
8381 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8382 (js2-consume-token)
8383 (let ((name (js2-label-node-name label))
8384 labeled-stmt
8385 dup)
8386 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8387 ;; flag both labels if possible when used in editing mode
8388 (if (and js2-parse-ide-mode
8389 (setq dup (js2-get-label-by-name labeled-stmt name)))
8390 (js2-report-error "msg.dup.label" nil
8391 (js2-node-abs-pos dup) (js2-node-len dup)))
8392 (js2-report-error "msg.dup.label" nil
8393 (js2-node-pos label) (js2-node-len label)))
8394 (js2-labeled-stmt-node-add-label bundle label)
8395 (js2-node-add-children bundle label)
8396 ;; Add one reference to the bundle per label in `js2-label-set'
8397 (push (cons name bundle) js2-label-set)))
8398
8399 (defun js2-parse-name-or-label ()
8400 "Parser for identifier or label. Last token matched must be js2-NAME.
8401 Called when we found a name in a statement context. If it's a label, we gather
8402 up any following labels and the next non-label statement into a
8403 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8404 expression and return it wrapped in a `js2-expr-stmt-node'."
8405 (let ((pos js2-token-beg)
8406 (end js2-token-end)
8407 expr
8408 stmt
8409 pn
8410 bundle
8411 (continue t))
8412 ;; set check for label and call down to `js2-parse-primary-expr'
8413 (js2-set-check-for-label)
8414 (setq expr (js2-parse-expr))
8415 (if (/= (js2-node-type expr) js2-LABEL)
8416 ;; Parsed non-label expression - wrap with expression stmt.
8417 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8418 ;; else parsed a label
8419 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8420 (js2-record-label expr bundle)
8421 ;; look for more labels
8422 (while (and continue (= (js2-peek-token) js2-NAME))
8423 (js2-set-check-for-label)
8424 (setq expr (js2-parse-expr))
8425 (if (/= (js2-node-type expr) js2-LABEL)
8426 (progn
8427 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8428 continue nil)
8429 (js2-auto-insert-semicolon stmt))
8430 (js2-record-label expr bundle)))
8431 ;; no more labels; now parse the labeled statement
8432 (unwind-protect
8433 (unless stmt
8434 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8435 (setq stmt (js2-statement-helper))))
8436 ;; remove the labels for this statement from the global set
8437 (dolist (label (js2-labeled-stmt-node-labels bundle))
8438 (setq js2-label-set (remove label js2-label-set))))
8439 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8440 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8441 (js2-node-add-children bundle stmt)
8442 bundle)))
8443
8444 (defun js2-parse-expr-stmt ()
8445 "Default parser in statement context, if no recognized statement found."
8446 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8447
8448 (defun js2-parse-variables (decl-type pos)
8449 "Parse a comma-separated list of variable declarations.
8450 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8451
8452 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8453 For 'var' or 'const', the keyword should be the token last scanned.
8454
8455 POS is the position where the node should start. It's sometimes the
8456 var/const/let keyword, and other times the beginning of the first token
8457 in the first variable declaration.
8458
8459 Returns the parsed `js2-var-decl-node' expression node."
8460 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8461 :pos pos))
8462 destructuring
8463 kid-pos
8464 tt
8465 init
8466 name
8467 end
8468 nbeg nend
8469 vi
8470 (continue t))
8471 ;; Example:
8472 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8473 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8474 ;; var {a, b} = baz;
8475 (while continue
8476 (setq destructuring nil
8477 name nil
8478 tt (js2-peek-token)
8479 kid-pos js2-token-beg
8480 end js2-token-end
8481 init nil)
8482 (if (or (= tt js2-LB) (= tt js2-LC))
8483 ;; Destructuring assignment, e.g., var [a, b] = ...
8484 (setq destructuring (js2-parse-primary-expr-lhs)
8485 end (js2-node-end destructuring))
8486 ;; Simple variable name
8487 (when (js2-must-match js2-NAME "msg.bad.var")
8488 (setq name (js2-create-name-node)
8489 nbeg js2-token-beg
8490 nend js2-token-end
8491 end nend)
8492 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8493 (when (js2-match-token js2-ASSIGN)
8494 (setq init (js2-parse-assign-expr)
8495 end (js2-node-end init))
8496 (if (and js2-parse-ide-mode
8497 (or (js2-object-node-p init)
8498 (js2-function-node-p init)))
8499 (js2-record-imenu-functions init name)))
8500 (when name
8501 (js2-set-face nbeg nend (if (js2-function-node-p init)
8502 'font-lock-function-name-face
8503 'font-lock-variable-name-face)
8504 'record))
8505 (setq vi (make-js2-var-init-node :pos kid-pos
8506 :len (- end kid-pos)
8507 :type decl-type))
8508 (if destructuring
8509 (progn
8510 (if (and (null init) (not js2-in-for-init))
8511 (js2-report-error "msg.destruct.assign.no.init"))
8512 (js2-define-destruct-symbols destructuring
8513 decl-type
8514 'font-lock-variable-name-face)
8515 (setf (js2-var-init-node-target vi) destructuring))
8516 (setf (js2-var-init-node-target vi) name))
8517 (setf (js2-var-init-node-initializer vi) init)
8518 (js2-node-add-children vi name destructuring init)
8519 (js2-block-node-push result vi)
8520 (unless (js2-match-token js2-COMMA)
8521 (setq continue nil)))
8522 (setf (js2-node-len result) (- end pos))
8523 result))
8524
8525 (defun js2-parse-let (pos &optional stmt-p)
8526 "Parse a let expression or statement.
8527 A let-expression is of the form `let (vars) expr'.
8528 A let-statment is of the form `let (vars) {statements}'.
8529 The third form of let is a variable declaration list, handled
8530 by `js2-parse-variables'."
8531 (let ((pn (make-js2-let-node :pos pos))
8532 beg vars body)
8533 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8534 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8535 (js2-push-scope pn)
8536 (unwind-protect
8537 (progn
8538 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8539 (if (js2-must-match js2-RP "msg.no.paren.let")
8540 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8541 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8542 ;; let statement
8543 (progn
8544 (js2-consume-token)
8545 (setf beg js2-token-beg ; position stmt at LC
8546 body (js2-parse-statements))
8547 (js2-must-match js2-RC "msg.no.curly.let")
8548 (setf (js2-node-len body) (- js2-token-end beg)
8549 (js2-node-len pn) (- js2-token-end pos)
8550 (js2-let-node-body pn) body
8551 (js2-node-type pn) js2-LET))
8552 ;; let expression
8553 (setf body (js2-parse-expr)
8554 (js2-node-len pn) (- (js2-node-end body) pos)
8555 (js2-let-node-body pn) body))
8556 (js2-node-add-children pn vars body))
8557 (js2-pop-scope))
8558 pn))
8559
8560 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8561 (js2-scope-put-symbol (or scope js2-current-scope)
8562 name
8563 (make-js2-symbol decl-type name node)))
8564
8565 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8566 "Define a symbol in the current scope.
8567 If NODE is non-nil, it is the AST node associated with the symbol."
8568 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8569 (symbol (if defining-scope
8570 (js2-scope-get-symbol defining-scope name)))
8571 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8572 (cond
8573 ((and symbol ; already defined
8574 (or (= sdt js2-CONST) ; old version is const
8575 (= decl-type js2-CONST) ; new version is const
8576 ;; two let-bound vars in this block have same name
8577 (and (= sdt js2-LET)
8578 (eq defining-scope js2-current-scope))))
8579 (js2-report-error
8580 (cond
8581 ((= sdt js2-CONST) "msg.const.redecl")
8582 ((= sdt js2-LET) "msg.let.redecl")
8583 ((= sdt js2-VAR) "msg.var.redecl")
8584 ((= sdt js2-FUNCTION) "msg.function.redecl")
8585 (t "msg.parm.redecl"))
8586 name))
8587 ((= decl-type js2-LET)
8588 (if (and (not ignore-not-in-block)
8589 (or (= (js2-node-type js2-current-scope) js2-IF)
8590 (js2-loop-node-p js2-current-scope)))
8591 (js2-report-error "msg.let.decl.not.in.block")
8592 (js2-define-new-symbol decl-type name node)))
8593 ((or (= decl-type js2-VAR)
8594 (= decl-type js2-CONST)
8595 (= decl-type js2-FUNCTION))
8596 (if symbol
8597 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8598 (js2-add-strict-warning "msg.var.redecl" name)
8599 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8600 (js2-add-strict-warning "msg.var.hides.arg" name)))
8601 (js2-define-new-symbol decl-type name node
8602 js2-current-script-or-fn)))
8603 ((= decl-type js2-LP)
8604 (if symbol
8605 ;; must be duplicate parameter. Second parameter hides the
8606 ;; first, so go ahead and add the second pararameter
8607 (js2-report-warning "msg.dup.parms" name))
8608 (js2-define-new-symbol decl-type name node))
8609 (t (js2-code-bug)))))
8610
8611 (defun js2-parse-expr (&optional oneshot)
8612 (let* ((pn (js2-parse-assign-expr))
8613 (pos (js2-node-pos pn))
8614 left
8615 right
8616 op-pos)
8617 (while (and (not oneshot)
8618 (js2-match-token js2-COMMA))
8619 (setq op-pos (- js2-token-beg pos)) ; relative
8620 (if (= (js2-peek-token) js2-YIELD)
8621 (js2-report-error "msg.yield.parenthesized"))
8622 (setq right (js2-parse-assign-expr)
8623 left pn
8624 pn (make-js2-infix-node :type js2-COMMA
8625 :pos pos
8626 :len (- js2-ts-cursor pos)
8627 :op-pos op-pos
8628 :left left
8629 :right right))
8630 (js2-node-add-children pn left right))
8631 pn))
8632
8633 (defun js2-parse-assign-expr ()
8634 (let ((tt (js2-peek-token))
8635 (pos js2-token-beg)
8636 pn
8637 left
8638 right
8639 op-pos)
8640 (if (= tt js2-YIELD)
8641 (js2-parse-return-or-yield tt t)
8642 ;; not yield - parse assignment expression
8643 (setq pn (js2-parse-cond-expr)
8644 tt (js2-peek-token))
8645 (when (and (<= js2-first-assign tt)
8646 (<= tt js2-last-assign))
8647 ;; tt express assignment (=, |=, ^=, ..., %=)
8648 (js2-consume-token)
8649 (setq op-pos (- js2-token-beg pos) ; relative
8650 left pn
8651 right (js2-parse-assign-expr)
8652 pn (make-js2-assign-node :type tt
8653 :pos pos
8654 :len (- (js2-node-end right) pos)
8655 :op-pos op-pos
8656 :left left
8657 :right right))
8658 (when js2-parse-ide-mode
8659 (js2-highlight-assign-targets pn left right)
8660 (if (or (js2-function-node-p right)
8661 (js2-object-node-p right))
8662 (js2-record-imenu-functions right left)))
8663 ;; do this last so ide checks above can use absolute positions
8664 (js2-node-add-children pn left right))
8665 pn)))
8666
8667 (defun js2-parse-cond-expr ()
8668 (let ((pos js2-token-beg)
8669 (pn (js2-parse-or-expr))
8670 test-expr
8671 if-true
8672 if-false
8673 q-pos
8674 c-pos)
8675 (when (js2-match-token js2-HOOK)
8676 (setq q-pos (- js2-token-beg pos)
8677 if-true (js2-parse-assign-expr))
8678 (js2-must-match js2-COLON "msg.no.colon.cond")
8679 (setq c-pos (- js2-token-beg pos)
8680 if-false (js2-parse-assign-expr)
8681 test-expr pn
8682 pn (make-js2-cond-node :pos pos
8683 :len (- (js2-node-end if-false) pos)
8684 :test-expr test-expr
8685 :true-expr if-true
8686 :false-expr if-false
8687 :q-pos q-pos
8688 :c-pos c-pos))
8689 (js2-node-add-children pn test-expr if-true if-false))
8690 pn))
8691
8692 (defun js2-make-binary (type left parser)
8693 "Helper for constructing a binary-operator AST node.
8694 LEFT is the left-side-expression, already parsed, and the
8695 binary operator should have just been matched.
8696 PARSER is a function to call to parse the right operand,
8697 or a `js2-node' struct if it has already been parsed."
8698 (let* ((pos (js2-node-pos left))
8699 (op-pos (- js2-token-beg pos))
8700 (right (if (js2-node-p parser)
8701 parser
8702 (funcall parser)))
8703 (pn (make-js2-infix-node :type type
8704 :pos pos
8705 :len (- (js2-node-end right) pos)
8706 :op-pos op-pos
8707 :left left
8708 :right right)))
8709 (js2-node-add-children pn left right)
8710 pn))
8711
8712 (defun js2-parse-or-expr ()
8713 (let ((pn (js2-parse-and-expr)))
8714 (when (js2-match-token js2-OR)
8715 (setq pn (js2-make-binary js2-OR
8716 pn
8717 'js2-parse-or-expr)))
8718 pn))
8719
8720 (defun js2-parse-and-expr ()
8721 (let ((pn (js2-parse-bit-or-expr)))
8722 (when (js2-match-token js2-AND)
8723 (setq pn (js2-make-binary js2-AND
8724 pn
8725 'js2-parse-and-expr)))
8726 pn))
8727
8728 (defun js2-parse-bit-or-expr ()
8729 (let ((pn (js2-parse-bit-xor-expr)))
8730 (while (js2-match-token js2-BITOR)
8731 (setq pn (js2-make-binary js2-BITOR
8732 pn
8733 'js2-parse-bit-xor-expr)))
8734 pn))
8735
8736 (defun js2-parse-bit-xor-expr ()
8737 (let ((pn (js2-parse-bit-and-expr)))
8738 (while (js2-match-token js2-BITXOR)
8739 (setq pn (js2-make-binary js2-BITXOR
8740 pn
8741 'js2-parse-bit-and-expr)))
8742 pn))
8743
8744 (defun js2-parse-bit-and-expr ()
8745 (let ((pn (js2-parse-eq-expr)))
8746 (while (js2-match-token js2-BITAND)
8747 (setq pn (js2-make-binary js2-BITAND
8748 pn
8749 'js2-parse-eq-expr)))
8750 pn))
8751
8752 (defconst js2-parse-eq-ops
8753 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8754
8755 (defun js2-parse-eq-expr ()
8756 (let ((pn (js2-parse-rel-expr))
8757 tt)
8758 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8759 (js2-consume-token)
8760 (setq pn (js2-make-binary tt
8761 pn
8762 'js2-parse-rel-expr)))
8763 pn))
8764
8765 (defconst js2-parse-rel-ops
8766 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8767
8768 (defun js2-parse-rel-expr ()
8769 (let ((pn (js2-parse-shift-expr))
8770 (continue t)
8771 tt)
8772 (while continue
8773 (setq tt (js2-peek-token))
8774 (cond
8775 ((and js2-in-for-init (= tt js2-IN))
8776 (setq continue nil))
8777 ((memq tt js2-parse-rel-ops)
8778 (js2-consume-token)
8779 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8780 (t
8781 (setq continue nil))))
8782 pn))
8783
8784 (defconst js2-parse-shift-ops
8785 (list js2-LSH js2-URSH js2-RSH))
8786
8787 (defun js2-parse-shift-expr ()
8788 (let ((pn (js2-parse-add-expr))
8789 tt
8790 (continue t))
8791 (while continue
8792 (setq tt (js2-peek-token))
8793 (if (memq tt js2-parse-shift-ops)
8794 (progn
8795 (js2-consume-token)
8796 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8797 (setq continue nil)))
8798 pn))
8799
8800 (defun js2-parse-add-expr ()
8801 (let ((pn (js2-parse-mul-expr))
8802 tt
8803 (continue t))
8804 (while continue
8805 (setq tt (js2-peek-token))
8806 (if (or (= tt js2-ADD) (= tt js2-SUB))
8807 (progn
8808 (js2-consume-token)
8809 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8810 (setq continue nil)))
8811 pn))
8812
8813 (defconst js2-parse-mul-ops
8814 (list js2-MUL js2-DIV js2-MOD))
8815
8816 (defun js2-parse-mul-expr ()
8817 (let ((pn (js2-parse-unary-expr))
8818 tt
8819 (continue t))
8820 (while continue
8821 (setq tt (js2-peek-token))
8822 (if (memq tt js2-parse-mul-ops)
8823 (progn
8824 (js2-consume-token)
8825 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8826 (setq continue nil)))
8827 pn))
8828
8829 (defsubst js2-make-unary (type parser &rest args)
8830 "Make a unary node of type TYPE.
8831 PARSER is either a node (for postfix operators) or a function to call
8832 to parse the operand (for prefix operators)."
8833 (let* ((pos js2-token-beg)
8834 (postfix (js2-node-p parser))
8835 (expr (if postfix
8836 parser
8837 (apply parser args)))
8838 end
8839 pn)
8840 (if postfix ; e.g. i++
8841 (setq pos (js2-node-pos expr)
8842 end js2-token-end)
8843 (setq end (js2-node-end expr)))
8844 (setq pn (make-js2-unary-node :type type
8845 :pos pos
8846 :len (- end pos)
8847 :operand expr))
8848 (js2-node-add-children pn expr)
8849 pn))
8850
8851 (defconst js2-incrementable-node-types
8852 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8853 "Node types that can be the operand of a ++ or -- operator.")
8854
8855 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8856 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8857 js2-incrementable-node-types)
8858 (js2-report-error (if (= tt js2-INC)
8859 "msg.bad.incr"
8860 "msg.bad.decr")
8861 nil beg (- end beg))))
8862
8863 (defun js2-parse-unary-expr ()
8864 (let ((tt (js2-peek-token))
8865 pn expr beg end)
8866 (cond
8867 ((or (= tt js2-VOID)
8868 (= tt js2-NOT)
8869 (= tt js2-BITNOT)
8870 (= tt js2-TYPEOF))
8871 (js2-consume-token)
8872 (js2-make-unary tt 'js2-parse-unary-expr))
8873 ((= tt js2-ADD)
8874 (js2-consume-token)
8875 ;; Convert to special POS token in decompiler and parse tree
8876 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8877 ((= tt js2-SUB)
8878 (js2-consume-token)
8879 ;; Convert to special NEG token in decompiler and parse tree
8880 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8881 ((or (= tt js2-INC)
8882 (= tt js2-DEC))
8883 (js2-consume-token)
8884 (prog1
8885 (setq beg js2-token-beg
8886 end js2-token-end
8887 expr (js2-make-unary tt 'js2-parse-member-expr t))
8888 (js2-check-bad-inc-dec tt beg end expr)))
8889 ((= tt js2-DELPROP)
8890 (js2-consume-token)
8891 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8892 ((= tt js2-ERROR)
8893 (js2-consume-token)
8894 (make-js2-error-node)) ; try to continue
8895 ((and (= tt js2-LT)
8896 js2-compiler-xml-available)
8897 ;; XML stream encountered in expression.
8898 (js2-consume-token)
8899 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8900 (t
8901 (setq pn (js2-parse-member-expr t)
8902 ;; Don't look across a newline boundary for a postfix incop.
8903 tt (js2-peek-token-or-eol))
8904 (when (or (= tt js2-INC) (= tt js2-DEC))
8905 (js2-consume-token)
8906 (setf expr pn
8907 pn (js2-make-unary tt expr))
8908 (js2-node-set-prop pn 'postfix t)
8909 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8910 pn))))
8911
8912 (defun js2-parse-xml-initializer ()
8913 "Parse an E4X XML initializer.
8914 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8915 Then I'll postprocess the result, depending on whether we're in IDE
8916 mode or codegen mode, and generate the appropriate rewritten AST.
8917 IDE mode uses a rich AST that models the XML structure. Codegen mode
8918 just concatenates everything and makes a new XML or XMLList out of it."
8919 (let ((tt (js2-get-first-xml-token))
8920 pn-xml
8921 pn
8922 expr
8923 kids
8924 expr-pos
8925 (continue t)
8926 (first-token t))
8927 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8928 (js2-report-error "msg.syntax"))
8929 (setq pn-xml (make-js2-xml-node))
8930 (while continue
8931 (if first-token
8932 (setq first-token nil)
8933 (setq tt (js2-get-next-xml-token)))
8934 (cond
8935 ;; js2-XML means we found a {expr} in the XML stream.
8936 ;; The js2-ts-string is the XML up to the left-curly.
8937 ((= tt js2-XML)
8938 (push (make-js2-string-node :pos js2-token-beg
8939 :len (- js2-ts-cursor js2-token-beg))
8940 kids)
8941 (js2-must-match js2-LC "msg.syntax")
8942 (setq expr-pos js2-ts-cursor
8943 expr (if (eq (js2-peek-token) js2-RC)
8944 (make-js2-empty-expr-node :pos expr-pos)
8945 (js2-parse-expr)))
8946 (js2-must-match js2-RC "msg.syntax")
8947 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8948 :len (js2-node-len expr)
8949 :expr expr))
8950 (js2-node-add-children pn expr)
8951 (push pn kids))
8952 ;; a js2-XMLEND token means we hit the final close-tag.
8953 ((= tt js2-XMLEND)
8954 (push (make-js2-string-node :pos js2-token-beg
8955 :len (- js2-ts-cursor js2-token-beg))
8956 kids)
8957 (dolist (kid (nreverse kids))
8958 (js2-block-node-push pn-xml kid))
8959 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8960 (js2-node-pos pn-xml))
8961 continue nil))
8962 (t
8963 (js2-report-error "msg.syntax")
8964 (setq continue nil))))
8965 pn-xml))
8966
8967
8968 (defun js2-parse-argument-list ()
8969 "Parse an argument list and return it as a lisp list of nodes.
8970 Returns the list in reverse order. Consumes the right-paren token."
8971 (let (result)
8972 (unless (js2-match-token js2-RP)
8973 (loop do
8974 (if (= (js2-peek-token) js2-YIELD)
8975 (js2-report-error "msg.yield.parenthesized"))
8976 (push (js2-parse-assign-expr) result)
8977 while
8978 (js2-match-token js2-COMMA))
8979 (js2-must-match js2-RP "msg.no.paren.arg")
8980 result)))
8981
8982 (defun js2-parse-member-expr (&optional allow-call-syntax)
8983 (let ((tt (js2-peek-token))
8984 pn
8985 pos
8986 target
8987 args
8988 beg
8989 end
8990 init
8991 tail)
8992 (if (/= tt js2-NEW)
8993 (setq pn (js2-parse-primary-expr))
8994 ;; parse a 'new' expression
8995 (js2-consume-token)
8996 (setq pos js2-token-beg
8997 beg pos
8998 target (js2-parse-member-expr)
8999 end (js2-node-end target)
9000 pn (make-js2-new-node :pos pos
9001 :target target
9002 :len (- end pos)))
9003 (js2-node-add-children pn target)
9004 (when (js2-match-token js2-LP)
9005 ;; Add the arguments to pn, if any are supplied.
9006 (setf beg pos ; start of "new" keyword
9007 pos js2-token-beg
9008 args (nreverse (js2-parse-argument-list))
9009 (js2-new-node-args pn) args
9010 end js2-token-end
9011 (js2-new-node-lp pn) (- pos beg)
9012 (js2-new-node-rp pn) (- end 1 beg))
9013 (apply #'js2-node-add-children pn args))
9014 (when (and js2-allow-rhino-new-expr-initializer
9015 (js2-match-token js2-LC))
9016 (setf init (js2-parse-object-literal)
9017 end (js2-node-end init)
9018 (js2-new-node-initializer pn) init)
9019 (js2-node-add-children pn init))
9020 (setf (js2-node-len pn) (- end beg))) ; end outer if
9021 (js2-parse-member-expr-tail allow-call-syntax pn)))
9022
9023 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9024 "Parse a chain of property/array accesses or function calls.
9025 Includes parsing for E4X operators like `..' and `.@'.
9026 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9027 Returns an expression tree that includes PN, the parent node."
9028 (let ((beg (js2-node-pos pn))
9029 tt
9030 (continue t))
9031 (while continue
9032 (setq tt (js2-peek-token))
9033 (cond
9034 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9035 (setq pn (js2-parse-property-access tt pn)))
9036 ((= tt js2-DOTQUERY)
9037 (setq pn (js2-parse-dot-query pn)))
9038 ((= tt js2-LB)
9039 (setq pn (js2-parse-element-get pn)))
9040 ((= tt js2-LP)
9041 (if allow-call-syntax
9042 (setq pn (js2-parse-function-call pn))
9043 (setq continue nil)))
9044 (t
9045 (setq continue nil))))
9046 (if (>= js2-highlight-level 2)
9047 (js2-parse-highlight-member-expr-node pn))
9048 pn))
9049
9050 (defun js2-parse-dot-query (pn)
9051 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9052 Last token parsed must be `js2-DOTQUERY'."
9053 (let ((pos (js2-node-pos pn))
9054 op-pos
9055 expr
9056 end)
9057 (js2-consume-token)
9058 (js2-must-have-xml)
9059 (js2-set-requires-activation)
9060 (setq op-pos js2-token-beg
9061 expr (js2-parse-expr)
9062 end (js2-node-end expr)
9063 pn (make-js2-xml-dot-query-node :left pn
9064 :pos pos
9065 :op-pos op-pos
9066 :right expr))
9067 (js2-node-add-children pn
9068 (js2-xml-dot-query-node-left pn)
9069 (js2-xml-dot-query-node-right pn))
9070 (if (js2-must-match js2-RP "msg.no.paren")
9071 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9072 end js2-token-end))
9073 (setf (js2-node-len pn) (- end pos))
9074 pn))
9075
9076 (defun js2-parse-element-get (pn)
9077 "Parse an element-get expression, e.g. foo[bar].
9078 Last token parsed must be `js2-RB'."
9079 (let ((lb js2-token-beg)
9080 (pos (js2-node-pos pn))
9081 rb
9082 expr)
9083 (js2-consume-token)
9084 (setq expr (js2-parse-expr))
9085 (if (js2-must-match js2-RB "msg.no.bracket.index")
9086 (setq rb js2-token-beg))
9087 (setq pn (make-js2-elem-get-node :target pn
9088 :pos pos
9089 :element expr
9090 :lb (js2-relpos lb pos)
9091 :rb (js2-relpos rb pos)
9092 :len (- js2-token-end pos)))
9093 (js2-node-add-children pn
9094 (js2-elem-get-node-target pn)
9095 (js2-elem-get-node-element pn))
9096 pn))
9097
9098 (defun js2-parse-function-call (pn)
9099 (let (args
9100 (pos (js2-node-pos pn)))
9101 (js2-consume-token)
9102 (setq pn (make-js2-call-node :pos pos
9103 :target pn
9104 :lp (- js2-token-beg pos)))
9105 (js2-node-add-children pn (js2-call-node-target pn))
9106 ;; Add the arguments to pn, if any are supplied.
9107 (setf args (nreverse (js2-parse-argument-list))
9108 (js2-call-node-rp pn) (- js2-token-beg pos)
9109 (js2-call-node-args pn) args)
9110 (apply #'js2-node-add-children pn args)
9111 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9112 pn))
9113
9114 (defun js2-parse-property-access (tt pn)
9115 "Parse a property access, XML descendants access, or XML attr access."
9116 (let ((member-type-flags 0)
9117 (dot-pos js2-token-beg)
9118 (dot-len (if (= tt js2-DOTDOT) 2 1))
9119 name
9120 ref ; right side of . or .. operator
9121 result)
9122 (js2-consume-token)
9123 (when (= tt js2-DOTDOT)
9124 (js2-must-have-xml)
9125 (setq member-type-flags js2-descendants-flag))
9126 (if (not js2-compiler-xml-available)
9127 (progn
9128 (js2-must-match-prop-name "msg.no.name.after.dot")
9129 (setq name (js2-create-name-node t js2-GETPROP)
9130 result (make-js2-prop-get-node :left pn
9131 :pos js2-token-beg
9132 :right name
9133 :len (- js2-token-end
9134 js2-token-beg)))
9135 (js2-node-add-children result pn name)
9136 result)
9137 ;; otherwise look for XML operators
9138 (setf result (if (= tt js2-DOT)
9139 (make-js2-prop-get-node)
9140 (make-js2-infix-node :type js2-DOTDOT))
9141 (js2-node-pos result) (js2-node-pos pn)
9142 (js2-infix-node-op-pos result) dot-pos
9143 (js2-infix-node-left result) pn ; do this after setting position
9144 tt (js2-next-token))
9145 (cond
9146 ;; needed for generator.throw()
9147 ((= tt js2-THROW)
9148 (js2-save-name-token-data js2-token-beg "throw")
9149 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9150 ;; handles: name, ns::name, ns::*, ns::[expr]
9151 ((js2-valid-prop-name-token tt)
9152 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9153 ;; handles: *, *::name, *::*, *::[expr]
9154 ((= tt js2-MUL)
9155 (js2-save-name-token-data js2-token-beg "*")
9156 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9157 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9158 ((= tt js2-XMLATTR)
9159 (setq result (js2-parse-attribute-access)))
9160 (t
9161 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9162 (if ref
9163 (setf (js2-node-len result) (- (js2-node-end ref)
9164 (js2-node-pos result))
9165 (js2-infix-node-right result) ref))
9166 (if (js2-infix-node-p result)
9167 (js2-node-add-children result
9168 (js2-infix-node-left result)
9169 (js2-infix-node-right result)))
9170 result)))
9171
9172 (defun js2-parse-attribute-access ()
9173 "Parse an E4X XML attribute expression.
9174 This includes expressions of the forms:
9175
9176 @attr @ns::attr @ns::*
9177 @* @*::attr @*::*
9178 @[expr] @*::[expr] @ns::[expr]
9179
9180 Called if we peeked an '@' token."
9181 (let ((tt (js2-next-token))
9182 (at-pos js2-token-beg))
9183 (cond
9184 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9185 ((js2-valid-prop-name-token tt)
9186 (js2-parse-property-name at-pos js2-ts-string 0))
9187 ;; handles: @*, @*::name, @*::*, @*::[expr]
9188 ((= tt js2-MUL)
9189 (js2-save-name-token-data js2-token-beg "*")
9190 (js2-parse-property-name js2-token-beg "*" 0))
9191 ;; handles @[expr]
9192 ((= tt js2-LB)
9193 (js2-parse-xml-elem-ref at-pos))
9194 (t
9195 (js2-report-error "msg.no.name.after.xmlAttr")
9196 ;; Avoid cascaded errors that happen if we make an error node here.
9197 (js2-save-name-token-data js2-token-beg "")
9198 (js2-parse-property-name js2-token-beg "" 0)))))
9199
9200 (defun js2-parse-property-name (at-pos s member-type-flags)
9201 "Check if :: follows name in which case it becomes qualified name.
9202
9203 AT-POS is a natural number if we just read an '@' token, else nil.
9204 S is the name or string that was matched: an identifier, 'throw' or '*'.
9205 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9206
9207 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9208 operator, or the name is followed by ::. For a plain name, returns a
9209 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9210 (let ((pos (or at-pos js2-token-beg))
9211 colon-pos
9212 (name (js2-create-name-node t js2-current-token))
9213 ns
9214 tt
9215 ref
9216 pn)
9217 (catch 'return
9218 (when (js2-match-token js2-COLONCOLON)
9219 (setq ns name
9220 colon-pos js2-token-beg
9221 tt (js2-next-token))
9222 (cond
9223 ;; handles name::name
9224 ((js2-valid-prop-name-token tt)
9225 (setq name (js2-create-name-node)))
9226 ;; handles name::*
9227 ((= tt js2-MUL)
9228 (js2-save-name-token-data js2-token-beg "*")
9229 (setq name (js2-create-name-node)))
9230 ;; handles name::[expr]
9231 ((= tt js2-LB)
9232 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9233 (t
9234 (js2-report-error "msg.no.name.after.coloncolon"))))
9235 (if (and (null ns) (zerop member-type-flags))
9236 name
9237 (prog1
9238 (setq pn
9239 (make-js2-xml-prop-ref-node :pos pos
9240 :len (- (js2-node-end name) pos)
9241 :at-pos at-pos
9242 :colon-pos colon-pos
9243 :propname name))
9244 (js2-node-add-children pn name))))))
9245
9246 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9247 "Parse the [expr] portion of an xml element reference.
9248 For instance, @[expr], @*::[expr], or ns::[expr]."
9249 (let* ((lb js2-token-beg)
9250 (pos (or at-pos lb))
9251 rb
9252 (expr (js2-parse-expr))
9253 (end (js2-node-end expr))
9254 pn)
9255 (if (js2-must-match js2-RB "msg.no.bracket.index")
9256 (setq rb js2-token-beg
9257 end js2-token-end))
9258 (prog1
9259 (setq pn
9260 (make-js2-xml-elem-ref-node :pos pos
9261 :len (- end pos)
9262 :namespace namespace
9263 :colon-pos colon-pos
9264 :at-pos at-pos
9265 :expr expr
9266 :lb (js2-relpos lb pos)
9267 :rb (js2-relpos rb pos)))
9268 (js2-node-add-children pn namespace expr))))
9269
9270 (defsubst js2-parse-primary-expr-lhs ()
9271 (let ((js2-is-in-lhs t))
9272 (js2-parse-primary-expr)))
9273
9274 (defun js2-parse-primary-expr ()
9275 "Parses a literal (leaf) expression of some sort.
9276 Includes complex literals such as functions, object-literals,
9277 array-literals, array comprehensions and regular expressions."
9278 (let ((tt-flagged (js2-next-flagged-token))
9279 pn ; parent node (usually return value)
9280 tt
9281 px-pos ; paren-expr pos
9282 len
9283 flags ; regexp flags
9284 expr)
9285 (setq tt js2-current-token)
9286 (cond
9287 ((= tt js2-FUNCTION)
9288 (js2-parse-function 'FUNCTION_EXPRESSION))
9289 ((= tt js2-LB)
9290 (js2-parse-array-literal))
9291 ((= tt js2-LC)
9292 (js2-parse-object-literal))
9293 ((= tt js2-LET)
9294 (js2-parse-let js2-token-beg))
9295 ((= tt js2-LP)
9296 (setq px-pos js2-token-beg
9297 expr (js2-parse-expr))
9298 (js2-must-match js2-RP "msg.no.paren")
9299 (setq pn (make-js2-paren-node :pos px-pos
9300 :expr expr
9301 :len (- js2-token-end px-pos)))
9302 (js2-node-add-children pn (js2-paren-node-expr pn))
9303 pn)
9304 ((= tt js2-XMLATTR)
9305 (js2-must-have-xml)
9306 (js2-parse-attribute-access))
9307 ((= tt js2-NAME)
9308 (js2-parse-name tt-flagged tt))
9309 ((= tt js2-NUMBER)
9310 (make-js2-number-node))
9311 ((= tt js2-STRING)
9312 (prog1
9313 (make-js2-string-node)
9314 (js2-record-face 'font-lock-string-face)))
9315 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9316 ;; Got / or /= which in this context means a regexp literal
9317 (setq px-pos js2-token-beg)
9318 (js2-read-regexp tt)
9319 (setq flags js2-ts-regexp-flags
9320 js2-ts-regexp-flags nil)
9321 (prog1
9322 (make-js2-regexp-node :pos px-pos
9323 :len (- js2-ts-cursor px-pos)
9324 :value js2-ts-string
9325 :flags flags)
9326 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9327 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9328 ((or (= tt js2-NULL)
9329 (= tt js2-THIS)
9330 (= tt js2-FALSE)
9331 (= tt js2-TRUE))
9332 (make-js2-keyword-node :type tt))
9333 ((= tt js2-RESERVED)
9334 (js2-report-error "msg.reserved.id")
9335 (make-js2-name-node))
9336 ((= tt js2-ERROR)
9337 ;; the scanner or one of its subroutines reported the error.
9338 (make-js2-error-node))
9339 ((= tt js2-EOF)
9340 (setq px-pos (point-at-bol)
9341 len (- js2-ts-cursor px-pos))
9342 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9343 (make-js2-error-node :pos px-pos :len len))
9344 (t
9345 (js2-report-error "msg.syntax")
9346 (make-js2-error-node)))))
9347
9348 (defun js2-parse-name (tt-flagged tt)
9349 (let ((name js2-ts-string)
9350 (name-pos js2-token-beg)
9351 node)
9352 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9353 (= (js2-peek-token) js2-COLON))
9354 (prog1
9355 ;; Do not consume colon, it is used as unwind indicator
9356 ;; to return to statementHelper.
9357 (make-js2-label-node :pos name-pos
9358 :len (- js2-token-end name-pos)
9359 :name name)
9360 (js2-set-face name-pos
9361 js2-token-end
9362 'font-lock-variable-name-face 'record))
9363 ;; Otherwise not a label, just a name. Unfortunately peeking
9364 ;; the next token to check for a colon has biffed js2-token-beg
9365 ;; and js2-token-end. We store the name's bounds in buffer vars
9366 ;; and `js2-create-name-node' uses them.
9367 (js2-save-name-token-data name-pos name)
9368 (setq node (if js2-compiler-xml-available
9369 (js2-parse-property-name nil name 0)
9370 (js2-create-name-node 'check-activation)))
9371 (if js2-highlight-external-variables
9372 (js2-record-name-node node))
9373 node)))
9374
9375 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9376 (js2-add-strict-warning
9377 msg nil
9378 ;; back up from comma to beginning of line or array/objlit
9379 (max (if elems
9380 (js2-node-pos (car elems))
9381 pos)
9382 (save-excursion
9383 (goto-char comma-pos)
9384 (back-to-indentation)
9385 (point)))
9386 comma-pos))
9387
9388 (defun js2-parse-array-literal ()
9389 (let ((pos js2-token-beg)
9390 (end js2-token-end)
9391 (after-lb-or-comma t)
9392 after-comma
9393 tt
9394 elems
9395 pn
9396 (continue t))
9397 (unless js2-is-in-lhs
9398 (js2-push-scope (make-js2-scope))) ; for array comp
9399 (while continue
9400 (setq tt (js2-peek-token))
9401 (cond
9402 ;; comma
9403 ((= tt js2-COMMA)
9404 (js2-consume-token)
9405 (setq after-comma js2-token-end)
9406 (if (not after-lb-or-comma)
9407 (setq after-lb-or-comma t)
9408 (push nil elems)))
9409 ;; end of array
9410 ((or (= tt js2-RB)
9411 (= tt js2-EOF)) ; prevent infinite loop
9412 (if (= tt js2-EOF)
9413 (js2-report-error "msg.no.bracket.arg" nil pos)
9414 (js2-consume-token))
9415 (setq continue nil
9416 end js2-token-end
9417 pn (make-js2-array-node :pos pos
9418 :len (- js2-ts-cursor pos)
9419 :elems (nreverse elems)))
9420 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9421 (when after-comma
9422 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9423 pos elems after-comma)))
9424 ;; destructuring binding
9425 (js2-is-in-lhs
9426 (push (if (or (= tt js2-LC)
9427 (= tt js2-LB)
9428 (= tt js2-NAME))
9429 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9430 (js2-parse-primary-expr-lhs)
9431 ;; invalid pattern
9432 (js2-consume-token)
9433 (js2-report-error "msg.bad.var")
9434 (make-js2-error-node))
9435 elems)
9436 (setq after-lb-or-comma nil
9437 after-comma nil))
9438 ;; array comp
9439 ((and (>= js2-language-version 170)
9440 (= tt js2-FOR) ; check for array comprehension
9441 (not after-lb-or-comma) ; "for" can't follow a comma
9442 elems ; must have at least 1 element
9443 (not (cdr elems))) ; but no 2nd element
9444 (setf continue nil
9445 pn (js2-parse-array-comprehension (car elems) pos)))
9446
9447 ;; another element
9448 (t
9449 (unless after-lb-or-comma
9450 (js2-report-error "msg.no.bracket.arg"))
9451 (push (js2-parse-assign-expr) elems)
9452 (setq after-lb-or-comma nil
9453 after-comma nil))))
9454 (unless js2-is-in-lhs
9455 (js2-pop-scope))
9456 pn))
9457
9458 (defun js2-parse-array-comprehension (expr pos)
9459 "Parse a JavaScript 1.7 Array Comprehension.
9460 EXPR is the first expression after the opening left-bracket.
9461 POS is the beginning of the LB token preceding EXPR.
9462 We should have just parsed the 'for' keyword before calling this function."
9463 (let (loops
9464 loop
9465 first
9466 prev
9467 filter
9468 if-pos
9469 result)
9470 (while (= (js2-peek-token) js2-FOR)
9471 (let ((prev (car loops))) ; rearrange scope chain
9472 (push (setq loop (js2-parse-array-comp-loop)) loops)
9473 (if prev ; each loop is parent scope to the next one
9474 (setf (js2-scope-parent-scope loop) prev)
9475 ; first loop takes expr scope's parent
9476 (setf (js2-scope-parent-scope (setq first loop))
9477 (js2-scope-parent-scope js2-current-scope)))))
9478 ;; set expr scope's parent to the last loop
9479 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9480 (when (= (js2-peek-token) js2-IF)
9481 (js2-consume-token)
9482 (setq if-pos (- js2-token-beg pos) ; relative
9483 filter (js2-parse-condition)))
9484 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9485 (setq result (make-js2-array-comp-node :pos pos
9486 :len (- js2-ts-cursor pos)
9487 :result expr
9488 :loops (nreverse loops)
9489 :filter (car filter)
9490 :lp (js2-relpos (second filter) pos)
9491 :rp (js2-relpos (third filter) pos)
9492 :if-pos if-pos))
9493 (apply #'js2-node-add-children result expr (car filter)
9494 (js2-array-comp-node-loops result))
9495 (setq js2-current-scope first) ; pop to the first loop
9496 result))
9497
9498 (defun js2-parse-array-comp-loop ()
9499 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9500 Last token peeked should be the initial FOR."
9501 (let ((pos js2-token-beg)
9502 (pn (make-js2-array-comp-loop-node))
9503 tt
9504 iter
9505 obj
9506 foreach-p
9507 in-pos
9508 each-pos
9509 lp
9510 rp)
9511 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9512 (js2-push-scope pn)
9513 (unwind-protect
9514 (progn
9515 (when (js2-match-token js2-NAME)
9516 (if (string= js2-ts-string "each")
9517 (progn
9518 (setq foreach-p t
9519 each-pos (- js2-token-beg pos)) ; relative
9520 (js2-record-face 'font-lock-keyword-face))
9521 (js2-report-error "msg.no.paren.for")))
9522 (if (js2-must-match js2-LP "msg.no.paren.for")
9523 (setq lp (- js2-token-beg pos)))
9524 (setq tt (js2-peek-token))
9525 (cond
9526 ((or (= tt js2-LB)
9527 (= tt js2-LC))
9528 ;; handle destructuring assignment
9529 (setq iter (js2-parse-primary-expr-lhs))
9530 (js2-define-destruct-symbols iter js2-LET
9531 'font-lock-variable-name-face t))
9532 ((js2-valid-prop-name-token tt)
9533 (js2-consume-token)
9534 (setq iter (js2-create-name-node)))
9535 (t
9536 (js2-report-error "msg.bad.var")))
9537 ;; Define as a let since we want the scope of the variable to
9538 ;; be restricted to the array comprehension
9539 (if (js2-name-node-p iter)
9540 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9541 (if (js2-must-match js2-IN "msg.in.after.for.name")
9542 (setq in-pos (- js2-token-beg pos)))
9543 (setq obj (js2-parse-expr))
9544 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9545 (setq rp (- js2-token-beg pos)))
9546 (setf (js2-node-pos pn) pos
9547 (js2-node-len pn) (- js2-ts-cursor pos)
9548 (js2-array-comp-loop-node-iterator pn) iter
9549 (js2-array-comp-loop-node-object pn) obj
9550 (js2-array-comp-loop-node-in-pos pn) in-pos
9551 (js2-array-comp-loop-node-each-pos pn) each-pos
9552 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9553 (js2-array-comp-loop-node-lp pn) lp
9554 (js2-array-comp-loop-node-rp pn) rp)
9555 (js2-node-add-children pn iter obj))
9556 (js2-pop-scope))
9557 pn))
9558
9559 (defun js2-parse-object-literal ()
9560 (let ((pos js2-token-beg)
9561 tt
9562 elems
9563 result
9564 after-comma
9565 (continue t))
9566 (while continue
9567 (setq tt (js2-peek-token))
9568 (cond
9569 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9570 ((or (js2-valid-prop-name-token tt)
9571 (= tt js2-STRING))
9572 (setq after-comma nil
9573 result (js2-parse-named-prop tt))
9574 (if (and (null result)
9575 (not js2-recover-from-parse-errors))
9576 (setq continue nil)
9577 (push result elems)))
9578 ;; {12: x} or {10.7: x}
9579 ((= tt js2-NUMBER)
9580 (js2-consume-token)
9581 (setq after-comma nil)
9582 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9583 ;; trailing comma
9584 ((= tt js2-RC)
9585 (setq continue nil)
9586 (if after-comma
9587 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9588 pos elems after-comma)))
9589 (t
9590 (js2-report-error "msg.bad.prop")
9591 (unless js2-recover-from-parse-errors
9592 (setq continue nil)))) ; end switch
9593 (if (js2-match-token js2-COMMA)
9594 (setq after-comma js2-token-end)
9595 (setq continue nil))) ; end loop
9596 (js2-must-match js2-RC "msg.no.brace.prop")
9597 (setq result (make-js2-object-node :pos pos
9598 :len (- js2-ts-cursor pos)
9599 :elems (nreverse elems)))
9600 (apply #'js2-node-add-children result (js2-object-node-elems result))
9601 result))
9602
9603 (defun js2-parse-named-prop (tt)
9604 "Parse a name, string, or getter/setter object property.
9605 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9606 (js2-consume-token)
9607 (let ((string-prop (and (= tt js2-STRING)
9608 (make-js2-string-node)))
9609 expr
9610 (ppos js2-token-beg)
9611 (pend js2-token-end)
9612 (name (js2-create-name-node))
9613 (prop js2-ts-string))
9614 (cond
9615 ;; getter/setter prop
9616 ((and (= tt js2-NAME)
9617 (= (js2-peek-token) js2-NAME)
9618 (or (string= prop "get")
9619 (string= prop "set")))
9620 (js2-consume-token)
9621 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9622 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9623 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9624 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9625 ;; abbreviated destructuring bind e.g., {a, b} = c;
9626 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9627 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9628 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9629 ;; assignment but it's difficult because it requires looking ahead of expression.
9630 ((and js2-is-in-lhs
9631 (= tt js2-NAME)
9632 (let ((ctk (js2-peek-token)))
9633 (or (= ctk js2-COMMA)
9634 (= ctk js2-RC)
9635 (js2-valid-prop-name-token ctk))))
9636 name)
9637 ;; regular prop
9638 (t
9639 (prog1
9640 (setq expr (js2-parse-plain-property (or string-prop name)))
9641 (js2-set-face ppos pend
9642 (if (js2-function-node-p
9643 (js2-object-prop-node-right expr))
9644 'font-lock-function-name-face
9645 'font-lock-variable-name-face)
9646 'record))))))
9647
9648 (defun js2-parse-plain-property (prop)
9649 "Parse a non-getter/setter property in an object literal.
9650 PROP is the node representing the property: a number, name or string."
9651 (js2-must-match js2-COLON "msg.no.colon.prop")
9652 (let* ((pos (js2-node-pos prop))
9653 (colon (- js2-token-beg pos))
9654 (expr (js2-parse-assign-expr))
9655 (result (make-js2-object-prop-node
9656 :pos pos
9657 ;; don't include last consumed token in length
9658 :len (- (+ (js2-node-pos expr)
9659 (js2-node-len expr))
9660 pos)
9661 :left prop
9662 :right expr
9663 :op-pos colon)))
9664 (js2-node-add-children result prop expr)
9665 result))
9666
9667 (defun js2-parse-getter-setter-prop (pos prop get-p)
9668 "Parse getter or setter property in an object literal.
9669 JavaScript syntax is:
9670
9671 { get foo() {...}, set foo(x) {...} }
9672
9673 and expression closure style is also supported
9674
9675 { get foo() x, set foo(x) _x = x }
9676
9677 POS is the start position of the `get' or `set' keyword.
9678 PROP is the `js2-name-node' representing the property name.
9679 GET-P is non-nil if the keyword was `get'."
9680 (let ((type (if get-p js2-GET js2-SET))
9681 result
9682 end
9683 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9684 ;; it has to be an anonymous function, as we already parsed the name
9685 (if (/= (js2-node-type fn) js2-FUNCTION)
9686 (js2-report-error "msg.bad.prop")
9687 (if (plusp (length (js2-function-name fn)))
9688 (js2-report-error "msg.bad.prop")))
9689 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9690 (setq end (js2-node-end fn)
9691 result (make-js2-getter-setter-node :type type
9692 :pos pos
9693 :len (- end pos)
9694 :left prop
9695 :right fn))
9696 (js2-node-add-children result prop fn)
9697 result))
9698
9699 (defun js2-create-name-node (&optional check-activation-p token)
9700 "Create a name node using the token info from last scanned name.
9701 In some cases we need to either synthesize a name node, or we lost
9702 the name token information by peeking. If the TOKEN parameter is
9703 not `js2-NAME', then we use the token info saved in instance vars."
9704 (let ((beg js2-token-beg)
9705 (s js2-ts-string)
9706 name)
9707 (when (/= js2-current-token js2-NAME)
9708 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9709 s js2-prev-name-token-string
9710 js2-prev-name-token-start nil
9711 js2-prev-name-token-string nil))
9712 (setq name (make-js2-name-node :pos beg
9713 :name s
9714 :len (length s)))
9715 (if check-activation-p
9716 (js2-check-activation-name s (or token js2-NAME)))
9717 name))
9718
9719 ;;; Indentation support
9720
9721 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9722 ;; Karl cleverly deduces that the desired indentation level is often a
9723 ;; function of paren/bracket/brace nesting depth, which can be determined
9724 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9725 ;; then does some equally clever checks to see if we're in the context of a
9726 ;; substatement of a possibly braceless statement keyword such as if, while,
9727 ;; or finally. This approach yields pretty good results.
9728
9729 ;; The indenter is often "wrong", however, and needs to be overridden.
9730 ;; The right long-term solution is probably to emulate (or integrate
9731 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9732 ;; parse tree from `js2-parse' is present, which is not true at the
9733 ;; moment the user is typing, computing indentation is still thousands
9734 ;; of lines of code to handle every possible syntactic edge case.
9735
9736 ;; In the meantime, the compromise solution is that we offer a "bounce
9737 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9738 ;; current line indent among various likely guess points. This approach
9739 ;; is far from perfect, but should at least make it slightly easier to
9740 ;; move the line towards its desired indentation when manually
9741 ;; overriding Karl's heuristic nesting guesser.
9742
9743 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9744 ;; extensions such as `let' and Array comprehensions. Major kudos to
9745 ;; Karl for coming up with the initial approach, which packs a lot of
9746 ;; punch for so little code.
9747
9748 (defconst js-possibly-braceless-keywords-re
9749 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9750 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9751 "try" "while" "with" "let")))
9752 "Regular expression matching keywords that are optionally
9753 followed by an opening brace.")
9754
9755 (defconst js-indent-operator-re
9756 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9757 (regexp-opt '("in" "instanceof") 'words))
9758 "Regular expression matching operators that affect indentation
9759 of continued expressions.")
9760
9761 (defconst js-declaration-keyword-re
9762 (regexp-opt '("var" "let" "const") 'words)
9763 "Regular expression matching variable declaration keywords.")
9764
9765 ;; This function has horrible results if you're typing an array
9766 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9767 ;; in conjunction with electric-indent, so just disabling it.
9768 (defsubst js2-code-at-bol-p ()
9769 "Return t if the first character on line is non-whitespace."
9770 nil)
9771
9772 (defun js2-insert-and-indent (key)
9773 "Run command bound to key and indent current line. Runs the command
9774 bound to KEY in the global keymap and indents the current line."
9775 (interactive (list (this-command-keys)))
9776 (let ((cmd (lookup-key (current-global-map) key)))
9777 (if (commandp cmd)
9778 (call-interactively cmd)))
9779 ;; don't do the electric keys inside comments or strings,
9780 ;; and don't do bounce-indent with them.
9781 (let ((parse-state (syntax-ppss (point)))
9782 (js2-bounce-indent-p (js2-code-at-bol-p)))
9783 (unless (or (nth 3 parse-state)
9784 (nth 4 parse-state))
9785 (indent-according-to-mode))))
9786
9787 (defun js-re-search-forward-inner (regexp &optional bound count)
9788 "Auxiliary function for `js-re-search-forward'."
9789 (let (parse saved-point)
9790 (while (> count 0)
9791 (re-search-forward regexp bound)
9792 (setq parse (if saved-point
9793 (parse-partial-sexp saved-point (point))
9794 (syntax-ppss (point))))
9795 (cond ((nth 3 parse)
9796 (re-search-forward
9797 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9798 (save-excursion (end-of-line) (point)) t))
9799 ((nth 7 parse)
9800 (forward-line))
9801 ((or (nth 4 parse)
9802 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9803 (re-search-forward "\\*/"))
9804 (t
9805 (setq count (1- count))))
9806 (setq saved-point (point))))
9807 (point))
9808
9809 (defun js-re-search-forward (regexp &optional bound noerror count)
9810 "Search forward but ignore strings and comments. Invokes
9811 `re-search-forward' but treats the buffer as if strings and
9812 comments have been removed."
9813 (let ((saved-point (point))
9814 (search-expr
9815 (cond ((null count)
9816 '(js-re-search-forward-inner regexp bound 1))
9817 ((< count 0)
9818 '(js-re-search-backward-inner regexp bound (- count)))
9819 ((> count 0)
9820 '(js-re-search-forward-inner regexp bound count)))))
9821 (condition-case err
9822 (eval search-expr)
9823 (search-failed
9824 (goto-char saved-point)
9825 (unless noerror
9826 (error (error-message-string err)))))))
9827
9828 (defun js-re-search-backward-inner (regexp &optional bound count)
9829 "Auxiliary function for `js-re-search-backward'."
9830 (let (parse saved-point)
9831 (while (> count 0)
9832 (re-search-backward regexp bound)
9833 (setq parse (if saved-point
9834 (parse-partial-sexp saved-point (point))
9835 (syntax-ppss (point))))
9836 (cond ((nth 3 parse)
9837 (re-search-backward
9838 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9839 (save-excursion (beginning-of-line) (point)) t))
9840 ((nth 7 parse)
9841 (goto-char (nth 8 parse)))
9842 ((or (nth 4 parse)
9843 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9844 (re-search-backward "/\\*"))
9845 (t
9846 (setq count (1- count))))))
9847 (point))
9848
9849 (defun js-re-search-backward (regexp &optional bound noerror count)
9850 "Search backward but ignore strings and comments. Invokes
9851 `re-search-backward' but treats the buffer as if strings and
9852 comments have been removed."
9853 (let ((saved-point (point))
9854 (search-expr
9855 (cond ((null count)
9856 '(js-re-search-backward-inner regexp bound 1))
9857 ((< count 0)
9858 '(js-re-search-forward-inner regexp bound (- count)))
9859 ((> count 0)
9860 '(js-re-search-backward-inner regexp bound count)))))
9861 (condition-case err
9862 (eval search-expr)
9863 (search-failed
9864 (goto-char saved-point)
9865 (unless noerror
9866 (error (error-message-string err)))))))
9867
9868 (defun js-looking-at-operator-p ()
9869 "Return non-nil if text after point is an operator (that is not
9870 a comma)."
9871 (save-match-data
9872 (and (looking-at js-indent-operator-re)
9873 (or (not (looking-at ":"))
9874 (save-excursion
9875 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9876 (looking-at "?")))))))
9877
9878 (defun js-continued-expression-p ()
9879 "Returns non-nil if the current line continues an expression."
9880 (save-excursion
9881 (back-to-indentation)
9882 (or (js-looking-at-operator-p)
9883 ;; comment
9884 (and (js-re-search-backward "\n" nil t)
9885 (progn
9886 (skip-chars-backward " \t")
9887 (backward-char)
9888 (and (js-looking-at-operator-p)
9889 (and (progn (backward-char)
9890 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9891
9892 (defun js-end-of-do-while-loop-p ()
9893 "Returns non-nil if word after point is `while' of a do-while
9894 statement, else returns nil. A braceless do-while statement
9895 spanning several lines requires that the start of the loop is
9896 indented to the same column as the current line."
9897 (interactive)
9898 (save-excursion
9899 (save-match-data
9900 (when (looking-at "\\s-*\\<while\\>")
9901 (if (save-excursion
9902 (skip-chars-backward "[ \t\n]*}")
9903 (looking-at "[ \t\n]*}"))
9904 (save-excursion
9905 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9906 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9907 (or (looking-at "\\<do\\>")
9908 (let ((saved-indent (current-indentation)))
9909 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9910 (/= (current-indentation) saved-indent)))
9911 (and (looking-at "[ \t]*\\<do\\>")
9912 (not (js-re-search-forward
9913 "\\<while\\>" (point-at-eol) t))
9914 (= (current-indentation) saved-indent)))))))))
9915
9916 (defun js-multiline-decl-indentation ()
9917 "Returns the declaration indentation column if the current line belongs
9918 to a multiline declaration statement. All declarations are lined up vertically:
9919
9920 var a = 10,
9921 b = 20,
9922 c = 30;
9923
9924 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9925 assigned expression is a function or array/object literal, it will be indented
9926 differently:
9927
9928 var o = { var bar = 2,
9929 foo: 3 o = {
9930 }, foo: 3
9931 bar = 2; };
9932 "
9933 (let (forward-sexp-function ; use lisp version
9934 at-opening-bracket)
9935 (save-excursion
9936 (back-to-indentation)
9937 (when (not (looking-at js-declaration-keyword-re))
9938 (when (looking-at js-indent-operator-re)
9939 (goto-char (match-end 0))) ; continued expressions are ok
9940 (while (and (not at-opening-bracket)
9941 (not (bobp))
9942 (let ((pos (point)))
9943 (save-excursion
9944 (js2-backward-sws)
9945 (or (eq (char-before) ?,)
9946 (and (not (eq (char-before) ?\;))
9947 (and
9948 (prog2 (skip-chars-backward "[[:punct:]]")
9949 (looking-at js-indent-operator-re)
9950 (js2-backward-sws))
9951 (not (eq (char-before) ?\;))))
9952 (js2-same-line pos)))))
9953 (condition-case err
9954 (backward-sexp)
9955 (scan-error (setq at-opening-bracket t))))
9956 (when (looking-at js-declaration-keyword-re)
9957 (- (1+ (match-end 0)) (point-at-bol)))))))
9958
9959 (defun js-ctrl-statement-indentation ()
9960 "Returns the proper indentation of the current line if it
9961 starts the body of a control statement without braces, else
9962 returns nil."
9963 (let (forward-sexp-function) ; temporarily unbind it
9964 (save-excursion
9965 (back-to-indentation)
9966 (when (and (not (js2-same-line (point-min)))
9967 (not (looking-at "{"))
9968 (js-re-search-backward "[[:graph:]]" nil t)
9969 (not (looking-at "[{([]"))
9970 (progn
9971 (forward-char)
9972 (when (= (char-before) ?\))
9973 ;; scan-sexps sometimes throws an error
9974 (ignore-errors (backward-sexp))
9975 (skip-chars-backward " \t" (point-at-bol)))
9976 (let ((pt (point)))
9977 (back-to-indentation)
9978 (and (looking-at js-possibly-braceless-keywords-re)
9979 (= (match-end 0) pt)
9980 (not (js-end-of-do-while-loop-p))))))
9981 (+ (current-indentation) js2-basic-offset)))))
9982
9983 (defun js2-indent-in-array-comp (parse-status)
9984 "Return non-nil if we think we're in an array comprehension.
9985 In particular, return the buffer position of the first `for' kwd."
9986 (let ((end (point)))
9987 (when (nth 1 parse-status)
9988 (save-excursion
9989 (goto-char (nth 1 parse-status))
9990 (when (looking-at "\\[")
9991 (forward-char 1)
9992 (js2-forward-sws)
9993 (if (looking-at "[[{]")
9994 (let (forward-sexp-function) ; use lisp version
9995 (forward-sexp) ; skip destructuring form
9996 (js2-forward-sws)
9997 (if (and (/= (char-after) ?,) ; regular array
9998 (looking-at "for"))
9999 (match-beginning 0)))
10000 ;; to skip arbitrary expressions we need the parser,
10001 ;; so we'll just guess at it.
10002 (if (and (> end (point)) ; not empty literal
10003 (re-search-forward "[^,]]* \\(for\\) " end t))
10004 (match-beginning 1))))))))
10005
10006 (defun js2-array-comp-indentation (parse-status for-kwd)
10007 (if (js2-same-line for-kwd)
10008 ;; first continuation line
10009 (save-excursion
10010 (goto-char (nth 1 parse-status))
10011 (forward-char 1)
10012 (skip-chars-forward " \t")
10013 (current-column))
10014 (save-excursion
10015 (goto-char for-kwd)
10016 (current-column))))
10017
10018 (defun js-proper-indentation (parse-status)
10019 "Return the proper indentation for the current line."
10020 (save-excursion
10021 (back-to-indentation)
10022 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10023 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10024 (continued-expr-p (js-continued-expression-p))
10025 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10026 (js-multiline-decl-indentation)))
10027 (bracket (nth 1 parse-status))
10028 beg)
10029 (cond
10030 ;; indent array comprehension continuation lines specially
10031 ((and bracket
10032 (not (js2-same-line bracket))
10033 (setq beg (js2-indent-in-array-comp parse-status))
10034 (>= (point) (save-excursion
10035 (goto-char beg)
10036 (point-at-bol)))) ; at or after first loop?
10037 (js2-array-comp-indentation parse-status beg))
10038
10039 (ctrl-stmt-indent)
10040
10041 ((and declaration-indent continued-expr-p)
10042 (+ declaration-indent js2-basic-offset))
10043
10044 (declaration-indent)
10045
10046 (bracket
10047 (goto-char bracket)
10048 (cond
10049 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10050 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10051 (when (save-excursion (skip-chars-backward " \t)")
10052 (looking-at ")"))
10053 (backward-list))
10054 (if (and (nth 1 p)
10055 (not js2-consistent-level-indent-inner-bracket-p))
10056 (progn (goto-char (1+ (nth 1 p)))
10057 (skip-chars-forward " \t"))
10058 (back-to-indentation)
10059 (when (and js2-pretty-multiline-decl-indentation-p
10060 js2-always-indent-assigned-expr-in-decls-p
10061 (looking-at js-declaration-keyword-re))
10062 (goto-char (1+ (match-end 0)))))
10063 (cond (same-indent-p
10064 (current-column))
10065 (continued-expr-p
10066 (+ (current-column) (* 2 js2-basic-offset)))
10067 (t
10068 (+ (current-column) js2-basic-offset)))))
10069 (t
10070 (unless same-indent-p
10071 (forward-char)
10072 (skip-chars-forward " \t"))
10073 (current-column))))
10074
10075 (continued-expr-p js2-basic-offset)
10076
10077 (t 0)))))
10078
10079 (defun js2-lineup-comment (parse-status)
10080 "Indent a multi-line block comment continuation line."
10081 (let* ((beg (nth 8 parse-status))
10082 (first-line (js2-same-line beg))
10083 (offset (save-excursion
10084 (goto-char beg)
10085 (if (looking-at "/\\*")
10086 (+ 1 (current-column))
10087 0))))
10088 (unless first-line
10089 (indent-line-to offset))))
10090
10091 (defun js2-backward-sws ()
10092 "Move backward through whitespace and comments."
10093 (interactive)
10094 (while (forward-comment -1)))
10095
10096 (defun js2-forward-sws ()
10097 "Move forward through whitespace and comments."
10098 (interactive)
10099 (while (forward-comment 1)))
10100
10101 (defsubst js2-current-indent (&optional pos)
10102 "Return column of indentation on current line.
10103 If POS is non-nil, go to that point and return indentation for that line."
10104 (save-excursion
10105 (if pos
10106 (goto-char pos))
10107 (back-to-indentation)
10108 (current-column)))
10109
10110 (defsubst js2-arglist-close ()
10111 "Return non-nil if we're on a line beginning with a close-paren/brace."
10112 (save-match-data
10113 (save-excursion
10114 (goto-char (point-at-bol))
10115 (js2-forward-sws)
10116 (looking-at "[])}]"))))
10117
10118 (defsubst js2-indent-looks-like-label-p ()
10119 (goto-char (point-at-bol))
10120 (js2-forward-sws)
10121 (looking-at (concat js2-mode-identifier-re ":")))
10122
10123 (defun js2-indent-in-objlit-p (parse-status)
10124 "Return non-nil if this looks like an object-literal entry."
10125 (let ((start (nth 1 parse-status)))
10126 (and
10127 start
10128 (save-excursion
10129 (and (zerop (forward-line -1))
10130 (not (< (point) start)) ; crossed a {} boundary
10131 (js2-indent-looks-like-label-p)))
10132 (save-excursion
10133 (js2-indent-looks-like-label-p)))))
10134
10135 ;; if prev line looks like foobar({ then we're passing an object
10136 ;; literal to a function call, and people pretty much always want to
10137 ;; de-dent back to the previous line, so move the 'basic-offset'
10138 ;; position to the front.
10139 (defsubst js2-indent-objlit-arg-p (parse-status)
10140 (save-excursion
10141 (back-to-indentation)
10142 (js2-backward-sws)
10143 (and (eq (1- (point)) (nth 1 parse-status))
10144 (eq (char-before) ?{)
10145 (progn
10146 (forward-char -1)
10147 (skip-chars-backward " \t")
10148 (eq (char-before) ?\()))))
10149
10150 (defsubst js2-indent-case-block-p ()
10151 (save-excursion
10152 (back-to-indentation)
10153 (js2-backward-sws)
10154 (goto-char (point-at-bol))
10155 (skip-chars-forward " \t")
10156 (save-match-data
10157 (looking-at "case\\s-.+:"))))
10158
10159 (defsubst js2-syntax-bol ()
10160 "Return the point at the first non-whitespace char on the line.
10161 Returns `point-at-bol' if the line is empty."
10162 (save-excursion
10163 (beginning-of-line)
10164 (skip-chars-forward " \t")
10165 (point)))
10166
10167 (defun js2-bounce-indent (normal-col parse-status backwards)
10168 "Cycle among alternate computed indentation positions.
10169 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10170 of the buffer to the current point. NORMAL-COL is the indentation
10171 column computed by the heuristic guesser based on current paren,
10172 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10173 in reverse."
10174 (let ((cur-indent (js2-current-indent))
10175 (old-buffer-undo-list buffer-undo-list)
10176 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10177 (current-line (save-excursion
10178 (forward-line 0) ; move to bol
10179 (1+ (count-lines (point-min) (point)))))
10180 positions
10181 pos
10182 main-pos
10183 anchor
10184 arglist-cont
10185 same-indent
10186 prev-line-col
10187 basic-offset
10188 computed-pos)
10189 ;; temporarily don't record undo info, if user requested this
10190 (if js2-mode-indent-inhibit-undo
10191 (setq buffer-undo-list t))
10192 (unwind-protect
10193 (progn
10194 ;; first likely point: indent from beginning of previous code line
10195 (push (setq basic-offset
10196 (+ (save-excursion
10197 (back-to-indentation)
10198 (js2-backward-sws)
10199 (back-to-indentation)
10200 (setq prev-line-col (current-column)))
10201 js2-basic-offset))
10202 positions)
10203
10204 ;; (first + epsilon) likely point: indent 2x from beginning of
10205 ;; previous code line. Some companies like this approach. Ahem.
10206 ;; Seriously, though -- 4-space indent for expression continuation
10207 ;; lines isn't a bad idea. We should eventually implement it
10208 ;; that way.
10209 (push (setq basic-offset
10210 (+ (save-excursion
10211 (back-to-indentation)
10212 (js2-backward-sws)
10213 (back-to-indentation)
10214 (setq prev-line-col (current-column)))
10215 (* 2 js2-basic-offset)))
10216 positions)
10217
10218 ;; second likely point: indent from assign-expr RHS. This
10219 ;; is just a crude guess based on finding " = " on the previous
10220 ;; line containing actual code.
10221 (setq pos (save-excursion
10222 (save-match-data
10223 (forward-line -1)
10224 (goto-char (point-at-bol))
10225 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10226 (point-at-eol) t)
10227 (goto-char (match-end 1))
10228 (skip-chars-forward " \t\r\n")
10229 (current-column)))))
10230 (when pos
10231 (incf pos js2-basic-offset)
10232 (push pos positions))
10233
10234 ;; third likely point: same indent as previous line of code.
10235 ;; Make it the first likely point if we're not on an
10236 ;; arglist-close line and previous line ends in a comma, or
10237 ;; both this line and prev line look like object-literal
10238 ;; elements.
10239 (setq pos (save-excursion
10240 (goto-char (point-at-bol))
10241 (js2-backward-sws)
10242 (back-to-indentation)
10243 (prog1
10244 (current-column)
10245 ;; while we're here, look for trailing comma
10246 (if (save-excursion
10247 (goto-char (point-at-eol))
10248 (js2-backward-sws)
10249 (eq (char-before) ?,))
10250 (setq arglist-cont (1- (point)))))))
10251 (when pos
10252 (if (and (or arglist-cont
10253 (js2-indent-in-objlit-p parse-status))
10254 (not (js2-arglist-close)))
10255 (setq same-indent pos))
10256 (push pos positions))
10257
10258 ;; fourth likely point: first preceding code with less indentation
10259 ;; than the immediately preceding code line.
10260 (setq pos (save-excursion
10261 (back-to-indentation)
10262 (js2-backward-sws)
10263 (back-to-indentation)
10264 (setq anchor (current-column))
10265 (while (and (zerop (forward-line -1))
10266 (>= (progn
10267 (back-to-indentation)
10268 (current-column))
10269 anchor)))
10270 (setq pos (current-column))))
10271 (push pos positions)
10272
10273 ;; nesting-heuristic position, main by default
10274 (push (setq main-pos normal-col) positions)
10275
10276 ;; delete duplicates and sort positions list
10277 (setq positions (sort (delete-dups positions) '<))
10278
10279 ;; comma-list continuation lines: prev line indent takes precedence
10280 (if same-indent
10281 (setq main-pos same-indent))
10282
10283 ;; common special cases where we want to indent in from previous line
10284 (if (or (js2-indent-case-block-p)
10285 (js2-indent-objlit-arg-p parse-status))
10286 (setq main-pos basic-offset))
10287
10288 ;; if bouncing backwards, reverse positions list
10289 (if backwards
10290 (setq positions (reverse positions)))
10291
10292 ;; record whether we're already sitting on one of the alternatives
10293 (setq pos (member cur-indent positions))
10294
10295 (cond
10296 ;; case 0: we're one one of the alternatives and this is the
10297 ;; first time they've pressed TAB on this line (best-guess).
10298 ((and js2-mode-indent-ignore-first-tab
10299 pos
10300 ;; first time pressing TAB on this line?
10301 (not (eq js2-mode-last-indented-line current-line)))
10302 ;; do nothing
10303 (setq computed-pos nil))
10304 ;; case 1: only one computed position => use it
10305 ((null (cdr positions))
10306 (setq computed-pos 0))
10307 ;; case 2: not on any of the computed spots => use main spot
10308 ((not pos)
10309 (setq computed-pos (js2-position main-pos positions)))
10310 ;; case 3: on last position: cycle to first position
10311 ((null (cdr pos))
10312 (setq computed-pos 0))
10313 ;; case 4: on intermediate position: cycle to next position
10314 (t
10315 (setq computed-pos (js2-position (second pos) positions))))
10316
10317 ;; see if any hooks want to indent; otherwise we do it
10318 (loop with result = nil
10319 for hook in js2-indent-hook
10320 while (null result)
10321 do
10322 (setq result (funcall hook positions computed-pos))
10323 finally do
10324 (unless (or result (null computed-pos))
10325 (indent-line-to (nth computed-pos positions)))))
10326
10327 ;; finally
10328 (if js2-mode-indent-inhibit-undo
10329 (setq buffer-undo-list old-buffer-undo-list))
10330 ;; see commentary for `js2-mode-last-indented-line'
10331 (setq js2-mode-last-indented-line current-line))))
10332
10333 (defun js2-indent-bounce-backwards ()
10334 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10335 cycles between the computed indentation positions in reverse order."
10336 (interactive)
10337 (js2-indent-line t))
10338
10339 (defsubst js2-1-line-comment-continuation-p ()
10340 "Return t if we're in a 1-line comment continuation.
10341 If so, we don't ever want to use bounce-indent."
10342 (save-excursion
10343 (save-match-data
10344 (and (progn
10345 (forward-line 0)
10346 (looking-at "\\s-*//"))
10347 (progn
10348 (forward-line -1)
10349 (forward-line 0)
10350 (when (looking-at "\\s-*$")
10351 (js2-backward-sws)
10352 (forward-line 0))
10353 (looking-at "\\s-*//"))))))
10354
10355 (defun js2-indent-line (&optional bounce-backwards)
10356 "Indent the current line as JavaScript source text."
10357 (interactive)
10358 (let (parse-status
10359 offset
10360 indent-col
10361 moved
10362 ;; don't whine about errors/warnings when we're indenting.
10363 ;; This has to be set before calling parse-partial-sexp below.
10364 (inhibit-point-motion-hooks t))
10365 (setq parse-status (save-excursion
10366 (syntax-ppss (point-at-bol)))
10367 offset (- (point) (save-excursion
10368 (back-to-indentation)
10369 (point))))
10370 (js2-with-underscore-as-word-syntax
10371 (if (nth 4 parse-status)
10372 (js2-lineup-comment parse-status)
10373 (setq indent-col (js-proper-indentation parse-status))
10374 ;; see comments below about js2-mode-last-indented-line
10375 (cond
10376 ;; bounce-indenting is disabled during electric-key indent.
10377 ;; It doesn't work well on first line of buffer.
10378 ((and js2-bounce-indent-p
10379 (not (js2-same-line (point-min)))
10380 (not (js2-1-line-comment-continuation-p)))
10381 (js2-bounce-indent indent-col parse-status bounce-backwards))
10382 ;; just indent to the guesser's likely spot
10383 (t (indent-line-to indent-col)))
10384 (when (plusp offset)
10385 (forward-char offset))))))
10386
10387 (defun js2-indent-region (start end)
10388 "Indent the region, but don't use bounce indenting."
10389 (let ((js2-bounce-indent-p nil)
10390 (indent-region-function nil)
10391 (after-change-functions (remq 'js2-mode-edit
10392 after-change-functions)))
10393 (indent-region start end nil) ; nil for byte-compiler
10394 (js2-mode-edit start end (- end start))))
10395
10396 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10397
10398 ;;;###autoload
10399 (defun js2-mode ()
10400 "Major mode for editing JavaScript code."
10401 (interactive)
10402 (kill-all-local-variables)
10403 (set-syntax-table js2-mode-syntax-table)
10404 (use-local-map js2-mode-map)
10405 (make-local-variable 'comment-start)
10406 (make-local-variable 'comment-end)
10407 (make-local-variable 'comment-start-skip)
10408 (setq major-mode 'js2-mode
10409 mode-name "JavaScript-IDE"
10410 comment-start "//" ; used by comment-region; don't change it
10411 comment-end "")
10412 (setq local-abbrev-table js2-mode-abbrev-table)
10413 (set (make-local-variable 'max-lisp-eval-depth)
10414 (max max-lisp-eval-depth 3000))
10415 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10416 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10417
10418 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10419 ;; on most platforms other than the one I originally wrote it on. So it's
10420 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10421 ;; with our binding of the RET key inside comments: short lines stay short.
10422 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10423
10424 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10425 (set (make-local-variable 'next-error-function) #'js2-next-error)
10426 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10427 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10428 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10429 ;; for characters inside regexp literals.
10430 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10431 ;; this is necessary to make `show-paren-function' work properly
10432 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10433 ;; needed for M-x rgrep, among other things
10434 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10435
10436 ;; some variables needed by cc-engine for paragraph-fill, etc.
10437 (setq c-buffer-is-cc-mode t
10438 c-comment-prefix-regexp js2-comment-prefix-regexp
10439 c-comment-start-regexp "/[*/]\\|\\s|"
10440 c-paragraph-start js2-paragraph-start
10441 c-paragraph-separate "$"
10442 comment-start-skip js2-comment-start-skip
10443 c-syntactic-ws-start js2-syntactic-ws-start
10444 c-syntactic-ws-end js2-syntactic-ws-end
10445 c-syntactic-eol js2-syntactic-eol)
10446
10447 (setq js2-default-externs
10448 (append js2-ecma-262-externs
10449 (if js2-include-browser-externs
10450 js2-browser-externs)
10451 (if js2-include-gears-externs
10452 js2-gears-externs)
10453 (if js2-include-rhino-externs
10454 js2-rhino-externs)))
10455
10456 ;; We do our own syntax highlighting based on the parse tree.
10457 ;; However, we want minor modes that add keywords to highlight properly
10458 ;; (examples: doxymacs, column-marker). We do this by not letting
10459 ;; font-lock unfontify anything, and telling it to fontify after we
10460 ;; re-parse and re-highlight the buffer. (We currently don't do any
10461 ;; work with regions other than the whole buffer.)
10462 (dolist (var '(font-lock-unfontify-buffer-function
10463 font-lock-unfontify-region-function))
10464 (set (make-local-variable var) (lambda (&rest args) t)))
10465
10466 ;; Don't let font-lock do syntactic (string/comment) fontification.
10467 (set (make-local-variable #'font-lock-syntactic-face-function)
10468 (lambda (state) nil))
10469
10470 ;; Experiment: make reparse-delay longer for longer files.
10471 (if (plusp js2-dynamic-idle-timer-adjust)
10472 (setq js2-idle-timer-delay
10473 (* js2-idle-timer-delay
10474 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10475
10476 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10477 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10478 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10479 (imenu-add-to-menubar (concat "IM-" mode-name))
10480 (when js2-mirror-mode
10481 (js2-enter-mirror-mode))
10482 (add-to-invisibility-spec '(js2-outline . t))
10483 (set (make-local-variable 'line-move-ignore-invisible) t)
10484 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10485 (setq js2-mode-functions-hidden nil
10486 js2-mode-comments-hidden nil
10487 js2-mode-buffer-dirty-p t
10488 js2-mode-parsing nil)
10489 (js2-reparse)
10490
10491 (if (fboundp 'run-mode-hooks)
10492 (run-mode-hooks 'js2-mode-hook)
10493 (run-hooks 'js2-mode-hook)))
10494
10495 (defun js2-mode-exit ()
10496 "Exit `js2-mode' and clean up."
10497 (interactive)
10498 (when js2-mode-node-overlay
10499 (delete-overlay js2-mode-node-overlay)
10500 (setq js2-mode-node-overlay nil))
10501 (js2-remove-overlays)
10502 (setq js2-mode-ast nil)
10503 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10504 (remove-from-invisibility-spec '(js2-outline . t))
10505 (js2-mode-show-all)
10506 (js2-with-unmodifying-text-property-changes
10507 (js2-clear-face (point-min) (point-max))))
10508
10509 (defun js2-before-save ()
10510 "Clean up whitespace before saving file.
10511 You can disable this by customizing `js2-cleanup-whitespace'."
10512 (when js2-cleanup-whitespace
10513 (let ((col (current-column)))
10514 (delete-trailing-whitespace)
10515 ;; don't change trailing whitespace on current line
10516 (unless (eq (current-column) col)
10517 (indent-to col)))))
10518
10519 (defsubst js2-mode-reset-timer ()
10520 "Cancel any existing parse timer and schedule a new one."
10521 (if js2-mode-parse-timer
10522 (cancel-timer js2-mode-parse-timer))
10523 (setq js2-mode-parsing nil)
10524 (setq js2-mode-parse-timer
10525 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10526
10527 (defun js2-mode-edit (beg end len)
10528 "Schedule a new parse after buffer is edited.
10529 Buffer edit spans from BEG to END and is of length LEN.
10530 Also clears the `js2-magic' bit on autoinserted parens/brackets
10531 if the edit occurred on a line different from the magic paren."
10532 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10533 (line (if magic-pos (line-number-at-pos magic-pos))))
10534 (and line
10535 (or (/= (line-number-at-pos beg) line)
10536 (and (> 0 len)
10537 (/= (line-number-at-pos end) line)))
10538 (js2-mode-mundanify-parens)))
10539 (setq js2-mode-buffer-dirty-p t)
10540 (js2-mode-hide-overlay)
10541 (js2-mode-reset-timer))
10542
10543 (defun js2-mode-run-font-lock ()
10544 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10545 This is intended to allow modes that install their own font-lock keywords
10546 to work with js2-mode. In practice it never seems to work for long.
10547 Hopefully the Emacs maintainers can help figure out a way to make it work."
10548 (when (and (boundp 'font-lock-keywords)
10549 font-lock-keywords
10550 (boundp 'font-lock-mode)
10551 font-lock-mode)
10552 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10553 ;; play nicely with js2-mode. They go out of their way to fail to
10554 ;; provide any option for saying "look, fontify the farging buffer
10555 ;; with just the keywords already". Argh.
10556 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10557 (let (font-lock-verbose)
10558 (font-lock-fontify-buffer))))
10559
10560 (defun js2-reparse (&optional force)
10561 "Re-parse current buffer after user finishes some data entry.
10562 If we get any user input while parsing, including cursor motion,
10563 we discard the parse and reschedule it. If FORCE is nil, then the
10564 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10565 (let (time
10566 interrupted-p
10567 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10568 (unless js2-mode-parsing
10569 (setq js2-mode-parsing t)
10570 (unwind-protect
10571 (when (or js2-mode-buffer-dirty-p force)
10572 (js2-remove-overlays)
10573 (js2-with-unmodifying-text-property-changes
10574 (setq js2-mode-buffer-dirty-p nil
10575 js2-mode-fontifications nil
10576 js2-mode-deferred-properties nil)
10577 (if js2-mode-verbose-parse-p
10578 (message "parsing..."))
10579 (setq time
10580 (js2-time
10581 (setq interrupted-p
10582 (catch 'interrupted
10583 (setq js2-mode-ast (js2-parse))
10584 ;; if parsing is interrupted, comments and regex
10585 ;; literals stay ignored by `parse-partial-sexp'
10586 (remove-text-properties (point-min) (point-max)
10587 '(syntax-table))
10588 (js2-mode-apply-deferred-properties)
10589 (js2-mode-remove-suppressed-warnings)
10590 (js2-mode-show-warnings)
10591 (js2-mode-show-errors)
10592 (js2-mode-run-font-lock) ; note: doesn't work
10593 (js2-mode-highlight-magic-parens)
10594 (if (>= js2-highlight-level 1)
10595 (js2-highlight-jsdoc js2-mode-ast))
10596 nil))))
10597 (if interrupted-p
10598 (progn
10599 ;; unfinished parse => try again
10600 (setq js2-mode-buffer-dirty-p t)
10601 (js2-mode-reset-timer))
10602 (if js2-mode-verbose-parse-p
10603 (message "Parse time: %s" time)))))
10604 (setq js2-mode-parsing nil)
10605 (unless interrupted-p
10606 (setq js2-mode-parse-timer nil))))))
10607
10608 (defun js2-mode-show-node ()
10609 "Debugging aid: highlight selected AST node on mouse click."
10610 (interactive)
10611 (let ((node (js2-node-at-point))
10612 beg
10613 end)
10614 (when js2-mode-show-overlay
10615 (if (null node)
10616 (message "No node found at location %s" (point))
10617 (setq beg (js2-node-abs-pos node)
10618 end (+ beg (js2-node-len node)))
10619 (if js2-mode-node-overlay
10620 (move-overlay js2-mode-node-overlay beg end)
10621 (setq js2-mode-node-overlay (make-overlay beg end))
10622 (overlay-put js2-mode-node-overlay 'face 'highlight))
10623 (js2-with-unmodifying-text-property-changes
10624 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10625 (message "%s, parent: %s"
10626 (js2-node-short-name node)
10627 (if (js2-node-parent node)
10628 (js2-node-short-name (js2-node-parent node))
10629 "nil"))))))
10630
10631 (defun js2-mode-hide-overlay (&optional p1 p2)
10632 "Remove the debugging overlay when the point moves.
10633 P1 and P2 are the old and new values of point, respectively."
10634 (when js2-mode-node-overlay
10635 (let ((beg (overlay-start js2-mode-node-overlay))
10636 (end (overlay-end js2-mode-node-overlay)))
10637 ;; Sometimes we're called spuriously.
10638 (unless (and p2
10639 (>= p2 beg)
10640 (<= p2 end))
10641 (js2-with-unmodifying-text-property-changes
10642 (remove-text-properties beg end '(point-left nil)))
10643 (delete-overlay js2-mode-node-overlay)
10644 (setq js2-mode-node-overlay nil)))))
10645
10646 (defun js2-mode-reset ()
10647 "Debugging helper: reset everything."
10648 (interactive)
10649 (js2-mode-exit)
10650 (js2-mode))
10651
10652 (defsubst js2-mode-show-warn-or-err (e face)
10653 "Highlight a warning or error E with FACE.
10654 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10655 (let* ((key (first e))
10656 (beg (second e))
10657 (end (+ beg (third e)))
10658 ;; Don't inadvertently go out of bounds.
10659 (beg (max (point-min) (min beg (point-max))))
10660 (end (max (point-min) (min end (point-max))))
10661 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10662 (ovl (make-overlay beg end)))
10663 (overlay-put ovl 'face face)
10664 (overlay-put ovl 'js2-error t)
10665 (put-text-property beg end 'help-echo (js2-get-msg key))
10666 (put-text-property beg end 'point-entered #'js2-echo-error)))
10667
10668 (defun js2-remove-overlays ()
10669 "Remove overlays from buffer that have a `js2-error' property."
10670 (let ((beg (point-min))
10671 (end (point-max)))
10672 (save-excursion
10673 (dolist (o (overlays-in beg end))
10674 (when (overlay-get o 'js2-error)
10675 (delete-overlay o))))))
10676
10677 (defun js2-error-at-point (&optional pos)
10678 "Return non-nil if there's an error overlay at POS.
10679 Defaults to point."
10680 (loop with pos = (or pos (point))
10681 for o in (overlays-at pos)
10682 thereis (overlay-get o 'js2-error)))
10683
10684 (defun js2-mode-apply-deferred-properties ()
10685 "Apply fontifications and other text properties recorded during parsing."
10686 (when (plusp js2-highlight-level)
10687 ;; We defer clearing faces as long as possible to eliminate flashing.
10688 (js2-clear-face (point-min) (point-max))
10689 ;; Have to reverse the recorded fontifications list so that errors
10690 ;; and warnings overwrite the normal fontifications.
10691 (dolist (f (nreverse js2-mode-fontifications))
10692 (put-text-property (first f) (second f) 'face (third f)))
10693 (setq js2-mode-fontifications nil))
10694 (dolist (p js2-mode-deferred-properties)
10695 (apply #'put-text-property p))
10696 (setq js2-mode-deferred-properties nil))
10697
10698 (defun js2-mode-show-errors ()
10699 "Highlight syntax errors."
10700 (when js2-mode-show-parse-errors
10701 (dolist (e (js2-ast-root-errors js2-mode-ast))
10702 (js2-mode-show-warn-or-err e 'js2-error-face))))
10703
10704 (defun js2-mode-remove-suppressed-warnings ()
10705 "Take suppressed warnings out of the AST warnings list.
10706 This ensures that the counts and `next-error' are correct."
10707 (setf (js2-ast-root-warnings js2-mode-ast)
10708 (js2-delete-if
10709 (lambda (e)
10710 (let ((key (caar e)))
10711 (or
10712 (and (not js2-strict-trailing-comma-warning)
10713 (string-match "trailing\\.comma" key))
10714 (and (not js2-strict-cond-assign-warning)
10715 (string= key "msg.equal.as.assign"))
10716 (and js2-missing-semi-one-line-override
10717 (string= key "msg.missing.semi")
10718 (let* ((beg (second e))
10719 (node (js2-node-at-point beg))
10720 (fn (js2-mode-find-parent-fn node))
10721 (body (and fn (js2-function-node-body fn)))
10722 (lc (and body (js2-node-abs-pos body)))
10723 (rc (and lc (+ lc (js2-node-len body)))))
10724 (and fn
10725 (or (null body)
10726 (save-excursion
10727 (goto-char beg)
10728 (and (js2-same-line lc)
10729 (js2-same-line rc))))))))))
10730 (js2-ast-root-warnings js2-mode-ast))))
10731
10732 (defun js2-mode-show-warnings ()
10733 "Highlight strict-mode warnings."
10734 (when js2-mode-show-strict-warnings
10735 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10736 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10737
10738 (defun js2-echo-error (old-point new-point)
10739 "Called by point-motion hooks."
10740 (let ((msg (get-text-property new-point 'help-echo)))
10741 (if msg
10742 (message msg))))
10743
10744 (defalias #'js2-echo-help #'js2-echo-error)
10745
10746 (defun js2-enter-key ()
10747 "Handle user pressing the Enter key."
10748 (interactive)
10749 (let ((parse-status (save-excursion
10750 (syntax-ppss (point)))))
10751 (cond
10752 ;; check if we're inside a string
10753 ((nth 3 parse-status)
10754 (js2-mode-split-string parse-status))
10755 ;; check if inside a block comment
10756 ((nth 4 parse-status)
10757 (js2-mode-extend-comment))
10758 (t
10759 ;; should probably figure out what the mode-map says we should do
10760 (if js2-indent-on-enter-key
10761 (let ((js2-bounce-indent-p nil))
10762 (js2-indent-line)))
10763 (insert "\n")
10764 (if js2-enter-indents-newline
10765 (let ((js2-bounce-indent-p nil))
10766 (js2-indent-line)))))))
10767
10768 (defun js2-mode-split-string (parse-status)
10769 "Turn a newline in mid-string into a string concatenation.
10770 PARSE-STATUS is as documented in `parse-partial-sexp'."
10771 (let* ((col (current-column))
10772 (quote-char (nth 3 parse-status))
10773 (quote-string (string quote-char))
10774 (string-beg (nth 8 parse-status))
10775 (indent (save-match-data
10776 (or
10777 (save-excursion
10778 (back-to-indentation)
10779 (if (looking-at "\\+")
10780 (current-column)))
10781 (save-excursion
10782 (goto-char string-beg)
10783 (if (looking-back "\\+\\s-+")
10784 (goto-char (match-beginning 0)))
10785 (current-column))))))
10786 (insert quote-char "\n")
10787 (indent-to indent)
10788 (insert "+ " quote-string)
10789 (when (eolp)
10790 (insert quote-string)
10791 (backward-char 1))))
10792
10793 (defun js2-mode-extend-comment ()
10794 "When inside a comment block, add comment prefix."
10795 (let (star single col first-line needs-close)
10796 (save-excursion
10797 (back-to-indentation)
10798 (cond
10799 ((looking-at "\\*[^/]")
10800 (setq star t
10801 col (current-column)))
10802 ((looking-at "/\\*")
10803 (setq star t
10804 first-line t
10805 col (1+ (current-column))))
10806 ((looking-at "//")
10807 (setq single t
10808 col (current-column)))))
10809 ;; Heuristic for whether we need to close the comment:
10810 ;; if we've got a parse error here, assume it's an unterminated
10811 ;; comment.
10812 (setq needs-close
10813 (or
10814 (eq (get-text-property (1- (point)) 'point-entered)
10815 'js2-echo-error)
10816 ;; The heuristic above doesn't work well when we're
10817 ;; creating a comment and there's another one downstream,
10818 ;; as our parser thinks this one ends at the end of the
10819 ;; next one. (You can have a /* inside a js block comment.)
10820 ;; So just close it if the next non-ws char isn't a *.
10821 (and first-line
10822 (eolp)
10823 (save-excursion
10824 (skip-chars-forward " \t\r\n")
10825 (not (eq (char-after) ?*))))))
10826 (insert "\n")
10827 (cond
10828 (star
10829 (indent-to col)
10830 (insert "* ")
10831 (if (and first-line needs-close)
10832 (save-excursion
10833 (insert "\n")
10834 (indent-to col)
10835 (insert "*/"))))
10836 (single
10837 (when (save-excursion
10838 (and (zerop (forward-line 1))
10839 (looking-at "\\s-*//")))
10840 (indent-to col)
10841 (insert "// "))))))
10842
10843 (defun js2-beginning-of-line ()
10844 "Toggles point between bol and first non-whitespace char in line.
10845 Also moves past comment delimiters when inside comments."
10846 (interactive)
10847 (let (node beg)
10848 (cond
10849 ((bolp)
10850 (back-to-indentation))
10851 ((looking-at "//")
10852 (skip-chars-forward "/ \t"))
10853 ((and (eq (char-after) ?*)
10854 (setq node (js2-comment-at-point))
10855 (memq (js2-comment-node-format node) '(jsdoc block))
10856 (save-excursion
10857 (skip-chars-backward " \t")
10858 (bolp)))
10859 (skip-chars-forward "\* \t"))
10860 (t
10861 (goto-char (point-at-bol))))))
10862
10863 (defun js2-end-of-line ()
10864 "Toggles point between eol and last non-whitespace char in line."
10865 (interactive)
10866 (if (eolp)
10867 (skip-chars-backward " \t")
10868 (goto-char (point-at-eol))))
10869
10870 (defun js2-enter-mirror-mode()
10871 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10872 on insertion."
10873 (interactive)
10874 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10875 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10876 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10877 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10878 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10879 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10880 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10881 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10882
10883 (defun js2-leave-mirror-mode()
10884 "Turns off mirror mode."
10885 (interactive)
10886 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10887 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10888
10889 (defsubst js2-mode-inside-string ()
10890 "Return non-nil if inside a string.
10891 Actually returns the quote character that begins the string."
10892 (let ((parse-state (save-excursion
10893 (syntax-ppss (point)))))
10894 (nth 3 parse-state)))
10895
10896 (defsubst js2-mode-inside-comment-or-string ()
10897 "Return non-nil if inside a comment or string."
10898 (or
10899 (let ((comment-start
10900 (save-excursion
10901 (goto-char (point-at-bol))
10902 (if (re-search-forward "//" (point-at-eol) t)
10903 (match-beginning 0)))))
10904 (and comment-start
10905 (<= comment-start (point))))
10906 (let ((parse-state (save-excursion
10907 (syntax-ppss (point)))))
10908 (or (nth 3 parse-state)
10909 (nth 4 parse-state)))))
10910
10911 (defsubst js2-make-magic-delimiter (delim &optional pos)
10912 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10913 Sets value of `js2-magic' text property to line number at POS."
10914 (propertize delim
10915 'js2-magic (line-number-at-pos pos)
10916 'face 'js2-magic-paren-face))
10917
10918 (defun js2-mode-match-delimiter (open close)
10919 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10920 The rule we use, which as far as we can tell is how Eclipse works,
10921 is that we insert the match if we're not in a comment or string,
10922 and the next non-whitespace character is either punctuation or
10923 occurs on another line."
10924 (insert open)
10925 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10926 (not (js2-mode-inside-comment-or-string)))
10927 (save-excursion
10928 (insert (js2-make-magic-delimiter close)))
10929 (when js2-auto-indent-p
10930 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10931 (js2-indent-line)))))
10932
10933 (defun js2-mode-match-bracket ()
10934 "Insert matching bracket."
10935 (interactive)
10936 (js2-mode-match-delimiter "[" "]"))
10937
10938 (defun js2-mode-match-paren ()
10939 "Insert matching paren unless already inserted."
10940 (interactive)
10941 (js2-mode-match-delimiter "(" ")"))
10942
10943 (defun js2-mode-match-curly (arg)
10944 "Insert matching curly-brace.
10945 With prefix arg, no formatting or indentation will occur -- the close-brace
10946 is simply inserted directly at the point."
10947 (interactive "p")
10948 (let (try-pos)
10949 (cond
10950 (current-prefix-arg
10951 (js2-mode-match-delimiter "{" "}"))
10952 ((and js2-auto-insert-catch-block
10953 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10954 (point-at-bol))
10955 (match-beginning 1))))
10956 (js2-insert-catch-skel try-pos))
10957 (t
10958 ;; Otherwise try to do something smarter.
10959 (insert "{")
10960 (unless (or (not (looking-at "\\s-*$"))
10961 (save-excursion
10962 (skip-chars-forward " \t\r\n")
10963 (and (looking-at "}")
10964 (js2-error-at-point)))
10965 (js2-mode-inside-comment-or-string))
10966 (undo-boundary)
10967 ;; absolutely mystifying bug: when inserting the next "\n",
10968 ;; the buffer-undo-list is given two new entries: the inserted range,
10969 ;; and the incorrect position of the point. It's recorded incorrectly
10970 ;; as being before the opening "{", not after it. But it's recorded
10971 ;; as the correct value if you're debugging `js2-mode-match-curly'
10972 ;; in edebug. I have no idea why it's doing this, but incrementing
10973 ;; the inserted position fixes the problem, so that the undo takes us
10974 ;; back to just after the user-inserted "{".
10975 (insert "\n")
10976 (ignore-errors
10977 (incf (cadr buffer-undo-list)))
10978 (js2-indent-line)
10979 (save-excursion
10980 (insert "\n}")
10981 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10982 (js2-indent-line))))))))
10983
10984 (defun js2-insert-catch-skel (try-pos)
10985 "Complete a try/catch block after inserting a { following a try keyword.
10986 Rationale is that a try always needs a catch or a finally, and the catch is
10987 the more likely of the two.
10988
10989 TRY-POS is the buffer position of the try keyword. The open-curly should
10990 already have been inserted."
10991 (insert "{")
10992 (let ((try-col (save-excursion
10993 (goto-char try-pos)
10994 (current-column))))
10995 (insert "\n")
10996 (undo-boundary)
10997 (js2-indent-line) ;; indent the blank line where cursor will end up
10998 (save-excursion
10999 (insert "\n")
11000 (indent-to try-col)
11001 (insert "} catch (x) {\n\n")
11002 (indent-to try-col)
11003 (insert "}"))))
11004
11005 (defun js2-mode-highlight-magic-parens ()
11006 "Re-highlight magic parens after parsing nukes the 'face prop."
11007 (let ((beg (point-min))
11008 end)
11009 (while (setq beg (next-single-property-change beg 'js2-magic))
11010 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11011 (if (get-text-property beg 'js2-magic)
11012 (js2-with-unmodifying-text-property-changes
11013 (put-text-property beg (or end (1+ beg))
11014 'face 'js2-magic-paren-face))))))
11015
11016 (defun js2-mode-mundanify-parens ()
11017 "Clear all magic parens and brackets."
11018 (let ((beg (point-min))
11019 end)
11020 (while (setq beg (next-single-property-change beg 'js2-magic))
11021 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11022 (remove-text-properties beg (or end (1+ beg))
11023 '(js2-magic face)))))
11024
11025 (defsubst js2-match-quote (quote-string)
11026 (let ((start-quote (js2-mode-inside-string)))
11027 (cond
11028 ;; inside a comment - don't do quote-matching, since we can't
11029 ;; reliably figure out if we're in a string inside the comment
11030 ((js2-comment-at-point)
11031 (insert quote-string))
11032 ((not start-quote)
11033 ;; not in string => insert matched quotes
11034 (insert quote-string)
11035 ;; exception: if we're just before a word, don't double it.
11036 (unless (looking-at "[^ \t\r\n]")
11037 (save-excursion
11038 (insert quote-string))))
11039 ((looking-at quote-string)
11040 (if (looking-back "[^\\]\\\\")
11041 (insert quote-string)
11042 (forward-char 1)))
11043 ((and js2-mode-escape-quotes
11044 (save-excursion
11045 (save-match-data
11046 (re-search-forward quote-string (point-at-eol) t))))
11047 ;; inside terminated string, escape quote (unless already escaped)
11048 (insert (if (looking-back "[^\\]\\\\")
11049 quote-string
11050 (concat "\\" quote-string))))
11051 (t
11052 (insert quote-string))))) ; else terminate the string
11053
11054 (defun js2-mode-match-single-quote ()
11055 "Insert matching single-quote."
11056 (interactive)
11057 (let ((parse-status (syntax-ppss (point))))
11058 ;; don't match inside comments, since apostrophe is more common
11059 (if (nth 4 parse-status)
11060 (insert "'")
11061 (js2-match-quote "'"))))
11062
11063 (defun js2-mode-match-double-quote ()
11064 "Insert matching double-quote."
11065 (interactive)
11066 (js2-match-quote "\""))
11067
11068 ;; Eclipse works as follows:
11069 ;; * type an open-paren and it auto-inserts close-paren
11070 ;; - auto-inserted paren gets a green bracket
11071 ;; - green bracket means typing close-paren there will skip it
11072 ;; * if you insert any text on a different line, it turns off
11073 (defun js2-mode-magic-close-paren ()
11074 "Skip over close-paren rather than inserting, where appropriate."
11075 (interactive)
11076 (let* ((here (point))
11077 (parse-status (syntax-ppss here))
11078 (open-pos (nth 1 parse-status))
11079 (close last-input-event)
11080 (open (cond
11081 ((eq close ?\))
11082 ?\()
11083 ((eq close ?\])
11084 ?\[)
11085 ((eq close ?})
11086 ?{)
11087 (t nil))))
11088 (if (and (eq (char-after) close)
11089 (eq open (char-after open-pos))
11090 (js2-same-line open-pos)
11091 (get-text-property here 'js2-magic))
11092 (progn
11093 (remove-text-properties here (1+ here) '(js2-magic face))
11094 (forward-char 1))
11095 (insert-char close 1))
11096 (blink-matching-open)))
11097
11098 (defun js2-mode-wait-for-parse (callback)
11099 "Invoke CALLBACK when parsing is finished.
11100 If parsing is already finished, calls CALLBACK immediately."
11101 (if (not js2-mode-buffer-dirty-p)
11102 (funcall callback)
11103 (push callback js2-mode-pending-parse-callbacks)
11104 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11105
11106 (defun js2-mode-parse-finished ()
11107 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11108 ;; We can't let errors propagate up, since it prevents the
11109 ;; `js2-parse' method from completing normally and returning
11110 ;; the ast, which makes things mysteriously not work right.
11111 (unwind-protect
11112 (dolist (cb js2-mode-pending-parse-callbacks)
11113 (condition-case err
11114 (funcall cb)
11115 (error (message "%s" err))))
11116 (setq js2-mode-pending-parse-callbacks nil)))
11117
11118 (defun js2-mode-flag-region (from to flag)
11119 "Hide or show text from FROM to TO, according to FLAG.
11120 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11121 Returns the created overlay if FLAG is non-nil."
11122 (remove-overlays from to 'invisible 'js2-outline)
11123 (when flag
11124 (let ((o (make-overlay from to)))
11125 (overlay-put o 'invisible 'js2-outline)
11126 (overlay-put o 'isearch-open-invisible
11127 'js2-isearch-open-invisible)
11128 o)))
11129
11130 ;; Function to be set as an outline-isearch-open-invisible' property
11131 ;; to the overlay that makes the outline invisible (see
11132 ;; `js2-mode-flag-region').
11133 (defun js2-isearch-open-invisible (overlay)
11134 ;; We rely on the fact that isearch places point on the matched text.
11135 (js2-mode-show-element))
11136
11137 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11138 "Return cons cell of bounds of folding overlay at POS.
11139 Returns nil if not found."
11140 (let ((overlays (overlays-at (or pos (point))))
11141 o)
11142 (while (and overlays
11143 (not o))
11144 (if (overlay-get (car overlays) 'invisible)
11145 (setq o (car overlays))
11146 (setq overlays (cdr overlays))))
11147 (if o
11148 (cons (overlay-start o) (overlay-end o)))))
11149
11150 (defun js2-mode-function-at-point (&optional pos)
11151 "Return the innermost function node enclosing current point.
11152 Returns nil if point is not in a function."
11153 (let ((node (js2-node-at-point pos)))
11154 (while (and node (not (js2-function-node-p node)))
11155 (setq node (js2-node-parent node)))
11156 (if (js2-function-node-p node)
11157 node)))
11158
11159 (defun js2-mode-toggle-element ()
11160 "Hide or show the foldable element at the point."
11161 (interactive)
11162 (let (comment fn pos)
11163 (save-excursion
11164 (save-match-data
11165 (cond
11166 ;; /* ... */ comment?
11167 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11168 (if (js2-mode-invisible-overlay-bounds
11169 (setq pos (+ 3 (js2-node-abs-pos comment))))
11170 (progn
11171 (goto-char pos)
11172 (js2-mode-show-element))
11173 (js2-mode-hide-element)))
11174 ;; //-comment?
11175 ((save-excursion
11176 (back-to-indentation)
11177 (looking-at js2-mode-//-comment-re))
11178 (js2-mode-toggle-//-comment))
11179 ;; function?
11180 ((setq fn (js2-mode-function-at-point))
11181 (setq pos (and (js2-function-node-body fn)
11182 (js2-node-abs-pos (js2-function-node-body fn))))
11183 (goto-char (1+ pos))
11184 (if (js2-mode-invisible-overlay-bounds)
11185 (js2-mode-show-element)
11186 (js2-mode-hide-element)))
11187 (t
11188 (message "Nothing at point to hide or show")))))))
11189
11190 (defun js2-mode-hide-element ()
11191 "Fold/hide contents of a block, showing ellipses.
11192 Show the hidden text with \\[js2-mode-show-element]."
11193 (interactive)
11194 (if js2-mode-buffer-dirty-p
11195 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11196 (let (node body beg end)
11197 (cond
11198 ((js2-mode-invisible-overlay-bounds)
11199 (message "already hidden"))
11200 (t
11201 (setq node (js2-node-at-point))
11202 (cond
11203 ((js2-block-comment-p node)
11204 (js2-mode-hide-comment node))
11205 (t
11206 (while (and node (not (js2-function-node-p node)))
11207 (setq node (js2-node-parent node)))
11208 (if (and node
11209 (setq body (js2-function-node-body node)))
11210 (progn
11211 (setq beg (js2-node-abs-pos body)
11212 end (+ beg (js2-node-len body)))
11213 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11214 (message "No collapsable element found at point"))))))))
11215
11216 (defun js2-mode-show-element ()
11217 "Show the hidden element at current point."
11218 (interactive)
11219 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11220 (if bounds
11221 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11222 (message "Nothing to un-hide"))))
11223
11224 (defun js2-mode-show-all ()
11225 "Show all of the text in the buffer."
11226 (interactive)
11227 (js2-mode-flag-region (point-min) (point-max) nil))
11228
11229 (defun js2-mode-toggle-hide-functions ()
11230 (interactive)
11231 (if js2-mode-functions-hidden
11232 (js2-mode-show-functions)
11233 (js2-mode-hide-functions)))
11234
11235 (defun js2-mode-hide-functions ()
11236 "Hides all non-nested function bodies in the buffer.
11237 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11238 to open an individual entry."
11239 (interactive)
11240 (if js2-mode-buffer-dirty-p
11241 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11242 (if (null js2-mode-ast)
11243 (message "Oops - parsing failed")
11244 (setq js2-mode-functions-hidden t)
11245 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11246
11247 (defun js2-mode-function-hider (n endp)
11248 (when (not endp)
11249 (let ((tt (js2-node-type n))
11250 body beg end)
11251 (cond
11252 ((and (= tt js2-FUNCTION)
11253 (setq body (js2-function-node-body n)))
11254 (setq beg (js2-node-abs-pos body)
11255 end (+ beg (js2-node-len body)))
11256 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11257 nil) ; don't process children of function
11258 (t
11259 t))))) ; keep processing other AST nodes
11260
11261 (defun js2-mode-show-functions ()
11262 "Un-hide any folded function bodies in the buffer."
11263 (interactive)
11264 (setq js2-mode-functions-hidden nil)
11265 (save-excursion
11266 (goto-char (point-min))
11267 (while (/= (goto-char (next-overlay-change (point)))
11268 (point-max))
11269 (dolist (o (overlays-at (point)))
11270 (when (and (overlay-get o 'invisible)
11271 (not (overlay-get o 'comment)))
11272 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11273
11274 (defun js2-mode-hide-comment (n)
11275 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11276 3 ; /**
11277 2)) ; /*
11278 (beg (+ (js2-node-abs-pos n) head))
11279 (end (- (+ beg (js2-node-len n)) head 2))
11280 (o (js2-mode-flag-region beg end 'hide)))
11281 (overlay-put o 'comment t)))
11282
11283 (defun js2-mode-toggle-hide-comments ()
11284 "Folds all block comments in the buffer.
11285 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11286 to open an individual entry."
11287 (interactive)
11288 (if js2-mode-comments-hidden
11289 (js2-mode-show-comments)
11290 (js2-mode-hide-comments)))
11291
11292 (defun js2-mode-hide-comments ()
11293 (interactive)
11294 (if js2-mode-buffer-dirty-p
11295 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11296 (if (null js2-mode-ast)
11297 (message "Oops - parsing failed")
11298 (setq js2-mode-comments-hidden t)
11299 (dolist (n (js2-ast-root-comments js2-mode-ast))
11300 (let ((format (js2-comment-node-format n)))
11301 (when (js2-block-comment-p n)
11302 (js2-mode-hide-comment n))))
11303 (js2-mode-hide-//-comments)))
11304
11305 (defsubst js2-mode-extend-//-comment (direction)
11306 "Find start or end of a block of similar //-comment lines.
11307 DIRECTION is -1 to look back, 1 to look forward.
11308 INDENT is the indentation level to match.
11309 Returns the end-of-line position of the furthest adjacent
11310 //-comment line with the same indentation as the current line.
11311 If there is no such matching line, returns current end of line."
11312 (let ((pos (point-at-eol))
11313 (indent (current-indentation)))
11314 (save-excursion
11315 (save-match-data
11316 (while (and (zerop (forward-line direction))
11317 (looking-at js2-mode-//-comment-re)
11318 (eq indent (length (match-string 1))))
11319 (setq pos (point-at-eol)))
11320 pos))))
11321
11322 (defun js2-mode-hide-//-comments ()
11323 "Fold adjacent 1-line comments, showing only snippet of first one."
11324 (let (beg end)
11325 (save-excursion
11326 (save-match-data
11327 (goto-char (point-min))
11328 (while (re-search-forward js2-mode-//-comment-re nil t)
11329 (setq beg (point)
11330 end (js2-mode-extend-//-comment 1))
11331 (unless (eq beg end)
11332 (overlay-put (js2-mode-flag-region beg end 'hide)
11333 'comment t))
11334 (goto-char end)
11335 (forward-char 1))))))
11336
11337 (defun js2-mode-toggle-//-comment ()
11338 "Fold or un-fold any multi-line //-comment at point.
11339 Caller should have determined that this line starts with a //-comment."
11340 (let* ((beg (point-at-eol))
11341 (end beg))
11342 (save-excursion
11343 (goto-char end)
11344 (if (js2-mode-invisible-overlay-bounds)
11345 (js2-mode-show-element)
11346 ;; else hide the comment
11347 (setq beg (js2-mode-extend-//-comment -1)
11348 end (js2-mode-extend-//-comment 1))
11349 (unless (eq beg end)
11350 (overlay-put (js2-mode-flag-region beg end 'hide)
11351 'comment t))))))
11352
11353 (defun js2-mode-show-comments ()
11354 "Un-hide any hidden comments, leaving other hidden elements alone."
11355 (interactive)
11356 (setq js2-mode-comments-hidden nil)
11357 (save-excursion
11358 (goto-char (point-min))
11359 (while (/= (goto-char (next-overlay-change (point)))
11360 (point-max))
11361 (dolist (o (overlays-at (point)))
11362 (when (overlay-get o 'comment)
11363 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11364
11365 (defun js2-mode-display-warnings-and-errors ()
11366 "Turn on display of warnings and errors."
11367 (interactive)
11368 (setq js2-mode-show-parse-errors t
11369 js2-mode-show-strict-warnings t)
11370 (js2-reparse 'force))
11371
11372 (defun js2-mode-hide-warnings-and-errors ()
11373 "Turn off display of warnings and errors."
11374 (interactive)
11375 (setq js2-mode-show-parse-errors nil
11376 js2-mode-show-strict-warnings nil)
11377 (js2-reparse 'force))
11378
11379 (defun js2-mode-toggle-warnings-and-errors ()
11380 "Toggle the display of warnings and errors.
11381 Some users don't like having warnings/errors reported while they type."
11382 (interactive)
11383 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11384 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11385 (if (interactive-p)
11386 (message "warnings and errors %s"
11387 (if js2-mode-show-parse-errors
11388 "enabled"
11389 "disabled")))
11390 (js2-reparse 'force))
11391
11392 (defun js2-mode-customize ()
11393 (interactive)
11394 (customize-group 'js2-mode))
11395
11396 (defun js2-mode-forward-sexp (&optional arg)
11397 "Move forward across one statement or balanced expression.
11398 With ARG, do it that many times. Negative arg -N means
11399 move backward across N balanced expressions."
11400 (interactive "p")
11401 (setq arg (or arg 1))
11402 (if js2-mode-buffer-dirty-p
11403 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11404 (let (node end (start (point)))
11405 (cond
11406 ;; backward-sexp
11407 ;; could probably make this better for some cases:
11408 ;; - if in statement block (e.g. function body), go to parent
11409 ;; - infix exprs like (foo in bar) - maybe go to beginning
11410 ;; of infix expr if in the right-side expression?
11411 ((and arg (minusp arg))
11412 (dotimes (i (- arg))
11413 (js2-backward-sws)
11414 (forward-char -1) ; enter the node we backed up to
11415 (setq node (js2-node-at-point (point) t))
11416 (goto-char (if node
11417 (js2-node-abs-pos node)
11418 (point-min)))))
11419 (t
11420 ;; forward-sexp
11421 (js2-forward-sws)
11422 (dotimes (i arg)
11423 (js2-forward-sws)
11424 (setq node (js2-node-at-point (point) t)
11425 end (if node (+ (js2-node-abs-pos node)
11426 (js2-node-len node))))
11427 (goto-char (or end (point-max))))))))
11428
11429 (defun js2-next-error (&optional arg reset)
11430 "Move to next parse error.
11431 Typically invoked via \\[next-error].
11432 ARG is the number of errors, forward or backward, to move.
11433 RESET means start over from the beginning."
11434 (interactive "p")
11435 (if (or (null js2-mode-ast)
11436 (and (null (js2-ast-root-errors js2-mode-ast))
11437 (null (js2-ast-root-warnings js2-mode-ast))))
11438 (message "No errors")
11439 (when reset
11440 (goto-char (point-min)))
11441 (let* ((errs (copy-sequence
11442 (append (js2-ast-root-errors js2-mode-ast)
11443 (js2-ast-root-warnings js2-mode-ast))))
11444 (continue t)
11445 (start (point))
11446 (count (or arg 1))
11447 (backward (minusp count))
11448 (sorter (if backward '> '<))
11449 (stopper (if backward '< '>))
11450 (count (abs count))
11451 all-errs
11452 err)
11453 ;; sort by start position
11454 (setq errs (sort errs (lambda (e1 e2)
11455 (funcall sorter (second e1) (second e2))))
11456 all-errs errs)
11457 ;; find nth error with pos > start
11458 (while (and errs continue)
11459 (when (funcall stopper (cadar errs) start)
11460 (setq err (car errs))
11461 (if (zerop (decf count))
11462 (setq continue nil)))
11463 (setq errs (cdr errs)))
11464 (if err
11465 (goto-char (second err))
11466 ;; wrap around to first error
11467 (goto-char (second (car all-errs)))
11468 ;; if we were already on it, echo msg again
11469 (if (= (point) start)
11470 (js2-echo-error (point) (point)))))))
11471
11472 (defun js2-down-mouse-3 ()
11473 "Make right-click move the point to the click location.
11474 This makes right-click context menu operations a bit more intuitive.
11475 The point will not move if the region is active, however, to avoid
11476 destroying the region selection."
11477 (interactive)
11478 (when (and js2-move-point-on-right-click
11479 (not mark-active))
11480 (let ((e last-input-event))
11481 (ignore-errors
11482 (goto-char (cadadr e))))))
11483
11484 (defun js2-mode-create-imenu-index ()
11485 "Return an alist for `imenu--index-alist'."
11486 ;; This is built up in `js2-parse-record-imenu' during parsing.
11487 (when js2-mode-ast
11488 ;; if we have an ast but no recorder, they're requesting a rescan
11489 (unless js2-imenu-recorder
11490 (js2-reparse 'force))
11491 (prog1
11492 (js2-build-imenu-index)
11493 (setq js2-imenu-recorder nil
11494 js2-imenu-function-map nil))))
11495
11496 (defun js2-mode-find-tag ()
11497 "Replacement for `find-tag-default'.
11498 `find-tag-default' returns a ridiculous answer inside comments."
11499 (let (beg end)
11500 (js2-with-underscore-as-word-syntax
11501 (save-excursion
11502 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11503 (looking-back "[A-Za-z0-9_$]"))
11504 (setq beg (progn (forward-word -1) (point))
11505 end (progn (forward-word 1) (point)))
11506 (setq beg (progn (forward-word 1) (point))
11507 end (progn (forward-word -1) (point))))
11508 (replace-regexp-in-string
11509 "[\"']" ""
11510 (buffer-substring-no-properties beg end))))))
11511
11512 (defun js2-mode-forward-sibling ()
11513 "Move to the end of the sibling following point in parent.
11514 Returns non-nil if successful, or nil if there was no following sibling."
11515 (let* ((node (js2-node-at-point))
11516 (parent (js2-mode-find-enclosing-fn node))
11517 sib)
11518 (when (setq sib (js2-node-find-child-after (point) parent))
11519 (goto-char (+ (js2-node-abs-pos sib)
11520 (js2-node-len sib))))))
11521
11522 (defun js2-mode-backward-sibling ()
11523 "Move to the beginning of the sibling node preceding point in parent.
11524 Parent is defined as the enclosing script or function."
11525 (let* ((node (js2-node-at-point))
11526 (parent (js2-mode-find-enclosing-fn node))
11527 sib)
11528 (when (setq sib (js2-node-find-child-before (point) parent))
11529 (goto-char (js2-node-abs-pos sib)))))
11530
11531 (defun js2-beginning-of-defun ()
11532 "Go to line on which current function starts, and return non-nil.
11533 If we're not in a function, go to beginning of previous script-level element."
11534 (interactive)
11535 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11536 pos sib)
11537 (cond
11538 ((and (js2-function-node-p parent)
11539 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11540 (goto-char pos))
11541 (t
11542 (js2-mode-backward-sibling)))))
11543
11544 (defun js2-end-of-defun ()
11545 "Go to the char after the last position of the current function.
11546 If we're not in a function, skips over the next script-level element."
11547 (interactive)
11548 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11549 (if (not (js2-function-node-p parent))
11550 ;; punt: skip over next script-level element beyond point
11551 (js2-mode-forward-sibling)
11552 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11553 (js2-node-len parent)))))))
11554
11555 (defun js2-mark-defun (&optional allow-extend)
11556 "Put mark at end of this function, point at beginning.
11557 The function marked is the one that contains point.
11558
11559 Interactively, if this command is repeated,
11560 or (in Transient Mark mode) if the mark is active,
11561 it marks the next defun after the ones already marked."
11562 (interactive "p")
11563 (let (extended)
11564 (when (and allow-extend
11565 (or (and (eq last-command this-command) (mark t))
11566 (and transient-mark-mode mark-active)))
11567 (let ((sib (save-excursion
11568 (goto-char (mark))
11569 (if (js2-mode-forward-sibling)
11570 (point))))
11571 node)
11572 (if sib
11573 (progn
11574 (set-mark sib)
11575 (setq extended t))
11576 ;; no more siblings - try extending to enclosing node
11577 (goto-char (mark t)))))
11578 (when (not extended)
11579 (let ((node (js2-node-at-point (point) t)) ; skip comments
11580 ast fn stmt parent beg end)
11581 (when (js2-ast-root-p node)
11582 (setq ast node
11583 node (or (js2-node-find-child-after (point) node)
11584 (js2-node-find-child-before (point) node))))
11585 ;; only mark whole buffer if we can't find any children
11586 (if (null node)
11587 (setq node ast))
11588 (if (js2-function-node-p node)
11589 (setq parent node)
11590 (setq fn (js2-mode-find-enclosing-fn node)
11591 stmt (if (or (null fn)
11592 (js2-ast-root-p fn))
11593 (js2-mode-find-first-stmt node))
11594 parent (or stmt fn)))
11595 (setq beg (js2-node-abs-pos parent)
11596 end (+ beg (js2-node-len parent)))
11597 (push-mark beg)
11598 (goto-char end)
11599 (exchange-point-and-mark)))))
11600
11601 (defun js2-narrow-to-defun ()
11602 "Narrow to the function enclosing point."
11603 (interactive)
11604 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11605 (fn (if (js2-script-node-p node)
11606 node
11607 (js2-mode-find-enclosing-fn node)))
11608 (beg (js2-node-abs-pos fn)))
11609 (unless (js2-ast-root-p fn)
11610 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11611
11612 (provide 'js2-mode)
11613
11614 ;;; js2-mode.el ends here