]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Include function's AST node in parent scope's symbol table entry
[gnu-emacs-elpa] / 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 has outdated information and is mostly
84 ;; 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-indent-switch-body nil
275 "When nil, case labels are indented on the same level as the
276 containing switch statement. Otherwise, all lines inside
277 switch statement body are indented one additional level."
278 :type 'boolean
279 :group 'js2-mode)
280 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
281
282 (defcustom js2-idle-timer-delay 0.2
283 "Delay in secs before re-parsing after user makes changes.
284 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
285 :type 'number
286 :group 'js2-mode)
287 (make-variable-buffer-local 'js2-idle-timer-delay)
288
289 (defcustom js2-dynamic-idle-timer-adjust 0
290 "Positive to adjust `js2-idle-timer-delay' based on file size.
291 The idea is that for short files, parsing is faster so we can be
292 more responsive to user edits without interfering with editing.
293 The buffer length in characters (typically bytes) is divided by
294 this value and used to multiply `js2-idle-timer-delay' for the
295 buffer. For example, a 21k file and 10k adjust yields 21k/10k
296 == 2, so js2-idle-timer-delay is multiplied by 2.
297 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
298 `js2-idle-timer-delay' is not dependent on the file size."
299 :type 'number
300 :group 'js2-mode)
301
302 (defcustom js2-concat-multiline-strings t
303 "When non-nil, `js2-line-break' in mid-string will make it a
304 string concatenation. When `eol', the '+' will be inserted at the
305 end of the line, otherwise, at the beginning of the next line."
306 :type '(choice (const t) (const eol) (const nil))
307 :group 'js2-mode)
308
309 (defcustom js2-mode-show-parse-errors t
310 "True to highlight parse errors."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-strict-warnings t
315 "Non-nil to emit Ecma strict-mode warnings.
316 Some of the warnings can be individually disabled by other flags,
317 even if this flag is non-nil."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-strict-trailing-comma-warning t
322 "Non-nil to warn about trailing commas in array literals.
323 Ecma-262-5.1 allows them, but older versions of IE raise an error."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-missing-semi-warning t
328 "Non-nil to warn about semicolon auto-insertion after statement.
329 Technically this is legal per Ecma-262, but some style guides disallow
330 depending on it."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-missing-semi-one-line-override nil
335 "Non-nil to permit missing semicolons in one-line functions.
336 In one-liner functions such as `function identity(x) {return x}'
337 people often omit the semicolon for a cleaner look. If you are
338 such a person, you can suppress the missing-semicolon warning
339 by setting this variable to t."
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-inconsistent-return-warning t
344 "Non-nil to warn about mixing returns with value-returns.
345 It's perfectly legal to have a `return' and a `return foo' in the
346 same function, but it's often an indicator of a bug, and it also
347 interferes with type inference (in systems that support it.)"
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-cond-assign-warning t
352 "Non-nil to warn about expressions like if (a = b).
353 This often should have been '==' instead of '='. If the warning
354 is enabled, you can suppress it on a per-expression basis by
355 parenthesizing the expression, e.g. if ((a = b)) ..."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-strict-var-redeclaration-warning t
360 "Non-nil to warn about redeclaring variables in a script or function."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-strict-var-hides-function-arg-warning t
365 "Non-nil to warn about a var decl hiding a function argument."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-skip-preprocessor-directives nil
370 "Non-nil to treat lines beginning with # as comments.
371 Useful for viewing Mozilla JavaScript source code."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-language-version 200
376 "Configures what JavaScript language version to recognize.
377 Currently versions 150, 160, 170, 180 and 200 are supported,
378 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
379 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
380 yield, and Array comprehensions, and 1.8 adds function closures."
381 :type 'integer
382 :group 'js2-mode)
383
384 (defcustom js2-allow-keywords-as-property-names t
385 "If non-nil, you can use JavaScript keywords as object property names.
386 Examples:
387
388 var foo = {int: 5, while: 6, continue: 7};
389 foo.return = 8;
390
391 Ecma-262 5.1 allows this syntax, but some engines still don't."
392 :type 'boolean
393 :group 'js2-mode)
394
395 (defcustom js2-instanceof-has-side-effects nil
396 "If non-nil, treats the instanceof operator as having side effects.
397 This is useful for xulrunner apps."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-move-point-on-right-click t
402 "Non-nil to move insertion point when you right-click.
403 This makes right-click context menu behavior a bit more intuitive,
404 since menu operations generally apply to the point. The exception
405 is if there is a region selection, in which case the point does -not-
406 move, so cut/copy/paste can work properly.
407
408 Note that IntelliJ moves the point, and Eclipse leaves it alone,
409 so this behavior is customizable."
410 :group 'js2-mode
411 :type 'boolean)
412
413 (defcustom js2-allow-rhino-new-expr-initializer t
414 "Non-nil to support a Rhino's experimental syntactic construct.
415
416 Rhino supports the ability to follow a `new' expression with an object
417 literal, which is used to set additional properties on the new object
418 after calling its constructor. Syntax:
419
420 new <expr> [ ( arglist ) ] [initializer]
421
422 Hence, this expression:
423
424 new Object {a: 1, b: 2}
425
426 results in an Object with properties a=1 and b=2. This syntax is
427 apparently not configurable in Rhino - it's currently always enabled,
428 as of Rhino version 1.7R2."
429 :type 'boolean
430 :group 'js2-mode)
431
432 (defcustom js2-allow-member-expr-as-function-name nil
433 "Non-nil to support experimental Rhino syntax for function names.
434
435 Rhino supports an experimental syntax configured via the Rhino Context
436 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
437
438 function <member-expr> ( [ arg-list ] ) { <body> }
439
440 Where member-expr is a non-parenthesized 'member expression', which
441 is anything at the grammar level of a new-expression or lower, meaning
442 any expression that does not involve infix or unary operators.
443
444 When <member-expr> is not a simple identifier, then it is syntactic
445 sugar for assigning the anonymous function to the <member-expr>. Hence,
446 this code:
447
448 function a.b().c[2] (x, y) { ... }
449
450 is rewritten as:
451
452 a.b().c[2] = function(x, y) {...}
453
454 which doesn't seem particularly useful, but Rhino permits it."
455 :type 'boolean
456 :group 'js2-mode)
457
458 ;; scanner variables
459
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
462 `(progn
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
465
466 (defvar js2-EOF_CHAR -1
467 "Represents end of stream. Distinct from js2-EOF token type.")
468
469 ;; I originally used symbols to represent tokens, but Rhino uses
470 ;; ints and then sets various flag bits in them, so ints it is.
471 ;; The upshot is that we need a `js2-' prefix in front of each name.
472 (defvar js2-ERROR -1)
473 (defvar js2-EOF 0)
474 (defvar js2-EOL 1)
475 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
476 (defvar js2-LEAVEWITH 3)
477 (defvar js2-RETURN 4)
478 (defvar js2-GOTO 5)
479 (defvar js2-IFEQ 6)
480 (defvar js2-IFNE 7)
481 (defvar js2-SETNAME 8)
482 (defvar js2-BITOR 9)
483 (defvar js2-BITXOR 10)
484 (defvar js2-BITAND 11)
485 (defvar js2-EQ 12)
486 (defvar js2-NE 13)
487 (defvar js2-LT 14)
488 (defvar js2-LE 15)
489 (defvar js2-GT 16)
490 (defvar js2-GE 17)
491 (defvar js2-LSH 18)
492 (defvar js2-RSH 19)
493 (defvar js2-URSH 20)
494 (defvar js2-ADD 21) ; infix plus
495 (defvar js2-SUB 22) ; infix minus
496 (defvar js2-MUL 23)
497 (defvar js2-DIV 24)
498 (defvar js2-MOD 25)
499 (defvar js2-NOT 26)
500 (defvar js2-BITNOT 27)
501 (defvar js2-POS 28) ; unary plus
502 (defvar js2-NEG 29) ; unary minus
503 (defvar js2-NEW 30)
504 (defvar js2-DELPROP 31)
505 (defvar js2-TYPEOF 32)
506 (defvar js2-GETPROP 33)
507 (defvar js2-GETPROPNOWARN 34)
508 (defvar js2-SETPROP 35)
509 (defvar js2-GETELEM 36)
510 (defvar js2-SETELEM 37)
511 (defvar js2-CALL 38)
512 (defvar js2-NAME 39) ; an identifier
513 (defvar js2-NUMBER 40)
514 (defvar js2-STRING 41)
515 (defvar js2-NULL 42)
516 (defvar js2-THIS 43)
517 (defvar js2-FALSE 44)
518 (defvar js2-TRUE 45)
519 (defvar js2-SHEQ 46) ; shallow equality (===)
520 (defvar js2-SHNE 47) ; shallow inequality (!==)
521 (defvar js2-REGEXP 48)
522 (defvar js2-BINDNAME 49)
523 (defvar js2-THROW 50)
524 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
525 (defvar js2-IN 52)
526 (defvar js2-INSTANCEOF 53)
527 (defvar js2-LOCAL_LOAD 54)
528 (defvar js2-GETVAR 55)
529 (defvar js2-SETVAR 56)
530 (defvar js2-CATCH_SCOPE 57)
531 (defvar js2-ENUM_INIT_KEYS 58)
532 (defvar js2-ENUM_INIT_VALUES 59)
533 (defvar js2-ENUM_INIT_ARRAY 60)
534 (defvar js2-ENUM_NEXT 61)
535 (defvar js2-ENUM_ID 62)
536 (defvar js2-THISFN 63)
537 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
538 (defvar js2-ARRAYLIT 65) ; array literal
539 (defvar js2-OBJECTLIT 66) ; object literal
540 (defvar js2-GET_REF 67) ; *reference
541 (defvar js2-SET_REF 68) ; *reference = something
542 (defvar js2-DEL_REF 69) ; delete reference
543 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
544 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
545 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
546
547 ;; XML support
548 (defvar js2-DEFAULTNAMESPACE 73)
549 (defvar js2-ESCXMLATTR 74)
550 (defvar js2-ESCXMLTEXT 75)
551 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
552 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
553 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
554 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
555
556 (defvar js2-first-bytecode js2-ENTERWITH)
557 (defvar js2-last-bytecode js2-REF_NS_NAME)
558
559 (defvar js2-TRY 80)
560 (defvar js2-SEMI 81) ; semicolon
561 (defvar js2-LB 82) ; left and right brackets
562 (defvar js2-RB 83)
563 (defvar js2-LC 84) ; left and right curly-braces
564 (defvar js2-RC 85)
565 (defvar js2-LP 86) ; left and right parens
566 (defvar js2-RP 87)
567 (defvar js2-COMMA 88) ; comma operator
568
569 (defvar js2-ASSIGN 89) ; simple assignment (=)
570 (defvar js2-ASSIGN_BITOR 90) ; |=
571 (defvar js2-ASSIGN_BITXOR 91) ; ^=
572 (defvar js2-ASSIGN_BITAND 92) ; &=
573 (defvar js2-ASSIGN_LSH 93) ; <<=
574 (defvar js2-ASSIGN_RSH 94) ; >>=
575 (defvar js2-ASSIGN_URSH 95) ; >>>=
576 (defvar js2-ASSIGN_ADD 96) ; +=
577 (defvar js2-ASSIGN_SUB 97) ; -=
578 (defvar js2-ASSIGN_MUL 98) ; *=
579 (defvar js2-ASSIGN_DIV 99) ; /=
580 (defvar js2-ASSIGN_MOD 100) ; %=
581
582 (defvar js2-first-assign js2-ASSIGN)
583 (defvar js2-last-assign js2-ASSIGN_MOD)
584
585 (defvar js2-HOOK 101) ; conditional (?:)
586 (defvar js2-COLON 102)
587 (defvar js2-OR 103) ; logical or (||)
588 (defvar js2-AND 104) ; logical and (&&)
589 (defvar js2-INC 105) ; increment/decrement (++ --)
590 (defvar js2-DEC 106)
591 (defvar js2-DOT 107) ; member operator (.)
592 (defvar js2-FUNCTION 108) ; function keyword
593 (defvar js2-EXPORT 109) ; export keyword
594 (defvar js2-IMPORT 110) ; import keyword
595 (defvar js2-IF 111) ; if keyword
596 (defvar js2-ELSE 112) ; else keyword
597 (defvar js2-SWITCH 113) ; switch keyword
598 (defvar js2-CASE 114) ; case keyword
599 (defvar js2-DEFAULT 115) ; default keyword
600 (defvar js2-WHILE 116) ; while keyword
601 (defvar js2-DO 117) ; do keyword
602 (defvar js2-FOR 118) ; for keyword
603 (defvar js2-BREAK 119) ; break keyword
604 (defvar js2-CONTINUE 120) ; continue keyword
605 (defvar js2-VAR 121) ; var keyword
606 (defvar js2-WITH 122) ; with keyword
607 (defvar js2-CATCH 123) ; catch keyword
608 (defvar js2-FINALLY 124) ; finally keyword
609 (defvar js2-VOID 125) ; void keyword
610 (defvar js2-RESERVED 126) ; reserved keywords
611
612 (defvar js2-EMPTY 127)
613
614 ;; Types used for the parse tree - never returned by scanner.
615
616 (defvar js2-BLOCK 128) ; statement block
617 (defvar js2-LABEL 129) ; label
618 (defvar js2-TARGET 130)
619 (defvar js2-LOOP 131)
620 (defvar js2-EXPR_VOID 132) ; expression statement in functions
621 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
622 (defvar js2-JSR 134)
623 (defvar js2-SCRIPT 135) ; top-level node for entire script
624 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
625 (defvar js2-USE_STACK 137)
626 (defvar js2-SETPROP_OP 138) ; x.y op= something
627 (defvar js2-SETELEM_OP 139) ; x[y] op= something
628 (defvar js2-LOCAL_BLOCK 140)
629 (defvar js2-SET_REF_OP 141) ; *reference op= something
630
631 ;; For XML support:
632 (defvar js2-DOTDOT 142) ; member operator (..)
633 (defvar js2-COLONCOLON 143) ; namespace::name
634 (defvar js2-XML 144) ; XML type
635 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
636 (defvar js2-XMLATTR 146) ; @
637 (defvar js2-XMLEND 147)
638
639 ;; Optimizer-only tokens
640 (defvar js2-TO_OBJECT 148)
641 (defvar js2-TO_DOUBLE 149)
642
643 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
644 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
645 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
646 (defvar js2-CONST 153)
647 (defvar js2-SETCONST 154)
648 (defvar js2-SETCONSTVAR 155)
649 (defvar js2-ARRAYCOMP 156)
650 (defvar js2-LETEXPR 157)
651 (defvar js2-WITHEXPR 158)
652 (defvar js2-DEBUGGER 159)
653
654 (defvar js2-COMMENT 160)
655 (defvar js2-ENUM 161) ; for "enum" reserved word
656 (defvar js2-TRIPLEDOT 162) ; for rest parameter
657 (defvar js2-ARROW 163) ; function arrow (=>)
658
659 (defconst js2-num-tokens (1+ js2-ARROW))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
677
678 ;; FIXME: Unused.
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
684
685 ;; FIXME: Unused.
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (defstruct (js2-token
708 (:constructor nil)
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
711 (type js2-EOF)
712 (beg 1)
713 (end -1)
714 (string "")
715 number
716 regexp-flags
717 comment-type
718 follows-eol-p)
719
720 (defstruct (js2-ts-state
721 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
722 (cursor js2-ts-cursor)
723 (tokens (copy-sequence js2-ti-tokens))
724 (tokens-cursor js2-ti-tokens-cursor)
725 (lookahead js2-ti-lookahead))))
726 lineno
727 cursor
728 tokens
729 tokens-cursor
730 lookahead)
731
732 ;;; Parser variables
733
734 (js2-deflocal js2-parsed-errors nil
735 "List of errors produced during scanning/parsing.")
736
737 (js2-deflocal js2-parsed-warnings nil
738 "List of warnings produced during scanning/parsing.")
739
740 (js2-deflocal js2-recover-from-parse-errors t
741 "Non-nil to continue parsing after a syntax error.
742
743 In recovery mode, the AST will be built in full, and any error
744 nodes will be flagged with appropriate error information. If
745 this flag is nil, a syntax error will result in an error being
746 signaled.
747
748 The variable is automatically buffer-local, because different
749 modes that use the parser will need different settings.")
750
751 (js2-deflocal js2-parse-hook nil
752 "List of callbacks for receiving parsing progress.")
753
754 (defvar js2-parse-finished-hook nil
755 "List of callbacks to notify when parsing finishes.
756 Not called if parsing was interrupted.")
757
758 (js2-deflocal js2-is-eval-code nil
759 "True if we're evaluating code in a string.
760 If non-nil, the tokenizer will record the token text, and the AST nodes
761 will record their source text. Off by default for IDE modes, since the
762 text is available in the buffer.")
763
764 (defvar js2-parse-ide-mode t
765 "Non-nil if the parser is being used for `js2-mode'.
766 If non-nil, the parser will set text properties for fontification
767 and the syntax table. The value should be nil when using the
768 parser as a frontend to an interpreter or byte compiler.")
769
770 ;;; Parser instance variables (buffer-local vars for js2-parse)
771
772 (defconst js2-ti-after-eol (lsh 1 16)
773 "Flag: first token of the source line.")
774
775 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
776
777 (js2-deflocal js2-compiler-generate-debug-info t)
778 (js2-deflocal js2-compiler-use-dynamic-scope nil)
779 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
780 (js2-deflocal js2-compiler-xml-available t)
781 (js2-deflocal js2-compiler-optimization-level 0)
782 (js2-deflocal js2-compiler-generating-source t)
783 (js2-deflocal js2-compiler-strict-mode nil)
784 (js2-deflocal js2-compiler-report-warning-as-error nil)
785 (js2-deflocal js2-compiler-generate-observer-count nil)
786 (js2-deflocal js2-compiler-activation-names nil)
787
788 ;; SKIP: sourceURI
789
790 ;; There's a compileFunction method in Context.java - may need it.
791 (js2-deflocal js2-called-by-compile-function nil
792 "True if `js2-parse' was called by `js2-compile-function'.
793 Will only be used when we finish implementing the interpreter.")
794
795 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
796
797 ;; SKIP: node factory - we're going to just call functions directly,
798 ;; and eventually go to a unified AST format.
799
800 (js2-deflocal js2-nesting-of-function 0)
801
802 (js2-deflocal js2-recorded-identifiers nil
803 "Tracks identifiers found during parsing.")
804
805 (js2-deflocal js2-is-in-destructuring nil
806 "True while parsing destructuring expression.")
807
808 (defcustom js2-global-externs nil
809 "A list of any extern names you'd like to consider always declared.
810 This list is global and is used by all `js2-mode' files.
811 You can create buffer-local externs list using `js2-additional-externs'.
812
813 There is also a buffer-local variable `js2-default-externs',
814 which is initialized by default to include the Ecma-262 externs
815 and the standard browser externs. The three lists are all
816 checked during highlighting."
817 :type 'list
818 :group 'js2-mode)
819
820 (js2-deflocal js2-default-externs nil
821 "Default external declarations.
822
823 These are currently only used for highlighting undeclared variables,
824 which only worries about top-level (unqualified) references.
825 As js2-mode's processing improves, we will flesh out this list.
826
827 The initial value is set to `js2-ecma-262-externs', unless some
828 of the `js2-include-?-externs' variables are set to t, in which
829 case the browser, Rhino and/or Node.js externs are also included.
830
831 See `js2-additional-externs' for more information.")
832
833 (defcustom js2-include-browser-externs t
834 "Non-nil to include browser externs in the master externs list.
835 If you work on JavaScript files that are not intended for browsers,
836 such as Mozilla Rhino server-side JavaScript, set this to nil.
837 See `js2-additional-externs' for more information about externs."
838 :type 'boolean
839 :group 'js2-mode)
840
841 (defcustom js2-include-rhino-externs nil
842 "Non-nil to include Mozilla Rhino externs in the master externs list.
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-node-externs nil
848 "Non-nil to include Node.js externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (js2-deflocal js2-additional-externs nil
854 "A buffer-local list of additional external declarations.
855 It is used to decide whether variables are considered undeclared
856 for purposes of highlighting.
857
858 Each entry is a Lisp string. The string should be the fully qualified
859 name of an external entity. All externs should be added to this list,
860 so that as js2-mode's processing improves it can take advantage of them.
861
862 You may want to declare your externs in three ways.
863 First, you can add externs that are valid for all your JavaScript files.
864 You should probably do this by adding them to `js2-global-externs', which
865 is a global list used for all js2-mode files.
866
867 Next, you can add a function to `js2-init-hook' that adds additional
868 externs appropriate for the specific file, perhaps based on its path.
869 These should go in `js2-additional-externs', which is buffer-local.
870
871 Third, you can use JSLint's global declaration, as long as
872 `js2-include-jslint-globals' is non-nil, which see.
873
874 Finally, you can add a function to `js2-post-parse-callbacks',
875 which is called after parsing completes, and `js2-mode-ast' is bound to
876 the root of the parse tree. At this stage you can set up an AST
877 node visitor using `js2-visit-ast' and examine the parse tree
878 for specific import patterns that may imply the existence of
879 other externs, possibly tied to your build system. These should also
880 be added to `js2-additional-externs'.
881
882 Your post-parse callback may of course also use the simpler and
883 faster (but perhaps less robust) approach of simply scanning the
884 buffer text for your imports, using regular expressions.")
885
886 ;; SKIP: decompiler
887 ;; SKIP: encoded-source
888
889 ;;; The following variables are per-function and should be saved/restored
890 ;;; during function parsing...
891
892 (js2-deflocal js2-current-script-or-fn nil)
893 (js2-deflocal js2-current-scope nil)
894 (js2-deflocal js2-nesting-of-with 0)
895 (js2-deflocal js2-label-set nil
896 "An alist mapping label names to nodes.")
897
898 (js2-deflocal js2-loop-set nil)
899 (js2-deflocal js2-loop-and-switch-set nil)
900 (js2-deflocal js2-has-return-value nil)
901 (js2-deflocal js2-end-flags 0)
902
903 ;;; ...end of per function variables
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.unnamed.function.stmt" ; added by js2-mode
1507 "function statement requires a name")
1508
1509 (js2-msg "msg.no.paren.parms"
1510 "missing ( before function parameters.")
1511
1512 (js2-msg "msg.no.parm"
1513 "missing formal parameter")
1514
1515 (js2-msg "msg.no.paren.after.parms"
1516 "missing ) after formal parameters")
1517
1518 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1519 "parameter without default follows parameter with default")
1520
1521 (js2-msg "msg.param.after.rest" ; added by js2-mode
1522 "parameter after rest parameter")
1523
1524 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1525 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1526
1527 (js2-msg "msg.no.brace.body"
1528 "missing '{' before function body")
1529
1530 (js2-msg "msg.no.brace.after.body"
1531 "missing } after function body")
1532
1533 (js2-msg "msg.no.paren.cond"
1534 "missing ( before condition")
1535
1536 (js2-msg "msg.no.paren.after.cond"
1537 "missing ) after condition")
1538
1539 (js2-msg "msg.no.semi.stmt"
1540 "missing ; before statement")
1541
1542 (js2-msg "msg.missing.semi"
1543 "missing ; after statement")
1544
1545 (js2-msg "msg.no.name.after.dot"
1546 "missing name after . operator")
1547
1548 (js2-msg "msg.no.name.after.coloncolon"
1549 "missing name after :: operator")
1550
1551 (js2-msg "msg.no.name.after.dotdot"
1552 "missing name after .. operator")
1553
1554 (js2-msg "msg.no.name.after.xmlAttr"
1555 "missing name after .@")
1556
1557 (js2-msg "msg.no.bracket.index"
1558 "missing ] in index expression")
1559
1560 (js2-msg "msg.no.paren.switch"
1561 "missing ( before switch expression")
1562
1563 (js2-msg "msg.no.paren.after.switch"
1564 "missing ) after switch expression")
1565
1566 (js2-msg "msg.no.brace.switch"
1567 "missing '{' before switch body")
1568
1569 (js2-msg "msg.bad.switch"
1570 "invalid switch statement")
1571
1572 (js2-msg "msg.no.colon.case"
1573 "missing : after case expression")
1574
1575 (js2-msg "msg.double.switch.default"
1576 "double default label in the switch statement")
1577
1578 (js2-msg "msg.no.while.do"
1579 "missing while after do-loop body")
1580
1581 (js2-msg "msg.no.paren.for"
1582 "missing ( after for")
1583
1584 (js2-msg "msg.no.semi.for"
1585 "missing ; after for-loop initializer")
1586
1587 (js2-msg "msg.no.semi.for.cond"
1588 "missing ; after for-loop condition")
1589
1590 (js2-msg "msg.in.after.for.name"
1591 "missing in or of after for")
1592
1593 (js2-msg "msg.no.paren.for.ctrl"
1594 "missing ) after for-loop control")
1595
1596 (js2-msg "msg.no.paren.with"
1597 "missing ( before with-statement object")
1598
1599 (js2-msg "msg.no.paren.after.with"
1600 "missing ) after with-statement object")
1601
1602 (js2-msg "msg.no.paren.after.let"
1603 "missing ( after let")
1604
1605 (js2-msg "msg.no.paren.let"
1606 "missing ) after variable list")
1607
1608 (js2-msg "msg.no.curly.let"
1609 "missing } after let statement")
1610
1611 (js2-msg "msg.bad.return"
1612 "invalid return")
1613
1614 (js2-msg "msg.no.brace.block"
1615 "missing } in compound statement")
1616
1617 (js2-msg "msg.bad.label"
1618 "invalid label")
1619
1620 (js2-msg "msg.bad.var"
1621 "missing variable name")
1622
1623 (js2-msg "msg.bad.var.init"
1624 "invalid variable initialization")
1625
1626 (js2-msg "msg.no.colon.cond"
1627 "missing : in conditional expression")
1628
1629 (js2-msg "msg.no.paren.arg"
1630 "missing ) after argument list")
1631
1632 (js2-msg "msg.no.bracket.arg"
1633 "missing ] after element list")
1634
1635 (js2-msg "msg.bad.prop"
1636 "invalid property id")
1637
1638 (js2-msg "msg.no.colon.prop"
1639 "missing : after property id")
1640
1641 (js2-msg "msg.no.brace.prop"
1642 "missing } after property list")
1643
1644 (js2-msg "msg.no.paren"
1645 "missing ) in parenthetical")
1646
1647 (js2-msg "msg.reserved.id"
1648 "identifier is a reserved word")
1649
1650 (js2-msg "msg.no.paren.catch"
1651 "missing ( before catch-block condition")
1652
1653 (js2-msg "msg.bad.catchcond"
1654 "invalid catch block condition")
1655
1656 (js2-msg "msg.catch.unreachable"
1657 "any catch clauses following an unqualified catch are unreachable")
1658
1659 (js2-msg "msg.no.brace.try"
1660 "missing '{' before try block")
1661
1662 (js2-msg "msg.no.brace.catchblock"
1663 "missing '{' before catch-block body")
1664
1665 (js2-msg "msg.try.no.catchfinally"
1666 "'try' without 'catch' or 'finally'")
1667
1668 (js2-msg "msg.no.return.value"
1669 "function %s does not always return a value")
1670
1671 (js2-msg "msg.anon.no.return.value"
1672 "anonymous function does not always return a value")
1673
1674 (js2-msg "msg.return.inconsistent"
1675 "return statement is inconsistent with previous usage")
1676
1677 (js2-msg "msg.generator.returns"
1678 "TypeError: generator function '%s' returns a value")
1679
1680 (js2-msg "msg.anon.generator.returns"
1681 "TypeError: anonymous generator function returns a value")
1682
1683 (js2-msg "msg.syntax"
1684 "syntax error")
1685
1686 (js2-msg "msg.unexpected.eof"
1687 "Unexpected end of file")
1688
1689 (js2-msg "msg.XML.bad.form"
1690 "illegally formed XML syntax")
1691
1692 (js2-msg "msg.XML.not.available"
1693 "XML runtime not available")
1694
1695 (js2-msg "msg.too.deep.parser.recursion"
1696 "Too deep recursion while parsing")
1697
1698 (js2-msg "msg.no.side.effects"
1699 "Code has no side effects")
1700
1701 (js2-msg "msg.extra.trailing.comma"
1702 "Trailing comma is not supported in some browsers")
1703
1704 (js2-msg "msg.array.trailing.comma"
1705 "Trailing comma yields different behavior across browsers")
1706
1707 (js2-msg "msg.equal.as.assign"
1708 (concat "Test for equality (==) mistyped as assignment (=)?"
1709 " (parenthesize to suppress warning)"))
1710
1711 (js2-msg "msg.var.hides.arg"
1712 "Variable %s hides argument")
1713
1714 (js2-msg "msg.destruct.assign.no.init"
1715 "Missing = in destructuring declaration")
1716
1717 ;; ScriptRuntime
1718 (js2-msg "msg.no.properties"
1719 "%s has no properties.")
1720
1721 (js2-msg "msg.invalid.iterator"
1722 "Invalid iterator value")
1723
1724 (js2-msg "msg.iterator.primitive"
1725 "__iterator__ returned a primitive value")
1726
1727 (js2-msg "msg.assn.create.strict"
1728 "Assignment to undeclared variable %s")
1729
1730 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1731 "Undeclared variable or function '%s'")
1732
1733 (js2-msg "msg.ref.undefined.prop"
1734 "Reference to undefined property '%s'")
1735
1736 (js2-msg "msg.prop.not.found"
1737 "Property %s not found.")
1738
1739 (js2-msg "msg.invalid.type"
1740 "Invalid JavaScript value of type %s")
1741
1742 (js2-msg "msg.primitive.expected"
1743 "Primitive type expected (had %s instead)")
1744
1745 (js2-msg "msg.namespace.expected"
1746 "Namespace object expected to left of :: (found %s instead)")
1747
1748 (js2-msg "msg.null.to.object"
1749 "Cannot convert null to an object.")
1750
1751 (js2-msg "msg.undef.to.object"
1752 "Cannot convert undefined to an object.")
1753
1754 (js2-msg "msg.cyclic.value"
1755 "Cyclic %s value not allowed.")
1756
1757 (js2-msg "msg.is.not.defined"
1758 "'%s' is not defined.")
1759
1760 (js2-msg "msg.undef.prop.read"
1761 "Cannot read property '%s' from %s")
1762
1763 (js2-msg "msg.undef.prop.write"
1764 "Cannot set property '%s' of %s to '%s'")
1765
1766 (js2-msg "msg.undef.prop.delete"
1767 "Cannot delete property '%s' of %s")
1768
1769 (js2-msg "msg.undef.method.call"
1770 "Cannot call method '%s' of %s")
1771
1772 (js2-msg "msg.undef.with"
1773 "Cannot apply 'with' to %s")
1774
1775 (js2-msg "msg.isnt.function"
1776 "%s is not a function, it is %s.")
1777
1778 (js2-msg "msg.isnt.function.in"
1779 "Cannot call property %s in object %s. "
1780 "It is not a function, it is '%s'.")
1781
1782 (js2-msg "msg.function.not.found"
1783 "Cannot find function %s.")
1784
1785 (js2-msg "msg.function.not.found.in"
1786 "Cannot find function %s in object %s.")
1787
1788 (js2-msg "msg.isnt.xml.object"
1789 "%s is not an xml object.")
1790
1791 (js2-msg "msg.no.ref.to.get"
1792 "%s is not a reference to read reference value.")
1793
1794 (js2-msg "msg.no.ref.to.set"
1795 "%s is not a reference to set reference value to %s.")
1796
1797 (js2-msg "msg.no.ref.from.function"
1798 "Function %s can not be used as the left-hand "
1799 "side of assignment or as an operand of ++ or -- operator.")
1800
1801 (js2-msg "msg.bad.default.value"
1802 "Object's getDefaultValue() method returned an object.")
1803
1804 (js2-msg "msg.instanceof.not.object"
1805 "Can't use instanceof on a non-object.")
1806
1807 (js2-msg "msg.instanceof.bad.prototype"
1808 "'prototype' property of %s is not an object.")
1809
1810 (js2-msg "msg.bad.radix"
1811 "illegal radix %s.")
1812
1813 ;; ScriptableObject
1814 (js2-msg "msg.default.value"
1815 "Cannot find default value for object.")
1816
1817 (js2-msg "msg.zero.arg.ctor"
1818 "Cannot load class '%s' which has no zero-parameter constructor.")
1819
1820 (js2-msg "msg.ctor.multiple.parms"
1821 "Can't define constructor or class %s since more than "
1822 "one constructor has multiple parameters.")
1823
1824 (js2-msg "msg.extend.scriptable"
1825 "%s must extend ScriptableObject in order to define property %s.")
1826
1827 (js2-msg "msg.bad.getter.parms"
1828 "In order to define a property, getter %s must have zero "
1829 "parameters or a single ScriptableObject parameter.")
1830
1831 (js2-msg "msg.obj.getter.parms"
1832 "Expected static or delegated getter %s to take "
1833 "a ScriptableObject parameter.")
1834
1835 (js2-msg "msg.getter.static"
1836 "Getter and setter must both be static or neither be static.")
1837
1838 (js2-msg "msg.setter.return"
1839 "Setter must have void return type: %s")
1840
1841 (js2-msg "msg.setter2.parms"
1842 "Two-parameter setter must take a ScriptableObject as "
1843 "its first parameter.")
1844
1845 (js2-msg "msg.setter1.parms"
1846 "Expected single parameter setter for %s")
1847
1848 (js2-msg "msg.setter2.expected"
1849 "Expected static or delegated setter %s to take two parameters.")
1850
1851 (js2-msg "msg.setter.parms"
1852 "Expected either one or two parameters for setter.")
1853
1854 (js2-msg "msg.setter.bad.type"
1855 "Unsupported parameter type '%s' in setter '%s'.")
1856
1857 (js2-msg "msg.add.sealed"
1858 "Cannot add a property to a sealed object: %s.")
1859
1860 (js2-msg "msg.remove.sealed"
1861 "Cannot remove a property from a sealed object: %s.")
1862
1863 (js2-msg "msg.modify.sealed"
1864 "Cannot modify a property of a sealed object: %s.")
1865
1866 (js2-msg "msg.modify.readonly"
1867 "Cannot modify readonly property: %s.")
1868
1869 ;; TokenStream
1870 (js2-msg "msg.missing.exponent"
1871 "missing exponent")
1872
1873 (js2-msg "msg.caught.nfe"
1874 "number format error")
1875
1876 (js2-msg "msg.unterminated.string.lit"
1877 "unterminated string literal")
1878
1879 (js2-msg "msg.unterminated.comment"
1880 "unterminated comment")
1881
1882 (js2-msg "msg.unterminated.re.lit"
1883 "unterminated regular expression literal")
1884
1885 (js2-msg "msg.invalid.re.flag"
1886 "invalid flag after regular expression")
1887
1888 (js2-msg "msg.no.re.input.for"
1889 "no input for %s")
1890
1891 (js2-msg "msg.illegal.character"
1892 "illegal character")
1893
1894 (js2-msg "msg.invalid.escape"
1895 "invalid Unicode escape sequence")
1896
1897 (js2-msg "msg.bad.namespace"
1898 "not a valid default namespace statement. "
1899 "Syntax is: default xml namespace = EXPRESSION;")
1900
1901 ;; TokensStream warnings
1902 (js2-msg "msg.bad.octal.literal"
1903 "illegal octal literal digit %s; "
1904 "interpreting it as a decimal digit")
1905
1906 (js2-msg "msg.reserved.keyword"
1907 "illegal usage of future reserved keyword %s; "
1908 "interpreting it as ordinary identifier")
1909
1910 (js2-msg "msg.script.is.not.constructor"
1911 "Script objects are not constructors.")
1912
1913 ;; Arrays
1914 (js2-msg "msg.arraylength.bad"
1915 "Inappropriate array length.")
1916
1917 ;; Arrays
1918 (js2-msg "msg.arraylength.too.big"
1919 "Array length %s exceeds supported capacity limit.")
1920
1921 ;; URI
1922 (js2-msg "msg.bad.uri"
1923 "Malformed URI sequence.")
1924
1925 ;; Number
1926 (js2-msg "msg.bad.precision"
1927 "Precision %s out of range.")
1928
1929 ;; NativeGenerator
1930 (js2-msg "msg.send.newborn"
1931 "Attempt to send value to newborn generator")
1932
1933 (js2-msg "msg.already.exec.gen"
1934 "Already executing generator")
1935
1936 (js2-msg "msg.StopIteration.invalid"
1937 "StopIteration may not be changed to an arbitrary object.")
1938
1939 ;; Interpreter
1940 (js2-msg "msg.yield.closing"
1941 "Yield from closing generator")
1942
1943 ;;; Tokens Buffer
1944
1945 (defconst js2-ti-max-lookahead 2)
1946 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1947
1948 ;; Have to call `js2-init-scanner' to initialize the values.
1949 (js2-deflocal js2-ti-tokens nil)
1950 (js2-deflocal js2-ti-tokens-cursor nil)
1951 (js2-deflocal js2-ti-lookahead nil)
1952
1953 (defun js2-new-token (offset)
1954 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1955 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1956 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1957 token))
1958
1959 (defsubst js2-current-token ()
1960 (aref js2-ti-tokens js2-ti-tokens-cursor))
1961
1962 (defsubst js2-current-token-string ()
1963 (js2-token-string (js2-current-token)))
1964
1965 (defsubst js2-current-token-type ()
1966 (js2-token-type (js2-current-token)))
1967
1968 (defsubst js2-current-token-beg ()
1969 (js2-token-beg (js2-current-token)))
1970
1971 (defsubst js2-current-token-end ()
1972 (js2-token-end (js2-current-token)))
1973
1974 (defun js2-current-token-len ()
1975 (let ((token (js2-current-token)))
1976 (- (js2-token-end token)
1977 (js2-token-beg token))))
1978
1979 (defun js2-ts-seek (state)
1980 (setq js2-ts-lineno (js2-ts-state-lineno state)
1981 js2-ts-cursor (js2-ts-state-cursor state)
1982 js2-ti-tokens (js2-ts-state-tokens state)
1983 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1984 js2-ti-lookahead (js2-ts-state-lookahead state)))
1985
1986 ;;; Utilities
1987
1988 (defun js2-delete-if (predicate list)
1989 "Remove all items satisfying PREDICATE in LIST."
1990 (loop for item in list
1991 if (not (funcall predicate item))
1992 collect item))
1993
1994 (defun js2-position (element list)
1995 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1996 Returns nil if element is not found in the list."
1997 (let ((count 0)
1998 found)
1999 (while (and list (not found))
2000 (if (eq element (car list))
2001 (setq found t)
2002 (setq count (1+ count)
2003 list (cdr list))))
2004 (if found count)))
2005
2006 (defun js2-find-if (predicate list)
2007 "Find first item satisfying PREDICATE in LIST."
2008 (let (result)
2009 (while (and list (not result))
2010 (if (funcall predicate (car list))
2011 (setq result (car list)))
2012 (setq list (cdr list)))
2013 result))
2014
2015 (defmacro js2-time (form)
2016 "Evaluate FORM, discard result, and return elapsed time in sec."
2017 (declare (debug t))
2018 (let ((beg (make-symbol "--js2-time-beg--"))
2019 (delta (make-symbol "--js2-time-end--")))
2020 `(let ((,beg (current-time))
2021 ,delta)
2022 ,form
2023 (/ (truncate (* (- (float-time (current-time))
2024 (float-time ,beg))
2025 10000))
2026 10000.0))))
2027
2028 (defsubst js2-same-line (pos)
2029 "Return t if POS is on the same line as current point."
2030 (and (>= pos (point-at-bol))
2031 (<= pos (point-at-eol))))
2032
2033 (defun js2-code-bug ()
2034 "Signal an error when we encounter an unexpected code path."
2035 (error "failed assertion"))
2036
2037 (defsubst js2-record-text-property (beg end prop value)
2038 "Record a text property to set when parsing finishes."
2039 (push (list beg end prop value) js2-mode-deferred-properties))
2040
2041 ;; I'd like to associate errors with nodes, but for now the
2042 ;; easiest thing to do is get the context info from the last token.
2043 (defun js2-record-parse-error (msg &optional arg pos len)
2044 (push (list (list msg arg)
2045 (or pos (js2-current-token-beg))
2046 (or len (js2-current-token-len)))
2047 js2-parsed-errors))
2048
2049 (defun js2-report-error (msg &optional msg-arg pos len)
2050 "Signal a syntax error or record a parse error."
2051 (if js2-recover-from-parse-errors
2052 (js2-record-parse-error msg msg-arg pos len)
2053 (signal 'js2-syntax-error
2054 (list msg
2055 js2-ts-lineno
2056 (save-excursion
2057 (goto-char js2-ts-cursor)
2058 (current-column))
2059 js2-ts-hit-eof))))
2060
2061 (defun js2-report-warning (msg &optional msg-arg pos len face)
2062 (if js2-compiler-report-warning-as-error
2063 (js2-report-error msg msg-arg pos len)
2064 (push (list (list msg msg-arg)
2065 (or pos (js2-current-token-beg))
2066 (or len (js2-current-token-len))
2067 face)
2068 js2-parsed-warnings)))
2069
2070 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2071 (if js2-compiler-strict-mode
2072 (js2-report-warning msg-id msg-arg beg
2073 (and beg end (- end beg)))))
2074
2075 (put 'js2-syntax-error 'error-conditions
2076 '(error syntax-error js2-syntax-error))
2077 (put 'js2-syntax-error 'error-message "Syntax error")
2078
2079 (put 'js2-parse-error 'error-conditions
2080 '(error parse-error js2-parse-error))
2081 (put 'js2-parse-error 'error-message "Parse error")
2082
2083 (defmacro js2-clear-flag (flags flag)
2084 `(setq ,flags (logand ,flags (lognot ,flag))))
2085
2086 (defmacro js2-set-flag (flags flag)
2087 "Logical-or FLAG into FLAGS."
2088 `(setq ,flags (logior ,flags ,flag)))
2089
2090 (defsubst js2-flag-set-p (flags flag)
2091 (/= 0 (logand flags flag)))
2092
2093 (defsubst js2-flag-not-set-p (flags flag)
2094 (zerop (logand flags flag)))
2095
2096 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2097 "Evaluate BODY with the _ character set to be word-syntax."
2098 (declare (indent 0) (debug t))
2099 (let ((old-syntax (make-symbol "old-syntax")))
2100 `(let ((,old-syntax (string (char-syntax ?_))))
2101 (unwind-protect
2102 (progn
2103 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2104 ,@body)
2105 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2106
2107 (defsubst js2-char-uppercase-p (c)
2108 "Return t if C is an uppercase character.
2109 Handles unicode and latin chars properly."
2110 (/= c (downcase c)))
2111
2112 (defsubst js2-char-lowercase-p (c)
2113 "Return t if C is an uppercase character.
2114 Handles unicode and latin chars properly."
2115 (/= c (upcase c)))
2116
2117 ;;; AST struct and function definitions
2118
2119 ;; flags for ast node property 'member-type (used for e4x operators)
2120 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2121 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2122 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2123
2124 (defsubst js2-relpos (pos anchor)
2125 "Convert POS to be relative to ANCHOR.
2126 If POS is nil, returns nil."
2127 (and pos (- pos anchor)))
2128
2129 (defun js2-make-pad (indent)
2130 (if (zerop indent)
2131 ""
2132 (make-string (* indent js2-basic-offset) ? )))
2133
2134 (defun js2-visit-ast (node callback)
2135 "Visit every node in ast NODE with visitor CALLBACK.
2136
2137 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2138 called twice: once to visit the node, and again after all the node's
2139 children have been processed. The END-P argument is nil on the first
2140 call and non-nil on the second call. The return value of the callback
2141 affects the traversal: if non-nil, the children of NODE are processed.
2142 If the callback returns nil, or if the node has no children, then the
2143 callback is called immediately with a non-nil END-P argument.
2144
2145 The node traversal is approximately lexical-order, although there
2146 are currently no guarantees around this."
2147 (when node
2148 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2149 ;; visit the node
2150 (when (funcall callback node nil)
2151 ;; visit the kids
2152 (cond
2153 ((eq vfunc 'js2-visit-none)
2154 nil) ; don't even bother calling it
2155 ;; Each AST node type has to define a `js2-visitor' function
2156 ;; that takes a node and a callback, and calls `js2-visit-ast'
2157 ;; on each child of the node.
2158 (vfunc
2159 (funcall vfunc node callback))
2160 (t
2161 (error "%s does not define a visitor-traversal function"
2162 (aref node 0)))))
2163 ;; call the end-visit
2164 (funcall callback node t))))
2165
2166 (defstruct (js2-node
2167 (:constructor nil)) ; abstract
2168 "Base AST node type."
2169 (type -1) ; token type
2170 (pos -1) ; start position of this AST node in parsed input
2171 (len 1) ; num characters spanned by the node
2172 props ; optional node property list (an alist)
2173 parent) ; link to parent node; null for root
2174
2175 (defsubst js2-node-get-prop (node prop &optional default)
2176 (or (cadr (assoc prop (js2-node-props node))) default))
2177
2178 (defsubst js2-node-set-prop (node prop value)
2179 (setf (js2-node-props node)
2180 (cons (list prop value) (js2-node-props node))))
2181
2182 (defun js2-fixup-starts (n nodes)
2183 "Adjust the start positions of NODES to be relative to N.
2184 Any node in the list may be nil, for convenience."
2185 (dolist (node nodes)
2186 (when node
2187 (setf (js2-node-pos node) (- (js2-node-pos node)
2188 (js2-node-pos n))))))
2189
2190 (defun js2-node-add-children (parent &rest nodes)
2191 "Set parent node of NODES to PARENT, and return PARENT.
2192 Does nothing if we're not recording parent links.
2193 If any given node in NODES is nil, doesn't record that link."
2194 (js2-fixup-starts parent nodes)
2195 (dolist (node nodes)
2196 (and node
2197 (setf (js2-node-parent node) parent))))
2198
2199 ;; Non-recursive since it's called a frightening number of times.
2200 (defun js2-node-abs-pos (n)
2201 (let ((pos (js2-node-pos n)))
2202 (while (setq n (js2-node-parent n))
2203 (setq pos (+ pos (js2-node-pos n))))
2204 pos))
2205
2206 (defsubst js2-node-abs-end (n)
2207 "Return absolute buffer position of end of N."
2208 (+ (js2-node-abs-pos n) (js2-node-len n)))
2209
2210 ;; It's important to make sure block nodes have a Lisp list for the
2211 ;; child nodes, to limit printing recursion depth in an AST that
2212 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2213 ;; a sufficiently large vector tree.
2214
2215 (defstruct (js2-block-node
2216 (:include js2-node)
2217 (:constructor nil)
2218 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2219 (pos (js2-current-token-beg))
2220 len
2221 props
2222 kids)))
2223 "A block of statements."
2224 kids) ; a Lisp list of the child statement nodes
2225
2226 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2227 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2228
2229 (defun js2-visit-block (ast callback)
2230 "Visit the `js2-block-node' children of AST."
2231 (dolist (kid (js2-block-node-kids ast))
2232 (js2-visit-ast kid callback)))
2233
2234 (defun js2-print-block (n i)
2235 (let ((pad (js2-make-pad i)))
2236 (insert pad "{\n")
2237 (dolist (kid (js2-block-node-kids n))
2238 (js2-print-ast kid (1+ i)))
2239 (insert pad "}")))
2240
2241 (defstruct (js2-scope
2242 (:include js2-block-node)
2243 (:constructor nil)
2244 (:constructor make-js2-scope (&key (type js2-BLOCK)
2245 (pos (js2-current-token-beg))
2246 len
2247 kids)))
2248 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2249 ;; I don't have one of those handy, so I'll use an alist for now.
2250 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2251 ;; and is much lighter-weight to construct (both CPU and mem).
2252 ;; The keys are interned strings (symbols) for faster lookup.
2253 ;; Should switch to hybrid alist/hashtable eventually.
2254 symbol-table ; an alist of (symbol . js2-symbol)
2255 parent-scope ; a `js2-scope'
2256 top) ; top-level `js2-scope' (script/function)
2257
2258 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2259 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2260
2261 (defun js2-node-get-enclosing-scope (node)
2262 "Return the innermost `js2-scope' node surrounding NODE.
2263 Returns nil if there is no enclosing scope node."
2264 (let ((parent (js2-node-parent node)))
2265 (while (not (js2-scope-p parent))
2266 (setq parent (js2-node-parent parent)))
2267 parent))
2268
2269 (defun js2-get-defining-scope (scope name)
2270 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2271 Returns `js2-scope' in which NAME is defined, or nil if not found."
2272 (let ((sym (if (symbolp name)
2273 name
2274 (intern name)))
2275 table
2276 result
2277 (continue t))
2278 (while (and scope continue)
2279 (if (and (setq table (js2-scope-symbol-table scope))
2280 (assq sym table))
2281 (setq continue nil
2282 result scope)
2283 (setq scope (js2-scope-parent-scope scope))))
2284 result))
2285
2286 (defun js2-scope-get-symbol (scope name)
2287 "Return symbol table entry for NAME in SCOPE.
2288 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2289 (and (js2-scope-symbol-table scope)
2290 (cdr (assq (if (symbolp name)
2291 name
2292 (intern name))
2293 (js2-scope-symbol-table scope)))))
2294
2295 (defun js2-scope-put-symbol (scope name symbol)
2296 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2297 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2298 (let* ((table (js2-scope-symbol-table scope))
2299 (sym (if (symbolp name) name (intern name)))
2300 (entry (assq sym table)))
2301 (if entry
2302 (setcdr entry symbol)
2303 (push (cons sym symbol)
2304 (js2-scope-symbol-table scope)))))
2305
2306 (defstruct (js2-symbol
2307 (:constructor nil)
2308 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2309 "A symbol table entry."
2310 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2311 ;; js2-LET, or js2-CONST
2312 decl-type
2313 name ; string
2314 ast-node) ; a `js2-node'
2315
2316 (defstruct (js2-error-node
2317 (:include js2-node)
2318 (:constructor nil) ; silence emacs21 byte-compiler
2319 (:constructor make-js2-error-node (&key (type js2-ERROR)
2320 (pos (js2-current-token-beg))
2321 len)))
2322 "AST node representing a parse error.")
2323
2324 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2325 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2326
2327 (defstruct (js2-script-node
2328 (:include js2-scope)
2329 (:constructor nil)
2330 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2331 (pos (js2-current-token-beg))
2332 len
2333 ;; FIXME: What are those?
2334 var-decls
2335 fun-decls)))
2336 functions ; Lisp list of nested functions
2337 regexps ; Lisp list of (string . flags)
2338 symbols ; alist (every symbol gets unique index)
2339 (param-count 0)
2340 var-names ; vector of string names
2341 consts ; bool-vector matching var-decls
2342 (temp-number 0)) ; for generating temp variables
2343
2344 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2345 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2346
2347 (defun js2-print-script (node indent)
2348 (dolist (kid (js2-block-node-kids node))
2349 (js2-print-ast kid indent)))
2350
2351 (defstruct (js2-ast-root
2352 (:include js2-script-node)
2353 (:constructor nil)
2354 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2355 (pos (js2-current-token-beg))
2356 len
2357 buffer)))
2358 "The root node of a js2 AST."
2359 buffer ; the source buffer from which the code was parsed
2360 comments ; a Lisp list of comments, ordered by start position
2361 errors ; a Lisp list of errors found during parsing
2362 warnings ; a Lisp list of warnings found during parsing
2363 node-count) ; number of nodes in the tree, including the root
2364
2365 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2366 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2367
2368 (defun js2-visit-ast-root (ast callback)
2369 (dolist (kid (js2-ast-root-kids ast))
2370 (js2-visit-ast kid callback))
2371 (dolist (comment (js2-ast-root-comments ast))
2372 (js2-visit-ast comment callback)))
2373
2374 (defstruct (js2-comment-node
2375 (:include js2-node)
2376 (:constructor nil)
2377 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2378 (pos (js2-current-token-beg))
2379 len
2380 format)))
2381 format) ; 'line, 'block, 'jsdoc or 'html
2382
2383 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2384 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2385
2386 (defun js2-print-comment (n i)
2387 ;; We really ought to link end-of-line comments to their nodes.
2388 ;; Or maybe we could add a new comment type, 'endline.
2389 (insert (js2-make-pad i)
2390 (js2-node-string n)))
2391
2392 (defstruct (js2-expr-stmt-node
2393 (:include js2-node)
2394 (:constructor nil)
2395 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2396 (pos js2-ts-cursor)
2397 len
2398 expr)))
2399 "An expression statement."
2400 expr)
2401
2402 (defsubst js2-expr-stmt-node-set-has-result (node)
2403 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2404 (setf (js2-node-type node) js2-EXPR_RESULT))
2405
2406 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2407 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2408
2409 (defun js2-visit-expr-stmt-node (n v)
2410 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2411
2412 (defun js2-print-expr-stmt-node (n indent)
2413 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2414 (insert ";\n"))
2415
2416 (defstruct (js2-loop-node
2417 (:include js2-scope)
2418 (:constructor nil))
2419 "Abstract supertype of loop nodes."
2420 body ; a `js2-block-node'
2421 lp ; position of left-paren, nil if omitted
2422 rp) ; position of right-paren, nil if omitted
2423
2424 (defstruct (js2-do-node
2425 (:include js2-loop-node)
2426 (:constructor nil)
2427 (:constructor make-js2-do-node (&key (type js2-DO)
2428 (pos (js2-current-token-beg))
2429 len
2430 body
2431 condition
2432 while-pos
2433 lp
2434 rp)))
2435 "AST node for do-loop."
2436 condition ; while (expression)
2437 while-pos) ; buffer position of 'while' keyword
2438
2439 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2440 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2441
2442 (defun js2-visit-do-node (n v)
2443 (js2-visit-ast (js2-do-node-body n) v)
2444 (js2-visit-ast (js2-do-node-condition n) v))
2445
2446 (defun js2-print-do-node (n i)
2447 (let ((pad (js2-make-pad i)))
2448 (insert pad "do {\n")
2449 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2450 (js2-print-ast kid (1+ i)))
2451 (insert pad "} while (")
2452 (js2-print-ast (js2-do-node-condition n) 0)
2453 (insert ");\n")))
2454
2455 (defstruct (js2-while-node
2456 (:include js2-loop-node)
2457 (:constructor nil)
2458 (:constructor make-js2-while-node (&key (type js2-WHILE)
2459 (pos (js2-current-token-beg))
2460 len body
2461 condition lp
2462 rp)))
2463 "AST node for while-loop."
2464 condition) ; while-condition
2465
2466 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2467 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2468
2469 (defun js2-visit-while-node (n v)
2470 (js2-visit-ast (js2-while-node-condition n) v)
2471 (js2-visit-ast (js2-while-node-body n) v))
2472
2473 (defun js2-print-while-node (n i)
2474 (let ((pad (js2-make-pad i)))
2475 (insert pad "while (")
2476 (js2-print-ast (js2-while-node-condition n) 0)
2477 (insert ") {\n")
2478 (js2-print-body (js2-while-node-body n) (1+ i))
2479 (insert pad "}\n")))
2480
2481 (defstruct (js2-for-node
2482 (:include js2-loop-node)
2483 (:constructor nil)
2484 (:constructor make-js2-for-node (&key (type js2-FOR)
2485 (pos js2-ts-cursor)
2486 len body init
2487 condition
2488 update lp rp)))
2489 "AST node for a C-style for-loop."
2490 init ; initialization expression
2491 condition ; loop condition
2492 update) ; update clause
2493
2494 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2495 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2496
2497 (defun js2-visit-for-node (n v)
2498 (js2-visit-ast (js2-for-node-init n) v)
2499 (js2-visit-ast (js2-for-node-condition n) v)
2500 (js2-visit-ast (js2-for-node-update n) v)
2501 (js2-visit-ast (js2-for-node-body n) v))
2502
2503 (defun js2-print-for-node (n i)
2504 (let ((pad (js2-make-pad i)))
2505 (insert pad "for (")
2506 (js2-print-ast (js2-for-node-init n) 0)
2507 (insert "; ")
2508 (js2-print-ast (js2-for-node-condition n) 0)
2509 (insert "; ")
2510 (js2-print-ast (js2-for-node-update n) 0)
2511 (insert ") {\n")
2512 (js2-print-body (js2-for-node-body n) (1+ i))
2513 (insert pad "}\n")))
2514
2515 (defstruct (js2-for-in-node
2516 (:include js2-loop-node)
2517 (:constructor nil)
2518 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2519 (pos js2-ts-cursor)
2520 len body
2521 iterator
2522 object
2523 in-pos
2524 each-pos
2525 foreach-p forof-p
2526 lp rp)))
2527 "AST node for a for..in loop."
2528 iterator ; [var] foo in ...
2529 object ; object over which we're iterating
2530 in-pos ; buffer position of 'in' keyword
2531 each-pos ; buffer position of 'each' keyword, if foreach-p
2532 foreach-p ; t if it's a for-each loop
2533 forof-p) ; t if it's a for-of loop
2534
2535 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2536 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2537
2538 (defun js2-visit-for-in-node (n v)
2539 (js2-visit-ast (js2-for-in-node-iterator n) v)
2540 (js2-visit-ast (js2-for-in-node-object n) v)
2541 (js2-visit-ast (js2-for-in-node-body n) v))
2542
2543 (defun js2-print-for-in-node (n i)
2544 (let ((pad (js2-make-pad i))
2545 (foreach (js2-for-in-node-foreach-p n))
2546 (forof (js2-for-in-node-forof-p n)))
2547 (insert pad "for ")
2548 (if foreach
2549 (insert "each "))
2550 (insert "(")
2551 (js2-print-ast (js2-for-in-node-iterator n) 0)
2552 (insert (if forof " of " " in "))
2553 (js2-print-ast (js2-for-in-node-object n) 0)
2554 (insert ") {\n")
2555 (js2-print-body (js2-for-in-node-body n) (1+ i))
2556 (insert pad "}\n")))
2557
2558 (defstruct (js2-return-node
2559 (:include js2-node)
2560 (:constructor nil)
2561 (:constructor make-js2-return-node (&key (type js2-RETURN)
2562 (pos js2-ts-cursor)
2563 len
2564 retval)))
2565 "AST node for a return statement."
2566 retval) ; expression to return, or 'undefined
2567
2568 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2569 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2570
2571 (defun js2-visit-return-node (n v)
2572 (js2-visit-ast (js2-return-node-retval n) v))
2573
2574 (defun js2-print-return-node (n i)
2575 (insert (js2-make-pad i) "return")
2576 (when (js2-return-node-retval n)
2577 (insert " ")
2578 (js2-print-ast (js2-return-node-retval n) 0))
2579 (insert ";\n"))
2580
2581 (defstruct (js2-if-node
2582 (:include js2-node)
2583 (:constructor nil)
2584 (:constructor make-js2-if-node (&key (type js2-IF)
2585 (pos js2-ts-cursor)
2586 len condition
2587 then-part
2588 else-pos
2589 else-part lp
2590 rp)))
2591 "AST node for an if-statement."
2592 condition ; expression
2593 then-part ; statement or block
2594 else-pos ; optional buffer position of 'else' keyword
2595 else-part ; optional statement or block
2596 lp ; position of left-paren, nil if omitted
2597 rp) ; position of right-paren, nil if omitted
2598
2599 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2600 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2601
2602 (defun js2-visit-if-node (n v)
2603 (js2-visit-ast (js2-if-node-condition n) v)
2604 (js2-visit-ast (js2-if-node-then-part n) v)
2605 (js2-visit-ast (js2-if-node-else-part n) v))
2606
2607 (defun js2-print-if-node (n i)
2608 (let ((pad (js2-make-pad i))
2609 (then-part (js2-if-node-then-part n))
2610 (else-part (js2-if-node-else-part n)))
2611 (insert pad "if (")
2612 (js2-print-ast (js2-if-node-condition n) 0)
2613 (insert ") {\n")
2614 (js2-print-body then-part (1+ i))
2615 (insert pad "}")
2616 (cond
2617 ((not else-part)
2618 (insert "\n"))
2619 ((js2-if-node-p else-part)
2620 (insert " else ")
2621 (js2-print-body else-part i))
2622 (t
2623 (insert " else {\n")
2624 (js2-print-body else-part (1+ i))
2625 (insert pad "}\n")))))
2626
2627 (defstruct (js2-try-node
2628 (:include js2-node)
2629 (:constructor nil)
2630 (:constructor make-js2-try-node (&key (type js2-TRY)
2631 (pos js2-ts-cursor)
2632 len
2633 try-block
2634 catch-clauses
2635 finally-block)))
2636 "AST node for a try-statement."
2637 try-block
2638 catch-clauses ; a Lisp list of `js2-catch-node'
2639 finally-block) ; a `js2-finally-node'
2640
2641 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2642 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2643
2644 (defun js2-visit-try-node (n v)
2645 (js2-visit-ast (js2-try-node-try-block n) v)
2646 (dolist (clause (js2-try-node-catch-clauses n))
2647 (js2-visit-ast clause v))
2648 (js2-visit-ast (js2-try-node-finally-block n) v))
2649
2650 (defun js2-print-try-node (n i)
2651 (let ((pad (js2-make-pad i))
2652 (catches (js2-try-node-catch-clauses n))
2653 (finally (js2-try-node-finally-block n)))
2654 (insert pad "try {\n")
2655 (js2-print-body (js2-try-node-try-block n) (1+ i))
2656 (insert pad "}")
2657 (when catches
2658 (dolist (catch catches)
2659 (js2-print-ast catch i)))
2660 (if finally
2661 (js2-print-ast finally i)
2662 (insert "\n"))))
2663
2664 (defstruct (js2-catch-node
2665 (:include js2-node)
2666 (:constructor nil)
2667 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2668 (pos js2-ts-cursor)
2669 len
2670 param
2671 guard-kwd
2672 guard-expr
2673 block lp
2674 rp)))
2675 "AST node for a catch clause."
2676 param ; destructuring form or simple name node
2677 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2678 guard-expr ; catch condition, a `js2-node'
2679 block ; statements, a `js2-block-node'
2680 lp ; buffer position of left-paren, nil if omitted
2681 rp) ; buffer position of right-paren, nil if omitted
2682
2683 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2684 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2685
2686 (defun js2-visit-catch-node (n v)
2687 (js2-visit-ast (js2-catch-node-param n) v)
2688 (when (js2-catch-node-guard-kwd n)
2689 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2690 (js2-visit-ast (js2-catch-node-block n) v))
2691
2692 (defun js2-print-catch-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (guard-kwd (js2-catch-node-guard-kwd n))
2695 (guard-expr (js2-catch-node-guard-expr n)))
2696 (insert " catch (")
2697 (js2-print-ast (js2-catch-node-param n) 0)
2698 (when guard-kwd
2699 (insert " if ")
2700 (js2-print-ast guard-expr 0))
2701 (insert ") {\n")
2702 (js2-print-body (js2-catch-node-block n) (1+ i))
2703 (insert pad "}")))
2704
2705 (defstruct (js2-finally-node
2706 (:include js2-node)
2707 (:constructor nil)
2708 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2709 (pos js2-ts-cursor)
2710 len body)))
2711 "AST node for a finally clause."
2712 body) ; a `js2-node', often but not always a block node
2713
2714 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2715 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2716
2717 (defun js2-visit-finally-node (n v)
2718 (js2-visit-ast (js2-finally-node-body n) v))
2719
2720 (defun js2-print-finally-node (n i)
2721 (let ((pad (js2-make-pad i)))
2722 (insert " finally {\n")
2723 (js2-print-body (js2-finally-node-body n) (1+ i))
2724 (insert pad "}\n")))
2725
2726 (defstruct (js2-switch-node
2727 (:include js2-node)
2728 (:constructor nil)
2729 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2730 (pos js2-ts-cursor)
2731 len
2732 discriminant
2733 cases lp
2734 rp)))
2735 "AST node for a switch statement."
2736 discriminant ; a `js2-node' (switch expression)
2737 cases ; a Lisp list of `js2-case-node'
2738 lp ; position of open-paren for discriminant, nil if omitted
2739 rp) ; position of close-paren for discriminant, nil if omitted
2740
2741 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2742 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2743
2744 (defun js2-visit-switch-node (n v)
2745 (js2-visit-ast (js2-switch-node-discriminant n) v)
2746 (dolist (c (js2-switch-node-cases n))
2747 (js2-visit-ast c v)))
2748
2749 (defun js2-print-switch-node (n i)
2750 (let ((pad (js2-make-pad i))
2751 (cases (js2-switch-node-cases n)))
2752 (insert pad "switch (")
2753 (js2-print-ast (js2-switch-node-discriminant n) 0)
2754 (insert ") {\n")
2755 (dolist (case cases)
2756 (js2-print-ast case i))
2757 (insert pad "}\n")))
2758
2759 (defstruct (js2-case-node
2760 (:include js2-block-node)
2761 (:constructor nil)
2762 (:constructor make-js2-case-node (&key (type js2-CASE)
2763 (pos js2-ts-cursor)
2764 len kids expr)))
2765 "AST node for a case clause of a switch statement."
2766 expr) ; the case expression (nil for default)
2767
2768 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2769 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2770
2771 (defun js2-visit-case-node (n v)
2772 (js2-visit-ast (js2-case-node-expr n) v)
2773 (js2-visit-block n v))
2774
2775 (defun js2-print-case-node (n i)
2776 (let ((pad (js2-make-pad i))
2777 (expr (js2-case-node-expr n)))
2778 (insert pad)
2779 (if (null expr)
2780 (insert "default:\n")
2781 (insert "case ")
2782 (js2-print-ast expr 0)
2783 (insert ":\n"))
2784 (dolist (kid (js2-case-node-kids n))
2785 (js2-print-ast kid (1+ i)))))
2786
2787 (defstruct (js2-throw-node
2788 (:include js2-node)
2789 (:constructor nil)
2790 (:constructor make-js2-throw-node (&key (type js2-THROW)
2791 (pos js2-ts-cursor)
2792 len expr)))
2793 "AST node for a throw statement."
2794 expr) ; the expression to throw
2795
2796 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2797 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2798
2799 (defun js2-visit-throw-node (n v)
2800 (js2-visit-ast (js2-throw-node-expr n) v))
2801
2802 (defun js2-print-throw-node (n i)
2803 (insert (js2-make-pad i) "throw ")
2804 (js2-print-ast (js2-throw-node-expr n) 0)
2805 (insert ";\n"))
2806
2807 (defstruct (js2-with-node
2808 (:include js2-node)
2809 (:constructor nil)
2810 (:constructor make-js2-with-node (&key (type js2-WITH)
2811 (pos js2-ts-cursor)
2812 len object
2813 body lp rp)))
2814 "AST node for a with-statement."
2815 object
2816 body
2817 lp ; buffer position of left-paren around object, nil if omitted
2818 rp) ; buffer position of right-paren around object, nil if omitted
2819
2820 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2821 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2822
2823 (defun js2-visit-with-node (n v)
2824 (js2-visit-ast (js2-with-node-object n) v)
2825 (js2-visit-ast (js2-with-node-body n) v))
2826
2827 (defun js2-print-with-node (n i)
2828 (let ((pad (js2-make-pad i)))
2829 (insert pad "with (")
2830 (js2-print-ast (js2-with-node-object n) 0)
2831 (insert ") {\n")
2832 (js2-print-body (js2-with-node-body n) (1+ i))
2833 (insert pad "}\n")))
2834
2835 (defstruct (js2-label-node
2836 (:include js2-node)
2837 (:constructor nil)
2838 (:constructor make-js2-label-node (&key (type js2-LABEL)
2839 (pos js2-ts-cursor)
2840 len name)))
2841 "AST node for a statement label or case label."
2842 name ; a string
2843 loop) ; for validating and code-generating continue-to-label
2844
2845 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2846 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2847
2848 (defun js2-print-label (n i)
2849 (insert (js2-make-pad i)
2850 (js2-label-node-name n)
2851 ":\n"))
2852
2853 (defstruct (js2-labeled-stmt-node
2854 (:include js2-node)
2855 (:constructor nil)
2856 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2857 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2858 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2859 (pos js2-ts-cursor)
2860 len labels stmt)))
2861 "AST node for a statement with one or more labels.
2862 Multiple labels for a statement are collapsed into the labels field."
2863 labels ; Lisp list of `js2-label-node'
2864 stmt) ; the statement these labels are for
2865
2866 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2867 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2868
2869 (defun js2-get-label-by-name (lbl-stmt name)
2870 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2871 Returns nil if no such label is in the list."
2872 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2873 result)
2874 (while (and label-list (not result))
2875 (if (string= (js2-label-node-name (car label-list)) name)
2876 (setq result (car label-list))
2877 (setq label-list (cdr label-list))))
2878 result))
2879
2880 (defun js2-visit-labeled-stmt (n v)
2881 (dolist (label (js2-labeled-stmt-node-labels n))
2882 (js2-visit-ast label v))
2883 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2884
2885 (defun js2-print-labeled-stmt (n i)
2886 (dolist (label (js2-labeled-stmt-node-labels n))
2887 (js2-print-ast label i))
2888 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2889
2890 (defun js2-labeled-stmt-node-contains (node label)
2891 "Return t if NODE contains LABEL in its label set.
2892 NODE is a `js2-labels-node'. LABEL is an identifier."
2893 (loop for nl in (js2-labeled-stmt-node-labels node)
2894 if (string= label (js2-label-node-name nl))
2895 return t
2896 finally return nil))
2897
2898 (defsubst js2-labeled-stmt-node-add-label (node label)
2899 "Add a `js2-label-node' to the label set for this statement."
2900 (setf (js2-labeled-stmt-node-labels node)
2901 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2902
2903 (defstruct (js2-jump-node
2904 (:include js2-node)
2905 (:constructor nil))
2906 "Abstract supertype of break and continue nodes."
2907 label ; `js2-name-node' for location of label identifier, if present
2908 target) ; target js2-labels-node or loop/switch statement
2909
2910 (defun js2-visit-jump-node (n v)
2911 ;; We don't visit the target, since it's a back-link.
2912 (js2-visit-ast (js2-jump-node-label n) v))
2913
2914 (defstruct (js2-break-node
2915 (:include js2-jump-node)
2916 (:constructor nil)
2917 (:constructor make-js2-break-node (&key (type js2-BREAK)
2918 (pos js2-ts-cursor)
2919 len label target)))
2920 "AST node for a break statement.
2921 The label field is a `js2-name-node', possibly nil, for the named label
2922 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2923 is the target of the break - a label node or enclosing loop/switch statement.")
2924
2925 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2926 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2927
2928 (defun js2-print-break-node (n i)
2929 (insert (js2-make-pad i) "break")
2930 (when (js2-break-node-label n)
2931 (insert " ")
2932 (js2-print-ast (js2-break-node-label n) 0))
2933 (insert ";\n"))
2934
2935 (defstruct (js2-continue-node
2936 (:include js2-jump-node)
2937 (:constructor nil)
2938 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2939 (pos js2-ts-cursor)
2940 len label target)))
2941 "AST node for a continue statement.
2942 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2943 It is nil if continue specifies no label. The target field is the jump target:
2944 a `js2-label-node' or the innermost enclosing loop.")
2945
2946 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2947 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2948
2949 (defun js2-print-continue-node (n i)
2950 (insert (js2-make-pad i) "continue")
2951 (when (js2-continue-node-label n)
2952 (insert " ")
2953 (js2-print-ast (js2-continue-node-label n) 0))
2954 (insert ";\n"))
2955
2956 (defstruct (js2-function-node
2957 (:include js2-script-node)
2958 (:constructor nil)
2959 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2960 (pos js2-ts-cursor)
2961 len
2962 (ftype 'FUNCTION)
2963 (form 'FUNCTION_STATEMENT)
2964 (name "")
2965 params rest-p
2966 body
2967 lp rp)))
2968 "AST node for a function declaration.
2969 The `params' field is a Lisp list of nodes. Each node is either a simple
2970 `js2-name-node', or if it's a destructuring-assignment parameter, a
2971 `js2-array-node' or `js2-object-node'."
2972 ftype ; FUNCTION, GETTER or SETTER
2973 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2974 name ; function name (a `js2-name-node', or nil if anonymous)
2975 params ; a Lisp list of destructuring forms or simple name nodes
2976 rest-p ; if t, the last parameter is rest parameter
2977 body ; a `js2-block-node' or expression node (1.8 only)
2978 lp ; position of arg-list open-paren, or nil if omitted
2979 rp ; position of arg-list close-paren, or nil if omitted
2980 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2981 needs-activation ; t if we need an activation object for this frame
2982 is-generator ; t if this function contains a yield
2983 member-expr) ; nonstandard Ecma extension from Rhino
2984
2985 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2986 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2987
2988 (defun js2-visit-function-node (n v)
2989 (js2-visit-ast (js2-function-node-name n) v)
2990 (dolist (p (js2-function-node-params n))
2991 (js2-visit-ast p v))
2992 (js2-visit-ast (js2-function-node-body n) v))
2993
2994 (defun js2-print-function-node (n i)
2995 (let* ((pad (js2-make-pad i))
2996 (getter (js2-node-get-prop n 'GETTER_SETTER))
2997 (name (or (js2-function-node-name n)
2998 (js2-function-node-member-expr n)))
2999 (params (js2-function-node-params n))
3000 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3001 (rest-p (js2-function-node-rest-p n))
3002 (body (js2-function-node-body n))
3003 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3004 (unless (or getter arrow)
3005 (insert pad "function"))
3006 (when name
3007 (insert " ")
3008 (js2-print-ast name 0))
3009 (insert "(")
3010 (loop with len = (length params)
3011 for param in params
3012 for count from 1
3013 do
3014 (when (and rest-p (= count len))
3015 (insert "..."))
3016 (js2-print-ast param 0)
3017 (when (< count len)
3018 (insert ", ")))
3019 (insert ") ")
3020 (when arrow
3021 (insert "=> "))
3022 (insert "{")
3023 ;; TODO: fix this to be smarter about indenting, etc.
3024 (unless expr
3025 (insert "\n"))
3026 (if (js2-block-node-p body)
3027 (js2-print-body body (1+ i))
3028 (js2-print-ast body 0))
3029 (insert pad "}")
3030 (unless expr
3031 (insert "\n"))))
3032
3033 (defun js2-function-name (node)
3034 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3035 (and (js2-function-node-name node)
3036 (js2-name-node-name (js2-function-node-name node))))
3037
3038 ;; Having this be an expression node makes it more flexible.
3039 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3040 ;; that work better if you assume it's an expression. Whenever we have
3041 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3042 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3043 (defstruct (js2-var-decl-node
3044 (:include js2-node)
3045 (:constructor nil)
3046 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3047 (pos (js2-current-token-beg))
3048 len kids
3049 decl-type)))
3050 "AST node for a variable declaration list (VAR, CONST or LET).
3051 The node bounds differ depending on the declaration type. For VAR or
3052 CONST declarations, the bounds include the var/const keyword. For LET
3053 declarations, the node begins at the position of the first child."
3054 kids ; a Lisp list of `js2-var-init-node' structs.
3055 decl-type) ; js2-VAR, js2-CONST or js2-LET
3056
3057 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3058 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3059
3060 (defun js2-visit-var-decl (n v)
3061 (dolist (kid (js2-var-decl-node-kids n))
3062 (js2-visit-ast kid v)))
3063
3064 (defun js2-print-var-decl (n i)
3065 (let ((pad (js2-make-pad i))
3066 (tt (js2-var-decl-node-decl-type n)))
3067 (insert pad)
3068 (insert (cond
3069 ((= tt js2-VAR) "var ")
3070 ((= tt js2-LET) "let ")
3071 ((= tt js2-CONST) "const ")
3072 (t
3073 (error "malformed var-decl node"))))
3074 (loop with kids = (js2-var-decl-node-kids n)
3075 with len = (length kids)
3076 for kid in kids
3077 for count from 1
3078 do
3079 (js2-print-ast kid 0)
3080 (if (< count len)
3081 (insert ", ")))))
3082
3083 (defstruct (js2-var-init-node
3084 (:include js2-node)
3085 (:constructor nil)
3086 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3087 (pos js2-ts-cursor)
3088 len target
3089 initializer)))
3090 "AST node for a variable declaration.
3091 The type field will be js2-CONST for a const decl."
3092 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3093 initializer) ; initializer expression, a `js2-node'
3094
3095 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3096 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3097
3098 (defun js2-visit-var-init-node (n v)
3099 (js2-visit-ast (js2-var-init-node-target n) v)
3100 (js2-visit-ast (js2-var-init-node-initializer n) v))
3101
3102 (defun js2-print-var-init-node (n i)
3103 (let ((pad (js2-make-pad i))
3104 (name (js2-var-init-node-target n))
3105 (init (js2-var-init-node-initializer n)))
3106 (insert pad)
3107 (js2-print-ast name 0)
3108 (when init
3109 (insert " = ")
3110 (js2-print-ast init 0))))
3111
3112 (defstruct (js2-cond-node
3113 (:include js2-node)
3114 (:constructor nil)
3115 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3116 (pos js2-ts-cursor)
3117 len
3118 test-expr
3119 true-expr
3120 false-expr
3121 q-pos c-pos)))
3122 "AST node for the ternary operator"
3123 test-expr
3124 true-expr
3125 false-expr
3126 q-pos ; buffer position of ?
3127 c-pos) ; buffer position of :
3128
3129 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3130 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3131
3132 (defun js2-visit-cond-node (n v)
3133 (js2-visit-ast (js2-cond-node-test-expr n) v)
3134 (js2-visit-ast (js2-cond-node-true-expr n) v)
3135 (js2-visit-ast (js2-cond-node-false-expr n) v))
3136
3137 (defun js2-print-cond-node (n i)
3138 (let ((pad (js2-make-pad i)))
3139 (insert pad)
3140 (js2-print-ast (js2-cond-node-test-expr n) 0)
3141 (insert " ? ")
3142 (js2-print-ast (js2-cond-node-true-expr n) 0)
3143 (insert " : ")
3144 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3145
3146 (defstruct (js2-infix-node
3147 (:include js2-node)
3148 (:constructor nil)
3149 (:constructor make-js2-infix-node (&key type
3150 (pos js2-ts-cursor)
3151 len op-pos
3152 left right)))
3153 "Represents infix expressions.
3154 Includes assignment ops like `|=', and the comma operator.
3155 The type field inherited from `js2-node' holds the operator."
3156 op-pos ; buffer position where operator begins
3157 left ; any `js2-node'
3158 right) ; any `js2-node'
3159
3160 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3161 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3162
3163 (defun js2-visit-infix-node (n v)
3164 (js2-visit-ast (js2-infix-node-left n) v)
3165 (js2-visit-ast (js2-infix-node-right n) v))
3166
3167 (defconst js2-operator-tokens
3168 (let ((table (make-hash-table :test 'eq))
3169 (tokens
3170 (list (cons js2-IN "in")
3171 (cons js2-TYPEOF "typeof")
3172 (cons js2-INSTANCEOF "instanceof")
3173 (cons js2-DELPROP "delete")
3174 (cons js2-COMMA ",")
3175 (cons js2-COLON ":")
3176 (cons js2-OR "||")
3177 (cons js2-AND "&&")
3178 (cons js2-INC "++")
3179 (cons js2-DEC "--")
3180 (cons js2-BITOR "|")
3181 (cons js2-BITXOR "^")
3182 (cons js2-BITAND "&")
3183 (cons js2-EQ "==")
3184 (cons js2-NE "!=")
3185 (cons js2-LT "<")
3186 (cons js2-LE "<=")
3187 (cons js2-GT ">")
3188 (cons js2-GE ">=")
3189 (cons js2-LSH "<<")
3190 (cons js2-RSH ">>")
3191 (cons js2-URSH ">>>")
3192 (cons js2-ADD "+") ; infix plus
3193 (cons js2-SUB "-") ; infix minus
3194 (cons js2-MUL "*")
3195 (cons js2-DIV "/")
3196 (cons js2-MOD "%")
3197 (cons js2-NOT "!")
3198 (cons js2-BITNOT "~")
3199 (cons js2-POS "+") ; unary plus
3200 (cons js2-NEG "-") ; unary minus
3201 (cons js2-SHEQ "===") ; shallow equality
3202 (cons js2-SHNE "!==") ; shallow inequality
3203 (cons js2-ASSIGN "=")
3204 (cons js2-ASSIGN_BITOR "|=")
3205 (cons js2-ASSIGN_BITXOR "^=")
3206 (cons js2-ASSIGN_BITAND "&=")
3207 (cons js2-ASSIGN_LSH "<<=")
3208 (cons js2-ASSIGN_RSH ">>=")
3209 (cons js2-ASSIGN_URSH ">>>=")
3210 (cons js2-ASSIGN_ADD "+=")
3211 (cons js2-ASSIGN_SUB "-=")
3212 (cons js2-ASSIGN_MUL "*=")
3213 (cons js2-ASSIGN_DIV "/=")
3214 (cons js2-ASSIGN_MOD "%="))))
3215 (loop for (k . v) in tokens do
3216 (puthash k v table))
3217 table))
3218
3219 (defun js2-print-infix-node (n i)
3220 (let* ((tt (js2-node-type n))
3221 (op (gethash tt js2-operator-tokens)))
3222 (unless op
3223 (error "unrecognized infix operator %s" (js2-node-type n)))
3224 (insert (js2-make-pad i))
3225 (js2-print-ast (js2-infix-node-left n) 0)
3226 (unless (= tt js2-COMMA)
3227 (insert " "))
3228 (insert op)
3229 (insert " ")
3230 (js2-print-ast (js2-infix-node-right n) 0)))
3231
3232 (defstruct (js2-assign-node
3233 (:include js2-infix-node)
3234 (:constructor nil)
3235 (:constructor make-js2-assign-node (&key type
3236 (pos js2-ts-cursor)
3237 len op-pos
3238 left right)))
3239 "Represents any assignment.
3240 The type field holds the actual assignment operator.")
3241
3242 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3243 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3244
3245 (defstruct (js2-unary-node
3246 (:include js2-node)
3247 (:constructor nil)
3248 (:constructor make-js2-unary-node (&key type ; required
3249 (pos js2-ts-cursor)
3250 len operand)))
3251 "AST node type for unary operator nodes.
3252 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3253 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3254 property is added if the operator follows the operand."
3255 operand) ; a `js2-node' expression
3256
3257 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3258 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3259
3260 (defun js2-visit-unary-node (n v)
3261 (js2-visit-ast (js2-unary-node-operand n) v))
3262
3263 (defun js2-print-unary-node (n i)
3264 (let* ((tt (js2-node-type n))
3265 (op (gethash tt js2-operator-tokens))
3266 (postfix (js2-node-get-prop n 'postfix)))
3267 (unless op
3268 (error "unrecognized unary operator %s" tt))
3269 (insert (js2-make-pad i))
3270 (unless postfix
3271 (insert op))
3272 (if (or (= tt js2-TYPEOF)
3273 (= tt js2-DELPROP))
3274 (insert " "))
3275 (js2-print-ast (js2-unary-node-operand n) 0)
3276 (when postfix
3277 (insert op))))
3278
3279 (defstruct (js2-let-node
3280 (:include js2-scope)
3281 (:constructor nil)
3282 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3283 (pos (js2-current-token-beg))
3284 len vars body
3285 lp rp)))
3286 "AST node for a let expression or a let statement.
3287 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3288 vars ; a `js2-var-decl-node'
3289 body ; a `js2-node' representing the expression or body block
3290 lp
3291 rp)
3292
3293 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3294 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3295
3296 (defun js2-visit-let-node (n v)
3297 (js2-visit-ast (js2-let-node-vars n) v)
3298 (js2-visit-ast (js2-let-node-body n) v))
3299
3300 (defun js2-print-let-node (n i)
3301 (insert (js2-make-pad i) "let (")
3302 (js2-print-ast (js2-let-node-vars n) 0)
3303 (insert ") ")
3304 (js2-print-ast (js2-let-node-body n) i))
3305
3306 (defstruct (js2-keyword-node
3307 (:include js2-node)
3308 (:constructor nil)
3309 (:constructor make-js2-keyword-node (&key type
3310 (pos (js2-current-token-beg))
3311 (len (- js2-ts-cursor pos)))))
3312 "AST node representing a literal keyword such as `null'.
3313 Used for `null', `this', `true', `false' and `debugger'.
3314 The node type is set to js2-NULL, js2-THIS, etc.")
3315
3316 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3317 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3318
3319 (defun js2-print-keyword-node (n i)
3320 (insert (js2-make-pad i)
3321 (let ((tt (js2-node-type n)))
3322 (cond
3323 ((= tt js2-THIS) "this")
3324 ((= tt js2-NULL) "null")
3325 ((= tt js2-TRUE) "true")
3326 ((= tt js2-FALSE) "false")
3327 ((= tt js2-DEBUGGER) "debugger")
3328 (t (error "Invalid keyword literal type: %d" tt))))))
3329
3330 (defsubst js2-this-node-p (node)
3331 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3332 (eq (js2-node-type node) js2-THIS))
3333
3334 (defstruct (js2-new-node
3335 (:include js2-node)
3336 (:constructor nil)
3337 (:constructor make-js2-new-node (&key (type js2-NEW)
3338 (pos (js2-current-token-beg))
3339 len target
3340 args initializer
3341 lp rp)))
3342 "AST node for new-expression such as new Foo()."
3343 target ; an identifier or reference
3344 args ; a Lisp list of argument nodes
3345 lp ; position of left-paren, nil if omitted
3346 rp ; position of right-paren, nil if omitted
3347 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3348
3349 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3350 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3351
3352 (defun js2-visit-new-node (n v)
3353 (js2-visit-ast (js2-new-node-target n) v)
3354 (dolist (arg (js2-new-node-args n))
3355 (js2-visit-ast arg v))
3356 (js2-visit-ast (js2-new-node-initializer n) v))
3357
3358 (defun js2-print-new-node (n i)
3359 (insert (js2-make-pad i) "new ")
3360 (js2-print-ast (js2-new-node-target n))
3361 (insert "(")
3362 (js2-print-list (js2-new-node-args n))
3363 (insert ")")
3364 (when (js2-new-node-initializer n)
3365 (insert " ")
3366 (js2-print-ast (js2-new-node-initializer n))))
3367
3368 (defstruct (js2-name-node
3369 (:include js2-node)
3370 (:constructor nil)
3371 (:constructor make-js2-name-node (&key (type js2-NAME)
3372 (pos (js2-current-token-beg))
3373 (len (- js2-ts-cursor
3374 (js2-current-token-beg)))
3375 (name (js2-current-token-string)))))
3376 "AST node for a JavaScript identifier"
3377 name ; a string
3378 scope) ; a `js2-scope' (optional, used for codegen)
3379
3380 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3381 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3382
3383 (defun js2-print-name-node (n i)
3384 (insert (js2-make-pad i)
3385 (js2-name-node-name n)))
3386
3387 (defsubst js2-name-node-length (node)
3388 "Return identifier length of NODE, a `js2-name-node'.
3389 Returns 0 if NODE is nil or its identifier field is nil."
3390 (if node
3391 (length (js2-name-node-name node))
3392 0))
3393
3394 (defstruct (js2-number-node
3395 (:include js2-node)
3396 (:constructor nil)
3397 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3398 (pos (js2-current-token-beg))
3399 (len (- js2-ts-cursor
3400 (js2-current-token-beg)))
3401 (value (js2-current-token-string))
3402 (num-value (js2-token-number
3403 (js2-current-token))))))
3404 "AST node for a number literal."
3405 value ; the original string, e.g. "6.02e23"
3406 num-value) ; the parsed number value
3407
3408 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3409 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3410
3411 (defun js2-print-number-node (n i)
3412 (insert (js2-make-pad i)
3413 (number-to-string (js2-number-node-num-value n))))
3414
3415 (defstruct (js2-regexp-node
3416 (:include js2-node)
3417 (:constructor nil)
3418 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3419 (pos (js2-current-token-beg))
3420 (len (- js2-ts-cursor
3421 (js2-current-token-beg)))
3422 value flags)))
3423 "AST node for a regular expression literal."
3424 value ; the regexp string, without // delimiters
3425 flags) ; a string of flags, e.g. `mi'.
3426
3427 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3428 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3429
3430 (defun js2-print-regexp (n i)
3431 (insert (js2-make-pad i)
3432 "/"
3433 (js2-regexp-node-value n)
3434 "/")
3435 (if (js2-regexp-node-flags n)
3436 (insert (js2-regexp-node-flags n))))
3437
3438 (defstruct (js2-string-node
3439 (:include js2-node)
3440 (:constructor nil)
3441 (:constructor make-js2-string-node (&key (type js2-STRING)
3442 (pos (js2-current-token-beg))
3443 (len (- js2-ts-cursor
3444 (js2-current-token-beg)))
3445 (value (js2-current-token-string)))))
3446 "String literal.
3447 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3448 You can tell the quote type by looking at the first character."
3449 value) ; the characters of the string, including the quotes
3450
3451 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3452 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3453
3454 (defun js2-print-string-node (n i)
3455 (insert (js2-make-pad i)
3456 (js2-node-string n)))
3457
3458 (defstruct (js2-array-node
3459 (:include js2-node)
3460 (:constructor nil)
3461 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3462 (pos js2-ts-cursor)
3463 len elems)))
3464 "AST node for an array literal."
3465 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3466
3467 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3468 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3469
3470 (defun js2-visit-array-node (n v)
3471 (dolist (e (js2-array-node-elems n))
3472 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3473
3474 (defun js2-print-array-node (n i)
3475 (insert (js2-make-pad i) "[")
3476 (js2-print-list (js2-array-node-elems n))
3477 (insert "]"))
3478
3479 (defstruct (js2-object-node
3480 (:include js2-node)
3481 (:constructor nil)
3482 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3483 (pos js2-ts-cursor)
3484 len
3485 elems)))
3486 "AST node for an object literal expression.
3487 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3488 The latter represents abbreviation in destructuring expressions."
3489 elems)
3490
3491 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3492 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3493
3494 (defun js2-visit-object-node (n v)
3495 (dolist (e (js2-object-node-elems n))
3496 (js2-visit-ast e v)))
3497
3498 (defun js2-print-object-node (n i)
3499 (insert (js2-make-pad i) "{")
3500 (js2-print-list (js2-object-node-elems n))
3501 (insert "}"))
3502
3503 (defstruct (js2-object-prop-node
3504 (:include js2-infix-node)
3505 (:constructor nil)
3506 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3507 (pos js2-ts-cursor)
3508 len left
3509 right op-pos)))
3510 "AST node for an object literal prop:value entry.
3511 The `left' field is the property: a name node, string node or number node.
3512 The `right' field is a `js2-node' representing the initializer value.")
3513
3514 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3515 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3516
3517 (defun js2-print-object-prop-node (n i)
3518 (insert (js2-make-pad i))
3519 (js2-print-ast (js2-object-prop-node-left n) 0)
3520 (insert ": ")
3521 (js2-print-ast (js2-object-prop-node-right n) 0))
3522
3523 (defstruct (js2-getter-setter-node
3524 (:include js2-infix-node)
3525 (:constructor nil)
3526 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3527 (pos js2-ts-cursor)
3528 len left right)))
3529 "AST node for a getter/setter property in an object literal.
3530 The `left' field is the `js2-name-node' naming the getter/setter prop.
3531 The `right' field is always an anonymous `js2-function-node' with a node
3532 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3533
3534 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3535 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3536
3537 (defun js2-print-getter-setter (n i)
3538 (let ((pad (js2-make-pad i))
3539 (left (js2-getter-setter-node-left n))
3540 (right (js2-getter-setter-node-right n)))
3541 (insert pad)
3542 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3543 (js2-print-ast left 0)
3544 (js2-print-ast right 0)))
3545
3546 (defstruct (js2-prop-get-node
3547 (:include js2-infix-node)
3548 (:constructor nil)
3549 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3550 (pos js2-ts-cursor)
3551 len left right)))
3552 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3553
3554 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3555 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3556
3557 (defun js2-visit-prop-get-node (n v)
3558 (js2-visit-ast (js2-prop-get-node-left n) v)
3559 (js2-visit-ast (js2-prop-get-node-right n) v))
3560
3561 (defun js2-print-prop-get-node (n i)
3562 (insert (js2-make-pad i))
3563 (js2-print-ast (js2-prop-get-node-left n) 0)
3564 (insert ".")
3565 (js2-print-ast (js2-prop-get-node-right n) 0))
3566
3567 (defstruct (js2-elem-get-node
3568 (:include js2-node)
3569 (:constructor nil)
3570 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3571 (pos js2-ts-cursor)
3572 len target element
3573 lb rb)))
3574 "AST node for an array index expression such as foo[bar]."
3575 target ; a `js2-node' - the expression preceding the "."
3576 element ; a `js2-node' - the expression in brackets
3577 lb ; position of left-bracket, nil if omitted
3578 rb) ; position of right-bracket, nil if omitted
3579
3580 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3581 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3582
3583 (defun js2-visit-elem-get-node (n v)
3584 (js2-visit-ast (js2-elem-get-node-target n) v)
3585 (js2-visit-ast (js2-elem-get-node-element n) v))
3586
3587 (defun js2-print-elem-get-node (n i)
3588 (insert (js2-make-pad i))
3589 (js2-print-ast (js2-elem-get-node-target n) 0)
3590 (insert "[")
3591 (js2-print-ast (js2-elem-get-node-element n) 0)
3592 (insert "]"))
3593
3594 (defstruct (js2-call-node
3595 (:include js2-node)
3596 (:constructor nil)
3597 (:constructor make-js2-call-node (&key (type js2-CALL)
3598 (pos js2-ts-cursor)
3599 len target args
3600 lp rp)))
3601 "AST node for a JavaScript function call."
3602 target ; a `js2-node' evaluating to the function to call
3603 args ; a Lisp list of `js2-node' arguments
3604 lp ; position of open-paren, or nil if missing
3605 rp) ; position of close-paren, or nil if missing
3606
3607 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3608 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3609
3610 (defun js2-visit-call-node (n v)
3611 (js2-visit-ast (js2-call-node-target n) v)
3612 (dolist (arg (js2-call-node-args n))
3613 (js2-visit-ast arg v)))
3614
3615 (defun js2-print-call-node (n i)
3616 (insert (js2-make-pad i))
3617 (js2-print-ast (js2-call-node-target n) 0)
3618 (insert "(")
3619 (js2-print-list (js2-call-node-args n))
3620 (insert ")"))
3621
3622 (defstruct (js2-yield-node
3623 (:include js2-node)
3624 (:constructor nil)
3625 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3626 (pos js2-ts-cursor)
3627 len value)))
3628 "AST node for yield statement or expression."
3629 value) ; optional: value to be yielded
3630
3631 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3632 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3633
3634 (defun js2-visit-yield-node (n v)
3635 (js2-visit-ast (js2-yield-node-value n) v))
3636
3637 (defun js2-print-yield-node (n i)
3638 (insert (js2-make-pad i))
3639 (insert "yield")
3640 (when (js2-yield-node-value n)
3641 (insert " ")
3642 (js2-print-ast (js2-yield-node-value n) 0)))
3643
3644 (defstruct (js2-paren-node
3645 (:include js2-node)
3646 (:constructor nil)
3647 (:constructor make-js2-paren-node (&key (type js2-LP)
3648 (pos js2-ts-cursor)
3649 len expr)))
3650 "AST node for a parenthesized expression.
3651 In particular, used when the parens are syntactically optional,
3652 as opposed to required parens such as those enclosing an if-conditional."
3653 expr) ; `js2-node'
3654
3655 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3656 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3657
3658 (defun js2-visit-paren-node (n v)
3659 (js2-visit-ast (js2-paren-node-expr n) v))
3660
3661 (defun js2-print-paren-node (n i)
3662 (insert (js2-make-pad i))
3663 (insert "(")
3664 (js2-print-ast (js2-paren-node-expr n) 0)
3665 (insert ")"))
3666
3667 (defstruct (js2-array-comp-node
3668 (:include js2-scope)
3669 (:constructor nil)
3670 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3671 (pos js2-ts-cursor)
3672 len result
3673 loops filter
3674 if-pos lp rp)))
3675 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3676 result ; result expression (just after left-bracket)
3677 loops ; a Lisp list of `js2-array-comp-loop-node'
3678 filter ; guard/filter expression
3679 if-pos ; buffer pos of 'if' keyword, if present, else nil
3680 lp ; buffer position of if-guard left-paren, or nil if not present
3681 rp) ; buffer position of if-guard right-paren, or nil if not present
3682
3683 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3684 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3685
3686 (defun js2-visit-array-comp-node (n v)
3687 (js2-visit-ast (js2-array-comp-node-result n) v)
3688 (dolist (l (js2-array-comp-node-loops n))
3689 (js2-visit-ast l v))
3690 (js2-visit-ast (js2-array-comp-node-filter n) v))
3691
3692 (defun js2-print-array-comp-node (n i)
3693 (let ((pad (js2-make-pad i))
3694 (result (js2-array-comp-node-result n))
3695 (loops (js2-array-comp-node-loops n))
3696 (filter (js2-array-comp-node-filter n)))
3697 (insert pad "[")
3698 (js2-print-ast result 0)
3699 (dolist (l loops)
3700 (insert " ")
3701 (js2-print-ast l 0))
3702 (when filter
3703 (insert " if (")
3704 (js2-print-ast filter 0)
3705 (insert ")"))
3706 (insert "]")))
3707
3708 (defstruct (js2-array-comp-loop-node
3709 (:include js2-for-in-node)
3710 (:constructor nil)
3711 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3712 (pos js2-ts-cursor)
3713 len iterator
3714 object in-pos
3715 foreach-p
3716 each-pos
3717 forof-p
3718 lp rp)))
3719 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3720
3721 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3722 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3723
3724 (defun js2-visit-array-comp-loop (n v)
3725 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3726 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3727
3728 (defun js2-print-array-comp-loop (n _i)
3729 (insert "for ")
3730 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3731 (insert "(")
3732 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3733 (insert (if (js2-array-comp-loop-node-forof-p n)
3734 " of " " in "))
3735 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3736 (insert ")"))
3737
3738 (defstruct (js2-empty-expr-node
3739 (:include js2-node)
3740 (:constructor nil)
3741 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3742 (pos (js2-current-token-beg))
3743 len)))
3744 "AST node for an empty expression.")
3745
3746 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3747 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3748
3749 (defstruct (js2-xml-node
3750 (:include js2-block-node)
3751 (:constructor nil)
3752 (:constructor make-js2-xml-node (&key (type js2-XML)
3753 (pos (js2-current-token-beg))
3754 len kids)))
3755 "AST node for initial parse of E4X literals.
3756 The kids field is a list of XML fragments, each a `js2-string-node' or
3757 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3758
3759 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3760 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3761
3762 (defun js2-print-xml-node (n i)
3763 (dolist (kid (js2-xml-node-kids n))
3764 (js2-print-ast kid i)))
3765
3766 (defstruct (js2-xml-js-expr-node
3767 (:include js2-xml-node)
3768 (:constructor nil)
3769 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3770 (pos js2-ts-cursor)
3771 len expr)))
3772 "AST node for an embedded JavaScript {expression} in an E4X literal.
3773 The start and end fields correspond to the curly-braces."
3774 expr) ; a `js2-expr-node' of some sort
3775
3776 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3777 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3778
3779 (defun js2-visit-xml-js-expr (n v)
3780 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3781
3782 (defun js2-print-xml-js-expr (n i)
3783 (insert (js2-make-pad i))
3784 (insert "{")
3785 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3786 (insert "}"))
3787
3788 (defstruct (js2-xml-dot-query-node
3789 (:include js2-infix-node)
3790 (:constructor nil)
3791 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3792 (pos js2-ts-cursor)
3793 op-pos len left
3794 right rp)))
3795 "AST node for an E4X foo.(bar) filter expression.
3796 Note that the left-paren is automatically the character immediately
3797 following the dot (.) in the operator. No whitespace is permitted
3798 between the dot and the lp by the scanner."
3799 rp)
3800
3801 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3802 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3803
3804 (defun js2-print-xml-dot-query (n i)
3805 (insert (js2-make-pad i))
3806 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3807 (insert ".(")
3808 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3809 (insert ")"))
3810
3811 (defstruct (js2-xml-ref-node
3812 (:include js2-node)
3813 (:constructor nil)) ; abstract
3814 "Base type for E4X XML attribute-access or property-get expressions.
3815 Such expressions can take a variety of forms. The general syntax has
3816 three parts:
3817
3818 - (optional) an @ (specifying an attribute access)
3819 - (optional) a namespace (a `js2-name-node') and double-colon
3820 - (required) either a `js2-name-node' or a bracketed [expression]
3821
3822 The property-name expressions (examples: ns::name, @name) are
3823 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3824 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3825
3826 This node type (or more specifically, its subclasses) will sometimes
3827 be the right-hand child of a `js2-prop-get-node' or a
3828 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3829 The `js2-xml-ref-node' may also be a standalone primary expression with
3830 no explicit target, which is valid in certain expression contexts such as
3831
3832 company..employee.(@id < 100)
3833
3834 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3835 expression whose parent is a `js2-xml-dot-query-node'."
3836 namespace
3837 at-pos
3838 colon-pos)
3839
3840 (defsubst js2-xml-ref-node-attr-access-p (node)
3841 "Return non-nil if this expression began with an @-token."
3842 (and (numberp (js2-xml-ref-node-at-pos node))
3843 (plusp (js2-xml-ref-node-at-pos node))))
3844
3845 (defstruct (js2-xml-prop-ref-node
3846 (:include js2-xml-ref-node)
3847 (:constructor nil)
3848 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3849 (pos (js2-current-token-beg))
3850 len propname
3851 namespace at-pos
3852 colon-pos)))
3853 "AST node for an E4X XML [expr] property-ref expression.
3854 The JavaScript syntax is an optional @, an optional ns::, and a name.
3855
3856 [ '@' ] [ name '::' ] name
3857
3858 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3859 @ns::*, @*::attr, @*::*, and @*.
3860
3861 The node starts at the @ token, if present. Otherwise it starts at the
3862 namespace name. The node bounds extend through the closing right-bracket,
3863 or if it is missing due to a syntax error, through the end of the index
3864 expression."
3865 propname)
3866
3867 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3868 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3869
3870 (defun js2-visit-xml-prop-ref-node (n v)
3871 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3872 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3873
3874 (defun js2-print-xml-prop-ref-node (n i)
3875 (insert (js2-make-pad i))
3876 (if (js2-xml-ref-node-attr-access-p n)
3877 (insert "@"))
3878 (when (js2-xml-prop-ref-node-namespace n)
3879 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3880 (insert "::"))
3881 (if (js2-xml-prop-ref-node-propname n)
3882 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3883
3884 (defstruct (js2-xml-elem-ref-node
3885 (:include js2-xml-ref-node)
3886 (:constructor nil)
3887 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3888 (pos (js2-current-token-beg))
3889 len expr lb rb
3890 namespace at-pos
3891 colon-pos)))
3892 "AST node for an E4X XML [expr] member-ref expression.
3893 Syntax:
3894
3895 [ '@' ] [ name '::' ] '[' expr ']'
3896
3897 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3898
3899 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3900 is not a legal E4X XML element-ref expression, since it's already used
3901 for standard JavaScript element-get array indexing. Hence, a
3902 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3903 non-nil namespace node, or both.
3904
3905 The node starts at the @ token, if present. Otherwise it starts
3906 at the namespace name. The node bounds extend through the closing
3907 right-bracket, or if it is missing due to a syntax error, through the
3908 end of the index expression."
3909 expr ; the bracketed index expression
3910 lb
3911 rb)
3912
3913 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3914 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3915
3916 (defun js2-visit-xml-elem-ref-node (n v)
3917 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3918 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3919
3920 (defun js2-print-xml-elem-ref-node (n i)
3921 (insert (js2-make-pad i))
3922 (if (js2-xml-ref-node-attr-access-p n)
3923 (insert "@"))
3924 (when (js2-xml-elem-ref-node-namespace n)
3925 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3926 (insert "::"))
3927 (insert "[")
3928 (if (js2-xml-elem-ref-node-expr n)
3929 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3930 (insert "]"))
3931
3932 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3933
3934 (defstruct (js2-xml-start-tag-node
3935 (:include js2-xml-node)
3936 (:constructor nil)
3937 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3938 (pos js2-ts-cursor)
3939 len name attrs kids
3940 empty-p)))
3941 "AST node for an XML start-tag. Not currently used.
3942 The `kids' field is a Lisp list of child content nodes."
3943 name ; a `js2-xml-name-node'
3944 attrs ; a Lisp list of `js2-xml-attr-node'
3945 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3946
3947 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3948 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3949
3950 (defun js2-visit-xml-start-tag (n v)
3951 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3952 (dolist (attr (js2-xml-start-tag-node-attrs n))
3953 (js2-visit-ast attr v))
3954 (js2-visit-block n v))
3955
3956 (defun js2-print-xml-start-tag (n i)
3957 (insert (js2-make-pad i) "<")
3958 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3959 (when (js2-xml-start-tag-node-attrs n)
3960 (insert " ")
3961 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3962 (insert ">"))
3963
3964 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3965 ;; and add the end-tag to the kids list of the parent as well.
3966 (defstruct (js2-xml-end-tag-node
3967 (:include js2-xml-node)
3968 (:constructor nil)
3969 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3970 (pos js2-ts-cursor)
3971 len name)))
3972 "AST node for an XML end-tag. Not currently used."
3973 name) ; a `js2-xml-name-node'
3974
3975 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3976 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3977
3978 (defun js2-visit-xml-end-tag (n v)
3979 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3980
3981 (defun js2-print-xml-end-tag (n i)
3982 (insert (js2-make-pad i))
3983 (insert "</")
3984 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3985 (insert ">"))
3986
3987 (defstruct (js2-xml-name-node
3988 (:include js2-xml-node)
3989 (:constructor nil)
3990 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3991 (pos js2-ts-cursor)
3992 len namespace kids)))
3993 "AST node for an E4X XML name. Not currently used.
3994 Any XML name can be qualified with a namespace, hence the namespace field.
3995 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3996 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3997 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3998 namespace) ; a `js2-string-node'
3999
4000 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4001 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4002
4003 (defun js2-visit-xml-name-node (n v)
4004 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4005
4006 (defun js2-print-xml-name-node (n i)
4007 (insert (js2-make-pad i))
4008 (when (js2-xml-name-node-namespace n)
4009 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4010 (insert "::"))
4011 (dolist (kid (js2-xml-name-node-kids n))
4012 (js2-print-ast kid 0)))
4013
4014 (defstruct (js2-xml-pi-node
4015 (:include js2-xml-node)
4016 (:constructor nil)
4017 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4018 (pos js2-ts-cursor)
4019 len name attrs)))
4020 "AST node for an E4X XML processing instruction. Not currently used."
4021 name ; a `js2-xml-name-node'
4022 attrs) ; a list of `js2-xml-attr-node'
4023
4024 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4025 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4026
4027 (defun js2-visit-xml-pi-node (n v)
4028 (js2-visit-ast (js2-xml-pi-node-name n) v)
4029 (dolist (attr (js2-xml-pi-node-attrs n))
4030 (js2-visit-ast attr v)))
4031
4032 (defun js2-print-xml-pi-node (n i)
4033 (insert (js2-make-pad i) "<?")
4034 (js2-print-ast (js2-xml-pi-node-name n))
4035 (when (js2-xml-pi-node-attrs n)
4036 (insert " ")
4037 (js2-print-list (js2-xml-pi-node-attrs n)))
4038 (insert "?>"))
4039
4040 (defstruct (js2-xml-cdata-node
4041 (:include js2-xml-node)
4042 (:constructor nil)
4043 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4044 (pos js2-ts-cursor)
4045 len content)))
4046 "AST node for a CDATA escape section. Not currently used."
4047 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4048
4049 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4050 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4051
4052 (defun js2-visit-xml-cdata-node (n v)
4053 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4054
4055 (defun js2-print-xml-cdata-node (n i)
4056 (insert (js2-make-pad i))
4057 (js2-print-ast (js2-xml-cdata-node-content n)))
4058
4059 (defstruct (js2-xml-attr-node
4060 (:include js2-xml-node)
4061 (:constructor nil)
4062 (:constructor make-js2-attr-node (&key (type js2-XML)
4063 (pos js2-ts-cursor)
4064 len name value
4065 eq-pos quote-type)))
4066 "AST node representing a foo='bar' XML attribute value. Not yet used."
4067 name ; a `js2-xml-name-node'
4068 value ; a `js2-xml-name-node'
4069 eq-pos ; buffer position of "=" sign
4070 quote-type) ; 'single or 'double
4071
4072 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4073 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4074
4075 (defun js2-visit-xml-attr-node (n v)
4076 (js2-visit-ast (js2-xml-attr-node-name n) v)
4077 (js2-visit-ast (js2-xml-attr-node-value n) v))
4078
4079 (defun js2-print-xml-attr-node (n i)
4080 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4081 "'"
4082 "\"")))
4083 (insert (js2-make-pad i))
4084 (js2-print-ast (js2-xml-attr-node-name n) 0)
4085 (insert "=" quote)
4086 (js2-print-ast (js2-xml-attr-node-value n) 0)
4087 (insert quote)))
4088
4089 (defstruct (js2-xml-text-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-text-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len content)))
4095 "AST node for an E4X XML text node. Not currently used."
4096 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4097
4098 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4099 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4100
4101 (defun js2-visit-xml-text-node (n v)
4102 (js2-visit-ast (js2-xml-text-node-content n) v))
4103
4104 (defun js2-print-xml-text-node (n i)
4105 (insert (js2-make-pad i))
4106 (dolist (kid (js2-xml-text-node-content n))
4107 (js2-print-ast kid)))
4108
4109 (defstruct (js2-xml-comment-node
4110 (:include js2-xml-node)
4111 (:constructor nil)
4112 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4113 (pos js2-ts-cursor)
4114 len)))
4115 "AST node for E4X XML comment. Not currently used.")
4116
4117 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4118 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4119
4120 (defun js2-print-xml-comment (n i)
4121 (insert (js2-make-pad i)
4122 (js2-node-string n)))
4123
4124 ;;; Node utilities
4125
4126 (defsubst js2-node-line (n)
4127 "Fetch the source line number at the start of node N.
4128 This is O(n) in the length of the source buffer; use prudently."
4129 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4130
4131 (defsubst js2-block-node-kid (n i)
4132 "Return child I of node N, or nil if there aren't that many."
4133 (nth i (js2-block-node-kids n)))
4134
4135 (defsubst js2-block-node-first (n)
4136 "Return first child of block node N, or nil if there is none."
4137 (first (js2-block-node-kids n)))
4138
4139 (defun js2-node-root (n)
4140 "Return the root of the AST containing N.
4141 If N has no parent pointer, returns N."
4142 (let ((parent (js2-node-parent n)))
4143 (if parent
4144 (js2-node-root parent)
4145 n)))
4146
4147 (defsubst js2-node-short-name (n)
4148 "Return the short name of node N as a string, e.g. `js2-if-node'."
4149 (substring (symbol-name (aref n 0))
4150 (length "cl-struct-")))
4151
4152 (defun js2-node-child-list (node)
4153 "Return the child list for NODE, a Lisp list of nodes.
4154 Works for block nodes, array nodes, obj literals, funarg lists,
4155 var decls and try nodes (for catch clauses). Note that you should call
4156 `js2-block-node-kids' on the function body for the body statements.
4157 Returns nil for zero-length child lists or unsupported nodes."
4158 (cond
4159 ((js2-function-node-p node)
4160 (js2-function-node-params node))
4161 ((js2-block-node-p node)
4162 (js2-block-node-kids node))
4163 ((js2-try-node-p node)
4164 (js2-try-node-catch-clauses node))
4165 ((js2-array-node-p node)
4166 (js2-array-node-elems node))
4167 ((js2-object-node-p node)
4168 (js2-object-node-elems node))
4169 ((js2-call-node-p node)
4170 (js2-call-node-args node))
4171 ((js2-new-node-p node)
4172 (js2-new-node-args node))
4173 ((js2-var-decl-node-p node)
4174 (js2-var-decl-node-kids node))
4175 (t
4176 nil)))
4177
4178 (defun js2-node-set-child-list (node kids)
4179 "Set the child list for NODE to KIDS."
4180 (cond
4181 ((js2-function-node-p node)
4182 (setf (js2-function-node-params node) kids))
4183 ((js2-block-node-p node)
4184 (setf (js2-block-node-kids node) kids))
4185 ((js2-try-node-p node)
4186 (setf (js2-try-node-catch-clauses node) kids))
4187 ((js2-array-node-p node)
4188 (setf (js2-array-node-elems node) kids))
4189 ((js2-object-node-p node)
4190 (setf (js2-object-node-elems node) kids))
4191 ((js2-call-node-p node)
4192 (setf (js2-call-node-args node) kids))
4193 ((js2-new-node-p node)
4194 (setf (js2-new-node-args node) kids))
4195 ((js2-var-decl-node-p node)
4196 (setf (js2-var-decl-node-kids node) kids))
4197 (t
4198 (error "Unsupported node type: %s" (js2-node-short-name node))))
4199 kids)
4200
4201 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4202 (defconst js2-paren-expr-nodes
4203 '(cl-struct-js2-array-comp-loop-node
4204 cl-struct-js2-array-comp-node
4205 cl-struct-js2-call-node
4206 cl-struct-js2-catch-node
4207 cl-struct-js2-do-node
4208 cl-struct-js2-elem-get-node
4209 cl-struct-js2-for-in-node
4210 cl-struct-js2-for-node
4211 cl-struct-js2-function-node
4212 cl-struct-js2-if-node
4213 cl-struct-js2-let-node
4214 cl-struct-js2-new-node
4215 cl-struct-js2-paren-node
4216 cl-struct-js2-switch-node
4217 cl-struct-js2-while-node
4218 cl-struct-js2-with-node
4219 cl-struct-js2-xml-dot-query-node)
4220 "Node types that can have a parenthesized child expression.
4221 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4222
4223 (defsubst js2-paren-expr-node-p (node)
4224 "Return t for nodes that typically have a parenthesized child expression.
4225 Useful for computing the indentation anchors for arg-lists and conditions.
4226 Note that it may return a false positive, for instance when NODE is
4227 a `js2-new-node' and there are no arguments or parentheses."
4228 (memq (aref node 0) js2-paren-expr-nodes))
4229
4230 ;; Fake polymorphism... yech.
4231 (defun js2-node-lp (node)
4232 "Return relative left-paren position for NODE, if applicable.
4233 For `js2-elem-get-node' structs, returns left-bracket position.
4234 Note that the position may be nil in the case of a parse error."
4235 (cond
4236 ((js2-elem-get-node-p node)
4237 (js2-elem-get-node-lb node))
4238 ((js2-loop-node-p node)
4239 (js2-loop-node-lp node))
4240 ((js2-function-node-p node)
4241 (js2-function-node-lp node))
4242 ((js2-if-node-p node)
4243 (js2-if-node-lp node))
4244 ((js2-new-node-p node)
4245 (js2-new-node-lp node))
4246 ((js2-call-node-p node)
4247 (js2-call-node-lp node))
4248 ((js2-paren-node-p node)
4249 0)
4250 ((js2-switch-node-p node)
4251 (js2-switch-node-lp node))
4252 ((js2-catch-node-p node)
4253 (js2-catch-node-lp node))
4254 ((js2-let-node-p node)
4255 (js2-let-node-lp node))
4256 ((js2-array-comp-node-p node)
4257 (js2-array-comp-node-lp node))
4258 ((js2-with-node-p node)
4259 (js2-with-node-lp node))
4260 ((js2-xml-dot-query-node-p node)
4261 (1+ (js2-infix-node-op-pos node)))
4262 (t
4263 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4264
4265 ;; Fake polymorphism... blech.
4266 (defun js2-node-rp (node)
4267 "Return relative right-paren position for NODE, if applicable.
4268 For `js2-elem-get-node' structs, returns right-bracket position.
4269 Note that the position may be nil in the case of a parse error."
4270 (cond
4271 ((js2-elem-get-node-p node)
4272 (js2-elem-get-node-rb node))
4273 ((js2-loop-node-p node)
4274 (js2-loop-node-rp node))
4275 ((js2-function-node-p node)
4276 (js2-function-node-rp node))
4277 ((js2-if-node-p node)
4278 (js2-if-node-rp node))
4279 ((js2-new-node-p node)
4280 (js2-new-node-rp node))
4281 ((js2-call-node-p node)
4282 (js2-call-node-rp node))
4283 ((js2-paren-node-p node)
4284 (1- (js2-node-len node)))
4285 ((js2-switch-node-p node)
4286 (js2-switch-node-rp node))
4287 ((js2-catch-node-p node)
4288 (js2-catch-node-rp node))
4289 ((js2-let-node-p node)
4290 (js2-let-node-rp node))
4291 ((js2-array-comp-node-p node)
4292 (js2-array-comp-node-rp node))
4293 ((js2-with-node-p node)
4294 (js2-with-node-rp node))
4295 ((js2-xml-dot-query-node-p node)
4296 (1+ (js2-xml-dot-query-node-rp node)))
4297 (t
4298 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4299
4300 (defsubst js2-node-first-child (node)
4301 "Return the first element of `js2-node-child-list' for NODE."
4302 (car (js2-node-child-list node)))
4303
4304 (defsubst js2-node-last-child (node)
4305 "Return the last element of `js2-node-last-child' for NODE."
4306 (car (last (js2-node-child-list node))))
4307
4308 (defun js2-node-prev-sibling (node)
4309 "Return the previous statement in parent.
4310 Works for parents supported by `js2-node-child-list'.
4311 Returns nil if NODE is not in the parent, or PARENT is
4312 not a supported node, or if NODE is the first child."
4313 (let* ((p (js2-node-parent node))
4314 (kids (js2-node-child-list p))
4315 (sib (car kids)))
4316 (while (and kids
4317 (not (eq node (cadr kids))))
4318 (setq kids (cdr kids)
4319 sib (car kids)))
4320 sib))
4321
4322 (defun js2-node-next-sibling (node)
4323 "Return the next statement in parent block.
4324 Returns nil if NODE is not in the block, or PARENT is not
4325 a block node, or if NODE is the last statement."
4326 (let* ((p (js2-node-parent node))
4327 (kids (js2-node-child-list p)))
4328 (while (and kids
4329 (not (eq node (car kids))))
4330 (setq kids (cdr kids)))
4331 (cadr kids)))
4332
4333 (defun js2-node-find-child-before (pos parent &optional after)
4334 "Find the last child that starts before POS in parent.
4335 If AFTER is non-nil, returns first child starting after POS.
4336 POS is an absolute buffer position. PARENT is any node
4337 supported by `js2-node-child-list'.
4338 Returns nil if no applicable child is found."
4339 (let ((kids (if (js2-function-node-p parent)
4340 (js2-block-node-kids (js2-function-node-body parent))
4341 (js2-node-child-list parent)))
4342 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4343 (js2-function-node-body parent)
4344 parent)))
4345 kid result fn
4346 (continue t))
4347 (setq fn (if after '>= '<))
4348 (while (and kids continue)
4349 (setq kid (car kids))
4350 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4351 (setq result kid
4352 continue (not after))
4353 (setq continue after))
4354 (setq kids (cdr kids)))
4355 result))
4356
4357 (defun js2-node-find-child-after (pos parent)
4358 "Find first child that starts after POS in parent.
4359 POS is an absolute buffer position. PARENT is any node
4360 supported by `js2-node-child-list'.
4361 Returns nil if no applicable child is found."
4362 (js2-node-find-child-before pos parent 'after))
4363
4364 (defun js2-node-replace-child (pos parent new-node)
4365 "Replace node at index POS in PARENT with NEW-NODE.
4366 Only works for parents supported by `js2-node-child-list'."
4367 (let ((kids (js2-node-child-list parent))
4368 (i 0))
4369 (while (< i pos)
4370 (setq kids (cdr kids)
4371 i (1+ i)))
4372 (setcar kids new-node)
4373 (js2-node-add-children parent new-node)))
4374
4375 (defun js2-node-buffer (n)
4376 "Return the buffer associated with AST N.
4377 Returns nil if the buffer is not set as a property on the root
4378 node, or if parent links were not recorded during parsing."
4379 (let ((root (js2-node-root n)))
4380 (and root
4381 (js2-ast-root-p root)
4382 (js2-ast-root-buffer root))))
4383
4384 (defun js2-block-node-push (n kid)
4385 "Push js2-node KID onto the end of js2-block-node N's child list.
4386 KID is always added to the -end- of the kids list.
4387 Function also calls `js2-node-add-children' to add the parent link."
4388 (let ((kids (js2-node-child-list n)))
4389 (if kids
4390 (setcdr kids (nconc (cdr kids) (list kid)))
4391 (js2-node-set-child-list n (list kid)))
4392 (js2-node-add-children n kid)))
4393
4394 (defun js2-node-string (node)
4395 (with-current-buffer (or (js2-node-buffer node)
4396 (error "No buffer available for node %s" node))
4397 (let ((pos (js2-node-abs-pos node)))
4398 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4399
4400 ;; Container for storing the node we're looking for in a traversal.
4401 (js2-deflocal js2-discovered-node nil)
4402
4403 ;; Keep track of absolute node position during traversals.
4404 (js2-deflocal js2-visitor-offset nil)
4405
4406 (js2-deflocal js2-node-search-point nil)
4407
4408 (when js2-mode-dev-mode-p
4409 (defun js2-find-node-at-point ()
4410 (interactive)
4411 (let ((node (js2-node-at-point)))
4412 (message "%s" (or node "No node found at point"))))
4413 (defun js2-node-name-at-point ()
4414 (interactive)
4415 (let ((node (js2-node-at-point)))
4416 (message "%s" (if node
4417 (js2-node-short-name node)
4418 "No node found at point.")))))
4419
4420 (defun js2-node-at-point (&optional pos skip-comments)
4421 "Return AST node at POS, a buffer position, defaulting to current point.
4422 The `js2-mode-ast' variable must be set to the current parse tree.
4423 Signals an error if the AST (`js2-mode-ast') is nil.
4424 Always returns a node - if it can't find one, it returns the root.
4425 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4426 (let ((ast js2-mode-ast)
4427 result)
4428 (unless ast
4429 (error "No JavaScript AST available"))
4430 ;; Look through comments first, since they may be inside nodes that
4431 ;; would otherwise report a match.
4432 (setq pos (or pos (point))
4433 result (if (> pos (js2-node-abs-end ast))
4434 ast
4435 (if (not skip-comments)
4436 (js2-comment-at-point pos))))
4437 (unless result
4438 (setq js2-discovered-node nil
4439 js2-visitor-offset 0
4440 js2-node-search-point pos)
4441 (unwind-protect
4442 (catch 'js2-visit-done
4443 (js2-visit-ast ast #'js2-node-at-point-visitor))
4444 (setq js2-visitor-offset nil
4445 js2-node-search-point nil))
4446 (setq result js2-discovered-node))
4447 ;; may have found a comment beyond end of last child node,
4448 ;; since visiting the ast-root looks at the comment-list last.
4449 (if (and skip-comments
4450 (js2-comment-node-p result))
4451 (setq result nil))
4452 (or result js2-mode-ast)))
4453
4454 (defun js2-node-at-point-visitor (node end-p)
4455 (let ((rel-pos (js2-node-pos node))
4456 abs-pos
4457 abs-end
4458 (point js2-node-search-point))
4459 (cond
4460 (end-p
4461 ;; this evaluates to a non-nil return value, even if it's zero
4462 (decf js2-visitor-offset rel-pos))
4463 ;; we already looked for comments before visiting, and don't want them now
4464 ((js2-comment-node-p node)
4465 nil)
4466 (t
4467 (setq abs-pos (incf js2-visitor-offset rel-pos)
4468 ;; we only want to use the node if the point is before
4469 ;; the last character position in the node, so we decrement
4470 ;; the absolute end by 1.
4471 abs-end (+ abs-pos (js2-node-len node) -1))
4472 (cond
4473 ;; If this node starts after search-point, stop the search.
4474 ((> abs-pos point)
4475 (throw 'js2-visit-done nil))
4476 ;; If this node ends before the search-point, don't check kids.
4477 ((> point abs-end)
4478 nil)
4479 (t
4480 ;; Otherwise point is within this node, possibly in a child.
4481 (setq js2-discovered-node node)
4482 t)))))) ; keep processing kids to look for more specific match
4483
4484 (defsubst js2-block-comment-p (node)
4485 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4486 (and (js2-comment-node-p node)
4487 (memq (js2-comment-node-format node) '(jsdoc block))))
4488
4489 ;; TODO: put the comments in a vector and binary-search them instead
4490 (defun js2-comment-at-point (&optional pos)
4491 "Look through scanned comment nodes for one containing POS.
4492 POS is a buffer position that defaults to current point.
4493 Function returns nil if POS was not in any comment node."
4494 (let ((ast js2-mode-ast)
4495 (x (or pos (point)))
4496 beg end)
4497 (unless ast
4498 (error "No JavaScript AST available"))
4499 (catch 'done
4500 ;; Comments are stored in lexical order.
4501 (dolist (comment (js2-ast-root-comments ast) nil)
4502 (setq beg (js2-node-abs-pos comment)
4503 end (+ beg (js2-node-len comment)))
4504 (if (and (>= x beg)
4505 (<= x end))
4506 (throw 'done comment))))))
4507
4508 (defun js2-mode-find-parent-fn (node)
4509 "Find function enclosing NODE.
4510 Returns nil if NODE is not inside a function."
4511 (setq node (js2-node-parent node))
4512 (while (and node (not (js2-function-node-p node)))
4513 (setq node (js2-node-parent node)))
4514 (and (js2-function-node-p node) node))
4515
4516 (defun js2-mode-find-enclosing-fn (node)
4517 "Find function or root enclosing NODE."
4518 (if (js2-ast-root-p node)
4519 node
4520 (setq node (js2-node-parent node))
4521 (while (not (or (js2-ast-root-p node)
4522 (js2-function-node-p node)))
4523 (setq node (js2-node-parent node)))
4524 node))
4525
4526 (defun js2-mode-find-enclosing-node (beg end)
4527 "Find script or function fully enclosing BEG and END."
4528 (let ((node (js2-node-at-point beg))
4529 pos
4530 (continue t))
4531 (while continue
4532 (if (or (js2-ast-root-p node)
4533 (and (js2-function-node-p node)
4534 (<= (setq pos (js2-node-abs-pos node)) beg)
4535 (>= (+ pos (js2-node-len node)) end)))
4536 (setq continue nil)
4537 (setq node (js2-node-parent node))))
4538 node))
4539
4540 (defun js2-node-parent-script-or-fn (node)
4541 "Find script or function immediately enclosing NODE.
4542 If NODE is the ast-root, returns nil."
4543 (if (js2-ast-root-p node)
4544 nil
4545 (setq node (js2-node-parent node))
4546 (while (and node (not (or (js2-function-node-p node)
4547 (js2-script-node-p node))))
4548 (setq node (js2-node-parent node)))
4549 node))
4550
4551 (defun js2-node-is-descendant (node ancestor)
4552 "Return t if NODE is a descendant of ANCESTOR."
4553 (while (and node
4554 (not (eq node ancestor)))
4555 (setq node (js2-node-parent node)))
4556 node)
4557
4558 ;;; visitor infrastructure
4559
4560 (defun js2-visit-none (_node _callback)
4561 "Visitor for AST node that have no node children."
4562 nil)
4563
4564 (defun js2-print-none (_node _indent)
4565 "Visitor for AST node with no printed representation.")
4566
4567 (defun js2-print-body (node indent)
4568 "Print a statement, or a block without braces."
4569 (if (js2-block-node-p node)
4570 (dolist (kid (js2-block-node-kids node))
4571 (js2-print-ast kid indent))
4572 (js2-print-ast node indent)))
4573
4574 (defun js2-print-list (args &optional delimiter)
4575 (loop with len = (length args)
4576 for arg in args
4577 for count from 1
4578 do
4579 (when arg (js2-print-ast arg 0))
4580 (if (< count len)
4581 (insert (or delimiter ", ")))))
4582
4583 (defun js2-print-tree (ast)
4584 "Prints an AST to the current buffer.
4585 Makes `js2-ast-parent-nodes' available to the printer functions."
4586 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4587 (js2-print-ast ast)))
4588
4589 (defun js2-print-ast (node &optional indent)
4590 "Helper function for printing AST nodes.
4591 Requires `js2-ast-parent-nodes' to be non-nil.
4592 You should use `js2-print-tree' instead of this function."
4593 (let ((printer (get (aref node 0) 'js2-printer))
4594 (i (or indent 0)))
4595 ;; TODO: wedge comments in here somewhere
4596 (if printer
4597 (funcall printer node i))))
4598
4599 (defconst js2-side-effecting-tokens
4600 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4601 (dolist (tt (list js2-ASSIGN
4602 js2-ASSIGN_ADD
4603 js2-ASSIGN_BITAND
4604 js2-ASSIGN_BITOR
4605 js2-ASSIGN_BITXOR
4606 js2-ASSIGN_DIV
4607 js2-ASSIGN_LSH
4608 js2-ASSIGN_MOD
4609 js2-ASSIGN_MUL
4610 js2-ASSIGN_RSH
4611 js2-ASSIGN_SUB
4612 js2-ASSIGN_URSH
4613 js2-BLOCK
4614 js2-BREAK
4615 js2-CALL
4616 js2-CATCH
4617 js2-CATCH_SCOPE
4618 js2-CONST
4619 js2-CONTINUE
4620 js2-DEBUGGER
4621 js2-DEC
4622 js2-DELPROP
4623 js2-DEL_REF
4624 js2-DO
4625 js2-ELSE
4626 js2-EMPTY
4627 js2-ENTERWITH
4628 js2-EXPORT
4629 js2-EXPR_RESULT
4630 js2-FINALLY
4631 js2-FOR
4632 js2-FUNCTION
4633 js2-GOTO
4634 js2-IF
4635 js2-IFEQ
4636 js2-IFNE
4637 js2-IMPORT
4638 js2-INC
4639 js2-JSR
4640 js2-LABEL
4641 js2-LEAVEWITH
4642 js2-LET
4643 js2-LETEXPR
4644 js2-LOCAL_BLOCK
4645 js2-LOOP
4646 js2-NEW
4647 js2-REF_CALL
4648 js2-RETHROW
4649 js2-RETURN
4650 js2-RETURN_RESULT
4651 js2-SEMI
4652 js2-SETELEM
4653 js2-SETELEM_OP
4654 js2-SETNAME
4655 js2-SETPROP
4656 js2-SETPROP_OP
4657 js2-SETVAR
4658 js2-SET_REF
4659 js2-SET_REF_OP
4660 js2-SWITCH
4661 js2-TARGET
4662 js2-THROW
4663 js2-TRY
4664 js2-VAR
4665 js2-WHILE
4666 js2-WITH
4667 js2-WITHEXPR
4668 js2-YIELD))
4669 (aset tokens tt t))
4670 (if js2-instanceof-has-side-effects
4671 (aset tokens js2-INSTANCEOF t))
4672 tokens))
4673
4674 (defun js2-node-has-side-effects (node)
4675 "Return t if NODE has side effects."
4676 (when node ; makes it easier to handle malformed expressions
4677 (let ((tt (js2-node-type node)))
4678 (cond
4679 ;; This doubtless needs some work, since EXPR_VOID is used
4680 ;; in several ways in Rhino and I may not have caught them all.
4681 ;; I'll wait for people to notice incorrect warnings.
4682 ((and (= tt js2-EXPR_VOID)
4683 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4684 (let ((expr (js2-expr-stmt-node-expr node)))
4685 (or (js2-node-has-side-effects expr)
4686 (when (js2-string-node-p expr)
4687 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4688 ((= tt js2-COMMA)
4689 (js2-node-has-side-effects (js2-infix-node-right node)))
4690 ((or (= tt js2-AND)
4691 (= tt js2-OR))
4692 (or (js2-node-has-side-effects (js2-infix-node-right node))
4693 (js2-node-has-side-effects (js2-infix-node-left node))))
4694 ((= tt js2-HOOK)
4695 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4696 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4697 ((js2-paren-node-p node)
4698 (js2-node-has-side-effects (js2-paren-node-expr node)))
4699 ((= tt js2-ERROR) ; avoid cascaded error messages
4700 nil)
4701 (t
4702 (aref js2-side-effecting-tokens tt))))))
4703
4704 (defconst js2-stmt-node-types
4705 (list js2-BLOCK
4706 js2-BREAK
4707 js2-CONTINUE
4708 js2-DEFAULT ; e4x "default xml namespace" statement
4709 js2-DO
4710 js2-EXPR_RESULT
4711 js2-EXPR_VOID
4712 js2-FOR
4713 js2-IF
4714 js2-RETURN
4715 js2-SWITCH
4716 js2-THROW
4717 js2-TRY
4718 js2-WHILE
4719 js2-WITH)
4720 "Node types that only appear in statement contexts.
4721 The list does not include nodes that always appear as the child
4722 of another specific statement type, such as switch-cases,
4723 catch and finally blocks, and else-clauses. The list also excludes
4724 nodes like yield, let and var, which may appear in either expression
4725 or statement context, and in the latter context always have a
4726 `js2-expr-stmt-node' parent. Finally, the list does not include
4727 functions or scripts, which are treated separately from statements
4728 by the JavaScript parser and runtime.")
4729
4730 (defun js2-stmt-node-p (node)
4731 "Heuristic for figuring out if NODE is a statement.
4732 Some node types can appear in either an expression context or a
4733 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4734 For these node types in a statement context, the parent will be a
4735 `js2-expr-stmt-node'.
4736 Functions aren't included in the check."
4737 (memq (js2-node-type node) js2-stmt-node-types))
4738
4739 (defun js2-mode-find-first-stmt (node)
4740 "Search upward starting from NODE looking for a statement.
4741 For purposes of this function, a `js2-function-node' counts."
4742 (while (not (or (js2-stmt-node-p node)
4743 (js2-function-node-p node)))
4744 (setq node (js2-node-parent node)))
4745 node)
4746
4747 (defun js2-node-parent-stmt (node)
4748 "Return the node's first ancestor that is a statement.
4749 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4750 appearing in a statement context will have a parent that is a
4751 `js2-expr-stmt-node' that will be returned by this function."
4752 (let ((parent (js2-node-parent node)))
4753 (if (or (null parent)
4754 (js2-stmt-node-p parent)
4755 (and (js2-function-node-p parent)
4756 (not (eq (js2-function-node-form parent)
4757 'FUNCTION_EXPRESSION))))
4758 parent
4759 (js2-node-parent-stmt parent))))
4760
4761 ;; In the Mozilla Rhino sources, Roshan James writes:
4762 ;; Does consistent-return analysis on the function body when strict mode is
4763 ;; enabled.
4764 ;;
4765 ;; function (x) { return (x+1) }
4766 ;;
4767 ;; is ok, but
4768 ;;
4769 ;; function (x) { if (x < 0) return (x+1); }
4770 ;;
4771 ;; is not because the function can potentially return a value when the
4772 ;; condition is satisfied and if not, the function does not explicitly
4773 ;; return a value.
4774 ;;
4775 ;; This extends to checking mismatches such as "return" and "return <value>"
4776 ;; used in the same function. Warnings are not emitted if inconsistent
4777 ;; returns exist in code that can be statically shown to be unreachable.
4778 ;; Ex.
4779 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4780 ;;
4781 ;; emits no warning. However if the loop had a break statement, then a
4782 ;; warning would be emitted.
4783 ;;
4784 ;; The consistency analysis looks at control structures such as loops, ifs,
4785 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4786 ;; warns the user about an inconsistent set of termination possibilities.
4787 ;;
4788 ;; These flags enumerate the possible ways a statement/function can
4789 ;; terminate. These flags are used by endCheck() and by the Parser to
4790 ;; detect inconsistent return usage.
4791 ;;
4792 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4793 ;; able to execute (example: throw, continue)
4794 ;;
4795 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4796 ;; next one. Statement such as return dont. A compound statement may have
4797 ;; some branch that drops off control to the next statement.
4798 ;;
4799 ;; END_RETURNS indicates that the statement can return with no value.
4800 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4801 ;;
4802 ;; A compound statement such as
4803 ;; if (condition) {
4804 ;; return value;
4805 ;; }
4806 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4807
4808 (defconst js2-END_UNREACHED 0)
4809 (defconst js2-END_DROPS_OFF 1)
4810 (defconst js2-END_RETURNS 2)
4811 (defconst js2-END_RETURNS_VALUE 4)
4812 (defconst js2-END_YIELDS 8)
4813
4814 (defun js2-has-consistent-return-usage (node)
4815 "Check that every return usage in a function body is consistent.
4816 Returns t if the function satisfies strict mode requirement."
4817 (let ((n (js2-end-check node)))
4818 ;; either it doesn't return a value in any branch...
4819 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4820 ;; or it returns a value (or is unreached) at every branch
4821 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4822 js2-END_RETURNS
4823 js2-END_YIELDS)))))
4824
4825 (defun js2-end-check-if (node)
4826 "Ensure that return usage in then/else blocks is consistent.
4827 If there is no else block, then the return statement can fall through.
4828 Returns logical OR of END_* flags"
4829 (let ((th (js2-if-node-then-part node))
4830 (el (js2-if-node-else-part node)))
4831 (if (null th)
4832 js2-END_UNREACHED
4833 (logior (js2-end-check th) (if el
4834 (js2-end-check el)
4835 js2-END_DROPS_OFF)))))
4836
4837 (defun js2-end-check-switch (node)
4838 "Consistency of return statements is checked between the case statements.
4839 If there is no default, then the switch can fall through. If there is a
4840 default, we check to see if all code paths in the default return or if
4841 there is a code path that can fall through.
4842 Returns logical OR of END_* flags."
4843 (let ((rv js2-END_UNREACHED)
4844 default-case)
4845 ;; examine the cases
4846 (catch 'break
4847 (dolist (c (js2-switch-node-cases node))
4848 (if (js2-case-node-expr c)
4849 (js2-set-flag rv (js2-end-check-block c))
4850 (setq default-case c)
4851 (throw 'break nil))))
4852 ;; we don't care how the cases drop into each other
4853 (js2-clear-flag rv js2-END_DROPS_OFF)
4854 ;; examine the default
4855 (js2-set-flag rv (if default-case
4856 (js2-end-check default-case)
4857 js2-END_DROPS_OFF))
4858 rv))
4859
4860 (defun js2-end-check-try (node)
4861 "If the block has a finally, return consistency is checked in the
4862 finally block. If all code paths in the finally return, then the
4863 returns in the try-catch blocks don't matter. If there is a code path
4864 that does not return or if there is no finally block, the returns
4865 of the try and catch blocks are checked for mismatch.
4866 Returns logical OR of END_* flags."
4867 (let ((finally (js2-try-node-finally-block node))
4868 rv)
4869 ;; check the finally if it exists
4870 (setq rv (if finally
4871 (js2-end-check (js2-finally-node-body finally))
4872 js2-END_DROPS_OFF))
4873 ;; If the finally block always returns, then none of the returns
4874 ;; in the try or catch blocks matter.
4875 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4876 (js2-clear-flag rv js2-END_DROPS_OFF)
4877 ;; examine the try block
4878 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4879 ;; check each catch block
4880 (dolist (cb (js2-try-node-catch-clauses node))
4881 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4882 rv))
4883
4884 (defun js2-end-check-loop (node)
4885 "Return statement in the loop body must be consistent.
4886 The default assumption for any kind of a loop is that it will eventually
4887 terminate. The only exception is a loop with a constant true condition.
4888 Code that follows such a loop is examined only if one can determine
4889 statically that there is a break out of the loop.
4890
4891 for(... ; ... ; ...) {}
4892 for(... in ... ) {}
4893 while(...) { }
4894 do { } while(...)
4895
4896 Returns logical OR of END_* flags."
4897 (let ((rv (js2-end-check (js2-loop-node-body node)))
4898 (condition (cond
4899 ((js2-while-node-p node)
4900 (js2-while-node-condition node))
4901 ((js2-do-node-p node)
4902 (js2-do-node-condition node))
4903 ((js2-for-node-p node)
4904 (js2-for-node-condition node)))))
4905
4906 ;; check to see if the loop condition is always true
4907 (if (and condition
4908 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4909 (js2-clear-flag rv js2-END_DROPS_OFF))
4910
4911 ;; look for effect of breaks
4912 (js2-set-flag rv (js2-node-get-prop node
4913 'CONTROL_BLOCK_PROP
4914 js2-END_UNREACHED))
4915 rv))
4916
4917 (defun js2-end-check-block (node)
4918 "A general block of code is examined statement by statement.
4919 If any statement (even a compound one) returns in all branches, then
4920 subsequent statements are not examined.
4921 Returns logical OR of END_* flags."
4922 (let* ((rv js2-END_DROPS_OFF)
4923 (kids (js2-block-node-kids node))
4924 (n (car kids)))
4925 ;; Check each statment. If the statement can continue onto the next
4926 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4927 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4928 (js2-clear-flag rv js2-END_DROPS_OFF)
4929 (js2-set-flag rv (js2-end-check n))
4930 (setq kids (cdr kids)
4931 n (car kids)))
4932 rv))
4933
4934 (defun js2-end-check-label (node)
4935 "A labeled statement implies that there may be a break to the label.
4936 The function processes the labeled statement and then checks the
4937 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4938 particular label.
4939 Returns logical OR of END_* flags."
4940 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4941 (logior rv (js2-node-get-prop node
4942 'CONTROL_BLOCK_PROP
4943 js2-END_UNREACHED))))
4944
4945 (defun js2-end-check-break (node)
4946 "When a break is encountered annotate the statement being broken
4947 out of by setting its CONTROL_BLOCK_PROP property.
4948 Returns logical OR of END_* flags."
4949 (and (js2-break-node-target node)
4950 (js2-node-set-prop (js2-break-node-target node)
4951 'CONTROL_BLOCK_PROP
4952 js2-END_DROPS_OFF))
4953 js2-END_UNREACHED)
4954
4955 (defun js2-end-check (node)
4956 "Examine the body of a function, doing a basic reachability analysis.
4957 Returns a combination of flags END_* flags that indicate
4958 how the function execution can terminate. These constitute only the
4959 pessimistic set of termination conditions. It is possible that at
4960 runtime certain code paths will never be actually taken. Hence this
4961 analysis will flag errors in cases where there may not be errors.
4962 Returns logical OR of END_* flags"
4963 (let (kid)
4964 (cond
4965 ((js2-break-node-p node)
4966 (js2-end-check-break node))
4967 ((js2-expr-stmt-node-p node)
4968 (if (setq kid (js2-expr-stmt-node-expr node))
4969 (js2-end-check kid)
4970 js2-END_DROPS_OFF))
4971 ((or (js2-continue-node-p node)
4972 (js2-throw-node-p node))
4973 js2-END_UNREACHED)
4974 ((js2-return-node-p node)
4975 (if (setq kid (js2-return-node-retval node))
4976 js2-END_RETURNS_VALUE
4977 js2-END_RETURNS))
4978 ((js2-loop-node-p node)
4979 (js2-end-check-loop node))
4980 ((js2-switch-node-p node)
4981 (js2-end-check-switch node))
4982 ((js2-labeled-stmt-node-p node)
4983 (js2-end-check-label node))
4984 ((js2-if-node-p node)
4985 (js2-end-check-if node))
4986 ((js2-try-node-p node)
4987 (js2-end-check-try node))
4988 ((js2-block-node-p node)
4989 (if (null (js2-block-node-kids node))
4990 js2-END_DROPS_OFF
4991 (js2-end-check-block node)))
4992 ((js2-yield-node-p node)
4993 js2-END_YIELDS)
4994 (t
4995 js2-END_DROPS_OFF))))
4996
4997 (defun js2-always-defined-boolean-p (node)
4998 "Check if NODE always evaluates to true or false in boolean context.
4999 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5000 nor always false."
5001 (let ((tt (js2-node-type node))
5002 num)
5003 (cond
5004 ((or (= tt js2-FALSE) (= tt js2-NULL))
5005 'ALWAYS_FALSE)
5006 ((= tt js2-TRUE)
5007 'ALWAYS_TRUE)
5008 ((= tt js2-NUMBER)
5009 (setq num (js2-number-node-num-value node))
5010 (if (and (not (eq num 0.0e+NaN))
5011 (not (zerop num)))
5012 'ALWAYS_TRUE
5013 'ALWAYS_FALSE))
5014 (t
5015 nil))))
5016
5017 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5018 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5019
5020 (defvar js2-tokens nil
5021 "List of all defined token names.") ; initialized in `js2-token-names'
5022
5023 (defconst js2-token-names
5024 (let* ((names (make-vector js2-num-tokens -1))
5025 (case-fold-search nil) ; only match js2-UPPER_CASE
5026 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5027 (loop for sym in syms
5028 for i from 0
5029 do
5030 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5031 (not (boundp sym)))
5032 (aset names (symbol-value sym) ; code, e.g. 152
5033 (downcase
5034 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5035 (push sym js2-tokens)))
5036 names)
5037 "Vector mapping int values to token string names, sans `js2-' prefix.")
5038
5039 (defun js2-tt-name (tok)
5040 "Return a string name for TOK, a token symbol or code.
5041 Signals an error if it's not a recognized token."
5042 (let ((code tok))
5043 (if (symbolp tok)
5044 (setq code (symbol-value tok)))
5045 (if (eq code -1)
5046 "ERROR"
5047 (if (and (numberp code)
5048 (not (minusp code))
5049 (< code js2-num-tokens))
5050 (aref js2-token-names code)
5051 (error "Invalid token: %s" code)))))
5052
5053 (defsubst js2-tt-sym (tok)
5054 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5055 (intern (js2-tt-name tok)))
5056
5057 (defconst js2-token-codes
5058 (let ((table (make-hash-table :test 'eq :size 256)))
5059 (loop for name across js2-token-names
5060 for sym = (intern (concat "js2-" (upcase name)))
5061 do
5062 (puthash sym (symbol-value sym) table))
5063 ;; clean up a few that are "wrong" in Rhino's token codes
5064 (puthash 'js2-DELETE js2-DELPROP table)
5065 table)
5066 "Hashtable mapping token type symbols to their bytecodes.")
5067
5068 (defsubst js2-tt-code (sym)
5069 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5070 (or (gethash sym js2-token-codes)
5071 (error "Invalid token symbol: %s " sym))) ; signal code bug
5072
5073 (defun js2-report-scan-error (msg &optional no-throw beg len)
5074 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5075 (js2-report-error msg nil
5076 (or beg (js2-current-token-beg))
5077 (or len (js2-current-token-len)))
5078 (unless no-throw
5079 (throw 'return js2-ERROR)))
5080
5081 (defun js2-set-string-from-buffer (token)
5082 "Set `string' and `end' slots for TOKEN, return the string."
5083 (setf (js2-token-end token) js2-ts-cursor
5084 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5085
5086 ;; TODO: could potentially avoid a lot of consing by allocating a
5087 ;; char buffer the way Rhino does.
5088 (defsubst js2-add-to-string (c)
5089 (push c js2-ts-string-buffer))
5090
5091 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5092 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5093 ;; any other character: when it's not part of the current token, we
5094 ;; unget it, allowing it to be read again by the following call.
5095 (defsubst js2-unget-char ()
5096 (decf js2-ts-cursor))
5097
5098 ;; Rhino distinguishes \r and \n line endings. We don't need to
5099 ;; because we only scan from Emacs buffers, which always use \n.
5100 (defun js2-get-char ()
5101 "Read and return the next character from the input buffer.
5102 Increments `js2-ts-lineno' if the return value is a newline char.
5103 Updates `js2-ts-cursor' to the point after the returned char.
5104 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5105 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5106 (let (c)
5107 ;; check for end of buffer
5108 (if (>= js2-ts-cursor (point-max))
5109 (setq js2-ts-hit-eof t
5110 js2-ts-cursor (1+ js2-ts-cursor)
5111 c js2-EOF_CHAR) ; return value
5112 ;; otherwise read next char
5113 (setq c (char-before (incf js2-ts-cursor)))
5114 ;; if we read a newline, update counters
5115 (if (= c ?\n)
5116 (setq js2-ts-line-start js2-ts-cursor
5117 js2-ts-lineno (1+ js2-ts-lineno)))
5118 ;; TODO: skip over format characters
5119 c)))
5120
5121 (defun js2-read-unicode-escape ()
5122 "Read a \\uNNNN sequence from the input.
5123 Assumes the ?\ and ?u have already been read.
5124 Returns the unicode character, or nil if it wasn't a valid character.
5125 Doesn't change the values of any scanner variables."
5126 ;; I really wish I knew a better way to do this, but I can't
5127 ;; find the Emacs function that takes a 16-bit int and converts
5128 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5129 ;; Have to first check that it's 4 hex characters or it may stop
5130 ;; the read early.
5131 (ignore-errors
5132 (let ((s (buffer-substring-no-properties js2-ts-cursor
5133 (+ 4 js2-ts-cursor))))
5134 (if (string-match "[[:alnum:]]\\{4\\}" s)
5135 (read (concat "?\\u" s))))))
5136
5137 (defun js2-match-char (test)
5138 "Consume and return next character if it matches TEST, a character.
5139 Returns nil and consumes nothing if TEST is not the next character."
5140 (let ((c (js2-get-char)))
5141 (if (eq c test)
5142 t
5143 (js2-unget-char)
5144 nil)))
5145
5146 (defun js2-peek-char ()
5147 (prog1
5148 (js2-get-char)
5149 (js2-unget-char)))
5150
5151 (defun js2-java-identifier-start-p (c)
5152 (or
5153 (memq c '(?$ ?_))
5154 (js2-char-uppercase-p c)
5155 (js2-char-lowercase-p c)))
5156
5157 (defun js2-java-identifier-part-p (c)
5158 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5159 ;; TODO: make me Unicode-friendly. See comments above.
5160 (or
5161 (memq c '(?$ ?_))
5162 (js2-char-uppercase-p c)
5163 (js2-char-lowercase-p c)
5164 (and (>= c ?0) (<= c ?9))))
5165
5166 (defun js2-alpha-p (c)
5167 (cond ((and (<= ?A c) (<= c ?Z)) t)
5168 ((and (<= ?a c) (<= c ?z)) t)
5169 (t nil)))
5170
5171 (defsubst js2-digit-p (c)
5172 (and (<= ?0 c) (<= c ?9)))
5173
5174 (defun js2-js-space-p (c)
5175 (if (<= c 127)
5176 (memq c '(#x20 #x9 #xB #xC #xD))
5177 (or
5178 (eq c #xA0)
5179 ;; TODO: change this nil to check for Unicode space character
5180 nil)))
5181
5182 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5183
5184 (defun js2-skip-line ()
5185 "Skip to end of line."
5186 (while (not (memq (js2-get-char) js2-eol-chars)))
5187 (js2-unget-char)
5188 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5189 (setq js2-token-end js2-ts-cursor))
5190
5191 (defun js2-init-scanner (&optional buf line)
5192 "Create token stream for BUF starting on LINE.
5193 BUF defaults to `current-buffer' and LINE defaults to 1.
5194
5195 A buffer can only have one scanner active at a time, which yields
5196 dramatically simpler code than using a defstruct. If you need to
5197 have simultaneous scanners in a buffer, copy the regions to scan
5198 into temp buffers."
5199 (with-current-buffer (or buf (current-buffer))
5200 (setq js2-ts-dirty-line nil
5201 js2-ts-hit-eof nil
5202 js2-ts-line-start 0
5203 js2-ts-lineno (or line 1)
5204 js2-ts-line-end-char -1
5205 js2-ts-cursor (point-min)
5206 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5207 js2-ti-tokens-cursor 0
5208 js2-ti-lookahead 0
5209 js2-ts-is-xml-attribute nil
5210 js2-ts-xml-is-tag-content nil
5211 js2-ts-xml-open-tags-count 0
5212 js2-ts-string-buffer nil)))
5213
5214 ;; This function uses the cached op, string and number fields in
5215 ;; TokenStream; if getToken has been called since the passed token
5216 ;; was scanned, the op or string printed may be incorrect.
5217 (defun js2-token-to-string (token)
5218 ;; Not sure where this function is used in Rhino. Not tested.
5219 (if (not js2-debug-print-trees)
5220 ""
5221 (let ((name (js2-tt-name token)))
5222 (cond
5223 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5224 (concat name " `" (js2-current-token-string) "'"))
5225 ((eq token js2-NUMBER)
5226 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5227 (t
5228 name)))))
5229
5230 (defconst js2-keywords
5231 '(break
5232 case catch const continue
5233 debugger default delete do
5234 else enum
5235 false finally for function
5236 if in instanceof import
5237 let
5238 new null
5239 return
5240 switch
5241 this throw true try typeof
5242 var void
5243 while with
5244 yield))
5245
5246 ;; Token names aren't exactly the same as the keywords, unfortunately.
5247 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5248 (defconst js2-kwd-tokens
5249 (let ((table (make-vector js2-num-tokens nil))
5250 (tokens
5251 (list js2-BREAK
5252 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5253 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5254 js2-ELSE
5255 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5256 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5257 js2-LET
5258 js2-NEW js2-NULL
5259 js2-RETURN
5260 js2-SWITCH
5261 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5262 js2-VAR
5263 js2-WHILE js2-WITH
5264 js2-YIELD)))
5265 (dolist (i tokens)
5266 (aset table i 'font-lock-keyword-face))
5267 (aset table js2-STRING 'font-lock-string-face)
5268 (aset table js2-REGEXP 'font-lock-string-face)
5269 (aset table js2-COMMENT 'font-lock-comment-face)
5270 (aset table js2-THIS 'font-lock-builtin-face)
5271 (aset table js2-VOID 'font-lock-constant-face)
5272 (aset table js2-NULL 'font-lock-constant-face)
5273 (aset table js2-TRUE 'font-lock-constant-face)
5274 (aset table js2-FALSE 'font-lock-constant-face)
5275 table)
5276 "Vector whose values are non-nil for tokens that are keywords.
5277 The values are default faces to use for highlighting the keywords.")
5278
5279 (defconst js2-reserved-words
5280 '(abstract
5281 boolean byte
5282 char class
5283 double
5284 enum export extends
5285 final float
5286 goto
5287 implements import int interface
5288 long
5289 native
5290 package private protected public
5291 short static super synchronized
5292 throws transient
5293 volatile))
5294
5295 (defconst js2-keyword-names
5296 (let ((table (make-hash-table :test 'equal)))
5297 (loop for k in js2-keywords
5298 do (puthash
5299 (symbol-name k) ; instanceof
5300 (intern (concat "js2-"
5301 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5302 table))
5303 table)
5304 "JavaScript keywords by name, mapped to their symbols.")
5305
5306 (defconst js2-reserved-word-names
5307 (let ((table (make-hash-table :test 'equal)))
5308 (loop for k in js2-reserved-words
5309 do
5310 (puthash (symbol-name k) 'js2-RESERVED table))
5311 table)
5312 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5313
5314 (defun js2-collect-string (buf)
5315 "Convert BUF, a list of chars, to a string.
5316 Reverses BUF before converting."
5317 (if buf
5318 (apply #'string (nreverse buf))
5319 ""))
5320
5321 (defun js2-string-to-keyword (s)
5322 "Return token for S, a string, if S is a keyword or reserved word.
5323 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5324 (or (gethash s js2-keyword-names)
5325 (gethash s js2-reserved-word-names)))
5326
5327 (defsubst js2-ts-set-char-token-bounds (token)
5328 "Used when next token is one character."
5329 (setf (js2-token-beg token) (1- js2-ts-cursor)
5330 (js2-token-end token) js2-ts-cursor))
5331
5332 (defsubst js2-ts-return (token type)
5333 "Update the `end' and `type' slots of TOKEN,
5334 then throw `return' with value TYPE."
5335 (setf (js2-token-end token) js2-ts-cursor
5336 (js2-token-type token) type)
5337 (throw 'return type))
5338
5339 (defun js2-x-digit-to-int (c accumulator)
5340 "Build up a hex number.
5341 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5342 corresponding number. Otherwise return -1."
5343 (catch 'return
5344 (catch 'check
5345 ;; Use 0..9 < A..Z < a..z
5346 (cond
5347 ((<= c ?9)
5348 (decf c ?0)
5349 (if (<= 0 c)
5350 (throw 'check nil)))
5351 ((<= c ?F)
5352 (when (<= ?A c)
5353 (decf c (- ?A 10))
5354 (throw 'check nil)))
5355 ((<= c ?f)
5356 (when (<= ?a c)
5357 (decf c (- ?a 10))
5358 (throw 'check nil))))
5359 (throw 'return -1))
5360 (logior c (lsh accumulator 4))))
5361
5362 (defun js2-get-token ()
5363 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5364 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5365 next saved token.
5366
5367 This function will not return a newline (js2-EOL) - instead, it
5368 gobbles newlines until it finds a non-newline token. Call
5369 `js2-peek-token-or-eol' when you care about newlines.
5370
5371 This function will also not return a js2-COMMENT. Instead, it
5372 records comments found in `js2-scanned-comments'. If the token
5373 returned by this function immediately follows a jsdoc comment,
5374 the token is flagged as such."
5375 (if (zerop js2-ti-lookahead)
5376 (js2-get-token-internal)
5377 (decf js2-ti-lookahead)
5378 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5379 (let ((tt (js2-current-token-type)))
5380 (assert (not (= tt js2-EOL)))
5381 tt)))
5382
5383 (defun js2-unget-token ()
5384 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5385 (incf js2-ti-lookahead)
5386 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5387
5388 (defun js2-get-token-internal ()
5389 (let* ((token (js2-get-token-internal-1)) ; call scanner
5390 (tt (js2-token-type token))
5391 saw-eol
5392 face)
5393 ;; process comments
5394 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5395 (if (= tt js2-EOL)
5396 (setq saw-eol t)
5397 (setq saw-eol nil)
5398 (when js2-record-comments
5399 (js2-record-comment token)))
5400 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5401 (setq token (js2-get-token-internal-1) ; call scanner again
5402 tt (js2-token-type token)))
5403
5404 (when saw-eol
5405 (setf (js2-token-follows-eol-p token) t))
5406
5407 ;; perform lexical fontification as soon as token is scanned
5408 (when js2-parse-ide-mode
5409 (cond
5410 ((minusp tt)
5411 (js2-record-face 'js2-error token))
5412 ((setq face (aref js2-kwd-tokens tt))
5413 (js2-record-face face token))
5414 ((and (= tt js2-NAME)
5415 (equal (js2-token-string token) "undefined"))
5416 (js2-record-face 'font-lock-constant-face token))))
5417 tt))
5418
5419 (defun js2-get-token-internal-1 ()
5420 "Return next JavaScript token type, an int such as js2-RETURN.
5421 During operation, creates an instance of `js2-token' struct, sets
5422 its relevant fields and puts it into `js2-ti-tokens'."
5423 (let (c c1 identifier-start is-unicode-escape-start
5424 contains-escape escape-val str result base
5425 is-integer quote-char val look-for-slash continue tt
5426 (token (js2-new-token 0)))
5427 (setq
5428 tt
5429 (catch 'return
5430 (while t
5431 ;; Eat whitespace, possibly sensitive to newlines.
5432 (setq continue t)
5433 (while continue
5434 (setq c (js2-get-char))
5435 (cond
5436 ((eq c js2-EOF_CHAR)
5437 (js2-unget-char)
5438 (js2-ts-set-char-token-bounds token)
5439 (throw 'return js2-EOF))
5440 ((eq c ?\n)
5441 (js2-ts-set-char-token-bounds token)
5442 (setq js2-ts-dirty-line nil)
5443 (throw 'return js2-EOL))
5444 ((not (js2-js-space-p c))
5445 (if (/= c ?-) ; in case end of HTML comment
5446 (setq js2-ts-dirty-line t))
5447 (setq continue nil))))
5448 ;; Assume the token will be 1 char - fixed up below.
5449 (js2-ts-set-char-token-bounds token)
5450 (when (eq c ?@)
5451 (throw 'return js2-XMLATTR))
5452 ;; identifier/keyword/instanceof?
5453 ;; watch out for starting with a <backslash>
5454 (cond
5455 ((eq c ?\\)
5456 (setq c (js2-get-char))
5457 (if (eq c ?u)
5458 (setq identifier-start t
5459 is-unicode-escape-start t
5460 js2-ts-string-buffer nil)
5461 (setq identifier-start nil)
5462 (js2-unget-char)
5463 (setq c ?\\)))
5464 (t
5465 (when (setq identifier-start (js2-java-identifier-start-p c))
5466 (setq js2-ts-string-buffer nil)
5467 (js2-add-to-string c))))
5468 (when identifier-start
5469 (setq contains-escape is-unicode-escape-start)
5470 (catch 'break
5471 (while t
5472 (if is-unicode-escape-start
5473 ;; strictly speaking we should probably push-back
5474 ;; all the bad characters if the <backslash>uXXXX
5475 ;; sequence is malformed. But since there isn't a
5476 ;; correct context(is there?) for a bad Unicode
5477 ;; escape sequence in an identifier, we can report
5478 ;; an error here.
5479 (progn
5480 (setq escape-val 0)
5481 (dotimes (_ 4)
5482 (setq c (js2-get-char)
5483 escape-val (js2-x-digit-to-int c escape-val))
5484 ;; Next check takes care of c < 0 and bad escape
5485 (if (minusp escape-val)
5486 (throw 'break nil)))
5487 (if (minusp escape-val)
5488 (js2-report-scan-error "msg.invalid.escape" t))
5489 (js2-add-to-string escape-val)
5490 (setq is-unicode-escape-start nil))
5491 (setq c (js2-get-char))
5492 (cond
5493 ((eq c ?\\)
5494 (setq c (js2-get-char))
5495 (if (eq c ?u)
5496 (setq is-unicode-escape-start t
5497 contains-escape t)
5498 (js2-report-scan-error "msg.illegal.character" t)))
5499 (t
5500 (if (or (eq c js2-EOF_CHAR)
5501 (not (js2-java-identifier-part-p c)))
5502 (throw 'break nil))
5503 (js2-add-to-string c))))))
5504 (js2-unget-char)
5505 (setf str (js2-collect-string js2-ts-string-buffer)
5506 (js2-token-end token) js2-ts-cursor)
5507 (unless contains-escape
5508 ;; OPT we shouldn't have to make a string (object!) to
5509 ;; check if it's a keyword.
5510 ;; Return the corresponding token if it's a keyword
5511 (when (setq result (js2-string-to-keyword str))
5512 (if (and (< js2-language-version 170)
5513 (memq result '(js2-LET js2-YIELD)))
5514 ;; LET and YIELD are tokens only in 1.7 and later
5515 (setq result 'js2-NAME))
5516 (if (not (eq result 'js2-RESERVED))
5517 (throw 'return (js2-tt-code result)))
5518 (js2-report-warning "msg.reserved.keyword" str)))
5519 ;; If we want to intern these as Rhino does, just use (intern str)
5520 (setf (js2-token-string token) str)
5521 (throw 'return js2-NAME)) ; end identifier/kwd check
5522 ;; is it a number?
5523 (when (or (js2-digit-p c)
5524 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5525 (setq js2-ts-string-buffer nil
5526 base 10)
5527 (when (eq c ?0)
5528 (setq c (js2-get-char))
5529 (cond
5530 ((or (eq c ?x) (eq c ?X))
5531 (setq base 16)
5532 (setq c (js2-get-char)))
5533 ((js2-digit-p c)
5534 (setq base 8))
5535 (t
5536 (js2-add-to-string ?0))))
5537 (if (eq base 16)
5538 (while (<= 0 (js2-x-digit-to-int c 0))
5539 (js2-add-to-string c)
5540 (setq c (js2-get-char)))
5541 (while (and (<= ?0 c) (<= c ?9))
5542 ;; We permit 08 and 09 as decimal numbers, which
5543 ;; makes our behavior a superset of the ECMA
5544 ;; numeric grammar. We might not always be so
5545 ;; permissive, so we warn about it.
5546 (when (and (eq base 8) (>= c ?8))
5547 (js2-report-warning "msg.bad.octal.literal"
5548 (if (eq c ?8) "8" "9"))
5549 (setq base 10))
5550 (js2-add-to-string c)
5551 (setq c (js2-get-char))))
5552 (setq is-integer t)
5553 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5554 (setq is-integer nil)
5555 (when (eq c ?.)
5556 (loop do
5557 (js2-add-to-string c)
5558 (setq c (js2-get-char))
5559 while (js2-digit-p c)))
5560 (when (memq c '(?e ?E))
5561 (js2-add-to-string c)
5562 (setq c (js2-get-char))
5563 (when (memq c '(?+ ?-))
5564 (js2-add-to-string c)
5565 (setq c (js2-get-char)))
5566 (unless (js2-digit-p c)
5567 (js2-report-scan-error "msg.missing.exponent" t))
5568 (loop do
5569 (js2-add-to-string c)
5570 (setq c (js2-get-char))
5571 while (js2-digit-p c))))
5572 (js2-unget-char)
5573 (let ((str (js2-set-string-from-buffer token)))
5574 (setf (js2-token-number token)
5575 (if (and (eq base 10) (not is-integer))
5576 (string-to-number str)
5577 ;; TODO: call runtime number-parser. Some of it is in
5578 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5579 (string-to-number str))))
5580 (throw 'return js2-NUMBER))
5581 ;; is it a string?
5582 (when (memq c '(?\" ?\'))
5583 ;; We attempt to accumulate a string the fast way, by
5584 ;; building it directly out of the reader. But if there
5585 ;; are any escaped characters in the string, we revert to
5586 ;; building it out of a string buffer.
5587 (setq quote-char c
5588 js2-ts-string-buffer nil
5589 c (js2-get-char))
5590 (catch 'break
5591 (while (/= c quote-char)
5592 (catch 'continue
5593 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5594 (js2-unget-char)
5595 (setf (js2-token-end token) js2-ts-cursor)
5596 (js2-report-error "msg.unterminated.string.lit")
5597 (throw 'return js2-STRING))
5598 (when (eq c ?\\)
5599 ;; We've hit an escaped character
5600 (setq c (js2-get-char))
5601 (case c
5602 (?b (setq c ?\b))
5603 (?f (setq c ?\f))
5604 (?n (setq c ?\n))
5605 (?r (setq c ?\r))
5606 (?t (setq c ?\t))
5607 (?v (setq c ?\v))
5608 (?u
5609 (setq c1 (js2-read-unicode-escape))
5610 (if js2-parse-ide-mode
5611 (if c1
5612 (progn
5613 ;; just copy the string in IDE-mode
5614 (js2-add-to-string ?\\)
5615 (js2-add-to-string ?u)
5616 (dotimes (_ 3)
5617 (js2-add-to-string (js2-get-char)))
5618 (setq c (js2-get-char))) ; added at end of loop
5619 ;; flag it as an invalid escape
5620 (js2-report-warning "msg.invalid.escape"
5621 nil (- js2-ts-cursor 2) 6))
5622 ;; Get 4 hex digits; if the u escape is not
5623 ;; followed by 4 hex digits, use 'u' + the
5624 ;; literal character sequence that follows.
5625 (js2-add-to-string ?u)
5626 (setq escape-val 0)
5627 (dotimes (_ 4)
5628 (setq c (js2-get-char)
5629 escape-val (js2-x-digit-to-int c escape-val))
5630 (if (minusp escape-val)
5631 (throw 'continue nil))
5632 (js2-add-to-string c))
5633 ;; prepare for replace of stored 'u' sequence by escape value
5634 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5635 c escape-val)))
5636 (?x
5637 ;; Get 2 hex digits, defaulting to 'x'+literal
5638 ;; sequence, as above.
5639 (setq c (js2-get-char)
5640 escape-val (js2-x-digit-to-int c 0))
5641 (if (minusp escape-val)
5642 (progn
5643 (js2-add-to-string ?x)
5644 (throw 'continue nil))
5645 (setq c1 c
5646 c (js2-get-char)
5647 escape-val (js2-x-digit-to-int c escape-val))
5648 (if (minusp escape-val)
5649 (progn
5650 (js2-add-to-string ?x)
5651 (js2-add-to-string c1)
5652 (throw 'continue nil))
5653 ;; got 2 hex digits
5654 (setq c escape-val))))
5655 (?\n
5656 ;; Remove line terminator after escape to follow
5657 ;; SpiderMonkey and C/C++
5658 (setq c (js2-get-char))
5659 (throw 'continue nil))
5660 (t
5661 (when (and (<= ?0 c) (< c ?8))
5662 (setq val (- c ?0)
5663 c (js2-get-char))
5664 (when (and (<= ?0 c) (< c ?8))
5665 (setq val (- (+ (* 8 val) c) ?0)
5666 c (js2-get-char))
5667 (when (and (<= ?0 c)
5668 (< c ?8)
5669 (< val #o37))
5670 ;; c is 3rd char of octal sequence only
5671 ;; if the resulting val <= 0377
5672 (setq val (- (+ (* 8 val) c) ?0)
5673 c (js2-get-char))))
5674 (js2-unget-char)
5675 (setq c val)))))
5676 (js2-add-to-string c)
5677 (setq c (js2-get-char)))))
5678 (js2-set-string-from-buffer token)
5679 (throw 'return js2-STRING))
5680 (js2-ts-return token
5681 (case c
5682 (?\;
5683 (throw 'return js2-SEMI))
5684 (?\[
5685 (throw 'return js2-LB))
5686 (?\]
5687 (throw 'return js2-RB))
5688 (?{
5689 (throw 'return js2-LC))
5690 (?}
5691 (throw 'return js2-RC))
5692 (?\(
5693 (throw 'return js2-LP))
5694 (?\)
5695 (throw 'return js2-RP))
5696 (?,
5697 (throw 'return js2-COMMA))
5698 (??
5699 (throw 'return js2-HOOK))
5700 (?:
5701 (if (js2-match-char ?:)
5702 js2-COLONCOLON
5703 (throw 'return js2-COLON)))
5704 (?.
5705 (if (js2-match-char ?.)
5706 (if (js2-match-char ?.)
5707 js2-TRIPLEDOT js2-DOTDOT)
5708 (if (js2-match-char ?\()
5709 js2-DOTQUERY
5710 (throw 'return js2-DOT))))
5711 (?|
5712 (if (js2-match-char ?|)
5713 (throw 'return js2-OR)
5714 (if (js2-match-char ?=)
5715 js2-ASSIGN_BITOR
5716 (throw 'return js2-BITOR))))
5717 (?^
5718 (if (js2-match-char ?=)
5719 js2-ASSIGN_BITOR
5720 (throw 'return js2-BITXOR)))
5721 (?&
5722 (if (js2-match-char ?&)
5723 (throw 'return js2-AND)
5724 (if (js2-match-char ?=)
5725 js2-ASSIGN_BITAND
5726 (throw 'return js2-BITAND))))
5727 (?=
5728 (if (js2-match-char ?=)
5729 (if (js2-match-char ?=)
5730 js2-SHEQ
5731 (throw 'return js2-EQ))
5732 (if (js2-match-char ?>)
5733 (js2-ts-return token js2-ARROW)
5734 (throw 'return js2-ASSIGN))))
5735 (?!
5736 (if (js2-match-char ?=)
5737 (if (js2-match-char ?=)
5738 js2-SHNE
5739 js2-NE)
5740 (throw 'return js2-NOT)))
5741 (?<
5742 ;; NB:treat HTML begin-comment as comment-till-eol
5743 (when (js2-match-char ?!)
5744 (when (js2-match-char ?-)
5745 (when (js2-match-char ?-)
5746 (js2-skip-line)
5747 (setf (js2-token-comment-type (js2-current-token)) 'html)
5748 (throw 'return js2-COMMENT)))
5749 (js2-unget-char))
5750 (if (js2-match-char ?<)
5751 (if (js2-match-char ?=)
5752 js2-ASSIGN_LSH
5753 js2-LSH)
5754 (if (js2-match-char ?=)
5755 js2-LE
5756 (throw 'return js2-LT))))
5757 (?>
5758 (if (js2-match-char ?>)
5759 (if (js2-match-char ?>)
5760 (if (js2-match-char ?=)
5761 js2-ASSIGN_URSH
5762 js2-URSH)
5763 (if (js2-match-char ?=)
5764 js2-ASSIGN_RSH
5765 js2-RSH))
5766 (if (js2-match-char ?=)
5767 js2-GE
5768 (throw 'return js2-GT))))
5769 (?*
5770 (if (js2-match-char ?=)
5771 js2-ASSIGN_MUL
5772 (throw 'return js2-MUL)))
5773 (?/
5774 ;; is it a // comment?
5775 (when (js2-match-char ?/)
5776 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5777 (js2-skip-line)
5778 (setf (js2-token-comment-type token) 'line)
5779 ;; include newline so highlighting goes to end of window
5780 (incf (js2-token-end token))
5781 (throw 'return js2-COMMENT))
5782 ;; is it a /* comment?
5783 (when (js2-match-char ?*)
5784 (setf look-for-slash nil
5785 (js2-token-beg token) (- js2-ts-cursor 2)
5786 (js2-token-comment-type token)
5787 (if (js2-match-char ?*)
5788 (progn
5789 (setq look-for-slash t)
5790 'jsdoc)
5791 'block))
5792 (while t
5793 (setq c (js2-get-char))
5794 (cond
5795 ((eq c js2-EOF_CHAR)
5796 (setf (js2-token-end token) (1- js2-ts-cursor))
5797 (js2-report-error "msg.unterminated.comment")
5798 (throw 'return js2-COMMENT))
5799 ((eq c ?*)
5800 (setq look-for-slash t))
5801 ((eq c ?/)
5802 (if look-for-slash
5803 (js2-ts-return token js2-COMMENT)))
5804 (t
5805 (setf look-for-slash nil
5806 (js2-token-end token) js2-ts-cursor)))))
5807 (if (js2-match-char ?=)
5808 js2-ASSIGN_DIV
5809 (throw 'return js2-DIV)))
5810 (?#
5811 (when js2-skip-preprocessor-directives
5812 (js2-skip-line)
5813 (setf (js2-token-comment-type token) 'preprocessor
5814 (js2-token-end token) js2-ts-cursor)
5815 (throw 'return js2-COMMENT))
5816 (throw 'return js2-ERROR))
5817 (?%
5818 (if (js2-match-char ?=)
5819 js2-ASSIGN_MOD
5820 (throw 'return js2-MOD)))
5821 (?~
5822 (throw 'return js2-BITNOT))
5823 (?+
5824 (if (js2-match-char ?=)
5825 js2-ASSIGN_ADD
5826 (if (js2-match-char ?+)
5827 js2-INC
5828 (throw 'return js2-ADD))))
5829 (?-
5830 (cond
5831 ((js2-match-char ?=)
5832 (setq c js2-ASSIGN_SUB))
5833 ((js2-match-char ?-)
5834 (unless js2-ts-dirty-line
5835 ;; treat HTML end-comment after possible whitespace
5836 ;; after line start as comment-until-eol
5837 (when (js2-match-char ?>)
5838 (js2-skip-line)
5839 (setf (js2-token-comment-type (js2-current-token)) 'html)
5840 (throw 'return js2-COMMENT)))
5841 (setq c js2-DEC))
5842 (t
5843 (setq c js2-SUB)))
5844 (setq js2-ts-dirty-line t)
5845 c)
5846 (otherwise
5847 (js2-report-scan-error "msg.illegal.character")))))))
5848 (setf (js2-token-type token) tt)
5849 token))
5850
5851 (defun js2-read-regexp (start-tt)
5852 "Called by parser when it gets / or /= in literal context."
5853 (let (c err
5854 in-class ; inside a '[' .. ']' character-class
5855 flags
5856 (continue t)
5857 (token (js2-new-token 0)))
5858 (setq js2-ts-string-buffer nil)
5859 (if (eq start-tt js2-ASSIGN_DIV)
5860 ;; mis-scanned /=
5861 (js2-add-to-string ?=)
5862 (if (not (eq start-tt js2-DIV))
5863 (error "failed assertion")))
5864 (while (and (not err)
5865 (or (/= (setq c (js2-get-char)) ?/)
5866 in-class))
5867 (cond
5868 ((or (= c ?\n)
5869 (= c js2-EOF_CHAR))
5870 (setf (js2-token-end token) (1- js2-ts-cursor)
5871 err t
5872 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5873 (js2-report-error "msg.unterminated.re.lit"))
5874 (t (cond
5875 ((= c ?\\)
5876 (js2-add-to-string c)
5877 (setq c (js2-get-char)))
5878 ((= c ?\[)
5879 (setq in-class t))
5880 ((= c ?\])
5881 (setq in-class nil)))
5882 (js2-add-to-string c))))
5883 (unless err
5884 (while continue
5885 (cond
5886 ((js2-match-char ?g)
5887 (push ?g flags))
5888 ((js2-match-char ?i)
5889 (push ?i flags))
5890 ((js2-match-char ?m)
5891 (push ?m flags))
5892 (t
5893 (setq continue nil))))
5894 (if (js2-alpha-p (js2-peek-char))
5895 (js2-report-scan-error "msg.invalid.re.flag" t
5896 js2-ts-cursor 1))
5897 (js2-set-string-from-buffer token)
5898 ;; tell `parse-partial-sexp' to ignore this range of chars
5899 (js2-record-text-property (js2-current-token-beg)
5900 (js2-current-token-end) 'syntax-class '(2)))
5901 (js2-collect-string flags)))
5902
5903 (defun js2-get-first-xml-token ()
5904 (setq js2-ts-xml-open-tags-count 0
5905 js2-ts-is-xml-attribute nil
5906 js2-ts-xml-is-tag-content nil)
5907 (js2-unget-char)
5908 (js2-get-next-xml-token))
5909
5910 (defun js2-xml-discard-string (token)
5911 "Throw away the string in progress and flag an XML parse error."
5912 (setf js2-ts-string-buffer nil
5913 (js2-token-string token) nil)
5914 (js2-report-scan-error "msg.XML.bad.form" t))
5915
5916 (defun js2-get-next-xml-token ()
5917 (setq js2-ts-string-buffer nil) ; for recording the XML
5918 (let ((token (js2-new-token 0))
5919 c result)
5920 (setq result
5921 (catch 'return
5922 (while t
5923 (setq c (js2-get-char))
5924 (cond
5925 ((= c js2-EOF_CHAR)
5926 (throw 'return js2-ERROR))
5927 (js2-ts-xml-is-tag-content
5928 (case c
5929 (?>
5930 (js2-add-to-string c)
5931 (setq js2-ts-xml-is-tag-content nil
5932 js2-ts-is-xml-attribute nil))
5933 (?/
5934 (js2-add-to-string c)
5935 (when (eq ?> (js2-peek-char))
5936 (setq c (js2-get-char))
5937 (js2-add-to-string c)
5938 (setq js2-ts-xml-is-tag-content nil)
5939 (decf js2-ts-xml-open-tags-count)))
5940 (?{
5941 (js2-unget-char)
5942 (js2-set-string-from-buffer token)
5943 (throw 'return js2-XML))
5944 ((?\' ?\")
5945 (js2-add-to-string c)
5946 (unless (js2-read-quoted-string c token)
5947 (throw 'return js2-ERROR)))
5948 (?=
5949 (js2-add-to-string c)
5950 (setq js2-ts-is-xml-attribute t))
5951 ((? ?\t ?\r ?\n)
5952 (js2-add-to-string c))
5953 (t
5954 (js2-add-to-string c)
5955 (setq js2-ts-is-xml-attribute nil)))
5956 (when (and (not js2-ts-xml-is-tag-content)
5957 (zerop js2-ts-xml-open-tags-count))
5958 (js2-set-string-from-buffer token)
5959 (throw 'return js2-XMLEND)))
5960 (t
5961 ;; else not tag content
5962 (case c
5963 (?<
5964 (js2-add-to-string c)
5965 (setq c (js2-peek-char))
5966 (case c
5967 (?!
5968 (setq c (js2-get-char)) ;; skip !
5969 (js2-add-to-string c)
5970 (setq c (js2-peek-char))
5971 (case c
5972 (?-
5973 (setq c (js2-get-char)) ;; skip -
5974 (js2-add-to-string c)
5975 (if (eq c ?-)
5976 (progn
5977 (js2-add-to-string c)
5978 (unless (js2-read-xml-comment token)
5979 (throw 'return js2-ERROR)))
5980 (js2-xml-discard-string token)
5981 (throw 'return js2-ERROR)))
5982 (?\[
5983 (setq c (js2-get-char)) ;; skip [
5984 (js2-add-to-string c)
5985 (if (and (= (js2-get-char) ?C)
5986 (= (js2-get-char) ?D)
5987 (= (js2-get-char) ?A)
5988 (= (js2-get-char) ?T)
5989 (= (js2-get-char) ?A)
5990 (= (js2-get-char) ?\[))
5991 (progn
5992 (js2-add-to-string ?C)
5993 (js2-add-to-string ?D)
5994 (js2-add-to-string ?A)
5995 (js2-add-to-string ?T)
5996 (js2-add-to-string ?A)
5997 (js2-add-to-string ?\[)
5998 (unless (js2-read-cdata token)
5999 (throw 'return js2-ERROR)))
6000 (js2-xml-discard-string token)
6001 (throw 'return js2-ERROR)))
6002 (t
6003 (unless (js2-read-entity token)
6004 (throw 'return js2-ERROR))))
6005 ;; Allow bare CDATA section, e.g.:
6006 ;; let xml = <![CDATA[ foo bar baz ]]>;
6007 (when (zerop js2-ts-xml-open-tags-count)
6008 (throw 'return js2-XMLEND)))
6009 (??
6010 (setq c (js2-get-char)) ;; skip ?
6011 (js2-add-to-string c)
6012 (unless (js2-read-PI token)
6013 (throw 'return js2-ERROR)))
6014 (?/
6015 ;; end tag
6016 (setq c (js2-get-char)) ;; skip /
6017 (js2-add-to-string c)
6018 (when (zerop js2-ts-xml-open-tags-count)
6019 (js2-xml-discard-string token)
6020 (throw 'return js2-ERROR))
6021 (setq js2-ts-xml-is-tag-content t)
6022 (decf js2-ts-xml-open-tags-count))
6023 (t
6024 ;; start tag
6025 (setq js2-ts-xml-is-tag-content t)
6026 (incf js2-ts-xml-open-tags-count))))
6027 (?{
6028 (js2-unget-char)
6029 (js2-set-string-from-buffer token)
6030 (throw 'return js2-XML))
6031 (t
6032 (js2-add-to-string c))))))))
6033 (setf (js2-token-end token) js2-ts-cursor)
6034 (setf (js2-token-type token) result)
6035 result))
6036
6037 (defun js2-read-quoted-string (quote token)
6038 (let (c)
6039 (catch 'return
6040 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6041 (js2-add-to-string c)
6042 (if (eq c quote)
6043 (throw 'return t)))
6044 (js2-xml-discard-string token) ;; throw away string in progress
6045 nil)))
6046
6047 (defun js2-read-xml-comment (token)
6048 (let ((c (js2-get-char)))
6049 (catch 'return
6050 (while (/= c js2-EOF_CHAR)
6051 (catch 'continue
6052 (js2-add-to-string c)
6053 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6054 (setq c (js2-get-char))
6055 (js2-add-to-string c)
6056 (if (eq (js2-peek-char) ?>)
6057 (progn
6058 (setq c (js2-get-char)) ;; skip >
6059 (js2-add-to-string c)
6060 (throw 'return t))
6061 (throw 'continue nil)))
6062 (setq c (js2-get-char))))
6063 (js2-xml-discard-string token)
6064 nil)))
6065
6066 (defun js2-read-cdata (token)
6067 (let ((c (js2-get-char)))
6068 (catch 'return
6069 (while (/= c js2-EOF_CHAR)
6070 (catch 'continue
6071 (js2-add-to-string c)
6072 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6073 (setq c (js2-get-char))
6074 (js2-add-to-string c)
6075 (if (eq (js2-peek-char) ?>)
6076 (progn
6077 (setq c (js2-get-char)) ;; Skip >
6078 (js2-add-to-string c)
6079 (throw 'return t))
6080 (throw 'continue nil)))
6081 (setq c (js2-get-char))))
6082 (js2-xml-discard-string token)
6083 nil)))
6084
6085 (defun js2-read-entity (token)
6086 (let ((decl-tags 1)
6087 c)
6088 (catch 'return
6089 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6090 (js2-add-to-string c)
6091 (case c
6092 (?<
6093 (incf decl-tags))
6094 (?>
6095 (decf decl-tags)
6096 (if (zerop decl-tags)
6097 (throw 'return t)))))
6098 (js2-xml-discard-string token)
6099 nil)))
6100
6101 (defun js2-read-PI (token)
6102 "Scan an XML processing instruction."
6103 (let (c)
6104 (catch 'return
6105 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6106 (js2-add-to-string c)
6107 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6108 (setq c (js2-get-char)) ;; Skip >
6109 (js2-add-to-string c)
6110 (throw 'return t)))
6111 (js2-xml-discard-string token)
6112 nil)))
6113
6114 ;;; Highlighting
6115
6116 (defun js2-set-face (beg end face &optional record)
6117 "Fontify a region. If RECORD is non-nil, record for later."
6118 (when (plusp js2-highlight-level)
6119 (setq beg (min (point-max) beg)
6120 beg (max (point-min) beg)
6121 end (min (point-max) end)
6122 end (max (point-min) end))
6123 (if record
6124 (push (list beg end face) js2-mode-fontifications)
6125 (put-text-property beg end 'font-lock-face face))))
6126
6127 (defsubst js2-clear-face (beg end)
6128 (remove-text-properties beg end '(font-lock-face nil
6129 help-echo nil
6130 point-entered nil
6131 c-in-sws nil)))
6132
6133 (defconst js2-ecma-global-props
6134 (concat "^"
6135 (regexp-opt
6136 '("Infinity" "NaN" "undefined" "arguments") t)
6137 "$")
6138 "Value properties of the Ecma-262 Global Object.
6139 Shown at or above `js2-highlight-level' 2.")
6140
6141 ;; might want to add the name "arguments" to this list?
6142 (defconst js2-ecma-object-props
6143 (concat "^"
6144 (regexp-opt
6145 '("prototype" "__proto__" "__parent__") t)
6146 "$")
6147 "Value properties of the Ecma-262 Object constructor.
6148 Shown at or above `js2-highlight-level' 2.")
6149
6150 (defconst js2-ecma-global-funcs
6151 (concat
6152 "^"
6153 (regexp-opt
6154 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6155 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6156 "$")
6157 "Function properties of the Ecma-262 Global object.
6158 Shown at or above `js2-highlight-level' 2.")
6159
6160 (defconst js2-ecma-number-props
6161 (concat "^"
6162 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6163 "NEGATIVE_INFINITY"
6164 "POSITIVE_INFINITY") t)
6165 "$")
6166 "Properties of the Ecma-262 Number constructor.
6167 Shown at or above `js2-highlight-level' 2.")
6168
6169 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6170 "Properties of the Ecma-262 Date constructor.
6171 Shown at or above `js2-highlight-level' 2.")
6172
6173 (defconst js2-ecma-math-props
6174 (concat "^"
6175 (regexp-opt
6176 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6177 t)
6178 "$")
6179 "Properties of the Ecma-262 Math object.
6180 Shown at or above `js2-highlight-level' 2.")
6181
6182 (defconst js2-ecma-math-funcs
6183 (concat "^"
6184 (regexp-opt
6185 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6186 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6187 "$")
6188 "Function properties of the Ecma-262 Math object.
6189 Shown at or above `js2-highlight-level' 2.")
6190
6191 (defconst js2-ecma-function-props
6192 (concat
6193 "^"
6194 (regexp-opt
6195 '(;; properties of the Object prototype object
6196 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6197 "toLocaleString" "toString" "valueOf"
6198 ;; properties of the Function prototype object
6199 "apply" "call"
6200 ;; properties of the Array prototype object
6201 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6202 "splice" "unshift"
6203 ;; properties of the String prototype object
6204 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6205 "localeCompare" "match" "replace" "search" "split" "substring"
6206 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6207 "toUpperCase"
6208 ;; properties of the Number prototype object
6209 "toExponential" "toFixed" "toPrecision"
6210 ;; properties of the Date prototype object
6211 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6212 "getMinutes" "getMonth" "getSeconds" "getTime"
6213 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6214 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6215 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6216 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6217 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6218 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6219 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6220 "toTimeString" "toUTCString"
6221 ;; properties of the RegExp prototype object
6222 "exec" "test"
6223 ;; properties of the JSON prototype object
6224 "parse" "stringify"
6225 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6226 "toSource" "__defineGetter__" "__defineSetter__"
6227 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6228 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6229 t)
6230 "$")
6231 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6232 Shown at or above `js2-highlight-level' 3.")
6233
6234 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6235 (let ((target-name (and target
6236 (js2-name-node-p target)
6237 (js2-name-node-name target)))
6238 (prop-name (if prop (js2-name-node-name prop)))
6239 (level2 (>= js2-highlight-level 2))
6240 (level3 (>= js2-highlight-level 3)))
6241 (when level2
6242 (let ((face
6243 (if call-p
6244 (cond
6245 ((and target prop)
6246 (cond
6247 ((and level3 (string-match js2-ecma-function-props prop-name))
6248 'font-lock-builtin-face)
6249 ((and target-name prop)
6250 (cond
6251 ((string= target-name "Date")
6252 (if (string-match js2-ecma-date-props prop-name)
6253 'font-lock-builtin-face))
6254 ((string= target-name "Math")
6255 (if (string-match js2-ecma-math-funcs prop-name)
6256 'font-lock-builtin-face))))))
6257 (prop
6258 (if (string-match js2-ecma-global-funcs prop-name)
6259 'font-lock-builtin-face)))
6260 (cond
6261 ((and target prop)
6262 (cond
6263 ((string= target-name "Number")
6264 (if (string-match js2-ecma-number-props prop-name)
6265 'font-lock-constant-face))
6266 ((string= target-name "Math")
6267 (if (string-match js2-ecma-math-props prop-name)
6268 'font-lock-constant-face))))
6269 (prop
6270 (if (string-match js2-ecma-object-props prop-name)
6271 'font-lock-constant-face))))))
6272 (when face
6273 (let ((pos (+ (js2-node-pos parent) ; absolute
6274 (js2-node-pos prop)))) ; relative
6275 (js2-set-face pos
6276 (+ pos (js2-node-len prop))
6277 face 'record)))))))
6278
6279 (defun js2-parse-highlight-member-expr-node (node)
6280 "Perform syntax highlighting of EcmaScript built-in properties.
6281 The variable `js2-highlight-level' governs this highighting."
6282 (let (face target prop name pos end parent call-p callee)
6283 (cond
6284 ;; case 1: simple name, e.g. foo
6285 ((js2-name-node-p node)
6286 (setq name (js2-name-node-name node))
6287 ;; possible for name to be nil in rare cases - saw it when
6288 ;; running js2-mode on an elisp buffer. Might as well try to
6289 ;; make it so js2-mode never barfs.
6290 (when name
6291 (setq face (if (string-match js2-ecma-global-props name)
6292 'font-lock-constant-face))
6293 (when face
6294 (setq pos (js2-node-pos node)
6295 end (+ pos (js2-node-len node)))
6296 (js2-set-face pos end face 'record))))
6297 ;; case 2: property access or function call
6298 ((or (js2-prop-get-node-p node)
6299 ;; highlight function call if expr is a prop-get node
6300 ;; or a plain name (i.e. unqualified function call)
6301 (and (setq call-p (js2-call-node-p node))
6302 (setq callee (js2-call-node-target node)) ; separate setq!
6303 (or (js2-prop-get-node-p callee)
6304 (js2-name-node-p callee))))
6305 (setq parent node
6306 node (if call-p callee node))
6307 (if (and call-p (js2-name-node-p callee))
6308 (setq prop callee)
6309 (setq target (js2-prop-get-node-left node)
6310 prop (js2-prop-get-node-right node)))
6311 (cond
6312 ((js2-name-node-p prop)
6313 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6314 (js2-parse-highlight-prop-get parent target prop call-p))
6315 ((js2-name-node-p target)
6316 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6317 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6318
6319 (defun js2-parse-highlight-member-expr-fn-name (expr)
6320 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6321 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6322 We currently only handle the case where the last component is a prop-get
6323 of a simple name. Called before EXPR has a parent node."
6324 (let (pos
6325 (name (and (js2-prop-get-node-p expr)
6326 (js2-prop-get-node-right expr))))
6327 (when (js2-name-node-p name)
6328 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6329 (js2-node-pos name)))
6330 (+ pos (js2-node-len name))
6331 'font-lock-function-name-face
6332 'record))))
6333
6334 ;; source: http://jsdoc.sourceforge.net/
6335 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6336 ;; allows type specifications, and needs work before entering the wild.
6337
6338 (defconst js2-jsdoc-param-tag-regexp
6339 (concat "^\\s-*\\*+\\s-*\\(@"
6340 "\\(?:param\\|argument\\)"
6341 "\\)"
6342 "\\s-*\\({[^}]+}\\)?" ; optional type
6343 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6344 "\\>")
6345 "Matches jsdoc tags with optional type and optional param name.")
6346
6347 (defconst js2-jsdoc-typed-tag-regexp
6348 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6349 (regexp-opt
6350 '("enum"
6351 "extends"
6352 "field"
6353 "id"
6354 "implements"
6355 "lends"
6356 "mods"
6357 "requires"
6358 "return"
6359 "returns"
6360 "throw"
6361 "throws"))
6362 "\\)\\)\\s-*\\({[^}]+}\\)?")
6363 "Matches jsdoc tags with optional type.")
6364
6365 (defconst js2-jsdoc-arg-tag-regexp
6366 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6367 (regexp-opt
6368 '("alias"
6369 "augments"
6370 "borrows"
6371 "bug"
6372 "base"
6373 "config"
6374 "default"
6375 "define"
6376 "exception"
6377 "function"
6378 "member"
6379 "memberOf"
6380 "name"
6381 "namespace"
6382 "property"
6383 "since"
6384 "suppress"
6385 "this"
6386 "throws"
6387 "type"
6388 "version"))
6389 "\\)\\)\\s-+\\([^ \t]+\\)")
6390 "Matches jsdoc tags with a single argument.")
6391
6392 (defconst js2-jsdoc-empty-tag-regexp
6393 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6394 (regexp-opt
6395 '("addon"
6396 "author"
6397 "class"
6398 "const"
6399 "constant"
6400 "constructor"
6401 "constructs"
6402 "deprecated"
6403 "desc"
6404 "description"
6405 "event"
6406 "example"
6407 "exec"
6408 "export"
6409 "fileoverview"
6410 "final"
6411 "function"
6412 "hidden"
6413 "ignore"
6414 "implicitCast"
6415 "inheritDoc"
6416 "inner"
6417 "interface"
6418 "license"
6419 "noalias"
6420 "noshadow"
6421 "notypecheck"
6422 "override"
6423 "owner"
6424 "preserve"
6425 "preserveTry"
6426 "private"
6427 "protected"
6428 "public"
6429 "static"
6430 "supported"
6431 ))
6432 "\\)\\)\\s-*")
6433 "Matches empty jsdoc tags.")
6434
6435 (defconst js2-jsdoc-link-tag-regexp
6436 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6437 "Matches a jsdoc link or code tag.")
6438
6439 (defconst js2-jsdoc-see-tag-regexp
6440 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6441 "Matches a jsdoc @see tag.")
6442
6443 (defconst js2-jsdoc-html-tag-regexp
6444 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6445 "Matches a simple (no attributes) html start- or end-tag.")
6446
6447 (defun js2-jsdoc-highlight-helper ()
6448 (js2-set-face (match-beginning 1)
6449 (match-end 1)
6450 'js2-jsdoc-tag)
6451 (if (match-beginning 2)
6452 (if (save-excursion
6453 (goto-char (match-beginning 2))
6454 (= (char-after) ?{))
6455 (js2-set-face (1+ (match-beginning 2))
6456 (1- (match-end 2))
6457 'js2-jsdoc-type)
6458 (js2-set-face (match-beginning 2)
6459 (match-end 2)
6460 'js2-jsdoc-value)))
6461 (if (match-beginning 3)
6462 (js2-set-face (match-beginning 3)
6463 (match-end 3)
6464 'js2-jsdoc-value)))
6465
6466 (defun js2-highlight-jsdoc (ast)
6467 "Highlight doc comment tags."
6468 (let ((comments (js2-ast-root-comments ast))
6469 beg end)
6470 (save-excursion
6471 (dolist (node comments)
6472 (when (eq (js2-comment-node-format node) 'jsdoc)
6473 (setq beg (js2-node-abs-pos node)
6474 end (+ beg (js2-node-len node)))
6475 (save-restriction
6476 (narrow-to-region beg end)
6477 (dolist (re (list js2-jsdoc-param-tag-regexp
6478 js2-jsdoc-typed-tag-regexp
6479 js2-jsdoc-arg-tag-regexp
6480 js2-jsdoc-link-tag-regexp
6481 js2-jsdoc-see-tag-regexp
6482 js2-jsdoc-empty-tag-regexp))
6483 (goto-char beg)
6484 (while (re-search-forward re nil t)
6485 (js2-jsdoc-highlight-helper)))
6486 ;; simple highlighting for html tags
6487 (goto-char beg)
6488 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6489 (js2-set-face (match-beginning 1)
6490 (match-end 1)
6491 'js2-jsdoc-html-tag-delimiter)
6492 (js2-set-face (match-beginning 2)
6493 (match-end 2)
6494 'js2-jsdoc-html-tag-name)
6495 (js2-set-face (match-beginning 3)
6496 (match-end 3)
6497 'js2-jsdoc-html-tag-delimiter))))))))
6498
6499 (defun js2-highlight-assign-targets (_node left right)
6500 "Highlight function properties and external variables."
6501 (let (leftpos name)
6502 ;; highlight vars and props assigned function values
6503 (when (js2-function-node-p right)
6504 (cond
6505 ;; var foo = function() {...}
6506 ((js2-name-node-p left)
6507 (setq name left))
6508 ;; foo.bar.baz = function() {...}
6509 ((and (js2-prop-get-node-p left)
6510 (js2-name-node-p (js2-prop-get-node-right left)))
6511 (setq name (js2-prop-get-node-right left))))
6512 (when name
6513 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6514 (+ leftpos (js2-node-len name))
6515 'font-lock-function-name-face
6516 'record)))))
6517
6518 (defun js2-record-name-node (node)
6519 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6520 later. NODE must be a name node."
6521 (let ((leftpos (js2-node-abs-pos node)))
6522 (push (list node js2-current-scope
6523 leftpos
6524 (+ leftpos (js2-node-len node)))
6525 js2-recorded-identifiers)))
6526
6527 (defun js2-highlight-undeclared-vars ()
6528 "After entire parse is finished, look for undeclared variable references.
6529 We have to wait until entire buffer is parsed, since JavaScript permits var
6530 decls to occur after they're used.
6531
6532 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6533 it is considered declared."
6534 (let (name)
6535 (dolist (entry js2-recorded-identifiers)
6536 (destructuring-bind (name-node scope pos end) entry
6537 (setq name (js2-name-node-name name-node))
6538 (unless (or (member name js2-global-externs)
6539 (member name js2-default-externs)
6540 (member name js2-additional-externs)
6541 (js2-get-defining-scope scope name))
6542 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6543 'js2-external-variable))))
6544 (setq js2-recorded-identifiers nil)))
6545
6546 (defun js2-set-default-externs ()
6547 "Set the value of `js2-default-externs' based on the various
6548 `js2-include-?-externs' variables."
6549 (setq js2-default-externs
6550 (append js2-ecma-262-externs
6551 (if js2-include-browser-externs js2-browser-externs)
6552 (if js2-include-rhino-externs js2-rhino-externs)
6553 (if js2-include-node-externs js2-node-externs)
6554 (if (or js2-include-browser-externs js2-include-node-externs)
6555 js2-typed-array-externs))))
6556
6557 (defun js2-apply-jslint-globals ()
6558 (setq js2-additional-externs
6559 (nconc (js2-get-jslint-globals)
6560 js2-additional-externs)))
6561
6562 (defun js2-get-jslint-globals ()
6563 (loop for node in (js2-ast-root-comments js2-mode-ast)
6564 when (and (eq 'block (js2-comment-node-format node))
6565 (save-excursion
6566 (goto-char (js2-node-abs-pos node))
6567 (looking-at "/\\*global ")))
6568 append (js2-get-jslint-globals-in
6569 (match-end 0)
6570 (js2-node-abs-end node))))
6571
6572 (defun js2-get-jslint-globals-in (beg end)
6573 (let (res)
6574 (save-excursion
6575 (goto-char beg)
6576 (while (re-search-forward js2-mode-identifier-re end t)
6577 (let ((match (match-string 0)))
6578 (unless (member match '("true" "false"))
6579 (push match res)))))
6580 (nreverse res)))
6581
6582 ;;; IMenu support
6583
6584 ;; We currently only support imenu, but eventually should support speedbar and
6585 ;; possibly other browsing mechanisms.
6586
6587 ;; The basic strategy is to identify function assignment targets of the form
6588 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6589 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6590 ;; for imenu after parsing is finished.
6591
6592 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6593 ;; JavaScript, and the general problem is undecidable. However, several forms
6594 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6595 ;; include:
6596
6597 ;; function foo() -- function declaration
6598 ;; foo = function() -- function expression assigned to variable
6599 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6600 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6601 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6602 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6603 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6604 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6605 ;; function foo() {function bar() {...}} -- nested function
6606 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6607
6608 ;; This list boils down to a few forms that can be combined recursively.
6609 ;; Top-level named function declarations include both the left-hand (name)
6610 ;; and the right-hand (function value) expressions needed to produce an imenu
6611 ;; entry. The other "right-hand" forms we need to look for are:
6612 ;; - functions declared as props/getters/setters in object literals
6613 ;; - nested named function declarations
6614 ;; The "left-hand" expressions that functions can be assigned to include:
6615 ;; - local/global variables
6616 ;; - nested property-get expressions like a.b.c.d
6617 ;; - element gets like foo[10] or foo['bar'] where the index
6618 ;; expression can be trivially converted to a property name. They
6619 ;; effectively then become property gets.
6620
6621 ;; All the different definition types are canonicalized into the form
6622 ;; foo.bar.baz = position-of-function-keyword
6623
6624 ;; We need to build a trie-like structure for imenu. As an example,
6625 ;; consider the following JavaScript code:
6626
6627 ;; a = function() {...} // function at position 5
6628 ;; b = function() {...} // function at position 25
6629 ;; foo = function() {...} // function at position 100
6630 ;; foo.bar = function() {...} // function at position 200
6631 ;; foo.bar.baz = function() {...} // function at position 300
6632 ;; foo.bar.zab = function() {...} // function at position 400
6633
6634 ;; During parsing we accumulate an entry for each definition in
6635 ;; the variable `js2-imenu-recorder', like so:
6636
6637 ;; '((fn a 5)
6638 ;; (fn b 25)
6639 ;; (fn foo 100)
6640 ;; (fn foo bar 200)
6641 ;; (fn foo bar baz 300)
6642 ;; (fn foo bar zab 400))
6643
6644 ;; Where 'fn' is the respective function node.
6645 ;; After parsing these entries are merged into this alist-trie:
6646
6647 ;; '((a . 1)
6648 ;; (b . 2)
6649 ;; (foo (<definition> . 3)
6650 ;; (bar (<definition> . 6)
6651 ;; (baz . 100)
6652 ;; (zab . 200))))
6653
6654 ;; Note the wacky need for a <definition> name. The token can be anything
6655 ;; that isn't a valid JavaScript identifier, because you might make foo
6656 ;; a function and then start setting properties on it that are also functions.
6657
6658 (defun js2-prop-node-name (node)
6659 "Return the name of a node that may be a property-get/property-name.
6660 If NODE is not a valid name-node, string-node or integral number-node,
6661 returns nil. Otherwise returns the string name/value of the node."
6662 (cond
6663 ((js2-name-node-p node)
6664 (js2-name-node-name node))
6665 ((js2-string-node-p node)
6666 (js2-string-node-value node))
6667 ((and (js2-number-node-p node)
6668 (string-match "^[0-9]+$" (js2-number-node-value node)))
6669 (js2-number-node-value node))
6670 ((js2-this-node-p node)
6671 "this")))
6672
6673 (defun js2-node-qname-component (node)
6674 "Return the name of this node, if it contributes to a qname.
6675 Returns nil if the node doesn't contribute."
6676 (copy-sequence
6677 (or (js2-prop-node-name node)
6678 (if (and (js2-function-node-p node)
6679 (js2-function-node-name node))
6680 (js2-name-node-name (js2-function-node-name node))))))
6681
6682 (defun js2-record-imenu-entry (fn-node qname pos)
6683 "Add an entry to `js2-imenu-recorder'.
6684 FN-NODE should be the current item's function node.
6685
6686 Associate FN-NODE with its QNAME for later lookup.
6687 This is used in postprocessing the chain list. For each chain, we find
6688 the parent function, look up its qname, then prepend a copy of it to the chain."
6689 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6690 (unless js2-imenu-function-map
6691 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6692 (puthash fn-node qname js2-imenu-function-map))
6693
6694 (defun js2-record-imenu-functions (node &optional var)
6695 "Record function definitions for imenu.
6696 NODE is a function node or an object literal.
6697 VAR, if non-nil, is the expression that NODE is being assigned to.
6698 When passed arguments of wrong type, does nothing."
6699 (when js2-parse-ide-mode
6700 (let ((fun-p (js2-function-node-p node))
6701 qname fname-node)
6702 (cond
6703 ;; non-anonymous function declaration?
6704 ((and fun-p
6705 (not var)
6706 (setq fname-node (js2-function-node-name node)))
6707 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6708 ;; for remaining forms, compute left-side tree branch first
6709 ((and var (setq qname (js2-compute-nested-prop-get var)))
6710 (cond
6711 ;; foo.bar.baz = function
6712 (fun-p
6713 (js2-record-imenu-entry node qname (js2-node-pos node)))
6714 ;; foo.bar.baz = object-literal
6715 ;; look for nested functions: {a: {b: function() {...} }}
6716 ((js2-object-node-p node)
6717 ;; Node position here is still absolute, since the parser
6718 ;; passes the assignment target and value expressions
6719 ;; to us before they are added as children of the assignment node.
6720 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6721
6722 (defun js2-compute-nested-prop-get (node)
6723 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6724 component nodes as a list. Otherwise return nil. Element-gets are treated
6725 as property-gets if the index expression is a string, or a positive integer."
6726 (let (left right head)
6727 (cond
6728 ((or (js2-name-node-p node)
6729 (js2-this-node-p node))
6730 (list node))
6731 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6732 ((js2-prop-get-node-p node) ; foo.bar
6733 (setq left (js2-prop-get-node-left node)
6734 right (js2-prop-get-node-right node))
6735 (if (setq head (js2-compute-nested-prop-get left))
6736 (nconc head (list right))))
6737 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6738 (setq left (js2-elem-get-node-target node)
6739 right (js2-elem-get-node-element node))
6740 (if (or (js2-string-node-p right) ; ['bar']
6741 (and (js2-number-node-p right) ; [10]
6742 (string-match "^[0-9]+$"
6743 (js2-number-node-value right))))
6744 (if (setq head (js2-compute-nested-prop-get left))
6745 (nconc head (list right))))))))
6746
6747 (defun js2-record-object-literal (node qname pos)
6748 "Recursively process an object literal looking for functions.
6749 NODE is an object literal that is the right-hand child of an assignment
6750 expression. QNAME is a list of nodes representing the assignment target,
6751 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6752 POS is the absolute position of the node.
6753 We do a depth-first traversal of NODE. For any functions we find,
6754 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6755 (let (right)
6756 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6757 (let ((left (js2-infix-node-left e))
6758 ;; Element positions are relative to the parent position.
6759 (pos (+ pos (js2-node-pos e))))
6760 (cond
6761 ;; foo: function() {...}
6762 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6763 (when (js2-prop-node-name left)
6764 ;; As a policy decision, we record the position of the property,
6765 ;; not the position of the `function' keyword, since the property
6766 ;; is effectively the name of the function.
6767 (js2-record-imenu-entry right (append qname (list left)) pos)))
6768 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6769 ((js2-object-node-p right)
6770 (js2-record-object-literal right
6771 (append qname (list (js2-infix-node-left e)))
6772 (+ pos (js2-node-pos right)))))))))
6773
6774 (defun js2-node-top-level-decl-p (node)
6775 "Return t if NODE's name is defined in the top-level scope.
6776 Also returns t if NODE's name is not defined in any scope, since it implies
6777 that it's an external variable, which must also be in the top-level scope."
6778 (let* ((name (js2-prop-node-name node))
6779 (this-scope (js2-node-get-enclosing-scope node))
6780 defining-scope)
6781 (cond
6782 ((js2-this-node-p node)
6783 nil)
6784 ((null this-scope)
6785 t)
6786 ((setq defining-scope (js2-get-defining-scope this-scope name))
6787 (js2-ast-root-p defining-scope))
6788 (t t))))
6789
6790 (defun js2-wrapper-function-p (node)
6791 "Return t if NODE is a function expression that's immediately invoked.
6792 NODE must be `js2-function-node'."
6793 (let ((parent (js2-node-parent node)))
6794 (or
6795 ;; function(){...}();
6796 (js2-call-node-p parent)
6797 (and (js2-paren-node-p parent)
6798 ;; (function(){...})();
6799 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6800 ;; (function(){...}).call(this);
6801 (and (js2-prop-get-node-p parent)
6802 (member (js2-name-node-name (js2-prop-get-node-right parent))
6803 '("call" "apply"))
6804 (js2-call-node-p (js2-node-parent parent))))))))
6805
6806 (defun js2-browse-postprocess-chains (entries)
6807 "Modify function-declaration name chains after parsing finishes.
6808 Some of the information is only available after the parse tree is complete.
6809 For instance, processing a nested scope requires a parent function node."
6810 (let (result fn parent-qname p elem)
6811 (dolist (entry entries)
6812 ;; function node goes first
6813 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6814 ;; Examine head's defining scope:
6815 ;; Pre-processed chain, or top-level/external, keep as-is.
6816 (if (or (stringp head) (js2-node-top-level-decl-p head))
6817 (push chain result)
6818 (when (js2-this-node-p head)
6819 (setq chain (cdr chain))) ; discard this-node
6820 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6821 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6822 (when (eq parent-qname 'not-found)
6823 ;; anonymous function expressions are not recorded
6824 ;; during the parse, so we need to handle this case here
6825 (setq parent-qname
6826 (if (js2-wrapper-function-p fn)
6827 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6828 (if (js2-ast-root-p grandparent)
6829 nil
6830 (gethash grandparent js2-imenu-function-map 'skip)))
6831 'skip))
6832 (puthash fn parent-qname js2-imenu-function-map))
6833 (unless (eq parent-qname 'skip)
6834 ;; prefix parent fn qname to this chain.
6835 (let ((qname (append parent-qname chain)))
6836 (puthash current-fn (butlast qname) js2-imenu-function-map)
6837 (push qname result)))))))
6838 ;; finally replace each node in each chain with its name.
6839 (dolist (chain result)
6840 (setq p chain)
6841 (while p
6842 (if (js2-node-p (setq elem (car p)))
6843 (setcar p (js2-node-qname-component elem)))
6844 (setq p (cdr p))))
6845 result))
6846
6847 ;; Merge name chains into a trie-like tree structure of nested lists.
6848 ;; To simplify construction of the trie, we first build it out using the rule
6849 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6850 ;; [key, num-or-list]. The second element can be a number; if so, this key
6851 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6852 ;; associated with the key at this level.) Otherwise the second element is
6853 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6854 ;; a simple recursive formulation.
6855 ;;
6856 ;; js2-mode is building the data structure for imenu. The imenu documentation
6857 ;; claims that it's the structure above, but in practice it wants the children
6858 ;; at the same list level as the key for that level, which is how I've drawn
6859 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6860 ;; list wrapper around the children at each level.
6861 ;;
6862 ;; A completed nested imenu-alist entry looks like this:
6863 ;; '(("foo"
6864 ;; ("<definition>" . 7)
6865 ;; ("bar"
6866 ;; ("a" . 40)
6867 ;; ("b" . 60))))
6868 ;;
6869 ;; In particular, the documentation for `imenu--index-alist' says that
6870 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6871 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6872
6873 (defun js2-treeify (lst)
6874 "Convert (a b c d) to (a ((b ((c d)))))."
6875 (if (null (cddr lst)) ; list length <= 2
6876 lst
6877 (list (car lst) (list (js2-treeify (cdr lst))))))
6878
6879 (defun js2-build-alist-trie (chains trie)
6880 "Merge declaration name chains into a trie-like alist structure for imenu.
6881 CHAINS is the qname chain list produced during parsing. TRIE is a
6882 list of elements built up so far."
6883 (let (head tail pos branch kids)
6884 (dolist (chain chains)
6885 (setq head (car chain)
6886 tail (cdr chain)
6887 pos (if (numberp (car tail)) (car tail))
6888 branch (js2-find-if (lambda (n)
6889 (string= (car n) head))
6890 trie)
6891 kids (second branch))
6892 (cond
6893 ;; case 1: this key isn't in the trie yet
6894 ((null branch)
6895 (if trie
6896 (setcdr (last trie) (list (js2-treeify chain)))
6897 (setq trie (list (js2-treeify chain)))))
6898 ;; case 2: key is present with a single number entry: replace w/ list
6899 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6900 ;; ("<definition>" 20)))
6901 ((numberp kids)
6902 (setcar (cdr branch)
6903 (list (list "<definition-1>" kids)
6904 (if pos
6905 (list "<definition-2>" pos)
6906 (js2-treeify tail)))))
6907 ;; case 3: key is there (with kids), and we're a number entry
6908 (pos
6909 (setcdr (last kids)
6910 (list
6911 (list (format "<definition-%d>"
6912 (1+ (loop for kid in kids
6913 count (eq ?< (aref (car kid) 0)))))
6914 pos))))
6915 ;; case 4: key is there with kids, need to merge in our chain
6916 (t
6917 (js2-build-alist-trie (list tail) kids))))
6918 trie))
6919
6920 (defun js2-flatten-trie (trie)
6921 "Convert TRIE to imenu-format.
6922 Recurses through nodes, and for each one whose second element is a list,
6923 appends the list's flattened elements to the current element. Also
6924 changes the tails into conses. For instance, this pre-flattened trie
6925
6926 '(a ((b 20)
6927 (c ((d 30)
6928 (e 40)))))
6929
6930 becomes
6931
6932 '(a (b . 20)
6933 (c (d . 30)
6934 (e . 40)))
6935
6936 Note that the root of the trie has no key, just a list of chains.
6937 This is also true for the value of any key with multiple children,
6938 e.g. key 'c' in the example above."
6939 (cond
6940 ((listp (car trie))
6941 (mapcar #'js2-flatten-trie trie))
6942 (t
6943 (if (numberp (second trie))
6944 (cons (car trie) (second trie))
6945 ;; else pop list and append its kids
6946 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6947
6948 (defun js2-build-imenu-index ()
6949 "Turn `js2-imenu-recorder' into an imenu data structure."
6950 (unless (eq js2-imenu-recorder 'empty)
6951 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6952 (result (js2-build-alist-trie chains nil)))
6953 (js2-flatten-trie result))))
6954
6955 (defun js2-test-print-chains (chains)
6956 "Print a list of qname chains.
6957 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6958 i.e. one or more nodes, and an integer position as the list tail."
6959 (mapconcat (lambda (chain)
6960 (concat "("
6961 (mapconcat (lambda (elem)
6962 (if (js2-node-p elem)
6963 (or (js2-node-qname-component elem)
6964 "nil")
6965 (number-to-string elem)))
6966 chain
6967 " ")
6968 ")"))
6969 chains
6970 "\n"))
6971
6972 ;;; Parser
6973
6974 (defconst js2-version "1.8.5"
6975 "Version of JavaScript supported.")
6976
6977 (defun js2-record-face (face &optional token)
6978 "Record a style run of FACE for TOKEN or the current token."
6979 (unless token (setq token (js2-current-token)))
6980 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
6981
6982 (defsubst js2-node-end (n)
6983 "Computes the absolute end of node N.
6984 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6985 is only true until the node is added to its parent; i.e., while parsing."
6986 (+ (js2-node-pos n)
6987 (js2-node-len n)))
6988
6989 (defun js2-record-comment (token)
6990 "Record a comment in `js2-scanned-comments'."
6991 (let ((ct (js2-token-comment-type token))
6992 (beg (js2-token-beg token))
6993 (end (js2-token-end token)))
6994 (push (make-js2-comment-node :len (- end beg)
6995 :format ct)
6996 js2-scanned-comments)
6997 (when js2-parse-ide-mode
6998 (js2-record-face (if (eq ct 'jsdoc)
6999 'font-lock-doc-face
7000 'font-lock-comment-face)
7001 token)
7002 (when (memq ct '(html preprocessor))
7003 ;; Tell cc-engine the bounds of the comment.
7004 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7005
7006 (defun js2-peek-token ()
7007 "Return the next token type without consuming it.
7008 If `js2-ti-lookahead' is positive, return the type of next token
7009 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7010 (if (not (zerop js2-ti-lookahead))
7011 (js2-token-type
7012 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7013 (let ((tt (js2-get-token-internal)))
7014 (js2-unget-token)
7015 tt)))
7016
7017 (defalias 'js2-next-token 'js2-get-token)
7018
7019 (defun js2-match-token (match)
7020 "Get next token and return t if it matches MATCH, a bytecode.
7021 Returns nil and consumes nothing if MATCH is not the next token."
7022 (if (/= (js2-get-token) match)
7023 (ignore (js2-unget-token))
7024 t))
7025
7026 (defun js2-match-contextual-kwd (name)
7027 "Consume and return t if next token is `js2-NAME', and its
7028 string is NAME. Returns nil and keeps current token otherwise."
7029 (if (or (/= (js2-get-token) js2-NAME)
7030 (not (string= (js2-current-token-string) name)))
7031 (progn
7032 (js2-unget-token)
7033 nil)
7034 (js2-record-face 'font-lock-keyword-face)
7035 t))
7036
7037 (defun js2-valid-prop-name-token (tt)
7038 (or (= tt js2-NAME)
7039 (and js2-allow-keywords-as-property-names
7040 (plusp tt)
7041 (aref js2-kwd-tokens tt))))
7042
7043 (defun js2-match-prop-name ()
7044 "Consume token and return t if next token is a valid property name.
7045 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7046 is non-nil and it's a keyword token."
7047 (if (js2-valid-prop-name-token (js2-get-token))
7048 t
7049 (js2-unget-token)
7050 nil))
7051
7052 (defun js2-must-match-prop-name (msg-id &optional pos len)
7053 (if (js2-match-prop-name)
7054 t
7055 (js2-report-error msg-id nil pos len)
7056 nil))
7057
7058 (defun js2-peek-token-or-eol ()
7059 "Return js2-EOL if the next token immediately follows a newline.
7060 Else returns the next token. Used in situations where we don't
7061 consider certain token types valid if they are preceded by a newline.
7062 One example is the postfix ++ or -- operator, which has to be on the
7063 same line as its operand."
7064 (let ((tt (js2-get-token))
7065 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7066 (js2-unget-token)
7067 (if follows-eol
7068 js2-EOL
7069 tt)))
7070
7071 (defun js2-must-match (token msg-id &optional pos len)
7072 "Match next token to token code TOKEN, or record a syntax error.
7073 MSG-ID is the error message to report if the match fails.
7074 Returns t on match, nil if no match."
7075 (if (js2-match-token token)
7076 t
7077 (js2-report-error msg-id nil pos len)
7078 nil))
7079
7080 (defsubst js2-inside-function ()
7081 (plusp js2-nesting-of-function))
7082
7083 (defun js2-set-requires-activation ()
7084 (if (js2-function-node-p js2-current-script-or-fn)
7085 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7086
7087 (defun js2-check-activation-name (name _token)
7088 (when (js2-inside-function)
7089 ;; skip language-version 1.2 check from Rhino
7090 (if (or (string= "arguments" name)
7091 (and js2-compiler-activation-names ; only used in codegen
7092 (gethash name js2-compiler-activation-names)))
7093 (js2-set-requires-activation))))
7094
7095 (defun js2-set-is-generator ()
7096 (if (js2-function-node-p js2-current-script-or-fn)
7097 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7098
7099 (defun js2-must-have-xml ()
7100 (unless js2-compiler-xml-available
7101 (js2-report-error "msg.XML.not.available")))
7102
7103 (defun js2-push-scope (scope)
7104 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7105 (assert (js2-scope-p scope))
7106 (assert (null (js2-scope-parent-scope scope)))
7107 (assert (not (eq js2-current-scope scope)))
7108 (setf (js2-scope-parent-scope scope) js2-current-scope
7109 js2-current-scope scope))
7110
7111 (defsubst js2-pop-scope ()
7112 (setq js2-current-scope
7113 (js2-scope-parent-scope js2-current-scope)))
7114
7115 (defun js2-enter-loop (loop-node)
7116 (push loop-node js2-loop-set)
7117 (push loop-node js2-loop-and-switch-set)
7118 (js2-push-scope loop-node)
7119 ;; Tell the current labeled statement (if any) its statement,
7120 ;; and set the jump target of the first label to the loop.
7121 ;; These are used in `js2-parse-continue' to verify that the
7122 ;; continue target is an actual labeled loop. (And for codegen.)
7123 (when js2-labeled-stmt
7124 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7125 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7126 js2-labeled-stmt))) loop-node)))
7127
7128 (defun js2-exit-loop ()
7129 (pop js2-loop-set)
7130 (pop js2-loop-and-switch-set)
7131 (js2-pop-scope))
7132
7133 (defsubst js2-enter-switch (switch-node)
7134 (push switch-node js2-loop-and-switch-set))
7135
7136 (defsubst js2-exit-switch ()
7137 (pop js2-loop-and-switch-set))
7138
7139 (defun js2-parse (&optional buf cb)
7140 "Tell the js2 parser to parse a region of JavaScript.
7141
7142 BUF is a buffer or buffer name containing the code to parse.
7143 Call `narrow-to-region' first to parse only part of the buffer.
7144
7145 The returned AST root node is given some additional properties:
7146 `node-count' - total number of nodes in the AST
7147 `buffer' - BUF. The buffer it refers to may change or be killed,
7148 so the value is not necessarily reliable.
7149
7150 An optional callback CB can be specified to report parsing
7151 progress. If `(functionp CB)' returns t, it will be called with
7152 the current line number once before parsing begins, then again
7153 each time the lexer reaches a new line number.
7154
7155 CB can also be a list of the form `(symbol cb ...)' to specify
7156 multiple callbacks with different criteria. Each symbol is a
7157 criterion keyword, and the following element is the callback to
7158 call
7159
7160 :line - called whenever the line number changes
7161 :token - called for each new token consumed
7162
7163 The list of criteria could be extended to include entering or
7164 leaving a statement, an expression, or a function definition."
7165 (if (and cb (not (functionp cb)))
7166 (error "criteria callbacks not yet implemented"))
7167 (let ((inhibit-point-motion-hooks t)
7168 (js2-compiler-xml-available (>= js2-language-version 160))
7169 ;; This is a recursive-descent parser, so give it a big stack.
7170 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7171 (max-specpdl-size (max max-specpdl-size 3000))
7172 (case-fold-search nil)
7173 ast)
7174 (message nil) ; clear any error message from previous parse
7175 (with-current-buffer (or buf (current-buffer))
7176 (setq js2-scanned-comments nil
7177 js2-parsed-errors nil
7178 js2-parsed-warnings nil
7179 js2-imenu-recorder nil
7180 js2-imenu-function-map nil
7181 js2-label-set nil)
7182 (js2-init-scanner)
7183 (setq ast (with-silent-modifications
7184 (js2-do-parse)))
7185 (unless js2-ts-hit-eof
7186 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7187 (setf (js2-ast-root-errors ast) js2-parsed-errors
7188 (js2-ast-root-warnings ast) js2-parsed-warnings)
7189 ;; if we didn't find any declarations, put a dummy in this list so we
7190 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7191 (unless js2-imenu-recorder
7192 (setq js2-imenu-recorder 'empty))
7193 (run-hooks 'js2-parse-finished-hook)
7194 ast)))
7195
7196 ;; Corresponds to Rhino's Parser.parse() method.
7197 (defun js2-do-parse ()
7198 "Parse current buffer starting from current point.
7199 Scanner should be initialized."
7200 (let ((pos js2-ts-cursor)
7201 (end js2-ts-cursor) ; in case file is empty
7202 root n tt)
7203 ;; initialize buffer-local parsing vars
7204 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7205 js2-current-script-or-fn root
7206 js2-current-scope root
7207 js2-nesting-of-function 0
7208 js2-labeled-stmt nil
7209 js2-recorded-identifiers nil) ; for js2-highlight
7210 (while (/= (setq tt (js2-get-token)) js2-EOF)
7211 (if (= tt js2-FUNCTION)
7212 (progn
7213 (setq n (if js2-called-by-compile-function
7214 (js2-parse-function-expr)
7215 (js2-parse-function-stmt))))
7216 ;; not a function - parse a statement
7217 (js2-unget-token)
7218 (setq n (js2-parse-statement)))
7219 ;; add function or statement to script
7220 (setq end (js2-node-end n))
7221 (js2-block-node-push root n))
7222 ;; add comments to root in lexical order
7223 (when js2-scanned-comments
7224 ;; if we find a comment beyond end of normal kids, use its end
7225 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7226 (dolist (comment js2-scanned-comments)
7227 (push comment (js2-ast-root-comments root))
7228 (js2-node-add-children root comment)))
7229 (setf (js2-node-len root) (- end pos))
7230 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7231 ;; Give extensions a chance to muck with things before highlighting starts.
7232 (let ((js2-additional-externs js2-additional-externs))
7233 (save-excursion
7234 (run-hooks 'js2-post-parse-callbacks))
7235 (js2-highlight-undeclared-vars))
7236 root))
7237
7238 (defun js2-function-parser ()
7239 (js2-get-token)
7240 (js2-parse-function-stmt))
7241
7242 (defun js2-parse-function-closure-body (fn-node)
7243 "Parse a JavaScript 1.8 function closure body."
7244 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7245 (if js2-ts-hit-eof
7246 (js2-report-error "msg.no.brace.body" nil
7247 (js2-node-pos fn-node)
7248 (- js2-ts-cursor (js2-node-pos fn-node)))
7249 (js2-node-add-children fn-node
7250 (setf (js2-function-node-body fn-node)
7251 (js2-parse-expr t))))))
7252
7253 (defun js2-parse-function-body (fn-node)
7254 (js2-must-match js2-LC "msg.no.brace.body"
7255 (js2-node-pos fn-node)
7256 (- js2-ts-cursor (js2-node-pos fn-node)))
7257 (let ((pos (js2-current-token-beg)) ; LC position
7258 (pn (make-js2-block-node)) ; starts at LC position
7259 tt
7260 end)
7261 (incf js2-nesting-of-function)
7262 (unwind-protect
7263 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7264 (= tt js2-EOF)
7265 (= tt js2-RC)))
7266 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7267 (js2-parse-statement)
7268 (js2-get-token)
7269 (js2-parse-function-stmt))))
7270 (decf js2-nesting-of-function))
7271 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7272 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7273 (setq end (js2-current-token-end)))
7274 (setf (js2-node-pos pn) pos
7275 (js2-node-len pn) (- end pos))
7276 (setf (js2-function-node-body fn-node) pn)
7277 (js2-node-add-children fn-node pn)
7278 pn))
7279
7280 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7281 "Declare and fontify destructuring parameters inside NODE.
7282 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7283 (cond
7284 ((js2-name-node-p node)
7285 (let (leftpos)
7286 (js2-define-symbol decl-type (js2-name-node-name node)
7287 node ignore-not-in-block)
7288 (when face
7289 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7290 (+ leftpos (js2-node-len node))
7291 face 'record))))
7292 ((js2-object-node-p node)
7293 (dolist (elem (js2-object-node-elems node))
7294 (js2-define-destruct-symbols
7295 (if (js2-object-prop-node-p elem)
7296 (js2-object-prop-node-right elem)
7297 ;; abbreviated destructuring {a, b}
7298 elem)
7299 decl-type face ignore-not-in-block)))
7300 ((js2-array-node-p node)
7301 (dolist (elem (js2-array-node-elems node))
7302 (when elem
7303 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7304 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7305 (js2-node-len node)))))
7306
7307 (defun js2-parse-function-params (function-type fn-node pos)
7308 (if (js2-match-token js2-RP)
7309 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7310 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7311 (eq (js2-current-token-type) js2-NAME)))
7312 params param default-found rest-param-at)
7313 (when paren-free-arrow
7314 (js2-unget-token))
7315 (loop for tt = (js2-peek-token)
7316 do
7317 (cond
7318 ;; destructuring param
7319 ((and (not paren-free-arrow)
7320 (or (= tt js2-LB) (= tt js2-LC)))
7321 (js2-get-token)
7322 (when default-found
7323 (js2-report-error "msg.no.default.after.default.param"))
7324 (setq param (js2-parse-destruct-primary-expr))
7325 (js2-define-destruct-symbols param
7326 js2-LP
7327 'js2-function-param)
7328 (push param params))
7329 ;; variable name
7330 (t
7331 (when (and (>= js2-language-version 200)
7332 (not paren-free-arrow)
7333 (js2-match-token js2-TRIPLEDOT)
7334 (not rest-param-at))
7335 ;; to report errors if there are more parameters
7336 (setq rest-param-at (length params)))
7337 (js2-must-match js2-NAME "msg.no.parm")
7338 (js2-record-face 'js2-function-param)
7339 (setq param (js2-create-name-node))
7340 (js2-define-symbol js2-LP (js2-current-token-string) param)
7341 ;; default parameter value
7342 (when (or (and default-found
7343 (not rest-param-at)
7344 (js2-must-match js2-ASSIGN
7345 "msg.no.default.after.default.param"
7346 (js2-node-pos param)
7347 (js2-node-len param)))
7348 (and (>= js2-language-version 200)
7349 (js2-match-token js2-ASSIGN)))
7350 (assert (not paren-free-arrow))
7351 (let* ((pos (js2-node-pos param))
7352 (tt (js2-current-token-type))
7353 (op-pos (- (js2-current-token-beg) pos))
7354 (left param)
7355 (right (js2-parse-assign-expr))
7356 (len (- (js2-node-end right) pos)))
7357 (setq param (make-js2-assign-node
7358 :type tt :pos pos :len len :op-pos op-pos
7359 :left left :right right)
7360 default-found t)
7361 (js2-node-add-children param left right)))
7362 (push param params)))
7363 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7364 (js2-report-error "msg.param.after.rest" nil
7365 (js2-node-pos param) (js2-node-len param)))
7366 while
7367 (js2-match-token js2-COMMA))
7368 (when (and (not paren-free-arrow)
7369 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7370 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7371 (when rest-param-at
7372 (setf (js2-function-node-rest-p fn-node) t))
7373 (dolist (p params)
7374 (js2-node-add-children fn-node p)
7375 (push p (js2-function-node-params fn-node))))))
7376
7377 (defun js2-check-inconsistent-return-warning (fn-node name)
7378 "Possibly show inconsistent-return warning.
7379 Last token scanned is the close-curly for the function body."
7380 (when (and js2-mode-show-strict-warnings
7381 js2-strict-inconsistent-return-warning
7382 (not (js2-has-consistent-return-usage
7383 (js2-function-node-body fn-node))))
7384 ;; Have it extend from close-curly to bol or beginning of block.
7385 (let ((pos (save-excursion
7386 (goto-char (js2-current-token-end))
7387 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7388 (point-at-bol))))
7389 (end (js2-current-token-end)))
7390 (if (plusp (js2-name-node-length name))
7391 (js2-add-strict-warning "msg.no.return.value"
7392 (js2-name-node-name name) pos end)
7393 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7394
7395 (defun js2-parse-function-stmt ()
7396 (let ((pos (js2-current-token-beg)))
7397 (js2-must-match js2-NAME "msg.unnamed.function.stmt")
7398 (let ((name (js2-create-name-node t))
7399 pn member-expr)
7400 (cond
7401 ((js2-match-token js2-LP)
7402 (js2-parse-function 'FUNCTION_STATEMENT pos name))
7403 (js2-allow-member-expr-as-function-name
7404 (setq member-expr (js2-parse-member-expr-tail nil name))
7405 (js2-parse-highlight-member-expr-fn-name member-expr)
7406 (js2-must-match js2-LP "msg.no.paren.parms")
7407 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos)
7408 (js2-function-node-member-expr pn) member-expr)
7409 pn)
7410 (t
7411 (js2-report-error "msg.no.paren.parms")
7412 (make-js2-error-node))))))
7413
7414 (defun js2-parse-function-expr ()
7415 (let ((pos (js2-current-token-beg))
7416 name)
7417 (when (js2-match-token js2-NAME)
7418 (setq name (js2-create-name-node t)))
7419 (js2-must-match js2-LP "msg.no.paren.parms")
7420 (js2-parse-function 'FUNCTION_EXPRESSION pos name)))
7421
7422 (defun js2-parse-function (function-type pos &optional name)
7423 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7424 beginning of the first token (function keyword, unless it's an
7425 arrow function), NAME is js2-name-node."
7426 (let (fn-node lp)
7427 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7428 (setq lp (js2-current-token-beg)))
7429 (setf fn-node (make-js2-function-node :pos pos
7430 :name name
7431 :form function-type
7432 :lp (if lp (- lp pos))))
7433 (when name
7434 (js2-set-face (js2-node-pos name) (js2-node-end name)
7435 'font-lock-function-name-face 'record)
7436 (when (plusp (js2-name-node-length name))
7437 ;; Function statements define a symbol in the enclosing scope
7438 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7439 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7440 ;; 1. Nested functions are not affected by the dynamic scope flag
7441 ;; as dynamic scope is already a parent of their scope.
7442 ;; 2. Functions defined under the with statement also immune to
7443 ;; this setup, in which case dynamic scope is ignored in favor
7444 ;; of the with object.
7445 (setf (js2-function-node-ignore-dynamic fn-node) t))
7446 ;; dynamically bind all the per-function variables
7447 (let ((js2-current-script-or-fn fn-node)
7448 (js2-current-scope fn-node)
7449 (js2-nesting-of-with 0)
7450 (js2-end-flags 0)
7451 js2-label-set
7452 js2-loop-set
7453 js2-loop-and-switch-set)
7454 (js2-parse-function-params function-type fn-node pos)
7455 (when (eq function-type 'FUNCTION_ARROW)
7456 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7457 (if (and (>= js2-language-version 180)
7458 (/= (js2-peek-token) js2-LC))
7459 (js2-parse-function-closure-body fn-node)
7460 (js2-parse-function-body fn-node))
7461 (js2-check-inconsistent-return-warning fn-node name)
7462
7463 (when name
7464 (js2-node-add-children fn-node name)
7465 ;; Function expressions define a name only in the body of the
7466 ;; function, and only if not hidden by a parameter name
7467 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7468 (null (js2-scope-get-symbol js2-current-scope
7469 (js2-name-node-name name))))
7470 (js2-define-symbol js2-FUNCTION
7471 (js2-name-node-name name)
7472 fn-node))
7473 (when (eq function-type 'FUNCTION_STATEMENT)
7474 (js2-record-imenu-functions fn-node))))
7475
7476 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7477 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7478 ;; We wait until after parsing the function to set its parent scope,
7479 ;; since `js2-define-symbol' needs the defining-scope check to stop
7480 ;; at the function boundary when checking for redeclarations.
7481 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7482 fn-node))
7483
7484 (defun js2-parse-statements (&optional parent)
7485 "Parse a statement list. Last token consumed must be js2-LC.
7486
7487 PARENT can be a `js2-block-node', in which case the statements are
7488 appended to PARENT. Otherwise a new `js2-block-node' is created
7489 and returned.
7490
7491 This function does not match the closing js2-RC: the caller
7492 matches the RC so it can provide a suitable error message if not
7493 matched. This means it's up to the caller to set the length of
7494 the node to include the closing RC. The node start pos is set to
7495 the absolute buffer start position, and the caller should fix it
7496 up to be relative to the parent node. All children of this block
7497 node are given relative start positions and correct lengths."
7498 (let ((pn (or parent (make-js2-block-node)))
7499 tt)
7500 (setf (js2-node-pos pn) (js2-current-token-beg))
7501 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7502 (/= tt js2-RC))
7503 (js2-block-node-push pn (js2-parse-statement)))
7504 pn))
7505
7506 (defun js2-parse-statement ()
7507 (let (pn beg end)
7508 ;; coarse-grained user-interrupt check - needs work
7509 (and js2-parse-interruptable-p
7510 (zerop (% (incf js2-parse-stmt-count)
7511 js2-statements-per-pause))
7512 (input-pending-p)
7513 (throw 'interrupted t))
7514 (setq pn (js2-statement-helper))
7515 ;; no-side-effects warning check
7516 (unless (js2-node-has-side-effects pn)
7517 (setq end (js2-node-end pn))
7518 (save-excursion
7519 (goto-char end)
7520 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7521 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7522 pn))
7523
7524 ;; These correspond to the switch cases in Parser.statementHelper
7525 (defconst js2-parsers
7526 (let ((parsers (make-vector js2-num-tokens
7527 #'js2-parse-expr-stmt)))
7528 (aset parsers js2-BREAK #'js2-parse-break)
7529 (aset parsers js2-CONST #'js2-parse-const-var)
7530 (aset parsers js2-CONTINUE #'js2-parse-continue)
7531 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7532 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7533 (aset parsers js2-DO #'js2-parse-do)
7534 (aset parsers js2-FOR #'js2-parse-for)
7535 (aset parsers js2-FUNCTION #'js2-function-parser)
7536 (aset parsers js2-IF #'js2-parse-if)
7537 (aset parsers js2-LC #'js2-parse-block)
7538 (aset parsers js2-LET #'js2-parse-let-stmt)
7539 (aset parsers js2-NAME #'js2-parse-name-or-label)
7540 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7541 (aset parsers js2-SEMI #'js2-parse-semi)
7542 (aset parsers js2-SWITCH #'js2-parse-switch)
7543 (aset parsers js2-THROW #'js2-parse-throw)
7544 (aset parsers js2-TRY #'js2-parse-try)
7545 (aset parsers js2-VAR #'js2-parse-const-var)
7546 (aset parsers js2-WHILE #'js2-parse-while)
7547 (aset parsers js2-WITH #'js2-parse-with)
7548 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7549 parsers)
7550 "A vector mapping token types to parser functions.")
7551
7552 (defun js2-parse-warn-missing-semi (beg end)
7553 (and js2-mode-show-strict-warnings
7554 js2-strict-missing-semi-warning
7555 (js2-add-strict-warning
7556 "msg.missing.semi" nil
7557 ;; back up to beginning of statement or line
7558 (max beg (save-excursion
7559 (goto-char end)
7560 (point-at-bol)))
7561 end)))
7562
7563 (defconst js2-no-semi-insertion
7564 (list js2-IF
7565 js2-SWITCH
7566 js2-WHILE
7567 js2-DO
7568 js2-FOR
7569 js2-TRY
7570 js2-WITH
7571 js2-LC
7572 js2-ERROR
7573 js2-SEMI
7574 js2-FUNCTION)
7575 "List of tokens that don't do automatic semicolon insertion.")
7576
7577 (defconst js2-autoinsert-semi-and-warn
7578 (list js2-ERROR js2-EOF js2-RC))
7579
7580 (defun js2-statement-helper ()
7581 (let* ((tt (js2-get-token))
7582 (first-tt tt)
7583 (parser (if (= tt js2-ERROR)
7584 #'js2-parse-semi
7585 (aref js2-parsers tt)))
7586 pn)
7587 ;; If the statement is set, then it's been told its label by now.
7588 (and js2-labeled-stmt
7589 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7590 (setq js2-labeled-stmt nil))
7591 (setq pn (funcall parser))
7592 ;; Don't do auto semi insertion for certain statement types.
7593 (unless (or (memq first-tt js2-no-semi-insertion)
7594 (js2-labeled-stmt-node-p pn))
7595 (js2-auto-insert-semicolon pn))
7596 pn))
7597
7598 (defun js2-auto-insert-semicolon (pn)
7599 (let* ((tt (js2-get-token))
7600 (pos (js2-node-pos pn)))
7601 (cond
7602 ((= tt js2-SEMI)
7603 ;; extend the node bounds to include the semicolon.
7604 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7605 ((memq tt js2-autoinsert-semi-and-warn)
7606 (js2-unget-token) ; Not ';', do not consume.
7607 ;; Autoinsert ;
7608 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7609 (t
7610 (if (not (js2-token-follows-eol-p (js2-current-token)))
7611 ;; Report error if no EOL or autoinsert ';' otherwise
7612 (js2-report-error "msg.no.semi.stmt")
7613 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7614 (js2-unget-token) ; Not ';', do not consume.
7615 ))))
7616
7617 (defun js2-parse-condition ()
7618 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7619 The parens are discarded and the expression node is returned.
7620 The `pos' field of the return value is set to an absolute position
7621 that must be fixed up by the caller.
7622 Return value is a list (EXPR LP RP), with absolute paren positions."
7623 (let (pn lp rp)
7624 (if (js2-must-match js2-LP "msg.no.paren.cond")
7625 (setq lp (js2-current-token-beg)))
7626 (setq pn (js2-parse-expr))
7627 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7628 (setq rp (js2-current-token-beg)))
7629 ;; Report strict warning on code like "if (a = 7) ..."
7630 (if (and js2-strict-cond-assign-warning
7631 (js2-assign-node-p pn))
7632 (js2-add-strict-warning "msg.equal.as.assign" nil
7633 (js2-node-pos pn)
7634 (+ (js2-node-pos pn)
7635 (js2-node-len pn))))
7636 (list pn lp rp)))
7637
7638 (defun js2-parse-if ()
7639 "Parser for if-statement. Last matched token must be js2-IF."
7640 (let ((pos (js2-current-token-beg))
7641 cond if-true if-false else-pos end pn)
7642 (setq cond (js2-parse-condition)
7643 if-true (js2-parse-statement)
7644 if-false (if (js2-match-token js2-ELSE)
7645 (progn
7646 (setq else-pos (- (js2-current-token-beg) pos))
7647 (js2-parse-statement)))
7648 end (js2-node-end (or if-false if-true))
7649 pn (make-js2-if-node :pos pos
7650 :len (- end pos)
7651 :condition (car cond)
7652 :then-part if-true
7653 :else-part if-false
7654 :else-pos else-pos
7655 :lp (js2-relpos (second cond) pos)
7656 :rp (js2-relpos (third cond) pos)))
7657 (js2-node-add-children pn (car cond) if-true if-false)
7658 pn))
7659
7660 (defun js2-parse-switch ()
7661 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7662 (let ((pos (js2-current-token-beg))
7663 tt pn discriminant has-default case-expr case-node
7664 case-pos cases stmt lp)
7665 (if (js2-must-match js2-LP "msg.no.paren.switch")
7666 (setq lp (js2-current-token-beg)))
7667 (setq discriminant (js2-parse-expr)
7668 pn (make-js2-switch-node :discriminant discriminant
7669 :pos pos
7670 :lp (js2-relpos lp pos)))
7671 (js2-node-add-children pn discriminant)
7672 (js2-enter-switch pn)
7673 (unwind-protect
7674 (progn
7675 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7676 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7677 (js2-must-match js2-LC "msg.no.brace.switch")
7678 (catch 'break
7679 (while t
7680 (setq tt (js2-next-token)
7681 case-pos (js2-current-token-beg))
7682 (cond
7683 ((= tt js2-RC)
7684 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7685 (throw 'break nil)) ; done
7686 ((= tt js2-CASE)
7687 (setq case-expr (js2-parse-expr))
7688 (js2-must-match js2-COLON "msg.no.colon.case"))
7689 ((= tt js2-DEFAULT)
7690 (if has-default
7691 (js2-report-error "msg.double.switch.default"))
7692 (setq has-default t
7693 case-expr nil)
7694 (js2-must-match js2-COLON "msg.no.colon.case"))
7695 (t
7696 (js2-report-error "msg.bad.switch")
7697 (throw 'break nil)))
7698 (setq case-node (make-js2-case-node :pos case-pos
7699 :len (- (js2-current-token-end) case-pos)
7700 :expr case-expr))
7701 (js2-node-add-children case-node case-expr)
7702 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7703 (/= tt js2-CASE)
7704 (/= tt js2-DEFAULT)
7705 (/= tt js2-EOF))
7706 (setf stmt (js2-parse-statement)
7707 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7708 (js2-block-node-push case-node stmt))
7709 (push case-node cases)))
7710 ;; add cases last, as pushing reverses the order to be correct
7711 (dolist (kid cases)
7712 (js2-node-add-children pn kid)
7713 (push kid (js2-switch-node-cases pn)))
7714 pn) ; return value
7715 (js2-exit-switch))))
7716
7717 (defun js2-parse-while ()
7718 "Parser for while-statement. Last matched token must be js2-WHILE."
7719 (let ((pos (js2-current-token-beg))
7720 (pn (make-js2-while-node))
7721 cond body)
7722 (js2-enter-loop pn)
7723 (unwind-protect
7724 (progn
7725 (setf cond (js2-parse-condition)
7726 (js2-while-node-condition pn) (car cond)
7727 body (js2-parse-statement)
7728 (js2-while-node-body pn) body
7729 (js2-node-len pn) (- (js2-node-end body) pos)
7730 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7731 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7732 (js2-node-add-children pn body (car cond)))
7733 (js2-exit-loop))
7734 pn))
7735
7736 (defun js2-parse-do ()
7737 "Parser for do-statement. Last matched token must be js2-DO."
7738 (let ((pos (js2-current-token-beg))
7739 (pn (make-js2-do-node))
7740 cond body end)
7741 (js2-enter-loop pn)
7742 (unwind-protect
7743 (progn
7744 (setq body (js2-parse-statement))
7745 (js2-must-match js2-WHILE "msg.no.while.do")
7746 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7747 cond (js2-parse-condition)
7748 (js2-do-node-condition pn) (car cond)
7749 (js2-do-node-body pn) body
7750 end js2-ts-cursor
7751 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7752 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7753 (js2-node-add-children pn (car cond) body))
7754 (js2-exit-loop))
7755 ;; Always auto-insert semicolon to follow SpiderMonkey:
7756 ;; It is required by ECMAScript but is ignored by the rest of
7757 ;; world; see bug 238945
7758 (if (js2-match-token js2-SEMI)
7759 (setq end js2-ts-cursor))
7760 (setf (js2-node-len pn) (- end pos))
7761 pn))
7762
7763 (defun js2-parse-for ()
7764 "Parser for for-statement. Last matched token must be js2-FOR.
7765 Parses for, for-in, and for each-in statements."
7766 (let ((for-pos (js2-current-token-beg))
7767 pn is-for-each is-for-in-or-of is-for-of
7768 in-pos each-pos tmp-pos
7769 init ; Node init is also foo in 'foo in object'
7770 cond ; Node cond is also object in 'foo in object'
7771 incr ; 3rd section of for-loop initializer
7772 body tt lp rp)
7773 ;; See if this is a for each () instead of just a for ()
7774 (when (js2-match-token js2-NAME)
7775 (if (string= "each" (js2-current-token-string))
7776 (progn
7777 (setq is-for-each t
7778 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7779 (js2-record-face 'font-lock-keyword-face))
7780 (js2-report-error "msg.no.paren.for")))
7781 (if (js2-must-match js2-LP "msg.no.paren.for")
7782 (setq lp (- (js2-current-token-beg) for-pos)))
7783 (setq tt (js2-get-token))
7784 ;; 'for' makes local scope
7785 (js2-push-scope (make-js2-scope))
7786 (unwind-protect
7787 ;; parse init clause
7788 (let ((js2-in-for-init t)) ; set as dynamic variable
7789 (cond
7790 ((= tt js2-SEMI)
7791 (js2-unget-token)
7792 (setq init (make-js2-empty-expr-node)))
7793 ((or (= tt js2-VAR) (= tt js2-LET))
7794 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7795 (t
7796 (js2-unget-token)
7797 (setq init (js2-parse-expr)))))
7798 (if (or (js2-match-token js2-IN)
7799 (and (>= js2-language-version 200)
7800 (js2-match-contextual-kwd "of")
7801 (setq is-for-of t)))
7802 (setq is-for-in-or-of t
7803 in-pos (- (js2-current-token-beg) for-pos)
7804 ;; scope of iteration target object is not the scope we've created above.
7805 ;; stash current scope temporary.
7806 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7807 (js2-parse-expr))) ; object over which we're iterating
7808 ;; else ordinary for loop - parse cond and incr
7809 (js2-must-match js2-SEMI "msg.no.semi.for")
7810 (setq cond (if (= (js2-peek-token) js2-SEMI)
7811 (make-js2-empty-expr-node) ; no loop condition
7812 (js2-parse-expr)))
7813 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7814 (setq tmp-pos (js2-current-token-end)
7815 incr (if (= (js2-peek-token) js2-RP)
7816 (make-js2-empty-expr-node :pos tmp-pos)
7817 (js2-parse-expr))))
7818 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7819 (setq rp (- (js2-current-token-beg) for-pos)))
7820 (if (not is-for-in-or-of)
7821 (setq pn (make-js2-for-node :init init
7822 :condition cond
7823 :update incr
7824 :lp lp
7825 :rp rp))
7826 ;; cond could be null if 'in obj' got eaten by the init node.
7827 (if (js2-infix-node-p init)
7828 ;; it was (foo in bar) instead of (var foo in bar)
7829 (setq cond (js2-infix-node-right init)
7830 init (js2-infix-node-left init))
7831 (if (and (js2-var-decl-node-p init)
7832 (> (length (js2-var-decl-node-kids init)) 1))
7833 (js2-report-error "msg.mult.index")))
7834 (setq pn (make-js2-for-in-node :iterator init
7835 :object cond
7836 :in-pos in-pos
7837 :foreach-p is-for-each
7838 :each-pos each-pos
7839 :forof-p is-for-of
7840 :lp lp
7841 :rp rp)))
7842 (unwind-protect
7843 (progn
7844 (js2-enter-loop pn)
7845 ;; We have to parse the body -after- creating the loop node,
7846 ;; so that the loop node appears in the js2-loop-set, allowing
7847 ;; break/continue statements to find the enclosing loop.
7848 (setf body (js2-parse-statement)
7849 (js2-loop-node-body pn) body
7850 (js2-node-pos pn) for-pos
7851 (js2-node-len pn) (- (js2-node-end body) for-pos))
7852 (js2-node-add-children pn init cond incr body))
7853 ;; finally
7854 (js2-exit-loop))
7855 (js2-pop-scope))
7856 pn))
7857
7858 (defun js2-parse-try ()
7859 "Parser for try-statement. Last matched token must be js2-TRY."
7860 (let ((try-pos (js2-current-token-beg))
7861 try-end
7862 try-block
7863 catch-blocks
7864 finally-block
7865 saw-default-catch
7866 peek
7867 param
7868 catch-cond
7869 catch-node
7870 guard-kwd
7871 catch-pos
7872 finally-pos
7873 pn
7874 block
7875 lp
7876 rp)
7877 (if (/= (js2-peek-token) js2-LC)
7878 (js2-report-error "msg.no.brace.try"))
7879 (setq try-block (js2-parse-statement)
7880 try-end (js2-node-end try-block)
7881 peek (js2-peek-token))
7882 (cond
7883 ((= peek js2-CATCH)
7884 (while (js2-match-token js2-CATCH)
7885 (setq catch-pos (js2-current-token-beg)
7886 guard-kwd nil
7887 catch-cond nil
7888 lp nil
7889 rp nil)
7890 (if saw-default-catch
7891 (js2-report-error "msg.catch.unreachable"))
7892 (if (js2-must-match js2-LP "msg.no.paren.catch")
7893 (setq lp (- (js2-current-token-beg) catch-pos)))
7894 (js2-push-scope (make-js2-scope))
7895 (let ((tt (js2-peek-token)))
7896 (cond
7897 ;; destructuring pattern
7898 ;; catch ({ message, file }) { ... }
7899 ((or (= tt js2-LB) (= tt js2-LC))
7900 (js2-get-token)
7901 (setq param (js2-parse-destruct-primary-expr))
7902 (js2-define-destruct-symbols param js2-LET nil))
7903 ;; simple name
7904 (t
7905 (js2-must-match js2-NAME "msg.bad.catchcond")
7906 (setq param (js2-create-name-node))
7907 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7908 ;; pattern guard
7909 (if (js2-match-token js2-IF)
7910 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7911 catch-cond (js2-parse-expr))
7912 (setq saw-default-catch t))
7913 (if (js2-must-match js2-RP "msg.bad.catchcond")
7914 (setq rp (- (js2-current-token-beg) catch-pos)))
7915 (js2-must-match js2-LC "msg.no.brace.catchblock")
7916 (setq block (js2-parse-statements)
7917 try-end (js2-node-end block)
7918 catch-node (make-js2-catch-node :pos catch-pos
7919 :param param
7920 :guard-expr catch-cond
7921 :guard-kwd guard-kwd
7922 :block block
7923 :lp lp
7924 :rp rp))
7925 (js2-pop-scope)
7926 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7927 (setq try-end (js2-current-token-beg)))
7928 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7929 (js2-node-len catch-node) (- try-end catch-pos))
7930 (js2-node-add-children catch-node param catch-cond block)
7931 (push catch-node catch-blocks)))
7932 ((/= peek js2-FINALLY)
7933 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7934 (js2-node-pos try-block)
7935 (- (setq try-end (js2-node-end try-block))
7936 (js2-node-pos try-block)))))
7937 (when (js2-match-token js2-FINALLY)
7938 (setq finally-pos (js2-current-token-beg)
7939 block (js2-parse-statement)
7940 try-end (js2-node-end block)
7941 finally-block (make-js2-finally-node :pos finally-pos
7942 :len (- try-end finally-pos)
7943 :body block))
7944 (js2-node-add-children finally-block block))
7945 (setq pn (make-js2-try-node :pos try-pos
7946 :len (- try-end try-pos)
7947 :try-block try-block
7948 :finally-block finally-block))
7949 (js2-node-add-children pn try-block finally-block)
7950 ;; push them onto the try-node, which reverses and corrects their order
7951 (dolist (cb catch-blocks)
7952 (js2-node-add-children pn cb)
7953 (push cb (js2-try-node-catch-clauses pn)))
7954 pn))
7955
7956 (defun js2-parse-throw ()
7957 "Parser for throw-statement. Last matched token must be js2-THROW."
7958 (let ((pos (js2-current-token-beg))
7959 expr pn)
7960 (if (= (js2-peek-token-or-eol) js2-EOL)
7961 ;; ECMAScript does not allow new lines before throw expression,
7962 ;; see bug 256617
7963 (js2-report-error "msg.bad.throw.eol"))
7964 (setq expr (js2-parse-expr)
7965 pn (make-js2-throw-node :pos pos
7966 :len (- (js2-node-end expr) pos)
7967 :expr expr))
7968 (js2-node-add-children pn expr)
7969 pn))
7970
7971 (defun js2-match-jump-label-name (label-name)
7972 "If break/continue specified a label, return that label's labeled stmt.
7973 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7974 does not match an existing label, reports an error and returns nil."
7975 (let ((bundle (cdr (assoc label-name js2-label-set))))
7976 (if (null bundle)
7977 (js2-report-error "msg.undef.label"))
7978 bundle))
7979
7980 (defun js2-parse-break ()
7981 "Parser for break-statement. Last matched token must be js2-BREAK."
7982 (let ((pos (js2-current-token-beg))
7983 (end (js2-current-token-end))
7984 break-target ; statement to break from
7985 break-label ; in "break foo", name-node representing the foo
7986 labels ; matching labeled statement to break to
7987 pn)
7988 (when (eq (js2-peek-token-or-eol) js2-NAME)
7989 (js2-get-token)
7990 (setq break-label (js2-create-name-node)
7991 end (js2-node-end break-label)
7992 ;; matchJumpLabelName only matches if there is one
7993 labels (js2-match-jump-label-name (js2-current-token-string))
7994 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7995 (unless (or break-target break-label)
7996 ;; no break target specified - try for innermost enclosing loop/switch
7997 (if (null js2-loop-and-switch-set)
7998 (unless break-label
7999 (js2-report-error "msg.bad.break" nil pos (length "break")))
8000 (setq break-target (car js2-loop-and-switch-set))))
8001 (setq pn (make-js2-break-node :pos pos
8002 :len (- end pos)
8003 :label break-label
8004 :target break-target))
8005 (js2-node-add-children pn break-label) ; but not break-target
8006 pn))
8007
8008 (defun js2-parse-continue ()
8009 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8010 (let ((pos (js2-current-token-beg))
8011 (end (js2-current-token-end))
8012 label ; optional user-specified label, a `js2-name-node'
8013 labels ; current matching labeled stmt, if any
8014 target ; the `js2-loop-node' target of this continue stmt
8015 pn)
8016 (when (= (js2-peek-token-or-eol) js2-NAME)
8017 (js2-get-token)
8018 (setq label (js2-create-name-node)
8019 end (js2-node-end label)
8020 ;; matchJumpLabelName only matches if there is one
8021 labels (js2-match-jump-label-name (js2-current-token-string))))
8022 (cond
8023 ((null labels) ; no current label to go to
8024 (if (null js2-loop-set) ; no loop to continue to
8025 (js2-report-error "msg.continue.outside" nil pos
8026 (length "continue"))
8027 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8028 (t
8029 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8030 (setq target (js2-labeled-stmt-node-stmt labels))
8031 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8032 (setq pn (make-js2-continue-node :pos pos
8033 :len (- end pos)
8034 :label label
8035 :target target))
8036 (js2-node-add-children pn label) ; but not target - it's not our child
8037 pn))
8038
8039 (defun js2-parse-with ()
8040 "Parser for with-statement. Last matched token must be js2-WITH."
8041 (let ((pos (js2-current-token-beg))
8042 obj body pn lp rp)
8043 (if (js2-must-match js2-LP "msg.no.paren.with")
8044 (setq lp (js2-current-token-beg)))
8045 (setq obj (js2-parse-expr))
8046 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8047 (setq rp (js2-current-token-beg)))
8048 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8049 (setq body (js2-parse-statement)))
8050 (setq pn (make-js2-with-node :pos pos
8051 :len (- (js2-node-end body) pos)
8052 :object obj
8053 :body body
8054 :lp (js2-relpos lp pos)
8055 :rp (js2-relpos rp pos)))
8056 (js2-node-add-children pn obj body)
8057 pn))
8058
8059 (defun js2-parse-const-var ()
8060 "Parser for var- or const-statement.
8061 Last matched token must be js2-CONST or js2-VAR."
8062 (let ((tt (js2-current-token-type))
8063 (pos (js2-current-token-beg))
8064 expr pn)
8065 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8066 pn (make-js2-expr-stmt-node :pos pos
8067 :len (- (js2-node-end expr) pos)
8068 :expr expr))
8069 (js2-node-add-children pn expr)
8070 pn))
8071
8072 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8073 (let ((pn (make-js2-expr-stmt-node :pos pos
8074 :len (js2-node-len expr)
8075 :type (if (js2-inside-function)
8076 js2-EXPR_VOID
8077 js2-EXPR_RESULT)
8078 :expr expr)))
8079 (if add-child
8080 (js2-node-add-children pn expr))
8081 pn))
8082
8083 (defun js2-parse-let-stmt ()
8084 "Parser for let-statement. Last matched token must be js2-LET."
8085 (let ((pos (js2-current-token-beg))
8086 expr pn)
8087 (if (= (js2-peek-token) js2-LP)
8088 ;; let expression in statement context
8089 (setq expr (js2-parse-let pos 'statement)
8090 pn (js2-wrap-with-expr-stmt pos expr t))
8091 ;; else we're looking at a statement like let x=6, y=7;
8092 (setf expr (js2-parse-variables js2-LET pos)
8093 pn (js2-wrap-with-expr-stmt pos expr t)
8094 (js2-node-type pn) js2-EXPR_RESULT))
8095 pn))
8096
8097 (defun js2-parse-ret-yield ()
8098 (js2-parse-return-or-yield (js2-current-token-type) nil))
8099
8100 (defconst js2-parse-return-stmt-enders
8101 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8102
8103 (defsubst js2-now-all-set (before after mask)
8104 "Return whether or not the bits in the mask have changed to all set.
8105 BEFORE is bits before change, AFTER is bits after change, and MASK is
8106 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8107 but not BEFORE."
8108 (and (/= (logand before mask) mask)
8109 (= (logand after mask) mask)))
8110
8111 (defun js2-parse-return-or-yield (tt expr-context)
8112 (let ((pos (js2-current-token-beg))
8113 (end (js2-current-token-end))
8114 (before js2-end-flags)
8115 (inside-function (js2-inside-function))
8116 e ret name)
8117 (unless inside-function
8118 (js2-report-error (if (eq tt js2-RETURN)
8119 "msg.bad.return"
8120 "msg.bad.yield")))
8121 ;; This is ugly, but we don't want to require a semicolon.
8122 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8123 (setq e (js2-parse-expr)
8124 end (js2-node-end e)))
8125 (cond
8126 ((eq tt js2-RETURN)
8127 (js2-set-flag js2-end-flags (if (null e)
8128 js2-end-returns
8129 js2-end-returns-value))
8130 (setq ret (make-js2-return-node :pos pos
8131 :len (- end pos)
8132 :retval e))
8133 (js2-node-add-children ret e)
8134 ;; See if we need a strict mode warning.
8135 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8136 ;; more thorough and accurate than this before/after flag check.
8137 ;; E.g. if there's a finally-block that always returns, we shouldn't
8138 ;; show a warning generated by inconsistent returns in the catch blocks.
8139 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8140 ;; so we know which returns/yields to highlight, and we should get rid of
8141 ;; all the checking in `js2-parse-return-or-yield'.
8142 (if (and js2-strict-inconsistent-return-warning
8143 (js2-now-all-set before js2-end-flags
8144 (logior js2-end-returns js2-end-returns-value)))
8145 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8146 (t
8147 (unless (js2-inside-function)
8148 (js2-report-error "msg.bad.yield"))
8149 (js2-set-flag js2-end-flags js2-end-yields)
8150 (setq ret (make-js2-yield-node :pos pos
8151 :len (- end pos)
8152 :value e))
8153 (js2-node-add-children ret e)
8154 (unless expr-context
8155 (setq e ret
8156 ret (js2-wrap-with-expr-stmt pos e t))
8157 (js2-set-requires-activation)
8158 (js2-set-is-generator))))
8159 ;; see if we are mixing yields and value returns.
8160 (when (and inside-function
8161 (js2-now-all-set before js2-end-flags
8162 (logior js2-end-yields js2-end-returns-value)))
8163 (setq name (js2-function-name js2-current-script-or-fn))
8164 (if (zerop (length name))
8165 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8166 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8167 ret))
8168
8169 (defun js2-parse-debugger ()
8170 (make-js2-keyword-node :type js2-DEBUGGER))
8171
8172 (defun js2-parse-block ()
8173 "Parser for a curly-delimited statement block.
8174 Last token matched must be `js2-LC'."
8175 (let ((pos (js2-current-token-beg))
8176 (pn (make-js2-scope)))
8177 (js2-push-scope pn)
8178 (unwind-protect
8179 (progn
8180 (js2-parse-statements pn)
8181 (js2-must-match js2-RC "msg.no.brace.block")
8182 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8183 (js2-pop-scope))
8184 pn))
8185
8186 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8187 (defun js2-parse-semi ()
8188 "Parse a statement or handle an error.
8189 Current token type is `js2-SEMI' or `js2-ERROR'."
8190 (let ((tt (js2-current-token-type)) pos len)
8191 (if (eq tt js2-SEMI)
8192 (make-js2-empty-expr-node :len 1)
8193 (setq pos (js2-current-token-beg)
8194 len (- (js2-current-token-end) pos))
8195 (js2-report-error "msg.syntax" nil pos len)
8196 (make-js2-error-node :pos pos :len len))))
8197
8198 (defun js2-parse-default-xml-namespace ()
8199 "Parse a `default xml namespace = <expr>' e4x statement."
8200 (let ((pos (js2-current-token-beg))
8201 end len expr unary)
8202 (js2-must-have-xml)
8203 (js2-set-requires-activation)
8204 (setq len (- js2-ts-cursor pos))
8205 (unless (and (js2-match-token js2-NAME)
8206 (string= (js2-current-token-string) "xml"))
8207 (js2-report-error "msg.bad.namespace" nil pos len))
8208 (unless (and (js2-match-token js2-NAME)
8209 (string= (js2-current-token-string) "namespace"))
8210 (js2-report-error "msg.bad.namespace" nil pos len))
8211 (unless (js2-match-token js2-ASSIGN)
8212 (js2-report-error "msg.bad.namespace" nil pos len))
8213 (setq expr (js2-parse-expr)
8214 end (js2-node-end expr)
8215 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8216 :pos pos
8217 :len (- end pos)
8218 :operand expr))
8219 (js2-node-add-children unary expr)
8220 (make-js2-expr-stmt-node :pos pos
8221 :len (- end pos)
8222 :expr unary)))
8223
8224 (defun js2-record-label (label bundle)
8225 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8226 (js2-get-token)
8227 (let ((name (js2-label-node-name label))
8228 labeled-stmt
8229 dup)
8230 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8231 ;; flag both labels if possible when used in editing mode
8232 (if (and js2-parse-ide-mode
8233 (setq dup (js2-get-label-by-name labeled-stmt name)))
8234 (js2-report-error "msg.dup.label" nil
8235 (js2-node-abs-pos dup) (js2-node-len dup)))
8236 (js2-report-error "msg.dup.label" nil
8237 (js2-node-pos label) (js2-node-len label)))
8238 (js2-labeled-stmt-node-add-label bundle label)
8239 (js2-node-add-children bundle label)
8240 ;; Add one reference to the bundle per label in `js2-label-set'
8241 (push (cons name bundle) js2-label-set)))
8242
8243 (defun js2-parse-name-or-label ()
8244 "Parser for identifier or label. Last token matched must be js2-NAME.
8245 Called when we found a name in a statement context. If it's a label, we gather
8246 up any following labels and the next non-label statement into a
8247 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8248 expression and return it wrapped in a `js2-expr-stmt-node'."
8249 (let ((pos (js2-current-token-beg))
8250 expr stmt bundle
8251 (continue t))
8252 ;; set check for label and call down to `js2-parse-primary-expr'
8253 (setq expr (js2-maybe-parse-label))
8254 (if (null expr)
8255 ;; Parse the non-label expression and wrap with expression stmt.
8256 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8257 ;; else parsed a label
8258 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8259 (js2-record-label expr bundle)
8260 ;; look for more labels
8261 (while (and continue (= (js2-get-token) js2-NAME))
8262 (if (setq expr (js2-maybe-parse-label))
8263 (js2-record-label expr bundle)
8264 (setq expr (js2-parse-expr)
8265 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8266 continue nil)
8267 (js2-auto-insert-semicolon stmt)))
8268 ;; no more labels; now parse the labeled statement
8269 (unwind-protect
8270 (unless stmt
8271 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8272 (setq stmt (js2-statement-helper))))
8273 ;; remove the labels for this statement from the global set
8274 (dolist (label (js2-labeled-stmt-node-labels bundle))
8275 (setq js2-label-set (remove label js2-label-set))))
8276 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8277 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8278 (js2-node-add-children bundle stmt)
8279 bundle)))
8280
8281 (defun js2-maybe-parse-label ()
8282 (assert (= (js2-current-token-type) js2-NAME))
8283 (let (label-pos
8284 (next-tt (js2-get-token))
8285 (label-end (js2-current-token-end)))
8286 ;; Do not consume colon, it is used as unwind indicator
8287 ;; to return to statementHelper.
8288 (js2-unget-token)
8289 (if (= next-tt js2-COLON)
8290 (prog2
8291 (setq label-pos (js2-current-token-beg))
8292 (make-js2-label-node :pos label-pos
8293 :len (- label-end label-pos)
8294 :name (js2-current-token-string))
8295 (js2-set-face label-pos
8296 label-end
8297 'font-lock-variable-name-face 'record))
8298 ;; Backtrack from the name token, too.
8299 (js2-unget-token)
8300 nil)))
8301
8302 (defun js2-parse-expr-stmt ()
8303 "Default parser in statement context, if no recognized statement found."
8304 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8305 (progn
8306 (js2-unget-token)
8307 (js2-parse-expr)) t))
8308
8309 (defun js2-parse-variables (decl-type pos)
8310 "Parse a comma-separated list of variable declarations.
8311 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8312
8313 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8314 For 'var' or 'const', the keyword should be the token last scanned.
8315
8316 POS is the position where the node should start. It's sometimes the
8317 var/const/let keyword, and other times the beginning of the first token
8318 in the first variable declaration.
8319
8320 Returns the parsed `js2-var-decl-node' expression node."
8321 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8322 :pos pos))
8323 destructuring kid-pos tt init name end nbeg nend vi
8324 (continue t))
8325 ;; Example:
8326 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8327 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8328 ;; var {a, b} = baz;
8329 (while continue
8330 (setq destructuring nil
8331 name nil
8332 tt (js2-get-token)
8333 kid-pos (js2-current-token-beg)
8334 end (js2-current-token-end)
8335 init nil)
8336 (if (or (= tt js2-LB) (= tt js2-LC))
8337 ;; Destructuring assignment, e.g., var [a, b] = ...
8338 (setq destructuring (js2-parse-destruct-primary-expr)
8339 end (js2-node-end destructuring))
8340 ;; Simple variable name
8341 (js2-unget-token)
8342 (when (js2-must-match js2-NAME "msg.bad.var")
8343 (setq name (js2-create-name-node)
8344 nbeg (js2-current-token-beg)
8345 nend (js2-current-token-end)
8346 end nend)
8347 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8348 (when (js2-match-token js2-ASSIGN)
8349 (setq init (js2-parse-assign-expr)
8350 end (js2-node-end init))
8351 (js2-record-imenu-functions init name))
8352 (when name
8353 (js2-set-face nbeg nend (if (js2-function-node-p init)
8354 'font-lock-function-name-face
8355 'font-lock-variable-name-face)
8356 'record))
8357 (setq vi (make-js2-var-init-node :pos kid-pos
8358 :len (- end kid-pos)
8359 :type decl-type))
8360 (if destructuring
8361 (progn
8362 (if (and (null init) (not js2-in-for-init))
8363 (js2-report-error "msg.destruct.assign.no.init"))
8364 (js2-define-destruct-symbols destructuring
8365 decl-type
8366 'font-lock-variable-name-face)
8367 (setf (js2-var-init-node-target vi) destructuring))
8368 (setf (js2-var-init-node-target vi) name))
8369 (setf (js2-var-init-node-initializer vi) init)
8370 (js2-node-add-children vi name destructuring init)
8371 (js2-block-node-push result vi)
8372 (unless (js2-match-token js2-COMMA)
8373 (setq continue nil)))
8374 (setf (js2-node-len result) (- end pos))
8375 result))
8376
8377 (defun js2-parse-let (pos &optional stmt-p)
8378 "Parse a let expression or statement.
8379 A let-expression is of the form `let (vars) expr'.
8380 A let-statment is of the form `let (vars) {statements}'.
8381 The third form of let is a variable declaration list, handled
8382 by `js2-parse-variables'."
8383 (let ((pn (make-js2-let-node :pos pos))
8384 beg vars body)
8385 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8386 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8387 (js2-push-scope pn)
8388 (unwind-protect
8389 (progn
8390 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8391 (if (js2-must-match js2-RP "msg.no.paren.let")
8392 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8393 (if (and stmt-p (eq (js2-get-token) js2-LC))
8394 ;; let statement
8395 (progn
8396 (setf beg (js2-current-token-beg) ; position stmt at LC
8397 body (js2-parse-statements))
8398 (js2-must-match js2-RC "msg.no.curly.let")
8399 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8400 (js2-node-len pn) (- (js2-current-token-end) pos)
8401 (js2-let-node-body pn) body
8402 (js2-node-type pn) js2-LET))
8403 ;; let expression
8404 (js2-unget-token)
8405 (setf body (js2-parse-expr)
8406 (js2-node-len pn) (- (js2-node-end body) pos)
8407 (js2-let-node-body pn) body))
8408 (js2-node-add-children pn vars body))
8409 (js2-pop-scope))
8410 pn))
8411
8412 (defun js2-define-new-symbol (decl-type name node &optional scope)
8413 (js2-scope-put-symbol (or scope js2-current-scope)
8414 name
8415 (make-js2-symbol decl-type name node)))
8416
8417 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8418 "Define a symbol in the current scope.
8419 If NODE is non-nil, it is the AST node associated with the symbol."
8420 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8421 (symbol (if defining-scope
8422 (js2-scope-get-symbol defining-scope name)))
8423 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8424 (cond
8425 ((and symbol ; already defined
8426 (or (= sdt js2-CONST) ; old version is const
8427 (= decl-type js2-CONST) ; new version is const
8428 ;; two let-bound vars in this block have same name
8429 (and (= sdt js2-LET)
8430 (eq defining-scope js2-current-scope))))
8431 (js2-report-error
8432 (cond
8433 ((= sdt js2-CONST) "msg.const.redecl")
8434 ((= sdt js2-LET) "msg.let.redecl")
8435 ((= sdt js2-VAR) "msg.var.redecl")
8436 ((= sdt js2-FUNCTION) "msg.function.redecl")
8437 (t "msg.parm.redecl"))
8438 name))
8439 ((= decl-type js2-LET)
8440 (if (and (not ignore-not-in-block)
8441 (or (= (js2-node-type js2-current-scope) js2-IF)
8442 (js2-loop-node-p js2-current-scope)))
8443 (js2-report-error "msg.let.decl.not.in.block")
8444 (js2-define-new-symbol decl-type name node)))
8445 ((or (= decl-type js2-VAR)
8446 (= decl-type js2-CONST)
8447 (= decl-type js2-FUNCTION))
8448 (if symbol
8449 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8450 (js2-add-strict-warning "msg.var.redecl" name)
8451 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8452 (js2-add-strict-warning "msg.var.hides.arg" name)))
8453 (js2-define-new-symbol decl-type name node
8454 js2-current-script-or-fn)))
8455 ((= decl-type js2-LP)
8456 (if symbol
8457 ;; must be duplicate parameter. Second parameter hides the
8458 ;; first, so go ahead and add the second pararameter
8459 (js2-report-warning "msg.dup.parms" name))
8460 (js2-define-new-symbol decl-type name node))
8461 (t (js2-code-bug)))))
8462
8463 (defun js2-parse-expr (&optional oneshot)
8464 (let* ((pn (js2-parse-assign-expr))
8465 (pos (js2-node-pos pn))
8466 left
8467 right
8468 op-pos)
8469 (while (and (not oneshot)
8470 (js2-match-token js2-COMMA))
8471 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8472 (if (= (js2-peek-token) js2-YIELD)
8473 (js2-report-error "msg.yield.parenthesized"))
8474 (setq right (js2-parse-assign-expr)
8475 left pn
8476 pn (make-js2-infix-node :type js2-COMMA
8477 :pos pos
8478 :len (- js2-ts-cursor pos)
8479 :op-pos op-pos
8480 :left left
8481 :right right))
8482 (js2-node-add-children pn left right))
8483 pn))
8484
8485 (defun js2-parse-assign-expr ()
8486 (let ((tt (js2-get-token))
8487 (pos (js2-current-token-beg))
8488 pn left right op-pos
8489 ts-state recorded-identifiers)
8490 (if (= tt js2-YIELD)
8491 (js2-parse-return-or-yield tt t)
8492 ;; Save the tokenizer state in case we find an arrow function
8493 ;; and have to rewind.
8494 (setq ts-state (make-js2-ts-state)
8495 recorded-identifiers js2-recorded-identifiers)
8496 ;; not yield - parse assignment expression
8497 (setq pn (js2-parse-cond-expr)
8498 tt (js2-get-token))
8499 (cond
8500 ((and (<= js2-first-assign tt)
8501 (<= tt js2-last-assign))
8502 ;; tt express assignment (=, |=, ^=, ..., %=)
8503 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8504 left pn)
8505 (setq right (js2-parse-assign-expr)
8506 pn (make-js2-assign-node :type tt
8507 :pos pos
8508 :len (- (js2-node-end right) pos)
8509 :op-pos op-pos
8510 :left left
8511 :right right))
8512 (when js2-parse-ide-mode
8513 (js2-highlight-assign-targets pn left right)
8514 (js2-record-imenu-functions right left))
8515 ;; do this last so ide checks above can use absolute positions
8516 (js2-node-add-children pn left right))
8517 ((and (= tt js2-ARROW)
8518 (>= js2-language-version 200))
8519 (js2-ts-seek ts-state)
8520 (setq js2-recorded-identifiers recorded-identifiers)
8521 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg))))
8522 (t
8523 (js2-unget-token)))
8524 pn)))
8525
8526 (defun js2-parse-cond-expr ()
8527 (let ((pos (js2-current-token-beg))
8528 (pn (js2-parse-or-expr))
8529 test-expr
8530 if-true
8531 if-false
8532 q-pos
8533 c-pos)
8534 (when (js2-match-token js2-HOOK)
8535 (setq q-pos (- (js2-current-token-beg) pos)
8536 if-true (js2-parse-assign-expr))
8537 (js2-must-match js2-COLON "msg.no.colon.cond")
8538 (setq c-pos (- (js2-current-token-beg) pos)
8539 if-false (js2-parse-assign-expr)
8540 test-expr pn
8541 pn (make-js2-cond-node :pos pos
8542 :len (- (js2-node-end if-false) pos)
8543 :test-expr test-expr
8544 :true-expr if-true
8545 :false-expr if-false
8546 :q-pos q-pos
8547 :c-pos c-pos))
8548 (js2-node-add-children pn test-expr if-true if-false))
8549 pn))
8550
8551 (defun js2-make-binary (type left parser)
8552 "Helper for constructing a binary-operator AST node.
8553 LEFT is the left-side-expression, already parsed, and the
8554 binary operator should have just been matched.
8555 PARSER is a function to call to parse the right operand,
8556 or a `js2-node' struct if it has already been parsed.
8557 FIXME: The latter option is unused?"
8558 (let* ((pos (js2-node-pos left))
8559 (op-pos (- (js2-current-token-beg) pos))
8560 (right (if (js2-node-p parser)
8561 parser
8562 (js2-get-token)
8563 (funcall parser)))
8564 (pn (make-js2-infix-node :type type
8565 :pos pos
8566 :len (- (js2-node-end right) pos)
8567 :op-pos op-pos
8568 :left left
8569 :right right)))
8570 (js2-node-add-children pn left right)
8571 pn))
8572
8573 (defun js2-parse-or-expr ()
8574 (let ((pn (js2-parse-and-expr)))
8575 (when (js2-match-token js2-OR)
8576 (setq pn (js2-make-binary js2-OR
8577 pn
8578 'js2-parse-or-expr)))
8579 pn))
8580
8581 (defun js2-parse-and-expr ()
8582 (let ((pn (js2-parse-bit-or-expr)))
8583 (when (js2-match-token js2-AND)
8584 (setq pn (js2-make-binary js2-AND
8585 pn
8586 'js2-parse-and-expr)))
8587 pn))
8588
8589 (defun js2-parse-bit-or-expr ()
8590 (let ((pn (js2-parse-bit-xor-expr)))
8591 (while (js2-match-token js2-BITOR)
8592 (setq pn (js2-make-binary js2-BITOR
8593 pn
8594 'js2-parse-bit-xor-expr)))
8595 pn))
8596
8597 (defun js2-parse-bit-xor-expr ()
8598 (let ((pn (js2-parse-bit-and-expr)))
8599 (while (js2-match-token js2-BITXOR)
8600 (setq pn (js2-make-binary js2-BITXOR
8601 pn
8602 'js2-parse-bit-and-expr)))
8603 pn))
8604
8605 (defun js2-parse-bit-and-expr ()
8606 (let ((pn (js2-parse-eq-expr)))
8607 (while (js2-match-token js2-BITAND)
8608 (setq pn (js2-make-binary js2-BITAND
8609 pn
8610 'js2-parse-eq-expr)))
8611 pn))
8612
8613 (defconst js2-parse-eq-ops
8614 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8615
8616 (defun js2-parse-eq-expr ()
8617 (let ((pn (js2-parse-rel-expr))
8618 tt)
8619 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8620 (setq pn (js2-make-binary tt
8621 pn
8622 'js2-parse-rel-expr)))
8623 (js2-unget-token)
8624 pn))
8625
8626 (defconst js2-parse-rel-ops
8627 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8628
8629 (defun js2-parse-rel-expr ()
8630 (let ((pn (js2-parse-shift-expr))
8631 (continue t)
8632 tt)
8633 (while continue
8634 (setq tt (js2-get-token))
8635 (cond
8636 ((and js2-in-for-init (= tt js2-IN))
8637 (js2-unget-token)
8638 (setq continue nil))
8639 ((memq tt js2-parse-rel-ops)
8640 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8641 (t
8642 (js2-unget-token)
8643 (setq continue nil))))
8644 pn))
8645
8646 (defconst js2-parse-shift-ops
8647 (list js2-LSH js2-URSH js2-RSH))
8648
8649 (defun js2-parse-shift-expr ()
8650 (let ((pn (js2-parse-add-expr))
8651 tt
8652 (continue t))
8653 (while continue
8654 (setq tt (js2-get-token))
8655 (if (memq tt js2-parse-shift-ops)
8656 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8657 (js2-unget-token)
8658 (setq continue nil)))
8659 pn))
8660
8661 (defun js2-parse-add-expr ()
8662 (let ((pn (js2-parse-mul-expr))
8663 tt
8664 (continue t))
8665 (while continue
8666 (setq tt (js2-get-token))
8667 (if (or (= tt js2-ADD) (= tt js2-SUB))
8668 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8669 (js2-unget-token)
8670 (setq continue nil)))
8671 pn))
8672
8673 (defconst js2-parse-mul-ops
8674 (list js2-MUL js2-DIV js2-MOD))
8675
8676 (defun js2-parse-mul-expr ()
8677 (let ((pn (js2-parse-unary-expr))
8678 tt
8679 (continue t))
8680 (while continue
8681 (setq tt (js2-get-token))
8682 (if (memq tt js2-parse-mul-ops)
8683 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8684 (js2-unget-token)
8685 (setq continue nil)))
8686 pn))
8687
8688 (defun js2-make-unary (type parser &rest args)
8689 "Make a unary node of type TYPE.
8690 PARSER is either a node (for postfix operators) or a function to call
8691 to parse the operand (for prefix operators)."
8692 (let* ((pos (js2-current-token-beg))
8693 (postfix (js2-node-p parser))
8694 (expr (if postfix
8695 parser
8696 (apply parser args)))
8697 end
8698 pn)
8699 (if postfix ; e.g. i++
8700 (setq pos (js2-node-pos expr)
8701 end (js2-current-token-end))
8702 (setq end (js2-node-end expr)))
8703 (setq pn (make-js2-unary-node :type type
8704 :pos pos
8705 :len (- end pos)
8706 :operand expr))
8707 (js2-node-add-children pn expr)
8708 pn))
8709
8710 (defconst js2-incrementable-node-types
8711 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8712 "Node types that can be the operand of a ++ or -- operator.")
8713
8714 (defun js2-check-bad-inc-dec (tt beg end unary)
8715 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8716 js2-incrementable-node-types)
8717 (js2-report-error (if (= tt js2-INC)
8718 "msg.bad.incr"
8719 "msg.bad.decr")
8720 nil beg (- end beg))))
8721
8722 (defun js2-parse-unary-expr ()
8723 (let ((tt (js2-current-token-type))
8724 pn expr beg end)
8725 (cond
8726 ((or (= tt js2-VOID)
8727 (= tt js2-NOT)
8728 (= tt js2-BITNOT)
8729 (= tt js2-TYPEOF))
8730 (js2-get-token)
8731 (js2-make-unary tt 'js2-parse-unary-expr))
8732 ((= tt js2-ADD)
8733 (js2-get-token)
8734 ;; Convert to special POS token in decompiler and parse tree
8735 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8736 ((= tt js2-SUB)
8737 (js2-get-token)
8738 ;; Convert to special NEG token in decompiler and parse tree
8739 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8740 ((or (= tt js2-INC)
8741 (= tt js2-DEC))
8742 (js2-get-token)
8743 (prog1
8744 (setq beg (js2-current-token-beg)
8745 end (js2-current-token-end)
8746 expr (js2-make-unary tt 'js2-parse-member-expr t))
8747 (js2-check-bad-inc-dec tt beg end expr)))
8748 ((= tt js2-DELPROP)
8749 (js2-get-token)
8750 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8751 ((= tt js2-ERROR)
8752 (js2-get-token)
8753 (make-js2-error-node)) ; try to continue
8754 ((and (= tt js2-LT)
8755 js2-compiler-xml-available)
8756 ;; XML stream encountered in expression.
8757 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8758 (t
8759 (setq pn (js2-parse-member-expr t)
8760 ;; Don't look across a newline boundary for a postfix incop.
8761 tt (js2-peek-token-or-eol))
8762 (when (or (= tt js2-INC) (= tt js2-DEC))
8763 (js2-get-token)
8764 (setf expr pn
8765 pn (js2-make-unary tt expr))
8766 (js2-node-set-prop pn 'postfix t)
8767 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8768 pn))))
8769
8770 (defun js2-parse-xml-initializer ()
8771 "Parse an E4X XML initializer.
8772 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8773 Then I'll postprocess the result, depending on whether we're in IDE
8774 mode or codegen mode, and generate the appropriate rewritten AST.
8775 IDE mode uses a rich AST that models the XML structure. Codegen mode
8776 just concatenates everything and makes a new XML or XMLList out of it."
8777 (let ((tt (js2-get-first-xml-token))
8778 pn-xml pn expr kids expr-pos
8779 (continue t)
8780 (first-token t))
8781 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8782 (js2-report-error "msg.syntax"))
8783 (setq pn-xml (make-js2-xml-node))
8784 (while continue
8785 (if first-token
8786 (setq first-token nil)
8787 (setq tt (js2-get-next-xml-token)))
8788 (cond
8789 ;; js2-XML means we found a {expr} in the XML stream.
8790 ;; The token string is the XML up to the left-curly.
8791 ((= tt js2-XML)
8792 (push (make-js2-string-node :pos (js2-current-token-beg)
8793 :len (- js2-ts-cursor (js2-current-token-beg)))
8794 kids)
8795 (js2-must-match js2-LC "msg.syntax")
8796 (setq expr-pos js2-ts-cursor
8797 expr (if (eq (js2-peek-token) js2-RC)
8798 (make-js2-empty-expr-node :pos expr-pos)
8799 (js2-parse-expr)))
8800 (js2-must-match js2-RC "msg.syntax")
8801 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8802 :len (js2-node-len expr)
8803 :expr expr))
8804 (js2-node-add-children pn expr)
8805 (push pn kids))
8806 ;; a js2-XMLEND token means we hit the final close-tag.
8807 ((= tt js2-XMLEND)
8808 (push (make-js2-string-node :pos (js2-current-token-beg)
8809 :len (- js2-ts-cursor (js2-current-token-beg)))
8810 kids)
8811 (dolist (kid (nreverse kids))
8812 (js2-block-node-push pn-xml kid))
8813 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8814 (js2-node-pos pn-xml))
8815 continue nil))
8816 (t
8817 (js2-report-error "msg.syntax")
8818 (setq continue nil))))
8819 pn-xml))
8820
8821
8822 (defun js2-parse-argument-list ()
8823 "Parse an argument list and return it as a Lisp list of nodes.
8824 Returns the list in reverse order. Consumes the right-paren token."
8825 (let (result)
8826 (unless (js2-match-token js2-RP)
8827 (loop do
8828 (if (= (js2-peek-token) js2-YIELD)
8829 (js2-report-error "msg.yield.parenthesized"))
8830 (push (js2-parse-assign-expr) result)
8831 while
8832 (js2-match-token js2-COMMA))
8833 (js2-must-match js2-RP "msg.no.paren.arg")
8834 result)))
8835
8836 (defun js2-parse-member-expr (&optional allow-call-syntax)
8837 (let ((tt (js2-current-token-type))
8838 pn pos target args beg end init)
8839 (if (/= tt js2-NEW)
8840 (setq pn (js2-parse-primary-expr))
8841 ;; parse a 'new' expression
8842 (js2-get-token)
8843 (setq pos (js2-current-token-beg)
8844 beg pos
8845 target (js2-parse-member-expr)
8846 end (js2-node-end target)
8847 pn (make-js2-new-node :pos pos
8848 :target target
8849 :len (- end pos)))
8850 (js2-node-add-children pn target)
8851 (when (js2-match-token js2-LP)
8852 ;; Add the arguments to pn, if any are supplied.
8853 (setf beg pos ; start of "new" keyword
8854 pos (js2-current-token-beg)
8855 args (nreverse (js2-parse-argument-list))
8856 (js2-new-node-args pn) args
8857 end (js2-current-token-end)
8858 (js2-new-node-lp pn) (- pos beg)
8859 (js2-new-node-rp pn) (- end 1 beg))
8860 (apply #'js2-node-add-children pn args))
8861 (when (and js2-allow-rhino-new-expr-initializer
8862 (js2-match-token js2-LC))
8863 (setf init (js2-parse-object-literal)
8864 end (js2-node-end init)
8865 (js2-new-node-initializer pn) init)
8866 (js2-node-add-children pn init))
8867 (setf (js2-node-len pn) (- end beg))) ; end outer if
8868 (js2-parse-member-expr-tail allow-call-syntax pn)))
8869
8870 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8871 "Parse a chain of property/array accesses or function calls.
8872 Includes parsing for E4X operators like `..' and `.@'.
8873 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8874 Returns an expression tree that includes PN, the parent node."
8875 (let (tt
8876 (continue t))
8877 (while continue
8878 (setq tt (js2-get-token))
8879 (cond
8880 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8881 (setq pn (js2-parse-property-access tt pn)))
8882 ((= tt js2-DOTQUERY)
8883 (setq pn (js2-parse-dot-query pn)))
8884 ((= tt js2-LB)
8885 (setq pn (js2-parse-element-get pn)))
8886 ((= tt js2-LP)
8887 (if allow-call-syntax
8888 (setq pn (js2-parse-function-call pn))
8889 (js2-unget-token)
8890 (setq continue nil)))
8891 (t
8892 (js2-unget-token)
8893 (setq continue nil))))
8894 (if (>= js2-highlight-level 2)
8895 (js2-parse-highlight-member-expr-node pn))
8896 pn))
8897
8898 (defun js2-parse-dot-query (pn)
8899 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8900 Last token parsed must be `js2-DOTQUERY'."
8901 (let ((pos (js2-node-pos pn))
8902 op-pos expr end)
8903 (js2-must-have-xml)
8904 (js2-set-requires-activation)
8905 (setq op-pos (js2-current-token-beg)
8906 expr (js2-parse-expr)
8907 end (js2-node-end expr)
8908 pn (make-js2-xml-dot-query-node :left pn
8909 :pos pos
8910 :op-pos op-pos
8911 :right expr))
8912 (js2-node-add-children pn
8913 (js2-xml-dot-query-node-left pn)
8914 (js2-xml-dot-query-node-right pn))
8915 (if (js2-must-match js2-RP "msg.no.paren")
8916 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
8917 end (js2-current-token-end)))
8918 (setf (js2-node-len pn) (- end pos))
8919 pn))
8920
8921 (defun js2-parse-element-get (pn)
8922 "Parse an element-get expression, e.g. foo[bar].
8923 Last token parsed must be `js2-RB'."
8924 (let ((lb (js2-current-token-beg))
8925 (pos (js2-node-pos pn))
8926 rb expr)
8927 (setq expr (js2-parse-expr))
8928 (if (js2-must-match js2-RB "msg.no.bracket.index")
8929 (setq rb (js2-current-token-beg)))
8930 (setq pn (make-js2-elem-get-node :target pn
8931 :pos pos
8932 :element expr
8933 :lb (js2-relpos lb pos)
8934 :rb (js2-relpos rb pos)
8935 :len (- (js2-current-token-end) pos)))
8936 (js2-node-add-children pn
8937 (js2-elem-get-node-target pn)
8938 (js2-elem-get-node-element pn))
8939 pn))
8940
8941 (defun js2-parse-function-call (pn)
8942 (let (args
8943 (pos (js2-node-pos pn)))
8944 (setq pn (make-js2-call-node :pos pos
8945 :target pn
8946 :lp (- (js2-current-token-beg) pos)))
8947 (js2-node-add-children pn (js2-call-node-target pn))
8948 ;; Add the arguments to pn, if any are supplied.
8949 (setf args (nreverse (js2-parse-argument-list))
8950 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
8951 (js2-call-node-args pn) args)
8952 (apply #'js2-node-add-children pn args)
8953 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8954 pn))
8955
8956 (defun js2-parse-property-access (tt pn)
8957 "Parse a property access, XML descendants access, or XML attr access."
8958 (let ((member-type-flags 0)
8959 (dot-pos (js2-current-token-beg))
8960 (dot-len (if (= tt js2-DOTDOT) 2 1))
8961 name
8962 ref ; right side of . or .. operator
8963 result)
8964 (when (= tt js2-DOTDOT)
8965 (js2-must-have-xml)
8966 (setq member-type-flags js2-descendants-flag))
8967 (if (not js2-compiler-xml-available)
8968 (progn
8969 (js2-must-match-prop-name "msg.no.name.after.dot")
8970 (setq name (js2-create-name-node t js2-GETPROP)
8971 result (make-js2-prop-get-node :left pn
8972 :pos (js2-current-token-beg)
8973 :right name
8974 :len (js2-current-token-len)))
8975 (js2-node-add-children result pn name)
8976 result)
8977 ;; otherwise look for XML operators
8978 (setf result (if (= tt js2-DOT)
8979 (make-js2-prop-get-node)
8980 (make-js2-infix-node :type js2-DOTDOT))
8981 (js2-node-pos result) (js2-node-pos pn)
8982 (js2-infix-node-op-pos result) dot-pos
8983 (js2-infix-node-left result) pn ; do this after setting position
8984 tt (js2-next-token))
8985 (cond
8986 ;; needed for generator.throw()
8987 ((= tt js2-THROW)
8988 (setq ref (js2-parse-property-name nil nil member-type-flags)))
8989 ;; handles: name, ns::name, ns::*, ns::[expr]
8990 ((js2-valid-prop-name-token tt)
8991 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
8992 ;; handles: *, *::name, *::*, *::[expr]
8993 ((= tt js2-MUL)
8994 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8995 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8996 ((= tt js2-XMLATTR)
8997 (setq result (js2-parse-attribute-access)))
8998 (t
8999 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9000 (if ref
9001 (setf (js2-node-len result) (- (js2-node-end ref)
9002 (js2-node-pos result))
9003 (js2-infix-node-right result) ref))
9004 (if (js2-infix-node-p result)
9005 (js2-node-add-children result
9006 (js2-infix-node-left result)
9007 (js2-infix-node-right result)))
9008 result)))
9009
9010 (defun js2-parse-attribute-access ()
9011 "Parse an E4X XML attribute expression.
9012 This includes expressions of the forms:
9013
9014 @attr @ns::attr @ns::*
9015 @* @*::attr @*::*
9016 @[expr] @*::[expr] @ns::[expr]
9017
9018 Called if we peeked an '@' token."
9019 (let ((tt (js2-next-token))
9020 (at-pos (js2-current-token-beg)))
9021 (cond
9022 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9023 ((js2-valid-prop-name-token tt)
9024 (js2-parse-property-name at-pos nil 0))
9025 ;; handles: @*, @*::name, @*::*, @*::[expr]
9026 ((= tt js2-MUL)
9027 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9028 ;; handles @[expr]
9029 ((= tt js2-LB)
9030 (js2-parse-xml-elem-ref at-pos))
9031 (t
9032 (js2-report-error "msg.no.name.after.xmlAttr")
9033 ;; Avoid cascaded errors that happen if we make an error node here.
9034 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9035
9036 (defun js2-parse-property-name (at-pos s member-type-flags)
9037 "Check if :: follows name in which case it becomes qualified name.
9038
9039 AT-POS is a natural number if we just read an '@' token, else nil.
9040 S is the name or string that was matched: an identifier, 'throw' or '*'.
9041 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9042
9043 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9044 operator, or the name is followed by ::. For a plain name, returns a
9045 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9046 (let ((pos (or at-pos (js2-current-token-beg)))
9047 colon-pos
9048 (name (js2-create-name-node t (js2-current-token-type) s))
9049 ns tt pn)
9050 (catch 'return
9051 (when (js2-match-token js2-COLONCOLON)
9052 (setq ns name
9053 colon-pos (js2-current-token-beg)
9054 tt (js2-next-token))
9055 (cond
9056 ;; handles name::name
9057 ((js2-valid-prop-name-token tt)
9058 (setq name (js2-create-name-node)))
9059 ;; handles name::*
9060 ((= tt js2-MUL)
9061 (setq name (js2-create-name-node nil nil "*")))
9062 ;; handles name::[expr]
9063 ((= tt js2-LB)
9064 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9065 (t
9066 (js2-report-error "msg.no.name.after.coloncolon"))))
9067 (if (and (null ns) (zerop member-type-flags))
9068 name
9069 (prog1
9070 (setq pn
9071 (make-js2-xml-prop-ref-node :pos pos
9072 :len (- (js2-node-end name) pos)
9073 :at-pos at-pos
9074 :colon-pos colon-pos
9075 :propname name))
9076 (js2-node-add-children pn name))))))
9077
9078 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9079 "Parse the [expr] portion of an xml element reference.
9080 For instance, @[expr], @*::[expr], or ns::[expr]."
9081 (let* ((lb (js2-current-token-beg))
9082 (pos (or at-pos lb))
9083 rb
9084 (expr (js2-parse-expr))
9085 (end (js2-node-end expr))
9086 pn)
9087 (if (js2-must-match js2-RB "msg.no.bracket.index")
9088 (setq rb (js2-current-token-beg)
9089 end (js2-current-token-end)))
9090 (prog1
9091 (setq pn
9092 (make-js2-xml-elem-ref-node :pos pos
9093 :len (- end pos)
9094 :namespace namespace
9095 :colon-pos colon-pos
9096 :at-pos at-pos
9097 :expr expr
9098 :lb (js2-relpos lb pos)
9099 :rb (js2-relpos rb pos)))
9100 (js2-node-add-children pn namespace expr))))
9101
9102 (defun js2-parse-destruct-primary-expr ()
9103 (let ((js2-is-in-destructuring t))
9104 (js2-parse-primary-expr)))
9105
9106 (defun js2-parse-primary-expr ()
9107 "Parse a literal (leaf) expression of some sort.
9108 Includes complex literals such as functions, object-literals,
9109 array-literals, array comprehensions and regular expressions."
9110 (let (pn ; parent node (usually return value)
9111 tt
9112 px-pos ; paren-expr pos
9113 len
9114 flags ; regexp flags
9115 expr)
9116 (setq tt (js2-current-token-type))
9117 (cond
9118 ((= tt js2-FUNCTION)
9119 (js2-parse-function-expr))
9120 ((= tt js2-LB)
9121 (js2-parse-array-literal))
9122 ((= tt js2-LC)
9123 (js2-parse-object-literal))
9124 ((= tt js2-LET)
9125 (js2-parse-let (js2-current-token-beg)))
9126 ((= tt js2-LP)
9127 (setq px-pos (js2-current-token-beg)
9128 expr (js2-parse-expr))
9129 (js2-must-match js2-RP "msg.no.paren")
9130 (setq pn (make-js2-paren-node :pos px-pos
9131 :expr expr
9132 :len (- (js2-current-token-end) px-pos)))
9133 (js2-node-add-children pn (js2-paren-node-expr pn))
9134 pn)
9135 ((= tt js2-XMLATTR)
9136 (js2-must-have-xml)
9137 (js2-parse-attribute-access))
9138 ((= tt js2-NAME)
9139 (js2-parse-name tt))
9140 ((= tt js2-NUMBER)
9141 (make-js2-number-node))
9142 ((= tt js2-STRING)
9143 (prog1
9144 (make-js2-string-node)
9145 (js2-record-face 'font-lock-string-face)))
9146 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9147 ;; Got / or /= which in this context means a regexp literal
9148 (setq px-pos (js2-current-token-beg))
9149 (setq flags (js2-read-regexp tt))
9150 (prog1
9151 (make-js2-regexp-node :pos px-pos
9152 :len (- js2-ts-cursor px-pos)
9153 :value (js2-current-token-string)
9154 :flags flags)
9155 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9156 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9157 ((or (= tt js2-NULL)
9158 (= tt js2-THIS)
9159 (= tt js2-FALSE)
9160 (= tt js2-TRUE))
9161 (make-js2-keyword-node :type tt))
9162 ((= tt js2-RP)
9163 ;; Not valid expression syntax, but this is valid in an arrow
9164 ;; function with no params: () => body.
9165 (if (eq (js2-peek-token) js2-ARROW)
9166 (progn
9167 (js2-unget-token) ; Put back the right paren.
9168 ;; Return whatever, it will hopefully be rewinded and
9169 ;; reparsed when we reach the =>.
9170 (make-js2-keyword-node :type js2-NULL))
9171 (js2-report-error "msg.syntax")
9172 (make-js2-error-node)))
9173 ((= tt js2-TRIPLEDOT)
9174 ;; Likewise, only valid in an arrow function with a rest param.
9175 (if (and (js2-match-token js2-NAME)
9176 (js2-match-token js2-RP)
9177 (eq (js2-peek-token) js2-ARROW))
9178 (progn
9179 (js2-unget-token) ; Put back the right paren.
9180 ;; See the previous case.
9181 (make-js2-keyword-node :type js2-NULL))
9182 (js2-report-error "msg.syntax")
9183 (make-js2-error-node)))
9184 ((= tt js2-RESERVED)
9185 (js2-report-error "msg.reserved.id")
9186 (make-js2-name-node))
9187 ((= tt js2-ERROR)
9188 ;; the scanner or one of its subroutines reported the error.
9189 (make-js2-error-node))
9190 ((= tt js2-EOF)
9191 (setq px-pos (point-at-bol)
9192 len (- js2-ts-cursor px-pos))
9193 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9194 (make-js2-error-node :pos (1- js2-ts-cursor)))
9195 (t
9196 (js2-report-error "msg.syntax")
9197 (make-js2-error-node)))))
9198
9199 (defun js2-parse-name (_tt)
9200 (let ((name (js2-current-token-string))
9201 node)
9202 (setq node (if js2-compiler-xml-available
9203 (js2-parse-property-name nil name 0)
9204 (js2-create-name-node 'check-activation nil name)))
9205 (if js2-highlight-external-variables
9206 (js2-record-name-node node))
9207 node))
9208
9209 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9210 (js2-add-strict-warning
9211 msg nil
9212 ;; back up from comma to beginning of line or array/objlit
9213 (max (if elems
9214 (js2-node-pos (car elems))
9215 pos)
9216 (save-excursion
9217 (goto-char comma-pos)
9218 (back-to-indentation)
9219 (point)))
9220 comma-pos))
9221
9222 (defun js2-parse-array-literal ()
9223 (let ((pos (js2-current-token-beg))
9224 (after-lb-or-comma t)
9225 after-comma tt elems pn
9226 (continue t))
9227 (unless js2-is-in-destructuring
9228 (js2-push-scope (make-js2-scope))) ; for array comp
9229 (while continue
9230 (setq tt (js2-get-token))
9231 (cond
9232 ;; comma
9233 ((= tt js2-COMMA)
9234 (setq after-comma (js2-current-token-end))
9235 (if (not after-lb-or-comma)
9236 (setq after-lb-or-comma t)
9237 (push nil elems)))
9238 ;; end of array
9239 ((or (= tt js2-RB)
9240 (= tt js2-EOF)) ; prevent infinite loop
9241 (if (= tt js2-EOF)
9242 (js2-report-error "msg.no.bracket.arg" nil pos))
9243 (setq continue nil
9244 pn (make-js2-array-node :pos pos
9245 :len (- js2-ts-cursor pos)
9246 :elems (nreverse elems)))
9247 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9248 (when (and after-comma (not js2-is-in-destructuring))
9249 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9250 pos elems after-comma)))
9251 ;; destructuring binding
9252 (js2-is-in-destructuring
9253 (push (if (or (= tt js2-LC)
9254 (= tt js2-LB)
9255 (= tt js2-NAME))
9256 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9257 (js2-parse-destruct-primary-expr)
9258 ;; invalid pattern
9259 (js2-report-error "msg.bad.var")
9260 (make-js2-error-node))
9261 elems)
9262 (setq after-lb-or-comma nil
9263 after-comma nil))
9264 ;; array comp
9265 ((and (>= js2-language-version 170)
9266 (= tt js2-FOR) ; check for array comprehension
9267 (not after-lb-or-comma) ; "for" can't follow a comma
9268 elems ; must have at least 1 element
9269 (not (cdr elems))) ; but no 2nd element
9270 (js2-unget-token)
9271 (setf continue nil
9272 pn (js2-parse-array-comprehension (car elems) pos)))
9273
9274 ;; another element
9275 (t
9276 (unless after-lb-or-comma
9277 (js2-report-error "msg.no.bracket.arg"))
9278 (js2-unget-token)
9279 (push (js2-parse-assign-expr) elems)
9280 (setq after-lb-or-comma nil
9281 after-comma nil))))
9282 (unless js2-is-in-destructuring
9283 (js2-pop-scope))
9284 pn))
9285
9286 (defun js2-parse-array-comprehension (expr pos)
9287 "Parse a JavaScript 1.7 Array Comprehension.
9288 EXPR is the first expression after the opening left-bracket.
9289 POS is the beginning of the LB token preceding EXPR.
9290 We should have just parsed the 'for' keyword before calling this function."
9291 (let (loops loop first filter if-pos result)
9292 (while (= (js2-get-token) js2-FOR)
9293 (let ((prev (car loops))) ; rearrange scope chain
9294 (push (setq loop (js2-parse-array-comp-loop)) loops)
9295 (if prev ; each loop is parent scope to the next one
9296 (setf (js2-scope-parent-scope loop) prev)
9297 ; first loop takes expr scope's parent
9298 (setf (js2-scope-parent-scope (setq first loop))
9299 (js2-scope-parent-scope js2-current-scope)))))
9300 (js2-unget-token)
9301 ;; set expr scope's parent to the last loop
9302 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9303 (if (/= (js2-get-token) js2-IF)
9304 (js2-unget-token)
9305 (setq if-pos (- (js2-current-token-beg) pos) ; relative
9306 filter (js2-parse-condition)))
9307 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9308 (setq result (make-js2-array-comp-node :pos pos
9309 :len (- js2-ts-cursor pos)
9310 :result expr
9311 :loops (nreverse loops)
9312 :filter (car filter)
9313 :lp (js2-relpos (second filter) pos)
9314 :rp (js2-relpos (third filter) pos)
9315 :if-pos if-pos))
9316 (apply #'js2-node-add-children result expr (car filter)
9317 (js2-array-comp-node-loops result))
9318 (setq js2-current-scope first) ; pop to the first loop
9319 result))
9320
9321 (defun js2-parse-array-comp-loop ()
9322 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9323 Last token peeked should be the initial FOR."
9324 (let ((pos (js2-current-token-beg))
9325 (pn (make-js2-array-comp-loop-node))
9326 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9327 (assert (= (js2-current-token-type) js2-FOR))
9328 (js2-push-scope pn)
9329 (unwind-protect
9330 (progn
9331 (when (js2-match-token js2-NAME)
9332 (if (string= (js2-current-token-string) "each")
9333 (progn
9334 (setq foreach-p t
9335 each-pos (- (js2-current-token-beg) pos)) ; relative
9336 (js2-record-face 'font-lock-keyword-face))
9337 (js2-report-error "msg.no.paren.for")))
9338 (if (js2-must-match js2-LP "msg.no.paren.for")
9339 (setq lp (- (js2-current-token-beg) pos)))
9340 (setq tt (js2-peek-token))
9341 (cond
9342 ((or (= tt js2-LB)
9343 (= tt js2-LC))
9344 (js2-get-token)
9345 (setq iter (js2-parse-destruct-primary-expr))
9346 (js2-define-destruct-symbols iter js2-LET
9347 'font-lock-variable-name-face t))
9348 ((js2-match-token js2-NAME)
9349 (setq iter (js2-create-name-node)))
9350 (t
9351 (js2-report-error "msg.bad.var")))
9352 ;; Define as a let since we want the scope of the variable to
9353 ;; be restricted to the array comprehension
9354 (if (js2-name-node-p iter)
9355 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9356 (if (or (js2-match-token js2-IN)
9357 (and (>= js2-language-version 200)
9358 (js2-match-contextual-kwd "of")
9359 (setq forof-p t)))
9360 (setq in-pos (- (js2-current-token-beg) pos))
9361 (js2-report-error "msg.in.after.for.name"))
9362 (setq obj (js2-parse-expr))
9363 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9364 (setq rp (- (js2-current-token-beg) pos)))
9365 (setf (js2-node-pos pn) pos
9366 (js2-node-len pn) (- js2-ts-cursor pos)
9367 (js2-array-comp-loop-node-iterator pn) iter
9368 (js2-array-comp-loop-node-object pn) obj
9369 (js2-array-comp-loop-node-in-pos pn) in-pos
9370 (js2-array-comp-loop-node-each-pos pn) each-pos
9371 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9372 (js2-array-comp-loop-node-forof-p pn) forof-p
9373 (js2-array-comp-loop-node-lp pn) lp
9374 (js2-array-comp-loop-node-rp pn) rp)
9375 (js2-node-add-children pn iter obj))
9376 (js2-pop-scope))
9377 pn))
9378
9379 (defun js2-parse-object-literal ()
9380 (let ((pos (js2-current-token-beg))
9381 tt elems result after-comma
9382 (continue t))
9383 (while continue
9384 (setq tt (js2-get-token))
9385 (cond
9386 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9387 ;; {get foo() {...}}, or {set foo(x) {...}}
9388 ((or (js2-valid-prop-name-token tt)
9389 (= tt js2-STRING))
9390 (setq after-comma nil
9391 result (js2-parse-named-prop tt))
9392 (if (and (null result)
9393 (not js2-recover-from-parse-errors))
9394 (setq continue nil)
9395 (push result elems)))
9396 ;; {12: x} or {10.7: x}
9397 ((= tt js2-NUMBER)
9398 (setq after-comma nil)
9399 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9400 ;; trailing comma
9401 ((= tt js2-RC)
9402 (js2-unget-token)
9403 (setq continue nil)
9404 (if after-comma
9405 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9406 pos elems after-comma)))
9407 (t
9408 (js2-report-error "msg.bad.prop")
9409 (unless js2-recover-from-parse-errors
9410 (setq continue nil)))) ; end switch
9411 (if (js2-match-token js2-COMMA)
9412 (setq after-comma (js2-current-token-end))
9413 (setq continue nil))) ; end loop
9414 (js2-must-match js2-RC "msg.no.brace.prop")
9415 (setq result (make-js2-object-node :pos pos
9416 :len (- js2-ts-cursor pos)
9417 :elems (nreverse elems)))
9418 (apply #'js2-node-add-children result (js2-object-node-elems result))
9419 result))
9420
9421 (defun js2-parse-named-prop (tt)
9422 "Parse a name, string, or getter/setter object property.
9423 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9424 (let ((string-prop (and (= tt js2-STRING)
9425 (make-js2-string-node)))
9426 expr
9427 (ppos (js2-current-token-beg))
9428 (pend (js2-current-token-end))
9429 (name (js2-create-name-node))
9430 (prop (js2-current-token-string)))
9431 (cond
9432 ;; getter/setter prop
9433 ((and (= tt js2-NAME)
9434 (= (js2-peek-token) js2-NAME)
9435 (or (string= prop "get")
9436 (string= prop "set")))
9437 (js2-get-token)
9438 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9439 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9440 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9441 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9442 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9443 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9444 ;; when patterns are used in variable declarations, function parameters,
9445 ;; catch-clause, and iterators.
9446 ;; We have to set `js2-is-in-destructuring' to t when the current
9447 ;; expressions are on the left side of any assignment, but it's difficult
9448 ;; because it requires looking ahead of expression.
9449 ((and js2-is-in-destructuring
9450 (= tt js2-NAME)
9451 (let ((ctk (js2-peek-token)))
9452 (or (= ctk js2-COMMA)
9453 (= ctk js2-RC)
9454 (js2-valid-prop-name-token ctk))))
9455 name)
9456 ;; regular prop
9457 (t
9458 (prog1
9459 (setq expr (js2-parse-plain-property (or string-prop name)))
9460 (js2-set-face ppos pend
9461 (if (js2-function-node-p
9462 (js2-object-prop-node-right expr))
9463 'font-lock-function-name-face
9464 'font-lock-variable-name-face)
9465 'record))))))
9466
9467 (defun js2-parse-plain-property (prop)
9468 "Parse a non-getter/setter property in an object literal.
9469 PROP is the node representing the property: a number, name or string."
9470 (js2-must-match js2-COLON "msg.no.colon.prop")
9471 (let* ((pos (js2-node-pos prop))
9472 (colon (- (js2-current-token-beg) pos))
9473 (expr (js2-parse-assign-expr))
9474 (result (make-js2-object-prop-node
9475 :pos pos
9476 ;; don't include last consumed token in length
9477 :len (- (+ (js2-node-pos expr)
9478 (js2-node-len expr))
9479 pos)
9480 :left prop
9481 :right expr
9482 :op-pos colon)))
9483 (js2-node-add-children result prop expr)
9484 result))
9485
9486 (defun js2-parse-getter-setter-prop (pos prop get-p)
9487 "Parse getter or setter property in an object literal.
9488 JavaScript syntax is:
9489
9490 { get foo() {...}, set foo(x) {...} }
9491
9492 and expression closure style is also supported
9493
9494 { get foo() x, set foo(x) _x = x }
9495
9496 POS is the start position of the `get' or `set' keyword.
9497 PROP is the `js2-name-node' representing the property name.
9498 GET-P is non-nil if the keyword was `get'."
9499 (let ((type (if get-p js2-GET js2-SET))
9500 result end
9501 (fn (js2-parse-function-expr)))
9502 ;; it has to be an anonymous function, as we already parsed the name
9503 (if (/= (js2-node-type fn) js2-FUNCTION)
9504 (js2-report-error "msg.bad.prop")
9505 (if (plusp (length (js2-function-name fn)))
9506 (js2-report-error "msg.bad.prop")))
9507 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9508 (setq end (js2-node-end fn)
9509 result (make-js2-getter-setter-node :type type
9510 :pos pos
9511 :len (- end pos)
9512 :left prop
9513 :right fn))
9514 (js2-node-add-children result prop fn)
9515 result))
9516
9517 (defun js2-create-name-node (&optional check-activation-p token string)
9518 "Create a name node using the current token and, optionally, STRING.
9519 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9520 (let* ((beg (js2-current-token-beg))
9521 (tt (js2-current-token-type))
9522 (s (or string
9523 (if (= js2-NAME tt)
9524 (js2-current-token-string)
9525 (js2-tt-name tt))))
9526 name)
9527 (setq name (make-js2-name-node :pos beg
9528 :name s
9529 :len (length s)))
9530 (if check-activation-p
9531 (js2-check-activation-name s (or token js2-NAME)))
9532 name))
9533
9534 ;;; Indentation support
9535
9536 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9537 ;; Karl cleverly deduces that the desired indentation level is often a
9538 ;; function of paren/bracket/brace nesting depth, which can be determined
9539 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9540 ;; then does some equally clever checks to see if we're in the context of a
9541 ;; substatement of a possibly braceless statement keyword such as if, while,
9542 ;; or finally. This approach yields pretty good results.
9543
9544 ;; The indenter is often "wrong", however, and needs to be overridden.
9545 ;; The right long-term solution is probably to emulate (or integrate
9546 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9547 ;; parse tree from `js2-parse' is present, which is not true at the
9548 ;; moment the user is typing, computing indentation is still thousands
9549 ;; of lines of code to handle every possible syntactic edge case.
9550
9551 ;; In the meantime, the compromise solution is that we offer a "bounce
9552 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9553 ;; current line indent among various likely guess points. This approach
9554 ;; is far from perfect, but should at least make it slightly easier to
9555 ;; move the line towards its desired indentation when manually
9556 ;; overriding Karl's heuristic nesting guesser.
9557
9558 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9559 ;; extensions such as `let' and Array comprehensions. Major kudos to
9560 ;; Karl for coming up with the initial approach, which packs a lot of
9561 ;; punch for so little code.
9562
9563 (defconst js2-possibly-braceless-keywords-re
9564 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9565 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9566 "try" "while" "with" "let")))
9567 "Regular expression matching keywords that are optionally
9568 followed by an opening brace.")
9569
9570 (defconst js2-indent-operator-re
9571 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9572 (regexp-opt '("in" "instanceof") 'words))
9573 "Regular expression matching operators that affect indentation
9574 of continued expressions.")
9575
9576 (defconst js2-declaration-keyword-re
9577 (regexp-opt '("var" "let" "const") 'words)
9578 "Regular expression matching variable declaration keywords.")
9579
9580 (defun js2-re-search-forward-inner (regexp &optional bound count)
9581 "Auxiliary function for `js2-re-search-forward'."
9582 (let (parse saved-point)
9583 (while (> count 0)
9584 (re-search-forward regexp bound)
9585 (setq parse (if saved-point
9586 (parse-partial-sexp saved-point (point))
9587 (syntax-ppss (point))))
9588 (cond ((nth 3 parse)
9589 (re-search-forward
9590 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9591 (save-excursion (end-of-line) (point)) t))
9592 ((nth 7 parse)
9593 (forward-line))
9594 ((or (nth 4 parse)
9595 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9596 (re-search-forward "\\*/"))
9597 (t
9598 (setq count (1- count))))
9599 (setq saved-point (point))))
9600 (point))
9601
9602 (defun js2-re-search-forward (regexp &optional bound noerror count)
9603 "Search forward but ignore strings and comments.
9604 Invokes `re-search-forward' but treats the buffer as if strings
9605 and comments have been removed."
9606 (let ((saved-point (point)))
9607 (condition-case err
9608 (cond ((null count)
9609 (js2-re-search-forward-inner regexp bound 1))
9610 ((< count 0)
9611 (js2-re-search-backward-inner regexp bound (- count)))
9612 ((> count 0)
9613 (js2-re-search-forward-inner regexp bound count)))
9614 (search-failed
9615 (goto-char saved-point)
9616 (unless noerror
9617 (error (error-message-string err)))))))
9618
9619 (defun js2-re-search-backward-inner (regexp &optional bound count)
9620 "Auxiliary function for `js2-re-search-backward'."
9621 (let (parse)
9622 (while (> count 0)
9623 (re-search-backward regexp bound)
9624 (setq parse (syntax-ppss (point)))
9625 (cond ((nth 3 parse)
9626 (re-search-backward
9627 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9628 (line-beginning-position) t))
9629 ((nth 7 parse)
9630 (goto-char (nth 8 parse)))
9631 ((or (nth 4 parse)
9632 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9633 (re-search-backward "/\\*"))
9634 (t
9635 (setq count (1- count))))))
9636 (point))
9637
9638 (defun js2-re-search-backward (regexp &optional bound noerror count)
9639 "Search backward but ignore strings and comments.
9640 Invokes `re-search-backward' but treats the buffer as if strings
9641 and comments have been removed."
9642 (let ((saved-point (point)))
9643 (condition-case err
9644 (cond ((null count)
9645 (js2-re-search-backward-inner regexp bound 1))
9646 ((< count 0)
9647 (js2-re-search-forward-inner regexp bound (- count)))
9648 ((> count 0)
9649 (js2-re-search-backward-inner regexp bound count)))
9650 (search-failed
9651 (goto-char saved-point)
9652 (unless noerror
9653 (error (error-message-string err)))))))
9654
9655 (defun js2-looking-at-operator-p ()
9656 "Return non-nil if text after point is a non-comma operator."
9657 (and (looking-at js2-indent-operator-re)
9658 (or (not (looking-at ":"))
9659 (save-excursion
9660 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9661 (looking-at "?"))))))
9662
9663 (defun js2-continued-expression-p ()
9664 "Return non-nil if the current line continues an expression."
9665 (save-excursion
9666 (back-to-indentation)
9667 (or (js2-looking-at-operator-p)
9668 (when (catch 'found
9669 (while (and (re-search-backward "\n" nil t)
9670 (let ((state (syntax-ppss)))
9671 (when (nth 4 state)
9672 (goto-char (nth 8 state))) ;; skip comments
9673 (skip-chars-backward " \t")
9674 (if (bolp)
9675 t
9676 (throw 'found t))))))
9677 (backward-char)
9678 (when (js2-looking-at-operator-p)
9679 (backward-char)
9680 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9681
9682 (defun js2-end-of-do-while-loop-p ()
9683 "Return non-nil if word after point is `while' of a do-while
9684 statement, else returns nil. A braceless do-while statement
9685 spanning several lines requires that the start of the loop is
9686 indented to the same column as the current line."
9687 (interactive)
9688 (save-excursion
9689 (when (looking-at "\\s-*\\<while\\>")
9690 (if (save-excursion
9691 (skip-chars-backward "[ \t\n]*}")
9692 (looking-at "[ \t\n]*}"))
9693 (save-excursion
9694 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9695 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9696 (or (looking-at "\\<do\\>")
9697 (let ((saved-indent (current-indentation)))
9698 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9699 (/= (current-indentation) saved-indent)))
9700 (and (looking-at "[ \t]*\\<do\\>")
9701 (not (js2-re-search-forward
9702 "\\<while\\>" (point-at-eol) t))
9703 (= (current-indentation) saved-indent))))))))
9704
9705 (defun js2-multiline-decl-indentation ()
9706 "Return the declaration indentation column if the current line belongs
9707 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9708 (let (forward-sexp-function ; use Lisp version
9709 at-opening-bracket)
9710 (save-excursion
9711 (back-to-indentation)
9712 (when (not (looking-at js2-declaration-keyword-re))
9713 (when (looking-at js2-indent-operator-re)
9714 (goto-char (match-end 0))) ; continued expressions are ok
9715 (while (and (not at-opening-bracket)
9716 (not (bobp))
9717 (let ((pos (point)))
9718 (save-excursion
9719 (js2-backward-sws)
9720 (or (eq (char-before) ?,)
9721 (and (not (eq (char-before) ?\;))
9722 (prog2 (skip-syntax-backward ".")
9723 (looking-at js2-indent-operator-re)
9724 (js2-backward-sws))
9725 (not (eq (char-before) ?\;)))
9726 (js2-same-line pos)))))
9727 (condition-case _
9728 (backward-sexp)
9729 (scan-error (setq at-opening-bracket t))))
9730 (when (looking-at js2-declaration-keyword-re)
9731 (goto-char (match-end 0))
9732 (1+ (current-column)))))))
9733
9734 (defun js2-ctrl-statement-indentation ()
9735 "Return the proper indentation of current line if it is a control statement.
9736 Returns an indentation if this line starts the body of a control
9737 statement without braces, else returns nil."
9738 (let (forward-sexp-function)
9739 (save-excursion
9740 (back-to-indentation)
9741 (when (and (not (js2-same-line (point-min)))
9742 (not (looking-at "{"))
9743 (js2-re-search-backward "[[:graph:]]" nil t)
9744 (not (looking-at "[{([]"))
9745 (progn
9746 (forward-char)
9747 (when (= (char-before) ?\))
9748 ;; scan-sexps sometimes throws an error
9749 (ignore-errors (backward-sexp))
9750 (skip-chars-backward " \t" (point-at-bol)))
9751 (let ((pt (point)))
9752 (back-to-indentation)
9753 (when (looking-at "}[ \t]*")
9754 (goto-char (match-end 0)))
9755 (and (looking-at js2-possibly-braceless-keywords-re)
9756 (= (match-end 0) pt)
9757 (not (js2-end-of-do-while-loop-p))))))
9758 (+ (current-indentation) js2-basic-offset)))))
9759
9760 (defun js2-indent-in-array-comp (parse-status)
9761 "Return non-nil if we think we're in an array comprehension.
9762 In particular, return the buffer position of the first `for' kwd."
9763 (let ((bracket (nth 1 parse-status))
9764 (end (point)))
9765 (when bracket
9766 (save-excursion
9767 (goto-char bracket)
9768 (when (looking-at "\\[")
9769 (forward-char 1)
9770 (js2-forward-sws)
9771 (if (looking-at "[[{]")
9772 (let (forward-sexp-function) ; use Lisp version
9773 (forward-sexp) ; skip destructuring form
9774 (js2-forward-sws)
9775 (if (and (/= (char-after) ?,) ; regular array
9776 (looking-at "for"))
9777 (match-beginning 0)))
9778 ;; to skip arbitrary expressions we need the parser,
9779 ;; so we'll just guess at it.
9780 (if (and (> end (point)) ; not empty literal
9781 (re-search-forward "[^,]]* \\(for\\) " end t)
9782 ;; not inside comment or string literal
9783 (let ((state (parse-partial-sexp bracket (point))))
9784 (not (or (nth 3 state) (nth 4 state)))))
9785 (match-beginning 1))))))))
9786
9787 (defun js2-array-comp-indentation (parse-status for-kwd)
9788 (if (js2-same-line for-kwd)
9789 ;; first continuation line
9790 (save-excursion
9791 (goto-char (nth 1 parse-status))
9792 (forward-char 1)
9793 (skip-chars-forward " \t")
9794 (current-column))
9795 (save-excursion
9796 (goto-char for-kwd)
9797 (current-column))))
9798
9799 (defun js2-proper-indentation (parse-status)
9800 "Return the proper indentation for the current line."
9801 (save-excursion
9802 (back-to-indentation)
9803 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9804 (at-closing-bracket (looking-at "[]})]"))
9805 (same-indent-p (or at-closing-bracket
9806 (looking-at "\\<case\\>\\|\\<default\\>")))
9807 (continued-expr-p (js2-continued-expression-p))
9808 (declaration-indent (and js2-pretty-multiline-declarations
9809 (js2-multiline-decl-indentation)))
9810 (bracket (nth 1 parse-status))
9811 beg indent)
9812 (cond
9813 ;; indent array comprehension continuation lines specially
9814 ((and bracket
9815 (>= js2-language-version 170)
9816 (not (js2-same-line bracket))
9817 (setq beg (js2-indent-in-array-comp parse-status))
9818 (>= (point) (save-excursion
9819 (goto-char beg)
9820 (point-at-bol)))) ; at or after first loop?
9821 (js2-array-comp-indentation parse-status beg))
9822
9823 (ctrl-stmt-indent)
9824
9825 ((and declaration-indent continued-expr-p)
9826 (+ declaration-indent js2-basic-offset))
9827
9828 (declaration-indent)
9829
9830 (bracket
9831 (goto-char bracket)
9832 (cond
9833 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9834 (when (save-excursion (skip-chars-backward " \t)")
9835 (looking-at ")"))
9836 (backward-list))
9837 (back-to-indentation)
9838 (and (eq js2-pretty-multiline-declarations 'all)
9839 (looking-at js2-declaration-keyword-re)
9840 (goto-char (1+ (match-end 0))))
9841 (setq indent
9842 (cond (same-indent-p
9843 (current-column))
9844 (continued-expr-p
9845 (+ (current-column) (* 2 js2-basic-offset)))
9846 (t
9847 (+ (current-column) js2-basic-offset))))
9848 (if (and js2-indent-switch-body
9849 (not at-closing-bracket)
9850 (looking-at "\\_<switch\\_>"))
9851 (+ indent js2-basic-offset)
9852 indent))
9853 (t
9854 (unless same-indent-p
9855 (forward-char)
9856 (skip-chars-forward " \t"))
9857 (current-column))))
9858
9859 (continued-expr-p js2-basic-offset)
9860
9861 (t 0)))))
9862
9863 (defun js2-lineup-comment (parse-status)
9864 "Indent a multi-line block comment continuation line."
9865 (let* ((beg (nth 8 parse-status))
9866 (first-line (js2-same-line beg))
9867 (offset (save-excursion
9868 (goto-char beg)
9869 (if (looking-at "/\\*")
9870 (+ 1 (current-column))
9871 0))))
9872 (unless first-line
9873 (indent-line-to offset))))
9874
9875 (defun js2-backward-sws ()
9876 "Move backward through whitespace and comments."
9877 (interactive)
9878 (while (forward-comment -1)))
9879
9880 (defun js2-forward-sws ()
9881 "Move forward through whitespace and comments."
9882 (interactive)
9883 (while (forward-comment 1)))
9884
9885 (defun js2-current-indent (&optional pos)
9886 "Return column of indentation on current line.
9887 If POS is non-nil, go to that point and return indentation for that line."
9888 (save-excursion
9889 (if pos
9890 (goto-char pos))
9891 (back-to-indentation)
9892 (current-column)))
9893
9894 (defun js2-arglist-close ()
9895 "Return non-nil if we're on a line beginning with a close-paren/brace."
9896 (save-excursion
9897 (goto-char (point-at-bol))
9898 (js2-forward-sws)
9899 (looking-at "[])}]")))
9900
9901 (defun js2-indent-looks-like-label-p ()
9902 (goto-char (point-at-bol))
9903 (js2-forward-sws)
9904 (looking-at (concat js2-mode-identifier-re ":")))
9905
9906 (defun js2-indent-in-objlit-p (parse-status)
9907 "Return non-nil if this looks like an object-literal entry."
9908 (let ((start (nth 1 parse-status)))
9909 (and
9910 start
9911 (save-excursion
9912 (and (zerop (forward-line -1))
9913 (not (< (point) start)) ; crossed a {} boundary
9914 (js2-indent-looks-like-label-p)))
9915 (save-excursion
9916 (js2-indent-looks-like-label-p)))))
9917
9918 ;; If prev line looks like foobar({ then we're passing an object
9919 ;; literal to a function call, and people pretty much always want to
9920 ;; de-dent back to the previous line, so move the 'basic-offset'
9921 ;; position to the front.
9922 (defun js2-indent-objlit-arg-p (parse-status)
9923 (save-excursion
9924 (back-to-indentation)
9925 (js2-backward-sws)
9926 (and (eq (1- (point)) (nth 1 parse-status))
9927 (eq (char-before) ?{)
9928 (progn
9929 (forward-char -1)
9930 (skip-chars-backward " \t")
9931 (eq (char-before) ?\()))))
9932
9933 (defun js2-indent-case-block-p ()
9934 (save-excursion
9935 (back-to-indentation)
9936 (js2-backward-sws)
9937 (goto-char (point-at-bol))
9938 (skip-chars-forward " \t")
9939 (looking-at "case\\s-.+:")))
9940
9941 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9942 "Cycle among alternate computed indentation positions.
9943 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9944 of the buffer to the current point. NORMAL-COL is the indentation
9945 column computed by the heuristic guesser based on current paren,
9946 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9947 in reverse."
9948 (let ((cur-indent (js2-current-indent))
9949 (old-buffer-undo-list buffer-undo-list)
9950 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9951 (current-line (save-excursion
9952 (forward-line 0) ; move to bol
9953 (1+ (count-lines (point-min) (point)))))
9954 positions pos main-pos anchor arglist-cont same-indent
9955 basic-offset computed-pos)
9956 ;; temporarily don't record undo info, if user requested this
9957 (when js2-mode-indent-inhibit-undo
9958 (setq buffer-undo-list t))
9959 (unwind-protect
9960 (progn
9961 ;; First likely point: indent from beginning of previous code line
9962 (push (setq basic-offset
9963 (+ (save-excursion
9964 (back-to-indentation)
9965 (js2-backward-sws)
9966 (back-to-indentation)
9967 (current-column))
9968 js2-basic-offset))
9969 positions)
9970
9971 ;; (First + epsilon) likely point: indent 2x from beginning of
9972 ;; previous code line. Google does it this way.
9973 (push (setq basic-offset
9974 (+ (save-excursion
9975 (back-to-indentation)
9976 (js2-backward-sws)
9977 (back-to-indentation)
9978 (current-column))
9979 (* 2 js2-basic-offset)))
9980 positions)
9981
9982 ;; Second likely point: indent from assign-expr RHS. This
9983 ;; is just a crude guess based on finding " = " on the previous
9984 ;; line containing actual code.
9985 (setq pos (save-excursion
9986 (forward-line -1)
9987 (goto-char (point-at-bol))
9988 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9989 (point-at-eol) t)
9990 (goto-char (match-end 1))
9991 (skip-chars-forward " \t\r\n")
9992 (current-column))))
9993 (when pos
9994 (incf pos js2-basic-offset)
9995 (push pos positions))
9996
9997 ;; Third likely point: same indent as previous line of code.
9998 ;; Make it the first likely point if we're not on an
9999 ;; arglist-close line and previous line ends in a comma, or
10000 ;; both this line and prev line look like object-literal
10001 ;; elements.
10002 (setq pos (save-excursion
10003 (goto-char (point-at-bol))
10004 (js2-backward-sws)
10005 (back-to-indentation)
10006 (prog1
10007 (current-column)
10008 ;; while we're here, look for trailing comma
10009 (if (save-excursion
10010 (goto-char (point-at-eol))
10011 (js2-backward-sws)
10012 (eq (char-before) ?,))
10013 (setq arglist-cont (1- (point)))))))
10014 (when pos
10015 (if (and (or arglist-cont
10016 (js2-indent-in-objlit-p parse-status))
10017 (not (js2-arglist-close)))
10018 (setq same-indent pos))
10019 (push pos positions))
10020
10021 ;; Fourth likely point: first preceding code with less indentation.
10022 ;; than the immediately preceding code line.
10023 (setq pos (save-excursion
10024 (back-to-indentation)
10025 (js2-backward-sws)
10026 (back-to-indentation)
10027 (setq anchor (current-column))
10028 (while (and (zerop (forward-line -1))
10029 (>= (progn
10030 (back-to-indentation)
10031 (current-column))
10032 anchor)))
10033 (setq pos (current-column))))
10034 (push pos positions)
10035
10036 ;; nesting-heuristic position, main by default
10037 (push (setq main-pos normal-col) positions)
10038
10039 ;; delete duplicates and sort positions list
10040 (setq positions (sort (delete-dups positions) '<))
10041
10042 ;; comma-list continuation lines: prev line indent takes precedence
10043 (if same-indent
10044 (setq main-pos same-indent))
10045
10046 ;; common special cases where we want to indent in from previous line
10047 (if (or (js2-indent-case-block-p)
10048 (js2-indent-objlit-arg-p parse-status))
10049 (setq main-pos basic-offset))
10050
10051 ;; if bouncing backwards, reverse positions list
10052 (if backwards
10053 (setq positions (reverse positions)))
10054
10055 ;; record whether we're already sitting on one of the alternatives
10056 (setq pos (member cur-indent positions))
10057
10058 (cond
10059 ;; case 0: we're one one of the alternatives and this is the
10060 ;; first time they've pressed TAB on this line (best-guess).
10061 ((and js2-mode-indent-ignore-first-tab
10062 pos
10063 ;; first time pressing TAB on this line?
10064 (not (eq js2-mode-last-indented-line current-line)))
10065 ;; do nothing
10066 (setq computed-pos nil))
10067 ;; case 1: only one computed position => use it
10068 ((null (cdr positions))
10069 (setq computed-pos 0))
10070 ;; case 2: not on any of the computed spots => use main spot
10071 ((not pos)
10072 (setq computed-pos (js2-position main-pos positions)))
10073 ;; case 3: on last position: cycle to first position
10074 ((null (cdr pos))
10075 (setq computed-pos 0))
10076 ;; case 4: on intermediate position: cycle to next position
10077 (t
10078 (setq computed-pos (js2-position (second pos) positions))))
10079
10080 ;; see if any hooks want to indent; otherwise we do it
10081 (loop with result = nil
10082 for hook in js2-indent-hook
10083 while (null result)
10084 do
10085 (setq result (funcall hook positions computed-pos))
10086 finally do
10087 (unless (or result (null computed-pos))
10088 (indent-line-to (nth computed-pos positions)))))
10089
10090 ;; finally
10091 (if js2-mode-indent-inhibit-undo
10092 (setq buffer-undo-list old-buffer-undo-list))
10093 ;; see commentary for `js2-mode-last-indented-line'
10094 (setq js2-mode-last-indented-line current-line))))
10095
10096 (defun js2-indent-bounce-backwards ()
10097 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10098 cycles between the computed indentation positions in reverse order."
10099 (interactive)
10100 (js2-indent-line t))
10101
10102 (defun js2-1-line-comment-continuation-p ()
10103 "Return t if we're in a 1-line comment continuation.
10104 If so, we don't ever want to use bounce-indent."
10105 (save-excursion
10106 (and (progn
10107 (forward-line 0)
10108 (looking-at "\\s-*//"))
10109 (progn
10110 (forward-line -1)
10111 (forward-line 0)
10112 (when (looking-at "\\s-*$")
10113 (js2-backward-sws)
10114 (forward-line 0))
10115 (looking-at "\\s-*//")))))
10116
10117 (defun js2-indent-line (&optional bounce-backwards)
10118 "Indent the current line as JavaScript source text."
10119 (interactive)
10120 (let (parse-status offset indent-col
10121 ;; Don't whine about errors/warnings when we're indenting.
10122 ;; This has to be set before calling parse-partial-sexp below.
10123 (inhibit-point-motion-hooks t))
10124 (setq parse-status (save-excursion
10125 (syntax-ppss (point-at-bol)))
10126 offset (- (point) (save-excursion
10127 (back-to-indentation)
10128 (point))))
10129 (js2-with-underscore-as-word-syntax
10130 (if (nth 4 parse-status)
10131 (js2-lineup-comment parse-status)
10132 (setq indent-col (js2-proper-indentation parse-status))
10133 ;; See comments below about `js2-mode-last-indented-line'.
10134 (cond
10135 ;; bounce-indenting is disabled during electric-key indent.
10136 ;; It doesn't work well on first line of buffer.
10137 ((and js2-bounce-indent-p
10138 (not (js2-same-line (point-min)))
10139 (not (js2-1-line-comment-continuation-p)))
10140 (js2-bounce-indent indent-col parse-status bounce-backwards))
10141 ;; just indent to the guesser's likely spot
10142 (t (indent-line-to indent-col))))
10143 (when (plusp offset)
10144 (forward-char offset)))))
10145
10146 (defun js2-indent-region (start end)
10147 "Indent the region, but don't use bounce indenting."
10148 (let ((js2-bounce-indent-p nil)
10149 (indent-region-function nil)
10150 (after-change-functions (remq 'js2-mode-edit
10151 after-change-functions)))
10152 (indent-region start end nil) ; nil for byte-compiler
10153 (js2-mode-edit start end (- end start))))
10154
10155 (defvar js2-minor-mode-map
10156 (let ((map (make-sparse-keymap)))
10157 (define-key map (kbd "C-c C-`") #'js2-next-error)
10158 (define-key map [mouse-1] #'js2-mode-show-node)
10159 map)
10160 "Keymap used when `js2-minor-mode' is active.")
10161
10162 ;;;###autoload
10163 (define-minor-mode js2-minor-mode
10164 "Minor mode for running js2 as a background linter.
10165 This allows you to use a different major mode for JavaScript editing,
10166 such as `espresso-mode', while retaining the asynchronous error/warning
10167 highlighting features of `js2-mode'."
10168 :group 'js2-mode
10169 :lighter " js-lint"
10170 (if js2-minor-mode
10171 (js2-minor-mode-enter)
10172 (js2-minor-mode-exit)))
10173
10174 (defun js2-minor-mode-enter ()
10175 "Initialization for `js2-minor-mode'."
10176 (set (make-local-variable 'max-lisp-eval-depth)
10177 (max max-lisp-eval-depth 3000))
10178 (setq next-error-function #'js2-next-error)
10179 (js2-set-default-externs)
10180 ;; Experiment: make reparse-delay longer for longer files.
10181 (if (plusp js2-dynamic-idle-timer-adjust)
10182 (setq js2-idle-timer-delay
10183 (* js2-idle-timer-delay
10184 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10185 (setq js2-mode-buffer-dirty-p t
10186 js2-mode-parsing nil)
10187 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10188 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10189 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10190 (when js2-include-jslint-globals
10191 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10192 (run-hooks 'js2-init-hook)
10193 (js2-reparse))
10194
10195 (defun js2-minor-mode-exit ()
10196 "Turn off `js2-minor-mode'."
10197 (setq next-error-function nil)
10198 (remove-hook 'after-change-functions #'js2-mode-edit t)
10199 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10200 (when js2-mode-node-overlay
10201 (delete-overlay js2-mode-node-overlay)
10202 (setq js2-mode-node-overlay nil))
10203 (js2-remove-overlays)
10204 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10205 (setq js2-mode-ast nil))
10206
10207 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10208 (make-variable-buffer-local 'js2-source-buffer)
10209
10210 (defun* js2-display-error-list ()
10211 "Display a navigable buffer listing parse errors/warnings."
10212 (interactive)
10213 (unless (js2-have-errors-p)
10214 (message "No errors")
10215 (return-from js2-display-error-list))
10216 (labels ((annotate-list
10217 (lst type)
10218 "Add diagnostic TYPE and line number to errs list"
10219 (mapcar (lambda (err)
10220 (list err type (line-number-at-pos (nth 1 err))))
10221 lst)))
10222 (let* ((srcbuf (current-buffer))
10223 (errbuf (get-buffer-create "*js-lint*"))
10224 (errors (annotate-list
10225 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10226 'js2-error)) ; must be a valid face name
10227 (warnings (annotate-list
10228 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10229 'js2-warning)) ; must be a valid face name
10230 (all-errs (sort (append errors warnings)
10231 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10232 (with-current-buffer errbuf
10233 (let ((inhibit-read-only t))
10234 (erase-buffer)
10235 (dolist (err all-errs)
10236 (destructuring-bind ((msg-key beg _end &rest) type line) err
10237 (insert-text-button
10238 (format "line %d: %s" line (js2-get-msg msg-key))
10239 'face type
10240 'follow-link "\C-m"
10241 'action 'js2-error-buffer-jump
10242 'js2-msg (js2-get-msg msg-key)
10243 'js2-pos beg)
10244 (insert "\n"))))
10245 (js2-error-buffer-mode)
10246 (setq js2-source-buffer srcbuf)
10247 (pop-to-buffer errbuf)
10248 (goto-char (point-min))
10249 (unless (eobp)
10250 (js2-error-buffer-view))))))
10251
10252 (defvar js2-error-buffer-mode-map
10253 (let ((map (make-sparse-keymap)))
10254 (define-key map "n" #'js2-error-buffer-next)
10255 (define-key map "p" #'js2-error-buffer-prev)
10256 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10257 (define-key map "o" #'js2-error-buffer-view)
10258 (define-key map "q" #'js2-error-buffer-quit)
10259 map)
10260 "Keymap used for js2 diagnostics buffers.")
10261
10262 (defun js2-error-buffer-mode ()
10263 "Major mode for js2 diagnostics buffers.
10264 Selecting an error will jump it to the corresponding source-buffer error.
10265 \\{js2-error-buffer-mode-map}"
10266 (interactive)
10267 (setq major-mode 'js2-error-buffer-mode
10268 mode-name "JS Lint Diagnostics")
10269 (use-local-map js2-error-buffer-mode-map)
10270 (setq truncate-lines t)
10271 (set-buffer-modified-p nil)
10272 (setq buffer-read-only t)
10273 (run-hooks 'js2-error-buffer-mode-hook))
10274
10275 (defun js2-error-buffer-next ()
10276 "Move to next error and view it."
10277 (interactive)
10278 (when (zerop (forward-line 1))
10279 (js2-error-buffer-view)))
10280
10281 (defun js2-error-buffer-prev ()
10282 "Move to previous error and view it."
10283 (interactive)
10284 (when (zerop (forward-line -1))
10285 (js2-error-buffer-view)))
10286
10287 (defun js2-error-buffer-quit ()
10288 "Kill the current buffer."
10289 (interactive)
10290 (kill-buffer))
10291
10292 (defun js2-error-buffer-jump (&rest ignored)
10293 "Jump cursor to current error in source buffer."
10294 (interactive)
10295 (when (js2-error-buffer-view)
10296 (pop-to-buffer js2-source-buffer)))
10297
10298 (defun js2-error-buffer-view ()
10299 "Scroll source buffer to show error at current line."
10300 (interactive)
10301 (cond
10302 ((not (eq major-mode 'js2-error-buffer-mode))
10303 (message "Not in a js2 errors buffer"))
10304 ((not (buffer-live-p js2-source-buffer))
10305 (message "Source buffer has been killed"))
10306 ((not (wholenump (get-text-property (point) 'js2-pos)))
10307 (message "There does not seem to be an error here"))
10308 (t
10309 (let ((pos (get-text-property (point) 'js2-pos))
10310 (msg (get-text-property (point) 'js2-msg)))
10311 (save-selected-window
10312 (pop-to-buffer js2-source-buffer)
10313 (goto-char pos)
10314 (message msg))))))
10315
10316 ;;;###autoload
10317 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10318 ;; FIXME: Should derive from js-mode.
10319 "Major mode for editing JavaScript code."
10320 ;; Used by comment-region; don't change it.
10321 (set (make-local-variable 'comment-start) "//")
10322 (set (make-local-variable 'comment-end) "")
10323 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10324 (set (make-local-variable 'max-lisp-eval-depth)
10325 (max max-lisp-eval-depth 3000))
10326 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10327 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10328 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10329 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10330 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10331 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10332 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10333 ;; for characters inside regexp literals.
10334 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10335 ;; this is necessary to make `show-paren-function' work properly
10336 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10337 ;; needed for M-x rgrep, among other things
10338 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10339
10340 (set (make-local-variable 'electric-indent-chars)
10341 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10342 electric-indent-chars))
10343 (set (make-local-variable 'electric-layout-rules)
10344 '((?\; . after) (?\{ . after) (?\} . before)))
10345
10346 ;; some variables needed by cc-engine for paragraph-fill, etc.
10347 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10348 c-comment-start-regexp "/[*/]\\|\\s|"
10349 c-line-comment-starter "//"
10350 c-paragraph-start js2-paragraph-start
10351 c-paragraph-separate "$"
10352 c-syntactic-ws-start js2-syntactic-ws-start
10353 c-syntactic-ws-end js2-syntactic-ws-end
10354 c-syntactic-eol js2-syntactic-eol)
10355
10356 (let ((c-buffer-is-cc-mode t))
10357 ;; Copied from `js-mode'. Also see Bug#6071.
10358 (make-local-variable 'paragraph-start)
10359 (make-local-variable 'paragraph-separate)
10360 (make-local-variable 'paragraph-ignore-fill-prefix)
10361 (make-local-variable 'adaptive-fill-mode)
10362 (make-local-variable 'adaptive-fill-regexp)
10363 (c-setup-paragraph-variables))
10364
10365 (setq font-lock-defaults '(nil t))
10366
10367 ;; Experiment: make reparse-delay longer for longer files.
10368 (when (plusp js2-dynamic-idle-timer-adjust)
10369 (setq js2-idle-timer-delay
10370 (* js2-idle-timer-delay
10371 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10372
10373 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10374 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10375 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10376 (setq next-error-function #'js2-next-error)
10377 (imenu-add-to-menubar (concat "IM-" mode-name))
10378 (add-to-invisibility-spec '(js2-outline . t))
10379 (set (make-local-variable 'line-move-ignore-invisible) t)
10380 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10381
10382 (setq js2-mode-functions-hidden nil
10383 js2-mode-comments-hidden nil
10384 js2-mode-buffer-dirty-p t
10385 js2-mode-parsing nil)
10386
10387 (js2-set-default-externs)
10388
10389 (when js2-include-jslint-globals
10390 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10391
10392 (run-hooks 'js2-init-hook)
10393
10394 (js2-reparse))
10395
10396 (defun js2-mode-exit ()
10397 "Exit `js2-mode' and clean up."
10398 (interactive)
10399 (when js2-mode-node-overlay
10400 (delete-overlay js2-mode-node-overlay)
10401 (setq js2-mode-node-overlay nil))
10402 (js2-remove-overlays)
10403 (setq js2-mode-ast nil)
10404 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10405 (remove-from-invisibility-spec '(js2-outline . t))
10406 (js2-mode-show-all)
10407 (with-silent-modifications
10408 (js2-clear-face (point-min) (point-max))))
10409
10410 (defun js2-mode-reset-timer ()
10411 "Cancel any existing parse timer and schedule a new one."
10412 (if js2-mode-parse-timer
10413 (cancel-timer js2-mode-parse-timer))
10414 (setq js2-mode-parsing nil)
10415 (let ((timer (timer-create)))
10416 (setq js2-mode-parse-timer timer)
10417 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10418 (timer-set-idle-time timer js2-idle-timer-delay)
10419 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10420 (timer-activate-when-idle timer nil)))
10421
10422 (defun js2-mode-idle-reparse (buffer)
10423 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10424 it to be reparsed when the buffer is selected."
10425 (if (eq buffer (current-buffer))
10426 (js2-reparse)
10427 ;; reparse when the buffer is selected again
10428 (with-current-buffer buffer
10429 (add-hook 'window-configuration-change-hook
10430 #'js2-mode-idle-reparse-inner
10431 nil t))))
10432
10433 (defun js2-mode-idle-reparse-inner ()
10434 (remove-hook 'window-configuration-change-hook
10435 #'js2-mode-idle-reparse-inner
10436 t)
10437 (js2-reparse))
10438
10439 (defun js2-mode-edit (_beg _end _len)
10440 "Schedule a new parse after buffer is edited.
10441 Buffer edit spans from BEG to END and is of length LEN."
10442 (setq js2-mode-buffer-dirty-p t)
10443 (js2-mode-hide-overlay)
10444 (js2-mode-reset-timer))
10445
10446 (defun js2-minor-mode-edit (_beg _end _len)
10447 "Callback for buffer edits in `js2-mode'.
10448 Schedules a new parse after buffer is edited.
10449 Buffer edit spans from BEG to END and is of length LEN."
10450 (setq js2-mode-buffer-dirty-p t)
10451 (js2-mode-hide-overlay)
10452 (js2-mode-reset-timer))
10453
10454 (defun js2-reparse (&optional force)
10455 "Re-parse current buffer after user finishes some data entry.
10456 If we get any user input while parsing, including cursor motion,
10457 we discard the parse and reschedule it. If FORCE is nil, then the
10458 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10459 (let (time
10460 interrupted-p
10461 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10462 (unless js2-mode-parsing
10463 (setq js2-mode-parsing t)
10464 (unwind-protect
10465 (when (or js2-mode-buffer-dirty-p force)
10466 (js2-remove-overlays)
10467 (with-silent-modifications
10468 (setq js2-mode-buffer-dirty-p nil
10469 js2-mode-fontifications nil
10470 js2-mode-deferred-properties nil)
10471 (if js2-mode-verbose-parse-p
10472 (message "parsing..."))
10473 (setq time
10474 (js2-time
10475 (setq interrupted-p
10476 (catch 'interrupted
10477 (js2-parse)
10478 ;; if parsing is interrupted, comments and regex
10479 ;; literals stay ignored by `parse-partial-sexp'
10480 (remove-text-properties (point-min) (point-max)
10481 '(syntax-table))
10482 (js2-mode-apply-deferred-properties)
10483 (js2-mode-remove-suppressed-warnings)
10484 (js2-mode-show-warnings)
10485 (js2-mode-show-errors)
10486 (if (>= js2-highlight-level 1)
10487 (js2-highlight-jsdoc js2-mode-ast))
10488 nil))))
10489 (if interrupted-p
10490 (progn
10491 ;; unfinished parse => try again
10492 (setq js2-mode-buffer-dirty-p t)
10493 (js2-mode-reset-timer))
10494 (if js2-mode-verbose-parse-p
10495 (message "Parse time: %s" time)))))
10496 (setq js2-mode-parsing nil)
10497 (unless interrupted-p
10498 (setq js2-mode-parse-timer nil))))))
10499
10500 (defun js2-mode-show-node (event)
10501 "Debugging aid: highlight selected AST node on mouse click."
10502 (interactive "e")
10503 (mouse-set-point event)
10504 (setq deactivate-mark t)
10505 (when js2-mode-show-overlay
10506 (let ((node (js2-node-at-point))
10507 beg end)
10508 (if (null node)
10509 (message "No node found at location %s" (point))
10510 (setq beg (js2-node-abs-pos node)
10511 end (+ beg (js2-node-len node)))
10512 (if js2-mode-node-overlay
10513 (move-overlay js2-mode-node-overlay beg end)
10514 (setq js2-mode-node-overlay (make-overlay beg end))
10515 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10516 (with-silent-modifications
10517 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10518 (message "%s, parent: %s"
10519 (js2-node-short-name node)
10520 (if (js2-node-parent node)
10521 (js2-node-short-name (js2-node-parent node))
10522 "nil"))))))
10523
10524 (defun js2-mode-hide-overlay (&optional _p1 p2)
10525 "Remove the debugging overlay when the point moves.
10526 P1 and P2 are the old and new values of point, respectively."
10527 (when js2-mode-node-overlay
10528 (let ((beg (overlay-start js2-mode-node-overlay))
10529 (end (overlay-end js2-mode-node-overlay)))
10530 ;; Sometimes we're called spuriously.
10531 (unless (and p2
10532 (>= p2 beg)
10533 (<= p2 end))
10534 (with-silent-modifications
10535 (remove-text-properties beg end '(point-left nil)))
10536 (delete-overlay js2-mode-node-overlay)
10537 (setq js2-mode-node-overlay nil)))))
10538
10539 (defun js2-mode-reset ()
10540 "Debugging helper: reset everything."
10541 (interactive)
10542 (js2-mode-exit)
10543 (js2-mode))
10544
10545 (defun js2-mode-show-warn-or-err (e face)
10546 "Highlight a warning or error E with FACE.
10547 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10548 The last element is optional. When present, use instead of FACE."
10549 (let* ((key (first e))
10550 (beg (second e))
10551 (end (+ beg (third e)))
10552 ;; Don't inadvertently go out of bounds.
10553 (beg (max (point-min) (min beg (point-max))))
10554 (end (max (point-min) (min end (point-max))))
10555 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10556 (ovl (make-overlay beg end)))
10557 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10558 (overlay-put ovl 'js2-error t)
10559 (put-text-property beg end 'help-echo (js2-get-msg key))
10560 (put-text-property beg end 'point-entered #'js2-echo-error)))
10561
10562 (defun js2-remove-overlays ()
10563 "Remove overlays from buffer that have a `js2-error' property."
10564 (let ((beg (point-min))
10565 (end (point-max)))
10566 (save-excursion
10567 (dolist (o (overlays-in beg end))
10568 (when (overlay-get o 'js2-error)
10569 (delete-overlay o))))))
10570
10571 (defun js2-error-at-point (&optional pos)
10572 "Return non-nil if there's an error overlay at POS.
10573 Defaults to point."
10574 (loop with pos = (or pos (point))
10575 for o in (overlays-at pos)
10576 thereis (overlay-get o 'js2-error)))
10577
10578 (defun js2-mode-apply-deferred-properties ()
10579 "Apply fontifications and other text properties recorded during parsing."
10580 (when (plusp js2-highlight-level)
10581 ;; We defer clearing faces as long as possible to eliminate flashing.
10582 (js2-clear-face (point-min) (point-max))
10583 ;; Have to reverse the recorded fontifications list so that errors
10584 ;; and warnings overwrite the normal fontifications.
10585 (dolist (f (nreverse js2-mode-fontifications))
10586 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10587 (setq js2-mode-fontifications nil))
10588 (dolist (p js2-mode-deferred-properties)
10589 (apply #'put-text-property p))
10590 (setq js2-mode-deferred-properties nil))
10591
10592 (defun js2-mode-show-errors ()
10593 "Highlight syntax errors."
10594 (when js2-mode-show-parse-errors
10595 (dolist (e (js2-ast-root-errors js2-mode-ast))
10596 (js2-mode-show-warn-or-err e 'js2-error))))
10597
10598 (defun js2-mode-remove-suppressed-warnings ()
10599 "Take suppressed warnings out of the AST warnings list.
10600 This ensures that the counts and `next-error' are correct."
10601 (setf (js2-ast-root-warnings js2-mode-ast)
10602 (js2-delete-if
10603 (lambda (e)
10604 (let ((key (caar e)))
10605 (or
10606 (and (not js2-strict-trailing-comma-warning)
10607 (string-match "trailing\\.comma" key))
10608 (and (not js2-strict-cond-assign-warning)
10609 (string= key "msg.equal.as.assign"))
10610 (and js2-missing-semi-one-line-override
10611 (string= key "msg.missing.semi")
10612 (let* ((beg (second e))
10613 (node (js2-node-at-point beg))
10614 (fn (js2-mode-find-parent-fn node))
10615 (body (and fn (js2-function-node-body fn)))
10616 (lc (and body (js2-node-abs-pos body)))
10617 (rc (and lc (+ lc (js2-node-len body)))))
10618 (and fn
10619 (or (null body)
10620 (save-excursion
10621 (goto-char beg)
10622 (and (js2-same-line lc)
10623 (js2-same-line rc))))))))))
10624 (js2-ast-root-warnings js2-mode-ast))))
10625
10626 (defun js2-mode-show-warnings ()
10627 "Highlight strict-mode warnings."
10628 (when js2-mode-show-strict-warnings
10629 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10630 (js2-mode-show-warn-or-err e 'js2-warning))))
10631
10632 (defun js2-echo-error (_old-point new-point)
10633 "Called by point-motion hooks."
10634 (let ((msg (get-text-property new-point 'help-echo)))
10635 (when (and (stringp msg)
10636 (not (active-minibuffer-window))
10637 (not (current-message)))
10638 (message msg))))
10639
10640 (defalias 'js2-echo-help #'js2-echo-error)
10641
10642 (defun js2-line-break (&optional _soft)
10643 "Break line at point and indent, continuing comment if within one.
10644 If inside a string, and `js2-concat-multiline-strings' is not
10645 nil, turn it into concatenation."
10646 (interactive)
10647 (let ((parse-status (syntax-ppss)))
10648 (cond
10649 ;; Check if we're inside a string.
10650 ((nth 3 parse-status)
10651 (if js2-concat-multiline-strings
10652 (js2-mode-split-string parse-status)
10653 (insert "\n")))
10654 ;; Check if inside a block comment.
10655 ((nth 4 parse-status)
10656 (js2-mode-extend-comment (nth 8 parse-status)))
10657 (t
10658 (newline-and-indent)))))
10659
10660 (defun js2-mode-split-string (parse-status)
10661 "Turn a newline in mid-string into a string concatenation.
10662 PARSE-STATUS is as documented in `parse-partial-sexp'."
10663 (let* ((quote-char (nth 3 parse-status))
10664 (at-eol (eq js2-concat-multiline-strings 'eol)))
10665 (insert quote-char)
10666 (insert (if at-eol " +\n" "\n"))
10667 (unless at-eol
10668 (insert "+ "))
10669 (js2-indent-line)
10670 (insert quote-char)
10671 (when (eolp)
10672 (insert quote-char)
10673 (backward-char 1))))
10674
10675 (defun js2-mode-extend-comment (start-pos)
10676 "Indent the line and, when inside a comment block, add comment prefix."
10677 (let (star single col first-line needs-close)
10678 (save-excursion
10679 (back-to-indentation)
10680 (when (< (point) start-pos)
10681 (goto-char start-pos))
10682 (cond
10683 ((looking-at "\\*[^/]")
10684 (setq star t
10685 col (current-column)))
10686 ((looking-at "/\\*")
10687 (setq star t
10688 first-line t
10689 col (1+ (current-column))))
10690 ((looking-at "//")
10691 (setq single t
10692 col (current-column)))))
10693 ;; Heuristic for whether we need to close the comment:
10694 ;; if we've got a parse error here, assume it's an unterminated
10695 ;; comment.
10696 (setq needs-close
10697 (or
10698 (eq (get-text-property (1- (point)) 'point-entered)
10699 'js2-echo-error)
10700 ;; The heuristic above doesn't work well when we're
10701 ;; creating a comment and there's another one downstream,
10702 ;; as our parser thinks this one ends at the end of the
10703 ;; next one. (You can have a /* inside a js block comment.)
10704 ;; So just close it if the next non-ws char isn't a *.
10705 (and first-line
10706 (eolp)
10707 (save-excursion
10708 (skip-chars-forward " \t\r\n")
10709 (not (eq (char-after) ?*))))))
10710 (delete-horizontal-space)
10711 (insert "\n")
10712 (cond
10713 (star
10714 (indent-to col)
10715 (insert "* ")
10716 (if (and first-line needs-close)
10717 (save-excursion
10718 (insert "\n")
10719 (indent-to col)
10720 (insert "*/"))))
10721 ((and single
10722 (save-excursion
10723 (and (zerop (forward-line 1))
10724 (looking-at "\\s-*//"))))
10725 (indent-to col)
10726 (insert "// ")))
10727 ;; Don't need to extend the comment after all.
10728 (js2-indent-line)))
10729
10730 (defun js2-beginning-of-line ()
10731 "Toggle point between bol and first non-whitespace char in line.
10732 Also moves past comment delimiters when inside comments."
10733 (interactive)
10734 (let (node)
10735 (cond
10736 ((bolp)
10737 (back-to-indentation))
10738 ((looking-at "//")
10739 (skip-chars-forward "/ \t"))
10740 ((and (eq (char-after) ?*)
10741 (setq node (js2-comment-at-point))
10742 (memq (js2-comment-node-format node) '(jsdoc block))
10743 (save-excursion
10744 (skip-chars-backward " \t")
10745 (bolp)))
10746 (skip-chars-forward "\* \t"))
10747 (t
10748 (goto-char (point-at-bol))))))
10749
10750 (defun js2-end-of-line ()
10751 "Toggle point between eol and last non-whitespace char in line."
10752 (interactive)
10753 (if (eolp)
10754 (skip-chars-backward " \t")
10755 (goto-char (point-at-eol))))
10756
10757 (defun js2-mode-wait-for-parse (callback)
10758 "Invoke CALLBACK when parsing is finished.
10759 If parsing is already finished, calls CALLBACK immediately."
10760 (if (not js2-mode-buffer-dirty-p)
10761 (funcall callback)
10762 (push callback js2-mode-pending-parse-callbacks)
10763 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10764
10765 (defun js2-mode-parse-finished ()
10766 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10767 ;; We can't let errors propagate up, since it prevents the
10768 ;; `js2-parse' method from completing normally and returning
10769 ;; the ast, which makes things mysteriously not work right.
10770 (unwind-protect
10771 (dolist (cb js2-mode-pending-parse-callbacks)
10772 (condition-case err
10773 (funcall cb)
10774 (error (message "%s" err))))
10775 (setq js2-mode-pending-parse-callbacks nil)))
10776
10777 (defun js2-mode-flag-region (from to flag)
10778 "Hide or show text from FROM to TO, according to FLAG.
10779 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10780 Returns the created overlay if FLAG is non-nil."
10781 (remove-overlays from to 'invisible 'js2-outline)
10782 (when flag
10783 (let ((o (make-overlay from to)))
10784 (overlay-put o 'invisible 'js2-outline)
10785 (overlay-put o 'isearch-open-invisible
10786 'js2-isearch-open-invisible)
10787 o)))
10788
10789 ;; Function to be set as an outline-isearch-open-invisible' property
10790 ;; to the overlay that makes the outline invisible (see
10791 ;; `js2-mode-flag-region').
10792 (defun js2-isearch-open-invisible (_overlay)
10793 ;; We rely on the fact that isearch places point on the matched text.
10794 (js2-mode-show-element))
10795
10796 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10797 "Return cons cell of bounds of folding overlay at POS.
10798 Returns nil if not found."
10799 (let ((overlays (overlays-at (or pos (point))))
10800 o)
10801 (while (and overlays
10802 (not o))
10803 (if (overlay-get (car overlays) 'invisible)
10804 (setq o (car overlays))
10805 (setq overlays (cdr overlays))))
10806 (if o
10807 (cons (overlay-start o) (overlay-end o)))))
10808
10809 (defun js2-mode-function-at-point (&optional pos)
10810 "Return the innermost function node enclosing current point.
10811 Returns nil if point is not in a function."
10812 (let ((node (js2-node-at-point pos)))
10813 (while (and node (not (js2-function-node-p node)))
10814 (setq node (js2-node-parent node)))
10815 (if (js2-function-node-p node)
10816 node)))
10817
10818 (defun js2-mode-toggle-element ()
10819 "Hide or show the foldable element at the point."
10820 (interactive)
10821 (let (comment fn pos)
10822 (save-excursion
10823 (cond
10824 ;; /* ... */ comment?
10825 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10826 (if (js2-mode-invisible-overlay-bounds
10827 (setq pos (+ 3 (js2-node-abs-pos comment))))
10828 (progn
10829 (goto-char pos)
10830 (js2-mode-show-element))
10831 (js2-mode-hide-element)))
10832 ;; //-comment?
10833 ((save-excursion
10834 (back-to-indentation)
10835 (looking-at js2-mode-//-comment-re))
10836 (js2-mode-toggle-//-comment))
10837 ;; function?
10838 ((setq fn (js2-mode-function-at-point))
10839 (setq pos (and (js2-function-node-body fn)
10840 (js2-node-abs-pos (js2-function-node-body fn))))
10841 (goto-char (1+ pos))
10842 (if (js2-mode-invisible-overlay-bounds)
10843 (js2-mode-show-element)
10844 (js2-mode-hide-element)))
10845 (t
10846 (message "Nothing at point to hide or show"))))))
10847
10848 (defun js2-mode-hide-element ()
10849 "Fold/hide contents of a block, showing ellipses.
10850 Show the hidden text with \\[js2-mode-show-element]."
10851 (interactive)
10852 (if js2-mode-buffer-dirty-p
10853 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10854 (let (node body beg end)
10855 (cond
10856 ((js2-mode-invisible-overlay-bounds)
10857 (message "already hidden"))
10858 (t
10859 (setq node (js2-node-at-point))
10860 (cond
10861 ((js2-block-comment-p node)
10862 (js2-mode-hide-comment node))
10863 (t
10864 (while (and node (not (js2-function-node-p node)))
10865 (setq node (js2-node-parent node)))
10866 (if (and node
10867 (setq body (js2-function-node-body node)))
10868 (progn
10869 (setq beg (js2-node-abs-pos body)
10870 end (+ beg (js2-node-len body)))
10871 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10872 (message "No collapsable element found at point"))))))))
10873
10874 (defun js2-mode-show-element ()
10875 "Show the hidden element at current point."
10876 (interactive)
10877 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10878 (if bounds
10879 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10880 (message "Nothing to un-hide"))))
10881
10882 (defun js2-mode-show-all ()
10883 "Show all of the text in the buffer."
10884 (interactive)
10885 (js2-mode-flag-region (point-min) (point-max) nil))
10886
10887 (defun js2-mode-toggle-hide-functions ()
10888 (interactive)
10889 (if js2-mode-functions-hidden
10890 (js2-mode-show-functions)
10891 (js2-mode-hide-functions)))
10892
10893 (defun js2-mode-hide-functions ()
10894 "Hides all non-nested function bodies in the buffer.
10895 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10896 to open an individual entry."
10897 (interactive)
10898 (if js2-mode-buffer-dirty-p
10899 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10900 (if (null js2-mode-ast)
10901 (message "Oops - parsing failed")
10902 (setq js2-mode-functions-hidden t)
10903 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10904
10905 (defun js2-mode-function-hider (n endp)
10906 (when (not endp)
10907 (let ((tt (js2-node-type n))
10908 body beg end)
10909 (cond
10910 ((and (= tt js2-FUNCTION)
10911 (setq body (js2-function-node-body n)))
10912 (setq beg (js2-node-abs-pos body)
10913 end (+ beg (js2-node-len body)))
10914 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10915 nil) ; don't process children of function
10916 (t
10917 t))))) ; keep processing other AST nodes
10918
10919 (defun js2-mode-show-functions ()
10920 "Un-hide any folded function bodies in the buffer."
10921 (interactive)
10922 (setq js2-mode-functions-hidden nil)
10923 (save-excursion
10924 (goto-char (point-min))
10925 (while (/= (goto-char (next-overlay-change (point)))
10926 (point-max))
10927 (dolist (o (overlays-at (point)))
10928 (when (and (overlay-get o 'invisible)
10929 (not (overlay-get o 'comment)))
10930 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10931
10932 (defun js2-mode-hide-comment (n)
10933 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10934 3 ; /**
10935 2)) ; /*
10936 (beg (+ (js2-node-abs-pos n) head))
10937 (end (- (+ beg (js2-node-len n)) head 2))
10938 (o (js2-mode-flag-region beg end 'hide)))
10939 (overlay-put o 'comment t)))
10940
10941 (defun js2-mode-toggle-hide-comments ()
10942 "Folds all block comments in the buffer.
10943 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10944 to open an individual entry."
10945 (interactive)
10946 (if js2-mode-comments-hidden
10947 (js2-mode-show-comments)
10948 (js2-mode-hide-comments)))
10949
10950 (defun js2-mode-hide-comments ()
10951 (interactive)
10952 (if js2-mode-buffer-dirty-p
10953 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10954 (if (null js2-mode-ast)
10955 (message "Oops - parsing failed")
10956 (setq js2-mode-comments-hidden t)
10957 (dolist (n (js2-ast-root-comments js2-mode-ast))
10958 (when (js2-block-comment-p n)
10959 (js2-mode-hide-comment n)))
10960 (js2-mode-hide-//-comments)))
10961
10962 (defun js2-mode-extend-//-comment (direction)
10963 "Find start or end of a block of similar //-comment lines.
10964 DIRECTION is -1 to look back, 1 to look forward.
10965 INDENT is the indentation level to match.
10966 Returns the end-of-line position of the furthest adjacent
10967 //-comment line with the same indentation as the current line.
10968 If there is no such matching line, returns current end of line."
10969 (let ((pos (point-at-eol))
10970 (indent (current-indentation)))
10971 (save-excursion
10972 (while (and (zerop (forward-line direction))
10973 (looking-at js2-mode-//-comment-re)
10974 (eq indent (length (match-string 1))))
10975 (setq pos (point-at-eol))
10976 pos))))
10977
10978 (defun js2-mode-hide-//-comments ()
10979 "Fold adjacent 1-line comments, showing only snippet of first one."
10980 (let (beg end)
10981 (save-excursion
10982 (goto-char (point-min))
10983 (while (re-search-forward js2-mode-//-comment-re nil t)
10984 (setq beg (point)
10985 end (js2-mode-extend-//-comment 1))
10986 (unless (eq beg end)
10987 (overlay-put (js2-mode-flag-region beg end 'hide)
10988 'comment t))
10989 (goto-char end)
10990 (forward-char 1)))))
10991
10992 (defun js2-mode-toggle-//-comment ()
10993 "Fold or un-fold any multi-line //-comment at point.
10994 Caller should have determined that this line starts with a //-comment."
10995 (let* ((beg (point-at-eol))
10996 (end beg))
10997 (save-excursion
10998 (goto-char end)
10999 (if (js2-mode-invisible-overlay-bounds)
11000 (js2-mode-show-element)
11001 ;; else hide the comment
11002 (setq beg (js2-mode-extend-//-comment -1)
11003 end (js2-mode-extend-//-comment 1))
11004 (unless (eq beg end)
11005 (overlay-put (js2-mode-flag-region beg end 'hide)
11006 'comment t))))))
11007
11008 (defun js2-mode-show-comments ()
11009 "Un-hide any hidden comments, leaving other hidden elements alone."
11010 (interactive)
11011 (setq js2-mode-comments-hidden nil)
11012 (save-excursion
11013 (goto-char (point-min))
11014 (while (/= (goto-char (next-overlay-change (point)))
11015 (point-max))
11016 (dolist (o (overlays-at (point)))
11017 (when (overlay-get o 'comment)
11018 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11019
11020 (defun js2-mode-display-warnings-and-errors ()
11021 "Turn on display of warnings and errors."
11022 (interactive)
11023 (setq js2-mode-show-parse-errors t
11024 js2-mode-show-strict-warnings t)
11025 (js2-reparse 'force))
11026
11027 (defun js2-mode-hide-warnings-and-errors ()
11028 "Turn off display of warnings and errors."
11029 (interactive)
11030 (setq js2-mode-show-parse-errors nil
11031 js2-mode-show-strict-warnings nil)
11032 (js2-reparse 'force))
11033
11034 (defun js2-mode-toggle-warnings-and-errors ()
11035 "Toggle the display of warnings and errors.
11036 Some users don't like having warnings/errors reported while they type."
11037 (interactive)
11038 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11039 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11040 (if (called-interactively-p 'any)
11041 (message "warnings and errors %s"
11042 (if js2-mode-show-parse-errors
11043 "enabled"
11044 "disabled")))
11045 (js2-reparse 'force))
11046
11047 (defun js2-mode-customize ()
11048 (interactive)
11049 (customize-group 'js2-mode))
11050
11051 (defun js2-mode-forward-sexp (&optional arg)
11052 "Move forward across one statement or balanced expression.
11053 With ARG, do it that many times. Negative arg -N means
11054 move backward across N balanced expressions."
11055 (interactive "p")
11056 (setq arg (or arg 1))
11057 (save-restriction
11058 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11059 (js2-reparse)
11060 (let (forward-sexp-function
11061 node (start (point)) pos lp rp child)
11062 (cond
11063 ;; backward-sexp
11064 ;; could probably make this better for some cases:
11065 ;; - if in statement block (e.g. function body), go to parent
11066 ;; - infix exprs like (foo in bar) - maybe go to beginning
11067 ;; of infix expr if in the right-side expression?
11068 ((and arg (minusp arg))
11069 (dotimes (_ (- arg))
11070 (js2-backward-sws)
11071 (forward-char -1) ; Enter the node we backed up to.
11072 (when (setq node (js2-node-at-point (point) t))
11073 (setq pos (js2-node-abs-pos node))
11074 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11075 (setq lp (car parens)
11076 rp (cdr parens)))
11077 (when (and lp (> start lp))
11078 (if (and rp (<= start rp))
11079 ;; Between parens, check if there's a child node we can jump.
11080 (when (setq child (js2-node-closest-child node (point) lp t))
11081 (setq pos (js2-node-abs-pos child)))
11082 ;; Before both parens.
11083 (setq pos lp)))
11084 (let ((state (parse-partial-sexp start pos)))
11085 (goto-char (if (not (zerop (car state)))
11086 ;; Stumble at the unbalanced paren if < 0, or
11087 ;; jump a bit further if > 0.
11088 (scan-sexps start -1)
11089 pos))))
11090 (unless pos (goto-char (point-min)))))
11091 (t
11092 ;; forward-sexp
11093 (dotimes (_ arg)
11094 (js2-forward-sws)
11095 (when (setq node (js2-node-at-point (point) t))
11096 (setq pos (js2-node-abs-pos node))
11097 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11098 (setq lp (car parens)
11099 rp (cdr parens)))
11100 (or
11101 (when (and rp (<= start rp))
11102 (if (> start lp)
11103 (when (setq child (js2-node-closest-child node (point) rp))
11104 (setq pos (js2-node-abs-end child)))
11105 (setq pos (1+ rp))))
11106 ;; No parens or child nodes, looks for the end of the curren node.
11107 (incf pos (js2-node-len
11108 (if (js2-expr-stmt-node-p (js2-node-parent node))
11109 ;; Stop after the semicolon.
11110 (js2-node-parent node)
11111 node))))
11112 (let ((state (save-excursion (parse-partial-sexp start pos))))
11113 (goto-char (if (not (zerop (car state)))
11114 (scan-sexps start 1)
11115 pos))))
11116 (unless pos (goto-char (point-max)))))))))
11117
11118 (defun js2-mode-forward-sexp-parens (node abs-pos)
11119 "Return a cons cell with positions of main parens in NODE."
11120 (cond
11121 ((or (js2-array-node-p node)
11122 (js2-object-node-p node)
11123 (js2-array-comp-node-p node)
11124 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11125 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11126 ((js2-paren-expr-node-p node)
11127 (let ((lp (js2-node-lp node))
11128 (rp (js2-node-rp node)))
11129 (cons (when lp (+ abs-pos lp))
11130 (when rp (+ abs-pos rp)))))))
11131
11132 (defun js2-node-closest-child (parent point limit &optional before)
11133 (let* ((parent-pos (js2-node-abs-pos parent))
11134 (rpoint (- point parent-pos))
11135 (rlimit (- limit parent-pos))
11136 (min (min rpoint rlimit))
11137 (max (max rpoint rlimit))
11138 found)
11139 (catch 'done
11140 (js2-visit-ast
11141 parent
11142 (lambda (node _end-p)
11143 (if (eq node parent)
11144 t
11145 (let ((pos (js2-node-pos node)) ;; Both relative values.
11146 (end (+ (js2-node-pos node) (js2-node-len node))))
11147 (when (and (>= pos min) (<= end max)
11148 (if before (< pos rpoint) (> end rpoint)))
11149 (setq found node))
11150 (when (> end rpoint)
11151 (throw 'done nil)))
11152 nil))))
11153 found))
11154
11155 (defun js2-errors ()
11156 "Return a list of errors found."
11157 (and js2-mode-ast
11158 (js2-ast-root-errors js2-mode-ast)))
11159
11160 (defun js2-warnings ()
11161 "Return a list of warnings found."
11162 (and js2-mode-ast
11163 (js2-ast-root-warnings js2-mode-ast)))
11164
11165 (defun js2-have-errors-p ()
11166 "Return non-nil if any parse errors or warnings were found."
11167 (or (js2-errors) (js2-warnings)))
11168
11169 (defun js2-errors-and-warnings ()
11170 "Return a copy of the concatenated errors and warnings lists.
11171 They are appended: first the errors, then the warnings.
11172 Entries are of the form (MSG BEG END)."
11173 (when js2-mode-ast
11174 (append (js2-ast-root-errors js2-mode-ast)
11175 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11176
11177 (defun js2-next-error (&optional arg reset)
11178 "Move to next parse error.
11179 Typically invoked via \\[next-error].
11180 ARG is the number of errors, forward or backward, to move.
11181 RESET means start over from the beginning."
11182 (interactive "p")
11183 (if (not (or (js2-errors) (js2-warnings)))
11184 (message "No errors")
11185 (when reset
11186 (goto-char (point-min)))
11187 (let* ((errs (js2-errors-and-warnings))
11188 (continue t)
11189 (start (point))
11190 (count (or arg 1))
11191 (backward (minusp count))
11192 (sorter (if backward '> '<))
11193 (stopper (if backward '< '>))
11194 (count (abs count))
11195 all-errs err)
11196 ;; Sort by start position.
11197 (setq errs (sort errs (lambda (e1 e2)
11198 (funcall sorter (second e1) (second e2))))
11199 all-errs errs)
11200 ;; Find nth error with pos > start.
11201 (while (and errs continue)
11202 (when (funcall stopper (cadar errs) start)
11203 (setq err (car errs))
11204 (if (zerop (decf count))
11205 (setq continue nil)))
11206 (setq errs (cdr errs)))
11207 ;; Clear for `js2-echo-error'.
11208 (message nil)
11209 (if err
11210 (goto-char (second err))
11211 ;; Wrap around to first error.
11212 (goto-char (second (car all-errs)))
11213 ;; If we were already on it, echo msg again.
11214 (if (= (point) start)
11215 (js2-echo-error (point) (point)))))))
11216
11217 (defun js2-down-mouse-3 ()
11218 "Make right-click move the point to the click location.
11219 This makes right-click context menu operations a bit more intuitive.
11220 The point will not move if the region is active, however, to avoid
11221 destroying the region selection."
11222 (interactive)
11223 (when (and js2-move-point-on-right-click
11224 (not mark-active))
11225 (let ((e last-input-event))
11226 (ignore-errors
11227 (goto-char (cadadr e))))))
11228
11229 (defun js2-mode-create-imenu-index ()
11230 "Return an alist for `imenu--index-alist'."
11231 ;; This is built up in `js2-parse-record-imenu' during parsing.
11232 (when js2-mode-ast
11233 ;; if we have an ast but no recorder, they're requesting a rescan
11234 (unless js2-imenu-recorder
11235 (js2-reparse 'force))
11236 (prog1
11237 (js2-build-imenu-index)
11238 (setq js2-imenu-recorder nil
11239 js2-imenu-function-map nil))))
11240
11241 (defun js2-mode-find-tag ()
11242 "Replacement for `find-tag-default'.
11243 `find-tag-default' returns a ridiculous answer inside comments."
11244 (let (beg end)
11245 (js2-with-underscore-as-word-syntax
11246 (save-excursion
11247 (if (and (not (looking-at "[[:alnum:]_$]"))
11248 (looking-back "[[:alnum:]_$]"))
11249 (setq beg (progn (forward-word -1) (point))
11250 end (progn (forward-word 1) (point)))
11251 (setq beg (progn (forward-word 1) (point))
11252 end (progn (forward-word -1) (point))))
11253 (replace-regexp-in-string
11254 "[\"']" ""
11255 (buffer-substring-no-properties beg end))))))
11256
11257 (defun js2-mode-forward-sibling ()
11258 "Move to the end of the sibling following point in parent.
11259 Returns non-nil if successful, or nil if there was no following sibling."
11260 (let* ((node (js2-node-at-point))
11261 (parent (js2-mode-find-enclosing-fn node))
11262 sib)
11263 (when (setq sib (js2-node-find-child-after (point) parent))
11264 (goto-char (+ (js2-node-abs-pos sib)
11265 (js2-node-len sib))))))
11266
11267 (defun js2-mode-backward-sibling ()
11268 "Move to the beginning of the sibling node preceding point in parent.
11269 Parent is defined as the enclosing script or function."
11270 (let* ((node (js2-node-at-point))
11271 (parent (js2-mode-find-enclosing-fn node))
11272 sib)
11273 (when (setq sib (js2-node-find-child-before (point) parent))
11274 (goto-char (js2-node-abs-pos sib)))))
11275
11276 (defun js2-beginning-of-defun (&optional arg)
11277 "Go to line on which current function starts, and return t on success.
11278 If we're not in a function or already at the beginning of one, go
11279 to beginning of previous script-level element.
11280 With ARG N, do that N times. If N is negative, move forward."
11281 (setq arg (or arg 1))
11282 (if (plusp arg)
11283 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11284 (when (cond
11285 ((js2-function-node-p parent)
11286 (goto-char (js2-node-abs-pos parent)))
11287 (t
11288 (js2-mode-backward-sibling)))
11289 (if (> arg 1)
11290 (js2-beginning-of-defun (1- arg))
11291 t)))
11292 (when (js2-end-of-defun)
11293 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11294
11295 (defun js2-end-of-defun ()
11296 "Go to the char after the last position of the current function
11297 or script-level element."
11298 (let* ((node (js2-node-at-point))
11299 (parent (or (and (js2-function-node-p node) node)
11300 (js2-node-parent-script-or-fn node)))
11301 script)
11302 (unless (js2-function-node-p parent)
11303 ;; Use current script-level node, or, if none, the next one.
11304 (setq script (or parent node)
11305 parent (js2-node-find-child-before (point) script))
11306 (when (or (null parent)
11307 (>= (point) (+ (js2-node-abs-pos parent)
11308 (js2-node-len parent))))
11309 (setq parent (js2-node-find-child-after (point) script))))
11310 (when parent
11311 (goto-char (+ (js2-node-abs-pos parent)
11312 (js2-node-len parent))))))
11313
11314 (defun js2-mark-defun (&optional allow-extend)
11315 "Put mark at end of this function, point at beginning.
11316 The function marked is the one that contains point.
11317
11318 Interactively, if this command is repeated,
11319 or (in Transient Mark mode) if the mark is active,
11320 it marks the next defun after the ones already marked."
11321 (interactive "p")
11322 (let (extended)
11323 (when (and allow-extend
11324 (or (and (eq last-command this-command) (mark t))
11325 (and transient-mark-mode mark-active)))
11326 (let ((sib (save-excursion
11327 (goto-char (mark))
11328 (if (js2-mode-forward-sibling)
11329 (point)))))
11330 (if sib
11331 (progn
11332 (set-mark sib)
11333 (setq extended t))
11334 ;; no more siblings - try extending to enclosing node
11335 (goto-char (mark t)))))
11336 (when (not extended)
11337 (let ((node (js2-node-at-point (point) t)) ; skip comments
11338 ast fn stmt parent beg end)
11339 (when (js2-ast-root-p node)
11340 (setq ast node
11341 node (or (js2-node-find-child-after (point) node)
11342 (js2-node-find-child-before (point) node))))
11343 ;; only mark whole buffer if we can't find any children
11344 (if (null node)
11345 (setq node ast))
11346 (if (js2-function-node-p node)
11347 (setq parent node)
11348 (setq fn (js2-mode-find-enclosing-fn node)
11349 stmt (if (or (null fn)
11350 (js2-ast-root-p fn))
11351 (js2-mode-find-first-stmt node))
11352 parent (or stmt fn)))
11353 (setq beg (js2-node-abs-pos parent)
11354 end (+ beg (js2-node-len parent)))
11355 (push-mark beg)
11356 (goto-char end)
11357 (exchange-point-and-mark)))))
11358
11359 (defun js2-narrow-to-defun ()
11360 "Narrow to the function enclosing point."
11361 (interactive)
11362 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11363 (fn (if (js2-script-node-p node)
11364 node
11365 (js2-mode-find-enclosing-fn node)))
11366 (beg (js2-node-abs-pos fn)))
11367 (unless (js2-ast-root-p fn)
11368 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11369
11370 (provide 'js2-mode)
11371
11372 ;;; js2-mode.el ends here