]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Don't need `funcall` where FUNCTION is constant
[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 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; Installation:
47 ;;
48 ;; To install it as your major mode for JavaScript editing:
49
50 ;; (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
51
52 ;; Alternately, to install it as a minor mode just for JavaScript linting,
53 ;; you must add it to the appropriate major-mode hook. Normally this would be:
54
55 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
56
57 ;; To customize how it works:
58 ;; M-x customize-group RET js2-mode RET
59
60 ;; Notes:
61
62 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
63 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
64 ;; `js2-mode' current as the EcmaScript language standard evolves.
65
66 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
67 ;; customizable. It is a surprising amount of work to support customizable
68 ;; indentation. The current compromise is that the tab key lets you cycle among
69 ;; various likely indentation points, similar to the behavior of python-mode.
70
71 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
72 ;; and `mumamo', although it could be made to do so with some effort.
73 ;; This means that `js2-mode' is currently only useful for editing JavaScript
74 ;; files, and not for editing JavaScript within <script> tags or templates.
75
76 ;;; Code:
77
78 (eval-when-compile
79 (require 'cl))
80
81 (require 'imenu)
82 (require 'cc-cmds) ; for `c-fill-paragraph'
83
84 (eval-and-compile
85 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
86 (require 'cc-langs) ; it's here in Emacs 21...
87 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
88
89 (defvar electric-layout-rules)
90
91 ;;; Externs (variables presumed to be defined by the host system)
92
93 (defvar js2-ecma-262-externs
94 (mapcar 'symbol-name
95 '(Array Boolean Date Error EvalError Function Infinity JSON
96 Math NaN Number Object RangeError ReferenceError RegExp
97 String SyntaxError TypeError URIError arguments
98 decodeURI decodeURIComponent encodeURI
99 encodeURIComponent escape eval isFinite isNaN
100 parseFloat parseInt undefined unescape))
101 "Ecma-262 externs. Included in `js2-externs' by default.")
102
103 (defvar js2-browser-externs
104 (mapcar 'symbol-name
105 '(;; DOM level 1
106 Attr CDATASection CharacterData Comment DOMException
107 DOMImplementation Document DocumentFragment
108 DocumentType Element Entity EntityReference
109 ExceptionCode NamedNodeMap Node NodeList Notation
110 ProcessingInstruction Text
111
112 ;; DOM level 2
113 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
114 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
115 HTMLBodyElement HTMLButtonElement HTMLCollection
116 HTMLDListElement HTMLDirectoryElement HTMLDivElement
117 HTMLDocument HTMLElement HTMLFieldSetElement
118 HTMLFontElement HTMLFormElement HTMLFrameElement
119 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
120 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
121 HTMLImageElement HTMLInputElement HTMLIsIndexElement
122 HTMLLIElement HTMLLabelElement HTMLLegendElement
123 HTMLLinkElement HTMLMapElement HTMLMenuElement
124 HTMLMetaElement HTMLModElement HTMLOListElement
125 HTMLObjectElement HTMLOptGroupElement
126 HTMLOptionElement HTMLOptionsCollection
127 HTMLParagraphElement HTMLParamElement HTMLPreElement
128 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
129 HTMLStyleElement HTMLTableCaptionElement
130 HTMLTableCellElement HTMLTableColElement
131 HTMLTableElement HTMLTableRowElement
132 HTMLTableSectionElement HTMLTextAreaElement
133 HTMLTitleElement HTMLUListElement
134
135 ;; DOM level 3
136 DOMConfiguration DOMError DOMException
137 DOMImplementationList DOMImplementationSource
138 DOMLocator DOMStringList NameList TypeInfo
139 UserDataHandler
140
141 ;; Window
142 window alert confirm document java navigator prompt screen
143 self top
144
145 ;; W3C CSS
146 CSSCharsetRule CSSFontFace CSSFontFaceRule
147 CSSImportRule CSSMediaRule CSSPageRule
148 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
149 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
150 CSSValue CSSValueList Counter DOMImplementationCSS
151 DocumentCSS DocumentStyle ElementCSSInlineStyle
152 LinkStyle MediaList RGBColor Rect StyleSheet
153 StyleSheetList ViewCSS
154
155 ;; W3C Event
156 EventListener EventTarget Event DocumentEvent UIEvent
157 MouseEvent MutationEvent KeyboardEvent
158
159 ;; W3C Range
160 DocumentRange Range RangeException
161
162 ;; W3C XML
163 XPathResult XMLHttpRequest))
164 "Browser externs.
165 You can cause these to be included or excluded with the custom
166 variable `js2-include-browser-externs'.")
167
168 (defvar js2-rhino-externs
169 (mapcar 'symbol-name
170 '(Packages importClass importPackage com org java
171 ;; Global object (shell) externs.
172 defineClass deserialize doctest gc help load
173 loadClass print quit readFile readUrl runCommand seal
174 serialize spawn sync toint32 version))
175 "Mozilla Rhino externs.
176 Set `js2-include-rhino-externs' to t to include them.")
177
178 (defvar js2-gears-externs
179 (mapcar 'symbol-name
180 '(
181 ;; TODO(stevey): add these
182 ))
183 "Google Gears externs.
184 Set `js2-include-gears-externs' to t to include them.")
185
186 ;;; Variables
187
188 (defun js2-mark-safe-local (name pred)
189 "Make the variable NAME buffer-local and mark it as safe file-local
190 variable with predicate PRED."
191 (make-variable-buffer-local name)
192 (put name 'safe-local-variable pred))
193
194 (defcustom js2-highlight-level 2
195 "Amount of syntax highlighting to perform.
196 0 or a negative value means none.
197 1 adds basic syntax highlighting.
198 2 adds highlighting of some Ecma built-in properties.
199 3 adds highlighting of many Ecma built-in functions."
200 :group 'js2-mode
201 :type '(choice (const :tag "None" 0)
202 (const :tag "Basic" 1)
203 (const :tag "Include Properties" 2)
204 (const :tag "Include Functions" 3)))
205
206 (defvar js2-mode-dev-mode-p nil
207 "Non-nil if running in development mode. Normally nil.")
208
209 (defgroup js2-mode nil
210 "An improved JavaScript mode."
211 :group 'languages)
212
213 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
214 (numberp c-basic-offset))
215 c-basic-offset
216 4)
217 "Number of spaces to indent nested statements.
218 Similar to `c-basic-offset'."
219 :group 'js2-mode
220 :type 'integer)
221 (js2-mark-safe-local 'js2-basic-offset 'integerp)
222
223
224 (defcustom js2-bounce-indent-p nil
225 "Non-nil to have indent-line function choose among alternatives.
226 If nil, the indent-line function will indent to a predetermined column
227 based on heuristic guessing. If non-nil, then if the current line is
228 already indented to that predetermined column, indenting will choose
229 another likely column and indent to that spot. Repeated invocation of
230 the indent-line function will cycle among the computed alternatives.
231 See the function `js2-bounce-indent' for details. When it is non-nil,
232 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
233 :type 'boolean
234 :group 'js2-mode)
235
236 (defcustom js2-pretty-multiline-declarations t
237 "Non-nil to line up multiline declarations vertically:
238
239 var a = 10,
240 b = 20,
241 c = 30;
242
243 If the value is not `all', and the first assigned value in
244 declaration is a function/array/object literal spanning several
245 lines, it won't be indented additionally:
246
247 var o = { var bar = 2,
248 foo: 3 vs. o = {
249 }, foo: 3
250 bar = 2; };"
251 :group 'js2-mode
252 :type 'symbol)
253 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
254
255 (defcustom js2-idle-timer-delay 0.2
256 "Delay in secs before re-parsing after user makes changes.
257 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
258 :type 'number
259 :group 'js2-mode)
260 (make-variable-buffer-local 'js2-idle-timer-delay)
261
262 (defcustom js2-dynamic-idle-timer-adjust 0
263 "Positive to adjust `js2-idle-timer-delay' based on file size.
264 The idea is that for short files, parsing is faster so we can be
265 more responsive to user edits without interfering with editing.
266 The buffer length in characters (typically bytes) is divided by
267 this value and used to multiply `js2-idle-timer-delay' for the
268 buffer. For example, a 21k file and 10k adjust yields 21k/10k
269 == 2, so js2-idle-timer-delay is multiplied by 2.
270 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
271 `js2-idle-timer-delay' is not dependent on the file size."
272 :type 'number
273 :group 'js2-mode)
274
275 (defcustom js2-mode-escape-quotes t
276 "Non-nil to disable automatic quote-escaping inside strings."
277 :type 'boolean
278 :group 'js2-mode)
279
280 (defcustom js2-concat-multiline-strings t
281 "Non-nil to automatically turn a newline in mid-string into a
282 string concatenation. When `eol', the '+' will be inserted at the
283 end of the line, otherwise, at the beginning of the next line."
284 :type '(choice (const t) (const eol) (const nil))
285 :group 'js2-mode)
286
287 (defcustom js2-mode-squeeze-spaces t
288 "Non-nil to normalize whitespace when filling in comments.
289 Multiple runs of spaces are converted to a single space."
290 :type 'boolean
291 :group 'js2-mode)
292
293 (defcustom js2-mode-show-parse-errors t
294 "True to highlight parse errors."
295 :type 'boolean
296 :group 'js2-mode)
297
298 (defcustom js2-mode-show-strict-warnings t
299 "Non-nil to emit Ecma strict-mode warnings.
300 Some of the warnings can be individually disabled by other flags,
301 even if this flag is non-nil."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-strict-trailing-comma-warning t
306 "Non-nil to warn about trailing commas in array literals.
307 Ecma-262 forbids them, but many browsers permit them. IE is the
308 big exception, and can produce bugs if you have trailing commas."
309 :type 'boolean
310 :group 'js2-mode)
311
312 (defcustom js2-strict-missing-semi-warning t
313 "Non-nil to warn about semicolon auto-insertion after statement.
314 Technically this is legal per Ecma-262, but some style guides disallow
315 depending on it."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-missing-semi-one-line-override nil
320 "Non-nil to permit missing semicolons in one-line functions.
321 In one-liner functions such as `function identity(x) {return x}'
322 people often omit the semicolon for a cleaner look. If you are
323 such a person, you can suppress the missing-semicolon warning
324 by setting this variable to t."
325 :type 'boolean
326 :group 'js2-mode)
327
328 (defcustom js2-strict-inconsistent-return-warning t
329 "Non-nil to warn about mixing returns with value-returns.
330 It's perfectly legal to have a `return' and a `return foo' in the
331 same function, but it's often an indicator of a bug, and it also
332 interferes with type inference (in systems that support it.)"
333 :type 'boolean
334 :group 'js2-mode)
335
336 (defcustom js2-strict-cond-assign-warning t
337 "Non-nil to warn about expressions like if (a = b).
338 This often should have been '==' instead of '='. If the warning
339 is enabled, you can suppress it on a per-expression basis by
340 parenthesizing the expression, e.g. if ((a = b)) ..."
341 :type 'boolean
342 :group 'js2-mode)
343
344 (defcustom js2-strict-var-redeclaration-warning t
345 "Non-nil to warn about redeclaring variables in a script or function."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-var-hides-function-arg-warning t
350 "Non-nil to warn about a var decl hiding a function argument."
351 :type 'boolean
352 :group 'js2-mode)
353
354 (defcustom js2-skip-preprocessor-directives nil
355 "Non-nil to treat lines beginning with # as comments.
356 Useful for viewing Mozilla JavaScript source code."
357 :type 'boolean
358 :group 'js2-mode)
359
360 (defcustom js2-language-version 200
361 "Configures what JavaScript language version to recognize.
362 Currently versions 150, 160, 170, 180 and 200 are supported,
363 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
364 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
365 yield, and Array comprehensions, and 1.8 adds function closures."
366 :type 'integer
367 :group 'js2-mode)
368
369 (defcustom js2-allow-keywords-as-property-names t
370 "If non-nil, you can use JavaScript keywords as object property names.
371 Examples:
372
373 var foo = {int: 5, while: 6, continue: 7};
374 foo.return = 8;
375
376 Ecma-262 forbids this syntax, but many browsers support it."
377 :type 'boolean
378 :group 'js2-mode)
379
380 (defcustom js2-instanceof-has-side-effects nil
381 "If non-nil, treats the instanceof operator as having side effects.
382 This is useful for xulrunner apps."
383 :type 'boolean
384 :group 'js2-mode)
385
386 (defcustom js2-move-point-on-right-click t
387 "Non-nil to move insertion point when you right-click.
388 This makes right-click context menu behavior a bit more intuitive,
389 since menu operations generally apply to the point. The exception
390 is if there is a region selection, in which case the point does -not-
391 move, so cut/copy/paste can work properly.
392
393 Note that IntelliJ moves the point, and Eclipse leaves it alone,
394 so this behavior is customizable."
395 :group 'js2-mode
396 :type 'boolean)
397
398 (defcustom js2-allow-rhino-new-expr-initializer t
399 "Non-nil to support a Rhino's experimental syntactic construct.
400
401 Rhino supports the ability to follow a `new' expression with an object
402 literal, which is used to set additional properties on the new object
403 after calling its constructor. Syntax:
404
405 new <expr> [ ( arglist ) ] [initializer]
406
407 Hence, this expression:
408
409 new Object {a: 1, b: 2}
410
411 results in an Object with properties a=1 and b=2. This syntax is
412 apparently not configurable in Rhino - it's currently always enabled,
413 as of Rhino version 1.7R2."
414 :type 'boolean
415 :group 'js2-mode)
416
417 (defcustom js2-allow-member-expr-as-function-name nil
418 "Non-nil to support experimental Rhino syntax for function names.
419
420 Rhino supports an experimental syntax configured via the Rhino Context
421 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
422
423 function <member-expr> ( [ arg-list ] ) { <body> }
424
425 Where member-expr is a non-parenthesized 'member expression', which
426 is anything at the grammar level of a new-expression or lower, meaning
427 any expression that does not involve infix or unary operators.
428
429 When <member-expr> is not a simple identifier, then it is syntactic
430 sugar for assigning the anonymous function to the <member-expr>. Hence,
431 this code:
432
433 function a.b().c[2] (x, y) { ... }
434
435 is rewritten as:
436
437 a.b().c[2] = function(x, y) {...}
438
439 which doesn't seem particularly useful, but Rhino permits it."
440 :type 'boolean
441 :group 'js2-mode)
442
443 (defvar js2-mode-version 20120416
444 "Release number for `js2-mode'.")
445
446 ;; scanner variables
447
448 (defmacro js2-deflocal (name value &optional comment)
449 "Define a buffer-local variable NAME with VALUE and COMMENT."
450 `(progn
451 (defvar ,name ,value ,comment)
452 (make-variable-buffer-local ',name)))
453
454 ;; We record the start and end position of each token.
455 (js2-deflocal js2-token-beg 1)
456 (js2-deflocal js2-token-end -1)
457
458 (defvar js2-EOF_CHAR -1
459 "Represents end of stream. Distinct from js2-EOF token type.")
460
461 ;; I originally used symbols to represent tokens, but Rhino uses
462 ;; ints and then sets various flag bits in them, so ints it is.
463 ;; The upshot is that we need a `js2-' prefix in front of each name.
464 (defvar js2-ERROR -1)
465 (defvar js2-EOF 0)
466 (defvar js2-EOL 1)
467 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
468 (defvar js2-LEAVEWITH 3)
469 (defvar js2-RETURN 4)
470 (defvar js2-GOTO 5)
471 (defvar js2-IFEQ 6)
472 (defvar js2-IFNE 7)
473 (defvar js2-SETNAME 8)
474 (defvar js2-BITOR 9)
475 (defvar js2-BITXOR 10)
476 (defvar js2-BITAND 11)
477 (defvar js2-EQ 12)
478 (defvar js2-NE 13)
479 (defvar js2-LT 14)
480 (defvar js2-LE 15)
481 (defvar js2-GT 16)
482 (defvar js2-GE 17)
483 (defvar js2-LSH 18)
484 (defvar js2-RSH 19)
485 (defvar js2-URSH 20)
486 (defvar js2-ADD 21) ; infix plus
487 (defvar js2-SUB 22) ; infix minus
488 (defvar js2-MUL 23)
489 (defvar js2-DIV 24)
490 (defvar js2-MOD 25)
491 (defvar js2-NOT 26)
492 (defvar js2-BITNOT 27)
493 (defvar js2-POS 28) ; unary plus
494 (defvar js2-NEG 29) ; unary minus
495 (defvar js2-NEW 30)
496 (defvar js2-DELPROP 31)
497 (defvar js2-TYPEOF 32)
498 (defvar js2-GETPROP 33)
499 (defvar js2-GETPROPNOWARN 34)
500 (defvar js2-SETPROP 35)
501 (defvar js2-GETELEM 36)
502 (defvar js2-SETELEM 37)
503 (defvar js2-CALL 38)
504 (defvar js2-NAME 39) ; an identifier
505 (defvar js2-NUMBER 40)
506 (defvar js2-STRING 41)
507 (defvar js2-NULL 42)
508 (defvar js2-THIS 43)
509 (defvar js2-FALSE 44)
510 (defvar js2-TRUE 45)
511 (defvar js2-SHEQ 46) ; shallow equality (===)
512 (defvar js2-SHNE 47) ; shallow inequality (!==)
513 (defvar js2-REGEXP 48)
514 (defvar js2-BINDNAME 49)
515 (defvar js2-THROW 50)
516 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
517 (defvar js2-IN 52)
518 (defvar js2-INSTANCEOF 53)
519 (defvar js2-LOCAL_LOAD 54)
520 (defvar js2-GETVAR 55)
521 (defvar js2-SETVAR 56)
522 (defvar js2-CATCH_SCOPE 57)
523 (defvar js2-ENUM_INIT_KEYS 58)
524 (defvar js2-ENUM_INIT_VALUES 59)
525 (defvar js2-ENUM_INIT_ARRAY 60)
526 (defvar js2-ENUM_NEXT 61)
527 (defvar js2-ENUM_ID 62)
528 (defvar js2-THISFN 63)
529 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
530 (defvar js2-ARRAYLIT 65) ; array literal
531 (defvar js2-OBJECTLIT 66) ; object literal
532 (defvar js2-GET_REF 67) ; *reference
533 (defvar js2-SET_REF 68) ; *reference = something
534 (defvar js2-DEL_REF 69) ; delete reference
535 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
536 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
537 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
538
539 ;; XML support
540 (defvar js2-DEFAULTNAMESPACE 73)
541 (defvar js2-ESCXMLATTR 74)
542 (defvar js2-ESCXMLTEXT 75)
543 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
544 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
545 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
546 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
547
548 (defvar js2-first-bytecode js2-ENTERWITH)
549 (defvar js2-last-bytecode js2-REF_NS_NAME)
550
551 (defvar js2-TRY 80)
552 (defvar js2-SEMI 81) ; semicolon
553 (defvar js2-LB 82) ; left and right brackets
554 (defvar js2-RB 83)
555 (defvar js2-LC 84) ; left and right curly-braces
556 (defvar js2-RC 85)
557 (defvar js2-LP 86) ; left and right parens
558 (defvar js2-RP 87)
559 (defvar js2-COMMA 88) ; comma operator
560
561 (defvar js2-ASSIGN 89) ; simple assignment (=)
562 (defvar js2-ASSIGN_BITOR 90) ; |=
563 (defvar js2-ASSIGN_BITXOR 91) ; ^=
564 (defvar js2-ASSIGN_BITAND 92) ; &=
565 (defvar js2-ASSIGN_LSH 93) ; <<=
566 (defvar js2-ASSIGN_RSH 94) ; >>=
567 (defvar js2-ASSIGN_URSH 95) ; >>>=
568 (defvar js2-ASSIGN_ADD 96) ; +=
569 (defvar js2-ASSIGN_SUB 97) ; -=
570 (defvar js2-ASSIGN_MUL 98) ; *=
571 (defvar js2-ASSIGN_DIV 99) ; /=
572 (defvar js2-ASSIGN_MOD 100) ; %=
573
574 (defvar js2-first-assign js2-ASSIGN)
575 (defvar js2-last-assign js2-ASSIGN_MOD)
576
577 (defvar js2-HOOK 101) ; conditional (?:)
578 (defvar js2-COLON 102)
579 (defvar js2-OR 103) ; logical or (||)
580 (defvar js2-AND 104) ; logical and (&&)
581 (defvar js2-INC 105) ; increment/decrement (++ --)
582 (defvar js2-DEC 106)
583 (defvar js2-DOT 107) ; member operator (.)
584 (defvar js2-FUNCTION 108) ; function keyword
585 (defvar js2-EXPORT 109) ; export keyword
586 (defvar js2-IMPORT 110) ; import keyword
587 (defvar js2-IF 111) ; if keyword
588 (defvar js2-ELSE 112) ; else keyword
589 (defvar js2-SWITCH 113) ; switch keyword
590 (defvar js2-CASE 114) ; case keyword
591 (defvar js2-DEFAULT 115) ; default keyword
592 (defvar js2-WHILE 116) ; while keyword
593 (defvar js2-DO 117) ; do keyword
594 (defvar js2-FOR 118) ; for keyword
595 (defvar js2-BREAK 119) ; break keyword
596 (defvar js2-CONTINUE 120) ; continue keyword
597 (defvar js2-VAR 121) ; var keyword
598 (defvar js2-WITH 122) ; with keyword
599 (defvar js2-CATCH 123) ; catch keyword
600 (defvar js2-FINALLY 124) ; finally keyword
601 (defvar js2-VOID 125) ; void keyword
602 (defvar js2-RESERVED 126) ; reserved keywords
603
604 (defvar js2-EMPTY 127)
605
606 ;; Types used for the parse tree - never returned by scanner.
607
608 (defvar js2-BLOCK 128) ; statement block
609 (defvar js2-LABEL 129) ; label
610 (defvar js2-TARGET 130)
611 (defvar js2-LOOP 131)
612 (defvar js2-EXPR_VOID 132) ; expression statement in functions
613 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
614 (defvar js2-JSR 134)
615 (defvar js2-SCRIPT 135) ; top-level node for entire script
616 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
617 (defvar js2-USE_STACK 137)
618 (defvar js2-SETPROP_OP 138) ; x.y op= something
619 (defvar js2-SETELEM_OP 139) ; x[y] op= something
620 (defvar js2-LOCAL_BLOCK 140)
621 (defvar js2-SET_REF_OP 141) ; *reference op= something
622
623 ;; For XML support:
624 (defvar js2-DOTDOT 142) ; member operator (..)
625 (defvar js2-COLONCOLON 143) ; namespace::name
626 (defvar js2-XML 144) ; XML type
627 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
628 (defvar js2-XMLATTR 146) ; @
629 (defvar js2-XMLEND 147)
630
631 ;; Optimizer-only tokens
632 (defvar js2-TO_OBJECT 148)
633 (defvar js2-TO_DOUBLE 149)
634
635 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
636 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
637 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
638 (defvar js2-CONST 153)
639 (defvar js2-SETCONST 154)
640 (defvar js2-SETCONSTVAR 155)
641 (defvar js2-ARRAYCOMP 156)
642 (defvar js2-LETEXPR 157)
643 (defvar js2-WITHEXPR 158)
644 (defvar js2-DEBUGGER 159)
645
646 (defvar js2-COMMENT 160)
647 (defvar js2-ENUM 161) ; for "enum" reserved word
648 (defvar js2-TRIPLEDOT 162) ; for rest parameter
649
650 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
651
652 (defconst js2-debug-print-trees nil)
653
654 ;; Rhino accepts any string or stream as input. Emacs character
655 ;; processing works best in buffers, so we'll assume the input is a
656 ;; buffer. JavaScript strings can be copied into temp buffers before
657 ;; scanning them.
658
659 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
660 ;; They're the Emacs equivalent of instance variables, more or less.
661
662 (js2-deflocal js2-ts-dirty-line nil
663 "Token stream buffer-local variable.
664 Indicates stuff other than whitespace since start of line.")
665
666 (js2-deflocal js2-ts-regexp-flags nil
667 "Token stream buffer-local variable.")
668
669 (js2-deflocal js2-ts-string ""
670 "Token stream buffer-local variable.
671 Last string scanned.")
672
673 (js2-deflocal js2-ts-number nil
674 "Token stream buffer-local variable.
675 Last literal number scanned.")
676
677 (js2-deflocal js2-ts-hit-eof nil
678 "Token stream buffer-local variable.")
679
680 (js2-deflocal js2-ts-line-start 0
681 "Token stream buffer-local variable.")
682
683 (js2-deflocal js2-ts-lineno 1
684 "Token stream buffer-local variable.")
685
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 (js2-deflocal js2-ts-is-xml-attribute nil
694 "Token stream buffer-local variable.")
695
696 (js2-deflocal js2-ts-xml-is-tag-content nil
697 "Token stream buffer-local variable.")
698
699 (js2-deflocal js2-ts-xml-open-tags-count 0
700 "Token stream buffer-local variable.")
701
702 (js2-deflocal js2-ts-string-buffer nil
703 "Token stream buffer-local variable.
704 List of chars built up while scanning various tokens.")
705
706 (js2-deflocal js2-ts-comment-type nil
707 "Token stream buffer-local variable.")
708
709 ;;; Parser variables
710
711 (js2-deflocal js2-parsed-errors nil
712 "List of errors produced during scanning/parsing.")
713
714 (js2-deflocal js2-parsed-warnings nil
715 "List of warnings produced during scanning/parsing.")
716
717 (js2-deflocal js2-recover-from-parse-errors t
718 "Non-nil to continue parsing after a syntax error.
719
720 In recovery mode, the AST will be built in full, and any error
721 nodes will be flagged with appropriate error information. If
722 this flag is nil, a syntax error will result in an error being
723 signaled.
724
725 The variable is automatically buffer-local, because different
726 modes that use the parser will need different settings.")
727
728 (js2-deflocal js2-parse-hook nil
729 "List of callbacks for receiving parsing progress.")
730
731 (defvar js2-parse-finished-hook nil
732 "List of callbacks to notify when parsing finishes.
733 Not called if parsing was interrupted.")
734
735 (js2-deflocal js2-is-eval-code nil
736 "True if we're evaluating code in a string.
737 If non-nil, the tokenizer will record the token text, and the AST nodes
738 will record their source text. Off by default for IDE modes, since the
739 text is available in the buffer.")
740
741 (defvar js2-parse-ide-mode t
742 "Non-nil if the parser is being used for `js2-mode'.
743 If non-nil, the parser will set text properties for fontification
744 and the syntax table. The value should be nil when using the
745 parser as a frontend to an interpreter or byte compiler.")
746
747 ;;; Parser instance variables (buffer-local vars for js2-parse)
748
749 (defconst js2-clear-ti-mask #xFFFF
750 "Mask to clear token information bits.")
751
752 (defconst js2-ti-after-eol (lsh 1 16)
753 "Flag: first token of the source line.")
754
755 (defconst js2-ti-check-label (lsh 1 17)
756 "Flag: indicates to check for label.")
757
758 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
759
760 (js2-deflocal js2-compiler-generate-debug-info t)
761 (js2-deflocal js2-compiler-use-dynamic-scope nil)
762 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
763 (js2-deflocal js2-compiler-xml-available t)
764 (js2-deflocal js2-compiler-optimization-level 0)
765 (js2-deflocal js2-compiler-generating-source t)
766 (js2-deflocal js2-compiler-strict-mode nil)
767 (js2-deflocal js2-compiler-report-warning-as-error nil)
768 (js2-deflocal js2-compiler-generate-observer-count nil)
769 (js2-deflocal js2-compiler-activation-names nil)
770
771 ;; SKIP: sourceURI
772
773 ;; There's a compileFunction method in Context.java - may need it.
774 (js2-deflocal js2-called-by-compile-function nil
775 "True if `js2-parse' was called by `js2-compile-function'.
776 Will only be used when we finish implementing the interpreter.")
777
778 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
779
780 (js2-deflocal js2-current-flagged-token js2-EOF)
781 (js2-deflocal js2-current-token js2-EOF)
782
783 ;; SKIP: node factory - we're going to just call functions directly,
784 ;; and eventually go to a unified AST format.
785
786 (js2-deflocal js2-nesting-of-function 0)
787
788 (js2-deflocal js2-recorded-identifiers nil
789 "Tracks identifiers found during parsing.")
790
791 (js2-deflocal js2-is-in-destructuring nil
792 "True while parsing destructuring expression.")
793
794 (defcustom js2-global-externs nil
795 "A list of any extern names you'd like to consider always declared.
796 This list is global and is used by all `js2-mode' files.
797 You can create buffer-local externs list using `js2-additional-externs'.
798
799 There is also a buffer-local variable `js2-default-externs',
800 which is initialized by default to include the Ecma-262 externs
801 and the standard browser externs. The three lists are all
802 checked during highlighting."
803 :type 'list
804 :group 'js2-mode)
805
806 (js2-deflocal js2-default-externs nil
807 "Default external declarations.
808
809 These are currently only used for highlighting undeclared variables,
810 which only worries about top-level (unqualified) references.
811 As js2-mode's processing improves, we will flesh out this list.
812
813 The initial value is set to `js2-ecma-262-externs', unless you
814 have set `js2-include-browser-externs', in which case the browser
815 externs are also included.
816
817 See `js2-additional-externs' for more information.")
818
819 (defcustom js2-include-browser-externs t
820 "Non-nil to include browser externs in the master externs list.
821 If you work on JavaScript files that are not intended for browsers,
822 such as Mozilla Rhino server-side JavaScript, set this to nil.
823 You can always include them on a per-file basis by calling
824 `js2-add-browser-externs' from a function on `js2-mode-hook'.
825
826 See `js2-additional-externs' for more information about externs."
827 :type 'boolean
828 :group 'js2-mode)
829
830 (defcustom js2-include-rhino-externs t
831 "Non-nil to include Mozilla Rhino externs in the master externs list.
832 See `js2-additional-externs' for more information about externs."
833 :type 'boolean
834 :group 'js2-mode)
835
836 (defcustom js2-include-gears-externs t
837 "Non-nil to include Google Gears externs in the master externs list.
838 See `js2-additional-externs' for more information about externs."
839 :type 'boolean
840 :group 'js2-mode)
841
842 (js2-deflocal js2-additional-externs nil
843 "A buffer-local list of additional external declarations.
844 It is used to decide whether variables are considered undeclared
845 for purposes of highlighting.
846
847 Each entry is a Lisp string. The string should be the fully qualified
848 name of an external entity. All externs should be added to this list,
849 so that as js2-mode's processing improves it can take advantage of them.
850
851 You may want to declare your externs in three ways.
852 First, you can add externs that are valid for all your JavaScript files.
853 You should probably do this by adding them to `js2-global-externs', which
854 is a global list used for all js2-mode files.
855
856 Next, you can add a function to `js2-mode-hook' that adds additional
857 externs appropriate for the specific file, perhaps based on its path.
858 These should go in `js2-additional-externs', which is buffer-local.
859
860 Finally, you can add a function to `js2-post-parse-callbacks',
861 which is called after parsing completes, and `root' is bound to
862 the root of the parse tree. At this stage you can set up an AST
863 node visitor using `js2-visit-ast' and examine the parse tree
864 for specific import patterns that may imply the existence of
865 other externs, possibly tied to your build system. These should also
866 be added to `js2-additional-externs'.
867
868 Your post-parse callback may of course also use the simpler and
869 faster (but perhaps less robust) approach of simply scanning the
870 buffer text for your imports, using regular expressions.")
871
872 ;; SKIP: decompiler
873 ;; SKIP: encoded-source
874
875 ;;; The following variables are per-function and should be saved/restored
876 ;;; during function parsing...
877
878 (js2-deflocal js2-current-script-or-fn nil)
879 (js2-deflocal js2-current-scope nil)
880 (js2-deflocal js2-nesting-of-with 0)
881 (js2-deflocal js2-label-set nil
882 "An alist mapping label names to nodes.")
883
884 (js2-deflocal js2-loop-set nil)
885 (js2-deflocal js2-loop-and-switch-set nil)
886 (js2-deflocal js2-has-return-value nil)
887 (js2-deflocal js2-end-flags 0)
888
889 ;;; ...end of per function variables
890
891 ;; Without 2-token lookahead, labels are a problem.
892 ;; These vars store the token info of the last matched name,
893 ;; iff it wasn't the last matched token. Only valid in some contexts.
894 (defvar js2-prev-name-token-start nil)
895 (defvar js2-prev-name-token-string nil)
896
897 (defsubst js2-save-name-token-data (pos name)
898 (setq js2-prev-name-token-start pos
899 js2-prev-name-token-string name))
900
901 ;; These flags enumerate the possible ways a statement/function can
902 ;; terminate. These flags are used by endCheck() and by the Parser to
903 ;; detect inconsistent return usage.
904 ;;
905 ;; END_UNREACHED is reserved for code paths that are assumed to always be
906 ;; able to execute (example: throw, continue)
907 ;;
908 ;; END_DROPS_OFF indicates if the statement can transfer control to the
909 ;; next one. Statement such as return dont. A compound statement may have
910 ;; some branch that drops off control to the next statement.
911 ;;
912 ;; END_RETURNS indicates that the statement can return (without arguments)
913 ;; END_RETURNS_VALUE indicates that the statement can return a value.
914 ;;
915 ;; A compound statement such as
916 ;; if (condition) {
917 ;; return value;
918 ;; }
919 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
920
921 (defconst js2-end-unreached #x0)
922 (defconst js2-end-drops-off #x1)
923 (defconst js2-end-returns #x2)
924 (defconst js2-end-returns-value #x4)
925 (defconst js2-end-yields #x8)
926
927 ;; Rhino awkwardly passes a statementLabel parameter to the
928 ;; statementHelper() function, the main statement parser, which
929 ;; is then used by quite a few of the sub-parsers. We just make
930 ;; it a buffer-local variable and make sure it's cleaned up properly.
931 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
932
933 ;; Similarly, Rhino passes an inForInit boolean through about half
934 ;; the expression parsers. We use a dynamically-scoped variable,
935 ;; which makes it easier to funcall the parsers individually without
936 ;; worrying about whether they take the parameter or not.
937 (js2-deflocal js2-in-for-init nil)
938 (js2-deflocal js2-temp-name-counter 0)
939 (js2-deflocal js2-parse-stmt-count 0)
940
941 (defsubst js2-get-next-temp-name ()
942 (format "$%d" (incf js2-temp-name-counter)))
943
944 (defvar js2-parse-interruptable-p t
945 "Set this to nil to force parse to continue until finished.
946 This will mostly be useful for interpreters.")
947
948 (defvar js2-statements-per-pause 50
949 "Pause after this many statements to check for user input.
950 If user input is pending, stop the parse and discard the tree.
951 This makes for a smoother user experience for large files.
952 You may have to wait a second or two before the highlighting
953 and error-reporting appear, but you can always type ahead if
954 you wish. This appears to be more or less how Eclipse, IntelliJ
955 and other editors work.")
956
957 (js2-deflocal js2-record-comments t
958 "Instructs the scanner to record comments in `js2-scanned-comments'.")
959
960 (js2-deflocal js2-scanned-comments nil
961 "List of all comments from the current parse.")
962
963 (defcustom js2-mode-indent-inhibit-undo nil
964 "Non-nil to disable collection of Undo information when indenting lines.
965 Some users have requested this behavior. It's nil by default because
966 other Emacs modes don't work this way."
967 :type 'boolean
968 :group 'js2-mode)
969
970 (defcustom js2-mode-indent-ignore-first-tab nil
971 "If non-nil, ignore first TAB keypress if we look indented properly.
972 It's fairly common for users to navigate to an already-indented line
973 and press TAB for reassurance that it's been indented. For this class
974 of users, we want the first TAB press on a line to be ignored if the
975 line is already indented to one of the precomputed alternatives.
976
977 This behavior is only partly implemented. If you TAB-indent a line,
978 navigate to another line, and then navigate back, it fails to clear
979 the last-indented variable, so it thinks you've already hit TAB once,
980 and performs the indent. A full solution would involve getting on the
981 point-motion hooks for the entire buffer. If we come across another
982 use cases that requires watching point motion, I'll consider doing it.
983
984 If you set this variable to nil, then the TAB key will always change
985 the indentation of the current line, if more than one alternative
986 indentation spot exists."
987 :type 'boolean
988 :group 'js2-mode)
989
990 (defvar js2-indent-hook nil
991 "A hook for user-defined indentation rules.
992
993 Functions on this hook should expect two arguments: (LIST INDEX)
994 The LIST argument is the list of computed indentation points for
995 the current line. INDEX is the list index of the indentation point
996 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
997 indent function is not going to change the current line indentation.
998
999 If a hook function on this list returns a non-nil value, then
1000 `js2-bounce-indent' assumes the hook function has performed its own
1001 indentation, and will do nothing. If all hook functions on the list
1002 return nil, then `js2-bounce-indent' will use its computed indentation
1003 and reindent the line.
1004
1005 When hook functions on this hook list are called, the variable
1006 `js2-mode-ast' may or may not be set, depending on whether the
1007 parse tree is available. If the variable is nil, you can pass a
1008 callback to `js2-mode-wait-for-parse', and your callback will be
1009 called after the new parse tree is built. This can take some time
1010 in large files.")
1011
1012 (defface js2-warning
1013 `((((class color) (background light))
1014 (:underline "orange"))
1015 (((class color) (background dark))
1016 (:underline "orange"))
1017 (t (:underline t)))
1018 "Face for JavaScript warnings."
1019 :group 'js2-mode)
1020
1021 (defface js2-error
1022 `((((class color) (background light))
1023 (:foreground "red"))
1024 (((class color) (background dark))
1025 (:foreground "red"))
1026 (t (:foreground "red")))
1027 "Face for JavaScript errors."
1028 :group 'js2-mode)
1029
1030 (defface js2-jsdoc-tag
1031 '((t :foreground "SlateGray"))
1032 "Face used to highlight @whatever tags in jsdoc comments."
1033 :group 'js2-mode)
1034
1035 (defface js2-jsdoc-type
1036 '((t :foreground "SteelBlue"))
1037 "Face used to highlight {FooBar} types in jsdoc comments."
1038 :group 'js2-mode)
1039
1040 (defface js2-jsdoc-value
1041 '((t :foreground "PeachPuff3"))
1042 "Face used to highlight tag values in jsdoc comments."
1043 :group 'js2-mode)
1044
1045 (defface js2-function-param
1046 '((t :foreground "SeaGreen"))
1047 "Face used to highlight function parameters in javascript."
1048 :group 'js2-mode)
1049
1050 (defface js2-instance-member
1051 '((t :foreground "DarkOrchid"))
1052 "Face used to highlight instance variables in javascript.
1053 Not currently used."
1054 :group 'js2-mode)
1055
1056 (defface js2-private-member
1057 '((t :foreground "PeachPuff3"))
1058 "Face used to highlight calls to private methods in javascript.
1059 Not currently used."
1060 :group 'js2-mode)
1061
1062 (defface js2-private-function-call
1063 '((t :foreground "goldenrod"))
1064 "Face used to highlight calls to private functions in javascript.
1065 Not currently used."
1066 :group 'js2-mode)
1067
1068 (defface js2-jsdoc-html-tag-name
1069 '((((class color) (min-colors 88) (background light))
1070 (:foreground "rosybrown"))
1071 (((class color) (min-colors 8) (background dark))
1072 (:foreground "yellow"))
1073 (((class color) (min-colors 8) (background light))
1074 (:foreground "magenta")))
1075 "Face used to highlight jsdoc html tag names"
1076 :group 'js2-mode)
1077
1078 (defface js2-jsdoc-html-tag-delimiter
1079 '((((class color) (min-colors 88) (background light))
1080 (:foreground "dark khaki"))
1081 (((class color) (min-colors 8) (background dark))
1082 (:foreground "green"))
1083 (((class color) (min-colors 8) (background light))
1084 (:foreground "green")))
1085 "Face used to highlight brackets in jsdoc html tags."
1086 :group 'js2-mode)
1087
1088 (defface js2-external-variable
1089 '((t :foreground "orange"))
1090 "Face used to highlight undeclared variable identifiers.")
1091
1092 (defcustom js2-post-parse-callbacks nil
1093 "A list of callback functions invoked after parsing finishes.
1094 Currently, the main use for this function is to add synthetic
1095 declarations to `js2-recorded-identifiers', which see."
1096 :type 'list
1097 :group 'js2-mode)
1098
1099 (defcustom js2-highlight-external-variables t
1100 "Non-nil to highlight undeclared variable identifiers.
1101 An undeclared variable is any variable not declared with var or let
1102 in the current scope or any lexically enclosing scope. If you use
1103 such a variable, then you are either expecting it to originate from
1104 another file, or you've got a potential bug."
1105 :type 'boolean
1106 :group 'js2-mode)
1107
1108 (defcustom js2-auto-insert-catch-block t
1109 "Non-nil to insert matching catch block on open-curly after `try'."
1110 :type 'boolean
1111 :group 'js2-mode)
1112
1113 (defvar js2-mode-map
1114 (let ((map (make-sparse-keymap))
1115 keys)
1116 (define-key map [mouse-1] #'js2-mode-show-node)
1117 (define-key map (kbd "M-j") #'js2-line-break)
1118 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1119 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1120 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1121 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1122 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1123 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1124 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1125 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1126 (when js2-bounce-indent-p
1127 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1128
1129 (define-key map [menu-bar javascript]
1130 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1131
1132 (define-key map [menu-bar javascript customize-js2-mode]
1133 '(menu-item "Customize js2-mode" js2-mode-customize
1134 :help "Customize the behavior of this mode"))
1135
1136 (define-key map [menu-bar javascript js2-force-refresh]
1137 '(menu-item "Force buffer refresh" js2-mode-reset
1138 :help "Re-parse the buffer from scratch"))
1139
1140 (define-key map [menu-bar javascript separator-2]
1141 '("--"))
1142
1143 (define-key map [menu-bar javascript next-error]
1144 '(menu-item "Next warning or error" next-error
1145 :enabled (and js2-mode-ast
1146 (or (js2-ast-root-errors js2-mode-ast)
1147 (js2-ast-root-warnings js2-mode-ast)))
1148 :help "Move to next warning or error"))
1149
1150 (define-key map [menu-bar javascript display-errors]
1151 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1152 :visible (not js2-mode-show-parse-errors)
1153 :help "Turn on display of warnings and errors"))
1154
1155 (define-key map [menu-bar javascript hide-errors]
1156 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1157 :visible js2-mode-show-parse-errors
1158 :help "Turn off display of warnings and errors"))
1159
1160 (define-key map [menu-bar javascript separator-1]
1161 '("--"))
1162
1163 (define-key map [menu-bar javascript js2-toggle-function]
1164 '(menu-item "Show/collapse element" js2-mode-toggle-element
1165 :help "Hide or show function body or comment"))
1166
1167 (define-key map [menu-bar javascript show-comments]
1168 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1169 :visible js2-mode-comments-hidden
1170 :help "Expand all hidden block comments"))
1171
1172 (define-key map [menu-bar javascript hide-comments]
1173 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1174 :visible (not js2-mode-comments-hidden)
1175 :help "Show block comments as /*...*/"))
1176
1177 (define-key map [menu-bar javascript show-all-functions]
1178 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1179 :visible js2-mode-functions-hidden
1180 :help "Expand all hidden function bodies"))
1181
1182 (define-key map [menu-bar javascript hide-all-functions]
1183 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1184 :visible (not js2-mode-functions-hidden)
1185 :help "Show {...} for all top-level function bodies"))
1186
1187 map)
1188 "Keymap used in `js2-mode' buffers.")
1189
1190 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1191
1192 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1193 "Matches a //-comment line. Must be first non-whitespace on line.
1194 First match-group is the leading whitespace.")
1195
1196 (defvar js2-mode-hook nil)
1197
1198 (js2-deflocal js2-mode-ast nil "Private variable.")
1199 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1200 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1201 (js2-deflocal js2-mode-parsing nil "Private variable.")
1202 (js2-deflocal js2-mode-node-overlay nil)
1203
1204 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1205 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1206
1207 (js2-deflocal js2-mode-fontifications nil "Private variable")
1208 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1209 (js2-deflocal js2-imenu-recorder nil "Private variable")
1210 (js2-deflocal js2-imenu-function-map nil "Private variable")
1211
1212 (defvar js2-paragraph-start
1213 "\\(@[a-zA-Z]+\\>\\|$\\)")
1214
1215 ;; Note that we also set a 'c-in-sws text property in html comments,
1216 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1217 (defvar js2-syntactic-ws-start
1218 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1219
1220 (defvar js2-syntactic-ws-end
1221 "\\s \\|[\n\r/]\\|\\s!")
1222
1223 (defvar js2-syntactic-eol
1224 (concat "\\s *\\(/\\*[^*\n\r]*"
1225 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1226 "\\*+/\\s *\\)*"
1227 "\\(//\\|/\\*[^*\n\r]*"
1228 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1229 "\\|\\\\$\\|$\\)")
1230 "Copied from `java-mode'. Needed for some cc-engine functions.")
1231
1232 (defvar js2-comment-prefix-regexp
1233 "//+\\|\\**")
1234
1235 (defvar js2-comment-start-skip
1236 "\\(//+\\|/\\*+\\)\\s *")
1237
1238 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1239 "Non-nil to emit status messages during parsing.")
1240
1241 (defvar js2-mode-functions-hidden nil "Private variable.")
1242 (defvar js2-mode-comments-hidden nil "Private variable.")
1243
1244 (defvar js2-mode-syntax-table
1245 (let ((table (make-syntax-table)))
1246 (c-populate-syntax-table table)
1247 table)
1248 "Syntax table used in `js2-mode' buffers.")
1249
1250 (defvar js2-mode-abbrev-table nil
1251 "Abbrev table in use in `js2-mode' buffers.")
1252 (define-abbrev-table 'js2-mode-abbrev-table ())
1253
1254 (defvar js2-mode-pending-parse-callbacks nil
1255 "List of functions waiting to be notified that parse is finished.")
1256
1257 (defvar js2-mode-last-indented-line -1)
1258
1259 ;;; Localizable error and warning messages
1260
1261 ;; Messages are copied from Rhino's Messages.properties.
1262 ;; Many of the Java-specific messages have been elided.
1263 ;; Add any js2-specific ones at the end, so we can keep
1264 ;; this file synced with changes to Rhino's.
1265
1266 (defvar js2-message-table
1267 (make-hash-table :test 'equal :size 250)
1268 "Contains localized messages for `js2-mode'.")
1269
1270 ;; TODO(stevey): construct this table at compile-time.
1271 (defmacro js2-msg (key &rest strings)
1272 `(puthash ,key (concat ,@strings)
1273 js2-message-table))
1274
1275 (defun js2-get-msg (msg-key)
1276 "Look up a localized message.
1277 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1278 the correct number of ARGS must be provided."
1279 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1280 (args (if (listp msg-key) (cdr msg-key)))
1281 (msg (gethash key js2-message-table)))
1282 (if msg
1283 (apply #'format msg args)
1284 key))) ; default to showing the key
1285
1286 (js2-msg "msg.dup.parms"
1287 "Duplicate parameter name '%s'.")
1288
1289 (js2-msg "msg.too.big.jump"
1290 "Program too complex: jump offset too big.")
1291
1292 (js2-msg "msg.too.big.index"
1293 "Program too complex: internal index exceeds 64K limit.")
1294
1295 (js2-msg "msg.while.compiling.fn"
1296 "Encountered code generation error while compiling function '%s': %s")
1297
1298 (js2-msg "msg.while.compiling.script"
1299 "Encountered code generation error while compiling script: %s")
1300
1301 ;; Context
1302 (js2-msg "msg.ctor.not.found"
1303 "Constructor for '%s' not found.")
1304
1305 (js2-msg "msg.not.ctor"
1306 "'%s' is not a constructor.")
1307
1308 ;; FunctionObject
1309 (js2-msg "msg.varargs.ctor"
1310 "Method or constructor '%s' must be static "
1311 "with the signature (Context cx, Object[] args, "
1312 "Function ctorObj, boolean inNewExpr) "
1313 "to define a variable arguments constructor.")
1314
1315 (js2-msg "msg.varargs.fun"
1316 "Method '%s' must be static with the signature "
1317 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1318 "to define a variable arguments function.")
1319
1320 (js2-msg "msg.incompat.call"
1321 "Method '%s' called on incompatible object.")
1322
1323 (js2-msg "msg.bad.parms"
1324 "Unsupported parameter type '%s' in method '%s'.")
1325
1326 (js2-msg "msg.bad.method.return"
1327 "Unsupported return type '%s' in method '%s'.")
1328
1329 (js2-msg "msg.bad.ctor.return"
1330 "Construction of objects of type '%s' is not supported.")
1331
1332 (js2-msg "msg.no.overload"
1333 "Method '%s' occurs multiple times in class '%s'.")
1334
1335 (js2-msg "msg.method.not.found"
1336 "Method '%s' not found in '%s'.")
1337
1338 ;; IRFactory
1339
1340 (js2-msg "msg.bad.for.in.lhs"
1341 "Invalid left-hand side of for..in loop.")
1342
1343 (js2-msg "msg.mult.index"
1344 "Only one variable allowed in for..in loop.")
1345
1346 (js2-msg "msg.bad.for.in.destruct"
1347 "Left hand side of for..in loop must be an array of "
1348 "length 2 to accept key/value pair.")
1349
1350 (js2-msg "msg.cant.convert"
1351 "Can't convert to type '%s'.")
1352
1353 (js2-msg "msg.bad.assign.left"
1354 "Invalid assignment left-hand side.")
1355
1356 (js2-msg "msg.bad.decr"
1357 "Invalid decerement operand.")
1358
1359 (js2-msg "msg.bad.incr"
1360 "Invalid increment operand.")
1361
1362 (js2-msg "msg.bad.yield"
1363 "yield must be in a function.")
1364
1365 (js2-msg "msg.yield.parenthesized"
1366 "yield expression must be parenthesized.")
1367
1368 ;; NativeGlobal
1369 (js2-msg "msg.cant.call.indirect"
1370 "Function '%s' must be called directly, and not by way of a "
1371 "function of another name.")
1372
1373 (js2-msg "msg.eval.nonstring"
1374 "Calling eval() with anything other than a primitive "
1375 "string value will simply return the value. "
1376 "Is this what you intended?")
1377
1378 (js2-msg "msg.eval.nonstring.strict"
1379 "Calling eval() with anything other than a primitive "
1380 "string value is not allowed in strict mode.")
1381
1382 (js2-msg "msg.bad.destruct.op"
1383 "Invalid destructuring assignment operator")
1384
1385 ;; NativeCall
1386 (js2-msg "msg.only.from.new"
1387 "'%s' may only be invoked from a `new' expression.")
1388
1389 (js2-msg "msg.deprec.ctor"
1390 "The '%s' constructor is deprecated.")
1391
1392 ;; NativeFunction
1393 (js2-msg "msg.no.function.ref.found"
1394 "no source found to decompile function reference %s")
1395
1396 (js2-msg "msg.arg.isnt.array"
1397 "second argument to Function.prototype.apply must be an array")
1398
1399 ;; NativeGlobal
1400 (js2-msg "msg.bad.esc.mask"
1401 "invalid string escape mask")
1402
1403 ;; NativeRegExp
1404 (js2-msg "msg.bad.quant"
1405 "Invalid quantifier %s")
1406
1407 (js2-msg "msg.overlarge.backref"
1408 "Overly large back reference %s")
1409
1410 (js2-msg "msg.overlarge.min"
1411 "Overly large minimum %s")
1412
1413 (js2-msg "msg.overlarge.max"
1414 "Overly large maximum %s")
1415
1416 (js2-msg "msg.zero.quant"
1417 "Zero quantifier %s")
1418
1419 (js2-msg "msg.max.lt.min"
1420 "Maximum %s less than minimum")
1421
1422 (js2-msg "msg.unterm.quant"
1423 "Unterminated quantifier %s")
1424
1425 (js2-msg "msg.unterm.paren"
1426 "Unterminated parenthetical %s")
1427
1428 (js2-msg "msg.unterm.class"
1429 "Unterminated character class %s")
1430
1431 (js2-msg "msg.bad.range"
1432 "Invalid range in character class.")
1433
1434 (js2-msg "msg.trail.backslash"
1435 "Trailing \\ in regular expression.")
1436
1437 (js2-msg "msg.re.unmatched.right.paren"
1438 "unmatched ) in regular expression.")
1439
1440 (js2-msg "msg.no.regexp"
1441 "Regular expressions are not available.")
1442
1443 (js2-msg "msg.bad.backref"
1444 "back-reference exceeds number of capturing parentheses.")
1445
1446 (js2-msg "msg.bad.regexp.compile"
1447 "Only one argument may be specified if the first "
1448 "argument to RegExp.prototype.compile is a RegExp object.")
1449
1450 ;; Parser
1451 (js2-msg "msg.got.syntax.errors"
1452 "Compilation produced %s syntax errors.")
1453
1454 (js2-msg "msg.var.redecl"
1455 "TypeError: redeclaration of var %s.")
1456
1457 (js2-msg "msg.const.redecl"
1458 "TypeError: redeclaration of const %s.")
1459
1460 (js2-msg "msg.let.redecl"
1461 "TypeError: redeclaration of variable %s.")
1462
1463 (js2-msg "msg.parm.redecl"
1464 "TypeError: redeclaration of formal parameter %s.")
1465
1466 (js2-msg "msg.fn.redecl"
1467 "TypeError: redeclaration of function %s.")
1468
1469 (js2-msg "msg.let.decl.not.in.block"
1470 "SyntaxError: let declaration not directly within block")
1471
1472 ;; NodeTransformer
1473 (js2-msg "msg.dup.label"
1474 "duplicated label")
1475
1476 (js2-msg "msg.undef.label"
1477 "undefined label")
1478
1479 (js2-msg "msg.bad.break"
1480 "unlabelled break must be inside loop or switch")
1481
1482 (js2-msg "msg.continue.outside"
1483 "continue must be inside loop")
1484
1485 (js2-msg "msg.continue.nonloop"
1486 "continue can only use labels of iteration statements")
1487
1488 (js2-msg "msg.bad.throw.eol"
1489 "Line terminator is not allowed between the throw "
1490 "keyword and throw expression.")
1491
1492 (js2-msg "msg.no.paren.parms"
1493 "missing ( before function parameters.")
1494
1495 (js2-msg "msg.no.parm"
1496 "missing formal parameter")
1497
1498 (js2-msg "msg.no.paren.after.parms"
1499 "missing ) after formal parameters")
1500
1501 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1502 "parameter without default follows parameter with default")
1503
1504 (js2-msg "msg.param.after.rest" ; added by js2-mode
1505 "parameter after rest parameter")
1506
1507 (js2-msg "msg.no.brace.body"
1508 "missing '{' before function body")
1509
1510 (js2-msg "msg.no.brace.after.body"
1511 "missing } after function body")
1512
1513 (js2-msg "msg.no.paren.cond"
1514 "missing ( before condition")
1515
1516 (js2-msg "msg.no.paren.after.cond"
1517 "missing ) after condition")
1518
1519 (js2-msg "msg.no.semi.stmt"
1520 "missing ; before statement")
1521
1522 (js2-msg "msg.missing.semi"
1523 "missing ; after statement")
1524
1525 (js2-msg "msg.no.name.after.dot"
1526 "missing name after . operator")
1527
1528 (js2-msg "msg.no.name.after.coloncolon"
1529 "missing name after :: operator")
1530
1531 (js2-msg "msg.no.name.after.dotdot"
1532 "missing name after .. operator")
1533
1534 (js2-msg "msg.no.name.after.xmlAttr"
1535 "missing name after .@")
1536
1537 (js2-msg "msg.no.bracket.index"
1538 "missing ] in index expression")
1539
1540 (js2-msg "msg.no.paren.switch"
1541 "missing ( before switch expression")
1542
1543 (js2-msg "msg.no.paren.after.switch"
1544 "missing ) after switch expression")
1545
1546 (js2-msg "msg.no.brace.switch"
1547 "missing '{' before switch body")
1548
1549 (js2-msg "msg.bad.switch"
1550 "invalid switch statement")
1551
1552 (js2-msg "msg.no.colon.case"
1553 "missing : after case expression")
1554
1555 (js2-msg "msg.double.switch.default"
1556 "double default label in the switch statement")
1557
1558 (js2-msg "msg.no.while.do"
1559 "missing while after do-loop body")
1560
1561 (js2-msg "msg.no.paren.for"
1562 "missing ( after for")
1563
1564 (js2-msg "msg.no.semi.for"
1565 "missing ; after for-loop initializer")
1566
1567 (js2-msg "msg.no.semi.for.cond"
1568 "missing ; after for-loop condition")
1569
1570 (js2-msg "msg.in.after.for.name"
1571 "missing in or of after for")
1572
1573 (js2-msg "msg.no.paren.for.ctrl"
1574 "missing ) after for-loop control")
1575
1576 (js2-msg "msg.no.paren.with"
1577 "missing ( before with-statement object")
1578
1579 (js2-msg "msg.no.paren.after.with"
1580 "missing ) after with-statement object")
1581
1582 (js2-msg "msg.no.paren.after.let"
1583 "missing ( after let")
1584
1585 (js2-msg "msg.no.paren.let"
1586 "missing ) after variable list")
1587
1588 (js2-msg "msg.no.curly.let"
1589 "missing } after let statement")
1590
1591 (js2-msg "msg.bad.return"
1592 "invalid return")
1593
1594 (js2-msg "msg.no.brace.block"
1595 "missing } in compound statement")
1596
1597 (js2-msg "msg.bad.label"
1598 "invalid label")
1599
1600 (js2-msg "msg.bad.var"
1601 "missing variable name")
1602
1603 (js2-msg "msg.bad.var.init"
1604 "invalid variable initialization")
1605
1606 (js2-msg "msg.no.colon.cond"
1607 "missing : in conditional expression")
1608
1609 (js2-msg "msg.no.paren.arg"
1610 "missing ) after argument list")
1611
1612 (js2-msg "msg.no.bracket.arg"
1613 "missing ] after element list")
1614
1615 (js2-msg "msg.bad.prop"
1616 "invalid property id")
1617
1618 (js2-msg "msg.no.colon.prop"
1619 "missing : after property id")
1620
1621 (js2-msg "msg.no.brace.prop"
1622 "missing } after property list")
1623
1624 (js2-msg "msg.no.paren"
1625 "missing ) in parenthetical")
1626
1627 (js2-msg "msg.reserved.id"
1628 "identifier is a reserved word")
1629
1630 (js2-msg "msg.no.paren.catch"
1631 "missing ( before catch-block condition")
1632
1633 (js2-msg "msg.bad.catchcond"
1634 "invalid catch block condition")
1635
1636 (js2-msg "msg.catch.unreachable"
1637 "any catch clauses following an unqualified catch are unreachable")
1638
1639 (js2-msg "msg.no.brace.try"
1640 "missing '{' before try block")
1641
1642 (js2-msg "msg.no.brace.catchblock"
1643 "missing '{' before catch-block body")
1644
1645 (js2-msg "msg.try.no.catchfinally"
1646 "'try' without 'catch' or 'finally'")
1647
1648 (js2-msg "msg.no.return.value"
1649 "function %s does not always return a value")
1650
1651 (js2-msg "msg.anon.no.return.value"
1652 "anonymous function does not always return a value")
1653
1654 (js2-msg "msg.return.inconsistent"
1655 "return statement is inconsistent with previous usage")
1656
1657 (js2-msg "msg.generator.returns"
1658 "TypeError: generator function '%s' returns a value")
1659
1660 (js2-msg "msg.anon.generator.returns"
1661 "TypeError: anonymous generator function returns a value")
1662
1663 (js2-msg "msg.syntax"
1664 "syntax error")
1665
1666 (js2-msg "msg.unexpected.eof"
1667 "Unexpected end of file")
1668
1669 (js2-msg "msg.XML.bad.form"
1670 "illegally formed XML syntax")
1671
1672 (js2-msg "msg.XML.not.available"
1673 "XML runtime not available")
1674
1675 (js2-msg "msg.too.deep.parser.recursion"
1676 "Too deep recursion while parsing")
1677
1678 (js2-msg "msg.no.side.effects"
1679 "Code has no side effects")
1680
1681 (js2-msg "msg.extra.trailing.comma"
1682 "Trailing comma is not legal in an ECMA-262 object initializer")
1683
1684 (js2-msg "msg.array.trailing.comma"
1685 "Trailing comma yields different behavior across browsers")
1686
1687 (js2-msg "msg.equal.as.assign"
1688 (concat "Test for equality (==) mistyped as assignment (=)?"
1689 " (parenthesize to suppress warning)"))
1690
1691 (js2-msg "msg.var.hides.arg"
1692 "Variable %s hides argument")
1693
1694 (js2-msg "msg.destruct.assign.no.init"
1695 "Missing = in destructuring declaration")
1696
1697 ;; ScriptRuntime
1698 (js2-msg "msg.no.properties"
1699 "%s has no properties.")
1700
1701 (js2-msg "msg.invalid.iterator"
1702 "Invalid iterator value")
1703
1704 (js2-msg "msg.iterator.primitive"
1705 "__iterator__ returned a primitive value")
1706
1707 (js2-msg "msg.assn.create.strict"
1708 "Assignment to undeclared variable %s")
1709
1710 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1711 "Undeclared variable or function '%s'")
1712
1713 (js2-msg "msg.ref.undefined.prop"
1714 "Reference to undefined property '%s'")
1715
1716 (js2-msg "msg.prop.not.found"
1717 "Property %s not found.")
1718
1719 (js2-msg "msg.invalid.type"
1720 "Invalid JavaScript value of type %s")
1721
1722 (js2-msg "msg.primitive.expected"
1723 "Primitive type expected (had %s instead)")
1724
1725 (js2-msg "msg.namespace.expected"
1726 "Namespace object expected to left of :: (found %s instead)")
1727
1728 (js2-msg "msg.null.to.object"
1729 "Cannot convert null to an object.")
1730
1731 (js2-msg "msg.undef.to.object"
1732 "Cannot convert undefined to an object.")
1733
1734 (js2-msg "msg.cyclic.value"
1735 "Cyclic %s value not allowed.")
1736
1737 (js2-msg "msg.is.not.defined"
1738 "'%s' is not defined.")
1739
1740 (js2-msg "msg.undef.prop.read"
1741 "Cannot read property '%s' from %s")
1742
1743 (js2-msg "msg.undef.prop.write"
1744 "Cannot set property '%s' of %s to '%s'")
1745
1746 (js2-msg "msg.undef.prop.delete"
1747 "Cannot delete property '%s' of %s")
1748
1749 (js2-msg "msg.undef.method.call"
1750 "Cannot call method '%s' of %s")
1751
1752 (js2-msg "msg.undef.with"
1753 "Cannot apply 'with' to %s")
1754
1755 (js2-msg "msg.isnt.function"
1756 "%s is not a function, it is %s.")
1757
1758 (js2-msg "msg.isnt.function.in"
1759 "Cannot call property %s in object %s. "
1760 "It is not a function, it is '%s'.")
1761
1762 (js2-msg "msg.function.not.found"
1763 "Cannot find function %s.")
1764
1765 (js2-msg "msg.function.not.found.in"
1766 "Cannot find function %s in object %s.")
1767
1768 (js2-msg "msg.isnt.xml.object"
1769 "%s is not an xml object.")
1770
1771 (js2-msg "msg.no.ref.to.get"
1772 "%s is not a reference to read reference value.")
1773
1774 (js2-msg "msg.no.ref.to.set"
1775 "%s is not a reference to set reference value to %s.")
1776
1777 (js2-msg "msg.no.ref.from.function"
1778 "Function %s can not be used as the left-hand "
1779 "side of assignment or as an operand of ++ or -- operator.")
1780
1781 (js2-msg "msg.bad.default.value"
1782 "Object's getDefaultValue() method returned an object.")
1783
1784 (js2-msg "msg.instanceof.not.object"
1785 "Can't use instanceof on a non-object.")
1786
1787 (js2-msg "msg.instanceof.bad.prototype"
1788 "'prototype' property of %s is not an object.")
1789
1790 (js2-msg "msg.bad.radix"
1791 "illegal radix %s.")
1792
1793 ;; ScriptableObject
1794 (js2-msg "msg.default.value"
1795 "Cannot find default value for object.")
1796
1797 (js2-msg "msg.zero.arg.ctor"
1798 "Cannot load class '%s' which has no zero-parameter constructor.")
1799
1800 (js2-msg "msg.ctor.multiple.parms"
1801 "Can't define constructor or class %s since more than "
1802 "one constructor has multiple parameters.")
1803
1804 (js2-msg "msg.extend.scriptable"
1805 "%s must extend ScriptableObject in order to define property %s.")
1806
1807 (js2-msg "msg.bad.getter.parms"
1808 "In order to define a property, getter %s must have zero "
1809 "parameters or a single ScriptableObject parameter.")
1810
1811 (js2-msg "msg.obj.getter.parms"
1812 "Expected static or delegated getter %s to take "
1813 "a ScriptableObject parameter.")
1814
1815 (js2-msg "msg.getter.static"
1816 "Getter and setter must both be static or neither be static.")
1817
1818 (js2-msg "msg.setter.return"
1819 "Setter must have void return type: %s")
1820
1821 (js2-msg "msg.setter2.parms"
1822 "Two-parameter setter must take a ScriptableObject as "
1823 "its first parameter.")
1824
1825 (js2-msg "msg.setter1.parms"
1826 "Expected single parameter setter for %s")
1827
1828 (js2-msg "msg.setter2.expected"
1829 "Expected static or delegated setter %s to take two parameters.")
1830
1831 (js2-msg "msg.setter.parms"
1832 "Expected either one or two parameters for setter.")
1833
1834 (js2-msg "msg.setter.bad.type"
1835 "Unsupported parameter type '%s' in setter '%s'.")
1836
1837 (js2-msg "msg.add.sealed"
1838 "Cannot add a property to a sealed object: %s.")
1839
1840 (js2-msg "msg.remove.sealed"
1841 "Cannot remove a property from a sealed object: %s.")
1842
1843 (js2-msg "msg.modify.sealed"
1844 "Cannot modify a property of a sealed object: %s.")
1845
1846 (js2-msg "msg.modify.readonly"
1847 "Cannot modify readonly property: %s.")
1848
1849 ;; TokenStream
1850 (js2-msg "msg.missing.exponent"
1851 "missing exponent")
1852
1853 (js2-msg "msg.caught.nfe"
1854 "number format error")
1855
1856 (js2-msg "msg.unterminated.string.lit"
1857 "unterminated string literal")
1858
1859 (js2-msg "msg.unterminated.comment"
1860 "unterminated comment")
1861
1862 (js2-msg "msg.unterminated.re.lit"
1863 "unterminated regular expression literal")
1864
1865 (js2-msg "msg.invalid.re.flag"
1866 "invalid flag after regular expression")
1867
1868 (js2-msg "msg.no.re.input.for"
1869 "no input for %s")
1870
1871 (js2-msg "msg.illegal.character"
1872 "illegal character")
1873
1874 (js2-msg "msg.invalid.escape"
1875 "invalid Unicode escape sequence")
1876
1877 (js2-msg "msg.bad.namespace"
1878 "not a valid default namespace statement. "
1879 "Syntax is: default xml namespace = EXPRESSION;")
1880
1881 ;; TokensStream warnings
1882 (js2-msg "msg.bad.octal.literal"
1883 "illegal octal literal digit %s; "
1884 "interpreting it as a decimal digit")
1885
1886 (js2-msg "msg.reserved.keyword"
1887 "illegal usage of future reserved keyword %s; "
1888 "interpreting it as ordinary identifier")
1889
1890 (js2-msg "msg.script.is.not.constructor"
1891 "Script objects are not constructors.")
1892
1893 ;; Arrays
1894 (js2-msg "msg.arraylength.bad"
1895 "Inappropriate array length.")
1896
1897 ;; Arrays
1898 (js2-msg "msg.arraylength.too.big"
1899 "Array length %s exceeds supported capacity limit.")
1900
1901 ;; URI
1902 (js2-msg "msg.bad.uri"
1903 "Malformed URI sequence.")
1904
1905 ;; Number
1906 (js2-msg "msg.bad.precision"
1907 "Precision %s out of range.")
1908
1909 ;; NativeGenerator
1910 (js2-msg "msg.send.newborn"
1911 "Attempt to send value to newborn generator")
1912
1913 (js2-msg "msg.already.exec.gen"
1914 "Already executing generator")
1915
1916 (js2-msg "msg.StopIteration.invalid"
1917 "StopIteration may not be changed to an arbitrary object.")
1918
1919 ;; Interpreter
1920 (js2-msg "msg.yield.closing"
1921 "Yield from closing generator")
1922
1923 ;;; Utilities
1924
1925 (defun js2-delete-if (predicate list)
1926 "Remove all items satisfying PREDICATE in LIST."
1927 (loop for item in list
1928 if (not (funcall predicate item))
1929 collect item))
1930
1931 (defun js2-position (element list)
1932 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1933 Returns nil if element is not found in the list."
1934 (let ((count 0)
1935 found)
1936 (while (and list (not found))
1937 (if (eq element (car list))
1938 (setq found t)
1939 (setq count (1+ count)
1940 list (cdr list))))
1941 (if found count)))
1942
1943 (defun js2-find-if (predicate list)
1944 "Find first item satisfying PREDICATE in LIST."
1945 (let (result)
1946 (while (and list (not result))
1947 (if (funcall predicate (car list))
1948 (setq result (car list)))
1949 (setq list (cdr list)))
1950 result))
1951
1952 (defmacro js2-time (form)
1953 "Evaluate FORM, discard result, and return elapsed time in sec."
1954 (declare (debug t))
1955 (let ((beg (make-symbol "--js2-time-beg--"))
1956 (delta (make-symbol "--js2-time-end--")))
1957 `(let ((,beg (current-time))
1958 ,delta)
1959 ,form
1960 (/ (truncate (* (- (float-time (current-time))
1961 (float-time ,beg))
1962 10000))
1963 10000.0))))
1964
1965 (defsubst js2-same-line (pos)
1966 "Return t if POS is on the same line as current point."
1967 (and (>= pos (point-at-bol))
1968 (<= pos (point-at-eol))))
1969
1970 (defun js2-same-line-2 (p1 p2)
1971 "Return t if P1 is on the same line as P2."
1972 (save-excursion
1973 (goto-char p1)
1974 (js2-same-line p2)))
1975
1976 (defun js2-code-bug ()
1977 "Signal an error when we encounter an unexpected code path."
1978 (error "failed assertion"))
1979
1980 (defsubst js2-record-text-property (beg end prop value)
1981 "Record a text property to set when parsing finishes."
1982 (push (list beg end prop value) js2-mode-deferred-properties))
1983
1984 ;; I'd like to associate errors with nodes, but for now the
1985 ;; easiest thing to do is get the context info from the last token.
1986 (defun js2-record-parse-error (msg &optional arg pos len)
1987 (push (list (list msg arg)
1988 (or pos js2-token-beg)
1989 (or len (- js2-token-end js2-token-beg)))
1990 js2-parsed-errors))
1991
1992 (defun js2-report-error (msg &optional msg-arg pos len)
1993 "Signal a syntax error or record a parse error."
1994 (if js2-recover-from-parse-errors
1995 (js2-record-parse-error msg msg-arg pos len)
1996 (signal 'js2-syntax-error
1997 (list msg
1998 js2-ts-lineno
1999 (save-excursion
2000 (goto-char js2-ts-cursor)
2001 (current-column))
2002 js2-ts-hit-eof))))
2003
2004 (defun js2-report-warning (msg &optional msg-arg pos len face)
2005 (if js2-compiler-report-warning-as-error
2006 (js2-report-error msg msg-arg pos len)
2007 (push (list (list msg msg-arg)
2008 (or pos js2-token-beg)
2009 (or len (- js2-token-end js2-token-beg))
2010 face)
2011 js2-parsed-warnings)))
2012
2013 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2014 (if js2-compiler-strict-mode
2015 (js2-report-warning msg-id msg-arg beg
2016 (and beg end (- end beg)))))
2017
2018 (put 'js2-syntax-error 'error-conditions
2019 '(error syntax-error js2-syntax-error))
2020 (put 'js2-syntax-error 'error-message "Syntax error")
2021
2022 (put 'js2-parse-error 'error-conditions
2023 '(error parse-error js2-parse-error))
2024 (put 'js2-parse-error 'error-message "Parse error")
2025
2026 (defmacro js2-clear-flag (flags flag)
2027 `(setq ,flags (logand ,flags (lognot ,flag))))
2028
2029 (defmacro js2-set-flag (flags flag)
2030 "Logical-or FLAG into FLAGS."
2031 `(setq ,flags (logior ,flags ,flag)))
2032
2033 (defsubst js2-flag-set-p (flags flag)
2034 (/= 0 (logand flags flag)))
2035
2036 (defsubst js2-flag-not-set-p (flags flag)
2037 (zerop (logand flags flag)))
2038
2039 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2040 "Evaluate BODY with the _ character set to be word-syntax."
2041 (declare (indent 0) (debug t))
2042 (let ((old-syntax (make-symbol "old-syntax")))
2043 `(let ((,old-syntax (string (char-syntax ?_))))
2044 (unwind-protect
2045 (progn
2046 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2047 ,@body)
2048 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2049
2050 (defsubst js2-char-uppercase-p (c)
2051 "Return t if C is an uppercase character.
2052 Handles unicode and latin chars properly."
2053 (/= c (downcase c)))
2054
2055 (defsubst js2-char-lowercase-p (c)
2056 "Return t if C is an uppercase character.
2057 Handles unicode and latin chars properly."
2058 (/= c (upcase c)))
2059
2060 ;;; AST struct and function definitions
2061
2062 ;; flags for ast node property 'member-type (used for e4x operators)
2063 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2064 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2065 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2066
2067 (defsubst js2-relpos (pos anchor)
2068 "Convert POS to be relative to ANCHOR.
2069 If POS is nil, returns nil."
2070 (and pos (- pos anchor)))
2071
2072 (defun js2-make-pad (indent)
2073 (if (zerop indent)
2074 ""
2075 (make-string (* indent js2-basic-offset) ? )))
2076
2077 (defun js2-visit-ast (node callback)
2078 "Visit every node in ast NODE with visitor CALLBACK.
2079
2080 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2081 called twice: once to visit the node, and again after all the node's
2082 children have been processed. The END-P argument is nil on the first
2083 call and non-nil on the second call. The return value of the callback
2084 affects the traversal: if non-nil, the children of NODE are processed.
2085 If the callback returns nil, or if the node has no children, then the
2086 callback is called immediately with a non-nil END-P argument.
2087
2088 The node traversal is approximately lexical-order, although there
2089 are currently no guarantees around this."
2090 (when node
2091 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2092 ;; visit the node
2093 (when (funcall callback node nil)
2094 ;; visit the kids
2095 (cond
2096 ((eq vfunc 'js2-visit-none)
2097 nil) ; don't even bother calling it
2098 ;; Each AST node type has to define a `js2-visitor' function
2099 ;; that takes a node and a callback, and calls `js2-visit-ast'
2100 ;; on each child of the node.
2101 (vfunc
2102 (funcall vfunc node callback))
2103 (t
2104 (error "%s does not define a visitor-traversal function"
2105 (aref node 0)))))
2106 ;; call the end-visit
2107 (funcall callback node t))))
2108
2109 (defstruct (js2-node
2110 (:constructor nil)) ; abstract
2111 "Base AST node type."
2112 (type -1) ; token type
2113 (pos -1) ; start position of this AST node in parsed input
2114 (len 1) ; num characters spanned by the node
2115 props ; optional node property list (an alist)
2116 parent) ; link to parent node; null for root
2117
2118 (defsubst js2-node-get-prop (node prop &optional default)
2119 (or (cadr (assoc prop (js2-node-props node))) default))
2120
2121 (defsubst js2-node-set-prop (node prop value)
2122 (setf (js2-node-props node)
2123 (cons (list prop value) (js2-node-props node))))
2124
2125 (defun js2-fixup-starts (n nodes)
2126 "Adjust the start positions of NODES to be relative to N.
2127 Any node in the list may be nil, for convenience."
2128 (dolist (node nodes)
2129 (when node
2130 (setf (js2-node-pos node) (- (js2-node-pos node)
2131 (js2-node-pos n))))))
2132
2133 (defun js2-node-add-children (parent &rest nodes)
2134 "Set parent node of NODES to PARENT, and return PARENT.
2135 Does nothing if we're not recording parent links.
2136 If any given node in NODES is nil, doesn't record that link."
2137 (js2-fixup-starts parent nodes)
2138 (dolist (node nodes)
2139 (and node
2140 (setf (js2-node-parent node) parent))))
2141
2142 ;; Non-recursive since it's called a frightening number of times.
2143 (defun js2-node-abs-pos (n)
2144 (let ((pos (js2-node-pos n)))
2145 (while (setq n (js2-node-parent n))
2146 (setq pos (+ pos (js2-node-pos n))))
2147 pos))
2148
2149 (defsubst js2-node-abs-end (n)
2150 "Return absolute buffer position of end of N."
2151 (+ (js2-node-abs-pos n) (js2-node-len n)))
2152
2153 ;; It's important to make sure block nodes have a Lisp list for the
2154 ;; child nodes, to limit printing recursion depth in an AST that
2155 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2156 ;; a sufficiently large vector tree.
2157
2158 (defstruct (js2-block-node
2159 (:include js2-node)
2160 (:constructor nil)
2161 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2162 (pos js2-token-beg)
2163 len
2164 props
2165 kids)))
2166 "A block of statements."
2167 kids) ; a Lisp list of the child statement nodes
2168
2169 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2170 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2171
2172 (defun js2-visit-block (ast callback)
2173 "Visit the `js2-block-node' children of AST."
2174 (dolist (kid (js2-block-node-kids ast))
2175 (js2-visit-ast kid callback)))
2176
2177 (defun js2-print-block (n i)
2178 (let ((pad (js2-make-pad i)))
2179 (insert pad "{\n")
2180 (dolist (kid (js2-block-node-kids n))
2181 (js2-print-ast kid (1+ i)))
2182 (insert pad "}")))
2183
2184 (defstruct (js2-scope
2185 (:include js2-block-node)
2186 (:constructor nil)
2187 (:constructor make-js2-scope (&key (type js2-BLOCK)
2188 (pos js2-token-beg)
2189 len
2190 kids)))
2191 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2192 ;; I don't have one of those handy, so I'll use an alist for now.
2193 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2194 ;; and is much lighter-weight to construct (both CPU and mem).
2195 ;; The keys are interned strings (symbols) for faster lookup.
2196 ;; Should switch to hybrid alist/hashtable eventually.
2197 symbol-table ; an alist of (symbol . js2-symbol)
2198 parent-scope ; a `js2-scope'
2199 top) ; top-level `js2-scope' (script/function)
2200
2201 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2202 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2203
2204 (defun js2-scope-set-parent-scope (scope parent)
2205 (setf (js2-scope-parent-scope scope) parent
2206 (js2-scope-top scope) (if (null parent)
2207 scope
2208 (js2-scope-top parent))))
2209
2210 (defun js2-node-get-enclosing-scope (node)
2211 "Return the innermost `js2-scope' node surrounding NODE.
2212 Returns nil if there is no enclosing scope node."
2213 (let ((parent (js2-node-parent node)))
2214 (while (not (js2-scope-p parent))
2215 (setq parent (js2-node-parent parent)))
2216 parent))
2217
2218 (defun js2-get-defining-scope (scope name)
2219 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2220 Returns `js2-scope' in which NAME is defined, or nil if not found."
2221 (let ((sym (if (symbolp name)
2222 name
2223 (intern name)))
2224 table
2225 result
2226 (continue t))
2227 (while (and scope continue)
2228 (if (and (setq table (js2-scope-symbol-table scope))
2229 (assq sym table))
2230 (setq continue nil
2231 result scope)
2232 (setq scope (js2-scope-parent-scope scope))))
2233 result))
2234
2235 (defun js2-scope-get-symbol (scope name)
2236 "Return symbol table entry for NAME in SCOPE.
2237 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2238 (and (js2-scope-symbol-table scope)
2239 (cdr (assq (if (symbolp name)
2240 name
2241 (intern name))
2242 (js2-scope-symbol-table scope)))))
2243
2244 (defun js2-scope-put-symbol (scope name symbol)
2245 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2246 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2247 (let* ((table (js2-scope-symbol-table scope))
2248 (sym (if (symbolp name) name (intern name)))
2249 (entry (assq sym table)))
2250 (if entry
2251 (setcdr entry symbol)
2252 (push (cons sym symbol)
2253 (js2-scope-symbol-table scope)))))
2254
2255 (defstruct (js2-symbol
2256 (:constructor nil)
2257 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2258 "A symbol table entry."
2259 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2260 ;; js2-LET, or js2-CONST
2261 decl-type
2262 name ; string
2263 ast-node) ; a `js2-node'
2264
2265 (defstruct (js2-error-node
2266 (:include js2-node)
2267 (:constructor nil) ; silence emacs21 byte-compiler
2268 (:constructor make-js2-error-node (&key (type js2-ERROR)
2269 (pos js2-token-beg)
2270 len)))
2271 "AST node representing a parse error.")
2272
2273 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2274 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2275
2276 (defstruct (js2-script-node
2277 (:include js2-scope)
2278 (:constructor nil)
2279 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2280 (pos js2-token-beg)
2281 len
2282 var-decls
2283 fun-decls)))
2284 functions ; Lisp list of nested functions
2285 regexps ; Lisp list of (string . flags)
2286 symbols ; alist (every symbol gets unique index)
2287 (param-count 0)
2288 var-names ; vector of string names
2289 consts ; bool-vector matching var-decls
2290 (temp-number 0)) ; for generating temp variables
2291
2292 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2293 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2294
2295 (defun js2-print-script (node indent)
2296 (dolist (kid (js2-block-node-kids node))
2297 (js2-print-ast kid indent)))
2298
2299 (defstruct (js2-ast-root
2300 (:include js2-script-node)
2301 (:constructor nil)
2302 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2303 (pos js2-token-beg)
2304 len
2305 buffer)))
2306 "The root node of a js2 AST."
2307 buffer ; the source buffer from which the code was parsed
2308 comments ; a Lisp list of comments, ordered by start position
2309 errors ; a Lisp list of errors found during parsing
2310 warnings ; a Lisp list of warnings found during parsing
2311 node-count) ; number of nodes in the tree, including the root
2312
2313 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2314 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2315
2316 (defun js2-visit-ast-root (ast callback)
2317 (dolist (kid (js2-ast-root-kids ast))
2318 (js2-visit-ast kid callback))
2319 (dolist (comment (js2-ast-root-comments ast))
2320 (js2-visit-ast comment callback)))
2321
2322 (defstruct (js2-comment-node
2323 (:include js2-node)
2324 (:constructor nil)
2325 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2326 (pos js2-token-beg)
2327 len
2328 (format js2-ts-comment-type))))
2329 format) ; 'line, 'block, 'jsdoc or 'html
2330
2331 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2332 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2333
2334 (defun js2-print-comment (n i)
2335 ;; We really ought to link end-of-line comments to their nodes.
2336 ;; Or maybe we could add a new comment type, 'endline.
2337 (insert (js2-make-pad i)
2338 (js2-node-string n)))
2339
2340 (defstruct (js2-expr-stmt-node
2341 (:include js2-node)
2342 (:constructor nil)
2343 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2344 (pos js2-ts-cursor)
2345 len
2346 expr)))
2347 "An expression statement."
2348 expr)
2349
2350 (defsubst js2-expr-stmt-node-set-has-result (node)
2351 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2352 (setf (js2-node-type node) js2-EXPR_RESULT))
2353
2354 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2355 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2356
2357 (defun js2-visit-expr-stmt-node (n v)
2358 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2359
2360 (defun js2-print-expr-stmt-node (n indent)
2361 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2362 (insert ";\n"))
2363
2364 (defstruct (js2-loop-node
2365 (:include js2-scope)
2366 (:constructor nil))
2367 "Abstract supertype of loop nodes."
2368 body ; a `js2-block-node'
2369 lp ; position of left-paren, nil if omitted
2370 rp) ; position of right-paren, nil if omitted
2371
2372 (defstruct (js2-do-node
2373 (:include js2-loop-node)
2374 (:constructor nil)
2375 (:constructor make-js2-do-node (&key (type js2-DO)
2376 (pos js2-token-beg)
2377 len
2378 body
2379 condition
2380 while-pos
2381 lp
2382 rp)))
2383 "AST node for do-loop."
2384 condition ; while (expression)
2385 while-pos) ; buffer position of 'while' keyword
2386
2387 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2388 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2389
2390 (defun js2-visit-do-node (n v)
2391 (js2-visit-ast (js2-do-node-body n) v)
2392 (js2-visit-ast (js2-do-node-condition n) v))
2393
2394 (defun js2-print-do-node (n i)
2395 (let ((pad (js2-make-pad i)))
2396 (insert pad "do {\n")
2397 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2398 (js2-print-ast kid (1+ i)))
2399 (insert pad "} while (")
2400 (js2-print-ast (js2-do-node-condition n) 0)
2401 (insert ");\n")))
2402
2403 (defstruct (js2-while-node
2404 (:include js2-loop-node)
2405 (:constructor nil)
2406 (:constructor make-js2-while-node (&key (type js2-WHILE)
2407 (pos js2-token-beg)
2408 len body
2409 condition lp
2410 rp)))
2411 "AST node for while-loop."
2412 condition) ; while-condition
2413
2414 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2415 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2416
2417 (defun js2-visit-while-node (n v)
2418 (js2-visit-ast (js2-while-node-condition n) v)
2419 (js2-visit-ast (js2-while-node-body n) v))
2420
2421 (defun js2-print-while-node (n i)
2422 (let ((pad (js2-make-pad i)))
2423 (insert pad "while (")
2424 (js2-print-ast (js2-while-node-condition n) 0)
2425 (insert ") {\n")
2426 (js2-print-body (js2-while-node-body n) (1+ i))
2427 (insert pad "}\n")))
2428
2429 (defstruct (js2-for-node
2430 (:include js2-loop-node)
2431 (:constructor nil)
2432 (:constructor make-js2-for-node (&key (type js2-FOR)
2433 (pos js2-ts-cursor)
2434 len body init
2435 condition
2436 update lp rp)))
2437 "AST node for a C-style for-loop."
2438 init ; initialization expression
2439 condition ; loop condition
2440 update) ; update clause
2441
2442 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2443 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2444
2445 (defun js2-visit-for-node (n v)
2446 (js2-visit-ast (js2-for-node-init n) v)
2447 (js2-visit-ast (js2-for-node-condition n) v)
2448 (js2-visit-ast (js2-for-node-update n) v)
2449 (js2-visit-ast (js2-for-node-body n) v))
2450
2451 (defun js2-print-for-node (n i)
2452 (let ((pad (js2-make-pad i)))
2453 (insert pad "for (")
2454 (js2-print-ast (js2-for-node-init n) 0)
2455 (insert "; ")
2456 (js2-print-ast (js2-for-node-condition n) 0)
2457 (insert "; ")
2458 (js2-print-ast (js2-for-node-update n) 0)
2459 (insert ") {\n")
2460 (js2-print-body (js2-for-node-body n) (1+ i))
2461 (insert pad "}\n")))
2462
2463 (defstruct (js2-for-in-node
2464 (:include js2-loop-node)
2465 (:constructor nil)
2466 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2467 (pos js2-ts-cursor)
2468 len body
2469 iterator
2470 object
2471 in-pos
2472 each-pos
2473 foreach-p forof-p
2474 lp rp)))
2475 "AST node for a for..in loop."
2476 iterator ; [var] foo in ...
2477 object ; object over which we're iterating
2478 in-pos ; buffer position of 'in' keyword
2479 each-pos ; buffer position of 'each' keyword, if foreach-p
2480 foreach-p ; t if it's a for-each loop
2481 forof-p) ; t if it's a for-of loop
2482
2483 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2484 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2485
2486 (defun js2-visit-for-in-node (n v)
2487 (js2-visit-ast (js2-for-in-node-iterator n) v)
2488 (js2-visit-ast (js2-for-in-node-object n) v)
2489 (js2-visit-ast (js2-for-in-node-body n) v))
2490
2491 (defun js2-print-for-in-node (n i)
2492 (let ((pad (js2-make-pad i))
2493 (foreach (js2-for-in-node-foreach-p n))
2494 (forof (js2-for-in-node-forof-p n)))
2495 (insert pad "for ")
2496 (if foreach
2497 (insert "each "))
2498 (insert "(")
2499 (js2-print-ast (js2-for-in-node-iterator n) 0)
2500 (if forof
2501 (insert " of ")
2502 (insert " in "))
2503 (js2-print-ast (js2-for-in-node-object n) 0)
2504 (insert ") {\n")
2505 (js2-print-body (js2-for-in-node-body n) (1+ i))
2506 (insert pad "}\n")))
2507
2508 (defstruct (js2-return-node
2509 (:include js2-node)
2510 (:constructor nil)
2511 (:constructor make-js2-return-node (&key (type js2-RETURN)
2512 (pos js2-ts-cursor)
2513 len
2514 retval)))
2515 "AST node for a return statement."
2516 retval) ; expression to return, or 'undefined
2517
2518 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2519 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2520
2521 (defun js2-visit-return-node (n v)
2522 (js2-visit-ast (js2-return-node-retval n) v))
2523
2524 (defun js2-print-return-node (n i)
2525 (insert (js2-make-pad i) "return")
2526 (when (js2-return-node-retval n)
2527 (insert " ")
2528 (js2-print-ast (js2-return-node-retval n) 0))
2529 (insert ";\n"))
2530
2531 (defstruct (js2-if-node
2532 (:include js2-node)
2533 (:constructor nil)
2534 (:constructor make-js2-if-node (&key (type js2-IF)
2535 (pos js2-ts-cursor)
2536 len condition
2537 then-part
2538 else-pos
2539 else-part lp
2540 rp)))
2541 "AST node for an if-statement."
2542 condition ; expression
2543 then-part ; statement or block
2544 else-pos ; optional buffer position of 'else' keyword
2545 else-part ; optional statement or block
2546 lp ; position of left-paren, nil if omitted
2547 rp) ; position of right-paren, nil if omitted
2548
2549 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2550 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2551
2552 (defun js2-visit-if-node (n v)
2553 (js2-visit-ast (js2-if-node-condition n) v)
2554 (js2-visit-ast (js2-if-node-then-part n) v)
2555 (js2-visit-ast (js2-if-node-else-part n) v))
2556
2557 (defun js2-print-if-node (n i)
2558 (let ((pad (js2-make-pad i))
2559 (then-part (js2-if-node-then-part n))
2560 (else-part (js2-if-node-else-part n)))
2561 (insert pad "if (")
2562 (js2-print-ast (js2-if-node-condition n) 0)
2563 (insert ") {\n")
2564 (js2-print-body then-part (1+ i))
2565 (insert pad "}")
2566 (cond
2567 ((not else-part)
2568 (insert "\n"))
2569 ((js2-if-node-p else-part)
2570 (insert " else ")
2571 (js2-print-body else-part i))
2572 (t
2573 (insert " else {\n")
2574 (js2-print-body else-part (1+ i))
2575 (insert pad "}\n")))))
2576
2577 (defstruct (js2-try-node
2578 (:include js2-node)
2579 (:constructor nil)
2580 (:constructor make-js2-try-node (&key (type js2-TRY)
2581 (pos js2-ts-cursor)
2582 len
2583 try-block
2584 catch-clauses
2585 finally-block)))
2586 "AST node for a try-statement."
2587 try-block
2588 catch-clauses ; a Lisp list of `js2-catch-node'
2589 finally-block) ; a `js2-finally-node'
2590
2591 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2592 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2593
2594 (defun js2-visit-try-node (n v)
2595 (js2-visit-ast (js2-try-node-try-block n) v)
2596 (dolist (clause (js2-try-node-catch-clauses n))
2597 (js2-visit-ast clause v))
2598 (js2-visit-ast (js2-try-node-finally-block n) v))
2599
2600 (defun js2-print-try-node (n i)
2601 (let ((pad (js2-make-pad i))
2602 (catches (js2-try-node-catch-clauses n))
2603 (finally (js2-try-node-finally-block n)))
2604 (insert pad "try {\n")
2605 (js2-print-body (js2-try-node-try-block n) (1+ i))
2606 (insert pad "}")
2607 (when catches
2608 (dolist (catch catches)
2609 (js2-print-ast catch i)))
2610 (if finally
2611 (js2-print-ast finally i)
2612 (insert "\n"))))
2613
2614 (defstruct (js2-catch-node
2615 (:include js2-node)
2616 (:constructor nil)
2617 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2618 (pos js2-ts-cursor)
2619 len
2620 param
2621 guard-kwd
2622 guard-expr
2623 block lp
2624 rp)))
2625 "AST node for a catch clause."
2626 param ; destructuring form or simple name node
2627 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2628 guard-expr ; catch condition, a `js2-node'
2629 block ; statements, a `js2-block-node'
2630 lp ; buffer position of left-paren, nil if omitted
2631 rp) ; buffer position of right-paren, nil if omitted
2632
2633 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2634 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2635
2636 (defun js2-visit-catch-node (n v)
2637 (js2-visit-ast (js2-catch-node-param n) v)
2638 (when (js2-catch-node-guard-kwd n)
2639 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2640 (js2-visit-ast (js2-catch-node-block n) v))
2641
2642 (defun js2-print-catch-node (n i)
2643 (let ((pad (js2-make-pad i))
2644 (guard-kwd (js2-catch-node-guard-kwd n))
2645 (guard-expr (js2-catch-node-guard-expr n)))
2646 (insert " catch (")
2647 (js2-print-ast (js2-catch-node-param n) 0)
2648 (when guard-kwd
2649 (insert " if ")
2650 (js2-print-ast guard-expr 0))
2651 (insert ") {\n")
2652 (js2-print-body (js2-catch-node-block n) (1+ i))
2653 (insert pad "}")))
2654
2655 (defstruct (js2-finally-node
2656 (:include js2-node)
2657 (:constructor nil)
2658 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2659 (pos js2-ts-cursor)
2660 len body)))
2661 "AST node for a finally clause."
2662 body) ; a `js2-node', often but not always a block node
2663
2664 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2665 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2666
2667 (defun js2-visit-finally-node (n v)
2668 (js2-visit-ast (js2-finally-node-body n) v))
2669
2670 (defun js2-print-finally-node (n i)
2671 (let ((pad (js2-make-pad i)))
2672 (insert " finally {\n")
2673 (js2-print-body (js2-finally-node-body n) (1+ i))
2674 (insert pad "}\n")))
2675
2676 (defstruct (js2-switch-node
2677 (:include js2-node)
2678 (:constructor nil)
2679 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2680 (pos js2-ts-cursor)
2681 len
2682 discriminant
2683 cases lp
2684 rp)))
2685 "AST node for a switch statement."
2686 discriminant ; a `js2-node' (switch expression)
2687 cases ; a Lisp list of `js2-case-node'
2688 lp ; position of open-paren for discriminant, nil if omitted
2689 rp) ; position of close-paren for discriminant, nil if omitted
2690
2691 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2692 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2693
2694 (defun js2-visit-switch-node (n v)
2695 (js2-visit-ast (js2-switch-node-discriminant n) v)
2696 (dolist (c (js2-switch-node-cases n))
2697 (js2-visit-ast c v)))
2698
2699 (defun js2-print-switch-node (n i)
2700 (let ((pad (js2-make-pad i))
2701 (cases (js2-switch-node-cases n)))
2702 (insert pad "switch (")
2703 (js2-print-ast (js2-switch-node-discriminant n) 0)
2704 (insert ") {\n")
2705 (dolist (case cases)
2706 (js2-print-ast case i))
2707 (insert pad "}\n")))
2708
2709 (defstruct (js2-case-node
2710 (:include js2-block-node)
2711 (:constructor nil)
2712 (:constructor make-js2-case-node (&key (type js2-CASE)
2713 (pos js2-ts-cursor)
2714 len kids expr)))
2715 "AST node for a case clause of a switch statement."
2716 expr) ; the case expression (nil for default)
2717
2718 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2719 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2720
2721 (defun js2-visit-case-node (n v)
2722 (js2-visit-ast (js2-case-node-expr n) v)
2723 (js2-visit-block n v))
2724
2725 (defun js2-print-case-node (n i)
2726 (let ((pad (js2-make-pad i))
2727 (expr (js2-case-node-expr n)))
2728 (insert pad)
2729 (if (null expr)
2730 (insert "default:\n")
2731 (insert "case ")
2732 (js2-print-ast expr 0)
2733 (insert ":\n"))
2734 (dolist (kid (js2-case-node-kids n))
2735 (js2-print-ast kid (1+ i)))))
2736
2737 (defstruct (js2-throw-node
2738 (:include js2-node)
2739 (:constructor nil)
2740 (:constructor make-js2-throw-node (&key (type js2-THROW)
2741 (pos js2-ts-cursor)
2742 len expr)))
2743 "AST node for a throw statement."
2744 expr) ; the expression to throw
2745
2746 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2747 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2748
2749 (defun js2-visit-throw-node (n v)
2750 (js2-visit-ast (js2-throw-node-expr n) v))
2751
2752 (defun js2-print-throw-node (n i)
2753 (insert (js2-make-pad i) "throw ")
2754 (js2-print-ast (js2-throw-node-expr n) 0)
2755 (insert ";\n"))
2756
2757 (defstruct (js2-with-node
2758 (:include js2-node)
2759 (:constructor nil)
2760 (:constructor make-js2-with-node (&key (type js2-WITH)
2761 (pos js2-ts-cursor)
2762 len object
2763 body lp rp)))
2764 "AST node for a with-statement."
2765 object
2766 body
2767 lp ; buffer position of left-paren around object, nil if omitted
2768 rp) ; buffer position of right-paren around object, nil if omitted
2769
2770 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2771 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2772
2773 (defun js2-visit-with-node (n v)
2774 (js2-visit-ast (js2-with-node-object n) v)
2775 (js2-visit-ast (js2-with-node-body n) v))
2776
2777 (defun js2-print-with-node (n i)
2778 (let ((pad (js2-make-pad i)))
2779 (insert pad "with (")
2780 (js2-print-ast (js2-with-node-object n) 0)
2781 (insert ") {\n")
2782 (js2-print-body (js2-with-node-body n) (1+ i))
2783 (insert pad "}\n")))
2784
2785 (defstruct (js2-label-node
2786 (:include js2-node)
2787 (:constructor nil)
2788 (:constructor make-js2-label-node (&key (type js2-LABEL)
2789 (pos js2-ts-cursor)
2790 len name)))
2791 "AST node for a statement label or case label."
2792 name ; a string
2793 loop) ; for validating and code-generating continue-to-label
2794
2795 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2796 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2797
2798 (defun js2-print-label (n i)
2799 (insert (js2-make-pad i)
2800 (js2-label-node-name n)
2801 ":\n"))
2802
2803 (defstruct (js2-labeled-stmt-node
2804 (:include js2-node)
2805 (:constructor nil)
2806 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2807 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2808 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2809 (pos js2-ts-cursor)
2810 len labels stmt)))
2811 "AST node for a statement with one or more labels.
2812 Multiple labels for a statement are collapsed into the labels field."
2813 labels ; Lisp list of `js2-label-node'
2814 stmt) ; the statement these labels are for
2815
2816 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2817 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2818
2819 (defun js2-get-label-by-name (lbl-stmt name)
2820 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2821 Returns nil if no such label is in the list."
2822 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2823 result)
2824 (while (and label-list (not result))
2825 (if (string= (js2-label-node-name (car label-list)) name)
2826 (setq result (car label-list))
2827 (setq label-list (cdr label-list))))
2828 result))
2829
2830 (defun js2-visit-labeled-stmt (n v)
2831 (dolist (label (js2-labeled-stmt-node-labels n))
2832 (js2-visit-ast label v))
2833 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2834
2835 (defun js2-print-labeled-stmt (n i)
2836 (dolist (label (js2-labeled-stmt-node-labels n))
2837 (js2-print-ast label i))
2838 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2839
2840 (defun js2-labeled-stmt-node-contains (node label)
2841 "Return t if NODE contains LABEL in its label set.
2842 NODE is a `js2-labels-node'. LABEL is an identifier."
2843 (loop for nl in (js2-labeled-stmt-node-labels node)
2844 if (string= label (js2-label-node-name nl))
2845 return t
2846 finally return nil))
2847
2848 (defsubst js2-labeled-stmt-node-add-label (node label)
2849 "Add a `js2-label-node' to the label set for this statement."
2850 (setf (js2-labeled-stmt-node-labels node)
2851 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2852
2853 (defstruct (js2-jump-node
2854 (:include js2-node)
2855 (:constructor nil))
2856 "Abstract supertype of break and continue nodes."
2857 label ; `js2-name-node' for location of label identifier, if present
2858 target) ; target js2-labels-node or loop/switch statement
2859
2860 (defun js2-visit-jump-node (n v)
2861 ;; We don't visit the target, since it's a back-link.
2862 (js2-visit-ast (js2-jump-node-label n) v))
2863
2864 (defstruct (js2-break-node
2865 (:include js2-jump-node)
2866 (:constructor nil)
2867 (:constructor make-js2-break-node (&key (type js2-BREAK)
2868 (pos js2-ts-cursor)
2869 len label target)))
2870 "AST node for a break statement.
2871 The label field is a `js2-name-node', possibly nil, for the named label
2872 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2873 is the target of the break - a label node or enclosing loop/switch statement.")
2874
2875 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2876 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2877
2878 (defun js2-print-break-node (n i)
2879 (insert (js2-make-pad i) "break")
2880 (when (js2-break-node-label n)
2881 (insert " ")
2882 (js2-print-ast (js2-break-node-label n) 0))
2883 (insert ";\n"))
2884
2885 (defstruct (js2-continue-node
2886 (:include js2-jump-node)
2887 (:constructor nil)
2888 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2889 (pos js2-ts-cursor)
2890 len label target)))
2891 "AST node for a continue statement.
2892 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2893 It is nil if continue specifies no label. The target field is the jump target:
2894 a `js2-label-node' or the innermost enclosing loop.")
2895
2896 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2897 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2898
2899 (defun js2-print-continue-node (n i)
2900 (insert (js2-make-pad i) "continue")
2901 (when (js2-continue-node-label n)
2902 (insert " ")
2903 (js2-print-ast (js2-continue-node-label n) 0))
2904 (insert ";\n"))
2905
2906 (defstruct (js2-function-node
2907 (:include js2-script-node)
2908 (:constructor nil)
2909 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2910 (pos js2-ts-cursor)
2911 len
2912 (ftype 'FUNCTION)
2913 (form 'FUNCTION_STATEMENT)
2914 (name "")
2915 params rest-p
2916 body
2917 lp rp)))
2918 "AST node for a function declaration.
2919 The `params' field is a Lisp list of nodes. Each node is either a simple
2920 `js2-name-node', or if it's a destructuring-assignment parameter, a
2921 `js2-array-node' or `js2-object-node'."
2922 ftype ; FUNCTION, GETTER or SETTER
2923 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2924 name ; function name (a `js2-name-node', or nil if anonymous)
2925 params ; a Lisp list of destructuring forms or simple name nodes
2926 rest-p ; if t, the last parameter is rest parameter
2927 body ; a `js2-block-node' or expression node (1.8 only)
2928 lp ; position of arg-list open-paren, or nil if omitted
2929 rp ; position of arg-list close-paren, or nil if omitted
2930 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2931 needs-activation ; t if we need an activation object for this frame
2932 is-generator ; t if this function contains a yield
2933 member-expr) ; nonstandard Ecma extension from Rhino
2934
2935 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2936 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2937
2938 (defun js2-visit-function-node (n v)
2939 (js2-visit-ast (js2-function-node-name n) v)
2940 (dolist (p (js2-function-node-params n))
2941 (js2-visit-ast p v))
2942 (js2-visit-ast (js2-function-node-body n) v))
2943
2944 (defun js2-print-function-node (n i)
2945 (let ((pad (js2-make-pad i))
2946 (getter (js2-node-get-prop n 'GETTER_SETTER))
2947 (name (js2-function-node-name n))
2948 (params (js2-function-node-params n))
2949 (rest-p (js2-function-node-rest-p n))
2950 (body (js2-function-node-body n))
2951 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2952 (unless getter
2953 (insert pad "function"))
2954 (when name
2955 (insert " ")
2956 (js2-print-ast name 0))
2957 (insert "(")
2958 (loop with len = (length params)
2959 for param in params
2960 for count from 1
2961 do
2962 (when (and rest-p (= count len))
2963 (insert "..."))
2964 (js2-print-ast param 0)
2965 (when (< count len)
2966 (insert ", ")))
2967 (insert ") {")
2968 (unless expr
2969 (insert "\n"))
2970 ;; TODO: fix this to be smarter about indenting, etc.
2971 (js2-print-body body (1+ i))
2972 (insert pad "}")
2973 (unless expr
2974 (insert "\n"))))
2975
2976 (defun js2-function-name (node)
2977 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2978 (and (js2-function-node-name node)
2979 (js2-name-node-name (js2-function-node-name node))))
2980
2981 ;; Having this be an expression node makes it more flexible.
2982 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2983 ;; that work better if you assume it's an expression. Whenever we have
2984 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2985 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2986 (defstruct (js2-var-decl-node
2987 (:include js2-node)
2988 (:constructor nil)
2989 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2990 (pos js2-token-beg)
2991 len kids
2992 decl-type)))
2993 "AST node for a variable declaration list (VAR, CONST or LET).
2994 The node bounds differ depending on the declaration type. For VAR or
2995 CONST declarations, the bounds include the var/const keyword. For LET
2996 declarations, the node begins at the position of the first child."
2997 kids ; a Lisp list of `js2-var-init-node' structs.
2998 decl-type) ; js2-VAR, js2-CONST or js2-LET
2999
3000 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3001 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3002
3003 (defun js2-visit-var-decl (n v)
3004 (dolist (kid (js2-var-decl-node-kids n))
3005 (js2-visit-ast kid v)))
3006
3007 (defun js2-print-var-decl (n i)
3008 (let ((pad (js2-make-pad i))
3009 (tt (js2-var-decl-node-decl-type n)))
3010 (insert pad)
3011 (insert (cond
3012 ((= tt js2-VAR) "var ")
3013 ((= tt js2-LET) "let ")
3014 ((= tt js2-CONST) "const ")
3015 (t
3016 (error "malformed var-decl node"))))
3017 (loop with kids = (js2-var-decl-node-kids n)
3018 with len = (length kids)
3019 for kid in kids
3020 for count from 1
3021 do
3022 (js2-print-ast kid 0)
3023 (if (< count len)
3024 (insert ", ")))))
3025
3026 (defstruct (js2-var-init-node
3027 (:include js2-node)
3028 (:constructor nil)
3029 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3030 (pos js2-ts-cursor)
3031 len target
3032 initializer)))
3033 "AST node for a variable declaration.
3034 The type field will be js2-CONST for a const decl."
3035 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3036 initializer) ; initializer expression, a `js2-node'
3037
3038 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3039 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3040
3041 (defun js2-visit-var-init-node (n v)
3042 (js2-visit-ast (js2-var-init-node-target n) v)
3043 (js2-visit-ast (js2-var-init-node-initializer n) v))
3044
3045 (defun js2-print-var-init-node (n i)
3046 (let ((pad (js2-make-pad i))
3047 (name (js2-var-init-node-target n))
3048 (init (js2-var-init-node-initializer n)))
3049 (insert pad)
3050 (js2-print-ast name 0)
3051 (when init
3052 (insert " = ")
3053 (js2-print-ast init 0))))
3054
3055 (defstruct (js2-cond-node
3056 (:include js2-node)
3057 (:constructor nil)
3058 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3059 (pos js2-ts-cursor)
3060 len
3061 test-expr
3062 true-expr
3063 false-expr
3064 q-pos c-pos)))
3065 "AST node for the ternary operator"
3066 test-expr
3067 true-expr
3068 false-expr
3069 q-pos ; buffer position of ?
3070 c-pos) ; buffer position of :
3071
3072 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3073 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3074
3075 (defun js2-visit-cond-node (n v)
3076 (js2-visit-ast (js2-cond-node-test-expr n) v)
3077 (js2-visit-ast (js2-cond-node-true-expr n) v)
3078 (js2-visit-ast (js2-cond-node-false-expr n) v))
3079
3080 (defun js2-print-cond-node (n i)
3081 (let ((pad (js2-make-pad i)))
3082 (insert pad)
3083 (js2-print-ast (js2-cond-node-test-expr n) 0)
3084 (insert " ? ")
3085 (js2-print-ast (js2-cond-node-true-expr n) 0)
3086 (insert " : ")
3087 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3088
3089 (defstruct (js2-infix-node
3090 (:include js2-node)
3091 (:constructor nil)
3092 (:constructor make-js2-infix-node (&key type
3093 (pos js2-ts-cursor)
3094 len op-pos
3095 left right)))
3096 "Represents infix expressions.
3097 Includes assignment ops like `|=', and the comma operator.
3098 The type field inherited from `js2-node' holds the operator."
3099 op-pos ; buffer position where operator begins
3100 left ; any `js2-node'
3101 right) ; any `js2-node'
3102
3103 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3104 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3105
3106 (defun js2-visit-infix-node (n v)
3107 (js2-visit-ast (js2-infix-node-left n) v)
3108 (js2-visit-ast (js2-infix-node-right n) v))
3109
3110 (defconst js2-operator-tokens
3111 (let ((table (make-hash-table :test 'eq))
3112 (tokens
3113 (list (cons js2-IN "in")
3114 (cons js2-TYPEOF "typeof")
3115 (cons js2-INSTANCEOF "instanceof")
3116 (cons js2-DELPROP "delete")
3117 (cons js2-COMMA ",")
3118 (cons js2-COLON ":")
3119 (cons js2-OR "||")
3120 (cons js2-AND "&&")
3121 (cons js2-INC "++")
3122 (cons js2-DEC "--")
3123 (cons js2-BITOR "|")
3124 (cons js2-BITXOR "^")
3125 (cons js2-BITAND "&")
3126 (cons js2-EQ "==")
3127 (cons js2-NE "!=")
3128 (cons js2-LT "<")
3129 (cons js2-LE "<=")
3130 (cons js2-GT ">")
3131 (cons js2-GE ">=")
3132 (cons js2-LSH "<<")
3133 (cons js2-RSH ">>")
3134 (cons js2-URSH ">>>")
3135 (cons js2-ADD "+") ; infix plus
3136 (cons js2-SUB "-") ; infix minus
3137 (cons js2-MUL "*")
3138 (cons js2-DIV "/")
3139 (cons js2-MOD "%")
3140 (cons js2-NOT "!")
3141 (cons js2-BITNOT "~")
3142 (cons js2-POS "+") ; unary plus
3143 (cons js2-NEG "-") ; unary minus
3144 (cons js2-SHEQ "===") ; shallow equality
3145 (cons js2-SHNE "!==") ; shallow inequality
3146 (cons js2-ASSIGN "=")
3147 (cons js2-ASSIGN_BITOR "|=")
3148 (cons js2-ASSIGN_BITXOR "^=")
3149 (cons js2-ASSIGN_BITAND "&=")
3150 (cons js2-ASSIGN_LSH "<<=")
3151 (cons js2-ASSIGN_RSH ">>=")
3152 (cons js2-ASSIGN_URSH ">>>=")
3153 (cons js2-ASSIGN_ADD "+=")
3154 (cons js2-ASSIGN_SUB "-=")
3155 (cons js2-ASSIGN_MUL "*=")
3156 (cons js2-ASSIGN_DIV "/=")
3157 (cons js2-ASSIGN_MOD "%="))))
3158 (loop for (k . v) in tokens do
3159 (puthash k v table))
3160 table))
3161
3162 (defun js2-print-infix-node (n i)
3163 (let* ((tt (js2-node-type n))
3164 (op (gethash tt js2-operator-tokens)))
3165 (unless op
3166 (error "unrecognized infix operator %s" (js2-node-type n)))
3167 (insert (js2-make-pad i))
3168 (js2-print-ast (js2-infix-node-left n) 0)
3169 (unless (= tt js2-COMMA)
3170 (insert " "))
3171 (insert op)
3172 (insert " ")
3173 (js2-print-ast (js2-infix-node-right n) 0)))
3174
3175 (defstruct (js2-assign-node
3176 (:include js2-infix-node)
3177 (:constructor nil)
3178 (:constructor make-js2-assign-node (&key type
3179 (pos js2-ts-cursor)
3180 len op-pos
3181 left right)))
3182 "Represents any assignment.
3183 The type field holds the actual assignment operator.")
3184
3185 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3186 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3187
3188 (defstruct (js2-unary-node
3189 (:include js2-node)
3190 (:constructor nil)
3191 (:constructor make-js2-unary-node (&key type ; required
3192 (pos js2-ts-cursor)
3193 len operand)))
3194 "AST node type for unary operator nodes.
3195 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3196 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3197 property is added if the operator follows the operand."
3198 operand) ; a `js2-node' expression
3199
3200 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3201 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3202
3203 (defun js2-visit-unary-node (n v)
3204 (js2-visit-ast (js2-unary-node-operand n) v))
3205
3206 (defun js2-print-unary-node (n i)
3207 (let* ((tt (js2-node-type n))
3208 (op (gethash tt js2-operator-tokens))
3209 (postfix (js2-node-get-prop n 'postfix)))
3210 (unless op
3211 (error "unrecognized unary operator %s" tt))
3212 (insert (js2-make-pad i))
3213 (unless postfix
3214 (insert op))
3215 (if (or (= tt js2-TYPEOF)
3216 (= tt js2-DELPROP))
3217 (insert " "))
3218 (js2-print-ast (js2-unary-node-operand n) 0)
3219 (when postfix
3220 (insert op))))
3221
3222 (defstruct (js2-let-node
3223 (:include js2-scope)
3224 (:constructor nil)
3225 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3226 (pos js2-token-beg)
3227 len vars body
3228 lp rp)))
3229 "AST node for a let expression or a let statement.
3230 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3231 vars ; a `js2-var-decl-node'
3232 body ; a `js2-node' representing the expression or body block
3233 lp
3234 rp)
3235
3236 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3237 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3238
3239 (defun js2-visit-let-node (n v)
3240 (js2-visit-ast (js2-let-node-vars n) v)
3241 (js2-visit-ast (js2-let-node-body n) v))
3242
3243 (defun js2-print-let-node (n i)
3244 (insert (js2-make-pad i) "let (")
3245 (js2-print-ast (js2-let-node-vars n) 0)
3246 (insert ") ")
3247 (js2-print-ast (js2-let-node-body n) i))
3248
3249 (defstruct (js2-keyword-node
3250 (:include js2-node)
3251 (:constructor nil)
3252 (:constructor make-js2-keyword-node (&key type
3253 (pos js2-token-beg)
3254 (len (- js2-ts-cursor pos)))))
3255 "AST node representing a literal keyword such as `null'.
3256 Used for `null', `this', `true', `false' and `debugger'.
3257 The node type is set to js2-NULL, js2-THIS, etc.")
3258
3259 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3260 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3261
3262 (defun js2-print-keyword-node (n i)
3263 (insert (js2-make-pad i)
3264 (let ((tt (js2-node-type n)))
3265 (cond
3266 ((= tt js2-THIS) "this")
3267 ((= tt js2-NULL) "null")
3268 ((= tt js2-TRUE) "true")
3269 ((= tt js2-FALSE) "false")
3270 ((= tt js2-DEBUGGER) "debugger")
3271 (t (error "Invalid keyword literal type: %d" tt))))))
3272
3273 (defsubst js2-this-node-p (node)
3274 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3275 (eq (js2-node-type node) js2-THIS))
3276
3277 (defstruct (js2-new-node
3278 (:include js2-node)
3279 (:constructor nil)
3280 (:constructor make-js2-new-node (&key (type js2-NEW)
3281 (pos js2-token-beg)
3282 len target
3283 args initializer
3284 lp rp)))
3285 "AST node for new-expression such as new Foo()."
3286 target ; an identifier or reference
3287 args ; a Lisp list of argument nodes
3288 lp ; position of left-paren, nil if omitted
3289 rp ; position of right-paren, nil if omitted
3290 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3291
3292 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3293 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3294
3295 (defun js2-visit-new-node (n v)
3296 (js2-visit-ast (js2-new-node-target n) v)
3297 (dolist (arg (js2-new-node-args n))
3298 (js2-visit-ast arg v))
3299 (js2-visit-ast (js2-new-node-initializer n) v))
3300
3301 (defun js2-print-new-node (n i)
3302 (insert (js2-make-pad i) "new ")
3303 (js2-print-ast (js2-new-node-target n))
3304 (insert "(")
3305 (js2-print-list (js2-new-node-args n))
3306 (insert ")")
3307 (when (js2-new-node-initializer n)
3308 (insert " ")
3309 (js2-print-ast (js2-new-node-initializer n))))
3310
3311 (defstruct (js2-name-node
3312 (:include js2-node)
3313 (:constructor nil)
3314 (:constructor make-js2-name-node (&key (type js2-NAME)
3315 (pos js2-token-beg)
3316 (len (- js2-ts-cursor
3317 js2-token-beg))
3318 (name js2-ts-string))))
3319 "AST node for a JavaScript identifier"
3320 name ; a string
3321 scope) ; a `js2-scope' (optional, used for codegen)
3322
3323 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3324 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3325
3326 (defun js2-print-name-node (n i)
3327 (insert (js2-make-pad i)
3328 (js2-name-node-name n)))
3329
3330 (defsubst js2-name-node-length (node)
3331 "Return identifier length of NODE, a `js2-name-node'.
3332 Returns 0 if NODE is nil or its identifier field is nil."
3333 (if node
3334 (length (js2-name-node-name node))
3335 0))
3336
3337 (defstruct (js2-number-node
3338 (:include js2-node)
3339 (:constructor nil)
3340 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3341 (pos js2-token-beg)
3342 (len (- js2-ts-cursor
3343 js2-token-beg))
3344 (value js2-ts-string)
3345 (num-value js2-ts-number))))
3346 "AST node for a number literal."
3347 value ; the original string, e.g. "6.02e23"
3348 num-value) ; the parsed number value
3349
3350 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3351 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3352
3353 (defun js2-print-number-node (n i)
3354 (insert (js2-make-pad i)
3355 (number-to-string (js2-number-node-num-value n))))
3356
3357 (defstruct (js2-regexp-node
3358 (:include js2-node)
3359 (:constructor nil)
3360 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3361 (pos js2-token-beg)
3362 (len (- js2-ts-cursor
3363 js2-token-beg))
3364 value flags)))
3365 "AST node for a regular expression literal."
3366 value ; the regexp string, without // delimiters
3367 flags) ; a string of flags, e.g. `mi'.
3368
3369 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3370 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3371
3372 (defun js2-print-regexp (n i)
3373 (insert (js2-make-pad i)
3374 "/"
3375 (js2-regexp-node-value n)
3376 "/")
3377 (if (js2-regexp-node-flags n)
3378 (insert (js2-regexp-node-flags n))))
3379
3380 (defstruct (js2-string-node
3381 (:include js2-node)
3382 (:constructor nil)
3383 (:constructor make-js2-string-node (&key (type js2-STRING)
3384 (pos js2-token-beg)
3385 (len (- js2-ts-cursor
3386 js2-token-beg))
3387 (value js2-ts-string))))
3388 "String literal.
3389 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3390 You can tell the quote type by looking at the first character."
3391 value) ; the characters of the string, including the quotes
3392
3393 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3394 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3395
3396 (defun js2-print-string-node (n i)
3397 (insert (js2-make-pad i)
3398 (js2-node-string n)))
3399
3400 (defstruct (js2-array-node
3401 (:include js2-node)
3402 (:constructor nil)
3403 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3404 (pos js2-ts-cursor)
3405 len elems)))
3406 "AST node for an array literal."
3407 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3408
3409 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3410 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3411
3412 (defun js2-visit-array-node (n v)
3413 (dolist (e (js2-array-node-elems n))
3414 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3415
3416 (defun js2-print-array-node (n i)
3417 (insert (js2-make-pad i) "[")
3418 (js2-print-list (js2-array-node-elems n))
3419 (insert "]"))
3420
3421 (defstruct (js2-object-node
3422 (:include js2-node)
3423 (:constructor nil)
3424 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3425 (pos js2-ts-cursor)
3426 len
3427 elems)))
3428 "AST node for an object literal expression.
3429 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3430 The latter represents abbreviation in destructuring expressions."
3431 elems)
3432
3433 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3434 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3435
3436 (defun js2-visit-object-node (n v)
3437 (dolist (e (js2-object-node-elems n))
3438 (js2-visit-ast e v)))
3439
3440 (defun js2-print-object-node (n i)
3441 (insert (js2-make-pad i) "{")
3442 (js2-print-list (js2-object-node-elems n))
3443 (insert "}"))
3444
3445 (defstruct (js2-object-prop-node
3446 (:include js2-infix-node)
3447 (:constructor nil)
3448 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3449 (pos js2-ts-cursor)
3450 len left
3451 right op-pos)))
3452 "AST node for an object literal prop:value entry.
3453 The `left' field is the property: a name node, string node or number node.
3454 The `right' field is a `js2-node' representing the initializer value.")
3455
3456 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3457 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3458
3459 (defun js2-print-object-prop-node (n i)
3460 (insert (js2-make-pad i))
3461 (js2-print-ast (js2-object-prop-node-left n) 0)
3462 (insert ": ")
3463 (js2-print-ast (js2-object-prop-node-right n) 0))
3464
3465 (defstruct (js2-getter-setter-node
3466 (:include js2-infix-node)
3467 (:constructor nil)
3468 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3469 (pos js2-ts-cursor)
3470 len left right)))
3471 "AST node for a getter/setter property in an object literal.
3472 The `left' field is the `js2-name-node' naming the getter/setter prop.
3473 The `right' field is always an anonymous `js2-function-node' with a node
3474 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3475
3476 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3477 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3478
3479 (defun js2-print-getter-setter (n i)
3480 (let ((pad (js2-make-pad i))
3481 (left (js2-getter-setter-node-left n))
3482 (right (js2-getter-setter-node-right n)))
3483 (insert pad)
3484 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3485 (js2-print-ast left 0)
3486 (js2-print-ast right 0)))
3487
3488 (defstruct (js2-prop-get-node
3489 (:include js2-infix-node)
3490 (:constructor nil)
3491 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3492 (pos js2-ts-cursor)
3493 len left right)))
3494 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3495
3496 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3497 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3498
3499 (defun js2-visit-prop-get-node (n v)
3500 (js2-visit-ast (js2-prop-get-node-left n) v)
3501 (js2-visit-ast (js2-prop-get-node-right n) v))
3502
3503 (defun js2-print-prop-get-node (n i)
3504 (insert (js2-make-pad i))
3505 (js2-print-ast (js2-prop-get-node-left n) 0)
3506 (insert ".")
3507 (js2-print-ast (js2-prop-get-node-right n) 0))
3508
3509 (defstruct (js2-elem-get-node
3510 (:include js2-node)
3511 (:constructor nil)
3512 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3513 (pos js2-ts-cursor)
3514 len target element
3515 lb rb)))
3516 "AST node for an array index expression such as foo[bar]."
3517 target ; a `js2-node' - the expression preceding the "."
3518 element ; a `js2-node' - the expression in brackets
3519 lb ; position of left-bracket, nil if omitted
3520 rb) ; position of right-bracket, nil if omitted
3521
3522 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3523 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3524
3525 (defun js2-visit-elem-get-node (n v)
3526 (js2-visit-ast (js2-elem-get-node-target n) v)
3527 (js2-visit-ast (js2-elem-get-node-element n) v))
3528
3529 (defun js2-print-elem-get-node (n i)
3530 (insert (js2-make-pad i))
3531 (js2-print-ast (js2-elem-get-node-target n) 0)
3532 (insert "[")
3533 (js2-print-ast (js2-elem-get-node-element n) 0)
3534 (insert "]"))
3535
3536 (defstruct (js2-call-node
3537 (:include js2-node)
3538 (:constructor nil)
3539 (:constructor make-js2-call-node (&key (type js2-CALL)
3540 (pos js2-ts-cursor)
3541 len target args
3542 lp rp)))
3543 "AST node for a JavaScript function call."
3544 target ; a `js2-node' evaluating to the function to call
3545 args ; a Lisp list of `js2-node' arguments
3546 lp ; position of open-paren, or nil if missing
3547 rp) ; position of close-paren, or nil if missing
3548
3549 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3550 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3551
3552 (defun js2-visit-call-node (n v)
3553 (js2-visit-ast (js2-call-node-target n) v)
3554 (dolist (arg (js2-call-node-args n))
3555 (js2-visit-ast arg v)))
3556
3557 (defun js2-print-call-node (n i)
3558 (insert (js2-make-pad i))
3559 (js2-print-ast (js2-call-node-target n) 0)
3560 (insert "(")
3561 (js2-print-list (js2-call-node-args n))
3562 (insert ")"))
3563
3564 (defstruct (js2-yield-node
3565 (:include js2-node)
3566 (:constructor nil)
3567 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3568 (pos js2-ts-cursor)
3569 len value)))
3570 "AST node for yield statement or expression."
3571 value) ; optional: value to be yielded
3572
3573 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3574 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3575
3576 (defun js2-visit-yield-node (n v)
3577 (js2-visit-ast (js2-yield-node-value n) v))
3578
3579 (defun js2-print-yield-node (n i)
3580 (insert (js2-make-pad i))
3581 (insert "yield")
3582 (when (js2-yield-node-value n)
3583 (insert " ")
3584 (js2-print-ast (js2-yield-node-value n) 0)))
3585
3586 (defstruct (js2-paren-node
3587 (:include js2-node)
3588 (:constructor nil)
3589 (:constructor make-js2-paren-node (&key (type js2-LP)
3590 (pos js2-ts-cursor)
3591 len expr)))
3592 "AST node for a parenthesized expression.
3593 In particular, used when the parens are syntactically optional,
3594 as opposed to required parens such as those enclosing an if-conditional."
3595 expr) ; `js2-node'
3596
3597 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3598 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3599
3600 (defun js2-visit-paren-node (n v)
3601 (js2-visit-ast (js2-paren-node-expr n) v))
3602
3603 (defun js2-print-paren-node (n i)
3604 (insert (js2-make-pad i))
3605 (insert "(")
3606 (js2-print-ast (js2-paren-node-expr n) 0)
3607 (insert ")"))
3608
3609 (defstruct (js2-array-comp-node
3610 (:include js2-scope)
3611 (:constructor nil)
3612 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3613 (pos js2-ts-cursor)
3614 len result
3615 loops filter
3616 if-pos lp rp)))
3617 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3618 result ; result expression (just after left-bracket)
3619 loops ; a Lisp list of `js2-array-comp-loop-node'
3620 filter ; guard/filter expression
3621 if-pos ; buffer pos of 'if' keyword, if present, else nil
3622 lp ; buffer position of if-guard left-paren, or nil if not present
3623 rp) ; buffer position of if-guard right-paren, or nil if not present
3624
3625 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3626 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3627
3628 (defun js2-visit-array-comp-node (n v)
3629 (js2-visit-ast (js2-array-comp-node-result n) v)
3630 (dolist (l (js2-array-comp-node-loops n))
3631 (js2-visit-ast l v))
3632 (js2-visit-ast (js2-array-comp-node-filter n) v))
3633
3634 (defun js2-print-array-comp-node (n i)
3635 (let ((pad (js2-make-pad i))
3636 (result (js2-array-comp-node-result n))
3637 (loops (js2-array-comp-node-loops n))
3638 (filter (js2-array-comp-node-filter n)))
3639 (insert pad "[")
3640 (js2-print-ast result 0)
3641 (dolist (l loops)
3642 (insert " ")
3643 (js2-print-ast l 0))
3644 (when filter
3645 (insert " if (")
3646 (js2-print-ast filter 0)
3647 (insert ")"))
3648 (insert "]")))
3649
3650 (defstruct (js2-array-comp-loop-node
3651 (:include js2-for-in-node)
3652 (:constructor nil)
3653 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3654 (pos js2-ts-cursor)
3655 len iterator
3656 object in-pos
3657 foreach-p
3658 each-pos
3659 forof-p
3660 lp rp)))
3661 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3662
3663 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3664 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3665
3666 (defun js2-visit-array-comp-loop (n v)
3667 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3668 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3669
3670 (defun js2-print-array-comp-loop (n i)
3671 (insert "for ")
3672 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3673 (insert "(")
3674 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3675 (if (js2-array-comp-loop-node-forof-p n)
3676 (insert " of ")
3677 (insert " in "))
3678 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3679 (insert ")"))
3680
3681 (defstruct (js2-empty-expr-node
3682 (:include js2-node)
3683 (:constructor nil)
3684 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3685 (pos js2-token-beg)
3686 len)))
3687 "AST node for an empty expression.")
3688
3689 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3690 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3691
3692 (defstruct (js2-xml-node
3693 (:include js2-block-node)
3694 (:constructor nil)
3695 (:constructor make-js2-xml-node (&key (type js2-XML)
3696 (pos js2-token-beg)
3697 len kids)))
3698 "AST node for initial parse of E4X literals.
3699 The kids field is a list of XML fragments, each a `js2-string-node' or
3700 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3701
3702 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3703 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3704
3705 (defun js2-print-xml-node (n i)
3706 (dolist (kid (js2-xml-node-kids n))
3707 (js2-print-ast kid i)))
3708
3709 (defstruct (js2-xml-js-expr-node
3710 (:include js2-xml-node)
3711 (:constructor nil)
3712 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3713 (pos js2-ts-cursor)
3714 len expr)))
3715 "AST node for an embedded JavaScript {expression} in an E4X literal.
3716 The start and end fields correspond to the curly-braces."
3717 expr) ; a `js2-expr-node' of some sort
3718
3719 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3720 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3721
3722 (defun js2-visit-xml-js-expr (n v)
3723 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3724
3725 (defun js2-print-xml-js-expr (n i)
3726 (insert (js2-make-pad i))
3727 (insert "{")
3728 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3729 (insert "}"))
3730
3731 (defstruct (js2-xml-dot-query-node
3732 (:include js2-infix-node)
3733 (:constructor nil)
3734 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3735 (pos js2-ts-cursor)
3736 op-pos len left
3737 right rp)))
3738 "AST node for an E4X foo.(bar) filter expression.
3739 Note that the left-paren is automatically the character immediately
3740 following the dot (.) in the operator. No whitespace is permitted
3741 between the dot and the lp by the scanner."
3742 rp)
3743
3744 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3745 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3746
3747 (defun js2-print-xml-dot-query (n i)
3748 (insert (js2-make-pad i))
3749 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3750 (insert ".(")
3751 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3752 (insert ")"))
3753
3754 (defstruct (js2-xml-ref-node
3755 (:include js2-node)
3756 (:constructor nil)) ; abstract
3757 "Base type for E4X XML attribute-access or property-get expressions.
3758 Such expressions can take a variety of forms. The general syntax has
3759 three parts:
3760
3761 - (optional) an @ (specifying an attribute access)
3762 - (optional) a namespace (a `js2-name-node') and double-colon
3763 - (required) either a `js2-name-node' or a bracketed [expression]
3764
3765 The property-name expressions (examples: ns::name, @name) are
3766 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3767 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3768
3769 This node type (or more specifically, its subclasses) will sometimes
3770 be the right-hand child of a `js2-prop-get-node' or a
3771 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3772 The `js2-xml-ref-node' may also be a standalone primary expression with
3773 no explicit target, which is valid in certain expression contexts such as
3774
3775 company..employee.(@id < 100)
3776
3777 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3778 expression whose parent is a `js2-xml-dot-query-node'."
3779 namespace
3780 at-pos
3781 colon-pos)
3782
3783 (defsubst js2-xml-ref-node-attr-access-p (node)
3784 "Return non-nil if this expression began with an @-token."
3785 (and (numberp (js2-xml-ref-node-at-pos node))
3786 (plusp (js2-xml-ref-node-at-pos node))))
3787
3788 (defstruct (js2-xml-prop-ref-node
3789 (:include js2-xml-ref-node)
3790 (:constructor nil)
3791 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3792 (pos js2-token-beg)
3793 len propname
3794 namespace at-pos
3795 colon-pos)))
3796 "AST node for an E4X XML [expr] property-ref expression.
3797 The JavaScript syntax is an optional @, an optional ns::, and a name.
3798
3799 [ '@' ] [ name '::' ] name
3800
3801 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3802 @ns::*, @*::attr, @*::*, and @*.
3803
3804 The node starts at the @ token, if present. Otherwise it starts at the
3805 namespace name. The node bounds extend through the closing right-bracket,
3806 or if it is missing due to a syntax error, through the end of the index
3807 expression."
3808 propname)
3809
3810 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3811 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3812
3813 (defun js2-visit-xml-prop-ref-node (n v)
3814 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3815 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3816
3817 (defun js2-print-xml-prop-ref-node (n i)
3818 (insert (js2-make-pad i))
3819 (if (js2-xml-ref-node-attr-access-p n)
3820 (insert "@"))
3821 (when (js2-xml-prop-ref-node-namespace n)
3822 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3823 (insert "::"))
3824 (if (js2-xml-prop-ref-node-propname n)
3825 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3826
3827 (defstruct (js2-xml-elem-ref-node
3828 (:include js2-xml-ref-node)
3829 (:constructor nil)
3830 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3831 (pos js2-token-beg)
3832 len expr lb rb
3833 namespace at-pos
3834 colon-pos)))
3835 "AST node for an E4X XML [expr] member-ref expression.
3836 Syntax:
3837
3838 [ '@' ] [ name '::' ] '[' expr ']'
3839
3840 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3841
3842 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3843 is not a legal E4X XML element-ref expression, since it's already used
3844 for standard JavaScript element-get array indexing. Hence, a
3845 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3846 non-nil namespace node, or both.
3847
3848 The node starts at the @ token, if present. Otherwise it starts
3849 at the namespace name. The node bounds extend through the closing
3850 right-bracket, or if it is missing due to a syntax error, through the
3851 end of the index expression."
3852 expr ; the bracketed index expression
3853 lb
3854 rb)
3855
3856 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3857 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3858
3859 (defun js2-visit-xml-elem-ref-node (n v)
3860 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3861 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3862
3863 (defun js2-print-xml-elem-ref-node (n i)
3864 (insert (js2-make-pad i))
3865 (if (js2-xml-ref-node-attr-access-p n)
3866 (insert "@"))
3867 (when (js2-xml-elem-ref-node-namespace n)
3868 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3869 (insert "::"))
3870 (insert "[")
3871 (if (js2-xml-elem-ref-node-expr n)
3872 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3873 (insert "]"))
3874
3875 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3876
3877 (defstruct (js2-xml-start-tag-node
3878 (:include js2-xml-node)
3879 (:constructor nil)
3880 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3881 (pos js2-ts-cursor)
3882 len name attrs kids
3883 empty-p)))
3884 "AST node for an XML start-tag. Not currently used.
3885 The `kids' field is a Lisp list of child content nodes."
3886 name ; a `js2-xml-name-node'
3887 attrs ; a Lisp list of `js2-xml-attr-node'
3888 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3889
3890 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3891 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3892
3893 (defun js2-visit-xml-start-tag (n v)
3894 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3895 (dolist (attr (js2-xml-start-tag-node-attrs n))
3896 (js2-visit-ast attr v))
3897 (js2-visit-block n v))
3898
3899 (defun js2-print-xml-start-tag (n i)
3900 (insert (js2-make-pad i) "<")
3901 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3902 (when (js2-xml-start-tag-node-attrs n)
3903 (insert " ")
3904 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3905 (insert ">"))
3906
3907 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3908 ;; and add the end-tag to the kids list of the parent as well.
3909 (defstruct (js2-xml-end-tag-node
3910 (:include js2-xml-node)
3911 (:constructor nil)
3912 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3913 (pos js2-ts-cursor)
3914 len name)))
3915 "AST node for an XML end-tag. Not currently used."
3916 name) ; a `js2-xml-name-node'
3917
3918 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3919 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3920
3921 (defun js2-visit-xml-end-tag (n v)
3922 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3923
3924 (defun js2-print-xml-end-tag (n i)
3925 (insert (js2-make-pad i))
3926 (insert "</")
3927 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3928 (insert ">"))
3929
3930 (defstruct (js2-xml-name-node
3931 (:include js2-xml-node)
3932 (:constructor nil)
3933 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3934 (pos js2-ts-cursor)
3935 len namespace kids)))
3936 "AST node for an E4X XML name. Not currently used.
3937 Any XML name can be qualified with a namespace, hence the namespace field.
3938 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3939 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3940 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3941 namespace) ; a `js2-string-node'
3942
3943 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3944 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3945
3946 (defun js2-visit-xml-name-node (n v)
3947 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3948
3949 (defun js2-print-xml-name-node (n i)
3950 (insert (js2-make-pad i))
3951 (when (js2-xml-name-node-namespace n)
3952 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3953 (insert "::"))
3954 (dolist (kid (js2-xml-name-node-kids n))
3955 (js2-print-ast kid 0)))
3956
3957 (defstruct (js2-xml-pi-node
3958 (:include js2-xml-node)
3959 (:constructor nil)
3960 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3961 (pos js2-ts-cursor)
3962 len name attrs)))
3963 "AST node for an E4X XML processing instruction. Not currently used."
3964 name ; a `js2-xml-name-node'
3965 attrs) ; a list of `js2-xml-attr-node'
3966
3967 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3968 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3969
3970 (defun js2-visit-xml-pi-node (n v)
3971 (js2-visit-ast (js2-xml-pi-node-name n) v)
3972 (dolist (attr (js2-xml-pi-node-attrs n))
3973 (js2-visit-ast attr v)))
3974
3975 (defun js2-print-xml-pi-node (n i)
3976 (insert (js2-make-pad i) "<?")
3977 (js2-print-ast (js2-xml-pi-node-name n))
3978 (when (js2-xml-pi-node-attrs n)
3979 (insert " ")
3980 (js2-print-list (js2-xml-pi-node-attrs n)))
3981 (insert "?>"))
3982
3983 (defstruct (js2-xml-cdata-node
3984 (:include js2-xml-node)
3985 (:constructor nil)
3986 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3987 (pos js2-ts-cursor)
3988 len content)))
3989 "AST node for a CDATA escape section. Not currently used."
3990 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3991
3992 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3993 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3994
3995 (defun js2-visit-xml-cdata-node (n v)
3996 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3997
3998 (defun js2-print-xml-cdata-node (n i)
3999 (insert (js2-make-pad i))
4000 (js2-print-ast (js2-xml-cdata-node-content n)))
4001
4002 (defstruct (js2-xml-attr-node
4003 (:include js2-xml-node)
4004 (:constructor nil)
4005 (:constructor make-js2-attr-node (&key (type js2-XML)
4006 (pos js2-ts-cursor)
4007 len name value
4008 eq-pos quote-type)))
4009 "AST node representing a foo='bar' XML attribute value. Not yet used."
4010 name ; a `js2-xml-name-node'
4011 value ; a `js2-xml-name-node'
4012 eq-pos ; buffer position of "=" sign
4013 quote-type) ; 'single or 'double
4014
4015 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4016 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4017
4018 (defun js2-visit-xml-attr-node (n v)
4019 (js2-visit-ast (js2-xml-attr-node-name n) v)
4020 (js2-visit-ast (js2-xml-attr-node-value n) v))
4021
4022 (defun js2-print-xml-attr-node (n i)
4023 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4024 "'"
4025 "\"")))
4026 (insert (js2-make-pad i))
4027 (js2-print-ast (js2-xml-attr-node-name n) 0)
4028 (insert "=" quote)
4029 (js2-print-ast (js2-xml-attr-node-value n) 0)
4030 (insert quote)))
4031
4032 (defstruct (js2-xml-text-node
4033 (:include js2-xml-node)
4034 (:constructor nil)
4035 (:constructor make-js2-text-node (&key (type js2-XML)
4036 (pos js2-ts-cursor)
4037 len content)))
4038 "AST node for an E4X XML text node. Not currently used."
4039 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4040
4041 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4042 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4043
4044 (defun js2-visit-xml-text-node (n v)
4045 (js2-visit-ast (js2-xml-text-node-content n) v))
4046
4047 (defun js2-print-xml-text-node (n i)
4048 (insert (js2-make-pad i))
4049 (dolist (kid (js2-xml-text-node-content n))
4050 (js2-print-ast kid)))
4051
4052 (defstruct (js2-xml-comment-node
4053 (:include js2-xml-node)
4054 (:constructor nil)
4055 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4056 (pos js2-ts-cursor)
4057 len)))
4058 "AST node for E4X XML comment. Not currently used.")
4059
4060 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4061 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4062
4063 (defun js2-print-xml-comment (n i)
4064 (insert (js2-make-pad i)
4065 (js2-node-string n)))
4066
4067 ;;; Node utilities
4068
4069 (defsubst js2-node-line (n)
4070 "Fetch the source line number at the start of node N.
4071 This is O(n) in the length of the source buffer; use prudently."
4072 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4073
4074 (defsubst js2-block-node-kid (n i)
4075 "Return child I of node N, or nil if there aren't that many."
4076 (nth i (js2-block-node-kids n)))
4077
4078 (defsubst js2-block-node-first (n)
4079 "Return first child of block node N, or nil if there is none."
4080 (first (js2-block-node-kids n)))
4081
4082 (defun js2-node-root (n)
4083 "Return the root of the AST containing N.
4084 If N has no parent pointer, returns N."
4085 (let ((parent (js2-node-parent n)))
4086 (if parent
4087 (js2-node-root parent)
4088 n)))
4089
4090 (defun js2-node-position-in-parent (node &optional parent)
4091 "Return the position of NODE in parent's block-kids list.
4092 PARENT can be supplied if known. Positioned returned is zero-indexed.
4093 Returns 0 if NODE is not a child of a block statement, or if NODE
4094 is not a statement node."
4095 (let ((p (or parent (js2-node-parent node)))
4096 (i 0))
4097 (if (not (js2-block-node-p p))
4098 i
4099 (or (js2-position node (js2-block-node-kids p))
4100 0))))
4101
4102 (defsubst js2-node-short-name (n)
4103 "Return the short name of node N as a string, e.g. `js2-if-node'."
4104 (substring (symbol-name (aref n 0))
4105 (length "cl-struct-")))
4106
4107 (defun js2-node-child-list (node)
4108 "Return the child list for NODE, a Lisp list of nodes.
4109 Works for block nodes, array nodes, obj literals, funarg lists,
4110 var decls and try nodes (for catch clauses). Note that you should call
4111 `js2-block-node-kids' on the function body for the body statements.
4112 Returns nil for zero-length child lists or unsupported nodes."
4113 (cond
4114 ((js2-function-node-p node)
4115 (js2-function-node-params node))
4116 ((js2-block-node-p node)
4117 (js2-block-node-kids node))
4118 ((js2-try-node-p node)
4119 (js2-try-node-catch-clauses node))
4120 ((js2-array-node-p node)
4121 (js2-array-node-elems node))
4122 ((js2-object-node-p node)
4123 (js2-object-node-elems node))
4124 ((js2-call-node-p node)
4125 (js2-call-node-args node))
4126 ((js2-new-node-p node)
4127 (js2-new-node-args node))
4128 ((js2-var-decl-node-p node)
4129 (js2-var-decl-node-kids node))
4130 (t
4131 nil)))
4132
4133 (defun js2-node-set-child-list (node kids)
4134 "Set the child list for NODE to KIDS."
4135 (cond
4136 ((js2-function-node-p node)
4137 (setf (js2-function-node-params node) kids))
4138 ((js2-block-node-p node)
4139 (setf (js2-block-node-kids node) kids))
4140 ((js2-try-node-p node)
4141 (setf (js2-try-node-catch-clauses node) kids))
4142 ((js2-array-node-p node)
4143 (setf (js2-array-node-elems node) kids))
4144 ((js2-object-node-p node)
4145 (setf (js2-object-node-elems node) kids))
4146 ((js2-call-node-p node)
4147 (setf (js2-call-node-args node) kids))
4148 ((js2-new-node-p node)
4149 (setf (js2-new-node-args node) kids))
4150 ((js2-var-decl-node-p node)
4151 (setf (js2-var-decl-node-kids node) kids))
4152 (t
4153 (error "Unsupported node type: %s" (js2-node-short-name node))))
4154 kids)
4155
4156 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4157 (defconst js2-paren-expr-nodes
4158 '(cl-struct-js2-array-comp-loop-node
4159 cl-struct-js2-array-comp-node
4160 cl-struct-js2-call-node
4161 cl-struct-js2-catch-node
4162 cl-struct-js2-do-node
4163 cl-struct-js2-elem-get-node
4164 cl-struct-js2-for-in-node
4165 cl-struct-js2-for-node
4166 cl-struct-js2-function-node
4167 cl-struct-js2-if-node
4168 cl-struct-js2-let-node
4169 cl-struct-js2-new-node
4170 cl-struct-js2-paren-node
4171 cl-struct-js2-switch-node
4172 cl-struct-js2-while-node
4173 cl-struct-js2-with-node
4174 cl-struct-js2-xml-dot-query-node)
4175 "Node types that can have a parenthesized child expression.
4176 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4177
4178 (defsubst js2-paren-expr-node-p (node)
4179 "Return t for nodes that typically have a parenthesized child expression.
4180 Useful for computing the indentation anchors for arg-lists and conditions.
4181 Note that it may return a false positive, for instance when NODE is
4182 a `js2-new-node' and there are no arguments or parentheses."
4183 (memq (aref node 0) js2-paren-expr-nodes))
4184
4185 ;; Fake polymorphism... yech.
4186 (defun js2-node-lp (node)
4187 "Return relative left-paren position for NODE, if applicable.
4188 For `js2-elem-get-node' structs, returns left-bracket position.
4189 Note that the position may be nil in the case of a parse error."
4190 (cond
4191 ((js2-elem-get-node-p node)
4192 (js2-elem-get-node-lb node))
4193 ((js2-loop-node-p node)
4194 (js2-loop-node-lp node))
4195 ((js2-function-node-p node)
4196 (js2-function-node-lp node))
4197 ((js2-if-node-p node)
4198 (js2-if-node-lp node))
4199 ((js2-new-node-p node)
4200 (js2-new-node-lp node))
4201 ((js2-call-node-p node)
4202 (js2-call-node-lp node))
4203 ((js2-paren-node-p node)
4204 (js2-node-pos node))
4205 ((js2-switch-node-p node)
4206 (js2-switch-node-lp node))
4207 ((js2-catch-node-p node)
4208 (js2-catch-node-lp node))
4209 ((js2-let-node-p node)
4210 (js2-let-node-lp node))
4211 ((js2-array-comp-node-p node)
4212 (js2-array-comp-node-lp node))
4213 ((js2-with-node-p node)
4214 (js2-with-node-lp node))
4215 ((js2-xml-dot-query-node-p node)
4216 (1+ (js2-infix-node-op-pos node)))
4217 (t
4218 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4219
4220 ;; Fake polymorphism... blech.
4221 (defun js2-node-rp (node)
4222 "Return relative right-paren position for NODE, if applicable.
4223 For `js2-elem-get-node' structs, returns right-bracket position.
4224 Note that the position may be nil in the case of a parse error."
4225 (cond
4226 ((js2-elem-get-node-p node)
4227 (js2-elem-get-node-rb node))
4228 ((js2-loop-node-p node)
4229 (js2-loop-node-rp node))
4230 ((js2-function-node-p node)
4231 (js2-function-node-rp node))
4232 ((js2-if-node-p node)
4233 (js2-if-node-rp node))
4234 ((js2-new-node-p node)
4235 (js2-new-node-rp node))
4236 ((js2-call-node-p node)
4237 (js2-call-node-rp node))
4238 ((js2-paren-node-p node)
4239 (+ (js2-node-pos node) (js2-node-len node)))
4240 ((js2-switch-node-p node)
4241 (js2-switch-node-rp node))
4242 ((js2-catch-node-p node)
4243 (js2-catch-node-rp node))
4244 ((js2-let-node-p node)
4245 (js2-let-node-rp node))
4246 ((js2-array-comp-node-p node)
4247 (js2-array-comp-node-rp node))
4248 ((js2-with-node-p node)
4249 (js2-with-node-rp node))
4250 ((js2-xml-dot-query-node-p node)
4251 (1+ (js2-xml-dot-query-node-rp node)))
4252 (t
4253 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4254
4255 (defsubst js2-node-first-child (node)
4256 "Return the first element of `js2-node-child-list' for NODE."
4257 (car (js2-node-child-list node)))
4258
4259 (defsubst js2-node-last-child (node)
4260 "Return the last element of `js2-node-last-child' for NODE."
4261 (car (last (js2-node-child-list node))))
4262
4263 (defun js2-node-prev-sibling (node)
4264 "Return the previous statement in parent.
4265 Works for parents supported by `js2-node-child-list'.
4266 Returns nil if NODE is not in the parent, or PARENT is
4267 not a supported node, or if NODE is the first child."
4268 (let* ((p (js2-node-parent node))
4269 (kids (js2-node-child-list p))
4270 (sib (car kids)))
4271 (while (and kids
4272 (not (eq node (cadr kids))))
4273 (setq kids (cdr kids)
4274 sib (car kids)))
4275 sib))
4276
4277 (defun js2-node-next-sibling (node)
4278 "Return the next statement in parent block.
4279 Returns nil if NODE is not in the block, or PARENT is not
4280 a block node, or if NODE is the last statement."
4281 (let* ((p (js2-node-parent node))
4282 (kids (js2-node-child-list p)))
4283 (while (and kids
4284 (not (eq node (car kids))))
4285 (setq kids (cdr kids)))
4286 (cadr kids)))
4287
4288 (defun js2-node-find-child-before (pos parent &optional after)
4289 "Find the last child that starts before POS in parent.
4290 If AFTER is non-nil, returns first child starting after POS.
4291 POS is an absolute buffer position. PARENT is any node
4292 supported by `js2-node-child-list'.
4293 Returns nil if no applicable child is found."
4294 (let ((kids (if (js2-function-node-p parent)
4295 (js2-block-node-kids (js2-function-node-body parent))
4296 (js2-node-child-list parent)))
4297 (beg (if (js2-function-node-p parent)
4298 (js2-node-abs-pos (js2-function-node-body parent))
4299 (js2-node-abs-pos parent)))
4300 kid result fn
4301 (continue t))
4302 (setq fn (if after '>= '<))
4303 (while (and kids continue)
4304 (setq kid (car kids))
4305 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4306 (setq result kid
4307 continue (if after nil t))
4308 (setq continue (if after t nil)))
4309 (setq kids (cdr kids)))
4310 result))
4311
4312 (defun js2-node-find-child-after (pos parent)
4313 "Find first child that starts after POS in parent.
4314 POS is an absolute buffer position. PARENT is any node
4315 supported by `js2-node-child-list'.
4316 Returns nil if no applicable child is found."
4317 (js2-node-find-child-before pos parent 'after))
4318
4319 (defun js2-node-replace-child (pos parent new-node)
4320 "Replace node at index POS in PARENT with NEW-NODE.
4321 Only works for parents supported by `js2-node-child-list'."
4322 (let ((kids (js2-node-child-list parent))
4323 (i 0))
4324 (while (< i pos)
4325 (setq kids (cdr kids)
4326 i (1+ i)))
4327 (setcar kids new-node)
4328 (js2-node-add-children parent new-node)))
4329
4330 (defun js2-node-buffer (n)
4331 "Return the buffer associated with AST N.
4332 Returns nil if the buffer is not set as a property on the root
4333 node, or if parent links were not recorded during parsing."
4334 (let ((root (js2-node-root n)))
4335 (and root
4336 (js2-ast-root-p root)
4337 (js2-ast-root-buffer root))))
4338
4339 (defun js2-block-node-push (n kid)
4340 "Push js2-node KID onto the end of js2-block-node N's child list.
4341 KID is always added to the -end- of the kids list.
4342 Function also calls `js2-node-add-children' to add the parent link."
4343 (let ((kids (js2-node-child-list n)))
4344 (if kids
4345 (setcdr kids (nconc (cdr kids) (list kid)))
4346 (js2-node-set-child-list n (list kid)))
4347 (js2-node-add-children n kid)))
4348
4349 (defun js2-node-string (node)
4350 (with-current-buffer (or (js2-node-buffer node)
4351 (error "No buffer available for node %s" node))
4352 (let ((pos (js2-node-abs-pos node)))
4353 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4354
4355 ;; Container for storing the node we're looking for in a traversal.
4356 (js2-deflocal js2-discovered-node nil)
4357
4358 ;; Keep track of absolute node position during traversals.
4359 (js2-deflocal js2-visitor-offset nil)
4360
4361 (js2-deflocal js2-node-search-point nil)
4362
4363 (when js2-mode-dev-mode-p
4364 (defun js2-find-node-at-point ()
4365 (interactive)
4366 (let ((node (js2-node-at-point)))
4367 (message "%s" (or node "No node found at point"))))
4368 (defun js2-node-name-at-point ()
4369 (interactive)
4370 (let ((node (js2-node-at-point)))
4371 (message "%s" (if node
4372 (js2-node-short-name node)
4373 "No node found at point.")))))
4374
4375 (defun js2-node-at-point (&optional pos skip-comments)
4376 "Return AST node at POS, a buffer position, defaulting to current point.
4377 The `js2-mode-ast' variable must be set to the current parse tree.
4378 Signals an error if the AST (`js2-mode-ast') is nil.
4379 Always returns a node - if it can't find one, it returns the root.
4380 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4381 (let ((ast js2-mode-ast)
4382 result)
4383 (unless ast
4384 (error "No JavaScript AST available"))
4385 ;; Look through comments first, since they may be inside nodes that
4386 ;; would otherwise report a match.
4387 (setq pos (or pos (point))
4388 result (if (> pos (js2-node-abs-end ast))
4389 ast
4390 (if (not skip-comments)
4391 (js2-comment-at-point pos))))
4392 (unless result
4393 (setq js2-discovered-node nil
4394 js2-visitor-offset 0
4395 js2-node-search-point pos)
4396 (unwind-protect
4397 (catch 'js2-visit-done
4398 (js2-visit-ast ast #'js2-node-at-point-visitor))
4399 (setq js2-visitor-offset nil
4400 js2-node-search-point nil))
4401 (setq result js2-discovered-node))
4402 ;; may have found a comment beyond end of last child node,
4403 ;; since visiting the ast-root looks at the comment-list last.
4404 (if (and skip-comments
4405 (js2-comment-node-p result))
4406 (setq result nil))
4407 (or result js2-mode-ast)))
4408
4409 (defun js2-node-at-point-visitor (node end-p)
4410 (let ((rel-pos (js2-node-pos node))
4411 abs-pos
4412 abs-end
4413 (point js2-node-search-point))
4414 (cond
4415 (end-p
4416 ;; this evaluates to a non-nil return value, even if it's zero
4417 (decf js2-visitor-offset rel-pos))
4418 ;; we already looked for comments before visiting, and don't want them now
4419 ((js2-comment-node-p node)
4420 nil)
4421 (t
4422 (setq abs-pos (incf js2-visitor-offset rel-pos)
4423 ;; we only want to use the node if the point is before
4424 ;; the last character position in the node, so we decrement
4425 ;; the absolute end by 1.
4426 abs-end (+ abs-pos (js2-node-len node) -1))
4427 (cond
4428 ;; If this node starts after search-point, stop the search.
4429 ((> abs-pos point)
4430 (throw 'js2-visit-done nil))
4431 ;; If this node ends before the search-point, don't check kids.
4432 ((> point abs-end)
4433 nil)
4434 (t
4435 ;; Otherwise point is within this node, possibly in a child.
4436 (setq js2-discovered-node node)
4437 t)))))) ; keep processing kids to look for more specific match
4438
4439 (defsubst js2-block-comment-p (node)
4440 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4441 (and (js2-comment-node-p node)
4442 (memq (js2-comment-node-format node) '(jsdoc block))))
4443
4444 ;; TODO: put the comments in a vector and binary-search them instead
4445 (defun js2-comment-at-point (&optional pos)
4446 "Look through scanned comment nodes for one containing POS.
4447 POS is a buffer position that defaults to current point.
4448 Function returns nil if POS was not in any comment node."
4449 (let ((ast js2-mode-ast)
4450 (x (or pos (point)))
4451 beg end)
4452 (unless ast
4453 (error "No JavaScript AST available"))
4454 (catch 'done
4455 ;; Comments are stored in lexical order.
4456 (dolist (comment (js2-ast-root-comments ast) nil)
4457 (setq beg (js2-node-abs-pos comment)
4458 end (+ beg (js2-node-len comment)))
4459 (if (and (>= x beg)
4460 (<= x end))
4461 (throw 'done comment))))))
4462
4463 (defun js2-mode-find-parent-fn (node)
4464 "Find function enclosing NODE.
4465 Returns nil if NODE is not inside a function."
4466 (setq node (js2-node-parent node))
4467 (while (and node (not (js2-function-node-p node)))
4468 (setq node (js2-node-parent node)))
4469 (and (js2-function-node-p node) node))
4470
4471 (defun js2-mode-find-enclosing-fn (node)
4472 "Find function or root enclosing NODE."
4473 (if (js2-ast-root-p node)
4474 node
4475 (setq node (js2-node-parent node))
4476 (while (not (or (js2-ast-root-p node)
4477 (js2-function-node-p node)))
4478 (setq node (js2-node-parent node)))
4479 node))
4480
4481 (defun js2-mode-find-enclosing-node (beg end)
4482 "Find script or function fully enclosing BEG and END."
4483 (let ((node (js2-node-at-point beg))
4484 pos
4485 (continue t))
4486 (while continue
4487 (if (or (js2-ast-root-p node)
4488 (and (js2-function-node-p node)
4489 (<= (setq pos (js2-node-abs-pos node)) beg)
4490 (>= (+ pos (js2-node-len node)) end)))
4491 (setq continue nil)
4492 (setq node (js2-node-parent node))))
4493 node))
4494
4495 (defun js2-node-parent-script-or-fn (node)
4496 "Find script or function immediately enclosing NODE.
4497 If NODE is the ast-root, returns nil."
4498 (if (js2-ast-root-p node)
4499 nil
4500 (setq node (js2-node-parent node))
4501 (while (and node (not (or (js2-function-node-p node)
4502 (js2-script-node-p node))))
4503 (setq node (js2-node-parent node)))
4504 node))
4505
4506 (defun js2-nested-function-p (node)
4507 "Return t if NODE is a nested function, or is inside a nested function."
4508 (unless (js2-ast-root-p node)
4509 (js2-function-node-p (if (js2-function-node-p node)
4510 (js2-node-parent-script-or-fn node)
4511 (js2-node-parent-script-or-fn
4512 (js2-node-parent-script-or-fn node))))))
4513
4514 (defun js2-mode-shift-kids (kids start offset)
4515 (dolist (kid kids)
4516 (if (> (js2-node-pos kid) start)
4517 (incf (js2-node-pos kid) offset))))
4518
4519 (defun js2-mode-shift-children (parent start offset)
4520 "Update start-positions of all children of PARENT beyond START."
4521 (let ((root (js2-node-root parent)))
4522 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4523 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4524
4525 (defun js2-node-is-descendant (node ancestor)
4526 "Return t if NODE is a descendant of ANCESTOR."
4527 (while (and node
4528 (not (eq node ancestor)))
4529 (setq node (js2-node-parent node)))
4530 node)
4531
4532 ;;; visitor infrastructure
4533
4534 (defun js2-visit-none (node callback)
4535 "Visitor for AST node that have no node children."
4536 nil)
4537
4538 (defun js2-print-none (node indent)
4539 "Visitor for AST node with no printed representation.")
4540
4541 (defun js2-print-body (node indent)
4542 "Print a statement, or a block without braces."
4543 (if (js2-block-node-p node)
4544 (dolist (kid (js2-block-node-kids node))
4545 (js2-print-ast kid indent))
4546 (js2-print-ast node indent)))
4547
4548 (defun js2-print-list (args &optional delimiter)
4549 (loop with len = (length args)
4550 for arg in args
4551 for count from 1
4552 do
4553 (when arg (js2-print-ast arg 0))
4554 (if (< count len)
4555 (insert (or delimiter ", ")))))
4556
4557 (defun js2-print-tree (ast)
4558 "Prints an AST to the current buffer.
4559 Makes `js2-ast-parent-nodes' available to the printer functions."
4560 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4561 (js2-print-ast ast)))
4562
4563 (defun js2-print-ast (node &optional indent)
4564 "Helper function for printing AST nodes.
4565 Requires `js2-ast-parent-nodes' to be non-nil.
4566 You should use `js2-print-tree' instead of this function."
4567 (let ((printer (get (aref node 0) 'js2-printer))
4568 (i (or indent 0))
4569 (pos (js2-node-abs-pos node)))
4570 ;; TODO: wedge comments in here somewhere
4571 (if printer
4572 (funcall printer node i))))
4573
4574 (defconst js2-side-effecting-tokens
4575 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4576 (dolist (tt (list js2-ASSIGN
4577 js2-ASSIGN_ADD
4578 js2-ASSIGN_BITAND
4579 js2-ASSIGN_BITOR
4580 js2-ASSIGN_BITXOR
4581 js2-ASSIGN_DIV
4582 js2-ASSIGN_LSH
4583 js2-ASSIGN_MOD
4584 js2-ASSIGN_MUL
4585 js2-ASSIGN_RSH
4586 js2-ASSIGN_SUB
4587 js2-ASSIGN_URSH
4588 js2-BLOCK
4589 js2-BREAK
4590 js2-CALL
4591 js2-CATCH
4592 js2-CATCH_SCOPE
4593 js2-CONST
4594 js2-CONTINUE
4595 js2-DEBUGGER
4596 js2-DEC
4597 js2-DELPROP
4598 js2-DEL_REF
4599 js2-DO
4600 js2-ELSE
4601 js2-EMPTY
4602 js2-ENTERWITH
4603 js2-EXPORT
4604 js2-EXPR_RESULT
4605 js2-FINALLY
4606 js2-FOR
4607 js2-FUNCTION
4608 js2-GOTO
4609 js2-IF
4610 js2-IFEQ
4611 js2-IFNE
4612 js2-IMPORT
4613 js2-INC
4614 js2-JSR
4615 js2-LABEL
4616 js2-LEAVEWITH
4617 js2-LET
4618 js2-LETEXPR
4619 js2-LOCAL_BLOCK
4620 js2-LOOP
4621 js2-NEW
4622 js2-REF_CALL
4623 js2-RETHROW
4624 js2-RETURN
4625 js2-RETURN_RESULT
4626 js2-SEMI
4627 js2-SETELEM
4628 js2-SETELEM_OP
4629 js2-SETNAME
4630 js2-SETPROP
4631 js2-SETPROP_OP
4632 js2-SETVAR
4633 js2-SET_REF
4634 js2-SET_REF_OP
4635 js2-SWITCH
4636 js2-TARGET
4637 js2-THROW
4638 js2-TRY
4639 js2-VAR
4640 js2-WHILE
4641 js2-WITH
4642 js2-WITHEXPR
4643 js2-YIELD))
4644 (aset tokens tt t))
4645 (if js2-instanceof-has-side-effects
4646 (aset tokens js2-INSTANCEOF t))
4647 tokens))
4648
4649 (defun js2-node-has-side-effects (node)
4650 "Return t if NODE has side effects."
4651 (when node ; makes it easier to handle malformed expressions
4652 (let ((tt (js2-node-type node)))
4653 (cond
4654 ;; This doubtless needs some work, since EXPR_VOID is used
4655 ;; in several ways in Rhino and I may not have caught them all.
4656 ;; I'll wait for people to notice incorrect warnings.
4657 ((and (= tt js2-EXPR_VOID)
4658 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4659 (let ((expr (js2-expr-stmt-node-expr node)))
4660 (or (js2-node-has-side-effects expr)
4661 (when (js2-string-node-p expr)
4662 (string= "use strict" (js2-string-node-value expr))))))
4663 ((= tt js2-COMMA)
4664 (js2-node-has-side-effects (js2-infix-node-right node)))
4665 ((or (= tt js2-AND)
4666 (= tt js2-OR))
4667 (or (js2-node-has-side-effects (js2-infix-node-right node))
4668 (js2-node-has-side-effects (js2-infix-node-left node))))
4669 ((= tt js2-HOOK)
4670 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4671 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4672 ((js2-paren-node-p node)
4673 (js2-node-has-side-effects (js2-paren-node-expr node)))
4674 ((= tt js2-ERROR) ; avoid cascaded error messages
4675 nil)
4676 (t
4677 (aref js2-side-effecting-tokens tt))))))
4678
4679 (defun js2-member-expr-leftmost-name (node)
4680 "For an expr such as foo.bar.baz, return leftmost node foo.
4681 NODE is any `js2-node' object. If it represents a member expression,
4682 which is any sequence of property gets, element-gets, function calls,
4683 or xml descendants/filter operators, then we look at the lexically
4684 leftmost (first) node in the chain. If it is a name-node we return it.
4685 Note that NODE can be a raw name-node and it will be returned as well.
4686 If NODE is not a name-node or member expression, or if it is a member
4687 expression whose leftmost target is not a name node, returns nil."
4688 (let ((continue t)
4689 result)
4690 (while (and continue (not result))
4691 (cond
4692 ((js2-name-node-p node)
4693 (setq result node))
4694 ((js2-prop-get-node-p node)
4695 (setq node (js2-prop-get-node-left node)))
4696 ;; TODO: handle call-nodes, xml-nodes, others?
4697 (t
4698 (setq continue nil))))
4699 result))
4700
4701 (defconst js2-stmt-node-types
4702 (list js2-BLOCK
4703 js2-BREAK
4704 js2-CONTINUE
4705 js2-DEFAULT ; e4x "default xml namespace" statement
4706 js2-DO
4707 js2-EXPR_RESULT
4708 js2-EXPR_VOID
4709 js2-FOR
4710 js2-IF
4711 js2-RETURN
4712 js2-SWITCH
4713 js2-THROW
4714 js2-TRY
4715 js2-WHILE
4716 js2-WITH)
4717 "Node types that only appear in statement contexts.
4718 The list does not include nodes that always appear as the child
4719 of another specific statement type, such as switch-cases,
4720 catch and finally blocks, and else-clauses. The list also excludes
4721 nodes like yield, let and var, which may appear in either expression
4722 or statement context, and in the latter context always have a
4723 `js2-expr-stmt-node' parent. Finally, the list does not include
4724 functions or scripts, which are treated separately from statements
4725 by the JavaScript parser and runtime.")
4726
4727 (defun js2-stmt-node-p (node)
4728 "Heuristic for figuring out if NODE is a statement.
4729 Some node types can appear in either an expression context or a
4730 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4731 For these node types in a statement context, the parent will be a
4732 `js2-expr-stmt-node'.
4733 Functions aren't included in the check."
4734 (memq (js2-node-type node) js2-stmt-node-types))
4735
4736 (defun js2-mode-find-first-stmt (node)
4737 "Search upward starting from NODE looking for a statement.
4738 For purposes of this function, a `js2-function-node' counts."
4739 (while (not (or (js2-stmt-node-p node)
4740 (js2-function-node-p node)))
4741 (setq node (js2-node-parent node)))
4742 node)
4743
4744 (defun js2-node-parent-stmt (node)
4745 "Return the node's first ancestor that is a statement.
4746 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4747 appearing in a statement context will have a parent that is a
4748 `js2-expr-stmt-node' that will be returned by this function."
4749 (let ((parent (js2-node-parent node)))
4750 (if (or (null parent)
4751 (js2-stmt-node-p parent)
4752 (and (js2-function-node-p parent)
4753 (not (eq (js2-function-node-form parent)
4754 'FUNCTION_EXPRESSION))))
4755 parent
4756 (js2-node-parent-stmt parent))))
4757
4758 ;; In the Mozilla Rhino sources, Roshan James writes:
4759 ;; Does consistent-return analysis on the function body when strict mode is
4760 ;; enabled.
4761 ;;
4762 ;; function (x) { return (x+1) }
4763 ;;
4764 ;; is ok, but
4765 ;;
4766 ;; function (x) { if (x < 0) return (x+1); }
4767 ;;
4768 ;; is not because the function can potentially return a value when the
4769 ;; condition is satisfied and if not, the function does not explicitly
4770 ;; return a value.
4771 ;;
4772 ;; This extends to checking mismatches such as "return" and "return <value>"
4773 ;; used in the same function. Warnings are not emitted if inconsistent
4774 ;; returns exist in code that can be statically shown to be unreachable.
4775 ;; Ex.
4776 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4777 ;;
4778 ;; emits no warning. However if the loop had a break statement, then a
4779 ;; warning would be emitted.
4780 ;;
4781 ;; The consistency analysis looks at control structures such as loops, ifs,
4782 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4783 ;; warns the user about an inconsistent set of termination possibilities.
4784 ;;
4785 ;; These flags enumerate the possible ways a statement/function can
4786 ;; terminate. These flags are used by endCheck() and by the Parser to
4787 ;; detect inconsistent return usage.
4788 ;;
4789 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4790 ;; able to execute (example: throw, continue)
4791 ;;
4792 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4793 ;; next one. Statement such as return dont. A compound statement may have
4794 ;; some branch that drops off control to the next statement.
4795 ;;
4796 ;; END_RETURNS indicates that the statement can return with no value.
4797 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4798 ;;
4799 ;; A compound statement such as
4800 ;; if (condition) {
4801 ;; return value;
4802 ;; }
4803 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4804
4805 (defconst js2-END_UNREACHED 0)
4806 (defconst js2-END_DROPS_OFF 1)
4807 (defconst js2-END_RETURNS 2)
4808 (defconst js2-END_RETURNS_VALUE 4)
4809 (defconst js2-END_YIELDS 8)
4810
4811 (defun js2-has-consistent-return-usage (node)
4812 "Check that every return usage in a function body is consistent.
4813 Returns t if the function satisfies strict mode requirement."
4814 (let ((n (js2-end-check node)))
4815 ;; either it doesn't return a value in any branch...
4816 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4817 ;; or it returns a value (or is unreached) at every branch
4818 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4819 js2-END_RETURNS
4820 js2-END_YIELDS)))))
4821
4822 (defun js2-end-check-if (node)
4823 "Ensure that return usage in then/else blocks is consistent.
4824 If there is no else block, then the return statement can fall through.
4825 Returns logical OR of END_* flags"
4826 (let ((th (js2-if-node-then-part node))
4827 (el (js2-if-node-else-part node)))
4828 (if (null th)
4829 js2-END_UNREACHED
4830 (logior (js2-end-check th) (if el
4831 (js2-end-check el)
4832 js2-END_DROPS_OFF)))))
4833
4834 (defun js2-end-check-switch (node)
4835 "Consistency of return statements is checked between the case statements.
4836 If there is no default, then the switch can fall through. If there is a
4837 default, we check to see if all code paths in the default return or if
4838 there is a code path that can fall through.
4839 Returns logical OR of END_* flags."
4840 (let ((rv js2-END_UNREACHED)
4841 default-case)
4842 ;; examine the cases
4843 (catch 'break
4844 (dolist (c (js2-switch-node-cases node))
4845 (if (js2-case-node-expr c)
4846 (js2-set-flag rv (js2-end-check-block c))
4847 (setq default-case c)
4848 (throw 'break nil))))
4849 ;; we don't care how the cases drop into each other
4850 (js2-clear-flag rv js2-END_DROPS_OFF)
4851 ;; examine the default
4852 (js2-set-flag rv (if default-case
4853 (js2-end-check default-case)
4854 js2-END_DROPS_OFF))
4855 rv))
4856
4857 (defun js2-end-check-try (node)
4858 "If the block has a finally, return consistency is checked in the
4859 finally block. If all code paths in the finally return, then the
4860 returns in the try-catch blocks don't matter. If there is a code path
4861 that does not return or if there is no finally block, the returns
4862 of the try and catch blocks are checked for mismatch.
4863 Returns logical OR of END_* flags."
4864 (let ((finally (js2-try-node-finally-block node))
4865 rv)
4866 ;; check the finally if it exists
4867 (setq rv (if finally
4868 (js2-end-check (js2-finally-node-body finally))
4869 js2-END_DROPS_OFF))
4870 ;; If the finally block always returns, then none of the returns
4871 ;; in the try or catch blocks matter.
4872 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4873 (js2-clear-flag rv js2-END_DROPS_OFF)
4874 ;; examine the try block
4875 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4876 ;; check each catch block
4877 (dolist (cb (js2-try-node-catch-clauses node))
4878 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4879 rv))
4880
4881 (defun js2-end-check-loop (node)
4882 "Return statement in the loop body must be consistent.
4883 The default assumption for any kind of a loop is that it will eventually
4884 terminate. The only exception is a loop with a constant true condition.
4885 Code that follows such a loop is examined only if one can determine
4886 statically that there is a break out of the loop.
4887
4888 for(... ; ... ; ...) {}
4889 for(... in ... ) {}
4890 while(...) { }
4891 do { } while(...)
4892
4893 Returns logical OR of END_* flags."
4894 (let ((rv (js2-end-check (js2-loop-node-body node)))
4895 (condition (cond
4896 ((js2-while-node-p node)
4897 (js2-while-node-condition node))
4898 ((js2-do-node-p node)
4899 (js2-do-node-condition node))
4900 ((js2-for-node-p node)
4901 (js2-for-node-condition node)))))
4902
4903 ;; check to see if the loop condition is always true
4904 (if (and condition
4905 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4906 (js2-clear-flag rv js2-END_DROPS_OFF))
4907
4908 ;; look for effect of breaks
4909 (js2-set-flag rv (js2-node-get-prop node
4910 'CONTROL_BLOCK_PROP
4911 js2-END_UNREACHED))
4912 rv))
4913
4914 (defun js2-end-check-block (node)
4915 "A general block of code is examined statement by statement.
4916 If any statement (even a compound one) returns in all branches, then
4917 subsequent statements are not examined.
4918 Returns logical OR of END_* flags."
4919 (let* ((rv js2-END_DROPS_OFF)
4920 (kids (js2-block-node-kids node))
4921 (n (car kids)))
4922 ;; Check each statment. If the statement can continue onto the next
4923 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4924 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4925 (js2-clear-flag rv js2-END_DROPS_OFF)
4926 (js2-set-flag rv (js2-end-check n))
4927 (setq kids (cdr kids)
4928 n (car kids)))
4929 rv))
4930
4931 (defun js2-end-check-label (node)
4932 "A labeled statement implies that there may be a break to the label.
4933 The function processes the labeled statement and then checks the
4934 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4935 particular label.
4936 Returns logical OR of END_* flags."
4937 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4938 (logior rv (js2-node-get-prop node
4939 'CONTROL_BLOCK_PROP
4940 js2-END_UNREACHED))))
4941
4942 (defun js2-end-check-break (node)
4943 "When a break is encountered annotate the statement being broken
4944 out of by setting its CONTROL_BLOCK_PROP property.
4945 Returns logical OR of END_* flags."
4946 (and (js2-break-node-target node)
4947 (js2-node-set-prop (js2-break-node-target node)
4948 'CONTROL_BLOCK_PROP
4949 js2-END_DROPS_OFF))
4950 js2-END_UNREACHED)
4951
4952 (defun js2-end-check (node)
4953 "Examine the body of a function, doing a basic reachability analysis.
4954 Returns a combination of flags END_* flags that indicate
4955 how the function execution can terminate. These constitute only the
4956 pessimistic set of termination conditions. It is possible that at
4957 runtime certain code paths will never be actually taken. Hence this
4958 analysis will flag errors in cases where there may not be errors.
4959 Returns logical OR of END_* flags"
4960 (let (kid)
4961 (cond
4962 ((js2-break-node-p node)
4963 (js2-end-check-break node))
4964 ((js2-expr-stmt-node-p node)
4965 (if (setq kid (js2-expr-stmt-node-expr node))
4966 (js2-end-check kid)
4967 js2-END_DROPS_OFF))
4968 ((or (js2-continue-node-p node)
4969 (js2-throw-node-p node))
4970 js2-END_UNREACHED)
4971 ((js2-return-node-p node)
4972 (if (setq kid (js2-return-node-retval node))
4973 js2-END_RETURNS_VALUE
4974 js2-END_RETURNS))
4975 ((js2-loop-node-p node)
4976 (js2-end-check-loop node))
4977 ((js2-switch-node-p node)
4978 (js2-end-check-switch node))
4979 ((js2-labeled-stmt-node-p node)
4980 (js2-end-check-label node))
4981 ((js2-if-node-p node)
4982 (js2-end-check-if node))
4983 ((js2-try-node-p node)
4984 (js2-end-check-try node))
4985 ((js2-block-node-p node)
4986 (if (null (js2-block-node-kids node))
4987 js2-END_DROPS_OFF
4988 (js2-end-check-block node)))
4989 ((js2-yield-node-p node)
4990 js2-END_YIELDS)
4991 (t
4992 js2-END_DROPS_OFF))))
4993
4994 (defun js2-always-defined-boolean-p (node)
4995 "Check if NODE always evaluates to true or false in boolean context.
4996 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4997 nor always false."
4998 (let ((tt (js2-node-type node))
4999 num)
5000 (cond
5001 ((or (= tt js2-FALSE) (= tt js2-NULL))
5002 'ALWAYS_FALSE)
5003 ((= tt js2-TRUE)
5004 'ALWAYS_TRUE)
5005 ((= tt js2-NUMBER)
5006 (setq num (js2-number-node-num-value node))
5007 (if (and (not (eq num 0.0e+NaN))
5008 (not (zerop num)))
5009 'ALWAYS_TRUE
5010 'ALWAYS_FALSE))
5011 (t
5012 nil))))
5013
5014 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5015 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5016
5017 (defvar js2-tokens nil
5018 "List of all defined token names.") ; initialized in `js2-token-names'
5019
5020 (defconst js2-token-names
5021 (let* ((names (make-vector js2-num-tokens -1))
5022 (case-fold-search nil) ; only match js2-UPPER_CASE
5023 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5024 (loop for sym in syms
5025 for i from 0
5026 do
5027 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5028 (not (boundp sym)))
5029 (aset names (symbol-value sym) ; code, e.g. 152
5030 (downcase
5031 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5032 (push sym js2-tokens)))
5033 names)
5034 "Vector mapping int values to token string names, sans `js2-' prefix.")
5035
5036 (defun js2-token-name (tok)
5037 "Return a string name for TOK, a token symbol or code.
5038 Signals an error if it's not a recognized token."
5039 (let ((code tok))
5040 (if (symbolp tok)
5041 (setq code (symbol-value tok)))
5042 (if (eq code -1)
5043 "ERROR"
5044 (if (and (numberp code)
5045 (not (minusp code))
5046 (< code js2-num-tokens))
5047 (aref js2-token-names code)
5048 (error "Invalid token: %s" code)))))
5049
5050 (defsubst js2-token-sym (tok)
5051 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5052 (intern (js2-token-name tok)))
5053
5054 (defconst js2-token-codes
5055 (let ((table (make-hash-table :test 'eq :size 256)))
5056 (loop for name across js2-token-names
5057 for sym = (intern (concat "js2-" (upcase name)))
5058 do
5059 (puthash sym (symbol-value sym) table))
5060 ;; clean up a few that are "wrong" in Rhino's token codes
5061 (puthash 'js2-DELETE js2-DELPROP table)
5062 table)
5063 "Hashtable mapping token symbols to their bytecodes.")
5064
5065 (defsubst js2-token-code (sym)
5066 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5067 (or (gethash sym js2-token-codes)
5068 (error "Invalid token symbol: %s " sym))) ; signal code bug
5069
5070 (defun js2-report-scan-error (msg &optional no-throw beg len)
5071 (setq js2-token-end js2-ts-cursor)
5072 (js2-report-error msg nil
5073 (or beg js2-token-beg)
5074 (or len (- js2-token-end js2-token-beg)))
5075 (unless no-throw
5076 (throw 'return js2-ERROR)))
5077
5078 (defun js2-get-string-from-buffer ()
5079 "Reverse the char accumulator and return it as a string."
5080 (setq js2-token-end js2-ts-cursor)
5081 (if js2-ts-string-buffer
5082 (apply #'string (nreverse js2-ts-string-buffer))
5083 ""))
5084
5085 ;; TODO: could potentially avoid a lot of consing by allocating a
5086 ;; char buffer the way Rhino does.
5087 (defsubst js2-add-to-string (c)
5088 (push c js2-ts-string-buffer))
5089
5090 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5091 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5092 ;; any other character: when it's not part of the current token, we
5093 ;; unget it, allowing it to be read again by the following call.
5094 (defsubst js2-unget-char ()
5095 (decf js2-ts-cursor))
5096
5097 ;; Rhino distinguishes \r and \n line endings. We don't need to
5098 ;; because we only scan from Emacs buffers, which always use \n.
5099 (defun js2-get-char ()
5100 "Read and return the next character from the input buffer.
5101 Increments `js2-ts-lineno' if the return value is a newline char.
5102 Updates `js2-ts-cursor' to the point after the returned char.
5103 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5104 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5105 (let (c)
5106 ;; check for end of buffer
5107 (if (>= js2-ts-cursor (point-max))
5108 (setq js2-ts-hit-eof t
5109 js2-ts-cursor (1+ js2-ts-cursor)
5110 c js2-EOF_CHAR) ; return value
5111 ;; otherwise read next char
5112 (setq c (char-before (incf js2-ts-cursor)))
5113 ;; if we read a newline, update counters
5114 (if (= c ?\n)
5115 (setq js2-ts-line-start js2-ts-cursor
5116 js2-ts-lineno (1+ js2-ts-lineno)))
5117 ;; TODO: skip over format characters
5118 c)))
5119
5120 (defun js2-read-unicode-escape ()
5121 "Read a \\uNNNN sequence from the input.
5122 Assumes the ?\ and ?u have already been read.
5123 Returns the unicode character, or nil if it wasn't a valid character.
5124 Doesn't change the values of any scanner variables."
5125 ;; I really wish I knew a better way to do this, but I can't
5126 ;; find the Emacs function that takes a 16-bit int and converts
5127 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5128 ;; Have to first check that it's 4 hex characters or it may stop
5129 ;; the read early.
5130 (ignore-errors
5131 (let ((s (buffer-substring-no-properties js2-ts-cursor
5132 (+ 4 js2-ts-cursor))))
5133 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5134 (read (concat "?\\u" s))))))
5135
5136 (defun js2-match-char (test)
5137 "Consume and return next character if it matches TEST, a character.
5138 Returns nil and consumes nothing if TEST is not the next character."
5139 (let ((c (js2-get-char)))
5140 (if (eq c test)
5141 t
5142 (js2-unget-char)
5143 nil)))
5144
5145 (defun js2-peek-char ()
5146 (prog1
5147 (js2-get-char)
5148 (js2-unget-char)))
5149
5150 (defun js2-java-identifier-start-p (c)
5151 (or
5152 (memq c '(?$ ?_))
5153 (js2-char-uppercase-p c)
5154 (js2-char-lowercase-p c)))
5155
5156 (defun js2-java-identifier-part-p (c)
5157 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5158 ;; TODO: make me Unicode-friendly. See comments above.
5159 (or
5160 (memq c '(?$ ?_))
5161 (js2-char-uppercase-p c)
5162 (js2-char-lowercase-p c)
5163 (and (>= c ?0) (<= c ?9))))
5164
5165 (defun js2-alpha-p (c)
5166 (cond ((and (<= ?A c) (<= c ?Z)) t)
5167 ((and (<= ?a c) (<= c ?z)) t)
5168 (t nil)))
5169
5170 (defsubst js2-digit-p (c)
5171 (and (<= ?0 c) (<= c ?9)))
5172
5173 (defun js2-js-space-p (c)
5174 (if (<= c 127)
5175 (memq c '(#x20 #x9 #xB #xC #xD))
5176 (or
5177 (eq c #xA0)
5178 ;; TODO: change this nil to check for Unicode space character
5179 nil)))
5180
5181 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5182
5183 (defun js2-skip-line ()
5184 "Skip to end of line."
5185 (let (c)
5186 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5187 (js2-unget-char)
5188 (setq js2-token-end js2-ts-cursor)))
5189
5190 (defun js2-init-scanner (&optional buf line)
5191 "Create token stream for BUF starting on LINE.
5192 BUF defaults to `current-buffer' and LINE defaults to 1.
5193
5194 A buffer can only have one scanner active at a time, which yields
5195 dramatically simpler code than using a defstruct. If you need to
5196 have simultaneous scanners in a buffer, copy the regions to scan
5197 into temp buffers."
5198 (with-current-buffer (or buf (current-buffer))
5199 (setq js2-ts-dirty-line nil
5200 js2-ts-regexp-flags nil
5201 js2-ts-string ""
5202 js2-ts-number nil
5203 js2-ts-hit-eof nil
5204 js2-ts-line-start 0
5205 js2-ts-lineno (or line 1)
5206 js2-ts-line-end-char -1
5207 js2-ts-cursor (point-min)
5208 js2-ts-is-xml-attribute nil
5209 js2-ts-xml-is-tag-content nil
5210 js2-ts-xml-open-tags-count 0
5211 js2-ts-string-buffer nil)))
5212
5213 ;; This function uses the cached op, string and number fields in
5214 ;; TokenStream; if getToken has been called since the passed token
5215 ;; was scanned, the op or string printed may be incorrect.
5216 (defun js2-token-to-string (token)
5217 ;; Not sure where this function is used in Rhino. Not tested.
5218 (if (not js2-debug-print-trees)
5219 ""
5220 (let ((name (js2-token-name token)))
5221 (cond
5222 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5223 (concat name " `" js2-ts-string "'"))
5224 ((eq token js2-NUMBER)
5225 (format "NUMBER %g" js2-ts-number))
5226 (t
5227 name)))))
5228
5229 (defconst js2-keywords
5230 '(break
5231 case catch const continue
5232 debugger default delete do
5233 else enum
5234 false finally for function
5235 if in instanceof import
5236 let
5237 new null
5238 return
5239 switch
5240 this throw true try typeof
5241 var void
5242 while with
5243 yield))
5244
5245 ;; Token names aren't exactly the same as the keywords, unfortunately.
5246 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5247 (defconst js2-kwd-tokens
5248 (let ((table (make-vector js2-num-tokens nil))
5249 (tokens
5250 (list js2-BREAK
5251 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5252 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5253 js2-ELSE
5254 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5255 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5256 js2-LET
5257 js2-NEW js2-NULL
5258 js2-RETURN
5259 js2-SWITCH
5260 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5261 js2-VAR
5262 js2-WHILE js2-WITH
5263 js2-YIELD)))
5264 (dolist (i tokens)
5265 (aset table i 'font-lock-keyword-face))
5266 (aset table js2-STRING 'font-lock-string-face)
5267 (aset table js2-REGEXP 'font-lock-string-face)
5268 (aset table js2-COMMENT 'font-lock-comment-face)
5269 (aset table js2-THIS 'font-lock-builtin-face)
5270 (aset table js2-VOID 'font-lock-constant-face)
5271 (aset table js2-NULL 'font-lock-constant-face)
5272 (aset table js2-TRUE 'font-lock-constant-face)
5273 (aset table js2-FALSE 'font-lock-constant-face)
5274 table)
5275 "Vector whose values are non-nil for tokens that are keywords.
5276 The values are default faces to use for highlighting the keywords.")
5277
5278 (defconst js2-reserved-words
5279 '(abstract
5280 boolean byte
5281 char class
5282 double
5283 enum export extends
5284 final float
5285 goto
5286 implements import int interface
5287 long
5288 native
5289 package private protected public
5290 short static super synchronized
5291 throws transient
5292 volatile))
5293
5294 (defconst js2-keyword-names
5295 (let ((table (make-hash-table :test 'equal)))
5296 (loop for k in js2-keywords
5297 do (puthash
5298 (symbol-name k) ; instanceof
5299 (intern (concat "js2-"
5300 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5301 table))
5302 table)
5303 "JavaScript keywords by name, mapped to their symbols.")
5304
5305 (defconst js2-reserved-word-names
5306 (let ((table (make-hash-table :test 'equal)))
5307 (loop for k in js2-reserved-words
5308 do
5309 (puthash (symbol-name k) 'js2-RESERVED table))
5310 table)
5311 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5312
5313 (defun js2-collect-string (buf)
5314 "Convert BUF, a list of chars, to a string.
5315 Reverses BUF before converting."
5316 (cond
5317 ((stringp buf)
5318 buf)
5319 ((null buf) ; for emacs21 compat
5320 "")
5321 (t
5322 (if buf
5323 (apply #'string (nreverse buf))
5324 ""))))
5325
5326 (defun js2-string-to-keyword (s)
5327 "Return token for S, a string, if S is a keyword or reserved word.
5328 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5329 (or (gethash s js2-keyword-names)
5330 (gethash s js2-reserved-word-names)))
5331
5332 (defsubst js2-ts-set-char-token-bounds ()
5333 "Used when next token is one character."
5334 (setq js2-token-beg (1- js2-ts-cursor)
5335 js2-token-end js2-ts-cursor))
5336
5337 (defsubst js2-ts-return (token)
5338 "Return an N-character TOKEN from `js2-get-token'.
5339 Updates `js2-token-end' accordingly."
5340 (setq js2-token-end js2-ts-cursor)
5341 (throw 'return token))
5342
5343 (defun js2-x-digit-to-int (c accumulator)
5344 "Build up a hex number.
5345 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5346 corresponding number. Otherwise return -1."
5347 (catch 'return
5348 (catch 'check
5349 ;; Use 0..9 < A..Z < a..z
5350 (cond
5351 ((<= c ?9)
5352 (decf c ?0)
5353 (if (<= 0 c)
5354 (throw 'check nil)))
5355 ((<= c ?F)
5356 (when (<= ?A c)
5357 (decf c (- ?A 10))
5358 (throw 'check nil)))
5359 ((<= c ?f)
5360 (when (<= ?a c)
5361 (decf c (- ?a 10))
5362 (throw 'check nil))))
5363 (throw 'return -1))
5364 (logior c (lsh accumulator 4))))
5365
5366 (defun js2-get-token ()
5367 "Return next JavaScript token, an int such as js2-RETURN."
5368 (let (c c1 identifier-start is-unicode-escape-start
5369 contains-escape escape-val escape-start str result base
5370 is-integer quote-char val look-for-slash continue)
5371 (catch 'return
5372 (while t
5373 ;; Eat whitespace, possibly sensitive to newlines.
5374 (setq continue t)
5375 (while continue
5376 (setq c (js2-get-char))
5377 (cond
5378 ((eq c js2-EOF_CHAR)
5379 (js2-ts-set-char-token-bounds)
5380 (throw 'return js2-EOF))
5381 ((eq c ?\n)
5382 (js2-ts-set-char-token-bounds)
5383 (setq js2-ts-dirty-line nil)
5384 (throw 'return js2-EOL))
5385 ((not (js2-js-space-p c))
5386 (if (/= c ?-) ; in case end of HTML comment
5387 (setq js2-ts-dirty-line t))
5388 (setq continue nil))))
5389 ;; Assume the token will be 1 char - fixed up below.
5390 (js2-ts-set-char-token-bounds)
5391 (when (eq c ?@)
5392 (throw 'return js2-XMLATTR))
5393 ;; identifier/keyword/instanceof?
5394 ;; watch out for starting with a <backslash>
5395 (cond
5396 ((eq c ?\\)
5397 (setq c (js2-get-char))
5398 (if (eq c ?u)
5399 (setq identifier-start t
5400 is-unicode-escape-start t
5401 js2-ts-string-buffer nil)
5402 (setq identifier-start nil)
5403 (js2-unget-char)
5404 (setq c ?\\)))
5405 (t
5406 (when (setq identifier-start (js2-java-identifier-start-p c))
5407 (setq js2-ts-string-buffer nil)
5408 (js2-add-to-string c))))
5409 (when identifier-start
5410 (setq contains-escape is-unicode-escape-start)
5411 (catch 'break
5412 (while t
5413 (if is-unicode-escape-start
5414 ;; strictly speaking we should probably push-back
5415 ;; all the bad characters if the <backslash>uXXXX
5416 ;; sequence is malformed. But since there isn't a
5417 ;; correct context(is there?) for a bad Unicode
5418 ;; escape sequence in an identifier, we can report
5419 ;; an error here.
5420 (progn
5421 (setq escape-val 0)
5422 (dotimes (i 4)
5423 (setq c (js2-get-char)
5424 escape-val (js2-x-digit-to-int c escape-val))
5425 ;; Next check takes care of c < 0 and bad escape
5426 (if (minusp escape-val)
5427 (throw 'break nil)))
5428 (if (minusp escape-val)
5429 (js2-report-scan-error "msg.invalid.escape" t))
5430 (js2-add-to-string escape-val)
5431 (setq is-unicode-escape-start nil))
5432 (setq c (js2-get-char))
5433 (cond
5434 ((eq c ?\\)
5435 (setq c (js2-get-char))
5436 (if (eq c ?u)
5437 (setq is-unicode-escape-start t
5438 contains-escape t)
5439 (js2-report-scan-error "msg.illegal.character" t)))
5440 (t
5441 (if (or (eq c js2-EOF_CHAR)
5442 (not (js2-java-identifier-part-p c)))
5443 (throw 'break nil))
5444 (js2-add-to-string c))))))
5445 (js2-unget-char)
5446 (setq str (js2-get-string-from-buffer))
5447 (unless contains-escape
5448 ;; OPT we shouldn't have to make a string (object!) to
5449 ;; check if it's a keyword.
5450 ;; Return the corresponding token if it's a keyword
5451 (when (setq result (js2-string-to-keyword str))
5452 (if (and (< js2-language-version 170)
5453 (memq result '(js2-LET js2-YIELD)))
5454 ;; LET and YIELD are tokens only in 1.7 and later
5455 (setq result 'js2-NAME))
5456 (if (not (eq result 'js2-RESERVED))
5457 (throw 'return (js2-token-code result)))
5458 (js2-report-warning "msg.reserved.keyword" str)))
5459 ;; If we want to intern these as Rhino does, just use (intern str)
5460 (setq js2-ts-string str)
5461 (throw 'return js2-NAME)) ; end identifier/kwd check
5462 ;; is it a number?
5463 (when (or (js2-digit-p c)
5464 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5465 (setq js2-ts-string-buffer nil
5466 base 10)
5467 (when (eq c ?0)
5468 (setq c (js2-get-char))
5469 (cond
5470 ((or (eq c ?x) (eq c ?X))
5471 (setq base 16)
5472 (setq c (js2-get-char)))
5473 ((js2-digit-p c)
5474 (setq base 8))
5475 (t
5476 (js2-add-to-string ?0))))
5477 (if (eq base 16)
5478 (while (<= 0 (js2-x-digit-to-int c 0))
5479 (js2-add-to-string c)
5480 (setq c (js2-get-char)))
5481 (while (and (<= ?0 c) (<= c ?9))
5482 ;; We permit 08 and 09 as decimal numbers, which
5483 ;; makes our behavior a superset of the ECMA
5484 ;; numeric grammar. We might not always be so
5485 ;; permissive, so we warn about it.
5486 (when (and (eq base 8) (>= c ?8))
5487 (js2-report-warning "msg.bad.octal.literal"
5488 (if (eq c ?8) "8" "9"))
5489 (setq base 10))
5490 (js2-add-to-string c)
5491 (setq c (js2-get-char))))
5492 (setq is-integer t)
5493 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5494 (setq is-integer nil)
5495 (when (eq c ?.)
5496 (loop do
5497 (js2-add-to-string c)
5498 (setq c (js2-get-char))
5499 while (js2-digit-p c)))
5500 (when (memq c '(?e ?E))
5501 (js2-add-to-string c)
5502 (setq c (js2-get-char))
5503 (when (memq c '(?+ ?-))
5504 (js2-add-to-string c)
5505 (setq c (js2-get-char)))
5506 (unless (js2-digit-p c)
5507 (js2-report-scan-error "msg.missing.exponent" t))
5508 (loop do
5509 (js2-add-to-string c)
5510 (setq c (js2-get-char))
5511 while (js2-digit-p c))))
5512 (js2-unget-char)
5513 (setq js2-ts-string (js2-get-string-from-buffer)
5514 js2-ts-number
5515 (if (and (eq base 10) (not is-integer))
5516 (string-to-number js2-ts-string)
5517 ;; TODO: call runtime number-parser. Some of it is in
5518 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5519 (string-to-number js2-ts-string)))
5520 (throw 'return js2-NUMBER))
5521 ;; is it a string?
5522 (when (memq c '(?\" ?\'))
5523 ;; We attempt to accumulate a string the fast way, by
5524 ;; building it directly out of the reader. But if there
5525 ;; are any escaped characters in the string, we revert to
5526 ;; building it out of a string buffer.
5527 (setq quote-char c
5528 js2-ts-string-buffer nil
5529 c (js2-get-char))
5530 (catch 'break
5531 (while (/= c quote-char)
5532 (catch 'continue
5533 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5534 (js2-unget-char)
5535 (setq js2-token-end js2-ts-cursor)
5536 (js2-report-error "msg.unterminated.string.lit")
5537 (throw 'return js2-STRING))
5538 (when (eq c ?\\)
5539 ;; We've hit an escaped character
5540 (setq c (js2-get-char))
5541 (case c
5542 (?b (setq c ?\b))
5543 (?f (setq c ?\f))
5544 (?n (setq c ?\n))
5545 (?r (setq c ?\r))
5546 (?t (setq c ?\t))
5547 (?v (setq c ?\v))
5548 (?u
5549 (setq c1 (js2-read-unicode-escape))
5550 (if js2-parse-ide-mode
5551 (if c1
5552 (progn
5553 ;; just copy the string in IDE-mode
5554 (js2-add-to-string ?\\)
5555 (js2-add-to-string ?u)
5556 (dotimes (i 3)
5557 (js2-add-to-string (js2-get-char)))
5558 (setq c (js2-get-char))) ; added at end of loop
5559 ;; flag it as an invalid escape
5560 (js2-report-warning "msg.invalid.escape"
5561 nil (- js2-ts-cursor 2) 6))
5562 ;; Get 4 hex digits; if the u escape is not
5563 ;; followed by 4 hex digits, use 'u' + the
5564 ;; literal character sequence that follows.
5565 (js2-add-to-string ?u)
5566 (setq escape-val 0)
5567 (dotimes (i 4)
5568 (setq c (js2-get-char)
5569 escape-val (js2-x-digit-to-int c escape-val))
5570 (if (minusp escape-val)
5571 (throw 'continue nil))
5572 (js2-add-to-string c))
5573 ;; prepare for replace of stored 'u' sequence by escape value
5574 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5575 c escape-val)))
5576 (?x
5577 ;; Get 2 hex digits, defaulting to 'x'+literal
5578 ;; sequence, as above.
5579 (setq c (js2-get-char)
5580 escape-val (js2-x-digit-to-int c 0))
5581 (if (minusp escape-val)
5582 (progn
5583 (js2-add-to-string ?x)
5584 (throw 'continue nil))
5585 (setq c1 c
5586 c (js2-get-char)
5587 escape-val (js2-x-digit-to-int c escape-val))
5588 (if (minusp escape-val)
5589 (progn
5590 (js2-add-to-string ?x)
5591 (js2-add-to-string c1)
5592 (throw 'continue nil))
5593 ;; got 2 hex digits
5594 (setq c escape-val))))
5595 (?\n
5596 ;; Remove line terminator after escape to follow
5597 ;; SpiderMonkey and C/C++
5598 (setq c (js2-get-char))
5599 (throw 'continue nil))
5600 (t
5601 (when (and (<= ?0 c) (< c ?8))
5602 (setq val (- c ?0)
5603 c (js2-get-char))
5604 (when (and (<= ?0 c) (< c ?8))
5605 (setq val (- (+ (* 8 val) c) ?0)
5606 c (js2-get-char))
5607 (when (and (<= ?0 c)
5608 (< c ?8)
5609 (< val #o37))
5610 ;; c is 3rd char of octal sequence only
5611 ;; if the resulting val <= 0377
5612 (setq val (- (+ (* 8 val) c) ?0)
5613 c (js2-get-char))))
5614 (js2-unget-char)
5615 (setq c val)))))
5616 (js2-add-to-string c)
5617 (setq c (js2-get-char)))))
5618 (setq js2-ts-string (js2-get-string-from-buffer))
5619 (throw 'return js2-STRING))
5620 (case c
5621 (?\;
5622 (throw 'return js2-SEMI))
5623 (?\[
5624 (throw 'return js2-LB))
5625 (?\]
5626 (throw 'return js2-RB))
5627 (?{
5628 (throw 'return js2-LC))
5629 (?}
5630 (throw 'return js2-RC))
5631 (?\(
5632 (throw 'return js2-LP))
5633 (?\)
5634 (throw 'return js2-RP))
5635 (?,
5636 (throw 'return js2-COMMA))
5637 (??
5638 (throw 'return js2-HOOK))
5639 (?:
5640 (if (js2-match-char ?:)
5641 (js2-ts-return js2-COLONCOLON)
5642 (throw 'return js2-COLON)))
5643 (?.
5644 (if (js2-match-char ?.)
5645 (if (js2-match-char ?.)
5646 (js2-ts-return js2-TRIPLEDOT)
5647 (js2-ts-return js2-DOTDOT))
5648 (if (js2-match-char ?\()
5649 (js2-ts-return js2-DOTQUERY)
5650 (throw 'return js2-DOT))))
5651 (?|
5652 (if (js2-match-char ?|)
5653 (throw 'return js2-OR)
5654 (if (js2-match-char ?=)
5655 (js2-ts-return js2-ASSIGN_BITOR)
5656 (throw 'return js2-BITOR))))
5657 (?^
5658 (if (js2-match-char ?=)
5659 (js2-ts-return js2-ASSIGN_BITOR)
5660 (throw 'return js2-BITXOR)))
5661 (?&
5662 (if (js2-match-char ?&)
5663 (throw 'return js2-AND)
5664 (if (js2-match-char ?=)
5665 (js2-ts-return js2-ASSIGN_BITAND)
5666 (throw 'return js2-BITAND))))
5667 (?=
5668 (if (js2-match-char ?=)
5669 (if (js2-match-char ?=)
5670 (js2-ts-return js2-SHEQ)
5671 (throw 'return js2-EQ))
5672 (throw 'return js2-ASSIGN)))
5673 (?!
5674 (if (js2-match-char ?=)
5675 (if (js2-match-char ?=)
5676 (js2-ts-return js2-SHNE)
5677 (js2-ts-return js2-NE))
5678 (throw 'return js2-NOT)))
5679 (?<
5680 ;; NB:treat HTML begin-comment as comment-till-eol
5681 (when (js2-match-char ?!)
5682 (when (js2-match-char ?-)
5683 (when (js2-match-char ?-)
5684 (js2-skip-line)
5685 (setq js2-ts-comment-type 'html)
5686 (throw 'return js2-COMMENT)))
5687 (js2-unget-char))
5688 (if (js2-match-char ?<)
5689 (if (js2-match-char ?=)
5690 (js2-ts-return js2-ASSIGN_LSH)
5691 (js2-ts-return js2-LSH))
5692 (if (js2-match-char ?=)
5693 (js2-ts-return js2-LE)
5694 (throw 'return js2-LT))))
5695 (?>
5696 (if (js2-match-char ?>)
5697 (if (js2-match-char ?>)
5698 (if (js2-match-char ?=)
5699 (js2-ts-return js2-ASSIGN_URSH)
5700 (js2-ts-return js2-URSH))
5701 (if (js2-match-char ?=)
5702 (js2-ts-return js2-ASSIGN_RSH)
5703 (js2-ts-return js2-RSH)))
5704 (if (js2-match-char ?=)
5705 (js2-ts-return js2-GE)
5706 (throw 'return js2-GT))))
5707 (?*
5708 (if (js2-match-char ?=)
5709 (js2-ts-return js2-ASSIGN_MUL)
5710 (throw 'return js2-MUL)))
5711 (?/
5712 ;; is it a // comment?
5713 (when (js2-match-char ?/)
5714 (setq js2-token-beg (- js2-ts-cursor 2))
5715 (js2-skip-line)
5716 (setq js2-ts-comment-type 'line)
5717 ;; include newline so highlighting goes to end of window
5718 (incf js2-token-end)
5719 (throw 'return js2-COMMENT))
5720 ;; is it a /* comment?
5721 (when (js2-match-char ?*)
5722 (setq look-for-slash nil
5723 js2-token-beg (- js2-ts-cursor 2)
5724 js2-ts-comment-type
5725 (if (js2-match-char ?*)
5726 (progn
5727 (setq look-for-slash t)
5728 'jsdoc)
5729 'block))
5730 (while t
5731 (setq c (js2-get-char))
5732 (cond
5733 ((eq c js2-EOF_CHAR)
5734 (setq js2-token-end (1- js2-ts-cursor))
5735 (js2-report-error "msg.unterminated.comment")
5736 (throw 'return js2-COMMENT))
5737 ((eq c ?*)
5738 (setq look-for-slash t))
5739 ((eq c ?/)
5740 (if look-for-slash
5741 (js2-ts-return js2-COMMENT)))
5742 (t
5743 (setq look-for-slash nil
5744 js2-token-end js2-ts-cursor)))))
5745 (if (js2-match-char ?=)
5746 (js2-ts-return js2-ASSIGN_DIV)
5747 (throw 'return js2-DIV)))
5748 (?#
5749 (when js2-skip-preprocessor-directives
5750 (js2-skip-line)
5751 (setq js2-ts-comment-type 'preprocessor
5752 js2-token-end js2-ts-cursor)
5753 (throw 'return js2-COMMENT))
5754 (throw 'return js2-ERROR))
5755 (?%
5756 (if (js2-match-char ?=)
5757 (js2-ts-return js2-ASSIGN_MOD)
5758 (throw 'return js2-MOD)))
5759 (?~
5760 (throw 'return js2-BITNOT))
5761 (?+
5762 (if (js2-match-char ?=)
5763 (js2-ts-return js2-ASSIGN_ADD)
5764 (if (js2-match-char ?+)
5765 (js2-ts-return js2-INC)
5766 (throw 'return js2-ADD))))
5767 (?-
5768 (cond
5769 ((js2-match-char ?=)
5770 (setq c js2-ASSIGN_SUB))
5771 ((js2-match-char ?-)
5772 (unless js2-ts-dirty-line
5773 ;; treat HTML end-comment after possible whitespace
5774 ;; after line start as comment-until-eol
5775 (when (js2-match-char ?>)
5776 (js2-skip-line)
5777 (setq js2-ts-comment-type 'html)
5778 (throw 'return js2-COMMENT)))
5779 (setq c js2-DEC))
5780 (t
5781 (setq c js2-SUB)))
5782 (setq js2-ts-dirty-line t)
5783 (js2-ts-return c))
5784 (otherwise
5785 (js2-report-scan-error "msg.illegal.character")))))))
5786
5787 (defun js2-read-regexp (start-token)
5788 "Called by parser when it gets / or /= in literal context."
5789 (let (c err
5790 in-class ; inside a '[' .. ']' character-class
5791 flags
5792 (continue t))
5793 (setq js2-token-beg js2-ts-cursor
5794 js2-ts-string-buffer nil
5795 js2-ts-regexp-flags nil)
5796 (if (eq start-token js2-ASSIGN_DIV)
5797 ;; mis-scanned /=
5798 (js2-add-to-string ?=)
5799 (if (not (eq start-token js2-DIV))
5800 (error "failed assertion")))
5801 (while (and (not err)
5802 (or (/= (setq c (js2-get-char)) ?/)
5803 in-class))
5804 (cond
5805 ((or (= c ?\n)
5806 (= c js2-EOF_CHAR))
5807 (setq js2-token-end (1- js2-ts-cursor)
5808 err t
5809 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5810 (js2-report-error "msg.unterminated.re.lit"))
5811 (t (cond
5812 ((= c ?\\)
5813 (js2-add-to-string c)
5814 (setq c (js2-get-char)))
5815 ((= c ?\[)
5816 (setq in-class t))
5817 ((= c ?\])
5818 (setq in-class nil)))
5819 (js2-add-to-string c))))
5820 (unless err
5821 (while continue
5822 (cond
5823 ((js2-match-char ?g)
5824 (push ?g flags))
5825 ((js2-match-char ?i)
5826 (push ?i flags))
5827 ((js2-match-char ?m)
5828 (push ?m flags))
5829 (t
5830 (setq continue nil))))
5831 (if (js2-alpha-p (js2-peek-char))
5832 (js2-report-scan-error "msg.invalid.re.flag" t
5833 js2-ts-cursor 1))
5834 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5835 js2-ts-regexp-flags (js2-collect-string flags)
5836 js2-token-end js2-ts-cursor)
5837 ;; tell `parse-partial-sexp' to ignore this range of chars
5838 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5839
5840 (defun js2-get-first-xml-token ()
5841 (setq js2-ts-xml-open-tags-count 0
5842 js2-ts-is-xml-attribute nil
5843 js2-ts-xml-is-tag-content nil)
5844 (js2-unget-char)
5845 (js2-get-next-xml-token))
5846
5847 (defun js2-xml-discard-string ()
5848 "Throw away the string in progress and flag an XML parse error."
5849 (setq js2-ts-string-buffer nil
5850 js2-ts-string nil)
5851 (js2-report-scan-error "msg.XML.bad.form" t))
5852
5853 (defun js2-get-next-xml-token ()
5854 (setq js2-ts-string-buffer nil ; for recording the XML
5855 js2-token-beg js2-ts-cursor)
5856 (let (c result)
5857 (setq result
5858 (catch 'return
5859 (while t
5860 (setq c (js2-get-char))
5861 (cond
5862 ((= c js2-EOF_CHAR)
5863 (throw 'return js2-ERROR))
5864 (js2-ts-xml-is-tag-content
5865 (case c
5866 (?>
5867 (js2-add-to-string c)
5868 (setq js2-ts-xml-is-tag-content nil
5869 js2-ts-is-xml-attribute nil))
5870 (?/
5871 (js2-add-to-string c)
5872 (when (eq ?> (js2-peek-char))
5873 (setq c (js2-get-char))
5874 (js2-add-to-string c)
5875 (setq js2-ts-xml-is-tag-content nil)
5876 (decf js2-ts-xml-open-tags-count)))
5877 (?{
5878 (js2-unget-char)
5879 (setq js2-ts-string (js2-get-string-from-buffer))
5880 (throw 'return js2-XML))
5881 ((?\' ?\")
5882 (js2-add-to-string c)
5883 (unless (js2-read-quoted-string c)
5884 (throw 'return js2-ERROR)))
5885 (?=
5886 (js2-add-to-string c)
5887 (setq js2-ts-is-xml-attribute t))
5888 ((? ?\t ?\r ?\n)
5889 (js2-add-to-string c))
5890 (t
5891 (js2-add-to-string c)
5892 (setq js2-ts-is-xml-attribute nil)))
5893 (when (and (not js2-ts-xml-is-tag-content)
5894 (zerop js2-ts-xml-open-tags-count))
5895 (setq js2-ts-string (js2-get-string-from-buffer))
5896 (throw 'return js2-XMLEND)))
5897 (t
5898 ;; else not tag content
5899 (case c
5900 (?<
5901 (js2-add-to-string c)
5902 (setq c (js2-peek-char))
5903 (case c
5904 (?!
5905 (setq c (js2-get-char)) ;; skip !
5906 (js2-add-to-string c)
5907 (setq c (js2-peek-char))
5908 (case c
5909 (?-
5910 (setq c (js2-get-char)) ;; skip -
5911 (js2-add-to-string c)
5912 (if (eq c ?-)
5913 (progn
5914 (js2-add-to-string c)
5915 (unless (js2-read-xml-comment)
5916 (throw 'return js2-ERROR)))
5917 (js2-xml-discard-string)
5918 (throw 'return js2-ERROR)))
5919 (?\[
5920 (setq c (js2-get-char)) ;; skip [
5921 (js2-add-to-string c)
5922 (if (and (= (js2-get-char) ?C)
5923 (= (js2-get-char) ?D)
5924 (= (js2-get-char) ?A)
5925 (= (js2-get-char) ?T)
5926 (= (js2-get-char) ?A)
5927 (= (js2-get-char) ?\[))
5928 (progn
5929 (js2-add-to-string ?C)
5930 (js2-add-to-string ?D)
5931 (js2-add-to-string ?A)
5932 (js2-add-to-string ?T)
5933 (js2-add-to-string ?A)
5934 (js2-add-to-string ?\[)
5935 (unless (js2-read-cdata)
5936 (throw 'return js2-ERROR)))
5937 (js2-xml-discard-string)
5938 (throw 'return js2-ERROR)))
5939 (t
5940 (unless (js2-read-entity)
5941 (throw 'return js2-ERROR))))
5942 ;; Allow bare CDATA section, e.g.:
5943 ;; let xml = <![CDATA[ foo bar baz ]]>;
5944 (when (zerop js2-ts-xml-open-tags-count)
5945 (throw 'return js2-XMLEND)))
5946 (??
5947 (setq c (js2-get-char)) ;; skip ?
5948 (js2-add-to-string c)
5949 (unless (js2-read-PI)
5950 (throw 'return js2-ERROR)))
5951 (?/
5952 ;; end tag
5953 (setq c (js2-get-char)) ;; skip /
5954 (js2-add-to-string c)
5955 (when (zerop js2-ts-xml-open-tags-count)
5956 (js2-xml-discard-string)
5957 (throw 'return js2-ERROR))
5958 (setq js2-ts-xml-is-tag-content t)
5959 (decf js2-ts-xml-open-tags-count))
5960 (t
5961 ;; start tag
5962 (setq js2-ts-xml-is-tag-content t)
5963 (incf js2-ts-xml-open-tags-count))))
5964 (?{
5965 (js2-unget-char)
5966 (setq js2-ts-string (js2-get-string-from-buffer))
5967 (throw 'return js2-XML))
5968 (t
5969 (js2-add-to-string c))))))))
5970 (setq js2-token-end js2-ts-cursor)
5971 result))
5972
5973 (defun js2-read-quoted-string (quote)
5974 (let (c)
5975 (catch 'return
5976 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5977 (js2-add-to-string c)
5978 (if (eq c quote)
5979 (throw 'return t)))
5980 (js2-xml-discard-string) ;; throw away string in progress
5981 nil)))
5982
5983 (defun js2-read-xml-comment ()
5984 (let ((c (js2-get-char)))
5985 (catch 'return
5986 (while (/= c js2-EOF_CHAR)
5987 (catch 'continue
5988 (js2-add-to-string c)
5989 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5990 (setq c (js2-get-char))
5991 (js2-add-to-string c)
5992 (if (eq (js2-peek-char) ?>)
5993 (progn
5994 (setq c (js2-get-char)) ;; skip >
5995 (js2-add-to-string c)
5996 (throw 'return t))
5997 (throw 'continue nil)))
5998 (setq c (js2-get-char))))
5999 (js2-xml-discard-string)
6000 nil)))
6001
6002 (defun js2-read-cdata ()
6003 (let ((c (js2-get-char)))
6004 (catch 'return
6005 (while (/= c js2-EOF_CHAR)
6006 (catch 'continue
6007 (js2-add-to-string c)
6008 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6009 (setq c (js2-get-char))
6010 (js2-add-to-string c)
6011 (if (eq (js2-peek-char) ?>)
6012 (progn
6013 (setq c (js2-get-char)) ;; Skip >
6014 (js2-add-to-string c)
6015 (throw 'return t))
6016 (throw 'continue nil)))
6017 (setq c (js2-get-char))))
6018 (js2-xml-discard-string)
6019 nil)))
6020
6021 (defun js2-read-entity ()
6022 (let ((decl-tags 1)
6023 c)
6024 (catch 'return
6025 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6026 (js2-add-to-string c)
6027 (case c
6028 (?<
6029 (incf decl-tags))
6030 (?>
6031 (decf decl-tags)
6032 (if (zerop decl-tags)
6033 (throw 'return t)))))
6034 (js2-xml-discard-string)
6035 nil)))
6036
6037 (defun js2-read-PI ()
6038 "Scan an XML processing instruction."
6039 (let (c)
6040 (catch 'return
6041 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6042 (js2-add-to-string c)
6043 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6044 (setq c (js2-get-char)) ;; Skip >
6045 (js2-add-to-string c)
6046 (throw 'return t)))
6047 (js2-xml-discard-string)
6048 nil)))
6049
6050 (defun js2-scanner-get-line ()
6051 "Return the text of the current scan line."
6052 (buffer-substring (point-at-bol) (point-at-eol)))
6053
6054 ;;; Highlighting
6055
6056 (defun js2-set-face (beg end face &optional record)
6057 "Fontify a region. If RECORD is non-nil, record for later."
6058 (when (plusp js2-highlight-level)
6059 (setq beg (min (point-max) beg)
6060 beg (max (point-min) beg)
6061 end (min (point-max) end)
6062 end (max (point-min) end))
6063 (if record
6064 (push (list beg end face) js2-mode-fontifications)
6065 (put-text-property beg end 'font-lock-face face))))
6066
6067 (defun js2-set-kid-face (pos kid len face)
6068 "Set-face on a child node.
6069 POS is absolute buffer position of parent.
6070 KID is the child node.
6071 LEN is the length to fontify.
6072 FACE is the face to fontify with."
6073 (js2-set-face (+ pos (js2-node-pos kid))
6074 (+ pos (js2-node-pos kid) (js2-node-len kid))
6075 face))
6076
6077 (defsubst js2-fontify-kwd (start length)
6078 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6079
6080 (defsubst js2-clear-face (beg end)
6081 (remove-text-properties beg end '(font-lock-face nil
6082 help-echo nil
6083 point-entered nil
6084 c-in-sws nil)))
6085
6086 (defconst js2-ecma-global-props
6087 (concat "^"
6088 (regexp-opt
6089 '("Infinity" "NaN" "undefined" "arguments") t)
6090 "$")
6091 "Value properties of the Ecma-262 Global Object.
6092 Shown at or above `js2-highlight-level' 2.")
6093
6094 ;; might want to add the name "arguments" to this list?
6095 (defconst js2-ecma-object-props
6096 (concat "^"
6097 (regexp-opt
6098 '("prototype" "__proto__" "__parent__") t)
6099 "$")
6100 "Value properties of the Ecma-262 Object constructor.
6101 Shown at or above `js2-highlight-level' 2.")
6102
6103 (defconst js2-ecma-global-funcs
6104 (concat
6105 "^"
6106 (regexp-opt
6107 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6108 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6109 "$")
6110 "Function properties of the Ecma-262 Global object.
6111 Shown at or above `js2-highlight-level' 2.")
6112
6113 (defconst js2-ecma-number-props
6114 (concat "^"
6115 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6116 "NEGATIVE_INFINITY"
6117 "POSITIVE_INFINITY") t)
6118 "$")
6119 "Properties of the Ecma-262 Number constructor.
6120 Shown at or above `js2-highlight-level' 2.")
6121
6122 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6123 "Properties of the Ecma-262 Date constructor.
6124 Shown at or above `js2-highlight-level' 2.")
6125
6126 (defconst js2-ecma-math-props
6127 (concat "^"
6128 (regexp-opt
6129 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6130 t)
6131 "$")
6132 "Properties of the Ecma-262 Math object.
6133 Shown at or above `js2-highlight-level' 2.")
6134
6135 (defconst js2-ecma-math-funcs
6136 (concat "^"
6137 (regexp-opt
6138 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6139 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6140 "$")
6141 "Function properties of the Ecma-262 Math object.
6142 Shown at or above `js2-highlight-level' 2.")
6143
6144 (defconst js2-ecma-function-props
6145 (concat
6146 "^"
6147 (regexp-opt
6148 '(;; properties of the Object prototype object
6149 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6150 "toLocaleString" "toString" "valueOf"
6151 ;; properties of the Function prototype object
6152 "apply" "call"
6153 ;; properties of the Array prototype object
6154 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6155 "splice" "unshift"
6156 ;; properties of the String prototype object
6157 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6158 "localeCompare" "match" "replace" "search" "split" "substring"
6159 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6160 "toUpperCase"
6161 ;; properties of the Number prototype object
6162 "toExponential" "toFixed" "toPrecision"
6163 ;; properties of the Date prototype object
6164 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6165 "getMinutes" "getMonth" "getSeconds" "getTime"
6166 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6167 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6168 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6169 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6170 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6171 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6172 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6173 "toTimeString" "toUTCString"
6174 ;; properties of the RegExp prototype object
6175 "exec" "test"
6176 ;; properties of the JSON prototype object
6177 "parse" "stringify"
6178 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6179 "toSource" "__defineGetter__" "__defineSetter__"
6180 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6181 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6182 t)
6183 "$")
6184 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6185 Shown at or above `js2-highlight-level' 3.")
6186
6187 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6188 (let ((target-name (and target
6189 (js2-name-node-p target)
6190 (js2-name-node-name target)))
6191 (prop-name (if prop (js2-name-node-name prop)))
6192 (level1 (>= js2-highlight-level 1))
6193 (level2 (>= js2-highlight-level 2))
6194 (level3 (>= js2-highlight-level 3))
6195 pos face)
6196 (when level2
6197 (if call-p
6198 (cond
6199 ((and target prop)
6200 (cond
6201 ((and level3 (string-match js2-ecma-function-props prop-name))
6202 (setq face 'font-lock-builtin-face))
6203 ((and target-name prop)
6204 (cond
6205 ((string= target-name "Date")
6206 (if (string-match js2-ecma-date-props prop-name)
6207 (setq face 'font-lock-builtin-face)))
6208 ((string= target-name "Math")
6209 (if (string-match js2-ecma-math-funcs prop-name)
6210 (setq face 'font-lock-builtin-face)))))))
6211 (prop
6212 (if (string-match js2-ecma-global-funcs prop-name)
6213 (setq face 'font-lock-builtin-face))))
6214 (cond
6215 ((and target prop)
6216 (cond
6217 ((string= target-name "Number")
6218 (if (string-match js2-ecma-number-props prop-name)
6219 (setq face 'font-lock-constant-face)))
6220 ((string= target-name "Math")
6221 (if (string-match js2-ecma-math-props prop-name)
6222 (setq face 'font-lock-constant-face)))))
6223 (prop
6224 (if (string-match js2-ecma-object-props prop-name)
6225 (setq face 'font-lock-constant-face)))))
6226 (when face
6227 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6228 (js2-node-pos prop))) ; relative
6229 (+ pos (js2-node-len prop))
6230 face 'record)))))
6231
6232 (defun js2-parse-highlight-member-expr-node (node)
6233 "Perform syntax highlighting of EcmaScript built-in properties.
6234 The variable `js2-highlight-level' governs this highighting."
6235 (let (face target prop name pos end parent call-p callee)
6236 (cond
6237 ;; case 1: simple name, e.g. foo
6238 ((js2-name-node-p node)
6239 (setq name (js2-name-node-name node))
6240 ;; possible for name to be nil in rare cases - saw it when
6241 ;; running js2-mode on an elisp buffer. Might as well try to
6242 ;; make it so js2-mode never barfs.
6243 (when name
6244 (setq face (if (string-match js2-ecma-global-props name)
6245 'font-lock-constant-face))
6246 (when face
6247 (setq pos (js2-node-pos node)
6248 end (+ pos (js2-node-len node)))
6249 (js2-set-face pos end face 'record))))
6250 ;; case 2: property access or function call
6251 ((or (js2-prop-get-node-p node)
6252 ;; highlight function call if expr is a prop-get node
6253 ;; or a plain name (i.e. unqualified function call)
6254 (and (setq call-p (js2-call-node-p node))
6255 (setq callee (js2-call-node-target node)) ; separate setq!
6256 (or (js2-prop-get-node-p callee)
6257 (js2-name-node-p callee))))
6258 (setq parent node
6259 node (if call-p callee node))
6260 (if (and call-p (js2-name-node-p callee))
6261 (setq prop callee)
6262 (setq target (js2-prop-get-node-left node)
6263 prop (js2-prop-get-node-right node)))
6264 (cond
6265 ((js2-name-node-p target)
6266 (if (js2-name-node-p prop)
6267 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6268 (js2-parse-highlight-prop-get parent target prop call-p)
6269 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6270 (js2-parse-highlight-prop-get parent target nil call-p)))
6271 ((js2-name-node-p prop)
6272 ;; case 2c: complex target, simple name, e.g. x[y].bar
6273 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6274
6275 (defun js2-parse-highlight-member-expr-fn-name (expr)
6276 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6277 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6278 We currently only handle the case where the last component is a prop-get
6279 of a simple name. Called before EXPR has a parent node."
6280 (let (pos
6281 (name (and (js2-prop-get-node-p expr)
6282 (js2-prop-get-node-right expr))))
6283 (when (js2-name-node-p name)
6284 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6285 (js2-node-pos name)))
6286 (+ pos (js2-node-len name))
6287 'font-lock-function-name-face
6288 'record))))
6289
6290 ;; source: http://jsdoc.sourceforge.net/
6291 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6292 ;; allows type specifications, and needs work before entering the wild.
6293
6294 (defconst js2-jsdoc-param-tag-regexp
6295 (concat "^\\s-*\\*+\\s-*\\(@"
6296 "\\(?:param\\|argument\\)"
6297 "\\)"
6298 "\\s-*\\({[^}]+}\\)?" ; optional type
6299 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6300 "\\>")
6301 "Matches jsdoc tags with optional type and optional param name.")
6302
6303 (defconst js2-jsdoc-typed-tag-regexp
6304 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6305 (regexp-opt
6306 '("enum"
6307 "extends"
6308 "field"
6309 "id"
6310 "implements"
6311 "lends"
6312 "mods"
6313 "requires"
6314 "return"
6315 "returns"
6316 "throw"
6317 "throws"))
6318 "\\)\\)\\s-*\\({[^}]+}\\)?")
6319 "Matches jsdoc tags with optional type.")
6320
6321 (defconst js2-jsdoc-arg-tag-regexp
6322 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6323 (regexp-opt
6324 '("alias"
6325 "augments"
6326 "borrows"
6327 "bug"
6328 "base"
6329 "config"
6330 "default"
6331 "define"
6332 "exception"
6333 "function"
6334 "member"
6335 "memberOf"
6336 "name"
6337 "namespace"
6338 "property"
6339 "since"
6340 "suppress"
6341 "this"
6342 "throws"
6343 "type"
6344 "version"))
6345 "\\)\\)\\s-+\\([^ \t]+\\)")
6346 "Matches jsdoc tags with a single argument.")
6347
6348 (defconst js2-jsdoc-empty-tag-regexp
6349 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6350 (regexp-opt
6351 '("addon"
6352 "author"
6353 "class"
6354 "const"
6355 "constant"
6356 "constructor"
6357 "constructs"
6358 "deprecated"
6359 "desc"
6360 "description"
6361 "event"
6362 "example"
6363 "exec"
6364 "export"
6365 "fileoverview"
6366 "final"
6367 "function"
6368 "hidden"
6369 "ignore"
6370 "implicitCast"
6371 "inheritDoc"
6372 "inner"
6373 "interface"
6374 "license"
6375 "noalias"
6376 "noshadow"
6377 "notypecheck"
6378 "override"
6379 "owner"
6380 "preserve"
6381 "preserveTry"
6382 "private"
6383 "protected"
6384 "public"
6385 "static"
6386 "supported"
6387 ))
6388 "\\)\\)\\s-*")
6389 "Matches empty jsdoc tags.")
6390
6391 (defconst js2-jsdoc-link-tag-regexp
6392 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6393 "Matches a jsdoc link or code tag.")
6394
6395 (defconst js2-jsdoc-see-tag-regexp
6396 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6397 "Matches a jsdoc @see tag.")
6398
6399 (defconst js2-jsdoc-html-tag-regexp
6400 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6401 "Matches a simple (no attributes) html start- or end-tag.")
6402
6403 (defun js2-jsdoc-highlight-helper ()
6404 (js2-set-face (match-beginning 1)
6405 (match-end 1)
6406 'js2-jsdoc-tag)
6407 (if (match-beginning 2)
6408 (if (save-excursion
6409 (goto-char (match-beginning 2))
6410 (= (char-after) ?{))
6411 (js2-set-face (1+ (match-beginning 2))
6412 (1- (match-end 2))
6413 'js2-jsdoc-type)
6414 (js2-set-face (match-beginning 2)
6415 (match-end 2)
6416 'js2-jsdoc-value)))
6417 (if (match-beginning 3)
6418 (js2-set-face (match-beginning 3)
6419 (match-end 3)
6420 'js2-jsdoc-value)))
6421
6422 (defun js2-highlight-jsdoc (ast)
6423 "Highlight doc comment tags."
6424 (let ((comments (js2-ast-root-comments ast))
6425 beg end)
6426 (save-excursion
6427 (dolist (node comments)
6428 (when (eq (js2-comment-node-format node) 'jsdoc)
6429 (setq beg (js2-node-abs-pos node)
6430 end (+ beg (js2-node-len node)))
6431 (save-restriction
6432 (narrow-to-region beg end)
6433 (dolist (re (list js2-jsdoc-param-tag-regexp
6434 js2-jsdoc-typed-tag-regexp
6435 js2-jsdoc-arg-tag-regexp
6436 js2-jsdoc-link-tag-regexp
6437 js2-jsdoc-see-tag-regexp
6438 js2-jsdoc-empty-tag-regexp))
6439 (goto-char beg)
6440 (while (re-search-forward re nil t)
6441 (js2-jsdoc-highlight-helper)))
6442 ;; simple highlighting for html tags
6443 (goto-char beg)
6444 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6445 (js2-set-face (match-beginning 1)
6446 (match-end 1)
6447 'js2-jsdoc-html-tag-delimiter)
6448 (js2-set-face (match-beginning 2)
6449 (match-end 2)
6450 'js2-jsdoc-html-tag-name)
6451 (js2-set-face (match-beginning 3)
6452 (match-end 3)
6453 'js2-jsdoc-html-tag-delimiter))))))))
6454
6455 (defun js2-highlight-assign-targets (node left right)
6456 "Highlight function properties and external variables."
6457 (let (leftpos end name)
6458 ;; highlight vars and props assigned function values
6459 (when (js2-function-node-p right)
6460 (cond
6461 ;; var foo = function() {...}
6462 ((js2-name-node-p left)
6463 (setq name left))
6464 ;; foo.bar.baz = function() {...}
6465 ((and (js2-prop-get-node-p left)
6466 (js2-name-node-p (js2-prop-get-node-right left)))
6467 (setq name (js2-prop-get-node-right left))))
6468 (when name
6469 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6470 (+ leftpos (js2-node-len name))
6471 'font-lock-function-name-face
6472 'record)))))
6473
6474 (defun js2-record-name-node (node)
6475 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6476 later. NODE must be a name node."
6477 (let (leftpos end)
6478 (push (list node js2-current-scope
6479 (setq leftpos (js2-node-abs-pos node))
6480 (setq end (+ leftpos (js2-node-len node))))
6481 js2-recorded-identifiers)))
6482
6483 (defun js2-highlight-undeclared-vars ()
6484 "After entire parse is finished, look for undeclared variable references.
6485 We have to wait until entire buffer is parsed, since JavaScript permits var
6486 decls to occur after they're used.
6487
6488 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6489 it is considered declared."
6490 (let (name)
6491 (dolist (entry js2-recorded-identifiers)
6492 (destructuring-bind (name-node scope pos end) entry
6493 (setq name (js2-name-node-name name-node))
6494 (unless (or (member name js2-global-externs)
6495 (member name js2-default-externs)
6496 (member name js2-additional-externs)
6497 (js2-get-defining-scope scope name))
6498 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6499 'js2-external-variable))))
6500 (setq js2-recorded-identifiers nil)))
6501
6502 ;;; IMenu support
6503
6504 ;; We currently only support imenu, but eventually should support speedbar and
6505 ;; possibly other browsing mechanisms.
6506
6507 ;; The basic strategy is to identify function assignment targets of the form
6508 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6509 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6510 ;; for imenu after parsing is finished.
6511
6512 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6513 ;; JavaScript, and the general problem is undecidable. However, several forms
6514 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6515 ;; include:
6516
6517 ;; function foo() -- function declaration
6518 ;; foo = function() -- function expression assigned to variable
6519 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6520 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6521 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6522 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6523 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6524 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6525 ;; function foo() {function bar() {...}} -- nested function
6526 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6527
6528 ;; This list boils down to a few forms that can be combined recursively.
6529 ;; Top-level named function declarations include both the left-hand (name)
6530 ;; and the right-hand (function value) expressions needed to produce an imenu
6531 ;; entry. The other "right-hand" forms we need to look for are:
6532 ;; - functions declared as props/getters/setters in object literals
6533 ;; - nested named function declarations
6534 ;; The "left-hand" expressions that functions can be assigned to include:
6535 ;; - local/global variables
6536 ;; - nested property-get expressions like a.b.c.d
6537 ;; - element gets like foo[10] or foo['bar'] where the index
6538 ;; expression can be trivially converted to a property name. They
6539 ;; effectively then become property gets.
6540
6541 ;; All the different definition types are canonicalized into the form
6542 ;; foo.bar.baz = position-of-function-keyword
6543
6544 ;; We need to build a trie-like structure for imenu. As an example,
6545 ;; consider the following JavaScript code:
6546
6547 ;; a = function() {...} // function at position 5
6548 ;; b = function() {...} // function at position 25
6549 ;; foo = function() {...} // function at position 100
6550 ;; foo.bar = function() {...} // function at position 200
6551 ;; foo.bar.baz = function() {...} // function at position 300
6552 ;; foo.bar.zab = function() {...} // function at position 400
6553
6554 ;; During parsing we accumulate an entry for each definition in
6555 ;; the variable `js2-imenu-recorder', like so:
6556
6557 ;; '((fn a 5)
6558 ;; (fn b 25)
6559 ;; (fn foo 100)
6560 ;; (fn foo bar 200)
6561 ;; (fn foo bar baz 300)
6562 ;; (fn foo bar zab 400))
6563
6564 ;; Where 'fn' is the respective function node.
6565 ;; After parsing these entries are merged into this alist-trie:
6566
6567 ;; '((a . 1)
6568 ;; (b . 2)
6569 ;; (foo (<definition> . 3)
6570 ;; (bar (<definition> . 6)
6571 ;; (baz . 100)
6572 ;; (zab . 200))))
6573
6574 ;; Note the wacky need for a <definition> name. The token can be anything
6575 ;; that isn't a valid JavaScript identifier, because you might make foo
6576 ;; a function and then start setting properties on it that are also functions.
6577
6578 (defun js2-prop-node-name (node)
6579 "Return the name of a node that may be a property-get/property-name.
6580 If NODE is not a valid name-node, string-node or integral number-node,
6581 returns nil. Otherwise returns the string name/value of the node."
6582 (cond
6583 ((js2-name-node-p node)
6584 (js2-name-node-name node))
6585 ((js2-string-node-p node)
6586 (js2-string-node-value node))
6587 ((and (js2-number-node-p node)
6588 (string-match "^[0-9]+$" (js2-number-node-value node)))
6589 (js2-number-node-value node))
6590 ((js2-this-node-p node)
6591 "this")))
6592
6593 (defun js2-node-qname-component (node)
6594 "Return the name of this node, if it contributes to a qname.
6595 Returns nil if the node doesn't contribute."
6596 (copy-sequence
6597 (or (js2-prop-node-name node)
6598 (if (and (js2-function-node-p node)
6599 (js2-function-node-name node))
6600 (js2-name-node-name (js2-function-node-name node))))))
6601
6602 (defun js2-record-imenu-entry (fn-node qname pos)
6603 "Add an entry to `js2-imenu-recorder'.
6604 FN-NODE should be the current item's function node.
6605
6606 Associate FN-NODE with its QNAME for later lookup.
6607 This is used in postprocessing the chain list. For each chain, we find
6608 the parent function, look up its qname, then prepend a copy of it to the chain."
6609 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6610 (unless js2-imenu-function-map
6611 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6612 (puthash fn-node qname js2-imenu-function-map))
6613
6614 (defun js2-record-imenu-functions (node &optional var)
6615 "Record function definitions for imenu.
6616 NODE is a function node or an object literal.
6617 VAR, if non-nil, is the expression that NODE is being assigned to.
6618 When passed arguments of wrong type, does nothing."
6619 (when js2-parse-ide-mode
6620 (let ((fun-p (js2-function-node-p node))
6621 qname left fname-node pos)
6622 (cond
6623 ;; non-anonymous function declaration?
6624 ((and fun-p
6625 (not var)
6626 (setq fname-node (js2-function-node-name node)))
6627 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6628 ;; for remaining forms, compute left-side tree branch first
6629 ((and var (setq qname (js2-compute-nested-prop-get var)))
6630 (cond
6631 ;; foo.bar.baz = function
6632 (fun-p
6633 (js2-record-imenu-entry node qname (js2-node-pos node)))
6634 ;; foo.bar.baz = object-literal
6635 ;; look for nested functions: {a: {b: function() {...} }}
6636 ((js2-object-node-p node)
6637 ;; Node position here is still absolute, since the parser
6638 ;; passes the assignment target and value expressions
6639 ;; to us before they are added as children of the assignment node.
6640 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6641
6642 (defun js2-compute-nested-prop-get (node)
6643 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6644 component nodes as a list. Otherwise return nil. Element-gets are treated
6645 as property-gets if the index expression is a string, or a positive integer."
6646 (let (left right head)
6647 (cond
6648 ((or (js2-name-node-p node)
6649 (js2-this-node-p node))
6650 (list node))
6651 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6652 ((js2-prop-get-node-p node) ; foo.bar
6653 (setq left (js2-prop-get-node-left node)
6654 right (js2-prop-get-node-right node))
6655 (if (setq head (js2-compute-nested-prop-get left))
6656 (nconc head (list right))))
6657 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6658 (setq left (js2-elem-get-node-target node)
6659 right (js2-elem-get-node-element node))
6660 (if (or (js2-string-node-p right) ; ['bar']
6661 (and (js2-number-node-p right) ; [10]
6662 (string-match "^[0-9]+$"
6663 (js2-number-node-value right))))
6664 (if (setq head (js2-compute-nested-prop-get left))
6665 (nconc head (list right))))))))
6666
6667 (defun js2-record-object-literal (node qname pos)
6668 "Recursively process an object literal looking for functions.
6669 NODE is an object literal that is the right-hand child of an assignment
6670 expression. QNAME is a list of nodes representing the assignment target,
6671 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6672 POS is the absolute position of the node.
6673 We do a depth-first traversal of NODE. For any functions we find,
6674 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6675 (let (left right prop-qname)
6676 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6677 (let ((left (js2-infix-node-left e))
6678 ;; Element positions are relative to the parent position.
6679 (pos (+ pos (js2-node-pos e))))
6680 (cond
6681 ;; foo: function() {...}
6682 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6683 (when (js2-prop-node-name left)
6684 ;; As a policy decision, we record the position of the property,
6685 ;; not the position of the `function' keyword, since the property
6686 ;; is effectively the name of the function.
6687 (js2-record-imenu-entry right (append qname (list left)) pos)))
6688 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6689 ((js2-object-node-p right)
6690 (js2-record-object-literal right
6691 (append qname (list (js2-infix-node-left e)))
6692 (+ pos (js2-node-pos right)))))))))
6693
6694 (defun js2-node-top-level-decl-p (node)
6695 "Return t if NODE's name is defined in the top-level scope.
6696 Also returns t if NODE's name is not defined in any scope, since it implies
6697 that it's an external variable, which must also be in the top-level scope."
6698 (let* ((name (js2-prop-node-name node))
6699 (this-scope (js2-node-get-enclosing-scope node))
6700 defining-scope)
6701 (cond
6702 ((js2-this-node-p node)
6703 nil)
6704 ((null this-scope)
6705 t)
6706 ((setq defining-scope (js2-get-defining-scope this-scope name))
6707 (js2-ast-root-p defining-scope))
6708 (t t))))
6709
6710 (defun js2-wrapper-function-p (node)
6711 "Returns t if NODE is a function expression that's immediately invoked.
6712 NODE must be `js2-function-node'."
6713 (let ((parent (js2-node-parent node)))
6714 (or
6715 ;; function(){...}();
6716 (js2-call-node-p parent)
6717 (and (js2-paren-node-p parent)
6718 ;; (function(){...})();
6719 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6720 ;; (function(){...}).call(this);
6721 (and (js2-prop-get-node-p parent)
6722 (member (js2-name-node-name (js2-prop-get-node-right parent))
6723 '("call" "apply"))
6724 (js2-call-node-p (js2-node-parent parent))))))))
6725
6726 (defun js2-browse-postprocess-chains (entries)
6727 "Modify function-declaration name chains after parsing finishes.
6728 Some of the information is only available after the parse tree is complete.
6729 For instance, processing a nested scope requires a parent function node."
6730 (let (result head fn current-fn parent-qname qname p elem)
6731 (dolist (entry entries)
6732 ;; function node goes first
6733 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6734 ;; Examine head's defining scope:
6735 ;; Pre-processed chain, or top-level/external, keep as-is.
6736 (if (or (stringp head) (js2-node-top-level-decl-p head))
6737 (push chain result)
6738 (when (js2-this-node-p head)
6739 (setq chain (cdr chain))) ; discard this-node
6740 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6741 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6742 (when (eq parent-qname 'not-found)
6743 ;; anonymous function expressions are not recorded
6744 ;; during the parse, so we need to handle this case here
6745 (setq parent-qname
6746 (if (js2-wrapper-function-p fn)
6747 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6748 (if (js2-ast-root-p grandparent)
6749 nil
6750 (gethash grandparent js2-imenu-function-map 'skip)))
6751 'skip))
6752 (puthash fn parent-qname js2-imenu-function-map))
6753 (unless (eq parent-qname 'skip)
6754 ;; prefix parent fn qname to this chain.
6755 (let ((qname (append parent-qname chain)))
6756 (puthash current-fn (butlast qname) js2-imenu-function-map)
6757 (push qname result)))))))
6758 ;; finally replace each node in each chain with its name.
6759 (dolist (chain result)
6760 (setq p chain)
6761 (while p
6762 (if (js2-node-p (setq elem (car p)))
6763 (setcar p (js2-node-qname-component elem)))
6764 (setq p (cdr p))))
6765 result))
6766
6767 ;; Merge name chains into a trie-like tree structure of nested lists.
6768 ;; To simplify construction of the trie, we first build it out using the rule
6769 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6770 ;; [key, num-or-list]. The second element can be a number; if so, this key
6771 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6772 ;; associated with the key at this level.) Otherwise the second element is
6773 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6774 ;; a simple recursive formulation.
6775 ;;
6776 ;; js2-mode is building the data structure for imenu. The imenu documentation
6777 ;; claims that it's the structure above, but in practice it wants the children
6778 ;; at the same list level as the key for that level, which is how I've drawn
6779 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6780 ;; list wrapper around the children at each level.
6781 ;;
6782 ;; A completed nested imenu-alist entry looks like this:
6783 ;; '(("foo"
6784 ;; ("<definition>" . 7)
6785 ;; ("bar"
6786 ;; ("a" . 40)
6787 ;; ("b" . 60))))
6788 ;;
6789 ;; In particular, the documentation for `imenu--index-alist' says that
6790 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6791 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6792
6793 (defun js2-treeify (lst)
6794 "Convert (a b c d) to (a ((b ((c d)))))."
6795 (if (null (cddr lst)) ; list length <= 2
6796 lst
6797 (list (car lst) (list (js2-treeify (cdr lst))))))
6798
6799 (defun js2-build-alist-trie (chains trie)
6800 "Merge declaration name chains into a trie-like alist structure for imenu.
6801 CHAINS is the qname chain list produced during parsing. TRIE is a
6802 list of elements built up so far."
6803 (let (head tail pos branch kids)
6804 (dolist (chain chains)
6805 (setq head (car chain)
6806 tail (cdr chain)
6807 pos (if (numberp (car tail)) (car tail))
6808 branch (js2-find-if (lambda (n)
6809 (string= (car n) head))
6810 trie)
6811 kids (second branch))
6812 (cond
6813 ;; case 1: this key isn't in the trie yet
6814 ((null branch)
6815 (if trie
6816 (setcdr (last trie) (list (js2-treeify chain)))
6817 (setq trie (list (js2-treeify chain)))))
6818 ;; case 2: key is present with a single number entry: replace w/ list
6819 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6820 ;; ("<definition>" 20)))
6821 ((numberp kids)
6822 (setcar (cdr branch)
6823 (list (list "<definition-1>" kids)
6824 (if pos
6825 (list "<definition-2>" pos)
6826 (js2-treeify tail)))))
6827 ;; case 3: key is there (with kids), and we're a number entry
6828 (pos
6829 (setcdr (last kids)
6830 (list
6831 (list (format "<definition-%d>"
6832 (1+ (loop for kid in kids
6833 count (eq ?< (aref (car kid) 0)))))
6834 pos))))
6835 ;; case 4: key is there with kids, need to merge in our chain
6836 (t
6837 (js2-build-alist-trie (list tail) kids))))
6838 trie))
6839
6840 (defun js2-flatten-trie (trie)
6841 "Convert TRIE to imenu-format.
6842 Recurses through nodes, and for each one whose second element is a list,
6843 appends the list's flattened elements to the current element. Also
6844 changes the tails into conses. For instance, this pre-flattened trie
6845
6846 '(a ((b 20)
6847 (c ((d 30)
6848 (e 40)))))
6849
6850 becomes
6851
6852 '(a (b . 20)
6853 (c (d . 30)
6854 (e . 40)))
6855
6856 Note that the root of the trie has no key, just a list of chains.
6857 This is also true for the value of any key with multiple children,
6858 e.g. key 'c' in the example above."
6859 (cond
6860 ((listp (car trie))
6861 (mapcar #'js2-flatten-trie trie))
6862 (t
6863 (if (numberp (second trie))
6864 (cons (car trie) (second trie))
6865 ;; else pop list and append its kids
6866 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6867
6868 (defun js2-build-imenu-index ()
6869 "Turn `js2-imenu-recorder' into an imenu data structure."
6870 (unless (eq js2-imenu-recorder 'empty)
6871 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6872 (result (js2-build-alist-trie chains nil)))
6873 (js2-flatten-trie result))))
6874
6875 (defun js2-test-print-chains (chains)
6876 "Print a list of qname chains.
6877 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6878 i.e. one or more nodes, and an integer position as the list tail."
6879 (mapconcat (lambda (chain)
6880 (concat "("
6881 (mapconcat (lambda (elem)
6882 (if (js2-node-p elem)
6883 (or (js2-node-qname-component elem)
6884 "nil")
6885 (number-to-string elem)))
6886 chain
6887 " ")
6888 ")"))
6889 chains
6890 "\n"))
6891
6892 ;;; Parser
6893
6894 (defconst js2-version "1.8.0"
6895 "Version of JavaScript supported, plus minor js2 version.")
6896
6897 (defmacro js2-record-face (face)
6898 "Record a style run of FACE for the current token."
6899 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6900
6901 (defsubst js2-node-end (n)
6902 "Computes the absolute end of node N.
6903 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6904 is only true until the node is added to its parent; i.e., while parsing."
6905 (+ (js2-node-pos n)
6906 (js2-node-len n)))
6907
6908 (defun js2-record-comment ()
6909 "Record a comment in `js2-scanned-comments'."
6910 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6911 :format js2-ts-comment-type)
6912 js2-scanned-comments)
6913 (when js2-parse-ide-mode
6914 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6915 'font-lock-doc-face
6916 'font-lock-comment-face))
6917 (when (memq js2-ts-comment-type '(html preprocessor))
6918 ;; Tell cc-engine the bounds of the comment.
6919 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6920
6921 ;; This function is called depressingly often, so it should be fast.
6922 ;; Most of the time it's looking at the same token it peeked before.
6923 (defun js2-peek-token ()
6924 "Return the next token without consuming it.
6925 If previous token was consumed, calls scanner to get new token.
6926 If previous token was -not- consumed, returns it (idempotent).
6927
6928 This function will not return a newline (js2-EOL) - instead, it
6929 gobbles newlines until it finds a non-newline token, and flags
6930 that token as appearing just after a newline.
6931
6932 This function will also not return a js2-COMMENT. Instead, it
6933 records comments found in `js2-scanned-comments'. If the token
6934 returned by this function immediately follows a jsdoc comment,
6935 the token is flagged as such.
6936
6937 Note that this function always returned the un-flagged token!
6938 The flags, if any, are saved in `js2-current-flagged-token'."
6939 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6940 js2-current-token ; most common case - return already-peeked token
6941 (let ((tt (js2-get-token)) ; call scanner
6942 saw-eol
6943 face)
6944 ;; process comments and whitespace
6945 (while (or (= tt js2-EOL)
6946 (= tt js2-COMMENT))
6947 (if (= tt js2-EOL)
6948 (setq saw-eol t)
6949 (setq saw-eol nil)
6950 (if js2-record-comments
6951 (js2-record-comment)))
6952 (setq tt (js2-get-token))) ; call scanner
6953 (setq js2-current-token tt
6954 js2-current-flagged-token (if saw-eol
6955 (logior tt js2-ti-after-eol)
6956 tt))
6957 ;; perform lexical fontification as soon as token is scanned
6958 (when js2-parse-ide-mode
6959 (cond
6960 ((minusp tt)
6961 (js2-record-face 'js2-error))
6962 ((setq face (aref js2-kwd-tokens tt))
6963 (js2-record-face face))
6964 ((and (= tt js2-NAME)
6965 (equal js2-ts-string "undefined"))
6966 (js2-record-face 'font-lock-constant-face))))
6967 tt))) ; return unflagged token
6968
6969 (defun js2-peek-flagged-token ()
6970 "Returns the current token along with any flags set for it."
6971 (js2-peek-token)
6972 js2-current-flagged-token)
6973
6974 (defsubst js2-consume-token ()
6975 (setq js2-current-flagged-token js2-EOF))
6976
6977 (defun js2-next-token ()
6978 (prog1
6979 (js2-peek-token)
6980 (js2-consume-token)))
6981
6982 (defun js2-next-flagged-token ()
6983 (js2-peek-token)
6984 (prog1 js2-current-flagged-token
6985 (js2-consume-token)))
6986
6987 (defun js2-match-token (match)
6988 "Consume and return t if next token matches MATCH, a bytecode.
6989 Returns nil and consumes nothing if MATCH is not the next token."
6990 (if (/= (js2-peek-token) match)
6991 nil
6992 (js2-consume-token)
6993 t))
6994
6995 (defun js2-match-contextual-kwd (name)
6996 "Consume and return t if next token is `js2-NAME', and its
6997 string is NAME. Returns nil and does nothing otherwise."
6998 (if (or (/= (js2-peek-token) js2-NAME)
6999 (not (string= js2-ts-string name)))
7000 nil
7001 (js2-consume-token)
7002 (js2-record-face 'font-lock-keyword-face)
7003 t))
7004
7005 (defun js2-valid-prop-name-token (tt)
7006 (or (= tt js2-NAME)
7007 (when (and js2-allow-keywords-as-property-names
7008 (plusp tt)
7009 (aref js2-kwd-tokens tt))
7010 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7011 t)))
7012
7013 (defun js2-match-prop-name ()
7014 "Consume token and return t if next token is a valid property name.
7015 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7016 is non-nil and it's a keyword token."
7017 (if (js2-valid-prop-name-token (js2-peek-token))
7018 (progn
7019 (js2-consume-token)
7020 t)
7021 nil))
7022
7023 (defun js2-must-match-prop-name (msg-id &optional pos len)
7024 (if (js2-match-prop-name)
7025 t
7026 (js2-report-error msg-id nil pos len)
7027 nil))
7028
7029 (defun js2-peek-token-or-eol ()
7030 "Return js2-EOL if the current token immediately follows a newline.
7031 Else returns the current token. Used in situations where we don't
7032 consider certain token types valid if they are preceded by a newline.
7033 One example is the postfix ++ or -- operator, which has to be on the
7034 same line as its operand."
7035 (let ((tt (js2-peek-token)))
7036 ;; Check for last peeked token flags
7037 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7038 js2-EOL
7039 tt)))
7040
7041 (defun js2-set-check-for-label ()
7042 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7043 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7044
7045 (defun js2-must-match (token msg-id &optional pos len)
7046 "Match next token to token code TOKEN, or record a syntax error.
7047 MSG-ID is the error message to report if the match fails.
7048 Returns t on match, nil if no match."
7049 (if (js2-match-token token)
7050 t
7051 (js2-report-error msg-id nil pos len)
7052 nil))
7053
7054 (defsubst js2-inside-function ()
7055 (plusp js2-nesting-of-function))
7056
7057 (defun js2-set-requires-activation ()
7058 (if (js2-function-node-p js2-current-script-or-fn)
7059 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7060
7061 (defun js2-check-activation-name (name token)
7062 (when (js2-inside-function)
7063 ;; skip language-version 1.2 check from Rhino
7064 (if (or (string= "arguments" name)
7065 (and js2-compiler-activation-names ; only used in codegen
7066 (gethash name js2-compiler-activation-names)))
7067 (js2-set-requires-activation))))
7068
7069 (defun js2-set-is-generator ()
7070 (if (js2-function-node-p js2-current-script-or-fn)
7071 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7072
7073 (defun js2-must-have-xml ()
7074 (unless js2-compiler-xml-available
7075 (js2-report-error "msg.XML.not.available")))
7076
7077 (defun js2-push-scope (scope)
7078 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7079 (assert (js2-scope-p scope))
7080 (assert (null (js2-scope-parent-scope scope)))
7081 (assert (not (eq js2-current-scope scope)))
7082 (setf (js2-scope-parent-scope scope) js2-current-scope
7083 js2-current-scope scope))
7084
7085 (defsubst js2-pop-scope ()
7086 (setq js2-current-scope
7087 (js2-scope-parent-scope js2-current-scope)))
7088
7089 (defun js2-enter-loop (loop-node)
7090 (push loop-node js2-loop-set)
7091 (push loop-node js2-loop-and-switch-set)
7092 (js2-push-scope loop-node)
7093 ;; Tell the current labeled statement (if any) its statement,
7094 ;; and set the jump target of the first label to the loop.
7095 ;; These are used in `js2-parse-continue' to verify that the
7096 ;; continue target is an actual labeled loop. (And for codegen.)
7097 (when js2-labeled-stmt
7098 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7099 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7100 js2-labeled-stmt))) loop-node)))
7101
7102 (defun js2-exit-loop ()
7103 (pop js2-loop-set)
7104 (pop js2-loop-and-switch-set)
7105 (js2-pop-scope))
7106
7107 (defsubst js2-enter-switch (switch-node)
7108 (push switch-node js2-loop-and-switch-set))
7109
7110 (defsubst js2-exit-switch ()
7111 (pop js2-loop-and-switch-set))
7112
7113 (defun js2-parse (&optional buf cb)
7114 "Tell the js2 parser to parse a region of JavaScript.
7115
7116 BUF is a buffer or buffer name containing the code to parse.
7117 Call `narrow-to-region' first to parse only part of the buffer.
7118
7119 The returned AST root node is given some additional properties:
7120 `node-count' - total number of nodes in the AST
7121 `buffer' - BUF. The buffer it refers to may change or be killed,
7122 so the value is not necessarily reliable.
7123
7124 An optional callback CB can be specified to report parsing
7125 progress. If `(functionp CB)' returns t, it will be called with
7126 the current line number once before parsing begins, then again
7127 each time the lexer reaches a new line number.
7128
7129 CB can also be a list of the form `(symbol cb ...)' to specify
7130 multiple callbacks with different criteria. Each symbol is a
7131 criterion keyword, and the following element is the callback to
7132 call
7133
7134 :line - called whenever the line number changes
7135 :token - called for each new token consumed
7136
7137 The list of criteria could be extended to include entering or
7138 leaving a statement, an expression, or a function definition."
7139 (if (and cb (not (functionp cb)))
7140 (error "criteria callbacks not yet implemented"))
7141 (let ((inhibit-point-motion-hooks t)
7142 (js2-compiler-xml-available (>= js2-language-version 160))
7143 ;; This is a recursive-descent parser, so give it a big stack.
7144 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7145 (max-specpdl-size (max max-specpdl-size 3000))
7146 (case-fold-search nil)
7147 ast)
7148 (message nil) ; clear any error message from previous parse
7149 (with-current-buffer (or buf (current-buffer))
7150 (setq js2-scanned-comments nil
7151 js2-parsed-errors nil
7152 js2-parsed-warnings nil
7153 js2-imenu-recorder nil
7154 js2-imenu-function-map nil
7155 js2-label-set nil)
7156 (js2-init-scanner)
7157 (setq ast (with-silent-modifications
7158 (js2-do-parse)))
7159 (unless js2-ts-hit-eof
7160 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7161 (setf (js2-ast-root-errors ast) js2-parsed-errors
7162 (js2-ast-root-warnings ast) js2-parsed-warnings)
7163 ;; if we didn't find any declarations, put a dummy in this list so we
7164 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7165 (unless js2-imenu-recorder
7166 (setq js2-imenu-recorder 'empty))
7167 (run-hooks 'js2-parse-finished-hook)
7168 ast)))
7169
7170 ;; Corresponds to Rhino's Parser.parse() method.
7171 (defun js2-do-parse ()
7172 "Parse current buffer starting from current point.
7173 Scanner should be initialized."
7174 (let ((pos js2-ts-cursor)
7175 (end js2-ts-cursor) ; in case file is empty
7176 root n tt)
7177 ;; initialize buffer-local parsing vars
7178 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7179 js2-current-script-or-fn root
7180 js2-current-scope root
7181 js2-current-flagged-token js2-EOF
7182 js2-nesting-of-function 0
7183 js2-labeled-stmt nil
7184 js2-recorded-identifiers nil) ; for js2-highlight
7185 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7186 (if (= tt js2-FUNCTION)
7187 (progn
7188 (js2-consume-token)
7189 (setq n (js2-parse-function (if js2-called-by-compile-function
7190 'FUNCTION_EXPRESSION
7191 'FUNCTION_STATEMENT))))
7192 ;; not a function - parse a statement
7193 (setq n (js2-parse-statement)))
7194 ;; add function or statement to script
7195 (setq end (js2-node-end n))
7196 (js2-block-node-push root n))
7197 ;; add comments to root in lexical order
7198 (when js2-scanned-comments
7199 ;; if we find a comment beyond end of normal kids, use its end
7200 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7201 (dolist (comment js2-scanned-comments)
7202 (push comment (js2-ast-root-comments root))
7203 (js2-node-add-children root comment)))
7204 (setf (js2-node-len root) (- end pos))
7205 ;; Give extensions a chance to muck with things before highlighting starts.
7206 (let ((js2-additional-externs js2-additional-externs))
7207 (save-excursion
7208 (dolist (callback js2-post-parse-callbacks)
7209 (funcall callback)))
7210 (js2-highlight-undeclared-vars))
7211 root))
7212
7213 (defun js2-function-parser ()
7214 (js2-consume-token)
7215 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7216
7217 (defun js2-parse-function-closure-body (fn-node)
7218 "Parse a JavaScript 1.8 function closure body."
7219 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7220 (if js2-ts-hit-eof
7221 (js2-report-error "msg.no.brace.body" nil
7222 (js2-node-pos fn-node)
7223 (- js2-ts-cursor (js2-node-pos fn-node)))
7224 (js2-node-add-children fn-node
7225 (setf (js2-function-node-body fn-node)
7226 (js2-parse-expr t))))))
7227
7228 (defun js2-parse-function-body (fn-node)
7229 (js2-must-match js2-LC "msg.no.brace.body"
7230 (js2-node-pos fn-node)
7231 (- js2-ts-cursor (js2-node-pos fn-node)))
7232 (let ((pos js2-token-beg) ; LC position
7233 (pn (make-js2-block-node)) ; starts at LC position
7234 tt
7235 end)
7236 (incf js2-nesting-of-function)
7237 (unwind-protect
7238 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7239 (= tt js2-EOF)
7240 (= tt js2-RC)))
7241 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7242 (js2-parse-statement)
7243 (js2-consume-token)
7244 (js2-parse-function 'FUNCTION_STATEMENT))))
7245 (decf js2-nesting-of-function))
7246 (setq end js2-token-end) ; assume no curly and leave at current token
7247 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7248 (setq end js2-token-end))
7249 (setf (js2-node-pos pn) pos
7250 (js2-node-len pn) (- end pos))
7251 (setf (js2-function-node-body fn-node) pn)
7252 (js2-node-add-children fn-node pn)
7253 pn))
7254
7255 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7256 "Declare and fontify destructuring parameters inside NODE.
7257 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7258 (cond
7259 ((js2-name-node-p node)
7260 (let (leftpos)
7261 (js2-define-symbol decl-type (js2-name-node-name node)
7262 node ignore-not-in-block)
7263 (when face
7264 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7265 (+ leftpos (js2-node-len node))
7266 face 'record))))
7267 ((js2-object-node-p node)
7268 (dolist (elem (js2-object-node-elems node))
7269 (js2-define-destruct-symbols
7270 (if (js2-object-prop-node-p elem)
7271 (js2-object-prop-node-right elem)
7272 ;; abbreviated destructuring {a, b}
7273 elem)
7274 decl-type face ignore-not-in-block)))
7275 ((js2-array-node-p node)
7276 (dolist (elem (js2-array-node-elems node))
7277 (when elem
7278 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7279 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7280 (js2-node-len node)))))
7281
7282 (defun js2-parse-function-params (fn-node pos)
7283 (if (js2-match-token js2-RP)
7284 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7285 (let (params len param default-found rest-param-at)
7286 (loop for tt = (js2-peek-token)
7287 do
7288 (cond
7289 ;; destructuring param
7290 ((or (= tt js2-LB) (= tt js2-LC))
7291 (when default-found
7292 (js2-report-error "msg.no.default.after.default.param"))
7293 (setq param (js2-parse-destruct-primary-expr))
7294 (js2-define-destruct-symbols param
7295 js2-LP
7296 'js2-function-param)
7297 (push param params))
7298 ;; variable name
7299 (t
7300 (when (and (>= js2-language-version 200)
7301 (js2-match-token js2-TRIPLEDOT)
7302 (not rest-param-at))
7303 ;; to report errors if there are more parameters
7304 (setq rest-param-at (length params)))
7305 (js2-must-match js2-NAME "msg.no.parm")
7306 (js2-record-face 'js2-function-param)
7307 (setq param (js2-create-name-node))
7308 (js2-define-symbol js2-LP js2-ts-string param)
7309 ;; default parameter value
7310 (when (or (and default-found
7311 (not rest-param-at)
7312 (js2-must-match js2-ASSIGN
7313 "msg.no.default.after.default.param"
7314 (js2-node-pos param)
7315 (js2-node-len param)))
7316 (and (>= js2-language-version 200)
7317 (js2-match-token js2-ASSIGN)))
7318 (let* ((pos (js2-node-pos param))
7319 (tt js2-current-token)
7320 (op-pos (- js2-token-beg pos))
7321 (left param)
7322 (right (js2-parse-assign-expr))
7323 (len (- (js2-node-end right) pos)))
7324 (setq param (make-js2-assign-node
7325 :type tt :pos pos :len len :op-pos op-pos
7326 :left left :right right)
7327 default-found t)
7328 (js2-node-add-children param left right)))
7329 (push param params)))
7330 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7331 (js2-report-error "msg.param.after.rest" nil
7332 (js2-node-pos param) (js2-node-len param)))
7333 while
7334 (js2-match-token js2-COMMA))
7335 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7336 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7337 (when rest-param-at
7338 (setf (js2-function-node-rest-p fn-node) t))
7339 (dolist (p params)
7340 (js2-node-add-children fn-node p)
7341 (push p (js2-function-node-params fn-node))))))
7342
7343 (defun js2-check-inconsistent-return-warning (fn-node name)
7344 "Possibly show inconsistent-return warning.
7345 Last token scanned is the close-curly for the function body."
7346 (when (and js2-mode-show-strict-warnings
7347 js2-strict-inconsistent-return-warning
7348 (not (js2-has-consistent-return-usage
7349 (js2-function-node-body fn-node))))
7350 ;; Have it extend from close-curly to bol or beginning of block.
7351 (let ((pos (save-excursion
7352 (goto-char js2-token-end)
7353 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7354 (point-at-bol))))
7355 (end js2-token-end))
7356 (if (plusp (js2-name-node-length name))
7357 (js2-add-strict-warning "msg.no.return.value"
7358 (js2-name-node-name name) pos end)
7359 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7360
7361 (defun js2-parse-function (function-type)
7362 "Function parser. FUNCTION-TYPE is a symbol."
7363 (let ((pos js2-token-beg) ; start of 'function' keyword
7364 name name-beg name-end fn-node lp
7365 (synthetic-type function-type)
7366 member-expr-node)
7367 ;; parse function name, expression, or non-name (anonymous)
7368 (cond
7369 ;; function foo(...)
7370 ((js2-match-token js2-NAME)
7371 (setq name (js2-create-name-node t)
7372 name-beg js2-token-beg
7373 name-end js2-token-end)
7374 (unless (js2-match-token js2-LP)
7375 (when js2-allow-member-expr-as-function-name
7376 ;; function foo.bar(...)
7377 (setq member-expr-node name
7378 name nil
7379 member-expr-node (js2-parse-member-expr-tail
7380 nil member-expr-node)))
7381 (js2-must-match js2-LP "msg.no.paren.parms")))
7382 ((js2-match-token js2-LP)
7383 nil) ; anonymous function: leave name as null
7384 (t
7385 ;; function random-member-expr(...)
7386 (when js2-allow-member-expr-as-function-name
7387 ;; Note that memberExpr can not start with '(' like
7388 ;; in function (1+2).toString(), because 'function (' already
7389 ;; processed as anonymous function
7390 (setq member-expr-node (js2-parse-member-expr)))
7391 (js2-must-match js2-LP "msg.no.paren.parms")))
7392 (if (= js2-current-token js2-LP) ; eventually matched LP?
7393 (setq lp js2-token-beg))
7394 (if member-expr-node
7395 (progn
7396 (setq synthetic-type 'FUNCTION_EXPRESSION)
7397 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7398 (if name
7399 (js2-set-face name-beg name-end
7400 'font-lock-function-name-face 'record)))
7401 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7402 (plusp (js2-name-node-length name)))
7403 ;; Function statements define a symbol in the enclosing scope
7404 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7405 (setf fn-node (make-js2-function-node :pos pos
7406 :name name
7407 :form function-type
7408 :lp (if lp (- lp pos))))
7409 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7410 ;; 1. Nested functions are not affected by the dynamic scope flag
7411 ;; as dynamic scope is already a parent of their scope.
7412 ;; 2. Functions defined under the with statement also immune to
7413 ;; this setup, in which case dynamic scope is ignored in favor
7414 ;; of the with object.
7415 (setf (js2-function-node-ignore-dynamic fn-node) t))
7416 ;; dynamically bind all the per-function variables
7417 (let ((js2-current-script-or-fn fn-node)
7418 (js2-current-scope fn-node)
7419 (js2-nesting-of-with 0)
7420 (js2-end-flags 0)
7421 js2-label-set
7422 js2-loop-set
7423 js2-loop-and-switch-set)
7424 (js2-parse-function-params fn-node pos)
7425 (if (and (>= js2-language-version 180)
7426 (/= (js2-peek-token) js2-LC))
7427 (js2-parse-function-closure-body fn-node)
7428 (js2-parse-function-body fn-node))
7429 (if name
7430 (js2-node-add-children fn-node name))
7431 (js2-check-inconsistent-return-warning fn-node name)
7432 ;; Function expressions define a name only in the body of the
7433 ;; function, and only if not hidden by a parameter name
7434 (if (and name
7435 (eq synthetic-type 'FUNCTION_EXPRESSION)
7436 (null (js2-scope-get-symbol js2-current-scope
7437 (js2-name-node-name name))))
7438 (js2-define-symbol js2-FUNCTION
7439 (js2-name-node-name name)
7440 fn-node))
7441 (if (and name
7442 (not (eq function-type 'FUNCTION_EXPRESSION)))
7443 (js2-record-imenu-functions fn-node)))
7444 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7445 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7446 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7447 ;; We wait until after parsing the function to set its parent scope,
7448 ;; since `js2-define-symbol' needs the defining-scope check to stop
7449 ;; at the function boundary when checking for redeclarations.
7450 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7451 fn-node))
7452
7453 (defun js2-parse-statements (&optional parent)
7454 "Parse a statement list. Last token consumed must be js2-LC.
7455
7456 PARENT can be a `js2-block-node', in which case the statements are
7457 appended to PARENT. Otherwise a new `js2-block-node' is created
7458 and returned.
7459
7460 This function does not match the closing js2-RC: the caller
7461 matches the RC so it can provide a suitable error message if not
7462 matched. This means it's up to the caller to set the length of
7463 the node to include the closing RC. The node start pos is set to
7464 the absolute buffer start position, and the caller should fix it
7465 up to be relative to the parent node. All children of this block
7466 node are given relative start positions and correct lengths."
7467 (let ((pn (or parent (make-js2-block-node)))
7468 tt)
7469 (setf (js2-node-pos pn) js2-token-beg)
7470 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7471 (/= tt js2-RC))
7472 (js2-block-node-push pn (js2-parse-statement)))
7473 pn))
7474
7475 (defun js2-parse-statement ()
7476 (let (tt pn beg end)
7477 ;; coarse-grained user-interrupt check - needs work
7478 (and js2-parse-interruptable-p
7479 (zerop (% (incf js2-parse-stmt-count)
7480 js2-statements-per-pause))
7481 (input-pending-p)
7482 (throw 'interrupted t))
7483 (setq pn (js2-statement-helper))
7484 ;; no-side-effects warning check
7485 (unless (js2-node-has-side-effects pn)
7486 (setq end (js2-node-end pn))
7487 (save-excursion
7488 (goto-char end)
7489 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7490 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7491 pn))
7492
7493 ;; These correspond to the switch cases in Parser.statementHelper
7494 (defconst js2-parsers
7495 (let ((parsers (make-vector js2-num-tokens
7496 #'js2-parse-expr-stmt)))
7497 (aset parsers js2-BREAK #'js2-parse-break)
7498 (aset parsers js2-CONST #'js2-parse-const-var)
7499 (aset parsers js2-CONTINUE #'js2-parse-continue)
7500 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7501 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7502 (aset parsers js2-DO #'js2-parse-do)
7503 (aset parsers js2-FOR #'js2-parse-for)
7504 (aset parsers js2-FUNCTION #'js2-function-parser)
7505 (aset parsers js2-IF #'js2-parse-if)
7506 (aset parsers js2-LC #'js2-parse-block)
7507 (aset parsers js2-LET #'js2-parse-let-stmt)
7508 (aset parsers js2-NAME #'js2-parse-name-or-label)
7509 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7510 (aset parsers js2-SEMI #'js2-parse-semi)
7511 (aset parsers js2-SWITCH #'js2-parse-switch)
7512 (aset parsers js2-THROW #'js2-parse-throw)
7513 (aset parsers js2-TRY #'js2-parse-try)
7514 (aset parsers js2-VAR #'js2-parse-const-var)
7515 (aset parsers js2-WHILE #'js2-parse-while)
7516 (aset parsers js2-WITH #'js2-parse-with)
7517 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7518 parsers)
7519 "A vector mapping token types to parser functions.")
7520
7521 (defun js2-parse-warn-missing-semi (beg end)
7522 (and js2-mode-show-strict-warnings
7523 js2-strict-missing-semi-warning
7524 (js2-add-strict-warning
7525 "msg.missing.semi" nil
7526 ;; back up to beginning of statement or line
7527 (max beg (save-excursion
7528 (goto-char end)
7529 (point-at-bol)))
7530 end)))
7531
7532 (defconst js2-no-semi-insertion
7533 (list js2-IF
7534 js2-SWITCH
7535 js2-WHILE
7536 js2-DO
7537 js2-FOR
7538 js2-TRY
7539 js2-WITH
7540 js2-LC
7541 js2-ERROR
7542 js2-SEMI
7543 js2-FUNCTION)
7544 "List of tokens that don't do automatic semicolon insertion.")
7545
7546 (defconst js2-autoinsert-semi-and-warn
7547 (list js2-ERROR js2-EOF js2-RC))
7548
7549 (defun js2-statement-helper ()
7550 (let* ((tt (js2-peek-token))
7551 (first-tt tt)
7552 (beg js2-token-beg)
7553 (parser (if (= tt js2-ERROR)
7554 #'js2-parse-semi
7555 (aref js2-parsers tt)))
7556 pn
7557 tt-flagged)
7558 ;; If the statement is set, then it's been told its label by now.
7559 (and js2-labeled-stmt
7560 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7561 (setq js2-labeled-stmt nil))
7562 (setq pn (funcall parser))
7563 ;; Don't do auto semi insertion for certain statement types.
7564 (unless (or (memq first-tt js2-no-semi-insertion)
7565 (js2-labeled-stmt-node-p pn))
7566 (js2-auto-insert-semicolon pn))
7567 pn))
7568
7569 (defun js2-auto-insert-semicolon (pn)
7570 (let* ((tt-flagged (js2-peek-flagged-token))
7571 (tt (logand tt-flagged js2-clear-ti-mask))
7572 (pos (js2-node-pos pn)))
7573 (cond
7574 ((= tt js2-SEMI)
7575 ;; Consume ';' as a part of expression
7576 (js2-consume-token)
7577 ;; extend the node bounds to include the semicolon.
7578 (setf (js2-node-len pn) (- js2-token-end pos)))
7579 ((memq tt js2-autoinsert-semi-and-warn)
7580 ;; Autoinsert ;
7581 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7582 (t
7583 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7584 ;; Report error if no EOL or autoinsert ';' otherwise
7585 (js2-report-error "msg.no.semi.stmt")
7586 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7587
7588 (defun js2-parse-condition ()
7589 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7590 The parens are discarded and the expression node is returned.
7591 The `pos' field of the return value is set to an absolute position
7592 that must be fixed up by the caller.
7593 Return value is a list (EXPR LP RP), with absolute paren positions."
7594 (let (pn lp rp)
7595 (if (js2-must-match js2-LP "msg.no.paren.cond")
7596 (setq lp js2-token-beg))
7597 (setq pn (js2-parse-expr))
7598 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7599 (setq rp js2-token-beg))
7600 ;; Report strict warning on code like "if (a = 7) ..."
7601 (if (and js2-strict-cond-assign-warning
7602 (js2-assign-node-p pn))
7603 (js2-add-strict-warning "msg.equal.as.assign" nil
7604 (js2-node-pos pn)
7605 (+ (js2-node-pos pn)
7606 (js2-node-len pn))))
7607 (list pn lp rp)))
7608
7609 (defun js2-parse-if ()
7610 "Parser for if-statement. Last matched token must be js2-IF."
7611 (let ((pos js2-token-beg)
7612 cond if-true if-false else-pos end pn)
7613 (js2-consume-token)
7614 (setq cond (js2-parse-condition)
7615 if-true (js2-parse-statement)
7616 if-false (if (js2-match-token js2-ELSE)
7617 (progn
7618 (setq else-pos (- js2-token-beg pos))
7619 (js2-parse-statement)))
7620 end (js2-node-end (or if-false if-true))
7621 pn (make-js2-if-node :pos pos
7622 :len (- end pos)
7623 :condition (car cond)
7624 :then-part if-true
7625 :else-part if-false
7626 :else-pos else-pos
7627 :lp (js2-relpos (second cond) pos)
7628 :rp (js2-relpos (third cond) pos)))
7629 (js2-node-add-children pn (car cond) if-true if-false)
7630 pn))
7631
7632 (defun js2-parse-switch ()
7633 "Parser for if-statement. Last matched token must be js2-SWITCH."
7634 (let ((pos js2-token-beg)
7635 tt pn discriminant has-default case-expr case-node
7636 case-pos cases stmt lp rp)
7637 (js2-consume-token)
7638 (if (js2-must-match js2-LP "msg.no.paren.switch")
7639 (setq lp js2-token-beg))
7640 (setq discriminant (js2-parse-expr)
7641 pn (make-js2-switch-node :discriminant discriminant
7642 :pos pos
7643 :lp (js2-relpos lp pos)))
7644 (js2-node-add-children pn discriminant)
7645 (js2-enter-switch pn)
7646 (unwind-protect
7647 (progn
7648 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7649 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7650 (js2-must-match js2-LC "msg.no.brace.switch")
7651 (catch 'break
7652 (while t
7653 (setq tt (js2-next-token)
7654 case-pos js2-token-beg)
7655 (cond
7656 ((= tt js2-RC)
7657 (setf (js2-node-len pn) (- js2-token-end pos))
7658 (throw 'break nil)) ; done
7659 ((= tt js2-CASE)
7660 (setq case-expr (js2-parse-expr))
7661 (js2-must-match js2-COLON "msg.no.colon.case"))
7662 ((= tt js2-DEFAULT)
7663 (if has-default
7664 (js2-report-error "msg.double.switch.default"))
7665 (setq has-default t
7666 case-expr nil)
7667 (js2-must-match js2-COLON "msg.no.colon.case"))
7668 (t
7669 (js2-report-error "msg.bad.switch")
7670 (throw 'break nil)))
7671 (setq case-node (make-js2-case-node :pos case-pos
7672 :len (- js2-token-end case-pos)
7673 :expr case-expr))
7674 (js2-node-add-children case-node case-expr)
7675 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7676 (/= tt js2-CASE)
7677 (/= tt js2-DEFAULT)
7678 (/= tt js2-EOF))
7679 (setf stmt (js2-parse-statement)
7680 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7681 (js2-block-node-push case-node stmt))
7682 (push case-node cases)))
7683 ;; add cases last, as pushing reverses the order to be correct
7684 (dolist (kid cases)
7685 (js2-node-add-children pn kid)
7686 (push kid (js2-switch-node-cases pn)))
7687 pn) ; return value
7688 (js2-exit-switch))))
7689
7690 (defun js2-parse-while ()
7691 "Parser for while-statement. Last matched token must be js2-WHILE."
7692 (let ((pos js2-token-beg)
7693 (pn (make-js2-while-node))
7694 cond body)
7695 (js2-consume-token)
7696 (js2-enter-loop pn)
7697 (unwind-protect
7698 (progn
7699 (setf cond (js2-parse-condition)
7700 (js2-while-node-condition pn) (car cond)
7701 body (js2-parse-statement)
7702 (js2-while-node-body pn) body
7703 (js2-node-len pn) (- (js2-node-end body) pos)
7704 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7705 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7706 (js2-node-add-children pn body (car cond)))
7707 (js2-exit-loop))
7708 pn))
7709
7710 (defun js2-parse-do ()
7711 "Parser for do-statement. Last matched token must be js2-DO."
7712 (let ((pos js2-token-beg)
7713 (pn (make-js2-do-node))
7714 cond body end)
7715 (js2-consume-token)
7716 (js2-enter-loop pn)
7717 (unwind-protect
7718 (progn
7719 (setq body (js2-parse-statement))
7720 (js2-must-match js2-WHILE "msg.no.while.do")
7721 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7722 cond (js2-parse-condition)
7723 (js2-do-node-condition pn) (car cond)
7724 (js2-do-node-body pn) body
7725 end js2-ts-cursor
7726 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7727 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7728 (js2-node-add-children pn (car cond) body))
7729 (js2-exit-loop))
7730 ;; Always auto-insert semicolon to follow SpiderMonkey:
7731 ;; It is required by ECMAScript but is ignored by the rest of
7732 ;; world; see bug 238945
7733 (if (js2-match-token js2-SEMI)
7734 (setq end js2-ts-cursor))
7735 (setf (js2-node-len pn) (- end pos))
7736 pn))
7737
7738 (defun js2-parse-for ()
7739 "Parser for for-statement. Last matched token must be js2-FOR.
7740 Parses for, for-in, and for each-in statements."
7741 (let ((for-pos js2-token-beg)
7742 pn is-for-each is-for-in-or-of is-for-of
7743 in-pos each-pos tmp-pos
7744 init ; Node init is also foo in 'foo in object'
7745 cond ; Node cond is also object in 'foo in object'
7746 incr ; 3rd section of for-loop initializer
7747 body tt lp rp)
7748 (js2-consume-token)
7749 ;; See if this is a for each () instead of just a for ()
7750 (when (js2-match-token js2-NAME)
7751 (if (string= "each" js2-ts-string)
7752 (progn
7753 (setq is-for-each t
7754 each-pos (- js2-token-beg for-pos)) ; relative
7755 (js2-record-face 'font-lock-keyword-face))
7756 (js2-report-error "msg.no.paren.for")))
7757 (if (js2-must-match js2-LP "msg.no.paren.for")
7758 (setq lp (- js2-token-beg for-pos)))
7759 (setq tt (js2-peek-token))
7760 ;; 'for' makes local scope
7761 (js2-push-scope (make-js2-scope))
7762 (unwind-protect
7763 ;; parse init clause
7764 (let ((js2-in-for-init t)) ; set as dynamic variable
7765 (cond
7766 ((= tt js2-SEMI)
7767 (setq init (make-js2-empty-expr-node)))
7768 ((or (= tt js2-VAR) (= tt js2-LET))
7769 (js2-consume-token)
7770 (setq init (js2-parse-variables tt js2-token-beg)))
7771 (t
7772 (setq init (js2-parse-expr)))))
7773 (if (or (js2-match-token js2-IN)
7774 (and (>= js2-language-version 200)
7775 (js2-match-contextual-kwd "of")
7776 (setq is-for-of t)))
7777 (setq is-for-in-or-of t
7778 in-pos (- js2-token-beg for-pos)
7779 ;; scope of iteration target object is not the scope we've created above.
7780 ;; stash current scope temporary.
7781 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7782 (js2-parse-expr))) ; object over which we're iterating
7783 ;; else ordinary for loop - parse cond and incr
7784 (js2-must-match js2-SEMI "msg.no.semi.for")
7785 (setq cond (if (= (js2-peek-token) js2-SEMI)
7786 (make-js2-empty-expr-node) ; no loop condition
7787 (js2-parse-expr)))
7788 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7789 (setq tmp-pos js2-token-end
7790 incr (if (= (js2-peek-token) js2-RP)
7791 (make-js2-empty-expr-node :pos tmp-pos)
7792 (js2-parse-expr))))
7793 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7794 (setq rp (- js2-token-beg for-pos)))
7795 (if (not is-for-in-or-of)
7796 (setq pn (make-js2-for-node :init init
7797 :condition cond
7798 :update incr
7799 :lp lp
7800 :rp rp))
7801 ;; cond could be null if 'in obj' got eaten by the init node.
7802 (if (js2-infix-node-p init)
7803 ;; it was (foo in bar) instead of (var foo in bar)
7804 (setq cond (js2-infix-node-right init)
7805 init (js2-infix-node-left init))
7806 (if (and (js2-var-decl-node-p init)
7807 (> (length (js2-var-decl-node-kids init)) 1))
7808 (js2-report-error "msg.mult.index")))
7809 (setq pn (make-js2-for-in-node :iterator init
7810 :object cond
7811 :in-pos in-pos
7812 :foreach-p is-for-each
7813 :each-pos each-pos
7814 :forof-p is-for-of
7815 :lp lp
7816 :rp rp)))
7817 (unwind-protect
7818 (progn
7819 (js2-enter-loop pn)
7820 ;; We have to parse the body -after- creating the loop node,
7821 ;; so that the loop node appears in the js2-loop-set, allowing
7822 ;; break/continue statements to find the enclosing loop.
7823 (setf body (js2-parse-statement)
7824 (js2-loop-node-body pn) body
7825 (js2-node-pos pn) for-pos
7826 (js2-node-len pn) (- (js2-node-end body) for-pos))
7827 (js2-node-add-children pn init cond incr body))
7828 ;; finally
7829 (js2-exit-loop))
7830 (js2-pop-scope))
7831 pn))
7832
7833 (defun js2-parse-try ()
7834 "Parser for try-statement. Last matched token must be js2-TRY."
7835 (let ((try-pos js2-token-beg)
7836 try-end
7837 try-block
7838 catch-blocks
7839 finally-block
7840 saw-default-catch
7841 peek
7842 param
7843 catch-cond
7844 catch-node
7845 guard-kwd
7846 catch-pos
7847 finally-pos
7848 pn
7849 block
7850 lp
7851 rp)
7852 (js2-consume-token)
7853 (if (/= (js2-peek-token) js2-LC)
7854 (js2-report-error "msg.no.brace.try"))
7855 (setq try-block (js2-parse-statement)
7856 try-end (js2-node-end try-block)
7857 peek (js2-peek-token))
7858 (cond
7859 ((= peek js2-CATCH)
7860 (while (js2-match-token js2-CATCH)
7861 (setq catch-pos js2-token-beg
7862 guard-kwd nil
7863 catch-cond nil
7864 lp nil
7865 rp nil)
7866 (if saw-default-catch
7867 (js2-report-error "msg.catch.unreachable"))
7868 (if (js2-must-match js2-LP "msg.no.paren.catch")
7869 (setq lp (- js2-token-beg catch-pos)))
7870 (js2-push-scope (make-js2-scope))
7871 (let ((tt (js2-peek-token)))
7872 (cond
7873 ;; destructuring pattern
7874 ;; catch ({ message, file }) { ... }
7875 ((or (= tt js2-LB) (= tt js2-LC))
7876 (setq param (js2-parse-destruct-primary-expr))
7877 (js2-define-destruct-symbols param js2-LET nil))
7878 ;; simple name
7879 (t
7880 (js2-must-match js2-NAME "msg.bad.catchcond")
7881 (setq param (js2-create-name-node))
7882 (js2-define-symbol js2-LET js2-ts-string param))))
7883 ;; pattern guard
7884 (if (js2-match-token js2-IF)
7885 (setq guard-kwd (- js2-token-beg catch-pos)
7886 catch-cond (js2-parse-expr))
7887 (setq saw-default-catch t))
7888 (if (js2-must-match js2-RP "msg.bad.catchcond")
7889 (setq rp (- js2-token-beg catch-pos)))
7890 (js2-must-match js2-LC "msg.no.brace.catchblock")
7891 (setq block (js2-parse-statements)
7892 try-end (js2-node-end block)
7893 catch-node (make-js2-catch-node :pos catch-pos
7894 :param param
7895 :guard-expr catch-cond
7896 :guard-kwd guard-kwd
7897 :block block
7898 :lp lp
7899 :rp rp))
7900 (js2-pop-scope)
7901 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7902 (setq try-end js2-token-beg))
7903 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7904 (js2-node-len catch-node) (- try-end catch-pos))
7905 (js2-node-add-children catch-node param catch-cond block)
7906 (push catch-node catch-blocks)))
7907 ((/= peek js2-FINALLY)
7908 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7909 (js2-node-pos try-block)
7910 (- (setq try-end (js2-node-end try-block))
7911 (js2-node-pos try-block)))))
7912 (when (js2-match-token js2-FINALLY)
7913 (setq finally-pos js2-token-beg
7914 block (js2-parse-statement)
7915 try-end (js2-node-end block)
7916 finally-block (make-js2-finally-node :pos finally-pos
7917 :len (- try-end finally-pos)
7918 :body block))
7919 (js2-node-add-children finally-block block))
7920 (setq pn (make-js2-try-node :pos try-pos
7921 :len (- try-end try-pos)
7922 :try-block try-block
7923 :finally-block finally-block))
7924 (js2-node-add-children pn try-block finally-block)
7925 ;; push them onto the try-node, which reverses and corrects their order
7926 (dolist (cb catch-blocks)
7927 (js2-node-add-children pn cb)
7928 (push cb (js2-try-node-catch-clauses pn)))
7929 pn))
7930
7931 (defun js2-parse-throw ()
7932 "Parser for throw-statement. Last matched token must be js2-THROW."
7933 (let ((pos js2-token-beg)
7934 expr pn)
7935 (js2-consume-token)
7936 (if (= (js2-peek-token-or-eol) js2-EOL)
7937 ;; ECMAScript does not allow new lines before throw expression,
7938 ;; see bug 256617
7939 (js2-report-error "msg.bad.throw.eol"))
7940 (setq expr (js2-parse-expr)
7941 pn (make-js2-throw-node :pos pos
7942 :len (- (js2-node-end expr) pos)
7943 :expr expr))
7944 (js2-node-add-children pn expr)
7945 pn))
7946
7947 (defun js2-match-jump-label-name (label-name)
7948 "If break/continue specified a label, return that label's labeled stmt.
7949 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7950 does not match an existing label, reports an error and returns nil."
7951 (let ((bundle (cdr (assoc label-name js2-label-set))))
7952 (if (null bundle)
7953 (js2-report-error "msg.undef.label"))
7954 bundle))
7955
7956 (defun js2-parse-break ()
7957 "Parser for break-statement. Last matched token must be js2-BREAK."
7958 (let ((pos js2-token-beg)
7959 (end js2-token-end)
7960 break-target ; statement to break from
7961 break-label ; in "break foo", name-node representing the foo
7962 labels ; matching labeled statement to break to
7963 pn)
7964 (js2-consume-token) ; `break'
7965 (when (eq (js2-peek-token-or-eol) js2-NAME)
7966 (js2-consume-token)
7967 (setq break-label (js2-create-name-node)
7968 end (js2-node-end break-label)
7969 ;; matchJumpLabelName only matches if there is one
7970 labels (js2-match-jump-label-name js2-ts-string)
7971 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7972 (unless (or break-target break-label)
7973 ;; no break target specified - try for innermost enclosing loop/switch
7974 (if (null js2-loop-and-switch-set)
7975 (unless break-label
7976 (js2-report-error "msg.bad.break" nil pos (length "break")))
7977 (setq break-target (car js2-loop-and-switch-set))))
7978 (setq pn (make-js2-break-node :pos pos
7979 :len (- end pos)
7980 :label break-label
7981 :target break-target))
7982 (js2-node-add-children pn break-label) ; but not break-target
7983 pn))
7984
7985 (defun js2-parse-continue ()
7986 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7987 (let ((pos js2-token-beg)
7988 (end js2-token-end)
7989 label ; optional user-specified label, a `js2-name-node'
7990 labels ; current matching labeled stmt, if any
7991 target ; the `js2-loop-node' target of this continue stmt
7992 pn)
7993 (js2-consume-token) ; `continue'
7994 (when (= (js2-peek-token-or-eol) js2-NAME)
7995 (js2-consume-token)
7996 (setq label (js2-create-name-node)
7997 end (js2-node-end label)
7998 ;; matchJumpLabelName only matches if there is one
7999 labels (js2-match-jump-label-name js2-ts-string)))
8000 (cond
8001 ((null labels) ; no current label to go to
8002 (if (null js2-loop-set) ; no loop to continue to
8003 (js2-report-error "msg.continue.outside" nil pos
8004 (length "continue"))
8005 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8006 (t
8007 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8008 (setq target (js2-labeled-stmt-node-stmt labels))
8009 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8010 (setq pn (make-js2-continue-node :pos pos
8011 :len (- end pos)
8012 :label label
8013 :target target))
8014 (js2-node-add-children pn label) ; but not target - it's not our child
8015 pn))
8016
8017 (defun js2-parse-with ()
8018 "Parser for with-statement. Last matched token must be js2-WITH."
8019 (js2-consume-token)
8020 (let ((pos js2-token-beg)
8021 obj body pn lp rp)
8022 (if (js2-must-match js2-LP "msg.no.paren.with")
8023 (setq lp js2-token-beg))
8024 (setq obj (js2-parse-expr))
8025 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8026 (setq rp js2-token-beg))
8027 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8028 (setq body (js2-parse-statement)))
8029 (setq pn (make-js2-with-node :pos pos
8030 :len (- (js2-node-end body) pos)
8031 :object obj
8032 :body body
8033 :lp (js2-relpos lp pos)
8034 :rp (js2-relpos rp pos)))
8035 (js2-node-add-children pn obj body)
8036 pn))
8037
8038 (defun js2-parse-const-var ()
8039 "Parser for var- or const-statement.
8040 Last matched token must be js2-CONST or js2-VAR."
8041 (let ((tt (js2-peek-token))
8042 (pos js2-token-beg)
8043 expr pn)
8044 (js2-consume-token)
8045 (setq expr (js2-parse-variables tt js2-token-beg)
8046 pn (make-js2-expr-stmt-node :pos pos
8047 :len (- (js2-node-end expr) pos)
8048 :expr expr))
8049 (js2-node-add-children pn expr)
8050 pn))
8051
8052 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8053 (let ((pn (make-js2-expr-stmt-node :pos pos
8054 :len (js2-node-len expr)
8055 :type (if (js2-inside-function)
8056 js2-EXPR_VOID
8057 js2-EXPR_RESULT)
8058 :expr expr)))
8059 (if add-child
8060 (js2-node-add-children pn expr))
8061 pn))
8062
8063 (defun js2-parse-let-stmt ()
8064 "Parser for let-statement. Last matched token must be js2-LET."
8065 (js2-consume-token)
8066 (let ((pos js2-token-beg)
8067 expr pn)
8068 (if (= (js2-peek-token) js2-LP)
8069 ;; let expression in statement context
8070 (setq expr (js2-parse-let pos 'statement)
8071 pn (js2-wrap-with-expr-stmt pos expr t))
8072 ;; else we're looking at a statement like let x=6, y=7;
8073 (setf expr (js2-parse-variables js2-LET pos)
8074 pn (js2-wrap-with-expr-stmt pos expr t)
8075 (js2-node-type pn) js2-EXPR_RESULT))
8076 pn))
8077
8078 (defun js2-parse-ret-yield ()
8079 (js2-parse-return-or-yield (js2-peek-token) nil))
8080
8081 (defconst js2-parse-return-stmt-enders
8082 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8083
8084 (defsubst js2-now-all-set (before after mask)
8085 "Return whether or not the bits in the mask have changed to all set.
8086 BEFORE is bits before change, AFTER is bits after change, and MASK is
8087 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8088 but not BEFORE."
8089 (and (/= (logand before mask) mask)
8090 (= (logand after mask) mask)))
8091
8092 (defun js2-parse-return-or-yield (tt expr-context)
8093 (let ((pos js2-token-beg)
8094 (end js2-token-end)
8095 (before js2-end-flags)
8096 (inside-function (js2-inside-function))
8097 e ret name)
8098 (unless inside-function
8099 (js2-report-error (if (eq tt js2-RETURN)
8100 "msg.bad.return"
8101 "msg.bad.yield")))
8102 (js2-consume-token)
8103 ;; This is ugly, but we don't want to require a semicolon.
8104 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8105 (setq e (js2-parse-expr)
8106 end (js2-node-end e)))
8107 (cond
8108 ((eq tt js2-RETURN)
8109 (js2-set-flag js2-end-flags (if (null e)
8110 js2-end-returns
8111 js2-end-returns-value))
8112 (setq ret (make-js2-return-node :pos pos
8113 :len (- end pos)
8114 :retval e))
8115 (js2-node-add-children ret e)
8116 ;; See if we need a strict mode warning.
8117 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8118 ;; more thorough and accurate than this before/after flag check.
8119 ;; E.g. if there's a finally-block that always returns, we shouldn't
8120 ;; show a warning generated by inconsistent returns in the catch blocks.
8121 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8122 ;; so we know which returns/yields to highlight, and we should get rid of
8123 ;; all the checking in `js2-parse-return-or-yield'.
8124 (if (and js2-strict-inconsistent-return-warning
8125 (js2-now-all-set before js2-end-flags
8126 (logior js2-end-returns js2-end-returns-value)))
8127 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8128 (t
8129 (unless (js2-inside-function)
8130 (js2-report-error "msg.bad.yield"))
8131 (js2-set-flag js2-end-flags js2-end-yields)
8132 (setq ret (make-js2-yield-node :pos pos
8133 :len (- end pos)
8134 :value e))
8135 (js2-node-add-children ret e)
8136 (unless expr-context
8137 (setq e ret
8138 ret (js2-wrap-with-expr-stmt pos e t))
8139 (js2-set-requires-activation)
8140 (js2-set-is-generator))))
8141 ;; see if we are mixing yields and value returns.
8142 (when (and inside-function
8143 (js2-now-all-set before js2-end-flags
8144 (logior js2-end-yields js2-end-returns-value)))
8145 (setq name (js2-function-name js2-current-script-or-fn))
8146 (if (zerop (length name))
8147 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8148 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8149 ret))
8150
8151 (defun js2-parse-debugger ()
8152 (js2-consume-token)
8153 (make-js2-keyword-node :type js2-DEBUGGER))
8154
8155 (defun js2-parse-block ()
8156 "Parser for a curly-delimited statement block.
8157 Last token matched must be `js2-LC'."
8158 (let ((pos js2-token-beg)
8159 (pn (make-js2-scope)))
8160 (js2-consume-token)
8161 (js2-push-scope pn)
8162 (unwind-protect
8163 (progn
8164 (js2-parse-statements pn)
8165 (js2-must-match js2-RC "msg.no.brace.block")
8166 (setf (js2-node-len pn) (- js2-token-end pos)))
8167 (js2-pop-scope))
8168 pn))
8169
8170 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8171 (defun js2-parse-semi ()
8172 "Parse a statement or handle an error.
8173 Last matched token is `js2-SEMI' or `js2-ERROR'."
8174 (let ((tt (js2-peek-token)) pos len)
8175 (js2-consume-token)
8176 (if (eq tt js2-SEMI)
8177 (make-js2-empty-expr-node :len 1)
8178 (setq pos js2-token-beg
8179 len (- js2-token-beg pos))
8180 (js2-report-error "msg.syntax" nil pos len)
8181 (make-js2-error-node :pos pos :len len))))
8182
8183 (defun js2-parse-default-xml-namespace ()
8184 "Parse a `default xml namespace = <expr>' e4x statement."
8185 (let ((pos js2-token-beg)
8186 end len expr unary es)
8187 (js2-consume-token)
8188 (js2-must-have-xml)
8189 (js2-set-requires-activation)
8190 (setq len (- js2-ts-cursor pos))
8191 (unless (and (js2-match-token js2-NAME)
8192 (string= js2-ts-string "xml"))
8193 (js2-report-error "msg.bad.namespace" nil pos len))
8194 (unless (and (js2-match-token js2-NAME)
8195 (string= js2-ts-string "namespace"))
8196 (js2-report-error "msg.bad.namespace" nil pos len))
8197 (unless (js2-match-token js2-ASSIGN)
8198 (js2-report-error "msg.bad.namespace" nil pos len))
8199 (setq expr (js2-parse-expr)
8200 end (js2-node-end expr)
8201 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8202 :pos pos
8203 :len (- end pos)
8204 :operand expr))
8205 (js2-node-add-children unary expr)
8206 (make-js2-expr-stmt-node :pos pos
8207 :len (- end pos)
8208 :expr unary)))
8209
8210 (defun js2-record-label (label bundle)
8211 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8212 (js2-consume-token)
8213 (let ((name (js2-label-node-name label))
8214 labeled-stmt
8215 dup)
8216 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8217 ;; flag both labels if possible when used in editing mode
8218 (if (and js2-parse-ide-mode
8219 (setq dup (js2-get-label-by-name labeled-stmt name)))
8220 (js2-report-error "msg.dup.label" nil
8221 (js2-node-abs-pos dup) (js2-node-len dup)))
8222 (js2-report-error "msg.dup.label" nil
8223 (js2-node-pos label) (js2-node-len label)))
8224 (js2-labeled-stmt-node-add-label bundle label)
8225 (js2-node-add-children bundle label)
8226 ;; Add one reference to the bundle per label in `js2-label-set'
8227 (push (cons name bundle) js2-label-set)))
8228
8229 (defun js2-parse-name-or-label ()
8230 "Parser for identifier or label. Last token matched must be js2-NAME.
8231 Called when we found a name in a statement context. If it's a label, we gather
8232 up any following labels and the next non-label statement into a
8233 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8234 expression and return it wrapped in a `js2-expr-stmt-node'."
8235 (let ((pos js2-token-beg)
8236 (end js2-token-end)
8237 expr stmt pn bundle
8238 (continue t))
8239 ;; set check for label and call down to `js2-parse-primary-expr'
8240 (js2-set-check-for-label)
8241 (setq expr (js2-parse-expr))
8242 (if (/= (js2-node-type expr) js2-LABEL)
8243 ;; Parsed non-label expression - wrap with expression stmt.
8244 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8245 ;; else parsed a label
8246 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8247 (js2-record-label expr bundle)
8248 ;; look for more labels
8249 (while (and continue (= (js2-peek-token) js2-NAME))
8250 (js2-set-check-for-label)
8251 (setq expr (js2-parse-expr))
8252 (if (/= (js2-node-type expr) js2-LABEL)
8253 (progn
8254 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8255 continue nil)
8256 (js2-auto-insert-semicolon stmt))
8257 (js2-record-label expr bundle)))
8258 ;; no more labels; now parse the labeled statement
8259 (unwind-protect
8260 (unless stmt
8261 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8262 (setq stmt (js2-statement-helper))))
8263 ;; remove the labels for this statement from the global set
8264 (dolist (label (js2-labeled-stmt-node-labels bundle))
8265 (setq js2-label-set (remove label js2-label-set))))
8266 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8267 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8268 (js2-node-add-children bundle stmt)
8269 bundle)))
8270
8271 (defun js2-parse-expr-stmt ()
8272 "Default parser in statement context, if no recognized statement found."
8273 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8274
8275 (defun js2-parse-variables (decl-type pos)
8276 "Parse a comma-separated list of variable declarations.
8277 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8278
8279 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8280 For 'var' or 'const', the keyword should be the token last scanned.
8281
8282 POS is the position where the node should start. It's sometimes the
8283 var/const/let keyword, and other times the beginning of the first token
8284 in the first variable declaration.
8285
8286 Returns the parsed `js2-var-decl-node' expression node."
8287 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8288 :pos pos))
8289 destructuring kid-pos tt init name end nbeg nend vi
8290 (continue t))
8291 ;; Example:
8292 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8293 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8294 ;; var {a, b} = baz;
8295 (while continue
8296 (setq destructuring nil
8297 name nil
8298 tt (js2-peek-token)
8299 kid-pos js2-token-beg
8300 end js2-token-end
8301 init nil)
8302 (if (or (= tt js2-LB) (= tt js2-LC))
8303 ;; Destructuring assignment, e.g., var [a, b] = ...
8304 (setq destructuring (js2-parse-destruct-primary-expr)
8305 end (js2-node-end destructuring))
8306 ;; Simple variable name
8307 (when (js2-must-match js2-NAME "msg.bad.var")
8308 (setq name (js2-create-name-node)
8309 nbeg js2-token-beg
8310 nend js2-token-end
8311 end nend)
8312 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8313 (when (js2-match-token js2-ASSIGN)
8314 (setq init (js2-parse-assign-expr)
8315 end (js2-node-end init))
8316 (js2-record-imenu-functions init name))
8317 (when name
8318 (js2-set-face nbeg nend (if (js2-function-node-p init)
8319 'font-lock-function-name-face
8320 'font-lock-variable-name-face)
8321 'record))
8322 (setq vi (make-js2-var-init-node :pos kid-pos
8323 :len (- end kid-pos)
8324 :type decl-type))
8325 (if destructuring
8326 (progn
8327 (if (and (null init) (not js2-in-for-init))
8328 (js2-report-error "msg.destruct.assign.no.init"))
8329 (js2-define-destruct-symbols destructuring
8330 decl-type
8331 'font-lock-variable-name-face)
8332 (setf (js2-var-init-node-target vi) destructuring))
8333 (setf (js2-var-init-node-target vi) name))
8334 (setf (js2-var-init-node-initializer vi) init)
8335 (js2-node-add-children vi name destructuring init)
8336 (js2-block-node-push result vi)
8337 (unless (js2-match-token js2-COMMA)
8338 (setq continue nil)))
8339 (setf (js2-node-len result) (- end pos))
8340 result))
8341
8342 (defun js2-parse-let (pos &optional stmt-p)
8343 "Parse a let expression or statement.
8344 A let-expression is of the form `let (vars) expr'.
8345 A let-statment is of the form `let (vars) {statements}'.
8346 The third form of let is a variable declaration list, handled
8347 by `js2-parse-variables'."
8348 (let ((pn (make-js2-let-node :pos pos))
8349 beg vars body)
8350 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8351 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8352 (js2-push-scope pn)
8353 (unwind-protect
8354 (progn
8355 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8356 (if (js2-must-match js2-RP "msg.no.paren.let")
8357 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8358 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8359 ;; let statement
8360 (progn
8361 (js2-consume-token)
8362 (setf beg js2-token-beg ; position stmt at LC
8363 body (js2-parse-statements))
8364 (js2-must-match js2-RC "msg.no.curly.let")
8365 (setf (js2-node-len body) (- js2-token-end beg)
8366 (js2-node-len pn) (- js2-token-end pos)
8367 (js2-let-node-body pn) body
8368 (js2-node-type pn) js2-LET))
8369 ;; let expression
8370 (setf body (js2-parse-expr)
8371 (js2-node-len pn) (- (js2-node-end body) pos)
8372 (js2-let-node-body pn) body))
8373 (js2-node-add-children pn vars body))
8374 (js2-pop-scope))
8375 pn))
8376
8377 (defun js2-define-new-symbol (decl-type name node &optional scope)
8378 (js2-scope-put-symbol (or scope js2-current-scope)
8379 name
8380 (make-js2-symbol decl-type name node)))
8381
8382 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8383 "Define a symbol in the current scope.
8384 If NODE is non-nil, it is the AST node associated with the symbol."
8385 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8386 (symbol (if defining-scope
8387 (js2-scope-get-symbol defining-scope name)))
8388 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8389 (cond
8390 ((and symbol ; already defined
8391 (or (= sdt js2-CONST) ; old version is const
8392 (= decl-type js2-CONST) ; new version is const
8393 ;; two let-bound vars in this block have same name
8394 (and (= sdt js2-LET)
8395 (eq defining-scope js2-current-scope))))
8396 (js2-report-error
8397 (cond
8398 ((= sdt js2-CONST) "msg.const.redecl")
8399 ((= sdt js2-LET) "msg.let.redecl")
8400 ((= sdt js2-VAR) "msg.var.redecl")
8401 ((= sdt js2-FUNCTION) "msg.function.redecl")
8402 (t "msg.parm.redecl"))
8403 name))
8404 ((= decl-type js2-LET)
8405 (if (and (not ignore-not-in-block)
8406 (or (= (js2-node-type js2-current-scope) js2-IF)
8407 (js2-loop-node-p js2-current-scope)))
8408 (js2-report-error "msg.let.decl.not.in.block")
8409 (js2-define-new-symbol decl-type name node)))
8410 ((or (= decl-type js2-VAR)
8411 (= decl-type js2-CONST)
8412 (= decl-type js2-FUNCTION))
8413 (if symbol
8414 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8415 (js2-add-strict-warning "msg.var.redecl" name)
8416 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8417 (js2-add-strict-warning "msg.var.hides.arg" name)))
8418 (js2-define-new-symbol decl-type name node
8419 js2-current-script-or-fn)))
8420 ((= decl-type js2-LP)
8421 (if symbol
8422 ;; must be duplicate parameter. Second parameter hides the
8423 ;; first, so go ahead and add the second pararameter
8424 (js2-report-warning "msg.dup.parms" name))
8425 (js2-define-new-symbol decl-type name node))
8426 (t (js2-code-bug)))))
8427
8428 (defun js2-parse-expr (&optional oneshot)
8429 (let* ((pn (js2-parse-assign-expr))
8430 (pos (js2-node-pos pn))
8431 left
8432 right
8433 op-pos)
8434 (while (and (not oneshot)
8435 (js2-match-token js2-COMMA))
8436 (setq op-pos (- js2-token-beg pos)) ; relative
8437 (if (= (js2-peek-token) js2-YIELD)
8438 (js2-report-error "msg.yield.parenthesized"))
8439 (setq right (js2-parse-assign-expr)
8440 left pn
8441 pn (make-js2-infix-node :type js2-COMMA
8442 :pos pos
8443 :len (- js2-ts-cursor pos)
8444 :op-pos op-pos
8445 :left left
8446 :right right))
8447 (js2-node-add-children pn left right))
8448 pn))
8449
8450 (defun js2-parse-assign-expr ()
8451 (let ((tt (js2-peek-token))
8452 (pos js2-token-beg)
8453 pn left right op-pos)
8454 (if (= tt js2-YIELD)
8455 (js2-parse-return-or-yield tt t)
8456 ;; not yield - parse assignment expression
8457 (setq pn (js2-parse-cond-expr)
8458 tt (js2-peek-token))
8459 (when (and (<= js2-first-assign tt)
8460 (<= tt js2-last-assign))
8461 ;; tt express assignment (=, |=, ^=, ..., %=)
8462 (js2-consume-token)
8463 (setq op-pos (- js2-token-beg pos) ; relative
8464 left pn
8465 right (js2-parse-assign-expr)
8466 pn (make-js2-assign-node :type tt
8467 :pos pos
8468 :len (- (js2-node-end right) pos)
8469 :op-pos op-pos
8470 :left left
8471 :right right))
8472 (when js2-parse-ide-mode
8473 (js2-highlight-assign-targets pn left right)
8474 (js2-record-imenu-functions right left))
8475 ;; do this last so ide checks above can use absolute positions
8476 (js2-node-add-children pn left right))
8477 pn)))
8478
8479 (defun js2-parse-cond-expr ()
8480 (let ((pos js2-token-beg)
8481 (pn (js2-parse-or-expr))
8482 test-expr
8483 if-true
8484 if-false
8485 q-pos
8486 c-pos)
8487 (when (js2-match-token js2-HOOK)
8488 (setq q-pos (- js2-token-beg pos)
8489 if-true (js2-parse-assign-expr))
8490 (js2-must-match js2-COLON "msg.no.colon.cond")
8491 (setq c-pos (- js2-token-beg pos)
8492 if-false (js2-parse-assign-expr)
8493 test-expr pn
8494 pn (make-js2-cond-node :pos pos
8495 :len (- (js2-node-end if-false) pos)
8496 :test-expr test-expr
8497 :true-expr if-true
8498 :false-expr if-false
8499 :q-pos q-pos
8500 :c-pos c-pos))
8501 (js2-node-add-children pn test-expr if-true if-false))
8502 pn))
8503
8504 (defun js2-make-binary (type left parser)
8505 "Helper for constructing a binary-operator AST node.
8506 LEFT is the left-side-expression, already parsed, and the
8507 binary operator should have just been matched.
8508 PARSER is a function to call to parse the right operand,
8509 or a `js2-node' struct if it has already been parsed."
8510 (let* ((pos (js2-node-pos left))
8511 (op-pos (- js2-token-beg pos))
8512 (right (if (js2-node-p parser)
8513 parser
8514 (funcall parser)))
8515 (pn (make-js2-infix-node :type type
8516 :pos pos
8517 :len (- (js2-node-end right) pos)
8518 :op-pos op-pos
8519 :left left
8520 :right right)))
8521 (js2-node-add-children pn left right)
8522 pn))
8523
8524 (defun js2-parse-or-expr ()
8525 (let ((pn (js2-parse-and-expr)))
8526 (when (js2-match-token js2-OR)
8527 (setq pn (js2-make-binary js2-OR
8528 pn
8529 'js2-parse-or-expr)))
8530 pn))
8531
8532 (defun js2-parse-and-expr ()
8533 (let ((pn (js2-parse-bit-or-expr)))
8534 (when (js2-match-token js2-AND)
8535 (setq pn (js2-make-binary js2-AND
8536 pn
8537 'js2-parse-and-expr)))
8538 pn))
8539
8540 (defun js2-parse-bit-or-expr ()
8541 (let ((pn (js2-parse-bit-xor-expr)))
8542 (while (js2-match-token js2-BITOR)
8543 (setq pn (js2-make-binary js2-BITOR
8544 pn
8545 'js2-parse-bit-xor-expr)))
8546 pn))
8547
8548 (defun js2-parse-bit-xor-expr ()
8549 (let ((pn (js2-parse-bit-and-expr)))
8550 (while (js2-match-token js2-BITXOR)
8551 (setq pn (js2-make-binary js2-BITXOR
8552 pn
8553 'js2-parse-bit-and-expr)))
8554 pn))
8555
8556 (defun js2-parse-bit-and-expr ()
8557 (let ((pn (js2-parse-eq-expr)))
8558 (while (js2-match-token js2-BITAND)
8559 (setq pn (js2-make-binary js2-BITAND
8560 pn
8561 'js2-parse-eq-expr)))
8562 pn))
8563
8564 (defconst js2-parse-eq-ops
8565 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8566
8567 (defun js2-parse-eq-expr ()
8568 (let ((pn (js2-parse-rel-expr))
8569 tt)
8570 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8571 (js2-consume-token)
8572 (setq pn (js2-make-binary tt
8573 pn
8574 'js2-parse-rel-expr)))
8575 pn))
8576
8577 (defconst js2-parse-rel-ops
8578 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8579
8580 (defun js2-parse-rel-expr ()
8581 (let ((pn (js2-parse-shift-expr))
8582 (continue t)
8583 tt)
8584 (while continue
8585 (setq tt (js2-peek-token))
8586 (cond
8587 ((and js2-in-for-init (= tt js2-IN))
8588 (setq continue nil))
8589 ((memq tt js2-parse-rel-ops)
8590 (js2-consume-token)
8591 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8592 (t
8593 (setq continue nil))))
8594 pn))
8595
8596 (defconst js2-parse-shift-ops
8597 (list js2-LSH js2-URSH js2-RSH))
8598
8599 (defun js2-parse-shift-expr ()
8600 (let ((pn (js2-parse-add-expr))
8601 tt
8602 (continue t))
8603 (while continue
8604 (setq tt (js2-peek-token))
8605 (if (memq tt js2-parse-shift-ops)
8606 (progn
8607 (js2-consume-token)
8608 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8609 (setq continue nil)))
8610 pn))
8611
8612 (defun js2-parse-add-expr ()
8613 (let ((pn (js2-parse-mul-expr))
8614 tt
8615 (continue t))
8616 (while continue
8617 (setq tt (js2-peek-token))
8618 (if (or (= tt js2-ADD) (= tt js2-SUB))
8619 (progn
8620 (js2-consume-token)
8621 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8622 (setq continue nil)))
8623 pn))
8624
8625 (defconst js2-parse-mul-ops
8626 (list js2-MUL js2-DIV js2-MOD))
8627
8628 (defun js2-parse-mul-expr ()
8629 (let ((pn (js2-parse-unary-expr))
8630 tt
8631 (continue t))
8632 (while continue
8633 (setq tt (js2-peek-token))
8634 (if (memq tt js2-parse-mul-ops)
8635 (progn
8636 (js2-consume-token)
8637 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8638 (setq continue nil)))
8639 pn))
8640
8641 (defun js2-make-unary (type parser &rest args)
8642 "Make a unary node of type TYPE.
8643 PARSER is either a node (for postfix operators) or a function to call
8644 to parse the operand (for prefix operators)."
8645 (let* ((pos js2-token-beg)
8646 (postfix (js2-node-p parser))
8647 (expr (if postfix
8648 parser
8649 (apply parser args)))
8650 end
8651 pn)
8652 (if postfix ; e.g. i++
8653 (setq pos (js2-node-pos expr)
8654 end js2-token-end)
8655 (setq end (js2-node-end expr)))
8656 (setq pn (make-js2-unary-node :type type
8657 :pos pos
8658 :len (- end pos)
8659 :operand expr))
8660 (js2-node-add-children pn expr)
8661 pn))
8662
8663 (defconst js2-incrementable-node-types
8664 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8665 "Node types that can be the operand of a ++ or -- operator.")
8666
8667 (defun js2-check-bad-inc-dec (tt beg end unary)
8668 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8669 js2-incrementable-node-types)
8670 (js2-report-error (if (= tt js2-INC)
8671 "msg.bad.incr"
8672 "msg.bad.decr")
8673 nil beg (- end beg))))
8674
8675 (defun js2-parse-unary-expr ()
8676 (let ((tt (js2-peek-token))
8677 pn expr beg end)
8678 (cond
8679 ((or (= tt js2-VOID)
8680 (= tt js2-NOT)
8681 (= tt js2-BITNOT)
8682 (= tt js2-TYPEOF))
8683 (js2-consume-token)
8684 (js2-make-unary tt 'js2-parse-unary-expr))
8685 ((= tt js2-ADD)
8686 (js2-consume-token)
8687 ;; Convert to special POS token in decompiler and parse tree
8688 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8689 ((= tt js2-SUB)
8690 (js2-consume-token)
8691 ;; Convert to special NEG token in decompiler and parse tree
8692 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8693 ((or (= tt js2-INC)
8694 (= tt js2-DEC))
8695 (js2-consume-token)
8696 (prog1
8697 (setq beg js2-token-beg
8698 end js2-token-end
8699 expr (js2-make-unary tt 'js2-parse-member-expr t))
8700 (js2-check-bad-inc-dec tt beg end expr)))
8701 ((= tt js2-DELPROP)
8702 (js2-consume-token)
8703 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8704 ((= tt js2-ERROR)
8705 (js2-consume-token)
8706 (make-js2-error-node)) ; try to continue
8707 ((and (= tt js2-LT)
8708 js2-compiler-xml-available)
8709 ;; XML stream encountered in expression.
8710 (js2-consume-token)
8711 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8712 (t
8713 (setq pn (js2-parse-member-expr t)
8714 ;; Don't look across a newline boundary for a postfix incop.
8715 tt (js2-peek-token-or-eol))
8716 (when (or (= tt js2-INC) (= tt js2-DEC))
8717 (js2-consume-token)
8718 (setf expr pn
8719 pn (js2-make-unary tt expr))
8720 (js2-node-set-prop pn 'postfix t)
8721 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8722 pn))))
8723
8724 (defun js2-parse-xml-initializer ()
8725 "Parse an E4X XML initializer.
8726 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8727 Then I'll postprocess the result, depending on whether we're in IDE
8728 mode or codegen mode, and generate the appropriate rewritten AST.
8729 IDE mode uses a rich AST that models the XML structure. Codegen mode
8730 just concatenates everything and makes a new XML or XMLList out of it."
8731 (let ((tt (js2-get-first-xml-token))
8732 pn-xml pn expr kids expr-pos
8733 (continue t)
8734 (first-token t))
8735 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8736 (js2-report-error "msg.syntax"))
8737 (setq pn-xml (make-js2-xml-node))
8738 (while continue
8739 (if first-token
8740 (setq first-token nil)
8741 (setq tt (js2-get-next-xml-token)))
8742 (cond
8743 ;; js2-XML means we found a {expr} in the XML stream.
8744 ;; The js2-ts-string is the XML up to the left-curly.
8745 ((= tt js2-XML)
8746 (push (make-js2-string-node :pos js2-token-beg
8747 :len (- js2-ts-cursor js2-token-beg))
8748 kids)
8749 (js2-must-match js2-LC "msg.syntax")
8750 (setq expr-pos js2-ts-cursor
8751 expr (if (eq (js2-peek-token) js2-RC)
8752 (make-js2-empty-expr-node :pos expr-pos)
8753 (js2-parse-expr)))
8754 (js2-must-match js2-RC "msg.syntax")
8755 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8756 :len (js2-node-len expr)
8757 :expr expr))
8758 (js2-node-add-children pn expr)
8759 (push pn kids))
8760 ;; a js2-XMLEND token means we hit the final close-tag.
8761 ((= tt js2-XMLEND)
8762 (push (make-js2-string-node :pos js2-token-beg
8763 :len (- js2-ts-cursor js2-token-beg))
8764 kids)
8765 (dolist (kid (nreverse kids))
8766 (js2-block-node-push pn-xml kid))
8767 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8768 (js2-node-pos pn-xml))
8769 continue nil))
8770 (t
8771 (js2-report-error "msg.syntax")
8772 (setq continue nil))))
8773 pn-xml))
8774
8775
8776 (defun js2-parse-argument-list ()
8777 "Parse an argument list and return it as a Lisp list of nodes.
8778 Returns the list in reverse order. Consumes the right-paren token."
8779 (let (result)
8780 (unless (js2-match-token js2-RP)
8781 (loop do
8782 (if (= (js2-peek-token) js2-YIELD)
8783 (js2-report-error "msg.yield.parenthesized"))
8784 (push (js2-parse-assign-expr) result)
8785 while
8786 (js2-match-token js2-COMMA))
8787 (js2-must-match js2-RP "msg.no.paren.arg")
8788 result)))
8789
8790 (defun js2-parse-member-expr (&optional allow-call-syntax)
8791 (let ((tt (js2-peek-token))
8792 pn pos target args beg end init tail)
8793 (if (/= tt js2-NEW)
8794 (setq pn (js2-parse-primary-expr))
8795 ;; parse a 'new' expression
8796 (js2-consume-token)
8797 (setq pos js2-token-beg
8798 beg pos
8799 target (js2-parse-member-expr)
8800 end (js2-node-end target)
8801 pn (make-js2-new-node :pos pos
8802 :target target
8803 :len (- end pos)))
8804 (js2-node-add-children pn target)
8805 (when (js2-match-token js2-LP)
8806 ;; Add the arguments to pn, if any are supplied.
8807 (setf beg pos ; start of "new" keyword
8808 pos js2-token-beg
8809 args (nreverse (js2-parse-argument-list))
8810 (js2-new-node-args pn) args
8811 end js2-token-end
8812 (js2-new-node-lp pn) (- pos beg)
8813 (js2-new-node-rp pn) (- end 1 beg))
8814 (apply #'js2-node-add-children pn args))
8815 (when (and js2-allow-rhino-new-expr-initializer
8816 (js2-match-token js2-LC))
8817 (setf init (js2-parse-object-literal)
8818 end (js2-node-end init)
8819 (js2-new-node-initializer pn) init)
8820 (js2-node-add-children pn init))
8821 (setf (js2-node-len pn) (- end beg))) ; end outer if
8822 (js2-parse-member-expr-tail allow-call-syntax pn)))
8823
8824 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8825 "Parse a chain of property/array accesses or function calls.
8826 Includes parsing for E4X operators like `..' and `.@'.
8827 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8828 Returns an expression tree that includes PN, the parent node."
8829 (let ((beg (js2-node-pos pn))
8830 tt
8831 (continue t))
8832 (while continue
8833 (setq tt (js2-peek-token))
8834 (cond
8835 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8836 (setq pn (js2-parse-property-access tt pn)))
8837 ((= tt js2-DOTQUERY)
8838 (setq pn (js2-parse-dot-query pn)))
8839 ((= tt js2-LB)
8840 (setq pn (js2-parse-element-get pn)))
8841 ((= tt js2-LP)
8842 (if allow-call-syntax
8843 (setq pn (js2-parse-function-call pn))
8844 (setq continue nil)))
8845 (t
8846 (setq continue nil))))
8847 (if (>= js2-highlight-level 2)
8848 (js2-parse-highlight-member-expr-node pn))
8849 pn))
8850
8851 (defun js2-parse-dot-query (pn)
8852 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8853 Last token parsed must be `js2-DOTQUERY'."
8854 (let ((pos (js2-node-pos pn))
8855 op-pos expr end)
8856 (js2-consume-token)
8857 (js2-must-have-xml)
8858 (js2-set-requires-activation)
8859 (setq op-pos js2-token-beg
8860 expr (js2-parse-expr)
8861 end (js2-node-end expr)
8862 pn (make-js2-xml-dot-query-node :left pn
8863 :pos pos
8864 :op-pos op-pos
8865 :right expr))
8866 (js2-node-add-children pn
8867 (js2-xml-dot-query-node-left pn)
8868 (js2-xml-dot-query-node-right pn))
8869 (if (js2-must-match js2-RP "msg.no.paren")
8870 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8871 end js2-token-end))
8872 (setf (js2-node-len pn) (- end pos))
8873 pn))
8874
8875 (defun js2-parse-element-get (pn)
8876 "Parse an element-get expression, e.g. foo[bar].
8877 Last token parsed must be `js2-RB'."
8878 (let ((lb js2-token-beg)
8879 (pos (js2-node-pos pn))
8880 rb expr)
8881 (js2-consume-token)
8882 (setq expr (js2-parse-expr))
8883 (if (js2-must-match js2-RB "msg.no.bracket.index")
8884 (setq rb js2-token-beg))
8885 (setq pn (make-js2-elem-get-node :target pn
8886 :pos pos
8887 :element expr
8888 :lb (js2-relpos lb pos)
8889 :rb (js2-relpos rb pos)
8890 :len (- js2-token-end pos)))
8891 (js2-node-add-children pn
8892 (js2-elem-get-node-target pn)
8893 (js2-elem-get-node-element pn))
8894 pn))
8895
8896 (defun js2-parse-function-call (pn)
8897 (let (args
8898 (pos (js2-node-pos pn)))
8899 (js2-consume-token)
8900 (setq pn (make-js2-call-node :pos pos
8901 :target pn
8902 :lp (- js2-token-beg pos)))
8903 (js2-node-add-children pn (js2-call-node-target pn))
8904 ;; Add the arguments to pn, if any are supplied.
8905 (setf args (nreverse (js2-parse-argument-list))
8906 (js2-call-node-rp pn) (- js2-token-beg pos)
8907 (js2-call-node-args pn) args)
8908 (apply #'js2-node-add-children pn args)
8909 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8910 pn))
8911
8912 (defun js2-parse-property-access (tt pn)
8913 "Parse a property access, XML descendants access, or XML attr access."
8914 (let ((member-type-flags 0)
8915 (dot-pos js2-token-beg)
8916 (dot-len (if (= tt js2-DOTDOT) 2 1))
8917 name
8918 ref ; right side of . or .. operator
8919 result)
8920 (js2-consume-token)
8921 (when (= tt js2-DOTDOT)
8922 (js2-must-have-xml)
8923 (setq member-type-flags js2-descendants-flag))
8924 (if (not js2-compiler-xml-available)
8925 (progn
8926 (js2-must-match-prop-name "msg.no.name.after.dot")
8927 (setq name (js2-create-name-node t js2-GETPROP)
8928 result (make-js2-prop-get-node :left pn
8929 :pos js2-token-beg
8930 :right name
8931 :len (- js2-token-end
8932 js2-token-beg)))
8933 (js2-node-add-children result pn name)
8934 result)
8935 ;; otherwise look for XML operators
8936 (setf result (if (= tt js2-DOT)
8937 (make-js2-prop-get-node)
8938 (make-js2-infix-node :type js2-DOTDOT))
8939 (js2-node-pos result) (js2-node-pos pn)
8940 (js2-infix-node-op-pos result) dot-pos
8941 (js2-infix-node-left result) pn ; do this after setting position
8942 tt (js2-next-token))
8943 (cond
8944 ;; needed for generator.throw()
8945 ((= tt js2-THROW)
8946 (js2-save-name-token-data js2-token-beg "throw")
8947 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8948 ;; handles: name, ns::name, ns::*, ns::[expr]
8949 ((js2-valid-prop-name-token tt)
8950 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8951 ;; handles: *, *::name, *::*, *::[expr]
8952 ((= tt js2-MUL)
8953 (js2-save-name-token-data js2-token-beg "*")
8954 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8955 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8956 ((= tt js2-XMLATTR)
8957 (setq result (js2-parse-attribute-access)))
8958 (t
8959 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8960 (if ref
8961 (setf (js2-node-len result) (- (js2-node-end ref)
8962 (js2-node-pos result))
8963 (js2-infix-node-right result) ref))
8964 (if (js2-infix-node-p result)
8965 (js2-node-add-children result
8966 (js2-infix-node-left result)
8967 (js2-infix-node-right result)))
8968 result)))
8969
8970 (defun js2-parse-attribute-access ()
8971 "Parse an E4X XML attribute expression.
8972 This includes expressions of the forms:
8973
8974 @attr @ns::attr @ns::*
8975 @* @*::attr @*::*
8976 @[expr] @*::[expr] @ns::[expr]
8977
8978 Called if we peeked an '@' token."
8979 (let ((tt (js2-next-token))
8980 (at-pos js2-token-beg))
8981 (cond
8982 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8983 ((js2-valid-prop-name-token tt)
8984 (js2-parse-property-name at-pos js2-ts-string 0))
8985 ;; handles: @*, @*::name, @*::*, @*::[expr]
8986 ((= tt js2-MUL)
8987 (js2-save-name-token-data js2-token-beg "*")
8988 (js2-parse-property-name js2-token-beg "*" 0))
8989 ;; handles @[expr]
8990 ((= tt js2-LB)
8991 (js2-parse-xml-elem-ref at-pos))
8992 (t
8993 (js2-report-error "msg.no.name.after.xmlAttr")
8994 ;; Avoid cascaded errors that happen if we make an error node here.
8995 (js2-save-name-token-data js2-token-beg "")
8996 (js2-parse-property-name js2-token-beg "" 0)))))
8997
8998 (defun js2-parse-property-name (at-pos s member-type-flags)
8999 "Check if :: follows name in which case it becomes qualified name.
9000
9001 AT-POS is a natural number if we just read an '@' token, else nil.
9002 S is the name or string that was matched: an identifier, 'throw' or '*'.
9003 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9004
9005 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9006 operator, or the name is followed by ::. For a plain name, returns a
9007 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9008 (let ((pos (or at-pos js2-token-beg))
9009 colon-pos
9010 (name (js2-create-name-node t js2-current-token))
9011 ns tt ref pn)
9012 (catch 'return
9013 (when (js2-match-token js2-COLONCOLON)
9014 (setq ns name
9015 colon-pos js2-token-beg
9016 tt (js2-next-token))
9017 (cond
9018 ;; handles name::name
9019 ((js2-valid-prop-name-token tt)
9020 (setq name (js2-create-name-node)))
9021 ;; handles name::*
9022 ((= tt js2-MUL)
9023 (js2-save-name-token-data js2-token-beg "*")
9024 (setq name (js2-create-name-node)))
9025 ;; handles name::[expr]
9026 ((= tt js2-LB)
9027 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9028 (t
9029 (js2-report-error "msg.no.name.after.coloncolon"))))
9030 (if (and (null ns) (zerop member-type-flags))
9031 name
9032 (prog1
9033 (setq pn
9034 (make-js2-xml-prop-ref-node :pos pos
9035 :len (- (js2-node-end name) pos)
9036 :at-pos at-pos
9037 :colon-pos colon-pos
9038 :propname name))
9039 (js2-node-add-children pn name))))))
9040
9041 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9042 "Parse the [expr] portion of an xml element reference.
9043 For instance, @[expr], @*::[expr], or ns::[expr]."
9044 (let* ((lb js2-token-beg)
9045 (pos (or at-pos lb))
9046 rb
9047 (expr (js2-parse-expr))
9048 (end (js2-node-end expr))
9049 pn)
9050 (if (js2-must-match js2-RB "msg.no.bracket.index")
9051 (setq rb js2-token-beg
9052 end js2-token-end))
9053 (prog1
9054 (setq pn
9055 (make-js2-xml-elem-ref-node :pos pos
9056 :len (- end pos)
9057 :namespace namespace
9058 :colon-pos colon-pos
9059 :at-pos at-pos
9060 :expr expr
9061 :lb (js2-relpos lb pos)
9062 :rb (js2-relpos rb pos)))
9063 (js2-node-add-children pn namespace expr))))
9064
9065 (defun js2-parse-destruct-primary-expr ()
9066 (let ((js2-is-in-destructuring t))
9067 (js2-parse-primary-expr)))
9068
9069 (defun js2-parse-primary-expr ()
9070 "Parse a literal (leaf) expression of some sort.
9071 Includes complex literals such as functions, object-literals,
9072 array-literals, array comprehensions and regular expressions."
9073 (let ((tt-flagged (js2-next-flagged-token))
9074 pn ; parent node (usually return value)
9075 tt
9076 px-pos ; paren-expr pos
9077 len
9078 flags ; regexp flags
9079 expr)
9080 (setq tt js2-current-token)
9081 (cond
9082 ((= tt js2-FUNCTION)
9083 (js2-parse-function 'FUNCTION_EXPRESSION))
9084 ((= tt js2-LB)
9085 (js2-parse-array-literal))
9086 ((= tt js2-LC)
9087 (js2-parse-object-literal))
9088 ((= tt js2-LET)
9089 (js2-parse-let js2-token-beg))
9090 ((= tt js2-LP)
9091 (setq px-pos js2-token-beg
9092 expr (js2-parse-expr))
9093 (js2-must-match js2-RP "msg.no.paren")
9094 (setq pn (make-js2-paren-node :pos px-pos
9095 :expr expr
9096 :len (- js2-token-end px-pos)))
9097 (js2-node-add-children pn (js2-paren-node-expr pn))
9098 pn)
9099 ((= tt js2-XMLATTR)
9100 (js2-must-have-xml)
9101 (js2-parse-attribute-access))
9102 ((= tt js2-NAME)
9103 (js2-parse-name tt-flagged tt))
9104 ((= tt js2-NUMBER)
9105 (make-js2-number-node))
9106 ((= tt js2-STRING)
9107 (prog1
9108 (make-js2-string-node)
9109 (js2-record-face 'font-lock-string-face)))
9110 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9111 ;; Got / or /= which in this context means a regexp literal
9112 (setq px-pos js2-token-beg)
9113 (js2-read-regexp tt)
9114 (setq flags js2-ts-regexp-flags
9115 js2-ts-regexp-flags nil)
9116 (prog1
9117 (make-js2-regexp-node :pos px-pos
9118 :len (- js2-ts-cursor px-pos)
9119 :value js2-ts-string
9120 :flags flags)
9121 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9122 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9123 ((or (= tt js2-NULL)
9124 (= tt js2-THIS)
9125 (= tt js2-FALSE)
9126 (= tt js2-TRUE))
9127 (make-js2-keyword-node :type tt))
9128 ((= tt js2-RESERVED)
9129 (js2-report-error "msg.reserved.id")
9130 (make-js2-name-node))
9131 ((= tt js2-ERROR)
9132 ;; the scanner or one of its subroutines reported the error.
9133 (make-js2-error-node))
9134 ((= tt js2-EOF)
9135 (setq px-pos (point-at-bol)
9136 len (- js2-ts-cursor px-pos))
9137 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9138 (make-js2-error-node :pos px-pos :len len))
9139 (t
9140 (js2-report-error "msg.syntax")
9141 (make-js2-error-node)))))
9142
9143 (defun js2-parse-name (tt-flagged tt)
9144 (let ((name js2-ts-string)
9145 (name-pos js2-token-beg)
9146 node)
9147 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9148 (= (js2-peek-token) js2-COLON))
9149 (prog1
9150 ;; Do not consume colon, it is used as unwind indicator
9151 ;; to return to statementHelper.
9152 (make-js2-label-node :pos name-pos
9153 :len (- js2-token-end name-pos)
9154 :name name)
9155 (js2-set-face name-pos
9156 js2-token-end
9157 'font-lock-variable-name-face 'record))
9158 ;; Otherwise not a label, just a name. Unfortunately peeking
9159 ;; the next token to check for a colon has biffed js2-token-beg
9160 ;; and js2-token-end. We store the name's bounds in buffer vars
9161 ;; and `js2-create-name-node' uses them.
9162 (js2-save-name-token-data name-pos name)
9163 (setq node (if js2-compiler-xml-available
9164 (js2-parse-property-name nil name 0)
9165 (js2-create-name-node 'check-activation)))
9166 (if js2-highlight-external-variables
9167 (js2-record-name-node node))
9168 node)))
9169
9170 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9171 (js2-add-strict-warning
9172 msg nil
9173 ;; back up from comma to beginning of line or array/objlit
9174 (max (if elems
9175 (js2-node-pos (car elems))
9176 pos)
9177 (save-excursion
9178 (goto-char comma-pos)
9179 (back-to-indentation)
9180 (point)))
9181 comma-pos))
9182
9183 (defun js2-parse-array-literal ()
9184 (let ((pos js2-token-beg)
9185 (end js2-token-end)
9186 (after-lb-or-comma t)
9187 after-comma tt elems pn
9188 (continue t))
9189 (unless js2-is-in-destructuring
9190 (js2-push-scope (make-js2-scope))) ; for array comp
9191 (while continue
9192 (setq tt (js2-peek-token))
9193 (cond
9194 ;; comma
9195 ((= tt js2-COMMA)
9196 (js2-consume-token)
9197 (setq after-comma js2-token-end)
9198 (if (not after-lb-or-comma)
9199 (setq after-lb-or-comma t)
9200 (push nil elems)))
9201 ;; end of array
9202 ((or (= tt js2-RB)
9203 (= tt js2-EOF)) ; prevent infinite loop
9204 (if (= tt js2-EOF)
9205 (js2-report-error "msg.no.bracket.arg" nil pos)
9206 (js2-consume-token))
9207 (setq continue nil
9208 end js2-token-end
9209 pn (make-js2-array-node :pos pos
9210 :len (- js2-ts-cursor pos)
9211 :elems (nreverse elems)))
9212 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9213 (when (and after-comma (not js2-is-in-destructuring))
9214 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9215 pos elems after-comma)))
9216 ;; destructuring binding
9217 (js2-is-in-destructuring
9218 (push (if (or (= tt js2-LC)
9219 (= tt js2-LB)
9220 (= tt js2-NAME))
9221 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9222 (js2-parse-destruct-primary-expr)
9223 ;; invalid pattern
9224 (js2-consume-token)
9225 (js2-report-error "msg.bad.var")
9226 (make-js2-error-node))
9227 elems)
9228 (setq after-lb-or-comma nil
9229 after-comma nil))
9230 ;; array comp
9231 ((and (>= js2-language-version 170)
9232 (= tt js2-FOR) ; check for array comprehension
9233 (not after-lb-or-comma) ; "for" can't follow a comma
9234 elems ; must have at least 1 element
9235 (not (cdr elems))) ; but no 2nd element
9236 (setf continue nil
9237 pn (js2-parse-array-comprehension (car elems) pos)))
9238
9239 ;; another element
9240 (t
9241 (unless after-lb-or-comma
9242 (js2-report-error "msg.no.bracket.arg"))
9243 (push (js2-parse-assign-expr) elems)
9244 (setq after-lb-or-comma nil
9245 after-comma nil))))
9246 (unless js2-is-in-destructuring
9247 (js2-pop-scope))
9248 pn))
9249
9250 (defun js2-parse-array-comprehension (expr pos)
9251 "Parse a JavaScript 1.7 Array Comprehension.
9252 EXPR is the first expression after the opening left-bracket.
9253 POS is the beginning of the LB token preceding EXPR.
9254 We should have just parsed the 'for' keyword before calling this function."
9255 (let (loops loop first prev filter if-pos result)
9256 (while (= (js2-peek-token) js2-FOR)
9257 (let ((prev (car loops))) ; rearrange scope chain
9258 (push (setq loop (js2-parse-array-comp-loop)) loops)
9259 (if prev ; each loop is parent scope to the next one
9260 (setf (js2-scope-parent-scope loop) prev)
9261 ; first loop takes expr scope's parent
9262 (setf (js2-scope-parent-scope (setq first loop))
9263 (js2-scope-parent-scope js2-current-scope)))))
9264 ;; set expr scope's parent to the last loop
9265 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9266 (when (= (js2-peek-token) js2-IF)
9267 (js2-consume-token)
9268 (setq if-pos (- js2-token-beg pos) ; relative
9269 filter (js2-parse-condition)))
9270 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9271 (setq result (make-js2-array-comp-node :pos pos
9272 :len (- js2-ts-cursor pos)
9273 :result expr
9274 :loops (nreverse loops)
9275 :filter (car filter)
9276 :lp (js2-relpos (second filter) pos)
9277 :rp (js2-relpos (third filter) pos)
9278 :if-pos if-pos))
9279 (apply #'js2-node-add-children result expr (car filter)
9280 (js2-array-comp-node-loops result))
9281 (setq js2-current-scope first) ; pop to the first loop
9282 result))
9283
9284 (defun js2-parse-array-comp-loop ()
9285 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9286 Last token peeked should be the initial FOR."
9287 (let ((pos js2-token-beg)
9288 (pn (make-js2-array-comp-loop-node))
9289 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9290 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9291 (js2-push-scope pn)
9292 (unwind-protect
9293 (progn
9294 (when (js2-match-token js2-NAME)
9295 (if (string= js2-ts-string "each")
9296 (progn
9297 (setq foreach-p t
9298 each-pos (- js2-token-beg pos)) ; relative
9299 (js2-record-face 'font-lock-keyword-face))
9300 (js2-report-error "msg.no.paren.for")))
9301 (if (js2-must-match js2-LP "msg.no.paren.for")
9302 (setq lp (- js2-token-beg pos)))
9303 (setq tt (js2-peek-token))
9304 (cond
9305 ((or (= tt js2-LB)
9306 (= tt js2-LC))
9307 (setq iter (js2-parse-destruct-primary-expr))
9308 (js2-define-destruct-symbols iter js2-LET
9309 'font-lock-variable-name-face t))
9310 ((js2-match-token js2-NAME)
9311 (setq iter (js2-create-name-node)))
9312 (t
9313 (js2-report-error "msg.bad.var")))
9314 ;; Define as a let since we want the scope of the variable to
9315 ;; be restricted to the array comprehension
9316 (if (js2-name-node-p iter)
9317 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9318 (if (or (js2-match-token js2-IN)
9319 (and (>= js2-language-version 200)
9320 (js2-match-contextual-kwd "of")
9321 (setq forof-p t)))
9322 (setq in-pos (- js2-token-beg pos))
9323 (js2-report-error "msg.in.after.for.name"))
9324 (setq obj (js2-parse-expr))
9325 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9326 (setq rp (- js2-token-beg pos)))
9327 (setf (js2-node-pos pn) pos
9328 (js2-node-len pn) (- js2-ts-cursor pos)
9329 (js2-array-comp-loop-node-iterator pn) iter
9330 (js2-array-comp-loop-node-object pn) obj
9331 (js2-array-comp-loop-node-in-pos pn) in-pos
9332 (js2-array-comp-loop-node-each-pos pn) each-pos
9333 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9334 (js2-array-comp-loop-node-forof-p pn) forof-p
9335 (js2-array-comp-loop-node-lp pn) lp
9336 (js2-array-comp-loop-node-rp pn) rp)
9337 (js2-node-add-children pn iter obj))
9338 (js2-pop-scope))
9339 pn))
9340
9341 (defun js2-parse-object-literal ()
9342 (let ((pos js2-token-beg)
9343 tt elems result after-comma
9344 (continue t))
9345 (while continue
9346 (setq tt (js2-peek-token))
9347 (cond
9348 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9349 ;; {get foo() {...}}, or {set foo(x) {...}}
9350 ((or (js2-valid-prop-name-token tt)
9351 (= tt js2-STRING))
9352 (setq after-comma nil
9353 result (js2-parse-named-prop tt))
9354 (if (and (null result)
9355 (not js2-recover-from-parse-errors))
9356 (setq continue nil)
9357 (push result elems)))
9358 ;; {12: x} or {10.7: x}
9359 ((= tt js2-NUMBER)
9360 (js2-consume-token)
9361 (setq after-comma nil)
9362 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9363 ;; trailing comma
9364 ((= tt js2-RC)
9365 (setq continue nil)
9366 (if after-comma
9367 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9368 pos elems after-comma)))
9369 (t
9370 (js2-report-error "msg.bad.prop")
9371 (unless js2-recover-from-parse-errors
9372 (setq continue nil)))) ; end switch
9373 (if (js2-match-token js2-COMMA)
9374 (setq after-comma js2-token-end)
9375 (setq continue nil))) ; end loop
9376 (js2-must-match js2-RC "msg.no.brace.prop")
9377 (setq result (make-js2-object-node :pos pos
9378 :len (- js2-ts-cursor pos)
9379 :elems (nreverse elems)))
9380 (apply #'js2-node-add-children result (js2-object-node-elems result))
9381 result))
9382
9383 (defun js2-parse-named-prop (tt)
9384 "Parse a name, string, or getter/setter object property.
9385 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9386 (js2-consume-token)
9387 (let ((string-prop (and (= tt js2-STRING)
9388 (make-js2-string-node)))
9389 expr
9390 (ppos js2-token-beg)
9391 (pend js2-token-end)
9392 (name (js2-create-name-node))
9393 (prop js2-ts-string))
9394 (cond
9395 ;; getter/setter prop
9396 ((and (= tt js2-NAME)
9397 (= (js2-peek-token) js2-NAME)
9398 (or (string= prop "get")
9399 (string= prop "set")))
9400 (js2-consume-token)
9401 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9402 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9403 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9404 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9405 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9406 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9407 ;; when patterns are used in variable declarations, function parameters,
9408 ;; catch-clause, and iterators.
9409 ;; We have to set `js2-is-in-destructuring' to t when the current
9410 ;; expressions are on the left side of any assignment, but it's difficult
9411 ;; because it requires looking ahead of expression.
9412 ((and js2-is-in-destructuring
9413 (= tt js2-NAME)
9414 (let ((ctk (js2-peek-token)))
9415 (or (= ctk js2-COMMA)
9416 (= ctk js2-RC)
9417 (js2-valid-prop-name-token ctk))))
9418 name)
9419 ;; regular prop
9420 (t
9421 (prog1
9422 (setq expr (js2-parse-plain-property (or string-prop name)))
9423 (js2-set-face ppos pend
9424 (if (js2-function-node-p
9425 (js2-object-prop-node-right expr))
9426 'font-lock-function-name-face
9427 'font-lock-variable-name-face)
9428 'record))))))
9429
9430 (defun js2-parse-plain-property (prop)
9431 "Parse a non-getter/setter property in an object literal.
9432 PROP is the node representing the property: a number, name or string."
9433 (js2-must-match js2-COLON "msg.no.colon.prop")
9434 (let* ((pos (js2-node-pos prop))
9435 (colon (- js2-token-beg pos))
9436 (expr (js2-parse-assign-expr))
9437 (result (make-js2-object-prop-node
9438 :pos pos
9439 ;; don't include last consumed token in length
9440 :len (- (+ (js2-node-pos expr)
9441 (js2-node-len expr))
9442 pos)
9443 :left prop
9444 :right expr
9445 :op-pos colon)))
9446 (js2-node-add-children result prop expr)
9447 result))
9448
9449 (defun js2-parse-getter-setter-prop (pos prop get-p)
9450 "Parse getter or setter property in an object literal.
9451 JavaScript syntax is:
9452
9453 { get foo() {...}, set foo(x) {...} }
9454
9455 and expression closure style is also supported
9456
9457 { get foo() x, set foo(x) _x = x }
9458
9459 POS is the start position of the `get' or `set' keyword.
9460 PROP is the `js2-name-node' representing the property name.
9461 GET-P is non-nil if the keyword was `get'."
9462 (let ((type (if get-p js2-GET js2-SET))
9463 result end
9464 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9465 ;; it has to be an anonymous function, as we already parsed the name
9466 (if (/= (js2-node-type fn) js2-FUNCTION)
9467 (js2-report-error "msg.bad.prop")
9468 (if (plusp (length (js2-function-name fn)))
9469 (js2-report-error "msg.bad.prop")))
9470 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9471 (setq end (js2-node-end fn)
9472 result (make-js2-getter-setter-node :type type
9473 :pos pos
9474 :len (- end pos)
9475 :left prop
9476 :right fn))
9477 (js2-node-add-children result prop fn)
9478 result))
9479
9480 (defun js2-create-name-node (&optional check-activation-p token)
9481 "Create a name node using the token info from last scanned name.
9482 In some cases we need to either synthesize a name node, or we lost
9483 the name token information by peeking. If the TOKEN parameter is
9484 not `js2-NAME', then we use the token info saved in instance vars."
9485 (let ((beg js2-token-beg)
9486 (s js2-ts-string)
9487 name)
9488 (when (/= js2-current-token js2-NAME)
9489 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9490 s js2-prev-name-token-string
9491 js2-prev-name-token-start nil
9492 js2-prev-name-token-string nil))
9493 (setq name (make-js2-name-node :pos beg
9494 :name s
9495 :len (length s)))
9496 (if check-activation-p
9497 (js2-check-activation-name s (or token js2-NAME)))
9498 name))
9499
9500 ;;; Indentation support
9501
9502 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9503 ;; Karl cleverly deduces that the desired indentation level is often a
9504 ;; function of paren/bracket/brace nesting depth, which can be determined
9505 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9506 ;; then does some equally clever checks to see if we're in the context of a
9507 ;; substatement of a possibly braceless statement keyword such as if, while,
9508 ;; or finally. This approach yields pretty good results.
9509
9510 ;; The indenter is often "wrong", however, and needs to be overridden.
9511 ;; The right long-term solution is probably to emulate (or integrate
9512 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9513 ;; parse tree from `js2-parse' is present, which is not true at the
9514 ;; moment the user is typing, computing indentation is still thousands
9515 ;; of lines of code to handle every possible syntactic edge case.
9516
9517 ;; In the meantime, the compromise solution is that we offer a "bounce
9518 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9519 ;; current line indent among various likely guess points. This approach
9520 ;; is far from perfect, but should at least make it slightly easier to
9521 ;; move the line towards its desired indentation when manually
9522 ;; overriding Karl's heuristic nesting guesser.
9523
9524 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9525 ;; extensions such as `let' and Array comprehensions. Major kudos to
9526 ;; Karl for coming up with the initial approach, which packs a lot of
9527 ;; punch for so little code.
9528
9529 (defconst js2-possibly-braceless-keywords-re
9530 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9531 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9532 "try" "while" "with" "let")))
9533 "Regular expression matching keywords that are optionally
9534 followed by an opening brace.")
9535
9536 (defconst js2-indent-operator-re
9537 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9538 (regexp-opt '("in" "instanceof") 'words))
9539 "Regular expression matching operators that affect indentation
9540 of continued expressions.")
9541
9542 (defconst js2-declaration-keyword-re
9543 (regexp-opt '("var" "let" "const") 'words)
9544 "Regular expression matching variable declaration keywords.")
9545
9546 ;; This function has horrible results if you're typing an array
9547 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9548 ;; in conjunction with electric-indent, so just disabling it.
9549 (defsubst js2-code-at-bol-p ()
9550 "Return t if the first character on line is non-whitespace."
9551 nil)
9552
9553 (defun js2-insert-and-indent (key)
9554 "Run command bound to KEY and indent current line.
9555 Runs the command bound to KEY in the global keymap and indents
9556 the current line."
9557 (interactive (list (this-command-keys)))
9558 (let ((cmd (lookup-key (current-global-map) key)))
9559 (if (commandp cmd)
9560 (call-interactively cmd)))
9561 ;; don't do the electric keys inside comments or strings,
9562 ;; and don't do bounce-indent with them.
9563 (let ((parse-state (syntax-ppss (point)))
9564 (js2-bounce-indent-p (js2-code-at-bol-p)))
9565 (unless (or (nth 3 parse-state)
9566 (nth 4 parse-state))
9567 (indent-according-to-mode))))
9568
9569 (defun js2-re-search-forward-inner (regexp &optional bound count)
9570 "Auxiliary function for `js2-re-search-forward'."
9571 (let (parse saved-point)
9572 (while (> count 0)
9573 (re-search-forward regexp bound)
9574 (setq parse (if saved-point
9575 (parse-partial-sexp saved-point (point))
9576 (syntax-ppss (point))))
9577 (cond ((nth 3 parse)
9578 (re-search-forward
9579 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9580 (save-excursion (end-of-line) (point)) t))
9581 ((nth 7 parse)
9582 (forward-line))
9583 ((or (nth 4 parse)
9584 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9585 (re-search-forward "\\*/"))
9586 (t
9587 (setq count (1- count))))
9588 (setq saved-point (point))))
9589 (point))
9590
9591 (defun js2-re-search-forward (regexp &optional bound noerror count)
9592 "Search forward but ignore strings and comments.
9593 Invokes `re-search-forward' but treats the buffer as if strings
9594 and comments have been removed."
9595 (let ((saved-point (point))
9596 (search-expr
9597 (cond ((null count)
9598 '(js2-re-search-forward-inner regexp bound 1))
9599 ((< count 0)
9600 '(js2-re-search-backward-inner regexp bound (- count)))
9601 ((> count 0)
9602 '(js2-re-search-forward-inner regexp bound count)))))
9603 (condition-case err
9604 (eval search-expr)
9605 (search-failed
9606 (goto-char saved-point)
9607 (unless noerror
9608 (error (error-message-string err)))))))
9609
9610 (defun js2-re-search-backward-inner (regexp &optional bound count)
9611 "Auxiliary function for `js2-re-search-backward'."
9612 (let (parse)
9613 (while (> count 0)
9614 (re-search-backward regexp bound)
9615 (setq parse (syntax-ppss (point)))
9616 (cond ((nth 3 parse)
9617 (re-search-backward
9618 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9619 (line-beginning-position) t))
9620 ((nth 7 parse)
9621 (goto-char (nth 8 parse)))
9622 ((or (nth 4 parse)
9623 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9624 (re-search-backward "/\\*"))
9625 (t
9626 (setq count (1- count))))))
9627 (point))
9628
9629 (defun js2-re-search-backward (regexp &optional bound noerror count)
9630 "Search backward but ignore strings and comments.
9631 Invokes `re-search-backward' but treats the buffer as if strings
9632 and comments have been removed."
9633 (let ((saved-point (point))
9634 (search-expr
9635 (cond ((null count)
9636 '(js2-re-search-backward-inner regexp bound 1))
9637 ((< count 0)
9638 '(js2-re-search-forward-inner regexp bound (- count)))
9639 ((> count 0)
9640 '(js2-re-search-backward-inner regexp bound count)))))
9641 (condition-case err
9642 (eval search-expr)
9643 (search-failed
9644 (goto-char saved-point)
9645 (unless noerror
9646 (error (error-message-string err)))))))
9647
9648 (defun js2-looking-at-operator-p ()
9649 "Return non-nil if text after point is a non-comma operator."
9650 (and (looking-at js2-indent-operator-re)
9651 (or (not (looking-at ":"))
9652 (save-excursion
9653 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9654 (looking-at "?"))))))
9655
9656 (defun js2-continued-expression-p ()
9657 "Return non-nil if the current line continues an expression."
9658 (save-excursion
9659 (back-to-indentation)
9660 (or (js2-looking-at-operator-p)
9661 (when (js2-re-search-backward "\n" nil t) ;; skip comments
9662 (skip-chars-backward " \t")
9663 (unless (bolp) ;; previous line is empty
9664 (backward-char)
9665 (when (js2-looking-at-operator-p)
9666 (backward-char)
9667 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))
9668
9669 (defun js2-end-of-do-while-loop-p ()
9670 "Return non-nil if word after point is `while' of a do-while
9671 statement, else returns nil. A braceless do-while statement
9672 spanning several lines requires that the start of the loop is
9673 indented to the same column as the current line."
9674 (interactive)
9675 (save-excursion
9676 (when (looking-at "\\s-*\\<while\\>")
9677 (if (save-excursion
9678 (skip-chars-backward "[ \t\n]*}")
9679 (looking-at "[ \t\n]*}"))
9680 (save-excursion
9681 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9682 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9683 (or (looking-at "\\<do\\>")
9684 (let ((saved-indent (current-indentation)))
9685 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9686 (/= (current-indentation) saved-indent)))
9687 (and (looking-at "[ \t]*\\<do\\>")
9688 (not (js2-re-search-forward
9689 "\\<while\\>" (point-at-eol) t))
9690 (= (current-indentation) saved-indent))))))))
9691
9692 (defun js2-multiline-decl-indentation ()
9693 "Returns the declaration indentation column if the current line belongs
9694 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9695 (let (forward-sexp-function ; use Lisp version
9696 at-opening-bracket)
9697 (save-excursion
9698 (back-to-indentation)
9699 (when (not (looking-at js2-declaration-keyword-re))
9700 (when (looking-at js2-indent-operator-re)
9701 (goto-char (match-end 0))) ; continued expressions are ok
9702 (while (and (not at-opening-bracket)
9703 (not (bobp))
9704 (let ((pos (point)))
9705 (save-excursion
9706 (js2-backward-sws)
9707 (or (eq (char-before) ?,)
9708 (and (not (eq (char-before) ?\;))
9709 (and
9710 (prog2 (skip-chars-backward "[[:punct:]]")
9711 (looking-at js2-indent-operator-re)
9712 (js2-backward-sws))
9713 (not (eq (char-before) ?\;))))
9714 (js2-same-line pos)))))
9715 (condition-case err
9716 (backward-sexp)
9717 (scan-error (setq at-opening-bracket t))))
9718 (when (looking-at js2-declaration-keyword-re)
9719 (goto-char (match-end 0))
9720 (1+ (current-column)))))))
9721
9722 (defun js2-ctrl-statement-indentation ()
9723 "Return the proper indentation of current line if it is a control statement.
9724 Returns an indentation if this line starts the body of a control
9725 statement without braces, else returns nil."
9726 (let (forward-sexp-function)
9727 (save-excursion
9728 (back-to-indentation)
9729 (when (and (not (js2-same-line (point-min)))
9730 (not (looking-at "{"))
9731 (js2-re-search-backward "[[:graph:]]" nil t)
9732 (not (looking-at "[{([]"))
9733 (progn
9734 (forward-char)
9735 (when (= (char-before) ?\))
9736 ;; scan-sexps sometimes throws an error
9737 (ignore-errors (backward-sexp))
9738 (skip-chars-backward " \t" (point-at-bol)))
9739 (let ((pt (point)))
9740 (back-to-indentation)
9741 (and (looking-at js2-possibly-braceless-keywords-re)
9742 (= (match-end 0) pt)
9743 (not (js2-end-of-do-while-loop-p))))))
9744 (+ (current-indentation) js2-basic-offset)))))
9745
9746 (defun js2-indent-in-array-comp (parse-status)
9747 "Return non-nil if we think we're in an array comprehension.
9748 In particular, return the buffer position of the first `for' kwd."
9749 (let ((bracket (nth 1 parse-status))
9750 (end (point)))
9751 (when bracket
9752 (save-excursion
9753 (goto-char bracket)
9754 (when (looking-at "\\[")
9755 (forward-char 1)
9756 (js2-forward-sws)
9757 (if (looking-at "[[{]")
9758 (let (forward-sexp-function) ; use Lisp version
9759 (forward-sexp) ; skip destructuring form
9760 (js2-forward-sws)
9761 (if (and (/= (char-after) ?,) ; regular array
9762 (looking-at "for"))
9763 (match-beginning 0)))
9764 ;; to skip arbitrary expressions we need the parser,
9765 ;; so we'll just guess at it.
9766 (if (and (> end (point)) ; not empty literal
9767 (re-search-forward "[^,]]* \\(for\\) " end t)
9768 ;; not inside comment or string literal
9769 (let ((state (parse-partial-sexp bracket (point))))
9770 (not (or (nth 3 state) (nth 4 state)))))
9771 (match-beginning 1))))))))
9772
9773 (defun js2-array-comp-indentation (parse-status for-kwd)
9774 (if (js2-same-line for-kwd)
9775 ;; first continuation line
9776 (save-excursion
9777 (goto-char (nth 1 parse-status))
9778 (forward-char 1)
9779 (skip-chars-forward " \t")
9780 (current-column))
9781 (save-excursion
9782 (goto-char for-kwd)
9783 (current-column))))
9784
9785 (defun js2-proper-indentation (parse-status)
9786 "Return the proper indentation for the current line."
9787 (save-excursion
9788 (back-to-indentation)
9789 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9790 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9791 (continued-expr-p (js2-continued-expression-p))
9792 (declaration-indent (and js2-pretty-multiline-declarations
9793 (js2-multiline-decl-indentation)))
9794 (bracket (nth 1 parse-status))
9795 beg)
9796 (cond
9797 ;; indent array comprehension continuation lines specially
9798 ((and bracket
9799 (>= js2-language-version 170)
9800 (not (js2-same-line bracket))
9801 (setq beg (js2-indent-in-array-comp parse-status))
9802 (>= (point) (save-excursion
9803 (goto-char beg)
9804 (point-at-bol)))) ; at or after first loop?
9805 (js2-array-comp-indentation parse-status beg))
9806
9807 (ctrl-stmt-indent)
9808
9809 ((and declaration-indent continued-expr-p)
9810 (+ declaration-indent js2-basic-offset))
9811
9812 (declaration-indent)
9813
9814 (bracket
9815 (goto-char bracket)
9816 (cond
9817 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9818 (when (save-excursion (skip-chars-backward " \t)")
9819 (looking-at ")"))
9820 (backward-list))
9821 (back-to-indentation)
9822 (and (eq js2-pretty-multiline-declarations 'all)
9823 (looking-at js2-declaration-keyword-re)
9824 (goto-char (1+ (match-end 0))))
9825 (cond (same-indent-p
9826 (current-column))
9827 (continued-expr-p
9828 (+ (current-column) (* 2 js2-basic-offset)))
9829 (t
9830 (+ (current-column) js2-basic-offset))))
9831 (t
9832 (unless same-indent-p
9833 (forward-char)
9834 (skip-chars-forward " \t"))
9835 (current-column))))
9836
9837 (continued-expr-p js2-basic-offset)
9838
9839 (t 0)))))
9840
9841 (defun js2-lineup-comment (parse-status)
9842 "Indent a multi-line block comment continuation line."
9843 (let* ((beg (nth 8 parse-status))
9844 (first-line (js2-same-line beg))
9845 (offset (save-excursion
9846 (goto-char beg)
9847 (if (looking-at "/\\*")
9848 (+ 1 (current-column))
9849 0))))
9850 (unless first-line
9851 (indent-line-to offset))))
9852
9853 (defun js2-backward-sws ()
9854 "Move backward through whitespace and comments."
9855 (interactive)
9856 (while (forward-comment -1)))
9857
9858 (defun js2-forward-sws ()
9859 "Move forward through whitespace and comments."
9860 (interactive)
9861 (while (forward-comment 1)))
9862
9863 (defun js2-current-indent (&optional pos)
9864 "Return column of indentation on current line.
9865 If POS is non-nil, go to that point and return indentation for that line."
9866 (save-excursion
9867 (if pos
9868 (goto-char pos))
9869 (back-to-indentation)
9870 (current-column)))
9871
9872 (defun js2-arglist-close ()
9873 "Return non-nil if we're on a line beginning with a close-paren/brace."
9874 (save-excursion
9875 (goto-char (point-at-bol))
9876 (js2-forward-sws)
9877 (looking-at "[])}]")))
9878
9879 (defun js2-indent-looks-like-label-p ()
9880 (goto-char (point-at-bol))
9881 (js2-forward-sws)
9882 (looking-at (concat js2-mode-identifier-re ":")))
9883
9884 (defun js2-indent-in-objlit-p (parse-status)
9885 "Return non-nil if this looks like an object-literal entry."
9886 (let ((start (nth 1 parse-status)))
9887 (and
9888 start
9889 (save-excursion
9890 (and (zerop (forward-line -1))
9891 (not (< (point) start)) ; crossed a {} boundary
9892 (js2-indent-looks-like-label-p)))
9893 (save-excursion
9894 (js2-indent-looks-like-label-p)))))
9895
9896 ;; If prev line looks like foobar({ then we're passing an object
9897 ;; literal to a function call, and people pretty much always want to
9898 ;; de-dent back to the previous line, so move the 'basic-offset'
9899 ;; position to the front.
9900 (defun js2-indent-objlit-arg-p (parse-status)
9901 (save-excursion
9902 (back-to-indentation)
9903 (js2-backward-sws)
9904 (and (eq (1- (point)) (nth 1 parse-status))
9905 (eq (char-before) ?{)
9906 (progn
9907 (forward-char -1)
9908 (skip-chars-backward " \t")
9909 (eq (char-before) ?\()))))
9910
9911 (defun js2-indent-case-block-p ()
9912 (save-excursion
9913 (back-to-indentation)
9914 (js2-backward-sws)
9915 (goto-char (point-at-bol))
9916 (skip-chars-forward " \t")
9917 (looking-at "case\\s-.+:")))
9918
9919 (defun js2-syntax-bol ()
9920 "Return the point at the first non-whitespace char on the line.
9921 Returns `point-at-bol' if the line is empty."
9922 (save-excursion
9923 (beginning-of-line)
9924 (skip-chars-forward " \t")
9925 (point)))
9926
9927 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9928 "Cycle among alternate computed indentation positions.
9929 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9930 of the buffer to the current point. NORMAL-COL is the indentation
9931 column computed by the heuristic guesser based on current paren,
9932 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9933 in reverse."
9934 (let ((cur-indent (js2-current-indent))
9935 (old-buffer-undo-list buffer-undo-list)
9936 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9937 (current-line (save-excursion
9938 (forward-line 0) ; move to bol
9939 (1+ (count-lines (point-min) (point)))))
9940 positions pos main-pos anchor arglist-cont same-indent
9941 prev-line-col basic-offset computed-pos)
9942 ;; temporarily don't record undo info, if user requested this
9943 (when js2-mode-indent-inhibit-undo
9944 (setq buffer-undo-list t))
9945 (unwind-protect
9946 (progn
9947 ;; First likely point: indent from beginning of previous code line
9948 (push (setq basic-offset
9949 (+ (save-excursion
9950 (back-to-indentation)
9951 (js2-backward-sws)
9952 (back-to-indentation)
9953 (setq prev-line-col (current-column)))
9954 js2-basic-offset))
9955 positions)
9956
9957 ;; (First + epsilon) likely point: indent 2x from beginning of
9958 ;; previous code line. Google does it this way.
9959 (push (setq basic-offset
9960 (+ (save-excursion
9961 (back-to-indentation)
9962 (js2-backward-sws)
9963 (back-to-indentation)
9964 (setq prev-line-col (current-column)))
9965 (* 2 js2-basic-offset)))
9966 positions)
9967
9968 ;; Second likely point: indent from assign-expr RHS. This
9969 ;; is just a crude guess based on finding " = " on the previous
9970 ;; line containing actual code.
9971 (setq pos (save-excursion
9972 (forward-line -1)
9973 (goto-char (point-at-bol))
9974 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9975 (point-at-eol) t)
9976 (goto-char (match-end 1))
9977 (skip-chars-forward " \t\r\n")
9978 (current-column))))
9979 (when pos
9980 (incf pos js2-basic-offset)
9981 (push pos positions))
9982
9983 ;; Third likely point: same indent as previous line of code.
9984 ;; Make it the first likely point if we're not on an
9985 ;; arglist-close line and previous line ends in a comma, or
9986 ;; both this line and prev line look like object-literal
9987 ;; elements.
9988 (setq pos (save-excursion
9989 (goto-char (point-at-bol))
9990 (js2-backward-sws)
9991 (back-to-indentation)
9992 (prog1
9993 (current-column)
9994 ;; while we're here, look for trailing comma
9995 (if (save-excursion
9996 (goto-char (point-at-eol))
9997 (js2-backward-sws)
9998 (eq (char-before) ?,))
9999 (setq arglist-cont (1- (point)))))))
10000 (when pos
10001 (if (and (or arglist-cont
10002 (js2-indent-in-objlit-p parse-status))
10003 (not (js2-arglist-close)))
10004 (setq same-indent pos))
10005 (push pos positions))
10006
10007 ;; Fourth likely point: first preceding code with less indentation.
10008 ;; than the immediately preceding code line.
10009 (setq pos (save-excursion
10010 (back-to-indentation)
10011 (js2-backward-sws)
10012 (back-to-indentation)
10013 (setq anchor (current-column))
10014 (while (and (zerop (forward-line -1))
10015 (>= (progn
10016 (back-to-indentation)
10017 (current-column))
10018 anchor)))
10019 (setq pos (current-column))))
10020 (push pos positions)
10021
10022 ;; nesting-heuristic position, main by default
10023 (push (setq main-pos normal-col) positions)
10024
10025 ;; delete duplicates and sort positions list
10026 (setq positions (sort (delete-dups positions) '<))
10027
10028 ;; comma-list continuation lines: prev line indent takes precedence
10029 (if same-indent
10030 (setq main-pos same-indent))
10031
10032 ;; common special cases where we want to indent in from previous line
10033 (if (or (js2-indent-case-block-p)
10034 (js2-indent-objlit-arg-p parse-status))
10035 (setq main-pos basic-offset))
10036
10037 ;; if bouncing backwards, reverse positions list
10038 (if backwards
10039 (setq positions (reverse positions)))
10040
10041 ;; record whether we're already sitting on one of the alternatives
10042 (setq pos (member cur-indent positions))
10043
10044 (cond
10045 ;; case 0: we're one one of the alternatives and this is the
10046 ;; first time they've pressed TAB on this line (best-guess).
10047 ((and js2-mode-indent-ignore-first-tab
10048 pos
10049 ;; first time pressing TAB on this line?
10050 (not (eq js2-mode-last-indented-line current-line)))
10051 ;; do nothing
10052 (setq computed-pos nil))
10053 ;; case 1: only one computed position => use it
10054 ((null (cdr positions))
10055 (setq computed-pos 0))
10056 ;; case 2: not on any of the computed spots => use main spot
10057 ((not pos)
10058 (setq computed-pos (js2-position main-pos positions)))
10059 ;; case 3: on last position: cycle to first position
10060 ((null (cdr pos))
10061 (setq computed-pos 0))
10062 ;; case 4: on intermediate position: cycle to next position
10063 (t
10064 (setq computed-pos (js2-position (second pos) positions))))
10065
10066 ;; see if any hooks want to indent; otherwise we do it
10067 (loop with result = nil
10068 for hook in js2-indent-hook
10069 while (null result)
10070 do
10071 (setq result (funcall hook positions computed-pos))
10072 finally do
10073 (unless (or result (null computed-pos))
10074 (indent-line-to (nth computed-pos positions)))))
10075
10076 ;; finally
10077 (if js2-mode-indent-inhibit-undo
10078 (setq buffer-undo-list old-buffer-undo-list))
10079 ;; see commentary for `js2-mode-last-indented-line'
10080 (setq js2-mode-last-indented-line current-line))))
10081
10082 (defun js2-indent-bounce-backwards ()
10083 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10084 cycles between the computed indentation positions in reverse order."
10085 (interactive)
10086 (js2-indent-line t))
10087
10088 (defun js2-1-line-comment-continuation-p ()
10089 "Return t if we're in a 1-line comment continuation.
10090 If so, we don't ever want to use bounce-indent."
10091 (save-excursion
10092 (and (progn
10093 (forward-line 0)
10094 (looking-at "\\s-*//"))
10095 (progn
10096 (forward-line -1)
10097 (forward-line 0)
10098 (when (looking-at "\\s-*$")
10099 (js2-backward-sws)
10100 (forward-line 0))
10101 (looking-at "\\s-*//")))))
10102
10103 (defun js2-indent-line (&optional bounce-backwards)
10104 "Indent the current line as JavaScript source text."
10105 (interactive)
10106 (let (parse-status current-indent offset indent-col moved
10107 ;; Don't whine about errors/warnings when we're indenting.
10108 ;; This has to be set before calling parse-partial-sexp below.
10109 (inhibit-point-motion-hooks t))
10110 (setq parse-status (save-excursion
10111 (syntax-ppss (point-at-bol)))
10112 offset (- (point) (save-excursion
10113 (back-to-indentation)
10114 (point))))
10115 (js2-with-underscore-as-word-syntax
10116 (if (nth 4 parse-status)
10117 (js2-lineup-comment parse-status)
10118 (setq indent-col (js2-proper-indentation parse-status))
10119 ;; See comments below about `js2-mode-last-indented-line'.
10120 (cond
10121 ;; bounce-indenting is disabled during electric-key indent.
10122 ;; It doesn't work well on first line of buffer.
10123 ((and js2-bounce-indent-p
10124 (not (js2-same-line (point-min)))
10125 (not (js2-1-line-comment-continuation-p)))
10126 (js2-bounce-indent indent-col parse-status bounce-backwards))
10127 ;; just indent to the guesser's likely spot
10128 (t (indent-line-to indent-col))))
10129 (when (plusp offset)
10130 (forward-char offset)))))
10131
10132 (defun js2-indent-region (start end)
10133 "Indent the region, but don't use bounce indenting."
10134 (let ((js2-bounce-indent-p nil)
10135 (indent-region-function nil)
10136 (after-change-functions (remq 'js2-mode-edit
10137 after-change-functions)))
10138 (indent-region start end nil) ; nil for byte-compiler
10139 (js2-mode-edit start end (- end start))))
10140
10141 (defvar js2-minor-mode-map
10142 (let ((map (make-sparse-keymap)))
10143 (define-key map (kbd "C-c C-`") #'js2-next-error)
10144 (define-key map [mouse-1] #'js2-mode-show-node)
10145 map)
10146 "Keymap used when `js2-minor-mode' is active.")
10147
10148 ;;;###autoload
10149 (define-minor-mode js2-minor-mode
10150 "Minor mode for running js2 as a background linter.
10151 This allows you to use a different major mode for JavaScript editing,
10152 such as `espresso-mode', while retaining the asynchronous error/warning
10153 highlighting features of `js2-mode'."
10154 :group 'js2-mode
10155 :lighter " js-lint"
10156 (if js2-minor-mode
10157 (js2-minor-mode-enter)
10158 (js2-minor-mode-exit)))
10159
10160 (defun js2-minor-mode-enter ()
10161 "Initialization for `js2-minor-mode'."
10162 (set (make-local-variable 'max-lisp-eval-depth)
10163 (max max-lisp-eval-depth 3000))
10164 (setq next-error-function #'js2-next-error)
10165 (setq js2-default-externs
10166 (append js2-ecma-262-externs
10167 (if js2-include-browser-externs js2-browser-externs)
10168 (if js2-include-gears-externs js2-gears-externs)
10169 (if js2-include-rhino-externs js2-rhino-externs)))
10170 ;; Experiment: make reparse-delay longer for longer files.
10171 (if (plusp js2-dynamic-idle-timer-adjust)
10172 (setq js2-idle-timer-delay
10173 (* js2-idle-timer-delay
10174 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10175 (setq js2-mode-buffer-dirty-p t
10176 js2-mode-parsing nil)
10177 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10178 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10179 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10180 (js2-reparse))
10181
10182 (defun js2-minor-mode-exit ()
10183 "Turn off `js2-minor-mode'."
10184 (setq next-error-function nil)
10185 (remove-hook 'after-change-functions #'js2-mode-edit t)
10186 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10187 (when js2-mode-node-overlay
10188 (delete-overlay js2-mode-node-overlay)
10189 (setq js2-mode-node-overlay nil))
10190 (js2-remove-overlays)
10191 (setq js2-mode-ast nil))
10192
10193 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10194 (make-variable-buffer-local 'js2-source-buffer)
10195
10196 (defun* js2-display-error-list ()
10197 "Display a navigable buffer listing parse errors/warnings."
10198 (interactive)
10199 (unless (js2-have-errors-p)
10200 (message "No errors")
10201 (return-from js2-display-error-list))
10202 (labels ((annotate-list
10203 (lst type)
10204 "Add diagnostic TYPE and line number to errs list"
10205 (mapcar (lambda (err)
10206 (append err (list type
10207 (line-number-at-pos (nth 1 err)))))
10208 lst)))
10209 (let* ((srcbuf (current-buffer))
10210 (errbuf (get-buffer-create "*js-lint*"))
10211 (errors (annotate-list
10212 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10213 'js2-error)) ; must be a valid face name
10214 (warnings (annotate-list
10215 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10216 'js2-warning)) ; must be a valid face name
10217 (all-errs (sort (append errors warnings)
10218 (lambda (e1 e2) (< (nth 1 e1) (nth 1 e2))))))
10219 (with-current-buffer errbuf
10220 (let ((inhibit-read-only t))
10221 (erase-buffer)
10222 (dolist (err all-errs)
10223 (destructuring-bind (msg-key beg end type line) err
10224 (insert-text-button
10225 (format "line %d: %s" line (js2-get-msg msg-key))
10226 'face type
10227 'follow-link "\C-m"
10228 'action 'js2-error-buffer-jump
10229 'js2-msg (js2-get-msg msg-key)
10230 'js2-pos beg)
10231 (insert "\n"))))
10232 (js2-error-buffer-mode)
10233 (setq js2-source-buffer srcbuf)
10234 (pop-to-buffer errbuf)
10235 (goto-char (point-min))
10236 (unless (eobp)
10237 (js2-error-buffer-view))))))
10238
10239 (defvar js2-error-buffer-mode-map
10240 (let ((map (make-sparse-keymap)))
10241 (define-key map "n" #'js2-error-buffer-next)
10242 (define-key map "p" #'js2-error-buffer-prev)
10243 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10244 (define-key map "o" #'js2-error-buffer-view)
10245 (define-key map "q" #'js2-error-buffer-quit)
10246 map)
10247 "Keymap used for js2 diagnostics buffers.")
10248
10249 (defun js2-error-buffer-mode ()
10250 "Major mode for js2 diagnostics buffers.
10251 Selecting an error will jump it to the corresponding source-buffer error.
10252 \\{js2-error-buffer-mode-map}"
10253 (interactive)
10254 (setq major-mode 'js2-error-buffer-mode
10255 mode-name "JS Lint Diagnostics")
10256 (use-local-map js2-error-buffer-mode-map)
10257 (setq truncate-lines t)
10258 (set-buffer-modified-p nil)
10259 (setq buffer-read-only t)
10260 (run-hooks 'js2-error-buffer-mode-hook))
10261
10262 (defun js2-error-buffer-next ()
10263 "Move to next error and view it."
10264 (interactive)
10265 (when (zerop (forward-line 1))
10266 (js2-error-buffer-view)))
10267
10268 (defun js2-error-buffer-prev ()
10269 "Move to previous error and view it."
10270 (interactive)
10271 (when (zerop (forward-line -1))
10272 (js2-error-buffer-view)))
10273
10274 (defun js2-error-buffer-quit ()
10275 "Kill the current buffer."
10276 (interactive)
10277 (kill-buffer))
10278
10279 (defun js2-error-buffer-jump (&rest ignored)
10280 "Jump cursor to current error in source buffer."
10281 (interactive)
10282 (when (js2-error-buffer-view)
10283 (pop-to-buffer js2-source-buffer)))
10284
10285 (defun js2-error-buffer-view ()
10286 "Scroll source buffer to show error at current line."
10287 (interactive)
10288 (cond
10289 ((not (eq major-mode 'js2-error-buffer-mode))
10290 (message "Not in a js2 errors buffer"))
10291 ((not (buffer-live-p js2-source-buffer))
10292 (message "Source buffer has been killed"))
10293 ((not (wholenump (get-text-property (point) 'js2-pos)))
10294 (message "There does not seem to be an error here"))
10295 (t
10296 (let ((pos (get-text-property (point) 'js2-pos))
10297 (msg (get-text-property (point) 'js2-msg)))
10298 (save-selected-window
10299 (pop-to-buffer js2-source-buffer)
10300 (goto-char pos)
10301 (message msg))))))
10302
10303 ;;;###autoload
10304 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10305 ;; FIXME: Should derive from js-mode.
10306 "Major mode for editing JavaScript code."
10307 (setq comment-start "//" ; used by comment-region; don't change it
10308 comment-end "")
10309 (set (make-local-variable 'max-lisp-eval-depth)
10310 (max max-lisp-eval-depth 3000))
10311 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10312 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10313 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10314 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10315 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10316 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10317 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10318 ;; for characters inside regexp literals.
10319 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10320 ;; this is necessary to make `show-paren-function' work properly
10321 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10322 ;; needed for M-x rgrep, among other things
10323 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10324
10325 (set (make-local-variable 'electric-indent-chars)
10326 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10327 electric-indent-chars))
10328 (set (make-local-variable 'electric-layout-rules)
10329 '((?\; . after) (?\{ . after) (?\} . before)))
10330
10331 ;; some variables needed by cc-engine for paragraph-fill, etc.
10332 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10333 c-comment-start-regexp "/[*/]\\|\\s|"
10334 c-line-comment-starter "//"
10335 c-paragraph-start js2-paragraph-start
10336 c-paragraph-separate "$"
10337 comment-start-skip js2-comment-start-skip
10338 c-syntactic-ws-start js2-syntactic-ws-start
10339 c-syntactic-ws-end js2-syntactic-ws-end
10340 c-syntactic-eol js2-syntactic-eol)
10341
10342 (let ((c-buffer-is-cc-mode t))
10343 ;; Copied from `js-mode'. Also see Bug#6071.
10344 (make-local-variable 'paragraph-start)
10345 (make-local-variable 'paragraph-separate)
10346 (make-local-variable 'paragraph-ignore-fill-prefix)
10347 (make-local-variable 'adaptive-fill-mode)
10348 (make-local-variable 'adaptive-fill-regexp)
10349 (c-setup-paragraph-variables))
10350
10351 (setq js2-default-externs
10352 (append js2-ecma-262-externs
10353 (if js2-include-browser-externs js2-browser-externs)
10354 (if js2-include-gears-externs js2-gears-externs)
10355 (if js2-include-rhino-externs js2-rhino-externs)))
10356
10357 (setq font-lock-defaults '(nil t))
10358
10359 ;; Experiment: make reparse-delay longer for longer files.
10360 (when (plusp js2-dynamic-idle-timer-adjust)
10361 (setq js2-idle-timer-delay
10362 (* js2-idle-timer-delay
10363 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10364
10365 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10366 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10367 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10368 (setq next-error-function #'js2-next-error)
10369 (imenu-add-to-menubar (concat "IM-" mode-name))
10370 (add-to-invisibility-spec '(js2-outline . t))
10371 (set (make-local-variable 'line-move-ignore-invisible) t)
10372 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10373
10374 (setq js2-mode-functions-hidden nil
10375 js2-mode-comments-hidden nil
10376 js2-mode-buffer-dirty-p t
10377 js2-mode-parsing nil)
10378 (js2-reparse))
10379
10380 (defun js2-mode-exit ()
10381 "Exit `js2-mode' and clean up."
10382 (interactive)
10383 (when js2-mode-node-overlay
10384 (delete-overlay js2-mode-node-overlay)
10385 (setq js2-mode-node-overlay nil))
10386 (js2-remove-overlays)
10387 (setq js2-mode-ast nil)
10388 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10389 (remove-from-invisibility-spec '(js2-outline . t))
10390 (js2-mode-show-all)
10391 (with-silent-modifications
10392 (js2-clear-face (point-min) (point-max))))
10393
10394 (defun js2-mode-reset-timer ()
10395 "Cancel any existing parse timer and schedule a new one."
10396 (if js2-mode-parse-timer
10397 (cancel-timer js2-mode-parse-timer))
10398 (setq js2-mode-parsing nil)
10399 (let ((timer (timer-create)))
10400 (setq js2-mode-parse-timer timer)
10401 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10402 (timer-set-idle-time timer js2-idle-timer-delay)
10403 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10404 (timer-activate-when-idle timer nil)))
10405
10406 (defun js2-mode-idle-reparse (buffer)
10407 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10408 it to be reparsed when the buffer is selected."
10409 (if (eq buffer (current-buffer))
10410 (js2-reparse)
10411 ;; reparse when the buffer is selected again
10412 (with-current-buffer buffer
10413 (add-hook 'window-configuration-change-hook
10414 #'js2-mode-idle-reparse-inner
10415 nil t))))
10416
10417 (defun js2-mode-idle-reparse-inner ()
10418 (remove-hook 'window-configuration-change-hook
10419 #'js2-mode-idle-reparse-inner
10420 t)
10421 (js2-reparse))
10422
10423 (defun js2-mode-edit (beg end len)
10424 "Schedule a new parse after buffer is edited.
10425 Buffer edit spans from BEG to END and is of length LEN."
10426 (setq js2-mode-buffer-dirty-p t)
10427 (js2-mode-hide-overlay)
10428 (js2-mode-reset-timer))
10429
10430 (defun js2-minor-mode-edit (beg end len)
10431 "Callback for buffer edits in `js2-mode'.
10432 Schedules a new parse after buffer is edited.
10433 Buffer edit spans from BEG to END and is of length LEN."
10434 (setq js2-mode-buffer-dirty-p t)
10435 (js2-mode-hide-overlay)
10436 (js2-mode-reset-timer))
10437
10438 (defun js2-reparse (&optional force)
10439 "Re-parse current buffer after user finishes some data entry.
10440 If we get any user input while parsing, including cursor motion,
10441 we discard the parse and reschedule it. If FORCE is nil, then the
10442 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10443 (let (time
10444 interrupted-p
10445 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10446 (unless js2-mode-parsing
10447 (setq js2-mode-parsing t)
10448 (unwind-protect
10449 (when (or js2-mode-buffer-dirty-p force)
10450 (js2-remove-overlays)
10451 (with-silent-modifications
10452 (setq js2-mode-buffer-dirty-p nil
10453 js2-mode-fontifications nil
10454 js2-mode-deferred-properties nil)
10455 (if js2-mode-verbose-parse-p
10456 (message "parsing..."))
10457 (setq time
10458 (js2-time
10459 (setq interrupted-p
10460 (catch 'interrupted
10461 (setq js2-mode-ast (js2-parse))
10462 ;; if parsing is interrupted, comments and regex
10463 ;; literals stay ignored by `parse-partial-sexp'
10464 (remove-text-properties (point-min) (point-max)
10465 '(syntax-table))
10466 (js2-mode-apply-deferred-properties)
10467 (js2-mode-remove-suppressed-warnings)
10468 (js2-mode-show-warnings)
10469 (js2-mode-show-errors)
10470 (if (>= js2-highlight-level 1)
10471 (js2-highlight-jsdoc js2-mode-ast))
10472 nil))))
10473 (if interrupted-p
10474 (progn
10475 ;; unfinished parse => try again
10476 (setq js2-mode-buffer-dirty-p t)
10477 (js2-mode-reset-timer))
10478 (if js2-mode-verbose-parse-p
10479 (message "Parse time: %s" time)))))
10480 (setq js2-mode-parsing nil)
10481 (unless interrupted-p
10482 (setq js2-mode-parse-timer nil))))))
10483
10484 (defun js2-mode-show-node (event)
10485 "Debugging aid: highlight selected AST node on mouse click."
10486 (interactive "e")
10487 (mouse-set-point event)
10488 (let ((node (js2-node-at-point))
10489 beg end)
10490 (when js2-mode-show-overlay
10491 (if (null node)
10492 (message "No node found at location %s" (point))
10493 (setq beg (js2-node-abs-pos node)
10494 end (+ beg (js2-node-len node)))
10495 (if js2-mode-node-overlay
10496 (move-overlay js2-mode-node-overlay beg end)
10497 (setq js2-mode-node-overlay (make-overlay beg end))
10498 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10499 (with-silent-modifications
10500 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10501 (message "%s, parent: %s"
10502 (js2-node-short-name node)
10503 (if (js2-node-parent node)
10504 (js2-node-short-name (js2-node-parent node))
10505 "nil"))))))
10506
10507 (put 'js2-mode-show-node 'CUA 'move)
10508
10509 (defun js2-mode-hide-overlay (&optional p1 p2)
10510 "Remove the debugging overlay when the point moves.
10511 P1 and P2 are the old and new values of point, respectively."
10512 (when js2-mode-node-overlay
10513 (let ((beg (overlay-start js2-mode-node-overlay))
10514 (end (overlay-end js2-mode-node-overlay)))
10515 ;; Sometimes we're called spuriously.
10516 (unless (and p2
10517 (>= p2 beg)
10518 (<= p2 end))
10519 (with-silent-modifications
10520 (remove-text-properties beg end '(point-left nil)))
10521 (delete-overlay js2-mode-node-overlay)
10522 (setq js2-mode-node-overlay nil)))))
10523
10524 (defun js2-mode-reset ()
10525 "Debugging helper: reset everything."
10526 (interactive)
10527 (js2-mode-exit)
10528 (js2-mode))
10529
10530 (defun js2-mode-show-warn-or-err (e face)
10531 "Highlight a warning or error E with FACE.
10532 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10533 The last element is optional. When present, use instead of FACE."
10534 (let* ((key (first e))
10535 (beg (second e))
10536 (end (+ beg (third e)))
10537 ;; Don't inadvertently go out of bounds.
10538 (beg (max (point-min) (min beg (point-max))))
10539 (end (max (point-min) (min end (point-max))))
10540 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10541 (ovl (make-overlay beg end)))
10542 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10543 (overlay-put ovl 'js2-error t)
10544 (put-text-property beg end 'help-echo (js2-get-msg key))
10545 (put-text-property beg end 'point-entered #'js2-echo-error)))
10546
10547 (defun js2-remove-overlays ()
10548 "Remove overlays from buffer that have a `js2-error' property."
10549 (let ((beg (point-min))
10550 (end (point-max)))
10551 (save-excursion
10552 (dolist (o (overlays-in beg end))
10553 (when (overlay-get o 'js2-error)
10554 (delete-overlay o))))))
10555
10556 (defun js2-error-at-point (&optional pos)
10557 "Return non-nil if there's an error overlay at POS.
10558 Defaults to point."
10559 (loop with pos = (or pos (point))
10560 for o in (overlays-at pos)
10561 thereis (overlay-get o 'js2-error)))
10562
10563 (defun js2-mode-apply-deferred-properties ()
10564 "Apply fontifications and other text properties recorded during parsing."
10565 (when (plusp js2-highlight-level)
10566 ;; We defer clearing faces as long as possible to eliminate flashing.
10567 (js2-clear-face (point-min) (point-max))
10568 ;; Have to reverse the recorded fontifications list so that errors
10569 ;; and warnings overwrite the normal fontifications.
10570 (dolist (f (nreverse js2-mode-fontifications))
10571 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10572 (setq js2-mode-fontifications nil))
10573 (dolist (p js2-mode-deferred-properties)
10574 (apply #'put-text-property p))
10575 (setq js2-mode-deferred-properties nil))
10576
10577 (defun js2-mode-show-errors ()
10578 "Highlight syntax errors."
10579 (when js2-mode-show-parse-errors
10580 (dolist (e (js2-ast-root-errors js2-mode-ast))
10581 (js2-mode-show-warn-or-err e 'js2-error))))
10582
10583 (defun js2-mode-remove-suppressed-warnings ()
10584 "Take suppressed warnings out of the AST warnings list.
10585 This ensures that the counts and `next-error' are correct."
10586 (setf (js2-ast-root-warnings js2-mode-ast)
10587 (js2-delete-if
10588 (lambda (e)
10589 (let ((key (caar e)))
10590 (or
10591 (and (not js2-strict-trailing-comma-warning)
10592 (string-match "trailing\\.comma" key))
10593 (and (not js2-strict-cond-assign-warning)
10594 (string= key "msg.equal.as.assign"))
10595 (and js2-missing-semi-one-line-override
10596 (string= key "msg.missing.semi")
10597 (let* ((beg (second e))
10598 (node (js2-node-at-point beg))
10599 (fn (js2-mode-find-parent-fn node))
10600 (body (and fn (js2-function-node-body fn)))
10601 (lc (and body (js2-node-abs-pos body)))
10602 (rc (and lc (+ lc (js2-node-len body)))))
10603 (and fn
10604 (or (null body)
10605 (save-excursion
10606 (goto-char beg)
10607 (and (js2-same-line lc)
10608 (js2-same-line rc))))))))))
10609 (js2-ast-root-warnings js2-mode-ast))))
10610
10611 (defun js2-mode-show-warnings ()
10612 "Highlight strict-mode warnings."
10613 (when js2-mode-show-strict-warnings
10614 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10615 (js2-mode-show-warn-or-err e 'js2-warning))))
10616
10617 (defun js2-echo-error (old-point new-point)
10618 "Called by point-motion hooks."
10619 (let ((msg (get-text-property new-point 'help-echo)))
10620 (when (and (stringp msg) (or (not (current-message))
10621 (string= (current-message) "Quit")))
10622 (message msg))))
10623
10624 (defalias #'js2-echo-help #'js2-echo-error)
10625
10626 (defun js2-line-break (&optional soft)
10627 "Break line at point and indent, continuing comment if within one.
10628 If inside a string, and `js2-concat-multiline-strings' is not
10629 nil, turn it into concatenation."
10630 (interactive)
10631 (let ((parse-status (syntax-ppss)))
10632 (cond
10633 ;; Check if we're inside a string.
10634 ((nth 3 parse-status)
10635 (if js2-concat-multiline-strings
10636 (js2-mode-split-string parse-status)
10637 (insert "\n")))
10638 ;; Check if inside a block comment.
10639 ((nth 4 parse-status)
10640 (js2-mode-extend-comment (nth 8 parse-status)))
10641 (t
10642 (newline-and-indent)))))
10643
10644 (defun js2-mode-split-string (parse-status)
10645 "Turn a newline in mid-string into a string concatenation.
10646 PARSE-STATUS is as documented in `parse-partial-sexp'."
10647 (let* ((col (current-column))
10648 (quote-char (nth 3 parse-status))
10649 (string-beg (nth 8 parse-status))
10650 (at-eol (eq js2-concat-multiline-strings 'eol)))
10651 (insert quote-char)
10652 (if at-eol
10653 (insert " +\n")
10654 (insert "\n"))
10655 (unless at-eol
10656 (insert "+ "))
10657 (js2-indent-line)
10658 (insert quote-char)
10659 (when (eolp)
10660 (insert quote-char)
10661 (backward-char 1))))
10662
10663 (defun js2-mode-extend-comment (start-pos)
10664 "Indent the line and, when inside a comment block, add comment prefix."
10665 (let (star single col first-line needs-close)
10666 (save-excursion
10667 (back-to-indentation)
10668 (when (< (point) start-pos)
10669 (goto-char start-pos))
10670 (cond
10671 ((looking-at "\\*[^/]")
10672 (setq star t
10673 col (current-column)))
10674 ((looking-at "/\\*")
10675 (setq star t
10676 first-line t
10677 col (1+ (current-column))))
10678 ((looking-at "//")
10679 (setq single t
10680 col (current-column)))))
10681 ;; Heuristic for whether we need to close the comment:
10682 ;; if we've got a parse error here, assume it's an unterminated
10683 ;; comment.
10684 (setq needs-close
10685 (or
10686 (eq (get-text-property (1- (point)) 'point-entered)
10687 'js2-echo-error)
10688 ;; The heuristic above doesn't work well when we're
10689 ;; creating a comment and there's another one downstream,
10690 ;; as our parser thinks this one ends at the end of the
10691 ;; next one. (You can have a /* inside a js block comment.)
10692 ;; So just close it if the next non-ws char isn't a *.
10693 (and first-line
10694 (eolp)
10695 (save-excursion
10696 (skip-chars-forward " \t\r\n")
10697 (not (eq (char-after) ?*))))))
10698 (delete-horizontal-space)
10699 (insert "\n")
10700 (cond
10701 (star
10702 (indent-to col)
10703 (insert "* ")
10704 (if (and first-line needs-close)
10705 (save-excursion
10706 (insert "\n")
10707 (indent-to col)
10708 (insert "*/"))))
10709 ((and single
10710 (save-excursion
10711 (and (zerop (forward-line 1))
10712 (looking-at "\\s-*//"))))
10713 (indent-to col)
10714 (insert "// "))
10715 ;; Don't need to extend the comment after all.
10716 (js2-indent-line))))
10717
10718 (defun js2-beginning-of-line ()
10719 "Toggles point between bol and first non-whitespace char in line.
10720 Also moves past comment delimiters when inside comments."
10721 (interactive)
10722 (let (node beg)
10723 (cond
10724 ((bolp)
10725 (back-to-indentation))
10726 ((looking-at "//")
10727 (skip-chars-forward "/ \t"))
10728 ((and (eq (char-after) ?*)
10729 (setq node (js2-comment-at-point))
10730 (memq (js2-comment-node-format node) '(jsdoc block))
10731 (save-excursion
10732 (skip-chars-backward " \t")
10733 (bolp)))
10734 (skip-chars-forward "\* \t"))
10735 (t
10736 (goto-char (point-at-bol))))))
10737
10738 (defun js2-end-of-line ()
10739 "Toggles point between eol and last non-whitespace char in line."
10740 (interactive)
10741 (if (eolp)
10742 (skip-chars-backward " \t")
10743 (goto-char (point-at-eol))))
10744
10745 (defsubst js2-mode-inside-string ()
10746 "Return non-nil if inside a string.
10747 Actually returns the quote character that begins the string."
10748 (nth 3 (syntax-ppss)))
10749
10750 (defun js2-mode-inside-comment-or-string ()
10751 "Return non-nil if inside a comment or string."
10752 (or
10753 (let ((comment-start
10754 (save-excursion
10755 (goto-char (point-at-bol))
10756 (if (re-search-forward "//" (point-at-eol) t)
10757 (match-beginning 0)))))
10758 (and comment-start
10759 (<= comment-start (point))))
10760 (let ((parse-state (syntax-ppss)))
10761 (or (nth 3 parse-state)
10762 (nth 4 parse-state)))))
10763
10764
10765 (defun js2-insert-catch-skel (try-pos)
10766 "Complete a try/catch block after inserting a { following a try keyword.
10767 Rationale is that a try always needs a catch or a finally, and the catch is
10768 the more likely of the two.
10769
10770 TRY-POS is the buffer position of the try keyword. The open-curly should
10771 already have been inserted."
10772 (insert "{")
10773 (let ((try-col (save-excursion
10774 (goto-char try-pos)
10775 (current-column))))
10776 (insert "\n")
10777 (undo-boundary)
10778 (js2-indent-line) ;; indent the blank line where cursor will end up
10779 (save-excursion
10780 (insert "\n")
10781 (indent-to try-col)
10782 (insert "} catch (x) {\n\n")
10783 (indent-to try-col)
10784 (insert "}"))))
10785
10786
10787 (defun js2-mode-wait-for-parse (callback)
10788 "Invoke CALLBACK when parsing is finished.
10789 If parsing is already finished, calls CALLBACK immediately."
10790 (if (not js2-mode-buffer-dirty-p)
10791 (funcall callback)
10792 (push callback js2-mode-pending-parse-callbacks)
10793 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10794
10795 (defun js2-mode-parse-finished ()
10796 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10797 ;; We can't let errors propagate up, since it prevents the
10798 ;; `js2-parse' method from completing normally and returning
10799 ;; the ast, which makes things mysteriously not work right.
10800 (unwind-protect
10801 (dolist (cb js2-mode-pending-parse-callbacks)
10802 (condition-case err
10803 (funcall cb)
10804 (error (message "%s" err))))
10805 (setq js2-mode-pending-parse-callbacks nil)))
10806
10807 (defun js2-mode-flag-region (from to flag)
10808 "Hide or show text from FROM to TO, according to FLAG.
10809 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10810 Returns the created overlay if FLAG is non-nil."
10811 (remove-overlays from to 'invisible 'js2-outline)
10812 (when flag
10813 (let ((o (make-overlay from to)))
10814 (overlay-put o 'invisible 'js2-outline)
10815 (overlay-put o 'isearch-open-invisible
10816 'js2-isearch-open-invisible)
10817 o)))
10818
10819 ;; Function to be set as an outline-isearch-open-invisible' property
10820 ;; to the overlay that makes the outline invisible (see
10821 ;; `js2-mode-flag-region').
10822 (defun js2-isearch-open-invisible (overlay)
10823 ;; We rely on the fact that isearch places point on the matched text.
10824 (js2-mode-show-element))
10825
10826 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10827 "Return cons cell of bounds of folding overlay at POS.
10828 Returns nil if not found."
10829 (let ((overlays (overlays-at (or pos (point))))
10830 o)
10831 (while (and overlays
10832 (not o))
10833 (if (overlay-get (car overlays) 'invisible)
10834 (setq o (car overlays))
10835 (setq overlays (cdr overlays))))
10836 (if o
10837 (cons (overlay-start o) (overlay-end o)))))
10838
10839 (defun js2-mode-function-at-point (&optional pos)
10840 "Return the innermost function node enclosing current point.
10841 Returns nil if point is not in a function."
10842 (let ((node (js2-node-at-point pos)))
10843 (while (and node (not (js2-function-node-p node)))
10844 (setq node (js2-node-parent node)))
10845 (if (js2-function-node-p node)
10846 node)))
10847
10848 (defun js2-mode-toggle-element ()
10849 "Hide or show the foldable element at the point."
10850 (interactive)
10851 (let (comment fn pos)
10852 (save-excursion
10853 (cond
10854 ;; /* ... */ comment?
10855 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10856 (if (js2-mode-invisible-overlay-bounds
10857 (setq pos (+ 3 (js2-node-abs-pos comment))))
10858 (progn
10859 (goto-char pos)
10860 (js2-mode-show-element))
10861 (js2-mode-hide-element)))
10862 ;; //-comment?
10863 ((save-excursion
10864 (back-to-indentation)
10865 (looking-at js2-mode-//-comment-re))
10866 (js2-mode-toggle-//-comment))
10867 ;; function?
10868 ((setq fn (js2-mode-function-at-point))
10869 (setq pos (and (js2-function-node-body fn)
10870 (js2-node-abs-pos (js2-function-node-body fn))))
10871 (goto-char (1+ pos))
10872 (if (js2-mode-invisible-overlay-bounds)
10873 (js2-mode-show-element)
10874 (js2-mode-hide-element)))
10875 (t
10876 (message "Nothing at point to hide or show"))))))
10877
10878 (defun js2-mode-hide-element ()
10879 "Fold/hide contents of a block, showing ellipses.
10880 Show the hidden text with \\[js2-mode-show-element]."
10881 (interactive)
10882 (if js2-mode-buffer-dirty-p
10883 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10884 (let (node body beg end)
10885 (cond
10886 ((js2-mode-invisible-overlay-bounds)
10887 (message "already hidden"))
10888 (t
10889 (setq node (js2-node-at-point))
10890 (cond
10891 ((js2-block-comment-p node)
10892 (js2-mode-hide-comment node))
10893 (t
10894 (while (and node (not (js2-function-node-p node)))
10895 (setq node (js2-node-parent node)))
10896 (if (and node
10897 (setq body (js2-function-node-body node)))
10898 (progn
10899 (setq beg (js2-node-abs-pos body)
10900 end (+ beg (js2-node-len body)))
10901 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10902 (message "No collapsable element found at point"))))))))
10903
10904 (defun js2-mode-show-element ()
10905 "Show the hidden element at current point."
10906 (interactive)
10907 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10908 (if bounds
10909 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10910 (message "Nothing to un-hide"))))
10911
10912 (defun js2-mode-show-all ()
10913 "Show all of the text in the buffer."
10914 (interactive)
10915 (js2-mode-flag-region (point-min) (point-max) nil))
10916
10917 (defun js2-mode-toggle-hide-functions ()
10918 (interactive)
10919 (if js2-mode-functions-hidden
10920 (js2-mode-show-functions)
10921 (js2-mode-hide-functions)))
10922
10923 (defun js2-mode-hide-functions ()
10924 "Hides all non-nested function bodies in the buffer.
10925 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10926 to open an individual entry."
10927 (interactive)
10928 (if js2-mode-buffer-dirty-p
10929 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10930 (if (null js2-mode-ast)
10931 (message "Oops - parsing failed")
10932 (setq js2-mode-functions-hidden t)
10933 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10934
10935 (defun js2-mode-function-hider (n endp)
10936 (when (not endp)
10937 (let ((tt (js2-node-type n))
10938 body beg end)
10939 (cond
10940 ((and (= tt js2-FUNCTION)
10941 (setq body (js2-function-node-body n)))
10942 (setq beg (js2-node-abs-pos body)
10943 end (+ beg (js2-node-len body)))
10944 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10945 nil) ; don't process children of function
10946 (t
10947 t))))) ; keep processing other AST nodes
10948
10949 (defun js2-mode-show-functions ()
10950 "Un-hide any folded function bodies in the buffer."
10951 (interactive)
10952 (setq js2-mode-functions-hidden nil)
10953 (save-excursion
10954 (goto-char (point-min))
10955 (while (/= (goto-char (next-overlay-change (point)))
10956 (point-max))
10957 (dolist (o (overlays-at (point)))
10958 (when (and (overlay-get o 'invisible)
10959 (not (overlay-get o 'comment)))
10960 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10961
10962 (defun js2-mode-hide-comment (n)
10963 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10964 3 ; /**
10965 2)) ; /*
10966 (beg (+ (js2-node-abs-pos n) head))
10967 (end (- (+ beg (js2-node-len n)) head 2))
10968 (o (js2-mode-flag-region beg end 'hide)))
10969 (overlay-put o 'comment t)))
10970
10971 (defun js2-mode-toggle-hide-comments ()
10972 "Folds all block comments in the buffer.
10973 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10974 to open an individual entry."
10975 (interactive)
10976 (if js2-mode-comments-hidden
10977 (js2-mode-show-comments)
10978 (js2-mode-hide-comments)))
10979
10980 (defun js2-mode-hide-comments ()
10981 (interactive)
10982 (if js2-mode-buffer-dirty-p
10983 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10984 (if (null js2-mode-ast)
10985 (message "Oops - parsing failed")
10986 (setq js2-mode-comments-hidden t)
10987 (dolist (n (js2-ast-root-comments js2-mode-ast))
10988 (let ((format (js2-comment-node-format n)))
10989 (when (js2-block-comment-p n)
10990 (js2-mode-hide-comment n))))
10991 (js2-mode-hide-//-comments)))
10992
10993 (defun js2-mode-extend-//-comment (direction)
10994 "Find start or end of a block of similar //-comment lines.
10995 DIRECTION is -1 to look back, 1 to look forward.
10996 INDENT is the indentation level to match.
10997 Returns the end-of-line position of the furthest adjacent
10998 //-comment line with the same indentation as the current line.
10999 If there is no such matching line, returns current end of line."
11000 (let ((pos (point-at-eol))
11001 (indent (current-indentation)))
11002 (save-excursion
11003 (while (and (zerop (forward-line direction))
11004 (looking-at js2-mode-//-comment-re)
11005 (eq indent (length (match-string 1))))
11006 (setq pos (point-at-eol))
11007 pos))))
11008
11009 (defun js2-mode-hide-//-comments ()
11010 "Fold adjacent 1-line comments, showing only snippet of first one."
11011 (let (beg end)
11012 (save-excursion
11013 (goto-char (point-min))
11014 (while (re-search-forward js2-mode-//-comment-re nil t)
11015 (setq beg (point)
11016 end (js2-mode-extend-//-comment 1))
11017 (unless (eq beg end)
11018 (overlay-put (js2-mode-flag-region beg end 'hide)
11019 'comment t))
11020 (goto-char end)
11021 (forward-char 1)))))
11022
11023 (defun js2-mode-toggle-//-comment ()
11024 "Fold or un-fold any multi-line //-comment at point.
11025 Caller should have determined that this line starts with a //-comment."
11026 (let* ((beg (point-at-eol))
11027 (end beg))
11028 (save-excursion
11029 (goto-char end)
11030 (if (js2-mode-invisible-overlay-bounds)
11031 (js2-mode-show-element)
11032 ;; else hide the comment
11033 (setq beg (js2-mode-extend-//-comment -1)
11034 end (js2-mode-extend-//-comment 1))
11035 (unless (eq beg end)
11036 (overlay-put (js2-mode-flag-region beg end 'hide)
11037 'comment t))))))
11038
11039 (defun js2-mode-show-comments ()
11040 "Un-hide any hidden comments, leaving other hidden elements alone."
11041 (interactive)
11042 (setq js2-mode-comments-hidden nil)
11043 (save-excursion
11044 (goto-char (point-min))
11045 (while (/= (goto-char (next-overlay-change (point)))
11046 (point-max))
11047 (dolist (o (overlays-at (point)))
11048 (when (overlay-get o 'comment)
11049 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11050
11051 (defun js2-mode-display-warnings-and-errors ()
11052 "Turn on display of warnings and errors."
11053 (interactive)
11054 (setq js2-mode-show-parse-errors t
11055 js2-mode-show-strict-warnings t)
11056 (js2-reparse 'force))
11057
11058 (defun js2-mode-hide-warnings-and-errors ()
11059 "Turn off display of warnings and errors."
11060 (interactive)
11061 (setq js2-mode-show-parse-errors nil
11062 js2-mode-show-strict-warnings nil)
11063 (js2-reparse 'force))
11064
11065 (defun js2-mode-toggle-warnings-and-errors ()
11066 "Toggle the display of warnings and errors.
11067 Some users don't like having warnings/errors reported while they type."
11068 (interactive)
11069 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11070 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11071 (if (called-interactively-p 'any)
11072 (message "warnings and errors %s"
11073 (if js2-mode-show-parse-errors
11074 "enabled"
11075 "disabled")))
11076 (js2-reparse 'force))
11077
11078 (defun js2-mode-customize ()
11079 (interactive)
11080 (customize-group 'js2-mode))
11081
11082 (defun js2-mode-forward-sexp (&optional arg)
11083 "Move forward across one statement or balanced expression.
11084 With ARG, do it that many times. Negative arg -N means
11085 move backward across N balanced expressions."
11086 (interactive "p")
11087 (setq arg (or arg 1))
11088 (save-restriction
11089 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11090 (js2-reparse))
11091 (let ((scan-msg "Containing expression ends prematurely")
11092 node (start (point)) pos lp rp child)
11093 (cond
11094 ;; backward-sexp
11095 ;; could probably make this better for some cases:
11096 ;; - if in statement block (e.g. function body), go to parent
11097 ;; - infix exprs like (foo in bar) - maybe go to beginning
11098 ;; of infix expr if in the right-side expression?
11099 ((and arg (minusp arg))
11100 (dotimes (i (- arg))
11101 (js2-backward-sws)
11102 (forward-char -1) ; enter the node we backed up to
11103 (when (setq node (js2-node-at-point (point) t))
11104 (setq pos (js2-node-abs-pos node))
11105 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11106 (setq lp (car parens)
11107 rp (cdr parens))))
11108 (goto-char
11109 (or (when (and lp (> start lp))
11110 (if (and rp (<= start rp))
11111 (if (setq child (js2-node-closest-child node (point) lp t))
11112 (js2-node-abs-pos child)
11113 (goto-char start)
11114 (signal 'scan-error (list scan-msg lp lp)))
11115 lp))
11116 pos
11117 (point-min)))))
11118 (t
11119 ;; forward-sexp
11120 (js2-forward-sws)
11121 (dotimes (i arg)
11122 (js2-forward-sws)
11123 (when (setq node (js2-node-at-point (point) t))
11124 (setq pos (js2-node-abs-pos node))
11125 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11126 (setq lp (car parens)
11127 rp (cdr parens))))
11128 (goto-char
11129 (or (when (and rp (<= start rp))
11130 (if (> start lp)
11131 (if (setq child (js2-node-closest-child node (point) rp))
11132 (js2-node-abs-end child)
11133 (goto-char start)
11134 (signal 'scan-error (list scan-msg rp (1+ rp))))
11135 (1+ rp)))
11136 (and pos
11137 (+ pos
11138 (js2-node-len
11139 (if (js2-expr-stmt-node-p (js2-node-parent node))
11140 ;; stop after the semicolon
11141 (js2-node-parent node)
11142 node))))
11143 (point-max))))))))
11144
11145 (defun js2-mode-forward-sexp-parens (node abs-pos)
11146 (cond
11147 ((or (js2-array-node-p node)
11148 (js2-object-node-p node)
11149 (js2-array-comp-node-p node)
11150 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11151 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11152 ((js2-paren-expr-node-p node)
11153 (let ((lp (js2-node-lp node))
11154 (rp (js2-node-rp node)))
11155 (cons (when lp (+ abs-pos lp))
11156 (when rp (+ abs-pos rp)))))))
11157
11158 (defun js2-node-closest-child (parent point limit &optional before)
11159 (let* ((parent-pos (js2-node-abs-pos parent))
11160 (rpoint (- point parent-pos))
11161 (rlimit (- limit parent-pos))
11162 (min (min rpoint rlimit))
11163 (max (max rpoint rlimit))
11164 found)
11165 (catch 'done
11166 (js2-visit-ast
11167 parent
11168 (lambda (node end-p)
11169 (if (eq node parent)
11170 t
11171 (let ((pos (js2-node-pos node)) ;; Both relative values.
11172 (end (+ (js2-node-pos node) (js2-node-len node))))
11173 (when (and (>= pos min) (<= end max)
11174 (if before (< pos rpoint) (> end rpoint)))
11175 (setq found node))
11176 (when (> end rpoint)
11177 (throw 'done nil)))
11178 nil))))
11179 found))
11180
11181 (defun js2-errors ()
11182 "Return a list of errors found."
11183 (and js2-mode-ast
11184 (js2-ast-root-errors js2-mode-ast)))
11185
11186 (defun js2-warnings ()
11187 "Return a list of warnings found."
11188 (and js2-mode-ast
11189 (js2-ast-root-warnings js2-mode-ast)))
11190
11191 (defun js2-have-errors-p ()
11192 "Return non-nil if any parse errors or warnings were found."
11193 (or (js2-errors) (js2-warnings)))
11194
11195 (defun js2-errors-and-warnings ()
11196 "Return a copy of the concatenated errors and warnings lists.
11197 They are appended: first the errors, then the warnings.
11198 Entries are of the form (MSG BEG END)."
11199 (when js2-mode-ast
11200 (append (js2-ast-root-errors js2-mode-ast)
11201 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11202
11203 (defun js2-next-error (&optional arg reset)
11204 "Move to next parse error.
11205 Typically invoked via \\[next-error].
11206 ARG is the number of errors, forward or backward, to move.
11207 RESET means start over from the beginning."
11208 (interactive "p")
11209 (if (not (or (js2-errors) (js2-warnings)))
11210 (message "No errors")
11211 (when reset
11212 (goto-char (point-min)))
11213 (let* ((errs (js2-errors-and-warnings))
11214 (continue t)
11215 (start (point))
11216 (count (or arg 1))
11217 (backward (minusp count))
11218 (sorter (if backward '> '<))
11219 (stopper (if backward '< '>))
11220 (count (abs count))
11221 all-errs err)
11222 ;; Sort by start position.
11223 (setq errs (sort errs (lambda (e1 e2)
11224 (funcall sorter (second e1) (second e2))))
11225 all-errs errs)
11226 ;; Find nth error with pos > start.
11227 (while (and errs continue)
11228 (when (funcall stopper (cadar errs) start)
11229 (setq err (car errs))
11230 (if (zerop (decf count))
11231 (setq continue nil)))
11232 (setq errs (cdr errs)))
11233 (if err
11234 (goto-char (second err))
11235 ;; Wrap around to first error.
11236 (goto-char (second (car all-errs)))
11237 ;; If we were already on it, echo msg again.
11238 (if (= (point) start)
11239 (js2-echo-error (point) (point)))))))
11240
11241 (defun js2-down-mouse-3 ()
11242 "Make right-click move the point to the click location.
11243 This makes right-click context menu operations a bit more intuitive.
11244 The point will not move if the region is active, however, to avoid
11245 destroying the region selection."
11246 (interactive)
11247 (when (and js2-move-point-on-right-click
11248 (not mark-active))
11249 (let ((e last-input-event))
11250 (ignore-errors
11251 (goto-char (cadadr e))))))
11252
11253 (defun js2-mode-create-imenu-index ()
11254 "Return an alist for `imenu--index-alist'."
11255 ;; This is built up in `js2-parse-record-imenu' during parsing.
11256 (when js2-mode-ast
11257 ;; if we have an ast but no recorder, they're requesting a rescan
11258 (unless js2-imenu-recorder
11259 (js2-reparse 'force))
11260 (prog1
11261 (js2-build-imenu-index)
11262 (setq js2-imenu-recorder nil
11263 js2-imenu-function-map nil))))
11264
11265 (defun js2-mode-find-tag ()
11266 "Replacement for `find-tag-default'.
11267 `find-tag-default' returns a ridiculous answer inside comments."
11268 (let (beg end)
11269 (js2-with-underscore-as-word-syntax
11270 (save-excursion
11271 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11272 (looking-back "[A-Za-z0-9_$]"))
11273 (setq beg (progn (forward-word -1) (point))
11274 end (progn (forward-word 1) (point)))
11275 (setq beg (progn (forward-word 1) (point))
11276 end (progn (forward-word -1) (point))))
11277 (replace-regexp-in-string
11278 "[\"']" ""
11279 (buffer-substring-no-properties beg end))))))
11280
11281 (defun js2-mode-forward-sibling ()
11282 "Move to the end of the sibling following point in parent.
11283 Returns non-nil if successful, or nil if there was no following sibling."
11284 (let* ((node (js2-node-at-point))
11285 (parent (js2-mode-find-enclosing-fn node))
11286 sib)
11287 (when (setq sib (js2-node-find-child-after (point) parent))
11288 (goto-char (+ (js2-node-abs-pos sib)
11289 (js2-node-len sib))))))
11290
11291 (defun js2-mode-backward-sibling ()
11292 "Move to the beginning of the sibling node preceding point in parent.
11293 Parent is defined as the enclosing script or function."
11294 (let* ((node (js2-node-at-point))
11295 (parent (js2-mode-find-enclosing-fn node))
11296 sib)
11297 (when (setq sib (js2-node-find-child-before (point) parent))
11298 (goto-char (js2-node-abs-pos sib)))))
11299
11300 (defun js2-beginning-of-defun (&optional arg)
11301 "Go to line on which current function starts, and return t on success.
11302 If we're not in a function or already at the beginning of one, go
11303 to beginning of previous script-level element.
11304 With ARG N, do that N times. If N is negative, move forward."
11305 (setq arg (or arg 1))
11306 (if (plusp arg)
11307 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11308 (when (cond
11309 ((js2-function-node-p parent)
11310 (goto-char (js2-node-abs-pos parent)))
11311 (t
11312 (js2-mode-backward-sibling)))
11313 (if (> arg 1)
11314 (js2-beginning-of-defun (1- arg))
11315 t)))
11316 (when (js2-end-of-defun)
11317 (if (>= arg -1)
11318 (js2-beginning-of-defun 1)
11319 (js2-beginning-of-defun (1+ arg))))))
11320
11321 (defun js2-end-of-defun ()
11322 "Go to the char after the last position of the current function
11323 or script-level element."
11324 (let* ((node (js2-node-at-point))
11325 (parent (or (and (js2-function-node-p node) node)
11326 (js2-node-parent-script-or-fn node)))
11327 script)
11328 (unless (js2-function-node-p parent)
11329 ;; Use current script-level node, or, if none, the next one.
11330 (setq script (or parent node)
11331 parent (js2-node-find-child-before (point) script))
11332 (when (or (null parent)
11333 (>= (point) (+ (js2-node-abs-pos parent)
11334 (js2-node-len parent))))
11335 (setq parent (js2-node-find-child-after (point) script))))
11336 (when parent
11337 (goto-char (+ (js2-node-abs-pos parent)
11338 (js2-node-len parent))))))
11339
11340 (defun js2-mark-defun (&optional allow-extend)
11341 "Put mark at end of this function, point at beginning.
11342 The function marked is the one that contains point.
11343
11344 Interactively, if this command is repeated,
11345 or (in Transient Mark mode) if the mark is active,
11346 it marks the next defun after the ones already marked."
11347 (interactive "p")
11348 (let (extended)
11349 (when (and allow-extend
11350 (or (and (eq last-command this-command) (mark t))
11351 (and transient-mark-mode mark-active)))
11352 (let ((sib (save-excursion
11353 (goto-char (mark))
11354 (if (js2-mode-forward-sibling)
11355 (point))))
11356 node)
11357 (if sib
11358 (progn
11359 (set-mark sib)
11360 (setq extended t))
11361 ;; no more siblings - try extending to enclosing node
11362 (goto-char (mark t)))))
11363 (when (not extended)
11364 (let ((node (js2-node-at-point (point) t)) ; skip comments
11365 ast fn stmt parent beg end)
11366 (when (js2-ast-root-p node)
11367 (setq ast node
11368 node (or (js2-node-find-child-after (point) node)
11369 (js2-node-find-child-before (point) node))))
11370 ;; only mark whole buffer if we can't find any children
11371 (if (null node)
11372 (setq node ast))
11373 (if (js2-function-node-p node)
11374 (setq parent node)
11375 (setq fn (js2-mode-find-enclosing-fn node)
11376 stmt (if (or (null fn)
11377 (js2-ast-root-p fn))
11378 (js2-mode-find-first-stmt node))
11379 parent (or stmt fn)))
11380 (setq beg (js2-node-abs-pos parent)
11381 end (+ beg (js2-node-len parent)))
11382 (push-mark beg)
11383 (goto-char end)
11384 (exchange-point-and-mark)))))
11385
11386 (defun js2-narrow-to-defun ()
11387 "Narrow to the function enclosing point."
11388 (interactive)
11389 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11390 (fn (if (js2-script-node-p node)
11391 node
11392 (js2-mode-find-enclosing-fn node)))
11393 (beg (js2-node-abs-pos fn)))
11394 (unless (js2-ast-root-p fn)
11395 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11396
11397 (provide 'js2-mode)
11398
11399 ;;; js2-mode.el ends here