]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Merge branch 'master' of github.com:leoliu/ggtags
[gnu-emacs-elpa] / packages / js2-mode / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2013 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20130619
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code is mentioned here for posterity, it has
84 ;; outdated information and is mostly unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 ;;; Variables
207
208 (defun js2-mark-safe-local (name pred)
209 "Make the variable NAME buffer-local and mark it as safe file-local
210 variable with predicate PRED."
211 (make-variable-buffer-local name)
212 (put name 'safe-local-variable pred))
213
214 (defcustom js2-highlight-level 2
215 "Amount of syntax highlighting to perform.
216 0 or a negative value means none.
217 1 adds basic syntax highlighting.
218 2 adds highlighting of some Ecma built-in properties.
219 3 adds highlighting of many Ecma built-in functions."
220 :group 'js2-mode
221 :type '(choice (const :tag "None" 0)
222 (const :tag "Basic" 1)
223 (const :tag "Include Properties" 2)
224 (const :tag "Include Functions" 3)))
225
226 (defvar js2-mode-dev-mode-p nil
227 "Non-nil if running in development mode. Normally nil.")
228
229 (defgroup js2-mode nil
230 "An improved JavaScript mode."
231 :group 'languages)
232
233 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
234 (numberp c-basic-offset))
235 c-basic-offset
236 4)
237 "Number of spaces to indent nested statements.
238 Similar to `c-basic-offset'."
239 :group 'js2-mode
240 :type 'integer)
241 (js2-mark-safe-local 'js2-basic-offset 'integerp)
242
243 (defcustom js2-bounce-indent-p nil
244 "Non-nil to have indent-line function choose among alternatives.
245 If nil, the indent-line function will indent to a predetermined column
246 based on heuristic guessing. If non-nil, then if the current line is
247 already indented to that predetermined column, indenting will choose
248 another likely column and indent to that spot. Repeated invocation of
249 the indent-line function will cycle among the computed alternatives.
250 See the function `js2-bounce-indent' for details. When it is non-nil,
251 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-pretty-multiline-declarations t
256 "Non-nil to line up multiline declarations vertically:
257
258 var a = 10,
259 b = 20,
260 c = 30;
261
262 If the value is not `all', and the first assigned value in
263 declaration is a function/array/object literal spanning several
264 lines, it won't be indented additionally:
265
266 var o = { var bar = 2,
267 foo: 3 vs. o = {
268 }, foo: 3
269 bar = 2; };"
270 :group 'js2-mode
271 :type 'symbol)
272 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
273
274 (defcustom js2-idle-timer-delay 0.2
275 "Delay in secs before re-parsing after user makes changes.
276 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
277 :type 'number
278 :group 'js2-mode)
279 (make-variable-buffer-local 'js2-idle-timer-delay)
280
281 (defcustom js2-dynamic-idle-timer-adjust 0
282 "Positive to adjust `js2-idle-timer-delay' based on file size.
283 The idea is that for short files, parsing is faster so we can be
284 more responsive to user edits without interfering with editing.
285 The buffer length in characters (typically bytes) is divided by
286 this value and used to multiply `js2-idle-timer-delay' for the
287 buffer. For example, a 21k file and 10k adjust yields 21k/10k
288 == 2, so js2-idle-timer-delay is multiplied by 2.
289 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
290 `js2-idle-timer-delay' is not dependent on the file size."
291 :type 'number
292 :group 'js2-mode)
293
294 (defcustom js2-concat-multiline-strings t
295 "When non-nil, `js2-line-break' in mid-string will make it a
296 string concatenation. When `eol', the '+' will be inserted at the
297 end of the line, otherwise, at the beginning of the next line."
298 :type '(choice (const t) (const eol) (const nil))
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-parse-errors t
302 "True to highlight parse errors."
303 :type 'boolean
304 :group 'js2-mode)
305
306 (defcustom js2-mode-show-strict-warnings t
307 "Non-nil to emit Ecma strict-mode warnings.
308 Some of the warnings can be individually disabled by other flags,
309 even if this flag is non-nil."
310 :type 'boolean
311 :group 'js2-mode)
312
313 (defcustom js2-strict-trailing-comma-warning t
314 "Non-nil to warn about trailing commas in array literals.
315 Ecma-262-5.1 allows them, but older versions of IE raise an error."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-strict-missing-semi-warning t
320 "Non-nil to warn about semicolon auto-insertion after statement.
321 Technically this is legal per Ecma-262, but some style guides disallow
322 depending on it."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-missing-semi-one-line-override nil
327 "Non-nil to permit missing semicolons in one-line functions.
328 In one-liner functions such as `function identity(x) {return x}'
329 people often omit the semicolon for a cleaner look. If you are
330 such a person, you can suppress the missing-semicolon warning
331 by setting this variable to t."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-strict-inconsistent-return-warning t
336 "Non-nil to warn about mixing returns with value-returns.
337 It's perfectly legal to have a `return' and a `return foo' in the
338 same function, but it's often an indicator of a bug, and it also
339 interferes with type inference (in systems that support it.)"
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-cond-assign-warning t
344 "Non-nil to warn about expressions like if (a = b).
345 This often should have been '==' instead of '='. If the warning
346 is enabled, you can suppress it on a per-expression basis by
347 parenthesizing the expression, e.g. if ((a = b)) ..."
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-var-redeclaration-warning t
352 "Non-nil to warn about redeclaring variables in a script or function."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-strict-var-hides-function-arg-warning t
357 "Non-nil to warn about a var decl hiding a function argument."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-skip-preprocessor-directives nil
362 "Non-nil to treat lines beginning with # as comments.
363 Useful for viewing Mozilla JavaScript source code."
364 :type 'boolean
365 :group 'js2-mode)
366
367 (defcustom js2-language-version 200
368 "Configures what JavaScript language version to recognize.
369 Currently versions 150, 160, 170, 180 and 200 are supported,
370 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
371 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
372 yield, and Array comprehensions, and 1.8 adds function closures."
373 :type 'integer
374 :group 'js2-mode)
375
376 (defcustom js2-allow-keywords-as-property-names t
377 "If non-nil, you can use JavaScript keywords as object property names.
378 Examples:
379
380 var foo = {int: 5, while: 6, continue: 7};
381 foo.return = 8;
382
383 Ecma-262 5.1 allows this syntax, but some engines still don't."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-instanceof-has-side-effects nil
388 "If non-nil, treats the instanceof operator as having side effects.
389 This is useful for xulrunner apps."
390 :type 'boolean
391 :group 'js2-mode)
392
393 (defcustom js2-move-point-on-right-click t
394 "Non-nil to move insertion point when you right-click.
395 This makes right-click context menu behavior a bit more intuitive,
396 since menu operations generally apply to the point. The exception
397 is if there is a region selection, in which case the point does -not-
398 move, so cut/copy/paste can work properly.
399
400 Note that IntelliJ moves the point, and Eclipse leaves it alone,
401 so this behavior is customizable."
402 :group 'js2-mode
403 :type 'boolean)
404
405 (defcustom js2-allow-rhino-new-expr-initializer t
406 "Non-nil to support a Rhino's experimental syntactic construct.
407
408 Rhino supports the ability to follow a `new' expression with an object
409 literal, which is used to set additional properties on the new object
410 after calling its constructor. Syntax:
411
412 new <expr> [ ( arglist ) ] [initializer]
413
414 Hence, this expression:
415
416 new Object {a: 1, b: 2}
417
418 results in an Object with properties a=1 and b=2. This syntax is
419 apparently not configurable in Rhino - it's currently always enabled,
420 as of Rhino version 1.7R2."
421 :type 'boolean
422 :group 'js2-mode)
423
424 (defcustom js2-allow-member-expr-as-function-name nil
425 "Non-nil to support experimental Rhino syntax for function names.
426
427 Rhino supports an experimental syntax configured via the Rhino Context
428 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
429
430 function <member-expr> ( [ arg-list ] ) { <body> }
431
432 Where member-expr is a non-parenthesized 'member expression', which
433 is anything at the grammar level of a new-expression or lower, meaning
434 any expression that does not involve infix or unary operators.
435
436 When <member-expr> is not a simple identifier, then it is syntactic
437 sugar for assigning the anonymous function to the <member-expr>. Hence,
438 this code:
439
440 function a.b().c[2] (x, y) { ... }
441
442 is rewritten as:
443
444 a.b().c[2] = function(x, y) {...}
445
446 which doesn't seem particularly useful, but Rhino permits it."
447 :type 'boolean
448 :group 'js2-mode)
449
450 ;; scanner variables
451
452 (defmacro js2-deflocal (name value &optional comment)
453 "Define a buffer-local variable NAME with VALUE and COMMENT."
454 `(progn
455 (defvar ,name ,value ,comment)
456 (make-variable-buffer-local ',name)))
457
458 ;; We record the start and end position of each token.
459 (js2-deflocal js2-token-beg 1)
460 (js2-deflocal js2-token-end -1)
461
462 (defvar js2-EOF_CHAR -1
463 "Represents end of stream. Distinct from js2-EOF token type.")
464
465 ;; I originally used symbols to represent tokens, but Rhino uses
466 ;; ints and then sets various flag bits in them, so ints it is.
467 ;; The upshot is that we need a `js2-' prefix in front of each name.
468 (defvar js2-ERROR -1)
469 (defvar js2-EOF 0)
470 (defvar js2-EOL 1)
471 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
472 (defvar js2-LEAVEWITH 3)
473 (defvar js2-RETURN 4)
474 (defvar js2-GOTO 5)
475 (defvar js2-IFEQ 6)
476 (defvar js2-IFNE 7)
477 (defvar js2-SETNAME 8)
478 (defvar js2-BITOR 9)
479 (defvar js2-BITXOR 10)
480 (defvar js2-BITAND 11)
481 (defvar js2-EQ 12)
482 (defvar js2-NE 13)
483 (defvar js2-LT 14)
484 (defvar js2-LE 15)
485 (defvar js2-GT 16)
486 (defvar js2-GE 17)
487 (defvar js2-LSH 18)
488 (defvar js2-RSH 19)
489 (defvar js2-URSH 20)
490 (defvar js2-ADD 21) ; infix plus
491 (defvar js2-SUB 22) ; infix minus
492 (defvar js2-MUL 23)
493 (defvar js2-DIV 24)
494 (defvar js2-MOD 25)
495 (defvar js2-NOT 26)
496 (defvar js2-BITNOT 27)
497 (defvar js2-POS 28) ; unary plus
498 (defvar js2-NEG 29) ; unary minus
499 (defvar js2-NEW 30)
500 (defvar js2-DELPROP 31)
501 (defvar js2-TYPEOF 32)
502 (defvar js2-GETPROP 33)
503 (defvar js2-GETPROPNOWARN 34)
504 (defvar js2-SETPROP 35)
505 (defvar js2-GETELEM 36)
506 (defvar js2-SETELEM 37)
507 (defvar js2-CALL 38)
508 (defvar js2-NAME 39) ; an identifier
509 (defvar js2-NUMBER 40)
510 (defvar js2-STRING 41)
511 (defvar js2-NULL 42)
512 (defvar js2-THIS 43)
513 (defvar js2-FALSE 44)
514 (defvar js2-TRUE 45)
515 (defvar js2-SHEQ 46) ; shallow equality (===)
516 (defvar js2-SHNE 47) ; shallow inequality (!==)
517 (defvar js2-REGEXP 48)
518 (defvar js2-BINDNAME 49)
519 (defvar js2-THROW 50)
520 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
521 (defvar js2-IN 52)
522 (defvar js2-INSTANCEOF 53)
523 (defvar js2-LOCAL_LOAD 54)
524 (defvar js2-GETVAR 55)
525 (defvar js2-SETVAR 56)
526 (defvar js2-CATCH_SCOPE 57)
527 (defvar js2-ENUM_INIT_KEYS 58)
528 (defvar js2-ENUM_INIT_VALUES 59)
529 (defvar js2-ENUM_INIT_ARRAY 60)
530 (defvar js2-ENUM_NEXT 61)
531 (defvar js2-ENUM_ID 62)
532 (defvar js2-THISFN 63)
533 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
534 (defvar js2-ARRAYLIT 65) ; array literal
535 (defvar js2-OBJECTLIT 66) ; object literal
536 (defvar js2-GET_REF 67) ; *reference
537 (defvar js2-SET_REF 68) ; *reference = something
538 (defvar js2-DEL_REF 69) ; delete reference
539 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
540 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
541 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
542
543 ;; XML support
544 (defvar js2-DEFAULTNAMESPACE 73)
545 (defvar js2-ESCXMLATTR 74)
546 (defvar js2-ESCXMLTEXT 75)
547 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
548 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
549 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
550 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
551
552 (defvar js2-first-bytecode js2-ENTERWITH)
553 (defvar js2-last-bytecode js2-REF_NS_NAME)
554
555 (defvar js2-TRY 80)
556 (defvar js2-SEMI 81) ; semicolon
557 (defvar js2-LB 82) ; left and right brackets
558 (defvar js2-RB 83)
559 (defvar js2-LC 84) ; left and right curly-braces
560 (defvar js2-RC 85)
561 (defvar js2-LP 86) ; left and right parens
562 (defvar js2-RP 87)
563 (defvar js2-COMMA 88) ; comma operator
564
565 (defvar js2-ASSIGN 89) ; simple assignment (=)
566 (defvar js2-ASSIGN_BITOR 90) ; |=
567 (defvar js2-ASSIGN_BITXOR 91) ; ^=
568 (defvar js2-ASSIGN_BITAND 92) ; &=
569 (defvar js2-ASSIGN_LSH 93) ; <<=
570 (defvar js2-ASSIGN_RSH 94) ; >>=
571 (defvar js2-ASSIGN_URSH 95) ; >>>=
572 (defvar js2-ASSIGN_ADD 96) ; +=
573 (defvar js2-ASSIGN_SUB 97) ; -=
574 (defvar js2-ASSIGN_MUL 98) ; *=
575 (defvar js2-ASSIGN_DIV 99) ; /=
576 (defvar js2-ASSIGN_MOD 100) ; %=
577
578 (defvar js2-first-assign js2-ASSIGN)
579 (defvar js2-last-assign js2-ASSIGN_MOD)
580
581 (defvar js2-HOOK 101) ; conditional (?:)
582 (defvar js2-COLON 102)
583 (defvar js2-OR 103) ; logical or (||)
584 (defvar js2-AND 104) ; logical and (&&)
585 (defvar js2-INC 105) ; increment/decrement (++ --)
586 (defvar js2-DEC 106)
587 (defvar js2-DOT 107) ; member operator (.)
588 (defvar js2-FUNCTION 108) ; function keyword
589 (defvar js2-EXPORT 109) ; export keyword
590 (defvar js2-IMPORT 110) ; import keyword
591 (defvar js2-IF 111) ; if keyword
592 (defvar js2-ELSE 112) ; else keyword
593 (defvar js2-SWITCH 113) ; switch keyword
594 (defvar js2-CASE 114) ; case keyword
595 (defvar js2-DEFAULT 115) ; default keyword
596 (defvar js2-WHILE 116) ; while keyword
597 (defvar js2-DO 117) ; do keyword
598 (defvar js2-FOR 118) ; for keyword
599 (defvar js2-BREAK 119) ; break keyword
600 (defvar js2-CONTINUE 120) ; continue keyword
601 (defvar js2-VAR 121) ; var keyword
602 (defvar js2-WITH 122) ; with keyword
603 (defvar js2-CATCH 123) ; catch keyword
604 (defvar js2-FINALLY 124) ; finally keyword
605 (defvar js2-VOID 125) ; void keyword
606 (defvar js2-RESERVED 126) ; reserved keywords
607
608 (defvar js2-EMPTY 127)
609
610 ;; Types used for the parse tree - never returned by scanner.
611
612 (defvar js2-BLOCK 128) ; statement block
613 (defvar js2-LABEL 129) ; label
614 (defvar js2-TARGET 130)
615 (defvar js2-LOOP 131)
616 (defvar js2-EXPR_VOID 132) ; expression statement in functions
617 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
618 (defvar js2-JSR 134)
619 (defvar js2-SCRIPT 135) ; top-level node for entire script
620 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
621 (defvar js2-USE_STACK 137)
622 (defvar js2-SETPROP_OP 138) ; x.y op= something
623 (defvar js2-SETELEM_OP 139) ; x[y] op= something
624 (defvar js2-LOCAL_BLOCK 140)
625 (defvar js2-SET_REF_OP 141) ; *reference op= something
626
627 ;; For XML support:
628 (defvar js2-DOTDOT 142) ; member operator (..)
629 (defvar js2-COLONCOLON 143) ; namespace::name
630 (defvar js2-XML 144) ; XML type
631 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
632 (defvar js2-XMLATTR 146) ; @
633 (defvar js2-XMLEND 147)
634
635 ;; Optimizer-only tokens
636 (defvar js2-TO_OBJECT 148)
637 (defvar js2-TO_DOUBLE 149)
638
639 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
640 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
641 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
642 (defvar js2-CONST 153)
643 (defvar js2-SETCONST 154)
644 (defvar js2-SETCONSTVAR 155)
645 (defvar js2-ARRAYCOMP 156)
646 (defvar js2-LETEXPR 157)
647 (defvar js2-WITHEXPR 158)
648 (defvar js2-DEBUGGER 159)
649
650 (defvar js2-COMMENT 160)
651 (defvar js2-ENUM 161) ; for "enum" reserved word
652 (defvar js2-TRIPLEDOT 162) ; for rest parameter
653
654 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
655
656 (defconst js2-debug-print-trees nil)
657
658 ;; Rhino accepts any string or stream as input. Emacs character
659 ;; processing works best in buffers, so we'll assume the input is a
660 ;; buffer. JavaScript strings can be copied into temp buffers before
661 ;; scanning them.
662
663 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
664 ;; They're the Emacs equivalent of instance variables, more or less.
665
666 (js2-deflocal js2-ts-dirty-line nil
667 "Token stream buffer-local variable.
668 Indicates stuff other than whitespace since start of line.")
669
670 (js2-deflocal js2-ts-regexp-flags nil
671 "Token stream buffer-local variable.")
672
673 (js2-deflocal js2-ts-string ""
674 "Token stream buffer-local variable.
675 Last string scanned.")
676
677 (js2-deflocal js2-ts-number nil
678 "Token stream buffer-local variable.
679 Last literal number scanned.")
680
681 (js2-deflocal js2-ts-hit-eof nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-line-start 0
685 "Token stream buffer-local variable.")
686
687 (js2-deflocal js2-ts-lineno 1
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-line-end-char -1
691 "Token stream buffer-local variable.")
692
693 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
694 "Token stream buffer-local variable.
695 Current scan position.")
696
697 (js2-deflocal js2-ts-is-xml-attribute nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-is-tag-content nil
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-xml-open-tags-count 0
704 "Token stream buffer-local variable.")
705
706 (js2-deflocal js2-ts-string-buffer nil
707 "Token stream buffer-local variable.
708 List of chars built up while scanning various tokens.")
709
710 (js2-deflocal js2-ts-comment-type nil
711 "Token stream buffer-local variable.")
712
713 ;;; Parser variables
714
715 (js2-deflocal js2-parsed-errors nil
716 "List of errors produced during scanning/parsing.")
717
718 (js2-deflocal js2-parsed-warnings nil
719 "List of warnings produced during scanning/parsing.")
720
721 (js2-deflocal js2-recover-from-parse-errors t
722 "Non-nil to continue parsing after a syntax error.
723
724 In recovery mode, the AST will be built in full, and any error
725 nodes will be flagged with appropriate error information. If
726 this flag is nil, a syntax error will result in an error being
727 signaled.
728
729 The variable is automatically buffer-local, because different
730 modes that use the parser will need different settings.")
731
732 (js2-deflocal js2-parse-hook nil
733 "List of callbacks for receiving parsing progress.")
734
735 (defvar js2-parse-finished-hook nil
736 "List of callbacks to notify when parsing finishes.
737 Not called if parsing was interrupted.")
738
739 (js2-deflocal js2-is-eval-code nil
740 "True if we're evaluating code in a string.
741 If non-nil, the tokenizer will record the token text, and the AST nodes
742 will record their source text. Off by default for IDE modes, since the
743 text is available in the buffer.")
744
745 (defvar js2-parse-ide-mode t
746 "Non-nil if the parser is being used for `js2-mode'.
747 If non-nil, the parser will set text properties for fontification
748 and the syntax table. The value should be nil when using the
749 parser as a frontend to an interpreter or byte compiler.")
750
751 ;;; Parser instance variables (buffer-local vars for js2-parse)
752
753 (defconst js2-clear-ti-mask #xFFFF
754 "Mask to clear token information bits.")
755
756 (defconst js2-ti-after-eol (lsh 1 16)
757 "Flag: first token of the source line.")
758
759 (defconst js2-ti-check-label (lsh 1 17)
760 "Flag: indicates to check for label.")
761
762 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
763
764 (js2-deflocal js2-compiler-generate-debug-info t)
765 (js2-deflocal js2-compiler-use-dynamic-scope nil)
766 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
767 (js2-deflocal js2-compiler-xml-available t)
768 (js2-deflocal js2-compiler-optimization-level 0)
769 (js2-deflocal js2-compiler-generating-source t)
770 (js2-deflocal js2-compiler-strict-mode nil)
771 (js2-deflocal js2-compiler-report-warning-as-error nil)
772 (js2-deflocal js2-compiler-generate-observer-count nil)
773 (js2-deflocal js2-compiler-activation-names nil)
774
775 ;; SKIP: sourceURI
776
777 ;; There's a compileFunction method in Context.java - may need it.
778 (js2-deflocal js2-called-by-compile-function nil
779 "True if `js2-parse' was called by `js2-compile-function'.
780 Will only be used when we finish implementing the interpreter.")
781
782 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
783
784 (js2-deflocal js2-current-flagged-token js2-EOF)
785 (js2-deflocal js2-current-token js2-EOF)
786
787 ;; SKIP: node factory - we're going to just call functions directly,
788 ;; and eventually go to a unified AST format.
789
790 (js2-deflocal js2-nesting-of-function 0)
791
792 (js2-deflocal js2-recorded-identifiers nil
793 "Tracks identifiers found during parsing.")
794
795 (js2-deflocal js2-is-in-destructuring nil
796 "True while parsing destructuring expression.")
797
798 (defcustom js2-global-externs nil
799 "A list of any extern names you'd like to consider always declared.
800 This list is global and is used by all `js2-mode' files.
801 You can create buffer-local externs list using `js2-additional-externs'.
802
803 There is also a buffer-local variable `js2-default-externs',
804 which is initialized by default to include the Ecma-262 externs
805 and the standard browser externs. The three lists are all
806 checked during highlighting."
807 :type 'list
808 :group 'js2-mode)
809
810 (js2-deflocal js2-default-externs nil
811 "Default external declarations.
812
813 These are currently only used for highlighting undeclared variables,
814 which only worries about top-level (unqualified) references.
815 As js2-mode's processing improves, we will flesh out this list.
816
817 The initial value is set to `js2-ecma-262-externs', unless some
818 of the `js2-include-?-externs' variables are set to t, in which
819 case the browser, Rhino and/or Node.js externs are also included.
820
821 See `js2-additional-externs' for more information.")
822
823 (defcustom js2-include-browser-externs t
824 "Non-nil to include browser externs in the master externs list.
825 If you work on JavaScript files that are not intended for browsers,
826 such as Mozilla Rhino server-side JavaScript, set this to nil.
827 See `js2-additional-externs' for more information about externs."
828 :type 'boolean
829 :group 'js2-mode)
830
831 (defcustom js2-include-rhino-externs nil
832 "Non-nil to include Mozilla Rhino externs in the master externs list.
833 See `js2-additional-externs' for more information about externs."
834 :type 'boolean
835 :group 'js2-mode)
836
837 (defcustom js2-include-node-externs nil
838 "Non-nil to include Node.js externs in the master externs list.
839 See `js2-additional-externs' for more information about externs."
840 :type 'boolean
841 :group 'js2-mode)
842
843 (js2-deflocal js2-additional-externs nil
844 "A buffer-local list of additional external declarations.
845 It is used to decide whether variables are considered undeclared
846 for purposes of highlighting.
847
848 Each entry is a Lisp string. The string should be the fully qualified
849 name of an external entity. All externs should be added to this list,
850 so that as js2-mode's processing improves it can take advantage of them.
851
852 You may want to declare your externs in three ways.
853 First, you can add externs that are valid for all your JavaScript files.
854 You should probably do this by adding them to `js2-global-externs', which
855 is a global list used for all js2-mode files.
856
857 Next, you can add a function to `js2-init-hook' that adds additional
858 externs appropriate for the specific file, perhaps based on its path.
859 These should go in `js2-additional-externs', which is buffer-local.
860
861 Third, you can use JSLint's global declaration, as long as
862 `js2-include-jslint-globals' is non-nil, which see.
863
864 Finally, you can add a function to `js2-post-parse-callbacks',
865 which is called after parsing completes, and `js2-mode-ast' is bound to
866 the root of the parse tree. At this stage you can set up an AST
867 node visitor using `js2-visit-ast' and examine the parse tree
868 for specific import patterns that may imply the existence of
869 other externs, possibly tied to your build system. These should also
870 be added to `js2-additional-externs'.
871
872 Your post-parse callback may of course also use the simpler and
873 faster (but perhaps less robust) approach of simply scanning the
874 buffer text for your imports, using regular expressions.")
875
876 ;; SKIP: decompiler
877 ;; SKIP: encoded-source
878
879 ;;; The following variables are per-function and should be saved/restored
880 ;;; during function parsing...
881
882 (js2-deflocal js2-current-script-or-fn nil)
883 (js2-deflocal js2-current-scope nil)
884 (js2-deflocal js2-nesting-of-with 0)
885 (js2-deflocal js2-label-set nil
886 "An alist mapping label names to nodes.")
887
888 (js2-deflocal js2-loop-set nil)
889 (js2-deflocal js2-loop-and-switch-set nil)
890 (js2-deflocal js2-has-return-value nil)
891 (js2-deflocal js2-end-flags 0)
892
893 ;;; ...end of per function variables
894
895 ;; Without 2-token lookahead, labels are a problem.
896 ;; These vars store the token info of the last matched name,
897 ;; iff it wasn't the last matched token. Only valid in some contexts.
898 (defvar js2-prev-name-token-start nil)
899 (defvar js2-prev-name-token-string nil)
900
901 (defsubst js2-save-name-token-data (pos name)
902 (setq js2-prev-name-token-start pos
903 js2-prev-name-token-string name))
904
905 ;; These flags enumerate the possible ways a statement/function can
906 ;; terminate. These flags are used by endCheck() and by the Parser to
907 ;; detect inconsistent return usage.
908 ;;
909 ;; END_UNREACHED is reserved for code paths that are assumed to always be
910 ;; able to execute (example: throw, continue)
911 ;;
912 ;; END_DROPS_OFF indicates if the statement can transfer control to the
913 ;; next one. Statement such as return dont. A compound statement may have
914 ;; some branch that drops off control to the next statement.
915 ;;
916 ;; END_RETURNS indicates that the statement can return (without arguments)
917 ;; END_RETURNS_VALUE indicates that the statement can return a value.
918 ;;
919 ;; A compound statement such as
920 ;; if (condition) {
921 ;; return value;
922 ;; }
923 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
924
925 (defconst js2-end-unreached #x0)
926 (defconst js2-end-drops-off #x1)
927 (defconst js2-end-returns #x2)
928 (defconst js2-end-returns-value #x4)
929 (defconst js2-end-yields #x8)
930
931 ;; Rhino awkwardly passes a statementLabel parameter to the
932 ;; statementHelper() function, the main statement parser, which
933 ;; is then used by quite a few of the sub-parsers. We just make
934 ;; it a buffer-local variable and make sure it's cleaned up properly.
935 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
936
937 ;; Similarly, Rhino passes an inForInit boolean through about half
938 ;; the expression parsers. We use a dynamically-scoped variable,
939 ;; which makes it easier to funcall the parsers individually without
940 ;; worrying about whether they take the parameter or not.
941 (js2-deflocal js2-in-for-init nil)
942 (js2-deflocal js2-temp-name-counter 0)
943 (js2-deflocal js2-parse-stmt-count 0)
944
945 (defsubst js2-get-next-temp-name ()
946 (format "$%d" (incf js2-temp-name-counter)))
947
948 (defvar js2-parse-interruptable-p t
949 "Set this to nil to force parse to continue until finished.
950 This will mostly be useful for interpreters.")
951
952 (defvar js2-statements-per-pause 50
953 "Pause after this many statements to check for user input.
954 If user input is pending, stop the parse and discard the tree.
955 This makes for a smoother user experience for large files.
956 You may have to wait a second or two before the highlighting
957 and error-reporting appear, but you can always type ahead if
958 you wish. This appears to be more or less how Eclipse, IntelliJ
959 and other editors work.")
960
961 (js2-deflocal js2-record-comments t
962 "Instructs the scanner to record comments in `js2-scanned-comments'.")
963
964 (js2-deflocal js2-scanned-comments nil
965 "List of all comments from the current parse.")
966
967 (defcustom js2-mode-indent-inhibit-undo nil
968 "Non-nil to disable collection of Undo information when indenting lines.
969 Some users have requested this behavior. It's nil by default because
970 other Emacs modes don't work this way."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defcustom js2-mode-indent-ignore-first-tab nil
975 "If non-nil, ignore first TAB keypress if we look indented properly.
976 It's fairly common for users to navigate to an already-indented line
977 and press TAB for reassurance that it's been indented. For this class
978 of users, we want the first TAB press on a line to be ignored if the
979 line is already indented to one of the precomputed alternatives.
980
981 This behavior is only partly implemented. If you TAB-indent a line,
982 navigate to another line, and then navigate back, it fails to clear
983 the last-indented variable, so it thinks you've already hit TAB once,
984 and performs the indent. A full solution would involve getting on the
985 point-motion hooks for the entire buffer. If we come across another
986 use cases that requires watching point motion, I'll consider doing it.
987
988 If you set this variable to nil, then the TAB key will always change
989 the indentation of the current line, if more than one alternative
990 indentation spot exists."
991 :type 'boolean
992 :group 'js2-mode)
993
994 (defvar js2-indent-hook nil
995 "A hook for user-defined indentation rules.
996
997 Functions on this hook should expect two arguments: (LIST INDEX)
998 The LIST argument is the list of computed indentation points for
999 the current line. INDEX is the list index of the indentation point
1000 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1001 indent function is not going to change the current line indentation.
1002
1003 If a hook function on this list returns a non-nil value, then
1004 `js2-bounce-indent' assumes the hook function has performed its own
1005 indentation, and will do nothing. If all hook functions on the list
1006 return nil, then `js2-bounce-indent' will use its computed indentation
1007 and reindent the line.
1008
1009 When hook functions on this hook list are called, the variable
1010 `js2-mode-ast' may or may not be set, depending on whether the
1011 parse tree is available. If the variable is nil, you can pass a
1012 callback to `js2-mode-wait-for-parse', and your callback will be
1013 called after the new parse tree is built. This can take some time
1014 in large files.")
1015
1016 (defface js2-warning
1017 `((((class color) (background light))
1018 (:underline "orange"))
1019 (((class color) (background dark))
1020 (:underline "orange"))
1021 (t (:underline t)))
1022 "Face for JavaScript warnings."
1023 :group 'js2-mode)
1024
1025 (defface js2-error
1026 `((((class color) (background light))
1027 (:foreground "red"))
1028 (((class color) (background dark))
1029 (:foreground "red"))
1030 (t (:foreground "red")))
1031 "Face for JavaScript errors."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-tag
1035 '((t :foreground "SlateGray"))
1036 "Face used to highlight @whatever tags in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-type
1040 '((t :foreground "SteelBlue"))
1041 "Face used to highlight {FooBar} types in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-value
1045 '((t :foreground "PeachPuff3"))
1046 "Face used to highlight tag values in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-function-param
1050 '((t :foreground "SeaGreen"))
1051 "Face used to highlight function parameters in javascript."
1052 :group 'js2-mode)
1053
1054 (defface js2-instance-member
1055 '((t :foreground "DarkOrchid"))
1056 "Face used to highlight instance variables in javascript.
1057 Not currently used."
1058 :group 'js2-mode)
1059
1060 (defface js2-private-member
1061 '((t :foreground "PeachPuff3"))
1062 "Face used to highlight calls to private methods in javascript.
1063 Not currently used."
1064 :group 'js2-mode)
1065
1066 (defface js2-private-function-call
1067 '((t :foreground "goldenrod"))
1068 "Face used to highlight calls to private functions in javascript.
1069 Not currently used."
1070 :group 'js2-mode)
1071
1072 (defface js2-jsdoc-html-tag-name
1073 '((((class color) (min-colors 88) (background light))
1074 (:foreground "rosybrown"))
1075 (((class color) (min-colors 8) (background dark))
1076 (:foreground "yellow"))
1077 (((class color) (min-colors 8) (background light))
1078 (:foreground "magenta")))
1079 "Face used to highlight jsdoc html tag names"
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-html-tag-delimiter
1083 '((((class color) (min-colors 88) (background light))
1084 (:foreground "dark khaki"))
1085 (((class color) (min-colors 8) (background dark))
1086 (:foreground "green"))
1087 (((class color) (min-colors 8) (background light))
1088 (:foreground "green")))
1089 "Face used to highlight brackets in jsdoc html tags."
1090 :group 'js2-mode)
1091
1092 (defface js2-external-variable
1093 '((t :foreground "orange"))
1094 "Face used to highlight undeclared variable identifiers.")
1095
1096 (defcustom js2-init-hook nil
1097 "List of functions to be called after `js2-mode' or
1098 `js2-minor-mode' has initialized all variables, before parsing
1099 the buffer for the first time."
1100 :type 'hook
1101 :group 'js2-mode
1102 :version "20130608")
1103
1104 (defcustom js2-post-parse-callbacks nil
1105 "List of callback functions invoked after parsing finishes.
1106 Currently, the main use for this function is to add synthetic
1107 declarations to `js2-recorded-identifiers', which see."
1108 :type 'hook
1109 :group 'js2-mode)
1110
1111 (defcustom js2-highlight-external-variables t
1112 "Non-nil to highlight undeclared variable identifiers.
1113 An undeclared variable is any variable not declared with var or let
1114 in the current scope or any lexically enclosing scope. If you use
1115 such a variable, then you are either expecting it to originate from
1116 another file, or you've got a potential bug."
1117 :type 'boolean
1118 :group 'js2-mode)
1119
1120 (defcustom js2-include-jslint-globals t
1121 "Non-nil to include the identifiers from JSLint global
1122 declaration (see http://www.jslint.com/lint.html#global) in the
1123 buffer-local externs list. See `js2-additional-externs' for more
1124 information."
1125 :type 'boolean
1126 :group 'js2-mode)
1127
1128 (defvar js2-mode-map
1129 (let ((map (make-sparse-keymap)))
1130 (define-key map [mouse-1] #'js2-mode-show-node)
1131 (define-key map (kbd "M-j") #'js2-line-break)
1132 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1133 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1134 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1135 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1136 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1137 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1138 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1139 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1140 (when js2-bounce-indent-p
1141 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1142
1143 (define-key map [menu-bar javascript]
1144 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1145
1146 (define-key map [menu-bar javascript customize-js2-mode]
1147 '(menu-item "Customize js2-mode" js2-mode-customize
1148 :help "Customize the behavior of this mode"))
1149
1150 (define-key map [menu-bar javascript js2-force-refresh]
1151 '(menu-item "Force buffer refresh" js2-mode-reset
1152 :help "Re-parse the buffer from scratch"))
1153
1154 (define-key map [menu-bar javascript separator-2]
1155 '("--"))
1156
1157 (define-key map [menu-bar javascript next-error]
1158 '(menu-item "Next warning or error" next-error
1159 :enabled (and js2-mode-ast
1160 (or (js2-ast-root-errors js2-mode-ast)
1161 (js2-ast-root-warnings js2-mode-ast)))
1162 :help "Move to next warning or error"))
1163
1164 (define-key map [menu-bar javascript display-errors]
1165 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1166 :visible (not js2-mode-show-parse-errors)
1167 :help "Turn on display of warnings and errors"))
1168
1169 (define-key map [menu-bar javascript hide-errors]
1170 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1171 :visible js2-mode-show-parse-errors
1172 :help "Turn off display of warnings and errors"))
1173
1174 (define-key map [menu-bar javascript separator-1]
1175 '("--"))
1176
1177 (define-key map [menu-bar javascript js2-toggle-function]
1178 '(menu-item "Show/collapse element" js2-mode-toggle-element
1179 :help "Hide or show function body or comment"))
1180
1181 (define-key map [menu-bar javascript show-comments]
1182 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1183 :visible js2-mode-comments-hidden
1184 :help "Expand all hidden block comments"))
1185
1186 (define-key map [menu-bar javascript hide-comments]
1187 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1188 :visible (not js2-mode-comments-hidden)
1189 :help "Show block comments as /*...*/"))
1190
1191 (define-key map [menu-bar javascript show-all-functions]
1192 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1193 :visible js2-mode-functions-hidden
1194 :help "Expand all hidden function bodies"))
1195
1196 (define-key map [menu-bar javascript hide-all-functions]
1197 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1198 :visible (not js2-mode-functions-hidden)
1199 :help "Show {...} for all top-level function bodies"))
1200
1201 map)
1202 "Keymap used in `js2-mode' buffers.")
1203
1204 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1205
1206 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1207 "Matches a //-comment line. Must be first non-whitespace on line.
1208 First match-group is the leading whitespace.")
1209
1210 (defvar js2-mode-hook nil)
1211
1212 (js2-deflocal js2-mode-ast nil "Private variable.")
1213 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1214 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1215 (js2-deflocal js2-mode-parsing nil "Private variable.")
1216 (js2-deflocal js2-mode-node-overlay nil)
1217
1218 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1219 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1220
1221 (js2-deflocal js2-mode-fontifications nil "Private variable")
1222 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1223 (js2-deflocal js2-imenu-recorder nil "Private variable")
1224 (js2-deflocal js2-imenu-function-map nil "Private variable")
1225
1226 (defvar js2-paragraph-start
1227 "\\(@[[:alpha:]]+\\>\\|$\\)")
1228
1229 ;; Note that we also set a 'c-in-sws text property in html comments,
1230 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1231 (defvar js2-syntactic-ws-start
1232 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1233
1234 (defvar js2-syntactic-ws-end
1235 "\\s \\|[\n\r/]\\|\\s!")
1236
1237 (defvar js2-syntactic-eol
1238 (concat "\\s *\\(/\\*[^*\n\r]*"
1239 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1240 "\\*+/\\s *\\)*"
1241 "\\(//\\|/\\*[^*\n\r]*"
1242 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1243 "\\|\\\\$\\|$\\)")
1244 "Copied from `java-mode'. Needed for some cc-engine functions.")
1245
1246 (defvar js2-comment-prefix-regexp
1247 "//+\\|\\**")
1248
1249 (defvar js2-comment-start-skip
1250 "\\(//+\\|/\\*+\\)\\s *")
1251
1252 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1253 "Non-nil to emit status messages during parsing.")
1254
1255 (defvar js2-mode-functions-hidden nil "Private variable.")
1256 (defvar js2-mode-comments-hidden nil "Private variable.")
1257
1258 (defvar js2-mode-syntax-table
1259 (let ((table (make-syntax-table)))
1260 (c-populate-syntax-table table)
1261 table)
1262 "Syntax table used in `js2-mode' buffers.")
1263
1264 (defvar js2-mode-abbrev-table nil
1265 "Abbrev table in use in `js2-mode' buffers.")
1266 (define-abbrev-table 'js2-mode-abbrev-table ())
1267
1268 (defvar js2-mode-pending-parse-callbacks nil
1269 "List of functions waiting to be notified that parse is finished.")
1270
1271 (defvar js2-mode-last-indented-line -1)
1272
1273 ;;; Localizable error and warning messages
1274
1275 ;; Messages are copied from Rhino's Messages.properties.
1276 ;; Many of the Java-specific messages have been elided.
1277 ;; Add any js2-specific ones at the end, so we can keep
1278 ;; this file synced with changes to Rhino's.
1279
1280 (defvar js2-message-table
1281 (make-hash-table :test 'equal :size 250)
1282 "Contains localized messages for `js2-mode'.")
1283
1284 ;; TODO(stevey): construct this table at compile-time.
1285 (defmacro js2-msg (key &rest strings)
1286 `(puthash ,key (concat ,@strings)
1287 js2-message-table))
1288
1289 (defun js2-get-msg (msg-key)
1290 "Look up a localized message.
1291 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1292 the correct number of ARGS must be provided."
1293 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1294 (args (if (listp msg-key) (cdr msg-key)))
1295 (msg (gethash key js2-message-table)))
1296 (if msg
1297 (apply #'format msg args)
1298 key))) ; default to showing the key
1299
1300 (js2-msg "msg.dup.parms"
1301 "Duplicate parameter name '%s'.")
1302
1303 (js2-msg "msg.too.big.jump"
1304 "Program too complex: jump offset too big.")
1305
1306 (js2-msg "msg.too.big.index"
1307 "Program too complex: internal index exceeds 64K limit.")
1308
1309 (js2-msg "msg.while.compiling.fn"
1310 "Encountered code generation error while compiling function '%s': %s")
1311
1312 (js2-msg "msg.while.compiling.script"
1313 "Encountered code generation error while compiling script: %s")
1314
1315 ;; Context
1316 (js2-msg "msg.ctor.not.found"
1317 "Constructor for '%s' not found.")
1318
1319 (js2-msg "msg.not.ctor"
1320 "'%s' is not a constructor.")
1321
1322 ;; FunctionObject
1323 (js2-msg "msg.varargs.ctor"
1324 "Method or constructor '%s' must be static "
1325 "with the signature (Context cx, Object[] args, "
1326 "Function ctorObj, boolean inNewExpr) "
1327 "to define a variable arguments constructor.")
1328
1329 (js2-msg "msg.varargs.fun"
1330 "Method '%s' must be static with the signature "
1331 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1332 "to define a variable arguments function.")
1333
1334 (js2-msg "msg.incompat.call"
1335 "Method '%s' called on incompatible object.")
1336
1337 (js2-msg "msg.bad.parms"
1338 "Unsupported parameter type '%s' in method '%s'.")
1339
1340 (js2-msg "msg.bad.method.return"
1341 "Unsupported return type '%s' in method '%s'.")
1342
1343 (js2-msg "msg.bad.ctor.return"
1344 "Construction of objects of type '%s' is not supported.")
1345
1346 (js2-msg "msg.no.overload"
1347 "Method '%s' occurs multiple times in class '%s'.")
1348
1349 (js2-msg "msg.method.not.found"
1350 "Method '%s' not found in '%s'.")
1351
1352 ;; IRFactory
1353
1354 (js2-msg "msg.bad.for.in.lhs"
1355 "Invalid left-hand side of for..in loop.")
1356
1357 (js2-msg "msg.mult.index"
1358 "Only one variable allowed in for..in loop.")
1359
1360 (js2-msg "msg.bad.for.in.destruct"
1361 "Left hand side of for..in loop must be an array of "
1362 "length 2 to accept key/value pair.")
1363
1364 (js2-msg "msg.cant.convert"
1365 "Can't convert to type '%s'.")
1366
1367 (js2-msg "msg.bad.assign.left"
1368 "Invalid assignment left-hand side.")
1369
1370 (js2-msg "msg.bad.decr"
1371 "Invalid decerement operand.")
1372
1373 (js2-msg "msg.bad.incr"
1374 "Invalid increment operand.")
1375
1376 (js2-msg "msg.bad.yield"
1377 "yield must be in a function.")
1378
1379 (js2-msg "msg.yield.parenthesized"
1380 "yield expression must be parenthesized.")
1381
1382 ;; NativeGlobal
1383 (js2-msg "msg.cant.call.indirect"
1384 "Function '%s' must be called directly, and not by way of a "
1385 "function of another name.")
1386
1387 (js2-msg "msg.eval.nonstring"
1388 "Calling eval() with anything other than a primitive "
1389 "string value will simply return the value. "
1390 "Is this what you intended?")
1391
1392 (js2-msg "msg.eval.nonstring.strict"
1393 "Calling eval() with anything other than a primitive "
1394 "string value is not allowed in strict mode.")
1395
1396 (js2-msg "msg.bad.destruct.op"
1397 "Invalid destructuring assignment operator")
1398
1399 ;; NativeCall
1400 (js2-msg "msg.only.from.new"
1401 "'%s' may only be invoked from a `new' expression.")
1402
1403 (js2-msg "msg.deprec.ctor"
1404 "The '%s' constructor is deprecated.")
1405
1406 ;; NativeFunction
1407 (js2-msg "msg.no.function.ref.found"
1408 "no source found to decompile function reference %s")
1409
1410 (js2-msg "msg.arg.isnt.array"
1411 "second argument to Function.prototype.apply must be an array")
1412
1413 ;; NativeGlobal
1414 (js2-msg "msg.bad.esc.mask"
1415 "invalid string escape mask")
1416
1417 ;; NativeRegExp
1418 (js2-msg "msg.bad.quant"
1419 "Invalid quantifier %s")
1420
1421 (js2-msg "msg.overlarge.backref"
1422 "Overly large back reference %s")
1423
1424 (js2-msg "msg.overlarge.min"
1425 "Overly large minimum %s")
1426
1427 (js2-msg "msg.overlarge.max"
1428 "Overly large maximum %s")
1429
1430 (js2-msg "msg.zero.quant"
1431 "Zero quantifier %s")
1432
1433 (js2-msg "msg.max.lt.min"
1434 "Maximum %s less than minimum")
1435
1436 (js2-msg "msg.unterm.quant"
1437 "Unterminated quantifier %s")
1438
1439 (js2-msg "msg.unterm.paren"
1440 "Unterminated parenthetical %s")
1441
1442 (js2-msg "msg.unterm.class"
1443 "Unterminated character class %s")
1444
1445 (js2-msg "msg.bad.range"
1446 "Invalid range in character class.")
1447
1448 (js2-msg "msg.trail.backslash"
1449 "Trailing \\ in regular expression.")
1450
1451 (js2-msg "msg.re.unmatched.right.paren"
1452 "unmatched ) in regular expression.")
1453
1454 (js2-msg "msg.no.regexp"
1455 "Regular expressions are not available.")
1456
1457 (js2-msg "msg.bad.backref"
1458 "back-reference exceeds number of capturing parentheses.")
1459
1460 (js2-msg "msg.bad.regexp.compile"
1461 "Only one argument may be specified if the first "
1462 "argument to RegExp.prototype.compile is a RegExp object.")
1463
1464 ;; Parser
1465 (js2-msg "msg.got.syntax.errors"
1466 "Compilation produced %s syntax errors.")
1467
1468 (js2-msg "msg.var.redecl"
1469 "TypeError: redeclaration of var %s.")
1470
1471 (js2-msg "msg.const.redecl"
1472 "TypeError: redeclaration of const %s.")
1473
1474 (js2-msg "msg.let.redecl"
1475 "TypeError: redeclaration of variable %s.")
1476
1477 (js2-msg "msg.parm.redecl"
1478 "TypeError: redeclaration of formal parameter %s.")
1479
1480 (js2-msg "msg.fn.redecl"
1481 "TypeError: redeclaration of function %s.")
1482
1483 (js2-msg "msg.let.decl.not.in.block"
1484 "SyntaxError: let declaration not directly within block")
1485
1486 ;; NodeTransformer
1487 (js2-msg "msg.dup.label"
1488 "duplicated label")
1489
1490 (js2-msg "msg.undef.label"
1491 "undefined label")
1492
1493 (js2-msg "msg.bad.break"
1494 "unlabelled break must be inside loop or switch")
1495
1496 (js2-msg "msg.continue.outside"
1497 "continue must be inside loop")
1498
1499 (js2-msg "msg.continue.nonloop"
1500 "continue can only use labels of iteration statements")
1501
1502 (js2-msg "msg.bad.throw.eol"
1503 "Line terminator is not allowed between the throw "
1504 "keyword and throw expression.")
1505
1506 (js2-msg "msg.no.paren.parms"
1507 "missing ( before function parameters.")
1508
1509 (js2-msg "msg.no.parm"
1510 "missing formal parameter")
1511
1512 (js2-msg "msg.no.paren.after.parms"
1513 "missing ) after formal parameters")
1514
1515 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1516 "parameter without default follows parameter with default")
1517
1518 (js2-msg "msg.param.after.rest" ; added by js2-mode
1519 "parameter after rest parameter")
1520
1521 (js2-msg "msg.no.brace.body"
1522 "missing '{' before function body")
1523
1524 (js2-msg "msg.no.brace.after.body"
1525 "missing } after function body")
1526
1527 (js2-msg "msg.no.paren.cond"
1528 "missing ( before condition")
1529
1530 (js2-msg "msg.no.paren.after.cond"
1531 "missing ) after condition")
1532
1533 (js2-msg "msg.no.semi.stmt"
1534 "missing ; before statement")
1535
1536 (js2-msg "msg.missing.semi"
1537 "missing ; after statement")
1538
1539 (js2-msg "msg.no.name.after.dot"
1540 "missing name after . operator")
1541
1542 (js2-msg "msg.no.name.after.coloncolon"
1543 "missing name after :: operator")
1544
1545 (js2-msg "msg.no.name.after.dotdot"
1546 "missing name after .. operator")
1547
1548 (js2-msg "msg.no.name.after.xmlAttr"
1549 "missing name after .@")
1550
1551 (js2-msg "msg.no.bracket.index"
1552 "missing ] in index expression")
1553
1554 (js2-msg "msg.no.paren.switch"
1555 "missing ( before switch expression")
1556
1557 (js2-msg "msg.no.paren.after.switch"
1558 "missing ) after switch expression")
1559
1560 (js2-msg "msg.no.brace.switch"
1561 "missing '{' before switch body")
1562
1563 (js2-msg "msg.bad.switch"
1564 "invalid switch statement")
1565
1566 (js2-msg "msg.no.colon.case"
1567 "missing : after case expression")
1568
1569 (js2-msg "msg.double.switch.default"
1570 "double default label in the switch statement")
1571
1572 (js2-msg "msg.no.while.do"
1573 "missing while after do-loop body")
1574
1575 (js2-msg "msg.no.paren.for"
1576 "missing ( after for")
1577
1578 (js2-msg "msg.no.semi.for"
1579 "missing ; after for-loop initializer")
1580
1581 (js2-msg "msg.no.semi.for.cond"
1582 "missing ; after for-loop condition")
1583
1584 (js2-msg "msg.in.after.for.name"
1585 "missing in or of after for")
1586
1587 (js2-msg "msg.no.paren.for.ctrl"
1588 "missing ) after for-loop control")
1589
1590 (js2-msg "msg.no.paren.with"
1591 "missing ( before with-statement object")
1592
1593 (js2-msg "msg.no.paren.after.with"
1594 "missing ) after with-statement object")
1595
1596 (js2-msg "msg.no.paren.after.let"
1597 "missing ( after let")
1598
1599 (js2-msg "msg.no.paren.let"
1600 "missing ) after variable list")
1601
1602 (js2-msg "msg.no.curly.let"
1603 "missing } after let statement")
1604
1605 (js2-msg "msg.bad.return"
1606 "invalid return")
1607
1608 (js2-msg "msg.no.brace.block"
1609 "missing } in compound statement")
1610
1611 (js2-msg "msg.bad.label"
1612 "invalid label")
1613
1614 (js2-msg "msg.bad.var"
1615 "missing variable name")
1616
1617 (js2-msg "msg.bad.var.init"
1618 "invalid variable initialization")
1619
1620 (js2-msg "msg.no.colon.cond"
1621 "missing : in conditional expression")
1622
1623 (js2-msg "msg.no.paren.arg"
1624 "missing ) after argument list")
1625
1626 (js2-msg "msg.no.bracket.arg"
1627 "missing ] after element list")
1628
1629 (js2-msg "msg.bad.prop"
1630 "invalid property id")
1631
1632 (js2-msg "msg.no.colon.prop"
1633 "missing : after property id")
1634
1635 (js2-msg "msg.no.brace.prop"
1636 "missing } after property list")
1637
1638 (js2-msg "msg.no.paren"
1639 "missing ) in parenthetical")
1640
1641 (js2-msg "msg.reserved.id"
1642 "identifier is a reserved word")
1643
1644 (js2-msg "msg.no.paren.catch"
1645 "missing ( before catch-block condition")
1646
1647 (js2-msg "msg.bad.catchcond"
1648 "invalid catch block condition")
1649
1650 (js2-msg "msg.catch.unreachable"
1651 "any catch clauses following an unqualified catch are unreachable")
1652
1653 (js2-msg "msg.no.brace.try"
1654 "missing '{' before try block")
1655
1656 (js2-msg "msg.no.brace.catchblock"
1657 "missing '{' before catch-block body")
1658
1659 (js2-msg "msg.try.no.catchfinally"
1660 "'try' without 'catch' or 'finally'")
1661
1662 (js2-msg "msg.no.return.value"
1663 "function %s does not always return a value")
1664
1665 (js2-msg "msg.anon.no.return.value"
1666 "anonymous function does not always return a value")
1667
1668 (js2-msg "msg.return.inconsistent"
1669 "return statement is inconsistent with previous usage")
1670
1671 (js2-msg "msg.generator.returns"
1672 "TypeError: generator function '%s' returns a value")
1673
1674 (js2-msg "msg.anon.generator.returns"
1675 "TypeError: anonymous generator function returns a value")
1676
1677 (js2-msg "msg.syntax"
1678 "syntax error")
1679
1680 (js2-msg "msg.unexpected.eof"
1681 "Unexpected end of file")
1682
1683 (js2-msg "msg.XML.bad.form"
1684 "illegally formed XML syntax")
1685
1686 (js2-msg "msg.XML.not.available"
1687 "XML runtime not available")
1688
1689 (js2-msg "msg.too.deep.parser.recursion"
1690 "Too deep recursion while parsing")
1691
1692 (js2-msg "msg.no.side.effects"
1693 "Code has no side effects")
1694
1695 (js2-msg "msg.extra.trailing.comma"
1696 "Trailing comma is not supported in some browsers")
1697
1698 (js2-msg "msg.array.trailing.comma"
1699 "Trailing comma yields different behavior across browsers")
1700
1701 (js2-msg "msg.equal.as.assign"
1702 (concat "Test for equality (==) mistyped as assignment (=)?"
1703 " (parenthesize to suppress warning)"))
1704
1705 (js2-msg "msg.var.hides.arg"
1706 "Variable %s hides argument")
1707
1708 (js2-msg "msg.destruct.assign.no.init"
1709 "Missing = in destructuring declaration")
1710
1711 ;; ScriptRuntime
1712 (js2-msg "msg.no.properties"
1713 "%s has no properties.")
1714
1715 (js2-msg "msg.invalid.iterator"
1716 "Invalid iterator value")
1717
1718 (js2-msg "msg.iterator.primitive"
1719 "__iterator__ returned a primitive value")
1720
1721 (js2-msg "msg.assn.create.strict"
1722 "Assignment to undeclared variable %s")
1723
1724 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1725 "Undeclared variable or function '%s'")
1726
1727 (js2-msg "msg.ref.undefined.prop"
1728 "Reference to undefined property '%s'")
1729
1730 (js2-msg "msg.prop.not.found"
1731 "Property %s not found.")
1732
1733 (js2-msg "msg.invalid.type"
1734 "Invalid JavaScript value of type %s")
1735
1736 (js2-msg "msg.primitive.expected"
1737 "Primitive type expected (had %s instead)")
1738
1739 (js2-msg "msg.namespace.expected"
1740 "Namespace object expected to left of :: (found %s instead)")
1741
1742 (js2-msg "msg.null.to.object"
1743 "Cannot convert null to an object.")
1744
1745 (js2-msg "msg.undef.to.object"
1746 "Cannot convert undefined to an object.")
1747
1748 (js2-msg "msg.cyclic.value"
1749 "Cyclic %s value not allowed.")
1750
1751 (js2-msg "msg.is.not.defined"
1752 "'%s' is not defined.")
1753
1754 (js2-msg "msg.undef.prop.read"
1755 "Cannot read property '%s' from %s")
1756
1757 (js2-msg "msg.undef.prop.write"
1758 "Cannot set property '%s' of %s to '%s'")
1759
1760 (js2-msg "msg.undef.prop.delete"
1761 "Cannot delete property '%s' of %s")
1762
1763 (js2-msg "msg.undef.method.call"
1764 "Cannot call method '%s' of %s")
1765
1766 (js2-msg "msg.undef.with"
1767 "Cannot apply 'with' to %s")
1768
1769 (js2-msg "msg.isnt.function"
1770 "%s is not a function, it is %s.")
1771
1772 (js2-msg "msg.isnt.function.in"
1773 "Cannot call property %s in object %s. "
1774 "It is not a function, it is '%s'.")
1775
1776 (js2-msg "msg.function.not.found"
1777 "Cannot find function %s.")
1778
1779 (js2-msg "msg.function.not.found.in"
1780 "Cannot find function %s in object %s.")
1781
1782 (js2-msg "msg.isnt.xml.object"
1783 "%s is not an xml object.")
1784
1785 (js2-msg "msg.no.ref.to.get"
1786 "%s is not a reference to read reference value.")
1787
1788 (js2-msg "msg.no.ref.to.set"
1789 "%s is not a reference to set reference value to %s.")
1790
1791 (js2-msg "msg.no.ref.from.function"
1792 "Function %s can not be used as the left-hand "
1793 "side of assignment or as an operand of ++ or -- operator.")
1794
1795 (js2-msg "msg.bad.default.value"
1796 "Object's getDefaultValue() method returned an object.")
1797
1798 (js2-msg "msg.instanceof.not.object"
1799 "Can't use instanceof on a non-object.")
1800
1801 (js2-msg "msg.instanceof.bad.prototype"
1802 "'prototype' property of %s is not an object.")
1803
1804 (js2-msg "msg.bad.radix"
1805 "illegal radix %s.")
1806
1807 ;; ScriptableObject
1808 (js2-msg "msg.default.value"
1809 "Cannot find default value for object.")
1810
1811 (js2-msg "msg.zero.arg.ctor"
1812 "Cannot load class '%s' which has no zero-parameter constructor.")
1813
1814 (js2-msg "msg.ctor.multiple.parms"
1815 "Can't define constructor or class %s since more than "
1816 "one constructor has multiple parameters.")
1817
1818 (js2-msg "msg.extend.scriptable"
1819 "%s must extend ScriptableObject in order to define property %s.")
1820
1821 (js2-msg "msg.bad.getter.parms"
1822 "In order to define a property, getter %s must have zero "
1823 "parameters or a single ScriptableObject parameter.")
1824
1825 (js2-msg "msg.obj.getter.parms"
1826 "Expected static or delegated getter %s to take "
1827 "a ScriptableObject parameter.")
1828
1829 (js2-msg "msg.getter.static"
1830 "Getter and setter must both be static or neither be static.")
1831
1832 (js2-msg "msg.setter.return"
1833 "Setter must have void return type: %s")
1834
1835 (js2-msg "msg.setter2.parms"
1836 "Two-parameter setter must take a ScriptableObject as "
1837 "its first parameter.")
1838
1839 (js2-msg "msg.setter1.parms"
1840 "Expected single parameter setter for %s")
1841
1842 (js2-msg "msg.setter2.expected"
1843 "Expected static or delegated setter %s to take two parameters.")
1844
1845 (js2-msg "msg.setter.parms"
1846 "Expected either one or two parameters for setter.")
1847
1848 (js2-msg "msg.setter.bad.type"
1849 "Unsupported parameter type '%s' in setter '%s'.")
1850
1851 (js2-msg "msg.add.sealed"
1852 "Cannot add a property to a sealed object: %s.")
1853
1854 (js2-msg "msg.remove.sealed"
1855 "Cannot remove a property from a sealed object: %s.")
1856
1857 (js2-msg "msg.modify.sealed"
1858 "Cannot modify a property of a sealed object: %s.")
1859
1860 (js2-msg "msg.modify.readonly"
1861 "Cannot modify readonly property: %s.")
1862
1863 ;; TokenStream
1864 (js2-msg "msg.missing.exponent"
1865 "missing exponent")
1866
1867 (js2-msg "msg.caught.nfe"
1868 "number format error")
1869
1870 (js2-msg "msg.unterminated.string.lit"
1871 "unterminated string literal")
1872
1873 (js2-msg "msg.unterminated.comment"
1874 "unterminated comment")
1875
1876 (js2-msg "msg.unterminated.re.lit"
1877 "unterminated regular expression literal")
1878
1879 (js2-msg "msg.invalid.re.flag"
1880 "invalid flag after regular expression")
1881
1882 (js2-msg "msg.no.re.input.for"
1883 "no input for %s")
1884
1885 (js2-msg "msg.illegal.character"
1886 "illegal character")
1887
1888 (js2-msg "msg.invalid.escape"
1889 "invalid Unicode escape sequence")
1890
1891 (js2-msg "msg.bad.namespace"
1892 "not a valid default namespace statement. "
1893 "Syntax is: default xml namespace = EXPRESSION;")
1894
1895 ;; TokensStream warnings
1896 (js2-msg "msg.bad.octal.literal"
1897 "illegal octal literal digit %s; "
1898 "interpreting it as a decimal digit")
1899
1900 (js2-msg "msg.reserved.keyword"
1901 "illegal usage of future reserved keyword %s; "
1902 "interpreting it as ordinary identifier")
1903
1904 (js2-msg "msg.script.is.not.constructor"
1905 "Script objects are not constructors.")
1906
1907 ;; Arrays
1908 (js2-msg "msg.arraylength.bad"
1909 "Inappropriate array length.")
1910
1911 ;; Arrays
1912 (js2-msg "msg.arraylength.too.big"
1913 "Array length %s exceeds supported capacity limit.")
1914
1915 ;; URI
1916 (js2-msg "msg.bad.uri"
1917 "Malformed URI sequence.")
1918
1919 ;; Number
1920 (js2-msg "msg.bad.precision"
1921 "Precision %s out of range.")
1922
1923 ;; NativeGenerator
1924 (js2-msg "msg.send.newborn"
1925 "Attempt to send value to newborn generator")
1926
1927 (js2-msg "msg.already.exec.gen"
1928 "Already executing generator")
1929
1930 (js2-msg "msg.StopIteration.invalid"
1931 "StopIteration may not be changed to an arbitrary object.")
1932
1933 ;; Interpreter
1934 (js2-msg "msg.yield.closing"
1935 "Yield from closing generator")
1936
1937 ;;; Utilities
1938
1939 (defun js2-delete-if (predicate list)
1940 "Remove all items satisfying PREDICATE in LIST."
1941 (loop for item in list
1942 if (not (funcall predicate item))
1943 collect item))
1944
1945 (defun js2-position (element list)
1946 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1947 Returns nil if element is not found in the list."
1948 (let ((count 0)
1949 found)
1950 (while (and list (not found))
1951 (if (eq element (car list))
1952 (setq found t)
1953 (setq count (1+ count)
1954 list (cdr list))))
1955 (if found count)))
1956
1957 (defun js2-find-if (predicate list)
1958 "Find first item satisfying PREDICATE in LIST."
1959 (let (result)
1960 (while (and list (not result))
1961 (if (funcall predicate (car list))
1962 (setq result (car list)))
1963 (setq list (cdr list)))
1964 result))
1965
1966 (defmacro js2-time (form)
1967 "Evaluate FORM, discard result, and return elapsed time in sec."
1968 (declare (debug t))
1969 (let ((beg (make-symbol "--js2-time-beg--"))
1970 (delta (make-symbol "--js2-time-end--")))
1971 `(let ((,beg (current-time))
1972 ,delta)
1973 ,form
1974 (/ (truncate (* (- (float-time (current-time))
1975 (float-time ,beg))
1976 10000))
1977 10000.0))))
1978
1979 (defsubst js2-same-line (pos)
1980 "Return t if POS is on the same line as current point."
1981 (and (>= pos (point-at-bol))
1982 (<= pos (point-at-eol))))
1983
1984 (defun js2-code-bug ()
1985 "Signal an error when we encounter an unexpected code path."
1986 (error "failed assertion"))
1987
1988 (defsubst js2-record-text-property (beg end prop value)
1989 "Record a text property to set when parsing finishes."
1990 (push (list beg end prop value) js2-mode-deferred-properties))
1991
1992 ;; I'd like to associate errors with nodes, but for now the
1993 ;; easiest thing to do is get the context info from the last token.
1994 (defun js2-record-parse-error (msg &optional arg pos len)
1995 (push (list (list msg arg)
1996 (or pos js2-token-beg)
1997 (or len (- js2-token-end js2-token-beg)))
1998 js2-parsed-errors))
1999
2000 (defun js2-report-error (msg &optional msg-arg pos len)
2001 "Signal a syntax error or record a parse error."
2002 (if js2-recover-from-parse-errors
2003 (js2-record-parse-error msg msg-arg pos len)
2004 (signal 'js2-syntax-error
2005 (list msg
2006 js2-ts-lineno
2007 (save-excursion
2008 (goto-char js2-ts-cursor)
2009 (current-column))
2010 js2-ts-hit-eof))))
2011
2012 (defun js2-report-warning (msg &optional msg-arg pos len face)
2013 (if js2-compiler-report-warning-as-error
2014 (js2-report-error msg msg-arg pos len)
2015 (push (list (list msg msg-arg)
2016 (or pos js2-token-beg)
2017 (or len (- js2-token-end js2-token-beg))
2018 face)
2019 js2-parsed-warnings)))
2020
2021 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2022 (if js2-compiler-strict-mode
2023 (js2-report-warning msg-id msg-arg beg
2024 (and beg end (- end beg)))))
2025
2026 (put 'js2-syntax-error 'error-conditions
2027 '(error syntax-error js2-syntax-error))
2028 (put 'js2-syntax-error 'error-message "Syntax error")
2029
2030 (put 'js2-parse-error 'error-conditions
2031 '(error parse-error js2-parse-error))
2032 (put 'js2-parse-error 'error-message "Parse error")
2033
2034 (defmacro js2-clear-flag (flags flag)
2035 `(setq ,flags (logand ,flags (lognot ,flag))))
2036
2037 (defmacro js2-set-flag (flags flag)
2038 "Logical-or FLAG into FLAGS."
2039 `(setq ,flags (logior ,flags ,flag)))
2040
2041 (defsubst js2-flag-set-p (flags flag)
2042 (/= 0 (logand flags flag)))
2043
2044 (defsubst js2-flag-not-set-p (flags flag)
2045 (zerop (logand flags flag)))
2046
2047 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2048 "Evaluate BODY with the _ character set to be word-syntax."
2049 (declare (indent 0) (debug t))
2050 (let ((old-syntax (make-symbol "old-syntax")))
2051 `(let ((,old-syntax (string (char-syntax ?_))))
2052 (unwind-protect
2053 (progn
2054 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2055 ,@body)
2056 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2057
2058 (defsubst js2-char-uppercase-p (c)
2059 "Return t if C is an uppercase character.
2060 Handles unicode and latin chars properly."
2061 (/= c (downcase c)))
2062
2063 (defsubst js2-char-lowercase-p (c)
2064 "Return t if C is an uppercase character.
2065 Handles unicode and latin chars properly."
2066 (/= c (upcase c)))
2067
2068 ;;; AST struct and function definitions
2069
2070 ;; flags for ast node property 'member-type (used for e4x operators)
2071 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2072 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2073 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2074
2075 (defsubst js2-relpos (pos anchor)
2076 "Convert POS to be relative to ANCHOR.
2077 If POS is nil, returns nil."
2078 (and pos (- pos anchor)))
2079
2080 (defun js2-make-pad (indent)
2081 (if (zerop indent)
2082 ""
2083 (make-string (* indent js2-basic-offset) ? )))
2084
2085 (defun js2-visit-ast (node callback)
2086 "Visit every node in ast NODE with visitor CALLBACK.
2087
2088 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2089 called twice: once to visit the node, and again after all the node's
2090 children have been processed. The END-P argument is nil on the first
2091 call and non-nil on the second call. The return value of the callback
2092 affects the traversal: if non-nil, the children of NODE are processed.
2093 If the callback returns nil, or if the node has no children, then the
2094 callback is called immediately with a non-nil END-P argument.
2095
2096 The node traversal is approximately lexical-order, although there
2097 are currently no guarantees around this."
2098 (when node
2099 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2100 ;; visit the node
2101 (when (funcall callback node nil)
2102 ;; visit the kids
2103 (cond
2104 ((eq vfunc 'js2-visit-none)
2105 nil) ; don't even bother calling it
2106 ;; Each AST node type has to define a `js2-visitor' function
2107 ;; that takes a node and a callback, and calls `js2-visit-ast'
2108 ;; on each child of the node.
2109 (vfunc
2110 (funcall vfunc node callback))
2111 (t
2112 (error "%s does not define a visitor-traversal function"
2113 (aref node 0)))))
2114 ;; call the end-visit
2115 (funcall callback node t))))
2116
2117 (defstruct (js2-node
2118 (:constructor nil)) ; abstract
2119 "Base AST node type."
2120 (type -1) ; token type
2121 (pos -1) ; start position of this AST node in parsed input
2122 (len 1) ; num characters spanned by the node
2123 props ; optional node property list (an alist)
2124 parent) ; link to parent node; null for root
2125
2126 (defsubst js2-node-get-prop (node prop &optional default)
2127 (or (cadr (assoc prop (js2-node-props node))) default))
2128
2129 (defsubst js2-node-set-prop (node prop value)
2130 (setf (js2-node-props node)
2131 (cons (list prop value) (js2-node-props node))))
2132
2133 (defun js2-fixup-starts (n nodes)
2134 "Adjust the start positions of NODES to be relative to N.
2135 Any node in the list may be nil, for convenience."
2136 (dolist (node nodes)
2137 (when node
2138 (setf (js2-node-pos node) (- (js2-node-pos node)
2139 (js2-node-pos n))))))
2140
2141 (defun js2-node-add-children (parent &rest nodes)
2142 "Set parent node of NODES to PARENT, and return PARENT.
2143 Does nothing if we're not recording parent links.
2144 If any given node in NODES is nil, doesn't record that link."
2145 (js2-fixup-starts parent nodes)
2146 (dolist (node nodes)
2147 (and node
2148 (setf (js2-node-parent node) parent))))
2149
2150 ;; Non-recursive since it's called a frightening number of times.
2151 (defun js2-node-abs-pos (n)
2152 (let ((pos (js2-node-pos n)))
2153 (while (setq n (js2-node-parent n))
2154 (setq pos (+ pos (js2-node-pos n))))
2155 pos))
2156
2157 (defsubst js2-node-abs-end (n)
2158 "Return absolute buffer position of end of N."
2159 (+ (js2-node-abs-pos n) (js2-node-len n)))
2160
2161 ;; It's important to make sure block nodes have a Lisp list for the
2162 ;; child nodes, to limit printing recursion depth in an AST that
2163 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2164 ;; a sufficiently large vector tree.
2165
2166 (defstruct (js2-block-node
2167 (:include js2-node)
2168 (:constructor nil)
2169 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2170 (pos js2-token-beg)
2171 len
2172 props
2173 kids)))
2174 "A block of statements."
2175 kids) ; a Lisp list of the child statement nodes
2176
2177 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2178 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2179
2180 (defun js2-visit-block (ast callback)
2181 "Visit the `js2-block-node' children of AST."
2182 (dolist (kid (js2-block-node-kids ast))
2183 (js2-visit-ast kid callback)))
2184
2185 (defun js2-print-block (n i)
2186 (let ((pad (js2-make-pad i)))
2187 (insert pad "{\n")
2188 (dolist (kid (js2-block-node-kids n))
2189 (js2-print-ast kid (1+ i)))
2190 (insert pad "}")))
2191
2192 (defstruct (js2-scope
2193 (:include js2-block-node)
2194 (:constructor nil)
2195 (:constructor make-js2-scope (&key (type js2-BLOCK)
2196 (pos js2-token-beg)
2197 len
2198 kids)))
2199 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2200 ;; I don't have one of those handy, so I'll use an alist for now.
2201 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2202 ;; and is much lighter-weight to construct (both CPU and mem).
2203 ;; The keys are interned strings (symbols) for faster lookup.
2204 ;; Should switch to hybrid alist/hashtable eventually.
2205 symbol-table ; an alist of (symbol . js2-symbol)
2206 parent-scope ; a `js2-scope'
2207 top) ; top-level `js2-scope' (script/function)
2208
2209 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2210 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2211
2212 (defun js2-node-get-enclosing-scope (node)
2213 "Return the innermost `js2-scope' node surrounding NODE.
2214 Returns nil if there is no enclosing scope node."
2215 (let ((parent (js2-node-parent node)))
2216 (while (not (js2-scope-p parent))
2217 (setq parent (js2-node-parent parent)))
2218 parent))
2219
2220 (defun js2-get-defining-scope (scope name)
2221 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2222 Returns `js2-scope' in which NAME is defined, or nil if not found."
2223 (let ((sym (if (symbolp name)
2224 name
2225 (intern name)))
2226 table
2227 result
2228 (continue t))
2229 (while (and scope continue)
2230 (if (and (setq table (js2-scope-symbol-table scope))
2231 (assq sym table))
2232 (setq continue nil
2233 result scope)
2234 (setq scope (js2-scope-parent-scope scope))))
2235 result))
2236
2237 (defun js2-scope-get-symbol (scope name)
2238 "Return symbol table entry for NAME in SCOPE.
2239 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2240 (and (js2-scope-symbol-table scope)
2241 (cdr (assq (if (symbolp name)
2242 name
2243 (intern name))
2244 (js2-scope-symbol-table scope)))))
2245
2246 (defun js2-scope-put-symbol (scope name symbol)
2247 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2248 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2249 (let* ((table (js2-scope-symbol-table scope))
2250 (sym (if (symbolp name) name (intern name)))
2251 (entry (assq sym table)))
2252 (if entry
2253 (setcdr entry symbol)
2254 (push (cons sym symbol)
2255 (js2-scope-symbol-table scope)))))
2256
2257 (defstruct (js2-symbol
2258 (:constructor nil)
2259 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2260 "A symbol table entry."
2261 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2262 ;; js2-LET, or js2-CONST
2263 decl-type
2264 name ; string
2265 ast-node) ; a `js2-node'
2266
2267 (defstruct (js2-error-node
2268 (:include js2-node)
2269 (:constructor nil) ; silence emacs21 byte-compiler
2270 (:constructor make-js2-error-node (&key (type js2-ERROR)
2271 (pos js2-token-beg)
2272 len)))
2273 "AST node representing a parse error.")
2274
2275 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2276 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2277
2278 (defstruct (js2-script-node
2279 (:include js2-scope)
2280 (:constructor nil)
2281 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2282 (pos js2-token-beg)
2283 len
2284 ;; FIXME: What are those?
2285 var-decls
2286 fun-decls)))
2287 functions ; Lisp list of nested functions
2288 regexps ; Lisp list of (string . flags)
2289 symbols ; alist (every symbol gets unique index)
2290 (param-count 0)
2291 var-names ; vector of string names
2292 consts ; bool-vector matching var-decls
2293 (temp-number 0)) ; for generating temp variables
2294
2295 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2296 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2297
2298 (defun js2-print-script (node indent)
2299 (dolist (kid (js2-block-node-kids node))
2300 (js2-print-ast kid indent)))
2301
2302 (defstruct (js2-ast-root
2303 (:include js2-script-node)
2304 (:constructor nil)
2305 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2306 (pos js2-token-beg)
2307 len
2308 buffer)))
2309 "The root node of a js2 AST."
2310 buffer ; the source buffer from which the code was parsed
2311 comments ; a Lisp list of comments, ordered by start position
2312 errors ; a Lisp list of errors found during parsing
2313 warnings ; a Lisp list of warnings found during parsing
2314 node-count) ; number of nodes in the tree, including the root
2315
2316 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2317 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2318
2319 (defun js2-visit-ast-root (ast callback)
2320 (dolist (kid (js2-ast-root-kids ast))
2321 (js2-visit-ast kid callback))
2322 (dolist (comment (js2-ast-root-comments ast))
2323 (js2-visit-ast comment callback)))
2324
2325 (defstruct (js2-comment-node
2326 (:include js2-node)
2327 (:constructor nil)
2328 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2329 (pos js2-token-beg)
2330 len
2331 (format js2-ts-comment-type))))
2332 format) ; 'line, 'block, 'jsdoc or 'html
2333
2334 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2335 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2336
2337 (defun js2-print-comment (n i)
2338 ;; We really ought to link end-of-line comments to their nodes.
2339 ;; Or maybe we could add a new comment type, 'endline.
2340 (insert (js2-make-pad i)
2341 (js2-node-string n)))
2342
2343 (defstruct (js2-expr-stmt-node
2344 (:include js2-node)
2345 (:constructor nil)
2346 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2347 (pos js2-ts-cursor)
2348 len
2349 expr)))
2350 "An expression statement."
2351 expr)
2352
2353 (defsubst js2-expr-stmt-node-set-has-result (node)
2354 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2355 (setf (js2-node-type node) js2-EXPR_RESULT))
2356
2357 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2358 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2359
2360 (defun js2-visit-expr-stmt-node (n v)
2361 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2362
2363 (defun js2-print-expr-stmt-node (n indent)
2364 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2365 (insert ";\n"))
2366
2367 (defstruct (js2-loop-node
2368 (:include js2-scope)
2369 (:constructor nil))
2370 "Abstract supertype of loop nodes."
2371 body ; a `js2-block-node'
2372 lp ; position of left-paren, nil if omitted
2373 rp) ; position of right-paren, nil if omitted
2374
2375 (defstruct (js2-do-node
2376 (:include js2-loop-node)
2377 (:constructor nil)
2378 (:constructor make-js2-do-node (&key (type js2-DO)
2379 (pos js2-token-beg)
2380 len
2381 body
2382 condition
2383 while-pos
2384 lp
2385 rp)))
2386 "AST node for do-loop."
2387 condition ; while (expression)
2388 while-pos) ; buffer position of 'while' keyword
2389
2390 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2391 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2392
2393 (defun js2-visit-do-node (n v)
2394 (js2-visit-ast (js2-do-node-body n) v)
2395 (js2-visit-ast (js2-do-node-condition n) v))
2396
2397 (defun js2-print-do-node (n i)
2398 (let ((pad (js2-make-pad i)))
2399 (insert pad "do {\n")
2400 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2401 (js2-print-ast kid (1+ i)))
2402 (insert pad "} while (")
2403 (js2-print-ast (js2-do-node-condition n) 0)
2404 (insert ");\n")))
2405
2406 (defstruct (js2-while-node
2407 (:include js2-loop-node)
2408 (:constructor nil)
2409 (:constructor make-js2-while-node (&key (type js2-WHILE)
2410 (pos js2-token-beg)
2411 len body
2412 condition lp
2413 rp)))
2414 "AST node for while-loop."
2415 condition) ; while-condition
2416
2417 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2418 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2419
2420 (defun js2-visit-while-node (n v)
2421 (js2-visit-ast (js2-while-node-condition n) v)
2422 (js2-visit-ast (js2-while-node-body n) v))
2423
2424 (defun js2-print-while-node (n i)
2425 (let ((pad (js2-make-pad i)))
2426 (insert pad "while (")
2427 (js2-print-ast (js2-while-node-condition n) 0)
2428 (insert ") {\n")
2429 (js2-print-body (js2-while-node-body n) (1+ i))
2430 (insert pad "}\n")))
2431
2432 (defstruct (js2-for-node
2433 (:include js2-loop-node)
2434 (:constructor nil)
2435 (:constructor make-js2-for-node (&key (type js2-FOR)
2436 (pos js2-ts-cursor)
2437 len body init
2438 condition
2439 update lp rp)))
2440 "AST node for a C-style for-loop."
2441 init ; initialization expression
2442 condition ; loop condition
2443 update) ; update clause
2444
2445 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2446 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2447
2448 (defun js2-visit-for-node (n v)
2449 (js2-visit-ast (js2-for-node-init n) v)
2450 (js2-visit-ast (js2-for-node-condition n) v)
2451 (js2-visit-ast (js2-for-node-update n) v)
2452 (js2-visit-ast (js2-for-node-body n) v))
2453
2454 (defun js2-print-for-node (n i)
2455 (let ((pad (js2-make-pad i)))
2456 (insert pad "for (")
2457 (js2-print-ast (js2-for-node-init n) 0)
2458 (insert "; ")
2459 (js2-print-ast (js2-for-node-condition n) 0)
2460 (insert "; ")
2461 (js2-print-ast (js2-for-node-update n) 0)
2462 (insert ") {\n")
2463 (js2-print-body (js2-for-node-body n) (1+ i))
2464 (insert pad "}\n")))
2465
2466 (defstruct (js2-for-in-node
2467 (:include js2-loop-node)
2468 (:constructor nil)
2469 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2470 (pos js2-ts-cursor)
2471 len body
2472 iterator
2473 object
2474 in-pos
2475 each-pos
2476 foreach-p forof-p
2477 lp rp)))
2478 "AST node for a for..in loop."
2479 iterator ; [var] foo in ...
2480 object ; object over which we're iterating
2481 in-pos ; buffer position of 'in' keyword
2482 each-pos ; buffer position of 'each' keyword, if foreach-p
2483 foreach-p ; t if it's a for-each loop
2484 forof-p) ; t if it's a for-of loop
2485
2486 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2487 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2488
2489 (defun js2-visit-for-in-node (n v)
2490 (js2-visit-ast (js2-for-in-node-iterator n) v)
2491 (js2-visit-ast (js2-for-in-node-object n) v)
2492 (js2-visit-ast (js2-for-in-node-body n) v))
2493
2494 (defun js2-print-for-in-node (n i)
2495 (let ((pad (js2-make-pad i))
2496 (foreach (js2-for-in-node-foreach-p n))
2497 (forof (js2-for-in-node-forof-p n)))
2498 (insert pad "for ")
2499 (if foreach
2500 (insert "each "))
2501 (insert "(")
2502 (js2-print-ast (js2-for-in-node-iterator n) 0)
2503 (insert (if forof " of " " in "))
2504 (js2-print-ast (js2-for-in-node-object n) 0)
2505 (insert ") {\n")
2506 (js2-print-body (js2-for-in-node-body n) (1+ i))
2507 (insert pad "}\n")))
2508
2509 (defstruct (js2-return-node
2510 (:include js2-node)
2511 (:constructor nil)
2512 (:constructor make-js2-return-node (&key (type js2-RETURN)
2513 (pos js2-ts-cursor)
2514 len
2515 retval)))
2516 "AST node for a return statement."
2517 retval) ; expression to return, or 'undefined
2518
2519 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2520 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2521
2522 (defun js2-visit-return-node (n v)
2523 (js2-visit-ast (js2-return-node-retval n) v))
2524
2525 (defun js2-print-return-node (n i)
2526 (insert (js2-make-pad i) "return")
2527 (when (js2-return-node-retval n)
2528 (insert " ")
2529 (js2-print-ast (js2-return-node-retval n) 0))
2530 (insert ";\n"))
2531
2532 (defstruct (js2-if-node
2533 (:include js2-node)
2534 (:constructor nil)
2535 (:constructor make-js2-if-node (&key (type js2-IF)
2536 (pos js2-ts-cursor)
2537 len condition
2538 then-part
2539 else-pos
2540 else-part lp
2541 rp)))
2542 "AST node for an if-statement."
2543 condition ; expression
2544 then-part ; statement or block
2545 else-pos ; optional buffer position of 'else' keyword
2546 else-part ; optional statement or block
2547 lp ; position of left-paren, nil if omitted
2548 rp) ; position of right-paren, nil if omitted
2549
2550 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2551 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2552
2553 (defun js2-visit-if-node (n v)
2554 (js2-visit-ast (js2-if-node-condition n) v)
2555 (js2-visit-ast (js2-if-node-then-part n) v)
2556 (js2-visit-ast (js2-if-node-else-part n) v))
2557
2558 (defun js2-print-if-node (n i)
2559 (let ((pad (js2-make-pad i))
2560 (then-part (js2-if-node-then-part n))
2561 (else-part (js2-if-node-else-part n)))
2562 (insert pad "if (")
2563 (js2-print-ast (js2-if-node-condition n) 0)
2564 (insert ") {\n")
2565 (js2-print-body then-part (1+ i))
2566 (insert pad "}")
2567 (cond
2568 ((not else-part)
2569 (insert "\n"))
2570 ((js2-if-node-p else-part)
2571 (insert " else ")
2572 (js2-print-body else-part i))
2573 (t
2574 (insert " else {\n")
2575 (js2-print-body else-part (1+ i))
2576 (insert pad "}\n")))))
2577
2578 (defstruct (js2-try-node
2579 (:include js2-node)
2580 (:constructor nil)
2581 (:constructor make-js2-try-node (&key (type js2-TRY)
2582 (pos js2-ts-cursor)
2583 len
2584 try-block
2585 catch-clauses
2586 finally-block)))
2587 "AST node for a try-statement."
2588 try-block
2589 catch-clauses ; a Lisp list of `js2-catch-node'
2590 finally-block) ; a `js2-finally-node'
2591
2592 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2593 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2594
2595 (defun js2-visit-try-node (n v)
2596 (js2-visit-ast (js2-try-node-try-block n) v)
2597 (dolist (clause (js2-try-node-catch-clauses n))
2598 (js2-visit-ast clause v))
2599 (js2-visit-ast (js2-try-node-finally-block n) v))
2600
2601 (defun js2-print-try-node (n i)
2602 (let ((pad (js2-make-pad i))
2603 (catches (js2-try-node-catch-clauses n))
2604 (finally (js2-try-node-finally-block n)))
2605 (insert pad "try {\n")
2606 (js2-print-body (js2-try-node-try-block n) (1+ i))
2607 (insert pad "}")
2608 (when catches
2609 (dolist (catch catches)
2610 (js2-print-ast catch i)))
2611 (if finally
2612 (js2-print-ast finally i)
2613 (insert "\n"))))
2614
2615 (defstruct (js2-catch-node
2616 (:include js2-node)
2617 (:constructor nil)
2618 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2619 (pos js2-ts-cursor)
2620 len
2621 param
2622 guard-kwd
2623 guard-expr
2624 block lp
2625 rp)))
2626 "AST node for a catch clause."
2627 param ; destructuring form or simple name node
2628 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2629 guard-expr ; catch condition, a `js2-node'
2630 block ; statements, a `js2-block-node'
2631 lp ; buffer position of left-paren, nil if omitted
2632 rp) ; buffer position of right-paren, nil if omitted
2633
2634 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2635 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2636
2637 (defun js2-visit-catch-node (n v)
2638 (js2-visit-ast (js2-catch-node-param n) v)
2639 (when (js2-catch-node-guard-kwd n)
2640 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2641 (js2-visit-ast (js2-catch-node-block n) v))
2642
2643 (defun js2-print-catch-node (n i)
2644 (let ((pad (js2-make-pad i))
2645 (guard-kwd (js2-catch-node-guard-kwd n))
2646 (guard-expr (js2-catch-node-guard-expr n)))
2647 (insert " catch (")
2648 (js2-print-ast (js2-catch-node-param n) 0)
2649 (when guard-kwd
2650 (insert " if ")
2651 (js2-print-ast guard-expr 0))
2652 (insert ") {\n")
2653 (js2-print-body (js2-catch-node-block n) (1+ i))
2654 (insert pad "}")))
2655
2656 (defstruct (js2-finally-node
2657 (:include js2-node)
2658 (:constructor nil)
2659 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2660 (pos js2-ts-cursor)
2661 len body)))
2662 "AST node for a finally clause."
2663 body) ; a `js2-node', often but not always a block node
2664
2665 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2666 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2667
2668 (defun js2-visit-finally-node (n v)
2669 (js2-visit-ast (js2-finally-node-body n) v))
2670
2671 (defun js2-print-finally-node (n i)
2672 (let ((pad (js2-make-pad i)))
2673 (insert " finally {\n")
2674 (js2-print-body (js2-finally-node-body n) (1+ i))
2675 (insert pad "}\n")))
2676
2677 (defstruct (js2-switch-node
2678 (:include js2-node)
2679 (:constructor nil)
2680 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2681 (pos js2-ts-cursor)
2682 len
2683 discriminant
2684 cases lp
2685 rp)))
2686 "AST node for a switch statement."
2687 discriminant ; a `js2-node' (switch expression)
2688 cases ; a Lisp list of `js2-case-node'
2689 lp ; position of open-paren for discriminant, nil if omitted
2690 rp) ; position of close-paren for discriminant, nil if omitted
2691
2692 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2693 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2694
2695 (defun js2-visit-switch-node (n v)
2696 (js2-visit-ast (js2-switch-node-discriminant n) v)
2697 (dolist (c (js2-switch-node-cases n))
2698 (js2-visit-ast c v)))
2699
2700 (defun js2-print-switch-node (n i)
2701 (let ((pad (js2-make-pad i))
2702 (cases (js2-switch-node-cases n)))
2703 (insert pad "switch (")
2704 (js2-print-ast (js2-switch-node-discriminant n) 0)
2705 (insert ") {\n")
2706 (dolist (case cases)
2707 (js2-print-ast case i))
2708 (insert pad "}\n")))
2709
2710 (defstruct (js2-case-node
2711 (:include js2-block-node)
2712 (:constructor nil)
2713 (:constructor make-js2-case-node (&key (type js2-CASE)
2714 (pos js2-ts-cursor)
2715 len kids expr)))
2716 "AST node for a case clause of a switch statement."
2717 expr) ; the case expression (nil for default)
2718
2719 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2720 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2721
2722 (defun js2-visit-case-node (n v)
2723 (js2-visit-ast (js2-case-node-expr n) v)
2724 (js2-visit-block n v))
2725
2726 (defun js2-print-case-node (n i)
2727 (let ((pad (js2-make-pad i))
2728 (expr (js2-case-node-expr n)))
2729 (insert pad)
2730 (if (null expr)
2731 (insert "default:\n")
2732 (insert "case ")
2733 (js2-print-ast expr 0)
2734 (insert ":\n"))
2735 (dolist (kid (js2-case-node-kids n))
2736 (js2-print-ast kid (1+ i)))))
2737
2738 (defstruct (js2-throw-node
2739 (:include js2-node)
2740 (:constructor nil)
2741 (:constructor make-js2-throw-node (&key (type js2-THROW)
2742 (pos js2-ts-cursor)
2743 len expr)))
2744 "AST node for a throw statement."
2745 expr) ; the expression to throw
2746
2747 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2748 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2749
2750 (defun js2-visit-throw-node (n v)
2751 (js2-visit-ast (js2-throw-node-expr n) v))
2752
2753 (defun js2-print-throw-node (n i)
2754 (insert (js2-make-pad i) "throw ")
2755 (js2-print-ast (js2-throw-node-expr n) 0)
2756 (insert ";\n"))
2757
2758 (defstruct (js2-with-node
2759 (:include js2-node)
2760 (:constructor nil)
2761 (:constructor make-js2-with-node (&key (type js2-WITH)
2762 (pos js2-ts-cursor)
2763 len object
2764 body lp rp)))
2765 "AST node for a with-statement."
2766 object
2767 body
2768 lp ; buffer position of left-paren around object, nil if omitted
2769 rp) ; buffer position of right-paren around object, nil if omitted
2770
2771 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2772 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2773
2774 (defun js2-visit-with-node (n v)
2775 (js2-visit-ast (js2-with-node-object n) v)
2776 (js2-visit-ast (js2-with-node-body n) v))
2777
2778 (defun js2-print-with-node (n i)
2779 (let ((pad (js2-make-pad i)))
2780 (insert pad "with (")
2781 (js2-print-ast (js2-with-node-object n) 0)
2782 (insert ") {\n")
2783 (js2-print-body (js2-with-node-body n) (1+ i))
2784 (insert pad "}\n")))
2785
2786 (defstruct (js2-label-node
2787 (:include js2-node)
2788 (:constructor nil)
2789 (:constructor make-js2-label-node (&key (type js2-LABEL)
2790 (pos js2-ts-cursor)
2791 len name)))
2792 "AST node for a statement label or case label."
2793 name ; a string
2794 loop) ; for validating and code-generating continue-to-label
2795
2796 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2797 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2798
2799 (defun js2-print-label (n i)
2800 (insert (js2-make-pad i)
2801 (js2-label-node-name n)
2802 ":\n"))
2803
2804 (defstruct (js2-labeled-stmt-node
2805 (:include js2-node)
2806 (:constructor nil)
2807 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2808 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2809 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2810 (pos js2-ts-cursor)
2811 len labels stmt)))
2812 "AST node for a statement with one or more labels.
2813 Multiple labels for a statement are collapsed into the labels field."
2814 labels ; Lisp list of `js2-label-node'
2815 stmt) ; the statement these labels are for
2816
2817 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2818 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2819
2820 (defun js2-get-label-by-name (lbl-stmt name)
2821 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2822 Returns nil if no such label is in the list."
2823 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2824 result)
2825 (while (and label-list (not result))
2826 (if (string= (js2-label-node-name (car label-list)) name)
2827 (setq result (car label-list))
2828 (setq label-list (cdr label-list))))
2829 result))
2830
2831 (defun js2-visit-labeled-stmt (n v)
2832 (dolist (label (js2-labeled-stmt-node-labels n))
2833 (js2-visit-ast label v))
2834 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2835
2836 (defun js2-print-labeled-stmt (n i)
2837 (dolist (label (js2-labeled-stmt-node-labels n))
2838 (js2-print-ast label i))
2839 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2840
2841 (defun js2-labeled-stmt-node-contains (node label)
2842 "Return t if NODE contains LABEL in its label set.
2843 NODE is a `js2-labels-node'. LABEL is an identifier."
2844 (loop for nl in (js2-labeled-stmt-node-labels node)
2845 if (string= label (js2-label-node-name nl))
2846 return t
2847 finally return nil))
2848
2849 (defsubst js2-labeled-stmt-node-add-label (node label)
2850 "Add a `js2-label-node' to the label set for this statement."
2851 (setf (js2-labeled-stmt-node-labels node)
2852 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2853
2854 (defstruct (js2-jump-node
2855 (:include js2-node)
2856 (:constructor nil))
2857 "Abstract supertype of break and continue nodes."
2858 label ; `js2-name-node' for location of label identifier, if present
2859 target) ; target js2-labels-node or loop/switch statement
2860
2861 (defun js2-visit-jump-node (n v)
2862 ;; We don't visit the target, since it's a back-link.
2863 (js2-visit-ast (js2-jump-node-label n) v))
2864
2865 (defstruct (js2-break-node
2866 (:include js2-jump-node)
2867 (:constructor nil)
2868 (:constructor make-js2-break-node (&key (type js2-BREAK)
2869 (pos js2-ts-cursor)
2870 len label target)))
2871 "AST node for a break statement.
2872 The label field is a `js2-name-node', possibly nil, for the named label
2873 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2874 is the target of the break - a label node or enclosing loop/switch statement.")
2875
2876 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2877 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2878
2879 (defun js2-print-break-node (n i)
2880 (insert (js2-make-pad i) "break")
2881 (when (js2-break-node-label n)
2882 (insert " ")
2883 (js2-print-ast (js2-break-node-label n) 0))
2884 (insert ";\n"))
2885
2886 (defstruct (js2-continue-node
2887 (:include js2-jump-node)
2888 (:constructor nil)
2889 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2890 (pos js2-ts-cursor)
2891 len label target)))
2892 "AST node for a continue statement.
2893 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2894 It is nil if continue specifies no label. The target field is the jump target:
2895 a `js2-label-node' or the innermost enclosing loop.")
2896
2897 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2898 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2899
2900 (defun js2-print-continue-node (n i)
2901 (insert (js2-make-pad i) "continue")
2902 (when (js2-continue-node-label n)
2903 (insert " ")
2904 (js2-print-ast (js2-continue-node-label n) 0))
2905 (insert ";\n"))
2906
2907 (defstruct (js2-function-node
2908 (:include js2-script-node)
2909 (:constructor nil)
2910 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2911 (pos js2-ts-cursor)
2912 len
2913 (ftype 'FUNCTION)
2914 (form 'FUNCTION_STATEMENT)
2915 (name "")
2916 params rest-p
2917 body
2918 lp rp)))
2919 "AST node for a function declaration.
2920 The `params' field is a Lisp list of nodes. Each node is either a simple
2921 `js2-name-node', or if it's a destructuring-assignment parameter, a
2922 `js2-array-node' or `js2-object-node'."
2923 ftype ; FUNCTION, GETTER or SETTER
2924 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2925 name ; function name (a `js2-name-node', or nil if anonymous)
2926 params ; a Lisp list of destructuring forms or simple name nodes
2927 rest-p ; if t, the last parameter is rest parameter
2928 body ; a `js2-block-node' or expression node (1.8 only)
2929 lp ; position of arg-list open-paren, or nil if omitted
2930 rp ; position of arg-list close-paren, or nil if omitted
2931 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2932 needs-activation ; t if we need an activation object for this frame
2933 is-generator ; t if this function contains a yield
2934 member-expr) ; nonstandard Ecma extension from Rhino
2935
2936 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2937 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2938
2939 (defun js2-visit-function-node (n v)
2940 (js2-visit-ast (js2-function-node-name n) v)
2941 (dolist (p (js2-function-node-params n))
2942 (js2-visit-ast p v))
2943 (js2-visit-ast (js2-function-node-body n) v))
2944
2945 (defun js2-print-function-node (n i)
2946 (let ((pad (js2-make-pad i))
2947 (getter (js2-node-get-prop n 'GETTER_SETTER))
2948 (name (js2-function-node-name n))
2949 (params (js2-function-node-params n))
2950 (rest-p (js2-function-node-rest-p n))
2951 (body (js2-function-node-body n))
2952 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2953 (unless getter
2954 (insert pad "function"))
2955 (when name
2956 (insert " ")
2957 (js2-print-ast name 0))
2958 (insert "(")
2959 (loop with len = (length params)
2960 for param in params
2961 for count from 1
2962 do
2963 (when (and rest-p (= count len))
2964 (insert "..."))
2965 (js2-print-ast param 0)
2966 (when (< count len)
2967 (insert ", ")))
2968 (insert ") {")
2969 (unless expr
2970 (insert "\n"))
2971 ;; TODO: fix this to be smarter about indenting, etc.
2972 (js2-print-body body (1+ i))
2973 (insert pad "}")
2974 (unless expr
2975 (insert "\n"))))
2976
2977 (defun js2-function-name (node)
2978 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2979 (and (js2-function-node-name node)
2980 (js2-name-node-name (js2-function-node-name node))))
2981
2982 ;; Having this be an expression node makes it more flexible.
2983 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2984 ;; that work better if you assume it's an expression. Whenever we have
2985 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2986 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2987 (defstruct (js2-var-decl-node
2988 (:include js2-node)
2989 (:constructor nil)
2990 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2991 (pos js2-token-beg)
2992 len kids
2993 decl-type)))
2994 "AST node for a variable declaration list (VAR, CONST or LET).
2995 The node bounds differ depending on the declaration type. For VAR or
2996 CONST declarations, the bounds include the var/const keyword. For LET
2997 declarations, the node begins at the position of the first child."
2998 kids ; a Lisp list of `js2-var-init-node' structs.
2999 decl-type) ; js2-VAR, js2-CONST or js2-LET
3000
3001 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3002 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3003
3004 (defun js2-visit-var-decl (n v)
3005 (dolist (kid (js2-var-decl-node-kids n))
3006 (js2-visit-ast kid v)))
3007
3008 (defun js2-print-var-decl (n i)
3009 (let ((pad (js2-make-pad i))
3010 (tt (js2-var-decl-node-decl-type n)))
3011 (insert pad)
3012 (insert (cond
3013 ((= tt js2-VAR) "var ")
3014 ((= tt js2-LET) "let ")
3015 ((= tt js2-CONST) "const ")
3016 (t
3017 (error "malformed var-decl node"))))
3018 (loop with kids = (js2-var-decl-node-kids n)
3019 with len = (length kids)
3020 for kid in kids
3021 for count from 1
3022 do
3023 (js2-print-ast kid 0)
3024 (if (< count len)
3025 (insert ", ")))))
3026
3027 (defstruct (js2-var-init-node
3028 (:include js2-node)
3029 (:constructor nil)
3030 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3031 (pos js2-ts-cursor)
3032 len target
3033 initializer)))
3034 "AST node for a variable declaration.
3035 The type field will be js2-CONST for a const decl."
3036 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3037 initializer) ; initializer expression, a `js2-node'
3038
3039 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3040 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3041
3042 (defun js2-visit-var-init-node (n v)
3043 (js2-visit-ast (js2-var-init-node-target n) v)
3044 (js2-visit-ast (js2-var-init-node-initializer n) v))
3045
3046 (defun js2-print-var-init-node (n i)
3047 (let ((pad (js2-make-pad i))
3048 (name (js2-var-init-node-target n))
3049 (init (js2-var-init-node-initializer n)))
3050 (insert pad)
3051 (js2-print-ast name 0)
3052 (when init
3053 (insert " = ")
3054 (js2-print-ast init 0))))
3055
3056 (defstruct (js2-cond-node
3057 (:include js2-node)
3058 (:constructor nil)
3059 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3060 (pos js2-ts-cursor)
3061 len
3062 test-expr
3063 true-expr
3064 false-expr
3065 q-pos c-pos)))
3066 "AST node for the ternary operator"
3067 test-expr
3068 true-expr
3069 false-expr
3070 q-pos ; buffer position of ?
3071 c-pos) ; buffer position of :
3072
3073 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3074 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3075
3076 (defun js2-visit-cond-node (n v)
3077 (js2-visit-ast (js2-cond-node-test-expr n) v)
3078 (js2-visit-ast (js2-cond-node-true-expr n) v)
3079 (js2-visit-ast (js2-cond-node-false-expr n) v))
3080
3081 (defun js2-print-cond-node (n i)
3082 (let ((pad (js2-make-pad i)))
3083 (insert pad)
3084 (js2-print-ast (js2-cond-node-test-expr n) 0)
3085 (insert " ? ")
3086 (js2-print-ast (js2-cond-node-true-expr n) 0)
3087 (insert " : ")
3088 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3089
3090 (defstruct (js2-infix-node
3091 (:include js2-node)
3092 (:constructor nil)
3093 (:constructor make-js2-infix-node (&key type
3094 (pos js2-ts-cursor)
3095 len op-pos
3096 left right)))
3097 "Represents infix expressions.
3098 Includes assignment ops like `|=', and the comma operator.
3099 The type field inherited from `js2-node' holds the operator."
3100 op-pos ; buffer position where operator begins
3101 left ; any `js2-node'
3102 right) ; any `js2-node'
3103
3104 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3105 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3106
3107 (defun js2-visit-infix-node (n v)
3108 (js2-visit-ast (js2-infix-node-left n) v)
3109 (js2-visit-ast (js2-infix-node-right n) v))
3110
3111 (defconst js2-operator-tokens
3112 (let ((table (make-hash-table :test 'eq))
3113 (tokens
3114 (list (cons js2-IN "in")
3115 (cons js2-TYPEOF "typeof")
3116 (cons js2-INSTANCEOF "instanceof")
3117 (cons js2-DELPROP "delete")
3118 (cons js2-COMMA ",")
3119 (cons js2-COLON ":")
3120 (cons js2-OR "||")
3121 (cons js2-AND "&&")
3122 (cons js2-INC "++")
3123 (cons js2-DEC "--")
3124 (cons js2-BITOR "|")
3125 (cons js2-BITXOR "^")
3126 (cons js2-BITAND "&")
3127 (cons js2-EQ "==")
3128 (cons js2-NE "!=")
3129 (cons js2-LT "<")
3130 (cons js2-LE "<=")
3131 (cons js2-GT ">")
3132 (cons js2-GE ">=")
3133 (cons js2-LSH "<<")
3134 (cons js2-RSH ">>")
3135 (cons js2-URSH ">>>")
3136 (cons js2-ADD "+") ; infix plus
3137 (cons js2-SUB "-") ; infix minus
3138 (cons js2-MUL "*")
3139 (cons js2-DIV "/")
3140 (cons js2-MOD "%")
3141 (cons js2-NOT "!")
3142 (cons js2-BITNOT "~")
3143 (cons js2-POS "+") ; unary plus
3144 (cons js2-NEG "-") ; unary minus
3145 (cons js2-SHEQ "===") ; shallow equality
3146 (cons js2-SHNE "!==") ; shallow inequality
3147 (cons js2-ASSIGN "=")
3148 (cons js2-ASSIGN_BITOR "|=")
3149 (cons js2-ASSIGN_BITXOR "^=")
3150 (cons js2-ASSIGN_BITAND "&=")
3151 (cons js2-ASSIGN_LSH "<<=")
3152 (cons js2-ASSIGN_RSH ">>=")
3153 (cons js2-ASSIGN_URSH ">>>=")
3154 (cons js2-ASSIGN_ADD "+=")
3155 (cons js2-ASSIGN_SUB "-=")
3156 (cons js2-ASSIGN_MUL "*=")
3157 (cons js2-ASSIGN_DIV "/=")
3158 (cons js2-ASSIGN_MOD "%="))))
3159 (loop for (k . v) in tokens do
3160 (puthash k v table))
3161 table))
3162
3163 (defun js2-print-infix-node (n i)
3164 (let* ((tt (js2-node-type n))
3165 (op (gethash tt js2-operator-tokens)))
3166 (unless op
3167 (error "unrecognized infix operator %s" (js2-node-type n)))
3168 (insert (js2-make-pad i))
3169 (js2-print-ast (js2-infix-node-left n) 0)
3170 (unless (= tt js2-COMMA)
3171 (insert " "))
3172 (insert op)
3173 (insert " ")
3174 (js2-print-ast (js2-infix-node-right n) 0)))
3175
3176 (defstruct (js2-assign-node
3177 (:include js2-infix-node)
3178 (:constructor nil)
3179 (:constructor make-js2-assign-node (&key type
3180 (pos js2-ts-cursor)
3181 len op-pos
3182 left right)))
3183 "Represents any assignment.
3184 The type field holds the actual assignment operator.")
3185
3186 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3187 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3188
3189 (defstruct (js2-unary-node
3190 (:include js2-node)
3191 (:constructor nil)
3192 (:constructor make-js2-unary-node (&key type ; required
3193 (pos js2-ts-cursor)
3194 len operand)))
3195 "AST node type for unary operator nodes.
3196 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3197 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3198 property is added if the operator follows the operand."
3199 operand) ; a `js2-node' expression
3200
3201 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3202 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3203
3204 (defun js2-visit-unary-node (n v)
3205 (js2-visit-ast (js2-unary-node-operand n) v))
3206
3207 (defun js2-print-unary-node (n i)
3208 (let* ((tt (js2-node-type n))
3209 (op (gethash tt js2-operator-tokens))
3210 (postfix (js2-node-get-prop n 'postfix)))
3211 (unless op
3212 (error "unrecognized unary operator %s" tt))
3213 (insert (js2-make-pad i))
3214 (unless postfix
3215 (insert op))
3216 (if (or (= tt js2-TYPEOF)
3217 (= tt js2-DELPROP))
3218 (insert " "))
3219 (js2-print-ast (js2-unary-node-operand n) 0)
3220 (when postfix
3221 (insert op))))
3222
3223 (defstruct (js2-let-node
3224 (:include js2-scope)
3225 (:constructor nil)
3226 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3227 (pos js2-token-beg)
3228 len vars body
3229 lp rp)))
3230 "AST node for a let expression or a let statement.
3231 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3232 vars ; a `js2-var-decl-node'
3233 body ; a `js2-node' representing the expression or body block
3234 lp
3235 rp)
3236
3237 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3238 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3239
3240 (defun js2-visit-let-node (n v)
3241 (js2-visit-ast (js2-let-node-vars n) v)
3242 (js2-visit-ast (js2-let-node-body n) v))
3243
3244 (defun js2-print-let-node (n i)
3245 (insert (js2-make-pad i) "let (")
3246 (js2-print-ast (js2-let-node-vars n) 0)
3247 (insert ") ")
3248 (js2-print-ast (js2-let-node-body n) i))
3249
3250 (defstruct (js2-keyword-node
3251 (:include js2-node)
3252 (:constructor nil)
3253 (:constructor make-js2-keyword-node (&key type
3254 (pos js2-token-beg)
3255 (len (- js2-ts-cursor pos)))))
3256 "AST node representing a literal keyword such as `null'.
3257 Used for `null', `this', `true', `false' and `debugger'.
3258 The node type is set to js2-NULL, js2-THIS, etc.")
3259
3260 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3261 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3262
3263 (defun js2-print-keyword-node (n i)
3264 (insert (js2-make-pad i)
3265 (let ((tt (js2-node-type n)))
3266 (cond
3267 ((= tt js2-THIS) "this")
3268 ((= tt js2-NULL) "null")
3269 ((= tt js2-TRUE) "true")
3270 ((= tt js2-FALSE) "false")
3271 ((= tt js2-DEBUGGER) "debugger")
3272 (t (error "Invalid keyword literal type: %d" tt))))))
3273
3274 (defsubst js2-this-node-p (node)
3275 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3276 (eq (js2-node-type node) js2-THIS))
3277
3278 (defstruct (js2-new-node
3279 (:include js2-node)
3280 (:constructor nil)
3281 (:constructor make-js2-new-node (&key (type js2-NEW)
3282 (pos js2-token-beg)
3283 len target
3284 args initializer
3285 lp rp)))
3286 "AST node for new-expression such as new Foo()."
3287 target ; an identifier or reference
3288 args ; a Lisp list of argument nodes
3289 lp ; position of left-paren, nil if omitted
3290 rp ; position of right-paren, nil if omitted
3291 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3292
3293 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3294 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3295
3296 (defun js2-visit-new-node (n v)
3297 (js2-visit-ast (js2-new-node-target n) v)
3298 (dolist (arg (js2-new-node-args n))
3299 (js2-visit-ast arg v))
3300 (js2-visit-ast (js2-new-node-initializer n) v))
3301
3302 (defun js2-print-new-node (n i)
3303 (insert (js2-make-pad i) "new ")
3304 (js2-print-ast (js2-new-node-target n))
3305 (insert "(")
3306 (js2-print-list (js2-new-node-args n))
3307 (insert ")")
3308 (when (js2-new-node-initializer n)
3309 (insert " ")
3310 (js2-print-ast (js2-new-node-initializer n))))
3311
3312 (defstruct (js2-name-node
3313 (:include js2-node)
3314 (:constructor nil)
3315 (:constructor make-js2-name-node (&key (type js2-NAME)
3316 (pos js2-token-beg)
3317 (len (- js2-ts-cursor
3318 js2-token-beg))
3319 (name js2-ts-string))))
3320 "AST node for a JavaScript identifier"
3321 name ; a string
3322 scope) ; a `js2-scope' (optional, used for codegen)
3323
3324 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3325 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3326
3327 (defun js2-print-name-node (n i)
3328 (insert (js2-make-pad i)
3329 (js2-name-node-name n)))
3330
3331 (defsubst js2-name-node-length (node)
3332 "Return identifier length of NODE, a `js2-name-node'.
3333 Returns 0 if NODE is nil or its identifier field is nil."
3334 (if node
3335 (length (js2-name-node-name node))
3336 0))
3337
3338 (defstruct (js2-number-node
3339 (:include js2-node)
3340 (:constructor nil)
3341 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3342 (pos js2-token-beg)
3343 (len (- js2-ts-cursor
3344 js2-token-beg))
3345 (value js2-ts-string)
3346 (num-value js2-ts-number))))
3347 "AST node for a number literal."
3348 value ; the original string, e.g. "6.02e23"
3349 num-value) ; the parsed number value
3350
3351 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3352 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3353
3354 (defun js2-print-number-node (n i)
3355 (insert (js2-make-pad i)
3356 (number-to-string (js2-number-node-num-value n))))
3357
3358 (defstruct (js2-regexp-node
3359 (:include js2-node)
3360 (:constructor nil)
3361 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3362 (pos js2-token-beg)
3363 (len (- js2-ts-cursor
3364 js2-token-beg))
3365 value flags)))
3366 "AST node for a regular expression literal."
3367 value ; the regexp string, without // delimiters
3368 flags) ; a string of flags, e.g. `mi'.
3369
3370 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3371 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3372
3373 (defun js2-print-regexp (n i)
3374 (insert (js2-make-pad i)
3375 "/"
3376 (js2-regexp-node-value n)
3377 "/")
3378 (if (js2-regexp-node-flags n)
3379 (insert (js2-regexp-node-flags n))))
3380
3381 (defstruct (js2-string-node
3382 (:include js2-node)
3383 (:constructor nil)
3384 (:constructor make-js2-string-node (&key (type js2-STRING)
3385 (pos js2-token-beg)
3386 (len (- js2-ts-cursor
3387 js2-token-beg))
3388 (value js2-ts-string))))
3389 "String literal.
3390 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3391 You can tell the quote type by looking at the first character."
3392 value) ; the characters of the string, including the quotes
3393
3394 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3395 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3396
3397 (defun js2-print-string-node (n i)
3398 (insert (js2-make-pad i)
3399 (js2-node-string n)))
3400
3401 (defstruct (js2-array-node
3402 (:include js2-node)
3403 (:constructor nil)
3404 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3405 (pos js2-ts-cursor)
3406 len elems)))
3407 "AST node for an array literal."
3408 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3409
3410 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3411 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3412
3413 (defun js2-visit-array-node (n v)
3414 (dolist (e (js2-array-node-elems n))
3415 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3416
3417 (defun js2-print-array-node (n i)
3418 (insert (js2-make-pad i) "[")
3419 (js2-print-list (js2-array-node-elems n))
3420 (insert "]"))
3421
3422 (defstruct (js2-object-node
3423 (:include js2-node)
3424 (:constructor nil)
3425 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3426 (pos js2-ts-cursor)
3427 len
3428 elems)))
3429 "AST node for an object literal expression.
3430 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3431 The latter represents abbreviation in destructuring expressions."
3432 elems)
3433
3434 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3435 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3436
3437 (defun js2-visit-object-node (n v)
3438 (dolist (e (js2-object-node-elems n))
3439 (js2-visit-ast e v)))
3440
3441 (defun js2-print-object-node (n i)
3442 (insert (js2-make-pad i) "{")
3443 (js2-print-list (js2-object-node-elems n))
3444 (insert "}"))
3445
3446 (defstruct (js2-object-prop-node
3447 (:include js2-infix-node)
3448 (:constructor nil)
3449 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3450 (pos js2-ts-cursor)
3451 len left
3452 right op-pos)))
3453 "AST node for an object literal prop:value entry.
3454 The `left' field is the property: a name node, string node or number node.
3455 The `right' field is a `js2-node' representing the initializer value.")
3456
3457 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3458 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3459
3460 (defun js2-print-object-prop-node (n i)
3461 (insert (js2-make-pad i))
3462 (js2-print-ast (js2-object-prop-node-left n) 0)
3463 (insert ": ")
3464 (js2-print-ast (js2-object-prop-node-right n) 0))
3465
3466 (defstruct (js2-getter-setter-node
3467 (:include js2-infix-node)
3468 (:constructor nil)
3469 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3470 (pos js2-ts-cursor)
3471 len left right)))
3472 "AST node for a getter/setter property in an object literal.
3473 The `left' field is the `js2-name-node' naming the getter/setter prop.
3474 The `right' field is always an anonymous `js2-function-node' with a node
3475 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3476
3477 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3478 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3479
3480 (defun js2-print-getter-setter (n i)
3481 (let ((pad (js2-make-pad i))
3482 (left (js2-getter-setter-node-left n))
3483 (right (js2-getter-setter-node-right n)))
3484 (insert pad)
3485 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3486 (js2-print-ast left 0)
3487 (js2-print-ast right 0)))
3488
3489 (defstruct (js2-prop-get-node
3490 (:include js2-infix-node)
3491 (:constructor nil)
3492 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3493 (pos js2-ts-cursor)
3494 len left right)))
3495 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3496
3497 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3498 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3499
3500 (defun js2-visit-prop-get-node (n v)
3501 (js2-visit-ast (js2-prop-get-node-left n) v)
3502 (js2-visit-ast (js2-prop-get-node-right n) v))
3503
3504 (defun js2-print-prop-get-node (n i)
3505 (insert (js2-make-pad i))
3506 (js2-print-ast (js2-prop-get-node-left n) 0)
3507 (insert ".")
3508 (js2-print-ast (js2-prop-get-node-right n) 0))
3509
3510 (defstruct (js2-elem-get-node
3511 (:include js2-node)
3512 (:constructor nil)
3513 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3514 (pos js2-ts-cursor)
3515 len target element
3516 lb rb)))
3517 "AST node for an array index expression such as foo[bar]."
3518 target ; a `js2-node' - the expression preceding the "."
3519 element ; a `js2-node' - the expression in brackets
3520 lb ; position of left-bracket, nil if omitted
3521 rb) ; position of right-bracket, nil if omitted
3522
3523 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3524 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3525
3526 (defun js2-visit-elem-get-node (n v)
3527 (js2-visit-ast (js2-elem-get-node-target n) v)
3528 (js2-visit-ast (js2-elem-get-node-element n) v))
3529
3530 (defun js2-print-elem-get-node (n i)
3531 (insert (js2-make-pad i))
3532 (js2-print-ast (js2-elem-get-node-target n) 0)
3533 (insert "[")
3534 (js2-print-ast (js2-elem-get-node-element n) 0)
3535 (insert "]"))
3536
3537 (defstruct (js2-call-node
3538 (:include js2-node)
3539 (:constructor nil)
3540 (:constructor make-js2-call-node (&key (type js2-CALL)
3541 (pos js2-ts-cursor)
3542 len target args
3543 lp rp)))
3544 "AST node for a JavaScript function call."
3545 target ; a `js2-node' evaluating to the function to call
3546 args ; a Lisp list of `js2-node' arguments
3547 lp ; position of open-paren, or nil if missing
3548 rp) ; position of close-paren, or nil if missing
3549
3550 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3551 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3552
3553 (defun js2-visit-call-node (n v)
3554 (js2-visit-ast (js2-call-node-target n) v)
3555 (dolist (arg (js2-call-node-args n))
3556 (js2-visit-ast arg v)))
3557
3558 (defun js2-print-call-node (n i)
3559 (insert (js2-make-pad i))
3560 (js2-print-ast (js2-call-node-target n) 0)
3561 (insert "(")
3562 (js2-print-list (js2-call-node-args n))
3563 (insert ")"))
3564
3565 (defstruct (js2-yield-node
3566 (:include js2-node)
3567 (:constructor nil)
3568 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3569 (pos js2-ts-cursor)
3570 len value)))
3571 "AST node for yield statement or expression."
3572 value) ; optional: value to be yielded
3573
3574 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3575 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3576
3577 (defun js2-visit-yield-node (n v)
3578 (js2-visit-ast (js2-yield-node-value n) v))
3579
3580 (defun js2-print-yield-node (n i)
3581 (insert (js2-make-pad i))
3582 (insert "yield")
3583 (when (js2-yield-node-value n)
3584 (insert " ")
3585 (js2-print-ast (js2-yield-node-value n) 0)))
3586
3587 (defstruct (js2-paren-node
3588 (:include js2-node)
3589 (:constructor nil)
3590 (:constructor make-js2-paren-node (&key (type js2-LP)
3591 (pos js2-ts-cursor)
3592 len expr)))
3593 "AST node for a parenthesized expression.
3594 In particular, used when the parens are syntactically optional,
3595 as opposed to required parens such as those enclosing an if-conditional."
3596 expr) ; `js2-node'
3597
3598 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3599 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3600
3601 (defun js2-visit-paren-node (n v)
3602 (js2-visit-ast (js2-paren-node-expr n) v))
3603
3604 (defun js2-print-paren-node (n i)
3605 (insert (js2-make-pad i))
3606 (insert "(")
3607 (js2-print-ast (js2-paren-node-expr n) 0)
3608 (insert ")"))
3609
3610 (defstruct (js2-array-comp-node
3611 (:include js2-scope)
3612 (:constructor nil)
3613 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3614 (pos js2-ts-cursor)
3615 len result
3616 loops filter
3617 if-pos lp rp)))
3618 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3619 result ; result expression (just after left-bracket)
3620 loops ; a Lisp list of `js2-array-comp-loop-node'
3621 filter ; guard/filter expression
3622 if-pos ; buffer pos of 'if' keyword, if present, else nil
3623 lp ; buffer position of if-guard left-paren, or nil if not present
3624 rp) ; buffer position of if-guard right-paren, or nil if not present
3625
3626 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3627 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3628
3629 (defun js2-visit-array-comp-node (n v)
3630 (js2-visit-ast (js2-array-comp-node-result n) v)
3631 (dolist (l (js2-array-comp-node-loops n))
3632 (js2-visit-ast l v))
3633 (js2-visit-ast (js2-array-comp-node-filter n) v))
3634
3635 (defun js2-print-array-comp-node (n i)
3636 (let ((pad (js2-make-pad i))
3637 (result (js2-array-comp-node-result n))
3638 (loops (js2-array-comp-node-loops n))
3639 (filter (js2-array-comp-node-filter n)))
3640 (insert pad "[")
3641 (js2-print-ast result 0)
3642 (dolist (l loops)
3643 (insert " ")
3644 (js2-print-ast l 0))
3645 (when filter
3646 (insert " if (")
3647 (js2-print-ast filter 0)
3648 (insert ")"))
3649 (insert "]")))
3650
3651 (defstruct (js2-array-comp-loop-node
3652 (:include js2-for-in-node)
3653 (:constructor nil)
3654 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3655 (pos js2-ts-cursor)
3656 len iterator
3657 object in-pos
3658 foreach-p
3659 each-pos
3660 forof-p
3661 lp rp)))
3662 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3663
3664 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3665 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3666
3667 (defun js2-visit-array-comp-loop (n v)
3668 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3669 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3670
3671 (defun js2-print-array-comp-loop (n _i)
3672 (insert "for ")
3673 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3674 (insert "(")
3675 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3676 (insert (if (js2-array-comp-loop-node-forof-p n)
3677 " of " " 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 (defsubst js2-node-short-name (n)
4091 "Return the short name of node N as a string, e.g. `js2-if-node'."
4092 (substring (symbol-name (aref n 0))
4093 (length "cl-struct-")))
4094
4095 (defun js2-node-child-list (node)
4096 "Return the child list for NODE, a Lisp list of nodes.
4097 Works for block nodes, array nodes, obj literals, funarg lists,
4098 var decls and try nodes (for catch clauses). Note that you should call
4099 `js2-block-node-kids' on the function body for the body statements.
4100 Returns nil for zero-length child lists or unsupported nodes."
4101 (cond
4102 ((js2-function-node-p node)
4103 (js2-function-node-params node))
4104 ((js2-block-node-p node)
4105 (js2-block-node-kids node))
4106 ((js2-try-node-p node)
4107 (js2-try-node-catch-clauses node))
4108 ((js2-array-node-p node)
4109 (js2-array-node-elems node))
4110 ((js2-object-node-p node)
4111 (js2-object-node-elems node))
4112 ((js2-call-node-p node)
4113 (js2-call-node-args node))
4114 ((js2-new-node-p node)
4115 (js2-new-node-args node))
4116 ((js2-var-decl-node-p node)
4117 (js2-var-decl-node-kids node))
4118 (t
4119 nil)))
4120
4121 (defun js2-node-set-child-list (node kids)
4122 "Set the child list for NODE to KIDS."
4123 (cond
4124 ((js2-function-node-p node)
4125 (setf (js2-function-node-params node) kids))
4126 ((js2-block-node-p node)
4127 (setf (js2-block-node-kids node) kids))
4128 ((js2-try-node-p node)
4129 (setf (js2-try-node-catch-clauses node) kids))
4130 ((js2-array-node-p node)
4131 (setf (js2-array-node-elems node) kids))
4132 ((js2-object-node-p node)
4133 (setf (js2-object-node-elems node) kids))
4134 ((js2-call-node-p node)
4135 (setf (js2-call-node-args node) kids))
4136 ((js2-new-node-p node)
4137 (setf (js2-new-node-args node) kids))
4138 ((js2-var-decl-node-p node)
4139 (setf (js2-var-decl-node-kids node) kids))
4140 (t
4141 (error "Unsupported node type: %s" (js2-node-short-name node))))
4142 kids)
4143
4144 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4145 (defconst js2-paren-expr-nodes
4146 '(cl-struct-js2-array-comp-loop-node
4147 cl-struct-js2-array-comp-node
4148 cl-struct-js2-call-node
4149 cl-struct-js2-catch-node
4150 cl-struct-js2-do-node
4151 cl-struct-js2-elem-get-node
4152 cl-struct-js2-for-in-node
4153 cl-struct-js2-for-node
4154 cl-struct-js2-function-node
4155 cl-struct-js2-if-node
4156 cl-struct-js2-let-node
4157 cl-struct-js2-new-node
4158 cl-struct-js2-paren-node
4159 cl-struct-js2-switch-node
4160 cl-struct-js2-while-node
4161 cl-struct-js2-with-node
4162 cl-struct-js2-xml-dot-query-node)
4163 "Node types that can have a parenthesized child expression.
4164 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4165
4166 (defsubst js2-paren-expr-node-p (node)
4167 "Return t for nodes that typically have a parenthesized child expression.
4168 Useful for computing the indentation anchors for arg-lists and conditions.
4169 Note that it may return a false positive, for instance when NODE is
4170 a `js2-new-node' and there are no arguments or parentheses."
4171 (memq (aref node 0) js2-paren-expr-nodes))
4172
4173 ;; Fake polymorphism... yech.
4174 (defun js2-node-lp (node)
4175 "Return relative left-paren position for NODE, if applicable.
4176 For `js2-elem-get-node' structs, returns left-bracket position.
4177 Note that the position may be nil in the case of a parse error."
4178 (cond
4179 ((js2-elem-get-node-p node)
4180 (js2-elem-get-node-lb node))
4181 ((js2-loop-node-p node)
4182 (js2-loop-node-lp node))
4183 ((js2-function-node-p node)
4184 (js2-function-node-lp node))
4185 ((js2-if-node-p node)
4186 (js2-if-node-lp node))
4187 ((js2-new-node-p node)
4188 (js2-new-node-lp node))
4189 ((js2-call-node-p node)
4190 (js2-call-node-lp node))
4191 ((js2-paren-node-p node)
4192 0)
4193 ((js2-switch-node-p node)
4194 (js2-switch-node-lp node))
4195 ((js2-catch-node-p node)
4196 (js2-catch-node-lp node))
4197 ((js2-let-node-p node)
4198 (js2-let-node-lp node))
4199 ((js2-array-comp-node-p node)
4200 (js2-array-comp-node-lp node))
4201 ((js2-with-node-p node)
4202 (js2-with-node-lp node))
4203 ((js2-xml-dot-query-node-p node)
4204 (1+ (js2-infix-node-op-pos node)))
4205 (t
4206 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4207
4208 ;; Fake polymorphism... blech.
4209 (defun js2-node-rp (node)
4210 "Return relative right-paren position for NODE, if applicable.
4211 For `js2-elem-get-node' structs, returns right-bracket position.
4212 Note that the position may be nil in the case of a parse error."
4213 (cond
4214 ((js2-elem-get-node-p node)
4215 (js2-elem-get-node-rb node))
4216 ((js2-loop-node-p node)
4217 (js2-loop-node-rp node))
4218 ((js2-function-node-p node)
4219 (js2-function-node-rp node))
4220 ((js2-if-node-p node)
4221 (js2-if-node-rp node))
4222 ((js2-new-node-p node)
4223 (js2-new-node-rp node))
4224 ((js2-call-node-p node)
4225 (js2-call-node-rp node))
4226 ((js2-paren-node-p node)
4227 (1- (js2-node-len node)))
4228 ((js2-switch-node-p node)
4229 (js2-switch-node-rp node))
4230 ((js2-catch-node-p node)
4231 (js2-catch-node-rp node))
4232 ((js2-let-node-p node)
4233 (js2-let-node-rp node))
4234 ((js2-array-comp-node-p node)
4235 (js2-array-comp-node-rp node))
4236 ((js2-with-node-p node)
4237 (js2-with-node-rp node))
4238 ((js2-xml-dot-query-node-p node)
4239 (1+ (js2-xml-dot-query-node-rp node)))
4240 (t
4241 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4242
4243 (defsubst js2-node-first-child (node)
4244 "Return the first element of `js2-node-child-list' for NODE."
4245 (car (js2-node-child-list node)))
4246
4247 (defsubst js2-node-last-child (node)
4248 "Return the last element of `js2-node-last-child' for NODE."
4249 (car (last (js2-node-child-list node))))
4250
4251 (defun js2-node-prev-sibling (node)
4252 "Return the previous statement in parent.
4253 Works for parents supported by `js2-node-child-list'.
4254 Returns nil if NODE is not in the parent, or PARENT is
4255 not a supported node, or if NODE is the first child."
4256 (let* ((p (js2-node-parent node))
4257 (kids (js2-node-child-list p))
4258 (sib (car kids)))
4259 (while (and kids
4260 (not (eq node (cadr kids))))
4261 (setq kids (cdr kids)
4262 sib (car kids)))
4263 sib))
4264
4265 (defun js2-node-next-sibling (node)
4266 "Return the next statement in parent block.
4267 Returns nil if NODE is not in the block, or PARENT is not
4268 a block node, or if NODE is the last statement."
4269 (let* ((p (js2-node-parent node))
4270 (kids (js2-node-child-list p)))
4271 (while (and kids
4272 (not (eq node (car kids))))
4273 (setq kids (cdr kids)))
4274 (cadr kids)))
4275
4276 (defun js2-node-find-child-before (pos parent &optional after)
4277 "Find the last child that starts before POS in parent.
4278 If AFTER is non-nil, returns first child starting after POS.
4279 POS is an absolute buffer position. PARENT is any node
4280 supported by `js2-node-child-list'.
4281 Returns nil if no applicable child is found."
4282 (let ((kids (if (js2-function-node-p parent)
4283 (js2-block-node-kids (js2-function-node-body parent))
4284 (js2-node-child-list parent)))
4285 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4286 (js2-function-node-body parent)
4287 parent)))
4288 kid result fn
4289 (continue t))
4290 (setq fn (if after '>= '<))
4291 (while (and kids continue)
4292 (setq kid (car kids))
4293 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4294 (setq result kid
4295 continue (not after))
4296 (setq continue after))
4297 (setq kids (cdr kids)))
4298 result))
4299
4300 (defun js2-node-find-child-after (pos parent)
4301 "Find first child that starts after POS in parent.
4302 POS is an absolute buffer position. PARENT is any node
4303 supported by `js2-node-child-list'.
4304 Returns nil if no applicable child is found."
4305 (js2-node-find-child-before pos parent 'after))
4306
4307 (defun js2-node-replace-child (pos parent new-node)
4308 "Replace node at index POS in PARENT with NEW-NODE.
4309 Only works for parents supported by `js2-node-child-list'."
4310 (let ((kids (js2-node-child-list parent))
4311 (i 0))
4312 (while (< i pos)
4313 (setq kids (cdr kids)
4314 i (1+ i)))
4315 (setcar kids new-node)
4316 (js2-node-add-children parent new-node)))
4317
4318 (defun js2-node-buffer (n)
4319 "Return the buffer associated with AST N.
4320 Returns nil if the buffer is not set as a property on the root
4321 node, or if parent links were not recorded during parsing."
4322 (let ((root (js2-node-root n)))
4323 (and root
4324 (js2-ast-root-p root)
4325 (js2-ast-root-buffer root))))
4326
4327 (defun js2-block-node-push (n kid)
4328 "Push js2-node KID onto the end of js2-block-node N's child list.
4329 KID is always added to the -end- of the kids list.
4330 Function also calls `js2-node-add-children' to add the parent link."
4331 (let ((kids (js2-node-child-list n)))
4332 (if kids
4333 (setcdr kids (nconc (cdr kids) (list kid)))
4334 (js2-node-set-child-list n (list kid)))
4335 (js2-node-add-children n kid)))
4336
4337 (defun js2-node-string (node)
4338 (with-current-buffer (or (js2-node-buffer node)
4339 (error "No buffer available for node %s" node))
4340 (let ((pos (js2-node-abs-pos node)))
4341 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4342
4343 ;; Container for storing the node we're looking for in a traversal.
4344 (js2-deflocal js2-discovered-node nil)
4345
4346 ;; Keep track of absolute node position during traversals.
4347 (js2-deflocal js2-visitor-offset nil)
4348
4349 (js2-deflocal js2-node-search-point nil)
4350
4351 (when js2-mode-dev-mode-p
4352 (defun js2-find-node-at-point ()
4353 (interactive)
4354 (let ((node (js2-node-at-point)))
4355 (message "%s" (or node "No node found at point"))))
4356 (defun js2-node-name-at-point ()
4357 (interactive)
4358 (let ((node (js2-node-at-point)))
4359 (message "%s" (if node
4360 (js2-node-short-name node)
4361 "No node found at point.")))))
4362
4363 (defun js2-node-at-point (&optional pos skip-comments)
4364 "Return AST node at POS, a buffer position, defaulting to current point.
4365 The `js2-mode-ast' variable must be set to the current parse tree.
4366 Signals an error if the AST (`js2-mode-ast') is nil.
4367 Always returns a node - if it can't find one, it returns the root.
4368 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4369 (let ((ast js2-mode-ast)
4370 result)
4371 (unless ast
4372 (error "No JavaScript AST available"))
4373 ;; Look through comments first, since they may be inside nodes that
4374 ;; would otherwise report a match.
4375 (setq pos (or pos (point))
4376 result (if (> pos (js2-node-abs-end ast))
4377 ast
4378 (if (not skip-comments)
4379 (js2-comment-at-point pos))))
4380 (unless result
4381 (setq js2-discovered-node nil
4382 js2-visitor-offset 0
4383 js2-node-search-point pos)
4384 (unwind-protect
4385 (catch 'js2-visit-done
4386 (js2-visit-ast ast #'js2-node-at-point-visitor))
4387 (setq js2-visitor-offset nil
4388 js2-node-search-point nil))
4389 (setq result js2-discovered-node))
4390 ;; may have found a comment beyond end of last child node,
4391 ;; since visiting the ast-root looks at the comment-list last.
4392 (if (and skip-comments
4393 (js2-comment-node-p result))
4394 (setq result nil))
4395 (or result js2-mode-ast)))
4396
4397 (defun js2-node-at-point-visitor (node end-p)
4398 (let ((rel-pos (js2-node-pos node))
4399 abs-pos
4400 abs-end
4401 (point js2-node-search-point))
4402 (cond
4403 (end-p
4404 ;; this evaluates to a non-nil return value, even if it's zero
4405 (decf js2-visitor-offset rel-pos))
4406 ;; we already looked for comments before visiting, and don't want them now
4407 ((js2-comment-node-p node)
4408 nil)
4409 (t
4410 (setq abs-pos (incf js2-visitor-offset rel-pos)
4411 ;; we only want to use the node if the point is before
4412 ;; the last character position in the node, so we decrement
4413 ;; the absolute end by 1.
4414 abs-end (+ abs-pos (js2-node-len node) -1))
4415 (cond
4416 ;; If this node starts after search-point, stop the search.
4417 ((> abs-pos point)
4418 (throw 'js2-visit-done nil))
4419 ;; If this node ends before the search-point, don't check kids.
4420 ((> point abs-end)
4421 nil)
4422 (t
4423 ;; Otherwise point is within this node, possibly in a child.
4424 (setq js2-discovered-node node)
4425 t)))))) ; keep processing kids to look for more specific match
4426
4427 (defsubst js2-block-comment-p (node)
4428 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4429 (and (js2-comment-node-p node)
4430 (memq (js2-comment-node-format node) '(jsdoc block))))
4431
4432 ;; TODO: put the comments in a vector and binary-search them instead
4433 (defun js2-comment-at-point (&optional pos)
4434 "Look through scanned comment nodes for one containing POS.
4435 POS is a buffer position that defaults to current point.
4436 Function returns nil if POS was not in any comment node."
4437 (let ((ast js2-mode-ast)
4438 (x (or pos (point)))
4439 beg end)
4440 (unless ast
4441 (error "No JavaScript AST available"))
4442 (catch 'done
4443 ;; Comments are stored in lexical order.
4444 (dolist (comment (js2-ast-root-comments ast) nil)
4445 (setq beg (js2-node-abs-pos comment)
4446 end (+ beg (js2-node-len comment)))
4447 (if (and (>= x beg)
4448 (<= x end))
4449 (throw 'done comment))))))
4450
4451 (defun js2-mode-find-parent-fn (node)
4452 "Find function enclosing NODE.
4453 Returns nil if NODE is not inside a function."
4454 (setq node (js2-node-parent node))
4455 (while (and node (not (js2-function-node-p node)))
4456 (setq node (js2-node-parent node)))
4457 (and (js2-function-node-p node) node))
4458
4459 (defun js2-mode-find-enclosing-fn (node)
4460 "Find function or root enclosing NODE."
4461 (if (js2-ast-root-p node)
4462 node
4463 (setq node (js2-node-parent node))
4464 (while (not (or (js2-ast-root-p node)
4465 (js2-function-node-p node)))
4466 (setq node (js2-node-parent node)))
4467 node))
4468
4469 (defun js2-mode-find-enclosing-node (beg end)
4470 "Find script or function fully enclosing BEG and END."
4471 (let ((node (js2-node-at-point beg))
4472 pos
4473 (continue t))
4474 (while continue
4475 (if (or (js2-ast-root-p node)
4476 (and (js2-function-node-p node)
4477 (<= (setq pos (js2-node-abs-pos node)) beg)
4478 (>= (+ pos (js2-node-len node)) end)))
4479 (setq continue nil)
4480 (setq node (js2-node-parent node))))
4481 node))
4482
4483 (defun js2-node-parent-script-or-fn (node)
4484 "Find script or function immediately enclosing NODE.
4485 If NODE is the ast-root, returns nil."
4486 (if (js2-ast-root-p node)
4487 nil
4488 (setq node (js2-node-parent node))
4489 (while (and node (not (or (js2-function-node-p node)
4490 (js2-script-node-p node))))
4491 (setq node (js2-node-parent node)))
4492 node))
4493
4494 (defun js2-node-is-descendant (node ancestor)
4495 "Return t if NODE is a descendant of ANCESTOR."
4496 (while (and node
4497 (not (eq node ancestor)))
4498 (setq node (js2-node-parent node)))
4499 node)
4500
4501 ;;; visitor infrastructure
4502
4503 (defun js2-visit-none (_node _callback)
4504 "Visitor for AST node that have no node children."
4505 nil)
4506
4507 (defun js2-print-none (_node _indent)
4508 "Visitor for AST node with no printed representation.")
4509
4510 (defun js2-print-body (node indent)
4511 "Print a statement, or a block without braces."
4512 (if (js2-block-node-p node)
4513 (dolist (kid (js2-block-node-kids node))
4514 (js2-print-ast kid indent))
4515 (js2-print-ast node indent)))
4516
4517 (defun js2-print-list (args &optional delimiter)
4518 (loop with len = (length args)
4519 for arg in args
4520 for count from 1
4521 do
4522 (when arg (js2-print-ast arg 0))
4523 (if (< count len)
4524 (insert (or delimiter ", ")))))
4525
4526 (defun js2-print-tree (ast)
4527 "Prints an AST to the current buffer.
4528 Makes `js2-ast-parent-nodes' available to the printer functions."
4529 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4530 (js2-print-ast ast)))
4531
4532 (defun js2-print-ast (node &optional indent)
4533 "Helper function for printing AST nodes.
4534 Requires `js2-ast-parent-nodes' to be non-nil.
4535 You should use `js2-print-tree' instead of this function."
4536 (let ((printer (get (aref node 0) 'js2-printer))
4537 (i (or indent 0)))
4538 ;; TODO: wedge comments in here somewhere
4539 (if printer
4540 (funcall printer node i))))
4541
4542 (defconst js2-side-effecting-tokens
4543 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4544 (dolist (tt (list js2-ASSIGN
4545 js2-ASSIGN_ADD
4546 js2-ASSIGN_BITAND
4547 js2-ASSIGN_BITOR
4548 js2-ASSIGN_BITXOR
4549 js2-ASSIGN_DIV
4550 js2-ASSIGN_LSH
4551 js2-ASSIGN_MOD
4552 js2-ASSIGN_MUL
4553 js2-ASSIGN_RSH
4554 js2-ASSIGN_SUB
4555 js2-ASSIGN_URSH
4556 js2-BLOCK
4557 js2-BREAK
4558 js2-CALL
4559 js2-CATCH
4560 js2-CATCH_SCOPE
4561 js2-CONST
4562 js2-CONTINUE
4563 js2-DEBUGGER
4564 js2-DEC
4565 js2-DELPROP
4566 js2-DEL_REF
4567 js2-DO
4568 js2-ELSE
4569 js2-EMPTY
4570 js2-ENTERWITH
4571 js2-EXPORT
4572 js2-EXPR_RESULT
4573 js2-FINALLY
4574 js2-FOR
4575 js2-FUNCTION
4576 js2-GOTO
4577 js2-IF
4578 js2-IFEQ
4579 js2-IFNE
4580 js2-IMPORT
4581 js2-INC
4582 js2-JSR
4583 js2-LABEL
4584 js2-LEAVEWITH
4585 js2-LET
4586 js2-LETEXPR
4587 js2-LOCAL_BLOCK
4588 js2-LOOP
4589 js2-NEW
4590 js2-REF_CALL
4591 js2-RETHROW
4592 js2-RETURN
4593 js2-RETURN_RESULT
4594 js2-SEMI
4595 js2-SETELEM
4596 js2-SETELEM_OP
4597 js2-SETNAME
4598 js2-SETPROP
4599 js2-SETPROP_OP
4600 js2-SETVAR
4601 js2-SET_REF
4602 js2-SET_REF_OP
4603 js2-SWITCH
4604 js2-TARGET
4605 js2-THROW
4606 js2-TRY
4607 js2-VAR
4608 js2-WHILE
4609 js2-WITH
4610 js2-WITHEXPR
4611 js2-YIELD))
4612 (aset tokens tt t))
4613 (if js2-instanceof-has-side-effects
4614 (aset tokens js2-INSTANCEOF t))
4615 tokens))
4616
4617 (defun js2-node-has-side-effects (node)
4618 "Return t if NODE has side effects."
4619 (when node ; makes it easier to handle malformed expressions
4620 (let ((tt (js2-node-type node)))
4621 (cond
4622 ;; This doubtless needs some work, since EXPR_VOID is used
4623 ;; in several ways in Rhino and I may not have caught them all.
4624 ;; I'll wait for people to notice incorrect warnings.
4625 ((and (= tt js2-EXPR_VOID)
4626 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4627 (let ((expr (js2-expr-stmt-node-expr node)))
4628 (or (js2-node-has-side-effects expr)
4629 (when (js2-string-node-p expr)
4630 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4631 ((= tt js2-COMMA)
4632 (js2-node-has-side-effects (js2-infix-node-right node)))
4633 ((or (= tt js2-AND)
4634 (= tt js2-OR))
4635 (or (js2-node-has-side-effects (js2-infix-node-right node))
4636 (js2-node-has-side-effects (js2-infix-node-left node))))
4637 ((= tt js2-HOOK)
4638 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4639 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4640 ((js2-paren-node-p node)
4641 (js2-node-has-side-effects (js2-paren-node-expr node)))
4642 ((= tt js2-ERROR) ; avoid cascaded error messages
4643 nil)
4644 (t
4645 (aref js2-side-effecting-tokens tt))))))
4646
4647 (defconst js2-stmt-node-types
4648 (list js2-BLOCK
4649 js2-BREAK
4650 js2-CONTINUE
4651 js2-DEFAULT ; e4x "default xml namespace" statement
4652 js2-DO
4653 js2-EXPR_RESULT
4654 js2-EXPR_VOID
4655 js2-FOR
4656 js2-IF
4657 js2-RETURN
4658 js2-SWITCH
4659 js2-THROW
4660 js2-TRY
4661 js2-WHILE
4662 js2-WITH)
4663 "Node types that only appear in statement contexts.
4664 The list does not include nodes that always appear as the child
4665 of another specific statement type, such as switch-cases,
4666 catch and finally blocks, and else-clauses. The list also excludes
4667 nodes like yield, let and var, which may appear in either expression
4668 or statement context, and in the latter context always have a
4669 `js2-expr-stmt-node' parent. Finally, the list does not include
4670 functions or scripts, which are treated separately from statements
4671 by the JavaScript parser and runtime.")
4672
4673 (defun js2-stmt-node-p (node)
4674 "Heuristic for figuring out if NODE is a statement.
4675 Some node types can appear in either an expression context or a
4676 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4677 For these node types in a statement context, the parent will be a
4678 `js2-expr-stmt-node'.
4679 Functions aren't included in the check."
4680 (memq (js2-node-type node) js2-stmt-node-types))
4681
4682 (defun js2-mode-find-first-stmt (node)
4683 "Search upward starting from NODE looking for a statement.
4684 For purposes of this function, a `js2-function-node' counts."
4685 (while (not (or (js2-stmt-node-p node)
4686 (js2-function-node-p node)))
4687 (setq node (js2-node-parent node)))
4688 node)
4689
4690 (defun js2-node-parent-stmt (node)
4691 "Return the node's first ancestor that is a statement.
4692 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4693 appearing in a statement context will have a parent that is a
4694 `js2-expr-stmt-node' that will be returned by this function."
4695 (let ((parent (js2-node-parent node)))
4696 (if (or (null parent)
4697 (js2-stmt-node-p parent)
4698 (and (js2-function-node-p parent)
4699 (not (eq (js2-function-node-form parent)
4700 'FUNCTION_EXPRESSION))))
4701 parent
4702 (js2-node-parent-stmt parent))))
4703
4704 ;; In the Mozilla Rhino sources, Roshan James writes:
4705 ;; Does consistent-return analysis on the function body when strict mode is
4706 ;; enabled.
4707 ;;
4708 ;; function (x) { return (x+1) }
4709 ;;
4710 ;; is ok, but
4711 ;;
4712 ;; function (x) { if (x < 0) return (x+1); }
4713 ;;
4714 ;; is not because the function can potentially return a value when the
4715 ;; condition is satisfied and if not, the function does not explicitly
4716 ;; return a value.
4717 ;;
4718 ;; This extends to checking mismatches such as "return" and "return <value>"
4719 ;; used in the same function. Warnings are not emitted if inconsistent
4720 ;; returns exist in code that can be statically shown to be unreachable.
4721 ;; Ex.
4722 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4723 ;;
4724 ;; emits no warning. However if the loop had a break statement, then a
4725 ;; warning would be emitted.
4726 ;;
4727 ;; The consistency analysis looks at control structures such as loops, ifs,
4728 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4729 ;; warns the user about an inconsistent set of termination possibilities.
4730 ;;
4731 ;; These flags enumerate the possible ways a statement/function can
4732 ;; terminate. These flags are used by endCheck() and by the Parser to
4733 ;; detect inconsistent return usage.
4734 ;;
4735 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4736 ;; able to execute (example: throw, continue)
4737 ;;
4738 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4739 ;; next one. Statement such as return dont. A compound statement may have
4740 ;; some branch that drops off control to the next statement.
4741 ;;
4742 ;; END_RETURNS indicates that the statement can return with no value.
4743 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4744 ;;
4745 ;; A compound statement such as
4746 ;; if (condition) {
4747 ;; return value;
4748 ;; }
4749 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4750
4751 (defconst js2-END_UNREACHED 0)
4752 (defconst js2-END_DROPS_OFF 1)
4753 (defconst js2-END_RETURNS 2)
4754 (defconst js2-END_RETURNS_VALUE 4)
4755 (defconst js2-END_YIELDS 8)
4756
4757 (defun js2-has-consistent-return-usage (node)
4758 "Check that every return usage in a function body is consistent.
4759 Returns t if the function satisfies strict mode requirement."
4760 (let ((n (js2-end-check node)))
4761 ;; either it doesn't return a value in any branch...
4762 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4763 ;; or it returns a value (or is unreached) at every branch
4764 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4765 js2-END_RETURNS
4766 js2-END_YIELDS)))))
4767
4768 (defun js2-end-check-if (node)
4769 "Ensure that return usage in then/else blocks is consistent.
4770 If there is no else block, then the return statement can fall through.
4771 Returns logical OR of END_* flags"
4772 (let ((th (js2-if-node-then-part node))
4773 (el (js2-if-node-else-part node)))
4774 (if (null th)
4775 js2-END_UNREACHED
4776 (logior (js2-end-check th) (if el
4777 (js2-end-check el)
4778 js2-END_DROPS_OFF)))))
4779
4780 (defun js2-end-check-switch (node)
4781 "Consistency of return statements is checked between the case statements.
4782 If there is no default, then the switch can fall through. If there is a
4783 default, we check to see if all code paths in the default return or if
4784 there is a code path that can fall through.
4785 Returns logical OR of END_* flags."
4786 (let ((rv js2-END_UNREACHED)
4787 default-case)
4788 ;; examine the cases
4789 (catch 'break
4790 (dolist (c (js2-switch-node-cases node))
4791 (if (js2-case-node-expr c)
4792 (js2-set-flag rv (js2-end-check-block c))
4793 (setq default-case c)
4794 (throw 'break nil))))
4795 ;; we don't care how the cases drop into each other
4796 (js2-clear-flag rv js2-END_DROPS_OFF)
4797 ;; examine the default
4798 (js2-set-flag rv (if default-case
4799 (js2-end-check default-case)
4800 js2-END_DROPS_OFF))
4801 rv))
4802
4803 (defun js2-end-check-try (node)
4804 "If the block has a finally, return consistency is checked in the
4805 finally block. If all code paths in the finally return, then the
4806 returns in the try-catch blocks don't matter. If there is a code path
4807 that does not return or if there is no finally block, the returns
4808 of the try and catch blocks are checked for mismatch.
4809 Returns logical OR of END_* flags."
4810 (let ((finally (js2-try-node-finally-block node))
4811 rv)
4812 ;; check the finally if it exists
4813 (setq rv (if finally
4814 (js2-end-check (js2-finally-node-body finally))
4815 js2-END_DROPS_OFF))
4816 ;; If the finally block always returns, then none of the returns
4817 ;; in the try or catch blocks matter.
4818 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4819 (js2-clear-flag rv js2-END_DROPS_OFF)
4820 ;; examine the try block
4821 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4822 ;; check each catch block
4823 (dolist (cb (js2-try-node-catch-clauses node))
4824 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4825 rv))
4826
4827 (defun js2-end-check-loop (node)
4828 "Return statement in the loop body must be consistent.
4829 The default assumption for any kind of a loop is that it will eventually
4830 terminate. The only exception is a loop with a constant true condition.
4831 Code that follows such a loop is examined only if one can determine
4832 statically that there is a break out of the loop.
4833
4834 for(... ; ... ; ...) {}
4835 for(... in ... ) {}
4836 while(...) { }
4837 do { } while(...)
4838
4839 Returns logical OR of END_* flags."
4840 (let ((rv (js2-end-check (js2-loop-node-body node)))
4841 (condition (cond
4842 ((js2-while-node-p node)
4843 (js2-while-node-condition node))
4844 ((js2-do-node-p node)
4845 (js2-do-node-condition node))
4846 ((js2-for-node-p node)
4847 (js2-for-node-condition node)))))
4848
4849 ;; check to see if the loop condition is always true
4850 (if (and condition
4851 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4852 (js2-clear-flag rv js2-END_DROPS_OFF))
4853
4854 ;; look for effect of breaks
4855 (js2-set-flag rv (js2-node-get-prop node
4856 'CONTROL_BLOCK_PROP
4857 js2-END_UNREACHED))
4858 rv))
4859
4860 (defun js2-end-check-block (node)
4861 "A general block of code is examined statement by statement.
4862 If any statement (even a compound one) returns in all branches, then
4863 subsequent statements are not examined.
4864 Returns logical OR of END_* flags."
4865 (let* ((rv js2-END_DROPS_OFF)
4866 (kids (js2-block-node-kids node))
4867 (n (car kids)))
4868 ;; Check each statment. If the statement can continue onto the next
4869 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4870 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4871 (js2-clear-flag rv js2-END_DROPS_OFF)
4872 (js2-set-flag rv (js2-end-check n))
4873 (setq kids (cdr kids)
4874 n (car kids)))
4875 rv))
4876
4877 (defun js2-end-check-label (node)
4878 "A labeled statement implies that there may be a break to the label.
4879 The function processes the labeled statement and then checks the
4880 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4881 particular label.
4882 Returns logical OR of END_* flags."
4883 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4884 (logior rv (js2-node-get-prop node
4885 'CONTROL_BLOCK_PROP
4886 js2-END_UNREACHED))))
4887
4888 (defun js2-end-check-break (node)
4889 "When a break is encountered annotate the statement being broken
4890 out of by setting its CONTROL_BLOCK_PROP property.
4891 Returns logical OR of END_* flags."
4892 (and (js2-break-node-target node)
4893 (js2-node-set-prop (js2-break-node-target node)
4894 'CONTROL_BLOCK_PROP
4895 js2-END_DROPS_OFF))
4896 js2-END_UNREACHED)
4897
4898 (defun js2-end-check (node)
4899 "Examine the body of a function, doing a basic reachability analysis.
4900 Returns a combination of flags END_* flags that indicate
4901 how the function execution can terminate. These constitute only the
4902 pessimistic set of termination conditions. It is possible that at
4903 runtime certain code paths will never be actually taken. Hence this
4904 analysis will flag errors in cases where there may not be errors.
4905 Returns logical OR of END_* flags"
4906 (let (kid)
4907 (cond
4908 ((js2-break-node-p node)
4909 (js2-end-check-break node))
4910 ((js2-expr-stmt-node-p node)
4911 (if (setq kid (js2-expr-stmt-node-expr node))
4912 (js2-end-check kid)
4913 js2-END_DROPS_OFF))
4914 ((or (js2-continue-node-p node)
4915 (js2-throw-node-p node))
4916 js2-END_UNREACHED)
4917 ((js2-return-node-p node)
4918 (if (setq kid (js2-return-node-retval node))
4919 js2-END_RETURNS_VALUE
4920 js2-END_RETURNS))
4921 ((js2-loop-node-p node)
4922 (js2-end-check-loop node))
4923 ((js2-switch-node-p node)
4924 (js2-end-check-switch node))
4925 ((js2-labeled-stmt-node-p node)
4926 (js2-end-check-label node))
4927 ((js2-if-node-p node)
4928 (js2-end-check-if node))
4929 ((js2-try-node-p node)
4930 (js2-end-check-try node))
4931 ((js2-block-node-p node)
4932 (if (null (js2-block-node-kids node))
4933 js2-END_DROPS_OFF
4934 (js2-end-check-block node)))
4935 ((js2-yield-node-p node)
4936 js2-END_YIELDS)
4937 (t
4938 js2-END_DROPS_OFF))))
4939
4940 (defun js2-always-defined-boolean-p (node)
4941 "Check if NODE always evaluates to true or false in boolean context.
4942 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4943 nor always false."
4944 (let ((tt (js2-node-type node))
4945 num)
4946 (cond
4947 ((or (= tt js2-FALSE) (= tt js2-NULL))
4948 'ALWAYS_FALSE)
4949 ((= tt js2-TRUE)
4950 'ALWAYS_TRUE)
4951 ((= tt js2-NUMBER)
4952 (setq num (js2-number-node-num-value node))
4953 (if (and (not (eq num 0.0e+NaN))
4954 (not (zerop num)))
4955 'ALWAYS_TRUE
4956 'ALWAYS_FALSE))
4957 (t
4958 nil))))
4959
4960 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4961 ;; Corresponds to Rhino files Token.java and TokenStream.java.
4962
4963 (defvar js2-tokens nil
4964 "List of all defined token names.") ; initialized in `js2-token-names'
4965
4966 (defconst js2-token-names
4967 (let* ((names (make-vector js2-num-tokens -1))
4968 (case-fold-search nil) ; only match js2-UPPER_CASE
4969 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
4970 (loop for sym in syms
4971 for i from 0
4972 do
4973 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
4974 (not (boundp sym)))
4975 (aset names (symbol-value sym) ; code, e.g. 152
4976 (downcase
4977 (substring (symbol-name sym) 4))) ; name, e.g. "let"
4978 (push sym js2-tokens)))
4979 names)
4980 "Vector mapping int values to token string names, sans `js2-' prefix.")
4981
4982 (defun js2-token-name (tok)
4983 "Return a string name for TOK, a token symbol or code.
4984 Signals an error if it's not a recognized token."
4985 (let ((code tok))
4986 (if (symbolp tok)
4987 (setq code (symbol-value tok)))
4988 (if (eq code -1)
4989 "ERROR"
4990 (if (and (numberp code)
4991 (not (minusp code))
4992 (< code js2-num-tokens))
4993 (aref js2-token-names code)
4994 (error "Invalid token: %s" code)))))
4995
4996 (defsubst js2-token-sym (tok)
4997 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
4998 (intern (js2-token-name tok)))
4999
5000 (defconst js2-token-codes
5001 (let ((table (make-hash-table :test 'eq :size 256)))
5002 (loop for name across js2-token-names
5003 for sym = (intern (concat "js2-" (upcase name)))
5004 do
5005 (puthash sym (symbol-value sym) table))
5006 ;; clean up a few that are "wrong" in Rhino's token codes
5007 (puthash 'js2-DELETE js2-DELPROP table)
5008 table)
5009 "Hashtable mapping token symbols to their bytecodes.")
5010
5011 (defsubst js2-token-code (sym)
5012 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5013 (or (gethash sym js2-token-codes)
5014 (error "Invalid token symbol: %s " sym))) ; signal code bug
5015
5016 (defun js2-report-scan-error (msg &optional no-throw beg len)
5017 (setq js2-token-end js2-ts-cursor)
5018 (js2-report-error msg nil
5019 (or beg js2-token-beg)
5020 (or len (- js2-token-end js2-token-beg)))
5021 (unless no-throw
5022 (throw 'return js2-ERROR)))
5023
5024 (defun js2-get-string-from-buffer ()
5025 "Reverse the char accumulator and return it as a string."
5026 (setq js2-token-end js2-ts-cursor)
5027 (if js2-ts-string-buffer
5028 (apply #'string (nreverse js2-ts-string-buffer))
5029 ""))
5030
5031 ;; TODO: could potentially avoid a lot of consing by allocating a
5032 ;; char buffer the way Rhino does.
5033 (defsubst js2-add-to-string (c)
5034 (push c js2-ts-string-buffer))
5035
5036 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5037 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5038 ;; any other character: when it's not part of the current token, we
5039 ;; unget it, allowing it to be read again by the following call.
5040 (defsubst js2-unget-char ()
5041 (decf js2-ts-cursor))
5042
5043 ;; Rhino distinguishes \r and \n line endings. We don't need to
5044 ;; because we only scan from Emacs buffers, which always use \n.
5045 (defun js2-get-char ()
5046 "Read and return the next character from the input buffer.
5047 Increments `js2-ts-lineno' if the return value is a newline char.
5048 Updates `js2-ts-cursor' to the point after the returned char.
5049 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5050 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5051 (let (c)
5052 ;; check for end of buffer
5053 (if (>= js2-ts-cursor (point-max))
5054 (setq js2-ts-hit-eof t
5055 js2-ts-cursor (1+ js2-ts-cursor)
5056 c js2-EOF_CHAR) ; return value
5057 ;; otherwise read next char
5058 (setq c (char-before (incf js2-ts-cursor)))
5059 ;; if we read a newline, update counters
5060 (if (= c ?\n)
5061 (setq js2-ts-line-start js2-ts-cursor
5062 js2-ts-lineno (1+ js2-ts-lineno)))
5063 ;; TODO: skip over format characters
5064 c)))
5065
5066 (defun js2-read-unicode-escape ()
5067 "Read a \\uNNNN sequence from the input.
5068 Assumes the ?\ and ?u have already been read.
5069 Returns the unicode character, or nil if it wasn't a valid character.
5070 Doesn't change the values of any scanner variables."
5071 ;; I really wish I knew a better way to do this, but I can't
5072 ;; find the Emacs function that takes a 16-bit int and converts
5073 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5074 ;; Have to first check that it's 4 hex characters or it may stop
5075 ;; the read early.
5076 (ignore-errors
5077 (let ((s (buffer-substring-no-properties js2-ts-cursor
5078 (+ 4 js2-ts-cursor))))
5079 (if (string-match "[[:alnum:]]\\{4\\}" s)
5080 (read (concat "?\\u" s))))))
5081
5082 (defun js2-match-char (test)
5083 "Consume and return next character if it matches TEST, a character.
5084 Returns nil and consumes nothing if TEST is not the next character."
5085 (let ((c (js2-get-char)))
5086 (if (eq c test)
5087 t
5088 (js2-unget-char)
5089 nil)))
5090
5091 (defun js2-peek-char ()
5092 (prog1
5093 (js2-get-char)
5094 (js2-unget-char)))
5095
5096 (defun js2-java-identifier-start-p (c)
5097 (or
5098 (memq c '(?$ ?_))
5099 (js2-char-uppercase-p c)
5100 (js2-char-lowercase-p c)))
5101
5102 (defun js2-java-identifier-part-p (c)
5103 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5104 ;; TODO: make me Unicode-friendly. See comments above.
5105 (or
5106 (memq c '(?$ ?_))
5107 (js2-char-uppercase-p c)
5108 (js2-char-lowercase-p c)
5109 (and (>= c ?0) (<= c ?9))))
5110
5111 (defun js2-alpha-p (c)
5112 (cond ((and (<= ?A c) (<= c ?Z)) t)
5113 ((and (<= ?a c) (<= c ?z)) t)
5114 (t nil)))
5115
5116 (defsubst js2-digit-p (c)
5117 (and (<= ?0 c) (<= c ?9)))
5118
5119 (defun js2-js-space-p (c)
5120 (if (<= c 127)
5121 (memq c '(#x20 #x9 #xB #xC #xD))
5122 (or
5123 (eq c #xA0)
5124 ;; TODO: change this nil to check for Unicode space character
5125 nil)))
5126
5127 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5128
5129 (defun js2-skip-line ()
5130 "Skip to end of line."
5131 (while (not (memq (js2-get-char) js2-eol-chars)))
5132 (js2-unget-char)
5133 (setq js2-token-end js2-ts-cursor))
5134
5135 (defun js2-init-scanner (&optional buf line)
5136 "Create token stream for BUF starting on LINE.
5137 BUF defaults to `current-buffer' and LINE defaults to 1.
5138
5139 A buffer can only have one scanner active at a time, which yields
5140 dramatically simpler code than using a defstruct. If you need to
5141 have simultaneous scanners in a buffer, copy the regions to scan
5142 into temp buffers."
5143 (with-current-buffer (or buf (current-buffer))
5144 (setq js2-ts-dirty-line nil
5145 js2-ts-regexp-flags nil
5146 js2-ts-string ""
5147 js2-ts-number nil
5148 js2-ts-hit-eof nil
5149 js2-ts-line-start 0
5150 js2-ts-lineno (or line 1)
5151 js2-ts-line-end-char -1
5152 js2-ts-cursor (point-min)
5153 js2-ts-is-xml-attribute nil
5154 js2-ts-xml-is-tag-content nil
5155 js2-ts-xml-open-tags-count 0
5156 js2-ts-string-buffer nil)))
5157
5158 ;; This function uses the cached op, string and number fields in
5159 ;; TokenStream; if getToken has been called since the passed token
5160 ;; was scanned, the op or string printed may be incorrect.
5161 (defun js2-token-to-string (token)
5162 ;; Not sure where this function is used in Rhino. Not tested.
5163 (if (not js2-debug-print-trees)
5164 ""
5165 (let ((name (js2-token-name token)))
5166 (cond
5167 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5168 (concat name " `" js2-ts-string "'"))
5169 ((eq token js2-NUMBER)
5170 (format "NUMBER %g" js2-ts-number))
5171 (t
5172 name)))))
5173
5174 (defconst js2-keywords
5175 '(break
5176 case catch const continue
5177 debugger default delete do
5178 else enum
5179 false finally for function
5180 if in instanceof import
5181 let
5182 new null
5183 return
5184 switch
5185 this throw true try typeof
5186 var void
5187 while with
5188 yield))
5189
5190 ;; Token names aren't exactly the same as the keywords, unfortunately.
5191 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5192 (defconst js2-kwd-tokens
5193 (let ((table (make-vector js2-num-tokens nil))
5194 (tokens
5195 (list js2-BREAK
5196 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5197 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5198 js2-ELSE
5199 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5200 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5201 js2-LET
5202 js2-NEW js2-NULL
5203 js2-RETURN
5204 js2-SWITCH
5205 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5206 js2-VAR
5207 js2-WHILE js2-WITH
5208 js2-YIELD)))
5209 (dolist (i tokens)
5210 (aset table i 'font-lock-keyword-face))
5211 (aset table js2-STRING 'font-lock-string-face)
5212 (aset table js2-REGEXP 'font-lock-string-face)
5213 (aset table js2-COMMENT 'font-lock-comment-face)
5214 (aset table js2-THIS 'font-lock-builtin-face)
5215 (aset table js2-VOID 'font-lock-constant-face)
5216 (aset table js2-NULL 'font-lock-constant-face)
5217 (aset table js2-TRUE 'font-lock-constant-face)
5218 (aset table js2-FALSE 'font-lock-constant-face)
5219 table)
5220 "Vector whose values are non-nil for tokens that are keywords.
5221 The values are default faces to use for highlighting the keywords.")
5222
5223 (defconst js2-reserved-words
5224 '(abstract
5225 boolean byte
5226 char class
5227 double
5228 enum export extends
5229 final float
5230 goto
5231 implements import int interface
5232 long
5233 native
5234 package private protected public
5235 short static super synchronized
5236 throws transient
5237 volatile))
5238
5239 (defconst js2-keyword-names
5240 (let ((table (make-hash-table :test 'equal)))
5241 (loop for k in js2-keywords
5242 do (puthash
5243 (symbol-name k) ; instanceof
5244 (intern (concat "js2-"
5245 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5246 table))
5247 table)
5248 "JavaScript keywords by name, mapped to their symbols.")
5249
5250 (defconst js2-reserved-word-names
5251 (let ((table (make-hash-table :test 'equal)))
5252 (loop for k in js2-reserved-words
5253 do
5254 (puthash (symbol-name k) 'js2-RESERVED table))
5255 table)
5256 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5257
5258 (defun js2-collect-string (buf)
5259 "Convert BUF, a list of chars, to a string.
5260 Reverses BUF before converting."
5261 (cond
5262 ((stringp buf)
5263 buf)
5264 ((null buf) ; for emacs21 compat
5265 "")
5266 (t
5267 (if buf
5268 (apply #'string (nreverse buf))
5269 ""))))
5270
5271 (defun js2-string-to-keyword (s)
5272 "Return token for S, a string, if S is a keyword or reserved word.
5273 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5274 (or (gethash s js2-keyword-names)
5275 (gethash s js2-reserved-word-names)))
5276
5277 (defsubst js2-ts-set-char-token-bounds ()
5278 "Used when next token is one character."
5279 (setq js2-token-beg (1- js2-ts-cursor)
5280 js2-token-end js2-ts-cursor))
5281
5282 (defsubst js2-ts-return (token)
5283 "Return an N-character TOKEN from `js2-get-token'.
5284 Updates `js2-token-end' accordingly."
5285 (setq js2-token-end js2-ts-cursor)
5286 (throw 'return token))
5287
5288 (defun js2-x-digit-to-int (c accumulator)
5289 "Build up a hex number.
5290 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5291 corresponding number. Otherwise return -1."
5292 (catch 'return
5293 (catch 'check
5294 ;; Use 0..9 < A..Z < a..z
5295 (cond
5296 ((<= c ?9)
5297 (decf c ?0)
5298 (if (<= 0 c)
5299 (throw 'check nil)))
5300 ((<= c ?F)
5301 (when (<= ?A c)
5302 (decf c (- ?A 10))
5303 (throw 'check nil)))
5304 ((<= c ?f)
5305 (when (<= ?a c)
5306 (decf c (- ?a 10))
5307 (throw 'check nil))))
5308 (throw 'return -1))
5309 (logior c (lsh accumulator 4))))
5310
5311 (defun js2-get-token ()
5312 "Return next JavaScript token, an int such as js2-RETURN."
5313 (let (c c1 identifier-start is-unicode-escape-start
5314 contains-escape escape-val str result base
5315 is-integer quote-char val look-for-slash continue)
5316 (catch 'return
5317 (while t
5318 ;; Eat whitespace, possibly sensitive to newlines.
5319 (setq continue t)
5320 (while continue
5321 (setq c (js2-get-char))
5322 (cond
5323 ((eq c js2-EOF_CHAR)
5324 (js2-ts-set-char-token-bounds)
5325 (throw 'return js2-EOF))
5326 ((eq c ?\n)
5327 (js2-ts-set-char-token-bounds)
5328 (setq js2-ts-dirty-line nil)
5329 (throw 'return js2-EOL))
5330 ((not (js2-js-space-p c))
5331 (if (/= c ?-) ; in case end of HTML comment
5332 (setq js2-ts-dirty-line t))
5333 (setq continue nil))))
5334 ;; Assume the token will be 1 char - fixed up below.
5335 (js2-ts-set-char-token-bounds)
5336 (when (eq c ?@)
5337 (throw 'return js2-XMLATTR))
5338 ;; identifier/keyword/instanceof?
5339 ;; watch out for starting with a <backslash>
5340 (cond
5341 ((eq c ?\\)
5342 (setq c (js2-get-char))
5343 (if (eq c ?u)
5344 (setq identifier-start t
5345 is-unicode-escape-start t
5346 js2-ts-string-buffer nil)
5347 (setq identifier-start nil)
5348 (js2-unget-char)
5349 (setq c ?\\)))
5350 (t
5351 (when (setq identifier-start (js2-java-identifier-start-p c))
5352 (setq js2-ts-string-buffer nil)
5353 (js2-add-to-string c))))
5354 (when identifier-start
5355 (setq contains-escape is-unicode-escape-start)
5356 (catch 'break
5357 (while t
5358 (if is-unicode-escape-start
5359 ;; strictly speaking we should probably push-back
5360 ;; all the bad characters if the <backslash>uXXXX
5361 ;; sequence is malformed. But since there isn't a
5362 ;; correct context(is there?) for a bad Unicode
5363 ;; escape sequence in an identifier, we can report
5364 ;; an error here.
5365 (progn
5366 (setq escape-val 0)
5367 (dotimes (_ 4)
5368 (setq c (js2-get-char)
5369 escape-val (js2-x-digit-to-int c escape-val))
5370 ;; Next check takes care of c < 0 and bad escape
5371 (if (minusp escape-val)
5372 (throw 'break nil)))
5373 (if (minusp escape-val)
5374 (js2-report-scan-error "msg.invalid.escape" t))
5375 (js2-add-to-string escape-val)
5376 (setq is-unicode-escape-start nil))
5377 (setq c (js2-get-char))
5378 (cond
5379 ((eq c ?\\)
5380 (setq c (js2-get-char))
5381 (if (eq c ?u)
5382 (setq is-unicode-escape-start t
5383 contains-escape t)
5384 (js2-report-scan-error "msg.illegal.character" t)))
5385 (t
5386 (if (or (eq c js2-EOF_CHAR)
5387 (not (js2-java-identifier-part-p c)))
5388 (throw 'break nil))
5389 (js2-add-to-string c))))))
5390 (js2-unget-char)
5391 (setq str (js2-get-string-from-buffer))
5392 (unless contains-escape
5393 ;; OPT we shouldn't have to make a string (object!) to
5394 ;; check if it's a keyword.
5395 ;; Return the corresponding token if it's a keyword
5396 (when (setq result (js2-string-to-keyword str))
5397 (if (and (< js2-language-version 170)
5398 (memq result '(js2-LET js2-YIELD)))
5399 ;; LET and YIELD are tokens only in 1.7 and later
5400 (setq result 'js2-NAME))
5401 (if (not (eq result 'js2-RESERVED))
5402 (throw 'return (js2-token-code result)))
5403 (js2-report-warning "msg.reserved.keyword" str)))
5404 ;; If we want to intern these as Rhino does, just use (intern str)
5405 (setq js2-ts-string str)
5406 (throw 'return js2-NAME)) ; end identifier/kwd check
5407 ;; is it a number?
5408 (when (or (js2-digit-p c)
5409 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5410 (setq js2-ts-string-buffer nil
5411 base 10)
5412 (when (eq c ?0)
5413 (setq c (js2-get-char))
5414 (cond
5415 ((or (eq c ?x) (eq c ?X))
5416 (setq base 16)
5417 (setq c (js2-get-char)))
5418 ((js2-digit-p c)
5419 (setq base 8))
5420 (t
5421 (js2-add-to-string ?0))))
5422 (if (eq base 16)
5423 (while (<= 0 (js2-x-digit-to-int c 0))
5424 (js2-add-to-string c)
5425 (setq c (js2-get-char)))
5426 (while (and (<= ?0 c) (<= c ?9))
5427 ;; We permit 08 and 09 as decimal numbers, which
5428 ;; makes our behavior a superset of the ECMA
5429 ;; numeric grammar. We might not always be so
5430 ;; permissive, so we warn about it.
5431 (when (and (eq base 8) (>= c ?8))
5432 (js2-report-warning "msg.bad.octal.literal"
5433 (if (eq c ?8) "8" "9"))
5434 (setq base 10))
5435 (js2-add-to-string c)
5436 (setq c (js2-get-char))))
5437 (setq is-integer t)
5438 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5439 (setq is-integer nil)
5440 (when (eq c ?.)
5441 (loop do
5442 (js2-add-to-string c)
5443 (setq c (js2-get-char))
5444 while (js2-digit-p c)))
5445 (when (memq c '(?e ?E))
5446 (js2-add-to-string c)
5447 (setq c (js2-get-char))
5448 (when (memq c '(?+ ?-))
5449 (js2-add-to-string c)
5450 (setq c (js2-get-char)))
5451 (unless (js2-digit-p c)
5452 (js2-report-scan-error "msg.missing.exponent" t))
5453 (loop do
5454 (js2-add-to-string c)
5455 (setq c (js2-get-char))
5456 while (js2-digit-p c))))
5457 (js2-unget-char)
5458 (setq js2-ts-string (js2-get-string-from-buffer)
5459 js2-ts-number
5460 (if (and (eq base 10) (not is-integer))
5461 (string-to-number js2-ts-string)
5462 ;; TODO: call runtime number-parser. Some of it is in
5463 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5464 (string-to-number js2-ts-string)))
5465 (throw 'return js2-NUMBER))
5466 ;; is it a string?
5467 (when (memq c '(?\" ?\'))
5468 ;; We attempt to accumulate a string the fast way, by
5469 ;; building it directly out of the reader. But if there
5470 ;; are any escaped characters in the string, we revert to
5471 ;; building it out of a string buffer.
5472 (setq quote-char c
5473 js2-ts-string-buffer nil
5474 c (js2-get-char))
5475 (catch 'break
5476 (while (/= c quote-char)
5477 (catch 'continue
5478 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5479 (js2-unget-char)
5480 (setq js2-token-end js2-ts-cursor)
5481 (js2-report-error "msg.unterminated.string.lit")
5482 (throw 'return js2-STRING))
5483 (when (eq c ?\\)
5484 ;; We've hit an escaped character
5485 (setq c (js2-get-char))
5486 (case c
5487 (?b (setq c ?\b))
5488 (?f (setq c ?\f))
5489 (?n (setq c ?\n))
5490 (?r (setq c ?\r))
5491 (?t (setq c ?\t))
5492 (?v (setq c ?\v))
5493 (?u
5494 (setq c1 (js2-read-unicode-escape))
5495 (if js2-parse-ide-mode
5496 (if c1
5497 (progn
5498 ;; just copy the string in IDE-mode
5499 (js2-add-to-string ?\\)
5500 (js2-add-to-string ?u)
5501 (dotimes (_ 3)
5502 (js2-add-to-string (js2-get-char)))
5503 (setq c (js2-get-char))) ; added at end of loop
5504 ;; flag it as an invalid escape
5505 (js2-report-warning "msg.invalid.escape"
5506 nil (- js2-ts-cursor 2) 6))
5507 ;; Get 4 hex digits; if the u escape is not
5508 ;; followed by 4 hex digits, use 'u' + the
5509 ;; literal character sequence that follows.
5510 (js2-add-to-string ?u)
5511 (setq escape-val 0)
5512 (dotimes (_ 4)
5513 (setq c (js2-get-char)
5514 escape-val (js2-x-digit-to-int c escape-val))
5515 (if (minusp escape-val)
5516 (throw 'continue nil))
5517 (js2-add-to-string c))
5518 ;; prepare for replace of stored 'u' sequence by escape value
5519 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5520 c escape-val)))
5521 (?x
5522 ;; Get 2 hex digits, defaulting to 'x'+literal
5523 ;; sequence, as above.
5524 (setq c (js2-get-char)
5525 escape-val (js2-x-digit-to-int c 0))
5526 (if (minusp escape-val)
5527 (progn
5528 (js2-add-to-string ?x)
5529 (throw 'continue nil))
5530 (setq c1 c
5531 c (js2-get-char)
5532 escape-val (js2-x-digit-to-int c escape-val))
5533 (if (minusp escape-val)
5534 (progn
5535 (js2-add-to-string ?x)
5536 (js2-add-to-string c1)
5537 (throw 'continue nil))
5538 ;; got 2 hex digits
5539 (setq c escape-val))))
5540 (?\n
5541 ;; Remove line terminator after escape to follow
5542 ;; SpiderMonkey and C/C++
5543 (setq c (js2-get-char))
5544 (throw 'continue nil))
5545 (t
5546 (when (and (<= ?0 c) (< c ?8))
5547 (setq val (- c ?0)
5548 c (js2-get-char))
5549 (when (and (<= ?0 c) (< c ?8))
5550 (setq val (- (+ (* 8 val) c) ?0)
5551 c (js2-get-char))
5552 (when (and (<= ?0 c)
5553 (< c ?8)
5554 (< val #o37))
5555 ;; c is 3rd char of octal sequence only
5556 ;; if the resulting val <= 0377
5557 (setq val (- (+ (* 8 val) c) ?0)
5558 c (js2-get-char))))
5559 (js2-unget-char)
5560 (setq c val)))))
5561 (js2-add-to-string c)
5562 (setq c (js2-get-char)))))
5563 (setq js2-ts-string (js2-get-string-from-buffer))
5564 (throw 'return js2-STRING))
5565 (js2-ts-return
5566 (case c
5567 (?\;
5568 (throw 'return js2-SEMI))
5569 (?\[
5570 (throw 'return js2-LB))
5571 (?\]
5572 (throw 'return js2-RB))
5573 (?{
5574 (throw 'return js2-LC))
5575 (?}
5576 (throw 'return js2-RC))
5577 (?\(
5578 (throw 'return js2-LP))
5579 (?\)
5580 (throw 'return js2-RP))
5581 (?,
5582 (throw 'return js2-COMMA))
5583 (??
5584 (throw 'return js2-HOOK))
5585 (?:
5586 (if (js2-match-char ?:)
5587 js2-COLONCOLON
5588 (throw 'return js2-COLON)))
5589 (?.
5590 (if (js2-match-char ?.)
5591 (if (js2-match-char ?.)
5592 js2-TRIPLEDOT js2-DOTDOT)
5593 (if (js2-match-char ?\()
5594 js2-DOTQUERY
5595 (throw 'return js2-DOT))))
5596 (?|
5597 (if (js2-match-char ?|)
5598 (throw 'return js2-OR)
5599 (if (js2-match-char ?=)
5600 js2-ASSIGN_BITOR
5601 (throw 'return js2-BITOR))))
5602 (?^
5603 (if (js2-match-char ?=)
5604 js2-ASSIGN_BITOR
5605 (throw 'return js2-BITXOR)))
5606 (?&
5607 (if (js2-match-char ?&)
5608 (throw 'return js2-AND)
5609 (if (js2-match-char ?=)
5610 js2-ASSIGN_BITAND
5611 (throw 'return js2-BITAND))))
5612 (?=
5613 (if (js2-match-char ?=)
5614 (if (js2-match-char ?=)
5615 js2-SHEQ
5616 (throw 'return js2-EQ))
5617 (throw 'return js2-ASSIGN)))
5618 (?!
5619 (if (js2-match-char ?=)
5620 (if (js2-match-char ?=)
5621 js2-SHNE
5622 js2-NE)
5623 (throw 'return js2-NOT)))
5624 (?<
5625 ;; NB:treat HTML begin-comment as comment-till-eol
5626 (when (js2-match-char ?!)
5627 (when (js2-match-char ?-)
5628 (when (js2-match-char ?-)
5629 (js2-skip-line)
5630 (setq js2-ts-comment-type 'html)
5631 (throw 'return js2-COMMENT)))
5632 (js2-unget-char))
5633 (if (js2-match-char ?<)
5634 (if (js2-match-char ?=)
5635 js2-ASSIGN_LSH
5636 js2-LSH)
5637 (if (js2-match-char ?=)
5638 js2-LE
5639 (throw 'return js2-LT))))
5640 (?>
5641 (if (js2-match-char ?>)
5642 (if (js2-match-char ?>)
5643 (if (js2-match-char ?=)
5644 js2-ASSIGN_URSH
5645 js2-URSH)
5646 (if (js2-match-char ?=)
5647 js2-ASSIGN_RSH
5648 js2-RSH))
5649 (if (js2-match-char ?=)
5650 js2-GE
5651 (throw 'return js2-GT))))
5652 (?*
5653 (if (js2-match-char ?=)
5654 js2-ASSIGN_MUL
5655 (throw 'return js2-MUL)))
5656 (?/
5657 ;; is it a // comment?
5658 (when (js2-match-char ?/)
5659 (setq js2-token-beg (- js2-ts-cursor 2))
5660 (js2-skip-line)
5661 (setq js2-ts-comment-type 'line)
5662 ;; include newline so highlighting goes to end of window
5663 (incf js2-token-end)
5664 (throw 'return js2-COMMENT))
5665 ;; is it a /* comment?
5666 (when (js2-match-char ?*)
5667 (setq look-for-slash nil
5668 js2-token-beg (- js2-ts-cursor 2)
5669 js2-ts-comment-type
5670 (if (js2-match-char ?*)
5671 (progn
5672 (setq look-for-slash t)
5673 'jsdoc)
5674 'block))
5675 (while t
5676 (setq c (js2-get-char))
5677 (cond
5678 ((eq c js2-EOF_CHAR)
5679 (setq js2-token-end (1- js2-ts-cursor))
5680 (js2-report-error "msg.unterminated.comment")
5681 (throw 'return js2-COMMENT))
5682 ((eq c ?*)
5683 (setq look-for-slash t))
5684 ((eq c ?/)
5685 (if look-for-slash
5686 (js2-ts-return js2-COMMENT)))
5687 (t
5688 (setq look-for-slash nil
5689 js2-token-end js2-ts-cursor)))))
5690 (if (js2-match-char ?=)
5691 js2-ASSIGN_DIV
5692 (throw 'return js2-DIV)))
5693 (?#
5694 (when js2-skip-preprocessor-directives
5695 (js2-skip-line)
5696 (setq js2-ts-comment-type 'preprocessor
5697 js2-token-end js2-ts-cursor)
5698 (throw 'return js2-COMMENT))
5699 (throw 'return js2-ERROR))
5700 (?%
5701 (if (js2-match-char ?=)
5702 js2-ASSIGN_MOD
5703 (throw 'return js2-MOD)))
5704 (?~
5705 (throw 'return js2-BITNOT))
5706 (?+
5707 (if (js2-match-char ?=)
5708 js2-ASSIGN_ADD
5709 (if (js2-match-char ?+)
5710 js2-INC
5711 (throw 'return js2-ADD))))
5712 (?-
5713 (cond
5714 ((js2-match-char ?=)
5715 (setq c js2-ASSIGN_SUB))
5716 ((js2-match-char ?-)
5717 (unless js2-ts-dirty-line
5718 ;; treat HTML end-comment after possible whitespace
5719 ;; after line start as comment-until-eol
5720 (when (js2-match-char ?>)
5721 (js2-skip-line)
5722 (setq js2-ts-comment-type 'html)
5723 (throw 'return js2-COMMENT)))
5724 (setq c js2-DEC))
5725 (t
5726 (setq c js2-SUB)))
5727 (setq js2-ts-dirty-line t)
5728 c)
5729 (otherwise
5730 (js2-report-scan-error "msg.illegal.character"))))))))
5731
5732 (defun js2-read-regexp (start-token)
5733 "Called by parser when it gets / or /= in literal context."
5734 (let (c err
5735 in-class ; inside a '[' .. ']' character-class
5736 flags
5737 (continue t))
5738 (setq js2-token-beg js2-ts-cursor
5739 js2-ts-string-buffer nil
5740 js2-ts-regexp-flags nil)
5741 (if (eq start-token js2-ASSIGN_DIV)
5742 ;; mis-scanned /=
5743 (js2-add-to-string ?=)
5744 (if (not (eq start-token js2-DIV))
5745 (error "failed assertion")))
5746 (while (and (not err)
5747 (or (/= (setq c (js2-get-char)) ?/)
5748 in-class))
5749 (cond
5750 ((or (= c ?\n)
5751 (= c js2-EOF_CHAR))
5752 (setq js2-token-end (1- js2-ts-cursor)
5753 err t
5754 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5755 (js2-report-error "msg.unterminated.re.lit"))
5756 (t (cond
5757 ((= c ?\\)
5758 (js2-add-to-string c)
5759 (setq c (js2-get-char)))
5760 ((= c ?\[)
5761 (setq in-class t))
5762 ((= c ?\])
5763 (setq in-class nil)))
5764 (js2-add-to-string c))))
5765 (unless err
5766 (while continue
5767 (cond
5768 ((js2-match-char ?g)
5769 (push ?g flags))
5770 ((js2-match-char ?i)
5771 (push ?i flags))
5772 ((js2-match-char ?m)
5773 (push ?m flags))
5774 (t
5775 (setq continue nil))))
5776 (if (js2-alpha-p (js2-peek-char))
5777 (js2-report-scan-error "msg.invalid.re.flag" t
5778 js2-ts-cursor 1))
5779 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5780 js2-ts-regexp-flags (js2-collect-string flags)
5781 js2-token-end js2-ts-cursor)
5782 ;; tell `parse-partial-sexp' to ignore this range of chars
5783 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5784
5785 (defun js2-get-first-xml-token ()
5786 (setq js2-ts-xml-open-tags-count 0
5787 js2-ts-is-xml-attribute nil
5788 js2-ts-xml-is-tag-content nil)
5789 (js2-unget-char)
5790 (js2-get-next-xml-token))
5791
5792 (defun js2-xml-discard-string ()
5793 "Throw away the string in progress and flag an XML parse error."
5794 (setq js2-ts-string-buffer nil
5795 js2-ts-string nil)
5796 (js2-report-scan-error "msg.XML.bad.form" t))
5797
5798 (defun js2-get-next-xml-token ()
5799 (setq js2-ts-string-buffer nil ; for recording the XML
5800 js2-token-beg js2-ts-cursor)
5801 (let (c result)
5802 (setq result
5803 (catch 'return
5804 (while t
5805 (setq c (js2-get-char))
5806 (cond
5807 ((= c js2-EOF_CHAR)
5808 (throw 'return js2-ERROR))
5809 (js2-ts-xml-is-tag-content
5810 (case c
5811 (?>
5812 (js2-add-to-string c)
5813 (setq js2-ts-xml-is-tag-content nil
5814 js2-ts-is-xml-attribute nil))
5815 (?/
5816 (js2-add-to-string c)
5817 (when (eq ?> (js2-peek-char))
5818 (setq c (js2-get-char))
5819 (js2-add-to-string c)
5820 (setq js2-ts-xml-is-tag-content nil)
5821 (decf js2-ts-xml-open-tags-count)))
5822 (?{
5823 (js2-unget-char)
5824 (setq js2-ts-string (js2-get-string-from-buffer))
5825 (throw 'return js2-XML))
5826 ((?\' ?\")
5827 (js2-add-to-string c)
5828 (unless (js2-read-quoted-string c)
5829 (throw 'return js2-ERROR)))
5830 (?=
5831 (js2-add-to-string c)
5832 (setq js2-ts-is-xml-attribute t))
5833 ((? ?\t ?\r ?\n)
5834 (js2-add-to-string c))
5835 (t
5836 (js2-add-to-string c)
5837 (setq js2-ts-is-xml-attribute nil)))
5838 (when (and (not js2-ts-xml-is-tag-content)
5839 (zerop js2-ts-xml-open-tags-count))
5840 (setq js2-ts-string (js2-get-string-from-buffer))
5841 (throw 'return js2-XMLEND)))
5842 (t
5843 ;; else not tag content
5844 (case c
5845 (?<
5846 (js2-add-to-string c)
5847 (setq c (js2-peek-char))
5848 (case c
5849 (?!
5850 (setq c (js2-get-char)) ;; skip !
5851 (js2-add-to-string c)
5852 (setq c (js2-peek-char))
5853 (case c
5854 (?-
5855 (setq c (js2-get-char)) ;; skip -
5856 (js2-add-to-string c)
5857 (if (eq c ?-)
5858 (progn
5859 (js2-add-to-string c)
5860 (unless (js2-read-xml-comment)
5861 (throw 'return js2-ERROR)))
5862 (js2-xml-discard-string)
5863 (throw 'return js2-ERROR)))
5864 (?\[
5865 (setq c (js2-get-char)) ;; skip [
5866 (js2-add-to-string c)
5867 (if (and (= (js2-get-char) ?C)
5868 (= (js2-get-char) ?D)
5869 (= (js2-get-char) ?A)
5870 (= (js2-get-char) ?T)
5871 (= (js2-get-char) ?A)
5872 (= (js2-get-char) ?\[))
5873 (progn
5874 (js2-add-to-string ?C)
5875 (js2-add-to-string ?D)
5876 (js2-add-to-string ?A)
5877 (js2-add-to-string ?T)
5878 (js2-add-to-string ?A)
5879 (js2-add-to-string ?\[)
5880 (unless (js2-read-cdata)
5881 (throw 'return js2-ERROR)))
5882 (js2-xml-discard-string)
5883 (throw 'return js2-ERROR)))
5884 (t
5885 (unless (js2-read-entity)
5886 (throw 'return js2-ERROR))))
5887 ;; Allow bare CDATA section, e.g.:
5888 ;; let xml = <![CDATA[ foo bar baz ]]>;
5889 (when (zerop js2-ts-xml-open-tags-count)
5890 (throw 'return js2-XMLEND)))
5891 (??
5892 (setq c (js2-get-char)) ;; skip ?
5893 (js2-add-to-string c)
5894 (unless (js2-read-PI)
5895 (throw 'return js2-ERROR)))
5896 (?/
5897 ;; end tag
5898 (setq c (js2-get-char)) ;; skip /
5899 (js2-add-to-string c)
5900 (when (zerop js2-ts-xml-open-tags-count)
5901 (js2-xml-discard-string)
5902 (throw 'return js2-ERROR))
5903 (setq js2-ts-xml-is-tag-content t)
5904 (decf js2-ts-xml-open-tags-count))
5905 (t
5906 ;; start tag
5907 (setq js2-ts-xml-is-tag-content t)
5908 (incf js2-ts-xml-open-tags-count))))
5909 (?{
5910 (js2-unget-char)
5911 (setq js2-ts-string (js2-get-string-from-buffer))
5912 (throw 'return js2-XML))
5913 (t
5914 (js2-add-to-string c))))))))
5915 (setq js2-token-end js2-ts-cursor)
5916 result))
5917
5918 (defun js2-read-quoted-string (quote)
5919 (let (c)
5920 (catch 'return
5921 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5922 (js2-add-to-string c)
5923 (if (eq c quote)
5924 (throw 'return t)))
5925 (js2-xml-discard-string) ;; throw away string in progress
5926 nil)))
5927
5928 (defun js2-read-xml-comment ()
5929 (let ((c (js2-get-char)))
5930 (catch 'return
5931 (while (/= c js2-EOF_CHAR)
5932 (catch 'continue
5933 (js2-add-to-string c)
5934 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5935 (setq c (js2-get-char))
5936 (js2-add-to-string c)
5937 (if (eq (js2-peek-char) ?>)
5938 (progn
5939 (setq c (js2-get-char)) ;; skip >
5940 (js2-add-to-string c)
5941 (throw 'return t))
5942 (throw 'continue nil)))
5943 (setq c (js2-get-char))))
5944 (js2-xml-discard-string)
5945 nil)))
5946
5947 (defun js2-read-cdata ()
5948 (let ((c (js2-get-char)))
5949 (catch 'return
5950 (while (/= c js2-EOF_CHAR)
5951 (catch 'continue
5952 (js2-add-to-string c)
5953 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5954 (setq c (js2-get-char))
5955 (js2-add-to-string c)
5956 (if (eq (js2-peek-char) ?>)
5957 (progn
5958 (setq c (js2-get-char)) ;; Skip >
5959 (js2-add-to-string c)
5960 (throw 'return t))
5961 (throw 'continue nil)))
5962 (setq c (js2-get-char))))
5963 (js2-xml-discard-string)
5964 nil)))
5965
5966 (defun js2-read-entity ()
5967 (let ((decl-tags 1)
5968 c)
5969 (catch 'return
5970 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5971 (js2-add-to-string c)
5972 (case c
5973 (?<
5974 (incf decl-tags))
5975 (?>
5976 (decf decl-tags)
5977 (if (zerop decl-tags)
5978 (throw 'return t)))))
5979 (js2-xml-discard-string)
5980 nil)))
5981
5982 (defun js2-read-PI ()
5983 "Scan an XML processing instruction."
5984 (let (c)
5985 (catch 'return
5986 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5987 (js2-add-to-string c)
5988 (when (and (eq c ??) (eq (js2-peek-char) ?>))
5989 (setq c (js2-get-char)) ;; Skip >
5990 (js2-add-to-string c)
5991 (throw 'return t)))
5992 (js2-xml-discard-string)
5993 nil)))
5994
5995 ;;; Highlighting
5996
5997 (defun js2-set-face (beg end face &optional record)
5998 "Fontify a region. If RECORD is non-nil, record for later."
5999 (when (plusp js2-highlight-level)
6000 (setq beg (min (point-max) beg)
6001 beg (max (point-min) beg)
6002 end (min (point-max) end)
6003 end (max (point-min) end))
6004 (if record
6005 (push (list beg end face) js2-mode-fontifications)
6006 (put-text-property beg end 'font-lock-face face))))
6007
6008 (defsubst js2-clear-face (beg end)
6009 (remove-text-properties beg end '(font-lock-face nil
6010 help-echo nil
6011 point-entered nil
6012 c-in-sws nil)))
6013
6014 (defconst js2-ecma-global-props
6015 (concat "^"
6016 (regexp-opt
6017 '("Infinity" "NaN" "undefined" "arguments") t)
6018 "$")
6019 "Value properties of the Ecma-262 Global Object.
6020 Shown at or above `js2-highlight-level' 2.")
6021
6022 ;; might want to add the name "arguments" to this list?
6023 (defconst js2-ecma-object-props
6024 (concat "^"
6025 (regexp-opt
6026 '("prototype" "__proto__" "__parent__") t)
6027 "$")
6028 "Value properties of the Ecma-262 Object constructor.
6029 Shown at or above `js2-highlight-level' 2.")
6030
6031 (defconst js2-ecma-global-funcs
6032 (concat
6033 "^"
6034 (regexp-opt
6035 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6036 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6037 "$")
6038 "Function properties of the Ecma-262 Global object.
6039 Shown at or above `js2-highlight-level' 2.")
6040
6041 (defconst js2-ecma-number-props
6042 (concat "^"
6043 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6044 "NEGATIVE_INFINITY"
6045 "POSITIVE_INFINITY") t)
6046 "$")
6047 "Properties of the Ecma-262 Number constructor.
6048 Shown at or above `js2-highlight-level' 2.")
6049
6050 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6051 "Properties of the Ecma-262 Date constructor.
6052 Shown at or above `js2-highlight-level' 2.")
6053
6054 (defconst js2-ecma-math-props
6055 (concat "^"
6056 (regexp-opt
6057 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6058 t)
6059 "$")
6060 "Properties of the Ecma-262 Math object.
6061 Shown at or above `js2-highlight-level' 2.")
6062
6063 (defconst js2-ecma-math-funcs
6064 (concat "^"
6065 (regexp-opt
6066 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6067 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6068 "$")
6069 "Function properties of the Ecma-262 Math object.
6070 Shown at or above `js2-highlight-level' 2.")
6071
6072 (defconst js2-ecma-function-props
6073 (concat
6074 "^"
6075 (regexp-opt
6076 '(;; properties of the Object prototype object
6077 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6078 "toLocaleString" "toString" "valueOf"
6079 ;; properties of the Function prototype object
6080 "apply" "call"
6081 ;; properties of the Array prototype object
6082 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6083 "splice" "unshift"
6084 ;; properties of the String prototype object
6085 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6086 "localeCompare" "match" "replace" "search" "split" "substring"
6087 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6088 "toUpperCase"
6089 ;; properties of the Number prototype object
6090 "toExponential" "toFixed" "toPrecision"
6091 ;; properties of the Date prototype object
6092 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6093 "getMinutes" "getMonth" "getSeconds" "getTime"
6094 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6095 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6096 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6097 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6098 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6099 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6100 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6101 "toTimeString" "toUTCString"
6102 ;; properties of the RegExp prototype object
6103 "exec" "test"
6104 ;; properties of the JSON prototype object
6105 "parse" "stringify"
6106 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6107 "toSource" "__defineGetter__" "__defineSetter__"
6108 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6109 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6110 t)
6111 "$")
6112 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6113 Shown at or above `js2-highlight-level' 3.")
6114
6115 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6116 (let ((target-name (and target
6117 (js2-name-node-p target)
6118 (js2-name-node-name target)))
6119 (prop-name (if prop (js2-name-node-name prop)))
6120 (level2 (>= js2-highlight-level 2))
6121 (level3 (>= js2-highlight-level 3)))
6122 (when level2
6123 (let ((face
6124 (if call-p
6125 (cond
6126 ((and target prop)
6127 (cond
6128 ((and level3 (string-match js2-ecma-function-props prop-name))
6129 'font-lock-builtin-face)
6130 ((and target-name prop)
6131 (cond
6132 ((string= target-name "Date")
6133 (if (string-match js2-ecma-date-props prop-name)
6134 'font-lock-builtin-face))
6135 ((string= target-name "Math")
6136 (if (string-match js2-ecma-math-funcs prop-name)
6137 'font-lock-builtin-face))))))
6138 (prop
6139 (if (string-match js2-ecma-global-funcs prop-name)
6140 'font-lock-builtin-face)))
6141 (cond
6142 ((and target prop)
6143 (cond
6144 ((string= target-name "Number")
6145 (if (string-match js2-ecma-number-props prop-name)
6146 'font-lock-constant-face))
6147 ((string= target-name "Math")
6148 (if (string-match js2-ecma-math-props prop-name)
6149 'font-lock-constant-face))))
6150 (prop
6151 (if (string-match js2-ecma-object-props prop-name)
6152 'font-lock-constant-face))))))
6153 (when face
6154 (let ((pos (+ (js2-node-pos parent) ; absolute
6155 (js2-node-pos prop)))) ; relative
6156 (js2-set-face pos
6157 (+ pos (js2-node-len prop))
6158 face 'record)))))))
6159
6160 (defun js2-parse-highlight-member-expr-node (node)
6161 "Perform syntax highlighting of EcmaScript built-in properties.
6162 The variable `js2-highlight-level' governs this highighting."
6163 (let (face target prop name pos end parent call-p callee)
6164 (cond
6165 ;; case 1: simple name, e.g. foo
6166 ((js2-name-node-p node)
6167 (setq name (js2-name-node-name node))
6168 ;; possible for name to be nil in rare cases - saw it when
6169 ;; running js2-mode on an elisp buffer. Might as well try to
6170 ;; make it so js2-mode never barfs.
6171 (when name
6172 (setq face (if (string-match js2-ecma-global-props name)
6173 'font-lock-constant-face))
6174 (when face
6175 (setq pos (js2-node-pos node)
6176 end (+ pos (js2-node-len node)))
6177 (js2-set-face pos end face 'record))))
6178 ;; case 2: property access or function call
6179 ((or (js2-prop-get-node-p node)
6180 ;; highlight function call if expr is a prop-get node
6181 ;; or a plain name (i.e. unqualified function call)
6182 (and (setq call-p (js2-call-node-p node))
6183 (setq callee (js2-call-node-target node)) ; separate setq!
6184 (or (js2-prop-get-node-p callee)
6185 (js2-name-node-p callee))))
6186 (setq parent node
6187 node (if call-p callee node))
6188 (if (and call-p (js2-name-node-p callee))
6189 (setq prop callee)
6190 (setq target (js2-prop-get-node-left node)
6191 prop (js2-prop-get-node-right node)))
6192 (cond
6193 ((js2-name-node-p prop)
6194 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6195 (js2-parse-highlight-prop-get parent target prop call-p))
6196 ((js2-name-node-p target)
6197 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6198 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6199
6200 (defun js2-parse-highlight-member-expr-fn-name (expr)
6201 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6202 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6203 We currently only handle the case where the last component is a prop-get
6204 of a simple name. Called before EXPR has a parent node."
6205 (let (pos
6206 (name (and (js2-prop-get-node-p expr)
6207 (js2-prop-get-node-right expr))))
6208 (when (js2-name-node-p name)
6209 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6210 (js2-node-pos name)))
6211 (+ pos (js2-node-len name))
6212 'font-lock-function-name-face
6213 'record))))
6214
6215 ;; source: http://jsdoc.sourceforge.net/
6216 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6217 ;; allows type specifications, and needs work before entering the wild.
6218
6219 (defconst js2-jsdoc-param-tag-regexp
6220 (concat "^\\s-*\\*+\\s-*\\(@"
6221 "\\(?:param\\|argument\\)"
6222 "\\)"
6223 "\\s-*\\({[^}]+}\\)?" ; optional type
6224 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6225 "\\>")
6226 "Matches jsdoc tags with optional type and optional param name.")
6227
6228 (defconst js2-jsdoc-typed-tag-regexp
6229 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6230 (regexp-opt
6231 '("enum"
6232 "extends"
6233 "field"
6234 "id"
6235 "implements"
6236 "lends"
6237 "mods"
6238 "requires"
6239 "return"
6240 "returns"
6241 "throw"
6242 "throws"))
6243 "\\)\\)\\s-*\\({[^}]+}\\)?")
6244 "Matches jsdoc tags with optional type.")
6245
6246 (defconst js2-jsdoc-arg-tag-regexp
6247 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6248 (regexp-opt
6249 '("alias"
6250 "augments"
6251 "borrows"
6252 "bug"
6253 "base"
6254 "config"
6255 "default"
6256 "define"
6257 "exception"
6258 "function"
6259 "member"
6260 "memberOf"
6261 "name"
6262 "namespace"
6263 "property"
6264 "since"
6265 "suppress"
6266 "this"
6267 "throws"
6268 "type"
6269 "version"))
6270 "\\)\\)\\s-+\\([^ \t]+\\)")
6271 "Matches jsdoc tags with a single argument.")
6272
6273 (defconst js2-jsdoc-empty-tag-regexp
6274 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6275 (regexp-opt
6276 '("addon"
6277 "author"
6278 "class"
6279 "const"
6280 "constant"
6281 "constructor"
6282 "constructs"
6283 "deprecated"
6284 "desc"
6285 "description"
6286 "event"
6287 "example"
6288 "exec"
6289 "export"
6290 "fileoverview"
6291 "final"
6292 "function"
6293 "hidden"
6294 "ignore"
6295 "implicitCast"
6296 "inheritDoc"
6297 "inner"
6298 "interface"
6299 "license"
6300 "noalias"
6301 "noshadow"
6302 "notypecheck"
6303 "override"
6304 "owner"
6305 "preserve"
6306 "preserveTry"
6307 "private"
6308 "protected"
6309 "public"
6310 "static"
6311 "supported"
6312 ))
6313 "\\)\\)\\s-*")
6314 "Matches empty jsdoc tags.")
6315
6316 (defconst js2-jsdoc-link-tag-regexp
6317 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6318 "Matches a jsdoc link or code tag.")
6319
6320 (defconst js2-jsdoc-see-tag-regexp
6321 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6322 "Matches a jsdoc @see tag.")
6323
6324 (defconst js2-jsdoc-html-tag-regexp
6325 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6326 "Matches a simple (no attributes) html start- or end-tag.")
6327
6328 (defun js2-jsdoc-highlight-helper ()
6329 (js2-set-face (match-beginning 1)
6330 (match-end 1)
6331 'js2-jsdoc-tag)
6332 (if (match-beginning 2)
6333 (if (save-excursion
6334 (goto-char (match-beginning 2))
6335 (= (char-after) ?{))
6336 (js2-set-face (1+ (match-beginning 2))
6337 (1- (match-end 2))
6338 'js2-jsdoc-type)
6339 (js2-set-face (match-beginning 2)
6340 (match-end 2)
6341 'js2-jsdoc-value)))
6342 (if (match-beginning 3)
6343 (js2-set-face (match-beginning 3)
6344 (match-end 3)
6345 'js2-jsdoc-value)))
6346
6347 (defun js2-highlight-jsdoc (ast)
6348 "Highlight doc comment tags."
6349 (let ((comments (js2-ast-root-comments ast))
6350 beg end)
6351 (save-excursion
6352 (dolist (node comments)
6353 (when (eq (js2-comment-node-format node) 'jsdoc)
6354 (setq beg (js2-node-abs-pos node)
6355 end (+ beg (js2-node-len node)))
6356 (save-restriction
6357 (narrow-to-region beg end)
6358 (dolist (re (list js2-jsdoc-param-tag-regexp
6359 js2-jsdoc-typed-tag-regexp
6360 js2-jsdoc-arg-tag-regexp
6361 js2-jsdoc-link-tag-regexp
6362 js2-jsdoc-see-tag-regexp
6363 js2-jsdoc-empty-tag-regexp))
6364 (goto-char beg)
6365 (while (re-search-forward re nil t)
6366 (js2-jsdoc-highlight-helper)))
6367 ;; simple highlighting for html tags
6368 (goto-char beg)
6369 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6370 (js2-set-face (match-beginning 1)
6371 (match-end 1)
6372 'js2-jsdoc-html-tag-delimiter)
6373 (js2-set-face (match-beginning 2)
6374 (match-end 2)
6375 'js2-jsdoc-html-tag-name)
6376 (js2-set-face (match-beginning 3)
6377 (match-end 3)
6378 'js2-jsdoc-html-tag-delimiter))))))))
6379
6380 (defun js2-highlight-assign-targets (_node left right)
6381 "Highlight function properties and external variables."
6382 (let (leftpos name)
6383 ;; highlight vars and props assigned function values
6384 (when (js2-function-node-p right)
6385 (cond
6386 ;; var foo = function() {...}
6387 ((js2-name-node-p left)
6388 (setq name left))
6389 ;; foo.bar.baz = function() {...}
6390 ((and (js2-prop-get-node-p left)
6391 (js2-name-node-p (js2-prop-get-node-right left)))
6392 (setq name (js2-prop-get-node-right left))))
6393 (when name
6394 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6395 (+ leftpos (js2-node-len name))
6396 'font-lock-function-name-face
6397 'record)))))
6398
6399 (defun js2-record-name-node (node)
6400 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6401 later. NODE must be a name node."
6402 (let ((leftpos (js2-node-abs-pos node)))
6403 (push (list node js2-current-scope
6404 leftpos
6405 (+ leftpos (js2-node-len node)))
6406 js2-recorded-identifiers)))
6407
6408 (defun js2-highlight-undeclared-vars ()
6409 "After entire parse is finished, look for undeclared variable references.
6410 We have to wait until entire buffer is parsed, since JavaScript permits var
6411 decls to occur after they're used.
6412
6413 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6414 it is considered declared."
6415 (let (name)
6416 (dolist (entry js2-recorded-identifiers)
6417 (destructuring-bind (name-node scope pos end) entry
6418 (setq name (js2-name-node-name name-node))
6419 (unless (or (member name js2-global-externs)
6420 (member name js2-default-externs)
6421 (member name js2-additional-externs)
6422 (js2-get-defining-scope scope name))
6423 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6424 'js2-external-variable))))
6425 (setq js2-recorded-identifiers nil)))
6426
6427 (defun js2-set-default-externs ()
6428 "Set the value of `js2-default-externs' based on the various
6429 `js2-include-?-externs' variables."
6430 (setq js2-default-externs
6431 (append js2-ecma-262-externs
6432 (if js2-include-browser-externs js2-browser-externs)
6433 (if js2-include-rhino-externs js2-rhino-externs)
6434 (if js2-include-node-externs js2-node-externs)
6435 (if (or js2-include-browser-externs js2-include-node-externs)
6436 js2-typed-array-externs))))
6437
6438 (defun js2-apply-jslint-globals ()
6439 (setq js2-additional-externs
6440 (nconc (js2-get-jslint-globals)
6441 js2-additional-externs)))
6442
6443 (defun js2-get-jslint-globals ()
6444 (loop for node in (js2-ast-root-comments js2-mode-ast)
6445 when (and (eq 'block (js2-comment-node-format node))
6446 (save-excursion
6447 (goto-char (js2-node-abs-pos node))
6448 (looking-at "/\\*global ")))
6449 append (js2-get-jslint-globals-in
6450 (match-end 0)
6451 (js2-node-abs-end node))))
6452
6453 (defun js2-get-jslint-globals-in (beg end)
6454 (let (res)
6455 (save-excursion
6456 (goto-char beg)
6457 (while (re-search-forward js2-mode-identifier-re end t)
6458 (let ((match (match-string 0)))
6459 (unless (member match '("true" "false"))
6460 (push match res)))))
6461 (nreverse res)))
6462
6463 ;;; IMenu support
6464
6465 ;; We currently only support imenu, but eventually should support speedbar and
6466 ;; possibly other browsing mechanisms.
6467
6468 ;; The basic strategy is to identify function assignment targets of the form
6469 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6470 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6471 ;; for imenu after parsing is finished.
6472
6473 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6474 ;; JavaScript, and the general problem is undecidable. However, several forms
6475 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6476 ;; include:
6477
6478 ;; function foo() -- function declaration
6479 ;; foo = function() -- function expression assigned to variable
6480 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6481 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6482 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6483 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6484 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6485 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6486 ;; function foo() {function bar() {...}} -- nested function
6487 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6488
6489 ;; This list boils down to a few forms that can be combined recursively.
6490 ;; Top-level named function declarations include both the left-hand (name)
6491 ;; and the right-hand (function value) expressions needed to produce an imenu
6492 ;; entry. The other "right-hand" forms we need to look for are:
6493 ;; - functions declared as props/getters/setters in object literals
6494 ;; - nested named function declarations
6495 ;; The "left-hand" expressions that functions can be assigned to include:
6496 ;; - local/global variables
6497 ;; - nested property-get expressions like a.b.c.d
6498 ;; - element gets like foo[10] or foo['bar'] where the index
6499 ;; expression can be trivially converted to a property name. They
6500 ;; effectively then become property gets.
6501
6502 ;; All the different definition types are canonicalized into the form
6503 ;; foo.bar.baz = position-of-function-keyword
6504
6505 ;; We need to build a trie-like structure for imenu. As an example,
6506 ;; consider the following JavaScript code:
6507
6508 ;; a = function() {...} // function at position 5
6509 ;; b = function() {...} // function at position 25
6510 ;; foo = function() {...} // function at position 100
6511 ;; foo.bar = function() {...} // function at position 200
6512 ;; foo.bar.baz = function() {...} // function at position 300
6513 ;; foo.bar.zab = function() {...} // function at position 400
6514
6515 ;; During parsing we accumulate an entry for each definition in
6516 ;; the variable `js2-imenu-recorder', like so:
6517
6518 ;; '((fn a 5)
6519 ;; (fn b 25)
6520 ;; (fn foo 100)
6521 ;; (fn foo bar 200)
6522 ;; (fn foo bar baz 300)
6523 ;; (fn foo bar zab 400))
6524
6525 ;; Where 'fn' is the respective function node.
6526 ;; After parsing these entries are merged into this alist-trie:
6527
6528 ;; '((a . 1)
6529 ;; (b . 2)
6530 ;; (foo (<definition> . 3)
6531 ;; (bar (<definition> . 6)
6532 ;; (baz . 100)
6533 ;; (zab . 200))))
6534
6535 ;; Note the wacky need for a <definition> name. The token can be anything
6536 ;; that isn't a valid JavaScript identifier, because you might make foo
6537 ;; a function and then start setting properties on it that are also functions.
6538
6539 (defun js2-prop-node-name (node)
6540 "Return the name of a node that may be a property-get/property-name.
6541 If NODE is not a valid name-node, string-node or integral number-node,
6542 returns nil. Otherwise returns the string name/value of the node."
6543 (cond
6544 ((js2-name-node-p node)
6545 (js2-name-node-name node))
6546 ((js2-string-node-p node)
6547 (js2-string-node-value node))
6548 ((and (js2-number-node-p node)
6549 (string-match "^[0-9]+$" (js2-number-node-value node)))
6550 (js2-number-node-value node))
6551 ((js2-this-node-p node)
6552 "this")))
6553
6554 (defun js2-node-qname-component (node)
6555 "Return the name of this node, if it contributes to a qname.
6556 Returns nil if the node doesn't contribute."
6557 (copy-sequence
6558 (or (js2-prop-node-name node)
6559 (if (and (js2-function-node-p node)
6560 (js2-function-node-name node))
6561 (js2-name-node-name (js2-function-node-name node))))))
6562
6563 (defun js2-record-imenu-entry (fn-node qname pos)
6564 "Add an entry to `js2-imenu-recorder'.
6565 FN-NODE should be the current item's function node.
6566
6567 Associate FN-NODE with its QNAME for later lookup.
6568 This is used in postprocessing the chain list. For each chain, we find
6569 the parent function, look up its qname, then prepend a copy of it to the chain."
6570 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6571 (unless js2-imenu-function-map
6572 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6573 (puthash fn-node qname js2-imenu-function-map))
6574
6575 (defun js2-record-imenu-functions (node &optional var)
6576 "Record function definitions for imenu.
6577 NODE is a function node or an object literal.
6578 VAR, if non-nil, is the expression that NODE is being assigned to.
6579 When passed arguments of wrong type, does nothing."
6580 (when js2-parse-ide-mode
6581 (let ((fun-p (js2-function-node-p node))
6582 qname fname-node)
6583 (cond
6584 ;; non-anonymous function declaration?
6585 ((and fun-p
6586 (not var)
6587 (setq fname-node (js2-function-node-name node)))
6588 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6589 ;; for remaining forms, compute left-side tree branch first
6590 ((and var (setq qname (js2-compute-nested-prop-get var)))
6591 (cond
6592 ;; foo.bar.baz = function
6593 (fun-p
6594 (js2-record-imenu-entry node qname (js2-node-pos node)))
6595 ;; foo.bar.baz = object-literal
6596 ;; look for nested functions: {a: {b: function() {...} }}
6597 ((js2-object-node-p node)
6598 ;; Node position here is still absolute, since the parser
6599 ;; passes the assignment target and value expressions
6600 ;; to us before they are added as children of the assignment node.
6601 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6602
6603 (defun js2-compute-nested-prop-get (node)
6604 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6605 component nodes as a list. Otherwise return nil. Element-gets are treated
6606 as property-gets if the index expression is a string, or a positive integer."
6607 (let (left right head)
6608 (cond
6609 ((or (js2-name-node-p node)
6610 (js2-this-node-p node))
6611 (list node))
6612 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6613 ((js2-prop-get-node-p node) ; foo.bar
6614 (setq left (js2-prop-get-node-left node)
6615 right (js2-prop-get-node-right node))
6616 (if (setq head (js2-compute-nested-prop-get left))
6617 (nconc head (list right))))
6618 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6619 (setq left (js2-elem-get-node-target node)
6620 right (js2-elem-get-node-element node))
6621 (if (or (js2-string-node-p right) ; ['bar']
6622 (and (js2-number-node-p right) ; [10]
6623 (string-match "^[0-9]+$"
6624 (js2-number-node-value right))))
6625 (if (setq head (js2-compute-nested-prop-get left))
6626 (nconc head (list right))))))))
6627
6628 (defun js2-record-object-literal (node qname pos)
6629 "Recursively process an object literal looking for functions.
6630 NODE is an object literal that is the right-hand child of an assignment
6631 expression. QNAME is a list of nodes representing the assignment target,
6632 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6633 POS is the absolute position of the node.
6634 We do a depth-first traversal of NODE. For any functions we find,
6635 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6636 (let (right)
6637 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6638 (let ((left (js2-infix-node-left e))
6639 ;; Element positions are relative to the parent position.
6640 (pos (+ pos (js2-node-pos e))))
6641 (cond
6642 ;; foo: function() {...}
6643 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6644 (when (js2-prop-node-name left)
6645 ;; As a policy decision, we record the position of the property,
6646 ;; not the position of the `function' keyword, since the property
6647 ;; is effectively the name of the function.
6648 (js2-record-imenu-entry right (append qname (list left)) pos)))
6649 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6650 ((js2-object-node-p right)
6651 (js2-record-object-literal right
6652 (append qname (list (js2-infix-node-left e)))
6653 (+ pos (js2-node-pos right)))))))))
6654
6655 (defun js2-node-top-level-decl-p (node)
6656 "Return t if NODE's name is defined in the top-level scope.
6657 Also returns t if NODE's name is not defined in any scope, since it implies
6658 that it's an external variable, which must also be in the top-level scope."
6659 (let* ((name (js2-prop-node-name node))
6660 (this-scope (js2-node-get-enclosing-scope node))
6661 defining-scope)
6662 (cond
6663 ((js2-this-node-p node)
6664 nil)
6665 ((null this-scope)
6666 t)
6667 ((setq defining-scope (js2-get-defining-scope this-scope name))
6668 (js2-ast-root-p defining-scope))
6669 (t t))))
6670
6671 (defun js2-wrapper-function-p (node)
6672 "Return t if NODE is a function expression that's immediately invoked.
6673 NODE must be `js2-function-node'."
6674 (let ((parent (js2-node-parent node)))
6675 (or
6676 ;; function(){...}();
6677 (js2-call-node-p parent)
6678 (and (js2-paren-node-p parent)
6679 ;; (function(){...})();
6680 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6681 ;; (function(){...}).call(this);
6682 (and (js2-prop-get-node-p parent)
6683 (member (js2-name-node-name (js2-prop-get-node-right parent))
6684 '("call" "apply"))
6685 (js2-call-node-p (js2-node-parent parent))))))))
6686
6687 (defun js2-browse-postprocess-chains (entries)
6688 "Modify function-declaration name chains after parsing finishes.
6689 Some of the information is only available after the parse tree is complete.
6690 For instance, processing a nested scope requires a parent function node."
6691 (let (result fn parent-qname p elem)
6692 (dolist (entry entries)
6693 ;; function node goes first
6694 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6695 ;; Examine head's defining scope:
6696 ;; Pre-processed chain, or top-level/external, keep as-is.
6697 (if (or (stringp head) (js2-node-top-level-decl-p head))
6698 (push chain result)
6699 (when (js2-this-node-p head)
6700 (setq chain (cdr chain))) ; discard this-node
6701 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6702 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6703 (when (eq parent-qname 'not-found)
6704 ;; anonymous function expressions are not recorded
6705 ;; during the parse, so we need to handle this case here
6706 (setq parent-qname
6707 (if (js2-wrapper-function-p fn)
6708 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6709 (if (js2-ast-root-p grandparent)
6710 nil
6711 (gethash grandparent js2-imenu-function-map 'skip)))
6712 'skip))
6713 (puthash fn parent-qname js2-imenu-function-map))
6714 (unless (eq parent-qname 'skip)
6715 ;; prefix parent fn qname to this chain.
6716 (let ((qname (append parent-qname chain)))
6717 (puthash current-fn (butlast qname) js2-imenu-function-map)
6718 (push qname result)))))))
6719 ;; finally replace each node in each chain with its name.
6720 (dolist (chain result)
6721 (setq p chain)
6722 (while p
6723 (if (js2-node-p (setq elem (car p)))
6724 (setcar p (js2-node-qname-component elem)))
6725 (setq p (cdr p))))
6726 result))
6727
6728 ;; Merge name chains into a trie-like tree structure of nested lists.
6729 ;; To simplify construction of the trie, we first build it out using the rule
6730 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6731 ;; [key, num-or-list]. The second element can be a number; if so, this key
6732 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6733 ;; associated with the key at this level.) Otherwise the second element is
6734 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6735 ;; a simple recursive formulation.
6736 ;;
6737 ;; js2-mode is building the data structure for imenu. The imenu documentation
6738 ;; claims that it's the structure above, but in practice it wants the children
6739 ;; at the same list level as the key for that level, which is how I've drawn
6740 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6741 ;; list wrapper around the children at each level.
6742 ;;
6743 ;; A completed nested imenu-alist entry looks like this:
6744 ;; '(("foo"
6745 ;; ("<definition>" . 7)
6746 ;; ("bar"
6747 ;; ("a" . 40)
6748 ;; ("b" . 60))))
6749 ;;
6750 ;; In particular, the documentation for `imenu--index-alist' says that
6751 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6752 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6753
6754 (defun js2-treeify (lst)
6755 "Convert (a b c d) to (a ((b ((c d)))))."
6756 (if (null (cddr lst)) ; list length <= 2
6757 lst
6758 (list (car lst) (list (js2-treeify (cdr lst))))))
6759
6760 (defun js2-build-alist-trie (chains trie)
6761 "Merge declaration name chains into a trie-like alist structure for imenu.
6762 CHAINS is the qname chain list produced during parsing. TRIE is a
6763 list of elements built up so far."
6764 (let (head tail pos branch kids)
6765 (dolist (chain chains)
6766 (setq head (car chain)
6767 tail (cdr chain)
6768 pos (if (numberp (car tail)) (car tail))
6769 branch (js2-find-if (lambda (n)
6770 (string= (car n) head))
6771 trie)
6772 kids (second branch))
6773 (cond
6774 ;; case 1: this key isn't in the trie yet
6775 ((null branch)
6776 (if trie
6777 (setcdr (last trie) (list (js2-treeify chain)))
6778 (setq trie (list (js2-treeify chain)))))
6779 ;; case 2: key is present with a single number entry: replace w/ list
6780 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6781 ;; ("<definition>" 20)))
6782 ((numberp kids)
6783 (setcar (cdr branch)
6784 (list (list "<definition-1>" kids)
6785 (if pos
6786 (list "<definition-2>" pos)
6787 (js2-treeify tail)))))
6788 ;; case 3: key is there (with kids), and we're a number entry
6789 (pos
6790 (setcdr (last kids)
6791 (list
6792 (list (format "<definition-%d>"
6793 (1+ (loop for kid in kids
6794 count (eq ?< (aref (car kid) 0)))))
6795 pos))))
6796 ;; case 4: key is there with kids, need to merge in our chain
6797 (t
6798 (js2-build-alist-trie (list tail) kids))))
6799 trie))
6800
6801 (defun js2-flatten-trie (trie)
6802 "Convert TRIE to imenu-format.
6803 Recurses through nodes, and for each one whose second element is a list,
6804 appends the list's flattened elements to the current element. Also
6805 changes the tails into conses. For instance, this pre-flattened trie
6806
6807 '(a ((b 20)
6808 (c ((d 30)
6809 (e 40)))))
6810
6811 becomes
6812
6813 '(a (b . 20)
6814 (c (d . 30)
6815 (e . 40)))
6816
6817 Note that the root of the trie has no key, just a list of chains.
6818 This is also true for the value of any key with multiple children,
6819 e.g. key 'c' in the example above."
6820 (cond
6821 ((listp (car trie))
6822 (mapcar #'js2-flatten-trie trie))
6823 (t
6824 (if (numberp (second trie))
6825 (cons (car trie) (second trie))
6826 ;; else pop list and append its kids
6827 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6828
6829 (defun js2-build-imenu-index ()
6830 "Turn `js2-imenu-recorder' into an imenu data structure."
6831 (unless (eq js2-imenu-recorder 'empty)
6832 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6833 (result (js2-build-alist-trie chains nil)))
6834 (js2-flatten-trie result))))
6835
6836 (defun js2-test-print-chains (chains)
6837 "Print a list of qname chains.
6838 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6839 i.e. one or more nodes, and an integer position as the list tail."
6840 (mapconcat (lambda (chain)
6841 (concat "("
6842 (mapconcat (lambda (elem)
6843 (if (js2-node-p elem)
6844 (or (js2-node-qname-component elem)
6845 "nil")
6846 (number-to-string elem)))
6847 chain
6848 " ")
6849 ")"))
6850 chains
6851 "\n"))
6852
6853 ;;; Parser
6854
6855 (defconst js2-version "1.8.5"
6856 "Version of JavaScript supported.")
6857
6858 (defmacro js2-record-face (face)
6859 "Record a style run of FACE for the current token."
6860 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6861
6862 (defsubst js2-node-end (n)
6863 "Computes the absolute end of node N.
6864 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6865 is only true until the node is added to its parent; i.e., while parsing."
6866 (+ (js2-node-pos n)
6867 (js2-node-len n)))
6868
6869 (defun js2-record-comment ()
6870 "Record a comment in `js2-scanned-comments'."
6871 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6872 :format js2-ts-comment-type)
6873 js2-scanned-comments)
6874 (when js2-parse-ide-mode
6875 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6876 'font-lock-doc-face
6877 'font-lock-comment-face))
6878 (when (memq js2-ts-comment-type '(html preprocessor))
6879 ;; Tell cc-engine the bounds of the comment.
6880 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6881
6882 ;; This function is called depressingly often, so it should be fast.
6883 ;; Most of the time it's looking at the same token it peeked before.
6884 (defun js2-peek-token ()
6885 "Return the next token without consuming it.
6886 If previous token was consumed, calls scanner to get new token.
6887 If previous token was -not- consumed, returns it (idempotent).
6888
6889 This function will not return a newline (js2-EOL) - instead, it
6890 gobbles newlines until it finds a non-newline token, and flags
6891 that token as appearing just after a newline.
6892
6893 This function will also not return a js2-COMMENT. Instead, it
6894 records comments found in `js2-scanned-comments'. If the token
6895 returned by this function immediately follows a jsdoc comment,
6896 the token is flagged as such.
6897
6898 Note that this function always returned the un-flagged token!
6899 The flags, if any, are saved in `js2-current-flagged-token'."
6900 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6901 js2-current-token ; most common case - return already-peeked token
6902 (let ((tt (js2-get-token)) ; call scanner
6903 saw-eol
6904 face)
6905 ;; process comments and whitespace
6906 (while (or (= tt js2-EOL)
6907 (= tt js2-COMMENT))
6908 (if (= tt js2-EOL)
6909 (setq saw-eol t)
6910 (setq saw-eol nil)
6911 (if js2-record-comments
6912 (js2-record-comment)))
6913 (setq tt (js2-get-token))) ; call scanner
6914 (setq js2-current-token tt
6915 js2-current-flagged-token (if saw-eol
6916 (logior tt js2-ti-after-eol)
6917 tt))
6918 ;; perform lexical fontification as soon as token is scanned
6919 (when js2-parse-ide-mode
6920 (cond
6921 ((minusp tt)
6922 (js2-record-face 'js2-error))
6923 ((setq face (aref js2-kwd-tokens tt))
6924 (js2-record-face face))
6925 ((and (= tt js2-NAME)
6926 (equal js2-ts-string "undefined"))
6927 (js2-record-face 'font-lock-constant-face))))
6928 tt))) ; return unflagged token
6929
6930 (defun js2-peek-flagged-token ()
6931 "Return the current token along with any flags set for it."
6932 (js2-peek-token)
6933 js2-current-flagged-token)
6934
6935 (defsubst js2-consume-token ()
6936 (setq js2-current-flagged-token js2-EOF))
6937
6938 (defun js2-next-token ()
6939 (prog1
6940 (js2-peek-token)
6941 (js2-consume-token)))
6942
6943 (defun js2-next-flagged-token ()
6944 (js2-peek-token)
6945 (prog1 js2-current-flagged-token
6946 (js2-consume-token)))
6947
6948 (defun js2-match-token (match)
6949 "Consume and return t if next token matches MATCH, a bytecode.
6950 Returns nil and consumes nothing if MATCH is not the next token."
6951 (if (/= (js2-peek-token) match)
6952 nil
6953 (js2-consume-token)
6954 t))
6955
6956 (defun js2-match-contextual-kwd (name)
6957 "Consume and return t if next token is `js2-NAME', and its
6958 string is NAME. Returns nil and does nothing otherwise."
6959 (if (or (/= (js2-peek-token) js2-NAME)
6960 (not (string= js2-ts-string name)))
6961 nil
6962 (js2-consume-token)
6963 (js2-record-face 'font-lock-keyword-face)
6964 t))
6965
6966 (defun js2-valid-prop-name-token (tt)
6967 (or (= tt js2-NAME)
6968 (when (and js2-allow-keywords-as-property-names
6969 (plusp tt)
6970 (aref js2-kwd-tokens tt))
6971 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6972 t)))
6973
6974 (defun js2-match-prop-name ()
6975 "Consume token and return t if next token is a valid property name.
6976 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6977 is non-nil and it's a keyword token."
6978 (if (js2-valid-prop-name-token (js2-peek-token))
6979 (progn
6980 (js2-consume-token)
6981 t)
6982 nil))
6983
6984 (defun js2-must-match-prop-name (msg-id &optional pos len)
6985 (if (js2-match-prop-name)
6986 t
6987 (js2-report-error msg-id nil pos len)
6988 nil))
6989
6990 (defun js2-peek-token-or-eol ()
6991 "Return js2-EOL if the current token immediately follows a newline.
6992 Else returns the current token. Used in situations where we don't
6993 consider certain token types valid if they are preceded by a newline.
6994 One example is the postfix ++ or -- operator, which has to be on the
6995 same line as its operand."
6996 (let ((tt (js2-peek-token)))
6997 ;; Check for last peeked token flags
6998 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
6999 js2-EOL
7000 tt)))
7001
7002 (defun js2-set-check-for-label ()
7003 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7004 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7005
7006 (defun js2-must-match (token msg-id &optional pos len)
7007 "Match next token to token code TOKEN, or record a syntax error.
7008 MSG-ID is the error message to report if the match fails.
7009 Returns t on match, nil if no match."
7010 (if (js2-match-token token)
7011 t
7012 (js2-report-error msg-id nil pos len)
7013 nil))
7014
7015 (defsubst js2-inside-function ()
7016 (plusp js2-nesting-of-function))
7017
7018 (defun js2-set-requires-activation ()
7019 (if (js2-function-node-p js2-current-script-or-fn)
7020 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7021
7022 (defun js2-check-activation-name (name _token)
7023 (when (js2-inside-function)
7024 ;; skip language-version 1.2 check from Rhino
7025 (if (or (string= "arguments" name)
7026 (and js2-compiler-activation-names ; only used in codegen
7027 (gethash name js2-compiler-activation-names)))
7028 (js2-set-requires-activation))))
7029
7030 (defun js2-set-is-generator ()
7031 (if (js2-function-node-p js2-current-script-or-fn)
7032 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7033
7034 (defun js2-must-have-xml ()
7035 (unless js2-compiler-xml-available
7036 (js2-report-error "msg.XML.not.available")))
7037
7038 (defun js2-push-scope (scope)
7039 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7040 (assert (js2-scope-p scope))
7041 (assert (null (js2-scope-parent-scope scope)))
7042 (assert (not (eq js2-current-scope scope)))
7043 (setf (js2-scope-parent-scope scope) js2-current-scope
7044 js2-current-scope scope))
7045
7046 (defsubst js2-pop-scope ()
7047 (setq js2-current-scope
7048 (js2-scope-parent-scope js2-current-scope)))
7049
7050 (defun js2-enter-loop (loop-node)
7051 (push loop-node js2-loop-set)
7052 (push loop-node js2-loop-and-switch-set)
7053 (js2-push-scope loop-node)
7054 ;; Tell the current labeled statement (if any) its statement,
7055 ;; and set the jump target of the first label to the loop.
7056 ;; These are used in `js2-parse-continue' to verify that the
7057 ;; continue target is an actual labeled loop. (And for codegen.)
7058 (when js2-labeled-stmt
7059 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7060 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7061 js2-labeled-stmt))) loop-node)))
7062
7063 (defun js2-exit-loop ()
7064 (pop js2-loop-set)
7065 (pop js2-loop-and-switch-set)
7066 (js2-pop-scope))
7067
7068 (defsubst js2-enter-switch (switch-node)
7069 (push switch-node js2-loop-and-switch-set))
7070
7071 (defsubst js2-exit-switch ()
7072 (pop js2-loop-and-switch-set))
7073
7074 (defun js2-parse (&optional buf cb)
7075 "Tell the js2 parser to parse a region of JavaScript.
7076
7077 BUF is a buffer or buffer name containing the code to parse.
7078 Call `narrow-to-region' first to parse only part of the buffer.
7079
7080 The returned AST root node is given some additional properties:
7081 `node-count' - total number of nodes in the AST
7082 `buffer' - BUF. The buffer it refers to may change or be killed,
7083 so the value is not necessarily reliable.
7084
7085 An optional callback CB can be specified to report parsing
7086 progress. If `(functionp CB)' returns t, it will be called with
7087 the current line number once before parsing begins, then again
7088 each time the lexer reaches a new line number.
7089
7090 CB can also be a list of the form `(symbol cb ...)' to specify
7091 multiple callbacks with different criteria. Each symbol is a
7092 criterion keyword, and the following element is the callback to
7093 call
7094
7095 :line - called whenever the line number changes
7096 :token - called for each new token consumed
7097
7098 The list of criteria could be extended to include entering or
7099 leaving a statement, an expression, or a function definition."
7100 (if (and cb (not (functionp cb)))
7101 (error "criteria callbacks not yet implemented"))
7102 (let ((inhibit-point-motion-hooks t)
7103 (js2-compiler-xml-available (>= js2-language-version 160))
7104 ;; This is a recursive-descent parser, so give it a big stack.
7105 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7106 (max-specpdl-size (max max-specpdl-size 3000))
7107 (case-fold-search nil)
7108 ast)
7109 (message nil) ; clear any error message from previous parse
7110 (with-current-buffer (or buf (current-buffer))
7111 (setq js2-scanned-comments nil
7112 js2-parsed-errors nil
7113 js2-parsed-warnings nil
7114 js2-imenu-recorder nil
7115 js2-imenu-function-map nil
7116 js2-label-set nil)
7117 (js2-init-scanner)
7118 (setq ast (with-silent-modifications
7119 (js2-do-parse)))
7120 (unless js2-ts-hit-eof
7121 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7122 (setf (js2-ast-root-errors ast) js2-parsed-errors
7123 (js2-ast-root-warnings ast) js2-parsed-warnings)
7124 ;; if we didn't find any declarations, put a dummy in this list so we
7125 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7126 (unless js2-imenu-recorder
7127 (setq js2-imenu-recorder 'empty))
7128 (run-hooks 'js2-parse-finished-hook)
7129 ast)))
7130
7131 ;; Corresponds to Rhino's Parser.parse() method.
7132 (defun js2-do-parse ()
7133 "Parse current buffer starting from current point.
7134 Scanner should be initialized."
7135 (let ((pos js2-ts-cursor)
7136 (end js2-ts-cursor) ; in case file is empty
7137 root n tt)
7138 ;; initialize buffer-local parsing vars
7139 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7140 js2-current-script-or-fn root
7141 js2-current-scope root
7142 js2-current-flagged-token js2-EOF
7143 js2-nesting-of-function 0
7144 js2-labeled-stmt nil
7145 js2-recorded-identifiers nil) ; for js2-highlight
7146 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7147 (if (= tt js2-FUNCTION)
7148 (progn
7149 (js2-consume-token)
7150 (setq n (js2-parse-function (if js2-called-by-compile-function
7151 'FUNCTION_EXPRESSION
7152 'FUNCTION_STATEMENT))))
7153 ;; not a function - parse a statement
7154 (setq n (js2-parse-statement)))
7155 ;; add function or statement to script
7156 (setq end (js2-node-end n))
7157 (js2-block-node-push root n))
7158 ;; add comments to root in lexical order
7159 (when js2-scanned-comments
7160 ;; if we find a comment beyond end of normal kids, use its end
7161 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7162 (dolist (comment js2-scanned-comments)
7163 (push comment (js2-ast-root-comments root))
7164 (js2-node-add-children root comment)))
7165 (setf (js2-node-len root) (- end pos))
7166 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7167 ;; Give extensions a chance to muck with things before highlighting starts.
7168 (let ((js2-additional-externs js2-additional-externs))
7169 (save-excursion
7170 (run-hooks 'js2-post-parse-callbacks))
7171 (js2-highlight-undeclared-vars))
7172 root))
7173
7174 (defun js2-function-parser ()
7175 (js2-consume-token)
7176 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7177
7178 (defun js2-parse-function-closure-body (fn-node)
7179 "Parse a JavaScript 1.8 function closure body."
7180 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7181 (if js2-ts-hit-eof
7182 (js2-report-error "msg.no.brace.body" nil
7183 (js2-node-pos fn-node)
7184 (- js2-ts-cursor (js2-node-pos fn-node)))
7185 (js2-node-add-children fn-node
7186 (setf (js2-function-node-body fn-node)
7187 (js2-parse-expr t))))))
7188
7189 (defun js2-parse-function-body (fn-node)
7190 (js2-must-match js2-LC "msg.no.brace.body"
7191 (js2-node-pos fn-node)
7192 (- js2-ts-cursor (js2-node-pos fn-node)))
7193 (let ((pos js2-token-beg) ; LC position
7194 (pn (make-js2-block-node)) ; starts at LC position
7195 tt
7196 end)
7197 (incf js2-nesting-of-function)
7198 (unwind-protect
7199 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7200 (= tt js2-EOF)
7201 (= tt js2-RC)))
7202 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7203 (js2-parse-statement)
7204 (js2-consume-token)
7205 (js2-parse-function 'FUNCTION_STATEMENT))))
7206 (decf js2-nesting-of-function))
7207 (setq end js2-token-end) ; assume no curly and leave at current token
7208 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7209 (setq end js2-token-end))
7210 (setf (js2-node-pos pn) pos
7211 (js2-node-len pn) (- end pos))
7212 (setf (js2-function-node-body fn-node) pn)
7213 (js2-node-add-children fn-node pn)
7214 pn))
7215
7216 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7217 "Declare and fontify destructuring parameters inside NODE.
7218 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7219 (cond
7220 ((js2-name-node-p node)
7221 (let (leftpos)
7222 (js2-define-symbol decl-type (js2-name-node-name node)
7223 node ignore-not-in-block)
7224 (when face
7225 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7226 (+ leftpos (js2-node-len node))
7227 face 'record))))
7228 ((js2-object-node-p node)
7229 (dolist (elem (js2-object-node-elems node))
7230 (js2-define-destruct-symbols
7231 (if (js2-object-prop-node-p elem)
7232 (js2-object-prop-node-right elem)
7233 ;; abbreviated destructuring {a, b}
7234 elem)
7235 decl-type face ignore-not-in-block)))
7236 ((js2-array-node-p node)
7237 (dolist (elem (js2-array-node-elems node))
7238 (when elem
7239 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7240 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7241 (js2-node-len node)))))
7242
7243 (defun js2-parse-function-params (fn-node pos)
7244 (if (js2-match-token js2-RP)
7245 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7246 (let (params param default-found rest-param-at)
7247 (loop for tt = (js2-peek-token)
7248 do
7249 (cond
7250 ;; destructuring param
7251 ((or (= tt js2-LB) (= tt js2-LC))
7252 (when default-found
7253 (js2-report-error "msg.no.default.after.default.param"))
7254 (setq param (js2-parse-destruct-primary-expr))
7255 (js2-define-destruct-symbols param
7256 js2-LP
7257 'js2-function-param)
7258 (push param params))
7259 ;; variable name
7260 (t
7261 (when (and (>= js2-language-version 200)
7262 (js2-match-token js2-TRIPLEDOT)
7263 (not rest-param-at))
7264 ;; to report errors if there are more parameters
7265 (setq rest-param-at (length params)))
7266 (js2-must-match js2-NAME "msg.no.parm")
7267 (js2-record-face 'js2-function-param)
7268 (setq param (js2-create-name-node))
7269 (js2-define-symbol js2-LP js2-ts-string param)
7270 ;; default parameter value
7271 (when (or (and default-found
7272 (not rest-param-at)
7273 (js2-must-match js2-ASSIGN
7274 "msg.no.default.after.default.param"
7275 (js2-node-pos param)
7276 (js2-node-len param)))
7277 (and (>= js2-language-version 200)
7278 (js2-match-token js2-ASSIGN)))
7279 (let* ((pos (js2-node-pos param))
7280 (tt js2-current-token)
7281 (op-pos (- js2-token-beg pos))
7282 (left param)
7283 (right (js2-parse-assign-expr))
7284 (len (- (js2-node-end right) pos)))
7285 (setq param (make-js2-assign-node
7286 :type tt :pos pos :len len :op-pos op-pos
7287 :left left :right right)
7288 default-found t)
7289 (js2-node-add-children param left right)))
7290 (push param params)))
7291 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7292 (js2-report-error "msg.param.after.rest" nil
7293 (js2-node-pos param) (js2-node-len param)))
7294 while
7295 (js2-match-token js2-COMMA))
7296 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7297 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7298 (when rest-param-at
7299 (setf (js2-function-node-rest-p fn-node) t))
7300 (dolist (p params)
7301 (js2-node-add-children fn-node p)
7302 (push p (js2-function-node-params fn-node))))))
7303
7304 (defun js2-check-inconsistent-return-warning (fn-node name)
7305 "Possibly show inconsistent-return warning.
7306 Last token scanned is the close-curly for the function body."
7307 (when (and js2-mode-show-strict-warnings
7308 js2-strict-inconsistent-return-warning
7309 (not (js2-has-consistent-return-usage
7310 (js2-function-node-body fn-node))))
7311 ;; Have it extend from close-curly to bol or beginning of block.
7312 (let ((pos (save-excursion
7313 (goto-char js2-token-end)
7314 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7315 (point-at-bol))))
7316 (end js2-token-end))
7317 (if (plusp (js2-name-node-length name))
7318 (js2-add-strict-warning "msg.no.return.value"
7319 (js2-name-node-name name) pos end)
7320 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7321
7322 (defun js2-parse-function (function-type)
7323 "Function parser. FUNCTION-TYPE is a symbol."
7324 (let ((pos js2-token-beg) ; start of 'function' keyword
7325 name name-beg name-end fn-node lp
7326 (synthetic-type function-type)
7327 member-expr-node)
7328 ;; parse function name, expression, or non-name (anonymous)
7329 (cond
7330 ;; function foo(...)
7331 ((js2-match-token js2-NAME)
7332 (setq name (js2-create-name-node t)
7333 name-beg js2-token-beg
7334 name-end js2-token-end)
7335 (unless (js2-match-token js2-LP)
7336 (when js2-allow-member-expr-as-function-name
7337 ;; function foo.bar(...)
7338 (setq member-expr-node name
7339 name nil
7340 member-expr-node (js2-parse-member-expr-tail
7341 nil member-expr-node)))
7342 (js2-must-match js2-LP "msg.no.paren.parms")))
7343 ((js2-match-token js2-LP)
7344 nil) ; anonymous function: leave name as null
7345 (t
7346 ;; function random-member-expr(...)
7347 (when js2-allow-member-expr-as-function-name
7348 ;; Note that memberExpr can not start with '(' like
7349 ;; in function (1+2).toString(), because 'function (' already
7350 ;; processed as anonymous function
7351 (setq member-expr-node (js2-parse-member-expr)))
7352 (js2-must-match js2-LP "msg.no.paren.parms")))
7353 (if (= js2-current-token js2-LP) ; eventually matched LP?
7354 (setq lp js2-token-beg))
7355 (if member-expr-node
7356 (progn
7357 (setq synthetic-type 'FUNCTION_EXPRESSION)
7358 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7359 (if name
7360 (js2-set-face name-beg name-end
7361 'font-lock-function-name-face 'record)))
7362 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7363 (plusp (js2-name-node-length name)))
7364 ;; Function statements define a symbol in the enclosing scope
7365 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7366 (setf fn-node (make-js2-function-node :pos pos
7367 :name name
7368 :form function-type
7369 :lp (if lp (- lp pos))))
7370 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7371 ;; 1. Nested functions are not affected by the dynamic scope flag
7372 ;; as dynamic scope is already a parent of their scope.
7373 ;; 2. Functions defined under the with statement also immune to
7374 ;; this setup, in which case dynamic scope is ignored in favor
7375 ;; of the with object.
7376 (setf (js2-function-node-ignore-dynamic fn-node) t))
7377 ;; dynamically bind all the per-function variables
7378 (let ((js2-current-script-or-fn fn-node)
7379 (js2-current-scope fn-node)
7380 (js2-nesting-of-with 0)
7381 (js2-end-flags 0)
7382 js2-label-set
7383 js2-loop-set
7384 js2-loop-and-switch-set)
7385 (js2-parse-function-params fn-node pos)
7386 (if (and (>= js2-language-version 180)
7387 (/= (js2-peek-token) js2-LC))
7388 (js2-parse-function-closure-body fn-node)
7389 (js2-parse-function-body fn-node))
7390 (if name
7391 (js2-node-add-children fn-node name))
7392 (js2-check-inconsistent-return-warning fn-node name)
7393 ;; Function expressions define a name only in the body of the
7394 ;; function, and only if not hidden by a parameter name
7395 (if (and name
7396 (eq synthetic-type 'FUNCTION_EXPRESSION)
7397 (null (js2-scope-get-symbol js2-current-scope
7398 (js2-name-node-name name))))
7399 (js2-define-symbol js2-FUNCTION
7400 (js2-name-node-name name)
7401 fn-node))
7402 (if (and name
7403 (not (eq function-type 'FUNCTION_EXPRESSION)))
7404 (js2-record-imenu-functions fn-node)))
7405 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7406 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7407 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7408 ;; We wait until after parsing the function to set its parent scope,
7409 ;; since `js2-define-symbol' needs the defining-scope check to stop
7410 ;; at the function boundary when checking for redeclarations.
7411 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7412 fn-node))
7413
7414 (defun js2-parse-statements (&optional parent)
7415 "Parse a statement list. Last token consumed must be js2-LC.
7416
7417 PARENT can be a `js2-block-node', in which case the statements are
7418 appended to PARENT. Otherwise a new `js2-block-node' is created
7419 and returned.
7420
7421 This function does not match the closing js2-RC: the caller
7422 matches the RC so it can provide a suitable error message if not
7423 matched. This means it's up to the caller to set the length of
7424 the node to include the closing RC. The node start pos is set to
7425 the absolute buffer start position, and the caller should fix it
7426 up to be relative to the parent node. All children of this block
7427 node are given relative start positions and correct lengths."
7428 (let ((pn (or parent (make-js2-block-node)))
7429 tt)
7430 (setf (js2-node-pos pn) js2-token-beg)
7431 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7432 (/= tt js2-RC))
7433 (js2-block-node-push pn (js2-parse-statement)))
7434 pn))
7435
7436 (defun js2-parse-statement ()
7437 (let (pn beg end)
7438 ;; coarse-grained user-interrupt check - needs work
7439 (and js2-parse-interruptable-p
7440 (zerop (% (incf js2-parse-stmt-count)
7441 js2-statements-per-pause))
7442 (input-pending-p)
7443 (throw 'interrupted t))
7444 (setq pn (js2-statement-helper))
7445 ;; no-side-effects warning check
7446 (unless (js2-node-has-side-effects pn)
7447 (setq end (js2-node-end pn))
7448 (save-excursion
7449 (goto-char end)
7450 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7451 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7452 pn))
7453
7454 ;; These correspond to the switch cases in Parser.statementHelper
7455 (defconst js2-parsers
7456 (let ((parsers (make-vector js2-num-tokens
7457 #'js2-parse-expr-stmt)))
7458 (aset parsers js2-BREAK #'js2-parse-break)
7459 (aset parsers js2-CONST #'js2-parse-const-var)
7460 (aset parsers js2-CONTINUE #'js2-parse-continue)
7461 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7462 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7463 (aset parsers js2-DO #'js2-parse-do)
7464 (aset parsers js2-FOR #'js2-parse-for)
7465 (aset parsers js2-FUNCTION #'js2-function-parser)
7466 (aset parsers js2-IF #'js2-parse-if)
7467 (aset parsers js2-LC #'js2-parse-block)
7468 (aset parsers js2-LET #'js2-parse-let-stmt)
7469 (aset parsers js2-NAME #'js2-parse-name-or-label)
7470 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7471 (aset parsers js2-SEMI #'js2-parse-semi)
7472 (aset parsers js2-SWITCH #'js2-parse-switch)
7473 (aset parsers js2-THROW #'js2-parse-throw)
7474 (aset parsers js2-TRY #'js2-parse-try)
7475 (aset parsers js2-VAR #'js2-parse-const-var)
7476 (aset parsers js2-WHILE #'js2-parse-while)
7477 (aset parsers js2-WITH #'js2-parse-with)
7478 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7479 parsers)
7480 "A vector mapping token types to parser functions.")
7481
7482 (defun js2-parse-warn-missing-semi (beg end)
7483 (and js2-mode-show-strict-warnings
7484 js2-strict-missing-semi-warning
7485 (js2-add-strict-warning
7486 "msg.missing.semi" nil
7487 ;; back up to beginning of statement or line
7488 (max beg (save-excursion
7489 (goto-char end)
7490 (point-at-bol)))
7491 end)))
7492
7493 (defconst js2-no-semi-insertion
7494 (list js2-IF
7495 js2-SWITCH
7496 js2-WHILE
7497 js2-DO
7498 js2-FOR
7499 js2-TRY
7500 js2-WITH
7501 js2-LC
7502 js2-ERROR
7503 js2-SEMI
7504 js2-FUNCTION)
7505 "List of tokens that don't do automatic semicolon insertion.")
7506
7507 (defconst js2-autoinsert-semi-and-warn
7508 (list js2-ERROR js2-EOF js2-RC))
7509
7510 (defun js2-statement-helper ()
7511 (let* ((tt (js2-peek-token))
7512 (first-tt tt)
7513 (parser (if (= tt js2-ERROR)
7514 #'js2-parse-semi
7515 (aref js2-parsers tt)))
7516 pn)
7517 ;; If the statement is set, then it's been told its label by now.
7518 (and js2-labeled-stmt
7519 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7520 (setq js2-labeled-stmt nil))
7521 (setq pn (funcall parser))
7522 ;; Don't do auto semi insertion for certain statement types.
7523 (unless (or (memq first-tt js2-no-semi-insertion)
7524 (js2-labeled-stmt-node-p pn))
7525 (js2-auto-insert-semicolon pn))
7526 pn))
7527
7528 (defun js2-auto-insert-semicolon (pn)
7529 (let* ((tt-flagged (js2-peek-flagged-token))
7530 (tt (logand tt-flagged js2-clear-ti-mask))
7531 (pos (js2-node-pos pn)))
7532 (cond
7533 ((= tt js2-SEMI)
7534 ;; Consume ';' as a part of expression
7535 (js2-consume-token)
7536 ;; extend the node bounds to include the semicolon.
7537 (setf (js2-node-len pn) (- js2-token-end pos)))
7538 ((memq tt js2-autoinsert-semi-and-warn)
7539 ;; Autoinsert ;
7540 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7541 (t
7542 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7543 ;; Report error if no EOL or autoinsert ';' otherwise
7544 (js2-report-error "msg.no.semi.stmt")
7545 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7546
7547 (defun js2-parse-condition ()
7548 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7549 The parens are discarded and the expression node is returned.
7550 The `pos' field of the return value is set to an absolute position
7551 that must be fixed up by the caller.
7552 Return value is a list (EXPR LP RP), with absolute paren positions."
7553 (let (pn lp rp)
7554 (if (js2-must-match js2-LP "msg.no.paren.cond")
7555 (setq lp js2-token-beg))
7556 (setq pn (js2-parse-expr))
7557 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7558 (setq rp js2-token-beg))
7559 ;; Report strict warning on code like "if (a = 7) ..."
7560 (if (and js2-strict-cond-assign-warning
7561 (js2-assign-node-p pn))
7562 (js2-add-strict-warning "msg.equal.as.assign" nil
7563 (js2-node-pos pn)
7564 (+ (js2-node-pos pn)
7565 (js2-node-len pn))))
7566 (list pn lp rp)))
7567
7568 (defun js2-parse-if ()
7569 "Parser for if-statement. Last matched token must be js2-IF."
7570 (let ((pos js2-token-beg)
7571 cond if-true if-false else-pos end pn)
7572 (js2-consume-token)
7573 (setq cond (js2-parse-condition)
7574 if-true (js2-parse-statement)
7575 if-false (if (js2-match-token js2-ELSE)
7576 (progn
7577 (setq else-pos (- js2-token-beg pos))
7578 (js2-parse-statement)))
7579 end (js2-node-end (or if-false if-true))
7580 pn (make-js2-if-node :pos pos
7581 :len (- end pos)
7582 :condition (car cond)
7583 :then-part if-true
7584 :else-part if-false
7585 :else-pos else-pos
7586 :lp (js2-relpos (second cond) pos)
7587 :rp (js2-relpos (third cond) pos)))
7588 (js2-node-add-children pn (car cond) if-true if-false)
7589 pn))
7590
7591 (defun js2-parse-switch ()
7592 "Parser for if-statement. Last matched token must be js2-SWITCH."
7593 (let ((pos js2-token-beg)
7594 tt pn discriminant has-default case-expr case-node
7595 case-pos cases stmt lp)
7596 (js2-consume-token)
7597 (if (js2-must-match js2-LP "msg.no.paren.switch")
7598 (setq lp js2-token-beg))
7599 (setq discriminant (js2-parse-expr)
7600 pn (make-js2-switch-node :discriminant discriminant
7601 :pos pos
7602 :lp (js2-relpos lp pos)))
7603 (js2-node-add-children pn discriminant)
7604 (js2-enter-switch pn)
7605 (unwind-protect
7606 (progn
7607 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7608 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7609 (js2-must-match js2-LC "msg.no.brace.switch")
7610 (catch 'break
7611 (while t
7612 (setq tt (js2-next-token)
7613 case-pos js2-token-beg)
7614 (cond
7615 ((= tt js2-RC)
7616 (setf (js2-node-len pn) (- js2-token-end pos))
7617 (throw 'break nil)) ; done
7618 ((= tt js2-CASE)
7619 (setq case-expr (js2-parse-expr))
7620 (js2-must-match js2-COLON "msg.no.colon.case"))
7621 ((= tt js2-DEFAULT)
7622 (if has-default
7623 (js2-report-error "msg.double.switch.default"))
7624 (setq has-default t
7625 case-expr nil)
7626 (js2-must-match js2-COLON "msg.no.colon.case"))
7627 (t
7628 (js2-report-error "msg.bad.switch")
7629 (throw 'break nil)))
7630 (setq case-node (make-js2-case-node :pos case-pos
7631 :len (- js2-token-end case-pos)
7632 :expr case-expr))
7633 (js2-node-add-children case-node case-expr)
7634 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7635 (/= tt js2-CASE)
7636 (/= tt js2-DEFAULT)
7637 (/= tt js2-EOF))
7638 (setf stmt (js2-parse-statement)
7639 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7640 (js2-block-node-push case-node stmt))
7641 (push case-node cases)))
7642 ;; add cases last, as pushing reverses the order to be correct
7643 (dolist (kid cases)
7644 (js2-node-add-children pn kid)
7645 (push kid (js2-switch-node-cases pn)))
7646 pn) ; return value
7647 (js2-exit-switch))))
7648
7649 (defun js2-parse-while ()
7650 "Parser for while-statement. Last matched token must be js2-WHILE."
7651 (let ((pos js2-token-beg)
7652 (pn (make-js2-while-node))
7653 cond body)
7654 (js2-consume-token)
7655 (js2-enter-loop pn)
7656 (unwind-protect
7657 (progn
7658 (setf cond (js2-parse-condition)
7659 (js2-while-node-condition pn) (car cond)
7660 body (js2-parse-statement)
7661 (js2-while-node-body pn) body
7662 (js2-node-len pn) (- (js2-node-end body) pos)
7663 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7664 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7665 (js2-node-add-children pn body (car cond)))
7666 (js2-exit-loop))
7667 pn))
7668
7669 (defun js2-parse-do ()
7670 "Parser for do-statement. Last matched token must be js2-DO."
7671 (let ((pos js2-token-beg)
7672 (pn (make-js2-do-node))
7673 cond body end)
7674 (js2-consume-token)
7675 (js2-enter-loop pn)
7676 (unwind-protect
7677 (progn
7678 (setq body (js2-parse-statement))
7679 (js2-must-match js2-WHILE "msg.no.while.do")
7680 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7681 cond (js2-parse-condition)
7682 (js2-do-node-condition pn) (car cond)
7683 (js2-do-node-body pn) body
7684 end js2-ts-cursor
7685 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7686 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7687 (js2-node-add-children pn (car cond) body))
7688 (js2-exit-loop))
7689 ;; Always auto-insert semicolon to follow SpiderMonkey:
7690 ;; It is required by ECMAScript but is ignored by the rest of
7691 ;; world; see bug 238945
7692 (if (js2-match-token js2-SEMI)
7693 (setq end js2-ts-cursor))
7694 (setf (js2-node-len pn) (- end pos))
7695 pn))
7696
7697 (defun js2-parse-for ()
7698 "Parser for for-statement. Last matched token must be js2-FOR.
7699 Parses for, for-in, and for each-in statements."
7700 (let ((for-pos js2-token-beg)
7701 pn is-for-each is-for-in-or-of is-for-of
7702 in-pos each-pos tmp-pos
7703 init ; Node init is also foo in 'foo in object'
7704 cond ; Node cond is also object in 'foo in object'
7705 incr ; 3rd section of for-loop initializer
7706 body tt lp rp)
7707 (js2-consume-token)
7708 ;; See if this is a for each () instead of just a for ()
7709 (when (js2-match-token js2-NAME)
7710 (if (string= "each" js2-ts-string)
7711 (progn
7712 (setq is-for-each t
7713 each-pos (- js2-token-beg for-pos)) ; relative
7714 (js2-record-face 'font-lock-keyword-face))
7715 (js2-report-error "msg.no.paren.for")))
7716 (if (js2-must-match js2-LP "msg.no.paren.for")
7717 (setq lp (- js2-token-beg for-pos)))
7718 (setq tt (js2-peek-token))
7719 ;; 'for' makes local scope
7720 (js2-push-scope (make-js2-scope))
7721 (unwind-protect
7722 ;; parse init clause
7723 (let ((js2-in-for-init t)) ; set as dynamic variable
7724 (cond
7725 ((= tt js2-SEMI)
7726 (setq init (make-js2-empty-expr-node)))
7727 ((or (= tt js2-VAR) (= tt js2-LET))
7728 (js2-consume-token)
7729 (setq init (js2-parse-variables tt js2-token-beg)))
7730 (t
7731 (setq init (js2-parse-expr)))))
7732 (if (or (js2-match-token js2-IN)
7733 (and (>= js2-language-version 200)
7734 (js2-match-contextual-kwd "of")
7735 (setq is-for-of t)))
7736 (setq is-for-in-or-of t
7737 in-pos (- js2-token-beg for-pos)
7738 ;; scope of iteration target object is not the scope we've created above.
7739 ;; stash current scope temporary.
7740 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7741 (js2-parse-expr))) ; object over which we're iterating
7742 ;; else ordinary for loop - parse cond and incr
7743 (js2-must-match js2-SEMI "msg.no.semi.for")
7744 (setq cond (if (= (js2-peek-token) js2-SEMI)
7745 (make-js2-empty-expr-node) ; no loop condition
7746 (js2-parse-expr)))
7747 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7748 (setq tmp-pos js2-token-end
7749 incr (if (= (js2-peek-token) js2-RP)
7750 (make-js2-empty-expr-node :pos tmp-pos)
7751 (js2-parse-expr))))
7752 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7753 (setq rp (- js2-token-beg for-pos)))
7754 (if (not is-for-in-or-of)
7755 (setq pn (make-js2-for-node :init init
7756 :condition cond
7757 :update incr
7758 :lp lp
7759 :rp rp))
7760 ;; cond could be null if 'in obj' got eaten by the init node.
7761 (if (js2-infix-node-p init)
7762 ;; it was (foo in bar) instead of (var foo in bar)
7763 (setq cond (js2-infix-node-right init)
7764 init (js2-infix-node-left init))
7765 (if (and (js2-var-decl-node-p init)
7766 (> (length (js2-var-decl-node-kids init)) 1))
7767 (js2-report-error "msg.mult.index")))
7768 (setq pn (make-js2-for-in-node :iterator init
7769 :object cond
7770 :in-pos in-pos
7771 :foreach-p is-for-each
7772 :each-pos each-pos
7773 :forof-p is-for-of
7774 :lp lp
7775 :rp rp)))
7776 (unwind-protect
7777 (progn
7778 (js2-enter-loop pn)
7779 ;; We have to parse the body -after- creating the loop node,
7780 ;; so that the loop node appears in the js2-loop-set, allowing
7781 ;; break/continue statements to find the enclosing loop.
7782 (setf body (js2-parse-statement)
7783 (js2-loop-node-body pn) body
7784 (js2-node-pos pn) for-pos
7785 (js2-node-len pn) (- (js2-node-end body) for-pos))
7786 (js2-node-add-children pn init cond incr body))
7787 ;; finally
7788 (js2-exit-loop))
7789 (js2-pop-scope))
7790 pn))
7791
7792 (defun js2-parse-try ()
7793 "Parser for try-statement. Last matched token must be js2-TRY."
7794 (let ((try-pos js2-token-beg)
7795 try-end
7796 try-block
7797 catch-blocks
7798 finally-block
7799 saw-default-catch
7800 peek
7801 param
7802 catch-cond
7803 catch-node
7804 guard-kwd
7805 catch-pos
7806 finally-pos
7807 pn
7808 block
7809 lp
7810 rp)
7811 (js2-consume-token)
7812 (if (/= (js2-peek-token) js2-LC)
7813 (js2-report-error "msg.no.brace.try"))
7814 (setq try-block (js2-parse-statement)
7815 try-end (js2-node-end try-block)
7816 peek (js2-peek-token))
7817 (cond
7818 ((= peek js2-CATCH)
7819 (while (js2-match-token js2-CATCH)
7820 (setq catch-pos js2-token-beg
7821 guard-kwd nil
7822 catch-cond nil
7823 lp nil
7824 rp nil)
7825 (if saw-default-catch
7826 (js2-report-error "msg.catch.unreachable"))
7827 (if (js2-must-match js2-LP "msg.no.paren.catch")
7828 (setq lp (- js2-token-beg catch-pos)))
7829 (js2-push-scope (make-js2-scope))
7830 (let ((tt (js2-peek-token)))
7831 (cond
7832 ;; destructuring pattern
7833 ;; catch ({ message, file }) { ... }
7834 ((or (= tt js2-LB) (= tt js2-LC))
7835 (setq param (js2-parse-destruct-primary-expr))
7836 (js2-define-destruct-symbols param js2-LET nil))
7837 ;; simple name
7838 (t
7839 (js2-must-match js2-NAME "msg.bad.catchcond")
7840 (setq param (js2-create-name-node))
7841 (js2-define-symbol js2-LET js2-ts-string param))))
7842 ;; pattern guard
7843 (if (js2-match-token js2-IF)
7844 (setq guard-kwd (- js2-token-beg catch-pos)
7845 catch-cond (js2-parse-expr))
7846 (setq saw-default-catch t))
7847 (if (js2-must-match js2-RP "msg.bad.catchcond")
7848 (setq rp (- js2-token-beg catch-pos)))
7849 (js2-must-match js2-LC "msg.no.brace.catchblock")
7850 (setq block (js2-parse-statements)
7851 try-end (js2-node-end block)
7852 catch-node (make-js2-catch-node :pos catch-pos
7853 :param param
7854 :guard-expr catch-cond
7855 :guard-kwd guard-kwd
7856 :block block
7857 :lp lp
7858 :rp rp))
7859 (js2-pop-scope)
7860 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7861 (setq try-end js2-token-beg))
7862 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7863 (js2-node-len catch-node) (- try-end catch-pos))
7864 (js2-node-add-children catch-node param catch-cond block)
7865 (push catch-node catch-blocks)))
7866 ((/= peek js2-FINALLY)
7867 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7868 (js2-node-pos try-block)
7869 (- (setq try-end (js2-node-end try-block))
7870 (js2-node-pos try-block)))))
7871 (when (js2-match-token js2-FINALLY)
7872 (setq finally-pos js2-token-beg
7873 block (js2-parse-statement)
7874 try-end (js2-node-end block)
7875 finally-block (make-js2-finally-node :pos finally-pos
7876 :len (- try-end finally-pos)
7877 :body block))
7878 (js2-node-add-children finally-block block))
7879 (setq pn (make-js2-try-node :pos try-pos
7880 :len (- try-end try-pos)
7881 :try-block try-block
7882 :finally-block finally-block))
7883 (js2-node-add-children pn try-block finally-block)
7884 ;; push them onto the try-node, which reverses and corrects their order
7885 (dolist (cb catch-blocks)
7886 (js2-node-add-children pn cb)
7887 (push cb (js2-try-node-catch-clauses pn)))
7888 pn))
7889
7890 (defun js2-parse-throw ()
7891 "Parser for throw-statement. Last matched token must be js2-THROW."
7892 (let ((pos js2-token-beg)
7893 expr pn)
7894 (js2-consume-token)
7895 (if (= (js2-peek-token-or-eol) js2-EOL)
7896 ;; ECMAScript does not allow new lines before throw expression,
7897 ;; see bug 256617
7898 (js2-report-error "msg.bad.throw.eol"))
7899 (setq expr (js2-parse-expr)
7900 pn (make-js2-throw-node :pos pos
7901 :len (- (js2-node-end expr) pos)
7902 :expr expr))
7903 (js2-node-add-children pn expr)
7904 pn))
7905
7906 (defun js2-match-jump-label-name (label-name)
7907 "If break/continue specified a label, return that label's labeled stmt.
7908 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7909 does not match an existing label, reports an error and returns nil."
7910 (let ((bundle (cdr (assoc label-name js2-label-set))))
7911 (if (null bundle)
7912 (js2-report-error "msg.undef.label"))
7913 bundle))
7914
7915 (defun js2-parse-break ()
7916 "Parser for break-statement. Last matched token must be js2-BREAK."
7917 (let ((pos js2-token-beg)
7918 (end js2-token-end)
7919 break-target ; statement to break from
7920 break-label ; in "break foo", name-node representing the foo
7921 labels ; matching labeled statement to break to
7922 pn)
7923 (js2-consume-token) ; `break'
7924 (when (eq (js2-peek-token-or-eol) js2-NAME)
7925 (js2-consume-token)
7926 (setq break-label (js2-create-name-node)
7927 end (js2-node-end break-label)
7928 ;; matchJumpLabelName only matches if there is one
7929 labels (js2-match-jump-label-name js2-ts-string)
7930 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7931 (unless (or break-target break-label)
7932 ;; no break target specified - try for innermost enclosing loop/switch
7933 (if (null js2-loop-and-switch-set)
7934 (unless break-label
7935 (js2-report-error "msg.bad.break" nil pos (length "break")))
7936 (setq break-target (car js2-loop-and-switch-set))))
7937 (setq pn (make-js2-break-node :pos pos
7938 :len (- end pos)
7939 :label break-label
7940 :target break-target))
7941 (js2-node-add-children pn break-label) ; but not break-target
7942 pn))
7943
7944 (defun js2-parse-continue ()
7945 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7946 (let ((pos js2-token-beg)
7947 (end js2-token-end)
7948 label ; optional user-specified label, a `js2-name-node'
7949 labels ; current matching labeled stmt, if any
7950 target ; the `js2-loop-node' target of this continue stmt
7951 pn)
7952 (js2-consume-token) ; `continue'
7953 (when (= (js2-peek-token-or-eol) js2-NAME)
7954 (js2-consume-token)
7955 (setq label (js2-create-name-node)
7956 end (js2-node-end label)
7957 ;; matchJumpLabelName only matches if there is one
7958 labels (js2-match-jump-label-name js2-ts-string)))
7959 (cond
7960 ((null labels) ; no current label to go to
7961 (if (null js2-loop-set) ; no loop to continue to
7962 (js2-report-error "msg.continue.outside" nil pos
7963 (length "continue"))
7964 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7965 (t
7966 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7967 (setq target (js2-labeled-stmt-node-stmt labels))
7968 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7969 (setq pn (make-js2-continue-node :pos pos
7970 :len (- end pos)
7971 :label label
7972 :target target))
7973 (js2-node-add-children pn label) ; but not target - it's not our child
7974 pn))
7975
7976 (defun js2-parse-with ()
7977 "Parser for with-statement. Last matched token must be js2-WITH."
7978 (js2-consume-token)
7979 (let ((pos js2-token-beg)
7980 obj body pn lp rp)
7981 (if (js2-must-match js2-LP "msg.no.paren.with")
7982 (setq lp js2-token-beg))
7983 (setq obj (js2-parse-expr))
7984 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7985 (setq rp js2-token-beg))
7986 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7987 (setq body (js2-parse-statement)))
7988 (setq pn (make-js2-with-node :pos pos
7989 :len (- (js2-node-end body) pos)
7990 :object obj
7991 :body body
7992 :lp (js2-relpos lp pos)
7993 :rp (js2-relpos rp pos)))
7994 (js2-node-add-children pn obj body)
7995 pn))
7996
7997 (defun js2-parse-const-var ()
7998 "Parser for var- or const-statement.
7999 Last matched token must be js2-CONST or js2-VAR."
8000 (let ((tt (js2-peek-token))
8001 (pos js2-token-beg)
8002 expr pn)
8003 (js2-consume-token)
8004 (setq expr (js2-parse-variables tt js2-token-beg)
8005 pn (make-js2-expr-stmt-node :pos pos
8006 :len (- (js2-node-end expr) pos)
8007 :expr expr))
8008 (js2-node-add-children pn expr)
8009 pn))
8010
8011 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8012 (let ((pn (make-js2-expr-stmt-node :pos pos
8013 :len (js2-node-len expr)
8014 :type (if (js2-inside-function)
8015 js2-EXPR_VOID
8016 js2-EXPR_RESULT)
8017 :expr expr)))
8018 (if add-child
8019 (js2-node-add-children pn expr))
8020 pn))
8021
8022 (defun js2-parse-let-stmt ()
8023 "Parser for let-statement. Last matched token must be js2-LET."
8024 (js2-consume-token)
8025 (let ((pos js2-token-beg)
8026 expr pn)
8027 (if (= (js2-peek-token) js2-LP)
8028 ;; let expression in statement context
8029 (setq expr (js2-parse-let pos 'statement)
8030 pn (js2-wrap-with-expr-stmt pos expr t))
8031 ;; else we're looking at a statement like let x=6, y=7;
8032 (setf expr (js2-parse-variables js2-LET pos)
8033 pn (js2-wrap-with-expr-stmt pos expr t)
8034 (js2-node-type pn) js2-EXPR_RESULT))
8035 pn))
8036
8037 (defun js2-parse-ret-yield ()
8038 (js2-parse-return-or-yield (js2-peek-token) nil))
8039
8040 (defconst js2-parse-return-stmt-enders
8041 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8042
8043 (defsubst js2-now-all-set (before after mask)
8044 "Return whether or not the bits in the mask have changed to all set.
8045 BEFORE is bits before change, AFTER is bits after change, and MASK is
8046 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8047 but not BEFORE."
8048 (and (/= (logand before mask) mask)
8049 (= (logand after mask) mask)))
8050
8051 (defun js2-parse-return-or-yield (tt expr-context)
8052 (let ((pos js2-token-beg)
8053 (end js2-token-end)
8054 (before js2-end-flags)
8055 (inside-function (js2-inside-function))
8056 e ret name)
8057 (unless inside-function
8058 (js2-report-error (if (eq tt js2-RETURN)
8059 "msg.bad.return"
8060 "msg.bad.yield")))
8061 (js2-consume-token)
8062 ;; This is ugly, but we don't want to require a semicolon.
8063 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8064 (setq e (js2-parse-expr)
8065 end (js2-node-end e)))
8066 (cond
8067 ((eq tt js2-RETURN)
8068 (js2-set-flag js2-end-flags (if (null e)
8069 js2-end-returns
8070 js2-end-returns-value))
8071 (setq ret (make-js2-return-node :pos pos
8072 :len (- end pos)
8073 :retval e))
8074 (js2-node-add-children ret e)
8075 ;; See if we need a strict mode warning.
8076 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8077 ;; more thorough and accurate than this before/after flag check.
8078 ;; E.g. if there's a finally-block that always returns, we shouldn't
8079 ;; show a warning generated by inconsistent returns in the catch blocks.
8080 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8081 ;; so we know which returns/yields to highlight, and we should get rid of
8082 ;; all the checking in `js2-parse-return-or-yield'.
8083 (if (and js2-strict-inconsistent-return-warning
8084 (js2-now-all-set before js2-end-flags
8085 (logior js2-end-returns js2-end-returns-value)))
8086 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8087 (t
8088 (unless (js2-inside-function)
8089 (js2-report-error "msg.bad.yield"))
8090 (js2-set-flag js2-end-flags js2-end-yields)
8091 (setq ret (make-js2-yield-node :pos pos
8092 :len (- end pos)
8093 :value e))
8094 (js2-node-add-children ret e)
8095 (unless expr-context
8096 (setq e ret
8097 ret (js2-wrap-with-expr-stmt pos e t))
8098 (js2-set-requires-activation)
8099 (js2-set-is-generator))))
8100 ;; see if we are mixing yields and value returns.
8101 (when (and inside-function
8102 (js2-now-all-set before js2-end-flags
8103 (logior js2-end-yields js2-end-returns-value)))
8104 (setq name (js2-function-name js2-current-script-or-fn))
8105 (if (zerop (length name))
8106 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8107 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8108 ret))
8109
8110 (defun js2-parse-debugger ()
8111 (js2-consume-token)
8112 (make-js2-keyword-node :type js2-DEBUGGER))
8113
8114 (defun js2-parse-block ()
8115 "Parser for a curly-delimited statement block.
8116 Last token matched must be `js2-LC'."
8117 (let ((pos js2-token-beg)
8118 (pn (make-js2-scope)))
8119 (js2-consume-token)
8120 (js2-push-scope pn)
8121 (unwind-protect
8122 (progn
8123 (js2-parse-statements pn)
8124 (js2-must-match js2-RC "msg.no.brace.block")
8125 (setf (js2-node-len pn) (- js2-token-end pos)))
8126 (js2-pop-scope))
8127 pn))
8128
8129 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8130 (defun js2-parse-semi ()
8131 "Parse a statement or handle an error.
8132 Last matched token is `js2-SEMI' or `js2-ERROR'."
8133 (let ((tt (js2-peek-token)) pos len)
8134 (js2-consume-token)
8135 (if (eq tt js2-SEMI)
8136 (make-js2-empty-expr-node :len 1)
8137 (setq pos js2-token-beg
8138 len (- js2-token-beg pos))
8139 (js2-report-error "msg.syntax" nil pos len)
8140 (make-js2-error-node :pos pos :len len))))
8141
8142 (defun js2-parse-default-xml-namespace ()
8143 "Parse a `default xml namespace = <expr>' e4x statement."
8144 (let ((pos js2-token-beg)
8145 end len expr unary)
8146 (js2-consume-token)
8147 (js2-must-have-xml)
8148 (js2-set-requires-activation)
8149 (setq len (- js2-ts-cursor pos))
8150 (unless (and (js2-match-token js2-NAME)
8151 (string= js2-ts-string "xml"))
8152 (js2-report-error "msg.bad.namespace" nil pos len))
8153 (unless (and (js2-match-token js2-NAME)
8154 (string= js2-ts-string "namespace"))
8155 (js2-report-error "msg.bad.namespace" nil pos len))
8156 (unless (js2-match-token js2-ASSIGN)
8157 (js2-report-error "msg.bad.namespace" nil pos len))
8158 (setq expr (js2-parse-expr)
8159 end (js2-node-end expr)
8160 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8161 :pos pos
8162 :len (- end pos)
8163 :operand expr))
8164 (js2-node-add-children unary expr)
8165 (make-js2-expr-stmt-node :pos pos
8166 :len (- end pos)
8167 :expr unary)))
8168
8169 (defun js2-record-label (label bundle)
8170 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8171 (js2-consume-token)
8172 (let ((name (js2-label-node-name label))
8173 labeled-stmt
8174 dup)
8175 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8176 ;; flag both labels if possible when used in editing mode
8177 (if (and js2-parse-ide-mode
8178 (setq dup (js2-get-label-by-name labeled-stmt name)))
8179 (js2-report-error "msg.dup.label" nil
8180 (js2-node-abs-pos dup) (js2-node-len dup)))
8181 (js2-report-error "msg.dup.label" nil
8182 (js2-node-pos label) (js2-node-len label)))
8183 (js2-labeled-stmt-node-add-label bundle label)
8184 (js2-node-add-children bundle label)
8185 ;; Add one reference to the bundle per label in `js2-label-set'
8186 (push (cons name bundle) js2-label-set)))
8187
8188 (defun js2-parse-name-or-label ()
8189 "Parser for identifier or label. Last token matched must be js2-NAME.
8190 Called when we found a name in a statement context. If it's a label, we gather
8191 up any following labels and the next non-label statement into a
8192 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8193 expression and return it wrapped in a `js2-expr-stmt-node'."
8194 (let ((pos js2-token-beg)
8195 expr stmt pn bundle
8196 (continue t))
8197 ;; set check for label and call down to `js2-parse-primary-expr'
8198 (js2-set-check-for-label)
8199 (setq expr (js2-parse-expr))
8200 (if (/= (js2-node-type expr) js2-LABEL)
8201 ;; Parsed non-label expression - wrap with expression stmt.
8202 (setq pn (js2-wrap-with-expr-stmt pos expr t)) ;FIXME: `pn' is unused!
8203 ;; else parsed a label
8204 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8205 (js2-record-label expr bundle)
8206 ;; look for more labels
8207 (while (and continue (= (js2-peek-token) js2-NAME))
8208 (js2-set-check-for-label)
8209 (setq expr (js2-parse-expr))
8210 (if (/= (js2-node-type expr) js2-LABEL)
8211 (progn
8212 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8213 continue nil)
8214 (js2-auto-insert-semicolon stmt))
8215 (js2-record-label expr bundle)))
8216 ;; no more labels; now parse the labeled statement
8217 (unwind-protect
8218 (unless stmt
8219 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8220 (setq stmt (js2-statement-helper))))
8221 ;; remove the labels for this statement from the global set
8222 (dolist (label (js2-labeled-stmt-node-labels bundle))
8223 (setq js2-label-set (remove label js2-label-set))))
8224 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8225 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8226 (js2-node-add-children bundle stmt)
8227 bundle)))
8228
8229 (defun js2-parse-expr-stmt ()
8230 "Default parser in statement context, if no recognized statement found."
8231 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8232
8233 (defun js2-parse-variables (decl-type pos)
8234 "Parse a comma-separated list of variable declarations.
8235 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8236
8237 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8238 For 'var' or 'const', the keyword should be the token last scanned.
8239
8240 POS is the position where the node should start. It's sometimes the
8241 var/const/let keyword, and other times the beginning of the first token
8242 in the first variable declaration.
8243
8244 Returns the parsed `js2-var-decl-node' expression node."
8245 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8246 :pos pos))
8247 destructuring kid-pos tt init name end nbeg nend vi
8248 (continue t))
8249 ;; Example:
8250 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8251 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8252 ;; var {a, b} = baz;
8253 (while continue
8254 (setq destructuring nil
8255 name nil
8256 tt (js2-peek-token)
8257 kid-pos js2-token-beg
8258 end js2-token-end
8259 init nil)
8260 (if (or (= tt js2-LB) (= tt js2-LC))
8261 ;; Destructuring assignment, e.g., var [a, b] = ...
8262 (setq destructuring (js2-parse-destruct-primary-expr)
8263 end (js2-node-end destructuring))
8264 ;; Simple variable name
8265 (when (js2-must-match js2-NAME "msg.bad.var")
8266 (setq name (js2-create-name-node)
8267 nbeg js2-token-beg
8268 nend js2-token-end
8269 end nend)
8270 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8271 (when (js2-match-token js2-ASSIGN)
8272 (setq init (js2-parse-assign-expr)
8273 end (js2-node-end init))
8274 (js2-record-imenu-functions init name))
8275 (when name
8276 (js2-set-face nbeg nend (if (js2-function-node-p init)
8277 'font-lock-function-name-face
8278 'font-lock-variable-name-face)
8279 'record))
8280 (setq vi (make-js2-var-init-node :pos kid-pos
8281 :len (- end kid-pos)
8282 :type decl-type))
8283 (if destructuring
8284 (progn
8285 (if (and (null init) (not js2-in-for-init))
8286 (js2-report-error "msg.destruct.assign.no.init"))
8287 (js2-define-destruct-symbols destructuring
8288 decl-type
8289 'font-lock-variable-name-face)
8290 (setf (js2-var-init-node-target vi) destructuring))
8291 (setf (js2-var-init-node-target vi) name))
8292 (setf (js2-var-init-node-initializer vi) init)
8293 (js2-node-add-children vi name destructuring init)
8294 (js2-block-node-push result vi)
8295 (unless (js2-match-token js2-COMMA)
8296 (setq continue nil)))
8297 (setf (js2-node-len result) (- end pos))
8298 result))
8299
8300 (defun js2-parse-let (pos &optional stmt-p)
8301 "Parse a let expression or statement.
8302 A let-expression is of the form `let (vars) expr'.
8303 A let-statment is of the form `let (vars) {statements}'.
8304 The third form of let is a variable declaration list, handled
8305 by `js2-parse-variables'."
8306 (let ((pn (make-js2-let-node :pos pos))
8307 beg vars body)
8308 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8309 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8310 (js2-push-scope pn)
8311 (unwind-protect
8312 (progn
8313 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8314 (if (js2-must-match js2-RP "msg.no.paren.let")
8315 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8316 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8317 ;; let statement
8318 (progn
8319 (js2-consume-token)
8320 (setf beg js2-token-beg ; position stmt at LC
8321 body (js2-parse-statements))
8322 (js2-must-match js2-RC "msg.no.curly.let")
8323 (setf (js2-node-len body) (- js2-token-end beg)
8324 (js2-node-len pn) (- js2-token-end pos)
8325 (js2-let-node-body pn) body
8326 (js2-node-type pn) js2-LET))
8327 ;; let expression
8328 (setf body (js2-parse-expr)
8329 (js2-node-len pn) (- (js2-node-end body) pos)
8330 (js2-let-node-body pn) body))
8331 (js2-node-add-children pn vars body))
8332 (js2-pop-scope))
8333 pn))
8334
8335 (defun js2-define-new-symbol (decl-type name node &optional scope)
8336 (js2-scope-put-symbol (or scope js2-current-scope)
8337 name
8338 (make-js2-symbol decl-type name node)))
8339
8340 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8341 "Define a symbol in the current scope.
8342 If NODE is non-nil, it is the AST node associated with the symbol."
8343 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8344 (symbol (if defining-scope
8345 (js2-scope-get-symbol defining-scope name)))
8346 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8347 (cond
8348 ((and symbol ; already defined
8349 (or (= sdt js2-CONST) ; old version is const
8350 (= decl-type js2-CONST) ; new version is const
8351 ;; two let-bound vars in this block have same name
8352 (and (= sdt js2-LET)
8353 (eq defining-scope js2-current-scope))))
8354 (js2-report-error
8355 (cond
8356 ((= sdt js2-CONST) "msg.const.redecl")
8357 ((= sdt js2-LET) "msg.let.redecl")
8358 ((= sdt js2-VAR) "msg.var.redecl")
8359 ((= sdt js2-FUNCTION) "msg.function.redecl")
8360 (t "msg.parm.redecl"))
8361 name))
8362 ((= decl-type js2-LET)
8363 (if (and (not ignore-not-in-block)
8364 (or (= (js2-node-type js2-current-scope) js2-IF)
8365 (js2-loop-node-p js2-current-scope)))
8366 (js2-report-error "msg.let.decl.not.in.block")
8367 (js2-define-new-symbol decl-type name node)))
8368 ((or (= decl-type js2-VAR)
8369 (= decl-type js2-CONST)
8370 (= decl-type js2-FUNCTION))
8371 (if symbol
8372 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8373 (js2-add-strict-warning "msg.var.redecl" name)
8374 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8375 (js2-add-strict-warning "msg.var.hides.arg" name)))
8376 (js2-define-new-symbol decl-type name node
8377 js2-current-script-or-fn)))
8378 ((= decl-type js2-LP)
8379 (if symbol
8380 ;; must be duplicate parameter. Second parameter hides the
8381 ;; first, so go ahead and add the second pararameter
8382 (js2-report-warning "msg.dup.parms" name))
8383 (js2-define-new-symbol decl-type name node))
8384 (t (js2-code-bug)))))
8385
8386 (defun js2-parse-expr (&optional oneshot)
8387 (let* ((pn (js2-parse-assign-expr))
8388 (pos (js2-node-pos pn))
8389 left
8390 right
8391 op-pos)
8392 (while (and (not oneshot)
8393 (js2-match-token js2-COMMA))
8394 (setq op-pos (- js2-token-beg pos)) ; relative
8395 (if (= (js2-peek-token) js2-YIELD)
8396 (js2-report-error "msg.yield.parenthesized"))
8397 (setq right (js2-parse-assign-expr)
8398 left pn
8399 pn (make-js2-infix-node :type js2-COMMA
8400 :pos pos
8401 :len (- js2-ts-cursor pos)
8402 :op-pos op-pos
8403 :left left
8404 :right right))
8405 (js2-node-add-children pn left right))
8406 pn))
8407
8408 (defun js2-parse-assign-expr ()
8409 (let ((tt (js2-peek-token))
8410 (pos js2-token-beg)
8411 pn left right op-pos)
8412 (if (= tt js2-YIELD)
8413 (js2-parse-return-or-yield tt t)
8414 ;; not yield - parse assignment expression
8415 (setq pn (js2-parse-cond-expr)
8416 tt (js2-peek-token))
8417 (when (and (<= js2-first-assign tt)
8418 (<= tt js2-last-assign))
8419 ;; tt express assignment (=, |=, ^=, ..., %=)
8420 (js2-consume-token)
8421 (setq op-pos (- js2-token-beg pos) ; relative
8422 left pn
8423 right (js2-parse-assign-expr)
8424 pn (make-js2-assign-node :type tt
8425 :pos pos
8426 :len (- (js2-node-end right) pos)
8427 :op-pos op-pos
8428 :left left
8429 :right right))
8430 (when js2-parse-ide-mode
8431 (js2-highlight-assign-targets pn left right)
8432 (js2-record-imenu-functions right left))
8433 ;; do this last so ide checks above can use absolute positions
8434 (js2-node-add-children pn left right))
8435 pn)))
8436
8437 (defun js2-parse-cond-expr ()
8438 (let ((pos js2-token-beg)
8439 (pn (js2-parse-or-expr))
8440 test-expr
8441 if-true
8442 if-false
8443 q-pos
8444 c-pos)
8445 (when (js2-match-token js2-HOOK)
8446 (setq q-pos (- js2-token-beg pos)
8447 if-true (js2-parse-assign-expr))
8448 (js2-must-match js2-COLON "msg.no.colon.cond")
8449 (setq c-pos (- js2-token-beg pos)
8450 if-false (js2-parse-assign-expr)
8451 test-expr pn
8452 pn (make-js2-cond-node :pos pos
8453 :len (- (js2-node-end if-false) pos)
8454 :test-expr test-expr
8455 :true-expr if-true
8456 :false-expr if-false
8457 :q-pos q-pos
8458 :c-pos c-pos))
8459 (js2-node-add-children pn test-expr if-true if-false))
8460 pn))
8461
8462 (defun js2-make-binary (type left parser)
8463 "Helper for constructing a binary-operator AST node.
8464 LEFT is the left-side-expression, already parsed, and the
8465 binary operator should have just been matched.
8466 PARSER is a function to call to parse the right operand,
8467 or a `js2-node' struct if it has already been parsed."
8468 (let* ((pos (js2-node-pos left))
8469 (op-pos (- js2-token-beg pos))
8470 (right (if (js2-node-p parser)
8471 parser
8472 (funcall parser)))
8473 (pn (make-js2-infix-node :type type
8474 :pos pos
8475 :len (- (js2-node-end right) pos)
8476 :op-pos op-pos
8477 :left left
8478 :right right)))
8479 (js2-node-add-children pn left right)
8480 pn))
8481
8482 (defun js2-parse-or-expr ()
8483 (let ((pn (js2-parse-and-expr)))
8484 (when (js2-match-token js2-OR)
8485 (setq pn (js2-make-binary js2-OR
8486 pn
8487 'js2-parse-or-expr)))
8488 pn))
8489
8490 (defun js2-parse-and-expr ()
8491 (let ((pn (js2-parse-bit-or-expr)))
8492 (when (js2-match-token js2-AND)
8493 (setq pn (js2-make-binary js2-AND
8494 pn
8495 'js2-parse-and-expr)))
8496 pn))
8497
8498 (defun js2-parse-bit-or-expr ()
8499 (let ((pn (js2-parse-bit-xor-expr)))
8500 (while (js2-match-token js2-BITOR)
8501 (setq pn (js2-make-binary js2-BITOR
8502 pn
8503 'js2-parse-bit-xor-expr)))
8504 pn))
8505
8506 (defun js2-parse-bit-xor-expr ()
8507 (let ((pn (js2-parse-bit-and-expr)))
8508 (while (js2-match-token js2-BITXOR)
8509 (setq pn (js2-make-binary js2-BITXOR
8510 pn
8511 'js2-parse-bit-and-expr)))
8512 pn))
8513
8514 (defun js2-parse-bit-and-expr ()
8515 (let ((pn (js2-parse-eq-expr)))
8516 (while (js2-match-token js2-BITAND)
8517 (setq pn (js2-make-binary js2-BITAND
8518 pn
8519 'js2-parse-eq-expr)))
8520 pn))
8521
8522 (defconst js2-parse-eq-ops
8523 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8524
8525 (defun js2-parse-eq-expr ()
8526 (let ((pn (js2-parse-rel-expr))
8527 tt)
8528 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8529 (js2-consume-token)
8530 (setq pn (js2-make-binary tt
8531 pn
8532 'js2-parse-rel-expr)))
8533 pn))
8534
8535 (defconst js2-parse-rel-ops
8536 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8537
8538 (defun js2-parse-rel-expr ()
8539 (let ((pn (js2-parse-shift-expr))
8540 (continue t)
8541 tt)
8542 (while continue
8543 (setq tt (js2-peek-token))
8544 (cond
8545 ((and js2-in-for-init (= tt js2-IN))
8546 (setq continue nil))
8547 ((memq tt js2-parse-rel-ops)
8548 (js2-consume-token)
8549 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8550 (t
8551 (setq continue nil))))
8552 pn))
8553
8554 (defconst js2-parse-shift-ops
8555 (list js2-LSH js2-URSH js2-RSH))
8556
8557 (defun js2-parse-shift-expr ()
8558 (let ((pn (js2-parse-add-expr))
8559 tt
8560 (continue t))
8561 (while continue
8562 (setq tt (js2-peek-token))
8563 (if (memq tt js2-parse-shift-ops)
8564 (progn
8565 (js2-consume-token)
8566 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8567 (setq continue nil)))
8568 pn))
8569
8570 (defun js2-parse-add-expr ()
8571 (let ((pn (js2-parse-mul-expr))
8572 tt
8573 (continue t))
8574 (while continue
8575 (setq tt (js2-peek-token))
8576 (if (or (= tt js2-ADD) (= tt js2-SUB))
8577 (progn
8578 (js2-consume-token)
8579 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8580 (setq continue nil)))
8581 pn))
8582
8583 (defconst js2-parse-mul-ops
8584 (list js2-MUL js2-DIV js2-MOD))
8585
8586 (defun js2-parse-mul-expr ()
8587 (let ((pn (js2-parse-unary-expr))
8588 tt
8589 (continue t))
8590 (while continue
8591 (setq tt (js2-peek-token))
8592 (if (memq tt js2-parse-mul-ops)
8593 (progn
8594 (js2-consume-token)
8595 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8596 (setq continue nil)))
8597 pn))
8598
8599 (defun js2-make-unary (type parser &rest args)
8600 "Make a unary node of type TYPE.
8601 PARSER is either a node (for postfix operators) or a function to call
8602 to parse the operand (for prefix operators)."
8603 (let* ((pos js2-token-beg)
8604 (postfix (js2-node-p parser))
8605 (expr (if postfix
8606 parser
8607 (apply parser args)))
8608 end
8609 pn)
8610 (if postfix ; e.g. i++
8611 (setq pos (js2-node-pos expr)
8612 end js2-token-end)
8613 (setq end (js2-node-end expr)))
8614 (setq pn (make-js2-unary-node :type type
8615 :pos pos
8616 :len (- end pos)
8617 :operand expr))
8618 (js2-node-add-children pn expr)
8619 pn))
8620
8621 (defconst js2-incrementable-node-types
8622 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8623 "Node types that can be the operand of a ++ or -- operator.")
8624
8625 (defun js2-check-bad-inc-dec (tt beg end unary)
8626 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8627 js2-incrementable-node-types)
8628 (js2-report-error (if (= tt js2-INC)
8629 "msg.bad.incr"
8630 "msg.bad.decr")
8631 nil beg (- end beg))))
8632
8633 (defun js2-parse-unary-expr ()
8634 (let ((tt (js2-peek-token))
8635 pn expr beg end)
8636 (cond
8637 ((or (= tt js2-VOID)
8638 (= tt js2-NOT)
8639 (= tt js2-BITNOT)
8640 (= tt js2-TYPEOF))
8641 (js2-consume-token)
8642 (js2-make-unary tt 'js2-parse-unary-expr))
8643 ((= tt js2-ADD)
8644 (js2-consume-token)
8645 ;; Convert to special POS token in decompiler and parse tree
8646 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8647 ((= tt js2-SUB)
8648 (js2-consume-token)
8649 ;; Convert to special NEG token in decompiler and parse tree
8650 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8651 ((or (= tt js2-INC)
8652 (= tt js2-DEC))
8653 (js2-consume-token)
8654 (prog1
8655 (setq beg js2-token-beg
8656 end js2-token-end
8657 expr (js2-make-unary tt 'js2-parse-member-expr t))
8658 (js2-check-bad-inc-dec tt beg end expr)))
8659 ((= tt js2-DELPROP)
8660 (js2-consume-token)
8661 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8662 ((= tt js2-ERROR)
8663 (js2-consume-token)
8664 (make-js2-error-node)) ; try to continue
8665 ((and (= tt js2-LT)
8666 js2-compiler-xml-available)
8667 ;; XML stream encountered in expression.
8668 (js2-consume-token)
8669 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8670 (t
8671 (setq pn (js2-parse-member-expr t)
8672 ;; Don't look across a newline boundary for a postfix incop.
8673 tt (js2-peek-token-or-eol))
8674 (when (or (= tt js2-INC) (= tt js2-DEC))
8675 (js2-consume-token)
8676 (setf expr pn
8677 pn (js2-make-unary tt expr))
8678 (js2-node-set-prop pn 'postfix t)
8679 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8680 pn))))
8681
8682 (defun js2-parse-xml-initializer ()
8683 "Parse an E4X XML initializer.
8684 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8685 Then I'll postprocess the result, depending on whether we're in IDE
8686 mode or codegen mode, and generate the appropriate rewritten AST.
8687 IDE mode uses a rich AST that models the XML structure. Codegen mode
8688 just concatenates everything and makes a new XML or XMLList out of it."
8689 (let ((tt (js2-get-first-xml-token))
8690 pn-xml pn expr kids expr-pos
8691 (continue t)
8692 (first-token t))
8693 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8694 (js2-report-error "msg.syntax"))
8695 (setq pn-xml (make-js2-xml-node))
8696 (while continue
8697 (if first-token
8698 (setq first-token nil)
8699 (setq tt (js2-get-next-xml-token)))
8700 (cond
8701 ;; js2-XML means we found a {expr} in the XML stream.
8702 ;; The js2-ts-string is the XML up to the left-curly.
8703 ((= tt js2-XML)
8704 (push (make-js2-string-node :pos js2-token-beg
8705 :len (- js2-ts-cursor js2-token-beg))
8706 kids)
8707 (js2-must-match js2-LC "msg.syntax")
8708 (setq expr-pos js2-ts-cursor
8709 expr (if (eq (js2-peek-token) js2-RC)
8710 (make-js2-empty-expr-node :pos expr-pos)
8711 (js2-parse-expr)))
8712 (js2-must-match js2-RC "msg.syntax")
8713 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8714 :len (js2-node-len expr)
8715 :expr expr))
8716 (js2-node-add-children pn expr)
8717 (push pn kids))
8718 ;; a js2-XMLEND token means we hit the final close-tag.
8719 ((= tt js2-XMLEND)
8720 (push (make-js2-string-node :pos js2-token-beg
8721 :len (- js2-ts-cursor js2-token-beg))
8722 kids)
8723 (dolist (kid (nreverse kids))
8724 (js2-block-node-push pn-xml kid))
8725 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8726 (js2-node-pos pn-xml))
8727 continue nil))
8728 (t
8729 (js2-report-error "msg.syntax")
8730 (setq continue nil))))
8731 pn-xml))
8732
8733
8734 (defun js2-parse-argument-list ()
8735 "Parse an argument list and return it as a Lisp list of nodes.
8736 Returns the list in reverse order. Consumes the right-paren token."
8737 (let (result)
8738 (unless (js2-match-token js2-RP)
8739 (loop do
8740 (if (= (js2-peek-token) js2-YIELD)
8741 (js2-report-error "msg.yield.parenthesized"))
8742 (push (js2-parse-assign-expr) result)
8743 while
8744 (js2-match-token js2-COMMA))
8745 (js2-must-match js2-RP "msg.no.paren.arg")
8746 result)))
8747
8748 (defun js2-parse-member-expr (&optional allow-call-syntax)
8749 (let ((tt (js2-peek-token))
8750 pn pos target args beg end init)
8751 (if (/= tt js2-NEW)
8752 (setq pn (js2-parse-primary-expr))
8753 ;; parse a 'new' expression
8754 (js2-consume-token)
8755 (setq pos js2-token-beg
8756 beg pos
8757 target (js2-parse-member-expr)
8758 end (js2-node-end target)
8759 pn (make-js2-new-node :pos pos
8760 :target target
8761 :len (- end pos)))
8762 (js2-node-add-children pn target)
8763 (when (js2-match-token js2-LP)
8764 ;; Add the arguments to pn, if any are supplied.
8765 (setf beg pos ; start of "new" keyword
8766 pos js2-token-beg
8767 args (nreverse (js2-parse-argument-list))
8768 (js2-new-node-args pn) args
8769 end js2-token-end
8770 (js2-new-node-lp pn) (- pos beg)
8771 (js2-new-node-rp pn) (- end 1 beg))
8772 (apply #'js2-node-add-children pn args))
8773 (when (and js2-allow-rhino-new-expr-initializer
8774 (js2-match-token js2-LC))
8775 (setf init (js2-parse-object-literal)
8776 end (js2-node-end init)
8777 (js2-new-node-initializer pn) init)
8778 (js2-node-add-children pn init))
8779 (setf (js2-node-len pn) (- end beg))) ; end outer if
8780 (js2-parse-member-expr-tail allow-call-syntax pn)))
8781
8782 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8783 "Parse a chain of property/array accesses or function calls.
8784 Includes parsing for E4X operators like `..' and `.@'.
8785 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8786 Returns an expression tree that includes PN, the parent node."
8787 (let (tt
8788 (continue t))
8789 (while continue
8790 (setq tt (js2-peek-token))
8791 (cond
8792 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8793 (setq pn (js2-parse-property-access tt pn)))
8794 ((= tt js2-DOTQUERY)
8795 (setq pn (js2-parse-dot-query pn)))
8796 ((= tt js2-LB)
8797 (setq pn (js2-parse-element-get pn)))
8798 ((= tt js2-LP)
8799 (if allow-call-syntax
8800 (setq pn (js2-parse-function-call pn))
8801 (setq continue nil)))
8802 (t
8803 (setq continue nil))))
8804 (if (>= js2-highlight-level 2)
8805 (js2-parse-highlight-member-expr-node pn))
8806 pn))
8807
8808 (defun js2-parse-dot-query (pn)
8809 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8810 Last token parsed must be `js2-DOTQUERY'."
8811 (let ((pos (js2-node-pos pn))
8812 op-pos expr end)
8813 (js2-consume-token)
8814 (js2-must-have-xml)
8815 (js2-set-requires-activation)
8816 (setq op-pos js2-token-beg
8817 expr (js2-parse-expr)
8818 end (js2-node-end expr)
8819 pn (make-js2-xml-dot-query-node :left pn
8820 :pos pos
8821 :op-pos op-pos
8822 :right expr))
8823 (js2-node-add-children pn
8824 (js2-xml-dot-query-node-left pn)
8825 (js2-xml-dot-query-node-right pn))
8826 (if (js2-must-match js2-RP "msg.no.paren")
8827 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8828 end js2-token-end))
8829 (setf (js2-node-len pn) (- end pos))
8830 pn))
8831
8832 (defun js2-parse-element-get (pn)
8833 "Parse an element-get expression, e.g. foo[bar].
8834 Last token parsed must be `js2-RB'."
8835 (let ((lb js2-token-beg)
8836 (pos (js2-node-pos pn))
8837 rb expr)
8838 (js2-consume-token)
8839 (setq expr (js2-parse-expr))
8840 (if (js2-must-match js2-RB "msg.no.bracket.index")
8841 (setq rb js2-token-beg))
8842 (setq pn (make-js2-elem-get-node :target pn
8843 :pos pos
8844 :element expr
8845 :lb (js2-relpos lb pos)
8846 :rb (js2-relpos rb pos)
8847 :len (- js2-token-end pos)))
8848 (js2-node-add-children pn
8849 (js2-elem-get-node-target pn)
8850 (js2-elem-get-node-element pn))
8851 pn))
8852
8853 (defun js2-parse-function-call (pn)
8854 (let (args
8855 (pos (js2-node-pos pn)))
8856 (js2-consume-token)
8857 (setq pn (make-js2-call-node :pos pos
8858 :target pn
8859 :lp (- js2-token-beg pos)))
8860 (js2-node-add-children pn (js2-call-node-target pn))
8861 ;; Add the arguments to pn, if any are supplied.
8862 (setf args (nreverse (js2-parse-argument-list))
8863 (js2-call-node-rp pn) (- js2-token-beg pos)
8864 (js2-call-node-args pn) args)
8865 (apply #'js2-node-add-children pn args)
8866 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8867 pn))
8868
8869 (defun js2-parse-property-access (tt pn)
8870 "Parse a property access, XML descendants access, or XML attr access."
8871 (let ((member-type-flags 0)
8872 (dot-pos js2-token-beg)
8873 (dot-len (if (= tt js2-DOTDOT) 2 1))
8874 name
8875 ref ; right side of . or .. operator
8876 result)
8877 (js2-consume-token)
8878 (when (= tt js2-DOTDOT)
8879 (js2-must-have-xml)
8880 (setq member-type-flags js2-descendants-flag))
8881 (if (not js2-compiler-xml-available)
8882 (progn
8883 (js2-must-match-prop-name "msg.no.name.after.dot")
8884 (setq name (js2-create-name-node t js2-GETPROP)
8885 result (make-js2-prop-get-node :left pn
8886 :pos js2-token-beg
8887 :right name
8888 :len (- js2-token-end
8889 js2-token-beg)))
8890 (js2-node-add-children result pn name)
8891 result)
8892 ;; otherwise look for XML operators
8893 (setf result (if (= tt js2-DOT)
8894 (make-js2-prop-get-node)
8895 (make-js2-infix-node :type js2-DOTDOT))
8896 (js2-node-pos result) (js2-node-pos pn)
8897 (js2-infix-node-op-pos result) dot-pos
8898 (js2-infix-node-left result) pn ; do this after setting position
8899 tt (js2-next-token))
8900 (cond
8901 ;; needed for generator.throw()
8902 ((= tt js2-THROW)
8903 (js2-save-name-token-data js2-token-beg "throw")
8904 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8905 ;; handles: name, ns::name, ns::*, ns::[expr]
8906 ((js2-valid-prop-name-token tt)
8907 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8908 ;; handles: *, *::name, *::*, *::[expr]
8909 ((= tt js2-MUL)
8910 (js2-save-name-token-data js2-token-beg "*")
8911 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8912 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8913 ((= tt js2-XMLATTR)
8914 (setq result (js2-parse-attribute-access)))
8915 (t
8916 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8917 (if ref
8918 (setf (js2-node-len result) (- (js2-node-end ref)
8919 (js2-node-pos result))
8920 (js2-infix-node-right result) ref))
8921 (if (js2-infix-node-p result)
8922 (js2-node-add-children result
8923 (js2-infix-node-left result)
8924 (js2-infix-node-right result)))
8925 result)))
8926
8927 (defun js2-parse-attribute-access ()
8928 "Parse an E4X XML attribute expression.
8929 This includes expressions of the forms:
8930
8931 @attr @ns::attr @ns::*
8932 @* @*::attr @*::*
8933 @[expr] @*::[expr] @ns::[expr]
8934
8935 Called if we peeked an '@' token."
8936 (let ((tt (js2-next-token))
8937 (at-pos js2-token-beg))
8938 (cond
8939 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8940 ((js2-valid-prop-name-token tt)
8941 (js2-parse-property-name at-pos js2-ts-string 0))
8942 ;; handles: @*, @*::name, @*::*, @*::[expr]
8943 ((= tt js2-MUL)
8944 (js2-save-name-token-data js2-token-beg "*")
8945 (js2-parse-property-name js2-token-beg "*" 0))
8946 ;; handles @[expr]
8947 ((= tt js2-LB)
8948 (js2-parse-xml-elem-ref at-pos))
8949 (t
8950 (js2-report-error "msg.no.name.after.xmlAttr")
8951 ;; Avoid cascaded errors that happen if we make an error node here.
8952 (js2-save-name-token-data js2-token-beg "")
8953 (js2-parse-property-name js2-token-beg "" 0)))))
8954
8955 (defun js2-parse-property-name (at-pos _s member-type-flags)
8956 "Check if :: follows name in which case it becomes qualified name.
8957
8958 AT-POS is a natural number if we just read an '@' token, else nil.
8959 S is the name or string that was matched: an identifier, 'throw' or '*'.
8960 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8961
8962 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8963 operator, or the name is followed by ::. For a plain name, returns a
8964 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8965 (let ((pos (or at-pos js2-token-beg))
8966 colon-pos
8967 (name (js2-create-name-node t js2-current-token))
8968 ns tt pn)
8969 (catch 'return
8970 (when (js2-match-token js2-COLONCOLON)
8971 (setq ns name
8972 colon-pos js2-token-beg
8973 tt (js2-next-token))
8974 (cond
8975 ;; handles name::name
8976 ((js2-valid-prop-name-token tt)
8977 (setq name (js2-create-name-node)))
8978 ;; handles name::*
8979 ((= tt js2-MUL)
8980 (js2-save-name-token-data js2-token-beg "*")
8981 (setq name (js2-create-name-node)))
8982 ;; handles name::[expr]
8983 ((= tt js2-LB)
8984 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8985 (t
8986 (js2-report-error "msg.no.name.after.coloncolon"))))
8987 (if (and (null ns) (zerop member-type-flags))
8988 name
8989 (prog1
8990 (setq pn
8991 (make-js2-xml-prop-ref-node :pos pos
8992 :len (- (js2-node-end name) pos)
8993 :at-pos at-pos
8994 :colon-pos colon-pos
8995 :propname name))
8996 (js2-node-add-children pn name))))))
8997
8998 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8999 "Parse the [expr] portion of an xml element reference.
9000 For instance, @[expr], @*::[expr], or ns::[expr]."
9001 (let* ((lb js2-token-beg)
9002 (pos (or at-pos lb))
9003 rb
9004 (expr (js2-parse-expr))
9005 (end (js2-node-end expr))
9006 pn)
9007 (if (js2-must-match js2-RB "msg.no.bracket.index")
9008 (setq rb js2-token-beg
9009 end js2-token-end))
9010 (prog1
9011 (setq pn
9012 (make-js2-xml-elem-ref-node :pos pos
9013 :len (- end pos)
9014 :namespace namespace
9015 :colon-pos colon-pos
9016 :at-pos at-pos
9017 :expr expr
9018 :lb (js2-relpos lb pos)
9019 :rb (js2-relpos rb pos)))
9020 (js2-node-add-children pn namespace expr))))
9021
9022 (defun js2-parse-destruct-primary-expr ()
9023 (let ((js2-is-in-destructuring t))
9024 (js2-parse-primary-expr)))
9025
9026 (defun js2-parse-primary-expr ()
9027 "Parse a literal (leaf) expression of some sort.
9028 Includes complex literals such as functions, object-literals,
9029 array-literals, array comprehensions and regular expressions."
9030 (let ((tt-flagged (js2-next-flagged-token))
9031 pn ; parent node (usually return value)
9032 tt
9033 px-pos ; paren-expr pos
9034 len
9035 flags ; regexp flags
9036 expr)
9037 (setq tt js2-current-token)
9038 (cond
9039 ((= tt js2-FUNCTION)
9040 (js2-parse-function 'FUNCTION_EXPRESSION))
9041 ((= tt js2-LB)
9042 (js2-parse-array-literal))
9043 ((= tt js2-LC)
9044 (js2-parse-object-literal))
9045 ((= tt js2-LET)
9046 (js2-parse-let js2-token-beg))
9047 ((= tt js2-LP)
9048 (setq px-pos js2-token-beg
9049 expr (js2-parse-expr))
9050 (js2-must-match js2-RP "msg.no.paren")
9051 (setq pn (make-js2-paren-node :pos px-pos
9052 :expr expr
9053 :len (- js2-token-end px-pos)))
9054 (js2-node-add-children pn (js2-paren-node-expr pn))
9055 pn)
9056 ((= tt js2-XMLATTR)
9057 (js2-must-have-xml)
9058 (js2-parse-attribute-access))
9059 ((= tt js2-NAME)
9060 (js2-parse-name tt-flagged tt))
9061 ((= tt js2-NUMBER)
9062 (make-js2-number-node))
9063 ((= tt js2-STRING)
9064 (prog1
9065 (make-js2-string-node)
9066 (js2-record-face 'font-lock-string-face)))
9067 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9068 ;; Got / or /= which in this context means a regexp literal
9069 (setq px-pos js2-token-beg)
9070 (js2-read-regexp tt)
9071 (setq flags js2-ts-regexp-flags
9072 js2-ts-regexp-flags nil)
9073 (prog1
9074 (make-js2-regexp-node :pos px-pos
9075 :len (- js2-ts-cursor px-pos)
9076 :value js2-ts-string
9077 :flags flags)
9078 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9079 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9080 ((or (= tt js2-NULL)
9081 (= tt js2-THIS)
9082 (= tt js2-FALSE)
9083 (= tt js2-TRUE))
9084 (make-js2-keyword-node :type tt))
9085 ((= tt js2-RESERVED)
9086 (js2-report-error "msg.reserved.id")
9087 (make-js2-name-node))
9088 ((= tt js2-ERROR)
9089 ;; the scanner or one of its subroutines reported the error.
9090 (make-js2-error-node))
9091 ((= tt js2-EOF)
9092 (setq px-pos (point-at-bol)
9093 len (- js2-ts-cursor px-pos))
9094 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9095 (make-js2-error-node :pos px-pos :len len))
9096 (t
9097 (js2-report-error "msg.syntax")
9098 (make-js2-error-node)))))
9099
9100 (defun js2-parse-name (tt-flagged _tt)
9101 (let ((name js2-ts-string)
9102 (name-pos js2-token-beg)
9103 node)
9104 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9105 (= (js2-peek-token) js2-COLON))
9106 (prog1
9107 ;; Do not consume colon, it is used as unwind indicator
9108 ;; to return to statementHelper.
9109 (make-js2-label-node :pos name-pos
9110 :len (- js2-token-end name-pos)
9111 :name name)
9112 (js2-set-face name-pos
9113 js2-token-end
9114 'font-lock-variable-name-face 'record))
9115 ;; Otherwise not a label, just a name. Unfortunately peeking
9116 ;; the next token to check for a colon has biffed js2-token-beg
9117 ;; and js2-token-end. We store the name's bounds in buffer vars
9118 ;; and `js2-create-name-node' uses them.
9119 (js2-save-name-token-data name-pos name)
9120 (setq node (if js2-compiler-xml-available
9121 (js2-parse-property-name nil name 0)
9122 (js2-create-name-node 'check-activation)))
9123 (if js2-highlight-external-variables
9124 (js2-record-name-node node))
9125 node)))
9126
9127 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9128 (js2-add-strict-warning
9129 msg nil
9130 ;; back up from comma to beginning of line or array/objlit
9131 (max (if elems
9132 (js2-node-pos (car elems))
9133 pos)
9134 (save-excursion
9135 (goto-char comma-pos)
9136 (back-to-indentation)
9137 (point)))
9138 comma-pos))
9139
9140 (defun js2-parse-array-literal ()
9141 (let ((pos js2-token-beg)
9142 (after-lb-or-comma t)
9143 after-comma tt elems pn
9144 (continue t))
9145 (unless js2-is-in-destructuring
9146 (js2-push-scope (make-js2-scope))) ; for array comp
9147 (while continue
9148 (setq tt (js2-peek-token))
9149 (cond
9150 ;; comma
9151 ((= tt js2-COMMA)
9152 (js2-consume-token)
9153 (setq after-comma js2-token-end)
9154 (if (not after-lb-or-comma)
9155 (setq after-lb-or-comma t)
9156 (push nil elems)))
9157 ;; end of array
9158 ((or (= tt js2-RB)
9159 (= tt js2-EOF)) ; prevent infinite loop
9160 (if (= tt js2-EOF)
9161 (js2-report-error "msg.no.bracket.arg" nil pos)
9162 (js2-consume-token))
9163 (setq continue nil
9164 pn (make-js2-array-node :pos pos
9165 :len (- js2-ts-cursor pos)
9166 :elems (nreverse elems)))
9167 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9168 (when (and after-comma (not js2-is-in-destructuring))
9169 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9170 pos elems after-comma)))
9171 ;; destructuring binding
9172 (js2-is-in-destructuring
9173 (push (if (or (= tt js2-LC)
9174 (= tt js2-LB)
9175 (= tt js2-NAME))
9176 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9177 (js2-parse-destruct-primary-expr)
9178 ;; invalid pattern
9179 (js2-consume-token)
9180 (js2-report-error "msg.bad.var")
9181 (make-js2-error-node))
9182 elems)
9183 (setq after-lb-or-comma nil
9184 after-comma nil))
9185 ;; array comp
9186 ((and (>= js2-language-version 170)
9187 (= tt js2-FOR) ; check for array comprehension
9188 (not after-lb-or-comma) ; "for" can't follow a comma
9189 elems ; must have at least 1 element
9190 (not (cdr elems))) ; but no 2nd element
9191 (setf continue nil
9192 pn (js2-parse-array-comprehension (car elems) pos)))
9193
9194 ;; another element
9195 (t
9196 (unless after-lb-or-comma
9197 (js2-report-error "msg.no.bracket.arg"))
9198 (push (js2-parse-assign-expr) elems)
9199 (setq after-lb-or-comma nil
9200 after-comma nil))))
9201 (unless js2-is-in-destructuring
9202 (js2-pop-scope))
9203 pn))
9204
9205 (defun js2-parse-array-comprehension (expr pos)
9206 "Parse a JavaScript 1.7 Array Comprehension.
9207 EXPR is the first expression after the opening left-bracket.
9208 POS is the beginning of the LB token preceding EXPR.
9209 We should have just parsed the 'for' keyword before calling this function."
9210 (let (loops loop first filter if-pos result)
9211 (while (= (js2-peek-token) js2-FOR)
9212 (let ((prev (car loops))) ; rearrange scope chain
9213 (push (setq loop (js2-parse-array-comp-loop)) loops)
9214 (if prev ; each loop is parent scope to the next one
9215 (setf (js2-scope-parent-scope loop) prev)
9216 ; first loop takes expr scope's parent
9217 (setf (js2-scope-parent-scope (setq first loop))
9218 (js2-scope-parent-scope js2-current-scope)))))
9219 ;; set expr scope's parent to the last loop
9220 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9221 (when (= (js2-peek-token) js2-IF)
9222 (js2-consume-token)
9223 (setq if-pos (- js2-token-beg pos) ; relative
9224 filter (js2-parse-condition)))
9225 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9226 (setq result (make-js2-array-comp-node :pos pos
9227 :len (- js2-ts-cursor pos)
9228 :result expr
9229 :loops (nreverse loops)
9230 :filter (car filter)
9231 :lp (js2-relpos (second filter) pos)
9232 :rp (js2-relpos (third filter) pos)
9233 :if-pos if-pos))
9234 (apply #'js2-node-add-children result expr (car filter)
9235 (js2-array-comp-node-loops result))
9236 (setq js2-current-scope first) ; pop to the first loop
9237 result))
9238
9239 (defun js2-parse-array-comp-loop ()
9240 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9241 Last token peeked should be the initial FOR."
9242 (let ((pos js2-token-beg)
9243 (pn (make-js2-array-comp-loop-node))
9244 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9245 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9246 (js2-push-scope pn)
9247 (unwind-protect
9248 (progn
9249 (when (js2-match-token js2-NAME)
9250 (if (string= js2-ts-string "each")
9251 (progn
9252 (setq foreach-p t
9253 each-pos (- js2-token-beg pos)) ; relative
9254 (js2-record-face 'font-lock-keyword-face))
9255 (js2-report-error "msg.no.paren.for")))
9256 (if (js2-must-match js2-LP "msg.no.paren.for")
9257 (setq lp (- js2-token-beg pos)))
9258 (setq tt (js2-peek-token))
9259 (cond
9260 ((or (= tt js2-LB)
9261 (= tt js2-LC))
9262 (setq iter (js2-parse-destruct-primary-expr))
9263 (js2-define-destruct-symbols iter js2-LET
9264 'font-lock-variable-name-face t))
9265 ((js2-match-token js2-NAME)
9266 (setq iter (js2-create-name-node)))
9267 (t
9268 (js2-report-error "msg.bad.var")))
9269 ;; Define as a let since we want the scope of the variable to
9270 ;; be restricted to the array comprehension
9271 (if (js2-name-node-p iter)
9272 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9273 (if (or (js2-match-token js2-IN)
9274 (and (>= js2-language-version 200)
9275 (js2-match-contextual-kwd "of")
9276 (setq forof-p t)))
9277 (setq in-pos (- js2-token-beg pos))
9278 (js2-report-error "msg.in.after.for.name"))
9279 (setq obj (js2-parse-expr))
9280 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9281 (setq rp (- js2-token-beg pos)))
9282 (setf (js2-node-pos pn) pos
9283 (js2-node-len pn) (- js2-ts-cursor pos)
9284 (js2-array-comp-loop-node-iterator pn) iter
9285 (js2-array-comp-loop-node-object pn) obj
9286 (js2-array-comp-loop-node-in-pos pn) in-pos
9287 (js2-array-comp-loop-node-each-pos pn) each-pos
9288 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9289 (js2-array-comp-loop-node-forof-p pn) forof-p
9290 (js2-array-comp-loop-node-lp pn) lp
9291 (js2-array-comp-loop-node-rp pn) rp)
9292 (js2-node-add-children pn iter obj))
9293 (js2-pop-scope))
9294 pn))
9295
9296 (defun js2-parse-object-literal ()
9297 (let ((pos js2-token-beg)
9298 tt elems result after-comma
9299 (continue t))
9300 (while continue
9301 (setq tt (js2-peek-token))
9302 (cond
9303 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9304 ;; {get foo() {...}}, or {set foo(x) {...}}
9305 ((or (js2-valid-prop-name-token tt)
9306 (= tt js2-STRING))
9307 (setq after-comma nil
9308 result (js2-parse-named-prop tt))
9309 (if (and (null result)
9310 (not js2-recover-from-parse-errors))
9311 (setq continue nil)
9312 (push result elems)))
9313 ;; {12: x} or {10.7: x}
9314 ((= tt js2-NUMBER)
9315 (js2-consume-token)
9316 (setq after-comma nil)
9317 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9318 ;; trailing comma
9319 ((= tt js2-RC)
9320 (setq continue nil)
9321 (if after-comma
9322 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9323 pos elems after-comma)))
9324 (t
9325 (js2-report-error "msg.bad.prop")
9326 (unless js2-recover-from-parse-errors
9327 (setq continue nil)))) ; end switch
9328 (if (js2-match-token js2-COMMA)
9329 (setq after-comma js2-token-end)
9330 (setq continue nil))) ; end loop
9331 (js2-must-match js2-RC "msg.no.brace.prop")
9332 (setq result (make-js2-object-node :pos pos
9333 :len (- js2-ts-cursor pos)
9334 :elems (nreverse elems)))
9335 (apply #'js2-node-add-children result (js2-object-node-elems result))
9336 result))
9337
9338 (defun js2-parse-named-prop (tt)
9339 "Parse a name, string, or getter/setter object property.
9340 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9341 (js2-consume-token)
9342 (let ((string-prop (and (= tt js2-STRING)
9343 (make-js2-string-node)))
9344 expr
9345 (ppos js2-token-beg)
9346 (pend js2-token-end)
9347 (name (js2-create-name-node))
9348 (prop js2-ts-string))
9349 (cond
9350 ;; getter/setter prop
9351 ((and (= tt js2-NAME)
9352 (= (js2-peek-token) js2-NAME)
9353 (or (string= prop "get")
9354 (string= prop "set")))
9355 (js2-consume-token)
9356 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9357 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9358 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9359 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9360 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9361 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9362 ;; when patterns are used in variable declarations, function parameters,
9363 ;; catch-clause, and iterators.
9364 ;; We have to set `js2-is-in-destructuring' to t when the current
9365 ;; expressions are on the left side of any assignment, but it's difficult
9366 ;; because it requires looking ahead of expression.
9367 ((and js2-is-in-destructuring
9368 (= tt js2-NAME)
9369 (let ((ctk (js2-peek-token)))
9370 (or (= ctk js2-COMMA)
9371 (= ctk js2-RC)
9372 (js2-valid-prop-name-token ctk))))
9373 name)
9374 ;; regular prop
9375 (t
9376 (prog1
9377 (setq expr (js2-parse-plain-property (or string-prop name)))
9378 (js2-set-face ppos pend
9379 (if (js2-function-node-p
9380 (js2-object-prop-node-right expr))
9381 'font-lock-function-name-face
9382 'font-lock-variable-name-face)
9383 'record))))))
9384
9385 (defun js2-parse-plain-property (prop)
9386 "Parse a non-getter/setter property in an object literal.
9387 PROP is the node representing the property: a number, name or string."
9388 (js2-must-match js2-COLON "msg.no.colon.prop")
9389 (let* ((pos (js2-node-pos prop))
9390 (colon (- js2-token-beg pos))
9391 (expr (js2-parse-assign-expr))
9392 (result (make-js2-object-prop-node
9393 :pos pos
9394 ;; don't include last consumed token in length
9395 :len (- (+ (js2-node-pos expr)
9396 (js2-node-len expr))
9397 pos)
9398 :left prop
9399 :right expr
9400 :op-pos colon)))
9401 (js2-node-add-children result prop expr)
9402 result))
9403
9404 (defun js2-parse-getter-setter-prop (pos prop get-p)
9405 "Parse getter or setter property in an object literal.
9406 JavaScript syntax is:
9407
9408 { get foo() {...}, set foo(x) {...} }
9409
9410 and expression closure style is also supported
9411
9412 { get foo() x, set foo(x) _x = x }
9413
9414 POS is the start position of the `get' or `set' keyword.
9415 PROP is the `js2-name-node' representing the property name.
9416 GET-P is non-nil if the keyword was `get'."
9417 (let ((type (if get-p js2-GET js2-SET))
9418 result end
9419 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9420 ;; it has to be an anonymous function, as we already parsed the name
9421 (if (/= (js2-node-type fn) js2-FUNCTION)
9422 (js2-report-error "msg.bad.prop")
9423 (if (plusp (length (js2-function-name fn)))
9424 (js2-report-error "msg.bad.prop")))
9425 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9426 (setq end (js2-node-end fn)
9427 result (make-js2-getter-setter-node :type type
9428 :pos pos
9429 :len (- end pos)
9430 :left prop
9431 :right fn))
9432 (js2-node-add-children result prop fn)
9433 result))
9434
9435 (defun js2-create-name-node (&optional check-activation-p token)
9436 "Create a name node using the token info from last scanned name.
9437 In some cases we need to either synthesize a name node, or we lost
9438 the name token information by peeking. If the TOKEN parameter is
9439 not `js2-NAME', then we use the token info saved in instance vars."
9440 (let ((beg js2-token-beg)
9441 (s js2-ts-string)
9442 name)
9443 (when (/= js2-current-token js2-NAME)
9444 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9445 s js2-prev-name-token-string
9446 js2-prev-name-token-start nil
9447 js2-prev-name-token-string nil))
9448 (setq name (make-js2-name-node :pos beg
9449 :name s
9450 :len (length s)))
9451 (if check-activation-p
9452 (js2-check-activation-name s (or token js2-NAME)))
9453 name))
9454
9455 ;;; Indentation support
9456
9457 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9458 ;; Karl cleverly deduces that the desired indentation level is often a
9459 ;; function of paren/bracket/brace nesting depth, which can be determined
9460 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9461 ;; then does some equally clever checks to see if we're in the context of a
9462 ;; substatement of a possibly braceless statement keyword such as if, while,
9463 ;; or finally. This approach yields pretty good results.
9464
9465 ;; The indenter is often "wrong", however, and needs to be overridden.
9466 ;; The right long-term solution is probably to emulate (or integrate
9467 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9468 ;; parse tree from `js2-parse' is present, which is not true at the
9469 ;; moment the user is typing, computing indentation is still thousands
9470 ;; of lines of code to handle every possible syntactic edge case.
9471
9472 ;; In the meantime, the compromise solution is that we offer a "bounce
9473 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9474 ;; current line indent among various likely guess points. This approach
9475 ;; is far from perfect, but should at least make it slightly easier to
9476 ;; move the line towards its desired indentation when manually
9477 ;; overriding Karl's heuristic nesting guesser.
9478
9479 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9480 ;; extensions such as `let' and Array comprehensions. Major kudos to
9481 ;; Karl for coming up with the initial approach, which packs a lot of
9482 ;; punch for so little code.
9483
9484 (defconst js2-possibly-braceless-keywords-re
9485 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9486 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9487 "try" "while" "with" "let")))
9488 "Regular expression matching keywords that are optionally
9489 followed by an opening brace.")
9490
9491 (defconst js2-indent-operator-re
9492 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9493 (regexp-opt '("in" "instanceof") 'words))
9494 "Regular expression matching operators that affect indentation
9495 of continued expressions.")
9496
9497 (defconst js2-declaration-keyword-re
9498 (regexp-opt '("var" "let" "const") 'words)
9499 "Regular expression matching variable declaration keywords.")
9500
9501 (defun js2-re-search-forward-inner (regexp &optional bound count)
9502 "Auxiliary function for `js2-re-search-forward'."
9503 (let (parse saved-point)
9504 (while (> count 0)
9505 (re-search-forward regexp bound)
9506 (setq parse (if saved-point
9507 (parse-partial-sexp saved-point (point))
9508 (syntax-ppss (point))))
9509 (cond ((nth 3 parse)
9510 (re-search-forward
9511 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9512 (save-excursion (end-of-line) (point)) t))
9513 ((nth 7 parse)
9514 (forward-line))
9515 ((or (nth 4 parse)
9516 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9517 (re-search-forward "\\*/"))
9518 (t
9519 (setq count (1- count))))
9520 (setq saved-point (point))))
9521 (point))
9522
9523 (defun js2-re-search-forward (regexp &optional bound noerror count)
9524 "Search forward but ignore strings and comments.
9525 Invokes `re-search-forward' but treats the buffer as if strings
9526 and comments have been removed."
9527 (let ((saved-point (point)))
9528 (condition-case err
9529 (cond ((null count)
9530 (js2-re-search-forward-inner regexp bound 1))
9531 ((< count 0)
9532 (js2-re-search-backward-inner regexp bound (- count)))
9533 ((> count 0)
9534 (js2-re-search-forward-inner regexp bound count)))
9535 (search-failed
9536 (goto-char saved-point)
9537 (unless noerror
9538 (error (error-message-string err)))))))
9539
9540 (defun js2-re-search-backward-inner (regexp &optional bound count)
9541 "Auxiliary function for `js2-re-search-backward'."
9542 (let (parse)
9543 (while (> count 0)
9544 (re-search-backward regexp bound)
9545 (setq parse (syntax-ppss (point)))
9546 (cond ((nth 3 parse)
9547 (re-search-backward
9548 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9549 (line-beginning-position) t))
9550 ((nth 7 parse)
9551 (goto-char (nth 8 parse)))
9552 ((or (nth 4 parse)
9553 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9554 (re-search-backward "/\\*"))
9555 (t
9556 (setq count (1- count))))))
9557 (point))
9558
9559 (defun js2-re-search-backward (regexp &optional bound noerror count)
9560 "Search backward but ignore strings and comments.
9561 Invokes `re-search-backward' but treats the buffer as if strings
9562 and comments have been removed."
9563 (let ((saved-point (point)))
9564 (condition-case err
9565 (cond ((null count)
9566 (js2-re-search-backward-inner regexp bound 1))
9567 ((< count 0)
9568 (js2-re-search-forward-inner regexp bound (- count)))
9569 ((> count 0)
9570 (js2-re-search-backward-inner regexp bound count)))
9571 (search-failed
9572 (goto-char saved-point)
9573 (unless noerror
9574 (error (error-message-string err)))))))
9575
9576 (defun js2-looking-at-operator-p ()
9577 "Return non-nil if text after point is a non-comma operator."
9578 (and (looking-at js2-indent-operator-re)
9579 (or (not (looking-at ":"))
9580 (save-excursion
9581 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9582 (looking-at "?"))))))
9583
9584 (defun js2-continued-expression-p ()
9585 "Return non-nil if the current line continues an expression."
9586 (save-excursion
9587 (back-to-indentation)
9588 (or (js2-looking-at-operator-p)
9589 (when (catch 'found
9590 (while (and (re-search-backward "\n" nil t)
9591 (let ((state (syntax-ppss)))
9592 (when (nth 4 state)
9593 (goto-char (nth 8 state))) ;; skip comments
9594 (skip-chars-backward " \t")
9595 (if (bolp)
9596 t
9597 (throw 'found t))))))
9598 (backward-char)
9599 (when (js2-looking-at-operator-p)
9600 (backward-char)
9601 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9602
9603 (defun js2-end-of-do-while-loop-p ()
9604 "Return non-nil if word after point is `while' of a do-while
9605 statement, else returns nil. A braceless do-while statement
9606 spanning several lines requires that the start of the loop is
9607 indented to the same column as the current line."
9608 (interactive)
9609 (save-excursion
9610 (when (looking-at "\\s-*\\<while\\>")
9611 (if (save-excursion
9612 (skip-chars-backward "[ \t\n]*}")
9613 (looking-at "[ \t\n]*}"))
9614 (save-excursion
9615 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9616 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9617 (or (looking-at "\\<do\\>")
9618 (let ((saved-indent (current-indentation)))
9619 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9620 (/= (current-indentation) saved-indent)))
9621 (and (looking-at "[ \t]*\\<do\\>")
9622 (not (js2-re-search-forward
9623 "\\<while\\>" (point-at-eol) t))
9624 (= (current-indentation) saved-indent))))))))
9625
9626 (defun js2-multiline-decl-indentation ()
9627 "Return the declaration indentation column if the current line belongs
9628 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9629 (let (forward-sexp-function ; use Lisp version
9630 at-opening-bracket)
9631 (save-excursion
9632 (back-to-indentation)
9633 (when (not (looking-at js2-declaration-keyword-re))
9634 (when (looking-at js2-indent-operator-re)
9635 (goto-char (match-end 0))) ; continued expressions are ok
9636 (while (and (not at-opening-bracket)
9637 (not (bobp))
9638 (let ((pos (point)))
9639 (save-excursion
9640 (js2-backward-sws)
9641 (or (eq (char-before) ?,)
9642 (and (not (eq (char-before) ?\;))
9643 (prog2 (skip-syntax-backward ".")
9644 (looking-at js2-indent-operator-re)
9645 (js2-backward-sws))
9646 (not (eq (char-before) ?\;)))
9647 (js2-same-line pos)))))
9648 (condition-case _
9649 (backward-sexp)
9650 (scan-error (setq at-opening-bracket t))))
9651 (when (looking-at js2-declaration-keyword-re)
9652 (goto-char (match-end 0))
9653 (1+ (current-column)))))))
9654
9655 (defun js2-ctrl-statement-indentation ()
9656 "Return the proper indentation of current line if it is a control statement.
9657 Returns an indentation if this line starts the body of a control
9658 statement without braces, else returns nil."
9659 (let (forward-sexp-function)
9660 (save-excursion
9661 (back-to-indentation)
9662 (when (and (not (js2-same-line (point-min)))
9663 (not (looking-at "{"))
9664 (js2-re-search-backward "[[:graph:]]" nil t)
9665 (not (looking-at "[{([]"))
9666 (progn
9667 (forward-char)
9668 (when (= (char-before) ?\))
9669 ;; scan-sexps sometimes throws an error
9670 (ignore-errors (backward-sexp))
9671 (skip-chars-backward " \t" (point-at-bol)))
9672 (let ((pt (point)))
9673 (back-to-indentation)
9674 (when (looking-at "}[ \t]*")
9675 (goto-char (match-end 0)))
9676 (and (looking-at js2-possibly-braceless-keywords-re)
9677 (= (match-end 0) pt)
9678 (not (js2-end-of-do-while-loop-p))))))
9679 (+ (current-indentation) js2-basic-offset)))))
9680
9681 (defun js2-indent-in-array-comp (parse-status)
9682 "Return non-nil if we think we're in an array comprehension.
9683 In particular, return the buffer position of the first `for' kwd."
9684 (let ((bracket (nth 1 parse-status))
9685 (end (point)))
9686 (when bracket
9687 (save-excursion
9688 (goto-char bracket)
9689 (when (looking-at "\\[")
9690 (forward-char 1)
9691 (js2-forward-sws)
9692 (if (looking-at "[[{]")
9693 (let (forward-sexp-function) ; use Lisp version
9694 (forward-sexp) ; skip destructuring form
9695 (js2-forward-sws)
9696 (if (and (/= (char-after) ?,) ; regular array
9697 (looking-at "for"))
9698 (match-beginning 0)))
9699 ;; to skip arbitrary expressions we need the parser,
9700 ;; so we'll just guess at it.
9701 (if (and (> end (point)) ; not empty literal
9702 (re-search-forward "[^,]]* \\(for\\) " end t)
9703 ;; not inside comment or string literal
9704 (let ((state (parse-partial-sexp bracket (point))))
9705 (not (or (nth 3 state) (nth 4 state)))))
9706 (match-beginning 1))))))))
9707
9708 (defun js2-array-comp-indentation (parse-status for-kwd)
9709 (if (js2-same-line for-kwd)
9710 ;; first continuation line
9711 (save-excursion
9712 (goto-char (nth 1 parse-status))
9713 (forward-char 1)
9714 (skip-chars-forward " \t")
9715 (current-column))
9716 (save-excursion
9717 (goto-char for-kwd)
9718 (current-column))))
9719
9720 (defun js2-proper-indentation (parse-status)
9721 "Return the proper indentation for the current line."
9722 (save-excursion
9723 (back-to-indentation)
9724 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9725 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9726 (continued-expr-p (js2-continued-expression-p))
9727 (declaration-indent (and js2-pretty-multiline-declarations
9728 (js2-multiline-decl-indentation)))
9729 (bracket (nth 1 parse-status))
9730 beg)
9731 (cond
9732 ;; indent array comprehension continuation lines specially
9733 ((and bracket
9734 (>= js2-language-version 170)
9735 (not (js2-same-line bracket))
9736 (setq beg (js2-indent-in-array-comp parse-status))
9737 (>= (point) (save-excursion
9738 (goto-char beg)
9739 (point-at-bol)))) ; at or after first loop?
9740 (js2-array-comp-indentation parse-status beg))
9741
9742 (ctrl-stmt-indent)
9743
9744 ((and declaration-indent continued-expr-p)
9745 (+ declaration-indent js2-basic-offset))
9746
9747 (declaration-indent)
9748
9749 (bracket
9750 (goto-char bracket)
9751 (cond
9752 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9753 (when (save-excursion (skip-chars-backward " \t)")
9754 (looking-at ")"))
9755 (backward-list))
9756 (back-to-indentation)
9757 (and (eq js2-pretty-multiline-declarations 'all)
9758 (looking-at js2-declaration-keyword-re)
9759 (goto-char (1+ (match-end 0))))
9760 (cond (same-indent-p
9761 (current-column))
9762 (continued-expr-p
9763 (+ (current-column) (* 2 js2-basic-offset)))
9764 (t
9765 (+ (current-column) js2-basic-offset))))
9766 (t
9767 (unless same-indent-p
9768 (forward-char)
9769 (skip-chars-forward " \t"))
9770 (current-column))))
9771
9772 (continued-expr-p js2-basic-offset)
9773
9774 (t 0)))))
9775
9776 (defun js2-lineup-comment (parse-status)
9777 "Indent a multi-line block comment continuation line."
9778 (let* ((beg (nth 8 parse-status))
9779 (first-line (js2-same-line beg))
9780 (offset (save-excursion
9781 (goto-char beg)
9782 (if (looking-at "/\\*")
9783 (+ 1 (current-column))
9784 0))))
9785 (unless first-line
9786 (indent-line-to offset))))
9787
9788 (defun js2-backward-sws ()
9789 "Move backward through whitespace and comments."
9790 (interactive)
9791 (while (forward-comment -1)))
9792
9793 (defun js2-forward-sws ()
9794 "Move forward through whitespace and comments."
9795 (interactive)
9796 (while (forward-comment 1)))
9797
9798 (defun js2-current-indent (&optional pos)
9799 "Return column of indentation on current line.
9800 If POS is non-nil, go to that point and return indentation for that line."
9801 (save-excursion
9802 (if pos
9803 (goto-char pos))
9804 (back-to-indentation)
9805 (current-column)))
9806
9807 (defun js2-arglist-close ()
9808 "Return non-nil if we're on a line beginning with a close-paren/brace."
9809 (save-excursion
9810 (goto-char (point-at-bol))
9811 (js2-forward-sws)
9812 (looking-at "[])}]")))
9813
9814 (defun js2-indent-looks-like-label-p ()
9815 (goto-char (point-at-bol))
9816 (js2-forward-sws)
9817 (looking-at (concat js2-mode-identifier-re ":")))
9818
9819 (defun js2-indent-in-objlit-p (parse-status)
9820 "Return non-nil if this looks like an object-literal entry."
9821 (let ((start (nth 1 parse-status)))
9822 (and
9823 start
9824 (save-excursion
9825 (and (zerop (forward-line -1))
9826 (not (< (point) start)) ; crossed a {} boundary
9827 (js2-indent-looks-like-label-p)))
9828 (save-excursion
9829 (js2-indent-looks-like-label-p)))))
9830
9831 ;; If prev line looks like foobar({ then we're passing an object
9832 ;; literal to a function call, and people pretty much always want to
9833 ;; de-dent back to the previous line, so move the 'basic-offset'
9834 ;; position to the front.
9835 (defun js2-indent-objlit-arg-p (parse-status)
9836 (save-excursion
9837 (back-to-indentation)
9838 (js2-backward-sws)
9839 (and (eq (1- (point)) (nth 1 parse-status))
9840 (eq (char-before) ?{)
9841 (progn
9842 (forward-char -1)
9843 (skip-chars-backward " \t")
9844 (eq (char-before) ?\()))))
9845
9846 (defun js2-indent-case-block-p ()
9847 (save-excursion
9848 (back-to-indentation)
9849 (js2-backward-sws)
9850 (goto-char (point-at-bol))
9851 (skip-chars-forward " \t")
9852 (looking-at "case\\s-.+:")))
9853
9854 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9855 "Cycle among alternate computed indentation positions.
9856 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9857 of the buffer to the current point. NORMAL-COL is the indentation
9858 column computed by the heuristic guesser based on current paren,
9859 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9860 in reverse."
9861 (let ((cur-indent (js2-current-indent))
9862 (old-buffer-undo-list buffer-undo-list)
9863 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9864 (current-line (save-excursion
9865 (forward-line 0) ; move to bol
9866 (1+ (count-lines (point-min) (point)))))
9867 positions pos main-pos anchor arglist-cont same-indent
9868 basic-offset computed-pos)
9869 ;; temporarily don't record undo info, if user requested this
9870 (when js2-mode-indent-inhibit-undo
9871 (setq buffer-undo-list t))
9872 (unwind-protect
9873 (progn
9874 ;; First likely point: indent from beginning of previous code line
9875 (push (setq basic-offset
9876 (+ (save-excursion
9877 (back-to-indentation)
9878 (js2-backward-sws)
9879 (back-to-indentation)
9880 (current-column))
9881 js2-basic-offset))
9882 positions)
9883
9884 ;; (First + epsilon) likely point: indent 2x from beginning of
9885 ;; previous code line. Google does it this way.
9886 (push (setq basic-offset
9887 (+ (save-excursion
9888 (back-to-indentation)
9889 (js2-backward-sws)
9890 (back-to-indentation)
9891 (current-column))
9892 (* 2 js2-basic-offset)))
9893 positions)
9894
9895 ;; Second likely point: indent from assign-expr RHS. This
9896 ;; is just a crude guess based on finding " = " on the previous
9897 ;; line containing actual code.
9898 (setq pos (save-excursion
9899 (forward-line -1)
9900 (goto-char (point-at-bol))
9901 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9902 (point-at-eol) t)
9903 (goto-char (match-end 1))
9904 (skip-chars-forward " \t\r\n")
9905 (current-column))))
9906 (when pos
9907 (incf pos js2-basic-offset)
9908 (push pos positions))
9909
9910 ;; Third likely point: same indent as previous line of code.
9911 ;; Make it the first likely point if we're not on an
9912 ;; arglist-close line and previous line ends in a comma, or
9913 ;; both this line and prev line look like object-literal
9914 ;; elements.
9915 (setq pos (save-excursion
9916 (goto-char (point-at-bol))
9917 (js2-backward-sws)
9918 (back-to-indentation)
9919 (prog1
9920 (current-column)
9921 ;; while we're here, look for trailing comma
9922 (if (save-excursion
9923 (goto-char (point-at-eol))
9924 (js2-backward-sws)
9925 (eq (char-before) ?,))
9926 (setq arglist-cont (1- (point)))))))
9927 (when pos
9928 (if (and (or arglist-cont
9929 (js2-indent-in-objlit-p parse-status))
9930 (not (js2-arglist-close)))
9931 (setq same-indent pos))
9932 (push pos positions))
9933
9934 ;; Fourth likely point: first preceding code with less indentation.
9935 ;; than the immediately preceding code line.
9936 (setq pos (save-excursion
9937 (back-to-indentation)
9938 (js2-backward-sws)
9939 (back-to-indentation)
9940 (setq anchor (current-column))
9941 (while (and (zerop (forward-line -1))
9942 (>= (progn
9943 (back-to-indentation)
9944 (current-column))
9945 anchor)))
9946 (setq pos (current-column))))
9947 (push pos positions)
9948
9949 ;; nesting-heuristic position, main by default
9950 (push (setq main-pos normal-col) positions)
9951
9952 ;; delete duplicates and sort positions list
9953 (setq positions (sort (delete-dups positions) '<))
9954
9955 ;; comma-list continuation lines: prev line indent takes precedence
9956 (if same-indent
9957 (setq main-pos same-indent))
9958
9959 ;; common special cases where we want to indent in from previous line
9960 (if (or (js2-indent-case-block-p)
9961 (js2-indent-objlit-arg-p parse-status))
9962 (setq main-pos basic-offset))
9963
9964 ;; if bouncing backwards, reverse positions list
9965 (if backwards
9966 (setq positions (reverse positions)))
9967
9968 ;; record whether we're already sitting on one of the alternatives
9969 (setq pos (member cur-indent positions))
9970
9971 (cond
9972 ;; case 0: we're one one of the alternatives and this is the
9973 ;; first time they've pressed TAB on this line (best-guess).
9974 ((and js2-mode-indent-ignore-first-tab
9975 pos
9976 ;; first time pressing TAB on this line?
9977 (not (eq js2-mode-last-indented-line current-line)))
9978 ;; do nothing
9979 (setq computed-pos nil))
9980 ;; case 1: only one computed position => use it
9981 ((null (cdr positions))
9982 (setq computed-pos 0))
9983 ;; case 2: not on any of the computed spots => use main spot
9984 ((not pos)
9985 (setq computed-pos (js2-position main-pos positions)))
9986 ;; case 3: on last position: cycle to first position
9987 ((null (cdr pos))
9988 (setq computed-pos 0))
9989 ;; case 4: on intermediate position: cycle to next position
9990 (t
9991 (setq computed-pos (js2-position (second pos) positions))))
9992
9993 ;; see if any hooks want to indent; otherwise we do it
9994 (loop with result = nil
9995 for hook in js2-indent-hook
9996 while (null result)
9997 do
9998 (setq result (funcall hook positions computed-pos))
9999 finally do
10000 (unless (or result (null computed-pos))
10001 (indent-line-to (nth computed-pos positions)))))
10002
10003 ;; finally
10004 (if js2-mode-indent-inhibit-undo
10005 (setq buffer-undo-list old-buffer-undo-list))
10006 ;; see commentary for `js2-mode-last-indented-line'
10007 (setq js2-mode-last-indented-line current-line))))
10008
10009 (defun js2-indent-bounce-backwards ()
10010 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10011 cycles between the computed indentation positions in reverse order."
10012 (interactive)
10013 (js2-indent-line t))
10014
10015 (defun js2-1-line-comment-continuation-p ()
10016 "Return t if we're in a 1-line comment continuation.
10017 If so, we don't ever want to use bounce-indent."
10018 (save-excursion
10019 (and (progn
10020 (forward-line 0)
10021 (looking-at "\\s-*//"))
10022 (progn
10023 (forward-line -1)
10024 (forward-line 0)
10025 (when (looking-at "\\s-*$")
10026 (js2-backward-sws)
10027 (forward-line 0))
10028 (looking-at "\\s-*//")))))
10029
10030 (defun js2-indent-line (&optional bounce-backwards)
10031 "Indent the current line as JavaScript source text."
10032 (interactive)
10033 (let (parse-status offset indent-col
10034 ;; Don't whine about errors/warnings when we're indenting.
10035 ;; This has to be set before calling parse-partial-sexp below.
10036 (inhibit-point-motion-hooks t))
10037 (setq parse-status (save-excursion
10038 (syntax-ppss (point-at-bol)))
10039 offset (- (point) (save-excursion
10040 (back-to-indentation)
10041 (point))))
10042 (js2-with-underscore-as-word-syntax
10043 (if (nth 4 parse-status)
10044 (js2-lineup-comment parse-status)
10045 (setq indent-col (js2-proper-indentation parse-status))
10046 ;; See comments below about `js2-mode-last-indented-line'.
10047 (cond
10048 ;; bounce-indenting is disabled during electric-key indent.
10049 ;; It doesn't work well on first line of buffer.
10050 ((and js2-bounce-indent-p
10051 (not (js2-same-line (point-min)))
10052 (not (js2-1-line-comment-continuation-p)))
10053 (js2-bounce-indent indent-col parse-status bounce-backwards))
10054 ;; just indent to the guesser's likely spot
10055 (t (indent-line-to indent-col))))
10056 (when (plusp offset)
10057 (forward-char offset)))))
10058
10059 (defun js2-indent-region (start end)
10060 "Indent the region, but don't use bounce indenting."
10061 (let ((js2-bounce-indent-p nil)
10062 (indent-region-function nil)
10063 (after-change-functions (remq 'js2-mode-edit
10064 after-change-functions)))
10065 (indent-region start end nil) ; nil for byte-compiler
10066 (js2-mode-edit start end (- end start))))
10067
10068 (defvar js2-minor-mode-map
10069 (let ((map (make-sparse-keymap)))
10070 (define-key map (kbd "C-c C-`") #'js2-next-error)
10071 (define-key map [mouse-1] #'js2-mode-show-node)
10072 map)
10073 "Keymap used when `js2-minor-mode' is active.")
10074
10075 ;;;###autoload
10076 (define-minor-mode js2-minor-mode
10077 "Minor mode for running js2 as a background linter.
10078 This allows you to use a different major mode for JavaScript editing,
10079 such as `espresso-mode', while retaining the asynchronous error/warning
10080 highlighting features of `js2-mode'."
10081 :group 'js2-mode
10082 :lighter " js-lint"
10083 (if js2-minor-mode
10084 (js2-minor-mode-enter)
10085 (js2-minor-mode-exit)))
10086
10087 (defun js2-minor-mode-enter ()
10088 "Initialization for `js2-minor-mode'."
10089 (set (make-local-variable 'max-lisp-eval-depth)
10090 (max max-lisp-eval-depth 3000))
10091 (setq next-error-function #'js2-next-error)
10092 (js2-set-default-externs)
10093 ;; Experiment: make reparse-delay longer for longer files.
10094 (if (plusp js2-dynamic-idle-timer-adjust)
10095 (setq js2-idle-timer-delay
10096 (* js2-idle-timer-delay
10097 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10098 (setq js2-mode-buffer-dirty-p t
10099 js2-mode-parsing nil)
10100 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10101 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10102 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10103 (when js2-include-jslint-globals
10104 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10105 (run-hooks 'js2-init-hook)
10106 (js2-reparse))
10107
10108 (defun js2-minor-mode-exit ()
10109 "Turn off `js2-minor-mode'."
10110 (setq next-error-function nil)
10111 (remove-hook 'after-change-functions #'js2-mode-edit t)
10112 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10113 (when js2-mode-node-overlay
10114 (delete-overlay js2-mode-node-overlay)
10115 (setq js2-mode-node-overlay nil))
10116 (js2-remove-overlays)
10117 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10118 (setq js2-mode-ast nil))
10119
10120 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10121 (make-variable-buffer-local 'js2-source-buffer)
10122
10123 (defun* js2-display-error-list ()
10124 "Display a navigable buffer listing parse errors/warnings."
10125 (interactive)
10126 (unless (js2-have-errors-p)
10127 (message "No errors")
10128 (return-from js2-display-error-list))
10129 (labels ((annotate-list
10130 (lst type)
10131 "Add diagnostic TYPE and line number to errs list"
10132 (mapcar (lambda (err)
10133 (list err type (line-number-at-pos (nth 1 err))))
10134 lst)))
10135 (let* ((srcbuf (current-buffer))
10136 (errbuf (get-buffer-create "*js-lint*"))
10137 (errors (annotate-list
10138 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10139 'js2-error)) ; must be a valid face name
10140 (warnings (annotate-list
10141 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10142 'js2-warning)) ; must be a valid face name
10143 (all-errs (sort (append errors warnings)
10144 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10145 (with-current-buffer errbuf
10146 (let ((inhibit-read-only t))
10147 (erase-buffer)
10148 (dolist (err all-errs)
10149 (destructuring-bind ((msg-key beg _end &rest) type line) err
10150 (insert-text-button
10151 (format "line %d: %s" line (js2-get-msg msg-key))
10152 'face type
10153 'follow-link "\C-m"
10154 'action 'js2-error-buffer-jump
10155 'js2-msg (js2-get-msg msg-key)
10156 'js2-pos beg)
10157 (insert "\n"))))
10158 (js2-error-buffer-mode)
10159 (setq js2-source-buffer srcbuf)
10160 (pop-to-buffer errbuf)
10161 (goto-char (point-min))
10162 (unless (eobp)
10163 (js2-error-buffer-view))))))
10164
10165 (defvar js2-error-buffer-mode-map
10166 (let ((map (make-sparse-keymap)))
10167 (define-key map "n" #'js2-error-buffer-next)
10168 (define-key map "p" #'js2-error-buffer-prev)
10169 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10170 (define-key map "o" #'js2-error-buffer-view)
10171 (define-key map "q" #'js2-error-buffer-quit)
10172 map)
10173 "Keymap used for js2 diagnostics buffers.")
10174
10175 (defun js2-error-buffer-mode ()
10176 "Major mode for js2 diagnostics buffers.
10177 Selecting an error will jump it to the corresponding source-buffer error.
10178 \\{js2-error-buffer-mode-map}"
10179 (interactive)
10180 (setq major-mode 'js2-error-buffer-mode
10181 mode-name "JS Lint Diagnostics")
10182 (use-local-map js2-error-buffer-mode-map)
10183 (setq truncate-lines t)
10184 (set-buffer-modified-p nil)
10185 (setq buffer-read-only t)
10186 (run-hooks 'js2-error-buffer-mode-hook))
10187
10188 (defun js2-error-buffer-next ()
10189 "Move to next error and view it."
10190 (interactive)
10191 (when (zerop (forward-line 1))
10192 (js2-error-buffer-view)))
10193
10194 (defun js2-error-buffer-prev ()
10195 "Move to previous error and view it."
10196 (interactive)
10197 (when (zerop (forward-line -1))
10198 (js2-error-buffer-view)))
10199
10200 (defun js2-error-buffer-quit ()
10201 "Kill the current buffer."
10202 (interactive)
10203 (kill-buffer))
10204
10205 (defun js2-error-buffer-jump (&rest ignored)
10206 "Jump cursor to current error in source buffer."
10207 (interactive)
10208 (when (js2-error-buffer-view)
10209 (pop-to-buffer js2-source-buffer)))
10210
10211 (defun js2-error-buffer-view ()
10212 "Scroll source buffer to show error at current line."
10213 (interactive)
10214 (cond
10215 ((not (eq major-mode 'js2-error-buffer-mode))
10216 (message "Not in a js2 errors buffer"))
10217 ((not (buffer-live-p js2-source-buffer))
10218 (message "Source buffer has been killed"))
10219 ((not (wholenump (get-text-property (point) 'js2-pos)))
10220 (message "There does not seem to be an error here"))
10221 (t
10222 (let ((pos (get-text-property (point) 'js2-pos))
10223 (msg (get-text-property (point) 'js2-msg)))
10224 (save-selected-window
10225 (pop-to-buffer js2-source-buffer)
10226 (goto-char pos)
10227 (message msg))))))
10228
10229 ;;;###autoload
10230 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10231 ;; FIXME: Should derive from js-mode.
10232 "Major mode for editing JavaScript code."
10233 ;; Used by comment-region; don't change it.
10234 (set (make-local-variable 'comment-start) "//")
10235 (set (make-local-variable 'comment-end) "")
10236 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10237 (set (make-local-variable 'max-lisp-eval-depth)
10238 (max max-lisp-eval-depth 3000))
10239 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10240 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10241 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10242 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10243 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10244 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10245 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10246 ;; for characters inside regexp literals.
10247 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10248 ;; this is necessary to make `show-paren-function' work properly
10249 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10250 ;; needed for M-x rgrep, among other things
10251 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10252
10253 (set (make-local-variable 'electric-indent-chars)
10254 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10255 electric-indent-chars))
10256 (set (make-local-variable 'electric-layout-rules)
10257 '((?\; . after) (?\{ . after) (?\} . before)))
10258
10259 ;; some variables needed by cc-engine for paragraph-fill, etc.
10260 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10261 c-comment-start-regexp "/[*/]\\|\\s|"
10262 c-line-comment-starter "//"
10263 c-paragraph-start js2-paragraph-start
10264 c-paragraph-separate "$"
10265 c-syntactic-ws-start js2-syntactic-ws-start
10266 c-syntactic-ws-end js2-syntactic-ws-end
10267 c-syntactic-eol js2-syntactic-eol)
10268
10269 (let ((c-buffer-is-cc-mode t))
10270 ;; Copied from `js-mode'. Also see Bug#6071.
10271 (make-local-variable 'paragraph-start)
10272 (make-local-variable 'paragraph-separate)
10273 (make-local-variable 'paragraph-ignore-fill-prefix)
10274 (make-local-variable 'adaptive-fill-mode)
10275 (make-local-variable 'adaptive-fill-regexp)
10276 (c-setup-paragraph-variables))
10277
10278 (setq font-lock-defaults '(nil t))
10279
10280 ;; Experiment: make reparse-delay longer for longer files.
10281 (when (plusp js2-dynamic-idle-timer-adjust)
10282 (setq js2-idle-timer-delay
10283 (* js2-idle-timer-delay
10284 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10285
10286 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10287 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10288 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10289 (setq next-error-function #'js2-next-error)
10290 (imenu-add-to-menubar (concat "IM-" mode-name))
10291 (add-to-invisibility-spec '(js2-outline . t))
10292 (set (make-local-variable 'line-move-ignore-invisible) t)
10293 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10294
10295 (setq js2-mode-functions-hidden nil
10296 js2-mode-comments-hidden nil
10297 js2-mode-buffer-dirty-p t
10298 js2-mode-parsing nil)
10299
10300 (js2-set-default-externs)
10301
10302 (when js2-include-jslint-globals
10303 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10304
10305 (run-hooks 'js2-init-hook)
10306
10307 (js2-reparse))
10308
10309 (defun js2-mode-exit ()
10310 "Exit `js2-mode' and clean up."
10311 (interactive)
10312 (when js2-mode-node-overlay
10313 (delete-overlay js2-mode-node-overlay)
10314 (setq js2-mode-node-overlay nil))
10315 (js2-remove-overlays)
10316 (setq js2-mode-ast nil)
10317 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10318 (remove-from-invisibility-spec '(js2-outline . t))
10319 (js2-mode-show-all)
10320 (with-silent-modifications
10321 (js2-clear-face (point-min) (point-max))))
10322
10323 (defun js2-mode-reset-timer ()
10324 "Cancel any existing parse timer and schedule a new one."
10325 (if js2-mode-parse-timer
10326 (cancel-timer js2-mode-parse-timer))
10327 (setq js2-mode-parsing nil)
10328 (let ((timer (timer-create)))
10329 (setq js2-mode-parse-timer timer)
10330 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10331 (timer-set-idle-time timer js2-idle-timer-delay)
10332 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10333 (timer-activate-when-idle timer nil)))
10334
10335 (defun js2-mode-idle-reparse (buffer)
10336 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10337 it to be reparsed when the buffer is selected."
10338 (if (eq buffer (current-buffer))
10339 (js2-reparse)
10340 ;; reparse when the buffer is selected again
10341 (with-current-buffer buffer
10342 (add-hook 'window-configuration-change-hook
10343 #'js2-mode-idle-reparse-inner
10344 nil t))))
10345
10346 (defun js2-mode-idle-reparse-inner ()
10347 (remove-hook 'window-configuration-change-hook
10348 #'js2-mode-idle-reparse-inner
10349 t)
10350 (js2-reparse))
10351
10352 (defun js2-mode-edit (_beg _end _len)
10353 "Schedule a new parse after buffer is edited.
10354 Buffer edit spans from BEG to END and is of length LEN."
10355 (setq js2-mode-buffer-dirty-p t)
10356 (js2-mode-hide-overlay)
10357 (js2-mode-reset-timer))
10358
10359 (defun js2-minor-mode-edit (_beg _end _len)
10360 "Callback for buffer edits in `js2-mode'.
10361 Schedules a new parse after buffer is edited.
10362 Buffer edit spans from BEG to END and is of length LEN."
10363 (setq js2-mode-buffer-dirty-p t)
10364 (js2-mode-hide-overlay)
10365 (js2-mode-reset-timer))
10366
10367 (defun js2-reparse (&optional force)
10368 "Re-parse current buffer after user finishes some data entry.
10369 If we get any user input while parsing, including cursor motion,
10370 we discard the parse and reschedule it. If FORCE is nil, then the
10371 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10372 (let (time
10373 interrupted-p
10374 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10375 (unless js2-mode-parsing
10376 (setq js2-mode-parsing t)
10377 (unwind-protect
10378 (when (or js2-mode-buffer-dirty-p force)
10379 (js2-remove-overlays)
10380 (with-silent-modifications
10381 (setq js2-mode-buffer-dirty-p nil
10382 js2-mode-fontifications nil
10383 js2-mode-deferred-properties nil)
10384 (if js2-mode-verbose-parse-p
10385 (message "parsing..."))
10386 (setq time
10387 (js2-time
10388 (setq interrupted-p
10389 (catch 'interrupted
10390 (js2-parse)
10391 ;; if parsing is interrupted, comments and regex
10392 ;; literals stay ignored by `parse-partial-sexp'
10393 (remove-text-properties (point-min) (point-max)
10394 '(syntax-table))
10395 (js2-mode-apply-deferred-properties)
10396 (js2-mode-remove-suppressed-warnings)
10397 (js2-mode-show-warnings)
10398 (js2-mode-show-errors)
10399 (if (>= js2-highlight-level 1)
10400 (js2-highlight-jsdoc js2-mode-ast))
10401 nil))))
10402 (if interrupted-p
10403 (progn
10404 ;; unfinished parse => try again
10405 (setq js2-mode-buffer-dirty-p t)
10406 (js2-mode-reset-timer))
10407 (if js2-mode-verbose-parse-p
10408 (message "Parse time: %s" time)))))
10409 (setq js2-mode-parsing nil)
10410 (unless interrupted-p
10411 (setq js2-mode-parse-timer nil))))))
10412
10413 (defun js2-mode-show-node (event)
10414 "Debugging aid: highlight selected AST node on mouse click."
10415 (interactive "e")
10416 (mouse-set-point event)
10417 (setq deactivate-mark t)
10418 (when js2-mode-show-overlay
10419 (let ((node (js2-node-at-point))
10420 beg end)
10421 (if (null node)
10422 (message "No node found at location %s" (point))
10423 (setq beg (js2-node-abs-pos node)
10424 end (+ beg (js2-node-len node)))
10425 (if js2-mode-node-overlay
10426 (move-overlay js2-mode-node-overlay beg end)
10427 (setq js2-mode-node-overlay (make-overlay beg end))
10428 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10429 (with-silent-modifications
10430 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10431 (message "%s, parent: %s"
10432 (js2-node-short-name node)
10433 (if (js2-node-parent node)
10434 (js2-node-short-name (js2-node-parent node))
10435 "nil"))))))
10436
10437 (defun js2-mode-hide-overlay (&optional _p1 p2)
10438 "Remove the debugging overlay when the point moves.
10439 P1 and P2 are the old and new values of point, respectively."
10440 (when js2-mode-node-overlay
10441 (let ((beg (overlay-start js2-mode-node-overlay))
10442 (end (overlay-end js2-mode-node-overlay)))
10443 ;; Sometimes we're called spuriously.
10444 (unless (and p2
10445 (>= p2 beg)
10446 (<= p2 end))
10447 (with-silent-modifications
10448 (remove-text-properties beg end '(point-left nil)))
10449 (delete-overlay js2-mode-node-overlay)
10450 (setq js2-mode-node-overlay nil)))))
10451
10452 (defun js2-mode-reset ()
10453 "Debugging helper: reset everything."
10454 (interactive)
10455 (js2-mode-exit)
10456 (js2-mode))
10457
10458 (defun js2-mode-show-warn-or-err (e face)
10459 "Highlight a warning or error E with FACE.
10460 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10461 The last element is optional. When present, use instead of FACE."
10462 (let* ((key (first e))
10463 (beg (second e))
10464 (end (+ beg (third e)))
10465 ;; Don't inadvertently go out of bounds.
10466 (beg (max (point-min) (min beg (point-max))))
10467 (end (max (point-min) (min end (point-max))))
10468 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10469 (ovl (make-overlay beg end)))
10470 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10471 (overlay-put ovl 'js2-error t)
10472 (put-text-property beg end 'help-echo (js2-get-msg key))
10473 (put-text-property beg end 'point-entered #'js2-echo-error)))
10474
10475 (defun js2-remove-overlays ()
10476 "Remove overlays from buffer that have a `js2-error' property."
10477 (let ((beg (point-min))
10478 (end (point-max)))
10479 (save-excursion
10480 (dolist (o (overlays-in beg end))
10481 (when (overlay-get o 'js2-error)
10482 (delete-overlay o))))))
10483
10484 (defun js2-error-at-point (&optional pos)
10485 "Return non-nil if there's an error overlay at POS.
10486 Defaults to point."
10487 (loop with pos = (or pos (point))
10488 for o in (overlays-at pos)
10489 thereis (overlay-get o 'js2-error)))
10490
10491 (defun js2-mode-apply-deferred-properties ()
10492 "Apply fontifications and other text properties recorded during parsing."
10493 (when (plusp js2-highlight-level)
10494 ;; We defer clearing faces as long as possible to eliminate flashing.
10495 (js2-clear-face (point-min) (point-max))
10496 ;; Have to reverse the recorded fontifications list so that errors
10497 ;; and warnings overwrite the normal fontifications.
10498 (dolist (f (nreverse js2-mode-fontifications))
10499 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10500 (setq js2-mode-fontifications nil))
10501 (dolist (p js2-mode-deferred-properties)
10502 (apply #'put-text-property p))
10503 (setq js2-mode-deferred-properties nil))
10504
10505 (defun js2-mode-show-errors ()
10506 "Highlight syntax errors."
10507 (when js2-mode-show-parse-errors
10508 (dolist (e (js2-ast-root-errors js2-mode-ast))
10509 (js2-mode-show-warn-or-err e 'js2-error))))
10510
10511 (defun js2-mode-remove-suppressed-warnings ()
10512 "Take suppressed warnings out of the AST warnings list.
10513 This ensures that the counts and `next-error' are correct."
10514 (setf (js2-ast-root-warnings js2-mode-ast)
10515 (js2-delete-if
10516 (lambda (e)
10517 (let ((key (caar e)))
10518 (or
10519 (and (not js2-strict-trailing-comma-warning)
10520 (string-match "trailing\\.comma" key))
10521 (and (not js2-strict-cond-assign-warning)
10522 (string= key "msg.equal.as.assign"))
10523 (and js2-missing-semi-one-line-override
10524 (string= key "msg.missing.semi")
10525 (let* ((beg (second e))
10526 (node (js2-node-at-point beg))
10527 (fn (js2-mode-find-parent-fn node))
10528 (body (and fn (js2-function-node-body fn)))
10529 (lc (and body (js2-node-abs-pos body)))
10530 (rc (and lc (+ lc (js2-node-len body)))))
10531 (and fn
10532 (or (null body)
10533 (save-excursion
10534 (goto-char beg)
10535 (and (js2-same-line lc)
10536 (js2-same-line rc))))))))))
10537 (js2-ast-root-warnings js2-mode-ast))))
10538
10539 (defun js2-mode-show-warnings ()
10540 "Highlight strict-mode warnings."
10541 (when js2-mode-show-strict-warnings
10542 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10543 (js2-mode-show-warn-or-err e 'js2-warning))))
10544
10545 (defun js2-echo-error (_old-point new-point)
10546 "Called by point-motion hooks."
10547 (let ((msg (get-text-property new-point 'help-echo)))
10548 (when (and (stringp msg)
10549 (not (active-minibuffer-window))
10550 (not (current-message)))
10551 (message msg))))
10552
10553 (defalias 'js2-echo-help #'js2-echo-error)
10554
10555 (defun js2-line-break (&optional _soft)
10556 "Break line at point and indent, continuing comment if within one.
10557 If inside a string, and `js2-concat-multiline-strings' is not
10558 nil, turn it into concatenation."
10559 (interactive)
10560 (let ((parse-status (syntax-ppss)))
10561 (cond
10562 ;; Check if we're inside a string.
10563 ((nth 3 parse-status)
10564 (if js2-concat-multiline-strings
10565 (js2-mode-split-string parse-status)
10566 (insert "\n")))
10567 ;; Check if inside a block comment.
10568 ((nth 4 parse-status)
10569 (js2-mode-extend-comment (nth 8 parse-status)))
10570 (t
10571 (newline-and-indent)))))
10572
10573 (defun js2-mode-split-string (parse-status)
10574 "Turn a newline in mid-string into a string concatenation.
10575 PARSE-STATUS is as documented in `parse-partial-sexp'."
10576 (let* ((quote-char (nth 3 parse-status))
10577 (at-eol (eq js2-concat-multiline-strings 'eol)))
10578 (insert quote-char)
10579 (insert (if at-eol " +\n" "\n"))
10580 (unless at-eol
10581 (insert "+ "))
10582 (js2-indent-line)
10583 (insert quote-char)
10584 (when (eolp)
10585 (insert quote-char)
10586 (backward-char 1))))
10587
10588 (defun js2-mode-extend-comment (start-pos)
10589 "Indent the line and, when inside a comment block, add comment prefix."
10590 (let (star single col first-line needs-close)
10591 (save-excursion
10592 (back-to-indentation)
10593 (when (< (point) start-pos)
10594 (goto-char start-pos))
10595 (cond
10596 ((looking-at "\\*[^/]")
10597 (setq star t
10598 col (current-column)))
10599 ((looking-at "/\\*")
10600 (setq star t
10601 first-line t
10602 col (1+ (current-column))))
10603 ((looking-at "//")
10604 (setq single t
10605 col (current-column)))))
10606 ;; Heuristic for whether we need to close the comment:
10607 ;; if we've got a parse error here, assume it's an unterminated
10608 ;; comment.
10609 (setq needs-close
10610 (or
10611 (eq (get-text-property (1- (point)) 'point-entered)
10612 'js2-echo-error)
10613 ;; The heuristic above doesn't work well when we're
10614 ;; creating a comment and there's another one downstream,
10615 ;; as our parser thinks this one ends at the end of the
10616 ;; next one. (You can have a /* inside a js block comment.)
10617 ;; So just close it if the next non-ws char isn't a *.
10618 (and first-line
10619 (eolp)
10620 (save-excursion
10621 (skip-chars-forward " \t\r\n")
10622 (not (eq (char-after) ?*))))))
10623 (delete-horizontal-space)
10624 (insert "\n")
10625 (cond
10626 (star
10627 (indent-to col)
10628 (insert "* ")
10629 (if (and first-line needs-close)
10630 (save-excursion
10631 (insert "\n")
10632 (indent-to col)
10633 (insert "*/"))))
10634 ((and single
10635 (save-excursion
10636 (and (zerop (forward-line 1))
10637 (looking-at "\\s-*//"))))
10638 (indent-to col)
10639 (insert "// ")))
10640 ;; Don't need to extend the comment after all.
10641 (js2-indent-line)))
10642
10643 (defun js2-beginning-of-line ()
10644 "Toggle point between bol and first non-whitespace char in line.
10645 Also moves past comment delimiters when inside comments."
10646 (interactive)
10647 (let (node)
10648 (cond
10649 ((bolp)
10650 (back-to-indentation))
10651 ((looking-at "//")
10652 (skip-chars-forward "/ \t"))
10653 ((and (eq (char-after) ?*)
10654 (setq node (js2-comment-at-point))
10655 (memq (js2-comment-node-format node) '(jsdoc block))
10656 (save-excursion
10657 (skip-chars-backward " \t")
10658 (bolp)))
10659 (skip-chars-forward "\* \t"))
10660 (t
10661 (goto-char (point-at-bol))))))
10662
10663 (defun js2-end-of-line ()
10664 "Toggle point between eol and last non-whitespace char in line."
10665 (interactive)
10666 (if (eolp)
10667 (skip-chars-backward " \t")
10668 (goto-char (point-at-eol))))
10669
10670 (defun js2-mode-wait-for-parse (callback)
10671 "Invoke CALLBACK when parsing is finished.
10672 If parsing is already finished, calls CALLBACK immediately."
10673 (if (not js2-mode-buffer-dirty-p)
10674 (funcall callback)
10675 (push callback js2-mode-pending-parse-callbacks)
10676 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10677
10678 (defun js2-mode-parse-finished ()
10679 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10680 ;; We can't let errors propagate up, since it prevents the
10681 ;; `js2-parse' method from completing normally and returning
10682 ;; the ast, which makes things mysteriously not work right.
10683 (unwind-protect
10684 (dolist (cb js2-mode-pending-parse-callbacks)
10685 (condition-case err
10686 (funcall cb)
10687 (error (message "%s" err))))
10688 (setq js2-mode-pending-parse-callbacks nil)))
10689
10690 (defun js2-mode-flag-region (from to flag)
10691 "Hide or show text from FROM to TO, according to FLAG.
10692 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10693 Returns the created overlay if FLAG is non-nil."
10694 (remove-overlays from to 'invisible 'js2-outline)
10695 (when flag
10696 (let ((o (make-overlay from to)))
10697 (overlay-put o 'invisible 'js2-outline)
10698 (overlay-put o 'isearch-open-invisible
10699 'js2-isearch-open-invisible)
10700 o)))
10701
10702 ;; Function to be set as an outline-isearch-open-invisible' property
10703 ;; to the overlay that makes the outline invisible (see
10704 ;; `js2-mode-flag-region').
10705 (defun js2-isearch-open-invisible (_overlay)
10706 ;; We rely on the fact that isearch places point on the matched text.
10707 (js2-mode-show-element))
10708
10709 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10710 "Return cons cell of bounds of folding overlay at POS.
10711 Returns nil if not found."
10712 (let ((overlays (overlays-at (or pos (point))))
10713 o)
10714 (while (and overlays
10715 (not o))
10716 (if (overlay-get (car overlays) 'invisible)
10717 (setq o (car overlays))
10718 (setq overlays (cdr overlays))))
10719 (if o
10720 (cons (overlay-start o) (overlay-end o)))))
10721
10722 (defun js2-mode-function-at-point (&optional pos)
10723 "Return the innermost function node enclosing current point.
10724 Returns nil if point is not in a function."
10725 (let ((node (js2-node-at-point pos)))
10726 (while (and node (not (js2-function-node-p node)))
10727 (setq node (js2-node-parent node)))
10728 (if (js2-function-node-p node)
10729 node)))
10730
10731 (defun js2-mode-toggle-element ()
10732 "Hide or show the foldable element at the point."
10733 (interactive)
10734 (let (comment fn pos)
10735 (save-excursion
10736 (cond
10737 ;; /* ... */ comment?
10738 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10739 (if (js2-mode-invisible-overlay-bounds
10740 (setq pos (+ 3 (js2-node-abs-pos comment))))
10741 (progn
10742 (goto-char pos)
10743 (js2-mode-show-element))
10744 (js2-mode-hide-element)))
10745 ;; //-comment?
10746 ((save-excursion
10747 (back-to-indentation)
10748 (looking-at js2-mode-//-comment-re))
10749 (js2-mode-toggle-//-comment))
10750 ;; function?
10751 ((setq fn (js2-mode-function-at-point))
10752 (setq pos (and (js2-function-node-body fn)
10753 (js2-node-abs-pos (js2-function-node-body fn))))
10754 (goto-char (1+ pos))
10755 (if (js2-mode-invisible-overlay-bounds)
10756 (js2-mode-show-element)
10757 (js2-mode-hide-element)))
10758 (t
10759 (message "Nothing at point to hide or show"))))))
10760
10761 (defun js2-mode-hide-element ()
10762 "Fold/hide contents of a block, showing ellipses.
10763 Show the hidden text with \\[js2-mode-show-element]."
10764 (interactive)
10765 (if js2-mode-buffer-dirty-p
10766 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10767 (let (node body beg end)
10768 (cond
10769 ((js2-mode-invisible-overlay-bounds)
10770 (message "already hidden"))
10771 (t
10772 (setq node (js2-node-at-point))
10773 (cond
10774 ((js2-block-comment-p node)
10775 (js2-mode-hide-comment node))
10776 (t
10777 (while (and node (not (js2-function-node-p node)))
10778 (setq node (js2-node-parent node)))
10779 (if (and node
10780 (setq body (js2-function-node-body node)))
10781 (progn
10782 (setq beg (js2-node-abs-pos body)
10783 end (+ beg (js2-node-len body)))
10784 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10785 (message "No collapsable element found at point"))))))))
10786
10787 (defun js2-mode-show-element ()
10788 "Show the hidden element at current point."
10789 (interactive)
10790 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10791 (if bounds
10792 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10793 (message "Nothing to un-hide"))))
10794
10795 (defun js2-mode-show-all ()
10796 "Show all of the text in the buffer."
10797 (interactive)
10798 (js2-mode-flag-region (point-min) (point-max) nil))
10799
10800 (defun js2-mode-toggle-hide-functions ()
10801 (interactive)
10802 (if js2-mode-functions-hidden
10803 (js2-mode-show-functions)
10804 (js2-mode-hide-functions)))
10805
10806 (defun js2-mode-hide-functions ()
10807 "Hides all non-nested function bodies in the buffer.
10808 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10809 to open an individual entry."
10810 (interactive)
10811 (if js2-mode-buffer-dirty-p
10812 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10813 (if (null js2-mode-ast)
10814 (message "Oops - parsing failed")
10815 (setq js2-mode-functions-hidden t)
10816 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10817
10818 (defun js2-mode-function-hider (n endp)
10819 (when (not endp)
10820 (let ((tt (js2-node-type n))
10821 body beg end)
10822 (cond
10823 ((and (= tt js2-FUNCTION)
10824 (setq body (js2-function-node-body n)))
10825 (setq beg (js2-node-abs-pos body)
10826 end (+ beg (js2-node-len body)))
10827 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10828 nil) ; don't process children of function
10829 (t
10830 t))))) ; keep processing other AST nodes
10831
10832 (defun js2-mode-show-functions ()
10833 "Un-hide any folded function bodies in the buffer."
10834 (interactive)
10835 (setq js2-mode-functions-hidden nil)
10836 (save-excursion
10837 (goto-char (point-min))
10838 (while (/= (goto-char (next-overlay-change (point)))
10839 (point-max))
10840 (dolist (o (overlays-at (point)))
10841 (when (and (overlay-get o 'invisible)
10842 (not (overlay-get o 'comment)))
10843 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10844
10845 (defun js2-mode-hide-comment (n)
10846 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10847 3 ; /**
10848 2)) ; /*
10849 (beg (+ (js2-node-abs-pos n) head))
10850 (end (- (+ beg (js2-node-len n)) head 2))
10851 (o (js2-mode-flag-region beg end 'hide)))
10852 (overlay-put o 'comment t)))
10853
10854 (defun js2-mode-toggle-hide-comments ()
10855 "Folds all block comments in the buffer.
10856 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10857 to open an individual entry."
10858 (interactive)
10859 (if js2-mode-comments-hidden
10860 (js2-mode-show-comments)
10861 (js2-mode-hide-comments)))
10862
10863 (defun js2-mode-hide-comments ()
10864 (interactive)
10865 (if js2-mode-buffer-dirty-p
10866 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10867 (if (null js2-mode-ast)
10868 (message "Oops - parsing failed")
10869 (setq js2-mode-comments-hidden t)
10870 (dolist (n (js2-ast-root-comments js2-mode-ast))
10871 (when (js2-block-comment-p n)
10872 (js2-mode-hide-comment n)))
10873 (js2-mode-hide-//-comments)))
10874
10875 (defun js2-mode-extend-//-comment (direction)
10876 "Find start or end of a block of similar //-comment lines.
10877 DIRECTION is -1 to look back, 1 to look forward.
10878 INDENT is the indentation level to match.
10879 Returns the end-of-line position of the furthest adjacent
10880 //-comment line with the same indentation as the current line.
10881 If there is no such matching line, returns current end of line."
10882 (let ((pos (point-at-eol))
10883 (indent (current-indentation)))
10884 (save-excursion
10885 (while (and (zerop (forward-line direction))
10886 (looking-at js2-mode-//-comment-re)
10887 (eq indent (length (match-string 1))))
10888 (setq pos (point-at-eol))
10889 pos))))
10890
10891 (defun js2-mode-hide-//-comments ()
10892 "Fold adjacent 1-line comments, showing only snippet of first one."
10893 (let (beg end)
10894 (save-excursion
10895 (goto-char (point-min))
10896 (while (re-search-forward js2-mode-//-comment-re nil t)
10897 (setq beg (point)
10898 end (js2-mode-extend-//-comment 1))
10899 (unless (eq beg end)
10900 (overlay-put (js2-mode-flag-region beg end 'hide)
10901 'comment t))
10902 (goto-char end)
10903 (forward-char 1)))))
10904
10905 (defun js2-mode-toggle-//-comment ()
10906 "Fold or un-fold any multi-line //-comment at point.
10907 Caller should have determined that this line starts with a //-comment."
10908 (let* ((beg (point-at-eol))
10909 (end beg))
10910 (save-excursion
10911 (goto-char end)
10912 (if (js2-mode-invisible-overlay-bounds)
10913 (js2-mode-show-element)
10914 ;; else hide the comment
10915 (setq beg (js2-mode-extend-//-comment -1)
10916 end (js2-mode-extend-//-comment 1))
10917 (unless (eq beg end)
10918 (overlay-put (js2-mode-flag-region beg end 'hide)
10919 'comment t))))))
10920
10921 (defun js2-mode-show-comments ()
10922 "Un-hide any hidden comments, leaving other hidden elements alone."
10923 (interactive)
10924 (setq js2-mode-comments-hidden nil)
10925 (save-excursion
10926 (goto-char (point-min))
10927 (while (/= (goto-char (next-overlay-change (point)))
10928 (point-max))
10929 (dolist (o (overlays-at (point)))
10930 (when (overlay-get o 'comment)
10931 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10932
10933 (defun js2-mode-display-warnings-and-errors ()
10934 "Turn on display of warnings and errors."
10935 (interactive)
10936 (setq js2-mode-show-parse-errors t
10937 js2-mode-show-strict-warnings t)
10938 (js2-reparse 'force))
10939
10940 (defun js2-mode-hide-warnings-and-errors ()
10941 "Turn off display of warnings and errors."
10942 (interactive)
10943 (setq js2-mode-show-parse-errors nil
10944 js2-mode-show-strict-warnings nil)
10945 (js2-reparse 'force))
10946
10947 (defun js2-mode-toggle-warnings-and-errors ()
10948 "Toggle the display of warnings and errors.
10949 Some users don't like having warnings/errors reported while they type."
10950 (interactive)
10951 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10952 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10953 (if (called-interactively-p 'any)
10954 (message "warnings and errors %s"
10955 (if js2-mode-show-parse-errors
10956 "enabled"
10957 "disabled")))
10958 (js2-reparse 'force))
10959
10960 (defun js2-mode-customize ()
10961 (interactive)
10962 (customize-group 'js2-mode))
10963
10964 (defun js2-mode-forward-sexp (&optional arg)
10965 "Move forward across one statement or balanced expression.
10966 With ARG, do it that many times. Negative arg -N means
10967 move backward across N balanced expressions."
10968 (interactive "p")
10969 (setq arg (or arg 1))
10970 (save-restriction
10971 (widen) ;; `blink-matching-open' calls `narrow-to-region'
10972 (js2-reparse))
10973 (let (forward-sexp-function
10974 node (start (point)) pos lp rp child)
10975 (cond
10976 ;; backward-sexp
10977 ;; could probably make this better for some cases:
10978 ;; - if in statement block (e.g. function body), go to parent
10979 ;; - infix exprs like (foo in bar) - maybe go to beginning
10980 ;; of infix expr if in the right-side expression?
10981 ((and arg (minusp arg))
10982 (dotimes (_ (- arg))
10983 (js2-backward-sws)
10984 (forward-char -1) ; Enter the node we backed up to.
10985 (when (setq node (js2-node-at-point (point) t))
10986 (setq pos (js2-node-abs-pos node))
10987 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10988 (setq lp (car parens)
10989 rp (cdr parens)))
10990 (when (and lp (> start lp))
10991 (if (and rp (<= start rp))
10992 ;; Between parens, check if there's a child node we can jump.
10993 (when (setq child (js2-node-closest-child node (point) lp t))
10994 (setq pos (js2-node-abs-pos child)))
10995 ;; Before both parens.
10996 (setq pos lp)))
10997 (let ((state (parse-partial-sexp start pos)))
10998 (goto-char (if (not (zerop (car state)))
10999 ;; Stumble at the unbalanced paren if < 0, or
11000 ;; jump a bit further if > 0.
11001 (scan-sexps start -1)
11002 pos))))
11003 (unless pos (goto-char (point-min)))))
11004 (t
11005 ;; forward-sexp
11006 (dotimes (_ arg)
11007 (js2-forward-sws)
11008 (when (setq node (js2-node-at-point (point) t))
11009 (setq pos (js2-node-abs-pos node))
11010 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11011 (setq lp (car parens)
11012 rp (cdr parens)))
11013 (or
11014 (when (and rp (<= start rp))
11015 (if (> start lp)
11016 (when (setq child (js2-node-closest-child node (point) rp))
11017 (setq pos (js2-node-abs-end child)))
11018 (setq pos (1+ rp))))
11019 ;; No parens or child nodes, looks for the end of the curren node.
11020 (incf pos (js2-node-len
11021 (if (js2-expr-stmt-node-p (js2-node-parent node))
11022 ;; Stop after the semicolon.
11023 (js2-node-parent node)
11024 node))))
11025 (let ((state (save-excursion (parse-partial-sexp start pos))))
11026 (goto-char (if (not (zerop (car state)))
11027 (scan-sexps start 1)
11028 pos))))
11029 (unless pos (goto-char (point-max))))))))
11030
11031 (defun js2-mode-forward-sexp-parens (node abs-pos)
11032 "Return a cons cell with positions of main parens in NODE."
11033 (cond
11034 ((or (js2-array-node-p node)
11035 (js2-object-node-p node)
11036 (js2-array-comp-node-p node)
11037 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11038 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11039 ((js2-paren-expr-node-p node)
11040 (let ((lp (js2-node-lp node))
11041 (rp (js2-node-rp node)))
11042 (cons (when lp (+ abs-pos lp))
11043 (when rp (+ abs-pos rp)))))))
11044
11045 (defun js2-node-closest-child (parent point limit &optional before)
11046 (let* ((parent-pos (js2-node-abs-pos parent))
11047 (rpoint (- point parent-pos))
11048 (rlimit (- limit parent-pos))
11049 (min (min rpoint rlimit))
11050 (max (max rpoint rlimit))
11051 found)
11052 (catch 'done
11053 (js2-visit-ast
11054 parent
11055 (lambda (node _end-p)
11056 (if (eq node parent)
11057 t
11058 (let ((pos (js2-node-pos node)) ;; Both relative values.
11059 (end (+ (js2-node-pos node) (js2-node-len node))))
11060 (when (and (>= pos min) (<= end max)
11061 (if before (< pos rpoint) (> end rpoint)))
11062 (setq found node))
11063 (when (> end rpoint)
11064 (throw 'done nil)))
11065 nil))))
11066 found))
11067
11068 (defun js2-errors ()
11069 "Return a list of errors found."
11070 (and js2-mode-ast
11071 (js2-ast-root-errors js2-mode-ast)))
11072
11073 (defun js2-warnings ()
11074 "Return a list of warnings found."
11075 (and js2-mode-ast
11076 (js2-ast-root-warnings js2-mode-ast)))
11077
11078 (defun js2-have-errors-p ()
11079 "Return non-nil if any parse errors or warnings were found."
11080 (or (js2-errors) (js2-warnings)))
11081
11082 (defun js2-errors-and-warnings ()
11083 "Return a copy of the concatenated errors and warnings lists.
11084 They are appended: first the errors, then the warnings.
11085 Entries are of the form (MSG BEG END)."
11086 (when js2-mode-ast
11087 (append (js2-ast-root-errors js2-mode-ast)
11088 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11089
11090 (defun js2-next-error (&optional arg reset)
11091 "Move to next parse error.
11092 Typically invoked via \\[next-error].
11093 ARG is the number of errors, forward or backward, to move.
11094 RESET means start over from the beginning."
11095 (interactive "p")
11096 (if (not (or (js2-errors) (js2-warnings)))
11097 (message "No errors")
11098 (when reset
11099 (goto-char (point-min)))
11100 (let* ((errs (js2-errors-and-warnings))
11101 (continue t)
11102 (start (point))
11103 (count (or arg 1))
11104 (backward (minusp count))
11105 (sorter (if backward '> '<))
11106 (stopper (if backward '< '>))
11107 (count (abs count))
11108 all-errs err)
11109 ;; Sort by start position.
11110 (setq errs (sort errs (lambda (e1 e2)
11111 (funcall sorter (second e1) (second e2))))
11112 all-errs errs)
11113 ;; Find nth error with pos > start.
11114 (while (and errs continue)
11115 (when (funcall stopper (cadar errs) start)
11116 (setq err (car errs))
11117 (if (zerop (decf count))
11118 (setq continue nil)))
11119 (setq errs (cdr errs)))
11120 ;; Clear for `js2-echo-error'.
11121 (message nil)
11122 (if err
11123 (goto-char (second err))
11124 ;; Wrap around to first error.
11125 (goto-char (second (car all-errs)))
11126 ;; If we were already on it, echo msg again.
11127 (if (= (point) start)
11128 (js2-echo-error (point) (point)))))))
11129
11130 (defun js2-down-mouse-3 ()
11131 "Make right-click move the point to the click location.
11132 This makes right-click context menu operations a bit more intuitive.
11133 The point will not move if the region is active, however, to avoid
11134 destroying the region selection."
11135 (interactive)
11136 (when (and js2-move-point-on-right-click
11137 (not mark-active))
11138 (let ((e last-input-event))
11139 (ignore-errors
11140 (goto-char (cadadr e))))))
11141
11142 (defun js2-mode-create-imenu-index ()
11143 "Return an alist for `imenu--index-alist'."
11144 ;; This is built up in `js2-parse-record-imenu' during parsing.
11145 (when js2-mode-ast
11146 ;; if we have an ast but no recorder, they're requesting a rescan
11147 (unless js2-imenu-recorder
11148 (js2-reparse 'force))
11149 (prog1
11150 (js2-build-imenu-index)
11151 (setq js2-imenu-recorder nil
11152 js2-imenu-function-map nil))))
11153
11154 (defun js2-mode-find-tag ()
11155 "Replacement for `find-tag-default'.
11156 `find-tag-default' returns a ridiculous answer inside comments."
11157 (let (beg end)
11158 (js2-with-underscore-as-word-syntax
11159 (save-excursion
11160 (if (and (not (looking-at "[[:alnum:]_$]"))
11161 (looking-back "[[:alnum:]_$]"))
11162 (setq beg (progn (forward-word -1) (point))
11163 end (progn (forward-word 1) (point)))
11164 (setq beg (progn (forward-word 1) (point))
11165 end (progn (forward-word -1) (point))))
11166 (replace-regexp-in-string
11167 "[\"']" ""
11168 (buffer-substring-no-properties beg end))))))
11169
11170 (defun js2-mode-forward-sibling ()
11171 "Move to the end of the sibling following point in parent.
11172 Returns non-nil if successful, or nil if there was no following sibling."
11173 (let* ((node (js2-node-at-point))
11174 (parent (js2-mode-find-enclosing-fn node))
11175 sib)
11176 (when (setq sib (js2-node-find-child-after (point) parent))
11177 (goto-char (+ (js2-node-abs-pos sib)
11178 (js2-node-len sib))))))
11179
11180 (defun js2-mode-backward-sibling ()
11181 "Move to the beginning of the sibling node preceding point in parent.
11182 Parent is defined as the enclosing script or function."
11183 (let* ((node (js2-node-at-point))
11184 (parent (js2-mode-find-enclosing-fn node))
11185 sib)
11186 (when (setq sib (js2-node-find-child-before (point) parent))
11187 (goto-char (js2-node-abs-pos sib)))))
11188
11189 (defun js2-beginning-of-defun (&optional arg)
11190 "Go to line on which current function starts, and return t on success.
11191 If we're not in a function or already at the beginning of one, go
11192 to beginning of previous script-level element.
11193 With ARG N, do that N times. If N is negative, move forward."
11194 (setq arg (or arg 1))
11195 (if (plusp arg)
11196 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11197 (when (cond
11198 ((js2-function-node-p parent)
11199 (goto-char (js2-node-abs-pos parent)))
11200 (t
11201 (js2-mode-backward-sibling)))
11202 (if (> arg 1)
11203 (js2-beginning-of-defun (1- arg))
11204 t)))
11205 (when (js2-end-of-defun)
11206 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11207
11208 (defun js2-end-of-defun ()
11209 "Go to the char after the last position of the current function
11210 or script-level element."
11211 (let* ((node (js2-node-at-point))
11212 (parent (or (and (js2-function-node-p node) node)
11213 (js2-node-parent-script-or-fn node)))
11214 script)
11215 (unless (js2-function-node-p parent)
11216 ;; Use current script-level node, or, if none, the next one.
11217 (setq script (or parent node)
11218 parent (js2-node-find-child-before (point) script))
11219 (when (or (null parent)
11220 (>= (point) (+ (js2-node-abs-pos parent)
11221 (js2-node-len parent))))
11222 (setq parent (js2-node-find-child-after (point) script))))
11223 (when parent
11224 (goto-char (+ (js2-node-abs-pos parent)
11225 (js2-node-len parent))))))
11226
11227 (defun js2-mark-defun (&optional allow-extend)
11228 "Put mark at end of this function, point at beginning.
11229 The function marked is the one that contains point.
11230
11231 Interactively, if this command is repeated,
11232 or (in Transient Mark mode) if the mark is active,
11233 it marks the next defun after the ones already marked."
11234 (interactive "p")
11235 (let (extended)
11236 (when (and allow-extend
11237 (or (and (eq last-command this-command) (mark t))
11238 (and transient-mark-mode mark-active)))
11239 (let ((sib (save-excursion
11240 (goto-char (mark))
11241 (if (js2-mode-forward-sibling)
11242 (point)))))
11243 (if sib
11244 (progn
11245 (set-mark sib)
11246 (setq extended t))
11247 ;; no more siblings - try extending to enclosing node
11248 (goto-char (mark t)))))
11249 (when (not extended)
11250 (let ((node (js2-node-at-point (point) t)) ; skip comments
11251 ast fn stmt parent beg end)
11252 (when (js2-ast-root-p node)
11253 (setq ast node
11254 node (or (js2-node-find-child-after (point) node)
11255 (js2-node-find-child-before (point) node))))
11256 ;; only mark whole buffer if we can't find any children
11257 (if (null node)
11258 (setq node ast))
11259 (if (js2-function-node-p node)
11260 (setq parent node)
11261 (setq fn (js2-mode-find-enclosing-fn node)
11262 stmt (if (or (null fn)
11263 (js2-ast-root-p fn))
11264 (js2-mode-find-first-stmt node))
11265 parent (or stmt fn)))
11266 (setq beg (js2-node-abs-pos parent)
11267 end (+ beg (js2-node-len parent)))
11268 (push-mark beg)
11269 (goto-char end)
11270 (exchange-point-and-mark)))))
11271
11272 (defun js2-narrow-to-defun ()
11273 "Narrow to the function enclosing point."
11274 (interactive)
11275 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11276 (fn (if (js2-script-node-p node)
11277 node
11278 (js2-mode-find-enclosing-fn node)))
11279 (beg (js2-node-abs-pos fn)))
11280 (unless (js2-ast-root-p fn)
11281 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11282
11283 (provide 'js2-mode)
11284
11285 ;;; js2-mode.el ends here