]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Don't call `js2-mode-edit' when inside `indent-region'
[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-indent-on-enter-key nil
244 "Non-nil to have Enter/Return key indent the line.
245 This is unusual for Emacs modes but common in IDEs like Eclipse."
246 :type 'boolean
247 :group 'js2-mode)
248
249 (defcustom js2-enter-indents-newline nil
250 "Non-nil to have Enter/Return key indent the newly-inserted line.
251 This is unusual for Emacs modes but common in IDEs like Eclipse."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-rebind-eol-bol-keys t
256 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
257 If non-nil, bounce between bol/eol and first/last non-whitespace char."
258 :group 'js2-mode
259 :type 'boolean)
260
261 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
262 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
263 Each value in the list is passed to `define-key'."
264 :type 'list
265 :group 'js2-mode)
266
267 (defcustom js2-idle-timer-delay 0.2
268 "Delay in secs before re-parsing after user makes changes.
269 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
270 :type 'number
271 :group 'js2-mode)
272 (make-variable-buffer-local 'js2-idle-timer-delay)
273
274 (defcustom js2-dynamic-idle-timer-adjust 0
275 "Positive to adjust `js2-idle-timer-delay' based on file size.
276 The idea is that for short files, parsing is faster so we can be
277 more responsive to user edits without interfering with editing.
278 The buffer length in characters (typically bytes) is divided by
279 this value and used to multiply `js2-idle-timer-delay' for the
280 buffer. For example, a 21k file and 10k adjust yields 21k/10k
281 == 2, so js2-idle-timer-delay is multiplied by 2.
282 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
283 `js2-idle-timer-delay' is not dependent on the file size."
284 :type 'number
285 :group 'js2-mode)
286
287 (defcustom js2-mode-escape-quotes t
288 "Non-nil to disable automatic quote-escaping inside strings."
289 :type 'boolean
290 :group 'js2-mode)
291
292 (defcustom js2-mode-squeeze-spaces t
293 "Non-nil to normalize whitespace when filling in comments.
294 Multiple runs of spaces are converted to a single space."
295 :type 'boolean
296 :group 'js2-mode)
297
298 (defcustom js2-mode-show-parse-errors t
299 "True to highlight parse errors."
300 :type 'boolean
301 :group 'js2-mode)
302
303 (defcustom js2-mode-show-strict-warnings t
304 "Non-nil to emit Ecma strict-mode warnings.
305 Some of the warnings can be individually disabled by other flags,
306 even if this flag is non-nil."
307 :type 'boolean
308 :group 'js2-mode)
309
310 (defcustom js2-strict-trailing-comma-warning t
311 "Non-nil to warn about trailing commas in array literals.
312 Ecma-262 forbids them, but many browsers permit them. IE is the
313 big exception, and can produce bugs if you have trailing commas."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-missing-semi-warning t
318 "Non-nil to warn about semicolon auto-insertion after statement.
319 Technically this is legal per Ecma-262, but some style guides disallow
320 depending on it."
321 :type 'boolean
322 :group 'js2-mode)
323
324 (defcustom js2-missing-semi-one-line-override nil
325 "Non-nil to permit missing semicolons in one-line functions.
326 In one-liner functions such as `function identity(x) {return x}'
327 people often omit the semicolon for a cleaner look. If you are
328 such a person, you can suppress the missing-semicolon warning
329 by setting this variable to t."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-inconsistent-return-warning t
334 "Non-nil to warn about mixing returns with value-returns.
335 It's perfectly legal to have a `return' and a `return foo' in the
336 same function, but it's often an indicator of a bug, and it also
337 interferes with type inference (in systems that support it.)"
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-strict-cond-assign-warning t
342 "Non-nil to warn about expressions like if (a = b).
343 This often should have been '==' instead of '='. If the warning
344 is enabled, you can suppress it on a per-expression basis by
345 parenthesizing the expression, e.g. if ((a = b)) ..."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-cond-assign-warning t
350 "Non-nil to warn about expressions like if (a = b).
351 This often should have been '==' instead of '='. If the warning
352 is enabled, you can suppress it on a per-expression basis by
353 parenthesizing the expression, e.g. if ((a = b)) ..."
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-var-redeclaration-warning t
358 "Non-nil to warn about redeclaring variables in a script or function."
359 :type 'boolean
360 :group 'js2-mode)
361
362 (defcustom js2-strict-var-hides-function-arg-warning t
363 "Non-nil to warn about a var decl hiding a function argument."
364 :type 'boolean
365 :group 'js2-mode)
366
367 (defcustom js2-skip-preprocessor-directives nil
368 "Non-nil to treat lines beginning with # as comments.
369 Useful for viewing Mozilla JavaScript source code."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-language-version 180
374 "Configures what JavaScript language version to recognize.
375 Currently versions 150, 160, 170 and 180 are supported, corresponding
376 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
377 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
378 and 1.8 adds function closures."
379 :type 'integer
380 :group 'js2-mode)
381
382 (defcustom js2-allow-keywords-as-property-names t
383 "If non-nil, you can use JavaScript keywords as object property names.
384 Examples:
385
386 var foo = {int: 5, while: 6, continue: 7};
387 foo.return = 8;
388
389 Ecma-262 forbids this syntax, but many browsers support it."
390 :type 'boolean
391 :group 'js2-mode)
392
393 (defcustom js2-instanceof-has-side-effects nil
394 "If non-nil, treats the instanceof operator as having side effects.
395 This is useful for xulrunner apps."
396 :type 'boolean
397 :group 'js2-mode)
398
399 (defcustom js2-cleanup-whitespace nil
400 "Non-nil to invoke `delete-trailing-whitespace' before saves."
401 :type 'boolean
402 :group 'js2-mode)
403
404 (defcustom js2-move-point-on-right-click t
405 "Non-nil to move insertion point when you right-click.
406 This makes right-click context menu behavior a bit more intuitive,
407 since menu operations generally apply to the point. The exception
408 is if there is a region selection, in which case the point does -not-
409 move, so cut/copy/paste etc. can work properly.
410
411 Note that IntelliJ moves the point, and Eclipse leaves it alone,
412 so this behavior is customizable."
413 :group 'js2-mode
414 :type 'boolean)
415
416 (defcustom js2-allow-rhino-new-expr-initializer t
417 "Non-nil to support a Rhino's experimental syntactic construct.
418
419 Rhino supports the ability to follow a `new' expression with an object
420 literal, which is used to set additional properties on the new object
421 after calling its constructor. Syntax:
422
423 new <expr> [ ( arglist ) ] [initializer]
424
425 Hence, this expression:
426
427 new Object {a: 1, b: 2}
428
429 results in an Object with properties a=1 and b=2. This syntax is
430 apparently not configurable in Rhino - it's currently always enabled,
431 as of Rhino version 1.7R2."
432 :type 'boolean
433 :group 'js2-mode)
434
435 (defcustom js2-allow-member-expr-as-function-name nil
436 "Non-nil to support experimental Rhino syntax for function names.
437
438 Rhino supports an experimental syntax configured via the Rhino Context
439 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
440
441 function <member-expr> ( [ arg-list ] ) { <body> }
442
443 Where member-expr is a non-parenthesized 'member expression', which
444 is anything at the grammar level of a new-expression or lower, meaning
445 any expression that does not involve infix or unary operators.
446
447 When <member-expr> is not a simple identifier, then it is syntactic
448 sugar for assigning the anonymous function to the <member-expr>. Hence,
449 this code:
450
451 function a.b().c[2] (x, y) { ... }
452
453 is rewritten as:
454
455 a.b().c[2] = function(x, y) {...}
456
457 which doesn't seem particularly useful, but Rhino permits it."
458 :type 'boolean
459 :group 'js2-mode)
460
461 (defvar js2-mode-version 20101228
462 "Release number for `js2-mode'.")
463
464 ;; scanner variables
465
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
468 `(progn
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
471
472 ;; We record the start and end position of each token.
473 (js2-deflocal js2-token-beg 1)
474 (js2-deflocal js2-token-end -1)
475
476 (defvar js2-EOF_CHAR -1
477 "Represents end of stream. Distinct from js2-EOF token type.")
478
479 ;; I originally used symbols to represent tokens, but Rhino uses
480 ;; ints and then sets various flag bits in them, so ints it is.
481 ;; The upshot is that we need a `js2-' prefix in front of each name.
482 (defvar js2-ERROR -1)
483 (defvar js2-EOF 0)
484 (defvar js2-EOL 1)
485 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
486 (defvar js2-LEAVEWITH 3)
487 (defvar js2-RETURN 4)
488 (defvar js2-GOTO 5)
489 (defvar js2-IFEQ 6)
490 (defvar js2-IFNE 7)
491 (defvar js2-SETNAME 8)
492 (defvar js2-BITOR 9)
493 (defvar js2-BITXOR 10)
494 (defvar js2-BITAND 11)
495 (defvar js2-EQ 12)
496 (defvar js2-NE 13)
497 (defvar js2-LT 14)
498 (defvar js2-LE 15)
499 (defvar js2-GT 16)
500 (defvar js2-GE 17)
501 (defvar js2-LSH 18)
502 (defvar js2-RSH 19)
503 (defvar js2-URSH 20)
504 (defvar js2-ADD 21) ; infix plus
505 (defvar js2-SUB 22) ; infix minus
506 (defvar js2-MUL 23)
507 (defvar js2-DIV 24)
508 (defvar js2-MOD 25)
509 (defvar js2-NOT 26)
510 (defvar js2-BITNOT 27)
511 (defvar js2-POS 28) ; unary plus
512 (defvar js2-NEG 29) ; unary minus
513 (defvar js2-NEW 30)
514 (defvar js2-DELPROP 31)
515 (defvar js2-TYPEOF 32)
516 (defvar js2-GETPROP 33)
517 (defvar js2-GETPROPNOWARN 34)
518 (defvar js2-SETPROP 35)
519 (defvar js2-GETELEM 36)
520 (defvar js2-SETELEM 37)
521 (defvar js2-CALL 38)
522 (defvar js2-NAME 39) ; an identifier
523 (defvar js2-NUMBER 40)
524 (defvar js2-STRING 41)
525 (defvar js2-NULL 42)
526 (defvar js2-THIS 43)
527 (defvar js2-FALSE 44)
528 (defvar js2-TRUE 45)
529 (defvar js2-SHEQ 46) ; shallow equality (===)
530 (defvar js2-SHNE 47) ; shallow inequality (!==)
531 (defvar js2-REGEXP 48)
532 (defvar js2-BINDNAME 49)
533 (defvar js2-THROW 50)
534 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
535 (defvar js2-IN 52)
536 (defvar js2-INSTANCEOF 53)
537 (defvar js2-LOCAL_LOAD 54)
538 (defvar js2-GETVAR 55)
539 (defvar js2-SETVAR 56)
540 (defvar js2-CATCH_SCOPE 57)
541 (defvar js2-ENUM_INIT_KEYS 58)
542 (defvar js2-ENUM_INIT_VALUES 59)
543 (defvar js2-ENUM_INIT_ARRAY 60)
544 (defvar js2-ENUM_NEXT 61)
545 (defvar js2-ENUM_ID 62)
546 (defvar js2-THISFN 63)
547 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
548 (defvar js2-ARRAYLIT 65) ; array literal
549 (defvar js2-OBJECTLIT 66) ; object literal
550 (defvar js2-GET_REF 67) ; *reference
551 (defvar js2-SET_REF 68) ; *reference = something
552 (defvar js2-DEL_REF 69) ; delete reference
553 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
554 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
555 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
556
557 ;; XML support
558 (defvar js2-DEFAULTNAMESPACE 73)
559 (defvar js2-ESCXMLATTR 74)
560 (defvar js2-ESCXMLTEXT 75)
561 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
562 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
563 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
564 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
565
566 (defvar js2-first-bytecode js2-ENTERWITH)
567 (defvar js2-last-bytecode js2-REF_NS_NAME)
568
569 (defvar js2-TRY 80)
570 (defvar js2-SEMI 81) ; semicolon
571 (defvar js2-LB 82) ; left and right brackets
572 (defvar js2-RB 83)
573 (defvar js2-LC 84) ; left and right curly-braces
574 (defvar js2-RC 85)
575 (defvar js2-LP 86) ; left and right parens
576 (defvar js2-RP 87)
577 (defvar js2-COMMA 88) ; comma operator
578
579 (defvar js2-ASSIGN 89) ; simple assignment (=)
580 (defvar js2-ASSIGN_BITOR 90) ; |=
581 (defvar js2-ASSIGN_BITXOR 91) ; ^=
582 (defvar js2-ASSIGN_BITAND 92) ; &=
583 (defvar js2-ASSIGN_LSH 93) ; <<=
584 (defvar js2-ASSIGN_RSH 94) ; >>=
585 (defvar js2-ASSIGN_URSH 95) ; >>>=
586 (defvar js2-ASSIGN_ADD 96) ; +=
587 (defvar js2-ASSIGN_SUB 97) ; -=
588 (defvar js2-ASSIGN_MUL 98) ; *=
589 (defvar js2-ASSIGN_DIV 99) ; /=
590 (defvar js2-ASSIGN_MOD 100) ; %=
591
592 (defvar js2-first-assign js2-ASSIGN)
593 (defvar js2-last-assign js2-ASSIGN_MOD)
594
595 (defvar js2-HOOK 101) ; conditional (?:)
596 (defvar js2-COLON 102)
597 (defvar js2-OR 103) ; logical or (||)
598 (defvar js2-AND 104) ; logical and (&&)
599 (defvar js2-INC 105) ; increment/decrement (++ --)
600 (defvar js2-DEC 106)
601 (defvar js2-DOT 107) ; member operator (.)
602 (defvar js2-FUNCTION 108) ; function keyword
603 (defvar js2-EXPORT 109) ; export keyword
604 (defvar js2-IMPORT 110) ; import keyword
605 (defvar js2-IF 111) ; if keyword
606 (defvar js2-ELSE 112) ; else keyword
607 (defvar js2-SWITCH 113) ; switch keyword
608 (defvar js2-CASE 114) ; case keyword
609 (defvar js2-DEFAULT 115) ; default keyword
610 (defvar js2-WHILE 116) ; while keyword
611 (defvar js2-DO 117) ; do keyword
612 (defvar js2-FOR 118) ; for keyword
613 (defvar js2-BREAK 119) ; break keyword
614 (defvar js2-CONTINUE 120) ; continue keyword
615 (defvar js2-VAR 121) ; var keyword
616 (defvar js2-WITH 122) ; with keyword
617 (defvar js2-CATCH 123) ; catch keyword
618 (defvar js2-FINALLY 124) ; finally keyword
619 (defvar js2-VOID 125) ; void keyword
620 (defvar js2-RESERVED 126) ; reserved keywords
621
622 (defvar js2-EMPTY 127)
623
624 ;; Types used for the parse tree - never returned by scanner.
625
626 (defvar js2-BLOCK 128) ; statement block
627 (defvar js2-LABEL 129) ; label
628 (defvar js2-TARGET 130)
629 (defvar js2-LOOP 131)
630 (defvar js2-EXPR_VOID 132) ; expression statement in functions
631 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
632 (defvar js2-JSR 134)
633 (defvar js2-SCRIPT 135) ; top-level node for entire script
634 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
635 (defvar js2-USE_STACK 137)
636 (defvar js2-SETPROP_OP 138) ; x.y op= something
637 (defvar js2-SETELEM_OP 139) ; x[y] op= something
638 (defvar js2-LOCAL_BLOCK 140)
639 (defvar js2-SET_REF_OP 141) ; *reference op= something
640
641 ;; For XML support:
642 (defvar js2-DOTDOT 142) ; member operator (..)
643 (defvar js2-COLONCOLON 143) ; namespace::name
644 (defvar js2-XML 144) ; XML type
645 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
646 (defvar js2-XMLATTR 146) ; @
647 (defvar js2-XMLEND 147)
648
649 ;; Optimizer-only tokens
650 (defvar js2-TO_OBJECT 148)
651 (defvar js2-TO_DOUBLE 149)
652
653 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
654 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
655 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
656 (defvar js2-CONST 153)
657 (defvar js2-SETCONST 154)
658 (defvar js2-SETCONSTVAR 155)
659 (defvar js2-ARRAYCOMP 156)
660 (defvar js2-LETEXPR 157)
661 (defvar js2-WITHEXPR 158)
662 (defvar js2-DEBUGGER 159)
663
664 (defvar js2-COMMENT 160)
665 (defvar js2-ENUM 161) ; for "enum" reserved word
666
667 (defconst js2-num-tokens (1+ js2-ENUM))
668
669 (defconst js2-debug-print-trees nil)
670
671 ;; Rhino accepts any string or stream as input. Emacs character
672 ;; processing works best in buffers, so we'll assume the input is a
673 ;; buffer. JavaScript strings can be copied into temp buffers before
674 ;; scanning them.
675
676 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
677 ;; They're the Emacs equivalent of instance variables, more or less.
678
679 (js2-deflocal js2-ts-dirty-line nil
680 "Token stream buffer-local variable.
681 Indicates stuff other than whitespace since start of line.")
682
683 (js2-deflocal js2-ts-regexp-flags nil
684 "Token stream buffer-local variable.")
685
686 (js2-deflocal js2-ts-string ""
687 "Token stream buffer-local variable.
688 Last string scanned.")
689
690 (js2-deflocal js2-ts-number nil
691 "Token stream buffer-local variable.
692 Last literal number scanned.")
693
694 (js2-deflocal js2-ts-hit-eof nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-line-start 0
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-lineno 1
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-line-end-char -1
704 "Token stream buffer-local variable.")
705
706 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
707 "Token stream buffer-local variable.
708 Current scan position.")
709
710 (js2-deflocal js2-ts-is-xml-attribute nil
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-xml-is-tag-content nil
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-xml-open-tags-count 0
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-string-buffer nil
720 "Token stream buffer-local variable.
721 List of chars built up while scanning various tokens.")
722
723 (js2-deflocal js2-ts-comment-type nil
724 "Token stream buffer-local variable.")
725
726 ;;; Parser variables
727
728 (js2-deflocal js2-parsed-errors nil
729 "List of errors produced during scanning/parsing.")
730
731 (js2-deflocal js2-parsed-warnings nil
732 "List of warnings produced during scanning/parsing.")
733
734 (js2-deflocal js2-recover-from-parse-errors t
735 "Non-nil to continue parsing after a syntax error.
736
737 In recovery mode, the AST will be built in full, and any error
738 nodes will be flagged with appropriate error information. If
739 this flag is nil, a syntax error will result in an error being
740 signaled.
741
742 The variable is automatically buffer-local, because different
743 modes that use the parser will need different settings.")
744
745 (js2-deflocal js2-parse-hook nil
746 "List of callbacks for receiving parsing progress.")
747
748 (defvar js2-parse-finished-hook nil
749 "List of callbacks to notify when parsing finishes.
750 Not called if parsing was interrupted.")
751
752 (js2-deflocal js2-is-eval-code nil
753 "True if we're evaluating code in a string.
754 If non-nil, the tokenizer will record the token text, and the AST nodes
755 will record their source text. Off by default for IDE modes, since the
756 text is available in the buffer.")
757
758 (defvar js2-parse-ide-mode t
759 "Non-nil if the parser is being used for `js2-mode'.
760 If non-nil, the parser will set text properties for fontification
761 and the syntax table. The value should be nil when using the
762 parser as a frontend to an interpreter or byte compiler.")
763
764 ;;; Parser instance variables (buffer-local vars for js2-parse)
765
766 (defconst js2-clear-ti-mask #xFFFF
767 "Mask to clear token information bits.")
768
769 (defconst js2-ti-after-eol (lsh 1 16)
770 "Flag: first token of the source line.")
771
772 (defconst js2-ti-check-label (lsh 1 17)
773 "Flag: indicates to check for label.")
774
775 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
776
777 (js2-deflocal js2-compiler-generate-debug-info t)
778 (js2-deflocal js2-compiler-use-dynamic-scope nil)
779 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
780 (js2-deflocal js2-compiler-xml-available t)
781 (js2-deflocal js2-compiler-optimization-level 0)
782 (js2-deflocal js2-compiler-generating-source t)
783 (js2-deflocal js2-compiler-strict-mode nil)
784 (js2-deflocal js2-compiler-report-warning-as-error nil)
785 (js2-deflocal js2-compiler-generate-observer-count nil)
786 (js2-deflocal js2-compiler-activation-names nil)
787
788 ;; SKIP: sourceURI
789
790 ;; There's a compileFunction method in Context.java - may need it.
791 (js2-deflocal js2-called-by-compile-function nil
792 "True if `js2-parse' was called by `js2-compile-function'.
793 Will only be used when we finish implementing the interpreter.")
794
795 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
796
797 (js2-deflocal js2-current-flagged-token js2-EOF)
798 (js2-deflocal js2-current-token js2-EOF)
799
800 ;; SKIP: node factory - we're going to just call functions directly,
801 ;; and eventually go to a unified AST format.
802
803 (js2-deflocal js2-nesting-of-function 0)
804
805 (js2-deflocal js2-recorded-identifiers nil
806 "Tracks identifiers found during parsing.")
807
808 (defmacro js2-in-lhs (body)
809 `(let ((js2-is-in-lhs t))
810 ,body))
811
812 (defmacro js2-in-rhs (body)
813 `(let ((js2-is-in-lhs nil))
814 ,body))
815
816 (js2-deflocal js2-is-in-lhs nil
817 "True while parsing lhs statement")
818
819 (defcustom js2-global-externs nil
820 "A list of any extern names you'd like to consider always declared.
821 This list is global and is used by all js2-mode files.
822 You can create buffer-local externs list using `js2-additional-externs'.
823
824 There is also a buffer-local variable `js2-default-externs',
825 which is initialized by default to include the Ecma-262 externs
826 and the standard browser externs. The three lists are all
827 checked during highlighting."
828 :type 'list
829 :group 'js2-mode)
830
831 (js2-deflocal js2-default-externs nil
832 "Default external declarations.
833
834 These are currently only used for highlighting undeclared variables,
835 which only worries about top-level (unqualified) references.
836 As js2-mode's processing improves, we will flesh out this list.
837
838 The initial value is set to `js2-ecma-262-externs', unless you
839 have set `js2-include-browser-externs', in which case the browser
840 externs are also included.
841
842 See `js2-additional-externs' for more information.")
843
844 (defcustom js2-include-browser-externs t
845 "Non-nil to include browser externs in the master externs list.
846 If you work on JavaScript files that are not intended for browsers,
847 such as Mozilla Rhino server-side JavaScript, set this to nil.
848 You can always include them on a per-file basis by calling
849 `js2-add-browser-externs' from a function on `js2-mode-hook'.
850
851 See `js2-additional-externs' for more information about externs."
852 :type 'boolean
853 :group 'js2-mode)
854
855 (defcustom js2-include-rhino-externs t
856 "Non-nil to include Mozilla Rhino externs in the master externs list.
857 See `js2-additional-externs' for more information about externs."
858 :type 'boolean
859 :group 'js2-mode)
860
861 (defcustom js2-include-gears-externs t
862 "Non-nil to include Google Gears externs in the master externs list.
863 See `js2-additional-externs' for more information about externs."
864 :type 'boolean
865 :group 'js2-mode)
866
867 (js2-deflocal js2-additional-externs nil
868 "A buffer-local list of additional external declarations.
869 It is used to decide whether variables are considered undeclared
870 for purposes of highlighting.
871
872 Each entry is a lisp string. The string should be the fully qualified
873 name of an external entity. All externs should be added to this list,
874 so that as js2-mode's processing improves it can take advantage of them.
875
876 You may want to declare your externs in three ways.
877 First, you can add externs that are valid for all your JavaScript files.
878 You should probably do this by adding them to `js2-global-externs', which
879 is a global list used for all js2-mode files.
880
881 Next, you can add a function to `js2-mode-hook' that adds additional
882 externs appropriate for the specific file, perhaps based on its path.
883 These should go in `js2-additional-externs', which is buffer-local.
884
885 Finally, you can add a function to `js2-post-parse-callbacks',
886 which is called after parsing completes, and `root' is bound to
887 the root of the parse tree. At this stage you can set up an AST
888 node visitor using `js2-visit-ast' and examine the parse tree
889 for specific import patterns that may imply the existence of
890 other externs, possibly tied to your build system. These should also
891 be added to `js2-additional-externs'.
892
893 Your post-parse callback may of course also use the simpler and
894 faster (but perhaps less robust) approach of simply scanning the
895 buffer text for your imports, using regular expressions.")
896
897 ;; SKIP: decompiler
898 ;; SKIP: encoded-source
899
900 ;;; The following variables are per-function and should be saved/restored
901 ;;; during function parsing...
902
903 (js2-deflocal js2-current-script-or-fn nil)
904 (js2-deflocal js2-current-scope nil)
905 (js2-deflocal js2-nesting-of-with 0)
906 (js2-deflocal js2-label-set nil
907 "An alist mapping label names to nodes.")
908
909 (js2-deflocal js2-loop-set nil)
910 (js2-deflocal js2-loop-and-switch-set nil)
911 (js2-deflocal js2-has-return-value nil)
912 (js2-deflocal js2-end-flags 0)
913
914 ;;; ...end of per function variables
915
916 ;; Without 2-token lookahead, labels are a problem.
917 ;; These vars store the token info of the last matched name,
918 ;; iff it wasn't the last matched token. Only valid in some contexts.
919 (defvar js2-prev-name-token-start nil)
920 (defvar js2-prev-name-token-string nil)
921
922 (defsubst js2-save-name-token-data (pos name)
923 (setq js2-prev-name-token-start pos
924 js2-prev-name-token-string name))
925
926 ;; These flags enumerate the possible ways a statement/function can
927 ;; terminate. These flags are used by endCheck() and by the Parser to
928 ;; detect inconsistent return usage.
929 ;;
930 ;; END_UNREACHED is reserved for code paths that are assumed to always be
931 ;; able to execute (example: throw, continue)
932 ;;
933 ;; END_DROPS_OFF indicates if the statement can transfer control to the
934 ;; next one. Statement such as return dont. A compound statement may have
935 ;; some branch that drops off control to the next statement.
936 ;;
937 ;; END_RETURNS indicates that the statement can return (without arguments)
938 ;; END_RETURNS_VALUE indicates that the statement can return a value.
939 ;;
940 ;; A compound statement such as
941 ;; if (condition) {
942 ;; return value;
943 ;; }
944 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
945
946 (defconst js2-end-unreached #x0)
947 (defconst js2-end-drops-off #x1)
948 (defconst js2-end-returns #x2)
949 (defconst js2-end-returns-value #x4)
950 (defconst js2-end-yields #x8)
951
952 ;; Rhino awkwardly passes a statementLabel parameter to the
953 ;; statementHelper() function, the main statement parser, which
954 ;; is then used by quite a few of the sub-parsers. We just make
955 ;; it a buffer-local variable and make sure it's cleaned up properly.
956 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
957
958 ;; Similarly, Rhino passes an inForInit boolean through about half
959 ;; the expression parsers. We use a dynamically-scoped variable,
960 ;; which makes it easier to funcall the parsers individually without
961 ;; worrying about whether they take the parameter or not.
962 (js2-deflocal js2-in-for-init nil)
963 (js2-deflocal js2-temp-name-counter 0)
964 (js2-deflocal js2-parse-stmt-count 0)
965
966 (defsubst js2-get-next-temp-name ()
967 (format "$%d" (incf js2-temp-name-counter)))
968
969 (defvar js2-parse-interruptable-p t
970 "Set this to nil to force parse to continue until finished.
971 This will mostly be useful for interpreters.")
972
973 (defvar js2-statements-per-pause 50
974 "Pause after this many statements to check for user input.
975 If user input is pending, stop the parse and discard the tree.
976 This makes for a smoother user experience for large files.
977 You may have to wait a second or two before the highlighting
978 and error-reporting appear, but you can always type ahead if
979 you wish. This appears to be more or less how Eclipse, IntelliJ
980 and other editors work.")
981
982 (js2-deflocal js2-record-comments t
983 "Instructs the scanner to record comments in `js2-scanned-comments'.")
984
985 (js2-deflocal js2-scanned-comments nil
986 "List of all comments from the current parse.")
987
988 (defcustom js2-mode-indent-inhibit-undo nil
989 "Non-nil to disable collection of Undo information when indenting lines.
990 Some users have requested this behavior. It's nil by default because
991 other Emacs modes don't work this way."
992 :type 'boolean
993 :group 'js2-mode)
994
995 (defcustom js2-mode-indent-ignore-first-tab nil
996 "If non-nil, ignore first TAB keypress if we look indented properly.
997 It's fairly common for users to navigate to an already-indented line
998 and press TAB for reassurance that it's been indented. For this class
999 of users, we want the first TAB press on a line to be ignored if the
1000 line is already indented to one of the precomputed alternatives.
1001
1002 This behavior is only partly implemented. If you TAB-indent a line,
1003 navigate to another line, and then navigate back, it fails to clear
1004 the last-indented variable, so it thinks you've already hit TAB once,
1005 and performs the indent. A full solution would involve getting on the
1006 point-motion hooks for the entire buffer. If we come across another
1007 use cases that requires watching point motion, I'll consider doing it.
1008
1009 If you set this variable to nil, then the TAB key will always change
1010 the indentation of the current line, if more than one alternative
1011 indentation spot exists."
1012 :type 'boolean
1013 :group 'js2-mode)
1014
1015 (defvar js2-indent-hook nil
1016 "A hook for user-defined indentation rules.
1017
1018 Functions on this hook should expect two arguments: (LIST INDEX)
1019 The LIST argument is the list of computed indentation points for
1020 the current line. INDEX is the list index of the indentation point
1021 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1022 indent function is not going to change the current line indentation.
1023
1024 If a hook function on this list returns a non-nil value, then
1025 `js2-bounce-indent' assumes the hook function has performed its own
1026 indentation, and will do nothing. If all hook functions on the list
1027 return nil, then `js2-bounce-indent' will use its computed indentation
1028 and reindent the line.
1029
1030 When hook functions on this hook list are called, the variable
1031 `js2-mode-ast' may or may not be set, depending on whether the
1032 parse tree is available. If the variable is nil, you can pass a
1033 callback to `js2-mode-wait-for-parse', and your callback will be
1034 called after the new parse tree is built. This can take some time
1035 in large files.")
1036
1037 (defface js2-warning-face
1038 `((((class color) (background light))
1039 (:underline "orange"))
1040 (((class color) (background dark))
1041 (:underline "orange"))
1042 (t (:underline t)))
1043 "Face for JavaScript warnings."
1044 :group 'js2-mode)
1045
1046 (defface js2-error-face
1047 `((((class color) (background light))
1048 (:foreground "red"))
1049 (((class color) (background dark))
1050 (:foreground "red"))
1051 (t (:foreground "red")))
1052 "Face for JavaScript errors."
1053 :group 'js2-mode)
1054
1055 (defface js2-jsdoc-tag-face
1056 '((t :foreground "SlateGray"))
1057 "Face used to highlight @whatever tags in jsdoc comments."
1058 :group 'js2-mode)
1059
1060 (defface js2-jsdoc-type-face
1061 '((t :foreground "SteelBlue"))
1062 "Face used to highlight {FooBar} types in jsdoc comments."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-value-face
1066 '((t :foreground "PeachPuff3"))
1067 "Face used to highlight tag values in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-function-param-face
1071 '((t :foreground "SeaGreen"))
1072 "Face used to highlight function parameters in javascript."
1073 :group 'js2-mode)
1074
1075 (defface js2-instance-member-face
1076 '((t :foreground "DarkOrchid"))
1077 "Face used to highlight instance variables in javascript.
1078 Not currently used."
1079 :group 'js2-mode)
1080
1081 (defface js2-private-member-face
1082 '((t :foreground "PeachPuff3"))
1083 "Face used to highlight calls to private methods in javascript.
1084 Not currently used."
1085 :group 'js2-mode)
1086
1087 (defface js2-private-function-call-face
1088 '((t :foreground "goldenrod"))
1089 "Face used to highlight calls to private functions in javascript.
1090 Not currently used."
1091 :group 'js2-mode)
1092
1093 (defface js2-jsdoc-html-tag-name-face
1094 (if js2-emacs22
1095 '((((class color) (min-colors 88) (background light))
1096 (:foreground "rosybrown"))
1097 (((class color) (min-colors 8) (background dark))
1098 (:foreground "yellow"))
1099 (((class color) (min-colors 8) (background light))
1100 (:foreground "magenta")))
1101 '((((type tty pc) (class color) (background light))
1102 (:foreground "magenta"))
1103 (((type tty pc) (class color) (background dark))
1104 (:foreground "yellow"))
1105 (t (:foreground "RosyBrown"))))
1106 "Face used to highlight jsdoc html tag names"
1107 :group 'js2-mode)
1108
1109 (defface js2-jsdoc-html-tag-delimiter-face
1110 (if js2-emacs22
1111 '((((class color) (min-colors 88) (background light))
1112 (:foreground "dark khaki"))
1113 (((class color) (min-colors 8) (background dark))
1114 (:foreground "green"))
1115 (((class color) (min-colors 8) (background light))
1116 (:foreground "green")))
1117 '((((type tty pc) (class color) (background light))
1118 (:foreground "green"))
1119 (((type tty pc) (class color) (background dark))
1120 (:foreground "green"))
1121 (t (:foreground "dark khaki"))))
1122 "Face used to highlight brackets in jsdoc html tags."
1123 :group 'js2-mode)
1124
1125 (defface js2-magic-paren-face
1126 '((t :underline t))
1127 "Face used to color parens that will be auto-overwritten."
1128 :group 'js2-mode)
1129
1130 (defcustom js2-post-parse-callbacks nil
1131 "A list of callback functions invoked after parsing finishes.
1132 Currently, the main use for this function is to add synthetic
1133 declarations to `js2-recorded-identifiers', which see."
1134 :type 'list
1135 :group 'js2-mode)
1136
1137 (defface js2-external-variable-face
1138 '((t :foreground "orange"))
1139 "Face used to highlight undeclared variable identifiers.
1140 An undeclared variable is any variable not declared with var or let
1141 in the current scope or any lexically enclosing scope. If you use
1142 such a variable, then you are either expecting it to originate from
1143 another file, or you've got a potential bug."
1144 :group 'js2-mode)
1145
1146 (defcustom js2-highlight-external-variables t
1147 "Non-nil to highlight undeclared variable identifiers."
1148 :type 'boolean
1149 :group 'js2-mode)
1150
1151 (defcustom js2-auto-insert-catch-block t
1152 "Non-nil to insert matching catch block on open-curly after `try'."
1153 :type 'boolean
1154 :group 'js2-mode)
1155
1156 (defvar js2-mode-map
1157 (let ((map (make-sparse-keymap))
1158 keys)
1159 (define-key map [mouse-1] #'js2-mode-show-node)
1160 (define-key map (kbd "C-m") #'js2-enter-key)
1161 (when js2-rebind-eol-bol-keys
1162 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1163 (define-key map (kbd "C-e") #'js2-end-of-line))
1164 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1165 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1166 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1167 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1168 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1169 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1170 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1171 (define-key map (kbd "C-c C-`") #'js2-next-error)
1172 ;; also define user's preference for next-error, if available
1173 (if (setq keys (where-is-internal #'next-error))
1174 (define-key map (car keys) #'js2-next-error))
1175 (define-key map (or (car (where-is-internal #'mark-defun))
1176 (kbd "M-C-h"))
1177 #'js2-mark-defun)
1178 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1179 (kbd "C-x nd"))
1180 #'js2-narrow-to-defun)
1181 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1182 (when js2-auto-indent-p
1183 (mapc (lambda (key)
1184 (define-key map key #'js2-insert-and-indent))
1185 js2-electric-keys))
1186 (when js2-bounce-indent-p
1187 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1188
1189 (define-key map [menu-bar javascript]
1190 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1191
1192 (define-key map [menu-bar javascript customize-js2-mode]
1193 '(menu-item "Customize js2-mode" js2-mode-customize
1194 :help "Customize the behavior of this mode"))
1195
1196 (define-key map [menu-bar javascript js2-force-refresh]
1197 '(menu-item "Force buffer refresh" js2-mode-reset
1198 :help "Re-parse the buffer from scratch"))
1199
1200 (define-key map [menu-bar javascript separator-2]
1201 '("--"))
1202
1203 (define-key map [menu-bar javascript next-error]
1204 '(menu-item "Next warning or error" js2-next-error
1205 :enabled (and js2-mode-ast
1206 (or (js2-ast-root-errors js2-mode-ast)
1207 (js2-ast-root-warnings js2-mode-ast)))
1208 :help "Move to next warning or error"))
1209
1210 (define-key map [menu-bar javascript display-errors]
1211 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1212 :visible (not js2-mode-show-parse-errors)
1213 :help "Turn on display of warnings and errors"))
1214
1215 (define-key map [menu-bar javascript hide-errors]
1216 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1217 :visible js2-mode-show-parse-errors
1218 :help "Turn off display of warnings and errors"))
1219
1220 (define-key map [menu-bar javascript separator-1]
1221 '("--"))
1222
1223 (define-key map [menu-bar javascript js2-toggle-function]
1224 '(menu-item "Show/collapse element" js2-mode-toggle-element
1225 :help "Hide or show function body or comment"))
1226
1227 (define-key map [menu-bar javascript show-comments]
1228 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1229 :visible js2-mode-comments-hidden
1230 :help "Expand all hidden block comments"))
1231
1232 (define-key map [menu-bar javascript hide-comments]
1233 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1234 :visible (not js2-mode-comments-hidden)
1235 :help "Show block comments as /*...*/"))
1236
1237 (define-key map [menu-bar javascript show-all-functions]
1238 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1239 :visible js2-mode-functions-hidden
1240 :help "Expand all hidden function bodies"))
1241
1242 (define-key map [menu-bar javascript hide-all-functions]
1243 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1244 :visible (not js2-mode-functions-hidden)
1245 :help "Show {...} for all top-level function bodies"))
1246
1247 map)
1248 "Keymap used in `js2-mode' buffers.")
1249
1250 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1251
1252 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1253 "Matches a //-comment line. Must be first non-whitespace on line.
1254 First match-group is the leading whitespace.")
1255
1256 (defvar js2-mode-hook nil)
1257
1258 (js2-deflocal js2-mode-ast nil "Private variable.")
1259 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1260 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1261 (js2-deflocal js2-mode-parsing nil "Private variable.")
1262 (js2-deflocal js2-mode-node-overlay nil)
1263
1264 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1265 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1266
1267 (js2-deflocal js2-mode-fontifications nil "Private variable")
1268 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1269 (js2-deflocal js2-imenu-recorder nil "Private variable")
1270 (js2-deflocal js2-imenu-function-map nil "Private variable")
1271
1272 (defvar js2-paragraph-start
1273 "\\(@[a-zA-Z]+\\>\\|$\\)")
1274
1275 ;; Note that we also set a 'c-in-sws text property in html comments,
1276 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1277 (defvar js2-syntactic-ws-start
1278 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1279
1280 (defvar js2-syntactic-ws-end
1281 "\\s \\|[\n\r/]\\|\\s!")
1282
1283 (defvar js2-syntactic-eol
1284 (concat "\\s *\\(/\\*[^*\n\r]*"
1285 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1286 "\\*+/\\s *\\)*"
1287 "\\(//\\|/\\*[^*\n\r]*"
1288 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1289 "\\|\\\\$\\|$\\)")
1290 "Copied from `java-mode'. Needed for some cc-engine functions.")
1291
1292 (defvar js2-comment-prefix-regexp
1293 "//+\\|\\**")
1294
1295 (defvar js2-comment-start-skip
1296 "\\(//+\\|/\\*+\\)\\s *")
1297
1298 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1299 "Non-nil to emit status messages during parsing.")
1300
1301 (defvar js2-mode-functions-hidden nil "private variable")
1302 (defvar js2-mode-comments-hidden nil "private variable")
1303
1304 (defvar js2-mode-syntax-table
1305 (let ((table (make-syntax-table)))
1306 (c-populate-syntax-table table)
1307 table)
1308 "Syntax table used in js2-mode buffers.")
1309
1310 (defvar js2-mode-abbrev-table nil
1311 "Abbrev table in use in `js2-mode' buffers.")
1312 (define-abbrev-table 'js2-mode-abbrev-table ())
1313
1314 (defvar js2-mode-pending-parse-callbacks nil
1315 "List of functions waiting to be notified that parse is finished.")
1316
1317 (defvar js2-mode-last-indented-line -1)
1318
1319 ;;; Localizable error and warning messages
1320
1321 ;; Messages are copied from Rhino's Messages.properties.
1322 ;; Many of the Java-specific messages have been elided.
1323 ;; Add any js2-specific ones at the end, so we can keep
1324 ;; this file synced with changes to Rhino's.
1325
1326 (defvar js2-message-table
1327 (make-hash-table :test 'equal :size 250)
1328 "Contains localized messages for js2-mode.")
1329
1330 ;; TODO(stevey): construct this table at compile-time.
1331 (defmacro js2-msg (key &rest strings)
1332 `(puthash ,key (funcall #'concat ,@strings)
1333 js2-message-table))
1334
1335 (defun js2-get-msg (msg-key)
1336 "Look up a localized message.
1337 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1338 the correct number of ARGS must be provided."
1339 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1340 (args (if (listp msg-key) (cdr msg-key)))
1341 (msg (gethash key js2-message-table)))
1342 (if msg
1343 (apply #'format msg args)
1344 key))) ; default to showing the key
1345
1346 (js2-msg "msg.dup.parms"
1347 "Duplicate parameter name '%s'.")
1348
1349 (js2-msg "msg.too.big.jump"
1350 "Program too complex: jump offset too big.")
1351
1352 (js2-msg "msg.too.big.index"
1353 "Program too complex: internal index exceeds 64K limit.")
1354
1355 (js2-msg "msg.while.compiling.fn"
1356 "Encountered code generation error while compiling function '%s': %s")
1357
1358 (js2-msg "msg.while.compiling.script"
1359 "Encountered code generation error while compiling script: %s")
1360
1361 ;; Context
1362 (js2-msg "msg.ctor.not.found"
1363 "Constructor for '%s' not found.")
1364
1365 (js2-msg "msg.not.ctor"
1366 "'%s' is not a constructor.")
1367
1368 ;; FunctionObject
1369 (js2-msg "msg.varargs.ctor"
1370 "Method or constructor '%s' must be static "
1371 "with the signature (Context cx, Object[] args, "
1372 "Function ctorObj, boolean inNewExpr) "
1373 "to define a variable arguments constructor.")
1374
1375 (js2-msg "msg.varargs.fun"
1376 "Method '%s' must be static with the signature "
1377 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1378 "to define a variable arguments function.")
1379
1380 (js2-msg "msg.incompat.call"
1381 "Method '%s' called on incompatible object.")
1382
1383 (js2-msg "msg.bad.parms"
1384 "Unsupported parameter type '%s' in method '%s'.")
1385
1386 (js2-msg "msg.bad.method.return"
1387 "Unsupported return type '%s' in method '%s'.")
1388
1389 (js2-msg "msg.bad.ctor.return"
1390 "Construction of objects of type '%s' is not supported.")
1391
1392 (js2-msg "msg.no.overload"
1393 "Method '%s' occurs multiple times in class '%s'.")
1394
1395 (js2-msg "msg.method.not.found"
1396 "Method '%s' not found in '%s'.")
1397
1398 ;; IRFactory
1399
1400 (js2-msg "msg.bad.for.in.lhs"
1401 "Invalid left-hand side of for..in loop.")
1402
1403 (js2-msg "msg.mult.index"
1404 "Only one variable allowed in for..in loop.")
1405
1406 (js2-msg "msg.bad.for.in.destruct"
1407 "Left hand side of for..in loop must be an array of "
1408 "length 2 to accept key/value pair.")
1409
1410 (js2-msg "msg.cant.convert"
1411 "Can't convert to type '%s'.")
1412
1413 (js2-msg "msg.bad.assign.left"
1414 "Invalid assignment left-hand side.")
1415
1416 (js2-msg "msg.bad.decr"
1417 "Invalid decerement operand.")
1418
1419 (js2-msg "msg.bad.incr"
1420 "Invalid increment operand.")
1421
1422 (js2-msg "msg.bad.yield"
1423 "yield must be in a function.")
1424
1425 (js2-msg "msg.yield.parenthesized"
1426 "yield expression must be parenthesized.")
1427
1428 ;; NativeGlobal
1429 (js2-msg "msg.cant.call.indirect"
1430 "Function '%s' must be called directly, and not by way of a "
1431 "function of another name.")
1432
1433 (js2-msg "msg.eval.nonstring"
1434 "Calling eval() with anything other than a primitive "
1435 "string value will simply return the value. "
1436 "Is this what you intended?")
1437
1438 (js2-msg "msg.eval.nonstring.strict"
1439 "Calling eval() with anything other than a primitive "
1440 "string value is not allowed in strict mode.")
1441
1442 (js2-msg "msg.bad.destruct.op"
1443 "Invalid destructuring assignment operator")
1444
1445 ;; NativeCall
1446 (js2-msg "msg.only.from.new"
1447 "'%s' may only be invoked from a `new' expression.")
1448
1449 (js2-msg "msg.deprec.ctor"
1450 "The '%s' constructor is deprecated.")
1451
1452 ;; NativeFunction
1453 (js2-msg "msg.no.function.ref.found"
1454 "no source found to decompile function reference %s")
1455
1456 (js2-msg "msg.arg.isnt.array"
1457 "second argument to Function.prototype.apply must be an array")
1458
1459 ;; NativeGlobal
1460 (js2-msg "msg.bad.esc.mask"
1461 "invalid string escape mask")
1462
1463 ;; NativeRegExp
1464 (js2-msg "msg.bad.quant"
1465 "Invalid quantifier %s")
1466
1467 (js2-msg "msg.overlarge.backref"
1468 "Overly large back reference %s")
1469
1470 (js2-msg "msg.overlarge.min"
1471 "Overly large minimum %s")
1472
1473 (js2-msg "msg.overlarge.max"
1474 "Overly large maximum %s")
1475
1476 (js2-msg "msg.zero.quant"
1477 "Zero quantifier %s")
1478
1479 (js2-msg "msg.max.lt.min"
1480 "Maximum %s less than minimum")
1481
1482 (js2-msg "msg.unterm.quant"
1483 "Unterminated quantifier %s")
1484
1485 (js2-msg "msg.unterm.paren"
1486 "Unterminated parenthetical %s")
1487
1488 (js2-msg "msg.unterm.class"
1489 "Unterminated character class %s")
1490
1491 (js2-msg "msg.bad.range"
1492 "Invalid range in character class.")
1493
1494 (js2-msg "msg.trail.backslash"
1495 "Trailing \\ in regular expression.")
1496
1497 (js2-msg "msg.re.unmatched.right.paren"
1498 "unmatched ) in regular expression.")
1499
1500 (js2-msg "msg.no.regexp"
1501 "Regular expressions are not available.")
1502
1503 (js2-msg "msg.bad.backref"
1504 "back-reference exceeds number of capturing parentheses.")
1505
1506 (js2-msg "msg.bad.regexp.compile"
1507 "Only one argument may be specified if the first "
1508 "argument to RegExp.prototype.compile is a RegExp object.")
1509
1510 ;; Parser
1511 (js2-msg "msg.got.syntax.errors"
1512 "Compilation produced %s syntax errors.")
1513
1514 (js2-msg "msg.var.redecl"
1515 "TypeError: redeclaration of var %s.")
1516
1517 (js2-msg "msg.const.redecl"
1518 "TypeError: redeclaration of const %s.")
1519
1520 (js2-msg "msg.let.redecl"
1521 "TypeError: redeclaration of variable %s.")
1522
1523 (js2-msg "msg.parm.redecl"
1524 "TypeError: redeclaration of formal parameter %s.")
1525
1526 (js2-msg "msg.fn.redecl"
1527 "TypeError: redeclaration of function %s.")
1528
1529 (js2-msg "msg.let.decl.not.in.block"
1530 "SyntaxError: let declaration not directly within block")
1531
1532 ;; NodeTransformer
1533 (js2-msg "msg.dup.label"
1534 "duplicated label")
1535
1536 (js2-msg "msg.undef.label"
1537 "undefined label")
1538
1539 (js2-msg "msg.bad.break"
1540 "unlabelled break must be inside loop or switch")
1541
1542 (js2-msg "msg.continue.outside"
1543 "continue must be inside loop")
1544
1545 (js2-msg "msg.continue.nonloop"
1546 "continue can only use labels of iteration statements")
1547
1548 (js2-msg "msg.bad.throw.eol"
1549 "Line terminator is not allowed between the throw "
1550 "keyword and throw expression.")
1551
1552 (js2-msg "msg.no.paren.parms"
1553 "missing ( before function parameters.")
1554
1555 (js2-msg "msg.no.parm"
1556 "missing formal parameter")
1557
1558 (js2-msg "msg.no.paren.after.parms"
1559 "missing ) after formal parameters")
1560
1561 (js2-msg "msg.no.brace.body"
1562 "missing '{' before function body")
1563
1564 (js2-msg "msg.no.brace.after.body"
1565 "missing } after function body")
1566
1567 (js2-msg "msg.no.paren.cond"
1568 "missing ( before condition")
1569
1570 (js2-msg "msg.no.paren.after.cond"
1571 "missing ) after condition")
1572
1573 (js2-msg "msg.no.semi.stmt"
1574 "missing ; before statement")
1575
1576 (js2-msg "msg.missing.semi"
1577 "missing ; after statement")
1578
1579 (js2-msg "msg.no.name.after.dot"
1580 "missing name after . operator")
1581
1582 (js2-msg "msg.no.name.after.coloncolon"
1583 "missing name after :: operator")
1584
1585 (js2-msg "msg.no.name.after.dotdot"
1586 "missing name after .. operator")
1587
1588 (js2-msg "msg.no.name.after.xmlAttr"
1589 "missing name after .@")
1590
1591 (js2-msg "msg.no.bracket.index"
1592 "missing ] in index expression")
1593
1594 (js2-msg "msg.no.paren.switch"
1595 "missing ( before switch expression")
1596
1597 (js2-msg "msg.no.paren.after.switch"
1598 "missing ) after switch expression")
1599
1600 (js2-msg "msg.no.brace.switch"
1601 "missing '{' before switch body")
1602
1603 (js2-msg "msg.bad.switch"
1604 "invalid switch statement")
1605
1606 (js2-msg "msg.no.colon.case"
1607 "missing : after case expression")
1608
1609 (js2-msg "msg.double.switch.default"
1610 "double default label in the switch statement")
1611
1612 (js2-msg "msg.no.while.do"
1613 "missing while after do-loop body")
1614
1615 (js2-msg "msg.no.paren.for"
1616 "missing ( after for")
1617
1618 (js2-msg "msg.no.semi.for"
1619 "missing ; after for-loop initializer")
1620
1621 (js2-msg "msg.no.semi.for.cond"
1622 "missing ; after for-loop condition")
1623
1624 (js2-msg "msg.in.after.for.name"
1625 "missing in after for")
1626
1627 (js2-msg "msg.no.paren.for.ctrl"
1628 "missing ) after for-loop control")
1629
1630 (js2-msg "msg.no.paren.with"
1631 "missing ( before with-statement object")
1632
1633 (js2-msg "msg.no.paren.after.with"
1634 "missing ) after with-statement object")
1635
1636 (js2-msg "msg.no.paren.after.let"
1637 "missing ( after let")
1638
1639 (js2-msg "msg.no.paren.let"
1640 "missing ) after variable list")
1641
1642 (js2-msg "msg.no.curly.let"
1643 "missing } after let statement")
1644
1645 (js2-msg "msg.bad.return"
1646 "invalid return")
1647
1648 (js2-msg "msg.no.brace.block"
1649 "missing } in compound statement")
1650
1651 (js2-msg "msg.bad.label"
1652 "invalid label")
1653
1654 (js2-msg "msg.bad.var"
1655 "missing variable name")
1656
1657 (js2-msg "msg.bad.var.init"
1658 "invalid variable initialization")
1659
1660 (js2-msg "msg.no.colon.cond"
1661 "missing : in conditional expression")
1662
1663 (js2-msg "msg.no.paren.arg"
1664 "missing ) after argument list")
1665
1666 (js2-msg "msg.no.bracket.arg"
1667 "missing ] after element list")
1668
1669 (js2-msg "msg.bad.prop"
1670 "invalid property id")
1671
1672 (js2-msg "msg.no.colon.prop"
1673 "missing : after property id")
1674
1675 (js2-msg "msg.no.brace.prop"
1676 "missing } after property list")
1677
1678 (js2-msg "msg.no.paren"
1679 "missing ) in parenthetical")
1680
1681 (js2-msg "msg.reserved.id"
1682 "identifier is a reserved word")
1683
1684 (js2-msg "msg.no.paren.catch"
1685 "missing ( before catch-block condition")
1686
1687 (js2-msg "msg.bad.catchcond"
1688 "invalid catch block condition")
1689
1690 (js2-msg "msg.catch.unreachable"
1691 "any catch clauses following an unqualified catch are unreachable")
1692
1693 (js2-msg "msg.no.brace.try"
1694 "missing '{' before try block")
1695
1696 (js2-msg "msg.no.brace.catchblock"
1697 "missing '{' before catch-block body")
1698
1699 (js2-msg "msg.try.no.catchfinally"
1700 "'try' without 'catch' or 'finally'")
1701
1702 (js2-msg "msg.no.return.value"
1703 "function %s does not always return a value")
1704
1705 (js2-msg "msg.anon.no.return.value"
1706 "anonymous function does not always return a value")
1707
1708 (js2-msg "msg.return.inconsistent"
1709 "return statement is inconsistent with previous usage")
1710
1711 (js2-msg "msg.generator.returns"
1712 "TypeError: generator function '%s' returns a value")
1713
1714 (js2-msg "msg.anon.generator.returns"
1715 "TypeError: anonymous generator function returns a value")
1716
1717 (js2-msg "msg.syntax"
1718 "syntax error")
1719
1720 (js2-msg "msg.unexpected.eof"
1721 "Unexpected end of file")
1722
1723 (js2-msg "msg.XML.bad.form"
1724 "illegally formed XML syntax")
1725
1726 (js2-msg "msg.XML.not.available"
1727 "XML runtime not available")
1728
1729 (js2-msg "msg.too.deep.parser.recursion"
1730 "Too deep recursion while parsing")
1731
1732 (js2-msg "msg.no.side.effects"
1733 "Code has no side effects")
1734
1735 (js2-msg "msg.extra.trailing.comma"
1736 "Trailing comma is not legal in an ECMA-262 object initializer")
1737
1738 (js2-msg "msg.array.trailing.comma"
1739 "Trailing comma yields different behavior across browsers")
1740
1741 (js2-msg "msg.equal.as.assign"
1742 (concat "Test for equality (==) mistyped as assignment (=)?"
1743 " (parenthesize to suppress warning)"))
1744
1745 (js2-msg "msg.var.hides.arg"
1746 "Variable %s hides argument")
1747
1748 (js2-msg "msg.destruct.assign.no.init"
1749 "Missing = in destructuring declaration")
1750
1751 ;; ScriptRuntime
1752 (js2-msg "msg.no.properties"
1753 "%s has no properties.")
1754
1755 (js2-msg "msg.invalid.iterator"
1756 "Invalid iterator value")
1757
1758 (js2-msg "msg.iterator.primitive"
1759 "__iterator__ returned a primitive value")
1760
1761 (js2-msg "msg.assn.create.strict"
1762 "Assignment to undeclared variable %s")
1763
1764 (js2-msg "msg.ref.undefined.prop"
1765 "Reference to undefined property '%s'")
1766
1767 (js2-msg "msg.prop.not.found"
1768 "Property %s not found.")
1769
1770 (js2-msg "msg.invalid.type"
1771 "Invalid JavaScript value of type %s")
1772
1773 (js2-msg "msg.primitive.expected"
1774 "Primitive type expected (had %s instead)")
1775
1776 (js2-msg "msg.namespace.expected"
1777 "Namespace object expected to left of :: (found %s instead)")
1778
1779 (js2-msg "msg.null.to.object"
1780 "Cannot convert null to an object.")
1781
1782 (js2-msg "msg.undef.to.object"
1783 "Cannot convert undefined to an object.")
1784
1785 (js2-msg "msg.cyclic.value"
1786 "Cyclic %s value not allowed.")
1787
1788 (js2-msg "msg.is.not.defined"
1789 "'%s' is not defined.")
1790
1791 (js2-msg "msg.undef.prop.read"
1792 "Cannot read property '%s' from %s")
1793
1794 (js2-msg "msg.undef.prop.write"
1795 "Cannot set property '%s' of %s to '%s'")
1796
1797 (js2-msg "msg.undef.prop.delete"
1798 "Cannot delete property '%s' of %s")
1799
1800 (js2-msg "msg.undef.method.call"
1801 "Cannot call method '%s' of %s")
1802
1803 (js2-msg "msg.undef.with"
1804 "Cannot apply 'with' to %s")
1805
1806 (js2-msg "msg.isnt.function"
1807 "%s is not a function, it is %s.")
1808
1809 (js2-msg "msg.isnt.function.in"
1810 "Cannot call property %s in object %s. "
1811 "It is not a function, it is '%s'.")
1812
1813 (js2-msg "msg.function.not.found"
1814 "Cannot find function %s.")
1815
1816 (js2-msg "msg.function.not.found.in"
1817 "Cannot find function %s in object %s.")
1818
1819 (js2-msg "msg.isnt.xml.object"
1820 "%s is not an xml object.")
1821
1822 (js2-msg "msg.no.ref.to.get"
1823 "%s is not a reference to read reference value.")
1824
1825 (js2-msg "msg.no.ref.to.set"
1826 "%s is not a reference to set reference value to %s.")
1827
1828 (js2-msg "msg.no.ref.from.function"
1829 "Function %s can not be used as the left-hand "
1830 "side of assignment or as an operand of ++ or -- operator.")
1831
1832 (js2-msg "msg.bad.default.value"
1833 "Object's getDefaultValue() method returned an object.")
1834
1835 (js2-msg "msg.instanceof.not.object"
1836 "Can't use instanceof on a non-object.")
1837
1838 (js2-msg "msg.instanceof.bad.prototype"
1839 "'prototype' property of %s is not an object.")
1840
1841 (js2-msg "msg.bad.radix"
1842 "illegal radix %s.")
1843
1844 ;; ScriptableObject
1845 (js2-msg "msg.default.value"
1846 "Cannot find default value for object.")
1847
1848 (js2-msg "msg.zero.arg.ctor"
1849 "Cannot load class '%s' which has no zero-parameter constructor.")
1850
1851 (js2-msg "msg.ctor.multiple.parms"
1852 "Can't define constructor or class %s since more than "
1853 "one constructor has multiple parameters.")
1854
1855 (js2-msg "msg.extend.scriptable"
1856 "%s must extend ScriptableObject in order to define property %s.")
1857
1858 (js2-msg "msg.bad.getter.parms"
1859 "In order to define a property, getter %s must have zero "
1860 "parameters or a single ScriptableObject parameter.")
1861
1862 (js2-msg "msg.obj.getter.parms"
1863 "Expected static or delegated getter %s to take "
1864 "a ScriptableObject parameter.")
1865
1866 (js2-msg "msg.getter.static"
1867 "Getter and setter must both be static or neither be static.")
1868
1869 (js2-msg "msg.setter.return"
1870 "Setter must have void return type: %s")
1871
1872 (js2-msg "msg.setter2.parms"
1873 "Two-parameter setter must take a ScriptableObject as "
1874 "its first parameter.")
1875
1876 (js2-msg "msg.setter1.parms"
1877 "Expected single parameter setter for %s")
1878
1879 (js2-msg "msg.setter2.expected"
1880 "Expected static or delegated setter %s to take two parameters.")
1881
1882 (js2-msg "msg.setter.parms"
1883 "Expected either one or two parameters for setter.")
1884
1885 (js2-msg "msg.setter.bad.type"
1886 "Unsupported parameter type '%s' in setter '%s'.")
1887
1888 (js2-msg "msg.add.sealed"
1889 "Cannot add a property to a sealed object: %s.")
1890
1891 (js2-msg "msg.remove.sealed"
1892 "Cannot remove a property from a sealed object: %s.")
1893
1894 (js2-msg "msg.modify.sealed"
1895 "Cannot modify a property of a sealed object: %s.")
1896
1897 (js2-msg "msg.modify.readonly"
1898 "Cannot modify readonly property: %s.")
1899
1900 ;; TokenStream
1901 (js2-msg "msg.missing.exponent"
1902 "missing exponent")
1903
1904 (js2-msg "msg.caught.nfe"
1905 "number format error")
1906
1907 (js2-msg "msg.unterminated.string.lit"
1908 "unterminated string literal")
1909
1910 (js2-msg "msg.unterminated.comment"
1911 "unterminated comment")
1912
1913 (js2-msg "msg.unterminated.re.lit"
1914 "unterminated regular expression literal")
1915
1916 (js2-msg "msg.invalid.re.flag"
1917 "invalid flag after regular expression")
1918
1919 (js2-msg "msg.no.re.input.for"
1920 "no input for %s")
1921
1922 (js2-msg "msg.illegal.character"
1923 "illegal character")
1924
1925 (js2-msg "msg.invalid.escape"
1926 "invalid Unicode escape sequence")
1927
1928 (js2-msg "msg.bad.namespace"
1929 "not a valid default namespace statement. "
1930 "Syntax is: default xml namespace = EXPRESSION;")
1931
1932 ;; TokensStream warnings
1933 (js2-msg "msg.bad.octal.literal"
1934 "illegal octal literal digit %s; "
1935 "interpreting it as a decimal digit")
1936
1937 (js2-msg "msg.reserved.keyword"
1938 "illegal usage of future reserved keyword %s; "
1939 "interpreting it as ordinary identifier")
1940
1941 (js2-msg "msg.script.is.not.constructor"
1942 "Script objects are not constructors.")
1943
1944 ;; Arrays
1945 (js2-msg "msg.arraylength.bad"
1946 "Inappropriate array length.")
1947
1948 ;; Arrays
1949 (js2-msg "msg.arraylength.too.big"
1950 "Array length %s exceeds supported capacity limit.")
1951
1952 ;; URI
1953 (js2-msg "msg.bad.uri"
1954 "Malformed URI sequence.")
1955
1956 ;; Number
1957 (js2-msg "msg.bad.precision"
1958 "Precision %s out of range.")
1959
1960 ;; NativeGenerator
1961 (js2-msg "msg.send.newborn"
1962 "Attempt to send value to newborn generator")
1963
1964 (js2-msg "msg.already.exec.gen"
1965 "Already executing generator")
1966
1967 (js2-msg "msg.StopIteration.invalid"
1968 "StopIteration may not be changed to an arbitrary object.")
1969
1970 ;; Interpreter
1971 (js2-msg "msg.yield.closing"
1972 "Yield from closing generator")
1973
1974 ;;; Utilities
1975
1976 (defun js2-delete-if (predicate list)
1977 "Remove all items satisfying PREDICATE in LIST."
1978 (loop for item in list
1979 if (not (funcall predicate item))
1980 collect item))
1981
1982 (defun js2-position (element list)
1983 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1984 Returns nil if element is not found in the list."
1985 (let ((count 0)
1986 found)
1987 (while (and list (not found))
1988 (if (eq element (car list))
1989 (setq found t)
1990 (setq count (1+ count)
1991 list (cdr list))))
1992 (if found count)))
1993
1994 (defun js2-find-if (predicate list)
1995 "Find first item satisfying PREDICATE in LIST."
1996 (let (result)
1997 (while (and list (not result))
1998 (if (funcall predicate (car list))
1999 (setq result (car list)))
2000 (setq list (cdr list)))
2001 result))
2002
2003 (defmacro js2-time (form)
2004 "Evaluate FORM, discard result, and return elapsed time in sec"
2005 (declare (debug t))
2006 (let ((beg (make-symbol "--js2-time-beg--"))
2007 (delta (make-symbol "--js2-time-end--")))
2008 `(let ((,beg (current-time))
2009 ,delta)
2010 ,form
2011 (/ (truncate (* (- (float-time (current-time))
2012 (float-time ,beg))
2013 10000))
2014 10000.0))))
2015
2016 (defsubst js2-same-line (pos)
2017 "Return t if POS is on the same line as current point."
2018 (and (>= pos (point-at-bol))
2019 (<= pos (point-at-eol))))
2020
2021 (defsubst js2-same-line-2 (p1 p2)
2022 "Return t if p1 is on the same line as p2."
2023 (save-excursion
2024 (goto-char p1)
2025 (js2-same-line p2)))
2026
2027 (defun js2-code-bug ()
2028 "Signal an error when we encounter an unexpected code path."
2029 (error "failed assertion"))
2030
2031 (defsubst js2-record-text-property (beg end prop value)
2032 "Record a text property to set when parsing finishes."
2033 (push (list beg end prop value) js2-mode-deferred-properties))
2034
2035 ;; I'd like to associate errors with nodes, but for now the
2036 ;; easiest thing to do is get the context info from the last token.
2037 (defsubst js2-record-parse-error (msg &optional arg pos len)
2038 (push (list (list msg arg)
2039 (or pos js2-token-beg)
2040 (or len (- js2-token-end js2-token-beg)))
2041 js2-parsed-errors))
2042
2043 (defsubst js2-report-error (msg &optional msg-arg pos len)
2044 "Signal a syntax error or record a parse error."
2045 (if js2-recover-from-parse-errors
2046 (js2-record-parse-error msg msg-arg pos len)
2047 (signal 'js2-syntax-error
2048 (list msg
2049 js2-ts-lineno
2050 (save-excursion
2051 (goto-char js2-ts-cursor)
2052 (current-column))
2053 js2-ts-hit-eof))))
2054
2055 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2056 (if js2-compiler-report-warning-as-error
2057 (js2-report-error msg msg-arg pos len)
2058 (push (list (list msg msg-arg)
2059 (or pos js2-token-beg)
2060 (or len (- js2-token-end js2-token-beg)))
2061 js2-parsed-warnings)))
2062
2063 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2064 (if js2-compiler-strict-mode
2065 (js2-report-warning msg-id msg-arg beg
2066 (and beg end (- end beg)))))
2067
2068 (put 'js2-syntax-error 'error-conditions
2069 '(error syntax-error js2-syntax-error))
2070 (put 'js2-syntax-error 'error-message "Syntax error")
2071
2072 (put 'js2-parse-error 'error-conditions
2073 '(error parse-error js2-parse-error))
2074 (put 'js2-parse-error 'error-message "Parse error")
2075
2076 (defmacro js2-clear-flag (flags flag)
2077 `(setq ,flags (logand ,flags (lognot ,flag))))
2078
2079 (defmacro js2-set-flag (flags flag)
2080 "Logical-or FLAG into FLAGS."
2081 `(setq ,flags (logior ,flags ,flag)))
2082
2083 (defsubst js2-flag-set-p (flags flag)
2084 (/= 0 (logand flags flag)))
2085
2086 (defsubst js2-flag-not-set-p (flags flag)
2087 (zerop (logand flags flag)))
2088
2089 ;; Stolen shamelessly from James Clark's nxml-mode.
2090 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2091 "Evaluate BODY without any text property changes modifying the buffer.
2092 Any text properties changes happen as usual but the changes are not treated as
2093 modifications to the buffer."
2094 (declare (indent 0) (debug t))
2095 (let ((modified (make-symbol "modified")))
2096 `(let ((,modified (buffer-modified-p))
2097 (inhibit-read-only t)
2098 (inhibit-modification-hooks t)
2099 (buffer-undo-list t)
2100 (deactivate-mark nil)
2101 ;; Apparently these avoid file locking problems.
2102 (buffer-file-name nil)
2103 (buffer-file-truename nil))
2104 (unwind-protect
2105 (progn ,@body)
2106 (unless ,modified
2107 (restore-buffer-modified-p nil))))))
2108
2109 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2110 "Evaluate BODY with the _ character set to be word-syntax."
2111 (declare (indent 0) (debug t))
2112 (let ((old-syntax (make-symbol "old-syntax")))
2113 `(let ((,old-syntax (string (char-syntax ?_))))
2114 (unwind-protect
2115 (progn
2116 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2117 ,@body)
2118 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2119
2120 (defsubst js2-char-uppercase-p (c)
2121 "Return t if C is an uppercase character.
2122 Handles unicode and latin chars properly."
2123 (/= c (downcase c)))
2124
2125 (defsubst js2-char-lowercase-p (c)
2126 "Return t if C is an uppercase character.
2127 Handles unicode and latin chars properly."
2128 (/= c (upcase c)))
2129
2130 ;;; AST struct and function definitions
2131
2132 ;; flags for ast node property 'member-type (used for e4x operators)
2133 (defvar js2-property-flag #x1 "property access: element is valid name")
2134 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2135 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2136
2137 (defsubst js2-relpos (pos anchor)
2138 "Convert POS to be relative to ANCHOR.
2139 If POS is nil, returns nil."
2140 (and pos (- pos anchor)))
2141
2142 (defsubst js2-make-pad (indent)
2143 (if (zerop indent)
2144 ""
2145 (make-string (* indent js2-basic-offset) ? )))
2146
2147 (defsubst js2-visit-ast (node callback)
2148 "Visit every node in ast NODE with visitor CALLBACK.
2149
2150 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2151 called twice: once to visit the node, and again after all the node's
2152 children have been processed. The END-P argument is nil on the first
2153 call and non-nil on the second call. The return value of the callback
2154 affects the traversal: if non-nil, the children of NODE are processed.
2155 If the callback returns nil, or if the node has no children, then the
2156 callback is called immediately with a non-nil END-P argument.
2157
2158 The node traversal is approximately lexical-order, although there
2159 are currently no guarantees around this."
2160 (if node
2161 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2162 ;; visit the node
2163 (when (funcall callback node nil)
2164 ;; visit the kids
2165 (cond
2166 ((eq vfunc 'js2-visit-none)
2167 nil) ; don't even bother calling it
2168 ;; Each AST node type has to define a `js2-visitor' function
2169 ;; that takes a node and a callback, and calls `js2-visit-ast'
2170 ;; on each child of the node.
2171 (vfunc
2172 (funcall vfunc node callback))
2173 (t
2174 (error "%s does not define a visitor-traversal function"
2175 (aref node 0)))))
2176 ;; call the end-visit
2177 (funcall callback node t))))
2178
2179 (defstruct (js2-node
2180 (:constructor nil)) ; abstract
2181 "Base AST node type."
2182 (type -1) ; token type
2183 (pos -1) ; start position of this AST node in parsed input
2184 (len 1) ; num characters spanned by the node
2185 props ; optional node property list (an alist)
2186 parent) ; link to parent node; null for root
2187
2188 (defsubst js2-node-get-prop (node prop &optional default)
2189 (or (cadr (assoc prop (js2-node-props node))) default))
2190
2191 (defsubst js2-node-set-prop (node prop value)
2192 (setf (js2-node-props node)
2193 (cons (list prop value) (js2-node-props node))))
2194
2195 (defsubst js2-fixup-starts (n nodes)
2196 "Adjust the start positions of NODES to be relative to N.
2197 Any node in the list may be nil, for convenience."
2198 (dolist (node nodes)
2199 (when node
2200 (setf (js2-node-pos node) (- (js2-node-pos node)
2201 (js2-node-pos n))))))
2202
2203 (defsubst js2-node-add-children (parent &rest nodes)
2204 "Set parent node of NODES to PARENT, and return PARENT.
2205 Does nothing if we're not recording parent links.
2206 If any given node in NODES is nil, doesn't record that link."
2207 (js2-fixup-starts parent nodes)
2208 (dolist (node nodes)
2209 (and node
2210 (setf (js2-node-parent node) parent))))
2211
2212 ;; Non-recursive since it's called a frightening number of times.
2213 (defsubst js2-node-abs-pos (n)
2214 (let ((pos (js2-node-pos n)))
2215 (while (setq n (js2-node-parent n))
2216 (setq pos (+ pos (js2-node-pos n))))
2217 pos))
2218
2219 (defsubst js2-node-abs-end (n)
2220 "Return absolute buffer position of end of N."
2221 (+ (js2-node-abs-pos n) (js2-node-len n)))
2222
2223 ;; It's important to make sure block nodes have a lisp list for the
2224 ;; child nodes, to limit printing recursion depth in an AST that
2225 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2226 ;; a sufficiently large vector tree.
2227
2228 (defstruct (js2-block-node
2229 (:include js2-node)
2230 (:constructor nil)
2231 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2232 (pos js2-token-beg)
2233 len
2234 props
2235 kids)))
2236 "A block of statements."
2237 kids) ; a lisp list of the child statement nodes
2238
2239 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2240 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2241
2242 (defsubst js2-visit-block (ast callback)
2243 "Visit the `js2-block-node' children of AST."
2244 (dolist (kid (js2-block-node-kids ast))
2245 (js2-visit-ast kid callback)))
2246
2247 (defun js2-print-block (n i)
2248 (let ((pad (js2-make-pad i)))
2249 (insert pad "{\n")
2250 (dolist (kid (js2-block-node-kids n))
2251 (js2-print-ast kid (1+ i)))
2252 (insert pad "}")))
2253
2254 (defstruct (js2-scope
2255 (:include js2-block-node)
2256 (:constructor nil)
2257 (:constructor make-js2-scope (&key (type js2-BLOCK)
2258 (pos js2-token-beg)
2259 len
2260 kids)))
2261 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2262 ;; I don't have one of those handy, so I'll use an alist for now.
2263 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2264 ;; and is much lighter-weight to construct (both CPU and mem).
2265 ;; The keys are interned strings (symbols) for faster lookup.
2266 ;; Should switch to hybrid alist/hashtable eventually.
2267 symbol-table ; an alist of (symbol . js2-symbol)
2268 parent-scope ; a `js2-scope'
2269 top) ; top-level `js2-scope' (script/function)
2270
2271 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2272 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2273
2274 (defun js2-scope-set-parent-scope (scope parent)
2275 (setf (js2-scope-parent-scope scope) parent
2276 (js2-scope-top scope) (if (null parent)
2277 scope
2278 (js2-scope-top parent))))
2279
2280 (defun js2-node-get-enclosing-scope (node)
2281 "Return the innermost `js2-scope' node surrounding NODE.
2282 Returns nil if there is no enclosing scope node."
2283 (let ((parent (js2-node-parent node)))
2284 (while (not (js2-scope-p parent))
2285 (setq parent (js2-node-parent parent)))
2286 parent))
2287
2288 (defun js2-get-defining-scope (scope name)
2289 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2290 Returns `js2-scope' in which NAME is defined, or nil if not found."
2291 (let ((sym (if (symbolp name)
2292 name
2293 (intern name)))
2294 table
2295 result
2296 (continue t))
2297 (while (and scope continue)
2298 (if (and (setq table (js2-scope-symbol-table scope))
2299 (assq sym table))
2300 (setq continue nil
2301 result scope)
2302 (setq scope (js2-scope-parent-scope scope))))
2303 result))
2304
2305 (defsubst js2-scope-get-symbol (scope name)
2306 "Return symbol table entry for NAME in SCOPE.
2307 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2308 (and (js2-scope-symbol-table scope)
2309 (cdr (assq (if (symbolp name)
2310 name
2311 (intern name))
2312 (js2-scope-symbol-table scope)))))
2313
2314 (defsubst js2-scope-put-symbol (scope name symbol)
2315 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2316 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2317 (let* ((table (js2-scope-symbol-table scope))
2318 (sym (if (symbolp name) name (intern name)))
2319 (entry (assq sym table)))
2320 (if entry
2321 (setcdr entry symbol)
2322 (push (cons sym symbol)
2323 (js2-scope-symbol-table scope)))))
2324
2325 (defstruct (js2-symbol
2326 (:constructor nil)
2327 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2328 "A symbol table entry."
2329 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2330 ;; js2-LET, or js2-CONST
2331 decl-type
2332 name ; string
2333 ast-node) ; a `js2-node'
2334
2335 (defstruct (js2-error-node
2336 (:include js2-node)
2337 (:constructor nil) ; silence emacs21 byte-compiler
2338 (:constructor make-js2-error-node (&key (type js2-ERROR)
2339 (pos js2-token-beg)
2340 len)))
2341 "AST node representing a parse error.")
2342
2343 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2344 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2345
2346 (defstruct (js2-script-node
2347 (:include js2-scope)
2348 (:constructor nil)
2349 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2350 (pos js2-token-beg)
2351 len
2352 var-decls
2353 fun-decls)))
2354 functions ; lisp list of nested functions
2355 regexps ; lisp list of (string . flags)
2356 symbols ; alist (every symbol gets unique index)
2357 (param-count 0)
2358 var-names ; vector of string names
2359 consts ; bool-vector matching var-decls
2360 (temp-number 0)) ; for generating temp variables
2361
2362 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2363 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2364
2365 (defun js2-print-script (node indent)
2366 (dolist (kid (js2-block-node-kids node))
2367 (js2-print-ast kid indent)))
2368
2369 (defstruct (js2-ast-root
2370 (:include js2-script-node)
2371 (:constructor nil)
2372 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2373 (pos js2-token-beg)
2374 len
2375 buffer)))
2376 "The root node of a js2 AST."
2377 buffer ; the source buffer from which the code was parsed
2378 comments ; a lisp list of comments, ordered by start position
2379 errors ; a lisp list of errors found during parsing
2380 warnings ; a lisp list of warnings found during parsing
2381 node-count) ; number of nodes in the tree, including the root
2382
2383 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2384 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2385
2386 (defun js2-visit-ast-root (ast callback)
2387 (dolist (kid (js2-ast-root-kids ast))
2388 (js2-visit-ast kid callback))
2389 (dolist (comment (js2-ast-root-comments ast))
2390 (js2-visit-ast comment callback)))
2391
2392 (defstruct (js2-comment-node
2393 (:include js2-node)
2394 (:constructor nil)
2395 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2396 (pos js2-token-beg)
2397 len
2398 (format js2-ts-comment-type))))
2399 format) ; 'line, 'block, 'jsdoc or 'html
2400
2401 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2402 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2403
2404 (defun js2-print-comment (n i)
2405 ;; We really ought to link end-of-line comments to their nodes.
2406 ;; Or maybe we could add a new comment type, 'endline.
2407 (insert (js2-make-pad i)
2408 (js2-node-string n)))
2409
2410 (defstruct (js2-expr-stmt-node
2411 (:include js2-node)
2412 (:constructor nil)
2413 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2414 (pos js2-ts-cursor)
2415 len
2416 expr)))
2417 "An expression statement."
2418 expr)
2419
2420 (defsubst js2-expr-stmt-node-set-has-result (node)
2421 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2422 (setf (js2-node-type node) js2-EXPR_RESULT))
2423
2424 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2425 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2426
2427 (defun js2-visit-expr-stmt-node (n v)
2428 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2429
2430 (defun js2-print-expr-stmt-node (n indent)
2431 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2432 (insert ";\n"))
2433
2434 (defstruct (js2-loop-node
2435 (:include js2-scope)
2436 (:constructor nil))
2437 "Abstract supertype of loop nodes."
2438 body ; a `js2-block-node'
2439 lp ; position of left-paren, nil if omitted
2440 rp) ; position of right-paren, nil if omitted
2441
2442 (defstruct (js2-do-node
2443 (:include js2-loop-node)
2444 (:constructor nil)
2445 (:constructor make-js2-do-node (&key (type js2-DO)
2446 (pos js2-token-beg)
2447 len
2448 body
2449 condition
2450 while-pos
2451 lp
2452 rp)))
2453 "AST node for do-loop."
2454 condition ; while (expression)
2455 while-pos) ; buffer position of 'while' keyword
2456
2457 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2458 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2459
2460 (defun js2-visit-do-node (n v)
2461 (js2-visit-ast (js2-do-node-body n) v)
2462 (js2-visit-ast (js2-do-node-condition n) v))
2463
2464 (defun js2-print-do-node (n i)
2465 (let ((pad (js2-make-pad i)))
2466 (insert pad "do {\n")
2467 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2468 (js2-print-ast kid (1+ i)))
2469 (insert pad "} while (")
2470 (js2-print-ast (js2-do-node-condition n) 0)
2471 (insert ");\n")))
2472
2473 (defstruct (js2-while-node
2474 (:include js2-loop-node)
2475 (:constructor nil)
2476 (:constructor make-js2-while-node (&key (type js2-WHILE)
2477 (pos js2-token-beg)
2478 len
2479 body
2480 condition
2481 lp
2482 rp)))
2483 "AST node for while-loop."
2484 condition) ; while-condition
2485
2486 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2487 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2488
2489 (defun js2-visit-while-node (n v)
2490 (js2-visit-ast (js2-while-node-condition n) v)
2491 (js2-visit-ast (js2-while-node-body n) v))
2492
2493 (defun js2-print-while-node (n i)
2494 (let ((pad (js2-make-pad i)))
2495 (insert pad "while (")
2496 (js2-print-ast (js2-while-node-condition n) 0)
2497 (insert ") {\n")
2498 (js2-print-body (js2-while-node-body n) (1+ i))
2499 (insert pad "}\n")))
2500
2501 (defstruct (js2-for-node
2502 (:include js2-loop-node)
2503 (:constructor nil)
2504 (:constructor make-js2-for-node (&key (type js2-FOR)
2505 (pos js2-ts-cursor)
2506 len
2507 body
2508 init
2509 condition
2510 update
2511 lp
2512 rp)))
2513 "AST node for a C-style for-loop."
2514 init ; initialization expression
2515 condition ; loop condition
2516 update) ; update clause
2517
2518 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2519 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2520
2521 (defun js2-visit-for-node (n v)
2522 (js2-visit-ast (js2-for-node-init n) v)
2523 (js2-visit-ast (js2-for-node-condition n) v)
2524 (js2-visit-ast (js2-for-node-update n) v)
2525 (js2-visit-ast (js2-for-node-body n) v))
2526
2527 (defun js2-print-for-node (n i)
2528 (let ((pad (js2-make-pad i)))
2529 (insert pad "for (")
2530 (js2-print-ast (js2-for-node-init n) 0)
2531 (insert "; ")
2532 (js2-print-ast (js2-for-node-condition n) 0)
2533 (insert "; ")
2534 (js2-print-ast (js2-for-node-update n) 0)
2535 (insert ") {\n")
2536 (js2-print-body (js2-for-node-body n) (1+ i))
2537 (insert pad "}\n")))
2538
2539 (defstruct (js2-for-in-node
2540 (:include js2-loop-node)
2541 (:constructor nil)
2542 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2543 (pos js2-ts-cursor)
2544 len
2545 body
2546 iterator
2547 object
2548 in-pos
2549 each-pos
2550 foreach-p
2551 lp
2552 rp)))
2553 "AST node for a for..in loop."
2554 iterator ; [var] foo in ...
2555 object ; object over which we're iterating
2556 in-pos ; buffer position of 'in' keyword
2557 each-pos ; buffer position of 'each' keyword, if foreach-p
2558 foreach-p) ; t if it's a for-each loop
2559
2560 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2561 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2562
2563 (defun js2-visit-for-in-node (n v)
2564 (js2-visit-ast (js2-for-in-node-iterator n) v)
2565 (js2-visit-ast (js2-for-in-node-object n) v)
2566 (js2-visit-ast (js2-for-in-node-body n) v))
2567
2568 (defun js2-print-for-in-node (n i)
2569 (let ((pad (js2-make-pad i))
2570 (foreach (js2-for-in-node-foreach-p n)))
2571 (insert pad "for ")
2572 (if foreach
2573 (insert "each "))
2574 (insert "(")
2575 (js2-print-ast (js2-for-in-node-iterator n) 0)
2576 (insert " in ")
2577 (js2-print-ast (js2-for-in-node-object n) 0)
2578 (insert ") {\n")
2579 (js2-print-body (js2-for-in-node-body n) (1+ i))
2580 (insert pad "}\n")))
2581
2582 (defstruct (js2-return-node
2583 (:include js2-node)
2584 (:constructor nil)
2585 (:constructor make-js2-return-node (&key (type js2-RETURN)
2586 (pos js2-ts-cursor)
2587 len
2588 retval)))
2589 "AST node for a return statement."
2590 retval) ; expression to return, or 'undefined
2591
2592 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2593 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2594
2595 (defun js2-visit-return-node (n v)
2596 (js2-visit-ast (js2-return-node-retval n) v))
2597
2598 (defun js2-print-return-node (n i)
2599 (insert (js2-make-pad i) "return")
2600 (when (js2-return-node-retval n)
2601 (insert " ")
2602 (js2-print-ast (js2-return-node-retval n) 0))
2603 (insert ";\n"))
2604
2605 (defstruct (js2-if-node
2606 (:include js2-node)
2607 (:constructor nil)
2608 (:constructor make-js2-if-node (&key (type js2-IF)
2609 (pos js2-ts-cursor)
2610 len
2611 condition
2612 then-part
2613 else-pos
2614 else-part
2615 lp
2616 rp)))
2617 "AST node for an if-statement."
2618 condition ; expression
2619 then-part ; statement or block
2620 else-pos ; optional buffer position of 'else' keyword
2621 else-part ; optional statement or block
2622 lp ; position of left-paren, nil if omitted
2623 rp) ; position of right-paren, nil if omitted
2624
2625 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2626 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2627
2628 (defun js2-visit-if-node (n v)
2629 (js2-visit-ast (js2-if-node-condition n) v)
2630 (js2-visit-ast (js2-if-node-then-part n) v)
2631 (js2-visit-ast (js2-if-node-else-part n) v))
2632
2633 (defun js2-print-if-node (n i)
2634 (let ((pad (js2-make-pad i))
2635 (then-part (js2-if-node-then-part n))
2636 (else-part (js2-if-node-else-part n)))
2637 (insert pad "if (")
2638 (js2-print-ast (js2-if-node-condition n) 0)
2639 (insert ") {\n")
2640 (js2-print-body then-part (1+ i))
2641 (insert pad "}")
2642 (cond
2643 ((not else-part)
2644 (insert "\n"))
2645 ((js2-if-node-p else-part)
2646 (insert " else ")
2647 (js2-print-body else-part i))
2648 (t
2649 (insert " else {\n")
2650 (js2-print-body else-part (1+ i))
2651 (insert pad "}\n")))))
2652
2653 (defstruct (js2-try-node
2654 (:include js2-node)
2655 (:constructor nil)
2656 (:constructor make-js2-try-node (&key (type js2-TRY)
2657 (pos js2-ts-cursor)
2658 len
2659 try-block
2660 catch-clauses
2661 finally-block)))
2662 "AST node for a try-statement."
2663 try-block
2664 catch-clauses ; a lisp list of `js2-catch-node'
2665 finally-block) ; a `js2-finally-node'
2666
2667 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2668 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2669
2670 (defun js2-visit-try-node (n v)
2671 (js2-visit-ast (js2-try-node-try-block n) v)
2672 (dolist (clause (js2-try-node-catch-clauses n))
2673 (js2-visit-ast clause v))
2674 (js2-visit-ast (js2-try-node-finally-block n) v))
2675
2676 (defun js2-print-try-node (n i)
2677 (let ((pad (js2-make-pad i))
2678 (catches (js2-try-node-catch-clauses n))
2679 (finally (js2-try-node-finally-block n)))
2680 (insert pad "try {\n")
2681 (js2-print-body (js2-try-node-try-block n) (1+ i))
2682 (insert pad "}")
2683 (when catches
2684 (dolist (catch catches)
2685 (js2-print-ast catch i)))
2686 (if finally
2687 (js2-print-ast finally i)
2688 (insert "\n"))))
2689
2690 (defstruct (js2-catch-node
2691 (:include js2-node)
2692 (:constructor nil)
2693 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2694 (pos js2-ts-cursor)
2695 len
2696 param
2697 guard-kwd
2698 guard-expr
2699 block
2700 lp
2701 rp)))
2702 "AST node for a catch clause."
2703 param ; destructuring form or simple name node
2704 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2705 guard-expr ; catch condition, a `js2-node'
2706 block ; statements, a `js2-block-node'
2707 lp ; buffer position of left-paren, nil if omitted
2708 rp) ; buffer position of right-paren, nil if omitted
2709
2710 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2711 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2712
2713 (defun js2-visit-catch-node (n v)
2714 (js2-visit-ast (js2-catch-node-param n) v)
2715 (when (js2-catch-node-guard-kwd n)
2716 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2717 (js2-visit-ast (js2-catch-node-block n) v))
2718
2719 (defun js2-print-catch-node (n i)
2720 (let ((pad (js2-make-pad i))
2721 (guard-kwd (js2-catch-node-guard-kwd n))
2722 (guard-expr (js2-catch-node-guard-expr n)))
2723 (insert " catch (")
2724 (js2-print-ast (js2-catch-node-param n) 0)
2725 (when guard-kwd
2726 (insert " if ")
2727 (js2-print-ast guard-expr 0))
2728 (insert ") {\n")
2729 (js2-print-body (js2-catch-node-block n) (1+ i))
2730 (insert pad "}")))
2731
2732 (defstruct (js2-finally-node
2733 (:include js2-node)
2734 (:constructor nil)
2735 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2736 (pos js2-ts-cursor)
2737 len
2738 body)))
2739 "AST node for a finally clause."
2740 body) ; a `js2-node', often but not always a block node
2741
2742 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2743 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2744
2745 (defun js2-visit-finally-node (n v)
2746 (js2-visit-ast (js2-finally-node-body n) v))
2747
2748 (defun js2-print-finally-node (n i)
2749 (let ((pad (js2-make-pad i)))
2750 (insert " finally {\n")
2751 (js2-print-body (js2-finally-node-body n) (1+ i))
2752 (insert pad "}\n")))
2753
2754 (defstruct (js2-switch-node
2755 (:include js2-node)
2756 (:constructor nil)
2757 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2758 (pos js2-ts-cursor)
2759 len
2760 discriminant
2761 cases
2762 lp
2763 rp)))
2764 "AST node for a switch statement."
2765 discriminant ; a `js2-node' (switch expression)
2766 cases ; a lisp list of `js2-case-node'
2767 lp ; position of open-paren for discriminant, nil if omitted
2768 rp) ; position of close-paren for discriminant, nil if omitted
2769
2770 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2771 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2772
2773 (defun js2-visit-switch-node (n v)
2774 (js2-visit-ast (js2-switch-node-discriminant n) v)
2775 (dolist (c (js2-switch-node-cases n))
2776 (js2-visit-ast c v)))
2777
2778 (defun js2-print-switch-node (n i)
2779 (let ((pad (js2-make-pad i))
2780 (cases (js2-switch-node-cases n)))
2781 (insert pad "switch (")
2782 (js2-print-ast (js2-switch-node-discriminant n) 0)
2783 (insert ") {\n")
2784 (dolist (case cases)
2785 (js2-print-ast case i))
2786 (insert pad "}\n")))
2787
2788 (defstruct (js2-case-node
2789 (:include js2-block-node)
2790 (:constructor nil)
2791 (:constructor make-js2-case-node (&key (type js2-CASE)
2792 (pos js2-ts-cursor)
2793 len
2794 kids
2795 expr)))
2796 "AST node for a case clause of a switch statement."
2797 expr) ; the case expression (nil for default)
2798
2799 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2800 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2801
2802 (defun js2-visit-case-node (n v)
2803 (js2-visit-ast (js2-case-node-expr n) v)
2804 (js2-visit-block n v))
2805
2806 (defun js2-print-case-node (n i)
2807 (let ((pad (js2-make-pad i))
2808 (expr (js2-case-node-expr n)))
2809 (insert pad)
2810 (if (null expr)
2811 (insert "default:\n")
2812 (insert "case ")
2813 (js2-print-ast expr 0)
2814 (insert ":\n"))
2815 (dolist (kid (js2-case-node-kids n))
2816 (js2-print-ast kid (1+ i)))))
2817
2818 (defstruct (js2-throw-node
2819 (:include js2-node)
2820 (:constructor nil)
2821 (:constructor make-js2-throw-node (&key (type js2-THROW)
2822 (pos js2-ts-cursor)
2823 len
2824 expr)))
2825 "AST node for a throw statement."
2826 expr) ; the expression to throw
2827
2828 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2829 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2830
2831 (defun js2-visit-throw-node (n v)
2832 (js2-visit-ast (js2-throw-node-expr n) v))
2833
2834 (defun js2-print-throw-node (n i)
2835 (insert (js2-make-pad i) "throw ")
2836 (js2-print-ast (js2-throw-node-expr n) 0)
2837 (insert ";\n"))
2838
2839 (defstruct (js2-with-node
2840 (:include js2-node)
2841 (:constructor nil)
2842 (:constructor make-js2-with-node (&key (type js2-WITH)
2843 (pos js2-ts-cursor)
2844 len
2845 object
2846 body
2847 lp
2848 rp)))
2849 "AST node for a with-statement."
2850 object
2851 body
2852 lp ; buffer position of left-paren around object, nil if omitted
2853 rp) ; buffer position of right-paren around object, nil if omitted
2854
2855 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2856 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2857
2858 (defun js2-visit-with-node (n v)
2859 (js2-visit-ast (js2-with-node-object n) v)
2860 (js2-visit-ast (js2-with-node-body n) v))
2861
2862 (defun js2-print-with-node (n i)
2863 (let ((pad (js2-make-pad i)))
2864 (insert pad "with (")
2865 (js2-print-ast (js2-with-node-object n) 0)
2866 (insert ") {\n")
2867 (js2-print-body (js2-with-node-body n) (1+ i))
2868 (insert pad "}\n")))
2869
2870 (defstruct (js2-label-node
2871 (:include js2-node)
2872 (:constructor nil)
2873 (:constructor make-js2-label-node (&key (type js2-LABEL)
2874 (pos js2-ts-cursor)
2875 len
2876 name)))
2877 "AST node for a statement label or case label."
2878 name ; a string
2879 loop) ; for validating and code-generating continue-to-label
2880
2881 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2882 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2883
2884 (defun js2-print-label (n i)
2885 (insert (js2-make-pad i)
2886 (js2-label-node-name n)
2887 ":\n"))
2888
2889 (defstruct (js2-labeled-stmt-node
2890 (:include js2-node)
2891 (:constructor nil)
2892 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2893 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2894 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2895 (pos js2-ts-cursor)
2896 len
2897 labels
2898 stmt)))
2899 "AST node for a statement with one or more labels.
2900 Multiple labels for a statement are collapsed into the labels field."
2901 labels ; lisp list of `js2-label-node'
2902 stmt) ; the statement these labels are for
2903
2904 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2905 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2906
2907 (defun js2-get-label-by-name (lbl-stmt name)
2908 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2909 Returns nil if no such label is in the list."
2910 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2911 result)
2912 (while (and label-list (not result))
2913 (if (string= (js2-label-node-name (car label-list)) name)
2914 (setq result (car label-list))
2915 (setq label-list (cdr label-list))))
2916 result))
2917
2918 (defun js2-visit-labeled-stmt (n v)
2919 (dolist (label (js2-labeled-stmt-node-labels n))
2920 (js2-visit-ast label v))
2921 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2922
2923 (defun js2-print-labeled-stmt (n i)
2924 (dolist (label (js2-labeled-stmt-node-labels n))
2925 (js2-print-ast label i))
2926 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2927
2928 (defun js2-labeled-stmt-node-contains (node label)
2929 "Return t if NODE contains LABEL in its label set.
2930 NODE is a `js2-labels-node'. LABEL is an identifier."
2931 (loop for nl in (js2-labeled-stmt-node-labels node)
2932 if (string= label (js2-label-node-name nl))
2933 return t
2934 finally return nil))
2935
2936 (defsubst js2-labeled-stmt-node-add-label (node label)
2937 "Add a `js2-label-node' to the label set for this statement."
2938 (setf (js2-labeled-stmt-node-labels node)
2939 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2940
2941 (defstruct (js2-jump-node
2942 (:include js2-node)
2943 (:constructor nil))
2944 "Abstract supertype of break and continue nodes."
2945 label ; `js2-name-node' for location of label identifier, if present
2946 target) ; target js2-labels-node or loop/switch statement
2947
2948 (defun js2-visit-jump-node (n v)
2949 (js2-visit-ast (js2-jump-node-label n) v))
2950
2951 (defstruct (js2-break-node
2952 (:include js2-jump-node)
2953 (:constructor nil)
2954 (:constructor make-js2-break-node (&key (type js2-BREAK)
2955 (pos js2-ts-cursor)
2956 len
2957 label
2958 target)))
2959 "AST node for a break statement.
2960 The label field is a `js2-name-node', possibly nil, for the named label
2961 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2962 is the target of the break - a label node or enclosing loop/switch statement.")
2963
2964 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2965 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2966
2967 (defun js2-print-break-node (n i)
2968 (insert (js2-make-pad i) "break")
2969 (when (js2-break-node-label n)
2970 (insert " ")
2971 (js2-print-ast (js2-break-node-label n) 0))
2972 (insert ";\n"))
2973
2974 (defstruct (js2-continue-node
2975 (:include js2-jump-node)
2976 (:constructor nil)
2977 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2978 (pos js2-ts-cursor)
2979 len
2980 label
2981 target)))
2982 "AST node for a continue statement.
2983 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2984 It is nil if continue specifies no label. The target field is the jump target:
2985 a `js2-label-node' or the innermost enclosing loop.")
2986
2987 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2988 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2989
2990 (defun js2-print-continue-node (n i)
2991 (insert (js2-make-pad i) "continue")
2992 (when (js2-continue-node-label n)
2993 (insert " ")
2994 (js2-print-ast (js2-continue-node-label n) 0))
2995 (insert ";\n"))
2996
2997 (defstruct (js2-function-node
2998 (:include js2-script-node)
2999 (:constructor nil)
3000 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3001 (pos js2-ts-cursor)
3002 len
3003 (ftype 'FUNCTION)
3004 (form 'FUNCTION_STATEMENT)
3005 (name "")
3006 params
3007 body
3008 lp
3009 rp)))
3010 "AST node for a function declaration.
3011 The `params' field is a lisp list of nodes. Each node is either a simple
3012 `js2-name-node', or if it's a destructuring-assignment parameter, a
3013 `js2-array-node' or `js2-object-node'."
3014 ftype ; FUNCTION, GETTER or SETTER
3015 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3016 name ; function name (a `js2-name-node', or nil if anonymous)
3017 params ; a lisp list of destructuring forms or simple name nodes
3018 body ; a `js2-block-node' or expression node (1.8 only)
3019 lp ; position of arg-list open-paren, or nil if omitted
3020 rp ; position of arg-list close-paren, or nil if omitted
3021 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3022 needs-activation ; t if we need an activation object for this frame
3023 is-generator ; t if this function contains a yield
3024 member-expr) ; nonstandard Ecma extension from Rhino
3025
3026 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3027 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3028
3029 (defun js2-visit-function-node (n v)
3030 (js2-visit-ast (js2-function-node-name n) v)
3031 (dolist (p (js2-function-node-params n))
3032 (js2-visit-ast p v))
3033 (js2-visit-ast (js2-function-node-body n) v))
3034
3035 (defun js2-print-function-node (n i)
3036 (let ((pad (js2-make-pad i))
3037 (getter (js2-node-get-prop n 'GETTER_SETTER))
3038 (name (js2-function-node-name n))
3039 (params (js2-function-node-params n))
3040 (body (js2-function-node-body n))
3041 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3042 (unless getter
3043 (insert pad "function"))
3044 (when name
3045 (insert " ")
3046 (js2-print-ast name 0))
3047 (insert "(")
3048 (loop with len = (length params)
3049 for param in params
3050 for count from 1
3051 do
3052 (js2-print-ast param 0)
3053 (if (< count len)
3054 (insert ", ")))
3055 (insert ") {")
3056 (unless expr
3057 (insert "\n"))
3058 ;; TODO: fix this to be smarter about indenting, etc.
3059 (js2-print-body body (1+ i))
3060 (insert pad "}")
3061 (unless expr
3062 (insert "\n"))))
3063
3064 (defsubst js2-function-name (node)
3065 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3066 (and (js2-function-node-name node)
3067 (js2-name-node-name (js2-function-node-name node))))
3068
3069 ;; Having this be an expression node makes it more flexible.
3070 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3071 ;; that work better if you assume it's an expression. Whenever we have
3072 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3073 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3074 (defstruct (js2-var-decl-node
3075 (:include js2-node)
3076 (:constructor nil)
3077 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3078 (pos js2-token-beg)
3079 len
3080 kids
3081 decl-type)))
3082 "AST node for a variable declaration list (VAR, CONST or LET).
3083 The node bounds differ depending on the declaration type. For VAR or
3084 CONST declarations, the bounds include the var/const keyword. For LET
3085 declarations, the node begins at the position of the first child."
3086 kids ; a lisp list of `js2-var-init-node' structs.
3087 decl-type) ; js2-VAR, js2-CONST or js2-LET
3088
3089 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3090 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3091
3092 (defun js2-visit-var-decl (n v)
3093 (dolist (kid (js2-var-decl-node-kids n))
3094 (js2-visit-ast kid v)))
3095
3096 (defun js2-print-var-decl (n i)
3097 (let ((pad (js2-make-pad i))
3098 (tt (js2-var-decl-node-decl-type n)))
3099 (insert pad)
3100 (insert (cond
3101 ((= tt js2-VAR) "var ")
3102 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3103 ((= tt js2-CONST) "const ")
3104 (t
3105 (error "malformed var-decl node"))))
3106 (loop with kids = (js2-var-decl-node-kids n)
3107 with len = (length kids)
3108 for kid in kids
3109 for count from 1
3110 do
3111 (js2-print-ast kid 0)
3112 (if (< count len)
3113 (insert ", ")))))
3114
3115 (defstruct (js2-var-init-node
3116 (:include js2-node)
3117 (:constructor nil)
3118 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3119 (pos js2-ts-cursor)
3120 len
3121 target
3122 initializer)))
3123 "AST node for a variable declaration.
3124 The type field will be js2-CONST for a const decl."
3125 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3126 initializer) ; initializer expression, a `js2-node'
3127
3128 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3129 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3130
3131 (defun js2-visit-var-init-node (n v)
3132 (js2-visit-ast (js2-var-init-node-target n) v)
3133 (js2-visit-ast (js2-var-init-node-initializer n) v))
3134
3135 (defun js2-print-var-init-node (n i)
3136 (let ((pad (js2-make-pad i))
3137 (name (js2-var-init-node-target n))
3138 (init (js2-var-init-node-initializer n)))
3139 (insert pad)
3140 (js2-print-ast name 0)
3141 (when init
3142 (insert " = ")
3143 (js2-print-ast init 0))))
3144
3145 (defstruct (js2-cond-node
3146 (:include js2-node)
3147 (:constructor nil)
3148 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3149 (pos js2-ts-cursor)
3150 len
3151 test-expr
3152 true-expr
3153 false-expr
3154 q-pos
3155 c-pos)))
3156 "AST node for the ternary operator"
3157 test-expr
3158 true-expr
3159 false-expr
3160 q-pos ; buffer position of ?
3161 c-pos) ; buffer position of :
3162
3163 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3164 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3165
3166 (defun js2-visit-cond-node (n v)
3167 (js2-visit-ast (js2-cond-node-test-expr n) v)
3168 (js2-visit-ast (js2-cond-node-true-expr n) v)
3169 (js2-visit-ast (js2-cond-node-false-expr n) v))
3170
3171 (defun js2-print-cond-node (n i)
3172 (let ((pad (js2-make-pad i)))
3173 (insert pad)
3174 (js2-print-ast (js2-cond-node-test-expr n) 0)
3175 (insert " ? ")
3176 (js2-print-ast (js2-cond-node-true-expr n) 0)
3177 (insert " : ")
3178 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3179
3180 (defstruct (js2-infix-node
3181 (:include js2-node)
3182 (:constructor nil)
3183 (:constructor make-js2-infix-node (&key type
3184 (pos js2-ts-cursor)
3185 len
3186 op-pos
3187 left
3188 right)))
3189 "Represents infix expressions.
3190 Includes assignment ops like `|=', and the comma operator.
3191 The type field inherited from `js2-node' holds the operator."
3192 op-pos ; buffer position where operator begins
3193 left ; any `js2-node'
3194 right) ; any `js2-node'
3195
3196 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3197 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3198
3199 (defun js2-visit-infix-node (n v)
3200 (js2-visit-ast (js2-infix-node-left n) v)
3201 (js2-visit-ast (js2-infix-node-right n) v))
3202
3203 (defconst js2-operator-tokens
3204 (let ((table (make-hash-table :test 'eq))
3205 (tokens
3206 (list (cons js2-IN "in")
3207 (cons js2-TYPEOF "typeof")
3208 (cons js2-INSTANCEOF "instanceof")
3209 (cons js2-DELPROP "delete")
3210 (cons js2-COMMA ",")
3211 (cons js2-COLON ":")
3212 (cons js2-OR "||")
3213 (cons js2-AND "&&")
3214 (cons js2-INC "++")
3215 (cons js2-DEC "--")
3216 (cons js2-BITOR "|")
3217 (cons js2-BITXOR "^")
3218 (cons js2-BITAND "&")
3219 (cons js2-EQ "==")
3220 (cons js2-NE "!=")
3221 (cons js2-LT "<")
3222 (cons js2-LE "<=")
3223 (cons js2-GT ">")
3224 (cons js2-GE ">=")
3225 (cons js2-LSH "<<")
3226 (cons js2-RSH ">>")
3227 (cons js2-URSH ">>>")
3228 (cons js2-ADD "+") ; infix plus
3229 (cons js2-SUB "-") ; infix minus
3230 (cons js2-MUL "*")
3231 (cons js2-DIV "/")
3232 (cons js2-MOD "%")
3233 (cons js2-NOT "!")
3234 (cons js2-BITNOT "~")
3235 (cons js2-POS "+") ; unary plus
3236 (cons js2-NEG "-") ; unary minus
3237 (cons js2-SHEQ "===") ; shallow equality
3238 (cons js2-SHNE "!==") ; shallow inequality
3239 (cons js2-ASSIGN "=")
3240 (cons js2-ASSIGN_BITOR "|=")
3241 (cons js2-ASSIGN_BITXOR "^=")
3242 (cons js2-ASSIGN_BITAND "&=")
3243 (cons js2-ASSIGN_LSH "<<=")
3244 (cons js2-ASSIGN_RSH ">>=")
3245 (cons js2-ASSIGN_URSH ">>>=")
3246 (cons js2-ASSIGN_ADD "+=")
3247 (cons js2-ASSIGN_SUB "-=")
3248 (cons js2-ASSIGN_MUL "*=")
3249 (cons js2-ASSIGN_DIV "/=")
3250 (cons js2-ASSIGN_MOD "%="))))
3251 (loop for (k . v) in tokens do
3252 (puthash k v table))
3253 table))
3254
3255 (defun js2-print-infix-node (n i)
3256 (let* ((tt (js2-node-type n))
3257 (op (gethash tt js2-operator-tokens)))
3258 (unless op
3259 (error "unrecognized infix operator %s" (js2-node-type n)))
3260 (insert (js2-make-pad i))
3261 (js2-print-ast (js2-infix-node-left n) 0)
3262 (unless (= tt js2-COMMA)
3263 (insert " "))
3264 (insert op)
3265 (insert " ")
3266 (js2-print-ast (js2-infix-node-right n) 0)))
3267
3268 (defstruct (js2-assign-node
3269 (:include js2-infix-node)
3270 (:constructor nil)
3271 (:constructor make-js2-assign-node (&key type
3272 (pos js2-ts-cursor)
3273 len
3274 op-pos
3275 left
3276 right)))
3277 "Represents any assignment.
3278 The type field holds the actual assignment operator.")
3279
3280 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3281 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3282
3283 (defstruct (js2-unary-node
3284 (:include js2-node)
3285 (:constructor nil)
3286 (:constructor make-js2-unary-node (&key type ; required
3287 (pos js2-ts-cursor)
3288 len
3289 operand)))
3290 "AST node type for unary operator nodes.
3291 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3292 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3293 property is added if the operator follows the operand."
3294 operand) ; a `js2-node' expression
3295
3296 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3297 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3298
3299 (defun js2-visit-unary-node (n v)
3300 (js2-visit-ast (js2-unary-node-operand n) v))
3301
3302 (defun js2-print-unary-node (n i)
3303 (let* ((tt (js2-node-type n))
3304 (op (gethash tt js2-operator-tokens))
3305 (postfix (js2-node-get-prop n 'postfix)))
3306 (unless op
3307 (error "unrecognized unary operator %s" tt))
3308 (insert (js2-make-pad i))
3309 (unless postfix
3310 (insert op))
3311 (if (or (= tt js2-TYPEOF)
3312 (= tt js2-DELPROP))
3313 (insert " "))
3314 (js2-print-ast (js2-unary-node-operand n) 0)
3315 (when postfix
3316 (insert op))))
3317
3318 (defstruct (js2-let-node
3319 (:include js2-scope)
3320 (:constructor nil)
3321 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3322 (pos js2-token-beg)
3323 len
3324 vars
3325 body
3326 lp
3327 rp)))
3328 "AST node for a let expression or a let statement.
3329 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3330 vars ; a `js2-var-decl-node'
3331 body ; a `js2-node' representing the expression or body block
3332 lp
3333 rp)
3334
3335 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3336 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3337
3338 (defun js2-visit-let-node (n v)
3339 (js2-visit-ast (js2-let-node-vars n) v)
3340 (js2-visit-ast (js2-let-node-body n) v))
3341
3342 (defun js2-print-let-node (n i)
3343 (insert (js2-make-pad i) "let (")
3344 (js2-print-ast (js2-let-node-vars n) 0)
3345 (insert ") ")
3346 (js2-print-ast (js2-let-node-body n) i))
3347
3348 (defstruct (js2-keyword-node
3349 (:include js2-node)
3350 (:constructor nil)
3351 (:constructor make-js2-keyword-node (&key type
3352 (pos js2-token-beg)
3353 (len (- js2-ts-cursor pos)))))
3354 "AST node representing a literal keyword such as `null'.
3355 Used for `null', `this', `true', `false' and `debugger'.
3356 The node type is set to js2-NULL, js2-THIS, etc.")
3357
3358 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3359 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3360
3361 (defun js2-print-keyword-node (n i)
3362 (insert (js2-make-pad i)
3363 (let ((tt (js2-node-type n)))
3364 (cond
3365 ((= tt js2-THIS) "this")
3366 ((= tt js2-NULL) "null")
3367 ((= tt js2-TRUE) "true")
3368 ((= tt js2-FALSE) "false")
3369 ((= tt js2-DEBUGGER) "debugger")
3370 (t (error "Invalid keyword literal type: %d" tt))))))
3371
3372 (defsubst js2-this-node-p (node)
3373 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3374 (eq (js2-node-type node) js2-THIS))
3375
3376 (defstruct (js2-new-node
3377 (:include js2-node)
3378 (:constructor nil)
3379 (:constructor make-js2-new-node (&key (type js2-NEW)
3380 (pos js2-token-beg)
3381 len
3382 target
3383 args
3384 initializer
3385 lp
3386 rp)))
3387 "AST node for new-expression such as new Foo()."
3388 target ; an identifier or reference
3389 args ; a lisp list of argument nodes
3390 lp ; position of left-paren, nil if omitted
3391 rp ; position of right-paren, nil if omitted
3392 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3393
3394 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3395 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3396
3397 (defun js2-visit-new-node (n v)
3398 (js2-visit-ast (js2-new-node-target n) v)
3399 (dolist (arg (js2-new-node-args n))
3400 (js2-visit-ast arg v))
3401 (js2-visit-ast (js2-new-node-initializer n) v))
3402
3403 (defun js2-print-new-node (n i)
3404 (insert (js2-make-pad i) "new ")
3405 (js2-print-ast (js2-new-node-target n))
3406 (insert "(")
3407 (js2-print-list (js2-new-node-args n))
3408 (insert ")")
3409 (when (js2-new-node-initializer n)
3410 (insert " ")
3411 (js2-print-ast (js2-new-node-initializer n))))
3412
3413 (defstruct (js2-name-node
3414 (:include js2-node)
3415 (:constructor nil)
3416 (:constructor make-js2-name-node (&key (type js2-NAME)
3417 (pos js2-token-beg)
3418 (len (- js2-ts-cursor
3419 js2-token-beg))
3420 (name js2-ts-string))))
3421 "AST node for a JavaScript identifier"
3422 name ; a string
3423 scope) ; a `js2-scope' (optional, used for codegen)
3424
3425 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3426 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3427
3428 (defun js2-print-name-node (n i)
3429 (insert (js2-make-pad i)
3430 (js2-name-node-name n)))
3431
3432 (defsubst js2-name-node-length (node)
3433 "Return identifier length of NODE, a `js2-name-node'.
3434 Returns 0 if NODE is nil or its identifier field is nil."
3435 (if node
3436 (length (js2-name-node-name node))
3437 0))
3438
3439 (defstruct (js2-number-node
3440 (:include js2-node)
3441 (:constructor nil)
3442 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3443 (pos js2-token-beg)
3444 (len (- js2-ts-cursor
3445 js2-token-beg))
3446 (value js2-ts-string)
3447 (num-value js2-ts-number))))
3448 "AST node for a number literal."
3449 value ; the original string, e.g. "6.02e23"
3450 num-value) ; the parsed number value
3451
3452 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3453 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3454
3455 (defun js2-print-number-node (n i)
3456 (insert (js2-make-pad i)
3457 (number-to-string (js2-number-node-num-value n))))
3458
3459 (defstruct (js2-regexp-node
3460 (:include js2-node)
3461 (:constructor nil)
3462 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3463 (pos js2-token-beg)
3464 (len (- js2-ts-cursor
3465 js2-token-beg))
3466 value
3467 flags)))
3468 "AST node for a regular expression literal."
3469 value ; the regexp string, without // delimiters
3470 flags) ; a string of flags, e.g. `mi'.
3471
3472 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3473 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3474
3475 (defun js2-print-regexp (n i)
3476 (insert (js2-make-pad i)
3477 "/"
3478 (js2-regexp-node-value n)
3479 "/")
3480 (if (js2-regexp-node-flags n)
3481 (insert (js2-regexp-node-flags n))))
3482
3483 (defstruct (js2-string-node
3484 (:include js2-node)
3485 (:constructor nil)
3486 (:constructor make-js2-string-node (&key (type js2-STRING)
3487 (pos js2-token-beg)
3488 (len (- js2-ts-cursor
3489 js2-token-beg))
3490 (value js2-ts-string))))
3491 "String literal.
3492 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3493 You can tell the quote type by looking at the first character."
3494 value) ; the characters of the string, including the quotes
3495
3496 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3497 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3498
3499 (defun js2-print-string-node (n i)
3500 (insert (js2-make-pad i)
3501 (js2-node-string n)))
3502
3503 (defstruct (js2-array-node
3504 (:include js2-node)
3505 (:constructor nil)
3506 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3507 (pos js2-ts-cursor)
3508 len
3509 elems)))
3510 "AST node for an array literal."
3511 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3512
3513 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3514 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3515
3516 (defun js2-visit-array-node (n v)
3517 (dolist (e (js2-array-node-elems n))
3518 (js2-visit-ast e v)))
3519
3520 (defun js2-print-array-node (n i)
3521 (insert (js2-make-pad i) "[")
3522 (js2-print-list (js2-array-node-elems n))
3523 (insert "]"))
3524
3525 (defstruct (js2-object-node
3526 (:include js2-node)
3527 (:constructor nil)
3528 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3529 (pos js2-ts-cursor)
3530 len
3531 elems)))
3532 "AST node for an object literal expression.
3533 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3534 the latter represents abbreviation in destructuring expressions."
3535 elems)
3536
3537 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3538 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3539
3540 (defun js2-visit-object-node (n v)
3541 (dolist (e (js2-object-node-elems n))
3542 (js2-visit-ast e v)))
3543
3544 (defun js2-print-object-node (n i)
3545 (insert (js2-make-pad i) "{")
3546 (js2-print-list (js2-object-node-elems n))
3547 (insert "}"))
3548
3549 (defstruct (js2-object-prop-node
3550 (:include js2-infix-node)
3551 (:constructor nil)
3552 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3553 (pos js2-ts-cursor)
3554 len
3555 left
3556 right
3557 op-pos)))
3558 "AST node for an object literal prop:value entry.
3559 The `left' field is the property: a name node, string node or number node.
3560 The `right' field is a `js2-node' representing the initializer value.")
3561
3562 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3563 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3564
3565 (defun js2-print-object-prop-node (n i)
3566 (insert (js2-make-pad i))
3567 (js2-print-ast (js2-object-prop-node-left n) 0)
3568 (insert ":")
3569 (js2-print-ast (js2-object-prop-node-right n) 0))
3570
3571 (defstruct (js2-getter-setter-node
3572 (:include js2-infix-node)
3573 (:constructor nil)
3574 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3575 (pos js2-ts-cursor)
3576 len
3577 left
3578 right)))
3579 "AST node for a getter/setter property in an object literal.
3580 The `left' field is the `js2-name-node' naming the getter/setter prop.
3581 The `right' field is always an anonymous `js2-function-node' with a node
3582 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3583
3584 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3585 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3586
3587 (defun js2-print-getter-setter (n i)
3588 (let ((pad (js2-make-pad i))
3589 (left (js2-getter-setter-node-left n))
3590 (right (js2-getter-setter-node-right n)))
3591 (insert pad)
3592 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3593 (js2-print-ast left 0)
3594 (js2-print-ast right 0)))
3595
3596 (defstruct (js2-prop-get-node
3597 (:include js2-infix-node)
3598 (:constructor nil)
3599 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3600 (pos js2-ts-cursor)
3601 len
3602 left
3603 right)))
3604 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3605
3606 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3607 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3608
3609 (defun js2-visit-prop-get-node (n v)
3610 (js2-visit-ast (js2-prop-get-node-left n) v)
3611 (js2-visit-ast (js2-prop-get-node-right n) v))
3612
3613 (defun js2-print-prop-get-node (n i)
3614 (insert (js2-make-pad i))
3615 (js2-print-ast (js2-prop-get-node-left n) 0)
3616 (insert ".")
3617 (js2-print-ast (js2-prop-get-node-right n) 0))
3618
3619 (defstruct (js2-elem-get-node
3620 (:include js2-node)
3621 (:constructor nil)
3622 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3623 (pos js2-ts-cursor)
3624 len
3625 target
3626 element
3627 lb
3628 rb)))
3629 "AST node for an array index expression such as foo[bar]."
3630 target ; a `js2-node' - the expression preceding the "."
3631 element ; a `js2-node' - the expression in brackets
3632 lb ; position of left-bracket, nil if omitted
3633 rb) ; position of right-bracket, nil if omitted
3634
3635 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3636 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3637
3638 (defun js2-visit-elem-get-node (n v)
3639 (js2-visit-ast (js2-elem-get-node-target n) v)
3640 (js2-visit-ast (js2-elem-get-node-element n) v))
3641
3642 (defun js2-print-elem-get-node (n i)
3643 (insert (js2-make-pad i))
3644 (js2-print-ast (js2-elem-get-node-target n) 0)
3645 (insert "[")
3646 (js2-print-ast (js2-elem-get-node-element n) 0)
3647 (insert "]"))
3648
3649 (defstruct (js2-call-node
3650 (:include js2-node)
3651 (:constructor nil)
3652 (:constructor make-js2-call-node (&key (type js2-CALL)
3653 (pos js2-ts-cursor)
3654 len
3655 target
3656 args
3657 lp
3658 rp)))
3659 "AST node for a JavaScript function call."
3660 target ; a `js2-node' evaluating to the function to call
3661 args ; a lisp list of `js2-node' arguments
3662 lp ; position of open-paren, or nil if missing
3663 rp) ; position of close-paren, or nil if missing
3664
3665 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3666 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3667
3668 (defun js2-visit-call-node (n v)
3669 (js2-visit-ast (js2-call-node-target n) v)
3670 (dolist (arg (js2-call-node-args n))
3671 (js2-visit-ast arg v)))
3672
3673 (defun js2-print-call-node (n i)
3674 (insert (js2-make-pad i))
3675 (js2-print-ast (js2-call-node-target n) 0)
3676 (insert "(")
3677 (js2-print-list (js2-call-node-args n))
3678 (insert ")"))
3679
3680 (defstruct (js2-yield-node
3681 (:include js2-node)
3682 (:constructor nil)
3683 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3684 (pos js2-ts-cursor)
3685 len
3686 value)))
3687 "AST node for yield statement or expression."
3688 value) ; optional: value to be yielded
3689
3690 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3691 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3692
3693 (defun js2-visit-yield-node (n v)
3694 (js2-visit-ast (js2-yield-node-value n) v))
3695
3696 (defun js2-print-yield-node (n i)
3697 (insert (js2-make-pad i))
3698 (insert "yield")
3699 (when (js2-yield-node-value n)
3700 (insert " ")
3701 (js2-print-ast (js2-yield-node-value n) 0)))
3702
3703 (defstruct (js2-paren-node
3704 (:include js2-node)
3705 (:constructor nil)
3706 (:constructor make-js2-paren-node (&key (type js2-LP)
3707 (pos js2-ts-cursor)
3708 len
3709 expr)))
3710 "AST node for a parenthesized expression.
3711 In particular, used when the parens are syntactically optional,
3712 as opposed to required parens such as those enclosing an if-conditional."
3713 expr) ; `js2-node'
3714
3715 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3716 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3717
3718 (defun js2-visit-paren-node (n v)
3719 (js2-visit-ast (js2-paren-node-expr n) v))
3720
3721 (defun js2-print-paren-node (n i)
3722 (insert (js2-make-pad i))
3723 (insert "(")
3724 (js2-print-ast (js2-paren-node-expr n) 0)
3725 (insert ")"))
3726
3727 (defstruct (js2-array-comp-node
3728 (:include js2-scope)
3729 (:constructor nil)
3730 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3731 (pos js2-ts-cursor)
3732 len
3733 result
3734 loops
3735 filter
3736 if-pos
3737 lp
3738 rp)))
3739 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3740 result ; result expression (just after left-bracket)
3741 loops ; a lisp list of `js2-array-comp-loop-node'
3742 filter ; guard/filter expression
3743 if-pos ; buffer pos of 'if' keyword, if present, else nil
3744 lp ; buffer position of if-guard left-paren, or nil if not present
3745 rp) ; buffer position of if-guard right-paren, or nil if not present
3746
3747 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3748 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3749
3750 (defun js2-visit-array-comp-node (n v)
3751 (js2-visit-ast (js2-array-comp-node-result n) v)
3752 (dolist (l (js2-array-comp-node-loops n))
3753 (js2-visit-ast l v))
3754 (js2-visit-ast (js2-array-comp-node-filter n) v))
3755
3756 (defun js2-print-array-comp-node (n i)
3757 (let ((pad (js2-make-pad i))
3758 (result (js2-array-comp-node-result n))
3759 (loops (js2-array-comp-node-loops n))
3760 (filter (js2-array-comp-node-filter n)))
3761 (insert pad "[")
3762 (js2-print-ast result 0)
3763 (dolist (l loops)
3764 (insert " ")
3765 (js2-print-ast l 0))
3766 (when filter
3767 (insert " if (")
3768 (js2-print-ast filter 0))
3769 (insert ")]")))
3770
3771 (defstruct (js2-array-comp-loop-node
3772 (:include js2-for-in-node)
3773 (:constructor nil)
3774 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3775 (pos js2-ts-cursor)
3776 len
3777 iterator
3778 object
3779 in-pos
3780 foreach-p
3781 each-pos
3782 lp
3783 rp)))
3784 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3785
3786 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3787 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3788
3789 (defun js2-visit-array-comp-loop (n v)
3790 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3791 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3792
3793 (defun js2-print-array-comp-loop (n i)
3794 (insert "for (")
3795 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3796 (insert " in ")
3797 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3798 (insert ")"))
3799
3800 (defstruct (js2-empty-expr-node
3801 (:include js2-node)
3802 (:constructor nil)
3803 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3804 (pos js2-token-beg)
3805 len)))
3806 "AST node for an empty expression.")
3807
3808 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3809 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3810
3811 (defstruct (js2-xml-node
3812 (:include js2-block-node)
3813 (:constructor nil)
3814 (:constructor make-js2-xml-node (&key (type js2-XML)
3815 (pos js2-token-beg)
3816 len
3817 kids)))
3818 "AST node for initial parse of E4X literals.
3819 The kids field is a list of XML fragments, each a `js2-string-node' or
3820 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3821
3822 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3823 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3824
3825 (defun js2-print-xml-node (n i)
3826 (dolist (kid (js2-xml-node-kids n))
3827 (js2-print-ast kid i)))
3828
3829 (defstruct (js2-xml-js-expr-node
3830 (:include js2-xml-node)
3831 (:constructor nil)
3832 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3833 (pos js2-ts-cursor)
3834 len
3835 expr)))
3836 "AST node for an embedded JavaScript {expression} in an E4X literal.
3837 The start and end fields correspond to the curly-braces."
3838 expr) ; a `js2-expr-node' of some sort
3839
3840 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3841 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3842
3843 (defun js2-visit-xml-js-expr (n v)
3844 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3845
3846 (defun js2-print-xml-js-expr (n i)
3847 (insert (js2-make-pad i))
3848 (insert "{")
3849 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3850 (insert "}"))
3851
3852 (defstruct (js2-xml-dot-query-node
3853 (:include js2-infix-node)
3854 (:constructor nil)
3855 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3856 (pos js2-ts-cursor)
3857 op-pos
3858 len
3859 left
3860 right
3861 rp)))
3862 "AST node for an E4X foo.(bar) filter expression.
3863 Note that the left-paren is automatically the character immediately
3864 following the dot (.) in the operator. No whitespace is permitted
3865 between the dot and the lp by the scanner."
3866 rp)
3867
3868 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3869 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3870
3871 (defun js2-print-xml-dot-query (n i)
3872 (insert (js2-make-pad i))
3873 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3874 (insert ".(")
3875 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3876 (insert ")"))
3877
3878 (defstruct (js2-xml-ref-node
3879 (:include js2-node)
3880 (:constructor nil)) ; abstract
3881 "Base type for E4X XML attribute-access or property-get expressions.
3882 Such expressions can take a variety of forms. The general syntax has
3883 three parts:
3884
3885 - (optional) an @ (specifying an attribute access)
3886 - (optional) a namespace (a `js2-name-node') and double-colon
3887 - (required) either a `js2-name-node' or a bracketed [expression]
3888
3889 The property-name expressions (examples: ns::name, @name) are
3890 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3891 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3892
3893 This node type (or more specifically, its subclasses) will sometimes
3894 be the right-hand child of a `js2-prop-get-node' or a
3895 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3896 The `js2-xml-ref-node' may also be a standalone primary expression with
3897 no explicit target, which is valid in certain expression contexts such as
3898
3899 company..employee.(@id < 100)
3900
3901 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3902 expression whose parent is a `js2-xml-dot-query-node'."
3903 namespace
3904 at-pos
3905 colon-pos)
3906
3907 (defsubst js2-xml-ref-node-attr-access-p (node)
3908 "Return non-nil if this expression began with an @-token."
3909 (and (numberp (js2-xml-ref-node-at-pos node))
3910 (plusp (js2-xml-ref-node-at-pos node))))
3911
3912 (defstruct (js2-xml-prop-ref-node
3913 (:include js2-xml-ref-node)
3914 (:constructor nil)
3915 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3916 (pos js2-token-beg)
3917 len
3918 propname
3919 namespace
3920 at-pos
3921 colon-pos)))
3922 "AST node for an E4X XML [expr] property-ref expression.
3923 The JavaScript syntax is an optional @, an optional ns::, and a name.
3924
3925 [ '@' ] [ name '::' ] name
3926
3927 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3928 @ns::*, @*::attr, @*::*, and @*.
3929
3930 The node starts at the @ token, if present. Otherwise it starts at the
3931 namespace name. The node bounds extend through the closing right-bracket,
3932 or if it is missing due to a syntax error, through the end of the index
3933 expression."
3934 propname)
3935
3936 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3937 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3938
3939 (defun js2-visit-xml-prop-ref-node (n v)
3940 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3941 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3942
3943 (defun js2-print-xml-prop-ref-node (n i)
3944 (insert (js2-make-pad i))
3945 (if (js2-xml-ref-node-attr-access-p n)
3946 (insert "@"))
3947 (when (js2-xml-prop-ref-node-namespace n)
3948 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3949 (insert "::"))
3950 (if (js2-xml-prop-ref-node-propname n)
3951 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3952
3953 (defstruct (js2-xml-elem-ref-node
3954 (:include js2-xml-ref-node)
3955 (:constructor nil)
3956 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3957 (pos js2-token-beg)
3958 len
3959 expr
3960 lb
3961 rb
3962 namespace
3963 at-pos
3964 colon-pos)))
3965 "AST node for an E4X XML [expr] member-ref expression.
3966 Syntax:
3967
3968 [ '@' ] [ name '::' ] '[' expr ']'
3969
3970 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3971
3972 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3973 is not a legal E4X XML element-ref expression, since it's already used
3974 for standard JavaScript element-get array indexing. Hence, a
3975 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3976 non-nil namespace node, or both.
3977
3978 The node starts at the @ token, if present. Otherwise it starts
3979 at the namespace name. The node bounds extend through the closing
3980 right-bracket, or if it is missing due to a syntax error, through the
3981 end of the index expression."
3982 expr ; the bracketed index expression
3983 lb
3984 rb)
3985
3986 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3987 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3988
3989 (defun js2-visit-xml-elem-ref-node (n v)
3990 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3991 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3992
3993 (defun js2-print-xml-elem-ref-node (n i)
3994 (insert (js2-make-pad i))
3995 (if (js2-xml-ref-node-attr-access-p n)
3996 (insert "@"))
3997 (when (js2-xml-elem-ref-node-namespace n)
3998 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3999 (insert "::"))
4000 (insert "[")
4001 (if (js2-xml-elem-ref-node-expr n)
4002 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4003 (insert "]"))
4004
4005 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4006
4007 (defstruct (js2-xml-start-tag-node
4008 (:include js2-xml-node)
4009 (:constructor nil)
4010 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4011 (pos js2-ts-cursor)
4012 len
4013 name
4014 attrs
4015 kids
4016 empty-p)))
4017 "AST node for an XML start-tag. Not currently used.
4018 The `kids' field is a lisp list of child content nodes."
4019 name ; a `js2-xml-name-node'
4020 attrs ; a lisp list of `js2-xml-attr-node'
4021 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4022
4023 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4024 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4025
4026 (defun js2-visit-xml-start-tag (n v)
4027 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4028 (dolist (attr (js2-xml-start-tag-node-attrs n))
4029 (js2-visit-ast attr v))
4030 (js2-visit-block n v))
4031
4032 (defun js2-print-xml-start-tag (n i)
4033 (insert (js2-make-pad i) "<")
4034 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4035 (when (js2-xml-start-tag-node-attrs n)
4036 (insert " ")
4037 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4038 (insert ">"))
4039
4040 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4041 ;; and add the end-tag to the kids list of the parent as well.
4042 (defstruct (js2-xml-end-tag-node
4043 (:include js2-xml-node)
4044 (:constructor nil)
4045 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4046 (pos js2-ts-cursor)
4047 len
4048 name)))
4049 "AST node for an XML end-tag. Not currently used."
4050 name) ; a `js2-xml-name-node'
4051
4052 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4053 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4054
4055 (defun js2-visit-xml-end-tag (n v)
4056 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4057
4058 (defun js2-print-xml-end-tag (n i)
4059 (insert (js2-make-pad i))
4060 (insert "</")
4061 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4062 (insert ">"))
4063
4064 (defstruct (js2-xml-name-node
4065 (:include js2-xml-node)
4066 (:constructor nil)
4067 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4068 (pos js2-ts-cursor)
4069 len
4070 namespace
4071 kids)))
4072 "AST node for an E4X XML name. Not currently used.
4073 Any XML name can be qualified with a namespace, hence the namespace field.
4074 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4075 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4076 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4077 namespace) ; a `js2-string-node'
4078
4079 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4080 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4081
4082 (defun js2-visit-xml-name-node (n v)
4083 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4084
4085 (defun js2-print-xml-name-node (n i)
4086 (insert (js2-make-pad i))
4087 (when (js2-xml-name-node-namespace n)
4088 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4089 (insert "::"))
4090 (dolist (kid (js2-xml-name-node-kids n))
4091 (js2-print-ast kid 0)))
4092
4093 (defstruct (js2-xml-pi-node
4094 (:include js2-xml-node)
4095 (:constructor nil)
4096 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4097 (pos js2-ts-cursor)
4098 len
4099 name
4100 attrs)))
4101 "AST node for an E4X XML processing instruction. Not currently used."
4102 name ; a `js2-xml-name-node'
4103 attrs) ; a list of `js2-xml-attr-node'
4104
4105 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4106 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4107
4108 (defun js2-visit-xml-pi-node (n v)
4109 (js2-visit-ast (js2-xml-pi-node-name n) v)
4110 (dolist (attr (js2-xml-pi-node-attrs n))
4111 (js2-visit-ast attr v)))
4112
4113 (defun js2-print-xml-pi-node (n i)
4114 (insert (js2-make-pad i) "<?")
4115 (js2-print-ast (js2-xml-pi-node-name n))
4116 (when (js2-xml-pi-node-attrs n)
4117 (insert " ")
4118 (js2-print-list (js2-xml-pi-node-attrs n)))
4119 (insert "?>"))
4120
4121 (defstruct (js2-xml-cdata-node
4122 (:include js2-xml-node)
4123 (:constructor nil)
4124 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4125 (pos js2-ts-cursor)
4126 len
4127 content)))
4128 "AST node for a CDATA escape section. Not currently used."
4129 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4130
4131 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4132 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4133
4134 (defun js2-visit-xml-cdata-node (n v)
4135 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4136
4137 (defun js2-print-xml-cdata-node (n i)
4138 (insert (js2-make-pad i))
4139 (js2-print-ast (js2-xml-cdata-node-content n)))
4140
4141 (defstruct (js2-xml-attr-node
4142 (:include js2-xml-node)
4143 (:constructor nil)
4144 (:constructor make-js2-attr-node (&key (type js2-XML)
4145 (pos js2-ts-cursor)
4146 len
4147 name
4148 value
4149 eq-pos
4150 quote-type)))
4151 "AST node representing a foo='bar' XML attribute value. Not yet used."
4152 name ; a `js2-xml-name-node'
4153 value ; a `js2-xml-name-node'
4154 eq-pos ; buffer position of "=" sign
4155 quote-type) ; 'single or 'double
4156
4157 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4158 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4159
4160 (defun js2-visit-xml-attr-node (n v)
4161 (js2-visit-ast (js2-xml-attr-node-name n) v)
4162 (js2-visit-ast (js2-xml-attr-node-value n) v))
4163
4164 (defun js2-print-xml-attr-node (n i)
4165 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4166 "'"
4167 "\"")))
4168 (insert (js2-make-pad i))
4169 (js2-print-ast (js2-xml-attr-node-name n) 0)
4170 (insert "=" quote)
4171 (js2-print-ast (js2-xml-attr-node-value n) 0)
4172 (insert quote)))
4173
4174 (defstruct (js2-xml-text-node
4175 (:include js2-xml-node)
4176 (:constructor nil)
4177 (:constructor make-js2-text-node (&key (type js2-XML)
4178 (pos js2-ts-cursor)
4179 len
4180 content)))
4181 "AST node for an E4X XML text node. Not currently used."
4182 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4183
4184 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4185 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4186
4187 (defun js2-visit-xml-text-node (n v)
4188 (js2-visit-ast (js2-xml-text-node-content n) v))
4189
4190 (defun js2-print-xml-text-node (n i)
4191 (insert (js2-make-pad i))
4192 (dolist (kid (js2-xml-text-node-content n))
4193 (js2-print-ast kid)))
4194
4195 (defstruct (js2-xml-comment-node
4196 (:include js2-xml-node)
4197 (:constructor nil)
4198 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4199 (pos js2-ts-cursor)
4200 len)))
4201 "AST node for E4X XML comment. Not currently used.")
4202
4203 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4204 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4205
4206 (defun js2-print-xml-comment (n i)
4207 (insert (js2-make-pad i)
4208 (js2-node-string n)))
4209
4210 ;;; Node utilities
4211
4212 (defsubst js2-node-line (n)
4213 "Fetch the source line number at the start of node N.
4214 This is O(n) in the length of the source buffer; use prudently."
4215 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4216
4217 (defsubst js2-block-node-kid (n i)
4218 "Return child I of node N, or nil if there aren't that many."
4219 (nth i (js2-block-node-kids n)))
4220
4221 (defsubst js2-block-node-first (n)
4222 "Return first child of block node N, or nil if there is none."
4223 (first (js2-block-node-kids n)))
4224
4225 (defun js2-node-root (n)
4226 "Return the root of the AST containing N.
4227 If N has no parent pointer, returns N."
4228 (let ((parent (js2-node-parent n)))
4229 (if parent
4230 (js2-node-root parent)
4231 n)))
4232
4233 (defun js2-node-position-in-parent (node &optional parent)
4234 "Return the position of NODE in parent's block-kids list.
4235 PARENT can be supplied if known. Positioned returned is zero-indexed.
4236 Returns 0 if NODE is not a child of a block statement, or if NODE
4237 is not a statement node."
4238 (let ((p (or parent (js2-node-parent node)))
4239 (i 0))
4240 (if (not (js2-block-node-p p))
4241 i
4242 (or (js2-position node (js2-block-node-kids p))
4243 0))))
4244
4245 (defsubst js2-node-short-name (n)
4246 "Return the short name of node N as a string, e.g. `js2-if-node'."
4247 (substring (symbol-name (aref n 0))
4248 (length "cl-struct-")))
4249
4250 (defsubst js2-node-child-list (node)
4251 "Return the child list for NODE, a lisp list of nodes.
4252 Works for block nodes, array nodes, obj literals, funarg lists,
4253 var decls and try nodes (for catch clauses). Note that you should call
4254 `js2-block-node-kids' on the function body for the body statements.
4255 Returns nil for zero-length child lists or unsupported nodes."
4256 (cond
4257 ((js2-function-node-p node)
4258 (js2-function-node-params node))
4259 ((js2-block-node-p node)
4260 (js2-block-node-kids node))
4261 ((js2-try-node-p node)
4262 (js2-try-node-catch-clauses node))
4263 ((js2-array-node-p node)
4264 (js2-array-node-elems node))
4265 ((js2-object-node-p node)
4266 (js2-object-node-elems node))
4267 ((js2-call-node-p node)
4268 (js2-call-node-args node))
4269 ((js2-new-node-p node)
4270 (js2-new-node-args node))
4271 ((js2-var-decl-node-p node)
4272 (js2-var-decl-node-kids node))
4273 (t
4274 nil)))
4275
4276 (defsubst js2-node-set-child-list (node kids)
4277 "Set the child list for NODE to KIDS."
4278 (cond
4279 ((js2-function-node-p node)
4280 (setf (js2-function-node-params node) kids))
4281 ((js2-block-node-p node)
4282 (setf (js2-block-node-kids node) kids))
4283 ((js2-try-node-p node)
4284 (setf (js2-try-node-catch-clauses node) kids))
4285 ((js2-array-node-p node)
4286 (setf (js2-array-node-elems node) kids))
4287 ((js2-object-node-p node)
4288 (setf (js2-object-node-elems node) kids))
4289 ((js2-call-node-p node)
4290 (setf (js2-call-node-args node) kids))
4291 ((js2-new-node-p node)
4292 (setf (js2-new-node-args node) kids))
4293 ((js2-var-decl-node-p node)
4294 (setf (js2-var-decl-node-kids node) kids))
4295 (t
4296 (error "Unsupported node type: %s" (js2-node-short-name node))))
4297 kids)
4298
4299 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4300 (defconst js2-paren-expr-nodes
4301 '(cl-struct-js2-array-comp-loop-node
4302 cl-struct-js2-array-comp-node
4303 cl-struct-js2-call-node
4304 cl-struct-js2-catch-node
4305 cl-struct-js2-do-node
4306 cl-struct-js2-elem-get-node
4307 cl-struct-js2-for-in-node
4308 cl-struct-js2-for-node
4309 cl-struct-js2-function-node
4310 cl-struct-js2-if-node
4311 cl-struct-js2-let-node
4312 cl-struct-js2-new-node
4313 cl-struct-js2-paren-node
4314 cl-struct-js2-switch-node
4315 cl-struct-js2-while-node
4316 cl-struct-js2-with-node
4317 cl-struct-js2-xml-dot-query-node)
4318 "Node types that can have a parenthesized child expression.
4319 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4320
4321 (defsubst js2-paren-expr-node-p (node)
4322 "Return t for nodes that typically have a parenthesized child expression.
4323 Useful for computing the indentation anchors for arg-lists and conditions.
4324 Note that it may return a false positive, for instance when NODE is
4325 a `js2-new-node' and there are no arguments or parentheses."
4326 (memq (aref node 0) js2-paren-expr-nodes))
4327
4328 ;; Fake polymorphism... yech.
4329 (defsubst js2-node-lp (node)
4330 "Return relative left-paren position for NODE, if applicable.
4331 For `js2-elem-get-node' structs, returns left-bracket position.
4332 Note that the position may be nil in the case of a parse error."
4333 (cond
4334 ((js2-elem-get-node-p node)
4335 (js2-elem-get-node-lb node))
4336 ((js2-loop-node-p node)
4337 (js2-loop-node-lp node))
4338 ((js2-function-node-p node)
4339 (js2-function-node-lp node))
4340 ((js2-if-node-p node)
4341 (js2-if-node-lp node))
4342 ((js2-new-node-p node)
4343 (js2-new-node-lp node))
4344 ((js2-call-node-p node)
4345 (js2-call-node-lp node))
4346 ((js2-paren-node-p node)
4347 (js2-node-pos node))
4348 ((js2-switch-node-p node)
4349 (js2-switch-node-lp node))
4350 ((js2-catch-node-p node)
4351 (js2-catch-node-lp node))
4352 ((js2-let-node-p node)
4353 (js2-let-node-lp node))
4354 ((js2-array-comp-node-p node)
4355 (js2-array-comp-node-lp node))
4356 ((js2-with-node-p node)
4357 (js2-with-node-lp node))
4358 ((js2-xml-dot-query-node-p node)
4359 (1+ (js2-infix-node-op-pos node)))
4360 (t
4361 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4362
4363 ;; Fake polymorphism... blech.
4364 (defsubst js2-node-rp (node)
4365 "Return relative right-paren position for NODE, if applicable.
4366 For `js2-elem-get-node' structs, returns right-bracket position.
4367 Note that the position may be nil in the case of a parse error."
4368 (cond
4369 ((js2-elem-get-node-p node)
4370 (js2-elem-get-node-lb node))
4371 ((js2-loop-node-p node)
4372 (js2-loop-node-rp node))
4373 ((js2-function-node-p node)
4374 (js2-function-node-rp node))
4375 ((js2-if-node-p node)
4376 (js2-if-node-rp node))
4377 ((js2-new-node-p node)
4378 (js2-new-node-rp node))
4379 ((js2-call-node-p node)
4380 (js2-call-node-rp node))
4381 ((js2-paren-node-p node)
4382 (+ (js2-node-pos node) (js2-node-len node)))
4383 ((js2-switch-node-p node)
4384 (js2-switch-node-rp node))
4385 ((js2-catch-node-p node)
4386 (js2-catch-node-rp node))
4387 ((js2-let-node-p node)
4388 (js2-let-node-rp node))
4389 ((js2-array-comp-node-p node)
4390 (js2-array-comp-node-rp node))
4391 ((js2-with-node-p node)
4392 (js2-with-node-rp node))
4393 ((js2-xml-dot-query-node-p node)
4394 (1+ (js2-xml-dot-query-node-rp node)))
4395 (t
4396 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4397
4398 (defsubst js2-node-first-child (node)
4399 "Returns the first element of `js2-node-child-list' for NODE."
4400 (car (js2-node-child-list node)))
4401
4402 (defsubst js2-node-last-child (node)
4403 "Returns the last element of `js2-node-last-child' for NODE."
4404 (car (last (js2-node-child-list node))))
4405
4406 (defun js2-node-prev-sibling (node)
4407 "Return the previous statement in parent.
4408 Works for parents supported by `js2-node-child-list'.
4409 Returns nil if NODE is not in the parent, or PARENT is
4410 not a supported node, or if NODE is the first child."
4411 (let* ((p (js2-node-parent node))
4412 (kids (js2-node-child-list p))
4413 (sib (car kids)))
4414 (while (and kids
4415 (not (eq node (cadr kids))))
4416 (setq kids (cdr kids)
4417 sib (car kids)))
4418 sib))
4419
4420 (defun js2-node-next-sibling (node)
4421 "Return the next statement in parent block.
4422 Returns nil if NODE is not in the block, or PARENT is not
4423 a block node, or if NODE is the last statement."
4424 (let* ((p (js2-node-parent node))
4425 (kids (js2-node-child-list p)))
4426 (while (and kids
4427 (not (eq node (car kids))))
4428 (setq kids (cdr kids)))
4429 (cadr kids)))
4430
4431 (defun js2-node-find-child-before (pos parent &optional after)
4432 "Find the last child that starts before POS in parent.
4433 If AFTER is non-nil, returns first child starting after POS.
4434 POS is an absolute buffer position. PARENT is any node
4435 supported by `js2-node-child-list'.
4436 Returns nil if no applicable child is found."
4437 (let ((kids (if (js2-function-node-p parent)
4438 (js2-block-node-kids (js2-function-node-body parent))
4439 (js2-node-child-list parent)))
4440 (beg (if (js2-function-node-p parent)
4441 (js2-node-abs-pos (js2-function-node-body parent))
4442 (js2-node-abs-pos parent)))
4443 kid
4444 result
4445 fn
4446 (continue t))
4447 (setq fn (if after '> '<))
4448 (while (and kids continue)
4449 (setq kid (car kids))
4450 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4451 (setq result kid
4452 continue (if after nil t))
4453 (setq continue (if after t nil)))
4454 (setq kids (cdr kids)))
4455 result))
4456
4457 (defun js2-node-find-child-after (pos parent)
4458 "Find first child that starts after POS in parent.
4459 POS is an absolute buffer position. PARENT is any node
4460 supported by `js2-node-child-list'.
4461 Returns nil if no applicable child is found."
4462 (js2-node-find-child-before pos parent 'after))
4463
4464 (defun js2-node-replace-child (pos parent new-node)
4465 "Replace node at index POS in PARENT with NEW-NODE.
4466 Only works for parents supported by `js2-node-child-list'."
4467 (let ((kids (js2-node-child-list parent))
4468 (i 0))
4469 (while (< i pos)
4470 (setq kids (cdr kids)
4471 i (1+ i)))
4472 (setcar kids new-node)
4473 (js2-node-add-children parent new-node)))
4474
4475 (defun js2-node-buffer (n)
4476 "Return the buffer associated with AST N.
4477 Returns nil if the buffer is not set as a property on the root
4478 node, or if parent links were not recorded during parsing."
4479 (let ((root (js2-node-root n)))
4480 (and root
4481 (js2-ast-root-p root)
4482 (js2-ast-root-buffer root))))
4483
4484 (defsubst js2-block-node-push (n kid)
4485 "Push js2-node KID onto the end of js2-block-node N's child list.
4486 KID is always added to the -end- of the kids list.
4487 Function also calls `js2-node-add-children' to add the parent link."
4488 (let ((kids (js2-node-child-list n)))
4489 (if kids
4490 (setcdr kids (nconc (cdr kids) (list kid)))
4491 (js2-node-set-child-list n (list kid)))
4492 (js2-node-add-children n kid)))
4493
4494 (defun js2-node-string (node)
4495 (let ((buf (js2-node-buffer node))
4496 pos)
4497 (unless buf
4498 (error "No buffer available for node %s" node))
4499 (save-excursion
4500 (set-buffer buf)
4501 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4502 (+ pos (js2-node-len node))))))
4503
4504 ;; Container for storing the node we're looking for in a traversal.
4505 (js2-deflocal js2-discovered-node nil)
4506
4507 ;; Keep track of absolute node position during traversals.
4508 (js2-deflocal js2-visitor-offset nil)
4509
4510 (js2-deflocal js2-node-search-point nil)
4511
4512 (when js2-mode-dev-mode-p
4513 (defun js2-find-node-at-point ()
4514 (interactive)
4515 (let ((node (js2-node-at-point)))
4516 (message "%s" (or node "No node found at point"))))
4517 (defun js2-node-name-at-point ()
4518 (interactive)
4519 (let ((node (js2-node-at-point)))
4520 (message "%s" (if node
4521 (js2-node-short-name node)
4522 "No node found at point.")))))
4523
4524 (defun js2-node-at-point (&optional pos skip-comments)
4525 "Return AST node at POS, a buffer position, defaulting to current point.
4526 The `js2-mode-ast' variable must be set to the current parse tree.
4527 Signals an error if the AST (`js2-mode-ast') is nil.
4528 Always returns a node - if it can't find one, it returns the root.
4529 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4530 (let ((ast js2-mode-ast)
4531 result)
4532 (unless ast
4533 (error "No JavaScript AST available"))
4534 ;; Look through comments first, since they may be inside nodes that
4535 ;; would otherwise report a match.
4536 (setq pos (or pos (point))
4537 result (if (> pos (js2-node-abs-end ast))
4538 ast
4539 (if (not skip-comments)
4540 (js2-comment-at-point pos))))
4541 (unless result
4542 (setq js2-discovered-node nil
4543 js2-visitor-offset 0
4544 js2-node-search-point pos)
4545 (unwind-protect
4546 (catch 'js2-visit-done
4547 (js2-visit-ast ast #'js2-node-at-point-visitor))
4548 (setq js2-visitor-offset nil
4549 js2-node-search-point nil))
4550 (setq result js2-discovered-node))
4551 ;; may have found a comment beyond end of last child node,
4552 ;; since visiting the ast-root looks at the comment-list last.
4553 (if (and skip-comments
4554 (js2-comment-node-p result))
4555 (setq result nil))
4556 (or result js2-mode-ast)))
4557
4558 (defun js2-node-at-point-visitor (node end-p)
4559 (let ((rel-pos (js2-node-pos node))
4560 abs-pos
4561 abs-end
4562 (point js2-node-search-point))
4563 (cond
4564 (end-p
4565 ;; this evaluates to a non-nil return value, even if it's zero
4566 (decf js2-visitor-offset rel-pos))
4567 ;; we already looked for comments before visiting, and don't want them now
4568 ((js2-comment-node-p node)
4569 nil)
4570 (t
4571 (setq abs-pos (incf js2-visitor-offset rel-pos)
4572 ;; we only want to use the node if the point is before
4573 ;; the last character position in the node, so we decrement
4574 ;; the absolute end by 1.
4575 abs-end (+ abs-pos (js2-node-len node) -1))
4576 (cond
4577 ;; If this node starts after search-point, stop the search.
4578 ((> abs-pos point)
4579 (throw 'js2-visit-done nil))
4580 ;; If this node ends before the search-point, don't check kids.
4581 ((> point abs-end)
4582 nil)
4583 (t
4584 ;; Otherwise point is within this node, possibly in a child.
4585 (setq js2-discovered-node node)
4586 t)))))) ; keep processing kids to look for more specific match
4587
4588 (defsubst js2-block-comment-p (node)
4589 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4590 (and (js2-comment-node-p node)
4591 (memq (js2-comment-node-format node) '(jsdoc block))))
4592
4593 ;; TODO: put the comments in a vector and binary-search them instead
4594 (defun js2-comment-at-point (&optional pos)
4595 "Look through scanned comment nodes for one containing POS.
4596 POS is a buffer position that defaults to current point.
4597 Function returns nil if POS was not in any comment node."
4598 (let ((ast js2-mode-ast)
4599 (x (or pos (point)))
4600 beg
4601 end)
4602 (unless ast
4603 (error "No JavaScript AST available"))
4604 (catch 'done
4605 ;; Comments are stored in lexical order.
4606 (dolist (comment (js2-ast-root-comments ast) nil)
4607 (setq beg (js2-node-abs-pos comment)
4608 end (+ beg (js2-node-len comment)))
4609 (if (and (>= x beg)
4610 (<= x end))
4611 (throw 'done comment))))))
4612
4613 (defun js2-mode-find-parent-fn (node)
4614 "Find function enclosing NODE.
4615 Returns nil if NODE is not inside a function."
4616 (setq node (js2-node-parent node))
4617 (while (and node (not (js2-function-node-p node)))
4618 (setq node (js2-node-parent node)))
4619 (and (js2-function-node-p node) node))
4620
4621 (defun js2-mode-find-enclosing-fn (node)
4622 "Find function or root enclosing NODE."
4623 (if (js2-ast-root-p node)
4624 node
4625 (setq node (js2-node-parent node))
4626 (while (not (or (js2-ast-root-p node)
4627 (js2-function-node-p node)))
4628 (setq node (js2-node-parent node)))
4629 node))
4630
4631 (defun js2-mode-find-enclosing-node (beg end)
4632 "Find script or function fully enclosing BEG and END."
4633 (let ((node (js2-node-at-point beg))
4634 pos
4635 (continue t))
4636 (while continue
4637 (if (or (js2-ast-root-p node)
4638 (and (js2-function-node-p node)
4639 (<= (setq pos (js2-node-abs-pos node)) beg)
4640 (>= (+ pos (js2-node-len node)) end)))
4641 (setq continue nil)
4642 (setq node (js2-node-parent node))))
4643 node))
4644
4645 (defun js2-node-parent-script-or-fn (node)
4646 "Find script or function immediately enclosing NODE.
4647 If NODE is the ast-root, returns nil."
4648 (if (js2-ast-root-p node)
4649 nil
4650 (setq node (js2-node-parent node))
4651 (while (and node (not (or (js2-function-node-p node)
4652 (js2-script-node-p node))))
4653 (setq node (js2-node-parent node)))
4654 node))
4655
4656 (defsubst js2-nested-function-p (node)
4657 "Return t if NODE is a nested function, or is inside a nested function."
4658 (unless (js2-ast-root-p node)
4659 (js2-function-node-p (if (js2-function-node-p node)
4660 (js2-node-parent-script-or-fn node)
4661 (js2-node-parent-script-or-fn
4662 (js2-node-parent-script-or-fn node))))))
4663
4664 (defsubst js2-function-param-node-p (node)
4665 "Return non-nil if NODE is a param node of a `js2-function-node'."
4666 (let ((parent (js2-node-parent node)))
4667 (and parent
4668 (js2-function-node-p parent)
4669 (memq node (js2-function-node-params parent)))))
4670
4671 (defsubst js2-mode-shift-kids (kids start offset)
4672 (dolist (kid kids)
4673 (if (> (js2-node-pos kid) start)
4674 (incf (js2-node-pos kid) offset))))
4675
4676 (defsubst js2-mode-shift-children (parent start offset)
4677 "Update start-positions of all children of PARENT beyond START."
4678 (let ((root (js2-node-root parent)))
4679 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4680 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4681
4682 (defsubst js2-node-is-descendant (node ancestor)
4683 "Return t if NODE is a descendant of ANCESTOR."
4684 (while (and node
4685 (not (eq node ancestor)))
4686 (setq node (js2-node-parent node)))
4687 node)
4688
4689 ;;; visitor infrastructure
4690
4691 (defun js2-visit-none (node callback)
4692 "Visitor for AST node that have no node children."
4693 nil)
4694
4695 (defun js2-print-none (node indent)
4696 "Visitor for AST node with no printed representation.")
4697
4698 (defun js2-print-body (node indent)
4699 "Print a statement, or a block without braces."
4700 (if (js2-block-node-p node)
4701 (dolist (kid (js2-block-node-kids node))
4702 (js2-print-ast kid indent))
4703 (js2-print-ast node indent)))
4704
4705 (defun js2-print-list (args &optional delimiter)
4706 (loop with len = (length args)
4707 for arg in args
4708 for count from 1
4709 do
4710 (js2-print-ast arg 0)
4711 (if (< count len)
4712 (insert (or delimiter ", ")))))
4713
4714 (defun js2-print-tree (ast)
4715 "Prints an AST to the current buffer.
4716 Makes `js2-ast-parent-nodes' available to the printer functions."
4717 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4718 (js2-print-ast ast)))
4719
4720 (defun js2-print-ast (node &optional indent)
4721 "Helper function for printing AST nodes.
4722 Requires `js2-ast-parent-nodes' to be non-nil.
4723 You should use `js2-print-tree' instead of this function."
4724 (let ((printer (get (aref node 0) 'js2-printer))
4725 (i (or indent 0))
4726 (pos (js2-node-abs-pos node)))
4727 ;; TODO: wedge comments in here somewhere
4728 (if printer
4729 (funcall printer node i))))
4730
4731 (defconst js2-side-effecting-tokens
4732 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4733 (dolist (tt (list js2-ASSIGN
4734 js2-ASSIGN_ADD
4735 js2-ASSIGN_BITAND
4736 js2-ASSIGN_BITOR
4737 js2-ASSIGN_BITXOR
4738 js2-ASSIGN_DIV
4739 js2-ASSIGN_LSH
4740 js2-ASSIGN_MOD
4741 js2-ASSIGN_MUL
4742 js2-ASSIGN_RSH
4743 js2-ASSIGN_SUB
4744 js2-ASSIGN_URSH
4745 js2-BLOCK
4746 js2-BREAK
4747 js2-CALL
4748 js2-CATCH
4749 js2-CATCH_SCOPE
4750 js2-CONST
4751 js2-CONTINUE
4752 js2-DEBUGGER
4753 js2-DEC
4754 js2-DELPROP
4755 js2-DEL_REF
4756 js2-DO
4757 js2-ELSE
4758 js2-EMPTY
4759 js2-ENTERWITH
4760 js2-EXPORT
4761 js2-EXPR_RESULT
4762 js2-FINALLY
4763 js2-FOR
4764 js2-FUNCTION
4765 js2-GOTO
4766 js2-IF
4767 js2-IFEQ
4768 js2-IFNE
4769 js2-IMPORT
4770 js2-INC
4771 js2-JSR
4772 js2-LABEL
4773 js2-LEAVEWITH
4774 js2-LET
4775 js2-LETEXPR
4776 js2-LOCAL_BLOCK
4777 js2-LOOP
4778 js2-NEW
4779 js2-REF_CALL
4780 js2-RETHROW
4781 js2-RETURN
4782 js2-RETURN_RESULT
4783 js2-SEMI
4784 js2-SETELEM
4785 js2-SETELEM_OP
4786 js2-SETNAME
4787 js2-SETPROP
4788 js2-SETPROP_OP
4789 js2-SETVAR
4790 js2-SET_REF
4791 js2-SET_REF_OP
4792 js2-SWITCH
4793 js2-TARGET
4794 js2-THROW
4795 js2-TRY
4796 js2-VAR
4797 js2-WHILE
4798 js2-WITH
4799 js2-WITHEXPR
4800 js2-YIELD))
4801 (aset tokens tt t))
4802 (if js2-instanceof-has-side-effects
4803 (aset tokens js2-INSTANCEOF t))
4804 tokens))
4805
4806 (defun js2-node-has-side-effects (node)
4807 "Return t if NODE has side effects."
4808 (when node ; makes it easier to handle malformed expressions
4809 (let ((tt (js2-node-type node)))
4810 (cond
4811 ;; This doubtless needs some work, since EXPR_VOID is used
4812 ;; in several ways in Rhino, and I may not have caught them all.
4813 ;; I'll wait for people to notice incorrect warnings.
4814 ((and (= tt js2-EXPR_VOID)
4815 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4816 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4817 ((= tt js2-COMMA)
4818 (js2-node-has-side-effects (js2-infix-node-right node)))
4819 ((or (= tt js2-AND)
4820 (= tt js2-OR))
4821 (or (js2-node-has-side-effects (js2-infix-node-right node))
4822 (js2-node-has-side-effects (js2-infix-node-left node))))
4823 ((= tt js2-HOOK)
4824 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4825 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4826 ((js2-paren-node-p node)
4827 (js2-node-has-side-effects (js2-paren-node-expr node)))
4828 ((= tt js2-ERROR) ; avoid cascaded error messages
4829 nil)
4830 (t
4831 (aref js2-side-effecting-tokens tt))))))
4832
4833 (defun js2-member-expr-leftmost-name (node)
4834 "For an expr such as foo.bar.baz, return leftmost node foo.
4835 NODE is any `js2-node' object. If it represents a member expression,
4836 which is any sequence of property gets, element-gets, function calls,
4837 or xml descendants/filter operators, then we look at the lexically
4838 leftmost (first) node in the chain. If it is a name-node we return it.
4839 Note that NODE can be a raw name-node and it will be returned as well.
4840 If NODE is not a name-node or member expression, or if it is a member
4841 expression whose leftmost target is not a name node, returns nil."
4842 (let ((continue t)
4843 result)
4844 (while (and continue (not result))
4845 (cond
4846 ((js2-name-node-p node)
4847 (setq result node))
4848 ((js2-prop-get-node-p node)
4849 (setq node (js2-prop-get-node-left node)))
4850 ;; TODO: handle call-nodes, xml-nodes, others?
4851 (t
4852 (setq continue nil))))
4853 result))
4854
4855 (defconst js2-stmt-node-types
4856 (list js2-BLOCK
4857 js2-BREAK
4858 js2-CONTINUE
4859 js2-DEFAULT ; e4x "default xml namespace" statement
4860 js2-DO
4861 js2-EXPR_RESULT
4862 js2-EXPR_VOID
4863 js2-FOR
4864 js2-IF
4865 js2-RETURN
4866 js2-SWITCH
4867 js2-THROW
4868 js2-TRY
4869 js2-WHILE
4870 js2-WITH)
4871 "Node types that only appear in statement contexts.
4872 The list does not include nodes that always appear as the child
4873 of another specific statement type, such as switch-cases,
4874 catch and finally blocks, and else-clauses. The list also excludes
4875 nodes like yield, let and var, which may appear in either expression
4876 or statement context, and in the latter context always have a
4877 `js2-expr-stmt-node' parent. Finally, the list does not include
4878 functions or scripts, which are treated separately from statements
4879 by the JavaScript parser and runtime.")
4880
4881 (defun js2-stmt-node-p (node)
4882 "Heuristic for figuring out if NODE is a statement.
4883 Some node types can appear in either an expression context or a
4884 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4885 For these node types in a statement context, the parent will be a
4886 `js2-expr-stmt-node'.
4887 Functions aren't included in the check."
4888 (memq (js2-node-type node) js2-stmt-node-types))
4889
4890 (defsubst js2-mode-find-first-stmt (node)
4891 "Search upward starting from NODE looking for a statement.
4892 For purposes of this function, a `js2-function-node' counts."
4893 (while (not (or (js2-stmt-node-p node)
4894 (js2-function-node-p node)))
4895 (setq node (js2-node-parent node)))
4896 node)
4897
4898 (defun js2-node-parent-stmt (node)
4899 "Return the node's first ancestor that is a statement.
4900 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4901 appearing in a statement context will have a parent that is a
4902 `js2-expr-stmt-node' that will be returned by this function."
4903 (let ((parent (js2-node-parent node)))
4904 (if (or (null parent)
4905 (js2-stmt-node-p parent)
4906 (and (js2-function-node-p parent)
4907 (not (eq (js2-function-node-form parent)
4908 'FUNCTION_EXPRESSION))))
4909 parent
4910 (js2-node-parent-stmt parent))))
4911
4912 ;; In the Mozilla Rhino sources, Roshan James writes:
4913 ;; Does consistent-return analysis on the function body when strict mode is
4914 ;; enabled.
4915 ;;
4916 ;; function (x) { return (x+1) }
4917 ;;
4918 ;; is ok, but
4919 ;;
4920 ;; function (x) { if (x < 0) return (x+1); }
4921 ;;
4922 ;; is not because the function can potentially return a value when the
4923 ;; condition is satisfied and if not, the function does not explicitly
4924 ;; return a value.
4925 ;;
4926 ;; This extends to checking mismatches such as "return" and "return <value>"
4927 ;; used in the same function. Warnings are not emitted if inconsistent
4928 ;; returns exist in code that can be statically shown to be unreachable.
4929 ;; Ex.
4930 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4931 ;;
4932 ;; emits no warning. However if the loop had a break statement, then a
4933 ;; warning would be emitted.
4934 ;;
4935 ;; The consistency analysis looks at control structures such as loops, ifs,
4936 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4937 ;; warns the user about an inconsistent set of termination possibilities.
4938 ;;
4939 ;; These flags enumerate the possible ways a statement/function can
4940 ;; terminate. These flags are used by endCheck() and by the Parser to
4941 ;; detect inconsistent return usage.
4942 ;;
4943 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4944 ;; able to execute (example: throw, continue)
4945 ;;
4946 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4947 ;; next one. Statement such as return dont. A compound statement may have
4948 ;; some branch that drops off control to the next statement.
4949 ;;
4950 ;; END_RETURNS indicates that the statement can return with no value.
4951 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4952 ;;
4953 ;; A compound statement such as
4954 ;; if (condition) {
4955 ;; return value;
4956 ;; }
4957 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4958
4959 (defconst js2-END_UNREACHED 0)
4960 (defconst js2-END_DROPS_OFF 1)
4961 (defconst js2-END_RETURNS 2)
4962 (defconst js2-END_RETURNS_VALUE 4)
4963 (defconst js2-END_YIELDS 8)
4964
4965 (defun js2-has-consistent-return-usage (node)
4966 "Check that every return usage in a function body is consistent.
4967 Returns t if the function satisfies strict mode requirement."
4968 (let ((n (js2-end-check node)))
4969 ;; either it doesn't return a value in any branch...
4970 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4971 ;; or it returns a value (or is unreached) at every branch
4972 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4973 js2-END_RETURNS
4974 js2-END_YIELDS)))))
4975
4976 (defun js2-end-check-if (node)
4977 "Returns in the then and else blocks must be consistent with each other.
4978 If there is no else block, then the return statement can fall through.
4979 Returns logical OR of END_* flags"
4980 (let ((th (js2-if-node-then-part node))
4981 (el (js2-if-node-else-part node)))
4982 (if (null th)
4983 js2-END_UNREACHED
4984 (logior (js2-end-check th) (if el
4985 (js2-end-check el)
4986 js2-END_DROPS_OFF)))))
4987
4988 (defun js2-end-check-switch (node)
4989 "Consistency of return statements is checked between the case statements.
4990 If there is no default, then the switch can fall through. If there is a
4991 default, we check to see if all code paths in the default return or if
4992 there is a code path that can fall through.
4993 Returns logical OR of END_* flags."
4994 (let ((rv js2-END_UNREACHED)
4995 default-case)
4996 ;; examine the cases
4997 (catch 'break
4998 (dolist (c (js2-switch-node-cases node))
4999 (if (js2-case-node-expr c)
5000 (js2-set-flag rv (js2-end-check-block c))
5001 (setq default-case c)
5002 (throw 'break nil))))
5003 ;; we don't care how the cases drop into each other
5004 (js2-clear-flag rv js2-END_DROPS_OFF)
5005 ;; examine the default
5006 (js2-set-flag rv (if default-case
5007 (js2-end-check default-case)
5008 js2-END_DROPS_OFF))
5009 rv))
5010
5011 (defun js2-end-check-try (node)
5012 "If the block has a finally, return consistency is checked in the
5013 finally block. If all code paths in the finally return, then the
5014 returns in the try-catch blocks don't matter. If there is a code path
5015 that does not return or if there is no finally block, the returns
5016 of the try and catch blocks are checked for mismatch.
5017 Returns logical OR of END_* flags."
5018 (let ((finally (js2-try-node-finally-block node))
5019 rv)
5020 ;; check the finally if it exists
5021 (setq rv (if finally
5022 (js2-end-check (js2-finally-node-body finally))
5023 js2-END_DROPS_OFF))
5024 ;; If the finally block always returns, then none of the returns
5025 ;; in the try or catch blocks matter.
5026 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5027 (js2-clear-flag rv js2-END_DROPS_OFF)
5028 ;; examine the try block
5029 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5030 ;; check each catch block
5031 (dolist (cb (js2-try-node-catch-clauses node))
5032 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5033 rv))
5034
5035 (defun js2-end-check-loop (node)
5036 "Return statement in the loop body must be consistent. The default
5037 assumption for any kind of a loop is that it will eventually terminate.
5038 The only exception is a loop with a constant true condition. Code that
5039 follows such a loop is examined only if one can statically determine
5040 that there is a break out of the loop.
5041
5042 for(... ; ... ; ...) {}
5043 for(... in ... ) {}
5044 while(...) { }
5045 do { } while(...)
5046
5047 Returns logical OR of END_* flags."
5048 (let ((rv (js2-end-check (js2-loop-node-body node)))
5049 (condition (cond
5050 ((js2-while-node-p node)
5051 (js2-while-node-condition node))
5052 ((js2-do-node-p node)
5053 (js2-do-node-condition node))
5054 ((js2-for-node-p node)
5055 (js2-for-node-condition node)))))
5056
5057 ;; check to see if the loop condition is always true
5058 (if (and condition
5059 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5060 (js2-clear-flag rv js2-END_DROPS_OFF))
5061
5062 ;; look for effect of breaks
5063 (js2-set-flag rv (js2-node-get-prop node
5064 'CONTROL_BLOCK_PROP
5065 js2-END_UNREACHED))
5066 rv))
5067
5068 (defun js2-end-check-block (node)
5069 "A general block of code is examined statement by statement.
5070 If any statement (even a compound one) returns in all branches, then
5071 subsequent statements are not examined.
5072 Returns logical OR of END_* flags."
5073 (let* ((rv js2-END_DROPS_OFF)
5074 (kids (js2-block-node-kids node))
5075 (n (car kids)))
5076 ;; Check each statment. If the statement can continue onto the next
5077 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5078 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5079 (js2-clear-flag rv js2-END_DROPS_OFF)
5080 (js2-set-flag rv (js2-end-check n))
5081 (setq kids (cdr kids)
5082 n (car kids)))
5083 rv))
5084
5085 (defun js2-end-check-label (node)
5086 "A labeled statement implies that there may be a break to the label.
5087 The function processes the labeled statement and then checks the
5088 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5089 particular label.
5090 Returns logical OR of END_* flags."
5091 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5092 (logior rv (js2-node-get-prop node
5093 'CONTROL_BLOCK_PROP
5094 js2-END_UNREACHED))))
5095
5096 (defun js2-end-check-break (node)
5097 "When a break is encountered annotate the statement being broken
5098 out of by setting its CONTROL_BLOCK_PROP property.
5099 Returns logical OR of END_* flags."
5100 (and (js2-break-node-target node)
5101 (js2-node-set-prop (js2-break-node-target node)
5102 'CONTROL_BLOCK_PROP
5103 js2-END_DROPS_OFF))
5104 js2-END_UNREACHED)
5105
5106 (defun js2-end-check (node)
5107 "Examine the body of a function, doing a basic reachability analysis.
5108 Returns a combination of flags END_* flags that indicate
5109 how the function execution can terminate. These constitute only the
5110 pessimistic set of termination conditions. It is possible that at
5111 runtime certain code paths will never be actually taken. Hence this
5112 analysis will flag errors in cases where there may not be errors.
5113 Returns logical OR of END_* flags"
5114 (let (kid)
5115 (cond
5116 ((js2-break-node-p node)
5117 (js2-end-check-break node))
5118 ((js2-expr-stmt-node-p node)
5119 (if (setq kid (js2-expr-stmt-node-expr node))
5120 (js2-end-check kid)
5121 js2-END_DROPS_OFF))
5122 ((or (js2-continue-node-p node)
5123 (js2-throw-node-p node))
5124 js2-END_UNREACHED)
5125 ((js2-return-node-p node)
5126 (if (setq kid (js2-return-node-retval node))
5127 js2-END_RETURNS_VALUE
5128 js2-END_RETURNS))
5129 ((js2-loop-node-p node)
5130 (js2-end-check-loop node))
5131 ((js2-switch-node-p node)
5132 (js2-end-check-switch node))
5133 ((js2-labeled-stmt-node-p node)
5134 (js2-end-check-label node))
5135 ((js2-if-node-p node)
5136 (js2-end-check-if node))
5137 ((js2-try-node-p node)
5138 (js2-end-check-try node))
5139 ((js2-block-node-p node)
5140 (if (null (js2-block-node-kids node))
5141 js2-END_DROPS_OFF
5142 (js2-end-check-block node)))
5143 ((js2-yield-node-p node)
5144 js2-END_YIELDS)
5145 (t
5146 js2-END_DROPS_OFF))))
5147
5148 (defun js2-always-defined-boolean-p (node)
5149 "Check if NODE always evaluates to true or false in boolean context.
5150 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5151 nor always false."
5152 (let ((tt (js2-node-type node))
5153 num)
5154 (cond
5155 ((or (= tt js2-FALSE) (= tt js2-NULL))
5156 'ALWAYS_FALSE)
5157 ((= tt js2-TRUE)
5158 'ALWAYS_TRUE)
5159 ((= tt js2-NUMBER)
5160 (setq num (js2-number-node-num-value node))
5161 (if (and (not (eq num 0.0e+NaN))
5162 (not (zerop num)))
5163 'ALWAYS_TRUE
5164 'ALWAYS_FALSE))
5165 (t
5166 nil))))
5167
5168 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5169 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5170
5171 (defvar js2-tokens nil
5172 "List of all defined token names.") ; initialized in `js2-token-names'
5173
5174 (defconst js2-token-names
5175 (let* ((names (make-vector js2-num-tokens -1))
5176 (case-fold-search nil) ; only match js2-UPPER_CASE
5177 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5178 (loop for sym in syms
5179 for i from 0
5180 do
5181 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5182 (not (boundp sym)))
5183 (aset names (symbol-value sym) ; code, e.g. 152
5184 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5185 (push sym js2-tokens)))
5186 names)
5187 "Vector mapping int values to token string names, sans `js2-' prefix.")
5188
5189 (defun js2-token-name (tok)
5190 "Return a string name for TOK, a token symbol or code.
5191 Signals an error if it's not a recognized token."
5192 (let ((code tok))
5193 (if (symbolp tok)
5194 (setq code (symbol-value tok)))
5195 (if (eq code -1)
5196 "ERROR"
5197 (if (and (numberp code)
5198 (not (minusp code))
5199 (< code js2-num-tokens))
5200 (aref js2-token-names code)
5201 (error "Invalid token: %s" code)))))
5202
5203 (defsubst js2-token-sym (tok)
5204 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5205 (intern (js2-token-name tok)))
5206
5207 (defconst js2-token-codes
5208 (let ((table (make-hash-table :test 'eq :size 256)))
5209 (loop for name across js2-token-names
5210 for sym = (intern (concat "js2-" name))
5211 do
5212 (puthash sym (symbol-value sym) table))
5213 ;; clean up a few that are "wrong" in Rhino's token codes
5214 (puthash 'js2-DELETE js2-DELPROP table)
5215 table)
5216 "Hashtable mapping token symbols to their bytecodes.")
5217
5218 (defsubst js2-token-code (sym)
5219 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5220 (or (gethash sym js2-token-codes)
5221 (error "Invalid token symbol: %s " sym))) ; signal code bug
5222
5223 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5224 (setq js2-token-end js2-ts-cursor)
5225 (js2-report-error msg nil
5226 (or beg js2-token-beg)
5227 (or len (- js2-token-end js2-token-beg)))
5228 (unless no-throw
5229 (throw 'return js2-ERROR)))
5230
5231 (defsubst js2-get-string-from-buffer ()
5232 "Reverse the char accumulator and return it as a string."
5233 (setq js2-token-end js2-ts-cursor)
5234 (if js2-ts-string-buffer
5235 (apply #'string (nreverse js2-ts-string-buffer))
5236 ""))
5237
5238 ;; TODO: could potentially avoid a lot of consing by allocating a
5239 ;; char buffer the way Rhino does.
5240 (defsubst js2-add-to-string (c)
5241 (push c js2-ts-string-buffer))
5242
5243 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5244 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5245 ;; any other character: when it's not part of the current token, we
5246 ;; unget it, allowing it to be read again by the following call.
5247 (defsubst js2-unget-char ()
5248 (decf js2-ts-cursor))
5249
5250 ;; Rhino distinguishes \r and \n line endings. We don't need to
5251 ;; because we only scan from Emacs buffers, which always use \n.
5252 (defsubst js2-get-char ()
5253 "Read and return the next character from the input buffer.
5254 Increments `js2-ts-lineno' if the return value is a newline char.
5255 Updates `js2-ts-cursor' to the point after the returned char.
5256 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5257 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5258 (let (c)
5259 ;; check for end of buffer
5260 (if (>= js2-ts-cursor (point-max))
5261 (setq js2-ts-hit-eof t
5262 js2-ts-cursor (1+ js2-ts-cursor)
5263 c js2-EOF_CHAR) ; return value
5264 ;; otherwise read next char
5265 (setq c (char-before (incf js2-ts-cursor)))
5266 ;; if we read a newline, update counters
5267 (if (= c ?\n)
5268 (setq js2-ts-line-start js2-ts-cursor
5269 js2-ts-lineno (1+ js2-ts-lineno)))
5270 ;; TODO: skip over format characters
5271 c)))
5272
5273 (defsubst js2-read-unicode-escape ()
5274 "Read a \\uNNNN sequence from the input.
5275 Assumes the ?\ and ?u have already been read.
5276 Returns the unicode character, or nil if it wasn't a valid character.
5277 Doesn't change the values of any scanner variables."
5278 ;; I really wish I knew a better way to do this, but I can't
5279 ;; find the Emacs function that takes a 16-bit int and converts
5280 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5281 ;; Have to first check that it's 4 hex characters or it may stop
5282 ;; the read early.
5283 (ignore-errors
5284 (let ((s (buffer-substring-no-properties js2-ts-cursor
5285 (+ 4 js2-ts-cursor))))
5286 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5287 (read (concat "?\\u" s))))))
5288
5289 (defsubst js2-match-char (test)
5290 "Consume and return next character if it matches TEST, a character.
5291 Returns nil and consumes nothing if TEST is not the next character."
5292 (let ((c (js2-get-char)))
5293 (if (eq c test)
5294 t
5295 (js2-unget-char)
5296 nil)))
5297
5298 (defsubst js2-peek-char ()
5299 (prog1
5300 (js2-get-char)
5301 (js2-unget-char)))
5302
5303 (defsubst js2-java-identifier-start-p (c)
5304 (or
5305 (memq c '(?$ ?_))
5306 (js2-char-uppercase-p c)
5307 (js2-char-lowercase-p c)))
5308
5309 (defsubst js2-java-identifier-part-p (c)
5310 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5311 ;; TODO: make me Unicode-friendly. See comments above.
5312 (or
5313 (memq c '(?$ ?_))
5314 (js2-char-uppercase-p c)
5315 (js2-char-lowercase-p c)
5316 (and (>= c ?0) (<= c ?9))))
5317
5318 (defsubst js2-alpha-p (c)
5319 (cond ((and (<= ?A c) (<= c ?Z)) t)
5320 ((and (<= ?a c) (<= c ?z)) t)
5321 (t nil)))
5322
5323 (defsubst js2-digit-p (c)
5324 (and (<= ?0 c) (<= c ?9)))
5325
5326 (defsubst js2-js-space-p (c)
5327 (if (<= c 127)
5328 (memq c '(#x20 #x9 #xB #xC #xD))
5329 (or
5330 (eq c #xA0)
5331 ;; TODO: change this nil to check for Unicode space character
5332 nil)))
5333
5334 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5335
5336 (defsubst js2-skip-line ()
5337 "Skip to end of line"
5338 (let (c)
5339 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5340 (js2-unget-char)
5341 (setq js2-token-end js2-ts-cursor)))
5342
5343 (defun js2-init-scanner (&optional buf line)
5344 "Create token stream for BUF starting on LINE.
5345 BUF defaults to current-buffer and line defaults to 1.
5346
5347 A buffer can only have one scanner active at a time, which yields
5348 dramatically simpler code than using a defstruct. If you need to
5349 have simultaneous scanners in a buffer, copy the regions to scan
5350 into temp buffers."
5351 (save-excursion
5352 (when buf
5353 (set-buffer buf))
5354 (setq js2-ts-dirty-line nil
5355 js2-ts-regexp-flags nil
5356 js2-ts-string ""
5357 js2-ts-number nil
5358 js2-ts-hit-eof nil
5359 js2-ts-line-start 0
5360 js2-ts-lineno (or line 1)
5361 js2-ts-line-end-char -1
5362 js2-ts-cursor (point-min)
5363 js2-ts-is-xml-attribute nil
5364 js2-ts-xml-is-tag-content nil
5365 js2-ts-xml-open-tags-count 0
5366 js2-ts-string-buffer nil)))
5367
5368 ;; This function uses the cached op, string and number fields in
5369 ;; TokenStream; if getToken has been called since the passed token
5370 ;; was scanned, the op or string printed may be incorrect.
5371 (defun js2-token-to-string (token)
5372 ;; Not sure where this function is used in Rhino. Not tested.
5373 (if (not js2-debug-print-trees)
5374 ""
5375 (let ((name (js2-token-name token)))
5376 (cond
5377 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5378 (concat name " `" js2-ts-string "'"))
5379 ((eq token js2-NUMBER)
5380 (format "NUMBER %g" js2-ts-number))
5381 (t
5382 name)))))
5383
5384 (defconst js2-keywords
5385 '(break
5386 case catch const continue
5387 debugger default delete do
5388 else enum
5389 false finally for function
5390 if in instanceof import
5391 let
5392 new null
5393 return
5394 switch
5395 this throw true try typeof
5396 var void
5397 while with
5398 yield))
5399
5400 ;; Token names aren't exactly the same as the keywords, unfortunately.
5401 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5402 (defconst js2-kwd-tokens
5403 (let ((table (make-vector js2-num-tokens nil))
5404 (tokens
5405 (list js2-BREAK
5406 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5407 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5408 js2-ELSE
5409 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5410 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5411 js2-LET
5412 js2-NEW js2-NULL
5413 js2-RETURN
5414 js2-SWITCH
5415 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5416 js2-VAR
5417 js2-WHILE js2-WITH
5418 js2-YIELD)))
5419 (dolist (i tokens)
5420 (aset table i 'font-lock-keyword-face))
5421 (aset table js2-STRING 'font-lock-string-face)
5422 (aset table js2-REGEXP 'font-lock-string-face)
5423 (aset table js2-COMMENT 'font-lock-comment-face)
5424 (aset table js2-THIS 'font-lock-builtin-face)
5425 (aset table js2-VOID 'font-lock-constant-face)
5426 (aset table js2-NULL 'font-lock-constant-face)
5427 (aset table js2-TRUE 'font-lock-constant-face)
5428 (aset table js2-FALSE 'font-lock-constant-face)
5429 table)
5430 "Vector whose values are non-nil for tokens that are keywords.
5431 The values are default faces to use for highlighting the keywords.")
5432
5433 (defconst js2-reserved-words
5434 '(abstract
5435 boolean byte
5436 char class
5437 double
5438 enum export extends
5439 final float
5440 goto
5441 implements import int interface
5442 long
5443 native
5444 package private protected public
5445 short static super synchronized
5446 throws transient
5447 volatile))
5448
5449 (defconst js2-keyword-names
5450 (let ((table (make-hash-table :test 'equal)))
5451 (loop for k in js2-keywords
5452 do (puthash
5453 (symbol-name k) ; instanceof
5454 (intern (concat "js2-"
5455 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5456 table))
5457 table)
5458 "JavaScript keywords by name, mapped to their symbols.")
5459
5460 (defconst js2-reserved-word-names
5461 (let ((table (make-hash-table :test 'equal)))
5462 (loop for k in js2-reserved-words
5463 do
5464 (puthash (symbol-name k) 'js2-RESERVED table))
5465 table)
5466 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5467
5468 (defsubst js2-collect-string (buf)
5469 "Convert BUF, a list of chars, to a string.
5470 Reverses BUF before converting."
5471 (cond
5472 ((stringp buf)
5473 buf)
5474 ((null buf) ; for emacs21 compat
5475 "")
5476 (t
5477 (if buf
5478 (apply #'string (nreverse buf))
5479 ""))))
5480
5481 (defun js2-string-to-keyword (s)
5482 "Return token for S, a string, if S is a keyword or reserved word.
5483 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5484 (or (gethash s js2-keyword-names)
5485 (gethash s js2-reserved-word-names)))
5486
5487 (defsubst js2-ts-set-char-token-bounds ()
5488 "Used when next token is one character."
5489 (setq js2-token-beg (1- js2-ts-cursor)
5490 js2-token-end js2-ts-cursor))
5491
5492 (defsubst js2-ts-return (token)
5493 "Return an N-character TOKEN from `js2-get-token'.
5494 Updates `js2-token-end' accordingly."
5495 (setq js2-token-end js2-ts-cursor)
5496 (throw 'return token))
5497
5498 (defsubst js2-x-digit-to-int (c accumulator)
5499 "Build up a hex number.
5500 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5501 corresponding number. Otherwise return -1."
5502 (catch 'return
5503 (catch 'check
5504 ;; Use 0..9 < A..Z < a..z
5505 (cond
5506 ((<= c ?9)
5507 (decf c ?0)
5508 (if (<= 0 c)
5509 (throw 'check nil)))
5510 ((<= c ?F)
5511 (when (<= ?A c)
5512 (decf c (- ?A 10))
5513 (throw 'check nil)))
5514 ((<= c ?f)
5515 (when (<= ?a c)
5516 (decf c (- ?a 10))
5517 (throw 'check nil))))
5518 (throw 'return -1))
5519 (logior c (lsh accumulator 4))))
5520
5521 (defun js2-get-token ()
5522 "Return next JavaScript token, an int such as js2-RETURN."
5523 (let (c
5524 c1
5525 identifier-start
5526 is-unicode-escape-start
5527 contains-escape
5528 escape-val
5529 escape-start
5530 str
5531 result
5532 base
5533 is-integer
5534 quote-char
5535 val
5536 look-for-slash
5537 continue)
5538 (catch 'return
5539 (while t
5540 ;; Eat whitespace, possibly sensitive to newlines.
5541 (setq continue t)
5542 (while continue
5543 (setq c (js2-get-char))
5544 (cond
5545 ((eq c js2-EOF_CHAR)
5546 (js2-ts-set-char-token-bounds)
5547 (throw 'return js2-EOF))
5548 ((eq c ?\n)
5549 (js2-ts-set-char-token-bounds)
5550 (setq js2-ts-dirty-line nil)
5551 (throw 'return js2-EOL))
5552 ((not (js2-js-space-p c))
5553 (if (/= c ?-) ; in case end of HTML comment
5554 (setq js2-ts-dirty-line t))
5555 (setq continue nil))))
5556 ;; Assume the token will be 1 char - fixed up below.
5557 (js2-ts-set-char-token-bounds)
5558 (when (eq c ?@)
5559 (throw 'return js2-XMLATTR))
5560 ;; identifier/keyword/instanceof?
5561 ;; watch out for starting with a <backslash>
5562 (cond
5563 ((eq c ?\\)
5564 (setq c (js2-get-char))
5565 (if (eq c ?u)
5566 (setq identifier-start t
5567 is-unicode-escape-start t
5568 js2-ts-string-buffer nil)
5569 (setq identifier-start nil)
5570 (js2-unget-char)
5571 (setq c ?\\)))
5572 (t
5573 (when (setq identifier-start (js2-java-identifier-start-p c))
5574 (setq js2-ts-string-buffer nil)
5575 (js2-add-to-string c))))
5576 (when identifier-start
5577 (setq contains-escape is-unicode-escape-start)
5578 (catch 'break
5579 (while t
5580 (if is-unicode-escape-start
5581 ;; strictly speaking we should probably push-back
5582 ;; all the bad characters if the <backslash>uXXXX
5583 ;; sequence is malformed. But since there isn't a
5584 ;; correct context(is there?) for a bad Unicode
5585 ;; escape sequence in an identifier, we can report
5586 ;; an error here.
5587 (progn
5588 (setq escape-val 0)
5589 (dotimes (i 4)
5590 (setq c (js2-get-char)
5591 escape-val (js2-x-digit-to-int c escape-val))
5592 ;; Next check takes care of c < 0 and bad escape
5593 (if (minusp escape-val)
5594 (throw 'break nil)))
5595 (if (minusp escape-val)
5596 (js2-report-scan-error "msg.invalid.escape" t))
5597 (js2-add-to-string escape-val)
5598 (setq is-unicode-escape-start nil))
5599 (setq c (js2-get-char))
5600 (cond
5601 ((eq c ?\\)
5602 (setq c (js2-get-char))
5603 (if (eq c ?u)
5604 (setq is-unicode-escape-start t
5605 contains-escape t)
5606 (js2-report-scan-error "msg.illegal.character" t)))
5607 (t
5608 (if (or (eq c js2-EOF_CHAR)
5609 (not (js2-java-identifier-part-p c)))
5610 (throw 'break nil))
5611 (js2-add-to-string c))))))
5612 (js2-unget-char)
5613 (setq str (js2-get-string-from-buffer))
5614 (unless contains-escape
5615 ;; OPT we shouldn't have to make a string (object!) to
5616 ;; check if it's a keyword.
5617 ;; Return the corresponding token if it's a keyword
5618 (when (setq result (js2-string-to-keyword str))
5619 (if (and (< js2-language-version 170)
5620 (memq result '(js2-LET js2-YIELD)))
5621 ;; LET and YIELD are tokens only in 1.7 and later
5622 (setq result 'js2-NAME))
5623 (if (not (eq result 'js2-RESERVED))
5624 (throw 'return (js2-token-code result)))
5625 (js2-report-warning "msg.reserved.keyword" str)))
5626 ;; If we want to intern these as Rhino does, just use (intern str)
5627 (setq js2-ts-string str)
5628 (throw 'return js2-NAME)) ; end identifier/kwd check
5629 ;; is it a number?
5630 (when (or (js2-digit-p c)
5631 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5632 (setq js2-ts-string-buffer nil
5633 base 10)
5634 (when (eq c ?0)
5635 (setq c (js2-get-char))
5636 (cond
5637 ((or (eq c ?x) (eq c ?X))
5638 (setq base 16)
5639 (setq c (js2-get-char)))
5640 ((js2-digit-p c)
5641 (setq base 8))
5642 (t
5643 (js2-add-to-string ?0))))
5644 (if (eq base 16)
5645 (while (<= 0 (js2-x-digit-to-int c 0))
5646 (js2-add-to-string c)
5647 (setq c (js2-get-char)))
5648 (while (and (<= ?0 c) (<= c ?9))
5649 ;; We permit 08 and 09 as decimal numbers, which
5650 ;; makes our behavior a superset of the ECMA
5651 ;; numeric grammar. We might not always be so
5652 ;; permissive, so we warn about it.
5653 (when (and (eq base 8) (>= c ?8))
5654 (js2-report-warning "msg.bad.octal.literal"
5655 (if (eq c ?8) "8" "9"))
5656 (setq base 10))
5657 (js2-add-to-string c)
5658 (setq c (js2-get-char))))
5659 (setq is-integer t)
5660 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5661 (setq is-integer nil)
5662 (when (eq c ?.)
5663 (loop do
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))
5666 while (js2-digit-p c)))
5667 (when (memq c '(?e ?E))
5668 (js2-add-to-string c)
5669 (setq c (js2-get-char))
5670 (when (memq c '(?+ ?-))
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char)))
5673 (unless (js2-digit-p c)
5674 (js2-report-scan-error "msg.missing.exponent" t))
5675 (loop do
5676 (js2-add-to-string c)
5677 (setq c (js2-get-char))
5678 while (js2-digit-p c))))
5679 (js2-unget-char)
5680 (setq js2-ts-string (js2-get-string-from-buffer)
5681 js2-ts-number
5682 (if (and (eq base 10) (not is-integer))
5683 (string-to-number js2-ts-string)
5684 ;; TODO: call runtime number-parser. Some of it is in
5685 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5686 (string-to-number js2-ts-string)))
5687 (throw 'return js2-NUMBER))
5688 ;; is it a string?
5689 (when (memq c '(?\" ?\'))
5690 ;; We attempt to accumulate a string the fast way, by
5691 ;; building it directly out of the reader. But if there
5692 ;; are any escaped characters in the string, we revert to
5693 ;; building it out of a string buffer.
5694 (setq quote-char c
5695 js2-ts-string-buffer nil
5696 c (js2-get-char))
5697 (catch 'break
5698 (while (/= c quote-char)
5699 (catch 'continue
5700 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5701 (js2-unget-char)
5702 (setq js2-token-end js2-ts-cursor)
5703 (js2-report-error "msg.unterminated.string.lit")
5704 (throw 'return js2-STRING))
5705 (when (eq c ?\\)
5706 ;; We've hit an escaped character
5707 (setq c (js2-get-char))
5708 (case c
5709 (?b (setq c ?\b))
5710 (?f (setq c ?\f))
5711 (?n (setq c ?\n))
5712 (?r (setq c ?\r))
5713 (?t (setq c ?\t))
5714 (?v (setq c ?\v))
5715 (?u
5716 (setq c1 (js2-read-unicode-escape))
5717 (if js2-parse-ide-mode
5718 (if c1
5719 (progn
5720 ;; just copy the string in IDE-mode
5721 (js2-add-to-string ?\\)
5722 (js2-add-to-string ?u)
5723 (dotimes (i 3)
5724 (js2-add-to-string (js2-get-char)))
5725 (setq c (js2-get-char))) ; added at end of loop
5726 ;; flag it as an invalid escape
5727 (js2-report-warning "msg.invalid.escape"
5728 nil (- js2-ts-cursor 2) 6))
5729 ;; Get 4 hex digits; if the u escape is not
5730 ;; followed by 4 hex digits, use 'u' + the
5731 ;; literal character sequence that follows.
5732 (js2-add-to-string ?u)
5733 (setq escape-val 0)
5734 (dotimes (i 4)
5735 (setq c (js2-get-char)
5736 escape-val (js2-x-digit-to-int c escape-val))
5737 (if (minusp escape-val)
5738 (throw 'continue nil))
5739 (js2-add-to-string c))
5740 ;; prepare for replace of stored 'u' sequence by escape value
5741 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5742 c escape-val)))
5743 (?x
5744 ;; Get 2 hex digits, defaulting to 'x'+literal
5745 ;; sequence, as above.
5746 (setq c (js2-get-char)
5747 escape-val (js2-x-digit-to-int c 0))
5748 (if (minusp escape-val)
5749 (progn
5750 (js2-add-to-string ?x)
5751 (throw 'continue nil))
5752 (setq c1 c
5753 c (js2-get-char)
5754 escape-val (js2-x-digit-to-int c escape-val))
5755 (if (minusp escape-val)
5756 (progn
5757 (js2-add-to-string ?x)
5758 (js2-add-to-string c1)
5759 (throw 'continue nil))
5760 ;; got 2 hex digits
5761 (setq c escape-val))))
5762 (?\n
5763 ;; Remove line terminator after escape to follow
5764 ;; SpiderMonkey and C/C++
5765 (setq c (js2-get-char))
5766 (throw 'continue nil))
5767 (t
5768 (when (and (<= ?0 c) (< c ?8))
5769 (setq val (- c ?0)
5770 c (js2-get-char))
5771 (when (and (<= ?0 c) (< c ?8))
5772 (setq val (- (+ (* 8 val) c) ?0)
5773 c (js2-get-char))
5774 (when (and (<= ?0 c)
5775 (< c ?8)
5776 (< val #o37))
5777 ;; c is 3rd char of octal sequence only
5778 ;; if the resulting val <= 0377
5779 (setq val (- (+ (* 8 val) c) ?0)
5780 c (js2-get-char))))
5781 (js2-unget-char)
5782 (setq c val)))))
5783 (js2-add-to-string c)
5784 (setq c (js2-get-char)))))
5785 (setq js2-ts-string (js2-get-string-from-buffer))
5786 (throw 'return js2-STRING))
5787 (case c
5788 (?\;
5789 (throw 'return js2-SEMI))
5790 (?\[
5791 (throw 'return js2-LB))
5792 (?\]
5793 (throw 'return js2-RB))
5794 (?{
5795 (throw 'return js2-LC))
5796 (?}
5797 (throw 'return js2-RC))
5798 (?\(
5799 (throw 'return js2-LP))
5800 (?\)
5801 (throw 'return js2-RP))
5802 (?,
5803 (throw 'return js2-COMMA))
5804 (??
5805 (throw 'return js2-HOOK))
5806 (?:
5807 (if (js2-match-char ?:)
5808 (js2-ts-return js2-COLONCOLON)
5809 (throw 'return js2-COLON)))
5810 (?.
5811 (if (js2-match-char ?.)
5812 (js2-ts-return js2-DOTDOT)
5813 (if (js2-match-char ?\()
5814 (js2-ts-return js2-DOTQUERY)
5815 (throw 'return js2-DOT))))
5816 (?|
5817 (if (js2-match-char ?|)
5818 (throw 'return js2-OR)
5819 (if (js2-match-char ?=)
5820 (js2-ts-return js2-ASSIGN_BITOR)
5821 (throw 'return js2-BITOR))))
5822 (?^
5823 (if (js2-match-char ?=)
5824 (js2-ts-return js2-ASSIGN_BITOR)
5825 (throw 'return js2-BITXOR)))
5826 (?&
5827 (if (js2-match-char ?&)
5828 (throw 'return js2-AND)
5829 (if (js2-match-char ?=)
5830 (js2-ts-return js2-ASSIGN_BITAND)
5831 (throw 'return js2-BITAND))))
5832 (?=
5833 (if (js2-match-char ?=)
5834 (if (js2-match-char ?=)
5835 (js2-ts-return js2-SHEQ)
5836 (throw 'return js2-EQ))
5837 (throw 'return js2-ASSIGN)))
5838 (?!
5839 (if (js2-match-char ?=)
5840 (if (js2-match-char ?=)
5841 (js2-ts-return js2-SHNE)
5842 (js2-ts-return js2-NE))
5843 (throw 'return js2-NOT)))
5844 (?<
5845 ;; NB:treat HTML begin-comment as comment-till-eol
5846 (when (js2-match-char ?!)
5847 (when (js2-match-char ?-)
5848 (when (js2-match-char ?-)
5849 (js2-skip-line)
5850 (setq js2-ts-comment-type 'html)
5851 (throw 'return js2-COMMENT)))
5852 (js2-unget-char))
5853 (if (js2-match-char ?<)
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-ASSIGN_LSH)
5856 (js2-ts-return js2-LSH))
5857 (if (js2-match-char ?=)
5858 (js2-ts-return js2-LE)
5859 (throw 'return js2-LT))))
5860 (?>
5861 (if (js2-match-char ?>)
5862 (if (js2-match-char ?>)
5863 (if (js2-match-char ?=)
5864 (js2-ts-return js2-ASSIGN_URSH)
5865 (js2-ts-return js2-URSH))
5866 (if (js2-match-char ?=)
5867 (js2-ts-return js2-ASSIGN_RSH)
5868 (js2-ts-return js2-RSH)))
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-GE)
5871 (throw 'return js2-GT))))
5872 (?*
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_MUL)
5875 (throw 'return js2-MUL)))
5876 (?/
5877 ;; is it a // comment?
5878 (when (js2-match-char ?/)
5879 (setq js2-token-beg (- js2-ts-cursor 2))
5880 (js2-skip-line)
5881 (setq js2-ts-comment-type 'line)
5882 ;; include newline so highlighting goes to end of window
5883 (incf js2-token-end)
5884 (throw 'return js2-COMMENT))
5885 ;; is it a /* comment?
5886 (when (js2-match-char ?*)
5887 (setq look-for-slash nil
5888 js2-token-beg (- js2-ts-cursor 2)
5889 js2-ts-comment-type
5890 (if (js2-match-char ?*)
5891 (progn
5892 (setq look-for-slash t)
5893 'jsdoc)
5894 'block))
5895 (while t
5896 (setq c (js2-get-char))
5897 (cond
5898 ((eq c js2-EOF_CHAR)
5899 (setq js2-token-end (1- js2-ts-cursor))
5900 (js2-report-error "msg.unterminated.comment")
5901 (throw 'return js2-COMMENT))
5902 ((eq c ?*)
5903 (setq look-for-slash t))
5904 ((eq c ?/)
5905 (if look-for-slash
5906 (js2-ts-return js2-COMMENT)))
5907 (t
5908 (setq look-for-slash nil
5909 js2-token-end js2-ts-cursor)))))
5910 (if (js2-match-char ?=)
5911 (js2-ts-return js2-ASSIGN_DIV)
5912 (throw 'return js2-DIV)))
5913 (?#
5914 (when js2-skip-preprocessor-directives
5915 (js2-skip-line)
5916 (setq js2-ts-comment-type 'preprocessor
5917 js2-token-end js2-ts-cursor)
5918 (throw 'return js2-COMMENT))
5919 (throw 'return js2-ERROR))
5920 (?%
5921 (if (js2-match-char ?=)
5922 (js2-ts-return js2-ASSIGN_MOD)
5923 (throw 'return js2-MOD)))
5924 (?~
5925 (throw 'return js2-BITNOT))
5926 (?+
5927 (if (js2-match-char ?=)
5928 (js2-ts-return js2-ASSIGN_ADD)
5929 (if (js2-match-char ?+)
5930 (js2-ts-return js2-INC)
5931 (throw 'return js2-ADD))))
5932 (?-
5933 (cond
5934 ((js2-match-char ?=)
5935 (setq c js2-ASSIGN_SUB))
5936 ((js2-match-char ?-)
5937 (unless js2-ts-dirty-line
5938 ;; treat HTML end-comment after possible whitespace
5939 ;; after line start as comment-until-eol
5940 (when (js2-match-char ?>)
5941 (js2-skip-line)
5942 (setq js2-ts-comment-type 'html)
5943 (throw 'return js2-COMMENT)))
5944 (setq c js2-DEC))
5945 (t
5946 (setq c js2-SUB)))
5947 (setq js2-ts-dirty-line t)
5948 (js2-ts-return c))
5949 (otherwise
5950 (js2-report-scan-error "msg.illegal.character")))))))
5951
5952 (defun js2-read-regexp (start-token)
5953 "Called by parser when it gets / or /= in literal context."
5954 (let (c
5955 err
5956 in-class ; inside a '[' .. ']' character-class
5957 flags
5958 (continue t))
5959 (setq js2-token-beg js2-ts-cursor
5960 js2-ts-string-buffer nil
5961 js2-ts-regexp-flags nil)
5962 (if (eq start-token js2-ASSIGN_DIV)
5963 ;; mis-scanned /=
5964 (js2-add-to-string ?=)
5965 (if (not (eq start-token js2-DIV))
5966 (error "failed assertion")))
5967 (while (and (not err)
5968 (or (/= (setq c (js2-get-char)) ?/)
5969 in-class))
5970 (cond
5971 ((or (= c ?\n)
5972 (= c js2-EOF_CHAR))
5973 (setq js2-token-end (1- js2-ts-cursor)
5974 err t
5975 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5976 (js2-report-error "msg.unterminated.re.lit"))
5977 (t (cond
5978 ((= c ?\\)
5979 (js2-add-to-string c)
5980 (setq c (js2-get-char)))
5981 ((= c ?\[)
5982 (setq in-class t))
5983 ((= c ?\])
5984 (setq in-class nil)))
5985 (js2-add-to-string c))))
5986 (unless err
5987 (while continue
5988 (cond
5989 ((js2-match-char ?g)
5990 (push ?g flags))
5991 ((js2-match-char ?i)
5992 (push ?i flags))
5993 ((js2-match-char ?m)
5994 (push ?m flags))
5995 (t
5996 (setq continue nil))))
5997 (if (js2-alpha-p (js2-peek-char))
5998 (js2-report-scan-error "msg.invalid.re.flag" t
5999 js2-ts-cursor 1))
6000 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6001 js2-ts-regexp-flags (js2-collect-string flags)
6002 js2-token-end js2-ts-cursor)
6003 ;; tell `parse-partial-sexp' to ignore this range of chars
6004 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6005
6006 (defun js2-get-first-xml-token ()
6007 (setq js2-ts-xml-open-tags-count 0
6008 js2-ts-is-xml-attribute nil
6009 js2-ts-xml-is-tag-content nil)
6010 (js2-unget-char)
6011 (js2-get-next-xml-token))
6012
6013 (defsubst js2-xml-discard-string ()
6014 "Throw away the string in progress and flag an XML parse error."
6015 (setq js2-ts-string-buffer nil
6016 js2-ts-string nil)
6017 (js2-report-scan-error "msg.XML.bad.form" t))
6018
6019 (defun js2-get-next-xml-token ()
6020 (setq js2-ts-string-buffer nil ; for recording the XML
6021 js2-token-beg js2-ts-cursor)
6022 (let (c result)
6023 (setq result
6024 (catch 'return
6025 (while t
6026 (setq c (js2-get-char))
6027 (cond
6028 ((= c js2-EOF_CHAR)
6029 (throw 'return js2-ERROR))
6030 (js2-ts-xml-is-tag-content
6031 (case c
6032 (?>
6033 (js2-add-to-string c)
6034 (setq js2-ts-xml-is-tag-content nil
6035 js2-ts-is-xml-attribute nil))
6036 (?/
6037 (js2-add-to-string c)
6038 (when (eq ?> (js2-peek-char))
6039 (setq c (js2-get-char))
6040 (js2-add-to-string c)
6041 (setq js2-ts-xml-is-tag-content nil)
6042 (decf js2-ts-xml-open-tags-count)))
6043 (?{
6044 (js2-unget-char)
6045 (setq js2-ts-string (js2-get-string-from-buffer))
6046 (throw 'return js2-XML))
6047 ((?\' ?\")
6048 (js2-add-to-string c)
6049 (unless (js2-read-quoted-string c)
6050 (throw 'return js2-ERROR)))
6051 (?=
6052 (js2-add-to-string c)
6053 (setq js2-ts-is-xml-attribute t))
6054 ((? ?\t ?\r ?\n)
6055 (js2-add-to-string c))
6056 (t
6057 (js2-add-to-string c)
6058 (setq js2-ts-is-xml-attribute nil)))
6059 (when (and (not js2-ts-xml-is-tag-content)
6060 (zerop js2-ts-xml-open-tags-count))
6061 (setq js2-ts-string (js2-get-string-from-buffer))
6062 (throw 'return js2-XMLEND)))
6063 (t
6064 ;; else not tag content
6065 (case c
6066 (?<
6067 (js2-add-to-string c)
6068 (setq c (js2-peek-char))
6069 (case c
6070 (?!
6071 (setq c (js2-get-char)) ;; skip !
6072 (js2-add-to-string c)
6073 (setq c (js2-peek-char))
6074 (case c
6075 (?-
6076 (setq c (js2-get-char)) ;; skip -
6077 (js2-add-to-string c)
6078 (if (eq c ?-)
6079 (progn
6080 (js2-add-to-string c)
6081 (unless (js2-read-xml-comment)
6082 (throw 'return js2-ERROR)))
6083 (js2-xml-discard-string)
6084 (throw 'return js2-ERROR)))
6085 (?\[
6086 (setq c (js2-get-char)) ;; skip [
6087 (js2-add-to-string c)
6088 (if (and (= (js2-get-char) ?C)
6089 (= (js2-get-char) ?D)
6090 (= (js2-get-char) ?A)
6091 (= (js2-get-char) ?T)
6092 (= (js2-get-char) ?A)
6093 (= (js2-get-char) ?\[))
6094 (progn
6095 (js2-add-to-string ?C)
6096 (js2-add-to-string ?D)
6097 (js2-add-to-string ?A)
6098 (js2-add-to-string ?T)
6099 (js2-add-to-string ?A)
6100 (js2-add-to-string ?\[)
6101 (unless (js2-read-cdata)
6102 (throw 'return js2-ERROR)))
6103 (js2-xml-discard-string)
6104 (throw 'return js2-ERROR)))
6105 (t
6106 (unless (js2-read-entity)
6107 (throw 'return js2-ERROR))))
6108 ;; allow bare CDATA section
6109 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6110 (when (zerop js2-ts-xml-open-tags-count)
6111 (throw 'return js2-XMLEND)))
6112 (??
6113 (setq c (js2-get-char)) ;; skip ?
6114 (js2-add-to-string c)
6115 (unless (js2-read-PI)
6116 (throw 'return js2-ERROR)))
6117 (?/
6118 ;; end tag
6119 (setq c (js2-get-char)) ;; skip /
6120 (js2-add-to-string c)
6121 (when (zerop js2-ts-xml-open-tags-count)
6122 (js2-xml-discard-string)
6123 (throw 'return js2-ERROR))
6124 (setq js2-ts-xml-is-tag-content t)
6125 (decf js2-ts-xml-open-tags-count))
6126 (t
6127 ;; start tag
6128 (setq js2-ts-xml-is-tag-content t)
6129 (incf js2-ts-xml-open-tags-count))))
6130 (?{
6131 (js2-unget-char)
6132 (setq js2-ts-string (js2-get-string-from-buffer))
6133 (throw 'return js2-XML))
6134 (t
6135 (js2-add-to-string c))))))))
6136 (setq js2-token-end js2-ts-cursor)
6137 result))
6138
6139 (defun js2-read-quoted-string (quote)
6140 (let (c)
6141 (catch 'return
6142 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6143 (js2-add-to-string c)
6144 (if (eq c quote)
6145 (throw 'return t)))
6146 (js2-xml-discard-string) ;; throw away string in progress
6147 nil)))
6148
6149 (defun js2-read-xml-comment ()
6150 (let ((c (js2-get-char)))
6151 (catch 'return
6152 (while (/= c js2-EOF_CHAR)
6153 (catch 'continue
6154 (js2-add-to-string c)
6155 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6156 (setq c (js2-get-char))
6157 (js2-add-to-string c)
6158 (if (eq (js2-peek-char) ?>)
6159 (progn
6160 (setq c (js2-get-char)) ;; skip >
6161 (js2-add-to-string c)
6162 (throw 'return t))
6163 (throw 'continue nil)))
6164 (setq c (js2-get-char))))
6165 (js2-xml-discard-string)
6166 nil)))
6167
6168 (defun js2-read-cdata ()
6169 (let ((c (js2-get-char)))
6170 (catch 'return
6171 (while (/= c js2-EOF_CHAR)
6172 (catch 'continue
6173 (js2-add-to-string c)
6174 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6175 (setq c (js2-get-char))
6176 (js2-add-to-string c)
6177 (if (eq (js2-peek-char) ?>)
6178 (progn
6179 (setq c (js2-get-char)) ;; Skip >
6180 (js2-add-to-string c)
6181 (throw 'return t))
6182 (throw 'continue nil)))
6183 (setq c (js2-get-char))))
6184 (js2-xml-discard-string)
6185 nil)))
6186
6187 (defun js2-read-entity ()
6188 (let ((decl-tags 1)
6189 c)
6190 (catch 'return
6191 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6192 (js2-add-to-string c)
6193 (case c
6194 (?<
6195 (incf decl-tags))
6196 (?>
6197 (decf decl-tags)
6198 (if (zerop decl-tags)
6199 (throw 'return t)))))
6200 (js2-xml-discard-string)
6201 nil)))
6202
6203 (defun js2-read-PI ()
6204 "Scan an XML processing instruction."
6205 (let (c)
6206 (catch 'return
6207 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6208 (js2-add-to-string c)
6209 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6210 (setq c (js2-get-char)) ;; Skip >
6211 (js2-add-to-string c)
6212 (throw 'return t)))
6213 (js2-xml-discard-string)
6214 nil)))
6215
6216 (defun js2-scanner-get-line ()
6217 "Return the text of the current scan line."
6218 (buffer-substring (point-at-bol) (point-at-eol)))
6219
6220 ;;; Highlighting
6221
6222 (defsubst js2-set-face (beg end face &optional record)
6223 "Fontify a region. If RECORD is non-nil, record for later."
6224 (when (plusp js2-highlight-level)
6225 (setq beg (min (point-max) beg)
6226 beg (max (point-min) beg)
6227 end (min (point-max) end)
6228 end (max (point-min) end))
6229 (if record
6230 (push (list beg end face) js2-mode-fontifications)
6231 (put-text-property beg end 'face face))))
6232
6233 (defsubst js2-set-kid-face (pos kid len face)
6234 "Set-face on a child node.
6235 POS is absolute buffer position of parent.
6236 KID is the child node.
6237 LEN is the length to fontify.
6238 FACE is the face to fontify with."
6239 (js2-set-face (+ pos (js2-node-pos kid))
6240 (+ pos (js2-node-pos kid) (js2-node-len kid))
6241 face))
6242
6243 (defsubst js2-fontify-kwd (start length)
6244 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6245
6246 (defsubst js2-clear-face (beg end)
6247 (remove-text-properties beg end '(face nil
6248 help-echo nil
6249 point-entered nil
6250 c-in-sws nil)))
6251
6252 (defconst js2-ecma-global-props
6253 (concat "^"
6254 (regexp-opt
6255 '("Infinity" "NaN" "undefined" "arguments") t)
6256 "$")
6257 "Value properties of the Ecma-262 Global Object.
6258 Shown at or above `js2-highlight-level' 2.")
6259
6260 ;; might want to add the name "arguments" to this list?
6261 (defconst js2-ecma-object-props
6262 (concat "^"
6263 (regexp-opt
6264 '("prototype" "__proto__" "__parent__") t)
6265 "$")
6266 "Value properties of the Ecma-262 Object constructor.
6267 Shown at or above `js2-highlight-level' 2.")
6268
6269 (defconst js2-ecma-global-funcs
6270 (concat
6271 "^"
6272 (regexp-opt
6273 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6274 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6275 "$")
6276 "Function properties of the Ecma-262 Global object.
6277 Shown at or above `js2-highlight-level' 2.")
6278
6279 (defconst js2-ecma-number-props
6280 (concat "^"
6281 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6282 "NEGATIVE_INFINITY"
6283 "POSITIVE_INFINITY") t)
6284 "$")
6285 "Properties of the Ecma-262 Number constructor.
6286 Shown at or above `js2-highlight-level' 2.")
6287
6288 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6289 "Properties of the Ecma-262 Date constructor.
6290 Shown at or above `js2-highlight-level' 2.")
6291
6292 (defconst js2-ecma-math-props
6293 (concat "^"
6294 (regexp-opt
6295 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6296 t)
6297 "$")
6298 "Properties of the Ecma-262 Math object.
6299 Shown at or above `js2-highlight-level' 2.")
6300
6301 (defconst js2-ecma-math-funcs
6302 (concat "^"
6303 (regexp-opt
6304 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6305 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6306 "$")
6307 "Function properties of the Ecma-262 Math object.
6308 Shown at or above `js2-highlight-level' 2.")
6309
6310 (defconst js2-ecma-function-props
6311 (concat
6312 "^"
6313 (regexp-opt
6314 '(;; properties of the Object prototype object
6315 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6316 "toLocaleString" "toString" "valueOf"
6317 ;; properties of the Function prototype object
6318 "apply" "call"
6319 ;; properties of the Array prototype object
6320 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6321 "splice" "unshift"
6322 ;; properties of the String prototype object
6323 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6324 "localeCompare" "match" "replace" "search" "split" "substring"
6325 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6326 "toUpperCase"
6327 ;; properties of the Number prototype object
6328 "toExponential" "toFixed" "toPrecision"
6329 ;; properties of the Date prototype object
6330 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6331 "getMinutes" "getMonth" "getSeconds" "getTime"
6332 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6333 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6334 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6335 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6336 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6337 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6338 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6339 "toTimeString" "toUTCString"
6340 ;; properties of the RegExp prototype object
6341 "exec" "test"
6342 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6343 "toSource" "__defineGetter__" "__defineSetter__"
6344 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6345 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6346 t)
6347 "$")
6348 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6349 Shown at or above `js2-highlight-level' 3.")
6350
6351 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6352 (let ((target-name (and target
6353 (js2-name-node-p target)
6354 (js2-name-node-name target)))
6355 (prop-name (if prop (js2-name-node-name prop)))
6356 (level1 (>= js2-highlight-level 1))
6357 (level2 (>= js2-highlight-level 2))
6358 (level3 (>= js2-highlight-level 3))
6359 pos
6360 face)
6361 (when level2
6362 (if call-p
6363 (cond
6364 ((and target prop)
6365 (cond
6366 ((and level3 (string-match js2-ecma-function-props prop-name))
6367 (setq face 'font-lock-builtin-face))
6368 ((and target-name prop)
6369 (cond
6370 ((string= target-name "Date")
6371 (if (string-match js2-ecma-date-props prop-name)
6372 (setq face 'font-lock-builtin-face)))
6373 ((string= target-name "Math")
6374 (if (string-match js2-ecma-math-funcs prop-name)
6375 (setq face 'font-lock-builtin-face)))))))
6376 (prop
6377 (if (string-match js2-ecma-global-funcs prop-name)
6378 (setq face 'font-lock-builtin-face))))
6379 (cond
6380 ((and target prop)
6381 (cond
6382 ((string= target-name "Number")
6383 (if (string-match js2-ecma-number-props prop-name)
6384 (setq face 'font-lock-constant-face)))
6385 ((string= target-name "Math")
6386 (if (string-match js2-ecma-math-props prop-name)
6387 (setq face 'font-lock-constant-face)))))
6388 (prop
6389 (if (string-match js2-ecma-object-props prop-name)
6390 (setq face 'font-lock-constant-face)))))
6391 (when face
6392 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6393 (js2-node-pos prop))) ; relative
6394 (+ pos (js2-node-len prop))
6395 face)))))
6396
6397 (defun js2-parse-highlight-member-expr-node (node)
6398 "Perform syntax highlighting of EcmaScript built-in properties.
6399 The variable `js2-highlight-level' governs this highighting."
6400 (let (face target prop name pos end parent call-p callee)
6401 (cond
6402 ;; case 1: simple name, e.g. foo
6403 ((js2-name-node-p node)
6404 (setq name (js2-name-node-name node))
6405 ;; possible for name to be nil in rare cases - saw it when
6406 ;; running js2-mode on an elisp buffer. Might as well try to
6407 ;; make it so js2-mode never barfs.
6408 (when name
6409 (setq face (if (string-match js2-ecma-global-props name)
6410 'font-lock-constant-face))
6411 (when face
6412 (setq pos (js2-node-pos node)
6413 end (+ pos (js2-node-len node)))
6414 (js2-set-face pos end face))))
6415 ;; case 2: property access or function call
6416 ((or (js2-prop-get-node-p node)
6417 ;; highlight function call if expr is a prop-get node
6418 ;; or a plain name (i.e. unqualified function call)
6419 (and (setq call-p (js2-call-node-p node))
6420 (setq callee (js2-call-node-target node)) ; separate setq!
6421 (or (js2-prop-get-node-p callee)
6422 (js2-name-node-p callee))))
6423 (setq parent node
6424 node (if call-p callee node))
6425 (if (and call-p (js2-name-node-p callee))
6426 (setq prop callee)
6427 (setq target (js2-prop-get-node-left node)
6428 prop (js2-prop-get-node-right node)))
6429 (cond
6430 ((js2-name-node-p target)
6431 (if (js2-name-node-p prop)
6432 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6433 (js2-parse-highlight-prop-get parent target prop call-p)
6434 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6435 (js2-parse-highlight-prop-get parent target nil call-p)))
6436 ((js2-name-node-p prop)
6437 ;; case 2c: complex target, simple name, e.g. x[y].bar
6438 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6439
6440 (defun js2-parse-highlight-member-expr-fn-name (expr)
6441 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6442 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6443 We currently only handle the case where the last component is a prop-get
6444 of a simple name. Called before EXPR has a parent node."
6445 (let (pos
6446 (name (and (js2-prop-get-node-p expr)
6447 (js2-prop-get-node-right expr))))
6448 (when (js2-name-node-p name)
6449 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6450 (js2-node-pos name)))
6451 (+ pos (js2-node-len name))
6452 'font-lock-function-name-face
6453 'record))))
6454
6455 ;; source: http://jsdoc.sourceforge.net/
6456 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6457 ;; allows type specifications, and needs work before entering the wild.
6458
6459 (defconst js2-jsdoc-param-tag-regexp
6460 (concat "^\\s-*\\*+\\s-*\\(@"
6461 "\\(?:param\\|argument\\)"
6462 "\\)"
6463 "\\s-*\\({[^}]+}\\)?" ; optional type
6464 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6465 "\\>")
6466 "Matches jsdoc tags with optional type and optional param name.")
6467
6468 (defconst js2-jsdoc-typed-tag-regexp
6469 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6470 (regexp-opt
6471 '("enum"
6472 "extends"
6473 "field"
6474 "id"
6475 "implements"
6476 "lends"
6477 "mods"
6478 "requires"
6479 "return"
6480 "returns"
6481 "throw"
6482 "throws"))
6483 "\\)\\)\\s-*\\({[^}]+}\\)?")
6484 "Matches jsdoc tags with optional type.")
6485
6486 (defconst js2-jsdoc-arg-tag-regexp
6487 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6488 (regexp-opt
6489 '("alias"
6490 "augments"
6491 "borrows"
6492 "bug"
6493 "base"
6494 "config"
6495 "default"
6496 "define"
6497 "exception"
6498 "function"
6499 "member"
6500 "memberOf"
6501 "name"
6502 "namespace"
6503 "property"
6504 "since"
6505 "suppress"
6506 "this"
6507 "throws"
6508 "type"
6509 "version"))
6510 "\\)\\)\\s-+\\([^ \t]+\\)")
6511 "Matches jsdoc tags with a single argument.")
6512
6513 (defconst js2-jsdoc-empty-tag-regexp
6514 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6515 (regexp-opt
6516 '("addon"
6517 "author"
6518 "class"
6519 "const"
6520 "constant"
6521 "constructor"
6522 "constructs"
6523 "deprecated"
6524 "desc"
6525 "description"
6526 "event"
6527 "example"
6528 "exec"
6529 "export"
6530 "fileoverview"
6531 "final"
6532 "function"
6533 "hidden"
6534 "ignore"
6535 "implicitCast"
6536 "inheritDoc"
6537 "inner"
6538 "interface"
6539 "license"
6540 "noalias"
6541 "noshadow"
6542 "notypecheck"
6543 "override"
6544 "owner"
6545 "preserve"
6546 "preserveTry"
6547 "private"
6548 "protected"
6549 "public"
6550 "static"
6551 "supported"
6552 ))
6553 "\\)\\)\\s-*")
6554 "Matches empty jsdoc tags.")
6555
6556 (defconst js2-jsdoc-link-tag-regexp
6557 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6558 "Matches a jsdoc link or code tag.")
6559
6560 (defconst js2-jsdoc-see-tag-regexp
6561 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6562 "Matches a jsdoc @see tag.")
6563
6564 (defconst js2-jsdoc-html-tag-regexp
6565 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6566 "Matches a simple (no attributes) html start- or end-tag.")
6567
6568 (defsubst js2-jsdoc-highlight-helper ()
6569 (js2-set-face (match-beginning 1)
6570 (match-end 1)
6571 'js2-jsdoc-tag-face)
6572 (if (match-beginning 2)
6573 (if (save-excursion
6574 (goto-char (match-beginning 2))
6575 (= (char-after) ?{))
6576 (js2-set-face (1+ (match-beginning 2))
6577 (1- (match-end 2))
6578 'js2-jsdoc-type-face)
6579 (js2-set-face (match-beginning 2)
6580 (match-end 2)
6581 'js2-jsdoc-value-face)))
6582 (if (match-beginning 3)
6583 (js2-set-face (match-beginning 3)
6584 (match-end 3)
6585 'js2-jsdoc-value-face)))
6586
6587 (defun js2-highlight-jsdoc (ast)
6588 "Highlight doc comment tags."
6589 (let ((comments (js2-ast-root-comments ast))
6590 beg end)
6591 (save-excursion
6592 (dolist (node comments)
6593 (when (eq (js2-comment-node-format node) 'jsdoc)
6594 (setq beg (js2-node-abs-pos node)
6595 end (+ beg (js2-node-len node)))
6596 (save-restriction
6597 (narrow-to-region beg end)
6598 (dolist (re (list js2-jsdoc-param-tag-regexp
6599 js2-jsdoc-typed-tag-regexp
6600 js2-jsdoc-arg-tag-regexp
6601 js2-jsdoc-link-tag-regexp
6602 js2-jsdoc-see-tag-regexp
6603 js2-jsdoc-empty-tag-regexp))
6604 (goto-char beg)
6605 (while (re-search-forward re nil t)
6606 (js2-jsdoc-highlight-helper)))
6607 ;; simple highlighting for html tags
6608 (goto-char beg)
6609 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6610 (js2-set-face (match-beginning 1)
6611 (match-end 1)
6612 'js2-jsdoc-html-tag-delimiter-face)
6613 (js2-set-face (match-beginning 2)
6614 (match-end 2)
6615 'js2-jsdoc-html-tag-name-face)
6616 (js2-set-face (match-beginning 3)
6617 (match-end 3)
6618 'js2-jsdoc-html-tag-delimiter-face))))))))
6619
6620 (defun js2-highlight-assign-targets (node left right)
6621 "Highlight function properties and external variables."
6622 (let (leftpos end name)
6623 ;; highlight vars and props assigned function values
6624 (when (js2-function-node-p right)
6625 (cond
6626 ;; var foo = function() {...}
6627 ((js2-name-node-p left)
6628 (setq name left))
6629 ;; foo.bar.baz = function() {...}
6630 ((and (js2-prop-get-node-p left)
6631 (js2-name-node-p (js2-prop-get-node-right left)))
6632 (setq name (js2-prop-get-node-right left))))
6633 (when name
6634 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6635 (+ leftpos (js2-node-len name))
6636 'font-lock-function-name-face
6637 'record)))))
6638
6639 (defun js2-record-name-node (node)
6640 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6641 later. NODE must be a name node."
6642 (let (leftpos end)
6643 (push (list node js2-current-scope
6644 (setq leftpos (js2-node-abs-pos node))
6645 (setq end (+ leftpos (js2-node-len node))))
6646 js2-recorded-identifiers)))
6647
6648 (defun js2-highlight-undeclared-vars ()
6649 "After entire parse is finished, look for undeclared variable references.
6650 We have to wait until entire buffer is parsed, since JavaScript permits var
6651 decls to occur after they're used.
6652
6653 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6654 it is considered declared."
6655 (let (name)
6656 (dolist (entry js2-recorded-identifiers)
6657 (destructuring-bind (name-node scope pos end) entry
6658 (setq name (js2-name-node-name name-node))
6659 (unless (or (member name js2-global-externs)
6660 (member name js2-default-externs)
6661 (member name js2-additional-externs)
6662 (js2-get-defining-scope scope name))
6663 (js2-set-face pos end 'js2-external-variable-face 'record)
6664 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6665 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6666 (setq js2-recorded-identifiers nil)))
6667
6668 ;;; IMenu support
6669
6670 ;; We currently only support imenu, but eventually should support speedbar and
6671 ;; possibly other browsing mechanisms.
6672
6673 ;; The basic strategy is to identify function assignment targets of the form
6674 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6675 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6676 ;; for imenu after parsing is finished.
6677
6678 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6679 ;; JavaScript, and the general problem is undecidable. However, several forms
6680 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6681 ;; include:
6682
6683 ;; function foo() -- function declaration
6684 ;; foo = function() -- function expression assigned to variable
6685 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6686 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6687 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6688 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6689 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6690 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6691 ;; function foo() {function bar() {...}} -- nested function
6692 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6693
6694 ;; This list boils down to a few forms that can be combined recursively.
6695 ;; Top-level named function declarations include both the left-hand (name)
6696 ;; and the right-hand (function value) expressions needed to produce an imenu
6697 ;; entry. The other "right-hand" forms we need to look for are:
6698 ;; - functions declared as props/getters/setters in object literals
6699 ;; - nested named function declarations
6700 ;; The "left-hand" expressions that functions can be assigned to include:
6701 ;; - local/global variables
6702 ;; - nested property-get expressions like a.b.c.d
6703 ;; - element gets like foo[10] or foo['bar'] where the index
6704 ;; expression can be trivially converted to a property name. They
6705 ;; effectively then become property gets.
6706
6707 ;; All the different definition types are canonicalized into the form
6708 ;; foo.bar.baz = position-of-function-keyword
6709
6710 ;; We need to build a trie-like structure for imenu. As an example,
6711 ;; consider the following JavaScript code:
6712
6713 ;; a = function() {...} // function at position 5
6714 ;; b = function() {...} // function at position 25
6715 ;; foo = function() {...} // function at position 100
6716 ;; foo.bar = function() {...} // function at position 200
6717 ;; foo.bar.baz = function() {...} // function at position 300
6718 ;; foo.bar.zab = function() {...} // function at position 400
6719
6720 ;; During parsing we accumulate an entry for each definition in
6721 ;; the variable `js2-imenu-recorder', like so:
6722
6723 ;; '((a 5)
6724 ;; (b 25)
6725 ;; (foo 100)
6726 ;; (foo bar 200)
6727 ;; (foo bar baz 300)
6728 ;; (foo bar zab 400))
6729
6730 ;; After parsing these entries are merged into this alist-trie:
6731
6732 ;; '((a . 1)
6733 ;; (b . 2)
6734 ;; (foo (<definition> . 3)
6735 ;; (bar (<definition> . 6)
6736 ;; (baz . 100)
6737 ;; (zab . 200))))
6738
6739 ;; Note the wacky need for a <definition> name. The token can be anything
6740 ;; that isn't a valid JavaScript identifier, because you might make foo
6741 ;; a function and then start setting properties on it that are also functions.
6742
6743 (defsubst js2-prop-node-name (node)
6744 "Return the name of a node that may be a property-get/property-name.
6745 If NODE is not a valid name-node, string-node or integral number-node,
6746 returns nil. Otherwise returns the string name/value of the node."
6747 (cond
6748 ((js2-name-node-p node)
6749 (js2-name-node-name node))
6750 ((js2-string-node-p node)
6751 (js2-string-node-value node))
6752 ((and (js2-number-node-p node)
6753 (string-match "^[0-9]+$" (js2-number-node-value node)))
6754 (js2-number-node-value node))
6755 ((js2-this-node-p node)
6756 "this")))
6757
6758 (defsubst js2-node-qname-component (node)
6759 "Test function: return the name of this node, if it contributes to a qname.
6760 Returns nil if the node doesn't contribute."
6761 (copy-sequence
6762 (or (js2-prop-node-name node)
6763 (if (and (js2-function-node-p node)
6764 (js2-function-node-name node))
6765 (js2-name-node-name (js2-function-node-name node))))))
6766
6767 (defsubst js2-record-function-qname (fn-node qname)
6768 "Associate FN-NODE with its QNAME for later lookup.
6769 This is used in postprocessing the chain list. When we find a chain
6770 whose first element is a js2-THIS keyword node, we look up the parent
6771 function and see (using this map) whether it is the tail of a chain.
6772 If so, we replace the this-node with a copy of the parent's qname."
6773 (unless js2-imenu-function-map
6774 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6775 (puthash fn-node qname js2-imenu-function-map))
6776
6777 (defun js2-record-imenu-functions (node &optional var)
6778 "Record function definitions for imenu.
6779 NODE is a function node or an object literal.
6780 VAR, if non-nil, is the expression that NODE is being assigned to."
6781 (when js2-parse-ide-mode
6782 (let ((fun-p (js2-function-node-p node))
6783 qname left fname-node pos)
6784 (cond
6785 ;; non-anonymous function declaration?
6786 ((and fun-p
6787 (not var)
6788 (setq fname-node (js2-function-node-name node)))
6789 (push (setq qname (list fname-node (js2-node-pos node)))
6790 js2-imenu-recorder)
6791 (js2-record-function-qname node qname))
6792 ;; for remaining forms, compute left-side tree branch first
6793 ((and var (setq qname (js2-compute-nested-prop-get var)))
6794 (cond
6795 ;; foo.bar.baz = function
6796 (fun-p
6797 (push (nconc qname (list (js2-node-pos node)))
6798 js2-imenu-recorder)
6799 (js2-record-function-qname node qname))
6800 ;; foo.bar.baz = object-literal
6801 ;; look for nested functions: {a: {b: function() {...} }}
6802 ((js2-object-node-p node)
6803 ;; Node position here is still absolute, since the parser
6804 ;; passes the assignment target and value expressions
6805 ;; to us before they are added as children of the assignment node.
6806 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6807
6808 (defun js2-compute-nested-prop-get (node)
6809 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6810 component nodes as a list. Otherwise return nil. Element-gets are treated
6811 as property-gets if the index expression is a string, or a positive integer."
6812 (let (left right head)
6813 (cond
6814 ((or (js2-name-node-p node)
6815 (js2-this-node-p node))
6816 (list node))
6817 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6818 ((js2-prop-get-node-p node) ; foo.bar
6819 (setq left (js2-prop-get-node-left node)
6820 right (js2-prop-get-node-right node))
6821 (if (setq head (js2-compute-nested-prop-get left))
6822 (nconc head (list right))))
6823 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6824 (setq left (js2-elem-get-node-target node)
6825 right (js2-elem-get-node-element node))
6826 (if (or (js2-string-node-p right) ; ['bar']
6827 (and (js2-number-node-p right) ; [10]
6828 (string-match "^[0-9]+$"
6829 (js2-number-node-value right))))
6830 (if (setq head (js2-compute-nested-prop-get left))
6831 (nconc head (list right))))))))
6832
6833 (defun js2-record-object-literal (node qname pos)
6834 "Recursively process an object literal looking for functions.
6835 NODE is an object literal that is the right-hand child of an assignment
6836 expression. QNAME is a list of nodes representing the assignment target,
6837 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6838 POS is the absolute position of the node.
6839 We do a depth-first traversal of NODE. Any functions we find are prefixed
6840 with QNAME plus the property name of the function and appended to the
6841 variable `js2-imenu-recorder'."
6842 (let (left right)
6843 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6844 (let ((left (js2-infix-node-left e))
6845 ;; Element positions are relative to the parent position.
6846 (pos (+ pos (js2-node-pos e))))
6847 (cond
6848 ;; foo: function() {...}
6849 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6850 (when (js2-prop-node-name left)
6851 ;; As a policy decision, we record the position of the property,
6852 ;; not the position of the `function' keyword, since the property
6853 ;; is effectively the name of the function.
6854 (push (append qname (list left pos))
6855 js2-imenu-recorder)
6856 (js2-record-function-qname right qname)))
6857 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6858 ((js2-object-node-p right)
6859 (js2-record-object-literal right
6860 (append qname (list (js2-infix-node-left e)))
6861 (+ pos (js2-node-pos right)))))))))
6862
6863 (defsubst js2-node-top-level-decl-p (node)
6864 "Return t if NODE's name is defined in the top-level scope.
6865 Also returns t if NODE's name is not defined in any scope, since it implies
6866 that it's an external variable, which must also be in the top-level scope."
6867 (let* ((name (js2-prop-node-name node))
6868 (this-scope (js2-node-get-enclosing-scope node))
6869 defining-scope)
6870 (cond
6871 ((js2-this-node-p node)
6872 nil)
6873 ((null this-scope)
6874 t)
6875 ((setq defining-scope (js2-get-defining-scope this-scope name))
6876 (js2-ast-root-p defining-scope))
6877 (t t))))
6878
6879 (defsubst js2-wrapper-function-p (node)
6880 "Returns t if NODE is a function expression that's immediately invoked.
6881 NODE must be `js2-function-node'."
6882 (let ((parent (js2-node-parent node)))
6883 (or
6884 ;; function(){...}();
6885 (js2-call-node-p parent)
6886 (and (js2-paren-node-p parent)
6887 ;; (function(){...})();
6888 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6889 ;; (function(){...}).call(this);
6890 (and (js2-prop-get-node-p parent)
6891 (member (js2-name-node-name (js2-prop-get-node-right parent))
6892 '("call" "apply"))
6893 (js2-call-node-p (js2-node-parent parent))))))))
6894
6895 (defun js2-browse-postprocess-chains (chains)
6896 "Modify function-declaration name chains after parsing finishes.
6897 Some of the information is only available after the parse tree is complete.
6898 For instance, following a 'this' reference requires a parent function node."
6899 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6900 result head fn fn-type parent-chain p elem parent)
6901 (dolist (chain chains)
6902 ;; examine the head of each node to get its defining scope
6903 (setq head (car chain))
6904 ;; if top-level/external, keep as-is
6905 (if (js2-node-top-level-decl-p head)
6906 (push chain result)
6907 (cond
6908 ;; starts with this-reference
6909 ((js2-this-node-p head)
6910 (setq fn (js2-node-parent-script-or-fn head)
6911 chain (cdr chain))) ; discard this-node
6912 ;; nested named function
6913 ((js2-function-node-p (setq parent (js2-node-parent head)))
6914 (setq fn (js2-node-parent-script-or-fn parent)))
6915 ;; variable assigned a function expression
6916 (t (setq fn (js2-node-parent-script-or-fn head))))
6917 (when fn
6918 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6919 (unless fn-type
6920 (setq fn-type
6921 (cond ((js2-nested-function-p fn) 'skip)
6922 ((setq parent-chain
6923 (gethash fn js2-imenu-function-map))
6924 'named)
6925 ((js2-wrapper-function-p fn) 'anon)
6926 (t 'skip)))
6927 (puthash fn fn-type js2-imenu-fn-type-map))
6928 (case fn-type
6929 ('anon (push chain result)) ; anonymous top-level wrapper
6930 ('named ; top-level named function
6931 ;; prefix parent fn qname, which is
6932 ;; parent-chain sans last elem, to this chain.
6933 (push (append (butlast parent-chain) chain) result))))))
6934 ;; finally replace each node in each chain with its name.
6935 (dolist (chain result)
6936 (setq p chain)
6937 (while p
6938 (if (js2-node-p (setq elem (car p)))
6939 (setcar p (js2-node-qname-component elem)))
6940 (setq p (cdr p))))
6941 result))
6942
6943 ;; Merge name chains into a trie-like tree structure of nested lists.
6944 ;; To simplify construction of the trie, we first build it out using the rule
6945 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6946 ;; [key, num-or-list]. The second element can be a number; if so, this key
6947 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6948 ;; associated with the key at this level.) Otherwise the second element is
6949 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6950 ;; a simple recursive formulation.
6951 ;;
6952 ;; js2-mode is building the data structure for imenu. The imenu documentation
6953 ;; claims that it's the structure above, but in practice it wants the children
6954 ;; at the same list level as the key for that level, which is how I've drawn
6955 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6956 ;; list wrapper around the children at each level.
6957 ;;
6958 ;; A completed nested imenu-alist entry looks like this:
6959 ;; '(("foo"
6960 ;; ("<definition>" . 7)
6961 ;; ("bar"
6962 ;; ("a" . 40)
6963 ;; ("b" . 60))))
6964 ;;
6965 ;; In particular, the documentation for `imenu--index-alist' says that
6966 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6967 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6968
6969 (defsubst js2-treeify (lst)
6970 "Convert (a b c d) to (a ((b ((c d)))))"
6971 (if (null (cddr lst)) ; list length <= 2
6972 lst
6973 (list (car lst) (list (js2-treeify (cdr lst))))))
6974
6975 (defun js2-build-alist-trie (chains trie)
6976 "Merge declaration name chains into a trie-like alist structure for imenu.
6977 CHAINS is the qname chain list produced during parsing. TRIE is a
6978 list of elements built up so far."
6979 (let (head tail pos branch kids)
6980 (dolist (chain chains)
6981 (setq head (car chain)
6982 tail (cdr chain)
6983 pos (if (numberp (car tail)) (car tail))
6984 branch (js2-find-if (lambda (n)
6985 (string= (car n) head))
6986 trie)
6987 kids (second branch))
6988 (cond
6989 ;; case 1: this key isn't in the trie yet
6990 ((null branch)
6991 (if trie
6992 (setcdr (last trie) (list (js2-treeify chain)))
6993 (setq trie (list (js2-treeify chain)))))
6994 ;; case 2: key is present with a single number entry: replace w/ list
6995 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6996 ;; ("<definition>" 20)))
6997 ((numberp kids)
6998 (setcar (cdr branch)
6999 (list (list "<definition-1>" kids)
7000 (if pos
7001 (list "<definition-2>" pos)
7002 (js2-treeify tail)))))
7003 ;; case 3: key is there (with kids), and we're a number entry
7004 (pos
7005 (setcdr (last kids)
7006 (list
7007 (list (format "<definition-%d>"
7008 (1+ (loop for kid in kids
7009 count (eq ?< (aref (car kid) 0)))))
7010 pos))))
7011 ;; case 4: key is there with kids, need to merge in our chain
7012 (t
7013 (js2-build-alist-trie (list tail) kids))))
7014 trie))
7015
7016 (defun js2-flatten-trie (trie)
7017 "Convert TRIE to imenu-format.
7018 Recurses through nodes, and for each one whose second element is a list,
7019 appends the list's flattened elements to the current element. Also
7020 changes the tails into conses. For instance, this pre-flattened trie
7021
7022 '(a ((b 20)
7023 (c ((d 30)
7024 (e 40)))))
7025
7026 becomes
7027
7028 '(a (b . 20)
7029 (c (d . 30)
7030 (e . 40)))
7031
7032 Note that the root of the trie has no key, just a list of chains.
7033 This is also true for the value of any key with multiple children,
7034 e.g. key 'c' in the example above."
7035 (cond
7036 ((listp (car trie))
7037 (mapcar #'js2-flatten-trie trie))
7038 (t
7039 (if (numberp (second trie))
7040 (cons (car trie) (second trie))
7041 ;; else pop list and append its kids
7042 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7043
7044 (defun js2-build-imenu-index ()
7045 "Turn `js2-imenu-recorder' into an imenu data structure."
7046 (unless (eq js2-imenu-recorder 'empty)
7047 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7048 (result (js2-build-alist-trie chains nil)))
7049 (js2-flatten-trie result))))
7050
7051 (defun js2-test-print-chains (chains)
7052 "Print a list of qname chains.
7053 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7054 i.e. one or more nodes, and an integer position as the list tail."
7055 (mapconcat (lambda (chain)
7056 (concat "("
7057 (mapconcat (lambda (elem)
7058 (if (js2-node-p elem)
7059 (or (js2-node-qname-component elem)
7060 "nil")
7061 (number-to-string elem)))
7062 chain
7063 " ")
7064 ")"))
7065 chains
7066 "\n"))
7067
7068 ;;; Parser
7069
7070 (defconst js2-version "1.8.0"
7071 "Version of JavaScript supported, plus minor js2 version.")
7072
7073 (defmacro js2-record-face (face)
7074 "Record a style run of FACE for the current token."
7075 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7076
7077 (defsubst js2-node-end (n)
7078 "Computes the absolute end of node N.
7079 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7080 is only true until the node is added to its parent; i.e., while parsing."
7081 (+ (js2-node-pos n)
7082 (js2-node-len n)))
7083
7084 (defsubst js2-record-comment ()
7085 "Record a comment in `js2-scanned-comments'."
7086 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7087 :format js2-ts-comment-type)
7088 js2-scanned-comments)
7089 (when js2-parse-ide-mode
7090 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7091 'font-lock-doc-face
7092 'font-lock-comment-face))
7093 (when (memq js2-ts-comment-type '(html preprocessor))
7094 ;; Tell cc-engine the bounds of the comment.
7095 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7096
7097 ;; This function is called depressingly often, so it should be fast.
7098 ;; Most of the time it's looking at the same token it peeked before.
7099 (defsubst js2-peek-token ()
7100 "Returns the next token without consuming it.
7101 If previous token was consumed, calls scanner to get new token.
7102 If previous token was -not- consumed, returns it (idempotent).
7103
7104 This function will not return a newline (js2-EOL) - instead, it
7105 gobbles newlines until it finds a non-newline token, and flags
7106 that token as appearing just after a newline.
7107
7108 This function will also not return a js2-COMMENT. Instead, it
7109 records comments found in `js2-scanned-comments'. If the token
7110 returned by this function immediately follows a jsdoc comment,
7111 the token is flagged as such.
7112
7113 Note that this function always returned the un-flagged token!
7114 The flags, if any, are saved in `js2-current-flagged-token'."
7115 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7116 js2-current-token ; most common case - return already-peeked token
7117 (let ((tt (js2-get-token)) ; call scanner
7118 saw-eol
7119 face)
7120 ;; process comments and whitespace
7121 (while (or (= tt js2-EOL)
7122 (= tt js2-COMMENT))
7123 (if (= tt js2-EOL)
7124 (setq saw-eol t)
7125 (setq saw-eol nil)
7126 (if js2-record-comments
7127 (js2-record-comment)))
7128 (setq tt (js2-get-token))) ; call scanner
7129 (setq js2-current-token tt
7130 js2-current-flagged-token (if saw-eol
7131 (logior tt js2-ti-after-eol)
7132 tt))
7133 ;; perform lexical fontification as soon as token is scanned
7134 (when js2-parse-ide-mode
7135 (cond
7136 ((minusp tt)
7137 (js2-record-face 'js2-error-face))
7138 ((setq face (aref js2-kwd-tokens tt))
7139 (js2-record-face face))
7140 ((and (= tt js2-NAME)
7141 (equal js2-ts-string "undefined"))
7142 (js2-record-face 'font-lock-constant-face))))
7143 tt))) ; return unflagged token
7144
7145 (defsubst js2-peek-flagged-token ()
7146 "Returns the current token along with any flags set for it."
7147 (js2-peek-token)
7148 js2-current-flagged-token)
7149
7150 (defsubst js2-consume-token ()
7151 (setq js2-current-flagged-token js2-EOF))
7152
7153 (defsubst js2-next-token ()
7154 (prog1
7155 (js2-peek-token)
7156 (js2-consume-token)))
7157
7158 (defsubst js2-next-flagged-token ()
7159 (js2-peek-token)
7160 (prog1 js2-current-flagged-token
7161 (js2-consume-token)))
7162
7163 (defsubst js2-match-token (match)
7164 "Consume and return t if next token matches MATCH, a bytecode.
7165 Returns nil and consumes nothing if MATCH is not the next token."
7166 (if (/= (js2-peek-token) match)
7167 nil
7168 (js2-consume-token)
7169 t))
7170
7171 (defsubst js2-valid-prop-name-token (tt)
7172 (or (= tt js2-NAME)
7173 (and js2-allow-keywords-as-property-names
7174 (plusp tt)
7175 (aref js2-kwd-tokens tt))))
7176
7177 (defsubst js2-match-prop-name ()
7178 "Consume token and return t if next token is a valid property name.
7179 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7180 is non-nil and it's a keyword token."
7181 (if (js2-valid-prop-name-token (js2-peek-token))
7182 (progn
7183 (js2-consume-token)
7184 t)
7185 nil))
7186
7187 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7188 (if (js2-match-prop-name)
7189 t
7190 (js2-report-error msg-id nil pos len)
7191 nil))
7192
7193 (defsubst js2-peek-token-or-eol ()
7194 "Return js2-EOL if the current token immediately follows a newline.
7195 Else returns the current token. Used in situations where we don't
7196 consider certain token types valid if they are preceded by a newline.
7197 One example is the postfix ++ or -- operator, which has to be on the
7198 same line as its operand."
7199 (let ((tt (js2-peek-token)))
7200 ;; Check for last peeked token flags
7201 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7202 js2-EOL
7203 tt)))
7204
7205 (defsubst js2-set-check-for-label ()
7206 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7207 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7208
7209 (defsubst js2-must-match (token msg-id &optional pos len)
7210 "Match next token to token code TOKEN, or record a syntax error.
7211 MSG-ID is the error message to report if the match fails.
7212 Returns t on match, nil if no match."
7213 (if (js2-match-token token)
7214 t
7215 (js2-report-error msg-id nil pos len)
7216 nil))
7217
7218 (defsubst js2-inside-function ()
7219 (plusp js2-nesting-of-function))
7220
7221 (defsubst js2-set-requires-activation ()
7222 (if (js2-function-node-p js2-current-script-or-fn)
7223 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7224
7225 (defsubst js2-check-activation-name (name token)
7226 (when (js2-inside-function)
7227 ;; skip language-version 1.2 check from Rhino
7228 (if (or (string= "arguments" name)
7229 (and js2-compiler-activation-names ; only used in codegen
7230 (gethash name js2-compiler-activation-names)))
7231 (js2-set-requires-activation))))
7232
7233 (defsubst js2-set-is-generator ()
7234 (if (js2-function-node-p js2-current-script-or-fn)
7235 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7236
7237 (defsubst js2-must-have-xml ()
7238 (unless js2-compiler-xml-available
7239 (js2-report-error "msg.XML.not.available")))
7240
7241 (defsubst js2-push-scope (scope)
7242 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7243 (assert (js2-scope-p scope))
7244 (assert (null (js2-scope-parent-scope scope)))
7245 (assert (not (eq js2-current-scope scope)))
7246 (setf (js2-scope-parent-scope scope) js2-current-scope
7247 js2-current-scope scope))
7248
7249 (defsubst js2-pop-scope ()
7250 (setq js2-current-scope
7251 (js2-scope-parent-scope js2-current-scope)))
7252
7253 (defsubst js2-enter-loop (loop-node)
7254 (push loop-node js2-loop-set)
7255 (push loop-node js2-loop-and-switch-set)
7256 (js2-push-scope loop-node)
7257 ;; Tell the current labeled statement (if any) its statement,
7258 ;; and set the jump target of the first label to the loop.
7259 ;; These are used in `js2-parse-continue' to verify that the
7260 ;; continue target is an actual labeled loop. (And for codegen.)
7261 (when js2-labeled-stmt
7262 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7263 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7264 js2-labeled-stmt))) loop-node)))
7265
7266 (defsubst js2-exit-loop ()
7267 (pop js2-loop-set)
7268 (pop js2-loop-and-switch-set)
7269 (js2-pop-scope))
7270
7271 (defsubst js2-enter-switch (switch-node)
7272 (push switch-node js2-loop-and-switch-set))
7273
7274 (defsubst js2-exit-switch ()
7275 (pop js2-loop-and-switch-set))
7276
7277 (defun js2-parse (&optional buf cb)
7278 "Tells the js2 parser to parse a region of JavaScript.
7279
7280 BUF is a buffer or buffer name containing the code to parse.
7281 Call `narrow-to-region' first to parse only part of the buffer.
7282
7283 The returned AST root node is given some additional properties:
7284 `node-count' - total number of nodes in the AST
7285 `buffer' - BUF. The buffer it refers to may change or be killed,
7286 so the value is not necessarily reliable.
7287
7288 An optional callback CB can be specified to report parsing
7289 progress. If `(functionp CB)' returns t, it will be called with
7290 the current line number once before parsing begins, then again
7291 each time the lexer reaches a new line number.
7292
7293 CB can also be a list of the form `(symbol cb ...)' to specify
7294 multiple callbacks with different criteria. Each symbol is a
7295 criterion keyword, and the following element is the callback to
7296 call
7297
7298 :line - called whenever the line number changes
7299 :token - called for each new token consumed
7300
7301 The list of criteria could be extended to include entering or
7302 leaving a statement, an expression, or a function definition."
7303 (if (and cb (not (functionp cb)))
7304 (error "criteria callbacks not yet implemented"))
7305 (let ((inhibit-point-motion-hooks t)
7306 (js2-compiler-xml-available (>= js2-language-version 160))
7307 ;; This is a recursive-descent parser, so give it a big stack.
7308 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7309 (max-specpdl-size (max max-specpdl-size 3000))
7310 (case-fold-search nil)
7311 ast)
7312 (or buf (setq buf (current-buffer)))
7313 (message nil) ; clear any error message from previous parse
7314 (save-excursion
7315 (set-buffer buf)
7316 (setq js2-scanned-comments nil
7317 js2-parsed-errors nil
7318 js2-parsed-warnings nil
7319 js2-imenu-recorder nil
7320 js2-imenu-function-map nil
7321 js2-label-set nil)
7322 (js2-init-scanner)
7323 (setq ast (js2-with-unmodifying-text-property-changes
7324 (js2-do-parse)))
7325 (unless js2-ts-hit-eof
7326 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7327 (setf (js2-ast-root-errors ast) js2-parsed-errors
7328 (js2-ast-root-warnings ast) js2-parsed-warnings)
7329 ;; if we didn't find any declarations, put a dummy in this list so we
7330 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7331 (unless js2-imenu-recorder
7332 (setq js2-imenu-recorder 'empty))
7333 (run-hooks 'js2-parse-finished-hook)
7334 ast)))
7335
7336 ;; Corresponds to Rhino's Parser.parse() method.
7337 (defun js2-do-parse ()
7338 "Parse current buffer starting from current point.
7339 Scanner should be initialized."
7340 (let ((pos js2-ts-cursor)
7341 (end js2-ts-cursor) ; in case file is empty
7342 root n tt)
7343 ;; initialize buffer-local parsing vars
7344 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7345 js2-current-script-or-fn root
7346 js2-current-scope root
7347 js2-current-flagged-token js2-EOF
7348 js2-nesting-of-function 0
7349 js2-labeled-stmt nil
7350 js2-recorded-identifiers nil) ; for js2-highlight
7351 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7352 (if (= tt js2-FUNCTION)
7353 (progn
7354 (js2-consume-token)
7355 (setq n (js2-parse-function (if js2-called-by-compile-function
7356 'FUNCTION_EXPRESSION
7357 'FUNCTION_STATEMENT))))
7358 ;; not a function - parse a statement
7359 (setq n (js2-parse-statement)))
7360 ;; add function or statement to script
7361 (setq end (js2-node-end n))
7362 (js2-block-node-push root n))
7363 ;; add comments to root in lexical order
7364 (when js2-scanned-comments
7365 ;; if we find a comment beyond end of normal kids, use its end
7366 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7367 (dolist (comment js2-scanned-comments)
7368 (push comment (js2-ast-root-comments root))
7369 (js2-node-add-children root comment)))
7370 (setf (js2-node-len root) (- end pos))
7371 ;; Give extensions a chance to muck with things before highlighting starts.
7372 (let ((js2-additional-externs js2-additional-externs))
7373 (dolist (callback js2-post-parse-callbacks)
7374 (funcall callback))
7375 (js2-highlight-undeclared-vars))
7376 root))
7377
7378 (defun js2-function-parser ()
7379 (js2-consume-token)
7380 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7381
7382 (defun js2-parse-function-closure-body (fn-node)
7383 "Parse a JavaScript 1.8 function closure body."
7384 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7385 (if js2-ts-hit-eof
7386 (js2-report-error "msg.no.brace.body" nil
7387 (js2-node-pos fn-node)
7388 (- js2-ts-cursor (js2-node-pos fn-node)))
7389 (js2-node-add-children fn-node
7390 (setf (js2-function-node-body fn-node)
7391 (js2-parse-expr t))))))
7392
7393 (defun js2-parse-function-body (fn-node)
7394 (js2-must-match js2-LC "msg.no.brace.body"
7395 (js2-node-pos fn-node)
7396 (- js2-ts-cursor (js2-node-pos fn-node)))
7397 (let ((pos js2-token-beg) ; LC position
7398 (pn (make-js2-block-node)) ; starts at LC position
7399 tt
7400 end)
7401 (incf js2-nesting-of-function)
7402 (unwind-protect
7403 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7404 (= tt js2-EOF)
7405 (= tt js2-RC)))
7406 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7407 (js2-parse-statement)
7408 (js2-consume-token)
7409 (js2-parse-function 'FUNCTION_STATEMENT))))
7410 (decf js2-nesting-of-function))
7411 (setq end js2-token-end) ; assume no curly and leave at current token
7412 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7413 (setq end js2-token-end))
7414 (setf (js2-node-pos pn) pos
7415 (js2-node-len pn) (- end pos))
7416 (setf (js2-function-node-body fn-node) pn)
7417 (js2-node-add-children fn-node pn)
7418 pn))
7419
7420 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7421 "Declare and fontify destructuring parameters inside NODE.
7422 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7423 (cond
7424 ((js2-name-node-p node)
7425 (let (leftpos)
7426 (js2-define-symbol decl-type (js2-name-node-name node)
7427 node ignore-not-in-block)
7428 (when face
7429 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7430 (+ leftpos (js2-node-len node))
7431 face 'record))))
7432 ((js2-object-node-p node)
7433 (dolist (elem (js2-object-node-elems node))
7434 (js2-define-destruct-symbols
7435 (if (js2-object-prop-node-p elem)
7436 (js2-object-prop-node-right elem)
7437 ;; abbreviated destructuring {a, b}
7438 elem)
7439 decl-type face ignore-not-in-block)))
7440 ((js2-array-node-p node)
7441 (dolist (elem (js2-array-node-elems node))
7442 (when elem
7443 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7444 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7445 (js2-node-len node)))))
7446
7447 (defun js2-parse-function-params (fn-node pos)
7448 (if (js2-match-token js2-RP)
7449 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7450 (let (params len param)
7451 (loop for tt = (js2-peek-token)
7452 do
7453 (cond
7454 ;; destructuring param
7455 ((or (= tt js2-LB) (= tt js2-LC))
7456 (setq param (js2-parse-primary-expr-lhs))
7457 (js2-define-destruct-symbols param
7458 js2-LP
7459 'js2-function-param-face)
7460 (push param params))
7461 ;; simple name
7462 (t
7463 (js2-must-match js2-NAME "msg.no.parm")
7464 (js2-record-face 'js2-function-param-face)
7465 (setq param (js2-create-name-node))
7466 (js2-define-symbol js2-LP js2-ts-string param)
7467 (push param params)))
7468 while
7469 (js2-match-token js2-COMMA))
7470 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7471 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7472 (dolist (p params)
7473 (js2-node-add-children fn-node p)
7474 (push p (js2-function-node-params fn-node))))))
7475
7476 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7477 "Possibly show inconsistent-return warning.
7478 Last token scanned is the close-curly for the function body."
7479 (when (and js2-mode-show-strict-warnings
7480 js2-strict-inconsistent-return-warning
7481 (not (js2-has-consistent-return-usage
7482 (js2-function-node-body fn-node))))
7483 ;; Have it extend from close-curly to bol or beginning of block.
7484 (let ((pos (save-excursion
7485 (goto-char js2-token-end)
7486 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7487 (point-at-bol))))
7488 (end js2-token-end))
7489 (if (plusp (js2-name-node-length name))
7490 (js2-add-strict-warning "msg.no.return.value"
7491 (js2-name-node-name name) pos end)
7492 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7493
7494 (defun js2-parse-function (function-type)
7495 "Function parser. FUNCTION-TYPE is a symbol."
7496 (let ((pos js2-token-beg) ; start of 'function' keyword
7497 name
7498 name-beg
7499 name-end
7500 fn-node
7501 lp
7502 (synthetic-type function-type)
7503 member-expr-node)
7504 ;; parse function name, expression, or non-name (anonymous)
7505 (cond
7506 ;; function foo(...)
7507 ((js2-match-token js2-NAME)
7508 (setq name (js2-create-name-node t)
7509 name-beg js2-token-beg
7510 name-end js2-token-end)
7511 (unless (js2-match-token js2-LP)
7512 (when js2-allow-member-expr-as-function-name
7513 ;; function foo.bar(...)
7514 (setq member-expr-node name
7515 name nil
7516 member-expr-node (js2-parse-member-expr-tail
7517 nil member-expr-node)))
7518 (js2-must-match js2-LP "msg.no.paren.parms")))
7519 ((js2-match-token js2-LP)
7520 nil) ; anonymous function: leave name as null
7521 (t
7522 ;; function random-member-expr(...)
7523 (when js2-allow-member-expr-as-function-name
7524 ;; Note that memberExpr can not start with '(' like
7525 ;; in function (1+2).toString(), because 'function (' already
7526 ;; processed as anonymous function
7527 (setq member-expr-node (js2-parse-member-expr)))
7528 (js2-must-match js2-LP "msg.no.paren.parms")))
7529 (if (= js2-current-token js2-LP) ; eventually matched LP?
7530 (setq lp js2-token-beg))
7531 (if member-expr-node
7532 (progn
7533 (setq synthetic-type 'FUNCTION_EXPRESSION)
7534 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7535 (if name
7536 (js2-set-face name-beg name-end
7537 'font-lock-function-name-face 'record)))
7538 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7539 (plusp (js2-name-node-length name)))
7540 ;; Function statements define a symbol in the enclosing scope
7541 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7542 (setf fn-node (make-js2-function-node :pos pos
7543 :name name
7544 :form function-type
7545 :lp (if lp (- lp pos))))
7546 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7547 ;; 1. Nested functions are not affected by the dynamic scope flag
7548 ;; as dynamic scope is already a parent of their scope.
7549 ;; 2. Functions defined under the with statement also immune to
7550 ;; this setup, in which case dynamic scope is ignored in favor
7551 ;; of the with object.
7552 (setf (js2-function-node-ignore-dynamic fn-node) t))
7553 ;; dynamically bind all the per-function variables
7554 (let ((js2-current-script-or-fn fn-node)
7555 (js2-current-scope fn-node)
7556 (js2-nesting-of-with 0)
7557 (js2-end-flags 0)
7558 js2-label-set
7559 js2-loop-set
7560 js2-loop-and-switch-set)
7561 (js2-parse-function-params fn-node pos)
7562 (if (and (>= js2-language-version 180)
7563 (/= (js2-peek-token) js2-LC))
7564 (js2-parse-function-closure-body fn-node)
7565 (js2-parse-function-body fn-node))
7566 (if name
7567 (js2-node-add-children fn-node name))
7568 (js2-check-inconsistent-return-warning fn-node name)
7569 ;; Function expressions define a name only in the body of the
7570 ;; function, and only if not hidden by a parameter name
7571 (if (and name
7572 (eq synthetic-type 'FUNCTION_EXPRESSION)
7573 (null (js2-scope-get-symbol js2-current-scope
7574 (js2-name-node-name name))))
7575 (js2-define-symbol js2-FUNCTION
7576 (js2-name-node-name name)
7577 fn-node))
7578 (if (and name
7579 (not (eq function-type 'FUNCTION_EXPRESSION)))
7580 (js2-record-imenu-functions fn-node)))
7581 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7582 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7583 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7584 ;; We wait until after parsing the function to set its parent scope,
7585 ;; since `js2-define-symbol' needs the defining-scope check to stop
7586 ;; at the function boundary when checking for redeclarations.
7587 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7588 fn-node))
7589
7590 (defun js2-parse-statements (&optional parent)
7591 "Parse a statement list. Last token consumed must be js2-LC.
7592
7593 PARENT can be a `js2-block-node', in which case the statements are
7594 appended to PARENT. Otherwise a new `js2-block-node' is created
7595 and returned.
7596
7597 This function does not match the closing js2-RC: the caller
7598 matches the RC so it can provide a suitable error message if not
7599 matched. This means it's up to the caller to set the length of
7600 the node to include the closing RC. The node start pos is set to
7601 the absolute buffer start position, and the caller should fix it
7602 up to be relative to the parent node. All children of this block
7603 node are given relative start positions and correct lengths."
7604 (let ((pn (or parent (make-js2-block-node)))
7605 tt)
7606 (setf (js2-node-pos pn) js2-token-beg)
7607 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7608 (/= tt js2-RC))
7609 (js2-block-node-push pn (js2-parse-statement)))
7610 pn))
7611
7612 (defun js2-parse-statement ()
7613 (let (tt pn beg end)
7614 ;; coarse-grained user-interrupt check - needs work
7615 (and js2-parse-interruptable-p
7616 (zerop (% (incf js2-parse-stmt-count)
7617 js2-statements-per-pause))
7618 (input-pending-p)
7619 (throw 'interrupted t))
7620 (setq pn (js2-statement-helper))
7621 ;; no-side-effects warning check
7622 (unless (js2-node-has-side-effects pn)
7623 (setq end (js2-node-end pn))
7624 (save-excursion
7625 (goto-char end)
7626 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7627 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7628 pn))
7629
7630 ;; These correspond to the switch cases in Parser.statementHelper
7631 (defconst js2-parsers
7632 (let ((parsers (make-vector js2-num-tokens
7633 #'js2-parse-expr-stmt)))
7634 (aset parsers js2-BREAK #'js2-parse-break)
7635 (aset parsers js2-CONST #'js2-parse-const-var)
7636 (aset parsers js2-CONTINUE #'js2-parse-continue)
7637 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7638 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7639 (aset parsers js2-DO #'js2-parse-do)
7640 (aset parsers js2-FOR #'js2-parse-for)
7641 (aset parsers js2-FUNCTION #'js2-function-parser)
7642 (aset parsers js2-IF #'js2-parse-if)
7643 (aset parsers js2-LC #'js2-parse-block)
7644 (aset parsers js2-LET #'js2-parse-let-stmt)
7645 (aset parsers js2-NAME #'js2-parse-name-or-label)
7646 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7647 (aset parsers js2-SEMI #'js2-parse-semi)
7648 (aset parsers js2-SWITCH #'js2-parse-switch)
7649 (aset parsers js2-THROW #'js2-parse-throw)
7650 (aset parsers js2-TRY #'js2-parse-try)
7651 (aset parsers js2-VAR #'js2-parse-const-var)
7652 (aset parsers js2-WHILE #'js2-parse-while)
7653 (aset parsers js2-WITH #'js2-parse-with)
7654 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7655 parsers)
7656 "A vector mapping token types to parser functions.")
7657
7658 (defsubst js2-parse-warn-missing-semi (beg end)
7659 (and js2-mode-show-strict-warnings
7660 js2-strict-missing-semi-warning
7661 (js2-add-strict-warning
7662 "msg.missing.semi" nil
7663 ;; back up to beginning of statement or line
7664 (max beg (save-excursion
7665 (goto-char end)
7666 (point-at-bol)))
7667 end)))
7668
7669 (defconst js2-no-semi-insertion
7670 (list js2-IF
7671 js2-SWITCH
7672 js2-WHILE
7673 js2-DO
7674 js2-FOR
7675 js2-TRY
7676 js2-WITH
7677 js2-LC
7678 js2-ERROR
7679 js2-SEMI
7680 js2-FUNCTION)
7681 "List of tokens that don't do automatic semicolon insertion.")
7682
7683 (defconst js2-autoinsert-semi-and-warn
7684 (list js2-ERROR js2-EOF js2-RC))
7685
7686 (defun js2-statement-helper ()
7687 (let* ((tt (js2-peek-token))
7688 (first-tt tt)
7689 (beg js2-token-beg)
7690 (parser (if (= tt js2-ERROR)
7691 #'js2-parse-semi
7692 (aref js2-parsers tt)))
7693 pn
7694 tt-flagged)
7695 ;; If the statement is set, then it's been told its label by now.
7696 (and js2-labeled-stmt
7697 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7698 (setq js2-labeled-stmt nil))
7699 (setq pn (funcall parser))
7700 ;; Don't do auto semi insertion for certain statement types.
7701 (unless (or (memq first-tt js2-no-semi-insertion)
7702 (js2-labeled-stmt-node-p pn))
7703 (js2-auto-insert-semicolon pn))
7704 pn))
7705
7706 (defun js2-auto-insert-semicolon (pn)
7707 (let* ((tt-flagged (js2-peek-flagged-token))
7708 (tt (logand tt-flagged js2-clear-ti-mask))
7709 (pos (js2-node-pos pn)))
7710 (cond
7711 ((= tt js2-SEMI)
7712 ;; Consume ';' as a part of expression
7713 (js2-consume-token)
7714 ;; extend the node bounds to include the semicolon.
7715 (setf (js2-node-len pn) (- js2-token-end pos)))
7716 ((memq tt js2-autoinsert-semi-and-warn)
7717 ;; Autoinsert ;
7718 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7719 (t
7720 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7721 ;; Report error if no EOL or autoinsert ';' otherwise
7722 (js2-report-error "msg.no.semi.stmt")
7723 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7724
7725 (defun js2-parse-condition ()
7726 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7727 The parens are discarded and the expression node is returned.
7728 The `pos' field of the return value is set to an absolute position
7729 that must be fixed up by the caller.
7730 Return value is a list (EXPR LP RP), with absolute paren positions."
7731 (let (pn lp rp)
7732 (if (js2-must-match js2-LP "msg.no.paren.cond")
7733 (setq lp js2-token-beg))
7734 (setq pn (js2-parse-expr))
7735 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7736 (setq rp js2-token-beg))
7737 ;; Report strict warning on code like "if (a = 7) ..."
7738 (if (and js2-strict-cond-assign-warning
7739 (js2-assign-node-p pn))
7740 (js2-add-strict-warning "msg.equal.as.assign" nil
7741 (js2-node-pos pn)
7742 (+ (js2-node-pos pn)
7743 (js2-node-len pn))))
7744 (list pn lp rp)))
7745
7746 (defun js2-parse-if ()
7747 "Parser for if-statement. Last matched token must be js2-IF."
7748 (let ((pos js2-token-beg)
7749 cond
7750 if-true
7751 if-false
7752 else-pos
7753 end
7754 pn)
7755 (js2-consume-token)
7756 (setq cond (js2-parse-condition)
7757 if-true (js2-parse-statement)
7758 if-false (if (js2-match-token js2-ELSE)
7759 (progn
7760 (setq else-pos (- js2-token-beg pos))
7761 (js2-parse-statement)))
7762 end (js2-node-end (or if-false if-true))
7763 pn (make-js2-if-node :pos pos
7764 :len (- end pos)
7765 :condition (car cond)
7766 :then-part if-true
7767 :else-part if-false
7768 :else-pos else-pos
7769 :lp (js2-relpos (second cond) pos)
7770 :rp (js2-relpos (third cond) pos)))
7771 (js2-node-add-children pn (car cond) if-true if-false)
7772 pn))
7773
7774 (defun js2-parse-switch ()
7775 "Parser for if-statement. Last matched token must be js2-SWITCH."
7776 (let ((pos js2-token-beg)
7777 tt
7778 pn
7779 discriminant
7780 has-default
7781 case-expr
7782 case-node
7783 case-pos
7784 cases
7785 stmt
7786 lp
7787 rp)
7788 (js2-consume-token)
7789 (if (js2-must-match js2-LP "msg.no.paren.switch")
7790 (setq lp js2-token-beg))
7791 (setq discriminant (js2-parse-expr)
7792 pn (make-js2-switch-node :discriminant discriminant
7793 :pos pos
7794 :lp (js2-relpos lp pos)))
7795 (js2-node-add-children pn discriminant)
7796 (js2-enter-switch pn)
7797 (unwind-protect
7798 (progn
7799 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7800 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7801 (js2-must-match js2-LC "msg.no.brace.switch")
7802 (catch 'break
7803 (while t
7804 (setq tt (js2-next-token)
7805 case-pos js2-token-beg)
7806 (cond
7807 ((= tt js2-RC)
7808 (setf (js2-node-len pn) (- js2-token-end pos))
7809 (throw 'break nil)) ; done
7810 ((= tt js2-CASE)
7811 (setq case-expr (js2-parse-expr))
7812 (js2-must-match js2-COLON "msg.no.colon.case"))
7813 ((= tt js2-DEFAULT)
7814 (if has-default
7815 (js2-report-error "msg.double.switch.default"))
7816 (setq has-default t
7817 case-expr nil)
7818 (js2-must-match js2-COLON "msg.no.colon.case"))
7819 (t
7820 (js2-report-error "msg.bad.switch")
7821 (throw 'break nil)))
7822 (setq case-node (make-js2-case-node :pos case-pos
7823 :len (- js2-token-end case-pos)
7824 :expr case-expr))
7825 (js2-node-add-children case-node case-expr)
7826 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7827 (/= tt js2-CASE)
7828 (/= tt js2-DEFAULT)
7829 (/= tt js2-EOF))
7830 (setf stmt (js2-parse-statement)
7831 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7832 (js2-block-node-push case-node stmt))
7833 (push case-node cases)))
7834 ;; add cases last, as pushing reverses the order to be correct
7835 (dolist (kid cases)
7836 (js2-node-add-children pn kid)
7837 (push kid (js2-switch-node-cases pn)))
7838 pn) ; return value
7839 (js2-exit-switch))))
7840
7841 (defun js2-parse-while ()
7842 "Parser for while-statement. Last matched token must be js2-WHILE."
7843 (let ((pos js2-token-beg)
7844 (pn (make-js2-while-node))
7845 cond
7846 body)
7847 (js2-consume-token)
7848 (js2-enter-loop pn)
7849 (unwind-protect
7850 (progn
7851 (setf cond (js2-parse-condition)
7852 (js2-while-node-condition pn) (car cond)
7853 body (js2-parse-statement)
7854 (js2-while-node-body pn) body
7855 (js2-node-len pn) (- (js2-node-end body) pos)
7856 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7857 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7858 (js2-node-add-children pn body (car cond)))
7859 (js2-exit-loop))
7860 pn))
7861
7862 (defun js2-parse-do ()
7863 "Parser for do-statement. Last matched token must be js2-DO."
7864 (let ((pos js2-token-beg)
7865 (pn (make-js2-do-node))
7866 cond
7867 body
7868 end)
7869 (js2-consume-token)
7870 (js2-enter-loop pn)
7871 (unwind-protect
7872 (progn
7873 (setq body (js2-parse-statement))
7874 (js2-must-match js2-WHILE "msg.no.while.do")
7875 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7876 cond (js2-parse-condition)
7877 (js2-do-node-condition pn) (car cond)
7878 (js2-do-node-body pn) body
7879 end js2-ts-cursor
7880 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7881 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7882 (js2-node-add-children pn (car cond) body))
7883 (js2-exit-loop))
7884 ;; Always auto-insert semicolon to follow SpiderMonkey:
7885 ;; It is required by ECMAScript but is ignored by the rest of
7886 ;; world; see bug 238945
7887 (if (js2-match-token js2-SEMI)
7888 (setq end js2-ts-cursor))
7889 (setf (js2-node-len pn) (- end pos))
7890 pn))
7891
7892 (defun js2-parse-for ()
7893 "Parser for for-statement. Last matched token must be js2-FOR.
7894 Parses for, for-in, and for each-in statements."
7895 (let ((for-pos js2-token-beg)
7896 pn
7897 is-for-each
7898 is-for-in
7899 in-pos
7900 each-pos
7901 tmp-pos
7902 init ; Node init is also foo in 'foo in object'
7903 cond ; Node cond is also object in 'foo in object'
7904 incr ; 3rd section of for-loop initializer
7905 body
7906 tt
7907 lp
7908 rp)
7909 (js2-consume-token)
7910 ;; See if this is a for each () instead of just a for ()
7911 (when (js2-match-token js2-NAME)
7912 (if (string= "each" js2-ts-string)
7913 (progn
7914 (setq is-for-each t
7915 each-pos (- js2-token-beg for-pos)) ; relative
7916 (js2-record-face 'font-lock-keyword-face))
7917 (js2-report-error "msg.no.paren.for")))
7918 (if (js2-must-match js2-LP "msg.no.paren.for")
7919 (setq lp (- js2-token-beg for-pos)))
7920 (setq tt (js2-peek-token))
7921 ;; 'for' makes local scope
7922 (js2-push-scope (make-js2-scope))
7923 (unwind-protect
7924 ;; parse init clause
7925 (let ((js2-in-for-init t)) ; set as dynamic variable
7926 (cond
7927 ((= tt js2-SEMI)
7928 (setq init (make-js2-empty-expr-node)))
7929 ((or (= tt js2-VAR) (= tt js2-LET))
7930 (js2-consume-token)
7931 (setq init (js2-parse-variables tt js2-token-beg)))
7932 (t
7933 (setq init (js2-parse-expr)))))
7934 (if (js2-match-token js2-IN)
7935 (setq is-for-in t
7936 in-pos (- js2-token-beg for-pos)
7937 ;; scope of iteration target object is not the scope we've created above.
7938 ;; stash current scope temporary.
7939 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7940 (js2-parse-expr))) ; object over which we're iterating
7941 ;; else ordinary for loop - parse cond and incr
7942 (js2-must-match js2-SEMI "msg.no.semi.for")
7943 (setq cond (if (= (js2-peek-token) js2-SEMI)
7944 (make-js2-empty-expr-node) ; no loop condition
7945 (js2-parse-expr)))
7946 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7947 (setq tmp-pos js2-token-end
7948 incr (if (= (js2-peek-token) js2-RP)
7949 (make-js2-empty-expr-node :pos tmp-pos)
7950 (js2-parse-expr))))
7951 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7952 (setq rp (- js2-token-beg for-pos)))
7953 (if (not is-for-in)
7954 (setq pn (make-js2-for-node :init init
7955 :condition cond
7956 :update incr
7957 :lp lp
7958 :rp rp))
7959 ;; cond could be null if 'in obj' got eaten by the init node.
7960 (if (js2-infix-node-p init)
7961 ;; it was (foo in bar) instead of (var foo in bar)
7962 (setq cond (js2-infix-node-right init)
7963 init (js2-infix-node-left init))
7964 (if (and (js2-var-decl-node-p init)
7965 (> (length (js2-var-decl-node-kids init)) 1))
7966 (js2-report-error "msg.mult.index")))
7967 (setq pn (make-js2-for-in-node :iterator init
7968 :object cond
7969 :in-pos in-pos
7970 :foreach-p is-for-each
7971 :each-pos each-pos
7972 :lp lp
7973 :rp rp)))
7974 (unwind-protect
7975 (progn
7976 (js2-enter-loop pn)
7977 ;; We have to parse the body -after- creating the loop node,
7978 ;; so that the loop node appears in the js2-loop-set, allowing
7979 ;; break/continue statements to find the enclosing loop.
7980 (setf body (js2-parse-statement)
7981 (js2-loop-node-body pn) body
7982 (js2-node-pos pn) for-pos
7983 (js2-node-len pn) (- (js2-node-end body) for-pos))
7984 (js2-node-add-children pn init cond incr body))
7985 ;; finally
7986 (js2-exit-loop))
7987 (js2-pop-scope))
7988 pn))
7989
7990 (defun js2-parse-try ()
7991 "Parser for try-statement. Last matched token must be js2-TRY."
7992 (let ((try-pos js2-token-beg)
7993 try-end
7994 try-block
7995 catch-blocks
7996 finally-block
7997 saw-default-catch
7998 peek
7999 param
8000 catch-cond
8001 catch-node
8002 guard-kwd
8003 catch-pos
8004 finally-pos
8005 pn
8006 block
8007 lp
8008 rp)
8009 (js2-consume-token)
8010 (if (/= (js2-peek-token) js2-LC)
8011 (js2-report-error "msg.no.brace.try"))
8012 (setq try-block (js2-parse-statement)
8013 try-end (js2-node-end try-block)
8014 peek (js2-peek-token))
8015 (cond
8016 ((= peek js2-CATCH)
8017 (while (js2-match-token js2-CATCH)
8018 (setq catch-pos js2-token-beg
8019 guard-kwd nil
8020 catch-cond nil
8021 lp nil
8022 rp nil)
8023 (if saw-default-catch
8024 (js2-report-error "msg.catch.unreachable"))
8025 (if (js2-must-match js2-LP "msg.no.paren.catch")
8026 (setq lp (- js2-token-beg catch-pos)))
8027 (js2-push-scope (make-js2-scope))
8028 (let ((tt (js2-peek-token)))
8029 (cond
8030 ;; destructuring pattern
8031 ;; catch ({ message, file }) { ... }
8032 ((or (= tt js2-LB) (= tt js2-LC))
8033 (setq param
8034 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8035 js2-LET nil)))
8036 ;; simple name
8037 (t
8038 (js2-must-match js2-NAME "msg.bad.catchcond")
8039 (setq param (js2-create-name-node))
8040 (js2-define-symbol js2-LET js2-ts-string param))))
8041 ;; pattern guard
8042 (if (js2-match-token js2-IF)
8043 (setq guard-kwd (- js2-token-beg catch-pos)
8044 catch-cond (js2-parse-expr))
8045 (setq saw-default-catch t))
8046 (if (js2-must-match js2-RP "msg.bad.catchcond")
8047 (setq rp (- js2-token-beg catch-pos)))
8048 (js2-must-match js2-LC "msg.no.brace.catchblock")
8049 (setq block (js2-parse-statements)
8050 try-end (js2-node-end block)
8051 catch-node (make-js2-catch-node :pos catch-pos
8052 :param param
8053 :guard-expr catch-cond
8054 :guard-kwd guard-kwd
8055 :block block
8056 :lp lp
8057 :rp rp))
8058 (js2-pop-scope)
8059 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8060 (setq try-end js2-token-beg))
8061 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8062 (js2-node-len catch-node) (- try-end catch-pos))
8063 (js2-node-add-children catch-node param catch-cond block)
8064 (push catch-node catch-blocks)))
8065 ((/= peek js2-FINALLY)
8066 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8067 (js2-node-pos try-block)
8068 (- (setq try-end (js2-node-end try-block))
8069 (js2-node-pos try-block)))))
8070 (when (js2-match-token js2-FINALLY)
8071 (setq finally-pos js2-token-beg
8072 block (js2-parse-statement)
8073 try-end (js2-node-end block)
8074 finally-block (make-js2-finally-node :pos finally-pos
8075 :len (- try-end finally-pos)
8076 :body block))
8077 (js2-node-add-children finally-block block))
8078 (setq pn (make-js2-try-node :pos try-pos
8079 :len (- try-end try-pos)
8080 :try-block try-block
8081 :finally-block finally-block))
8082 (js2-node-add-children pn try-block finally-block)
8083 ;; push them onto the try-node, which reverses and corrects their order
8084 (dolist (cb catch-blocks)
8085 (js2-node-add-children pn cb)
8086 (push cb (js2-try-node-catch-clauses pn)))
8087 pn))
8088
8089 (defun js2-parse-throw ()
8090 "Parser for throw-statement. Last matched token must be js2-THROW."
8091 (let ((pos js2-token-beg)
8092 expr
8093 pn)
8094 (js2-consume-token)
8095 (if (= (js2-peek-token-or-eol) js2-EOL)
8096 ;; ECMAScript does not allow new lines before throw expression,
8097 ;; see bug 256617
8098 (js2-report-error "msg.bad.throw.eol"))
8099 (setq expr (js2-parse-expr)
8100 pn (make-js2-throw-node :pos pos
8101 :len (- (js2-node-end expr) pos)
8102 :expr expr))
8103 (js2-node-add-children pn expr)
8104 pn))
8105
8106 (defsubst js2-match-jump-label-name (label-name)
8107 "If break/continue specified a label, return that label's labeled stmt.
8108 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8109 does not match an existing label, reports an error and returns nil."
8110 (let ((bundle (cdr (assoc label-name js2-label-set))))
8111 (if (null bundle)
8112 (js2-report-error "msg.undef.label"))
8113 bundle))
8114
8115 (defun js2-parse-break ()
8116 "Parser for break-statement. Last matched token must be js2-BREAK."
8117 (let ((pos js2-token-beg)
8118 (end js2-token-end)
8119 break-target ; statement to break from
8120 break-label ; in "break foo", name-node representing the foo
8121 labels ; matching labeled statement to break to
8122 pn)
8123 (js2-consume-token) ; `break'
8124 (when (eq (js2-peek-token-or-eol) js2-NAME)
8125 (js2-consume-token)
8126 (setq break-label (js2-create-name-node)
8127 end (js2-node-end break-label)
8128 ;; matchJumpLabelName only matches if there is one
8129 labels (js2-match-jump-label-name js2-ts-string)
8130 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8131 (unless (or break-target break-label)
8132 ;; no break target specified - try for innermost enclosing loop/switch
8133 (if (null js2-loop-and-switch-set)
8134 (unless break-label
8135 (js2-report-error "msg.bad.break" nil pos (length "break")))
8136 (setq break-target (car js2-loop-and-switch-set))))
8137 (setq pn (make-js2-break-node :pos pos
8138 :len (- end pos)
8139 :label break-label
8140 :target break-target))
8141 (js2-node-add-children pn break-label) ; but not break-target
8142 pn))
8143
8144 (defun js2-parse-continue ()
8145 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8146 (let ((pos js2-token-beg)
8147 (end js2-token-end)
8148 label ; optional user-specified label, a `js2-name-node'
8149 labels ; current matching labeled stmt, if any
8150 target ; the `js2-loop-node' target of this continue stmt
8151 pn)
8152 (js2-consume-token) ; `continue'
8153 (when (= (js2-peek-token-or-eol) js2-NAME)
8154 (js2-consume-token)
8155 (setq label (js2-create-name-node)
8156 end (js2-node-end label)
8157 ;; matchJumpLabelName only matches if there is one
8158 labels (js2-match-jump-label-name js2-ts-string)))
8159 (cond
8160 ((null labels) ; no current label to go to
8161 (if (null js2-loop-set) ; no loop to continue to
8162 (js2-report-error "msg.continue.outside" nil pos
8163 (length "continue"))
8164 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8165 (t
8166 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8167 (setq target (js2-labeled-stmt-node-stmt labels))
8168 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8169 (setq pn (make-js2-continue-node :pos pos
8170 :len (- end pos)
8171 :label label
8172 :target target))
8173 (js2-node-add-children pn label) ; but not target - it's not our child
8174 pn))
8175
8176 (defun js2-parse-with ()
8177 "Parser for with-statement. Last matched token must be js2-WITH."
8178 (js2-consume-token)
8179 (let ((pos js2-token-beg)
8180 obj body pn lp rp)
8181 (if (js2-must-match js2-LP "msg.no.paren.with")
8182 (setq lp js2-token-beg))
8183 (setq obj (js2-parse-expr))
8184 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8185 (setq rp js2-token-beg))
8186 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8187 (setq body (js2-parse-statement)))
8188 (setq pn (make-js2-with-node :pos pos
8189 :len (- (js2-node-end body) pos)
8190 :object obj
8191 :body body
8192 :lp (js2-relpos lp pos)
8193 :rp (js2-relpos rp pos)))
8194 (js2-node-add-children pn obj body)
8195 pn))
8196
8197 (defun js2-parse-const-var ()
8198 "Parser for var- or const-statement.
8199 Last matched token must be js2-CONST or js2-VAR."
8200 (let ((tt (js2-peek-token))
8201 (pos js2-token-beg)
8202 expr
8203 pn)
8204 (js2-consume-token)
8205 (setq expr (js2-parse-variables tt js2-token-beg)
8206 pn (make-js2-expr-stmt-node :pos pos
8207 :len (- (js2-node-end expr) pos)
8208 :expr expr))
8209 (js2-node-add-children pn expr)
8210 pn))
8211
8212 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8213 (let ((pn (make-js2-expr-stmt-node :pos pos
8214 :len (js2-node-len expr)
8215 :type (if (js2-inside-function)
8216 js2-EXPR_VOID
8217 js2-EXPR_RESULT)
8218 :expr expr)))
8219 (if add-child
8220 (js2-node-add-children pn expr))
8221 pn))
8222
8223 (defun js2-parse-let-stmt ()
8224 "Parser for let-statement. Last matched token must be js2-LET."
8225 (js2-consume-token)
8226 (let ((pos js2-token-beg)
8227 expr
8228 pn)
8229 (if (= (js2-peek-token) js2-LP)
8230 ;; let expression in statement context
8231 (setq expr (js2-parse-let pos 'statement)
8232 pn (js2-wrap-with-expr-stmt pos expr t))
8233 ;; else we're looking at a statement like let x=6, y=7;
8234 (setf expr (js2-parse-variables js2-LET pos)
8235 pn (js2-wrap-with-expr-stmt pos expr t)
8236 (js2-node-type pn) js2-EXPR_RESULT))
8237 pn))
8238
8239 (defun js2-parse-ret-yield ()
8240 (js2-parse-return-or-yield (js2-peek-token) nil))
8241
8242 (defconst js2-parse-return-stmt-enders
8243 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8244
8245 (defsubst js2-now-all-set (before after mask)
8246 "Return whether or not the bits in the mask have changed to all set.
8247 BEFORE is bits before change, AFTER is bits after change, and MASK is
8248 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8249 but not BEFORE."
8250 (and (/= (logand before mask) mask)
8251 (= (logand after mask) mask)))
8252
8253 (defun js2-parse-return-or-yield (tt expr-context)
8254 (let ((pos js2-token-beg)
8255 (end js2-token-end)
8256 (before js2-end-flags)
8257 (inside-function (js2-inside-function))
8258 e
8259 ret
8260 name)
8261 (unless inside-function
8262 (js2-report-error (if (eq tt js2-RETURN)
8263 "msg.bad.return"
8264 "msg.bad.yield")))
8265 (js2-consume-token)
8266 ;; This is ugly, but we don't want to require a semicolon.
8267 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8268 (setq e (js2-parse-expr)
8269 end (js2-node-end e)))
8270 (cond
8271 ((eq tt js2-RETURN)
8272 (js2-set-flag js2-end-flags (if (null e)
8273 js2-end-returns
8274 js2-end-returns-value))
8275 (setq ret (make-js2-return-node :pos pos
8276 :len (- end pos)
8277 :retval e))
8278 (js2-node-add-children ret e)
8279 ;; See if we need a strict mode warning.
8280 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8281 ;; more thorough and accurate than this before/after flag check.
8282 ;; E.g. if there's a finally-block that always returns, we shouldn't
8283 ;; show a warning generated by inconsistent returns in the catch blocks.
8284 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8285 ;; so we know which returns/yields to highlight, and we should get rid of
8286 ;; all the checking in `js2-parse-return-or-yield'.
8287 (if (and js2-strict-inconsistent-return-warning
8288 (js2-now-all-set before js2-end-flags
8289 (logior js2-end-returns js2-end-returns-value)))
8290 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8291 (t
8292 (unless (js2-inside-function)
8293 (js2-report-error "msg.bad.yield"))
8294 (js2-set-flag js2-end-flags js2-end-yields)
8295 (setq ret (make-js2-yield-node :pos pos
8296 :len (- end pos)
8297 :value e))
8298 (js2-node-add-children ret e)
8299 (unless expr-context
8300 (setq e ret
8301 ret (js2-wrap-with-expr-stmt pos e t))
8302 (js2-set-requires-activation)
8303 (js2-set-is-generator))))
8304 ;; see if we are mixing yields and value returns.
8305 (when (and inside-function
8306 (js2-now-all-set before js2-end-flags
8307 (logior js2-end-yields js2-end-returns-value)))
8308 (setq name (js2-function-name js2-current-script-or-fn))
8309 (if (zerop (length name))
8310 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8311 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8312 ret))
8313
8314 (defun js2-parse-debugger ()
8315 (js2-consume-token)
8316 (make-js2-keyword-node :type js2-DEBUGGER))
8317
8318 (defun js2-parse-block ()
8319 "Parser for a curly-delimited statement block.
8320 Last token matched must be js2-LC."
8321 (let ((pos js2-token-beg)
8322 (pn (make-js2-scope)))
8323 (js2-consume-token)
8324 (js2-push-scope pn)
8325 (unwind-protect
8326 (progn
8327 (js2-parse-statements pn)
8328 (js2-must-match js2-RC "msg.no.brace.block")
8329 (setf (js2-node-len pn) (- js2-token-end pos)))
8330 (js2-pop-scope))
8331 pn))
8332
8333 ;; for js2-ERROR too, to have a node for error recovery to work on
8334 (defun js2-parse-semi ()
8335 "Parse a statement or handle an error.
8336 Last matched token is js-SEMI or js-ERROR."
8337 (let ((tt (js2-peek-token)) pos len)
8338 (js2-consume-token)
8339 (if (eq tt js2-SEMI)
8340 (make-js2-empty-expr-node :len 1)
8341 (setq pos js2-token-beg
8342 len (- js2-token-beg pos))
8343 (js2-report-error "msg.syntax" nil pos len)
8344 (make-js2-error-node :pos pos :len len))))
8345
8346 (defun js2-parse-default-xml-namespace ()
8347 "Parse a `default xml namespace = <expr>' e4x statement."
8348 (let ((pos js2-token-beg)
8349 end len expr unary es)
8350 (js2-consume-token)
8351 (js2-must-have-xml)
8352 (js2-set-requires-activation)
8353 (setq len (- js2-ts-cursor pos))
8354 (unless (and (js2-match-token js2-NAME)
8355 (string= js2-ts-string "xml"))
8356 (js2-report-error "msg.bad.namespace" nil pos len))
8357 (unless (and (js2-match-token js2-NAME)
8358 (string= js2-ts-string "namespace"))
8359 (js2-report-error "msg.bad.namespace" nil pos len))
8360 (unless (js2-match-token js2-ASSIGN)
8361 (js2-report-error "msg.bad.namespace" nil pos len))
8362 (setq expr (js2-parse-expr)
8363 end (js2-node-end expr)
8364 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8365 :pos pos
8366 :len (- end pos)
8367 :operand expr))
8368 (js2-node-add-children unary expr)
8369 (make-js2-expr-stmt-node :pos pos
8370 :len (- end pos)
8371 :expr unary)))
8372
8373 (defun js2-record-label (label bundle)
8374 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8375 (js2-consume-token)
8376 (let ((name (js2-label-node-name label))
8377 labeled-stmt
8378 dup)
8379 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8380 ;; flag both labels if possible when used in editing mode
8381 (if (and js2-parse-ide-mode
8382 (setq dup (js2-get-label-by-name labeled-stmt name)))
8383 (js2-report-error "msg.dup.label" nil
8384 (js2-node-abs-pos dup) (js2-node-len dup)))
8385 (js2-report-error "msg.dup.label" nil
8386 (js2-node-pos label) (js2-node-len label)))
8387 (js2-labeled-stmt-node-add-label bundle label)
8388 (js2-node-add-children bundle label)
8389 ;; Add one reference to the bundle per label in `js2-label-set'
8390 (push (cons name bundle) js2-label-set)))
8391
8392 (defun js2-parse-name-or-label ()
8393 "Parser for identifier or label. Last token matched must be js2-NAME.
8394 Called when we found a name in a statement context. If it's a label, we gather
8395 up any following labels and the next non-label statement into a
8396 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8397 expression and return it wrapped in a `js2-expr-stmt-node'."
8398 (let ((pos js2-token-beg)
8399 (end js2-token-end)
8400 expr
8401 stmt
8402 pn
8403 bundle
8404 (continue t))
8405 ;; set check for label and call down to `js2-parse-primary-expr'
8406 (js2-set-check-for-label)
8407 (setq expr (js2-parse-expr))
8408 (if (/= (js2-node-type expr) js2-LABEL)
8409 ;; Parsed non-label expression - wrap with expression stmt.
8410 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8411 ;; else parsed a label
8412 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8413 (js2-record-label expr bundle)
8414 ;; look for more labels
8415 (while (and continue (= (js2-peek-token) js2-NAME))
8416 (js2-set-check-for-label)
8417 (setq expr (js2-parse-expr))
8418 (if (/= (js2-node-type expr) js2-LABEL)
8419 (progn
8420 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8421 continue nil)
8422 (js2-auto-insert-semicolon stmt))
8423 (js2-record-label expr bundle)))
8424 ;; no more labels; now parse the labeled statement
8425 (unwind-protect
8426 (unless stmt
8427 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8428 (setq stmt (js2-statement-helper))))
8429 ;; remove the labels for this statement from the global set
8430 (dolist (label (js2-labeled-stmt-node-labels bundle))
8431 (setq js2-label-set (remove label js2-label-set))))
8432 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8433 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8434 (js2-node-add-children bundle stmt)
8435 bundle)))
8436
8437 (defun js2-parse-expr-stmt ()
8438 "Default parser in statement context, if no recognized statement found."
8439 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8440
8441 (defun js2-parse-variables (decl-type pos)
8442 "Parse a comma-separated list of variable declarations.
8443 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8444
8445 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8446 For 'var' or 'const', the keyword should be the token last scanned.
8447
8448 POS is the position where the node should start. It's sometimes the
8449 var/const/let keyword, and other times the beginning of the first token
8450 in the first variable declaration.
8451
8452 Returns the parsed `js2-var-decl-node' expression node."
8453 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8454 :pos pos))
8455 destructuring
8456 kid-pos
8457 tt
8458 init
8459 name
8460 end
8461 nbeg nend
8462 vi
8463 (continue t))
8464 ;; Example:
8465 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8466 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8467 ;; var {a, b} = baz;
8468 (while continue
8469 (setq destructuring nil
8470 name nil
8471 tt (js2-peek-token)
8472 kid-pos js2-token-beg
8473 end js2-token-end
8474 init nil)
8475 (if (or (= tt js2-LB) (= tt js2-LC))
8476 ;; Destructuring assignment, e.g., var [a, b] = ...
8477 (setq destructuring (js2-parse-primary-expr-lhs)
8478 end (js2-node-end destructuring))
8479 ;; Simple variable name
8480 (when (js2-must-match js2-NAME "msg.bad.var")
8481 (setq name (js2-create-name-node)
8482 nbeg js2-token-beg
8483 nend js2-token-end
8484 end nend)
8485 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8486 (when (js2-match-token js2-ASSIGN)
8487 (setq init (js2-parse-assign-expr)
8488 end (js2-node-end init))
8489 (if (and js2-parse-ide-mode
8490 (or (js2-object-node-p init)
8491 (js2-function-node-p init)))
8492 (js2-record-imenu-functions init name)))
8493 (when name
8494 (js2-set-face nbeg nend (if (js2-function-node-p init)
8495 'font-lock-function-name-face
8496 'font-lock-variable-name-face)
8497 'record))
8498 (setq vi (make-js2-var-init-node :pos kid-pos
8499 :len (- end kid-pos)
8500 :type decl-type))
8501 (if destructuring
8502 (progn
8503 (if (and (null init) (not js2-in-for-init))
8504 (js2-report-error "msg.destruct.assign.no.init"))
8505 (js2-define-destruct-symbols destructuring
8506 decl-type
8507 'font-lock-variable-name-face)
8508 (setf (js2-var-init-node-target vi) destructuring))
8509 (setf (js2-var-init-node-target vi) name))
8510 (setf (js2-var-init-node-initializer vi) init)
8511 (js2-node-add-children vi name destructuring init)
8512 (js2-block-node-push result vi)
8513 (unless (js2-match-token js2-COMMA)
8514 (setq continue nil)))
8515 (setf (js2-node-len result) (- end pos))
8516 result))
8517
8518 (defun js2-parse-let (pos &optional stmt-p)
8519 "Parse a let expression or statement.
8520 A let-expression is of the form `let (vars) expr'.
8521 A let-statment is of the form `let (vars) {statements}'.
8522 The third form of let is a variable declaration list, handled
8523 by `js2-parse-variables'."
8524 (let ((pn (make-js2-let-node :pos pos))
8525 beg vars body)
8526 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8527 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8528 (js2-push-scope pn)
8529 (unwind-protect
8530 (progn
8531 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8532 (if (js2-must-match js2-RP "msg.no.paren.let")
8533 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8534 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8535 ;; let statement
8536 (progn
8537 (js2-consume-token)
8538 (setf beg js2-token-beg ; position stmt at LC
8539 body (js2-parse-statements))
8540 (js2-must-match js2-RC "msg.no.curly.let")
8541 (setf (js2-node-len body) (- js2-token-end beg)
8542 (js2-node-len pn) (- js2-token-end pos)
8543 (js2-let-node-body pn) body
8544 (js2-node-type pn) js2-LET))
8545 ;; let expression
8546 (setf body (js2-parse-expr)
8547 (js2-node-len pn) (- (js2-node-end body) pos)
8548 (js2-let-node-body pn) body))
8549 (js2-node-add-children pn vars body))
8550 (js2-pop-scope))
8551 pn))
8552
8553 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8554 (js2-scope-put-symbol (or scope js2-current-scope)
8555 name
8556 (make-js2-symbol decl-type name node)))
8557
8558 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8559 "Define a symbol in the current scope.
8560 If NODE is non-nil, it is the AST node associated with the symbol."
8561 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8562 (symbol (if defining-scope
8563 (js2-scope-get-symbol defining-scope name)))
8564 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8565 (cond
8566 ((and symbol ; already defined
8567 (or (= sdt js2-CONST) ; old version is const
8568 (= decl-type js2-CONST) ; new version is const
8569 ;; two let-bound vars in this block have same name
8570 (and (= sdt js2-LET)
8571 (eq defining-scope js2-current-scope))))
8572 (js2-report-error
8573 (cond
8574 ((= sdt js2-CONST) "msg.const.redecl")
8575 ((= sdt js2-LET) "msg.let.redecl")
8576 ((= sdt js2-VAR) "msg.var.redecl")
8577 ((= sdt js2-FUNCTION) "msg.function.redecl")
8578 (t "msg.parm.redecl"))
8579 name))
8580 ((= decl-type js2-LET)
8581 (if (and (not ignore-not-in-block)
8582 (or (= (js2-node-type js2-current-scope) js2-IF)
8583 (js2-loop-node-p js2-current-scope)))
8584 (js2-report-error "msg.let.decl.not.in.block")
8585 (js2-define-new-symbol decl-type name node)))
8586 ((or (= decl-type js2-VAR)
8587 (= decl-type js2-CONST)
8588 (= decl-type js2-FUNCTION))
8589 (if symbol
8590 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8591 (js2-add-strict-warning "msg.var.redecl" name)
8592 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8593 (js2-add-strict-warning "msg.var.hides.arg" name)))
8594 (js2-define-new-symbol decl-type name node
8595 js2-current-script-or-fn)))
8596 ((= decl-type js2-LP)
8597 (if symbol
8598 ;; must be duplicate parameter. Second parameter hides the
8599 ;; first, so go ahead and add the second pararameter
8600 (js2-report-warning "msg.dup.parms" name))
8601 (js2-define-new-symbol decl-type name node))
8602 (t (js2-code-bug)))))
8603
8604 (defun js2-parse-expr (&optional oneshot)
8605 (let* ((pn (js2-parse-assign-expr))
8606 (pos (js2-node-pos pn))
8607 left
8608 right
8609 op-pos)
8610 (while (and (not oneshot)
8611 (js2-match-token js2-COMMA))
8612 (setq op-pos (- js2-token-beg pos)) ; relative
8613 (if (= (js2-peek-token) js2-YIELD)
8614 (js2-report-error "msg.yield.parenthesized"))
8615 (setq right (js2-parse-assign-expr)
8616 left pn
8617 pn (make-js2-infix-node :type js2-COMMA
8618 :pos pos
8619 :len (- js2-ts-cursor pos)
8620 :op-pos op-pos
8621 :left left
8622 :right right))
8623 (js2-node-add-children pn left right))
8624 pn))
8625
8626 (defun js2-parse-assign-expr ()
8627 (let ((tt (js2-peek-token))
8628 (pos js2-token-beg)
8629 pn
8630 left
8631 right
8632 op-pos)
8633 (if (= tt js2-YIELD)
8634 (js2-parse-return-or-yield tt t)
8635 ;; not yield - parse assignment expression
8636 (setq pn (js2-parse-cond-expr)
8637 tt (js2-peek-token))
8638 (when (and (<= js2-first-assign tt)
8639 (<= tt js2-last-assign))
8640 ;; tt express assignment (=, |=, ^=, ..., %=)
8641 (js2-consume-token)
8642 (setq op-pos (- js2-token-beg pos) ; relative
8643 left pn
8644 right (js2-parse-assign-expr)
8645 pn (make-js2-assign-node :type tt
8646 :pos pos
8647 :len (- (js2-node-end right) pos)
8648 :op-pos op-pos
8649 :left left
8650 :right right))
8651 (when js2-parse-ide-mode
8652 (js2-highlight-assign-targets pn left right)
8653 (if (or (js2-function-node-p right)
8654 (js2-object-node-p right))
8655 (js2-record-imenu-functions right left)))
8656 ;; do this last so ide checks above can use absolute positions
8657 (js2-node-add-children pn left right))
8658 pn)))
8659
8660 (defun js2-parse-cond-expr ()
8661 (let ((pos js2-token-beg)
8662 (pn (js2-parse-or-expr))
8663 test-expr
8664 if-true
8665 if-false
8666 q-pos
8667 c-pos)
8668 (when (js2-match-token js2-HOOK)
8669 (setq q-pos (- js2-token-beg pos)
8670 if-true (js2-parse-assign-expr))
8671 (js2-must-match js2-COLON "msg.no.colon.cond")
8672 (setq c-pos (- js2-token-beg pos)
8673 if-false (js2-parse-assign-expr)
8674 test-expr pn
8675 pn (make-js2-cond-node :pos pos
8676 :len (- (js2-node-end if-false) pos)
8677 :test-expr test-expr
8678 :true-expr if-true
8679 :false-expr if-false
8680 :q-pos q-pos
8681 :c-pos c-pos))
8682 (js2-node-add-children pn test-expr if-true if-false))
8683 pn))
8684
8685 (defun js2-make-binary (type left parser)
8686 "Helper for constructing a binary-operator AST node.
8687 LEFT is the left-side-expression, already parsed, and the
8688 binary operator should have just been matched.
8689 PARSER is a function to call to parse the right operand,
8690 or a `js2-node' struct if it has already been parsed."
8691 (let* ((pos (js2-node-pos left))
8692 (op-pos (- js2-token-beg pos))
8693 (right (if (js2-node-p parser)
8694 parser
8695 (funcall parser)))
8696 (pn (make-js2-infix-node :type type
8697 :pos pos
8698 :len (- (js2-node-end right) pos)
8699 :op-pos op-pos
8700 :left left
8701 :right right)))
8702 (js2-node-add-children pn left right)
8703 pn))
8704
8705 (defun js2-parse-or-expr ()
8706 (let ((pn (js2-parse-and-expr)))
8707 (when (js2-match-token js2-OR)
8708 (setq pn (js2-make-binary js2-OR
8709 pn
8710 'js2-parse-or-expr)))
8711 pn))
8712
8713 (defun js2-parse-and-expr ()
8714 (let ((pn (js2-parse-bit-or-expr)))
8715 (when (js2-match-token js2-AND)
8716 (setq pn (js2-make-binary js2-AND
8717 pn
8718 'js2-parse-and-expr)))
8719 pn))
8720
8721 (defun js2-parse-bit-or-expr ()
8722 (let ((pn (js2-parse-bit-xor-expr)))
8723 (while (js2-match-token js2-BITOR)
8724 (setq pn (js2-make-binary js2-BITOR
8725 pn
8726 'js2-parse-bit-xor-expr)))
8727 pn))
8728
8729 (defun js2-parse-bit-xor-expr ()
8730 (let ((pn (js2-parse-bit-and-expr)))
8731 (while (js2-match-token js2-BITXOR)
8732 (setq pn (js2-make-binary js2-BITXOR
8733 pn
8734 'js2-parse-bit-and-expr)))
8735 pn))
8736
8737 (defun js2-parse-bit-and-expr ()
8738 (let ((pn (js2-parse-eq-expr)))
8739 (while (js2-match-token js2-BITAND)
8740 (setq pn (js2-make-binary js2-BITAND
8741 pn
8742 'js2-parse-eq-expr)))
8743 pn))
8744
8745 (defconst js2-parse-eq-ops
8746 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8747
8748 (defun js2-parse-eq-expr ()
8749 (let ((pn (js2-parse-rel-expr))
8750 tt)
8751 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8752 (js2-consume-token)
8753 (setq pn (js2-make-binary tt
8754 pn
8755 'js2-parse-rel-expr)))
8756 pn))
8757
8758 (defconst js2-parse-rel-ops
8759 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8760
8761 (defun js2-parse-rel-expr ()
8762 (let ((pn (js2-parse-shift-expr))
8763 (continue t)
8764 tt)
8765 (while continue
8766 (setq tt (js2-peek-token))
8767 (cond
8768 ((and js2-in-for-init (= tt js2-IN))
8769 (setq continue nil))
8770 ((memq tt js2-parse-rel-ops)
8771 (js2-consume-token)
8772 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8773 (t
8774 (setq continue nil))))
8775 pn))
8776
8777 (defconst js2-parse-shift-ops
8778 (list js2-LSH js2-URSH js2-RSH))
8779
8780 (defun js2-parse-shift-expr ()
8781 (let ((pn (js2-parse-add-expr))
8782 tt
8783 (continue t))
8784 (while continue
8785 (setq tt (js2-peek-token))
8786 (if (memq tt js2-parse-shift-ops)
8787 (progn
8788 (js2-consume-token)
8789 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8790 (setq continue nil)))
8791 pn))
8792
8793 (defun js2-parse-add-expr ()
8794 (let ((pn (js2-parse-mul-expr))
8795 tt
8796 (continue t))
8797 (while continue
8798 (setq tt (js2-peek-token))
8799 (if (or (= tt js2-ADD) (= tt js2-SUB))
8800 (progn
8801 (js2-consume-token)
8802 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8803 (setq continue nil)))
8804 pn))
8805
8806 (defconst js2-parse-mul-ops
8807 (list js2-MUL js2-DIV js2-MOD))
8808
8809 (defun js2-parse-mul-expr ()
8810 (let ((pn (js2-parse-unary-expr))
8811 tt
8812 (continue t))
8813 (while continue
8814 (setq tt (js2-peek-token))
8815 (if (memq tt js2-parse-mul-ops)
8816 (progn
8817 (js2-consume-token)
8818 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8819 (setq continue nil)))
8820 pn))
8821
8822 (defsubst js2-make-unary (type parser &rest args)
8823 "Make a unary node of type TYPE.
8824 PARSER is either a node (for postfix operators) or a function to call
8825 to parse the operand (for prefix operators)."
8826 (let* ((pos js2-token-beg)
8827 (postfix (js2-node-p parser))
8828 (expr (if postfix
8829 parser
8830 (apply parser args)))
8831 end
8832 pn)
8833 (if postfix ; e.g. i++
8834 (setq pos (js2-node-pos expr)
8835 end js2-token-end)
8836 (setq end (js2-node-end expr)))
8837 (setq pn (make-js2-unary-node :type type
8838 :pos pos
8839 :len (- end pos)
8840 :operand expr))
8841 (js2-node-add-children pn expr)
8842 pn))
8843
8844 (defconst js2-incrementable-node-types
8845 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8846 "Node types that can be the operand of a ++ or -- operator.")
8847
8848 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8849 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8850 js2-incrementable-node-types)
8851 (js2-report-error (if (= tt js2-INC)
8852 "msg.bad.incr"
8853 "msg.bad.decr")
8854 nil beg (- end beg))))
8855
8856 (defun js2-parse-unary-expr ()
8857 (let ((tt (js2-peek-token))
8858 pn expr beg end)
8859 (cond
8860 ((or (= tt js2-VOID)
8861 (= tt js2-NOT)
8862 (= tt js2-BITNOT)
8863 (= tt js2-TYPEOF))
8864 (js2-consume-token)
8865 (js2-make-unary tt 'js2-parse-unary-expr))
8866 ((= tt js2-ADD)
8867 (js2-consume-token)
8868 ;; Convert to special POS token in decompiler and parse tree
8869 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8870 ((= tt js2-SUB)
8871 (js2-consume-token)
8872 ;; Convert to special NEG token in decompiler and parse tree
8873 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8874 ((or (= tt js2-INC)
8875 (= tt js2-DEC))
8876 (js2-consume-token)
8877 (prog1
8878 (setq beg js2-token-beg
8879 end js2-token-end
8880 expr (js2-make-unary tt 'js2-parse-member-expr t))
8881 (js2-check-bad-inc-dec tt beg end expr)))
8882 ((= tt js2-DELPROP)
8883 (js2-consume-token)
8884 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8885 ((= tt js2-ERROR)
8886 (js2-consume-token)
8887 (make-js2-error-node)) ; try to continue
8888 ((and (= tt js2-LT)
8889 js2-compiler-xml-available)
8890 ;; XML stream encountered in expression.
8891 (js2-consume-token)
8892 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8893 (t
8894 (setq pn (js2-parse-member-expr t)
8895 ;; Don't look across a newline boundary for a postfix incop.
8896 tt (js2-peek-token-or-eol))
8897 (when (or (= tt js2-INC) (= tt js2-DEC))
8898 (js2-consume-token)
8899 (setf expr pn
8900 pn (js2-make-unary tt expr))
8901 (js2-node-set-prop pn 'postfix t)
8902 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8903 pn))))
8904
8905 (defun js2-parse-xml-initializer ()
8906 "Parse an E4X XML initializer.
8907 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8908 Then I'll postprocess the result, depending on whether we're in IDE
8909 mode or codegen mode, and generate the appropriate rewritten AST.
8910 IDE mode uses a rich AST that models the XML structure. Codegen mode
8911 just concatenates everything and makes a new XML or XMLList out of it."
8912 (let ((tt (js2-get-first-xml-token))
8913 pn-xml
8914 pn
8915 expr
8916 kids
8917 expr-pos
8918 (continue t)
8919 (first-token t))
8920 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8921 (js2-report-error "msg.syntax"))
8922 (setq pn-xml (make-js2-xml-node))
8923 (while continue
8924 (if first-token
8925 (setq first-token nil)
8926 (setq tt (js2-get-next-xml-token)))
8927 (cond
8928 ;; js2-XML means we found a {expr} in the XML stream.
8929 ;; The js2-ts-string is the XML up to the left-curly.
8930 ((= tt js2-XML)
8931 (push (make-js2-string-node :pos js2-token-beg
8932 :len (- js2-ts-cursor js2-token-beg))
8933 kids)
8934 (js2-must-match js2-LC "msg.syntax")
8935 (setq expr-pos js2-ts-cursor
8936 expr (if (eq (js2-peek-token) js2-RC)
8937 (make-js2-empty-expr-node :pos expr-pos)
8938 (js2-parse-expr)))
8939 (js2-must-match js2-RC "msg.syntax")
8940 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8941 :len (js2-node-len expr)
8942 :expr expr))
8943 (js2-node-add-children pn expr)
8944 (push pn kids))
8945 ;; a js2-XMLEND token means we hit the final close-tag.
8946 ((= tt js2-XMLEND)
8947 (push (make-js2-string-node :pos js2-token-beg
8948 :len (- js2-ts-cursor js2-token-beg))
8949 kids)
8950 (dolist (kid (nreverse kids))
8951 (js2-block-node-push pn-xml kid))
8952 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8953 (js2-node-pos pn-xml))
8954 continue nil))
8955 (t
8956 (js2-report-error "msg.syntax")
8957 (setq continue nil))))
8958 pn-xml))
8959
8960
8961 (defun js2-parse-argument-list ()
8962 "Parse an argument list and return it as a lisp list of nodes.
8963 Returns the list in reverse order. Consumes the right-paren token."
8964 (let (result)
8965 (unless (js2-match-token js2-RP)
8966 (loop do
8967 (if (= (js2-peek-token) js2-YIELD)
8968 (js2-report-error "msg.yield.parenthesized"))
8969 (push (js2-parse-assign-expr) result)
8970 while
8971 (js2-match-token js2-COMMA))
8972 (js2-must-match js2-RP "msg.no.paren.arg")
8973 result)))
8974
8975 (defun js2-parse-member-expr (&optional allow-call-syntax)
8976 (let ((tt (js2-peek-token))
8977 pn
8978 pos
8979 target
8980 args
8981 beg
8982 end
8983 init
8984 tail)
8985 (if (/= tt js2-NEW)
8986 (setq pn (js2-parse-primary-expr))
8987 ;; parse a 'new' expression
8988 (js2-consume-token)
8989 (setq pos js2-token-beg
8990 beg pos
8991 target (js2-parse-member-expr)
8992 end (js2-node-end target)
8993 pn (make-js2-new-node :pos pos
8994 :target target
8995 :len (- end pos)))
8996 (js2-node-add-children pn target)
8997 (when (js2-match-token js2-LP)
8998 ;; Add the arguments to pn, if any are supplied.
8999 (setf beg pos ; start of "new" keyword
9000 pos js2-token-beg
9001 args (nreverse (js2-parse-argument-list))
9002 (js2-new-node-args pn) args
9003 end js2-token-end
9004 (js2-new-node-lp pn) (- pos beg)
9005 (js2-new-node-rp pn) (- end 1 beg))
9006 (apply #'js2-node-add-children pn args))
9007 (when (and js2-allow-rhino-new-expr-initializer
9008 (js2-match-token js2-LC))
9009 (setf init (js2-parse-object-literal)
9010 end (js2-node-end init)
9011 (js2-new-node-initializer pn) init)
9012 (js2-node-add-children pn init))
9013 (setf (js2-node-len pn) (- end beg))) ; end outer if
9014 (js2-parse-member-expr-tail allow-call-syntax pn)))
9015
9016 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9017 "Parse a chain of property/array accesses or function calls.
9018 Includes parsing for E4X operators like `..' and `.@'.
9019 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9020 Returns an expression tree that includes PN, the parent node."
9021 (let ((beg (js2-node-pos pn))
9022 tt
9023 (continue t))
9024 (while continue
9025 (setq tt (js2-peek-token))
9026 (cond
9027 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9028 (setq pn (js2-parse-property-access tt pn)))
9029 ((= tt js2-DOTQUERY)
9030 (setq pn (js2-parse-dot-query pn)))
9031 ((= tt js2-LB)
9032 (setq pn (js2-parse-element-get pn)))
9033 ((= tt js2-LP)
9034 (if allow-call-syntax
9035 (setq pn (js2-parse-function-call pn))
9036 (setq continue nil)))
9037 (t
9038 (setq continue nil))))
9039 (if (>= js2-highlight-level 2)
9040 (js2-parse-highlight-member-expr-node pn))
9041 pn))
9042
9043 (defun js2-parse-dot-query (pn)
9044 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9045 Last token parsed must be `js2-DOTQUERY'."
9046 (let ((pos (js2-node-pos pn))
9047 op-pos
9048 expr
9049 end)
9050 (js2-consume-token)
9051 (js2-must-have-xml)
9052 (js2-set-requires-activation)
9053 (setq op-pos js2-token-beg
9054 expr (js2-parse-expr)
9055 end (js2-node-end expr)
9056 pn (make-js2-xml-dot-query-node :left pn
9057 :pos pos
9058 :op-pos op-pos
9059 :right expr))
9060 (js2-node-add-children pn
9061 (js2-xml-dot-query-node-left pn)
9062 (js2-xml-dot-query-node-right pn))
9063 (if (js2-must-match js2-RP "msg.no.paren")
9064 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9065 end js2-token-end))
9066 (setf (js2-node-len pn) (- end pos))
9067 pn))
9068
9069 (defun js2-parse-element-get (pn)
9070 "Parse an element-get expression, e.g. foo[bar].
9071 Last token parsed must be `js2-RB'."
9072 (let ((lb js2-token-beg)
9073 (pos (js2-node-pos pn))
9074 rb
9075 expr)
9076 (js2-consume-token)
9077 (setq expr (js2-parse-expr))
9078 (if (js2-must-match js2-RB "msg.no.bracket.index")
9079 (setq rb js2-token-beg))
9080 (setq pn (make-js2-elem-get-node :target pn
9081 :pos pos
9082 :element expr
9083 :lb (js2-relpos lb pos)
9084 :rb (js2-relpos rb pos)
9085 :len (- js2-token-end pos)))
9086 (js2-node-add-children pn
9087 (js2-elem-get-node-target pn)
9088 (js2-elem-get-node-element pn))
9089 pn))
9090
9091 (defun js2-parse-function-call (pn)
9092 (let (args
9093 (pos (js2-node-pos pn)))
9094 (js2-consume-token)
9095 (setq pn (make-js2-call-node :pos pos
9096 :target pn
9097 :lp (- js2-token-beg pos)))
9098 (js2-node-add-children pn (js2-call-node-target pn))
9099 ;; Add the arguments to pn, if any are supplied.
9100 (setf args (nreverse (js2-parse-argument-list))
9101 (js2-call-node-rp pn) (- js2-token-beg pos)
9102 (js2-call-node-args pn) args)
9103 (apply #'js2-node-add-children pn args)
9104 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9105 pn))
9106
9107 (defun js2-parse-property-access (tt pn)
9108 "Parse a property access, XML descendants access, or XML attr access."
9109 (let ((member-type-flags 0)
9110 (dot-pos js2-token-beg)
9111 (dot-len (if (= tt js2-DOTDOT) 2 1))
9112 name
9113 ref ; right side of . or .. operator
9114 result)
9115 (js2-consume-token)
9116 (when (= tt js2-DOTDOT)
9117 (js2-must-have-xml)
9118 (setq member-type-flags js2-descendants-flag))
9119 (if (not js2-compiler-xml-available)
9120 (progn
9121 (js2-must-match-prop-name "msg.no.name.after.dot")
9122 (setq name (js2-create-name-node t js2-GETPROP)
9123 result (make-js2-prop-get-node :left pn
9124 :pos js2-token-beg
9125 :right name
9126 :len (- js2-token-end
9127 js2-token-beg)))
9128 (js2-node-add-children result pn name)
9129 result)
9130 ;; otherwise look for XML operators
9131 (setf result (if (= tt js2-DOT)
9132 (make-js2-prop-get-node)
9133 (make-js2-infix-node :type js2-DOTDOT))
9134 (js2-node-pos result) (js2-node-pos pn)
9135 (js2-infix-node-op-pos result) dot-pos
9136 (js2-infix-node-left result) pn ; do this after setting position
9137 tt (js2-next-token))
9138 (cond
9139 ;; needed for generator.throw()
9140 ((= tt js2-THROW)
9141 (js2-save-name-token-data js2-token-beg "throw")
9142 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9143 ;; handles: name, ns::name, ns::*, ns::[expr]
9144 ((js2-valid-prop-name-token tt)
9145 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9146 ;; handles: *, *::name, *::*, *::[expr]
9147 ((= tt js2-MUL)
9148 (js2-save-name-token-data js2-token-beg "*")
9149 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9150 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9151 ((= tt js2-XMLATTR)
9152 (setq result (js2-parse-attribute-access)))
9153 (t
9154 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9155 (if ref
9156 (setf (js2-node-len result) (- (js2-node-end ref)
9157 (js2-node-pos result))
9158 (js2-infix-node-right result) ref))
9159 (if (js2-infix-node-p result)
9160 (js2-node-add-children result
9161 (js2-infix-node-left result)
9162 (js2-infix-node-right result)))
9163 result)))
9164
9165 (defun js2-parse-attribute-access ()
9166 "Parse an E4X XML attribute expression.
9167 This includes expressions of the forms:
9168
9169 @attr @ns::attr @ns::*
9170 @* @*::attr @*::*
9171 @[expr] @*::[expr] @ns::[expr]
9172
9173 Called if we peeked an '@' token."
9174 (let ((tt (js2-next-token))
9175 (at-pos js2-token-beg))
9176 (cond
9177 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9178 ((js2-valid-prop-name-token tt)
9179 (js2-parse-property-name at-pos js2-ts-string 0))
9180 ;; handles: @*, @*::name, @*::*, @*::[expr]
9181 ((= tt js2-MUL)
9182 (js2-save-name-token-data js2-token-beg "*")
9183 (js2-parse-property-name js2-token-beg "*" 0))
9184 ;; handles @[expr]
9185 ((= tt js2-LB)
9186 (js2-parse-xml-elem-ref at-pos))
9187 (t
9188 (js2-report-error "msg.no.name.after.xmlAttr")
9189 ;; Avoid cascaded errors that happen if we make an error node here.
9190 (js2-save-name-token-data js2-token-beg "")
9191 (js2-parse-property-name js2-token-beg "" 0)))))
9192
9193 (defun js2-parse-property-name (at-pos s member-type-flags)
9194 "Check if :: follows name in which case it becomes qualified name.
9195
9196 AT-POS is a natural number if we just read an '@' token, else nil.
9197 S is the name or string that was matched: an identifier, 'throw' or '*'.
9198 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9199
9200 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9201 operator, or the name is followed by ::. For a plain name, returns a
9202 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9203 (let ((pos (or at-pos js2-token-beg))
9204 colon-pos
9205 (name (js2-create-name-node t js2-current-token))
9206 ns
9207 tt
9208 ref
9209 pn)
9210 (catch 'return
9211 (when (js2-match-token js2-COLONCOLON)
9212 (setq ns name
9213 colon-pos js2-token-beg
9214 tt (js2-next-token))
9215 (cond
9216 ;; handles name::name
9217 ((js2-valid-prop-name-token tt)
9218 (setq name (js2-create-name-node)))
9219 ;; handles name::*
9220 ((= tt js2-MUL)
9221 (js2-save-name-token-data js2-token-beg "*")
9222 (setq name (js2-create-name-node)))
9223 ;; handles name::[expr]
9224 ((= tt js2-LB)
9225 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9226 (t
9227 (js2-report-error "msg.no.name.after.coloncolon"))))
9228 (if (and (null ns) (zerop member-type-flags))
9229 name
9230 (prog1
9231 (setq pn
9232 (make-js2-xml-prop-ref-node :pos pos
9233 :len (- (js2-node-end name) pos)
9234 :at-pos at-pos
9235 :colon-pos colon-pos
9236 :propname name))
9237 (js2-node-add-children pn name))))))
9238
9239 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9240 "Parse the [expr] portion of an xml element reference.
9241 For instance, @[expr], @*::[expr], or ns::[expr]."
9242 (let* ((lb js2-token-beg)
9243 (pos (or at-pos lb))
9244 rb
9245 (expr (js2-parse-expr))
9246 (end (js2-node-end expr))
9247 pn)
9248 (if (js2-must-match js2-RB "msg.no.bracket.index")
9249 (setq rb js2-token-beg
9250 end js2-token-end))
9251 (prog1
9252 (setq pn
9253 (make-js2-xml-elem-ref-node :pos pos
9254 :len (- end pos)
9255 :namespace namespace
9256 :colon-pos colon-pos
9257 :at-pos at-pos
9258 :expr expr
9259 :lb (js2-relpos lb pos)
9260 :rb (js2-relpos rb pos)))
9261 (js2-node-add-children pn namespace expr))))
9262
9263 (defsubst js2-parse-primary-expr-lhs ()
9264 (let ((js2-is-in-lhs t))
9265 (js2-parse-primary-expr)))
9266
9267 (defun js2-parse-primary-expr ()
9268 "Parses a literal (leaf) expression of some sort.
9269 Includes complex literals such as functions, object-literals,
9270 array-literals, array comprehensions and regular expressions."
9271 (let ((tt-flagged (js2-next-flagged-token))
9272 pn ; parent node (usually return value)
9273 tt
9274 px-pos ; paren-expr pos
9275 len
9276 flags ; regexp flags
9277 expr)
9278 (setq tt js2-current-token)
9279 (cond
9280 ((= tt js2-FUNCTION)
9281 (js2-parse-function 'FUNCTION_EXPRESSION))
9282 ((= tt js2-LB)
9283 (js2-parse-array-literal))
9284 ((= tt js2-LC)
9285 (js2-parse-object-literal))
9286 ((= tt js2-LET)
9287 (js2-parse-let js2-token-beg))
9288 ((= tt js2-LP)
9289 (setq px-pos js2-token-beg
9290 expr (js2-parse-expr))
9291 (js2-must-match js2-RP "msg.no.paren")
9292 (setq pn (make-js2-paren-node :pos px-pos
9293 :expr expr
9294 :len (- js2-token-end px-pos)))
9295 (js2-node-add-children pn (js2-paren-node-expr pn))
9296 pn)
9297 ((= tt js2-XMLATTR)
9298 (js2-must-have-xml)
9299 (js2-parse-attribute-access))
9300 ((= tt js2-NAME)
9301 (js2-parse-name tt-flagged tt))
9302 ((= tt js2-NUMBER)
9303 (make-js2-number-node))
9304 ((= tt js2-STRING)
9305 (prog1
9306 (make-js2-string-node)
9307 (js2-record-face 'font-lock-string-face)))
9308 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9309 ;; Got / or /= which in this context means a regexp literal
9310 (setq px-pos js2-token-beg)
9311 (js2-read-regexp tt)
9312 (setq flags js2-ts-regexp-flags
9313 js2-ts-regexp-flags nil)
9314 (prog1
9315 (make-js2-regexp-node :pos px-pos
9316 :len (- js2-ts-cursor px-pos)
9317 :value js2-ts-string
9318 :flags flags)
9319 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9320 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9321 ((or (= tt js2-NULL)
9322 (= tt js2-THIS)
9323 (= tt js2-FALSE)
9324 (= tt js2-TRUE))
9325 (make-js2-keyword-node :type tt))
9326 ((= tt js2-RESERVED)
9327 (js2-report-error "msg.reserved.id")
9328 (make-js2-name-node))
9329 ((= tt js2-ERROR)
9330 ;; the scanner or one of its subroutines reported the error.
9331 (make-js2-error-node))
9332 ((= tt js2-EOF)
9333 (setq px-pos (point-at-bol)
9334 len (- js2-ts-cursor px-pos))
9335 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9336 (make-js2-error-node :pos px-pos :len len))
9337 (t
9338 (js2-report-error "msg.syntax")
9339 (make-js2-error-node)))))
9340
9341 (defun js2-parse-name (tt-flagged tt)
9342 (let ((name js2-ts-string)
9343 (name-pos js2-token-beg)
9344 node)
9345 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9346 (= (js2-peek-token) js2-COLON))
9347 (prog1
9348 ;; Do not consume colon, it is used as unwind indicator
9349 ;; to return to statementHelper.
9350 (make-js2-label-node :pos name-pos
9351 :len (- js2-token-end name-pos)
9352 :name name)
9353 (js2-set-face name-pos
9354 js2-token-end
9355 'font-lock-variable-name-face 'record))
9356 ;; Otherwise not a label, just a name. Unfortunately peeking
9357 ;; the next token to check for a colon has biffed js2-token-beg
9358 ;; and js2-token-end. We store the name's bounds in buffer vars
9359 ;; and `js2-create-name-node' uses them.
9360 (js2-save-name-token-data name-pos name)
9361 (setq node (if js2-compiler-xml-available
9362 (js2-parse-property-name nil name 0)
9363 (js2-create-name-node 'check-activation)))
9364 (if js2-highlight-external-variables
9365 (js2-record-name-node node))
9366 node)))
9367
9368 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9369 (js2-add-strict-warning
9370 msg nil
9371 ;; back up from comma to beginning of line or array/objlit
9372 (max (if elems
9373 (js2-node-pos (car elems))
9374 pos)
9375 (save-excursion
9376 (goto-char comma-pos)
9377 (back-to-indentation)
9378 (point)))
9379 comma-pos))
9380
9381 (defun js2-parse-array-literal ()
9382 (let ((pos js2-token-beg)
9383 (end js2-token-end)
9384 (after-lb-or-comma t)
9385 after-comma
9386 tt
9387 elems
9388 pn
9389 (continue t))
9390 (unless js2-is-in-lhs
9391 (js2-push-scope (make-js2-scope))) ; for array comp
9392 (while continue
9393 (setq tt (js2-peek-token))
9394 (cond
9395 ;; comma
9396 ((= tt js2-COMMA)
9397 (js2-consume-token)
9398 (setq after-comma js2-token-end)
9399 (if (not after-lb-or-comma)
9400 (setq after-lb-or-comma t)
9401 (push nil elems)))
9402 ;; end of array
9403 ((or (= tt js2-RB)
9404 (= tt js2-EOF)) ; prevent infinite loop
9405 (if (= tt js2-EOF)
9406 (js2-report-error "msg.no.bracket.arg" nil pos)
9407 (js2-consume-token))
9408 (setq continue nil
9409 end js2-token-end
9410 pn (make-js2-array-node :pos pos
9411 :len (- js2-ts-cursor pos)
9412 :elems (nreverse elems)))
9413 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9414 (when after-comma
9415 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9416 pos elems after-comma)))
9417 ;; destructuring binding
9418 (js2-is-in-lhs
9419 (push (if (or (= tt js2-LC)
9420 (= tt js2-LB)
9421 (= tt js2-NAME))
9422 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9423 (js2-parse-primary-expr-lhs)
9424 ;; invalid pattern
9425 (js2-consume-token)
9426 (js2-report-error "msg.bad.var")
9427 (make-js2-error-node))
9428 elems)
9429 (setq after-lb-or-comma nil
9430 after-comma nil))
9431 ;; array comp
9432 ((and (>= js2-language-version 170)
9433 (= tt js2-FOR) ; check for array comprehension
9434 (not after-lb-or-comma) ; "for" can't follow a comma
9435 elems ; must have at least 1 element
9436 (not (cdr elems))) ; but no 2nd element
9437 (setf continue nil
9438 pn (js2-parse-array-comprehension (car elems) pos)))
9439
9440 ;; another element
9441 (t
9442 (unless after-lb-or-comma
9443 (js2-report-error "msg.no.bracket.arg"))
9444 (push (js2-parse-assign-expr) elems)
9445 (setq after-lb-or-comma nil
9446 after-comma nil))))
9447 (unless js2-is-in-lhs
9448 (js2-pop-scope))
9449 pn))
9450
9451 (defun js2-parse-array-comprehension (expr pos)
9452 "Parse a JavaScript 1.7 Array Comprehension.
9453 EXPR is the first expression after the opening left-bracket.
9454 POS is the beginning of the LB token preceding EXPR.
9455 We should have just parsed the 'for' keyword before calling this function."
9456 (let (loops
9457 loop
9458 first
9459 prev
9460 filter
9461 if-pos
9462 result)
9463 (while (= (js2-peek-token) js2-FOR)
9464 (let ((prev (car loops))) ; rearrange scope chain
9465 (push (setq loop (js2-parse-array-comp-loop)) loops)
9466 (if prev ; each loop is parent scope to the next one
9467 (setf (js2-scope-parent-scope loop) prev)
9468 ; first loop takes expr scope's parent
9469 (setf (js2-scope-parent-scope (setq first loop))
9470 (js2-scope-parent-scope js2-current-scope)))))
9471 ;; set expr scope's parent to the last loop
9472 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9473 (when (= (js2-peek-token) js2-IF)
9474 (js2-consume-token)
9475 (setq if-pos (- js2-token-beg pos) ; relative
9476 filter (js2-parse-condition)))
9477 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9478 (setq result (make-js2-array-comp-node :pos pos
9479 :len (- js2-ts-cursor pos)
9480 :result expr
9481 :loops (nreverse loops)
9482 :filter (car filter)
9483 :lp (js2-relpos (second filter) pos)
9484 :rp (js2-relpos (third filter) pos)
9485 :if-pos if-pos))
9486 (apply #'js2-node-add-children result expr (car filter)
9487 (js2-array-comp-node-loops result))
9488 (setq js2-current-scope first) ; pop to the first loop
9489 result))
9490
9491 (defun js2-parse-array-comp-loop ()
9492 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9493 Last token peeked should be the initial FOR."
9494 (let ((pos js2-token-beg)
9495 (pn (make-js2-array-comp-loop-node))
9496 tt
9497 iter
9498 obj
9499 foreach-p
9500 in-pos
9501 each-pos
9502 lp
9503 rp)
9504 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9505 (js2-push-scope pn)
9506 (unwind-protect
9507 (progn
9508 (when (js2-match-token js2-NAME)
9509 (if (string= js2-ts-string "each")
9510 (progn
9511 (setq foreach-p t
9512 each-pos (- js2-token-beg pos)) ; relative
9513 (js2-record-face 'font-lock-keyword-face))
9514 (js2-report-error "msg.no.paren.for")))
9515 (if (js2-must-match js2-LP "msg.no.paren.for")
9516 (setq lp (- js2-token-beg pos)))
9517 (setq tt (js2-peek-token))
9518 (cond
9519 ((or (= tt js2-LB)
9520 (= tt js2-LC))
9521 ;; handle destructuring assignment
9522 (setq iter (js2-parse-primary-expr-lhs))
9523 (js2-define-destruct-symbols iter js2-LET
9524 'font-lock-variable-name-face t))
9525 ((js2-valid-prop-name-token tt)
9526 (js2-consume-token)
9527 (setq iter (js2-create-name-node)))
9528 (t
9529 (js2-report-error "msg.bad.var")))
9530 ;; Define as a let since we want the scope of the variable to
9531 ;; be restricted to the array comprehension
9532 (if (js2-name-node-p iter)
9533 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9534 (if (js2-must-match js2-IN "msg.in.after.for.name")
9535 (setq in-pos (- js2-token-beg pos)))
9536 (setq obj (js2-parse-expr))
9537 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9538 (setq rp (- js2-token-beg pos)))
9539 (setf (js2-node-pos pn) pos
9540 (js2-node-len pn) (- js2-ts-cursor pos)
9541 (js2-array-comp-loop-node-iterator pn) iter
9542 (js2-array-comp-loop-node-object pn) obj
9543 (js2-array-comp-loop-node-in-pos pn) in-pos
9544 (js2-array-comp-loop-node-each-pos pn) each-pos
9545 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9546 (js2-array-comp-loop-node-lp pn) lp
9547 (js2-array-comp-loop-node-rp pn) rp)
9548 (js2-node-add-children pn iter obj))
9549 (js2-pop-scope))
9550 pn))
9551
9552 (defun js2-parse-object-literal ()
9553 (let ((pos js2-token-beg)
9554 tt
9555 elems
9556 result
9557 after-comma
9558 (continue t))
9559 (while continue
9560 (setq tt (js2-peek-token))
9561 (cond
9562 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9563 ((or (js2-valid-prop-name-token tt)
9564 (= tt js2-STRING))
9565 (setq after-comma nil
9566 result (js2-parse-named-prop tt))
9567 (if (and (null result)
9568 (not js2-recover-from-parse-errors))
9569 (setq continue nil)
9570 (push result elems)))
9571 ;; {12: x} or {10.7: x}
9572 ((= tt js2-NUMBER)
9573 (js2-consume-token)
9574 (setq after-comma nil)
9575 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9576 ;; trailing comma
9577 ((= tt js2-RC)
9578 (setq continue nil)
9579 (if after-comma
9580 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9581 pos elems after-comma)))
9582 (t
9583 (js2-report-error "msg.bad.prop")
9584 (unless js2-recover-from-parse-errors
9585 (setq continue nil)))) ; end switch
9586 (if (js2-match-token js2-COMMA)
9587 (setq after-comma js2-token-end)
9588 (setq continue nil))) ; end loop
9589 (js2-must-match js2-RC "msg.no.brace.prop")
9590 (setq result (make-js2-object-node :pos pos
9591 :len (- js2-ts-cursor pos)
9592 :elems (nreverse elems)))
9593 (apply #'js2-node-add-children result (js2-object-node-elems result))
9594 result))
9595
9596 (defun js2-parse-named-prop (tt)
9597 "Parse a name, string, or getter/setter object property.
9598 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9599 (js2-consume-token)
9600 (let ((string-prop (and (= tt js2-STRING)
9601 (make-js2-string-node)))
9602 expr
9603 (ppos js2-token-beg)
9604 (pend js2-token-end)
9605 (name (js2-create-name-node))
9606 (prop js2-ts-string))
9607 (cond
9608 ;; getter/setter prop
9609 ((and (= tt js2-NAME)
9610 (= (js2-peek-token) js2-NAME)
9611 (or (string= prop "get")
9612 (string= prop "set")))
9613 (js2-consume-token)
9614 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9615 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9616 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9617 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9618 ;; abbreviated destructuring bind e.g., {a, b} = c;
9619 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9620 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9621 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9622 ;; assignment but it's difficult because it requires looking ahead of expression.
9623 ((and js2-is-in-lhs
9624 (= tt js2-NAME)
9625 (let ((ctk (js2-peek-token)))
9626 (or (= ctk js2-COMMA)
9627 (= ctk js2-RC)
9628 (js2-valid-prop-name-token ctk))))
9629 name)
9630 ;; regular prop
9631 (t
9632 (prog1
9633 (setq expr (js2-parse-plain-property (or string-prop name)))
9634 (js2-set-face ppos pend
9635 (if (js2-function-node-p
9636 (js2-object-prop-node-right expr))
9637 'font-lock-function-name-face
9638 'font-lock-variable-name-face)
9639 'record))))))
9640
9641 (defun js2-parse-plain-property (prop)
9642 "Parse a non-getter/setter property in an object literal.
9643 PROP is the node representing the property: a number, name or string."
9644 (js2-must-match js2-COLON "msg.no.colon.prop")
9645 (let* ((pos (js2-node-pos prop))
9646 (colon (- js2-token-beg pos))
9647 (expr (js2-parse-assign-expr))
9648 (result (make-js2-object-prop-node
9649 :pos pos
9650 ;; don't include last consumed token in length
9651 :len (- (+ (js2-node-pos expr)
9652 (js2-node-len expr))
9653 pos)
9654 :left prop
9655 :right expr
9656 :op-pos colon)))
9657 (js2-node-add-children result prop expr)
9658 result))
9659
9660 (defun js2-parse-getter-setter-prop (pos prop get-p)
9661 "Parse getter or setter property in an object literal.
9662 JavaScript syntax is:
9663
9664 { get foo() {...}, set foo(x) {...} }
9665
9666 and expression closure style is also supported
9667
9668 { get foo() x, set foo(x) _x = x }
9669
9670 POS is the start position of the `get' or `set' keyword.
9671 PROP is the `js2-name-node' representing the property name.
9672 GET-P is non-nil if the keyword was `get'."
9673 (let ((type (if get-p js2-GET js2-SET))
9674 result
9675 end
9676 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9677 ;; it has to be an anonymous function, as we already parsed the name
9678 (if (/= (js2-node-type fn) js2-FUNCTION)
9679 (js2-report-error "msg.bad.prop")
9680 (if (plusp (length (js2-function-name fn)))
9681 (js2-report-error "msg.bad.prop")))
9682 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9683 (setq end (js2-node-end fn)
9684 result (make-js2-getter-setter-node :type type
9685 :pos pos
9686 :len (- end pos)
9687 :left prop
9688 :right fn))
9689 (js2-node-add-children result prop fn)
9690 result))
9691
9692 (defun js2-create-name-node (&optional check-activation-p token)
9693 "Create a name node using the token info from last scanned name.
9694 In some cases we need to either synthesize a name node, or we lost
9695 the name token information by peeking. If the TOKEN parameter is
9696 not `js2-NAME', then we use the token info saved in instance vars."
9697 (let ((beg js2-token-beg)
9698 (s js2-ts-string)
9699 name)
9700 (when (/= js2-current-token js2-NAME)
9701 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9702 s js2-prev-name-token-string
9703 js2-prev-name-token-start nil
9704 js2-prev-name-token-string nil))
9705 (setq name (make-js2-name-node :pos beg
9706 :name s
9707 :len (length s)))
9708 (if check-activation-p
9709 (js2-check-activation-name s (or token js2-NAME)))
9710 name))
9711
9712 ;;; Indentation support
9713
9714 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9715 ;; Karl cleverly deduces that the desired indentation level is often a
9716 ;; function of paren/bracket/brace nesting depth, which can be determined
9717 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9718 ;; then does some equally clever checks to see if we're in the context of a
9719 ;; substatement of a possibly braceless statement keyword such as if, while,
9720 ;; or finally. This approach yields pretty good results.
9721
9722 ;; The indenter is often "wrong", however, and needs to be overridden.
9723 ;; The right long-term solution is probably to emulate (or integrate
9724 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9725 ;; parse tree from `js2-parse' is present, which is not true at the
9726 ;; moment the user is typing, computing indentation is still thousands
9727 ;; of lines of code to handle every possible syntactic edge case.
9728
9729 ;; In the meantime, the compromise solution is that we offer a "bounce
9730 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9731 ;; current line indent among various likely guess points. This approach
9732 ;; is far from perfect, but should at least make it slightly easier to
9733 ;; move the line towards its desired indentation when manually
9734 ;; overriding Karl's heuristic nesting guesser.
9735
9736 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9737 ;; extensions such as `let' and Array comprehensions. Major kudos to
9738 ;; Karl for coming up with the initial approach, which packs a lot of
9739 ;; punch for so little code.
9740
9741 (defconst js-possibly-braceless-keywords-re
9742 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9743 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9744 "try" "while" "with" "let")))
9745 "Regular expression matching keywords that are optionally
9746 followed by an opening brace.")
9747
9748 (defconst js-indent-operator-re
9749 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9750 (regexp-opt '("in" "instanceof") 'words))
9751 "Regular expression matching operators that affect indentation
9752 of continued expressions.")
9753
9754 (defconst js-declaration-keyword-re
9755 (regexp-opt '("var" "let" "const") 'words)
9756 "Regular expression matching variable declaration keywords.")
9757
9758 ;; This function has horrible results if you're typing an array
9759 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9760 ;; in conjunction with electric-indent, so just disabling it.
9761 (defsubst js2-code-at-bol-p ()
9762 "Return t if the first character on line is non-whitespace."
9763 nil)
9764
9765 (defun js2-insert-and-indent (key)
9766 "Run command bound to key and indent current line. Runs the command
9767 bound to KEY in the global keymap and indents the current line."
9768 (interactive (list (this-command-keys)))
9769 (let ((cmd (lookup-key (current-global-map) key)))
9770 (if (commandp cmd)
9771 (call-interactively cmd)))
9772 ;; don't do the electric keys inside comments or strings,
9773 ;; and don't do bounce-indent with them.
9774 (let ((parse-state (syntax-ppss (point)))
9775 (js2-bounce-indent-p (js2-code-at-bol-p)))
9776 (unless (or (nth 3 parse-state)
9777 (nth 4 parse-state))
9778 (indent-according-to-mode))))
9779
9780 (defun js-re-search-forward-inner (regexp &optional bound count)
9781 "Auxiliary function for `js-re-search-forward'."
9782 (let (parse saved-point)
9783 (while (> count 0)
9784 (re-search-forward regexp bound)
9785 (setq parse (if saved-point
9786 (parse-partial-sexp saved-point (point))
9787 (syntax-ppss (point))))
9788 (cond ((nth 3 parse)
9789 (re-search-forward
9790 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9791 (save-excursion (end-of-line) (point)) t))
9792 ((nth 7 parse)
9793 (forward-line))
9794 ((or (nth 4 parse)
9795 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9796 (re-search-forward "\\*/"))
9797 (t
9798 (setq count (1- count))))
9799 (setq saved-point (point))))
9800 (point))
9801
9802 (defun js-re-search-forward (regexp &optional bound noerror count)
9803 "Search forward but ignore strings and comments. Invokes
9804 `re-search-forward' but treats the buffer as if strings and
9805 comments have been removed."
9806 (let ((saved-point (point))
9807 (search-expr
9808 (cond ((null count)
9809 '(js-re-search-forward-inner regexp bound 1))
9810 ((< count 0)
9811 '(js-re-search-backward-inner regexp bound (- count)))
9812 ((> count 0)
9813 '(js-re-search-forward-inner regexp bound count)))))
9814 (condition-case err
9815 (eval search-expr)
9816 (search-failed
9817 (goto-char saved-point)
9818 (unless noerror
9819 (error (error-message-string err)))))))
9820
9821 (defun js-re-search-backward-inner (regexp &optional bound count)
9822 "Auxiliary function for `js-re-search-backward'."
9823 (let (parse saved-point)
9824 (while (> count 0)
9825 (re-search-backward regexp bound)
9826 (setq parse (if saved-point
9827 (parse-partial-sexp saved-point (point))
9828 (syntax-ppss (point))))
9829 (cond ((nth 3 parse)
9830 (re-search-backward
9831 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9832 (save-excursion (beginning-of-line) (point)) t))
9833 ((nth 7 parse)
9834 (goto-char (nth 8 parse)))
9835 ((or (nth 4 parse)
9836 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9837 (re-search-backward "/\\*"))
9838 (t
9839 (setq count (1- count))))))
9840 (point))
9841
9842 (defun js-re-search-backward (regexp &optional bound noerror count)
9843 "Search backward but ignore strings and comments. Invokes
9844 `re-search-backward' but treats the buffer as if strings and
9845 comments have been removed."
9846 (let ((saved-point (point))
9847 (search-expr
9848 (cond ((null count)
9849 '(js-re-search-backward-inner regexp bound 1))
9850 ((< count 0)
9851 '(js-re-search-forward-inner regexp bound (- count)))
9852 ((> count 0)
9853 '(js-re-search-backward-inner regexp bound count)))))
9854 (condition-case err
9855 (eval search-expr)
9856 (search-failed
9857 (goto-char saved-point)
9858 (unless noerror
9859 (error (error-message-string err)))))))
9860
9861 (defun js-looking-at-operator-p ()
9862 "Return non-nil if text after point is an operator (that is not
9863 a comma)."
9864 (save-match-data
9865 (and (looking-at js-indent-operator-re)
9866 (or (not (looking-at ":"))
9867 (save-excursion
9868 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9869 (looking-at "?")))))))
9870
9871 (defun js-continued-expression-p ()
9872 "Returns non-nil if the current line continues an expression."
9873 (save-excursion
9874 (back-to-indentation)
9875 (or (js-looking-at-operator-p)
9876 ;; comment
9877 (and (js-re-search-backward "\n" nil t)
9878 (progn
9879 (skip-chars-backward " \t")
9880 (backward-char)
9881 (and (js-looking-at-operator-p)
9882 (and (progn (backward-char)
9883 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9884
9885 (defun js-end-of-do-while-loop-p ()
9886 "Returns non-nil if word after point is `while' of a do-while
9887 statement, else returns nil. A braceless do-while statement
9888 spanning several lines requires that the start of the loop is
9889 indented to the same column as the current line."
9890 (interactive)
9891 (save-excursion
9892 (save-match-data
9893 (when (looking-at "\\s-*\\<while\\>")
9894 (if (save-excursion
9895 (skip-chars-backward "[ \t\n]*}")
9896 (looking-at "[ \t\n]*}"))
9897 (save-excursion
9898 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9899 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9900 (or (looking-at "\\<do\\>")
9901 (let ((saved-indent (current-indentation)))
9902 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9903 (/= (current-indentation) saved-indent)))
9904 (and (looking-at "[ \t]*\\<do\\>")
9905 (not (js-re-search-forward
9906 "\\<while\\>" (point-at-eol) t))
9907 (= (current-indentation) saved-indent)))))))))
9908
9909 (defun js-multiline-decl-indentation ()
9910 "Returns the proper indentation of the current line if it belongs
9911 to a multiline declaration statement. All assignments are lined up vertically:
9912
9913 var a = 10,
9914 b = 20,
9915 c = 30;
9916 "
9917 (let (forward-sexp-function ; use lisp version
9918 at-opening-bracket)
9919 (save-excursion
9920 (back-to-indentation)
9921 (when (looking-at (concat js2-mode-identifier-re "[ \t]*=[^=]"))
9922 (while (not (save-excursion
9923 ;; unary ops
9924 (skip-chars-backward "-+~! \t")
9925 (or at-opening-bracket
9926 ;; explicit semicolon
9927 (save-excursion (js2-backward-sws)
9928 (= (char-before) ?\;))
9929 ;; implicit semicolon
9930 (and (bolp)
9931 (progn (js2-backward-sws)
9932 (/= (char-before) ?,))
9933 (progn (skip-chars-backward "[[:punct:]]")
9934 (not (looking-at js-indent-operator-re)))))))
9935 (condition-case err
9936 (backward-sexp)
9937 (scan-error (setq at-opening-bracket t))))
9938 (when (looking-at js-declaration-keyword-re)
9939 (- (1+ (match-end 0)) (point-at-bol)))))))
9940
9941 (defun js-ctrl-statement-indentation ()
9942 "Returns the proper indentation of the current line if it
9943 starts the body of a control statement without braces, else
9944 returns nil."
9945 (let (forward-sexp-function) ; temporarily unbind it
9946 (save-excursion
9947 (back-to-indentation)
9948 (when (and (not (js2-same-line (point-min)))
9949 (not (looking-at "{"))
9950 (js-re-search-backward "[[:graph:]]" nil t)
9951 (not (looking-at "[{([]"))
9952 (progn
9953 (forward-char)
9954 (when (= (char-before) ?\))
9955 ;; scan-sexps sometimes throws an error
9956 (ignore-errors (backward-sexp))
9957 (skip-chars-backward " \t" (point-at-bol)))
9958 (let ((pt (point)))
9959 (back-to-indentation)
9960 (and (looking-at js-possibly-braceless-keywords-re)
9961 (= (match-end 0) pt)
9962 (not (js-end-of-do-while-loop-p))))))
9963 (+ (current-indentation) js2-basic-offset)))))
9964
9965 (defun js2-indent-in-array-comp (parse-status)
9966 "Return non-nil if we think we're in an array comprehension.
9967 In particular, return the buffer position of the first `for' kwd."
9968 (let ((end (point)))
9969 (when (nth 1 parse-status)
9970 (save-excursion
9971 (goto-char (nth 1 parse-status))
9972 (when (looking-at "\\[")
9973 (forward-char 1)
9974 (js2-forward-sws)
9975 (if (looking-at "[[{]")
9976 (let (forward-sexp-function) ; use lisp version
9977 (forward-sexp) ; skip destructuring form
9978 (js2-forward-sws)
9979 (if (and (/= (char-after) ?,) ; regular array
9980 (looking-at "for"))
9981 (match-beginning 0)))
9982 ;; to skip arbitrary expressions we need the parser,
9983 ;; so we'll just guess at it.
9984 (if (re-search-forward "[^,]* \\(for\\) " end t)
9985 (match-beginning 1))))))))
9986
9987 (defun js2-array-comp-indentation (parse-status for-kwd)
9988 (if (js2-same-line for-kwd)
9989 ;; first continuation line
9990 (save-excursion
9991 (goto-char (nth 1 parse-status))
9992 (forward-char 1)
9993 (skip-chars-forward " \t")
9994 (current-column))
9995 (save-excursion
9996 (goto-char for-kwd)
9997 (current-column))))
9998
9999 (defun js-proper-indentation (parse-status)
10000 "Return the proper indentation for the current line."
10001 (save-excursion
10002 (back-to-indentation)
10003 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10004 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10005 (continued-expr-p (js-continued-expression-p))
10006 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10007 (js-multiline-decl-indentation)))
10008 (bracket (nth 1 parse-status))
10009 beg)
10010 (cond
10011 ;; indent array comprehension continuation lines specially
10012 ((and bracket
10013 (not (js2-same-line bracket))
10014 (setq beg (js2-indent-in-array-comp parse-status))
10015 (>= (point) (save-excursion
10016 (goto-char beg)
10017 (point-at-bol)))) ; at or after first loop?
10018 (js2-array-comp-indentation parse-status beg))
10019
10020 (ctrl-stmt-indent)
10021
10022 (declaration-indent)
10023
10024 (bracket
10025 (goto-char bracket)
10026 (cond
10027 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10028 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10029 (when (save-excursion (skip-chars-backward " \t)")
10030 (looking-at ")"))
10031 (backward-list))
10032 (if (and (nth 1 p)
10033 (not js2-consistent-level-indent-inner-bracket-p))
10034 (progn (goto-char (1+ (nth 1 p)))
10035 (skip-chars-forward " \t"))
10036 (back-to-indentation))
10037 (cond (same-indent-p
10038 (current-column))
10039 (continued-expr-p
10040 (+ (current-column) (* 2 js2-basic-offset)))
10041 (t
10042 (+ (current-column) js2-basic-offset)))))
10043 (t
10044 (unless same-indent-p
10045 (forward-char)
10046 (skip-chars-forward " \t"))
10047 (current-column))))
10048
10049 (continued-expr-p js2-basic-offset)
10050
10051 (t 0)))))
10052
10053 (defun js2-lineup-comment (parse-status)
10054 "Indent a multi-line block comment continuation line."
10055 (let* ((beg (nth 8 parse-status))
10056 (first-line (js2-same-line beg))
10057 (offset (save-excursion
10058 (goto-char beg)
10059 (if (looking-at "/\\*")
10060 (+ 1 (current-column))
10061 0))))
10062 (unless first-line
10063 (indent-line-to offset))))
10064
10065 (defun js2-backward-sws ()
10066 "Move backward through whitespace and comments."
10067 (interactive)
10068 (while (forward-comment -1)))
10069
10070 (defun js2-forward-sws ()
10071 "Move forward through whitespace and comments."
10072 (interactive)
10073 (while (forward-comment 1)))
10074
10075 (defsubst js2-current-indent (&optional pos)
10076 "Return column of indentation on current line.
10077 If POS is non-nil, go to that point and return indentation for that line."
10078 (save-excursion
10079 (if pos
10080 (goto-char pos))
10081 (back-to-indentation)
10082 (current-column)))
10083
10084 (defsubst js2-arglist-close ()
10085 "Return non-nil if we're on a line beginning with a close-paren/brace."
10086 (save-match-data
10087 (save-excursion
10088 (goto-char (point-at-bol))
10089 (js2-forward-sws)
10090 (looking-at "[])}]"))))
10091
10092 (defsubst js2-indent-looks-like-label-p ()
10093 (goto-char (point-at-bol))
10094 (js2-forward-sws)
10095 (looking-at (concat js2-mode-identifier-re ":")))
10096
10097 (defun js2-indent-in-objlit-p (parse-status)
10098 "Return non-nil if this looks like an object-literal entry."
10099 (let ((start (nth 1 parse-status)))
10100 (and
10101 start
10102 (save-excursion
10103 (and (zerop (forward-line -1))
10104 (not (< (point) start)) ; crossed a {} boundary
10105 (js2-indent-looks-like-label-p)))
10106 (save-excursion
10107 (js2-indent-looks-like-label-p)))))
10108
10109 ;; if prev line looks like foobar({ then we're passing an object
10110 ;; literal to a function call, and people pretty much always want to
10111 ;; de-dent back to the previous line, so move the 'basic-offset'
10112 ;; position to the front.
10113 (defsubst js2-indent-objlit-arg-p (parse-status)
10114 (save-excursion
10115 (back-to-indentation)
10116 (js2-backward-sws)
10117 (and (eq (1- (point)) (nth 1 parse-status))
10118 (eq (char-before) ?{)
10119 (progn
10120 (forward-char -1)
10121 (skip-chars-backward " \t")
10122 (eq (char-before) ?\()))))
10123
10124 (defsubst js2-indent-case-block-p ()
10125 (save-excursion
10126 (back-to-indentation)
10127 (js2-backward-sws)
10128 (goto-char (point-at-bol))
10129 (skip-chars-forward " \t")
10130 (save-match-data
10131 (looking-at "case\\s-.+:"))))
10132
10133 (defsubst js2-syntax-bol ()
10134 "Return the point at the first non-whitespace char on the line.
10135 Returns `point-at-bol' if the line is empty."
10136 (save-excursion
10137 (beginning-of-line)
10138 (skip-chars-forward " \t")
10139 (point)))
10140
10141 (defun js2-bounce-indent (normal-col parse-status backwards)
10142 "Cycle among alternate computed indentation positions.
10143 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10144 of the buffer to the current point. NORMAL-COL is the indentation
10145 column computed by the heuristic guesser based on current paren,
10146 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10147 in reverse."
10148 (let ((cur-indent (js2-current-indent))
10149 (old-buffer-undo-list buffer-undo-list)
10150 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10151 (current-line (save-excursion
10152 (forward-line 0) ; move to bol
10153 (1+ (count-lines (point-min) (point)))))
10154 positions
10155 pos
10156 main-pos
10157 anchor
10158 arglist-cont
10159 same-indent
10160 prev-line-col
10161 basic-offset
10162 computed-pos)
10163 ;; temporarily don't record undo info, if user requested this
10164 (if js2-mode-indent-inhibit-undo
10165 (setq buffer-undo-list t))
10166 (unwind-protect
10167 (progn
10168 ;; first likely point: indent from beginning of previous code line
10169 (push (setq basic-offset
10170 (+ (save-excursion
10171 (back-to-indentation)
10172 (js2-backward-sws)
10173 (back-to-indentation)
10174 (setq prev-line-col (current-column)))
10175 js2-basic-offset))
10176 positions)
10177
10178 ;; (first + epsilon) likely point: indent 2x from beginning of
10179 ;; previous code line. Some companies like this approach. Ahem.
10180 ;; Seriously, though -- 4-space indent for expression continuation
10181 ;; lines isn't a bad idea. We should eventually implement it
10182 ;; that way.
10183 (push (setq basic-offset
10184 (+ (save-excursion
10185 (back-to-indentation)
10186 (js2-backward-sws)
10187 (back-to-indentation)
10188 (setq prev-line-col (current-column)))
10189 (* 2 js2-basic-offset)))
10190 positions)
10191
10192 ;; second likely point: indent from assign-expr RHS. This
10193 ;; is just a crude guess based on finding " = " on the previous
10194 ;; line containing actual code.
10195 (setq pos (save-excursion
10196 (save-match-data
10197 (forward-line -1)
10198 (goto-char (point-at-bol))
10199 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10200 (point-at-eol) t)
10201 (goto-char (match-end 1))
10202 (skip-chars-forward " \t\r\n")
10203 (current-column)))))
10204 (when pos
10205 (incf pos js2-basic-offset)
10206 (push pos positions))
10207
10208 ;; third likely point: same indent as previous line of code.
10209 ;; Make it the first likely point if we're not on an
10210 ;; arglist-close line and previous line ends in a comma, or
10211 ;; both this line and prev line look like object-literal
10212 ;; elements.
10213 (setq pos (save-excursion
10214 (goto-char (point-at-bol))
10215 (js2-backward-sws)
10216 (back-to-indentation)
10217 (prog1
10218 (current-column)
10219 ;; while we're here, look for trailing comma
10220 (if (save-excursion
10221 (goto-char (point-at-eol))
10222 (js2-backward-sws)
10223 (eq (char-before) ?,))
10224 (setq arglist-cont (1- (point)))))))
10225 (when pos
10226 (if (and (or arglist-cont
10227 (js2-indent-in-objlit-p parse-status))
10228 (not (js2-arglist-close)))
10229 (setq same-indent pos))
10230 (push pos positions))
10231
10232 ;; fourth likely point: first preceding code with less indentation
10233 ;; than the immediately preceding code line.
10234 (setq pos (save-excursion
10235 (back-to-indentation)
10236 (js2-backward-sws)
10237 (back-to-indentation)
10238 (setq anchor (current-column))
10239 (while (and (zerop (forward-line -1))
10240 (>= (progn
10241 (back-to-indentation)
10242 (current-column))
10243 anchor)))
10244 (setq pos (current-column))))
10245 (push pos positions)
10246
10247 ;; nesting-heuristic position, main by default
10248 (push (setq main-pos normal-col) positions)
10249
10250 ;; delete duplicates and sort positions list
10251 (setq positions (sort (delete-dups positions) '<))
10252
10253 ;; comma-list continuation lines: prev line indent takes precedence
10254 (if same-indent
10255 (setq main-pos same-indent))
10256
10257 ;; common special cases where we want to indent in from previous line
10258 (if (or (js2-indent-case-block-p)
10259 (js2-indent-objlit-arg-p parse-status))
10260 (setq main-pos basic-offset))
10261
10262 ;; if bouncing backwards, reverse positions list
10263 (if backwards
10264 (setq positions (reverse positions)))
10265
10266 ;; record whether we're already sitting on one of the alternatives
10267 (setq pos (member cur-indent positions))
10268
10269 (cond
10270 ;; case 0: we're one one of the alternatives and this is the
10271 ;; first time they've pressed TAB on this line (best-guess).
10272 ((and js2-mode-indent-ignore-first-tab
10273 pos
10274 ;; first time pressing TAB on this line?
10275 (not (eq js2-mode-last-indented-line current-line)))
10276 ;; do nothing
10277 (setq computed-pos nil))
10278 ;; case 1: only one computed position => use it
10279 ((null (cdr positions))
10280 (setq computed-pos 0))
10281 ;; case 2: not on any of the computed spots => use main spot
10282 ((not pos)
10283 (setq computed-pos (js2-position main-pos positions)))
10284 ;; case 3: on last position: cycle to first position
10285 ((null (cdr pos))
10286 (setq computed-pos 0))
10287 ;; case 4: on intermediate position: cycle to next position
10288 (t
10289 (setq computed-pos (js2-position (second pos) positions))))
10290
10291 ;; see if any hooks want to indent; otherwise we do it
10292 (loop with result = nil
10293 for hook in js2-indent-hook
10294 while (null result)
10295 do
10296 (setq result (funcall hook positions computed-pos))
10297 finally do
10298 (unless (or result (null computed-pos))
10299 (indent-line-to (nth computed-pos positions)))))
10300
10301 ;; finally
10302 (if js2-mode-indent-inhibit-undo
10303 (setq buffer-undo-list old-buffer-undo-list))
10304 ;; see commentary for `js2-mode-last-indented-line'
10305 (setq js2-mode-last-indented-line current-line))))
10306
10307 (defun js2-indent-bounce-backwards ()
10308 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10309 cycles between the computed indentation positions in reverse order."
10310 (interactive)
10311 (js2-indent-line t))
10312
10313 (defsubst js2-1-line-comment-continuation-p ()
10314 "Return t if we're in a 1-line comment continuation.
10315 If so, we don't ever want to use bounce-indent."
10316 (save-excursion
10317 (save-match-data
10318 (and (progn
10319 (forward-line 0)
10320 (looking-at "\\s-*//"))
10321 (progn
10322 (forward-line -1)
10323 (forward-line 0)
10324 (when (looking-at "\\s-*$")
10325 (js2-backward-sws)
10326 (forward-line 0))
10327 (looking-at "\\s-*//"))))))
10328
10329 (defun js2-indent-line (&optional bounce-backwards)
10330 "Indent the current line as JavaScript source text."
10331 (interactive)
10332 (let (parse-status
10333 current-indent
10334 offset
10335 indent-col
10336 moved
10337 ;; don't whine about errors/warnings when we're indenting.
10338 ;; This has to be set before calling parse-partial-sexp below.
10339 (inhibit-point-motion-hooks t))
10340 (setq parse-status (save-excursion
10341 (syntax-ppss (point-at-bol)))
10342 offset (- (point) (save-excursion
10343 (back-to-indentation)
10344 (setq current-indent (current-column))
10345 (point))))
10346 (js2-with-underscore-as-word-syntax
10347 (if (nth 4 parse-status)
10348 (js2-lineup-comment parse-status)
10349 (setq indent-col (js-proper-indentation parse-status))
10350 ;; see comments below about js2-mode-last-indented-line
10351 (when
10352 (cond
10353 ;; bounce-indenting is disabled during electric-key indent.
10354 ;; It doesn't work well on first line of buffer.
10355 ((and js2-bounce-indent-p
10356 (not (js2-same-line (point-min)))
10357 (not (js2-1-line-comment-continuation-p)))
10358 (js2-bounce-indent indent-col parse-status bounce-backwards)
10359 (setq moved t))
10360 ;; just indent to the guesser's likely spot
10361 ((/= current-indent indent-col)
10362 (indent-line-to indent-col)
10363 (setq moved t)))
10364 (when (and moved (plusp offset))
10365 (forward-char offset)))))))
10366
10367 (defun js2-indent-region (start end)
10368 "Indent the region, but don't use bounce indenting."
10369 (let ((js2-bounce-indent-p nil)
10370 (indent-region-function nil)
10371 (after-change-functions (delq 'js2-mode-edit
10372 after-change-functions)))
10373 (indent-region start end nil) ; nil for byte-compiler
10374 (js2-mode-edit start end (- end start))))
10375
10376 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10377
10378 ;;;###autoload
10379 (defun js2-mode ()
10380 "Major mode for editing JavaScript code."
10381 (interactive)
10382 (kill-all-local-variables)
10383 (set-syntax-table js2-mode-syntax-table)
10384 (use-local-map js2-mode-map)
10385 (make-local-variable 'comment-start)
10386 (make-local-variable 'comment-end)
10387 (make-local-variable 'comment-start-skip)
10388 (setq major-mode 'js2-mode
10389 mode-name "JavaScript-IDE"
10390 comment-start "//" ; used by comment-region; don't change it
10391 comment-end "")
10392 (setq local-abbrev-table js2-mode-abbrev-table)
10393 (set (make-local-variable 'max-lisp-eval-depth)
10394 (max max-lisp-eval-depth 3000))
10395 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10396 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10397
10398 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10399 ;; on most platforms other than the one I originally wrote it on. So it's
10400 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10401 ;; with our binding of the RET key inside comments: short lines stay short.
10402 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10403
10404 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10405 (set (make-local-variable 'next-error-function) #'js2-next-error)
10406 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10407 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10408 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10409 ;; for characters inside regexp literals.
10410 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10411 ;; this is necessary to make `show-paren-function' work properly
10412 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10413 ;; needed for M-x rgrep, among other things
10414 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10415
10416 ;; some variables needed by cc-engine for paragraph-fill, etc.
10417 (setq c-buffer-is-cc-mode t
10418 c-comment-prefix-regexp js2-comment-prefix-regexp
10419 c-comment-start-regexp "/[*/]\\|\\s|"
10420 c-paragraph-start js2-paragraph-start
10421 c-paragraph-separate "$"
10422 comment-start-skip js2-comment-start-skip
10423 c-syntactic-ws-start js2-syntactic-ws-start
10424 c-syntactic-ws-end js2-syntactic-ws-end
10425 c-syntactic-eol js2-syntactic-eol)
10426
10427 (setq js2-default-externs
10428 (append js2-ecma-262-externs
10429 (if js2-include-browser-externs
10430 js2-browser-externs)
10431 (if js2-include-gears-externs
10432 js2-gears-externs)
10433 (if js2-include-rhino-externs
10434 js2-rhino-externs)))
10435
10436 ;; We do our own syntax highlighting based on the parse tree.
10437 ;; However, we want minor modes that add keywords to highlight properly
10438 ;; (examples: doxymacs, column-marker). We do this by not letting
10439 ;; font-lock unfontify anything, and telling it to fontify after we
10440 ;; re-parse and re-highlight the buffer. (We currently don't do any
10441 ;; work with regions other than the whole buffer.)
10442 (dolist (var '(font-lock-unfontify-buffer-function
10443 font-lock-unfontify-region-function))
10444 (set (make-local-variable var) (lambda (&rest args) t)))
10445
10446 ;; Don't let font-lock do syntactic (string/comment) fontification.
10447 (set (make-local-variable #'font-lock-syntactic-face-function)
10448 (lambda (state) nil))
10449
10450 ;; Experiment: make reparse-delay longer for longer files.
10451 (if (plusp js2-dynamic-idle-timer-adjust)
10452 (setq js2-idle-timer-delay
10453 (* js2-idle-timer-delay
10454 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10455
10456 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10457 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10458 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10459 (imenu-add-to-menubar (concat "IM-" mode-name))
10460 (when js2-mirror-mode
10461 (js2-enter-mirror-mode))
10462 (add-to-invisibility-spec '(js2-outline . t))
10463 (set (make-local-variable 'line-move-ignore-invisible) t)
10464 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10465 (setq js2-mode-functions-hidden nil
10466 js2-mode-comments-hidden nil
10467 js2-mode-buffer-dirty-p t
10468 js2-mode-parsing nil)
10469 (js2-reparse)
10470
10471 (if (fboundp 'run-mode-hooks)
10472 (run-mode-hooks 'js2-mode-hook)
10473 (run-hooks 'js2-mode-hook)))
10474
10475 (defun js2-mode-exit ()
10476 "Exit `js2-mode' and clean up."
10477 (interactive)
10478 (when js2-mode-node-overlay
10479 (delete-overlay js2-mode-node-overlay)
10480 (setq js2-mode-node-overlay nil))
10481 (js2-remove-overlays)
10482 (setq js2-mode-ast nil)
10483 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10484 (remove-from-invisibility-spec '(js2-outline . t))
10485 (js2-mode-show-all)
10486 (js2-with-unmodifying-text-property-changes
10487 (js2-clear-face (point-min) (point-max))))
10488
10489 (defun js2-before-save ()
10490 "Clean up whitespace before saving file.
10491 You can disable this by customizing `js2-cleanup-whitespace'."
10492 (when js2-cleanup-whitespace
10493 (let ((col (current-column)))
10494 (delete-trailing-whitespace)
10495 ;; don't change trailing whitespace on current line
10496 (unless (eq (current-column) col)
10497 (indent-to col)))))
10498
10499 (defsubst js2-mode-reset-timer ()
10500 "Cancel any existing parse timer and schedule a new one."
10501 (if js2-mode-parse-timer
10502 (cancel-timer js2-mode-parse-timer))
10503 (setq js2-mode-parsing nil)
10504 (setq js2-mode-parse-timer
10505 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10506
10507 (defun js2-mode-edit (beg end len)
10508 "Schedule a new parse after buffer is edited.
10509 Buffer edit spans from BEG to END and is of length LEN.
10510 Also clears the `js2-magic' bit on autoinserted parens/brackets
10511 if the edit occurred on a line different from the magic paren."
10512 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10513 (line (if magic-pos (line-number-at-pos magic-pos))))
10514 (and line
10515 (or (/= (line-number-at-pos beg) line)
10516 (and (> 0 len)
10517 (/= (line-number-at-pos end) line)))
10518 (js2-mode-mundanify-parens)))
10519 (setq js2-mode-buffer-dirty-p t)
10520 (js2-mode-hide-overlay)
10521 (js2-mode-reset-timer))
10522
10523 (defun js2-mode-run-font-lock ()
10524 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10525 This is intended to allow modes that install their own font-lock keywords
10526 to work with js2-mode. In practice it never seems to work for long.
10527 Hopefully the Emacs maintainers can help figure out a way to make it work."
10528 (when (and (boundp 'font-lock-keywords)
10529 font-lock-keywords
10530 (boundp 'font-lock-mode)
10531 font-lock-mode)
10532 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10533 ;; play nicely with js2-mode. They go out of their way to fail to
10534 ;; provide any option for saying "look, fontify the farging buffer
10535 ;; with just the keywords already". Argh.
10536 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10537 (let (font-lock-verbose)
10538 (font-lock-fontify-buffer))))
10539
10540 (defun js2-reparse (&optional force)
10541 "Re-parse current buffer after user finishes some data entry.
10542 If we get any user input while parsing, including cursor motion,
10543 we discard the parse and reschedule it. If FORCE is nil, then the
10544 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10545 (let (time
10546 interrupted-p
10547 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10548 (unless js2-mode-parsing
10549 (setq js2-mode-parsing t)
10550 (unwind-protect
10551 (when (or js2-mode-buffer-dirty-p force)
10552 (js2-remove-overlays)
10553 (js2-with-unmodifying-text-property-changes
10554 (setq js2-mode-buffer-dirty-p nil
10555 js2-mode-fontifications nil
10556 js2-mode-deferred-properties nil)
10557 (if js2-mode-verbose-parse-p
10558 (message "parsing..."))
10559 (setq time
10560 (js2-time
10561 (setq interrupted-p
10562 (catch 'interrupted
10563 (setq js2-mode-ast (js2-parse))
10564 ;; if parsing is interrupted, comments and regex
10565 ;; literals stay ignored by `parse-partial-sexp'
10566 (remove-text-properties (point-min) (point-max)
10567 '(syntax-table))
10568 (js2-mode-apply-deferred-properties)
10569 (js2-mode-remove-suppressed-warnings)
10570 (js2-mode-show-warnings)
10571 (js2-mode-show-errors)
10572 (js2-mode-run-font-lock) ; note: doesn't work
10573 (js2-mode-highlight-magic-parens)
10574 (if (>= js2-highlight-level 1)
10575 (js2-highlight-jsdoc js2-mode-ast))
10576 nil))))
10577 (if interrupted-p
10578 (progn
10579 ;; unfinished parse => try again
10580 (setq js2-mode-buffer-dirty-p t)
10581 (js2-mode-reset-timer))
10582 (if js2-mode-verbose-parse-p
10583 (message "Parse time: %s" time)))))
10584 (setq js2-mode-parsing nil)
10585 (unless interrupted-p
10586 (setq js2-mode-parse-timer nil))))))
10587
10588 (defun js2-mode-show-node ()
10589 "Debugging aid: highlight selected AST node on mouse click."
10590 (interactive)
10591 (let ((node (js2-node-at-point))
10592 beg
10593 end)
10594 (when js2-mode-show-overlay
10595 (if (null node)
10596 (message "No node found at location %s" (point))
10597 (setq beg (js2-node-abs-pos node)
10598 end (+ beg (js2-node-len node)))
10599 (if js2-mode-node-overlay
10600 (move-overlay js2-mode-node-overlay beg end)
10601 (setq js2-mode-node-overlay (make-overlay beg end))
10602 (overlay-put js2-mode-node-overlay 'face 'highlight))
10603 (js2-with-unmodifying-text-property-changes
10604 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10605 (message "%s, parent: %s"
10606 (js2-node-short-name node)
10607 (if (js2-node-parent node)
10608 (js2-node-short-name (js2-node-parent node))
10609 "nil"))))))
10610
10611 (defun js2-mode-hide-overlay (&optional p1 p2)
10612 "Remove the debugging overlay when the point moves.
10613 P1 and P2 are the old and new values of point, respectively."
10614 (when js2-mode-node-overlay
10615 (let ((beg (overlay-start js2-mode-node-overlay))
10616 (end (overlay-end js2-mode-node-overlay)))
10617 ;; Sometimes we're called spuriously.
10618 (unless (and p2
10619 (>= p2 beg)
10620 (<= p2 end))
10621 (js2-with-unmodifying-text-property-changes
10622 (remove-text-properties beg end '(point-left nil)))
10623 (delete-overlay js2-mode-node-overlay)
10624 (setq js2-mode-node-overlay nil)))))
10625
10626 (defun js2-mode-reset ()
10627 "Debugging helper: reset everything."
10628 (interactive)
10629 (js2-mode-exit)
10630 (js2-mode))
10631
10632 (defsubst js2-mode-show-warn-or-err (e face)
10633 "Highlight a warning or error E with FACE.
10634 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10635 (let* ((key (first e))
10636 (beg (second e))
10637 (end (+ beg (third e)))
10638 ;; Don't inadvertently go out of bounds.
10639 (beg (max (point-min) (min beg (point-max))))
10640 (end (max (point-min) (min end (point-max))))
10641 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10642 (ovl (make-overlay beg end)))
10643 (overlay-put ovl 'face face)
10644 (overlay-put ovl 'js2-error t)
10645 (put-text-property beg end 'help-echo (js2-get-msg key))
10646 (put-text-property beg end 'point-entered #'js2-echo-error)))
10647
10648 (defun js2-remove-overlays ()
10649 "Remove overlays from buffer that have a `js2-error' property."
10650 (let ((beg (point-min))
10651 (end (point-max)))
10652 (save-excursion
10653 (dolist (o (overlays-in beg end))
10654 (when (overlay-get o 'js2-error)
10655 (delete-overlay o))))))
10656
10657 (defun js2-error-at-point (&optional pos)
10658 "Return non-nil if there's an error overlay at POS.
10659 Defaults to point."
10660 (loop with pos = (or pos (point))
10661 for o in (overlays-at pos)
10662 thereis (overlay-get o 'js2-error)))
10663
10664 (defun js2-mode-apply-deferred-properties ()
10665 "Apply fontifications and other text properties recorded during parsing."
10666 (when (plusp js2-highlight-level)
10667 ;; We defer clearing faces as long as possible to eliminate flashing.
10668 (js2-clear-face (point-min) (point-max))
10669 ;; Have to reverse the recorded fontifications list so that errors
10670 ;; and warnings overwrite the normal fontifications.
10671 (dolist (f (nreverse js2-mode-fontifications))
10672 (put-text-property (first f) (second f) 'face (third f)))
10673 (setq js2-mode-fontifications nil))
10674 (dolist (p js2-mode-deferred-properties)
10675 (apply #'put-text-property p))
10676 (setq js2-mode-deferred-properties nil))
10677
10678 (defun js2-mode-show-errors ()
10679 "Highlight syntax errors."
10680 (when js2-mode-show-parse-errors
10681 (dolist (e (js2-ast-root-errors js2-mode-ast))
10682 (js2-mode-show-warn-or-err e 'js2-error-face))))
10683
10684 (defun js2-mode-remove-suppressed-warnings ()
10685 "Take suppressed warnings out of the AST warnings list.
10686 This ensures that the counts and `next-error' are correct."
10687 (setf (js2-ast-root-warnings js2-mode-ast)
10688 (js2-delete-if
10689 (lambda (e)
10690 (let ((key (caar e)))
10691 (or
10692 (and (not js2-strict-trailing-comma-warning)
10693 (string-match "trailing\\.comma" key))
10694 (and (not js2-strict-cond-assign-warning)
10695 (string= key "msg.equal.as.assign"))
10696 (and js2-missing-semi-one-line-override
10697 (string= key "msg.missing.semi")
10698 (let* ((beg (second e))
10699 (node (js2-node-at-point beg))
10700 (fn (js2-mode-find-parent-fn node))
10701 (body (and fn (js2-function-node-body fn)))
10702 (lc (and body (js2-node-abs-pos body)))
10703 (rc (and lc (+ lc (js2-node-len body)))))
10704 (and fn
10705 (or (null body)
10706 (save-excursion
10707 (goto-char beg)
10708 (and (js2-same-line lc)
10709 (js2-same-line rc))))))))))
10710 (js2-ast-root-warnings js2-mode-ast))))
10711
10712 (defun js2-mode-show-warnings ()
10713 "Highlight strict-mode warnings."
10714 (when js2-mode-show-strict-warnings
10715 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10716 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10717
10718 (defun js2-echo-error (old-point new-point)
10719 "Called by point-motion hooks."
10720 (let ((msg (get-text-property new-point 'help-echo)))
10721 (if msg
10722 (message msg))))
10723
10724 (defalias #'js2-echo-help #'js2-echo-error)
10725
10726 (defun js2-enter-key ()
10727 "Handle user pressing the Enter key."
10728 (interactive)
10729 (let ((parse-status (save-excursion
10730 (syntax-ppss (point)))))
10731 (cond
10732 ;; check if we're inside a string
10733 ((nth 3 parse-status)
10734 (js2-mode-split-string parse-status))
10735 ;; check if inside a block comment
10736 ((nth 4 parse-status)
10737 (js2-mode-extend-comment))
10738 (t
10739 ;; should probably figure out what the mode-map says we should do
10740 (if js2-indent-on-enter-key
10741 (let ((js2-bounce-indent-p nil))
10742 (js2-indent-line)))
10743 (insert "\n")
10744 (if js2-enter-indents-newline
10745 (let ((js2-bounce-indent-p nil))
10746 (js2-indent-line)))))))
10747
10748 (defun js2-mode-split-string (parse-status)
10749 "Turn a newline in mid-string into a string concatenation.
10750 PARSE-STATUS is as documented in `parse-partial-sexp'."
10751 (let* ((col (current-column))
10752 (quote-char (nth 3 parse-status))
10753 (quote-string (string quote-char))
10754 (string-beg (nth 8 parse-status))
10755 (indent (save-match-data
10756 (or
10757 (save-excursion
10758 (back-to-indentation)
10759 (if (looking-at "\\+")
10760 (current-column)))
10761 (save-excursion
10762 (goto-char string-beg)
10763 (if (looking-back "\\+\\s-+")
10764 (goto-char (match-beginning 0)))
10765 (current-column))))))
10766 (insert quote-char "\n")
10767 (indent-to indent)
10768 (insert "+ " quote-string)
10769 (when (eolp)
10770 (insert quote-string)
10771 (backward-char 1))))
10772
10773 (defun js2-mode-extend-comment ()
10774 "When inside a comment block, add comment prefix."
10775 (let (star single col first-line needs-close)
10776 (save-excursion
10777 (back-to-indentation)
10778 (cond
10779 ((looking-at "\\*[^/]")
10780 (setq star t
10781 col (current-column)))
10782 ((looking-at "/\\*")
10783 (setq star t
10784 first-line t
10785 col (1+ (current-column))))
10786 ((looking-at "//")
10787 (setq single t
10788 col (current-column)))))
10789 ;; Heuristic for whether we need to close the comment:
10790 ;; if we've got a parse error here, assume it's an unterminated
10791 ;; comment.
10792 (setq needs-close
10793 (or
10794 (eq (get-text-property (1- (point)) 'point-entered)
10795 'js2-echo-error)
10796 ;; The heuristic above doesn't work well when we're
10797 ;; creating a comment and there's another one downstream,
10798 ;; as our parser thinks this one ends at the end of the
10799 ;; next one. (You can have a /* inside a js block comment.)
10800 ;; So just close it if the next non-ws char isn't a *.
10801 (and first-line
10802 (eolp)
10803 (save-excursion
10804 (skip-chars-forward " \t\r\n")
10805 (not (eq (char-after) ?*))))))
10806 (insert "\n")
10807 (cond
10808 (star
10809 (indent-to col)
10810 (insert "* ")
10811 (if (and first-line needs-close)
10812 (save-excursion
10813 (insert "\n")
10814 (indent-to col)
10815 (insert "*/"))))
10816 (single
10817 (when (save-excursion
10818 (and (zerop (forward-line 1))
10819 (looking-at "\\s-*//")))
10820 (indent-to col)
10821 (insert "// "))))))
10822
10823 (defun js2-beginning-of-line ()
10824 "Toggles point between bol and first non-whitespace char in line.
10825 Also moves past comment delimiters when inside comments."
10826 (interactive)
10827 (let (node beg)
10828 (cond
10829 ((bolp)
10830 (back-to-indentation))
10831 ((looking-at "//")
10832 (skip-chars-forward "/ \t"))
10833 ((and (eq (char-after) ?*)
10834 (setq node (js2-comment-at-point))
10835 (memq (js2-comment-node-format node) '(jsdoc block))
10836 (save-excursion
10837 (skip-chars-backward " \t")
10838 (bolp)))
10839 (skip-chars-forward "\* \t"))
10840 (t
10841 (goto-char (point-at-bol))))))
10842
10843 (defun js2-end-of-line ()
10844 "Toggles point between eol and last non-whitespace char in line."
10845 (interactive)
10846 (if (eolp)
10847 (skip-chars-backward " \t")
10848 (goto-char (point-at-eol))))
10849
10850 (defun js2-enter-mirror-mode()
10851 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10852 on insertion."
10853 (interactive)
10854 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10855 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10856 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10857 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10858 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10859 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10860 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10861 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10862
10863 (defun js2-leave-mirror-mode()
10864 "Turns off mirror mode."
10865 (interactive)
10866 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10867 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10868
10869 (defsubst js2-mode-inside-string ()
10870 "Return non-nil if inside a string.
10871 Actually returns the quote character that begins the string."
10872 (let ((parse-state (save-excursion
10873 (syntax-ppss (point)))))
10874 (nth 3 parse-state)))
10875
10876 (defsubst js2-mode-inside-comment-or-string ()
10877 "Return non-nil if inside a comment or string."
10878 (or
10879 (let ((comment-start
10880 (save-excursion
10881 (goto-char (point-at-bol))
10882 (if (re-search-forward "//" (point-at-eol) t)
10883 (match-beginning 0)))))
10884 (and comment-start
10885 (<= comment-start (point))))
10886 (let ((parse-state (save-excursion
10887 (syntax-ppss (point)))))
10888 (or (nth 3 parse-state)
10889 (nth 4 parse-state)))))
10890
10891 (defsubst js2-make-magic-delimiter (delim &optional pos)
10892 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10893 Sets value of `js2-magic' text property to line number at POS."
10894 (propertize delim
10895 'js2-magic (line-number-at-pos pos)
10896 'face 'js2-magic-paren-face))
10897
10898 (defun js2-mode-match-delimiter (open close)
10899 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10900 The rule we use, which as far as we can tell is how Eclipse works,
10901 is that we insert the match if we're not in a comment or string,
10902 and the next non-whitespace character is either punctuation or
10903 occurs on another line."
10904 (insert open)
10905 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10906 (not (js2-mode-inside-comment-or-string)))
10907 (save-excursion
10908 (insert (js2-make-magic-delimiter close)))
10909 (when js2-auto-indent-p
10910 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10911 (js2-indent-line)))))
10912
10913 (defun js2-mode-match-bracket ()
10914 "Insert matching bracket."
10915 (interactive)
10916 (js2-mode-match-delimiter "[" "]"))
10917
10918 (defun js2-mode-match-paren ()
10919 "Insert matching paren unless already inserted."
10920 (interactive)
10921 (js2-mode-match-delimiter "(" ")"))
10922
10923 (defun js2-mode-match-curly (arg)
10924 "Insert matching curly-brace.
10925 With prefix arg, no formatting or indentation will occur -- the close-brace
10926 is simply inserted directly at the point."
10927 (interactive "p")
10928 (let (try-pos)
10929 (cond
10930 (current-prefix-arg
10931 (js2-mode-match-delimiter "{" "}"))
10932 ((and js2-auto-insert-catch-block
10933 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10934 (point-at-bol))
10935 (match-beginning 1))))
10936 (js2-insert-catch-skel try-pos))
10937 (t
10938 ;; Otherwise try to do something smarter.
10939 (insert "{")
10940 (unless (or (not (looking-at "\\s-*$"))
10941 (save-excursion
10942 (skip-chars-forward " \t\r\n")
10943 (and (looking-at "}")
10944 (js2-error-at-point)))
10945 (js2-mode-inside-comment-or-string))
10946 (undo-boundary)
10947 ;; absolutely mystifying bug: when inserting the next "\n",
10948 ;; the buffer-undo-list is given two new entries: the inserted range,
10949 ;; and the incorrect position of the point. It's recorded incorrectly
10950 ;; as being before the opening "{", not after it. But it's recorded
10951 ;; as the correct value if you're debugging `js2-mode-match-curly'
10952 ;; in edebug. I have no idea why it's doing this, but incrementing
10953 ;; the inserted position fixes the problem, so that the undo takes us
10954 ;; back to just after the user-inserted "{".
10955 (insert "\n")
10956 (ignore-errors
10957 (incf (cadr buffer-undo-list)))
10958 (js2-indent-line)
10959 (save-excursion
10960 (insert "\n}")
10961 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10962 (js2-indent-line))))))))
10963
10964 (defun js2-insert-catch-skel (try-pos)
10965 "Complete a try/catch block after inserting a { following a try keyword.
10966 Rationale is that a try always needs a catch or a finally, and the catch is
10967 the more likely of the two.
10968
10969 TRY-POS is the buffer position of the try keyword. The open-curly should
10970 already have been inserted."
10971 (insert "{")
10972 (let ((try-col (save-excursion
10973 (goto-char try-pos)
10974 (current-column))))
10975 (insert "\n")
10976 (undo-boundary)
10977 (js2-indent-line) ;; indent the blank line where cursor will end up
10978 (save-excursion
10979 (insert "\n")
10980 (indent-to try-col)
10981 (insert "} catch (x) {\n\n")
10982 (indent-to try-col)
10983 (insert "}"))))
10984
10985 (defun js2-mode-highlight-magic-parens ()
10986 "Re-highlight magic parens after parsing nukes the 'face prop."
10987 (let ((beg (point-min))
10988 end)
10989 (while (setq beg (next-single-property-change beg 'js2-magic))
10990 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10991 (if (get-text-property beg 'js2-magic)
10992 (js2-with-unmodifying-text-property-changes
10993 (put-text-property beg (or end (1+ beg))
10994 'face 'js2-magic-paren-face))))))
10995
10996 (defun js2-mode-mundanify-parens ()
10997 "Clear all magic parens and brackets."
10998 (let ((beg (point-min))
10999 end)
11000 (while (setq beg (next-single-property-change beg 'js2-magic))
11001 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11002 (remove-text-properties beg (or end (1+ beg))
11003 '(js2-magic face)))))
11004
11005 (defsubst js2-match-quote (quote-string)
11006 (let ((start-quote (js2-mode-inside-string)))
11007 (cond
11008 ;; inside a comment - don't do quote-matching, since we can't
11009 ;; reliably figure out if we're in a string inside the comment
11010 ((js2-comment-at-point)
11011 (insert quote-string))
11012 ((not start-quote)
11013 ;; not in string => insert matched quotes
11014 (insert quote-string)
11015 ;; exception: if we're just before a word, don't double it.
11016 (unless (looking-at "[^ \t\r\n]")
11017 (save-excursion
11018 (insert quote-string))))
11019 ((looking-at quote-string)
11020 (if (looking-back "[^\\]\\\\")
11021 (insert quote-string)
11022 (forward-char 1)))
11023 ((and js2-mode-escape-quotes
11024 (save-excursion
11025 (save-match-data
11026 (re-search-forward quote-string (point-at-eol) t))))
11027 ;; inside terminated string, escape quote (unless already escaped)
11028 (insert (if (looking-back "[^\\]\\\\")
11029 quote-string
11030 (concat "\\" quote-string))))
11031 (t
11032 (insert quote-string))))) ; else terminate the string
11033
11034 (defun js2-mode-match-single-quote ()
11035 "Insert matching single-quote."
11036 (interactive)
11037 (let ((parse-status (syntax-ppss (point))))
11038 ;; don't match inside comments, since apostrophe is more common
11039 (if (nth 4 parse-status)
11040 (insert "'")
11041 (js2-match-quote "'"))))
11042
11043 (defun js2-mode-match-double-quote ()
11044 "Insert matching double-quote."
11045 (interactive)
11046 (js2-match-quote "\""))
11047
11048 ;; Eclipse works as follows:
11049 ;; * type an open-paren and it auto-inserts close-paren
11050 ;; - auto-inserted paren gets a green bracket
11051 ;; - green bracket means typing close-paren there will skip it
11052 ;; * if you insert any text on a different line, it turns off
11053 (defun js2-mode-magic-close-paren ()
11054 "Skip over close-paren rather than inserting, where appropriate."
11055 (interactive)
11056 (let* ((here (point))
11057 (parse-status (syntax-ppss here))
11058 (open-pos (nth 1 parse-status))
11059 (close last-input-event)
11060 (open (cond
11061 ((eq close ?\))
11062 ?\()
11063 ((eq close ?\])
11064 ?\[)
11065 ((eq close ?})
11066 ?{)
11067 (t nil))))
11068 (if (and (eq (char-after) close)
11069 (eq open (char-after open-pos))
11070 (js2-same-line open-pos)
11071 (get-text-property here 'js2-magic))
11072 (progn
11073 (remove-text-properties here (1+ here) '(js2-magic face))
11074 (forward-char 1))
11075 (insert-char close 1))
11076 (blink-matching-open)))
11077
11078 (defun js2-mode-wait-for-parse (callback)
11079 "Invoke CALLBACK when parsing is finished.
11080 If parsing is already finished, calls CALLBACK immediately."
11081 (if (not js2-mode-buffer-dirty-p)
11082 (funcall callback)
11083 (push callback js2-mode-pending-parse-callbacks)
11084 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11085
11086 (defun js2-mode-parse-finished ()
11087 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11088 ;; We can't let errors propagate up, since it prevents the
11089 ;; `js2-parse' method from completing normally and returning
11090 ;; the ast, which makes things mysteriously not work right.
11091 (unwind-protect
11092 (dolist (cb js2-mode-pending-parse-callbacks)
11093 (condition-case err
11094 (funcall cb)
11095 (error (message "%s" err))))
11096 (setq js2-mode-pending-parse-callbacks nil)))
11097
11098 (defun js2-mode-flag-region (from to flag)
11099 "Hide or show text from FROM to TO, according to FLAG.
11100 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11101 Returns the created overlay if FLAG is non-nil."
11102 (remove-overlays from to 'invisible 'js2-outline)
11103 (when flag
11104 (let ((o (make-overlay from to)))
11105 (overlay-put o 'invisible 'js2-outline)
11106 (overlay-put o 'isearch-open-invisible
11107 'js2-isearch-open-invisible)
11108 o)))
11109
11110 ;; Function to be set as an outline-isearch-open-invisible' property
11111 ;; to the overlay that makes the outline invisible (see
11112 ;; `js2-mode-flag-region').
11113 (defun js2-isearch-open-invisible (overlay)
11114 ;; We rely on the fact that isearch places point on the matched text.
11115 (js2-mode-show-element))
11116
11117 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11118 "Return cons cell of bounds of folding overlay at POS.
11119 Returns nil if not found."
11120 (let ((overlays (overlays-at (or pos (point))))
11121 o)
11122 (while (and overlays
11123 (not o))
11124 (if (overlay-get (car overlays) 'invisible)
11125 (setq o (car overlays))
11126 (setq overlays (cdr overlays))))
11127 (if o
11128 (cons (overlay-start o) (overlay-end o)))))
11129
11130 (defun js2-mode-function-at-point (&optional pos)
11131 "Return the innermost function node enclosing current point.
11132 Returns nil if point is not in a function."
11133 (let ((node (js2-node-at-point pos)))
11134 (while (and node (not (js2-function-node-p node)))
11135 (setq node (js2-node-parent node)))
11136 (if (js2-function-node-p node)
11137 node)))
11138
11139 (defun js2-mode-toggle-element ()
11140 "Hide or show the foldable element at the point."
11141 (interactive)
11142 (let (comment fn pos)
11143 (save-excursion
11144 (save-match-data
11145 (cond
11146 ;; /* ... */ comment?
11147 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11148 (if (js2-mode-invisible-overlay-bounds
11149 (setq pos (+ 3 (js2-node-abs-pos comment))))
11150 (progn
11151 (goto-char pos)
11152 (js2-mode-show-element))
11153 (js2-mode-hide-element)))
11154 ;; //-comment?
11155 ((save-excursion
11156 (back-to-indentation)
11157 (looking-at js2-mode-//-comment-re))
11158 (js2-mode-toggle-//-comment))
11159 ;; function?
11160 ((setq fn (js2-mode-function-at-point))
11161 (setq pos (and (js2-function-node-body fn)
11162 (js2-node-abs-pos (js2-function-node-body fn))))
11163 (goto-char (1+ pos))
11164 (if (js2-mode-invisible-overlay-bounds)
11165 (js2-mode-show-element)
11166 (js2-mode-hide-element)))
11167 (t
11168 (message "Nothing at point to hide or show")))))))
11169
11170 (defun js2-mode-hide-element ()
11171 "Fold/hide contents of a block, showing ellipses.
11172 Show the hidden text with \\[js2-mode-show-element]."
11173 (interactive)
11174 (if js2-mode-buffer-dirty-p
11175 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11176 (let (node body beg end)
11177 (cond
11178 ((js2-mode-invisible-overlay-bounds)
11179 (message "already hidden"))
11180 (t
11181 (setq node (js2-node-at-point))
11182 (cond
11183 ((js2-block-comment-p node)
11184 (js2-mode-hide-comment node))
11185 (t
11186 (while (and node (not (js2-function-node-p node)))
11187 (setq node (js2-node-parent node)))
11188 (if (and node
11189 (setq body (js2-function-node-body node)))
11190 (progn
11191 (setq beg (js2-node-abs-pos body)
11192 end (+ beg (js2-node-len body)))
11193 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11194 (message "No collapsable element found at point"))))))))
11195
11196 (defun js2-mode-show-element ()
11197 "Show the hidden element at current point."
11198 (interactive)
11199 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11200 (if bounds
11201 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11202 (message "Nothing to un-hide"))))
11203
11204 (defun js2-mode-show-all ()
11205 "Show all of the text in the buffer."
11206 (interactive)
11207 (js2-mode-flag-region (point-min) (point-max) nil))
11208
11209 (defun js2-mode-toggle-hide-functions ()
11210 (interactive)
11211 (if js2-mode-functions-hidden
11212 (js2-mode-show-functions)
11213 (js2-mode-hide-functions)))
11214
11215 (defun js2-mode-hide-functions ()
11216 "Hides all non-nested function bodies in the buffer.
11217 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11218 to open an individual entry."
11219 (interactive)
11220 (if js2-mode-buffer-dirty-p
11221 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11222 (if (null js2-mode-ast)
11223 (message "Oops - parsing failed")
11224 (setq js2-mode-functions-hidden t)
11225 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11226
11227 (defun js2-mode-function-hider (n endp)
11228 (when (not endp)
11229 (let ((tt (js2-node-type n))
11230 body beg end)
11231 (cond
11232 ((and (= tt js2-FUNCTION)
11233 (setq body (js2-function-node-body n)))
11234 (setq beg (js2-node-abs-pos body)
11235 end (+ beg (js2-node-len body)))
11236 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11237 nil) ; don't process children of function
11238 (t
11239 t))))) ; keep processing other AST nodes
11240
11241 (defun js2-mode-show-functions ()
11242 "Un-hide any folded function bodies in the buffer."
11243 (interactive)
11244 (setq js2-mode-functions-hidden nil)
11245 (save-excursion
11246 (goto-char (point-min))
11247 (while (/= (goto-char (next-overlay-change (point)))
11248 (point-max))
11249 (dolist (o (overlays-at (point)))
11250 (when (and (overlay-get o 'invisible)
11251 (not (overlay-get o 'comment)))
11252 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11253
11254 (defun js2-mode-hide-comment (n)
11255 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11256 3 ; /**
11257 2)) ; /*
11258 (beg (+ (js2-node-abs-pos n) head))
11259 (end (- (+ beg (js2-node-len n)) head 2))
11260 (o (js2-mode-flag-region beg end 'hide)))
11261 (overlay-put o 'comment t)))
11262
11263 (defun js2-mode-toggle-hide-comments ()
11264 "Folds all block comments in the buffer.
11265 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11266 to open an individual entry."
11267 (interactive)
11268 (if js2-mode-comments-hidden
11269 (js2-mode-show-comments)
11270 (js2-mode-hide-comments)))
11271
11272 (defun js2-mode-hide-comments ()
11273 (interactive)
11274 (if js2-mode-buffer-dirty-p
11275 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11276 (if (null js2-mode-ast)
11277 (message "Oops - parsing failed")
11278 (setq js2-mode-comments-hidden t)
11279 (dolist (n (js2-ast-root-comments js2-mode-ast))
11280 (let ((format (js2-comment-node-format n)))
11281 (when (js2-block-comment-p n)
11282 (js2-mode-hide-comment n))))
11283 (js2-mode-hide-//-comments)))
11284
11285 (defsubst js2-mode-extend-//-comment (direction)
11286 "Find start or end of a block of similar //-comment lines.
11287 DIRECTION is -1 to look back, 1 to look forward.
11288 INDENT is the indentation level to match.
11289 Returns the end-of-line position of the furthest adjacent
11290 //-comment line with the same indentation as the current line.
11291 If there is no such matching line, returns current end of line."
11292 (let ((pos (point-at-eol))
11293 (indent (current-indentation)))
11294 (save-excursion
11295 (save-match-data
11296 (while (and (zerop (forward-line direction))
11297 (looking-at js2-mode-//-comment-re)
11298 (eq indent (length (match-string 1))))
11299 (setq pos (point-at-eol)))
11300 pos))))
11301
11302 (defun js2-mode-hide-//-comments ()
11303 "Fold adjacent 1-line comments, showing only snippet of first one."
11304 (let (beg end)
11305 (save-excursion
11306 (save-match-data
11307 (goto-char (point-min))
11308 (while (re-search-forward js2-mode-//-comment-re nil t)
11309 (setq beg (point)
11310 end (js2-mode-extend-//-comment 1))
11311 (unless (eq beg end)
11312 (overlay-put (js2-mode-flag-region beg end 'hide)
11313 'comment t))
11314 (goto-char end)
11315 (forward-char 1))))))
11316
11317 (defun js2-mode-toggle-//-comment ()
11318 "Fold or un-fold any multi-line //-comment at point.
11319 Caller should have determined that this line starts with a //-comment."
11320 (let* ((beg (point-at-eol))
11321 (end beg))
11322 (save-excursion
11323 (goto-char end)
11324 (if (js2-mode-invisible-overlay-bounds)
11325 (js2-mode-show-element)
11326 ;; else hide the comment
11327 (setq beg (js2-mode-extend-//-comment -1)
11328 end (js2-mode-extend-//-comment 1))
11329 (unless (eq beg end)
11330 (overlay-put (js2-mode-flag-region beg end 'hide)
11331 'comment t))))))
11332
11333 (defun js2-mode-show-comments ()
11334 "Un-hide any hidden comments, leaving other hidden elements alone."
11335 (interactive)
11336 (setq js2-mode-comments-hidden nil)
11337 (save-excursion
11338 (goto-char (point-min))
11339 (while (/= (goto-char (next-overlay-change (point)))
11340 (point-max))
11341 (dolist (o (overlays-at (point)))
11342 (when (overlay-get o 'comment)
11343 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11344
11345 (defun js2-mode-display-warnings-and-errors ()
11346 "Turn on display of warnings and errors."
11347 (interactive)
11348 (setq js2-mode-show-parse-errors t
11349 js2-mode-show-strict-warnings t)
11350 (js2-reparse 'force))
11351
11352 (defun js2-mode-hide-warnings-and-errors ()
11353 "Turn off display of warnings and errors."
11354 (interactive)
11355 (setq js2-mode-show-parse-errors nil
11356 js2-mode-show-strict-warnings nil)
11357 (js2-reparse 'force))
11358
11359 (defun js2-mode-toggle-warnings-and-errors ()
11360 "Toggle the display of warnings and errors.
11361 Some users don't like having warnings/errors reported while they type."
11362 (interactive)
11363 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11364 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11365 (if (interactive-p)
11366 (message "warnings and errors %s"
11367 (if js2-mode-show-parse-errors
11368 "enabled"
11369 "disabled")))
11370 (js2-reparse 'force))
11371
11372 (defun js2-mode-customize ()
11373 (interactive)
11374 (customize-group 'js2-mode))
11375
11376 (defun js2-mode-forward-sexp (&optional arg)
11377 "Move forward across one statement or balanced expression.
11378 With ARG, do it that many times. Negative arg -N means
11379 move backward across N balanced expressions."
11380 (interactive "p")
11381 (setq arg (or arg 1))
11382 (if js2-mode-buffer-dirty-p
11383 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11384 (let (node end (start (point)))
11385 (cond
11386 ;; backward-sexp
11387 ;; could probably make this better for some cases:
11388 ;; - if in statement block (e.g. function body), go to parent
11389 ;; - infix exprs like (foo in bar) - maybe go to beginning
11390 ;; of infix expr if in the right-side expression?
11391 ((and arg (minusp arg))
11392 (dotimes (i (- arg))
11393 (js2-backward-sws)
11394 (forward-char -1) ; enter the node we backed up to
11395 (setq node (js2-node-at-point (point) t))
11396 (goto-char (if node
11397 (js2-node-abs-pos node)
11398 (point-min)))))
11399 (t
11400 ;; forward-sexp
11401 (js2-forward-sws)
11402 (dotimes (i arg)
11403 (js2-forward-sws)
11404 (setq node (js2-node-at-point (point) t)
11405 end (if node (+ (js2-node-abs-pos node)
11406 (js2-node-len node))))
11407 (goto-char (or end (point-max))))))))
11408
11409 (defun js2-next-error (&optional arg reset)
11410 "Move to next parse error.
11411 Typically invoked via \\[next-error].
11412 ARG is the number of errors, forward or backward, to move.
11413 RESET means start over from the beginning."
11414 (interactive "p")
11415 (if (or (null js2-mode-ast)
11416 (and (null (js2-ast-root-errors js2-mode-ast))
11417 (null (js2-ast-root-warnings js2-mode-ast))))
11418 (message "No errors")
11419 (when reset
11420 (goto-char (point-min)))
11421 (let* ((errs (copy-sequence
11422 (append (js2-ast-root-errors js2-mode-ast)
11423 (js2-ast-root-warnings js2-mode-ast))))
11424 (continue t)
11425 (start (point))
11426 (count (or arg 1))
11427 (backward (minusp count))
11428 (sorter (if backward '> '<))
11429 (stopper (if backward '< '>))
11430 (count (abs count))
11431 all-errs
11432 err)
11433 ;; sort by start position
11434 (setq errs (sort errs (lambda (e1 e2)
11435 (funcall sorter (second e1) (second e2))))
11436 all-errs errs)
11437 ;; find nth error with pos > start
11438 (while (and errs continue)
11439 (when (funcall stopper (cadar errs) start)
11440 (setq err (car errs))
11441 (if (zerop (decf count))
11442 (setq continue nil)))
11443 (setq errs (cdr errs)))
11444 (if err
11445 (goto-char (second err))
11446 ;; wrap around to first error
11447 (goto-char (second (car all-errs)))
11448 ;; if we were already on it, echo msg again
11449 (if (= (point) start)
11450 (js2-echo-error (point) (point)))))))
11451
11452 (defun js2-down-mouse-3 ()
11453 "Make right-click move the point to the click location.
11454 This makes right-click context menu operations a bit more intuitive.
11455 The point will not move if the region is active, however, to avoid
11456 destroying the region selection."
11457 (interactive)
11458 (when (and js2-move-point-on-right-click
11459 (not mark-active))
11460 (let ((e last-input-event))
11461 (ignore-errors
11462 (goto-char (cadadr e))))))
11463
11464 (defun js2-mode-create-imenu-index ()
11465 "Return an alist for `imenu--index-alist'."
11466 ;; This is built up in `js2-parse-record-imenu' during parsing.
11467 (when js2-mode-ast
11468 ;; if we have an ast but no recorder, they're requesting a rescan
11469 (unless js2-imenu-recorder
11470 (js2-reparse 'force))
11471 (prog1
11472 (js2-build-imenu-index)
11473 (setq js2-imenu-recorder nil
11474 js2-imenu-function-map nil))))
11475
11476 (defun js2-mode-find-tag ()
11477 "Replacement for `find-tag-default'.
11478 `find-tag-default' returns a ridiculous answer inside comments."
11479 (let (beg end)
11480 (js2-with-underscore-as-word-syntax
11481 (save-excursion
11482 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11483 (looking-back "[A-Za-z0-9_$]"))
11484 (setq beg (progn (forward-word -1) (point))
11485 end (progn (forward-word 1) (point)))
11486 (setq beg (progn (forward-word 1) (point))
11487 end (progn (forward-word -1) (point))))
11488 (replace-regexp-in-string
11489 "[\"']" ""
11490 (buffer-substring-no-properties beg end))))))
11491
11492 (defun js2-mode-forward-sibling ()
11493 "Move to the end of the sibling following point in parent.
11494 Returns non-nil if successful, or nil if there was no following sibling."
11495 (let* ((node (js2-node-at-point))
11496 (parent (js2-mode-find-enclosing-fn node))
11497 sib)
11498 (when (setq sib (js2-node-find-child-after (point) parent))
11499 (goto-char (+ (js2-node-abs-pos sib)
11500 (js2-node-len sib))))))
11501
11502 (defun js2-mode-backward-sibling ()
11503 "Move to the beginning of the sibling node preceding point in parent.
11504 Parent is defined as the enclosing script or function."
11505 (let* ((node (js2-node-at-point))
11506 (parent (js2-mode-find-enclosing-fn node))
11507 sib)
11508 (when (setq sib (js2-node-find-child-before (point) parent))
11509 (goto-char (js2-node-abs-pos sib)))))
11510
11511 (defun js2-beginning-of-defun ()
11512 "Go to line on which current function starts, and return non-nil.
11513 If we're not in a function, go to beginning of previous script-level element."
11514 (interactive)
11515 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11516 pos sib)
11517 (cond
11518 ((and (js2-function-node-p parent)
11519 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11520 (goto-char pos))
11521 (t
11522 (js2-mode-backward-sibling)))))
11523
11524 (defun js2-end-of-defun ()
11525 "Go to the char after the last position of the current function.
11526 If we're not in a function, skips over the next script-level element."
11527 (interactive)
11528 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11529 (if (not (js2-function-node-p parent))
11530 ;; punt: skip over next script-level element beyond point
11531 (js2-mode-forward-sibling)
11532 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11533 (js2-node-len parent)))))))
11534
11535 (defun js2-mark-defun (&optional allow-extend)
11536 "Put mark at end of this function, point at beginning.
11537 The function marked is the one that contains point.
11538
11539 Interactively, if this command is repeated,
11540 or (in Transient Mark mode) if the mark is active,
11541 it marks the next defun after the ones already marked."
11542 (interactive "p")
11543 (let (extended)
11544 (when (and allow-extend
11545 (or (and (eq last-command this-command) (mark t))
11546 (and transient-mark-mode mark-active)))
11547 (let ((sib (save-excursion
11548 (goto-char (mark))
11549 (if (js2-mode-forward-sibling)
11550 (point))))
11551 node)
11552 (if sib
11553 (progn
11554 (set-mark sib)
11555 (setq extended t))
11556 ;; no more siblings - try extending to enclosing node
11557 (goto-char (mark t)))))
11558 (when (not extended)
11559 (let ((node (js2-node-at-point (point) t)) ; skip comments
11560 ast fn stmt parent beg end)
11561 (when (js2-ast-root-p node)
11562 (setq ast node
11563 node (or (js2-node-find-child-after (point) node)
11564 (js2-node-find-child-before (point) node))))
11565 ;; only mark whole buffer if we can't find any children
11566 (if (null node)
11567 (setq node ast))
11568 (if (js2-function-node-p node)
11569 (setq parent node)
11570 (setq fn (js2-mode-find-enclosing-fn node)
11571 stmt (if (or (null fn)
11572 (js2-ast-root-p fn))
11573 (js2-mode-find-first-stmt node))
11574 parent (or stmt fn)))
11575 (setq beg (js2-node-abs-pos parent)
11576 end (+ beg (js2-node-len parent)))
11577 (push-mark beg)
11578 (goto-char end)
11579 (exchange-point-and-mark)))))
11580
11581 (defun js2-narrow-to-defun ()
11582 "Narrow to the function enclosing point."
11583 (interactive)
11584 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11585 (fn (if (js2-script-node-p node)
11586 node
11587 (js2-mode-find-enclosing-fn node)))
11588 (beg (js2-node-abs-pos fn)))
11589 (unless (js2-ast-root-p fn)
11590 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11591
11592 (provide 'js2-mode)
11593
11594 ;;; js2-mode.el ends here