]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Tweak headers, remove extra vars, set the version to 1.0
[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 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-pretty-multiline-declarations t
238 "Non-nil to line up multiline declarations vertically:
239
240 var a = 10,
241 b = 20,
242 c = 30;
243
244 If the value is not `all', and the first assigned value in
245 declaration is a function/array/object literal spanning several
246 lines, it won't be indented additionally:
247
248 var o = { var bar = 2,
249 foo: 3 vs. o = {
250 }, foo: 3
251 bar = 2; };"
252 :group 'js2-mode
253 :type 'symbol)
254 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
255
256 (defcustom js2-indent-on-enter-key nil
257 "Non-nil to have Enter/Return key indent the line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
259 :type 'boolean
260 :group 'js2-mode)
261
262 (defcustom js2-enter-indents-newline nil
263 "Non-nil to have Enter/Return key indent the newly-inserted line.
264 This is unusual for Emacs modes but common in IDEs like Eclipse."
265 :type 'boolean
266 :group 'js2-mode)
267
268 (defcustom js2-rebind-eol-bol-keys t
269 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
270 If non-nil, bounce between bol/eol and first/last non-whitespace char."
271 :group 'js2-mode
272 :type 'boolean)
273
274 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
275 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
276 Each value in the list is passed to `define-key'."
277 :type 'list
278 :group 'js2-mode)
279
280 (defcustom js2-idle-timer-delay 0.2
281 "Delay in secs before re-parsing after user makes changes.
282 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
283 :type 'number
284 :group 'js2-mode)
285 (make-variable-buffer-local 'js2-idle-timer-delay)
286
287 (defcustom js2-dynamic-idle-timer-adjust 0
288 "Positive to adjust `js2-idle-timer-delay' based on file size.
289 The idea is that for short files, parsing is faster so we can be
290 more responsive to user edits without interfering with editing.
291 The buffer length in characters (typically bytes) is divided by
292 this value and used to multiply `js2-idle-timer-delay' for the
293 buffer. For example, a 21k file and 10k adjust yields 21k/10k
294 == 2, so js2-idle-timer-delay is multiplied by 2.
295 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
296 `js2-idle-timer-delay' is not dependent on the file size."
297 :type 'number
298 :group 'js2-mode)
299
300 (defcustom js2-mode-escape-quotes t
301 "Non-nil to disable automatic quote-escaping inside strings."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-concat-multiline-strings t
306 "Non-nil to automatically turn a newline in mid-string into a
307 string concatenation. When `eol', the '+' will be inserted at the
308 end of the line, otherwise, at the beginning of the next line."
309 :type '(choice (const t) (const eol) (const nil))
310 :group 'js2-mode)
311
312 (defcustom js2-mode-show-parse-errors t
313 "True to highlight parse errors."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-mode-show-strict-warnings t
318 "Non-nil to emit Ecma strict-mode warnings.
319 Some of the warnings can be individually disabled by other flags,
320 even if this flag is non-nil."
321 :type 'boolean
322 :group 'js2-mode)
323
324 (defcustom js2-strict-trailing-comma-warning t
325 "Non-nil to warn about trailing commas in array literals.
326 Ecma-262 forbids them, but many browsers permit them. IE is the
327 big exception, and can produce bugs if you have trailing commas."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-strict-missing-semi-warning t
332 "Non-nil to warn about semicolon auto-insertion after statement.
333 Technically this is legal per Ecma-262, but some style guides disallow
334 depending on it."
335 :type 'boolean
336 :group 'js2-mode)
337
338 (defcustom js2-missing-semi-one-line-override nil
339 "Non-nil to permit missing semicolons in one-line functions.
340 In one-liner functions such as `function identity(x) {return x}'
341 people often omit the semicolon for a cleaner look. If you are
342 such a person, you can suppress the missing-semicolon warning
343 by setting this variable to t."
344 :type 'boolean
345 :group 'js2-mode)
346
347 (defcustom js2-strict-inconsistent-return-warning t
348 "Non-nil to warn about mixing returns with value-returns.
349 It's perfectly legal to have a `return' and a `return foo' in the
350 same function, but it's often an indicator of a bug, and it also
351 interferes with type inference (in systems that support it.)"
352 :type 'boolean
353 :group 'js2-mode)
354
355 (defcustom js2-strict-cond-assign-warning t
356 "Non-nil to warn about expressions like if (a = b).
357 This often should have been '==' instead of '='. If the warning
358 is enabled, you can suppress it on a per-expression basis by
359 parenthesizing the expression, e.g. if ((a = b)) ..."
360 :type 'boolean
361 :group 'js2-mode)
362
363 (defcustom js2-strict-var-redeclaration-warning t
364 "Non-nil to warn about redeclaring variables in a script or function."
365 :type 'boolean
366 :group 'js2-mode)
367
368 (defcustom js2-strict-var-hides-function-arg-warning t
369 "Non-nil to warn about a var decl hiding a function argument."
370 :type 'boolean
371 :group 'js2-mode)
372
373 (defcustom js2-skip-preprocessor-directives nil
374 "Non-nil to treat lines beginning with # as comments.
375 Useful for viewing Mozilla JavaScript source code."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-language-version 200
380 "Configures what JavaScript language version to recognize.
381 Currently versions 150, 160, 170, 180 and 200 are supported,
382 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
383 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
384 yield, and Array comprehensions, and 1.8 adds function closures."
385 :type 'integer
386 :group 'js2-mode)
387
388 (defcustom js2-allow-keywords-as-property-names t
389 "If non-nil, you can use JavaScript keywords as object property names.
390 Examples:
391
392 var foo = {int: 5, while: 6, continue: 7};
393 foo.return = 8;
394
395 Ecma-262 forbids this syntax, but many browsers support it."
396 :type 'boolean
397 :group 'js2-mode)
398
399 (defcustom js2-instanceof-has-side-effects nil
400 "If non-nil, treats the instanceof operator as having side effects.
401 This is useful for xulrunner apps."
402 :type 'boolean
403 :group 'js2-mode)
404
405 (defcustom js2-cleanup-whitespace nil
406 "Non-nil to invoke `delete-trailing-whitespace' before saves."
407 :type 'boolean
408 :group 'js2-mode)
409
410 (defcustom js2-move-point-on-right-click t
411 "Non-nil to move insertion point when you right-click.
412 This makes right-click context menu behavior a bit more intuitive,
413 since menu operations generally apply to the point. The exception
414 is if there is a region selection, in which case the point does -not-
415 move, so cut/copy/paste etc. can work properly.
416
417 Note that IntelliJ moves the point, and Eclipse leaves it alone,
418 so this behavior is customizable."
419 :group 'js2-mode
420 :type 'boolean)
421
422 (defcustom js2-allow-rhino-new-expr-initializer t
423 "Non-nil to support a Rhino's experimental syntactic construct.
424
425 Rhino supports the ability to follow a `new' expression with an object
426 literal, which is used to set additional properties on the new object
427 after calling its constructor. Syntax:
428
429 new <expr> [ ( arglist ) ] [initializer]
430
431 Hence, this expression:
432
433 new Object {a: 1, b: 2}
434
435 results in an Object with properties a=1 and b=2. This syntax is
436 apparently not configurable in Rhino - it's currently always enabled,
437 as of Rhino version 1.7R2."
438 :type 'boolean
439 :group 'js2-mode)
440
441 (defcustom js2-allow-member-expr-as-function-name nil
442 "Non-nil to support experimental Rhino syntax for function names.
443
444 Rhino supports an experimental syntax configured via the Rhino Context
445 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
446
447 function <member-expr> ( [ arg-list ] ) { <body> }
448
449 Where member-expr is a non-parenthesized 'member expression', which
450 is anything at the grammar level of a new-expression or lower, meaning
451 any expression that does not involve infix or unary operators.
452
453 When <member-expr> is not a simple identifier, then it is syntactic
454 sugar for assigning the anonymous function to the <member-expr>. Hence,
455 this code:
456
457 function a.b().c[2] (x, y) { ... }
458
459 is rewritten as:
460
461 a.b().c[2] = function(x, y) {...}
462
463 which doesn't seem particularly useful, but Rhino permits it."
464 :type 'boolean
465 :group 'js2-mode)
466
467 ;; scanner variables
468
469 (defmacro js2-deflocal (name value &optional comment)
470 "Define a buffer-local variable NAME with VALUE and COMMENT."
471 `(progn
472 (defvar ,name ,value ,comment)
473 (make-variable-buffer-local ',name)))
474
475 ;; We record the start and end position of each token.
476 (js2-deflocal js2-token-beg 1)
477 (js2-deflocal js2-token-end -1)
478
479 (defvar js2-EOF_CHAR -1
480 "Represents end of stream. Distinct from js2-EOF token type.")
481
482 ;; I originally used symbols to represent tokens, but Rhino uses
483 ;; ints and then sets various flag bits in them, so ints it is.
484 ;; The upshot is that we need a `js2-' prefix in front of each name.
485 (defvar js2-ERROR -1)
486 (defvar js2-EOF 0)
487 (defvar js2-EOL 1)
488 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
489 (defvar js2-LEAVEWITH 3)
490 (defvar js2-RETURN 4)
491 (defvar js2-GOTO 5)
492 (defvar js2-IFEQ 6)
493 (defvar js2-IFNE 7)
494 (defvar js2-SETNAME 8)
495 (defvar js2-BITOR 9)
496 (defvar js2-BITXOR 10)
497 (defvar js2-BITAND 11)
498 (defvar js2-EQ 12)
499 (defvar js2-NE 13)
500 (defvar js2-LT 14)
501 (defvar js2-LE 15)
502 (defvar js2-GT 16)
503 (defvar js2-GE 17)
504 (defvar js2-LSH 18)
505 (defvar js2-RSH 19)
506 (defvar js2-URSH 20)
507 (defvar js2-ADD 21) ; infix plus
508 (defvar js2-SUB 22) ; infix minus
509 (defvar js2-MUL 23)
510 (defvar js2-DIV 24)
511 (defvar js2-MOD 25)
512 (defvar js2-NOT 26)
513 (defvar js2-BITNOT 27)
514 (defvar js2-POS 28) ; unary plus
515 (defvar js2-NEG 29) ; unary minus
516 (defvar js2-NEW 30)
517 (defvar js2-DELPROP 31)
518 (defvar js2-TYPEOF 32)
519 (defvar js2-GETPROP 33)
520 (defvar js2-GETPROPNOWARN 34)
521 (defvar js2-SETPROP 35)
522 (defvar js2-GETELEM 36)
523 (defvar js2-SETELEM 37)
524 (defvar js2-CALL 38)
525 (defvar js2-NAME 39) ; an identifier
526 (defvar js2-NUMBER 40)
527 (defvar js2-STRING 41)
528 (defvar js2-NULL 42)
529 (defvar js2-THIS 43)
530 (defvar js2-FALSE 44)
531 (defvar js2-TRUE 45)
532 (defvar js2-SHEQ 46) ; shallow equality (===)
533 (defvar js2-SHNE 47) ; shallow inequality (!==)
534 (defvar js2-REGEXP 48)
535 (defvar js2-BINDNAME 49)
536 (defvar js2-THROW 50)
537 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
538 (defvar js2-IN 52)
539 (defvar js2-INSTANCEOF 53)
540 (defvar js2-LOCAL_LOAD 54)
541 (defvar js2-GETVAR 55)
542 (defvar js2-SETVAR 56)
543 (defvar js2-CATCH_SCOPE 57)
544 (defvar js2-ENUM_INIT_KEYS 58)
545 (defvar js2-ENUM_INIT_VALUES 59)
546 (defvar js2-ENUM_INIT_ARRAY 60)
547 (defvar js2-ENUM_NEXT 61)
548 (defvar js2-ENUM_ID 62)
549 (defvar js2-THISFN 63)
550 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
551 (defvar js2-ARRAYLIT 65) ; array literal
552 (defvar js2-OBJECTLIT 66) ; object literal
553 (defvar js2-GET_REF 67) ; *reference
554 (defvar js2-SET_REF 68) ; *reference = something
555 (defvar js2-DEL_REF 69) ; delete reference
556 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
557 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
558 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
559
560 ;; XML support
561 (defvar js2-DEFAULTNAMESPACE 73)
562 (defvar js2-ESCXMLATTR 74)
563 (defvar js2-ESCXMLTEXT 75)
564 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
565 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
566 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
567 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
568
569 (defvar js2-first-bytecode js2-ENTERWITH)
570 (defvar js2-last-bytecode js2-REF_NS_NAME)
571
572 (defvar js2-TRY 80)
573 (defvar js2-SEMI 81) ; semicolon
574 (defvar js2-LB 82) ; left and right brackets
575 (defvar js2-RB 83)
576 (defvar js2-LC 84) ; left and right curly-braces
577 (defvar js2-RC 85)
578 (defvar js2-LP 86) ; left and right parens
579 (defvar js2-RP 87)
580 (defvar js2-COMMA 88) ; comma operator
581
582 (defvar js2-ASSIGN 89) ; simple assignment (=)
583 (defvar js2-ASSIGN_BITOR 90) ; |=
584 (defvar js2-ASSIGN_BITXOR 91) ; ^=
585 (defvar js2-ASSIGN_BITAND 92) ; &=
586 (defvar js2-ASSIGN_LSH 93) ; <<=
587 (defvar js2-ASSIGN_RSH 94) ; >>=
588 (defvar js2-ASSIGN_URSH 95) ; >>>=
589 (defvar js2-ASSIGN_ADD 96) ; +=
590 (defvar js2-ASSIGN_SUB 97) ; -=
591 (defvar js2-ASSIGN_MUL 98) ; *=
592 (defvar js2-ASSIGN_DIV 99) ; /=
593 (defvar js2-ASSIGN_MOD 100) ; %=
594
595 (defvar js2-first-assign js2-ASSIGN)
596 (defvar js2-last-assign js2-ASSIGN_MOD)
597
598 (defvar js2-HOOK 101) ; conditional (?:)
599 (defvar js2-COLON 102)
600 (defvar js2-OR 103) ; logical or (||)
601 (defvar js2-AND 104) ; logical and (&&)
602 (defvar js2-INC 105) ; increment/decrement (++ --)
603 (defvar js2-DEC 106)
604 (defvar js2-DOT 107) ; member operator (.)
605 (defvar js2-FUNCTION 108) ; function keyword
606 (defvar js2-EXPORT 109) ; export keyword
607 (defvar js2-IMPORT 110) ; import keyword
608 (defvar js2-IF 111) ; if keyword
609 (defvar js2-ELSE 112) ; else keyword
610 (defvar js2-SWITCH 113) ; switch keyword
611 (defvar js2-CASE 114) ; case keyword
612 (defvar js2-DEFAULT 115) ; default keyword
613 (defvar js2-WHILE 116) ; while keyword
614 (defvar js2-DO 117) ; do keyword
615 (defvar js2-FOR 118) ; for keyword
616 (defvar js2-BREAK 119) ; break keyword
617 (defvar js2-CONTINUE 120) ; continue keyword
618 (defvar js2-VAR 121) ; var keyword
619 (defvar js2-WITH 122) ; with keyword
620 (defvar js2-CATCH 123) ; catch keyword
621 (defvar js2-FINALLY 124) ; finally keyword
622 (defvar js2-VOID 125) ; void keyword
623 (defvar js2-RESERVED 126) ; reserved keywords
624
625 (defvar js2-EMPTY 127)
626
627 ;; Types used for the parse tree - never returned by scanner.
628
629 (defvar js2-BLOCK 128) ; statement block
630 (defvar js2-LABEL 129) ; label
631 (defvar js2-TARGET 130)
632 (defvar js2-LOOP 131)
633 (defvar js2-EXPR_VOID 132) ; expression statement in functions
634 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
635 (defvar js2-JSR 134)
636 (defvar js2-SCRIPT 135) ; top-level node for entire script
637 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
638 (defvar js2-USE_STACK 137)
639 (defvar js2-SETPROP_OP 138) ; x.y op= something
640 (defvar js2-SETELEM_OP 139) ; x[y] op= something
641 (defvar js2-LOCAL_BLOCK 140)
642 (defvar js2-SET_REF_OP 141) ; *reference op= something
643
644 ;; For XML support:
645 (defvar js2-DOTDOT 142) ; member operator (..)
646 (defvar js2-COLONCOLON 143) ; namespace::name
647 (defvar js2-XML 144) ; XML type
648 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
649 (defvar js2-XMLATTR 146) ; @
650 (defvar js2-XMLEND 147)
651
652 ;; Optimizer-only tokens
653 (defvar js2-TO_OBJECT 148)
654 (defvar js2-TO_DOUBLE 149)
655
656 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
657 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
658 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
659 (defvar js2-CONST 153)
660 (defvar js2-SETCONST 154)
661 (defvar js2-SETCONSTVAR 155)
662 (defvar js2-ARRAYCOMP 156)
663 (defvar js2-LETEXPR 157)
664 (defvar js2-WITHEXPR 158)
665 (defvar js2-DEBUGGER 159)
666
667 (defvar js2-COMMENT 160)
668 (defvar js2-ENUM 161) ; for "enum" reserved word
669 (defvar js2-TRIPLEDOT 162) ; for rest parameter
670
671 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
672
673 (defconst js2-debug-print-trees nil)
674
675 ;; Rhino accepts any string or stream as input. Emacs character
676 ;; processing works best in buffers, so we'll assume the input is a
677 ;; buffer. JavaScript strings can be copied into temp buffers before
678 ;; scanning them.
679
680 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
681 ;; They're the Emacs equivalent of instance variables, more or less.
682
683 (js2-deflocal js2-ts-dirty-line nil
684 "Token stream buffer-local variable.
685 Indicates stuff other than whitespace since start of line.")
686
687 (js2-deflocal js2-ts-regexp-flags nil
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-string ""
691 "Token stream buffer-local variable.
692 Last string scanned.")
693
694 (js2-deflocal js2-ts-number nil
695 "Token stream buffer-local variable.
696 Last literal number scanned.")
697
698 (js2-deflocal js2-ts-hit-eof nil
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-line-start 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-lineno 1
705 "Token stream buffer-local variable.")
706
707 (js2-deflocal js2-ts-line-end-char -1
708 "Token stream buffer-local variable.")
709
710 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
711 "Token stream buffer-local variable.
712 Current scan position.")
713
714 (js2-deflocal js2-ts-is-xml-attribute nil
715 "Token stream buffer-local variable.")
716
717 (js2-deflocal js2-ts-xml-is-tag-content nil
718 "Token stream buffer-local variable.")
719
720 (js2-deflocal js2-ts-xml-open-tags-count 0
721 "Token stream buffer-local variable.")
722
723 (js2-deflocal js2-ts-string-buffer nil
724 "Token stream buffer-local variable.
725 List of chars built up while scanning various tokens.")
726
727 (js2-deflocal js2-ts-comment-type nil
728 "Token stream buffer-local variable.")
729
730 ;;; Parser variables
731
732 (js2-deflocal js2-parsed-errors nil
733 "List of errors produced during scanning/parsing.")
734
735 (js2-deflocal js2-parsed-warnings nil
736 "List of warnings produced during scanning/parsing.")
737
738 (js2-deflocal js2-recover-from-parse-errors t
739 "Non-nil to continue parsing after a syntax error.
740
741 In recovery mode, the AST will be built in full, and any error
742 nodes will be flagged with appropriate error information. If
743 this flag is nil, a syntax error will result in an error being
744 signaled.
745
746 The variable is automatically buffer-local, because different
747 modes that use the parser will need different settings.")
748
749 (js2-deflocal js2-parse-hook nil
750 "List of callbacks for receiving parsing progress.")
751
752 (defvar js2-parse-finished-hook nil
753 "List of callbacks to notify when parsing finishes.
754 Not called if parsing was interrupted.")
755
756 (js2-deflocal js2-is-eval-code nil
757 "True if we're evaluating code in a string.
758 If non-nil, the tokenizer will record the token text, and the AST nodes
759 will record their source text. Off by default for IDE modes, since the
760 text is available in the buffer.")
761
762 (defvar js2-parse-ide-mode t
763 "Non-nil if the parser is being used for `js2-mode'.
764 If non-nil, the parser will set text properties for fontification
765 and the syntax table. The value should be nil when using the
766 parser as a frontend to an interpreter or byte compiler.")
767
768 ;;; Parser instance variables (buffer-local vars for js2-parse)
769
770 (defconst js2-clear-ti-mask #xFFFF
771 "Mask to clear token information bits.")
772
773 (defconst js2-ti-after-eol (lsh 1 16)
774 "Flag: first token of the source line.")
775
776 (defconst js2-ti-check-label (lsh 1 17)
777 "Flag: indicates to check for label.")
778
779 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
780
781 (js2-deflocal js2-compiler-generate-debug-info t)
782 (js2-deflocal js2-compiler-use-dynamic-scope nil)
783 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
784 (js2-deflocal js2-compiler-xml-available t)
785 (js2-deflocal js2-compiler-optimization-level 0)
786 (js2-deflocal js2-compiler-generating-source t)
787 (js2-deflocal js2-compiler-strict-mode nil)
788 (js2-deflocal js2-compiler-report-warning-as-error nil)
789 (js2-deflocal js2-compiler-generate-observer-count nil)
790 (js2-deflocal js2-compiler-activation-names nil)
791
792 ;; SKIP: sourceURI
793
794 ;; There's a compileFunction method in Context.java - may need it.
795 (js2-deflocal js2-called-by-compile-function nil
796 "True if `js2-parse' was called by `js2-compile-function'.
797 Will only be used when we finish implementing the interpreter.")
798
799 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
800
801 (js2-deflocal js2-current-flagged-token js2-EOF)
802 (js2-deflocal js2-current-token js2-EOF)
803
804 ;; SKIP: node factory - we're going to just call functions directly,
805 ;; and eventually go to a unified AST format.
806
807 (js2-deflocal js2-nesting-of-function 0)
808
809 (js2-deflocal js2-recorded-identifiers nil
810 "Tracks identifiers found during parsing.")
811
812 (js2-deflocal js2-is-in-destructuring nil
813 "True while parsing destructuring expression.")
814
815 (defcustom js2-global-externs nil
816 "A list of any extern names you'd like to consider always declared.
817 This list is global and is used by all js2-mode files.
818 You can create buffer-local externs list using `js2-additional-externs'.
819
820 There is also a buffer-local variable `js2-default-externs',
821 which is initialized by default to include the Ecma-262 externs
822 and the standard browser externs. The three lists are all
823 checked during highlighting."
824 :type 'list
825 :group 'js2-mode)
826
827 (js2-deflocal js2-default-externs nil
828 "Default external declarations.
829
830 These are currently only used for highlighting undeclared variables,
831 which only worries about top-level (unqualified) references.
832 As js2-mode's processing improves, we will flesh out this list.
833
834 The initial value is set to `js2-ecma-262-externs', unless you
835 have set `js2-include-browser-externs', in which case the browser
836 externs are also included.
837
838 See `js2-additional-externs' for more information.")
839
840 (defcustom js2-include-browser-externs t
841 "Non-nil to include browser externs in the master externs list.
842 If you work on JavaScript files that are not intended for browsers,
843 such as Mozilla Rhino server-side JavaScript, set this to nil.
844 You can always include them on a per-file basis by calling
845 `js2-add-browser-externs' from a function on `js2-mode-hook'.
846
847 See `js2-additional-externs' for more information about externs."
848 :type 'boolean
849 :group 'js2-mode)
850
851 (defcustom js2-include-rhino-externs t
852 "Non-nil to include Mozilla Rhino externs in the master externs list.
853 See `js2-additional-externs' for more information about externs."
854 :type 'boolean
855 :group 'js2-mode)
856
857 (defcustom js2-include-gears-externs t
858 "Non-nil to include Google Gears externs in the master externs list.
859 See `js2-additional-externs' for more information about externs."
860 :type 'boolean
861 :group 'js2-mode)
862
863 (js2-deflocal js2-additional-externs nil
864 "A buffer-local list of additional external declarations.
865 It is used to decide whether variables are considered undeclared
866 for purposes of highlighting.
867
868 Each entry is a lisp string. The string should be the fully qualified
869 name of an external entity. All externs should be added to this list,
870 so that as js2-mode's processing improves it can take advantage of them.
871
872 You may want to declare your externs in three ways.
873 First, you can add externs that are valid for all your JavaScript files.
874 You should probably do this by adding them to `js2-global-externs', which
875 is a global list used for all js2-mode files.
876
877 Next, you can add a function to `js2-mode-hook' that adds additional
878 externs appropriate for the specific file, perhaps based on its path.
879 These should go in `js2-additional-externs', which is buffer-local.
880
881 Finally, you can add a function to `js2-post-parse-callbacks',
882 which is called after parsing completes, and `root' is bound to
883 the root of the parse tree. At this stage you can set up an AST
884 node visitor using `js2-visit-ast' and examine the parse tree
885 for specific import patterns that may imply the existence of
886 other externs, possibly tied to your build system. These should also
887 be added to `js2-additional-externs'.
888
889 Your post-parse callback may of course also use the simpler and
890 faster (but perhaps less robust) approach of simply scanning the
891 buffer text for your imports, using regular expressions.")
892
893 ;; SKIP: decompiler
894 ;; SKIP: encoded-source
895
896 ;;; The following variables are per-function and should be saved/restored
897 ;;; during function parsing...
898
899 (js2-deflocal js2-current-script-or-fn nil)
900 (js2-deflocal js2-current-scope nil)
901 (js2-deflocal js2-nesting-of-with 0)
902 (js2-deflocal js2-label-set nil
903 "An alist mapping label names to nodes.")
904
905 (js2-deflocal js2-loop-set nil)
906 (js2-deflocal js2-loop-and-switch-set nil)
907 (js2-deflocal js2-has-return-value nil)
908 (js2-deflocal js2-end-flags 0)
909
910 ;;; ...end of per function variables
911
912 ;; Without 2-token lookahead, labels are a problem.
913 ;; These vars store the token info of the last matched name,
914 ;; iff it wasn't the last matched token. Only valid in some contexts.
915 (defvar js2-prev-name-token-start nil)
916 (defvar js2-prev-name-token-string nil)
917
918 (defsubst js2-save-name-token-data (pos name)
919 (setq js2-prev-name-token-start pos
920 js2-prev-name-token-string name))
921
922 ;; These flags enumerate the possible ways a statement/function can
923 ;; terminate. These flags are used by endCheck() and by the Parser to
924 ;; detect inconsistent return usage.
925 ;;
926 ;; END_UNREACHED is reserved for code paths that are assumed to always be
927 ;; able to execute (example: throw, continue)
928 ;;
929 ;; END_DROPS_OFF indicates if the statement can transfer control to the
930 ;; next one. Statement such as return dont. A compound statement may have
931 ;; some branch that drops off control to the next statement.
932 ;;
933 ;; END_RETURNS indicates that the statement can return (without arguments)
934 ;; END_RETURNS_VALUE indicates that the statement can return a value.
935 ;;
936 ;; A compound statement such as
937 ;; if (condition) {
938 ;; return value;
939 ;; }
940 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
941
942 (defconst js2-end-unreached #x0)
943 (defconst js2-end-drops-off #x1)
944 (defconst js2-end-returns #x2)
945 (defconst js2-end-returns-value #x4)
946 (defconst js2-end-yields #x8)
947
948 ;; Rhino awkwardly passes a statementLabel parameter to the
949 ;; statementHelper() function, the main statement parser, which
950 ;; is then used by quite a few of the sub-parsers. We just make
951 ;; it a buffer-local variable and make sure it's cleaned up properly.
952 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
953
954 ;; Similarly, Rhino passes an inForInit boolean through about half
955 ;; the expression parsers. We use a dynamically-scoped variable,
956 ;; which makes it easier to funcall the parsers individually without
957 ;; worrying about whether they take the parameter or not.
958 (js2-deflocal js2-in-for-init nil)
959 (js2-deflocal js2-temp-name-counter 0)
960 (js2-deflocal js2-parse-stmt-count 0)
961
962 (defsubst js2-get-next-temp-name ()
963 (format "$%d" (incf js2-temp-name-counter)))
964
965 (defvar js2-parse-interruptable-p t
966 "Set this to nil to force parse to continue until finished.
967 This will mostly be useful for interpreters.")
968
969 (defvar js2-statements-per-pause 50
970 "Pause after this many statements to check for user input.
971 If user input is pending, stop the parse and discard the tree.
972 This makes for a smoother user experience for large files.
973 You may have to wait a second or two before the highlighting
974 and error-reporting appear, but you can always type ahead if
975 you wish. This appears to be more or less how Eclipse, IntelliJ
976 and other editors work.")
977
978 (js2-deflocal js2-record-comments t
979 "Instructs the scanner to record comments in `js2-scanned-comments'.")
980
981 (js2-deflocal js2-scanned-comments nil
982 "List of all comments from the current parse.")
983
984 (defcustom js2-mode-indent-inhibit-undo nil
985 "Non-nil to disable collection of Undo information when indenting lines.
986 Some users have requested this behavior. It's nil by default because
987 other Emacs modes don't work this way."
988 :type 'boolean
989 :group 'js2-mode)
990
991 (defcustom js2-mode-indent-ignore-first-tab nil
992 "If non-nil, ignore first TAB keypress if we look indented properly.
993 It's fairly common for users to navigate to an already-indented line
994 and press TAB for reassurance that it's been indented. For this class
995 of users, we want the first TAB press on a line to be ignored if the
996 line is already indented to one of the precomputed alternatives.
997
998 This behavior is only partly implemented. If you TAB-indent a line,
999 navigate to another line, and then navigate back, it fails to clear
1000 the last-indented variable, so it thinks you've already hit TAB once,
1001 and performs the indent. A full solution would involve getting on the
1002 point-motion hooks for the entire buffer. If we come across another
1003 use cases that requires watching point motion, I'll consider doing it.
1004
1005 If you set this variable to nil, then the TAB key will always change
1006 the indentation of the current line, if more than one alternative
1007 indentation spot exists."
1008 :type 'boolean
1009 :group 'js2-mode)
1010
1011 (defvar js2-indent-hook nil
1012 "A hook for user-defined indentation rules.
1013
1014 Functions on this hook should expect two arguments: (LIST INDEX)
1015 The LIST argument is the list of computed indentation points for
1016 the current line. INDEX is the list index of the indentation point
1017 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1018 indent function is not going to change the current line indentation.
1019
1020 If a hook function on this list returns a non-nil value, then
1021 `js2-bounce-indent' assumes the hook function has performed its own
1022 indentation, and will do nothing. If all hook functions on the list
1023 return nil, then `js2-bounce-indent' will use its computed indentation
1024 and reindent the line.
1025
1026 When hook functions on this hook list are called, the variable
1027 `js2-mode-ast' may or may not be set, depending on whether the
1028 parse tree is available. If the variable is nil, you can pass a
1029 callback to `js2-mode-wait-for-parse', and your callback will be
1030 called after the new parse tree is built. This can take some time
1031 in large files.")
1032
1033 (defface js2-warning-face
1034 `((((class color) (background light))
1035 (:underline "orange"))
1036 (((class color) (background dark))
1037 (:underline "orange"))
1038 (t (:underline t)))
1039 "Face for JavaScript warnings."
1040 :group 'js2-mode)
1041
1042 (defface js2-error-face
1043 `((((class color) (background light))
1044 (:foreground "red"))
1045 (((class color) (background dark))
1046 (:foreground "red"))
1047 (t (:foreground "red")))
1048 "Face for JavaScript errors."
1049 :group 'js2-mode)
1050
1051 (defface js2-jsdoc-tag-face
1052 '((t :foreground "SlateGray"))
1053 "Face used to highlight @whatever tags in jsdoc comments."
1054 :group 'js2-mode)
1055
1056 (defface js2-jsdoc-type-face
1057 '((t :foreground "SteelBlue"))
1058 "Face used to highlight {FooBar} types in jsdoc comments."
1059 :group 'js2-mode)
1060
1061 (defface js2-jsdoc-value-face
1062 '((t :foreground "PeachPuff3"))
1063 "Face used to highlight tag values in jsdoc comments."
1064 :group 'js2-mode)
1065
1066 (defface js2-function-param-face
1067 '((t :foreground "SeaGreen"))
1068 "Face used to highlight function parameters in javascript."
1069 :group 'js2-mode)
1070
1071 (defface js2-instance-member-face
1072 '((t :foreground "DarkOrchid"))
1073 "Face used to highlight instance variables in javascript.
1074 Not currently used."
1075 :group 'js2-mode)
1076
1077 (defface js2-private-member-face
1078 '((t :foreground "PeachPuff3"))
1079 "Face used to highlight calls to private methods in javascript.
1080 Not currently used."
1081 :group 'js2-mode)
1082
1083 (defface js2-private-function-call-face
1084 '((t :foreground "goldenrod"))
1085 "Face used to highlight calls to private functions in javascript.
1086 Not currently used."
1087 :group 'js2-mode)
1088
1089 (defface js2-jsdoc-html-tag-name-face
1090 (if js2-emacs22
1091 '((((class color) (min-colors 88) (background light))
1092 (:foreground "rosybrown"))
1093 (((class color) (min-colors 8) (background dark))
1094 (:foreground "yellow"))
1095 (((class color) (min-colors 8) (background light))
1096 (:foreground "magenta")))
1097 '((((type tty pc) (class color) (background light))
1098 (:foreground "magenta"))
1099 (((type tty pc) (class color) (background dark))
1100 (:foreground "yellow"))
1101 (t (:foreground "RosyBrown"))))
1102 "Face used to highlight jsdoc html tag names"
1103 :group 'js2-mode)
1104
1105 (defface js2-jsdoc-html-tag-delimiter-face
1106 (if js2-emacs22
1107 '((((class color) (min-colors 88) (background light))
1108 (:foreground "dark khaki"))
1109 (((class color) (min-colors 8) (background dark))
1110 (:foreground "green"))
1111 (((class color) (min-colors 8) (background light))
1112 (:foreground "green")))
1113 '((((type tty pc) (class color) (background light))
1114 (:foreground "green"))
1115 (((type tty pc) (class color) (background dark))
1116 (:foreground "green"))
1117 (t (:foreground "dark khaki"))))
1118 "Face used to highlight brackets in jsdoc html tags."
1119 :group 'js2-mode)
1120
1121 (defface js2-magic-paren-face
1122 '((t :underline t))
1123 "Face used to color parens that will be auto-overwritten."
1124 :group 'js2-mode)
1125
1126 (defcustom js2-post-parse-callbacks nil
1127 "A list of callback functions invoked after parsing finishes.
1128 Currently, the main use for this function is to add synthetic
1129 declarations to `js2-recorded-identifiers', which see."
1130 :type 'list
1131 :group 'js2-mode)
1132
1133 (defface js2-external-variable-face
1134 '((t :foreground "orange"))
1135 "Face used to highlight undeclared variable identifiers.
1136 An undeclared variable is any variable not declared with var or let
1137 in the current scope or any lexically enclosing scope. If you use
1138 such a variable, then you are either expecting it to originate from
1139 another file, or you've got a potential bug."
1140 :group 'js2-mode)
1141
1142 (defcustom js2-highlight-external-variables t
1143 "Non-nil to highlight undeclared variable identifiers."
1144 :type 'boolean
1145 :group 'js2-mode)
1146
1147 (defcustom js2-auto-insert-catch-block t
1148 "Non-nil to insert matching catch block on open-curly after `try'."
1149 :type 'boolean
1150 :group 'js2-mode)
1151
1152 (defvar js2-mode-map
1153 (let ((map (make-sparse-keymap))
1154 keys)
1155 (define-key map [mouse-1] #'js2-mode-show-node)
1156 (define-key map (kbd "C-m") #'js2-enter-key)
1157 (when js2-rebind-eol-bol-keys
1158 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1159 (define-key map (kbd "C-e") #'js2-end-of-line))
1160 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1161 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1162 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1163 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1164 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1165 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1166 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1167 (define-key map (kbd "C-c C-`") #'js2-next-error)
1168 (define-key map (or (car (where-is-internal #'mark-defun))
1169 (kbd "M-C-h"))
1170 #'js2-mark-defun)
1171 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1172 (kbd "C-x nd"))
1173 #'js2-narrow-to-defun)
1174 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1175 (when js2-auto-indent-p
1176 (mapc (lambda (key)
1177 (define-key map key #'js2-insert-and-indent))
1178 js2-electric-keys))
1179 (when js2-bounce-indent-p
1180 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1181
1182 (define-key map [menu-bar javascript]
1183 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1184
1185 (define-key map [menu-bar javascript customize-js2-mode]
1186 '(menu-item "Customize js2-mode" js2-mode-customize
1187 :help "Customize the behavior of this mode"))
1188
1189 (define-key map [menu-bar javascript js2-force-refresh]
1190 '(menu-item "Force buffer refresh" js2-mode-reset
1191 :help "Re-parse the buffer from scratch"))
1192
1193 (define-key map [menu-bar javascript separator-2]
1194 '("--"))
1195
1196 (define-key map [menu-bar javascript next-error]
1197 '(menu-item "Next warning or error" js2-next-error
1198 :enabled (and js2-mode-ast
1199 (or (js2-ast-root-errors js2-mode-ast)
1200 (js2-ast-root-warnings js2-mode-ast)))
1201 :help "Move to next warning or error"))
1202
1203 (define-key map [menu-bar javascript display-errors]
1204 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1205 :visible (not js2-mode-show-parse-errors)
1206 :help "Turn on display of warnings and errors"))
1207
1208 (define-key map [menu-bar javascript hide-errors]
1209 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1210 :visible js2-mode-show-parse-errors
1211 :help "Turn off display of warnings and errors"))
1212
1213 (define-key map [menu-bar javascript separator-1]
1214 '("--"))
1215
1216 (define-key map [menu-bar javascript js2-toggle-function]
1217 '(menu-item "Show/collapse element" js2-mode-toggle-element
1218 :help "Hide or show function body or comment"))
1219
1220 (define-key map [menu-bar javascript show-comments]
1221 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1222 :visible js2-mode-comments-hidden
1223 :help "Expand all hidden block comments"))
1224
1225 (define-key map [menu-bar javascript hide-comments]
1226 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1227 :visible (not js2-mode-comments-hidden)
1228 :help "Show block comments as /*...*/"))
1229
1230 (define-key map [menu-bar javascript show-all-functions]
1231 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1232 :visible js2-mode-functions-hidden
1233 :help "Expand all hidden function bodies"))
1234
1235 (define-key map [menu-bar javascript hide-all-functions]
1236 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1237 :visible (not js2-mode-functions-hidden)
1238 :help "Show {...} for all top-level function bodies"))
1239
1240 map)
1241 "Keymap used in `js2-mode' buffers.")
1242
1243 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1244
1245 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1246 "Matches a //-comment line. Must be first non-whitespace on line.
1247 First match-group is the leading whitespace.")
1248
1249 (defvar js2-mode-hook nil)
1250
1251 (js2-deflocal js2-mode-ast nil "Private variable.")
1252 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1253 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1254 (js2-deflocal js2-mode-parsing nil "Private variable.")
1255 (js2-deflocal js2-mode-node-overlay nil)
1256
1257 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1258 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1259
1260 (js2-deflocal js2-mode-fontifications nil "Private variable")
1261 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1262 (js2-deflocal js2-imenu-recorder nil "Private variable")
1263 (js2-deflocal js2-imenu-function-map nil "Private variable")
1264
1265 (defvar js2-paragraph-start
1266 "\\(@[a-zA-Z]+\\>\\|$\\)")
1267
1268 ;; Note that we also set a 'c-in-sws text property in html comments,
1269 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1270 (defvar js2-syntactic-ws-start
1271 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1272
1273 (defvar js2-syntactic-ws-end
1274 "\\s \\|[\n\r/]\\|\\s!")
1275
1276 (defvar js2-syntactic-eol
1277 (concat "\\s *\\(/\\*[^*\n\r]*"
1278 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1279 "\\*+/\\s *\\)*"
1280 "\\(//\\|/\\*[^*\n\r]*"
1281 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1282 "\\|\\\\$\\|$\\)")
1283 "Copied from `java-mode'. Needed for some cc-engine functions.")
1284
1285 (defvar js2-comment-prefix-regexp
1286 "//+\\|\\**")
1287
1288 (defvar js2-comment-start-skip
1289 "\\(//+\\|/\\*+\\)\\s *")
1290
1291 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1292 "Non-nil to emit status messages during parsing.")
1293
1294 (defvar js2-mode-functions-hidden nil "private variable")
1295 (defvar js2-mode-comments-hidden nil "private variable")
1296
1297 (defvar js2-mode-syntax-table
1298 (let ((table (make-syntax-table)))
1299 (c-populate-syntax-table table)
1300 table)
1301 "Syntax table used in js2-mode buffers.")
1302
1303 (defvar js2-mode-abbrev-table nil
1304 "Abbrev table in use in `js2-mode' buffers.")
1305 (define-abbrev-table 'js2-mode-abbrev-table ())
1306
1307 (defvar js2-mode-pending-parse-callbacks nil
1308 "List of functions waiting to be notified that parse is finished.")
1309
1310 (defvar js2-mode-last-indented-line -1)
1311
1312 ;;; Localizable error and warning messages
1313
1314 ;; Messages are copied from Rhino's Messages.properties.
1315 ;; Many of the Java-specific messages have been elided.
1316 ;; Add any js2-specific ones at the end, so we can keep
1317 ;; this file synced with changes to Rhino's.
1318
1319 (defvar js2-message-table
1320 (make-hash-table :test 'equal :size 250)
1321 "Contains localized messages for js2-mode.")
1322
1323 ;; TODO(stevey): construct this table at compile-time.
1324 (defmacro js2-msg (key &rest strings)
1325 `(puthash ,key (funcall #'concat ,@strings)
1326 js2-message-table))
1327
1328 (defun js2-get-msg (msg-key)
1329 "Look up a localized message.
1330 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1331 the correct number of ARGS must be provided."
1332 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1333 (args (if (listp msg-key) (cdr msg-key)))
1334 (msg (gethash key js2-message-table)))
1335 (if msg
1336 (apply #'format msg args)
1337 key))) ; default to showing the key
1338
1339 (js2-msg "msg.dup.parms"
1340 "Duplicate parameter name '%s'.")
1341
1342 (js2-msg "msg.too.big.jump"
1343 "Program too complex: jump offset too big.")
1344
1345 (js2-msg "msg.too.big.index"
1346 "Program too complex: internal index exceeds 64K limit.")
1347
1348 (js2-msg "msg.while.compiling.fn"
1349 "Encountered code generation error while compiling function '%s': %s")
1350
1351 (js2-msg "msg.while.compiling.script"
1352 "Encountered code generation error while compiling script: %s")
1353
1354 ;; Context
1355 (js2-msg "msg.ctor.not.found"
1356 "Constructor for '%s' not found.")
1357
1358 (js2-msg "msg.not.ctor"
1359 "'%s' is not a constructor.")
1360
1361 ;; FunctionObject
1362 (js2-msg "msg.varargs.ctor"
1363 "Method or constructor '%s' must be static "
1364 "with the signature (Context cx, Object[] args, "
1365 "Function ctorObj, boolean inNewExpr) "
1366 "to define a variable arguments constructor.")
1367
1368 (js2-msg "msg.varargs.fun"
1369 "Method '%s' must be static with the signature "
1370 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1371 "to define a variable arguments function.")
1372
1373 (js2-msg "msg.incompat.call"
1374 "Method '%s' called on incompatible object.")
1375
1376 (js2-msg "msg.bad.parms"
1377 "Unsupported parameter type '%s' in method '%s'.")
1378
1379 (js2-msg "msg.bad.method.return"
1380 "Unsupported return type '%s' in method '%s'.")
1381
1382 (js2-msg "msg.bad.ctor.return"
1383 "Construction of objects of type '%s' is not supported.")
1384
1385 (js2-msg "msg.no.overload"
1386 "Method '%s' occurs multiple times in class '%s'.")
1387
1388 (js2-msg "msg.method.not.found"
1389 "Method '%s' not found in '%s'.")
1390
1391 ;; IRFactory
1392
1393 (js2-msg "msg.bad.for.in.lhs"
1394 "Invalid left-hand side of for..in loop.")
1395
1396 (js2-msg "msg.mult.index"
1397 "Only one variable allowed in for..in loop.")
1398
1399 (js2-msg "msg.bad.for.in.destruct"
1400 "Left hand side of for..in loop must be an array of "
1401 "length 2 to accept key/value pair.")
1402
1403 (js2-msg "msg.cant.convert"
1404 "Can't convert to type '%s'.")
1405
1406 (js2-msg "msg.bad.assign.left"
1407 "Invalid assignment left-hand side.")
1408
1409 (js2-msg "msg.bad.decr"
1410 "Invalid decerement operand.")
1411
1412 (js2-msg "msg.bad.incr"
1413 "Invalid increment operand.")
1414
1415 (js2-msg "msg.bad.yield"
1416 "yield must be in a function.")
1417
1418 (js2-msg "msg.yield.parenthesized"
1419 "yield expression must be parenthesized.")
1420
1421 ;; NativeGlobal
1422 (js2-msg "msg.cant.call.indirect"
1423 "Function '%s' must be called directly, and not by way of a "
1424 "function of another name.")
1425
1426 (js2-msg "msg.eval.nonstring"
1427 "Calling eval() with anything other than a primitive "
1428 "string value will simply return the value. "
1429 "Is this what you intended?")
1430
1431 (js2-msg "msg.eval.nonstring.strict"
1432 "Calling eval() with anything other than a primitive "
1433 "string value is not allowed in strict mode.")
1434
1435 (js2-msg "msg.bad.destruct.op"
1436 "Invalid destructuring assignment operator")
1437
1438 ;; NativeCall
1439 (js2-msg "msg.only.from.new"
1440 "'%s' may only be invoked from a `new' expression.")
1441
1442 (js2-msg "msg.deprec.ctor"
1443 "The '%s' constructor is deprecated.")
1444
1445 ;; NativeFunction
1446 (js2-msg "msg.no.function.ref.found"
1447 "no source found to decompile function reference %s")
1448
1449 (js2-msg "msg.arg.isnt.array"
1450 "second argument to Function.prototype.apply must be an array")
1451
1452 ;; NativeGlobal
1453 (js2-msg "msg.bad.esc.mask"
1454 "invalid string escape mask")
1455
1456 ;; NativeRegExp
1457 (js2-msg "msg.bad.quant"
1458 "Invalid quantifier %s")
1459
1460 (js2-msg "msg.overlarge.backref"
1461 "Overly large back reference %s")
1462
1463 (js2-msg "msg.overlarge.min"
1464 "Overly large minimum %s")
1465
1466 (js2-msg "msg.overlarge.max"
1467 "Overly large maximum %s")
1468
1469 (js2-msg "msg.zero.quant"
1470 "Zero quantifier %s")
1471
1472 (js2-msg "msg.max.lt.min"
1473 "Maximum %s less than minimum")
1474
1475 (js2-msg "msg.unterm.quant"
1476 "Unterminated quantifier %s")
1477
1478 (js2-msg "msg.unterm.paren"
1479 "Unterminated parenthetical %s")
1480
1481 (js2-msg "msg.unterm.class"
1482 "Unterminated character class %s")
1483
1484 (js2-msg "msg.bad.range"
1485 "Invalid range in character class.")
1486
1487 (js2-msg "msg.trail.backslash"
1488 "Trailing \\ in regular expression.")
1489
1490 (js2-msg "msg.re.unmatched.right.paren"
1491 "unmatched ) in regular expression.")
1492
1493 (js2-msg "msg.no.regexp"
1494 "Regular expressions are not available.")
1495
1496 (js2-msg "msg.bad.backref"
1497 "back-reference exceeds number of capturing parentheses.")
1498
1499 (js2-msg "msg.bad.regexp.compile"
1500 "Only one argument may be specified if the first "
1501 "argument to RegExp.prototype.compile is a RegExp object.")
1502
1503 ;; Parser
1504 (js2-msg "msg.got.syntax.errors"
1505 "Compilation produced %s syntax errors.")
1506
1507 (js2-msg "msg.var.redecl"
1508 "TypeError: redeclaration of var %s.")
1509
1510 (js2-msg "msg.const.redecl"
1511 "TypeError: redeclaration of const %s.")
1512
1513 (js2-msg "msg.let.redecl"
1514 "TypeError: redeclaration of variable %s.")
1515
1516 (js2-msg "msg.parm.redecl"
1517 "TypeError: redeclaration of formal parameter %s.")
1518
1519 (js2-msg "msg.fn.redecl"
1520 "TypeError: redeclaration of function %s.")
1521
1522 (js2-msg "msg.let.decl.not.in.block"
1523 "SyntaxError: let declaration not directly within block")
1524
1525 ;; NodeTransformer
1526 (js2-msg "msg.dup.label"
1527 "duplicated label")
1528
1529 (js2-msg "msg.undef.label"
1530 "undefined label")
1531
1532 (js2-msg "msg.bad.break"
1533 "unlabelled break must be inside loop or switch")
1534
1535 (js2-msg "msg.continue.outside"
1536 "continue must be inside loop")
1537
1538 (js2-msg "msg.continue.nonloop"
1539 "continue can only use labels of iteration statements")
1540
1541 (js2-msg "msg.bad.throw.eol"
1542 "Line terminator is not allowed between the throw "
1543 "keyword and throw expression.")
1544
1545 (js2-msg "msg.no.paren.parms"
1546 "missing ( before function parameters.")
1547
1548 (js2-msg "msg.no.parm"
1549 "missing formal parameter")
1550
1551 (js2-msg "msg.no.paren.after.parms"
1552 "missing ) after formal parameters")
1553
1554 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1555 "parameter without default follows parameter with default")
1556
1557 (js2-msg "msg.param.after.rest" ; added by js2-mode
1558 "parameter after rest parameter")
1559
1560 (js2-msg "msg.no.brace.body"
1561 "missing '{' before function body")
1562
1563 (js2-msg "msg.no.brace.after.body"
1564 "missing } after function body")
1565
1566 (js2-msg "msg.no.paren.cond"
1567 "missing ( before condition")
1568
1569 (js2-msg "msg.no.paren.after.cond"
1570 "missing ) after condition")
1571
1572 (js2-msg "msg.no.semi.stmt"
1573 "missing ; before statement")
1574
1575 (js2-msg "msg.missing.semi"
1576 "missing ; after statement")
1577
1578 (js2-msg "msg.no.name.after.dot"
1579 "missing name after . operator")
1580
1581 (js2-msg "msg.no.name.after.coloncolon"
1582 "missing name after :: operator")
1583
1584 (js2-msg "msg.no.name.after.dotdot"
1585 "missing name after .. operator")
1586
1587 (js2-msg "msg.no.name.after.xmlAttr"
1588 "missing name after .@")
1589
1590 (js2-msg "msg.no.bracket.index"
1591 "missing ] in index expression")
1592
1593 (js2-msg "msg.no.paren.switch"
1594 "missing ( before switch expression")
1595
1596 (js2-msg "msg.no.paren.after.switch"
1597 "missing ) after switch expression")
1598
1599 (js2-msg "msg.no.brace.switch"
1600 "missing '{' before switch body")
1601
1602 (js2-msg "msg.bad.switch"
1603 "invalid switch statement")
1604
1605 (js2-msg "msg.no.colon.case"
1606 "missing : after case expression")
1607
1608 (js2-msg "msg.double.switch.default"
1609 "double default label in the switch statement")
1610
1611 (js2-msg "msg.no.while.do"
1612 "missing while after do-loop body")
1613
1614 (js2-msg "msg.no.paren.for"
1615 "missing ( after for")
1616
1617 (js2-msg "msg.no.semi.for"
1618 "missing ; after for-loop initializer")
1619
1620 (js2-msg "msg.no.semi.for.cond"
1621 "missing ; after for-loop condition")
1622
1623 (js2-msg "msg.in.after.for.name"
1624 "missing in or of after for")
1625
1626 (js2-msg "msg.no.paren.for.ctrl"
1627 "missing ) after for-loop control")
1628
1629 (js2-msg "msg.no.paren.with"
1630 "missing ( before with-statement object")
1631
1632 (js2-msg "msg.no.paren.after.with"
1633 "missing ) after with-statement object")
1634
1635 (js2-msg "msg.no.paren.after.let"
1636 "missing ( after let")
1637
1638 (js2-msg "msg.no.paren.let"
1639 "missing ) after variable list")
1640
1641 (js2-msg "msg.no.curly.let"
1642 "missing } after let statement")
1643
1644 (js2-msg "msg.bad.return"
1645 "invalid return")
1646
1647 (js2-msg "msg.no.brace.block"
1648 "missing } in compound statement")
1649
1650 (js2-msg "msg.bad.label"
1651 "invalid label")
1652
1653 (js2-msg "msg.bad.var"
1654 "missing variable name")
1655
1656 (js2-msg "msg.bad.var.init"
1657 "invalid variable initialization")
1658
1659 (js2-msg "msg.no.colon.cond"
1660 "missing : in conditional expression")
1661
1662 (js2-msg "msg.no.paren.arg"
1663 "missing ) after argument list")
1664
1665 (js2-msg "msg.no.bracket.arg"
1666 "missing ] after element list")
1667
1668 (js2-msg "msg.bad.prop"
1669 "invalid property id")
1670
1671 (js2-msg "msg.no.colon.prop"
1672 "missing : after property id")
1673
1674 (js2-msg "msg.no.brace.prop"
1675 "missing } after property list")
1676
1677 (js2-msg "msg.no.paren"
1678 "missing ) in parenthetical")
1679
1680 (js2-msg "msg.reserved.id"
1681 "identifier is a reserved word")
1682
1683 (js2-msg "msg.no.paren.catch"
1684 "missing ( before catch-block condition")
1685
1686 (js2-msg "msg.bad.catchcond"
1687 "invalid catch block condition")
1688
1689 (js2-msg "msg.catch.unreachable"
1690 "any catch clauses following an unqualified catch are unreachable")
1691
1692 (js2-msg "msg.no.brace.try"
1693 "missing '{' before try block")
1694
1695 (js2-msg "msg.no.brace.catchblock"
1696 "missing '{' before catch-block body")
1697
1698 (js2-msg "msg.try.no.catchfinally"
1699 "'try' without 'catch' or 'finally'")
1700
1701 (js2-msg "msg.no.return.value"
1702 "function %s does not always return a value")
1703
1704 (js2-msg "msg.anon.no.return.value"
1705 "anonymous function does not always return a value")
1706
1707 (js2-msg "msg.return.inconsistent"
1708 "return statement is inconsistent with previous usage")
1709
1710 (js2-msg "msg.generator.returns"
1711 "TypeError: generator function '%s' returns a value")
1712
1713 (js2-msg "msg.anon.generator.returns"
1714 "TypeError: anonymous generator function returns a value")
1715
1716 (js2-msg "msg.syntax"
1717 "syntax error")
1718
1719 (js2-msg "msg.unexpected.eof"
1720 "Unexpected end of file")
1721
1722 (js2-msg "msg.XML.bad.form"
1723 "illegally formed XML syntax")
1724
1725 (js2-msg "msg.XML.not.available"
1726 "XML runtime not available")
1727
1728 (js2-msg "msg.too.deep.parser.recursion"
1729 "Too deep recursion while parsing")
1730
1731 (js2-msg "msg.no.side.effects"
1732 "Code has no side effects")
1733
1734 (js2-msg "msg.extra.trailing.comma"
1735 "Trailing comma is not legal in an ECMA-262 object initializer")
1736
1737 (js2-msg "msg.array.trailing.comma"
1738 "Trailing comma yields different behavior across browsers")
1739
1740 (js2-msg "msg.equal.as.assign"
1741 (concat "Test for equality (==) mistyped as assignment (=)?"
1742 " (parenthesize to suppress warning)"))
1743
1744 (js2-msg "msg.var.hides.arg"
1745 "Variable %s hides argument")
1746
1747 (js2-msg "msg.destruct.assign.no.init"
1748 "Missing = in destructuring declaration")
1749
1750 ;; ScriptRuntime
1751 (js2-msg "msg.no.properties"
1752 "%s has no properties.")
1753
1754 (js2-msg "msg.invalid.iterator"
1755 "Invalid iterator value")
1756
1757 (js2-msg "msg.iterator.primitive"
1758 "__iterator__ returned a primitive value")
1759
1760 (js2-msg "msg.assn.create.strict"
1761 "Assignment to undeclared variable %s")
1762
1763 (js2-msg "msg.ref.undefined.prop"
1764 "Reference to undefined property '%s'")
1765
1766 (js2-msg "msg.prop.not.found"
1767 "Property %s not found.")
1768
1769 (js2-msg "msg.invalid.type"
1770 "Invalid JavaScript value of type %s")
1771
1772 (js2-msg "msg.primitive.expected"
1773 "Primitive type expected (had %s instead)")
1774
1775 (js2-msg "msg.namespace.expected"
1776 "Namespace object expected to left of :: (found %s instead)")
1777
1778 (js2-msg "msg.null.to.object"
1779 "Cannot convert null to an object.")
1780
1781 (js2-msg "msg.undef.to.object"
1782 "Cannot convert undefined to an object.")
1783
1784 (js2-msg "msg.cyclic.value"
1785 "Cyclic %s value not allowed.")
1786
1787 (js2-msg "msg.is.not.defined"
1788 "'%s' is not defined.")
1789
1790 (js2-msg "msg.undef.prop.read"
1791 "Cannot read property '%s' from %s")
1792
1793 (js2-msg "msg.undef.prop.write"
1794 "Cannot set property '%s' of %s to '%s'")
1795
1796 (js2-msg "msg.undef.prop.delete"
1797 "Cannot delete property '%s' of %s")
1798
1799 (js2-msg "msg.undef.method.call"
1800 "Cannot call method '%s' of %s")
1801
1802 (js2-msg "msg.undef.with"
1803 "Cannot apply 'with' to %s")
1804
1805 (js2-msg "msg.isnt.function"
1806 "%s is not a function, it is %s.")
1807
1808 (js2-msg "msg.isnt.function.in"
1809 "Cannot call property %s in object %s. "
1810 "It is not a function, it is '%s'.")
1811
1812 (js2-msg "msg.function.not.found"
1813 "Cannot find function %s.")
1814
1815 (js2-msg "msg.function.not.found.in"
1816 "Cannot find function %s in object %s.")
1817
1818 (js2-msg "msg.isnt.xml.object"
1819 "%s is not an xml object.")
1820
1821 (js2-msg "msg.no.ref.to.get"
1822 "%s is not a reference to read reference value.")
1823
1824 (js2-msg "msg.no.ref.to.set"
1825 "%s is not a reference to set reference value to %s.")
1826
1827 (js2-msg "msg.no.ref.from.function"
1828 "Function %s can not be used as the left-hand "
1829 "side of assignment or as an operand of ++ or -- operator.")
1830
1831 (js2-msg "msg.bad.default.value"
1832 "Object's getDefaultValue() method returned an object.")
1833
1834 (js2-msg "msg.instanceof.not.object"
1835 "Can't use instanceof on a non-object.")
1836
1837 (js2-msg "msg.instanceof.bad.prototype"
1838 "'prototype' property of %s is not an object.")
1839
1840 (js2-msg "msg.bad.radix"
1841 "illegal radix %s.")
1842
1843 ;; ScriptableObject
1844 (js2-msg "msg.default.value"
1845 "Cannot find default value for object.")
1846
1847 (js2-msg "msg.zero.arg.ctor"
1848 "Cannot load class '%s' which has no zero-parameter constructor.")
1849
1850 (js2-msg "msg.ctor.multiple.parms"
1851 "Can't define constructor or class %s since more than "
1852 "one constructor has multiple parameters.")
1853
1854 (js2-msg "msg.extend.scriptable"
1855 "%s must extend ScriptableObject in order to define property %s.")
1856
1857 (js2-msg "msg.bad.getter.parms"
1858 "In order to define a property, getter %s must have zero "
1859 "parameters or a single ScriptableObject parameter.")
1860
1861 (js2-msg "msg.obj.getter.parms"
1862 "Expected static or delegated getter %s to take "
1863 "a ScriptableObject parameter.")
1864
1865 (js2-msg "msg.getter.static"
1866 "Getter and setter must both be static or neither be static.")
1867
1868 (js2-msg "msg.setter.return"
1869 "Setter must have void return type: %s")
1870
1871 (js2-msg "msg.setter2.parms"
1872 "Two-parameter setter must take a ScriptableObject as "
1873 "its first parameter.")
1874
1875 (js2-msg "msg.setter1.parms"
1876 "Expected single parameter setter for %s")
1877
1878 (js2-msg "msg.setter2.expected"
1879 "Expected static or delegated setter %s to take two parameters.")
1880
1881 (js2-msg "msg.setter.parms"
1882 "Expected either one or two parameters for setter.")
1883
1884 (js2-msg "msg.setter.bad.type"
1885 "Unsupported parameter type '%s' in setter '%s'.")
1886
1887 (js2-msg "msg.add.sealed"
1888 "Cannot add a property to a sealed object: %s.")
1889
1890 (js2-msg "msg.remove.sealed"
1891 "Cannot remove a property from a sealed object: %s.")
1892
1893 (js2-msg "msg.modify.sealed"
1894 "Cannot modify a property of a sealed object: %s.")
1895
1896 (js2-msg "msg.modify.readonly"
1897 "Cannot modify readonly property: %s.")
1898
1899 ;; TokenStream
1900 (js2-msg "msg.missing.exponent"
1901 "missing exponent")
1902
1903 (js2-msg "msg.caught.nfe"
1904 "number format error")
1905
1906 (js2-msg "msg.unterminated.string.lit"
1907 "unterminated string literal")
1908
1909 (js2-msg "msg.unterminated.comment"
1910 "unterminated comment")
1911
1912 (js2-msg "msg.unterminated.re.lit"
1913 "unterminated regular expression literal")
1914
1915 (js2-msg "msg.invalid.re.flag"
1916 "invalid flag after regular expression")
1917
1918 (js2-msg "msg.no.re.input.for"
1919 "no input for %s")
1920
1921 (js2-msg "msg.illegal.character"
1922 "illegal character")
1923
1924 (js2-msg "msg.invalid.escape"
1925 "invalid Unicode escape sequence")
1926
1927 (js2-msg "msg.bad.namespace"
1928 "not a valid default namespace statement. "
1929 "Syntax is: default xml namespace = EXPRESSION;")
1930
1931 ;; TokensStream warnings
1932 (js2-msg "msg.bad.octal.literal"
1933 "illegal octal literal digit %s; "
1934 "interpreting it as a decimal digit")
1935
1936 (js2-msg "msg.reserved.keyword"
1937 "illegal usage of future reserved keyword %s; "
1938 "interpreting it as ordinary identifier")
1939
1940 (js2-msg "msg.script.is.not.constructor"
1941 "Script objects are not constructors.")
1942
1943 ;; Arrays
1944 (js2-msg "msg.arraylength.bad"
1945 "Inappropriate array length.")
1946
1947 ;; Arrays
1948 (js2-msg "msg.arraylength.too.big"
1949 "Array length %s exceeds supported capacity limit.")
1950
1951 ;; URI
1952 (js2-msg "msg.bad.uri"
1953 "Malformed URI sequence.")
1954
1955 ;; Number
1956 (js2-msg "msg.bad.precision"
1957 "Precision %s out of range.")
1958
1959 ;; NativeGenerator
1960 (js2-msg "msg.send.newborn"
1961 "Attempt to send value to newborn generator")
1962
1963 (js2-msg "msg.already.exec.gen"
1964 "Already executing generator")
1965
1966 (js2-msg "msg.StopIteration.invalid"
1967 "StopIteration may not be changed to an arbitrary object.")
1968
1969 ;; Interpreter
1970 (js2-msg "msg.yield.closing"
1971 "Yield from closing generator")
1972
1973 ;;; Utilities
1974
1975 (defun js2-delete-if (predicate list)
1976 "Remove all items satisfying PREDICATE in LIST."
1977 (loop for item in list
1978 if (not (funcall predicate item))
1979 collect item))
1980
1981 (defun js2-position (element list)
1982 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1983 Returns nil if element is not found in the list."
1984 (let ((count 0)
1985 found)
1986 (while (and list (not found))
1987 (if (eq element (car list))
1988 (setq found t)
1989 (setq count (1+ count)
1990 list (cdr list))))
1991 (if found count)))
1992
1993 (defun js2-find-if (predicate list)
1994 "Find first item satisfying PREDICATE in LIST."
1995 (let (result)
1996 (while (and list (not result))
1997 (if (funcall predicate (car list))
1998 (setq result (car list)))
1999 (setq list (cdr list)))
2000 result))
2001
2002 (defmacro js2-time (form)
2003 "Evaluate FORM, discard result, and return elapsed time in sec"
2004 (declare (debug t))
2005 (let ((beg (make-symbol "--js2-time-beg--"))
2006 (delta (make-symbol "--js2-time-end--")))
2007 `(let ((,beg (current-time))
2008 ,delta)
2009 ,form
2010 (/ (truncate (* (- (float-time (current-time))
2011 (float-time ,beg))
2012 10000))
2013 10000.0))))
2014
2015 (defsubst js2-same-line (pos)
2016 "Return t if POS is on the same line as current point."
2017 (and (>= pos (point-at-bol))
2018 (<= pos (point-at-eol))))
2019
2020 (defsubst js2-same-line-2 (p1 p2)
2021 "Return t if p1 is on the same line as p2."
2022 (save-excursion
2023 (goto-char p1)
2024 (js2-same-line p2)))
2025
2026 (defun js2-code-bug ()
2027 "Signal an error when we encounter an unexpected code path."
2028 (error "failed assertion"))
2029
2030 (defsubst js2-record-text-property (beg end prop value)
2031 "Record a text property to set when parsing finishes."
2032 (push (list beg end prop value) js2-mode-deferred-properties))
2033
2034 ;; I'd like to associate errors with nodes, but for now the
2035 ;; easiest thing to do is get the context info from the last token.
2036 (defsubst js2-record-parse-error (msg &optional arg pos len)
2037 (push (list (list msg arg)
2038 (or pos js2-token-beg)
2039 (or len (- js2-token-end js2-token-beg)))
2040 js2-parsed-errors))
2041
2042 (defsubst js2-report-error (msg &optional msg-arg pos len)
2043 "Signal a syntax error or record a parse error."
2044 (if js2-recover-from-parse-errors
2045 (js2-record-parse-error msg msg-arg pos len)
2046 (signal 'js2-syntax-error
2047 (list msg
2048 js2-ts-lineno
2049 (save-excursion
2050 (goto-char js2-ts-cursor)
2051 (current-column))
2052 js2-ts-hit-eof))))
2053
2054 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2055 (if js2-compiler-report-warning-as-error
2056 (js2-report-error msg msg-arg pos len)
2057 (push (list (list msg msg-arg)
2058 (or pos js2-token-beg)
2059 (or len (- js2-token-end js2-token-beg)))
2060 js2-parsed-warnings)))
2061
2062 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2063 (if js2-compiler-strict-mode
2064 (js2-report-warning msg-id msg-arg beg
2065 (and beg end (- end beg)))))
2066
2067 (put 'js2-syntax-error 'error-conditions
2068 '(error syntax-error js2-syntax-error))
2069 (put 'js2-syntax-error 'error-message "Syntax error")
2070
2071 (put 'js2-parse-error 'error-conditions
2072 '(error parse-error js2-parse-error))
2073 (put 'js2-parse-error 'error-message "Parse error")
2074
2075 (defmacro js2-clear-flag (flags flag)
2076 `(setq ,flags (logand ,flags (lognot ,flag))))
2077
2078 (defmacro js2-set-flag (flags flag)
2079 "Logical-or FLAG into FLAGS."
2080 `(setq ,flags (logior ,flags ,flag)))
2081
2082 (defsubst js2-flag-set-p (flags flag)
2083 (/= 0 (logand flags flag)))
2084
2085 (defsubst js2-flag-not-set-p (flags flag)
2086 (zerop (logand flags flag)))
2087
2088 ;; Stolen shamelessly from James Clark's nxml-mode.
2089 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2090 "Evaluate BODY without any text property changes modifying the buffer.
2091 Any text properties changes happen as usual but the changes are not treated as
2092 modifications to the buffer."
2093 (declare (indent 0) (debug t))
2094 (let ((modified (make-symbol "modified")))
2095 `(let ((,modified (buffer-modified-p))
2096 (inhibit-read-only t)
2097 (inhibit-modification-hooks t)
2098 (buffer-undo-list t)
2099 (deactivate-mark nil)
2100 ;; Apparently these avoid file locking problems.
2101 (buffer-file-name nil)
2102 (buffer-file-truename nil))
2103 (unwind-protect
2104 (progn ,@body)
2105 (unless ,modified
2106 (restore-buffer-modified-p nil))))))
2107
2108 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2109 "Evaluate BODY with the _ character set to be word-syntax."
2110 (declare (indent 0) (debug t))
2111 (let ((old-syntax (make-symbol "old-syntax")))
2112 `(let ((,old-syntax (string (char-syntax ?_))))
2113 (unwind-protect
2114 (progn
2115 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2116 ,@body)
2117 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2118
2119 (defsubst js2-char-uppercase-p (c)
2120 "Return t if C is an uppercase character.
2121 Handles unicode and latin chars properly."
2122 (/= c (downcase c)))
2123
2124 (defsubst js2-char-lowercase-p (c)
2125 "Return t if C is an uppercase character.
2126 Handles unicode and latin chars properly."
2127 (/= c (upcase c)))
2128
2129 ;;; AST struct and function definitions
2130
2131 ;; flags for ast node property 'member-type (used for e4x operators)
2132 (defvar js2-property-flag #x1 "property access: element is valid name")
2133 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2134 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2135
2136 (defsubst js2-relpos (pos anchor)
2137 "Convert POS to be relative to ANCHOR.
2138 If POS is nil, returns nil."
2139 (and pos (- pos anchor)))
2140
2141 (defsubst js2-make-pad (indent)
2142 (if (zerop indent)
2143 ""
2144 (make-string (* indent js2-basic-offset) ? )))
2145
2146 (defsubst js2-visit-ast (node callback)
2147 "Visit every node in ast NODE with visitor CALLBACK.
2148
2149 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2150 called twice: once to visit the node, and again after all the node's
2151 children have been processed. The END-P argument is nil on the first
2152 call and non-nil on the second call. The return value of the callback
2153 affects the traversal: if non-nil, the children of NODE are processed.
2154 If the callback returns nil, or if the node has no children, then the
2155 callback is called immediately with a non-nil END-P argument.
2156
2157 The node traversal is approximately lexical-order, although there
2158 are currently no guarantees around this."
2159 (if node
2160 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2161 ;; visit the node
2162 (when (funcall callback node nil)
2163 ;; visit the kids
2164 (cond
2165 ((eq vfunc 'js2-visit-none)
2166 nil) ; don't even bother calling it
2167 ;; Each AST node type has to define a `js2-visitor' function
2168 ;; that takes a node and a callback, and calls `js2-visit-ast'
2169 ;; on each child of the node.
2170 (vfunc
2171 (funcall vfunc node callback))
2172 (t
2173 (error "%s does not define a visitor-traversal function"
2174 (aref node 0)))))
2175 ;; call the end-visit
2176 (funcall callback node t))))
2177
2178 (defstruct (js2-node
2179 (:constructor nil)) ; abstract
2180 "Base AST node type."
2181 (type -1) ; token type
2182 (pos -1) ; start position of this AST node in parsed input
2183 (len 1) ; num characters spanned by the node
2184 props ; optional node property list (an alist)
2185 parent) ; link to parent node; null for root
2186
2187 (defsubst js2-node-get-prop (node prop &optional default)
2188 (or (cadr (assoc prop (js2-node-props node))) default))
2189
2190 (defsubst js2-node-set-prop (node prop value)
2191 (setf (js2-node-props node)
2192 (cons (list prop value) (js2-node-props node))))
2193
2194 (defsubst js2-fixup-starts (n nodes)
2195 "Adjust the start positions of NODES to be relative to N.
2196 Any node in the list may be nil, for convenience."
2197 (dolist (node nodes)
2198 (when node
2199 (setf (js2-node-pos node) (- (js2-node-pos node)
2200 (js2-node-pos n))))))
2201
2202 (defsubst js2-node-add-children (parent &rest nodes)
2203 "Set parent node of NODES to PARENT, and return PARENT.
2204 Does nothing if we're not recording parent links.
2205 If any given node in NODES is nil, doesn't record that link."
2206 (js2-fixup-starts parent nodes)
2207 (dolist (node nodes)
2208 (and node
2209 (setf (js2-node-parent node) parent))))
2210
2211 ;; Non-recursive since it's called a frightening number of times.
2212 (defsubst js2-node-abs-pos (n)
2213 (let ((pos (js2-node-pos n)))
2214 (while (setq n (js2-node-parent n))
2215 (setq pos (+ pos (js2-node-pos n))))
2216 pos))
2217
2218 (defsubst js2-node-abs-end (n)
2219 "Return absolute buffer position of end of N."
2220 (+ (js2-node-abs-pos n) (js2-node-len n)))
2221
2222 ;; It's important to make sure block nodes have a lisp list for the
2223 ;; child nodes, to limit printing recursion depth in an AST that
2224 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2225 ;; a sufficiently large vector tree.
2226
2227 (defstruct (js2-block-node
2228 (:include js2-node)
2229 (:constructor nil)
2230 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2231 (pos js2-token-beg)
2232 len
2233 props
2234 kids)))
2235 "A block of statements."
2236 kids) ; a lisp list of the child statement nodes
2237
2238 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2239 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2240
2241 (defsubst js2-visit-block (ast callback)
2242 "Visit the `js2-block-node' children of AST."
2243 (dolist (kid (js2-block-node-kids ast))
2244 (js2-visit-ast kid callback)))
2245
2246 (defun js2-print-block (n i)
2247 (let ((pad (js2-make-pad i)))
2248 (insert pad "{\n")
2249 (dolist (kid (js2-block-node-kids n))
2250 (js2-print-ast kid (1+ i)))
2251 (insert pad "}")))
2252
2253 (defstruct (js2-scope
2254 (:include js2-block-node)
2255 (:constructor nil)
2256 (:constructor make-js2-scope (&key (type js2-BLOCK)
2257 (pos js2-token-beg)
2258 len
2259 kids)))
2260 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2261 ;; I don't have one of those handy, so I'll use an alist for now.
2262 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2263 ;; and is much lighter-weight to construct (both CPU and mem).
2264 ;; The keys are interned strings (symbols) for faster lookup.
2265 ;; Should switch to hybrid alist/hashtable eventually.
2266 symbol-table ; an alist of (symbol . js2-symbol)
2267 parent-scope ; a `js2-scope'
2268 top) ; top-level `js2-scope' (script/function)
2269
2270 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2271 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2272
2273 (defun js2-scope-set-parent-scope (scope parent)
2274 (setf (js2-scope-parent-scope scope) parent
2275 (js2-scope-top scope) (if (null parent)
2276 scope
2277 (js2-scope-top parent))))
2278
2279 (defun js2-node-get-enclosing-scope (node)
2280 "Return the innermost `js2-scope' node surrounding NODE.
2281 Returns nil if there is no enclosing scope node."
2282 (let ((parent (js2-node-parent node)))
2283 (while (not (js2-scope-p parent))
2284 (setq parent (js2-node-parent parent)))
2285 parent))
2286
2287 (defun js2-get-defining-scope (scope name)
2288 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2289 Returns `js2-scope' in which NAME is defined, or nil if not found."
2290 (let ((sym (if (symbolp name)
2291 name
2292 (intern name)))
2293 table
2294 result
2295 (continue t))
2296 (while (and scope continue)
2297 (if (and (setq table (js2-scope-symbol-table scope))
2298 (assq sym table))
2299 (setq continue nil
2300 result scope)
2301 (setq scope (js2-scope-parent-scope scope))))
2302 result))
2303
2304 (defsubst js2-scope-get-symbol (scope name)
2305 "Return symbol table entry for NAME in SCOPE.
2306 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2307 (and (js2-scope-symbol-table scope)
2308 (cdr (assq (if (symbolp name)
2309 name
2310 (intern name))
2311 (js2-scope-symbol-table scope)))))
2312
2313 (defsubst js2-scope-put-symbol (scope name symbol)
2314 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2315 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2316 (let* ((table (js2-scope-symbol-table scope))
2317 (sym (if (symbolp name) name (intern name)))
2318 (entry (assq sym table)))
2319 (if entry
2320 (setcdr entry symbol)
2321 (push (cons sym symbol)
2322 (js2-scope-symbol-table scope)))))
2323
2324 (defstruct (js2-symbol
2325 (:constructor nil)
2326 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2327 "A symbol table entry."
2328 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2329 ;; js2-LET, or js2-CONST
2330 decl-type
2331 name ; string
2332 ast-node) ; a `js2-node'
2333
2334 (defstruct (js2-error-node
2335 (:include js2-node)
2336 (:constructor nil) ; silence emacs21 byte-compiler
2337 (:constructor make-js2-error-node (&key (type js2-ERROR)
2338 (pos js2-token-beg)
2339 len)))
2340 "AST node representing a parse error.")
2341
2342 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2343 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2344
2345 (defstruct (js2-script-node
2346 (:include js2-scope)
2347 (:constructor nil)
2348 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2349 (pos js2-token-beg)
2350 len
2351 var-decls
2352 fun-decls)))
2353 functions ; lisp list of nested functions
2354 regexps ; lisp list of (string . flags)
2355 symbols ; alist (every symbol gets unique index)
2356 (param-count 0)
2357 var-names ; vector of string names
2358 consts ; bool-vector matching var-decls
2359 (temp-number 0)) ; for generating temp variables
2360
2361 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2362 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2363
2364 (defun js2-print-script (node indent)
2365 (dolist (kid (js2-block-node-kids node))
2366 (js2-print-ast kid indent)))
2367
2368 (defstruct (js2-ast-root
2369 (:include js2-script-node)
2370 (:constructor nil)
2371 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2372 (pos js2-token-beg)
2373 len
2374 buffer)))
2375 "The root node of a js2 AST."
2376 buffer ; the source buffer from which the code was parsed
2377 comments ; a lisp list of comments, ordered by start position
2378 errors ; a lisp list of errors found during parsing
2379 warnings ; a lisp list of warnings found during parsing
2380 node-count) ; number of nodes in the tree, including the root
2381
2382 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2383 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2384
2385 (defun js2-visit-ast-root (ast callback)
2386 (dolist (kid (js2-ast-root-kids ast))
2387 (js2-visit-ast kid callback))
2388 (dolist (comment (js2-ast-root-comments ast))
2389 (js2-visit-ast comment callback)))
2390
2391 (defstruct (js2-comment-node
2392 (:include js2-node)
2393 (:constructor nil)
2394 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2395 (pos js2-token-beg)
2396 len
2397 (format js2-ts-comment-type))))
2398 format) ; 'line, 'block, 'jsdoc or 'html
2399
2400 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2401 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2402
2403 (defun js2-print-comment (n i)
2404 ;; We really ought to link end-of-line comments to their nodes.
2405 ;; Or maybe we could add a new comment type, 'endline.
2406 (insert (js2-make-pad i)
2407 (js2-node-string n)))
2408
2409 (defstruct (js2-expr-stmt-node
2410 (:include js2-node)
2411 (:constructor nil)
2412 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2413 (pos js2-ts-cursor)
2414 len
2415 expr)))
2416 "An expression statement."
2417 expr)
2418
2419 (defsubst js2-expr-stmt-node-set-has-result (node)
2420 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2421 (setf (js2-node-type node) js2-EXPR_RESULT))
2422
2423 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2424 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2425
2426 (defun js2-visit-expr-stmt-node (n v)
2427 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2428
2429 (defun js2-print-expr-stmt-node (n indent)
2430 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2431 (insert ";\n"))
2432
2433 (defstruct (js2-loop-node
2434 (:include js2-scope)
2435 (:constructor nil))
2436 "Abstract supertype of loop nodes."
2437 body ; a `js2-block-node'
2438 lp ; position of left-paren, nil if omitted
2439 rp) ; position of right-paren, nil if omitted
2440
2441 (defstruct (js2-do-node
2442 (:include js2-loop-node)
2443 (:constructor nil)
2444 (:constructor make-js2-do-node (&key (type js2-DO)
2445 (pos js2-token-beg)
2446 len
2447 body
2448 condition
2449 while-pos
2450 lp
2451 rp)))
2452 "AST node for do-loop."
2453 condition ; while (expression)
2454 while-pos) ; buffer position of 'while' keyword
2455
2456 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2457 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2458
2459 (defun js2-visit-do-node (n v)
2460 (js2-visit-ast (js2-do-node-body n) v)
2461 (js2-visit-ast (js2-do-node-condition n) v))
2462
2463 (defun js2-print-do-node (n i)
2464 (let ((pad (js2-make-pad i)))
2465 (insert pad "do {\n")
2466 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2467 (js2-print-ast kid (1+ i)))
2468 (insert pad "} while (")
2469 (js2-print-ast (js2-do-node-condition n) 0)
2470 (insert ");\n")))
2471
2472 (defstruct (js2-while-node
2473 (:include js2-loop-node)
2474 (:constructor nil)
2475 (:constructor make-js2-while-node (&key (type js2-WHILE)
2476 (pos js2-token-beg)
2477 len
2478 body
2479 condition
2480 lp
2481 rp)))
2482 "AST node for while-loop."
2483 condition) ; while-condition
2484
2485 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2486 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2487
2488 (defun js2-visit-while-node (n v)
2489 (js2-visit-ast (js2-while-node-condition n) v)
2490 (js2-visit-ast (js2-while-node-body n) v))
2491
2492 (defun js2-print-while-node (n i)
2493 (let ((pad (js2-make-pad i)))
2494 (insert pad "while (")
2495 (js2-print-ast (js2-while-node-condition n) 0)
2496 (insert ") {\n")
2497 (js2-print-body (js2-while-node-body n) (1+ i))
2498 (insert pad "}\n")))
2499
2500 (defstruct (js2-for-node
2501 (:include js2-loop-node)
2502 (:constructor nil)
2503 (:constructor make-js2-for-node (&key (type js2-FOR)
2504 (pos js2-ts-cursor)
2505 len
2506 body
2507 init
2508 condition
2509 update
2510 lp
2511 rp)))
2512 "AST node for a C-style for-loop."
2513 init ; initialization expression
2514 condition ; loop condition
2515 update) ; update clause
2516
2517 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2518 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2519
2520 (defun js2-visit-for-node (n v)
2521 (js2-visit-ast (js2-for-node-init n) v)
2522 (js2-visit-ast (js2-for-node-condition n) v)
2523 (js2-visit-ast (js2-for-node-update n) v)
2524 (js2-visit-ast (js2-for-node-body n) v))
2525
2526 (defun js2-print-for-node (n i)
2527 (let ((pad (js2-make-pad i)))
2528 (insert pad "for (")
2529 (js2-print-ast (js2-for-node-init n) 0)
2530 (insert "; ")
2531 (js2-print-ast (js2-for-node-condition n) 0)
2532 (insert "; ")
2533 (js2-print-ast (js2-for-node-update n) 0)
2534 (insert ") {\n")
2535 (js2-print-body (js2-for-node-body n) (1+ i))
2536 (insert pad "}\n")))
2537
2538 (defstruct (js2-for-in-node
2539 (:include js2-loop-node)
2540 (:constructor nil)
2541 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2542 (pos js2-ts-cursor)
2543 len
2544 body
2545 iterator
2546 object
2547 in-pos
2548 each-pos
2549 foreach-p forof-p
2550 lp rp)))
2551 "AST node for a for..in loop."
2552 iterator ; [var] foo in ...
2553 object ; object over which we're iterating
2554 in-pos ; buffer position of 'in' keyword
2555 each-pos ; buffer position of 'each' keyword, if foreach-p
2556 foreach-p ; t if it's a for-each loop
2557 forof-p) ; t if it's a for-of loop
2558
2559 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2560 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2561
2562 (defun js2-visit-for-in-node (n v)
2563 (js2-visit-ast (js2-for-in-node-iterator n) v)
2564 (js2-visit-ast (js2-for-in-node-object n) v)
2565 (js2-visit-ast (js2-for-in-node-body n) v))
2566
2567 (defun js2-print-for-in-node (n i)
2568 (let ((pad (js2-make-pad i))
2569 (foreach (js2-for-in-node-foreach-p n))
2570 (forof (js2-for-in-node-forof-p n)))
2571 (insert pad "for ")
2572 (if foreach
2573 (insert "each "))
2574 (insert "(")
2575 (js2-print-ast (js2-for-in-node-iterator n) 0)
2576 (if forof
2577 (insert " of ")
2578 (insert " in "))
2579 (js2-print-ast (js2-for-in-node-object n) 0)
2580 (insert ") {\n")
2581 (js2-print-body (js2-for-in-node-body n) (1+ i))
2582 (insert pad "}\n")))
2583
2584 (defstruct (js2-return-node
2585 (:include js2-node)
2586 (:constructor nil)
2587 (:constructor make-js2-return-node (&key (type js2-RETURN)
2588 (pos js2-ts-cursor)
2589 len
2590 retval)))
2591 "AST node for a return statement."
2592 retval) ; expression to return, or 'undefined
2593
2594 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2595 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2596
2597 (defun js2-visit-return-node (n v)
2598 (js2-visit-ast (js2-return-node-retval n) v))
2599
2600 (defun js2-print-return-node (n i)
2601 (insert (js2-make-pad i) "return")
2602 (when (js2-return-node-retval n)
2603 (insert " ")
2604 (js2-print-ast (js2-return-node-retval n) 0))
2605 (insert ";\n"))
2606
2607 (defstruct (js2-if-node
2608 (:include js2-node)
2609 (:constructor nil)
2610 (:constructor make-js2-if-node (&key (type js2-IF)
2611 (pos js2-ts-cursor)
2612 len
2613 condition
2614 then-part
2615 else-pos
2616 else-part
2617 lp
2618 rp)))
2619 "AST node for an if-statement."
2620 condition ; expression
2621 then-part ; statement or block
2622 else-pos ; optional buffer position of 'else' keyword
2623 else-part ; optional statement or block
2624 lp ; position of left-paren, nil if omitted
2625 rp) ; position of right-paren, nil if omitted
2626
2627 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2628 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2629
2630 (defun js2-visit-if-node (n v)
2631 (js2-visit-ast (js2-if-node-condition n) v)
2632 (js2-visit-ast (js2-if-node-then-part n) v)
2633 (js2-visit-ast (js2-if-node-else-part n) v))
2634
2635 (defun js2-print-if-node (n i)
2636 (let ((pad (js2-make-pad i))
2637 (then-part (js2-if-node-then-part n))
2638 (else-part (js2-if-node-else-part n)))
2639 (insert pad "if (")
2640 (js2-print-ast (js2-if-node-condition n) 0)
2641 (insert ") {\n")
2642 (js2-print-body then-part (1+ i))
2643 (insert pad "}")
2644 (cond
2645 ((not else-part)
2646 (insert "\n"))
2647 ((js2-if-node-p else-part)
2648 (insert " else ")
2649 (js2-print-body else-part i))
2650 (t
2651 (insert " else {\n")
2652 (js2-print-body else-part (1+ i))
2653 (insert pad "}\n")))))
2654
2655 (defstruct (js2-try-node
2656 (:include js2-node)
2657 (:constructor nil)
2658 (:constructor make-js2-try-node (&key (type js2-TRY)
2659 (pos js2-ts-cursor)
2660 len
2661 try-block
2662 catch-clauses
2663 finally-block)))
2664 "AST node for a try-statement."
2665 try-block
2666 catch-clauses ; a lisp list of `js2-catch-node'
2667 finally-block) ; a `js2-finally-node'
2668
2669 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2670 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2671
2672 (defun js2-visit-try-node (n v)
2673 (js2-visit-ast (js2-try-node-try-block n) v)
2674 (dolist (clause (js2-try-node-catch-clauses n))
2675 (js2-visit-ast clause v))
2676 (js2-visit-ast (js2-try-node-finally-block n) v))
2677
2678 (defun js2-print-try-node (n i)
2679 (let ((pad (js2-make-pad i))
2680 (catches (js2-try-node-catch-clauses n))
2681 (finally (js2-try-node-finally-block n)))
2682 (insert pad "try {\n")
2683 (js2-print-body (js2-try-node-try-block n) (1+ i))
2684 (insert pad "}")
2685 (when catches
2686 (dolist (catch catches)
2687 (js2-print-ast catch i)))
2688 (if finally
2689 (js2-print-ast finally i)
2690 (insert "\n"))))
2691
2692 (defstruct (js2-catch-node
2693 (:include js2-node)
2694 (:constructor nil)
2695 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2696 (pos js2-ts-cursor)
2697 len
2698 param
2699 guard-kwd
2700 guard-expr
2701 block
2702 lp
2703 rp)))
2704 "AST node for a catch clause."
2705 param ; destructuring form or simple name node
2706 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2707 guard-expr ; catch condition, a `js2-node'
2708 block ; statements, a `js2-block-node'
2709 lp ; buffer position of left-paren, nil if omitted
2710 rp) ; buffer position of right-paren, nil if omitted
2711
2712 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2713 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2714
2715 (defun js2-visit-catch-node (n v)
2716 (js2-visit-ast (js2-catch-node-param n) v)
2717 (when (js2-catch-node-guard-kwd n)
2718 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2719 (js2-visit-ast (js2-catch-node-block n) v))
2720
2721 (defun js2-print-catch-node (n i)
2722 (let ((pad (js2-make-pad i))
2723 (guard-kwd (js2-catch-node-guard-kwd n))
2724 (guard-expr (js2-catch-node-guard-expr n)))
2725 (insert " catch (")
2726 (js2-print-ast (js2-catch-node-param n) 0)
2727 (when guard-kwd
2728 (insert " if ")
2729 (js2-print-ast guard-expr 0))
2730 (insert ") {\n")
2731 (js2-print-body (js2-catch-node-block n) (1+ i))
2732 (insert pad "}")))
2733
2734 (defstruct (js2-finally-node
2735 (:include js2-node)
2736 (:constructor nil)
2737 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2738 (pos js2-ts-cursor)
2739 len
2740 body)))
2741 "AST node for a finally clause."
2742 body) ; a `js2-node', often but not always a block node
2743
2744 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2745 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2746
2747 (defun js2-visit-finally-node (n v)
2748 (js2-visit-ast (js2-finally-node-body n) v))
2749
2750 (defun js2-print-finally-node (n i)
2751 (let ((pad (js2-make-pad i)))
2752 (insert " finally {\n")
2753 (js2-print-body (js2-finally-node-body n) (1+ i))
2754 (insert pad "}\n")))
2755
2756 (defstruct (js2-switch-node
2757 (:include js2-node)
2758 (:constructor nil)
2759 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2760 (pos js2-ts-cursor)
2761 len
2762 discriminant
2763 cases
2764 lp
2765 rp)))
2766 "AST node for a switch statement."
2767 discriminant ; a `js2-node' (switch expression)
2768 cases ; a lisp list of `js2-case-node'
2769 lp ; position of open-paren for discriminant, nil if omitted
2770 rp) ; position of close-paren for discriminant, nil if omitted
2771
2772 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2773 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2774
2775 (defun js2-visit-switch-node (n v)
2776 (js2-visit-ast (js2-switch-node-discriminant n) v)
2777 (dolist (c (js2-switch-node-cases n))
2778 (js2-visit-ast c v)))
2779
2780 (defun js2-print-switch-node (n i)
2781 (let ((pad (js2-make-pad i))
2782 (cases (js2-switch-node-cases n)))
2783 (insert pad "switch (")
2784 (js2-print-ast (js2-switch-node-discriminant n) 0)
2785 (insert ") {\n")
2786 (dolist (case cases)
2787 (js2-print-ast case i))
2788 (insert pad "}\n")))
2789
2790 (defstruct (js2-case-node
2791 (:include js2-block-node)
2792 (:constructor nil)
2793 (:constructor make-js2-case-node (&key (type js2-CASE)
2794 (pos js2-ts-cursor)
2795 len
2796 kids
2797 expr)))
2798 "AST node for a case clause of a switch statement."
2799 expr) ; the case expression (nil for default)
2800
2801 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2802 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2803
2804 (defun js2-visit-case-node (n v)
2805 (js2-visit-ast (js2-case-node-expr n) v)
2806 (js2-visit-block n v))
2807
2808 (defun js2-print-case-node (n i)
2809 (let ((pad (js2-make-pad i))
2810 (expr (js2-case-node-expr n)))
2811 (insert pad)
2812 (if (null expr)
2813 (insert "default:\n")
2814 (insert "case ")
2815 (js2-print-ast expr 0)
2816 (insert ":\n"))
2817 (dolist (kid (js2-case-node-kids n))
2818 (js2-print-ast kid (1+ i)))))
2819
2820 (defstruct (js2-throw-node
2821 (:include js2-node)
2822 (:constructor nil)
2823 (:constructor make-js2-throw-node (&key (type js2-THROW)
2824 (pos js2-ts-cursor)
2825 len
2826 expr)))
2827 "AST node for a throw statement."
2828 expr) ; the expression to throw
2829
2830 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2831 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2832
2833 (defun js2-visit-throw-node (n v)
2834 (js2-visit-ast (js2-throw-node-expr n) v))
2835
2836 (defun js2-print-throw-node (n i)
2837 (insert (js2-make-pad i) "throw ")
2838 (js2-print-ast (js2-throw-node-expr n) 0)
2839 (insert ";\n"))
2840
2841 (defstruct (js2-with-node
2842 (:include js2-node)
2843 (:constructor nil)
2844 (:constructor make-js2-with-node (&key (type js2-WITH)
2845 (pos js2-ts-cursor)
2846 len
2847 object
2848 body
2849 lp
2850 rp)))
2851 "AST node for a with-statement."
2852 object
2853 body
2854 lp ; buffer position of left-paren around object, nil if omitted
2855 rp) ; buffer position of right-paren around object, nil if omitted
2856
2857 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2858 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2859
2860 (defun js2-visit-with-node (n v)
2861 (js2-visit-ast (js2-with-node-object n) v)
2862 (js2-visit-ast (js2-with-node-body n) v))
2863
2864 (defun js2-print-with-node (n i)
2865 (let ((pad (js2-make-pad i)))
2866 (insert pad "with (")
2867 (js2-print-ast (js2-with-node-object n) 0)
2868 (insert ") {\n")
2869 (js2-print-body (js2-with-node-body n) (1+ i))
2870 (insert pad "}\n")))
2871
2872 (defstruct (js2-label-node
2873 (:include js2-node)
2874 (:constructor nil)
2875 (:constructor make-js2-label-node (&key (type js2-LABEL)
2876 (pos js2-ts-cursor)
2877 len
2878 name)))
2879 "AST node for a statement label or case label."
2880 name ; a string
2881 loop) ; for validating and code-generating continue-to-label
2882
2883 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2884 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2885
2886 (defun js2-print-label (n i)
2887 (insert (js2-make-pad i)
2888 (js2-label-node-name n)
2889 ":\n"))
2890
2891 (defstruct (js2-labeled-stmt-node
2892 (:include js2-node)
2893 (:constructor nil)
2894 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2895 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2896 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2897 (pos js2-ts-cursor)
2898 len
2899 labels
2900 stmt)))
2901 "AST node for a statement with one or more labels.
2902 Multiple labels for a statement are collapsed into the labels field."
2903 labels ; lisp list of `js2-label-node'
2904 stmt) ; the statement these labels are for
2905
2906 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2907 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2908
2909 (defun js2-get-label-by-name (lbl-stmt name)
2910 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2911 Returns nil if no such label is in the list."
2912 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2913 result)
2914 (while (and label-list (not result))
2915 (if (string= (js2-label-node-name (car label-list)) name)
2916 (setq result (car label-list))
2917 (setq label-list (cdr label-list))))
2918 result))
2919
2920 (defun js2-visit-labeled-stmt (n v)
2921 (dolist (label (js2-labeled-stmt-node-labels n))
2922 (js2-visit-ast label v))
2923 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2924
2925 (defun js2-print-labeled-stmt (n i)
2926 (dolist (label (js2-labeled-stmt-node-labels n))
2927 (js2-print-ast label i))
2928 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2929
2930 (defun js2-labeled-stmt-node-contains (node label)
2931 "Return t if NODE contains LABEL in its label set.
2932 NODE is a `js2-labels-node'. LABEL is an identifier."
2933 (loop for nl in (js2-labeled-stmt-node-labels node)
2934 if (string= label (js2-label-node-name nl))
2935 return t
2936 finally return nil))
2937
2938 (defsubst js2-labeled-stmt-node-add-label (node label)
2939 "Add a `js2-label-node' to the label set for this statement."
2940 (setf (js2-labeled-stmt-node-labels node)
2941 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2942
2943 (defstruct (js2-jump-node
2944 (:include js2-node)
2945 (:constructor nil))
2946 "Abstract supertype of break and continue nodes."
2947 label ; `js2-name-node' for location of label identifier, if present
2948 target) ; target js2-labels-node or loop/switch statement
2949
2950 (defun js2-visit-jump-node (n v)
2951 (js2-visit-ast (js2-jump-node-label n) v))
2952
2953 (defstruct (js2-break-node
2954 (:include js2-jump-node)
2955 (:constructor nil)
2956 (:constructor make-js2-break-node (&key (type js2-BREAK)
2957 (pos js2-ts-cursor)
2958 len
2959 label
2960 target)))
2961 "AST node for a break statement.
2962 The label field is a `js2-name-node', possibly nil, for the named label
2963 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2964 is the target of the break - a label node or enclosing loop/switch statement.")
2965
2966 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2967 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2968
2969 (defun js2-print-break-node (n i)
2970 (insert (js2-make-pad i) "break")
2971 (when (js2-break-node-label n)
2972 (insert " ")
2973 (js2-print-ast (js2-break-node-label n) 0))
2974 (insert ";\n"))
2975
2976 (defstruct (js2-continue-node
2977 (:include js2-jump-node)
2978 (:constructor nil)
2979 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2980 (pos js2-ts-cursor)
2981 len
2982 label
2983 target)))
2984 "AST node for a continue statement.
2985 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2986 It is nil if continue specifies no label. The target field is the jump target:
2987 a `js2-label-node' or the innermost enclosing loop.")
2988
2989 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2990 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2991
2992 (defun js2-print-continue-node (n i)
2993 (insert (js2-make-pad i) "continue")
2994 (when (js2-continue-node-label n)
2995 (insert " ")
2996 (js2-print-ast (js2-continue-node-label n) 0))
2997 (insert ";\n"))
2998
2999 (defstruct (js2-function-node
3000 (:include js2-script-node)
3001 (:constructor nil)
3002 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3003 (pos js2-ts-cursor)
3004 len
3005 (ftype 'FUNCTION)
3006 (form 'FUNCTION_STATEMENT)
3007 (name "")
3008 params rest-p
3009 body
3010 lp rp)))
3011 "AST node for a function declaration.
3012 The `params' field is a lisp list of nodes. Each node is either a simple
3013 `js2-name-node', or if it's a destructuring-assignment parameter, a
3014 `js2-array-node' or `js2-object-node'."
3015 ftype ; FUNCTION, GETTER or SETTER
3016 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3017 name ; function name (a `js2-name-node', or nil if anonymous)
3018 params ; a lisp list of destructuring forms or simple name nodes
3019 rest-p ; if t, the last parameter is rest parameter
3020 body ; a `js2-block-node' or expression node (1.8 only)
3021 lp ; position of arg-list open-paren, or nil if omitted
3022 rp ; position of arg-list close-paren, or nil if omitted
3023 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3024 needs-activation ; t if we need an activation object for this frame
3025 is-generator ; t if this function contains a yield
3026 member-expr) ; nonstandard Ecma extension from Rhino
3027
3028 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3029 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3030
3031 (defun js2-visit-function-node (n v)
3032 (js2-visit-ast (js2-function-node-name n) v)
3033 (dolist (p (js2-function-node-params n))
3034 (js2-visit-ast p v))
3035 (js2-visit-ast (js2-function-node-body n) v))
3036
3037 (defun js2-print-function-node (n i)
3038 (let ((pad (js2-make-pad i))
3039 (getter (js2-node-get-prop n 'GETTER_SETTER))
3040 (name (js2-function-node-name n))
3041 (params (js2-function-node-params n))
3042 (rest-p (js2-function-node-rest-p n))
3043 (body (js2-function-node-body n))
3044 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3045 (unless getter
3046 (insert pad "function"))
3047 (when name
3048 (insert " ")
3049 (js2-print-ast name 0))
3050 (insert "(")
3051 (loop with len = (length params)
3052 for param in params
3053 for count from 1
3054 do
3055 (when (and rest-p (= count len))
3056 (insert "..."))
3057 (js2-print-ast param 0)
3058 (when (< count len)
3059 (insert ", ")))
3060 (insert ") {")
3061 (unless expr
3062 (insert "\n"))
3063 ;; TODO: fix this to be smarter about indenting, etc.
3064 (js2-print-body body (1+ i))
3065 (insert pad "}")
3066 (unless expr
3067 (insert "\n"))))
3068
3069 (defsubst js2-function-name (node)
3070 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3071 (and (js2-function-node-name node)
3072 (js2-name-node-name (js2-function-node-name node))))
3073
3074 ;; Having this be an expression node makes it more flexible.
3075 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3076 ;; that work better if you assume it's an expression. Whenever we have
3077 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3078 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3079 (defstruct (js2-var-decl-node
3080 (:include js2-node)
3081 (:constructor nil)
3082 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3083 (pos js2-token-beg)
3084 len
3085 kids
3086 decl-type)))
3087 "AST node for a variable declaration list (VAR, CONST or LET).
3088 The node bounds differ depending on the declaration type. For VAR or
3089 CONST declarations, the bounds include the var/const keyword. For LET
3090 declarations, the node begins at the position of the first child."
3091 kids ; a lisp list of `js2-var-init-node' structs.
3092 decl-type) ; js2-VAR, js2-CONST or js2-LET
3093
3094 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3095 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3096
3097 (defun js2-visit-var-decl (n v)
3098 (dolist (kid (js2-var-decl-node-kids n))
3099 (js2-visit-ast kid v)))
3100
3101 (defun js2-print-var-decl (n i)
3102 (let ((pad (js2-make-pad i))
3103 (tt (js2-var-decl-node-decl-type n)))
3104 (insert pad)
3105 (insert (cond
3106 ((= tt js2-VAR) "var ")
3107 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3108 ((= tt js2-CONST) "const ")
3109 (t
3110 (error "malformed var-decl node"))))
3111 (loop with kids = (js2-var-decl-node-kids n)
3112 with len = (length kids)
3113 for kid in kids
3114 for count from 1
3115 do
3116 (js2-print-ast kid 0)
3117 (if (< count len)
3118 (insert ", ")))))
3119
3120 (defstruct (js2-var-init-node
3121 (:include js2-node)
3122 (:constructor nil)
3123 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3124 (pos js2-ts-cursor)
3125 len
3126 target
3127 initializer)))
3128 "AST node for a variable declaration.
3129 The type field will be js2-CONST for a const decl."
3130 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3131 initializer) ; initializer expression, a `js2-node'
3132
3133 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3134 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3135
3136 (defun js2-visit-var-init-node (n v)
3137 (js2-visit-ast (js2-var-init-node-target n) v)
3138 (js2-visit-ast (js2-var-init-node-initializer n) v))
3139
3140 (defun js2-print-var-init-node (n i)
3141 (let ((pad (js2-make-pad i))
3142 (name (js2-var-init-node-target n))
3143 (init (js2-var-init-node-initializer n)))
3144 (insert pad)
3145 (js2-print-ast name 0)
3146 (when init
3147 (insert " = ")
3148 (js2-print-ast init 0))))
3149
3150 (defstruct (js2-cond-node
3151 (:include js2-node)
3152 (:constructor nil)
3153 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3154 (pos js2-ts-cursor)
3155 len
3156 test-expr
3157 true-expr
3158 false-expr
3159 q-pos
3160 c-pos)))
3161 "AST node for the ternary operator"
3162 test-expr
3163 true-expr
3164 false-expr
3165 q-pos ; buffer position of ?
3166 c-pos) ; buffer position of :
3167
3168 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3169 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3170
3171 (defun js2-visit-cond-node (n v)
3172 (js2-visit-ast (js2-cond-node-test-expr n) v)
3173 (js2-visit-ast (js2-cond-node-true-expr n) v)
3174 (js2-visit-ast (js2-cond-node-false-expr n) v))
3175
3176 (defun js2-print-cond-node (n i)
3177 (let ((pad (js2-make-pad i)))
3178 (insert pad)
3179 (js2-print-ast (js2-cond-node-test-expr n) 0)
3180 (insert " ? ")
3181 (js2-print-ast (js2-cond-node-true-expr n) 0)
3182 (insert " : ")
3183 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3184
3185 (defstruct (js2-infix-node
3186 (:include js2-node)
3187 (:constructor nil)
3188 (:constructor make-js2-infix-node (&key type
3189 (pos js2-ts-cursor)
3190 len
3191 op-pos
3192 left
3193 right)))
3194 "Represents infix expressions.
3195 Includes assignment ops like `|=', and the comma operator.
3196 The type field inherited from `js2-node' holds the operator."
3197 op-pos ; buffer position where operator begins
3198 left ; any `js2-node'
3199 right) ; any `js2-node'
3200
3201 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3202 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3203
3204 (defun js2-visit-infix-node (n v)
3205 (js2-visit-ast (js2-infix-node-left n) v)
3206 (js2-visit-ast (js2-infix-node-right n) v))
3207
3208 (defconst js2-operator-tokens
3209 (let ((table (make-hash-table :test 'eq))
3210 (tokens
3211 (list (cons js2-IN "in")
3212 (cons js2-TYPEOF "typeof")
3213 (cons js2-INSTANCEOF "instanceof")
3214 (cons js2-DELPROP "delete")
3215 (cons js2-COMMA ",")
3216 (cons js2-COLON ":")
3217 (cons js2-OR "||")
3218 (cons js2-AND "&&")
3219 (cons js2-INC "++")
3220 (cons js2-DEC "--")
3221 (cons js2-BITOR "|")
3222 (cons js2-BITXOR "^")
3223 (cons js2-BITAND "&")
3224 (cons js2-EQ "==")
3225 (cons js2-NE "!=")
3226 (cons js2-LT "<")
3227 (cons js2-LE "<=")
3228 (cons js2-GT ">")
3229 (cons js2-GE ">=")
3230 (cons js2-LSH "<<")
3231 (cons js2-RSH ">>")
3232 (cons js2-URSH ">>>")
3233 (cons js2-ADD "+") ; infix plus
3234 (cons js2-SUB "-") ; infix minus
3235 (cons js2-MUL "*")
3236 (cons js2-DIV "/")
3237 (cons js2-MOD "%")
3238 (cons js2-NOT "!")
3239 (cons js2-BITNOT "~")
3240 (cons js2-POS "+") ; unary plus
3241 (cons js2-NEG "-") ; unary minus
3242 (cons js2-SHEQ "===") ; shallow equality
3243 (cons js2-SHNE "!==") ; shallow inequality
3244 (cons js2-ASSIGN "=")
3245 (cons js2-ASSIGN_BITOR "|=")
3246 (cons js2-ASSIGN_BITXOR "^=")
3247 (cons js2-ASSIGN_BITAND "&=")
3248 (cons js2-ASSIGN_LSH "<<=")
3249 (cons js2-ASSIGN_RSH ">>=")
3250 (cons js2-ASSIGN_URSH ">>>=")
3251 (cons js2-ASSIGN_ADD "+=")
3252 (cons js2-ASSIGN_SUB "-=")
3253 (cons js2-ASSIGN_MUL "*=")
3254 (cons js2-ASSIGN_DIV "/=")
3255 (cons js2-ASSIGN_MOD "%="))))
3256 (loop for (k . v) in tokens do
3257 (puthash k v table))
3258 table))
3259
3260 (defun js2-print-infix-node (n i)
3261 (let* ((tt (js2-node-type n))
3262 (op (gethash tt js2-operator-tokens)))
3263 (unless op
3264 (error "unrecognized infix operator %s" (js2-node-type n)))
3265 (insert (js2-make-pad i))
3266 (js2-print-ast (js2-infix-node-left n) 0)
3267 (unless (= tt js2-COMMA)
3268 (insert " "))
3269 (insert op)
3270 (insert " ")
3271 (js2-print-ast (js2-infix-node-right n) 0)))
3272
3273 (defstruct (js2-assign-node
3274 (:include js2-infix-node)
3275 (:constructor nil)
3276 (:constructor make-js2-assign-node (&key type
3277 (pos js2-ts-cursor)
3278 len
3279 op-pos
3280 left
3281 right)))
3282 "Represents any assignment.
3283 The type field holds the actual assignment operator.")
3284
3285 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3286 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3287
3288 (defstruct (js2-unary-node
3289 (:include js2-node)
3290 (:constructor nil)
3291 (:constructor make-js2-unary-node (&key type ; required
3292 (pos js2-ts-cursor)
3293 len
3294 operand)))
3295 "AST node type for unary operator nodes.
3296 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3297 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3298 property is added if the operator follows the operand."
3299 operand) ; a `js2-node' expression
3300
3301 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3302 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3303
3304 (defun js2-visit-unary-node (n v)
3305 (js2-visit-ast (js2-unary-node-operand n) v))
3306
3307 (defun js2-print-unary-node (n i)
3308 (let* ((tt (js2-node-type n))
3309 (op (gethash tt js2-operator-tokens))
3310 (postfix (js2-node-get-prop n 'postfix)))
3311 (unless op
3312 (error "unrecognized unary operator %s" tt))
3313 (insert (js2-make-pad i))
3314 (unless postfix
3315 (insert op))
3316 (if (or (= tt js2-TYPEOF)
3317 (= tt js2-DELPROP))
3318 (insert " "))
3319 (js2-print-ast (js2-unary-node-operand n) 0)
3320 (when postfix
3321 (insert op))))
3322
3323 (defstruct (js2-let-node
3324 (:include js2-scope)
3325 (:constructor nil)
3326 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3327 (pos js2-token-beg)
3328 len
3329 vars
3330 body
3331 lp
3332 rp)))
3333 "AST node for a let expression or a let statement.
3334 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3335 vars ; a `js2-var-decl-node'
3336 body ; a `js2-node' representing the expression or body block
3337 lp
3338 rp)
3339
3340 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3341 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3342
3343 (defun js2-visit-let-node (n v)
3344 (js2-visit-ast (js2-let-node-vars n) v)
3345 (js2-visit-ast (js2-let-node-body n) v))
3346
3347 (defun js2-print-let-node (n i)
3348 (insert (js2-make-pad i) "let (")
3349 (js2-print-ast (js2-let-node-vars n) 0)
3350 (insert ") ")
3351 (js2-print-ast (js2-let-node-body n) i))
3352
3353 (defstruct (js2-keyword-node
3354 (:include js2-node)
3355 (:constructor nil)
3356 (:constructor make-js2-keyword-node (&key type
3357 (pos js2-token-beg)
3358 (len (- js2-ts-cursor pos)))))
3359 "AST node representing a literal keyword such as `null'.
3360 Used for `null', `this', `true', `false' and `debugger'.
3361 The node type is set to js2-NULL, js2-THIS, etc.")
3362
3363 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3364 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3365
3366 (defun js2-print-keyword-node (n i)
3367 (insert (js2-make-pad i)
3368 (let ((tt (js2-node-type n)))
3369 (cond
3370 ((= tt js2-THIS) "this")
3371 ((= tt js2-NULL) "null")
3372 ((= tt js2-TRUE) "true")
3373 ((= tt js2-FALSE) "false")
3374 ((= tt js2-DEBUGGER) "debugger")
3375 (t (error "Invalid keyword literal type: %d" tt))))))
3376
3377 (defsubst js2-this-node-p (node)
3378 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3379 (eq (js2-node-type node) js2-THIS))
3380
3381 (defstruct (js2-new-node
3382 (:include js2-node)
3383 (:constructor nil)
3384 (:constructor make-js2-new-node (&key (type js2-NEW)
3385 (pos js2-token-beg)
3386 len
3387 target
3388 args
3389 initializer
3390 lp
3391 rp)))
3392 "AST node for new-expression such as new Foo()."
3393 target ; an identifier or reference
3394 args ; a lisp list of argument nodes
3395 lp ; position of left-paren, nil if omitted
3396 rp ; position of right-paren, nil if omitted
3397 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3398
3399 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3400 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3401
3402 (defun js2-visit-new-node (n v)
3403 (js2-visit-ast (js2-new-node-target n) v)
3404 (dolist (arg (js2-new-node-args n))
3405 (js2-visit-ast arg v))
3406 (js2-visit-ast (js2-new-node-initializer n) v))
3407
3408 (defun js2-print-new-node (n i)
3409 (insert (js2-make-pad i) "new ")
3410 (js2-print-ast (js2-new-node-target n))
3411 (insert "(")
3412 (js2-print-list (js2-new-node-args n))
3413 (insert ")")
3414 (when (js2-new-node-initializer n)
3415 (insert " ")
3416 (js2-print-ast (js2-new-node-initializer n))))
3417
3418 (defstruct (js2-name-node
3419 (:include js2-node)
3420 (:constructor nil)
3421 (:constructor make-js2-name-node (&key (type js2-NAME)
3422 (pos js2-token-beg)
3423 (len (- js2-ts-cursor
3424 js2-token-beg))
3425 (name js2-ts-string))))
3426 "AST node for a JavaScript identifier"
3427 name ; a string
3428 scope) ; a `js2-scope' (optional, used for codegen)
3429
3430 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3431 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3432
3433 (defun js2-print-name-node (n i)
3434 (insert (js2-make-pad i)
3435 (js2-name-node-name n)))
3436
3437 (defsubst js2-name-node-length (node)
3438 "Return identifier length of NODE, a `js2-name-node'.
3439 Returns 0 if NODE is nil or its identifier field is nil."
3440 (if node
3441 (length (js2-name-node-name node))
3442 0))
3443
3444 (defstruct (js2-number-node
3445 (:include js2-node)
3446 (:constructor nil)
3447 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3448 (pos js2-token-beg)
3449 (len (- js2-ts-cursor
3450 js2-token-beg))
3451 (value js2-ts-string)
3452 (num-value js2-ts-number))))
3453 "AST node for a number literal."
3454 value ; the original string, e.g. "6.02e23"
3455 num-value) ; the parsed number value
3456
3457 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3458 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3459
3460 (defun js2-print-number-node (n i)
3461 (insert (js2-make-pad i)
3462 (number-to-string (js2-number-node-num-value n))))
3463
3464 (defstruct (js2-regexp-node
3465 (:include js2-node)
3466 (:constructor nil)
3467 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3468 (pos js2-token-beg)
3469 (len (- js2-ts-cursor
3470 js2-token-beg))
3471 value
3472 flags)))
3473 "AST node for a regular expression literal."
3474 value ; the regexp string, without // delimiters
3475 flags) ; a string of flags, e.g. `mi'.
3476
3477 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3478 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3479
3480 (defun js2-print-regexp (n i)
3481 (insert (js2-make-pad i)
3482 "/"
3483 (js2-regexp-node-value n)
3484 "/")
3485 (if (js2-regexp-node-flags n)
3486 (insert (js2-regexp-node-flags n))))
3487
3488 (defstruct (js2-string-node
3489 (:include js2-node)
3490 (:constructor nil)
3491 (:constructor make-js2-string-node (&key (type js2-STRING)
3492 (pos js2-token-beg)
3493 (len (- js2-ts-cursor
3494 js2-token-beg))
3495 (value js2-ts-string))))
3496 "String literal.
3497 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3498 You can tell the quote type by looking at the first character."
3499 value) ; the characters of the string, including the quotes
3500
3501 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3502 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3503
3504 (defun js2-print-string-node (n i)
3505 (insert (js2-make-pad i)
3506 (js2-node-string n)))
3507
3508 (defstruct (js2-array-node
3509 (:include js2-node)
3510 (:constructor nil)
3511 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3512 (pos js2-ts-cursor)
3513 len
3514 elems)))
3515 "AST node for an array literal."
3516 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3517
3518 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3519 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3520
3521 (defun js2-visit-array-node (n v)
3522 (dolist (e (js2-array-node-elems n))
3523 (js2-visit-ast e v)))
3524
3525 (defun js2-print-array-node (n i)
3526 (insert (js2-make-pad i) "[")
3527 (js2-print-list (js2-array-node-elems n))
3528 (insert "]"))
3529
3530 (defstruct (js2-object-node
3531 (:include js2-node)
3532 (:constructor nil)
3533 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3534 (pos js2-ts-cursor)
3535 len
3536 elems)))
3537 "AST node for an object literal expression.
3538 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3539 the latter represents abbreviation in destructuring expressions."
3540 elems)
3541
3542 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3543 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3544
3545 (defun js2-visit-object-node (n v)
3546 (dolist (e (js2-object-node-elems n))
3547 (js2-visit-ast e v)))
3548
3549 (defun js2-print-object-node (n i)
3550 (insert (js2-make-pad i) "{")
3551 (js2-print-list (js2-object-node-elems n))
3552 (insert "}"))
3553
3554 (defstruct (js2-object-prop-node
3555 (:include js2-infix-node)
3556 (:constructor nil)
3557 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3558 (pos js2-ts-cursor)
3559 len
3560 left
3561 right
3562 op-pos)))
3563 "AST node for an object literal prop:value entry.
3564 The `left' field is the property: a name node, string node or number node.
3565 The `right' field is a `js2-node' representing the initializer value.")
3566
3567 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3568 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3569
3570 (defun js2-print-object-prop-node (n i)
3571 (insert (js2-make-pad i))
3572 (js2-print-ast (js2-object-prop-node-left n) 0)
3573 (insert ": ")
3574 (js2-print-ast (js2-object-prop-node-right n) 0))
3575
3576 (defstruct (js2-getter-setter-node
3577 (:include js2-infix-node)
3578 (:constructor nil)
3579 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3580 (pos js2-ts-cursor)
3581 len
3582 left
3583 right)))
3584 "AST node for a getter/setter property in an object literal.
3585 The `left' field is the `js2-name-node' naming the getter/setter prop.
3586 The `right' field is always an anonymous `js2-function-node' with a node
3587 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3588
3589 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3590 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3591
3592 (defun js2-print-getter-setter (n i)
3593 (let ((pad (js2-make-pad i))
3594 (left (js2-getter-setter-node-left n))
3595 (right (js2-getter-setter-node-right n)))
3596 (insert pad)
3597 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3598 (js2-print-ast left 0)
3599 (js2-print-ast right 0)))
3600
3601 (defstruct (js2-prop-get-node
3602 (:include js2-infix-node)
3603 (:constructor nil)
3604 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3605 (pos js2-ts-cursor)
3606 len
3607 left
3608 right)))
3609 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3610
3611 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3612 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3613
3614 (defun js2-visit-prop-get-node (n v)
3615 (js2-visit-ast (js2-prop-get-node-left n) v)
3616 (js2-visit-ast (js2-prop-get-node-right n) v))
3617
3618 (defun js2-print-prop-get-node (n i)
3619 (insert (js2-make-pad i))
3620 (js2-print-ast (js2-prop-get-node-left n) 0)
3621 (insert ".")
3622 (js2-print-ast (js2-prop-get-node-right n) 0))
3623
3624 (defstruct (js2-elem-get-node
3625 (:include js2-node)
3626 (:constructor nil)
3627 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3628 (pos js2-ts-cursor)
3629 len
3630 target
3631 element
3632 lb
3633 rb)))
3634 "AST node for an array index expression such as foo[bar]."
3635 target ; a `js2-node' - the expression preceding the "."
3636 element ; a `js2-node' - the expression in brackets
3637 lb ; position of left-bracket, nil if omitted
3638 rb) ; position of right-bracket, nil if omitted
3639
3640 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3641 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3642
3643 (defun js2-visit-elem-get-node (n v)
3644 (js2-visit-ast (js2-elem-get-node-target n) v)
3645 (js2-visit-ast (js2-elem-get-node-element n) v))
3646
3647 (defun js2-print-elem-get-node (n i)
3648 (insert (js2-make-pad i))
3649 (js2-print-ast (js2-elem-get-node-target n) 0)
3650 (insert "[")
3651 (js2-print-ast (js2-elem-get-node-element n) 0)
3652 (insert "]"))
3653
3654 (defstruct (js2-call-node
3655 (:include js2-node)
3656 (:constructor nil)
3657 (:constructor make-js2-call-node (&key (type js2-CALL)
3658 (pos js2-ts-cursor)
3659 len
3660 target
3661 args
3662 lp
3663 rp)))
3664 "AST node for a JavaScript function call."
3665 target ; a `js2-node' evaluating to the function to call
3666 args ; a lisp list of `js2-node' arguments
3667 lp ; position of open-paren, or nil if missing
3668 rp) ; position of close-paren, or nil if missing
3669
3670 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3671 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3672
3673 (defun js2-visit-call-node (n v)
3674 (js2-visit-ast (js2-call-node-target n) v)
3675 (dolist (arg (js2-call-node-args n))
3676 (js2-visit-ast arg v)))
3677
3678 (defun js2-print-call-node (n i)
3679 (insert (js2-make-pad i))
3680 (js2-print-ast (js2-call-node-target n) 0)
3681 (insert "(")
3682 (js2-print-list (js2-call-node-args n))
3683 (insert ")"))
3684
3685 (defstruct (js2-yield-node
3686 (:include js2-node)
3687 (:constructor nil)
3688 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3689 (pos js2-ts-cursor)
3690 len
3691 value)))
3692 "AST node for yield statement or expression."
3693 value) ; optional: value to be yielded
3694
3695 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3696 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3697
3698 (defun js2-visit-yield-node (n v)
3699 (js2-visit-ast (js2-yield-node-value n) v))
3700
3701 (defun js2-print-yield-node (n i)
3702 (insert (js2-make-pad i))
3703 (insert "yield")
3704 (when (js2-yield-node-value n)
3705 (insert " ")
3706 (js2-print-ast (js2-yield-node-value n) 0)))
3707
3708 (defstruct (js2-paren-node
3709 (:include js2-node)
3710 (:constructor nil)
3711 (:constructor make-js2-paren-node (&key (type js2-LP)
3712 (pos js2-ts-cursor)
3713 len
3714 expr)))
3715 "AST node for a parenthesized expression.
3716 In particular, used when the parens are syntactically optional,
3717 as opposed to required parens such as those enclosing an if-conditional."
3718 expr) ; `js2-node'
3719
3720 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3721 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3722
3723 (defun js2-visit-paren-node (n v)
3724 (js2-visit-ast (js2-paren-node-expr n) v))
3725
3726 (defun js2-print-paren-node (n i)
3727 (insert (js2-make-pad i))
3728 (insert "(")
3729 (js2-print-ast (js2-paren-node-expr n) 0)
3730 (insert ")"))
3731
3732 (defstruct (js2-array-comp-node
3733 (:include js2-scope)
3734 (:constructor nil)
3735 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3736 (pos js2-ts-cursor)
3737 len
3738 result
3739 loops
3740 filter
3741 if-pos
3742 lp
3743 rp)))
3744 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3745 result ; result expression (just after left-bracket)
3746 loops ; a lisp list of `js2-array-comp-loop-node'
3747 filter ; guard/filter expression
3748 if-pos ; buffer pos of 'if' keyword, if present, else nil
3749 lp ; buffer position of if-guard left-paren, or nil if not present
3750 rp) ; buffer position of if-guard right-paren, or nil if not present
3751
3752 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3753 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3754
3755 (defun js2-visit-array-comp-node (n v)
3756 (js2-visit-ast (js2-array-comp-node-result n) v)
3757 (dolist (l (js2-array-comp-node-loops n))
3758 (js2-visit-ast l v))
3759 (js2-visit-ast (js2-array-comp-node-filter n) v))
3760
3761 (defun js2-print-array-comp-node (n i)
3762 (let ((pad (js2-make-pad i))
3763 (result (js2-array-comp-node-result n))
3764 (loops (js2-array-comp-node-loops n))
3765 (filter (js2-array-comp-node-filter n)))
3766 (insert pad "[")
3767 (js2-print-ast result 0)
3768 (dolist (l loops)
3769 (insert " ")
3770 (js2-print-ast l 0))
3771 (when filter
3772 (insert " if (")
3773 (js2-print-ast filter 0)
3774 (insert ")"))
3775 (insert "]")))
3776
3777 (defstruct (js2-array-comp-loop-node
3778 (:include js2-for-in-node)
3779 (:constructor nil)
3780 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3781 (pos js2-ts-cursor)
3782 len
3783 iterator
3784 object
3785 in-pos
3786 foreach-p
3787 each-pos
3788 forof-p
3789 lp rp)))
3790 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3791
3792 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3793 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3794
3795 (defun js2-visit-array-comp-loop (n v)
3796 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3797 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3798
3799 (defun js2-print-array-comp-loop (n i)
3800 (insert "for (")
3801 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3802 (if (js2-array-comp-loop-node-forof-p n)
3803 (insert " of ")
3804 (insert " in "))
3805 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3806 (insert ")"))
3807
3808 (defstruct (js2-empty-expr-node
3809 (:include js2-node)
3810 (:constructor nil)
3811 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3812 (pos js2-token-beg)
3813 len)))
3814 "AST node for an empty expression.")
3815
3816 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3817 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3818
3819 (defstruct (js2-xml-node
3820 (:include js2-block-node)
3821 (:constructor nil)
3822 (:constructor make-js2-xml-node (&key (type js2-XML)
3823 (pos js2-token-beg)
3824 len
3825 kids)))
3826 "AST node for initial parse of E4X literals.
3827 The kids field is a list of XML fragments, each a `js2-string-node' or
3828 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3829
3830 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3831 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3832
3833 (defun js2-print-xml-node (n i)
3834 (dolist (kid (js2-xml-node-kids n))
3835 (js2-print-ast kid i)))
3836
3837 (defstruct (js2-xml-js-expr-node
3838 (:include js2-xml-node)
3839 (:constructor nil)
3840 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3841 (pos js2-ts-cursor)
3842 len
3843 expr)))
3844 "AST node for an embedded JavaScript {expression} in an E4X literal.
3845 The start and end fields correspond to the curly-braces."
3846 expr) ; a `js2-expr-node' of some sort
3847
3848 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3849 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3850
3851 (defun js2-visit-xml-js-expr (n v)
3852 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3853
3854 (defun js2-print-xml-js-expr (n i)
3855 (insert (js2-make-pad i))
3856 (insert "{")
3857 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3858 (insert "}"))
3859
3860 (defstruct (js2-xml-dot-query-node
3861 (:include js2-infix-node)
3862 (:constructor nil)
3863 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3864 (pos js2-ts-cursor)
3865 op-pos
3866 len
3867 left
3868 right
3869 rp)))
3870 "AST node for an E4X foo.(bar) filter expression.
3871 Note that the left-paren is automatically the character immediately
3872 following the dot (.) in the operator. No whitespace is permitted
3873 between the dot and the lp by the scanner."
3874 rp)
3875
3876 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3877 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3878
3879 (defun js2-print-xml-dot-query (n i)
3880 (insert (js2-make-pad i))
3881 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3882 (insert ".(")
3883 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3884 (insert ")"))
3885
3886 (defstruct (js2-xml-ref-node
3887 (:include js2-node)
3888 (:constructor nil)) ; abstract
3889 "Base type for E4X XML attribute-access or property-get expressions.
3890 Such expressions can take a variety of forms. The general syntax has
3891 three parts:
3892
3893 - (optional) an @ (specifying an attribute access)
3894 - (optional) a namespace (a `js2-name-node') and double-colon
3895 - (required) either a `js2-name-node' or a bracketed [expression]
3896
3897 The property-name expressions (examples: ns::name, @name) are
3898 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3899 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3900
3901 This node type (or more specifically, its subclasses) will sometimes
3902 be the right-hand child of a `js2-prop-get-node' or a
3903 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3904 The `js2-xml-ref-node' may also be a standalone primary expression with
3905 no explicit target, which is valid in certain expression contexts such as
3906
3907 company..employee.(@id < 100)
3908
3909 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3910 expression whose parent is a `js2-xml-dot-query-node'."
3911 namespace
3912 at-pos
3913 colon-pos)
3914
3915 (defsubst js2-xml-ref-node-attr-access-p (node)
3916 "Return non-nil if this expression began with an @-token."
3917 (and (numberp (js2-xml-ref-node-at-pos node))
3918 (plusp (js2-xml-ref-node-at-pos node))))
3919
3920 (defstruct (js2-xml-prop-ref-node
3921 (:include js2-xml-ref-node)
3922 (:constructor nil)
3923 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3924 (pos js2-token-beg)
3925 len
3926 propname
3927 namespace
3928 at-pos
3929 colon-pos)))
3930 "AST node for an E4X XML [expr] property-ref expression.
3931 The JavaScript syntax is an optional @, an optional ns::, and a name.
3932
3933 [ '@' ] [ name '::' ] name
3934
3935 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3936 @ns::*, @*::attr, @*::*, and @*.
3937
3938 The node starts at the @ token, if present. Otherwise it starts at the
3939 namespace name. The node bounds extend through the closing right-bracket,
3940 or if it is missing due to a syntax error, through the end of the index
3941 expression."
3942 propname)
3943
3944 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3945 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3946
3947 (defun js2-visit-xml-prop-ref-node (n v)
3948 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3949 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3950
3951 (defun js2-print-xml-prop-ref-node (n i)
3952 (insert (js2-make-pad i))
3953 (if (js2-xml-ref-node-attr-access-p n)
3954 (insert "@"))
3955 (when (js2-xml-prop-ref-node-namespace n)
3956 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3957 (insert "::"))
3958 (if (js2-xml-prop-ref-node-propname n)
3959 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3960
3961 (defstruct (js2-xml-elem-ref-node
3962 (:include js2-xml-ref-node)
3963 (:constructor nil)
3964 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3965 (pos js2-token-beg)
3966 len
3967 expr
3968 lb
3969 rb
3970 namespace
3971 at-pos
3972 colon-pos)))
3973 "AST node for an E4X XML [expr] member-ref expression.
3974 Syntax:
3975
3976 [ '@' ] [ name '::' ] '[' expr ']'
3977
3978 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3979
3980 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3981 is not a legal E4X XML element-ref expression, since it's already used
3982 for standard JavaScript element-get array indexing. Hence, a
3983 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3984 non-nil namespace node, or both.
3985
3986 The node starts at the @ token, if present. Otherwise it starts
3987 at the namespace name. The node bounds extend through the closing
3988 right-bracket, or if it is missing due to a syntax error, through the
3989 end of the index expression."
3990 expr ; the bracketed index expression
3991 lb
3992 rb)
3993
3994 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3995 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3996
3997 (defun js2-visit-xml-elem-ref-node (n v)
3998 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3999 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4000
4001 (defun js2-print-xml-elem-ref-node (n i)
4002 (insert (js2-make-pad i))
4003 (if (js2-xml-ref-node-attr-access-p n)
4004 (insert "@"))
4005 (when (js2-xml-elem-ref-node-namespace n)
4006 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4007 (insert "::"))
4008 (insert "[")
4009 (if (js2-xml-elem-ref-node-expr n)
4010 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4011 (insert "]"))
4012
4013 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4014
4015 (defstruct (js2-xml-start-tag-node
4016 (:include js2-xml-node)
4017 (:constructor nil)
4018 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4019 (pos js2-ts-cursor)
4020 len
4021 name
4022 attrs
4023 kids
4024 empty-p)))
4025 "AST node for an XML start-tag. Not currently used.
4026 The `kids' field is a lisp list of child content nodes."
4027 name ; a `js2-xml-name-node'
4028 attrs ; a lisp list of `js2-xml-attr-node'
4029 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4030
4031 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4032 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4033
4034 (defun js2-visit-xml-start-tag (n v)
4035 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4036 (dolist (attr (js2-xml-start-tag-node-attrs n))
4037 (js2-visit-ast attr v))
4038 (js2-visit-block n v))
4039
4040 (defun js2-print-xml-start-tag (n i)
4041 (insert (js2-make-pad i) "<")
4042 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4043 (when (js2-xml-start-tag-node-attrs n)
4044 (insert " ")
4045 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4046 (insert ">"))
4047
4048 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4049 ;; and add the end-tag to the kids list of the parent as well.
4050 (defstruct (js2-xml-end-tag-node
4051 (:include js2-xml-node)
4052 (:constructor nil)
4053 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4054 (pos js2-ts-cursor)
4055 len
4056 name)))
4057 "AST node for an XML end-tag. Not currently used."
4058 name) ; a `js2-xml-name-node'
4059
4060 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4061 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4062
4063 (defun js2-visit-xml-end-tag (n v)
4064 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4065
4066 (defun js2-print-xml-end-tag (n i)
4067 (insert (js2-make-pad i))
4068 (insert "</")
4069 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4070 (insert ">"))
4071
4072 (defstruct (js2-xml-name-node
4073 (:include js2-xml-node)
4074 (:constructor nil)
4075 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4076 (pos js2-ts-cursor)
4077 len
4078 namespace
4079 kids)))
4080 "AST node for an E4X XML name. Not currently used.
4081 Any XML name can be qualified with a namespace, hence the namespace field.
4082 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4083 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4084 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4085 namespace) ; a `js2-string-node'
4086
4087 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4088 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4089
4090 (defun js2-visit-xml-name-node (n v)
4091 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4092
4093 (defun js2-print-xml-name-node (n i)
4094 (insert (js2-make-pad i))
4095 (when (js2-xml-name-node-namespace n)
4096 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4097 (insert "::"))
4098 (dolist (kid (js2-xml-name-node-kids n))
4099 (js2-print-ast kid 0)))
4100
4101 (defstruct (js2-xml-pi-node
4102 (:include js2-xml-node)
4103 (:constructor nil)
4104 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4105 (pos js2-ts-cursor)
4106 len
4107 name
4108 attrs)))
4109 "AST node for an E4X XML processing instruction. Not currently used."
4110 name ; a `js2-xml-name-node'
4111 attrs) ; a list of `js2-xml-attr-node'
4112
4113 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4114 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4115
4116 (defun js2-visit-xml-pi-node (n v)
4117 (js2-visit-ast (js2-xml-pi-node-name n) v)
4118 (dolist (attr (js2-xml-pi-node-attrs n))
4119 (js2-visit-ast attr v)))
4120
4121 (defun js2-print-xml-pi-node (n i)
4122 (insert (js2-make-pad i) "<?")
4123 (js2-print-ast (js2-xml-pi-node-name n))
4124 (when (js2-xml-pi-node-attrs n)
4125 (insert " ")
4126 (js2-print-list (js2-xml-pi-node-attrs n)))
4127 (insert "?>"))
4128
4129 (defstruct (js2-xml-cdata-node
4130 (:include js2-xml-node)
4131 (:constructor nil)
4132 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4133 (pos js2-ts-cursor)
4134 len
4135 content)))
4136 "AST node for a CDATA escape section. Not currently used."
4137 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4138
4139 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4140 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4141
4142 (defun js2-visit-xml-cdata-node (n v)
4143 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4144
4145 (defun js2-print-xml-cdata-node (n i)
4146 (insert (js2-make-pad i))
4147 (js2-print-ast (js2-xml-cdata-node-content n)))
4148
4149 (defstruct (js2-xml-attr-node
4150 (:include js2-xml-node)
4151 (:constructor nil)
4152 (:constructor make-js2-attr-node (&key (type js2-XML)
4153 (pos js2-ts-cursor)
4154 len
4155 name
4156 value
4157 eq-pos
4158 quote-type)))
4159 "AST node representing a foo='bar' XML attribute value. Not yet used."
4160 name ; a `js2-xml-name-node'
4161 value ; a `js2-xml-name-node'
4162 eq-pos ; buffer position of "=" sign
4163 quote-type) ; 'single or 'double
4164
4165 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4166 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4167
4168 (defun js2-visit-xml-attr-node (n v)
4169 (js2-visit-ast (js2-xml-attr-node-name n) v)
4170 (js2-visit-ast (js2-xml-attr-node-value n) v))
4171
4172 (defun js2-print-xml-attr-node (n i)
4173 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4174 "'"
4175 "\"")))
4176 (insert (js2-make-pad i))
4177 (js2-print-ast (js2-xml-attr-node-name n) 0)
4178 (insert "=" quote)
4179 (js2-print-ast (js2-xml-attr-node-value n) 0)
4180 (insert quote)))
4181
4182 (defstruct (js2-xml-text-node
4183 (:include js2-xml-node)
4184 (:constructor nil)
4185 (:constructor make-js2-text-node (&key (type js2-XML)
4186 (pos js2-ts-cursor)
4187 len
4188 content)))
4189 "AST node for an E4X XML text node. Not currently used."
4190 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4191
4192 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4193 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4194
4195 (defun js2-visit-xml-text-node (n v)
4196 (js2-visit-ast (js2-xml-text-node-content n) v))
4197
4198 (defun js2-print-xml-text-node (n i)
4199 (insert (js2-make-pad i))
4200 (dolist (kid (js2-xml-text-node-content n))
4201 (js2-print-ast kid)))
4202
4203 (defstruct (js2-xml-comment-node
4204 (:include js2-xml-node)
4205 (:constructor nil)
4206 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4207 (pos js2-ts-cursor)
4208 len)))
4209 "AST node for E4X XML comment. Not currently used.")
4210
4211 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4212 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4213
4214 (defun js2-print-xml-comment (n i)
4215 (insert (js2-make-pad i)
4216 (js2-node-string n)))
4217
4218 ;;; Node utilities
4219
4220 (defsubst js2-node-line (n)
4221 "Fetch the source line number at the start of node N.
4222 This is O(n) in the length of the source buffer; use prudently."
4223 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4224
4225 (defsubst js2-block-node-kid (n i)
4226 "Return child I of node N, or nil if there aren't that many."
4227 (nth i (js2-block-node-kids n)))
4228
4229 (defsubst js2-block-node-first (n)
4230 "Return first child of block node N, or nil if there is none."
4231 (first (js2-block-node-kids n)))
4232
4233 (defun js2-node-root (n)
4234 "Return the root of the AST containing N.
4235 If N has no parent pointer, returns N."
4236 (let ((parent (js2-node-parent n)))
4237 (if parent
4238 (js2-node-root parent)
4239 n)))
4240
4241 (defun js2-node-position-in-parent (node &optional parent)
4242 "Return the position of NODE in parent's block-kids list.
4243 PARENT can be supplied if known. Positioned returned is zero-indexed.
4244 Returns 0 if NODE is not a child of a block statement, or if NODE
4245 is not a statement node."
4246 (let ((p (or parent (js2-node-parent node)))
4247 (i 0))
4248 (if (not (js2-block-node-p p))
4249 i
4250 (or (js2-position node (js2-block-node-kids p))
4251 0))))
4252
4253 (defsubst js2-node-short-name (n)
4254 "Return the short name of node N as a string, e.g. `js2-if-node'."
4255 (substring (symbol-name (aref n 0))
4256 (length "cl-struct-")))
4257
4258 (defsubst js2-node-child-list (node)
4259 "Return the child list for NODE, a lisp list of nodes.
4260 Works for block nodes, array nodes, obj literals, funarg lists,
4261 var decls and try nodes (for catch clauses). Note that you should call
4262 `js2-block-node-kids' on the function body for the body statements.
4263 Returns nil for zero-length child lists or unsupported nodes."
4264 (cond
4265 ((js2-function-node-p node)
4266 (js2-function-node-params node))
4267 ((js2-block-node-p node)
4268 (js2-block-node-kids node))
4269 ((js2-try-node-p node)
4270 (js2-try-node-catch-clauses node))
4271 ((js2-array-node-p node)
4272 (js2-array-node-elems node))
4273 ((js2-object-node-p node)
4274 (js2-object-node-elems node))
4275 ((js2-call-node-p node)
4276 (js2-call-node-args node))
4277 ((js2-new-node-p node)
4278 (js2-new-node-args node))
4279 ((js2-var-decl-node-p node)
4280 (js2-var-decl-node-kids node))
4281 (t
4282 nil)))
4283
4284 (defsubst js2-node-set-child-list (node kids)
4285 "Set the child list for NODE to KIDS."
4286 (cond
4287 ((js2-function-node-p node)
4288 (setf (js2-function-node-params node) kids))
4289 ((js2-block-node-p node)
4290 (setf (js2-block-node-kids node) kids))
4291 ((js2-try-node-p node)
4292 (setf (js2-try-node-catch-clauses node) kids))
4293 ((js2-array-node-p node)
4294 (setf (js2-array-node-elems node) kids))
4295 ((js2-object-node-p node)
4296 (setf (js2-object-node-elems node) kids))
4297 ((js2-call-node-p node)
4298 (setf (js2-call-node-args node) kids))
4299 ((js2-new-node-p node)
4300 (setf (js2-new-node-args node) kids))
4301 ((js2-var-decl-node-p node)
4302 (setf (js2-var-decl-node-kids node) kids))
4303 (t
4304 (error "Unsupported node type: %s" (js2-node-short-name node))))
4305 kids)
4306
4307 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4308 (defconst js2-paren-expr-nodes
4309 '(cl-struct-js2-array-comp-loop-node
4310 cl-struct-js2-array-comp-node
4311 cl-struct-js2-call-node
4312 cl-struct-js2-catch-node
4313 cl-struct-js2-do-node
4314 cl-struct-js2-elem-get-node
4315 cl-struct-js2-for-in-node
4316 cl-struct-js2-for-node
4317 cl-struct-js2-function-node
4318 cl-struct-js2-if-node
4319 cl-struct-js2-let-node
4320 cl-struct-js2-new-node
4321 cl-struct-js2-paren-node
4322 cl-struct-js2-switch-node
4323 cl-struct-js2-while-node
4324 cl-struct-js2-with-node
4325 cl-struct-js2-xml-dot-query-node)
4326 "Node types that can have a parenthesized child expression.
4327 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4328
4329 (defsubst js2-paren-expr-node-p (node)
4330 "Return t for nodes that typically have a parenthesized child expression.
4331 Useful for computing the indentation anchors for arg-lists and conditions.
4332 Note that it may return a false positive, for instance when NODE is
4333 a `js2-new-node' and there are no arguments or parentheses."
4334 (memq (aref node 0) js2-paren-expr-nodes))
4335
4336 ;; Fake polymorphism... yech.
4337 (defsubst js2-node-lp (node)
4338 "Return relative left-paren position for NODE, if applicable.
4339 For `js2-elem-get-node' structs, returns left-bracket position.
4340 Note that the position may be nil in the case of a parse error."
4341 (cond
4342 ((js2-elem-get-node-p node)
4343 (js2-elem-get-node-lb node))
4344 ((js2-loop-node-p node)
4345 (js2-loop-node-lp node))
4346 ((js2-function-node-p node)
4347 (js2-function-node-lp node))
4348 ((js2-if-node-p node)
4349 (js2-if-node-lp node))
4350 ((js2-new-node-p node)
4351 (js2-new-node-lp node))
4352 ((js2-call-node-p node)
4353 (js2-call-node-lp node))
4354 ((js2-paren-node-p node)
4355 (js2-node-pos node))
4356 ((js2-switch-node-p node)
4357 (js2-switch-node-lp node))
4358 ((js2-catch-node-p node)
4359 (js2-catch-node-lp node))
4360 ((js2-let-node-p node)
4361 (js2-let-node-lp node))
4362 ((js2-array-comp-node-p node)
4363 (js2-array-comp-node-lp node))
4364 ((js2-with-node-p node)
4365 (js2-with-node-lp node))
4366 ((js2-xml-dot-query-node-p node)
4367 (1+ (js2-infix-node-op-pos node)))
4368 (t
4369 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4370
4371 ;; Fake polymorphism... blech.
4372 (defsubst js2-node-rp (node)
4373 "Return relative right-paren position for NODE, if applicable.
4374 For `js2-elem-get-node' structs, returns right-bracket position.
4375 Note that the position may be nil in the case of a parse error."
4376 (cond
4377 ((js2-elem-get-node-p node)
4378 (js2-elem-get-node-rb node))
4379 ((js2-loop-node-p node)
4380 (js2-loop-node-rp node))
4381 ((js2-function-node-p node)
4382 (js2-function-node-rp node))
4383 ((js2-if-node-p node)
4384 (js2-if-node-rp node))
4385 ((js2-new-node-p node)
4386 (js2-new-node-rp node))
4387 ((js2-call-node-p node)
4388 (js2-call-node-rp node))
4389 ((js2-paren-node-p node)
4390 (+ (js2-node-pos node) (js2-node-len node)))
4391 ((js2-switch-node-p node)
4392 (js2-switch-node-rp node))
4393 ((js2-catch-node-p node)
4394 (js2-catch-node-rp node))
4395 ((js2-let-node-p node)
4396 (js2-let-node-rp node))
4397 ((js2-array-comp-node-p node)
4398 (js2-array-comp-node-rp node))
4399 ((js2-with-node-p node)
4400 (js2-with-node-rp node))
4401 ((js2-xml-dot-query-node-p node)
4402 (1+ (js2-xml-dot-query-node-rp node)))
4403 (t
4404 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4405
4406 (defsubst js2-node-first-child (node)
4407 "Returns the first element of `js2-node-child-list' for NODE."
4408 (car (js2-node-child-list node)))
4409
4410 (defsubst js2-node-last-child (node)
4411 "Returns the last element of `js2-node-last-child' for NODE."
4412 (car (last (js2-node-child-list node))))
4413
4414 (defun js2-node-prev-sibling (node)
4415 "Return the previous statement in parent.
4416 Works for parents supported by `js2-node-child-list'.
4417 Returns nil if NODE is not in the parent, or PARENT is
4418 not a supported node, or if NODE is the first child."
4419 (let* ((p (js2-node-parent node))
4420 (kids (js2-node-child-list p))
4421 (sib (car kids)))
4422 (while (and kids
4423 (not (eq node (cadr kids))))
4424 (setq kids (cdr kids)
4425 sib (car kids)))
4426 sib))
4427
4428 (defun js2-node-next-sibling (node)
4429 "Return the next statement in parent block.
4430 Returns nil if NODE is not in the block, or PARENT is not
4431 a block node, or if NODE is the last statement."
4432 (let* ((p (js2-node-parent node))
4433 (kids (js2-node-child-list p)))
4434 (while (and kids
4435 (not (eq node (car kids))))
4436 (setq kids (cdr kids)))
4437 (cadr kids)))
4438
4439 (defun js2-node-find-child-before (pos parent &optional after)
4440 "Find the last child that starts before POS in parent.
4441 If AFTER is non-nil, returns first child starting after POS.
4442 POS is an absolute buffer position. PARENT is any node
4443 supported by `js2-node-child-list'.
4444 Returns nil if no applicable child is found."
4445 (let ((kids (if (js2-function-node-p parent)
4446 (js2-block-node-kids (js2-function-node-body parent))
4447 (js2-node-child-list parent)))
4448 (beg (if (js2-function-node-p parent)
4449 (js2-node-abs-pos (js2-function-node-body parent))
4450 (js2-node-abs-pos parent)))
4451 kid
4452 result
4453 fn
4454 (continue t))
4455 (setq fn (if after '>= '<))
4456 (while (and kids continue)
4457 (setq kid (car kids))
4458 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4459 (setq result kid
4460 continue (if after nil t))
4461 (setq continue (if after t nil)))
4462 (setq kids (cdr kids)))
4463 result))
4464
4465 (defun js2-node-find-child-after (pos parent)
4466 "Find first child that starts after POS in parent.
4467 POS is an absolute buffer position. PARENT is any node
4468 supported by `js2-node-child-list'.
4469 Returns nil if no applicable child is found."
4470 (js2-node-find-child-before pos parent 'after))
4471
4472 (defun js2-node-replace-child (pos parent new-node)
4473 "Replace node at index POS in PARENT with NEW-NODE.
4474 Only works for parents supported by `js2-node-child-list'."
4475 (let ((kids (js2-node-child-list parent))
4476 (i 0))
4477 (while (< i pos)
4478 (setq kids (cdr kids)
4479 i (1+ i)))
4480 (setcar kids new-node)
4481 (js2-node-add-children parent new-node)))
4482
4483 (defun js2-node-buffer (n)
4484 "Return the buffer associated with AST N.
4485 Returns nil if the buffer is not set as a property on the root
4486 node, or if parent links were not recorded during parsing."
4487 (let ((root (js2-node-root n)))
4488 (and root
4489 (js2-ast-root-p root)
4490 (js2-ast-root-buffer root))))
4491
4492 (defsubst js2-block-node-push (n kid)
4493 "Push js2-node KID onto the end of js2-block-node N's child list.
4494 KID is always added to the -end- of the kids list.
4495 Function also calls `js2-node-add-children' to add the parent link."
4496 (let ((kids (js2-node-child-list n)))
4497 (if kids
4498 (setcdr kids (nconc (cdr kids) (list kid)))
4499 (js2-node-set-child-list n (list kid)))
4500 (js2-node-add-children n kid)))
4501
4502 (defun js2-node-string (node)
4503 (let ((buf (js2-node-buffer node))
4504 pos)
4505 (unless buf
4506 (error "No buffer available for node %s" node))
4507 (with-current-buffer buf
4508 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4509 (+ pos (js2-node-len node))))))
4510
4511 ;; Container for storing the node we're looking for in a traversal.
4512 (js2-deflocal js2-discovered-node nil)
4513
4514 ;; Keep track of absolute node position during traversals.
4515 (js2-deflocal js2-visitor-offset nil)
4516
4517 (js2-deflocal js2-node-search-point nil)
4518
4519 (when js2-mode-dev-mode-p
4520 (defun js2-find-node-at-point ()
4521 (interactive)
4522 (let ((node (js2-node-at-point)))
4523 (message "%s" (or node "No node found at point"))))
4524 (defun js2-node-name-at-point ()
4525 (interactive)
4526 (let ((node (js2-node-at-point)))
4527 (message "%s" (if node
4528 (js2-node-short-name node)
4529 "No node found at point.")))))
4530
4531 (defun js2-node-at-point (&optional pos skip-comments)
4532 "Return AST node at POS, a buffer position, defaulting to current point.
4533 The `js2-mode-ast' variable must be set to the current parse tree.
4534 Signals an error if the AST (`js2-mode-ast') is nil.
4535 Always returns a node - if it can't find one, it returns the root.
4536 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4537 (let ((ast js2-mode-ast)
4538 result)
4539 (unless ast
4540 (error "No JavaScript AST available"))
4541 ;; Look through comments first, since they may be inside nodes that
4542 ;; would otherwise report a match.
4543 (setq pos (or pos (point))
4544 result (if (> pos (js2-node-abs-end ast))
4545 ast
4546 (if (not skip-comments)
4547 (js2-comment-at-point pos))))
4548 (unless result
4549 (setq js2-discovered-node nil
4550 js2-visitor-offset 0
4551 js2-node-search-point pos)
4552 (unwind-protect
4553 (catch 'js2-visit-done
4554 (js2-visit-ast ast #'js2-node-at-point-visitor))
4555 (setq js2-visitor-offset nil
4556 js2-node-search-point nil))
4557 (setq result js2-discovered-node))
4558 ;; may have found a comment beyond end of last child node,
4559 ;; since visiting the ast-root looks at the comment-list last.
4560 (if (and skip-comments
4561 (js2-comment-node-p result))
4562 (setq result nil))
4563 (or result js2-mode-ast)))
4564
4565 (defun js2-node-at-point-visitor (node end-p)
4566 (let ((rel-pos (js2-node-pos node))
4567 abs-pos
4568 abs-end
4569 (point js2-node-search-point))
4570 (cond
4571 (end-p
4572 ;; this evaluates to a non-nil return value, even if it's zero
4573 (decf js2-visitor-offset rel-pos))
4574 ;; we already looked for comments before visiting, and don't want them now
4575 ((js2-comment-node-p node)
4576 nil)
4577 (t
4578 (setq abs-pos (incf js2-visitor-offset rel-pos)
4579 ;; we only want to use the node if the point is before
4580 ;; the last character position in the node, so we decrement
4581 ;; the absolute end by 1.
4582 abs-end (+ abs-pos (js2-node-len node) -1))
4583 (cond
4584 ;; If this node starts after search-point, stop the search.
4585 ((> abs-pos point)
4586 (throw 'js2-visit-done nil))
4587 ;; If this node ends before the search-point, don't check kids.
4588 ((> point abs-end)
4589 nil)
4590 (t
4591 ;; Otherwise point is within this node, possibly in a child.
4592 (setq js2-discovered-node node)
4593 t)))))) ; keep processing kids to look for more specific match
4594
4595 (defsubst js2-block-comment-p (node)
4596 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4597 (and (js2-comment-node-p node)
4598 (memq (js2-comment-node-format node) '(jsdoc block))))
4599
4600 ;; TODO: put the comments in a vector and binary-search them instead
4601 (defun js2-comment-at-point (&optional pos)
4602 "Look through scanned comment nodes for one containing POS.
4603 POS is a buffer position that defaults to current point.
4604 Function returns nil if POS was not in any comment node."
4605 (let ((ast js2-mode-ast)
4606 (x (or pos (point)))
4607 beg
4608 end)
4609 (unless ast
4610 (error "No JavaScript AST available"))
4611 (catch 'done
4612 ;; Comments are stored in lexical order.
4613 (dolist (comment (js2-ast-root-comments ast) nil)
4614 (setq beg (js2-node-abs-pos comment)
4615 end (+ beg (js2-node-len comment)))
4616 (if (and (>= x beg)
4617 (<= x end))
4618 (throw 'done comment))))))
4619
4620 (defun js2-mode-find-parent-fn (node)
4621 "Find function enclosing NODE.
4622 Returns nil if NODE is not inside a function."
4623 (setq node (js2-node-parent node))
4624 (while (and node (not (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 (and (js2-function-node-p node) node))
4627
4628 (defun js2-mode-find-enclosing-fn (node)
4629 "Find function or root enclosing NODE."
4630 (if (js2-ast-root-p node)
4631 node
4632 (setq node (js2-node-parent node))
4633 (while (not (or (js2-ast-root-p node)
4634 (js2-function-node-p node)))
4635 (setq node (js2-node-parent node)))
4636 node))
4637
4638 (defun js2-mode-find-enclosing-node (beg end)
4639 "Find script or function fully enclosing BEG and END."
4640 (let ((node (js2-node-at-point beg))
4641 pos
4642 (continue t))
4643 (while continue
4644 (if (or (js2-ast-root-p node)
4645 (and (js2-function-node-p node)
4646 (<= (setq pos (js2-node-abs-pos node)) beg)
4647 (>= (+ pos (js2-node-len node)) end)))
4648 (setq continue nil)
4649 (setq node (js2-node-parent node))))
4650 node))
4651
4652 (defun js2-node-parent-script-or-fn (node)
4653 "Find script or function immediately enclosing NODE.
4654 If NODE is the ast-root, returns nil."
4655 (if (js2-ast-root-p node)
4656 nil
4657 (setq node (js2-node-parent node))
4658 (while (and node (not (or (js2-function-node-p node)
4659 (js2-script-node-p node))))
4660 (setq node (js2-node-parent node)))
4661 node))
4662
4663 (defsubst js2-nested-function-p (node)
4664 "Return t if NODE is a nested function, or is inside a nested function."
4665 (unless (js2-ast-root-p node)
4666 (js2-function-node-p (if (js2-function-node-p node)
4667 (js2-node-parent-script-or-fn node)
4668 (js2-node-parent-script-or-fn
4669 (js2-node-parent-script-or-fn node))))))
4670
4671 (defsubst js2-function-param-node-p (node)
4672 "Return non-nil if NODE is a param node of a `js2-function-node'."
4673 (let ((parent (js2-node-parent node)))
4674 (and parent
4675 (js2-function-node-p parent)
4676 (memq node (js2-function-node-params parent)))))
4677
4678 (defsubst js2-mode-shift-kids (kids start offset)
4679 (dolist (kid kids)
4680 (if (> (js2-node-pos kid) start)
4681 (incf (js2-node-pos kid) offset))))
4682
4683 (defsubst js2-mode-shift-children (parent start offset)
4684 "Update start-positions of all children of PARENT beyond START."
4685 (let ((root (js2-node-root parent)))
4686 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4687 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4688
4689 (defsubst js2-node-is-descendant (node ancestor)
4690 "Return t if NODE is a descendant of ANCESTOR."
4691 (while (and node
4692 (not (eq node ancestor)))
4693 (setq node (js2-node-parent node)))
4694 node)
4695
4696 ;;; visitor infrastructure
4697
4698 (defun js2-visit-none (node callback)
4699 "Visitor for AST node that have no node children."
4700 nil)
4701
4702 (defun js2-print-none (node indent)
4703 "Visitor for AST node with no printed representation.")
4704
4705 (defun js2-print-body (node indent)
4706 "Print a statement, or a block without braces."
4707 (if (js2-block-node-p node)
4708 (dolist (kid (js2-block-node-kids node))
4709 (js2-print-ast kid indent))
4710 (js2-print-ast node indent)))
4711
4712 (defun js2-print-list (args &optional delimiter)
4713 (loop with len = (length args)
4714 for arg in args
4715 for count from 1
4716 do
4717 (js2-print-ast arg 0)
4718 (if (< count len)
4719 (insert (or delimiter ", ")))))
4720
4721 (defun js2-print-tree (ast)
4722 "Prints an AST to the current buffer.
4723 Makes `js2-ast-parent-nodes' available to the printer functions."
4724 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4725 (js2-print-ast ast)))
4726
4727 (defun js2-print-ast (node &optional indent)
4728 "Helper function for printing AST nodes.
4729 Requires `js2-ast-parent-nodes' to be non-nil.
4730 You should use `js2-print-tree' instead of this function."
4731 (let ((printer (get (aref node 0) 'js2-printer))
4732 (i (or indent 0))
4733 (pos (js2-node-abs-pos node)))
4734 ;; TODO: wedge comments in here somewhere
4735 (if printer
4736 (funcall printer node i))))
4737
4738 (defconst js2-side-effecting-tokens
4739 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4740 (dolist (tt (list js2-ASSIGN
4741 js2-ASSIGN_ADD
4742 js2-ASSIGN_BITAND
4743 js2-ASSIGN_BITOR
4744 js2-ASSIGN_BITXOR
4745 js2-ASSIGN_DIV
4746 js2-ASSIGN_LSH
4747 js2-ASSIGN_MOD
4748 js2-ASSIGN_MUL
4749 js2-ASSIGN_RSH
4750 js2-ASSIGN_SUB
4751 js2-ASSIGN_URSH
4752 js2-BLOCK
4753 js2-BREAK
4754 js2-CALL
4755 js2-CATCH
4756 js2-CATCH_SCOPE
4757 js2-CONST
4758 js2-CONTINUE
4759 js2-DEBUGGER
4760 js2-DEC
4761 js2-DELPROP
4762 js2-DEL_REF
4763 js2-DO
4764 js2-ELSE
4765 js2-EMPTY
4766 js2-ENTERWITH
4767 js2-EXPORT
4768 js2-EXPR_RESULT
4769 js2-FINALLY
4770 js2-FOR
4771 js2-FUNCTION
4772 js2-GOTO
4773 js2-IF
4774 js2-IFEQ
4775 js2-IFNE
4776 js2-IMPORT
4777 js2-INC
4778 js2-JSR
4779 js2-LABEL
4780 js2-LEAVEWITH
4781 js2-LET
4782 js2-LETEXPR
4783 js2-LOCAL_BLOCK
4784 js2-LOOP
4785 js2-NEW
4786 js2-REF_CALL
4787 js2-RETHROW
4788 js2-RETURN
4789 js2-RETURN_RESULT
4790 js2-SEMI
4791 js2-SETELEM
4792 js2-SETELEM_OP
4793 js2-SETNAME
4794 js2-SETPROP
4795 js2-SETPROP_OP
4796 js2-SETVAR
4797 js2-SET_REF
4798 js2-SET_REF_OP
4799 js2-SWITCH
4800 js2-TARGET
4801 js2-THROW
4802 js2-TRY
4803 js2-VAR
4804 js2-WHILE
4805 js2-WITH
4806 js2-WITHEXPR
4807 js2-YIELD))
4808 (aset tokens tt t))
4809 (if js2-instanceof-has-side-effects
4810 (aset tokens js2-INSTANCEOF t))
4811 tokens))
4812
4813 (defun js2-node-has-side-effects (node)
4814 "Return t if NODE has side effects."
4815 (when node ; makes it easier to handle malformed expressions
4816 (let ((tt (js2-node-type node)))
4817 (cond
4818 ;; This doubtless needs some work, since EXPR_VOID is used
4819 ;; in several ways in Rhino, and I may not have caught them all.
4820 ;; I'll wait for people to notice incorrect warnings.
4821 ((and (= tt js2-EXPR_VOID)
4822 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4823 (let ((expr (js2-expr-stmt-node-expr node)))
4824 (or (js2-node-has-side-effects expr)
4825 (when (js2-string-node-p expr)
4826 (string= "use strict" (js2-string-node-value expr))))))
4827 ((= tt js2-COMMA)
4828 (js2-node-has-side-effects (js2-infix-node-right node)))
4829 ((or (= tt js2-AND)
4830 (= tt js2-OR))
4831 (or (js2-node-has-side-effects (js2-infix-node-right node))
4832 (js2-node-has-side-effects (js2-infix-node-left node))))
4833 ((= tt js2-HOOK)
4834 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4835 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4836 ((js2-paren-node-p node)
4837 (js2-node-has-side-effects (js2-paren-node-expr node)))
4838 ((= tt js2-ERROR) ; avoid cascaded error messages
4839 nil)
4840 (t
4841 (aref js2-side-effecting-tokens tt))))))
4842
4843 (defun js2-member-expr-leftmost-name (node)
4844 "For an expr such as foo.bar.baz, return leftmost node foo.
4845 NODE is any `js2-node' object. If it represents a member expression,
4846 which is any sequence of property gets, element-gets, function calls,
4847 or xml descendants/filter operators, then we look at the lexically
4848 leftmost (first) node in the chain. If it is a name-node we return it.
4849 Note that NODE can be a raw name-node and it will be returned as well.
4850 If NODE is not a name-node or member expression, or if it is a member
4851 expression whose leftmost target is not a name node, returns nil."
4852 (let ((continue t)
4853 result)
4854 (while (and continue (not result))
4855 (cond
4856 ((js2-name-node-p node)
4857 (setq result node))
4858 ((js2-prop-get-node-p node)
4859 (setq node (js2-prop-get-node-left node)))
4860 ;; TODO: handle call-nodes, xml-nodes, others?
4861 (t
4862 (setq continue nil))))
4863 result))
4864
4865 (defconst js2-stmt-node-types
4866 (list js2-BLOCK
4867 js2-BREAK
4868 js2-CONTINUE
4869 js2-DEFAULT ; e4x "default xml namespace" statement
4870 js2-DO
4871 js2-EXPR_RESULT
4872 js2-EXPR_VOID
4873 js2-FOR
4874 js2-IF
4875 js2-RETURN
4876 js2-SWITCH
4877 js2-THROW
4878 js2-TRY
4879 js2-WHILE
4880 js2-WITH)
4881 "Node types that only appear in statement contexts.
4882 The list does not include nodes that always appear as the child
4883 of another specific statement type, such as switch-cases,
4884 catch and finally blocks, and else-clauses. The list also excludes
4885 nodes like yield, let and var, which may appear in either expression
4886 or statement context, and in the latter context always have a
4887 `js2-expr-stmt-node' parent. Finally, the list does not include
4888 functions or scripts, which are treated separately from statements
4889 by the JavaScript parser and runtime.")
4890
4891 (defun js2-stmt-node-p (node)
4892 "Heuristic for figuring out if NODE is a statement.
4893 Some node types can appear in either an expression context or a
4894 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4895 For these node types in a statement context, the parent will be a
4896 `js2-expr-stmt-node'.
4897 Functions aren't included in the check."
4898 (memq (js2-node-type node) js2-stmt-node-types))
4899
4900 (defsubst js2-mode-find-first-stmt (node)
4901 "Search upward starting from NODE looking for a statement.
4902 For purposes of this function, a `js2-function-node' counts."
4903 (while (not (or (js2-stmt-node-p node)
4904 (js2-function-node-p node)))
4905 (setq node (js2-node-parent node)))
4906 node)
4907
4908 (defun js2-node-parent-stmt (node)
4909 "Return the node's first ancestor that is a statement.
4910 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4911 appearing in a statement context will have a parent that is a
4912 `js2-expr-stmt-node' that will be returned by this function."
4913 (let ((parent (js2-node-parent node)))
4914 (if (or (null parent)
4915 (js2-stmt-node-p parent)
4916 (and (js2-function-node-p parent)
4917 (not (eq (js2-function-node-form parent)
4918 'FUNCTION_EXPRESSION))))
4919 parent
4920 (js2-node-parent-stmt parent))))
4921
4922 ;; In the Mozilla Rhino sources, Roshan James writes:
4923 ;; Does consistent-return analysis on the function body when strict mode is
4924 ;; enabled.
4925 ;;
4926 ;; function (x) { return (x+1) }
4927 ;;
4928 ;; is ok, but
4929 ;;
4930 ;; function (x) { if (x < 0) return (x+1); }
4931 ;;
4932 ;; is not because the function can potentially return a value when the
4933 ;; condition is satisfied and if not, the function does not explicitly
4934 ;; return a value.
4935 ;;
4936 ;; This extends to checking mismatches such as "return" and "return <value>"
4937 ;; used in the same function. Warnings are not emitted if inconsistent
4938 ;; returns exist in code that can be statically shown to be unreachable.
4939 ;; Ex.
4940 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4941 ;;
4942 ;; emits no warning. However if the loop had a break statement, then a
4943 ;; warning would be emitted.
4944 ;;
4945 ;; The consistency analysis looks at control structures such as loops, ifs,
4946 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4947 ;; warns the user about an inconsistent set of termination possibilities.
4948 ;;
4949 ;; These flags enumerate the possible ways a statement/function can
4950 ;; terminate. These flags are used by endCheck() and by the Parser to
4951 ;; detect inconsistent return usage.
4952 ;;
4953 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4954 ;; able to execute (example: throw, continue)
4955 ;;
4956 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4957 ;; next one. Statement such as return dont. A compound statement may have
4958 ;; some branch that drops off control to the next statement.
4959 ;;
4960 ;; END_RETURNS indicates that the statement can return with no value.
4961 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4962 ;;
4963 ;; A compound statement such as
4964 ;; if (condition) {
4965 ;; return value;
4966 ;; }
4967 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4968
4969 (defconst js2-END_UNREACHED 0)
4970 (defconst js2-END_DROPS_OFF 1)
4971 (defconst js2-END_RETURNS 2)
4972 (defconst js2-END_RETURNS_VALUE 4)
4973 (defconst js2-END_YIELDS 8)
4974
4975 (defun js2-has-consistent-return-usage (node)
4976 "Check that every return usage in a function body is consistent.
4977 Returns t if the function satisfies strict mode requirement."
4978 (let ((n (js2-end-check node)))
4979 ;; either it doesn't return a value in any branch...
4980 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4981 ;; or it returns a value (or is unreached) at every branch
4982 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4983 js2-END_RETURNS
4984 js2-END_YIELDS)))))
4985
4986 (defun js2-end-check-if (node)
4987 "Returns in the then and else blocks must be consistent with each other.
4988 If there is no else block, then the return statement can fall through.
4989 Returns logical OR of END_* flags"
4990 (let ((th (js2-if-node-then-part node))
4991 (el (js2-if-node-else-part node)))
4992 (if (null th)
4993 js2-END_UNREACHED
4994 (logior (js2-end-check th) (if el
4995 (js2-end-check el)
4996 js2-END_DROPS_OFF)))))
4997
4998 (defun js2-end-check-switch (node)
4999 "Consistency of return statements is checked between the case statements.
5000 If there is no default, then the switch can fall through. If there is a
5001 default, we check to see if all code paths in the default return or if
5002 there is a code path that can fall through.
5003 Returns logical OR of END_* flags."
5004 (let ((rv js2-END_UNREACHED)
5005 default-case)
5006 ;; examine the cases
5007 (catch 'break
5008 (dolist (c (js2-switch-node-cases node))
5009 (if (js2-case-node-expr c)
5010 (js2-set-flag rv (js2-end-check-block c))
5011 (setq default-case c)
5012 (throw 'break nil))))
5013 ;; we don't care how the cases drop into each other
5014 (js2-clear-flag rv js2-END_DROPS_OFF)
5015 ;; examine the default
5016 (js2-set-flag rv (if default-case
5017 (js2-end-check default-case)
5018 js2-END_DROPS_OFF))
5019 rv))
5020
5021 (defun js2-end-check-try (node)
5022 "If the block has a finally, return consistency is checked in the
5023 finally block. If all code paths in the finally return, then the
5024 returns in the try-catch blocks don't matter. If there is a code path
5025 that does not return or if there is no finally block, the returns
5026 of the try and catch blocks are checked for mismatch.
5027 Returns logical OR of END_* flags."
5028 (let ((finally (js2-try-node-finally-block node))
5029 rv)
5030 ;; check the finally if it exists
5031 (setq rv (if finally
5032 (js2-end-check (js2-finally-node-body finally))
5033 js2-END_DROPS_OFF))
5034 ;; If the finally block always returns, then none of the returns
5035 ;; in the try or catch blocks matter.
5036 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5037 (js2-clear-flag rv js2-END_DROPS_OFF)
5038 ;; examine the try block
5039 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5040 ;; check each catch block
5041 (dolist (cb (js2-try-node-catch-clauses node))
5042 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5043 rv))
5044
5045 (defun js2-end-check-loop (node)
5046 "Return statement in the loop body must be consistent. The default
5047 assumption for any kind of a loop is that it will eventually terminate.
5048 The only exception is a loop with a constant true condition. Code that
5049 follows such a loop is examined only if one can statically determine
5050 that there is a break out of the loop.
5051
5052 for(... ; ... ; ...) {}
5053 for(... in ... ) {}
5054 while(...) { }
5055 do { } while(...)
5056
5057 Returns logical OR of END_* flags."
5058 (let ((rv (js2-end-check (js2-loop-node-body node)))
5059 (condition (cond
5060 ((js2-while-node-p node)
5061 (js2-while-node-condition node))
5062 ((js2-do-node-p node)
5063 (js2-do-node-condition node))
5064 ((js2-for-node-p node)
5065 (js2-for-node-condition node)))))
5066
5067 ;; check to see if the loop condition is always true
5068 (if (and condition
5069 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5070 (js2-clear-flag rv js2-END_DROPS_OFF))
5071
5072 ;; look for effect of breaks
5073 (js2-set-flag rv (js2-node-get-prop node
5074 'CONTROL_BLOCK_PROP
5075 js2-END_UNREACHED))
5076 rv))
5077
5078 (defun js2-end-check-block (node)
5079 "A general block of code is examined statement by statement.
5080 If any statement (even a compound one) returns in all branches, then
5081 subsequent statements are not examined.
5082 Returns logical OR of END_* flags."
5083 (let* ((rv js2-END_DROPS_OFF)
5084 (kids (js2-block-node-kids node))
5085 (n (car kids)))
5086 ;; Check each statment. If the statement can continue onto the next
5087 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5088 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5089 (js2-clear-flag rv js2-END_DROPS_OFF)
5090 (js2-set-flag rv (js2-end-check n))
5091 (setq kids (cdr kids)
5092 n (car kids)))
5093 rv))
5094
5095 (defun js2-end-check-label (node)
5096 "A labeled statement implies that there may be a break to the label.
5097 The function processes the labeled statement and then checks the
5098 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5099 particular label.
5100 Returns logical OR of END_* flags."
5101 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5102 (logior rv (js2-node-get-prop node
5103 'CONTROL_BLOCK_PROP
5104 js2-END_UNREACHED))))
5105
5106 (defun js2-end-check-break (node)
5107 "When a break is encountered annotate the statement being broken
5108 out of by setting its CONTROL_BLOCK_PROP property.
5109 Returns logical OR of END_* flags."
5110 (and (js2-break-node-target node)
5111 (js2-node-set-prop (js2-break-node-target node)
5112 'CONTROL_BLOCK_PROP
5113 js2-END_DROPS_OFF))
5114 js2-END_UNREACHED)
5115
5116 (defun js2-end-check (node)
5117 "Examine the body of a function, doing a basic reachability analysis.
5118 Returns a combination of flags END_* flags that indicate
5119 how the function execution can terminate. These constitute only the
5120 pessimistic set of termination conditions. It is possible that at
5121 runtime certain code paths will never be actually taken. Hence this
5122 analysis will flag errors in cases where there may not be errors.
5123 Returns logical OR of END_* flags"
5124 (let (kid)
5125 (cond
5126 ((js2-break-node-p node)
5127 (js2-end-check-break node))
5128 ((js2-expr-stmt-node-p node)
5129 (if (setq kid (js2-expr-stmt-node-expr node))
5130 (js2-end-check kid)
5131 js2-END_DROPS_OFF))
5132 ((or (js2-continue-node-p node)
5133 (js2-throw-node-p node))
5134 js2-END_UNREACHED)
5135 ((js2-return-node-p node)
5136 (if (setq kid (js2-return-node-retval node))
5137 js2-END_RETURNS_VALUE
5138 js2-END_RETURNS))
5139 ((js2-loop-node-p node)
5140 (js2-end-check-loop node))
5141 ((js2-switch-node-p node)
5142 (js2-end-check-switch node))
5143 ((js2-labeled-stmt-node-p node)
5144 (js2-end-check-label node))
5145 ((js2-if-node-p node)
5146 (js2-end-check-if node))
5147 ((js2-try-node-p node)
5148 (js2-end-check-try node))
5149 ((js2-block-node-p node)
5150 (if (null (js2-block-node-kids node))
5151 js2-END_DROPS_OFF
5152 (js2-end-check-block node)))
5153 ((js2-yield-node-p node)
5154 js2-END_YIELDS)
5155 (t
5156 js2-END_DROPS_OFF))))
5157
5158 (defun js2-always-defined-boolean-p (node)
5159 "Check if NODE always evaluates to true or false in boolean context.
5160 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5161 nor always false."
5162 (let ((tt (js2-node-type node))
5163 num)
5164 (cond
5165 ((or (= tt js2-FALSE) (= tt js2-NULL))
5166 'ALWAYS_FALSE)
5167 ((= tt js2-TRUE)
5168 'ALWAYS_TRUE)
5169 ((= tt js2-NUMBER)
5170 (setq num (js2-number-node-num-value node))
5171 (if (and (not (eq num 0.0e+NaN))
5172 (not (zerop num)))
5173 'ALWAYS_TRUE
5174 'ALWAYS_FALSE))
5175 (t
5176 nil))))
5177
5178 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5179 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5180
5181 (defvar js2-tokens nil
5182 "List of all defined token names.") ; initialized in `js2-token-names'
5183
5184 (defconst js2-token-names
5185 (let* ((names (make-vector js2-num-tokens -1))
5186 (case-fold-search nil) ; only match js2-UPPER_CASE
5187 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5188 (loop for sym in syms
5189 for i from 0
5190 do
5191 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5192 (not (boundp sym)))
5193 (aset names (symbol-value sym) ; code, e.g. 152
5194 (downcase
5195 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5196 (push sym js2-tokens)))
5197 names)
5198 "Vector mapping int values to token string names, sans `js2-' prefix.")
5199
5200 (defun js2-token-name (tok)
5201 "Return a string name for TOK, a token symbol or code.
5202 Signals an error if it's not a recognized token."
5203 (let ((code tok))
5204 (if (symbolp tok)
5205 (setq code (symbol-value tok)))
5206 (if (eq code -1)
5207 "ERROR"
5208 (if (and (numberp code)
5209 (not (minusp code))
5210 (< code js2-num-tokens))
5211 (aref js2-token-names code)
5212 (error "Invalid token: %s" code)))))
5213
5214 (defsubst js2-token-sym (tok)
5215 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5216 (intern (js2-token-name tok)))
5217
5218 (defconst js2-token-codes
5219 (let ((table (make-hash-table :test 'eq :size 256)))
5220 (loop for name across js2-token-names
5221 for sym = (intern (concat "js2-" (upcase name)))
5222 do
5223 (puthash sym (symbol-value sym) table))
5224 ;; clean up a few that are "wrong" in Rhino's token codes
5225 (puthash 'js2-DELETE js2-DELPROP table)
5226 table)
5227 "Hashtable mapping token symbols to their bytecodes.")
5228
5229 (defsubst js2-token-code (sym)
5230 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5231 (or (gethash sym js2-token-codes)
5232 (error "Invalid token symbol: %s " sym))) ; signal code bug
5233
5234 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5235 (setq js2-token-end js2-ts-cursor)
5236 (js2-report-error msg nil
5237 (or beg js2-token-beg)
5238 (or len (- js2-token-end js2-token-beg)))
5239 (unless no-throw
5240 (throw 'return js2-ERROR)))
5241
5242 (defsubst js2-get-string-from-buffer ()
5243 "Reverse the char accumulator and return it as a string."
5244 (setq js2-token-end js2-ts-cursor)
5245 (if js2-ts-string-buffer
5246 (apply #'string (nreverse js2-ts-string-buffer))
5247 ""))
5248
5249 ;; TODO: could potentially avoid a lot of consing by allocating a
5250 ;; char buffer the way Rhino does.
5251 (defsubst js2-add-to-string (c)
5252 (push c js2-ts-string-buffer))
5253
5254 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5255 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5256 ;; any other character: when it's not part of the current token, we
5257 ;; unget it, allowing it to be read again by the following call.
5258 (defsubst js2-unget-char ()
5259 (decf js2-ts-cursor))
5260
5261 ;; Rhino distinguishes \r and \n line endings. We don't need to
5262 ;; because we only scan from Emacs buffers, which always use \n.
5263 (defsubst js2-get-char ()
5264 "Read and return the next character from the input buffer.
5265 Increments `js2-ts-lineno' if the return value is a newline char.
5266 Updates `js2-ts-cursor' to the point after the returned char.
5267 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5268 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5269 (let (c)
5270 ;; check for end of buffer
5271 (if (>= js2-ts-cursor (point-max))
5272 (setq js2-ts-hit-eof t
5273 js2-ts-cursor (1+ js2-ts-cursor)
5274 c js2-EOF_CHAR) ; return value
5275 ;; otherwise read next char
5276 (setq c (char-before (incf js2-ts-cursor)))
5277 ;; if we read a newline, update counters
5278 (if (= c ?\n)
5279 (setq js2-ts-line-start js2-ts-cursor
5280 js2-ts-lineno (1+ js2-ts-lineno)))
5281 ;; TODO: skip over format characters
5282 c)))
5283
5284 (defsubst js2-read-unicode-escape ()
5285 "Read a \\uNNNN sequence from the input.
5286 Assumes the ?\ and ?u have already been read.
5287 Returns the unicode character, or nil if it wasn't a valid character.
5288 Doesn't change the values of any scanner variables."
5289 ;; I really wish I knew a better way to do this, but I can't
5290 ;; find the Emacs function that takes a 16-bit int and converts
5291 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5292 ;; Have to first check that it's 4 hex characters or it may stop
5293 ;; the read early.
5294 (ignore-errors
5295 (let ((s (buffer-substring-no-properties js2-ts-cursor
5296 (+ 4 js2-ts-cursor))))
5297 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5298 (read (concat "?\\u" s))))))
5299
5300 (defsubst js2-match-char (test)
5301 "Consume and return next character if it matches TEST, a character.
5302 Returns nil and consumes nothing if TEST is not the next character."
5303 (let ((c (js2-get-char)))
5304 (if (eq c test)
5305 t
5306 (js2-unget-char)
5307 nil)))
5308
5309 (defsubst js2-peek-char ()
5310 (prog1
5311 (js2-get-char)
5312 (js2-unget-char)))
5313
5314 (defsubst js2-java-identifier-start-p (c)
5315 (or
5316 (memq c '(?$ ?_))
5317 (js2-char-uppercase-p c)
5318 (js2-char-lowercase-p c)))
5319
5320 (defsubst js2-java-identifier-part-p (c)
5321 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5322 ;; TODO: make me Unicode-friendly. See comments above.
5323 (or
5324 (memq c '(?$ ?_))
5325 (js2-char-uppercase-p c)
5326 (js2-char-lowercase-p c)
5327 (and (>= c ?0) (<= c ?9))))
5328
5329 (defsubst js2-alpha-p (c)
5330 (cond ((and (<= ?A c) (<= c ?Z)) t)
5331 ((and (<= ?a c) (<= c ?z)) t)
5332 (t nil)))
5333
5334 (defsubst js2-digit-p (c)
5335 (and (<= ?0 c) (<= c ?9)))
5336
5337 (defsubst js2-js-space-p (c)
5338 (if (<= c 127)
5339 (memq c '(#x20 #x9 #xB #xC #xD))
5340 (or
5341 (eq c #xA0)
5342 ;; TODO: change this nil to check for Unicode space character
5343 nil)))
5344
5345 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5346
5347 (defsubst js2-skip-line ()
5348 "Skip to end of line"
5349 (let (c)
5350 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5351 (js2-unget-char)
5352 (setq js2-token-end js2-ts-cursor)))
5353
5354 (defun js2-init-scanner (&optional buf line)
5355 "Create token stream for BUF starting on LINE.
5356 BUF defaults to current-buffer and line defaults to 1.
5357
5358 A buffer can only have one scanner active at a time, which yields
5359 dramatically simpler code than using a defstruct. If you need to
5360 have simultaneous scanners in a buffer, copy the regions to scan
5361 into temp buffers."
5362 (save-excursion
5363 (when buf
5364 (set-buffer buf))
5365 (setq js2-ts-dirty-line nil
5366 js2-ts-regexp-flags nil
5367 js2-ts-string ""
5368 js2-ts-number nil
5369 js2-ts-hit-eof nil
5370 js2-ts-line-start 0
5371 js2-ts-lineno (or line 1)
5372 js2-ts-line-end-char -1
5373 js2-ts-cursor (point-min)
5374 js2-ts-is-xml-attribute nil
5375 js2-ts-xml-is-tag-content nil
5376 js2-ts-xml-open-tags-count 0
5377 js2-ts-string-buffer nil)))
5378
5379 ;; This function uses the cached op, string and number fields in
5380 ;; TokenStream; if getToken has been called since the passed token
5381 ;; was scanned, the op or string printed may be incorrect.
5382 (defun js2-token-to-string (token)
5383 ;; Not sure where this function is used in Rhino. Not tested.
5384 (if (not js2-debug-print-trees)
5385 ""
5386 (let ((name (js2-token-name token)))
5387 (cond
5388 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5389 (concat name " `" js2-ts-string "'"))
5390 ((eq token js2-NUMBER)
5391 (format "NUMBER %g" js2-ts-number))
5392 (t
5393 name)))))
5394
5395 (defconst js2-keywords
5396 '(break
5397 case catch const continue
5398 debugger default delete do
5399 else enum
5400 false finally for function
5401 if in instanceof import
5402 let
5403 new null
5404 return
5405 switch
5406 this throw true try typeof
5407 var void
5408 while with
5409 yield))
5410
5411 ;; Token names aren't exactly the same as the keywords, unfortunately.
5412 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5413 (defconst js2-kwd-tokens
5414 (let ((table (make-vector js2-num-tokens nil))
5415 (tokens
5416 (list js2-BREAK
5417 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5418 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5419 js2-ELSE
5420 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5421 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5422 js2-LET
5423 js2-NEW js2-NULL
5424 js2-RETURN
5425 js2-SWITCH
5426 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5427 js2-VAR
5428 js2-WHILE js2-WITH
5429 js2-YIELD)))
5430 (dolist (i tokens)
5431 (aset table i 'font-lock-keyword-face))
5432 (aset table js2-STRING 'font-lock-string-face)
5433 (aset table js2-REGEXP 'font-lock-string-face)
5434 (aset table js2-COMMENT 'font-lock-comment-face)
5435 (aset table js2-THIS 'font-lock-builtin-face)
5436 (aset table js2-VOID 'font-lock-constant-face)
5437 (aset table js2-NULL 'font-lock-constant-face)
5438 (aset table js2-TRUE 'font-lock-constant-face)
5439 (aset table js2-FALSE 'font-lock-constant-face)
5440 table)
5441 "Vector whose values are non-nil for tokens that are keywords.
5442 The values are default faces to use for highlighting the keywords.")
5443
5444 (defconst js2-reserved-words
5445 '(abstract
5446 boolean byte
5447 char class
5448 double
5449 enum export extends
5450 final float
5451 goto
5452 implements import int interface
5453 long
5454 native
5455 package private protected public
5456 short static super synchronized
5457 throws transient
5458 volatile))
5459
5460 (defconst js2-keyword-names
5461 (let ((table (make-hash-table :test 'equal)))
5462 (loop for k in js2-keywords
5463 do (puthash
5464 (symbol-name k) ; instanceof
5465 (intern (concat "js2-"
5466 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5467 table))
5468 table)
5469 "JavaScript keywords by name, mapped to their symbols.")
5470
5471 (defconst js2-reserved-word-names
5472 (let ((table (make-hash-table :test 'equal)))
5473 (loop for k in js2-reserved-words
5474 do
5475 (puthash (symbol-name k) 'js2-RESERVED table))
5476 table)
5477 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5478
5479 (defsubst js2-collect-string (buf)
5480 "Convert BUF, a list of chars, to a string.
5481 Reverses BUF before converting."
5482 (cond
5483 ((stringp buf)
5484 buf)
5485 ((null buf) ; for emacs21 compat
5486 "")
5487 (t
5488 (if buf
5489 (apply #'string (nreverse buf))
5490 ""))))
5491
5492 (defun js2-string-to-keyword (s)
5493 "Return token for S, a string, if S is a keyword or reserved word.
5494 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5495 (or (gethash s js2-keyword-names)
5496 (gethash s js2-reserved-word-names)))
5497
5498 (defsubst js2-ts-set-char-token-bounds ()
5499 "Used when next token is one character."
5500 (setq js2-token-beg (1- js2-ts-cursor)
5501 js2-token-end js2-ts-cursor))
5502
5503 (defsubst js2-ts-return (token)
5504 "Return an N-character TOKEN from `js2-get-token'.
5505 Updates `js2-token-end' accordingly."
5506 (setq js2-token-end js2-ts-cursor)
5507 (throw 'return token))
5508
5509 (defsubst js2-x-digit-to-int (c accumulator)
5510 "Build up a hex number.
5511 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5512 corresponding number. Otherwise return -1."
5513 (catch 'return
5514 (catch 'check
5515 ;; Use 0..9 < A..Z < a..z
5516 (cond
5517 ((<= c ?9)
5518 (decf c ?0)
5519 (if (<= 0 c)
5520 (throw 'check nil)))
5521 ((<= c ?F)
5522 (when (<= ?A c)
5523 (decf c (- ?A 10))
5524 (throw 'check nil)))
5525 ((<= c ?f)
5526 (when (<= ?a c)
5527 (decf c (- ?a 10))
5528 (throw 'check nil))))
5529 (throw 'return -1))
5530 (logior c (lsh accumulator 4))))
5531
5532 (defun js2-get-token ()
5533 "Return next JavaScript token, an int such as js2-RETURN."
5534 (let (c
5535 c1
5536 identifier-start
5537 is-unicode-escape-start
5538 contains-escape
5539 escape-val
5540 escape-start
5541 str
5542 result
5543 base
5544 is-integer
5545 quote-char
5546 val
5547 look-for-slash
5548 continue)
5549 (catch 'return
5550 (while t
5551 ;; Eat whitespace, possibly sensitive to newlines.
5552 (setq continue t)
5553 (while continue
5554 (setq c (js2-get-char))
5555 (cond
5556 ((eq c js2-EOF_CHAR)
5557 (js2-ts-set-char-token-bounds)
5558 (throw 'return js2-EOF))
5559 ((eq c ?\n)
5560 (js2-ts-set-char-token-bounds)
5561 (setq js2-ts-dirty-line nil)
5562 (throw 'return js2-EOL))
5563 ((not (js2-js-space-p c))
5564 (if (/= c ?-) ; in case end of HTML comment
5565 (setq js2-ts-dirty-line t))
5566 (setq continue nil))))
5567 ;; Assume the token will be 1 char - fixed up below.
5568 (js2-ts-set-char-token-bounds)
5569 (when (eq c ?@)
5570 (throw 'return js2-XMLATTR))
5571 ;; identifier/keyword/instanceof?
5572 ;; watch out for starting with a <backslash>
5573 (cond
5574 ((eq c ?\\)
5575 (setq c (js2-get-char))
5576 (if (eq c ?u)
5577 (setq identifier-start t
5578 is-unicode-escape-start t
5579 js2-ts-string-buffer nil)
5580 (setq identifier-start nil)
5581 (js2-unget-char)
5582 (setq c ?\\)))
5583 (t
5584 (when (setq identifier-start (js2-java-identifier-start-p c))
5585 (setq js2-ts-string-buffer nil)
5586 (js2-add-to-string c))))
5587 (when identifier-start
5588 (setq contains-escape is-unicode-escape-start)
5589 (catch 'break
5590 (while t
5591 (if is-unicode-escape-start
5592 ;; strictly speaking we should probably push-back
5593 ;; all the bad characters if the <backslash>uXXXX
5594 ;; sequence is malformed. But since there isn't a
5595 ;; correct context(is there?) for a bad Unicode
5596 ;; escape sequence in an identifier, we can report
5597 ;; an error here.
5598 (progn
5599 (setq escape-val 0)
5600 (dotimes (i 4)
5601 (setq c (js2-get-char)
5602 escape-val (js2-x-digit-to-int c escape-val))
5603 ;; Next check takes care of c < 0 and bad escape
5604 (if (minusp escape-val)
5605 (throw 'break nil)))
5606 (if (minusp escape-val)
5607 (js2-report-scan-error "msg.invalid.escape" t))
5608 (js2-add-to-string escape-val)
5609 (setq is-unicode-escape-start nil))
5610 (setq c (js2-get-char))
5611 (cond
5612 ((eq c ?\\)
5613 (setq c (js2-get-char))
5614 (if (eq c ?u)
5615 (setq is-unicode-escape-start t
5616 contains-escape t)
5617 (js2-report-scan-error "msg.illegal.character" t)))
5618 (t
5619 (if (or (eq c js2-EOF_CHAR)
5620 (not (js2-java-identifier-part-p c)))
5621 (throw 'break nil))
5622 (js2-add-to-string c))))))
5623 (js2-unget-char)
5624 (setq str (js2-get-string-from-buffer))
5625 (unless contains-escape
5626 ;; OPT we shouldn't have to make a string (object!) to
5627 ;; check if it's a keyword.
5628 ;; Return the corresponding token if it's a keyword
5629 (when (setq result (js2-string-to-keyword str))
5630 (if (and (< js2-language-version 170)
5631 (memq result '(js2-LET js2-YIELD)))
5632 ;; LET and YIELD are tokens only in 1.7 and later
5633 (setq result 'js2-NAME))
5634 (if (not (eq result 'js2-RESERVED))
5635 (throw 'return (js2-token-code result)))
5636 (js2-report-warning "msg.reserved.keyword" str)))
5637 ;; If we want to intern these as Rhino does, just use (intern str)
5638 (setq js2-ts-string str)
5639 (throw 'return js2-NAME)) ; end identifier/kwd check
5640 ;; is it a number?
5641 (when (or (js2-digit-p c)
5642 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5643 (setq js2-ts-string-buffer nil
5644 base 10)
5645 (when (eq c ?0)
5646 (setq c (js2-get-char))
5647 (cond
5648 ((or (eq c ?x) (eq c ?X))
5649 (setq base 16)
5650 (setq c (js2-get-char)))
5651 ((js2-digit-p c)
5652 (setq base 8))
5653 (t
5654 (js2-add-to-string ?0))))
5655 (if (eq base 16)
5656 (while (<= 0 (js2-x-digit-to-int c 0))
5657 (js2-add-to-string c)
5658 (setq c (js2-get-char)))
5659 (while (and (<= ?0 c) (<= c ?9))
5660 ;; We permit 08 and 09 as decimal numbers, which
5661 ;; makes our behavior a superset of the ECMA
5662 ;; numeric grammar. We might not always be so
5663 ;; permissive, so we warn about it.
5664 (when (and (eq base 8) (>= c ?8))
5665 (js2-report-warning "msg.bad.octal.literal"
5666 (if (eq c ?8) "8" "9"))
5667 (setq base 10))
5668 (js2-add-to-string c)
5669 (setq c (js2-get-char))))
5670 (setq is-integer t)
5671 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5672 (setq is-integer nil)
5673 (when (eq c ?.)
5674 (loop do
5675 (js2-add-to-string c)
5676 (setq c (js2-get-char))
5677 while (js2-digit-p c)))
5678 (when (memq c '(?e ?E))
5679 (js2-add-to-string c)
5680 (setq c (js2-get-char))
5681 (when (memq c '(?+ ?-))
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char)))
5684 (unless (js2-digit-p c)
5685 (js2-report-scan-error "msg.missing.exponent" t))
5686 (loop do
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 while (js2-digit-p c))))
5690 (js2-unget-char)
5691 (setq js2-ts-string (js2-get-string-from-buffer)
5692 js2-ts-number
5693 (if (and (eq base 10) (not is-integer))
5694 (string-to-number js2-ts-string)
5695 ;; TODO: call runtime number-parser. Some of it is in
5696 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5697 (string-to-number js2-ts-string)))
5698 (throw 'return js2-NUMBER))
5699 ;; is it a string?
5700 (when (memq c '(?\" ?\'))
5701 ;; We attempt to accumulate a string the fast way, by
5702 ;; building it directly out of the reader. But if there
5703 ;; are any escaped characters in the string, we revert to
5704 ;; building it out of a string buffer.
5705 (setq quote-char c
5706 js2-ts-string-buffer nil
5707 c (js2-get-char))
5708 (catch 'break
5709 (while (/= c quote-char)
5710 (catch 'continue
5711 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5712 (js2-unget-char)
5713 (setq js2-token-end js2-ts-cursor)
5714 (js2-report-error "msg.unterminated.string.lit")
5715 (throw 'return js2-STRING))
5716 (when (eq c ?\\)
5717 ;; We've hit an escaped character
5718 (setq c (js2-get-char))
5719 (case c
5720 (?b (setq c ?\b))
5721 (?f (setq c ?\f))
5722 (?n (setq c ?\n))
5723 (?r (setq c ?\r))
5724 (?t (setq c ?\t))
5725 (?v (setq c ?\v))
5726 (?u
5727 (setq c1 (js2-read-unicode-escape))
5728 (if js2-parse-ide-mode
5729 (if c1
5730 (progn
5731 ;; just copy the string in IDE-mode
5732 (js2-add-to-string ?\\)
5733 (js2-add-to-string ?u)
5734 (dotimes (i 3)
5735 (js2-add-to-string (js2-get-char)))
5736 (setq c (js2-get-char))) ; added at end of loop
5737 ;; flag it as an invalid escape
5738 (js2-report-warning "msg.invalid.escape"
5739 nil (- js2-ts-cursor 2) 6))
5740 ;; Get 4 hex digits; if the u escape is not
5741 ;; followed by 4 hex digits, use 'u' + the
5742 ;; literal character sequence that follows.
5743 (js2-add-to-string ?u)
5744 (setq escape-val 0)
5745 (dotimes (i 4)
5746 (setq c (js2-get-char)
5747 escape-val (js2-x-digit-to-int c escape-val))
5748 (if (minusp escape-val)
5749 (throw 'continue nil))
5750 (js2-add-to-string c))
5751 ;; prepare for replace of stored 'u' sequence by escape value
5752 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5753 c escape-val)))
5754 (?x
5755 ;; Get 2 hex digits, defaulting to 'x'+literal
5756 ;; sequence, as above.
5757 (setq c (js2-get-char)
5758 escape-val (js2-x-digit-to-int c 0))
5759 (if (minusp escape-val)
5760 (progn
5761 (js2-add-to-string ?x)
5762 (throw 'continue nil))
5763 (setq c1 c
5764 c (js2-get-char)
5765 escape-val (js2-x-digit-to-int c escape-val))
5766 (if (minusp escape-val)
5767 (progn
5768 (js2-add-to-string ?x)
5769 (js2-add-to-string c1)
5770 (throw 'continue nil))
5771 ;; got 2 hex digits
5772 (setq c escape-val))))
5773 (?\n
5774 ;; Remove line terminator after escape to follow
5775 ;; SpiderMonkey and C/C++
5776 (setq c (js2-get-char))
5777 (throw 'continue nil))
5778 (t
5779 (when (and (<= ?0 c) (< c ?8))
5780 (setq val (- c ?0)
5781 c (js2-get-char))
5782 (when (and (<= ?0 c) (< c ?8))
5783 (setq val (- (+ (* 8 val) c) ?0)
5784 c (js2-get-char))
5785 (when (and (<= ?0 c)
5786 (< c ?8)
5787 (< val #o37))
5788 ;; c is 3rd char of octal sequence only
5789 ;; if the resulting val <= 0377
5790 (setq val (- (+ (* 8 val) c) ?0)
5791 c (js2-get-char))))
5792 (js2-unget-char)
5793 (setq c val)))))
5794 (js2-add-to-string c)
5795 (setq c (js2-get-char)))))
5796 (setq js2-ts-string (js2-get-string-from-buffer))
5797 (throw 'return js2-STRING))
5798 (case c
5799 (?\;
5800 (throw 'return js2-SEMI))
5801 (?\[
5802 (throw 'return js2-LB))
5803 (?\]
5804 (throw 'return js2-RB))
5805 (?{
5806 (throw 'return js2-LC))
5807 (?}
5808 (throw 'return js2-RC))
5809 (?\(
5810 (throw 'return js2-LP))
5811 (?\)
5812 (throw 'return js2-RP))
5813 (?,
5814 (throw 'return js2-COMMA))
5815 (??
5816 (throw 'return js2-HOOK))
5817 (?:
5818 (if (js2-match-char ?:)
5819 (js2-ts-return js2-COLONCOLON)
5820 (throw 'return js2-COLON)))
5821 (?.
5822 (if (js2-match-char ?.)
5823 (if (js2-match-char ?.)
5824 (js2-ts-return js2-TRIPLEDOT)
5825 (js2-ts-return js2-DOTDOT))
5826 (if (js2-match-char ?\()
5827 (js2-ts-return js2-DOTQUERY)
5828 (throw 'return js2-DOT))))
5829 (?|
5830 (if (js2-match-char ?|)
5831 (throw 'return js2-OR)
5832 (if (js2-match-char ?=)
5833 (js2-ts-return js2-ASSIGN_BITOR)
5834 (throw 'return js2-BITOR))))
5835 (?^
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-ASSIGN_BITOR)
5838 (throw 'return js2-BITXOR)))
5839 (?&
5840 (if (js2-match-char ?&)
5841 (throw 'return js2-AND)
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_BITAND)
5844 (throw 'return js2-BITAND))))
5845 (?=
5846 (if (js2-match-char ?=)
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-SHEQ)
5849 (throw 'return js2-EQ))
5850 (throw 'return js2-ASSIGN)))
5851 (?!
5852 (if (js2-match-char ?=)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-SHNE)
5855 (js2-ts-return js2-NE))
5856 (throw 'return js2-NOT)))
5857 (?<
5858 ;; NB:treat HTML begin-comment as comment-till-eol
5859 (when (js2-match-char ?!)
5860 (when (js2-match-char ?-)
5861 (when (js2-match-char ?-)
5862 (js2-skip-line)
5863 (setq js2-ts-comment-type 'html)
5864 (throw 'return js2-COMMENT)))
5865 (js2-unget-char))
5866 (if (js2-match-char ?<)
5867 (if (js2-match-char ?=)
5868 (js2-ts-return js2-ASSIGN_LSH)
5869 (js2-ts-return js2-LSH))
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-LE)
5872 (throw 'return js2-LT))))
5873 (?>
5874 (if (js2-match-char ?>)
5875 (if (js2-match-char ?>)
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-ASSIGN_URSH)
5878 (js2-ts-return js2-URSH))
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_RSH)
5881 (js2-ts-return js2-RSH)))
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-GE)
5884 (throw 'return js2-GT))))
5885 (?*
5886 (if (js2-match-char ?=)
5887 (js2-ts-return js2-ASSIGN_MUL)
5888 (throw 'return js2-MUL)))
5889 (?/
5890 ;; is it a // comment?
5891 (when (js2-match-char ?/)
5892 (setq js2-token-beg (- js2-ts-cursor 2))
5893 (js2-skip-line)
5894 (setq js2-ts-comment-type 'line)
5895 ;; include newline so highlighting goes to end of window
5896 (incf js2-token-end)
5897 (throw 'return js2-COMMENT))
5898 ;; is it a /* comment?
5899 (when (js2-match-char ?*)
5900 (setq look-for-slash nil
5901 js2-token-beg (- js2-ts-cursor 2)
5902 js2-ts-comment-type
5903 (if (js2-match-char ?*)
5904 (progn
5905 (setq look-for-slash t)
5906 'jsdoc)
5907 'block))
5908 (while t
5909 (setq c (js2-get-char))
5910 (cond
5911 ((eq c js2-EOF_CHAR)
5912 (setq js2-token-end (1- js2-ts-cursor))
5913 (js2-report-error "msg.unterminated.comment")
5914 (throw 'return js2-COMMENT))
5915 ((eq c ?*)
5916 (setq look-for-slash t))
5917 ((eq c ?/)
5918 (if look-for-slash
5919 (js2-ts-return js2-COMMENT)))
5920 (t
5921 (setq look-for-slash nil
5922 js2-token-end js2-ts-cursor)))))
5923 (if (js2-match-char ?=)
5924 (js2-ts-return js2-ASSIGN_DIV)
5925 (throw 'return js2-DIV)))
5926 (?#
5927 (when js2-skip-preprocessor-directives
5928 (js2-skip-line)
5929 (setq js2-ts-comment-type 'preprocessor
5930 js2-token-end js2-ts-cursor)
5931 (throw 'return js2-COMMENT))
5932 (throw 'return js2-ERROR))
5933 (?%
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_MOD)
5936 (throw 'return js2-MOD)))
5937 (?~
5938 (throw 'return js2-BITNOT))
5939 (?+
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_ADD)
5942 (if (js2-match-char ?+)
5943 (js2-ts-return js2-INC)
5944 (throw 'return js2-ADD))))
5945 (?-
5946 (cond
5947 ((js2-match-char ?=)
5948 (setq c js2-ASSIGN_SUB))
5949 ((js2-match-char ?-)
5950 (unless js2-ts-dirty-line
5951 ;; treat HTML end-comment after possible whitespace
5952 ;; after line start as comment-until-eol
5953 (when (js2-match-char ?>)
5954 (js2-skip-line)
5955 (setq js2-ts-comment-type 'html)
5956 (throw 'return js2-COMMENT)))
5957 (setq c js2-DEC))
5958 (t
5959 (setq c js2-SUB)))
5960 (setq js2-ts-dirty-line t)
5961 (js2-ts-return c))
5962 (otherwise
5963 (js2-report-scan-error "msg.illegal.character")))))))
5964
5965 (defun js2-read-regexp (start-token)
5966 "Called by parser when it gets / or /= in literal context."
5967 (let (c
5968 err
5969 in-class ; inside a '[' .. ']' character-class
5970 flags
5971 (continue t))
5972 (setq js2-token-beg js2-ts-cursor
5973 js2-ts-string-buffer nil
5974 js2-ts-regexp-flags nil)
5975 (if (eq start-token js2-ASSIGN_DIV)
5976 ;; mis-scanned /=
5977 (js2-add-to-string ?=)
5978 (if (not (eq start-token js2-DIV))
5979 (error "failed assertion")))
5980 (while (and (not err)
5981 (or (/= (setq c (js2-get-char)) ?/)
5982 in-class))
5983 (cond
5984 ((or (= c ?\n)
5985 (= c js2-EOF_CHAR))
5986 (setq js2-token-end (1- js2-ts-cursor)
5987 err t
5988 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5989 (js2-report-error "msg.unterminated.re.lit"))
5990 (t (cond
5991 ((= c ?\\)
5992 (js2-add-to-string c)
5993 (setq c (js2-get-char)))
5994 ((= c ?\[)
5995 (setq in-class t))
5996 ((= c ?\])
5997 (setq in-class nil)))
5998 (js2-add-to-string c))))
5999 (unless err
6000 (while continue
6001 (cond
6002 ((js2-match-char ?g)
6003 (push ?g flags))
6004 ((js2-match-char ?i)
6005 (push ?i flags))
6006 ((js2-match-char ?m)
6007 (push ?m flags))
6008 (t
6009 (setq continue nil))))
6010 (if (js2-alpha-p (js2-peek-char))
6011 (js2-report-scan-error "msg.invalid.re.flag" t
6012 js2-ts-cursor 1))
6013 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6014 js2-ts-regexp-flags (js2-collect-string flags)
6015 js2-token-end js2-ts-cursor)
6016 ;; tell `parse-partial-sexp' to ignore this range of chars
6017 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6018
6019 (defun js2-get-first-xml-token ()
6020 (setq js2-ts-xml-open-tags-count 0
6021 js2-ts-is-xml-attribute nil
6022 js2-ts-xml-is-tag-content nil)
6023 (js2-unget-char)
6024 (js2-get-next-xml-token))
6025
6026 (defsubst js2-xml-discard-string ()
6027 "Throw away the string in progress and flag an XML parse error."
6028 (setq js2-ts-string-buffer nil
6029 js2-ts-string nil)
6030 (js2-report-scan-error "msg.XML.bad.form" t))
6031
6032 (defun js2-get-next-xml-token ()
6033 (setq js2-ts-string-buffer nil ; for recording the XML
6034 js2-token-beg js2-ts-cursor)
6035 (let (c result)
6036 (setq result
6037 (catch 'return
6038 (while t
6039 (setq c (js2-get-char))
6040 (cond
6041 ((= c js2-EOF_CHAR)
6042 (throw 'return js2-ERROR))
6043 (js2-ts-xml-is-tag-content
6044 (case c
6045 (?>
6046 (js2-add-to-string c)
6047 (setq js2-ts-xml-is-tag-content nil
6048 js2-ts-is-xml-attribute nil))
6049 (?/
6050 (js2-add-to-string c)
6051 (when (eq ?> (js2-peek-char))
6052 (setq c (js2-get-char))
6053 (js2-add-to-string c)
6054 (setq js2-ts-xml-is-tag-content nil)
6055 (decf js2-ts-xml-open-tags-count)))
6056 (?{
6057 (js2-unget-char)
6058 (setq js2-ts-string (js2-get-string-from-buffer))
6059 (throw 'return js2-XML))
6060 ((?\' ?\")
6061 (js2-add-to-string c)
6062 (unless (js2-read-quoted-string c)
6063 (throw 'return js2-ERROR)))
6064 (?=
6065 (js2-add-to-string c)
6066 (setq js2-ts-is-xml-attribute t))
6067 ((? ?\t ?\r ?\n)
6068 (js2-add-to-string c))
6069 (t
6070 (js2-add-to-string c)
6071 (setq js2-ts-is-xml-attribute nil)))
6072 (when (and (not js2-ts-xml-is-tag-content)
6073 (zerop js2-ts-xml-open-tags-count))
6074 (setq js2-ts-string (js2-get-string-from-buffer))
6075 (throw 'return js2-XMLEND)))
6076 (t
6077 ;; else not tag content
6078 (case c
6079 (?<
6080 (js2-add-to-string c)
6081 (setq c (js2-peek-char))
6082 (case c
6083 (?!
6084 (setq c (js2-get-char)) ;; skip !
6085 (js2-add-to-string c)
6086 (setq c (js2-peek-char))
6087 (case c
6088 (?-
6089 (setq c (js2-get-char)) ;; skip -
6090 (js2-add-to-string c)
6091 (if (eq c ?-)
6092 (progn
6093 (js2-add-to-string c)
6094 (unless (js2-read-xml-comment)
6095 (throw 'return js2-ERROR)))
6096 (js2-xml-discard-string)
6097 (throw 'return js2-ERROR)))
6098 (?\[
6099 (setq c (js2-get-char)) ;; skip [
6100 (js2-add-to-string c)
6101 (if (and (= (js2-get-char) ?C)
6102 (= (js2-get-char) ?D)
6103 (= (js2-get-char) ?A)
6104 (= (js2-get-char) ?T)
6105 (= (js2-get-char) ?A)
6106 (= (js2-get-char) ?\[))
6107 (progn
6108 (js2-add-to-string ?C)
6109 (js2-add-to-string ?D)
6110 (js2-add-to-string ?A)
6111 (js2-add-to-string ?T)
6112 (js2-add-to-string ?A)
6113 (js2-add-to-string ?\[)
6114 (unless (js2-read-cdata)
6115 (throw 'return js2-ERROR)))
6116 (js2-xml-discard-string)
6117 (throw 'return js2-ERROR)))
6118 (t
6119 (unless (js2-read-entity)
6120 (throw 'return js2-ERROR))))
6121 ;; allow bare CDATA section
6122 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6123 (when (zerop js2-ts-xml-open-tags-count)
6124 (throw 'return js2-XMLEND)))
6125 (??
6126 (setq c (js2-get-char)) ;; skip ?
6127 (js2-add-to-string c)
6128 (unless (js2-read-PI)
6129 (throw 'return js2-ERROR)))
6130 (?/
6131 ;; end tag
6132 (setq c (js2-get-char)) ;; skip /
6133 (js2-add-to-string c)
6134 (when (zerop js2-ts-xml-open-tags-count)
6135 (js2-xml-discard-string)
6136 (throw 'return js2-ERROR))
6137 (setq js2-ts-xml-is-tag-content t)
6138 (decf js2-ts-xml-open-tags-count))
6139 (t
6140 ;; start tag
6141 (setq js2-ts-xml-is-tag-content t)
6142 (incf js2-ts-xml-open-tags-count))))
6143 (?{
6144 (js2-unget-char)
6145 (setq js2-ts-string (js2-get-string-from-buffer))
6146 (throw 'return js2-XML))
6147 (t
6148 (js2-add-to-string c))))))))
6149 (setq js2-token-end js2-ts-cursor)
6150 result))
6151
6152 (defun js2-read-quoted-string (quote)
6153 (let (c)
6154 (catch 'return
6155 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6156 (js2-add-to-string c)
6157 (if (eq c quote)
6158 (throw 'return t)))
6159 (js2-xml-discard-string) ;; throw away string in progress
6160 nil)))
6161
6162 (defun js2-read-xml-comment ()
6163 (let ((c (js2-get-char)))
6164 (catch 'return
6165 (while (/= c js2-EOF_CHAR)
6166 (catch 'continue
6167 (js2-add-to-string c)
6168 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6169 (setq c (js2-get-char))
6170 (js2-add-to-string c)
6171 (if (eq (js2-peek-char) ?>)
6172 (progn
6173 (setq c (js2-get-char)) ;; skip >
6174 (js2-add-to-string c)
6175 (throw 'return t))
6176 (throw 'continue nil)))
6177 (setq c (js2-get-char))))
6178 (js2-xml-discard-string)
6179 nil)))
6180
6181 (defun js2-read-cdata ()
6182 (let ((c (js2-get-char)))
6183 (catch 'return
6184 (while (/= c js2-EOF_CHAR)
6185 (catch 'continue
6186 (js2-add-to-string c)
6187 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6188 (setq c (js2-get-char))
6189 (js2-add-to-string c)
6190 (if (eq (js2-peek-char) ?>)
6191 (progn
6192 (setq c (js2-get-char)) ;; Skip >
6193 (js2-add-to-string c)
6194 (throw 'return t))
6195 (throw 'continue nil)))
6196 (setq c (js2-get-char))))
6197 (js2-xml-discard-string)
6198 nil)))
6199
6200 (defun js2-read-entity ()
6201 (let ((decl-tags 1)
6202 c)
6203 (catch 'return
6204 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6205 (js2-add-to-string c)
6206 (case c
6207 (?<
6208 (incf decl-tags))
6209 (?>
6210 (decf decl-tags)
6211 (if (zerop decl-tags)
6212 (throw 'return t)))))
6213 (js2-xml-discard-string)
6214 nil)))
6215
6216 (defun js2-read-PI ()
6217 "Scan an XML processing instruction."
6218 (let (c)
6219 (catch 'return
6220 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6221 (js2-add-to-string c)
6222 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6223 (setq c (js2-get-char)) ;; Skip >
6224 (js2-add-to-string c)
6225 (throw 'return t)))
6226 (js2-xml-discard-string)
6227 nil)))
6228
6229 (defun js2-scanner-get-line ()
6230 "Return the text of the current scan line."
6231 (buffer-substring (point-at-bol) (point-at-eol)))
6232
6233 ;;; Highlighting
6234
6235 (defsubst js2-set-face (beg end face &optional record)
6236 "Fontify a region. If RECORD is non-nil, record for later."
6237 (when (plusp js2-highlight-level)
6238 (setq beg (min (point-max) beg)
6239 beg (max (point-min) beg)
6240 end (min (point-max) end)
6241 end (max (point-min) end))
6242 (if record
6243 (push (list beg end face) js2-mode-fontifications)
6244 (put-text-property beg end 'font-lock-face face))))
6245
6246 (defsubst js2-set-kid-face (pos kid len face)
6247 "Set-face on a child node.
6248 POS is absolute buffer position of parent.
6249 KID is the child node.
6250 LEN is the length to fontify.
6251 FACE is the face to fontify with."
6252 (js2-set-face (+ pos (js2-node-pos kid))
6253 (+ pos (js2-node-pos kid) (js2-node-len kid))
6254 face))
6255
6256 (defsubst js2-fontify-kwd (start length)
6257 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6258
6259 (defsubst js2-clear-face (beg end)
6260 (remove-text-properties beg end '(font-lock-face nil
6261 help-echo nil
6262 point-entered nil
6263 c-in-sws nil)))
6264
6265 (defconst js2-ecma-global-props
6266 (concat "^"
6267 (regexp-opt
6268 '("Infinity" "NaN" "undefined" "arguments") t)
6269 "$")
6270 "Value properties of the Ecma-262 Global Object.
6271 Shown at or above `js2-highlight-level' 2.")
6272
6273 ;; might want to add the name "arguments" to this list?
6274 (defconst js2-ecma-object-props
6275 (concat "^"
6276 (regexp-opt
6277 '("prototype" "__proto__" "__parent__") t)
6278 "$")
6279 "Value properties of the Ecma-262 Object constructor.
6280 Shown at or above `js2-highlight-level' 2.")
6281
6282 (defconst js2-ecma-global-funcs
6283 (concat
6284 "^"
6285 (regexp-opt
6286 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6287 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6288 "$")
6289 "Function properties of the Ecma-262 Global object.
6290 Shown at or above `js2-highlight-level' 2.")
6291
6292 (defconst js2-ecma-number-props
6293 (concat "^"
6294 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6295 "NEGATIVE_INFINITY"
6296 "POSITIVE_INFINITY") t)
6297 "$")
6298 "Properties of the Ecma-262 Number constructor.
6299 Shown at or above `js2-highlight-level' 2.")
6300
6301 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6302 "Properties of the Ecma-262 Date constructor.
6303 Shown at or above `js2-highlight-level' 2.")
6304
6305 (defconst js2-ecma-math-props
6306 (concat "^"
6307 (regexp-opt
6308 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6309 t)
6310 "$")
6311 "Properties of the Ecma-262 Math object.
6312 Shown at or above `js2-highlight-level' 2.")
6313
6314 (defconst js2-ecma-math-funcs
6315 (concat "^"
6316 (regexp-opt
6317 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6318 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6319 "$")
6320 "Function properties of the Ecma-262 Math object.
6321 Shown at or above `js2-highlight-level' 2.")
6322
6323 (defconst js2-ecma-function-props
6324 (concat
6325 "^"
6326 (regexp-opt
6327 '(;; properties of the Object prototype object
6328 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6329 "toLocaleString" "toString" "valueOf"
6330 ;; properties of the Function prototype object
6331 "apply" "call"
6332 ;; properties of the Array prototype object
6333 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6334 "splice" "unshift"
6335 ;; properties of the String prototype object
6336 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6337 "localeCompare" "match" "replace" "search" "split" "substring"
6338 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6339 "toUpperCase"
6340 ;; properties of the Number prototype object
6341 "toExponential" "toFixed" "toPrecision"
6342 ;; properties of the Date prototype object
6343 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6344 "getMinutes" "getMonth" "getSeconds" "getTime"
6345 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6346 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6347 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6348 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6349 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6350 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6351 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6352 "toTimeString" "toUTCString"
6353 ;; properties of the RegExp prototype object
6354 "exec" "test"
6355 ;; properties of the JSON prototype object
6356 "parse" "stringify"
6357 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6358 "toSource" "__defineGetter__" "__defineSetter__"
6359 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6360 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6361 t)
6362 "$")
6363 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6364 Shown at or above `js2-highlight-level' 3.")
6365
6366 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6367 (let ((target-name (and target
6368 (js2-name-node-p target)
6369 (js2-name-node-name target)))
6370 (prop-name (if prop (js2-name-node-name prop)))
6371 (level1 (>= js2-highlight-level 1))
6372 (level2 (>= js2-highlight-level 2))
6373 (level3 (>= js2-highlight-level 3))
6374 pos
6375 face)
6376 (when level2
6377 (if call-p
6378 (cond
6379 ((and target prop)
6380 (cond
6381 ((and level3 (string-match js2-ecma-function-props prop-name))
6382 (setq face 'font-lock-builtin-face))
6383 ((and target-name prop)
6384 (cond
6385 ((string= target-name "Date")
6386 (if (string-match js2-ecma-date-props prop-name)
6387 (setq face 'font-lock-builtin-face)))
6388 ((string= target-name "Math")
6389 (if (string-match js2-ecma-math-funcs prop-name)
6390 (setq face 'font-lock-builtin-face)))))))
6391 (prop
6392 (if (string-match js2-ecma-global-funcs prop-name)
6393 (setq face 'font-lock-builtin-face))))
6394 (cond
6395 ((and target prop)
6396 (cond
6397 ((string= target-name "Number")
6398 (if (string-match js2-ecma-number-props prop-name)
6399 (setq face 'font-lock-constant-face)))
6400 ((string= target-name "Math")
6401 (if (string-match js2-ecma-math-props prop-name)
6402 (setq face 'font-lock-constant-face)))))
6403 (prop
6404 (if (string-match js2-ecma-object-props prop-name)
6405 (setq face 'font-lock-constant-face)))))
6406 (when face
6407 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6408 (js2-node-pos prop))) ; relative
6409 (+ pos (js2-node-len prop))
6410 face 'record)))))
6411
6412 (defun js2-parse-highlight-member-expr-node (node)
6413 "Perform syntax highlighting of EcmaScript built-in properties.
6414 The variable `js2-highlight-level' governs this highighting."
6415 (let (face target prop name pos end parent call-p callee)
6416 (cond
6417 ;; case 1: simple name, e.g. foo
6418 ((js2-name-node-p node)
6419 (setq name (js2-name-node-name node))
6420 ;; possible for name to be nil in rare cases - saw it when
6421 ;; running js2-mode on an elisp buffer. Might as well try to
6422 ;; make it so js2-mode never barfs.
6423 (when name
6424 (setq face (if (string-match js2-ecma-global-props name)
6425 'font-lock-constant-face))
6426 (when face
6427 (setq pos (js2-node-pos node)
6428 end (+ pos (js2-node-len node)))
6429 (js2-set-face pos end face 'record))))
6430 ;; case 2: property access or function call
6431 ((or (js2-prop-get-node-p node)
6432 ;; highlight function call if expr is a prop-get node
6433 ;; or a plain name (i.e. unqualified function call)
6434 (and (setq call-p (js2-call-node-p node))
6435 (setq callee (js2-call-node-target node)) ; separate setq!
6436 (or (js2-prop-get-node-p callee)
6437 (js2-name-node-p callee))))
6438 (setq parent node
6439 node (if call-p callee node))
6440 (if (and call-p (js2-name-node-p callee))
6441 (setq prop callee)
6442 (setq target (js2-prop-get-node-left node)
6443 prop (js2-prop-get-node-right node)))
6444 (cond
6445 ((js2-name-node-p target)
6446 (if (js2-name-node-p prop)
6447 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6448 (js2-parse-highlight-prop-get parent target prop call-p)
6449 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6450 (js2-parse-highlight-prop-get parent target nil call-p)))
6451 ((js2-name-node-p prop)
6452 ;; case 2c: complex target, simple name, e.g. x[y].bar
6453 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6454
6455 (defun js2-parse-highlight-member-expr-fn-name (expr)
6456 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6457 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6458 We currently only handle the case where the last component is a prop-get
6459 of a simple name. Called before EXPR has a parent node."
6460 (let (pos
6461 (name (and (js2-prop-get-node-p expr)
6462 (js2-prop-get-node-right expr))))
6463 (when (js2-name-node-p name)
6464 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6465 (js2-node-pos name)))
6466 (+ pos (js2-node-len name))
6467 'font-lock-function-name-face
6468 'record))))
6469
6470 ;; source: http://jsdoc.sourceforge.net/
6471 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6472 ;; allows type specifications, and needs work before entering the wild.
6473
6474 (defconst js2-jsdoc-param-tag-regexp
6475 (concat "^\\s-*\\*+\\s-*\\(@"
6476 "\\(?:param\\|argument\\)"
6477 "\\)"
6478 "\\s-*\\({[^}]+}\\)?" ; optional type
6479 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6480 "\\>")
6481 "Matches jsdoc tags with optional type and optional param name.")
6482
6483 (defconst js2-jsdoc-typed-tag-regexp
6484 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6485 (regexp-opt
6486 '("enum"
6487 "extends"
6488 "field"
6489 "id"
6490 "implements"
6491 "lends"
6492 "mods"
6493 "requires"
6494 "return"
6495 "returns"
6496 "throw"
6497 "throws"))
6498 "\\)\\)\\s-*\\({[^}]+}\\)?")
6499 "Matches jsdoc tags with optional type.")
6500
6501 (defconst js2-jsdoc-arg-tag-regexp
6502 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6503 (regexp-opt
6504 '("alias"
6505 "augments"
6506 "borrows"
6507 "bug"
6508 "base"
6509 "config"
6510 "default"
6511 "define"
6512 "exception"
6513 "function"
6514 "member"
6515 "memberOf"
6516 "name"
6517 "namespace"
6518 "property"
6519 "since"
6520 "suppress"
6521 "this"
6522 "throws"
6523 "type"
6524 "version"))
6525 "\\)\\)\\s-+\\([^ \t]+\\)")
6526 "Matches jsdoc tags with a single argument.")
6527
6528 (defconst js2-jsdoc-empty-tag-regexp
6529 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6530 (regexp-opt
6531 '("addon"
6532 "author"
6533 "class"
6534 "const"
6535 "constant"
6536 "constructor"
6537 "constructs"
6538 "deprecated"
6539 "desc"
6540 "description"
6541 "event"
6542 "example"
6543 "exec"
6544 "export"
6545 "fileoverview"
6546 "final"
6547 "function"
6548 "hidden"
6549 "ignore"
6550 "implicitCast"
6551 "inheritDoc"
6552 "inner"
6553 "interface"
6554 "license"
6555 "noalias"
6556 "noshadow"
6557 "notypecheck"
6558 "override"
6559 "owner"
6560 "preserve"
6561 "preserveTry"
6562 "private"
6563 "protected"
6564 "public"
6565 "static"
6566 "supported"
6567 ))
6568 "\\)\\)\\s-*")
6569 "Matches empty jsdoc tags.")
6570
6571 (defconst js2-jsdoc-link-tag-regexp
6572 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6573 "Matches a jsdoc link or code tag.")
6574
6575 (defconst js2-jsdoc-see-tag-regexp
6576 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6577 "Matches a jsdoc @see tag.")
6578
6579 (defconst js2-jsdoc-html-tag-regexp
6580 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6581 "Matches a simple (no attributes) html start- or end-tag.")
6582
6583 (defsubst js2-jsdoc-highlight-helper ()
6584 (js2-set-face (match-beginning 1)
6585 (match-end 1)
6586 'js2-jsdoc-tag-face)
6587 (if (match-beginning 2)
6588 (if (save-excursion
6589 (goto-char (match-beginning 2))
6590 (= (char-after) ?{))
6591 (js2-set-face (1+ (match-beginning 2))
6592 (1- (match-end 2))
6593 'js2-jsdoc-type-face)
6594 (js2-set-face (match-beginning 2)
6595 (match-end 2)
6596 'js2-jsdoc-value-face)))
6597 (if (match-beginning 3)
6598 (js2-set-face (match-beginning 3)
6599 (match-end 3)
6600 'js2-jsdoc-value-face)))
6601
6602 (defun js2-highlight-jsdoc (ast)
6603 "Highlight doc comment tags."
6604 (let ((comments (js2-ast-root-comments ast))
6605 beg end)
6606 (save-excursion
6607 (dolist (node comments)
6608 (when (eq (js2-comment-node-format node) 'jsdoc)
6609 (setq beg (js2-node-abs-pos node)
6610 end (+ beg (js2-node-len node)))
6611 (save-restriction
6612 (narrow-to-region beg end)
6613 (dolist (re (list js2-jsdoc-param-tag-regexp
6614 js2-jsdoc-typed-tag-regexp
6615 js2-jsdoc-arg-tag-regexp
6616 js2-jsdoc-link-tag-regexp
6617 js2-jsdoc-see-tag-regexp
6618 js2-jsdoc-empty-tag-regexp))
6619 (goto-char beg)
6620 (while (re-search-forward re nil t)
6621 (js2-jsdoc-highlight-helper)))
6622 ;; simple highlighting for html tags
6623 (goto-char beg)
6624 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6625 (js2-set-face (match-beginning 1)
6626 (match-end 1)
6627 'js2-jsdoc-html-tag-delimiter-face)
6628 (js2-set-face (match-beginning 2)
6629 (match-end 2)
6630 'js2-jsdoc-html-tag-name-face)
6631 (js2-set-face (match-beginning 3)
6632 (match-end 3)
6633 'js2-jsdoc-html-tag-delimiter-face))))))))
6634
6635 (defun js2-highlight-assign-targets (node left right)
6636 "Highlight function properties and external variables."
6637 (let (leftpos end name)
6638 ;; highlight vars and props assigned function values
6639 (when (js2-function-node-p right)
6640 (cond
6641 ;; var foo = function() {...}
6642 ((js2-name-node-p left)
6643 (setq name left))
6644 ;; foo.bar.baz = function() {...}
6645 ((and (js2-prop-get-node-p left)
6646 (js2-name-node-p (js2-prop-get-node-right left)))
6647 (setq name (js2-prop-get-node-right left))))
6648 (when name
6649 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6650 (+ leftpos (js2-node-len name))
6651 'font-lock-function-name-face
6652 'record)))))
6653
6654 (defun js2-record-name-node (node)
6655 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6656 later. NODE must be a name node."
6657 (let (leftpos end)
6658 (push (list node js2-current-scope
6659 (setq leftpos (js2-node-abs-pos node))
6660 (setq end (+ leftpos (js2-node-len node))))
6661 js2-recorded-identifiers)))
6662
6663 (defun js2-highlight-undeclared-vars ()
6664 "After entire parse is finished, look for undeclared variable references.
6665 We have to wait until entire buffer is parsed, since JavaScript permits var
6666 decls to occur after they're used.
6667
6668 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6669 it is considered declared."
6670 (let (name)
6671 (dolist (entry js2-recorded-identifiers)
6672 (destructuring-bind (name-node scope pos end) entry
6673 (setq name (js2-name-node-name name-node))
6674 (unless (or (member name js2-global-externs)
6675 (member name js2-default-externs)
6676 (member name js2-additional-externs)
6677 (js2-get-defining-scope scope name))
6678 (js2-set-face pos end 'js2-external-variable-face 'record)
6679 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6680 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6681 (setq js2-recorded-identifiers nil)))
6682
6683 ;;; IMenu support
6684
6685 ;; We currently only support imenu, but eventually should support speedbar and
6686 ;; possibly other browsing mechanisms.
6687
6688 ;; The basic strategy is to identify function assignment targets of the form
6689 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6690 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6691 ;; for imenu after parsing is finished.
6692
6693 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6694 ;; JavaScript, and the general problem is undecidable. However, several forms
6695 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6696 ;; include:
6697
6698 ;; function foo() -- function declaration
6699 ;; foo = function() -- function expression assigned to variable
6700 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6701 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6702 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6703 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6704 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6705 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6706 ;; function foo() {function bar() {...}} -- nested function
6707 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6708
6709 ;; This list boils down to a few forms that can be combined recursively.
6710 ;; Top-level named function declarations include both the left-hand (name)
6711 ;; and the right-hand (function value) expressions needed to produce an imenu
6712 ;; entry. The other "right-hand" forms we need to look for are:
6713 ;; - functions declared as props/getters/setters in object literals
6714 ;; - nested named function declarations
6715 ;; The "left-hand" expressions that functions can be assigned to include:
6716 ;; - local/global variables
6717 ;; - nested property-get expressions like a.b.c.d
6718 ;; - element gets like foo[10] or foo['bar'] where the index
6719 ;; expression can be trivially converted to a property name. They
6720 ;; effectively then become property gets.
6721
6722 ;; All the different definition types are canonicalized into the form
6723 ;; foo.bar.baz = position-of-function-keyword
6724
6725 ;; We need to build a trie-like structure for imenu. As an example,
6726 ;; consider the following JavaScript code:
6727
6728 ;; a = function() {...} // function at position 5
6729 ;; b = function() {...} // function at position 25
6730 ;; foo = function() {...} // function at position 100
6731 ;; foo.bar = function() {...} // function at position 200
6732 ;; foo.bar.baz = function() {...} // function at position 300
6733 ;; foo.bar.zab = function() {...} // function at position 400
6734
6735 ;; During parsing we accumulate an entry for each definition in
6736 ;; the variable `js2-imenu-recorder', like so:
6737
6738 ;; '((fn a 5)
6739 ;; (fn b 25)
6740 ;; (fn foo 100)
6741 ;; (fn foo bar 200)
6742 ;; (fn foo bar baz 300)
6743 ;; (fn foo bar zab 400))
6744
6745 ;; Where 'fn' is the respective function node.
6746 ;; After parsing these entries are merged into this alist-trie:
6747
6748 ;; '((a . 1)
6749 ;; (b . 2)
6750 ;; (foo (<definition> . 3)
6751 ;; (bar (<definition> . 6)
6752 ;; (baz . 100)
6753 ;; (zab . 200))))
6754
6755 ;; Note the wacky need for a <definition> name. The token can be anything
6756 ;; that isn't a valid JavaScript identifier, because you might make foo
6757 ;; a function and then start setting properties on it that are also functions.
6758
6759 (defsubst js2-prop-node-name (node)
6760 "Return the name of a node that may be a property-get/property-name.
6761 If NODE is not a valid name-node, string-node or integral number-node,
6762 returns nil. Otherwise returns the string name/value of the node."
6763 (cond
6764 ((js2-name-node-p node)
6765 (js2-name-node-name node))
6766 ((js2-string-node-p node)
6767 (js2-string-node-value node))
6768 ((and (js2-number-node-p node)
6769 (string-match "^[0-9]+$" (js2-number-node-value node)))
6770 (js2-number-node-value node))
6771 ((js2-this-node-p node)
6772 "this")))
6773
6774 (defsubst js2-node-qname-component (node)
6775 "Return the name of this node, if it contributes to a qname.
6776 Returns nil if the node doesn't contribute."
6777 (copy-sequence
6778 (or (js2-prop-node-name node)
6779 (if (and (js2-function-node-p node)
6780 (js2-function-node-name node))
6781 (js2-name-node-name (js2-function-node-name node))))))
6782
6783 (defsubst js2-record-imenu-entry (fn-node qname pos)
6784 "Add an entry to `js2-imenu-recorder'.
6785 FN-NODE should be the current item's function node.
6786
6787 Associate FN-NODE with its QNAME for later lookup.
6788 This is used in postprocessing the chain list. For each chain, we find
6789 the parent function, look up its qname, then prepend a copy of it to the chain."
6790 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6791 (unless js2-imenu-function-map
6792 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6793 (puthash fn-node qname js2-imenu-function-map))
6794
6795 (defun js2-record-imenu-functions (node &optional var)
6796 "Record function definitions for imenu.
6797 NODE is a function node or an object literal.
6798 VAR, if non-nil, is the expression that NODE is being assigned to.
6799 When passed arguments of wrong type, does nothing."
6800 (when js2-parse-ide-mode
6801 (let ((fun-p (js2-function-node-p node))
6802 qname left fname-node pos)
6803 (cond
6804 ;; non-anonymous function declaration?
6805 ((and fun-p
6806 (not var)
6807 (setq fname-node (js2-function-node-name node)))
6808 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6809 ;; for remaining forms, compute left-side tree branch first
6810 ((and var (setq qname (js2-compute-nested-prop-get var)))
6811 (cond
6812 ;; foo.bar.baz = function
6813 (fun-p
6814 (js2-record-imenu-entry node qname (js2-node-pos node)))
6815 ;; foo.bar.baz = object-literal
6816 ;; look for nested functions: {a: {b: function() {...} }}
6817 ((js2-object-node-p node)
6818 ;; Node position here is still absolute, since the parser
6819 ;; passes the assignment target and value expressions
6820 ;; to us before they are added as children of the assignment node.
6821 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6822
6823 (defun js2-compute-nested-prop-get (node)
6824 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6825 component nodes as a list. Otherwise return nil. Element-gets are treated
6826 as property-gets if the index expression is a string, or a positive integer."
6827 (let (left right head)
6828 (cond
6829 ((or (js2-name-node-p node)
6830 (js2-this-node-p node))
6831 (list node))
6832 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6833 ((js2-prop-get-node-p node) ; foo.bar
6834 (setq left (js2-prop-get-node-left node)
6835 right (js2-prop-get-node-right node))
6836 (if (setq head (js2-compute-nested-prop-get left))
6837 (nconc head (list right))))
6838 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6839 (setq left (js2-elem-get-node-target node)
6840 right (js2-elem-get-node-element node))
6841 (if (or (js2-string-node-p right) ; ['bar']
6842 (and (js2-number-node-p right) ; [10]
6843 (string-match "^[0-9]+$"
6844 (js2-number-node-value right))))
6845 (if (setq head (js2-compute-nested-prop-get left))
6846 (nconc head (list right))))))))
6847
6848 (defun js2-record-object-literal (node qname pos)
6849 "Recursively process an object literal looking for functions.
6850 NODE is an object literal that is the right-hand child of an assignment
6851 expression. QNAME is a list of nodes representing the assignment target,
6852 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6853 POS is the absolute position of the node.
6854 We do a depth-first traversal of NODE. For any functions we find,
6855 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6856 (let (left right prop-qname)
6857 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6858 (let ((left (js2-infix-node-left e))
6859 ;; Element positions are relative to the parent position.
6860 (pos (+ pos (js2-node-pos e))))
6861 (cond
6862 ;; foo: function() {...}
6863 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6864 (when (js2-prop-node-name left)
6865 ;; As a policy decision, we record the position of the property,
6866 ;; not the position of the `function' keyword, since the property
6867 ;; is effectively the name of the function.
6868 (js2-record-imenu-entry right (append qname (list left)) pos)))
6869 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6870 ((js2-object-node-p right)
6871 (js2-record-object-literal right
6872 (append qname (list (js2-infix-node-left e)))
6873 (+ pos (js2-node-pos right)))))))))
6874
6875 (defsubst js2-node-top-level-decl-p (node)
6876 "Return t if NODE's name is defined in the top-level scope.
6877 Also returns t if NODE's name is not defined in any scope, since it implies
6878 that it's an external variable, which must also be in the top-level scope."
6879 (let* ((name (js2-prop-node-name node))
6880 (this-scope (js2-node-get-enclosing-scope node))
6881 defining-scope)
6882 (cond
6883 ((js2-this-node-p node)
6884 nil)
6885 ((null this-scope)
6886 t)
6887 ((setq defining-scope (js2-get-defining-scope this-scope name))
6888 (js2-ast-root-p defining-scope))
6889 (t t))))
6890
6891 (defsubst js2-wrapper-function-p (node)
6892 "Returns t if NODE is a function expression that's immediately invoked.
6893 NODE must be `js2-function-node'."
6894 (let ((parent (js2-node-parent node)))
6895 (or
6896 ;; function(){...}();
6897 (js2-call-node-p parent)
6898 (and (js2-paren-node-p parent)
6899 ;; (function(){...})();
6900 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6901 ;; (function(){...}).call(this);
6902 (and (js2-prop-get-node-p parent)
6903 (member (js2-name-node-name (js2-prop-get-node-right parent))
6904 '("call" "apply"))
6905 (js2-call-node-p (js2-node-parent parent))))))))
6906
6907 (defun js2-browse-postprocess-chains (entries)
6908 "Modify function-declaration name chains after parsing finishes.
6909 Some of the information is only available after the parse tree is complete.
6910 For instance, processing a nested scope requires a parent function node."
6911 (let (result head fn current-fn parent-qname qname p elem)
6912 (dolist (entry entries)
6913 ;; function node goes first
6914 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6915 ;; Examine head's defining scope:
6916 ;; Pre-processed chain, or top-level/external, keep as-is.
6917 (if (or (stringp head) (js2-node-top-level-decl-p head))
6918 (push chain result)
6919 (when (js2-this-node-p head)
6920 (setq chain (cdr chain))) ; discard this-node
6921 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6922 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6923 (when (eq parent-qname 'not-found)
6924 ;; anonymous function expressions are not recorded
6925 ;; during the parse, so we need to handle this case here
6926 (setq parent-qname
6927 (if (js2-wrapper-function-p fn)
6928 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6929 (if (js2-ast-root-p grandparent)
6930 nil
6931 (gethash grandparent js2-imenu-function-map 'skip)))
6932 'skip))
6933 (puthash fn parent-qname js2-imenu-function-map))
6934 (unless (eq parent-qname 'skip)
6935 ;; prefix parent fn qname to this chain.
6936 (let ((qname (append parent-qname chain)))
6937 (puthash current-fn (butlast qname) js2-imenu-function-map)
6938 (push qname result)))))))
6939 ;; finally replace each node in each chain with its name.
6940 (dolist (chain result)
6941 (setq p chain)
6942 (while p
6943 (if (js2-node-p (setq elem (car p)))
6944 (setcar p (js2-node-qname-component elem)))
6945 (setq p (cdr p))))
6946 result))
6947
6948 ;; Merge name chains into a trie-like tree structure of nested lists.
6949 ;; To simplify construction of the trie, we first build it out using the rule
6950 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6951 ;; [key, num-or-list]. The second element can be a number; if so, this key
6952 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6953 ;; associated with the key at this level.) Otherwise the second element is
6954 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6955 ;; a simple recursive formulation.
6956 ;;
6957 ;; js2-mode is building the data structure for imenu. The imenu documentation
6958 ;; claims that it's the structure above, but in practice it wants the children
6959 ;; at the same list level as the key for that level, which is how I've drawn
6960 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6961 ;; list wrapper around the children at each level.
6962 ;;
6963 ;; A completed nested imenu-alist entry looks like this:
6964 ;; '(("foo"
6965 ;; ("<definition>" . 7)
6966 ;; ("bar"
6967 ;; ("a" . 40)
6968 ;; ("b" . 60))))
6969 ;;
6970 ;; In particular, the documentation for `imenu--index-alist' says that
6971 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6972 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6973
6974 (defun js2-treeify (lst)
6975 "Convert (a b c d) to (a ((b ((c d)))))"
6976 (if (null (cddr lst)) ; list length <= 2
6977 lst
6978 (list (car lst) (list (js2-treeify (cdr lst))))))
6979
6980 (defun js2-build-alist-trie (chains trie)
6981 "Merge declaration name chains into a trie-like alist structure for imenu.
6982 CHAINS is the qname chain list produced during parsing. TRIE is a
6983 list of elements built up so far."
6984 (let (head tail pos branch kids)
6985 (dolist (chain chains)
6986 (setq head (car chain)
6987 tail (cdr chain)
6988 pos (if (numberp (car tail)) (car tail))
6989 branch (js2-find-if (lambda (n)
6990 (string= (car n) head))
6991 trie)
6992 kids (second branch))
6993 (cond
6994 ;; case 1: this key isn't in the trie yet
6995 ((null branch)
6996 (if trie
6997 (setcdr (last trie) (list (js2-treeify chain)))
6998 (setq trie (list (js2-treeify chain)))))
6999 ;; case 2: key is present with a single number entry: replace w/ list
7000 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7001 ;; ("<definition>" 20)))
7002 ((numberp kids)
7003 (setcar (cdr branch)
7004 (list (list "<definition-1>" kids)
7005 (if pos
7006 (list "<definition-2>" pos)
7007 (js2-treeify tail)))))
7008 ;; case 3: key is there (with kids), and we're a number entry
7009 (pos
7010 (setcdr (last kids)
7011 (list
7012 (list (format "<definition-%d>"
7013 (1+ (loop for kid in kids
7014 count (eq ?< (aref (car kid) 0)))))
7015 pos))))
7016 ;; case 4: key is there with kids, need to merge in our chain
7017 (t
7018 (js2-build-alist-trie (list tail) kids))))
7019 trie))
7020
7021 (defun js2-flatten-trie (trie)
7022 "Convert TRIE to imenu-format.
7023 Recurses through nodes, and for each one whose second element is a list,
7024 appends the list's flattened elements to the current element. Also
7025 changes the tails into conses. For instance, this pre-flattened trie
7026
7027 '(a ((b 20)
7028 (c ((d 30)
7029 (e 40)))))
7030
7031 becomes
7032
7033 '(a (b . 20)
7034 (c (d . 30)
7035 (e . 40)))
7036
7037 Note that the root of the trie has no key, just a list of chains.
7038 This is also true for the value of any key with multiple children,
7039 e.g. key 'c' in the example above."
7040 (cond
7041 ((listp (car trie))
7042 (mapcar #'js2-flatten-trie trie))
7043 (t
7044 (if (numberp (second trie))
7045 (cons (car trie) (second trie))
7046 ;; else pop list and append its kids
7047 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7048
7049 (defun js2-build-imenu-index ()
7050 "Turn `js2-imenu-recorder' into an imenu data structure."
7051 (unless (eq js2-imenu-recorder 'empty)
7052 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7053 (result (js2-build-alist-trie chains nil)))
7054 (js2-flatten-trie result))))
7055
7056 (defun js2-test-print-chains (chains)
7057 "Print a list of qname chains.
7058 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7059 i.e. one or more nodes, and an integer position as the list tail."
7060 (mapconcat (lambda (chain)
7061 (concat "("
7062 (mapconcat (lambda (elem)
7063 (if (js2-node-p elem)
7064 (or (js2-node-qname-component elem)
7065 "nil")
7066 (number-to-string elem)))
7067 chain
7068 " ")
7069 ")"))
7070 chains
7071 "\n"))
7072
7073 ;;; Parser
7074
7075 (defconst js2-version "1.8.5"
7076 "Version of JavaScript supported.")
7077
7078 (defmacro js2-record-face (face)
7079 "Record a style run of FACE for the current token."
7080 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7081
7082 (defsubst js2-node-end (n)
7083 "Computes the absolute end of node N.
7084 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7085 is only true until the node is added to its parent; i.e., while parsing."
7086 (+ (js2-node-pos n)
7087 (js2-node-len n)))
7088
7089 (defsubst js2-record-comment ()
7090 "Record a comment in `js2-scanned-comments'."
7091 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7092 :format js2-ts-comment-type)
7093 js2-scanned-comments)
7094 (when js2-parse-ide-mode
7095 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7096 'font-lock-doc-face
7097 'font-lock-comment-face))
7098 (when (memq js2-ts-comment-type '(html preprocessor))
7099 ;; Tell cc-engine the bounds of the comment.
7100 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7101
7102 ;; This function is called depressingly often, so it should be fast.
7103 ;; Most of the time it's looking at the same token it peeked before.
7104 (defsubst js2-peek-token ()
7105 "Returns the next token without consuming it.
7106 If previous token was consumed, calls scanner to get new token.
7107 If previous token was -not- consumed, returns it (idempotent).
7108
7109 This function will not return a newline (js2-EOL) - instead, it
7110 gobbles newlines until it finds a non-newline token, and flags
7111 that token as appearing just after a newline.
7112
7113 This function will also not return a js2-COMMENT. Instead, it
7114 records comments found in `js2-scanned-comments'. If the token
7115 returned by this function immediately follows a jsdoc comment,
7116 the token is flagged as such.
7117
7118 Note that this function always returned the un-flagged token!
7119 The flags, if any, are saved in `js2-current-flagged-token'."
7120 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7121 js2-current-token ; most common case - return already-peeked token
7122 (let ((tt (js2-get-token)) ; call scanner
7123 saw-eol
7124 face)
7125 ;; process comments and whitespace
7126 (while (or (= tt js2-EOL)
7127 (= tt js2-COMMENT))
7128 (if (= tt js2-EOL)
7129 (setq saw-eol t)
7130 (setq saw-eol nil)
7131 (if js2-record-comments
7132 (js2-record-comment)))
7133 (setq tt (js2-get-token))) ; call scanner
7134 (setq js2-current-token tt
7135 js2-current-flagged-token (if saw-eol
7136 (logior tt js2-ti-after-eol)
7137 tt))
7138 ;; perform lexical fontification as soon as token is scanned
7139 (when js2-parse-ide-mode
7140 (cond
7141 ((minusp tt)
7142 (js2-record-face 'js2-error-face))
7143 ((setq face (aref js2-kwd-tokens tt))
7144 (js2-record-face face))
7145 ((and (= tt js2-NAME)
7146 (equal js2-ts-string "undefined"))
7147 (js2-record-face 'font-lock-constant-face))))
7148 tt))) ; return unflagged token
7149
7150 (defsubst js2-peek-flagged-token ()
7151 "Returns the current token along with any flags set for it."
7152 (js2-peek-token)
7153 js2-current-flagged-token)
7154
7155 (defsubst js2-consume-token ()
7156 (setq js2-current-flagged-token js2-EOF))
7157
7158 (defsubst js2-next-token ()
7159 (prog1
7160 (js2-peek-token)
7161 (js2-consume-token)))
7162
7163 (defsubst js2-next-flagged-token ()
7164 (js2-peek-token)
7165 (prog1 js2-current-flagged-token
7166 (js2-consume-token)))
7167
7168 (defsubst js2-match-token (match)
7169 "Consume and return t if next token matches MATCH, a bytecode.
7170 Returns nil and consumes nothing if MATCH is not the next token."
7171 (if (/= (js2-peek-token) match)
7172 nil
7173 (js2-consume-token)
7174 t))
7175
7176 (defun js2-match-contextual-kwd (name)
7177 "Consume and return t if next token is `js2-NAME', and its
7178 string is NAME. Returns nil and does nothing otherwise."
7179 (if (or (/= (js2-peek-token) js2-NAME)
7180 (not (string= js2-ts-string name)))
7181 nil
7182 (js2-consume-token)
7183 (js2-record-face 'font-lock-keyword-face)
7184 t))
7185
7186 (defsubst js2-valid-prop-name-token (tt)
7187 (or (= tt js2-NAME)
7188 (when (and js2-allow-keywords-as-property-names
7189 (plusp tt)
7190 (aref js2-kwd-tokens tt))
7191 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7192 t)))
7193
7194 (defsubst js2-match-prop-name ()
7195 "Consume token and return t if next token is a valid property name.
7196 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7197 is non-nil and it's a keyword token."
7198 (if (js2-valid-prop-name-token (js2-peek-token))
7199 (progn
7200 (js2-consume-token)
7201 t)
7202 nil))
7203
7204 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7205 (if (js2-match-prop-name)
7206 t
7207 (js2-report-error msg-id nil pos len)
7208 nil))
7209
7210 (defsubst js2-peek-token-or-eol ()
7211 "Return js2-EOL if the current token immediately follows a newline.
7212 Else returns the current token. Used in situations where we don't
7213 consider certain token types valid if they are preceded by a newline.
7214 One example is the postfix ++ or -- operator, which has to be on the
7215 same line as its operand."
7216 (let ((tt (js2-peek-token)))
7217 ;; Check for last peeked token flags
7218 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7219 js2-EOL
7220 tt)))
7221
7222 (defsubst js2-set-check-for-label ()
7223 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7224 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7225
7226 (defsubst js2-must-match (token msg-id &optional pos len)
7227 "Match next token to token code TOKEN, or record a syntax error.
7228 MSG-ID is the error message to report if the match fails.
7229 Returns t on match, nil if no match."
7230 (if (js2-match-token token)
7231 t
7232 (js2-report-error msg-id nil pos len)
7233 nil))
7234
7235 (defsubst js2-inside-function ()
7236 (plusp js2-nesting-of-function))
7237
7238 (defsubst js2-set-requires-activation ()
7239 (if (js2-function-node-p js2-current-script-or-fn)
7240 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7241
7242 (defsubst js2-check-activation-name (name token)
7243 (when (js2-inside-function)
7244 ;; skip language-version 1.2 check from Rhino
7245 (if (or (string= "arguments" name)
7246 (and js2-compiler-activation-names ; only used in codegen
7247 (gethash name js2-compiler-activation-names)))
7248 (js2-set-requires-activation))))
7249
7250 (defsubst js2-set-is-generator ()
7251 (if (js2-function-node-p js2-current-script-or-fn)
7252 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7253
7254 (defsubst js2-must-have-xml ()
7255 (unless js2-compiler-xml-available
7256 (js2-report-error "msg.XML.not.available")))
7257
7258 (defsubst js2-push-scope (scope)
7259 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7260 (assert (js2-scope-p scope))
7261 (assert (null (js2-scope-parent-scope scope)))
7262 (assert (not (eq js2-current-scope scope)))
7263 (setf (js2-scope-parent-scope scope) js2-current-scope
7264 js2-current-scope scope))
7265
7266 (defsubst js2-pop-scope ()
7267 (setq js2-current-scope
7268 (js2-scope-parent-scope js2-current-scope)))
7269
7270 (defsubst js2-enter-loop (loop-node)
7271 (push loop-node js2-loop-set)
7272 (push loop-node js2-loop-and-switch-set)
7273 (js2-push-scope loop-node)
7274 ;; Tell the current labeled statement (if any) its statement,
7275 ;; and set the jump target of the first label to the loop.
7276 ;; These are used in `js2-parse-continue' to verify that the
7277 ;; continue target is an actual labeled loop. (And for codegen.)
7278 (when js2-labeled-stmt
7279 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7280 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7281 js2-labeled-stmt))) loop-node)))
7282
7283 (defsubst js2-exit-loop ()
7284 (pop js2-loop-set)
7285 (pop js2-loop-and-switch-set)
7286 (js2-pop-scope))
7287
7288 (defsubst js2-enter-switch (switch-node)
7289 (push switch-node js2-loop-and-switch-set))
7290
7291 (defsubst js2-exit-switch ()
7292 (pop js2-loop-and-switch-set))
7293
7294 (defun js2-parse (&optional buf cb)
7295 "Tells the js2 parser to parse a region of JavaScript.
7296
7297 BUF is a buffer or buffer name containing the code to parse.
7298 Call `narrow-to-region' first to parse only part of the buffer.
7299
7300 The returned AST root node is given some additional properties:
7301 `node-count' - total number of nodes in the AST
7302 `buffer' - BUF. The buffer it refers to may change or be killed,
7303 so the value is not necessarily reliable.
7304
7305 An optional callback CB can be specified to report parsing
7306 progress. If `(functionp CB)' returns t, it will be called with
7307 the current line number once before parsing begins, then again
7308 each time the lexer reaches a new line number.
7309
7310 CB can also be a list of the form `(symbol cb ...)' to specify
7311 multiple callbacks with different criteria. Each symbol is a
7312 criterion keyword, and the following element is the callback to
7313 call
7314
7315 :line - called whenever the line number changes
7316 :token - called for each new token consumed
7317
7318 The list of criteria could be extended to include entering or
7319 leaving a statement, an expression, or a function definition."
7320 (if (and cb (not (functionp cb)))
7321 (error "criteria callbacks not yet implemented"))
7322 (let ((inhibit-point-motion-hooks t)
7323 (js2-compiler-xml-available (>= js2-language-version 160))
7324 ;; This is a recursive-descent parser, so give it a big stack.
7325 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7326 (max-specpdl-size (max max-specpdl-size 3000))
7327 (case-fold-search nil)
7328 ast)
7329 (message nil) ; clear any error message from previous parse
7330 (save-excursion
7331 (when buf (set-buffer buf))
7332 (setq js2-scanned-comments nil
7333 js2-parsed-errors nil
7334 js2-parsed-warnings nil
7335 js2-imenu-recorder nil
7336 js2-imenu-function-map nil
7337 js2-label-set nil)
7338 (js2-init-scanner)
7339 (setq ast (js2-with-unmodifying-text-property-changes
7340 (js2-do-parse)))
7341 (unless js2-ts-hit-eof
7342 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7343 (setf (js2-ast-root-errors ast) js2-parsed-errors
7344 (js2-ast-root-warnings ast) js2-parsed-warnings)
7345 ;; if we didn't find any declarations, put a dummy in this list so we
7346 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7347 (unless js2-imenu-recorder
7348 (setq js2-imenu-recorder 'empty))
7349 (run-hooks 'js2-parse-finished-hook)
7350 ast)))
7351
7352 ;; Corresponds to Rhino's Parser.parse() method.
7353 (defun js2-do-parse ()
7354 "Parse current buffer starting from current point.
7355 Scanner should be initialized."
7356 (let ((pos js2-ts-cursor)
7357 (end js2-ts-cursor) ; in case file is empty
7358 root n tt)
7359 ;; initialize buffer-local parsing vars
7360 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7361 js2-current-script-or-fn root
7362 js2-current-scope root
7363 js2-current-flagged-token js2-EOF
7364 js2-nesting-of-function 0
7365 js2-labeled-stmt nil
7366 js2-recorded-identifiers nil) ; for js2-highlight
7367 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7368 (if (= tt js2-FUNCTION)
7369 (progn
7370 (js2-consume-token)
7371 (setq n (js2-parse-function (if js2-called-by-compile-function
7372 'FUNCTION_EXPRESSION
7373 'FUNCTION_STATEMENT))))
7374 ;; not a function - parse a statement
7375 (setq n (js2-parse-statement)))
7376 ;; add function or statement to script
7377 (setq end (js2-node-end n))
7378 (js2-block-node-push root n))
7379 ;; add comments to root in lexical order
7380 (when js2-scanned-comments
7381 ;; if we find a comment beyond end of normal kids, use its end
7382 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7383 (dolist (comment js2-scanned-comments)
7384 (push comment (js2-ast-root-comments root))
7385 (js2-node-add-children root comment)))
7386 (setf (js2-node-len root) (- end pos))
7387 ;; Give extensions a chance to muck with things before highlighting starts.
7388 (let ((js2-additional-externs js2-additional-externs))
7389 (dolist (callback js2-post-parse-callbacks)
7390 (funcall callback))
7391 (js2-highlight-undeclared-vars))
7392 root))
7393
7394 (defun js2-function-parser ()
7395 (js2-consume-token)
7396 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7397
7398 (defun js2-parse-function-closure-body (fn-node)
7399 "Parse a JavaScript 1.8 function closure body."
7400 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7401 (if js2-ts-hit-eof
7402 (js2-report-error "msg.no.brace.body" nil
7403 (js2-node-pos fn-node)
7404 (- js2-ts-cursor (js2-node-pos fn-node)))
7405 (js2-node-add-children fn-node
7406 (setf (js2-function-node-body fn-node)
7407 (js2-parse-expr t))))))
7408
7409 (defun js2-parse-function-body (fn-node)
7410 (js2-must-match js2-LC "msg.no.brace.body"
7411 (js2-node-pos fn-node)
7412 (- js2-ts-cursor (js2-node-pos fn-node)))
7413 (let ((pos js2-token-beg) ; LC position
7414 (pn (make-js2-block-node)) ; starts at LC position
7415 tt
7416 end)
7417 (incf js2-nesting-of-function)
7418 (unwind-protect
7419 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7420 (= tt js2-EOF)
7421 (= tt js2-RC)))
7422 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7423 (js2-parse-statement)
7424 (js2-consume-token)
7425 (js2-parse-function 'FUNCTION_STATEMENT))))
7426 (decf js2-nesting-of-function))
7427 (setq end js2-token-end) ; assume no curly and leave at current token
7428 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7429 (setq end js2-token-end))
7430 (setf (js2-node-pos pn) pos
7431 (js2-node-len pn) (- end pos))
7432 (setf (js2-function-node-body fn-node) pn)
7433 (js2-node-add-children fn-node pn)
7434 pn))
7435
7436 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7437 "Declare and fontify destructuring parameters inside NODE.
7438 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7439 (cond
7440 ((js2-name-node-p node)
7441 (let (leftpos)
7442 (js2-define-symbol decl-type (js2-name-node-name node)
7443 node ignore-not-in-block)
7444 (when face
7445 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7446 (+ leftpos (js2-node-len node))
7447 face 'record))))
7448 ((js2-object-node-p node)
7449 (dolist (elem (js2-object-node-elems node))
7450 (js2-define-destruct-symbols
7451 (if (js2-object-prop-node-p elem)
7452 (js2-object-prop-node-right elem)
7453 ;; abbreviated destructuring {a, b}
7454 elem)
7455 decl-type face ignore-not-in-block)))
7456 ((js2-array-node-p node)
7457 (dolist (elem (js2-array-node-elems node))
7458 (when elem
7459 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7460 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7461 (js2-node-len node)))))
7462
7463 (defun js2-parse-function-params (fn-node pos)
7464 (if (js2-match-token js2-RP)
7465 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7466 (let (params len param default-found rest-param-at)
7467 (loop for tt = (js2-peek-token)
7468 do
7469 (cond
7470 ;; destructuring param
7471 ((or (= tt js2-LB) (= tt js2-LC))
7472 (when default-found
7473 (js2-report-error "msg.no.default.after.default.param"))
7474 (setq param (js2-parse-destruct-primary-expr))
7475 (js2-define-destruct-symbols param
7476 js2-LP
7477 'js2-function-param-face)
7478 (push param params))
7479 ;; variable name
7480 (t
7481 (when (and (>= js2-language-version 200)
7482 (js2-match-token js2-TRIPLEDOT)
7483 (not rest-param-at))
7484 ;; to report errors if there are more parameters
7485 (setq rest-param-at (length params)))
7486 (js2-must-match js2-NAME "msg.no.parm")
7487 (js2-record-face 'js2-function-param-face)
7488 (setq param (js2-create-name-node))
7489 (js2-define-symbol js2-LP js2-ts-string param)
7490 ;; default parameter value
7491 (when (or (and default-found
7492 (not rest-param-at)
7493 (js2-must-match js2-ASSIGN
7494 "msg.no.default.after.default.param"
7495 (js2-node-pos param)
7496 (js2-node-len param)))
7497 (and (>= js2-language-version 200)
7498 (js2-match-token js2-ASSIGN)))
7499 (let* ((pos (js2-node-pos param))
7500 (tt js2-current-token)
7501 (op-pos (- js2-token-beg pos))
7502 (left param)
7503 (right (js2-parse-assign-expr))
7504 (len (- (js2-node-end right) pos)))
7505 (setq param (make-js2-assign-node
7506 :type tt :pos pos :len len :op-pos op-pos
7507 :left left :right right)
7508 default-found t)
7509 (js2-node-add-children param left right)))
7510 (push param params)))
7511 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7512 (js2-report-error "msg.param.after.rest" nil
7513 (js2-node-pos param) (js2-node-len param)))
7514 while
7515 (js2-match-token js2-COMMA))
7516 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7517 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7518 (when rest-param-at
7519 (setf (js2-function-node-rest-p fn-node) t))
7520 (dolist (p params)
7521 (js2-node-add-children fn-node p)
7522 (push p (js2-function-node-params fn-node))))))
7523
7524 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7525 "Possibly show inconsistent-return warning.
7526 Last token scanned is the close-curly for the function body."
7527 (when (and js2-mode-show-strict-warnings
7528 js2-strict-inconsistent-return-warning
7529 (not (js2-has-consistent-return-usage
7530 (js2-function-node-body fn-node))))
7531 ;; Have it extend from close-curly to bol or beginning of block.
7532 (let ((pos (save-excursion
7533 (goto-char js2-token-end)
7534 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7535 (point-at-bol))))
7536 (end js2-token-end))
7537 (if (plusp (js2-name-node-length name))
7538 (js2-add-strict-warning "msg.no.return.value"
7539 (js2-name-node-name name) pos end)
7540 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7541
7542 (defun js2-parse-function (function-type)
7543 "Function parser. FUNCTION-TYPE is a symbol."
7544 (let ((pos js2-token-beg) ; start of 'function' keyword
7545 name
7546 name-beg
7547 name-end
7548 fn-node
7549 lp
7550 (synthetic-type function-type)
7551 member-expr-node)
7552 ;; parse function name, expression, or non-name (anonymous)
7553 (cond
7554 ;; function foo(...)
7555 ((js2-match-token js2-NAME)
7556 (setq name (js2-create-name-node t)
7557 name-beg js2-token-beg
7558 name-end js2-token-end)
7559 (unless (js2-match-token js2-LP)
7560 (when js2-allow-member-expr-as-function-name
7561 ;; function foo.bar(...)
7562 (setq member-expr-node name
7563 name nil
7564 member-expr-node (js2-parse-member-expr-tail
7565 nil member-expr-node)))
7566 (js2-must-match js2-LP "msg.no.paren.parms")))
7567 ((js2-match-token js2-LP)
7568 nil) ; anonymous function: leave name as null
7569 (t
7570 ;; function random-member-expr(...)
7571 (when js2-allow-member-expr-as-function-name
7572 ;; Note that memberExpr can not start with '(' like
7573 ;; in function (1+2).toString(), because 'function (' already
7574 ;; processed as anonymous function
7575 (setq member-expr-node (js2-parse-member-expr)))
7576 (js2-must-match js2-LP "msg.no.paren.parms")))
7577 (if (= js2-current-token js2-LP) ; eventually matched LP?
7578 (setq lp js2-token-beg))
7579 (if member-expr-node
7580 (progn
7581 (setq synthetic-type 'FUNCTION_EXPRESSION)
7582 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7583 (if name
7584 (js2-set-face name-beg name-end
7585 'font-lock-function-name-face 'record)))
7586 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7587 (plusp (js2-name-node-length name)))
7588 ;; Function statements define a symbol in the enclosing scope
7589 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7590 (setf fn-node (make-js2-function-node :pos pos
7591 :name name
7592 :form function-type
7593 :lp (if lp (- lp pos))))
7594 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7595 ;; 1. Nested functions are not affected by the dynamic scope flag
7596 ;; as dynamic scope is already a parent of their scope.
7597 ;; 2. Functions defined under the with statement also immune to
7598 ;; this setup, in which case dynamic scope is ignored in favor
7599 ;; of the with object.
7600 (setf (js2-function-node-ignore-dynamic fn-node) t))
7601 ;; dynamically bind all the per-function variables
7602 (let ((js2-current-script-or-fn fn-node)
7603 (js2-current-scope fn-node)
7604 (js2-nesting-of-with 0)
7605 (js2-end-flags 0)
7606 js2-label-set
7607 js2-loop-set
7608 js2-loop-and-switch-set)
7609 (js2-parse-function-params fn-node pos)
7610 (if (and (>= js2-language-version 180)
7611 (/= (js2-peek-token) js2-LC))
7612 (js2-parse-function-closure-body fn-node)
7613 (js2-parse-function-body fn-node))
7614 (if name
7615 (js2-node-add-children fn-node name))
7616 (js2-check-inconsistent-return-warning fn-node name)
7617 ;; Function expressions define a name only in the body of the
7618 ;; function, and only if not hidden by a parameter name
7619 (if (and name
7620 (eq synthetic-type 'FUNCTION_EXPRESSION)
7621 (null (js2-scope-get-symbol js2-current-scope
7622 (js2-name-node-name name))))
7623 (js2-define-symbol js2-FUNCTION
7624 (js2-name-node-name name)
7625 fn-node))
7626 (if (and name
7627 (not (eq function-type 'FUNCTION_EXPRESSION)))
7628 (js2-record-imenu-functions fn-node)))
7629 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7630 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7631 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7632 ;; We wait until after parsing the function to set its parent scope,
7633 ;; since `js2-define-symbol' needs the defining-scope check to stop
7634 ;; at the function boundary when checking for redeclarations.
7635 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7636 fn-node))
7637
7638 (defun js2-parse-statements (&optional parent)
7639 "Parse a statement list. Last token consumed must be js2-LC.
7640
7641 PARENT can be a `js2-block-node', in which case the statements are
7642 appended to PARENT. Otherwise a new `js2-block-node' is created
7643 and returned.
7644
7645 This function does not match the closing js2-RC: the caller
7646 matches the RC so it can provide a suitable error message if not
7647 matched. This means it's up to the caller to set the length of
7648 the node to include the closing RC. The node start pos is set to
7649 the absolute buffer start position, and the caller should fix it
7650 up to be relative to the parent node. All children of this block
7651 node are given relative start positions and correct lengths."
7652 (let ((pn (or parent (make-js2-block-node)))
7653 tt)
7654 (setf (js2-node-pos pn) js2-token-beg)
7655 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7656 (/= tt js2-RC))
7657 (js2-block-node-push pn (js2-parse-statement)))
7658 pn))
7659
7660 (defun js2-parse-statement ()
7661 (let (tt pn beg end)
7662 ;; coarse-grained user-interrupt check - needs work
7663 (and js2-parse-interruptable-p
7664 (zerop (% (incf js2-parse-stmt-count)
7665 js2-statements-per-pause))
7666 (input-pending-p)
7667 (throw 'interrupted t))
7668 (setq pn (js2-statement-helper))
7669 ;; no-side-effects warning check
7670 (unless (js2-node-has-side-effects pn)
7671 (setq end (js2-node-end pn))
7672 (save-excursion
7673 (goto-char end)
7674 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7675 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7676 pn))
7677
7678 ;; These correspond to the switch cases in Parser.statementHelper
7679 (defconst js2-parsers
7680 (let ((parsers (make-vector js2-num-tokens
7681 #'js2-parse-expr-stmt)))
7682 (aset parsers js2-BREAK #'js2-parse-break)
7683 (aset parsers js2-CONST #'js2-parse-const-var)
7684 (aset parsers js2-CONTINUE #'js2-parse-continue)
7685 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7686 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7687 (aset parsers js2-DO #'js2-parse-do)
7688 (aset parsers js2-FOR #'js2-parse-for)
7689 (aset parsers js2-FUNCTION #'js2-function-parser)
7690 (aset parsers js2-IF #'js2-parse-if)
7691 (aset parsers js2-LC #'js2-parse-block)
7692 (aset parsers js2-LET #'js2-parse-let-stmt)
7693 (aset parsers js2-NAME #'js2-parse-name-or-label)
7694 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7695 (aset parsers js2-SEMI #'js2-parse-semi)
7696 (aset parsers js2-SWITCH #'js2-parse-switch)
7697 (aset parsers js2-THROW #'js2-parse-throw)
7698 (aset parsers js2-TRY #'js2-parse-try)
7699 (aset parsers js2-VAR #'js2-parse-const-var)
7700 (aset parsers js2-WHILE #'js2-parse-while)
7701 (aset parsers js2-WITH #'js2-parse-with)
7702 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7703 parsers)
7704 "A vector mapping token types to parser functions.")
7705
7706 (defsubst js2-parse-warn-missing-semi (beg end)
7707 (and js2-mode-show-strict-warnings
7708 js2-strict-missing-semi-warning
7709 (js2-add-strict-warning
7710 "msg.missing.semi" nil
7711 ;; back up to beginning of statement or line
7712 (max beg (save-excursion
7713 (goto-char end)
7714 (point-at-bol)))
7715 end)))
7716
7717 (defconst js2-no-semi-insertion
7718 (list js2-IF
7719 js2-SWITCH
7720 js2-WHILE
7721 js2-DO
7722 js2-FOR
7723 js2-TRY
7724 js2-WITH
7725 js2-LC
7726 js2-ERROR
7727 js2-SEMI
7728 js2-FUNCTION)
7729 "List of tokens that don't do automatic semicolon insertion.")
7730
7731 (defconst js2-autoinsert-semi-and-warn
7732 (list js2-ERROR js2-EOF js2-RC))
7733
7734 (defun js2-statement-helper ()
7735 (let* ((tt (js2-peek-token))
7736 (first-tt tt)
7737 (beg js2-token-beg)
7738 (parser (if (= tt js2-ERROR)
7739 #'js2-parse-semi
7740 (aref js2-parsers tt)))
7741 pn
7742 tt-flagged)
7743 ;; If the statement is set, then it's been told its label by now.
7744 (and js2-labeled-stmt
7745 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7746 (setq js2-labeled-stmt nil))
7747 (setq pn (funcall parser))
7748 ;; Don't do auto semi insertion for certain statement types.
7749 (unless (or (memq first-tt js2-no-semi-insertion)
7750 (js2-labeled-stmt-node-p pn))
7751 (js2-auto-insert-semicolon pn))
7752 pn))
7753
7754 (defun js2-auto-insert-semicolon (pn)
7755 (let* ((tt-flagged (js2-peek-flagged-token))
7756 (tt (logand tt-flagged js2-clear-ti-mask))
7757 (pos (js2-node-pos pn)))
7758 (cond
7759 ((= tt js2-SEMI)
7760 ;; Consume ';' as a part of expression
7761 (js2-consume-token)
7762 ;; extend the node bounds to include the semicolon.
7763 (setf (js2-node-len pn) (- js2-token-end pos)))
7764 ((memq tt js2-autoinsert-semi-and-warn)
7765 ;; Autoinsert ;
7766 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7767 (t
7768 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7769 ;; Report error if no EOL or autoinsert ';' otherwise
7770 (js2-report-error "msg.no.semi.stmt")
7771 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7772
7773 (defun js2-parse-condition ()
7774 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7775 The parens are discarded and the expression node is returned.
7776 The `pos' field of the return value is set to an absolute position
7777 that must be fixed up by the caller.
7778 Return value is a list (EXPR LP RP), with absolute paren positions."
7779 (let (pn lp rp)
7780 (if (js2-must-match js2-LP "msg.no.paren.cond")
7781 (setq lp js2-token-beg))
7782 (setq pn (js2-parse-expr))
7783 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7784 (setq rp js2-token-beg))
7785 ;; Report strict warning on code like "if (a = 7) ..."
7786 (if (and js2-strict-cond-assign-warning
7787 (js2-assign-node-p pn))
7788 (js2-add-strict-warning "msg.equal.as.assign" nil
7789 (js2-node-pos pn)
7790 (+ (js2-node-pos pn)
7791 (js2-node-len pn))))
7792 (list pn lp rp)))
7793
7794 (defun js2-parse-if ()
7795 "Parser for if-statement. Last matched token must be js2-IF."
7796 (let ((pos js2-token-beg)
7797 cond
7798 if-true
7799 if-false
7800 else-pos
7801 end
7802 pn)
7803 (js2-consume-token)
7804 (setq cond (js2-parse-condition)
7805 if-true (js2-parse-statement)
7806 if-false (if (js2-match-token js2-ELSE)
7807 (progn
7808 (setq else-pos (- js2-token-beg pos))
7809 (js2-parse-statement)))
7810 end (js2-node-end (or if-false if-true))
7811 pn (make-js2-if-node :pos pos
7812 :len (- end pos)
7813 :condition (car cond)
7814 :then-part if-true
7815 :else-part if-false
7816 :else-pos else-pos
7817 :lp (js2-relpos (second cond) pos)
7818 :rp (js2-relpos (third cond) pos)))
7819 (js2-node-add-children pn (car cond) if-true if-false)
7820 pn))
7821
7822 (defun js2-parse-switch ()
7823 "Parser for if-statement. Last matched token must be js2-SWITCH."
7824 (let ((pos js2-token-beg)
7825 tt
7826 pn
7827 discriminant
7828 has-default
7829 case-expr
7830 case-node
7831 case-pos
7832 cases
7833 stmt
7834 lp
7835 rp)
7836 (js2-consume-token)
7837 (if (js2-must-match js2-LP "msg.no.paren.switch")
7838 (setq lp js2-token-beg))
7839 (setq discriminant (js2-parse-expr)
7840 pn (make-js2-switch-node :discriminant discriminant
7841 :pos pos
7842 :lp (js2-relpos lp pos)))
7843 (js2-node-add-children pn discriminant)
7844 (js2-enter-switch pn)
7845 (unwind-protect
7846 (progn
7847 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7848 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7849 (js2-must-match js2-LC "msg.no.brace.switch")
7850 (catch 'break
7851 (while t
7852 (setq tt (js2-next-token)
7853 case-pos js2-token-beg)
7854 (cond
7855 ((= tt js2-RC)
7856 (setf (js2-node-len pn) (- js2-token-end pos))
7857 (throw 'break nil)) ; done
7858 ((= tt js2-CASE)
7859 (setq case-expr (js2-parse-expr))
7860 (js2-must-match js2-COLON "msg.no.colon.case"))
7861 ((= tt js2-DEFAULT)
7862 (if has-default
7863 (js2-report-error "msg.double.switch.default"))
7864 (setq has-default t
7865 case-expr nil)
7866 (js2-must-match js2-COLON "msg.no.colon.case"))
7867 (t
7868 (js2-report-error "msg.bad.switch")
7869 (throw 'break nil)))
7870 (setq case-node (make-js2-case-node :pos case-pos
7871 :len (- js2-token-end case-pos)
7872 :expr case-expr))
7873 (js2-node-add-children case-node case-expr)
7874 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7875 (/= tt js2-CASE)
7876 (/= tt js2-DEFAULT)
7877 (/= tt js2-EOF))
7878 (setf stmt (js2-parse-statement)
7879 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7880 (js2-block-node-push case-node stmt))
7881 (push case-node cases)))
7882 ;; add cases last, as pushing reverses the order to be correct
7883 (dolist (kid cases)
7884 (js2-node-add-children pn kid)
7885 (push kid (js2-switch-node-cases pn)))
7886 pn) ; return value
7887 (js2-exit-switch))))
7888
7889 (defun js2-parse-while ()
7890 "Parser for while-statement. Last matched token must be js2-WHILE."
7891 (let ((pos js2-token-beg)
7892 (pn (make-js2-while-node))
7893 cond
7894 body)
7895 (js2-consume-token)
7896 (js2-enter-loop pn)
7897 (unwind-protect
7898 (progn
7899 (setf cond (js2-parse-condition)
7900 (js2-while-node-condition pn) (car cond)
7901 body (js2-parse-statement)
7902 (js2-while-node-body pn) body
7903 (js2-node-len pn) (- (js2-node-end body) pos)
7904 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7905 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7906 (js2-node-add-children pn body (car cond)))
7907 (js2-exit-loop))
7908 pn))
7909
7910 (defun js2-parse-do ()
7911 "Parser for do-statement. Last matched token must be js2-DO."
7912 (let ((pos js2-token-beg)
7913 (pn (make-js2-do-node))
7914 cond
7915 body
7916 end)
7917 (js2-consume-token)
7918 (js2-enter-loop pn)
7919 (unwind-protect
7920 (progn
7921 (setq body (js2-parse-statement))
7922 (js2-must-match js2-WHILE "msg.no.while.do")
7923 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7924 cond (js2-parse-condition)
7925 (js2-do-node-condition pn) (car cond)
7926 (js2-do-node-body pn) body
7927 end js2-ts-cursor
7928 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7929 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7930 (js2-node-add-children pn (car cond) body))
7931 (js2-exit-loop))
7932 ;; Always auto-insert semicolon to follow SpiderMonkey:
7933 ;; It is required by ECMAScript but is ignored by the rest of
7934 ;; world; see bug 238945
7935 (if (js2-match-token js2-SEMI)
7936 (setq end js2-ts-cursor))
7937 (setf (js2-node-len pn) (- end pos))
7938 pn))
7939
7940 (defun js2-parse-for ()
7941 "Parser for for-statement. Last matched token must be js2-FOR.
7942 Parses for, for-in, and for each-in statements."
7943 (let ((for-pos js2-token-beg)
7944 pn is-for-each is-for-in-or-of is-for-of
7945 in-pos each-pos tmp-pos
7946 init ; Node init is also foo in 'foo in object'
7947 cond ; Node cond is also object in 'foo in object'
7948 incr ; 3rd section of for-loop initializer
7949 body tt lp rp)
7950 (js2-consume-token)
7951 ;; See if this is a for each () instead of just a for ()
7952 (when (js2-match-token js2-NAME)
7953 (if (string= "each" js2-ts-string)
7954 (progn
7955 (setq is-for-each t
7956 each-pos (- js2-token-beg for-pos)) ; relative
7957 (js2-record-face 'font-lock-keyword-face))
7958 (js2-report-error "msg.no.paren.for")))
7959 (if (js2-must-match js2-LP "msg.no.paren.for")
7960 (setq lp (- js2-token-beg for-pos)))
7961 (setq tt (js2-peek-token))
7962 ;; 'for' makes local scope
7963 (js2-push-scope (make-js2-scope))
7964 (unwind-protect
7965 ;; parse init clause
7966 (let ((js2-in-for-init t)) ; set as dynamic variable
7967 (cond
7968 ((= tt js2-SEMI)
7969 (setq init (make-js2-empty-expr-node)))
7970 ((or (= tt js2-VAR) (= tt js2-LET))
7971 (js2-consume-token)
7972 (setq init (js2-parse-variables tt js2-token-beg)))
7973 (t
7974 (setq init (js2-parse-expr)))))
7975 (if (or (js2-match-token js2-IN)
7976 (and (>= js2-language-version 200)
7977 (js2-match-contextual-kwd "of")
7978 (setq is-for-of t)))
7979 (setq is-for-in-or-of t
7980 in-pos (- js2-token-beg for-pos)
7981 ;; scope of iteration target object is not the scope we've created above.
7982 ;; stash current scope temporary.
7983 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7984 (js2-parse-expr))) ; object over which we're iterating
7985 ;; else ordinary for loop - parse cond and incr
7986 (js2-must-match js2-SEMI "msg.no.semi.for")
7987 (setq cond (if (= (js2-peek-token) js2-SEMI)
7988 (make-js2-empty-expr-node) ; no loop condition
7989 (js2-parse-expr)))
7990 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7991 (setq tmp-pos js2-token-end
7992 incr (if (= (js2-peek-token) js2-RP)
7993 (make-js2-empty-expr-node :pos tmp-pos)
7994 (js2-parse-expr))))
7995 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7996 (setq rp (- js2-token-beg for-pos)))
7997 (if (not is-for-in-or-of)
7998 (setq pn (make-js2-for-node :init init
7999 :condition cond
8000 :update incr
8001 :lp lp
8002 :rp rp))
8003 ;; cond could be null if 'in obj' got eaten by the init node.
8004 (if (js2-infix-node-p init)
8005 ;; it was (foo in bar) instead of (var foo in bar)
8006 (setq cond (js2-infix-node-right init)
8007 init (js2-infix-node-left init))
8008 (if (and (js2-var-decl-node-p init)
8009 (> (length (js2-var-decl-node-kids init)) 1))
8010 (js2-report-error "msg.mult.index")))
8011 (setq pn (make-js2-for-in-node :iterator init
8012 :object cond
8013 :in-pos in-pos
8014 :foreach-p is-for-each
8015 :each-pos each-pos
8016 :forof-p is-for-of
8017 :lp lp
8018 :rp rp)))
8019 (unwind-protect
8020 (progn
8021 (js2-enter-loop pn)
8022 ;; We have to parse the body -after- creating the loop node,
8023 ;; so that the loop node appears in the js2-loop-set, allowing
8024 ;; break/continue statements to find the enclosing loop.
8025 (setf body (js2-parse-statement)
8026 (js2-loop-node-body pn) body
8027 (js2-node-pos pn) for-pos
8028 (js2-node-len pn) (- (js2-node-end body) for-pos))
8029 (js2-node-add-children pn init cond incr body))
8030 ;; finally
8031 (js2-exit-loop))
8032 (js2-pop-scope))
8033 pn))
8034
8035 (defun js2-parse-try ()
8036 "Parser for try-statement. Last matched token must be js2-TRY."
8037 (let ((try-pos js2-token-beg)
8038 try-end
8039 try-block
8040 catch-blocks
8041 finally-block
8042 saw-default-catch
8043 peek
8044 param
8045 catch-cond
8046 catch-node
8047 guard-kwd
8048 catch-pos
8049 finally-pos
8050 pn
8051 block
8052 lp
8053 rp)
8054 (js2-consume-token)
8055 (if (/= (js2-peek-token) js2-LC)
8056 (js2-report-error "msg.no.brace.try"))
8057 (setq try-block (js2-parse-statement)
8058 try-end (js2-node-end try-block)
8059 peek (js2-peek-token))
8060 (cond
8061 ((= peek js2-CATCH)
8062 (while (js2-match-token js2-CATCH)
8063 (setq catch-pos js2-token-beg
8064 guard-kwd nil
8065 catch-cond nil
8066 lp nil
8067 rp nil)
8068 (if saw-default-catch
8069 (js2-report-error "msg.catch.unreachable"))
8070 (if (js2-must-match js2-LP "msg.no.paren.catch")
8071 (setq lp (- js2-token-beg catch-pos)))
8072 (js2-push-scope (make-js2-scope))
8073 (let ((tt (js2-peek-token)))
8074 (cond
8075 ;; destructuring pattern
8076 ;; catch ({ message, file }) { ... }
8077 ((or (= tt js2-LB) (= tt js2-LC))
8078 (setq param (js2-parse-destruct-primary-expr))
8079 (js2-define-destruct-symbols param js2-LET nil))
8080 ;; simple name
8081 (t
8082 (js2-must-match js2-NAME "msg.bad.catchcond")
8083 (setq param (js2-create-name-node))
8084 (js2-define-symbol js2-LET js2-ts-string param))))
8085 ;; pattern guard
8086 (if (js2-match-token js2-IF)
8087 (setq guard-kwd (- js2-token-beg catch-pos)
8088 catch-cond (js2-parse-expr))
8089 (setq saw-default-catch t))
8090 (if (js2-must-match js2-RP "msg.bad.catchcond")
8091 (setq rp (- js2-token-beg catch-pos)))
8092 (js2-must-match js2-LC "msg.no.brace.catchblock")
8093 (setq block (js2-parse-statements)
8094 try-end (js2-node-end block)
8095 catch-node (make-js2-catch-node :pos catch-pos
8096 :param param
8097 :guard-expr catch-cond
8098 :guard-kwd guard-kwd
8099 :block block
8100 :lp lp
8101 :rp rp))
8102 (js2-pop-scope)
8103 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8104 (setq try-end js2-token-beg))
8105 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8106 (js2-node-len catch-node) (- try-end catch-pos))
8107 (js2-node-add-children catch-node param catch-cond block)
8108 (push catch-node catch-blocks)))
8109 ((/= peek js2-FINALLY)
8110 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8111 (js2-node-pos try-block)
8112 (- (setq try-end (js2-node-end try-block))
8113 (js2-node-pos try-block)))))
8114 (when (js2-match-token js2-FINALLY)
8115 (setq finally-pos js2-token-beg
8116 block (js2-parse-statement)
8117 try-end (js2-node-end block)
8118 finally-block (make-js2-finally-node :pos finally-pos
8119 :len (- try-end finally-pos)
8120 :body block))
8121 (js2-node-add-children finally-block block))
8122 (setq pn (make-js2-try-node :pos try-pos
8123 :len (- try-end try-pos)
8124 :try-block try-block
8125 :finally-block finally-block))
8126 (js2-node-add-children pn try-block finally-block)
8127 ;; push them onto the try-node, which reverses and corrects their order
8128 (dolist (cb catch-blocks)
8129 (js2-node-add-children pn cb)
8130 (push cb (js2-try-node-catch-clauses pn)))
8131 pn))
8132
8133 (defun js2-parse-throw ()
8134 "Parser for throw-statement. Last matched token must be js2-THROW."
8135 (let ((pos js2-token-beg)
8136 expr
8137 pn)
8138 (js2-consume-token)
8139 (if (= (js2-peek-token-or-eol) js2-EOL)
8140 ;; ECMAScript does not allow new lines before throw expression,
8141 ;; see bug 256617
8142 (js2-report-error "msg.bad.throw.eol"))
8143 (setq expr (js2-parse-expr)
8144 pn (make-js2-throw-node :pos pos
8145 :len (- (js2-node-end expr) pos)
8146 :expr expr))
8147 (js2-node-add-children pn expr)
8148 pn))
8149
8150 (defsubst js2-match-jump-label-name (label-name)
8151 "If break/continue specified a label, return that label's labeled stmt.
8152 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8153 does not match an existing label, reports an error and returns nil."
8154 (let ((bundle (cdr (assoc label-name js2-label-set))))
8155 (if (null bundle)
8156 (js2-report-error "msg.undef.label"))
8157 bundle))
8158
8159 (defun js2-parse-break ()
8160 "Parser for break-statement. Last matched token must be js2-BREAK."
8161 (let ((pos js2-token-beg)
8162 (end js2-token-end)
8163 break-target ; statement to break from
8164 break-label ; in "break foo", name-node representing the foo
8165 labels ; matching labeled statement to break to
8166 pn)
8167 (js2-consume-token) ; `break'
8168 (when (eq (js2-peek-token-or-eol) js2-NAME)
8169 (js2-consume-token)
8170 (setq break-label (js2-create-name-node)
8171 end (js2-node-end break-label)
8172 ;; matchJumpLabelName only matches if there is one
8173 labels (js2-match-jump-label-name js2-ts-string)
8174 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8175 (unless (or break-target break-label)
8176 ;; no break target specified - try for innermost enclosing loop/switch
8177 (if (null js2-loop-and-switch-set)
8178 (unless break-label
8179 (js2-report-error "msg.bad.break" nil pos (length "break")))
8180 (setq break-target (car js2-loop-and-switch-set))))
8181 (setq pn (make-js2-break-node :pos pos
8182 :len (- end pos)
8183 :label break-label
8184 :target break-target))
8185 (js2-node-add-children pn break-label) ; but not break-target
8186 pn))
8187
8188 (defun js2-parse-continue ()
8189 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8190 (let ((pos js2-token-beg)
8191 (end js2-token-end)
8192 label ; optional user-specified label, a `js2-name-node'
8193 labels ; current matching labeled stmt, if any
8194 target ; the `js2-loop-node' target of this continue stmt
8195 pn)
8196 (js2-consume-token) ; `continue'
8197 (when (= (js2-peek-token-or-eol) js2-NAME)
8198 (js2-consume-token)
8199 (setq label (js2-create-name-node)
8200 end (js2-node-end label)
8201 ;; matchJumpLabelName only matches if there is one
8202 labels (js2-match-jump-label-name js2-ts-string)))
8203 (cond
8204 ((null labels) ; no current label to go to
8205 (if (null js2-loop-set) ; no loop to continue to
8206 (js2-report-error "msg.continue.outside" nil pos
8207 (length "continue"))
8208 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8209 (t
8210 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8211 (setq target (js2-labeled-stmt-node-stmt labels))
8212 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8213 (setq pn (make-js2-continue-node :pos pos
8214 :len (- end pos)
8215 :label label
8216 :target target))
8217 (js2-node-add-children pn label) ; but not target - it's not our child
8218 pn))
8219
8220 (defun js2-parse-with ()
8221 "Parser for with-statement. Last matched token must be js2-WITH."
8222 (js2-consume-token)
8223 (let ((pos js2-token-beg)
8224 obj body pn lp rp)
8225 (if (js2-must-match js2-LP "msg.no.paren.with")
8226 (setq lp js2-token-beg))
8227 (setq obj (js2-parse-expr))
8228 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8229 (setq rp js2-token-beg))
8230 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8231 (setq body (js2-parse-statement)))
8232 (setq pn (make-js2-with-node :pos pos
8233 :len (- (js2-node-end body) pos)
8234 :object obj
8235 :body body
8236 :lp (js2-relpos lp pos)
8237 :rp (js2-relpos rp pos)))
8238 (js2-node-add-children pn obj body)
8239 pn))
8240
8241 (defun js2-parse-const-var ()
8242 "Parser for var- or const-statement.
8243 Last matched token must be js2-CONST or js2-VAR."
8244 (let ((tt (js2-peek-token))
8245 (pos js2-token-beg)
8246 expr
8247 pn)
8248 (js2-consume-token)
8249 (setq expr (js2-parse-variables tt js2-token-beg)
8250 pn (make-js2-expr-stmt-node :pos pos
8251 :len (- (js2-node-end expr) pos)
8252 :expr expr))
8253 (js2-node-add-children pn expr)
8254 pn))
8255
8256 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8257 (let ((pn (make-js2-expr-stmt-node :pos pos
8258 :len (js2-node-len expr)
8259 :type (if (js2-inside-function)
8260 js2-EXPR_VOID
8261 js2-EXPR_RESULT)
8262 :expr expr)))
8263 (if add-child
8264 (js2-node-add-children pn expr))
8265 pn))
8266
8267 (defun js2-parse-let-stmt ()
8268 "Parser for let-statement. Last matched token must be js2-LET."
8269 (js2-consume-token)
8270 (let ((pos js2-token-beg)
8271 expr
8272 pn)
8273 (if (= (js2-peek-token) js2-LP)
8274 ;; let expression in statement context
8275 (setq expr (js2-parse-let pos 'statement)
8276 pn (js2-wrap-with-expr-stmt pos expr t))
8277 ;; else we're looking at a statement like let x=6, y=7;
8278 (setf expr (js2-parse-variables js2-LET pos)
8279 pn (js2-wrap-with-expr-stmt pos expr t)
8280 (js2-node-type pn) js2-EXPR_RESULT))
8281 pn))
8282
8283 (defun js2-parse-ret-yield ()
8284 (js2-parse-return-or-yield (js2-peek-token) nil))
8285
8286 (defconst js2-parse-return-stmt-enders
8287 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8288
8289 (defsubst js2-now-all-set (before after mask)
8290 "Return whether or not the bits in the mask have changed to all set.
8291 BEFORE is bits before change, AFTER is bits after change, and MASK is
8292 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8293 but not BEFORE."
8294 (and (/= (logand before mask) mask)
8295 (= (logand after mask) mask)))
8296
8297 (defun js2-parse-return-or-yield (tt expr-context)
8298 (let ((pos js2-token-beg)
8299 (end js2-token-end)
8300 (before js2-end-flags)
8301 (inside-function (js2-inside-function))
8302 e
8303 ret
8304 name)
8305 (unless inside-function
8306 (js2-report-error (if (eq tt js2-RETURN)
8307 "msg.bad.return"
8308 "msg.bad.yield")))
8309 (js2-consume-token)
8310 ;; This is ugly, but we don't want to require a semicolon.
8311 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8312 (setq e (js2-parse-expr)
8313 end (js2-node-end e)))
8314 (cond
8315 ((eq tt js2-RETURN)
8316 (js2-set-flag js2-end-flags (if (null e)
8317 js2-end-returns
8318 js2-end-returns-value))
8319 (setq ret (make-js2-return-node :pos pos
8320 :len (- end pos)
8321 :retval e))
8322 (js2-node-add-children ret e)
8323 ;; See if we need a strict mode warning.
8324 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8325 ;; more thorough and accurate than this before/after flag check.
8326 ;; E.g. if there's a finally-block that always returns, we shouldn't
8327 ;; show a warning generated by inconsistent returns in the catch blocks.
8328 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8329 ;; so we know which returns/yields to highlight, and we should get rid of
8330 ;; all the checking in `js2-parse-return-or-yield'.
8331 (if (and js2-strict-inconsistent-return-warning
8332 (js2-now-all-set before js2-end-flags
8333 (logior js2-end-returns js2-end-returns-value)))
8334 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8335 (t
8336 (unless (js2-inside-function)
8337 (js2-report-error "msg.bad.yield"))
8338 (js2-set-flag js2-end-flags js2-end-yields)
8339 (setq ret (make-js2-yield-node :pos pos
8340 :len (- end pos)
8341 :value e))
8342 (js2-node-add-children ret e)
8343 (unless expr-context
8344 (setq e ret
8345 ret (js2-wrap-with-expr-stmt pos e t))
8346 (js2-set-requires-activation)
8347 (js2-set-is-generator))))
8348 ;; see if we are mixing yields and value returns.
8349 (when (and inside-function
8350 (js2-now-all-set before js2-end-flags
8351 (logior js2-end-yields js2-end-returns-value)))
8352 (setq name (js2-function-name js2-current-script-or-fn))
8353 (if (zerop (length name))
8354 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8355 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8356 ret))
8357
8358 (defun js2-parse-debugger ()
8359 (js2-consume-token)
8360 (make-js2-keyword-node :type js2-DEBUGGER))
8361
8362 (defun js2-parse-block ()
8363 "Parser for a curly-delimited statement block.
8364 Last token matched must be js2-LC."
8365 (let ((pos js2-token-beg)
8366 (pn (make-js2-scope)))
8367 (js2-consume-token)
8368 (js2-push-scope pn)
8369 (unwind-protect
8370 (progn
8371 (js2-parse-statements pn)
8372 (js2-must-match js2-RC "msg.no.brace.block")
8373 (setf (js2-node-len pn) (- js2-token-end pos)))
8374 (js2-pop-scope))
8375 pn))
8376
8377 ;; for js2-ERROR too, to have a node for error recovery to work on
8378 (defun js2-parse-semi ()
8379 "Parse a statement or handle an error.
8380 Last matched token is js2-SEMI or js2-ERROR."
8381 (let ((tt (js2-peek-token)) pos len)
8382 (js2-consume-token)
8383 (if (eq tt js2-SEMI)
8384 (make-js2-empty-expr-node :len 1)
8385 (setq pos js2-token-beg
8386 len (- js2-token-beg pos))
8387 (js2-report-error "msg.syntax" nil pos len)
8388 (make-js2-error-node :pos pos :len len))))
8389
8390 (defun js2-parse-default-xml-namespace ()
8391 "Parse a `default xml namespace = <expr>' e4x statement."
8392 (let ((pos js2-token-beg)
8393 end len expr unary es)
8394 (js2-consume-token)
8395 (js2-must-have-xml)
8396 (js2-set-requires-activation)
8397 (setq len (- js2-ts-cursor pos))
8398 (unless (and (js2-match-token js2-NAME)
8399 (string= js2-ts-string "xml"))
8400 (js2-report-error "msg.bad.namespace" nil pos len))
8401 (unless (and (js2-match-token js2-NAME)
8402 (string= js2-ts-string "namespace"))
8403 (js2-report-error "msg.bad.namespace" nil pos len))
8404 (unless (js2-match-token js2-ASSIGN)
8405 (js2-report-error "msg.bad.namespace" nil pos len))
8406 (setq expr (js2-parse-expr)
8407 end (js2-node-end expr)
8408 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8409 :pos pos
8410 :len (- end pos)
8411 :operand expr))
8412 (js2-node-add-children unary expr)
8413 (make-js2-expr-stmt-node :pos pos
8414 :len (- end pos)
8415 :expr unary)))
8416
8417 (defun js2-record-label (label bundle)
8418 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8419 (js2-consume-token)
8420 (let ((name (js2-label-node-name label))
8421 labeled-stmt
8422 dup)
8423 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8424 ;; flag both labels if possible when used in editing mode
8425 (if (and js2-parse-ide-mode
8426 (setq dup (js2-get-label-by-name labeled-stmt name)))
8427 (js2-report-error "msg.dup.label" nil
8428 (js2-node-abs-pos dup) (js2-node-len dup)))
8429 (js2-report-error "msg.dup.label" nil
8430 (js2-node-pos label) (js2-node-len label)))
8431 (js2-labeled-stmt-node-add-label bundle label)
8432 (js2-node-add-children bundle label)
8433 ;; Add one reference to the bundle per label in `js2-label-set'
8434 (push (cons name bundle) js2-label-set)))
8435
8436 (defun js2-parse-name-or-label ()
8437 "Parser for identifier or label. Last token matched must be js2-NAME.
8438 Called when we found a name in a statement context. If it's a label, we gather
8439 up any following labels and the next non-label statement into a
8440 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8441 expression and return it wrapped in a `js2-expr-stmt-node'."
8442 (let ((pos js2-token-beg)
8443 (end js2-token-end)
8444 expr
8445 stmt
8446 pn
8447 bundle
8448 (continue t))
8449 ;; set check for label and call down to `js2-parse-primary-expr'
8450 (js2-set-check-for-label)
8451 (setq expr (js2-parse-expr))
8452 (if (/= (js2-node-type expr) js2-LABEL)
8453 ;; Parsed non-label expression - wrap with expression stmt.
8454 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8455 ;; else parsed a label
8456 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8457 (js2-record-label expr bundle)
8458 ;; look for more labels
8459 (while (and continue (= (js2-peek-token) js2-NAME))
8460 (js2-set-check-for-label)
8461 (setq expr (js2-parse-expr))
8462 (if (/= (js2-node-type expr) js2-LABEL)
8463 (progn
8464 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8465 continue nil)
8466 (js2-auto-insert-semicolon stmt))
8467 (js2-record-label expr bundle)))
8468 ;; no more labels; now parse the labeled statement
8469 (unwind-protect
8470 (unless stmt
8471 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8472 (setq stmt (js2-statement-helper))))
8473 ;; remove the labels for this statement from the global set
8474 (dolist (label (js2-labeled-stmt-node-labels bundle))
8475 (setq js2-label-set (remove label js2-label-set))))
8476 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8477 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8478 (js2-node-add-children bundle stmt)
8479 bundle)))
8480
8481 (defun js2-parse-expr-stmt ()
8482 "Default parser in statement context, if no recognized statement found."
8483 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8484
8485 (defun js2-parse-variables (decl-type pos)
8486 "Parse a comma-separated list of variable declarations.
8487 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8488
8489 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8490 For 'var' or 'const', the keyword should be the token last scanned.
8491
8492 POS is the position where the node should start. It's sometimes the
8493 var/const/let keyword, and other times the beginning of the first token
8494 in the first variable declaration.
8495
8496 Returns the parsed `js2-var-decl-node' expression node."
8497 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8498 :pos pos))
8499 destructuring
8500 kid-pos
8501 tt
8502 init
8503 name
8504 end
8505 nbeg nend
8506 vi
8507 (continue t))
8508 ;; Example:
8509 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8510 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8511 ;; var {a, b} = baz;
8512 (while continue
8513 (setq destructuring nil
8514 name nil
8515 tt (js2-peek-token)
8516 kid-pos js2-token-beg
8517 end js2-token-end
8518 init nil)
8519 (if (or (= tt js2-LB) (= tt js2-LC))
8520 ;; Destructuring assignment, e.g., var [a, b] = ...
8521 (setq destructuring (js2-parse-destruct-primary-expr)
8522 end (js2-node-end destructuring))
8523 ;; Simple variable name
8524 (when (js2-must-match js2-NAME "msg.bad.var")
8525 (setq name (js2-create-name-node)
8526 nbeg js2-token-beg
8527 nend js2-token-end
8528 end nend)
8529 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8530 (when (js2-match-token js2-ASSIGN)
8531 (setq init (js2-parse-assign-expr)
8532 end (js2-node-end init))
8533 (js2-record-imenu-functions init name))
8534 (when name
8535 (js2-set-face nbeg nend (if (js2-function-node-p init)
8536 'font-lock-function-name-face
8537 'font-lock-variable-name-face)
8538 'record))
8539 (setq vi (make-js2-var-init-node :pos kid-pos
8540 :len (- end kid-pos)
8541 :type decl-type))
8542 (if destructuring
8543 (progn
8544 (if (and (null init) (not js2-in-for-init))
8545 (js2-report-error "msg.destruct.assign.no.init"))
8546 (js2-define-destruct-symbols destructuring
8547 decl-type
8548 'font-lock-variable-name-face)
8549 (setf (js2-var-init-node-target vi) destructuring))
8550 (setf (js2-var-init-node-target vi) name))
8551 (setf (js2-var-init-node-initializer vi) init)
8552 (js2-node-add-children vi name destructuring init)
8553 (js2-block-node-push result vi)
8554 (unless (js2-match-token js2-COMMA)
8555 (setq continue nil)))
8556 (setf (js2-node-len result) (- end pos))
8557 result))
8558
8559 (defun js2-parse-let (pos &optional stmt-p)
8560 "Parse a let expression or statement.
8561 A let-expression is of the form `let (vars) expr'.
8562 A let-statment is of the form `let (vars) {statements}'.
8563 The third form of let is a variable declaration list, handled
8564 by `js2-parse-variables'."
8565 (let ((pn (make-js2-let-node :pos pos))
8566 beg vars body)
8567 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8568 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8569 (js2-push-scope pn)
8570 (unwind-protect
8571 (progn
8572 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8573 (if (js2-must-match js2-RP "msg.no.paren.let")
8574 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8575 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8576 ;; let statement
8577 (progn
8578 (js2-consume-token)
8579 (setf beg js2-token-beg ; position stmt at LC
8580 body (js2-parse-statements))
8581 (js2-must-match js2-RC "msg.no.curly.let")
8582 (setf (js2-node-len body) (- js2-token-end beg)
8583 (js2-node-len pn) (- js2-token-end pos)
8584 (js2-let-node-body pn) body
8585 (js2-node-type pn) js2-LET))
8586 ;; let expression
8587 (setf body (js2-parse-expr)
8588 (js2-node-len pn) (- (js2-node-end body) pos)
8589 (js2-let-node-body pn) body))
8590 (js2-node-add-children pn vars body))
8591 (js2-pop-scope))
8592 pn))
8593
8594 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8595 (js2-scope-put-symbol (or scope js2-current-scope)
8596 name
8597 (make-js2-symbol decl-type name node)))
8598
8599 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8600 "Define a symbol in the current scope.
8601 If NODE is non-nil, it is the AST node associated with the symbol."
8602 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8603 (symbol (if defining-scope
8604 (js2-scope-get-symbol defining-scope name)))
8605 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8606 (cond
8607 ((and symbol ; already defined
8608 (or (= sdt js2-CONST) ; old version is const
8609 (= decl-type js2-CONST) ; new version is const
8610 ;; two let-bound vars in this block have same name
8611 (and (= sdt js2-LET)
8612 (eq defining-scope js2-current-scope))))
8613 (js2-report-error
8614 (cond
8615 ((= sdt js2-CONST) "msg.const.redecl")
8616 ((= sdt js2-LET) "msg.let.redecl")
8617 ((= sdt js2-VAR) "msg.var.redecl")
8618 ((= sdt js2-FUNCTION) "msg.function.redecl")
8619 (t "msg.parm.redecl"))
8620 name))
8621 ((= decl-type js2-LET)
8622 (if (and (not ignore-not-in-block)
8623 (or (= (js2-node-type js2-current-scope) js2-IF)
8624 (js2-loop-node-p js2-current-scope)))
8625 (js2-report-error "msg.let.decl.not.in.block")
8626 (js2-define-new-symbol decl-type name node)))
8627 ((or (= decl-type js2-VAR)
8628 (= decl-type js2-CONST)
8629 (= decl-type js2-FUNCTION))
8630 (if symbol
8631 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8632 (js2-add-strict-warning "msg.var.redecl" name)
8633 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8634 (js2-add-strict-warning "msg.var.hides.arg" name)))
8635 (js2-define-new-symbol decl-type name node
8636 js2-current-script-or-fn)))
8637 ((= decl-type js2-LP)
8638 (if symbol
8639 ;; must be duplicate parameter. Second parameter hides the
8640 ;; first, so go ahead and add the second pararameter
8641 (js2-report-warning "msg.dup.parms" name))
8642 (js2-define-new-symbol decl-type name node))
8643 (t (js2-code-bug)))))
8644
8645 (defun js2-parse-expr (&optional oneshot)
8646 (let* ((pn (js2-parse-assign-expr))
8647 (pos (js2-node-pos pn))
8648 left
8649 right
8650 op-pos)
8651 (while (and (not oneshot)
8652 (js2-match-token js2-COMMA))
8653 (setq op-pos (- js2-token-beg pos)) ; relative
8654 (if (= (js2-peek-token) js2-YIELD)
8655 (js2-report-error "msg.yield.parenthesized"))
8656 (setq right (js2-parse-assign-expr)
8657 left pn
8658 pn (make-js2-infix-node :type js2-COMMA
8659 :pos pos
8660 :len (- js2-ts-cursor pos)
8661 :op-pos op-pos
8662 :left left
8663 :right right))
8664 (js2-node-add-children pn left right))
8665 pn))
8666
8667 (defun js2-parse-assign-expr ()
8668 (let ((tt (js2-peek-token))
8669 (pos js2-token-beg)
8670 pn
8671 left
8672 right
8673 op-pos)
8674 (if (= tt js2-YIELD)
8675 (js2-parse-return-or-yield tt t)
8676 ;; not yield - parse assignment expression
8677 (setq pn (js2-parse-cond-expr)
8678 tt (js2-peek-token))
8679 (when (and (<= js2-first-assign tt)
8680 (<= tt js2-last-assign))
8681 ;; tt express assignment (=, |=, ^=, ..., %=)
8682 (js2-consume-token)
8683 (setq op-pos (- js2-token-beg pos) ; relative
8684 left pn
8685 right (js2-parse-assign-expr)
8686 pn (make-js2-assign-node :type tt
8687 :pos pos
8688 :len (- (js2-node-end right) pos)
8689 :op-pos op-pos
8690 :left left
8691 :right right))
8692 (when js2-parse-ide-mode
8693 (js2-highlight-assign-targets pn left right)
8694 (js2-record-imenu-functions right left))
8695 ;; do this last so ide checks above can use absolute positions
8696 (js2-node-add-children pn left right))
8697 pn)))
8698
8699 (defun js2-parse-cond-expr ()
8700 (let ((pos js2-token-beg)
8701 (pn (js2-parse-or-expr))
8702 test-expr
8703 if-true
8704 if-false
8705 q-pos
8706 c-pos)
8707 (when (js2-match-token js2-HOOK)
8708 (setq q-pos (- js2-token-beg pos)
8709 if-true (js2-parse-assign-expr))
8710 (js2-must-match js2-COLON "msg.no.colon.cond")
8711 (setq c-pos (- js2-token-beg pos)
8712 if-false (js2-parse-assign-expr)
8713 test-expr pn
8714 pn (make-js2-cond-node :pos pos
8715 :len (- (js2-node-end if-false) pos)
8716 :test-expr test-expr
8717 :true-expr if-true
8718 :false-expr if-false
8719 :q-pos q-pos
8720 :c-pos c-pos))
8721 (js2-node-add-children pn test-expr if-true if-false))
8722 pn))
8723
8724 (defun js2-make-binary (type left parser)
8725 "Helper for constructing a binary-operator AST node.
8726 LEFT is the left-side-expression, already parsed, and the
8727 binary operator should have just been matched.
8728 PARSER is a function to call to parse the right operand,
8729 or a `js2-node' struct if it has already been parsed."
8730 (let* ((pos (js2-node-pos left))
8731 (op-pos (- js2-token-beg pos))
8732 (right (if (js2-node-p parser)
8733 parser
8734 (funcall parser)))
8735 (pn (make-js2-infix-node :type type
8736 :pos pos
8737 :len (- (js2-node-end right) pos)
8738 :op-pos op-pos
8739 :left left
8740 :right right)))
8741 (js2-node-add-children pn left right)
8742 pn))
8743
8744 (defun js2-parse-or-expr ()
8745 (let ((pn (js2-parse-and-expr)))
8746 (when (js2-match-token js2-OR)
8747 (setq pn (js2-make-binary js2-OR
8748 pn
8749 'js2-parse-or-expr)))
8750 pn))
8751
8752 (defun js2-parse-and-expr ()
8753 (let ((pn (js2-parse-bit-or-expr)))
8754 (when (js2-match-token js2-AND)
8755 (setq pn (js2-make-binary js2-AND
8756 pn
8757 'js2-parse-and-expr)))
8758 pn))
8759
8760 (defun js2-parse-bit-or-expr ()
8761 (let ((pn (js2-parse-bit-xor-expr)))
8762 (while (js2-match-token js2-BITOR)
8763 (setq pn (js2-make-binary js2-BITOR
8764 pn
8765 'js2-parse-bit-xor-expr)))
8766 pn))
8767
8768 (defun js2-parse-bit-xor-expr ()
8769 (let ((pn (js2-parse-bit-and-expr)))
8770 (while (js2-match-token js2-BITXOR)
8771 (setq pn (js2-make-binary js2-BITXOR
8772 pn
8773 'js2-parse-bit-and-expr)))
8774 pn))
8775
8776 (defun js2-parse-bit-and-expr ()
8777 (let ((pn (js2-parse-eq-expr)))
8778 (while (js2-match-token js2-BITAND)
8779 (setq pn (js2-make-binary js2-BITAND
8780 pn
8781 'js2-parse-eq-expr)))
8782 pn))
8783
8784 (defconst js2-parse-eq-ops
8785 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8786
8787 (defun js2-parse-eq-expr ()
8788 (let ((pn (js2-parse-rel-expr))
8789 tt)
8790 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8791 (js2-consume-token)
8792 (setq pn (js2-make-binary tt
8793 pn
8794 'js2-parse-rel-expr)))
8795 pn))
8796
8797 (defconst js2-parse-rel-ops
8798 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8799
8800 (defun js2-parse-rel-expr ()
8801 (let ((pn (js2-parse-shift-expr))
8802 (continue t)
8803 tt)
8804 (while continue
8805 (setq tt (js2-peek-token))
8806 (cond
8807 ((and js2-in-for-init (= tt js2-IN))
8808 (setq continue nil))
8809 ((memq tt js2-parse-rel-ops)
8810 (js2-consume-token)
8811 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8812 (t
8813 (setq continue nil))))
8814 pn))
8815
8816 (defconst js2-parse-shift-ops
8817 (list js2-LSH js2-URSH js2-RSH))
8818
8819 (defun js2-parse-shift-expr ()
8820 (let ((pn (js2-parse-add-expr))
8821 tt
8822 (continue t))
8823 (while continue
8824 (setq tt (js2-peek-token))
8825 (if (memq tt js2-parse-shift-ops)
8826 (progn
8827 (js2-consume-token)
8828 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8829 (setq continue nil)))
8830 pn))
8831
8832 (defun js2-parse-add-expr ()
8833 (let ((pn (js2-parse-mul-expr))
8834 tt
8835 (continue t))
8836 (while continue
8837 (setq tt (js2-peek-token))
8838 (if (or (= tt js2-ADD) (= tt js2-SUB))
8839 (progn
8840 (js2-consume-token)
8841 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8842 (setq continue nil)))
8843 pn))
8844
8845 (defconst js2-parse-mul-ops
8846 (list js2-MUL js2-DIV js2-MOD))
8847
8848 (defun js2-parse-mul-expr ()
8849 (let ((pn (js2-parse-unary-expr))
8850 tt
8851 (continue t))
8852 (while continue
8853 (setq tt (js2-peek-token))
8854 (if (memq tt js2-parse-mul-ops)
8855 (progn
8856 (js2-consume-token)
8857 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8858 (setq continue nil)))
8859 pn))
8860
8861 (defsubst js2-make-unary (type parser &rest args)
8862 "Make a unary node of type TYPE.
8863 PARSER is either a node (for postfix operators) or a function to call
8864 to parse the operand (for prefix operators)."
8865 (let* ((pos js2-token-beg)
8866 (postfix (js2-node-p parser))
8867 (expr (if postfix
8868 parser
8869 (apply parser args)))
8870 end
8871 pn)
8872 (if postfix ; e.g. i++
8873 (setq pos (js2-node-pos expr)
8874 end js2-token-end)
8875 (setq end (js2-node-end expr)))
8876 (setq pn (make-js2-unary-node :type type
8877 :pos pos
8878 :len (- end pos)
8879 :operand expr))
8880 (js2-node-add-children pn expr)
8881 pn))
8882
8883 (defconst js2-incrementable-node-types
8884 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8885 "Node types that can be the operand of a ++ or -- operator.")
8886
8887 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8888 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8889 js2-incrementable-node-types)
8890 (js2-report-error (if (= tt js2-INC)
8891 "msg.bad.incr"
8892 "msg.bad.decr")
8893 nil beg (- end beg))))
8894
8895 (defun js2-parse-unary-expr ()
8896 (let ((tt (js2-peek-token))
8897 pn expr beg end)
8898 (cond
8899 ((or (= tt js2-VOID)
8900 (= tt js2-NOT)
8901 (= tt js2-BITNOT)
8902 (= tt js2-TYPEOF))
8903 (js2-consume-token)
8904 (js2-make-unary tt 'js2-parse-unary-expr))
8905 ((= tt js2-ADD)
8906 (js2-consume-token)
8907 ;; Convert to special POS token in decompiler and parse tree
8908 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8909 ((= tt js2-SUB)
8910 (js2-consume-token)
8911 ;; Convert to special NEG token in decompiler and parse tree
8912 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8913 ((or (= tt js2-INC)
8914 (= tt js2-DEC))
8915 (js2-consume-token)
8916 (prog1
8917 (setq beg js2-token-beg
8918 end js2-token-end
8919 expr (js2-make-unary tt 'js2-parse-member-expr t))
8920 (js2-check-bad-inc-dec tt beg end expr)))
8921 ((= tt js2-DELPROP)
8922 (js2-consume-token)
8923 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8924 ((= tt js2-ERROR)
8925 (js2-consume-token)
8926 (make-js2-error-node)) ; try to continue
8927 ((and (= tt js2-LT)
8928 js2-compiler-xml-available)
8929 ;; XML stream encountered in expression.
8930 (js2-consume-token)
8931 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8932 (t
8933 (setq pn (js2-parse-member-expr t)
8934 ;; Don't look across a newline boundary for a postfix incop.
8935 tt (js2-peek-token-or-eol))
8936 (when (or (= tt js2-INC) (= tt js2-DEC))
8937 (js2-consume-token)
8938 (setf expr pn
8939 pn (js2-make-unary tt expr))
8940 (js2-node-set-prop pn 'postfix t)
8941 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8942 pn))))
8943
8944 (defun js2-parse-xml-initializer ()
8945 "Parse an E4X XML initializer.
8946 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8947 Then I'll postprocess the result, depending on whether we're in IDE
8948 mode or codegen mode, and generate the appropriate rewritten AST.
8949 IDE mode uses a rich AST that models the XML structure. Codegen mode
8950 just concatenates everything and makes a new XML or XMLList out of it."
8951 (let ((tt (js2-get-first-xml-token))
8952 pn-xml
8953 pn
8954 expr
8955 kids
8956 expr-pos
8957 (continue t)
8958 (first-token t))
8959 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8960 (js2-report-error "msg.syntax"))
8961 (setq pn-xml (make-js2-xml-node))
8962 (while continue
8963 (if first-token
8964 (setq first-token nil)
8965 (setq tt (js2-get-next-xml-token)))
8966 (cond
8967 ;; js2-XML means we found a {expr} in the XML stream.
8968 ;; The js2-ts-string is the XML up to the left-curly.
8969 ((= tt js2-XML)
8970 (push (make-js2-string-node :pos js2-token-beg
8971 :len (- js2-ts-cursor js2-token-beg))
8972 kids)
8973 (js2-must-match js2-LC "msg.syntax")
8974 (setq expr-pos js2-ts-cursor
8975 expr (if (eq (js2-peek-token) js2-RC)
8976 (make-js2-empty-expr-node :pos expr-pos)
8977 (js2-parse-expr)))
8978 (js2-must-match js2-RC "msg.syntax")
8979 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8980 :len (js2-node-len expr)
8981 :expr expr))
8982 (js2-node-add-children pn expr)
8983 (push pn kids))
8984 ;; a js2-XMLEND token means we hit the final close-tag.
8985 ((= tt js2-XMLEND)
8986 (push (make-js2-string-node :pos js2-token-beg
8987 :len (- js2-ts-cursor js2-token-beg))
8988 kids)
8989 (dolist (kid (nreverse kids))
8990 (js2-block-node-push pn-xml kid))
8991 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8992 (js2-node-pos pn-xml))
8993 continue nil))
8994 (t
8995 (js2-report-error "msg.syntax")
8996 (setq continue nil))))
8997 pn-xml))
8998
8999
9000 (defun js2-parse-argument-list ()
9001 "Parse an argument list and return it as a lisp list of nodes.
9002 Returns the list in reverse order. Consumes the right-paren token."
9003 (let (result)
9004 (unless (js2-match-token js2-RP)
9005 (loop do
9006 (if (= (js2-peek-token) js2-YIELD)
9007 (js2-report-error "msg.yield.parenthesized"))
9008 (push (js2-parse-assign-expr) result)
9009 while
9010 (js2-match-token js2-COMMA))
9011 (js2-must-match js2-RP "msg.no.paren.arg")
9012 result)))
9013
9014 (defun js2-parse-member-expr (&optional allow-call-syntax)
9015 (let ((tt (js2-peek-token))
9016 pn
9017 pos
9018 target
9019 args
9020 beg
9021 end
9022 init
9023 tail)
9024 (if (/= tt js2-NEW)
9025 (setq pn (js2-parse-primary-expr))
9026 ;; parse a 'new' expression
9027 (js2-consume-token)
9028 (setq pos js2-token-beg
9029 beg pos
9030 target (js2-parse-member-expr)
9031 end (js2-node-end target)
9032 pn (make-js2-new-node :pos pos
9033 :target target
9034 :len (- end pos)))
9035 (js2-node-add-children pn target)
9036 (when (js2-match-token js2-LP)
9037 ;; Add the arguments to pn, if any are supplied.
9038 (setf beg pos ; start of "new" keyword
9039 pos js2-token-beg
9040 args (nreverse (js2-parse-argument-list))
9041 (js2-new-node-args pn) args
9042 end js2-token-end
9043 (js2-new-node-lp pn) (- pos beg)
9044 (js2-new-node-rp pn) (- end 1 beg))
9045 (apply #'js2-node-add-children pn args))
9046 (when (and js2-allow-rhino-new-expr-initializer
9047 (js2-match-token js2-LC))
9048 (setf init (js2-parse-object-literal)
9049 end (js2-node-end init)
9050 (js2-new-node-initializer pn) init)
9051 (js2-node-add-children pn init))
9052 (setf (js2-node-len pn) (- end beg))) ; end outer if
9053 (js2-parse-member-expr-tail allow-call-syntax pn)))
9054
9055 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9056 "Parse a chain of property/array accesses or function calls.
9057 Includes parsing for E4X operators like `..' and `.@'.
9058 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9059 Returns an expression tree that includes PN, the parent node."
9060 (let ((beg (js2-node-pos pn))
9061 tt
9062 (continue t))
9063 (while continue
9064 (setq tt (js2-peek-token))
9065 (cond
9066 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9067 (setq pn (js2-parse-property-access tt pn)))
9068 ((= tt js2-DOTQUERY)
9069 (setq pn (js2-parse-dot-query pn)))
9070 ((= tt js2-LB)
9071 (setq pn (js2-parse-element-get pn)))
9072 ((= tt js2-LP)
9073 (if allow-call-syntax
9074 (setq pn (js2-parse-function-call pn))
9075 (setq continue nil)))
9076 (t
9077 (setq continue nil))))
9078 (if (>= js2-highlight-level 2)
9079 (js2-parse-highlight-member-expr-node pn))
9080 pn))
9081
9082 (defun js2-parse-dot-query (pn)
9083 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9084 Last token parsed must be `js2-DOTQUERY'."
9085 (let ((pos (js2-node-pos pn))
9086 op-pos
9087 expr
9088 end)
9089 (js2-consume-token)
9090 (js2-must-have-xml)
9091 (js2-set-requires-activation)
9092 (setq op-pos js2-token-beg
9093 expr (js2-parse-expr)
9094 end (js2-node-end expr)
9095 pn (make-js2-xml-dot-query-node :left pn
9096 :pos pos
9097 :op-pos op-pos
9098 :right expr))
9099 (js2-node-add-children pn
9100 (js2-xml-dot-query-node-left pn)
9101 (js2-xml-dot-query-node-right pn))
9102 (if (js2-must-match js2-RP "msg.no.paren")
9103 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9104 end js2-token-end))
9105 (setf (js2-node-len pn) (- end pos))
9106 pn))
9107
9108 (defun js2-parse-element-get (pn)
9109 "Parse an element-get expression, e.g. foo[bar].
9110 Last token parsed must be `js2-RB'."
9111 (let ((lb js2-token-beg)
9112 (pos (js2-node-pos pn))
9113 rb
9114 expr)
9115 (js2-consume-token)
9116 (setq expr (js2-parse-expr))
9117 (if (js2-must-match js2-RB "msg.no.bracket.index")
9118 (setq rb js2-token-beg))
9119 (setq pn (make-js2-elem-get-node :target pn
9120 :pos pos
9121 :element expr
9122 :lb (js2-relpos lb pos)
9123 :rb (js2-relpos rb pos)
9124 :len (- js2-token-end pos)))
9125 (js2-node-add-children pn
9126 (js2-elem-get-node-target pn)
9127 (js2-elem-get-node-element pn))
9128 pn))
9129
9130 (defun js2-parse-function-call (pn)
9131 (let (args
9132 (pos (js2-node-pos pn)))
9133 (js2-consume-token)
9134 (setq pn (make-js2-call-node :pos pos
9135 :target pn
9136 :lp (- js2-token-beg pos)))
9137 (js2-node-add-children pn (js2-call-node-target pn))
9138 ;; Add the arguments to pn, if any are supplied.
9139 (setf args (nreverse (js2-parse-argument-list))
9140 (js2-call-node-rp pn) (- js2-token-beg pos)
9141 (js2-call-node-args pn) args)
9142 (apply #'js2-node-add-children pn args)
9143 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9144 pn))
9145
9146 (defun js2-parse-property-access (tt pn)
9147 "Parse a property access, XML descendants access, or XML attr access."
9148 (let ((member-type-flags 0)
9149 (dot-pos js2-token-beg)
9150 (dot-len (if (= tt js2-DOTDOT) 2 1))
9151 name
9152 ref ; right side of . or .. operator
9153 result)
9154 (js2-consume-token)
9155 (when (= tt js2-DOTDOT)
9156 (js2-must-have-xml)
9157 (setq member-type-flags js2-descendants-flag))
9158 (if (not js2-compiler-xml-available)
9159 (progn
9160 (js2-must-match-prop-name "msg.no.name.after.dot")
9161 (setq name (js2-create-name-node t js2-GETPROP)
9162 result (make-js2-prop-get-node :left pn
9163 :pos js2-token-beg
9164 :right name
9165 :len (- js2-token-end
9166 js2-token-beg)))
9167 (js2-node-add-children result pn name)
9168 result)
9169 ;; otherwise look for XML operators
9170 (setf result (if (= tt js2-DOT)
9171 (make-js2-prop-get-node)
9172 (make-js2-infix-node :type js2-DOTDOT))
9173 (js2-node-pos result) (js2-node-pos pn)
9174 (js2-infix-node-op-pos result) dot-pos
9175 (js2-infix-node-left result) pn ; do this after setting position
9176 tt (js2-next-token))
9177 (cond
9178 ;; needed for generator.throw()
9179 ((= tt js2-THROW)
9180 (js2-save-name-token-data js2-token-beg "throw")
9181 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9182 ;; handles: name, ns::name, ns::*, ns::[expr]
9183 ((js2-valid-prop-name-token tt)
9184 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9185 ;; handles: *, *::name, *::*, *::[expr]
9186 ((= tt js2-MUL)
9187 (js2-save-name-token-data js2-token-beg "*")
9188 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9189 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9190 ((= tt js2-XMLATTR)
9191 (setq result (js2-parse-attribute-access)))
9192 (t
9193 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9194 (if ref
9195 (setf (js2-node-len result) (- (js2-node-end ref)
9196 (js2-node-pos result))
9197 (js2-infix-node-right result) ref))
9198 (if (js2-infix-node-p result)
9199 (js2-node-add-children result
9200 (js2-infix-node-left result)
9201 (js2-infix-node-right result)))
9202 result)))
9203
9204 (defun js2-parse-attribute-access ()
9205 "Parse an E4X XML attribute expression.
9206 This includes expressions of the forms:
9207
9208 @attr @ns::attr @ns::*
9209 @* @*::attr @*::*
9210 @[expr] @*::[expr] @ns::[expr]
9211
9212 Called if we peeked an '@' token."
9213 (let ((tt (js2-next-token))
9214 (at-pos js2-token-beg))
9215 (cond
9216 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9217 ((js2-valid-prop-name-token tt)
9218 (js2-parse-property-name at-pos js2-ts-string 0))
9219 ;; handles: @*, @*::name, @*::*, @*::[expr]
9220 ((= tt js2-MUL)
9221 (js2-save-name-token-data js2-token-beg "*")
9222 (js2-parse-property-name js2-token-beg "*" 0))
9223 ;; handles @[expr]
9224 ((= tt js2-LB)
9225 (js2-parse-xml-elem-ref at-pos))
9226 (t
9227 (js2-report-error "msg.no.name.after.xmlAttr")
9228 ;; Avoid cascaded errors that happen if we make an error node here.
9229 (js2-save-name-token-data js2-token-beg "")
9230 (js2-parse-property-name js2-token-beg "" 0)))))
9231
9232 (defun js2-parse-property-name (at-pos s member-type-flags)
9233 "Check if :: follows name in which case it becomes qualified name.
9234
9235 AT-POS is a natural number if we just read an '@' token, else nil.
9236 S is the name or string that was matched: an identifier, 'throw' or '*'.
9237 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9238
9239 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9240 operator, or the name is followed by ::. For a plain name, returns a
9241 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9242 (let ((pos (or at-pos js2-token-beg))
9243 colon-pos
9244 (name (js2-create-name-node t js2-current-token))
9245 ns
9246 tt
9247 ref
9248 pn)
9249 (catch 'return
9250 (when (js2-match-token js2-COLONCOLON)
9251 (setq ns name
9252 colon-pos js2-token-beg
9253 tt (js2-next-token))
9254 (cond
9255 ;; handles name::name
9256 ((js2-valid-prop-name-token tt)
9257 (setq name (js2-create-name-node)))
9258 ;; handles name::*
9259 ((= tt js2-MUL)
9260 (js2-save-name-token-data js2-token-beg "*")
9261 (setq name (js2-create-name-node)))
9262 ;; handles name::[expr]
9263 ((= tt js2-LB)
9264 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9265 (t
9266 (js2-report-error "msg.no.name.after.coloncolon"))))
9267 (if (and (null ns) (zerop member-type-flags))
9268 name
9269 (prog1
9270 (setq pn
9271 (make-js2-xml-prop-ref-node :pos pos
9272 :len (- (js2-node-end name) pos)
9273 :at-pos at-pos
9274 :colon-pos colon-pos
9275 :propname name))
9276 (js2-node-add-children pn name))))))
9277
9278 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9279 "Parse the [expr] portion of an xml element reference.
9280 For instance, @[expr], @*::[expr], or ns::[expr]."
9281 (let* ((lb js2-token-beg)
9282 (pos (or at-pos lb))
9283 rb
9284 (expr (js2-parse-expr))
9285 (end (js2-node-end expr))
9286 pn)
9287 (if (js2-must-match js2-RB "msg.no.bracket.index")
9288 (setq rb js2-token-beg
9289 end js2-token-end))
9290 (prog1
9291 (setq pn
9292 (make-js2-xml-elem-ref-node :pos pos
9293 :len (- end pos)
9294 :namespace namespace
9295 :colon-pos colon-pos
9296 :at-pos at-pos
9297 :expr expr
9298 :lb (js2-relpos lb pos)
9299 :rb (js2-relpos rb pos)))
9300 (js2-node-add-children pn namespace expr))))
9301
9302 (defun js2-parse-destruct-primary-expr ()
9303 (let ((js2-is-in-destructuring t))
9304 (js2-parse-primary-expr)))
9305
9306 (defun js2-parse-primary-expr ()
9307 "Parses a literal (leaf) expression of some sort.
9308 Includes complex literals such as functions, object-literals,
9309 array-literals, array comprehensions and regular expressions."
9310 (let ((tt-flagged (js2-next-flagged-token))
9311 pn ; parent node (usually return value)
9312 tt
9313 px-pos ; paren-expr pos
9314 len
9315 flags ; regexp flags
9316 expr)
9317 (setq tt js2-current-token)
9318 (cond
9319 ((= tt js2-FUNCTION)
9320 (js2-parse-function 'FUNCTION_EXPRESSION))
9321 ((= tt js2-LB)
9322 (js2-parse-array-literal))
9323 ((= tt js2-LC)
9324 (js2-parse-object-literal))
9325 ((= tt js2-LET)
9326 (js2-parse-let js2-token-beg))
9327 ((= tt js2-LP)
9328 (setq px-pos js2-token-beg
9329 expr (js2-parse-expr))
9330 (js2-must-match js2-RP "msg.no.paren")
9331 (setq pn (make-js2-paren-node :pos px-pos
9332 :expr expr
9333 :len (- js2-token-end px-pos)))
9334 (js2-node-add-children pn (js2-paren-node-expr pn))
9335 pn)
9336 ((= tt js2-XMLATTR)
9337 (js2-must-have-xml)
9338 (js2-parse-attribute-access))
9339 ((= tt js2-NAME)
9340 (js2-parse-name tt-flagged tt))
9341 ((= tt js2-NUMBER)
9342 (make-js2-number-node))
9343 ((= tt js2-STRING)
9344 (prog1
9345 (make-js2-string-node)
9346 (js2-record-face 'font-lock-string-face)))
9347 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9348 ;; Got / or /= which in this context means a regexp literal
9349 (setq px-pos js2-token-beg)
9350 (js2-read-regexp tt)
9351 (setq flags js2-ts-regexp-flags
9352 js2-ts-regexp-flags nil)
9353 (prog1
9354 (make-js2-regexp-node :pos px-pos
9355 :len (- js2-ts-cursor px-pos)
9356 :value js2-ts-string
9357 :flags flags)
9358 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9359 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9360 ((or (= tt js2-NULL)
9361 (= tt js2-THIS)
9362 (= tt js2-FALSE)
9363 (= tt js2-TRUE))
9364 (make-js2-keyword-node :type tt))
9365 ((= tt js2-RESERVED)
9366 (js2-report-error "msg.reserved.id")
9367 (make-js2-name-node))
9368 ((= tt js2-ERROR)
9369 ;; the scanner or one of its subroutines reported the error.
9370 (make-js2-error-node))
9371 ((= tt js2-EOF)
9372 (setq px-pos (point-at-bol)
9373 len (- js2-ts-cursor px-pos))
9374 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9375 (make-js2-error-node :pos px-pos :len len))
9376 (t
9377 (js2-report-error "msg.syntax")
9378 (make-js2-error-node)))))
9379
9380 (defun js2-parse-name (tt-flagged tt)
9381 (let ((name js2-ts-string)
9382 (name-pos js2-token-beg)
9383 node)
9384 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9385 (= (js2-peek-token) js2-COLON))
9386 (prog1
9387 ;; Do not consume colon, it is used as unwind indicator
9388 ;; to return to statementHelper.
9389 (make-js2-label-node :pos name-pos
9390 :len (- js2-token-end name-pos)
9391 :name name)
9392 (js2-set-face name-pos
9393 js2-token-end
9394 'font-lock-variable-name-face 'record))
9395 ;; Otherwise not a label, just a name. Unfortunately peeking
9396 ;; the next token to check for a colon has biffed js2-token-beg
9397 ;; and js2-token-end. We store the name's bounds in buffer vars
9398 ;; and `js2-create-name-node' uses them.
9399 (js2-save-name-token-data name-pos name)
9400 (setq node (if js2-compiler-xml-available
9401 (js2-parse-property-name nil name 0)
9402 (js2-create-name-node 'check-activation)))
9403 (if js2-highlight-external-variables
9404 (js2-record-name-node node))
9405 node)))
9406
9407 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9408 (js2-add-strict-warning
9409 msg nil
9410 ;; back up from comma to beginning of line or array/objlit
9411 (max (if elems
9412 (js2-node-pos (car elems))
9413 pos)
9414 (save-excursion
9415 (goto-char comma-pos)
9416 (back-to-indentation)
9417 (point)))
9418 comma-pos))
9419
9420 (defun js2-parse-array-literal ()
9421 (let ((pos js2-token-beg)
9422 (end js2-token-end)
9423 (after-lb-or-comma t)
9424 after-comma
9425 tt
9426 elems
9427 pn
9428 (continue t))
9429 (unless js2-is-in-destructuring
9430 (js2-push-scope (make-js2-scope))) ; for array comp
9431 (while continue
9432 (setq tt (js2-peek-token))
9433 (cond
9434 ;; comma
9435 ((= tt js2-COMMA)
9436 (js2-consume-token)
9437 (setq after-comma js2-token-end)
9438 (if (not after-lb-or-comma)
9439 (setq after-lb-or-comma t)
9440 (push nil elems)))
9441 ;; end of array
9442 ((or (= tt js2-RB)
9443 (= tt js2-EOF)) ; prevent infinite loop
9444 (if (= tt js2-EOF)
9445 (js2-report-error "msg.no.bracket.arg" nil pos)
9446 (js2-consume-token))
9447 (setq continue nil
9448 end js2-token-end
9449 pn (make-js2-array-node :pos pos
9450 :len (- js2-ts-cursor pos)
9451 :elems (nreverse elems)))
9452 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9453 (when (and after-comma (not js2-is-in-destructuring))
9454 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9455 pos elems after-comma)))
9456 ;; destructuring binding
9457 (js2-is-in-destructuring
9458 (push (if (or (= tt js2-LC)
9459 (= tt js2-LB)
9460 (= tt js2-NAME))
9461 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9462 (js2-parse-destruct-primary-expr)
9463 ;; invalid pattern
9464 (js2-consume-token)
9465 (js2-report-error "msg.bad.var")
9466 (make-js2-error-node))
9467 elems)
9468 (setq after-lb-or-comma nil
9469 after-comma nil))
9470 ;; array comp
9471 ((and (>= js2-language-version 170)
9472 (= tt js2-FOR) ; check for array comprehension
9473 (not after-lb-or-comma) ; "for" can't follow a comma
9474 elems ; must have at least 1 element
9475 (not (cdr elems))) ; but no 2nd element
9476 (setf continue nil
9477 pn (js2-parse-array-comprehension (car elems) pos)))
9478
9479 ;; another element
9480 (t
9481 (unless after-lb-or-comma
9482 (js2-report-error "msg.no.bracket.arg"))
9483 (push (js2-parse-assign-expr) elems)
9484 (setq after-lb-or-comma nil
9485 after-comma nil))))
9486 (unless js2-is-in-destructuring
9487 (js2-pop-scope))
9488 pn))
9489
9490 (defun js2-parse-array-comprehension (expr pos)
9491 "Parse a JavaScript 1.7 Array Comprehension.
9492 EXPR is the first expression after the opening left-bracket.
9493 POS is the beginning of the LB token preceding EXPR.
9494 We should have just parsed the 'for' keyword before calling this function."
9495 (let (loops
9496 loop
9497 first
9498 prev
9499 filter
9500 if-pos
9501 result)
9502 (while (= (js2-peek-token) js2-FOR)
9503 (let ((prev (car loops))) ; rearrange scope chain
9504 (push (setq loop (js2-parse-array-comp-loop)) loops)
9505 (if prev ; each loop is parent scope to the next one
9506 (setf (js2-scope-parent-scope loop) prev)
9507 ; first loop takes expr scope's parent
9508 (setf (js2-scope-parent-scope (setq first loop))
9509 (js2-scope-parent-scope js2-current-scope)))))
9510 ;; set expr scope's parent to the last loop
9511 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9512 (when (= (js2-peek-token) js2-IF)
9513 (js2-consume-token)
9514 (setq if-pos (- js2-token-beg pos) ; relative
9515 filter (js2-parse-condition)))
9516 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9517 (setq result (make-js2-array-comp-node :pos pos
9518 :len (- js2-ts-cursor pos)
9519 :result expr
9520 :loops (nreverse loops)
9521 :filter (car filter)
9522 :lp (js2-relpos (second filter) pos)
9523 :rp (js2-relpos (third filter) pos)
9524 :if-pos if-pos))
9525 (apply #'js2-node-add-children result expr (car filter)
9526 (js2-array-comp-node-loops result))
9527 (setq js2-current-scope first) ; pop to the first loop
9528 result))
9529
9530 (defun js2-parse-array-comp-loop ()
9531 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9532 Last token peeked should be the initial FOR."
9533 (let ((pos js2-token-beg)
9534 (pn (make-js2-array-comp-loop-node))
9535 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9536 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9537 (js2-push-scope pn)
9538 (unwind-protect
9539 (progn
9540 (when (js2-match-token js2-NAME)
9541 (if (string= js2-ts-string "each")
9542 (progn
9543 (setq foreach-p t
9544 each-pos (- js2-token-beg pos)) ; relative
9545 (js2-record-face 'font-lock-keyword-face))
9546 (js2-report-error "msg.no.paren.for")))
9547 (if (js2-must-match js2-LP "msg.no.paren.for")
9548 (setq lp (- js2-token-beg pos)))
9549 (setq tt (js2-peek-token))
9550 (cond
9551 ((or (= tt js2-LB)
9552 (= tt js2-LC))
9553 (setq iter (js2-parse-destruct-primary-expr))
9554 (js2-define-destruct-symbols iter js2-LET
9555 'font-lock-variable-name-face t))
9556 ((js2-match-token js2-NAME)
9557 (setq iter (js2-create-name-node)))
9558 (t
9559 (js2-report-error "msg.bad.var")))
9560 ;; Define as a let since we want the scope of the variable to
9561 ;; be restricted to the array comprehension
9562 (if (js2-name-node-p iter)
9563 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9564 (if (or (js2-match-token js2-IN)
9565 (and (>= js2-language-version 200)
9566 (js2-match-contextual-kwd "of")
9567 (setq forof-p t)))
9568 (setq in-pos (- js2-token-beg pos))
9569 (js2-report-error "msg.in.after.for.name"))
9570 (setq obj (js2-parse-expr))
9571 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9572 (setq rp (- js2-token-beg pos)))
9573 (setf (js2-node-pos pn) pos
9574 (js2-node-len pn) (- js2-ts-cursor pos)
9575 (js2-array-comp-loop-node-iterator pn) iter
9576 (js2-array-comp-loop-node-object pn) obj
9577 (js2-array-comp-loop-node-in-pos pn) in-pos
9578 (js2-array-comp-loop-node-each-pos pn) each-pos
9579 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9580 (js2-array-comp-loop-node-forof-p pn) forof-p
9581 (js2-array-comp-loop-node-lp pn) lp
9582 (js2-array-comp-loop-node-rp pn) rp)
9583 (js2-node-add-children pn iter obj))
9584 (js2-pop-scope))
9585 pn))
9586
9587 (defun js2-parse-object-literal ()
9588 (let ((pos js2-token-beg)
9589 tt
9590 elems
9591 result
9592 after-comma
9593 (continue t))
9594 (while continue
9595 (setq tt (js2-peek-token))
9596 (cond
9597 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9598 ((or (js2-valid-prop-name-token tt)
9599 (= tt js2-STRING))
9600 (setq after-comma nil
9601 result (js2-parse-named-prop tt))
9602 (if (and (null result)
9603 (not js2-recover-from-parse-errors))
9604 (setq continue nil)
9605 (push result elems)))
9606 ;; {12: x} or {10.7: x}
9607 ((= tt js2-NUMBER)
9608 (js2-consume-token)
9609 (setq after-comma nil)
9610 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9611 ;; trailing comma
9612 ((= tt js2-RC)
9613 (setq continue nil)
9614 (if after-comma
9615 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9616 pos elems after-comma)))
9617 (t
9618 (js2-report-error "msg.bad.prop")
9619 (unless js2-recover-from-parse-errors
9620 (setq continue nil)))) ; end switch
9621 (if (js2-match-token js2-COMMA)
9622 (setq after-comma js2-token-end)
9623 (setq continue nil))) ; end loop
9624 (js2-must-match js2-RC "msg.no.brace.prop")
9625 (setq result (make-js2-object-node :pos pos
9626 :len (- js2-ts-cursor pos)
9627 :elems (nreverse elems)))
9628 (apply #'js2-node-add-children result (js2-object-node-elems result))
9629 result))
9630
9631 (defun js2-parse-named-prop (tt)
9632 "Parse a name, string, or getter/setter object property.
9633 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9634 (js2-consume-token)
9635 (let ((string-prop (and (= tt js2-STRING)
9636 (make-js2-string-node)))
9637 expr
9638 (ppos js2-token-beg)
9639 (pend js2-token-end)
9640 (name (js2-create-name-node))
9641 (prop js2-ts-string))
9642 (cond
9643 ;; getter/setter prop
9644 ((and (= tt js2-NAME)
9645 (= (js2-peek-token) js2-NAME)
9646 (or (string= prop "get")
9647 (string= prop "set")))
9648 (js2-consume-token)
9649 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9650 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9651 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9652 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9653 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9654 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9655 ;; when patterns are used in variable declarations, function parameters,
9656 ;; catch-clause, and iterators.
9657 ;; We have to set `js2-is-in-destructuring' to t when the current
9658 ;; expressions are on the left side of any assignment, but it's difficult
9659 ;; because it requires looking ahead of expression.
9660 ((and js2-is-in-destructuring
9661 (= tt js2-NAME)
9662 (let ((ctk (js2-peek-token)))
9663 (or (= ctk js2-COMMA)
9664 (= ctk js2-RC)
9665 (js2-valid-prop-name-token ctk))))
9666 name)
9667 ;; regular prop
9668 (t
9669 (prog1
9670 (setq expr (js2-parse-plain-property (or string-prop name)))
9671 (js2-set-face ppos pend
9672 (if (js2-function-node-p
9673 (js2-object-prop-node-right expr))
9674 'font-lock-function-name-face
9675 'font-lock-variable-name-face)
9676 'record))))))
9677
9678 (defun js2-parse-plain-property (prop)
9679 "Parse a non-getter/setter property in an object literal.
9680 PROP is the node representing the property: a number, name or string."
9681 (js2-must-match js2-COLON "msg.no.colon.prop")
9682 (let* ((pos (js2-node-pos prop))
9683 (colon (- js2-token-beg pos))
9684 (expr (js2-parse-assign-expr))
9685 (result (make-js2-object-prop-node
9686 :pos pos
9687 ;; don't include last consumed token in length
9688 :len (- (+ (js2-node-pos expr)
9689 (js2-node-len expr))
9690 pos)
9691 :left prop
9692 :right expr
9693 :op-pos colon)))
9694 (js2-node-add-children result prop expr)
9695 result))
9696
9697 (defun js2-parse-getter-setter-prop (pos prop get-p)
9698 "Parse getter or setter property in an object literal.
9699 JavaScript syntax is:
9700
9701 { get foo() {...}, set foo(x) {...} }
9702
9703 and expression closure style is also supported
9704
9705 { get foo() x, set foo(x) _x = x }
9706
9707 POS is the start position of the `get' or `set' keyword.
9708 PROP is the `js2-name-node' representing the property name.
9709 GET-P is non-nil if the keyword was `get'."
9710 (let ((type (if get-p js2-GET js2-SET))
9711 result
9712 end
9713 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9714 ;; it has to be an anonymous function, as we already parsed the name
9715 (if (/= (js2-node-type fn) js2-FUNCTION)
9716 (js2-report-error "msg.bad.prop")
9717 (if (plusp (length (js2-function-name fn)))
9718 (js2-report-error "msg.bad.prop")))
9719 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9720 (setq end (js2-node-end fn)
9721 result (make-js2-getter-setter-node :type type
9722 :pos pos
9723 :len (- end pos)
9724 :left prop
9725 :right fn))
9726 (js2-node-add-children result prop fn)
9727 result))
9728
9729 (defun js2-create-name-node (&optional check-activation-p token)
9730 "Create a name node using the token info from last scanned name.
9731 In some cases we need to either synthesize a name node, or we lost
9732 the name token information by peeking. If the TOKEN parameter is
9733 not `js2-NAME', then we use the token info saved in instance vars."
9734 (let ((beg js2-token-beg)
9735 (s js2-ts-string)
9736 name)
9737 (when (/= js2-current-token js2-NAME)
9738 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9739 s js2-prev-name-token-string
9740 js2-prev-name-token-start nil
9741 js2-prev-name-token-string nil))
9742 (setq name (make-js2-name-node :pos beg
9743 :name s
9744 :len (length s)))
9745 (if check-activation-p
9746 (js2-check-activation-name s (or token js2-NAME)))
9747 name))
9748
9749 ;;; Indentation support
9750
9751 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9752 ;; Karl cleverly deduces that the desired indentation level is often a
9753 ;; function of paren/bracket/brace nesting depth, which can be determined
9754 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9755 ;; then does some equally clever checks to see if we're in the context of a
9756 ;; substatement of a possibly braceless statement keyword such as if, while,
9757 ;; or finally. This approach yields pretty good results.
9758
9759 ;; The indenter is often "wrong", however, and needs to be overridden.
9760 ;; The right long-term solution is probably to emulate (or integrate
9761 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9762 ;; parse tree from `js2-parse' is present, which is not true at the
9763 ;; moment the user is typing, computing indentation is still thousands
9764 ;; of lines of code to handle every possible syntactic edge case.
9765
9766 ;; In the meantime, the compromise solution is that we offer a "bounce
9767 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9768 ;; current line indent among various likely guess points. This approach
9769 ;; is far from perfect, but should at least make it slightly easier to
9770 ;; move the line towards its desired indentation when manually
9771 ;; overriding Karl's heuristic nesting guesser.
9772
9773 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9774 ;; extensions such as `let' and Array comprehensions. Major kudos to
9775 ;; Karl for coming up with the initial approach, which packs a lot of
9776 ;; punch for so little code.
9777
9778 (defconst js2-possibly-braceless-keywords-re
9779 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9780 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9781 "try" "while" "with" "let")))
9782 "Regular expression matching keywords that are optionally
9783 followed by an opening brace.")
9784
9785 (defconst js2-indent-operator-re
9786 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9787 (regexp-opt '("in" "instanceof") 'words))
9788 "Regular expression matching operators that affect indentation
9789 of continued expressions.")
9790
9791 (defconst js2-declaration-keyword-re
9792 (regexp-opt '("var" "let" "const") 'words)
9793 "Regular expression matching variable declaration keywords.")
9794
9795 ;; This function has horrible results if you're typing an array
9796 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9797 ;; in conjunction with electric-indent, so just disabling it.
9798 (defsubst js2-code-at-bol-p ()
9799 "Return t if the first character on line is non-whitespace."
9800 nil)
9801
9802 (defun js2-insert-and-indent (key)
9803 "Run command bound to key and indent current line. Runs the command
9804 bound to KEY in the global keymap and indents the current line."
9805 (interactive (list (this-command-keys)))
9806 (let ((cmd (lookup-key (current-global-map) key)))
9807 (if (commandp cmd)
9808 (call-interactively cmd)))
9809 ;; don't do the electric keys inside comments or strings,
9810 ;; and don't do bounce-indent with them.
9811 (let ((parse-state (syntax-ppss (point)))
9812 (js2-bounce-indent-p (js2-code-at-bol-p)))
9813 (unless (or (nth 3 parse-state)
9814 (nth 4 parse-state))
9815 (indent-according-to-mode))))
9816
9817 (defun js2-re-search-forward-inner (regexp &optional bound count)
9818 "Auxiliary function for `js2-re-search-forward'."
9819 (let (parse saved-point)
9820 (while (> count 0)
9821 (re-search-forward regexp bound)
9822 (setq parse (if saved-point
9823 (parse-partial-sexp saved-point (point))
9824 (syntax-ppss (point))))
9825 (cond ((nth 3 parse)
9826 (re-search-forward
9827 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9828 (save-excursion (end-of-line) (point)) t))
9829 ((nth 7 parse)
9830 (forward-line))
9831 ((or (nth 4 parse)
9832 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9833 (re-search-forward "\\*/"))
9834 (t
9835 (setq count (1- count))))
9836 (setq saved-point (point))))
9837 (point))
9838
9839 (defun js2-re-search-forward (regexp &optional bound noerror count)
9840 "Search forward but ignore strings and comments. Invokes
9841 `re-search-forward' but treats the buffer as if strings and
9842 comments have been removed."
9843 (let ((saved-point (point))
9844 (search-expr
9845 (cond ((null count)
9846 '(js2-re-search-forward-inner regexp bound 1))
9847 ((< count 0)
9848 '(js2-re-search-backward-inner regexp bound (- count)))
9849 ((> count 0)
9850 '(js2-re-search-forward-inner regexp bound count)))))
9851 (condition-case err
9852 (eval search-expr)
9853 (search-failed
9854 (goto-char saved-point)
9855 (unless noerror
9856 (error (error-message-string err)))))))
9857
9858 (defun js2-re-search-backward-inner (regexp &optional bound count)
9859 "Auxiliary function for `js2-re-search-backward'."
9860 (let (parse saved-point)
9861 (while (> count 0)
9862 (re-search-backward regexp bound)
9863 (setq parse (if saved-point
9864 (parse-partial-sexp saved-point (point))
9865 (syntax-ppss (point))))
9866 (cond ((nth 3 parse)
9867 (re-search-backward
9868 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9869 (save-excursion (beginning-of-line) (point)) t))
9870 ((nth 7 parse)
9871 (goto-char (nth 8 parse)))
9872 ((or (nth 4 parse)
9873 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9874 (re-search-backward "/\\*"))
9875 (t
9876 (setq count (1- count))))))
9877 (point))
9878
9879 (defun js2-re-search-backward (regexp &optional bound noerror count)
9880 "Search backward but ignore strings and comments. Invokes
9881 `re-search-backward' but treats the buffer as if strings and
9882 comments have been removed."
9883 (let ((saved-point (point))
9884 (search-expr
9885 (cond ((null count)
9886 '(js2-re-search-backward-inner regexp bound 1))
9887 ((< count 0)
9888 '(js2-re-search-forward-inner regexp bound (- count)))
9889 ((> count 0)
9890 '(js2-re-search-backward-inner regexp bound count)))))
9891 (condition-case err
9892 (eval search-expr)
9893 (search-failed
9894 (goto-char saved-point)
9895 (unless noerror
9896 (error (error-message-string err)))))))
9897
9898 (defun js2-looking-at-operator-p ()
9899 "Return non-nil if text after point is an operator (that is not
9900 a comma)."
9901 (save-match-data
9902 (and (looking-at js2-indent-operator-re)
9903 (or (not (looking-at ":"))
9904 (save-excursion
9905 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9906 (looking-at "?")))))))
9907
9908 (defun js2-continued-expression-p ()
9909 "Returns non-nil if the current line continues an expression."
9910 (save-excursion
9911 (back-to-indentation)
9912 (or (js2-looking-at-operator-p)
9913 (when (catch 'found
9914 (while (and (re-search-backward "\n" nil t)
9915 (let ((state (syntax-ppss)))
9916 (when (nth 4 state)
9917 (goto-char (nth 8 state))) ;; skip comments
9918 (skip-chars-backward " \t")
9919 (if (bolp)
9920 t
9921 (throw 'found t))))))
9922 (backward-char)
9923 (when (js2-looking-at-operator-p)
9924 (backward-char)
9925 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9926
9927 (defun js2-end-of-do-while-loop-p ()
9928 "Returns non-nil if word after point is `while' of a do-while
9929 statement, else returns nil. A braceless do-while statement
9930 spanning several lines requires that the start of the loop is
9931 indented to the same column as the current line."
9932 (interactive)
9933 (save-excursion
9934 (save-match-data
9935 (when (looking-at "\\s-*\\<while\\>")
9936 (if (save-excursion
9937 (skip-chars-backward "[ \t\n]*}")
9938 (looking-at "[ \t\n]*}"))
9939 (save-excursion
9940 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9941 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9942 (or (looking-at "\\<do\\>")
9943 (let ((saved-indent (current-indentation)))
9944 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9945 (/= (current-indentation) saved-indent)))
9946 (and (looking-at "[ \t]*\\<do\\>")
9947 (not (js2-re-search-forward
9948 "\\<while\\>" (point-at-eol) t))
9949 (= (current-indentation) saved-indent)))))))))
9950
9951 (defun js2-multiline-decl-indentation ()
9952 "Returns the declaration indentation column if the current line belongs
9953 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9954 (let (forward-sexp-function ; use Lisp version
9955 at-opening-bracket)
9956 (save-excursion
9957 (back-to-indentation)
9958 (when (not (looking-at js2-declaration-keyword-re))
9959 (when (looking-at js2-indent-operator-re)
9960 (goto-char (match-end 0))) ; continued expressions are ok
9961 (while (and (not at-opening-bracket)
9962 (not (bobp))
9963 (let ((pos (point)))
9964 (save-excursion
9965 (js2-backward-sws)
9966 (or (eq (char-before) ?,)
9967 (and (not (eq (char-before) ?\;))
9968 (and
9969 (prog2 (skip-chars-backward "[[:punct:]]")
9970 (looking-at js2-indent-operator-re)
9971 (js2-backward-sws))
9972 (not (eq (char-before) ?\;))))
9973 (js2-same-line pos)))))
9974 (condition-case err
9975 (backward-sexp)
9976 (scan-error (setq at-opening-bracket t))))
9977 (when (looking-at js2-declaration-keyword-re)
9978 (goto-char (match-end 0))
9979 (1+ (current-column)))))))
9980
9981 (defun js2-ctrl-statement-indentation ()
9982 "Returns the proper indentation of the current line if it
9983 starts the body of a control statement without braces, else
9984 returns nil."
9985 (let (forward-sexp-function) ; temporarily unbind it
9986 (save-excursion
9987 (back-to-indentation)
9988 (when (and (not (js2-same-line (point-min)))
9989 (not (looking-at "{"))
9990 (js2-re-search-backward "[[:graph:]]" nil t)
9991 (not (looking-at "[{([]"))
9992 (progn
9993 (forward-char)
9994 (when (= (char-before) ?\))
9995 ;; scan-sexps sometimes throws an error
9996 (ignore-errors (backward-sexp))
9997 (skip-chars-backward " \t" (point-at-bol)))
9998 (let ((pt (point)))
9999 (back-to-indentation)
10000 (and (looking-at js2-possibly-braceless-keywords-re)
10001 (= (match-end 0) pt)
10002 (not (js2-end-of-do-while-loop-p))))))
10003 (+ (current-indentation) js2-basic-offset)))))
10004
10005 (defun js2-indent-in-array-comp (parse-status)
10006 "Return non-nil if we think we're in an array comprehension.
10007 In particular, return the buffer position of the first `for' kwd."
10008 (let ((bracket (nth 1 parse-status))
10009 (end (point)))
10010 (when bracket
10011 (save-excursion
10012 (goto-char bracket)
10013 (when (looking-at "\\[")
10014 (forward-char 1)
10015 (js2-forward-sws)
10016 (if (looking-at "[[{]")
10017 (let (forward-sexp-function) ; use lisp version
10018 (forward-sexp) ; skip destructuring form
10019 (js2-forward-sws)
10020 (if (and (/= (char-after) ?,) ; regular array
10021 (looking-at "for"))
10022 (match-beginning 0)))
10023 ;; to skip arbitrary expressions we need the parser,
10024 ;; so we'll just guess at it.
10025 (if (and (> end (point)) ; not empty literal
10026 (re-search-forward "[^,]]* \\(for\\) " end t)
10027 ;; not inside comment or string literal
10028 (let ((state (parse-partial-sexp bracket (point))))
10029 (not (or (nth 3 state) (nth 4 state)))))
10030 (match-beginning 1))))))))
10031
10032 (defun js2-array-comp-indentation (parse-status for-kwd)
10033 (if (js2-same-line for-kwd)
10034 ;; first continuation line
10035 (save-excursion
10036 (goto-char (nth 1 parse-status))
10037 (forward-char 1)
10038 (skip-chars-forward " \t")
10039 (current-column))
10040 (save-excursion
10041 (goto-char for-kwd)
10042 (current-column))))
10043
10044 (defun js2-proper-indentation (parse-status)
10045 "Return the proper indentation for the current line."
10046 (save-excursion
10047 (back-to-indentation)
10048 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10049 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10050 (continued-expr-p (js2-continued-expression-p))
10051 (declaration-indent (and js2-pretty-multiline-declarations
10052 (js2-multiline-decl-indentation)))
10053 (bracket (nth 1 parse-status))
10054 beg)
10055 (cond
10056 ;; indent array comprehension continuation lines specially
10057 ((and bracket
10058 (>= js2-language-version 170)
10059 (not (js2-same-line bracket))
10060 (setq beg (js2-indent-in-array-comp parse-status))
10061 (>= (point) (save-excursion
10062 (goto-char beg)
10063 (point-at-bol)))) ; at or after first loop?
10064 (js2-array-comp-indentation parse-status beg))
10065
10066 (ctrl-stmt-indent)
10067
10068 ((and declaration-indent continued-expr-p)
10069 (+ declaration-indent js2-basic-offset))
10070
10071 (declaration-indent)
10072
10073 (bracket
10074 (goto-char bracket)
10075 (cond
10076 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10077 (when (save-excursion (skip-chars-backward " \t)")
10078 (looking-at ")"))
10079 (backward-list))
10080 (back-to-indentation)
10081 (and (eq js2-pretty-multiline-declarations 'all)
10082 (looking-at js2-declaration-keyword-re)
10083 (goto-char (1+ (match-end 0))))
10084 (cond (same-indent-p
10085 (current-column))
10086 (continued-expr-p
10087 (+ (current-column) (* 2 js2-basic-offset)))
10088 (t
10089 (+ (current-column) js2-basic-offset))))
10090 (t
10091 (unless same-indent-p
10092 (forward-char)
10093 (skip-chars-forward " \t"))
10094 (current-column))))
10095
10096 (continued-expr-p js2-basic-offset)
10097
10098 (t 0)))))
10099
10100 (defun js2-lineup-comment (parse-status)
10101 "Indent a multi-line block comment continuation line."
10102 (let* ((beg (nth 8 parse-status))
10103 (first-line (js2-same-line beg))
10104 (offset (save-excursion
10105 (goto-char beg)
10106 (if (looking-at "/\\*")
10107 (+ 1 (current-column))
10108 0))))
10109 (unless first-line
10110 (indent-line-to offset))))
10111
10112 (defun js2-backward-sws ()
10113 "Move backward through whitespace and comments."
10114 (interactive)
10115 (while (forward-comment -1)))
10116
10117 (defun js2-forward-sws ()
10118 "Move forward through whitespace and comments."
10119 (interactive)
10120 (while (forward-comment 1)))
10121
10122 (defsubst js2-current-indent (&optional pos)
10123 "Return column of indentation on current line.
10124 If POS is non-nil, go to that point and return indentation for that line."
10125 (save-excursion
10126 (if pos
10127 (goto-char pos))
10128 (back-to-indentation)
10129 (current-column)))
10130
10131 (defsubst js2-arglist-close ()
10132 "Return non-nil if we're on a line beginning with a close-paren/brace."
10133 (save-match-data
10134 (save-excursion
10135 (goto-char (point-at-bol))
10136 (js2-forward-sws)
10137 (looking-at "[])}]"))))
10138
10139 (defsubst js2-indent-looks-like-label-p ()
10140 (goto-char (point-at-bol))
10141 (js2-forward-sws)
10142 (looking-at (concat js2-mode-identifier-re ":")))
10143
10144 (defun js2-indent-in-objlit-p (parse-status)
10145 "Return non-nil if this looks like an object-literal entry."
10146 (let ((start (nth 1 parse-status)))
10147 (and
10148 start
10149 (save-excursion
10150 (and (zerop (forward-line -1))
10151 (not (< (point) start)) ; crossed a {} boundary
10152 (js2-indent-looks-like-label-p)))
10153 (save-excursion
10154 (js2-indent-looks-like-label-p)))))
10155
10156 ;; if prev line looks like foobar({ then we're passing an object
10157 ;; literal to a function call, and people pretty much always want to
10158 ;; de-dent back to the previous line, so move the 'basic-offset'
10159 ;; position to the front.
10160 (defsubst js2-indent-objlit-arg-p (parse-status)
10161 (save-excursion
10162 (back-to-indentation)
10163 (js2-backward-sws)
10164 (and (eq (1- (point)) (nth 1 parse-status))
10165 (eq (char-before) ?{)
10166 (progn
10167 (forward-char -1)
10168 (skip-chars-backward " \t")
10169 (eq (char-before) ?\()))))
10170
10171 (defsubst js2-indent-case-block-p ()
10172 (save-excursion
10173 (back-to-indentation)
10174 (js2-backward-sws)
10175 (goto-char (point-at-bol))
10176 (skip-chars-forward " \t")
10177 (save-match-data
10178 (looking-at "case\\s-.+:"))))
10179
10180 (defsubst js2-syntax-bol ()
10181 "Return the point at the first non-whitespace char on the line.
10182 Returns `point-at-bol' if the line is empty."
10183 (save-excursion
10184 (beginning-of-line)
10185 (skip-chars-forward " \t")
10186 (point)))
10187
10188 (defun js2-bounce-indent (normal-col parse-status backwards)
10189 "Cycle among alternate computed indentation positions.
10190 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10191 of the buffer to the current point. NORMAL-COL is the indentation
10192 column computed by the heuristic guesser based on current paren,
10193 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10194 in reverse."
10195 (let ((cur-indent (js2-current-indent))
10196 (old-buffer-undo-list buffer-undo-list)
10197 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10198 (current-line (save-excursion
10199 (forward-line 0) ; move to bol
10200 (1+ (count-lines (point-min) (point)))))
10201 positions
10202 pos
10203 main-pos
10204 anchor
10205 arglist-cont
10206 same-indent
10207 prev-line-col
10208 basic-offset
10209 computed-pos)
10210 ;; temporarily don't record undo info, if user requested this
10211 (if js2-mode-indent-inhibit-undo
10212 (setq buffer-undo-list t))
10213 (unwind-protect
10214 (progn
10215 ;; first likely point: indent from beginning of previous code line
10216 (push (setq basic-offset
10217 (+ (save-excursion
10218 (back-to-indentation)
10219 (js2-backward-sws)
10220 (back-to-indentation)
10221 (setq prev-line-col (current-column)))
10222 js2-basic-offset))
10223 positions)
10224
10225 ;; (first + epsilon) likely point: indent 2x from beginning of
10226 ;; previous code line. Some companies like this approach. Ahem.
10227 ;; Seriously, though -- 4-space indent for expression continuation
10228 ;; lines isn't a bad idea. We should eventually implement it
10229 ;; that way.
10230 (push (setq basic-offset
10231 (+ (save-excursion
10232 (back-to-indentation)
10233 (js2-backward-sws)
10234 (back-to-indentation)
10235 (setq prev-line-col (current-column)))
10236 (* 2 js2-basic-offset)))
10237 positions)
10238
10239 ;; second likely point: indent from assign-expr RHS. This
10240 ;; is just a crude guess based on finding " = " on the previous
10241 ;; line containing actual code.
10242 (setq pos (save-excursion
10243 (save-match-data
10244 (forward-line -1)
10245 (goto-char (point-at-bol))
10246 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10247 (point-at-eol) t)
10248 (goto-char (match-end 1))
10249 (skip-chars-forward " \t\r\n")
10250 (current-column)))))
10251 (when pos
10252 (incf pos js2-basic-offset)
10253 (push pos positions))
10254
10255 ;; third likely point: same indent as previous line of code.
10256 ;; Make it the first likely point if we're not on an
10257 ;; arglist-close line and previous line ends in a comma, or
10258 ;; both this line and prev line look like object-literal
10259 ;; elements.
10260 (setq pos (save-excursion
10261 (goto-char (point-at-bol))
10262 (js2-backward-sws)
10263 (back-to-indentation)
10264 (prog1
10265 (current-column)
10266 ;; while we're here, look for trailing comma
10267 (if (save-excursion
10268 (goto-char (point-at-eol))
10269 (js2-backward-sws)
10270 (eq (char-before) ?,))
10271 (setq arglist-cont (1- (point)))))))
10272 (when pos
10273 (if (and (or arglist-cont
10274 (js2-indent-in-objlit-p parse-status))
10275 (not (js2-arglist-close)))
10276 (setq same-indent pos))
10277 (push pos positions))
10278
10279 ;; fourth likely point: first preceding code with less indentation
10280 ;; than the immediately preceding code line.
10281 (setq pos (save-excursion
10282 (back-to-indentation)
10283 (js2-backward-sws)
10284 (back-to-indentation)
10285 (setq anchor (current-column))
10286 (while (and (zerop (forward-line -1))
10287 (>= (progn
10288 (back-to-indentation)
10289 (current-column))
10290 anchor)))
10291 (setq pos (current-column))))
10292 (push pos positions)
10293
10294 ;; nesting-heuristic position, main by default
10295 (push (setq main-pos normal-col) positions)
10296
10297 ;; delete duplicates and sort positions list
10298 (setq positions (sort (delete-dups positions) '<))
10299
10300 ;; comma-list continuation lines: prev line indent takes precedence
10301 (if same-indent
10302 (setq main-pos same-indent))
10303
10304 ;; common special cases where we want to indent in from previous line
10305 (if (or (js2-indent-case-block-p)
10306 (js2-indent-objlit-arg-p parse-status))
10307 (setq main-pos basic-offset))
10308
10309 ;; if bouncing backwards, reverse positions list
10310 (if backwards
10311 (setq positions (reverse positions)))
10312
10313 ;; record whether we're already sitting on one of the alternatives
10314 (setq pos (member cur-indent positions))
10315
10316 (cond
10317 ;; case 0: we're one one of the alternatives and this is the
10318 ;; first time they've pressed TAB on this line (best-guess).
10319 ((and js2-mode-indent-ignore-first-tab
10320 pos
10321 ;; first time pressing TAB on this line?
10322 (not (eq js2-mode-last-indented-line current-line)))
10323 ;; do nothing
10324 (setq computed-pos nil))
10325 ;; case 1: only one computed position => use it
10326 ((null (cdr positions))
10327 (setq computed-pos 0))
10328 ;; case 2: not on any of the computed spots => use main spot
10329 ((not pos)
10330 (setq computed-pos (js2-position main-pos positions)))
10331 ;; case 3: on last position: cycle to first position
10332 ((null (cdr pos))
10333 (setq computed-pos 0))
10334 ;; case 4: on intermediate position: cycle to next position
10335 (t
10336 (setq computed-pos (js2-position (second pos) positions))))
10337
10338 ;; see if any hooks want to indent; otherwise we do it
10339 (loop with result = nil
10340 for hook in js2-indent-hook
10341 while (null result)
10342 do
10343 (setq result (funcall hook positions computed-pos))
10344 finally do
10345 (unless (or result (null computed-pos))
10346 (indent-line-to (nth computed-pos positions)))))
10347
10348 ;; finally
10349 (if js2-mode-indent-inhibit-undo
10350 (setq buffer-undo-list old-buffer-undo-list))
10351 ;; see commentary for `js2-mode-last-indented-line'
10352 (setq js2-mode-last-indented-line current-line))))
10353
10354 (defun js2-indent-bounce-backwards ()
10355 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10356 cycles between the computed indentation positions in reverse order."
10357 (interactive)
10358 (js2-indent-line t))
10359
10360 (defsubst js2-1-line-comment-continuation-p ()
10361 "Return t if we're in a 1-line comment continuation.
10362 If so, we don't ever want to use bounce-indent."
10363 (save-excursion
10364 (save-match-data
10365 (and (progn
10366 (forward-line 0)
10367 (looking-at "\\s-*//"))
10368 (progn
10369 (forward-line -1)
10370 (forward-line 0)
10371 (when (looking-at "\\s-*$")
10372 (js2-backward-sws)
10373 (forward-line 0))
10374 (looking-at "\\s-*//"))))))
10375
10376 (defun js2-indent-line (&optional bounce-backwards)
10377 "Indent the current line as JavaScript source text."
10378 (interactive)
10379 (let (parse-status
10380 offset
10381 indent-col
10382 moved
10383 ;; don't whine about errors/warnings when we're indenting.
10384 ;; This has to be set before calling parse-partial-sexp below.
10385 (inhibit-point-motion-hooks t))
10386 (setq parse-status (save-excursion
10387 (syntax-ppss (point-at-bol)))
10388 offset (- (point) (save-excursion
10389 (back-to-indentation)
10390 (point))))
10391 (js2-with-underscore-as-word-syntax
10392 (if (nth 4 parse-status)
10393 (js2-lineup-comment parse-status)
10394 (setq indent-col (js2-proper-indentation parse-status))
10395 ;; see comments below about js2-mode-last-indented-line
10396 (cond
10397 ;; bounce-indenting is disabled during electric-key indent.
10398 ;; It doesn't work well on first line of buffer.
10399 ((and js2-bounce-indent-p
10400 (not (js2-same-line (point-min)))
10401 (not (js2-1-line-comment-continuation-p)))
10402 (js2-bounce-indent indent-col parse-status bounce-backwards))
10403 ;; just indent to the guesser's likely spot
10404 (t (indent-line-to indent-col))))
10405 (when (plusp offset)
10406 (forward-char offset)))))
10407
10408 (defun js2-indent-region (start end)
10409 "Indent the region, but don't use bounce indenting."
10410 (let ((js2-bounce-indent-p nil)
10411 (indent-region-function nil)
10412 (after-change-functions (remq 'js2-mode-edit
10413 after-change-functions)))
10414 (indent-region start end nil) ; nil for byte-compiler
10415 (js2-mode-edit start end (- end start))))
10416
10417 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10418
10419 ;;;###autoload
10420 (defun js2-mode ()
10421 "Major mode for editing JavaScript code.
10422
10423 \\{js2-mode-map}"
10424 (interactive)
10425 (kill-all-local-variables)
10426 (set-syntax-table js2-mode-syntax-table)
10427 (use-local-map js2-mode-map)
10428 (make-local-variable 'comment-start)
10429 (make-local-variable 'comment-end)
10430 (make-local-variable 'comment-start-skip)
10431 (setq major-mode 'js2-mode
10432 mode-name "JavaScript-IDE"
10433 comment-start "//" ; used by comment-region; don't change it
10434 comment-end "")
10435 (setq local-abbrev-table js2-mode-abbrev-table)
10436 (set (make-local-variable 'max-lisp-eval-depth)
10437 (max max-lisp-eval-depth 3000))
10438 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10439 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10440
10441 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10442 ;; on most platforms other than the one I originally wrote it on.
10443 ;; So it's back to `c-fill-paragraph'.
10444 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10445
10446 (add-hook 'before-save-hook #'js2-before-save nil t)
10447 (set (make-local-variable 'next-error-function) #'js2-next-error)
10448 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10449 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10450 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10451 ;; for characters inside regexp literals.
10452 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10453 ;; this is necessary to make `show-paren-function' work properly
10454 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10455 ;; needed for M-x rgrep, among other things
10456 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10457
10458 ;; some variables needed by cc-engine for paragraph-fill, etc.
10459 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10460 c-comment-start-regexp "/[*/]\\|\\s|"
10461 c-line-comment-starter "//"
10462 c-paragraph-start js2-paragraph-start
10463 c-paragraph-separate "$"
10464 comment-start-skip js2-comment-start-skip
10465 c-syntactic-ws-start js2-syntactic-ws-start
10466 c-syntactic-ws-end js2-syntactic-ws-end
10467 c-syntactic-eol js2-syntactic-eol)
10468
10469 (let ((c-buffer-is-cc-mode t))
10470 ;; Copied from `js-mode'. Also see Bug#6071.
10471 (make-local-variable 'paragraph-start)
10472 (make-local-variable 'paragraph-separate)
10473 (make-local-variable 'paragraph-ignore-fill-prefix)
10474 (make-local-variable 'adaptive-fill-mode)
10475 (make-local-variable 'adaptive-fill-regexp)
10476 (c-setup-paragraph-variables))
10477
10478 (setq js2-default-externs
10479 (append js2-ecma-262-externs
10480 (if js2-include-browser-externs
10481 js2-browser-externs)
10482 (if js2-include-gears-externs
10483 js2-gears-externs)
10484 (if js2-include-rhino-externs
10485 js2-rhino-externs)))
10486
10487 ;; We do our own syntax highlighting based on the parse tree.
10488 ;; However, we want minor modes that add keywords to highlight properly
10489 ;; (examples: doxymacs, column-marker).
10490 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10491 (setq font-lock-defaults '(nil t))
10492
10493 ;; Experiment: make reparse-delay longer for longer files.
10494 (if (plusp js2-dynamic-idle-timer-adjust)
10495 (setq js2-idle-timer-delay
10496 (* js2-idle-timer-delay
10497 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10498
10499 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10500 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10501 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10502 (imenu-add-to-menubar (concat "IM-" mode-name))
10503 (when js2-mirror-mode
10504 (js2-enter-mirror-mode))
10505 (add-to-invisibility-spec '(js2-outline . t))
10506 (set (make-local-variable 'line-move-ignore-invisible) t)
10507 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10508
10509 (if (fboundp 'run-mode-hooks)
10510 (run-mode-hooks 'js2-mode-hook)
10511 (run-hooks 'js2-mode-hook))
10512
10513 (setq js2-mode-functions-hidden nil
10514 js2-mode-comments-hidden nil
10515 js2-mode-buffer-dirty-p t
10516 js2-mode-parsing nil)
10517 (js2-reparse))
10518
10519 (defun js2-mode-exit ()
10520 "Exit `js2-mode' and clean up."
10521 (interactive)
10522 (when js2-mode-node-overlay
10523 (delete-overlay js2-mode-node-overlay)
10524 (setq js2-mode-node-overlay nil))
10525 (js2-remove-overlays)
10526 (setq js2-mode-ast nil)
10527 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10528 (remove-from-invisibility-spec '(js2-outline . t))
10529 (js2-mode-show-all)
10530 (js2-with-unmodifying-text-property-changes
10531 (js2-clear-face (point-min) (point-max))))
10532
10533 (defun js2-before-save ()
10534 "Clean up whitespace before saving file.
10535 You can disable this by customizing `js2-cleanup-whitespace'."
10536 (when js2-cleanup-whitespace
10537 (let ((col (current-column)))
10538 (delete-trailing-whitespace)
10539 ;; don't change trailing whitespace on current line
10540 (unless (eq (current-column) col)
10541 (indent-to col)))))
10542
10543 (defsubst js2-mode-reset-timer ()
10544 "Cancel any existing parse timer and schedule a new one."
10545 (if js2-mode-parse-timer
10546 (cancel-timer js2-mode-parse-timer))
10547 (setq js2-mode-parsing nil)
10548 (let ((timer (timer-create)))
10549 (setq js2-mode-parse-timer timer)
10550 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10551 (timer-set-idle-time timer js2-idle-timer-delay)
10552 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10553 (timer-activate-when-idle timer nil)))
10554
10555 (defun js2-mode-idle-reparse (buffer)
10556 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10557 it to be reparsed when the buffer is selected."
10558 (if (eq buffer (current-buffer))
10559 (js2-reparse)
10560 ;; reparse when the buffer is selected again
10561 (with-current-buffer buffer
10562 (add-hook 'window-configuration-change-hook
10563 #'js2-mode-idle-reparse-inner
10564 nil t))))
10565
10566 (defun js2-mode-idle-reparse-inner ()
10567 (remove-hook 'window-configuration-change-hook
10568 #'js2-mode-idle-reparse-inner
10569 t)
10570 (js2-reparse))
10571
10572 (defun js2-mode-edit (beg end len)
10573 "Schedule a new parse after buffer is edited.
10574 Buffer edit spans from BEG to END and is of length LEN.
10575 Also clears the `js2-magic' bit on autoinserted parens/brackets
10576 if the edit occurred on a line different from the magic paren."
10577 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10578 (line (if magic-pos (line-number-at-pos magic-pos))))
10579 (and line
10580 (or (/= (line-number-at-pos beg) line)
10581 (and (> 0 len)
10582 (/= (line-number-at-pos end) line)))
10583 (js2-mode-mundanify-parens)))
10584 (setq js2-mode-buffer-dirty-p t)
10585 (js2-mode-hide-overlay)
10586 (js2-mode-reset-timer))
10587
10588 (defun js2-reparse (&optional force)
10589 "Re-parse current buffer after user finishes some data entry.
10590 If we get any user input while parsing, including cursor motion,
10591 we discard the parse and reschedule it. If FORCE is nil, then the
10592 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10593 (let (time
10594 interrupted-p
10595 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10596 (unless js2-mode-parsing
10597 (setq js2-mode-parsing t)
10598 (unwind-protect
10599 (when (or js2-mode-buffer-dirty-p force)
10600 (js2-remove-overlays)
10601 (js2-with-unmodifying-text-property-changes
10602 (setq js2-mode-buffer-dirty-p nil
10603 js2-mode-fontifications nil
10604 js2-mode-deferred-properties nil)
10605 (if js2-mode-verbose-parse-p
10606 (message "parsing..."))
10607 (setq time
10608 (js2-time
10609 (setq interrupted-p
10610 (catch 'interrupted
10611 (setq js2-mode-ast (js2-parse))
10612 ;; if parsing is interrupted, comments and regex
10613 ;; literals stay ignored by `parse-partial-sexp'
10614 (remove-text-properties (point-min) (point-max)
10615 '(syntax-table))
10616 (js2-mode-apply-deferred-properties)
10617 (js2-mode-remove-suppressed-warnings)
10618 (js2-mode-show-warnings)
10619 (js2-mode-show-errors)
10620 (js2-mode-highlight-magic-parens)
10621 (if (>= js2-highlight-level 1)
10622 (js2-highlight-jsdoc js2-mode-ast))
10623 nil))))
10624 (if interrupted-p
10625 (progn
10626 ;; unfinished parse => try again
10627 (setq js2-mode-buffer-dirty-p t)
10628 (js2-mode-reset-timer))
10629 (if js2-mode-verbose-parse-p
10630 (message "Parse time: %s" time)))))
10631 (setq js2-mode-parsing nil)
10632 (unless interrupted-p
10633 (setq js2-mode-parse-timer nil))))))
10634
10635 (defun js2-mode-show-node (event)
10636 "Debugging aid: highlight selected AST node on mouse click."
10637 (interactive "e")
10638 (mouse-set-point event)
10639 (setq deactivate-mark t)
10640 (when js2-mode-show-overlay
10641 (let ((node (js2-node-at-point))
10642 beg end)
10643 (if (null node)
10644 (message "No node found at location %s" (point))
10645 (setq beg (js2-node-abs-pos node)
10646 end (+ beg (js2-node-len node)))
10647 (if js2-mode-node-overlay
10648 (move-overlay js2-mode-node-overlay beg end)
10649 (setq js2-mode-node-overlay (make-overlay beg end))
10650 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10651 (js2-with-unmodifying-text-property-changes
10652 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10653 (message "%s, parent: %s"
10654 (js2-node-short-name node)
10655 (if (js2-node-parent node)
10656 (js2-node-short-name (js2-node-parent node))
10657 "nil"))))))
10658
10659 (defun js2-mode-hide-overlay (&optional p1 p2)
10660 "Remove the debugging overlay when the point moves.
10661 P1 and P2 are the old and new values of point, respectively."
10662 (when js2-mode-node-overlay
10663 (let ((beg (overlay-start js2-mode-node-overlay))
10664 (end (overlay-end js2-mode-node-overlay)))
10665 ;; Sometimes we're called spuriously.
10666 (unless (and p2
10667 (>= p2 beg)
10668 (<= p2 end))
10669 (js2-with-unmodifying-text-property-changes
10670 (remove-text-properties beg end '(point-left nil)))
10671 (delete-overlay js2-mode-node-overlay)
10672 (setq js2-mode-node-overlay nil)))))
10673
10674 (defun js2-mode-reset ()
10675 "Debugging helper: reset everything."
10676 (interactive)
10677 (js2-mode-exit)
10678 (js2-mode))
10679
10680 (defsubst js2-mode-show-warn-or-err (e face)
10681 "Highlight a warning or error E with FACE.
10682 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10683 (let* ((key (first e))
10684 (beg (second e))
10685 (end (+ beg (third e)))
10686 ;; Don't inadvertently go out of bounds.
10687 (beg (max (point-min) (min beg (point-max))))
10688 (end (max (point-min) (min end (point-max))))
10689 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10690 (ovl (make-overlay beg end)))
10691 (overlay-put ovl 'font-lock-face face)
10692 (overlay-put ovl 'js2-error t)
10693 (put-text-property beg end 'help-echo (js2-get-msg key))
10694 (put-text-property beg end 'point-entered #'js2-echo-error)))
10695
10696 (defun js2-remove-overlays ()
10697 "Remove overlays from buffer that have a `js2-error' property."
10698 (let ((beg (point-min))
10699 (end (point-max)))
10700 (save-excursion
10701 (dolist (o (overlays-in beg end))
10702 (when (overlay-get o 'js2-error)
10703 (delete-overlay o))))))
10704
10705 (defun js2-error-at-point (&optional pos)
10706 "Return non-nil if there's an error overlay at POS.
10707 Defaults to point."
10708 (loop with pos = (or pos (point))
10709 for o in (overlays-at pos)
10710 thereis (overlay-get o 'js2-error)))
10711
10712 (defun js2-mode-apply-deferred-properties ()
10713 "Apply fontifications and other text properties recorded during parsing."
10714 (when (plusp js2-highlight-level)
10715 ;; We defer clearing faces as long as possible to eliminate flashing.
10716 (js2-clear-face (point-min) (point-max))
10717 ;; Have to reverse the recorded fontifications list so that errors
10718 ;; and warnings overwrite the normal fontifications.
10719 (dolist (f (nreverse js2-mode-fontifications))
10720 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10721 (setq js2-mode-fontifications nil))
10722 (dolist (p js2-mode-deferred-properties)
10723 (apply #'put-text-property p))
10724 (setq js2-mode-deferred-properties nil))
10725
10726 (defun js2-mode-show-errors ()
10727 "Highlight syntax errors."
10728 (when js2-mode-show-parse-errors
10729 (dolist (e (js2-ast-root-errors js2-mode-ast))
10730 (js2-mode-show-warn-or-err e 'js2-error-face))))
10731
10732 (defun js2-mode-remove-suppressed-warnings ()
10733 "Take suppressed warnings out of the AST warnings list.
10734 This ensures that the counts and `next-error' are correct."
10735 (setf (js2-ast-root-warnings js2-mode-ast)
10736 (js2-delete-if
10737 (lambda (e)
10738 (let ((key (caar e)))
10739 (or
10740 (and (not js2-strict-trailing-comma-warning)
10741 (string-match "trailing\\.comma" key))
10742 (and (not js2-strict-cond-assign-warning)
10743 (string= key "msg.equal.as.assign"))
10744 (and js2-missing-semi-one-line-override
10745 (string= key "msg.missing.semi")
10746 (let* ((beg (second e))
10747 (node (js2-node-at-point beg))
10748 (fn (js2-mode-find-parent-fn node))
10749 (body (and fn (js2-function-node-body fn)))
10750 (lc (and body (js2-node-abs-pos body)))
10751 (rc (and lc (+ lc (js2-node-len body)))))
10752 (and fn
10753 (or (null body)
10754 (save-excursion
10755 (goto-char beg)
10756 (and (js2-same-line lc)
10757 (js2-same-line rc))))))))))
10758 (js2-ast-root-warnings js2-mode-ast))))
10759
10760 (defun js2-mode-show-warnings ()
10761 "Highlight strict-mode warnings."
10762 (when js2-mode-show-strict-warnings
10763 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10764 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10765
10766 (defun js2-echo-error (old-point new-point)
10767 "Called by point-motion hooks."
10768 (let ((msg (get-text-property new-point 'help-echo)))
10769 (if (and msg (or (not (current-message))
10770 (string= (current-message) "Quit")))
10771 (message msg))))
10772
10773 (defalias #'js2-echo-help #'js2-echo-error)
10774
10775 (defun js2-enter-key ()
10776 "Handle user pressing the Enter key."
10777 (interactive)
10778 (let ((parse-status (save-excursion
10779 (syntax-ppss (point))))
10780 (js2-bounce-indent-p nil))
10781 (cond
10782 ;; check if we're inside a string
10783 ((nth 3 parse-status)
10784 (if js2-concat-multiline-strings
10785 (js2-mode-split-string parse-status)
10786 (insert "\n")))
10787 ;; check if inside a block comment
10788 ((nth 4 parse-status)
10789 (js2-mode-extend-comment))
10790 (t
10791 ;; should probably figure out what the mode-map says we should do
10792 (if js2-indent-on-enter-key
10793 (js2-indent-line))
10794 (insert "\n")
10795 (if js2-enter-indents-newline
10796 (js2-indent-line))))))
10797
10798 (defun js2-mode-split-string (parse-status)
10799 "Turn a newline in mid-string into a string concatenation.
10800 PARSE-STATUS is as documented in `parse-partial-sexp'."
10801 (let* ((col (current-column))
10802 (quote-char (nth 3 parse-status))
10803 (quote-string (string quote-char))
10804 (string-beg (nth 8 parse-status))
10805 (at-eol (eq js2-concat-multiline-strings 'eol))
10806 (indent (save-match-data
10807 (or
10808 (save-excursion
10809 (back-to-indentation)
10810 (if (looking-at "\\+")
10811 (current-column)))
10812 (save-excursion
10813 (goto-char string-beg)
10814 (if (looking-back "\\+\\s-+")
10815 (goto-char (match-beginning 0)))
10816 (current-column))))))
10817 (insert quote-char)
10818 (if at-eol
10819 (insert " +\n")
10820 (insert "\n"))
10821 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10822 (indent-to indent)
10823 (unless at-eol
10824 (insert "+ "))
10825 (insert quote-string)
10826 (when (eolp)
10827 (insert quote-string)
10828 (backward-char 1))))
10829
10830 (defun js2-mode-extend-comment ()
10831 "Indent the line and, when inside a comment block, add comment prefix."
10832 (let (star single col first-line needs-close)
10833 (save-excursion
10834 (back-to-indentation)
10835 (cond
10836 ((looking-at "\\*[^/]")
10837 (setq star t
10838 col (current-column)))
10839 ((looking-at "/\\*")
10840 (setq star t
10841 first-line t
10842 col (1+ (current-column))))
10843 ((looking-at "//")
10844 (setq single t
10845 col (current-column)))))
10846 ;; Heuristic for whether we need to close the comment:
10847 ;; if we've got a parse error here, assume it's an unterminated
10848 ;; comment.
10849 (setq needs-close
10850 (or
10851 (eq (get-text-property (1- (point)) 'point-entered)
10852 'js2-echo-error)
10853 ;; The heuristic above doesn't work well when we're
10854 ;; creating a comment and there's another one downstream,
10855 ;; as our parser thinks this one ends at the end of the
10856 ;; next one. (You can have a /* inside a js block comment.)
10857 ;; So just close it if the next non-ws char isn't a *.
10858 (and first-line
10859 (eolp)
10860 (save-excursion
10861 (skip-chars-forward " \t\r\n")
10862 (not (eq (char-after) ?*))))))
10863 (insert "\n")
10864 (cond
10865 (star
10866 (indent-to col)
10867 (insert "* ")
10868 (if (and first-line needs-close)
10869 (save-excursion
10870 (insert "\n")
10871 (indent-to col)
10872 (insert "*/"))))
10873 ((and single
10874 (save-excursion
10875 (and (zerop (forward-line 1))
10876 (looking-at "\\s-*//"))))
10877 (indent-to col)
10878 (insert "// "))
10879 ;; don't need to extend the comment after all
10880 (js2-enter-indents-newline
10881 (js2-indent-line)))))
10882
10883 (defun js2-beginning-of-line ()
10884 "Toggles point between bol and first non-whitespace char in line.
10885 Also moves past comment delimiters when inside comments."
10886 (interactive)
10887 (let (node beg)
10888 (cond
10889 ((bolp)
10890 (back-to-indentation))
10891 ((looking-at "//")
10892 (skip-chars-forward "/ \t"))
10893 ((and (eq (char-after) ?*)
10894 (setq node (js2-comment-at-point))
10895 (memq (js2-comment-node-format node) '(jsdoc block))
10896 (save-excursion
10897 (skip-chars-backward " \t")
10898 (bolp)))
10899 (skip-chars-forward "\* \t"))
10900 (t
10901 (goto-char (point-at-bol))))))
10902
10903 (defun js2-end-of-line ()
10904 "Toggles point between eol and last non-whitespace char in line."
10905 (interactive)
10906 (if (eolp)
10907 (skip-chars-backward " \t")
10908 (goto-char (point-at-eol))))
10909
10910 (defun js2-enter-mirror-mode()
10911 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10912 on insertion."
10913 (interactive)
10914 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10915 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10916 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10917 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10918 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10919 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10920 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10921 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10922
10923 (defun js2-leave-mirror-mode()
10924 "Turns off mirror mode."
10925 (interactive)
10926 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10927 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10928
10929 (defsubst js2-mode-inside-string ()
10930 "Return non-nil if inside a string.
10931 Actually returns the quote character that begins the string."
10932 (let ((parse-state (save-excursion
10933 (syntax-ppss (point)))))
10934 (nth 3 parse-state)))
10935
10936 (defsubst js2-mode-inside-comment-or-string ()
10937 "Return non-nil if inside a comment or string."
10938 (or
10939 (let ((comment-start
10940 (save-excursion
10941 (goto-char (point-at-bol))
10942 (if (re-search-forward "//" (point-at-eol) t)
10943 (match-beginning 0)))))
10944 (and comment-start
10945 (<= comment-start (point))))
10946 (let ((parse-state (save-excursion
10947 (syntax-ppss (point)))))
10948 (or (nth 3 parse-state)
10949 (nth 4 parse-state)))))
10950
10951 (defsubst js2-make-magic-delimiter (delim &optional pos)
10952 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10953 Sets value of `js2-magic' text property to line number at POS."
10954 (propertize delim
10955 'js2-magic (line-number-at-pos pos)
10956 'font-lock-face 'js2-magic-paren-face))
10957
10958 (defun js2-mode-match-delimiter (open close)
10959 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10960 The rule we use, which as far as we can tell is how Eclipse works,
10961 is that we insert the match if we're not in a comment or string,
10962 and the next non-whitespace character is either punctuation or
10963 occurs on another line."
10964 (insert open)
10965 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10966 (not (js2-mode-inside-comment-or-string)))
10967 (save-excursion
10968 (insert (js2-make-magic-delimiter close)))
10969 (when js2-auto-indent-p
10970 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10971 (js2-indent-line)))))
10972
10973 (defun js2-mode-match-bracket ()
10974 "Insert matching bracket."
10975 (interactive)
10976 (js2-mode-match-delimiter "[" "]"))
10977
10978 (defun js2-mode-match-paren ()
10979 "Insert matching paren unless already inserted."
10980 (interactive)
10981 (js2-mode-match-delimiter "(" ")"))
10982
10983 (defun js2-mode-match-curly (arg)
10984 "Insert matching curly-brace.
10985 With prefix arg, no formatting or indentation will occur -- the close-brace
10986 is simply inserted directly at the point."
10987 (interactive "p")
10988 (let (try-pos)
10989 (cond
10990 (current-prefix-arg
10991 (js2-mode-match-delimiter "{" "}"))
10992 ((and js2-auto-insert-catch-block
10993 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10994 (point-at-bol))
10995 (match-beginning 1))))
10996 (js2-insert-catch-skel try-pos))
10997 (t
10998 ;; Otherwise try to do something smarter.
10999 (insert "{")
11000 (unless (or (not (looking-at "\\s-*$"))
11001 (save-excursion
11002 (skip-chars-forward " \t\r\n")
11003 (and (looking-at "}")
11004 (js2-error-at-point)))
11005 (js2-mode-inside-comment-or-string))
11006 (undo-boundary)
11007 ;; absolutely mystifying bug: when inserting the next "\n",
11008 ;; the buffer-undo-list is given two new entries: the inserted range,
11009 ;; and the incorrect position of the point. It's recorded incorrectly
11010 ;; as being before the opening "{", not after it. But it's recorded
11011 ;; as the correct value if you're debugging `js2-mode-match-curly'
11012 ;; in edebug. I have no idea why it's doing this, but incrementing
11013 ;; the inserted position fixes the problem, so that the undo takes us
11014 ;; back to just after the user-inserted "{".
11015 (insert "\n")
11016 (ignore-errors
11017 (incf (cadr buffer-undo-list)))
11018 (js2-indent-line)
11019 (save-excursion
11020 (insert "\n}")
11021 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11022 (js2-indent-line))))))))
11023
11024 (defun js2-insert-catch-skel (try-pos)
11025 "Complete a try/catch block after inserting a { following a try keyword.
11026 Rationale is that a try always needs a catch or a finally, and the catch is
11027 the more likely of the two.
11028
11029 TRY-POS is the buffer position of the try keyword. The open-curly should
11030 already have been inserted."
11031 (insert "{")
11032 (let ((try-col (save-excursion
11033 (goto-char try-pos)
11034 (current-column))))
11035 (insert "\n")
11036 (undo-boundary)
11037 (js2-indent-line) ;; indent the blank line where cursor will end up
11038 (save-excursion
11039 (insert "\n")
11040 (indent-to try-col)
11041 (insert "} catch (x) {\n\n")
11042 (indent-to try-col)
11043 (insert "}"))))
11044
11045 (defun js2-mode-highlight-magic-parens ()
11046 "Re-highlight magic parens after parsing nukes the 'face prop."
11047 (let ((beg (point-min))
11048 end)
11049 (while (setq beg (next-single-property-change beg 'js2-magic))
11050 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11051 (if (get-text-property beg 'js2-magic)
11052 (js2-with-unmodifying-text-property-changes
11053 (put-text-property beg (or end (1+ beg))
11054 'font-lock-face 'js2-magic-paren-face))))))
11055
11056 (defun js2-mode-mundanify-parens ()
11057 "Clear all magic parens and brackets."
11058 (let ((beg (point-min))
11059 end)
11060 (while (setq beg (next-single-property-change beg 'js2-magic))
11061 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11062 (remove-text-properties beg (or end (1+ beg))
11063 '(js2-magic face)))))
11064
11065 (defsubst js2-match-quote (quote-string)
11066 (let ((start-quote (js2-mode-inside-string)))
11067 (cond
11068 ;; inside a comment - don't do quote-matching, since we can't
11069 ;; reliably figure out if we're in a string inside the comment
11070 ((js2-comment-at-point)
11071 (insert quote-string))
11072 ((not start-quote)
11073 ;; not in string => insert matched quotes
11074 (insert quote-string)
11075 ;; exception: if we're just before a word, don't double it.
11076 (unless (looking-at "[^ \t\r\n]")
11077 (save-excursion
11078 (insert quote-string))))
11079 ((looking-at quote-string)
11080 (if (looking-back "[^\\]\\\\")
11081 (insert quote-string)
11082 (forward-char 1)))
11083 ((and js2-mode-escape-quotes
11084 (save-excursion
11085 (save-match-data
11086 (re-search-forward quote-string (point-at-eol) t))))
11087 ;; inside terminated string, escape quote (unless already escaped)
11088 (insert (if (looking-back "[^\\]\\\\")
11089 quote-string
11090 (concat "\\" quote-string))))
11091 (t
11092 (insert quote-string))))) ; else terminate the string
11093
11094 (defun js2-mode-match-single-quote ()
11095 "Insert matching single-quote."
11096 (interactive)
11097 (let ((parse-status (syntax-ppss (point))))
11098 ;; don't match inside comments, since apostrophe is more common
11099 (if (nth 4 parse-status)
11100 (insert "'")
11101 (js2-match-quote "'"))))
11102
11103 (defun js2-mode-match-double-quote ()
11104 "Insert matching double-quote."
11105 (interactive)
11106 (js2-match-quote "\""))
11107
11108 ;; Eclipse works as follows:
11109 ;; * type an open-paren and it auto-inserts close-paren
11110 ;; - auto-inserted paren gets a green bracket
11111 ;; - green bracket means typing close-paren there will skip it
11112 ;; * if you insert any text on a different line, it turns off
11113 (defun js2-mode-magic-close-paren ()
11114 "Skip over close-paren rather than inserting, where appropriate."
11115 (interactive)
11116 (let* ((here (point))
11117 (parse-status (syntax-ppss here))
11118 (open-pos (nth 1 parse-status))
11119 (close last-input-event)
11120 (open (cond
11121 ((eq close ?\))
11122 ?\()
11123 ((eq close ?\])
11124 ?\[)
11125 ((eq close ?})
11126 ?{)
11127 (t nil))))
11128 (if (and (eq (char-after) close)
11129 (eq open (char-after open-pos))
11130 (js2-same-line open-pos)
11131 (get-text-property here 'js2-magic))
11132 (progn
11133 (remove-text-properties here (1+ here) '(js2-magic face))
11134 (forward-char 1))
11135 (insert-char close 1))
11136 (blink-matching-open)))
11137
11138 (defun js2-mode-wait-for-parse (callback)
11139 "Invoke CALLBACK when parsing is finished.
11140 If parsing is already finished, calls CALLBACK immediately."
11141 (if (not js2-mode-buffer-dirty-p)
11142 (funcall callback)
11143 (push callback js2-mode-pending-parse-callbacks)
11144 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11145
11146 (defun js2-mode-parse-finished ()
11147 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11148 ;; We can't let errors propagate up, since it prevents the
11149 ;; `js2-parse' method from completing normally and returning
11150 ;; the ast, which makes things mysteriously not work right.
11151 (unwind-protect
11152 (dolist (cb js2-mode-pending-parse-callbacks)
11153 (condition-case err
11154 (funcall cb)
11155 (error (message "%s" err))))
11156 (setq js2-mode-pending-parse-callbacks nil)))
11157
11158 (defun js2-mode-flag-region (from to flag)
11159 "Hide or show text from FROM to TO, according to FLAG.
11160 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11161 Returns the created overlay if FLAG is non-nil."
11162 (remove-overlays from to 'invisible 'js2-outline)
11163 (when flag
11164 (let ((o (make-overlay from to)))
11165 (overlay-put o 'invisible 'js2-outline)
11166 (overlay-put o 'isearch-open-invisible
11167 'js2-isearch-open-invisible)
11168 o)))
11169
11170 ;; Function to be set as an outline-isearch-open-invisible' property
11171 ;; to the overlay that makes the outline invisible (see
11172 ;; `js2-mode-flag-region').
11173 (defun js2-isearch-open-invisible (overlay)
11174 ;; We rely on the fact that isearch places point on the matched text.
11175 (js2-mode-show-element))
11176
11177 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11178 "Return cons cell of bounds of folding overlay at POS.
11179 Returns nil if not found."
11180 (let ((overlays (overlays-at (or pos (point))))
11181 o)
11182 (while (and overlays
11183 (not o))
11184 (if (overlay-get (car overlays) 'invisible)
11185 (setq o (car overlays))
11186 (setq overlays (cdr overlays))))
11187 (if o
11188 (cons (overlay-start o) (overlay-end o)))))
11189
11190 (defun js2-mode-function-at-point (&optional pos)
11191 "Return the innermost function node enclosing current point.
11192 Returns nil if point is not in a function."
11193 (let ((node (js2-node-at-point pos)))
11194 (while (and node (not (js2-function-node-p node)))
11195 (setq node (js2-node-parent node)))
11196 (if (js2-function-node-p node)
11197 node)))
11198
11199 (defun js2-mode-toggle-element ()
11200 "Hide or show the foldable element at the point."
11201 (interactive)
11202 (let (comment fn pos)
11203 (save-excursion
11204 (save-match-data
11205 (cond
11206 ;; /* ... */ comment?
11207 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11208 (if (js2-mode-invisible-overlay-bounds
11209 (setq pos (+ 3 (js2-node-abs-pos comment))))
11210 (progn
11211 (goto-char pos)
11212 (js2-mode-show-element))
11213 (js2-mode-hide-element)))
11214 ;; //-comment?
11215 ((save-excursion
11216 (back-to-indentation)
11217 (looking-at js2-mode-//-comment-re))
11218 (js2-mode-toggle-//-comment))
11219 ;; function?
11220 ((setq fn (js2-mode-function-at-point))
11221 (setq pos (and (js2-function-node-body fn)
11222 (js2-node-abs-pos (js2-function-node-body fn))))
11223 (goto-char (1+ pos))
11224 (if (js2-mode-invisible-overlay-bounds)
11225 (js2-mode-show-element)
11226 (js2-mode-hide-element)))
11227 (t
11228 (message "Nothing at point to hide or show")))))))
11229
11230 (defun js2-mode-hide-element ()
11231 "Fold/hide contents of a block, showing ellipses.
11232 Show the hidden text with \\[js2-mode-show-element]."
11233 (interactive)
11234 (if js2-mode-buffer-dirty-p
11235 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11236 (let (node body beg end)
11237 (cond
11238 ((js2-mode-invisible-overlay-bounds)
11239 (message "already hidden"))
11240 (t
11241 (setq node (js2-node-at-point))
11242 (cond
11243 ((js2-block-comment-p node)
11244 (js2-mode-hide-comment node))
11245 (t
11246 (while (and node (not (js2-function-node-p node)))
11247 (setq node (js2-node-parent node)))
11248 (if (and node
11249 (setq body (js2-function-node-body node)))
11250 (progn
11251 (setq beg (js2-node-abs-pos body)
11252 end (+ beg (js2-node-len body)))
11253 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11254 (message "No collapsable element found at point"))))))))
11255
11256 (defun js2-mode-show-element ()
11257 "Show the hidden element at current point."
11258 (interactive)
11259 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11260 (if bounds
11261 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11262 (message "Nothing to un-hide"))))
11263
11264 (defun js2-mode-show-all ()
11265 "Show all of the text in the buffer."
11266 (interactive)
11267 (js2-mode-flag-region (point-min) (point-max) nil))
11268
11269 (defun js2-mode-toggle-hide-functions ()
11270 (interactive)
11271 (if js2-mode-functions-hidden
11272 (js2-mode-show-functions)
11273 (js2-mode-hide-functions)))
11274
11275 (defun js2-mode-hide-functions ()
11276 "Hides all non-nested function bodies in the buffer.
11277 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11278 to open an individual entry."
11279 (interactive)
11280 (if js2-mode-buffer-dirty-p
11281 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11282 (if (null js2-mode-ast)
11283 (message "Oops - parsing failed")
11284 (setq js2-mode-functions-hidden t)
11285 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11286
11287 (defun js2-mode-function-hider (n endp)
11288 (when (not endp)
11289 (let ((tt (js2-node-type n))
11290 body beg end)
11291 (cond
11292 ((and (= tt js2-FUNCTION)
11293 (setq body (js2-function-node-body n)))
11294 (setq beg (js2-node-abs-pos body)
11295 end (+ beg (js2-node-len body)))
11296 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11297 nil) ; don't process children of function
11298 (t
11299 t))))) ; keep processing other AST nodes
11300
11301 (defun js2-mode-show-functions ()
11302 "Un-hide any folded function bodies in the buffer."
11303 (interactive)
11304 (setq js2-mode-functions-hidden nil)
11305 (save-excursion
11306 (goto-char (point-min))
11307 (while (/= (goto-char (next-overlay-change (point)))
11308 (point-max))
11309 (dolist (o (overlays-at (point)))
11310 (when (and (overlay-get o 'invisible)
11311 (not (overlay-get o 'comment)))
11312 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11313
11314 (defun js2-mode-hide-comment (n)
11315 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11316 3 ; /**
11317 2)) ; /*
11318 (beg (+ (js2-node-abs-pos n) head))
11319 (end (- (+ beg (js2-node-len n)) head 2))
11320 (o (js2-mode-flag-region beg end 'hide)))
11321 (overlay-put o 'comment t)))
11322
11323 (defun js2-mode-toggle-hide-comments ()
11324 "Folds all block comments in the buffer.
11325 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11326 to open an individual entry."
11327 (interactive)
11328 (if js2-mode-comments-hidden
11329 (js2-mode-show-comments)
11330 (js2-mode-hide-comments)))
11331
11332 (defun js2-mode-hide-comments ()
11333 (interactive)
11334 (if js2-mode-buffer-dirty-p
11335 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11336 (if (null js2-mode-ast)
11337 (message "Oops - parsing failed")
11338 (setq js2-mode-comments-hidden t)
11339 (dolist (n (js2-ast-root-comments js2-mode-ast))
11340 (let ((format (js2-comment-node-format n)))
11341 (when (js2-block-comment-p n)
11342 (js2-mode-hide-comment n))))
11343 (js2-mode-hide-//-comments)))
11344
11345 (defsubst js2-mode-extend-//-comment (direction)
11346 "Find start or end of a block of similar //-comment lines.
11347 DIRECTION is -1 to look back, 1 to look forward.
11348 INDENT is the indentation level to match.
11349 Returns the end-of-line position of the furthest adjacent
11350 //-comment line with the same indentation as the current line.
11351 If there is no such matching line, returns current end of line."
11352 (let ((pos (point-at-eol))
11353 (indent (current-indentation)))
11354 (save-excursion
11355 (save-match-data
11356 (while (and (zerop (forward-line direction))
11357 (looking-at js2-mode-//-comment-re)
11358 (eq indent (length (match-string 1))))
11359 (setq pos (point-at-eol)))
11360 pos))))
11361
11362 (defun js2-mode-hide-//-comments ()
11363 "Fold adjacent 1-line comments, showing only snippet of first one."
11364 (let (beg end)
11365 (save-excursion
11366 (save-match-data
11367 (goto-char (point-min))
11368 (while (re-search-forward js2-mode-//-comment-re nil t)
11369 (setq beg (point)
11370 end (js2-mode-extend-//-comment 1))
11371 (unless (eq beg end)
11372 (overlay-put (js2-mode-flag-region beg end 'hide)
11373 'comment t))
11374 (goto-char end)
11375 (forward-char 1))))))
11376
11377 (defun js2-mode-toggle-//-comment ()
11378 "Fold or un-fold any multi-line //-comment at point.
11379 Caller should have determined that this line starts with a //-comment."
11380 (let* ((beg (point-at-eol))
11381 (end beg))
11382 (save-excursion
11383 (goto-char end)
11384 (if (js2-mode-invisible-overlay-bounds)
11385 (js2-mode-show-element)
11386 ;; else hide the comment
11387 (setq beg (js2-mode-extend-//-comment -1)
11388 end (js2-mode-extend-//-comment 1))
11389 (unless (eq beg end)
11390 (overlay-put (js2-mode-flag-region beg end 'hide)
11391 'comment t))))))
11392
11393 (defun js2-mode-show-comments ()
11394 "Un-hide any hidden comments, leaving other hidden elements alone."
11395 (interactive)
11396 (setq js2-mode-comments-hidden nil)
11397 (save-excursion
11398 (goto-char (point-min))
11399 (while (/= (goto-char (next-overlay-change (point)))
11400 (point-max))
11401 (dolist (o (overlays-at (point)))
11402 (when (overlay-get o 'comment)
11403 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11404
11405 (defun js2-mode-display-warnings-and-errors ()
11406 "Turn on display of warnings and errors."
11407 (interactive)
11408 (setq js2-mode-show-parse-errors t
11409 js2-mode-show-strict-warnings t)
11410 (js2-reparse 'force))
11411
11412 (defun js2-mode-hide-warnings-and-errors ()
11413 "Turn off display of warnings and errors."
11414 (interactive)
11415 (setq js2-mode-show-parse-errors nil
11416 js2-mode-show-strict-warnings nil)
11417 (js2-reparse 'force))
11418
11419 (defun js2-mode-toggle-warnings-and-errors ()
11420 "Toggle the display of warnings and errors.
11421 Some users don't like having warnings/errors reported while they type."
11422 (interactive)
11423 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11424 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11425 (if (interactive-p)
11426 (message "warnings and errors %s"
11427 (if js2-mode-show-parse-errors
11428 "enabled"
11429 "disabled")))
11430 (js2-reparse 'force))
11431
11432 (defun js2-mode-customize ()
11433 (interactive)
11434 (customize-group 'js2-mode))
11435
11436 (defun js2-mode-forward-sexp (&optional arg)
11437 "Move forward across one statement or balanced expression.
11438 With ARG, do it that many times. Negative arg -N means
11439 move backward across N balanced expressions."
11440 (interactive "p")
11441 (setq arg (or arg 1))
11442 (save-restriction
11443 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11444 (js2-reparse))
11445 (let ((scan-msg "Containing expression ends prematurely")
11446 node (start (point)) pos lp rp child)
11447 (cond
11448 ;; backward-sexp
11449 ;; could probably make this better for some cases:
11450 ;; - if in statement block (e.g. function body), go to parent
11451 ;; - infix exprs like (foo in bar) - maybe go to beginning
11452 ;; of infix expr if in the right-side expression?
11453 ((and arg (minusp arg))
11454 (dotimes (i (- arg))
11455 (js2-backward-sws)
11456 (forward-char -1) ; enter the node we backed up to
11457 (when (setq node (js2-node-at-point (point) t))
11458 (setq pos (js2-node-abs-pos node))
11459 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11460 (setq lp (car parens)
11461 rp (cdr parens))))
11462 (goto-char
11463 (or (when (and lp (> start lp))
11464 (if (and rp (<= start rp))
11465 (if (setq child (js2-node-closest-child node (point) lp t))
11466 (js2-node-abs-pos child)
11467 (goto-char start)
11468 (signal 'scan-error (list scan-msg lp lp)))
11469 lp))
11470 pos
11471 (point-min)))))
11472 (t
11473 ;; forward-sexp
11474 (js2-forward-sws)
11475 (dotimes (i arg)
11476 (js2-forward-sws)
11477 (when (setq node (js2-node-at-point (point) t))
11478 (setq pos (js2-node-abs-pos node))
11479 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11480 (setq lp (car parens)
11481 rp (cdr parens))))
11482 (goto-char
11483 (or (when (and rp (<= start rp))
11484 (if (> start lp)
11485 (if (setq child (js2-node-closest-child node (point) rp))
11486 (js2-node-abs-end child)
11487 (goto-char start)
11488 (signal 'scan-error (list scan-msg rp (1+ rp))))
11489 (1+ rp)))
11490 (and pos
11491 (+ pos
11492 (js2-node-len
11493 (if (js2-expr-stmt-node-p (js2-node-parent node))
11494 ;; stop after the semicolon
11495 (js2-node-parent node)
11496 node))))
11497 (point-max))))))))
11498
11499 (defun js2-mode-forward-sexp-parens (node abs-pos)
11500 (cond
11501 ((or (js2-array-node-p node)
11502 (js2-object-node-p node)
11503 (js2-array-comp-node-p node)
11504 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11505 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11506 ((js2-paren-expr-node-p node)
11507 (let ((lp (js2-node-lp node))
11508 (rp (js2-node-rp node)))
11509 (cons (when lp (+ abs-pos lp))
11510 (when rp (+ abs-pos rp)))))))
11511
11512 (defun js2-node-closest-child (parent point limit &optional before)
11513 (let* ((parent-pos (js2-node-abs-pos parent))
11514 (rpoint (- point parent-pos))
11515 (rlimit (- limit parent-pos))
11516 (min (min rpoint rlimit))
11517 (max (max rpoint rlimit))
11518 found)
11519 (catch 'done
11520 (js2-visit-ast
11521 parent
11522 (lambda (node end-p)
11523 (if (eq node parent)
11524 t
11525 (let ((pos (js2-node-pos node)) ;; Both relative values.
11526 (end (+ (js2-node-pos node) (js2-node-len node))))
11527 (when (and (>= pos min) (<= end max)
11528 (if before (< pos rpoint) (> end rpoint)))
11529 (setq found node))
11530 (when (> end rpoint)
11531 (throw 'done nil)))
11532 nil))))
11533 found))
11534
11535 (defun js2-next-error (&optional arg reset)
11536 "Move to next parse error.
11537 Typically invoked via \\[next-error].
11538 ARG is the number of errors, forward or backward, to move.
11539 RESET means start over from the beginning."
11540 (interactive "p")
11541 (if (or (null js2-mode-ast)
11542 (and (null (js2-ast-root-errors js2-mode-ast))
11543 (null (js2-ast-root-warnings js2-mode-ast))))
11544 (message "No errors")
11545 (when reset
11546 (goto-char (point-min)))
11547 (let* ((errs (copy-sequence
11548 (append (js2-ast-root-errors js2-mode-ast)
11549 (js2-ast-root-warnings js2-mode-ast))))
11550 (continue t)
11551 (start (point))
11552 (count (or arg 1))
11553 (backward (minusp count))
11554 (sorter (if backward '> '<))
11555 (stopper (if backward '< '>))
11556 (count (abs count))
11557 all-errs
11558 err)
11559 ;; sort by start position
11560 (setq errs (sort errs (lambda (e1 e2)
11561 (funcall sorter (second e1) (second e2))))
11562 all-errs errs)
11563 ;; find nth error with pos > start
11564 (while (and errs continue)
11565 (when (funcall stopper (cadar errs) start)
11566 (setq err (car errs))
11567 (if (zerop (decf count))
11568 (setq continue nil)))
11569 (setq errs (cdr errs)))
11570 (if err
11571 (goto-char (second err))
11572 ;; wrap around to first error
11573 (goto-char (second (car all-errs)))
11574 ;; if we were already on it, echo msg again
11575 (if (= (point) start)
11576 (js2-echo-error (point) (point)))))))
11577
11578 (defun js2-down-mouse-3 ()
11579 "Make right-click move the point to the click location.
11580 This makes right-click context menu operations a bit more intuitive.
11581 The point will not move if the region is active, however, to avoid
11582 destroying the region selection."
11583 (interactive)
11584 (when (and js2-move-point-on-right-click
11585 (not mark-active))
11586 (let ((e last-input-event))
11587 (ignore-errors
11588 (goto-char (cadadr e))))))
11589
11590 (defun js2-mode-create-imenu-index ()
11591 "Return an alist for `imenu--index-alist'."
11592 ;; This is built up in `js2-parse-record-imenu' during parsing.
11593 (when js2-mode-ast
11594 ;; if we have an ast but no recorder, they're requesting a rescan
11595 (unless js2-imenu-recorder
11596 (js2-reparse 'force))
11597 (prog1
11598 (js2-build-imenu-index)
11599 (setq js2-imenu-recorder nil
11600 js2-imenu-function-map nil))))
11601
11602 (defun js2-mode-find-tag ()
11603 "Replacement for `find-tag-default'.
11604 `find-tag-default' returns a ridiculous answer inside comments."
11605 (let (beg end)
11606 (js2-with-underscore-as-word-syntax
11607 (save-excursion
11608 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11609 (looking-back "[A-Za-z0-9_$]"))
11610 (setq beg (progn (forward-word -1) (point))
11611 end (progn (forward-word 1) (point)))
11612 (setq beg (progn (forward-word 1) (point))
11613 end (progn (forward-word -1) (point))))
11614 (replace-regexp-in-string
11615 "[\"']" ""
11616 (buffer-substring-no-properties beg end))))))
11617
11618 (defun js2-mode-forward-sibling ()
11619 "Move to the end of the sibling following point in parent.
11620 Returns non-nil if successful, or nil if there was no following sibling."
11621 (let* ((node (js2-node-at-point))
11622 (parent (js2-mode-find-enclosing-fn node))
11623 sib)
11624 (when (setq sib (js2-node-find-child-after (point) parent))
11625 (goto-char (+ (js2-node-abs-pos sib)
11626 (js2-node-len sib))))))
11627
11628 (defun js2-mode-backward-sibling ()
11629 "Move to the beginning of the sibling node preceding point in parent.
11630 Parent is defined as the enclosing script or function."
11631 (let* ((node (js2-node-at-point))
11632 (parent (js2-mode-find-enclosing-fn node))
11633 sib)
11634 (when (setq sib (js2-node-find-child-before (point) parent))
11635 (goto-char (js2-node-abs-pos sib)))))
11636
11637 (defun js2-beginning-of-defun (&optional arg)
11638 "Go to line on which current function starts, and return t on success.
11639 If we're not in a function or already at the beginning of one, go
11640 to beginning of previous script-level element.
11641 With ARG N, do that N times. If N is negative, move forward."
11642 (setq arg (or arg 1))
11643 (if (plusp arg)
11644 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11645 (when (cond
11646 ((js2-function-node-p parent)
11647 (goto-char (js2-node-abs-pos parent)))
11648 (t
11649 (js2-mode-backward-sibling)))
11650 (if (> arg 1)
11651 (js2-beginning-of-defun (1- arg))
11652 t)))
11653 (when (js2-end-of-defun)
11654 (if (>= arg -1)
11655 (js2-beginning-of-defun 1)
11656 (js2-beginning-of-defun (1+ arg))))))
11657
11658 (defun js2-end-of-defun ()
11659 "Go to the char after the last position of the current function
11660 or script-level element."
11661 (let* ((node (js2-node-at-point))
11662 (parent (or (and (js2-function-node-p node) node)
11663 (js2-node-parent-script-or-fn node)))
11664 script)
11665 (unless (js2-function-node-p parent)
11666 ;; use current script-level node, or, if none, the next one
11667 (setq script (or parent node))
11668 (setq parent (js2-node-find-child-before (point) script))
11669 (when (or (null parent)
11670 (>= (point) (+ (js2-node-abs-pos parent)
11671 (js2-node-len parent))))
11672 (setq parent (js2-node-find-child-after (point) script))))
11673 (when parent
11674 (goto-char (+ (js2-node-abs-pos parent)
11675 (js2-node-len parent))))))
11676
11677 (defun js2-mark-defun (&optional allow-extend)
11678 "Put mark at end of this function, point at beginning.
11679 The function marked is the one that contains point.
11680
11681 Interactively, if this command is repeated,
11682 or (in Transient Mark mode) if the mark is active,
11683 it marks the next defun after the ones already marked."
11684 (interactive "p")
11685 (let (extended)
11686 (when (and allow-extend
11687 (or (and (eq last-command this-command) (mark t))
11688 (and transient-mark-mode mark-active)))
11689 (let ((sib (save-excursion
11690 (goto-char (mark))
11691 (if (js2-mode-forward-sibling)
11692 (point))))
11693 node)
11694 (if sib
11695 (progn
11696 (set-mark sib)
11697 (setq extended t))
11698 ;; no more siblings - try extending to enclosing node
11699 (goto-char (mark t)))))
11700 (when (not extended)
11701 (let ((node (js2-node-at-point (point) t)) ; skip comments
11702 ast fn stmt parent beg end)
11703 (when (js2-ast-root-p node)
11704 (setq ast node
11705 node (or (js2-node-find-child-after (point) node)
11706 (js2-node-find-child-before (point) node))))
11707 ;; only mark whole buffer if we can't find any children
11708 (if (null node)
11709 (setq node ast))
11710 (if (js2-function-node-p node)
11711 (setq parent node)
11712 (setq fn (js2-mode-find-enclosing-fn node)
11713 stmt (if (or (null fn)
11714 (js2-ast-root-p fn))
11715 (js2-mode-find-first-stmt node))
11716 parent (or stmt fn)))
11717 (setq beg (js2-node-abs-pos parent)
11718 end (+ beg (js2-node-len parent)))
11719 (push-mark beg)
11720 (goto-char end)
11721 (exchange-point-and-mark)))))
11722
11723 (defun js2-narrow-to-defun ()
11724 "Narrow to the function enclosing point."
11725 (interactive)
11726 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11727 (fn (if (js2-script-node-p node)
11728 node
11729 (js2-mode-find-enclosing-fn node)))
11730 (beg (js2-node-abs-pos fn)))
11731 (unless (js2-ast-root-p fn)
11732 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11733
11734 (provide 'js2-mode)
11735
11736 ;;; js2-mode.el ends here