]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Do not warn about trailing commas in destructuring assignment arrays
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
180
181 (defvar js2-emacs22 (>= emacs-major-version 22))
182
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
189 :group 'js2-mode
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
194
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
197
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
200 :group 'languages)
201
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
204 c-basic-offset
205 4)
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
208 :group 'js2-mode
209 :type 'integer)
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
211
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-consistent-level-indent-inner-bracket-p t
238 "Non-nil to make indentation level inner bracket consistent,
239 regardless of the beginning bracket position."
240 :group 'js2-mode
241 :type 'boolean)
242 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
243
244 (defcustom js2-pretty-multiline-decl-indentation-p t
245 "Non-nil to line up multiline declarations vertically. See the
246 function `js-multiline-decl-indentation' for details."
247 :group 'js2-mode
248 :type 'boolean)
249 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
250
251 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
252 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
253 always additionally indent function expression or array/object literal
254 assigned in a declaration, even when only one var is declared."
255 :group 'js2-mode
256 :type 'boolean)
257 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
258
259 (defcustom js2-indent-on-enter-key nil
260 "Non-nil to have Enter/Return key indent the line.
261 This is unusual for Emacs modes but common in IDEs like Eclipse."
262 :type 'boolean
263 :group 'js2-mode)
264
265 (defcustom js2-enter-indents-newline nil
266 "Non-nil to have Enter/Return key indent the newly-inserted line.
267 This is unusual for Emacs modes but common in IDEs like Eclipse."
268 :type 'boolean
269 :group 'js2-mode)
270
271 (defcustom js2-rebind-eol-bol-keys t
272 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
273 If non-nil, bounce between bol/eol and first/last non-whitespace char."
274 :group 'js2-mode
275 :type 'boolean)
276
277 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
278 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
279 Each value in the list is passed to `define-key'."
280 :type 'list
281 :group 'js2-mode)
282
283 (defcustom js2-idle-timer-delay 0.2
284 "Delay in secs before re-parsing after user makes changes.
285 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
286 :type 'number
287 :group 'js2-mode)
288 (make-variable-buffer-local 'js2-idle-timer-delay)
289
290 (defcustom js2-dynamic-idle-timer-adjust 0
291 "Positive to adjust `js2-idle-timer-delay' based on file size.
292 The idea is that for short files, parsing is faster so we can be
293 more responsive to user edits without interfering with editing.
294 The buffer length in characters (typically bytes) is divided by
295 this value and used to multiply `js2-idle-timer-delay' for the
296 buffer. For example, a 21k file and 10k adjust yields 21k/10k
297 == 2, so js2-idle-timer-delay is multiplied by 2.
298 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
299 `js2-idle-timer-delay' is not dependent on the file size."
300 :type 'number
301 :group 'js2-mode)
302
303 (defcustom js2-mode-escape-quotes t
304 "Non-nil to disable automatic quote-escaping inside strings."
305 :type 'boolean
306 :group 'js2-mode)
307
308 (defcustom js2-mode-squeeze-spaces t
309 "Non-nil to normalize whitespace when filling in comments.
310 Multiple runs of spaces are converted to a single space."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-parse-errors t
315 "True to highlight parse errors."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-mode-show-strict-warnings t
320 "Non-nil to emit Ecma strict-mode warnings.
321 Some of the warnings can be individually disabled by other flags,
322 even if this flag is non-nil."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-strict-trailing-comma-warning t
327 "Non-nil to warn about trailing commas in array literals.
328 Ecma-262 forbids them, but many browsers permit them. IE is the
329 big exception, and can produce bugs if you have trailing commas."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-cond-assign-warning t
366 "Non-nil to warn about expressions like if (a = b).
367 This often should have been '==' instead of '='. If the warning
368 is enabled, you can suppress it on a per-expression basis by
369 parenthesizing the expression, e.g. if ((a = b)) ..."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-strict-var-redeclaration-warning t
374 "Non-nil to warn about redeclaring variables in a script or function."
375 :type 'boolean
376 :group 'js2-mode)
377
378 (defcustom js2-strict-var-hides-function-arg-warning t
379 "Non-nil to warn about a var decl hiding a function argument."
380 :type 'boolean
381 :group 'js2-mode)
382
383 (defcustom js2-skip-preprocessor-directives nil
384 "Non-nil to treat lines beginning with # as comments.
385 Useful for viewing Mozilla JavaScript source code."
386 :type 'boolean
387 :group 'js2-mode)
388
389 (defcustom js2-language-version 180
390 "Configures what JavaScript language version to recognize.
391 Currently versions 150, 160, 170 and 180 are supported, corresponding
392 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
393 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
394 and 1.8 adds function closures."
395 :type 'integer
396 :group 'js2-mode)
397
398 (defcustom js2-allow-keywords-as-property-names t
399 "If non-nil, you can use JavaScript keywords as object property names.
400 Examples:
401
402 var foo = {int: 5, while: 6, continue: 7};
403 foo.return = 8;
404
405 Ecma-262 forbids this syntax, but many browsers support it."
406 :type 'boolean
407 :group 'js2-mode)
408
409 (defcustom js2-instanceof-has-side-effects nil
410 "If non-nil, treats the instanceof operator as having side effects.
411 This is useful for xulrunner apps."
412 :type 'boolean
413 :group 'js2-mode)
414
415 (defcustom js2-cleanup-whitespace nil
416 "Non-nil to invoke `delete-trailing-whitespace' before saves."
417 :type 'boolean
418 :group 'js2-mode)
419
420 (defcustom js2-move-point-on-right-click t
421 "Non-nil to move insertion point when you right-click.
422 This makes right-click context menu behavior a bit more intuitive,
423 since menu operations generally apply to the point. The exception
424 is if there is a region selection, in which case the point does -not-
425 move, so cut/copy/paste etc. can work properly.
426
427 Note that IntelliJ moves the point, and Eclipse leaves it alone,
428 so this behavior is customizable."
429 :group 'js2-mode
430 :type 'boolean)
431
432 (defcustom js2-allow-rhino-new-expr-initializer t
433 "Non-nil to support a Rhino's experimental syntactic construct.
434
435 Rhino supports the ability to follow a `new' expression with an object
436 literal, which is used to set additional properties on the new object
437 after calling its constructor. Syntax:
438
439 new <expr> [ ( arglist ) ] [initializer]
440
441 Hence, this expression:
442
443 new Object {a: 1, b: 2}
444
445 results in an Object with properties a=1 and b=2. This syntax is
446 apparently not configurable in Rhino - it's currently always enabled,
447 as of Rhino version 1.7R2."
448 :type 'boolean
449 :group 'js2-mode)
450
451 (defcustom js2-allow-member-expr-as-function-name nil
452 "Non-nil to support experimental Rhino syntax for function names.
453
454 Rhino supports an experimental syntax configured via the Rhino Context
455 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
456
457 function <member-expr> ( [ arg-list ] ) { <body> }
458
459 Where member-expr is a non-parenthesized 'member expression', which
460 is anything at the grammar level of a new-expression or lower, meaning
461 any expression that does not involve infix or unary operators.
462
463 When <member-expr> is not a simple identifier, then it is syntactic
464 sugar for assigning the anonymous function to the <member-expr>. Hence,
465 this code:
466
467 function a.b().c[2] (x, y) { ... }
468
469 is rewritten as:
470
471 a.b().c[2] = function(x, y) {...}
472
473 which doesn't seem particularly useful, but Rhino permits it."
474 :type 'boolean
475 :group 'js2-mode)
476
477 (defvar js2-mode-version 20101228
478 "Release number for `js2-mode'.")
479
480 ;; scanner variables
481
482 (defmacro js2-deflocal (name value &optional comment)
483 "Define a buffer-local variable NAME with VALUE and COMMENT."
484 `(progn
485 (defvar ,name ,value ,comment)
486 (make-variable-buffer-local ',name)))
487
488 ;; We record the start and end position of each token.
489 (js2-deflocal js2-token-beg 1)
490 (js2-deflocal js2-token-end -1)
491
492 (defvar js2-EOF_CHAR -1
493 "Represents end of stream. Distinct from js2-EOF token type.")
494
495 ;; I originally used symbols to represent tokens, but Rhino uses
496 ;; ints and then sets various flag bits in them, so ints it is.
497 ;; The upshot is that we need a `js2-' prefix in front of each name.
498 (defvar js2-ERROR -1)
499 (defvar js2-EOF 0)
500 (defvar js2-EOL 1)
501 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
502 (defvar js2-LEAVEWITH 3)
503 (defvar js2-RETURN 4)
504 (defvar js2-GOTO 5)
505 (defvar js2-IFEQ 6)
506 (defvar js2-IFNE 7)
507 (defvar js2-SETNAME 8)
508 (defvar js2-BITOR 9)
509 (defvar js2-BITXOR 10)
510 (defvar js2-BITAND 11)
511 (defvar js2-EQ 12)
512 (defvar js2-NE 13)
513 (defvar js2-LT 14)
514 (defvar js2-LE 15)
515 (defvar js2-GT 16)
516 (defvar js2-GE 17)
517 (defvar js2-LSH 18)
518 (defvar js2-RSH 19)
519 (defvar js2-URSH 20)
520 (defvar js2-ADD 21) ; infix plus
521 (defvar js2-SUB 22) ; infix minus
522 (defvar js2-MUL 23)
523 (defvar js2-DIV 24)
524 (defvar js2-MOD 25)
525 (defvar js2-NOT 26)
526 (defvar js2-BITNOT 27)
527 (defvar js2-POS 28) ; unary plus
528 (defvar js2-NEG 29) ; unary minus
529 (defvar js2-NEW 30)
530 (defvar js2-DELPROP 31)
531 (defvar js2-TYPEOF 32)
532 (defvar js2-GETPROP 33)
533 (defvar js2-GETPROPNOWARN 34)
534 (defvar js2-SETPROP 35)
535 (defvar js2-GETELEM 36)
536 (defvar js2-SETELEM 37)
537 (defvar js2-CALL 38)
538 (defvar js2-NAME 39) ; an identifier
539 (defvar js2-NUMBER 40)
540 (defvar js2-STRING 41)
541 (defvar js2-NULL 42)
542 (defvar js2-THIS 43)
543 (defvar js2-FALSE 44)
544 (defvar js2-TRUE 45)
545 (defvar js2-SHEQ 46) ; shallow equality (===)
546 (defvar js2-SHNE 47) ; shallow inequality (!==)
547 (defvar js2-REGEXP 48)
548 (defvar js2-BINDNAME 49)
549 (defvar js2-THROW 50)
550 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
551 (defvar js2-IN 52)
552 (defvar js2-INSTANCEOF 53)
553 (defvar js2-LOCAL_LOAD 54)
554 (defvar js2-GETVAR 55)
555 (defvar js2-SETVAR 56)
556 (defvar js2-CATCH_SCOPE 57)
557 (defvar js2-ENUM_INIT_KEYS 58)
558 (defvar js2-ENUM_INIT_VALUES 59)
559 (defvar js2-ENUM_INIT_ARRAY 60)
560 (defvar js2-ENUM_NEXT 61)
561 (defvar js2-ENUM_ID 62)
562 (defvar js2-THISFN 63)
563 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
564 (defvar js2-ARRAYLIT 65) ; array literal
565 (defvar js2-OBJECTLIT 66) ; object literal
566 (defvar js2-GET_REF 67) ; *reference
567 (defvar js2-SET_REF 68) ; *reference = something
568 (defvar js2-DEL_REF 69) ; delete reference
569 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
570 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
571 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
572
573 ;; XML support
574 (defvar js2-DEFAULTNAMESPACE 73)
575 (defvar js2-ESCXMLATTR 74)
576 (defvar js2-ESCXMLTEXT 75)
577 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
578 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
579 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
580 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
581
582 (defvar js2-first-bytecode js2-ENTERWITH)
583 (defvar js2-last-bytecode js2-REF_NS_NAME)
584
585 (defvar js2-TRY 80)
586 (defvar js2-SEMI 81) ; semicolon
587 (defvar js2-LB 82) ; left and right brackets
588 (defvar js2-RB 83)
589 (defvar js2-LC 84) ; left and right curly-braces
590 (defvar js2-RC 85)
591 (defvar js2-LP 86) ; left and right parens
592 (defvar js2-RP 87)
593 (defvar js2-COMMA 88) ; comma operator
594
595 (defvar js2-ASSIGN 89) ; simple assignment (=)
596 (defvar js2-ASSIGN_BITOR 90) ; |=
597 (defvar js2-ASSIGN_BITXOR 91) ; ^=
598 (defvar js2-ASSIGN_BITAND 92) ; &=
599 (defvar js2-ASSIGN_LSH 93) ; <<=
600 (defvar js2-ASSIGN_RSH 94) ; >>=
601 (defvar js2-ASSIGN_URSH 95) ; >>>=
602 (defvar js2-ASSIGN_ADD 96) ; +=
603 (defvar js2-ASSIGN_SUB 97) ; -=
604 (defvar js2-ASSIGN_MUL 98) ; *=
605 (defvar js2-ASSIGN_DIV 99) ; /=
606 (defvar js2-ASSIGN_MOD 100) ; %=
607
608 (defvar js2-first-assign js2-ASSIGN)
609 (defvar js2-last-assign js2-ASSIGN_MOD)
610
611 (defvar js2-HOOK 101) ; conditional (?:)
612 (defvar js2-COLON 102)
613 (defvar js2-OR 103) ; logical or (||)
614 (defvar js2-AND 104) ; logical and (&&)
615 (defvar js2-INC 105) ; increment/decrement (++ --)
616 (defvar js2-DEC 106)
617 (defvar js2-DOT 107) ; member operator (.)
618 (defvar js2-FUNCTION 108) ; function keyword
619 (defvar js2-EXPORT 109) ; export keyword
620 (defvar js2-IMPORT 110) ; import keyword
621 (defvar js2-IF 111) ; if keyword
622 (defvar js2-ELSE 112) ; else keyword
623 (defvar js2-SWITCH 113) ; switch keyword
624 (defvar js2-CASE 114) ; case keyword
625 (defvar js2-DEFAULT 115) ; default keyword
626 (defvar js2-WHILE 116) ; while keyword
627 (defvar js2-DO 117) ; do keyword
628 (defvar js2-FOR 118) ; for keyword
629 (defvar js2-BREAK 119) ; break keyword
630 (defvar js2-CONTINUE 120) ; continue keyword
631 (defvar js2-VAR 121) ; var keyword
632 (defvar js2-WITH 122) ; with keyword
633 (defvar js2-CATCH 123) ; catch keyword
634 (defvar js2-FINALLY 124) ; finally keyword
635 (defvar js2-VOID 125) ; void keyword
636 (defvar js2-RESERVED 126) ; reserved keywords
637
638 (defvar js2-EMPTY 127)
639
640 ;; Types used for the parse tree - never returned by scanner.
641
642 (defvar js2-BLOCK 128) ; statement block
643 (defvar js2-LABEL 129) ; label
644 (defvar js2-TARGET 130)
645 (defvar js2-LOOP 131)
646 (defvar js2-EXPR_VOID 132) ; expression statement in functions
647 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
648 (defvar js2-JSR 134)
649 (defvar js2-SCRIPT 135) ; top-level node for entire script
650 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
651 (defvar js2-USE_STACK 137)
652 (defvar js2-SETPROP_OP 138) ; x.y op= something
653 (defvar js2-SETELEM_OP 139) ; x[y] op= something
654 (defvar js2-LOCAL_BLOCK 140)
655 (defvar js2-SET_REF_OP 141) ; *reference op= something
656
657 ;; For XML support:
658 (defvar js2-DOTDOT 142) ; member operator (..)
659 (defvar js2-COLONCOLON 143) ; namespace::name
660 (defvar js2-XML 144) ; XML type
661 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
662 (defvar js2-XMLATTR 146) ; @
663 (defvar js2-XMLEND 147)
664
665 ;; Optimizer-only tokens
666 (defvar js2-TO_OBJECT 148)
667 (defvar js2-TO_DOUBLE 149)
668
669 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
670 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
671 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
672 (defvar js2-CONST 153)
673 (defvar js2-SETCONST 154)
674 (defvar js2-SETCONSTVAR 155)
675 (defvar js2-ARRAYCOMP 156)
676 (defvar js2-LETEXPR 157)
677 (defvar js2-WITHEXPR 158)
678 (defvar js2-DEBUGGER 159)
679
680 (defvar js2-COMMENT 160)
681 (defvar js2-ENUM 161) ; for "enum" reserved word
682
683 (defconst js2-num-tokens (1+ js2-ENUM))
684
685 (defconst js2-debug-print-trees nil)
686
687 ;; Rhino accepts any string or stream as input. Emacs character
688 ;; processing works best in buffers, so we'll assume the input is a
689 ;; buffer. JavaScript strings can be copied into temp buffers before
690 ;; scanning them.
691
692 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
693 ;; They're the Emacs equivalent of instance variables, more or less.
694
695 (js2-deflocal js2-ts-dirty-line nil
696 "Token stream buffer-local variable.
697 Indicates stuff other than whitespace since start of line.")
698
699 (js2-deflocal js2-ts-regexp-flags nil
700 "Token stream buffer-local variable.")
701
702 (js2-deflocal js2-ts-string ""
703 "Token stream buffer-local variable.
704 Last string scanned.")
705
706 (js2-deflocal js2-ts-number nil
707 "Token stream buffer-local variable.
708 Last literal number scanned.")
709
710 (js2-deflocal js2-ts-hit-eof nil
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-line-start 0
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-lineno 1
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-line-end-char -1
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
723 "Token stream buffer-local variable.
724 Current scan position.")
725
726 (js2-deflocal js2-ts-is-xml-attribute nil
727 "Token stream buffer-local variable.")
728
729 (js2-deflocal js2-ts-xml-is-tag-content nil
730 "Token stream buffer-local variable.")
731
732 (js2-deflocal js2-ts-xml-open-tags-count 0
733 "Token stream buffer-local variable.")
734
735 (js2-deflocal js2-ts-string-buffer nil
736 "Token stream buffer-local variable.
737 List of chars built up while scanning various tokens.")
738
739 (js2-deflocal js2-ts-comment-type nil
740 "Token stream buffer-local variable.")
741
742 ;;; Parser variables
743
744 (js2-deflocal js2-parsed-errors nil
745 "List of errors produced during scanning/parsing.")
746
747 (js2-deflocal js2-parsed-warnings nil
748 "List of warnings produced during scanning/parsing.")
749
750 (js2-deflocal js2-recover-from-parse-errors t
751 "Non-nil to continue parsing after a syntax error.
752
753 In recovery mode, the AST will be built in full, and any error
754 nodes will be flagged with appropriate error information. If
755 this flag is nil, a syntax error will result in an error being
756 signaled.
757
758 The variable is automatically buffer-local, because different
759 modes that use the parser will need different settings.")
760
761 (js2-deflocal js2-parse-hook nil
762 "List of callbacks for receiving parsing progress.")
763
764 (defvar js2-parse-finished-hook nil
765 "List of callbacks to notify when parsing finishes.
766 Not called if parsing was interrupted.")
767
768 (js2-deflocal js2-is-eval-code nil
769 "True if we're evaluating code in a string.
770 If non-nil, the tokenizer will record the token text, and the AST nodes
771 will record their source text. Off by default for IDE modes, since the
772 text is available in the buffer.")
773
774 (defvar js2-parse-ide-mode t
775 "Non-nil if the parser is being used for `js2-mode'.
776 If non-nil, the parser will set text properties for fontification
777 and the syntax table. The value should be nil when using the
778 parser as a frontend to an interpreter or byte compiler.")
779
780 ;;; Parser instance variables (buffer-local vars for js2-parse)
781
782 (defconst js2-clear-ti-mask #xFFFF
783 "Mask to clear token information bits.")
784
785 (defconst js2-ti-after-eol (lsh 1 16)
786 "Flag: first token of the source line.")
787
788 (defconst js2-ti-check-label (lsh 1 17)
789 "Flag: indicates to check for label.")
790
791 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
792
793 (js2-deflocal js2-compiler-generate-debug-info t)
794 (js2-deflocal js2-compiler-use-dynamic-scope nil)
795 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
796 (js2-deflocal js2-compiler-xml-available t)
797 (js2-deflocal js2-compiler-optimization-level 0)
798 (js2-deflocal js2-compiler-generating-source t)
799 (js2-deflocal js2-compiler-strict-mode nil)
800 (js2-deflocal js2-compiler-report-warning-as-error nil)
801 (js2-deflocal js2-compiler-generate-observer-count nil)
802 (js2-deflocal js2-compiler-activation-names nil)
803
804 ;; SKIP: sourceURI
805
806 ;; There's a compileFunction method in Context.java - may need it.
807 (js2-deflocal js2-called-by-compile-function nil
808 "True if `js2-parse' was called by `js2-compile-function'.
809 Will only be used when we finish implementing the interpreter.")
810
811 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
812
813 (js2-deflocal js2-current-flagged-token js2-EOF)
814 (js2-deflocal js2-current-token js2-EOF)
815
816 ;; SKIP: node factory - we're going to just call functions directly,
817 ;; and eventually go to a unified AST format.
818
819 (js2-deflocal js2-nesting-of-function 0)
820
821 (js2-deflocal js2-recorded-identifiers nil
822 "Tracks identifiers found during parsing.")
823
824 (defmacro js2-in-lhs (body)
825 `(let ((js2-is-in-lhs t))
826 ,body))
827
828 (defmacro js2-in-rhs (body)
829 `(let ((js2-is-in-lhs nil))
830 ,body))
831
832 (js2-deflocal js2-is-in-lhs nil
833 "True while parsing lhs statement")
834
835 (defcustom js2-global-externs nil
836 "A list of any extern names you'd like to consider always declared.
837 This list is global and is used by all js2-mode files.
838 You can create buffer-local externs list using `js2-additional-externs'.
839
840 There is also a buffer-local variable `js2-default-externs',
841 which is initialized by default to include the Ecma-262 externs
842 and the standard browser externs. The three lists are all
843 checked during highlighting."
844 :type 'list
845 :group 'js2-mode)
846
847 (js2-deflocal js2-default-externs nil
848 "Default external declarations.
849
850 These are currently only used for highlighting undeclared variables,
851 which only worries about top-level (unqualified) references.
852 As js2-mode's processing improves, we will flesh out this list.
853
854 The initial value is set to `js2-ecma-262-externs', unless you
855 have set `js2-include-browser-externs', in which case the browser
856 externs are also included.
857
858 See `js2-additional-externs' for more information.")
859
860 (defcustom js2-include-browser-externs t
861 "Non-nil to include browser externs in the master externs list.
862 If you work on JavaScript files that are not intended for browsers,
863 such as Mozilla Rhino server-side JavaScript, set this to nil.
864 You can always include them on a per-file basis by calling
865 `js2-add-browser-externs' from a function on `js2-mode-hook'.
866
867 See `js2-additional-externs' for more information about externs."
868 :type 'boolean
869 :group 'js2-mode)
870
871 (defcustom js2-include-rhino-externs t
872 "Non-nil to include Mozilla Rhino externs in the master externs list.
873 See `js2-additional-externs' for more information about externs."
874 :type 'boolean
875 :group 'js2-mode)
876
877 (defcustom js2-include-gears-externs t
878 "Non-nil to include Google Gears externs in the master externs list.
879 See `js2-additional-externs' for more information about externs."
880 :type 'boolean
881 :group 'js2-mode)
882
883 (js2-deflocal js2-additional-externs nil
884 "A buffer-local list of additional external declarations.
885 It is used to decide whether variables are considered undeclared
886 for purposes of highlighting.
887
888 Each entry is a lisp string. The string should be the fully qualified
889 name of an external entity. All externs should be added to this list,
890 so that as js2-mode's processing improves it can take advantage of them.
891
892 You may want to declare your externs in three ways.
893 First, you can add externs that are valid for all your JavaScript files.
894 You should probably do this by adding them to `js2-global-externs', which
895 is a global list used for all js2-mode files.
896
897 Next, you can add a function to `js2-mode-hook' that adds additional
898 externs appropriate for the specific file, perhaps based on its path.
899 These should go in `js2-additional-externs', which is buffer-local.
900
901 Finally, you can add a function to `js2-post-parse-callbacks',
902 which is called after parsing completes, and `root' is bound to
903 the root of the parse tree. At this stage you can set up an AST
904 node visitor using `js2-visit-ast' and examine the parse tree
905 for specific import patterns that may imply the existence of
906 other externs, possibly tied to your build system. These should also
907 be added to `js2-additional-externs'.
908
909 Your post-parse callback may of course also use the simpler and
910 faster (but perhaps less robust) approach of simply scanning the
911 buffer text for your imports, using regular expressions.")
912
913 ;; SKIP: decompiler
914 ;; SKIP: encoded-source
915
916 ;;; The following variables are per-function and should be saved/restored
917 ;;; during function parsing...
918
919 (js2-deflocal js2-current-script-or-fn nil)
920 (js2-deflocal js2-current-scope nil)
921 (js2-deflocal js2-nesting-of-with 0)
922 (js2-deflocal js2-label-set nil
923 "An alist mapping label names to nodes.")
924
925 (js2-deflocal js2-loop-set nil)
926 (js2-deflocal js2-loop-and-switch-set nil)
927 (js2-deflocal js2-has-return-value nil)
928 (js2-deflocal js2-end-flags 0)
929
930 ;;; ...end of per function variables
931
932 ;; Without 2-token lookahead, labels are a problem.
933 ;; These vars store the token info of the last matched name,
934 ;; iff it wasn't the last matched token. Only valid in some contexts.
935 (defvar js2-prev-name-token-start nil)
936 (defvar js2-prev-name-token-string nil)
937
938 (defsubst js2-save-name-token-data (pos name)
939 (setq js2-prev-name-token-start pos
940 js2-prev-name-token-string name))
941
942 ;; These flags enumerate the possible ways a statement/function can
943 ;; terminate. These flags are used by endCheck() and by the Parser to
944 ;; detect inconsistent return usage.
945 ;;
946 ;; END_UNREACHED is reserved for code paths that are assumed to always be
947 ;; able to execute (example: throw, continue)
948 ;;
949 ;; END_DROPS_OFF indicates if the statement can transfer control to the
950 ;; next one. Statement such as return dont. A compound statement may have
951 ;; some branch that drops off control to the next statement.
952 ;;
953 ;; END_RETURNS indicates that the statement can return (without arguments)
954 ;; END_RETURNS_VALUE indicates that the statement can return a value.
955 ;;
956 ;; A compound statement such as
957 ;; if (condition) {
958 ;; return value;
959 ;; }
960 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
961
962 (defconst js2-end-unreached #x0)
963 (defconst js2-end-drops-off #x1)
964 (defconst js2-end-returns #x2)
965 (defconst js2-end-returns-value #x4)
966 (defconst js2-end-yields #x8)
967
968 ;; Rhino awkwardly passes a statementLabel parameter to the
969 ;; statementHelper() function, the main statement parser, which
970 ;; is then used by quite a few of the sub-parsers. We just make
971 ;; it a buffer-local variable and make sure it's cleaned up properly.
972 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
973
974 ;; Similarly, Rhino passes an inForInit boolean through about half
975 ;; the expression parsers. We use a dynamically-scoped variable,
976 ;; which makes it easier to funcall the parsers individually without
977 ;; worrying about whether they take the parameter or not.
978 (js2-deflocal js2-in-for-init nil)
979 (js2-deflocal js2-temp-name-counter 0)
980 (js2-deflocal js2-parse-stmt-count 0)
981
982 (defsubst js2-get-next-temp-name ()
983 (format "$%d" (incf js2-temp-name-counter)))
984
985 (defvar js2-parse-interruptable-p t
986 "Set this to nil to force parse to continue until finished.
987 This will mostly be useful for interpreters.")
988
989 (defvar js2-statements-per-pause 50
990 "Pause after this many statements to check for user input.
991 If user input is pending, stop the parse and discard the tree.
992 This makes for a smoother user experience for large files.
993 You may have to wait a second or two before the highlighting
994 and error-reporting appear, but you can always type ahead if
995 you wish. This appears to be more or less how Eclipse, IntelliJ
996 and other editors work.")
997
998 (js2-deflocal js2-record-comments t
999 "Instructs the scanner to record comments in `js2-scanned-comments'.")
1000
1001 (js2-deflocal js2-scanned-comments nil
1002 "List of all comments from the current parse.")
1003
1004 (defcustom js2-mode-indent-inhibit-undo nil
1005 "Non-nil to disable collection of Undo information when indenting lines.
1006 Some users have requested this behavior. It's nil by default because
1007 other Emacs modes don't work this way."
1008 :type 'boolean
1009 :group 'js2-mode)
1010
1011 (defcustom js2-mode-indent-ignore-first-tab nil
1012 "If non-nil, ignore first TAB keypress if we look indented properly.
1013 It's fairly common for users to navigate to an already-indented line
1014 and press TAB for reassurance that it's been indented. For this class
1015 of users, we want the first TAB press on a line to be ignored if the
1016 line is already indented to one of the precomputed alternatives.
1017
1018 This behavior is only partly implemented. If you TAB-indent a line,
1019 navigate to another line, and then navigate back, it fails to clear
1020 the last-indented variable, so it thinks you've already hit TAB once,
1021 and performs the indent. A full solution would involve getting on the
1022 point-motion hooks for the entire buffer. If we come across another
1023 use cases that requires watching point motion, I'll consider doing it.
1024
1025 If you set this variable to nil, then the TAB key will always change
1026 the indentation of the current line, if more than one alternative
1027 indentation spot exists."
1028 :type 'boolean
1029 :group 'js2-mode)
1030
1031 (defvar js2-indent-hook nil
1032 "A hook for user-defined indentation rules.
1033
1034 Functions on this hook should expect two arguments: (LIST INDEX)
1035 The LIST argument is the list of computed indentation points for
1036 the current line. INDEX is the list index of the indentation point
1037 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1038 indent function is not going to change the current line indentation.
1039
1040 If a hook function on this list returns a non-nil value, then
1041 `js2-bounce-indent' assumes the hook function has performed its own
1042 indentation, and will do nothing. If all hook functions on the list
1043 return nil, then `js2-bounce-indent' will use its computed indentation
1044 and reindent the line.
1045
1046 When hook functions on this hook list are called, the variable
1047 `js2-mode-ast' may or may not be set, depending on whether the
1048 parse tree is available. If the variable is nil, you can pass a
1049 callback to `js2-mode-wait-for-parse', and your callback will be
1050 called after the new parse tree is built. This can take some time
1051 in large files.")
1052
1053 (defface js2-warning-face
1054 `((((class color) (background light))
1055 (:underline "orange"))
1056 (((class color) (background dark))
1057 (:underline "orange"))
1058 (t (:underline t)))
1059 "Face for JavaScript warnings."
1060 :group 'js2-mode)
1061
1062 (defface js2-error-face
1063 `((((class color) (background light))
1064 (:foreground "red"))
1065 (((class color) (background dark))
1066 (:foreground "red"))
1067 (t (:foreground "red")))
1068 "Face for JavaScript errors."
1069 :group 'js2-mode)
1070
1071 (defface js2-jsdoc-tag-face
1072 '((t :foreground "SlateGray"))
1073 "Face used to highlight @whatever tags in jsdoc comments."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-type-face
1077 '((t :foreground "SteelBlue"))
1078 "Face used to highlight {FooBar} types in jsdoc comments."
1079 :group 'js2-mode)
1080
1081 (defface js2-jsdoc-value-face
1082 '((t :foreground "PeachPuff3"))
1083 "Face used to highlight tag values in jsdoc comments."
1084 :group 'js2-mode)
1085
1086 (defface js2-function-param-face
1087 '((t :foreground "SeaGreen"))
1088 "Face used to highlight function parameters in javascript."
1089 :group 'js2-mode)
1090
1091 (defface js2-instance-member-face
1092 '((t :foreground "DarkOrchid"))
1093 "Face used to highlight instance variables in javascript.
1094 Not currently used."
1095 :group 'js2-mode)
1096
1097 (defface js2-private-member-face
1098 '((t :foreground "PeachPuff3"))
1099 "Face used to highlight calls to private methods in javascript.
1100 Not currently used."
1101 :group 'js2-mode)
1102
1103 (defface js2-private-function-call-face
1104 '((t :foreground "goldenrod"))
1105 "Face used to highlight calls to private functions in javascript.
1106 Not currently used."
1107 :group 'js2-mode)
1108
1109 (defface js2-jsdoc-html-tag-name-face
1110 (if js2-emacs22
1111 '((((class color) (min-colors 88) (background light))
1112 (:foreground "rosybrown"))
1113 (((class color) (min-colors 8) (background dark))
1114 (:foreground "yellow"))
1115 (((class color) (min-colors 8) (background light))
1116 (:foreground "magenta")))
1117 '((((type tty pc) (class color) (background light))
1118 (:foreground "magenta"))
1119 (((type tty pc) (class color) (background dark))
1120 (:foreground "yellow"))
1121 (t (:foreground "RosyBrown"))))
1122 "Face used to highlight jsdoc html tag names"
1123 :group 'js2-mode)
1124
1125 (defface js2-jsdoc-html-tag-delimiter-face
1126 (if js2-emacs22
1127 '((((class color) (min-colors 88) (background light))
1128 (:foreground "dark khaki"))
1129 (((class color) (min-colors 8) (background dark))
1130 (:foreground "green"))
1131 (((class color) (min-colors 8) (background light))
1132 (:foreground "green")))
1133 '((((type tty pc) (class color) (background light))
1134 (:foreground "green"))
1135 (((type tty pc) (class color) (background dark))
1136 (:foreground "green"))
1137 (t (:foreground "dark khaki"))))
1138 "Face used to highlight brackets in jsdoc html tags."
1139 :group 'js2-mode)
1140
1141 (defface js2-magic-paren-face
1142 '((t :underline t))
1143 "Face used to color parens that will be auto-overwritten."
1144 :group 'js2-mode)
1145
1146 (defcustom js2-post-parse-callbacks nil
1147 "A list of callback functions invoked after parsing finishes.
1148 Currently, the main use for this function is to add synthetic
1149 declarations to `js2-recorded-identifiers', which see."
1150 :type 'list
1151 :group 'js2-mode)
1152
1153 (defface js2-external-variable-face
1154 '((t :foreground "orange"))
1155 "Face used to highlight undeclared variable identifiers.
1156 An undeclared variable is any variable not declared with var or let
1157 in the current scope or any lexically enclosing scope. If you use
1158 such a variable, then you are either expecting it to originate from
1159 another file, or you've got a potential bug."
1160 :group 'js2-mode)
1161
1162 (defcustom js2-highlight-external-variables t
1163 "Non-nil to highlight undeclared variable identifiers."
1164 :type 'boolean
1165 :group 'js2-mode)
1166
1167 (defcustom js2-auto-insert-catch-block t
1168 "Non-nil to insert matching catch block on open-curly after `try'."
1169 :type 'boolean
1170 :group 'js2-mode)
1171
1172 (defvar js2-mode-map
1173 (let ((map (make-sparse-keymap))
1174 keys)
1175 (define-key map [mouse-1] #'js2-mode-show-node)
1176 (define-key map (kbd "C-m") #'js2-enter-key)
1177 (when js2-rebind-eol-bol-keys
1178 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1179 (define-key map (kbd "C-e") #'js2-end-of-line))
1180 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1181 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1182 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1183 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1184 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1185 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1186 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1187 (define-key map (kbd "C-c C-`") #'js2-next-error)
1188 ;; also define user's preference for next-error, if available
1189 (if (setq keys (where-is-internal #'next-error))
1190 (define-key map (car keys) #'js2-next-error))
1191 (define-key map (or (car (where-is-internal #'mark-defun))
1192 (kbd "M-C-h"))
1193 #'js2-mark-defun)
1194 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1195 (kbd "C-x nd"))
1196 #'js2-narrow-to-defun)
1197 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1198 (when js2-auto-indent-p
1199 (mapc (lambda (key)
1200 (define-key map key #'js2-insert-and-indent))
1201 js2-electric-keys))
1202 (when js2-bounce-indent-p
1203 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1204
1205 (define-key map [menu-bar javascript]
1206 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1207
1208 (define-key map [menu-bar javascript customize-js2-mode]
1209 '(menu-item "Customize js2-mode" js2-mode-customize
1210 :help "Customize the behavior of this mode"))
1211
1212 (define-key map [menu-bar javascript js2-force-refresh]
1213 '(menu-item "Force buffer refresh" js2-mode-reset
1214 :help "Re-parse the buffer from scratch"))
1215
1216 (define-key map [menu-bar javascript separator-2]
1217 '("--"))
1218
1219 (define-key map [menu-bar javascript next-error]
1220 '(menu-item "Next warning or error" js2-next-error
1221 :enabled (and js2-mode-ast
1222 (or (js2-ast-root-errors js2-mode-ast)
1223 (js2-ast-root-warnings js2-mode-ast)))
1224 :help "Move to next warning or error"))
1225
1226 (define-key map [menu-bar javascript display-errors]
1227 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1228 :visible (not js2-mode-show-parse-errors)
1229 :help "Turn on display of warnings and errors"))
1230
1231 (define-key map [menu-bar javascript hide-errors]
1232 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1233 :visible js2-mode-show-parse-errors
1234 :help "Turn off display of warnings and errors"))
1235
1236 (define-key map [menu-bar javascript separator-1]
1237 '("--"))
1238
1239 (define-key map [menu-bar javascript js2-toggle-function]
1240 '(menu-item "Show/collapse element" js2-mode-toggle-element
1241 :help "Hide or show function body or comment"))
1242
1243 (define-key map [menu-bar javascript show-comments]
1244 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1245 :visible js2-mode-comments-hidden
1246 :help "Expand all hidden block comments"))
1247
1248 (define-key map [menu-bar javascript hide-comments]
1249 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1250 :visible (not js2-mode-comments-hidden)
1251 :help "Show block comments as /*...*/"))
1252
1253 (define-key map [menu-bar javascript show-all-functions]
1254 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1255 :visible js2-mode-functions-hidden
1256 :help "Expand all hidden function bodies"))
1257
1258 (define-key map [menu-bar javascript hide-all-functions]
1259 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1260 :visible (not js2-mode-functions-hidden)
1261 :help "Show {...} for all top-level function bodies"))
1262
1263 map)
1264 "Keymap used in `js2-mode' buffers.")
1265
1266 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1267
1268 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1269 "Matches a //-comment line. Must be first non-whitespace on line.
1270 First match-group is the leading whitespace.")
1271
1272 (defvar js2-mode-hook nil)
1273
1274 (js2-deflocal js2-mode-ast nil "Private variable.")
1275 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1276 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1277 (js2-deflocal js2-mode-parsing nil "Private variable.")
1278 (js2-deflocal js2-mode-node-overlay nil)
1279
1280 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1281 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1282
1283 (js2-deflocal js2-mode-fontifications nil "Private variable")
1284 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1285 (js2-deflocal js2-imenu-recorder nil "Private variable")
1286 (js2-deflocal js2-imenu-function-map nil "Private variable")
1287
1288 (defvar js2-paragraph-start
1289 "\\(@[a-zA-Z]+\\>\\|$\\)")
1290
1291 ;; Note that we also set a 'c-in-sws text property in html comments,
1292 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1293 (defvar js2-syntactic-ws-start
1294 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1295
1296 (defvar js2-syntactic-ws-end
1297 "\\s \\|[\n\r/]\\|\\s!")
1298
1299 (defvar js2-syntactic-eol
1300 (concat "\\s *\\(/\\*[^*\n\r]*"
1301 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1302 "\\*+/\\s *\\)*"
1303 "\\(//\\|/\\*[^*\n\r]*"
1304 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1305 "\\|\\\\$\\|$\\)")
1306 "Copied from `java-mode'. Needed for some cc-engine functions.")
1307
1308 (defvar js2-comment-prefix-regexp
1309 "//+\\|\\**")
1310
1311 (defvar js2-comment-start-skip
1312 "\\(//+\\|/\\*+\\)\\s *")
1313
1314 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1315 "Non-nil to emit status messages during parsing.")
1316
1317 (defvar js2-mode-functions-hidden nil "private variable")
1318 (defvar js2-mode-comments-hidden nil "private variable")
1319
1320 (defvar js2-mode-syntax-table
1321 (let ((table (make-syntax-table)))
1322 (c-populate-syntax-table table)
1323 table)
1324 "Syntax table used in js2-mode buffers.")
1325
1326 (defvar js2-mode-abbrev-table nil
1327 "Abbrev table in use in `js2-mode' buffers.")
1328 (define-abbrev-table 'js2-mode-abbrev-table ())
1329
1330 (defvar js2-mode-pending-parse-callbacks nil
1331 "List of functions waiting to be notified that parse is finished.")
1332
1333 (defvar js2-mode-last-indented-line -1)
1334
1335 ;;; Localizable error and warning messages
1336
1337 ;; Messages are copied from Rhino's Messages.properties.
1338 ;; Many of the Java-specific messages have been elided.
1339 ;; Add any js2-specific ones at the end, so we can keep
1340 ;; this file synced with changes to Rhino's.
1341
1342 (defvar js2-message-table
1343 (make-hash-table :test 'equal :size 250)
1344 "Contains localized messages for js2-mode.")
1345
1346 ;; TODO(stevey): construct this table at compile-time.
1347 (defmacro js2-msg (key &rest strings)
1348 `(puthash ,key (funcall #'concat ,@strings)
1349 js2-message-table))
1350
1351 (defun js2-get-msg (msg-key)
1352 "Look up a localized message.
1353 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1354 the correct number of ARGS must be provided."
1355 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1356 (args (if (listp msg-key) (cdr msg-key)))
1357 (msg (gethash key js2-message-table)))
1358 (if msg
1359 (apply #'format msg args)
1360 key))) ; default to showing the key
1361
1362 (js2-msg "msg.dup.parms"
1363 "Duplicate parameter name '%s'.")
1364
1365 (js2-msg "msg.too.big.jump"
1366 "Program too complex: jump offset too big.")
1367
1368 (js2-msg "msg.too.big.index"
1369 "Program too complex: internal index exceeds 64K limit.")
1370
1371 (js2-msg "msg.while.compiling.fn"
1372 "Encountered code generation error while compiling function '%s': %s")
1373
1374 (js2-msg "msg.while.compiling.script"
1375 "Encountered code generation error while compiling script: %s")
1376
1377 ;; Context
1378 (js2-msg "msg.ctor.not.found"
1379 "Constructor for '%s' not found.")
1380
1381 (js2-msg "msg.not.ctor"
1382 "'%s' is not a constructor.")
1383
1384 ;; FunctionObject
1385 (js2-msg "msg.varargs.ctor"
1386 "Method or constructor '%s' must be static "
1387 "with the signature (Context cx, Object[] args, "
1388 "Function ctorObj, boolean inNewExpr) "
1389 "to define a variable arguments constructor.")
1390
1391 (js2-msg "msg.varargs.fun"
1392 "Method '%s' must be static with the signature "
1393 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1394 "to define a variable arguments function.")
1395
1396 (js2-msg "msg.incompat.call"
1397 "Method '%s' called on incompatible object.")
1398
1399 (js2-msg "msg.bad.parms"
1400 "Unsupported parameter type '%s' in method '%s'.")
1401
1402 (js2-msg "msg.bad.method.return"
1403 "Unsupported return type '%s' in method '%s'.")
1404
1405 (js2-msg "msg.bad.ctor.return"
1406 "Construction of objects of type '%s' is not supported.")
1407
1408 (js2-msg "msg.no.overload"
1409 "Method '%s' occurs multiple times in class '%s'.")
1410
1411 (js2-msg "msg.method.not.found"
1412 "Method '%s' not found in '%s'.")
1413
1414 ;; IRFactory
1415
1416 (js2-msg "msg.bad.for.in.lhs"
1417 "Invalid left-hand side of for..in loop.")
1418
1419 (js2-msg "msg.mult.index"
1420 "Only one variable allowed in for..in loop.")
1421
1422 (js2-msg "msg.bad.for.in.destruct"
1423 "Left hand side of for..in loop must be an array of "
1424 "length 2 to accept key/value pair.")
1425
1426 (js2-msg "msg.cant.convert"
1427 "Can't convert to type '%s'.")
1428
1429 (js2-msg "msg.bad.assign.left"
1430 "Invalid assignment left-hand side.")
1431
1432 (js2-msg "msg.bad.decr"
1433 "Invalid decerement operand.")
1434
1435 (js2-msg "msg.bad.incr"
1436 "Invalid increment operand.")
1437
1438 (js2-msg "msg.bad.yield"
1439 "yield must be in a function.")
1440
1441 (js2-msg "msg.yield.parenthesized"
1442 "yield expression must be parenthesized.")
1443
1444 ;; NativeGlobal
1445 (js2-msg "msg.cant.call.indirect"
1446 "Function '%s' must be called directly, and not by way of a "
1447 "function of another name.")
1448
1449 (js2-msg "msg.eval.nonstring"
1450 "Calling eval() with anything other than a primitive "
1451 "string value will simply return the value. "
1452 "Is this what you intended?")
1453
1454 (js2-msg "msg.eval.nonstring.strict"
1455 "Calling eval() with anything other than a primitive "
1456 "string value is not allowed in strict mode.")
1457
1458 (js2-msg "msg.bad.destruct.op"
1459 "Invalid destructuring assignment operator")
1460
1461 ;; NativeCall
1462 (js2-msg "msg.only.from.new"
1463 "'%s' may only be invoked from a `new' expression.")
1464
1465 (js2-msg "msg.deprec.ctor"
1466 "The '%s' constructor is deprecated.")
1467
1468 ;; NativeFunction
1469 (js2-msg "msg.no.function.ref.found"
1470 "no source found to decompile function reference %s")
1471
1472 (js2-msg "msg.arg.isnt.array"
1473 "second argument to Function.prototype.apply must be an array")
1474
1475 ;; NativeGlobal
1476 (js2-msg "msg.bad.esc.mask"
1477 "invalid string escape mask")
1478
1479 ;; NativeRegExp
1480 (js2-msg "msg.bad.quant"
1481 "Invalid quantifier %s")
1482
1483 (js2-msg "msg.overlarge.backref"
1484 "Overly large back reference %s")
1485
1486 (js2-msg "msg.overlarge.min"
1487 "Overly large minimum %s")
1488
1489 (js2-msg "msg.overlarge.max"
1490 "Overly large maximum %s")
1491
1492 (js2-msg "msg.zero.quant"
1493 "Zero quantifier %s")
1494
1495 (js2-msg "msg.max.lt.min"
1496 "Maximum %s less than minimum")
1497
1498 (js2-msg "msg.unterm.quant"
1499 "Unterminated quantifier %s")
1500
1501 (js2-msg "msg.unterm.paren"
1502 "Unterminated parenthetical %s")
1503
1504 (js2-msg "msg.unterm.class"
1505 "Unterminated character class %s")
1506
1507 (js2-msg "msg.bad.range"
1508 "Invalid range in character class.")
1509
1510 (js2-msg "msg.trail.backslash"
1511 "Trailing \\ in regular expression.")
1512
1513 (js2-msg "msg.re.unmatched.right.paren"
1514 "unmatched ) in regular expression.")
1515
1516 (js2-msg "msg.no.regexp"
1517 "Regular expressions are not available.")
1518
1519 (js2-msg "msg.bad.backref"
1520 "back-reference exceeds number of capturing parentheses.")
1521
1522 (js2-msg "msg.bad.regexp.compile"
1523 "Only one argument may be specified if the first "
1524 "argument to RegExp.prototype.compile is a RegExp object.")
1525
1526 ;; Parser
1527 (js2-msg "msg.got.syntax.errors"
1528 "Compilation produced %s syntax errors.")
1529
1530 (js2-msg "msg.var.redecl"
1531 "TypeError: redeclaration of var %s.")
1532
1533 (js2-msg "msg.const.redecl"
1534 "TypeError: redeclaration of const %s.")
1535
1536 (js2-msg "msg.let.redecl"
1537 "TypeError: redeclaration of variable %s.")
1538
1539 (js2-msg "msg.parm.redecl"
1540 "TypeError: redeclaration of formal parameter %s.")
1541
1542 (js2-msg "msg.fn.redecl"
1543 "TypeError: redeclaration of function %s.")
1544
1545 (js2-msg "msg.let.decl.not.in.block"
1546 "SyntaxError: let declaration not directly within block")
1547
1548 ;; NodeTransformer
1549 (js2-msg "msg.dup.label"
1550 "duplicated label")
1551
1552 (js2-msg "msg.undef.label"
1553 "undefined label")
1554
1555 (js2-msg "msg.bad.break"
1556 "unlabelled break must be inside loop or switch")
1557
1558 (js2-msg "msg.continue.outside"
1559 "continue must be inside loop")
1560
1561 (js2-msg "msg.continue.nonloop"
1562 "continue can only use labels of iteration statements")
1563
1564 (js2-msg "msg.bad.throw.eol"
1565 "Line terminator is not allowed between the throw "
1566 "keyword and throw expression.")
1567
1568 (js2-msg "msg.no.paren.parms"
1569 "missing ( before function parameters.")
1570
1571 (js2-msg "msg.no.parm"
1572 "missing formal parameter")
1573
1574 (js2-msg "msg.no.paren.after.parms"
1575 "missing ) after formal parameters")
1576
1577 (js2-msg "msg.no.brace.body"
1578 "missing '{' before function body")
1579
1580 (js2-msg "msg.no.brace.after.body"
1581 "missing } after function body")
1582
1583 (js2-msg "msg.no.paren.cond"
1584 "missing ( before condition")
1585
1586 (js2-msg "msg.no.paren.after.cond"
1587 "missing ) after condition")
1588
1589 (js2-msg "msg.no.semi.stmt"
1590 "missing ; before statement")
1591
1592 (js2-msg "msg.missing.semi"
1593 "missing ; after statement")
1594
1595 (js2-msg "msg.no.name.after.dot"
1596 "missing name after . operator")
1597
1598 (js2-msg "msg.no.name.after.coloncolon"
1599 "missing name after :: operator")
1600
1601 (js2-msg "msg.no.name.after.dotdot"
1602 "missing name after .. operator")
1603
1604 (js2-msg "msg.no.name.after.xmlAttr"
1605 "missing name after .@")
1606
1607 (js2-msg "msg.no.bracket.index"
1608 "missing ] in index expression")
1609
1610 (js2-msg "msg.no.paren.switch"
1611 "missing ( before switch expression")
1612
1613 (js2-msg "msg.no.paren.after.switch"
1614 "missing ) after switch expression")
1615
1616 (js2-msg "msg.no.brace.switch"
1617 "missing '{' before switch body")
1618
1619 (js2-msg "msg.bad.switch"
1620 "invalid switch statement")
1621
1622 (js2-msg "msg.no.colon.case"
1623 "missing : after case expression")
1624
1625 (js2-msg "msg.double.switch.default"
1626 "double default label in the switch statement")
1627
1628 (js2-msg "msg.no.while.do"
1629 "missing while after do-loop body")
1630
1631 (js2-msg "msg.no.paren.for"
1632 "missing ( after for")
1633
1634 (js2-msg "msg.no.semi.for"
1635 "missing ; after for-loop initializer")
1636
1637 (js2-msg "msg.no.semi.for.cond"
1638 "missing ; after for-loop condition")
1639
1640 (js2-msg "msg.in.after.for.name"
1641 "missing in after for")
1642
1643 (js2-msg "msg.no.paren.for.ctrl"
1644 "missing ) after for-loop control")
1645
1646 (js2-msg "msg.no.paren.with"
1647 "missing ( before with-statement object")
1648
1649 (js2-msg "msg.no.paren.after.with"
1650 "missing ) after with-statement object")
1651
1652 (js2-msg "msg.no.paren.after.let"
1653 "missing ( after let")
1654
1655 (js2-msg "msg.no.paren.let"
1656 "missing ) after variable list")
1657
1658 (js2-msg "msg.no.curly.let"
1659 "missing } after let statement")
1660
1661 (js2-msg "msg.bad.return"
1662 "invalid return")
1663
1664 (js2-msg "msg.no.brace.block"
1665 "missing } in compound statement")
1666
1667 (js2-msg "msg.bad.label"
1668 "invalid label")
1669
1670 (js2-msg "msg.bad.var"
1671 "missing variable name")
1672
1673 (js2-msg "msg.bad.var.init"
1674 "invalid variable initialization")
1675
1676 (js2-msg "msg.no.colon.cond"
1677 "missing : in conditional expression")
1678
1679 (js2-msg "msg.no.paren.arg"
1680 "missing ) after argument list")
1681
1682 (js2-msg "msg.no.bracket.arg"
1683 "missing ] after element list")
1684
1685 (js2-msg "msg.bad.prop"
1686 "invalid property id")
1687
1688 (js2-msg "msg.no.colon.prop"
1689 "missing : after property id")
1690
1691 (js2-msg "msg.no.brace.prop"
1692 "missing } after property list")
1693
1694 (js2-msg "msg.no.paren"
1695 "missing ) in parenthetical")
1696
1697 (js2-msg "msg.reserved.id"
1698 "identifier is a reserved word")
1699
1700 (js2-msg "msg.no.paren.catch"
1701 "missing ( before catch-block condition")
1702
1703 (js2-msg "msg.bad.catchcond"
1704 "invalid catch block condition")
1705
1706 (js2-msg "msg.catch.unreachable"
1707 "any catch clauses following an unqualified catch are unreachable")
1708
1709 (js2-msg "msg.no.brace.try"
1710 "missing '{' before try block")
1711
1712 (js2-msg "msg.no.brace.catchblock"
1713 "missing '{' before catch-block body")
1714
1715 (js2-msg "msg.try.no.catchfinally"
1716 "'try' without 'catch' or 'finally'")
1717
1718 (js2-msg "msg.no.return.value"
1719 "function %s does not always return a value")
1720
1721 (js2-msg "msg.anon.no.return.value"
1722 "anonymous function does not always return a value")
1723
1724 (js2-msg "msg.return.inconsistent"
1725 "return statement is inconsistent with previous usage")
1726
1727 (js2-msg "msg.generator.returns"
1728 "TypeError: generator function '%s' returns a value")
1729
1730 (js2-msg "msg.anon.generator.returns"
1731 "TypeError: anonymous generator function returns a value")
1732
1733 (js2-msg "msg.syntax"
1734 "syntax error")
1735
1736 (js2-msg "msg.unexpected.eof"
1737 "Unexpected end of file")
1738
1739 (js2-msg "msg.XML.bad.form"
1740 "illegally formed XML syntax")
1741
1742 (js2-msg "msg.XML.not.available"
1743 "XML runtime not available")
1744
1745 (js2-msg "msg.too.deep.parser.recursion"
1746 "Too deep recursion while parsing")
1747
1748 (js2-msg "msg.no.side.effects"
1749 "Code has no side effects")
1750
1751 (js2-msg "msg.extra.trailing.comma"
1752 "Trailing comma is not legal in an ECMA-262 object initializer")
1753
1754 (js2-msg "msg.array.trailing.comma"
1755 "Trailing comma yields different behavior across browsers")
1756
1757 (js2-msg "msg.equal.as.assign"
1758 (concat "Test for equality (==) mistyped as assignment (=)?"
1759 " (parenthesize to suppress warning)"))
1760
1761 (js2-msg "msg.var.hides.arg"
1762 "Variable %s hides argument")
1763
1764 (js2-msg "msg.destruct.assign.no.init"
1765 "Missing = in destructuring declaration")
1766
1767 ;; ScriptRuntime
1768 (js2-msg "msg.no.properties"
1769 "%s has no properties.")
1770
1771 (js2-msg "msg.invalid.iterator"
1772 "Invalid iterator value")
1773
1774 (js2-msg "msg.iterator.primitive"
1775 "__iterator__ returned a primitive value")
1776
1777 (js2-msg "msg.assn.create.strict"
1778 "Assignment to undeclared variable %s")
1779
1780 (js2-msg "msg.ref.undefined.prop"
1781 "Reference to undefined property '%s'")
1782
1783 (js2-msg "msg.prop.not.found"
1784 "Property %s not found.")
1785
1786 (js2-msg "msg.invalid.type"
1787 "Invalid JavaScript value of type %s")
1788
1789 (js2-msg "msg.primitive.expected"
1790 "Primitive type expected (had %s instead)")
1791
1792 (js2-msg "msg.namespace.expected"
1793 "Namespace object expected to left of :: (found %s instead)")
1794
1795 (js2-msg "msg.null.to.object"
1796 "Cannot convert null to an object.")
1797
1798 (js2-msg "msg.undef.to.object"
1799 "Cannot convert undefined to an object.")
1800
1801 (js2-msg "msg.cyclic.value"
1802 "Cyclic %s value not allowed.")
1803
1804 (js2-msg "msg.is.not.defined"
1805 "'%s' is not defined.")
1806
1807 (js2-msg "msg.undef.prop.read"
1808 "Cannot read property '%s' from %s")
1809
1810 (js2-msg "msg.undef.prop.write"
1811 "Cannot set property '%s' of %s to '%s'")
1812
1813 (js2-msg "msg.undef.prop.delete"
1814 "Cannot delete property '%s' of %s")
1815
1816 (js2-msg "msg.undef.method.call"
1817 "Cannot call method '%s' of %s")
1818
1819 (js2-msg "msg.undef.with"
1820 "Cannot apply 'with' to %s")
1821
1822 (js2-msg "msg.isnt.function"
1823 "%s is not a function, it is %s.")
1824
1825 (js2-msg "msg.isnt.function.in"
1826 "Cannot call property %s in object %s. "
1827 "It is not a function, it is '%s'.")
1828
1829 (js2-msg "msg.function.not.found"
1830 "Cannot find function %s.")
1831
1832 (js2-msg "msg.function.not.found.in"
1833 "Cannot find function %s in object %s.")
1834
1835 (js2-msg "msg.isnt.xml.object"
1836 "%s is not an xml object.")
1837
1838 (js2-msg "msg.no.ref.to.get"
1839 "%s is not a reference to read reference value.")
1840
1841 (js2-msg "msg.no.ref.to.set"
1842 "%s is not a reference to set reference value to %s.")
1843
1844 (js2-msg "msg.no.ref.from.function"
1845 "Function %s can not be used as the left-hand "
1846 "side of assignment or as an operand of ++ or -- operator.")
1847
1848 (js2-msg "msg.bad.default.value"
1849 "Object's getDefaultValue() method returned an object.")
1850
1851 (js2-msg "msg.instanceof.not.object"
1852 "Can't use instanceof on a non-object.")
1853
1854 (js2-msg "msg.instanceof.bad.prototype"
1855 "'prototype' property of %s is not an object.")
1856
1857 (js2-msg "msg.bad.radix"
1858 "illegal radix %s.")
1859
1860 ;; ScriptableObject
1861 (js2-msg "msg.default.value"
1862 "Cannot find default value for object.")
1863
1864 (js2-msg "msg.zero.arg.ctor"
1865 "Cannot load class '%s' which has no zero-parameter constructor.")
1866
1867 (js2-msg "msg.ctor.multiple.parms"
1868 "Can't define constructor or class %s since more than "
1869 "one constructor has multiple parameters.")
1870
1871 (js2-msg "msg.extend.scriptable"
1872 "%s must extend ScriptableObject in order to define property %s.")
1873
1874 (js2-msg "msg.bad.getter.parms"
1875 "In order to define a property, getter %s must have zero "
1876 "parameters or a single ScriptableObject parameter.")
1877
1878 (js2-msg "msg.obj.getter.parms"
1879 "Expected static or delegated getter %s to take "
1880 "a ScriptableObject parameter.")
1881
1882 (js2-msg "msg.getter.static"
1883 "Getter and setter must both be static or neither be static.")
1884
1885 (js2-msg "msg.setter.return"
1886 "Setter must have void return type: %s")
1887
1888 (js2-msg "msg.setter2.parms"
1889 "Two-parameter setter must take a ScriptableObject as "
1890 "its first parameter.")
1891
1892 (js2-msg "msg.setter1.parms"
1893 "Expected single parameter setter for %s")
1894
1895 (js2-msg "msg.setter2.expected"
1896 "Expected static or delegated setter %s to take two parameters.")
1897
1898 (js2-msg "msg.setter.parms"
1899 "Expected either one or two parameters for setter.")
1900
1901 (js2-msg "msg.setter.bad.type"
1902 "Unsupported parameter type '%s' in setter '%s'.")
1903
1904 (js2-msg "msg.add.sealed"
1905 "Cannot add a property to a sealed object: %s.")
1906
1907 (js2-msg "msg.remove.sealed"
1908 "Cannot remove a property from a sealed object: %s.")
1909
1910 (js2-msg "msg.modify.sealed"
1911 "Cannot modify a property of a sealed object: %s.")
1912
1913 (js2-msg "msg.modify.readonly"
1914 "Cannot modify readonly property: %s.")
1915
1916 ;; TokenStream
1917 (js2-msg "msg.missing.exponent"
1918 "missing exponent")
1919
1920 (js2-msg "msg.caught.nfe"
1921 "number format error")
1922
1923 (js2-msg "msg.unterminated.string.lit"
1924 "unterminated string literal")
1925
1926 (js2-msg "msg.unterminated.comment"
1927 "unterminated comment")
1928
1929 (js2-msg "msg.unterminated.re.lit"
1930 "unterminated regular expression literal")
1931
1932 (js2-msg "msg.invalid.re.flag"
1933 "invalid flag after regular expression")
1934
1935 (js2-msg "msg.no.re.input.for"
1936 "no input for %s")
1937
1938 (js2-msg "msg.illegal.character"
1939 "illegal character")
1940
1941 (js2-msg "msg.invalid.escape"
1942 "invalid Unicode escape sequence")
1943
1944 (js2-msg "msg.bad.namespace"
1945 "not a valid default namespace statement. "
1946 "Syntax is: default xml namespace = EXPRESSION;")
1947
1948 ;; TokensStream warnings
1949 (js2-msg "msg.bad.octal.literal"
1950 "illegal octal literal digit %s; "
1951 "interpreting it as a decimal digit")
1952
1953 (js2-msg "msg.reserved.keyword"
1954 "illegal usage of future reserved keyword %s; "
1955 "interpreting it as ordinary identifier")
1956
1957 (js2-msg "msg.script.is.not.constructor"
1958 "Script objects are not constructors.")
1959
1960 ;; Arrays
1961 (js2-msg "msg.arraylength.bad"
1962 "Inappropriate array length.")
1963
1964 ;; Arrays
1965 (js2-msg "msg.arraylength.too.big"
1966 "Array length %s exceeds supported capacity limit.")
1967
1968 ;; URI
1969 (js2-msg "msg.bad.uri"
1970 "Malformed URI sequence.")
1971
1972 ;; Number
1973 (js2-msg "msg.bad.precision"
1974 "Precision %s out of range.")
1975
1976 ;; NativeGenerator
1977 (js2-msg "msg.send.newborn"
1978 "Attempt to send value to newborn generator")
1979
1980 (js2-msg "msg.already.exec.gen"
1981 "Already executing generator")
1982
1983 (js2-msg "msg.StopIteration.invalid"
1984 "StopIteration may not be changed to an arbitrary object.")
1985
1986 ;; Interpreter
1987 (js2-msg "msg.yield.closing"
1988 "Yield from closing generator")
1989
1990 ;;; Utilities
1991
1992 (defun js2-delete-if (predicate list)
1993 "Remove all items satisfying PREDICATE in LIST."
1994 (loop for item in list
1995 if (not (funcall predicate item))
1996 collect item))
1997
1998 (defun js2-position (element list)
1999 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2000 Returns nil if element is not found in the list."
2001 (let ((count 0)
2002 found)
2003 (while (and list (not found))
2004 (if (eq element (car list))
2005 (setq found t)
2006 (setq count (1+ count)
2007 list (cdr list))))
2008 (if found count)))
2009
2010 (defun js2-find-if (predicate list)
2011 "Find first item satisfying PREDICATE in LIST."
2012 (let (result)
2013 (while (and list (not result))
2014 (if (funcall predicate (car list))
2015 (setq result (car list)))
2016 (setq list (cdr list)))
2017 result))
2018
2019 (defmacro js2-time (form)
2020 "Evaluate FORM, discard result, and return elapsed time in sec"
2021 (declare (debug t))
2022 (let ((beg (make-symbol "--js2-time-beg--"))
2023 (delta (make-symbol "--js2-time-end--")))
2024 `(let ((,beg (current-time))
2025 ,delta)
2026 ,form
2027 (/ (truncate (* (- (float-time (current-time))
2028 (float-time ,beg))
2029 10000))
2030 10000.0))))
2031
2032 (defsubst js2-same-line (pos)
2033 "Return t if POS is on the same line as current point."
2034 (and (>= pos (point-at-bol))
2035 (<= pos (point-at-eol))))
2036
2037 (defsubst js2-same-line-2 (p1 p2)
2038 "Return t if p1 is on the same line as p2."
2039 (save-excursion
2040 (goto-char p1)
2041 (js2-same-line p2)))
2042
2043 (defun js2-code-bug ()
2044 "Signal an error when we encounter an unexpected code path."
2045 (error "failed assertion"))
2046
2047 (defsubst js2-record-text-property (beg end prop value)
2048 "Record a text property to set when parsing finishes."
2049 (push (list beg end prop value) js2-mode-deferred-properties))
2050
2051 ;; I'd like to associate errors with nodes, but for now the
2052 ;; easiest thing to do is get the context info from the last token.
2053 (defsubst js2-record-parse-error (msg &optional arg pos len)
2054 (push (list (list msg arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2057 js2-parsed-errors))
2058
2059 (defsubst js2-report-error (msg &optional msg-arg pos len)
2060 "Signal a syntax error or record a parse error."
2061 (if js2-recover-from-parse-errors
2062 (js2-record-parse-error msg msg-arg pos len)
2063 (signal 'js2-syntax-error
2064 (list msg
2065 js2-ts-lineno
2066 (save-excursion
2067 (goto-char js2-ts-cursor)
2068 (current-column))
2069 js2-ts-hit-eof))))
2070
2071 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2072 (if js2-compiler-report-warning-as-error
2073 (js2-report-error msg msg-arg pos len)
2074 (push (list (list msg msg-arg)
2075 (or pos js2-token-beg)
2076 (or len (- js2-token-end js2-token-beg)))
2077 js2-parsed-warnings)))
2078
2079 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2080 (if js2-compiler-strict-mode
2081 (js2-report-warning msg-id msg-arg beg
2082 (and beg end (- end beg)))))
2083
2084 (put 'js2-syntax-error 'error-conditions
2085 '(error syntax-error js2-syntax-error))
2086 (put 'js2-syntax-error 'error-message "Syntax error")
2087
2088 (put 'js2-parse-error 'error-conditions
2089 '(error parse-error js2-parse-error))
2090 (put 'js2-parse-error 'error-message "Parse error")
2091
2092 (defmacro js2-clear-flag (flags flag)
2093 `(setq ,flags (logand ,flags (lognot ,flag))))
2094
2095 (defmacro js2-set-flag (flags flag)
2096 "Logical-or FLAG into FLAGS."
2097 `(setq ,flags (logior ,flags ,flag)))
2098
2099 (defsubst js2-flag-set-p (flags flag)
2100 (/= 0 (logand flags flag)))
2101
2102 (defsubst js2-flag-not-set-p (flags flag)
2103 (zerop (logand flags flag)))
2104
2105 ;; Stolen shamelessly from James Clark's nxml-mode.
2106 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2107 "Evaluate BODY without any text property changes modifying the buffer.
2108 Any text properties changes happen as usual but the changes are not treated as
2109 modifications to the buffer."
2110 (declare (indent 0) (debug t))
2111 (let ((modified (make-symbol "modified")))
2112 `(let ((,modified (buffer-modified-p))
2113 (inhibit-read-only t)
2114 (inhibit-modification-hooks t)
2115 (buffer-undo-list t)
2116 (deactivate-mark nil)
2117 ;; Apparently these avoid file locking problems.
2118 (buffer-file-name nil)
2119 (buffer-file-truename nil))
2120 (unwind-protect
2121 (progn ,@body)
2122 (unless ,modified
2123 (restore-buffer-modified-p nil))))))
2124
2125 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2126 "Evaluate BODY with the _ character set to be word-syntax."
2127 (declare (indent 0) (debug t))
2128 (let ((old-syntax (make-symbol "old-syntax")))
2129 `(let ((,old-syntax (string (char-syntax ?_))))
2130 (unwind-protect
2131 (progn
2132 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2133 ,@body)
2134 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2135
2136 (defsubst js2-char-uppercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2139 (/= c (downcase c)))
2140
2141 (defsubst js2-char-lowercase-p (c)
2142 "Return t if C is an uppercase character.
2143 Handles unicode and latin chars properly."
2144 (/= c (upcase c)))
2145
2146 ;;; AST struct and function definitions
2147
2148 ;; flags for ast node property 'member-type (used for e4x operators)
2149 (defvar js2-property-flag #x1 "property access: element is valid name")
2150 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2151 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2152
2153 (defsubst js2-relpos (pos anchor)
2154 "Convert POS to be relative to ANCHOR.
2155 If POS is nil, returns nil."
2156 (and pos (- pos anchor)))
2157
2158 (defsubst js2-make-pad (indent)
2159 (if (zerop indent)
2160 ""
2161 (make-string (* indent js2-basic-offset) ? )))
2162
2163 (defsubst js2-visit-ast (node callback)
2164 "Visit every node in ast NODE with visitor CALLBACK.
2165
2166 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2167 called twice: once to visit the node, and again after all the node's
2168 children have been processed. The END-P argument is nil on the first
2169 call and non-nil on the second call. The return value of the callback
2170 affects the traversal: if non-nil, the children of NODE are processed.
2171 If the callback returns nil, or if the node has no children, then the
2172 callback is called immediately with a non-nil END-P argument.
2173
2174 The node traversal is approximately lexical-order, although there
2175 are currently no guarantees around this."
2176 (if node
2177 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2178 ;; visit the node
2179 (when (funcall callback node nil)
2180 ;; visit the kids
2181 (cond
2182 ((eq vfunc 'js2-visit-none)
2183 nil) ; don't even bother calling it
2184 ;; Each AST node type has to define a `js2-visitor' function
2185 ;; that takes a node and a callback, and calls `js2-visit-ast'
2186 ;; on each child of the node.
2187 (vfunc
2188 (funcall vfunc node callback))
2189 (t
2190 (error "%s does not define a visitor-traversal function"
2191 (aref node 0)))))
2192 ;; call the end-visit
2193 (funcall callback node t))))
2194
2195 (defstruct (js2-node
2196 (:constructor nil)) ; abstract
2197 "Base AST node type."
2198 (type -1) ; token type
2199 (pos -1) ; start position of this AST node in parsed input
2200 (len 1) ; num characters spanned by the node
2201 props ; optional node property list (an alist)
2202 parent) ; link to parent node; null for root
2203
2204 (defsubst js2-node-get-prop (node prop &optional default)
2205 (or (cadr (assoc prop (js2-node-props node))) default))
2206
2207 (defsubst js2-node-set-prop (node prop value)
2208 (setf (js2-node-props node)
2209 (cons (list prop value) (js2-node-props node))))
2210
2211 (defsubst js2-fixup-starts (n nodes)
2212 "Adjust the start positions of NODES to be relative to N.
2213 Any node in the list may be nil, for convenience."
2214 (dolist (node nodes)
2215 (when node
2216 (setf (js2-node-pos node) (- (js2-node-pos node)
2217 (js2-node-pos n))))))
2218
2219 (defsubst js2-node-add-children (parent &rest nodes)
2220 "Set parent node of NODES to PARENT, and return PARENT.
2221 Does nothing if we're not recording parent links.
2222 If any given node in NODES is nil, doesn't record that link."
2223 (js2-fixup-starts parent nodes)
2224 (dolist (node nodes)
2225 (and node
2226 (setf (js2-node-parent node) parent))))
2227
2228 ;; Non-recursive since it's called a frightening number of times.
2229 (defsubst js2-node-abs-pos (n)
2230 (let ((pos (js2-node-pos n)))
2231 (while (setq n (js2-node-parent n))
2232 (setq pos (+ pos (js2-node-pos n))))
2233 pos))
2234
2235 (defsubst js2-node-abs-end (n)
2236 "Return absolute buffer position of end of N."
2237 (+ (js2-node-abs-pos n) (js2-node-len n)))
2238
2239 ;; It's important to make sure block nodes have a lisp list for the
2240 ;; child nodes, to limit printing recursion depth in an AST that
2241 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2242 ;; a sufficiently large vector tree.
2243
2244 (defstruct (js2-block-node
2245 (:include js2-node)
2246 (:constructor nil)
2247 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2248 (pos js2-token-beg)
2249 len
2250 props
2251 kids)))
2252 "A block of statements."
2253 kids) ; a lisp list of the child statement nodes
2254
2255 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2256 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2257
2258 (defsubst js2-visit-block (ast callback)
2259 "Visit the `js2-block-node' children of AST."
2260 (dolist (kid (js2-block-node-kids ast))
2261 (js2-visit-ast kid callback)))
2262
2263 (defun js2-print-block (n i)
2264 (let ((pad (js2-make-pad i)))
2265 (insert pad "{\n")
2266 (dolist (kid (js2-block-node-kids n))
2267 (js2-print-ast kid (1+ i)))
2268 (insert pad "}")))
2269
2270 (defstruct (js2-scope
2271 (:include js2-block-node)
2272 (:constructor nil)
2273 (:constructor make-js2-scope (&key (type js2-BLOCK)
2274 (pos js2-token-beg)
2275 len
2276 kids)))
2277 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2278 ;; I don't have one of those handy, so I'll use an alist for now.
2279 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2280 ;; and is much lighter-weight to construct (both CPU and mem).
2281 ;; The keys are interned strings (symbols) for faster lookup.
2282 ;; Should switch to hybrid alist/hashtable eventually.
2283 symbol-table ; an alist of (symbol . js2-symbol)
2284 parent-scope ; a `js2-scope'
2285 top) ; top-level `js2-scope' (script/function)
2286
2287 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2288 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2289
2290 (defun js2-scope-set-parent-scope (scope parent)
2291 (setf (js2-scope-parent-scope scope) parent
2292 (js2-scope-top scope) (if (null parent)
2293 scope
2294 (js2-scope-top parent))))
2295
2296 (defun js2-node-get-enclosing-scope (node)
2297 "Return the innermost `js2-scope' node surrounding NODE.
2298 Returns nil if there is no enclosing scope node."
2299 (let ((parent (js2-node-parent node)))
2300 (while (not (js2-scope-p parent))
2301 (setq parent (js2-node-parent parent)))
2302 parent))
2303
2304 (defun js2-get-defining-scope (scope name)
2305 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2306 Returns `js2-scope' in which NAME is defined, or nil if not found."
2307 (let ((sym (if (symbolp name)
2308 name
2309 (intern name)))
2310 table
2311 result
2312 (continue t))
2313 (while (and scope continue)
2314 (if (and (setq table (js2-scope-symbol-table scope))
2315 (assq sym table))
2316 (setq continue nil
2317 result scope)
2318 (setq scope (js2-scope-parent-scope scope))))
2319 result))
2320
2321 (defsubst js2-scope-get-symbol (scope name)
2322 "Return symbol table entry for NAME in SCOPE.
2323 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2324 (and (js2-scope-symbol-table scope)
2325 (cdr (assq (if (symbolp name)
2326 name
2327 (intern name))
2328 (js2-scope-symbol-table scope)))))
2329
2330 (defsubst js2-scope-put-symbol (scope name symbol)
2331 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2332 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2333 (let* ((table (js2-scope-symbol-table scope))
2334 (sym (if (symbolp name) name (intern name)))
2335 (entry (assq sym table)))
2336 (if entry
2337 (setcdr entry symbol)
2338 (push (cons sym symbol)
2339 (js2-scope-symbol-table scope)))))
2340
2341 (defstruct (js2-symbol
2342 (:constructor nil)
2343 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2344 "A symbol table entry."
2345 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2346 ;; js2-LET, or js2-CONST
2347 decl-type
2348 name ; string
2349 ast-node) ; a `js2-node'
2350
2351 (defstruct (js2-error-node
2352 (:include js2-node)
2353 (:constructor nil) ; silence emacs21 byte-compiler
2354 (:constructor make-js2-error-node (&key (type js2-ERROR)
2355 (pos js2-token-beg)
2356 len)))
2357 "AST node representing a parse error.")
2358
2359 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2360 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2361
2362 (defstruct (js2-script-node
2363 (:include js2-scope)
2364 (:constructor nil)
2365 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2366 (pos js2-token-beg)
2367 len
2368 var-decls
2369 fun-decls)))
2370 functions ; lisp list of nested functions
2371 regexps ; lisp list of (string . flags)
2372 symbols ; alist (every symbol gets unique index)
2373 (param-count 0)
2374 var-names ; vector of string names
2375 consts ; bool-vector matching var-decls
2376 (temp-number 0)) ; for generating temp variables
2377
2378 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2379 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2380
2381 (defun js2-print-script (node indent)
2382 (dolist (kid (js2-block-node-kids node))
2383 (js2-print-ast kid indent)))
2384
2385 (defstruct (js2-ast-root
2386 (:include js2-script-node)
2387 (:constructor nil)
2388 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2389 (pos js2-token-beg)
2390 len
2391 buffer)))
2392 "The root node of a js2 AST."
2393 buffer ; the source buffer from which the code was parsed
2394 comments ; a lisp list of comments, ordered by start position
2395 errors ; a lisp list of errors found during parsing
2396 warnings ; a lisp list of warnings found during parsing
2397 node-count) ; number of nodes in the tree, including the root
2398
2399 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2400 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2401
2402 (defun js2-visit-ast-root (ast callback)
2403 (dolist (kid (js2-ast-root-kids ast))
2404 (js2-visit-ast kid callback))
2405 (dolist (comment (js2-ast-root-comments ast))
2406 (js2-visit-ast comment callback)))
2407
2408 (defstruct (js2-comment-node
2409 (:include js2-node)
2410 (:constructor nil)
2411 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2412 (pos js2-token-beg)
2413 len
2414 (format js2-ts-comment-type))))
2415 format) ; 'line, 'block, 'jsdoc or 'html
2416
2417 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2418 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2419
2420 (defun js2-print-comment (n i)
2421 ;; We really ought to link end-of-line comments to their nodes.
2422 ;; Or maybe we could add a new comment type, 'endline.
2423 (insert (js2-make-pad i)
2424 (js2-node-string n)))
2425
2426 (defstruct (js2-expr-stmt-node
2427 (:include js2-node)
2428 (:constructor nil)
2429 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2430 (pos js2-ts-cursor)
2431 len
2432 expr)))
2433 "An expression statement."
2434 expr)
2435
2436 (defsubst js2-expr-stmt-node-set-has-result (node)
2437 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2438 (setf (js2-node-type node) js2-EXPR_RESULT))
2439
2440 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2441 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2442
2443 (defun js2-visit-expr-stmt-node (n v)
2444 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2445
2446 (defun js2-print-expr-stmt-node (n indent)
2447 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2448 (insert ";\n"))
2449
2450 (defstruct (js2-loop-node
2451 (:include js2-scope)
2452 (:constructor nil))
2453 "Abstract supertype of loop nodes."
2454 body ; a `js2-block-node'
2455 lp ; position of left-paren, nil if omitted
2456 rp) ; position of right-paren, nil if omitted
2457
2458 (defstruct (js2-do-node
2459 (:include js2-loop-node)
2460 (:constructor nil)
2461 (:constructor make-js2-do-node (&key (type js2-DO)
2462 (pos js2-token-beg)
2463 len
2464 body
2465 condition
2466 while-pos
2467 lp
2468 rp)))
2469 "AST node for do-loop."
2470 condition ; while (expression)
2471 while-pos) ; buffer position of 'while' keyword
2472
2473 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2474 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2475
2476 (defun js2-visit-do-node (n v)
2477 (js2-visit-ast (js2-do-node-body n) v)
2478 (js2-visit-ast (js2-do-node-condition n) v))
2479
2480 (defun js2-print-do-node (n i)
2481 (let ((pad (js2-make-pad i)))
2482 (insert pad "do {\n")
2483 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2484 (js2-print-ast kid (1+ i)))
2485 (insert pad "} while (")
2486 (js2-print-ast (js2-do-node-condition n) 0)
2487 (insert ");\n")))
2488
2489 (defstruct (js2-while-node
2490 (:include js2-loop-node)
2491 (:constructor nil)
2492 (:constructor make-js2-while-node (&key (type js2-WHILE)
2493 (pos js2-token-beg)
2494 len
2495 body
2496 condition
2497 lp
2498 rp)))
2499 "AST node for while-loop."
2500 condition) ; while-condition
2501
2502 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2503 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2504
2505 (defun js2-visit-while-node (n v)
2506 (js2-visit-ast (js2-while-node-condition n) v)
2507 (js2-visit-ast (js2-while-node-body n) v))
2508
2509 (defun js2-print-while-node (n i)
2510 (let ((pad (js2-make-pad i)))
2511 (insert pad "while (")
2512 (js2-print-ast (js2-while-node-condition n) 0)
2513 (insert ") {\n")
2514 (js2-print-body (js2-while-node-body n) (1+ i))
2515 (insert pad "}\n")))
2516
2517 (defstruct (js2-for-node
2518 (:include js2-loop-node)
2519 (:constructor nil)
2520 (:constructor make-js2-for-node (&key (type js2-FOR)
2521 (pos js2-ts-cursor)
2522 len
2523 body
2524 init
2525 condition
2526 update
2527 lp
2528 rp)))
2529 "AST node for a C-style for-loop."
2530 init ; initialization expression
2531 condition ; loop condition
2532 update) ; update clause
2533
2534 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2535 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2536
2537 (defun js2-visit-for-node (n v)
2538 (js2-visit-ast (js2-for-node-init n) v)
2539 (js2-visit-ast (js2-for-node-condition n) v)
2540 (js2-visit-ast (js2-for-node-update n) v)
2541 (js2-visit-ast (js2-for-node-body n) v))
2542
2543 (defun js2-print-for-node (n i)
2544 (let ((pad (js2-make-pad i)))
2545 (insert pad "for (")
2546 (js2-print-ast (js2-for-node-init n) 0)
2547 (insert "; ")
2548 (js2-print-ast (js2-for-node-condition n) 0)
2549 (insert "; ")
2550 (js2-print-ast (js2-for-node-update n) 0)
2551 (insert ") {\n")
2552 (js2-print-body (js2-for-node-body n) (1+ i))
2553 (insert pad "}\n")))
2554
2555 (defstruct (js2-for-in-node
2556 (:include js2-loop-node)
2557 (:constructor nil)
2558 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2559 (pos js2-ts-cursor)
2560 len
2561 body
2562 iterator
2563 object
2564 in-pos
2565 each-pos
2566 foreach-p
2567 lp
2568 rp)))
2569 "AST node for a for..in loop."
2570 iterator ; [var] foo in ...
2571 object ; object over which we're iterating
2572 in-pos ; buffer position of 'in' keyword
2573 each-pos ; buffer position of 'each' keyword, if foreach-p
2574 foreach-p) ; t if it's a for-each loop
2575
2576 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2577 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2578
2579 (defun js2-visit-for-in-node (n v)
2580 (js2-visit-ast (js2-for-in-node-iterator n) v)
2581 (js2-visit-ast (js2-for-in-node-object n) v)
2582 (js2-visit-ast (js2-for-in-node-body n) v))
2583
2584 (defun js2-print-for-in-node (n i)
2585 (let ((pad (js2-make-pad i))
2586 (foreach (js2-for-in-node-foreach-p n)))
2587 (insert pad "for ")
2588 (if foreach
2589 (insert "each "))
2590 (insert "(")
2591 (js2-print-ast (js2-for-in-node-iterator n) 0)
2592 (insert " in ")
2593 (js2-print-ast (js2-for-in-node-object n) 0)
2594 (insert ") {\n")
2595 (js2-print-body (js2-for-in-node-body n) (1+ i))
2596 (insert pad "}\n")))
2597
2598 (defstruct (js2-return-node
2599 (:include js2-node)
2600 (:constructor nil)
2601 (:constructor make-js2-return-node (&key (type js2-RETURN)
2602 (pos js2-ts-cursor)
2603 len
2604 retval)))
2605 "AST node for a return statement."
2606 retval) ; expression to return, or 'undefined
2607
2608 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2609 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2610
2611 (defun js2-visit-return-node (n v)
2612 (js2-visit-ast (js2-return-node-retval n) v))
2613
2614 (defun js2-print-return-node (n i)
2615 (insert (js2-make-pad i) "return")
2616 (when (js2-return-node-retval n)
2617 (insert " ")
2618 (js2-print-ast (js2-return-node-retval n) 0))
2619 (insert ";\n"))
2620
2621 (defstruct (js2-if-node
2622 (:include js2-node)
2623 (:constructor nil)
2624 (:constructor make-js2-if-node (&key (type js2-IF)
2625 (pos js2-ts-cursor)
2626 len
2627 condition
2628 then-part
2629 else-pos
2630 else-part
2631 lp
2632 rp)))
2633 "AST node for an if-statement."
2634 condition ; expression
2635 then-part ; statement or block
2636 else-pos ; optional buffer position of 'else' keyword
2637 else-part ; optional statement or block
2638 lp ; position of left-paren, nil if omitted
2639 rp) ; position of right-paren, nil if omitted
2640
2641 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2642 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2643
2644 (defun js2-visit-if-node (n v)
2645 (js2-visit-ast (js2-if-node-condition n) v)
2646 (js2-visit-ast (js2-if-node-then-part n) v)
2647 (js2-visit-ast (js2-if-node-else-part n) v))
2648
2649 (defun js2-print-if-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (then-part (js2-if-node-then-part n))
2652 (else-part (js2-if-node-else-part n)))
2653 (insert pad "if (")
2654 (js2-print-ast (js2-if-node-condition n) 0)
2655 (insert ") {\n")
2656 (js2-print-body then-part (1+ i))
2657 (insert pad "}")
2658 (cond
2659 ((not else-part)
2660 (insert "\n"))
2661 ((js2-if-node-p else-part)
2662 (insert " else ")
2663 (js2-print-body else-part i))
2664 (t
2665 (insert " else {\n")
2666 (js2-print-body else-part (1+ i))
2667 (insert pad "}\n")))))
2668
2669 (defstruct (js2-try-node
2670 (:include js2-node)
2671 (:constructor nil)
2672 (:constructor make-js2-try-node (&key (type js2-TRY)
2673 (pos js2-ts-cursor)
2674 len
2675 try-block
2676 catch-clauses
2677 finally-block)))
2678 "AST node for a try-statement."
2679 try-block
2680 catch-clauses ; a lisp list of `js2-catch-node'
2681 finally-block) ; a `js2-finally-node'
2682
2683 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2684 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2685
2686 (defun js2-visit-try-node (n v)
2687 (js2-visit-ast (js2-try-node-try-block n) v)
2688 (dolist (clause (js2-try-node-catch-clauses n))
2689 (js2-visit-ast clause v))
2690 (js2-visit-ast (js2-try-node-finally-block n) v))
2691
2692 (defun js2-print-try-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (catches (js2-try-node-catch-clauses n))
2695 (finally (js2-try-node-finally-block n)))
2696 (insert pad "try {\n")
2697 (js2-print-body (js2-try-node-try-block n) (1+ i))
2698 (insert pad "}")
2699 (when catches
2700 (dolist (catch catches)
2701 (js2-print-ast catch i)))
2702 (if finally
2703 (js2-print-ast finally i)
2704 (insert "\n"))))
2705
2706 (defstruct (js2-catch-node
2707 (:include js2-node)
2708 (:constructor nil)
2709 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2710 (pos js2-ts-cursor)
2711 len
2712 param
2713 guard-kwd
2714 guard-expr
2715 block
2716 lp
2717 rp)))
2718 "AST node for a catch clause."
2719 param ; destructuring form or simple name node
2720 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2721 guard-expr ; catch condition, a `js2-node'
2722 block ; statements, a `js2-block-node'
2723 lp ; buffer position of left-paren, nil if omitted
2724 rp) ; buffer position of right-paren, nil if omitted
2725
2726 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2727 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2728
2729 (defun js2-visit-catch-node (n v)
2730 (js2-visit-ast (js2-catch-node-param n) v)
2731 (when (js2-catch-node-guard-kwd n)
2732 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2733 (js2-visit-ast (js2-catch-node-block n) v))
2734
2735 (defun js2-print-catch-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (guard-kwd (js2-catch-node-guard-kwd n))
2738 (guard-expr (js2-catch-node-guard-expr n)))
2739 (insert " catch (")
2740 (js2-print-ast (js2-catch-node-param n) 0)
2741 (when guard-kwd
2742 (insert " if ")
2743 (js2-print-ast guard-expr 0))
2744 (insert ") {\n")
2745 (js2-print-body (js2-catch-node-block n) (1+ i))
2746 (insert pad "}")))
2747
2748 (defstruct (js2-finally-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2752 (pos js2-ts-cursor)
2753 len
2754 body)))
2755 "AST node for a finally clause."
2756 body) ; a `js2-node', often but not always a block node
2757
2758 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2759 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2760
2761 (defun js2-visit-finally-node (n v)
2762 (js2-visit-ast (js2-finally-node-body n) v))
2763
2764 (defun js2-print-finally-node (n i)
2765 (let ((pad (js2-make-pad i)))
2766 (insert " finally {\n")
2767 (js2-print-body (js2-finally-node-body n) (1+ i))
2768 (insert pad "}\n")))
2769
2770 (defstruct (js2-switch-node
2771 (:include js2-node)
2772 (:constructor nil)
2773 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2774 (pos js2-ts-cursor)
2775 len
2776 discriminant
2777 cases
2778 lp
2779 rp)))
2780 "AST node for a switch statement."
2781 discriminant ; a `js2-node' (switch expression)
2782 cases ; a lisp list of `js2-case-node'
2783 lp ; position of open-paren for discriminant, nil if omitted
2784 rp) ; position of close-paren for discriminant, nil if omitted
2785
2786 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2787 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2788
2789 (defun js2-visit-switch-node (n v)
2790 (js2-visit-ast (js2-switch-node-discriminant n) v)
2791 (dolist (c (js2-switch-node-cases n))
2792 (js2-visit-ast c v)))
2793
2794 (defun js2-print-switch-node (n i)
2795 (let ((pad (js2-make-pad i))
2796 (cases (js2-switch-node-cases n)))
2797 (insert pad "switch (")
2798 (js2-print-ast (js2-switch-node-discriminant n) 0)
2799 (insert ") {\n")
2800 (dolist (case cases)
2801 (js2-print-ast case i))
2802 (insert pad "}\n")))
2803
2804 (defstruct (js2-case-node
2805 (:include js2-block-node)
2806 (:constructor nil)
2807 (:constructor make-js2-case-node (&key (type js2-CASE)
2808 (pos js2-ts-cursor)
2809 len
2810 kids
2811 expr)))
2812 "AST node for a case clause of a switch statement."
2813 expr) ; the case expression (nil for default)
2814
2815 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2816 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2817
2818 (defun js2-visit-case-node (n v)
2819 (js2-visit-ast (js2-case-node-expr n) v)
2820 (js2-visit-block n v))
2821
2822 (defun js2-print-case-node (n i)
2823 (let ((pad (js2-make-pad i))
2824 (expr (js2-case-node-expr n)))
2825 (insert pad)
2826 (if (null expr)
2827 (insert "default:\n")
2828 (insert "case ")
2829 (js2-print-ast expr 0)
2830 (insert ":\n"))
2831 (dolist (kid (js2-case-node-kids n))
2832 (js2-print-ast kid (1+ i)))))
2833
2834 (defstruct (js2-throw-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-throw-node (&key (type js2-THROW)
2838 (pos js2-ts-cursor)
2839 len
2840 expr)))
2841 "AST node for a throw statement."
2842 expr) ; the expression to throw
2843
2844 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2845 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2846
2847 (defun js2-visit-throw-node (n v)
2848 (js2-visit-ast (js2-throw-node-expr n) v))
2849
2850 (defun js2-print-throw-node (n i)
2851 (insert (js2-make-pad i) "throw ")
2852 (js2-print-ast (js2-throw-node-expr n) 0)
2853 (insert ";\n"))
2854
2855 (defstruct (js2-with-node
2856 (:include js2-node)
2857 (:constructor nil)
2858 (:constructor make-js2-with-node (&key (type js2-WITH)
2859 (pos js2-ts-cursor)
2860 len
2861 object
2862 body
2863 lp
2864 rp)))
2865 "AST node for a with-statement."
2866 object
2867 body
2868 lp ; buffer position of left-paren around object, nil if omitted
2869 rp) ; buffer position of right-paren around object, nil if omitted
2870
2871 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2872 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2873
2874 (defun js2-visit-with-node (n v)
2875 (js2-visit-ast (js2-with-node-object n) v)
2876 (js2-visit-ast (js2-with-node-body n) v))
2877
2878 (defun js2-print-with-node (n i)
2879 (let ((pad (js2-make-pad i)))
2880 (insert pad "with (")
2881 (js2-print-ast (js2-with-node-object n) 0)
2882 (insert ") {\n")
2883 (js2-print-body (js2-with-node-body n) (1+ i))
2884 (insert pad "}\n")))
2885
2886 (defstruct (js2-label-node
2887 (:include js2-node)
2888 (:constructor nil)
2889 (:constructor make-js2-label-node (&key (type js2-LABEL)
2890 (pos js2-ts-cursor)
2891 len
2892 name)))
2893 "AST node for a statement label or case label."
2894 name ; a string
2895 loop) ; for validating and code-generating continue-to-label
2896
2897 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2898 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2899
2900 (defun js2-print-label (n i)
2901 (insert (js2-make-pad i)
2902 (js2-label-node-name n)
2903 ":\n"))
2904
2905 (defstruct (js2-labeled-stmt-node
2906 (:include js2-node)
2907 (:constructor nil)
2908 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2909 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2910 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2911 (pos js2-ts-cursor)
2912 len
2913 labels
2914 stmt)))
2915 "AST node for a statement with one or more labels.
2916 Multiple labels for a statement are collapsed into the labels field."
2917 labels ; lisp list of `js2-label-node'
2918 stmt) ; the statement these labels are for
2919
2920 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2922
2923 (defun js2-get-label-by-name (lbl-stmt name)
2924 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2925 Returns nil if no such label is in the list."
2926 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2927 result)
2928 (while (and label-list (not result))
2929 (if (string= (js2-label-node-name (car label-list)) name)
2930 (setq result (car label-list))
2931 (setq label-list (cdr label-list))))
2932 result))
2933
2934 (defun js2-visit-labeled-stmt (n v)
2935 (dolist (label (js2-labeled-stmt-node-labels n))
2936 (js2-visit-ast label v))
2937 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2938
2939 (defun js2-print-labeled-stmt (n i)
2940 (dolist (label (js2-labeled-stmt-node-labels n))
2941 (js2-print-ast label i))
2942 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2943
2944 (defun js2-labeled-stmt-node-contains (node label)
2945 "Return t if NODE contains LABEL in its label set.
2946 NODE is a `js2-labels-node'. LABEL is an identifier."
2947 (loop for nl in (js2-labeled-stmt-node-labels node)
2948 if (string= label (js2-label-node-name nl))
2949 return t
2950 finally return nil))
2951
2952 (defsubst js2-labeled-stmt-node-add-label (node label)
2953 "Add a `js2-label-node' to the label set for this statement."
2954 (setf (js2-labeled-stmt-node-labels node)
2955 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2956
2957 (defstruct (js2-jump-node
2958 (:include js2-node)
2959 (:constructor nil))
2960 "Abstract supertype of break and continue nodes."
2961 label ; `js2-name-node' for location of label identifier, if present
2962 target) ; target js2-labels-node or loop/switch statement
2963
2964 (defun js2-visit-jump-node (n v)
2965 (js2-visit-ast (js2-jump-node-label n) v))
2966
2967 (defstruct (js2-break-node
2968 (:include js2-jump-node)
2969 (:constructor nil)
2970 (:constructor make-js2-break-node (&key (type js2-BREAK)
2971 (pos js2-ts-cursor)
2972 len
2973 label
2974 target)))
2975 "AST node for a break statement.
2976 The label field is a `js2-name-node', possibly nil, for the named label
2977 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2978 is the target of the break - a label node or enclosing loop/switch statement.")
2979
2980 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2981 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2982
2983 (defun js2-print-break-node (n i)
2984 (insert (js2-make-pad i) "break")
2985 (when (js2-break-node-label n)
2986 (insert " ")
2987 (js2-print-ast (js2-break-node-label n) 0))
2988 (insert ";\n"))
2989
2990 (defstruct (js2-continue-node
2991 (:include js2-jump-node)
2992 (:constructor nil)
2993 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2994 (pos js2-ts-cursor)
2995 len
2996 label
2997 target)))
2998 "AST node for a continue statement.
2999 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3000 It is nil if continue specifies no label. The target field is the jump target:
3001 a `js2-label-node' or the innermost enclosing loop.")
3002
3003 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3004 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3005
3006 (defun js2-print-continue-node (n i)
3007 (insert (js2-make-pad i) "continue")
3008 (when (js2-continue-node-label n)
3009 (insert " ")
3010 (js2-print-ast (js2-continue-node-label n) 0))
3011 (insert ";\n"))
3012
3013 (defstruct (js2-function-node
3014 (:include js2-script-node)
3015 (:constructor nil)
3016 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3017 (pos js2-ts-cursor)
3018 len
3019 (ftype 'FUNCTION)
3020 (form 'FUNCTION_STATEMENT)
3021 (name "")
3022 params
3023 body
3024 lp
3025 rp)))
3026 "AST node for a function declaration.
3027 The `params' field is a lisp list of nodes. Each node is either a simple
3028 `js2-name-node', or if it's a destructuring-assignment parameter, a
3029 `js2-array-node' or `js2-object-node'."
3030 ftype ; FUNCTION, GETTER or SETTER
3031 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3032 name ; function name (a `js2-name-node', or nil if anonymous)
3033 params ; a lisp list of destructuring forms or simple name nodes
3034 body ; a `js2-block-node' or expression node (1.8 only)
3035 lp ; position of arg-list open-paren, or nil if omitted
3036 rp ; position of arg-list close-paren, or nil if omitted
3037 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3038 needs-activation ; t if we need an activation object for this frame
3039 is-generator ; t if this function contains a yield
3040 member-expr) ; nonstandard Ecma extension from Rhino
3041
3042 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3043 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3044
3045 (defun js2-visit-function-node (n v)
3046 (js2-visit-ast (js2-function-node-name n) v)
3047 (dolist (p (js2-function-node-params n))
3048 (js2-visit-ast p v))
3049 (js2-visit-ast (js2-function-node-body n) v))
3050
3051 (defun js2-print-function-node (n i)
3052 (let ((pad (js2-make-pad i))
3053 (getter (js2-node-get-prop n 'GETTER_SETTER))
3054 (name (js2-function-node-name n))
3055 (params (js2-function-node-params n))
3056 (body (js2-function-node-body n))
3057 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3058 (unless getter
3059 (insert pad "function"))
3060 (when name
3061 (insert " ")
3062 (js2-print-ast name 0))
3063 (insert "(")
3064 (loop with len = (length params)
3065 for param in params
3066 for count from 1
3067 do
3068 (js2-print-ast param 0)
3069 (if (< count len)
3070 (insert ", ")))
3071 (insert ") {")
3072 (unless expr
3073 (insert "\n"))
3074 ;; TODO: fix this to be smarter about indenting, etc.
3075 (js2-print-body body (1+ i))
3076 (insert pad "}")
3077 (unless expr
3078 (insert "\n"))))
3079
3080 (defsubst js2-function-name (node)
3081 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3082 (and (js2-function-node-name node)
3083 (js2-name-node-name (js2-function-node-name node))))
3084
3085 ;; Having this be an expression node makes it more flexible.
3086 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3087 ;; that work better if you assume it's an expression. Whenever we have
3088 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3089 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3090 (defstruct (js2-var-decl-node
3091 (:include js2-node)
3092 (:constructor nil)
3093 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3094 (pos js2-token-beg)
3095 len
3096 kids
3097 decl-type)))
3098 "AST node for a variable declaration list (VAR, CONST or LET).
3099 The node bounds differ depending on the declaration type. For VAR or
3100 CONST declarations, the bounds include the var/const keyword. For LET
3101 declarations, the node begins at the position of the first child."
3102 kids ; a lisp list of `js2-var-init-node' structs.
3103 decl-type) ; js2-VAR, js2-CONST or js2-LET
3104
3105 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3106 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3107
3108 (defun js2-visit-var-decl (n v)
3109 (dolist (kid (js2-var-decl-node-kids n))
3110 (js2-visit-ast kid v)))
3111
3112 (defun js2-print-var-decl (n i)
3113 (let ((pad (js2-make-pad i))
3114 (tt (js2-var-decl-node-decl-type n)))
3115 (insert pad)
3116 (insert (cond
3117 ((= tt js2-VAR) "var ")
3118 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3119 ((= tt js2-CONST) "const ")
3120 (t
3121 (error "malformed var-decl node"))))
3122 (loop with kids = (js2-var-decl-node-kids n)
3123 with len = (length kids)
3124 for kid in kids
3125 for count from 1
3126 do
3127 (js2-print-ast kid 0)
3128 (if (< count len)
3129 (insert ", ")))))
3130
3131 (defstruct (js2-var-init-node
3132 (:include js2-node)
3133 (:constructor nil)
3134 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3135 (pos js2-ts-cursor)
3136 len
3137 target
3138 initializer)))
3139 "AST node for a variable declaration.
3140 The type field will be js2-CONST for a const decl."
3141 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3142 initializer) ; initializer expression, a `js2-node'
3143
3144 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3145 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3146
3147 (defun js2-visit-var-init-node (n v)
3148 (js2-visit-ast (js2-var-init-node-target n) v)
3149 (js2-visit-ast (js2-var-init-node-initializer n) v))
3150
3151 (defun js2-print-var-init-node (n i)
3152 (let ((pad (js2-make-pad i))
3153 (name (js2-var-init-node-target n))
3154 (init (js2-var-init-node-initializer n)))
3155 (insert pad)
3156 (js2-print-ast name 0)
3157 (when init
3158 (insert " = ")
3159 (js2-print-ast init 0))))
3160
3161 (defstruct (js2-cond-node
3162 (:include js2-node)
3163 (:constructor nil)
3164 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3165 (pos js2-ts-cursor)
3166 len
3167 test-expr
3168 true-expr
3169 false-expr
3170 q-pos
3171 c-pos)))
3172 "AST node for the ternary operator"
3173 test-expr
3174 true-expr
3175 false-expr
3176 q-pos ; buffer position of ?
3177 c-pos) ; buffer position of :
3178
3179 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3180 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3181
3182 (defun js2-visit-cond-node (n v)
3183 (js2-visit-ast (js2-cond-node-test-expr n) v)
3184 (js2-visit-ast (js2-cond-node-true-expr n) v)
3185 (js2-visit-ast (js2-cond-node-false-expr n) v))
3186
3187 (defun js2-print-cond-node (n i)
3188 (let ((pad (js2-make-pad i)))
3189 (insert pad)
3190 (js2-print-ast (js2-cond-node-test-expr n) 0)
3191 (insert " ? ")
3192 (js2-print-ast (js2-cond-node-true-expr n) 0)
3193 (insert " : ")
3194 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3195
3196 (defstruct (js2-infix-node
3197 (:include js2-node)
3198 (:constructor nil)
3199 (:constructor make-js2-infix-node (&key type
3200 (pos js2-ts-cursor)
3201 len
3202 op-pos
3203 left
3204 right)))
3205 "Represents infix expressions.
3206 Includes assignment ops like `|=', and the comma operator.
3207 The type field inherited from `js2-node' holds the operator."
3208 op-pos ; buffer position where operator begins
3209 left ; any `js2-node'
3210 right) ; any `js2-node'
3211
3212 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3213 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3214
3215 (defun js2-visit-infix-node (n v)
3216 (js2-visit-ast (js2-infix-node-left n) v)
3217 (js2-visit-ast (js2-infix-node-right n) v))
3218
3219 (defconst js2-operator-tokens
3220 (let ((table (make-hash-table :test 'eq))
3221 (tokens
3222 (list (cons js2-IN "in")
3223 (cons js2-TYPEOF "typeof")
3224 (cons js2-INSTANCEOF "instanceof")
3225 (cons js2-DELPROP "delete")
3226 (cons js2-COMMA ",")
3227 (cons js2-COLON ":")
3228 (cons js2-OR "||")
3229 (cons js2-AND "&&")
3230 (cons js2-INC "++")
3231 (cons js2-DEC "--")
3232 (cons js2-BITOR "|")
3233 (cons js2-BITXOR "^")
3234 (cons js2-BITAND "&")
3235 (cons js2-EQ "==")
3236 (cons js2-NE "!=")
3237 (cons js2-LT "<")
3238 (cons js2-LE "<=")
3239 (cons js2-GT ">")
3240 (cons js2-GE ">=")
3241 (cons js2-LSH "<<")
3242 (cons js2-RSH ">>")
3243 (cons js2-URSH ">>>")
3244 (cons js2-ADD "+") ; infix plus
3245 (cons js2-SUB "-") ; infix minus
3246 (cons js2-MUL "*")
3247 (cons js2-DIV "/")
3248 (cons js2-MOD "%")
3249 (cons js2-NOT "!")
3250 (cons js2-BITNOT "~")
3251 (cons js2-POS "+") ; unary plus
3252 (cons js2-NEG "-") ; unary minus
3253 (cons js2-SHEQ "===") ; shallow equality
3254 (cons js2-SHNE "!==") ; shallow inequality
3255 (cons js2-ASSIGN "=")
3256 (cons js2-ASSIGN_BITOR "|=")
3257 (cons js2-ASSIGN_BITXOR "^=")
3258 (cons js2-ASSIGN_BITAND "&=")
3259 (cons js2-ASSIGN_LSH "<<=")
3260 (cons js2-ASSIGN_RSH ">>=")
3261 (cons js2-ASSIGN_URSH ">>>=")
3262 (cons js2-ASSIGN_ADD "+=")
3263 (cons js2-ASSIGN_SUB "-=")
3264 (cons js2-ASSIGN_MUL "*=")
3265 (cons js2-ASSIGN_DIV "/=")
3266 (cons js2-ASSIGN_MOD "%="))))
3267 (loop for (k . v) in tokens do
3268 (puthash k v table))
3269 table))
3270
3271 (defun js2-print-infix-node (n i)
3272 (let* ((tt (js2-node-type n))
3273 (op (gethash tt js2-operator-tokens)))
3274 (unless op
3275 (error "unrecognized infix operator %s" (js2-node-type n)))
3276 (insert (js2-make-pad i))
3277 (js2-print-ast (js2-infix-node-left n) 0)
3278 (unless (= tt js2-COMMA)
3279 (insert " "))
3280 (insert op)
3281 (insert " ")
3282 (js2-print-ast (js2-infix-node-right n) 0)))
3283
3284 (defstruct (js2-assign-node
3285 (:include js2-infix-node)
3286 (:constructor nil)
3287 (:constructor make-js2-assign-node (&key type
3288 (pos js2-ts-cursor)
3289 len
3290 op-pos
3291 left
3292 right)))
3293 "Represents any assignment.
3294 The type field holds the actual assignment operator.")
3295
3296 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3297 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3298
3299 (defstruct (js2-unary-node
3300 (:include js2-node)
3301 (:constructor nil)
3302 (:constructor make-js2-unary-node (&key type ; required
3303 (pos js2-ts-cursor)
3304 len
3305 operand)))
3306 "AST node type for unary operator nodes.
3307 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3308 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3309 property is added if the operator follows the operand."
3310 operand) ; a `js2-node' expression
3311
3312 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3313 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3314
3315 (defun js2-visit-unary-node (n v)
3316 (js2-visit-ast (js2-unary-node-operand n) v))
3317
3318 (defun js2-print-unary-node (n i)
3319 (let* ((tt (js2-node-type n))
3320 (op (gethash tt js2-operator-tokens))
3321 (postfix (js2-node-get-prop n 'postfix)))
3322 (unless op
3323 (error "unrecognized unary operator %s" tt))
3324 (insert (js2-make-pad i))
3325 (unless postfix
3326 (insert op))
3327 (if (or (= tt js2-TYPEOF)
3328 (= tt js2-DELPROP))
3329 (insert " "))
3330 (js2-print-ast (js2-unary-node-operand n) 0)
3331 (when postfix
3332 (insert op))))
3333
3334 (defstruct (js2-let-node
3335 (:include js2-scope)
3336 (:constructor nil)
3337 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3338 (pos js2-token-beg)
3339 len
3340 vars
3341 body
3342 lp
3343 rp)))
3344 "AST node for a let expression or a let statement.
3345 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3346 vars ; a `js2-var-decl-node'
3347 body ; a `js2-node' representing the expression or body block
3348 lp
3349 rp)
3350
3351 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3352 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3353
3354 (defun js2-visit-let-node (n v)
3355 (js2-visit-ast (js2-let-node-vars n) v)
3356 (js2-visit-ast (js2-let-node-body n) v))
3357
3358 (defun js2-print-let-node (n i)
3359 (insert (js2-make-pad i) "let (")
3360 (js2-print-ast (js2-let-node-vars n) 0)
3361 (insert ") ")
3362 (js2-print-ast (js2-let-node-body n) i))
3363
3364 (defstruct (js2-keyword-node
3365 (:include js2-node)
3366 (:constructor nil)
3367 (:constructor make-js2-keyword-node (&key type
3368 (pos js2-token-beg)
3369 (len (- js2-ts-cursor pos)))))
3370 "AST node representing a literal keyword such as `null'.
3371 Used for `null', `this', `true', `false' and `debugger'.
3372 The node type is set to js2-NULL, js2-THIS, etc.")
3373
3374 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3376
3377 (defun js2-print-keyword-node (n i)
3378 (insert (js2-make-pad i)
3379 (let ((tt (js2-node-type n)))
3380 (cond
3381 ((= tt js2-THIS) "this")
3382 ((= tt js2-NULL) "null")
3383 ((= tt js2-TRUE) "true")
3384 ((= tt js2-FALSE) "false")
3385 ((= tt js2-DEBUGGER) "debugger")
3386 (t (error "Invalid keyword literal type: %d" tt))))))
3387
3388 (defsubst js2-this-node-p (node)
3389 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3390 (eq (js2-node-type node) js2-THIS))
3391
3392 (defstruct (js2-new-node
3393 (:include js2-node)
3394 (:constructor nil)
3395 (:constructor make-js2-new-node (&key (type js2-NEW)
3396 (pos js2-token-beg)
3397 len
3398 target
3399 args
3400 initializer
3401 lp
3402 rp)))
3403 "AST node for new-expression such as new Foo()."
3404 target ; an identifier or reference
3405 args ; a lisp list of argument nodes
3406 lp ; position of left-paren, nil if omitted
3407 rp ; position of right-paren, nil if omitted
3408 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3409
3410 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3411 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3412
3413 (defun js2-visit-new-node (n v)
3414 (js2-visit-ast (js2-new-node-target n) v)
3415 (dolist (arg (js2-new-node-args n))
3416 (js2-visit-ast arg v))
3417 (js2-visit-ast (js2-new-node-initializer n) v))
3418
3419 (defun js2-print-new-node (n i)
3420 (insert (js2-make-pad i) "new ")
3421 (js2-print-ast (js2-new-node-target n))
3422 (insert "(")
3423 (js2-print-list (js2-new-node-args n))
3424 (insert ")")
3425 (when (js2-new-node-initializer n)
3426 (insert " ")
3427 (js2-print-ast (js2-new-node-initializer n))))
3428
3429 (defstruct (js2-name-node
3430 (:include js2-node)
3431 (:constructor nil)
3432 (:constructor make-js2-name-node (&key (type js2-NAME)
3433 (pos js2-token-beg)
3434 (len (- js2-ts-cursor
3435 js2-token-beg))
3436 (name js2-ts-string))))
3437 "AST node for a JavaScript identifier"
3438 name ; a string
3439 scope) ; a `js2-scope' (optional, used for codegen)
3440
3441 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3442 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3443
3444 (defun js2-print-name-node (n i)
3445 (insert (js2-make-pad i)
3446 (js2-name-node-name n)))
3447
3448 (defsubst js2-name-node-length (node)
3449 "Return identifier length of NODE, a `js2-name-node'.
3450 Returns 0 if NODE is nil or its identifier field is nil."
3451 (if node
3452 (length (js2-name-node-name node))
3453 0))
3454
3455 (defstruct (js2-number-node
3456 (:include js2-node)
3457 (:constructor nil)
3458 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3459 (pos js2-token-beg)
3460 (len (- js2-ts-cursor
3461 js2-token-beg))
3462 (value js2-ts-string)
3463 (num-value js2-ts-number))))
3464 "AST node for a number literal."
3465 value ; the original string, e.g. "6.02e23"
3466 num-value) ; the parsed number value
3467
3468 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3470
3471 (defun js2-print-number-node (n i)
3472 (insert (js2-make-pad i)
3473 (number-to-string (js2-number-node-num-value n))))
3474
3475 (defstruct (js2-regexp-node
3476 (:include js2-node)
3477 (:constructor nil)
3478 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3479 (pos js2-token-beg)
3480 (len (- js2-ts-cursor
3481 js2-token-beg))
3482 value
3483 flags)))
3484 "AST node for a regular expression literal."
3485 value ; the regexp string, without // delimiters
3486 flags) ; a string of flags, e.g. `mi'.
3487
3488 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3489 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3490
3491 (defun js2-print-regexp (n i)
3492 (insert (js2-make-pad i)
3493 "/"
3494 (js2-regexp-node-value n)
3495 "/")
3496 (if (js2-regexp-node-flags n)
3497 (insert (js2-regexp-node-flags n))))
3498
3499 (defstruct (js2-string-node
3500 (:include js2-node)
3501 (:constructor nil)
3502 (:constructor make-js2-string-node (&key (type js2-STRING)
3503 (pos js2-token-beg)
3504 (len (- js2-ts-cursor
3505 js2-token-beg))
3506 (value js2-ts-string))))
3507 "String literal.
3508 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3509 You can tell the quote type by looking at the first character."
3510 value) ; the characters of the string, including the quotes
3511
3512 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3513 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3514
3515 (defun js2-print-string-node (n i)
3516 (insert (js2-make-pad i)
3517 (js2-node-string n)))
3518
3519 (defstruct (js2-array-node
3520 (:include js2-node)
3521 (:constructor nil)
3522 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3523 (pos js2-ts-cursor)
3524 len
3525 elems)))
3526 "AST node for an array literal."
3527 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3528
3529 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3530 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3531
3532 (defun js2-visit-array-node (n v)
3533 (dolist (e (js2-array-node-elems n))
3534 (js2-visit-ast e v)))
3535
3536 (defun js2-print-array-node (n i)
3537 (insert (js2-make-pad i) "[")
3538 (js2-print-list (js2-array-node-elems n))
3539 (insert "]"))
3540
3541 (defstruct (js2-object-node
3542 (:include js2-node)
3543 (:constructor nil)
3544 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3545 (pos js2-ts-cursor)
3546 len
3547 elems)))
3548 "AST node for an object literal expression.
3549 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3550 the latter represents abbreviation in destructuring expressions."
3551 elems)
3552
3553 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3554 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3555
3556 (defun js2-visit-object-node (n v)
3557 (dolist (e (js2-object-node-elems n))
3558 (js2-visit-ast e v)))
3559
3560 (defun js2-print-object-node (n i)
3561 (insert (js2-make-pad i) "{")
3562 (js2-print-list (js2-object-node-elems n))
3563 (insert "}"))
3564
3565 (defstruct (js2-object-prop-node
3566 (:include js2-infix-node)
3567 (:constructor nil)
3568 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3569 (pos js2-ts-cursor)
3570 len
3571 left
3572 right
3573 op-pos)))
3574 "AST node for an object literal prop:value entry.
3575 The `left' field is the property: a name node, string node or number node.
3576 The `right' field is a `js2-node' representing the initializer value.")
3577
3578 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3579 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3580
3581 (defun js2-print-object-prop-node (n i)
3582 (insert (js2-make-pad i))
3583 (js2-print-ast (js2-object-prop-node-left n) 0)
3584 (insert ":")
3585 (js2-print-ast (js2-object-prop-node-right n) 0))
3586
3587 (defstruct (js2-getter-setter-node
3588 (:include js2-infix-node)
3589 (:constructor nil)
3590 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3591 (pos js2-ts-cursor)
3592 len
3593 left
3594 right)))
3595 "AST node for a getter/setter property in an object literal.
3596 The `left' field is the `js2-name-node' naming the getter/setter prop.
3597 The `right' field is always an anonymous `js2-function-node' with a node
3598 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3599
3600 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3601 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3602
3603 (defun js2-print-getter-setter (n i)
3604 (let ((pad (js2-make-pad i))
3605 (left (js2-getter-setter-node-left n))
3606 (right (js2-getter-setter-node-right n)))
3607 (insert pad)
3608 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3609 (js2-print-ast left 0)
3610 (js2-print-ast right 0)))
3611
3612 (defstruct (js2-prop-get-node
3613 (:include js2-infix-node)
3614 (:constructor nil)
3615 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3616 (pos js2-ts-cursor)
3617 len
3618 left
3619 right)))
3620 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3621
3622 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3623 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3624
3625 (defun js2-visit-prop-get-node (n v)
3626 (js2-visit-ast (js2-prop-get-node-left n) v)
3627 (js2-visit-ast (js2-prop-get-node-right n) v))
3628
3629 (defun js2-print-prop-get-node (n i)
3630 (insert (js2-make-pad i))
3631 (js2-print-ast (js2-prop-get-node-left n) 0)
3632 (insert ".")
3633 (js2-print-ast (js2-prop-get-node-right n) 0))
3634
3635 (defstruct (js2-elem-get-node
3636 (:include js2-node)
3637 (:constructor nil)
3638 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3639 (pos js2-ts-cursor)
3640 len
3641 target
3642 element
3643 lb
3644 rb)))
3645 "AST node for an array index expression such as foo[bar]."
3646 target ; a `js2-node' - the expression preceding the "."
3647 element ; a `js2-node' - the expression in brackets
3648 lb ; position of left-bracket, nil if omitted
3649 rb) ; position of right-bracket, nil if omitted
3650
3651 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3652 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3653
3654 (defun js2-visit-elem-get-node (n v)
3655 (js2-visit-ast (js2-elem-get-node-target n) v)
3656 (js2-visit-ast (js2-elem-get-node-element n) v))
3657
3658 (defun js2-print-elem-get-node (n i)
3659 (insert (js2-make-pad i))
3660 (js2-print-ast (js2-elem-get-node-target n) 0)
3661 (insert "[")
3662 (js2-print-ast (js2-elem-get-node-element n) 0)
3663 (insert "]"))
3664
3665 (defstruct (js2-call-node
3666 (:include js2-node)
3667 (:constructor nil)
3668 (:constructor make-js2-call-node (&key (type js2-CALL)
3669 (pos js2-ts-cursor)
3670 len
3671 target
3672 args
3673 lp
3674 rp)))
3675 "AST node for a JavaScript function call."
3676 target ; a `js2-node' evaluating to the function to call
3677 args ; a lisp list of `js2-node' arguments
3678 lp ; position of open-paren, or nil if missing
3679 rp) ; position of close-paren, or nil if missing
3680
3681 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3682 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3683
3684 (defun js2-visit-call-node (n v)
3685 (js2-visit-ast (js2-call-node-target n) v)
3686 (dolist (arg (js2-call-node-args n))
3687 (js2-visit-ast arg v)))
3688
3689 (defun js2-print-call-node (n i)
3690 (insert (js2-make-pad i))
3691 (js2-print-ast (js2-call-node-target n) 0)
3692 (insert "(")
3693 (js2-print-list (js2-call-node-args n))
3694 (insert ")"))
3695
3696 (defstruct (js2-yield-node
3697 (:include js2-node)
3698 (:constructor nil)
3699 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3700 (pos js2-ts-cursor)
3701 len
3702 value)))
3703 "AST node for yield statement or expression."
3704 value) ; optional: value to be yielded
3705
3706 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3707 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3708
3709 (defun js2-visit-yield-node (n v)
3710 (js2-visit-ast (js2-yield-node-value n) v))
3711
3712 (defun js2-print-yield-node (n i)
3713 (insert (js2-make-pad i))
3714 (insert "yield")
3715 (when (js2-yield-node-value n)
3716 (insert " ")
3717 (js2-print-ast (js2-yield-node-value n) 0)))
3718
3719 (defstruct (js2-paren-node
3720 (:include js2-node)
3721 (:constructor nil)
3722 (:constructor make-js2-paren-node (&key (type js2-LP)
3723 (pos js2-ts-cursor)
3724 len
3725 expr)))
3726 "AST node for a parenthesized expression.
3727 In particular, used when the parens are syntactically optional,
3728 as opposed to required parens such as those enclosing an if-conditional."
3729 expr) ; `js2-node'
3730
3731 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3732 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3733
3734 (defun js2-visit-paren-node (n v)
3735 (js2-visit-ast (js2-paren-node-expr n) v))
3736
3737 (defun js2-print-paren-node (n i)
3738 (insert (js2-make-pad i))
3739 (insert "(")
3740 (js2-print-ast (js2-paren-node-expr n) 0)
3741 (insert ")"))
3742
3743 (defstruct (js2-array-comp-node
3744 (:include js2-scope)
3745 (:constructor nil)
3746 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3747 (pos js2-ts-cursor)
3748 len
3749 result
3750 loops
3751 filter
3752 if-pos
3753 lp
3754 rp)))
3755 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3756 result ; result expression (just after left-bracket)
3757 loops ; a lisp list of `js2-array-comp-loop-node'
3758 filter ; guard/filter expression
3759 if-pos ; buffer pos of 'if' keyword, if present, else nil
3760 lp ; buffer position of if-guard left-paren, or nil if not present
3761 rp) ; buffer position of if-guard right-paren, or nil if not present
3762
3763 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3764 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3765
3766 (defun js2-visit-array-comp-node (n v)
3767 (js2-visit-ast (js2-array-comp-node-result n) v)
3768 (dolist (l (js2-array-comp-node-loops n))
3769 (js2-visit-ast l v))
3770 (js2-visit-ast (js2-array-comp-node-filter n) v))
3771
3772 (defun js2-print-array-comp-node (n i)
3773 (let ((pad (js2-make-pad i))
3774 (result (js2-array-comp-node-result n))
3775 (loops (js2-array-comp-node-loops n))
3776 (filter (js2-array-comp-node-filter n)))
3777 (insert pad "[")
3778 (js2-print-ast result 0)
3779 (dolist (l loops)
3780 (insert " ")
3781 (js2-print-ast l 0))
3782 (when filter
3783 (insert " if (")
3784 (js2-print-ast filter 0))
3785 (insert ")]")))
3786
3787 (defstruct (js2-array-comp-loop-node
3788 (:include js2-for-in-node)
3789 (:constructor nil)
3790 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3791 (pos js2-ts-cursor)
3792 len
3793 iterator
3794 object
3795 in-pos
3796 foreach-p
3797 each-pos
3798 lp
3799 rp)))
3800 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3801
3802 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3803 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3804
3805 (defun js2-visit-array-comp-loop (n v)
3806 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3807 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3808
3809 (defun js2-print-array-comp-loop (n i)
3810 (insert "for (")
3811 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3812 (insert " in ")
3813 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3814 (insert ")"))
3815
3816 (defstruct (js2-empty-expr-node
3817 (:include js2-node)
3818 (:constructor nil)
3819 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3820 (pos js2-token-beg)
3821 len)))
3822 "AST node for an empty expression.")
3823
3824 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3825 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3826
3827 (defstruct (js2-xml-node
3828 (:include js2-block-node)
3829 (:constructor nil)
3830 (:constructor make-js2-xml-node (&key (type js2-XML)
3831 (pos js2-token-beg)
3832 len
3833 kids)))
3834 "AST node for initial parse of E4X literals.
3835 The kids field is a list of XML fragments, each a `js2-string-node' or
3836 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3837
3838 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3839 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3840
3841 (defun js2-print-xml-node (n i)
3842 (dolist (kid (js2-xml-node-kids n))
3843 (js2-print-ast kid i)))
3844
3845 (defstruct (js2-xml-js-expr-node
3846 (:include js2-xml-node)
3847 (:constructor nil)
3848 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3849 (pos js2-ts-cursor)
3850 len
3851 expr)))
3852 "AST node for an embedded JavaScript {expression} in an E4X literal.
3853 The start and end fields correspond to the curly-braces."
3854 expr) ; a `js2-expr-node' of some sort
3855
3856 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3857 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3858
3859 (defun js2-visit-xml-js-expr (n v)
3860 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3861
3862 (defun js2-print-xml-js-expr (n i)
3863 (insert (js2-make-pad i))
3864 (insert "{")
3865 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3866 (insert "}"))
3867
3868 (defstruct (js2-xml-dot-query-node
3869 (:include js2-infix-node)
3870 (:constructor nil)
3871 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3872 (pos js2-ts-cursor)
3873 op-pos
3874 len
3875 left
3876 right
3877 rp)))
3878 "AST node for an E4X foo.(bar) filter expression.
3879 Note that the left-paren is automatically the character immediately
3880 following the dot (.) in the operator. No whitespace is permitted
3881 between the dot and the lp by the scanner."
3882 rp)
3883
3884 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3885 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3886
3887 (defun js2-print-xml-dot-query (n i)
3888 (insert (js2-make-pad i))
3889 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3890 (insert ".(")
3891 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3892 (insert ")"))
3893
3894 (defstruct (js2-xml-ref-node
3895 (:include js2-node)
3896 (:constructor nil)) ; abstract
3897 "Base type for E4X XML attribute-access or property-get expressions.
3898 Such expressions can take a variety of forms. The general syntax has
3899 three parts:
3900
3901 - (optional) an @ (specifying an attribute access)
3902 - (optional) a namespace (a `js2-name-node') and double-colon
3903 - (required) either a `js2-name-node' or a bracketed [expression]
3904
3905 The property-name expressions (examples: ns::name, @name) are
3906 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3907 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3908
3909 This node type (or more specifically, its subclasses) will sometimes
3910 be the right-hand child of a `js2-prop-get-node' or a
3911 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3912 The `js2-xml-ref-node' may also be a standalone primary expression with
3913 no explicit target, which is valid in certain expression contexts such as
3914
3915 company..employee.(@id < 100)
3916
3917 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3918 expression whose parent is a `js2-xml-dot-query-node'."
3919 namespace
3920 at-pos
3921 colon-pos)
3922
3923 (defsubst js2-xml-ref-node-attr-access-p (node)
3924 "Return non-nil if this expression began with an @-token."
3925 (and (numberp (js2-xml-ref-node-at-pos node))
3926 (plusp (js2-xml-ref-node-at-pos node))))
3927
3928 (defstruct (js2-xml-prop-ref-node
3929 (:include js2-xml-ref-node)
3930 (:constructor nil)
3931 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3932 (pos js2-token-beg)
3933 len
3934 propname
3935 namespace
3936 at-pos
3937 colon-pos)))
3938 "AST node for an E4X XML [expr] property-ref expression.
3939 The JavaScript syntax is an optional @, an optional ns::, and a name.
3940
3941 [ '@' ] [ name '::' ] name
3942
3943 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3944 @ns::*, @*::attr, @*::*, and @*.
3945
3946 The node starts at the @ token, if present. Otherwise it starts at the
3947 namespace name. The node bounds extend through the closing right-bracket,
3948 or if it is missing due to a syntax error, through the end of the index
3949 expression."
3950 propname)
3951
3952 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3953 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3954
3955 (defun js2-visit-xml-prop-ref-node (n v)
3956 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3957 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3958
3959 (defun js2-print-xml-prop-ref-node (n i)
3960 (insert (js2-make-pad i))
3961 (if (js2-xml-ref-node-attr-access-p n)
3962 (insert "@"))
3963 (when (js2-xml-prop-ref-node-namespace n)
3964 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3965 (insert "::"))
3966 (if (js2-xml-prop-ref-node-propname n)
3967 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3968
3969 (defstruct (js2-xml-elem-ref-node
3970 (:include js2-xml-ref-node)
3971 (:constructor nil)
3972 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3973 (pos js2-token-beg)
3974 len
3975 expr
3976 lb
3977 rb
3978 namespace
3979 at-pos
3980 colon-pos)))
3981 "AST node for an E4X XML [expr] member-ref expression.
3982 Syntax:
3983
3984 [ '@' ] [ name '::' ] '[' expr ']'
3985
3986 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3987
3988 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3989 is not a legal E4X XML element-ref expression, since it's already used
3990 for standard JavaScript element-get array indexing. Hence, a
3991 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3992 non-nil namespace node, or both.
3993
3994 The node starts at the @ token, if present. Otherwise it starts
3995 at the namespace name. The node bounds extend through the closing
3996 right-bracket, or if it is missing due to a syntax error, through the
3997 end of the index expression."
3998 expr ; the bracketed index expression
3999 lb
4000 rb)
4001
4002 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4003 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4004
4005 (defun js2-visit-xml-elem-ref-node (n v)
4006 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4007 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4008
4009 (defun js2-print-xml-elem-ref-node (n i)
4010 (insert (js2-make-pad i))
4011 (if (js2-xml-ref-node-attr-access-p n)
4012 (insert "@"))
4013 (when (js2-xml-elem-ref-node-namespace n)
4014 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4015 (insert "::"))
4016 (insert "[")
4017 (if (js2-xml-elem-ref-node-expr n)
4018 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4019 (insert "]"))
4020
4021 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4022
4023 (defstruct (js2-xml-start-tag-node
4024 (:include js2-xml-node)
4025 (:constructor nil)
4026 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4027 (pos js2-ts-cursor)
4028 len
4029 name
4030 attrs
4031 kids
4032 empty-p)))
4033 "AST node for an XML start-tag. Not currently used.
4034 The `kids' field is a lisp list of child content nodes."
4035 name ; a `js2-xml-name-node'
4036 attrs ; a lisp list of `js2-xml-attr-node'
4037 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4038
4039 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4040 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4041
4042 (defun js2-visit-xml-start-tag (n v)
4043 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4044 (dolist (attr (js2-xml-start-tag-node-attrs n))
4045 (js2-visit-ast attr v))
4046 (js2-visit-block n v))
4047
4048 (defun js2-print-xml-start-tag (n i)
4049 (insert (js2-make-pad i) "<")
4050 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4051 (when (js2-xml-start-tag-node-attrs n)
4052 (insert " ")
4053 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4054 (insert ">"))
4055
4056 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4057 ;; and add the end-tag to the kids list of the parent as well.
4058 (defstruct (js2-xml-end-tag-node
4059 (:include js2-xml-node)
4060 (:constructor nil)
4061 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4062 (pos js2-ts-cursor)
4063 len
4064 name)))
4065 "AST node for an XML end-tag. Not currently used."
4066 name) ; a `js2-xml-name-node'
4067
4068 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4069 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4070
4071 (defun js2-visit-xml-end-tag (n v)
4072 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4073
4074 (defun js2-print-xml-end-tag (n i)
4075 (insert (js2-make-pad i))
4076 (insert "</")
4077 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4078 (insert ">"))
4079
4080 (defstruct (js2-xml-name-node
4081 (:include js2-xml-node)
4082 (:constructor nil)
4083 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4084 (pos js2-ts-cursor)
4085 len
4086 namespace
4087 kids)))
4088 "AST node for an E4X XML name. Not currently used.
4089 Any XML name can be qualified with a namespace, hence the namespace field.
4090 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4091 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4092 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4093 namespace) ; a `js2-string-node'
4094
4095 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4096 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4097
4098 (defun js2-visit-xml-name-node (n v)
4099 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4100
4101 (defun js2-print-xml-name-node (n i)
4102 (insert (js2-make-pad i))
4103 (when (js2-xml-name-node-namespace n)
4104 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4105 (insert "::"))
4106 (dolist (kid (js2-xml-name-node-kids n))
4107 (js2-print-ast kid 0)))
4108
4109 (defstruct (js2-xml-pi-node
4110 (:include js2-xml-node)
4111 (:constructor nil)
4112 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4113 (pos js2-ts-cursor)
4114 len
4115 name
4116 attrs)))
4117 "AST node for an E4X XML processing instruction. Not currently used."
4118 name ; a `js2-xml-name-node'
4119 attrs) ; a list of `js2-xml-attr-node'
4120
4121 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4122 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4123
4124 (defun js2-visit-xml-pi-node (n v)
4125 (js2-visit-ast (js2-xml-pi-node-name n) v)
4126 (dolist (attr (js2-xml-pi-node-attrs n))
4127 (js2-visit-ast attr v)))
4128
4129 (defun js2-print-xml-pi-node (n i)
4130 (insert (js2-make-pad i) "<?")
4131 (js2-print-ast (js2-xml-pi-node-name n))
4132 (when (js2-xml-pi-node-attrs n)
4133 (insert " ")
4134 (js2-print-list (js2-xml-pi-node-attrs n)))
4135 (insert "?>"))
4136
4137 (defstruct (js2-xml-cdata-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 content)))
4144 "AST node for a CDATA escape section. Not currently used."
4145 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4146
4147 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4148 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4149
4150 (defun js2-visit-xml-cdata-node (n v)
4151 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4152
4153 (defun js2-print-xml-cdata-node (n i)
4154 (insert (js2-make-pad i))
4155 (js2-print-ast (js2-xml-cdata-node-content n)))
4156
4157 (defstruct (js2-xml-attr-node
4158 (:include js2-xml-node)
4159 (:constructor nil)
4160 (:constructor make-js2-attr-node (&key (type js2-XML)
4161 (pos js2-ts-cursor)
4162 len
4163 name
4164 value
4165 eq-pos
4166 quote-type)))
4167 "AST node representing a foo='bar' XML attribute value. Not yet used."
4168 name ; a `js2-xml-name-node'
4169 value ; a `js2-xml-name-node'
4170 eq-pos ; buffer position of "=" sign
4171 quote-type) ; 'single or 'double
4172
4173 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4174 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4175
4176 (defun js2-visit-xml-attr-node (n v)
4177 (js2-visit-ast (js2-xml-attr-node-name n) v)
4178 (js2-visit-ast (js2-xml-attr-node-value n) v))
4179
4180 (defun js2-print-xml-attr-node (n i)
4181 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4182 "'"
4183 "\"")))
4184 (insert (js2-make-pad i))
4185 (js2-print-ast (js2-xml-attr-node-name n) 0)
4186 (insert "=" quote)
4187 (js2-print-ast (js2-xml-attr-node-value n) 0)
4188 (insert quote)))
4189
4190 (defstruct (js2-xml-text-node
4191 (:include js2-xml-node)
4192 (:constructor nil)
4193 (:constructor make-js2-text-node (&key (type js2-XML)
4194 (pos js2-ts-cursor)
4195 len
4196 content)))
4197 "AST node for an E4X XML text node. Not currently used."
4198 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4199
4200 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4201 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4202
4203 (defun js2-visit-xml-text-node (n v)
4204 (js2-visit-ast (js2-xml-text-node-content n) v))
4205
4206 (defun js2-print-xml-text-node (n i)
4207 (insert (js2-make-pad i))
4208 (dolist (kid (js2-xml-text-node-content n))
4209 (js2-print-ast kid)))
4210
4211 (defstruct (js2-xml-comment-node
4212 (:include js2-xml-node)
4213 (:constructor nil)
4214 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4215 (pos js2-ts-cursor)
4216 len)))
4217 "AST node for E4X XML comment. Not currently used.")
4218
4219 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4221
4222 (defun js2-print-xml-comment (n i)
4223 (insert (js2-make-pad i)
4224 (js2-node-string n)))
4225
4226 ;;; Node utilities
4227
4228 (defsubst js2-node-line (n)
4229 "Fetch the source line number at the start of node N.
4230 This is O(n) in the length of the source buffer; use prudently."
4231 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4232
4233 (defsubst js2-block-node-kid (n i)
4234 "Return child I of node N, or nil if there aren't that many."
4235 (nth i (js2-block-node-kids n)))
4236
4237 (defsubst js2-block-node-first (n)
4238 "Return first child of block node N, or nil if there is none."
4239 (first (js2-block-node-kids n)))
4240
4241 (defun js2-node-root (n)
4242 "Return the root of the AST containing N.
4243 If N has no parent pointer, returns N."
4244 (let ((parent (js2-node-parent n)))
4245 (if parent
4246 (js2-node-root parent)
4247 n)))
4248
4249 (defun js2-node-position-in-parent (node &optional parent)
4250 "Return the position of NODE in parent's block-kids list.
4251 PARENT can be supplied if known. Positioned returned is zero-indexed.
4252 Returns 0 if NODE is not a child of a block statement, or if NODE
4253 is not a statement node."
4254 (let ((p (or parent (js2-node-parent node)))
4255 (i 0))
4256 (if (not (js2-block-node-p p))
4257 i
4258 (or (js2-position node (js2-block-node-kids p))
4259 0))))
4260
4261 (defsubst js2-node-short-name (n)
4262 "Return the short name of node N as a string, e.g. `js2-if-node'."
4263 (substring (symbol-name (aref n 0))
4264 (length "cl-struct-")))
4265
4266 (defsubst js2-node-child-list (node)
4267 "Return the child list for NODE, a lisp list of nodes.
4268 Works for block nodes, array nodes, obj literals, funarg lists,
4269 var decls and try nodes (for catch clauses). Note that you should call
4270 `js2-block-node-kids' on the function body for the body statements.
4271 Returns nil for zero-length child lists or unsupported nodes."
4272 (cond
4273 ((js2-function-node-p node)
4274 (js2-function-node-params node))
4275 ((js2-block-node-p node)
4276 (js2-block-node-kids node))
4277 ((js2-try-node-p node)
4278 (js2-try-node-catch-clauses node))
4279 ((js2-array-node-p node)
4280 (js2-array-node-elems node))
4281 ((js2-object-node-p node)
4282 (js2-object-node-elems node))
4283 ((js2-call-node-p node)
4284 (js2-call-node-args node))
4285 ((js2-new-node-p node)
4286 (js2-new-node-args node))
4287 ((js2-var-decl-node-p node)
4288 (js2-var-decl-node-kids node))
4289 (t
4290 nil)))
4291
4292 (defsubst js2-node-set-child-list (node kids)
4293 "Set the child list for NODE to KIDS."
4294 (cond
4295 ((js2-function-node-p node)
4296 (setf (js2-function-node-params node) kids))
4297 ((js2-block-node-p node)
4298 (setf (js2-block-node-kids node) kids))
4299 ((js2-try-node-p node)
4300 (setf (js2-try-node-catch-clauses node) kids))
4301 ((js2-array-node-p node)
4302 (setf (js2-array-node-elems node) kids))
4303 ((js2-object-node-p node)
4304 (setf (js2-object-node-elems node) kids))
4305 ((js2-call-node-p node)
4306 (setf (js2-call-node-args node) kids))
4307 ((js2-new-node-p node)
4308 (setf (js2-new-node-args node) kids))
4309 ((js2-var-decl-node-p node)
4310 (setf (js2-var-decl-node-kids node) kids))
4311 (t
4312 (error "Unsupported node type: %s" (js2-node-short-name node))))
4313 kids)
4314
4315 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4316 (defconst js2-paren-expr-nodes
4317 '(cl-struct-js2-array-comp-loop-node
4318 cl-struct-js2-array-comp-node
4319 cl-struct-js2-call-node
4320 cl-struct-js2-catch-node
4321 cl-struct-js2-do-node
4322 cl-struct-js2-elem-get-node
4323 cl-struct-js2-for-in-node
4324 cl-struct-js2-for-node
4325 cl-struct-js2-function-node
4326 cl-struct-js2-if-node
4327 cl-struct-js2-let-node
4328 cl-struct-js2-new-node
4329 cl-struct-js2-paren-node
4330 cl-struct-js2-switch-node
4331 cl-struct-js2-while-node
4332 cl-struct-js2-with-node
4333 cl-struct-js2-xml-dot-query-node)
4334 "Node types that can have a parenthesized child expression.
4335 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4336
4337 (defsubst js2-paren-expr-node-p (node)
4338 "Return t for nodes that typically have a parenthesized child expression.
4339 Useful for computing the indentation anchors for arg-lists and conditions.
4340 Note that it may return a false positive, for instance when NODE is
4341 a `js2-new-node' and there are no arguments or parentheses."
4342 (memq (aref node 0) js2-paren-expr-nodes))
4343
4344 ;; Fake polymorphism... yech.
4345 (defsubst js2-node-lp (node)
4346 "Return relative left-paren position for NODE, if applicable.
4347 For `js2-elem-get-node' structs, returns left-bracket position.
4348 Note that the position may be nil in the case of a parse error."
4349 (cond
4350 ((js2-elem-get-node-p node)
4351 (js2-elem-get-node-lb node))
4352 ((js2-loop-node-p node)
4353 (js2-loop-node-lp node))
4354 ((js2-function-node-p node)
4355 (js2-function-node-lp node))
4356 ((js2-if-node-p node)
4357 (js2-if-node-lp node))
4358 ((js2-new-node-p node)
4359 (js2-new-node-lp node))
4360 ((js2-call-node-p node)
4361 (js2-call-node-lp node))
4362 ((js2-paren-node-p node)
4363 (js2-node-pos node))
4364 ((js2-switch-node-p node)
4365 (js2-switch-node-lp node))
4366 ((js2-catch-node-p node)
4367 (js2-catch-node-lp node))
4368 ((js2-let-node-p node)
4369 (js2-let-node-lp node))
4370 ((js2-array-comp-node-p node)
4371 (js2-array-comp-node-lp node))
4372 ((js2-with-node-p node)
4373 (js2-with-node-lp node))
4374 ((js2-xml-dot-query-node-p node)
4375 (1+ (js2-infix-node-op-pos node)))
4376 (t
4377 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4378
4379 ;; Fake polymorphism... blech.
4380 (defsubst js2-node-rp (node)
4381 "Return relative right-paren position for NODE, if applicable.
4382 For `js2-elem-get-node' structs, returns right-bracket position.
4383 Note that the position may be nil in the case of a parse error."
4384 (cond
4385 ((js2-elem-get-node-p node)
4386 (js2-elem-get-node-lb node))
4387 ((js2-loop-node-p node)
4388 (js2-loop-node-rp node))
4389 ((js2-function-node-p node)
4390 (js2-function-node-rp node))
4391 ((js2-if-node-p node)
4392 (js2-if-node-rp node))
4393 ((js2-new-node-p node)
4394 (js2-new-node-rp node))
4395 ((js2-call-node-p node)
4396 (js2-call-node-rp node))
4397 ((js2-paren-node-p node)
4398 (+ (js2-node-pos node) (js2-node-len node)))
4399 ((js2-switch-node-p node)
4400 (js2-switch-node-rp node))
4401 ((js2-catch-node-p node)
4402 (js2-catch-node-rp node))
4403 ((js2-let-node-p node)
4404 (js2-let-node-rp node))
4405 ((js2-array-comp-node-p node)
4406 (js2-array-comp-node-rp node))
4407 ((js2-with-node-p node)
4408 (js2-with-node-rp node))
4409 ((js2-xml-dot-query-node-p node)
4410 (1+ (js2-xml-dot-query-node-rp node)))
4411 (t
4412 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4413
4414 (defsubst js2-node-first-child (node)
4415 "Returns the first element of `js2-node-child-list' for NODE."
4416 (car (js2-node-child-list node)))
4417
4418 (defsubst js2-node-last-child (node)
4419 "Returns the last element of `js2-node-last-child' for NODE."
4420 (car (last (js2-node-child-list node))))
4421
4422 (defun js2-node-prev-sibling (node)
4423 "Return the previous statement in parent.
4424 Works for parents supported by `js2-node-child-list'.
4425 Returns nil if NODE is not in the parent, or PARENT is
4426 not a supported node, or if NODE is the first child."
4427 (let* ((p (js2-node-parent node))
4428 (kids (js2-node-child-list p))
4429 (sib (car kids)))
4430 (while (and kids
4431 (not (eq node (cadr kids))))
4432 (setq kids (cdr kids)
4433 sib (car kids)))
4434 sib))
4435
4436 (defun js2-node-next-sibling (node)
4437 "Return the next statement in parent block.
4438 Returns nil if NODE is not in the block, or PARENT is not
4439 a block node, or if NODE is the last statement."
4440 (let* ((p (js2-node-parent node))
4441 (kids (js2-node-child-list p)))
4442 (while (and kids
4443 (not (eq node (car kids))))
4444 (setq kids (cdr kids)))
4445 (cadr kids)))
4446
4447 (defun js2-node-find-child-before (pos parent &optional after)
4448 "Find the last child that starts before POS in parent.
4449 If AFTER is non-nil, returns first child starting after POS.
4450 POS is an absolute buffer position. PARENT is any node
4451 supported by `js2-node-child-list'.
4452 Returns nil if no applicable child is found."
4453 (let ((kids (if (js2-function-node-p parent)
4454 (js2-block-node-kids (js2-function-node-body parent))
4455 (js2-node-child-list parent)))
4456 (beg (if (js2-function-node-p parent)
4457 (js2-node-abs-pos (js2-function-node-body parent))
4458 (js2-node-abs-pos parent)))
4459 kid
4460 result
4461 fn
4462 (continue t))
4463 (setq fn (if after '> '<))
4464 (while (and kids continue)
4465 (setq kid (car kids))
4466 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4467 (setq result kid
4468 continue (if after nil t))
4469 (setq continue (if after t nil)))
4470 (setq kids (cdr kids)))
4471 result))
4472
4473 (defun js2-node-find-child-after (pos parent)
4474 "Find first child that starts after POS in parent.
4475 POS is an absolute buffer position. PARENT is any node
4476 supported by `js2-node-child-list'.
4477 Returns nil if no applicable child is found."
4478 (js2-node-find-child-before pos parent 'after))
4479
4480 (defun js2-node-replace-child (pos parent new-node)
4481 "Replace node at index POS in PARENT with NEW-NODE.
4482 Only works for parents supported by `js2-node-child-list'."
4483 (let ((kids (js2-node-child-list parent))
4484 (i 0))
4485 (while (< i pos)
4486 (setq kids (cdr kids)
4487 i (1+ i)))
4488 (setcar kids new-node)
4489 (js2-node-add-children parent new-node)))
4490
4491 (defun js2-node-buffer (n)
4492 "Return the buffer associated with AST N.
4493 Returns nil if the buffer is not set as a property on the root
4494 node, or if parent links were not recorded during parsing."
4495 (let ((root (js2-node-root n)))
4496 (and root
4497 (js2-ast-root-p root)
4498 (js2-ast-root-buffer root))))
4499
4500 (defsubst js2-block-node-push (n kid)
4501 "Push js2-node KID onto the end of js2-block-node N's child list.
4502 KID is always added to the -end- of the kids list.
4503 Function also calls `js2-node-add-children' to add the parent link."
4504 (let ((kids (js2-node-child-list n)))
4505 (if kids
4506 (setcdr kids (nconc (cdr kids) (list kid)))
4507 (js2-node-set-child-list n (list kid)))
4508 (js2-node-add-children n kid)))
4509
4510 (defun js2-node-string (node)
4511 (let ((buf (js2-node-buffer node))
4512 pos)
4513 (unless buf
4514 (error "No buffer available for node %s" node))
4515 (save-excursion
4516 (set-buffer buf)
4517 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4518 (+ pos (js2-node-len node))))))
4519
4520 ;; Container for storing the node we're looking for in a traversal.
4521 (js2-deflocal js2-discovered-node nil)
4522
4523 ;; Keep track of absolute node position during traversals.
4524 (js2-deflocal js2-visitor-offset nil)
4525
4526 (js2-deflocal js2-node-search-point nil)
4527
4528 (when js2-mode-dev-mode-p
4529 (defun js2-find-node-at-point ()
4530 (interactive)
4531 (let ((node (js2-node-at-point)))
4532 (message "%s" (or node "No node found at point"))))
4533 (defun js2-node-name-at-point ()
4534 (interactive)
4535 (let ((node (js2-node-at-point)))
4536 (message "%s" (if node
4537 (js2-node-short-name node)
4538 "No node found at point.")))))
4539
4540 (defun js2-node-at-point (&optional pos skip-comments)
4541 "Return AST node at POS, a buffer position, defaulting to current point.
4542 The `js2-mode-ast' variable must be set to the current parse tree.
4543 Signals an error if the AST (`js2-mode-ast') is nil.
4544 Always returns a node - if it can't find one, it returns the root.
4545 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4546 (let ((ast js2-mode-ast)
4547 result)
4548 (unless ast
4549 (error "No JavaScript AST available"))
4550 ;; Look through comments first, since they may be inside nodes that
4551 ;; would otherwise report a match.
4552 (setq pos (or pos (point))
4553 result (if (> pos (js2-node-abs-end ast))
4554 ast
4555 (if (not skip-comments)
4556 (js2-comment-at-point pos))))
4557 (unless result
4558 (setq js2-discovered-node nil
4559 js2-visitor-offset 0
4560 js2-node-search-point pos)
4561 (unwind-protect
4562 (catch 'js2-visit-done
4563 (js2-visit-ast ast #'js2-node-at-point-visitor))
4564 (setq js2-visitor-offset nil
4565 js2-node-search-point nil))
4566 (setq result js2-discovered-node))
4567 ;; may have found a comment beyond end of last child node,
4568 ;; since visiting the ast-root looks at the comment-list last.
4569 (if (and skip-comments
4570 (js2-comment-node-p result))
4571 (setq result nil))
4572 (or result js2-mode-ast)))
4573
4574 (defun js2-node-at-point-visitor (node end-p)
4575 (let ((rel-pos (js2-node-pos node))
4576 abs-pos
4577 abs-end
4578 (point js2-node-search-point))
4579 (cond
4580 (end-p
4581 ;; this evaluates to a non-nil return value, even if it's zero
4582 (decf js2-visitor-offset rel-pos))
4583 ;; we already looked for comments before visiting, and don't want them now
4584 ((js2-comment-node-p node)
4585 nil)
4586 (t
4587 (setq abs-pos (incf js2-visitor-offset rel-pos)
4588 ;; we only want to use the node if the point is before
4589 ;; the last character position in the node, so we decrement
4590 ;; the absolute end by 1.
4591 abs-end (+ abs-pos (js2-node-len node) -1))
4592 (cond
4593 ;; If this node starts after search-point, stop the search.
4594 ((> abs-pos point)
4595 (throw 'js2-visit-done nil))
4596 ;; If this node ends before the search-point, don't check kids.
4597 ((> point abs-end)
4598 nil)
4599 (t
4600 ;; Otherwise point is within this node, possibly in a child.
4601 (setq js2-discovered-node node)
4602 t)))))) ; keep processing kids to look for more specific match
4603
4604 (defsubst js2-block-comment-p (node)
4605 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4606 (and (js2-comment-node-p node)
4607 (memq (js2-comment-node-format node) '(jsdoc block))))
4608
4609 ;; TODO: put the comments in a vector and binary-search them instead
4610 (defun js2-comment-at-point (&optional pos)
4611 "Look through scanned comment nodes for one containing POS.
4612 POS is a buffer position that defaults to current point.
4613 Function returns nil if POS was not in any comment node."
4614 (let ((ast js2-mode-ast)
4615 (x (or pos (point)))
4616 beg
4617 end)
4618 (unless ast
4619 (error "No JavaScript AST available"))
4620 (catch 'done
4621 ;; Comments are stored in lexical order.
4622 (dolist (comment (js2-ast-root-comments ast) nil)
4623 (setq beg (js2-node-abs-pos comment)
4624 end (+ beg (js2-node-len comment)))
4625 (if (and (>= x beg)
4626 (<= x end))
4627 (throw 'done comment))))))
4628
4629 (defun js2-mode-find-parent-fn (node)
4630 "Find function enclosing NODE.
4631 Returns nil if NODE is not inside a function."
4632 (setq node (js2-node-parent node))
4633 (while (and node (not (js2-function-node-p node)))
4634 (setq node (js2-node-parent node)))
4635 (and (js2-function-node-p node) node))
4636
4637 (defun js2-mode-find-enclosing-fn (node)
4638 "Find function or root enclosing NODE."
4639 (if (js2-ast-root-p node)
4640 node
4641 (setq node (js2-node-parent node))
4642 (while (not (or (js2-ast-root-p node)
4643 (js2-function-node-p node)))
4644 (setq node (js2-node-parent node)))
4645 node))
4646
4647 (defun js2-mode-find-enclosing-node (beg end)
4648 "Find script or function fully enclosing BEG and END."
4649 (let ((node (js2-node-at-point beg))
4650 pos
4651 (continue t))
4652 (while continue
4653 (if (or (js2-ast-root-p node)
4654 (and (js2-function-node-p node)
4655 (<= (setq pos (js2-node-abs-pos node)) beg)
4656 (>= (+ pos (js2-node-len node)) end)))
4657 (setq continue nil)
4658 (setq node (js2-node-parent node))))
4659 node))
4660
4661 (defun js2-node-parent-script-or-fn (node)
4662 "Find script or function immediately enclosing NODE.
4663 If NODE is the ast-root, returns nil."
4664 (if (js2-ast-root-p node)
4665 nil
4666 (setq node (js2-node-parent node))
4667 (while (and node (not (or (js2-function-node-p node)
4668 (js2-script-node-p node))))
4669 (setq node (js2-node-parent node)))
4670 node))
4671
4672 (defsubst js2-nested-function-p (node)
4673 "Return t if NODE is a nested function, or is inside a nested function."
4674 (unless (js2-ast-root-p node)
4675 (js2-function-node-p (if (js2-function-node-p node)
4676 (js2-node-parent-script-or-fn node)
4677 (js2-node-parent-script-or-fn
4678 (js2-node-parent-script-or-fn node))))))
4679
4680 (defsubst js2-function-param-node-p (node)
4681 "Return non-nil if NODE is a param node of a `js2-function-node'."
4682 (let ((parent (js2-node-parent node)))
4683 (and parent
4684 (js2-function-node-p parent)
4685 (memq node (js2-function-node-params parent)))))
4686
4687 (defsubst js2-mode-shift-kids (kids start offset)
4688 (dolist (kid kids)
4689 (if (> (js2-node-pos kid) start)
4690 (incf (js2-node-pos kid) offset))))
4691
4692 (defsubst js2-mode-shift-children (parent start offset)
4693 "Update start-positions of all children of PARENT beyond START."
4694 (let ((root (js2-node-root parent)))
4695 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4696 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4697
4698 (defsubst js2-node-is-descendant (node ancestor)
4699 "Return t if NODE is a descendant of ANCESTOR."
4700 (while (and node
4701 (not (eq node ancestor)))
4702 (setq node (js2-node-parent node)))
4703 node)
4704
4705 ;;; visitor infrastructure
4706
4707 (defun js2-visit-none (node callback)
4708 "Visitor for AST node that have no node children."
4709 nil)
4710
4711 (defun js2-print-none (node indent)
4712 "Visitor for AST node with no printed representation.")
4713
4714 (defun js2-print-body (node indent)
4715 "Print a statement, or a block without braces."
4716 (if (js2-block-node-p node)
4717 (dolist (kid (js2-block-node-kids node))
4718 (js2-print-ast kid indent))
4719 (js2-print-ast node indent)))
4720
4721 (defun js2-print-list (args &optional delimiter)
4722 (loop with len = (length args)
4723 for arg in args
4724 for count from 1
4725 do
4726 (js2-print-ast arg 0)
4727 (if (< count len)
4728 (insert (or delimiter ", ")))))
4729
4730 (defun js2-print-tree (ast)
4731 "Prints an AST to the current buffer.
4732 Makes `js2-ast-parent-nodes' available to the printer functions."
4733 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4734 (js2-print-ast ast)))
4735
4736 (defun js2-print-ast (node &optional indent)
4737 "Helper function for printing AST nodes.
4738 Requires `js2-ast-parent-nodes' to be non-nil.
4739 You should use `js2-print-tree' instead of this function."
4740 (let ((printer (get (aref node 0) 'js2-printer))
4741 (i (or indent 0))
4742 (pos (js2-node-abs-pos node)))
4743 ;; TODO: wedge comments in here somewhere
4744 (if printer
4745 (funcall printer node i))))
4746
4747 (defconst js2-side-effecting-tokens
4748 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4749 (dolist (tt (list js2-ASSIGN
4750 js2-ASSIGN_ADD
4751 js2-ASSIGN_BITAND
4752 js2-ASSIGN_BITOR
4753 js2-ASSIGN_BITXOR
4754 js2-ASSIGN_DIV
4755 js2-ASSIGN_LSH
4756 js2-ASSIGN_MOD
4757 js2-ASSIGN_MUL
4758 js2-ASSIGN_RSH
4759 js2-ASSIGN_SUB
4760 js2-ASSIGN_URSH
4761 js2-BLOCK
4762 js2-BREAK
4763 js2-CALL
4764 js2-CATCH
4765 js2-CATCH_SCOPE
4766 js2-CONST
4767 js2-CONTINUE
4768 js2-DEBUGGER
4769 js2-DEC
4770 js2-DELPROP
4771 js2-DEL_REF
4772 js2-DO
4773 js2-ELSE
4774 js2-EMPTY
4775 js2-ENTERWITH
4776 js2-EXPORT
4777 js2-EXPR_RESULT
4778 js2-FINALLY
4779 js2-FOR
4780 js2-FUNCTION
4781 js2-GOTO
4782 js2-IF
4783 js2-IFEQ
4784 js2-IFNE
4785 js2-IMPORT
4786 js2-INC
4787 js2-JSR
4788 js2-LABEL
4789 js2-LEAVEWITH
4790 js2-LET
4791 js2-LETEXPR
4792 js2-LOCAL_BLOCK
4793 js2-LOOP
4794 js2-NEW
4795 js2-REF_CALL
4796 js2-RETHROW
4797 js2-RETURN
4798 js2-RETURN_RESULT
4799 js2-SEMI
4800 js2-SETELEM
4801 js2-SETELEM_OP
4802 js2-SETNAME
4803 js2-SETPROP
4804 js2-SETPROP_OP
4805 js2-SETVAR
4806 js2-SET_REF
4807 js2-SET_REF_OP
4808 js2-SWITCH
4809 js2-TARGET
4810 js2-THROW
4811 js2-TRY
4812 js2-VAR
4813 js2-WHILE
4814 js2-WITH
4815 js2-WITHEXPR
4816 js2-YIELD))
4817 (aset tokens tt t))
4818 (if js2-instanceof-has-side-effects
4819 (aset tokens js2-INSTANCEOF t))
4820 tokens))
4821
4822 (defun js2-node-has-side-effects (node)
4823 "Return t if NODE has side effects."
4824 (when node ; makes it easier to handle malformed expressions
4825 (let ((tt (js2-node-type node)))
4826 (cond
4827 ;; This doubtless needs some work, since EXPR_VOID is used
4828 ;; in several ways in Rhino, and I may not have caught them all.
4829 ;; I'll wait for people to notice incorrect warnings.
4830 ((and (= tt js2-EXPR_VOID)
4831 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4832 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4833 ((= tt js2-COMMA)
4834 (js2-node-has-side-effects (js2-infix-node-right node)))
4835 ((or (= tt js2-AND)
4836 (= tt js2-OR))
4837 (or (js2-node-has-side-effects (js2-infix-node-right node))
4838 (js2-node-has-side-effects (js2-infix-node-left node))))
4839 ((= tt js2-HOOK)
4840 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4841 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4842 ((js2-paren-node-p node)
4843 (js2-node-has-side-effects (js2-paren-node-expr node)))
4844 ((= tt js2-ERROR) ; avoid cascaded error messages
4845 nil)
4846 (t
4847 (aref js2-side-effecting-tokens tt))))))
4848
4849 (defun js2-member-expr-leftmost-name (node)
4850 "For an expr such as foo.bar.baz, return leftmost node foo.
4851 NODE is any `js2-node' object. If it represents a member expression,
4852 which is any sequence of property gets, element-gets, function calls,
4853 or xml descendants/filter operators, then we look at the lexically
4854 leftmost (first) node in the chain. If it is a name-node we return it.
4855 Note that NODE can be a raw name-node and it will be returned as well.
4856 If NODE is not a name-node or member expression, or if it is a member
4857 expression whose leftmost target is not a name node, returns nil."
4858 (let ((continue t)
4859 result)
4860 (while (and continue (not result))
4861 (cond
4862 ((js2-name-node-p node)
4863 (setq result node))
4864 ((js2-prop-get-node-p node)
4865 (setq node (js2-prop-get-node-left node)))
4866 ;; TODO: handle call-nodes, xml-nodes, others?
4867 (t
4868 (setq continue nil))))
4869 result))
4870
4871 (defconst js2-stmt-node-types
4872 (list js2-BLOCK
4873 js2-BREAK
4874 js2-CONTINUE
4875 js2-DEFAULT ; e4x "default xml namespace" statement
4876 js2-DO
4877 js2-EXPR_RESULT
4878 js2-EXPR_VOID
4879 js2-FOR
4880 js2-IF
4881 js2-RETURN
4882 js2-SWITCH
4883 js2-THROW
4884 js2-TRY
4885 js2-WHILE
4886 js2-WITH)
4887 "Node types that only appear in statement contexts.
4888 The list does not include nodes that always appear as the child
4889 of another specific statement type, such as switch-cases,
4890 catch and finally blocks, and else-clauses. The list also excludes
4891 nodes like yield, let and var, which may appear in either expression
4892 or statement context, and in the latter context always have a
4893 `js2-expr-stmt-node' parent. Finally, the list does not include
4894 functions or scripts, which are treated separately from statements
4895 by the JavaScript parser and runtime.")
4896
4897 (defun js2-stmt-node-p (node)
4898 "Heuristic for figuring out if NODE is a statement.
4899 Some node types can appear in either an expression context or a
4900 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4901 For these node types in a statement context, the parent will be a
4902 `js2-expr-stmt-node'.
4903 Functions aren't included in the check."
4904 (memq (js2-node-type node) js2-stmt-node-types))
4905
4906 (defsubst js2-mode-find-first-stmt (node)
4907 "Search upward starting from NODE looking for a statement.
4908 For purposes of this function, a `js2-function-node' counts."
4909 (while (not (or (js2-stmt-node-p node)
4910 (js2-function-node-p node)))
4911 (setq node (js2-node-parent node)))
4912 node)
4913
4914 (defun js2-node-parent-stmt (node)
4915 "Return the node's first ancestor that is a statement.
4916 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4917 appearing in a statement context will have a parent that is a
4918 `js2-expr-stmt-node' that will be returned by this function."
4919 (let ((parent (js2-node-parent node)))
4920 (if (or (null parent)
4921 (js2-stmt-node-p parent)
4922 (and (js2-function-node-p parent)
4923 (not (eq (js2-function-node-form parent)
4924 'FUNCTION_EXPRESSION))))
4925 parent
4926 (js2-node-parent-stmt parent))))
4927
4928 ;; In the Mozilla Rhino sources, Roshan James writes:
4929 ;; Does consistent-return analysis on the function body when strict mode is
4930 ;; enabled.
4931 ;;
4932 ;; function (x) { return (x+1) }
4933 ;;
4934 ;; is ok, but
4935 ;;
4936 ;; function (x) { if (x < 0) return (x+1); }
4937 ;;
4938 ;; is not because the function can potentially return a value when the
4939 ;; condition is satisfied and if not, the function does not explicitly
4940 ;; return a value.
4941 ;;
4942 ;; This extends to checking mismatches such as "return" and "return <value>"
4943 ;; used in the same function. Warnings are not emitted if inconsistent
4944 ;; returns exist in code that can be statically shown to be unreachable.
4945 ;; Ex.
4946 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4947 ;;
4948 ;; emits no warning. However if the loop had a break statement, then a
4949 ;; warning would be emitted.
4950 ;;
4951 ;; The consistency analysis looks at control structures such as loops, ifs,
4952 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4953 ;; warns the user about an inconsistent set of termination possibilities.
4954 ;;
4955 ;; These flags enumerate the possible ways a statement/function can
4956 ;; terminate. These flags are used by endCheck() and by the Parser to
4957 ;; detect inconsistent return usage.
4958 ;;
4959 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4960 ;; able to execute (example: throw, continue)
4961 ;;
4962 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4963 ;; next one. Statement such as return dont. A compound statement may have
4964 ;; some branch that drops off control to the next statement.
4965 ;;
4966 ;; END_RETURNS indicates that the statement can return with no value.
4967 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4968 ;;
4969 ;; A compound statement such as
4970 ;; if (condition) {
4971 ;; return value;
4972 ;; }
4973 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4974
4975 (defconst js2-END_UNREACHED 0)
4976 (defconst js2-END_DROPS_OFF 1)
4977 (defconst js2-END_RETURNS 2)
4978 (defconst js2-END_RETURNS_VALUE 4)
4979 (defconst js2-END_YIELDS 8)
4980
4981 (defun js2-has-consistent-return-usage (node)
4982 "Check that every return usage in a function body is consistent.
4983 Returns t if the function satisfies strict mode requirement."
4984 (let ((n (js2-end-check node)))
4985 ;; either it doesn't return a value in any branch...
4986 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4987 ;; or it returns a value (or is unreached) at every branch
4988 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4989 js2-END_RETURNS
4990 js2-END_YIELDS)))))
4991
4992 (defun js2-end-check-if (node)
4993 "Returns in the then and else blocks must be consistent with each other.
4994 If there is no else block, then the return statement can fall through.
4995 Returns logical OR of END_* flags"
4996 (let ((th (js2-if-node-then-part node))
4997 (el (js2-if-node-else-part node)))
4998 (if (null th)
4999 js2-END_UNREACHED
5000 (logior (js2-end-check th) (if el
5001 (js2-end-check el)
5002 js2-END_DROPS_OFF)))))
5003
5004 (defun js2-end-check-switch (node)
5005 "Consistency of return statements is checked between the case statements.
5006 If there is no default, then the switch can fall through. If there is a
5007 default, we check to see if all code paths in the default return or if
5008 there is a code path that can fall through.
5009 Returns logical OR of END_* flags."
5010 (let ((rv js2-END_UNREACHED)
5011 default-case)
5012 ;; examine the cases
5013 (catch 'break
5014 (dolist (c (js2-switch-node-cases node))
5015 (if (js2-case-node-expr c)
5016 (js2-set-flag rv (js2-end-check-block c))
5017 (setq default-case c)
5018 (throw 'break nil))))
5019 ;; we don't care how the cases drop into each other
5020 (js2-clear-flag rv js2-END_DROPS_OFF)
5021 ;; examine the default
5022 (js2-set-flag rv (if default-case
5023 (js2-end-check default-case)
5024 js2-END_DROPS_OFF))
5025 rv))
5026
5027 (defun js2-end-check-try (node)
5028 "If the block has a finally, return consistency is checked in the
5029 finally block. If all code paths in the finally return, then the
5030 returns in the try-catch blocks don't matter. If there is a code path
5031 that does not return or if there is no finally block, the returns
5032 of the try and catch blocks are checked for mismatch.
5033 Returns logical OR of END_* flags."
5034 (let ((finally (js2-try-node-finally-block node))
5035 rv)
5036 ;; check the finally if it exists
5037 (setq rv (if finally
5038 (js2-end-check (js2-finally-node-body finally))
5039 js2-END_DROPS_OFF))
5040 ;; If the finally block always returns, then none of the returns
5041 ;; in the try or catch blocks matter.
5042 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5043 (js2-clear-flag rv js2-END_DROPS_OFF)
5044 ;; examine the try block
5045 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5046 ;; check each catch block
5047 (dolist (cb (js2-try-node-catch-clauses node))
5048 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5049 rv))
5050
5051 (defun js2-end-check-loop (node)
5052 "Return statement in the loop body must be consistent. The default
5053 assumption for any kind of a loop is that it will eventually terminate.
5054 The only exception is a loop with a constant true condition. Code that
5055 follows such a loop is examined only if one can statically determine
5056 that there is a break out of the loop.
5057
5058 for(... ; ... ; ...) {}
5059 for(... in ... ) {}
5060 while(...) { }
5061 do { } while(...)
5062
5063 Returns logical OR of END_* flags."
5064 (let ((rv (js2-end-check (js2-loop-node-body node)))
5065 (condition (cond
5066 ((js2-while-node-p node)
5067 (js2-while-node-condition node))
5068 ((js2-do-node-p node)
5069 (js2-do-node-condition node))
5070 ((js2-for-node-p node)
5071 (js2-for-node-condition node)))))
5072
5073 ;; check to see if the loop condition is always true
5074 (if (and condition
5075 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5076 (js2-clear-flag rv js2-END_DROPS_OFF))
5077
5078 ;; look for effect of breaks
5079 (js2-set-flag rv (js2-node-get-prop node
5080 'CONTROL_BLOCK_PROP
5081 js2-END_UNREACHED))
5082 rv))
5083
5084 (defun js2-end-check-block (node)
5085 "A general block of code is examined statement by statement.
5086 If any statement (even a compound one) returns in all branches, then
5087 subsequent statements are not examined.
5088 Returns logical OR of END_* flags."
5089 (let* ((rv js2-END_DROPS_OFF)
5090 (kids (js2-block-node-kids node))
5091 (n (car kids)))
5092 ;; Check each statment. If the statement can continue onto the next
5093 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5094 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5095 (js2-clear-flag rv js2-END_DROPS_OFF)
5096 (js2-set-flag rv (js2-end-check n))
5097 (setq kids (cdr kids)
5098 n (car kids)))
5099 rv))
5100
5101 (defun js2-end-check-label (node)
5102 "A labeled statement implies that there may be a break to the label.
5103 The function processes the labeled statement and then checks the
5104 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5105 particular label.
5106 Returns logical OR of END_* flags."
5107 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5108 (logior rv (js2-node-get-prop node
5109 'CONTROL_BLOCK_PROP
5110 js2-END_UNREACHED))))
5111
5112 (defun js2-end-check-break (node)
5113 "When a break is encountered annotate the statement being broken
5114 out of by setting its CONTROL_BLOCK_PROP property.
5115 Returns logical OR of END_* flags."
5116 (and (js2-break-node-target node)
5117 (js2-node-set-prop (js2-break-node-target node)
5118 'CONTROL_BLOCK_PROP
5119 js2-END_DROPS_OFF))
5120 js2-END_UNREACHED)
5121
5122 (defun js2-end-check (node)
5123 "Examine the body of a function, doing a basic reachability analysis.
5124 Returns a combination of flags END_* flags that indicate
5125 how the function execution can terminate. These constitute only the
5126 pessimistic set of termination conditions. It is possible that at
5127 runtime certain code paths will never be actually taken. Hence this
5128 analysis will flag errors in cases where there may not be errors.
5129 Returns logical OR of END_* flags"
5130 (let (kid)
5131 (cond
5132 ((js2-break-node-p node)
5133 (js2-end-check-break node))
5134 ((js2-expr-stmt-node-p node)
5135 (if (setq kid (js2-expr-stmt-node-expr node))
5136 (js2-end-check kid)
5137 js2-END_DROPS_OFF))
5138 ((or (js2-continue-node-p node)
5139 (js2-throw-node-p node))
5140 js2-END_UNREACHED)
5141 ((js2-return-node-p node)
5142 (if (setq kid (js2-return-node-retval node))
5143 js2-END_RETURNS_VALUE
5144 js2-END_RETURNS))
5145 ((js2-loop-node-p node)
5146 (js2-end-check-loop node))
5147 ((js2-switch-node-p node)
5148 (js2-end-check-switch node))
5149 ((js2-labeled-stmt-node-p node)
5150 (js2-end-check-label node))
5151 ((js2-if-node-p node)
5152 (js2-end-check-if node))
5153 ((js2-try-node-p node)
5154 (js2-end-check-try node))
5155 ((js2-block-node-p node)
5156 (if (null (js2-block-node-kids node))
5157 js2-END_DROPS_OFF
5158 (js2-end-check-block node)))
5159 ((js2-yield-node-p node)
5160 js2-END_YIELDS)
5161 (t
5162 js2-END_DROPS_OFF))))
5163
5164 (defun js2-always-defined-boolean-p (node)
5165 "Check if NODE always evaluates to true or false in boolean context.
5166 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5167 nor always false."
5168 (let ((tt (js2-node-type node))
5169 num)
5170 (cond
5171 ((or (= tt js2-FALSE) (= tt js2-NULL))
5172 'ALWAYS_FALSE)
5173 ((= tt js2-TRUE)
5174 'ALWAYS_TRUE)
5175 ((= tt js2-NUMBER)
5176 (setq num (js2-number-node-num-value node))
5177 (if (and (not (eq num 0.0e+NaN))
5178 (not (zerop num)))
5179 'ALWAYS_TRUE
5180 'ALWAYS_FALSE))
5181 (t
5182 nil))))
5183
5184 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5185 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5186
5187 (defvar js2-tokens nil
5188 "List of all defined token names.") ; initialized in `js2-token-names'
5189
5190 (defconst js2-token-names
5191 (let* ((names (make-vector js2-num-tokens -1))
5192 (case-fold-search nil) ; only match js2-UPPER_CASE
5193 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5194 (loop for sym in syms
5195 for i from 0
5196 do
5197 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5198 (not (boundp sym)))
5199 (aset names (symbol-value sym) ; code, e.g. 152
5200 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5201 (push sym js2-tokens)))
5202 names)
5203 "Vector mapping int values to token string names, sans `js2-' prefix.")
5204
5205 (defun js2-token-name (tok)
5206 "Return a string name for TOK, a token symbol or code.
5207 Signals an error if it's not a recognized token."
5208 (let ((code tok))
5209 (if (symbolp tok)
5210 (setq code (symbol-value tok)))
5211 (if (eq code -1)
5212 "ERROR"
5213 (if (and (numberp code)
5214 (not (minusp code))
5215 (< code js2-num-tokens))
5216 (aref js2-token-names code)
5217 (error "Invalid token: %s" code)))))
5218
5219 (defsubst js2-token-sym (tok)
5220 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5221 (intern (js2-token-name tok)))
5222
5223 (defconst js2-token-codes
5224 (let ((table (make-hash-table :test 'eq :size 256)))
5225 (loop for name across js2-token-names
5226 for sym = (intern (concat "js2-" name))
5227 do
5228 (puthash sym (symbol-value sym) table))
5229 ;; clean up a few that are "wrong" in Rhino's token codes
5230 (puthash 'js2-DELETE js2-DELPROP table)
5231 table)
5232 "Hashtable mapping token symbols to their bytecodes.")
5233
5234 (defsubst js2-token-code (sym)
5235 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5236 (or (gethash sym js2-token-codes)
5237 (error "Invalid token symbol: %s " sym))) ; signal code bug
5238
5239 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5240 (setq js2-token-end js2-ts-cursor)
5241 (js2-report-error msg nil
5242 (or beg js2-token-beg)
5243 (or len (- js2-token-end js2-token-beg)))
5244 (unless no-throw
5245 (throw 'return js2-ERROR)))
5246
5247 (defsubst js2-get-string-from-buffer ()
5248 "Reverse the char accumulator and return it as a string."
5249 (setq js2-token-end js2-ts-cursor)
5250 (if js2-ts-string-buffer
5251 (apply #'string (nreverse js2-ts-string-buffer))
5252 ""))
5253
5254 ;; TODO: could potentially avoid a lot of consing by allocating a
5255 ;; char buffer the way Rhino does.
5256 (defsubst js2-add-to-string (c)
5257 (push c js2-ts-string-buffer))
5258
5259 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5260 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5261 ;; any other character: when it's not part of the current token, we
5262 ;; unget it, allowing it to be read again by the following call.
5263 (defsubst js2-unget-char ()
5264 (decf js2-ts-cursor))
5265
5266 ;; Rhino distinguishes \r and \n line endings. We don't need to
5267 ;; because we only scan from Emacs buffers, which always use \n.
5268 (defsubst js2-get-char ()
5269 "Read and return the next character from the input buffer.
5270 Increments `js2-ts-lineno' if the return value is a newline char.
5271 Updates `js2-ts-cursor' to the point after the returned char.
5272 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5273 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5274 (let (c)
5275 ;; check for end of buffer
5276 (if (>= js2-ts-cursor (point-max))
5277 (setq js2-ts-hit-eof t
5278 js2-ts-cursor (1+ js2-ts-cursor)
5279 c js2-EOF_CHAR) ; return value
5280 ;; otherwise read next char
5281 (setq c (char-before (incf js2-ts-cursor)))
5282 ;; if we read a newline, update counters
5283 (if (= c ?\n)
5284 (setq js2-ts-line-start js2-ts-cursor
5285 js2-ts-lineno (1+ js2-ts-lineno)))
5286 ;; TODO: skip over format characters
5287 c)))
5288
5289 (defsubst js2-read-unicode-escape ()
5290 "Read a \\uNNNN sequence from the input.
5291 Assumes the ?\ and ?u have already been read.
5292 Returns the unicode character, or nil if it wasn't a valid character.
5293 Doesn't change the values of any scanner variables."
5294 ;; I really wish I knew a better way to do this, but I can't
5295 ;; find the Emacs function that takes a 16-bit int and converts
5296 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5297 ;; Have to first check that it's 4 hex characters or it may stop
5298 ;; the read early.
5299 (ignore-errors
5300 (let ((s (buffer-substring-no-properties js2-ts-cursor
5301 (+ 4 js2-ts-cursor))))
5302 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5303 (read (concat "?\\u" s))))))
5304
5305 (defsubst js2-match-char (test)
5306 "Consume and return next character if it matches TEST, a character.
5307 Returns nil and consumes nothing if TEST is not the next character."
5308 (let ((c (js2-get-char)))
5309 (if (eq c test)
5310 t
5311 (js2-unget-char)
5312 nil)))
5313
5314 (defsubst js2-peek-char ()
5315 (prog1
5316 (js2-get-char)
5317 (js2-unget-char)))
5318
5319 (defsubst js2-java-identifier-start-p (c)
5320 (or
5321 (memq c '(?$ ?_))
5322 (js2-char-uppercase-p c)
5323 (js2-char-lowercase-p c)))
5324
5325 (defsubst js2-java-identifier-part-p (c)
5326 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5327 ;; TODO: make me Unicode-friendly. See comments above.
5328 (or
5329 (memq c '(?$ ?_))
5330 (js2-char-uppercase-p c)
5331 (js2-char-lowercase-p c)
5332 (and (>= c ?0) (<= c ?9))))
5333
5334 (defsubst js2-alpha-p (c)
5335 (cond ((and (<= ?A c) (<= c ?Z)) t)
5336 ((and (<= ?a c) (<= c ?z)) t)
5337 (t nil)))
5338
5339 (defsubst js2-digit-p (c)
5340 (and (<= ?0 c) (<= c ?9)))
5341
5342 (defsubst js2-js-space-p (c)
5343 (if (<= c 127)
5344 (memq c '(#x20 #x9 #xB #xC #xD))
5345 (or
5346 (eq c #xA0)
5347 ;; TODO: change this nil to check for Unicode space character
5348 nil)))
5349
5350 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5351
5352 (defsubst js2-skip-line ()
5353 "Skip to end of line"
5354 (let (c)
5355 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5356 (js2-unget-char)
5357 (setq js2-token-end js2-ts-cursor)))
5358
5359 (defun js2-init-scanner (&optional buf line)
5360 "Create token stream for BUF starting on LINE.
5361 BUF defaults to current-buffer and line defaults to 1.
5362
5363 A buffer can only have one scanner active at a time, which yields
5364 dramatically simpler code than using a defstruct. If you need to
5365 have simultaneous scanners in a buffer, copy the regions to scan
5366 into temp buffers."
5367 (save-excursion
5368 (when buf
5369 (set-buffer buf))
5370 (setq js2-ts-dirty-line nil
5371 js2-ts-regexp-flags nil
5372 js2-ts-string ""
5373 js2-ts-number nil
5374 js2-ts-hit-eof nil
5375 js2-ts-line-start 0
5376 js2-ts-lineno (or line 1)
5377 js2-ts-line-end-char -1
5378 js2-ts-cursor (point-min)
5379 js2-ts-is-xml-attribute nil
5380 js2-ts-xml-is-tag-content nil
5381 js2-ts-xml-open-tags-count 0
5382 js2-ts-string-buffer nil)))
5383
5384 ;; This function uses the cached op, string and number fields in
5385 ;; TokenStream; if getToken has been called since the passed token
5386 ;; was scanned, the op or string printed may be incorrect.
5387 (defun js2-token-to-string (token)
5388 ;; Not sure where this function is used in Rhino. Not tested.
5389 (if (not js2-debug-print-trees)
5390 ""
5391 (let ((name (js2-token-name token)))
5392 (cond
5393 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5394 (concat name " `" js2-ts-string "'"))
5395 ((eq token js2-NUMBER)
5396 (format "NUMBER %g" js2-ts-number))
5397 (t
5398 name)))))
5399
5400 (defconst js2-keywords
5401 '(break
5402 case catch const continue
5403 debugger default delete do
5404 else enum
5405 false finally for function
5406 if in instanceof import
5407 let
5408 new null
5409 return
5410 switch
5411 this throw true try typeof
5412 var void
5413 while with
5414 yield))
5415
5416 ;; Token names aren't exactly the same as the keywords, unfortunately.
5417 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5418 (defconst js2-kwd-tokens
5419 (let ((table (make-vector js2-num-tokens nil))
5420 (tokens
5421 (list js2-BREAK
5422 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5423 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5424 js2-ELSE
5425 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5426 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5427 js2-LET
5428 js2-NEW js2-NULL
5429 js2-RETURN
5430 js2-SWITCH
5431 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5432 js2-VAR
5433 js2-WHILE js2-WITH
5434 js2-YIELD)))
5435 (dolist (i tokens)
5436 (aset table i 'font-lock-keyword-face))
5437 (aset table js2-STRING 'font-lock-string-face)
5438 (aset table js2-REGEXP 'font-lock-string-face)
5439 (aset table js2-COMMENT 'font-lock-comment-face)
5440 (aset table js2-THIS 'font-lock-builtin-face)
5441 (aset table js2-VOID 'font-lock-constant-face)
5442 (aset table js2-NULL 'font-lock-constant-face)
5443 (aset table js2-TRUE 'font-lock-constant-face)
5444 (aset table js2-FALSE 'font-lock-constant-face)
5445 table)
5446 "Vector whose values are non-nil for tokens that are keywords.
5447 The values are default faces to use for highlighting the keywords.")
5448
5449 (defconst js2-reserved-words
5450 '(abstract
5451 boolean byte
5452 char class
5453 double
5454 enum export extends
5455 final float
5456 goto
5457 implements import int interface
5458 long
5459 native
5460 package private protected public
5461 short static super synchronized
5462 throws transient
5463 volatile))
5464
5465 (defconst js2-keyword-names
5466 (let ((table (make-hash-table :test 'equal)))
5467 (loop for k in js2-keywords
5468 do (puthash
5469 (symbol-name k) ; instanceof
5470 (intern (concat "js2-"
5471 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5472 table))
5473 table)
5474 "JavaScript keywords by name, mapped to their symbols.")
5475
5476 (defconst js2-reserved-word-names
5477 (let ((table (make-hash-table :test 'equal)))
5478 (loop for k in js2-reserved-words
5479 do
5480 (puthash (symbol-name k) 'js2-RESERVED table))
5481 table)
5482 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5483
5484 (defsubst js2-collect-string (buf)
5485 "Convert BUF, a list of chars, to a string.
5486 Reverses BUF before converting."
5487 (cond
5488 ((stringp buf)
5489 buf)
5490 ((null buf) ; for emacs21 compat
5491 "")
5492 (t
5493 (if buf
5494 (apply #'string (nreverse buf))
5495 ""))))
5496
5497 (defun js2-string-to-keyword (s)
5498 "Return token for S, a string, if S is a keyword or reserved word.
5499 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5500 (or (gethash s js2-keyword-names)
5501 (gethash s js2-reserved-word-names)))
5502
5503 (defsubst js2-ts-set-char-token-bounds ()
5504 "Used when next token is one character."
5505 (setq js2-token-beg (1- js2-ts-cursor)
5506 js2-token-end js2-ts-cursor))
5507
5508 (defsubst js2-ts-return (token)
5509 "Return an N-character TOKEN from `js2-get-token'.
5510 Updates `js2-token-end' accordingly."
5511 (setq js2-token-end js2-ts-cursor)
5512 (throw 'return token))
5513
5514 (defsubst js2-x-digit-to-int (c accumulator)
5515 "Build up a hex number.
5516 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5517 corresponding number. Otherwise return -1."
5518 (catch 'return
5519 (catch 'check
5520 ;; Use 0..9 < A..Z < a..z
5521 (cond
5522 ((<= c ?9)
5523 (decf c ?0)
5524 (if (<= 0 c)
5525 (throw 'check nil)))
5526 ((<= c ?F)
5527 (when (<= ?A c)
5528 (decf c (- ?A 10))
5529 (throw 'check nil)))
5530 ((<= c ?f)
5531 (when (<= ?a c)
5532 (decf c (- ?a 10))
5533 (throw 'check nil))))
5534 (throw 'return -1))
5535 (logior c (lsh accumulator 4))))
5536
5537 (defun js2-get-token ()
5538 "Return next JavaScript token, an int such as js2-RETURN."
5539 (let (c
5540 c1
5541 identifier-start
5542 is-unicode-escape-start
5543 contains-escape
5544 escape-val
5545 escape-start
5546 str
5547 result
5548 base
5549 is-integer
5550 quote-char
5551 val
5552 look-for-slash
5553 continue)
5554 (catch 'return
5555 (while t
5556 ;; Eat whitespace, possibly sensitive to newlines.
5557 (setq continue t)
5558 (while continue
5559 (setq c (js2-get-char))
5560 (cond
5561 ((eq c js2-EOF_CHAR)
5562 (js2-ts-set-char-token-bounds)
5563 (throw 'return js2-EOF))
5564 ((eq c ?\n)
5565 (js2-ts-set-char-token-bounds)
5566 (setq js2-ts-dirty-line nil)
5567 (throw 'return js2-EOL))
5568 ((not (js2-js-space-p c))
5569 (if (/= c ?-) ; in case end of HTML comment
5570 (setq js2-ts-dirty-line t))
5571 (setq continue nil))))
5572 ;; Assume the token will be 1 char - fixed up below.
5573 (js2-ts-set-char-token-bounds)
5574 (when (eq c ?@)
5575 (throw 'return js2-XMLATTR))
5576 ;; identifier/keyword/instanceof?
5577 ;; watch out for starting with a <backslash>
5578 (cond
5579 ((eq c ?\\)
5580 (setq c (js2-get-char))
5581 (if (eq c ?u)
5582 (setq identifier-start t
5583 is-unicode-escape-start t
5584 js2-ts-string-buffer nil)
5585 (setq identifier-start nil)
5586 (js2-unget-char)
5587 (setq c ?\\)))
5588 (t
5589 (when (setq identifier-start (js2-java-identifier-start-p c))
5590 (setq js2-ts-string-buffer nil)
5591 (js2-add-to-string c))))
5592 (when identifier-start
5593 (setq contains-escape is-unicode-escape-start)
5594 (catch 'break
5595 (while t
5596 (if is-unicode-escape-start
5597 ;; strictly speaking we should probably push-back
5598 ;; all the bad characters if the <backslash>uXXXX
5599 ;; sequence is malformed. But since there isn't a
5600 ;; correct context(is there?) for a bad Unicode
5601 ;; escape sequence in an identifier, we can report
5602 ;; an error here.
5603 (progn
5604 (setq escape-val 0)
5605 (dotimes (i 4)
5606 (setq c (js2-get-char)
5607 escape-val (js2-x-digit-to-int c escape-val))
5608 ;; Next check takes care of c < 0 and bad escape
5609 (if (minusp escape-val)
5610 (throw 'break nil)))
5611 (if (minusp escape-val)
5612 (js2-report-scan-error "msg.invalid.escape" t))
5613 (js2-add-to-string escape-val)
5614 (setq is-unicode-escape-start nil))
5615 (setq c (js2-get-char))
5616 (cond
5617 ((eq c ?\\)
5618 (setq c (js2-get-char))
5619 (if (eq c ?u)
5620 (setq is-unicode-escape-start t
5621 contains-escape t)
5622 (js2-report-scan-error "msg.illegal.character" t)))
5623 (t
5624 (if (or (eq c js2-EOF_CHAR)
5625 (not (js2-java-identifier-part-p c)))
5626 (throw 'break nil))
5627 (js2-add-to-string c))))))
5628 (js2-unget-char)
5629 (setq str (js2-get-string-from-buffer))
5630 (unless contains-escape
5631 ;; OPT we shouldn't have to make a string (object!) to
5632 ;; check if it's a keyword.
5633 ;; Return the corresponding token if it's a keyword
5634 (when (setq result (js2-string-to-keyword str))
5635 (if (and (< js2-language-version 170)
5636 (memq result '(js2-LET js2-YIELD)))
5637 ;; LET and YIELD are tokens only in 1.7 and later
5638 (setq result 'js2-NAME))
5639 (if (not (eq result 'js2-RESERVED))
5640 (throw 'return (js2-token-code result)))
5641 (js2-report-warning "msg.reserved.keyword" str)))
5642 ;; If we want to intern these as Rhino does, just use (intern str)
5643 (setq js2-ts-string str)
5644 (throw 'return js2-NAME)) ; end identifier/kwd check
5645 ;; is it a number?
5646 (when (or (js2-digit-p c)
5647 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5648 (setq js2-ts-string-buffer nil
5649 base 10)
5650 (when (eq c ?0)
5651 (setq c (js2-get-char))
5652 (cond
5653 ((or (eq c ?x) (eq c ?X))
5654 (setq base 16)
5655 (setq c (js2-get-char)))
5656 ((js2-digit-p c)
5657 (setq base 8))
5658 (t
5659 (js2-add-to-string ?0))))
5660 (if (eq base 16)
5661 (while (<= 0 (js2-x-digit-to-int c 0))
5662 (js2-add-to-string c)
5663 (setq c (js2-get-char)))
5664 (while (and (<= ?0 c) (<= c ?9))
5665 ;; We permit 08 and 09 as decimal numbers, which
5666 ;; makes our behavior a superset of the ECMA
5667 ;; numeric grammar. We might not always be so
5668 ;; permissive, so we warn about it.
5669 (when (and (eq base 8) (>= c ?8))
5670 (js2-report-warning "msg.bad.octal.literal"
5671 (if (eq c ?8) "8" "9"))
5672 (setq base 10))
5673 (js2-add-to-string c)
5674 (setq c (js2-get-char))))
5675 (setq is-integer t)
5676 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5677 (setq is-integer nil)
5678 (when (eq c ?.)
5679 (loop do
5680 (js2-add-to-string c)
5681 (setq c (js2-get-char))
5682 while (js2-digit-p c)))
5683 (when (memq c '(?e ?E))
5684 (js2-add-to-string c)
5685 (setq c (js2-get-char))
5686 (when (memq c '(?+ ?-))
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char)))
5689 (unless (js2-digit-p c)
5690 (js2-report-scan-error "msg.missing.exponent" t))
5691 (loop do
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 while (js2-digit-p c))))
5695 (js2-unget-char)
5696 (setq js2-ts-string (js2-get-string-from-buffer)
5697 js2-ts-number
5698 (if (and (eq base 10) (not is-integer))
5699 (string-to-number js2-ts-string)
5700 ;; TODO: call runtime number-parser. Some of it is in
5701 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5702 (string-to-number js2-ts-string)))
5703 (throw 'return js2-NUMBER))
5704 ;; is it a string?
5705 (when (memq c '(?\" ?\'))
5706 ;; We attempt to accumulate a string the fast way, by
5707 ;; building it directly out of the reader. But if there
5708 ;; are any escaped characters in the string, we revert to
5709 ;; building it out of a string buffer.
5710 (setq quote-char c
5711 js2-ts-string-buffer nil
5712 c (js2-get-char))
5713 (catch 'break
5714 (while (/= c quote-char)
5715 (catch 'continue
5716 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5717 (js2-unget-char)
5718 (setq js2-token-end js2-ts-cursor)
5719 (js2-report-error "msg.unterminated.string.lit")
5720 (throw 'return js2-STRING))
5721 (when (eq c ?\\)
5722 ;; We've hit an escaped character
5723 (setq c (js2-get-char))
5724 (case c
5725 (?b (setq c ?\b))
5726 (?f (setq c ?\f))
5727 (?n (setq c ?\n))
5728 (?r (setq c ?\r))
5729 (?t (setq c ?\t))
5730 (?v (setq c ?\v))
5731 (?u
5732 (setq c1 (js2-read-unicode-escape))
5733 (if js2-parse-ide-mode
5734 (if c1
5735 (progn
5736 ;; just copy the string in IDE-mode
5737 (js2-add-to-string ?\\)
5738 (js2-add-to-string ?u)
5739 (dotimes (i 3)
5740 (js2-add-to-string (js2-get-char)))
5741 (setq c (js2-get-char))) ; added at end of loop
5742 ;; flag it as an invalid escape
5743 (js2-report-warning "msg.invalid.escape"
5744 nil (- js2-ts-cursor 2) 6))
5745 ;; Get 4 hex digits; if the u escape is not
5746 ;; followed by 4 hex digits, use 'u' + the
5747 ;; literal character sequence that follows.
5748 (js2-add-to-string ?u)
5749 (setq escape-val 0)
5750 (dotimes (i 4)
5751 (setq c (js2-get-char)
5752 escape-val (js2-x-digit-to-int c escape-val))
5753 (if (minusp escape-val)
5754 (throw 'continue nil))
5755 (js2-add-to-string c))
5756 ;; prepare for replace of stored 'u' sequence by escape value
5757 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5758 c escape-val)))
5759 (?x
5760 ;; Get 2 hex digits, defaulting to 'x'+literal
5761 ;; sequence, as above.
5762 (setq c (js2-get-char)
5763 escape-val (js2-x-digit-to-int c 0))
5764 (if (minusp escape-val)
5765 (progn
5766 (js2-add-to-string ?x)
5767 (throw 'continue nil))
5768 (setq c1 c
5769 c (js2-get-char)
5770 escape-val (js2-x-digit-to-int c escape-val))
5771 (if (minusp escape-val)
5772 (progn
5773 (js2-add-to-string ?x)
5774 (js2-add-to-string c1)
5775 (throw 'continue nil))
5776 ;; got 2 hex digits
5777 (setq c escape-val))))
5778 (?\n
5779 ;; Remove line terminator after escape to follow
5780 ;; SpiderMonkey and C/C++
5781 (setq c (js2-get-char))
5782 (throw 'continue nil))
5783 (t
5784 (when (and (<= ?0 c) (< c ?8))
5785 (setq val (- c ?0)
5786 c (js2-get-char))
5787 (when (and (<= ?0 c) (< c ?8))
5788 (setq val (- (+ (* 8 val) c) ?0)
5789 c (js2-get-char))
5790 (when (and (<= ?0 c)
5791 (< c ?8)
5792 (< val #o37))
5793 ;; c is 3rd char of octal sequence only
5794 ;; if the resulting val <= 0377
5795 (setq val (- (+ (* 8 val) c) ?0)
5796 c (js2-get-char))))
5797 (js2-unget-char)
5798 (setq c val)))))
5799 (js2-add-to-string c)
5800 (setq c (js2-get-char)))))
5801 (setq js2-ts-string (js2-get-string-from-buffer))
5802 (throw 'return js2-STRING))
5803 (case c
5804 (?\;
5805 (throw 'return js2-SEMI))
5806 (?\[
5807 (throw 'return js2-LB))
5808 (?\]
5809 (throw 'return js2-RB))
5810 (?{
5811 (throw 'return js2-LC))
5812 (?}
5813 (throw 'return js2-RC))
5814 (?\(
5815 (throw 'return js2-LP))
5816 (?\)
5817 (throw 'return js2-RP))
5818 (?,
5819 (throw 'return js2-COMMA))
5820 (??
5821 (throw 'return js2-HOOK))
5822 (?:
5823 (if (js2-match-char ?:)
5824 (js2-ts-return js2-COLONCOLON)
5825 (throw 'return js2-COLON)))
5826 (?.
5827 (if (js2-match-char ?.)
5828 (js2-ts-return js2-DOTDOT)
5829 (if (js2-match-char ?\()
5830 (js2-ts-return js2-DOTQUERY)
5831 (throw 'return js2-DOT))))
5832 (?|
5833 (if (js2-match-char ?|)
5834 (throw 'return js2-OR)
5835 (if (js2-match-char ?=)
5836 (js2-ts-return js2-ASSIGN_BITOR)
5837 (throw 'return js2-BITOR))))
5838 (?^
5839 (if (js2-match-char ?=)
5840 (js2-ts-return js2-ASSIGN_BITOR)
5841 (throw 'return js2-BITXOR)))
5842 (?&
5843 (if (js2-match-char ?&)
5844 (throw 'return js2-AND)
5845 (if (js2-match-char ?=)
5846 (js2-ts-return js2-ASSIGN_BITAND)
5847 (throw 'return js2-BITAND))))
5848 (?=
5849 (if (js2-match-char ?=)
5850 (if (js2-match-char ?=)
5851 (js2-ts-return js2-SHEQ)
5852 (throw 'return js2-EQ))
5853 (throw 'return js2-ASSIGN)))
5854 (?!
5855 (if (js2-match-char ?=)
5856 (if (js2-match-char ?=)
5857 (js2-ts-return js2-SHNE)
5858 (js2-ts-return js2-NE))
5859 (throw 'return js2-NOT)))
5860 (?<
5861 ;; NB:treat HTML begin-comment as comment-till-eol
5862 (when (js2-match-char ?!)
5863 (when (js2-match-char ?-)
5864 (when (js2-match-char ?-)
5865 (js2-skip-line)
5866 (setq js2-ts-comment-type 'html)
5867 (throw 'return js2-COMMENT)))
5868 (js2-unget-char))
5869 (if (js2-match-char ?<)
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-ASSIGN_LSH)
5872 (js2-ts-return js2-LSH))
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-LE)
5875 (throw 'return js2-LT))))
5876 (?>
5877 (if (js2-match-char ?>)
5878 (if (js2-match-char ?>)
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_URSH)
5881 (js2-ts-return js2-URSH))
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-ASSIGN_RSH)
5884 (js2-ts-return js2-RSH)))
5885 (if (js2-match-char ?=)
5886 (js2-ts-return js2-GE)
5887 (throw 'return js2-GT))))
5888 (?*
5889 (if (js2-match-char ?=)
5890 (js2-ts-return js2-ASSIGN_MUL)
5891 (throw 'return js2-MUL)))
5892 (?/
5893 ;; is it a // comment?
5894 (when (js2-match-char ?/)
5895 (setq js2-token-beg (- js2-ts-cursor 2))
5896 (js2-skip-line)
5897 (setq js2-ts-comment-type 'line)
5898 ;; include newline so highlighting goes to end of window
5899 (incf js2-token-end)
5900 (throw 'return js2-COMMENT))
5901 ;; is it a /* comment?
5902 (when (js2-match-char ?*)
5903 (setq look-for-slash nil
5904 js2-token-beg (- js2-ts-cursor 2)
5905 js2-ts-comment-type
5906 (if (js2-match-char ?*)
5907 (progn
5908 (setq look-for-slash t)
5909 'jsdoc)
5910 'block))
5911 (while t
5912 (setq c (js2-get-char))
5913 (cond
5914 ((eq c js2-EOF_CHAR)
5915 (setq js2-token-end (1- js2-ts-cursor))
5916 (js2-report-error "msg.unterminated.comment")
5917 (throw 'return js2-COMMENT))
5918 ((eq c ?*)
5919 (setq look-for-slash t))
5920 ((eq c ?/)
5921 (if look-for-slash
5922 (js2-ts-return js2-COMMENT)))
5923 (t
5924 (setq look-for-slash nil
5925 js2-token-end js2-ts-cursor)))))
5926 (if (js2-match-char ?=)
5927 (js2-ts-return js2-ASSIGN_DIV)
5928 (throw 'return js2-DIV)))
5929 (?#
5930 (when js2-skip-preprocessor-directives
5931 (js2-skip-line)
5932 (setq js2-ts-comment-type 'preprocessor
5933 js2-token-end js2-ts-cursor)
5934 (throw 'return js2-COMMENT))
5935 (throw 'return js2-ERROR))
5936 (?%
5937 (if (js2-match-char ?=)
5938 (js2-ts-return js2-ASSIGN_MOD)
5939 (throw 'return js2-MOD)))
5940 (?~
5941 (throw 'return js2-BITNOT))
5942 (?+
5943 (if (js2-match-char ?=)
5944 (js2-ts-return js2-ASSIGN_ADD)
5945 (if (js2-match-char ?+)
5946 (js2-ts-return js2-INC)
5947 (throw 'return js2-ADD))))
5948 (?-
5949 (cond
5950 ((js2-match-char ?=)
5951 (setq c js2-ASSIGN_SUB))
5952 ((js2-match-char ?-)
5953 (unless js2-ts-dirty-line
5954 ;; treat HTML end-comment after possible whitespace
5955 ;; after line start as comment-until-eol
5956 (when (js2-match-char ?>)
5957 (js2-skip-line)
5958 (setq js2-ts-comment-type 'html)
5959 (throw 'return js2-COMMENT)))
5960 (setq c js2-DEC))
5961 (t
5962 (setq c js2-SUB)))
5963 (setq js2-ts-dirty-line t)
5964 (js2-ts-return c))
5965 (otherwise
5966 (js2-report-scan-error "msg.illegal.character")))))))
5967
5968 (defun js2-read-regexp (start-token)
5969 "Called by parser when it gets / or /= in literal context."
5970 (let (c
5971 err
5972 in-class ; inside a '[' .. ']' character-class
5973 flags
5974 (continue t))
5975 (setq js2-token-beg js2-ts-cursor
5976 js2-ts-string-buffer nil
5977 js2-ts-regexp-flags nil)
5978 (if (eq start-token js2-ASSIGN_DIV)
5979 ;; mis-scanned /=
5980 (js2-add-to-string ?=)
5981 (if (not (eq start-token js2-DIV))
5982 (error "failed assertion")))
5983 (while (and (not err)
5984 (or (/= (setq c (js2-get-char)) ?/)
5985 in-class))
5986 (cond
5987 ((or (= c ?\n)
5988 (= c js2-EOF_CHAR))
5989 (setq js2-token-end (1- js2-ts-cursor)
5990 err t
5991 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5992 (js2-report-error "msg.unterminated.re.lit"))
5993 (t (cond
5994 ((= c ?\\)
5995 (js2-add-to-string c)
5996 (setq c (js2-get-char)))
5997 ((= c ?\[)
5998 (setq in-class t))
5999 ((= c ?\])
6000 (setq in-class nil)))
6001 (js2-add-to-string c))))
6002 (unless err
6003 (while continue
6004 (cond
6005 ((js2-match-char ?g)
6006 (push ?g flags))
6007 ((js2-match-char ?i)
6008 (push ?i flags))
6009 ((js2-match-char ?m)
6010 (push ?m flags))
6011 (t
6012 (setq continue nil))))
6013 (if (js2-alpha-p (js2-peek-char))
6014 (js2-report-scan-error "msg.invalid.re.flag" t
6015 js2-ts-cursor 1))
6016 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6017 js2-ts-regexp-flags (js2-collect-string flags)
6018 js2-token-end js2-ts-cursor)
6019 ;; tell `parse-partial-sexp' to ignore this range of chars
6020 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6021
6022 (defun js2-get-first-xml-token ()
6023 (setq js2-ts-xml-open-tags-count 0
6024 js2-ts-is-xml-attribute nil
6025 js2-ts-xml-is-tag-content nil)
6026 (js2-unget-char)
6027 (js2-get-next-xml-token))
6028
6029 (defsubst js2-xml-discard-string ()
6030 "Throw away the string in progress and flag an XML parse error."
6031 (setq js2-ts-string-buffer nil
6032 js2-ts-string nil)
6033 (js2-report-scan-error "msg.XML.bad.form" t))
6034
6035 (defun js2-get-next-xml-token ()
6036 (setq js2-ts-string-buffer nil ; for recording the XML
6037 js2-token-beg js2-ts-cursor)
6038 (let (c result)
6039 (setq result
6040 (catch 'return
6041 (while t
6042 (setq c (js2-get-char))
6043 (cond
6044 ((= c js2-EOF_CHAR)
6045 (throw 'return js2-ERROR))
6046 (js2-ts-xml-is-tag-content
6047 (case c
6048 (?>
6049 (js2-add-to-string c)
6050 (setq js2-ts-xml-is-tag-content nil
6051 js2-ts-is-xml-attribute nil))
6052 (?/
6053 (js2-add-to-string c)
6054 (when (eq ?> (js2-peek-char))
6055 (setq c (js2-get-char))
6056 (js2-add-to-string c)
6057 (setq js2-ts-xml-is-tag-content nil)
6058 (decf js2-ts-xml-open-tags-count)))
6059 (?{
6060 (js2-unget-char)
6061 (setq js2-ts-string (js2-get-string-from-buffer))
6062 (throw 'return js2-XML))
6063 ((?\' ?\")
6064 (js2-add-to-string c)
6065 (unless (js2-read-quoted-string c)
6066 (throw 'return js2-ERROR)))
6067 (?=
6068 (js2-add-to-string c)
6069 (setq js2-ts-is-xml-attribute t))
6070 ((? ?\t ?\r ?\n)
6071 (js2-add-to-string c))
6072 (t
6073 (js2-add-to-string c)
6074 (setq js2-ts-is-xml-attribute nil)))
6075 (when (and (not js2-ts-xml-is-tag-content)
6076 (zerop js2-ts-xml-open-tags-count))
6077 (setq js2-ts-string (js2-get-string-from-buffer))
6078 (throw 'return js2-XMLEND)))
6079 (t
6080 ;; else not tag content
6081 (case c
6082 (?<
6083 (js2-add-to-string c)
6084 (setq c (js2-peek-char))
6085 (case c
6086 (?!
6087 (setq c (js2-get-char)) ;; skip !
6088 (js2-add-to-string c)
6089 (setq c (js2-peek-char))
6090 (case c
6091 (?-
6092 (setq c (js2-get-char)) ;; skip -
6093 (js2-add-to-string c)
6094 (if (eq c ?-)
6095 (progn
6096 (js2-add-to-string c)
6097 (unless (js2-read-xml-comment)
6098 (throw 'return js2-ERROR)))
6099 (js2-xml-discard-string)
6100 (throw 'return js2-ERROR)))
6101 (?\[
6102 (setq c (js2-get-char)) ;; skip [
6103 (js2-add-to-string c)
6104 (if (and (= (js2-get-char) ?C)
6105 (= (js2-get-char) ?D)
6106 (= (js2-get-char) ?A)
6107 (= (js2-get-char) ?T)
6108 (= (js2-get-char) ?A)
6109 (= (js2-get-char) ?\[))
6110 (progn
6111 (js2-add-to-string ?C)
6112 (js2-add-to-string ?D)
6113 (js2-add-to-string ?A)
6114 (js2-add-to-string ?T)
6115 (js2-add-to-string ?A)
6116 (js2-add-to-string ?\[)
6117 (unless (js2-read-cdata)
6118 (throw 'return js2-ERROR)))
6119 (js2-xml-discard-string)
6120 (throw 'return js2-ERROR)))
6121 (t
6122 (unless (js2-read-entity)
6123 (throw 'return js2-ERROR))))
6124 ;; allow bare CDATA section
6125 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6126 (when (zerop js2-ts-xml-open-tags-count)
6127 (throw 'return js2-XMLEND)))
6128 (??
6129 (setq c (js2-get-char)) ;; skip ?
6130 (js2-add-to-string c)
6131 (unless (js2-read-PI)
6132 (throw 'return js2-ERROR)))
6133 (?/
6134 ;; end tag
6135 (setq c (js2-get-char)) ;; skip /
6136 (js2-add-to-string c)
6137 (when (zerop js2-ts-xml-open-tags-count)
6138 (js2-xml-discard-string)
6139 (throw 'return js2-ERROR))
6140 (setq js2-ts-xml-is-tag-content t)
6141 (decf js2-ts-xml-open-tags-count))
6142 (t
6143 ;; start tag
6144 (setq js2-ts-xml-is-tag-content t)
6145 (incf js2-ts-xml-open-tags-count))))
6146 (?{
6147 (js2-unget-char)
6148 (setq js2-ts-string (js2-get-string-from-buffer))
6149 (throw 'return js2-XML))
6150 (t
6151 (js2-add-to-string c))))))))
6152 (setq js2-token-end js2-ts-cursor)
6153 result))
6154
6155 (defun js2-read-quoted-string (quote)
6156 (let (c)
6157 (catch 'return
6158 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6159 (js2-add-to-string c)
6160 (if (eq c quote)
6161 (throw 'return t)))
6162 (js2-xml-discard-string) ;; throw away string in progress
6163 nil)))
6164
6165 (defun js2-read-xml-comment ()
6166 (let ((c (js2-get-char)))
6167 (catch 'return
6168 (while (/= c js2-EOF_CHAR)
6169 (catch 'continue
6170 (js2-add-to-string c)
6171 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6172 (setq c (js2-get-char))
6173 (js2-add-to-string c)
6174 (if (eq (js2-peek-char) ?>)
6175 (progn
6176 (setq c (js2-get-char)) ;; skip >
6177 (js2-add-to-string c)
6178 (throw 'return t))
6179 (throw 'continue nil)))
6180 (setq c (js2-get-char))))
6181 (js2-xml-discard-string)
6182 nil)))
6183
6184 (defun js2-read-cdata ()
6185 (let ((c (js2-get-char)))
6186 (catch 'return
6187 (while (/= c js2-EOF_CHAR)
6188 (catch 'continue
6189 (js2-add-to-string c)
6190 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6191 (setq c (js2-get-char))
6192 (js2-add-to-string c)
6193 (if (eq (js2-peek-char) ?>)
6194 (progn
6195 (setq c (js2-get-char)) ;; Skip >
6196 (js2-add-to-string c)
6197 (throw 'return t))
6198 (throw 'continue nil)))
6199 (setq c (js2-get-char))))
6200 (js2-xml-discard-string)
6201 nil)))
6202
6203 (defun js2-read-entity ()
6204 (let ((decl-tags 1)
6205 c)
6206 (catch 'return
6207 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6208 (js2-add-to-string c)
6209 (case c
6210 (?<
6211 (incf decl-tags))
6212 (?>
6213 (decf decl-tags)
6214 (if (zerop decl-tags)
6215 (throw 'return t)))))
6216 (js2-xml-discard-string)
6217 nil)))
6218
6219 (defun js2-read-PI ()
6220 "Scan an XML processing instruction."
6221 (let (c)
6222 (catch 'return
6223 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6224 (js2-add-to-string c)
6225 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6226 (setq c (js2-get-char)) ;; Skip >
6227 (js2-add-to-string c)
6228 (throw 'return t)))
6229 (js2-xml-discard-string)
6230 nil)))
6231
6232 (defun js2-scanner-get-line ()
6233 "Return the text of the current scan line."
6234 (buffer-substring (point-at-bol) (point-at-eol)))
6235
6236 ;;; Highlighting
6237
6238 (defsubst js2-set-face (beg end face &optional record)
6239 "Fontify a region. If RECORD is non-nil, record for later."
6240 (when (plusp js2-highlight-level)
6241 (setq beg (min (point-max) beg)
6242 beg (max (point-min) beg)
6243 end (min (point-max) end)
6244 end (max (point-min) end))
6245 (if record
6246 (push (list beg end face) js2-mode-fontifications)
6247 (put-text-property beg end 'face face))))
6248
6249 (defsubst js2-set-kid-face (pos kid len face)
6250 "Set-face on a child node.
6251 POS is absolute buffer position of parent.
6252 KID is the child node.
6253 LEN is the length to fontify.
6254 FACE is the face to fontify with."
6255 (js2-set-face (+ pos (js2-node-pos kid))
6256 (+ pos (js2-node-pos kid) (js2-node-len kid))
6257 face))
6258
6259 (defsubst js2-fontify-kwd (start length)
6260 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6261
6262 (defsubst js2-clear-face (beg end)
6263 (remove-text-properties beg end '(face nil
6264 help-echo nil
6265 point-entered nil
6266 c-in-sws nil)))
6267
6268 (defconst js2-ecma-global-props
6269 (concat "^"
6270 (regexp-opt
6271 '("Infinity" "NaN" "undefined" "arguments") t)
6272 "$")
6273 "Value properties of the Ecma-262 Global Object.
6274 Shown at or above `js2-highlight-level' 2.")
6275
6276 ;; might want to add the name "arguments" to this list?
6277 (defconst js2-ecma-object-props
6278 (concat "^"
6279 (regexp-opt
6280 '("prototype" "__proto__" "__parent__") t)
6281 "$")
6282 "Value properties of the Ecma-262 Object constructor.
6283 Shown at or above `js2-highlight-level' 2.")
6284
6285 (defconst js2-ecma-global-funcs
6286 (concat
6287 "^"
6288 (regexp-opt
6289 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6290 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6291 "$")
6292 "Function properties of the Ecma-262 Global object.
6293 Shown at or above `js2-highlight-level' 2.")
6294
6295 (defconst js2-ecma-number-props
6296 (concat "^"
6297 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6298 "NEGATIVE_INFINITY"
6299 "POSITIVE_INFINITY") t)
6300 "$")
6301 "Properties of the Ecma-262 Number constructor.
6302 Shown at or above `js2-highlight-level' 2.")
6303
6304 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6305 "Properties of the Ecma-262 Date constructor.
6306 Shown at or above `js2-highlight-level' 2.")
6307
6308 (defconst js2-ecma-math-props
6309 (concat "^"
6310 (regexp-opt
6311 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6312 t)
6313 "$")
6314 "Properties of the Ecma-262 Math object.
6315 Shown at or above `js2-highlight-level' 2.")
6316
6317 (defconst js2-ecma-math-funcs
6318 (concat "^"
6319 (regexp-opt
6320 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6321 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6322 "$")
6323 "Function properties of the Ecma-262 Math object.
6324 Shown at or above `js2-highlight-level' 2.")
6325
6326 (defconst js2-ecma-function-props
6327 (concat
6328 "^"
6329 (regexp-opt
6330 '(;; properties of the Object prototype object
6331 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6332 "toLocaleString" "toString" "valueOf"
6333 ;; properties of the Function prototype object
6334 "apply" "call"
6335 ;; properties of the Array prototype object
6336 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6337 "splice" "unshift"
6338 ;; properties of the String prototype object
6339 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6340 "localeCompare" "match" "replace" "search" "split" "substring"
6341 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6342 "toUpperCase"
6343 ;; properties of the Number prototype object
6344 "toExponential" "toFixed" "toPrecision"
6345 ;; properties of the Date prototype object
6346 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6347 "getMinutes" "getMonth" "getSeconds" "getTime"
6348 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6349 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6350 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6351 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6352 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6353 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6354 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6355 "toTimeString" "toUTCString"
6356 ;; properties of the RegExp prototype object
6357 "exec" "test"
6358 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6359 "toSource" "__defineGetter__" "__defineSetter__"
6360 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6361 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6362 t)
6363 "$")
6364 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6365 Shown at or above `js2-highlight-level' 3.")
6366
6367 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6368 (let ((target-name (and target
6369 (js2-name-node-p target)
6370 (js2-name-node-name target)))
6371 (prop-name (if prop (js2-name-node-name prop)))
6372 (level1 (>= js2-highlight-level 1))
6373 (level2 (>= js2-highlight-level 2))
6374 (level3 (>= js2-highlight-level 3))
6375 pos
6376 face)
6377 (when level2
6378 (if call-p
6379 (cond
6380 ((and target prop)
6381 (cond
6382 ((and level3 (string-match js2-ecma-function-props prop-name))
6383 (setq face 'font-lock-builtin-face))
6384 ((and target-name prop)
6385 (cond
6386 ((string= target-name "Date")
6387 (if (string-match js2-ecma-date-props prop-name)
6388 (setq face 'font-lock-builtin-face)))
6389 ((string= target-name "Math")
6390 (if (string-match js2-ecma-math-funcs prop-name)
6391 (setq face 'font-lock-builtin-face)))))))
6392 (prop
6393 (if (string-match js2-ecma-global-funcs prop-name)
6394 (setq face 'font-lock-builtin-face))))
6395 (cond
6396 ((and target prop)
6397 (cond
6398 ((string= target-name "Number")
6399 (if (string-match js2-ecma-number-props prop-name)
6400 (setq face 'font-lock-constant-face)))
6401 ((string= target-name "Math")
6402 (if (string-match js2-ecma-math-props prop-name)
6403 (setq face 'font-lock-constant-face)))))
6404 (prop
6405 (if (string-match js2-ecma-object-props prop-name)
6406 (setq face 'font-lock-constant-face)))))
6407 (when face
6408 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6409 (js2-node-pos prop))) ; relative
6410 (+ pos (js2-node-len prop))
6411 face)))))
6412
6413 (defun js2-parse-highlight-member-expr-node (node)
6414 "Perform syntax highlighting of EcmaScript built-in properties.
6415 The variable `js2-highlight-level' governs this highighting."
6416 (let (face target prop name pos end parent call-p callee)
6417 (cond
6418 ;; case 1: simple name, e.g. foo
6419 ((js2-name-node-p node)
6420 (setq name (js2-name-node-name node))
6421 ;; possible for name to be nil in rare cases - saw it when
6422 ;; running js2-mode on an elisp buffer. Might as well try to
6423 ;; make it so js2-mode never barfs.
6424 (when name
6425 (setq face (if (string-match js2-ecma-global-props name)
6426 'font-lock-constant-face))
6427 (when face
6428 (setq pos (js2-node-pos node)
6429 end (+ pos (js2-node-len node)))
6430 (js2-set-face pos end face))))
6431 ;; case 2: property access or function call
6432 ((or (js2-prop-get-node-p node)
6433 ;; highlight function call if expr is a prop-get node
6434 ;; or a plain name (i.e. unqualified function call)
6435 (and (setq call-p (js2-call-node-p node))
6436 (setq callee (js2-call-node-target node)) ; separate setq!
6437 (or (js2-prop-get-node-p callee)
6438 (js2-name-node-p callee))))
6439 (setq parent node
6440 node (if call-p callee node))
6441 (if (and call-p (js2-name-node-p callee))
6442 (setq prop callee)
6443 (setq target (js2-prop-get-node-left node)
6444 prop (js2-prop-get-node-right node)))
6445 (cond
6446 ((js2-name-node-p target)
6447 (if (js2-name-node-p prop)
6448 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6449 (js2-parse-highlight-prop-get parent target prop call-p)
6450 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6451 (js2-parse-highlight-prop-get parent target nil call-p)))
6452 ((js2-name-node-p prop)
6453 ;; case 2c: complex target, simple name, e.g. x[y].bar
6454 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6455
6456 (defun js2-parse-highlight-member-expr-fn-name (expr)
6457 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6458 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6459 We currently only handle the case where the last component is a prop-get
6460 of a simple name. Called before EXPR has a parent node."
6461 (let (pos
6462 (name (and (js2-prop-get-node-p expr)
6463 (js2-prop-get-node-right expr))))
6464 (when (js2-name-node-p name)
6465 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6466 (js2-node-pos name)))
6467 (+ pos (js2-node-len name))
6468 'font-lock-function-name-face
6469 'record))))
6470
6471 ;; source: http://jsdoc.sourceforge.net/
6472 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6473 ;; allows type specifications, and needs work before entering the wild.
6474
6475 (defconst js2-jsdoc-param-tag-regexp
6476 (concat "^\\s-*\\*+\\s-*\\(@"
6477 "\\(?:param\\|argument\\)"
6478 "\\)"
6479 "\\s-*\\({[^}]+}\\)?" ; optional type
6480 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6481 "\\>")
6482 "Matches jsdoc tags with optional type and optional param name.")
6483
6484 (defconst js2-jsdoc-typed-tag-regexp
6485 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6486 (regexp-opt
6487 '("enum"
6488 "extends"
6489 "field"
6490 "id"
6491 "implements"
6492 "lends"
6493 "mods"
6494 "requires"
6495 "return"
6496 "returns"
6497 "throw"
6498 "throws"))
6499 "\\)\\)\\s-*\\({[^}]+}\\)?")
6500 "Matches jsdoc tags with optional type.")
6501
6502 (defconst js2-jsdoc-arg-tag-regexp
6503 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6504 (regexp-opt
6505 '("alias"
6506 "augments"
6507 "borrows"
6508 "bug"
6509 "base"
6510 "config"
6511 "default"
6512 "define"
6513 "exception"
6514 "function"
6515 "member"
6516 "memberOf"
6517 "name"
6518 "namespace"
6519 "property"
6520 "since"
6521 "suppress"
6522 "this"
6523 "throws"
6524 "type"
6525 "version"))
6526 "\\)\\)\\s-+\\([^ \t]+\\)")
6527 "Matches jsdoc tags with a single argument.")
6528
6529 (defconst js2-jsdoc-empty-tag-regexp
6530 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6531 (regexp-opt
6532 '("addon"
6533 "author"
6534 "class"
6535 "const"
6536 "constant"
6537 "constructor"
6538 "constructs"
6539 "deprecated"
6540 "desc"
6541 "description"
6542 "event"
6543 "example"
6544 "exec"
6545 "export"
6546 "fileoverview"
6547 "final"
6548 "function"
6549 "hidden"
6550 "ignore"
6551 "implicitCast"
6552 "inheritDoc"
6553 "inner"
6554 "interface"
6555 "license"
6556 "noalias"
6557 "noshadow"
6558 "notypecheck"
6559 "override"
6560 "owner"
6561 "preserve"
6562 "preserveTry"
6563 "private"
6564 "protected"
6565 "public"
6566 "static"
6567 "supported"
6568 ))
6569 "\\)\\)\\s-*")
6570 "Matches empty jsdoc tags.")
6571
6572 (defconst js2-jsdoc-link-tag-regexp
6573 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6574 "Matches a jsdoc link or code tag.")
6575
6576 (defconst js2-jsdoc-see-tag-regexp
6577 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6578 "Matches a jsdoc @see tag.")
6579
6580 (defconst js2-jsdoc-html-tag-regexp
6581 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6582 "Matches a simple (no attributes) html start- or end-tag.")
6583
6584 (defsubst js2-jsdoc-highlight-helper ()
6585 (js2-set-face (match-beginning 1)
6586 (match-end 1)
6587 'js2-jsdoc-tag-face)
6588 (if (match-beginning 2)
6589 (if (save-excursion
6590 (goto-char (match-beginning 2))
6591 (= (char-after) ?{))
6592 (js2-set-face (1+ (match-beginning 2))
6593 (1- (match-end 2))
6594 'js2-jsdoc-type-face)
6595 (js2-set-face (match-beginning 2)
6596 (match-end 2)
6597 'js2-jsdoc-value-face)))
6598 (if (match-beginning 3)
6599 (js2-set-face (match-beginning 3)
6600 (match-end 3)
6601 'js2-jsdoc-value-face)))
6602
6603 (defun js2-highlight-jsdoc (ast)
6604 "Highlight doc comment tags."
6605 (let ((comments (js2-ast-root-comments ast))
6606 beg end)
6607 (save-excursion
6608 (dolist (node comments)
6609 (when (eq (js2-comment-node-format node) 'jsdoc)
6610 (setq beg (js2-node-abs-pos node)
6611 end (+ beg (js2-node-len node)))
6612 (save-restriction
6613 (narrow-to-region beg end)
6614 (dolist (re (list js2-jsdoc-param-tag-regexp
6615 js2-jsdoc-typed-tag-regexp
6616 js2-jsdoc-arg-tag-regexp
6617 js2-jsdoc-link-tag-regexp
6618 js2-jsdoc-see-tag-regexp
6619 js2-jsdoc-empty-tag-regexp))
6620 (goto-char beg)
6621 (while (re-search-forward re nil t)
6622 (js2-jsdoc-highlight-helper)))
6623 ;; simple highlighting for html tags
6624 (goto-char beg)
6625 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6626 (js2-set-face (match-beginning 1)
6627 (match-end 1)
6628 'js2-jsdoc-html-tag-delimiter-face)
6629 (js2-set-face (match-beginning 2)
6630 (match-end 2)
6631 'js2-jsdoc-html-tag-name-face)
6632 (js2-set-face (match-beginning 3)
6633 (match-end 3)
6634 'js2-jsdoc-html-tag-delimiter-face))))))))
6635
6636 (defun js2-highlight-assign-targets (node left right)
6637 "Highlight function properties and external variables."
6638 (let (leftpos end name)
6639 ;; highlight vars and props assigned function values
6640 (when (js2-function-node-p right)
6641 (cond
6642 ;; var foo = function() {...}
6643 ((js2-name-node-p left)
6644 (setq name left))
6645 ;; foo.bar.baz = function() {...}
6646 ((and (js2-prop-get-node-p left)
6647 (js2-name-node-p (js2-prop-get-node-right left)))
6648 (setq name (js2-prop-get-node-right left))))
6649 (when name
6650 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6651 (+ leftpos (js2-node-len name))
6652 'font-lock-function-name-face
6653 'record)))))
6654
6655 (defun js2-record-name-node (node)
6656 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6657 later. NODE must be a name node."
6658 (let (leftpos end)
6659 (push (list node js2-current-scope
6660 (setq leftpos (js2-node-abs-pos node))
6661 (setq end (+ leftpos (js2-node-len node))))
6662 js2-recorded-identifiers)))
6663
6664 (defun js2-highlight-undeclared-vars ()
6665 "After entire parse is finished, look for undeclared variable references.
6666 We have to wait until entire buffer is parsed, since JavaScript permits var
6667 decls to occur after they're used.
6668
6669 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6670 it is considered declared."
6671 (let (name)
6672 (dolist (entry js2-recorded-identifiers)
6673 (destructuring-bind (name-node scope pos end) entry
6674 (setq name (js2-name-node-name name-node))
6675 (unless (or (member name js2-global-externs)
6676 (member name js2-default-externs)
6677 (member name js2-additional-externs)
6678 (js2-get-defining-scope scope name))
6679 (js2-set-face pos end 'js2-external-variable-face 'record)
6680 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6681 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6682 (setq js2-recorded-identifiers nil)))
6683
6684 ;;; IMenu support
6685
6686 ;; We currently only support imenu, but eventually should support speedbar and
6687 ;; possibly other browsing mechanisms.
6688
6689 ;; The basic strategy is to identify function assignment targets of the form
6690 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6691 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6692 ;; for imenu after parsing is finished.
6693
6694 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6695 ;; JavaScript, and the general problem is undecidable. However, several forms
6696 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6697 ;; include:
6698
6699 ;; function foo() -- function declaration
6700 ;; foo = function() -- function expression assigned to variable
6701 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6702 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6703 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6704 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6705 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6706 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6707 ;; function foo() {function bar() {...}} -- nested function
6708 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6709
6710 ;; This list boils down to a few forms that can be combined recursively.
6711 ;; Top-level named function declarations include both the left-hand (name)
6712 ;; and the right-hand (function value) expressions needed to produce an imenu
6713 ;; entry. The other "right-hand" forms we need to look for are:
6714 ;; - functions declared as props/getters/setters in object literals
6715 ;; - nested named function declarations
6716 ;; The "left-hand" expressions that functions can be assigned to include:
6717 ;; - local/global variables
6718 ;; - nested property-get expressions like a.b.c.d
6719 ;; - element gets like foo[10] or foo['bar'] where the index
6720 ;; expression can be trivially converted to a property name. They
6721 ;; effectively then become property gets.
6722
6723 ;; All the different definition types are canonicalized into the form
6724 ;; foo.bar.baz = position-of-function-keyword
6725
6726 ;; We need to build a trie-like structure for imenu. As an example,
6727 ;; consider the following JavaScript code:
6728
6729 ;; a = function() {...} // function at position 5
6730 ;; b = function() {...} // function at position 25
6731 ;; foo = function() {...} // function at position 100
6732 ;; foo.bar = function() {...} // function at position 200
6733 ;; foo.bar.baz = function() {...} // function at position 300
6734 ;; foo.bar.zab = function() {...} // function at position 400
6735
6736 ;; During parsing we accumulate an entry for each definition in
6737 ;; the variable `js2-imenu-recorder', like so:
6738
6739 ;; '((a 5)
6740 ;; (b 25)
6741 ;; (foo 100)
6742 ;; (foo bar 200)
6743 ;; (foo bar baz 300)
6744 ;; (foo bar zab 400))
6745
6746 ;; After parsing these entries are merged into this alist-trie:
6747
6748 ;; '((a . 1)
6749 ;; (b . 2)
6750 ;; (foo (<definition> . 3)
6751 ;; (bar (<definition> . 6)
6752 ;; (baz . 100)
6753 ;; (zab . 200))))
6754
6755 ;; Note the wacky need for a <definition> name. The token can be anything
6756 ;; that isn't a valid JavaScript identifier, because you might make foo
6757 ;; a function and then start setting properties on it that are also functions.
6758
6759 (defsubst js2-prop-node-name (node)
6760 "Return the name of a node that may be a property-get/property-name.
6761 If NODE is not a valid name-node, string-node or integral number-node,
6762 returns nil. Otherwise returns the string name/value of the node."
6763 (cond
6764 ((js2-name-node-p node)
6765 (js2-name-node-name node))
6766 ((js2-string-node-p node)
6767 (js2-string-node-value node))
6768 ((and (js2-number-node-p node)
6769 (string-match "^[0-9]+$" (js2-number-node-value node)))
6770 (js2-number-node-value node))
6771 ((js2-this-node-p node)
6772 "this")))
6773
6774 (defsubst js2-node-qname-component (node)
6775 "Test function: return the name of this node, if it contributes to a qname.
6776 Returns nil if the node doesn't contribute."
6777 (copy-sequence
6778 (or (js2-prop-node-name node)
6779 (if (and (js2-function-node-p node)
6780 (js2-function-node-name node))
6781 (js2-name-node-name (js2-function-node-name node))))))
6782
6783 (defsubst js2-record-function-qname (fn-node qname)
6784 "Associate FN-NODE with its QNAME for later lookup.
6785 This is used in postprocessing the chain list. When we find a chain
6786 whose first element is a js2-THIS keyword node, we look up the parent
6787 function and see (using this map) whether it is the tail of a chain.
6788 If so, we replace the this-node with a copy of the parent's qname."
6789 (unless js2-imenu-function-map
6790 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6791 (puthash fn-node qname js2-imenu-function-map))
6792
6793 (defun js2-record-imenu-functions (node &optional var)
6794 "Record function definitions for imenu.
6795 NODE is a function node or an object literal.
6796 VAR, if non-nil, is the expression that NODE is being assigned to."
6797 (when js2-parse-ide-mode
6798 (let ((fun-p (js2-function-node-p node))
6799 qname left fname-node pos)
6800 (cond
6801 ;; non-anonymous function declaration?
6802 ((and fun-p
6803 (not var)
6804 (setq fname-node (js2-function-node-name node)))
6805 (push (setq qname (list fname-node (js2-node-pos node)))
6806 js2-imenu-recorder)
6807 (js2-record-function-qname node qname))
6808 ;; for remaining forms, compute left-side tree branch first
6809 ((and var (setq qname (js2-compute-nested-prop-get var)))
6810 (cond
6811 ;; foo.bar.baz = function
6812 (fun-p
6813 (push (nconc qname (list (js2-node-pos node)))
6814 js2-imenu-recorder)
6815 (js2-record-function-qname node qname))
6816 ;; foo.bar.baz = object-literal
6817 ;; look for nested functions: {a: {b: function() {...} }}
6818 ((js2-object-node-p node)
6819 ;; Node position here is still absolute, since the parser
6820 ;; passes the assignment target and value expressions
6821 ;; to us before they are added as children of the assignment node.
6822 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6823
6824 (defun js2-compute-nested-prop-get (node)
6825 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6826 component nodes as a list. Otherwise return nil. Element-gets are treated
6827 as property-gets if the index expression is a string, or a positive integer."
6828 (let (left right head)
6829 (cond
6830 ((or (js2-name-node-p node)
6831 (js2-this-node-p node))
6832 (list node))
6833 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6834 ((js2-prop-get-node-p node) ; foo.bar
6835 (setq left (js2-prop-get-node-left node)
6836 right (js2-prop-get-node-right node))
6837 (if (setq head (js2-compute-nested-prop-get left))
6838 (nconc head (list right))))
6839 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6840 (setq left (js2-elem-get-node-target node)
6841 right (js2-elem-get-node-element node))
6842 (if (or (js2-string-node-p right) ; ['bar']
6843 (and (js2-number-node-p right) ; [10]
6844 (string-match "^[0-9]+$"
6845 (js2-number-node-value right))))
6846 (if (setq head (js2-compute-nested-prop-get left))
6847 (nconc head (list right))))))))
6848
6849 (defun js2-record-object-literal (node qname pos)
6850 "Recursively process an object literal looking for functions.
6851 NODE is an object literal that is the right-hand child of an assignment
6852 expression. QNAME is a list of nodes representing the assignment target,
6853 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6854 POS is the absolute position of the node.
6855 We do a depth-first traversal of NODE. Any functions we find are prefixed
6856 with QNAME plus the property name of the function and appended to the
6857 variable `js2-imenu-recorder'."
6858 (let (left right prop-qname)
6859 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6860 (let ((left (js2-infix-node-left e))
6861 ;; Element positions are relative to the parent position.
6862 (pos (+ pos (js2-node-pos e))))
6863 (cond
6864 ;; foo: function() {...}
6865 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6866 (when (js2-prop-node-name left)
6867 ;; As a policy decision, we record the position of the property,
6868 ;; not the position of the `function' keyword, since the property
6869 ;; is effectively the name of the function.
6870 (push (setq prop-qname (append qname (list left pos)))
6871 js2-imenu-recorder)
6872 (js2-record-function-qname right prop-qname)))
6873 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6874 ((js2-object-node-p right)
6875 (js2-record-object-literal right
6876 (append qname (list (js2-infix-node-left e)))
6877 (+ pos (js2-node-pos right)))))))))
6878
6879 (defsubst js2-node-top-level-decl-p (node)
6880 "Return t if NODE's name is defined in the top-level scope.
6881 Also returns t if NODE's name is not defined in any scope, since it implies
6882 that it's an external variable, which must also be in the top-level scope."
6883 (let* ((name (js2-prop-node-name node))
6884 (this-scope (js2-node-get-enclosing-scope node))
6885 defining-scope)
6886 (cond
6887 ((js2-this-node-p node)
6888 nil)
6889 ((null this-scope)
6890 t)
6891 ((setq defining-scope (js2-get-defining-scope this-scope name))
6892 (js2-ast-root-p defining-scope))
6893 (t t))))
6894
6895 (defsubst js2-wrapper-function-p (node)
6896 "Returns t if NODE is a function expression that's immediately invoked.
6897 NODE must be `js2-function-node'."
6898 (let ((parent (js2-node-parent node)))
6899 (or
6900 ;; function(){...}();
6901 (js2-call-node-p parent)
6902 (and (js2-paren-node-p parent)
6903 ;; (function(){...})();
6904 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6905 ;; (function(){...}).call(this);
6906 (and (js2-prop-get-node-p parent)
6907 (member (js2-name-node-name (js2-prop-get-node-right parent))
6908 '("call" "apply"))
6909 (js2-call-node-p (js2-node-parent parent))))))))
6910
6911 (defun js2-browse-postprocess-chains (chains)
6912 "Modify function-declaration name chains after parsing finishes.
6913 Some of the information is only available after the parse tree is complete.
6914 For instance, following a 'this' reference requires a parent function node."
6915 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6916 result head fn fn-type parent-chain p elem parent)
6917 (dolist (chain chains)
6918 ;; examine the head of each node to get its defining scope
6919 (setq head (car chain))
6920 ;; if top-level/external, keep as-is
6921 (if (js2-node-top-level-decl-p head)
6922 (push chain result)
6923 (cond
6924 ;; starts with this-reference
6925 ((js2-this-node-p head)
6926 (setq fn (js2-node-parent-script-or-fn head)
6927 chain (cdr chain))) ; discard this-node
6928 ;; nested named function
6929 ((js2-function-node-p (setq parent (js2-node-parent head)))
6930 (setq fn (js2-node-parent-script-or-fn parent)))
6931 ;; variable assigned a function expression
6932 (t (setq fn (js2-node-parent-script-or-fn head))))
6933 (when fn
6934 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6935 (unless fn-type
6936 (setq fn-type
6937 (cond ((js2-nested-function-p fn) 'skip)
6938 ((setq parent-chain
6939 (gethash fn js2-imenu-function-map))
6940 'named)
6941 ((js2-wrapper-function-p fn) 'anon)
6942 (t 'skip)))
6943 (puthash fn fn-type js2-imenu-fn-type-map))
6944 (case fn-type
6945 ('anon (push chain result)) ; anonymous top-level wrapper
6946 ('named ; top-level named function
6947 ;; prefix parent fn qname, which is
6948 ;; parent-chain sans last elem, to this chain.
6949 (push (append (butlast parent-chain) chain) result))))))
6950 ;; finally replace each node in each chain with its name.
6951 (dolist (chain result)
6952 (setq p chain)
6953 (while p
6954 (if (js2-node-p (setq elem (car p)))
6955 (setcar p (js2-node-qname-component elem)))
6956 (setq p (cdr p))))
6957 result))
6958
6959 ;; Merge name chains into a trie-like tree structure of nested lists.
6960 ;; To simplify construction of the trie, we first build it out using the rule
6961 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6962 ;; [key, num-or-list]. The second element can be a number; if so, this key
6963 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6964 ;; associated with the key at this level.) Otherwise the second element is
6965 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6966 ;; a simple recursive formulation.
6967 ;;
6968 ;; js2-mode is building the data structure for imenu. The imenu documentation
6969 ;; claims that it's the structure above, but in practice it wants the children
6970 ;; at the same list level as the key for that level, which is how I've drawn
6971 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6972 ;; list wrapper around the children at each level.
6973 ;;
6974 ;; A completed nested imenu-alist entry looks like this:
6975 ;; '(("foo"
6976 ;; ("<definition>" . 7)
6977 ;; ("bar"
6978 ;; ("a" . 40)
6979 ;; ("b" . 60))))
6980 ;;
6981 ;; In particular, the documentation for `imenu--index-alist' says that
6982 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6983 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6984
6985 (defsubst js2-treeify (lst)
6986 "Convert (a b c d) to (a ((b ((c d)))))"
6987 (if (null (cddr lst)) ; list length <= 2
6988 lst
6989 (list (car lst) (list (js2-treeify (cdr lst))))))
6990
6991 (defun js2-build-alist-trie (chains trie)
6992 "Merge declaration name chains into a trie-like alist structure for imenu.
6993 CHAINS is the qname chain list produced during parsing. TRIE is a
6994 list of elements built up so far."
6995 (let (head tail pos branch kids)
6996 (dolist (chain chains)
6997 (setq head (car chain)
6998 tail (cdr chain)
6999 pos (if (numberp (car tail)) (car tail))
7000 branch (js2-find-if (lambda (n)
7001 (string= (car n) head))
7002 trie)
7003 kids (second branch))
7004 (cond
7005 ;; case 1: this key isn't in the trie yet
7006 ((null branch)
7007 (if trie
7008 (setcdr (last trie) (list (js2-treeify chain)))
7009 (setq trie (list (js2-treeify chain)))))
7010 ;; case 2: key is present with a single number entry: replace w/ list
7011 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7012 ;; ("<definition>" 20)))
7013 ((numberp kids)
7014 (setcar (cdr branch)
7015 (list (list "<definition-1>" kids)
7016 (if pos
7017 (list "<definition-2>" pos)
7018 (js2-treeify tail)))))
7019 ;; case 3: key is there (with kids), and we're a number entry
7020 (pos
7021 (setcdr (last kids)
7022 (list
7023 (list (format "<definition-%d>"
7024 (1+ (loop for kid in kids
7025 count (eq ?< (aref (car kid) 0)))))
7026 pos))))
7027 ;; case 4: key is there with kids, need to merge in our chain
7028 (t
7029 (js2-build-alist-trie (list tail) kids))))
7030 trie))
7031
7032 (defun js2-flatten-trie (trie)
7033 "Convert TRIE to imenu-format.
7034 Recurses through nodes, and for each one whose second element is a list,
7035 appends the list's flattened elements to the current element. Also
7036 changes the tails into conses. For instance, this pre-flattened trie
7037
7038 '(a ((b 20)
7039 (c ((d 30)
7040 (e 40)))))
7041
7042 becomes
7043
7044 '(a (b . 20)
7045 (c (d . 30)
7046 (e . 40)))
7047
7048 Note that the root of the trie has no key, just a list of chains.
7049 This is also true for the value of any key with multiple children,
7050 e.g. key 'c' in the example above."
7051 (cond
7052 ((listp (car trie))
7053 (mapcar #'js2-flatten-trie trie))
7054 (t
7055 (if (numberp (second trie))
7056 (cons (car trie) (second trie))
7057 ;; else pop list and append its kids
7058 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7059
7060 (defun js2-build-imenu-index ()
7061 "Turn `js2-imenu-recorder' into an imenu data structure."
7062 (unless (eq js2-imenu-recorder 'empty)
7063 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7064 (result (js2-build-alist-trie chains nil)))
7065 (js2-flatten-trie result))))
7066
7067 (defun js2-test-print-chains (chains)
7068 "Print a list of qname chains.
7069 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7070 i.e. one or more nodes, and an integer position as the list tail."
7071 (mapconcat (lambda (chain)
7072 (concat "("
7073 (mapconcat (lambda (elem)
7074 (if (js2-node-p elem)
7075 (or (js2-node-qname-component elem)
7076 "nil")
7077 (number-to-string elem)))
7078 chain
7079 " ")
7080 ")"))
7081 chains
7082 "\n"))
7083
7084 ;;; Parser
7085
7086 (defconst js2-version "1.8.0"
7087 "Version of JavaScript supported, plus minor js2 version.")
7088
7089 (defmacro js2-record-face (face)
7090 "Record a style run of FACE for the current token."
7091 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7092
7093 (defsubst js2-node-end (n)
7094 "Computes the absolute end of node N.
7095 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7096 is only true until the node is added to its parent; i.e., while parsing."
7097 (+ (js2-node-pos n)
7098 (js2-node-len n)))
7099
7100 (defsubst js2-record-comment ()
7101 "Record a comment in `js2-scanned-comments'."
7102 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7103 :format js2-ts-comment-type)
7104 js2-scanned-comments)
7105 (when js2-parse-ide-mode
7106 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7107 'font-lock-doc-face
7108 'font-lock-comment-face))
7109 (when (memq js2-ts-comment-type '(html preprocessor))
7110 ;; Tell cc-engine the bounds of the comment.
7111 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7112
7113 ;; This function is called depressingly often, so it should be fast.
7114 ;; Most of the time it's looking at the same token it peeked before.
7115 (defsubst js2-peek-token ()
7116 "Returns the next token without consuming it.
7117 If previous token was consumed, calls scanner to get new token.
7118 If previous token was -not- consumed, returns it (idempotent).
7119
7120 This function will not return a newline (js2-EOL) - instead, it
7121 gobbles newlines until it finds a non-newline token, and flags
7122 that token as appearing just after a newline.
7123
7124 This function will also not return a js2-COMMENT. Instead, it
7125 records comments found in `js2-scanned-comments'. If the token
7126 returned by this function immediately follows a jsdoc comment,
7127 the token is flagged as such.
7128
7129 Note that this function always returned the un-flagged token!
7130 The flags, if any, are saved in `js2-current-flagged-token'."
7131 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7132 js2-current-token ; most common case - return already-peeked token
7133 (let ((tt (js2-get-token)) ; call scanner
7134 saw-eol
7135 face)
7136 ;; process comments and whitespace
7137 (while (or (= tt js2-EOL)
7138 (= tt js2-COMMENT))
7139 (if (= tt js2-EOL)
7140 (setq saw-eol t)
7141 (setq saw-eol nil)
7142 (if js2-record-comments
7143 (js2-record-comment)))
7144 (setq tt (js2-get-token))) ; call scanner
7145 (setq js2-current-token tt
7146 js2-current-flagged-token (if saw-eol
7147 (logior tt js2-ti-after-eol)
7148 tt))
7149 ;; perform lexical fontification as soon as token is scanned
7150 (when js2-parse-ide-mode
7151 (cond
7152 ((minusp tt)
7153 (js2-record-face 'js2-error-face))
7154 ((setq face (aref js2-kwd-tokens tt))
7155 (js2-record-face face))
7156 ((and (= tt js2-NAME)
7157 (equal js2-ts-string "undefined"))
7158 (js2-record-face 'font-lock-constant-face))))
7159 tt))) ; return unflagged token
7160
7161 (defsubst js2-peek-flagged-token ()
7162 "Returns the current token along with any flags set for it."
7163 (js2-peek-token)
7164 js2-current-flagged-token)
7165
7166 (defsubst js2-consume-token ()
7167 (setq js2-current-flagged-token js2-EOF))
7168
7169 (defsubst js2-next-token ()
7170 (prog1
7171 (js2-peek-token)
7172 (js2-consume-token)))
7173
7174 (defsubst js2-next-flagged-token ()
7175 (js2-peek-token)
7176 (prog1 js2-current-flagged-token
7177 (js2-consume-token)))
7178
7179 (defsubst js2-match-token (match)
7180 "Consume and return t if next token matches MATCH, a bytecode.
7181 Returns nil and consumes nothing if MATCH is not the next token."
7182 (if (/= (js2-peek-token) match)
7183 nil
7184 (js2-consume-token)
7185 t))
7186
7187 (defsubst js2-valid-prop-name-token (tt)
7188 (or (= tt js2-NAME)
7189 (and js2-allow-keywords-as-property-names
7190 (plusp tt)
7191 (aref js2-kwd-tokens tt))))
7192
7193 (defsubst js2-match-prop-name ()
7194 "Consume token and return t if next token is a valid property name.
7195 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7196 is non-nil and it's a keyword token."
7197 (if (js2-valid-prop-name-token (js2-peek-token))
7198 (progn
7199 (js2-consume-token)
7200 t)
7201 nil))
7202
7203 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7204 (if (js2-match-prop-name)
7205 t
7206 (js2-report-error msg-id nil pos len)
7207 nil))
7208
7209 (defsubst js2-peek-token-or-eol ()
7210 "Return js2-EOL if the current token immediately follows a newline.
7211 Else returns the current token. Used in situations where we don't
7212 consider certain token types valid if they are preceded by a newline.
7213 One example is the postfix ++ or -- operator, which has to be on the
7214 same line as its operand."
7215 (let ((tt (js2-peek-token)))
7216 ;; Check for last peeked token flags
7217 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7218 js2-EOL
7219 tt)))
7220
7221 (defsubst js2-set-check-for-label ()
7222 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7223 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7224
7225 (defsubst js2-must-match (token msg-id &optional pos len)
7226 "Match next token to token code TOKEN, or record a syntax error.
7227 MSG-ID is the error message to report if the match fails.
7228 Returns t on match, nil if no match."
7229 (if (js2-match-token token)
7230 t
7231 (js2-report-error msg-id nil pos len)
7232 nil))
7233
7234 (defsubst js2-inside-function ()
7235 (plusp js2-nesting-of-function))
7236
7237 (defsubst js2-set-requires-activation ()
7238 (if (js2-function-node-p js2-current-script-or-fn)
7239 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7240
7241 (defsubst js2-check-activation-name (name token)
7242 (when (js2-inside-function)
7243 ;; skip language-version 1.2 check from Rhino
7244 (if (or (string= "arguments" name)
7245 (and js2-compiler-activation-names ; only used in codegen
7246 (gethash name js2-compiler-activation-names)))
7247 (js2-set-requires-activation))))
7248
7249 (defsubst js2-set-is-generator ()
7250 (if (js2-function-node-p js2-current-script-or-fn)
7251 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7252
7253 (defsubst js2-must-have-xml ()
7254 (unless js2-compiler-xml-available
7255 (js2-report-error "msg.XML.not.available")))
7256
7257 (defsubst js2-push-scope (scope)
7258 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7259 (assert (js2-scope-p scope))
7260 (assert (null (js2-scope-parent-scope scope)))
7261 (assert (not (eq js2-current-scope scope)))
7262 (setf (js2-scope-parent-scope scope) js2-current-scope
7263 js2-current-scope scope))
7264
7265 (defsubst js2-pop-scope ()
7266 (setq js2-current-scope
7267 (js2-scope-parent-scope js2-current-scope)))
7268
7269 (defsubst js2-enter-loop (loop-node)
7270 (push loop-node js2-loop-set)
7271 (push loop-node js2-loop-and-switch-set)
7272 (js2-push-scope loop-node)
7273 ;; Tell the current labeled statement (if any) its statement,
7274 ;; and set the jump target of the first label to the loop.
7275 ;; These are used in `js2-parse-continue' to verify that the
7276 ;; continue target is an actual labeled loop. (And for codegen.)
7277 (when js2-labeled-stmt
7278 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7279 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7280 js2-labeled-stmt))) loop-node)))
7281
7282 (defsubst js2-exit-loop ()
7283 (pop js2-loop-set)
7284 (pop js2-loop-and-switch-set)
7285 (js2-pop-scope))
7286
7287 (defsubst js2-enter-switch (switch-node)
7288 (push switch-node js2-loop-and-switch-set))
7289
7290 (defsubst js2-exit-switch ()
7291 (pop js2-loop-and-switch-set))
7292
7293 (defun js2-parse (&optional buf cb)
7294 "Tells the js2 parser to parse a region of JavaScript.
7295
7296 BUF is a buffer or buffer name containing the code to parse.
7297 Call `narrow-to-region' first to parse only part of the buffer.
7298
7299 The returned AST root node is given some additional properties:
7300 `node-count' - total number of nodes in the AST
7301 `buffer' - BUF. The buffer it refers to may change or be killed,
7302 so the value is not necessarily reliable.
7303
7304 An optional callback CB can be specified to report parsing
7305 progress. If `(functionp CB)' returns t, it will be called with
7306 the current line number once before parsing begins, then again
7307 each time the lexer reaches a new line number.
7308
7309 CB can also be a list of the form `(symbol cb ...)' to specify
7310 multiple callbacks with different criteria. Each symbol is a
7311 criterion keyword, and the following element is the callback to
7312 call
7313
7314 :line - called whenever the line number changes
7315 :token - called for each new token consumed
7316
7317 The list of criteria could be extended to include entering or
7318 leaving a statement, an expression, or a function definition."
7319 (if (and cb (not (functionp cb)))
7320 (error "criteria callbacks not yet implemented"))
7321 (let ((inhibit-point-motion-hooks t)
7322 (js2-compiler-xml-available (>= js2-language-version 160))
7323 ;; This is a recursive-descent parser, so give it a big stack.
7324 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7325 (max-specpdl-size (max max-specpdl-size 3000))
7326 (case-fold-search nil)
7327 ast)
7328 (or buf (setq buf (current-buffer)))
7329 (message nil) ; clear any error message from previous parse
7330 (save-excursion
7331 (set-buffer buf)
7332 (setq js2-scanned-comments nil
7333 js2-parsed-errors nil
7334 js2-parsed-warnings nil
7335 js2-imenu-recorder nil
7336 js2-imenu-function-map nil
7337 js2-label-set nil)
7338 (js2-init-scanner)
7339 (setq ast (js2-with-unmodifying-text-property-changes
7340 (js2-do-parse)))
7341 (unless js2-ts-hit-eof
7342 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7343 (setf (js2-ast-root-errors ast) js2-parsed-errors
7344 (js2-ast-root-warnings ast) js2-parsed-warnings)
7345 ;; if we didn't find any declarations, put a dummy in this list so we
7346 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7347 (unless js2-imenu-recorder
7348 (setq js2-imenu-recorder 'empty))
7349 (run-hooks 'js2-parse-finished-hook)
7350 ast)))
7351
7352 ;; Corresponds to Rhino's Parser.parse() method.
7353 (defun js2-do-parse ()
7354 "Parse current buffer starting from current point.
7355 Scanner should be initialized."
7356 (let ((pos js2-ts-cursor)
7357 (end js2-ts-cursor) ; in case file is empty
7358 root n tt)
7359 ;; initialize buffer-local parsing vars
7360 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7361 js2-current-script-or-fn root
7362 js2-current-scope root
7363 js2-current-flagged-token js2-EOF
7364 js2-nesting-of-function 0
7365 js2-labeled-stmt nil
7366 js2-recorded-identifiers nil) ; for js2-highlight
7367 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7368 (if (= tt js2-FUNCTION)
7369 (progn
7370 (js2-consume-token)
7371 (setq n (js2-parse-function (if js2-called-by-compile-function
7372 'FUNCTION_EXPRESSION
7373 'FUNCTION_STATEMENT))))
7374 ;; not a function - parse a statement
7375 (setq n (js2-parse-statement)))
7376 ;; add function or statement to script
7377 (setq end (js2-node-end n))
7378 (js2-block-node-push root n))
7379 ;; add comments to root in lexical order
7380 (when js2-scanned-comments
7381 ;; if we find a comment beyond end of normal kids, use its end
7382 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7383 (dolist (comment js2-scanned-comments)
7384 (push comment (js2-ast-root-comments root))
7385 (js2-node-add-children root comment)))
7386 (setf (js2-node-len root) (- end pos))
7387 ;; Give extensions a chance to muck with things before highlighting starts.
7388 (let ((js2-additional-externs js2-additional-externs))
7389 (dolist (callback js2-post-parse-callbacks)
7390 (funcall callback))
7391 (js2-highlight-undeclared-vars))
7392 root))
7393
7394 (defun js2-function-parser ()
7395 (js2-consume-token)
7396 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7397
7398 (defun js2-parse-function-closure-body (fn-node)
7399 "Parse a JavaScript 1.8 function closure body."
7400 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7401 (if js2-ts-hit-eof
7402 (js2-report-error "msg.no.brace.body" nil
7403 (js2-node-pos fn-node)
7404 (- js2-ts-cursor (js2-node-pos fn-node)))
7405 (js2-node-add-children fn-node
7406 (setf (js2-function-node-body fn-node)
7407 (js2-parse-expr t))))))
7408
7409 (defun js2-parse-function-body (fn-node)
7410 (js2-must-match js2-LC "msg.no.brace.body"
7411 (js2-node-pos fn-node)
7412 (- js2-ts-cursor (js2-node-pos fn-node)))
7413 (let ((pos js2-token-beg) ; LC position
7414 (pn (make-js2-block-node)) ; starts at LC position
7415 tt
7416 end)
7417 (incf js2-nesting-of-function)
7418 (unwind-protect
7419 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7420 (= tt js2-EOF)
7421 (= tt js2-RC)))
7422 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7423 (js2-parse-statement)
7424 (js2-consume-token)
7425 (js2-parse-function 'FUNCTION_STATEMENT))))
7426 (decf js2-nesting-of-function))
7427 (setq end js2-token-end) ; assume no curly and leave at current token
7428 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7429 (setq end js2-token-end))
7430 (setf (js2-node-pos pn) pos
7431 (js2-node-len pn) (- end pos))
7432 (setf (js2-function-node-body fn-node) pn)
7433 (js2-node-add-children fn-node pn)
7434 pn))
7435
7436 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7437 "Declare and fontify destructuring parameters inside NODE.
7438 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7439 (cond
7440 ((js2-name-node-p node)
7441 (let (leftpos)
7442 (js2-define-symbol decl-type (js2-name-node-name node)
7443 node ignore-not-in-block)
7444 (when face
7445 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7446 (+ leftpos (js2-node-len node))
7447 face 'record))))
7448 ((js2-object-node-p node)
7449 (dolist (elem (js2-object-node-elems node))
7450 (js2-define-destruct-symbols
7451 (if (js2-object-prop-node-p elem)
7452 (js2-object-prop-node-right elem)
7453 ;; abbreviated destructuring {a, b}
7454 elem)
7455 decl-type face ignore-not-in-block)))
7456 ((js2-array-node-p node)
7457 (dolist (elem (js2-array-node-elems node))
7458 (when elem
7459 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7460 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7461 (js2-node-len node)))))
7462
7463 (defun js2-parse-function-params (fn-node pos)
7464 (if (js2-match-token js2-RP)
7465 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7466 (let (params len param)
7467 (loop for tt = (js2-peek-token)
7468 do
7469 (cond
7470 ;; destructuring param
7471 ((or (= tt js2-LB) (= tt js2-LC))
7472 (setq param (js2-parse-primary-expr-lhs))
7473 (js2-define-destruct-symbols param
7474 js2-LP
7475 'js2-function-param-face)
7476 (push param params))
7477 ;; simple name
7478 (t
7479 (js2-must-match js2-NAME "msg.no.parm")
7480 (js2-record-face 'js2-function-param-face)
7481 (setq param (js2-create-name-node))
7482 (js2-define-symbol js2-LP js2-ts-string param)
7483 (push param params)))
7484 while
7485 (js2-match-token js2-COMMA))
7486 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7487 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7488 (dolist (p params)
7489 (js2-node-add-children fn-node p)
7490 (push p (js2-function-node-params fn-node))))))
7491
7492 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7493 "Possibly show inconsistent-return warning.
7494 Last token scanned is the close-curly for the function body."
7495 (when (and js2-mode-show-strict-warnings
7496 js2-strict-inconsistent-return-warning
7497 (not (js2-has-consistent-return-usage
7498 (js2-function-node-body fn-node))))
7499 ;; Have it extend from close-curly to bol or beginning of block.
7500 (let ((pos (save-excursion
7501 (goto-char js2-token-end)
7502 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7503 (point-at-bol))))
7504 (end js2-token-end))
7505 (if (plusp (js2-name-node-length name))
7506 (js2-add-strict-warning "msg.no.return.value"
7507 (js2-name-node-name name) pos end)
7508 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7509
7510 (defun js2-parse-function (function-type)
7511 "Function parser. FUNCTION-TYPE is a symbol."
7512 (let ((pos js2-token-beg) ; start of 'function' keyword
7513 name
7514 name-beg
7515 name-end
7516 fn-node
7517 lp
7518 (synthetic-type function-type)
7519 member-expr-node)
7520 ;; parse function name, expression, or non-name (anonymous)
7521 (cond
7522 ;; function foo(...)
7523 ((js2-match-token js2-NAME)
7524 (setq name (js2-create-name-node t)
7525 name-beg js2-token-beg
7526 name-end js2-token-end)
7527 (unless (js2-match-token js2-LP)
7528 (when js2-allow-member-expr-as-function-name
7529 ;; function foo.bar(...)
7530 (setq member-expr-node name
7531 name nil
7532 member-expr-node (js2-parse-member-expr-tail
7533 nil member-expr-node)))
7534 (js2-must-match js2-LP "msg.no.paren.parms")))
7535 ((js2-match-token js2-LP)
7536 nil) ; anonymous function: leave name as null
7537 (t
7538 ;; function random-member-expr(...)
7539 (when js2-allow-member-expr-as-function-name
7540 ;; Note that memberExpr can not start with '(' like
7541 ;; in function (1+2).toString(), because 'function (' already
7542 ;; processed as anonymous function
7543 (setq member-expr-node (js2-parse-member-expr)))
7544 (js2-must-match js2-LP "msg.no.paren.parms")))
7545 (if (= js2-current-token js2-LP) ; eventually matched LP?
7546 (setq lp js2-token-beg))
7547 (if member-expr-node
7548 (progn
7549 (setq synthetic-type 'FUNCTION_EXPRESSION)
7550 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7551 (if name
7552 (js2-set-face name-beg name-end
7553 'font-lock-function-name-face 'record)))
7554 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7555 (plusp (js2-name-node-length name)))
7556 ;; Function statements define a symbol in the enclosing scope
7557 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7558 (setf fn-node (make-js2-function-node :pos pos
7559 :name name
7560 :form function-type
7561 :lp (if lp (- lp pos))))
7562 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7563 ;; 1. Nested functions are not affected by the dynamic scope flag
7564 ;; as dynamic scope is already a parent of their scope.
7565 ;; 2. Functions defined under the with statement also immune to
7566 ;; this setup, in which case dynamic scope is ignored in favor
7567 ;; of the with object.
7568 (setf (js2-function-node-ignore-dynamic fn-node) t))
7569 ;; dynamically bind all the per-function variables
7570 (let ((js2-current-script-or-fn fn-node)
7571 (js2-current-scope fn-node)
7572 (js2-nesting-of-with 0)
7573 (js2-end-flags 0)
7574 js2-label-set
7575 js2-loop-set
7576 js2-loop-and-switch-set)
7577 (js2-parse-function-params fn-node pos)
7578 (if (and (>= js2-language-version 180)
7579 (/= (js2-peek-token) js2-LC))
7580 (js2-parse-function-closure-body fn-node)
7581 (js2-parse-function-body fn-node))
7582 (if name
7583 (js2-node-add-children fn-node name))
7584 (js2-check-inconsistent-return-warning fn-node name)
7585 ;; Function expressions define a name only in the body of the
7586 ;; function, and only if not hidden by a parameter name
7587 (if (and name
7588 (eq synthetic-type 'FUNCTION_EXPRESSION)
7589 (null (js2-scope-get-symbol js2-current-scope
7590 (js2-name-node-name name))))
7591 (js2-define-symbol js2-FUNCTION
7592 (js2-name-node-name name)
7593 fn-node))
7594 (if (and name
7595 (not (eq function-type 'FUNCTION_EXPRESSION)))
7596 (js2-record-imenu-functions fn-node)))
7597 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7598 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7599 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7600 ;; We wait until after parsing the function to set its parent scope,
7601 ;; since `js2-define-symbol' needs the defining-scope check to stop
7602 ;; at the function boundary when checking for redeclarations.
7603 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7604 fn-node))
7605
7606 (defun js2-parse-statements (&optional parent)
7607 "Parse a statement list. Last token consumed must be js2-LC.
7608
7609 PARENT can be a `js2-block-node', in which case the statements are
7610 appended to PARENT. Otherwise a new `js2-block-node' is created
7611 and returned.
7612
7613 This function does not match the closing js2-RC: the caller
7614 matches the RC so it can provide a suitable error message if not
7615 matched. This means it's up to the caller to set the length of
7616 the node to include the closing RC. The node start pos is set to
7617 the absolute buffer start position, and the caller should fix it
7618 up to be relative to the parent node. All children of this block
7619 node are given relative start positions and correct lengths."
7620 (let ((pn (or parent (make-js2-block-node)))
7621 tt)
7622 (setf (js2-node-pos pn) js2-token-beg)
7623 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7624 (/= tt js2-RC))
7625 (js2-block-node-push pn (js2-parse-statement)))
7626 pn))
7627
7628 (defun js2-parse-statement ()
7629 (let (tt pn beg end)
7630 ;; coarse-grained user-interrupt check - needs work
7631 (and js2-parse-interruptable-p
7632 (zerop (% (incf js2-parse-stmt-count)
7633 js2-statements-per-pause))
7634 (input-pending-p)
7635 (throw 'interrupted t))
7636 (setq pn (js2-statement-helper))
7637 ;; no-side-effects warning check
7638 (unless (js2-node-has-side-effects pn)
7639 (setq end (js2-node-end pn))
7640 (save-excursion
7641 (goto-char end)
7642 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7643 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7644 pn))
7645
7646 ;; These correspond to the switch cases in Parser.statementHelper
7647 (defconst js2-parsers
7648 (let ((parsers (make-vector js2-num-tokens
7649 #'js2-parse-expr-stmt)))
7650 (aset parsers js2-BREAK #'js2-parse-break)
7651 (aset parsers js2-CONST #'js2-parse-const-var)
7652 (aset parsers js2-CONTINUE #'js2-parse-continue)
7653 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7654 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7655 (aset parsers js2-DO #'js2-parse-do)
7656 (aset parsers js2-FOR #'js2-parse-for)
7657 (aset parsers js2-FUNCTION #'js2-function-parser)
7658 (aset parsers js2-IF #'js2-parse-if)
7659 (aset parsers js2-LC #'js2-parse-block)
7660 (aset parsers js2-LET #'js2-parse-let-stmt)
7661 (aset parsers js2-NAME #'js2-parse-name-or-label)
7662 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7663 (aset parsers js2-SEMI #'js2-parse-semi)
7664 (aset parsers js2-SWITCH #'js2-parse-switch)
7665 (aset parsers js2-THROW #'js2-parse-throw)
7666 (aset parsers js2-TRY #'js2-parse-try)
7667 (aset parsers js2-VAR #'js2-parse-const-var)
7668 (aset parsers js2-WHILE #'js2-parse-while)
7669 (aset parsers js2-WITH #'js2-parse-with)
7670 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7671 parsers)
7672 "A vector mapping token types to parser functions.")
7673
7674 (defsubst js2-parse-warn-missing-semi (beg end)
7675 (and js2-mode-show-strict-warnings
7676 js2-strict-missing-semi-warning
7677 (js2-add-strict-warning
7678 "msg.missing.semi" nil
7679 ;; back up to beginning of statement or line
7680 (max beg (save-excursion
7681 (goto-char end)
7682 (point-at-bol)))
7683 end)))
7684
7685 (defconst js2-no-semi-insertion
7686 (list js2-IF
7687 js2-SWITCH
7688 js2-WHILE
7689 js2-DO
7690 js2-FOR
7691 js2-TRY
7692 js2-WITH
7693 js2-LC
7694 js2-ERROR
7695 js2-SEMI
7696 js2-FUNCTION)
7697 "List of tokens that don't do automatic semicolon insertion.")
7698
7699 (defconst js2-autoinsert-semi-and-warn
7700 (list js2-ERROR js2-EOF js2-RC))
7701
7702 (defun js2-statement-helper ()
7703 (let* ((tt (js2-peek-token))
7704 (first-tt tt)
7705 (beg js2-token-beg)
7706 (parser (if (= tt js2-ERROR)
7707 #'js2-parse-semi
7708 (aref js2-parsers tt)))
7709 pn
7710 tt-flagged)
7711 ;; If the statement is set, then it's been told its label by now.
7712 (and js2-labeled-stmt
7713 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7714 (setq js2-labeled-stmt nil))
7715 (setq pn (funcall parser))
7716 ;; Don't do auto semi insertion for certain statement types.
7717 (unless (or (memq first-tt js2-no-semi-insertion)
7718 (js2-labeled-stmt-node-p pn))
7719 (js2-auto-insert-semicolon pn))
7720 pn))
7721
7722 (defun js2-auto-insert-semicolon (pn)
7723 (let* ((tt-flagged (js2-peek-flagged-token))
7724 (tt (logand tt-flagged js2-clear-ti-mask))
7725 (pos (js2-node-pos pn)))
7726 (cond
7727 ((= tt js2-SEMI)
7728 ;; Consume ';' as a part of expression
7729 (js2-consume-token)
7730 ;; extend the node bounds to include the semicolon.
7731 (setf (js2-node-len pn) (- js2-token-end pos)))
7732 ((memq tt js2-autoinsert-semi-and-warn)
7733 ;; Autoinsert ;
7734 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7735 (t
7736 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7737 ;; Report error if no EOL or autoinsert ';' otherwise
7738 (js2-report-error "msg.no.semi.stmt")
7739 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7740
7741 (defun js2-parse-condition ()
7742 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7743 The parens are discarded and the expression node is returned.
7744 The `pos' field of the return value is set to an absolute position
7745 that must be fixed up by the caller.
7746 Return value is a list (EXPR LP RP), with absolute paren positions."
7747 (let (pn lp rp)
7748 (if (js2-must-match js2-LP "msg.no.paren.cond")
7749 (setq lp js2-token-beg))
7750 (setq pn (js2-parse-expr))
7751 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7752 (setq rp js2-token-beg))
7753 ;; Report strict warning on code like "if (a = 7) ..."
7754 (if (and js2-strict-cond-assign-warning
7755 (js2-assign-node-p pn))
7756 (js2-add-strict-warning "msg.equal.as.assign" nil
7757 (js2-node-pos pn)
7758 (+ (js2-node-pos pn)
7759 (js2-node-len pn))))
7760 (list pn lp rp)))
7761
7762 (defun js2-parse-if ()
7763 "Parser for if-statement. Last matched token must be js2-IF."
7764 (let ((pos js2-token-beg)
7765 cond
7766 if-true
7767 if-false
7768 else-pos
7769 end
7770 pn)
7771 (js2-consume-token)
7772 (setq cond (js2-parse-condition)
7773 if-true (js2-parse-statement)
7774 if-false (if (js2-match-token js2-ELSE)
7775 (progn
7776 (setq else-pos (- js2-token-beg pos))
7777 (js2-parse-statement)))
7778 end (js2-node-end (or if-false if-true))
7779 pn (make-js2-if-node :pos pos
7780 :len (- end pos)
7781 :condition (car cond)
7782 :then-part if-true
7783 :else-part if-false
7784 :else-pos else-pos
7785 :lp (js2-relpos (second cond) pos)
7786 :rp (js2-relpos (third cond) pos)))
7787 (js2-node-add-children pn (car cond) if-true if-false)
7788 pn))
7789
7790 (defun js2-parse-switch ()
7791 "Parser for if-statement. Last matched token must be js2-SWITCH."
7792 (let ((pos js2-token-beg)
7793 tt
7794 pn
7795 discriminant
7796 has-default
7797 case-expr
7798 case-node
7799 case-pos
7800 cases
7801 stmt
7802 lp
7803 rp)
7804 (js2-consume-token)
7805 (if (js2-must-match js2-LP "msg.no.paren.switch")
7806 (setq lp js2-token-beg))
7807 (setq discriminant (js2-parse-expr)
7808 pn (make-js2-switch-node :discriminant discriminant
7809 :pos pos
7810 :lp (js2-relpos lp pos)))
7811 (js2-node-add-children pn discriminant)
7812 (js2-enter-switch pn)
7813 (unwind-protect
7814 (progn
7815 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7816 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7817 (js2-must-match js2-LC "msg.no.brace.switch")
7818 (catch 'break
7819 (while t
7820 (setq tt (js2-next-token)
7821 case-pos js2-token-beg)
7822 (cond
7823 ((= tt js2-RC)
7824 (setf (js2-node-len pn) (- js2-token-end pos))
7825 (throw 'break nil)) ; done
7826 ((= tt js2-CASE)
7827 (setq case-expr (js2-parse-expr))
7828 (js2-must-match js2-COLON "msg.no.colon.case"))
7829 ((= tt js2-DEFAULT)
7830 (if has-default
7831 (js2-report-error "msg.double.switch.default"))
7832 (setq has-default t
7833 case-expr nil)
7834 (js2-must-match js2-COLON "msg.no.colon.case"))
7835 (t
7836 (js2-report-error "msg.bad.switch")
7837 (throw 'break nil)))
7838 (setq case-node (make-js2-case-node :pos case-pos
7839 :len (- js2-token-end case-pos)
7840 :expr case-expr))
7841 (js2-node-add-children case-node case-expr)
7842 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7843 (/= tt js2-CASE)
7844 (/= tt js2-DEFAULT)
7845 (/= tt js2-EOF))
7846 (setf stmt (js2-parse-statement)
7847 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7848 (js2-block-node-push case-node stmt))
7849 (push case-node cases)))
7850 ;; add cases last, as pushing reverses the order to be correct
7851 (dolist (kid cases)
7852 (js2-node-add-children pn kid)
7853 (push kid (js2-switch-node-cases pn)))
7854 pn) ; return value
7855 (js2-exit-switch))))
7856
7857 (defun js2-parse-while ()
7858 "Parser for while-statement. Last matched token must be js2-WHILE."
7859 (let ((pos js2-token-beg)
7860 (pn (make-js2-while-node))
7861 cond
7862 body)
7863 (js2-consume-token)
7864 (js2-enter-loop pn)
7865 (unwind-protect
7866 (progn
7867 (setf cond (js2-parse-condition)
7868 (js2-while-node-condition pn) (car cond)
7869 body (js2-parse-statement)
7870 (js2-while-node-body pn) body
7871 (js2-node-len pn) (- (js2-node-end body) pos)
7872 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7873 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7874 (js2-node-add-children pn body (car cond)))
7875 (js2-exit-loop))
7876 pn))
7877
7878 (defun js2-parse-do ()
7879 "Parser for do-statement. Last matched token must be js2-DO."
7880 (let ((pos js2-token-beg)
7881 (pn (make-js2-do-node))
7882 cond
7883 body
7884 end)
7885 (js2-consume-token)
7886 (js2-enter-loop pn)
7887 (unwind-protect
7888 (progn
7889 (setq body (js2-parse-statement))
7890 (js2-must-match js2-WHILE "msg.no.while.do")
7891 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7892 cond (js2-parse-condition)
7893 (js2-do-node-condition pn) (car cond)
7894 (js2-do-node-body pn) body
7895 end js2-ts-cursor
7896 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7897 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7898 (js2-node-add-children pn (car cond) body))
7899 (js2-exit-loop))
7900 ;; Always auto-insert semicolon to follow SpiderMonkey:
7901 ;; It is required by ECMAScript but is ignored by the rest of
7902 ;; world; see bug 238945
7903 (if (js2-match-token js2-SEMI)
7904 (setq end js2-ts-cursor))
7905 (setf (js2-node-len pn) (- end pos))
7906 pn))
7907
7908 (defun js2-parse-for ()
7909 "Parser for for-statement. Last matched token must be js2-FOR.
7910 Parses for, for-in, and for each-in statements."
7911 (let ((for-pos js2-token-beg)
7912 pn
7913 is-for-each
7914 is-for-in
7915 in-pos
7916 each-pos
7917 tmp-pos
7918 init ; Node init is also foo in 'foo in object'
7919 cond ; Node cond is also object in 'foo in object'
7920 incr ; 3rd section of for-loop initializer
7921 body
7922 tt
7923 lp
7924 rp)
7925 (js2-consume-token)
7926 ;; See if this is a for each () instead of just a for ()
7927 (when (js2-match-token js2-NAME)
7928 (if (string= "each" js2-ts-string)
7929 (progn
7930 (setq is-for-each t
7931 each-pos (- js2-token-beg for-pos)) ; relative
7932 (js2-record-face 'font-lock-keyword-face))
7933 (js2-report-error "msg.no.paren.for")))
7934 (if (js2-must-match js2-LP "msg.no.paren.for")
7935 (setq lp (- js2-token-beg for-pos)))
7936 (setq tt (js2-peek-token))
7937 ;; 'for' makes local scope
7938 (js2-push-scope (make-js2-scope))
7939 (unwind-protect
7940 ;; parse init clause
7941 (let ((js2-in-for-init t)) ; set as dynamic variable
7942 (cond
7943 ((= tt js2-SEMI)
7944 (setq init (make-js2-empty-expr-node)))
7945 ((or (= tt js2-VAR) (= tt js2-LET))
7946 (js2-consume-token)
7947 (setq init (js2-parse-variables tt js2-token-beg)))
7948 (t
7949 (setq init (js2-parse-expr)))))
7950 (if (js2-match-token js2-IN)
7951 (setq is-for-in t
7952 in-pos (- js2-token-beg for-pos)
7953 ;; scope of iteration target object is not the scope we've created above.
7954 ;; stash current scope temporary.
7955 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7956 (js2-parse-expr))) ; object over which we're iterating
7957 ;; else ordinary for loop - parse cond and incr
7958 (js2-must-match js2-SEMI "msg.no.semi.for")
7959 (setq cond (if (= (js2-peek-token) js2-SEMI)
7960 (make-js2-empty-expr-node) ; no loop condition
7961 (js2-parse-expr)))
7962 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7963 (setq tmp-pos js2-token-end
7964 incr (if (= (js2-peek-token) js2-RP)
7965 (make-js2-empty-expr-node :pos tmp-pos)
7966 (js2-parse-expr))))
7967 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7968 (setq rp (- js2-token-beg for-pos)))
7969 (if (not is-for-in)
7970 (setq pn (make-js2-for-node :init init
7971 :condition cond
7972 :update incr
7973 :lp lp
7974 :rp rp))
7975 ;; cond could be null if 'in obj' got eaten by the init node.
7976 (if (js2-infix-node-p init)
7977 ;; it was (foo in bar) instead of (var foo in bar)
7978 (setq cond (js2-infix-node-right init)
7979 init (js2-infix-node-left init))
7980 (if (and (js2-var-decl-node-p init)
7981 (> (length (js2-var-decl-node-kids init)) 1))
7982 (js2-report-error "msg.mult.index")))
7983 (setq pn (make-js2-for-in-node :iterator init
7984 :object cond
7985 :in-pos in-pos
7986 :foreach-p is-for-each
7987 :each-pos each-pos
7988 :lp lp
7989 :rp rp)))
7990 (unwind-protect
7991 (progn
7992 (js2-enter-loop pn)
7993 ;; We have to parse the body -after- creating the loop node,
7994 ;; so that the loop node appears in the js2-loop-set, allowing
7995 ;; break/continue statements to find the enclosing loop.
7996 (setf body (js2-parse-statement)
7997 (js2-loop-node-body pn) body
7998 (js2-node-pos pn) for-pos
7999 (js2-node-len pn) (- (js2-node-end body) for-pos))
8000 (js2-node-add-children pn init cond incr body))
8001 ;; finally
8002 (js2-exit-loop))
8003 (js2-pop-scope))
8004 pn))
8005
8006 (defun js2-parse-try ()
8007 "Parser for try-statement. Last matched token must be js2-TRY."
8008 (let ((try-pos js2-token-beg)
8009 try-end
8010 try-block
8011 catch-blocks
8012 finally-block
8013 saw-default-catch
8014 peek
8015 param
8016 catch-cond
8017 catch-node
8018 guard-kwd
8019 catch-pos
8020 finally-pos
8021 pn
8022 block
8023 lp
8024 rp)
8025 (js2-consume-token)
8026 (if (/= (js2-peek-token) js2-LC)
8027 (js2-report-error "msg.no.brace.try"))
8028 (setq try-block (js2-parse-statement)
8029 try-end (js2-node-end try-block)
8030 peek (js2-peek-token))
8031 (cond
8032 ((= peek js2-CATCH)
8033 (while (js2-match-token js2-CATCH)
8034 (setq catch-pos js2-token-beg
8035 guard-kwd nil
8036 catch-cond nil
8037 lp nil
8038 rp nil)
8039 (if saw-default-catch
8040 (js2-report-error "msg.catch.unreachable"))
8041 (if (js2-must-match js2-LP "msg.no.paren.catch")
8042 (setq lp (- js2-token-beg catch-pos)))
8043 (js2-push-scope (make-js2-scope))
8044 (let ((tt (js2-peek-token)))
8045 (cond
8046 ;; destructuring pattern
8047 ;; catch ({ message, file }) { ... }
8048 ((or (= tt js2-LB) (= tt js2-LC))
8049 (setq param
8050 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8051 js2-LET nil)))
8052 ;; simple name
8053 (t
8054 (js2-must-match js2-NAME "msg.bad.catchcond")
8055 (setq param (js2-create-name-node))
8056 (js2-define-symbol js2-LET js2-ts-string param))))
8057 ;; pattern guard
8058 (if (js2-match-token js2-IF)
8059 (setq guard-kwd (- js2-token-beg catch-pos)
8060 catch-cond (js2-parse-expr))
8061 (setq saw-default-catch t))
8062 (if (js2-must-match js2-RP "msg.bad.catchcond")
8063 (setq rp (- js2-token-beg catch-pos)))
8064 (js2-must-match js2-LC "msg.no.brace.catchblock")
8065 (setq block (js2-parse-statements)
8066 try-end (js2-node-end block)
8067 catch-node (make-js2-catch-node :pos catch-pos
8068 :param param
8069 :guard-expr catch-cond
8070 :guard-kwd guard-kwd
8071 :block block
8072 :lp lp
8073 :rp rp))
8074 (js2-pop-scope)
8075 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8076 (setq try-end js2-token-beg))
8077 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8078 (js2-node-len catch-node) (- try-end catch-pos))
8079 (js2-node-add-children catch-node param catch-cond block)
8080 (push catch-node catch-blocks)))
8081 ((/= peek js2-FINALLY)
8082 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8083 (js2-node-pos try-block)
8084 (- (setq try-end (js2-node-end try-block))
8085 (js2-node-pos try-block)))))
8086 (when (js2-match-token js2-FINALLY)
8087 (setq finally-pos js2-token-beg
8088 block (js2-parse-statement)
8089 try-end (js2-node-end block)
8090 finally-block (make-js2-finally-node :pos finally-pos
8091 :len (- try-end finally-pos)
8092 :body block))
8093 (js2-node-add-children finally-block block))
8094 (setq pn (make-js2-try-node :pos try-pos
8095 :len (- try-end try-pos)
8096 :try-block try-block
8097 :finally-block finally-block))
8098 (js2-node-add-children pn try-block finally-block)
8099 ;; push them onto the try-node, which reverses and corrects their order
8100 (dolist (cb catch-blocks)
8101 (js2-node-add-children pn cb)
8102 (push cb (js2-try-node-catch-clauses pn)))
8103 pn))
8104
8105 (defun js2-parse-throw ()
8106 "Parser for throw-statement. Last matched token must be js2-THROW."
8107 (let ((pos js2-token-beg)
8108 expr
8109 pn)
8110 (js2-consume-token)
8111 (if (= (js2-peek-token-or-eol) js2-EOL)
8112 ;; ECMAScript does not allow new lines before throw expression,
8113 ;; see bug 256617
8114 (js2-report-error "msg.bad.throw.eol"))
8115 (setq expr (js2-parse-expr)
8116 pn (make-js2-throw-node :pos pos
8117 :len (- (js2-node-end expr) pos)
8118 :expr expr))
8119 (js2-node-add-children pn expr)
8120 pn))
8121
8122 (defsubst js2-match-jump-label-name (label-name)
8123 "If break/continue specified a label, return that label's labeled stmt.
8124 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8125 does not match an existing label, reports an error and returns nil."
8126 (let ((bundle (cdr (assoc label-name js2-label-set))))
8127 (if (null bundle)
8128 (js2-report-error "msg.undef.label"))
8129 bundle))
8130
8131 (defun js2-parse-break ()
8132 "Parser for break-statement. Last matched token must be js2-BREAK."
8133 (let ((pos js2-token-beg)
8134 (end js2-token-end)
8135 break-target ; statement to break from
8136 break-label ; in "break foo", name-node representing the foo
8137 labels ; matching labeled statement to break to
8138 pn)
8139 (js2-consume-token) ; `break'
8140 (when (eq (js2-peek-token-or-eol) js2-NAME)
8141 (js2-consume-token)
8142 (setq break-label (js2-create-name-node)
8143 end (js2-node-end break-label)
8144 ;; matchJumpLabelName only matches if there is one
8145 labels (js2-match-jump-label-name js2-ts-string)
8146 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8147 (unless (or break-target break-label)
8148 ;; no break target specified - try for innermost enclosing loop/switch
8149 (if (null js2-loop-and-switch-set)
8150 (unless break-label
8151 (js2-report-error "msg.bad.break" nil pos (length "break")))
8152 (setq break-target (car js2-loop-and-switch-set))))
8153 (setq pn (make-js2-break-node :pos pos
8154 :len (- end pos)
8155 :label break-label
8156 :target break-target))
8157 (js2-node-add-children pn break-label) ; but not break-target
8158 pn))
8159
8160 (defun js2-parse-continue ()
8161 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8162 (let ((pos js2-token-beg)
8163 (end js2-token-end)
8164 label ; optional user-specified label, a `js2-name-node'
8165 labels ; current matching labeled stmt, if any
8166 target ; the `js2-loop-node' target of this continue stmt
8167 pn)
8168 (js2-consume-token) ; `continue'
8169 (when (= (js2-peek-token-or-eol) js2-NAME)
8170 (js2-consume-token)
8171 (setq label (js2-create-name-node)
8172 end (js2-node-end label)
8173 ;; matchJumpLabelName only matches if there is one
8174 labels (js2-match-jump-label-name js2-ts-string)))
8175 (cond
8176 ((null labels) ; no current label to go to
8177 (if (null js2-loop-set) ; no loop to continue to
8178 (js2-report-error "msg.continue.outside" nil pos
8179 (length "continue"))
8180 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8181 (t
8182 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8183 (setq target (js2-labeled-stmt-node-stmt labels))
8184 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8185 (setq pn (make-js2-continue-node :pos pos
8186 :len (- end pos)
8187 :label label
8188 :target target))
8189 (js2-node-add-children pn label) ; but not target - it's not our child
8190 pn))
8191
8192 (defun js2-parse-with ()
8193 "Parser for with-statement. Last matched token must be js2-WITH."
8194 (js2-consume-token)
8195 (let ((pos js2-token-beg)
8196 obj body pn lp rp)
8197 (if (js2-must-match js2-LP "msg.no.paren.with")
8198 (setq lp js2-token-beg))
8199 (setq obj (js2-parse-expr))
8200 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8201 (setq rp js2-token-beg))
8202 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8203 (setq body (js2-parse-statement)))
8204 (setq pn (make-js2-with-node :pos pos
8205 :len (- (js2-node-end body) pos)
8206 :object obj
8207 :body body
8208 :lp (js2-relpos lp pos)
8209 :rp (js2-relpos rp pos)))
8210 (js2-node-add-children pn obj body)
8211 pn))
8212
8213 (defun js2-parse-const-var ()
8214 "Parser for var- or const-statement.
8215 Last matched token must be js2-CONST or js2-VAR."
8216 (let ((tt (js2-peek-token))
8217 (pos js2-token-beg)
8218 expr
8219 pn)
8220 (js2-consume-token)
8221 (setq expr (js2-parse-variables tt js2-token-beg)
8222 pn (make-js2-expr-stmt-node :pos pos
8223 :len (- (js2-node-end expr) pos)
8224 :expr expr))
8225 (js2-node-add-children pn expr)
8226 pn))
8227
8228 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8229 (let ((pn (make-js2-expr-stmt-node :pos pos
8230 :len (js2-node-len expr)
8231 :type (if (js2-inside-function)
8232 js2-EXPR_VOID
8233 js2-EXPR_RESULT)
8234 :expr expr)))
8235 (if add-child
8236 (js2-node-add-children pn expr))
8237 pn))
8238
8239 (defun js2-parse-let-stmt ()
8240 "Parser for let-statement. Last matched token must be js2-LET."
8241 (js2-consume-token)
8242 (let ((pos js2-token-beg)
8243 expr
8244 pn)
8245 (if (= (js2-peek-token) js2-LP)
8246 ;; let expression in statement context
8247 (setq expr (js2-parse-let pos 'statement)
8248 pn (js2-wrap-with-expr-stmt pos expr t))
8249 ;; else we're looking at a statement like let x=6, y=7;
8250 (setf expr (js2-parse-variables js2-LET pos)
8251 pn (js2-wrap-with-expr-stmt pos expr t)
8252 (js2-node-type pn) js2-EXPR_RESULT))
8253 pn))
8254
8255 (defun js2-parse-ret-yield ()
8256 (js2-parse-return-or-yield (js2-peek-token) nil))
8257
8258 (defconst js2-parse-return-stmt-enders
8259 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8260
8261 (defsubst js2-now-all-set (before after mask)
8262 "Return whether or not the bits in the mask have changed to all set.
8263 BEFORE is bits before change, AFTER is bits after change, and MASK is
8264 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8265 but not BEFORE."
8266 (and (/= (logand before mask) mask)
8267 (= (logand after mask) mask)))
8268
8269 (defun js2-parse-return-or-yield (tt expr-context)
8270 (let ((pos js2-token-beg)
8271 (end js2-token-end)
8272 (before js2-end-flags)
8273 (inside-function (js2-inside-function))
8274 e
8275 ret
8276 name)
8277 (unless inside-function
8278 (js2-report-error (if (eq tt js2-RETURN)
8279 "msg.bad.return"
8280 "msg.bad.yield")))
8281 (js2-consume-token)
8282 ;; This is ugly, but we don't want to require a semicolon.
8283 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8284 (setq e (js2-parse-expr)
8285 end (js2-node-end e)))
8286 (cond
8287 ((eq tt js2-RETURN)
8288 (js2-set-flag js2-end-flags (if (null e)
8289 js2-end-returns
8290 js2-end-returns-value))
8291 (setq ret (make-js2-return-node :pos pos
8292 :len (- end pos)
8293 :retval e))
8294 (js2-node-add-children ret e)
8295 ;; See if we need a strict mode warning.
8296 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8297 ;; more thorough and accurate than this before/after flag check.
8298 ;; E.g. if there's a finally-block that always returns, we shouldn't
8299 ;; show a warning generated by inconsistent returns in the catch blocks.
8300 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8301 ;; so we know which returns/yields to highlight, and we should get rid of
8302 ;; all the checking in `js2-parse-return-or-yield'.
8303 (if (and js2-strict-inconsistent-return-warning
8304 (js2-now-all-set before js2-end-flags
8305 (logior js2-end-returns js2-end-returns-value)))
8306 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8307 (t
8308 (unless (js2-inside-function)
8309 (js2-report-error "msg.bad.yield"))
8310 (js2-set-flag js2-end-flags js2-end-yields)
8311 (setq ret (make-js2-yield-node :pos pos
8312 :len (- end pos)
8313 :value e))
8314 (js2-node-add-children ret e)
8315 (unless expr-context
8316 (setq e ret
8317 ret (js2-wrap-with-expr-stmt pos e t))
8318 (js2-set-requires-activation)
8319 (js2-set-is-generator))))
8320 ;; see if we are mixing yields and value returns.
8321 (when (and inside-function
8322 (js2-now-all-set before js2-end-flags
8323 (logior js2-end-yields js2-end-returns-value)))
8324 (setq name (js2-function-name js2-current-script-or-fn))
8325 (if (zerop (length name))
8326 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8327 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8328 ret))
8329
8330 (defun js2-parse-debugger ()
8331 (js2-consume-token)
8332 (make-js2-keyword-node :type js2-DEBUGGER))
8333
8334 (defun js2-parse-block ()
8335 "Parser for a curly-delimited statement block.
8336 Last token matched must be js2-LC."
8337 (let ((pos js2-token-beg)
8338 (pn (make-js2-scope)))
8339 (js2-consume-token)
8340 (js2-push-scope pn)
8341 (unwind-protect
8342 (progn
8343 (js2-parse-statements pn)
8344 (js2-must-match js2-RC "msg.no.brace.block")
8345 (setf (js2-node-len pn) (- js2-token-end pos)))
8346 (js2-pop-scope))
8347 pn))
8348
8349 ;; for js2-ERROR too, to have a node for error recovery to work on
8350 (defun js2-parse-semi ()
8351 "Parse a statement or handle an error.
8352 Last matched token is js-SEMI or js-ERROR."
8353 (let ((tt (js2-peek-token)) pos len)
8354 (js2-consume-token)
8355 (if (eq tt js2-SEMI)
8356 (make-js2-empty-expr-node :len 1)
8357 (setq pos js2-token-beg
8358 len (- js2-token-beg pos))
8359 (js2-report-error "msg.syntax" nil pos len)
8360 (make-js2-error-node :pos pos :len len))))
8361
8362 (defun js2-parse-default-xml-namespace ()
8363 "Parse a `default xml namespace = <expr>' e4x statement."
8364 (let ((pos js2-token-beg)
8365 end len expr unary es)
8366 (js2-consume-token)
8367 (js2-must-have-xml)
8368 (js2-set-requires-activation)
8369 (setq len (- js2-ts-cursor pos))
8370 (unless (and (js2-match-token js2-NAME)
8371 (string= js2-ts-string "xml"))
8372 (js2-report-error "msg.bad.namespace" nil pos len))
8373 (unless (and (js2-match-token js2-NAME)
8374 (string= js2-ts-string "namespace"))
8375 (js2-report-error "msg.bad.namespace" nil pos len))
8376 (unless (js2-match-token js2-ASSIGN)
8377 (js2-report-error "msg.bad.namespace" nil pos len))
8378 (setq expr (js2-parse-expr)
8379 end (js2-node-end expr)
8380 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8381 :pos pos
8382 :len (- end pos)
8383 :operand expr))
8384 (js2-node-add-children unary expr)
8385 (make-js2-expr-stmt-node :pos pos
8386 :len (- end pos)
8387 :expr unary)))
8388
8389 (defun js2-record-label (label bundle)
8390 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8391 (js2-consume-token)
8392 (let ((name (js2-label-node-name label))
8393 labeled-stmt
8394 dup)
8395 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8396 ;; flag both labels if possible when used in editing mode
8397 (if (and js2-parse-ide-mode
8398 (setq dup (js2-get-label-by-name labeled-stmt name)))
8399 (js2-report-error "msg.dup.label" nil
8400 (js2-node-abs-pos dup) (js2-node-len dup)))
8401 (js2-report-error "msg.dup.label" nil
8402 (js2-node-pos label) (js2-node-len label)))
8403 (js2-labeled-stmt-node-add-label bundle label)
8404 (js2-node-add-children bundle label)
8405 ;; Add one reference to the bundle per label in `js2-label-set'
8406 (push (cons name bundle) js2-label-set)))
8407
8408 (defun js2-parse-name-or-label ()
8409 "Parser for identifier or label. Last token matched must be js2-NAME.
8410 Called when we found a name in a statement context. If it's a label, we gather
8411 up any following labels and the next non-label statement into a
8412 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8413 expression and return it wrapped in a `js2-expr-stmt-node'."
8414 (let ((pos js2-token-beg)
8415 (end js2-token-end)
8416 expr
8417 stmt
8418 pn
8419 bundle
8420 (continue t))
8421 ;; set check for label and call down to `js2-parse-primary-expr'
8422 (js2-set-check-for-label)
8423 (setq expr (js2-parse-expr))
8424 (if (/= (js2-node-type expr) js2-LABEL)
8425 ;; Parsed non-label expression - wrap with expression stmt.
8426 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8427 ;; else parsed a label
8428 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8429 (js2-record-label expr bundle)
8430 ;; look for more labels
8431 (while (and continue (= (js2-peek-token) js2-NAME))
8432 (js2-set-check-for-label)
8433 (setq expr (js2-parse-expr))
8434 (if (/= (js2-node-type expr) js2-LABEL)
8435 (progn
8436 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8437 continue nil)
8438 (js2-auto-insert-semicolon stmt))
8439 (js2-record-label expr bundle)))
8440 ;; no more labels; now parse the labeled statement
8441 (unwind-protect
8442 (unless stmt
8443 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8444 (setq stmt (js2-statement-helper))))
8445 ;; remove the labels for this statement from the global set
8446 (dolist (label (js2-labeled-stmt-node-labels bundle))
8447 (setq js2-label-set (remove label js2-label-set))))
8448 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8449 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8450 (js2-node-add-children bundle stmt)
8451 bundle)))
8452
8453 (defun js2-parse-expr-stmt ()
8454 "Default parser in statement context, if no recognized statement found."
8455 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8456
8457 (defun js2-parse-variables (decl-type pos)
8458 "Parse a comma-separated list of variable declarations.
8459 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8460
8461 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8462 For 'var' or 'const', the keyword should be the token last scanned.
8463
8464 POS is the position where the node should start. It's sometimes the
8465 var/const/let keyword, and other times the beginning of the first token
8466 in the first variable declaration.
8467
8468 Returns the parsed `js2-var-decl-node' expression node."
8469 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8470 :pos pos))
8471 destructuring
8472 kid-pos
8473 tt
8474 init
8475 name
8476 end
8477 nbeg nend
8478 vi
8479 (continue t))
8480 ;; Example:
8481 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8482 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8483 ;; var {a, b} = baz;
8484 (while continue
8485 (setq destructuring nil
8486 name nil
8487 tt (js2-peek-token)
8488 kid-pos js2-token-beg
8489 end js2-token-end
8490 init nil)
8491 (if (or (= tt js2-LB) (= tt js2-LC))
8492 ;; Destructuring assignment, e.g., var [a, b] = ...
8493 (setq destructuring (js2-parse-primary-expr-lhs)
8494 end (js2-node-end destructuring))
8495 ;; Simple variable name
8496 (when (js2-must-match js2-NAME "msg.bad.var")
8497 (setq name (js2-create-name-node)
8498 nbeg js2-token-beg
8499 nend js2-token-end
8500 end nend)
8501 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8502 (when (js2-match-token js2-ASSIGN)
8503 (setq init (js2-parse-assign-expr)
8504 end (js2-node-end init))
8505 (if (and js2-parse-ide-mode
8506 (or (js2-object-node-p init)
8507 (js2-function-node-p init)))
8508 (js2-record-imenu-functions init name)))
8509 (when name
8510 (js2-set-face nbeg nend (if (js2-function-node-p init)
8511 'font-lock-function-name-face
8512 'font-lock-variable-name-face)
8513 'record))
8514 (setq vi (make-js2-var-init-node :pos kid-pos
8515 :len (- end kid-pos)
8516 :type decl-type))
8517 (if destructuring
8518 (progn
8519 (if (and (null init) (not js2-in-for-init))
8520 (js2-report-error "msg.destruct.assign.no.init"))
8521 (js2-define-destruct-symbols destructuring
8522 decl-type
8523 'font-lock-variable-name-face)
8524 (setf (js2-var-init-node-target vi) destructuring))
8525 (setf (js2-var-init-node-target vi) name))
8526 (setf (js2-var-init-node-initializer vi) init)
8527 (js2-node-add-children vi name destructuring init)
8528 (js2-block-node-push result vi)
8529 (unless (js2-match-token js2-COMMA)
8530 (setq continue nil)))
8531 (setf (js2-node-len result) (- end pos))
8532 result))
8533
8534 (defun js2-parse-let (pos &optional stmt-p)
8535 "Parse a let expression or statement.
8536 A let-expression is of the form `let (vars) expr'.
8537 A let-statment is of the form `let (vars) {statements}'.
8538 The third form of let is a variable declaration list, handled
8539 by `js2-parse-variables'."
8540 (let ((pn (make-js2-let-node :pos pos))
8541 beg vars body)
8542 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8543 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8544 (js2-push-scope pn)
8545 (unwind-protect
8546 (progn
8547 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8548 (if (js2-must-match js2-RP "msg.no.paren.let")
8549 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8550 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8551 ;; let statement
8552 (progn
8553 (js2-consume-token)
8554 (setf beg js2-token-beg ; position stmt at LC
8555 body (js2-parse-statements))
8556 (js2-must-match js2-RC "msg.no.curly.let")
8557 (setf (js2-node-len body) (- js2-token-end beg)
8558 (js2-node-len pn) (- js2-token-end pos)
8559 (js2-let-node-body pn) body
8560 (js2-node-type pn) js2-LET))
8561 ;; let expression
8562 (setf body (js2-parse-expr)
8563 (js2-node-len pn) (- (js2-node-end body) pos)
8564 (js2-let-node-body pn) body))
8565 (js2-node-add-children pn vars body))
8566 (js2-pop-scope))
8567 pn))
8568
8569 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8570 (js2-scope-put-symbol (or scope js2-current-scope)
8571 name
8572 (make-js2-symbol decl-type name node)))
8573
8574 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8575 "Define a symbol in the current scope.
8576 If NODE is non-nil, it is the AST node associated with the symbol."
8577 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8578 (symbol (if defining-scope
8579 (js2-scope-get-symbol defining-scope name)))
8580 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8581 (cond
8582 ((and symbol ; already defined
8583 (or (= sdt js2-CONST) ; old version is const
8584 (= decl-type js2-CONST) ; new version is const
8585 ;; two let-bound vars in this block have same name
8586 (and (= sdt js2-LET)
8587 (eq defining-scope js2-current-scope))))
8588 (js2-report-error
8589 (cond
8590 ((= sdt js2-CONST) "msg.const.redecl")
8591 ((= sdt js2-LET) "msg.let.redecl")
8592 ((= sdt js2-VAR) "msg.var.redecl")
8593 ((= sdt js2-FUNCTION) "msg.function.redecl")
8594 (t "msg.parm.redecl"))
8595 name))
8596 ((= decl-type js2-LET)
8597 (if (and (not ignore-not-in-block)
8598 (or (= (js2-node-type js2-current-scope) js2-IF)
8599 (js2-loop-node-p js2-current-scope)))
8600 (js2-report-error "msg.let.decl.not.in.block")
8601 (js2-define-new-symbol decl-type name node)))
8602 ((or (= decl-type js2-VAR)
8603 (= decl-type js2-CONST)
8604 (= decl-type js2-FUNCTION))
8605 (if symbol
8606 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8607 (js2-add-strict-warning "msg.var.redecl" name)
8608 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8609 (js2-add-strict-warning "msg.var.hides.arg" name)))
8610 (js2-define-new-symbol decl-type name node
8611 js2-current-script-or-fn)))
8612 ((= decl-type js2-LP)
8613 (if symbol
8614 ;; must be duplicate parameter. Second parameter hides the
8615 ;; first, so go ahead and add the second pararameter
8616 (js2-report-warning "msg.dup.parms" name))
8617 (js2-define-new-symbol decl-type name node))
8618 (t (js2-code-bug)))))
8619
8620 (defun js2-parse-expr (&optional oneshot)
8621 (let* ((pn (js2-parse-assign-expr))
8622 (pos (js2-node-pos pn))
8623 left
8624 right
8625 op-pos)
8626 (while (and (not oneshot)
8627 (js2-match-token js2-COMMA))
8628 (setq op-pos (- js2-token-beg pos)) ; relative
8629 (if (= (js2-peek-token) js2-YIELD)
8630 (js2-report-error "msg.yield.parenthesized"))
8631 (setq right (js2-parse-assign-expr)
8632 left pn
8633 pn (make-js2-infix-node :type js2-COMMA
8634 :pos pos
8635 :len (- js2-ts-cursor pos)
8636 :op-pos op-pos
8637 :left left
8638 :right right))
8639 (js2-node-add-children pn left right))
8640 pn))
8641
8642 (defun js2-parse-assign-expr ()
8643 (let ((tt (js2-peek-token))
8644 (pos js2-token-beg)
8645 pn
8646 left
8647 right
8648 op-pos)
8649 (if (= tt js2-YIELD)
8650 (js2-parse-return-or-yield tt t)
8651 ;; not yield - parse assignment expression
8652 (setq pn (js2-parse-cond-expr)
8653 tt (js2-peek-token))
8654 (when (and (<= js2-first-assign tt)
8655 (<= tt js2-last-assign))
8656 ;; tt express assignment (=, |=, ^=, ..., %=)
8657 (js2-consume-token)
8658 (setq op-pos (- js2-token-beg pos) ; relative
8659 left pn
8660 right (js2-parse-assign-expr)
8661 pn (make-js2-assign-node :type tt
8662 :pos pos
8663 :len (- (js2-node-end right) pos)
8664 :op-pos op-pos
8665 :left left
8666 :right right))
8667 (when js2-parse-ide-mode
8668 (js2-highlight-assign-targets pn left right)
8669 (if (or (js2-function-node-p right)
8670 (js2-object-node-p right))
8671 (js2-record-imenu-functions right left)))
8672 ;; do this last so ide checks above can use absolute positions
8673 (js2-node-add-children pn left right))
8674 pn)))
8675
8676 (defun js2-parse-cond-expr ()
8677 (let ((pos js2-token-beg)
8678 (pn (js2-parse-or-expr))
8679 test-expr
8680 if-true
8681 if-false
8682 q-pos
8683 c-pos)
8684 (when (js2-match-token js2-HOOK)
8685 (setq q-pos (- js2-token-beg pos)
8686 if-true (js2-parse-assign-expr))
8687 (js2-must-match js2-COLON "msg.no.colon.cond")
8688 (setq c-pos (- js2-token-beg pos)
8689 if-false (js2-parse-assign-expr)
8690 test-expr pn
8691 pn (make-js2-cond-node :pos pos
8692 :len (- (js2-node-end if-false) pos)
8693 :test-expr test-expr
8694 :true-expr if-true
8695 :false-expr if-false
8696 :q-pos q-pos
8697 :c-pos c-pos))
8698 (js2-node-add-children pn test-expr if-true if-false))
8699 pn))
8700
8701 (defun js2-make-binary (type left parser)
8702 "Helper for constructing a binary-operator AST node.
8703 LEFT is the left-side-expression, already parsed, and the
8704 binary operator should have just been matched.
8705 PARSER is a function to call to parse the right operand,
8706 or a `js2-node' struct if it has already been parsed."
8707 (let* ((pos (js2-node-pos left))
8708 (op-pos (- js2-token-beg pos))
8709 (right (if (js2-node-p parser)
8710 parser
8711 (funcall parser)))
8712 (pn (make-js2-infix-node :type type
8713 :pos pos
8714 :len (- (js2-node-end right) pos)
8715 :op-pos op-pos
8716 :left left
8717 :right right)))
8718 (js2-node-add-children pn left right)
8719 pn))
8720
8721 (defun js2-parse-or-expr ()
8722 (let ((pn (js2-parse-and-expr)))
8723 (when (js2-match-token js2-OR)
8724 (setq pn (js2-make-binary js2-OR
8725 pn
8726 'js2-parse-or-expr)))
8727 pn))
8728
8729 (defun js2-parse-and-expr ()
8730 (let ((pn (js2-parse-bit-or-expr)))
8731 (when (js2-match-token js2-AND)
8732 (setq pn (js2-make-binary js2-AND
8733 pn
8734 'js2-parse-and-expr)))
8735 pn))
8736
8737 (defun js2-parse-bit-or-expr ()
8738 (let ((pn (js2-parse-bit-xor-expr)))
8739 (while (js2-match-token js2-BITOR)
8740 (setq pn (js2-make-binary js2-BITOR
8741 pn
8742 'js2-parse-bit-xor-expr)))
8743 pn))
8744
8745 (defun js2-parse-bit-xor-expr ()
8746 (let ((pn (js2-parse-bit-and-expr)))
8747 (while (js2-match-token js2-BITXOR)
8748 (setq pn (js2-make-binary js2-BITXOR
8749 pn
8750 'js2-parse-bit-and-expr)))
8751 pn))
8752
8753 (defun js2-parse-bit-and-expr ()
8754 (let ((pn (js2-parse-eq-expr)))
8755 (while (js2-match-token js2-BITAND)
8756 (setq pn (js2-make-binary js2-BITAND
8757 pn
8758 'js2-parse-eq-expr)))
8759 pn))
8760
8761 (defconst js2-parse-eq-ops
8762 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8763
8764 (defun js2-parse-eq-expr ()
8765 (let ((pn (js2-parse-rel-expr))
8766 tt)
8767 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8768 (js2-consume-token)
8769 (setq pn (js2-make-binary tt
8770 pn
8771 'js2-parse-rel-expr)))
8772 pn))
8773
8774 (defconst js2-parse-rel-ops
8775 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8776
8777 (defun js2-parse-rel-expr ()
8778 (let ((pn (js2-parse-shift-expr))
8779 (continue t)
8780 tt)
8781 (while continue
8782 (setq tt (js2-peek-token))
8783 (cond
8784 ((and js2-in-for-init (= tt js2-IN))
8785 (setq continue nil))
8786 ((memq tt js2-parse-rel-ops)
8787 (js2-consume-token)
8788 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8789 (t
8790 (setq continue nil))))
8791 pn))
8792
8793 (defconst js2-parse-shift-ops
8794 (list js2-LSH js2-URSH js2-RSH))
8795
8796 (defun js2-parse-shift-expr ()
8797 (let ((pn (js2-parse-add-expr))
8798 tt
8799 (continue t))
8800 (while continue
8801 (setq tt (js2-peek-token))
8802 (if (memq tt js2-parse-shift-ops)
8803 (progn
8804 (js2-consume-token)
8805 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8806 (setq continue nil)))
8807 pn))
8808
8809 (defun js2-parse-add-expr ()
8810 (let ((pn (js2-parse-mul-expr))
8811 tt
8812 (continue t))
8813 (while continue
8814 (setq tt (js2-peek-token))
8815 (if (or (= tt js2-ADD) (= tt js2-SUB))
8816 (progn
8817 (js2-consume-token)
8818 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8819 (setq continue nil)))
8820 pn))
8821
8822 (defconst js2-parse-mul-ops
8823 (list js2-MUL js2-DIV js2-MOD))
8824
8825 (defun js2-parse-mul-expr ()
8826 (let ((pn (js2-parse-unary-expr))
8827 tt
8828 (continue t))
8829 (while continue
8830 (setq tt (js2-peek-token))
8831 (if (memq tt js2-parse-mul-ops)
8832 (progn
8833 (js2-consume-token)
8834 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8835 (setq continue nil)))
8836 pn))
8837
8838 (defsubst js2-make-unary (type parser &rest args)
8839 "Make a unary node of type TYPE.
8840 PARSER is either a node (for postfix operators) or a function to call
8841 to parse the operand (for prefix operators)."
8842 (let* ((pos js2-token-beg)
8843 (postfix (js2-node-p parser))
8844 (expr (if postfix
8845 parser
8846 (apply parser args)))
8847 end
8848 pn)
8849 (if postfix ; e.g. i++
8850 (setq pos (js2-node-pos expr)
8851 end js2-token-end)
8852 (setq end (js2-node-end expr)))
8853 (setq pn (make-js2-unary-node :type type
8854 :pos pos
8855 :len (- end pos)
8856 :operand expr))
8857 (js2-node-add-children pn expr)
8858 pn))
8859
8860 (defconst js2-incrementable-node-types
8861 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8862 "Node types that can be the operand of a ++ or -- operator.")
8863
8864 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8865 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8866 js2-incrementable-node-types)
8867 (js2-report-error (if (= tt js2-INC)
8868 "msg.bad.incr"
8869 "msg.bad.decr")
8870 nil beg (- end beg))))
8871
8872 (defun js2-parse-unary-expr ()
8873 (let ((tt (js2-peek-token))
8874 pn expr beg end)
8875 (cond
8876 ((or (= tt js2-VOID)
8877 (= tt js2-NOT)
8878 (= tt js2-BITNOT)
8879 (= tt js2-TYPEOF))
8880 (js2-consume-token)
8881 (js2-make-unary tt 'js2-parse-unary-expr))
8882 ((= tt js2-ADD)
8883 (js2-consume-token)
8884 ;; Convert to special POS token in decompiler and parse tree
8885 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8886 ((= tt js2-SUB)
8887 (js2-consume-token)
8888 ;; Convert to special NEG token in decompiler and parse tree
8889 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8890 ((or (= tt js2-INC)
8891 (= tt js2-DEC))
8892 (js2-consume-token)
8893 (prog1
8894 (setq beg js2-token-beg
8895 end js2-token-end
8896 expr (js2-make-unary tt 'js2-parse-member-expr t))
8897 (js2-check-bad-inc-dec tt beg end expr)))
8898 ((= tt js2-DELPROP)
8899 (js2-consume-token)
8900 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8901 ((= tt js2-ERROR)
8902 (js2-consume-token)
8903 (make-js2-error-node)) ; try to continue
8904 ((and (= tt js2-LT)
8905 js2-compiler-xml-available)
8906 ;; XML stream encountered in expression.
8907 (js2-consume-token)
8908 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8909 (t
8910 (setq pn (js2-parse-member-expr t)
8911 ;; Don't look across a newline boundary for a postfix incop.
8912 tt (js2-peek-token-or-eol))
8913 (when (or (= tt js2-INC) (= tt js2-DEC))
8914 (js2-consume-token)
8915 (setf expr pn
8916 pn (js2-make-unary tt expr))
8917 (js2-node-set-prop pn 'postfix t)
8918 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8919 pn))))
8920
8921 (defun js2-parse-xml-initializer ()
8922 "Parse an E4X XML initializer.
8923 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8924 Then I'll postprocess the result, depending on whether we're in IDE
8925 mode or codegen mode, and generate the appropriate rewritten AST.
8926 IDE mode uses a rich AST that models the XML structure. Codegen mode
8927 just concatenates everything and makes a new XML or XMLList out of it."
8928 (let ((tt (js2-get-first-xml-token))
8929 pn-xml
8930 pn
8931 expr
8932 kids
8933 expr-pos
8934 (continue t)
8935 (first-token t))
8936 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8937 (js2-report-error "msg.syntax"))
8938 (setq pn-xml (make-js2-xml-node))
8939 (while continue
8940 (if first-token
8941 (setq first-token nil)
8942 (setq tt (js2-get-next-xml-token)))
8943 (cond
8944 ;; js2-XML means we found a {expr} in the XML stream.
8945 ;; The js2-ts-string is the XML up to the left-curly.
8946 ((= tt js2-XML)
8947 (push (make-js2-string-node :pos js2-token-beg
8948 :len (- js2-ts-cursor js2-token-beg))
8949 kids)
8950 (js2-must-match js2-LC "msg.syntax")
8951 (setq expr-pos js2-ts-cursor
8952 expr (if (eq (js2-peek-token) js2-RC)
8953 (make-js2-empty-expr-node :pos expr-pos)
8954 (js2-parse-expr)))
8955 (js2-must-match js2-RC "msg.syntax")
8956 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8957 :len (js2-node-len expr)
8958 :expr expr))
8959 (js2-node-add-children pn expr)
8960 (push pn kids))
8961 ;; a js2-XMLEND token means we hit the final close-tag.
8962 ((= tt js2-XMLEND)
8963 (push (make-js2-string-node :pos js2-token-beg
8964 :len (- js2-ts-cursor js2-token-beg))
8965 kids)
8966 (dolist (kid (nreverse kids))
8967 (js2-block-node-push pn-xml kid))
8968 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8969 (js2-node-pos pn-xml))
8970 continue nil))
8971 (t
8972 (js2-report-error "msg.syntax")
8973 (setq continue nil))))
8974 pn-xml))
8975
8976
8977 (defun js2-parse-argument-list ()
8978 "Parse an argument list and return it as a lisp list of nodes.
8979 Returns the list in reverse order. Consumes the right-paren token."
8980 (let (result)
8981 (unless (js2-match-token js2-RP)
8982 (loop do
8983 (if (= (js2-peek-token) js2-YIELD)
8984 (js2-report-error "msg.yield.parenthesized"))
8985 (push (js2-parse-assign-expr) result)
8986 while
8987 (js2-match-token js2-COMMA))
8988 (js2-must-match js2-RP "msg.no.paren.arg")
8989 result)))
8990
8991 (defun js2-parse-member-expr (&optional allow-call-syntax)
8992 (let ((tt (js2-peek-token))
8993 pn
8994 pos
8995 target
8996 args
8997 beg
8998 end
8999 init
9000 tail)
9001 (if (/= tt js2-NEW)
9002 (setq pn (js2-parse-primary-expr))
9003 ;; parse a 'new' expression
9004 (js2-consume-token)
9005 (setq pos js2-token-beg
9006 beg pos
9007 target (js2-parse-member-expr)
9008 end (js2-node-end target)
9009 pn (make-js2-new-node :pos pos
9010 :target target
9011 :len (- end pos)))
9012 (js2-node-add-children pn target)
9013 (when (js2-match-token js2-LP)
9014 ;; Add the arguments to pn, if any are supplied.
9015 (setf beg pos ; start of "new" keyword
9016 pos js2-token-beg
9017 args (nreverse (js2-parse-argument-list))
9018 (js2-new-node-args pn) args
9019 end js2-token-end
9020 (js2-new-node-lp pn) (- pos beg)
9021 (js2-new-node-rp pn) (- end 1 beg))
9022 (apply #'js2-node-add-children pn args))
9023 (when (and js2-allow-rhino-new-expr-initializer
9024 (js2-match-token js2-LC))
9025 (setf init (js2-parse-object-literal)
9026 end (js2-node-end init)
9027 (js2-new-node-initializer pn) init)
9028 (js2-node-add-children pn init))
9029 (setf (js2-node-len pn) (- end beg))) ; end outer if
9030 (js2-parse-member-expr-tail allow-call-syntax pn)))
9031
9032 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9033 "Parse a chain of property/array accesses or function calls.
9034 Includes parsing for E4X operators like `..' and `.@'.
9035 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9036 Returns an expression tree that includes PN, the parent node."
9037 (let ((beg (js2-node-pos pn))
9038 tt
9039 (continue t))
9040 (while continue
9041 (setq tt (js2-peek-token))
9042 (cond
9043 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9044 (setq pn (js2-parse-property-access tt pn)))
9045 ((= tt js2-DOTQUERY)
9046 (setq pn (js2-parse-dot-query pn)))
9047 ((= tt js2-LB)
9048 (setq pn (js2-parse-element-get pn)))
9049 ((= tt js2-LP)
9050 (if allow-call-syntax
9051 (setq pn (js2-parse-function-call pn))
9052 (setq continue nil)))
9053 (t
9054 (setq continue nil))))
9055 (if (>= js2-highlight-level 2)
9056 (js2-parse-highlight-member-expr-node pn))
9057 pn))
9058
9059 (defun js2-parse-dot-query (pn)
9060 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9061 Last token parsed must be `js2-DOTQUERY'."
9062 (let ((pos (js2-node-pos pn))
9063 op-pos
9064 expr
9065 end)
9066 (js2-consume-token)
9067 (js2-must-have-xml)
9068 (js2-set-requires-activation)
9069 (setq op-pos js2-token-beg
9070 expr (js2-parse-expr)
9071 end (js2-node-end expr)
9072 pn (make-js2-xml-dot-query-node :left pn
9073 :pos pos
9074 :op-pos op-pos
9075 :right expr))
9076 (js2-node-add-children pn
9077 (js2-xml-dot-query-node-left pn)
9078 (js2-xml-dot-query-node-right pn))
9079 (if (js2-must-match js2-RP "msg.no.paren")
9080 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9081 end js2-token-end))
9082 (setf (js2-node-len pn) (- end pos))
9083 pn))
9084
9085 (defun js2-parse-element-get (pn)
9086 "Parse an element-get expression, e.g. foo[bar].
9087 Last token parsed must be `js2-RB'."
9088 (let ((lb js2-token-beg)
9089 (pos (js2-node-pos pn))
9090 rb
9091 expr)
9092 (js2-consume-token)
9093 (setq expr (js2-parse-expr))
9094 (if (js2-must-match js2-RB "msg.no.bracket.index")
9095 (setq rb js2-token-beg))
9096 (setq pn (make-js2-elem-get-node :target pn
9097 :pos pos
9098 :element expr
9099 :lb (js2-relpos lb pos)
9100 :rb (js2-relpos rb pos)
9101 :len (- js2-token-end pos)))
9102 (js2-node-add-children pn
9103 (js2-elem-get-node-target pn)
9104 (js2-elem-get-node-element pn))
9105 pn))
9106
9107 (defun js2-parse-function-call (pn)
9108 (let (args
9109 (pos (js2-node-pos pn)))
9110 (js2-consume-token)
9111 (setq pn (make-js2-call-node :pos pos
9112 :target pn
9113 :lp (- js2-token-beg pos)))
9114 (js2-node-add-children pn (js2-call-node-target pn))
9115 ;; Add the arguments to pn, if any are supplied.
9116 (setf args (nreverse (js2-parse-argument-list))
9117 (js2-call-node-rp pn) (- js2-token-beg pos)
9118 (js2-call-node-args pn) args)
9119 (apply #'js2-node-add-children pn args)
9120 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9121 pn))
9122
9123 (defun js2-parse-property-access (tt pn)
9124 "Parse a property access, XML descendants access, or XML attr access."
9125 (let ((member-type-flags 0)
9126 (dot-pos js2-token-beg)
9127 (dot-len (if (= tt js2-DOTDOT) 2 1))
9128 name
9129 ref ; right side of . or .. operator
9130 result)
9131 (js2-consume-token)
9132 (when (= tt js2-DOTDOT)
9133 (js2-must-have-xml)
9134 (setq member-type-flags js2-descendants-flag))
9135 (if (not js2-compiler-xml-available)
9136 (progn
9137 (js2-must-match-prop-name "msg.no.name.after.dot")
9138 (setq name (js2-create-name-node t js2-GETPROP)
9139 result (make-js2-prop-get-node :left pn
9140 :pos js2-token-beg
9141 :right name
9142 :len (- js2-token-end
9143 js2-token-beg)))
9144 (js2-node-add-children result pn name)
9145 result)
9146 ;; otherwise look for XML operators
9147 (setf result (if (= tt js2-DOT)
9148 (make-js2-prop-get-node)
9149 (make-js2-infix-node :type js2-DOTDOT))
9150 (js2-node-pos result) (js2-node-pos pn)
9151 (js2-infix-node-op-pos result) dot-pos
9152 (js2-infix-node-left result) pn ; do this after setting position
9153 tt (js2-next-token))
9154 (cond
9155 ;; needed for generator.throw()
9156 ((= tt js2-THROW)
9157 (js2-save-name-token-data js2-token-beg "throw")
9158 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9159 ;; handles: name, ns::name, ns::*, ns::[expr]
9160 ((js2-valid-prop-name-token tt)
9161 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9162 ;; handles: *, *::name, *::*, *::[expr]
9163 ((= tt js2-MUL)
9164 (js2-save-name-token-data js2-token-beg "*")
9165 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9166 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9167 ((= tt js2-XMLATTR)
9168 (setq result (js2-parse-attribute-access)))
9169 (t
9170 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9171 (if ref
9172 (setf (js2-node-len result) (- (js2-node-end ref)
9173 (js2-node-pos result))
9174 (js2-infix-node-right result) ref))
9175 (if (js2-infix-node-p result)
9176 (js2-node-add-children result
9177 (js2-infix-node-left result)
9178 (js2-infix-node-right result)))
9179 result)))
9180
9181 (defun js2-parse-attribute-access ()
9182 "Parse an E4X XML attribute expression.
9183 This includes expressions of the forms:
9184
9185 @attr @ns::attr @ns::*
9186 @* @*::attr @*::*
9187 @[expr] @*::[expr] @ns::[expr]
9188
9189 Called if we peeked an '@' token."
9190 (let ((tt (js2-next-token))
9191 (at-pos js2-token-beg))
9192 (cond
9193 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9194 ((js2-valid-prop-name-token tt)
9195 (js2-parse-property-name at-pos js2-ts-string 0))
9196 ;; handles: @*, @*::name, @*::*, @*::[expr]
9197 ((= tt js2-MUL)
9198 (js2-save-name-token-data js2-token-beg "*")
9199 (js2-parse-property-name js2-token-beg "*" 0))
9200 ;; handles @[expr]
9201 ((= tt js2-LB)
9202 (js2-parse-xml-elem-ref at-pos))
9203 (t
9204 (js2-report-error "msg.no.name.after.xmlAttr")
9205 ;; Avoid cascaded errors that happen if we make an error node here.
9206 (js2-save-name-token-data js2-token-beg "")
9207 (js2-parse-property-name js2-token-beg "" 0)))))
9208
9209 (defun js2-parse-property-name (at-pos s member-type-flags)
9210 "Check if :: follows name in which case it becomes qualified name.
9211
9212 AT-POS is a natural number if we just read an '@' token, else nil.
9213 S is the name or string that was matched: an identifier, 'throw' or '*'.
9214 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9215
9216 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9217 operator, or the name is followed by ::. For a plain name, returns a
9218 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9219 (let ((pos (or at-pos js2-token-beg))
9220 colon-pos
9221 (name (js2-create-name-node t js2-current-token))
9222 ns
9223 tt
9224 ref
9225 pn)
9226 (catch 'return
9227 (when (js2-match-token js2-COLONCOLON)
9228 (setq ns name
9229 colon-pos js2-token-beg
9230 tt (js2-next-token))
9231 (cond
9232 ;; handles name::name
9233 ((js2-valid-prop-name-token tt)
9234 (setq name (js2-create-name-node)))
9235 ;; handles name::*
9236 ((= tt js2-MUL)
9237 (js2-save-name-token-data js2-token-beg "*")
9238 (setq name (js2-create-name-node)))
9239 ;; handles name::[expr]
9240 ((= tt js2-LB)
9241 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9242 (t
9243 (js2-report-error "msg.no.name.after.coloncolon"))))
9244 (if (and (null ns) (zerop member-type-flags))
9245 name
9246 (prog1
9247 (setq pn
9248 (make-js2-xml-prop-ref-node :pos pos
9249 :len (- (js2-node-end name) pos)
9250 :at-pos at-pos
9251 :colon-pos colon-pos
9252 :propname name))
9253 (js2-node-add-children pn name))))))
9254
9255 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9256 "Parse the [expr] portion of an xml element reference.
9257 For instance, @[expr], @*::[expr], or ns::[expr]."
9258 (let* ((lb js2-token-beg)
9259 (pos (or at-pos lb))
9260 rb
9261 (expr (js2-parse-expr))
9262 (end (js2-node-end expr))
9263 pn)
9264 (if (js2-must-match js2-RB "msg.no.bracket.index")
9265 (setq rb js2-token-beg
9266 end js2-token-end))
9267 (prog1
9268 (setq pn
9269 (make-js2-xml-elem-ref-node :pos pos
9270 :len (- end pos)
9271 :namespace namespace
9272 :colon-pos colon-pos
9273 :at-pos at-pos
9274 :expr expr
9275 :lb (js2-relpos lb pos)
9276 :rb (js2-relpos rb pos)))
9277 (js2-node-add-children pn namespace expr))))
9278
9279 (defsubst js2-parse-primary-expr-lhs ()
9280 (let ((js2-is-in-lhs t))
9281 (js2-parse-primary-expr)))
9282
9283 (defun js2-parse-primary-expr ()
9284 "Parses a literal (leaf) expression of some sort.
9285 Includes complex literals such as functions, object-literals,
9286 array-literals, array comprehensions and regular expressions."
9287 (let ((tt-flagged (js2-next-flagged-token))
9288 pn ; parent node (usually return value)
9289 tt
9290 px-pos ; paren-expr pos
9291 len
9292 flags ; regexp flags
9293 expr)
9294 (setq tt js2-current-token)
9295 (cond
9296 ((= tt js2-FUNCTION)
9297 (js2-parse-function 'FUNCTION_EXPRESSION))
9298 ((= tt js2-LB)
9299 (js2-parse-array-literal))
9300 ((= tt js2-LC)
9301 (js2-parse-object-literal))
9302 ((= tt js2-LET)
9303 (js2-parse-let js2-token-beg))
9304 ((= tt js2-LP)
9305 (setq px-pos js2-token-beg
9306 expr (js2-parse-expr))
9307 (js2-must-match js2-RP "msg.no.paren")
9308 (setq pn (make-js2-paren-node :pos px-pos
9309 :expr expr
9310 :len (- js2-token-end px-pos)))
9311 (js2-node-add-children pn (js2-paren-node-expr pn))
9312 pn)
9313 ((= tt js2-XMLATTR)
9314 (js2-must-have-xml)
9315 (js2-parse-attribute-access))
9316 ((= tt js2-NAME)
9317 (js2-parse-name tt-flagged tt))
9318 ((= tt js2-NUMBER)
9319 (make-js2-number-node))
9320 ((= tt js2-STRING)
9321 (prog1
9322 (make-js2-string-node)
9323 (js2-record-face 'font-lock-string-face)))
9324 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9325 ;; Got / or /= which in this context means a regexp literal
9326 (setq px-pos js2-token-beg)
9327 (js2-read-regexp tt)
9328 (setq flags js2-ts-regexp-flags
9329 js2-ts-regexp-flags nil)
9330 (prog1
9331 (make-js2-regexp-node :pos px-pos
9332 :len (- js2-ts-cursor px-pos)
9333 :value js2-ts-string
9334 :flags flags)
9335 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9336 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9337 ((or (= tt js2-NULL)
9338 (= tt js2-THIS)
9339 (= tt js2-FALSE)
9340 (= tt js2-TRUE))
9341 (make-js2-keyword-node :type tt))
9342 ((= tt js2-RESERVED)
9343 (js2-report-error "msg.reserved.id")
9344 (make-js2-name-node))
9345 ((= tt js2-ERROR)
9346 ;; the scanner or one of its subroutines reported the error.
9347 (make-js2-error-node))
9348 ((= tt js2-EOF)
9349 (setq px-pos (point-at-bol)
9350 len (- js2-ts-cursor px-pos))
9351 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9352 (make-js2-error-node :pos px-pos :len len))
9353 (t
9354 (js2-report-error "msg.syntax")
9355 (make-js2-error-node)))))
9356
9357 (defun js2-parse-name (tt-flagged tt)
9358 (let ((name js2-ts-string)
9359 (name-pos js2-token-beg)
9360 node)
9361 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9362 (= (js2-peek-token) js2-COLON))
9363 (prog1
9364 ;; Do not consume colon, it is used as unwind indicator
9365 ;; to return to statementHelper.
9366 (make-js2-label-node :pos name-pos
9367 :len (- js2-token-end name-pos)
9368 :name name)
9369 (js2-set-face name-pos
9370 js2-token-end
9371 'font-lock-variable-name-face 'record))
9372 ;; Otherwise not a label, just a name. Unfortunately peeking
9373 ;; the next token to check for a colon has biffed js2-token-beg
9374 ;; and js2-token-end. We store the name's bounds in buffer vars
9375 ;; and `js2-create-name-node' uses them.
9376 (js2-save-name-token-data name-pos name)
9377 (setq node (if js2-compiler-xml-available
9378 (js2-parse-property-name nil name 0)
9379 (js2-create-name-node 'check-activation)))
9380 (if js2-highlight-external-variables
9381 (js2-record-name-node node))
9382 node)))
9383
9384 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9385 (js2-add-strict-warning
9386 msg nil
9387 ;; back up from comma to beginning of line or array/objlit
9388 (max (if elems
9389 (js2-node-pos (car elems))
9390 pos)
9391 (save-excursion
9392 (goto-char comma-pos)
9393 (back-to-indentation)
9394 (point)))
9395 comma-pos))
9396
9397 (defun js2-parse-array-literal ()
9398 (let ((pos js2-token-beg)
9399 (end js2-token-end)
9400 (after-lb-or-comma t)
9401 after-comma
9402 tt
9403 elems
9404 pn
9405 (continue t))
9406 (unless js2-is-in-lhs
9407 (js2-push-scope (make-js2-scope))) ; for array comp
9408 (while continue
9409 (setq tt (js2-peek-token))
9410 (cond
9411 ;; comma
9412 ((= tt js2-COMMA)
9413 (js2-consume-token)
9414 (setq after-comma js2-token-end)
9415 (if (not after-lb-or-comma)
9416 (setq after-lb-or-comma t)
9417 (push nil elems)))
9418 ;; end of array
9419 ((or (= tt js2-RB)
9420 (= tt js2-EOF)) ; prevent infinite loop
9421 (if (= tt js2-EOF)
9422 (js2-report-error "msg.no.bracket.arg" nil pos)
9423 (js2-consume-token))
9424 (setq continue nil
9425 end js2-token-end
9426 pn (make-js2-array-node :pos pos
9427 :len (- js2-ts-cursor pos)
9428 :elems (nreverse elems)))
9429 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9430 (when (and after-comma (not js2-is-in-lhs))
9431 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9432 pos elems after-comma)))
9433 ;; destructuring binding
9434 (js2-is-in-lhs
9435 (push (if (or (= tt js2-LC)
9436 (= tt js2-LB)
9437 (= tt js2-NAME))
9438 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9439 (js2-parse-primary-expr-lhs)
9440 ;; invalid pattern
9441 (js2-consume-token)
9442 (js2-report-error "msg.bad.var")
9443 (make-js2-error-node))
9444 elems)
9445 (setq after-lb-or-comma nil
9446 after-comma nil))
9447 ;; array comp
9448 ((and (>= js2-language-version 170)
9449 (= tt js2-FOR) ; check for array comprehension
9450 (not after-lb-or-comma) ; "for" can't follow a comma
9451 elems ; must have at least 1 element
9452 (not (cdr elems))) ; but no 2nd element
9453 (setf continue nil
9454 pn (js2-parse-array-comprehension (car elems) pos)))
9455
9456 ;; another element
9457 (t
9458 (unless after-lb-or-comma
9459 (js2-report-error "msg.no.bracket.arg"))
9460 (push (js2-parse-assign-expr) elems)
9461 (setq after-lb-or-comma nil
9462 after-comma nil))))
9463 (unless js2-is-in-lhs
9464 (js2-pop-scope))
9465 pn))
9466
9467 (defun js2-parse-array-comprehension (expr pos)
9468 "Parse a JavaScript 1.7 Array Comprehension.
9469 EXPR is the first expression after the opening left-bracket.
9470 POS is the beginning of the LB token preceding EXPR.
9471 We should have just parsed the 'for' keyword before calling this function."
9472 (let (loops
9473 loop
9474 first
9475 prev
9476 filter
9477 if-pos
9478 result)
9479 (while (= (js2-peek-token) js2-FOR)
9480 (let ((prev (car loops))) ; rearrange scope chain
9481 (push (setq loop (js2-parse-array-comp-loop)) loops)
9482 (if prev ; each loop is parent scope to the next one
9483 (setf (js2-scope-parent-scope loop) prev)
9484 ; first loop takes expr scope's parent
9485 (setf (js2-scope-parent-scope (setq first loop))
9486 (js2-scope-parent-scope js2-current-scope)))))
9487 ;; set expr scope's parent to the last loop
9488 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9489 (when (= (js2-peek-token) js2-IF)
9490 (js2-consume-token)
9491 (setq if-pos (- js2-token-beg pos) ; relative
9492 filter (js2-parse-condition)))
9493 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9494 (setq result (make-js2-array-comp-node :pos pos
9495 :len (- js2-ts-cursor pos)
9496 :result expr
9497 :loops (nreverse loops)
9498 :filter (car filter)
9499 :lp (js2-relpos (second filter) pos)
9500 :rp (js2-relpos (third filter) pos)
9501 :if-pos if-pos))
9502 (apply #'js2-node-add-children result expr (car filter)
9503 (js2-array-comp-node-loops result))
9504 (setq js2-current-scope first) ; pop to the first loop
9505 result))
9506
9507 (defun js2-parse-array-comp-loop ()
9508 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9509 Last token peeked should be the initial FOR."
9510 (let ((pos js2-token-beg)
9511 (pn (make-js2-array-comp-loop-node))
9512 tt
9513 iter
9514 obj
9515 foreach-p
9516 in-pos
9517 each-pos
9518 lp
9519 rp)
9520 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9521 (js2-push-scope pn)
9522 (unwind-protect
9523 (progn
9524 (when (js2-match-token js2-NAME)
9525 (if (string= js2-ts-string "each")
9526 (progn
9527 (setq foreach-p t
9528 each-pos (- js2-token-beg pos)) ; relative
9529 (js2-record-face 'font-lock-keyword-face))
9530 (js2-report-error "msg.no.paren.for")))
9531 (if (js2-must-match js2-LP "msg.no.paren.for")
9532 (setq lp (- js2-token-beg pos)))
9533 (setq tt (js2-peek-token))
9534 (cond
9535 ((or (= tt js2-LB)
9536 (= tt js2-LC))
9537 ;; handle destructuring assignment
9538 (setq iter (js2-parse-primary-expr-lhs))
9539 (js2-define-destruct-symbols iter js2-LET
9540 'font-lock-variable-name-face t))
9541 ((js2-valid-prop-name-token tt)
9542 (js2-consume-token)
9543 (setq iter (js2-create-name-node)))
9544 (t
9545 (js2-report-error "msg.bad.var")))
9546 ;; Define as a let since we want the scope of the variable to
9547 ;; be restricted to the array comprehension
9548 (if (js2-name-node-p iter)
9549 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9550 (if (js2-must-match js2-IN "msg.in.after.for.name")
9551 (setq in-pos (- js2-token-beg pos)))
9552 (setq obj (js2-parse-expr))
9553 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9554 (setq rp (- js2-token-beg pos)))
9555 (setf (js2-node-pos pn) pos
9556 (js2-node-len pn) (- js2-ts-cursor pos)
9557 (js2-array-comp-loop-node-iterator pn) iter
9558 (js2-array-comp-loop-node-object pn) obj
9559 (js2-array-comp-loop-node-in-pos pn) in-pos
9560 (js2-array-comp-loop-node-each-pos pn) each-pos
9561 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9562 (js2-array-comp-loop-node-lp pn) lp
9563 (js2-array-comp-loop-node-rp pn) rp)
9564 (js2-node-add-children pn iter obj))
9565 (js2-pop-scope))
9566 pn))
9567
9568 (defun js2-parse-object-literal ()
9569 (let ((pos js2-token-beg)
9570 tt
9571 elems
9572 result
9573 after-comma
9574 (continue t))
9575 (while continue
9576 (setq tt (js2-peek-token))
9577 (cond
9578 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9579 ((or (js2-valid-prop-name-token tt)
9580 (= tt js2-STRING))
9581 (setq after-comma nil
9582 result (js2-parse-named-prop tt))
9583 (if (and (null result)
9584 (not js2-recover-from-parse-errors))
9585 (setq continue nil)
9586 (push result elems)))
9587 ;; {12: x} or {10.7: x}
9588 ((= tt js2-NUMBER)
9589 (js2-consume-token)
9590 (setq after-comma nil)
9591 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9592 ;; trailing comma
9593 ((= tt js2-RC)
9594 (setq continue nil)
9595 (if after-comma
9596 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9597 pos elems after-comma)))
9598 (t
9599 (js2-report-error "msg.bad.prop")
9600 (unless js2-recover-from-parse-errors
9601 (setq continue nil)))) ; end switch
9602 (if (js2-match-token js2-COMMA)
9603 (setq after-comma js2-token-end)
9604 (setq continue nil))) ; end loop
9605 (js2-must-match js2-RC "msg.no.brace.prop")
9606 (setq result (make-js2-object-node :pos pos
9607 :len (- js2-ts-cursor pos)
9608 :elems (nreverse elems)))
9609 (apply #'js2-node-add-children result (js2-object-node-elems result))
9610 result))
9611
9612 (defun js2-parse-named-prop (tt)
9613 "Parse a name, string, or getter/setter object property.
9614 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9615 (js2-consume-token)
9616 (let ((string-prop (and (= tt js2-STRING)
9617 (make-js2-string-node)))
9618 expr
9619 (ppos js2-token-beg)
9620 (pend js2-token-end)
9621 (name (js2-create-name-node))
9622 (prop js2-ts-string))
9623 (cond
9624 ;; getter/setter prop
9625 ((and (= tt js2-NAME)
9626 (= (js2-peek-token) js2-NAME)
9627 (or (string= prop "get")
9628 (string= prop "set")))
9629 (js2-consume-token)
9630 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9631 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9632 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9633 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9634 ;; abbreviated destructuring bind e.g., {a, b} = c;
9635 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9636 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9637 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9638 ;; assignment but it's difficult because it requires looking ahead of expression.
9639 ((and js2-is-in-lhs
9640 (= tt js2-NAME)
9641 (let ((ctk (js2-peek-token)))
9642 (or (= ctk js2-COMMA)
9643 (= ctk js2-RC)
9644 (js2-valid-prop-name-token ctk))))
9645 name)
9646 ;; regular prop
9647 (t
9648 (prog1
9649 (setq expr (js2-parse-plain-property (or string-prop name)))
9650 (js2-set-face ppos pend
9651 (if (js2-function-node-p
9652 (js2-object-prop-node-right expr))
9653 'font-lock-function-name-face
9654 'font-lock-variable-name-face)
9655 'record))))))
9656
9657 (defun js2-parse-plain-property (prop)
9658 "Parse a non-getter/setter property in an object literal.
9659 PROP is the node representing the property: a number, name or string."
9660 (js2-must-match js2-COLON "msg.no.colon.prop")
9661 (let* ((pos (js2-node-pos prop))
9662 (colon (- js2-token-beg pos))
9663 (expr (js2-parse-assign-expr))
9664 (result (make-js2-object-prop-node
9665 :pos pos
9666 ;; don't include last consumed token in length
9667 :len (- (+ (js2-node-pos expr)
9668 (js2-node-len expr))
9669 pos)
9670 :left prop
9671 :right expr
9672 :op-pos colon)))
9673 (js2-node-add-children result prop expr)
9674 result))
9675
9676 (defun js2-parse-getter-setter-prop (pos prop get-p)
9677 "Parse getter or setter property in an object literal.
9678 JavaScript syntax is:
9679
9680 { get foo() {...}, set foo(x) {...} }
9681
9682 and expression closure style is also supported
9683
9684 { get foo() x, set foo(x) _x = x }
9685
9686 POS is the start position of the `get' or `set' keyword.
9687 PROP is the `js2-name-node' representing the property name.
9688 GET-P is non-nil if the keyword was `get'."
9689 (let ((type (if get-p js2-GET js2-SET))
9690 result
9691 end
9692 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9693 ;; it has to be an anonymous function, as we already parsed the name
9694 (if (/= (js2-node-type fn) js2-FUNCTION)
9695 (js2-report-error "msg.bad.prop")
9696 (if (plusp (length (js2-function-name fn)))
9697 (js2-report-error "msg.bad.prop")))
9698 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9699 (setq end (js2-node-end fn)
9700 result (make-js2-getter-setter-node :type type
9701 :pos pos
9702 :len (- end pos)
9703 :left prop
9704 :right fn))
9705 (js2-node-add-children result prop fn)
9706 result))
9707
9708 (defun js2-create-name-node (&optional check-activation-p token)
9709 "Create a name node using the token info from last scanned name.
9710 In some cases we need to either synthesize a name node, or we lost
9711 the name token information by peeking. If the TOKEN parameter is
9712 not `js2-NAME', then we use the token info saved in instance vars."
9713 (let ((beg js2-token-beg)
9714 (s js2-ts-string)
9715 name)
9716 (when (/= js2-current-token js2-NAME)
9717 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9718 s js2-prev-name-token-string
9719 js2-prev-name-token-start nil
9720 js2-prev-name-token-string nil))
9721 (setq name (make-js2-name-node :pos beg
9722 :name s
9723 :len (length s)))
9724 (if check-activation-p
9725 (js2-check-activation-name s (or token js2-NAME)))
9726 name))
9727
9728 ;;; Indentation support
9729
9730 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9731 ;; Karl cleverly deduces that the desired indentation level is often a
9732 ;; function of paren/bracket/brace nesting depth, which can be determined
9733 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9734 ;; then does some equally clever checks to see if we're in the context of a
9735 ;; substatement of a possibly braceless statement keyword such as if, while,
9736 ;; or finally. This approach yields pretty good results.
9737
9738 ;; The indenter is often "wrong", however, and needs to be overridden.
9739 ;; The right long-term solution is probably to emulate (or integrate
9740 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9741 ;; parse tree from `js2-parse' is present, which is not true at the
9742 ;; moment the user is typing, computing indentation is still thousands
9743 ;; of lines of code to handle every possible syntactic edge case.
9744
9745 ;; In the meantime, the compromise solution is that we offer a "bounce
9746 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9747 ;; current line indent among various likely guess points. This approach
9748 ;; is far from perfect, but should at least make it slightly easier to
9749 ;; move the line towards its desired indentation when manually
9750 ;; overriding Karl's heuristic nesting guesser.
9751
9752 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9753 ;; extensions such as `let' and Array comprehensions. Major kudos to
9754 ;; Karl for coming up with the initial approach, which packs a lot of
9755 ;; punch for so little code.
9756
9757 (defconst js-possibly-braceless-keywords-re
9758 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9759 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9760 "try" "while" "with" "let")))
9761 "Regular expression matching keywords that are optionally
9762 followed by an opening brace.")
9763
9764 (defconst js-indent-operator-re
9765 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9766 (regexp-opt '("in" "instanceof") 'words))
9767 "Regular expression matching operators that affect indentation
9768 of continued expressions.")
9769
9770 (defconst js-declaration-keyword-re
9771 (regexp-opt '("var" "let" "const") 'words)
9772 "Regular expression matching variable declaration keywords.")
9773
9774 ;; This function has horrible results if you're typing an array
9775 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9776 ;; in conjunction with electric-indent, so just disabling it.
9777 (defsubst js2-code-at-bol-p ()
9778 "Return t if the first character on line is non-whitespace."
9779 nil)
9780
9781 (defun js2-insert-and-indent (key)
9782 "Run command bound to key and indent current line. Runs the command
9783 bound to KEY in the global keymap and indents the current line."
9784 (interactive (list (this-command-keys)))
9785 (let ((cmd (lookup-key (current-global-map) key)))
9786 (if (commandp cmd)
9787 (call-interactively cmd)))
9788 ;; don't do the electric keys inside comments or strings,
9789 ;; and don't do bounce-indent with them.
9790 (let ((parse-state (syntax-ppss (point)))
9791 (js2-bounce-indent-p (js2-code-at-bol-p)))
9792 (unless (or (nth 3 parse-state)
9793 (nth 4 parse-state))
9794 (indent-according-to-mode))))
9795
9796 (defun js-re-search-forward-inner (regexp &optional bound count)
9797 "Auxiliary function for `js-re-search-forward'."
9798 (let (parse saved-point)
9799 (while (> count 0)
9800 (re-search-forward regexp bound)
9801 (setq parse (if saved-point
9802 (parse-partial-sexp saved-point (point))
9803 (syntax-ppss (point))))
9804 (cond ((nth 3 parse)
9805 (re-search-forward
9806 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9807 (save-excursion (end-of-line) (point)) t))
9808 ((nth 7 parse)
9809 (forward-line))
9810 ((or (nth 4 parse)
9811 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9812 (re-search-forward "\\*/"))
9813 (t
9814 (setq count (1- count))))
9815 (setq saved-point (point))))
9816 (point))
9817
9818 (defun js-re-search-forward (regexp &optional bound noerror count)
9819 "Search forward but ignore strings and comments. Invokes
9820 `re-search-forward' but treats the buffer as if strings and
9821 comments have been removed."
9822 (let ((saved-point (point))
9823 (search-expr
9824 (cond ((null count)
9825 '(js-re-search-forward-inner regexp bound 1))
9826 ((< count 0)
9827 '(js-re-search-backward-inner regexp bound (- count)))
9828 ((> count 0)
9829 '(js-re-search-forward-inner regexp bound count)))))
9830 (condition-case err
9831 (eval search-expr)
9832 (search-failed
9833 (goto-char saved-point)
9834 (unless noerror
9835 (error (error-message-string err)))))))
9836
9837 (defun js-re-search-backward-inner (regexp &optional bound count)
9838 "Auxiliary function for `js-re-search-backward'."
9839 (let (parse saved-point)
9840 (while (> count 0)
9841 (re-search-backward regexp bound)
9842 (setq parse (if saved-point
9843 (parse-partial-sexp saved-point (point))
9844 (syntax-ppss (point))))
9845 (cond ((nth 3 parse)
9846 (re-search-backward
9847 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9848 (save-excursion (beginning-of-line) (point)) t))
9849 ((nth 7 parse)
9850 (goto-char (nth 8 parse)))
9851 ((or (nth 4 parse)
9852 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9853 (re-search-backward "/\\*"))
9854 (t
9855 (setq count (1- count))))))
9856 (point))
9857
9858 (defun js-re-search-backward (regexp &optional bound noerror count)
9859 "Search backward but ignore strings and comments. Invokes
9860 `re-search-backward' but treats the buffer as if strings and
9861 comments have been removed."
9862 (let ((saved-point (point))
9863 (search-expr
9864 (cond ((null count)
9865 '(js-re-search-backward-inner regexp bound 1))
9866 ((< count 0)
9867 '(js-re-search-forward-inner regexp bound (- count)))
9868 ((> count 0)
9869 '(js-re-search-backward-inner regexp bound count)))))
9870 (condition-case err
9871 (eval search-expr)
9872 (search-failed
9873 (goto-char saved-point)
9874 (unless noerror
9875 (error (error-message-string err)))))))
9876
9877 (defun js-looking-at-operator-p ()
9878 "Return non-nil if text after point is an operator (that is not
9879 a comma)."
9880 (save-match-data
9881 (and (looking-at js-indent-operator-re)
9882 (or (not (looking-at ":"))
9883 (save-excursion
9884 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9885 (looking-at "?")))))))
9886
9887 (defun js-continued-expression-p ()
9888 "Returns non-nil if the current line continues an expression."
9889 (save-excursion
9890 (back-to-indentation)
9891 (or (js-looking-at-operator-p)
9892 ;; comment
9893 (and (js-re-search-backward "\n" nil t)
9894 (progn
9895 (skip-chars-backward " \t")
9896 (backward-char)
9897 (and (js-looking-at-operator-p)
9898 (and (progn (backward-char)
9899 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9900
9901 (defun js-end-of-do-while-loop-p ()
9902 "Returns non-nil if word after point is `while' of a do-while
9903 statement, else returns nil. A braceless do-while statement
9904 spanning several lines requires that the start of the loop is
9905 indented to the same column as the current line."
9906 (interactive)
9907 (save-excursion
9908 (save-match-data
9909 (when (looking-at "\\s-*\\<while\\>")
9910 (if (save-excursion
9911 (skip-chars-backward "[ \t\n]*}")
9912 (looking-at "[ \t\n]*}"))
9913 (save-excursion
9914 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9915 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9916 (or (looking-at "\\<do\\>")
9917 (let ((saved-indent (current-indentation)))
9918 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9919 (/= (current-indentation) saved-indent)))
9920 (and (looking-at "[ \t]*\\<do\\>")
9921 (not (js-re-search-forward
9922 "\\<while\\>" (point-at-eol) t))
9923 (= (current-indentation) saved-indent)))))))))
9924
9925 (defun js-multiline-decl-indentation ()
9926 "Returns the declaration indentation column if the current line belongs
9927 to a multiline declaration statement. All declarations are lined up vertically:
9928
9929 var a = 10,
9930 b = 20,
9931 c = 30;
9932
9933 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9934 assigned expression is a function or array/object literal, it will be indented
9935 differently:
9936
9937 var o = { var bar = 2,
9938 foo: 3 o = {
9939 }, foo: 3
9940 bar = 2; };
9941 "
9942 (let (forward-sexp-function ; use lisp version
9943 at-opening-bracket)
9944 (save-excursion
9945 (back-to-indentation)
9946 (when (not (looking-at js-declaration-keyword-re))
9947 (when (looking-at js-indent-operator-re)
9948 (goto-char (match-end 0))) ; continued expressions are ok
9949 (while (and (not at-opening-bracket)
9950 (not (bobp))
9951 (let ((pos (point)))
9952 (save-excursion
9953 (js2-backward-sws)
9954 (or (eq (char-before) ?,)
9955 (and (not (eq (char-before) ?\;))
9956 (and
9957 (prog2 (skip-chars-backward "[[:punct:]]")
9958 (looking-at js-indent-operator-re)
9959 (js2-backward-sws))
9960 (not (eq (char-before) ?\;))))
9961 (js2-same-line pos)))))
9962 (condition-case err
9963 (backward-sexp)
9964 (scan-error (setq at-opening-bracket t))))
9965 (when (looking-at js-declaration-keyword-re)
9966 (- (1+ (match-end 0)) (point-at-bol)))))))
9967
9968 (defun js-ctrl-statement-indentation ()
9969 "Returns the proper indentation of the current line if it
9970 starts the body of a control statement without braces, else
9971 returns nil."
9972 (let (forward-sexp-function) ; temporarily unbind it
9973 (save-excursion
9974 (back-to-indentation)
9975 (when (and (not (js2-same-line (point-min)))
9976 (not (looking-at "{"))
9977 (js-re-search-backward "[[:graph:]]" nil t)
9978 (not (looking-at "[{([]"))
9979 (progn
9980 (forward-char)
9981 (when (= (char-before) ?\))
9982 ;; scan-sexps sometimes throws an error
9983 (ignore-errors (backward-sexp))
9984 (skip-chars-backward " \t" (point-at-bol)))
9985 (let ((pt (point)))
9986 (back-to-indentation)
9987 (and (looking-at js-possibly-braceless-keywords-re)
9988 (= (match-end 0) pt)
9989 (not (js-end-of-do-while-loop-p))))))
9990 (+ (current-indentation) js2-basic-offset)))))
9991
9992 (defun js2-indent-in-array-comp (parse-status)
9993 "Return non-nil if we think we're in an array comprehension.
9994 In particular, return the buffer position of the first `for' kwd."
9995 (let ((end (point)))
9996 (when (nth 1 parse-status)
9997 (save-excursion
9998 (goto-char (nth 1 parse-status))
9999 (when (looking-at "\\[")
10000 (forward-char 1)
10001 (js2-forward-sws)
10002 (if (looking-at "[[{]")
10003 (let (forward-sexp-function) ; use lisp version
10004 (forward-sexp) ; skip destructuring form
10005 (js2-forward-sws)
10006 (if (and (/= (char-after) ?,) ; regular array
10007 (looking-at "for"))
10008 (match-beginning 0)))
10009 ;; to skip arbitrary expressions we need the parser,
10010 ;; so we'll just guess at it.
10011 (if (and (> end (point)) ; not empty literal
10012 (re-search-forward "[^,]]* \\(for\\) " end t))
10013 (match-beginning 1))))))))
10014
10015 (defun js2-array-comp-indentation (parse-status for-kwd)
10016 (if (js2-same-line for-kwd)
10017 ;; first continuation line
10018 (save-excursion
10019 (goto-char (nth 1 parse-status))
10020 (forward-char 1)
10021 (skip-chars-forward " \t")
10022 (current-column))
10023 (save-excursion
10024 (goto-char for-kwd)
10025 (current-column))))
10026
10027 (defun js-proper-indentation (parse-status)
10028 "Return the proper indentation for the current line."
10029 (save-excursion
10030 (back-to-indentation)
10031 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10032 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10033 (continued-expr-p (js-continued-expression-p))
10034 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10035 (js-multiline-decl-indentation)))
10036 (bracket (nth 1 parse-status))
10037 beg)
10038 (cond
10039 ;; indent array comprehension continuation lines specially
10040 ((and bracket
10041 (not (js2-same-line bracket))
10042 (setq beg (js2-indent-in-array-comp parse-status))
10043 (>= (point) (save-excursion
10044 (goto-char beg)
10045 (point-at-bol)))) ; at or after first loop?
10046 (js2-array-comp-indentation parse-status beg))
10047
10048 (ctrl-stmt-indent)
10049
10050 ((and declaration-indent continued-expr-p)
10051 (+ declaration-indent js2-basic-offset))
10052
10053 (declaration-indent)
10054
10055 (bracket
10056 (goto-char bracket)
10057 (cond
10058 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10059 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10060 (when (save-excursion (skip-chars-backward " \t)")
10061 (looking-at ")"))
10062 (backward-list))
10063 (if (and (nth 1 p)
10064 (not js2-consistent-level-indent-inner-bracket-p))
10065 (progn (goto-char (1+ (nth 1 p)))
10066 (skip-chars-forward " \t"))
10067 (back-to-indentation)
10068 (when (and js2-pretty-multiline-decl-indentation-p
10069 js2-always-indent-assigned-expr-in-decls-p
10070 (looking-at js-declaration-keyword-re))
10071 (goto-char (1+ (match-end 0)))))
10072 (cond (same-indent-p
10073 (current-column))
10074 (continued-expr-p
10075 (+ (current-column) (* 2 js2-basic-offset)))
10076 (t
10077 (+ (current-column) js2-basic-offset)))))
10078 (t
10079 (unless same-indent-p
10080 (forward-char)
10081 (skip-chars-forward " \t"))
10082 (current-column))))
10083
10084 (continued-expr-p js2-basic-offset)
10085
10086 (t 0)))))
10087
10088 (defun js2-lineup-comment (parse-status)
10089 "Indent a multi-line block comment continuation line."
10090 (let* ((beg (nth 8 parse-status))
10091 (first-line (js2-same-line beg))
10092 (offset (save-excursion
10093 (goto-char beg)
10094 (if (looking-at "/\\*")
10095 (+ 1 (current-column))
10096 0))))
10097 (unless first-line
10098 (indent-line-to offset))))
10099
10100 (defun js2-backward-sws ()
10101 "Move backward through whitespace and comments."
10102 (interactive)
10103 (while (forward-comment -1)))
10104
10105 (defun js2-forward-sws ()
10106 "Move forward through whitespace and comments."
10107 (interactive)
10108 (while (forward-comment 1)))
10109
10110 (defsubst js2-current-indent (&optional pos)
10111 "Return column of indentation on current line.
10112 If POS is non-nil, go to that point and return indentation for that line."
10113 (save-excursion
10114 (if pos
10115 (goto-char pos))
10116 (back-to-indentation)
10117 (current-column)))
10118
10119 (defsubst js2-arglist-close ()
10120 "Return non-nil if we're on a line beginning with a close-paren/brace."
10121 (save-match-data
10122 (save-excursion
10123 (goto-char (point-at-bol))
10124 (js2-forward-sws)
10125 (looking-at "[])}]"))))
10126
10127 (defsubst js2-indent-looks-like-label-p ()
10128 (goto-char (point-at-bol))
10129 (js2-forward-sws)
10130 (looking-at (concat js2-mode-identifier-re ":")))
10131
10132 (defun js2-indent-in-objlit-p (parse-status)
10133 "Return non-nil if this looks like an object-literal entry."
10134 (let ((start (nth 1 parse-status)))
10135 (and
10136 start
10137 (save-excursion
10138 (and (zerop (forward-line -1))
10139 (not (< (point) start)) ; crossed a {} boundary
10140 (js2-indent-looks-like-label-p)))
10141 (save-excursion
10142 (js2-indent-looks-like-label-p)))))
10143
10144 ;; if prev line looks like foobar({ then we're passing an object
10145 ;; literal to a function call, and people pretty much always want to
10146 ;; de-dent back to the previous line, so move the 'basic-offset'
10147 ;; position to the front.
10148 (defsubst js2-indent-objlit-arg-p (parse-status)
10149 (save-excursion
10150 (back-to-indentation)
10151 (js2-backward-sws)
10152 (and (eq (1- (point)) (nth 1 parse-status))
10153 (eq (char-before) ?{)
10154 (progn
10155 (forward-char -1)
10156 (skip-chars-backward " \t")
10157 (eq (char-before) ?\()))))
10158
10159 (defsubst js2-indent-case-block-p ()
10160 (save-excursion
10161 (back-to-indentation)
10162 (js2-backward-sws)
10163 (goto-char (point-at-bol))
10164 (skip-chars-forward " \t")
10165 (save-match-data
10166 (looking-at "case\\s-.+:"))))
10167
10168 (defsubst js2-syntax-bol ()
10169 "Return the point at the first non-whitespace char on the line.
10170 Returns `point-at-bol' if the line is empty."
10171 (save-excursion
10172 (beginning-of-line)
10173 (skip-chars-forward " \t")
10174 (point)))
10175
10176 (defun js2-bounce-indent (normal-col parse-status backwards)
10177 "Cycle among alternate computed indentation positions.
10178 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10179 of the buffer to the current point. NORMAL-COL is the indentation
10180 column computed by the heuristic guesser based on current paren,
10181 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10182 in reverse."
10183 (let ((cur-indent (js2-current-indent))
10184 (old-buffer-undo-list buffer-undo-list)
10185 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10186 (current-line (save-excursion
10187 (forward-line 0) ; move to bol
10188 (1+ (count-lines (point-min) (point)))))
10189 positions
10190 pos
10191 main-pos
10192 anchor
10193 arglist-cont
10194 same-indent
10195 prev-line-col
10196 basic-offset
10197 computed-pos)
10198 ;; temporarily don't record undo info, if user requested this
10199 (if js2-mode-indent-inhibit-undo
10200 (setq buffer-undo-list t))
10201 (unwind-protect
10202 (progn
10203 ;; first likely point: indent from beginning of previous code line
10204 (push (setq basic-offset
10205 (+ (save-excursion
10206 (back-to-indentation)
10207 (js2-backward-sws)
10208 (back-to-indentation)
10209 (setq prev-line-col (current-column)))
10210 js2-basic-offset))
10211 positions)
10212
10213 ;; (first + epsilon) likely point: indent 2x from beginning of
10214 ;; previous code line. Some companies like this approach. Ahem.
10215 ;; Seriously, though -- 4-space indent for expression continuation
10216 ;; lines isn't a bad idea. We should eventually implement it
10217 ;; that way.
10218 (push (setq basic-offset
10219 (+ (save-excursion
10220 (back-to-indentation)
10221 (js2-backward-sws)
10222 (back-to-indentation)
10223 (setq prev-line-col (current-column)))
10224 (* 2 js2-basic-offset)))
10225 positions)
10226
10227 ;; second likely point: indent from assign-expr RHS. This
10228 ;; is just a crude guess based on finding " = " on the previous
10229 ;; line containing actual code.
10230 (setq pos (save-excursion
10231 (save-match-data
10232 (forward-line -1)
10233 (goto-char (point-at-bol))
10234 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10235 (point-at-eol) t)
10236 (goto-char (match-end 1))
10237 (skip-chars-forward " \t\r\n")
10238 (current-column)))))
10239 (when pos
10240 (incf pos js2-basic-offset)
10241 (push pos positions))
10242
10243 ;; third likely point: same indent as previous line of code.
10244 ;; Make it the first likely point if we're not on an
10245 ;; arglist-close line and previous line ends in a comma, or
10246 ;; both this line and prev line look like object-literal
10247 ;; elements.
10248 (setq pos (save-excursion
10249 (goto-char (point-at-bol))
10250 (js2-backward-sws)
10251 (back-to-indentation)
10252 (prog1
10253 (current-column)
10254 ;; while we're here, look for trailing comma
10255 (if (save-excursion
10256 (goto-char (point-at-eol))
10257 (js2-backward-sws)
10258 (eq (char-before) ?,))
10259 (setq arglist-cont (1- (point)))))))
10260 (when pos
10261 (if (and (or arglist-cont
10262 (js2-indent-in-objlit-p parse-status))
10263 (not (js2-arglist-close)))
10264 (setq same-indent pos))
10265 (push pos positions))
10266
10267 ;; fourth likely point: first preceding code with less indentation
10268 ;; than the immediately preceding code line.
10269 (setq pos (save-excursion
10270 (back-to-indentation)
10271 (js2-backward-sws)
10272 (back-to-indentation)
10273 (setq anchor (current-column))
10274 (while (and (zerop (forward-line -1))
10275 (>= (progn
10276 (back-to-indentation)
10277 (current-column))
10278 anchor)))
10279 (setq pos (current-column))))
10280 (push pos positions)
10281
10282 ;; nesting-heuristic position, main by default
10283 (push (setq main-pos normal-col) positions)
10284
10285 ;; delete duplicates and sort positions list
10286 (setq positions (sort (delete-dups positions) '<))
10287
10288 ;; comma-list continuation lines: prev line indent takes precedence
10289 (if same-indent
10290 (setq main-pos same-indent))
10291
10292 ;; common special cases where we want to indent in from previous line
10293 (if (or (js2-indent-case-block-p)
10294 (js2-indent-objlit-arg-p parse-status))
10295 (setq main-pos basic-offset))
10296
10297 ;; if bouncing backwards, reverse positions list
10298 (if backwards
10299 (setq positions (reverse positions)))
10300
10301 ;; record whether we're already sitting on one of the alternatives
10302 (setq pos (member cur-indent positions))
10303
10304 (cond
10305 ;; case 0: we're one one of the alternatives and this is the
10306 ;; first time they've pressed TAB on this line (best-guess).
10307 ((and js2-mode-indent-ignore-first-tab
10308 pos
10309 ;; first time pressing TAB on this line?
10310 (not (eq js2-mode-last-indented-line current-line)))
10311 ;; do nothing
10312 (setq computed-pos nil))
10313 ;; case 1: only one computed position => use it
10314 ((null (cdr positions))
10315 (setq computed-pos 0))
10316 ;; case 2: not on any of the computed spots => use main spot
10317 ((not pos)
10318 (setq computed-pos (js2-position main-pos positions)))
10319 ;; case 3: on last position: cycle to first position
10320 ((null (cdr pos))
10321 (setq computed-pos 0))
10322 ;; case 4: on intermediate position: cycle to next position
10323 (t
10324 (setq computed-pos (js2-position (second pos) positions))))
10325
10326 ;; see if any hooks want to indent; otherwise we do it
10327 (loop with result = nil
10328 for hook in js2-indent-hook
10329 while (null result)
10330 do
10331 (setq result (funcall hook positions computed-pos))
10332 finally do
10333 (unless (or result (null computed-pos))
10334 (indent-line-to (nth computed-pos positions)))))
10335
10336 ;; finally
10337 (if js2-mode-indent-inhibit-undo
10338 (setq buffer-undo-list old-buffer-undo-list))
10339 ;; see commentary for `js2-mode-last-indented-line'
10340 (setq js2-mode-last-indented-line current-line))))
10341
10342 (defun js2-indent-bounce-backwards ()
10343 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10344 cycles between the computed indentation positions in reverse order."
10345 (interactive)
10346 (js2-indent-line t))
10347
10348 (defsubst js2-1-line-comment-continuation-p ()
10349 "Return t if we're in a 1-line comment continuation.
10350 If so, we don't ever want to use bounce-indent."
10351 (save-excursion
10352 (save-match-data
10353 (and (progn
10354 (forward-line 0)
10355 (looking-at "\\s-*//"))
10356 (progn
10357 (forward-line -1)
10358 (forward-line 0)
10359 (when (looking-at "\\s-*$")
10360 (js2-backward-sws)
10361 (forward-line 0))
10362 (looking-at "\\s-*//"))))))
10363
10364 (defun js2-indent-line (&optional bounce-backwards)
10365 "Indent the current line as JavaScript source text."
10366 (interactive)
10367 (let (parse-status
10368 offset
10369 indent-col
10370 moved
10371 ;; don't whine about errors/warnings when we're indenting.
10372 ;; This has to be set before calling parse-partial-sexp below.
10373 (inhibit-point-motion-hooks t))
10374 (setq parse-status (save-excursion
10375 (syntax-ppss (point-at-bol)))
10376 offset (- (point) (save-excursion
10377 (back-to-indentation)
10378 (point))))
10379 (js2-with-underscore-as-word-syntax
10380 (if (nth 4 parse-status)
10381 (js2-lineup-comment parse-status)
10382 (setq indent-col (js-proper-indentation parse-status))
10383 ;; see comments below about js2-mode-last-indented-line
10384 (cond
10385 ;; bounce-indenting is disabled during electric-key indent.
10386 ;; It doesn't work well on first line of buffer.
10387 ((and js2-bounce-indent-p
10388 (not (js2-same-line (point-min)))
10389 (not (js2-1-line-comment-continuation-p)))
10390 (js2-bounce-indent indent-col parse-status bounce-backwards))
10391 ;; just indent to the guesser's likely spot
10392 (t (indent-line-to indent-col)))
10393 (when (plusp offset)
10394 (forward-char offset))))))
10395
10396 (defun js2-indent-region (start end)
10397 "Indent the region, but don't use bounce indenting."
10398 (let ((js2-bounce-indent-p nil)
10399 (indent-region-function nil)
10400 (after-change-functions (remq 'js2-mode-edit
10401 after-change-functions)))
10402 (indent-region start end nil) ; nil for byte-compiler
10403 (js2-mode-edit start end (- end start))))
10404
10405 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10406
10407 ;;;###autoload
10408 (defun js2-mode ()
10409 "Major mode for editing JavaScript code."
10410 (interactive)
10411 (kill-all-local-variables)
10412 (set-syntax-table js2-mode-syntax-table)
10413 (use-local-map js2-mode-map)
10414 (make-local-variable 'comment-start)
10415 (make-local-variable 'comment-end)
10416 (make-local-variable 'comment-start-skip)
10417 (setq major-mode 'js2-mode
10418 mode-name "JavaScript-IDE"
10419 comment-start "//" ; used by comment-region; don't change it
10420 comment-end "")
10421 (setq local-abbrev-table js2-mode-abbrev-table)
10422 (set (make-local-variable 'max-lisp-eval-depth)
10423 (max max-lisp-eval-depth 3000))
10424 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10425 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10426
10427 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10428 ;; on most platforms other than the one I originally wrote it on. So it's
10429 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10430 ;; with our binding of the RET key inside comments: short lines stay short.
10431 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10432
10433 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10434 (set (make-local-variable 'next-error-function) #'js2-next-error)
10435 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10436 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10437 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10438 ;; for characters inside regexp literals.
10439 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10440 ;; this is necessary to make `show-paren-function' work properly
10441 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10442 ;; needed for M-x rgrep, among other things
10443 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10444
10445 ;; some variables needed by cc-engine for paragraph-fill, etc.
10446 (setq c-buffer-is-cc-mode t
10447 c-comment-prefix-regexp js2-comment-prefix-regexp
10448 c-comment-start-regexp "/[*/]\\|\\s|"
10449 c-paragraph-start js2-paragraph-start
10450 c-paragraph-separate "$"
10451 comment-start-skip js2-comment-start-skip
10452 c-syntactic-ws-start js2-syntactic-ws-start
10453 c-syntactic-ws-end js2-syntactic-ws-end
10454 c-syntactic-eol js2-syntactic-eol)
10455
10456 (setq js2-default-externs
10457 (append js2-ecma-262-externs
10458 (if js2-include-browser-externs
10459 js2-browser-externs)
10460 (if js2-include-gears-externs
10461 js2-gears-externs)
10462 (if js2-include-rhino-externs
10463 js2-rhino-externs)))
10464
10465 ;; We do our own syntax highlighting based on the parse tree.
10466 ;; However, we want minor modes that add keywords to highlight properly
10467 ;; (examples: doxymacs, column-marker). We do this by not letting
10468 ;; font-lock unfontify anything, and telling it to fontify after we
10469 ;; re-parse and re-highlight the buffer. (We currently don't do any
10470 ;; work with regions other than the whole buffer.)
10471 (dolist (var '(font-lock-unfontify-buffer-function
10472 font-lock-unfontify-region-function))
10473 (set (make-local-variable var) (lambda (&rest args) t)))
10474
10475 ;; Don't let font-lock do syntactic (string/comment) fontification.
10476 (set (make-local-variable #'font-lock-syntactic-face-function)
10477 (lambda (state) nil))
10478
10479 ;; Experiment: make reparse-delay longer for longer files.
10480 (if (plusp js2-dynamic-idle-timer-adjust)
10481 (setq js2-idle-timer-delay
10482 (* js2-idle-timer-delay
10483 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10484
10485 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10486 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10487 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10488 (imenu-add-to-menubar (concat "IM-" mode-name))
10489 (when js2-mirror-mode
10490 (js2-enter-mirror-mode))
10491 (add-to-invisibility-spec '(js2-outline . t))
10492 (set (make-local-variable 'line-move-ignore-invisible) t)
10493 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10494 (setq js2-mode-functions-hidden nil
10495 js2-mode-comments-hidden nil
10496 js2-mode-buffer-dirty-p t
10497 js2-mode-parsing nil)
10498 (js2-reparse)
10499
10500 (if (fboundp 'run-mode-hooks)
10501 (run-mode-hooks 'js2-mode-hook)
10502 (run-hooks 'js2-mode-hook)))
10503
10504 (defun js2-mode-exit ()
10505 "Exit `js2-mode' and clean up."
10506 (interactive)
10507 (when js2-mode-node-overlay
10508 (delete-overlay js2-mode-node-overlay)
10509 (setq js2-mode-node-overlay nil))
10510 (js2-remove-overlays)
10511 (setq js2-mode-ast nil)
10512 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10513 (remove-from-invisibility-spec '(js2-outline . t))
10514 (js2-mode-show-all)
10515 (js2-with-unmodifying-text-property-changes
10516 (js2-clear-face (point-min) (point-max))))
10517
10518 (defun js2-before-save ()
10519 "Clean up whitespace before saving file.
10520 You can disable this by customizing `js2-cleanup-whitespace'."
10521 (when js2-cleanup-whitespace
10522 (let ((col (current-column)))
10523 (delete-trailing-whitespace)
10524 ;; don't change trailing whitespace on current line
10525 (unless (eq (current-column) col)
10526 (indent-to col)))))
10527
10528 (defsubst js2-mode-reset-timer ()
10529 "Cancel any existing parse timer and schedule a new one."
10530 (if js2-mode-parse-timer
10531 (cancel-timer js2-mode-parse-timer))
10532 (setq js2-mode-parsing nil)
10533 (setq js2-mode-parse-timer
10534 (run-with-idle-timer js2-idle-timer-delay nil
10535 #'js2-mode-idle-reparse (current-buffer))))
10536
10537 (defun js2-mode-idle-reparse (buffer)
10538 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10539 it to be reparsed when the buffer is selected."
10540 (if (eq buffer (current-buffer))
10541 (js2-reparse)
10542 ;; reparse when the buffer is selected again
10543 (with-current-buffer buffer
10544 (add-hook 'window-configuration-change-hook
10545 #'js2-mode-idle-reparse-inner
10546 t))))
10547
10548 (defun js2-mode-idle-reparse-inner ()
10549 (remove-hook 'window-configuration-change-hook
10550 #'js2-mode-idle-reparse-inner
10551 t)
10552 (js2-reparse))
10553
10554 (defun js2-mode-edit (beg end len)
10555 "Schedule a new parse after buffer is edited.
10556 Buffer edit spans from BEG to END and is of length LEN.
10557 Also clears the `js2-magic' bit on autoinserted parens/brackets
10558 if the edit occurred on a line different from the magic paren."
10559 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10560 (line (if magic-pos (line-number-at-pos magic-pos))))
10561 (and line
10562 (or (/= (line-number-at-pos beg) line)
10563 (and (> 0 len)
10564 (/= (line-number-at-pos end) line)))
10565 (js2-mode-mundanify-parens)))
10566 (setq js2-mode-buffer-dirty-p t)
10567 (js2-mode-hide-overlay)
10568 (js2-mode-reset-timer))
10569
10570 (defun js2-mode-run-font-lock ()
10571 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10572 This is intended to allow modes that install their own font-lock keywords
10573 to work with js2-mode. In practice it never seems to work for long.
10574 Hopefully the Emacs maintainers can help figure out a way to make it work."
10575 (when (and (boundp 'font-lock-keywords)
10576 font-lock-keywords
10577 (boundp 'font-lock-mode)
10578 font-lock-mode)
10579 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10580 ;; play nicely with js2-mode. They go out of their way to fail to
10581 ;; provide any option for saying "look, fontify the farging buffer
10582 ;; with just the keywords already". Argh.
10583 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10584 (let (font-lock-verbose)
10585 (font-lock-fontify-buffer))))
10586
10587 (defun js2-reparse (&optional force)
10588 "Re-parse current buffer after user finishes some data entry.
10589 If we get any user input while parsing, including cursor motion,
10590 we discard the parse and reschedule it. If FORCE is nil, then the
10591 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10592 (let (time
10593 interrupted-p
10594 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10595 (unless js2-mode-parsing
10596 (setq js2-mode-parsing t)
10597 (unwind-protect
10598 (when (or js2-mode-buffer-dirty-p force)
10599 (js2-remove-overlays)
10600 (js2-with-unmodifying-text-property-changes
10601 (setq js2-mode-buffer-dirty-p nil
10602 js2-mode-fontifications nil
10603 js2-mode-deferred-properties nil)
10604 (if js2-mode-verbose-parse-p
10605 (message "parsing..."))
10606 (setq time
10607 (js2-time
10608 (setq interrupted-p
10609 (catch 'interrupted
10610 (setq js2-mode-ast (js2-parse))
10611 ;; if parsing is interrupted, comments and regex
10612 ;; literals stay ignored by `parse-partial-sexp'
10613 (remove-text-properties (point-min) (point-max)
10614 '(syntax-table))
10615 (js2-mode-apply-deferred-properties)
10616 (js2-mode-remove-suppressed-warnings)
10617 (js2-mode-show-warnings)
10618 (js2-mode-show-errors)
10619 (js2-mode-run-font-lock) ; note: doesn't work
10620 (js2-mode-highlight-magic-parens)
10621 (if (>= js2-highlight-level 1)
10622 (js2-highlight-jsdoc js2-mode-ast))
10623 nil))))
10624 (if interrupted-p
10625 (progn
10626 ;; unfinished parse => try again
10627 (setq js2-mode-buffer-dirty-p t)
10628 (js2-mode-reset-timer))
10629 (if js2-mode-verbose-parse-p
10630 (message "Parse time: %s" time)))))
10631 (setq js2-mode-parsing nil)
10632 (unless interrupted-p
10633 (setq js2-mode-parse-timer nil))))))
10634
10635 (defun js2-mode-show-node ()
10636 "Debugging aid: highlight selected AST node on mouse click."
10637 (interactive)
10638 (let ((node (js2-node-at-point))
10639 beg
10640 end)
10641 (when js2-mode-show-overlay
10642 (if (null node)
10643 (message "No node found at location %s" (point))
10644 (setq beg (js2-node-abs-pos node)
10645 end (+ beg (js2-node-len node)))
10646 (if js2-mode-node-overlay
10647 (move-overlay js2-mode-node-overlay beg end)
10648 (setq js2-mode-node-overlay (make-overlay beg end))
10649 (overlay-put js2-mode-node-overlay 'face 'highlight))
10650 (js2-with-unmodifying-text-property-changes
10651 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10652 (message "%s, parent: %s"
10653 (js2-node-short-name node)
10654 (if (js2-node-parent node)
10655 (js2-node-short-name (js2-node-parent node))
10656 "nil"))))))
10657
10658 (defun js2-mode-hide-overlay (&optional p1 p2)
10659 "Remove the debugging overlay when the point moves.
10660 P1 and P2 are the old and new values of point, respectively."
10661 (when js2-mode-node-overlay
10662 (let ((beg (overlay-start js2-mode-node-overlay))
10663 (end (overlay-end js2-mode-node-overlay)))
10664 ;; Sometimes we're called spuriously.
10665 (unless (and p2
10666 (>= p2 beg)
10667 (<= p2 end))
10668 (js2-with-unmodifying-text-property-changes
10669 (remove-text-properties beg end '(point-left nil)))
10670 (delete-overlay js2-mode-node-overlay)
10671 (setq js2-mode-node-overlay nil)))))
10672
10673 (defun js2-mode-reset ()
10674 "Debugging helper: reset everything."
10675 (interactive)
10676 (js2-mode-exit)
10677 (js2-mode))
10678
10679 (defsubst js2-mode-show-warn-or-err (e face)
10680 "Highlight a warning or error E with FACE.
10681 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10682 (let* ((key (first e))
10683 (beg (second e))
10684 (end (+ beg (third e)))
10685 ;; Don't inadvertently go out of bounds.
10686 (beg (max (point-min) (min beg (point-max))))
10687 (end (max (point-min) (min end (point-max))))
10688 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10689 (ovl (make-overlay beg end)))
10690 (overlay-put ovl 'face face)
10691 (overlay-put ovl 'js2-error t)
10692 (put-text-property beg end 'help-echo (js2-get-msg key))
10693 (put-text-property beg end 'point-entered #'js2-echo-error)))
10694
10695 (defun js2-remove-overlays ()
10696 "Remove overlays from buffer that have a `js2-error' property."
10697 (let ((beg (point-min))
10698 (end (point-max)))
10699 (save-excursion
10700 (dolist (o (overlays-in beg end))
10701 (when (overlay-get o 'js2-error)
10702 (delete-overlay o))))))
10703
10704 (defun js2-error-at-point (&optional pos)
10705 "Return non-nil if there's an error overlay at POS.
10706 Defaults to point."
10707 (loop with pos = (or pos (point))
10708 for o in (overlays-at pos)
10709 thereis (overlay-get o 'js2-error)))
10710
10711 (defun js2-mode-apply-deferred-properties ()
10712 "Apply fontifications and other text properties recorded during parsing."
10713 (when (plusp js2-highlight-level)
10714 ;; We defer clearing faces as long as possible to eliminate flashing.
10715 (js2-clear-face (point-min) (point-max))
10716 ;; Have to reverse the recorded fontifications list so that errors
10717 ;; and warnings overwrite the normal fontifications.
10718 (dolist (f (nreverse js2-mode-fontifications))
10719 (put-text-property (first f) (second f) 'face (third f)))
10720 (setq js2-mode-fontifications nil))
10721 (dolist (p js2-mode-deferred-properties)
10722 (apply #'put-text-property p))
10723 (setq js2-mode-deferred-properties nil))
10724
10725 (defun js2-mode-show-errors ()
10726 "Highlight syntax errors."
10727 (when js2-mode-show-parse-errors
10728 (dolist (e (js2-ast-root-errors js2-mode-ast))
10729 (js2-mode-show-warn-or-err e 'js2-error-face))))
10730
10731 (defun js2-mode-remove-suppressed-warnings ()
10732 "Take suppressed warnings out of the AST warnings list.
10733 This ensures that the counts and `next-error' are correct."
10734 (setf (js2-ast-root-warnings js2-mode-ast)
10735 (js2-delete-if
10736 (lambda (e)
10737 (let ((key (caar e)))
10738 (or
10739 (and (not js2-strict-trailing-comma-warning)
10740 (string-match "trailing\\.comma" key))
10741 (and (not js2-strict-cond-assign-warning)
10742 (string= key "msg.equal.as.assign"))
10743 (and js2-missing-semi-one-line-override
10744 (string= key "msg.missing.semi")
10745 (let* ((beg (second e))
10746 (node (js2-node-at-point beg))
10747 (fn (js2-mode-find-parent-fn node))
10748 (body (and fn (js2-function-node-body fn)))
10749 (lc (and body (js2-node-abs-pos body)))
10750 (rc (and lc (+ lc (js2-node-len body)))))
10751 (and fn
10752 (or (null body)
10753 (save-excursion
10754 (goto-char beg)
10755 (and (js2-same-line lc)
10756 (js2-same-line rc))))))))))
10757 (js2-ast-root-warnings js2-mode-ast))))
10758
10759 (defun js2-mode-show-warnings ()
10760 "Highlight strict-mode warnings."
10761 (when js2-mode-show-strict-warnings
10762 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10763 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10764
10765 (defun js2-echo-error (old-point new-point)
10766 "Called by point-motion hooks."
10767 (let ((msg (get-text-property new-point 'help-echo)))
10768 (if msg
10769 (message msg))))
10770
10771 (defalias #'js2-echo-help #'js2-echo-error)
10772
10773 (defun js2-enter-key ()
10774 "Handle user pressing the Enter key."
10775 (interactive)
10776 (let ((parse-status (save-excursion
10777 (syntax-ppss (point)))))
10778 (cond
10779 ;; check if we're inside a string
10780 ((nth 3 parse-status)
10781 (js2-mode-split-string parse-status))
10782 ;; check if inside a block comment
10783 ((nth 4 parse-status)
10784 (js2-mode-extend-comment))
10785 (t
10786 ;; should probably figure out what the mode-map says we should do
10787 (if js2-indent-on-enter-key
10788 (let ((js2-bounce-indent-p nil))
10789 (js2-indent-line)))
10790 (insert "\n")
10791 (if js2-enter-indents-newline
10792 (let ((js2-bounce-indent-p nil))
10793 (js2-indent-line)))))))
10794
10795 (defun js2-mode-split-string (parse-status)
10796 "Turn a newline in mid-string into a string concatenation.
10797 PARSE-STATUS is as documented in `parse-partial-sexp'."
10798 (let* ((col (current-column))
10799 (quote-char (nth 3 parse-status))
10800 (quote-string (string quote-char))
10801 (string-beg (nth 8 parse-status))
10802 (indent (save-match-data
10803 (or
10804 (save-excursion
10805 (back-to-indentation)
10806 (if (looking-at "\\+")
10807 (current-column)))
10808 (save-excursion
10809 (goto-char string-beg)
10810 (if (looking-back "\\+\\s-+")
10811 (goto-char (match-beginning 0)))
10812 (current-column))))))
10813 (insert quote-char "\n")
10814 (indent-to indent)
10815 (insert "+ " quote-string)
10816 (when (eolp)
10817 (insert quote-string)
10818 (backward-char 1))))
10819
10820 (defun js2-mode-extend-comment ()
10821 "When inside a comment block, add comment prefix."
10822 (let (star single col first-line needs-close)
10823 (save-excursion
10824 (back-to-indentation)
10825 (cond
10826 ((looking-at "\\*[^/]")
10827 (setq star t
10828 col (current-column)))
10829 ((looking-at "/\\*")
10830 (setq star t
10831 first-line t
10832 col (1+ (current-column))))
10833 ((looking-at "//")
10834 (setq single t
10835 col (current-column)))))
10836 ;; Heuristic for whether we need to close the comment:
10837 ;; if we've got a parse error here, assume it's an unterminated
10838 ;; comment.
10839 (setq needs-close
10840 (or
10841 (eq (get-text-property (1- (point)) 'point-entered)
10842 'js2-echo-error)
10843 ;; The heuristic above doesn't work well when we're
10844 ;; creating a comment and there's another one downstream,
10845 ;; as our parser thinks this one ends at the end of the
10846 ;; next one. (You can have a /* inside a js block comment.)
10847 ;; So just close it if the next non-ws char isn't a *.
10848 (and first-line
10849 (eolp)
10850 (save-excursion
10851 (skip-chars-forward " \t\r\n")
10852 (not (eq (char-after) ?*))))))
10853 (insert "\n")
10854 (cond
10855 (star
10856 (indent-to col)
10857 (insert "* ")
10858 (if (and first-line needs-close)
10859 (save-excursion
10860 (insert "\n")
10861 (indent-to col)
10862 (insert "*/"))))
10863 (single
10864 (when (save-excursion
10865 (and (zerop (forward-line 1))
10866 (looking-at "\\s-*//")))
10867 (indent-to col)
10868 (insert "// "))))))
10869
10870 (defun js2-beginning-of-line ()
10871 "Toggles point between bol and first non-whitespace char in line.
10872 Also moves past comment delimiters when inside comments."
10873 (interactive)
10874 (let (node beg)
10875 (cond
10876 ((bolp)
10877 (back-to-indentation))
10878 ((looking-at "//")
10879 (skip-chars-forward "/ \t"))
10880 ((and (eq (char-after) ?*)
10881 (setq node (js2-comment-at-point))
10882 (memq (js2-comment-node-format node) '(jsdoc block))
10883 (save-excursion
10884 (skip-chars-backward " \t")
10885 (bolp)))
10886 (skip-chars-forward "\* \t"))
10887 (t
10888 (goto-char (point-at-bol))))))
10889
10890 (defun js2-end-of-line ()
10891 "Toggles point between eol and last non-whitespace char in line."
10892 (interactive)
10893 (if (eolp)
10894 (skip-chars-backward " \t")
10895 (goto-char (point-at-eol))))
10896
10897 (defun js2-enter-mirror-mode()
10898 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10899 on insertion."
10900 (interactive)
10901 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10902 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10903 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10904 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10905 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10906 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10907 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10908 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10909
10910 (defun js2-leave-mirror-mode()
10911 "Turns off mirror mode."
10912 (interactive)
10913 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10914 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10915
10916 (defsubst js2-mode-inside-string ()
10917 "Return non-nil if inside a string.
10918 Actually returns the quote character that begins the string."
10919 (let ((parse-state (save-excursion
10920 (syntax-ppss (point)))))
10921 (nth 3 parse-state)))
10922
10923 (defsubst js2-mode-inside-comment-or-string ()
10924 "Return non-nil if inside a comment or string."
10925 (or
10926 (let ((comment-start
10927 (save-excursion
10928 (goto-char (point-at-bol))
10929 (if (re-search-forward "//" (point-at-eol) t)
10930 (match-beginning 0)))))
10931 (and comment-start
10932 (<= comment-start (point))))
10933 (let ((parse-state (save-excursion
10934 (syntax-ppss (point)))))
10935 (or (nth 3 parse-state)
10936 (nth 4 parse-state)))))
10937
10938 (defsubst js2-make-magic-delimiter (delim &optional pos)
10939 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10940 Sets value of `js2-magic' text property to line number at POS."
10941 (propertize delim
10942 'js2-magic (line-number-at-pos pos)
10943 'face 'js2-magic-paren-face))
10944
10945 (defun js2-mode-match-delimiter (open close)
10946 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10947 The rule we use, which as far as we can tell is how Eclipse works,
10948 is that we insert the match if we're not in a comment or string,
10949 and the next non-whitespace character is either punctuation or
10950 occurs on another line."
10951 (insert open)
10952 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10953 (not (js2-mode-inside-comment-or-string)))
10954 (save-excursion
10955 (insert (js2-make-magic-delimiter close)))
10956 (when js2-auto-indent-p
10957 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10958 (js2-indent-line)))))
10959
10960 (defun js2-mode-match-bracket ()
10961 "Insert matching bracket."
10962 (interactive)
10963 (js2-mode-match-delimiter "[" "]"))
10964
10965 (defun js2-mode-match-paren ()
10966 "Insert matching paren unless already inserted."
10967 (interactive)
10968 (js2-mode-match-delimiter "(" ")"))
10969
10970 (defun js2-mode-match-curly (arg)
10971 "Insert matching curly-brace.
10972 With prefix arg, no formatting or indentation will occur -- the close-brace
10973 is simply inserted directly at the point."
10974 (interactive "p")
10975 (let (try-pos)
10976 (cond
10977 (current-prefix-arg
10978 (js2-mode-match-delimiter "{" "}"))
10979 ((and js2-auto-insert-catch-block
10980 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10981 (point-at-bol))
10982 (match-beginning 1))))
10983 (js2-insert-catch-skel try-pos))
10984 (t
10985 ;; Otherwise try to do something smarter.
10986 (insert "{")
10987 (unless (or (not (looking-at "\\s-*$"))
10988 (save-excursion
10989 (skip-chars-forward " \t\r\n")
10990 (and (looking-at "}")
10991 (js2-error-at-point)))
10992 (js2-mode-inside-comment-or-string))
10993 (undo-boundary)
10994 ;; absolutely mystifying bug: when inserting the next "\n",
10995 ;; the buffer-undo-list is given two new entries: the inserted range,
10996 ;; and the incorrect position of the point. It's recorded incorrectly
10997 ;; as being before the opening "{", not after it. But it's recorded
10998 ;; as the correct value if you're debugging `js2-mode-match-curly'
10999 ;; in edebug. I have no idea why it's doing this, but incrementing
11000 ;; the inserted position fixes the problem, so that the undo takes us
11001 ;; back to just after the user-inserted "{".
11002 (insert "\n")
11003 (ignore-errors
11004 (incf (cadr buffer-undo-list)))
11005 (js2-indent-line)
11006 (save-excursion
11007 (insert "\n}")
11008 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11009 (js2-indent-line))))))))
11010
11011 (defun js2-insert-catch-skel (try-pos)
11012 "Complete a try/catch block after inserting a { following a try keyword.
11013 Rationale is that a try always needs a catch or a finally, and the catch is
11014 the more likely of the two.
11015
11016 TRY-POS is the buffer position of the try keyword. The open-curly should
11017 already have been inserted."
11018 (insert "{")
11019 (let ((try-col (save-excursion
11020 (goto-char try-pos)
11021 (current-column))))
11022 (insert "\n")
11023 (undo-boundary)
11024 (js2-indent-line) ;; indent the blank line where cursor will end up
11025 (save-excursion
11026 (insert "\n")
11027 (indent-to try-col)
11028 (insert "} catch (x) {\n\n")
11029 (indent-to try-col)
11030 (insert "}"))))
11031
11032 (defun js2-mode-highlight-magic-parens ()
11033 "Re-highlight magic parens after parsing nukes the 'face prop."
11034 (let ((beg (point-min))
11035 end)
11036 (while (setq beg (next-single-property-change beg 'js2-magic))
11037 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11038 (if (get-text-property beg 'js2-magic)
11039 (js2-with-unmodifying-text-property-changes
11040 (put-text-property beg (or end (1+ beg))
11041 'face 'js2-magic-paren-face))))))
11042
11043 (defun js2-mode-mundanify-parens ()
11044 "Clear all magic parens and brackets."
11045 (let ((beg (point-min))
11046 end)
11047 (while (setq beg (next-single-property-change beg 'js2-magic))
11048 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11049 (remove-text-properties beg (or end (1+ beg))
11050 '(js2-magic face)))))
11051
11052 (defsubst js2-match-quote (quote-string)
11053 (let ((start-quote (js2-mode-inside-string)))
11054 (cond
11055 ;; inside a comment - don't do quote-matching, since we can't
11056 ;; reliably figure out if we're in a string inside the comment
11057 ((js2-comment-at-point)
11058 (insert quote-string))
11059 ((not start-quote)
11060 ;; not in string => insert matched quotes
11061 (insert quote-string)
11062 ;; exception: if we're just before a word, don't double it.
11063 (unless (looking-at "[^ \t\r\n]")
11064 (save-excursion
11065 (insert quote-string))))
11066 ((looking-at quote-string)
11067 (if (looking-back "[^\\]\\\\")
11068 (insert quote-string)
11069 (forward-char 1)))
11070 ((and js2-mode-escape-quotes
11071 (save-excursion
11072 (save-match-data
11073 (re-search-forward quote-string (point-at-eol) t))))
11074 ;; inside terminated string, escape quote (unless already escaped)
11075 (insert (if (looking-back "[^\\]\\\\")
11076 quote-string
11077 (concat "\\" quote-string))))
11078 (t
11079 (insert quote-string))))) ; else terminate the string
11080
11081 (defun js2-mode-match-single-quote ()
11082 "Insert matching single-quote."
11083 (interactive)
11084 (let ((parse-status (syntax-ppss (point))))
11085 ;; don't match inside comments, since apostrophe is more common
11086 (if (nth 4 parse-status)
11087 (insert "'")
11088 (js2-match-quote "'"))))
11089
11090 (defun js2-mode-match-double-quote ()
11091 "Insert matching double-quote."
11092 (interactive)
11093 (js2-match-quote "\""))
11094
11095 ;; Eclipse works as follows:
11096 ;; * type an open-paren and it auto-inserts close-paren
11097 ;; - auto-inserted paren gets a green bracket
11098 ;; - green bracket means typing close-paren there will skip it
11099 ;; * if you insert any text on a different line, it turns off
11100 (defun js2-mode-magic-close-paren ()
11101 "Skip over close-paren rather than inserting, where appropriate."
11102 (interactive)
11103 (let* ((here (point))
11104 (parse-status (syntax-ppss here))
11105 (open-pos (nth 1 parse-status))
11106 (close last-input-event)
11107 (open (cond
11108 ((eq close ?\))
11109 ?\()
11110 ((eq close ?\])
11111 ?\[)
11112 ((eq close ?})
11113 ?{)
11114 (t nil))))
11115 (if (and (eq (char-after) close)
11116 (eq open (char-after open-pos))
11117 (js2-same-line open-pos)
11118 (get-text-property here 'js2-magic))
11119 (progn
11120 (remove-text-properties here (1+ here) '(js2-magic face))
11121 (forward-char 1))
11122 (insert-char close 1))
11123 (blink-matching-open)))
11124
11125 (defun js2-mode-wait-for-parse (callback)
11126 "Invoke CALLBACK when parsing is finished.
11127 If parsing is already finished, calls CALLBACK immediately."
11128 (if (not js2-mode-buffer-dirty-p)
11129 (funcall callback)
11130 (push callback js2-mode-pending-parse-callbacks)
11131 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11132
11133 (defun js2-mode-parse-finished ()
11134 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11135 ;; We can't let errors propagate up, since it prevents the
11136 ;; `js2-parse' method from completing normally and returning
11137 ;; the ast, which makes things mysteriously not work right.
11138 (unwind-protect
11139 (dolist (cb js2-mode-pending-parse-callbacks)
11140 (condition-case err
11141 (funcall cb)
11142 (error (message "%s" err))))
11143 (setq js2-mode-pending-parse-callbacks nil)))
11144
11145 (defun js2-mode-flag-region (from to flag)
11146 "Hide or show text from FROM to TO, according to FLAG.
11147 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11148 Returns the created overlay if FLAG is non-nil."
11149 (remove-overlays from to 'invisible 'js2-outline)
11150 (when flag
11151 (let ((o (make-overlay from to)))
11152 (overlay-put o 'invisible 'js2-outline)
11153 (overlay-put o 'isearch-open-invisible
11154 'js2-isearch-open-invisible)
11155 o)))
11156
11157 ;; Function to be set as an outline-isearch-open-invisible' property
11158 ;; to the overlay that makes the outline invisible (see
11159 ;; `js2-mode-flag-region').
11160 (defun js2-isearch-open-invisible (overlay)
11161 ;; We rely on the fact that isearch places point on the matched text.
11162 (js2-mode-show-element))
11163
11164 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11165 "Return cons cell of bounds of folding overlay at POS.
11166 Returns nil if not found."
11167 (let ((overlays (overlays-at (or pos (point))))
11168 o)
11169 (while (and overlays
11170 (not o))
11171 (if (overlay-get (car overlays) 'invisible)
11172 (setq o (car overlays))
11173 (setq overlays (cdr overlays))))
11174 (if o
11175 (cons (overlay-start o) (overlay-end o)))))
11176
11177 (defun js2-mode-function-at-point (&optional pos)
11178 "Return the innermost function node enclosing current point.
11179 Returns nil if point is not in a function."
11180 (let ((node (js2-node-at-point pos)))
11181 (while (and node (not (js2-function-node-p node)))
11182 (setq node (js2-node-parent node)))
11183 (if (js2-function-node-p node)
11184 node)))
11185
11186 (defun js2-mode-toggle-element ()
11187 "Hide or show the foldable element at the point."
11188 (interactive)
11189 (let (comment fn pos)
11190 (save-excursion
11191 (save-match-data
11192 (cond
11193 ;; /* ... */ comment?
11194 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11195 (if (js2-mode-invisible-overlay-bounds
11196 (setq pos (+ 3 (js2-node-abs-pos comment))))
11197 (progn
11198 (goto-char pos)
11199 (js2-mode-show-element))
11200 (js2-mode-hide-element)))
11201 ;; //-comment?
11202 ((save-excursion
11203 (back-to-indentation)
11204 (looking-at js2-mode-//-comment-re))
11205 (js2-mode-toggle-//-comment))
11206 ;; function?
11207 ((setq fn (js2-mode-function-at-point))
11208 (setq pos (and (js2-function-node-body fn)
11209 (js2-node-abs-pos (js2-function-node-body fn))))
11210 (goto-char (1+ pos))
11211 (if (js2-mode-invisible-overlay-bounds)
11212 (js2-mode-show-element)
11213 (js2-mode-hide-element)))
11214 (t
11215 (message "Nothing at point to hide or show")))))))
11216
11217 (defun js2-mode-hide-element ()
11218 "Fold/hide contents of a block, showing ellipses.
11219 Show the hidden text with \\[js2-mode-show-element]."
11220 (interactive)
11221 (if js2-mode-buffer-dirty-p
11222 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11223 (let (node body beg end)
11224 (cond
11225 ((js2-mode-invisible-overlay-bounds)
11226 (message "already hidden"))
11227 (t
11228 (setq node (js2-node-at-point))
11229 (cond
11230 ((js2-block-comment-p node)
11231 (js2-mode-hide-comment node))
11232 (t
11233 (while (and node (not (js2-function-node-p node)))
11234 (setq node (js2-node-parent node)))
11235 (if (and node
11236 (setq body (js2-function-node-body node)))
11237 (progn
11238 (setq beg (js2-node-abs-pos body)
11239 end (+ beg (js2-node-len body)))
11240 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11241 (message "No collapsable element found at point"))))))))
11242
11243 (defun js2-mode-show-element ()
11244 "Show the hidden element at current point."
11245 (interactive)
11246 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11247 (if bounds
11248 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11249 (message "Nothing to un-hide"))))
11250
11251 (defun js2-mode-show-all ()
11252 "Show all of the text in the buffer."
11253 (interactive)
11254 (js2-mode-flag-region (point-min) (point-max) nil))
11255
11256 (defun js2-mode-toggle-hide-functions ()
11257 (interactive)
11258 (if js2-mode-functions-hidden
11259 (js2-mode-show-functions)
11260 (js2-mode-hide-functions)))
11261
11262 (defun js2-mode-hide-functions ()
11263 "Hides all non-nested function bodies in the buffer.
11264 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11265 to open an individual entry."
11266 (interactive)
11267 (if js2-mode-buffer-dirty-p
11268 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11269 (if (null js2-mode-ast)
11270 (message "Oops - parsing failed")
11271 (setq js2-mode-functions-hidden t)
11272 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11273
11274 (defun js2-mode-function-hider (n endp)
11275 (when (not endp)
11276 (let ((tt (js2-node-type n))
11277 body beg end)
11278 (cond
11279 ((and (= tt js2-FUNCTION)
11280 (setq body (js2-function-node-body n)))
11281 (setq beg (js2-node-abs-pos body)
11282 end (+ beg (js2-node-len body)))
11283 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11284 nil) ; don't process children of function
11285 (t
11286 t))))) ; keep processing other AST nodes
11287
11288 (defun js2-mode-show-functions ()
11289 "Un-hide any folded function bodies in the buffer."
11290 (interactive)
11291 (setq js2-mode-functions-hidden nil)
11292 (save-excursion
11293 (goto-char (point-min))
11294 (while (/= (goto-char (next-overlay-change (point)))
11295 (point-max))
11296 (dolist (o (overlays-at (point)))
11297 (when (and (overlay-get o 'invisible)
11298 (not (overlay-get o 'comment)))
11299 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11300
11301 (defun js2-mode-hide-comment (n)
11302 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11303 3 ; /**
11304 2)) ; /*
11305 (beg (+ (js2-node-abs-pos n) head))
11306 (end (- (+ beg (js2-node-len n)) head 2))
11307 (o (js2-mode-flag-region beg end 'hide)))
11308 (overlay-put o 'comment t)))
11309
11310 (defun js2-mode-toggle-hide-comments ()
11311 "Folds all block comments in the buffer.
11312 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11313 to open an individual entry."
11314 (interactive)
11315 (if js2-mode-comments-hidden
11316 (js2-mode-show-comments)
11317 (js2-mode-hide-comments)))
11318
11319 (defun js2-mode-hide-comments ()
11320 (interactive)
11321 (if js2-mode-buffer-dirty-p
11322 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11323 (if (null js2-mode-ast)
11324 (message "Oops - parsing failed")
11325 (setq js2-mode-comments-hidden t)
11326 (dolist (n (js2-ast-root-comments js2-mode-ast))
11327 (let ((format (js2-comment-node-format n)))
11328 (when (js2-block-comment-p n)
11329 (js2-mode-hide-comment n))))
11330 (js2-mode-hide-//-comments)))
11331
11332 (defsubst js2-mode-extend-//-comment (direction)
11333 "Find start or end of a block of similar //-comment lines.
11334 DIRECTION is -1 to look back, 1 to look forward.
11335 INDENT is the indentation level to match.
11336 Returns the end-of-line position of the furthest adjacent
11337 //-comment line with the same indentation as the current line.
11338 If there is no such matching line, returns current end of line."
11339 (let ((pos (point-at-eol))
11340 (indent (current-indentation)))
11341 (save-excursion
11342 (save-match-data
11343 (while (and (zerop (forward-line direction))
11344 (looking-at js2-mode-//-comment-re)
11345 (eq indent (length (match-string 1))))
11346 (setq pos (point-at-eol)))
11347 pos))))
11348
11349 (defun js2-mode-hide-//-comments ()
11350 "Fold adjacent 1-line comments, showing only snippet of first one."
11351 (let (beg end)
11352 (save-excursion
11353 (save-match-data
11354 (goto-char (point-min))
11355 (while (re-search-forward js2-mode-//-comment-re nil t)
11356 (setq beg (point)
11357 end (js2-mode-extend-//-comment 1))
11358 (unless (eq beg end)
11359 (overlay-put (js2-mode-flag-region beg end 'hide)
11360 'comment t))
11361 (goto-char end)
11362 (forward-char 1))))))
11363
11364 (defun js2-mode-toggle-//-comment ()
11365 "Fold or un-fold any multi-line //-comment at point.
11366 Caller should have determined that this line starts with a //-comment."
11367 (let* ((beg (point-at-eol))
11368 (end beg))
11369 (save-excursion
11370 (goto-char end)
11371 (if (js2-mode-invisible-overlay-bounds)
11372 (js2-mode-show-element)
11373 ;; else hide the comment
11374 (setq beg (js2-mode-extend-//-comment -1)
11375 end (js2-mode-extend-//-comment 1))
11376 (unless (eq beg end)
11377 (overlay-put (js2-mode-flag-region beg end 'hide)
11378 'comment t))))))
11379
11380 (defun js2-mode-show-comments ()
11381 "Un-hide any hidden comments, leaving other hidden elements alone."
11382 (interactive)
11383 (setq js2-mode-comments-hidden nil)
11384 (save-excursion
11385 (goto-char (point-min))
11386 (while (/= (goto-char (next-overlay-change (point)))
11387 (point-max))
11388 (dolist (o (overlays-at (point)))
11389 (when (overlay-get o 'comment)
11390 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11391
11392 (defun js2-mode-display-warnings-and-errors ()
11393 "Turn on display of warnings and errors."
11394 (interactive)
11395 (setq js2-mode-show-parse-errors t
11396 js2-mode-show-strict-warnings t)
11397 (js2-reparse 'force))
11398
11399 (defun js2-mode-hide-warnings-and-errors ()
11400 "Turn off display of warnings and errors."
11401 (interactive)
11402 (setq js2-mode-show-parse-errors nil
11403 js2-mode-show-strict-warnings nil)
11404 (js2-reparse 'force))
11405
11406 (defun js2-mode-toggle-warnings-and-errors ()
11407 "Toggle the display of warnings and errors.
11408 Some users don't like having warnings/errors reported while they type."
11409 (interactive)
11410 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11411 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11412 (if (interactive-p)
11413 (message "warnings and errors %s"
11414 (if js2-mode-show-parse-errors
11415 "enabled"
11416 "disabled")))
11417 (js2-reparse 'force))
11418
11419 (defun js2-mode-customize ()
11420 (interactive)
11421 (customize-group 'js2-mode))
11422
11423 (defun js2-mode-forward-sexp (&optional arg)
11424 "Move forward across one statement or balanced expression.
11425 With ARG, do it that many times. Negative arg -N means
11426 move backward across N balanced expressions."
11427 (interactive "p")
11428 (setq arg (or arg 1))
11429 (if js2-mode-buffer-dirty-p
11430 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11431 (let (node end (start (point)))
11432 (cond
11433 ;; backward-sexp
11434 ;; could probably make this better for some cases:
11435 ;; - if in statement block (e.g. function body), go to parent
11436 ;; - infix exprs like (foo in bar) - maybe go to beginning
11437 ;; of infix expr if in the right-side expression?
11438 ((and arg (minusp arg))
11439 (dotimes (i (- arg))
11440 (js2-backward-sws)
11441 (forward-char -1) ; enter the node we backed up to
11442 (setq node (js2-node-at-point (point) t))
11443 (goto-char (if node
11444 (js2-node-abs-pos node)
11445 (point-min)))))
11446 (t
11447 ;; forward-sexp
11448 (js2-forward-sws)
11449 (dotimes (i arg)
11450 (js2-forward-sws)
11451 (setq node (js2-node-at-point (point) t)
11452 end (if node (+ (js2-node-abs-pos node)
11453 (js2-node-len node))))
11454 (goto-char (or end (point-max))))))))
11455
11456 (defun js2-next-error (&optional arg reset)
11457 "Move to next parse error.
11458 Typically invoked via \\[next-error].
11459 ARG is the number of errors, forward or backward, to move.
11460 RESET means start over from the beginning."
11461 (interactive "p")
11462 (if (or (null js2-mode-ast)
11463 (and (null (js2-ast-root-errors js2-mode-ast))
11464 (null (js2-ast-root-warnings js2-mode-ast))))
11465 (message "No errors")
11466 (when reset
11467 (goto-char (point-min)))
11468 (let* ((errs (copy-sequence
11469 (append (js2-ast-root-errors js2-mode-ast)
11470 (js2-ast-root-warnings js2-mode-ast))))
11471 (continue t)
11472 (start (point))
11473 (count (or arg 1))
11474 (backward (minusp count))
11475 (sorter (if backward '> '<))
11476 (stopper (if backward '< '>))
11477 (count (abs count))
11478 all-errs
11479 err)
11480 ;; sort by start position
11481 (setq errs (sort errs (lambda (e1 e2)
11482 (funcall sorter (second e1) (second e2))))
11483 all-errs errs)
11484 ;; find nth error with pos > start
11485 (while (and errs continue)
11486 (when (funcall stopper (cadar errs) start)
11487 (setq err (car errs))
11488 (if (zerop (decf count))
11489 (setq continue nil)))
11490 (setq errs (cdr errs)))
11491 (if err
11492 (goto-char (second err))
11493 ;; wrap around to first error
11494 (goto-char (second (car all-errs)))
11495 ;; if we were already on it, echo msg again
11496 (if (= (point) start)
11497 (js2-echo-error (point) (point)))))))
11498
11499 (defun js2-down-mouse-3 ()
11500 "Make right-click move the point to the click location.
11501 This makes right-click context menu operations a bit more intuitive.
11502 The point will not move if the region is active, however, to avoid
11503 destroying the region selection."
11504 (interactive)
11505 (when (and js2-move-point-on-right-click
11506 (not mark-active))
11507 (let ((e last-input-event))
11508 (ignore-errors
11509 (goto-char (cadadr e))))))
11510
11511 (defun js2-mode-create-imenu-index ()
11512 "Return an alist for `imenu--index-alist'."
11513 ;; This is built up in `js2-parse-record-imenu' during parsing.
11514 (when js2-mode-ast
11515 ;; if we have an ast but no recorder, they're requesting a rescan
11516 (unless js2-imenu-recorder
11517 (js2-reparse 'force))
11518 (prog1
11519 (js2-build-imenu-index)
11520 (setq js2-imenu-recorder nil
11521 js2-imenu-function-map nil))))
11522
11523 (defun js2-mode-find-tag ()
11524 "Replacement for `find-tag-default'.
11525 `find-tag-default' returns a ridiculous answer inside comments."
11526 (let (beg end)
11527 (js2-with-underscore-as-word-syntax
11528 (save-excursion
11529 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11530 (looking-back "[A-Za-z0-9_$]"))
11531 (setq beg (progn (forward-word -1) (point))
11532 end (progn (forward-word 1) (point)))
11533 (setq beg (progn (forward-word 1) (point))
11534 end (progn (forward-word -1) (point))))
11535 (replace-regexp-in-string
11536 "[\"']" ""
11537 (buffer-substring-no-properties beg end))))))
11538
11539 (defun js2-mode-forward-sibling ()
11540 "Move to the end of the sibling following point in parent.
11541 Returns non-nil if successful, or nil if there was no following sibling."
11542 (let* ((node (js2-node-at-point))
11543 (parent (js2-mode-find-enclosing-fn node))
11544 sib)
11545 (when (setq sib (js2-node-find-child-after (point) parent))
11546 (goto-char (+ (js2-node-abs-pos sib)
11547 (js2-node-len sib))))))
11548
11549 (defun js2-mode-backward-sibling ()
11550 "Move to the beginning of the sibling node preceding point in parent.
11551 Parent is defined as the enclosing script or function."
11552 (let* ((node (js2-node-at-point))
11553 (parent (js2-mode-find-enclosing-fn node))
11554 sib)
11555 (when (setq sib (js2-node-find-child-before (point) parent))
11556 (goto-char (js2-node-abs-pos sib)))))
11557
11558 (defun js2-beginning-of-defun ()
11559 "Go to line on which current function starts, and return non-nil.
11560 If we're not in a function, go to beginning of previous script-level element."
11561 (interactive)
11562 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11563 pos sib)
11564 (cond
11565 ((and (js2-function-node-p parent)
11566 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11567 (goto-char pos))
11568 (t
11569 (js2-mode-backward-sibling)))))
11570
11571 (defun js2-end-of-defun ()
11572 "Go to the char after the last position of the current function.
11573 If we're not in a function, skips over the next script-level element."
11574 (interactive)
11575 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11576 (if (not (js2-function-node-p parent))
11577 ;; punt: skip over next script-level element beyond point
11578 (js2-mode-forward-sibling)
11579 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11580 (js2-node-len parent)))))))
11581
11582 (defun js2-mark-defun (&optional allow-extend)
11583 "Put mark at end of this function, point at beginning.
11584 The function marked is the one that contains point.
11585
11586 Interactively, if this command is repeated,
11587 or (in Transient Mark mode) if the mark is active,
11588 it marks the next defun after the ones already marked."
11589 (interactive "p")
11590 (let (extended)
11591 (when (and allow-extend
11592 (or (and (eq last-command this-command) (mark t))
11593 (and transient-mark-mode mark-active)))
11594 (let ((sib (save-excursion
11595 (goto-char (mark))
11596 (if (js2-mode-forward-sibling)
11597 (point))))
11598 node)
11599 (if sib
11600 (progn
11601 (set-mark sib)
11602 (setq extended t))
11603 ;; no more siblings - try extending to enclosing node
11604 (goto-char (mark t)))))
11605 (when (not extended)
11606 (let ((node (js2-node-at-point (point) t)) ; skip comments
11607 ast fn stmt parent beg end)
11608 (when (js2-ast-root-p node)
11609 (setq ast node
11610 node (or (js2-node-find-child-after (point) node)
11611 (js2-node-find-child-before (point) node))))
11612 ;; only mark whole buffer if we can't find any children
11613 (if (null node)
11614 (setq node ast))
11615 (if (js2-function-node-p node)
11616 (setq parent node)
11617 (setq fn (js2-mode-find-enclosing-fn node)
11618 stmt (if (or (null fn)
11619 (js2-ast-root-p fn))
11620 (js2-mode-find-first-stmt node))
11621 parent (or stmt fn)))
11622 (setq beg (js2-node-abs-pos parent)
11623 end (+ beg (js2-node-len parent)))
11624 (push-mark beg)
11625 (goto-char end)
11626 (exchange-point-and-mark)))))
11627
11628 (defun js2-narrow-to-defun ()
11629 "Narrow to the function enclosing point."
11630 (interactive)
11631 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11632 (fn (if (js2-script-node-p node)
11633 node
11634 (js2-mode-find-enclosing-fn node)))
11635 (beg (js2-node-abs-pos fn)))
11636 (unless (js2-ast-root-p fn)
11637 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11638
11639 (provide 'js2-mode)
11640
11641 ;;; js2-mode.el ends here