]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Trailing comma is legal ecma-262-5.1
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2012 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: 1.0
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 and up
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 JSON
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 (make-obsolete-variable 'js2-mirror-mode 'electric-pair-mode "1.0")
219
220 (defcustom js2-auto-indent-p nil
221 "Automatic indentation with punctuation characters.
222 If non-nil, the current line is indented when certain punctuations
223 are inserted."
224 :group 'js2-mode
225 :type 'boolean)
226
227 (make-obsolete-variable 'js2-auto-indent-p 'electric-indent-mode "1.0")
228
229 (defcustom js2-bounce-indent-p nil
230 "Non-nil to have indent-line function choose among alternatives.
231 If nil, the indent-line function will indent to a predetermined column
232 based on heuristic guessing. If non-nil, then if the current line is
233 already indented to that predetermined column, indenting will choose
234 another likely column and indent to that spot. Repeated invocation of
235 the indent-line function will cycle among the computed alternatives.
236 See the function `js2-bounce-indent' for details. When it is non-nil,
237 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
238 :type 'boolean
239 :group 'js2-mode)
240
241 (defcustom js2-pretty-multiline-declarations t
242 "Non-nil to line up multiline declarations vertically:
243
244 var a = 10,
245 b = 20,
246 c = 30;
247
248 If the value is not `all', and the first assigned value in
249 declaration is a function/array/object literal spanning several
250 lines, it won't be indented additionally:
251
252 var o = { var bar = 2,
253 foo: 3 vs. o = {
254 }, foo: 3
255 bar = 2; };"
256 :group 'js2-mode
257 :type 'symbol)
258 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
259
260 (defcustom js2-indent-on-enter-key nil
261 "Non-nil to have Enter/Return key indent the line.
262 This is unusual for Emacs modes but common in IDEs like Eclipse."
263 :type 'boolean
264 :group 'js2-mode)
265
266 (make-obsolete-variable 'js2-indent-on-enter-key nil "1.0")
267
268 (defcustom js2-enter-indents-newline nil
269 "Non-nil to have Enter/Return key indent the newly-inserted line.
270 This is unusual for Emacs modes but common in IDEs like Eclipse."
271 :type 'boolean
272 :group 'js2-mode)
273
274 (make-obsolete-variable 'js2-enter-indents-newline nil "1.0")
275
276 (defcustom js2-rebind-eol-bol-keys t
277 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
278 If non-nil, bounce between bol/eol and first/last non-whitespace char."
279 :group 'js2-mode
280 :type 'boolean)
281
282 (make-obsolete-variable 'js2-rebind-eol-bol-keys nil "1.0")
283
284 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
285 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
286 Each value in the list is passed to `define-key'."
287 :type 'list
288 :group 'js2-mode)
289
290 (make-obsolete-variable 'js2-electric-keys 'electric-indent-chars "1.0")
291
292 (defcustom js2-idle-timer-delay 0.2
293 "Delay in secs before re-parsing after user makes changes.
294 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
295 :type 'number
296 :group 'js2-mode)
297 (make-variable-buffer-local 'js2-idle-timer-delay)
298
299 (defcustom js2-dynamic-idle-timer-adjust 0
300 "Positive to adjust `js2-idle-timer-delay' based on file size.
301 The idea is that for short files, parsing is faster so we can be
302 more responsive to user edits without interfering with editing.
303 The buffer length in characters (typically bytes) is divided by
304 this value and used to multiply `js2-idle-timer-delay' for the
305 buffer. For example, a 21k file and 10k adjust yields 21k/10k
306 == 2, so js2-idle-timer-delay is multiplied by 2.
307 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
308 `js2-idle-timer-delay' is not dependent on the file size."
309 :type 'number
310 :group 'js2-mode)
311
312 (defcustom js2-mode-escape-quotes t
313 "Non-nil to disable automatic quote-escaping inside strings."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (make-obsolete-variable 'js2-mode-escape-quotes nil "1.0")
318
319 (defcustom js2-concat-multiline-strings t
320 "Non-nil to automatically turn a newline in mid-string into a
321 string concatenation. When `eol', the '+' will be inserted at the
322 end of the line, otherwise, at the beginning of the next line."
323 :type '(choice (const t) (const eol) (const nil))
324 :group 'js2-mode)
325
326 (defcustom js2-mode-show-parse-errors t
327 "True to highlight parse errors."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-mode-show-strict-warnings t
332 "Non-nil to emit Ecma strict-mode warnings.
333 Some of the warnings can be individually disabled by other flags,
334 even if this flag is non-nil."
335 :type 'boolean
336 :group 'js2-mode)
337
338 (defcustom js2-strict-trailing-comma-warning t
339 "Non-nil to warn about trailing commas in array literals.
340 Ecma-262-5.1 allows them, but older versions of IE raise an error."
341 :type 'boolean
342 :group 'js2-mode)
343
344 (defcustom js2-strict-missing-semi-warning t
345 "Non-nil to warn about semicolon auto-insertion after statement.
346 Technically this is legal per Ecma-262, but some style guides disallow
347 depending on it."
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-missing-semi-one-line-override nil
352 "Non-nil to permit missing semicolons in one-line functions.
353 In one-liner functions such as `function identity(x) {return x}'
354 people often omit the semicolon for a cleaner look. If you are
355 such a person, you can suppress the missing-semicolon warning
356 by setting this variable to t."
357 :type 'boolean
358 :group 'js2-mode)
359
360 (defcustom js2-strict-inconsistent-return-warning t
361 "Non-nil to warn about mixing returns with value-returns.
362 It's perfectly legal to have a `return' and a `return foo' in the
363 same function, but it's often an indicator of a bug, and it also
364 interferes with type inference (in systems that support it.)"
365 :type 'boolean
366 :group 'js2-mode)
367
368 (defcustom js2-strict-cond-assign-warning t
369 "Non-nil to warn about expressions like if (a = b).
370 This often should have been '==' instead of '='. If the warning
371 is enabled, you can suppress it on a per-expression basis by
372 parenthesizing the expression, e.g. if ((a = b)) ..."
373 :type 'boolean
374 :group 'js2-mode)
375
376 (defcustom js2-strict-var-redeclaration-warning t
377 "Non-nil to warn about redeclaring variables in a script or function."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-strict-var-hides-function-arg-warning t
382 "Non-nil to warn about a var decl hiding a function argument."
383 :type 'boolean
384 :group 'js2-mode)
385
386 (defcustom js2-skip-preprocessor-directives nil
387 "Non-nil to treat lines beginning with # as comments.
388 Useful for viewing Mozilla JavaScript source code."
389 :type 'boolean
390 :group 'js2-mode)
391
392 (defcustom js2-language-version 200
393 "Configures what JavaScript language version to recognize.
394 Currently versions 150, 160, 170, 180 and 200 are supported,
395 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
396 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
397 yield, and Array comprehensions, and 1.8 adds function closures."
398 :type 'integer
399 :group 'js2-mode)
400
401 (defcustom js2-allow-keywords-as-property-names t
402 "If non-nil, you can use JavaScript keywords as object property names.
403 Examples:
404
405 var foo = {int: 5, while: 6, continue: 7};
406 foo.return = 8;
407
408 Ecma-262 forbids this syntax, but many browsers support it."
409 :type 'boolean
410 :group 'js2-mode)
411
412 (defcustom js2-instanceof-has-side-effects nil
413 "If non-nil, treats the instanceof operator as having side effects.
414 This is useful for xulrunner apps."
415 :type 'boolean
416 :group 'js2-mode)
417
418 (defcustom js2-cleanup-whitespace nil
419 "Non-nil to invoke `delete-trailing-whitespace' before saves."
420 :type 'boolean
421 :group 'js2-mode)
422
423 (make-obsolete-variable 'js2-cleanup-whitespace 'before-save-hook "1.0")
424
425 (defcustom js2-move-point-on-right-click t
426 "Non-nil to move insertion point when you right-click.
427 This makes right-click context menu behavior a bit more intuitive,
428 since menu operations generally apply to the point. The exception
429 is if there is a region selection, in which case the point does -not-
430 move, so cut/copy/paste etc. can work properly.
431
432 Note that IntelliJ moves the point, and Eclipse leaves it alone,
433 so this behavior is customizable."
434 :group 'js2-mode
435 :type 'boolean)
436
437 (defcustom js2-allow-rhino-new-expr-initializer t
438 "Non-nil to support a Rhino's experimental syntactic construct.
439
440 Rhino supports the ability to follow a `new' expression with an object
441 literal, which is used to set additional properties on the new object
442 after calling its constructor. Syntax:
443
444 new <expr> [ ( arglist ) ] [initializer]
445
446 Hence, this expression:
447
448 new Object {a: 1, b: 2}
449
450 results in an Object with properties a=1 and b=2. This syntax is
451 apparently not configurable in Rhino - it's currently always enabled,
452 as of Rhino version 1.7R2."
453 :type 'boolean
454 :group 'js2-mode)
455
456 (defcustom js2-allow-member-expr-as-function-name nil
457 "Non-nil to support experimental Rhino syntax for function names.
458
459 Rhino supports an experimental syntax configured via the Rhino Context
460 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
461
462 function <member-expr> ( [ arg-list ] ) { <body> }
463
464 Where member-expr is a non-parenthesized 'member expression', which
465 is anything at the grammar level of a new-expression or lower, meaning
466 any expression that does not involve infix or unary operators.
467
468 When <member-expr> is not a simple identifier, then it is syntactic
469 sugar for assigning the anonymous function to the <member-expr>. Hence,
470 this code:
471
472 function a.b().c[2] (x, y) { ... }
473
474 is rewritten as:
475
476 a.b().c[2] = function(x, y) {...}
477
478 which doesn't seem particularly useful, but Rhino permits it."
479 :type 'boolean
480 :group 'js2-mode)
481
482 ;; scanner variables
483
484 (defmacro js2-deflocal (name value &optional comment)
485 "Define a buffer-local variable NAME with VALUE and COMMENT."
486 `(progn
487 (defvar ,name ,value ,comment)
488 (make-variable-buffer-local ',name)))
489
490 ;; We record the start and end position of each token.
491 (js2-deflocal js2-token-beg 1)
492 (js2-deflocal js2-token-end -1)
493
494 (defvar js2-EOF_CHAR -1
495 "Represents end of stream. Distinct from js2-EOF token type.")
496
497 ;; I originally used symbols to represent tokens, but Rhino uses
498 ;; ints and then sets various flag bits in them, so ints it is.
499 ;; The upshot is that we need a `js2-' prefix in front of each name.
500 (defvar js2-ERROR -1)
501 (defvar js2-EOF 0)
502 (defvar js2-EOL 1)
503 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
504 (defvar js2-LEAVEWITH 3)
505 (defvar js2-RETURN 4)
506 (defvar js2-GOTO 5)
507 (defvar js2-IFEQ 6)
508 (defvar js2-IFNE 7)
509 (defvar js2-SETNAME 8)
510 (defvar js2-BITOR 9)
511 (defvar js2-BITXOR 10)
512 (defvar js2-BITAND 11)
513 (defvar js2-EQ 12)
514 (defvar js2-NE 13)
515 (defvar js2-LT 14)
516 (defvar js2-LE 15)
517 (defvar js2-GT 16)
518 (defvar js2-GE 17)
519 (defvar js2-LSH 18)
520 (defvar js2-RSH 19)
521 (defvar js2-URSH 20)
522 (defvar js2-ADD 21) ; infix plus
523 (defvar js2-SUB 22) ; infix minus
524 (defvar js2-MUL 23)
525 (defvar js2-DIV 24)
526 (defvar js2-MOD 25)
527 (defvar js2-NOT 26)
528 (defvar js2-BITNOT 27)
529 (defvar js2-POS 28) ; unary plus
530 (defvar js2-NEG 29) ; unary minus
531 (defvar js2-NEW 30)
532 (defvar js2-DELPROP 31)
533 (defvar js2-TYPEOF 32)
534 (defvar js2-GETPROP 33)
535 (defvar js2-GETPROPNOWARN 34)
536 (defvar js2-SETPROP 35)
537 (defvar js2-GETELEM 36)
538 (defvar js2-SETELEM 37)
539 (defvar js2-CALL 38)
540 (defvar js2-NAME 39) ; an identifier
541 (defvar js2-NUMBER 40)
542 (defvar js2-STRING 41)
543 (defvar js2-NULL 42)
544 (defvar js2-THIS 43)
545 (defvar js2-FALSE 44)
546 (defvar js2-TRUE 45)
547 (defvar js2-SHEQ 46) ; shallow equality (===)
548 (defvar js2-SHNE 47) ; shallow inequality (!==)
549 (defvar js2-REGEXP 48)
550 (defvar js2-BINDNAME 49)
551 (defvar js2-THROW 50)
552 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
553 (defvar js2-IN 52)
554 (defvar js2-INSTANCEOF 53)
555 (defvar js2-LOCAL_LOAD 54)
556 (defvar js2-GETVAR 55)
557 (defvar js2-SETVAR 56)
558 (defvar js2-CATCH_SCOPE 57)
559 (defvar js2-ENUM_INIT_KEYS 58)
560 (defvar js2-ENUM_INIT_VALUES 59)
561 (defvar js2-ENUM_INIT_ARRAY 60)
562 (defvar js2-ENUM_NEXT 61)
563 (defvar js2-ENUM_ID 62)
564 (defvar js2-THISFN 63)
565 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
566 (defvar js2-ARRAYLIT 65) ; array literal
567 (defvar js2-OBJECTLIT 66) ; object literal
568 (defvar js2-GET_REF 67) ; *reference
569 (defvar js2-SET_REF 68) ; *reference = something
570 (defvar js2-DEL_REF 69) ; delete reference
571 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
572 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
573 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
574
575 ;; XML support
576 (defvar js2-DEFAULTNAMESPACE 73)
577 (defvar js2-ESCXMLATTR 74)
578 (defvar js2-ESCXMLTEXT 75)
579 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
580 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
581 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
582 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
583
584 (defvar js2-first-bytecode js2-ENTERWITH)
585 (defvar js2-last-bytecode js2-REF_NS_NAME)
586
587 (defvar js2-TRY 80)
588 (defvar js2-SEMI 81) ; semicolon
589 (defvar js2-LB 82) ; left and right brackets
590 (defvar js2-RB 83)
591 (defvar js2-LC 84) ; left and right curly-braces
592 (defvar js2-RC 85)
593 (defvar js2-LP 86) ; left and right parens
594 (defvar js2-RP 87)
595 (defvar js2-COMMA 88) ; comma operator
596
597 (defvar js2-ASSIGN 89) ; simple assignment (=)
598 (defvar js2-ASSIGN_BITOR 90) ; |=
599 (defvar js2-ASSIGN_BITXOR 91) ; ^=
600 (defvar js2-ASSIGN_BITAND 92) ; &=
601 (defvar js2-ASSIGN_LSH 93) ; <<=
602 (defvar js2-ASSIGN_RSH 94) ; >>=
603 (defvar js2-ASSIGN_URSH 95) ; >>>=
604 (defvar js2-ASSIGN_ADD 96) ; +=
605 (defvar js2-ASSIGN_SUB 97) ; -=
606 (defvar js2-ASSIGN_MUL 98) ; *=
607 (defvar js2-ASSIGN_DIV 99) ; /=
608 (defvar js2-ASSIGN_MOD 100) ; %=
609
610 (defvar js2-first-assign js2-ASSIGN)
611 (defvar js2-last-assign js2-ASSIGN_MOD)
612
613 (defvar js2-HOOK 101) ; conditional (?:)
614 (defvar js2-COLON 102)
615 (defvar js2-OR 103) ; logical or (||)
616 (defvar js2-AND 104) ; logical and (&&)
617 (defvar js2-INC 105) ; increment/decrement (++ --)
618 (defvar js2-DEC 106)
619 (defvar js2-DOT 107) ; member operator (.)
620 (defvar js2-FUNCTION 108) ; function keyword
621 (defvar js2-EXPORT 109) ; export keyword
622 (defvar js2-IMPORT 110) ; import keyword
623 (defvar js2-IF 111) ; if keyword
624 (defvar js2-ELSE 112) ; else keyword
625 (defvar js2-SWITCH 113) ; switch keyword
626 (defvar js2-CASE 114) ; case keyword
627 (defvar js2-DEFAULT 115) ; default keyword
628 (defvar js2-WHILE 116) ; while keyword
629 (defvar js2-DO 117) ; do keyword
630 (defvar js2-FOR 118) ; for keyword
631 (defvar js2-BREAK 119) ; break keyword
632 (defvar js2-CONTINUE 120) ; continue keyword
633 (defvar js2-VAR 121) ; var keyword
634 (defvar js2-WITH 122) ; with keyword
635 (defvar js2-CATCH 123) ; catch keyword
636 (defvar js2-FINALLY 124) ; finally keyword
637 (defvar js2-VOID 125) ; void keyword
638 (defvar js2-RESERVED 126) ; reserved keywords
639
640 (defvar js2-EMPTY 127)
641
642 ;; Types used for the parse tree - never returned by scanner.
643
644 (defvar js2-BLOCK 128) ; statement block
645 (defvar js2-LABEL 129) ; label
646 (defvar js2-TARGET 130)
647 (defvar js2-LOOP 131)
648 (defvar js2-EXPR_VOID 132) ; expression statement in functions
649 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
650 (defvar js2-JSR 134)
651 (defvar js2-SCRIPT 135) ; top-level node for entire script
652 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
653 (defvar js2-USE_STACK 137)
654 (defvar js2-SETPROP_OP 138) ; x.y op= something
655 (defvar js2-SETELEM_OP 139) ; x[y] op= something
656 (defvar js2-LOCAL_BLOCK 140)
657 (defvar js2-SET_REF_OP 141) ; *reference op= something
658
659 ;; For XML support:
660 (defvar js2-DOTDOT 142) ; member operator (..)
661 (defvar js2-COLONCOLON 143) ; namespace::name
662 (defvar js2-XML 144) ; XML type
663 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
664 (defvar js2-XMLATTR 146) ; @
665 (defvar js2-XMLEND 147)
666
667 ;; Optimizer-only tokens
668 (defvar js2-TO_OBJECT 148)
669 (defvar js2-TO_DOUBLE 149)
670
671 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
672 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
673 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
674 (defvar js2-CONST 153)
675 (defvar js2-SETCONST 154)
676 (defvar js2-SETCONSTVAR 155)
677 (defvar js2-ARRAYCOMP 156)
678 (defvar js2-LETEXPR 157)
679 (defvar js2-WITHEXPR 158)
680 (defvar js2-DEBUGGER 159)
681
682 (defvar js2-COMMENT 160)
683 (defvar js2-ENUM 161) ; for "enum" reserved word
684 (defvar js2-TRIPLEDOT 162) ; for rest parameter
685
686 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
687
688 (defconst js2-debug-print-trees nil)
689
690 ;; Rhino accepts any string or stream as input. Emacs character
691 ;; processing works best in buffers, so we'll assume the input is a
692 ;; buffer. JavaScript strings can be copied into temp buffers before
693 ;; scanning them.
694
695 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
696 ;; They're the Emacs equivalent of instance variables, more or less.
697
698 (js2-deflocal js2-ts-dirty-line nil
699 "Token stream buffer-local variable.
700 Indicates stuff other than whitespace since start of line.")
701
702 (js2-deflocal js2-ts-regexp-flags nil
703 "Token stream buffer-local variable.")
704
705 (js2-deflocal js2-ts-string ""
706 "Token stream buffer-local variable.
707 Last string scanned.")
708
709 (js2-deflocal js2-ts-number nil
710 "Token stream buffer-local variable.
711 Last literal number scanned.")
712
713 (js2-deflocal js2-ts-hit-eof nil
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-line-start 0
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-lineno 1
720 "Token stream buffer-local variable.")
721
722 (js2-deflocal js2-ts-line-end-char -1
723 "Token stream buffer-local variable.")
724
725 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
726 "Token stream buffer-local variable.
727 Current scan position.")
728
729 (js2-deflocal js2-ts-is-xml-attribute nil
730 "Token stream buffer-local variable.")
731
732 (js2-deflocal js2-ts-xml-is-tag-content nil
733 "Token stream buffer-local variable.")
734
735 (js2-deflocal js2-ts-xml-open-tags-count 0
736 "Token stream buffer-local variable.")
737
738 (js2-deflocal js2-ts-string-buffer nil
739 "Token stream buffer-local variable.
740 List of chars built up while scanning various tokens.")
741
742 (js2-deflocal js2-ts-comment-type nil
743 "Token stream buffer-local variable.")
744
745 ;;; Parser variables
746
747 (js2-deflocal js2-parsed-errors nil
748 "List of errors produced during scanning/parsing.")
749
750 (js2-deflocal js2-parsed-warnings nil
751 "List of warnings produced during scanning/parsing.")
752
753 (js2-deflocal js2-recover-from-parse-errors t
754 "Non-nil to continue parsing after a syntax error.
755
756 In recovery mode, the AST will be built in full, and any error
757 nodes will be flagged with appropriate error information. If
758 this flag is nil, a syntax error will result in an error being
759 signaled.
760
761 The variable is automatically buffer-local, because different
762 modes that use the parser will need different settings.")
763
764 (js2-deflocal js2-parse-hook nil
765 "List of callbacks for receiving parsing progress.")
766
767 (defvar js2-parse-finished-hook nil
768 "List of callbacks to notify when parsing finishes.
769 Not called if parsing was interrupted.")
770
771 (js2-deflocal js2-is-eval-code nil
772 "True if we're evaluating code in a string.
773 If non-nil, the tokenizer will record the token text, and the AST nodes
774 will record their source text. Off by default for IDE modes, since the
775 text is available in the buffer.")
776
777 (defvar js2-parse-ide-mode t
778 "Non-nil if the parser is being used for `js2-mode'.
779 If non-nil, the parser will set text properties for fontification
780 and the syntax table. The value should be nil when using the
781 parser as a frontend to an interpreter or byte compiler.")
782
783 ;;; Parser instance variables (buffer-local vars for js2-parse)
784
785 (defconst js2-clear-ti-mask #xFFFF
786 "Mask to clear token information bits.")
787
788 (defconst js2-ti-after-eol (lsh 1 16)
789 "Flag: first token of the source line.")
790
791 (defconst js2-ti-check-label (lsh 1 17)
792 "Flag: indicates to check for label.")
793
794 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
795
796 (js2-deflocal js2-compiler-generate-debug-info t)
797 (js2-deflocal js2-compiler-use-dynamic-scope nil)
798 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
799 (js2-deflocal js2-compiler-xml-available t)
800 (js2-deflocal js2-compiler-optimization-level 0)
801 (js2-deflocal js2-compiler-generating-source t)
802 (js2-deflocal js2-compiler-strict-mode nil)
803 (js2-deflocal js2-compiler-report-warning-as-error nil)
804 (js2-deflocal js2-compiler-generate-observer-count nil)
805 (js2-deflocal js2-compiler-activation-names nil)
806
807 ;; SKIP: sourceURI
808
809 ;; There's a compileFunction method in Context.java - may need it.
810 (js2-deflocal js2-called-by-compile-function nil
811 "True if `js2-parse' was called by `js2-compile-function'.
812 Will only be used when we finish implementing the interpreter.")
813
814 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
815
816 (js2-deflocal js2-current-flagged-token js2-EOF)
817 (js2-deflocal js2-current-token js2-EOF)
818
819 ;; SKIP: node factory - we're going to just call functions directly,
820 ;; and eventually go to a unified AST format.
821
822 (js2-deflocal js2-nesting-of-function 0)
823
824 (js2-deflocal js2-recorded-identifiers nil
825 "Tracks identifiers found during parsing.")
826
827 (js2-deflocal js2-is-in-destructuring nil
828 "True while parsing destructuring expression.")
829
830 (defcustom js2-global-externs nil
831 "A list of any extern names you'd like to consider always declared.
832 This list is global and is used by all js2-mode files.
833 You can create buffer-local externs list using `js2-additional-externs'.
834
835 There is also a buffer-local variable `js2-default-externs',
836 which is initialized by default to include the Ecma-262 externs
837 and the standard browser externs. The three lists are all
838 checked during highlighting."
839 :type 'list
840 :group 'js2-mode)
841
842 (js2-deflocal js2-default-externs nil
843 "Default external declarations.
844
845 These are currently only used for highlighting undeclared variables,
846 which only worries about top-level (unqualified) references.
847 As js2-mode's processing improves, we will flesh out this list.
848
849 The initial value is set to `js2-ecma-262-externs', unless you
850 have set `js2-include-browser-externs', in which case the browser
851 externs are also included.
852
853 See `js2-additional-externs' for more information.")
854
855 (defcustom js2-include-browser-externs t
856 "Non-nil to include browser externs in the master externs list.
857 If you work on JavaScript files that are not intended for browsers,
858 such as Mozilla Rhino server-side JavaScript, set this to nil.
859 You can always include them on a per-file basis by calling
860 `js2-add-browser-externs' from a function on `js2-mode-hook'.
861
862 See `js2-additional-externs' for more information about externs."
863 :type 'boolean
864 :group 'js2-mode)
865
866 (defcustom js2-include-rhino-externs t
867 "Non-nil to include Mozilla Rhino externs in the master externs list.
868 See `js2-additional-externs' for more information about externs."
869 :type 'boolean
870 :group 'js2-mode)
871
872 (defcustom js2-include-gears-externs t
873 "Non-nil to include Google Gears externs in the master externs list.
874 See `js2-additional-externs' for more information about externs."
875 :type 'boolean
876 :group 'js2-mode)
877
878 (js2-deflocal js2-additional-externs nil
879 "A buffer-local list of additional external declarations.
880 It is used to decide whether variables are considered undeclared
881 for purposes of highlighting.
882
883 Each entry is a lisp string. The string should be the fully qualified
884 name of an external entity. All externs should be added to this list,
885 so that as js2-mode's processing improves it can take advantage of them.
886
887 You may want to declare your externs in three ways.
888 First, you can add externs that are valid for all your JavaScript files.
889 You should probably do this by adding them to `js2-global-externs', which
890 is a global list used for all js2-mode files.
891
892 Next, you can add a function to `js2-mode-hook' that adds additional
893 externs appropriate for the specific file, perhaps based on its path.
894 These should go in `js2-additional-externs', which is buffer-local.
895
896 Finally, you can add a function to `js2-post-parse-callbacks',
897 which is called after parsing completes, and `js2-mode-ast' is bound to
898 the root of the parse tree. At this stage you can set up an AST
899 node visitor using `js2-visit-ast' and examine the parse tree
900 for specific import patterns that may imply the existence of
901 other externs, possibly tied to your build system. These should also
902 be added to `js2-additional-externs'.
903
904 Your post-parse callback may of course also use the simpler and
905 faster (but perhaps less robust) approach of simply scanning the
906 buffer text for your imports, using regular expressions.")
907
908 ;; SKIP: decompiler
909 ;; SKIP: encoded-source
910
911 ;;; The following variables are per-function and should be saved/restored
912 ;;; during function parsing...
913
914 (js2-deflocal js2-current-script-or-fn nil)
915 (js2-deflocal js2-current-scope nil)
916 (js2-deflocal js2-nesting-of-with 0)
917 (js2-deflocal js2-label-set nil
918 "An alist mapping label names to nodes.")
919
920 (js2-deflocal js2-loop-set nil)
921 (js2-deflocal js2-loop-and-switch-set nil)
922 (js2-deflocal js2-has-return-value nil)
923 (js2-deflocal js2-end-flags 0)
924
925 ;;; ...end of per function variables
926
927 ;; Without 2-token lookahead, labels are a problem.
928 ;; These vars store the token info of the last matched name,
929 ;; iff it wasn't the last matched token. Only valid in some contexts.
930 (defvar js2-prev-name-token-start nil)
931 (defvar js2-prev-name-token-string nil)
932
933 (defsubst js2-save-name-token-data (pos name)
934 (setq js2-prev-name-token-start pos
935 js2-prev-name-token-string name))
936
937 ;; These flags enumerate the possible ways a statement/function can
938 ;; terminate. These flags are used by endCheck() and by the Parser to
939 ;; detect inconsistent return usage.
940 ;;
941 ;; END_UNREACHED is reserved for code paths that are assumed to always be
942 ;; able to execute (example: throw, continue)
943 ;;
944 ;; END_DROPS_OFF indicates if the statement can transfer control to the
945 ;; next one. Statement such as return dont. A compound statement may have
946 ;; some branch that drops off control to the next statement.
947 ;;
948 ;; END_RETURNS indicates that the statement can return (without arguments)
949 ;; END_RETURNS_VALUE indicates that the statement can return a value.
950 ;;
951 ;; A compound statement such as
952 ;; if (condition) {
953 ;; return value;
954 ;; }
955 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
956
957 (defconst js2-end-unreached #x0)
958 (defconst js2-end-drops-off #x1)
959 (defconst js2-end-returns #x2)
960 (defconst js2-end-returns-value #x4)
961 (defconst js2-end-yields #x8)
962
963 ;; Rhino awkwardly passes a statementLabel parameter to the
964 ;; statementHelper() function, the main statement parser, which
965 ;; is then used by quite a few of the sub-parsers. We just make
966 ;; it a buffer-local variable and make sure it's cleaned up properly.
967 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
968
969 ;; Similarly, Rhino passes an inForInit boolean through about half
970 ;; the expression parsers. We use a dynamically-scoped variable,
971 ;; which makes it easier to funcall the parsers individually without
972 ;; worrying about whether they take the parameter or not.
973 (js2-deflocal js2-in-for-init nil)
974 (js2-deflocal js2-temp-name-counter 0)
975 (js2-deflocal js2-parse-stmt-count 0)
976
977 (defsubst js2-get-next-temp-name ()
978 (format "$%d" (incf js2-temp-name-counter)))
979
980 (defvar js2-parse-interruptable-p t
981 "Set this to nil to force parse to continue until finished.
982 This will mostly be useful for interpreters.")
983
984 (defvar js2-statements-per-pause 50
985 "Pause after this many statements to check for user input.
986 If user input is pending, stop the parse and discard the tree.
987 This makes for a smoother user experience for large files.
988 You may have to wait a second or two before the highlighting
989 and error-reporting appear, but you can always type ahead if
990 you wish. This appears to be more or less how Eclipse, IntelliJ
991 and other editors work.")
992
993 (js2-deflocal js2-record-comments t
994 "Instructs the scanner to record comments in `js2-scanned-comments'.")
995
996 (js2-deflocal js2-scanned-comments nil
997 "List of all comments from the current parse.")
998
999 (defcustom js2-mode-indent-inhibit-undo nil
1000 "Non-nil to disable collection of Undo information when indenting lines.
1001 Some users have requested this behavior. It's nil by default because
1002 other Emacs modes don't work this way."
1003 :type 'boolean
1004 :group 'js2-mode)
1005
1006 (defcustom js2-mode-indent-ignore-first-tab nil
1007 "If non-nil, ignore first TAB keypress if we look indented properly.
1008 It's fairly common for users to navigate to an already-indented line
1009 and press TAB for reassurance that it's been indented. For this class
1010 of users, we want the first TAB press on a line to be ignored if the
1011 line is already indented to one of the precomputed alternatives.
1012
1013 This behavior is only partly implemented. If you TAB-indent a line,
1014 navigate to another line, and then navigate back, it fails to clear
1015 the last-indented variable, so it thinks you've already hit TAB once,
1016 and performs the indent. A full solution would involve getting on the
1017 point-motion hooks for the entire buffer. If we come across another
1018 use cases that requires watching point motion, I'll consider doing it.
1019
1020 If you set this variable to nil, then the TAB key will always change
1021 the indentation of the current line, if more than one alternative
1022 indentation spot exists."
1023 :type 'boolean
1024 :group 'js2-mode)
1025
1026 (defvar js2-indent-hook nil
1027 "A hook for user-defined indentation rules.
1028
1029 Functions on this hook should expect two arguments: (LIST INDEX)
1030 The LIST argument is the list of computed indentation points for
1031 the current line. INDEX is the list index of the indentation point
1032 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1033 indent function is not going to change the current line indentation.
1034
1035 If a hook function on this list returns a non-nil value, then
1036 `js2-bounce-indent' assumes the hook function has performed its own
1037 indentation, and will do nothing. If all hook functions on the list
1038 return nil, then `js2-bounce-indent' will use its computed indentation
1039 and reindent the line.
1040
1041 When hook functions on this hook list are called, the variable
1042 `js2-mode-ast' may or may not be set, depending on whether the
1043 parse tree is available. If the variable is nil, you can pass a
1044 callback to `js2-mode-wait-for-parse', and your callback will be
1045 called after the new parse tree is built. This can take some time
1046 in large files.")
1047
1048 (defface js2-warning-face
1049 `((((class color) (background light))
1050 (:underline "orange"))
1051 (((class color) (background dark))
1052 (:underline "orange"))
1053 (t (:underline t)))
1054 "Face for JavaScript warnings."
1055 :group 'js2-mode)
1056
1057 (defface js2-error-face
1058 `((((class color) (background light))
1059 (:foreground "red"))
1060 (((class color) (background dark))
1061 (:foreground "red"))
1062 (t (:foreground "red")))
1063 "Face for JavaScript errors."
1064 :group 'js2-mode)
1065
1066 (defface js2-jsdoc-tag-face
1067 '((t :foreground "SlateGray"))
1068 "Face used to highlight @whatever tags in jsdoc comments."
1069 :group 'js2-mode)
1070
1071 (defface js2-jsdoc-type-face
1072 '((t :foreground "SteelBlue"))
1073 "Face used to highlight {FooBar} types in jsdoc comments."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-value-face
1077 '((t :foreground "PeachPuff3"))
1078 "Face used to highlight tag values in jsdoc comments."
1079 :group 'js2-mode)
1080
1081 (defface js2-function-param-face
1082 '((t :foreground "SeaGreen"))
1083 "Face used to highlight function parameters in javascript."
1084 :group 'js2-mode)
1085
1086 (defface js2-instance-member-face
1087 '((t :foreground "DarkOrchid"))
1088 "Face used to highlight instance variables in javascript.
1089 Not currently used."
1090 :group 'js2-mode)
1091
1092 (defface js2-private-member-face
1093 '((t :foreground "PeachPuff3"))
1094 "Face used to highlight calls to private methods in javascript.
1095 Not currently used."
1096 :group 'js2-mode)
1097
1098 (defface js2-private-function-call-face
1099 '((t :foreground "goldenrod"))
1100 "Face used to highlight calls to private functions in javascript.
1101 Not currently used."
1102 :group 'js2-mode)
1103
1104 (defface js2-jsdoc-html-tag-name-face
1105 (if js2-emacs22
1106 '((((class color) (min-colors 88) (background light))
1107 (:foreground "rosybrown"))
1108 (((class color) (min-colors 8) (background dark))
1109 (:foreground "yellow"))
1110 (((class color) (min-colors 8) (background light))
1111 (:foreground "magenta")))
1112 '((((type tty pc) (class color) (background light))
1113 (:foreground "magenta"))
1114 (((type tty pc) (class color) (background dark))
1115 (:foreground "yellow"))
1116 (t (:foreground "RosyBrown"))))
1117 "Face used to highlight jsdoc html tag names"
1118 :group 'js2-mode)
1119
1120 (defface js2-jsdoc-html-tag-delimiter-face
1121 (if js2-emacs22
1122 '((((class color) (min-colors 88) (background light))
1123 (:foreground "dark khaki"))
1124 (((class color) (min-colors 8) (background dark))
1125 (:foreground "green"))
1126 (((class color) (min-colors 8) (background light))
1127 (:foreground "green")))
1128 '((((type tty pc) (class color) (background light))
1129 (:foreground "green"))
1130 (((type tty pc) (class color) (background dark))
1131 (:foreground "green"))
1132 (t (:foreground "dark khaki"))))
1133 "Face used to highlight brackets in jsdoc html tags."
1134 :group 'js2-mode)
1135
1136 (defface js2-magic-paren-face
1137 '((t :underline t))
1138 "Face used to color parens that will be auto-overwritten."
1139 :group 'js2-mode)
1140
1141 (defcustom js2-post-parse-callbacks nil
1142 "A list of callback functions invoked after parsing finishes.
1143 Currently, the main use for this function is to add synthetic
1144 declarations to `js2-recorded-identifiers', which see."
1145 :type 'list
1146 :group 'js2-mode)
1147
1148 (defface js2-external-variable-face
1149 '((t :foreground "orange"))
1150 "Face used to highlight undeclared variable identifiers.
1151 An undeclared variable is any variable not declared with var or let
1152 in the current scope or any lexically enclosing scope. If you use
1153 such a variable, then you are either expecting it to originate from
1154 another file, or you've got a potential bug."
1155 :group 'js2-mode)
1156
1157 (defcustom js2-highlight-external-variables t
1158 "Non-nil to highlight undeclared variable identifiers."
1159 :type 'boolean
1160 :group 'js2-mode)
1161
1162 (defcustom js2-auto-insert-catch-block t
1163 "Non-nil to insert matching catch block on open-curly after `try'."
1164 :type 'boolean
1165 :group 'js2-mode)
1166
1167 (defvar js2-mode-map
1168 (let ((map (make-sparse-keymap))
1169 keys)
1170 (define-key map [mouse-1] #'js2-mode-show-node)
1171 (define-key map (kbd "C-m") #'js2-enter-key)
1172 (when js2-rebind-eol-bol-keys
1173 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1174 (define-key map (kbd "C-e") #'js2-end-of-line))
1175 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1176 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1177 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1178 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1179 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1180 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1181 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1182 (define-key map (kbd "C-c C-`") #'js2-next-error)
1183 (define-key map (or (car (where-is-internal #'mark-defun))
1184 (kbd "M-C-h"))
1185 #'js2-mark-defun)
1186 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1187 (kbd "C-x nd"))
1188 #'js2-narrow-to-defun)
1189 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1190 (when js2-auto-indent-p
1191 (mapc (lambda (key)
1192 (define-key map key #'js2-insert-and-indent))
1193 js2-electric-keys))
1194 (when js2-bounce-indent-p
1195 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1196
1197 (define-key map [menu-bar javascript]
1198 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1199
1200 (define-key map [menu-bar javascript customize-js2-mode]
1201 '(menu-item "Customize js2-mode" js2-mode-customize
1202 :help "Customize the behavior of this mode"))
1203
1204 (define-key map [menu-bar javascript js2-force-refresh]
1205 '(menu-item "Force buffer refresh" js2-mode-reset
1206 :help "Re-parse the buffer from scratch"))
1207
1208 (define-key map [menu-bar javascript separator-2]
1209 '("--"))
1210
1211 (define-key map [menu-bar javascript next-error]
1212 '(menu-item "Next warning or error" js2-next-error
1213 :enabled (and js2-mode-ast
1214 (or (js2-ast-root-errors js2-mode-ast)
1215 (js2-ast-root-warnings js2-mode-ast)))
1216 :help "Move to next warning or error"))
1217
1218 (define-key map [menu-bar javascript display-errors]
1219 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1220 :visible (not js2-mode-show-parse-errors)
1221 :help "Turn on display of warnings and errors"))
1222
1223 (define-key map [menu-bar javascript hide-errors]
1224 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1225 :visible js2-mode-show-parse-errors
1226 :help "Turn off display of warnings and errors"))
1227
1228 (define-key map [menu-bar javascript separator-1]
1229 '("--"))
1230
1231 (define-key map [menu-bar javascript js2-toggle-function]
1232 '(menu-item "Show/collapse element" js2-mode-toggle-element
1233 :help "Hide or show function body or comment"))
1234
1235 (define-key map [menu-bar javascript show-comments]
1236 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1237 :visible js2-mode-comments-hidden
1238 :help "Expand all hidden block comments"))
1239
1240 (define-key map [menu-bar javascript hide-comments]
1241 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1242 :visible (not js2-mode-comments-hidden)
1243 :help "Show block comments as /*...*/"))
1244
1245 (define-key map [menu-bar javascript show-all-functions]
1246 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1247 :visible js2-mode-functions-hidden
1248 :help "Expand all hidden function bodies"))
1249
1250 (define-key map [menu-bar javascript hide-all-functions]
1251 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1252 :visible (not js2-mode-functions-hidden)
1253 :help "Show {...} for all top-level function bodies"))
1254
1255 map)
1256 "Keymap used in `js2-mode' buffers.")
1257
1258 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1259
1260 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1261 "Matches a //-comment line. Must be first non-whitespace on line.
1262 First match-group is the leading whitespace.")
1263
1264 (defvar js2-mode-hook nil)
1265
1266 (js2-deflocal js2-mode-ast nil "Private variable.")
1267 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1268 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1269 (js2-deflocal js2-mode-parsing nil "Private variable.")
1270 (js2-deflocal js2-mode-node-overlay nil)
1271
1272 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1273 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1274
1275 (js2-deflocal js2-mode-fontifications nil "Private variable")
1276 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1277 (js2-deflocal js2-imenu-recorder nil "Private variable")
1278 (js2-deflocal js2-imenu-function-map nil "Private variable")
1279
1280 (defvar js2-paragraph-start
1281 "\\(@[a-zA-Z]+\\>\\|$\\)")
1282
1283 ;; Note that we also set a 'c-in-sws text property in html comments,
1284 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1285 (defvar js2-syntactic-ws-start
1286 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1287
1288 (defvar js2-syntactic-ws-end
1289 "\\s \\|[\n\r/]\\|\\s!")
1290
1291 (defvar js2-syntactic-eol
1292 (concat "\\s *\\(/\\*[^*\n\r]*"
1293 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1294 "\\*+/\\s *\\)*"
1295 "\\(//\\|/\\*[^*\n\r]*"
1296 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1297 "\\|\\\\$\\|$\\)")
1298 "Copied from `java-mode'. Needed for some cc-engine functions.")
1299
1300 (defvar js2-comment-prefix-regexp
1301 "//+\\|\\**")
1302
1303 (defvar js2-comment-start-skip
1304 "\\(//+\\|/\\*+\\)\\s *")
1305
1306 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1307 "Non-nil to emit status messages during parsing.")
1308
1309 (defvar js2-mode-functions-hidden nil "private variable")
1310 (defvar js2-mode-comments-hidden nil "private variable")
1311
1312 (defvar js2-mode-syntax-table
1313 (let ((table (make-syntax-table)))
1314 (c-populate-syntax-table table)
1315 table)
1316 "Syntax table used in js2-mode buffers.")
1317
1318 (defvar js2-mode-abbrev-table nil
1319 "Abbrev table in use in `js2-mode' buffers.")
1320 (define-abbrev-table 'js2-mode-abbrev-table ())
1321
1322 (defvar js2-mode-pending-parse-callbacks nil
1323 "List of functions waiting to be notified that parse is finished.")
1324
1325 (defvar js2-mode-last-indented-line -1)
1326
1327 ;;; Localizable error and warning messages
1328
1329 ;; Messages are copied from Rhino's Messages.properties.
1330 ;; Many of the Java-specific messages have been elided.
1331 ;; Add any js2-specific ones at the end, so we can keep
1332 ;; this file synced with changes to Rhino's.
1333
1334 (defvar js2-message-table
1335 (make-hash-table :test 'equal :size 250)
1336 "Contains localized messages for js2-mode.")
1337
1338 ;; TODO(stevey): construct this table at compile-time.
1339 (defmacro js2-msg (key &rest strings)
1340 `(puthash ,key (funcall #'concat ,@strings)
1341 js2-message-table))
1342
1343 (defun js2-get-msg (msg-key)
1344 "Look up a localized message.
1345 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1346 the correct number of ARGS must be provided."
1347 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1348 (args (if (listp msg-key) (cdr msg-key)))
1349 (msg (gethash key js2-message-table)))
1350 (if msg
1351 (apply #'format msg args)
1352 key))) ; default to showing the key
1353
1354 (js2-msg "msg.dup.parms"
1355 "Duplicate parameter name '%s'.")
1356
1357 (js2-msg "msg.too.big.jump"
1358 "Program too complex: jump offset too big.")
1359
1360 (js2-msg "msg.too.big.index"
1361 "Program too complex: internal index exceeds 64K limit.")
1362
1363 (js2-msg "msg.while.compiling.fn"
1364 "Encountered code generation error while compiling function '%s': %s")
1365
1366 (js2-msg "msg.while.compiling.script"
1367 "Encountered code generation error while compiling script: %s")
1368
1369 ;; Context
1370 (js2-msg "msg.ctor.not.found"
1371 "Constructor for '%s' not found.")
1372
1373 (js2-msg "msg.not.ctor"
1374 "'%s' is not a constructor.")
1375
1376 ;; FunctionObject
1377 (js2-msg "msg.varargs.ctor"
1378 "Method or constructor '%s' must be static "
1379 "with the signature (Context cx, Object[] args, "
1380 "Function ctorObj, boolean inNewExpr) "
1381 "to define a variable arguments constructor.")
1382
1383 (js2-msg "msg.varargs.fun"
1384 "Method '%s' must be static with the signature "
1385 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1386 "to define a variable arguments function.")
1387
1388 (js2-msg "msg.incompat.call"
1389 "Method '%s' called on incompatible object.")
1390
1391 (js2-msg "msg.bad.parms"
1392 "Unsupported parameter type '%s' in method '%s'.")
1393
1394 (js2-msg "msg.bad.method.return"
1395 "Unsupported return type '%s' in method '%s'.")
1396
1397 (js2-msg "msg.bad.ctor.return"
1398 "Construction of objects of type '%s' is not supported.")
1399
1400 (js2-msg "msg.no.overload"
1401 "Method '%s' occurs multiple times in class '%s'.")
1402
1403 (js2-msg "msg.method.not.found"
1404 "Method '%s' not found in '%s'.")
1405
1406 ;; IRFactory
1407
1408 (js2-msg "msg.bad.for.in.lhs"
1409 "Invalid left-hand side of for..in loop.")
1410
1411 (js2-msg "msg.mult.index"
1412 "Only one variable allowed in for..in loop.")
1413
1414 (js2-msg "msg.bad.for.in.destruct"
1415 "Left hand side of for..in loop must be an array of "
1416 "length 2 to accept key/value pair.")
1417
1418 (js2-msg "msg.cant.convert"
1419 "Can't convert to type '%s'.")
1420
1421 (js2-msg "msg.bad.assign.left"
1422 "Invalid assignment left-hand side.")
1423
1424 (js2-msg "msg.bad.decr"
1425 "Invalid decerement operand.")
1426
1427 (js2-msg "msg.bad.incr"
1428 "Invalid increment operand.")
1429
1430 (js2-msg "msg.bad.yield"
1431 "yield must be in a function.")
1432
1433 (js2-msg "msg.yield.parenthesized"
1434 "yield expression must be parenthesized.")
1435
1436 ;; NativeGlobal
1437 (js2-msg "msg.cant.call.indirect"
1438 "Function '%s' must be called directly, and not by way of a "
1439 "function of another name.")
1440
1441 (js2-msg "msg.eval.nonstring"
1442 "Calling eval() with anything other than a primitive "
1443 "string value will simply return the value. "
1444 "Is this what you intended?")
1445
1446 (js2-msg "msg.eval.nonstring.strict"
1447 "Calling eval() with anything other than a primitive "
1448 "string value is not allowed in strict mode.")
1449
1450 (js2-msg "msg.bad.destruct.op"
1451 "Invalid destructuring assignment operator")
1452
1453 ;; NativeCall
1454 (js2-msg "msg.only.from.new"
1455 "'%s' may only be invoked from a `new' expression.")
1456
1457 (js2-msg "msg.deprec.ctor"
1458 "The '%s' constructor is deprecated.")
1459
1460 ;; NativeFunction
1461 (js2-msg "msg.no.function.ref.found"
1462 "no source found to decompile function reference %s")
1463
1464 (js2-msg "msg.arg.isnt.array"
1465 "second argument to Function.prototype.apply must be an array")
1466
1467 ;; NativeGlobal
1468 (js2-msg "msg.bad.esc.mask"
1469 "invalid string escape mask")
1470
1471 ;; NativeRegExp
1472 (js2-msg "msg.bad.quant"
1473 "Invalid quantifier %s")
1474
1475 (js2-msg "msg.overlarge.backref"
1476 "Overly large back reference %s")
1477
1478 (js2-msg "msg.overlarge.min"
1479 "Overly large minimum %s")
1480
1481 (js2-msg "msg.overlarge.max"
1482 "Overly large maximum %s")
1483
1484 (js2-msg "msg.zero.quant"
1485 "Zero quantifier %s")
1486
1487 (js2-msg "msg.max.lt.min"
1488 "Maximum %s less than minimum")
1489
1490 (js2-msg "msg.unterm.quant"
1491 "Unterminated quantifier %s")
1492
1493 (js2-msg "msg.unterm.paren"
1494 "Unterminated parenthetical %s")
1495
1496 (js2-msg "msg.unterm.class"
1497 "Unterminated character class %s")
1498
1499 (js2-msg "msg.bad.range"
1500 "Invalid range in character class.")
1501
1502 (js2-msg "msg.trail.backslash"
1503 "Trailing \\ in regular expression.")
1504
1505 (js2-msg "msg.re.unmatched.right.paren"
1506 "unmatched ) in regular expression.")
1507
1508 (js2-msg "msg.no.regexp"
1509 "Regular expressions are not available.")
1510
1511 (js2-msg "msg.bad.backref"
1512 "back-reference exceeds number of capturing parentheses.")
1513
1514 (js2-msg "msg.bad.regexp.compile"
1515 "Only one argument may be specified if the first "
1516 "argument to RegExp.prototype.compile is a RegExp object.")
1517
1518 ;; Parser
1519 (js2-msg "msg.got.syntax.errors"
1520 "Compilation produced %s syntax errors.")
1521
1522 (js2-msg "msg.var.redecl"
1523 "TypeError: redeclaration of var %s.")
1524
1525 (js2-msg "msg.const.redecl"
1526 "TypeError: redeclaration of const %s.")
1527
1528 (js2-msg "msg.let.redecl"
1529 "TypeError: redeclaration of variable %s.")
1530
1531 (js2-msg "msg.parm.redecl"
1532 "TypeError: redeclaration of formal parameter %s.")
1533
1534 (js2-msg "msg.fn.redecl"
1535 "TypeError: redeclaration of function %s.")
1536
1537 (js2-msg "msg.let.decl.not.in.block"
1538 "SyntaxError: let declaration not directly within block")
1539
1540 ;; NodeTransformer
1541 (js2-msg "msg.dup.label"
1542 "duplicated label")
1543
1544 (js2-msg "msg.undef.label"
1545 "undefined label")
1546
1547 (js2-msg "msg.bad.break"
1548 "unlabelled break must be inside loop or switch")
1549
1550 (js2-msg "msg.continue.outside"
1551 "continue must be inside loop")
1552
1553 (js2-msg "msg.continue.nonloop"
1554 "continue can only use labels of iteration statements")
1555
1556 (js2-msg "msg.bad.throw.eol"
1557 "Line terminator is not allowed between the throw "
1558 "keyword and throw expression.")
1559
1560 (js2-msg "msg.no.paren.parms"
1561 "missing ( before function parameters.")
1562
1563 (js2-msg "msg.no.parm"
1564 "missing formal parameter")
1565
1566 (js2-msg "msg.no.paren.after.parms"
1567 "missing ) after formal parameters")
1568
1569 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1570 "parameter without default follows parameter with default")
1571
1572 (js2-msg "msg.param.after.rest" ; added by js2-mode
1573 "parameter after rest parameter")
1574
1575 (js2-msg "msg.no.brace.body"
1576 "missing '{' before function body")
1577
1578 (js2-msg "msg.no.brace.after.body"
1579 "missing } after function body")
1580
1581 (js2-msg "msg.no.paren.cond"
1582 "missing ( before condition")
1583
1584 (js2-msg "msg.no.paren.after.cond"
1585 "missing ) after condition")
1586
1587 (js2-msg "msg.no.semi.stmt"
1588 "missing ; before statement")
1589
1590 (js2-msg "msg.missing.semi"
1591 "missing ; after statement")
1592
1593 (js2-msg "msg.no.name.after.dot"
1594 "missing name after . operator")
1595
1596 (js2-msg "msg.no.name.after.coloncolon"
1597 "missing name after :: operator")
1598
1599 (js2-msg "msg.no.name.after.dotdot"
1600 "missing name after .. operator")
1601
1602 (js2-msg "msg.no.name.after.xmlAttr"
1603 "missing name after .@")
1604
1605 (js2-msg "msg.no.bracket.index"
1606 "missing ] in index expression")
1607
1608 (js2-msg "msg.no.paren.switch"
1609 "missing ( before switch expression")
1610
1611 (js2-msg "msg.no.paren.after.switch"
1612 "missing ) after switch expression")
1613
1614 (js2-msg "msg.no.brace.switch"
1615 "missing '{' before switch body")
1616
1617 (js2-msg "msg.bad.switch"
1618 "invalid switch statement")
1619
1620 (js2-msg "msg.no.colon.case"
1621 "missing : after case expression")
1622
1623 (js2-msg "msg.double.switch.default"
1624 "double default label in the switch statement")
1625
1626 (js2-msg "msg.no.while.do"
1627 "missing while after do-loop body")
1628
1629 (js2-msg "msg.no.paren.for"
1630 "missing ( after for")
1631
1632 (js2-msg "msg.no.semi.for"
1633 "missing ; after for-loop initializer")
1634
1635 (js2-msg "msg.no.semi.for.cond"
1636 "missing ; after for-loop condition")
1637
1638 (js2-msg "msg.in.after.for.name"
1639 "missing in or of after for")
1640
1641 (js2-msg "msg.no.paren.for.ctrl"
1642 "missing ) after for-loop control")
1643
1644 (js2-msg "msg.no.paren.with"
1645 "missing ( before with-statement object")
1646
1647 (js2-msg "msg.no.paren.after.with"
1648 "missing ) after with-statement object")
1649
1650 (js2-msg "msg.no.paren.after.let"
1651 "missing ( after let")
1652
1653 (js2-msg "msg.no.paren.let"
1654 "missing ) after variable list")
1655
1656 (js2-msg "msg.no.curly.let"
1657 "missing } after let statement")
1658
1659 (js2-msg "msg.bad.return"
1660 "invalid return")
1661
1662 (js2-msg "msg.no.brace.block"
1663 "missing } in compound statement")
1664
1665 (js2-msg "msg.bad.label"
1666 "invalid label")
1667
1668 (js2-msg "msg.bad.var"
1669 "missing variable name")
1670
1671 (js2-msg "msg.bad.var.init"
1672 "invalid variable initialization")
1673
1674 (js2-msg "msg.no.colon.cond"
1675 "missing : in conditional expression")
1676
1677 (js2-msg "msg.no.paren.arg"
1678 "missing ) after argument list")
1679
1680 (js2-msg "msg.no.bracket.arg"
1681 "missing ] after element list")
1682
1683 (js2-msg "msg.bad.prop"
1684 "invalid property id")
1685
1686 (js2-msg "msg.no.colon.prop"
1687 "missing : after property id")
1688
1689 (js2-msg "msg.no.brace.prop"
1690 "missing } after property list")
1691
1692 (js2-msg "msg.no.paren"
1693 "missing ) in parenthetical")
1694
1695 (js2-msg "msg.reserved.id"
1696 "identifier is a reserved word")
1697
1698 (js2-msg "msg.no.paren.catch"
1699 "missing ( before catch-block condition")
1700
1701 (js2-msg "msg.bad.catchcond"
1702 "invalid catch block condition")
1703
1704 (js2-msg "msg.catch.unreachable"
1705 "any catch clauses following an unqualified catch are unreachable")
1706
1707 (js2-msg "msg.no.brace.try"
1708 "missing '{' before try block")
1709
1710 (js2-msg "msg.no.brace.catchblock"
1711 "missing '{' before catch-block body")
1712
1713 (js2-msg "msg.try.no.catchfinally"
1714 "'try' without 'catch' or 'finally'")
1715
1716 (js2-msg "msg.no.return.value"
1717 "function %s does not always return a value")
1718
1719 (js2-msg "msg.anon.no.return.value"
1720 "anonymous function does not always return a value")
1721
1722 (js2-msg "msg.return.inconsistent"
1723 "return statement is inconsistent with previous usage")
1724
1725 (js2-msg "msg.generator.returns"
1726 "TypeError: generator function '%s' returns a value")
1727
1728 (js2-msg "msg.anon.generator.returns"
1729 "TypeError: anonymous generator function returns a value")
1730
1731 (js2-msg "msg.syntax"
1732 "syntax error")
1733
1734 (js2-msg "msg.unexpected.eof"
1735 "Unexpected end of file")
1736
1737 (js2-msg "msg.XML.bad.form"
1738 "illegally formed XML syntax")
1739
1740 (js2-msg "msg.XML.not.available"
1741 "XML runtime not available")
1742
1743 (js2-msg "msg.too.deep.parser.recursion"
1744 "Too deep recursion while parsing")
1745
1746 (js2-msg "msg.no.side.effects"
1747 "Code has no side effects")
1748
1749 (js2-msg "msg.extra.trailing.comma"
1750 "Trailing comma is not supported in some browsers")
1751
1752 (js2-msg "msg.array.trailing.comma"
1753 "Trailing comma yields different behavior across browsers")
1754
1755 (js2-msg "msg.equal.as.assign"
1756 (concat "Test for equality (==) mistyped as assignment (=)?"
1757 " (parenthesize to suppress warning)"))
1758
1759 (js2-msg "msg.var.hides.arg"
1760 "Variable %s hides argument")
1761
1762 (js2-msg "msg.destruct.assign.no.init"
1763 "Missing = in destructuring declaration")
1764
1765 ;; ScriptRuntime
1766 (js2-msg "msg.no.properties"
1767 "%s has no properties.")
1768
1769 (js2-msg "msg.invalid.iterator"
1770 "Invalid iterator value")
1771
1772 (js2-msg "msg.iterator.primitive"
1773 "__iterator__ returned a primitive value")
1774
1775 (js2-msg "msg.assn.create.strict"
1776 "Assignment to undeclared variable %s")
1777
1778 (js2-msg "msg.ref.undefined.prop"
1779 "Reference to undefined property '%s'")
1780
1781 (js2-msg "msg.prop.not.found"
1782 "Property %s not found.")
1783
1784 (js2-msg "msg.invalid.type"
1785 "Invalid JavaScript value of type %s")
1786
1787 (js2-msg "msg.primitive.expected"
1788 "Primitive type expected (had %s instead)")
1789
1790 (js2-msg "msg.namespace.expected"
1791 "Namespace object expected to left of :: (found %s instead)")
1792
1793 (js2-msg "msg.null.to.object"
1794 "Cannot convert null to an object.")
1795
1796 (js2-msg "msg.undef.to.object"
1797 "Cannot convert undefined to an object.")
1798
1799 (js2-msg "msg.cyclic.value"
1800 "Cyclic %s value not allowed.")
1801
1802 (js2-msg "msg.is.not.defined"
1803 "'%s' is not defined.")
1804
1805 (js2-msg "msg.undef.prop.read"
1806 "Cannot read property '%s' from %s")
1807
1808 (js2-msg "msg.undef.prop.write"
1809 "Cannot set property '%s' of %s to '%s'")
1810
1811 (js2-msg "msg.undef.prop.delete"
1812 "Cannot delete property '%s' of %s")
1813
1814 (js2-msg "msg.undef.method.call"
1815 "Cannot call method '%s' of %s")
1816
1817 (js2-msg "msg.undef.with"
1818 "Cannot apply 'with' to %s")
1819
1820 (js2-msg "msg.isnt.function"
1821 "%s is not a function, it is %s.")
1822
1823 (js2-msg "msg.isnt.function.in"
1824 "Cannot call property %s in object %s. "
1825 "It is not a function, it is '%s'.")
1826
1827 (js2-msg "msg.function.not.found"
1828 "Cannot find function %s.")
1829
1830 (js2-msg "msg.function.not.found.in"
1831 "Cannot find function %s in object %s.")
1832
1833 (js2-msg "msg.isnt.xml.object"
1834 "%s is not an xml object.")
1835
1836 (js2-msg "msg.no.ref.to.get"
1837 "%s is not a reference to read reference value.")
1838
1839 (js2-msg "msg.no.ref.to.set"
1840 "%s is not a reference to set reference value to %s.")
1841
1842 (js2-msg "msg.no.ref.from.function"
1843 "Function %s can not be used as the left-hand "
1844 "side of assignment or as an operand of ++ or -- operator.")
1845
1846 (js2-msg "msg.bad.default.value"
1847 "Object's getDefaultValue() method returned an object.")
1848
1849 (js2-msg "msg.instanceof.not.object"
1850 "Can't use instanceof on a non-object.")
1851
1852 (js2-msg "msg.instanceof.bad.prototype"
1853 "'prototype' property of %s is not an object.")
1854
1855 (js2-msg "msg.bad.radix"
1856 "illegal radix %s.")
1857
1858 ;; ScriptableObject
1859 (js2-msg "msg.default.value"
1860 "Cannot find default value for object.")
1861
1862 (js2-msg "msg.zero.arg.ctor"
1863 "Cannot load class '%s' which has no zero-parameter constructor.")
1864
1865 (js2-msg "msg.ctor.multiple.parms"
1866 "Can't define constructor or class %s since more than "
1867 "one constructor has multiple parameters.")
1868
1869 (js2-msg "msg.extend.scriptable"
1870 "%s must extend ScriptableObject in order to define property %s.")
1871
1872 (js2-msg "msg.bad.getter.parms"
1873 "In order to define a property, getter %s must have zero "
1874 "parameters or a single ScriptableObject parameter.")
1875
1876 (js2-msg "msg.obj.getter.parms"
1877 "Expected static or delegated getter %s to take "
1878 "a ScriptableObject parameter.")
1879
1880 (js2-msg "msg.getter.static"
1881 "Getter and setter must both be static or neither be static.")
1882
1883 (js2-msg "msg.setter.return"
1884 "Setter must have void return type: %s")
1885
1886 (js2-msg "msg.setter2.parms"
1887 "Two-parameter setter must take a ScriptableObject as "
1888 "its first parameter.")
1889
1890 (js2-msg "msg.setter1.parms"
1891 "Expected single parameter setter for %s")
1892
1893 (js2-msg "msg.setter2.expected"
1894 "Expected static or delegated setter %s to take two parameters.")
1895
1896 (js2-msg "msg.setter.parms"
1897 "Expected either one or two parameters for setter.")
1898
1899 (js2-msg "msg.setter.bad.type"
1900 "Unsupported parameter type '%s' in setter '%s'.")
1901
1902 (js2-msg "msg.add.sealed"
1903 "Cannot add a property to a sealed object: %s.")
1904
1905 (js2-msg "msg.remove.sealed"
1906 "Cannot remove a property from a sealed object: %s.")
1907
1908 (js2-msg "msg.modify.sealed"
1909 "Cannot modify a property of a sealed object: %s.")
1910
1911 (js2-msg "msg.modify.readonly"
1912 "Cannot modify readonly property: %s.")
1913
1914 ;; TokenStream
1915 (js2-msg "msg.missing.exponent"
1916 "missing exponent")
1917
1918 (js2-msg "msg.caught.nfe"
1919 "number format error")
1920
1921 (js2-msg "msg.unterminated.string.lit"
1922 "unterminated string literal")
1923
1924 (js2-msg "msg.unterminated.comment"
1925 "unterminated comment")
1926
1927 (js2-msg "msg.unterminated.re.lit"
1928 "unterminated regular expression literal")
1929
1930 (js2-msg "msg.invalid.re.flag"
1931 "invalid flag after regular expression")
1932
1933 (js2-msg "msg.no.re.input.for"
1934 "no input for %s")
1935
1936 (js2-msg "msg.illegal.character"
1937 "illegal character")
1938
1939 (js2-msg "msg.invalid.escape"
1940 "invalid Unicode escape sequence")
1941
1942 (js2-msg "msg.bad.namespace"
1943 "not a valid default namespace statement. "
1944 "Syntax is: default xml namespace = EXPRESSION;")
1945
1946 ;; TokensStream warnings
1947 (js2-msg "msg.bad.octal.literal"
1948 "illegal octal literal digit %s; "
1949 "interpreting it as a decimal digit")
1950
1951 (js2-msg "msg.reserved.keyword"
1952 "illegal usage of future reserved keyword %s; "
1953 "interpreting it as ordinary identifier")
1954
1955 (js2-msg "msg.script.is.not.constructor"
1956 "Script objects are not constructors.")
1957
1958 ;; Arrays
1959 (js2-msg "msg.arraylength.bad"
1960 "Inappropriate array length.")
1961
1962 ;; Arrays
1963 (js2-msg "msg.arraylength.too.big"
1964 "Array length %s exceeds supported capacity limit.")
1965
1966 ;; URI
1967 (js2-msg "msg.bad.uri"
1968 "Malformed URI sequence.")
1969
1970 ;; Number
1971 (js2-msg "msg.bad.precision"
1972 "Precision %s out of range.")
1973
1974 ;; NativeGenerator
1975 (js2-msg "msg.send.newborn"
1976 "Attempt to send value to newborn generator")
1977
1978 (js2-msg "msg.already.exec.gen"
1979 "Already executing generator")
1980
1981 (js2-msg "msg.StopIteration.invalid"
1982 "StopIteration may not be changed to an arbitrary object.")
1983
1984 ;; Interpreter
1985 (js2-msg "msg.yield.closing"
1986 "Yield from closing generator")
1987
1988 ;;; Utilities
1989
1990 (defun js2-delete-if (predicate list)
1991 "Remove all items satisfying PREDICATE in LIST."
1992 (loop for item in list
1993 if (not (funcall predicate item))
1994 collect item))
1995
1996 (defun js2-position (element list)
1997 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1998 Returns nil if element is not found in the list."
1999 (let ((count 0)
2000 found)
2001 (while (and list (not found))
2002 (if (eq element (car list))
2003 (setq found t)
2004 (setq count (1+ count)
2005 list (cdr list))))
2006 (if found count)))
2007
2008 (defun js2-find-if (predicate list)
2009 "Find first item satisfying PREDICATE in LIST."
2010 (let (result)
2011 (while (and list (not result))
2012 (if (funcall predicate (car list))
2013 (setq result (car list)))
2014 (setq list (cdr list)))
2015 result))
2016
2017 (defmacro js2-time (form)
2018 "Evaluate FORM, discard result, and return elapsed time in sec"
2019 (declare (debug t))
2020 (let ((beg (make-symbol "--js2-time-beg--"))
2021 (delta (make-symbol "--js2-time-end--")))
2022 `(let ((,beg (current-time))
2023 ,delta)
2024 ,form
2025 (/ (truncate (* (- (float-time (current-time))
2026 (float-time ,beg))
2027 10000))
2028 10000.0))))
2029
2030 (defsubst js2-same-line (pos)
2031 "Return t if POS is on the same line as current point."
2032 (and (>= pos (point-at-bol))
2033 (<= pos (point-at-eol))))
2034
2035 (defsubst js2-same-line-2 (p1 p2)
2036 "Return t if p1 is on the same line as p2."
2037 (save-excursion
2038 (goto-char p1)
2039 (js2-same-line p2)))
2040
2041 (defun js2-code-bug ()
2042 "Signal an error when we encounter an unexpected code path."
2043 (error "failed assertion"))
2044
2045 (defsubst js2-record-text-property (beg end prop value)
2046 "Record a text property to set when parsing finishes."
2047 (push (list beg end prop value) js2-mode-deferred-properties))
2048
2049 ;; I'd like to associate errors with nodes, but for now the
2050 ;; easiest thing to do is get the context info from the last token.
2051 (defsubst js2-record-parse-error (msg &optional arg pos len)
2052 (push (list (list msg arg)
2053 (or pos js2-token-beg)
2054 (or len (- js2-token-end js2-token-beg)))
2055 js2-parsed-errors))
2056
2057 (defsubst js2-report-error (msg &optional msg-arg pos len)
2058 "Signal a syntax error or record a parse error."
2059 (if js2-recover-from-parse-errors
2060 (js2-record-parse-error msg msg-arg pos len)
2061 (signal 'js2-syntax-error
2062 (list msg
2063 js2-ts-lineno
2064 (save-excursion
2065 (goto-char js2-ts-cursor)
2066 (current-column))
2067 js2-ts-hit-eof))))
2068
2069 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2070 (if js2-compiler-report-warning-as-error
2071 (js2-report-error msg msg-arg pos len)
2072 (push (list (list msg msg-arg)
2073 (or pos js2-token-beg)
2074 (or len (- js2-token-end js2-token-beg)))
2075 js2-parsed-warnings)))
2076
2077 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2078 (if js2-compiler-strict-mode
2079 (js2-report-warning msg-id msg-arg beg
2080 (and beg end (- end beg)))))
2081
2082 (put 'js2-syntax-error 'error-conditions
2083 '(error syntax-error js2-syntax-error))
2084 (put 'js2-syntax-error 'error-message "Syntax error")
2085
2086 (put 'js2-parse-error 'error-conditions
2087 '(error parse-error js2-parse-error))
2088 (put 'js2-parse-error 'error-message "Parse error")
2089
2090 (defmacro js2-clear-flag (flags flag)
2091 `(setq ,flags (logand ,flags (lognot ,flag))))
2092
2093 (defmacro js2-set-flag (flags flag)
2094 "Logical-or FLAG into FLAGS."
2095 `(setq ,flags (logior ,flags ,flag)))
2096
2097 (defsubst js2-flag-set-p (flags flag)
2098 (/= 0 (logand flags flag)))
2099
2100 (defsubst js2-flag-not-set-p (flags flag)
2101 (zerop (logand flags flag)))
2102
2103 ;; Stolen shamelessly from James Clark's nxml-mode.
2104 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2105 "Evaluate BODY without any text property changes modifying the buffer.
2106 Any text properties changes happen as usual but the changes are not treated as
2107 modifications to the buffer."
2108 (declare (indent 0) (debug t))
2109 (let ((modified (make-symbol "modified")))
2110 `(let ((,modified (buffer-modified-p))
2111 (inhibit-read-only t)
2112 (inhibit-modification-hooks t)
2113 (buffer-undo-list t)
2114 (deactivate-mark nil)
2115 ;; Apparently these avoid file locking problems.
2116 (buffer-file-name nil)
2117 (buffer-file-truename nil))
2118 (unwind-protect
2119 (progn ,@body)
2120 (unless ,modified
2121 (restore-buffer-modified-p nil))))))
2122
2123 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2124 "Evaluate BODY with the _ character set to be word-syntax."
2125 (declare (indent 0) (debug t))
2126 (let ((old-syntax (make-symbol "old-syntax")))
2127 `(let ((,old-syntax (string (char-syntax ?_))))
2128 (unwind-protect
2129 (progn
2130 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2131 ,@body)
2132 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2133
2134 (defsubst js2-char-uppercase-p (c)
2135 "Return t if C is an uppercase character.
2136 Handles unicode and latin chars properly."
2137 (/= c (downcase c)))
2138
2139 (defsubst js2-char-lowercase-p (c)
2140 "Return t if C is an uppercase character.
2141 Handles unicode and latin chars properly."
2142 (/= c (upcase c)))
2143
2144 ;;; AST struct and function definitions
2145
2146 ;; flags for ast node property 'member-type (used for e4x operators)
2147 (defvar js2-property-flag #x1 "property access: element is valid name")
2148 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2149 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2150
2151 (defsubst js2-relpos (pos anchor)
2152 "Convert POS to be relative to ANCHOR.
2153 If POS is nil, returns nil."
2154 (and pos (- pos anchor)))
2155
2156 (defsubst js2-make-pad (indent)
2157 (if (zerop indent)
2158 ""
2159 (make-string (* indent js2-basic-offset) ? )))
2160
2161 (defsubst js2-visit-ast (node callback)
2162 "Visit every node in ast NODE with visitor CALLBACK.
2163
2164 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2165 called twice: once to visit the node, and again after all the node's
2166 children have been processed. The END-P argument is nil on the first
2167 call and non-nil on the second call. The return value of the callback
2168 affects the traversal: if non-nil, the children of NODE are processed.
2169 If the callback returns nil, or if the node has no children, then the
2170 callback is called immediately with a non-nil END-P argument.
2171
2172 The node traversal is approximately lexical-order, although there
2173 are currently no guarantees around this."
2174 (if node
2175 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2176 ;; visit the node
2177 (when (funcall callback node nil)
2178 ;; visit the kids
2179 (cond
2180 ((eq vfunc 'js2-visit-none)
2181 nil) ; don't even bother calling it
2182 ;; Each AST node type has to define a `js2-visitor' function
2183 ;; that takes a node and a callback, and calls `js2-visit-ast'
2184 ;; on each child of the node.
2185 (vfunc
2186 (funcall vfunc node callback))
2187 (t
2188 (error "%s does not define a visitor-traversal function"
2189 (aref node 0)))))
2190 ;; call the end-visit
2191 (funcall callback node t))))
2192
2193 (defstruct (js2-node
2194 (:constructor nil)) ; abstract
2195 "Base AST node type."
2196 (type -1) ; token type
2197 (pos -1) ; start position of this AST node in parsed input
2198 (len 1) ; num characters spanned by the node
2199 props ; optional node property list (an alist)
2200 parent) ; link to parent node; null for root
2201
2202 (defsubst js2-node-get-prop (node prop &optional default)
2203 (or (cadr (assoc prop (js2-node-props node))) default))
2204
2205 (defsubst js2-node-set-prop (node prop value)
2206 (setf (js2-node-props node)
2207 (cons (list prop value) (js2-node-props node))))
2208
2209 (defsubst js2-fixup-starts (n nodes)
2210 "Adjust the start positions of NODES to be relative to N.
2211 Any node in the list may be nil, for convenience."
2212 (dolist (node nodes)
2213 (when node
2214 (setf (js2-node-pos node) (- (js2-node-pos node)
2215 (js2-node-pos n))))))
2216
2217 (defsubst js2-node-add-children (parent &rest nodes)
2218 "Set parent node of NODES to PARENT, and return PARENT.
2219 Does nothing if we're not recording parent links.
2220 If any given node in NODES is nil, doesn't record that link."
2221 (js2-fixup-starts parent nodes)
2222 (dolist (node nodes)
2223 (and node
2224 (setf (js2-node-parent node) parent))))
2225
2226 ;; Non-recursive since it's called a frightening number of times.
2227 (defsubst js2-node-abs-pos (n)
2228 (let ((pos (js2-node-pos n)))
2229 (while (setq n (js2-node-parent n))
2230 (setq pos (+ pos (js2-node-pos n))))
2231 pos))
2232
2233 (defsubst js2-node-abs-end (n)
2234 "Return absolute buffer position of end of N."
2235 (+ (js2-node-abs-pos n) (js2-node-len n)))
2236
2237 ;; It's important to make sure block nodes have a lisp list for the
2238 ;; child nodes, to limit printing recursion depth in an AST that
2239 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2240 ;; a sufficiently large vector tree.
2241
2242 (defstruct (js2-block-node
2243 (:include js2-node)
2244 (:constructor nil)
2245 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2246 (pos js2-token-beg)
2247 len
2248 props
2249 kids)))
2250 "A block of statements."
2251 kids) ; a lisp list of the child statement nodes
2252
2253 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2254 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2255
2256 (defsubst js2-visit-block (ast callback)
2257 "Visit the `js2-block-node' children of AST."
2258 (dolist (kid (js2-block-node-kids ast))
2259 (js2-visit-ast kid callback)))
2260
2261 (defun js2-print-block (n i)
2262 (let ((pad (js2-make-pad i)))
2263 (insert pad "{\n")
2264 (dolist (kid (js2-block-node-kids n))
2265 (js2-print-ast kid (1+ i)))
2266 (insert pad "}")))
2267
2268 (defstruct (js2-scope
2269 (:include js2-block-node)
2270 (:constructor nil)
2271 (:constructor make-js2-scope (&key (type js2-BLOCK)
2272 (pos js2-token-beg)
2273 len
2274 kids)))
2275 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2276 ;; I don't have one of those handy, so I'll use an alist for now.
2277 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2278 ;; and is much lighter-weight to construct (both CPU and mem).
2279 ;; The keys are interned strings (symbols) for faster lookup.
2280 ;; Should switch to hybrid alist/hashtable eventually.
2281 symbol-table ; an alist of (symbol . js2-symbol)
2282 parent-scope ; a `js2-scope'
2283 top) ; top-level `js2-scope' (script/function)
2284
2285 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2286 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2287
2288 (defun js2-scope-set-parent-scope (scope parent)
2289 (setf (js2-scope-parent-scope scope) parent
2290 (js2-scope-top scope) (if (null parent)
2291 scope
2292 (js2-scope-top parent))))
2293
2294 (defun js2-node-get-enclosing-scope (node)
2295 "Return the innermost `js2-scope' node surrounding NODE.
2296 Returns nil if there is no enclosing scope node."
2297 (let ((parent (js2-node-parent node)))
2298 (while (not (js2-scope-p parent))
2299 (setq parent (js2-node-parent parent)))
2300 parent))
2301
2302 (defun js2-get-defining-scope (scope name)
2303 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2304 Returns `js2-scope' in which NAME is defined, or nil if not found."
2305 (let ((sym (if (symbolp name)
2306 name
2307 (intern name)))
2308 table
2309 result
2310 (continue t))
2311 (while (and scope continue)
2312 (if (and (setq table (js2-scope-symbol-table scope))
2313 (assq sym table))
2314 (setq continue nil
2315 result scope)
2316 (setq scope (js2-scope-parent-scope scope))))
2317 result))
2318
2319 (defsubst js2-scope-get-symbol (scope name)
2320 "Return symbol table entry for NAME in SCOPE.
2321 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2322 (and (js2-scope-symbol-table scope)
2323 (cdr (assq (if (symbolp name)
2324 name
2325 (intern name))
2326 (js2-scope-symbol-table scope)))))
2327
2328 (defsubst js2-scope-put-symbol (scope name symbol)
2329 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2330 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2331 (let* ((table (js2-scope-symbol-table scope))
2332 (sym (if (symbolp name) name (intern name)))
2333 (entry (assq sym table)))
2334 (if entry
2335 (setcdr entry symbol)
2336 (push (cons sym symbol)
2337 (js2-scope-symbol-table scope)))))
2338
2339 (defstruct (js2-symbol
2340 (:constructor nil)
2341 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2342 "A symbol table entry."
2343 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2344 ;; js2-LET, or js2-CONST
2345 decl-type
2346 name ; string
2347 ast-node) ; a `js2-node'
2348
2349 (defstruct (js2-error-node
2350 (:include js2-node)
2351 (:constructor nil) ; silence emacs21 byte-compiler
2352 (:constructor make-js2-error-node (&key (type js2-ERROR)
2353 (pos js2-token-beg)
2354 len)))
2355 "AST node representing a parse error.")
2356
2357 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2358 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2359
2360 (defstruct (js2-script-node
2361 (:include js2-scope)
2362 (:constructor nil)
2363 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2364 (pos js2-token-beg)
2365 len
2366 var-decls
2367 fun-decls)))
2368 functions ; lisp list of nested functions
2369 regexps ; lisp list of (string . flags)
2370 symbols ; alist (every symbol gets unique index)
2371 (param-count 0)
2372 var-names ; vector of string names
2373 consts ; bool-vector matching var-decls
2374 (temp-number 0)) ; for generating temp variables
2375
2376 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2377 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2378
2379 (defun js2-print-script (node indent)
2380 (dolist (kid (js2-block-node-kids node))
2381 (js2-print-ast kid indent)))
2382
2383 (defstruct (js2-ast-root
2384 (:include js2-script-node)
2385 (:constructor nil)
2386 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2387 (pos js2-token-beg)
2388 len
2389 buffer)))
2390 "The root node of a js2 AST."
2391 buffer ; the source buffer from which the code was parsed
2392 comments ; a lisp list of comments, ordered by start position
2393 errors ; a lisp list of errors found during parsing
2394 warnings ; a lisp list of warnings found during parsing
2395 node-count) ; number of nodes in the tree, including the root
2396
2397 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2398 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2399
2400 (defun js2-visit-ast-root (ast callback)
2401 (dolist (kid (js2-ast-root-kids ast))
2402 (js2-visit-ast kid callback))
2403 (dolist (comment (js2-ast-root-comments ast))
2404 (js2-visit-ast comment callback)))
2405
2406 (defstruct (js2-comment-node
2407 (:include js2-node)
2408 (:constructor nil)
2409 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2410 (pos js2-token-beg)
2411 len
2412 (format js2-ts-comment-type))))
2413 format) ; 'line, 'block, 'jsdoc or 'html
2414
2415 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2416 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2417
2418 (defun js2-print-comment (n i)
2419 ;; We really ought to link end-of-line comments to their nodes.
2420 ;; Or maybe we could add a new comment type, 'endline.
2421 (insert (js2-make-pad i)
2422 (js2-node-string n)))
2423
2424 (defstruct (js2-expr-stmt-node
2425 (:include js2-node)
2426 (:constructor nil)
2427 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2428 (pos js2-ts-cursor)
2429 len
2430 expr)))
2431 "An expression statement."
2432 expr)
2433
2434 (defsubst js2-expr-stmt-node-set-has-result (node)
2435 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2436 (setf (js2-node-type node) js2-EXPR_RESULT))
2437
2438 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2439 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2440
2441 (defun js2-visit-expr-stmt-node (n v)
2442 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2443
2444 (defun js2-print-expr-stmt-node (n indent)
2445 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2446 (insert ";\n"))
2447
2448 (defstruct (js2-loop-node
2449 (:include js2-scope)
2450 (:constructor nil))
2451 "Abstract supertype of loop nodes."
2452 body ; a `js2-block-node'
2453 lp ; position of left-paren, nil if omitted
2454 rp) ; position of right-paren, nil if omitted
2455
2456 (defstruct (js2-do-node
2457 (:include js2-loop-node)
2458 (:constructor nil)
2459 (:constructor make-js2-do-node (&key (type js2-DO)
2460 (pos js2-token-beg)
2461 len
2462 body
2463 condition
2464 while-pos
2465 lp
2466 rp)))
2467 "AST node for do-loop."
2468 condition ; while (expression)
2469 while-pos) ; buffer position of 'while' keyword
2470
2471 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2472 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2473
2474 (defun js2-visit-do-node (n v)
2475 (js2-visit-ast (js2-do-node-body n) v)
2476 (js2-visit-ast (js2-do-node-condition n) v))
2477
2478 (defun js2-print-do-node (n i)
2479 (let ((pad (js2-make-pad i)))
2480 (insert pad "do {\n")
2481 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2482 (js2-print-ast kid (1+ i)))
2483 (insert pad "} while (")
2484 (js2-print-ast (js2-do-node-condition n) 0)
2485 (insert ");\n")))
2486
2487 (defstruct (js2-while-node
2488 (:include js2-loop-node)
2489 (:constructor nil)
2490 (:constructor make-js2-while-node (&key (type js2-WHILE)
2491 (pos js2-token-beg)
2492 len
2493 body
2494 condition
2495 lp
2496 rp)))
2497 "AST node for while-loop."
2498 condition) ; while-condition
2499
2500 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2501 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2502
2503 (defun js2-visit-while-node (n v)
2504 (js2-visit-ast (js2-while-node-condition n) v)
2505 (js2-visit-ast (js2-while-node-body n) v))
2506
2507 (defun js2-print-while-node (n i)
2508 (let ((pad (js2-make-pad i)))
2509 (insert pad "while (")
2510 (js2-print-ast (js2-while-node-condition n) 0)
2511 (insert ") {\n")
2512 (js2-print-body (js2-while-node-body n) (1+ i))
2513 (insert pad "}\n")))
2514
2515 (defstruct (js2-for-node
2516 (:include js2-loop-node)
2517 (:constructor nil)
2518 (:constructor make-js2-for-node (&key (type js2-FOR)
2519 (pos js2-ts-cursor)
2520 len
2521 body
2522 init
2523 condition
2524 update
2525 lp
2526 rp)))
2527 "AST node for a C-style for-loop."
2528 init ; initialization expression
2529 condition ; loop condition
2530 update) ; update clause
2531
2532 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2533 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2534
2535 (defun js2-visit-for-node (n v)
2536 (js2-visit-ast (js2-for-node-init n) v)
2537 (js2-visit-ast (js2-for-node-condition n) v)
2538 (js2-visit-ast (js2-for-node-update n) v)
2539 (js2-visit-ast (js2-for-node-body n) v))
2540
2541 (defun js2-print-for-node (n i)
2542 (let ((pad (js2-make-pad i)))
2543 (insert pad "for (")
2544 (js2-print-ast (js2-for-node-init n) 0)
2545 (insert "; ")
2546 (js2-print-ast (js2-for-node-condition n) 0)
2547 (insert "; ")
2548 (js2-print-ast (js2-for-node-update n) 0)
2549 (insert ") {\n")
2550 (js2-print-body (js2-for-node-body n) (1+ i))
2551 (insert pad "}\n")))
2552
2553 (defstruct (js2-for-in-node
2554 (:include js2-loop-node)
2555 (:constructor nil)
2556 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2557 (pos js2-ts-cursor)
2558 len
2559 body
2560 iterator
2561 object
2562 in-pos
2563 each-pos
2564 foreach-p forof-p
2565 lp rp)))
2566 "AST node for a for..in loop."
2567 iterator ; [var] foo in ...
2568 object ; object over which we're iterating
2569 in-pos ; buffer position of 'in' keyword
2570 each-pos ; buffer position of 'each' keyword, if foreach-p
2571 foreach-p ; t if it's a for-each loop
2572 forof-p) ; t if it's a for-of loop
2573
2574 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2575 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2576
2577 (defun js2-visit-for-in-node (n v)
2578 (js2-visit-ast (js2-for-in-node-iterator n) v)
2579 (js2-visit-ast (js2-for-in-node-object n) v)
2580 (js2-visit-ast (js2-for-in-node-body n) v))
2581
2582 (defun js2-print-for-in-node (n i)
2583 (let ((pad (js2-make-pad i))
2584 (foreach (js2-for-in-node-foreach-p n))
2585 (forof (js2-for-in-node-forof-p n)))
2586 (insert pad "for ")
2587 (if foreach
2588 (insert "each "))
2589 (insert "(")
2590 (js2-print-ast (js2-for-in-node-iterator n) 0)
2591 (if forof
2592 (insert " of ")
2593 (insert " in "))
2594 (js2-print-ast (js2-for-in-node-object n) 0)
2595 (insert ") {\n")
2596 (js2-print-body (js2-for-in-node-body n) (1+ i))
2597 (insert pad "}\n")))
2598
2599 (defstruct (js2-return-node
2600 (:include js2-node)
2601 (:constructor nil)
2602 (:constructor make-js2-return-node (&key (type js2-RETURN)
2603 (pos js2-ts-cursor)
2604 len
2605 retval)))
2606 "AST node for a return statement."
2607 retval) ; expression to return, or 'undefined
2608
2609 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2610 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2611
2612 (defun js2-visit-return-node (n v)
2613 (js2-visit-ast (js2-return-node-retval n) v))
2614
2615 (defun js2-print-return-node (n i)
2616 (insert (js2-make-pad i) "return")
2617 (when (js2-return-node-retval n)
2618 (insert " ")
2619 (js2-print-ast (js2-return-node-retval n) 0))
2620 (insert ";\n"))
2621
2622 (defstruct (js2-if-node
2623 (:include js2-node)
2624 (:constructor nil)
2625 (:constructor make-js2-if-node (&key (type js2-IF)
2626 (pos js2-ts-cursor)
2627 len
2628 condition
2629 then-part
2630 else-pos
2631 else-part
2632 lp
2633 rp)))
2634 "AST node for an if-statement."
2635 condition ; expression
2636 then-part ; statement or block
2637 else-pos ; optional buffer position of 'else' keyword
2638 else-part ; optional statement or block
2639 lp ; position of left-paren, nil if omitted
2640 rp) ; position of right-paren, nil if omitted
2641
2642 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2643 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2644
2645 (defun js2-visit-if-node (n v)
2646 (js2-visit-ast (js2-if-node-condition n) v)
2647 (js2-visit-ast (js2-if-node-then-part n) v)
2648 (js2-visit-ast (js2-if-node-else-part n) v))
2649
2650 (defun js2-print-if-node (n i)
2651 (let ((pad (js2-make-pad i))
2652 (then-part (js2-if-node-then-part n))
2653 (else-part (js2-if-node-else-part n)))
2654 (insert pad "if (")
2655 (js2-print-ast (js2-if-node-condition n) 0)
2656 (insert ") {\n")
2657 (js2-print-body then-part (1+ i))
2658 (insert pad "}")
2659 (cond
2660 ((not else-part)
2661 (insert "\n"))
2662 ((js2-if-node-p else-part)
2663 (insert " else ")
2664 (js2-print-body else-part i))
2665 (t
2666 (insert " else {\n")
2667 (js2-print-body else-part (1+ i))
2668 (insert pad "}\n")))))
2669
2670 (defstruct (js2-try-node
2671 (:include js2-node)
2672 (:constructor nil)
2673 (:constructor make-js2-try-node (&key (type js2-TRY)
2674 (pos js2-ts-cursor)
2675 len
2676 try-block
2677 catch-clauses
2678 finally-block)))
2679 "AST node for a try-statement."
2680 try-block
2681 catch-clauses ; a lisp list of `js2-catch-node'
2682 finally-block) ; a `js2-finally-node'
2683
2684 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2685 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2686
2687 (defun js2-visit-try-node (n v)
2688 (js2-visit-ast (js2-try-node-try-block n) v)
2689 (dolist (clause (js2-try-node-catch-clauses n))
2690 (js2-visit-ast clause v))
2691 (js2-visit-ast (js2-try-node-finally-block n) v))
2692
2693 (defun js2-print-try-node (n i)
2694 (let ((pad (js2-make-pad i))
2695 (catches (js2-try-node-catch-clauses n))
2696 (finally (js2-try-node-finally-block n)))
2697 (insert pad "try {\n")
2698 (js2-print-body (js2-try-node-try-block n) (1+ i))
2699 (insert pad "}")
2700 (when catches
2701 (dolist (catch catches)
2702 (js2-print-ast catch i)))
2703 (if finally
2704 (js2-print-ast finally i)
2705 (insert "\n"))))
2706
2707 (defstruct (js2-catch-node
2708 (:include js2-node)
2709 (:constructor nil)
2710 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2711 (pos js2-ts-cursor)
2712 len
2713 param
2714 guard-kwd
2715 guard-expr
2716 block
2717 lp
2718 rp)))
2719 "AST node for a catch clause."
2720 param ; destructuring form or simple name node
2721 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2722 guard-expr ; catch condition, a `js2-node'
2723 block ; statements, a `js2-block-node'
2724 lp ; buffer position of left-paren, nil if omitted
2725 rp) ; buffer position of right-paren, nil if omitted
2726
2727 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2728 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2729
2730 (defun js2-visit-catch-node (n v)
2731 (js2-visit-ast (js2-catch-node-param n) v)
2732 (when (js2-catch-node-guard-kwd n)
2733 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2734 (js2-visit-ast (js2-catch-node-block n) v))
2735
2736 (defun js2-print-catch-node (n i)
2737 (let ((pad (js2-make-pad i))
2738 (guard-kwd (js2-catch-node-guard-kwd n))
2739 (guard-expr (js2-catch-node-guard-expr n)))
2740 (insert " catch (")
2741 (js2-print-ast (js2-catch-node-param n) 0)
2742 (when guard-kwd
2743 (insert " if ")
2744 (js2-print-ast guard-expr 0))
2745 (insert ") {\n")
2746 (js2-print-body (js2-catch-node-block n) (1+ i))
2747 (insert pad "}")))
2748
2749 (defstruct (js2-finally-node
2750 (:include js2-node)
2751 (:constructor nil)
2752 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2753 (pos js2-ts-cursor)
2754 len
2755 body)))
2756 "AST node for a finally clause."
2757 body) ; a `js2-node', often but not always a block node
2758
2759 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2760 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2761
2762 (defun js2-visit-finally-node (n v)
2763 (js2-visit-ast (js2-finally-node-body n) v))
2764
2765 (defun js2-print-finally-node (n i)
2766 (let ((pad (js2-make-pad i)))
2767 (insert " finally {\n")
2768 (js2-print-body (js2-finally-node-body n) (1+ i))
2769 (insert pad "}\n")))
2770
2771 (defstruct (js2-switch-node
2772 (:include js2-node)
2773 (:constructor nil)
2774 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2775 (pos js2-ts-cursor)
2776 len
2777 discriminant
2778 cases
2779 lp
2780 rp)))
2781 "AST node for a switch statement."
2782 discriminant ; a `js2-node' (switch expression)
2783 cases ; a lisp list of `js2-case-node'
2784 lp ; position of open-paren for discriminant, nil if omitted
2785 rp) ; position of close-paren for discriminant, nil if omitted
2786
2787 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2788 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2789
2790 (defun js2-visit-switch-node (n v)
2791 (js2-visit-ast (js2-switch-node-discriminant n) v)
2792 (dolist (c (js2-switch-node-cases n))
2793 (js2-visit-ast c v)))
2794
2795 (defun js2-print-switch-node (n i)
2796 (let ((pad (js2-make-pad i))
2797 (cases (js2-switch-node-cases n)))
2798 (insert pad "switch (")
2799 (js2-print-ast (js2-switch-node-discriminant n) 0)
2800 (insert ") {\n")
2801 (dolist (case cases)
2802 (js2-print-ast case i))
2803 (insert pad "}\n")))
2804
2805 (defstruct (js2-case-node
2806 (:include js2-block-node)
2807 (:constructor nil)
2808 (:constructor make-js2-case-node (&key (type js2-CASE)
2809 (pos js2-ts-cursor)
2810 len
2811 kids
2812 expr)))
2813 "AST node for a case clause of a switch statement."
2814 expr) ; the case expression (nil for default)
2815
2816 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2817 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2818
2819 (defun js2-visit-case-node (n v)
2820 (js2-visit-ast (js2-case-node-expr n) v)
2821 (js2-visit-block n v))
2822
2823 (defun js2-print-case-node (n i)
2824 (let ((pad (js2-make-pad i))
2825 (expr (js2-case-node-expr n)))
2826 (insert pad)
2827 (if (null expr)
2828 (insert "default:\n")
2829 (insert "case ")
2830 (js2-print-ast expr 0)
2831 (insert ":\n"))
2832 (dolist (kid (js2-case-node-kids n))
2833 (js2-print-ast kid (1+ i)))))
2834
2835 (defstruct (js2-throw-node
2836 (:include js2-node)
2837 (:constructor nil)
2838 (:constructor make-js2-throw-node (&key (type js2-THROW)
2839 (pos js2-ts-cursor)
2840 len
2841 expr)))
2842 "AST node for a throw statement."
2843 expr) ; the expression to throw
2844
2845 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2846 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2847
2848 (defun js2-visit-throw-node (n v)
2849 (js2-visit-ast (js2-throw-node-expr n) v))
2850
2851 (defun js2-print-throw-node (n i)
2852 (insert (js2-make-pad i) "throw ")
2853 (js2-print-ast (js2-throw-node-expr n) 0)
2854 (insert ";\n"))
2855
2856 (defstruct (js2-with-node
2857 (:include js2-node)
2858 (:constructor nil)
2859 (:constructor make-js2-with-node (&key (type js2-WITH)
2860 (pos js2-ts-cursor)
2861 len
2862 object
2863 body
2864 lp
2865 rp)))
2866 "AST node for a with-statement."
2867 object
2868 body
2869 lp ; buffer position of left-paren around object, nil if omitted
2870 rp) ; buffer position of right-paren around object, nil if omitted
2871
2872 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2873 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2874
2875 (defun js2-visit-with-node (n v)
2876 (js2-visit-ast (js2-with-node-object n) v)
2877 (js2-visit-ast (js2-with-node-body n) v))
2878
2879 (defun js2-print-with-node (n i)
2880 (let ((pad (js2-make-pad i)))
2881 (insert pad "with (")
2882 (js2-print-ast (js2-with-node-object n) 0)
2883 (insert ") {\n")
2884 (js2-print-body (js2-with-node-body n) (1+ i))
2885 (insert pad "}\n")))
2886
2887 (defstruct (js2-label-node
2888 (:include js2-node)
2889 (:constructor nil)
2890 (:constructor make-js2-label-node (&key (type js2-LABEL)
2891 (pos js2-ts-cursor)
2892 len
2893 name)))
2894 "AST node for a statement label or case label."
2895 name ; a string
2896 loop) ; for validating and code-generating continue-to-label
2897
2898 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2899 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2900
2901 (defun js2-print-label (n i)
2902 (insert (js2-make-pad i)
2903 (js2-label-node-name n)
2904 ":\n"))
2905
2906 (defstruct (js2-labeled-stmt-node
2907 (:include js2-node)
2908 (:constructor nil)
2909 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2910 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2911 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2912 (pos js2-ts-cursor)
2913 len
2914 labels
2915 stmt)))
2916 "AST node for a statement with one or more labels.
2917 Multiple labels for a statement are collapsed into the labels field."
2918 labels ; lisp list of `js2-label-node'
2919 stmt) ; the statement these labels are for
2920
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2922 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2923
2924 (defun js2-get-label-by-name (lbl-stmt name)
2925 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2926 Returns nil if no such label is in the list."
2927 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2928 result)
2929 (while (and label-list (not result))
2930 (if (string= (js2-label-node-name (car label-list)) name)
2931 (setq result (car label-list))
2932 (setq label-list (cdr label-list))))
2933 result))
2934
2935 (defun js2-visit-labeled-stmt (n v)
2936 (dolist (label (js2-labeled-stmt-node-labels n))
2937 (js2-visit-ast label v))
2938 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2939
2940 (defun js2-print-labeled-stmt (n i)
2941 (dolist (label (js2-labeled-stmt-node-labels n))
2942 (js2-print-ast label i))
2943 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2944
2945 (defun js2-labeled-stmt-node-contains (node label)
2946 "Return t if NODE contains LABEL in its label set.
2947 NODE is a `js2-labels-node'. LABEL is an identifier."
2948 (loop for nl in (js2-labeled-stmt-node-labels node)
2949 if (string= label (js2-label-node-name nl))
2950 return t
2951 finally return nil))
2952
2953 (defsubst js2-labeled-stmt-node-add-label (node label)
2954 "Add a `js2-label-node' to the label set for this statement."
2955 (setf (js2-labeled-stmt-node-labels node)
2956 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2957
2958 (defstruct (js2-jump-node
2959 (:include js2-node)
2960 (:constructor nil))
2961 "Abstract supertype of break and continue nodes."
2962 label ; `js2-name-node' for location of label identifier, if present
2963 target) ; target js2-labels-node or loop/switch statement
2964
2965 (defun js2-visit-jump-node (n v)
2966 (js2-visit-ast (js2-jump-node-label n) v))
2967
2968 (defstruct (js2-break-node
2969 (:include js2-jump-node)
2970 (:constructor nil)
2971 (:constructor make-js2-break-node (&key (type js2-BREAK)
2972 (pos js2-ts-cursor)
2973 len
2974 label
2975 target)))
2976 "AST node for a break statement.
2977 The label field is a `js2-name-node', possibly nil, for the named label
2978 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2979 is the target of the break - a label node or enclosing loop/switch statement.")
2980
2981 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2982 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2983
2984 (defun js2-print-break-node (n i)
2985 (insert (js2-make-pad i) "break")
2986 (when (js2-break-node-label n)
2987 (insert " ")
2988 (js2-print-ast (js2-break-node-label n) 0))
2989 (insert ";\n"))
2990
2991 (defstruct (js2-continue-node
2992 (:include js2-jump-node)
2993 (:constructor nil)
2994 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2995 (pos js2-ts-cursor)
2996 len
2997 label
2998 target)))
2999 "AST node for a continue statement.
3000 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3001 It is nil if continue specifies no label. The target field is the jump target:
3002 a `js2-label-node' or the innermost enclosing loop.")
3003
3004 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3005 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3006
3007 (defun js2-print-continue-node (n i)
3008 (insert (js2-make-pad i) "continue")
3009 (when (js2-continue-node-label n)
3010 (insert " ")
3011 (js2-print-ast (js2-continue-node-label n) 0))
3012 (insert ";\n"))
3013
3014 (defstruct (js2-function-node
3015 (:include js2-script-node)
3016 (:constructor nil)
3017 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3018 (pos js2-ts-cursor)
3019 len
3020 (ftype 'FUNCTION)
3021 (form 'FUNCTION_STATEMENT)
3022 (name "")
3023 params rest-p
3024 body
3025 lp 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 rest-p ; if t, the last parameter is rest parameter
3035 body ; a `js2-block-node' or expression node (1.8 only)
3036 lp ; position of arg-list open-paren, or nil if omitted
3037 rp ; position of arg-list close-paren, or nil if omitted
3038 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3039 needs-activation ; t if we need an activation object for this frame
3040 is-generator ; t if this function contains a yield
3041 member-expr) ; nonstandard Ecma extension from Rhino
3042
3043 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3044 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3045
3046 (defun js2-visit-function-node (n v)
3047 (js2-visit-ast (js2-function-node-name n) v)
3048 (dolist (p (js2-function-node-params n))
3049 (js2-visit-ast p v))
3050 (js2-visit-ast (js2-function-node-body n) v))
3051
3052 (defun js2-print-function-node (n i)
3053 (let ((pad (js2-make-pad i))
3054 (getter (js2-node-get-prop n 'GETTER_SETTER))
3055 (name (js2-function-node-name n))
3056 (params (js2-function-node-params n))
3057 (rest-p (js2-function-node-rest-p n))
3058 (body (js2-function-node-body n))
3059 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3060 (unless getter
3061 (insert pad "function"))
3062 (when name
3063 (insert " ")
3064 (js2-print-ast name 0))
3065 (insert "(")
3066 (loop with len = (length params)
3067 for param in params
3068 for count from 1
3069 do
3070 (when (and rest-p (= count len))
3071 (insert "..."))
3072 (js2-print-ast param 0)
3073 (when (< count len)
3074 (insert ", ")))
3075 (insert ") {")
3076 (unless expr
3077 (insert "\n"))
3078 ;; TODO: fix this to be smarter about indenting, etc.
3079 (js2-print-body body (1+ i))
3080 (insert pad "}")
3081 (unless expr
3082 (insert "\n"))))
3083
3084 (defsubst js2-function-name (node)
3085 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3086 (and (js2-function-node-name node)
3087 (js2-name-node-name (js2-function-node-name node))))
3088
3089 ;; Having this be an expression node makes it more flexible.
3090 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3091 ;; that work better if you assume it's an expression. Whenever we have
3092 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3093 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3094 (defstruct (js2-var-decl-node
3095 (:include js2-node)
3096 (:constructor nil)
3097 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3098 (pos js2-token-beg)
3099 len
3100 kids
3101 decl-type)))
3102 "AST node for a variable declaration list (VAR, CONST or LET).
3103 The node bounds differ depending on the declaration type. For VAR or
3104 CONST declarations, the bounds include the var/const keyword. For LET
3105 declarations, the node begins at the position of the first child."
3106 kids ; a lisp list of `js2-var-init-node' structs.
3107 decl-type) ; js2-VAR, js2-CONST or js2-LET
3108
3109 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3110 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3111
3112 (defun js2-visit-var-decl (n v)
3113 (dolist (kid (js2-var-decl-node-kids n))
3114 (js2-visit-ast kid v)))
3115
3116 (defun js2-print-var-decl (n i)
3117 (let ((pad (js2-make-pad i))
3118 (tt (js2-var-decl-node-decl-type n)))
3119 (insert pad)
3120 (insert (cond
3121 ((= tt js2-VAR) "var ")
3122 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3123 ((= tt js2-CONST) "const ")
3124 (t
3125 (error "malformed var-decl node"))))
3126 (loop with kids = (js2-var-decl-node-kids n)
3127 with len = (length kids)
3128 for kid in kids
3129 for count from 1
3130 do
3131 (js2-print-ast kid 0)
3132 (if (< count len)
3133 (insert ", ")))))
3134
3135 (defstruct (js2-var-init-node
3136 (:include js2-node)
3137 (:constructor nil)
3138 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3139 (pos js2-ts-cursor)
3140 len
3141 target
3142 initializer)))
3143 "AST node for a variable declaration.
3144 The type field will be js2-CONST for a const decl."
3145 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3146 initializer) ; initializer expression, a `js2-node'
3147
3148 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3149 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3150
3151 (defun js2-visit-var-init-node (n v)
3152 (js2-visit-ast (js2-var-init-node-target n) v)
3153 (js2-visit-ast (js2-var-init-node-initializer n) v))
3154
3155 (defun js2-print-var-init-node (n i)
3156 (let ((pad (js2-make-pad i))
3157 (name (js2-var-init-node-target n))
3158 (init (js2-var-init-node-initializer n)))
3159 (insert pad)
3160 (js2-print-ast name 0)
3161 (when init
3162 (insert " = ")
3163 (js2-print-ast init 0))))
3164
3165 (defstruct (js2-cond-node
3166 (:include js2-node)
3167 (:constructor nil)
3168 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3169 (pos js2-ts-cursor)
3170 len
3171 test-expr
3172 true-expr
3173 false-expr
3174 q-pos
3175 c-pos)))
3176 "AST node for the ternary operator"
3177 test-expr
3178 true-expr
3179 false-expr
3180 q-pos ; buffer position of ?
3181 c-pos) ; buffer position of :
3182
3183 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3184 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3185
3186 (defun js2-visit-cond-node (n v)
3187 (js2-visit-ast (js2-cond-node-test-expr n) v)
3188 (js2-visit-ast (js2-cond-node-true-expr n) v)
3189 (js2-visit-ast (js2-cond-node-false-expr n) v))
3190
3191 (defun js2-print-cond-node (n i)
3192 (let ((pad (js2-make-pad i)))
3193 (insert pad)
3194 (js2-print-ast (js2-cond-node-test-expr n) 0)
3195 (insert " ? ")
3196 (js2-print-ast (js2-cond-node-true-expr n) 0)
3197 (insert " : ")
3198 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3199
3200 (defstruct (js2-infix-node
3201 (:include js2-node)
3202 (:constructor nil)
3203 (:constructor make-js2-infix-node (&key type
3204 (pos js2-ts-cursor)
3205 len
3206 op-pos
3207 left
3208 right)))
3209 "Represents infix expressions.
3210 Includes assignment ops like `|=', and the comma operator.
3211 The type field inherited from `js2-node' holds the operator."
3212 op-pos ; buffer position where operator begins
3213 left ; any `js2-node'
3214 right) ; any `js2-node'
3215
3216 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3217 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3218
3219 (defun js2-visit-infix-node (n v)
3220 (js2-visit-ast (js2-infix-node-left n) v)
3221 (js2-visit-ast (js2-infix-node-right n) v))
3222
3223 (defconst js2-operator-tokens
3224 (let ((table (make-hash-table :test 'eq))
3225 (tokens
3226 (list (cons js2-IN "in")
3227 (cons js2-TYPEOF "typeof")
3228 (cons js2-INSTANCEOF "instanceof")
3229 (cons js2-DELPROP "delete")
3230 (cons js2-COMMA ",")
3231 (cons js2-COLON ":")
3232 (cons js2-OR "||")
3233 (cons js2-AND "&&")
3234 (cons js2-INC "++")
3235 (cons js2-DEC "--")
3236 (cons js2-BITOR "|")
3237 (cons js2-BITXOR "^")
3238 (cons js2-BITAND "&")
3239 (cons js2-EQ "==")
3240 (cons js2-NE "!=")
3241 (cons js2-LT "<")
3242 (cons js2-LE "<=")
3243 (cons js2-GT ">")
3244 (cons js2-GE ">=")
3245 (cons js2-LSH "<<")
3246 (cons js2-RSH ">>")
3247 (cons js2-URSH ">>>")
3248 (cons js2-ADD "+") ; infix plus
3249 (cons js2-SUB "-") ; infix minus
3250 (cons js2-MUL "*")
3251 (cons js2-DIV "/")
3252 (cons js2-MOD "%")
3253 (cons js2-NOT "!")
3254 (cons js2-BITNOT "~")
3255 (cons js2-POS "+") ; unary plus
3256 (cons js2-NEG "-") ; unary minus
3257 (cons js2-SHEQ "===") ; shallow equality
3258 (cons js2-SHNE "!==") ; shallow inequality
3259 (cons js2-ASSIGN "=")
3260 (cons js2-ASSIGN_BITOR "|=")
3261 (cons js2-ASSIGN_BITXOR "^=")
3262 (cons js2-ASSIGN_BITAND "&=")
3263 (cons js2-ASSIGN_LSH "<<=")
3264 (cons js2-ASSIGN_RSH ">>=")
3265 (cons js2-ASSIGN_URSH ">>>=")
3266 (cons js2-ASSIGN_ADD "+=")
3267 (cons js2-ASSIGN_SUB "-=")
3268 (cons js2-ASSIGN_MUL "*=")
3269 (cons js2-ASSIGN_DIV "/=")
3270 (cons js2-ASSIGN_MOD "%="))))
3271 (loop for (k . v) in tokens do
3272 (puthash k v table))
3273 table))
3274
3275 (defun js2-print-infix-node (n i)
3276 (let* ((tt (js2-node-type n))
3277 (op (gethash tt js2-operator-tokens)))
3278 (unless op
3279 (error "unrecognized infix operator %s" (js2-node-type n)))
3280 (insert (js2-make-pad i))
3281 (js2-print-ast (js2-infix-node-left n) 0)
3282 (unless (= tt js2-COMMA)
3283 (insert " "))
3284 (insert op)
3285 (insert " ")
3286 (js2-print-ast (js2-infix-node-right n) 0)))
3287
3288 (defstruct (js2-assign-node
3289 (:include js2-infix-node)
3290 (:constructor nil)
3291 (:constructor make-js2-assign-node (&key type
3292 (pos js2-ts-cursor)
3293 len
3294 op-pos
3295 left
3296 right)))
3297 "Represents any assignment.
3298 The type field holds the actual assignment operator.")
3299
3300 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3301 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3302
3303 (defstruct (js2-unary-node
3304 (:include js2-node)
3305 (:constructor nil)
3306 (:constructor make-js2-unary-node (&key type ; required
3307 (pos js2-ts-cursor)
3308 len
3309 operand)))
3310 "AST node type for unary operator nodes.
3311 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3312 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3313 property is added if the operator follows the operand."
3314 operand) ; a `js2-node' expression
3315
3316 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3317 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3318
3319 (defun js2-visit-unary-node (n v)
3320 (js2-visit-ast (js2-unary-node-operand n) v))
3321
3322 (defun js2-print-unary-node (n i)
3323 (let* ((tt (js2-node-type n))
3324 (op (gethash tt js2-operator-tokens))
3325 (postfix (js2-node-get-prop n 'postfix)))
3326 (unless op
3327 (error "unrecognized unary operator %s" tt))
3328 (insert (js2-make-pad i))
3329 (unless postfix
3330 (insert op))
3331 (if (or (= tt js2-TYPEOF)
3332 (= tt js2-DELPROP))
3333 (insert " "))
3334 (js2-print-ast (js2-unary-node-operand n) 0)
3335 (when postfix
3336 (insert op))))
3337
3338 (defstruct (js2-let-node
3339 (:include js2-scope)
3340 (:constructor nil)
3341 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3342 (pos js2-token-beg)
3343 len
3344 vars
3345 body
3346 lp
3347 rp)))
3348 "AST node for a let expression or a let statement.
3349 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3350 vars ; a `js2-var-decl-node'
3351 body ; a `js2-node' representing the expression or body block
3352 lp
3353 rp)
3354
3355 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3356 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3357
3358 (defun js2-visit-let-node (n v)
3359 (js2-visit-ast (js2-let-node-vars n) v)
3360 (js2-visit-ast (js2-let-node-body n) v))
3361
3362 (defun js2-print-let-node (n i)
3363 (insert (js2-make-pad i) "let (")
3364 (js2-print-ast (js2-let-node-vars n) 0)
3365 (insert ") ")
3366 (js2-print-ast (js2-let-node-body n) i))
3367
3368 (defstruct (js2-keyword-node
3369 (:include js2-node)
3370 (:constructor nil)
3371 (:constructor make-js2-keyword-node (&key type
3372 (pos js2-token-beg)
3373 (len (- js2-ts-cursor pos)))))
3374 "AST node representing a literal keyword such as `null'.
3375 Used for `null', `this', `true', `false' and `debugger'.
3376 The node type is set to js2-NULL, js2-THIS, etc.")
3377
3378 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3379 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3380
3381 (defun js2-print-keyword-node (n i)
3382 (insert (js2-make-pad i)
3383 (let ((tt (js2-node-type n)))
3384 (cond
3385 ((= tt js2-THIS) "this")
3386 ((= tt js2-NULL) "null")
3387 ((= tt js2-TRUE) "true")
3388 ((= tt js2-FALSE) "false")
3389 ((= tt js2-DEBUGGER) "debugger")
3390 (t (error "Invalid keyword literal type: %d" tt))))))
3391
3392 (defsubst js2-this-node-p (node)
3393 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3394 (eq (js2-node-type node) js2-THIS))
3395
3396 (defstruct (js2-new-node
3397 (:include js2-node)
3398 (:constructor nil)
3399 (:constructor make-js2-new-node (&key (type js2-NEW)
3400 (pos js2-token-beg)
3401 len
3402 target
3403 args
3404 initializer
3405 lp
3406 rp)))
3407 "AST node for new-expression such as new Foo()."
3408 target ; an identifier or reference
3409 args ; a lisp list of argument nodes
3410 lp ; position of left-paren, nil if omitted
3411 rp ; position of right-paren, nil if omitted
3412 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3413
3414 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3415 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3416
3417 (defun js2-visit-new-node (n v)
3418 (js2-visit-ast (js2-new-node-target n) v)
3419 (dolist (arg (js2-new-node-args n))
3420 (js2-visit-ast arg v))
3421 (js2-visit-ast (js2-new-node-initializer n) v))
3422
3423 (defun js2-print-new-node (n i)
3424 (insert (js2-make-pad i) "new ")
3425 (js2-print-ast (js2-new-node-target n))
3426 (insert "(")
3427 (js2-print-list (js2-new-node-args n))
3428 (insert ")")
3429 (when (js2-new-node-initializer n)
3430 (insert " ")
3431 (js2-print-ast (js2-new-node-initializer n))))
3432
3433 (defstruct (js2-name-node
3434 (:include js2-node)
3435 (:constructor nil)
3436 (:constructor make-js2-name-node (&key (type js2-NAME)
3437 (pos js2-token-beg)
3438 (len (- js2-ts-cursor
3439 js2-token-beg))
3440 (name js2-ts-string))))
3441 "AST node for a JavaScript identifier"
3442 name ; a string
3443 scope) ; a `js2-scope' (optional, used for codegen)
3444
3445 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3446 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3447
3448 (defun js2-print-name-node (n i)
3449 (insert (js2-make-pad i)
3450 (js2-name-node-name n)))
3451
3452 (defsubst js2-name-node-length (node)
3453 "Return identifier length of NODE, a `js2-name-node'.
3454 Returns 0 if NODE is nil or its identifier field is nil."
3455 (if node
3456 (length (js2-name-node-name node))
3457 0))
3458
3459 (defstruct (js2-number-node
3460 (:include js2-node)
3461 (:constructor nil)
3462 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3463 (pos js2-token-beg)
3464 (len (- js2-ts-cursor
3465 js2-token-beg))
3466 (value js2-ts-string)
3467 (num-value js2-ts-number))))
3468 "AST node for a number literal."
3469 value ; the original string, e.g. "6.02e23"
3470 num-value) ; the parsed number value
3471
3472 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3473 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3474
3475 (defun js2-print-number-node (n i)
3476 (insert (js2-make-pad i)
3477 (number-to-string (js2-number-node-num-value n))))
3478
3479 (defstruct (js2-regexp-node
3480 (:include js2-node)
3481 (:constructor nil)
3482 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3483 (pos js2-token-beg)
3484 (len (- js2-ts-cursor
3485 js2-token-beg))
3486 value
3487 flags)))
3488 "AST node for a regular expression literal."
3489 value ; the regexp string, without // delimiters
3490 flags) ; a string of flags, e.g. `mi'.
3491
3492 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3493 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3494
3495 (defun js2-print-regexp (n i)
3496 (insert (js2-make-pad i)
3497 "/"
3498 (js2-regexp-node-value n)
3499 "/")
3500 (if (js2-regexp-node-flags n)
3501 (insert (js2-regexp-node-flags n))))
3502
3503 (defstruct (js2-string-node
3504 (:include js2-node)
3505 (:constructor nil)
3506 (:constructor make-js2-string-node (&key (type js2-STRING)
3507 (pos js2-token-beg)
3508 (len (- js2-ts-cursor
3509 js2-token-beg))
3510 (value js2-ts-string))))
3511 "String literal.
3512 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3513 You can tell the quote type by looking at the first character."
3514 value) ; the characters of the string, including the quotes
3515
3516 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3517 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3518
3519 (defun js2-print-string-node (n i)
3520 (insert (js2-make-pad i)
3521 (js2-node-string n)))
3522
3523 (defstruct (js2-array-node
3524 (:include js2-node)
3525 (:constructor nil)
3526 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3527 (pos js2-ts-cursor)
3528 len
3529 elems)))
3530 "AST node for an array literal."
3531 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3532
3533 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3534 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3535
3536 (defun js2-visit-array-node (n v)
3537 (dolist (e (js2-array-node-elems n))
3538 (js2-visit-ast e v)))
3539
3540 (defun js2-print-array-node (n i)
3541 (insert (js2-make-pad i) "[")
3542 (js2-print-list (js2-array-node-elems n))
3543 (insert "]"))
3544
3545 (defstruct (js2-object-node
3546 (:include js2-node)
3547 (:constructor nil)
3548 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3549 (pos js2-ts-cursor)
3550 len
3551 elems)))
3552 "AST node for an object literal expression.
3553 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3554 the latter represents abbreviation in destructuring expressions."
3555 elems)
3556
3557 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3558 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3559
3560 (defun js2-visit-object-node (n v)
3561 (dolist (e (js2-object-node-elems n))
3562 (js2-visit-ast e v)))
3563
3564 (defun js2-print-object-node (n i)
3565 (insert (js2-make-pad i) "{")
3566 (js2-print-list (js2-object-node-elems n))
3567 (insert "}"))
3568
3569 (defstruct (js2-object-prop-node
3570 (:include js2-infix-node)
3571 (:constructor nil)
3572 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3573 (pos js2-ts-cursor)
3574 len
3575 left
3576 right
3577 op-pos)))
3578 "AST node for an object literal prop:value entry.
3579 The `left' field is the property: a name node, string node or number node.
3580 The `right' field is a `js2-node' representing the initializer value.")
3581
3582 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3583 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3584
3585 (defun js2-print-object-prop-node (n i)
3586 (insert (js2-make-pad i))
3587 (js2-print-ast (js2-object-prop-node-left n) 0)
3588 (insert ": ")
3589 (js2-print-ast (js2-object-prop-node-right n) 0))
3590
3591 (defstruct (js2-getter-setter-node
3592 (:include js2-infix-node)
3593 (:constructor nil)
3594 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3595 (pos js2-ts-cursor)
3596 len
3597 left
3598 right)))
3599 "AST node for a getter/setter property in an object literal.
3600 The `left' field is the `js2-name-node' naming the getter/setter prop.
3601 The `right' field is always an anonymous `js2-function-node' with a node
3602 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3603
3604 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3605 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3606
3607 (defun js2-print-getter-setter (n i)
3608 (let ((pad (js2-make-pad i))
3609 (left (js2-getter-setter-node-left n))
3610 (right (js2-getter-setter-node-right n)))
3611 (insert pad)
3612 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3613 (js2-print-ast left 0)
3614 (js2-print-ast right 0)))
3615
3616 (defstruct (js2-prop-get-node
3617 (:include js2-infix-node)
3618 (:constructor nil)
3619 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3620 (pos js2-ts-cursor)
3621 len
3622 left
3623 right)))
3624 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3625
3626 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3627 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3628
3629 (defun js2-visit-prop-get-node (n v)
3630 (js2-visit-ast (js2-prop-get-node-left n) v)
3631 (js2-visit-ast (js2-prop-get-node-right n) v))
3632
3633 (defun js2-print-prop-get-node (n i)
3634 (insert (js2-make-pad i))
3635 (js2-print-ast (js2-prop-get-node-left n) 0)
3636 (insert ".")
3637 (js2-print-ast (js2-prop-get-node-right n) 0))
3638
3639 (defstruct (js2-elem-get-node
3640 (:include js2-node)
3641 (:constructor nil)
3642 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3643 (pos js2-ts-cursor)
3644 len
3645 target
3646 element
3647 lb
3648 rb)))
3649 "AST node for an array index expression such as foo[bar]."
3650 target ; a `js2-node' - the expression preceding the "."
3651 element ; a `js2-node' - the expression in brackets
3652 lb ; position of left-bracket, nil if omitted
3653 rb) ; position of right-bracket, nil if omitted
3654
3655 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3656 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3657
3658 (defun js2-visit-elem-get-node (n v)
3659 (js2-visit-ast (js2-elem-get-node-target n) v)
3660 (js2-visit-ast (js2-elem-get-node-element n) v))
3661
3662 (defun js2-print-elem-get-node (n i)
3663 (insert (js2-make-pad i))
3664 (js2-print-ast (js2-elem-get-node-target n) 0)
3665 (insert "[")
3666 (js2-print-ast (js2-elem-get-node-element n) 0)
3667 (insert "]"))
3668
3669 (defstruct (js2-call-node
3670 (:include js2-node)
3671 (:constructor nil)
3672 (:constructor make-js2-call-node (&key (type js2-CALL)
3673 (pos js2-ts-cursor)
3674 len
3675 target
3676 args
3677 lp
3678 rp)))
3679 "AST node for a JavaScript function call."
3680 target ; a `js2-node' evaluating to the function to call
3681 args ; a lisp list of `js2-node' arguments
3682 lp ; position of open-paren, or nil if missing
3683 rp) ; position of close-paren, or nil if missing
3684
3685 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3686 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3687
3688 (defun js2-visit-call-node (n v)
3689 (js2-visit-ast (js2-call-node-target n) v)
3690 (dolist (arg (js2-call-node-args n))
3691 (js2-visit-ast arg v)))
3692
3693 (defun js2-print-call-node (n i)
3694 (insert (js2-make-pad i))
3695 (js2-print-ast (js2-call-node-target n) 0)
3696 (insert "(")
3697 (js2-print-list (js2-call-node-args n))
3698 (insert ")"))
3699
3700 (defstruct (js2-yield-node
3701 (:include js2-node)
3702 (:constructor nil)
3703 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3704 (pos js2-ts-cursor)
3705 len
3706 value)))
3707 "AST node for yield statement or expression."
3708 value) ; optional: value to be yielded
3709
3710 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3711 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3712
3713 (defun js2-visit-yield-node (n v)
3714 (js2-visit-ast (js2-yield-node-value n) v))
3715
3716 (defun js2-print-yield-node (n i)
3717 (insert (js2-make-pad i))
3718 (insert "yield")
3719 (when (js2-yield-node-value n)
3720 (insert " ")
3721 (js2-print-ast (js2-yield-node-value n) 0)))
3722
3723 (defstruct (js2-paren-node
3724 (:include js2-node)
3725 (:constructor nil)
3726 (:constructor make-js2-paren-node (&key (type js2-LP)
3727 (pos js2-ts-cursor)
3728 len
3729 expr)))
3730 "AST node for a parenthesized expression.
3731 In particular, used when the parens are syntactically optional,
3732 as opposed to required parens such as those enclosing an if-conditional."
3733 expr) ; `js2-node'
3734
3735 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3736 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3737
3738 (defun js2-visit-paren-node (n v)
3739 (js2-visit-ast (js2-paren-node-expr n) v))
3740
3741 (defun js2-print-paren-node (n i)
3742 (insert (js2-make-pad i))
3743 (insert "(")
3744 (js2-print-ast (js2-paren-node-expr n) 0)
3745 (insert ")"))
3746
3747 (defstruct (js2-array-comp-node
3748 (:include js2-scope)
3749 (:constructor nil)
3750 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3751 (pos js2-ts-cursor)
3752 len
3753 result
3754 loops
3755 filter
3756 if-pos
3757 lp
3758 rp)))
3759 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3760 result ; result expression (just after left-bracket)
3761 loops ; a lisp list of `js2-array-comp-loop-node'
3762 filter ; guard/filter expression
3763 if-pos ; buffer pos of 'if' keyword, if present, else nil
3764 lp ; buffer position of if-guard left-paren, or nil if not present
3765 rp) ; buffer position of if-guard right-paren, or nil if not present
3766
3767 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3768 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3769
3770 (defun js2-visit-array-comp-node (n v)
3771 (js2-visit-ast (js2-array-comp-node-result n) v)
3772 (dolist (l (js2-array-comp-node-loops n))
3773 (js2-visit-ast l v))
3774 (js2-visit-ast (js2-array-comp-node-filter n) v))
3775
3776 (defun js2-print-array-comp-node (n i)
3777 (let ((pad (js2-make-pad i))
3778 (result (js2-array-comp-node-result n))
3779 (loops (js2-array-comp-node-loops n))
3780 (filter (js2-array-comp-node-filter n)))
3781 (insert pad "[")
3782 (js2-print-ast result 0)
3783 (dolist (l loops)
3784 (insert " ")
3785 (js2-print-ast l 0))
3786 (when filter
3787 (insert " if (")
3788 (js2-print-ast filter 0)
3789 (insert ")"))
3790 (insert "]")))
3791
3792 (defstruct (js2-array-comp-loop-node
3793 (:include js2-for-in-node)
3794 (:constructor nil)
3795 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3796 (pos js2-ts-cursor)
3797 len
3798 iterator
3799 object
3800 in-pos
3801 foreach-p
3802 each-pos
3803 forof-p
3804 lp rp)))
3805 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3806
3807 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3808 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3809
3810 (defun js2-visit-array-comp-loop (n v)
3811 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3812 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3813
3814 (defun js2-print-array-comp-loop (n i)
3815 (insert "for (")
3816 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3817 (if (js2-array-comp-loop-node-forof-p n)
3818 (insert " of ")
3819 (insert " in "))
3820 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3821 (insert ")"))
3822
3823 (defstruct (js2-empty-expr-node
3824 (:include js2-node)
3825 (:constructor nil)
3826 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3827 (pos js2-token-beg)
3828 len)))
3829 "AST node for an empty expression.")
3830
3831 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3832 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3833
3834 (defstruct (js2-xml-node
3835 (:include js2-block-node)
3836 (:constructor nil)
3837 (:constructor make-js2-xml-node (&key (type js2-XML)
3838 (pos js2-token-beg)
3839 len
3840 kids)))
3841 "AST node for initial parse of E4X literals.
3842 The kids field is a list of XML fragments, each a `js2-string-node' or
3843 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3844
3845 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3846 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3847
3848 (defun js2-print-xml-node (n i)
3849 (dolist (kid (js2-xml-node-kids n))
3850 (js2-print-ast kid i)))
3851
3852 (defstruct (js2-xml-js-expr-node
3853 (:include js2-xml-node)
3854 (:constructor nil)
3855 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3856 (pos js2-ts-cursor)
3857 len
3858 expr)))
3859 "AST node for an embedded JavaScript {expression} in an E4X literal.
3860 The start and end fields correspond to the curly-braces."
3861 expr) ; a `js2-expr-node' of some sort
3862
3863 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3864 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3865
3866 (defun js2-visit-xml-js-expr (n v)
3867 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3868
3869 (defun js2-print-xml-js-expr (n i)
3870 (insert (js2-make-pad i))
3871 (insert "{")
3872 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3873 (insert "}"))
3874
3875 (defstruct (js2-xml-dot-query-node
3876 (:include js2-infix-node)
3877 (:constructor nil)
3878 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3879 (pos js2-ts-cursor)
3880 op-pos
3881 len
3882 left
3883 right
3884 rp)))
3885 "AST node for an E4X foo.(bar) filter expression.
3886 Note that the left-paren is automatically the character immediately
3887 following the dot (.) in the operator. No whitespace is permitted
3888 between the dot and the lp by the scanner."
3889 rp)
3890
3891 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3892 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3893
3894 (defun js2-print-xml-dot-query (n i)
3895 (insert (js2-make-pad i))
3896 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3897 (insert ".(")
3898 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3899 (insert ")"))
3900
3901 (defstruct (js2-xml-ref-node
3902 (:include js2-node)
3903 (:constructor nil)) ; abstract
3904 "Base type for E4X XML attribute-access or property-get expressions.
3905 Such expressions can take a variety of forms. The general syntax has
3906 three parts:
3907
3908 - (optional) an @ (specifying an attribute access)
3909 - (optional) a namespace (a `js2-name-node') and double-colon
3910 - (required) either a `js2-name-node' or a bracketed [expression]
3911
3912 The property-name expressions (examples: ns::name, @name) are
3913 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3914 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3915
3916 This node type (or more specifically, its subclasses) will sometimes
3917 be the right-hand child of a `js2-prop-get-node' or a
3918 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3919 The `js2-xml-ref-node' may also be a standalone primary expression with
3920 no explicit target, which is valid in certain expression contexts such as
3921
3922 company..employee.(@id < 100)
3923
3924 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3925 expression whose parent is a `js2-xml-dot-query-node'."
3926 namespace
3927 at-pos
3928 colon-pos)
3929
3930 (defsubst js2-xml-ref-node-attr-access-p (node)
3931 "Return non-nil if this expression began with an @-token."
3932 (and (numberp (js2-xml-ref-node-at-pos node))
3933 (plusp (js2-xml-ref-node-at-pos node))))
3934
3935 (defstruct (js2-xml-prop-ref-node
3936 (:include js2-xml-ref-node)
3937 (:constructor nil)
3938 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3939 (pos js2-token-beg)
3940 len
3941 propname
3942 namespace
3943 at-pos
3944 colon-pos)))
3945 "AST node for an E4X XML [expr] property-ref expression.
3946 The JavaScript syntax is an optional @, an optional ns::, and a name.
3947
3948 [ '@' ] [ name '::' ] name
3949
3950 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3951 @ns::*, @*::attr, @*::*, and @*.
3952
3953 The node starts at the @ token, if present. Otherwise it starts at the
3954 namespace name. The node bounds extend through the closing right-bracket,
3955 or if it is missing due to a syntax error, through the end of the index
3956 expression."
3957 propname)
3958
3959 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3960 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3961
3962 (defun js2-visit-xml-prop-ref-node (n v)
3963 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3964 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3965
3966 (defun js2-print-xml-prop-ref-node (n i)
3967 (insert (js2-make-pad i))
3968 (if (js2-xml-ref-node-attr-access-p n)
3969 (insert "@"))
3970 (when (js2-xml-prop-ref-node-namespace n)
3971 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3972 (insert "::"))
3973 (if (js2-xml-prop-ref-node-propname n)
3974 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3975
3976 (defstruct (js2-xml-elem-ref-node
3977 (:include js2-xml-ref-node)
3978 (:constructor nil)
3979 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3980 (pos js2-token-beg)
3981 len
3982 expr
3983 lb
3984 rb
3985 namespace
3986 at-pos
3987 colon-pos)))
3988 "AST node for an E4X XML [expr] member-ref expression.
3989 Syntax:
3990
3991 [ '@' ] [ name '::' ] '[' expr ']'
3992
3993 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3994
3995 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3996 is not a legal E4X XML element-ref expression, since it's already used
3997 for standard JavaScript element-get array indexing. Hence, a
3998 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3999 non-nil namespace node, or both.
4000
4001 The node starts at the @ token, if present. Otherwise it starts
4002 at the namespace name. The node bounds extend through the closing
4003 right-bracket, or if it is missing due to a syntax error, through the
4004 end of the index expression."
4005 expr ; the bracketed index expression
4006 lb
4007 rb)
4008
4009 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4010 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4011
4012 (defun js2-visit-xml-elem-ref-node (n v)
4013 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4014 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4015
4016 (defun js2-print-xml-elem-ref-node (n i)
4017 (insert (js2-make-pad i))
4018 (if (js2-xml-ref-node-attr-access-p n)
4019 (insert "@"))
4020 (when (js2-xml-elem-ref-node-namespace n)
4021 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4022 (insert "::"))
4023 (insert "[")
4024 (if (js2-xml-elem-ref-node-expr n)
4025 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4026 (insert "]"))
4027
4028 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4029
4030 (defstruct (js2-xml-start-tag-node
4031 (:include js2-xml-node)
4032 (:constructor nil)
4033 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4034 (pos js2-ts-cursor)
4035 len
4036 name
4037 attrs
4038 kids
4039 empty-p)))
4040 "AST node for an XML start-tag. Not currently used.
4041 The `kids' field is a lisp list of child content nodes."
4042 name ; a `js2-xml-name-node'
4043 attrs ; a lisp list of `js2-xml-attr-node'
4044 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4045
4046 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4047 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4048
4049 (defun js2-visit-xml-start-tag (n v)
4050 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4051 (dolist (attr (js2-xml-start-tag-node-attrs n))
4052 (js2-visit-ast attr v))
4053 (js2-visit-block n v))
4054
4055 (defun js2-print-xml-start-tag (n i)
4056 (insert (js2-make-pad i) "<")
4057 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4058 (when (js2-xml-start-tag-node-attrs n)
4059 (insert " ")
4060 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4061 (insert ">"))
4062
4063 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4064 ;; and add the end-tag to the kids list of the parent as well.
4065 (defstruct (js2-xml-end-tag-node
4066 (:include js2-xml-node)
4067 (:constructor nil)
4068 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4069 (pos js2-ts-cursor)
4070 len
4071 name)))
4072 "AST node for an XML end-tag. Not currently used."
4073 name) ; a `js2-xml-name-node'
4074
4075 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4076 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4077
4078 (defun js2-visit-xml-end-tag (n v)
4079 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4080
4081 (defun js2-print-xml-end-tag (n i)
4082 (insert (js2-make-pad i))
4083 (insert "</")
4084 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4085 (insert ">"))
4086
4087 (defstruct (js2-xml-name-node
4088 (:include js2-xml-node)
4089 (:constructor nil)
4090 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4091 (pos js2-ts-cursor)
4092 len
4093 namespace
4094 kids)))
4095 "AST node for an E4X XML name. Not currently used.
4096 Any XML name can be qualified with a namespace, hence the namespace field.
4097 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4098 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4099 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4100 namespace) ; a `js2-string-node'
4101
4102 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4103 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4104
4105 (defun js2-visit-xml-name-node (n v)
4106 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4107
4108 (defun js2-print-xml-name-node (n i)
4109 (insert (js2-make-pad i))
4110 (when (js2-xml-name-node-namespace n)
4111 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4112 (insert "::"))
4113 (dolist (kid (js2-xml-name-node-kids n))
4114 (js2-print-ast kid 0)))
4115
4116 (defstruct (js2-xml-pi-node
4117 (:include js2-xml-node)
4118 (:constructor nil)
4119 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4120 (pos js2-ts-cursor)
4121 len
4122 name
4123 attrs)))
4124 "AST node for an E4X XML processing instruction. Not currently used."
4125 name ; a `js2-xml-name-node'
4126 attrs) ; a list of `js2-xml-attr-node'
4127
4128 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4129 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4130
4131 (defun js2-visit-xml-pi-node (n v)
4132 (js2-visit-ast (js2-xml-pi-node-name n) v)
4133 (dolist (attr (js2-xml-pi-node-attrs n))
4134 (js2-visit-ast attr v)))
4135
4136 (defun js2-print-xml-pi-node (n i)
4137 (insert (js2-make-pad i) "<?")
4138 (js2-print-ast (js2-xml-pi-node-name n))
4139 (when (js2-xml-pi-node-attrs n)
4140 (insert " ")
4141 (js2-print-list (js2-xml-pi-node-attrs n)))
4142 (insert "?>"))
4143
4144 (defstruct (js2-xml-cdata-node
4145 (:include js2-xml-node)
4146 (:constructor nil)
4147 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4148 (pos js2-ts-cursor)
4149 len
4150 content)))
4151 "AST node for a CDATA escape section. Not currently used."
4152 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4153
4154 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4155 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4156
4157 (defun js2-visit-xml-cdata-node (n v)
4158 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4159
4160 (defun js2-print-xml-cdata-node (n i)
4161 (insert (js2-make-pad i))
4162 (js2-print-ast (js2-xml-cdata-node-content n)))
4163
4164 (defstruct (js2-xml-attr-node
4165 (:include js2-xml-node)
4166 (:constructor nil)
4167 (:constructor make-js2-attr-node (&key (type js2-XML)
4168 (pos js2-ts-cursor)
4169 len
4170 name
4171 value
4172 eq-pos
4173 quote-type)))
4174 "AST node representing a foo='bar' XML attribute value. Not yet used."
4175 name ; a `js2-xml-name-node'
4176 value ; a `js2-xml-name-node'
4177 eq-pos ; buffer position of "=" sign
4178 quote-type) ; 'single or 'double
4179
4180 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4181 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4182
4183 (defun js2-visit-xml-attr-node (n v)
4184 (js2-visit-ast (js2-xml-attr-node-name n) v)
4185 (js2-visit-ast (js2-xml-attr-node-value n) v))
4186
4187 (defun js2-print-xml-attr-node (n i)
4188 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4189 "'"
4190 "\"")))
4191 (insert (js2-make-pad i))
4192 (js2-print-ast (js2-xml-attr-node-name n) 0)
4193 (insert "=" quote)
4194 (js2-print-ast (js2-xml-attr-node-value n) 0)
4195 (insert quote)))
4196
4197 (defstruct (js2-xml-text-node
4198 (:include js2-xml-node)
4199 (:constructor nil)
4200 (:constructor make-js2-text-node (&key (type js2-XML)
4201 (pos js2-ts-cursor)
4202 len
4203 content)))
4204 "AST node for an E4X XML text node. Not currently used."
4205 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4206
4207 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4208 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4209
4210 (defun js2-visit-xml-text-node (n v)
4211 (js2-visit-ast (js2-xml-text-node-content n) v))
4212
4213 (defun js2-print-xml-text-node (n i)
4214 (insert (js2-make-pad i))
4215 (dolist (kid (js2-xml-text-node-content n))
4216 (js2-print-ast kid)))
4217
4218 (defstruct (js2-xml-comment-node
4219 (:include js2-xml-node)
4220 (:constructor nil)
4221 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4222 (pos js2-ts-cursor)
4223 len)))
4224 "AST node for E4X XML comment. Not currently used.")
4225
4226 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4227 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4228
4229 (defun js2-print-xml-comment (n i)
4230 (insert (js2-make-pad i)
4231 (js2-node-string n)))
4232
4233 ;;; Node utilities
4234
4235 (defsubst js2-node-line (n)
4236 "Fetch the source line number at the start of node N.
4237 This is O(n) in the length of the source buffer; use prudently."
4238 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4239
4240 (defsubst js2-block-node-kid (n i)
4241 "Return child I of node N, or nil if there aren't that many."
4242 (nth i (js2-block-node-kids n)))
4243
4244 (defsubst js2-block-node-first (n)
4245 "Return first child of block node N, or nil if there is none."
4246 (first (js2-block-node-kids n)))
4247
4248 (defun js2-node-root (n)
4249 "Return the root of the AST containing N.
4250 If N has no parent pointer, returns N."
4251 (let ((parent (js2-node-parent n)))
4252 (if parent
4253 (js2-node-root parent)
4254 n)))
4255
4256 (defun js2-node-position-in-parent (node &optional parent)
4257 "Return the position of NODE in parent's block-kids list.
4258 PARENT can be supplied if known. Positioned returned is zero-indexed.
4259 Returns 0 if NODE is not a child of a block statement, or if NODE
4260 is not a statement node."
4261 (let ((p (or parent (js2-node-parent node)))
4262 (i 0))
4263 (if (not (js2-block-node-p p))
4264 i
4265 (or (js2-position node (js2-block-node-kids p))
4266 0))))
4267
4268 (defsubst js2-node-short-name (n)
4269 "Return the short name of node N as a string, e.g. `js2-if-node'."
4270 (substring (symbol-name (aref n 0))
4271 (length "cl-struct-")))
4272
4273 (defsubst js2-node-child-list (node)
4274 "Return the child list for NODE, a lisp list of nodes.
4275 Works for block nodes, array nodes, obj literals, funarg lists,
4276 var decls and try nodes (for catch clauses). Note that you should call
4277 `js2-block-node-kids' on the function body for the body statements.
4278 Returns nil for zero-length child lists or unsupported nodes."
4279 (cond
4280 ((js2-function-node-p node)
4281 (js2-function-node-params node))
4282 ((js2-block-node-p node)
4283 (js2-block-node-kids node))
4284 ((js2-try-node-p node)
4285 (js2-try-node-catch-clauses node))
4286 ((js2-array-node-p node)
4287 (js2-array-node-elems node))
4288 ((js2-object-node-p node)
4289 (js2-object-node-elems node))
4290 ((js2-call-node-p node)
4291 (js2-call-node-args node))
4292 ((js2-new-node-p node)
4293 (js2-new-node-args node))
4294 ((js2-var-decl-node-p node)
4295 (js2-var-decl-node-kids node))
4296 (t
4297 nil)))
4298
4299 (defsubst js2-node-set-child-list (node kids)
4300 "Set the child list for NODE to KIDS."
4301 (cond
4302 ((js2-function-node-p node)
4303 (setf (js2-function-node-params node) kids))
4304 ((js2-block-node-p node)
4305 (setf (js2-block-node-kids node) kids))
4306 ((js2-try-node-p node)
4307 (setf (js2-try-node-catch-clauses node) kids))
4308 ((js2-array-node-p node)
4309 (setf (js2-array-node-elems node) kids))
4310 ((js2-object-node-p node)
4311 (setf (js2-object-node-elems node) kids))
4312 ((js2-call-node-p node)
4313 (setf (js2-call-node-args node) kids))
4314 ((js2-new-node-p node)
4315 (setf (js2-new-node-args node) kids))
4316 ((js2-var-decl-node-p node)
4317 (setf (js2-var-decl-node-kids node) kids))
4318 (t
4319 (error "Unsupported node type: %s" (js2-node-short-name node))))
4320 kids)
4321
4322 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4323 (defconst js2-paren-expr-nodes
4324 '(cl-struct-js2-array-comp-loop-node
4325 cl-struct-js2-array-comp-node
4326 cl-struct-js2-call-node
4327 cl-struct-js2-catch-node
4328 cl-struct-js2-do-node
4329 cl-struct-js2-elem-get-node
4330 cl-struct-js2-for-in-node
4331 cl-struct-js2-for-node
4332 cl-struct-js2-function-node
4333 cl-struct-js2-if-node
4334 cl-struct-js2-let-node
4335 cl-struct-js2-new-node
4336 cl-struct-js2-paren-node
4337 cl-struct-js2-switch-node
4338 cl-struct-js2-while-node
4339 cl-struct-js2-with-node
4340 cl-struct-js2-xml-dot-query-node)
4341 "Node types that can have a parenthesized child expression.
4342 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4343
4344 (defsubst js2-paren-expr-node-p (node)
4345 "Return t for nodes that typically have a parenthesized child expression.
4346 Useful for computing the indentation anchors for arg-lists and conditions.
4347 Note that it may return a false positive, for instance when NODE is
4348 a `js2-new-node' and there are no arguments or parentheses."
4349 (memq (aref node 0) js2-paren-expr-nodes))
4350
4351 ;; Fake polymorphism... yech.
4352 (defsubst js2-node-lp (node)
4353 "Return relative left-paren position for NODE, if applicable.
4354 For `js2-elem-get-node' structs, returns left-bracket position.
4355 Note that the position may be nil in the case of a parse error."
4356 (cond
4357 ((js2-elem-get-node-p node)
4358 (js2-elem-get-node-lb node))
4359 ((js2-loop-node-p node)
4360 (js2-loop-node-lp node))
4361 ((js2-function-node-p node)
4362 (js2-function-node-lp node))
4363 ((js2-if-node-p node)
4364 (js2-if-node-lp node))
4365 ((js2-new-node-p node)
4366 (js2-new-node-lp node))
4367 ((js2-call-node-p node)
4368 (js2-call-node-lp node))
4369 ((js2-paren-node-p node)
4370 (js2-node-pos node))
4371 ((js2-switch-node-p node)
4372 (js2-switch-node-lp node))
4373 ((js2-catch-node-p node)
4374 (js2-catch-node-lp node))
4375 ((js2-let-node-p node)
4376 (js2-let-node-lp node))
4377 ((js2-array-comp-node-p node)
4378 (js2-array-comp-node-lp node))
4379 ((js2-with-node-p node)
4380 (js2-with-node-lp node))
4381 ((js2-xml-dot-query-node-p node)
4382 (1+ (js2-infix-node-op-pos node)))
4383 (t
4384 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4385
4386 ;; Fake polymorphism... blech.
4387 (defsubst js2-node-rp (node)
4388 "Return relative right-paren position for NODE, if applicable.
4389 For `js2-elem-get-node' structs, returns right-bracket position.
4390 Note that the position may be nil in the case of a parse error."
4391 (cond
4392 ((js2-elem-get-node-p node)
4393 (js2-elem-get-node-rb node))
4394 ((js2-loop-node-p node)
4395 (js2-loop-node-rp node))
4396 ((js2-function-node-p node)
4397 (js2-function-node-rp node))
4398 ((js2-if-node-p node)
4399 (js2-if-node-rp node))
4400 ((js2-new-node-p node)
4401 (js2-new-node-rp node))
4402 ((js2-call-node-p node)
4403 (js2-call-node-rp node))
4404 ((js2-paren-node-p node)
4405 (+ (js2-node-pos node) (js2-node-len node)))
4406 ((js2-switch-node-p node)
4407 (js2-switch-node-rp node))
4408 ((js2-catch-node-p node)
4409 (js2-catch-node-rp node))
4410 ((js2-let-node-p node)
4411 (js2-let-node-rp node))
4412 ((js2-array-comp-node-p node)
4413 (js2-array-comp-node-rp node))
4414 ((js2-with-node-p node)
4415 (js2-with-node-rp node))
4416 ((js2-xml-dot-query-node-p node)
4417 (1+ (js2-xml-dot-query-node-rp node)))
4418 (t
4419 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4420
4421 (defsubst js2-node-first-child (node)
4422 "Returns the first element of `js2-node-child-list' for NODE."
4423 (car (js2-node-child-list node)))
4424
4425 (defsubst js2-node-last-child (node)
4426 "Returns the last element of `js2-node-last-child' for NODE."
4427 (car (last (js2-node-child-list node))))
4428
4429 (defun js2-node-prev-sibling (node)
4430 "Return the previous statement in parent.
4431 Works for parents supported by `js2-node-child-list'.
4432 Returns nil if NODE is not in the parent, or PARENT is
4433 not a supported node, or if NODE is the first child."
4434 (let* ((p (js2-node-parent node))
4435 (kids (js2-node-child-list p))
4436 (sib (car kids)))
4437 (while (and kids
4438 (not (eq node (cadr kids))))
4439 (setq kids (cdr kids)
4440 sib (car kids)))
4441 sib))
4442
4443 (defun js2-node-next-sibling (node)
4444 "Return the next statement in parent block.
4445 Returns nil if NODE is not in the block, or PARENT is not
4446 a block node, or if NODE is the last statement."
4447 (let* ((p (js2-node-parent node))
4448 (kids (js2-node-child-list p)))
4449 (while (and kids
4450 (not (eq node (car kids))))
4451 (setq kids (cdr kids)))
4452 (cadr kids)))
4453
4454 (defun js2-node-find-child-before (pos parent &optional after)
4455 "Find the last child that starts before POS in parent.
4456 If AFTER is non-nil, returns first child starting after POS.
4457 POS is an absolute buffer position. PARENT is any node
4458 supported by `js2-node-child-list'.
4459 Returns nil if no applicable child is found."
4460 (let ((kids (if (js2-function-node-p parent)
4461 (js2-block-node-kids (js2-function-node-body parent))
4462 (js2-node-child-list parent)))
4463 (beg (if (js2-function-node-p parent)
4464 (js2-node-abs-pos (js2-function-node-body parent))
4465 (js2-node-abs-pos parent)))
4466 kid
4467 result
4468 fn
4469 (continue t))
4470 (setq fn (if after '>= '<))
4471 (while (and kids continue)
4472 (setq kid (car kids))
4473 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4474 (setq result kid
4475 continue (if after nil t))
4476 (setq continue (if after t nil)))
4477 (setq kids (cdr kids)))
4478 result))
4479
4480 (defun js2-node-find-child-after (pos parent)
4481 "Find first child that starts after POS in parent.
4482 POS is an absolute buffer position. PARENT is any node
4483 supported by `js2-node-child-list'.
4484 Returns nil if no applicable child is found."
4485 (js2-node-find-child-before pos parent 'after))
4486
4487 (defun js2-node-replace-child (pos parent new-node)
4488 "Replace node at index POS in PARENT with NEW-NODE.
4489 Only works for parents supported by `js2-node-child-list'."
4490 (let ((kids (js2-node-child-list parent))
4491 (i 0))
4492 (while (< i pos)
4493 (setq kids (cdr kids)
4494 i (1+ i)))
4495 (setcar kids new-node)
4496 (js2-node-add-children parent new-node)))
4497
4498 (defun js2-node-buffer (n)
4499 "Return the buffer associated with AST N.
4500 Returns nil if the buffer is not set as a property on the root
4501 node, or if parent links were not recorded during parsing."
4502 (let ((root (js2-node-root n)))
4503 (and root
4504 (js2-ast-root-p root)
4505 (js2-ast-root-buffer root))))
4506
4507 (defsubst js2-block-node-push (n kid)
4508 "Push js2-node KID onto the end of js2-block-node N's child list.
4509 KID is always added to the -end- of the kids list.
4510 Function also calls `js2-node-add-children' to add the parent link."
4511 (let ((kids (js2-node-child-list n)))
4512 (if kids
4513 (setcdr kids (nconc (cdr kids) (list kid)))
4514 (js2-node-set-child-list n (list kid)))
4515 (js2-node-add-children n kid)))
4516
4517 (defun js2-node-string (node)
4518 (let ((buf (js2-node-buffer node))
4519 pos)
4520 (unless buf
4521 (error "No buffer available for node %s" node))
4522 (with-current-buffer buf
4523 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4524 (+ pos (js2-node-len node))))))
4525
4526 ;; Container for storing the node we're looking for in a traversal.
4527 (js2-deflocal js2-discovered-node nil)
4528
4529 ;; Keep track of absolute node position during traversals.
4530 (js2-deflocal js2-visitor-offset nil)
4531
4532 (js2-deflocal js2-node-search-point nil)
4533
4534 (when js2-mode-dev-mode-p
4535 (defun js2-find-node-at-point ()
4536 (interactive)
4537 (let ((node (js2-node-at-point)))
4538 (message "%s" (or node "No node found at point"))))
4539 (defun js2-node-name-at-point ()
4540 (interactive)
4541 (let ((node (js2-node-at-point)))
4542 (message "%s" (if node
4543 (js2-node-short-name node)
4544 "No node found at point.")))))
4545
4546 (defun js2-node-at-point (&optional pos skip-comments)
4547 "Return AST node at POS, a buffer position, defaulting to current point.
4548 The `js2-mode-ast' variable must be set to the current parse tree.
4549 Signals an error if the AST (`js2-mode-ast') is nil.
4550 Always returns a node - if it can't find one, it returns the root.
4551 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4552 (let ((ast js2-mode-ast)
4553 result)
4554 (unless ast
4555 (error "No JavaScript AST available"))
4556 ;; Look through comments first, since they may be inside nodes that
4557 ;; would otherwise report a match.
4558 (setq pos (or pos (point))
4559 result (if (> pos (js2-node-abs-end ast))
4560 ast
4561 (if (not skip-comments)
4562 (js2-comment-at-point pos))))
4563 (unless result
4564 (setq js2-discovered-node nil
4565 js2-visitor-offset 0
4566 js2-node-search-point pos)
4567 (unwind-protect
4568 (catch 'js2-visit-done
4569 (js2-visit-ast ast #'js2-node-at-point-visitor))
4570 (setq js2-visitor-offset nil
4571 js2-node-search-point nil))
4572 (setq result js2-discovered-node))
4573 ;; may have found a comment beyond end of last child node,
4574 ;; since visiting the ast-root looks at the comment-list last.
4575 (if (and skip-comments
4576 (js2-comment-node-p result))
4577 (setq result nil))
4578 (or result js2-mode-ast)))
4579
4580 (defun js2-node-at-point-visitor (node end-p)
4581 (let ((rel-pos (js2-node-pos node))
4582 abs-pos
4583 abs-end
4584 (point js2-node-search-point))
4585 (cond
4586 (end-p
4587 ;; this evaluates to a non-nil return value, even if it's zero
4588 (decf js2-visitor-offset rel-pos))
4589 ;; we already looked for comments before visiting, and don't want them now
4590 ((js2-comment-node-p node)
4591 nil)
4592 (t
4593 (setq abs-pos (incf js2-visitor-offset rel-pos)
4594 ;; we only want to use the node if the point is before
4595 ;; the last character position in the node, so we decrement
4596 ;; the absolute end by 1.
4597 abs-end (+ abs-pos (js2-node-len node) -1))
4598 (cond
4599 ;; If this node starts after search-point, stop the search.
4600 ((> abs-pos point)
4601 (throw 'js2-visit-done nil))
4602 ;; If this node ends before the search-point, don't check kids.
4603 ((> point abs-end)
4604 nil)
4605 (t
4606 ;; Otherwise point is within this node, possibly in a child.
4607 (setq js2-discovered-node node)
4608 t)))))) ; keep processing kids to look for more specific match
4609
4610 (defsubst js2-block-comment-p (node)
4611 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4612 (and (js2-comment-node-p node)
4613 (memq (js2-comment-node-format node) '(jsdoc block))))
4614
4615 ;; TODO: put the comments in a vector and binary-search them instead
4616 (defun js2-comment-at-point (&optional pos)
4617 "Look through scanned comment nodes for one containing POS.
4618 POS is a buffer position that defaults to current point.
4619 Function returns nil if POS was not in any comment node."
4620 (let ((ast js2-mode-ast)
4621 (x (or pos (point)))
4622 beg
4623 end)
4624 (unless ast
4625 (error "No JavaScript AST available"))
4626 (catch 'done
4627 ;; Comments are stored in lexical order.
4628 (dolist (comment (js2-ast-root-comments ast) nil)
4629 (setq beg (js2-node-abs-pos comment)
4630 end (+ beg (js2-node-len comment)))
4631 (if (and (>= x beg)
4632 (<= x end))
4633 (throw 'done comment))))))
4634
4635 (defun js2-mode-find-parent-fn (node)
4636 "Find function enclosing NODE.
4637 Returns nil if NODE is not inside a function."
4638 (setq node (js2-node-parent node))
4639 (while (and node (not (js2-function-node-p node)))
4640 (setq node (js2-node-parent node)))
4641 (and (js2-function-node-p node) node))
4642
4643 (defun js2-mode-find-enclosing-fn (node)
4644 "Find function or root enclosing NODE."
4645 (if (js2-ast-root-p node)
4646 node
4647 (setq node (js2-node-parent node))
4648 (while (not (or (js2-ast-root-p node)
4649 (js2-function-node-p node)))
4650 (setq node (js2-node-parent node)))
4651 node))
4652
4653 (defun js2-mode-find-enclosing-node (beg end)
4654 "Find script or function fully enclosing BEG and END."
4655 (let ((node (js2-node-at-point beg))
4656 pos
4657 (continue t))
4658 (while continue
4659 (if (or (js2-ast-root-p node)
4660 (and (js2-function-node-p node)
4661 (<= (setq pos (js2-node-abs-pos node)) beg)
4662 (>= (+ pos (js2-node-len node)) end)))
4663 (setq continue nil)
4664 (setq node (js2-node-parent node))))
4665 node))
4666
4667 (defun js2-node-parent-script-or-fn (node)
4668 "Find script or function immediately enclosing NODE.
4669 If NODE is the ast-root, returns nil."
4670 (if (js2-ast-root-p node)
4671 nil
4672 (setq node (js2-node-parent node))
4673 (while (and node (not (or (js2-function-node-p node)
4674 (js2-script-node-p node))))
4675 (setq node (js2-node-parent node)))
4676 node))
4677
4678 (defsubst js2-nested-function-p (node)
4679 "Return t if NODE is a nested function, or is inside a nested function."
4680 (unless (js2-ast-root-p node)
4681 (js2-function-node-p (if (js2-function-node-p node)
4682 (js2-node-parent-script-or-fn node)
4683 (js2-node-parent-script-or-fn
4684 (js2-node-parent-script-or-fn node))))))
4685
4686 (defsubst js2-function-param-node-p (node)
4687 "Return non-nil if NODE is a param node of a `js2-function-node'."
4688 (let ((parent (js2-node-parent node)))
4689 (and parent
4690 (js2-function-node-p parent)
4691 (memq node (js2-function-node-params parent)))))
4692
4693 (defsubst js2-mode-shift-kids (kids start offset)
4694 (dolist (kid kids)
4695 (if (> (js2-node-pos kid) start)
4696 (incf (js2-node-pos kid) offset))))
4697
4698 (defsubst js2-mode-shift-children (parent start offset)
4699 "Update start-positions of all children of PARENT beyond START."
4700 (let ((root (js2-node-root parent)))
4701 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4702 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4703
4704 (defsubst js2-node-is-descendant (node ancestor)
4705 "Return t if NODE is a descendant of ANCESTOR."
4706 (while (and node
4707 (not (eq node ancestor)))
4708 (setq node (js2-node-parent node)))
4709 node)
4710
4711 ;;; visitor infrastructure
4712
4713 (defun js2-visit-none (node callback)
4714 "Visitor for AST node that have no node children."
4715 nil)
4716
4717 (defun js2-print-none (node indent)
4718 "Visitor for AST node with no printed representation.")
4719
4720 (defun js2-print-body (node indent)
4721 "Print a statement, or a block without braces."
4722 (if (js2-block-node-p node)
4723 (dolist (kid (js2-block-node-kids node))
4724 (js2-print-ast kid indent))
4725 (js2-print-ast node indent)))
4726
4727 (defun js2-print-list (args &optional delimiter)
4728 (loop with len = (length args)
4729 for arg in args
4730 for count from 1
4731 do
4732 (js2-print-ast arg 0)
4733 (if (< count len)
4734 (insert (or delimiter ", ")))))
4735
4736 (defun js2-print-tree (ast)
4737 "Prints an AST to the current buffer.
4738 Makes `js2-ast-parent-nodes' available to the printer functions."
4739 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4740 (js2-print-ast ast)))
4741
4742 (defun js2-print-ast (node &optional indent)
4743 "Helper function for printing AST nodes.
4744 Requires `js2-ast-parent-nodes' to be non-nil.
4745 You should use `js2-print-tree' instead of this function."
4746 (let ((printer (get (aref node 0) 'js2-printer))
4747 (i (or indent 0))
4748 (pos (js2-node-abs-pos node)))
4749 ;; TODO: wedge comments in here somewhere
4750 (if printer
4751 (funcall printer node i))))
4752
4753 (defconst js2-side-effecting-tokens
4754 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4755 (dolist (tt (list js2-ASSIGN
4756 js2-ASSIGN_ADD
4757 js2-ASSIGN_BITAND
4758 js2-ASSIGN_BITOR
4759 js2-ASSIGN_BITXOR
4760 js2-ASSIGN_DIV
4761 js2-ASSIGN_LSH
4762 js2-ASSIGN_MOD
4763 js2-ASSIGN_MUL
4764 js2-ASSIGN_RSH
4765 js2-ASSIGN_SUB
4766 js2-ASSIGN_URSH
4767 js2-BLOCK
4768 js2-BREAK
4769 js2-CALL
4770 js2-CATCH
4771 js2-CATCH_SCOPE
4772 js2-CONST
4773 js2-CONTINUE
4774 js2-DEBUGGER
4775 js2-DEC
4776 js2-DELPROP
4777 js2-DEL_REF
4778 js2-DO
4779 js2-ELSE
4780 js2-EMPTY
4781 js2-ENTERWITH
4782 js2-EXPORT
4783 js2-EXPR_RESULT
4784 js2-FINALLY
4785 js2-FOR
4786 js2-FUNCTION
4787 js2-GOTO
4788 js2-IF
4789 js2-IFEQ
4790 js2-IFNE
4791 js2-IMPORT
4792 js2-INC
4793 js2-JSR
4794 js2-LABEL
4795 js2-LEAVEWITH
4796 js2-LET
4797 js2-LETEXPR
4798 js2-LOCAL_BLOCK
4799 js2-LOOP
4800 js2-NEW
4801 js2-REF_CALL
4802 js2-RETHROW
4803 js2-RETURN
4804 js2-RETURN_RESULT
4805 js2-SEMI
4806 js2-SETELEM
4807 js2-SETELEM_OP
4808 js2-SETNAME
4809 js2-SETPROP
4810 js2-SETPROP_OP
4811 js2-SETVAR
4812 js2-SET_REF
4813 js2-SET_REF_OP
4814 js2-SWITCH
4815 js2-TARGET
4816 js2-THROW
4817 js2-TRY
4818 js2-VAR
4819 js2-WHILE
4820 js2-WITH
4821 js2-WITHEXPR
4822 js2-YIELD))
4823 (aset tokens tt t))
4824 (if js2-instanceof-has-side-effects
4825 (aset tokens js2-INSTANCEOF t))
4826 tokens))
4827
4828 (defun js2-node-has-side-effects (node)
4829 "Return t if NODE has side effects."
4830 (when node ; makes it easier to handle malformed expressions
4831 (let ((tt (js2-node-type node)))
4832 (cond
4833 ;; This doubtless needs some work, since EXPR_VOID is used
4834 ;; in several ways in Rhino, and I may not have caught them all.
4835 ;; I'll wait for people to notice incorrect warnings.
4836 ((and (= tt js2-EXPR_VOID)
4837 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4838 (let ((expr (js2-expr-stmt-node-expr node)))
4839 (or (js2-node-has-side-effects expr)
4840 (when (js2-string-node-p expr)
4841 (string= "use strict" (js2-string-node-value expr))))))
4842 ((= tt js2-COMMA)
4843 (js2-node-has-side-effects (js2-infix-node-right node)))
4844 ((or (= tt js2-AND)
4845 (= tt js2-OR))
4846 (or (js2-node-has-side-effects (js2-infix-node-right node))
4847 (js2-node-has-side-effects (js2-infix-node-left node))))
4848 ((= tt js2-HOOK)
4849 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4850 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4851 ((js2-paren-node-p node)
4852 (js2-node-has-side-effects (js2-paren-node-expr node)))
4853 ((= tt js2-ERROR) ; avoid cascaded error messages
4854 nil)
4855 (t
4856 (aref js2-side-effecting-tokens tt))))))
4857
4858 (defun js2-member-expr-leftmost-name (node)
4859 "For an expr such as foo.bar.baz, return leftmost node foo.
4860 NODE is any `js2-node' object. If it represents a member expression,
4861 which is any sequence of property gets, element-gets, function calls,
4862 or xml descendants/filter operators, then we look at the lexically
4863 leftmost (first) node in the chain. If it is a name-node we return it.
4864 Note that NODE can be a raw name-node and it will be returned as well.
4865 If NODE is not a name-node or member expression, or if it is a member
4866 expression whose leftmost target is not a name node, returns nil."
4867 (let ((continue t)
4868 result)
4869 (while (and continue (not result))
4870 (cond
4871 ((js2-name-node-p node)
4872 (setq result node))
4873 ((js2-prop-get-node-p node)
4874 (setq node (js2-prop-get-node-left node)))
4875 ;; TODO: handle call-nodes, xml-nodes, others?
4876 (t
4877 (setq continue nil))))
4878 result))
4879
4880 (defconst js2-stmt-node-types
4881 (list js2-BLOCK
4882 js2-BREAK
4883 js2-CONTINUE
4884 js2-DEFAULT ; e4x "default xml namespace" statement
4885 js2-DO
4886 js2-EXPR_RESULT
4887 js2-EXPR_VOID
4888 js2-FOR
4889 js2-IF
4890 js2-RETURN
4891 js2-SWITCH
4892 js2-THROW
4893 js2-TRY
4894 js2-WHILE
4895 js2-WITH)
4896 "Node types that only appear in statement contexts.
4897 The list does not include nodes that always appear as the child
4898 of another specific statement type, such as switch-cases,
4899 catch and finally blocks, and else-clauses. The list also excludes
4900 nodes like yield, let and var, which may appear in either expression
4901 or statement context, and in the latter context always have a
4902 `js2-expr-stmt-node' parent. Finally, the list does not include
4903 functions or scripts, which are treated separately from statements
4904 by the JavaScript parser and runtime.")
4905
4906 (defun js2-stmt-node-p (node)
4907 "Heuristic for figuring out if NODE is a statement.
4908 Some node types can appear in either an expression context or a
4909 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4910 For these node types in a statement context, the parent will be a
4911 `js2-expr-stmt-node'.
4912 Functions aren't included in the check."
4913 (memq (js2-node-type node) js2-stmt-node-types))
4914
4915 (defsubst js2-mode-find-first-stmt (node)
4916 "Search upward starting from NODE looking for a statement.
4917 For purposes of this function, a `js2-function-node' counts."
4918 (while (not (or (js2-stmt-node-p node)
4919 (js2-function-node-p node)))
4920 (setq node (js2-node-parent node)))
4921 node)
4922
4923 (defun js2-node-parent-stmt (node)
4924 "Return the node's first ancestor that is a statement.
4925 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4926 appearing in a statement context will have a parent that is a
4927 `js2-expr-stmt-node' that will be returned by this function."
4928 (let ((parent (js2-node-parent node)))
4929 (if (or (null parent)
4930 (js2-stmt-node-p parent)
4931 (and (js2-function-node-p parent)
4932 (not (eq (js2-function-node-form parent)
4933 'FUNCTION_EXPRESSION))))
4934 parent
4935 (js2-node-parent-stmt parent))))
4936
4937 ;; In the Mozilla Rhino sources, Roshan James writes:
4938 ;; Does consistent-return analysis on the function body when strict mode is
4939 ;; enabled.
4940 ;;
4941 ;; function (x) { return (x+1) }
4942 ;;
4943 ;; is ok, but
4944 ;;
4945 ;; function (x) { if (x < 0) return (x+1); }
4946 ;;
4947 ;; is not because the function can potentially return a value when the
4948 ;; condition is satisfied and if not, the function does not explicitly
4949 ;; return a value.
4950 ;;
4951 ;; This extends to checking mismatches such as "return" and "return <value>"
4952 ;; used in the same function. Warnings are not emitted if inconsistent
4953 ;; returns exist in code that can be statically shown to be unreachable.
4954 ;; Ex.
4955 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4956 ;;
4957 ;; emits no warning. However if the loop had a break statement, then a
4958 ;; warning would be emitted.
4959 ;;
4960 ;; The consistency analysis looks at control structures such as loops, ifs,
4961 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4962 ;; warns the user about an inconsistent set of termination possibilities.
4963 ;;
4964 ;; These flags enumerate the possible ways a statement/function can
4965 ;; terminate. These flags are used by endCheck() and by the Parser to
4966 ;; detect inconsistent return usage.
4967 ;;
4968 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4969 ;; able to execute (example: throw, continue)
4970 ;;
4971 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4972 ;; next one. Statement such as return dont. A compound statement may have
4973 ;; some branch that drops off control to the next statement.
4974 ;;
4975 ;; END_RETURNS indicates that the statement can return with no value.
4976 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4977 ;;
4978 ;; A compound statement such as
4979 ;; if (condition) {
4980 ;; return value;
4981 ;; }
4982 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4983
4984 (defconst js2-END_UNREACHED 0)
4985 (defconst js2-END_DROPS_OFF 1)
4986 (defconst js2-END_RETURNS 2)
4987 (defconst js2-END_RETURNS_VALUE 4)
4988 (defconst js2-END_YIELDS 8)
4989
4990 (defun js2-has-consistent-return-usage (node)
4991 "Check that every return usage in a function body is consistent.
4992 Returns t if the function satisfies strict mode requirement."
4993 (let ((n (js2-end-check node)))
4994 ;; either it doesn't return a value in any branch...
4995 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4996 ;; or it returns a value (or is unreached) at every branch
4997 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4998 js2-END_RETURNS
4999 js2-END_YIELDS)))))
5000
5001 (defun js2-end-check-if (node)
5002 "Returns in the then and else blocks must be consistent with each other.
5003 If there is no else block, then the return statement can fall through.
5004 Returns logical OR of END_* flags"
5005 (let ((th (js2-if-node-then-part node))
5006 (el (js2-if-node-else-part node)))
5007 (if (null th)
5008 js2-END_UNREACHED
5009 (logior (js2-end-check th) (if el
5010 (js2-end-check el)
5011 js2-END_DROPS_OFF)))))
5012
5013 (defun js2-end-check-switch (node)
5014 "Consistency of return statements is checked between the case statements.
5015 If there is no default, then the switch can fall through. If there is a
5016 default, we check to see if all code paths in the default return or if
5017 there is a code path that can fall through.
5018 Returns logical OR of END_* flags."
5019 (let ((rv js2-END_UNREACHED)
5020 default-case)
5021 ;; examine the cases
5022 (catch 'break
5023 (dolist (c (js2-switch-node-cases node))
5024 (if (js2-case-node-expr c)
5025 (js2-set-flag rv (js2-end-check-block c))
5026 (setq default-case c)
5027 (throw 'break nil))))
5028 ;; we don't care how the cases drop into each other
5029 (js2-clear-flag rv js2-END_DROPS_OFF)
5030 ;; examine the default
5031 (js2-set-flag rv (if default-case
5032 (js2-end-check default-case)
5033 js2-END_DROPS_OFF))
5034 rv))
5035
5036 (defun js2-end-check-try (node)
5037 "If the block has a finally, return consistency is checked in the
5038 finally block. If all code paths in the finally return, then the
5039 returns in the try-catch blocks don't matter. If there is a code path
5040 that does not return or if there is no finally block, the returns
5041 of the try and catch blocks are checked for mismatch.
5042 Returns logical OR of END_* flags."
5043 (let ((finally (js2-try-node-finally-block node))
5044 rv)
5045 ;; check the finally if it exists
5046 (setq rv (if finally
5047 (js2-end-check (js2-finally-node-body finally))
5048 js2-END_DROPS_OFF))
5049 ;; If the finally block always returns, then none of the returns
5050 ;; in the try or catch blocks matter.
5051 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5052 (js2-clear-flag rv js2-END_DROPS_OFF)
5053 ;; examine the try block
5054 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5055 ;; check each catch block
5056 (dolist (cb (js2-try-node-catch-clauses node))
5057 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5058 rv))
5059
5060 (defun js2-end-check-loop (node)
5061 "Return statement in the loop body must be consistent. The default
5062 assumption for any kind of a loop is that it will eventually terminate.
5063 The only exception is a loop with a constant true condition. Code that
5064 follows such a loop is examined only if one can statically determine
5065 that there is a break out of the loop.
5066
5067 for(... ; ... ; ...) {}
5068 for(... in ... ) {}
5069 while(...) { }
5070 do { } while(...)
5071
5072 Returns logical OR of END_* flags."
5073 (let ((rv (js2-end-check (js2-loop-node-body node)))
5074 (condition (cond
5075 ((js2-while-node-p node)
5076 (js2-while-node-condition node))
5077 ((js2-do-node-p node)
5078 (js2-do-node-condition node))
5079 ((js2-for-node-p node)
5080 (js2-for-node-condition node)))))
5081
5082 ;; check to see if the loop condition is always true
5083 (if (and condition
5084 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5085 (js2-clear-flag rv js2-END_DROPS_OFF))
5086
5087 ;; look for effect of breaks
5088 (js2-set-flag rv (js2-node-get-prop node
5089 'CONTROL_BLOCK_PROP
5090 js2-END_UNREACHED))
5091 rv))
5092
5093 (defun js2-end-check-block (node)
5094 "A general block of code is examined statement by statement.
5095 If any statement (even a compound one) returns in all branches, then
5096 subsequent statements are not examined.
5097 Returns logical OR of END_* flags."
5098 (let* ((rv js2-END_DROPS_OFF)
5099 (kids (js2-block-node-kids node))
5100 (n (car kids)))
5101 ;; Check each statment. If the statement can continue onto the next
5102 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5103 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5104 (js2-clear-flag rv js2-END_DROPS_OFF)
5105 (js2-set-flag rv (js2-end-check n))
5106 (setq kids (cdr kids)
5107 n (car kids)))
5108 rv))
5109
5110 (defun js2-end-check-label (node)
5111 "A labeled statement implies that there may be a break to the label.
5112 The function processes the labeled statement and then checks the
5113 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5114 particular label.
5115 Returns logical OR of END_* flags."
5116 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5117 (logior rv (js2-node-get-prop node
5118 'CONTROL_BLOCK_PROP
5119 js2-END_UNREACHED))))
5120
5121 (defun js2-end-check-break (node)
5122 "When a break is encountered annotate the statement being broken
5123 out of by setting its CONTROL_BLOCK_PROP property.
5124 Returns logical OR of END_* flags."
5125 (and (js2-break-node-target node)
5126 (js2-node-set-prop (js2-break-node-target node)
5127 'CONTROL_BLOCK_PROP
5128 js2-END_DROPS_OFF))
5129 js2-END_UNREACHED)
5130
5131 (defun js2-end-check (node)
5132 "Examine the body of a function, doing a basic reachability analysis.
5133 Returns a combination of flags END_* flags that indicate
5134 how the function execution can terminate. These constitute only the
5135 pessimistic set of termination conditions. It is possible that at
5136 runtime certain code paths will never be actually taken. Hence this
5137 analysis will flag errors in cases where there may not be errors.
5138 Returns logical OR of END_* flags"
5139 (let (kid)
5140 (cond
5141 ((js2-break-node-p node)
5142 (js2-end-check-break node))
5143 ((js2-expr-stmt-node-p node)
5144 (if (setq kid (js2-expr-stmt-node-expr node))
5145 (js2-end-check kid)
5146 js2-END_DROPS_OFF))
5147 ((or (js2-continue-node-p node)
5148 (js2-throw-node-p node))
5149 js2-END_UNREACHED)
5150 ((js2-return-node-p node)
5151 (if (setq kid (js2-return-node-retval node))
5152 js2-END_RETURNS_VALUE
5153 js2-END_RETURNS))
5154 ((js2-loop-node-p node)
5155 (js2-end-check-loop node))
5156 ((js2-switch-node-p node)
5157 (js2-end-check-switch node))
5158 ((js2-labeled-stmt-node-p node)
5159 (js2-end-check-label node))
5160 ((js2-if-node-p node)
5161 (js2-end-check-if node))
5162 ((js2-try-node-p node)
5163 (js2-end-check-try node))
5164 ((js2-block-node-p node)
5165 (if (null (js2-block-node-kids node))
5166 js2-END_DROPS_OFF
5167 (js2-end-check-block node)))
5168 ((js2-yield-node-p node)
5169 js2-END_YIELDS)
5170 (t
5171 js2-END_DROPS_OFF))))
5172
5173 (defun js2-always-defined-boolean-p (node)
5174 "Check if NODE always evaluates to true or false in boolean context.
5175 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5176 nor always false."
5177 (let ((tt (js2-node-type node))
5178 num)
5179 (cond
5180 ((or (= tt js2-FALSE) (= tt js2-NULL))
5181 'ALWAYS_FALSE)
5182 ((= tt js2-TRUE)
5183 'ALWAYS_TRUE)
5184 ((= tt js2-NUMBER)
5185 (setq num (js2-number-node-num-value node))
5186 (if (and (not (eq num 0.0e+NaN))
5187 (not (zerop num)))
5188 'ALWAYS_TRUE
5189 'ALWAYS_FALSE))
5190 (t
5191 nil))))
5192
5193 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5194 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5195
5196 (defvar js2-tokens nil
5197 "List of all defined token names.") ; initialized in `js2-token-names'
5198
5199 (defconst js2-token-names
5200 (let* ((names (make-vector js2-num-tokens -1))
5201 (case-fold-search nil) ; only match js2-UPPER_CASE
5202 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5203 (loop for sym in syms
5204 for i from 0
5205 do
5206 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5207 (not (boundp sym)))
5208 (aset names (symbol-value sym) ; code, e.g. 152
5209 (downcase
5210 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5211 (push sym js2-tokens)))
5212 names)
5213 "Vector mapping int values to token string names, sans `js2-' prefix.")
5214
5215 (defun js2-token-name (tok)
5216 "Return a string name for TOK, a token symbol or code.
5217 Signals an error if it's not a recognized token."
5218 (let ((code tok))
5219 (if (symbolp tok)
5220 (setq code (symbol-value tok)))
5221 (if (eq code -1)
5222 "ERROR"
5223 (if (and (numberp code)
5224 (not (minusp code))
5225 (< code js2-num-tokens))
5226 (aref js2-token-names code)
5227 (error "Invalid token: %s" code)))))
5228
5229 (defsubst js2-token-sym (tok)
5230 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5231 (intern (js2-token-name tok)))
5232
5233 (defconst js2-token-codes
5234 (let ((table (make-hash-table :test 'eq :size 256)))
5235 (loop for name across js2-token-names
5236 for sym = (intern (concat "js2-" (upcase name)))
5237 do
5238 (puthash sym (symbol-value sym) table))
5239 ;; clean up a few that are "wrong" in Rhino's token codes
5240 (puthash 'js2-DELETE js2-DELPROP table)
5241 table)
5242 "Hashtable mapping token symbols to their bytecodes.")
5243
5244 (defsubst js2-token-code (sym)
5245 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5246 (or (gethash sym js2-token-codes)
5247 (error "Invalid token symbol: %s " sym))) ; signal code bug
5248
5249 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5250 (setq js2-token-end js2-ts-cursor)
5251 (js2-report-error msg nil
5252 (or beg js2-token-beg)
5253 (or len (- js2-token-end js2-token-beg)))
5254 (unless no-throw
5255 (throw 'return js2-ERROR)))
5256
5257 (defsubst js2-get-string-from-buffer ()
5258 "Reverse the char accumulator and return it as a string."
5259 (setq js2-token-end js2-ts-cursor)
5260 (if js2-ts-string-buffer
5261 (apply #'string (nreverse js2-ts-string-buffer))
5262 ""))
5263
5264 ;; TODO: could potentially avoid a lot of consing by allocating a
5265 ;; char buffer the way Rhino does.
5266 (defsubst js2-add-to-string (c)
5267 (push c js2-ts-string-buffer))
5268
5269 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5270 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5271 ;; any other character: when it's not part of the current token, we
5272 ;; unget it, allowing it to be read again by the following call.
5273 (defsubst js2-unget-char ()
5274 (decf js2-ts-cursor))
5275
5276 ;; Rhino distinguishes \r and \n line endings. We don't need to
5277 ;; because we only scan from Emacs buffers, which always use \n.
5278 (defsubst js2-get-char ()
5279 "Read and return the next character from the input buffer.
5280 Increments `js2-ts-lineno' if the return value is a newline char.
5281 Updates `js2-ts-cursor' to the point after the returned char.
5282 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5283 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5284 (let (c)
5285 ;; check for end of buffer
5286 (if (>= js2-ts-cursor (point-max))
5287 (setq js2-ts-hit-eof t
5288 js2-ts-cursor (1+ js2-ts-cursor)
5289 c js2-EOF_CHAR) ; return value
5290 ;; otherwise read next char
5291 (setq c (char-before (incf js2-ts-cursor)))
5292 ;; if we read a newline, update counters
5293 (if (= c ?\n)
5294 (setq js2-ts-line-start js2-ts-cursor
5295 js2-ts-lineno (1+ js2-ts-lineno)))
5296 ;; TODO: skip over format characters
5297 c)))
5298
5299 (defsubst js2-read-unicode-escape ()
5300 "Read a \\uNNNN sequence from the input.
5301 Assumes the ?\ and ?u have already been read.
5302 Returns the unicode character, or nil if it wasn't a valid character.
5303 Doesn't change the values of any scanner variables."
5304 ;; I really wish I knew a better way to do this, but I can't
5305 ;; find the Emacs function that takes a 16-bit int and converts
5306 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5307 ;; Have to first check that it's 4 hex characters or it may stop
5308 ;; the read early.
5309 (ignore-errors
5310 (let ((s (buffer-substring-no-properties js2-ts-cursor
5311 (+ 4 js2-ts-cursor))))
5312 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5313 (read (concat "?\\u" s))))))
5314
5315 (defsubst js2-match-char (test)
5316 "Consume and return next character if it matches TEST, a character.
5317 Returns nil and consumes nothing if TEST is not the next character."
5318 (let ((c (js2-get-char)))
5319 (if (eq c test)
5320 t
5321 (js2-unget-char)
5322 nil)))
5323
5324 (defsubst js2-peek-char ()
5325 (prog1
5326 (js2-get-char)
5327 (js2-unget-char)))
5328
5329 (defsubst js2-java-identifier-start-p (c)
5330 (or
5331 (memq c '(?$ ?_))
5332 (js2-char-uppercase-p c)
5333 (js2-char-lowercase-p c)))
5334
5335 (defsubst js2-java-identifier-part-p (c)
5336 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5337 ;; TODO: make me Unicode-friendly. See comments above.
5338 (or
5339 (memq c '(?$ ?_))
5340 (js2-char-uppercase-p c)
5341 (js2-char-lowercase-p c)
5342 (and (>= c ?0) (<= c ?9))))
5343
5344 (defsubst js2-alpha-p (c)
5345 (cond ((and (<= ?A c) (<= c ?Z)) t)
5346 ((and (<= ?a c) (<= c ?z)) t)
5347 (t nil)))
5348
5349 (defsubst js2-digit-p (c)
5350 (and (<= ?0 c) (<= c ?9)))
5351
5352 (defsubst js2-js-space-p (c)
5353 (if (<= c 127)
5354 (memq c '(#x20 #x9 #xB #xC #xD))
5355 (or
5356 (eq c #xA0)
5357 ;; TODO: change this nil to check for Unicode space character
5358 nil)))
5359
5360 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5361
5362 (defsubst js2-skip-line ()
5363 "Skip to end of line"
5364 (let (c)
5365 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5366 (js2-unget-char)
5367 (setq js2-token-end js2-ts-cursor)))
5368
5369 (defun js2-init-scanner (&optional buf line)
5370 "Create token stream for BUF starting on LINE.
5371 BUF defaults to current-buffer and line defaults to 1.
5372
5373 A buffer can only have one scanner active at a time, which yields
5374 dramatically simpler code than using a defstruct. If you need to
5375 have simultaneous scanners in a buffer, copy the regions to scan
5376 into temp buffers."
5377 (save-excursion
5378 (when buf
5379 (set-buffer buf))
5380 (setq js2-ts-dirty-line nil
5381 js2-ts-regexp-flags nil
5382 js2-ts-string ""
5383 js2-ts-number nil
5384 js2-ts-hit-eof nil
5385 js2-ts-line-start 0
5386 js2-ts-lineno (or line 1)
5387 js2-ts-line-end-char -1
5388 js2-ts-cursor (point-min)
5389 js2-ts-is-xml-attribute nil
5390 js2-ts-xml-is-tag-content nil
5391 js2-ts-xml-open-tags-count 0
5392 js2-ts-string-buffer nil)))
5393
5394 ;; This function uses the cached op, string and number fields in
5395 ;; TokenStream; if getToken has been called since the passed token
5396 ;; was scanned, the op or string printed may be incorrect.
5397 (defun js2-token-to-string (token)
5398 ;; Not sure where this function is used in Rhino. Not tested.
5399 (if (not js2-debug-print-trees)
5400 ""
5401 (let ((name (js2-token-name token)))
5402 (cond
5403 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5404 (concat name " `" js2-ts-string "'"))
5405 ((eq token js2-NUMBER)
5406 (format "NUMBER %g" js2-ts-number))
5407 (t
5408 name)))))
5409
5410 (defconst js2-keywords
5411 '(break
5412 case catch const continue
5413 debugger default delete do
5414 else enum
5415 false finally for function
5416 if in instanceof import
5417 let
5418 new null
5419 return
5420 switch
5421 this throw true try typeof
5422 var void
5423 while with
5424 yield))
5425
5426 ;; Token names aren't exactly the same as the keywords, unfortunately.
5427 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5428 (defconst js2-kwd-tokens
5429 (let ((table (make-vector js2-num-tokens nil))
5430 (tokens
5431 (list js2-BREAK
5432 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5433 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5434 js2-ELSE
5435 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5436 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5437 js2-LET
5438 js2-NEW js2-NULL
5439 js2-RETURN
5440 js2-SWITCH
5441 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5442 js2-VAR
5443 js2-WHILE js2-WITH
5444 js2-YIELD)))
5445 (dolist (i tokens)
5446 (aset table i 'font-lock-keyword-face))
5447 (aset table js2-STRING 'font-lock-string-face)
5448 (aset table js2-REGEXP 'font-lock-string-face)
5449 (aset table js2-COMMENT 'font-lock-comment-face)
5450 (aset table js2-THIS 'font-lock-builtin-face)
5451 (aset table js2-VOID 'font-lock-constant-face)
5452 (aset table js2-NULL 'font-lock-constant-face)
5453 (aset table js2-TRUE 'font-lock-constant-face)
5454 (aset table js2-FALSE 'font-lock-constant-face)
5455 table)
5456 "Vector whose values are non-nil for tokens that are keywords.
5457 The values are default faces to use for highlighting the keywords.")
5458
5459 (defconst js2-reserved-words
5460 '(abstract
5461 boolean byte
5462 char class
5463 double
5464 enum export extends
5465 final float
5466 goto
5467 implements import int interface
5468 long
5469 native
5470 package private protected public
5471 short static super synchronized
5472 throws transient
5473 volatile))
5474
5475 (defconst js2-keyword-names
5476 (let ((table (make-hash-table :test 'equal)))
5477 (loop for k in js2-keywords
5478 do (puthash
5479 (symbol-name k) ; instanceof
5480 (intern (concat "js2-"
5481 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5482 table))
5483 table)
5484 "JavaScript keywords by name, mapped to their symbols.")
5485
5486 (defconst js2-reserved-word-names
5487 (let ((table (make-hash-table :test 'equal)))
5488 (loop for k in js2-reserved-words
5489 do
5490 (puthash (symbol-name k) 'js2-RESERVED table))
5491 table)
5492 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5493
5494 (defsubst js2-collect-string (buf)
5495 "Convert BUF, a list of chars, to a string.
5496 Reverses BUF before converting."
5497 (cond
5498 ((stringp buf)
5499 buf)
5500 ((null buf) ; for emacs21 compat
5501 "")
5502 (t
5503 (if buf
5504 (apply #'string (nreverse buf))
5505 ""))))
5506
5507 (defun js2-string-to-keyword (s)
5508 "Return token for S, a string, if S is a keyword or reserved word.
5509 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5510 (or (gethash s js2-keyword-names)
5511 (gethash s js2-reserved-word-names)))
5512
5513 (defsubst js2-ts-set-char-token-bounds ()
5514 "Used when next token is one character."
5515 (setq js2-token-beg (1- js2-ts-cursor)
5516 js2-token-end js2-ts-cursor))
5517
5518 (defsubst js2-ts-return (token)
5519 "Return an N-character TOKEN from `js2-get-token'.
5520 Updates `js2-token-end' accordingly."
5521 (setq js2-token-end js2-ts-cursor)
5522 (throw 'return token))
5523
5524 (defsubst js2-x-digit-to-int (c accumulator)
5525 "Build up a hex number.
5526 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5527 corresponding number. Otherwise return -1."
5528 (catch 'return
5529 (catch 'check
5530 ;; Use 0..9 < A..Z < a..z
5531 (cond
5532 ((<= c ?9)
5533 (decf c ?0)
5534 (if (<= 0 c)
5535 (throw 'check nil)))
5536 ((<= c ?F)
5537 (when (<= ?A c)
5538 (decf c (- ?A 10))
5539 (throw 'check nil)))
5540 ((<= c ?f)
5541 (when (<= ?a c)
5542 (decf c (- ?a 10))
5543 (throw 'check nil))))
5544 (throw 'return -1))
5545 (logior c (lsh accumulator 4))))
5546
5547 (defun js2-get-token ()
5548 "Return next JavaScript token, an int such as js2-RETURN."
5549 (let (c
5550 c1
5551 identifier-start
5552 is-unicode-escape-start
5553 contains-escape
5554 escape-val
5555 escape-start
5556 str
5557 result
5558 base
5559 is-integer
5560 quote-char
5561 val
5562 look-for-slash
5563 continue)
5564 (catch 'return
5565 (while t
5566 ;; Eat whitespace, possibly sensitive to newlines.
5567 (setq continue t)
5568 (while continue
5569 (setq c (js2-get-char))
5570 (cond
5571 ((eq c js2-EOF_CHAR)
5572 (js2-ts-set-char-token-bounds)
5573 (throw 'return js2-EOF))
5574 ((eq c ?\n)
5575 (js2-ts-set-char-token-bounds)
5576 (setq js2-ts-dirty-line nil)
5577 (throw 'return js2-EOL))
5578 ((not (js2-js-space-p c))
5579 (if (/= c ?-) ; in case end of HTML comment
5580 (setq js2-ts-dirty-line t))
5581 (setq continue nil))))
5582 ;; Assume the token will be 1 char - fixed up below.
5583 (js2-ts-set-char-token-bounds)
5584 (when (eq c ?@)
5585 (throw 'return js2-XMLATTR))
5586 ;; identifier/keyword/instanceof?
5587 ;; watch out for starting with a <backslash>
5588 (cond
5589 ((eq c ?\\)
5590 (setq c (js2-get-char))
5591 (if (eq c ?u)
5592 (setq identifier-start t
5593 is-unicode-escape-start t
5594 js2-ts-string-buffer nil)
5595 (setq identifier-start nil)
5596 (js2-unget-char)
5597 (setq c ?\\)))
5598 (t
5599 (when (setq identifier-start (js2-java-identifier-start-p c))
5600 (setq js2-ts-string-buffer nil)
5601 (js2-add-to-string c))))
5602 (when identifier-start
5603 (setq contains-escape is-unicode-escape-start)
5604 (catch 'break
5605 (while t
5606 (if is-unicode-escape-start
5607 ;; strictly speaking we should probably push-back
5608 ;; all the bad characters if the <backslash>uXXXX
5609 ;; sequence is malformed. But since there isn't a
5610 ;; correct context(is there?) for a bad Unicode
5611 ;; escape sequence in an identifier, we can report
5612 ;; an error here.
5613 (progn
5614 (setq escape-val 0)
5615 (dotimes (i 4)
5616 (setq c (js2-get-char)
5617 escape-val (js2-x-digit-to-int c escape-val))
5618 ;; Next check takes care of c < 0 and bad escape
5619 (if (minusp escape-val)
5620 (throw 'break nil)))
5621 (if (minusp escape-val)
5622 (js2-report-scan-error "msg.invalid.escape" t))
5623 (js2-add-to-string escape-val)
5624 (setq is-unicode-escape-start nil))
5625 (setq c (js2-get-char))
5626 (cond
5627 ((eq c ?\\)
5628 (setq c (js2-get-char))
5629 (if (eq c ?u)
5630 (setq is-unicode-escape-start t
5631 contains-escape t)
5632 (js2-report-scan-error "msg.illegal.character" t)))
5633 (t
5634 (if (or (eq c js2-EOF_CHAR)
5635 (not (js2-java-identifier-part-p c)))
5636 (throw 'break nil))
5637 (js2-add-to-string c))))))
5638 (js2-unget-char)
5639 (setq str (js2-get-string-from-buffer))
5640 (unless contains-escape
5641 ;; OPT we shouldn't have to make a string (object!) to
5642 ;; check if it's a keyword.
5643 ;; Return the corresponding token if it's a keyword
5644 (when (setq result (js2-string-to-keyword str))
5645 (if (and (< js2-language-version 170)
5646 (memq result '(js2-LET js2-YIELD)))
5647 ;; LET and YIELD are tokens only in 1.7 and later
5648 (setq result 'js2-NAME))
5649 (if (not (eq result 'js2-RESERVED))
5650 (throw 'return (js2-token-code result)))
5651 (js2-report-warning "msg.reserved.keyword" str)))
5652 ;; If we want to intern these as Rhino does, just use (intern str)
5653 (setq js2-ts-string str)
5654 (throw 'return js2-NAME)) ; end identifier/kwd check
5655 ;; is it a number?
5656 (when (or (js2-digit-p c)
5657 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5658 (setq js2-ts-string-buffer nil
5659 base 10)
5660 (when (eq c ?0)
5661 (setq c (js2-get-char))
5662 (cond
5663 ((or (eq c ?x) (eq c ?X))
5664 (setq base 16)
5665 (setq c (js2-get-char)))
5666 ((js2-digit-p c)
5667 (setq base 8))
5668 (t
5669 (js2-add-to-string ?0))))
5670 (if (eq base 16)
5671 (while (<= 0 (js2-x-digit-to-int c 0))
5672 (js2-add-to-string c)
5673 (setq c (js2-get-char)))
5674 (while (and (<= ?0 c) (<= c ?9))
5675 ;; We permit 08 and 09 as decimal numbers, which
5676 ;; makes our behavior a superset of the ECMA
5677 ;; numeric grammar. We might not always be so
5678 ;; permissive, so we warn about it.
5679 (when (and (eq base 8) (>= c ?8))
5680 (js2-report-warning "msg.bad.octal.literal"
5681 (if (eq c ?8) "8" "9"))
5682 (setq base 10))
5683 (js2-add-to-string c)
5684 (setq c (js2-get-char))))
5685 (setq is-integer t)
5686 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5687 (setq is-integer nil)
5688 (when (eq c ?.)
5689 (loop do
5690 (js2-add-to-string c)
5691 (setq c (js2-get-char))
5692 while (js2-digit-p c)))
5693 (when (memq c '(?e ?E))
5694 (js2-add-to-string c)
5695 (setq c (js2-get-char))
5696 (when (memq c '(?+ ?-))
5697 (js2-add-to-string c)
5698 (setq c (js2-get-char)))
5699 (unless (js2-digit-p c)
5700 (js2-report-scan-error "msg.missing.exponent" t))
5701 (loop do
5702 (js2-add-to-string c)
5703 (setq c (js2-get-char))
5704 while (js2-digit-p c))))
5705 (js2-unget-char)
5706 (setq js2-ts-string (js2-get-string-from-buffer)
5707 js2-ts-number
5708 (if (and (eq base 10) (not is-integer))
5709 (string-to-number js2-ts-string)
5710 ;; TODO: call runtime number-parser. Some of it is in
5711 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5712 (string-to-number js2-ts-string)))
5713 (throw 'return js2-NUMBER))
5714 ;; is it a string?
5715 (when (memq c '(?\" ?\'))
5716 ;; We attempt to accumulate a string the fast way, by
5717 ;; building it directly out of the reader. But if there
5718 ;; are any escaped characters in the string, we revert to
5719 ;; building it out of a string buffer.
5720 (setq quote-char c
5721 js2-ts-string-buffer nil
5722 c (js2-get-char))
5723 (catch 'break
5724 (while (/= c quote-char)
5725 (catch 'continue
5726 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5727 (js2-unget-char)
5728 (setq js2-token-end js2-ts-cursor)
5729 (js2-report-error "msg.unterminated.string.lit")
5730 (throw 'return js2-STRING))
5731 (when (eq c ?\\)
5732 ;; We've hit an escaped character
5733 (setq c (js2-get-char))
5734 (case c
5735 (?b (setq c ?\b))
5736 (?f (setq c ?\f))
5737 (?n (setq c ?\n))
5738 (?r (setq c ?\r))
5739 (?t (setq c ?\t))
5740 (?v (setq c ?\v))
5741 (?u
5742 (setq c1 (js2-read-unicode-escape))
5743 (if js2-parse-ide-mode
5744 (if c1
5745 (progn
5746 ;; just copy the string in IDE-mode
5747 (js2-add-to-string ?\\)
5748 (js2-add-to-string ?u)
5749 (dotimes (i 3)
5750 (js2-add-to-string (js2-get-char)))
5751 (setq c (js2-get-char))) ; added at end of loop
5752 ;; flag it as an invalid escape
5753 (js2-report-warning "msg.invalid.escape"
5754 nil (- js2-ts-cursor 2) 6))
5755 ;; Get 4 hex digits; if the u escape is not
5756 ;; followed by 4 hex digits, use 'u' + the
5757 ;; literal character sequence that follows.
5758 (js2-add-to-string ?u)
5759 (setq escape-val 0)
5760 (dotimes (i 4)
5761 (setq c (js2-get-char)
5762 escape-val (js2-x-digit-to-int c escape-val))
5763 (if (minusp escape-val)
5764 (throw 'continue nil))
5765 (js2-add-to-string c))
5766 ;; prepare for replace of stored 'u' sequence by escape value
5767 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5768 c escape-val)))
5769 (?x
5770 ;; Get 2 hex digits, defaulting to 'x'+literal
5771 ;; sequence, as above.
5772 (setq c (js2-get-char)
5773 escape-val (js2-x-digit-to-int c 0))
5774 (if (minusp escape-val)
5775 (progn
5776 (js2-add-to-string ?x)
5777 (throw 'continue nil))
5778 (setq c1 c
5779 c (js2-get-char)
5780 escape-val (js2-x-digit-to-int c escape-val))
5781 (if (minusp escape-val)
5782 (progn
5783 (js2-add-to-string ?x)
5784 (js2-add-to-string c1)
5785 (throw 'continue nil))
5786 ;; got 2 hex digits
5787 (setq c escape-val))))
5788 (?\n
5789 ;; Remove line terminator after escape to follow
5790 ;; SpiderMonkey and C/C++
5791 (setq c (js2-get-char))
5792 (throw 'continue nil))
5793 (t
5794 (when (and (<= ?0 c) (< c ?8))
5795 (setq val (- c ?0)
5796 c (js2-get-char))
5797 (when (and (<= ?0 c) (< c ?8))
5798 (setq val (- (+ (* 8 val) c) ?0)
5799 c (js2-get-char))
5800 (when (and (<= ?0 c)
5801 (< c ?8)
5802 (< val #o37))
5803 ;; c is 3rd char of octal sequence only
5804 ;; if the resulting val <= 0377
5805 (setq val (- (+ (* 8 val) c) ?0)
5806 c (js2-get-char))))
5807 (js2-unget-char)
5808 (setq c val)))))
5809 (js2-add-to-string c)
5810 (setq c (js2-get-char)))))
5811 (setq js2-ts-string (js2-get-string-from-buffer))
5812 (throw 'return js2-STRING))
5813 (case c
5814 (?\;
5815 (throw 'return js2-SEMI))
5816 (?\[
5817 (throw 'return js2-LB))
5818 (?\]
5819 (throw 'return js2-RB))
5820 (?{
5821 (throw 'return js2-LC))
5822 (?}
5823 (throw 'return js2-RC))
5824 (?\(
5825 (throw 'return js2-LP))
5826 (?\)
5827 (throw 'return js2-RP))
5828 (?,
5829 (throw 'return js2-COMMA))
5830 (??
5831 (throw 'return js2-HOOK))
5832 (?:
5833 (if (js2-match-char ?:)
5834 (js2-ts-return js2-COLONCOLON)
5835 (throw 'return js2-COLON)))
5836 (?.
5837 (if (js2-match-char ?.)
5838 (if (js2-match-char ?.)
5839 (js2-ts-return js2-TRIPLEDOT)
5840 (js2-ts-return js2-DOTDOT))
5841 (if (js2-match-char ?\()
5842 (js2-ts-return js2-DOTQUERY)
5843 (throw 'return js2-DOT))))
5844 (?|
5845 (if (js2-match-char ?|)
5846 (throw 'return js2-OR)
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-ASSIGN_BITOR)
5849 (throw 'return js2-BITOR))))
5850 (?^
5851 (if (js2-match-char ?=)
5852 (js2-ts-return js2-ASSIGN_BITOR)
5853 (throw 'return js2-BITXOR)))
5854 (?&
5855 (if (js2-match-char ?&)
5856 (throw 'return js2-AND)
5857 (if (js2-match-char ?=)
5858 (js2-ts-return js2-ASSIGN_BITAND)
5859 (throw 'return js2-BITAND))))
5860 (?=
5861 (if (js2-match-char ?=)
5862 (if (js2-match-char ?=)
5863 (js2-ts-return js2-SHEQ)
5864 (throw 'return js2-EQ))
5865 (throw 'return js2-ASSIGN)))
5866 (?!
5867 (if (js2-match-char ?=)
5868 (if (js2-match-char ?=)
5869 (js2-ts-return js2-SHNE)
5870 (js2-ts-return js2-NE))
5871 (throw 'return js2-NOT)))
5872 (?<
5873 ;; NB:treat HTML begin-comment as comment-till-eol
5874 (when (js2-match-char ?!)
5875 (when (js2-match-char ?-)
5876 (when (js2-match-char ?-)
5877 (js2-skip-line)
5878 (setq js2-ts-comment-type 'html)
5879 (throw 'return js2-COMMENT)))
5880 (js2-unget-char))
5881 (if (js2-match-char ?<)
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-ASSIGN_LSH)
5884 (js2-ts-return js2-LSH))
5885 (if (js2-match-char ?=)
5886 (js2-ts-return js2-LE)
5887 (throw 'return js2-LT))))
5888 (?>
5889 (if (js2-match-char ?>)
5890 (if (js2-match-char ?>)
5891 (if (js2-match-char ?=)
5892 (js2-ts-return js2-ASSIGN_URSH)
5893 (js2-ts-return js2-URSH))
5894 (if (js2-match-char ?=)
5895 (js2-ts-return js2-ASSIGN_RSH)
5896 (js2-ts-return js2-RSH)))
5897 (if (js2-match-char ?=)
5898 (js2-ts-return js2-GE)
5899 (throw 'return js2-GT))))
5900 (?*
5901 (if (js2-match-char ?=)
5902 (js2-ts-return js2-ASSIGN_MUL)
5903 (throw 'return js2-MUL)))
5904 (?/
5905 ;; is it a // comment?
5906 (when (js2-match-char ?/)
5907 (setq js2-token-beg (- js2-ts-cursor 2))
5908 (js2-skip-line)
5909 (setq js2-ts-comment-type 'line)
5910 ;; include newline so highlighting goes to end of window
5911 (incf js2-token-end)
5912 (throw 'return js2-COMMENT))
5913 ;; is it a /* comment?
5914 (when (js2-match-char ?*)
5915 (setq look-for-slash nil
5916 js2-token-beg (- js2-ts-cursor 2)
5917 js2-ts-comment-type
5918 (if (js2-match-char ?*)
5919 (progn
5920 (setq look-for-slash t)
5921 'jsdoc)
5922 'block))
5923 (while t
5924 (setq c (js2-get-char))
5925 (cond
5926 ((eq c js2-EOF_CHAR)
5927 (setq js2-token-end (1- js2-ts-cursor))
5928 (js2-report-error "msg.unterminated.comment")
5929 (throw 'return js2-COMMENT))
5930 ((eq c ?*)
5931 (setq look-for-slash t))
5932 ((eq c ?/)
5933 (if look-for-slash
5934 (js2-ts-return js2-COMMENT)))
5935 (t
5936 (setq look-for-slash nil
5937 js2-token-end js2-ts-cursor)))))
5938 (if (js2-match-char ?=)
5939 (js2-ts-return js2-ASSIGN_DIV)
5940 (throw 'return js2-DIV)))
5941 (?#
5942 (when js2-skip-preprocessor-directives
5943 (js2-skip-line)
5944 (setq js2-ts-comment-type 'preprocessor
5945 js2-token-end js2-ts-cursor)
5946 (throw 'return js2-COMMENT))
5947 (throw 'return js2-ERROR))
5948 (?%
5949 (if (js2-match-char ?=)
5950 (js2-ts-return js2-ASSIGN_MOD)
5951 (throw 'return js2-MOD)))
5952 (?~
5953 (throw 'return js2-BITNOT))
5954 (?+
5955 (if (js2-match-char ?=)
5956 (js2-ts-return js2-ASSIGN_ADD)
5957 (if (js2-match-char ?+)
5958 (js2-ts-return js2-INC)
5959 (throw 'return js2-ADD))))
5960 (?-
5961 (cond
5962 ((js2-match-char ?=)
5963 (setq c js2-ASSIGN_SUB))
5964 ((js2-match-char ?-)
5965 (unless js2-ts-dirty-line
5966 ;; treat HTML end-comment after possible whitespace
5967 ;; after line start as comment-until-eol
5968 (when (js2-match-char ?>)
5969 (js2-skip-line)
5970 (setq js2-ts-comment-type 'html)
5971 (throw 'return js2-COMMENT)))
5972 (setq c js2-DEC))
5973 (t
5974 (setq c js2-SUB)))
5975 (setq js2-ts-dirty-line t)
5976 (js2-ts-return c))
5977 (otherwise
5978 (js2-report-scan-error "msg.illegal.character")))))))
5979
5980 (defun js2-read-regexp (start-token)
5981 "Called by parser when it gets / or /= in literal context."
5982 (let (c
5983 err
5984 in-class ; inside a '[' .. ']' character-class
5985 flags
5986 (continue t))
5987 (setq js2-token-beg js2-ts-cursor
5988 js2-ts-string-buffer nil
5989 js2-ts-regexp-flags nil)
5990 (if (eq start-token js2-ASSIGN_DIV)
5991 ;; mis-scanned /=
5992 (js2-add-to-string ?=)
5993 (if (not (eq start-token js2-DIV))
5994 (error "failed assertion")))
5995 (while (and (not err)
5996 (or (/= (setq c (js2-get-char)) ?/)
5997 in-class))
5998 (cond
5999 ((or (= c ?\n)
6000 (= c js2-EOF_CHAR))
6001 (setq js2-token-end (1- js2-ts-cursor)
6002 err t
6003 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6004 (js2-report-error "msg.unterminated.re.lit"))
6005 (t (cond
6006 ((= c ?\\)
6007 (js2-add-to-string c)
6008 (setq c (js2-get-char)))
6009 ((= c ?\[)
6010 (setq in-class t))
6011 ((= c ?\])
6012 (setq in-class nil)))
6013 (js2-add-to-string c))))
6014 (unless err
6015 (while continue
6016 (cond
6017 ((js2-match-char ?g)
6018 (push ?g flags))
6019 ((js2-match-char ?i)
6020 (push ?i flags))
6021 ((js2-match-char ?m)
6022 (push ?m flags))
6023 (t
6024 (setq continue nil))))
6025 (if (js2-alpha-p (js2-peek-char))
6026 (js2-report-scan-error "msg.invalid.re.flag" t
6027 js2-ts-cursor 1))
6028 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6029 js2-ts-regexp-flags (js2-collect-string flags)
6030 js2-token-end js2-ts-cursor)
6031 ;; tell `parse-partial-sexp' to ignore this range of chars
6032 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6033
6034 (defun js2-get-first-xml-token ()
6035 (setq js2-ts-xml-open-tags-count 0
6036 js2-ts-is-xml-attribute nil
6037 js2-ts-xml-is-tag-content nil)
6038 (js2-unget-char)
6039 (js2-get-next-xml-token))
6040
6041 (defsubst js2-xml-discard-string ()
6042 "Throw away the string in progress and flag an XML parse error."
6043 (setq js2-ts-string-buffer nil
6044 js2-ts-string nil)
6045 (js2-report-scan-error "msg.XML.bad.form" t))
6046
6047 (defun js2-get-next-xml-token ()
6048 (setq js2-ts-string-buffer nil ; for recording the XML
6049 js2-token-beg js2-ts-cursor)
6050 (let (c result)
6051 (setq result
6052 (catch 'return
6053 (while t
6054 (setq c (js2-get-char))
6055 (cond
6056 ((= c js2-EOF_CHAR)
6057 (throw 'return js2-ERROR))
6058 (js2-ts-xml-is-tag-content
6059 (case c
6060 (?>
6061 (js2-add-to-string c)
6062 (setq js2-ts-xml-is-tag-content nil
6063 js2-ts-is-xml-attribute nil))
6064 (?/
6065 (js2-add-to-string c)
6066 (when (eq ?> (js2-peek-char))
6067 (setq c (js2-get-char))
6068 (js2-add-to-string c)
6069 (setq js2-ts-xml-is-tag-content nil)
6070 (decf js2-ts-xml-open-tags-count)))
6071 (?{
6072 (js2-unget-char)
6073 (setq js2-ts-string (js2-get-string-from-buffer))
6074 (throw 'return js2-XML))
6075 ((?\' ?\")
6076 (js2-add-to-string c)
6077 (unless (js2-read-quoted-string c)
6078 (throw 'return js2-ERROR)))
6079 (?=
6080 (js2-add-to-string c)
6081 (setq js2-ts-is-xml-attribute t))
6082 ((? ?\t ?\r ?\n)
6083 (js2-add-to-string c))
6084 (t
6085 (js2-add-to-string c)
6086 (setq js2-ts-is-xml-attribute nil)))
6087 (when (and (not js2-ts-xml-is-tag-content)
6088 (zerop js2-ts-xml-open-tags-count))
6089 (setq js2-ts-string (js2-get-string-from-buffer))
6090 (throw 'return js2-XMLEND)))
6091 (t
6092 ;; else not tag content
6093 (case c
6094 (?<
6095 (js2-add-to-string c)
6096 (setq c (js2-peek-char))
6097 (case c
6098 (?!
6099 (setq c (js2-get-char)) ;; skip !
6100 (js2-add-to-string c)
6101 (setq c (js2-peek-char))
6102 (case c
6103 (?-
6104 (setq c (js2-get-char)) ;; skip -
6105 (js2-add-to-string c)
6106 (if (eq c ?-)
6107 (progn
6108 (js2-add-to-string c)
6109 (unless (js2-read-xml-comment)
6110 (throw 'return js2-ERROR)))
6111 (js2-xml-discard-string)
6112 (throw 'return js2-ERROR)))
6113 (?\[
6114 (setq c (js2-get-char)) ;; skip [
6115 (js2-add-to-string c)
6116 (if (and (= (js2-get-char) ?C)
6117 (= (js2-get-char) ?D)
6118 (= (js2-get-char) ?A)
6119 (= (js2-get-char) ?T)
6120 (= (js2-get-char) ?A)
6121 (= (js2-get-char) ?\[))
6122 (progn
6123 (js2-add-to-string ?C)
6124 (js2-add-to-string ?D)
6125 (js2-add-to-string ?A)
6126 (js2-add-to-string ?T)
6127 (js2-add-to-string ?A)
6128 (js2-add-to-string ?\[)
6129 (unless (js2-read-cdata)
6130 (throw 'return js2-ERROR)))
6131 (js2-xml-discard-string)
6132 (throw 'return js2-ERROR)))
6133 (t
6134 (unless (js2-read-entity)
6135 (throw 'return js2-ERROR))))
6136 ;; allow bare CDATA section
6137 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6138 (when (zerop js2-ts-xml-open-tags-count)
6139 (throw 'return js2-XMLEND)))
6140 (??
6141 (setq c (js2-get-char)) ;; skip ?
6142 (js2-add-to-string c)
6143 (unless (js2-read-PI)
6144 (throw 'return js2-ERROR)))
6145 (?/
6146 ;; end tag
6147 (setq c (js2-get-char)) ;; skip /
6148 (js2-add-to-string c)
6149 (when (zerop js2-ts-xml-open-tags-count)
6150 (js2-xml-discard-string)
6151 (throw 'return js2-ERROR))
6152 (setq js2-ts-xml-is-tag-content t)
6153 (decf js2-ts-xml-open-tags-count))
6154 (t
6155 ;; start tag
6156 (setq js2-ts-xml-is-tag-content t)
6157 (incf js2-ts-xml-open-tags-count))))
6158 (?{
6159 (js2-unget-char)
6160 (setq js2-ts-string (js2-get-string-from-buffer))
6161 (throw 'return js2-XML))
6162 (t
6163 (js2-add-to-string c))))))))
6164 (setq js2-token-end js2-ts-cursor)
6165 result))
6166
6167 (defun js2-read-quoted-string (quote)
6168 (let (c)
6169 (catch 'return
6170 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6171 (js2-add-to-string c)
6172 (if (eq c quote)
6173 (throw 'return t)))
6174 (js2-xml-discard-string) ;; throw away string in progress
6175 nil)))
6176
6177 (defun js2-read-xml-comment ()
6178 (let ((c (js2-get-char)))
6179 (catch 'return
6180 (while (/= c js2-EOF_CHAR)
6181 (catch 'continue
6182 (js2-add-to-string c)
6183 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6184 (setq c (js2-get-char))
6185 (js2-add-to-string c)
6186 (if (eq (js2-peek-char) ?>)
6187 (progn
6188 (setq c (js2-get-char)) ;; skip >
6189 (js2-add-to-string c)
6190 (throw 'return t))
6191 (throw 'continue nil)))
6192 (setq c (js2-get-char))))
6193 (js2-xml-discard-string)
6194 nil)))
6195
6196 (defun js2-read-cdata ()
6197 (let ((c (js2-get-char)))
6198 (catch 'return
6199 (while (/= c js2-EOF_CHAR)
6200 (catch 'continue
6201 (js2-add-to-string c)
6202 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6203 (setq c (js2-get-char))
6204 (js2-add-to-string c)
6205 (if (eq (js2-peek-char) ?>)
6206 (progn
6207 (setq c (js2-get-char)) ;; Skip >
6208 (js2-add-to-string c)
6209 (throw 'return t))
6210 (throw 'continue nil)))
6211 (setq c (js2-get-char))))
6212 (js2-xml-discard-string)
6213 nil)))
6214
6215 (defun js2-read-entity ()
6216 (let ((decl-tags 1)
6217 c)
6218 (catch 'return
6219 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6220 (js2-add-to-string c)
6221 (case c
6222 (?<
6223 (incf decl-tags))
6224 (?>
6225 (decf decl-tags)
6226 (if (zerop decl-tags)
6227 (throw 'return t)))))
6228 (js2-xml-discard-string)
6229 nil)))
6230
6231 (defun js2-read-PI ()
6232 "Scan an XML processing instruction."
6233 (let (c)
6234 (catch 'return
6235 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6236 (js2-add-to-string c)
6237 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6238 (setq c (js2-get-char)) ;; Skip >
6239 (js2-add-to-string c)
6240 (throw 'return t)))
6241 (js2-xml-discard-string)
6242 nil)))
6243
6244 (defun js2-scanner-get-line ()
6245 "Return the text of the current scan line."
6246 (buffer-substring (point-at-bol) (point-at-eol)))
6247
6248 ;;; Highlighting
6249
6250 (defsubst js2-set-face (beg end face &optional record)
6251 "Fontify a region. If RECORD is non-nil, record for later."
6252 (when (plusp js2-highlight-level)
6253 (setq beg (min (point-max) beg)
6254 beg (max (point-min) beg)
6255 end (min (point-max) end)
6256 end (max (point-min) end))
6257 (if record
6258 (push (list beg end face) js2-mode-fontifications)
6259 (put-text-property beg end 'font-lock-face face))))
6260
6261 (defsubst js2-set-kid-face (pos kid len face)
6262 "Set-face on a child node.
6263 POS is absolute buffer position of parent.
6264 KID is the child node.
6265 LEN is the length to fontify.
6266 FACE is the face to fontify with."
6267 (js2-set-face (+ pos (js2-node-pos kid))
6268 (+ pos (js2-node-pos kid) (js2-node-len kid))
6269 face))
6270
6271 (defsubst js2-fontify-kwd (start length)
6272 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6273
6274 (defsubst js2-clear-face (beg end)
6275 (remove-text-properties beg end '(font-lock-face nil
6276 help-echo nil
6277 point-entered nil
6278 c-in-sws nil)))
6279
6280 (defconst js2-ecma-global-props
6281 (concat "^"
6282 (regexp-opt
6283 '("Infinity" "NaN" "undefined" "arguments") t)
6284 "$")
6285 "Value properties of the Ecma-262 Global Object.
6286 Shown at or above `js2-highlight-level' 2.")
6287
6288 ;; might want to add the name "arguments" to this list?
6289 (defconst js2-ecma-object-props
6290 (concat "^"
6291 (regexp-opt
6292 '("prototype" "__proto__" "__parent__") t)
6293 "$")
6294 "Value properties of the Ecma-262 Object constructor.
6295 Shown at or above `js2-highlight-level' 2.")
6296
6297 (defconst js2-ecma-global-funcs
6298 (concat
6299 "^"
6300 (regexp-opt
6301 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6302 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6303 "$")
6304 "Function properties of the Ecma-262 Global object.
6305 Shown at or above `js2-highlight-level' 2.")
6306
6307 (defconst js2-ecma-number-props
6308 (concat "^"
6309 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6310 "NEGATIVE_INFINITY"
6311 "POSITIVE_INFINITY") t)
6312 "$")
6313 "Properties of the Ecma-262 Number constructor.
6314 Shown at or above `js2-highlight-level' 2.")
6315
6316 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6317 "Properties of the Ecma-262 Date constructor.
6318 Shown at or above `js2-highlight-level' 2.")
6319
6320 (defconst js2-ecma-math-props
6321 (concat "^"
6322 (regexp-opt
6323 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6324 t)
6325 "$")
6326 "Properties of the Ecma-262 Math object.
6327 Shown at or above `js2-highlight-level' 2.")
6328
6329 (defconst js2-ecma-math-funcs
6330 (concat "^"
6331 (regexp-opt
6332 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6333 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6334 "$")
6335 "Function properties of the Ecma-262 Math object.
6336 Shown at or above `js2-highlight-level' 2.")
6337
6338 (defconst js2-ecma-function-props
6339 (concat
6340 "^"
6341 (regexp-opt
6342 '(;; properties of the Object prototype object
6343 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6344 "toLocaleString" "toString" "valueOf"
6345 ;; properties of the Function prototype object
6346 "apply" "call"
6347 ;; properties of the Array prototype object
6348 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6349 "splice" "unshift"
6350 ;; properties of the String prototype object
6351 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6352 "localeCompare" "match" "replace" "search" "split" "substring"
6353 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6354 "toUpperCase"
6355 ;; properties of the Number prototype object
6356 "toExponential" "toFixed" "toPrecision"
6357 ;; properties of the Date prototype object
6358 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6359 "getMinutes" "getMonth" "getSeconds" "getTime"
6360 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6361 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6362 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6363 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6364 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6365 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6366 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6367 "toTimeString" "toUTCString"
6368 ;; properties of the RegExp prototype object
6369 "exec" "test"
6370 ;; properties of the JSON prototype object
6371 "parse" "stringify"
6372 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6373 "toSource" "__defineGetter__" "__defineSetter__"
6374 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6375 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6376 t)
6377 "$")
6378 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6379 Shown at or above `js2-highlight-level' 3.")
6380
6381 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6382 (let ((target-name (and target
6383 (js2-name-node-p target)
6384 (js2-name-node-name target)))
6385 (prop-name (if prop (js2-name-node-name prop)))
6386 (level1 (>= js2-highlight-level 1))
6387 (level2 (>= js2-highlight-level 2))
6388 (level3 (>= js2-highlight-level 3))
6389 pos
6390 face)
6391 (when level2
6392 (if call-p
6393 (cond
6394 ((and target prop)
6395 (cond
6396 ((and level3 (string-match js2-ecma-function-props prop-name))
6397 (setq face 'font-lock-builtin-face))
6398 ((and target-name prop)
6399 (cond
6400 ((string= target-name "Date")
6401 (if (string-match js2-ecma-date-props prop-name)
6402 (setq face 'font-lock-builtin-face)))
6403 ((string= target-name "Math")
6404 (if (string-match js2-ecma-math-funcs prop-name)
6405 (setq face 'font-lock-builtin-face)))))))
6406 (prop
6407 (if (string-match js2-ecma-global-funcs prop-name)
6408 (setq face 'font-lock-builtin-face))))
6409 (cond
6410 ((and target prop)
6411 (cond
6412 ((string= target-name "Number")
6413 (if (string-match js2-ecma-number-props prop-name)
6414 (setq face 'font-lock-constant-face)))
6415 ((string= target-name "Math")
6416 (if (string-match js2-ecma-math-props prop-name)
6417 (setq face 'font-lock-constant-face)))))
6418 (prop
6419 (if (string-match js2-ecma-object-props prop-name)
6420 (setq face 'font-lock-constant-face)))))
6421 (when face
6422 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6423 (js2-node-pos prop))) ; relative
6424 (+ pos (js2-node-len prop))
6425 face 'record)))))
6426
6427 (defun js2-parse-highlight-member-expr-node (node)
6428 "Perform syntax highlighting of EcmaScript built-in properties.
6429 The variable `js2-highlight-level' governs this highighting."
6430 (let (face target prop name pos end parent call-p callee)
6431 (cond
6432 ;; case 1: simple name, e.g. foo
6433 ((js2-name-node-p node)
6434 (setq name (js2-name-node-name node))
6435 ;; possible for name to be nil in rare cases - saw it when
6436 ;; running js2-mode on an elisp buffer. Might as well try to
6437 ;; make it so js2-mode never barfs.
6438 (when name
6439 (setq face (if (string-match js2-ecma-global-props name)
6440 'font-lock-constant-face))
6441 (when face
6442 (setq pos (js2-node-pos node)
6443 end (+ pos (js2-node-len node)))
6444 (js2-set-face pos end face 'record))))
6445 ;; case 2: property access or function call
6446 ((or (js2-prop-get-node-p node)
6447 ;; highlight function call if expr is a prop-get node
6448 ;; or a plain name (i.e. unqualified function call)
6449 (and (setq call-p (js2-call-node-p node))
6450 (setq callee (js2-call-node-target node)) ; separate setq!
6451 (or (js2-prop-get-node-p callee)
6452 (js2-name-node-p callee))))
6453 (setq parent node
6454 node (if call-p callee node))
6455 (if (and call-p (js2-name-node-p callee))
6456 (setq prop callee)
6457 (setq target (js2-prop-get-node-left node)
6458 prop (js2-prop-get-node-right node)))
6459 (cond
6460 ((js2-name-node-p target)
6461 (if (js2-name-node-p prop)
6462 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6463 (js2-parse-highlight-prop-get parent target prop call-p)
6464 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6465 (js2-parse-highlight-prop-get parent target nil call-p)))
6466 ((js2-name-node-p prop)
6467 ;; case 2c: complex target, simple name, e.g. x[y].bar
6468 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6469
6470 (defun js2-parse-highlight-member-expr-fn-name (expr)
6471 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6472 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6473 We currently only handle the case where the last component is a prop-get
6474 of a simple name. Called before EXPR has a parent node."
6475 (let (pos
6476 (name (and (js2-prop-get-node-p expr)
6477 (js2-prop-get-node-right expr))))
6478 (when (js2-name-node-p name)
6479 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6480 (js2-node-pos name)))
6481 (+ pos (js2-node-len name))
6482 'font-lock-function-name-face
6483 'record))))
6484
6485 ;; source: http://jsdoc.sourceforge.net/
6486 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6487 ;; allows type specifications, and needs work before entering the wild.
6488
6489 (defconst js2-jsdoc-param-tag-regexp
6490 (concat "^\\s-*\\*+\\s-*\\(@"
6491 "\\(?:param\\|argument\\)"
6492 "\\)"
6493 "\\s-*\\({[^}]+}\\)?" ; optional type
6494 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6495 "\\>")
6496 "Matches jsdoc tags with optional type and optional param name.")
6497
6498 (defconst js2-jsdoc-typed-tag-regexp
6499 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6500 (regexp-opt
6501 '("enum"
6502 "extends"
6503 "field"
6504 "id"
6505 "implements"
6506 "lends"
6507 "mods"
6508 "requires"
6509 "return"
6510 "returns"
6511 "throw"
6512 "throws"))
6513 "\\)\\)\\s-*\\({[^}]+}\\)?")
6514 "Matches jsdoc tags with optional type.")
6515
6516 (defconst js2-jsdoc-arg-tag-regexp
6517 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6518 (regexp-opt
6519 '("alias"
6520 "augments"
6521 "borrows"
6522 "bug"
6523 "base"
6524 "config"
6525 "default"
6526 "define"
6527 "exception"
6528 "function"
6529 "member"
6530 "memberOf"
6531 "name"
6532 "namespace"
6533 "property"
6534 "since"
6535 "suppress"
6536 "this"
6537 "throws"
6538 "type"
6539 "version"))
6540 "\\)\\)\\s-+\\([^ \t]+\\)")
6541 "Matches jsdoc tags with a single argument.")
6542
6543 (defconst js2-jsdoc-empty-tag-regexp
6544 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6545 (regexp-opt
6546 '("addon"
6547 "author"
6548 "class"
6549 "const"
6550 "constant"
6551 "constructor"
6552 "constructs"
6553 "deprecated"
6554 "desc"
6555 "description"
6556 "event"
6557 "example"
6558 "exec"
6559 "export"
6560 "fileoverview"
6561 "final"
6562 "function"
6563 "hidden"
6564 "ignore"
6565 "implicitCast"
6566 "inheritDoc"
6567 "inner"
6568 "interface"
6569 "license"
6570 "noalias"
6571 "noshadow"
6572 "notypecheck"
6573 "override"
6574 "owner"
6575 "preserve"
6576 "preserveTry"
6577 "private"
6578 "protected"
6579 "public"
6580 "static"
6581 "supported"
6582 ))
6583 "\\)\\)\\s-*")
6584 "Matches empty jsdoc tags.")
6585
6586 (defconst js2-jsdoc-link-tag-regexp
6587 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6588 "Matches a jsdoc link or code tag.")
6589
6590 (defconst js2-jsdoc-see-tag-regexp
6591 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6592 "Matches a jsdoc @see tag.")
6593
6594 (defconst js2-jsdoc-html-tag-regexp
6595 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6596 "Matches a simple (no attributes) html start- or end-tag.")
6597
6598 (defsubst js2-jsdoc-highlight-helper ()
6599 (js2-set-face (match-beginning 1)
6600 (match-end 1)
6601 'js2-jsdoc-tag-face)
6602 (if (match-beginning 2)
6603 (if (save-excursion
6604 (goto-char (match-beginning 2))
6605 (= (char-after) ?{))
6606 (js2-set-face (1+ (match-beginning 2))
6607 (1- (match-end 2))
6608 'js2-jsdoc-type-face)
6609 (js2-set-face (match-beginning 2)
6610 (match-end 2)
6611 'js2-jsdoc-value-face)))
6612 (if (match-beginning 3)
6613 (js2-set-face (match-beginning 3)
6614 (match-end 3)
6615 'js2-jsdoc-value-face)))
6616
6617 (defun js2-highlight-jsdoc (ast)
6618 "Highlight doc comment tags."
6619 (let ((comments (js2-ast-root-comments ast))
6620 beg end)
6621 (save-excursion
6622 (dolist (node comments)
6623 (when (eq (js2-comment-node-format node) 'jsdoc)
6624 (setq beg (js2-node-abs-pos node)
6625 end (+ beg (js2-node-len node)))
6626 (save-restriction
6627 (narrow-to-region beg end)
6628 (dolist (re (list js2-jsdoc-param-tag-regexp
6629 js2-jsdoc-typed-tag-regexp
6630 js2-jsdoc-arg-tag-regexp
6631 js2-jsdoc-link-tag-regexp
6632 js2-jsdoc-see-tag-regexp
6633 js2-jsdoc-empty-tag-regexp))
6634 (goto-char beg)
6635 (while (re-search-forward re nil t)
6636 (js2-jsdoc-highlight-helper)))
6637 ;; simple highlighting for html tags
6638 (goto-char beg)
6639 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6640 (js2-set-face (match-beginning 1)
6641 (match-end 1)
6642 'js2-jsdoc-html-tag-delimiter-face)
6643 (js2-set-face (match-beginning 2)
6644 (match-end 2)
6645 'js2-jsdoc-html-tag-name-face)
6646 (js2-set-face (match-beginning 3)
6647 (match-end 3)
6648 'js2-jsdoc-html-tag-delimiter-face))))))))
6649
6650 (defun js2-highlight-assign-targets (node left right)
6651 "Highlight function properties and external variables."
6652 (let (leftpos end name)
6653 ;; highlight vars and props assigned function values
6654 (when (js2-function-node-p right)
6655 (cond
6656 ;; var foo = function() {...}
6657 ((js2-name-node-p left)
6658 (setq name left))
6659 ;; foo.bar.baz = function() {...}
6660 ((and (js2-prop-get-node-p left)
6661 (js2-name-node-p (js2-prop-get-node-right left)))
6662 (setq name (js2-prop-get-node-right left))))
6663 (when name
6664 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6665 (+ leftpos (js2-node-len name))
6666 'font-lock-function-name-face
6667 'record)))))
6668
6669 (defun js2-record-name-node (node)
6670 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6671 later. NODE must be a name node."
6672 (let (leftpos end)
6673 (push (list node js2-current-scope
6674 (setq leftpos (js2-node-abs-pos node))
6675 (setq end (+ leftpos (js2-node-len node))))
6676 js2-recorded-identifiers)))
6677
6678 (defun js2-highlight-undeclared-vars ()
6679 "After entire parse is finished, look for undeclared variable references.
6680 We have to wait until entire buffer is parsed, since JavaScript permits var
6681 decls to occur after they're used.
6682
6683 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6684 it is considered declared."
6685 (let (name)
6686 (dolist (entry js2-recorded-identifiers)
6687 (destructuring-bind (name-node scope pos end) entry
6688 (setq name (js2-name-node-name name-node))
6689 (unless (or (member name js2-global-externs)
6690 (member name js2-default-externs)
6691 (member name js2-additional-externs)
6692 (js2-get-defining-scope scope name))
6693 (js2-set-face pos end 'js2-external-variable-face 'record)
6694 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6695 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6696 (setq js2-recorded-identifiers nil)))
6697
6698 ;;; IMenu support
6699
6700 ;; We currently only support imenu, but eventually should support speedbar and
6701 ;; possibly other browsing mechanisms.
6702
6703 ;; The basic strategy is to identify function assignment targets of the form
6704 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6705 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6706 ;; for imenu after parsing is finished.
6707
6708 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6709 ;; JavaScript, and the general problem is undecidable. However, several forms
6710 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6711 ;; include:
6712
6713 ;; function foo() -- function declaration
6714 ;; foo = function() -- function expression assigned to variable
6715 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6716 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6717 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6718 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6719 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6720 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6721 ;; function foo() {function bar() {...}} -- nested function
6722 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6723
6724 ;; This list boils down to a few forms that can be combined recursively.
6725 ;; Top-level named function declarations include both the left-hand (name)
6726 ;; and the right-hand (function value) expressions needed to produce an imenu
6727 ;; entry. The other "right-hand" forms we need to look for are:
6728 ;; - functions declared as props/getters/setters in object literals
6729 ;; - nested named function declarations
6730 ;; The "left-hand" expressions that functions can be assigned to include:
6731 ;; - local/global variables
6732 ;; - nested property-get expressions like a.b.c.d
6733 ;; - element gets like foo[10] or foo['bar'] where the index
6734 ;; expression can be trivially converted to a property name. They
6735 ;; effectively then become property gets.
6736
6737 ;; All the different definition types are canonicalized into the form
6738 ;; foo.bar.baz = position-of-function-keyword
6739
6740 ;; We need to build a trie-like structure for imenu. As an example,
6741 ;; consider the following JavaScript code:
6742
6743 ;; a = function() {...} // function at position 5
6744 ;; b = function() {...} // function at position 25
6745 ;; foo = function() {...} // function at position 100
6746 ;; foo.bar = function() {...} // function at position 200
6747 ;; foo.bar.baz = function() {...} // function at position 300
6748 ;; foo.bar.zab = function() {...} // function at position 400
6749
6750 ;; During parsing we accumulate an entry for each definition in
6751 ;; the variable `js2-imenu-recorder', like so:
6752
6753 ;; '((fn a 5)
6754 ;; (fn b 25)
6755 ;; (fn foo 100)
6756 ;; (fn foo bar 200)
6757 ;; (fn foo bar baz 300)
6758 ;; (fn foo bar zab 400))
6759
6760 ;; Where 'fn' is the respective function node.
6761 ;; After parsing these entries are merged into this alist-trie:
6762
6763 ;; '((a . 1)
6764 ;; (b . 2)
6765 ;; (foo (<definition> . 3)
6766 ;; (bar (<definition> . 6)
6767 ;; (baz . 100)
6768 ;; (zab . 200))))
6769
6770 ;; Note the wacky need for a <definition> name. The token can be anything
6771 ;; that isn't a valid JavaScript identifier, because you might make foo
6772 ;; a function and then start setting properties on it that are also functions.
6773
6774 (defsubst js2-prop-node-name (node)
6775 "Return the name of a node that may be a property-get/property-name.
6776 If NODE is not a valid name-node, string-node or integral number-node,
6777 returns nil. Otherwise returns the string name/value of the node."
6778 (cond
6779 ((js2-name-node-p node)
6780 (js2-name-node-name node))
6781 ((js2-string-node-p node)
6782 (js2-string-node-value node))
6783 ((and (js2-number-node-p node)
6784 (string-match "^[0-9]+$" (js2-number-node-value node)))
6785 (js2-number-node-value node))
6786 ((js2-this-node-p node)
6787 "this")))
6788
6789 (defsubst js2-node-qname-component (node)
6790 "Return the name of this node, if it contributes to a qname.
6791 Returns nil if the node doesn't contribute."
6792 (copy-sequence
6793 (or (js2-prop-node-name node)
6794 (if (and (js2-function-node-p node)
6795 (js2-function-node-name node))
6796 (js2-name-node-name (js2-function-node-name node))))))
6797
6798 (defsubst js2-record-imenu-entry (fn-node qname pos)
6799 "Add an entry to `js2-imenu-recorder'.
6800 FN-NODE should be the current item's function node.
6801
6802 Associate FN-NODE with its QNAME for later lookup.
6803 This is used in postprocessing the chain list. For each chain, we find
6804 the parent function, look up its qname, then prepend a copy of it to the chain."
6805 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6806 (unless js2-imenu-function-map
6807 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6808 (puthash fn-node qname js2-imenu-function-map))
6809
6810 (defun js2-record-imenu-functions (node &optional var)
6811 "Record function definitions for imenu.
6812 NODE is a function node or an object literal.
6813 VAR, if non-nil, is the expression that NODE is being assigned to.
6814 When passed arguments of wrong type, does nothing."
6815 (when js2-parse-ide-mode
6816 (let ((fun-p (js2-function-node-p node))
6817 qname left fname-node pos)
6818 (cond
6819 ;; non-anonymous function declaration?
6820 ((and fun-p
6821 (not var)
6822 (setq fname-node (js2-function-node-name node)))
6823 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6824 ;; for remaining forms, compute left-side tree branch first
6825 ((and var (setq qname (js2-compute-nested-prop-get var)))
6826 (cond
6827 ;; foo.bar.baz = function
6828 (fun-p
6829 (js2-record-imenu-entry node qname (js2-node-pos node)))
6830 ;; foo.bar.baz = object-literal
6831 ;; look for nested functions: {a: {b: function() {...} }}
6832 ((js2-object-node-p node)
6833 ;; Node position here is still absolute, since the parser
6834 ;; passes the assignment target and value expressions
6835 ;; to us before they are added as children of the assignment node.
6836 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6837
6838 (defun js2-compute-nested-prop-get (node)
6839 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6840 component nodes as a list. Otherwise return nil. Element-gets are treated
6841 as property-gets if the index expression is a string, or a positive integer."
6842 (let (left right head)
6843 (cond
6844 ((or (js2-name-node-p node)
6845 (js2-this-node-p node))
6846 (list node))
6847 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6848 ((js2-prop-get-node-p node) ; foo.bar
6849 (setq left (js2-prop-get-node-left node)
6850 right (js2-prop-get-node-right node))
6851 (if (setq head (js2-compute-nested-prop-get left))
6852 (nconc head (list right))))
6853 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6854 (setq left (js2-elem-get-node-target node)
6855 right (js2-elem-get-node-element node))
6856 (if (or (js2-string-node-p right) ; ['bar']
6857 (and (js2-number-node-p right) ; [10]
6858 (string-match "^[0-9]+$"
6859 (js2-number-node-value right))))
6860 (if (setq head (js2-compute-nested-prop-get left))
6861 (nconc head (list right))))))))
6862
6863 (defun js2-record-object-literal (node qname pos)
6864 "Recursively process an object literal looking for functions.
6865 NODE is an object literal that is the right-hand child of an assignment
6866 expression. QNAME is a list of nodes representing the assignment target,
6867 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6868 POS is the absolute position of the node.
6869 We do a depth-first traversal of NODE. For any functions we find,
6870 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6871 (let (left right prop-qname)
6872 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6873 (let ((left (js2-infix-node-left e))
6874 ;; Element positions are relative to the parent position.
6875 (pos (+ pos (js2-node-pos e))))
6876 (cond
6877 ;; foo: function() {...}
6878 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6879 (when (js2-prop-node-name left)
6880 ;; As a policy decision, we record the position of the property,
6881 ;; not the position of the `function' keyword, since the property
6882 ;; is effectively the name of the function.
6883 (js2-record-imenu-entry right (append qname (list left)) pos)))
6884 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6885 ((js2-object-node-p right)
6886 (js2-record-object-literal right
6887 (append qname (list (js2-infix-node-left e)))
6888 (+ pos (js2-node-pos right)))))))))
6889
6890 (defsubst js2-node-top-level-decl-p (node)
6891 "Return t if NODE's name is defined in the top-level scope.
6892 Also returns t if NODE's name is not defined in any scope, since it implies
6893 that it's an external variable, which must also be in the top-level scope."
6894 (let* ((name (js2-prop-node-name node))
6895 (this-scope (js2-node-get-enclosing-scope node))
6896 defining-scope)
6897 (cond
6898 ((js2-this-node-p node)
6899 nil)
6900 ((null this-scope)
6901 t)
6902 ((setq defining-scope (js2-get-defining-scope this-scope name))
6903 (js2-ast-root-p defining-scope))
6904 (t t))))
6905
6906 (defsubst js2-wrapper-function-p (node)
6907 "Returns t if NODE is a function expression that's immediately invoked.
6908 NODE must be `js2-function-node'."
6909 (let ((parent (js2-node-parent node)))
6910 (or
6911 ;; function(){...}();
6912 (js2-call-node-p parent)
6913 (and (js2-paren-node-p parent)
6914 ;; (function(){...})();
6915 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6916 ;; (function(){...}).call(this);
6917 (and (js2-prop-get-node-p parent)
6918 (member (js2-name-node-name (js2-prop-get-node-right parent))
6919 '("call" "apply"))
6920 (js2-call-node-p (js2-node-parent parent))))))))
6921
6922 (defun js2-browse-postprocess-chains (entries)
6923 "Modify function-declaration name chains after parsing finishes.
6924 Some of the information is only available after the parse tree is complete.
6925 For instance, processing a nested scope requires a parent function node."
6926 (let (result head fn current-fn parent-qname qname p elem)
6927 (dolist (entry entries)
6928 ;; function node goes first
6929 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6930 ;; Examine head's defining scope:
6931 ;; Pre-processed chain, or top-level/external, keep as-is.
6932 (if (or (stringp head) (js2-node-top-level-decl-p head))
6933 (push chain result)
6934 (when (js2-this-node-p head)
6935 (setq chain (cdr chain))) ; discard this-node
6936 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6937 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6938 (when (eq parent-qname 'not-found)
6939 ;; anonymous function expressions are not recorded
6940 ;; during the parse, so we need to handle this case here
6941 (setq parent-qname
6942 (if (js2-wrapper-function-p fn)
6943 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6944 (if (js2-ast-root-p grandparent)
6945 nil
6946 (gethash grandparent js2-imenu-function-map 'skip)))
6947 'skip))
6948 (puthash fn parent-qname js2-imenu-function-map))
6949 (unless (eq parent-qname 'skip)
6950 ;; prefix parent fn qname to this chain.
6951 (let ((qname (append parent-qname chain)))
6952 (puthash current-fn (butlast qname) js2-imenu-function-map)
6953 (push qname result)))))))
6954 ;; finally replace each node in each chain with its name.
6955 (dolist (chain result)
6956 (setq p chain)
6957 (while p
6958 (if (js2-node-p (setq elem (car p)))
6959 (setcar p (js2-node-qname-component elem)))
6960 (setq p (cdr p))))
6961 result))
6962
6963 ;; Merge name chains into a trie-like tree structure of nested lists.
6964 ;; To simplify construction of the trie, we first build it out using the rule
6965 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6966 ;; [key, num-or-list]. The second element can be a number; if so, this key
6967 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6968 ;; associated with the key at this level.) Otherwise the second element is
6969 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6970 ;; a simple recursive formulation.
6971 ;;
6972 ;; js2-mode is building the data structure for imenu. The imenu documentation
6973 ;; claims that it's the structure above, but in practice it wants the children
6974 ;; at the same list level as the key for that level, which is how I've drawn
6975 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6976 ;; list wrapper around the children at each level.
6977 ;;
6978 ;; A completed nested imenu-alist entry looks like this:
6979 ;; '(("foo"
6980 ;; ("<definition>" . 7)
6981 ;; ("bar"
6982 ;; ("a" . 40)
6983 ;; ("b" . 60))))
6984 ;;
6985 ;; In particular, the documentation for `imenu--index-alist' says that
6986 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6987 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6988
6989 (defun js2-treeify (lst)
6990 "Convert (a b c d) to (a ((b ((c d)))))"
6991 (if (null (cddr lst)) ; list length <= 2
6992 lst
6993 (list (car lst) (list (js2-treeify (cdr lst))))))
6994
6995 (defun js2-build-alist-trie (chains trie)
6996 "Merge declaration name chains into a trie-like alist structure for imenu.
6997 CHAINS is the qname chain list produced during parsing. TRIE is a
6998 list of elements built up so far."
6999 (let (head tail pos branch kids)
7000 (dolist (chain chains)
7001 (setq head (car chain)
7002 tail (cdr chain)
7003 pos (if (numberp (car tail)) (car tail))
7004 branch (js2-find-if (lambda (n)
7005 (string= (car n) head))
7006 trie)
7007 kids (second branch))
7008 (cond
7009 ;; case 1: this key isn't in the trie yet
7010 ((null branch)
7011 (if trie
7012 (setcdr (last trie) (list (js2-treeify chain)))
7013 (setq trie (list (js2-treeify chain)))))
7014 ;; case 2: key is present with a single number entry: replace w/ list
7015 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7016 ;; ("<definition>" 20)))
7017 ((numberp kids)
7018 (setcar (cdr branch)
7019 (list (list "<definition-1>" kids)
7020 (if pos
7021 (list "<definition-2>" pos)
7022 (js2-treeify tail)))))
7023 ;; case 3: key is there (with kids), and we're a number entry
7024 (pos
7025 (setcdr (last kids)
7026 (list
7027 (list (format "<definition-%d>"
7028 (1+ (loop for kid in kids
7029 count (eq ?< (aref (car kid) 0)))))
7030 pos))))
7031 ;; case 4: key is there with kids, need to merge in our chain
7032 (t
7033 (js2-build-alist-trie (list tail) kids))))
7034 trie))
7035
7036 (defun js2-flatten-trie (trie)
7037 "Convert TRIE to imenu-format.
7038 Recurses through nodes, and for each one whose second element is a list,
7039 appends the list's flattened elements to the current element. Also
7040 changes the tails into conses. For instance, this pre-flattened trie
7041
7042 '(a ((b 20)
7043 (c ((d 30)
7044 (e 40)))))
7045
7046 becomes
7047
7048 '(a (b . 20)
7049 (c (d . 30)
7050 (e . 40)))
7051
7052 Note that the root of the trie has no key, just a list of chains.
7053 This is also true for the value of any key with multiple children,
7054 e.g. key 'c' in the example above."
7055 (cond
7056 ((listp (car trie))
7057 (mapcar #'js2-flatten-trie trie))
7058 (t
7059 (if (numberp (second trie))
7060 (cons (car trie) (second trie))
7061 ;; else pop list and append its kids
7062 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7063
7064 (defun js2-build-imenu-index ()
7065 "Turn `js2-imenu-recorder' into an imenu data structure."
7066 (unless (eq js2-imenu-recorder 'empty)
7067 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7068 (result (js2-build-alist-trie chains nil)))
7069 (js2-flatten-trie result))))
7070
7071 (defun js2-test-print-chains (chains)
7072 "Print a list of qname chains.
7073 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7074 i.e. one or more nodes, and an integer position as the list tail."
7075 (mapconcat (lambda (chain)
7076 (concat "("
7077 (mapconcat (lambda (elem)
7078 (if (js2-node-p elem)
7079 (or (js2-node-qname-component elem)
7080 "nil")
7081 (number-to-string elem)))
7082 chain
7083 " ")
7084 ")"))
7085 chains
7086 "\n"))
7087
7088 ;;; Parser
7089
7090 (defconst js2-version "1.8.5"
7091 "Version of JavaScript supported.")
7092
7093 (defmacro js2-record-face (face)
7094 "Record a style run of FACE for the current token."
7095 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7096
7097 (defsubst js2-node-end (n)
7098 "Computes the absolute end of node N.
7099 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7100 is only true until the node is added to its parent; i.e., while parsing."
7101 (+ (js2-node-pos n)
7102 (js2-node-len n)))
7103
7104 (defsubst js2-record-comment ()
7105 "Record a comment in `js2-scanned-comments'."
7106 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7107 :format js2-ts-comment-type)
7108 js2-scanned-comments)
7109 (when js2-parse-ide-mode
7110 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7111 'font-lock-doc-face
7112 'font-lock-comment-face))
7113 (when (memq js2-ts-comment-type '(html preprocessor))
7114 ;; Tell cc-engine the bounds of the comment.
7115 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7116
7117 ;; This function is called depressingly often, so it should be fast.
7118 ;; Most of the time it's looking at the same token it peeked before.
7119 (defsubst js2-peek-token ()
7120 "Returns the next token without consuming it.
7121 If previous token was consumed, calls scanner to get new token.
7122 If previous token was -not- consumed, returns it (idempotent).
7123
7124 This function will not return a newline (js2-EOL) - instead, it
7125 gobbles newlines until it finds a non-newline token, and flags
7126 that token as appearing just after a newline.
7127
7128 This function will also not return a js2-COMMENT. Instead, it
7129 records comments found in `js2-scanned-comments'. If the token
7130 returned by this function immediately follows a jsdoc comment,
7131 the token is flagged as such.
7132
7133 Note that this function always returned the un-flagged token!
7134 The flags, if any, are saved in `js2-current-flagged-token'."
7135 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7136 js2-current-token ; most common case - return already-peeked token
7137 (let ((tt (js2-get-token)) ; call scanner
7138 saw-eol
7139 face)
7140 ;; process comments and whitespace
7141 (while (or (= tt js2-EOL)
7142 (= tt js2-COMMENT))
7143 (if (= tt js2-EOL)
7144 (setq saw-eol t)
7145 (setq saw-eol nil)
7146 (if js2-record-comments
7147 (js2-record-comment)))
7148 (setq tt (js2-get-token))) ; call scanner
7149 (setq js2-current-token tt
7150 js2-current-flagged-token (if saw-eol
7151 (logior tt js2-ti-after-eol)
7152 tt))
7153 ;; perform lexical fontification as soon as token is scanned
7154 (when js2-parse-ide-mode
7155 (cond
7156 ((minusp tt)
7157 (js2-record-face 'js2-error-face))
7158 ((setq face (aref js2-kwd-tokens tt))
7159 (js2-record-face face))
7160 ((and (= tt js2-NAME)
7161 (equal js2-ts-string "undefined"))
7162 (js2-record-face 'font-lock-constant-face))))
7163 tt))) ; return unflagged token
7164
7165 (defsubst js2-peek-flagged-token ()
7166 "Returns the current token along with any flags set for it."
7167 (js2-peek-token)
7168 js2-current-flagged-token)
7169
7170 (defsubst js2-consume-token ()
7171 (setq js2-current-flagged-token js2-EOF))
7172
7173 (defsubst js2-next-token ()
7174 (prog1
7175 (js2-peek-token)
7176 (js2-consume-token)))
7177
7178 (defsubst js2-next-flagged-token ()
7179 (js2-peek-token)
7180 (prog1 js2-current-flagged-token
7181 (js2-consume-token)))
7182
7183 (defsubst js2-match-token (match)
7184 "Consume and return t if next token matches MATCH, a bytecode.
7185 Returns nil and consumes nothing if MATCH is not the next token."
7186 (if (/= (js2-peek-token) match)
7187 nil
7188 (js2-consume-token)
7189 t))
7190
7191 (defun js2-match-contextual-kwd (name)
7192 "Consume and return t if next token is `js2-NAME', and its
7193 string is NAME. Returns nil and does nothing otherwise."
7194 (if (or (/= (js2-peek-token) js2-NAME)
7195 (not (string= js2-ts-string name)))
7196 nil
7197 (js2-consume-token)
7198 (js2-record-face 'font-lock-keyword-face)
7199 t))
7200
7201 (defsubst js2-valid-prop-name-token (tt)
7202 (or (= tt js2-NAME)
7203 (when (and js2-allow-keywords-as-property-names
7204 (plusp tt)
7205 (aref js2-kwd-tokens tt))
7206 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7207 t)))
7208
7209 (defsubst js2-match-prop-name ()
7210 "Consume token and return t if next token is a valid property name.
7211 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7212 is non-nil and it's a keyword token."
7213 (if (js2-valid-prop-name-token (js2-peek-token))
7214 (progn
7215 (js2-consume-token)
7216 t)
7217 nil))
7218
7219 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7220 (if (js2-match-prop-name)
7221 t
7222 (js2-report-error msg-id nil pos len)
7223 nil))
7224
7225 (defsubst js2-peek-token-or-eol ()
7226 "Return js2-EOL if the current token immediately follows a newline.
7227 Else returns the current token. Used in situations where we don't
7228 consider certain token types valid if they are preceded by a newline.
7229 One example is the postfix ++ or -- operator, which has to be on the
7230 same line as its operand."
7231 (let ((tt (js2-peek-token)))
7232 ;; Check for last peeked token flags
7233 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7234 js2-EOL
7235 tt)))
7236
7237 (defsubst js2-set-check-for-label ()
7238 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7239 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7240
7241 (defsubst js2-must-match (token msg-id &optional pos len)
7242 "Match next token to token code TOKEN, or record a syntax error.
7243 MSG-ID is the error message to report if the match fails.
7244 Returns t on match, nil if no match."
7245 (if (js2-match-token token)
7246 t
7247 (js2-report-error msg-id nil pos len)
7248 nil))
7249
7250 (defsubst js2-inside-function ()
7251 (plusp js2-nesting-of-function))
7252
7253 (defsubst js2-set-requires-activation ()
7254 (if (js2-function-node-p js2-current-script-or-fn)
7255 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7256
7257 (defsubst js2-check-activation-name (name token)
7258 (when (js2-inside-function)
7259 ;; skip language-version 1.2 check from Rhino
7260 (if (or (string= "arguments" name)
7261 (and js2-compiler-activation-names ; only used in codegen
7262 (gethash name js2-compiler-activation-names)))
7263 (js2-set-requires-activation))))
7264
7265 (defsubst js2-set-is-generator ()
7266 (if (js2-function-node-p js2-current-script-or-fn)
7267 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7268
7269 (defsubst js2-must-have-xml ()
7270 (unless js2-compiler-xml-available
7271 (js2-report-error "msg.XML.not.available")))
7272
7273 (defsubst js2-push-scope (scope)
7274 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7275 (assert (js2-scope-p scope))
7276 (assert (null (js2-scope-parent-scope scope)))
7277 (assert (not (eq js2-current-scope scope)))
7278 (setf (js2-scope-parent-scope scope) js2-current-scope
7279 js2-current-scope scope))
7280
7281 (defsubst js2-pop-scope ()
7282 (setq js2-current-scope
7283 (js2-scope-parent-scope js2-current-scope)))
7284
7285 (defsubst js2-enter-loop (loop-node)
7286 (push loop-node js2-loop-set)
7287 (push loop-node js2-loop-and-switch-set)
7288 (js2-push-scope loop-node)
7289 ;; Tell the current labeled statement (if any) its statement,
7290 ;; and set the jump target of the first label to the loop.
7291 ;; These are used in `js2-parse-continue' to verify that the
7292 ;; continue target is an actual labeled loop. (And for codegen.)
7293 (when js2-labeled-stmt
7294 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7295 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7296 js2-labeled-stmt))) loop-node)))
7297
7298 (defsubst js2-exit-loop ()
7299 (pop js2-loop-set)
7300 (pop js2-loop-and-switch-set)
7301 (js2-pop-scope))
7302
7303 (defsubst js2-enter-switch (switch-node)
7304 (push switch-node js2-loop-and-switch-set))
7305
7306 (defsubst js2-exit-switch ()
7307 (pop js2-loop-and-switch-set))
7308
7309 (defun js2-parse (&optional buf cb)
7310 "Tells the js2 parser to parse a region of JavaScript.
7311
7312 BUF is a buffer or buffer name containing the code to parse.
7313 Call `narrow-to-region' first to parse only part of the buffer.
7314
7315 The returned AST root node is given some additional properties:
7316 `node-count' - total number of nodes in the AST
7317 `buffer' - BUF. The buffer it refers to may change or be killed,
7318 so the value is not necessarily reliable.
7319
7320 An optional callback CB can be specified to report parsing
7321 progress. If `(functionp CB)' returns t, it will be called with
7322 the current line number once before parsing begins, then again
7323 each time the lexer reaches a new line number.
7324
7325 CB can also be a list of the form `(symbol cb ...)' to specify
7326 multiple callbacks with different criteria. Each symbol is a
7327 criterion keyword, and the following element is the callback to
7328 call
7329
7330 :line - called whenever the line number changes
7331 :token - called for each new token consumed
7332
7333 The list of criteria could be extended to include entering or
7334 leaving a statement, an expression, or a function definition."
7335 (if (and cb (not (functionp cb)))
7336 (error "criteria callbacks not yet implemented"))
7337 (let ((inhibit-point-motion-hooks t)
7338 (js2-compiler-xml-available (>= js2-language-version 160))
7339 ;; This is a recursive-descent parser, so give it a big stack.
7340 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7341 (max-specpdl-size (max max-specpdl-size 3000))
7342 (case-fold-search nil)
7343 ast)
7344 (message nil) ; clear any error message from previous parse
7345 (save-excursion
7346 (when buf (set-buffer buf))
7347 (setq js2-scanned-comments nil
7348 js2-parsed-errors nil
7349 js2-parsed-warnings nil
7350 js2-imenu-recorder nil
7351 js2-imenu-function-map nil
7352 js2-label-set nil)
7353 (js2-init-scanner)
7354 (setq ast (js2-with-unmodifying-text-property-changes
7355 (js2-do-parse)))
7356 (unless js2-ts-hit-eof
7357 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7358 (setf (js2-ast-root-errors ast) js2-parsed-errors
7359 (js2-ast-root-warnings ast) js2-parsed-warnings)
7360 ;; if we didn't find any declarations, put a dummy in this list so we
7361 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7362 (unless js2-imenu-recorder
7363 (setq js2-imenu-recorder 'empty))
7364 (run-hooks 'js2-parse-finished-hook)
7365 ast)))
7366
7367 ;; Corresponds to Rhino's Parser.parse() method.
7368 (defun js2-do-parse ()
7369 "Parse current buffer starting from current point.
7370 Scanner should be initialized."
7371 (let ((pos js2-ts-cursor)
7372 (end js2-ts-cursor) ; in case file is empty
7373 root n tt)
7374 ;; initialize buffer-local parsing vars
7375 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7376 js2-current-script-or-fn root
7377 js2-current-scope root
7378 js2-current-flagged-token js2-EOF
7379 js2-nesting-of-function 0
7380 js2-labeled-stmt nil
7381 js2-recorded-identifiers nil) ; for js2-highlight
7382 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7383 (if (= tt js2-FUNCTION)
7384 (progn
7385 (js2-consume-token)
7386 (setq n (js2-parse-function (if js2-called-by-compile-function
7387 'FUNCTION_EXPRESSION
7388 'FUNCTION_STATEMENT))))
7389 ;; not a function - parse a statement
7390 (setq n (js2-parse-statement)))
7391 ;; add function or statement to script
7392 (setq end (js2-node-end n))
7393 (js2-block-node-push root n))
7394 ;; add comments to root in lexical order
7395 (when js2-scanned-comments
7396 ;; if we find a comment beyond end of normal kids, use its end
7397 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7398 (dolist (comment js2-scanned-comments)
7399 (push comment (js2-ast-root-comments root))
7400 (js2-node-add-children root comment)))
7401 (setf (js2-node-len root) (- end pos))
7402 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7403 ;; Give extensions a chance to muck with things before highlighting starts.
7404 (let ((js2-additional-externs js2-additional-externs))
7405 (dolist (callback js2-post-parse-callbacks)
7406 (funcall callback))
7407 (js2-highlight-undeclared-vars))
7408 root))
7409
7410 (defun js2-function-parser ()
7411 (js2-consume-token)
7412 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7413
7414 (defun js2-parse-function-closure-body (fn-node)
7415 "Parse a JavaScript 1.8 function closure body."
7416 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7417 (if js2-ts-hit-eof
7418 (js2-report-error "msg.no.brace.body" nil
7419 (js2-node-pos fn-node)
7420 (- js2-ts-cursor (js2-node-pos fn-node)))
7421 (js2-node-add-children fn-node
7422 (setf (js2-function-node-body fn-node)
7423 (js2-parse-expr t))))))
7424
7425 (defun js2-parse-function-body (fn-node)
7426 (js2-must-match js2-LC "msg.no.brace.body"
7427 (js2-node-pos fn-node)
7428 (- js2-ts-cursor (js2-node-pos fn-node)))
7429 (let ((pos js2-token-beg) ; LC position
7430 (pn (make-js2-block-node)) ; starts at LC position
7431 tt
7432 end)
7433 (incf js2-nesting-of-function)
7434 (unwind-protect
7435 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7436 (= tt js2-EOF)
7437 (= tt js2-RC)))
7438 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7439 (js2-parse-statement)
7440 (js2-consume-token)
7441 (js2-parse-function 'FUNCTION_STATEMENT))))
7442 (decf js2-nesting-of-function))
7443 (setq end js2-token-end) ; assume no curly and leave at current token
7444 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7445 (setq end js2-token-end))
7446 (setf (js2-node-pos pn) pos
7447 (js2-node-len pn) (- end pos))
7448 (setf (js2-function-node-body fn-node) pn)
7449 (js2-node-add-children fn-node pn)
7450 pn))
7451
7452 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7453 "Declare and fontify destructuring parameters inside NODE.
7454 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7455 (cond
7456 ((js2-name-node-p node)
7457 (let (leftpos)
7458 (js2-define-symbol decl-type (js2-name-node-name node)
7459 node ignore-not-in-block)
7460 (when face
7461 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7462 (+ leftpos (js2-node-len node))
7463 face 'record))))
7464 ((js2-object-node-p node)
7465 (dolist (elem (js2-object-node-elems node))
7466 (js2-define-destruct-symbols
7467 (if (js2-object-prop-node-p elem)
7468 (js2-object-prop-node-right elem)
7469 ;; abbreviated destructuring {a, b}
7470 elem)
7471 decl-type face ignore-not-in-block)))
7472 ((js2-array-node-p node)
7473 (dolist (elem (js2-array-node-elems node))
7474 (when elem
7475 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7476 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7477 (js2-node-len node)))))
7478
7479 (defun js2-parse-function-params (fn-node pos)
7480 (if (js2-match-token js2-RP)
7481 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7482 (let (params len param default-found rest-param-at)
7483 (loop for tt = (js2-peek-token)
7484 do
7485 (cond
7486 ;; destructuring param
7487 ((or (= tt js2-LB) (= tt js2-LC))
7488 (when default-found
7489 (js2-report-error "msg.no.default.after.default.param"))
7490 (setq param (js2-parse-destruct-primary-expr))
7491 (js2-define-destruct-symbols param
7492 js2-LP
7493 'js2-function-param-face)
7494 (push param params))
7495 ;; variable name
7496 (t
7497 (when (and (>= js2-language-version 200)
7498 (js2-match-token js2-TRIPLEDOT)
7499 (not rest-param-at))
7500 ;; to report errors if there are more parameters
7501 (setq rest-param-at (length params)))
7502 (js2-must-match js2-NAME "msg.no.parm")
7503 (js2-record-face 'js2-function-param-face)
7504 (setq param (js2-create-name-node))
7505 (js2-define-symbol js2-LP js2-ts-string param)
7506 ;; default parameter value
7507 (when (or (and default-found
7508 (not rest-param-at)
7509 (js2-must-match js2-ASSIGN
7510 "msg.no.default.after.default.param"
7511 (js2-node-pos param)
7512 (js2-node-len param)))
7513 (and (>= js2-language-version 200)
7514 (js2-match-token js2-ASSIGN)))
7515 (let* ((pos (js2-node-pos param))
7516 (tt js2-current-token)
7517 (op-pos (- js2-token-beg pos))
7518 (left param)
7519 (right (js2-parse-assign-expr))
7520 (len (- (js2-node-end right) pos)))
7521 (setq param (make-js2-assign-node
7522 :type tt :pos pos :len len :op-pos op-pos
7523 :left left :right right)
7524 default-found t)
7525 (js2-node-add-children param left right)))
7526 (push param params)))
7527 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7528 (js2-report-error "msg.param.after.rest" nil
7529 (js2-node-pos param) (js2-node-len param)))
7530 while
7531 (js2-match-token js2-COMMA))
7532 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7533 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7534 (when rest-param-at
7535 (setf (js2-function-node-rest-p fn-node) t))
7536 (dolist (p params)
7537 (js2-node-add-children fn-node p)
7538 (push p (js2-function-node-params fn-node))))))
7539
7540 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7541 "Possibly show inconsistent-return warning.
7542 Last token scanned is the close-curly for the function body."
7543 (when (and js2-mode-show-strict-warnings
7544 js2-strict-inconsistent-return-warning
7545 (not (js2-has-consistent-return-usage
7546 (js2-function-node-body fn-node))))
7547 ;; Have it extend from close-curly to bol or beginning of block.
7548 (let ((pos (save-excursion
7549 (goto-char js2-token-end)
7550 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7551 (point-at-bol))))
7552 (end js2-token-end))
7553 (if (plusp (js2-name-node-length name))
7554 (js2-add-strict-warning "msg.no.return.value"
7555 (js2-name-node-name name) pos end)
7556 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7557
7558 (defun js2-parse-function (function-type)
7559 "Function parser. FUNCTION-TYPE is a symbol."
7560 (let ((pos js2-token-beg) ; start of 'function' keyword
7561 name
7562 name-beg
7563 name-end
7564 fn-node
7565 lp
7566 (synthetic-type function-type)
7567 member-expr-node)
7568 ;; parse function name, expression, or non-name (anonymous)
7569 (cond
7570 ;; function foo(...)
7571 ((js2-match-token js2-NAME)
7572 (setq name (js2-create-name-node t)
7573 name-beg js2-token-beg
7574 name-end js2-token-end)
7575 (unless (js2-match-token js2-LP)
7576 (when js2-allow-member-expr-as-function-name
7577 ;; function foo.bar(...)
7578 (setq member-expr-node name
7579 name nil
7580 member-expr-node (js2-parse-member-expr-tail
7581 nil member-expr-node)))
7582 (js2-must-match js2-LP "msg.no.paren.parms")))
7583 ((js2-match-token js2-LP)
7584 nil) ; anonymous function: leave name as null
7585 (t
7586 ;; function random-member-expr(...)
7587 (when js2-allow-member-expr-as-function-name
7588 ;; Note that memberExpr can not start with '(' like
7589 ;; in function (1+2).toString(), because 'function (' already
7590 ;; processed as anonymous function
7591 (setq member-expr-node (js2-parse-member-expr)))
7592 (js2-must-match js2-LP "msg.no.paren.parms")))
7593 (if (= js2-current-token js2-LP) ; eventually matched LP?
7594 (setq lp js2-token-beg))
7595 (if member-expr-node
7596 (progn
7597 (setq synthetic-type 'FUNCTION_EXPRESSION)
7598 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7599 (if name
7600 (js2-set-face name-beg name-end
7601 'font-lock-function-name-face 'record)))
7602 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7603 (plusp (js2-name-node-length name)))
7604 ;; Function statements define a symbol in the enclosing scope
7605 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7606 (setf fn-node (make-js2-function-node :pos pos
7607 :name name
7608 :form function-type
7609 :lp (if lp (- lp pos))))
7610 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7611 ;; 1. Nested functions are not affected by the dynamic scope flag
7612 ;; as dynamic scope is already a parent of their scope.
7613 ;; 2. Functions defined under the with statement also immune to
7614 ;; this setup, in which case dynamic scope is ignored in favor
7615 ;; of the with object.
7616 (setf (js2-function-node-ignore-dynamic fn-node) t))
7617 ;; dynamically bind all the per-function variables
7618 (let ((js2-current-script-or-fn fn-node)
7619 (js2-current-scope fn-node)
7620 (js2-nesting-of-with 0)
7621 (js2-end-flags 0)
7622 js2-label-set
7623 js2-loop-set
7624 js2-loop-and-switch-set)
7625 (js2-parse-function-params fn-node pos)
7626 (if (and (>= js2-language-version 180)
7627 (/= (js2-peek-token) js2-LC))
7628 (js2-parse-function-closure-body fn-node)
7629 (js2-parse-function-body fn-node))
7630 (if name
7631 (js2-node-add-children fn-node name))
7632 (js2-check-inconsistent-return-warning fn-node name)
7633 ;; Function expressions define a name only in the body of the
7634 ;; function, and only if not hidden by a parameter name
7635 (if (and name
7636 (eq synthetic-type 'FUNCTION_EXPRESSION)
7637 (null (js2-scope-get-symbol js2-current-scope
7638 (js2-name-node-name name))))
7639 (js2-define-symbol js2-FUNCTION
7640 (js2-name-node-name name)
7641 fn-node))
7642 (if (and name
7643 (not (eq function-type 'FUNCTION_EXPRESSION)))
7644 (js2-record-imenu-functions fn-node)))
7645 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7646 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7647 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7648 ;; We wait until after parsing the function to set its parent scope,
7649 ;; since `js2-define-symbol' needs the defining-scope check to stop
7650 ;; at the function boundary when checking for redeclarations.
7651 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7652 fn-node))
7653
7654 (defun js2-parse-statements (&optional parent)
7655 "Parse a statement list. Last token consumed must be js2-LC.
7656
7657 PARENT can be a `js2-block-node', in which case the statements are
7658 appended to PARENT. Otherwise a new `js2-block-node' is created
7659 and returned.
7660
7661 This function does not match the closing js2-RC: the caller
7662 matches the RC so it can provide a suitable error message if not
7663 matched. This means it's up to the caller to set the length of
7664 the node to include the closing RC. The node start pos is set to
7665 the absolute buffer start position, and the caller should fix it
7666 up to be relative to the parent node. All children of this block
7667 node are given relative start positions and correct lengths."
7668 (let ((pn (or parent (make-js2-block-node)))
7669 tt)
7670 (setf (js2-node-pos pn) js2-token-beg)
7671 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7672 (/= tt js2-RC))
7673 (js2-block-node-push pn (js2-parse-statement)))
7674 pn))
7675
7676 (defun js2-parse-statement ()
7677 (let (tt pn beg end)
7678 ;; coarse-grained user-interrupt check - needs work
7679 (and js2-parse-interruptable-p
7680 (zerop (% (incf js2-parse-stmt-count)
7681 js2-statements-per-pause))
7682 (input-pending-p)
7683 (throw 'interrupted t))
7684 (setq pn (js2-statement-helper))
7685 ;; no-side-effects warning check
7686 (unless (js2-node-has-side-effects pn)
7687 (setq end (js2-node-end pn))
7688 (save-excursion
7689 (goto-char end)
7690 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7691 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7692 pn))
7693
7694 ;; These correspond to the switch cases in Parser.statementHelper
7695 (defconst js2-parsers
7696 (let ((parsers (make-vector js2-num-tokens
7697 #'js2-parse-expr-stmt)))
7698 (aset parsers js2-BREAK #'js2-parse-break)
7699 (aset parsers js2-CONST #'js2-parse-const-var)
7700 (aset parsers js2-CONTINUE #'js2-parse-continue)
7701 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7702 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7703 (aset parsers js2-DO #'js2-parse-do)
7704 (aset parsers js2-FOR #'js2-parse-for)
7705 (aset parsers js2-FUNCTION #'js2-function-parser)
7706 (aset parsers js2-IF #'js2-parse-if)
7707 (aset parsers js2-LC #'js2-parse-block)
7708 (aset parsers js2-LET #'js2-parse-let-stmt)
7709 (aset parsers js2-NAME #'js2-parse-name-or-label)
7710 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7711 (aset parsers js2-SEMI #'js2-parse-semi)
7712 (aset parsers js2-SWITCH #'js2-parse-switch)
7713 (aset parsers js2-THROW #'js2-parse-throw)
7714 (aset parsers js2-TRY #'js2-parse-try)
7715 (aset parsers js2-VAR #'js2-parse-const-var)
7716 (aset parsers js2-WHILE #'js2-parse-while)
7717 (aset parsers js2-WITH #'js2-parse-with)
7718 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7719 parsers)
7720 "A vector mapping token types to parser functions.")
7721
7722 (defsubst js2-parse-warn-missing-semi (beg end)
7723 (and js2-mode-show-strict-warnings
7724 js2-strict-missing-semi-warning
7725 (js2-add-strict-warning
7726 "msg.missing.semi" nil
7727 ;; back up to beginning of statement or line
7728 (max beg (save-excursion
7729 (goto-char end)
7730 (point-at-bol)))
7731 end)))
7732
7733 (defconst js2-no-semi-insertion
7734 (list js2-IF
7735 js2-SWITCH
7736 js2-WHILE
7737 js2-DO
7738 js2-FOR
7739 js2-TRY
7740 js2-WITH
7741 js2-LC
7742 js2-ERROR
7743 js2-SEMI
7744 js2-FUNCTION)
7745 "List of tokens that don't do automatic semicolon insertion.")
7746
7747 (defconst js2-autoinsert-semi-and-warn
7748 (list js2-ERROR js2-EOF js2-RC))
7749
7750 (defun js2-statement-helper ()
7751 (let* ((tt (js2-peek-token))
7752 (first-tt tt)
7753 (beg js2-token-beg)
7754 (parser (if (= tt js2-ERROR)
7755 #'js2-parse-semi
7756 (aref js2-parsers tt)))
7757 pn
7758 tt-flagged)
7759 ;; If the statement is set, then it's been told its label by now.
7760 (and js2-labeled-stmt
7761 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7762 (setq js2-labeled-stmt nil))
7763 (setq pn (funcall parser))
7764 ;; Don't do auto semi insertion for certain statement types.
7765 (unless (or (memq first-tt js2-no-semi-insertion)
7766 (js2-labeled-stmt-node-p pn))
7767 (js2-auto-insert-semicolon pn))
7768 pn))
7769
7770 (defun js2-auto-insert-semicolon (pn)
7771 (let* ((tt-flagged (js2-peek-flagged-token))
7772 (tt (logand tt-flagged js2-clear-ti-mask))
7773 (pos (js2-node-pos pn)))
7774 (cond
7775 ((= tt js2-SEMI)
7776 ;; Consume ';' as a part of expression
7777 (js2-consume-token)
7778 ;; extend the node bounds to include the semicolon.
7779 (setf (js2-node-len pn) (- js2-token-end pos)))
7780 ((memq tt js2-autoinsert-semi-and-warn)
7781 ;; Autoinsert ;
7782 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7783 (t
7784 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7785 ;; Report error if no EOL or autoinsert ';' otherwise
7786 (js2-report-error "msg.no.semi.stmt")
7787 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7788
7789 (defun js2-parse-condition ()
7790 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7791 The parens are discarded and the expression node is returned.
7792 The `pos' field of the return value is set to an absolute position
7793 that must be fixed up by the caller.
7794 Return value is a list (EXPR LP RP), with absolute paren positions."
7795 (let (pn lp rp)
7796 (if (js2-must-match js2-LP "msg.no.paren.cond")
7797 (setq lp js2-token-beg))
7798 (setq pn (js2-parse-expr))
7799 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7800 (setq rp js2-token-beg))
7801 ;; Report strict warning on code like "if (a = 7) ..."
7802 (if (and js2-strict-cond-assign-warning
7803 (js2-assign-node-p pn))
7804 (js2-add-strict-warning "msg.equal.as.assign" nil
7805 (js2-node-pos pn)
7806 (+ (js2-node-pos pn)
7807 (js2-node-len pn))))
7808 (list pn lp rp)))
7809
7810 (defun js2-parse-if ()
7811 "Parser for if-statement. Last matched token must be js2-IF."
7812 (let ((pos js2-token-beg)
7813 cond
7814 if-true
7815 if-false
7816 else-pos
7817 end
7818 pn)
7819 (js2-consume-token)
7820 (setq cond (js2-parse-condition)
7821 if-true (js2-parse-statement)
7822 if-false (if (js2-match-token js2-ELSE)
7823 (progn
7824 (setq else-pos (- js2-token-beg pos))
7825 (js2-parse-statement)))
7826 end (js2-node-end (or if-false if-true))
7827 pn (make-js2-if-node :pos pos
7828 :len (- end pos)
7829 :condition (car cond)
7830 :then-part if-true
7831 :else-part if-false
7832 :else-pos else-pos
7833 :lp (js2-relpos (second cond) pos)
7834 :rp (js2-relpos (third cond) pos)))
7835 (js2-node-add-children pn (car cond) if-true if-false)
7836 pn))
7837
7838 (defun js2-parse-switch ()
7839 "Parser for if-statement. Last matched token must be js2-SWITCH."
7840 (let ((pos js2-token-beg)
7841 tt
7842 pn
7843 discriminant
7844 has-default
7845 case-expr
7846 case-node
7847 case-pos
7848 cases
7849 stmt
7850 lp
7851 rp)
7852 (js2-consume-token)
7853 (if (js2-must-match js2-LP "msg.no.paren.switch")
7854 (setq lp js2-token-beg))
7855 (setq discriminant (js2-parse-expr)
7856 pn (make-js2-switch-node :discriminant discriminant
7857 :pos pos
7858 :lp (js2-relpos lp pos)))
7859 (js2-node-add-children pn discriminant)
7860 (js2-enter-switch pn)
7861 (unwind-protect
7862 (progn
7863 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7864 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7865 (js2-must-match js2-LC "msg.no.brace.switch")
7866 (catch 'break
7867 (while t
7868 (setq tt (js2-next-token)
7869 case-pos js2-token-beg)
7870 (cond
7871 ((= tt js2-RC)
7872 (setf (js2-node-len pn) (- js2-token-end pos))
7873 (throw 'break nil)) ; done
7874 ((= tt js2-CASE)
7875 (setq case-expr (js2-parse-expr))
7876 (js2-must-match js2-COLON "msg.no.colon.case"))
7877 ((= tt js2-DEFAULT)
7878 (if has-default
7879 (js2-report-error "msg.double.switch.default"))
7880 (setq has-default t
7881 case-expr nil)
7882 (js2-must-match js2-COLON "msg.no.colon.case"))
7883 (t
7884 (js2-report-error "msg.bad.switch")
7885 (throw 'break nil)))
7886 (setq case-node (make-js2-case-node :pos case-pos
7887 :len (- js2-token-end case-pos)
7888 :expr case-expr))
7889 (js2-node-add-children case-node case-expr)
7890 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7891 (/= tt js2-CASE)
7892 (/= tt js2-DEFAULT)
7893 (/= tt js2-EOF))
7894 (setf stmt (js2-parse-statement)
7895 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7896 (js2-block-node-push case-node stmt))
7897 (push case-node cases)))
7898 ;; add cases last, as pushing reverses the order to be correct
7899 (dolist (kid cases)
7900 (js2-node-add-children pn kid)
7901 (push kid (js2-switch-node-cases pn)))
7902 pn) ; return value
7903 (js2-exit-switch))))
7904
7905 (defun js2-parse-while ()
7906 "Parser for while-statement. Last matched token must be js2-WHILE."
7907 (let ((pos js2-token-beg)
7908 (pn (make-js2-while-node))
7909 cond
7910 body)
7911 (js2-consume-token)
7912 (js2-enter-loop pn)
7913 (unwind-protect
7914 (progn
7915 (setf cond (js2-parse-condition)
7916 (js2-while-node-condition pn) (car cond)
7917 body (js2-parse-statement)
7918 (js2-while-node-body pn) body
7919 (js2-node-len pn) (- (js2-node-end body) pos)
7920 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7921 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7922 (js2-node-add-children pn body (car cond)))
7923 (js2-exit-loop))
7924 pn))
7925
7926 (defun js2-parse-do ()
7927 "Parser for do-statement. Last matched token must be js2-DO."
7928 (let ((pos js2-token-beg)
7929 (pn (make-js2-do-node))
7930 cond
7931 body
7932 end)
7933 (js2-consume-token)
7934 (js2-enter-loop pn)
7935 (unwind-protect
7936 (progn
7937 (setq body (js2-parse-statement))
7938 (js2-must-match js2-WHILE "msg.no.while.do")
7939 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7940 cond (js2-parse-condition)
7941 (js2-do-node-condition pn) (car cond)
7942 (js2-do-node-body pn) body
7943 end js2-ts-cursor
7944 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7945 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7946 (js2-node-add-children pn (car cond) body))
7947 (js2-exit-loop))
7948 ;; Always auto-insert semicolon to follow SpiderMonkey:
7949 ;; It is required by ECMAScript but is ignored by the rest of
7950 ;; world; see bug 238945
7951 (if (js2-match-token js2-SEMI)
7952 (setq end js2-ts-cursor))
7953 (setf (js2-node-len pn) (- end pos))
7954 pn))
7955
7956 (defun js2-parse-for ()
7957 "Parser for for-statement. Last matched token must be js2-FOR.
7958 Parses for, for-in, and for each-in statements."
7959 (let ((for-pos js2-token-beg)
7960 pn is-for-each is-for-in-or-of is-for-of
7961 in-pos each-pos tmp-pos
7962 init ; Node init is also foo in 'foo in object'
7963 cond ; Node cond is also object in 'foo in object'
7964 incr ; 3rd section of for-loop initializer
7965 body tt lp rp)
7966 (js2-consume-token)
7967 ;; See if this is a for each () instead of just a for ()
7968 (when (js2-match-token js2-NAME)
7969 (if (string= "each" js2-ts-string)
7970 (progn
7971 (setq is-for-each t
7972 each-pos (- js2-token-beg for-pos)) ; relative
7973 (js2-record-face 'font-lock-keyword-face))
7974 (js2-report-error "msg.no.paren.for")))
7975 (if (js2-must-match js2-LP "msg.no.paren.for")
7976 (setq lp (- js2-token-beg for-pos)))
7977 (setq tt (js2-peek-token))
7978 ;; 'for' makes local scope
7979 (js2-push-scope (make-js2-scope))
7980 (unwind-protect
7981 ;; parse init clause
7982 (let ((js2-in-for-init t)) ; set as dynamic variable
7983 (cond
7984 ((= tt js2-SEMI)
7985 (setq init (make-js2-empty-expr-node)))
7986 ((or (= tt js2-VAR) (= tt js2-LET))
7987 (js2-consume-token)
7988 (setq init (js2-parse-variables tt js2-token-beg)))
7989 (t
7990 (setq init (js2-parse-expr)))))
7991 (if (or (js2-match-token js2-IN)
7992 (and (>= js2-language-version 200)
7993 (js2-match-contextual-kwd "of")
7994 (setq is-for-of t)))
7995 (setq is-for-in-or-of t
7996 in-pos (- js2-token-beg for-pos)
7997 ;; scope of iteration target object is not the scope we've created above.
7998 ;; stash current scope temporary.
7999 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8000 (js2-parse-expr))) ; object over which we're iterating
8001 ;; else ordinary for loop - parse cond and incr
8002 (js2-must-match js2-SEMI "msg.no.semi.for")
8003 (setq cond (if (= (js2-peek-token) js2-SEMI)
8004 (make-js2-empty-expr-node) ; no loop condition
8005 (js2-parse-expr)))
8006 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8007 (setq tmp-pos js2-token-end
8008 incr (if (= (js2-peek-token) js2-RP)
8009 (make-js2-empty-expr-node :pos tmp-pos)
8010 (js2-parse-expr))))
8011 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8012 (setq rp (- js2-token-beg for-pos)))
8013 (if (not is-for-in-or-of)
8014 (setq pn (make-js2-for-node :init init
8015 :condition cond
8016 :update incr
8017 :lp lp
8018 :rp rp))
8019 ;; cond could be null if 'in obj' got eaten by the init node.
8020 (if (js2-infix-node-p init)
8021 ;; it was (foo in bar) instead of (var foo in bar)
8022 (setq cond (js2-infix-node-right init)
8023 init (js2-infix-node-left init))
8024 (if (and (js2-var-decl-node-p init)
8025 (> (length (js2-var-decl-node-kids init)) 1))
8026 (js2-report-error "msg.mult.index")))
8027 (setq pn (make-js2-for-in-node :iterator init
8028 :object cond
8029 :in-pos in-pos
8030 :foreach-p is-for-each
8031 :each-pos each-pos
8032 :forof-p is-for-of
8033 :lp lp
8034 :rp rp)))
8035 (unwind-protect
8036 (progn
8037 (js2-enter-loop pn)
8038 ;; We have to parse the body -after- creating the loop node,
8039 ;; so that the loop node appears in the js2-loop-set, allowing
8040 ;; break/continue statements to find the enclosing loop.
8041 (setf body (js2-parse-statement)
8042 (js2-loop-node-body pn) body
8043 (js2-node-pos pn) for-pos
8044 (js2-node-len pn) (- (js2-node-end body) for-pos))
8045 (js2-node-add-children pn init cond incr body))
8046 ;; finally
8047 (js2-exit-loop))
8048 (js2-pop-scope))
8049 pn))
8050
8051 (defun js2-parse-try ()
8052 "Parser for try-statement. Last matched token must be js2-TRY."
8053 (let ((try-pos js2-token-beg)
8054 try-end
8055 try-block
8056 catch-blocks
8057 finally-block
8058 saw-default-catch
8059 peek
8060 param
8061 catch-cond
8062 catch-node
8063 guard-kwd
8064 catch-pos
8065 finally-pos
8066 pn
8067 block
8068 lp
8069 rp)
8070 (js2-consume-token)
8071 (if (/= (js2-peek-token) js2-LC)
8072 (js2-report-error "msg.no.brace.try"))
8073 (setq try-block (js2-parse-statement)
8074 try-end (js2-node-end try-block)
8075 peek (js2-peek-token))
8076 (cond
8077 ((= peek js2-CATCH)
8078 (while (js2-match-token js2-CATCH)
8079 (setq catch-pos js2-token-beg
8080 guard-kwd nil
8081 catch-cond nil
8082 lp nil
8083 rp nil)
8084 (if saw-default-catch
8085 (js2-report-error "msg.catch.unreachable"))
8086 (if (js2-must-match js2-LP "msg.no.paren.catch")
8087 (setq lp (- js2-token-beg catch-pos)))
8088 (js2-push-scope (make-js2-scope))
8089 (let ((tt (js2-peek-token)))
8090 (cond
8091 ;; destructuring pattern
8092 ;; catch ({ message, file }) { ... }
8093 ((or (= tt js2-LB) (= tt js2-LC))
8094 (setq param (js2-parse-destruct-primary-expr))
8095 (js2-define-destruct-symbols param js2-LET nil))
8096 ;; simple name
8097 (t
8098 (js2-must-match js2-NAME "msg.bad.catchcond")
8099 (setq param (js2-create-name-node))
8100 (js2-define-symbol js2-LET js2-ts-string param))))
8101 ;; pattern guard
8102 (if (js2-match-token js2-IF)
8103 (setq guard-kwd (- js2-token-beg catch-pos)
8104 catch-cond (js2-parse-expr))
8105 (setq saw-default-catch t))
8106 (if (js2-must-match js2-RP "msg.bad.catchcond")
8107 (setq rp (- js2-token-beg catch-pos)))
8108 (js2-must-match js2-LC "msg.no.brace.catchblock")
8109 (setq block (js2-parse-statements)
8110 try-end (js2-node-end block)
8111 catch-node (make-js2-catch-node :pos catch-pos
8112 :param param
8113 :guard-expr catch-cond
8114 :guard-kwd guard-kwd
8115 :block block
8116 :lp lp
8117 :rp rp))
8118 (js2-pop-scope)
8119 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8120 (setq try-end js2-token-beg))
8121 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8122 (js2-node-len catch-node) (- try-end catch-pos))
8123 (js2-node-add-children catch-node param catch-cond block)
8124 (push catch-node catch-blocks)))
8125 ((/= peek js2-FINALLY)
8126 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8127 (js2-node-pos try-block)
8128 (- (setq try-end (js2-node-end try-block))
8129 (js2-node-pos try-block)))))
8130 (when (js2-match-token js2-FINALLY)
8131 (setq finally-pos js2-token-beg
8132 block (js2-parse-statement)
8133 try-end (js2-node-end block)
8134 finally-block (make-js2-finally-node :pos finally-pos
8135 :len (- try-end finally-pos)
8136 :body block))
8137 (js2-node-add-children finally-block block))
8138 (setq pn (make-js2-try-node :pos try-pos
8139 :len (- try-end try-pos)
8140 :try-block try-block
8141 :finally-block finally-block))
8142 (js2-node-add-children pn try-block finally-block)
8143 ;; push them onto the try-node, which reverses and corrects their order
8144 (dolist (cb catch-blocks)
8145 (js2-node-add-children pn cb)
8146 (push cb (js2-try-node-catch-clauses pn)))
8147 pn))
8148
8149 (defun js2-parse-throw ()
8150 "Parser for throw-statement. Last matched token must be js2-THROW."
8151 (let ((pos js2-token-beg)
8152 expr
8153 pn)
8154 (js2-consume-token)
8155 (if (= (js2-peek-token-or-eol) js2-EOL)
8156 ;; ECMAScript does not allow new lines before throw expression,
8157 ;; see bug 256617
8158 (js2-report-error "msg.bad.throw.eol"))
8159 (setq expr (js2-parse-expr)
8160 pn (make-js2-throw-node :pos pos
8161 :len (- (js2-node-end expr) pos)
8162 :expr expr))
8163 (js2-node-add-children pn expr)
8164 pn))
8165
8166 (defsubst js2-match-jump-label-name (label-name)
8167 "If break/continue specified a label, return that label's labeled stmt.
8168 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8169 does not match an existing label, reports an error and returns nil."
8170 (let ((bundle (cdr (assoc label-name js2-label-set))))
8171 (if (null bundle)
8172 (js2-report-error "msg.undef.label"))
8173 bundle))
8174
8175 (defun js2-parse-break ()
8176 "Parser for break-statement. Last matched token must be js2-BREAK."
8177 (let ((pos js2-token-beg)
8178 (end js2-token-end)
8179 break-target ; statement to break from
8180 break-label ; in "break foo", name-node representing the foo
8181 labels ; matching labeled statement to break to
8182 pn)
8183 (js2-consume-token) ; `break'
8184 (when (eq (js2-peek-token-or-eol) js2-NAME)
8185 (js2-consume-token)
8186 (setq break-label (js2-create-name-node)
8187 end (js2-node-end break-label)
8188 ;; matchJumpLabelName only matches if there is one
8189 labels (js2-match-jump-label-name js2-ts-string)
8190 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8191 (unless (or break-target break-label)
8192 ;; no break target specified - try for innermost enclosing loop/switch
8193 (if (null js2-loop-and-switch-set)
8194 (unless break-label
8195 (js2-report-error "msg.bad.break" nil pos (length "break")))
8196 (setq break-target (car js2-loop-and-switch-set))))
8197 (setq pn (make-js2-break-node :pos pos
8198 :len (- end pos)
8199 :label break-label
8200 :target break-target))
8201 (js2-node-add-children pn break-label) ; but not break-target
8202 pn))
8203
8204 (defun js2-parse-continue ()
8205 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8206 (let ((pos js2-token-beg)
8207 (end js2-token-end)
8208 label ; optional user-specified label, a `js2-name-node'
8209 labels ; current matching labeled stmt, if any
8210 target ; the `js2-loop-node' target of this continue stmt
8211 pn)
8212 (js2-consume-token) ; `continue'
8213 (when (= (js2-peek-token-or-eol) js2-NAME)
8214 (js2-consume-token)
8215 (setq label (js2-create-name-node)
8216 end (js2-node-end label)
8217 ;; matchJumpLabelName only matches if there is one
8218 labels (js2-match-jump-label-name js2-ts-string)))
8219 (cond
8220 ((null labels) ; no current label to go to
8221 (if (null js2-loop-set) ; no loop to continue to
8222 (js2-report-error "msg.continue.outside" nil pos
8223 (length "continue"))
8224 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8225 (t
8226 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8227 (setq target (js2-labeled-stmt-node-stmt labels))
8228 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8229 (setq pn (make-js2-continue-node :pos pos
8230 :len (- end pos)
8231 :label label
8232 :target target))
8233 (js2-node-add-children pn label) ; but not target - it's not our child
8234 pn))
8235
8236 (defun js2-parse-with ()
8237 "Parser for with-statement. Last matched token must be js2-WITH."
8238 (js2-consume-token)
8239 (let ((pos js2-token-beg)
8240 obj body pn lp rp)
8241 (if (js2-must-match js2-LP "msg.no.paren.with")
8242 (setq lp js2-token-beg))
8243 (setq obj (js2-parse-expr))
8244 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8245 (setq rp js2-token-beg))
8246 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8247 (setq body (js2-parse-statement)))
8248 (setq pn (make-js2-with-node :pos pos
8249 :len (- (js2-node-end body) pos)
8250 :object obj
8251 :body body
8252 :lp (js2-relpos lp pos)
8253 :rp (js2-relpos rp pos)))
8254 (js2-node-add-children pn obj body)
8255 pn))
8256
8257 (defun js2-parse-const-var ()
8258 "Parser for var- or const-statement.
8259 Last matched token must be js2-CONST or js2-VAR."
8260 (let ((tt (js2-peek-token))
8261 (pos js2-token-beg)
8262 expr
8263 pn)
8264 (js2-consume-token)
8265 (setq expr (js2-parse-variables tt js2-token-beg)
8266 pn (make-js2-expr-stmt-node :pos pos
8267 :len (- (js2-node-end expr) pos)
8268 :expr expr))
8269 (js2-node-add-children pn expr)
8270 pn))
8271
8272 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8273 (let ((pn (make-js2-expr-stmt-node :pos pos
8274 :len (js2-node-len expr)
8275 :type (if (js2-inside-function)
8276 js2-EXPR_VOID
8277 js2-EXPR_RESULT)
8278 :expr expr)))
8279 (if add-child
8280 (js2-node-add-children pn expr))
8281 pn))
8282
8283 (defun js2-parse-let-stmt ()
8284 "Parser for let-statement. Last matched token must be js2-LET."
8285 (js2-consume-token)
8286 (let ((pos js2-token-beg)
8287 expr
8288 pn)
8289 (if (= (js2-peek-token) js2-LP)
8290 ;; let expression in statement context
8291 (setq expr (js2-parse-let pos 'statement)
8292 pn (js2-wrap-with-expr-stmt pos expr t))
8293 ;; else we're looking at a statement like let x=6, y=7;
8294 (setf expr (js2-parse-variables js2-LET pos)
8295 pn (js2-wrap-with-expr-stmt pos expr t)
8296 (js2-node-type pn) js2-EXPR_RESULT))
8297 pn))
8298
8299 (defun js2-parse-ret-yield ()
8300 (js2-parse-return-or-yield (js2-peek-token) nil))
8301
8302 (defconst js2-parse-return-stmt-enders
8303 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8304
8305 (defsubst js2-now-all-set (before after mask)
8306 "Return whether or not the bits in the mask have changed to all set.
8307 BEFORE is bits before change, AFTER is bits after change, and MASK is
8308 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8309 but not BEFORE."
8310 (and (/= (logand before mask) mask)
8311 (= (logand after mask) mask)))
8312
8313 (defun js2-parse-return-or-yield (tt expr-context)
8314 (let ((pos js2-token-beg)
8315 (end js2-token-end)
8316 (before js2-end-flags)
8317 (inside-function (js2-inside-function))
8318 e
8319 ret
8320 name)
8321 (unless inside-function
8322 (js2-report-error (if (eq tt js2-RETURN)
8323 "msg.bad.return"
8324 "msg.bad.yield")))
8325 (js2-consume-token)
8326 ;; This is ugly, but we don't want to require a semicolon.
8327 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8328 (setq e (js2-parse-expr)
8329 end (js2-node-end e)))
8330 (cond
8331 ((eq tt js2-RETURN)
8332 (js2-set-flag js2-end-flags (if (null e)
8333 js2-end-returns
8334 js2-end-returns-value))
8335 (setq ret (make-js2-return-node :pos pos
8336 :len (- end pos)
8337 :retval e))
8338 (js2-node-add-children ret e)
8339 ;; See if we need a strict mode warning.
8340 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8341 ;; more thorough and accurate than this before/after flag check.
8342 ;; E.g. if there's a finally-block that always returns, we shouldn't
8343 ;; show a warning generated by inconsistent returns in the catch blocks.
8344 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8345 ;; so we know which returns/yields to highlight, and we should get rid of
8346 ;; all the checking in `js2-parse-return-or-yield'.
8347 (if (and js2-strict-inconsistent-return-warning
8348 (js2-now-all-set before js2-end-flags
8349 (logior js2-end-returns js2-end-returns-value)))
8350 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8351 (t
8352 (unless (js2-inside-function)
8353 (js2-report-error "msg.bad.yield"))
8354 (js2-set-flag js2-end-flags js2-end-yields)
8355 (setq ret (make-js2-yield-node :pos pos
8356 :len (- end pos)
8357 :value e))
8358 (js2-node-add-children ret e)
8359 (unless expr-context
8360 (setq e ret
8361 ret (js2-wrap-with-expr-stmt pos e t))
8362 (js2-set-requires-activation)
8363 (js2-set-is-generator))))
8364 ;; see if we are mixing yields and value returns.
8365 (when (and inside-function
8366 (js2-now-all-set before js2-end-flags
8367 (logior js2-end-yields js2-end-returns-value)))
8368 (setq name (js2-function-name js2-current-script-or-fn))
8369 (if (zerop (length name))
8370 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8371 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8372 ret))
8373
8374 (defun js2-parse-debugger ()
8375 (js2-consume-token)
8376 (make-js2-keyword-node :type js2-DEBUGGER))
8377
8378 (defun js2-parse-block ()
8379 "Parser for a curly-delimited statement block.
8380 Last token matched must be js2-LC."
8381 (let ((pos js2-token-beg)
8382 (pn (make-js2-scope)))
8383 (js2-consume-token)
8384 (js2-push-scope pn)
8385 (unwind-protect
8386 (progn
8387 (js2-parse-statements pn)
8388 (js2-must-match js2-RC "msg.no.brace.block")
8389 (setf (js2-node-len pn) (- js2-token-end pos)))
8390 (js2-pop-scope))
8391 pn))
8392
8393 ;; for js2-ERROR too, to have a node for error recovery to work on
8394 (defun js2-parse-semi ()
8395 "Parse a statement or handle an error.
8396 Last matched token is js2-SEMI or js2-ERROR."
8397 (let ((tt (js2-peek-token)) pos len)
8398 (js2-consume-token)
8399 (if (eq tt js2-SEMI)
8400 (make-js2-empty-expr-node :len 1)
8401 (setq pos js2-token-beg
8402 len (- js2-token-beg pos))
8403 (js2-report-error "msg.syntax" nil pos len)
8404 (make-js2-error-node :pos pos :len len))))
8405
8406 (defun js2-parse-default-xml-namespace ()
8407 "Parse a `default xml namespace = <expr>' e4x statement."
8408 (let ((pos js2-token-beg)
8409 end len expr unary es)
8410 (js2-consume-token)
8411 (js2-must-have-xml)
8412 (js2-set-requires-activation)
8413 (setq len (- js2-ts-cursor pos))
8414 (unless (and (js2-match-token js2-NAME)
8415 (string= js2-ts-string "xml"))
8416 (js2-report-error "msg.bad.namespace" nil pos len))
8417 (unless (and (js2-match-token js2-NAME)
8418 (string= js2-ts-string "namespace"))
8419 (js2-report-error "msg.bad.namespace" nil pos len))
8420 (unless (js2-match-token js2-ASSIGN)
8421 (js2-report-error "msg.bad.namespace" nil pos len))
8422 (setq expr (js2-parse-expr)
8423 end (js2-node-end expr)
8424 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8425 :pos pos
8426 :len (- end pos)
8427 :operand expr))
8428 (js2-node-add-children unary expr)
8429 (make-js2-expr-stmt-node :pos pos
8430 :len (- end pos)
8431 :expr unary)))
8432
8433 (defun js2-record-label (label bundle)
8434 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8435 (js2-consume-token)
8436 (let ((name (js2-label-node-name label))
8437 labeled-stmt
8438 dup)
8439 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8440 ;; flag both labels if possible when used in editing mode
8441 (if (and js2-parse-ide-mode
8442 (setq dup (js2-get-label-by-name labeled-stmt name)))
8443 (js2-report-error "msg.dup.label" nil
8444 (js2-node-abs-pos dup) (js2-node-len dup)))
8445 (js2-report-error "msg.dup.label" nil
8446 (js2-node-pos label) (js2-node-len label)))
8447 (js2-labeled-stmt-node-add-label bundle label)
8448 (js2-node-add-children bundle label)
8449 ;; Add one reference to the bundle per label in `js2-label-set'
8450 (push (cons name bundle) js2-label-set)))
8451
8452 (defun js2-parse-name-or-label ()
8453 "Parser for identifier or label. Last token matched must be js2-NAME.
8454 Called when we found a name in a statement context. If it's a label, we gather
8455 up any following labels and the next non-label statement into a
8456 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8457 expression and return it wrapped in a `js2-expr-stmt-node'."
8458 (let ((pos js2-token-beg)
8459 (end js2-token-end)
8460 expr
8461 stmt
8462 pn
8463 bundle
8464 (continue t))
8465 ;; set check for label and call down to `js2-parse-primary-expr'
8466 (js2-set-check-for-label)
8467 (setq expr (js2-parse-expr))
8468 (if (/= (js2-node-type expr) js2-LABEL)
8469 ;; Parsed non-label expression - wrap with expression stmt.
8470 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8471 ;; else parsed a label
8472 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8473 (js2-record-label expr bundle)
8474 ;; look for more labels
8475 (while (and continue (= (js2-peek-token) js2-NAME))
8476 (js2-set-check-for-label)
8477 (setq expr (js2-parse-expr))
8478 (if (/= (js2-node-type expr) js2-LABEL)
8479 (progn
8480 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8481 continue nil)
8482 (js2-auto-insert-semicolon stmt))
8483 (js2-record-label expr bundle)))
8484 ;; no more labels; now parse the labeled statement
8485 (unwind-protect
8486 (unless stmt
8487 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8488 (setq stmt (js2-statement-helper))))
8489 ;; remove the labels for this statement from the global set
8490 (dolist (label (js2-labeled-stmt-node-labels bundle))
8491 (setq js2-label-set (remove label js2-label-set))))
8492 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8493 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8494 (js2-node-add-children bundle stmt)
8495 bundle)))
8496
8497 (defun js2-parse-expr-stmt ()
8498 "Default parser in statement context, if no recognized statement found."
8499 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8500
8501 (defun js2-parse-variables (decl-type pos)
8502 "Parse a comma-separated list of variable declarations.
8503 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8504
8505 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8506 For 'var' or 'const', the keyword should be the token last scanned.
8507
8508 POS is the position where the node should start. It's sometimes the
8509 var/const/let keyword, and other times the beginning of the first token
8510 in the first variable declaration.
8511
8512 Returns the parsed `js2-var-decl-node' expression node."
8513 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8514 :pos pos))
8515 destructuring
8516 kid-pos
8517 tt
8518 init
8519 name
8520 end
8521 nbeg nend
8522 vi
8523 (continue t))
8524 ;; Example:
8525 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8526 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8527 ;; var {a, b} = baz;
8528 (while continue
8529 (setq destructuring nil
8530 name nil
8531 tt (js2-peek-token)
8532 kid-pos js2-token-beg
8533 end js2-token-end
8534 init nil)
8535 (if (or (= tt js2-LB) (= tt js2-LC))
8536 ;; Destructuring assignment, e.g., var [a, b] = ...
8537 (setq destructuring (js2-parse-destruct-primary-expr)
8538 end (js2-node-end destructuring))
8539 ;; Simple variable name
8540 (when (js2-must-match js2-NAME "msg.bad.var")
8541 (setq name (js2-create-name-node)
8542 nbeg js2-token-beg
8543 nend js2-token-end
8544 end nend)
8545 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8546 (when (js2-match-token js2-ASSIGN)
8547 (setq init (js2-parse-assign-expr)
8548 end (js2-node-end init))
8549 (js2-record-imenu-functions init name))
8550 (when name
8551 (js2-set-face nbeg nend (if (js2-function-node-p init)
8552 'font-lock-function-name-face
8553 'font-lock-variable-name-face)
8554 'record))
8555 (setq vi (make-js2-var-init-node :pos kid-pos
8556 :len (- end kid-pos)
8557 :type decl-type))
8558 (if destructuring
8559 (progn
8560 (if (and (null init) (not js2-in-for-init))
8561 (js2-report-error "msg.destruct.assign.no.init"))
8562 (js2-define-destruct-symbols destructuring
8563 decl-type
8564 'font-lock-variable-name-face)
8565 (setf (js2-var-init-node-target vi) destructuring))
8566 (setf (js2-var-init-node-target vi) name))
8567 (setf (js2-var-init-node-initializer vi) init)
8568 (js2-node-add-children vi name destructuring init)
8569 (js2-block-node-push result vi)
8570 (unless (js2-match-token js2-COMMA)
8571 (setq continue nil)))
8572 (setf (js2-node-len result) (- end pos))
8573 result))
8574
8575 (defun js2-parse-let (pos &optional stmt-p)
8576 "Parse a let expression or statement.
8577 A let-expression is of the form `let (vars) expr'.
8578 A let-statment is of the form `let (vars) {statements}'.
8579 The third form of let is a variable declaration list, handled
8580 by `js2-parse-variables'."
8581 (let ((pn (make-js2-let-node :pos pos))
8582 beg vars body)
8583 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8584 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8585 (js2-push-scope pn)
8586 (unwind-protect
8587 (progn
8588 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8589 (if (js2-must-match js2-RP "msg.no.paren.let")
8590 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8591 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8592 ;; let statement
8593 (progn
8594 (js2-consume-token)
8595 (setf beg js2-token-beg ; position stmt at LC
8596 body (js2-parse-statements))
8597 (js2-must-match js2-RC "msg.no.curly.let")
8598 (setf (js2-node-len body) (- js2-token-end beg)
8599 (js2-node-len pn) (- js2-token-end pos)
8600 (js2-let-node-body pn) body
8601 (js2-node-type pn) js2-LET))
8602 ;; let expression
8603 (setf body (js2-parse-expr)
8604 (js2-node-len pn) (- (js2-node-end body) pos)
8605 (js2-let-node-body pn) body))
8606 (js2-node-add-children pn vars body))
8607 (js2-pop-scope))
8608 pn))
8609
8610 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8611 (js2-scope-put-symbol (or scope js2-current-scope)
8612 name
8613 (make-js2-symbol decl-type name node)))
8614
8615 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8616 "Define a symbol in the current scope.
8617 If NODE is non-nil, it is the AST node associated with the symbol."
8618 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8619 (symbol (if defining-scope
8620 (js2-scope-get-symbol defining-scope name)))
8621 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8622 (cond
8623 ((and symbol ; already defined
8624 (or (= sdt js2-CONST) ; old version is const
8625 (= decl-type js2-CONST) ; new version is const
8626 ;; two let-bound vars in this block have same name
8627 (and (= sdt js2-LET)
8628 (eq defining-scope js2-current-scope))))
8629 (js2-report-error
8630 (cond
8631 ((= sdt js2-CONST) "msg.const.redecl")
8632 ((= sdt js2-LET) "msg.let.redecl")
8633 ((= sdt js2-VAR) "msg.var.redecl")
8634 ((= sdt js2-FUNCTION) "msg.function.redecl")
8635 (t "msg.parm.redecl"))
8636 name))
8637 ((= decl-type js2-LET)
8638 (if (and (not ignore-not-in-block)
8639 (or (= (js2-node-type js2-current-scope) js2-IF)
8640 (js2-loop-node-p js2-current-scope)))
8641 (js2-report-error "msg.let.decl.not.in.block")
8642 (js2-define-new-symbol decl-type name node)))
8643 ((or (= decl-type js2-VAR)
8644 (= decl-type js2-CONST)
8645 (= decl-type js2-FUNCTION))
8646 (if symbol
8647 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8648 (js2-add-strict-warning "msg.var.redecl" name)
8649 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8650 (js2-add-strict-warning "msg.var.hides.arg" name)))
8651 (js2-define-new-symbol decl-type name node
8652 js2-current-script-or-fn)))
8653 ((= decl-type js2-LP)
8654 (if symbol
8655 ;; must be duplicate parameter. Second parameter hides the
8656 ;; first, so go ahead and add the second pararameter
8657 (js2-report-warning "msg.dup.parms" name))
8658 (js2-define-new-symbol decl-type name node))
8659 (t (js2-code-bug)))))
8660
8661 (defun js2-parse-expr (&optional oneshot)
8662 (let* ((pn (js2-parse-assign-expr))
8663 (pos (js2-node-pos pn))
8664 left
8665 right
8666 op-pos)
8667 (while (and (not oneshot)
8668 (js2-match-token js2-COMMA))
8669 (setq op-pos (- js2-token-beg pos)) ; relative
8670 (if (= (js2-peek-token) js2-YIELD)
8671 (js2-report-error "msg.yield.parenthesized"))
8672 (setq right (js2-parse-assign-expr)
8673 left pn
8674 pn (make-js2-infix-node :type js2-COMMA
8675 :pos pos
8676 :len (- js2-ts-cursor pos)
8677 :op-pos op-pos
8678 :left left
8679 :right right))
8680 (js2-node-add-children pn left right))
8681 pn))
8682
8683 (defun js2-parse-assign-expr ()
8684 (let ((tt (js2-peek-token))
8685 (pos js2-token-beg)
8686 pn
8687 left
8688 right
8689 op-pos)
8690 (if (= tt js2-YIELD)
8691 (js2-parse-return-or-yield tt t)
8692 ;; not yield - parse assignment expression
8693 (setq pn (js2-parse-cond-expr)
8694 tt (js2-peek-token))
8695 (when (and (<= js2-first-assign tt)
8696 (<= tt js2-last-assign))
8697 ;; tt express assignment (=, |=, ^=, ..., %=)
8698 (js2-consume-token)
8699 (setq op-pos (- js2-token-beg pos) ; relative
8700 left pn
8701 right (js2-parse-assign-expr)
8702 pn (make-js2-assign-node :type tt
8703 :pos pos
8704 :len (- (js2-node-end right) pos)
8705 :op-pos op-pos
8706 :left left
8707 :right right))
8708 (when js2-parse-ide-mode
8709 (js2-highlight-assign-targets pn left right)
8710 (js2-record-imenu-functions right left))
8711 ;; do this last so ide checks above can use absolute positions
8712 (js2-node-add-children pn left right))
8713 pn)))
8714
8715 (defun js2-parse-cond-expr ()
8716 (let ((pos js2-token-beg)
8717 (pn (js2-parse-or-expr))
8718 test-expr
8719 if-true
8720 if-false
8721 q-pos
8722 c-pos)
8723 (when (js2-match-token js2-HOOK)
8724 (setq q-pos (- js2-token-beg pos)
8725 if-true (js2-parse-assign-expr))
8726 (js2-must-match js2-COLON "msg.no.colon.cond")
8727 (setq c-pos (- js2-token-beg pos)
8728 if-false (js2-parse-assign-expr)
8729 test-expr pn
8730 pn (make-js2-cond-node :pos pos
8731 :len (- (js2-node-end if-false) pos)
8732 :test-expr test-expr
8733 :true-expr if-true
8734 :false-expr if-false
8735 :q-pos q-pos
8736 :c-pos c-pos))
8737 (js2-node-add-children pn test-expr if-true if-false))
8738 pn))
8739
8740 (defun js2-make-binary (type left parser)
8741 "Helper for constructing a binary-operator AST node.
8742 LEFT is the left-side-expression, already parsed, and the
8743 binary operator should have just been matched.
8744 PARSER is a function to call to parse the right operand,
8745 or a `js2-node' struct if it has already been parsed."
8746 (let* ((pos (js2-node-pos left))
8747 (op-pos (- js2-token-beg pos))
8748 (right (if (js2-node-p parser)
8749 parser
8750 (funcall parser)))
8751 (pn (make-js2-infix-node :type type
8752 :pos pos
8753 :len (- (js2-node-end right) pos)
8754 :op-pos op-pos
8755 :left left
8756 :right right)))
8757 (js2-node-add-children pn left right)
8758 pn))
8759
8760 (defun js2-parse-or-expr ()
8761 (let ((pn (js2-parse-and-expr)))
8762 (when (js2-match-token js2-OR)
8763 (setq pn (js2-make-binary js2-OR
8764 pn
8765 'js2-parse-or-expr)))
8766 pn))
8767
8768 (defun js2-parse-and-expr ()
8769 (let ((pn (js2-parse-bit-or-expr)))
8770 (when (js2-match-token js2-AND)
8771 (setq pn (js2-make-binary js2-AND
8772 pn
8773 'js2-parse-and-expr)))
8774 pn))
8775
8776 (defun js2-parse-bit-or-expr ()
8777 (let ((pn (js2-parse-bit-xor-expr)))
8778 (while (js2-match-token js2-BITOR)
8779 (setq pn (js2-make-binary js2-BITOR
8780 pn
8781 'js2-parse-bit-xor-expr)))
8782 pn))
8783
8784 (defun js2-parse-bit-xor-expr ()
8785 (let ((pn (js2-parse-bit-and-expr)))
8786 (while (js2-match-token js2-BITXOR)
8787 (setq pn (js2-make-binary js2-BITXOR
8788 pn
8789 'js2-parse-bit-and-expr)))
8790 pn))
8791
8792 (defun js2-parse-bit-and-expr ()
8793 (let ((pn (js2-parse-eq-expr)))
8794 (while (js2-match-token js2-BITAND)
8795 (setq pn (js2-make-binary js2-BITAND
8796 pn
8797 'js2-parse-eq-expr)))
8798 pn))
8799
8800 (defconst js2-parse-eq-ops
8801 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8802
8803 (defun js2-parse-eq-expr ()
8804 (let ((pn (js2-parse-rel-expr))
8805 tt)
8806 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8807 (js2-consume-token)
8808 (setq pn (js2-make-binary tt
8809 pn
8810 'js2-parse-rel-expr)))
8811 pn))
8812
8813 (defconst js2-parse-rel-ops
8814 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8815
8816 (defun js2-parse-rel-expr ()
8817 (let ((pn (js2-parse-shift-expr))
8818 (continue t)
8819 tt)
8820 (while continue
8821 (setq tt (js2-peek-token))
8822 (cond
8823 ((and js2-in-for-init (= tt js2-IN))
8824 (setq continue nil))
8825 ((memq tt js2-parse-rel-ops)
8826 (js2-consume-token)
8827 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8828 (t
8829 (setq continue nil))))
8830 pn))
8831
8832 (defconst js2-parse-shift-ops
8833 (list js2-LSH js2-URSH js2-RSH))
8834
8835 (defun js2-parse-shift-expr ()
8836 (let ((pn (js2-parse-add-expr))
8837 tt
8838 (continue t))
8839 (while continue
8840 (setq tt (js2-peek-token))
8841 (if (memq tt js2-parse-shift-ops)
8842 (progn
8843 (js2-consume-token)
8844 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8845 (setq continue nil)))
8846 pn))
8847
8848 (defun js2-parse-add-expr ()
8849 (let ((pn (js2-parse-mul-expr))
8850 tt
8851 (continue t))
8852 (while continue
8853 (setq tt (js2-peek-token))
8854 (if (or (= tt js2-ADD) (= tt js2-SUB))
8855 (progn
8856 (js2-consume-token)
8857 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8858 (setq continue nil)))
8859 pn))
8860
8861 (defconst js2-parse-mul-ops
8862 (list js2-MUL js2-DIV js2-MOD))
8863
8864 (defun js2-parse-mul-expr ()
8865 (let ((pn (js2-parse-unary-expr))
8866 tt
8867 (continue t))
8868 (while continue
8869 (setq tt (js2-peek-token))
8870 (if (memq tt js2-parse-mul-ops)
8871 (progn
8872 (js2-consume-token)
8873 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8874 (setq continue nil)))
8875 pn))
8876
8877 (defsubst js2-make-unary (type parser &rest args)
8878 "Make a unary node of type TYPE.
8879 PARSER is either a node (for postfix operators) or a function to call
8880 to parse the operand (for prefix operators)."
8881 (let* ((pos js2-token-beg)
8882 (postfix (js2-node-p parser))
8883 (expr (if postfix
8884 parser
8885 (apply parser args)))
8886 end
8887 pn)
8888 (if postfix ; e.g. i++
8889 (setq pos (js2-node-pos expr)
8890 end js2-token-end)
8891 (setq end (js2-node-end expr)))
8892 (setq pn (make-js2-unary-node :type type
8893 :pos pos
8894 :len (- end pos)
8895 :operand expr))
8896 (js2-node-add-children pn expr)
8897 pn))
8898
8899 (defconst js2-incrementable-node-types
8900 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8901 "Node types that can be the operand of a ++ or -- operator.")
8902
8903 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8904 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8905 js2-incrementable-node-types)
8906 (js2-report-error (if (= tt js2-INC)
8907 "msg.bad.incr"
8908 "msg.bad.decr")
8909 nil beg (- end beg))))
8910
8911 (defun js2-parse-unary-expr ()
8912 (let ((tt (js2-peek-token))
8913 pn expr beg end)
8914 (cond
8915 ((or (= tt js2-VOID)
8916 (= tt js2-NOT)
8917 (= tt js2-BITNOT)
8918 (= tt js2-TYPEOF))
8919 (js2-consume-token)
8920 (js2-make-unary tt 'js2-parse-unary-expr))
8921 ((= tt js2-ADD)
8922 (js2-consume-token)
8923 ;; Convert to special POS token in decompiler and parse tree
8924 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8925 ((= tt js2-SUB)
8926 (js2-consume-token)
8927 ;; Convert to special NEG token in decompiler and parse tree
8928 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8929 ((or (= tt js2-INC)
8930 (= tt js2-DEC))
8931 (js2-consume-token)
8932 (prog1
8933 (setq beg js2-token-beg
8934 end js2-token-end
8935 expr (js2-make-unary tt 'js2-parse-member-expr t))
8936 (js2-check-bad-inc-dec tt beg end expr)))
8937 ((= tt js2-DELPROP)
8938 (js2-consume-token)
8939 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8940 ((= tt js2-ERROR)
8941 (js2-consume-token)
8942 (make-js2-error-node)) ; try to continue
8943 ((and (= tt js2-LT)
8944 js2-compiler-xml-available)
8945 ;; XML stream encountered in expression.
8946 (js2-consume-token)
8947 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8948 (t
8949 (setq pn (js2-parse-member-expr t)
8950 ;; Don't look across a newline boundary for a postfix incop.
8951 tt (js2-peek-token-or-eol))
8952 (when (or (= tt js2-INC) (= tt js2-DEC))
8953 (js2-consume-token)
8954 (setf expr pn
8955 pn (js2-make-unary tt expr))
8956 (js2-node-set-prop pn 'postfix t)
8957 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8958 pn))))
8959
8960 (defun js2-parse-xml-initializer ()
8961 "Parse an E4X XML initializer.
8962 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8963 Then I'll postprocess the result, depending on whether we're in IDE
8964 mode or codegen mode, and generate the appropriate rewritten AST.
8965 IDE mode uses a rich AST that models the XML structure. Codegen mode
8966 just concatenates everything and makes a new XML or XMLList out of it."
8967 (let ((tt (js2-get-first-xml-token))
8968 pn-xml
8969 pn
8970 expr
8971 kids
8972 expr-pos
8973 (continue t)
8974 (first-token t))
8975 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8976 (js2-report-error "msg.syntax"))
8977 (setq pn-xml (make-js2-xml-node))
8978 (while continue
8979 (if first-token
8980 (setq first-token nil)
8981 (setq tt (js2-get-next-xml-token)))
8982 (cond
8983 ;; js2-XML means we found a {expr} in the XML stream.
8984 ;; The js2-ts-string is the XML up to the left-curly.
8985 ((= tt js2-XML)
8986 (push (make-js2-string-node :pos js2-token-beg
8987 :len (- js2-ts-cursor js2-token-beg))
8988 kids)
8989 (js2-must-match js2-LC "msg.syntax")
8990 (setq expr-pos js2-ts-cursor
8991 expr (if (eq (js2-peek-token) js2-RC)
8992 (make-js2-empty-expr-node :pos expr-pos)
8993 (js2-parse-expr)))
8994 (js2-must-match js2-RC "msg.syntax")
8995 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8996 :len (js2-node-len expr)
8997 :expr expr))
8998 (js2-node-add-children pn expr)
8999 (push pn kids))
9000 ;; a js2-XMLEND token means we hit the final close-tag.
9001 ((= tt js2-XMLEND)
9002 (push (make-js2-string-node :pos js2-token-beg
9003 :len (- js2-ts-cursor js2-token-beg))
9004 kids)
9005 (dolist (kid (nreverse kids))
9006 (js2-block-node-push pn-xml kid))
9007 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9008 (js2-node-pos pn-xml))
9009 continue nil))
9010 (t
9011 (js2-report-error "msg.syntax")
9012 (setq continue nil))))
9013 pn-xml))
9014
9015
9016 (defun js2-parse-argument-list ()
9017 "Parse an argument list and return it as a lisp list of nodes.
9018 Returns the list in reverse order. Consumes the right-paren token."
9019 (let (result)
9020 (unless (js2-match-token js2-RP)
9021 (loop do
9022 (if (= (js2-peek-token) js2-YIELD)
9023 (js2-report-error "msg.yield.parenthesized"))
9024 (push (js2-parse-assign-expr) result)
9025 while
9026 (js2-match-token js2-COMMA))
9027 (js2-must-match js2-RP "msg.no.paren.arg")
9028 result)))
9029
9030 (defun js2-parse-member-expr (&optional allow-call-syntax)
9031 (let ((tt (js2-peek-token))
9032 pn
9033 pos
9034 target
9035 args
9036 beg
9037 end
9038 init
9039 tail)
9040 (if (/= tt js2-NEW)
9041 (setq pn (js2-parse-primary-expr))
9042 ;; parse a 'new' expression
9043 (js2-consume-token)
9044 (setq pos js2-token-beg
9045 beg pos
9046 target (js2-parse-member-expr)
9047 end (js2-node-end target)
9048 pn (make-js2-new-node :pos pos
9049 :target target
9050 :len (- end pos)))
9051 (js2-node-add-children pn target)
9052 (when (js2-match-token js2-LP)
9053 ;; Add the arguments to pn, if any are supplied.
9054 (setf beg pos ; start of "new" keyword
9055 pos js2-token-beg
9056 args (nreverse (js2-parse-argument-list))
9057 (js2-new-node-args pn) args
9058 end js2-token-end
9059 (js2-new-node-lp pn) (- pos beg)
9060 (js2-new-node-rp pn) (- end 1 beg))
9061 (apply #'js2-node-add-children pn args))
9062 (when (and js2-allow-rhino-new-expr-initializer
9063 (js2-match-token js2-LC))
9064 (setf init (js2-parse-object-literal)
9065 end (js2-node-end init)
9066 (js2-new-node-initializer pn) init)
9067 (js2-node-add-children pn init))
9068 (setf (js2-node-len pn) (- end beg))) ; end outer if
9069 (js2-parse-member-expr-tail allow-call-syntax pn)))
9070
9071 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9072 "Parse a chain of property/array accesses or function calls.
9073 Includes parsing for E4X operators like `..' and `.@'.
9074 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9075 Returns an expression tree that includes PN, the parent node."
9076 (let ((beg (js2-node-pos pn))
9077 tt
9078 (continue t))
9079 (while continue
9080 (setq tt (js2-peek-token))
9081 (cond
9082 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9083 (setq pn (js2-parse-property-access tt pn)))
9084 ((= tt js2-DOTQUERY)
9085 (setq pn (js2-parse-dot-query pn)))
9086 ((= tt js2-LB)
9087 (setq pn (js2-parse-element-get pn)))
9088 ((= tt js2-LP)
9089 (if allow-call-syntax
9090 (setq pn (js2-parse-function-call pn))
9091 (setq continue nil)))
9092 (t
9093 (setq continue nil))))
9094 (if (>= js2-highlight-level 2)
9095 (js2-parse-highlight-member-expr-node pn))
9096 pn))
9097
9098 (defun js2-parse-dot-query (pn)
9099 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9100 Last token parsed must be `js2-DOTQUERY'."
9101 (let ((pos (js2-node-pos pn))
9102 op-pos
9103 expr
9104 end)
9105 (js2-consume-token)
9106 (js2-must-have-xml)
9107 (js2-set-requires-activation)
9108 (setq op-pos js2-token-beg
9109 expr (js2-parse-expr)
9110 end (js2-node-end expr)
9111 pn (make-js2-xml-dot-query-node :left pn
9112 :pos pos
9113 :op-pos op-pos
9114 :right expr))
9115 (js2-node-add-children pn
9116 (js2-xml-dot-query-node-left pn)
9117 (js2-xml-dot-query-node-right pn))
9118 (if (js2-must-match js2-RP "msg.no.paren")
9119 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9120 end js2-token-end))
9121 (setf (js2-node-len pn) (- end pos))
9122 pn))
9123
9124 (defun js2-parse-element-get (pn)
9125 "Parse an element-get expression, e.g. foo[bar].
9126 Last token parsed must be `js2-RB'."
9127 (let ((lb js2-token-beg)
9128 (pos (js2-node-pos pn))
9129 rb
9130 expr)
9131 (js2-consume-token)
9132 (setq expr (js2-parse-expr))
9133 (if (js2-must-match js2-RB "msg.no.bracket.index")
9134 (setq rb js2-token-beg))
9135 (setq pn (make-js2-elem-get-node :target pn
9136 :pos pos
9137 :element expr
9138 :lb (js2-relpos lb pos)
9139 :rb (js2-relpos rb pos)
9140 :len (- js2-token-end pos)))
9141 (js2-node-add-children pn
9142 (js2-elem-get-node-target pn)
9143 (js2-elem-get-node-element pn))
9144 pn))
9145
9146 (defun js2-parse-function-call (pn)
9147 (let (args
9148 (pos (js2-node-pos pn)))
9149 (js2-consume-token)
9150 (setq pn (make-js2-call-node :pos pos
9151 :target pn
9152 :lp (- js2-token-beg pos)))
9153 (js2-node-add-children pn (js2-call-node-target pn))
9154 ;; Add the arguments to pn, if any are supplied.
9155 (setf args (nreverse (js2-parse-argument-list))
9156 (js2-call-node-rp pn) (- js2-token-beg pos)
9157 (js2-call-node-args pn) args)
9158 (apply #'js2-node-add-children pn args)
9159 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9160 pn))
9161
9162 (defun js2-parse-property-access (tt pn)
9163 "Parse a property access, XML descendants access, or XML attr access."
9164 (let ((member-type-flags 0)
9165 (dot-pos js2-token-beg)
9166 (dot-len (if (= tt js2-DOTDOT) 2 1))
9167 name
9168 ref ; right side of . or .. operator
9169 result)
9170 (js2-consume-token)
9171 (when (= tt js2-DOTDOT)
9172 (js2-must-have-xml)
9173 (setq member-type-flags js2-descendants-flag))
9174 (if (not js2-compiler-xml-available)
9175 (progn
9176 (js2-must-match-prop-name "msg.no.name.after.dot")
9177 (setq name (js2-create-name-node t js2-GETPROP)
9178 result (make-js2-prop-get-node :left pn
9179 :pos js2-token-beg
9180 :right name
9181 :len (- js2-token-end
9182 js2-token-beg)))
9183 (js2-node-add-children result pn name)
9184 result)
9185 ;; otherwise look for XML operators
9186 (setf result (if (= tt js2-DOT)
9187 (make-js2-prop-get-node)
9188 (make-js2-infix-node :type js2-DOTDOT))
9189 (js2-node-pos result) (js2-node-pos pn)
9190 (js2-infix-node-op-pos result) dot-pos
9191 (js2-infix-node-left result) pn ; do this after setting position
9192 tt (js2-next-token))
9193 (cond
9194 ;; needed for generator.throw()
9195 ((= tt js2-THROW)
9196 (js2-save-name-token-data js2-token-beg "throw")
9197 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9198 ;; handles: name, ns::name, ns::*, ns::[expr]
9199 ((js2-valid-prop-name-token tt)
9200 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9201 ;; handles: *, *::name, *::*, *::[expr]
9202 ((= tt js2-MUL)
9203 (js2-save-name-token-data js2-token-beg "*")
9204 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9205 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9206 ((= tt js2-XMLATTR)
9207 (setq result (js2-parse-attribute-access)))
9208 (t
9209 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9210 (if ref
9211 (setf (js2-node-len result) (- (js2-node-end ref)
9212 (js2-node-pos result))
9213 (js2-infix-node-right result) ref))
9214 (if (js2-infix-node-p result)
9215 (js2-node-add-children result
9216 (js2-infix-node-left result)
9217 (js2-infix-node-right result)))
9218 result)))
9219
9220 (defun js2-parse-attribute-access ()
9221 "Parse an E4X XML attribute expression.
9222 This includes expressions of the forms:
9223
9224 @attr @ns::attr @ns::*
9225 @* @*::attr @*::*
9226 @[expr] @*::[expr] @ns::[expr]
9227
9228 Called if we peeked an '@' token."
9229 (let ((tt (js2-next-token))
9230 (at-pos js2-token-beg))
9231 (cond
9232 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9233 ((js2-valid-prop-name-token tt)
9234 (js2-parse-property-name at-pos js2-ts-string 0))
9235 ;; handles: @*, @*::name, @*::*, @*::[expr]
9236 ((= tt js2-MUL)
9237 (js2-save-name-token-data js2-token-beg "*")
9238 (js2-parse-property-name js2-token-beg "*" 0))
9239 ;; handles @[expr]
9240 ((= tt js2-LB)
9241 (js2-parse-xml-elem-ref at-pos))
9242 (t
9243 (js2-report-error "msg.no.name.after.xmlAttr")
9244 ;; Avoid cascaded errors that happen if we make an error node here.
9245 (js2-save-name-token-data js2-token-beg "")
9246 (js2-parse-property-name js2-token-beg "" 0)))))
9247
9248 (defun js2-parse-property-name (at-pos s member-type-flags)
9249 "Check if :: follows name in which case it becomes qualified name.
9250
9251 AT-POS is a natural number if we just read an '@' token, else nil.
9252 S is the name or string that was matched: an identifier, 'throw' or '*'.
9253 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9254
9255 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9256 operator, or the name is followed by ::. For a plain name, returns a
9257 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9258 (let ((pos (or at-pos js2-token-beg))
9259 colon-pos
9260 (name (js2-create-name-node t js2-current-token))
9261 ns
9262 tt
9263 ref
9264 pn)
9265 (catch 'return
9266 (when (js2-match-token js2-COLONCOLON)
9267 (setq ns name
9268 colon-pos js2-token-beg
9269 tt (js2-next-token))
9270 (cond
9271 ;; handles name::name
9272 ((js2-valid-prop-name-token tt)
9273 (setq name (js2-create-name-node)))
9274 ;; handles name::*
9275 ((= tt js2-MUL)
9276 (js2-save-name-token-data js2-token-beg "*")
9277 (setq name (js2-create-name-node)))
9278 ;; handles name::[expr]
9279 ((= tt js2-LB)
9280 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9281 (t
9282 (js2-report-error "msg.no.name.after.coloncolon"))))
9283 (if (and (null ns) (zerop member-type-flags))
9284 name
9285 (prog1
9286 (setq pn
9287 (make-js2-xml-prop-ref-node :pos pos
9288 :len (- (js2-node-end name) pos)
9289 :at-pos at-pos
9290 :colon-pos colon-pos
9291 :propname name))
9292 (js2-node-add-children pn name))))))
9293
9294 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9295 "Parse the [expr] portion of an xml element reference.
9296 For instance, @[expr], @*::[expr], or ns::[expr]."
9297 (let* ((lb js2-token-beg)
9298 (pos (or at-pos lb))
9299 rb
9300 (expr (js2-parse-expr))
9301 (end (js2-node-end expr))
9302 pn)
9303 (if (js2-must-match js2-RB "msg.no.bracket.index")
9304 (setq rb js2-token-beg
9305 end js2-token-end))
9306 (prog1
9307 (setq pn
9308 (make-js2-xml-elem-ref-node :pos pos
9309 :len (- end pos)
9310 :namespace namespace
9311 :colon-pos colon-pos
9312 :at-pos at-pos
9313 :expr expr
9314 :lb (js2-relpos lb pos)
9315 :rb (js2-relpos rb pos)))
9316 (js2-node-add-children pn namespace expr))))
9317
9318 (defun js2-parse-destruct-primary-expr ()
9319 (let ((js2-is-in-destructuring t))
9320 (js2-parse-primary-expr)))
9321
9322 (defun js2-parse-primary-expr ()
9323 "Parses a literal (leaf) expression of some sort.
9324 Includes complex literals such as functions, object-literals,
9325 array-literals, array comprehensions and regular expressions."
9326 (let ((tt-flagged (js2-next-flagged-token))
9327 pn ; parent node (usually return value)
9328 tt
9329 px-pos ; paren-expr pos
9330 len
9331 flags ; regexp flags
9332 expr)
9333 (setq tt js2-current-token)
9334 (cond
9335 ((= tt js2-FUNCTION)
9336 (js2-parse-function 'FUNCTION_EXPRESSION))
9337 ((= tt js2-LB)
9338 (js2-parse-array-literal))
9339 ((= tt js2-LC)
9340 (js2-parse-object-literal))
9341 ((= tt js2-LET)
9342 (js2-parse-let js2-token-beg))
9343 ((= tt js2-LP)
9344 (setq px-pos js2-token-beg
9345 expr (js2-parse-expr))
9346 (js2-must-match js2-RP "msg.no.paren")
9347 (setq pn (make-js2-paren-node :pos px-pos
9348 :expr expr
9349 :len (- js2-token-end px-pos)))
9350 (js2-node-add-children pn (js2-paren-node-expr pn))
9351 pn)
9352 ((= tt js2-XMLATTR)
9353 (js2-must-have-xml)
9354 (js2-parse-attribute-access))
9355 ((= tt js2-NAME)
9356 (js2-parse-name tt-flagged tt))
9357 ((= tt js2-NUMBER)
9358 (make-js2-number-node))
9359 ((= tt js2-STRING)
9360 (prog1
9361 (make-js2-string-node)
9362 (js2-record-face 'font-lock-string-face)))
9363 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9364 ;; Got / or /= which in this context means a regexp literal
9365 (setq px-pos js2-token-beg)
9366 (js2-read-regexp tt)
9367 (setq flags js2-ts-regexp-flags
9368 js2-ts-regexp-flags nil)
9369 (prog1
9370 (make-js2-regexp-node :pos px-pos
9371 :len (- js2-ts-cursor px-pos)
9372 :value js2-ts-string
9373 :flags flags)
9374 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9375 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9376 ((or (= tt js2-NULL)
9377 (= tt js2-THIS)
9378 (= tt js2-FALSE)
9379 (= tt js2-TRUE))
9380 (make-js2-keyword-node :type tt))
9381 ((= tt js2-RESERVED)
9382 (js2-report-error "msg.reserved.id")
9383 (make-js2-name-node))
9384 ((= tt js2-ERROR)
9385 ;; the scanner or one of its subroutines reported the error.
9386 (make-js2-error-node))
9387 ((= tt js2-EOF)
9388 (setq px-pos (point-at-bol)
9389 len (- js2-ts-cursor px-pos))
9390 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9391 (make-js2-error-node :pos px-pos :len len))
9392 (t
9393 (js2-report-error "msg.syntax")
9394 (make-js2-error-node)))))
9395
9396 (defun js2-parse-name (tt-flagged tt)
9397 (let ((name js2-ts-string)
9398 (name-pos js2-token-beg)
9399 node)
9400 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9401 (= (js2-peek-token) js2-COLON))
9402 (prog1
9403 ;; Do not consume colon, it is used as unwind indicator
9404 ;; to return to statementHelper.
9405 (make-js2-label-node :pos name-pos
9406 :len (- js2-token-end name-pos)
9407 :name name)
9408 (js2-set-face name-pos
9409 js2-token-end
9410 'font-lock-variable-name-face 'record))
9411 ;; Otherwise not a label, just a name. Unfortunately peeking
9412 ;; the next token to check for a colon has biffed js2-token-beg
9413 ;; and js2-token-end. We store the name's bounds in buffer vars
9414 ;; and `js2-create-name-node' uses them.
9415 (js2-save-name-token-data name-pos name)
9416 (setq node (if js2-compiler-xml-available
9417 (js2-parse-property-name nil name 0)
9418 (js2-create-name-node 'check-activation)))
9419 (if js2-highlight-external-variables
9420 (js2-record-name-node node))
9421 node)))
9422
9423 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9424 (js2-add-strict-warning
9425 msg nil
9426 ;; back up from comma to beginning of line or array/objlit
9427 (max (if elems
9428 (js2-node-pos (car elems))
9429 pos)
9430 (save-excursion
9431 (goto-char comma-pos)
9432 (back-to-indentation)
9433 (point)))
9434 comma-pos))
9435
9436 (defun js2-parse-array-literal ()
9437 (let ((pos js2-token-beg)
9438 (end js2-token-end)
9439 (after-lb-or-comma t)
9440 after-comma
9441 tt
9442 elems
9443 pn
9444 (continue t))
9445 (unless js2-is-in-destructuring
9446 (js2-push-scope (make-js2-scope))) ; for array comp
9447 (while continue
9448 (setq tt (js2-peek-token))
9449 (cond
9450 ;; comma
9451 ((= tt js2-COMMA)
9452 (js2-consume-token)
9453 (setq after-comma js2-token-end)
9454 (if (not after-lb-or-comma)
9455 (setq after-lb-or-comma t)
9456 (push nil elems)))
9457 ;; end of array
9458 ((or (= tt js2-RB)
9459 (= tt js2-EOF)) ; prevent infinite loop
9460 (if (= tt js2-EOF)
9461 (js2-report-error "msg.no.bracket.arg" nil pos)
9462 (js2-consume-token))
9463 (setq continue nil
9464 end js2-token-end
9465 pn (make-js2-array-node :pos pos
9466 :len (- js2-ts-cursor pos)
9467 :elems (nreverse elems)))
9468 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9469 (when (and after-comma (not js2-is-in-destructuring))
9470 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9471 pos elems after-comma)))
9472 ;; destructuring binding
9473 (js2-is-in-destructuring
9474 (push (if (or (= tt js2-LC)
9475 (= tt js2-LB)
9476 (= tt js2-NAME))
9477 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9478 (js2-parse-destruct-primary-expr)
9479 ;; invalid pattern
9480 (js2-consume-token)
9481 (js2-report-error "msg.bad.var")
9482 (make-js2-error-node))
9483 elems)
9484 (setq after-lb-or-comma nil
9485 after-comma nil))
9486 ;; array comp
9487 ((and (>= js2-language-version 170)
9488 (= tt js2-FOR) ; check for array comprehension
9489 (not after-lb-or-comma) ; "for" can't follow a comma
9490 elems ; must have at least 1 element
9491 (not (cdr elems))) ; but no 2nd element
9492 (setf continue nil
9493 pn (js2-parse-array-comprehension (car elems) pos)))
9494
9495 ;; another element
9496 (t
9497 (unless after-lb-or-comma
9498 (js2-report-error "msg.no.bracket.arg"))
9499 (push (js2-parse-assign-expr) elems)
9500 (setq after-lb-or-comma nil
9501 after-comma nil))))
9502 (unless js2-is-in-destructuring
9503 (js2-pop-scope))
9504 pn))
9505
9506 (defun js2-parse-array-comprehension (expr pos)
9507 "Parse a JavaScript 1.7 Array Comprehension.
9508 EXPR is the first expression after the opening left-bracket.
9509 POS is the beginning of the LB token preceding EXPR.
9510 We should have just parsed the 'for' keyword before calling this function."
9511 (let (loops
9512 loop
9513 first
9514 prev
9515 filter
9516 if-pos
9517 result)
9518 (while (= (js2-peek-token) js2-FOR)
9519 (let ((prev (car loops))) ; rearrange scope chain
9520 (push (setq loop (js2-parse-array-comp-loop)) loops)
9521 (if prev ; each loop is parent scope to the next one
9522 (setf (js2-scope-parent-scope loop) prev)
9523 ; first loop takes expr scope's parent
9524 (setf (js2-scope-parent-scope (setq first loop))
9525 (js2-scope-parent-scope js2-current-scope)))))
9526 ;; set expr scope's parent to the last loop
9527 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9528 (when (= (js2-peek-token) js2-IF)
9529 (js2-consume-token)
9530 (setq if-pos (- js2-token-beg pos) ; relative
9531 filter (js2-parse-condition)))
9532 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9533 (setq result (make-js2-array-comp-node :pos pos
9534 :len (- js2-ts-cursor pos)
9535 :result expr
9536 :loops (nreverse loops)
9537 :filter (car filter)
9538 :lp (js2-relpos (second filter) pos)
9539 :rp (js2-relpos (third filter) pos)
9540 :if-pos if-pos))
9541 (apply #'js2-node-add-children result expr (car filter)
9542 (js2-array-comp-node-loops result))
9543 (setq js2-current-scope first) ; pop to the first loop
9544 result))
9545
9546 (defun js2-parse-array-comp-loop ()
9547 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9548 Last token peeked should be the initial FOR."
9549 (let ((pos js2-token-beg)
9550 (pn (make-js2-array-comp-loop-node))
9551 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9552 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9553 (js2-push-scope pn)
9554 (unwind-protect
9555 (progn
9556 (when (js2-match-token js2-NAME)
9557 (if (string= js2-ts-string "each")
9558 (progn
9559 (setq foreach-p t
9560 each-pos (- js2-token-beg pos)) ; relative
9561 (js2-record-face 'font-lock-keyword-face))
9562 (js2-report-error "msg.no.paren.for")))
9563 (if (js2-must-match js2-LP "msg.no.paren.for")
9564 (setq lp (- js2-token-beg pos)))
9565 (setq tt (js2-peek-token))
9566 (cond
9567 ((or (= tt js2-LB)
9568 (= tt js2-LC))
9569 (setq iter (js2-parse-destruct-primary-expr))
9570 (js2-define-destruct-symbols iter js2-LET
9571 'font-lock-variable-name-face t))
9572 ((js2-match-token js2-NAME)
9573 (setq iter (js2-create-name-node)))
9574 (t
9575 (js2-report-error "msg.bad.var")))
9576 ;; Define as a let since we want the scope of the variable to
9577 ;; be restricted to the array comprehension
9578 (if (js2-name-node-p iter)
9579 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9580 (if (or (js2-match-token js2-IN)
9581 (and (>= js2-language-version 200)
9582 (js2-match-contextual-kwd "of")
9583 (setq forof-p t)))
9584 (setq in-pos (- js2-token-beg pos))
9585 (js2-report-error "msg.in.after.for.name"))
9586 (setq obj (js2-parse-expr))
9587 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9588 (setq rp (- js2-token-beg pos)))
9589 (setf (js2-node-pos pn) pos
9590 (js2-node-len pn) (- js2-ts-cursor pos)
9591 (js2-array-comp-loop-node-iterator pn) iter
9592 (js2-array-comp-loop-node-object pn) obj
9593 (js2-array-comp-loop-node-in-pos pn) in-pos
9594 (js2-array-comp-loop-node-each-pos pn) each-pos
9595 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9596 (js2-array-comp-loop-node-forof-p pn) forof-p
9597 (js2-array-comp-loop-node-lp pn) lp
9598 (js2-array-comp-loop-node-rp pn) rp)
9599 (js2-node-add-children pn iter obj))
9600 (js2-pop-scope))
9601 pn))
9602
9603 (defun js2-parse-object-literal ()
9604 (let ((pos js2-token-beg)
9605 tt
9606 elems
9607 result
9608 after-comma
9609 (continue t))
9610 (while continue
9611 (setq tt (js2-peek-token))
9612 (cond
9613 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9614 ((or (js2-valid-prop-name-token tt)
9615 (= tt js2-STRING))
9616 (setq after-comma nil
9617 result (js2-parse-named-prop tt))
9618 (if (and (null result)
9619 (not js2-recover-from-parse-errors))
9620 (setq continue nil)
9621 (push result elems)))
9622 ;; {12: x} or {10.7: x}
9623 ((= tt js2-NUMBER)
9624 (js2-consume-token)
9625 (setq after-comma nil)
9626 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9627 ;; trailing comma
9628 ((= tt js2-RC)
9629 (setq continue nil)
9630 (if after-comma
9631 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9632 pos elems after-comma)))
9633 (t
9634 (js2-report-error "msg.bad.prop")
9635 (unless js2-recover-from-parse-errors
9636 (setq continue nil)))) ; end switch
9637 (if (js2-match-token js2-COMMA)
9638 (setq after-comma js2-token-end)
9639 (setq continue nil))) ; end loop
9640 (js2-must-match js2-RC "msg.no.brace.prop")
9641 (setq result (make-js2-object-node :pos pos
9642 :len (- js2-ts-cursor pos)
9643 :elems (nreverse elems)))
9644 (apply #'js2-node-add-children result (js2-object-node-elems result))
9645 result))
9646
9647 (defun js2-parse-named-prop (tt)
9648 "Parse a name, string, or getter/setter object property.
9649 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9650 (js2-consume-token)
9651 (let ((string-prop (and (= tt js2-STRING)
9652 (make-js2-string-node)))
9653 expr
9654 (ppos js2-token-beg)
9655 (pend js2-token-end)
9656 (name (js2-create-name-node))
9657 (prop js2-ts-string))
9658 (cond
9659 ;; getter/setter prop
9660 ((and (= tt js2-NAME)
9661 (= (js2-peek-token) js2-NAME)
9662 (or (string= prop "get")
9663 (string= prop "set")))
9664 (js2-consume-token)
9665 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9666 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9667 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9668 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9669 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9670 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9671 ;; when patterns are used in variable declarations, function parameters,
9672 ;; catch-clause, and iterators.
9673 ;; We have to set `js2-is-in-destructuring' to t when the current
9674 ;; expressions are on the left side of any assignment, but it's difficult
9675 ;; because it requires looking ahead of expression.
9676 ((and js2-is-in-destructuring
9677 (= tt js2-NAME)
9678 (let ((ctk (js2-peek-token)))
9679 (or (= ctk js2-COMMA)
9680 (= ctk js2-RC)
9681 (js2-valid-prop-name-token ctk))))
9682 name)
9683 ;; regular prop
9684 (t
9685 (prog1
9686 (setq expr (js2-parse-plain-property (or string-prop name)))
9687 (js2-set-face ppos pend
9688 (if (js2-function-node-p
9689 (js2-object-prop-node-right expr))
9690 'font-lock-function-name-face
9691 'font-lock-variable-name-face)
9692 'record))))))
9693
9694 (defun js2-parse-plain-property (prop)
9695 "Parse a non-getter/setter property in an object literal.
9696 PROP is the node representing the property: a number, name or string."
9697 (js2-must-match js2-COLON "msg.no.colon.prop")
9698 (let* ((pos (js2-node-pos prop))
9699 (colon (- js2-token-beg pos))
9700 (expr (js2-parse-assign-expr))
9701 (result (make-js2-object-prop-node
9702 :pos pos
9703 ;; don't include last consumed token in length
9704 :len (- (+ (js2-node-pos expr)
9705 (js2-node-len expr))
9706 pos)
9707 :left prop
9708 :right expr
9709 :op-pos colon)))
9710 (js2-node-add-children result prop expr)
9711 result))
9712
9713 (defun js2-parse-getter-setter-prop (pos prop get-p)
9714 "Parse getter or setter property in an object literal.
9715 JavaScript syntax is:
9716
9717 { get foo() {...}, set foo(x) {...} }
9718
9719 and expression closure style is also supported
9720
9721 { get foo() x, set foo(x) _x = x }
9722
9723 POS is the start position of the `get' or `set' keyword.
9724 PROP is the `js2-name-node' representing the property name.
9725 GET-P is non-nil if the keyword was `get'."
9726 (let ((type (if get-p js2-GET js2-SET))
9727 result
9728 end
9729 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9730 ;; it has to be an anonymous function, as we already parsed the name
9731 (if (/= (js2-node-type fn) js2-FUNCTION)
9732 (js2-report-error "msg.bad.prop")
9733 (if (plusp (length (js2-function-name fn)))
9734 (js2-report-error "msg.bad.prop")))
9735 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9736 (setq end (js2-node-end fn)
9737 result (make-js2-getter-setter-node :type type
9738 :pos pos
9739 :len (- end pos)
9740 :left prop
9741 :right fn))
9742 (js2-node-add-children result prop fn)
9743 result))
9744
9745 (defun js2-create-name-node (&optional check-activation-p token)
9746 "Create a name node using the token info from last scanned name.
9747 In some cases we need to either synthesize a name node, or we lost
9748 the name token information by peeking. If the TOKEN parameter is
9749 not `js2-NAME', then we use the token info saved in instance vars."
9750 (let ((beg js2-token-beg)
9751 (s js2-ts-string)
9752 name)
9753 (when (/= js2-current-token js2-NAME)
9754 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9755 s js2-prev-name-token-string
9756 js2-prev-name-token-start nil
9757 js2-prev-name-token-string nil))
9758 (setq name (make-js2-name-node :pos beg
9759 :name s
9760 :len (length s)))
9761 (if check-activation-p
9762 (js2-check-activation-name s (or token js2-NAME)))
9763 name))
9764
9765 ;;; Indentation support
9766
9767 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9768 ;; Karl cleverly deduces that the desired indentation level is often a
9769 ;; function of paren/bracket/brace nesting depth, which can be determined
9770 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9771 ;; then does some equally clever checks to see if we're in the context of a
9772 ;; substatement of a possibly braceless statement keyword such as if, while,
9773 ;; or finally. This approach yields pretty good results.
9774
9775 ;; The indenter is often "wrong", however, and needs to be overridden.
9776 ;; The right long-term solution is probably to emulate (or integrate
9777 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9778 ;; parse tree from `js2-parse' is present, which is not true at the
9779 ;; moment the user is typing, computing indentation is still thousands
9780 ;; of lines of code to handle every possible syntactic edge case.
9781
9782 ;; In the meantime, the compromise solution is that we offer a "bounce
9783 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9784 ;; current line indent among various likely guess points. This approach
9785 ;; is far from perfect, but should at least make it slightly easier to
9786 ;; move the line towards its desired indentation when manually
9787 ;; overriding Karl's heuristic nesting guesser.
9788
9789 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9790 ;; extensions such as `let' and Array comprehensions. Major kudos to
9791 ;; Karl for coming up with the initial approach, which packs a lot of
9792 ;; punch for so little code.
9793
9794 (defconst js2-possibly-braceless-keywords-re
9795 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9796 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9797 "try" "while" "with" "let")))
9798 "Regular expression matching keywords that are optionally
9799 followed by an opening brace.")
9800
9801 (defconst js2-indent-operator-re
9802 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9803 (regexp-opt '("in" "instanceof") 'words))
9804 "Regular expression matching operators that affect indentation
9805 of continued expressions.")
9806
9807 (defconst js2-declaration-keyword-re
9808 (regexp-opt '("var" "let" "const") 'words)
9809 "Regular expression matching variable declaration keywords.")
9810
9811 ;; This function has horrible results if you're typing an array
9812 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9813 ;; in conjunction with electric-indent, so just disabling it.
9814 (defsubst js2-code-at-bol-p ()
9815 "Return t if the first character on line is non-whitespace."
9816 nil)
9817
9818 (defun js2-insert-and-indent (key)
9819 "Run command bound to key and indent current line. Runs the command
9820 bound to KEY in the global keymap and indents the current line."
9821 (interactive (list (this-command-keys)))
9822 (let ((cmd (lookup-key (current-global-map) key)))
9823 (if (commandp cmd)
9824 (call-interactively cmd)))
9825 ;; don't do the electric keys inside comments or strings,
9826 ;; and don't do bounce-indent with them.
9827 (let ((parse-state (syntax-ppss (point)))
9828 (js2-bounce-indent-p (js2-code-at-bol-p)))
9829 (unless (or (nth 3 parse-state)
9830 (nth 4 parse-state))
9831 (indent-according-to-mode))))
9832
9833 (defun js2-re-search-forward-inner (regexp &optional bound count)
9834 "Auxiliary function for `js2-re-search-forward'."
9835 (let (parse saved-point)
9836 (while (> count 0)
9837 (re-search-forward regexp bound)
9838 (setq parse (if saved-point
9839 (parse-partial-sexp saved-point (point))
9840 (syntax-ppss (point))))
9841 (cond ((nth 3 parse)
9842 (re-search-forward
9843 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9844 (save-excursion (end-of-line) (point)) t))
9845 ((nth 7 parse)
9846 (forward-line))
9847 ((or (nth 4 parse)
9848 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9849 (re-search-forward "\\*/"))
9850 (t
9851 (setq count (1- count))))
9852 (setq saved-point (point))))
9853 (point))
9854
9855 (defun js2-re-search-forward (regexp &optional bound noerror count)
9856 "Search forward but ignore strings and comments. Invokes
9857 `re-search-forward' but treats the buffer as if strings and
9858 comments have been removed."
9859 (let ((saved-point (point))
9860 (search-expr
9861 (cond ((null count)
9862 '(js2-re-search-forward-inner regexp bound 1))
9863 ((< count 0)
9864 '(js2-re-search-backward-inner regexp bound (- count)))
9865 ((> count 0)
9866 '(js2-re-search-forward-inner regexp bound count)))))
9867 (condition-case err
9868 (eval search-expr)
9869 (search-failed
9870 (goto-char saved-point)
9871 (unless noerror
9872 (error (error-message-string err)))))))
9873
9874 (defun js2-re-search-backward-inner (regexp &optional bound count)
9875 "Auxiliary function for `js2-re-search-backward'."
9876 (let (parse saved-point)
9877 (while (> count 0)
9878 (re-search-backward regexp bound)
9879 (setq parse (if saved-point
9880 (parse-partial-sexp saved-point (point))
9881 (syntax-ppss (point))))
9882 (cond ((nth 3 parse)
9883 (re-search-backward
9884 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9885 (save-excursion (beginning-of-line) (point)) t))
9886 ((nth 7 parse)
9887 (goto-char (nth 8 parse)))
9888 ((or (nth 4 parse)
9889 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9890 (re-search-backward "/\\*"))
9891 (t
9892 (setq count (1- count))))))
9893 (point))
9894
9895 (defun js2-re-search-backward (regexp &optional bound noerror count)
9896 "Search backward but ignore strings and comments. Invokes
9897 `re-search-backward' but treats the buffer as if strings and
9898 comments have been removed."
9899 (let ((saved-point (point))
9900 (search-expr
9901 (cond ((null count)
9902 '(js2-re-search-backward-inner regexp bound 1))
9903 ((< count 0)
9904 '(js2-re-search-forward-inner regexp bound (- count)))
9905 ((> count 0)
9906 '(js2-re-search-backward-inner regexp bound count)))))
9907 (condition-case err
9908 (eval search-expr)
9909 (search-failed
9910 (goto-char saved-point)
9911 (unless noerror
9912 (error (error-message-string err)))))))
9913
9914 (defun js2-looking-at-operator-p ()
9915 "Return non-nil if text after point is an operator (that is not
9916 a comma)."
9917 (save-match-data
9918 (and (looking-at js2-indent-operator-re)
9919 (or (not (looking-at ":"))
9920 (save-excursion
9921 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9922 (looking-at "?")))))))
9923
9924 (defun js2-continued-expression-p ()
9925 "Returns non-nil if the current line continues an expression."
9926 (save-excursion
9927 (back-to-indentation)
9928 (or (js2-looking-at-operator-p)
9929 (when (catch 'found
9930 (while (and (re-search-backward "\n" nil t)
9931 (let ((state (syntax-ppss)))
9932 (when (nth 4 state)
9933 (goto-char (nth 8 state))) ;; skip comments
9934 (skip-chars-backward " \t")
9935 (if (bolp)
9936 t
9937 (throw 'found t))))))
9938 (backward-char)
9939 (when (js2-looking-at-operator-p)
9940 (backward-char)
9941 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9942
9943 (defun js2-end-of-do-while-loop-p ()
9944 "Returns non-nil if word after point is `while' of a do-while
9945 statement, else returns nil. A braceless do-while statement
9946 spanning several lines requires that the start of the loop is
9947 indented to the same column as the current line."
9948 (interactive)
9949 (save-excursion
9950 (save-match-data
9951 (when (looking-at "\\s-*\\<while\\>")
9952 (if (save-excursion
9953 (skip-chars-backward "[ \t\n]*}")
9954 (looking-at "[ \t\n]*}"))
9955 (save-excursion
9956 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9957 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9958 (or (looking-at "\\<do\\>")
9959 (let ((saved-indent (current-indentation)))
9960 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9961 (/= (current-indentation) saved-indent)))
9962 (and (looking-at "[ \t]*\\<do\\>")
9963 (not (js2-re-search-forward
9964 "\\<while\\>" (point-at-eol) t))
9965 (= (current-indentation) saved-indent)))))))))
9966
9967 (defun js2-multiline-decl-indentation ()
9968 "Returns the declaration indentation column if the current line belongs
9969 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9970 (let (forward-sexp-function ; use Lisp version
9971 at-opening-bracket)
9972 (save-excursion
9973 (back-to-indentation)
9974 (when (not (looking-at js2-declaration-keyword-re))
9975 (when (looking-at js2-indent-operator-re)
9976 (goto-char (match-end 0))) ; continued expressions are ok
9977 (while (and (not at-opening-bracket)
9978 (not (bobp))
9979 (let ((pos (point)))
9980 (save-excursion
9981 (js2-backward-sws)
9982 (or (eq (char-before) ?,)
9983 (and (not (eq (char-before) ?\;))
9984 (and
9985 (prog2 (skip-chars-backward "[[:punct:]]")
9986 (looking-at js2-indent-operator-re)
9987 (js2-backward-sws))
9988 (not (eq (char-before) ?\;))))
9989 (js2-same-line pos)))))
9990 (condition-case err
9991 (backward-sexp)
9992 (scan-error (setq at-opening-bracket t))))
9993 (when (looking-at js2-declaration-keyword-re)
9994 (goto-char (match-end 0))
9995 (1+ (current-column)))))))
9996
9997 (defun js2-ctrl-statement-indentation ()
9998 "Returns the proper indentation of the current line if it
9999 starts the body of a control statement without braces, else
10000 returns nil."
10001 (let (forward-sexp-function) ; temporarily unbind it
10002 (save-excursion
10003 (back-to-indentation)
10004 (when (and (not (js2-same-line (point-min)))
10005 (not (looking-at "{"))
10006 (js2-re-search-backward "[[:graph:]]" nil t)
10007 (not (looking-at "[{([]"))
10008 (progn
10009 (forward-char)
10010 (when (= (char-before) ?\))
10011 ;; scan-sexps sometimes throws an error
10012 (ignore-errors (backward-sexp))
10013 (skip-chars-backward " \t" (point-at-bol)))
10014 (let ((pt (point)))
10015 (back-to-indentation)
10016 (and (looking-at js2-possibly-braceless-keywords-re)
10017 (= (match-end 0) pt)
10018 (not (js2-end-of-do-while-loop-p))))))
10019 (+ (current-indentation) js2-basic-offset)))))
10020
10021 (defun js2-indent-in-array-comp (parse-status)
10022 "Return non-nil if we think we're in an array comprehension.
10023 In particular, return the buffer position of the first `for' kwd."
10024 (let ((bracket (nth 1 parse-status))
10025 (end (point)))
10026 (when bracket
10027 (save-excursion
10028 (goto-char bracket)
10029 (when (looking-at "\\[")
10030 (forward-char 1)
10031 (js2-forward-sws)
10032 (if (looking-at "[[{]")
10033 (let (forward-sexp-function) ; use lisp version
10034 (forward-sexp) ; skip destructuring form
10035 (js2-forward-sws)
10036 (if (and (/= (char-after) ?,) ; regular array
10037 (looking-at "for"))
10038 (match-beginning 0)))
10039 ;; to skip arbitrary expressions we need the parser,
10040 ;; so we'll just guess at it.
10041 (if (and (> end (point)) ; not empty literal
10042 (re-search-forward "[^,]]* \\(for\\) " end t)
10043 ;; not inside comment or string literal
10044 (let ((state (parse-partial-sexp bracket (point))))
10045 (not (or (nth 3 state) (nth 4 state)))))
10046 (match-beginning 1))))))))
10047
10048 (defun js2-array-comp-indentation (parse-status for-kwd)
10049 (if (js2-same-line for-kwd)
10050 ;; first continuation line
10051 (save-excursion
10052 (goto-char (nth 1 parse-status))
10053 (forward-char 1)
10054 (skip-chars-forward " \t")
10055 (current-column))
10056 (save-excursion
10057 (goto-char for-kwd)
10058 (current-column))))
10059
10060 (defun js2-proper-indentation (parse-status)
10061 "Return the proper indentation for the current line."
10062 (save-excursion
10063 (back-to-indentation)
10064 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10065 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10066 (continued-expr-p (js2-continued-expression-p))
10067 (declaration-indent (and js2-pretty-multiline-declarations
10068 (js2-multiline-decl-indentation)))
10069 (bracket (nth 1 parse-status))
10070 beg)
10071 (cond
10072 ;; indent array comprehension continuation lines specially
10073 ((and bracket
10074 (>= js2-language-version 170)
10075 (not (js2-same-line bracket))
10076 (setq beg (js2-indent-in-array-comp parse-status))
10077 (>= (point) (save-excursion
10078 (goto-char beg)
10079 (point-at-bol)))) ; at or after first loop?
10080 (js2-array-comp-indentation parse-status beg))
10081
10082 (ctrl-stmt-indent)
10083
10084 ((and declaration-indent continued-expr-p)
10085 (+ declaration-indent js2-basic-offset))
10086
10087 (declaration-indent)
10088
10089 (bracket
10090 (goto-char bracket)
10091 (cond
10092 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10093 (when (save-excursion (skip-chars-backward " \t)")
10094 (looking-at ")"))
10095 (backward-list))
10096 (back-to-indentation)
10097 (and (eq js2-pretty-multiline-declarations 'all)
10098 (looking-at js2-declaration-keyword-re)
10099 (goto-char (1+ (match-end 0))))
10100 (cond (same-indent-p
10101 (current-column))
10102 (continued-expr-p
10103 (+ (current-column) (* 2 js2-basic-offset)))
10104 (t
10105 (+ (current-column) js2-basic-offset))))
10106 (t
10107 (unless same-indent-p
10108 (forward-char)
10109 (skip-chars-forward " \t"))
10110 (current-column))))
10111
10112 (continued-expr-p js2-basic-offset)
10113
10114 (t 0)))))
10115
10116 (defun js2-lineup-comment (parse-status)
10117 "Indent a multi-line block comment continuation line."
10118 (let* ((beg (nth 8 parse-status))
10119 (first-line (js2-same-line beg))
10120 (offset (save-excursion
10121 (goto-char beg)
10122 (if (looking-at "/\\*")
10123 (+ 1 (current-column))
10124 0))))
10125 (unless first-line
10126 (indent-line-to offset))))
10127
10128 (defun js2-backward-sws ()
10129 "Move backward through whitespace and comments."
10130 (interactive)
10131 (while (forward-comment -1)))
10132
10133 (defun js2-forward-sws ()
10134 "Move forward through whitespace and comments."
10135 (interactive)
10136 (while (forward-comment 1)))
10137
10138 (defsubst js2-current-indent (&optional pos)
10139 "Return column of indentation on current line.
10140 If POS is non-nil, go to that point and return indentation for that line."
10141 (save-excursion
10142 (if pos
10143 (goto-char pos))
10144 (back-to-indentation)
10145 (current-column)))
10146
10147 (defsubst js2-arglist-close ()
10148 "Return non-nil if we're on a line beginning with a close-paren/brace."
10149 (save-match-data
10150 (save-excursion
10151 (goto-char (point-at-bol))
10152 (js2-forward-sws)
10153 (looking-at "[])}]"))))
10154
10155 (defsubst js2-indent-looks-like-label-p ()
10156 (goto-char (point-at-bol))
10157 (js2-forward-sws)
10158 (looking-at (concat js2-mode-identifier-re ":")))
10159
10160 (defun js2-indent-in-objlit-p (parse-status)
10161 "Return non-nil if this looks like an object-literal entry."
10162 (let ((start (nth 1 parse-status)))
10163 (and
10164 start
10165 (save-excursion
10166 (and (zerop (forward-line -1))
10167 (not (< (point) start)) ; crossed a {} boundary
10168 (js2-indent-looks-like-label-p)))
10169 (save-excursion
10170 (js2-indent-looks-like-label-p)))))
10171
10172 ;; if prev line looks like foobar({ then we're passing an object
10173 ;; literal to a function call, and people pretty much always want to
10174 ;; de-dent back to the previous line, so move the 'basic-offset'
10175 ;; position to the front.
10176 (defsubst js2-indent-objlit-arg-p (parse-status)
10177 (save-excursion
10178 (back-to-indentation)
10179 (js2-backward-sws)
10180 (and (eq (1- (point)) (nth 1 parse-status))
10181 (eq (char-before) ?{)
10182 (progn
10183 (forward-char -1)
10184 (skip-chars-backward " \t")
10185 (eq (char-before) ?\()))))
10186
10187 (defsubst js2-indent-case-block-p ()
10188 (save-excursion
10189 (back-to-indentation)
10190 (js2-backward-sws)
10191 (goto-char (point-at-bol))
10192 (skip-chars-forward " \t")
10193 (save-match-data
10194 (looking-at "case\\s-.+:"))))
10195
10196 (defsubst js2-syntax-bol ()
10197 "Return the point at the first non-whitespace char on the line.
10198 Returns `point-at-bol' if the line is empty."
10199 (save-excursion
10200 (beginning-of-line)
10201 (skip-chars-forward " \t")
10202 (point)))
10203
10204 (defun js2-bounce-indent (normal-col parse-status backwards)
10205 "Cycle among alternate computed indentation positions.
10206 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10207 of the buffer to the current point. NORMAL-COL is the indentation
10208 column computed by the heuristic guesser based on current paren,
10209 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10210 in reverse."
10211 (let ((cur-indent (js2-current-indent))
10212 (old-buffer-undo-list buffer-undo-list)
10213 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10214 (current-line (save-excursion
10215 (forward-line 0) ; move to bol
10216 (1+ (count-lines (point-min) (point)))))
10217 positions
10218 pos
10219 main-pos
10220 anchor
10221 arglist-cont
10222 same-indent
10223 prev-line-col
10224 basic-offset
10225 computed-pos)
10226 ;; temporarily don't record undo info, if user requested this
10227 (if js2-mode-indent-inhibit-undo
10228 (setq buffer-undo-list t))
10229 (unwind-protect
10230 (progn
10231 ;; first likely point: indent from beginning of previous code line
10232 (push (setq basic-offset
10233 (+ (save-excursion
10234 (back-to-indentation)
10235 (js2-backward-sws)
10236 (back-to-indentation)
10237 (setq prev-line-col (current-column)))
10238 js2-basic-offset))
10239 positions)
10240
10241 ;; (first + epsilon) likely point: indent 2x from beginning of
10242 ;; previous code line. Some companies like this approach. Ahem.
10243 ;; Seriously, though -- 4-space indent for expression continuation
10244 ;; lines isn't a bad idea. We should eventually implement it
10245 ;; that way.
10246 (push (setq basic-offset
10247 (+ (save-excursion
10248 (back-to-indentation)
10249 (js2-backward-sws)
10250 (back-to-indentation)
10251 (setq prev-line-col (current-column)))
10252 (* 2 js2-basic-offset)))
10253 positions)
10254
10255 ;; second likely point: indent from assign-expr RHS. This
10256 ;; is just a crude guess based on finding " = " on the previous
10257 ;; line containing actual code.
10258 (setq pos (save-excursion
10259 (save-match-data
10260 (forward-line -1)
10261 (goto-char (point-at-bol))
10262 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10263 (point-at-eol) t)
10264 (goto-char (match-end 1))
10265 (skip-chars-forward " \t\r\n")
10266 (current-column)))))
10267 (when pos
10268 (incf pos js2-basic-offset)
10269 (push pos positions))
10270
10271 ;; third likely point: same indent as previous line of code.
10272 ;; Make it the first likely point if we're not on an
10273 ;; arglist-close line and previous line ends in a comma, or
10274 ;; both this line and prev line look like object-literal
10275 ;; elements.
10276 (setq pos (save-excursion
10277 (goto-char (point-at-bol))
10278 (js2-backward-sws)
10279 (back-to-indentation)
10280 (prog1
10281 (current-column)
10282 ;; while we're here, look for trailing comma
10283 (if (save-excursion
10284 (goto-char (point-at-eol))
10285 (js2-backward-sws)
10286 (eq (char-before) ?,))
10287 (setq arglist-cont (1- (point)))))))
10288 (when pos
10289 (if (and (or arglist-cont
10290 (js2-indent-in-objlit-p parse-status))
10291 (not (js2-arglist-close)))
10292 (setq same-indent pos))
10293 (push pos positions))
10294
10295 ;; fourth likely point: first preceding code with less indentation
10296 ;; than the immediately preceding code line.
10297 (setq pos (save-excursion
10298 (back-to-indentation)
10299 (js2-backward-sws)
10300 (back-to-indentation)
10301 (setq anchor (current-column))
10302 (while (and (zerop (forward-line -1))
10303 (>= (progn
10304 (back-to-indentation)
10305 (current-column))
10306 anchor)))
10307 (setq pos (current-column))))
10308 (push pos positions)
10309
10310 ;; nesting-heuristic position, main by default
10311 (push (setq main-pos normal-col) positions)
10312
10313 ;; delete duplicates and sort positions list
10314 (setq positions (sort (delete-dups positions) '<))
10315
10316 ;; comma-list continuation lines: prev line indent takes precedence
10317 (if same-indent
10318 (setq main-pos same-indent))
10319
10320 ;; common special cases where we want to indent in from previous line
10321 (if (or (js2-indent-case-block-p)
10322 (js2-indent-objlit-arg-p parse-status))
10323 (setq main-pos basic-offset))
10324
10325 ;; if bouncing backwards, reverse positions list
10326 (if backwards
10327 (setq positions (reverse positions)))
10328
10329 ;; record whether we're already sitting on one of the alternatives
10330 (setq pos (member cur-indent positions))
10331
10332 (cond
10333 ;; case 0: we're one one of the alternatives and this is the
10334 ;; first time they've pressed TAB on this line (best-guess).
10335 ((and js2-mode-indent-ignore-first-tab
10336 pos
10337 ;; first time pressing TAB on this line?
10338 (not (eq js2-mode-last-indented-line current-line)))
10339 ;; do nothing
10340 (setq computed-pos nil))
10341 ;; case 1: only one computed position => use it
10342 ((null (cdr positions))
10343 (setq computed-pos 0))
10344 ;; case 2: not on any of the computed spots => use main spot
10345 ((not pos)
10346 (setq computed-pos (js2-position main-pos positions)))
10347 ;; case 3: on last position: cycle to first position
10348 ((null (cdr pos))
10349 (setq computed-pos 0))
10350 ;; case 4: on intermediate position: cycle to next position
10351 (t
10352 (setq computed-pos (js2-position (second pos) positions))))
10353
10354 ;; see if any hooks want to indent; otherwise we do it
10355 (loop with result = nil
10356 for hook in js2-indent-hook
10357 while (null result)
10358 do
10359 (setq result (funcall hook positions computed-pos))
10360 finally do
10361 (unless (or result (null computed-pos))
10362 (indent-line-to (nth computed-pos positions)))))
10363
10364 ;; finally
10365 (if js2-mode-indent-inhibit-undo
10366 (setq buffer-undo-list old-buffer-undo-list))
10367 ;; see commentary for `js2-mode-last-indented-line'
10368 (setq js2-mode-last-indented-line current-line))))
10369
10370 (defun js2-indent-bounce-backwards ()
10371 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10372 cycles between the computed indentation positions in reverse order."
10373 (interactive)
10374 (js2-indent-line t))
10375
10376 (defsubst js2-1-line-comment-continuation-p ()
10377 "Return t if we're in a 1-line comment continuation.
10378 If so, we don't ever want to use bounce-indent."
10379 (save-excursion
10380 (save-match-data
10381 (and (progn
10382 (forward-line 0)
10383 (looking-at "\\s-*//"))
10384 (progn
10385 (forward-line -1)
10386 (forward-line 0)
10387 (when (looking-at "\\s-*$")
10388 (js2-backward-sws)
10389 (forward-line 0))
10390 (looking-at "\\s-*//"))))))
10391
10392 (defun js2-indent-line (&optional bounce-backwards)
10393 "Indent the current line as JavaScript source text."
10394 (interactive)
10395 (let (parse-status
10396 offset
10397 indent-col
10398 moved
10399 ;; don't whine about errors/warnings when we're indenting.
10400 ;; This has to be set before calling parse-partial-sexp below.
10401 (inhibit-point-motion-hooks t))
10402 (setq parse-status (save-excursion
10403 (syntax-ppss (point-at-bol)))
10404 offset (- (point) (save-excursion
10405 (back-to-indentation)
10406 (point))))
10407 (js2-with-underscore-as-word-syntax
10408 (if (nth 4 parse-status)
10409 (js2-lineup-comment parse-status)
10410 (setq indent-col (js2-proper-indentation parse-status))
10411 ;; see comments below about js2-mode-last-indented-line
10412 (cond
10413 ;; bounce-indenting is disabled during electric-key indent.
10414 ;; It doesn't work well on first line of buffer.
10415 ((and js2-bounce-indent-p
10416 (not (js2-same-line (point-min)))
10417 (not (js2-1-line-comment-continuation-p)))
10418 (js2-bounce-indent indent-col parse-status bounce-backwards))
10419 ;; just indent to the guesser's likely spot
10420 (t (indent-line-to indent-col))))
10421 (when (plusp offset)
10422 (forward-char offset)))))
10423
10424 (defun js2-indent-region (start end)
10425 "Indent the region, but don't use bounce indenting."
10426 (let ((js2-bounce-indent-p nil)
10427 (indent-region-function nil)
10428 (after-change-functions (remq 'js2-mode-edit
10429 after-change-functions)))
10430 (indent-region start end nil) ; nil for byte-compiler
10431 (js2-mode-edit start end (- end start))))
10432
10433 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10434
10435 ;;;###autoload
10436 (defun js2-mode ()
10437 "Major mode for editing JavaScript code.
10438
10439 \\{js2-mode-map}"
10440 (interactive)
10441 (kill-all-local-variables)
10442 (set-syntax-table js2-mode-syntax-table)
10443 (use-local-map js2-mode-map)
10444 (make-local-variable 'comment-start)
10445 (make-local-variable 'comment-end)
10446 (make-local-variable 'comment-start-skip)
10447 (setq major-mode 'js2-mode
10448 mode-name "JavaScript-IDE"
10449 comment-start "//" ; used by comment-region; don't change it
10450 comment-end "")
10451 (setq local-abbrev-table js2-mode-abbrev-table)
10452 (set (make-local-variable 'max-lisp-eval-depth)
10453 (max max-lisp-eval-depth 3000))
10454 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10455 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10456
10457 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10458 ;; on most platforms other than the one I originally wrote it on.
10459 ;; So it's back to `c-fill-paragraph'.
10460 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10461
10462 (add-hook 'before-save-hook #'js2-before-save nil t)
10463 (set (make-local-variable 'next-error-function) #'js2-next-error)
10464 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10465 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10466 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10467 ;; for characters inside regexp literals.
10468 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10469 ;; this is necessary to make `show-paren-function' work properly
10470 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10471 ;; needed for M-x rgrep, among other things
10472 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10473
10474 ;; some variables needed by cc-engine for paragraph-fill, etc.
10475 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10476 c-comment-start-regexp "/[*/]\\|\\s|"
10477 c-line-comment-starter "//"
10478 c-paragraph-start js2-paragraph-start
10479 c-paragraph-separate "$"
10480 comment-start-skip js2-comment-start-skip
10481 c-syntactic-ws-start js2-syntactic-ws-start
10482 c-syntactic-ws-end js2-syntactic-ws-end
10483 c-syntactic-eol js2-syntactic-eol)
10484
10485 (let ((c-buffer-is-cc-mode t))
10486 ;; Copied from `js-mode'. Also see Bug#6071.
10487 (make-local-variable 'paragraph-start)
10488 (make-local-variable 'paragraph-separate)
10489 (make-local-variable 'paragraph-ignore-fill-prefix)
10490 (make-local-variable 'adaptive-fill-mode)
10491 (make-local-variable 'adaptive-fill-regexp)
10492 (c-setup-paragraph-variables))
10493
10494 (setq js2-default-externs
10495 (append js2-ecma-262-externs
10496 (if js2-include-browser-externs
10497 js2-browser-externs)
10498 (if js2-include-gears-externs
10499 js2-gears-externs)
10500 (if js2-include-rhino-externs
10501 js2-rhino-externs)))
10502
10503 ;; We do our own syntax highlighting based on the parse tree.
10504 ;; However, we want minor modes that add keywords to highlight properly
10505 ;; (examples: doxymacs, column-marker).
10506 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10507 (setq font-lock-defaults '(nil t))
10508
10509 ;; Experiment: make reparse-delay longer for longer files.
10510 (if (plusp js2-dynamic-idle-timer-adjust)
10511 (setq js2-idle-timer-delay
10512 (* js2-idle-timer-delay
10513 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10514
10515 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10516 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10517 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10518 (imenu-add-to-menubar (concat "IM-" mode-name))
10519 (when js2-mirror-mode
10520 (js2-enter-mirror-mode))
10521 (add-to-invisibility-spec '(js2-outline . t))
10522 (set (make-local-variable 'line-move-ignore-invisible) t)
10523 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10524
10525 (if (fboundp 'run-mode-hooks)
10526 (run-mode-hooks 'js2-mode-hook)
10527 (run-hooks 'js2-mode-hook))
10528
10529 (setq js2-mode-functions-hidden nil
10530 js2-mode-comments-hidden nil
10531 js2-mode-buffer-dirty-p t
10532 js2-mode-parsing nil)
10533 (js2-reparse))
10534
10535 (defun js2-mode-exit ()
10536 "Exit `js2-mode' and clean up."
10537 (interactive)
10538 (when js2-mode-node-overlay
10539 (delete-overlay js2-mode-node-overlay)
10540 (setq js2-mode-node-overlay nil))
10541 (js2-remove-overlays)
10542 (setq js2-mode-ast nil)
10543 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10544 (remove-from-invisibility-spec '(js2-outline . t))
10545 (js2-mode-show-all)
10546 (js2-with-unmodifying-text-property-changes
10547 (js2-clear-face (point-min) (point-max))))
10548
10549 (defun js2-before-save ()
10550 "Clean up whitespace before saving file.
10551 You can disable this by customizing `js2-cleanup-whitespace'."
10552 (when js2-cleanup-whitespace
10553 (let ((col (current-column)))
10554 (delete-trailing-whitespace)
10555 ;; don't change trailing whitespace on current line
10556 (unless (eq (current-column) col)
10557 (indent-to col)))))
10558
10559 (defsubst js2-mode-reset-timer ()
10560 "Cancel any existing parse timer and schedule a new one."
10561 (if js2-mode-parse-timer
10562 (cancel-timer js2-mode-parse-timer))
10563 (setq js2-mode-parsing nil)
10564 (let ((timer (timer-create)))
10565 (setq js2-mode-parse-timer timer)
10566 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10567 (timer-set-idle-time timer js2-idle-timer-delay)
10568 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10569 (timer-activate-when-idle timer nil)))
10570
10571 (defun js2-mode-idle-reparse (buffer)
10572 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10573 it to be reparsed when the buffer is selected."
10574 (if (eq buffer (current-buffer))
10575 (js2-reparse)
10576 ;; reparse when the buffer is selected again
10577 (with-current-buffer buffer
10578 (add-hook 'window-configuration-change-hook
10579 #'js2-mode-idle-reparse-inner
10580 nil t))))
10581
10582 (defun js2-mode-idle-reparse-inner ()
10583 (remove-hook 'window-configuration-change-hook
10584 #'js2-mode-idle-reparse-inner
10585 t)
10586 (js2-reparse))
10587
10588 (defun js2-mode-edit (beg end len)
10589 "Schedule a new parse after buffer is edited.
10590 Buffer edit spans from BEG to END and is of length LEN.
10591 Also clears the `js2-magic' bit on autoinserted parens/brackets
10592 if the edit occurred on a line different from the magic paren."
10593 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10594 (line (if magic-pos (line-number-at-pos magic-pos))))
10595 (and line
10596 (or (/= (line-number-at-pos beg) line)
10597 (and (> 0 len)
10598 (/= (line-number-at-pos end) line)))
10599 (js2-mode-mundanify-parens)))
10600 (setq js2-mode-buffer-dirty-p t)
10601 (js2-mode-hide-overlay)
10602 (js2-mode-reset-timer))
10603
10604 (defun js2-reparse (&optional force)
10605 "Re-parse current buffer after user finishes some data entry.
10606 If we get any user input while parsing, including cursor motion,
10607 we discard the parse and reschedule it. If FORCE is nil, then the
10608 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10609 (let (time
10610 interrupted-p
10611 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10612 (unless js2-mode-parsing
10613 (setq js2-mode-parsing t)
10614 (unwind-protect
10615 (when (or js2-mode-buffer-dirty-p force)
10616 (js2-remove-overlays)
10617 (js2-with-unmodifying-text-property-changes
10618 (setq js2-mode-buffer-dirty-p nil
10619 js2-mode-fontifications nil
10620 js2-mode-deferred-properties nil)
10621 (if js2-mode-verbose-parse-p
10622 (message "parsing..."))
10623 (setq time
10624 (js2-time
10625 (setq interrupted-p
10626 (catch 'interrupted
10627 (js2-parse)
10628 ;; if parsing is interrupted, comments and regex
10629 ;; literals stay ignored by `parse-partial-sexp'
10630 (remove-text-properties (point-min) (point-max)
10631 '(syntax-table))
10632 (js2-mode-apply-deferred-properties)
10633 (js2-mode-remove-suppressed-warnings)
10634 (js2-mode-show-warnings)
10635 (js2-mode-show-errors)
10636 (js2-mode-highlight-magic-parens)
10637 (if (>= js2-highlight-level 1)
10638 (js2-highlight-jsdoc js2-mode-ast))
10639 nil))))
10640 (if interrupted-p
10641 (progn
10642 ;; unfinished parse => try again
10643 (setq js2-mode-buffer-dirty-p t)
10644 (js2-mode-reset-timer))
10645 (if js2-mode-verbose-parse-p
10646 (message "Parse time: %s" time)))))
10647 (setq js2-mode-parsing nil)
10648 (unless interrupted-p
10649 (setq js2-mode-parse-timer nil))))))
10650
10651 (defun js2-mode-show-node (event)
10652 "Debugging aid: highlight selected AST node on mouse click."
10653 (interactive "e")
10654 (mouse-set-point event)
10655 (setq deactivate-mark t)
10656 (when js2-mode-show-overlay
10657 (let ((node (js2-node-at-point))
10658 beg end)
10659 (if (null node)
10660 (message "No node found at location %s" (point))
10661 (setq beg (js2-node-abs-pos node)
10662 end (+ beg (js2-node-len node)))
10663 (if js2-mode-node-overlay
10664 (move-overlay js2-mode-node-overlay beg end)
10665 (setq js2-mode-node-overlay (make-overlay beg end))
10666 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10667 (js2-with-unmodifying-text-property-changes
10668 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10669 (message "%s, parent: %s"
10670 (js2-node-short-name node)
10671 (if (js2-node-parent node)
10672 (js2-node-short-name (js2-node-parent node))
10673 "nil"))))))
10674
10675 (defun js2-mode-hide-overlay (&optional p1 p2)
10676 "Remove the debugging overlay when the point moves.
10677 P1 and P2 are the old and new values of point, respectively."
10678 (when js2-mode-node-overlay
10679 (let ((beg (overlay-start js2-mode-node-overlay))
10680 (end (overlay-end js2-mode-node-overlay)))
10681 ;; Sometimes we're called spuriously.
10682 (unless (and p2
10683 (>= p2 beg)
10684 (<= p2 end))
10685 (js2-with-unmodifying-text-property-changes
10686 (remove-text-properties beg end '(point-left nil)))
10687 (delete-overlay js2-mode-node-overlay)
10688 (setq js2-mode-node-overlay nil)))))
10689
10690 (defun js2-mode-reset ()
10691 "Debugging helper: reset everything."
10692 (interactive)
10693 (js2-mode-exit)
10694 (js2-mode))
10695
10696 (defsubst js2-mode-show-warn-or-err (e face)
10697 "Highlight a warning or error E with FACE.
10698 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10699 (let* ((key (first e))
10700 (beg (second e))
10701 (end (+ beg (third e)))
10702 ;; Don't inadvertently go out of bounds.
10703 (beg (max (point-min) (min beg (point-max))))
10704 (end (max (point-min) (min end (point-max))))
10705 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10706 (ovl (make-overlay beg end)))
10707 (overlay-put ovl 'font-lock-face face)
10708 (overlay-put ovl 'js2-error t)
10709 (put-text-property beg end 'help-echo (js2-get-msg key))
10710 (put-text-property beg end 'point-entered #'js2-echo-error)))
10711
10712 (defun js2-remove-overlays ()
10713 "Remove overlays from buffer that have a `js2-error' property."
10714 (let ((beg (point-min))
10715 (end (point-max)))
10716 (save-excursion
10717 (dolist (o (overlays-in beg end))
10718 (when (overlay-get o 'js2-error)
10719 (delete-overlay o))))))
10720
10721 (defun js2-error-at-point (&optional pos)
10722 "Return non-nil if there's an error overlay at POS.
10723 Defaults to point."
10724 (loop with pos = (or pos (point))
10725 for o in (overlays-at pos)
10726 thereis (overlay-get o 'js2-error)))
10727
10728 (defun js2-mode-apply-deferred-properties ()
10729 "Apply fontifications and other text properties recorded during parsing."
10730 (when (plusp js2-highlight-level)
10731 ;; We defer clearing faces as long as possible to eliminate flashing.
10732 (js2-clear-face (point-min) (point-max))
10733 ;; Have to reverse the recorded fontifications list so that errors
10734 ;; and warnings overwrite the normal fontifications.
10735 (dolist (f (nreverse js2-mode-fontifications))
10736 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10737 (setq js2-mode-fontifications nil))
10738 (dolist (p js2-mode-deferred-properties)
10739 (apply #'put-text-property p))
10740 (setq js2-mode-deferred-properties nil))
10741
10742 (defun js2-mode-show-errors ()
10743 "Highlight syntax errors."
10744 (when js2-mode-show-parse-errors
10745 (dolist (e (js2-ast-root-errors js2-mode-ast))
10746 (js2-mode-show-warn-or-err e 'js2-error-face))))
10747
10748 (defun js2-mode-remove-suppressed-warnings ()
10749 "Take suppressed warnings out of the AST warnings list.
10750 This ensures that the counts and `next-error' are correct."
10751 (setf (js2-ast-root-warnings js2-mode-ast)
10752 (js2-delete-if
10753 (lambda (e)
10754 (let ((key (caar e)))
10755 (or
10756 (and (not js2-strict-trailing-comma-warning)
10757 (string-match "trailing\\.comma" key))
10758 (and (not js2-strict-cond-assign-warning)
10759 (string= key "msg.equal.as.assign"))
10760 (and js2-missing-semi-one-line-override
10761 (string= key "msg.missing.semi")
10762 (let* ((beg (second e))
10763 (node (js2-node-at-point beg))
10764 (fn (js2-mode-find-parent-fn node))
10765 (body (and fn (js2-function-node-body fn)))
10766 (lc (and body (js2-node-abs-pos body)))
10767 (rc (and lc (+ lc (js2-node-len body)))))
10768 (and fn
10769 (or (null body)
10770 (save-excursion
10771 (goto-char beg)
10772 (and (js2-same-line lc)
10773 (js2-same-line rc))))))))))
10774 (js2-ast-root-warnings js2-mode-ast))))
10775
10776 (defun js2-mode-show-warnings ()
10777 "Highlight strict-mode warnings."
10778 (when js2-mode-show-strict-warnings
10779 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10780 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10781
10782 (defun js2-echo-error (old-point new-point)
10783 "Called by point-motion hooks."
10784 (let ((msg (get-text-property new-point 'help-echo)))
10785 (if (and msg (or (not (current-message))
10786 (string= (current-message) "Quit")))
10787 (message msg))))
10788
10789 (defalias #'js2-echo-help #'js2-echo-error)
10790
10791 (defun js2-enter-key ()
10792 "Handle user pressing the Enter key."
10793 (interactive)
10794 (let ((parse-status (save-excursion
10795 (syntax-ppss (point))))
10796 (js2-bounce-indent-p nil))
10797 (cond
10798 ;; check if we're inside a string
10799 ((nth 3 parse-status)
10800 (if js2-concat-multiline-strings
10801 (js2-mode-split-string parse-status)
10802 (insert "\n")))
10803 ;; check if inside a block comment
10804 ((nth 4 parse-status)
10805 (js2-mode-extend-comment))
10806 (t
10807 ;; should probably figure out what the mode-map says we should do
10808 (if js2-indent-on-enter-key
10809 (js2-indent-line))
10810 (insert "\n")
10811 (if js2-enter-indents-newline
10812 (js2-indent-line))))))
10813
10814 (defun js2-mode-split-string (parse-status)
10815 "Turn a newline in mid-string into a string concatenation.
10816 PARSE-STATUS is as documented in `parse-partial-sexp'."
10817 (let* ((col (current-column))
10818 (quote-char (nth 3 parse-status))
10819 (quote-string (string quote-char))
10820 (string-beg (nth 8 parse-status))
10821 (at-eol (eq js2-concat-multiline-strings 'eol))
10822 (indent (save-match-data
10823 (or
10824 (save-excursion
10825 (back-to-indentation)
10826 (if (looking-at "\\+")
10827 (current-column)))
10828 (save-excursion
10829 (goto-char string-beg)
10830 (if (looking-back "\\+\\s-+")
10831 (goto-char (match-beginning 0)))
10832 (current-column))))))
10833 (insert quote-char)
10834 (if at-eol
10835 (insert " +\n")
10836 (insert "\n"))
10837 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10838 (indent-to indent)
10839 (unless at-eol
10840 (insert "+ "))
10841 (insert quote-string)
10842 (when (eolp)
10843 (insert quote-string)
10844 (backward-char 1))))
10845
10846 (defun js2-mode-extend-comment ()
10847 "Indent the line and, when inside a comment block, add comment prefix."
10848 (let (star single col first-line needs-close)
10849 (save-excursion
10850 (back-to-indentation)
10851 (cond
10852 ((looking-at "\\*[^/]")
10853 (setq star t
10854 col (current-column)))
10855 ((looking-at "/\\*")
10856 (setq star t
10857 first-line t
10858 col (1+ (current-column))))
10859 ((looking-at "//")
10860 (setq single t
10861 col (current-column)))))
10862 ;; Heuristic for whether we need to close the comment:
10863 ;; if we've got a parse error here, assume it's an unterminated
10864 ;; comment.
10865 (setq needs-close
10866 (or
10867 (eq (get-text-property (1- (point)) 'point-entered)
10868 'js2-echo-error)
10869 ;; The heuristic above doesn't work well when we're
10870 ;; creating a comment and there's another one downstream,
10871 ;; as our parser thinks this one ends at the end of the
10872 ;; next one. (You can have a /* inside a js block comment.)
10873 ;; So just close it if the next non-ws char isn't a *.
10874 (and first-line
10875 (eolp)
10876 (save-excursion
10877 (skip-chars-forward " \t\r\n")
10878 (not (eq (char-after) ?*))))))
10879 (insert "\n")
10880 (cond
10881 (star
10882 (indent-to col)
10883 (insert "* ")
10884 (if (and first-line needs-close)
10885 (save-excursion
10886 (insert "\n")
10887 (indent-to col)
10888 (insert "*/"))))
10889 ((and single
10890 (save-excursion
10891 (and (zerop (forward-line 1))
10892 (looking-at "\\s-*//"))))
10893 (indent-to col)
10894 (insert "// "))
10895 ;; don't need to extend the comment after all
10896 (js2-enter-indents-newline
10897 (js2-indent-line)))))
10898
10899 (defun js2-beginning-of-line ()
10900 "Toggles point between bol and first non-whitespace char in line.
10901 Also moves past comment delimiters when inside comments."
10902 (interactive)
10903 (let (node beg)
10904 (cond
10905 ((bolp)
10906 (back-to-indentation))
10907 ((looking-at "//")
10908 (skip-chars-forward "/ \t"))
10909 ((and (eq (char-after) ?*)
10910 (setq node (js2-comment-at-point))
10911 (memq (js2-comment-node-format node) '(jsdoc block))
10912 (save-excursion
10913 (skip-chars-backward " \t")
10914 (bolp)))
10915 (skip-chars-forward "\* \t"))
10916 (t
10917 (goto-char (point-at-bol))))))
10918
10919 (defun js2-end-of-line ()
10920 "Toggles point between eol and last non-whitespace char in line."
10921 (interactive)
10922 (if (eolp)
10923 (skip-chars-backward " \t")
10924 (goto-char (point-at-eol))))
10925
10926 (defun js2-enter-mirror-mode()
10927 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10928 on insertion."
10929 (interactive)
10930 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10931 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10932 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10933 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10934 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10935 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10936 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10937 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10938
10939 (defun js2-leave-mirror-mode()
10940 "Turns off mirror mode."
10941 (interactive)
10942 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10943 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10944
10945 (defsubst js2-mode-inside-string ()
10946 "Return non-nil if inside a string.
10947 Actually returns the quote character that begins the string."
10948 (let ((parse-state (save-excursion
10949 (syntax-ppss (point)))))
10950 (nth 3 parse-state)))
10951
10952 (defsubst js2-mode-inside-comment-or-string ()
10953 "Return non-nil if inside a comment or string."
10954 (or
10955 (let ((comment-start
10956 (save-excursion
10957 (goto-char (point-at-bol))
10958 (if (re-search-forward "//" (point-at-eol) t)
10959 (match-beginning 0)))))
10960 (and comment-start
10961 (<= comment-start (point))))
10962 (let ((parse-state (save-excursion
10963 (syntax-ppss (point)))))
10964 (or (nth 3 parse-state)
10965 (nth 4 parse-state)))))
10966
10967 (defsubst js2-make-magic-delimiter (delim &optional pos)
10968 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10969 Sets value of `js2-magic' text property to line number at POS."
10970 (propertize delim
10971 'js2-magic (line-number-at-pos pos)
10972 'font-lock-face 'js2-magic-paren-face))
10973
10974 (defun js2-mode-match-delimiter (open close)
10975 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10976 The rule we use, which as far as we can tell is how Eclipse works,
10977 is that we insert the match if we're not in a comment or string,
10978 and the next non-whitespace character is either punctuation or
10979 occurs on another line."
10980 (insert open)
10981 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10982 (not (js2-mode-inside-comment-or-string)))
10983 (save-excursion
10984 (insert (js2-make-magic-delimiter close)))
10985 (when js2-auto-indent-p
10986 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10987 (js2-indent-line)))))
10988
10989 (defun js2-mode-match-bracket ()
10990 "Insert matching bracket."
10991 (interactive)
10992 (js2-mode-match-delimiter "[" "]"))
10993
10994 (defun js2-mode-match-paren ()
10995 "Insert matching paren unless already inserted."
10996 (interactive)
10997 (js2-mode-match-delimiter "(" ")"))
10998
10999 (defun js2-mode-match-curly (arg)
11000 "Insert matching curly-brace.
11001 With prefix arg, no formatting or indentation will occur -- the close-brace
11002 is simply inserted directly at the point."
11003 (interactive "p")
11004 (let (try-pos)
11005 (cond
11006 (current-prefix-arg
11007 (js2-mode-match-delimiter "{" "}"))
11008 ((and js2-auto-insert-catch-block
11009 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
11010 (point-at-bol))
11011 (match-beginning 1))))
11012 (js2-insert-catch-skel try-pos))
11013 (t
11014 ;; Otherwise try to do something smarter.
11015 (insert "{")
11016 (unless (or (not (looking-at "\\s-*$"))
11017 (save-excursion
11018 (skip-chars-forward " \t\r\n")
11019 (and (looking-at "}")
11020 (js2-error-at-point)))
11021 (js2-mode-inside-comment-or-string))
11022 (undo-boundary)
11023 ;; absolutely mystifying bug: when inserting the next "\n",
11024 ;; the buffer-undo-list is given two new entries: the inserted range,
11025 ;; and the incorrect position of the point. It's recorded incorrectly
11026 ;; as being before the opening "{", not after it. But it's recorded
11027 ;; as the correct value if you're debugging `js2-mode-match-curly'
11028 ;; in edebug. I have no idea why it's doing this, but incrementing
11029 ;; the inserted position fixes the problem, so that the undo takes us
11030 ;; back to just after the user-inserted "{".
11031 (insert "\n")
11032 (ignore-errors
11033 (incf (cadr buffer-undo-list)))
11034 (js2-indent-line)
11035 (save-excursion
11036 (insert "\n}")
11037 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11038 (js2-indent-line))))))))
11039
11040 (defun js2-insert-catch-skel (try-pos)
11041 "Complete a try/catch block after inserting a { following a try keyword.
11042 Rationale is that a try always needs a catch or a finally, and the catch is
11043 the more likely of the two.
11044
11045 TRY-POS is the buffer position of the try keyword. The open-curly should
11046 already have been inserted."
11047 (insert "{")
11048 (let ((try-col (save-excursion
11049 (goto-char try-pos)
11050 (current-column))))
11051 (insert "\n")
11052 (undo-boundary)
11053 (js2-indent-line) ;; indent the blank line where cursor will end up
11054 (save-excursion
11055 (insert "\n")
11056 (indent-to try-col)
11057 (insert "} catch (x) {\n\n")
11058 (indent-to try-col)
11059 (insert "}"))))
11060
11061 (defun js2-mode-highlight-magic-parens ()
11062 "Re-highlight magic parens after parsing nukes the 'face prop."
11063 (let ((beg (point-min))
11064 end)
11065 (while (setq beg (next-single-property-change beg 'js2-magic))
11066 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11067 (if (get-text-property beg 'js2-magic)
11068 (js2-with-unmodifying-text-property-changes
11069 (put-text-property beg (or end (1+ beg))
11070 'font-lock-face 'js2-magic-paren-face))))))
11071
11072 (defun js2-mode-mundanify-parens ()
11073 "Clear all magic parens and brackets."
11074 (let ((beg (point-min))
11075 end)
11076 (while (setq beg (next-single-property-change beg 'js2-magic))
11077 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11078 (remove-text-properties beg (or end (1+ beg))
11079 '(js2-magic face)))))
11080
11081 (defsubst js2-match-quote (quote-string)
11082 (let ((start-quote (js2-mode-inside-string)))
11083 (cond
11084 ;; inside a comment - don't do quote-matching, since we can't
11085 ;; reliably figure out if we're in a string inside the comment
11086 ((js2-comment-at-point)
11087 (insert quote-string))
11088 ((not start-quote)
11089 ;; not in string => insert matched quotes
11090 (insert quote-string)
11091 ;; exception: if we're just before a word, don't double it.
11092 (unless (looking-at "[^ \t\r\n]")
11093 (save-excursion
11094 (insert quote-string))))
11095 ((looking-at quote-string)
11096 (if (looking-back "[^\\]\\\\")
11097 (insert quote-string)
11098 (forward-char 1)))
11099 ((and js2-mode-escape-quotes
11100 (save-excursion
11101 (save-match-data
11102 (re-search-forward quote-string (point-at-eol) t))))
11103 ;; inside terminated string, escape quote (unless already escaped)
11104 (insert (if (looking-back "[^\\]\\\\")
11105 quote-string
11106 (concat "\\" quote-string))))
11107 (t
11108 (insert quote-string))))) ; else terminate the string
11109
11110 (defun js2-mode-match-single-quote ()
11111 "Insert matching single-quote."
11112 (interactive)
11113 (let ((parse-status (syntax-ppss (point))))
11114 ;; don't match inside comments, since apostrophe is more common
11115 (if (nth 4 parse-status)
11116 (insert "'")
11117 (js2-match-quote "'"))))
11118
11119 (defun js2-mode-match-double-quote ()
11120 "Insert matching double-quote."
11121 (interactive)
11122 (js2-match-quote "\""))
11123
11124 ;; Eclipse works as follows:
11125 ;; * type an open-paren and it auto-inserts close-paren
11126 ;; - auto-inserted paren gets a green bracket
11127 ;; - green bracket means typing close-paren there will skip it
11128 ;; * if you insert any text on a different line, it turns off
11129 (defun js2-mode-magic-close-paren ()
11130 "Skip over close-paren rather than inserting, where appropriate."
11131 (interactive)
11132 (let* ((here (point))
11133 (parse-status (syntax-ppss here))
11134 (open-pos (nth 1 parse-status))
11135 (close last-input-event)
11136 (open (cond
11137 ((eq close ?\))
11138 ?\()
11139 ((eq close ?\])
11140 ?\[)
11141 ((eq close ?})
11142 ?{)
11143 (t nil))))
11144 (if (and (eq (char-after) close)
11145 (eq open (char-after open-pos))
11146 (js2-same-line open-pos)
11147 (get-text-property here 'js2-magic))
11148 (progn
11149 (remove-text-properties here (1+ here) '(js2-magic face))
11150 (forward-char 1))
11151 (insert-char close 1))
11152 (blink-matching-open)))
11153
11154 (defun js2-mode-wait-for-parse (callback)
11155 "Invoke CALLBACK when parsing is finished.
11156 If parsing is already finished, calls CALLBACK immediately."
11157 (if (not js2-mode-buffer-dirty-p)
11158 (funcall callback)
11159 (push callback js2-mode-pending-parse-callbacks)
11160 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11161
11162 (defun js2-mode-parse-finished ()
11163 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11164 ;; We can't let errors propagate up, since it prevents the
11165 ;; `js2-parse' method from completing normally and returning
11166 ;; the ast, which makes things mysteriously not work right.
11167 (unwind-protect
11168 (dolist (cb js2-mode-pending-parse-callbacks)
11169 (condition-case err
11170 (funcall cb)
11171 (error (message "%s" err))))
11172 (setq js2-mode-pending-parse-callbacks nil)))
11173
11174 (defun js2-mode-flag-region (from to flag)
11175 "Hide or show text from FROM to TO, according to FLAG.
11176 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11177 Returns the created overlay if FLAG is non-nil."
11178 (remove-overlays from to 'invisible 'js2-outline)
11179 (when flag
11180 (let ((o (make-overlay from to)))
11181 (overlay-put o 'invisible 'js2-outline)
11182 (overlay-put o 'isearch-open-invisible
11183 'js2-isearch-open-invisible)
11184 o)))
11185
11186 ;; Function to be set as an outline-isearch-open-invisible' property
11187 ;; to the overlay that makes the outline invisible (see
11188 ;; `js2-mode-flag-region').
11189 (defun js2-isearch-open-invisible (overlay)
11190 ;; We rely on the fact that isearch places point on the matched text.
11191 (js2-mode-show-element))
11192
11193 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11194 "Return cons cell of bounds of folding overlay at POS.
11195 Returns nil if not found."
11196 (let ((overlays (overlays-at (or pos (point))))
11197 o)
11198 (while (and overlays
11199 (not o))
11200 (if (overlay-get (car overlays) 'invisible)
11201 (setq o (car overlays))
11202 (setq overlays (cdr overlays))))
11203 (if o
11204 (cons (overlay-start o) (overlay-end o)))))
11205
11206 (defun js2-mode-function-at-point (&optional pos)
11207 "Return the innermost function node enclosing current point.
11208 Returns nil if point is not in a function."
11209 (let ((node (js2-node-at-point pos)))
11210 (while (and node (not (js2-function-node-p node)))
11211 (setq node (js2-node-parent node)))
11212 (if (js2-function-node-p node)
11213 node)))
11214
11215 (defun js2-mode-toggle-element ()
11216 "Hide or show the foldable element at the point."
11217 (interactive)
11218 (let (comment fn pos)
11219 (save-excursion
11220 (save-match-data
11221 (cond
11222 ;; /* ... */ comment?
11223 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11224 (if (js2-mode-invisible-overlay-bounds
11225 (setq pos (+ 3 (js2-node-abs-pos comment))))
11226 (progn
11227 (goto-char pos)
11228 (js2-mode-show-element))
11229 (js2-mode-hide-element)))
11230 ;; //-comment?
11231 ((save-excursion
11232 (back-to-indentation)
11233 (looking-at js2-mode-//-comment-re))
11234 (js2-mode-toggle-//-comment))
11235 ;; function?
11236 ((setq fn (js2-mode-function-at-point))
11237 (setq pos (and (js2-function-node-body fn)
11238 (js2-node-abs-pos (js2-function-node-body fn))))
11239 (goto-char (1+ pos))
11240 (if (js2-mode-invisible-overlay-bounds)
11241 (js2-mode-show-element)
11242 (js2-mode-hide-element)))
11243 (t
11244 (message "Nothing at point to hide or show")))))))
11245
11246 (defun js2-mode-hide-element ()
11247 "Fold/hide contents of a block, showing ellipses.
11248 Show the hidden text with \\[js2-mode-show-element]."
11249 (interactive)
11250 (if js2-mode-buffer-dirty-p
11251 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11252 (let (node body beg end)
11253 (cond
11254 ((js2-mode-invisible-overlay-bounds)
11255 (message "already hidden"))
11256 (t
11257 (setq node (js2-node-at-point))
11258 (cond
11259 ((js2-block-comment-p node)
11260 (js2-mode-hide-comment node))
11261 (t
11262 (while (and node (not (js2-function-node-p node)))
11263 (setq node (js2-node-parent node)))
11264 (if (and node
11265 (setq body (js2-function-node-body node)))
11266 (progn
11267 (setq beg (js2-node-abs-pos body)
11268 end (+ beg (js2-node-len body)))
11269 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11270 (message "No collapsable element found at point"))))))))
11271
11272 (defun js2-mode-show-element ()
11273 "Show the hidden element at current point."
11274 (interactive)
11275 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11276 (if bounds
11277 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11278 (message "Nothing to un-hide"))))
11279
11280 (defun js2-mode-show-all ()
11281 "Show all of the text in the buffer."
11282 (interactive)
11283 (js2-mode-flag-region (point-min) (point-max) nil))
11284
11285 (defun js2-mode-toggle-hide-functions ()
11286 (interactive)
11287 (if js2-mode-functions-hidden
11288 (js2-mode-show-functions)
11289 (js2-mode-hide-functions)))
11290
11291 (defun js2-mode-hide-functions ()
11292 "Hides all non-nested function bodies in the buffer.
11293 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11294 to open an individual entry."
11295 (interactive)
11296 (if js2-mode-buffer-dirty-p
11297 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11298 (if (null js2-mode-ast)
11299 (message "Oops - parsing failed")
11300 (setq js2-mode-functions-hidden t)
11301 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11302
11303 (defun js2-mode-function-hider (n endp)
11304 (when (not endp)
11305 (let ((tt (js2-node-type n))
11306 body beg end)
11307 (cond
11308 ((and (= tt js2-FUNCTION)
11309 (setq body (js2-function-node-body n)))
11310 (setq beg (js2-node-abs-pos body)
11311 end (+ beg (js2-node-len body)))
11312 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11313 nil) ; don't process children of function
11314 (t
11315 t))))) ; keep processing other AST nodes
11316
11317 (defun js2-mode-show-functions ()
11318 "Un-hide any folded function bodies in the buffer."
11319 (interactive)
11320 (setq js2-mode-functions-hidden nil)
11321 (save-excursion
11322 (goto-char (point-min))
11323 (while (/= (goto-char (next-overlay-change (point)))
11324 (point-max))
11325 (dolist (o (overlays-at (point)))
11326 (when (and (overlay-get o 'invisible)
11327 (not (overlay-get o 'comment)))
11328 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11329
11330 (defun js2-mode-hide-comment (n)
11331 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11332 3 ; /**
11333 2)) ; /*
11334 (beg (+ (js2-node-abs-pos n) head))
11335 (end (- (+ beg (js2-node-len n)) head 2))
11336 (o (js2-mode-flag-region beg end 'hide)))
11337 (overlay-put o 'comment t)))
11338
11339 (defun js2-mode-toggle-hide-comments ()
11340 "Folds all block comments in the buffer.
11341 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11342 to open an individual entry."
11343 (interactive)
11344 (if js2-mode-comments-hidden
11345 (js2-mode-show-comments)
11346 (js2-mode-hide-comments)))
11347
11348 (defun js2-mode-hide-comments ()
11349 (interactive)
11350 (if js2-mode-buffer-dirty-p
11351 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11352 (if (null js2-mode-ast)
11353 (message "Oops - parsing failed")
11354 (setq js2-mode-comments-hidden t)
11355 (dolist (n (js2-ast-root-comments js2-mode-ast))
11356 (let ((format (js2-comment-node-format n)))
11357 (when (js2-block-comment-p n)
11358 (js2-mode-hide-comment n))))
11359 (js2-mode-hide-//-comments)))
11360
11361 (defsubst js2-mode-extend-//-comment (direction)
11362 "Find start or end of a block of similar //-comment lines.
11363 DIRECTION is -1 to look back, 1 to look forward.
11364 INDENT is the indentation level to match.
11365 Returns the end-of-line position of the furthest adjacent
11366 //-comment line with the same indentation as the current line.
11367 If there is no such matching line, returns current end of line."
11368 (let ((pos (point-at-eol))
11369 (indent (current-indentation)))
11370 (save-excursion
11371 (save-match-data
11372 (while (and (zerop (forward-line direction))
11373 (looking-at js2-mode-//-comment-re)
11374 (eq indent (length (match-string 1))))
11375 (setq pos (point-at-eol)))
11376 pos))))
11377
11378 (defun js2-mode-hide-//-comments ()
11379 "Fold adjacent 1-line comments, showing only snippet of first one."
11380 (let (beg end)
11381 (save-excursion
11382 (save-match-data
11383 (goto-char (point-min))
11384 (while (re-search-forward js2-mode-//-comment-re nil t)
11385 (setq beg (point)
11386 end (js2-mode-extend-//-comment 1))
11387 (unless (eq beg end)
11388 (overlay-put (js2-mode-flag-region beg end 'hide)
11389 'comment t))
11390 (goto-char end)
11391 (forward-char 1))))))
11392
11393 (defun js2-mode-toggle-//-comment ()
11394 "Fold or un-fold any multi-line //-comment at point.
11395 Caller should have determined that this line starts with a //-comment."
11396 (let* ((beg (point-at-eol))
11397 (end beg))
11398 (save-excursion
11399 (goto-char end)
11400 (if (js2-mode-invisible-overlay-bounds)
11401 (js2-mode-show-element)
11402 ;; else hide the comment
11403 (setq beg (js2-mode-extend-//-comment -1)
11404 end (js2-mode-extend-//-comment 1))
11405 (unless (eq beg end)
11406 (overlay-put (js2-mode-flag-region beg end 'hide)
11407 'comment t))))))
11408
11409 (defun js2-mode-show-comments ()
11410 "Un-hide any hidden comments, leaving other hidden elements alone."
11411 (interactive)
11412 (setq js2-mode-comments-hidden nil)
11413 (save-excursion
11414 (goto-char (point-min))
11415 (while (/= (goto-char (next-overlay-change (point)))
11416 (point-max))
11417 (dolist (o (overlays-at (point)))
11418 (when (overlay-get o 'comment)
11419 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11420
11421 (defun js2-mode-display-warnings-and-errors ()
11422 "Turn on display of warnings and errors."
11423 (interactive)
11424 (setq js2-mode-show-parse-errors t
11425 js2-mode-show-strict-warnings t)
11426 (js2-reparse 'force))
11427
11428 (defun js2-mode-hide-warnings-and-errors ()
11429 "Turn off display of warnings and errors."
11430 (interactive)
11431 (setq js2-mode-show-parse-errors nil
11432 js2-mode-show-strict-warnings nil)
11433 (js2-reparse 'force))
11434
11435 (defun js2-mode-toggle-warnings-and-errors ()
11436 "Toggle the display of warnings and errors.
11437 Some users don't like having warnings/errors reported while they type."
11438 (interactive)
11439 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11440 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11441 (if (interactive-p)
11442 (message "warnings and errors %s"
11443 (if js2-mode-show-parse-errors
11444 "enabled"
11445 "disabled")))
11446 (js2-reparse 'force))
11447
11448 (defun js2-mode-customize ()
11449 (interactive)
11450 (customize-group 'js2-mode))
11451
11452 (defun js2-mode-forward-sexp (&optional arg)
11453 "Move forward across one statement or balanced expression.
11454 With ARG, do it that many times. Negative arg -N means
11455 move backward across N balanced expressions."
11456 (interactive "p")
11457 (setq arg (or arg 1))
11458 (save-restriction
11459 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11460 (js2-reparse))
11461 (let ((scan-msg "Containing expression ends prematurely")
11462 node (start (point)) pos lp rp child)
11463 (cond
11464 ;; backward-sexp
11465 ;; could probably make this better for some cases:
11466 ;; - if in statement block (e.g. function body), go to parent
11467 ;; - infix exprs like (foo in bar) - maybe go to beginning
11468 ;; of infix expr if in the right-side expression?
11469 ((and arg (minusp arg))
11470 (dotimes (i (- arg))
11471 (js2-backward-sws)
11472 (forward-char -1) ; enter the node we backed up to
11473 (when (setq node (js2-node-at-point (point) t))
11474 (setq pos (js2-node-abs-pos node))
11475 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11476 (setq lp (car parens)
11477 rp (cdr parens))))
11478 (goto-char
11479 (or (when (and lp (> start lp))
11480 (if (and rp (<= start rp))
11481 (if (setq child (js2-node-closest-child node (point) lp t))
11482 (js2-node-abs-pos child)
11483 (goto-char start)
11484 (signal 'scan-error (list scan-msg lp lp)))
11485 lp))
11486 pos
11487 (point-min)))))
11488 (t
11489 ;; forward-sexp
11490 (js2-forward-sws)
11491 (dotimes (i arg)
11492 (js2-forward-sws)
11493 (when (setq node (js2-node-at-point (point) t))
11494 (setq pos (js2-node-abs-pos node))
11495 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11496 (setq lp (car parens)
11497 rp (cdr parens))))
11498 (goto-char
11499 (or (when (and rp (<= start rp))
11500 (if (> start lp)
11501 (if (setq child (js2-node-closest-child node (point) rp))
11502 (js2-node-abs-end child)
11503 (goto-char start)
11504 (signal 'scan-error (list scan-msg rp (1+ rp))))
11505 (1+ rp)))
11506 (and pos
11507 (+ pos
11508 (js2-node-len
11509 (if (js2-expr-stmt-node-p (js2-node-parent node))
11510 ;; stop after the semicolon
11511 (js2-node-parent node)
11512 node))))
11513 (point-max))))))))
11514
11515 (defun js2-mode-forward-sexp-parens (node abs-pos)
11516 (cond
11517 ((or (js2-array-node-p node)
11518 (js2-object-node-p node)
11519 (js2-array-comp-node-p node)
11520 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11521 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11522 ((js2-paren-expr-node-p node)
11523 (let ((lp (js2-node-lp node))
11524 (rp (js2-node-rp node)))
11525 (cons (when lp (+ abs-pos lp))
11526 (when rp (+ abs-pos rp)))))))
11527
11528 (defun js2-node-closest-child (parent point limit &optional before)
11529 (let* ((parent-pos (js2-node-abs-pos parent))
11530 (rpoint (- point parent-pos))
11531 (rlimit (- limit parent-pos))
11532 (min (min rpoint rlimit))
11533 (max (max rpoint rlimit))
11534 found)
11535 (catch 'done
11536 (js2-visit-ast
11537 parent
11538 (lambda (node end-p)
11539 (if (eq node parent)
11540 t
11541 (let ((pos (js2-node-pos node)) ;; Both relative values.
11542 (end (+ (js2-node-pos node) (js2-node-len node))))
11543 (when (and (>= pos min) (<= end max)
11544 (if before (< pos rpoint) (> end rpoint)))
11545 (setq found node))
11546 (when (> end rpoint)
11547 (throw 'done nil)))
11548 nil))))
11549 found))
11550
11551 (defun js2-next-error (&optional arg reset)
11552 "Move to next parse error.
11553 Typically invoked via \\[next-error].
11554 ARG is the number of errors, forward or backward, to move.
11555 RESET means start over from the beginning."
11556 (interactive "p")
11557 (if (or (null js2-mode-ast)
11558 (and (null (js2-ast-root-errors js2-mode-ast))
11559 (null (js2-ast-root-warnings js2-mode-ast))))
11560 (message "No errors")
11561 (when reset
11562 (goto-char (point-min)))
11563 (let* ((errs (copy-sequence
11564 (append (js2-ast-root-errors js2-mode-ast)
11565 (js2-ast-root-warnings js2-mode-ast))))
11566 (continue t)
11567 (start (point))
11568 (count (or arg 1))
11569 (backward (minusp count))
11570 (sorter (if backward '> '<))
11571 (stopper (if backward '< '>))
11572 (count (abs count))
11573 all-errs
11574 err)
11575 ;; sort by start position
11576 (setq errs (sort errs (lambda (e1 e2)
11577 (funcall sorter (second e1) (second e2))))
11578 all-errs errs)
11579 ;; find nth error with pos > start
11580 (while (and errs continue)
11581 (when (funcall stopper (cadar errs) start)
11582 (setq err (car errs))
11583 (if (zerop (decf count))
11584 (setq continue nil)))
11585 (setq errs (cdr errs)))
11586 (if err
11587 (goto-char (second err))
11588 ;; wrap around to first error
11589 (goto-char (second (car all-errs)))
11590 ;; if we were already on it, echo msg again
11591 (if (= (point) start)
11592 (js2-echo-error (point) (point)))))))
11593
11594 (defun js2-down-mouse-3 ()
11595 "Make right-click move the point to the click location.
11596 This makes right-click context menu operations a bit more intuitive.
11597 The point will not move if the region is active, however, to avoid
11598 destroying the region selection."
11599 (interactive)
11600 (when (and js2-move-point-on-right-click
11601 (not mark-active))
11602 (let ((e last-input-event))
11603 (ignore-errors
11604 (goto-char (cadadr e))))))
11605
11606 (defun js2-mode-create-imenu-index ()
11607 "Return an alist for `imenu--index-alist'."
11608 ;; This is built up in `js2-parse-record-imenu' during parsing.
11609 (when js2-mode-ast
11610 ;; if we have an ast but no recorder, they're requesting a rescan
11611 (unless js2-imenu-recorder
11612 (js2-reparse 'force))
11613 (prog1
11614 (js2-build-imenu-index)
11615 (setq js2-imenu-recorder nil
11616 js2-imenu-function-map nil))))
11617
11618 (defun js2-mode-find-tag ()
11619 "Replacement for `find-tag-default'.
11620 `find-tag-default' returns a ridiculous answer inside comments."
11621 (let (beg end)
11622 (js2-with-underscore-as-word-syntax
11623 (save-excursion
11624 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11625 (looking-back "[A-Za-z0-9_$]"))
11626 (setq beg (progn (forward-word -1) (point))
11627 end (progn (forward-word 1) (point)))
11628 (setq beg (progn (forward-word 1) (point))
11629 end (progn (forward-word -1) (point))))
11630 (replace-regexp-in-string
11631 "[\"']" ""
11632 (buffer-substring-no-properties beg end))))))
11633
11634 (defun js2-mode-forward-sibling ()
11635 "Move to the end of the sibling following point in parent.
11636 Returns non-nil if successful, or nil if there was no following sibling."
11637 (let* ((node (js2-node-at-point))
11638 (parent (js2-mode-find-enclosing-fn node))
11639 sib)
11640 (when (setq sib (js2-node-find-child-after (point) parent))
11641 (goto-char (+ (js2-node-abs-pos sib)
11642 (js2-node-len sib))))))
11643
11644 (defun js2-mode-backward-sibling ()
11645 "Move to the beginning of the sibling node preceding point in parent.
11646 Parent is defined as the enclosing script or function."
11647 (let* ((node (js2-node-at-point))
11648 (parent (js2-mode-find-enclosing-fn node))
11649 sib)
11650 (when (setq sib (js2-node-find-child-before (point) parent))
11651 (goto-char (js2-node-abs-pos sib)))))
11652
11653 (defun js2-beginning-of-defun (&optional arg)
11654 "Go to line on which current function starts, and return t on success.
11655 If we're not in a function or already at the beginning of one, go
11656 to beginning of previous script-level element.
11657 With ARG N, do that N times. If N is negative, move forward."
11658 (setq arg (or arg 1))
11659 (if (plusp arg)
11660 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11661 (when (cond
11662 ((js2-function-node-p parent)
11663 (goto-char (js2-node-abs-pos parent)))
11664 (t
11665 (js2-mode-backward-sibling)))
11666 (if (> arg 1)
11667 (js2-beginning-of-defun (1- arg))
11668 t)))
11669 (when (js2-end-of-defun)
11670 (if (>= arg -1)
11671 (js2-beginning-of-defun 1)
11672 (js2-beginning-of-defun (1+ arg))))))
11673
11674 (defun js2-end-of-defun ()
11675 "Go to the char after the last position of the current function
11676 or script-level element."
11677 (let* ((node (js2-node-at-point))
11678 (parent (or (and (js2-function-node-p node) node)
11679 (js2-node-parent-script-or-fn node)))
11680 script)
11681 (unless (js2-function-node-p parent)
11682 ;; use current script-level node, or, if none, the next one
11683 (setq script (or parent node))
11684 (setq parent (js2-node-find-child-before (point) script))
11685 (when (or (null parent)
11686 (>= (point) (+ (js2-node-abs-pos parent)
11687 (js2-node-len parent))))
11688 (setq parent (js2-node-find-child-after (point) script))))
11689 (when parent
11690 (goto-char (+ (js2-node-abs-pos parent)
11691 (js2-node-len parent))))))
11692
11693 (defun js2-mark-defun (&optional allow-extend)
11694 "Put mark at end of this function, point at beginning.
11695 The function marked is the one that contains point.
11696
11697 Interactively, if this command is repeated,
11698 or (in Transient Mark mode) if the mark is active,
11699 it marks the next defun after the ones already marked."
11700 (interactive "p")
11701 (let (extended)
11702 (when (and allow-extend
11703 (or (and (eq last-command this-command) (mark t))
11704 (and transient-mark-mode mark-active)))
11705 (let ((sib (save-excursion
11706 (goto-char (mark))
11707 (if (js2-mode-forward-sibling)
11708 (point))))
11709 node)
11710 (if sib
11711 (progn
11712 (set-mark sib)
11713 (setq extended t))
11714 ;; no more siblings - try extending to enclosing node
11715 (goto-char (mark t)))))
11716 (when (not extended)
11717 (let ((node (js2-node-at-point (point) t)) ; skip comments
11718 ast fn stmt parent beg end)
11719 (when (js2-ast-root-p node)
11720 (setq ast node
11721 node (or (js2-node-find-child-after (point) node)
11722 (js2-node-find-child-before (point) node))))
11723 ;; only mark whole buffer if we can't find any children
11724 (if (null node)
11725 (setq node ast))
11726 (if (js2-function-node-p node)
11727 (setq parent node)
11728 (setq fn (js2-mode-find-enclosing-fn node)
11729 stmt (if (or (null fn)
11730 (js2-ast-root-p fn))
11731 (js2-mode-find-first-stmt node))
11732 parent (or stmt fn)))
11733 (setq beg (js2-node-abs-pos parent)
11734 end (+ beg (js2-node-len parent)))
11735 (push-mark beg)
11736 (goto-char end)
11737 (exchange-point-and-mark)))))
11738
11739 (defun js2-narrow-to-defun ()
11740 "Narrow to the function enclosing point."
11741 (interactive)
11742 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11743 (fn (if (js2-script-node-p node)
11744 node
11745 (js2-mode-find-enclosing-fn node)))
11746 (beg (js2-node-abs-pos fn)))
11747 (unless (js2-ast-root-p fn)
11748 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11749
11750 (provide 'js2-mode)
11751
11752 ;;; js2-mode.el ends here