]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Bump the version
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 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: 20141115
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
930 ;; Rhino awkwardly passes a statementLabel parameter to the
931 ;; statementHelper() function, the main statement parser, which
932 ;; is then used by quite a few of the sub-parsers. We just make
933 ;; it a buffer-local variable and make sure it's cleaned up properly.
934 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
935
936 ;; Similarly, Rhino passes an inForInit boolean through about half
937 ;; the expression parsers. We use a dynamically-scoped variable,
938 ;; which makes it easier to funcall the parsers individually without
939 ;; worrying about whether they take the parameter or not.
940 (js2-deflocal js2-in-for-init nil)
941 (js2-deflocal js2-temp-name-counter 0)
942 (js2-deflocal js2-parse-stmt-count 0)
943
944 (defsubst js2-get-next-temp-name ()
945 (format "$%d" (incf js2-temp-name-counter)))
946
947 (defvar js2-parse-interruptable-p t
948 "Set this to nil to force parse to continue until finished.
949 This will mostly be useful for interpreters.")
950
951 (defvar js2-statements-per-pause 50
952 "Pause after this many statements to check for user input.
953 If user input is pending, stop the parse and discard the tree.
954 This makes for a smoother user experience for large files.
955 You may have to wait a second or two before the highlighting
956 and error-reporting appear, but you can always type ahead if
957 you wish. This appears to be more or less how Eclipse, IntelliJ
958 and other editors work.")
959
960 (js2-deflocal js2-record-comments t
961 "Instructs the scanner to record comments in `js2-scanned-comments'.")
962
963 (js2-deflocal js2-scanned-comments nil
964 "List of all comments from the current parse.")
965
966 (defcustom js2-mode-indent-inhibit-undo nil
967 "Non-nil to disable collection of Undo information when indenting lines.
968 Some users have requested this behavior. It's nil by default because
969 other Emacs modes don't work this way."
970 :type 'boolean
971 :group 'js2-mode)
972
973 (defcustom js2-mode-indent-ignore-first-tab nil
974 "If non-nil, ignore first TAB keypress if we look indented properly.
975 It's fairly common for users to navigate to an already-indented line
976 and press TAB for reassurance that it's been indented. For this class
977 of users, we want the first TAB press on a line to be ignored if the
978 line is already indented to one of the precomputed alternatives.
979
980 This behavior is only partly implemented. If you TAB-indent a line,
981 navigate to another line, and then navigate back, it fails to clear
982 the last-indented variable, so it thinks you've already hit TAB once,
983 and performs the indent. A full solution would involve getting on the
984 point-motion hooks for the entire buffer. If we come across another
985 use cases that requires watching point motion, I'll consider doing it.
986
987 If you set this variable to nil, then the TAB key will always change
988 the indentation of the current line, if more than one alternative
989 indentation spot exists."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defvar js2-indent-hook nil
994 "A hook for user-defined indentation rules.
995
996 Functions on this hook should expect two arguments: (LIST INDEX)
997 The LIST argument is the list of computed indentation points for
998 the current line. INDEX is the list index of the indentation point
999 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1000 indent function is not going to change the current line indentation.
1001
1002 If a hook function on this list returns a non-nil value, then
1003 `js2-bounce-indent' assumes the hook function has performed its own
1004 indentation, and will do nothing. If all hook functions on the list
1005 return nil, then `js2-bounce-indent' will use its computed indentation
1006 and reindent the line.
1007
1008 When hook functions on this hook list are called, the variable
1009 `js2-mode-ast' may or may not be set, depending on whether the
1010 parse tree is available. If the variable is nil, you can pass a
1011 callback to `js2-mode-wait-for-parse', and your callback will be
1012 called after the new parse tree is built. This can take some time
1013 in large files.")
1014
1015 (defface js2-warning
1016 `((((class color) (background light))
1017 (:underline "orange"))
1018 (((class color) (background dark))
1019 (:underline "orange"))
1020 (t (:underline t)))
1021 "Face for JavaScript warnings."
1022 :group 'js2-mode)
1023
1024 (defface js2-error
1025 `((((class color) (background light))
1026 (:foreground "red"))
1027 (((class color) (background dark))
1028 (:foreground "red"))
1029 (t (:foreground "red")))
1030 "Face for JavaScript errors."
1031 :group 'js2-mode)
1032
1033 (defface js2-jsdoc-tag
1034 '((t :foreground "SlateGray"))
1035 "Face used to highlight @whatever tags in jsdoc comments."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-type
1039 '((t :foreground "SteelBlue"))
1040 "Face used to highlight {FooBar} types in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-value
1044 '((t :foreground "PeachPuff3"))
1045 "Face used to highlight tag values in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-function-param
1049 '((t :foreground "SeaGreen"))
1050 "Face used to highlight function parameters in javascript."
1051 :group 'js2-mode)
1052
1053 (defface js2-function-call
1054 '((t :inherit default))
1055 "Face used to highlight function name in calls."
1056 :group 'js2-mode)
1057
1058 (defface js2-instance-member
1059 '((t :foreground "DarkOrchid"))
1060 "Face used to highlight instance variables in javascript.
1061 Not currently used."
1062 :group 'js2-mode)
1063
1064 (defface js2-private-member
1065 '((t :foreground "PeachPuff3"))
1066 "Face used to highlight calls to private methods in javascript.
1067 Not currently used."
1068 :group 'js2-mode)
1069
1070 (defface js2-private-function-call
1071 '((t :foreground "goldenrod"))
1072 "Face used to highlight calls to private functions in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-html-tag-name
1077 '((((class color) (min-colors 88) (background light))
1078 (:foreground "rosybrown"))
1079 (((class color) (min-colors 8) (background dark))
1080 (:foreground "yellow"))
1081 (((class color) (min-colors 8) (background light))
1082 (:foreground "magenta")))
1083 "Face used to highlight jsdoc html tag names"
1084 :group 'js2-mode)
1085
1086 (defface js2-jsdoc-html-tag-delimiter
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "dark khaki"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "green"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "green")))
1093 "Face used to highlight brackets in jsdoc html tags."
1094 :group 'js2-mode)
1095
1096 (defface js2-external-variable
1097 '((t :foreground "orange"))
1098 "Face used to highlight undeclared variable identifiers.")
1099
1100 (defcustom js2-init-hook nil
1101 "List of functions to be called after `js2-mode' or
1102 `js2-minor-mode' has initialized all variables, before parsing
1103 the buffer for the first time."
1104 :type 'hook
1105 :group 'js2-mode
1106 :version "20130608")
1107
1108 (defcustom js2-post-parse-callbacks nil
1109 "List of callback functions invoked after parsing finishes.
1110 Currently, the main use for this function is to add synthetic
1111 declarations to `js2-recorded-identifiers', which see."
1112 :type 'hook
1113 :group 'js2-mode)
1114
1115 (defcustom js2-build-imenu-callbacks nil
1116 "List of functions called during Imenu index generation.
1117 It's a good place to add additional entries to it, using
1118 `js2-record-imenu-entry'."
1119 :type 'hook
1120 :group 'js2-mode)
1121
1122 (defcustom js2-highlight-external-variables t
1123 "Non-nil to highlight undeclared variable identifiers.
1124 An undeclared variable is any variable not declared with var or let
1125 in the current scope or any lexically enclosing scope. If you use
1126 such a variable, then you are either expecting it to originate from
1127 another file, or you've got a potential bug."
1128 :type 'boolean
1129 :group 'js2-mode)
1130
1131 (defcustom js2-include-jslint-globals t
1132 "Non-nil to include the identifiers from JSLint global
1133 declaration (see http://www.jslint.com/lint.html#global) in the
1134 buffer-local externs list. See `js2-additional-externs' for more
1135 information."
1136 :type 'boolean
1137 :group 'js2-mode)
1138
1139 (defvar js2-mode-map
1140 (let ((map (make-sparse-keymap)))
1141 (define-key map [mouse-1] #'js2-mode-show-node)
1142 (define-key map (kbd "M-j") #'js2-line-break)
1143 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1144 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1145 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1146 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1147 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1148 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1149 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1150 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1151 (when js2-bounce-indent-p
1152 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1153
1154 (define-key map [menu-bar javascript]
1155 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1156
1157 (define-key map [menu-bar javascript customize-js2-mode]
1158 '(menu-item "Customize js2-mode" js2-mode-customize
1159 :help "Customize the behavior of this mode"))
1160
1161 (define-key map [menu-bar javascript js2-force-refresh]
1162 '(menu-item "Force buffer refresh" js2-mode-reset
1163 :help "Re-parse the buffer from scratch"))
1164
1165 (define-key map [menu-bar javascript separator-2]
1166 '("--"))
1167
1168 (define-key map [menu-bar javascript next-error]
1169 '(menu-item "Next warning or error" next-error
1170 :enabled (and js2-mode-ast
1171 (or (js2-ast-root-errors js2-mode-ast)
1172 (js2-ast-root-warnings js2-mode-ast)))
1173 :help "Move to next warning or error"))
1174
1175 (define-key map [menu-bar javascript display-errors]
1176 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1177 :visible (not js2-mode-show-parse-errors)
1178 :help "Turn on display of warnings and errors"))
1179
1180 (define-key map [menu-bar javascript hide-errors]
1181 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1182 :visible js2-mode-show-parse-errors
1183 :help "Turn off display of warnings and errors"))
1184
1185 (define-key map [menu-bar javascript separator-1]
1186 '("--"))
1187
1188 (define-key map [menu-bar javascript js2-toggle-function]
1189 '(menu-item "Show/collapse element" js2-mode-toggle-element
1190 :help "Hide or show function body or comment"))
1191
1192 (define-key map [menu-bar javascript show-comments]
1193 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1194 :visible js2-mode-comments-hidden
1195 :help "Expand all hidden block comments"))
1196
1197 (define-key map [menu-bar javascript hide-comments]
1198 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1199 :visible (not js2-mode-comments-hidden)
1200 :help "Show block comments as /*...*/"))
1201
1202 (define-key map [menu-bar javascript show-all-functions]
1203 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1204 :visible js2-mode-functions-hidden
1205 :help "Expand all hidden function bodies"))
1206
1207 (define-key map [menu-bar javascript hide-all-functions]
1208 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1209 :visible (not js2-mode-functions-hidden)
1210 :help "Show {...} for all top-level function bodies"))
1211
1212 map)
1213 "Keymap used in `js2-mode' buffers.")
1214
1215 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1216
1217 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1218 "Matches a //-comment line. Must be first non-whitespace on line.
1219 First match-group is the leading whitespace.")
1220
1221 (defvar js2-mode-hook nil)
1222
1223 (js2-deflocal js2-mode-ast nil "Private variable.")
1224 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1225 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1226 (js2-deflocal js2-mode-parsing nil "Private variable.")
1227 (js2-deflocal js2-mode-node-overlay nil)
1228
1229 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1230 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1231
1232 (js2-deflocal js2-mode-fontifications nil "Private variable")
1233 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1234 (js2-deflocal js2-imenu-recorder nil "Private variable")
1235 (js2-deflocal js2-imenu-function-map nil "Private variable")
1236
1237 (defvar js2-paragraph-start
1238 "\\(@[[:alpha:]]+\\>\\|$\\)")
1239
1240 ;; Note that we also set a 'c-in-sws text property in html comments,
1241 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1242 (defvar js2-syntactic-ws-start
1243 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1244
1245 (defvar js2-syntactic-ws-end
1246 "\\s \\|[\n\r/]\\|\\s!")
1247
1248 (defvar js2-syntactic-eol
1249 (concat "\\s *\\(/\\*[^*\n\r]*"
1250 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1251 "\\*+/\\s *\\)*"
1252 "\\(//\\|/\\*[^*\n\r]*"
1253 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1254 "\\|\\\\$\\|$\\)")
1255 "Copied from `java-mode'. Needed for some cc-engine functions.")
1256
1257 (defvar js2-comment-prefix-regexp
1258 "//+\\|\\**")
1259
1260 (defvar js2-comment-start-skip
1261 "\\(//+\\|/\\*+\\)\\s *")
1262
1263 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1264 "Non-nil to emit status messages during parsing.")
1265
1266 (defvar js2-mode-functions-hidden nil "Private variable.")
1267 (defvar js2-mode-comments-hidden nil "Private variable.")
1268
1269 (defvar js2-mode-syntax-table
1270 (let ((table (make-syntax-table)))
1271 (c-populate-syntax-table table)
1272 table)
1273 "Syntax table used in `js2-mode' buffers.")
1274
1275 (defvar js2-mode-abbrev-table nil
1276 "Abbrev table in use in `js2-mode' buffers.")
1277 (define-abbrev-table 'js2-mode-abbrev-table ())
1278
1279 (defvar js2-mode-pending-parse-callbacks nil
1280 "List of functions waiting to be notified that parse is finished.")
1281
1282 (defvar js2-mode-last-indented-line -1)
1283
1284 ;;; Localizable error and warning messages
1285
1286 ;; Messages are copied from Rhino's Messages.properties.
1287 ;; Many of the Java-specific messages have been elided.
1288 ;; Add any js2-specific ones at the end, so we can keep
1289 ;; this file synced with changes to Rhino's.
1290
1291 (defvar js2-message-table
1292 (make-hash-table :test 'equal :size 250)
1293 "Contains localized messages for `js2-mode'.")
1294
1295 ;; TODO(stevey): construct this table at compile-time.
1296 (defmacro js2-msg (key &rest strings)
1297 `(puthash ,key (concat ,@strings)
1298 js2-message-table))
1299
1300 (defun js2-get-msg (msg-key)
1301 "Look up a localized message.
1302 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1303 the correct number of ARGS must be provided."
1304 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1305 (args (if (listp msg-key) (cdr msg-key)))
1306 (msg (gethash key js2-message-table)))
1307 (if msg
1308 (apply #'format msg args)
1309 key))) ; default to showing the key
1310
1311 (js2-msg "msg.dup.parms"
1312 "Duplicate parameter name '%s'.")
1313
1314 (js2-msg "msg.too.big.jump"
1315 "Program too complex: jump offset too big.")
1316
1317 (js2-msg "msg.too.big.index"
1318 "Program too complex: internal index exceeds 64K limit.")
1319
1320 (js2-msg "msg.while.compiling.fn"
1321 "Encountered code generation error while compiling function '%s': %s")
1322
1323 (js2-msg "msg.while.compiling.script"
1324 "Encountered code generation error while compiling script: %s")
1325
1326 ;; Context
1327 (js2-msg "msg.ctor.not.found"
1328 "Constructor for '%s' not found.")
1329
1330 (js2-msg "msg.not.ctor"
1331 "'%s' is not a constructor.")
1332
1333 ;; FunctionObject
1334 (js2-msg "msg.varargs.ctor"
1335 "Method or constructor '%s' must be static "
1336 "with the signature (Context cx, Object[] args, "
1337 "Function ctorObj, boolean inNewExpr) "
1338 "to define a variable arguments constructor.")
1339
1340 (js2-msg "msg.varargs.fun"
1341 "Method '%s' must be static with the signature "
1342 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1343 "to define a variable arguments function.")
1344
1345 (js2-msg "msg.incompat.call"
1346 "Method '%s' called on incompatible object.")
1347
1348 (js2-msg "msg.bad.parms"
1349 "Unsupported parameter type '%s' in method '%s'.")
1350
1351 (js2-msg "msg.bad.method.return"
1352 "Unsupported return type '%s' in method '%s'.")
1353
1354 (js2-msg "msg.bad.ctor.return"
1355 "Construction of objects of type '%s' is not supported.")
1356
1357 (js2-msg "msg.no.overload"
1358 "Method '%s' occurs multiple times in class '%s'.")
1359
1360 (js2-msg "msg.method.not.found"
1361 "Method '%s' not found in '%s'.")
1362
1363 ;; IRFactory
1364
1365 (js2-msg "msg.bad.for.in.lhs"
1366 "Invalid left-hand side of for..in loop.")
1367
1368 (js2-msg "msg.mult.index"
1369 "Only one variable allowed in for..in loop.")
1370
1371 (js2-msg "msg.bad.for.in.destruct"
1372 "Left hand side of for..in loop must be an array of "
1373 "length 2 to accept key/value pair.")
1374
1375 (js2-msg "msg.cant.convert"
1376 "Can't convert to type '%s'.")
1377
1378 (js2-msg "msg.bad.assign.left"
1379 "Invalid assignment left-hand side.")
1380
1381 (js2-msg "msg.bad.decr"
1382 "Invalid decerement operand.")
1383
1384 (js2-msg "msg.bad.incr"
1385 "Invalid increment operand.")
1386
1387 (js2-msg "msg.bad.yield"
1388 "yield must be in a function.")
1389
1390 (js2-msg "msg.yield.parenthesized"
1391 "yield expression must be parenthesized.")
1392
1393 ;; NativeGlobal
1394 (js2-msg "msg.cant.call.indirect"
1395 "Function '%s' must be called directly, and not by way of a "
1396 "function of another name.")
1397
1398 (js2-msg "msg.eval.nonstring"
1399 "Calling eval() with anything other than a primitive "
1400 "string value will simply return the value. "
1401 "Is this what you intended?")
1402
1403 (js2-msg "msg.eval.nonstring.strict"
1404 "Calling eval() with anything other than a primitive "
1405 "string value is not allowed in strict mode.")
1406
1407 (js2-msg "msg.bad.destruct.op"
1408 "Invalid destructuring assignment operator")
1409
1410 ;; NativeCall
1411 (js2-msg "msg.only.from.new"
1412 "'%s' may only be invoked from a `new' expression.")
1413
1414 (js2-msg "msg.deprec.ctor"
1415 "The '%s' constructor is deprecated.")
1416
1417 ;; NativeFunction
1418 (js2-msg "msg.no.function.ref.found"
1419 "no source found to decompile function reference %s")
1420
1421 (js2-msg "msg.arg.isnt.array"
1422 "second argument to Function.prototype.apply must be an array")
1423
1424 ;; NativeGlobal
1425 (js2-msg "msg.bad.esc.mask"
1426 "invalid string escape mask")
1427
1428 ;; NativeRegExp
1429 (js2-msg "msg.bad.quant"
1430 "Invalid quantifier %s")
1431
1432 (js2-msg "msg.overlarge.backref"
1433 "Overly large back reference %s")
1434
1435 (js2-msg "msg.overlarge.min"
1436 "Overly large minimum %s")
1437
1438 (js2-msg "msg.overlarge.max"
1439 "Overly large maximum %s")
1440
1441 (js2-msg "msg.zero.quant"
1442 "Zero quantifier %s")
1443
1444 (js2-msg "msg.max.lt.min"
1445 "Maximum %s less than minimum")
1446
1447 (js2-msg "msg.unterm.quant"
1448 "Unterminated quantifier %s")
1449
1450 (js2-msg "msg.unterm.paren"
1451 "Unterminated parenthetical %s")
1452
1453 (js2-msg "msg.unterm.class"
1454 "Unterminated character class %s")
1455
1456 (js2-msg "msg.bad.range"
1457 "Invalid range in character class.")
1458
1459 (js2-msg "msg.trail.backslash"
1460 "Trailing \\ in regular expression.")
1461
1462 (js2-msg "msg.re.unmatched.right.paren"
1463 "unmatched ) in regular expression.")
1464
1465 (js2-msg "msg.no.regexp"
1466 "Regular expressions are not available.")
1467
1468 (js2-msg "msg.bad.backref"
1469 "back-reference exceeds number of capturing parentheses.")
1470
1471 (js2-msg "msg.bad.regexp.compile"
1472 "Only one argument may be specified if the first "
1473 "argument to RegExp.prototype.compile is a RegExp object.")
1474
1475 ;; Parser
1476 (js2-msg "msg.got.syntax.errors"
1477 "Compilation produced %s syntax errors.")
1478
1479 (js2-msg "msg.var.redecl"
1480 "TypeError: redeclaration of var %s.")
1481
1482 (js2-msg "msg.const.redecl"
1483 "TypeError: redeclaration of const %s.")
1484
1485 (js2-msg "msg.let.redecl"
1486 "TypeError: redeclaration of variable %s.")
1487
1488 (js2-msg "msg.parm.redecl"
1489 "TypeError: redeclaration of formal parameter %s.")
1490
1491 (js2-msg "msg.fn.redecl"
1492 "TypeError: redeclaration of function %s.")
1493
1494 (js2-msg "msg.let.decl.not.in.block"
1495 "SyntaxError: let declaration not directly within block")
1496
1497 ;; NodeTransformer
1498 (js2-msg "msg.dup.label"
1499 "duplicated label")
1500
1501 (js2-msg "msg.undef.label"
1502 "undefined label")
1503
1504 (js2-msg "msg.bad.break"
1505 "unlabelled break must be inside loop or switch")
1506
1507 (js2-msg "msg.continue.outside"
1508 "continue must be inside loop")
1509
1510 (js2-msg "msg.continue.nonloop"
1511 "continue can only use labels of iteration statements")
1512
1513 (js2-msg "msg.bad.throw.eol"
1514 "Line terminator is not allowed between the throw "
1515 "keyword and throw expression.")
1516
1517 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1518 "function statement requires a name")
1519
1520 (js2-msg "msg.no.paren.parms"
1521 "missing ( before function parameters.")
1522
1523 (js2-msg "msg.no.parm"
1524 "missing formal parameter")
1525
1526 (js2-msg "msg.no.paren.after.parms"
1527 "missing ) after formal parameters")
1528
1529 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1530 "parameter without default follows parameter with default")
1531
1532 (js2-msg "msg.param.after.rest" ; added by js2-mode
1533 "parameter after rest parameter")
1534
1535 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1536 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1537
1538 (js2-msg "msg.no.brace.body"
1539 "missing '{' before function body")
1540
1541 (js2-msg "msg.no.brace.after.body"
1542 "missing } after function body")
1543
1544 (js2-msg "msg.no.paren.cond"
1545 "missing ( before condition")
1546
1547 (js2-msg "msg.no.paren.after.cond"
1548 "missing ) after condition")
1549
1550 (js2-msg "msg.no.semi.stmt"
1551 "missing ; before statement")
1552
1553 (js2-msg "msg.missing.semi"
1554 "missing ; after statement")
1555
1556 (js2-msg "msg.no.name.after.dot"
1557 "missing name after . operator")
1558
1559 (js2-msg "msg.no.name.after.coloncolon"
1560 "missing name after :: operator")
1561
1562 (js2-msg "msg.no.name.after.dotdot"
1563 "missing name after .. operator")
1564
1565 (js2-msg "msg.no.name.after.xmlAttr"
1566 "missing name after .@")
1567
1568 (js2-msg "msg.no.bracket.index"
1569 "missing ] in index expression")
1570
1571 (js2-msg "msg.no.paren.switch"
1572 "missing ( before switch expression")
1573
1574 (js2-msg "msg.no.paren.after.switch"
1575 "missing ) after switch expression")
1576
1577 (js2-msg "msg.no.brace.switch"
1578 "missing '{' before switch body")
1579
1580 (js2-msg "msg.bad.switch"
1581 "invalid switch statement")
1582
1583 (js2-msg "msg.no.colon.case"
1584 "missing : after case expression")
1585
1586 (js2-msg "msg.double.switch.default"
1587 "double default label in the switch statement")
1588
1589 (js2-msg "msg.no.while.do"
1590 "missing while after do-loop body")
1591
1592 (js2-msg "msg.no.paren.for"
1593 "missing ( after for")
1594
1595 (js2-msg "msg.no.semi.for"
1596 "missing ; after for-loop initializer")
1597
1598 (js2-msg "msg.no.semi.for.cond"
1599 "missing ; after for-loop condition")
1600
1601 (js2-msg "msg.in.after.for.name"
1602 "missing in or of after for")
1603
1604 (js2-msg "msg.no.paren.for.ctrl"
1605 "missing ) after for-loop control")
1606
1607 (js2-msg "msg.no.paren.with"
1608 "missing ( before with-statement object")
1609
1610 (js2-msg "msg.no.paren.after.with"
1611 "missing ) after with-statement object")
1612
1613 (js2-msg "msg.no.paren.after.let"
1614 "missing ( after let")
1615
1616 (js2-msg "msg.no.paren.let"
1617 "missing ) after variable list")
1618
1619 (js2-msg "msg.no.curly.let"
1620 "missing } after let statement")
1621
1622 (js2-msg "msg.bad.return"
1623 "invalid return")
1624
1625 (js2-msg "msg.no.brace.block"
1626 "missing } in compound statement")
1627
1628 (js2-msg "msg.bad.label"
1629 "invalid label")
1630
1631 (js2-msg "msg.bad.var"
1632 "missing variable name")
1633
1634 (js2-msg "msg.bad.var.init"
1635 "invalid variable initialization")
1636
1637 (js2-msg "msg.no.colon.cond"
1638 "missing : in conditional expression")
1639
1640 (js2-msg "msg.no.paren.arg"
1641 "missing ) after argument list")
1642
1643 (js2-msg "msg.no.bracket.arg"
1644 "missing ] after element list")
1645
1646 (js2-msg "msg.bad.prop"
1647 "invalid property id")
1648
1649 (js2-msg "msg.no.colon.prop"
1650 "missing : after property id")
1651
1652 (js2-msg "msg.no.brace.prop"
1653 "missing } after property list")
1654
1655 (js2-msg "msg.no.paren"
1656 "missing ) in parenthetical")
1657
1658 (js2-msg "msg.reserved.id"
1659 "'%s' is a reserved identifier")
1660
1661 (js2-msg "msg.no.paren.catch"
1662 "missing ( before catch-block condition")
1663
1664 (js2-msg "msg.bad.catchcond"
1665 "invalid catch block condition")
1666
1667 (js2-msg "msg.catch.unreachable"
1668 "any catch clauses following an unqualified catch are unreachable")
1669
1670 (js2-msg "msg.no.brace.try"
1671 "missing '{' before try block")
1672
1673 (js2-msg "msg.no.brace.catchblock"
1674 "missing '{' before catch-block body")
1675
1676 (js2-msg "msg.try.no.catchfinally"
1677 "'try' without 'catch' or 'finally'")
1678
1679 (js2-msg "msg.no.return.value"
1680 "function %s does not always return a value")
1681
1682 (js2-msg "msg.anon.no.return.value"
1683 "anonymous function does not always return a value")
1684
1685 (js2-msg "msg.return.inconsistent"
1686 "return statement is inconsistent with previous usage")
1687
1688 (js2-msg "msg.generator.returns"
1689 "TypeError: legacy generator function '%s' returns a value")
1690
1691 (js2-msg "msg.anon.generator.returns"
1692 "TypeError: anonymous legacy generator function returns a value")
1693
1694 (js2-msg "msg.syntax"
1695 "syntax error")
1696
1697 (js2-msg "msg.unexpected.eof"
1698 "Unexpected end of file")
1699
1700 (js2-msg "msg.XML.bad.form"
1701 "illegally formed XML syntax")
1702
1703 (js2-msg "msg.XML.not.available"
1704 "XML runtime not available")
1705
1706 (js2-msg "msg.too.deep.parser.recursion"
1707 "Too deep recursion while parsing")
1708
1709 (js2-msg "msg.no.side.effects"
1710 "Code has no side effects")
1711
1712 (js2-msg "msg.extra.trailing.comma"
1713 "Trailing comma is not supported in some browsers")
1714
1715 (js2-msg "msg.array.trailing.comma"
1716 "Trailing comma yields different behavior across browsers")
1717
1718 (js2-msg "msg.equal.as.assign"
1719 (concat "Test for equality (==) mistyped as assignment (=)?"
1720 " (parenthesize to suppress warning)"))
1721
1722 (js2-msg "msg.var.hides.arg"
1723 "Variable %s hides argument")
1724
1725 (js2-msg "msg.destruct.assign.no.init"
1726 "Missing = in destructuring declaration")
1727
1728 ;; ScriptRuntime
1729 (js2-msg "msg.no.properties"
1730 "%s has no properties.")
1731
1732 (js2-msg "msg.invalid.iterator"
1733 "Invalid iterator value")
1734
1735 (js2-msg "msg.iterator.primitive"
1736 "__iterator__ returned a primitive value")
1737
1738 (js2-msg "msg.assn.create.strict"
1739 "Assignment to undeclared variable %s")
1740
1741 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1742 "Undeclared variable or function '%s'")
1743
1744 (js2-msg "msg.ref.undefined.prop"
1745 "Reference to undefined property '%s'")
1746
1747 (js2-msg "msg.prop.not.found"
1748 "Property %s not found.")
1749
1750 (js2-msg "msg.invalid.type"
1751 "Invalid JavaScript value of type %s")
1752
1753 (js2-msg "msg.primitive.expected"
1754 "Primitive type expected (had %s instead)")
1755
1756 (js2-msg "msg.namespace.expected"
1757 "Namespace object expected to left of :: (found %s instead)")
1758
1759 (js2-msg "msg.null.to.object"
1760 "Cannot convert null to an object.")
1761
1762 (js2-msg "msg.undef.to.object"
1763 "Cannot convert undefined to an object.")
1764
1765 (js2-msg "msg.cyclic.value"
1766 "Cyclic %s value not allowed.")
1767
1768 (js2-msg "msg.is.not.defined"
1769 "'%s' is not defined.")
1770
1771 (js2-msg "msg.undef.prop.read"
1772 "Cannot read property '%s' from %s")
1773
1774 (js2-msg "msg.undef.prop.write"
1775 "Cannot set property '%s' of %s to '%s'")
1776
1777 (js2-msg "msg.undef.prop.delete"
1778 "Cannot delete property '%s' of %s")
1779
1780 (js2-msg "msg.undef.method.call"
1781 "Cannot call method '%s' of %s")
1782
1783 (js2-msg "msg.undef.with"
1784 "Cannot apply 'with' to %s")
1785
1786 (js2-msg "msg.isnt.function"
1787 "%s is not a function, it is %s.")
1788
1789 (js2-msg "msg.isnt.function.in"
1790 "Cannot call property %s in object %s. "
1791 "It is not a function, it is '%s'.")
1792
1793 (js2-msg "msg.function.not.found"
1794 "Cannot find function %s.")
1795
1796 (js2-msg "msg.function.not.found.in"
1797 "Cannot find function %s in object %s.")
1798
1799 (js2-msg "msg.isnt.xml.object"
1800 "%s is not an xml object.")
1801
1802 (js2-msg "msg.no.ref.to.get"
1803 "%s is not a reference to read reference value.")
1804
1805 (js2-msg "msg.no.ref.to.set"
1806 "%s is not a reference to set reference value to %s.")
1807
1808 (js2-msg "msg.no.ref.from.function"
1809 "Function %s can not be used as the left-hand "
1810 "side of assignment or as an operand of ++ or -- operator.")
1811
1812 (js2-msg "msg.bad.default.value"
1813 "Object's getDefaultValue() method returned an object.")
1814
1815 (js2-msg "msg.instanceof.not.object"
1816 "Can't use instanceof on a non-object.")
1817
1818 (js2-msg "msg.instanceof.bad.prototype"
1819 "'prototype' property of %s is not an object.")
1820
1821 (js2-msg "msg.bad.radix"
1822 "illegal radix %s.")
1823
1824 ;; ScriptableObject
1825 (js2-msg "msg.default.value"
1826 "Cannot find default value for object.")
1827
1828 (js2-msg "msg.zero.arg.ctor"
1829 "Cannot load class '%s' which has no zero-parameter constructor.")
1830
1831 (js2-msg "msg.ctor.multiple.parms"
1832 "Can't define constructor or class %s since more than "
1833 "one constructor has multiple parameters.")
1834
1835 (js2-msg "msg.extend.scriptable"
1836 "%s must extend ScriptableObject in order to define property %s.")
1837
1838 (js2-msg "msg.bad.getter.parms"
1839 "In order to define a property, getter %s must have zero "
1840 "parameters or a single ScriptableObject parameter.")
1841
1842 (js2-msg "msg.obj.getter.parms"
1843 "Expected static or delegated getter %s to take "
1844 "a ScriptableObject parameter.")
1845
1846 (js2-msg "msg.getter.static"
1847 "Getter and setter must both be static or neither be static.")
1848
1849 (js2-msg "msg.setter.return"
1850 "Setter must have void return type: %s")
1851
1852 (js2-msg "msg.setter2.parms"
1853 "Two-parameter setter must take a ScriptableObject as "
1854 "its first parameter.")
1855
1856 (js2-msg "msg.setter1.parms"
1857 "Expected single parameter setter for %s")
1858
1859 (js2-msg "msg.setter2.expected"
1860 "Expected static or delegated setter %s to take two parameters.")
1861
1862 (js2-msg "msg.setter.parms"
1863 "Expected either one or two parameters for setter.")
1864
1865 (js2-msg "msg.setter.bad.type"
1866 "Unsupported parameter type '%s' in setter '%s'.")
1867
1868 (js2-msg "msg.add.sealed"
1869 "Cannot add a property to a sealed object: %s.")
1870
1871 (js2-msg "msg.remove.sealed"
1872 "Cannot remove a property from a sealed object: %s.")
1873
1874 (js2-msg "msg.modify.sealed"
1875 "Cannot modify a property of a sealed object: %s.")
1876
1877 (js2-msg "msg.modify.readonly"
1878 "Cannot modify readonly property: %s.")
1879
1880 ;; TokenStream
1881 (js2-msg "msg.missing.exponent"
1882 "missing exponent")
1883
1884 (js2-msg "msg.caught.nfe"
1885 "number format error")
1886
1887 (js2-msg "msg.unterminated.string.lit"
1888 "unterminated string literal")
1889
1890 (js2-msg "msg.unterminated.comment"
1891 "unterminated comment")
1892
1893 (js2-msg "msg.unterminated.re.lit"
1894 "unterminated regular expression literal")
1895
1896 (js2-msg "msg.invalid.re.flag"
1897 "invalid flag after regular expression")
1898
1899 (js2-msg "msg.no.re.input.for"
1900 "no input for %s")
1901
1902 (js2-msg "msg.illegal.character"
1903 "illegal character")
1904
1905 (js2-msg "msg.invalid.escape"
1906 "invalid Unicode escape sequence")
1907
1908 (js2-msg "msg.bad.namespace"
1909 "not a valid default namespace statement. "
1910 "Syntax is: default xml namespace = EXPRESSION;")
1911
1912 ;; TokensStream warnings
1913 (js2-msg "msg.bad.octal.literal"
1914 "illegal octal literal digit %s; "
1915 "interpreting it as a decimal digit")
1916
1917 (js2-msg "msg.missing.hex.digits"
1918 "missing hexadecimal digits after '0x'")
1919
1920 (js2-msg "msg.missing.binary.digits"
1921 "missing binary digits after '0b'")
1922
1923 (js2-msg "msg.missing.octal.digits"
1924 "missing octal digits after '0o'")
1925
1926 (js2-msg "msg.script.is.not.constructor"
1927 "Script objects are not constructors.")
1928
1929 ;; Arrays
1930 (js2-msg "msg.arraylength.bad"
1931 "Inappropriate array length.")
1932
1933 ;; Arrays
1934 (js2-msg "msg.arraylength.too.big"
1935 "Array length %s exceeds supported capacity limit.")
1936
1937 ;; URI
1938 (js2-msg "msg.bad.uri"
1939 "Malformed URI sequence.")
1940
1941 ;; Number
1942 (js2-msg "msg.bad.precision"
1943 "Precision %s out of range.")
1944
1945 ;; NativeGenerator
1946 (js2-msg "msg.send.newborn"
1947 "Attempt to send value to newborn generator")
1948
1949 (js2-msg "msg.already.exec.gen"
1950 "Already executing generator")
1951
1952 (js2-msg "msg.StopIteration.invalid"
1953 "StopIteration may not be changed to an arbitrary object.")
1954
1955 ;; Interpreter
1956 (js2-msg "msg.yield.closing"
1957 "Yield from closing generator")
1958
1959 ;;; Tokens Buffer
1960
1961 (defconst js2-ti-max-lookahead 2)
1962 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1963
1964 ;; Have to call `js2-init-scanner' to initialize the values.
1965 (js2-deflocal js2-ti-tokens nil)
1966 (js2-deflocal js2-ti-tokens-cursor nil)
1967 (js2-deflocal js2-ti-lookahead nil)
1968
1969 (defun js2-new-token (offset)
1970 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1971 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1972 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1973 token))
1974
1975 (defsubst js2-current-token ()
1976 (aref js2-ti-tokens js2-ti-tokens-cursor))
1977
1978 (defsubst js2-current-token-string ()
1979 (js2-token-string (js2-current-token)))
1980
1981 (defsubst js2-current-token-type ()
1982 (js2-token-type (js2-current-token)))
1983
1984 (defsubst js2-current-token-beg ()
1985 (js2-token-beg (js2-current-token)))
1986
1987 (defsubst js2-current-token-end ()
1988 (js2-token-end (js2-current-token)))
1989
1990 (defun js2-current-token-len ()
1991 (let ((token (js2-current-token)))
1992 (- (js2-token-end token)
1993 (js2-token-beg token))))
1994
1995 (defun js2-ts-seek (state)
1996 (setq js2-ts-lineno (js2-ts-state-lineno state)
1997 js2-ts-cursor (js2-ts-state-cursor state)
1998 js2-ti-tokens (js2-ts-state-tokens state)
1999 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2000 js2-ti-lookahead (js2-ts-state-lookahead state)))
2001
2002 ;;; Utilities
2003
2004 (defun js2-delete-if (predicate list)
2005 "Remove all items satisfying PREDICATE in LIST."
2006 (loop for item in list
2007 if (not (funcall predicate item))
2008 collect item))
2009
2010 (defun js2-position (element list)
2011 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2012 Returns nil if element is not found in the list."
2013 (let ((count 0)
2014 found)
2015 (while (and list (not found))
2016 (if (eq element (car list))
2017 (setq found t)
2018 (setq count (1+ count)
2019 list (cdr list))))
2020 (if found count)))
2021
2022 (defun js2-find-if (predicate list)
2023 "Find first item satisfying PREDICATE in LIST."
2024 (let (result)
2025 (while (and list (not result))
2026 (if (funcall predicate (car list))
2027 (setq result (car list)))
2028 (setq list (cdr list)))
2029 result))
2030
2031 (defmacro js2-time (form)
2032 "Evaluate FORM, discard result, and return elapsed time in sec."
2033 (declare (debug t))
2034 (let ((beg (make-symbol "--js2-time-beg--"))
2035 (delta (make-symbol "--js2-time-end--")))
2036 `(let ((,beg (current-time))
2037 ,delta)
2038 ,form
2039 (/ (truncate (* (- (float-time (current-time))
2040 (float-time ,beg))
2041 10000))
2042 10000.0))))
2043
2044 (defsubst js2-same-line (pos)
2045 "Return t if POS is on the same line as current point."
2046 (and (>= pos (point-at-bol))
2047 (<= pos (point-at-eol))))
2048
2049 (defun js2-code-bug ()
2050 "Signal an error when we encounter an unexpected code path."
2051 (error "failed assertion"))
2052
2053 (defsubst js2-record-text-property (beg end prop value)
2054 "Record a text property to set when parsing finishes."
2055 (push (list beg end prop value) js2-mode-deferred-properties))
2056
2057 ;; I'd like to associate errors with nodes, but for now the
2058 ;; easiest thing to do is get the context info from the last token.
2059 (defun js2-record-parse-error (msg &optional arg pos len)
2060 (push (list (list msg arg)
2061 (or pos (js2-current-token-beg))
2062 (or len (js2-current-token-len)))
2063 js2-parsed-errors))
2064
2065 (defun js2-report-error (msg &optional msg-arg pos len)
2066 "Signal a syntax error or record a parse error."
2067 (if js2-recover-from-parse-errors
2068 (js2-record-parse-error msg msg-arg pos len)
2069 (signal 'js2-syntax-error
2070 (list msg
2071 js2-ts-lineno
2072 (save-excursion
2073 (goto-char js2-ts-cursor)
2074 (current-column))
2075 js2-ts-hit-eof))))
2076
2077 (defun js2-report-warning (msg &optional msg-arg pos len face)
2078 (if js2-compiler-report-warning-as-error
2079 (js2-report-error msg msg-arg pos len)
2080 (push (list (list msg msg-arg)
2081 (or pos (js2-current-token-beg))
2082 (or len (js2-current-token-len))
2083 face)
2084 js2-parsed-warnings)))
2085
2086 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2087 (if js2-compiler-strict-mode
2088 (js2-report-warning msg-id msg-arg beg
2089 (and beg end (- end beg)))))
2090
2091 (put 'js2-syntax-error 'error-conditions
2092 '(error syntax-error js2-syntax-error))
2093 (put 'js2-syntax-error 'error-message "Syntax error")
2094
2095 (put 'js2-parse-error 'error-conditions
2096 '(error parse-error js2-parse-error))
2097 (put 'js2-parse-error 'error-message "Parse error")
2098
2099 (defmacro js2-clear-flag (flags flag)
2100 `(setq ,flags (logand ,flags (lognot ,flag))))
2101
2102 (defmacro js2-set-flag (flags flag)
2103 "Logical-or FLAG into FLAGS."
2104 `(setq ,flags (logior ,flags ,flag)))
2105
2106 (defsubst js2-flag-set-p (flags flag)
2107 (/= 0 (logand flags flag)))
2108
2109 (defsubst js2-flag-not-set-p (flags flag)
2110 (zerop (logand flags flag)))
2111
2112 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2113 "Evaluate BODY with the _ character set to be word-syntax."
2114 (declare (indent 0) (debug t))
2115 (let ((old-syntax (make-symbol "old-syntax")))
2116 `(let ((,old-syntax (string (char-syntax ?_))))
2117 (unwind-protect
2118 (progn
2119 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2120 ,@body)
2121 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2122
2123 ;;; AST struct and function definitions
2124
2125 ;; flags for ast node property 'member-type (used for e4x operators)
2126 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2127 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2128 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2129
2130 (defsubst js2-relpos (pos anchor)
2131 "Convert POS to be relative to ANCHOR.
2132 If POS is nil, returns nil."
2133 (and pos (- pos anchor)))
2134
2135 (defun js2-make-pad (indent)
2136 (if (zerop indent)
2137 ""
2138 (make-string (* indent js2-basic-offset) ? )))
2139
2140 (defun js2-visit-ast (node callback)
2141 "Visit every node in ast NODE with visitor CALLBACK.
2142
2143 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2144 called twice: once to visit the node, and again after all the node's
2145 children have been processed. The END-P argument is nil on the first
2146 call and non-nil on the second call. The return value of the callback
2147 affects the traversal: if non-nil, the children of NODE are processed.
2148 If the callback returns nil, or if the node has no children, then the
2149 callback is called immediately with a non-nil END-P argument.
2150
2151 The node traversal is approximately lexical-order, although there
2152 are currently no guarantees around this."
2153 (when node
2154 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2155 ;; visit the node
2156 (when (funcall callback node nil)
2157 ;; visit the kids
2158 (cond
2159 ((eq vfunc 'js2-visit-none)
2160 nil) ; don't even bother calling it
2161 ;; Each AST node type has to define a `js2-visitor' function
2162 ;; that takes a node and a callback, and calls `js2-visit-ast'
2163 ;; on each child of the node.
2164 (vfunc
2165 (funcall vfunc node callback))
2166 (t
2167 (error "%s does not define a visitor-traversal function"
2168 (aref node 0)))))
2169 ;; call the end-visit
2170 (funcall callback node t))))
2171
2172 (defstruct (js2-node
2173 (:constructor nil)) ; abstract
2174 "Base AST node type."
2175 (type -1) ; token type
2176 (pos -1) ; start position of this AST node in parsed input
2177 (len 1) ; num characters spanned by the node
2178 props ; optional node property list (an alist)
2179 parent) ; link to parent node; null for root
2180
2181 (defsubst js2-node-get-prop (node prop &optional default)
2182 (or (cadr (assoc prop (js2-node-props node))) default))
2183
2184 (defsubst js2-node-set-prop (node prop value)
2185 (setf (js2-node-props node)
2186 (cons (list prop value) (js2-node-props node))))
2187
2188 (defun js2-fixup-starts (n nodes)
2189 "Adjust the start positions of NODES to be relative to N.
2190 Any node in the list may be nil, for convenience."
2191 (dolist (node nodes)
2192 (when node
2193 (setf (js2-node-pos node) (- (js2-node-pos node)
2194 (js2-node-pos n))))))
2195
2196 (defun js2-node-add-children (parent &rest nodes)
2197 "Set parent node of NODES to PARENT, and return PARENT.
2198 Does nothing if we're not recording parent links.
2199 If any given node in NODES is nil, doesn't record that link."
2200 (js2-fixup-starts parent nodes)
2201 (dolist (node nodes)
2202 (and node
2203 (setf (js2-node-parent node) parent))))
2204
2205 ;; Non-recursive since it's called a frightening number of times.
2206 (defun js2-node-abs-pos (n)
2207 (let ((pos (js2-node-pos n)))
2208 (while (setq n (js2-node-parent n))
2209 (setq pos (+ pos (js2-node-pos n))))
2210 pos))
2211
2212 (defsubst js2-node-abs-end (n)
2213 "Return absolute buffer position of end of N."
2214 (+ (js2-node-abs-pos n) (js2-node-len n)))
2215
2216 ;; It's important to make sure block nodes have a Lisp list for the
2217 ;; child nodes, to limit printing recursion depth in an AST that
2218 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2219 ;; a sufficiently large vector tree.
2220
2221 (defstruct (js2-block-node
2222 (:include js2-node)
2223 (:constructor nil)
2224 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2225 (pos (js2-current-token-beg))
2226 len
2227 props
2228 kids)))
2229 "A block of statements."
2230 kids) ; a Lisp list of the child statement nodes
2231
2232 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2233 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2234
2235 (defun js2-visit-block (ast callback)
2236 "Visit the `js2-block-node' children of AST."
2237 (dolist (kid (js2-block-node-kids ast))
2238 (js2-visit-ast kid callback)))
2239
2240 (defun js2-print-block (n i)
2241 (let ((pad (js2-make-pad i)))
2242 (insert pad "{\n")
2243 (dolist (kid (js2-block-node-kids n))
2244 (js2-print-ast kid (1+ i)))
2245 (insert pad "}")))
2246
2247 (defstruct (js2-scope
2248 (:include js2-block-node)
2249 (:constructor nil)
2250 (:constructor make-js2-scope (&key (type js2-BLOCK)
2251 (pos (js2-current-token-beg))
2252 len
2253 kids)))
2254 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2255 ;; I don't have one of those handy, so I'll use an alist for now.
2256 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2257 ;; and is much lighter-weight to construct (both CPU and mem).
2258 ;; The keys are interned strings (symbols) for faster lookup.
2259 ;; Should switch to hybrid alist/hashtable eventually.
2260 symbol-table ; an alist of (symbol . js2-symbol)
2261 parent-scope ; a `js2-scope'
2262 top) ; top-level `js2-scope' (script/function)
2263
2264 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2265 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2266
2267 (defun js2-node-get-enclosing-scope (node)
2268 "Return the innermost `js2-scope' node surrounding NODE.
2269 Returns nil if there is no enclosing scope node."
2270 (let ((parent (js2-node-parent node)))
2271 (while (not (js2-scope-p parent))
2272 (setq parent (js2-node-parent parent)))
2273 parent))
2274
2275 (defun js2-get-defining-scope (scope name)
2276 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2277 Returns `js2-scope' in which NAME is defined, or nil if not found."
2278 (let ((sym (if (symbolp name)
2279 name
2280 (intern name)))
2281 table
2282 result
2283 (continue t))
2284 (while (and scope continue)
2285 (if (and (setq table (js2-scope-symbol-table scope))
2286 (assq sym table))
2287 (setq continue nil
2288 result scope)
2289 (setq scope (js2-scope-parent-scope scope))))
2290 result))
2291
2292 (defun js2-scope-get-symbol (scope name)
2293 "Return symbol table entry for NAME in SCOPE.
2294 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2295 (and (js2-scope-symbol-table scope)
2296 (cdr (assq (if (symbolp name)
2297 name
2298 (intern name))
2299 (js2-scope-symbol-table scope)))))
2300
2301 (defun js2-scope-put-symbol (scope name symbol)
2302 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2303 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2304 (let* ((table (js2-scope-symbol-table scope))
2305 (sym (if (symbolp name) name (intern name)))
2306 (entry (assq sym table)))
2307 (if entry
2308 (setcdr entry symbol)
2309 (push (cons sym symbol)
2310 (js2-scope-symbol-table scope)))))
2311
2312 (defstruct (js2-symbol
2313 (:constructor nil)
2314 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2315 "A symbol table entry."
2316 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2317 ;; js2-LET, or js2-CONST
2318 decl-type
2319 name ; string
2320 ast-node) ; a `js2-node'
2321
2322 (defstruct (js2-error-node
2323 (:include js2-node)
2324 (:constructor nil) ; silence emacs21 byte-compiler
2325 (:constructor make-js2-error-node (&key (type js2-ERROR)
2326 (pos (js2-current-token-beg))
2327 len)))
2328 "AST node representing a parse error.")
2329
2330 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2331 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2332
2333 (defstruct (js2-script-node
2334 (:include js2-scope)
2335 (:constructor nil)
2336 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2337 (pos (js2-current-token-beg))
2338 len
2339 ;; FIXME: What are those?
2340 var-decls
2341 fun-decls)))
2342 functions ; Lisp list of nested functions
2343 regexps ; Lisp list of (string . flags)
2344 symbols ; alist (every symbol gets unique index)
2345 (param-count 0)
2346 var-names ; vector of string names
2347 consts ; bool-vector matching var-decls
2348 (temp-number 0)) ; for generating temp variables
2349
2350 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2351 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2352
2353 (defun js2-print-script (node indent)
2354 (dolist (kid (js2-block-node-kids node))
2355 (js2-print-ast kid indent)))
2356
2357 (defstruct (js2-ast-root
2358 (:include js2-script-node)
2359 (:constructor nil)
2360 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2361 (pos (js2-current-token-beg))
2362 len
2363 buffer)))
2364 "The root node of a js2 AST."
2365 buffer ; the source buffer from which the code was parsed
2366 comments ; a Lisp list of comments, ordered by start position
2367 errors ; a Lisp list of errors found during parsing
2368 warnings ; a Lisp list of warnings found during parsing
2369 node-count) ; number of nodes in the tree, including the root
2370
2371 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2372 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2373
2374 (defun js2-visit-ast-root (ast callback)
2375 (dolist (kid (js2-ast-root-kids ast))
2376 (js2-visit-ast kid callback))
2377 (dolist (comment (js2-ast-root-comments ast))
2378 (js2-visit-ast comment callback)))
2379
2380 (defstruct (js2-comment-node
2381 (:include js2-node)
2382 (:constructor nil)
2383 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2384 (pos (js2-current-token-beg))
2385 len
2386 format)))
2387 format) ; 'line, 'block, 'jsdoc or 'html
2388
2389 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2390 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2391
2392 (defun js2-print-comment (n i)
2393 ;; We really ought to link end-of-line comments to their nodes.
2394 ;; Or maybe we could add a new comment type, 'endline.
2395 (insert (js2-make-pad i)
2396 (js2-node-string n)))
2397
2398 (defstruct (js2-expr-stmt-node
2399 (:include js2-node)
2400 (:constructor nil)
2401 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2402 (pos js2-ts-cursor)
2403 len
2404 expr)))
2405 "An expression statement."
2406 expr)
2407
2408 (defsubst js2-expr-stmt-node-set-has-result (node)
2409 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2410 (setf (js2-node-type node) js2-EXPR_RESULT))
2411
2412 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2413 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2414
2415 (defun js2-visit-expr-stmt-node (n v)
2416 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2417
2418 (defun js2-print-expr-stmt-node (n indent)
2419 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2420 (insert ";\n"))
2421
2422 (defstruct (js2-loop-node
2423 (:include js2-scope)
2424 (:constructor nil))
2425 "Abstract supertype of loop nodes."
2426 body ; a `js2-block-node'
2427 lp ; position of left-paren, nil if omitted
2428 rp) ; position of right-paren, nil if omitted
2429
2430 (defstruct (js2-do-node
2431 (:include js2-loop-node)
2432 (:constructor nil)
2433 (:constructor make-js2-do-node (&key (type js2-DO)
2434 (pos (js2-current-token-beg))
2435 len
2436 body
2437 condition
2438 while-pos
2439 lp
2440 rp)))
2441 "AST node for do-loop."
2442 condition ; while (expression)
2443 while-pos) ; buffer position of 'while' keyword
2444
2445 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2446 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2447
2448 (defun js2-visit-do-node (n v)
2449 (js2-visit-ast (js2-do-node-body n) v)
2450 (js2-visit-ast (js2-do-node-condition n) v))
2451
2452 (defun js2-print-do-node (n i)
2453 (let ((pad (js2-make-pad i)))
2454 (insert pad "do {\n")
2455 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2456 (js2-print-ast kid (1+ i)))
2457 (insert pad "} while (")
2458 (js2-print-ast (js2-do-node-condition n) 0)
2459 (insert ");\n")))
2460
2461 (defstruct (js2-while-node
2462 (:include js2-loop-node)
2463 (:constructor nil)
2464 (:constructor make-js2-while-node (&key (type js2-WHILE)
2465 (pos (js2-current-token-beg))
2466 len body
2467 condition lp
2468 rp)))
2469 "AST node for while-loop."
2470 condition) ; while-condition
2471
2472 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2473 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2474
2475 (defun js2-visit-while-node (n v)
2476 (js2-visit-ast (js2-while-node-condition n) v)
2477 (js2-visit-ast (js2-while-node-body n) v))
2478
2479 (defun js2-print-while-node (n i)
2480 (let ((pad (js2-make-pad i)))
2481 (insert pad "while (")
2482 (js2-print-ast (js2-while-node-condition n) 0)
2483 (insert ") {\n")
2484 (js2-print-body (js2-while-node-body n) (1+ i))
2485 (insert pad "}\n")))
2486
2487 (defstruct (js2-for-node
2488 (:include js2-loop-node)
2489 (:constructor nil)
2490 (:constructor make-js2-for-node (&key (type js2-FOR)
2491 (pos js2-ts-cursor)
2492 len body init
2493 condition
2494 update lp rp)))
2495 "AST node for a C-style for-loop."
2496 init ; initialization expression
2497 condition ; loop condition
2498 update) ; update clause
2499
2500 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2501 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2502
2503 (defun js2-visit-for-node (n v)
2504 (js2-visit-ast (js2-for-node-init n) v)
2505 (js2-visit-ast (js2-for-node-condition n) v)
2506 (js2-visit-ast (js2-for-node-update n) v)
2507 (js2-visit-ast (js2-for-node-body n) v))
2508
2509 (defun js2-print-for-node (n i)
2510 (let ((pad (js2-make-pad i)))
2511 (insert pad "for (")
2512 (js2-print-ast (js2-for-node-init n) 0)
2513 (insert "; ")
2514 (js2-print-ast (js2-for-node-condition n) 0)
2515 (insert "; ")
2516 (js2-print-ast (js2-for-node-update n) 0)
2517 (insert ") {\n")
2518 (js2-print-body (js2-for-node-body n) (1+ i))
2519 (insert pad "}\n")))
2520
2521 (defstruct (js2-for-in-node
2522 (:include js2-loop-node)
2523 (:constructor nil)
2524 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2525 (pos js2-ts-cursor)
2526 len body
2527 iterator
2528 object
2529 in-pos
2530 each-pos
2531 foreach-p forof-p
2532 lp rp)))
2533 "AST node for a for..in loop."
2534 iterator ; [var] foo in ...
2535 object ; object over which we're iterating
2536 in-pos ; buffer position of 'in' keyword
2537 each-pos ; buffer position of 'each' keyword, if foreach-p
2538 foreach-p ; t if it's a for-each loop
2539 forof-p) ; t if it's a for-of loop
2540
2541 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2542 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2543
2544 (defun js2-visit-for-in-node (n v)
2545 (js2-visit-ast (js2-for-in-node-iterator n) v)
2546 (js2-visit-ast (js2-for-in-node-object n) v)
2547 (js2-visit-ast (js2-for-in-node-body n) v))
2548
2549 (defun js2-print-for-in-node (n i)
2550 (let ((pad (js2-make-pad i))
2551 (foreach (js2-for-in-node-foreach-p n))
2552 (forof (js2-for-in-node-forof-p n)))
2553 (insert pad "for ")
2554 (if foreach
2555 (insert "each "))
2556 (insert "(")
2557 (js2-print-ast (js2-for-in-node-iterator n) 0)
2558 (insert (if forof " of " " in "))
2559 (js2-print-ast (js2-for-in-node-object n) 0)
2560 (insert ") {\n")
2561 (js2-print-body (js2-for-in-node-body n) (1+ i))
2562 (insert pad "}\n")))
2563
2564 (defstruct (js2-return-node
2565 (:include js2-node)
2566 (:constructor nil)
2567 (:constructor make-js2-return-node (&key (type js2-RETURN)
2568 (pos js2-ts-cursor)
2569 len
2570 retval)))
2571 "AST node for a return statement."
2572 retval) ; expression to return, or 'undefined
2573
2574 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2575 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2576
2577 (defun js2-visit-return-node (n v)
2578 (js2-visit-ast (js2-return-node-retval n) v))
2579
2580 (defun js2-print-return-node (n i)
2581 (insert (js2-make-pad i) "return")
2582 (when (js2-return-node-retval n)
2583 (insert " ")
2584 (js2-print-ast (js2-return-node-retval n) 0))
2585 (insert ";\n"))
2586
2587 (defstruct (js2-if-node
2588 (:include js2-node)
2589 (:constructor nil)
2590 (:constructor make-js2-if-node (&key (type js2-IF)
2591 (pos js2-ts-cursor)
2592 len condition
2593 then-part
2594 else-pos
2595 else-part lp
2596 rp)))
2597 "AST node for an if-statement."
2598 condition ; expression
2599 then-part ; statement or block
2600 else-pos ; optional buffer position of 'else' keyword
2601 else-part ; optional statement or block
2602 lp ; position of left-paren, nil if omitted
2603 rp) ; position of right-paren, nil if omitted
2604
2605 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2606 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2607
2608 (defun js2-visit-if-node (n v)
2609 (js2-visit-ast (js2-if-node-condition n) v)
2610 (js2-visit-ast (js2-if-node-then-part n) v)
2611 (js2-visit-ast (js2-if-node-else-part n) v))
2612
2613 (defun js2-print-if-node (n i)
2614 (let ((pad (js2-make-pad i))
2615 (then-part (js2-if-node-then-part n))
2616 (else-part (js2-if-node-else-part n)))
2617 (insert pad "if (")
2618 (js2-print-ast (js2-if-node-condition n) 0)
2619 (insert ") {\n")
2620 (js2-print-body then-part (1+ i))
2621 (insert pad "}")
2622 (cond
2623 ((not else-part)
2624 (insert "\n"))
2625 ((js2-if-node-p else-part)
2626 (insert " else ")
2627 (js2-print-body else-part i))
2628 (t
2629 (insert " else {\n")
2630 (js2-print-body else-part (1+ i))
2631 (insert pad "}\n")))))
2632
2633 (defstruct (js2-try-node
2634 (:include js2-node)
2635 (:constructor nil)
2636 (:constructor make-js2-try-node (&key (type js2-TRY)
2637 (pos js2-ts-cursor)
2638 len
2639 try-block
2640 catch-clauses
2641 finally-block)))
2642 "AST node for a try-statement."
2643 try-block
2644 catch-clauses ; a Lisp list of `js2-catch-node'
2645 finally-block) ; a `js2-finally-node'
2646
2647 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2648 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2649
2650 (defun js2-visit-try-node (n v)
2651 (js2-visit-ast (js2-try-node-try-block n) v)
2652 (dolist (clause (js2-try-node-catch-clauses n))
2653 (js2-visit-ast clause v))
2654 (js2-visit-ast (js2-try-node-finally-block n) v))
2655
2656 (defun js2-print-try-node (n i)
2657 (let ((pad (js2-make-pad i))
2658 (catches (js2-try-node-catch-clauses n))
2659 (finally (js2-try-node-finally-block n)))
2660 (insert pad "try {\n")
2661 (js2-print-body (js2-try-node-try-block n) (1+ i))
2662 (insert pad "}")
2663 (when catches
2664 (dolist (catch catches)
2665 (js2-print-ast catch i)))
2666 (if finally
2667 (js2-print-ast finally i)
2668 (insert "\n"))))
2669
2670 (defstruct (js2-catch-node
2671 (:include js2-node)
2672 (:constructor nil)
2673 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2674 (pos js2-ts-cursor)
2675 len
2676 param
2677 guard-kwd
2678 guard-expr
2679 block lp
2680 rp)))
2681 "AST node for a catch clause."
2682 param ; destructuring form or simple name node
2683 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2684 guard-expr ; catch condition, a `js2-node'
2685 block ; statements, a `js2-block-node'
2686 lp ; buffer position of left-paren, nil if omitted
2687 rp) ; buffer position of right-paren, nil if omitted
2688
2689 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2690 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2691
2692 (defun js2-visit-catch-node (n v)
2693 (js2-visit-ast (js2-catch-node-param n) v)
2694 (when (js2-catch-node-guard-kwd n)
2695 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2696 (js2-visit-ast (js2-catch-node-block n) v))
2697
2698 (defun js2-print-catch-node (n i)
2699 (let ((pad (js2-make-pad i))
2700 (guard-kwd (js2-catch-node-guard-kwd n))
2701 (guard-expr (js2-catch-node-guard-expr n)))
2702 (insert " catch (")
2703 (js2-print-ast (js2-catch-node-param n) 0)
2704 (when guard-kwd
2705 (insert " if ")
2706 (js2-print-ast guard-expr 0))
2707 (insert ") {\n")
2708 (js2-print-body (js2-catch-node-block n) (1+ i))
2709 (insert pad "}")))
2710
2711 (defstruct (js2-finally-node
2712 (:include js2-node)
2713 (:constructor nil)
2714 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2715 (pos js2-ts-cursor)
2716 len body)))
2717 "AST node for a finally clause."
2718 body) ; a `js2-node', often but not always a block node
2719
2720 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2721 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2722
2723 (defun js2-visit-finally-node (n v)
2724 (js2-visit-ast (js2-finally-node-body n) v))
2725
2726 (defun js2-print-finally-node (n i)
2727 (let ((pad (js2-make-pad i)))
2728 (insert " finally {\n")
2729 (js2-print-body (js2-finally-node-body n) (1+ i))
2730 (insert pad "}\n")))
2731
2732 (defstruct (js2-switch-node
2733 (:include js2-node)
2734 (:constructor nil)
2735 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2736 (pos js2-ts-cursor)
2737 len
2738 discriminant
2739 cases lp
2740 rp)))
2741 "AST node for a switch statement."
2742 discriminant ; a `js2-node' (switch expression)
2743 cases ; a Lisp list of `js2-case-node'
2744 lp ; position of open-paren for discriminant, nil if omitted
2745 rp) ; position of close-paren for discriminant, nil if omitted
2746
2747 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2748 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2749
2750 (defun js2-visit-switch-node (n v)
2751 (js2-visit-ast (js2-switch-node-discriminant n) v)
2752 (dolist (c (js2-switch-node-cases n))
2753 (js2-visit-ast c v)))
2754
2755 (defun js2-print-switch-node (n i)
2756 (let ((pad (js2-make-pad i))
2757 (cases (js2-switch-node-cases n)))
2758 (insert pad "switch (")
2759 (js2-print-ast (js2-switch-node-discriminant n) 0)
2760 (insert ") {\n")
2761 (dolist (case cases)
2762 (js2-print-ast case i))
2763 (insert pad "}\n")))
2764
2765 (defstruct (js2-case-node
2766 (:include js2-block-node)
2767 (:constructor nil)
2768 (:constructor make-js2-case-node (&key (type js2-CASE)
2769 (pos js2-ts-cursor)
2770 len kids expr)))
2771 "AST node for a case clause of a switch statement."
2772 expr) ; the case expression (nil for default)
2773
2774 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2775 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2776
2777 (defun js2-visit-case-node (n v)
2778 (js2-visit-ast (js2-case-node-expr n) v)
2779 (js2-visit-block n v))
2780
2781 (defun js2-print-case-node (n i)
2782 (let ((pad (js2-make-pad i))
2783 (expr (js2-case-node-expr n)))
2784 (insert pad)
2785 (if (null expr)
2786 (insert "default:\n")
2787 (insert "case ")
2788 (js2-print-ast expr 0)
2789 (insert ":\n"))
2790 (dolist (kid (js2-case-node-kids n))
2791 (js2-print-ast kid (1+ i)))))
2792
2793 (defstruct (js2-throw-node
2794 (:include js2-node)
2795 (:constructor nil)
2796 (:constructor make-js2-throw-node (&key (type js2-THROW)
2797 (pos js2-ts-cursor)
2798 len expr)))
2799 "AST node for a throw statement."
2800 expr) ; the expression to throw
2801
2802 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2803 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2804
2805 (defun js2-visit-throw-node (n v)
2806 (js2-visit-ast (js2-throw-node-expr n) v))
2807
2808 (defun js2-print-throw-node (n i)
2809 (insert (js2-make-pad i) "throw ")
2810 (js2-print-ast (js2-throw-node-expr n) 0)
2811 (insert ";\n"))
2812
2813 (defstruct (js2-with-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 (:constructor make-js2-with-node (&key (type js2-WITH)
2817 (pos js2-ts-cursor)
2818 len object
2819 body lp rp)))
2820 "AST node for a with-statement."
2821 object
2822 body
2823 lp ; buffer position of left-paren around object, nil if omitted
2824 rp) ; buffer position of right-paren around object, nil if omitted
2825
2826 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2827 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2828
2829 (defun js2-visit-with-node (n v)
2830 (js2-visit-ast (js2-with-node-object n) v)
2831 (js2-visit-ast (js2-with-node-body n) v))
2832
2833 (defun js2-print-with-node (n i)
2834 (let ((pad (js2-make-pad i)))
2835 (insert pad "with (")
2836 (js2-print-ast (js2-with-node-object n) 0)
2837 (insert ") {\n")
2838 (js2-print-body (js2-with-node-body n) (1+ i))
2839 (insert pad "}\n")))
2840
2841 (defstruct (js2-label-node
2842 (:include js2-node)
2843 (:constructor nil)
2844 (:constructor make-js2-label-node (&key (type js2-LABEL)
2845 (pos js2-ts-cursor)
2846 len name)))
2847 "AST node for a statement label or case label."
2848 name ; a string
2849 loop) ; for validating and code-generating continue-to-label
2850
2851 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2852 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2853
2854 (defun js2-print-label (n i)
2855 (insert (js2-make-pad i)
2856 (js2-label-node-name n)
2857 ":\n"))
2858
2859 (defstruct (js2-labeled-stmt-node
2860 (:include js2-node)
2861 (:constructor nil)
2862 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2863 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2864 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2865 (pos js2-ts-cursor)
2866 len labels stmt)))
2867 "AST node for a statement with one or more labels.
2868 Multiple labels for a statement are collapsed into the labels field."
2869 labels ; Lisp list of `js2-label-node'
2870 stmt) ; the statement these labels are for
2871
2872 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2873 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2874
2875 (defun js2-get-label-by-name (lbl-stmt name)
2876 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2877 Returns nil if no such label is in the list."
2878 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2879 result)
2880 (while (and label-list (not result))
2881 (if (string= (js2-label-node-name (car label-list)) name)
2882 (setq result (car label-list))
2883 (setq label-list (cdr label-list))))
2884 result))
2885
2886 (defun js2-visit-labeled-stmt (n v)
2887 (dolist (label (js2-labeled-stmt-node-labels n))
2888 (js2-visit-ast label v))
2889 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2890
2891 (defun js2-print-labeled-stmt (n i)
2892 (dolist (label (js2-labeled-stmt-node-labels n))
2893 (js2-print-ast label i))
2894 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2895
2896 (defun js2-labeled-stmt-node-contains (node label)
2897 "Return t if NODE contains LABEL in its label set.
2898 NODE is a `js2-labels-node'. LABEL is an identifier."
2899 (loop for nl in (js2-labeled-stmt-node-labels node)
2900 if (string= label (js2-label-node-name nl))
2901 return t
2902 finally return nil))
2903
2904 (defsubst js2-labeled-stmt-node-add-label (node label)
2905 "Add a `js2-label-node' to the label set for this statement."
2906 (setf (js2-labeled-stmt-node-labels node)
2907 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2908
2909 (defstruct (js2-jump-node
2910 (:include js2-node)
2911 (:constructor nil))
2912 "Abstract supertype of break and continue nodes."
2913 label ; `js2-name-node' for location of label identifier, if present
2914 target) ; target js2-labels-node or loop/switch statement
2915
2916 (defun js2-visit-jump-node (n v)
2917 ;; We don't visit the target, since it's a back-link.
2918 (js2-visit-ast (js2-jump-node-label n) v))
2919
2920 (defstruct (js2-break-node
2921 (:include js2-jump-node)
2922 (:constructor nil)
2923 (:constructor make-js2-break-node (&key (type js2-BREAK)
2924 (pos js2-ts-cursor)
2925 len label target)))
2926 "AST node for a break statement.
2927 The label field is a `js2-name-node', possibly nil, for the named label
2928 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2929 is the target of the break - a label node or enclosing loop/switch statement.")
2930
2931 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2932 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2933
2934 (defun js2-print-break-node (n i)
2935 (insert (js2-make-pad i) "break")
2936 (when (js2-break-node-label n)
2937 (insert " ")
2938 (js2-print-ast (js2-break-node-label n) 0))
2939 (insert ";\n"))
2940
2941 (defstruct (js2-continue-node
2942 (:include js2-jump-node)
2943 (:constructor nil)
2944 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2945 (pos js2-ts-cursor)
2946 len label target)))
2947 "AST node for a continue statement.
2948 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2949 It is nil if continue specifies no label. The target field is the jump target:
2950 a `js2-label-node' or the innermost enclosing loop.")
2951
2952 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2953 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2954
2955 (defun js2-print-continue-node (n i)
2956 (insert (js2-make-pad i) "continue")
2957 (when (js2-continue-node-label n)
2958 (insert " ")
2959 (js2-print-ast (js2-continue-node-label n) 0))
2960 (insert ";\n"))
2961
2962 (defstruct (js2-function-node
2963 (:include js2-script-node)
2964 (:constructor nil)
2965 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2966 (pos js2-ts-cursor)
2967 len
2968 (ftype 'FUNCTION)
2969 (form 'FUNCTION_STATEMENT)
2970 (name "")
2971 params rest-p
2972 body
2973 generator-type
2974 lp rp)))
2975 "AST node for a function declaration.
2976 The `params' field is a Lisp list of nodes. Each node is either a simple
2977 `js2-name-node', or if it's a destructuring-assignment parameter, a
2978 `js2-array-node' or `js2-object-node'."
2979 ftype ; FUNCTION, GETTER or SETTER
2980 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2981 name ; function name (a `js2-name-node', or nil if anonymous)
2982 params ; a Lisp list of destructuring forms or simple name nodes
2983 rest-p ; if t, the last parameter is rest parameter
2984 body ; a `js2-block-node' or expression node (1.8 only)
2985 lp ; position of arg-list open-paren, or nil if omitted
2986 rp ; position of arg-list close-paren, or nil if omitted
2987 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2988 needs-activation ; t if we need an activation object for this frame
2989 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2990 member-expr) ; nonstandard Ecma extension from Rhino
2991
2992 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2993 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2994
2995 (defun js2-visit-function-node (n v)
2996 (js2-visit-ast (js2-function-node-name n) v)
2997 (dolist (p (js2-function-node-params n))
2998 (js2-visit-ast p v))
2999 (js2-visit-ast (js2-function-node-body n) v))
3000
3001 (defun js2-print-function-node (n i)
3002 (let* ((pad (js2-make-pad i))
3003 (getter (js2-node-get-prop n 'GETTER_SETTER))
3004 (name (or (js2-function-node-name n)
3005 (js2-function-node-member-expr n)))
3006 (params (js2-function-node-params n))
3007 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3008 (rest-p (js2-function-node-rest-p n))
3009 (body (js2-function-node-body n))
3010 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3011 (unless (or getter arrow)
3012 (insert pad "function")
3013 (when (eq (js2-function-node-generator-type n) 'STAR)
3014 (insert "*")))
3015 (when name
3016 (insert " ")
3017 (js2-print-ast name 0))
3018 (insert "(")
3019 (loop with len = (length params)
3020 for param in params
3021 for count from 1
3022 do
3023 (when (and rest-p (= count len))
3024 (insert "..."))
3025 (js2-print-ast param 0)
3026 (when (< count len)
3027 (insert ", ")))
3028 (insert ") ")
3029 (when arrow
3030 (insert "=> "))
3031 (insert "{")
3032 ;; TODO: fix this to be smarter about indenting, etc.
3033 (unless expr
3034 (insert "\n"))
3035 (if (js2-block-node-p body)
3036 (js2-print-body body (1+ i))
3037 (js2-print-ast body 0))
3038 (insert pad "}")
3039 (unless expr
3040 (insert "\n"))))
3041
3042 (defun js2-function-name (node)
3043 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3044 (and (js2-function-node-name node)
3045 (js2-name-node-name (js2-function-node-name node))))
3046
3047 ;; Having this be an expression node makes it more flexible.
3048 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3049 ;; that work better if you assume it's an expression. Whenever we have
3050 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3051 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3052 (defstruct (js2-var-decl-node
3053 (:include js2-node)
3054 (:constructor nil)
3055 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3056 (pos (js2-current-token-beg))
3057 len kids
3058 decl-type)))
3059 "AST node for a variable declaration list (VAR, CONST or LET).
3060 The node bounds differ depending on the declaration type. For VAR or
3061 CONST declarations, the bounds include the var/const keyword. For LET
3062 declarations, the node begins at the position of the first child."
3063 kids ; a Lisp list of `js2-var-init-node' structs.
3064 decl-type) ; js2-VAR, js2-CONST or js2-LET
3065
3066 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3067 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3068
3069 (defun js2-visit-var-decl (n v)
3070 (dolist (kid (js2-var-decl-node-kids n))
3071 (js2-visit-ast kid v)))
3072
3073 (defun js2-print-var-decl (n i)
3074 (let ((pad (js2-make-pad i))
3075 (tt (js2-var-decl-node-decl-type n)))
3076 (insert pad)
3077 (insert (cond
3078 ((= tt js2-VAR) "var ")
3079 ((= tt js2-LET) "let ")
3080 ((= tt js2-CONST) "const ")
3081 (t
3082 (error "malformed var-decl node"))))
3083 (loop with kids = (js2-var-decl-node-kids n)
3084 with len = (length kids)
3085 for kid in kids
3086 for count from 1
3087 do
3088 (js2-print-ast kid 0)
3089 (if (< count len)
3090 (insert ", ")))))
3091
3092 (defstruct (js2-var-init-node
3093 (:include js2-node)
3094 (:constructor nil)
3095 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3096 (pos js2-ts-cursor)
3097 len target
3098 initializer)))
3099 "AST node for a variable declaration.
3100 The type field will be js2-CONST for a const decl."
3101 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3102 initializer) ; initializer expression, a `js2-node'
3103
3104 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3105 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3106
3107 (defun js2-visit-var-init-node (n v)
3108 (js2-visit-ast (js2-var-init-node-target n) v)
3109 (js2-visit-ast (js2-var-init-node-initializer n) v))
3110
3111 (defun js2-print-var-init-node (n i)
3112 (let ((pad (js2-make-pad i))
3113 (name (js2-var-init-node-target n))
3114 (init (js2-var-init-node-initializer n)))
3115 (insert pad)
3116 (js2-print-ast name 0)
3117 (when init
3118 (insert " = ")
3119 (js2-print-ast init 0))))
3120
3121 (defstruct (js2-cond-node
3122 (:include js2-node)
3123 (:constructor nil)
3124 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3125 (pos js2-ts-cursor)
3126 len
3127 test-expr
3128 true-expr
3129 false-expr
3130 q-pos c-pos)))
3131 "AST node for the ternary operator"
3132 test-expr
3133 true-expr
3134 false-expr
3135 q-pos ; buffer position of ?
3136 c-pos) ; buffer position of :
3137
3138 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3139 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3140
3141 (defun js2-visit-cond-node (n v)
3142 (js2-visit-ast (js2-cond-node-test-expr n) v)
3143 (js2-visit-ast (js2-cond-node-true-expr n) v)
3144 (js2-visit-ast (js2-cond-node-false-expr n) v))
3145
3146 (defun js2-print-cond-node (n i)
3147 (let ((pad (js2-make-pad i)))
3148 (insert pad)
3149 (js2-print-ast (js2-cond-node-test-expr n) 0)
3150 (insert " ? ")
3151 (js2-print-ast (js2-cond-node-true-expr n) 0)
3152 (insert " : ")
3153 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3154
3155 (defstruct (js2-infix-node
3156 (:include js2-node)
3157 (:constructor nil)
3158 (:constructor make-js2-infix-node (&key type
3159 (pos js2-ts-cursor)
3160 len op-pos
3161 left right)))
3162 "Represents infix expressions.
3163 Includes assignment ops like `|=', and the comma operator.
3164 The type field inherited from `js2-node' holds the operator."
3165 op-pos ; buffer position where operator begins
3166 left ; any `js2-node'
3167 right) ; any `js2-node'
3168
3169 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3170 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3171
3172 (defun js2-visit-infix-node (n v)
3173 (js2-visit-ast (js2-infix-node-left n) v)
3174 (js2-visit-ast (js2-infix-node-right n) v))
3175
3176 (defconst js2-operator-tokens
3177 (let ((table (make-hash-table :test 'eq))
3178 (tokens
3179 (list (cons js2-IN "in")
3180 (cons js2-TYPEOF "typeof")
3181 (cons js2-INSTANCEOF "instanceof")
3182 (cons js2-DELPROP "delete")
3183 (cons js2-COMMA ",")
3184 (cons js2-COLON ":")
3185 (cons js2-OR "||")
3186 (cons js2-AND "&&")
3187 (cons js2-INC "++")
3188 (cons js2-DEC "--")
3189 (cons js2-BITOR "|")
3190 (cons js2-BITXOR "^")
3191 (cons js2-BITAND "&")
3192 (cons js2-EQ "==")
3193 (cons js2-NE "!=")
3194 (cons js2-LT "<")
3195 (cons js2-LE "<=")
3196 (cons js2-GT ">")
3197 (cons js2-GE ">=")
3198 (cons js2-LSH "<<")
3199 (cons js2-RSH ">>")
3200 (cons js2-URSH ">>>")
3201 (cons js2-ADD "+") ; infix plus
3202 (cons js2-SUB "-") ; infix minus
3203 (cons js2-MUL "*")
3204 (cons js2-DIV "/")
3205 (cons js2-MOD "%")
3206 (cons js2-NOT "!")
3207 (cons js2-BITNOT "~")
3208 (cons js2-POS "+") ; unary plus
3209 (cons js2-NEG "-") ; unary minus
3210 (cons js2-TRIPLEDOT "...")
3211 (cons js2-SHEQ "===") ; shallow equality
3212 (cons js2-SHNE "!==") ; shallow inequality
3213 (cons js2-ASSIGN "=")
3214 (cons js2-ASSIGN_BITOR "|=")
3215 (cons js2-ASSIGN_BITXOR "^=")
3216 (cons js2-ASSIGN_BITAND "&=")
3217 (cons js2-ASSIGN_LSH "<<=")
3218 (cons js2-ASSIGN_RSH ">>=")
3219 (cons js2-ASSIGN_URSH ">>>=")
3220 (cons js2-ASSIGN_ADD "+=")
3221 (cons js2-ASSIGN_SUB "-=")
3222 (cons js2-ASSIGN_MUL "*=")
3223 (cons js2-ASSIGN_DIV "/=")
3224 (cons js2-ASSIGN_MOD "%="))))
3225 (loop for (k . v) in tokens do
3226 (puthash k v table))
3227 table))
3228
3229 (defun js2-print-infix-node (n i)
3230 (let* ((tt (js2-node-type n))
3231 (op (gethash tt js2-operator-tokens)))
3232 (unless op
3233 (error "unrecognized infix operator %s" (js2-node-type n)))
3234 (insert (js2-make-pad i))
3235 (js2-print-ast (js2-infix-node-left n) 0)
3236 (unless (= tt js2-COMMA)
3237 (insert " "))
3238 (insert op)
3239 (insert " ")
3240 (js2-print-ast (js2-infix-node-right n) 0)))
3241
3242 (defstruct (js2-assign-node
3243 (:include js2-infix-node)
3244 (:constructor nil)
3245 (:constructor make-js2-assign-node (&key type
3246 (pos js2-ts-cursor)
3247 len op-pos
3248 left right)))
3249 "Represents any assignment.
3250 The type field holds the actual assignment operator.")
3251
3252 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3253 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3254
3255 (defstruct (js2-unary-node
3256 (:include js2-node)
3257 (:constructor nil)
3258 (:constructor make-js2-unary-node (&key type ; required
3259 (pos js2-ts-cursor)
3260 len operand)))
3261 "AST node type for unary operator nodes.
3262 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3263 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3264 property is added if the operator follows the operand."
3265 operand) ; a `js2-node' expression
3266
3267 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3268 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3269
3270 (defun js2-visit-unary-node (n v)
3271 (js2-visit-ast (js2-unary-node-operand n) v))
3272
3273 (defun js2-print-unary-node (n i)
3274 (let* ((tt (js2-node-type n))
3275 (op (gethash tt js2-operator-tokens))
3276 (postfix (js2-node-get-prop n 'postfix)))
3277 (unless op
3278 (error "unrecognized unary operator %s" tt))
3279 (insert (js2-make-pad i))
3280 (unless postfix
3281 (insert op))
3282 (if (or (= tt js2-TYPEOF)
3283 (= tt js2-DELPROP))
3284 (insert " "))
3285 (js2-print-ast (js2-unary-node-operand n) 0)
3286 (when postfix
3287 (insert op))))
3288
3289 (defstruct (js2-let-node
3290 (:include js2-scope)
3291 (:constructor nil)
3292 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3293 (pos (js2-current-token-beg))
3294 len vars body
3295 lp rp)))
3296 "AST node for a let expression or a let statement.
3297 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3298 vars ; a `js2-var-decl-node'
3299 body ; a `js2-node' representing the expression or body block
3300 lp
3301 rp)
3302
3303 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3304 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3305
3306 (defun js2-visit-let-node (n v)
3307 (js2-visit-ast (js2-let-node-vars n) v)
3308 (js2-visit-ast (js2-let-node-body n) v))
3309
3310 (defun js2-print-let-node (n i)
3311 (insert (js2-make-pad i) "let (")
3312 (let ((p (point)))
3313 (js2-print-ast (js2-let-node-vars n) 0)
3314 (delete-region p (+ p 4)))
3315 (insert ") ")
3316 (js2-print-ast (js2-let-node-body n) i))
3317
3318 (defstruct (js2-keyword-node
3319 (:include js2-node)
3320 (:constructor nil)
3321 (:constructor make-js2-keyword-node (&key type
3322 (pos (js2-current-token-beg))
3323 (len (- js2-ts-cursor pos)))))
3324 "AST node representing a literal keyword such as `null'.
3325 Used for `null', `this', `true', `false' and `debugger'.
3326 The node type is set to js2-NULL, js2-THIS, etc.")
3327
3328 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3329 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3330
3331 (defun js2-print-keyword-node (n i)
3332 (insert (js2-make-pad i)
3333 (let ((tt (js2-node-type n)))
3334 (cond
3335 ((= tt js2-THIS) "this")
3336 ((= tt js2-NULL) "null")
3337 ((= tt js2-TRUE) "true")
3338 ((= tt js2-FALSE) "false")
3339 ((= tt js2-DEBUGGER) "debugger")
3340 (t (error "Invalid keyword literal type: %d" tt))))))
3341
3342 (defsubst js2-this-node-p (node)
3343 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3344 (eq (js2-node-type node) js2-THIS))
3345
3346 (defstruct (js2-new-node
3347 (:include js2-node)
3348 (:constructor nil)
3349 (:constructor make-js2-new-node (&key (type js2-NEW)
3350 (pos (js2-current-token-beg))
3351 len target
3352 args initializer
3353 lp rp)))
3354 "AST node for new-expression such as new Foo()."
3355 target ; an identifier or reference
3356 args ; a Lisp list of argument nodes
3357 lp ; position of left-paren, nil if omitted
3358 rp ; position of right-paren, nil if omitted
3359 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3360
3361 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3362 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3363
3364 (defun js2-visit-new-node (n v)
3365 (js2-visit-ast (js2-new-node-target n) v)
3366 (dolist (arg (js2-new-node-args n))
3367 (js2-visit-ast arg v))
3368 (js2-visit-ast (js2-new-node-initializer n) v))
3369
3370 (defun js2-print-new-node (n i)
3371 (insert (js2-make-pad i) "new ")
3372 (js2-print-ast (js2-new-node-target n))
3373 (insert "(")
3374 (js2-print-list (js2-new-node-args n))
3375 (insert ")")
3376 (when (js2-new-node-initializer n)
3377 (insert " ")
3378 (js2-print-ast (js2-new-node-initializer n))))
3379
3380 (defstruct (js2-name-node
3381 (:include js2-node)
3382 (:constructor nil)
3383 (:constructor make-js2-name-node (&key (type js2-NAME)
3384 (pos (js2-current-token-beg))
3385 (len (- js2-ts-cursor
3386 (js2-current-token-beg)))
3387 (name (js2-current-token-string)))))
3388 "AST node for a JavaScript identifier"
3389 name ; a string
3390 scope) ; a `js2-scope' (optional, used for codegen)
3391
3392 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3393 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3394
3395 (defun js2-print-name-node (n i)
3396 (insert (js2-make-pad i)
3397 (js2-name-node-name n)))
3398
3399 (defsubst js2-name-node-length (node)
3400 "Return identifier length of NODE, a `js2-name-node'.
3401 Returns 0 if NODE is nil or its identifier field is nil."
3402 (if node
3403 (length (js2-name-node-name node))
3404 0))
3405
3406 (defstruct (js2-number-node
3407 (:include js2-node)
3408 (:constructor nil)
3409 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3410 (pos (js2-current-token-beg))
3411 (len (- js2-ts-cursor
3412 (js2-current-token-beg)))
3413 (value (js2-current-token-string))
3414 (num-value (js2-token-number
3415 (js2-current-token))))))
3416 "AST node for a number literal."
3417 value ; the original string, e.g. "6.02e23"
3418 num-value) ; the parsed number value
3419
3420 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3421 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3422
3423 (defun js2-print-number-node (n i)
3424 (insert (js2-make-pad i)
3425 (number-to-string (js2-number-node-num-value n))))
3426
3427 (defstruct (js2-regexp-node
3428 (:include js2-node)
3429 (:constructor nil)
3430 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3431 (pos (js2-current-token-beg))
3432 (len (- js2-ts-cursor
3433 (js2-current-token-beg)))
3434 value flags)))
3435 "AST node for a regular expression literal."
3436 value ; the regexp string, without // delimiters
3437 flags) ; a string of flags, e.g. `mi'.
3438
3439 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3440 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3441
3442 (defun js2-print-regexp (n i)
3443 (insert (js2-make-pad i)
3444 "/"
3445 (js2-regexp-node-value n)
3446 "/")
3447 (if (js2-regexp-node-flags n)
3448 (insert (js2-regexp-node-flags n))))
3449
3450 (defstruct (js2-string-node
3451 (:include js2-node)
3452 (:constructor nil)
3453 (:constructor make-js2-string-node (&key (type js2-STRING)
3454 (pos (js2-current-token-beg))
3455 (len (- js2-ts-cursor
3456 (js2-current-token-beg)))
3457 (value (js2-current-token-string)))))
3458 "String literal.
3459 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3460 You can tell the quote type by looking at the first character."
3461 value) ; the characters of the string, including the quotes
3462
3463 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3464 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3465
3466 (defun js2-print-string-node (n i)
3467 (insert (js2-make-pad i)
3468 (js2-node-string n)))
3469
3470 (defstruct (js2-array-node
3471 (:include js2-node)
3472 (:constructor nil)
3473 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3474 (pos js2-ts-cursor)
3475 len elems)))
3476 "AST node for an array literal."
3477 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3478
3479 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3480 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3481
3482 (defun js2-visit-array-node (n v)
3483 (dolist (e (js2-array-node-elems n))
3484 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3485
3486 (defun js2-print-array-node (n i)
3487 (insert (js2-make-pad i) "[")
3488 (let ((elems (js2-array-node-elems n)))
3489 (js2-print-list elems)
3490 (when (and elems (null (car (last elems))))
3491 (insert ",")))
3492 (insert "]"))
3493
3494 (defstruct (js2-object-node
3495 (:include js2-node)
3496 (:constructor nil)
3497 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3498 (pos js2-ts-cursor)
3499 len
3500 elems)))
3501 "AST node for an object literal expression.
3502 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3503 The latter represents abbreviation in destructuring expressions."
3504 elems)
3505
3506 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3507 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3508
3509 (defun js2-visit-object-node (n v)
3510 (dolist (e (js2-object-node-elems n))
3511 (js2-visit-ast e v)))
3512
3513 (defun js2-print-object-node (n i)
3514 (insert (js2-make-pad i) "{")
3515 (js2-print-list (js2-object-node-elems n))
3516 (insert "}"))
3517
3518 (defstruct (js2-object-prop-node
3519 (:include js2-infix-node)
3520 (:constructor nil)
3521 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3522 (pos js2-ts-cursor)
3523 len left
3524 right op-pos)))
3525 "AST node for an object literal prop:value entry.
3526 The `left' field is the property: a name node, string node or number node.
3527 The `right' field is a `js2-node' representing the initializer value.")
3528
3529 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3530 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3531
3532 (defun js2-print-object-prop-node (n i)
3533 (insert (js2-make-pad i))
3534 (js2-print-ast (js2-object-prop-node-left n) 0)
3535 (insert ": ")
3536 (js2-print-ast (js2-object-prop-node-right n) 0))
3537
3538 (defstruct (js2-getter-setter-node
3539 (:include js2-infix-node)
3540 (:constructor nil)
3541 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3542 (pos js2-ts-cursor)
3543 len left right)))
3544 "AST node for a getter/setter property in an object literal.
3545 The `left' field is the `js2-name-node' naming the getter/setter prop.
3546 The `right' field is always an anonymous `js2-function-node' with a node
3547 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3548
3549 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3550 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3551
3552 (defun js2-print-getter-setter (n i)
3553 (let ((pad (js2-make-pad i))
3554 (left (js2-getter-setter-node-left n))
3555 (right (js2-getter-setter-node-right n)))
3556 (insert pad)
3557 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3558 (js2-print-ast left 0)
3559 (js2-print-ast right 0)))
3560
3561 (defstruct (js2-prop-get-node
3562 (:include js2-infix-node)
3563 (:constructor nil)
3564 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3565 (pos js2-ts-cursor)
3566 len left right)))
3567 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3568
3569 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3570 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3571
3572 (defun js2-visit-prop-get-node (n v)
3573 (js2-visit-ast (js2-prop-get-node-left n) v)
3574 (js2-visit-ast (js2-prop-get-node-right n) v))
3575
3576 (defun js2-print-prop-get-node (n i)
3577 (insert (js2-make-pad i))
3578 (js2-print-ast (js2-prop-get-node-left n) 0)
3579 (insert ".")
3580 (js2-print-ast (js2-prop-get-node-right n) 0))
3581
3582 (defstruct (js2-elem-get-node
3583 (:include js2-node)
3584 (:constructor nil)
3585 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3586 (pos js2-ts-cursor)
3587 len target element
3588 lb rb)))
3589 "AST node for an array index expression such as foo[bar]."
3590 target ; a `js2-node' - the expression preceding the "."
3591 element ; a `js2-node' - the expression in brackets
3592 lb ; position of left-bracket, nil if omitted
3593 rb) ; position of right-bracket, nil if omitted
3594
3595 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3596 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3597
3598 (defun js2-visit-elem-get-node (n v)
3599 (js2-visit-ast (js2-elem-get-node-target n) v)
3600 (js2-visit-ast (js2-elem-get-node-element n) v))
3601
3602 (defun js2-print-elem-get-node (n i)
3603 (insert (js2-make-pad i))
3604 (js2-print-ast (js2-elem-get-node-target n) 0)
3605 (insert "[")
3606 (js2-print-ast (js2-elem-get-node-element n) 0)
3607 (insert "]"))
3608
3609 (defstruct (js2-call-node
3610 (:include js2-node)
3611 (:constructor nil)
3612 (:constructor make-js2-call-node (&key (type js2-CALL)
3613 (pos js2-ts-cursor)
3614 len target args
3615 lp rp)))
3616 "AST node for a JavaScript function call."
3617 target ; a `js2-node' evaluating to the function to call
3618 args ; a Lisp list of `js2-node' arguments
3619 lp ; position of open-paren, or nil if missing
3620 rp) ; position of close-paren, or nil if missing
3621
3622 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3623 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3624
3625 (defun js2-visit-call-node (n v)
3626 (js2-visit-ast (js2-call-node-target n) v)
3627 (dolist (arg (js2-call-node-args n))
3628 (js2-visit-ast arg v)))
3629
3630 (defun js2-print-call-node (n i)
3631 (insert (js2-make-pad i))
3632 (js2-print-ast (js2-call-node-target n) 0)
3633 (insert "(")
3634 (js2-print-list (js2-call-node-args n))
3635 (insert ")"))
3636
3637 (defstruct (js2-yield-node
3638 (:include js2-node)
3639 (:constructor nil)
3640 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3641 (pos js2-ts-cursor)
3642 len value star-p)))
3643 "AST node for yield statement or expression."
3644 star-p ; whether it's yield*
3645 value) ; optional: value to be yielded
3646
3647 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3648 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3649
3650 (defun js2-visit-yield-node (n v)
3651 (js2-visit-ast (js2-yield-node-value n) v))
3652
3653 (defun js2-print-yield-node (n i)
3654 (insert (js2-make-pad i))
3655 (insert "yield")
3656 (when (js2-yield-node-star-p n)
3657 (insert "*"))
3658 (when (js2-yield-node-value n)
3659 (insert " ")
3660 (js2-print-ast (js2-yield-node-value n) 0)))
3661
3662 (defstruct (js2-paren-node
3663 (:include js2-node)
3664 (:constructor nil)
3665 (:constructor make-js2-paren-node (&key (type js2-LP)
3666 (pos js2-ts-cursor)
3667 len expr)))
3668 "AST node for a parenthesized expression.
3669 In particular, used when the parens are syntactically optional,
3670 as opposed to required parens such as those enclosing an if-conditional."
3671 expr) ; `js2-node'
3672
3673 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3674 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3675
3676 (defun js2-visit-paren-node (n v)
3677 (js2-visit-ast (js2-paren-node-expr n) v))
3678
3679 (defun js2-print-paren-node (n i)
3680 (insert (js2-make-pad i))
3681 (insert "(")
3682 (js2-print-ast (js2-paren-node-expr n) 0)
3683 (insert ")"))
3684
3685 (defstruct (js2-comp-node
3686 (:include js2-scope)
3687 (:constructor nil)
3688 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3689 (pos js2-ts-cursor)
3690 len result
3691 loops filters
3692 form)))
3693 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3694 result ; result expression (just after left-bracket)
3695 loops ; a Lisp list of `js2-comp-loop-node'
3696 filters ; a Lisp list of guard/filter expressions
3697 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3698 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3699 )
3700
3701 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3702 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3703
3704 (defun js2-visit-comp-node (n v)
3705 (js2-visit-ast (js2-comp-node-result n) v)
3706 (dolist (l (js2-comp-node-loops n))
3707 (js2-visit-ast l v))
3708 (dolist (f (js2-comp-node-filters n))
3709 (js2-visit-ast f v)))
3710
3711 (defun js2-print-comp-node (n i)
3712 (let ((pad (js2-make-pad i))
3713 (result (js2-comp-node-result n))
3714 (loops (js2-comp-node-loops n))
3715 (filters (js2-comp-node-filters n))
3716 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3717 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3718 (insert pad (if gen-p "(" "["))
3719 (when legacy-p
3720 (js2-print-ast result 0))
3721 (dolist (l loops)
3722 (when legacy-p
3723 (insert " "))
3724 (js2-print-ast l 0)
3725 (unless legacy-p
3726 (insert " ")))
3727 (dolist (f filters)
3728 (when legacy-p
3729 (insert " "))
3730 (insert "if (")
3731 (js2-print-ast f 0)
3732 (insert ")")
3733 (unless legacy-p
3734 (insert " ")))
3735 (unless legacy-p
3736 (js2-print-ast result 0))
3737 (insert (if gen-p ")" "]"))))
3738
3739 (defstruct (js2-comp-loop-node
3740 (:include js2-for-in-node)
3741 (:constructor nil)
3742 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3743 (pos js2-ts-cursor)
3744 len iterator
3745 object in-pos
3746 foreach-p
3747 each-pos
3748 forof-p
3749 lp rp)))
3750 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3751
3752 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3753 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3754
3755 (defun js2-visit-comp-loop (n v)
3756 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3757 (js2-visit-ast (js2-comp-loop-node-object n) v))
3758
3759 (defun js2-print-comp-loop (n _i)
3760 (insert "for ")
3761 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3762 (insert "(")
3763 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3764 (insert (if (js2-comp-loop-node-forof-p n)
3765 " of " " in "))
3766 (js2-print-ast (js2-comp-loop-node-object n) 0)
3767 (insert ")"))
3768
3769 (defstruct (js2-empty-expr-node
3770 (:include js2-node)
3771 (:constructor nil)
3772 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3773 (pos (js2-current-token-beg))
3774 len)))
3775 "AST node for an empty expression.")
3776
3777 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3778 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3779
3780 (defstruct (js2-xml-node
3781 (:include js2-block-node)
3782 (:constructor nil)
3783 (:constructor make-js2-xml-node (&key (type js2-XML)
3784 (pos (js2-current-token-beg))
3785 len kids)))
3786 "AST node for initial parse of E4X literals.
3787 The kids field is a list of XML fragments, each a `js2-string-node' or
3788 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3789
3790 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3791 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3792
3793 (defun js2-print-xml-node (n i)
3794 (dolist (kid (js2-xml-node-kids n))
3795 (js2-print-ast kid i)))
3796
3797 (defstruct (js2-xml-js-expr-node
3798 (:include js2-xml-node)
3799 (:constructor nil)
3800 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3801 (pos js2-ts-cursor)
3802 len expr)))
3803 "AST node for an embedded JavaScript {expression} in an E4X literal.
3804 The start and end fields correspond to the curly-braces."
3805 expr) ; a `js2-expr-node' of some sort
3806
3807 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3808 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3809
3810 (defun js2-visit-xml-js-expr (n v)
3811 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3812
3813 (defun js2-print-xml-js-expr (n i)
3814 (insert (js2-make-pad i))
3815 (insert "{")
3816 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3817 (insert "}"))
3818
3819 (defstruct (js2-xml-dot-query-node
3820 (:include js2-infix-node)
3821 (:constructor nil)
3822 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3823 (pos js2-ts-cursor)
3824 op-pos len left
3825 right rp)))
3826 "AST node for an E4X foo.(bar) filter expression.
3827 Note that the left-paren is automatically the character immediately
3828 following the dot (.) in the operator. No whitespace is permitted
3829 between the dot and the lp by the scanner."
3830 rp)
3831
3832 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3833 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3834
3835 (defun js2-print-xml-dot-query (n i)
3836 (insert (js2-make-pad i))
3837 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3838 (insert ".(")
3839 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3840 (insert ")"))
3841
3842 (defstruct (js2-xml-ref-node
3843 (:include js2-node)
3844 (:constructor nil)) ; abstract
3845 "Base type for E4X XML attribute-access or property-get expressions.
3846 Such expressions can take a variety of forms. The general syntax has
3847 three parts:
3848
3849 - (optional) an @ (specifying an attribute access)
3850 - (optional) a namespace (a `js2-name-node') and double-colon
3851 - (required) either a `js2-name-node' or a bracketed [expression]
3852
3853 The property-name expressions (examples: ns::name, @name) are
3854 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3855 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3856
3857 This node type (or more specifically, its subclasses) will sometimes
3858 be the right-hand child of a `js2-prop-get-node' or a
3859 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3860 The `js2-xml-ref-node' may also be a standalone primary expression with
3861 no explicit target, which is valid in certain expression contexts such as
3862
3863 company..employee.(@id < 100)
3864
3865 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3866 expression whose parent is a `js2-xml-dot-query-node'."
3867 namespace
3868 at-pos
3869 colon-pos)
3870
3871 (defsubst js2-xml-ref-node-attr-access-p (node)
3872 "Return non-nil if this expression began with an @-token."
3873 (and (numberp (js2-xml-ref-node-at-pos node))
3874 (plusp (js2-xml-ref-node-at-pos node))))
3875
3876 (defstruct (js2-xml-prop-ref-node
3877 (:include js2-xml-ref-node)
3878 (:constructor nil)
3879 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3880 (pos (js2-current-token-beg))
3881 len propname
3882 namespace at-pos
3883 colon-pos)))
3884 "AST node for an E4X XML [expr] property-ref expression.
3885 The JavaScript syntax is an optional @, an optional ns::, and a name.
3886
3887 [ '@' ] [ name '::' ] name
3888
3889 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3890 @ns::*, @*::attr, @*::*, and @*.
3891
3892 The node starts at the @ token, if present. Otherwise it starts at the
3893 namespace name. The node bounds extend through the closing right-bracket,
3894 or if it is missing due to a syntax error, through the end of the index
3895 expression."
3896 propname)
3897
3898 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3899 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3900
3901 (defun js2-visit-xml-prop-ref-node (n v)
3902 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3903 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3904
3905 (defun js2-print-xml-prop-ref-node (n i)
3906 (insert (js2-make-pad i))
3907 (if (js2-xml-ref-node-attr-access-p n)
3908 (insert "@"))
3909 (when (js2-xml-prop-ref-node-namespace n)
3910 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3911 (insert "::"))
3912 (if (js2-xml-prop-ref-node-propname n)
3913 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3914
3915 (defstruct (js2-xml-elem-ref-node
3916 (:include js2-xml-ref-node)
3917 (:constructor nil)
3918 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3919 (pos (js2-current-token-beg))
3920 len expr lb rb
3921 namespace at-pos
3922 colon-pos)))
3923 "AST node for an E4X XML [expr] member-ref expression.
3924 Syntax:
3925
3926 [ '@' ] [ name '::' ] '[' expr ']'
3927
3928 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3929
3930 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3931 is not a legal E4X XML element-ref expression, since it's already used
3932 for standard JavaScript element-get array indexing. Hence, a
3933 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3934 non-nil namespace node, or both.
3935
3936 The node starts at the @ token, if present. Otherwise it starts
3937 at the namespace name. The node bounds extend through the closing
3938 right-bracket, or if it is missing due to a syntax error, through the
3939 end of the index expression."
3940 expr ; the bracketed index expression
3941 lb
3942 rb)
3943
3944 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3945 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3946
3947 (defun js2-visit-xml-elem-ref-node (n v)
3948 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3949 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3950
3951 (defun js2-print-xml-elem-ref-node (n i)
3952 (insert (js2-make-pad i))
3953 (if (js2-xml-ref-node-attr-access-p n)
3954 (insert "@"))
3955 (when (js2-xml-elem-ref-node-namespace n)
3956 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3957 (insert "::"))
3958 (insert "[")
3959 (if (js2-xml-elem-ref-node-expr n)
3960 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3961 (insert "]"))
3962
3963 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3964
3965 (defstruct (js2-xml-start-tag-node
3966 (:include js2-xml-node)
3967 (:constructor nil)
3968 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3969 (pos js2-ts-cursor)
3970 len name attrs kids
3971 empty-p)))
3972 "AST node for an XML start-tag. Not currently used.
3973 The `kids' field is a Lisp list of child content nodes."
3974 name ; a `js2-xml-name-node'
3975 attrs ; a Lisp list of `js2-xml-attr-node'
3976 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3977
3978 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3979 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3980
3981 (defun js2-visit-xml-start-tag (n v)
3982 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3983 (dolist (attr (js2-xml-start-tag-node-attrs n))
3984 (js2-visit-ast attr v))
3985 (js2-visit-block n v))
3986
3987 (defun js2-print-xml-start-tag (n i)
3988 (insert (js2-make-pad i) "<")
3989 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3990 (when (js2-xml-start-tag-node-attrs n)
3991 (insert " ")
3992 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3993 (insert ">"))
3994
3995 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3996 ;; and add the end-tag to the kids list of the parent as well.
3997 (defstruct (js2-xml-end-tag-node
3998 (:include js2-xml-node)
3999 (:constructor nil)
4000 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4001 (pos js2-ts-cursor)
4002 len name)))
4003 "AST node for an XML end-tag. Not currently used."
4004 name) ; a `js2-xml-name-node'
4005
4006 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4007 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4008
4009 (defun js2-visit-xml-end-tag (n v)
4010 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4011
4012 (defun js2-print-xml-end-tag (n i)
4013 (insert (js2-make-pad i))
4014 (insert "</")
4015 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4016 (insert ">"))
4017
4018 (defstruct (js2-xml-name-node
4019 (:include js2-xml-node)
4020 (:constructor nil)
4021 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4022 (pos js2-ts-cursor)
4023 len namespace kids)))
4024 "AST node for an E4X XML name. Not currently used.
4025 Any XML name can be qualified with a namespace, hence the namespace field.
4026 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4027 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4028 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4029 namespace) ; a `js2-string-node'
4030
4031 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4032 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4033
4034 (defun js2-visit-xml-name-node (n v)
4035 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4036
4037 (defun js2-print-xml-name-node (n i)
4038 (insert (js2-make-pad i))
4039 (when (js2-xml-name-node-namespace n)
4040 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4041 (insert "::"))
4042 (dolist (kid (js2-xml-name-node-kids n))
4043 (js2-print-ast kid 0)))
4044
4045 (defstruct (js2-xml-pi-node
4046 (:include js2-xml-node)
4047 (:constructor nil)
4048 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4049 (pos js2-ts-cursor)
4050 len name attrs)))
4051 "AST node for an E4X XML processing instruction. Not currently used."
4052 name ; a `js2-xml-name-node'
4053 attrs) ; a list of `js2-xml-attr-node'
4054
4055 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4056 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4057
4058 (defun js2-visit-xml-pi-node (n v)
4059 (js2-visit-ast (js2-xml-pi-node-name n) v)
4060 (dolist (attr (js2-xml-pi-node-attrs n))
4061 (js2-visit-ast attr v)))
4062
4063 (defun js2-print-xml-pi-node (n i)
4064 (insert (js2-make-pad i) "<?")
4065 (js2-print-ast (js2-xml-pi-node-name n))
4066 (when (js2-xml-pi-node-attrs n)
4067 (insert " ")
4068 (js2-print-list (js2-xml-pi-node-attrs n)))
4069 (insert "?>"))
4070
4071 (defstruct (js2-xml-cdata-node
4072 (:include js2-xml-node)
4073 (:constructor nil)
4074 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4075 (pos js2-ts-cursor)
4076 len content)))
4077 "AST node for a CDATA escape section. Not currently used."
4078 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4079
4080 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4081 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4082
4083 (defun js2-visit-xml-cdata-node (n v)
4084 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4085
4086 (defun js2-print-xml-cdata-node (n i)
4087 (insert (js2-make-pad i))
4088 (js2-print-ast (js2-xml-cdata-node-content n)))
4089
4090 (defstruct (js2-xml-attr-node
4091 (:include js2-xml-node)
4092 (:constructor nil)
4093 (:constructor make-js2-attr-node (&key (type js2-XML)
4094 (pos js2-ts-cursor)
4095 len name value
4096 eq-pos quote-type)))
4097 "AST node representing a foo='bar' XML attribute value. Not yet used."
4098 name ; a `js2-xml-name-node'
4099 value ; a `js2-xml-name-node'
4100 eq-pos ; buffer position of "=" sign
4101 quote-type) ; 'single or 'double
4102
4103 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4104 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4105
4106 (defun js2-visit-xml-attr-node (n v)
4107 (js2-visit-ast (js2-xml-attr-node-name n) v)
4108 (js2-visit-ast (js2-xml-attr-node-value n) v))
4109
4110 (defun js2-print-xml-attr-node (n i)
4111 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4112 "'"
4113 "\"")))
4114 (insert (js2-make-pad i))
4115 (js2-print-ast (js2-xml-attr-node-name n) 0)
4116 (insert "=" quote)
4117 (js2-print-ast (js2-xml-attr-node-value n) 0)
4118 (insert quote)))
4119
4120 (defstruct (js2-xml-text-node
4121 (:include js2-xml-node)
4122 (:constructor nil)
4123 (:constructor make-js2-text-node (&key (type js2-XML)
4124 (pos js2-ts-cursor)
4125 len content)))
4126 "AST node for an E4X XML text node. Not currently used."
4127 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4128
4129 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4130 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4131
4132 (defun js2-visit-xml-text-node (n v)
4133 (js2-visit-ast (js2-xml-text-node-content n) v))
4134
4135 (defun js2-print-xml-text-node (n i)
4136 (insert (js2-make-pad i))
4137 (dolist (kid (js2-xml-text-node-content n))
4138 (js2-print-ast kid)))
4139
4140 (defstruct (js2-xml-comment-node
4141 (:include js2-xml-node)
4142 (:constructor nil)
4143 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4144 (pos js2-ts-cursor)
4145 len)))
4146 "AST node for E4X XML comment. Not currently used.")
4147
4148 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4149 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4150
4151 (defun js2-print-xml-comment (n i)
4152 (insert (js2-make-pad i)
4153 (js2-node-string n)))
4154
4155 ;;; Node utilities
4156
4157 (defsubst js2-node-line (n)
4158 "Fetch the source line number at the start of node N.
4159 This is O(n) in the length of the source buffer; use prudently."
4160 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4161
4162 (defsubst js2-block-node-kid (n i)
4163 "Return child I of node N, or nil if there aren't that many."
4164 (nth i (js2-block-node-kids n)))
4165
4166 (defsubst js2-block-node-first (n)
4167 "Return first child of block node N, or nil if there is none."
4168 (first (js2-block-node-kids n)))
4169
4170 (defun js2-node-root (n)
4171 "Return the root of the AST containing N.
4172 If N has no parent pointer, returns N."
4173 (let ((parent (js2-node-parent n)))
4174 (if parent
4175 (js2-node-root parent)
4176 n)))
4177
4178 (defsubst js2-node-short-name (n)
4179 "Return the short name of node N as a string, e.g. `js2-if-node'."
4180 (substring (symbol-name (aref n 0))
4181 (length "cl-struct-")))
4182
4183 (defun js2-node-child-list (node)
4184 "Return the child list for NODE, a Lisp list of nodes.
4185 Works for block nodes, array nodes, obj literals, funarg lists,
4186 var decls and try nodes (for catch clauses). Note that you should call
4187 `js2-block-node-kids' on the function body for the body statements.
4188 Returns nil for zero-length child lists or unsupported nodes."
4189 (cond
4190 ((js2-function-node-p node)
4191 (js2-function-node-params node))
4192 ((js2-block-node-p node)
4193 (js2-block-node-kids node))
4194 ((js2-try-node-p node)
4195 (js2-try-node-catch-clauses node))
4196 ((js2-array-node-p node)
4197 (js2-array-node-elems node))
4198 ((js2-object-node-p node)
4199 (js2-object-node-elems node))
4200 ((js2-call-node-p node)
4201 (js2-call-node-args node))
4202 ((js2-new-node-p node)
4203 (js2-new-node-args node))
4204 ((js2-var-decl-node-p node)
4205 (js2-var-decl-node-kids node))
4206 (t
4207 nil)))
4208
4209 (defun js2-node-set-child-list (node kids)
4210 "Set the child list for NODE to KIDS."
4211 (cond
4212 ((js2-function-node-p node)
4213 (setf (js2-function-node-params node) kids))
4214 ((js2-block-node-p node)
4215 (setf (js2-block-node-kids node) kids))
4216 ((js2-try-node-p node)
4217 (setf (js2-try-node-catch-clauses node) kids))
4218 ((js2-array-node-p node)
4219 (setf (js2-array-node-elems node) kids))
4220 ((js2-object-node-p node)
4221 (setf (js2-object-node-elems node) kids))
4222 ((js2-call-node-p node)
4223 (setf (js2-call-node-args node) kids))
4224 ((js2-new-node-p node)
4225 (setf (js2-new-node-args node) kids))
4226 ((js2-var-decl-node-p node)
4227 (setf (js2-var-decl-node-kids node) kids))
4228 (t
4229 (error "Unsupported node type: %s" (js2-node-short-name node))))
4230 kids)
4231
4232 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4233 (defconst js2-paren-expr-nodes
4234 '(cl-struct-js2-comp-loop-node
4235 cl-struct-js2-comp-node
4236 cl-struct-js2-call-node
4237 cl-struct-js2-catch-node
4238 cl-struct-js2-do-node
4239 cl-struct-js2-elem-get-node
4240 cl-struct-js2-for-in-node
4241 cl-struct-js2-for-node
4242 cl-struct-js2-function-node
4243 cl-struct-js2-if-node
4244 cl-struct-js2-let-node
4245 cl-struct-js2-new-node
4246 cl-struct-js2-paren-node
4247 cl-struct-js2-switch-node
4248 cl-struct-js2-while-node
4249 cl-struct-js2-with-node
4250 cl-struct-js2-xml-dot-query-node)
4251 "Node types that can have a parenthesized child expression.
4252 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4253
4254 (defsubst js2-paren-expr-node-p (node)
4255 "Return t for nodes that typically have a parenthesized child expression.
4256 Useful for computing the indentation anchors for arg-lists and conditions.
4257 Note that it may return a false positive, for instance when NODE is
4258 a `js2-new-node' and there are no arguments or parentheses."
4259 (memq (aref node 0) js2-paren-expr-nodes))
4260
4261 ;; Fake polymorphism... yech.
4262 (defun js2-node-lp (node)
4263 "Return relative left-paren position for NODE, if applicable.
4264 For `js2-elem-get-node' structs, returns left-bracket position.
4265 Note that the position may be nil in the case of a parse error."
4266 (cond
4267 ((js2-elem-get-node-p node)
4268 (js2-elem-get-node-lb node))
4269 ((js2-loop-node-p node)
4270 (js2-loop-node-lp node))
4271 ((js2-function-node-p node)
4272 (js2-function-node-lp node))
4273 ((js2-if-node-p node)
4274 (js2-if-node-lp node))
4275 ((js2-new-node-p node)
4276 (js2-new-node-lp node))
4277 ((js2-call-node-p node)
4278 (js2-call-node-lp node))
4279 ((js2-paren-node-p node)
4280 0)
4281 ((js2-switch-node-p node)
4282 (js2-switch-node-lp node))
4283 ((js2-catch-node-p node)
4284 (js2-catch-node-lp node))
4285 ((js2-let-node-p node)
4286 (js2-let-node-lp node))
4287 ((js2-comp-node-p node)
4288 0)
4289 ((js2-with-node-p node)
4290 (js2-with-node-lp node))
4291 ((js2-xml-dot-query-node-p node)
4292 (1+ (js2-infix-node-op-pos node)))
4293 (t
4294 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4295
4296 ;; Fake polymorphism... blech.
4297 (defun js2-node-rp (node)
4298 "Return relative right-paren position for NODE, if applicable.
4299 For `js2-elem-get-node' structs, returns right-bracket position.
4300 Note that the position may be nil in the case of a parse error."
4301 (cond
4302 ((js2-elem-get-node-p node)
4303 (js2-elem-get-node-rb node))
4304 ((js2-loop-node-p node)
4305 (js2-loop-node-rp node))
4306 ((js2-function-node-p node)
4307 (js2-function-node-rp node))
4308 ((js2-if-node-p node)
4309 (js2-if-node-rp node))
4310 ((js2-new-node-p node)
4311 (js2-new-node-rp node))
4312 ((js2-call-node-p node)
4313 (js2-call-node-rp node))
4314 ((js2-paren-node-p node)
4315 (1- (js2-node-len node)))
4316 ((js2-switch-node-p node)
4317 (js2-switch-node-rp node))
4318 ((js2-catch-node-p node)
4319 (js2-catch-node-rp node))
4320 ((js2-let-node-p node)
4321 (js2-let-node-rp node))
4322 ((js2-comp-node-p node)
4323 (1- (js2-node-len node)))
4324 ((js2-with-node-p node)
4325 (js2-with-node-rp node))
4326 ((js2-xml-dot-query-node-p node)
4327 (1+ (js2-xml-dot-query-node-rp node)))
4328 (t
4329 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4330
4331 (defsubst js2-node-first-child (node)
4332 "Return the first element of `js2-node-child-list' for NODE."
4333 (car (js2-node-child-list node)))
4334
4335 (defsubst js2-node-last-child (node)
4336 "Return the last element of `js2-node-last-child' for NODE."
4337 (car (last (js2-node-child-list node))))
4338
4339 (defun js2-node-prev-sibling (node)
4340 "Return the previous statement in parent.
4341 Works for parents supported by `js2-node-child-list'.
4342 Returns nil if NODE is not in the parent, or PARENT is
4343 not a supported node, or if NODE is the first child."
4344 (let* ((p (js2-node-parent node))
4345 (kids (js2-node-child-list p))
4346 (sib (car kids)))
4347 (while (and kids
4348 (not (eq node (cadr kids))))
4349 (setq kids (cdr kids)
4350 sib (car kids)))
4351 sib))
4352
4353 (defun js2-node-next-sibling (node)
4354 "Return the next statement in parent block.
4355 Returns nil if NODE is not in the block, or PARENT is not
4356 a block node, or if NODE is the last statement."
4357 (let* ((p (js2-node-parent node))
4358 (kids (js2-node-child-list p)))
4359 (while (and kids
4360 (not (eq node (car kids))))
4361 (setq kids (cdr kids)))
4362 (cadr kids)))
4363
4364 (defun js2-node-find-child-before (pos parent &optional after)
4365 "Find the last child that starts before POS in parent.
4366 If AFTER is non-nil, returns first child starting after POS.
4367 POS is an absolute buffer position. PARENT is any node
4368 supported by `js2-node-child-list'.
4369 Returns nil if no applicable child is found."
4370 (let ((kids (if (js2-function-node-p parent)
4371 (js2-block-node-kids (js2-function-node-body parent))
4372 (js2-node-child-list parent)))
4373 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4374 (js2-function-node-body parent)
4375 parent)))
4376 kid result fn
4377 (continue t))
4378 (setq fn (if after '>= '<))
4379 (while (and kids continue)
4380 (setq kid (car kids))
4381 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4382 (setq result kid
4383 continue (not after))
4384 (setq continue after))
4385 (setq kids (cdr kids)))
4386 result))
4387
4388 (defun js2-node-find-child-after (pos parent)
4389 "Find first child that starts after POS in parent.
4390 POS is an absolute buffer position. PARENT is any node
4391 supported by `js2-node-child-list'.
4392 Returns nil if no applicable child is found."
4393 (js2-node-find-child-before pos parent 'after))
4394
4395 (defun js2-node-replace-child (pos parent new-node)
4396 "Replace node at index POS in PARENT with NEW-NODE.
4397 Only works for parents supported by `js2-node-child-list'."
4398 (let ((kids (js2-node-child-list parent))
4399 (i 0))
4400 (while (< i pos)
4401 (setq kids (cdr kids)
4402 i (1+ i)))
4403 (setcar kids new-node)
4404 (js2-node-add-children parent new-node)))
4405
4406 (defun js2-node-buffer (n)
4407 "Return the buffer associated with AST N.
4408 Returns nil if the buffer is not set as a property on the root
4409 node, or if parent links were not recorded during parsing."
4410 (let ((root (js2-node-root n)))
4411 (and root
4412 (js2-ast-root-p root)
4413 (js2-ast-root-buffer root))))
4414
4415 (defun js2-block-node-push (n kid)
4416 "Push js2-node KID onto the end of js2-block-node N's child list.
4417 KID is always added to the -end- of the kids list.
4418 Function also calls `js2-node-add-children' to add the parent link."
4419 (let ((kids (js2-node-child-list n)))
4420 (if kids
4421 (setcdr kids (nconc (cdr kids) (list kid)))
4422 (js2-node-set-child-list n (list kid)))
4423 (js2-node-add-children n kid)))
4424
4425 (defun js2-node-string (node)
4426 (with-current-buffer (or (js2-node-buffer node)
4427 (error "No buffer available for node %s" node))
4428 (let ((pos (js2-node-abs-pos node)))
4429 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4430
4431 ;; Container for storing the node we're looking for in a traversal.
4432 (js2-deflocal js2-discovered-node nil)
4433
4434 ;; Keep track of absolute node position during traversals.
4435 (js2-deflocal js2-visitor-offset nil)
4436
4437 (js2-deflocal js2-node-search-point nil)
4438
4439 (when js2-mode-dev-mode-p
4440 (defun js2-find-node-at-point ()
4441 (interactive)
4442 (let ((node (js2-node-at-point)))
4443 (message "%s" (or node "No node found at point"))))
4444 (defun js2-node-name-at-point ()
4445 (interactive)
4446 (let ((node (js2-node-at-point)))
4447 (message "%s" (if node
4448 (js2-node-short-name node)
4449 "No node found at point.")))))
4450
4451 (defun js2-node-at-point (&optional pos skip-comments)
4452 "Return AST node at POS, a buffer position, defaulting to current point.
4453 The `js2-mode-ast' variable must be set to the current parse tree.
4454 Signals an error if the AST (`js2-mode-ast') is nil.
4455 Always returns a node - if it can't find one, it returns the root.
4456 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4457 (let ((ast js2-mode-ast)
4458 result)
4459 (unless ast
4460 (error "No JavaScript AST available"))
4461 ;; Look through comments first, since they may be inside nodes that
4462 ;; would otherwise report a match.
4463 (setq pos (or pos (point))
4464 result (if (> pos (js2-node-abs-end ast))
4465 ast
4466 (if (not skip-comments)
4467 (js2-comment-at-point pos))))
4468 (unless result
4469 (setq js2-discovered-node nil
4470 js2-visitor-offset 0
4471 js2-node-search-point pos)
4472 (unwind-protect
4473 (catch 'js2-visit-done
4474 (js2-visit-ast ast #'js2-node-at-point-visitor))
4475 (setq js2-visitor-offset nil
4476 js2-node-search-point nil))
4477 (setq result js2-discovered-node))
4478 ;; may have found a comment beyond end of last child node,
4479 ;; since visiting the ast-root looks at the comment-list last.
4480 (if (and skip-comments
4481 (js2-comment-node-p result))
4482 (setq result nil))
4483 (or result js2-mode-ast)))
4484
4485 (defun js2-node-at-point-visitor (node end-p)
4486 (let ((rel-pos (js2-node-pos node))
4487 abs-pos
4488 abs-end
4489 (point js2-node-search-point))
4490 (cond
4491 (end-p
4492 ;; this evaluates to a non-nil return value, even if it's zero
4493 (decf js2-visitor-offset rel-pos))
4494 ;; we already looked for comments before visiting, and don't want them now
4495 ((js2-comment-node-p node)
4496 nil)
4497 (t
4498 (setq abs-pos (incf js2-visitor-offset rel-pos)
4499 ;; we only want to use the node if the point is before
4500 ;; the last character position in the node, so we decrement
4501 ;; the absolute end by 1.
4502 abs-end (+ abs-pos (js2-node-len node) -1))
4503 (cond
4504 ;; If this node starts after search-point, stop the search.
4505 ((> abs-pos point)
4506 (throw 'js2-visit-done nil))
4507 ;; If this node ends before the search-point, don't check kids.
4508 ((> point abs-end)
4509 nil)
4510 (t
4511 ;; Otherwise point is within this node, possibly in a child.
4512 (setq js2-discovered-node node)
4513 t)))))) ; keep processing kids to look for more specific match
4514
4515 (defsubst js2-block-comment-p (node)
4516 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4517 (and (js2-comment-node-p node)
4518 (memq (js2-comment-node-format node) '(jsdoc block))))
4519
4520 ;; TODO: put the comments in a vector and binary-search them instead
4521 (defun js2-comment-at-point (&optional pos)
4522 "Look through scanned comment nodes for one containing POS.
4523 POS is a buffer position that defaults to current point.
4524 Function returns nil if POS was not in any comment node."
4525 (let ((ast js2-mode-ast)
4526 (x (or pos (point)))
4527 beg end)
4528 (unless ast
4529 (error "No JavaScript AST available"))
4530 (catch 'done
4531 ;; Comments are stored in lexical order.
4532 (dolist (comment (js2-ast-root-comments ast) nil)
4533 (setq beg (js2-node-abs-pos comment)
4534 end (+ beg (js2-node-len comment)))
4535 (if (and (>= x beg)
4536 (<= x end))
4537 (throw 'done comment))))))
4538
4539 (defun js2-mode-find-parent-fn (node)
4540 "Find function enclosing NODE.
4541 Returns nil if NODE is not inside a function."
4542 (setq node (js2-node-parent node))
4543 (while (and node (not (js2-function-node-p node)))
4544 (setq node (js2-node-parent node)))
4545 (and (js2-function-node-p node) node))
4546
4547 (defun js2-mode-find-enclosing-fn (node)
4548 "Find function or root enclosing NODE."
4549 (if (js2-ast-root-p node)
4550 node
4551 (setq node (js2-node-parent node))
4552 (while (not (or (js2-ast-root-p node)
4553 (js2-function-node-p node)))
4554 (setq node (js2-node-parent node)))
4555 node))
4556
4557 (defun js2-mode-find-enclosing-node (beg end)
4558 "Find node fully enclosing BEG and END."
4559 (let ((node (js2-node-at-point beg))
4560 pos
4561 (continue t))
4562 (while continue
4563 (if (or (js2-ast-root-p node)
4564 (and
4565 (<= (setq pos (js2-node-abs-pos node)) beg)
4566 (>= (+ pos (js2-node-len node)) end)))
4567 (setq continue nil)
4568 (setq node (js2-node-parent node))))
4569 node))
4570
4571 (defun js2-node-parent-script-or-fn (node)
4572 "Find script or function immediately enclosing NODE.
4573 If NODE is the ast-root, returns nil."
4574 (if (js2-ast-root-p node)
4575 nil
4576 (setq node (js2-node-parent node))
4577 (while (and node (not (or (js2-function-node-p node)
4578 (js2-script-node-p node))))
4579 (setq node (js2-node-parent node)))
4580 node))
4581
4582 (defun js2-node-is-descendant (node ancestor)
4583 "Return t if NODE is a descendant of ANCESTOR."
4584 (while (and node
4585 (not (eq node ancestor)))
4586 (setq node (js2-node-parent node)))
4587 node)
4588
4589 ;;; visitor infrastructure
4590
4591 (defun js2-visit-none (_node _callback)
4592 "Visitor for AST node that have no node children."
4593 nil)
4594
4595 (defun js2-print-none (_node _indent)
4596 "Visitor for AST node with no printed representation.")
4597
4598 (defun js2-print-body (node indent)
4599 "Print a statement, or a block without braces."
4600 (if (js2-block-node-p node)
4601 (dolist (kid (js2-block-node-kids node))
4602 (js2-print-ast kid indent))
4603 (js2-print-ast node indent)))
4604
4605 (defun js2-print-list (args &optional delimiter)
4606 (loop with len = (length args)
4607 for arg in args
4608 for count from 1
4609 do
4610 (when arg (js2-print-ast arg 0))
4611 (if (< count len)
4612 (insert (or delimiter ", ")))))
4613
4614 (defun js2-print-tree (ast)
4615 "Prints an AST to the current buffer.
4616 Makes `js2-ast-parent-nodes' available to the printer functions."
4617 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4618 (js2-print-ast ast)))
4619
4620 (defun js2-print-ast (node &optional indent)
4621 "Helper function for printing AST nodes.
4622 Requires `js2-ast-parent-nodes' to be non-nil.
4623 You should use `js2-print-tree' instead of this function."
4624 (let ((printer (get (aref node 0) 'js2-printer))
4625 (i (or indent 0)))
4626 ;; TODO: wedge comments in here somewhere
4627 (if printer
4628 (funcall printer node i))))
4629
4630 (defconst js2-side-effecting-tokens
4631 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4632 (dolist (tt (list js2-ASSIGN
4633 js2-ASSIGN_ADD
4634 js2-ASSIGN_BITAND
4635 js2-ASSIGN_BITOR
4636 js2-ASSIGN_BITXOR
4637 js2-ASSIGN_DIV
4638 js2-ASSIGN_LSH
4639 js2-ASSIGN_MOD
4640 js2-ASSIGN_MUL
4641 js2-ASSIGN_RSH
4642 js2-ASSIGN_SUB
4643 js2-ASSIGN_URSH
4644 js2-BLOCK
4645 js2-BREAK
4646 js2-CALL
4647 js2-CATCH
4648 js2-CATCH_SCOPE
4649 js2-CONST
4650 js2-CONTINUE
4651 js2-DEBUGGER
4652 js2-DEC
4653 js2-DELPROP
4654 js2-DEL_REF
4655 js2-DO
4656 js2-ELSE
4657 js2-EMPTY
4658 js2-ENTERWITH
4659 js2-EXPORT
4660 js2-EXPR_RESULT
4661 js2-FINALLY
4662 js2-FOR
4663 js2-FUNCTION
4664 js2-GOTO
4665 js2-IF
4666 js2-IFEQ
4667 js2-IFNE
4668 js2-IMPORT
4669 js2-INC
4670 js2-JSR
4671 js2-LABEL
4672 js2-LEAVEWITH
4673 js2-LET
4674 js2-LETEXPR
4675 js2-LOCAL_BLOCK
4676 js2-LOOP
4677 js2-NEW
4678 js2-REF_CALL
4679 js2-RETHROW
4680 js2-RETURN
4681 js2-RETURN_RESULT
4682 js2-SEMI
4683 js2-SETELEM
4684 js2-SETELEM_OP
4685 js2-SETNAME
4686 js2-SETPROP
4687 js2-SETPROP_OP
4688 js2-SETVAR
4689 js2-SET_REF
4690 js2-SET_REF_OP
4691 js2-SWITCH
4692 js2-TARGET
4693 js2-THROW
4694 js2-TRY
4695 js2-VAR
4696 js2-WHILE
4697 js2-WITH
4698 js2-WITHEXPR
4699 js2-YIELD))
4700 (aset tokens tt t))
4701 (if js2-instanceof-has-side-effects
4702 (aset tokens js2-INSTANCEOF t))
4703 tokens))
4704
4705 (defun js2-node-has-side-effects (node)
4706 "Return t if NODE has side effects."
4707 (when node ; makes it easier to handle malformed expressions
4708 (let ((tt (js2-node-type node)))
4709 (cond
4710 ;; This doubtless needs some work, since EXPR_VOID is used
4711 ;; in several ways in Rhino and I may not have caught them all.
4712 ;; I'll wait for people to notice incorrect warnings.
4713 ((and (= tt js2-EXPR_VOID)
4714 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4715 (let ((expr (js2-expr-stmt-node-expr node)))
4716 (or (js2-node-has-side-effects expr)
4717 (when (js2-string-node-p expr)
4718 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4719 ((= tt js2-COMMA)
4720 (js2-node-has-side-effects (js2-infix-node-right node)))
4721 ((or (= tt js2-AND)
4722 (= tt js2-OR))
4723 (or (js2-node-has-side-effects (js2-infix-node-right node))
4724 (js2-node-has-side-effects (js2-infix-node-left node))))
4725 ((= tt js2-HOOK)
4726 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4727 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4728 ((js2-paren-node-p node)
4729 (js2-node-has-side-effects (js2-paren-node-expr node)))
4730 ((= tt js2-ERROR) ; avoid cascaded error messages
4731 nil)
4732 (t
4733 (aref js2-side-effecting-tokens tt))))))
4734
4735 (defconst js2-stmt-node-types
4736 (list js2-BLOCK
4737 js2-BREAK
4738 js2-CONTINUE
4739 js2-DEFAULT ; e4x "default xml namespace" statement
4740 js2-DO
4741 js2-EXPR_RESULT
4742 js2-EXPR_VOID
4743 js2-FOR
4744 js2-IF
4745 js2-RETURN
4746 js2-SWITCH
4747 js2-THROW
4748 js2-TRY
4749 js2-WHILE
4750 js2-WITH)
4751 "Node types that only appear in statement contexts.
4752 The list does not include nodes that always appear as the child
4753 of another specific statement type, such as switch-cases,
4754 catch and finally blocks, and else-clauses. The list also excludes
4755 nodes like yield, let and var, which may appear in either expression
4756 or statement context, and in the latter context always have a
4757 `js2-expr-stmt-node' parent. Finally, the list does not include
4758 functions or scripts, which are treated separately from statements
4759 by the JavaScript parser and runtime.")
4760
4761 (defun js2-stmt-node-p (node)
4762 "Heuristic for figuring out if NODE is a statement.
4763 Some node types can appear in either an expression context or a
4764 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4765 For these node types in a statement context, the parent will be a
4766 `js2-expr-stmt-node'.
4767 Functions aren't included in the check."
4768 (memq (js2-node-type node) js2-stmt-node-types))
4769
4770 (defun js2-mode-find-first-stmt (node)
4771 "Search upward starting from NODE looking for a statement.
4772 For purposes of this function, a `js2-function-node' counts."
4773 (while (not (or (js2-stmt-node-p node)
4774 (js2-function-node-p node)))
4775 (setq node (js2-node-parent node)))
4776 node)
4777
4778 (defun js2-node-parent-stmt (node)
4779 "Return the node's first ancestor that is a statement.
4780 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4781 appearing in a statement context will have a parent that is a
4782 `js2-expr-stmt-node' that will be returned by this function."
4783 (let ((parent (js2-node-parent node)))
4784 (if (or (null parent)
4785 (js2-stmt-node-p parent)
4786 (and (js2-function-node-p parent)
4787 (not (eq (js2-function-node-form parent)
4788 'FUNCTION_EXPRESSION))))
4789 parent
4790 (js2-node-parent-stmt parent))))
4791
4792 ;; In the Mozilla Rhino sources, Roshan James writes:
4793 ;; Does consistent-return analysis on the function body when strict mode is
4794 ;; enabled.
4795 ;;
4796 ;; function (x) { return (x+1) }
4797 ;;
4798 ;; is ok, but
4799 ;;
4800 ;; function (x) { if (x < 0) return (x+1); }
4801 ;;
4802 ;; is not because the function can potentially return a value when the
4803 ;; condition is satisfied and if not, the function does not explicitly
4804 ;; return a value.
4805 ;;
4806 ;; This extends to checking mismatches such as "return" and "return <value>"
4807 ;; used in the same function. Warnings are not emitted if inconsistent
4808 ;; returns exist in code that can be statically shown to be unreachable.
4809 ;; Ex.
4810 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4811 ;;
4812 ;; emits no warning. However if the loop had a break statement, then a
4813 ;; warning would be emitted.
4814 ;;
4815 ;; The consistency analysis looks at control structures such as loops, ifs,
4816 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4817 ;; warns the user about an inconsistent set of termination possibilities.
4818 ;;
4819 ;; These flags enumerate the possible ways a statement/function can
4820 ;; terminate. These flags are used by endCheck() and by the Parser to
4821 ;; detect inconsistent return usage.
4822 ;;
4823 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4824 ;; able to execute (example: throw, continue)
4825 ;;
4826 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4827 ;; next one. Statement such as return dont. A compound statement may have
4828 ;; some branch that drops off control to the next statement.
4829 ;;
4830 ;; END_RETURNS indicates that the statement can return with no value.
4831 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4832 ;;
4833 ;; A compound statement such as
4834 ;; if (condition) {
4835 ;; return value;
4836 ;; }
4837 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4838
4839 (defconst js2-END_UNREACHED 0)
4840 (defconst js2-END_DROPS_OFF 1)
4841 (defconst js2-END_RETURNS 2)
4842 (defconst js2-END_RETURNS_VALUE 4)
4843 (defconst js2-END_YIELDS 8)
4844
4845 (defun js2-has-consistent-return-usage (node)
4846 "Check that every return usage in a function body is consistent.
4847 Returns t if the function satisfies strict mode requirement."
4848 (let ((n (js2-end-check node)))
4849 ;; either it doesn't return a value in any branch...
4850 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4851 ;; or it returns a value (or is unreached) at every branch
4852 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4853 js2-END_RETURNS
4854 js2-END_YIELDS)))))
4855
4856 (defun js2-end-check-if (node)
4857 "Ensure that return usage in then/else blocks is consistent.
4858 If there is no else block, then the return statement can fall through.
4859 Returns logical OR of END_* flags"
4860 (let ((th (js2-if-node-then-part node))
4861 (el (js2-if-node-else-part node)))
4862 (if (null th)
4863 js2-END_UNREACHED
4864 (logior (js2-end-check th) (if el
4865 (js2-end-check el)
4866 js2-END_DROPS_OFF)))))
4867
4868 (defun js2-end-check-switch (node)
4869 "Consistency of return statements is checked between the case statements.
4870 If there is no default, then the switch can fall through. If there is a
4871 default, we check to see if all code paths in the default return or if
4872 there is a code path that can fall through.
4873 Returns logical OR of END_* flags."
4874 (let ((rv js2-END_UNREACHED)
4875 default-case)
4876 ;; examine the cases
4877 (catch 'break
4878 (dolist (c (js2-switch-node-cases node))
4879 (if (js2-case-node-expr c)
4880 (js2-set-flag rv (js2-end-check-block c))
4881 (setq default-case c)
4882 (throw 'break nil))))
4883 ;; we don't care how the cases drop into each other
4884 (js2-clear-flag rv js2-END_DROPS_OFF)
4885 ;; examine the default
4886 (js2-set-flag rv (if default-case
4887 (js2-end-check default-case)
4888 js2-END_DROPS_OFF))
4889 rv))
4890
4891 (defun js2-end-check-try (node)
4892 "If the block has a finally, return consistency is checked in the
4893 finally block. If all code paths in the finally return, then the
4894 returns in the try-catch blocks don't matter. If there is a code path
4895 that does not return or if there is no finally block, the returns
4896 of the try and catch blocks are checked for mismatch.
4897 Returns logical OR of END_* flags."
4898 (let ((finally (js2-try-node-finally-block node))
4899 rv)
4900 ;; check the finally if it exists
4901 (setq rv (if finally
4902 (js2-end-check (js2-finally-node-body finally))
4903 js2-END_DROPS_OFF))
4904 ;; If the finally block always returns, then none of the returns
4905 ;; in the try or catch blocks matter.
4906 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4907 (js2-clear-flag rv js2-END_DROPS_OFF)
4908 ;; examine the try block
4909 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4910 ;; check each catch block
4911 (dolist (cb (js2-try-node-catch-clauses node))
4912 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4913 rv))
4914
4915 (defun js2-end-check-loop (node)
4916 "Return statement in the loop body must be consistent.
4917 The default assumption for any kind of a loop is that it will eventually
4918 terminate. The only exception is a loop with a constant true condition.
4919 Code that follows such a loop is examined only if one can determine
4920 statically that there is a break out of the loop.
4921
4922 for(... ; ... ; ...) {}
4923 for(... in ... ) {}
4924 while(...) { }
4925 do { } while(...)
4926
4927 Returns logical OR of END_* flags."
4928 (let ((rv (js2-end-check (js2-loop-node-body node)))
4929 (condition (cond
4930 ((js2-while-node-p node)
4931 (js2-while-node-condition node))
4932 ((js2-do-node-p node)
4933 (js2-do-node-condition node))
4934 ((js2-for-node-p node)
4935 (js2-for-node-condition node)))))
4936
4937 ;; check to see if the loop condition is always true
4938 (if (and condition
4939 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4940 (js2-clear-flag rv js2-END_DROPS_OFF))
4941
4942 ;; look for effect of breaks
4943 (js2-set-flag rv (js2-node-get-prop node
4944 'CONTROL_BLOCK_PROP
4945 js2-END_UNREACHED))
4946 rv))
4947
4948 (defun js2-end-check-block (node)
4949 "A general block of code is examined statement by statement.
4950 If any statement (even a compound one) returns in all branches, then
4951 subsequent statements are not examined.
4952 Returns logical OR of END_* flags."
4953 (let* ((rv js2-END_DROPS_OFF)
4954 (kids (js2-block-node-kids node))
4955 (n (car kids)))
4956 ;; Check each statment. If the statement can continue onto the next
4957 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4958 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4959 (js2-clear-flag rv js2-END_DROPS_OFF)
4960 (js2-set-flag rv (js2-end-check n))
4961 (setq kids (cdr kids)
4962 n (car kids)))
4963 rv))
4964
4965 (defun js2-end-check-label (node)
4966 "A labeled statement implies that there may be a break to the label.
4967 The function processes the labeled statement and then checks the
4968 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4969 particular label.
4970 Returns logical OR of END_* flags."
4971 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4972 (logior rv (js2-node-get-prop node
4973 'CONTROL_BLOCK_PROP
4974 js2-END_UNREACHED))))
4975
4976 (defun js2-end-check-break (node)
4977 "When a break is encountered annotate the statement being broken
4978 out of by setting its CONTROL_BLOCK_PROP property.
4979 Returns logical OR of END_* flags."
4980 (and (js2-break-node-target node)
4981 (js2-node-set-prop (js2-break-node-target node)
4982 'CONTROL_BLOCK_PROP
4983 js2-END_DROPS_OFF))
4984 js2-END_UNREACHED)
4985
4986 (defun js2-end-check (node)
4987 "Examine the body of a function, doing a basic reachability analysis.
4988 Returns a combination of flags END_* flags that indicate
4989 how the function execution can terminate. These constitute only the
4990 pessimistic set of termination conditions. It is possible that at
4991 runtime certain code paths will never be actually taken. Hence this
4992 analysis will flag errors in cases where there may not be errors.
4993 Returns logical OR of END_* flags"
4994 (let (kid)
4995 (cond
4996 ((js2-break-node-p node)
4997 (js2-end-check-break node))
4998 ((js2-expr-stmt-node-p node)
4999 (if (setq kid (js2-expr-stmt-node-expr node))
5000 (js2-end-check kid)
5001 js2-END_DROPS_OFF))
5002 ((or (js2-continue-node-p node)
5003 (js2-throw-node-p node))
5004 js2-END_UNREACHED)
5005 ((js2-return-node-p node)
5006 (if (setq kid (js2-return-node-retval node))
5007 js2-END_RETURNS_VALUE
5008 js2-END_RETURNS))
5009 ((js2-loop-node-p node)
5010 (js2-end-check-loop node))
5011 ((js2-switch-node-p node)
5012 (js2-end-check-switch node))
5013 ((js2-labeled-stmt-node-p node)
5014 (js2-end-check-label node))
5015 ((js2-if-node-p node)
5016 (js2-end-check-if node))
5017 ((js2-try-node-p node)
5018 (js2-end-check-try node))
5019 ((js2-block-node-p node)
5020 (if (null (js2-block-node-kids node))
5021 js2-END_DROPS_OFF
5022 (js2-end-check-block node)))
5023 ((js2-yield-node-p node)
5024 js2-END_YIELDS)
5025 (t
5026 js2-END_DROPS_OFF))))
5027
5028 (defun js2-always-defined-boolean-p (node)
5029 "Check if NODE always evaluates to true or false in boolean context.
5030 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5031 nor always false."
5032 (let ((tt (js2-node-type node))
5033 num)
5034 (cond
5035 ((or (= tt js2-FALSE) (= tt js2-NULL))
5036 'ALWAYS_FALSE)
5037 ((= tt js2-TRUE)
5038 'ALWAYS_TRUE)
5039 ((= tt js2-NUMBER)
5040 (setq num (js2-number-node-num-value node))
5041 (if (and (not (eq num 0.0e+NaN))
5042 (not (zerop num)))
5043 'ALWAYS_TRUE
5044 'ALWAYS_FALSE))
5045 (t
5046 nil))))
5047
5048 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5049 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5050
5051 (defvar js2-tokens nil
5052 "List of all defined token names.") ; initialized in `js2-token-names'
5053
5054 (defconst js2-token-names
5055 (let* ((names (make-vector js2-num-tokens -1))
5056 (case-fold-search nil) ; only match js2-UPPER_CASE
5057 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5058 (loop for sym in syms
5059 for i from 0
5060 do
5061 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5062 (not (boundp sym)))
5063 (aset names (symbol-value sym) ; code, e.g. 152
5064 (downcase
5065 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5066 (push sym js2-tokens)))
5067 names)
5068 "Vector mapping int values to token string names, sans `js2-' prefix.")
5069
5070 (defun js2-tt-name (tok)
5071 "Return a string name for TOK, a token symbol or code.
5072 Signals an error if it's not a recognized token."
5073 (let ((code tok))
5074 (if (symbolp tok)
5075 (setq code (symbol-value tok)))
5076 (if (eq code -1)
5077 "ERROR"
5078 (if (and (numberp code)
5079 (not (minusp code))
5080 (< code js2-num-tokens))
5081 (aref js2-token-names code)
5082 (error "Invalid token: %s" code)))))
5083
5084 (defsubst js2-tt-sym (tok)
5085 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5086 (intern (js2-tt-name tok)))
5087
5088 (defconst js2-token-codes
5089 (let ((table (make-hash-table :test 'eq :size 256)))
5090 (loop for name across js2-token-names
5091 for sym = (intern (concat "js2-" (upcase name)))
5092 do
5093 (puthash sym (symbol-value sym) table))
5094 ;; clean up a few that are "wrong" in Rhino's token codes
5095 (puthash 'js2-DELETE js2-DELPROP table)
5096 table)
5097 "Hashtable mapping token type symbols to their bytecodes.")
5098
5099 (defsubst js2-tt-code (sym)
5100 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5101 (or (gethash sym js2-token-codes)
5102 (error "Invalid token symbol: %s " sym))) ; signal code bug
5103
5104 (defun js2-report-scan-error (msg &optional no-throw beg len)
5105 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5106 (js2-report-error msg nil
5107 (or beg (js2-current-token-beg))
5108 (or len (js2-current-token-len)))
5109 (unless no-throw
5110 (throw 'return js2-ERROR)))
5111
5112 (defun js2-set-string-from-buffer (token)
5113 "Set `string' and `end' slots for TOKEN, return the string."
5114 (setf (js2-token-end token) js2-ts-cursor
5115 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5116
5117 ;; TODO: could potentially avoid a lot of consing by allocating a
5118 ;; char buffer the way Rhino does.
5119 (defsubst js2-add-to-string (c)
5120 (push c js2-ts-string-buffer))
5121
5122 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5123 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5124 ;; any other character: when it's not part of the current token, we
5125 ;; unget it, allowing it to be read again by the following call.
5126 (defsubst js2-unget-char ()
5127 (decf js2-ts-cursor))
5128
5129 ;; Rhino distinguishes \r and \n line endings. We don't need to
5130 ;; because we only scan from Emacs buffers, which always use \n.
5131 (defun js2-get-char ()
5132 "Read and return the next character from the input buffer.
5133 Increments `js2-ts-lineno' if the return value is a newline char.
5134 Updates `js2-ts-cursor' to the point after the returned char.
5135 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5136 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5137 (let (c)
5138 ;; check for end of buffer
5139 (if (>= js2-ts-cursor (point-max))
5140 (setq js2-ts-hit-eof t
5141 js2-ts-cursor (1+ js2-ts-cursor)
5142 c js2-EOF_CHAR) ; return value
5143 ;; otherwise read next char
5144 (setq c (char-before (incf js2-ts-cursor)))
5145 ;; if we read a newline, update counters
5146 (if (= c ?\n)
5147 (setq js2-ts-line-start js2-ts-cursor
5148 js2-ts-lineno (1+ js2-ts-lineno)))
5149 ;; TODO: skip over format characters
5150 c)))
5151
5152 (defun js2-read-unicode-escape ()
5153 "Read a \\uNNNN sequence from the input.
5154 Assumes the ?\ and ?u have already been read.
5155 Returns the unicode character, or nil if it wasn't a valid character.
5156 Doesn't change the values of any scanner variables."
5157 ;; I really wish I knew a better way to do this, but I can't
5158 ;; find the Emacs function that takes a 16-bit int and converts
5159 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5160 ;; Have to first check that it's 4 hex characters or it may stop
5161 ;; the read early.
5162 (ignore-errors
5163 (let ((s (buffer-substring-no-properties js2-ts-cursor
5164 (+ 4 js2-ts-cursor))))
5165 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5166 (read (concat "?\\u" s))))))
5167
5168 (defun js2-match-char (test)
5169 "Consume and return next character if it matches TEST, a character.
5170 Returns nil and consumes nothing if TEST is not the next character."
5171 (let ((c (js2-get-char)))
5172 (if (eq c test)
5173 t
5174 (js2-unget-char)
5175 nil)))
5176
5177 (defun js2-peek-char ()
5178 (prog1
5179 (js2-get-char)
5180 (js2-unget-char)))
5181
5182 (defun js2-identifier-start-p (c)
5183 "Is C a valid start to an ES5 Identifier?
5184 See http://es5.github.io/#x7.6"
5185 (or
5186 (memq c '(?$ ?_))
5187 (memq (get-char-code-property c 'general-category)
5188 ;; Letters
5189 '(Lu Ll Lt Lm Lo Nl))))
5190
5191 (defun js2-identifier-part-p (c)
5192 "Is C a valid part of an ES5 Identifier?
5193 See http://es5.github.io/#x7.6"
5194 (or
5195 (memq c '(?$ ?_ ?\u200c ?\u200d))
5196 (memq (get-char-code-property c 'general-category)
5197 '(;; Letters
5198 Lu Ll Lt Lm Lo Nl
5199 ;; Combining Marks
5200 Mn Mc
5201 ;; Digits
5202 Nd
5203 ;; Connector Punctuation
5204 Pc))))
5205
5206 (defun js2-alpha-p (c)
5207 (cond ((and (<= ?A c) (<= c ?Z)) t)
5208 ((and (<= ?a c) (<= c ?z)) t)
5209 (t nil)))
5210
5211 (defsubst js2-digit-p (c)
5212 (and (<= ?0 c) (<= c ?9)))
5213
5214 (defun js2-js-space-p (c)
5215 (if (<= c 127)
5216 (memq c '(#x20 #x9 #xB #xC #xD))
5217 (or
5218 (eq c #xA0)
5219 ;; TODO: change this nil to check for Unicode space character
5220 nil)))
5221
5222 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5223
5224 (defun js2-skip-line ()
5225 "Skip to end of line."
5226 (while (not (memq (js2-get-char) js2-eol-chars)))
5227 (js2-unget-char)
5228 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5229 (setq js2-token-end js2-ts-cursor))
5230
5231 (defun js2-init-scanner (&optional buf line)
5232 "Create token stream for BUF starting on LINE.
5233 BUF defaults to `current-buffer' and LINE defaults to 1.
5234
5235 A buffer can only have one scanner active at a time, which yields
5236 dramatically simpler code than using a defstruct. If you need to
5237 have simultaneous scanners in a buffer, copy the regions to scan
5238 into temp buffers."
5239 (with-current-buffer (or buf (current-buffer))
5240 (setq js2-ts-dirty-line nil
5241 js2-ts-hit-eof nil
5242 js2-ts-line-start 0
5243 js2-ts-lineno (or line 1)
5244 js2-ts-line-end-char -1
5245 js2-ts-cursor (point-min)
5246 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5247 js2-ti-tokens-cursor 0
5248 js2-ti-lookahead 0
5249 js2-ts-is-xml-attribute nil
5250 js2-ts-xml-is-tag-content nil
5251 js2-ts-xml-open-tags-count 0
5252 js2-ts-string-buffer nil)))
5253
5254 ;; This function uses the cached op, string and number fields in
5255 ;; TokenStream; if getToken has been called since the passed token
5256 ;; was scanned, the op or string printed may be incorrect.
5257 (defun js2-token-to-string (token)
5258 ;; Not sure where this function is used in Rhino. Not tested.
5259 (if (not js2-debug-print-trees)
5260 ""
5261 (let ((name (js2-tt-name token)))
5262 (cond
5263 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5264 (concat name " `" (js2-current-token-string) "'"))
5265 ((eq token js2-NUMBER)
5266 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5267 (t
5268 name)))))
5269
5270 (defconst js2-keywords
5271 '(break
5272 case catch const continue
5273 debugger default delete do
5274 else enum
5275 false finally for function
5276 if in instanceof import
5277 let
5278 new null
5279 return
5280 switch
5281 this throw true try typeof
5282 var void
5283 while with
5284 yield))
5285
5286 ;; Token names aren't exactly the same as the keywords, unfortunately.
5287 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5288 (defconst js2-kwd-tokens
5289 (let ((table (make-vector js2-num-tokens nil))
5290 (tokens
5291 (list js2-BREAK
5292 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5293 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5294 js2-ELSE
5295 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5296 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5297 js2-LET
5298 js2-NEW js2-NULL
5299 js2-RETURN
5300 js2-SWITCH
5301 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5302 js2-VAR
5303 js2-WHILE js2-WITH
5304 js2-YIELD)))
5305 (dolist (i tokens)
5306 (aset table i 'font-lock-keyword-face))
5307 (aset table js2-STRING 'font-lock-string-face)
5308 (aset table js2-REGEXP 'font-lock-string-face)
5309 (aset table js2-COMMENT 'font-lock-comment-face)
5310 (aset table js2-THIS 'font-lock-builtin-face)
5311 (aset table js2-VOID 'font-lock-constant-face)
5312 (aset table js2-NULL 'font-lock-constant-face)
5313 (aset table js2-TRUE 'font-lock-constant-face)
5314 (aset table js2-FALSE 'font-lock-constant-face)
5315 (aset table js2-NOT 'font-lock-negation-char-face)
5316 table)
5317 "Vector whose values are non-nil for tokens that are keywords.
5318 The values are default faces to use for highlighting the keywords.")
5319
5320 ;; FIXME: Support strict mode-only future reserved words, after we know
5321 ;; which parts scopes are in strict mode, and which are not.
5322 (defconst js2-reserved-words '(class export extends import super)
5323 "Future reserved keywords in ECMAScript 5.")
5324
5325 (defconst js2-keyword-names
5326 (let ((table (make-hash-table :test 'equal)))
5327 (loop for k in js2-keywords
5328 do (puthash
5329 (symbol-name k) ; instanceof
5330 (intern (concat "js2-"
5331 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5332 table))
5333 table)
5334 "JavaScript keywords by name, mapped to their symbols.")
5335
5336 (defconst js2-reserved-word-names
5337 (let ((table (make-hash-table :test 'equal)))
5338 (loop for k in js2-reserved-words
5339 do
5340 (puthash (symbol-name k) 'js2-RESERVED table))
5341 table)
5342 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5343
5344 (defun js2-collect-string (buf)
5345 "Convert BUF, a list of chars, to a string.
5346 Reverses BUF before converting."
5347 (if buf
5348 (apply #'string (nreverse buf))
5349 ""))
5350
5351 (defun js2-string-to-keyword (s)
5352 "Return token for S, a string, if S is a keyword or reserved word.
5353 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5354 (or (gethash s js2-keyword-names)
5355 (gethash s js2-reserved-word-names)))
5356
5357 (defsubst js2-ts-set-char-token-bounds (token)
5358 "Used when next token is one character."
5359 (setf (js2-token-beg token) (1- js2-ts-cursor)
5360 (js2-token-end token) js2-ts-cursor))
5361
5362 (defsubst js2-ts-return (token type)
5363 "Update the `end' and `type' slots of TOKEN,
5364 then throw `return' with value TYPE."
5365 (setf (js2-token-end token) js2-ts-cursor
5366 (js2-token-type token) type)
5367 (throw 'return type))
5368
5369 (defun js2-x-digit-to-int (c accumulator)
5370 "Build up a hex number.
5371 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5372 corresponding number. Otherwise return -1."
5373 (catch 'return
5374 (catch 'check
5375 ;; Use 0..9 < A..Z < a..z
5376 (cond
5377 ((<= c ?9)
5378 (decf c ?0)
5379 (if (<= 0 c)
5380 (throw 'check nil)))
5381 ((<= c ?F)
5382 (when (<= ?A c)
5383 (decf c (- ?A 10))
5384 (throw 'check nil)))
5385 ((<= c ?f)
5386 (when (<= ?a c)
5387 (decf c (- ?a 10))
5388 (throw 'check nil))))
5389 (throw 'return -1))
5390 (logior c (lsh accumulator 4))))
5391
5392 (defun js2-get-token ()
5393 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5394 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5395 next saved token.
5396
5397 This function will not return a newline (js2-EOL) - instead, it
5398 gobbles newlines until it finds a non-newline token. Call
5399 `js2-peek-token-or-eol' when you care about newlines.
5400
5401 This function will also not return a js2-COMMENT. Instead, it
5402 records comments found in `js2-scanned-comments'. If the token
5403 returned by this function immediately follows a jsdoc comment,
5404 the token is flagged as such."
5405 (if (zerop js2-ti-lookahead)
5406 (js2-get-token-internal)
5407 (decf js2-ti-lookahead)
5408 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5409 (let ((tt (js2-current-token-type)))
5410 (assert (not (= tt js2-EOL)))
5411 tt)))
5412
5413 (defun js2-unget-token ()
5414 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5415 (incf js2-ti-lookahead)
5416 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5417
5418 (defun js2-get-token-internal ()
5419 (let* ((token (js2-get-token-internal-1)) ; call scanner
5420 (tt (js2-token-type token))
5421 saw-eol
5422 face)
5423 ;; process comments
5424 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5425 (if (= tt js2-EOL)
5426 (setq saw-eol t)
5427 (setq saw-eol nil)
5428 (when js2-record-comments
5429 (js2-record-comment token)))
5430 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5431 (setq token (js2-get-token-internal-1) ; call scanner again
5432 tt (js2-token-type token)))
5433
5434 (when saw-eol
5435 (setf (js2-token-follows-eol-p token) t))
5436
5437 ;; perform lexical fontification as soon as token is scanned
5438 (when js2-parse-ide-mode
5439 (cond
5440 ((minusp tt)
5441 (js2-record-face 'js2-error token))
5442 ((setq face (aref js2-kwd-tokens tt))
5443 (js2-record-face face token))
5444 ((and (= tt js2-NAME)
5445 (equal (js2-token-string token) "undefined"))
5446 (js2-record-face 'font-lock-constant-face token))))
5447 tt))
5448
5449 (defun js2-get-token-internal-1 ()
5450 "Return next JavaScript token type, an int such as js2-RETURN.
5451 During operation, creates an instance of `js2-token' struct, sets
5452 its relevant fields and puts it into `js2-ti-tokens'."
5453 (let (c c1 identifier-start is-unicode-escape-start
5454 contains-escape escape-val str result base
5455 quote-char val look-for-slash continue tt
5456 (token (js2-new-token 0)))
5457 (setq
5458 tt
5459 (catch 'return
5460 (while t
5461 ;; Eat whitespace, possibly sensitive to newlines.
5462 (setq continue t)
5463 (while continue
5464 (setq c (js2-get-char))
5465 (cond
5466 ((eq c js2-EOF_CHAR)
5467 (js2-unget-char)
5468 (js2-ts-set-char-token-bounds token)
5469 (throw 'return js2-EOF))
5470 ((eq c ?\n)
5471 (js2-ts-set-char-token-bounds token)
5472 (setq js2-ts-dirty-line nil)
5473 (throw 'return js2-EOL))
5474 ((not (js2-js-space-p c))
5475 (if (/= c ?-) ; in case end of HTML comment
5476 (setq js2-ts-dirty-line t))
5477 (setq continue nil))))
5478 ;; Assume the token will be 1 char - fixed up below.
5479 (js2-ts-set-char-token-bounds token)
5480 (when (eq c ?@)
5481 (throw 'return js2-XMLATTR))
5482 ;; identifier/keyword/instanceof?
5483 ;; watch out for starting with a <backslash>
5484 (cond
5485 ((eq c ?\\)
5486 (setq c (js2-get-char))
5487 (if (eq c ?u)
5488 (setq identifier-start t
5489 is-unicode-escape-start t
5490 js2-ts-string-buffer nil)
5491 (setq identifier-start nil)
5492 (js2-unget-char)
5493 (setq c ?\\)))
5494 (t
5495 (when (setq identifier-start (js2-identifier-start-p c))
5496 (setq js2-ts-string-buffer nil)
5497 (js2-add-to-string c))))
5498 (when identifier-start
5499 (setq contains-escape is-unicode-escape-start)
5500 (catch 'break
5501 (while t
5502 (if is-unicode-escape-start
5503 ;; strictly speaking we should probably push-back
5504 ;; all the bad characters if the <backslash>uXXXX
5505 ;; sequence is malformed. But since there isn't a
5506 ;; correct context(is there?) for a bad Unicode
5507 ;; escape sequence in an identifier, we can report
5508 ;; an error here.
5509 (progn
5510 (setq escape-val 0)
5511 (dotimes (_ 4)
5512 (setq c (js2-get-char)
5513 escape-val (js2-x-digit-to-int c escape-val))
5514 ;; Next check takes care of c < 0 and bad escape
5515 (if (minusp escape-val)
5516 (throw 'break nil)))
5517 (if (minusp escape-val)
5518 (js2-report-scan-error "msg.invalid.escape" t))
5519 (js2-add-to-string escape-val)
5520 (setq is-unicode-escape-start nil))
5521 (setq c (js2-get-char))
5522 (cond
5523 ((eq c ?\\)
5524 (setq c (js2-get-char))
5525 (if (eq c ?u)
5526 (setq is-unicode-escape-start t
5527 contains-escape t)
5528 (js2-report-scan-error "msg.illegal.character" t)))
5529 (t
5530 (if (or (eq c js2-EOF_CHAR)
5531 (not (js2-identifier-part-p c)))
5532 (throw 'break nil))
5533 (js2-add-to-string c))))))
5534 (js2-unget-char)
5535 (setf str (js2-collect-string js2-ts-string-buffer)
5536 (js2-token-end token) js2-ts-cursor)
5537 ;; FIXME: Invalid in ES5 and ES6, see
5538 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5539 ;; Probably should just drop this conditional.
5540 (unless contains-escape
5541 ;; OPT we shouldn't have to make a string (object!) to
5542 ;; check if it's a keyword.
5543 ;; Return the corresponding token if it's a keyword
5544 (when (setq result (js2-string-to-keyword str))
5545 (if (and (< js2-language-version 170)
5546 (memq result '(js2-LET js2-YIELD)))
5547 ;; LET and YIELD are tokens only in 1.7 and later
5548 (setq result 'js2-NAME))
5549 (when (eq result 'js2-RESERVED)
5550 (setf (js2-token-string token) str))
5551 (throw 'return (js2-tt-code result))))
5552 ;; If we want to intern these as Rhino does, just use (intern str)
5553 (setf (js2-token-string token) str)
5554 (throw 'return js2-NAME)) ; end identifier/kwd check
5555 ;; is it a number?
5556 (when (or (js2-digit-p c)
5557 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5558 (setq js2-ts-string-buffer nil
5559 base 10)
5560 (when (eq c ?0)
5561 (setq c (js2-get-char))
5562 (cond
5563 ((or (eq c ?x) (eq c ?X))
5564 (setq base 16)
5565 (setq c (js2-get-char)))
5566 ((and (or (eq c ?b) (eq c ?B))
5567 (>= js2-language-version 200))
5568 (setq base 2)
5569 (setq c (js2-get-char)))
5570 ((and (or (eq c ?o) (eq c ?O))
5571 (>= js2-language-version 200))
5572 (setq base 8)
5573 (setq c (js2-get-char)))
5574 ((js2-digit-p c)
5575 (setq base 'maybe-8))
5576 (t
5577 (js2-add-to-string ?0))))
5578 (cond
5579 ((eq base 16)
5580 (if (> 0 (js2-x-digit-to-int c 0))
5581 (js2-report-scan-error "msg.missing.hex.digits")
5582 (while (<= 0 (js2-x-digit-to-int c 0))
5583 (js2-add-to-string c)
5584 (setq c (js2-get-char)))))
5585 ((eq base 2)
5586 (if (not (memq c '(?0 ?1)))
5587 (js2-report-scan-error "msg.missing.binary.digits")
5588 (while (memq c '(?0 ?1))
5589 (js2-add-to-string c)
5590 (setq c (js2-get-char)))))
5591 ((eq base 8)
5592 (if (or (> ?0 c) (< ?7 c))
5593 (js2-report-scan-error "msg.missing.octal.digits")
5594 (while (and (<= ?0 c) (>= ?7 c))
5595 (js2-add-to-string c)
5596 (setq c (js2-get-char)))))
5597 (t
5598 (while (and (<= ?0 c) (<= c ?9))
5599 ;; We permit 08 and 09 as decimal numbers, which
5600 ;; makes our behavior a superset of the ECMA
5601 ;; numeric grammar. We might not always be so
5602 ;; permissive, so we warn about it.
5603 (when (and (eq base 'maybe-8) (>= c ?8))
5604 (js2-report-warning "msg.bad.octal.literal"
5605 (if (eq c ?8) "8" "9"))
5606 (setq base 10))
5607 (js2-add-to-string c)
5608 (setq c (js2-get-char)))
5609 (when (eq base 'maybe-8)
5610 (setq base 8))))
5611 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5612 (when (eq c ?.)
5613 (loop do
5614 (js2-add-to-string c)
5615 (setq c (js2-get-char))
5616 while (js2-digit-p c)))
5617 (when (memq c '(?e ?E))
5618 (js2-add-to-string c)
5619 (setq c (js2-get-char))
5620 (when (memq c '(?+ ?-))
5621 (js2-add-to-string c)
5622 (setq c (js2-get-char)))
5623 (unless (js2-digit-p c)
5624 (js2-report-scan-error "msg.missing.exponent" t))
5625 (loop do
5626 (js2-add-to-string c)
5627 (setq c (js2-get-char))
5628 while (js2-digit-p c))))
5629 (js2-unget-char)
5630 (let ((str (js2-set-string-from-buffer token)))
5631 (setf (js2-token-number token)
5632 (js2-string-to-number str base)))
5633 (throw 'return js2-NUMBER))
5634 ;; is it a string?
5635 (when (memq c '(?\" ?\'))
5636 ;; We attempt to accumulate a string the fast way, by
5637 ;; building it directly out of the reader. But if there
5638 ;; are any escaped characters in the string, we revert to
5639 ;; building it out of a string buffer.
5640 (setq quote-char c
5641 js2-ts-string-buffer nil
5642 c (js2-get-char))
5643 (catch 'break
5644 (while (/= c quote-char)
5645 (catch 'continue
5646 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5647 (js2-unget-char)
5648 (setf (js2-token-end token) js2-ts-cursor)
5649 (js2-report-error "msg.unterminated.string.lit")
5650 (throw 'return js2-STRING))
5651 (when (eq c ?\\)
5652 ;; We've hit an escaped character
5653 (setq c (js2-get-char))
5654 (case c
5655 (?b (setq c ?\b))
5656 (?f (setq c ?\f))
5657 (?n (setq c ?\n))
5658 (?r (setq c ?\r))
5659 (?t (setq c ?\t))
5660 (?v (setq c ?\v))
5661 (?u
5662 (setq c1 (js2-read-unicode-escape))
5663 (if js2-parse-ide-mode
5664 (if c1
5665 (progn
5666 ;; just copy the string in IDE-mode
5667 (js2-add-to-string ?\\)
5668 (js2-add-to-string ?u)
5669 (dotimes (_ 3)
5670 (js2-add-to-string (js2-get-char)))
5671 (setq c (js2-get-char))) ; added at end of loop
5672 ;; flag it as an invalid escape
5673 (js2-report-warning "msg.invalid.escape"
5674 nil (- js2-ts-cursor 2) 6))
5675 ;; Get 4 hex digits; if the u escape is not
5676 ;; followed by 4 hex digits, use 'u' + the
5677 ;; literal character sequence that follows.
5678 (js2-add-to-string ?u)
5679 (setq escape-val 0)
5680 (dotimes (_ 4)
5681 (setq c (js2-get-char)
5682 escape-val (js2-x-digit-to-int c escape-val))
5683 (if (minusp escape-val)
5684 (throw 'continue nil))
5685 (js2-add-to-string c))
5686 ;; prepare for replace of stored 'u' sequence by escape value
5687 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5688 c escape-val)))
5689 (?x
5690 ;; Get 2 hex digits, defaulting to 'x'+literal
5691 ;; sequence, as above.
5692 (setq c (js2-get-char)
5693 escape-val (js2-x-digit-to-int c 0))
5694 (if (minusp escape-val)
5695 (progn
5696 (js2-add-to-string ?x)
5697 (throw 'continue nil))
5698 (setq c1 c
5699 c (js2-get-char)
5700 escape-val (js2-x-digit-to-int c escape-val))
5701 (if (minusp escape-val)
5702 (progn
5703 (js2-add-to-string ?x)
5704 (js2-add-to-string c1)
5705 (throw 'continue nil))
5706 ;; got 2 hex digits
5707 (setq c escape-val))))
5708 (?\n
5709 ;; Remove line terminator after escape to follow
5710 ;; SpiderMonkey and C/C++
5711 (setq c (js2-get-char))
5712 (throw 'continue nil))
5713 (t
5714 (when (and (<= ?0 c) (< c ?8))
5715 (setq val (- c ?0)
5716 c (js2-get-char))
5717 (when (and (<= ?0 c) (< c ?8))
5718 (setq val (- (+ (* 8 val) c) ?0)
5719 c (js2-get-char))
5720 (when (and (<= ?0 c)
5721 (< c ?8)
5722 (< val #o37))
5723 ;; c is 3rd char of octal sequence only
5724 ;; if the resulting val <= 0377
5725 (setq val (- (+ (* 8 val) c) ?0)
5726 c (js2-get-char))))
5727 (js2-unget-char)
5728 (setq c val)))))
5729 (js2-add-to-string c)
5730 (setq c (js2-get-char)))))
5731 (js2-set-string-from-buffer token)
5732 (throw 'return js2-STRING))
5733 (js2-ts-return token
5734 (case c
5735 (?\;
5736 (throw 'return js2-SEMI))
5737 (?\[
5738 (throw 'return js2-LB))
5739 (?\]
5740 (throw 'return js2-RB))
5741 (?{
5742 (throw 'return js2-LC))
5743 (?}
5744 (throw 'return js2-RC))
5745 (?\(
5746 (throw 'return js2-LP))
5747 (?\)
5748 (throw 'return js2-RP))
5749 (?,
5750 (throw 'return js2-COMMA))
5751 (??
5752 (throw 'return js2-HOOK))
5753 (?:
5754 (if (js2-match-char ?:)
5755 js2-COLONCOLON
5756 (throw 'return js2-COLON)))
5757 (?.
5758 (if (js2-match-char ?.)
5759 (if (js2-match-char ?.)
5760 js2-TRIPLEDOT js2-DOTDOT)
5761 (if (js2-match-char ?\()
5762 js2-DOTQUERY
5763 (throw 'return js2-DOT))))
5764 (?|
5765 (if (js2-match-char ?|)
5766 (throw 'return js2-OR)
5767 (if (js2-match-char ?=)
5768 js2-ASSIGN_BITOR
5769 (throw 'return js2-BITOR))))
5770 (?^
5771 (if (js2-match-char ?=)
5772 js2-ASSIGN_BITOR
5773 (throw 'return js2-BITXOR)))
5774 (?&
5775 (if (js2-match-char ?&)
5776 (throw 'return js2-AND)
5777 (if (js2-match-char ?=)
5778 js2-ASSIGN_BITAND
5779 (throw 'return js2-BITAND))))
5780 (?=
5781 (if (js2-match-char ?=)
5782 (if (js2-match-char ?=)
5783 js2-SHEQ
5784 (throw 'return js2-EQ))
5785 (if (js2-match-char ?>)
5786 (js2-ts-return token js2-ARROW)
5787 (throw 'return js2-ASSIGN))))
5788 (?!
5789 (if (js2-match-char ?=)
5790 (if (js2-match-char ?=)
5791 js2-SHNE
5792 js2-NE)
5793 (throw 'return js2-NOT)))
5794 (?<
5795 ;; NB:treat HTML begin-comment as comment-till-eol
5796 (when (js2-match-char ?!)
5797 (when (js2-match-char ?-)
5798 (when (js2-match-char ?-)
5799 (js2-skip-line)
5800 (setf (js2-token-comment-type (js2-current-token)) 'html)
5801 (throw 'return js2-COMMENT)))
5802 (js2-unget-char))
5803 (if (js2-match-char ?<)
5804 (if (js2-match-char ?=)
5805 js2-ASSIGN_LSH
5806 js2-LSH)
5807 (if (js2-match-char ?=)
5808 js2-LE
5809 (throw 'return js2-LT))))
5810 (?>
5811 (if (js2-match-char ?>)
5812 (if (js2-match-char ?>)
5813 (if (js2-match-char ?=)
5814 js2-ASSIGN_URSH
5815 js2-URSH)
5816 (if (js2-match-char ?=)
5817 js2-ASSIGN_RSH
5818 js2-RSH))
5819 (if (js2-match-char ?=)
5820 js2-GE
5821 (throw 'return js2-GT))))
5822 (?*
5823 (if (js2-match-char ?=)
5824 js2-ASSIGN_MUL
5825 (throw 'return js2-MUL)))
5826 (?/
5827 ;; is it a // comment?
5828 (when (js2-match-char ?/)
5829 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5830 (js2-skip-line)
5831 (setf (js2-token-comment-type token) 'line)
5832 ;; include newline so highlighting goes to end of window
5833 (incf (js2-token-end token))
5834 (throw 'return js2-COMMENT))
5835 ;; is it a /* comment?
5836 (when (js2-match-char ?*)
5837 (setf look-for-slash nil
5838 (js2-token-beg token) (- js2-ts-cursor 2)
5839 (js2-token-comment-type token)
5840 (if (js2-match-char ?*)
5841 (progn
5842 (setq look-for-slash t)
5843 'jsdoc)
5844 'block))
5845 (while t
5846 (setq c (js2-get-char))
5847 (cond
5848 ((eq c js2-EOF_CHAR)
5849 (setf (js2-token-end token) (1- js2-ts-cursor))
5850 (js2-report-error "msg.unterminated.comment")
5851 (throw 'return js2-COMMENT))
5852 ((eq c ?*)
5853 (setq look-for-slash t))
5854 ((eq c ?/)
5855 (if look-for-slash
5856 (js2-ts-return token js2-COMMENT)))
5857 (t
5858 (setf look-for-slash nil
5859 (js2-token-end token) js2-ts-cursor)))))
5860 (if (js2-match-char ?=)
5861 js2-ASSIGN_DIV
5862 (throw 'return js2-DIV)))
5863 (?#
5864 (when js2-skip-preprocessor-directives
5865 (js2-skip-line)
5866 (setf (js2-token-comment-type token) 'preprocessor
5867 (js2-token-end token) js2-ts-cursor)
5868 (throw 'return js2-COMMENT))
5869 (throw 'return js2-ERROR))
5870 (?%
5871 (if (js2-match-char ?=)
5872 js2-ASSIGN_MOD
5873 (throw 'return js2-MOD)))
5874 (?~
5875 (throw 'return js2-BITNOT))
5876 (?+
5877 (if (js2-match-char ?=)
5878 js2-ASSIGN_ADD
5879 (if (js2-match-char ?+)
5880 js2-INC
5881 (throw 'return js2-ADD))))
5882 (?-
5883 (cond
5884 ((js2-match-char ?=)
5885 (setq c js2-ASSIGN_SUB))
5886 ((js2-match-char ?-)
5887 (unless js2-ts-dirty-line
5888 ;; treat HTML end-comment after possible whitespace
5889 ;; after line start as comment-until-eol
5890 (when (js2-match-char ?>)
5891 (js2-skip-line)
5892 (setf (js2-token-comment-type (js2-current-token)) 'html)
5893 (throw 'return js2-COMMENT)))
5894 (setq c js2-DEC))
5895 (t
5896 (setq c js2-SUB)))
5897 (setq js2-ts-dirty-line t)
5898 c)
5899 (otherwise
5900 (js2-report-scan-error "msg.illegal.character")))))))
5901 (setf (js2-token-type token) tt)
5902 token))
5903
5904 (defsubst js2-string-to-number (str base)
5905 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5906 (condition-case nil
5907 (string-to-number str base)
5908 (overflow-error -1)))
5909
5910 (defun js2-read-regexp (start-tt)
5911 "Called by parser when it gets / or /= in literal context."
5912 (let (c err
5913 in-class ; inside a '[' .. ']' character-class
5914 flags
5915 (continue t)
5916 (token (js2-new-token 0)))
5917 (setq js2-ts-string-buffer nil)
5918 (if (eq start-tt js2-ASSIGN_DIV)
5919 ;; mis-scanned /=
5920 (js2-add-to-string ?=)
5921 (if (not (eq start-tt js2-DIV))
5922 (error "failed assertion")))
5923 (while (and (not err)
5924 (or (/= (setq c (js2-get-char)) ?/)
5925 in-class))
5926 (cond
5927 ((or (= c ?\n)
5928 (= c js2-EOF_CHAR))
5929 (setf (js2-token-end token) (1- js2-ts-cursor)
5930 err t
5931 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5932 (js2-report-error "msg.unterminated.re.lit"))
5933 (t (cond
5934 ((= c ?\\)
5935 (js2-add-to-string c)
5936 (setq c (js2-get-char)))
5937 ((= c ?\[)
5938 (setq in-class t))
5939 ((= c ?\])
5940 (setq in-class nil)))
5941 (js2-add-to-string c))))
5942 (unless err
5943 (while continue
5944 (cond
5945 ((js2-match-char ?g)
5946 (push ?g flags))
5947 ((js2-match-char ?i)
5948 (push ?i flags))
5949 ((js2-match-char ?m)
5950 (push ?m flags))
5951 (t
5952 (setq continue nil))))
5953 (if (js2-alpha-p (js2-peek-char))
5954 (js2-report-scan-error "msg.invalid.re.flag" t
5955 js2-ts-cursor 1))
5956 (js2-set-string-from-buffer token))
5957 (js2-collect-string flags)))
5958
5959 (defun js2-get-first-xml-token ()
5960 (setq js2-ts-xml-open-tags-count 0
5961 js2-ts-is-xml-attribute nil
5962 js2-ts-xml-is-tag-content nil)
5963 (js2-unget-char)
5964 (js2-get-next-xml-token))
5965
5966 (defun js2-xml-discard-string (token)
5967 "Throw away the string in progress and flag an XML parse error."
5968 (setf js2-ts-string-buffer nil
5969 (js2-token-string token) nil)
5970 (js2-report-scan-error "msg.XML.bad.form" t))
5971
5972 (defun js2-get-next-xml-token ()
5973 (setq js2-ts-string-buffer nil) ; for recording the XML
5974 (let ((token (js2-new-token 0))
5975 c result)
5976 (setq result
5977 (catch 'return
5978 (while t
5979 (setq c (js2-get-char))
5980 (cond
5981 ((= c js2-EOF_CHAR)
5982 (throw 'return js2-ERROR))
5983 (js2-ts-xml-is-tag-content
5984 (case c
5985 (?>
5986 (js2-add-to-string c)
5987 (setq js2-ts-xml-is-tag-content nil
5988 js2-ts-is-xml-attribute nil))
5989 (?/
5990 (js2-add-to-string c)
5991 (when (eq ?> (js2-peek-char))
5992 (setq c (js2-get-char))
5993 (js2-add-to-string c)
5994 (setq js2-ts-xml-is-tag-content nil)
5995 (decf js2-ts-xml-open-tags-count)))
5996 (?{
5997 (js2-unget-char)
5998 (js2-set-string-from-buffer token)
5999 (throw 'return js2-XML))
6000 ((?\' ?\")
6001 (js2-add-to-string c)
6002 (unless (js2-read-quoted-string c token)
6003 (throw 'return js2-ERROR)))
6004 (?=
6005 (js2-add-to-string c)
6006 (setq js2-ts-is-xml-attribute t))
6007 ((? ?\t ?\r ?\n)
6008 (js2-add-to-string c))
6009 (t
6010 (js2-add-to-string c)
6011 (setq js2-ts-is-xml-attribute nil)))
6012 (when (and (not js2-ts-xml-is-tag-content)
6013 (zerop js2-ts-xml-open-tags-count))
6014 (js2-set-string-from-buffer token)
6015 (throw 'return js2-XMLEND)))
6016 (t
6017 ;; else not tag content
6018 (case c
6019 (?<
6020 (js2-add-to-string c)
6021 (setq c (js2-peek-char))
6022 (case c
6023 (?!
6024 (setq c (js2-get-char)) ;; skip !
6025 (js2-add-to-string c)
6026 (setq c (js2-peek-char))
6027 (case c
6028 (?-
6029 (setq c (js2-get-char)) ;; skip -
6030 (js2-add-to-string c)
6031 (if (eq c ?-)
6032 (progn
6033 (js2-add-to-string c)
6034 (unless (js2-read-xml-comment token)
6035 (throw 'return js2-ERROR)))
6036 (js2-xml-discard-string token)
6037 (throw 'return js2-ERROR)))
6038 (?\[
6039 (setq c (js2-get-char)) ;; skip [
6040 (js2-add-to-string c)
6041 (if (and (= (js2-get-char) ?C)
6042 (= (js2-get-char) ?D)
6043 (= (js2-get-char) ?A)
6044 (= (js2-get-char) ?T)
6045 (= (js2-get-char) ?A)
6046 (= (js2-get-char) ?\[))
6047 (progn
6048 (js2-add-to-string ?C)
6049 (js2-add-to-string ?D)
6050 (js2-add-to-string ?A)
6051 (js2-add-to-string ?T)
6052 (js2-add-to-string ?A)
6053 (js2-add-to-string ?\[)
6054 (unless (js2-read-cdata token)
6055 (throw 'return js2-ERROR)))
6056 (js2-xml-discard-string token)
6057 (throw 'return js2-ERROR)))
6058 (t
6059 (unless (js2-read-entity token)
6060 (throw 'return js2-ERROR))))
6061 ;; Allow bare CDATA section, e.g.:
6062 ;; let xml = <![CDATA[ foo bar baz ]]>;
6063 (when (zerop js2-ts-xml-open-tags-count)
6064 (throw 'return js2-XMLEND)))
6065 (??
6066 (setq c (js2-get-char)) ;; skip ?
6067 (js2-add-to-string c)
6068 (unless (js2-read-PI token)
6069 (throw 'return js2-ERROR)))
6070 (?/
6071 ;; end tag
6072 (setq c (js2-get-char)) ;; skip /
6073 (js2-add-to-string c)
6074 (when (zerop js2-ts-xml-open-tags-count)
6075 (js2-xml-discard-string token)
6076 (throw 'return js2-ERROR))
6077 (setq js2-ts-xml-is-tag-content t)
6078 (decf js2-ts-xml-open-tags-count))
6079 (t
6080 ;; start tag
6081 (setq js2-ts-xml-is-tag-content t)
6082 (incf js2-ts-xml-open-tags-count))))
6083 (?{
6084 (js2-unget-char)
6085 (js2-set-string-from-buffer token)
6086 (throw 'return js2-XML))
6087 (t
6088 (js2-add-to-string c))))))))
6089 (setf (js2-token-end token) js2-ts-cursor)
6090 (setf (js2-token-type token) result)
6091 result))
6092
6093 (defun js2-read-quoted-string (quote token)
6094 (let (c)
6095 (catch 'return
6096 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6097 (js2-add-to-string c)
6098 (if (eq c quote)
6099 (throw 'return t)))
6100 (js2-xml-discard-string token) ;; throw away string in progress
6101 nil)))
6102
6103 (defun js2-read-xml-comment (token)
6104 (let ((c (js2-get-char)))
6105 (catch 'return
6106 (while (/= c js2-EOF_CHAR)
6107 (catch 'continue
6108 (js2-add-to-string c)
6109 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6110 (setq c (js2-get-char))
6111 (js2-add-to-string c)
6112 (if (eq (js2-peek-char) ?>)
6113 (progn
6114 (setq c (js2-get-char)) ;; skip >
6115 (js2-add-to-string c)
6116 (throw 'return t))
6117 (throw 'continue nil)))
6118 (setq c (js2-get-char))))
6119 (js2-xml-discard-string token)
6120 nil)))
6121
6122 (defun js2-read-cdata (token)
6123 (let ((c (js2-get-char)))
6124 (catch 'return
6125 (while (/= c js2-EOF_CHAR)
6126 (catch 'continue
6127 (js2-add-to-string c)
6128 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6129 (setq c (js2-get-char))
6130 (js2-add-to-string c)
6131 (if (eq (js2-peek-char) ?>)
6132 (progn
6133 (setq c (js2-get-char)) ;; Skip >
6134 (js2-add-to-string c)
6135 (throw 'return t))
6136 (throw 'continue nil)))
6137 (setq c (js2-get-char))))
6138 (js2-xml-discard-string token)
6139 nil)))
6140
6141 (defun js2-read-entity (token)
6142 (let ((decl-tags 1)
6143 c)
6144 (catch 'return
6145 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6146 (js2-add-to-string c)
6147 (case c
6148 (?<
6149 (incf decl-tags))
6150 (?>
6151 (decf decl-tags)
6152 (if (zerop decl-tags)
6153 (throw 'return t)))))
6154 (js2-xml-discard-string token)
6155 nil)))
6156
6157 (defun js2-read-PI (token)
6158 "Scan an XML processing instruction."
6159 (let (c)
6160 (catch 'return
6161 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6162 (js2-add-to-string c)
6163 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6164 (setq c (js2-get-char)) ;; Skip >
6165 (js2-add-to-string c)
6166 (throw 'return t)))
6167 (js2-xml-discard-string token)
6168 nil)))
6169
6170 ;;; Highlighting
6171
6172 (defun js2-set-face (beg end face &optional record)
6173 "Fontify a region. If RECORD is non-nil, record for later."
6174 (when (plusp js2-highlight-level)
6175 (setq beg (min (point-max) beg)
6176 beg (max (point-min) beg)
6177 end (min (point-max) end)
6178 end (max (point-min) end))
6179 (if record
6180 (push (list beg end face) js2-mode-fontifications)
6181 (put-text-property beg end 'font-lock-face face))))
6182
6183 (defsubst js2-clear-face (beg end)
6184 (remove-text-properties beg end '(font-lock-face nil
6185 help-echo nil
6186 point-entered nil
6187 c-in-sws nil)))
6188
6189 (defconst js2-ecma-global-props
6190 (concat "^"
6191 (regexp-opt
6192 '("Infinity" "NaN" "undefined" "arguments") t)
6193 "$")
6194 "Value properties of the Ecma-262 Global Object.
6195 Shown at or above `js2-highlight-level' 2.")
6196
6197 ;; might want to add the name "arguments" to this list?
6198 (defconst js2-ecma-object-props
6199 (concat "^"
6200 (regexp-opt
6201 '("prototype" "__proto__" "__parent__") t)
6202 "$")
6203 "Value properties of the Ecma-262 Object constructor.
6204 Shown at or above `js2-highlight-level' 2.")
6205
6206 (defconst js2-ecma-global-funcs
6207 (concat
6208 "^"
6209 (regexp-opt
6210 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6211 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6212 "$")
6213 "Function properties of the Ecma-262 Global object.
6214 Shown at or above `js2-highlight-level' 2.")
6215
6216 (defconst js2-ecma-number-props
6217 (concat "^"
6218 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6219 "NEGATIVE_INFINITY"
6220 "POSITIVE_INFINITY") t)
6221 "$")
6222 "Properties of the Ecma-262 Number constructor.
6223 Shown at or above `js2-highlight-level' 2.")
6224
6225 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6226 "Properties of the Ecma-262 Date constructor.
6227 Shown at or above `js2-highlight-level' 2.")
6228
6229 (defconst js2-ecma-math-props
6230 (concat "^"
6231 (regexp-opt
6232 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6233 t)
6234 "$")
6235 "Properties of the Ecma-262 Math object.
6236 Shown at or above `js2-highlight-level' 2.")
6237
6238 (defconst js2-ecma-math-funcs
6239 (concat "^"
6240 (regexp-opt
6241 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6242 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6243 "$")
6244 "Function properties of the Ecma-262 Math object.
6245 Shown at or above `js2-highlight-level' 2.")
6246
6247 (defconst js2-ecma-function-props
6248 (concat
6249 "^"
6250 (regexp-opt
6251 '(;; properties of the Object prototype object
6252 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6253 "toLocaleString" "toString" "valueOf"
6254 ;; properties of the Function prototype object
6255 "apply" "call"
6256 ;; properties of the Array prototype object
6257 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6258 "splice" "unshift"
6259 ;; properties of the String prototype object
6260 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6261 "localeCompare" "match" "replace" "search" "split" "substring"
6262 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6263 "toUpperCase"
6264 ;; properties of the Number prototype object
6265 "toExponential" "toFixed" "toPrecision"
6266 ;; properties of the Date prototype object
6267 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6268 "getMinutes" "getMonth" "getSeconds" "getTime"
6269 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6270 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6271 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6272 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6273 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6274 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6275 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6276 "toTimeString" "toUTCString"
6277 ;; properties of the RegExp prototype object
6278 "exec" "test"
6279 ;; properties of the JSON prototype object
6280 "parse" "stringify"
6281 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6282 "toSource" "__defineGetter__" "__defineSetter__"
6283 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6284 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6285 t)
6286 "$")
6287 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6288 Shown at or above `js2-highlight-level' 3.")
6289
6290 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6291 (let ((target-name (and target
6292 (js2-name-node-p target)
6293 (js2-name-node-name target)))
6294 (prop-name (if prop (js2-name-node-name prop)))
6295 (level2 (>= js2-highlight-level 2))
6296 (level3 (>= js2-highlight-level 3)))
6297 (when level2
6298 (let ((face
6299 (if call-p
6300 (cond
6301 ((and target prop)
6302 (cond
6303 ((and level3 (string-match js2-ecma-function-props prop-name))
6304 'font-lock-builtin-face)
6305 ((and target-name prop)
6306 (cond
6307 ((string= target-name "Date")
6308 (if (string-match js2-ecma-date-props prop-name)
6309 'font-lock-builtin-face))
6310 ((string= target-name "Math")
6311 (if (string-match js2-ecma-math-funcs prop-name)
6312 'font-lock-builtin-face))))))
6313 (prop
6314 (if (string-match js2-ecma-global-funcs prop-name)
6315 'font-lock-builtin-face)))
6316 (cond
6317 ((and target prop)
6318 (cond
6319 ((string= target-name "Number")
6320 (if (string-match js2-ecma-number-props prop-name)
6321 'font-lock-constant-face))
6322 ((string= target-name "Math")
6323 (if (string-match js2-ecma-math-props prop-name)
6324 'font-lock-constant-face))))
6325 (prop
6326 (if (string-match js2-ecma-object-props prop-name)
6327 'font-lock-constant-face))))))
6328 (when face
6329 (let ((pos (+ (js2-node-pos parent) ; absolute
6330 (js2-node-pos prop)))) ; relative
6331 (js2-set-face pos
6332 (+ pos (js2-node-len prop))
6333 face 'record)))))))
6334
6335 (defun js2-parse-highlight-member-expr-node (node)
6336 "Perform syntax highlighting of EcmaScript built-in properties.
6337 The variable `js2-highlight-level' governs this highighting."
6338 (let (face target prop name pos end parent call-p callee)
6339 (cond
6340 ;; case 1: simple name, e.g. foo
6341 ((js2-name-node-p node)
6342 (setq name (js2-name-node-name node))
6343 ;; possible for name to be nil in rare cases - saw it when
6344 ;; running js2-mode on an elisp buffer. Might as well try to
6345 ;; make it so js2-mode never barfs.
6346 (when name
6347 (setq face (if (string-match js2-ecma-global-props name)
6348 'font-lock-constant-face))
6349 (when face
6350 (setq pos (js2-node-pos node)
6351 end (+ pos (js2-node-len node)))
6352 (js2-set-face pos end face 'record))))
6353 ;; case 2: property access or function call
6354 ((or (js2-prop-get-node-p node)
6355 ;; highlight function call if expr is a prop-get node
6356 ;; or a plain name (i.e. unqualified function call)
6357 (and (setq call-p (js2-call-node-p node))
6358 (setq callee (js2-call-node-target node)) ; separate setq!
6359 (or (js2-prop-get-node-p callee)
6360 (js2-name-node-p callee))))
6361 (setq parent node
6362 node (if call-p callee node))
6363 (if (and call-p (js2-name-node-p callee))
6364 (setq prop callee)
6365 (setq target (js2-prop-get-node-left node)
6366 prop (js2-prop-get-node-right node)))
6367 (cond
6368 ((js2-name-node-p prop)
6369 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6370 (js2-parse-highlight-prop-get parent target prop call-p))
6371 ((js2-name-node-p target)
6372 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6373 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6374
6375 (defun js2-parse-highlight-member-expr-fn-name (expr)
6376 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6377 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6378 We currently only handle the case where the last component is a prop-get
6379 of a simple name. Called before EXPR has a parent node."
6380 (let (pos
6381 (name (and (js2-prop-get-node-p expr)
6382 (js2-prop-get-node-right expr))))
6383 (when (js2-name-node-p name)
6384 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6385 (js2-node-pos name)))
6386 (+ pos (js2-node-len name))
6387 'font-lock-function-name-face
6388 'record))))
6389
6390 ;; source: http://jsdoc.sourceforge.net/
6391 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6392 ;; allows type specifications, and needs work before entering the wild.
6393
6394 (defconst js2-jsdoc-param-tag-regexp
6395 (concat "^\\s-*\\*+\\s-*\\(@"
6396 "\\(?:param\\|argument\\)"
6397 "\\)"
6398 "\\s-*\\({[^}]+}\\)?" ; optional type
6399 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6400 "\\>")
6401 "Matches jsdoc tags with optional type and optional param name.")
6402
6403 (defconst js2-jsdoc-typed-tag-regexp
6404 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6405 (regexp-opt
6406 '("enum"
6407 "extends"
6408 "field"
6409 "id"
6410 "implements"
6411 "lends"
6412 "mods"
6413 "requires"
6414 "return"
6415 "returns"
6416 "throw"
6417 "throws"))
6418 "\\)\\)\\s-*\\({[^}]+}\\)?")
6419 "Matches jsdoc tags with optional type.")
6420
6421 (defconst js2-jsdoc-arg-tag-regexp
6422 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6423 (regexp-opt
6424 '("alias"
6425 "augments"
6426 "borrows"
6427 "bug"
6428 "base"
6429 "config"
6430 "default"
6431 "define"
6432 "exception"
6433 "function"
6434 "member"
6435 "memberOf"
6436 "name"
6437 "namespace"
6438 "property"
6439 "since"
6440 "suppress"
6441 "this"
6442 "throws"
6443 "type"
6444 "version"))
6445 "\\)\\)\\s-+\\([^ \t]+\\)")
6446 "Matches jsdoc tags with a single argument.")
6447
6448 (defconst js2-jsdoc-empty-tag-regexp
6449 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6450 (regexp-opt
6451 '("addon"
6452 "author"
6453 "class"
6454 "const"
6455 "constant"
6456 "constructor"
6457 "constructs"
6458 "deprecated"
6459 "desc"
6460 "description"
6461 "event"
6462 "example"
6463 "exec"
6464 "export"
6465 "fileoverview"
6466 "final"
6467 "function"
6468 "hidden"
6469 "ignore"
6470 "implicitCast"
6471 "inheritDoc"
6472 "inner"
6473 "interface"
6474 "license"
6475 "noalias"
6476 "noshadow"
6477 "notypecheck"
6478 "override"
6479 "owner"
6480 "preserve"
6481 "preserveTry"
6482 "private"
6483 "protected"
6484 "public"
6485 "static"
6486 "supported"
6487 ))
6488 "\\)\\)\\s-*")
6489 "Matches empty jsdoc tags.")
6490
6491 (defconst js2-jsdoc-link-tag-regexp
6492 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6493 "Matches a jsdoc link or code tag.")
6494
6495 (defconst js2-jsdoc-see-tag-regexp
6496 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6497 "Matches a jsdoc @see tag.")
6498
6499 (defconst js2-jsdoc-html-tag-regexp
6500 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6501 "Matches a simple (no attributes) html start- or end-tag.")
6502
6503 (defun js2-jsdoc-highlight-helper ()
6504 (js2-set-face (match-beginning 1)
6505 (match-end 1)
6506 'js2-jsdoc-tag)
6507 (if (match-beginning 2)
6508 (if (save-excursion
6509 (goto-char (match-beginning 2))
6510 (= (char-after) ?{))
6511 (js2-set-face (1+ (match-beginning 2))
6512 (1- (match-end 2))
6513 'js2-jsdoc-type)
6514 (js2-set-face (match-beginning 2)
6515 (match-end 2)
6516 'js2-jsdoc-value)))
6517 (if (match-beginning 3)
6518 (js2-set-face (match-beginning 3)
6519 (match-end 3)
6520 'js2-jsdoc-value)))
6521
6522 (defun js2-highlight-jsdoc (ast)
6523 "Highlight doc comment tags."
6524 (let ((comments (js2-ast-root-comments ast))
6525 beg end)
6526 (save-excursion
6527 (dolist (node comments)
6528 (when (eq (js2-comment-node-format node) 'jsdoc)
6529 (setq beg (js2-node-abs-pos node)
6530 end (+ beg (js2-node-len node)))
6531 (save-restriction
6532 (narrow-to-region beg end)
6533 (dolist (re (list js2-jsdoc-param-tag-regexp
6534 js2-jsdoc-typed-tag-regexp
6535 js2-jsdoc-arg-tag-regexp
6536 js2-jsdoc-link-tag-regexp
6537 js2-jsdoc-see-tag-regexp
6538 js2-jsdoc-empty-tag-regexp))
6539 (goto-char beg)
6540 (while (re-search-forward re nil t)
6541 (js2-jsdoc-highlight-helper)))
6542 ;; simple highlighting for html tags
6543 (goto-char beg)
6544 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6545 (js2-set-face (match-beginning 1)
6546 (match-end 1)
6547 'js2-jsdoc-html-tag-delimiter)
6548 (js2-set-face (match-beginning 2)
6549 (match-end 2)
6550 'js2-jsdoc-html-tag-name)
6551 (js2-set-face (match-beginning 3)
6552 (match-end 3)
6553 'js2-jsdoc-html-tag-delimiter))))))))
6554
6555 (defun js2-highlight-assign-targets (_node left right)
6556 "Highlight function properties and external variables."
6557 (let (leftpos name)
6558 ;; highlight vars and props assigned function values
6559 (when (js2-function-node-p right)
6560 (cond
6561 ;; var foo = function() {...}
6562 ((js2-name-node-p left)
6563 (setq name left))
6564 ;; foo.bar.baz = function() {...}
6565 ((and (js2-prop-get-node-p left)
6566 (js2-name-node-p (js2-prop-get-node-right left)))
6567 (setq name (js2-prop-get-node-right left))))
6568 (when name
6569 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6570 (+ leftpos (js2-node-len name))
6571 'font-lock-function-name-face
6572 'record)))))
6573
6574 (defun js2-record-name-node (node)
6575 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6576 later. NODE must be a name node."
6577 (let ((leftpos (js2-node-abs-pos node)))
6578 (push (list node js2-current-scope
6579 leftpos
6580 (+ leftpos (js2-node-len node)))
6581 js2-recorded-identifiers)))
6582
6583 (defun js2-highlight-undeclared-vars ()
6584 "After entire parse is finished, look for undeclared variable references.
6585 We have to wait until entire buffer is parsed, since JavaScript permits var
6586 decls to occur after they're used.
6587
6588 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6589 it is considered declared."
6590 (let (name)
6591 (dolist (entry js2-recorded-identifiers)
6592 (destructuring-bind (name-node scope pos end) entry
6593 (setq name (js2-name-node-name name-node))
6594 (unless (or (member name js2-global-externs)
6595 (member name js2-default-externs)
6596 (member name js2-additional-externs)
6597 (js2-get-defining-scope scope name))
6598 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6599 'js2-external-variable))))
6600 (setq js2-recorded-identifiers nil)))
6601
6602 (defun js2-set-default-externs ()
6603 "Set the value of `js2-default-externs' based on the various
6604 `js2-include-?-externs' variables."
6605 (setq js2-default-externs
6606 (append js2-ecma-262-externs
6607 (if js2-include-browser-externs js2-browser-externs)
6608 (if js2-include-rhino-externs js2-rhino-externs)
6609 (if js2-include-node-externs js2-node-externs)
6610 (if (or js2-include-browser-externs js2-include-node-externs)
6611 js2-typed-array-externs))))
6612
6613 (defun js2-apply-jslint-globals ()
6614 (setq js2-additional-externs
6615 (nconc (js2-get-jslint-globals)
6616 js2-additional-externs)))
6617
6618 (defun js2-get-jslint-globals ()
6619 (loop for node in (js2-ast-root-comments js2-mode-ast)
6620 when (and (eq 'block (js2-comment-node-format node))
6621 (save-excursion
6622 (goto-char (js2-node-abs-pos node))
6623 (looking-at "/\\*global ")))
6624 append (js2-get-jslint-globals-in
6625 (match-end 0)
6626 (js2-node-abs-end node))))
6627
6628 (defun js2-get-jslint-globals-in (beg end)
6629 (let (res)
6630 (save-excursion
6631 (goto-char beg)
6632 (while (re-search-forward js2-mode-identifier-re end t)
6633 (let ((match (match-string 0)))
6634 (unless (member match '("true" "false"))
6635 (push match res)))))
6636 (nreverse res)))
6637
6638 ;;; IMenu support
6639
6640 ;; We currently only support imenu, but eventually should support speedbar and
6641 ;; possibly other browsing mechanisms.
6642
6643 ;; The basic strategy is to identify function assignment targets of the form
6644 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6645 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6646 ;; for imenu after parsing is finished.
6647
6648 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6649 ;; JavaScript, and the general problem is undecidable. However, several forms
6650 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6651 ;; include:
6652
6653 ;; function foo() -- function declaration
6654 ;; foo = function() -- function expression assigned to variable
6655 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6656 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6657 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6658 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6659 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6660 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6661 ;; function foo() {function bar() {...}} -- nested function
6662 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6663
6664 ;; This list boils down to a few forms that can be combined recursively.
6665 ;; Top-level named function declarations include both the left-hand (name)
6666 ;; and the right-hand (function value) expressions needed to produce an imenu
6667 ;; entry. The other "right-hand" forms we need to look for are:
6668 ;; - functions declared as props/getters/setters in object literals
6669 ;; - nested named function declarations
6670 ;; The "left-hand" expressions that functions can be assigned to include:
6671 ;; - local/global variables
6672 ;; - nested property-get expressions like a.b.c.d
6673 ;; - element gets like foo[10] or foo['bar'] where the index
6674 ;; expression can be trivially converted to a property name. They
6675 ;; effectively then become property gets.
6676
6677 ;; All the different definition types are canonicalized into the form
6678 ;; foo.bar.baz = position-of-function-keyword
6679
6680 ;; We need to build a trie-like structure for imenu. As an example,
6681 ;; consider the following JavaScript code:
6682
6683 ;; a = function() {...} // function at position 5
6684 ;; b = function() {...} // function at position 25
6685 ;; foo = function() {...} // function at position 100
6686 ;; foo.bar = function() {...} // function at position 200
6687 ;; foo.bar.baz = function() {...} // function at position 300
6688 ;; foo.bar.zab = function() {...} // function at position 400
6689
6690 ;; During parsing we accumulate an entry for each definition in
6691 ;; the variable `js2-imenu-recorder', like so:
6692
6693 ;; '((fn a 5)
6694 ;; (fn b 25)
6695 ;; (fn foo 100)
6696 ;; (fn foo bar 200)
6697 ;; (fn foo bar baz 300)
6698 ;; (fn foo bar zab 400))
6699
6700 ;; Where 'fn' is the respective function node.
6701 ;; After parsing these entries are merged into this alist-trie:
6702
6703 ;; '((a . 1)
6704 ;; (b . 2)
6705 ;; (foo (<definition> . 3)
6706 ;; (bar (<definition> . 6)
6707 ;; (baz . 100)
6708 ;; (zab . 200))))
6709
6710 ;; Note the wacky need for a <definition> name. The token can be anything
6711 ;; that isn't a valid JavaScript identifier, because you might make foo
6712 ;; a function and then start setting properties on it that are also functions.
6713
6714 (defun js2-prop-node-name (node)
6715 "Return the name of a node that may be a property-get/property-name.
6716 If NODE is not a valid name-node, string-node or integral number-node,
6717 returns nil. Otherwise returns the string name/value of the node."
6718 (cond
6719 ((js2-name-node-p node)
6720 (js2-name-node-name node))
6721 ((js2-string-node-p node)
6722 (js2-string-node-value node))
6723 ((and (js2-number-node-p node)
6724 (string-match "^[0-9]+$" (js2-number-node-value node)))
6725 (js2-number-node-value node))
6726 ((js2-this-node-p node)
6727 "this")))
6728
6729 (defun js2-node-qname-component (node)
6730 "Return the name of this node, if it contributes to a qname.
6731 Returns nil if the node doesn't contribute."
6732 (copy-sequence
6733 (or (js2-prop-node-name node)
6734 (if (and (js2-function-node-p node)
6735 (js2-function-node-name node))
6736 (js2-name-node-name (js2-function-node-name node))))))
6737
6738 (defun js2-record-imenu-entry (fn-node qname pos)
6739 "Add an entry to `js2-imenu-recorder'.
6740 FN-NODE should be the current item's function node.
6741
6742 Associate FN-NODE with its QNAME for later lookup.
6743 This is used in postprocessing the chain list. For each chain, we find
6744 the parent function, look up its qname, then prepend a copy of it to the chain."
6745 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6746 (unless js2-imenu-function-map
6747 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6748 (puthash fn-node qname js2-imenu-function-map))
6749
6750 (defun js2-record-imenu-functions (node &optional var)
6751 "Record function definitions for imenu.
6752 NODE is a function node or an object literal.
6753 VAR, if non-nil, is the expression that NODE is being assigned to.
6754 When passed arguments of wrong type, does nothing."
6755 (when js2-parse-ide-mode
6756 (let ((fun-p (js2-function-node-p node))
6757 qname fname-node)
6758 (cond
6759 ;; non-anonymous function declaration?
6760 ((and fun-p
6761 (not var)
6762 (setq fname-node (js2-function-node-name node)))
6763 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6764 ;; for remaining forms, compute left-side tree branch first
6765 ((and var (setq qname (js2-compute-nested-prop-get var)))
6766 (cond
6767 ;; foo.bar.baz = function
6768 (fun-p
6769 (js2-record-imenu-entry node qname (js2-node-pos node)))
6770 ;; foo.bar.baz = object-literal
6771 ;; look for nested functions: {a: {b: function() {...} }}
6772 ((js2-object-node-p node)
6773 ;; Node position here is still absolute, since the parser
6774 ;; passes the assignment target and value expressions
6775 ;; to us before they are added as children of the assignment node.
6776 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6777
6778 (defun js2-compute-nested-prop-get (node)
6779 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6780 component nodes as a list. Otherwise return nil. Element-gets are treated
6781 as property-gets if the index expression is a string, or a positive integer."
6782 (let (left right head)
6783 (cond
6784 ((or (js2-name-node-p node)
6785 (js2-this-node-p node))
6786 (list node))
6787 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6788 ((js2-prop-get-node-p node) ; foo.bar
6789 (setq left (js2-prop-get-node-left node)
6790 right (js2-prop-get-node-right node))
6791 (if (setq head (js2-compute-nested-prop-get left))
6792 (nconc head (list right))))
6793 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6794 (setq left (js2-elem-get-node-target node)
6795 right (js2-elem-get-node-element node))
6796 (if (or (js2-string-node-p right) ; ['bar']
6797 (and (js2-number-node-p right) ; [10]
6798 (string-match "^[0-9]+$"
6799 (js2-number-node-value right))))
6800 (if (setq head (js2-compute-nested-prop-get left))
6801 (nconc head (list right))))))))
6802
6803 (defun js2-record-object-literal (node qname pos)
6804 "Recursively process an object literal looking for functions.
6805 NODE is an object literal that is the right-hand child of an assignment
6806 expression. QNAME is a list of nodes representing the assignment target,
6807 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6808 POS is the absolute position of the node.
6809 We do a depth-first traversal of NODE. For any functions we find,
6810 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6811 (let (right)
6812 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6813 (let ((left (js2-infix-node-left e))
6814 ;; Element positions are relative to the parent position.
6815 (pos (+ pos (js2-node-pos e))))
6816 (cond
6817 ;; foo: function() {...}
6818 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6819 (when (js2-prop-node-name left)
6820 ;; As a policy decision, we record the position of the property,
6821 ;; not the position of the `function' keyword, since the property
6822 ;; is effectively the name of the function.
6823 (js2-record-imenu-entry right (append qname (list left)) pos)))
6824 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6825 ((js2-object-node-p right)
6826 (js2-record-object-literal right
6827 (append qname (list (js2-infix-node-left e)))
6828 (+ pos (js2-node-pos right)))))))))
6829
6830 (defun js2-node-top-level-decl-p (node)
6831 "Return t if NODE's name is defined in the top-level scope.
6832 Also returns t if NODE's name is not defined in any scope, since it implies
6833 that it's an external variable, which must also be in the top-level scope."
6834 (let* ((name (js2-prop-node-name node))
6835 (this-scope (js2-node-get-enclosing-scope node))
6836 defining-scope)
6837 (cond
6838 ((js2-this-node-p node)
6839 nil)
6840 ((null this-scope)
6841 t)
6842 ((setq defining-scope (js2-get-defining-scope this-scope name))
6843 (js2-ast-root-p defining-scope))
6844 (t t))))
6845
6846 (defun js2-wrapper-function-p (node)
6847 "Return t if NODE is a function expression that's immediately invoked.
6848 NODE must be `js2-function-node'."
6849 (let ((parent (js2-node-parent node)))
6850 (or
6851 ;; function(){...}();
6852 (and (js2-call-node-p parent)
6853 (eq node (js2-call-node-target parent)))
6854 (and (js2-paren-node-p parent)
6855 ;; (function(){...})();
6856 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6857 ;; (function(){...}).call(this);
6858 (and (js2-prop-get-node-p parent)
6859 (member (js2-name-node-name (js2-prop-get-node-right parent))
6860 '("call" "apply"))
6861 (js2-call-node-p (js2-node-parent parent))))))))
6862
6863 (defun js2-browse-postprocess-chains ()
6864 "Modify function-declaration name chains after parsing finishes.
6865 Some of the information is only available after the parse tree is complete.
6866 For instance, processing a nested scope requires a parent function node."
6867 (let (result fn parent-qname p elem)
6868 (dolist (entry js2-imenu-recorder)
6869 ;; function node goes first
6870 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6871 ;; Examine head's defining scope:
6872 ;; Pre-processed chain, or top-level/external, keep as-is.
6873 (if (or (stringp head) (js2-node-top-level-decl-p head))
6874 (push chain result)
6875 (when (js2-this-node-p head)
6876 (setq chain (cdr chain))) ; discard this-node
6877 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6878 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6879 (when (eq parent-qname 'not-found)
6880 ;; anonymous function expressions are not recorded
6881 ;; during the parse, so we need to handle this case here
6882 (setq parent-qname
6883 (if (js2-wrapper-function-p fn)
6884 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6885 (if (js2-ast-root-p grandparent)
6886 nil
6887 (gethash grandparent js2-imenu-function-map 'skip)))
6888 'skip))
6889 (puthash fn parent-qname js2-imenu-function-map))
6890 (if (eq parent-qname 'skip)
6891 ;; We don't show it, let's record that fact.
6892 (remhash current-fn js2-imenu-function-map)
6893 ;; Prepend parent fn qname to this chain.
6894 (let ((qname (append parent-qname chain)))
6895 (puthash current-fn (butlast qname) js2-imenu-function-map)
6896 (push qname result)))))))
6897 ;; Collect chains obtained by third-party code.
6898 (let (js2-imenu-recorder)
6899 (run-hooks 'js2-build-imenu-callbacks)
6900 (dolist (entry js2-imenu-recorder)
6901 (push (cdr entry) result)))
6902 ;; Finally replace each node in each chain with its name.
6903 (dolist (chain result)
6904 (setq p chain)
6905 (while p
6906 (if (js2-node-p (setq elem (car p)))
6907 (setcar p (js2-node-qname-component elem)))
6908 (setq p (cdr p))))
6909 result))
6910
6911 ;; Merge name chains into a trie-like tree structure of nested lists.
6912 ;; To simplify construction of the trie, we first build it out using the rule
6913 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6914 ;; [key, num-or-list]. The second element can be a number; if so, this key
6915 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6916 ;; associated with the key at this level.) Otherwise the second element is
6917 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6918 ;; a simple recursive formulation.
6919 ;;
6920 ;; js2-mode is building the data structure for imenu. The imenu documentation
6921 ;; claims that it's the structure above, but in practice it wants the children
6922 ;; at the same list level as the key for that level, which is how I've drawn
6923 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6924 ;; list wrapper around the children at each level.
6925 ;;
6926 ;; A completed nested imenu-alist entry looks like this:
6927 ;; '(("foo"
6928 ;; ("<definition>" . 7)
6929 ;; ("bar"
6930 ;; ("a" . 40)
6931 ;; ("b" . 60))))
6932 ;;
6933 ;; In particular, the documentation for `imenu--index-alist' says that
6934 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6935 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6936
6937 (defun js2-treeify (lst)
6938 "Convert (a b c d) to (a ((b ((c d)))))."
6939 (if (null (cddr lst)) ; list length <= 2
6940 lst
6941 (list (car lst) (list (js2-treeify (cdr lst))))))
6942
6943 (defun js2-build-alist-trie (chains trie)
6944 "Merge declaration name chains into a trie-like alist structure for imenu.
6945 CHAINS is the qname chain list produced during parsing. TRIE is a
6946 list of elements built up so far."
6947 (let (head tail pos branch kids)
6948 (dolist (chain chains)
6949 (setq head (car chain)
6950 tail (cdr chain)
6951 pos (if (numberp (car tail)) (car tail))
6952 branch (js2-find-if (lambda (n)
6953 (string= (car n) head))
6954 trie)
6955 kids (second branch))
6956 (cond
6957 ;; case 1: this key isn't in the trie yet
6958 ((null branch)
6959 (if trie
6960 (setcdr (last trie) (list (js2-treeify chain)))
6961 (setq trie (list (js2-treeify chain)))))
6962 ;; case 2: key is present with a single number entry: replace w/ list
6963 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6964 ;; ("<definition>" 20)))
6965 ((numberp kids)
6966 (setcar (cdr branch)
6967 (list (list "<definition-1>" kids)
6968 (if pos
6969 (list "<definition-2>" pos)
6970 (js2-treeify tail)))))
6971 ;; case 3: key is there (with kids), and we're a number entry
6972 (pos
6973 (setcdr (last kids)
6974 (list
6975 (list (format "<definition-%d>"
6976 (1+ (loop for kid in kids
6977 count (eq ?< (aref (car kid) 0)))))
6978 pos))))
6979 ;; case 4: key is there with kids, need to merge in our chain
6980 (t
6981 (js2-build-alist-trie (list tail) kids))))
6982 trie))
6983
6984 (defun js2-flatten-trie (trie)
6985 "Convert TRIE to imenu-format.
6986 Recurses through nodes, and for each one whose second element is a list,
6987 appends the list's flattened elements to the current element. Also
6988 changes the tails into conses. For instance, this pre-flattened trie
6989
6990 '(a ((b 20)
6991 (c ((d 30)
6992 (e 40)))))
6993
6994 becomes
6995
6996 '(a (b . 20)
6997 (c (d . 30)
6998 (e . 40)))
6999
7000 Note that the root of the trie has no key, just a list of chains.
7001 This is also true for the value of any key with multiple children,
7002 e.g. key 'c' in the example above."
7003 (cond
7004 ((listp (car trie))
7005 (mapcar #'js2-flatten-trie trie))
7006 (t
7007 (if (numberp (second trie))
7008 (cons (car trie) (second trie))
7009 ;; else pop list and append its kids
7010 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7011
7012 (defun js2-build-imenu-index ()
7013 "Turn `js2-imenu-recorder' into an imenu data structure."
7014 (when (eq js2-imenu-recorder 'empty)
7015 (setq js2-imenu-recorder nil))
7016 (let* ((chains (js2-browse-postprocess-chains))
7017 (result (js2-build-alist-trie chains nil)))
7018 (js2-flatten-trie result)))
7019
7020 (defun js2-test-print-chains (chains)
7021 "Print a list of qname chains.
7022 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7023 i.e. one or more nodes, and an integer position as the list tail."
7024 (mapconcat (lambda (chain)
7025 (concat "("
7026 (mapconcat (lambda (elem)
7027 (if (js2-node-p elem)
7028 (or (js2-node-qname-component elem)
7029 "nil")
7030 (number-to-string elem)))
7031 chain
7032 " ")
7033 ")"))
7034 chains
7035 "\n"))
7036
7037 ;;; Parser
7038
7039 (defconst js2-version "1.8.5"
7040 "Version of JavaScript supported.")
7041
7042 (defun js2-record-face (face &optional token)
7043 "Record a style run of FACE for TOKEN or the current token."
7044 (unless token (setq token (js2-current-token)))
7045 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7046
7047 (defsubst js2-node-end (n)
7048 "Computes the absolute end of node N.
7049 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7050 is only true until the node is added to its parent; i.e., while parsing."
7051 (+ (js2-node-pos n)
7052 (js2-node-len n)))
7053
7054 (defun js2-record-comment (token)
7055 "Record a comment in `js2-scanned-comments'."
7056 (let ((ct (js2-token-comment-type token))
7057 (beg (js2-token-beg token))
7058 (end (js2-token-end token)))
7059 (push (make-js2-comment-node :len (- end beg)
7060 :format ct)
7061 js2-scanned-comments)
7062 (when js2-parse-ide-mode
7063 (js2-record-face (if (eq ct 'jsdoc)
7064 'font-lock-doc-face
7065 'font-lock-comment-face)
7066 token)
7067 (when (memq ct '(html preprocessor))
7068 ;; Tell cc-engine the bounds of the comment.
7069 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7070
7071 (defun js2-peek-token ()
7072 "Return the next token type without consuming it.
7073 If `js2-ti-lookahead' is positive, return the type of next token
7074 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7075 (if (not (zerop js2-ti-lookahead))
7076 (js2-token-type
7077 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7078 (let ((tt (js2-get-token-internal)))
7079 (js2-unget-token)
7080 tt)))
7081
7082 (defalias 'js2-next-token 'js2-get-token)
7083
7084 (defun js2-match-token (match &optional dont-unget)
7085 "Get next token and return t if it matches MATCH, a bytecode.
7086 Returns nil and consumes nothing if MATCH is not the next token."
7087 (if (/= (js2-get-token) match)
7088 (ignore (unless dont-unget (js2-unget-token)))
7089 t))
7090
7091 (defun js2-match-contextual-kwd (name)
7092 "Consume and return t if next token is `js2-NAME', and its
7093 string is NAME. Returns nil and keeps current token otherwise."
7094 (if (or (/= (js2-get-token) js2-NAME)
7095 (not (string= (js2-current-token-string) name)))
7096 (progn
7097 (js2-unget-token)
7098 nil)
7099 (js2-record-face 'font-lock-keyword-face)
7100 t))
7101
7102 (defun js2-valid-prop-name-token (tt)
7103 (or (= tt js2-NAME)
7104 (and js2-allow-keywords-as-property-names
7105 (plusp tt)
7106 (or (= tt js2-RESERVED)
7107 (aref js2-kwd-tokens tt)))))
7108
7109 (defun js2-match-prop-name ()
7110 "Consume token and return t if next token is a valid property name.
7111 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7112 is non-nil and it's a keyword token."
7113 (if (js2-valid-prop-name-token (js2-get-token))
7114 t
7115 (js2-unget-token)
7116 nil))
7117
7118 (defun js2-must-match-prop-name (msg-id &optional pos len)
7119 (if (js2-match-prop-name)
7120 t
7121 (js2-report-error msg-id nil pos len)
7122 nil))
7123
7124 (defun js2-peek-token-or-eol ()
7125 "Return js2-EOL if the next token immediately follows a newline.
7126 Else returns the next token. Used in situations where we don't
7127 consider certain token types valid if they are preceded by a newline.
7128 One example is the postfix ++ or -- operator, which has to be on the
7129 same line as its operand."
7130 (let ((tt (js2-get-token))
7131 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7132 (js2-unget-token)
7133 (if follows-eol
7134 js2-EOL
7135 tt)))
7136
7137 (defun js2-must-match (token msg-id &optional pos len)
7138 "Match next token to token code TOKEN, or record a syntax error.
7139 MSG-ID is the error message to report if the match fails.
7140 Returns t on match, nil if no match."
7141 (if (js2-match-token token t)
7142 t
7143 (js2-report-error msg-id nil pos len)
7144 (js2-unget-token)
7145 nil))
7146
7147 (defun js2-must-match-name (msg-id)
7148 (if (js2-match-token js2-NAME t)
7149 t
7150 (if (eq (js2-current-token-type) js2-RESERVED)
7151 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7152 (js2-report-error msg-id)
7153 (js2-unget-token))
7154 nil))
7155
7156 (defsubst js2-inside-function ()
7157 (plusp js2-nesting-of-function))
7158
7159 (defun js2-set-requires-activation ()
7160 (if (js2-function-node-p js2-current-script-or-fn)
7161 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7162
7163 (defun js2-check-activation-name (name _token)
7164 (when (js2-inside-function)
7165 ;; skip language-version 1.2 check from Rhino
7166 (if (or (string= "arguments" name)
7167 (and js2-compiler-activation-names ; only used in codegen
7168 (gethash name js2-compiler-activation-names)))
7169 (js2-set-requires-activation))))
7170
7171 (defun js2-set-is-generator ()
7172 (let ((fn-node js2-current-script-or-fn))
7173 (when (and (js2-function-node-p fn-node)
7174 (not (js2-function-node-generator-type fn-node)))
7175 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7176
7177 (defun js2-must-have-xml ()
7178 (unless js2-compiler-xml-available
7179 (js2-report-error "msg.XML.not.available")))
7180
7181 (defun js2-push-scope (scope)
7182 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7183 (assert (js2-scope-p scope))
7184 (assert (null (js2-scope-parent-scope scope)))
7185 (assert (not (eq js2-current-scope scope)))
7186 (setf (js2-scope-parent-scope scope) js2-current-scope
7187 js2-current-scope scope))
7188
7189 (defsubst js2-pop-scope ()
7190 (setq js2-current-scope
7191 (js2-scope-parent-scope js2-current-scope)))
7192
7193 (defun js2-enter-loop (loop-node)
7194 (push loop-node js2-loop-set)
7195 (push loop-node js2-loop-and-switch-set)
7196 (js2-push-scope loop-node)
7197 ;; Tell the current labeled statement (if any) its statement,
7198 ;; and set the jump target of the first label to the loop.
7199 ;; These are used in `js2-parse-continue' to verify that the
7200 ;; continue target is an actual labeled loop. (And for codegen.)
7201 (when js2-labeled-stmt
7202 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7203 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7204 js2-labeled-stmt))) loop-node)))
7205
7206 (defun js2-exit-loop ()
7207 (pop js2-loop-set)
7208 (pop js2-loop-and-switch-set)
7209 (js2-pop-scope))
7210
7211 (defsubst js2-enter-switch (switch-node)
7212 (push switch-node js2-loop-and-switch-set))
7213
7214 (defsubst js2-exit-switch ()
7215 (pop js2-loop-and-switch-set))
7216
7217 (defun js2-parse (&optional buf cb)
7218 "Tell the js2 parser to parse a region of JavaScript.
7219
7220 BUF is a buffer or buffer name containing the code to parse.
7221 Call `narrow-to-region' first to parse only part of the buffer.
7222
7223 The returned AST root node is given some additional properties:
7224 `node-count' - total number of nodes in the AST
7225 `buffer' - BUF. The buffer it refers to may change or be killed,
7226 so the value is not necessarily reliable.
7227
7228 An optional callback CB can be specified to report parsing
7229 progress. If `(functionp CB)' returns t, it will be called with
7230 the current line number once before parsing begins, then again
7231 each time the lexer reaches a new line number.
7232
7233 CB can also be a list of the form `(symbol cb ...)' to specify
7234 multiple callbacks with different criteria. Each symbol is a
7235 criterion keyword, and the following element is the callback to
7236 call
7237
7238 :line - called whenever the line number changes
7239 :token - called for each new token consumed
7240
7241 The list of criteria could be extended to include entering or
7242 leaving a statement, an expression, or a function definition."
7243 (if (and cb (not (functionp cb)))
7244 (error "criteria callbacks not yet implemented"))
7245 (let ((inhibit-point-motion-hooks t)
7246 (js2-compiler-xml-available (>= js2-language-version 160))
7247 ;; This is a recursive-descent parser, so give it a big stack.
7248 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7249 (max-specpdl-size (max max-specpdl-size 3000))
7250 (case-fold-search nil)
7251 ast)
7252 (with-current-buffer (or buf (current-buffer))
7253 (setq js2-scanned-comments nil
7254 js2-parsed-errors nil
7255 js2-parsed-warnings nil
7256 js2-imenu-recorder nil
7257 js2-imenu-function-map nil
7258 js2-label-set nil)
7259 (js2-init-scanner)
7260 (setq ast (with-silent-modifications
7261 (js2-do-parse)))
7262 (unless js2-ts-hit-eof
7263 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7264 (setf (js2-ast-root-errors ast) js2-parsed-errors
7265 (js2-ast-root-warnings ast) js2-parsed-warnings)
7266 ;; if we didn't find any declarations, put a dummy in this list so we
7267 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7268 (unless js2-imenu-recorder
7269 (setq js2-imenu-recorder 'empty))
7270 (run-hooks 'js2-parse-finished-hook)
7271 ast)))
7272
7273 ;; Corresponds to Rhino's Parser.parse() method.
7274 (defun js2-do-parse ()
7275 "Parse current buffer starting from current point.
7276 Scanner should be initialized."
7277 (let ((pos js2-ts-cursor)
7278 (end js2-ts-cursor) ; in case file is empty
7279 root n tt)
7280 ;; initialize buffer-local parsing vars
7281 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7282 js2-current-script-or-fn root
7283 js2-current-scope root
7284 js2-nesting-of-function 0
7285 js2-labeled-stmt nil
7286 js2-recorded-identifiers nil) ; for js2-highlight
7287 (while (/= (setq tt (js2-get-token)) js2-EOF)
7288 (if (= tt js2-FUNCTION)
7289 (progn
7290 (setq n (if js2-called-by-compile-function
7291 (js2-parse-function-expr)
7292 (js2-parse-function-stmt))))
7293 ;; not a function - parse a statement
7294 (js2-unget-token)
7295 (setq n (js2-parse-statement)))
7296 ;; add function or statement to script
7297 (setq end (js2-node-end n))
7298 (js2-block-node-push root n))
7299 ;; add comments to root in lexical order
7300 (when js2-scanned-comments
7301 ;; if we find a comment beyond end of normal kids, use its end
7302 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7303 (dolist (comment js2-scanned-comments)
7304 (push comment (js2-ast-root-comments root))
7305 (js2-node-add-children root comment)))
7306 (setf (js2-node-len root) (- end pos))
7307 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7308 ;; Give extensions a chance to muck with things before highlighting starts.
7309 (let ((js2-additional-externs js2-additional-externs))
7310 (save-excursion
7311 (run-hooks 'js2-post-parse-callbacks))
7312 (js2-highlight-undeclared-vars))
7313 root))
7314
7315 (defun js2-parse-function-closure-body (fn-node)
7316 "Parse a JavaScript 1.8 function closure body."
7317 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7318 (if js2-ts-hit-eof
7319 (js2-report-error "msg.no.brace.body" nil
7320 (js2-node-pos fn-node)
7321 (- js2-ts-cursor (js2-node-pos fn-node)))
7322 (js2-node-add-children fn-node
7323 (setf (js2-function-node-body fn-node)
7324 (js2-parse-expr t))))))
7325
7326 (defun js2-parse-function-body (fn-node)
7327 (js2-must-match js2-LC "msg.no.brace.body"
7328 (js2-node-pos fn-node)
7329 (- js2-ts-cursor (js2-node-pos fn-node)))
7330 (let ((pos (js2-current-token-beg)) ; LC position
7331 (pn (make-js2-block-node)) ; starts at LC position
7332 tt
7333 end)
7334 (incf js2-nesting-of-function)
7335 (unwind-protect
7336 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7337 (= tt js2-EOF)
7338 (= tt js2-RC)))
7339 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7340 (js2-parse-statement)
7341 (js2-get-token)
7342 (js2-parse-function-stmt))))
7343 (decf js2-nesting-of-function))
7344 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7345 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7346 (setq end (js2-current-token-end)))
7347 (setf (js2-node-pos pn) pos
7348 (js2-node-len pn) (- end pos))
7349 (setf (js2-function-node-body fn-node) pn)
7350 (js2-node-add-children fn-node pn)
7351 pn))
7352
7353 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7354 "Declare and fontify destructuring parameters inside NODE.
7355 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7356 (cond
7357 ((js2-name-node-p node)
7358 (let (leftpos)
7359 (js2-define-symbol decl-type (js2-name-node-name node)
7360 node ignore-not-in-block)
7361 (when face
7362 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7363 (+ leftpos (js2-node-len node))
7364 face 'record))))
7365 ((js2-object-node-p node)
7366 (dolist (elem (js2-object-node-elems node))
7367 (js2-define-destruct-symbols
7368 (if (js2-object-prop-node-p elem)
7369 (js2-object-prop-node-right elem)
7370 ;; abbreviated destructuring {a, b}
7371 elem)
7372 decl-type face ignore-not-in-block)))
7373 ((js2-array-node-p node)
7374 (dolist (elem (js2-array-node-elems node))
7375 (when elem
7376 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7377 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7378 (js2-node-len node)))))
7379
7380 (defun js2-parse-function-params (function-type fn-node pos)
7381 (if (js2-match-token js2-RP)
7382 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7383 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7384 (eq (js2-current-token-type) js2-NAME)))
7385 params param default-found rest-param-at)
7386 (when paren-free-arrow
7387 (js2-unget-token))
7388 (loop for tt = (js2-peek-token)
7389 do
7390 (cond
7391 ;; destructuring param
7392 ((and (not paren-free-arrow)
7393 (or (= tt js2-LB) (= tt js2-LC)))
7394 (js2-get-token)
7395 (when default-found
7396 (js2-report-error "msg.no.default.after.default.param"))
7397 (setq param (js2-parse-destruct-primary-expr))
7398 (js2-define-destruct-symbols param
7399 js2-LP
7400 'js2-function-param)
7401 (push param params))
7402 ;; variable name
7403 (t
7404 (when (and (>= js2-language-version 200)
7405 (not paren-free-arrow)
7406 (js2-match-token js2-TRIPLEDOT)
7407 (not rest-param-at))
7408 ;; to report errors if there are more parameters
7409 (setq rest-param-at (length params)))
7410 (js2-must-match-name "msg.no.parm")
7411 (js2-record-face 'js2-function-param)
7412 (setq param (js2-create-name-node))
7413 (js2-define-symbol js2-LP (js2-current-token-string) param)
7414 ;; default parameter value
7415 (when (or (and default-found
7416 (not rest-param-at)
7417 (js2-must-match js2-ASSIGN
7418 "msg.no.default.after.default.param"
7419 (js2-node-pos param)
7420 (js2-node-len param)))
7421 (and (>= js2-language-version 200)
7422 (js2-match-token js2-ASSIGN)))
7423 (assert (not paren-free-arrow))
7424 (let* ((pos (js2-node-pos param))
7425 (tt (js2-current-token-type))
7426 (op-pos (- (js2-current-token-beg) pos))
7427 (left param)
7428 (right (js2-parse-assign-expr))
7429 (len (- (js2-node-end right) pos)))
7430 (setq param (make-js2-assign-node
7431 :type tt :pos pos :len len :op-pos op-pos
7432 :left left :right right)
7433 default-found t)
7434 (js2-node-add-children param left right)))
7435 (push param params)))
7436 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7437 (js2-report-error "msg.param.after.rest" nil
7438 (js2-node-pos param) (js2-node-len param)))
7439 while
7440 (js2-match-token js2-COMMA))
7441 (when (and (not paren-free-arrow)
7442 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7443 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7444 (when rest-param-at
7445 (setf (js2-function-node-rest-p fn-node) t))
7446 (dolist (p params)
7447 (js2-node-add-children fn-node p)
7448 (push p (js2-function-node-params fn-node))))))
7449
7450 (defun js2-check-inconsistent-return-warning (fn-node name)
7451 "Possibly show inconsistent-return warning.
7452 Last token scanned is the close-curly for the function body."
7453 (when (and js2-mode-show-strict-warnings
7454 js2-strict-inconsistent-return-warning
7455 (not (js2-has-consistent-return-usage
7456 (js2-function-node-body fn-node))))
7457 ;; Have it extend from close-curly to bol or beginning of block.
7458 (let ((pos (save-excursion
7459 (goto-char (js2-current-token-end))
7460 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7461 (point-at-bol))))
7462 (end (js2-current-token-end)))
7463 (if (plusp (js2-name-node-length name))
7464 (js2-add-strict-warning "msg.no.return.value"
7465 (js2-name-node-name name) pos end)
7466 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7467
7468 (defun js2-parse-function-stmt ()
7469 (let ((pos (js2-current-token-beg))
7470 (star-p (js2-match-token js2-MUL)))
7471 (js2-must-match-name "msg.unnamed.function.stmt")
7472 (let ((name (js2-create-name-node t))
7473 pn member-expr)
7474 (cond
7475 ((js2-match-token js2-LP)
7476 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7477 (js2-allow-member-expr-as-function-name
7478 (setq member-expr (js2-parse-member-expr-tail nil name))
7479 (js2-parse-highlight-member-expr-fn-name member-expr)
7480 (js2-must-match js2-LP "msg.no.paren.parms")
7481 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7482 (js2-function-node-member-expr pn) member-expr)
7483 pn)
7484 (t
7485 (js2-report-error "msg.no.paren.parms")
7486 (make-js2-error-node))))))
7487
7488 (defun js2-parse-function-expr ()
7489 (let ((pos (js2-current-token-beg))
7490 (star-p (js2-match-token js2-MUL))
7491 name)
7492 (when (js2-match-token js2-NAME)
7493 (setq name (js2-create-name-node t)))
7494 (js2-must-match js2-LP "msg.no.paren.parms")
7495 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7496
7497 (defun js2-parse-function (function-type pos star-p &optional name)
7498 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7499 beginning of the first token (function keyword, unless it's an
7500 arrow function), NAME is js2-name-node."
7501 (let (fn-node lp)
7502 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7503 (setq lp (js2-current-token-beg)))
7504 (setf fn-node (make-js2-function-node :pos pos
7505 :name name
7506 :form function-type
7507 :lp (if lp (- lp pos))
7508 :generator-type (and star-p 'STAR)))
7509 (when name
7510 (js2-set-face (js2-node-pos name) (js2-node-end name)
7511 'font-lock-function-name-face 'record)
7512 (when (plusp (js2-name-node-length name))
7513 ;; Function statements define a symbol in the enclosing scope
7514 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7515 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7516 ;; 1. Nested functions are not affected by the dynamic scope flag
7517 ;; as dynamic scope is already a parent of their scope.
7518 ;; 2. Functions defined under the with statement also immune to
7519 ;; this setup, in which case dynamic scope is ignored in favor
7520 ;; of the with object.
7521 (setf (js2-function-node-ignore-dynamic fn-node) t))
7522 ;; dynamically bind all the per-function variables
7523 (let ((js2-current-script-or-fn fn-node)
7524 (js2-current-scope fn-node)
7525 (js2-nesting-of-with 0)
7526 (js2-end-flags 0)
7527 js2-label-set
7528 js2-loop-set
7529 js2-loop-and-switch-set)
7530 (js2-parse-function-params function-type fn-node pos)
7531 (when (eq function-type 'FUNCTION_ARROW)
7532 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7533 (if (and (>= js2-language-version 180)
7534 (/= (js2-peek-token) js2-LC))
7535 (js2-parse-function-closure-body fn-node)
7536 (js2-parse-function-body fn-node))
7537 (js2-check-inconsistent-return-warning fn-node name)
7538
7539 (when name
7540 (js2-node-add-children fn-node name)
7541 ;; Function expressions define a name only in the body of the
7542 ;; function, and only if not hidden by a parameter name
7543 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7544 (null (js2-scope-get-symbol js2-current-scope
7545 (js2-name-node-name name))))
7546 (js2-define-symbol js2-FUNCTION
7547 (js2-name-node-name name)
7548 fn-node))
7549 (when (eq function-type 'FUNCTION_STATEMENT)
7550 (js2-record-imenu-functions fn-node))))
7551
7552 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7553 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7554 ;; We wait until after parsing the function to set its parent scope,
7555 ;; since `js2-define-symbol' needs the defining-scope check to stop
7556 ;; at the function boundary when checking for redeclarations.
7557 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7558 fn-node))
7559
7560 (defun js2-parse-statements (&optional parent)
7561 "Parse a statement list. Last token consumed must be js2-LC.
7562
7563 PARENT can be a `js2-block-node', in which case the statements are
7564 appended to PARENT. Otherwise a new `js2-block-node' is created
7565 and returned.
7566
7567 This function does not match the closing js2-RC: the caller
7568 matches the RC so it can provide a suitable error message if not
7569 matched. This means it's up to the caller to set the length of
7570 the node to include the closing RC. The node start pos is set to
7571 the absolute buffer start position, and the caller should fix it
7572 up to be relative to the parent node. All children of this block
7573 node are given relative start positions and correct lengths."
7574 (let ((pn (or parent (make-js2-block-node)))
7575 tt)
7576 (setf (js2-node-pos pn) (js2-current-token-beg))
7577 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7578 (/= tt js2-RC))
7579 (js2-block-node-push pn (js2-parse-statement)))
7580 pn))
7581
7582 (defun js2-parse-statement ()
7583 (let (pn beg end)
7584 ;; coarse-grained user-interrupt check - needs work
7585 (and js2-parse-interruptable-p
7586 (zerop (% (incf js2-parse-stmt-count)
7587 js2-statements-per-pause))
7588 (input-pending-p)
7589 (throw 'interrupted t))
7590 (setq pn (js2-statement-helper))
7591 ;; no-side-effects warning check
7592 (unless (js2-node-has-side-effects pn)
7593 (setq end (js2-node-end pn))
7594 (save-excursion
7595 (goto-char end)
7596 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7597 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7598 pn))
7599
7600 ;; These correspond to the switch cases in Parser.statementHelper
7601 (defconst js2-parsers
7602 (let ((parsers (make-vector js2-num-tokens
7603 #'js2-parse-expr-stmt)))
7604 (aset parsers js2-BREAK #'js2-parse-break)
7605 (aset parsers js2-CONST #'js2-parse-const-var)
7606 (aset parsers js2-CONTINUE #'js2-parse-continue)
7607 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7608 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7609 (aset parsers js2-DO #'js2-parse-do)
7610 (aset parsers js2-FOR #'js2-parse-for)
7611 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7612 (aset parsers js2-IF #'js2-parse-if)
7613 (aset parsers js2-LC #'js2-parse-block)
7614 (aset parsers js2-LET #'js2-parse-let-stmt)
7615 (aset parsers js2-NAME #'js2-parse-name-or-label)
7616 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7617 (aset parsers js2-SEMI #'js2-parse-semi)
7618 (aset parsers js2-SWITCH #'js2-parse-switch)
7619 (aset parsers js2-THROW #'js2-parse-throw)
7620 (aset parsers js2-TRY #'js2-parse-try)
7621 (aset parsers js2-VAR #'js2-parse-const-var)
7622 (aset parsers js2-WHILE #'js2-parse-while)
7623 (aset parsers js2-WITH #'js2-parse-with)
7624 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7625 parsers)
7626 "A vector mapping token types to parser functions.")
7627
7628 (defun js2-parse-warn-missing-semi (beg end)
7629 (and js2-mode-show-strict-warnings
7630 js2-strict-missing-semi-warning
7631 (js2-add-strict-warning
7632 "msg.missing.semi" nil
7633 ;; back up to beginning of statement or line
7634 (max beg (save-excursion
7635 (goto-char end)
7636 (point-at-bol)))
7637 end)))
7638
7639 (defconst js2-no-semi-insertion
7640 (list js2-IF
7641 js2-SWITCH
7642 js2-WHILE
7643 js2-DO
7644 js2-FOR
7645 js2-TRY
7646 js2-WITH
7647 js2-LC
7648 js2-ERROR
7649 js2-SEMI
7650 js2-FUNCTION)
7651 "List of tokens that don't do automatic semicolon insertion.")
7652
7653 (defconst js2-autoinsert-semi-and-warn
7654 (list js2-ERROR js2-EOF js2-RC))
7655
7656 (defun js2-statement-helper ()
7657 (let* ((tt (js2-get-token))
7658 (first-tt tt)
7659 (parser (if (= tt js2-ERROR)
7660 #'js2-parse-semi
7661 (aref js2-parsers tt)))
7662 pn)
7663 ;; If the statement is set, then it's been told its label by now.
7664 (and js2-labeled-stmt
7665 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7666 (setq js2-labeled-stmt nil))
7667 (setq pn (funcall parser))
7668 ;; Don't do auto semi insertion for certain statement types.
7669 (unless (or (memq first-tt js2-no-semi-insertion)
7670 (js2-labeled-stmt-node-p pn))
7671 (js2-auto-insert-semicolon pn))
7672 pn))
7673
7674 (defun js2-auto-insert-semicolon (pn)
7675 (let* ((tt (js2-get-token))
7676 (pos (js2-node-pos pn)))
7677 (cond
7678 ((= tt js2-SEMI)
7679 ;; extend the node bounds to include the semicolon.
7680 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7681 ((memq tt js2-autoinsert-semi-and-warn)
7682 (js2-unget-token) ; Not ';', do not consume.
7683 ;; Autoinsert ;
7684 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7685 (t
7686 (if (not (js2-token-follows-eol-p (js2-current-token)))
7687 ;; Report error if no EOL or autoinsert ';' otherwise
7688 (js2-report-error "msg.no.semi.stmt")
7689 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7690 (js2-unget-token) ; Not ';', do not consume.
7691 ))))
7692
7693 (defun js2-parse-condition ()
7694 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7695 The parens are discarded and the expression node is returned.
7696 The `pos' field of the return value is set to an absolute position
7697 that must be fixed up by the caller.
7698 Return value is a list (EXPR LP RP), with absolute paren positions."
7699 (let (pn lp rp)
7700 (if (js2-must-match js2-LP "msg.no.paren.cond")
7701 (setq lp (js2-current-token-beg)))
7702 (setq pn (js2-parse-expr))
7703 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7704 (setq rp (js2-current-token-beg)))
7705 ;; Report strict warning on code like "if (a = 7) ..."
7706 (if (and js2-strict-cond-assign-warning
7707 (js2-assign-node-p pn))
7708 (js2-add-strict-warning "msg.equal.as.assign" nil
7709 (js2-node-pos pn)
7710 (+ (js2-node-pos pn)
7711 (js2-node-len pn))))
7712 (list pn lp rp)))
7713
7714 (defun js2-parse-if ()
7715 "Parser for if-statement. Last matched token must be js2-IF."
7716 (let ((pos (js2-current-token-beg))
7717 cond if-true if-false else-pos end pn)
7718 (setq cond (js2-parse-condition)
7719 if-true (js2-parse-statement)
7720 if-false (if (js2-match-token js2-ELSE)
7721 (progn
7722 (setq else-pos (- (js2-current-token-beg) pos))
7723 (js2-parse-statement)))
7724 end (js2-node-end (or if-false if-true))
7725 pn (make-js2-if-node :pos pos
7726 :len (- end pos)
7727 :condition (car cond)
7728 :then-part if-true
7729 :else-part if-false
7730 :else-pos else-pos
7731 :lp (js2-relpos (second cond) pos)
7732 :rp (js2-relpos (third cond) pos)))
7733 (js2-node-add-children pn (car cond) if-true if-false)
7734 pn))
7735
7736 (defun js2-parse-switch ()
7737 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7738 (let ((pos (js2-current-token-beg))
7739 tt pn discriminant has-default case-expr case-node
7740 case-pos cases stmt lp)
7741 (if (js2-must-match js2-LP "msg.no.paren.switch")
7742 (setq lp (js2-current-token-beg)))
7743 (setq discriminant (js2-parse-expr)
7744 pn (make-js2-switch-node :discriminant discriminant
7745 :pos pos
7746 :lp (js2-relpos lp pos)))
7747 (js2-node-add-children pn discriminant)
7748 (js2-enter-switch pn)
7749 (unwind-protect
7750 (progn
7751 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7752 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7753 (js2-must-match js2-LC "msg.no.brace.switch")
7754 (catch 'break
7755 (while t
7756 (setq tt (js2-next-token)
7757 case-pos (js2-current-token-beg))
7758 (cond
7759 ((= tt js2-RC)
7760 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7761 (throw 'break nil)) ; done
7762 ((= tt js2-CASE)
7763 (setq case-expr (js2-parse-expr))
7764 (js2-must-match js2-COLON "msg.no.colon.case"))
7765 ((= tt js2-DEFAULT)
7766 (if has-default
7767 (js2-report-error "msg.double.switch.default"))
7768 (setq has-default t
7769 case-expr nil)
7770 (js2-must-match js2-COLON "msg.no.colon.case"))
7771 (t
7772 (js2-report-error "msg.bad.switch")
7773 (throw 'break nil)))
7774 (setq case-node (make-js2-case-node :pos case-pos
7775 :len (- (js2-current-token-end) case-pos)
7776 :expr case-expr))
7777 (js2-node-add-children case-node case-expr)
7778 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7779 (/= tt js2-CASE)
7780 (/= tt js2-DEFAULT)
7781 (/= tt js2-EOF))
7782 (setf stmt (js2-parse-statement)
7783 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7784 (js2-block-node-push case-node stmt))
7785 (push case-node cases)))
7786 ;; add cases last, as pushing reverses the order to be correct
7787 (dolist (kid cases)
7788 (js2-node-add-children pn kid)
7789 (push kid (js2-switch-node-cases pn)))
7790 pn) ; return value
7791 (js2-exit-switch))))
7792
7793 (defun js2-parse-while ()
7794 "Parser for while-statement. Last matched token must be js2-WHILE."
7795 (let ((pos (js2-current-token-beg))
7796 (pn (make-js2-while-node))
7797 cond body)
7798 (js2-enter-loop pn)
7799 (unwind-protect
7800 (progn
7801 (setf cond (js2-parse-condition)
7802 (js2-while-node-condition pn) (car cond)
7803 body (js2-parse-statement)
7804 (js2-while-node-body pn) body
7805 (js2-node-len pn) (- (js2-node-end body) pos)
7806 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7807 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7808 (js2-node-add-children pn body (car cond)))
7809 (js2-exit-loop))
7810 pn))
7811
7812 (defun js2-parse-do ()
7813 "Parser for do-statement. Last matched token must be js2-DO."
7814 (let ((pos (js2-current-token-beg))
7815 (pn (make-js2-do-node))
7816 cond body end)
7817 (js2-enter-loop pn)
7818 (unwind-protect
7819 (progn
7820 (setq body (js2-parse-statement))
7821 (js2-must-match js2-WHILE "msg.no.while.do")
7822 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7823 cond (js2-parse-condition)
7824 (js2-do-node-condition pn) (car cond)
7825 (js2-do-node-body pn) body
7826 end js2-ts-cursor
7827 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7828 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7829 (js2-node-add-children pn (car cond) body))
7830 (js2-exit-loop))
7831 ;; Always auto-insert semicolon to follow SpiderMonkey:
7832 ;; It is required by ECMAScript but is ignored by the rest of
7833 ;; world; see bug 238945
7834 (if (js2-match-token js2-SEMI)
7835 (setq end js2-ts-cursor))
7836 (setf (js2-node-len pn) (- end pos))
7837 pn))
7838
7839 (defun js2-parse-for ()
7840 "Parser for for-statement. Last matched token must be js2-FOR.
7841 Parses for, for-in, and for each-in statements."
7842 (let ((for-pos (js2-current-token-beg))
7843 pn is-for-each is-for-in-or-of is-for-of
7844 in-pos each-pos tmp-pos
7845 init ; Node init is also foo in 'foo in object'
7846 cond ; Node cond is also object in 'foo in object'
7847 incr ; 3rd section of for-loop initializer
7848 body tt lp rp)
7849 ;; See if this is a for each () instead of just a for ()
7850 (when (js2-match-token js2-NAME)
7851 (if (string= "each" (js2-current-token-string))
7852 (progn
7853 (setq is-for-each t
7854 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7855 (js2-record-face 'font-lock-keyword-face))
7856 (js2-report-error "msg.no.paren.for")))
7857 (if (js2-must-match js2-LP "msg.no.paren.for")
7858 (setq lp (- (js2-current-token-beg) for-pos)))
7859 (setq tt (js2-get-token))
7860 ;; 'for' makes local scope
7861 (js2-push-scope (make-js2-scope))
7862 (unwind-protect
7863 ;; parse init clause
7864 (let ((js2-in-for-init t)) ; set as dynamic variable
7865 (cond
7866 ((= tt js2-SEMI)
7867 (js2-unget-token)
7868 (setq init (make-js2-empty-expr-node)))
7869 ((or (= tt js2-VAR) (= tt js2-LET))
7870 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7871 (t
7872 (js2-unget-token)
7873 (setq init (js2-parse-expr)))))
7874 (if (or (js2-match-token js2-IN)
7875 (and (>= js2-language-version 200)
7876 (js2-match-contextual-kwd "of")
7877 (setq is-for-of t)))
7878 (setq is-for-in-or-of t
7879 in-pos (- (js2-current-token-beg) for-pos)
7880 ;; scope of iteration target object is not the scope we've created above.
7881 ;; stash current scope temporary.
7882 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7883 (js2-parse-expr))) ; object over which we're iterating
7884 ;; else ordinary for loop - parse cond and incr
7885 (js2-must-match js2-SEMI "msg.no.semi.for")
7886 (setq cond (if (= (js2-peek-token) js2-SEMI)
7887 (make-js2-empty-expr-node) ; no loop condition
7888 (js2-parse-expr)))
7889 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7890 (setq tmp-pos (js2-current-token-end)
7891 incr (if (= (js2-peek-token) js2-RP)
7892 (make-js2-empty-expr-node :pos tmp-pos)
7893 (js2-parse-expr))))
7894 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7895 (setq rp (- (js2-current-token-beg) for-pos)))
7896 (if (not is-for-in-or-of)
7897 (setq pn (make-js2-for-node :init init
7898 :condition cond
7899 :update incr
7900 :lp lp
7901 :rp rp))
7902 ;; cond could be null if 'in obj' got eaten by the init node.
7903 (if (js2-infix-node-p init)
7904 ;; it was (foo in bar) instead of (var foo in bar)
7905 (setq cond (js2-infix-node-right init)
7906 init (js2-infix-node-left init))
7907 (if (and (js2-var-decl-node-p init)
7908 (> (length (js2-var-decl-node-kids init)) 1))
7909 (js2-report-error "msg.mult.index")))
7910 (setq pn (make-js2-for-in-node :iterator init
7911 :object cond
7912 :in-pos in-pos
7913 :foreach-p is-for-each
7914 :each-pos each-pos
7915 :forof-p is-for-of
7916 :lp lp
7917 :rp rp)))
7918 (unwind-protect
7919 (progn
7920 (js2-enter-loop pn)
7921 ;; We have to parse the body -after- creating the loop node,
7922 ;; so that the loop node appears in the js2-loop-set, allowing
7923 ;; break/continue statements to find the enclosing loop.
7924 (setf body (js2-parse-statement)
7925 (js2-loop-node-body pn) body
7926 (js2-node-pos pn) for-pos
7927 (js2-node-len pn) (- (js2-node-end body) for-pos))
7928 (js2-node-add-children pn init cond incr body))
7929 ;; finally
7930 (js2-exit-loop))
7931 (js2-pop-scope))
7932 pn))
7933
7934 (defun js2-parse-try ()
7935 "Parser for try-statement. Last matched token must be js2-TRY."
7936 (let ((try-pos (js2-current-token-beg))
7937 try-end
7938 try-block
7939 catch-blocks
7940 finally-block
7941 saw-default-catch
7942 peek
7943 param
7944 catch-cond
7945 catch-node
7946 guard-kwd
7947 catch-pos
7948 finally-pos
7949 pn
7950 block
7951 lp
7952 rp)
7953 (if (/= (js2-peek-token) js2-LC)
7954 (js2-report-error "msg.no.brace.try"))
7955 (setq try-block (js2-parse-statement)
7956 try-end (js2-node-end try-block)
7957 peek (js2-peek-token))
7958 (cond
7959 ((= peek js2-CATCH)
7960 (while (js2-match-token js2-CATCH)
7961 (setq catch-pos (js2-current-token-beg)
7962 guard-kwd nil
7963 catch-cond nil
7964 lp nil
7965 rp nil)
7966 (if saw-default-catch
7967 (js2-report-error "msg.catch.unreachable"))
7968 (if (js2-must-match js2-LP "msg.no.paren.catch")
7969 (setq lp (- (js2-current-token-beg) catch-pos)))
7970 (js2-push-scope (make-js2-scope))
7971 (let ((tt (js2-peek-token)))
7972 (cond
7973 ;; destructuring pattern
7974 ;; catch ({ message, file }) { ... }
7975 ((or (= tt js2-LB) (= tt js2-LC))
7976 (js2-get-token)
7977 (setq param (js2-parse-destruct-primary-expr))
7978 (js2-define-destruct-symbols param js2-LET nil))
7979 ;; simple name
7980 (t
7981 (js2-must-match-name "msg.bad.catchcond")
7982 (setq param (js2-create-name-node))
7983 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7984 ;; pattern guard
7985 (if (js2-match-token js2-IF)
7986 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7987 catch-cond (js2-parse-expr))
7988 (setq saw-default-catch t))
7989 (if (js2-must-match js2-RP "msg.bad.catchcond")
7990 (setq rp (- (js2-current-token-beg) catch-pos)))
7991 (js2-must-match js2-LC "msg.no.brace.catchblock")
7992 (setq block (js2-parse-statements)
7993 try-end (js2-node-end block)
7994 catch-node (make-js2-catch-node :pos catch-pos
7995 :param param
7996 :guard-expr catch-cond
7997 :guard-kwd guard-kwd
7998 :block block
7999 :lp lp
8000 :rp rp))
8001 (js2-pop-scope)
8002 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8003 (setq try-end (js2-current-token-beg)))
8004 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8005 (js2-node-len catch-node) (- try-end catch-pos))
8006 (js2-node-add-children catch-node param catch-cond block)
8007 (push catch-node catch-blocks)))
8008 ((/= peek js2-FINALLY)
8009 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8010 (js2-node-pos try-block)
8011 (- (setq try-end (js2-node-end try-block))
8012 (js2-node-pos try-block)))))
8013 (when (js2-match-token js2-FINALLY)
8014 (setq finally-pos (js2-current-token-beg)
8015 block (js2-parse-statement)
8016 try-end (js2-node-end block)
8017 finally-block (make-js2-finally-node :pos finally-pos
8018 :len (- try-end finally-pos)
8019 :body block))
8020 (js2-node-add-children finally-block block))
8021 (setq pn (make-js2-try-node :pos try-pos
8022 :len (- try-end try-pos)
8023 :try-block try-block
8024 :finally-block finally-block))
8025 (js2-node-add-children pn try-block finally-block)
8026 ;; push them onto the try-node, which reverses and corrects their order
8027 (dolist (cb catch-blocks)
8028 (js2-node-add-children pn cb)
8029 (push cb (js2-try-node-catch-clauses pn)))
8030 pn))
8031
8032 (defun js2-parse-throw ()
8033 "Parser for throw-statement. Last matched token must be js2-THROW."
8034 (let ((pos (js2-current-token-beg))
8035 expr pn)
8036 (if (= (js2-peek-token-or-eol) js2-EOL)
8037 ;; ECMAScript does not allow new lines before throw expression,
8038 ;; see bug 256617
8039 (js2-report-error "msg.bad.throw.eol"))
8040 (setq expr (js2-parse-expr)
8041 pn (make-js2-throw-node :pos pos
8042 :len (- (js2-node-end expr) pos)
8043 :expr expr))
8044 (js2-node-add-children pn expr)
8045 pn))
8046
8047 (defun js2-match-jump-label-name (label-name)
8048 "If break/continue specified a label, return that label's labeled stmt.
8049 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8050 does not match an existing label, reports an error and returns nil."
8051 (let ((bundle (cdr (assoc label-name js2-label-set))))
8052 (if (null bundle)
8053 (js2-report-error "msg.undef.label"))
8054 bundle))
8055
8056 (defun js2-parse-break ()
8057 "Parser for break-statement. Last matched token must be js2-BREAK."
8058 (let ((pos (js2-current-token-beg))
8059 (end (js2-current-token-end))
8060 break-target ; statement to break from
8061 break-label ; in "break foo", name-node representing the foo
8062 labels ; matching labeled statement to break to
8063 pn)
8064 (when (eq (js2-peek-token-or-eol) js2-NAME)
8065 (js2-get-token)
8066 (setq break-label (js2-create-name-node)
8067 end (js2-node-end break-label)
8068 ;; matchJumpLabelName only matches if there is one
8069 labels (js2-match-jump-label-name (js2-current-token-string))
8070 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8071 (unless (or break-target break-label)
8072 ;; no break target specified - try for innermost enclosing loop/switch
8073 (if (null js2-loop-and-switch-set)
8074 (unless break-label
8075 (js2-report-error "msg.bad.break" nil pos (length "break")))
8076 (setq break-target (car js2-loop-and-switch-set))))
8077 (setq pn (make-js2-break-node :pos pos
8078 :len (- end pos)
8079 :label break-label
8080 :target break-target))
8081 (js2-node-add-children pn break-label) ; but not break-target
8082 pn))
8083
8084 (defun js2-parse-continue ()
8085 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8086 (let ((pos (js2-current-token-beg))
8087 (end (js2-current-token-end))
8088 label ; optional user-specified label, a `js2-name-node'
8089 labels ; current matching labeled stmt, if any
8090 target ; the `js2-loop-node' target of this continue stmt
8091 pn)
8092 (when (= (js2-peek-token-or-eol) js2-NAME)
8093 (js2-get-token)
8094 (setq label (js2-create-name-node)
8095 end (js2-node-end label)
8096 ;; matchJumpLabelName only matches if there is one
8097 labels (js2-match-jump-label-name (js2-current-token-string))))
8098 (cond
8099 ((null labels) ; no current label to go to
8100 (if (null js2-loop-set) ; no loop to continue to
8101 (js2-report-error "msg.continue.outside" nil pos
8102 (length "continue"))
8103 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8104 (t
8105 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8106 (setq target (js2-labeled-stmt-node-stmt labels))
8107 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8108 (setq pn (make-js2-continue-node :pos pos
8109 :len (- end pos)
8110 :label label
8111 :target target))
8112 (js2-node-add-children pn label) ; but not target - it's not our child
8113 pn))
8114
8115 (defun js2-parse-with ()
8116 "Parser for with-statement. Last matched token must be js2-WITH."
8117 (let ((pos (js2-current-token-beg))
8118 obj body pn lp rp)
8119 (if (js2-must-match js2-LP "msg.no.paren.with")
8120 (setq lp (js2-current-token-beg)))
8121 (setq obj (js2-parse-expr))
8122 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8123 (setq rp (js2-current-token-beg)))
8124 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8125 (setq body (js2-parse-statement)))
8126 (setq pn (make-js2-with-node :pos pos
8127 :len (- (js2-node-end body) pos)
8128 :object obj
8129 :body body
8130 :lp (js2-relpos lp pos)
8131 :rp (js2-relpos rp pos)))
8132 (js2-node-add-children pn obj body)
8133 pn))
8134
8135 (defun js2-parse-const-var ()
8136 "Parser for var- or const-statement.
8137 Last matched token must be js2-CONST or js2-VAR."
8138 (let ((tt (js2-current-token-type))
8139 (pos (js2-current-token-beg))
8140 expr pn)
8141 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8142 pn (make-js2-expr-stmt-node :pos pos
8143 :len (- (js2-node-end expr) pos)
8144 :expr expr))
8145 (js2-node-add-children pn expr)
8146 pn))
8147
8148 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8149 (let ((pn (make-js2-expr-stmt-node :pos pos
8150 :len (js2-node-len expr)
8151 :type (if (js2-inside-function)
8152 js2-EXPR_VOID
8153 js2-EXPR_RESULT)
8154 :expr expr)))
8155 (if add-child
8156 (js2-node-add-children pn expr))
8157 pn))
8158
8159 (defun js2-parse-let-stmt ()
8160 "Parser for let-statement. Last matched token must be js2-LET."
8161 (let ((pos (js2-current-token-beg))
8162 expr pn)
8163 (if (= (js2-peek-token) js2-LP)
8164 ;; let expression in statement context
8165 (setq expr (js2-parse-let pos 'statement)
8166 pn (js2-wrap-with-expr-stmt pos expr t))
8167 ;; else we're looking at a statement like let x=6, y=7;
8168 (setf expr (js2-parse-variables js2-LET pos)
8169 pn (js2-wrap-with-expr-stmt pos expr t)
8170 (js2-node-type pn) js2-EXPR_RESULT))
8171 pn))
8172
8173 (defun js2-parse-ret-yield ()
8174 (js2-parse-return-or-yield (js2-current-token-type) nil))
8175
8176 (defconst js2-parse-return-stmt-enders
8177 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8178
8179 (defsubst js2-now-all-set (before after mask)
8180 "Return whether or not the bits in the mask have changed to all set.
8181 BEFORE is bits before change, AFTER is bits after change, and MASK is
8182 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8183 but not BEFORE."
8184 (and (/= (logand before mask) mask)
8185 (= (logand after mask) mask)))
8186
8187 (defun js2-parse-return-or-yield (tt expr-context)
8188 (let* ((pos (js2-current-token-beg))
8189 (end (js2-current-token-end))
8190 (before js2-end-flags)
8191 (inside-function (js2-inside-function))
8192 (gen-type (and inside-function (js2-function-node-generator-type
8193 js2-current-script-or-fn)))
8194 e ret name yield-star-p)
8195 (unless inside-function
8196 (js2-report-error (if (eq tt js2-RETURN)
8197 "msg.bad.return"
8198 "msg.bad.yield")))
8199 (when (and inside-function
8200 (eq gen-type 'STAR)
8201 (js2-match-token js2-MUL))
8202 (setq yield-star-p t))
8203 ;; This is ugly, but we don't want to require a semicolon.
8204 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8205 (setq e (js2-parse-expr)
8206 end (js2-node-end e)))
8207 (cond
8208 ((eq tt js2-RETURN)
8209 (js2-set-flag js2-end-flags (if (null e)
8210 js2-end-returns
8211 js2-end-returns-value))
8212 (setq ret (make-js2-return-node :pos pos
8213 :len (- end pos)
8214 :retval e))
8215 (js2-node-add-children ret e)
8216 ;; See if we need a strict mode warning.
8217 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8218 ;; more thorough and accurate than this before/after flag check.
8219 ;; E.g. if there's a finally-block that always returns, we shouldn't
8220 ;; show a warning generated by inconsistent returns in the catch blocks.
8221 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8222 ;; so we know which returns/yields to highlight, and we should get rid of
8223 ;; all the checking in `js2-parse-return-or-yield'.
8224 (if (and js2-strict-inconsistent-return-warning
8225 (js2-now-all-set before js2-end-flags
8226 (logior js2-end-returns js2-end-returns-value)))
8227 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8228 ((eq gen-type 'COMPREHENSION)
8229 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8230 ;; like SpiderMonkey does.
8231 (js2-report-error "msg.syntax" nil pos 5))
8232 (t
8233 (setq ret (make-js2-yield-node :pos pos
8234 :len (- end pos)
8235 :value e
8236 :star-p yield-star-p))
8237 (js2-node-add-children ret e)
8238 (unless expr-context
8239 (setq e ret
8240 ret (js2-wrap-with-expr-stmt pos e t))
8241 (js2-set-requires-activation)
8242 (js2-set-is-generator))))
8243 ;; see if we are mixing yields and value returns.
8244 (when (and inside-function
8245 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8246 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8247 'LEGACY))
8248 (setq name (js2-function-name js2-current-script-or-fn))
8249 (if (zerop (length name))
8250 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8251 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8252 ret))
8253
8254 (defun js2-parse-debugger ()
8255 (make-js2-keyword-node :type js2-DEBUGGER))
8256
8257 (defun js2-parse-block ()
8258 "Parser for a curly-delimited statement block.
8259 Last token matched must be `js2-LC'."
8260 (let ((pos (js2-current-token-beg))
8261 (pn (make-js2-scope)))
8262 (js2-push-scope pn)
8263 (unwind-protect
8264 (progn
8265 (js2-parse-statements pn)
8266 (js2-must-match js2-RC "msg.no.brace.block")
8267 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8268 (js2-pop-scope))
8269 pn))
8270
8271 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8272 (defun js2-parse-semi ()
8273 "Parse a statement or handle an error.
8274 Current token type is `js2-SEMI' or `js2-ERROR'."
8275 (let ((tt (js2-current-token-type)) pos len)
8276 (if (eq tt js2-SEMI)
8277 (make-js2-empty-expr-node :len 1)
8278 (setq pos (js2-current-token-beg)
8279 len (- (js2-current-token-end) pos))
8280 (js2-report-error "msg.syntax" nil pos len)
8281 (make-js2-error-node :pos pos :len len))))
8282
8283 (defun js2-parse-default-xml-namespace ()
8284 "Parse a `default xml namespace = <expr>' e4x statement."
8285 (let ((pos (js2-current-token-beg))
8286 end len expr unary)
8287 (js2-must-have-xml)
8288 (js2-set-requires-activation)
8289 (setq len (- js2-ts-cursor pos))
8290 (unless (and (js2-match-token js2-NAME)
8291 (string= (js2-current-token-string) "xml"))
8292 (js2-report-error "msg.bad.namespace" nil pos len))
8293 (unless (and (js2-match-token js2-NAME)
8294 (string= (js2-current-token-string) "namespace"))
8295 (js2-report-error "msg.bad.namespace" nil pos len))
8296 (unless (js2-match-token js2-ASSIGN)
8297 (js2-report-error "msg.bad.namespace" nil pos len))
8298 (setq expr (js2-parse-expr)
8299 end (js2-node-end expr)
8300 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8301 :pos pos
8302 :len (- end pos)
8303 :operand expr))
8304 (js2-node-add-children unary expr)
8305 (make-js2-expr-stmt-node :pos pos
8306 :len (- end pos)
8307 :expr unary)))
8308
8309 (defun js2-record-label (label bundle)
8310 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8311 (js2-get-token)
8312 (let ((name (js2-label-node-name label))
8313 labeled-stmt
8314 dup)
8315 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8316 ;; flag both labels if possible when used in editing mode
8317 (if (and js2-parse-ide-mode
8318 (setq dup (js2-get-label-by-name labeled-stmt name)))
8319 (js2-report-error "msg.dup.label" nil
8320 (js2-node-abs-pos dup) (js2-node-len dup)))
8321 (js2-report-error "msg.dup.label" nil
8322 (js2-node-pos label) (js2-node-len label)))
8323 (js2-labeled-stmt-node-add-label bundle label)
8324 (js2-node-add-children bundle label)
8325 ;; Add one reference to the bundle per label in `js2-label-set'
8326 (push (cons name bundle) js2-label-set)))
8327
8328 (defun js2-parse-name-or-label ()
8329 "Parser for identifier or label. Last token matched must be js2-NAME.
8330 Called when we found a name in a statement context. If it's a label, we gather
8331 up any following labels and the next non-label statement into a
8332 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8333 expression and return it wrapped in a `js2-expr-stmt-node'."
8334 (let ((pos (js2-current-token-beg))
8335 expr stmt bundle
8336 (continue t))
8337 ;; set check for label and call down to `js2-parse-primary-expr'
8338 (setq expr (js2-maybe-parse-label))
8339 (if (null expr)
8340 ;; Parse the non-label expression and wrap with expression stmt.
8341 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8342 ;; else parsed a label
8343 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8344 (js2-record-label expr bundle)
8345 ;; look for more labels
8346 (while (and continue (= (js2-get-token) js2-NAME))
8347 (if (setq expr (js2-maybe-parse-label))
8348 (js2-record-label expr bundle)
8349 (setq expr (js2-parse-expr)
8350 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8351 continue nil)
8352 (js2-auto-insert-semicolon stmt)))
8353 ;; no more labels; now parse the labeled statement
8354 (unwind-protect
8355 (unless stmt
8356 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8357 (js2-unget-token)
8358 (setq stmt (js2-statement-helper))))
8359 ;; remove the labels for this statement from the global set
8360 (dolist (label (js2-labeled-stmt-node-labels bundle))
8361 (setq js2-label-set (remove label js2-label-set))))
8362 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8363 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8364 (js2-node-add-children bundle stmt)
8365 bundle)))
8366
8367 (defun js2-maybe-parse-label ()
8368 (assert (= (js2-current-token-type) js2-NAME))
8369 (let (label-pos
8370 (next-tt (js2-get-token))
8371 (label-end (js2-current-token-end)))
8372 ;; Do not consume colon, it is used as unwind indicator
8373 ;; to return to statementHelper.
8374 (js2-unget-token)
8375 (if (= next-tt js2-COLON)
8376 (prog2
8377 (setq label-pos (js2-current-token-beg))
8378 (make-js2-label-node :pos label-pos
8379 :len (- label-end label-pos)
8380 :name (js2-current-token-string))
8381 (js2-set-face label-pos
8382 label-end
8383 'font-lock-variable-name-face 'record))
8384 ;; Backtrack from the name token, too.
8385 (js2-unget-token)
8386 nil)))
8387
8388 (defun js2-parse-expr-stmt ()
8389 "Default parser in statement context, if no recognized statement found."
8390 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8391 (progn
8392 (js2-unget-token)
8393 (js2-parse-expr)) t))
8394
8395 (defun js2-parse-variables (decl-type pos)
8396 "Parse a comma-separated list of variable declarations.
8397 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8398
8399 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8400 For 'var' or 'const', the keyword should be the token last scanned.
8401
8402 POS is the position where the node should start. It's sometimes the
8403 var/const/let keyword, and other times the beginning of the first token
8404 in the first variable declaration.
8405
8406 Returns the parsed `js2-var-decl-node' expression node."
8407 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8408 :pos pos))
8409 destructuring kid-pos tt init name end nbeg nend vi
8410 (continue t))
8411 ;; Example:
8412 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8413 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8414 ;; var {a, b} = baz;
8415 (while continue
8416 (setq destructuring nil
8417 name nil
8418 tt (js2-get-token)
8419 kid-pos (js2-current-token-beg)
8420 end (js2-current-token-end)
8421 init nil)
8422 (if (or (= tt js2-LB) (= tt js2-LC))
8423 ;; Destructuring assignment, e.g., var [a, b] = ...
8424 (setq destructuring (js2-parse-destruct-primary-expr)
8425 end (js2-node-end destructuring))
8426 ;; Simple variable name
8427 (js2-unget-token)
8428 (when (js2-must-match-name "msg.bad.var")
8429 (setq name (js2-create-name-node)
8430 nbeg (js2-current-token-beg)
8431 nend (js2-current-token-end)
8432 end nend)
8433 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8434 (when (js2-match-token js2-ASSIGN)
8435 (setq init (js2-parse-assign-expr)
8436 end (js2-node-end init))
8437 (js2-record-imenu-functions init name))
8438 (when name
8439 (js2-set-face nbeg nend (if (js2-function-node-p init)
8440 'font-lock-function-name-face
8441 'font-lock-variable-name-face)
8442 'record))
8443 (setq vi (make-js2-var-init-node :pos kid-pos
8444 :len (- end kid-pos)
8445 :type decl-type))
8446 (if destructuring
8447 (progn
8448 (if (and (null init) (not js2-in-for-init))
8449 (js2-report-error "msg.destruct.assign.no.init"))
8450 (js2-define-destruct-symbols destructuring
8451 decl-type
8452 'font-lock-variable-name-face)
8453 (setf (js2-var-init-node-target vi) destructuring))
8454 (setf (js2-var-init-node-target vi) name))
8455 (setf (js2-var-init-node-initializer vi) init)
8456 (js2-node-add-children vi name destructuring init)
8457 (js2-block-node-push result vi)
8458 (unless (js2-match-token js2-COMMA)
8459 (setq continue nil)))
8460 (setf (js2-node-len result) (- end pos))
8461 result))
8462
8463 (defun js2-parse-let (pos &optional stmt-p)
8464 "Parse a let expression or statement.
8465 A let-expression is of the form `let (vars) expr'.
8466 A let-statment is of the form `let (vars) {statements}'.
8467 The third form of let is a variable declaration list, handled
8468 by `js2-parse-variables'."
8469 (let ((pn (make-js2-let-node :pos pos))
8470 beg vars body)
8471 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8472 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8473 (js2-push-scope pn)
8474 (unwind-protect
8475 (progn
8476 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8477 (if (js2-must-match js2-RP "msg.no.paren.let")
8478 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8479 (if (and stmt-p (js2-match-token js2-LC))
8480 ;; let statement
8481 (progn
8482 (setf beg (js2-current-token-beg) ; position stmt at LC
8483 body (js2-parse-statements))
8484 (js2-must-match js2-RC "msg.no.curly.let")
8485 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8486 (js2-node-len pn) (- (js2-current-token-end) pos)
8487 (js2-let-node-body pn) body
8488 (js2-node-type pn) js2-LET))
8489 ;; let expression
8490 (setf body (js2-parse-expr)
8491 (js2-node-len pn) (- (js2-node-end body) pos)
8492 (js2-let-node-body pn) body))
8493 (setf (js2-let-node-vars pn) vars)
8494 (js2-node-add-children pn vars body))
8495 (js2-pop-scope))
8496 pn))
8497
8498 (defun js2-define-new-symbol (decl-type name node &optional scope)
8499 (js2-scope-put-symbol (or scope js2-current-scope)
8500 name
8501 (make-js2-symbol decl-type name node)))
8502
8503 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8504 "Define a symbol in the current scope.
8505 If NODE is non-nil, it is the AST node associated with the symbol."
8506 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8507 (symbol (if defining-scope
8508 (js2-scope-get-symbol defining-scope name)))
8509 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8510 (cond
8511 ((and symbol ; already defined
8512 (or (= sdt js2-CONST) ; old version is const
8513 (= decl-type js2-CONST) ; new version is const
8514 ;; two let-bound vars in this block have same name
8515 (and (= sdt js2-LET)
8516 (eq defining-scope js2-current-scope))))
8517 (js2-report-error
8518 (cond
8519 ((= sdt js2-CONST) "msg.const.redecl")
8520 ((= sdt js2-LET) "msg.let.redecl")
8521 ((= sdt js2-VAR) "msg.var.redecl")
8522 ((= sdt js2-FUNCTION) "msg.function.redecl")
8523 (t "msg.parm.redecl"))
8524 name))
8525 ((= decl-type js2-LET)
8526 (if (and (not ignore-not-in-block)
8527 (or (= (js2-node-type js2-current-scope) js2-IF)
8528 (js2-loop-node-p js2-current-scope)))
8529 (js2-report-error "msg.let.decl.not.in.block")
8530 (js2-define-new-symbol decl-type name node)))
8531 ((or (= decl-type js2-VAR)
8532 (= decl-type js2-CONST)
8533 (= decl-type js2-FUNCTION))
8534 (if symbol
8535 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8536 (js2-add-strict-warning "msg.var.redecl" name)
8537 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8538 (js2-add-strict-warning "msg.var.hides.arg" name)))
8539 (js2-define-new-symbol decl-type name node
8540 js2-current-script-or-fn)))
8541 ((= decl-type js2-LP)
8542 (if symbol
8543 ;; must be duplicate parameter. Second parameter hides the
8544 ;; first, so go ahead and add the second pararameter
8545 (js2-report-warning "msg.dup.parms" name))
8546 (js2-define-new-symbol decl-type name node))
8547 (t (js2-code-bug)))))
8548
8549 (defun js2-parse-paren-expr-or-generator-comp ()
8550 (let ((px-pos (js2-current-token-beg)))
8551 (if (and (>= js2-language-version 200)
8552 (js2-match-token js2-FOR))
8553 (js2-parse-generator-comp px-pos)
8554 (let* ((js2-in-for-init nil)
8555 (expr (js2-parse-expr))
8556 (pn (make-js2-paren-node :pos px-pos
8557 :expr expr
8558 :len (- (js2-current-token-end)
8559 px-pos))))
8560 (js2-node-add-children pn (js2-paren-node-expr pn))
8561 (js2-must-match js2-RP "msg.no.paren")
8562 pn))))
8563
8564 (defun js2-parse-expr (&optional oneshot)
8565 (let* ((pn (js2-parse-assign-expr))
8566 (pos (js2-node-pos pn))
8567 left
8568 right
8569 op-pos)
8570 (while (and (not oneshot)
8571 (js2-match-token js2-COMMA))
8572 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8573 (if (= (js2-peek-token) js2-YIELD)
8574 (js2-report-error "msg.yield.parenthesized"))
8575 (setq right (js2-parse-assign-expr)
8576 left pn
8577 pn (make-js2-infix-node :type js2-COMMA
8578 :pos pos
8579 :len (- js2-ts-cursor pos)
8580 :op-pos op-pos
8581 :left left
8582 :right right))
8583 (js2-node-add-children pn left right))
8584 pn))
8585
8586 (defun js2-parse-assign-expr ()
8587 (let ((tt (js2-get-token))
8588 (pos (js2-current-token-beg))
8589 pn left right op-pos
8590 ts-state recorded-identifiers parsed-errors)
8591 (if (= tt js2-YIELD)
8592 (js2-parse-return-or-yield tt t)
8593 ;; Save the tokenizer state in case we find an arrow function
8594 ;; and have to rewind.
8595 (setq ts-state (make-js2-ts-state)
8596 recorded-identifiers js2-recorded-identifiers
8597 parsed-errors js2-parsed-errors)
8598 ;; not yield - parse assignment expression
8599 (setq pn (js2-parse-cond-expr)
8600 tt (js2-get-token))
8601 (cond
8602 ((and (<= js2-first-assign tt)
8603 (<= tt js2-last-assign))
8604 ;; tt express assignment (=, |=, ^=, ..., %=)
8605 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8606 left pn)
8607 (setq right (js2-parse-assign-expr)
8608 pn (make-js2-assign-node :type tt
8609 :pos pos
8610 :len (- (js2-node-end right) pos)
8611 :op-pos op-pos
8612 :left left
8613 :right right))
8614 (when js2-parse-ide-mode
8615 (js2-highlight-assign-targets pn left right)
8616 (js2-record-imenu-functions right left))
8617 ;; do this last so ide checks above can use absolute positions
8618 (js2-node-add-children pn left right))
8619 ((and (= tt js2-ARROW)
8620 (>= js2-language-version 200))
8621 (js2-ts-seek ts-state)
8622 (setq js2-recorded-identifiers recorded-identifiers
8623 js2-parsed-errors parsed-errors)
8624 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8625 (t
8626 (js2-unget-token)))
8627 pn)))
8628
8629 (defun js2-parse-cond-expr ()
8630 (let ((pos (js2-current-token-beg))
8631 (pn (js2-parse-or-expr))
8632 test-expr
8633 if-true
8634 if-false
8635 q-pos
8636 c-pos)
8637 (when (js2-match-token js2-HOOK)
8638 (setq q-pos (- (js2-current-token-beg) pos)
8639 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8640 (js2-must-match js2-COLON "msg.no.colon.cond")
8641 (setq c-pos (- (js2-current-token-beg) pos)
8642 if-false (js2-parse-assign-expr)
8643 test-expr pn
8644 pn (make-js2-cond-node :pos pos
8645 :len (- (js2-node-end if-false) pos)
8646 :test-expr test-expr
8647 :true-expr if-true
8648 :false-expr if-false
8649 :q-pos q-pos
8650 :c-pos c-pos))
8651 (js2-node-add-children pn test-expr if-true if-false))
8652 pn))
8653
8654 (defun js2-make-binary (type left parser)
8655 "Helper for constructing a binary-operator AST node.
8656 LEFT is the left-side-expression, already parsed, and the
8657 binary operator should have just been matched.
8658 PARSER is a function to call to parse the right operand,
8659 or a `js2-node' struct if it has already been parsed.
8660 FIXME: The latter option is unused?"
8661 (let* ((pos (js2-node-pos left))
8662 (op-pos (- (js2-current-token-beg) pos))
8663 (right (if (js2-node-p parser)
8664 parser
8665 (js2-get-token)
8666 (funcall parser)))
8667 (pn (make-js2-infix-node :type type
8668 :pos pos
8669 :len (- (js2-node-end right) pos)
8670 :op-pos op-pos
8671 :left left
8672 :right right)))
8673 (js2-node-add-children pn left right)
8674 pn))
8675
8676 (defun js2-parse-or-expr ()
8677 (let ((pn (js2-parse-and-expr)))
8678 (when (js2-match-token js2-OR)
8679 (setq pn (js2-make-binary js2-OR
8680 pn
8681 'js2-parse-or-expr)))
8682 pn))
8683
8684 (defun js2-parse-and-expr ()
8685 (let ((pn (js2-parse-bit-or-expr)))
8686 (when (js2-match-token js2-AND)
8687 (setq pn (js2-make-binary js2-AND
8688 pn
8689 'js2-parse-and-expr)))
8690 pn))
8691
8692 (defun js2-parse-bit-or-expr ()
8693 (let ((pn (js2-parse-bit-xor-expr)))
8694 (while (js2-match-token js2-BITOR)
8695 (setq pn (js2-make-binary js2-BITOR
8696 pn
8697 'js2-parse-bit-xor-expr)))
8698 pn))
8699
8700 (defun js2-parse-bit-xor-expr ()
8701 (let ((pn (js2-parse-bit-and-expr)))
8702 (while (js2-match-token js2-BITXOR)
8703 (setq pn (js2-make-binary js2-BITXOR
8704 pn
8705 'js2-parse-bit-and-expr)))
8706 pn))
8707
8708 (defun js2-parse-bit-and-expr ()
8709 (let ((pn (js2-parse-eq-expr)))
8710 (while (js2-match-token js2-BITAND)
8711 (setq pn (js2-make-binary js2-BITAND
8712 pn
8713 'js2-parse-eq-expr)))
8714 pn))
8715
8716 (defconst js2-parse-eq-ops
8717 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8718
8719 (defun js2-parse-eq-expr ()
8720 (let ((pn (js2-parse-rel-expr))
8721 tt)
8722 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8723 (setq pn (js2-make-binary tt
8724 pn
8725 'js2-parse-rel-expr)))
8726 (js2-unget-token)
8727 pn))
8728
8729 (defconst js2-parse-rel-ops
8730 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8731
8732 (defun js2-parse-rel-expr ()
8733 (let ((pn (js2-parse-shift-expr))
8734 (continue t)
8735 tt)
8736 (while continue
8737 (setq tt (js2-get-token))
8738 (cond
8739 ((and js2-in-for-init (= tt js2-IN))
8740 (js2-unget-token)
8741 (setq continue nil))
8742 ((memq tt js2-parse-rel-ops)
8743 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8744 (t
8745 (js2-unget-token)
8746 (setq continue nil))))
8747 pn))
8748
8749 (defconst js2-parse-shift-ops
8750 (list js2-LSH js2-URSH js2-RSH))
8751
8752 (defun js2-parse-shift-expr ()
8753 (let ((pn (js2-parse-add-expr))
8754 tt
8755 (continue t))
8756 (while continue
8757 (setq tt (js2-get-token))
8758 (if (memq tt js2-parse-shift-ops)
8759 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8760 (js2-unget-token)
8761 (setq continue nil)))
8762 pn))
8763
8764 (defun js2-parse-add-expr ()
8765 (let ((pn (js2-parse-mul-expr))
8766 tt
8767 (continue t))
8768 (while continue
8769 (setq tt (js2-get-token))
8770 (if (or (= tt js2-ADD) (= tt js2-SUB))
8771 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8772 (js2-unget-token)
8773 (setq continue nil)))
8774 pn))
8775
8776 (defconst js2-parse-mul-ops
8777 (list js2-MUL js2-DIV js2-MOD))
8778
8779 (defun js2-parse-mul-expr ()
8780 (let ((pn (js2-parse-unary-expr))
8781 tt
8782 (continue t))
8783 (while continue
8784 (setq tt (js2-get-token))
8785 (if (memq tt js2-parse-mul-ops)
8786 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8787 (js2-unget-token)
8788 (setq continue nil)))
8789 pn))
8790
8791 (defun js2-make-unary (type parser &rest args)
8792 "Make a unary node of type TYPE.
8793 PARSER is either a node (for postfix operators) or a function to call
8794 to parse the operand (for prefix operators)."
8795 (let* ((pos (js2-current-token-beg))
8796 (postfix (js2-node-p parser))
8797 (expr (if postfix
8798 parser
8799 (apply parser args)))
8800 end
8801 pn)
8802 (if postfix ; e.g. i++
8803 (setq pos (js2-node-pos expr)
8804 end (js2-current-token-end))
8805 (setq end (js2-node-end expr)))
8806 (setq pn (make-js2-unary-node :type type
8807 :pos pos
8808 :len (- end pos)
8809 :operand expr))
8810 (js2-node-add-children pn expr)
8811 pn))
8812
8813 (defconst js2-incrementable-node-types
8814 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8815 "Node types that can be the operand of a ++ or -- operator.")
8816
8817 (defun js2-check-bad-inc-dec (tt beg end unary)
8818 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8819 js2-incrementable-node-types)
8820 (js2-report-error (if (= tt js2-INC)
8821 "msg.bad.incr"
8822 "msg.bad.decr")
8823 nil beg (- end beg))))
8824
8825 (defun js2-parse-unary-expr ()
8826 (let ((tt (js2-current-token-type))
8827 pn expr beg end)
8828 (cond
8829 ((or (= tt js2-VOID)
8830 (= tt js2-NOT)
8831 (= tt js2-BITNOT)
8832 (= tt js2-TYPEOF))
8833 (js2-get-token)
8834 (js2-make-unary tt 'js2-parse-unary-expr))
8835 ((= tt js2-ADD)
8836 (js2-get-token)
8837 ;; Convert to special POS token in decompiler and parse tree
8838 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8839 ((= tt js2-SUB)
8840 (js2-get-token)
8841 ;; Convert to special NEG token in decompiler and parse tree
8842 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8843 ((or (= tt js2-INC)
8844 (= tt js2-DEC))
8845 (js2-get-token)
8846 (prog1
8847 (setq beg (js2-current-token-beg)
8848 end (js2-current-token-end)
8849 expr (js2-make-unary tt 'js2-parse-member-expr t))
8850 (js2-check-bad-inc-dec tt beg end expr)))
8851 ((= tt js2-DELPROP)
8852 (js2-get-token)
8853 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8854 ((= tt js2-ERROR)
8855 (js2-get-token)
8856 (make-js2-error-node)) ; try to continue
8857 ((and (= tt js2-LT)
8858 js2-compiler-xml-available)
8859 ;; XML stream encountered in expression.
8860 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8861 (t
8862 (setq pn (js2-parse-member-expr t)
8863 ;; Don't look across a newline boundary for a postfix incop.
8864 tt (js2-peek-token-or-eol))
8865 (when (or (= tt js2-INC) (= tt js2-DEC))
8866 (js2-get-token)
8867 (setf expr pn
8868 pn (js2-make-unary tt expr))
8869 (js2-node-set-prop pn 'postfix t)
8870 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8871 pn))))
8872
8873 (defun js2-parse-xml-initializer ()
8874 "Parse an E4X XML initializer.
8875 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8876 Then I'll postprocess the result, depending on whether we're in IDE
8877 mode or codegen mode, and generate the appropriate rewritten AST.
8878 IDE mode uses a rich AST that models the XML structure. Codegen mode
8879 just concatenates everything and makes a new XML or XMLList out of it."
8880 (let ((tt (js2-get-first-xml-token))
8881 pn-xml pn expr kids expr-pos
8882 (continue t)
8883 (first-token t))
8884 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8885 (js2-report-error "msg.syntax"))
8886 (setq pn-xml (make-js2-xml-node))
8887 (while continue
8888 (if first-token
8889 (setq first-token nil)
8890 (setq tt (js2-get-next-xml-token)))
8891 (cond
8892 ;; js2-XML means we found a {expr} in the XML stream.
8893 ;; The token string is the XML up to the left-curly.
8894 ((= tt js2-XML)
8895 (push (make-js2-string-node :pos (js2-current-token-beg)
8896 :len (- js2-ts-cursor (js2-current-token-beg)))
8897 kids)
8898 (js2-must-match js2-LC "msg.syntax")
8899 (setq expr-pos js2-ts-cursor
8900 expr (if (eq (js2-peek-token) js2-RC)
8901 (make-js2-empty-expr-node :pos expr-pos)
8902 (js2-parse-expr)))
8903 (js2-must-match js2-RC "msg.syntax")
8904 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8905 :len (js2-node-len expr)
8906 :expr expr))
8907 (js2-node-add-children pn expr)
8908 (push pn kids))
8909 ;; a js2-XMLEND token means we hit the final close-tag.
8910 ((= tt js2-XMLEND)
8911 (push (make-js2-string-node :pos (js2-current-token-beg)
8912 :len (- js2-ts-cursor (js2-current-token-beg)))
8913 kids)
8914 (dolist (kid (nreverse kids))
8915 (js2-block-node-push pn-xml kid))
8916 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8917 (js2-node-pos pn-xml))
8918 continue nil))
8919 (t
8920 (js2-report-error "msg.syntax")
8921 (setq continue nil))))
8922 pn-xml))
8923
8924
8925 (defun js2-parse-argument-list ()
8926 "Parse an argument list and return it as a Lisp list of nodes.
8927 Returns the list in reverse order. Consumes the right-paren token."
8928 (let (result)
8929 (unless (js2-match-token js2-RP)
8930 (loop do
8931 (let ((tt (js2-get-token)))
8932 (if (= tt js2-YIELD)
8933 (js2-report-error "msg.yield.parenthesized"))
8934 (if (and (= tt js2-TRIPLEDOT)
8935 (>= js2-language-version 200))
8936 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8937 (js2-unget-token)
8938 (push (js2-parse-assign-expr) result)))
8939 while
8940 (js2-match-token js2-COMMA))
8941 (js2-must-match js2-RP "msg.no.paren.arg")
8942 result)))
8943
8944 (defun js2-parse-member-expr (&optional allow-call-syntax)
8945 (let ((tt (js2-current-token-type))
8946 pn pos target args beg end init)
8947 (if (/= tt js2-NEW)
8948 (setq pn (js2-parse-primary-expr))
8949 ;; parse a 'new' expression
8950 (js2-get-token)
8951 (setq pos (js2-current-token-beg)
8952 beg pos
8953 target (js2-parse-member-expr)
8954 end (js2-node-end target)
8955 pn (make-js2-new-node :pos pos
8956 :target target
8957 :len (- end pos)))
8958 (js2-highlight-function-call (js2-current-token))
8959 (js2-node-add-children pn target)
8960 (when (js2-match-token js2-LP)
8961 ;; Add the arguments to pn, if any are supplied.
8962 (setf beg pos ; start of "new" keyword
8963 pos (js2-current-token-beg)
8964 args (nreverse (js2-parse-argument-list))
8965 (js2-new-node-args pn) args
8966 end (js2-current-token-end)
8967 (js2-new-node-lp pn) (- pos beg)
8968 (js2-new-node-rp pn) (- end 1 beg))
8969 (apply #'js2-node-add-children pn args))
8970 (when (and js2-allow-rhino-new-expr-initializer
8971 (js2-match-token js2-LC))
8972 (setf init (js2-parse-object-literal)
8973 end (js2-node-end init)
8974 (js2-new-node-initializer pn) init)
8975 (js2-node-add-children pn init))
8976 (setf (js2-node-len pn) (- end beg))) ; end outer if
8977 (js2-parse-member-expr-tail allow-call-syntax pn)))
8978
8979 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8980 "Parse a chain of property/array accesses or function calls.
8981 Includes parsing for E4X operators like `..' and `.@'.
8982 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8983 Returns an expression tree that includes PN, the parent node."
8984 (let (tt
8985 (continue t))
8986 (while continue
8987 (setq tt (js2-get-token))
8988 (cond
8989 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8990 (setq pn (js2-parse-property-access tt pn)))
8991 ((= tt js2-DOTQUERY)
8992 (setq pn (js2-parse-dot-query pn)))
8993 ((= tt js2-LB)
8994 (setq pn (js2-parse-element-get pn)))
8995 ((= tt js2-LP)
8996 (js2-unget-token)
8997 (if allow-call-syntax
8998 (setq pn (js2-parse-function-call pn))
8999 (setq continue nil)))
9000 (t
9001 (js2-unget-token)
9002 (setq continue nil))))
9003 (if (>= js2-highlight-level 2)
9004 (js2-parse-highlight-member-expr-node pn))
9005 pn))
9006
9007 (defun js2-parse-dot-query (pn)
9008 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9009 Last token parsed must be `js2-DOTQUERY'."
9010 (let ((pos (js2-node-pos pn))
9011 op-pos expr end)
9012 (js2-must-have-xml)
9013 (js2-set-requires-activation)
9014 (setq op-pos (js2-current-token-beg)
9015 expr (js2-parse-expr)
9016 end (js2-node-end expr)
9017 pn (make-js2-xml-dot-query-node :left pn
9018 :pos pos
9019 :op-pos op-pos
9020 :right expr))
9021 (js2-node-add-children pn
9022 (js2-xml-dot-query-node-left pn)
9023 (js2-xml-dot-query-node-right pn))
9024 (if (js2-must-match js2-RP "msg.no.paren")
9025 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9026 end (js2-current-token-end)))
9027 (setf (js2-node-len pn) (- end pos))
9028 pn))
9029
9030 (defun js2-parse-element-get (pn)
9031 "Parse an element-get expression, e.g. foo[bar].
9032 Last token parsed must be `js2-RB'."
9033 (let ((lb (js2-current-token-beg))
9034 (pos (js2-node-pos pn))
9035 rb expr)
9036 (setq expr (js2-parse-expr))
9037 (if (js2-must-match js2-RB "msg.no.bracket.index")
9038 (setq rb (js2-current-token-beg)))
9039 (setq pn (make-js2-elem-get-node :target pn
9040 :pos pos
9041 :element expr
9042 :lb (js2-relpos lb pos)
9043 :rb (js2-relpos rb pos)
9044 :len (- (js2-current-token-end) pos)))
9045 (js2-node-add-children pn
9046 (js2-elem-get-node-target pn)
9047 (js2-elem-get-node-element pn))
9048 pn))
9049
9050 (defun js2-highlight-function-call (token)
9051 (when (eq (js2-token-type token) js2-NAME)
9052 (js2-record-face 'js2-function-call token)))
9053
9054 (defun js2-parse-function-call (pn)
9055 (js2-highlight-function-call (js2-current-token))
9056 (js2-get-token)
9057 (let (args
9058 (pos (js2-node-pos pn)))
9059 (setq pn (make-js2-call-node :pos pos
9060 :target pn
9061 :lp (- (js2-current-token-beg) pos)))
9062 (js2-node-add-children pn (js2-call-node-target pn))
9063 ;; Add the arguments to pn, if any are supplied.
9064 (setf args (nreverse (js2-parse-argument-list))
9065 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9066 (js2-call-node-args pn) args)
9067 (apply #'js2-node-add-children pn args)
9068 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9069 pn))
9070
9071 (defun js2-parse-property-access (tt pn)
9072 "Parse a property access, XML descendants access, or XML attr access."
9073 (let ((member-type-flags 0)
9074 (dot-pos (js2-current-token-beg))
9075 (dot-len (if (= tt js2-DOTDOT) 2 1))
9076 name
9077 ref ; right side of . or .. operator
9078 result)
9079 (when (= tt js2-DOTDOT)
9080 (js2-must-have-xml)
9081 (setq member-type-flags js2-descendants-flag))
9082 (if (not js2-compiler-xml-available)
9083 (progn
9084 (js2-must-match-prop-name "msg.no.name.after.dot")
9085 (setq name (js2-create-name-node t js2-GETPROP)
9086 result (make-js2-prop-get-node :left pn
9087 :pos (js2-current-token-beg)
9088 :right name
9089 :len (js2-current-token-len)))
9090 (js2-node-add-children result pn name)
9091 result)
9092 ;; otherwise look for XML operators
9093 (setf result (if (= tt js2-DOT)
9094 (make-js2-prop-get-node)
9095 (make-js2-infix-node :type js2-DOTDOT))
9096 (js2-node-pos result) (js2-node-pos pn)
9097 (js2-infix-node-op-pos result) dot-pos
9098 (js2-infix-node-left result) pn ; do this after setting position
9099 tt (js2-next-token))
9100 (cond
9101 ;; needed for generator.throw()
9102 ((= tt js2-THROW)
9103 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9104 ;; handles: name, ns::name, ns::*, ns::[expr]
9105 ((js2-valid-prop-name-token tt)
9106 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9107 ;; handles: *, *::name, *::*, *::[expr]
9108 ((= tt js2-MUL)
9109 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9110 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9111 ((= tt js2-XMLATTR)
9112 (setq result (js2-parse-attribute-access)))
9113 (t
9114 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9115 (if ref
9116 (setf (js2-node-len result) (- (js2-node-end ref)
9117 (js2-node-pos result))
9118 (js2-infix-node-right result) ref))
9119 (if (js2-infix-node-p result)
9120 (js2-node-add-children result
9121 (js2-infix-node-left result)
9122 (js2-infix-node-right result)))
9123 result)))
9124
9125 (defun js2-parse-attribute-access ()
9126 "Parse an E4X XML attribute expression.
9127 This includes expressions of the forms:
9128
9129 @attr @ns::attr @ns::*
9130 @* @*::attr @*::*
9131 @[expr] @*::[expr] @ns::[expr]
9132
9133 Called if we peeked an '@' token."
9134 (let ((tt (js2-next-token))
9135 (at-pos (js2-current-token-beg)))
9136 (cond
9137 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9138 ((js2-valid-prop-name-token tt)
9139 (js2-parse-property-name at-pos nil 0))
9140 ;; handles: @*, @*::name, @*::*, @*::[expr]
9141 ((= tt js2-MUL)
9142 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9143 ;; handles @[expr]
9144 ((= tt js2-LB)
9145 (js2-parse-xml-elem-ref at-pos))
9146 (t
9147 (js2-report-error "msg.no.name.after.xmlAttr")
9148 ;; Avoid cascaded errors that happen if we make an error node here.
9149 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9150
9151 (defun js2-parse-property-name (at-pos s member-type-flags)
9152 "Check if :: follows name in which case it becomes qualified name.
9153
9154 AT-POS is a natural number if we just read an '@' token, else nil.
9155 S is the name or string that was matched: an identifier, 'throw' or '*'.
9156 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9157
9158 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9159 operator, or the name is followed by ::. For a plain name, returns a
9160 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9161 (let ((pos (or at-pos (js2-current-token-beg)))
9162 colon-pos
9163 (name (js2-create-name-node t (js2-current-token-type) s))
9164 ns tt pn)
9165 (catch 'return
9166 (when (js2-match-token js2-COLONCOLON)
9167 (setq ns name
9168 colon-pos (js2-current-token-beg)
9169 tt (js2-next-token))
9170 (cond
9171 ;; handles name::name
9172 ((js2-valid-prop-name-token tt)
9173 (setq name (js2-create-name-node)))
9174 ;; handles name::*
9175 ((= tt js2-MUL)
9176 (setq name (js2-create-name-node nil nil "*")))
9177 ;; handles name::[expr]
9178 ((= tt js2-LB)
9179 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9180 (t
9181 (js2-report-error "msg.no.name.after.coloncolon"))))
9182 (if (and (null ns) (zerop member-type-flags))
9183 name
9184 (prog1
9185 (setq pn
9186 (make-js2-xml-prop-ref-node :pos pos
9187 :len (- (js2-node-end name) pos)
9188 :at-pos at-pos
9189 :colon-pos colon-pos
9190 :propname name))
9191 (js2-node-add-children pn name))))))
9192
9193 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9194 "Parse the [expr] portion of an xml element reference.
9195 For instance, @[expr], @*::[expr], or ns::[expr]."
9196 (let* ((lb (js2-current-token-beg))
9197 (pos (or at-pos lb))
9198 rb
9199 (expr (js2-parse-expr))
9200 (end (js2-node-end expr))
9201 pn)
9202 (if (js2-must-match js2-RB "msg.no.bracket.index")
9203 (setq rb (js2-current-token-beg)
9204 end (js2-current-token-end)))
9205 (prog1
9206 (setq pn
9207 (make-js2-xml-elem-ref-node :pos pos
9208 :len (- end pos)
9209 :namespace namespace
9210 :colon-pos colon-pos
9211 :at-pos at-pos
9212 :expr expr
9213 :lb (js2-relpos lb pos)
9214 :rb (js2-relpos rb pos)))
9215 (js2-node-add-children pn namespace expr))))
9216
9217 (defun js2-parse-destruct-primary-expr ()
9218 (let ((js2-is-in-destructuring t))
9219 (js2-parse-primary-expr)))
9220
9221 (defun js2-parse-primary-expr ()
9222 "Parse a literal (leaf) expression of some sort.
9223 Includes complex literals such as functions, object-literals,
9224 array-literals, array comprehensions and regular expressions."
9225 (let (pn ; parent node (usually return value)
9226 tt)
9227 (setq tt (js2-current-token-type))
9228 (cond
9229 ((= tt js2-FUNCTION)
9230 (js2-parse-function-expr))
9231 ((= tt js2-LB)
9232 (js2-parse-array-comp-or-literal))
9233 ((= tt js2-LC)
9234 (js2-parse-object-literal))
9235 ((= tt js2-LET)
9236 (js2-parse-let (js2-current-token-beg)))
9237 ((= tt js2-LP)
9238 (js2-parse-paren-expr-or-generator-comp))
9239 ((= tt js2-XMLATTR)
9240 (js2-must-have-xml)
9241 (js2-parse-attribute-access))
9242 ((= tt js2-NAME)
9243 (js2-parse-name tt))
9244 ((= tt js2-NUMBER)
9245 (make-js2-number-node))
9246 ((= tt js2-STRING)
9247 (prog1
9248 (make-js2-string-node)
9249 (js2-record-face 'font-lock-string-face)))
9250 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9251 ;; Got / or /= which in this context means a regexp literal
9252 (let ((px-pos (js2-current-token-beg))
9253 (flags (js2-read-regexp tt))
9254 (end (js2-current-token-end)))
9255 (prog1
9256 (make-js2-regexp-node :pos px-pos
9257 :len (- end px-pos)
9258 :value (js2-current-token-string)
9259 :flags flags)
9260 (js2-set-face px-pos end 'font-lock-string-face 'record)
9261 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9262 ((or (= tt js2-NULL)
9263 (= tt js2-THIS)
9264 (= tt js2-FALSE)
9265 (= tt js2-TRUE))
9266 (make-js2-keyword-node :type tt))
9267 ((= tt js2-RP)
9268 ;; Not valid expression syntax, but this is valid in an arrow
9269 ;; function with no params: () => body.
9270 (if (eq (js2-peek-token) js2-ARROW)
9271 (progn
9272 (js2-unget-token) ; Put back the right paren.
9273 ;; Return whatever, it will hopefully be rewinded and
9274 ;; reparsed when we reach the =>.
9275 (make-js2-keyword-node :type js2-NULL))
9276 (js2-report-error "msg.syntax")
9277 (make-js2-error-node)))
9278 ((= tt js2-TRIPLEDOT)
9279 ;; Likewise, only valid in an arrow function with a rest param.
9280 (if (and (js2-match-token js2-NAME)
9281 (js2-match-token js2-RP)
9282 (eq (js2-peek-token) js2-ARROW))
9283 (progn
9284 (js2-unget-token) ; Put back the right paren.
9285 ;; See the previous case.
9286 (make-js2-keyword-node :type js2-NULL))
9287 (js2-report-error "msg.syntax")
9288 (make-js2-error-node)))
9289 ((= tt js2-RESERVED)
9290 (js2-report-error "msg.reserved.id")
9291 (make-js2-name-node))
9292 ((= tt js2-ERROR)
9293 ;; the scanner or one of its subroutines reported the error.
9294 (make-js2-error-node))
9295 ((= tt js2-EOF)
9296 (let* ((px-pos (point-at-bol))
9297 (len (- js2-ts-cursor px-pos)))
9298 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9299 (make-js2-error-node :pos (1- js2-ts-cursor)))
9300 (t
9301 (js2-report-error "msg.syntax")
9302 (make-js2-error-node)))))
9303
9304 (defun js2-parse-name (_tt)
9305 (let ((name (js2-current-token-string))
9306 node)
9307 (setq node (if js2-compiler-xml-available
9308 (js2-parse-property-name nil name 0)
9309 (js2-create-name-node 'check-activation nil name)))
9310 (if js2-highlight-external-variables
9311 (js2-record-name-node node))
9312 node))
9313
9314 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9315 (js2-add-strict-warning
9316 msg nil
9317 ;; back up from comma to beginning of line or array/objlit
9318 (max (if elems
9319 (js2-node-pos (car elems))
9320 pos)
9321 (save-excursion
9322 (goto-char comma-pos)
9323 (back-to-indentation)
9324 (point)))
9325 comma-pos))
9326
9327 (defun js2-parse-array-comp-or-literal ()
9328 (let ((pos (js2-current-token-beg)))
9329 (if (and (>= js2-language-version 200)
9330 (js2-match-token js2-FOR))
9331 (js2-parse-array-comp pos)
9332 (js2-parse-array-literal pos))))
9333
9334 (defun js2-parse-array-literal (pos)
9335 (let ((after-lb-or-comma t)
9336 after-comma tt elems pn
9337 (continue t))
9338 (unless js2-is-in-destructuring
9339 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9340 (while continue
9341 (setq tt (js2-get-token))
9342 (cond
9343 ;; comma
9344 ((= tt js2-COMMA)
9345 (setq after-comma (js2-current-token-end))
9346 (if (not after-lb-or-comma)
9347 (setq after-lb-or-comma t)
9348 (push nil elems)))
9349 ;; end of array
9350 ((or (= tt js2-RB)
9351 (= tt js2-EOF)) ; prevent infinite loop
9352 (if (= tt js2-EOF)
9353 (js2-report-error "msg.no.bracket.arg" nil pos))
9354 (when (and after-comma (< js2-language-version 170))
9355 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9356 pos (remove nil elems) after-comma))
9357 (setq continue nil
9358 pn (make-js2-array-node :pos pos
9359 :len (- js2-ts-cursor pos)
9360 :elems (nreverse elems)))
9361 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9362 ;; destructuring binding
9363 (js2-is-in-destructuring
9364 (push (if (or (= tt js2-LC)
9365 (= tt js2-LB)
9366 (= tt js2-NAME))
9367 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9368 (js2-parse-destruct-primary-expr)
9369 ;; invalid pattern
9370 (js2-report-error "msg.bad.var")
9371 (make-js2-error-node))
9372 elems)
9373 (setq after-lb-or-comma nil
9374 after-comma nil))
9375 ;; array comp
9376 ((and (>= js2-language-version 170)
9377 (= tt js2-FOR) ; check for array comprehension
9378 (not after-lb-or-comma) ; "for" can't follow a comma
9379 elems ; must have at least 1 element
9380 (not (cdr elems))) ; but no 2nd element
9381 (js2-unget-token)
9382 (setf continue nil
9383 pn (js2-parse-legacy-array-comp (car elems) pos)))
9384 ;; another element
9385 (t
9386 (unless after-lb-or-comma
9387 (js2-report-error "msg.no.bracket.arg"))
9388 (if (and (= tt js2-TRIPLEDOT)
9389 (>= js2-language-version 200))
9390 ;; spread operator
9391 (push (js2-make-unary tt 'js2-parse-assign-expr)
9392 elems)
9393 (js2-unget-token)
9394 (push (js2-parse-assign-expr) elems))
9395 (setq after-lb-or-comma nil
9396 after-comma nil))))
9397 (unless js2-is-in-destructuring
9398 (js2-pop-scope))
9399 pn))
9400
9401 (defun js2-parse-legacy-array-comp (expr pos)
9402 "Parse a legacy array comprehension (JavaScript 1.7).
9403 EXPR is the first expression after the opening left-bracket.
9404 POS is the beginning of the LB token preceding EXPR.
9405 We should have just parsed the 'for' keyword before calling this function."
9406 (let ((current-scope js2-current-scope)
9407 loops first filter result)
9408 (unwind-protect
9409 (progn
9410 (while (js2-match-token js2-FOR)
9411 (let ((loop (make-js2-comp-loop-node)))
9412 (js2-push-scope loop)
9413 (push loop loops)
9414 (js2-parse-comp-loop loop)))
9415 ;; First loop takes expr scope's parent.
9416 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9417 (js2-scope-parent-scope current-scope))
9418 ;; Set expr scope's parent to the last loop.
9419 (setf (js2-scope-parent-scope current-scope) (car loops))
9420 (if (/= (js2-get-token) js2-IF)
9421 (js2-unget-token)
9422 (setq filter (js2-parse-condition))))
9423 (dotimes (_ (1- (length loops)))
9424 (js2-pop-scope)))
9425 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9426 (setq result (make-js2-comp-node :pos pos
9427 :len (- js2-ts-cursor pos)
9428 :result expr
9429 :loops (nreverse loops)
9430 :filters (and filter (list (car filter)))
9431 :form 'LEGACY_ARRAY))
9432 (apply #'js2-node-add-children result expr (car filter)
9433 (js2-comp-node-loops result))
9434 result))
9435
9436 (defun js2-parse-array-comp (pos)
9437 "Parse an ES6 array comprehension.
9438 POS is the beginning of the LB token.
9439 We should have just parsed the 'for' keyword before calling this function."
9440 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9441 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9442 pn))
9443
9444 (defun js2-parse-generator-comp (pos)
9445 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9446 (js2-current-script-or-fn
9447 (make-js2-function-node :generator-type 'COMPREHENSION))
9448 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9449 (js2-must-match js2-RP "msg.no.paren" pos)
9450 pn))
9451
9452 (defun js2-parse-comprehension (pos form)
9453 (let (loops filters expr result)
9454 (unwind-protect
9455 (progn
9456 (js2-unget-token)
9457 (while (js2-match-token js2-FOR)
9458 (let ((loop (make-js2-comp-loop-node)))
9459 (js2-push-scope loop)
9460 (push loop loops)
9461 (js2-parse-comp-loop loop)))
9462 (while (js2-match-token js2-IF)
9463 (push (car (js2-parse-condition)) filters))
9464 (setq expr (js2-parse-assign-expr)))
9465 (dolist (_ loops)
9466 (js2-pop-scope)))
9467 (setq result (make-js2-comp-node :pos pos
9468 :len (- js2-ts-cursor pos)
9469 :result expr
9470 :loops (nreverse loops)
9471 :filters (nreverse filters)
9472 :form form))
9473 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9474 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9475 result))
9476
9477 (defun js2-parse-comp-loop (pn &optional only-of-p)
9478 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9479 The current token should be the initial FOR.
9480 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9481 (let ((pos (js2-comp-loop-node-pos pn))
9482 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9483 (when (and (not only-of-p) (js2-match-token js2-NAME))
9484 (if (string= (js2-current-token-string) "each")
9485 (progn
9486 (setq foreach-p t
9487 each-pos (- (js2-current-token-beg) pos)) ; relative
9488 (js2-record-face 'font-lock-keyword-face))
9489 (js2-report-error "msg.no.paren.for")))
9490 (if (js2-must-match js2-LP "msg.no.paren.for")
9491 (setq lp (- (js2-current-token-beg) pos)))
9492 (setq tt (js2-peek-token))
9493 (cond
9494 ((or (= tt js2-LB)
9495 (= tt js2-LC))
9496 (js2-get-token)
9497 (setq iter (js2-parse-destruct-primary-expr))
9498 (js2-define-destruct-symbols iter js2-LET
9499 'font-lock-variable-name-face t))
9500 ((js2-match-token js2-NAME)
9501 (setq iter (js2-create-name-node)))
9502 (t
9503 (js2-report-error "msg.bad.var")))
9504 ;; Define as a let since we want the scope of the variable to
9505 ;; be restricted to the array comprehension
9506 (if (js2-name-node-p iter)
9507 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9508 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9509 (and (>= js2-language-version 200)
9510 (js2-match-contextual-kwd "of")
9511 (setq forof-p t)))
9512 (setq in-pos (- (js2-current-token-beg) pos))
9513 (js2-report-error "msg.in.after.for.name"))
9514 (setq obj (js2-parse-expr))
9515 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9516 (setq rp (- (js2-current-token-beg) pos)))
9517 (setf (js2-node-pos pn) pos
9518 (js2-node-len pn) (- js2-ts-cursor pos)
9519 (js2-comp-loop-node-iterator pn) iter
9520 (js2-comp-loop-node-object pn) obj
9521 (js2-comp-loop-node-in-pos pn) in-pos
9522 (js2-comp-loop-node-each-pos pn) each-pos
9523 (js2-comp-loop-node-foreach-p pn) foreach-p
9524 (js2-comp-loop-node-forof-p pn) forof-p
9525 (js2-comp-loop-node-lp pn) lp
9526 (js2-comp-loop-node-rp pn) rp)
9527 (js2-node-add-children pn iter obj)
9528 pn))
9529
9530 (defun js2-parse-object-literal ()
9531 (let ((pos (js2-current-token-beg))
9532 tt elems result after-comma
9533 (continue t))
9534 (while continue
9535 (setq tt (js2-get-token))
9536 (cond
9537 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9538 ;; {get foo() {...}}, or {set foo(x) {...}}
9539 ((or (js2-valid-prop-name-token tt)
9540 (= tt js2-STRING))
9541 (setq after-comma nil
9542 result (js2-parse-named-prop tt))
9543 (if (and (null result)
9544 (not js2-recover-from-parse-errors))
9545 (setq continue nil)
9546 (push result elems)))
9547 ;; {12: x} or {10.7: x}
9548 ((= tt js2-NUMBER)
9549 (setq after-comma nil)
9550 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9551 ;; trailing comma
9552 ((= tt js2-RC)
9553 (js2-unget-token)
9554 (setq continue nil)
9555 (if after-comma
9556 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9557 pos elems after-comma)))
9558 (t
9559 (js2-report-error "msg.bad.prop")
9560 (unless js2-recover-from-parse-errors
9561 (setq continue nil)))) ; end switch
9562 (if (js2-match-token js2-COMMA)
9563 (setq after-comma (js2-current-token-end))
9564 (setq continue nil))) ; end loop
9565 (js2-must-match js2-RC "msg.no.brace.prop")
9566 (setq result (make-js2-object-node :pos pos
9567 :len (- js2-ts-cursor pos)
9568 :elems (nreverse elems)))
9569 (apply #'js2-node-add-children result (js2-object-node-elems result))
9570 result))
9571
9572 (defun js2-parse-named-prop (tt)
9573 "Parse a name, string, or getter/setter object property.
9574 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9575 (let ((string-prop (and (= tt js2-STRING)
9576 (make-js2-string-node)))
9577 expr
9578 (ppos (js2-current-token-beg))
9579 (pend (js2-current-token-end))
9580 (name (js2-create-name-node))
9581 (prop (js2-current-token-string)))
9582 (cond
9583 ;; getter/setter prop
9584 ((and (= tt js2-NAME)
9585 (= (js2-peek-token) js2-NAME)
9586 (or (string= prop "get")
9587 (string= prop "set")))
9588 (js2-get-token)
9589 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9590 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9591 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9592 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9593 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9594 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9595 ;; when patterns are used in variable declarations, function parameters,
9596 ;; catch-clause, and iterators.
9597 ;; We have to set `js2-is-in-destructuring' to t when the current
9598 ;; expressions are on the left side of any assignment, but it's difficult
9599 ;; because it requires looking ahead of expression.
9600 ((and js2-is-in-destructuring
9601 (= tt js2-NAME)
9602 (let ((ctk (js2-peek-token)))
9603 (or (= ctk js2-COMMA)
9604 (= ctk js2-RC)
9605 (js2-valid-prop-name-token ctk))))
9606 name)
9607 ;; regular prop
9608 (t
9609 (prog1
9610 (setq expr (js2-parse-plain-property (or string-prop name)))
9611 (js2-set-face ppos pend
9612 (if (js2-function-node-p
9613 (js2-object-prop-node-right expr))
9614 'font-lock-function-name-face
9615 'font-lock-variable-name-face)
9616 'record))))))
9617
9618 (defun js2-parse-plain-property (prop)
9619 "Parse a non-getter/setter property in an object literal.
9620 PROP is the node representing the property: a number, name or string."
9621 (let ((pos (js2-node-pos prop))
9622 colon expr)
9623 (if (js2-must-match js2-COLON "msg.no.colon.prop")
9624 (setq colon (- (js2-current-token-beg) pos)
9625 expr (js2-parse-assign-expr))
9626 (setq expr (make-js2-error-node)))
9627 (let ((result (make-js2-object-prop-node
9628 :pos pos
9629 ;; don't include last consumed token in length
9630 :len (- (+ (js2-node-pos expr)
9631 (js2-node-len expr))
9632 pos)
9633 :left prop
9634 :right expr
9635 :op-pos colon)))
9636 (js2-node-add-children result prop expr)
9637 result)))
9638
9639 (defun js2-parse-getter-setter-prop (pos prop get-p)
9640 "Parse getter or setter property in an object literal.
9641 JavaScript syntax is:
9642
9643 { get foo() {...}, set foo(x) {...} }
9644
9645 and expression closure style is also supported
9646
9647 { get foo() x, set foo(x) _x = x }
9648
9649 POS is the start position of the `get' or `set' keyword.
9650 PROP is the `js2-name-node' representing the property name.
9651 GET-P is non-nil if the keyword was `get'."
9652 (let ((type (if get-p js2-GET js2-SET))
9653 result end
9654 (fn (js2-parse-function-expr)))
9655 ;; it has to be an anonymous function, as we already parsed the name
9656 (if (/= (js2-node-type fn) js2-FUNCTION)
9657 (js2-report-error "msg.bad.prop")
9658 (if (plusp (length (js2-function-name fn)))
9659 (js2-report-error "msg.bad.prop")))
9660 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9661 (setq end (js2-node-end fn)
9662 result (make-js2-getter-setter-node :type type
9663 :pos pos
9664 :len (- end pos)
9665 :left prop
9666 :right fn))
9667 (js2-node-add-children result prop fn)
9668 result))
9669
9670 (defun js2-create-name-node (&optional check-activation-p token string)
9671 "Create a name node using the current token and, optionally, STRING.
9672 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9673 (let* ((beg (js2-current-token-beg))
9674 (tt (js2-current-token-type))
9675 (s (or string
9676 (if (= js2-NAME tt)
9677 (js2-current-token-string)
9678 (js2-tt-name tt))))
9679 name)
9680 (setq name (make-js2-name-node :pos beg
9681 :name s
9682 :len (length s)))
9683 (if check-activation-p
9684 (js2-check-activation-name s (or token js2-NAME)))
9685 name))
9686
9687 ;;; Indentation support
9688
9689 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9690 ;; Karl cleverly deduces that the desired indentation level is often a
9691 ;; function of paren/bracket/brace nesting depth, which can be determined
9692 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9693 ;; then does some equally clever checks to see if we're in the context of a
9694 ;; substatement of a possibly braceless statement keyword such as if, while,
9695 ;; or finally. This approach yields pretty good results.
9696
9697 ;; The indenter is often "wrong", however, and needs to be overridden.
9698 ;; The right long-term solution is probably to emulate (or integrate
9699 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9700 ;; parse tree from `js2-parse' is present, which is not true at the
9701 ;; moment the user is typing, computing indentation is still thousands
9702 ;; of lines of code to handle every possible syntactic edge case.
9703
9704 ;; In the meantime, the compromise solution is that we offer a "bounce
9705 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9706 ;; current line indent among various likely guess points. This approach
9707 ;; is far from perfect, but should at least make it slightly easier to
9708 ;; move the line towards its desired indentation when manually
9709 ;; overriding Karl's heuristic nesting guesser.
9710
9711 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9712 ;; extensions such as `let' and Array comprehensions. Major kudos to
9713 ;; Karl for coming up with the initial approach, which packs a lot of
9714 ;; punch for so little code.
9715
9716 (defconst js2-possibly-braceless-keywords-re
9717 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9718 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9719 "try" "while" "with" "let")))
9720 "Regular expression matching keywords that are optionally
9721 followed by an opening brace.")
9722
9723 (defconst js2-indent-operator-re
9724 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9725 (regexp-opt '("in" "instanceof") 'words))
9726 "Regular expression matching operators that affect indentation
9727 of continued expressions.")
9728
9729 (defconst js2-declaration-keyword-re
9730 (regexp-opt '("var" "let" "const") 'words)
9731 "Regular expression matching variable declaration keywords.")
9732
9733 (defun js2-re-search-forward-inner (regexp &optional bound count)
9734 "Auxiliary function for `js2-re-search-forward'."
9735 (let (parse saved-point)
9736 (while (> count 0)
9737 (re-search-forward regexp bound)
9738 (setq parse (if saved-point
9739 (parse-partial-sexp saved-point (point))
9740 (syntax-ppss (point))))
9741 (cond ((nth 3 parse)
9742 (re-search-forward
9743 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9744 (save-excursion (end-of-line) (point)) t))
9745 ((nth 7 parse)
9746 (forward-line))
9747 ((or (nth 4 parse)
9748 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9749 (re-search-forward "\\*/"))
9750 (t
9751 (setq count (1- count))))
9752 (setq saved-point (point))))
9753 (point))
9754
9755 (defun js2-re-search-forward (regexp &optional bound noerror count)
9756 "Search forward but ignore strings and comments.
9757 Invokes `re-search-forward' but treats the buffer as if strings
9758 and comments have been removed."
9759 (let ((saved-point (point)))
9760 (condition-case err
9761 (cond ((null count)
9762 (js2-re-search-forward-inner regexp bound 1))
9763 ((< count 0)
9764 (js2-re-search-backward-inner regexp bound (- count)))
9765 ((> count 0)
9766 (js2-re-search-forward-inner regexp bound count)))
9767 (search-failed
9768 (goto-char saved-point)
9769 (unless noerror
9770 (error (error-message-string err)))))))
9771
9772 (defun js2-re-search-backward-inner (regexp &optional bound count)
9773 "Auxiliary function for `js2-re-search-backward'."
9774 (let (parse)
9775 (while (> count 0)
9776 (re-search-backward regexp bound)
9777 (setq parse (syntax-ppss (point)))
9778 (cond ((nth 3 parse)
9779 (re-search-backward
9780 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9781 (line-beginning-position) t))
9782 ((nth 7 parse)
9783 (goto-char (nth 8 parse)))
9784 ((or (nth 4 parse)
9785 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9786 (re-search-backward "/\\*"))
9787 (t
9788 (setq count (1- count))))))
9789 (point))
9790
9791 (defun js2-re-search-backward (regexp &optional bound noerror count)
9792 "Search backward but ignore strings and comments.
9793 Invokes `re-search-backward' but treats the buffer as if strings
9794 and comments have been removed."
9795 (let ((saved-point (point)))
9796 (condition-case err
9797 (cond ((null count)
9798 (js2-re-search-backward-inner regexp bound 1))
9799 ((< count 0)
9800 (js2-re-search-forward-inner regexp bound (- count)))
9801 ((> count 0)
9802 (js2-re-search-backward-inner regexp bound count)))
9803 (search-failed
9804 (goto-char saved-point)
9805 (unless noerror
9806 (error (error-message-string err)))))))
9807
9808 (defun js2-looking-at-operator-p ()
9809 "Return non-nil if text after point is a non-comma operator."
9810 (and (looking-at js2-indent-operator-re)
9811 (or (not (looking-at ":"))
9812 (save-excursion
9813 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9814 (looking-at "?"))))))
9815
9816 (defun js2-continued-expression-p ()
9817 "Return non-nil if the current line continues an expression."
9818 (save-excursion
9819 (back-to-indentation)
9820 (or (js2-looking-at-operator-p)
9821 (when (catch 'found
9822 (while (and (re-search-backward "\n" nil t)
9823 (let ((state (syntax-ppss)))
9824 (when (nth 4 state)
9825 (goto-char (nth 8 state))) ;; skip comments
9826 (skip-chars-backward " \t")
9827 (if (bolp)
9828 t
9829 (throw 'found t))))))
9830 (backward-char)
9831 (when (js2-looking-at-operator-p)
9832 (backward-char)
9833 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9834
9835 (defun js2-end-of-do-while-loop-p ()
9836 "Return non-nil if word after point is `while' of a do-while
9837 statement, else returns nil. A braceless do-while statement
9838 spanning several lines requires that the start of the loop is
9839 indented to the same column as the current line."
9840 (interactive)
9841 (save-excursion
9842 (when (looking-at "\\s-*\\<while\\>")
9843 (if (save-excursion
9844 (skip-chars-backward "[ \t\n]*}")
9845 (looking-at "[ \t\n]*}"))
9846 (save-excursion
9847 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9848 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9849 (or (looking-at "\\<do\\>")
9850 (let ((saved-indent (current-indentation)))
9851 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9852 (/= (current-indentation) saved-indent)))
9853 (and (looking-at "[ \t]*\\<do\\>")
9854 (not (js2-re-search-forward
9855 "\\<while\\>" (point-at-eol) t))
9856 (= (current-indentation) saved-indent))))))))
9857
9858 (defun js2-multiline-decl-indentation ()
9859 "Return the declaration indentation column if the current line belongs
9860 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9861 (let (forward-sexp-function ; use Lisp version
9862 at-opening-bracket)
9863 (save-excursion
9864 (back-to-indentation)
9865 (when (not (looking-at js2-declaration-keyword-re))
9866 (when (looking-at js2-indent-operator-re)
9867 (goto-char (match-end 0))) ; continued expressions are ok
9868 (while (and (not at-opening-bracket)
9869 (not (bobp))
9870 (let ((pos (point)))
9871 (save-excursion
9872 (js2-backward-sws)
9873 (or (eq (char-before) ?,)
9874 (and (not (eq (char-before) ?\;))
9875 (prog2 (skip-syntax-backward ".")
9876 (looking-at js2-indent-operator-re)
9877 (js2-backward-sws))
9878 (not (eq (char-before) ?\;)))
9879 (js2-same-line pos)))))
9880 (condition-case _
9881 (backward-sexp)
9882 (scan-error (setq at-opening-bracket t))))
9883 (when (looking-at js2-declaration-keyword-re)
9884 (goto-char (match-end 0))
9885 (1+ (current-column)))))))
9886
9887 (defun js2-ctrl-statement-indentation ()
9888 "Return the proper indentation of current line if it is a control statement.
9889 Returns an indentation if this line starts the body of a control
9890 statement without braces, else returns nil."
9891 (let (forward-sexp-function)
9892 (save-excursion
9893 (back-to-indentation)
9894 (when (and (not (js2-same-line (point-min)))
9895 (not (looking-at "{"))
9896 (js2-re-search-backward "[[:graph:]]" nil t)
9897 (not (looking-at "[{([]"))
9898 (progn
9899 (forward-char)
9900 (when (= (char-before) ?\))
9901 ;; scan-sexps sometimes throws an error
9902 (ignore-errors (backward-sexp))
9903 (skip-chars-backward " \t" (point-at-bol)))
9904 (let ((pt (point)))
9905 (back-to-indentation)
9906 (when (looking-at "}[ \t]*")
9907 (goto-char (match-end 0)))
9908 (and (looking-at js2-possibly-braceless-keywords-re)
9909 (= (match-end 0) pt)
9910 (not (js2-end-of-do-while-loop-p))))))
9911 (+ (current-indentation) js2-basic-offset)))))
9912
9913 (defun js2-indent-in-array-comp (parse-status)
9914 "Return non-nil if we think we're in an array comprehension.
9915 In particular, return the buffer position of the first `for' kwd."
9916 (let ((bracket (nth 1 parse-status))
9917 (end (point)))
9918 (when bracket
9919 (save-excursion
9920 (goto-char bracket)
9921 (when (looking-at "\\[")
9922 (forward-char 1)
9923 (js2-forward-sws)
9924 (if (looking-at "[[{]")
9925 (let (forward-sexp-function) ; use Lisp version
9926 (forward-sexp) ; skip destructuring form
9927 (js2-forward-sws)
9928 (if (and (/= (char-after) ?,) ; regular array
9929 (looking-at "for"))
9930 (match-beginning 0)))
9931 ;; to skip arbitrary expressions we need the parser,
9932 ;; so we'll just guess at it.
9933 (if (and (> end (point)) ; not empty literal
9934 (re-search-forward "[^,]]* \\(for\\) " end t)
9935 ;; not inside comment or string literal
9936 (let ((state (parse-partial-sexp bracket (point))))
9937 (not (or (nth 3 state) (nth 4 state)))))
9938 (match-beginning 1))))))))
9939
9940 (defun js2-array-comp-indentation (parse-status for-kwd)
9941 (if (js2-same-line for-kwd)
9942 ;; first continuation line
9943 (save-excursion
9944 (goto-char (nth 1 parse-status))
9945 (forward-char 1)
9946 (skip-chars-forward " \t")
9947 (current-column))
9948 (save-excursion
9949 (goto-char for-kwd)
9950 (current-column))))
9951
9952 (defun js2-proper-indentation (parse-status)
9953 "Return the proper indentation for the current line."
9954 (save-excursion
9955 (back-to-indentation)
9956 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9957 (at-closing-bracket (looking-at "[]})]"))
9958 (same-indent-p (or at-closing-bracket
9959 (looking-at "\\<case\\>[^:]")
9960 (and (looking-at "\\<default:")
9961 (save-excursion
9962 (js2-backward-sws)
9963 (not (memq (char-before) '(?, ?{)))))))
9964 (continued-expr-p (js2-continued-expression-p))
9965 (declaration-indent (and js2-pretty-multiline-declarations
9966 (js2-multiline-decl-indentation)))
9967 (bracket (nth 1 parse-status))
9968 beg indent)
9969 (cond
9970 ;; indent array comprehension continuation lines specially
9971 ((and bracket
9972 (>= js2-language-version 170)
9973 (not (js2-same-line bracket))
9974 (setq beg (js2-indent-in-array-comp parse-status))
9975 (>= (point) (save-excursion
9976 (goto-char beg)
9977 (point-at-bol)))) ; at or after first loop?
9978 (js2-array-comp-indentation parse-status beg))
9979
9980 (ctrl-stmt-indent)
9981
9982 ((and declaration-indent continued-expr-p)
9983 (+ declaration-indent js2-basic-offset))
9984
9985 (declaration-indent)
9986
9987 (bracket
9988 (goto-char bracket)
9989 (cond
9990 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9991 (when (save-excursion (skip-chars-backward " \t)")
9992 (looking-at ")"))
9993 (backward-list))
9994 (back-to-indentation)
9995 (and (eq js2-pretty-multiline-declarations 'all)
9996 (looking-at js2-declaration-keyword-re)
9997 (goto-char (1+ (match-end 0))))
9998 (setq indent
9999 (cond (same-indent-p
10000 (current-column))
10001 (continued-expr-p
10002 (+ (current-column) (* 2 js2-basic-offset)))
10003 (t
10004 (+ (current-column) js2-basic-offset))))
10005 (if (and js2-indent-switch-body
10006 (not at-closing-bracket)
10007 (looking-at "\\_<switch\\_>"))
10008 (+ indent js2-basic-offset)
10009 indent))
10010 (t
10011 (unless same-indent-p
10012 (forward-char)
10013 (skip-chars-forward " \t"))
10014 (current-column))))
10015
10016 (continued-expr-p js2-basic-offset)
10017
10018 (t 0)))))
10019
10020 (defun js2-lineup-comment (parse-status)
10021 "Indent a multi-line block comment continuation line."
10022 (let* ((beg (nth 8 parse-status))
10023 (first-line (js2-same-line beg))
10024 (offset (save-excursion
10025 (goto-char beg)
10026 (if (looking-at "/\\*")
10027 (+ 1 (current-column))
10028 0))))
10029 (unless first-line
10030 (indent-line-to offset))))
10031
10032 (defun js2-backward-sws ()
10033 "Move backward through whitespace and comments."
10034 (interactive)
10035 (while (forward-comment -1)))
10036
10037 (defun js2-forward-sws ()
10038 "Move forward through whitespace and comments."
10039 (interactive)
10040 (while (forward-comment 1)))
10041
10042 (defun js2-current-indent (&optional pos)
10043 "Return column of indentation on current line.
10044 If POS is non-nil, go to that point and return indentation for that line."
10045 (save-excursion
10046 (if pos
10047 (goto-char pos))
10048 (back-to-indentation)
10049 (current-column)))
10050
10051 (defun js2-arglist-close ()
10052 "Return non-nil if we're on a line beginning with a close-paren/brace."
10053 (save-excursion
10054 (goto-char (point-at-bol))
10055 (js2-forward-sws)
10056 (looking-at "[])}]")))
10057
10058 (defun js2-indent-looks-like-label-p ()
10059 (goto-char (point-at-bol))
10060 (js2-forward-sws)
10061 (looking-at (concat js2-mode-identifier-re ":")))
10062
10063 (defun js2-indent-in-objlit-p (parse-status)
10064 "Return non-nil if this looks like an object-literal entry."
10065 (let ((start (nth 1 parse-status)))
10066 (and
10067 start
10068 (save-excursion
10069 (and (zerop (forward-line -1))
10070 (not (< (point) start)) ; crossed a {} boundary
10071 (js2-indent-looks-like-label-p)))
10072 (save-excursion
10073 (js2-indent-looks-like-label-p)))))
10074
10075 ;; If prev line looks like foobar({ then we're passing an object
10076 ;; literal to a function call, and people pretty much always want to
10077 ;; de-dent back to the previous line, so move the 'basic-offset'
10078 ;; position to the front.
10079 (defun js2-indent-objlit-arg-p (parse-status)
10080 (save-excursion
10081 (back-to-indentation)
10082 (js2-backward-sws)
10083 (and (eq (1- (point)) (nth 1 parse-status))
10084 (eq (char-before) ?{)
10085 (progn
10086 (forward-char -1)
10087 (skip-chars-backward " \t")
10088 (eq (char-before) ?\()))))
10089
10090 (defun js2-indent-case-block-p ()
10091 (save-excursion
10092 (back-to-indentation)
10093 (js2-backward-sws)
10094 (goto-char (point-at-bol))
10095 (skip-chars-forward " \t")
10096 (looking-at "case\\s-.+:")))
10097
10098 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10099 "Cycle among alternate computed indentation positions.
10100 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10101 of the buffer to the current point. NORMAL-COL is the indentation
10102 column computed by the heuristic guesser based on current paren,
10103 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10104 in reverse."
10105 (let ((cur-indent (js2-current-indent))
10106 (old-buffer-undo-list buffer-undo-list)
10107 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10108 (current-line (save-excursion
10109 (forward-line 0) ; move to bol
10110 (1+ (count-lines (point-min) (point)))))
10111 positions pos main-pos anchor arglist-cont same-indent
10112 basic-offset computed-pos)
10113 ;; temporarily don't record undo info, if user requested this
10114 (when js2-mode-indent-inhibit-undo
10115 (setq buffer-undo-list t))
10116 (unwind-protect
10117 (progn
10118 ;; First likely point: indent from beginning of previous code line
10119 (push (setq basic-offset
10120 (+ (save-excursion
10121 (back-to-indentation)
10122 (js2-backward-sws)
10123 (back-to-indentation)
10124 (current-column))
10125 js2-basic-offset))
10126 positions)
10127
10128 ;; (First + epsilon) likely point: indent 2x from beginning of
10129 ;; previous code line. Google does it this way.
10130 (push (setq basic-offset
10131 (+ (save-excursion
10132 (back-to-indentation)
10133 (js2-backward-sws)
10134 (back-to-indentation)
10135 (current-column))
10136 (* 2 js2-basic-offset)))
10137 positions)
10138
10139 ;; Second likely point: indent from assign-expr RHS. This
10140 ;; is just a crude guess based on finding " = " on the previous
10141 ;; line containing actual code.
10142 (setq pos (save-excursion
10143 (forward-line -1)
10144 (goto-char (point-at-bol))
10145 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10146 (point-at-eol) t)
10147 (goto-char (match-end 1))
10148 (skip-chars-forward " \t\r\n")
10149 (current-column))))
10150 (when pos
10151 (incf pos js2-basic-offset)
10152 (push pos positions))
10153
10154 ;; Third likely point: same indent as previous line of code.
10155 ;; Make it the first likely point if we're not on an
10156 ;; arglist-close line and previous line ends in a comma, or
10157 ;; both this line and prev line look like object-literal
10158 ;; elements.
10159 (setq pos (save-excursion
10160 (goto-char (point-at-bol))
10161 (js2-backward-sws)
10162 (back-to-indentation)
10163 (prog1
10164 (current-column)
10165 ;; while we're here, look for trailing comma
10166 (if (save-excursion
10167 (goto-char (point-at-eol))
10168 (js2-backward-sws)
10169 (eq (char-before) ?,))
10170 (setq arglist-cont (1- (point)))))))
10171 (when pos
10172 (if (and (or arglist-cont
10173 (js2-indent-in-objlit-p parse-status))
10174 (not (js2-arglist-close)))
10175 (setq same-indent pos))
10176 (push pos positions))
10177
10178 ;; Fourth likely point: first preceding code with less indentation.
10179 ;; than the immediately preceding code line.
10180 (setq pos (save-excursion
10181 (back-to-indentation)
10182 (js2-backward-sws)
10183 (back-to-indentation)
10184 (setq anchor (current-column))
10185 (while (and (zerop (forward-line -1))
10186 (>= (progn
10187 (back-to-indentation)
10188 (current-column))
10189 anchor)))
10190 (setq pos (current-column))))
10191 (push pos positions)
10192
10193 ;; nesting-heuristic position, main by default
10194 (push (setq main-pos normal-col) positions)
10195
10196 ;; delete duplicates and sort positions list
10197 (setq positions (sort (delete-dups positions) '<))
10198
10199 ;; comma-list continuation lines: prev line indent takes precedence
10200 (if same-indent
10201 (setq main-pos same-indent))
10202
10203 ;; common special cases where we want to indent in from previous line
10204 (if (or (js2-indent-case-block-p)
10205 (js2-indent-objlit-arg-p parse-status))
10206 (setq main-pos basic-offset))
10207
10208 ;; if bouncing backwards, reverse positions list
10209 (if backwards
10210 (setq positions (reverse positions)))
10211
10212 ;; record whether we're already sitting on one of the alternatives
10213 (setq pos (member cur-indent positions))
10214
10215 (cond
10216 ;; case 0: we're one one of the alternatives and this is the
10217 ;; first time they've pressed TAB on this line (best-guess).
10218 ((and js2-mode-indent-ignore-first-tab
10219 pos
10220 ;; first time pressing TAB on this line?
10221 (not (eq js2-mode-last-indented-line current-line)))
10222 ;; do nothing
10223 (setq computed-pos nil))
10224 ;; case 1: only one computed position => use it
10225 ((null (cdr positions))
10226 (setq computed-pos 0))
10227 ;; case 2: not on any of the computed spots => use main spot
10228 ((not pos)
10229 (setq computed-pos (js2-position main-pos positions)))
10230 ;; case 3: on last position: cycle to first position
10231 ((null (cdr pos))
10232 (setq computed-pos 0))
10233 ;; case 4: on intermediate position: cycle to next position
10234 (t
10235 (setq computed-pos (js2-position (second pos) positions))))
10236
10237 ;; see if any hooks want to indent; otherwise we do it
10238 (loop with result = nil
10239 for hook in js2-indent-hook
10240 while (null result)
10241 do
10242 (setq result (funcall hook positions computed-pos))
10243 finally do
10244 (unless (or result (null computed-pos))
10245 (indent-line-to (nth computed-pos positions)))))
10246
10247 ;; finally
10248 (if js2-mode-indent-inhibit-undo
10249 (setq buffer-undo-list old-buffer-undo-list))
10250 ;; see commentary for `js2-mode-last-indented-line'
10251 (setq js2-mode-last-indented-line current-line))))
10252
10253 (defun js2-indent-bounce-backwards ()
10254 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10255 cycles between the computed indentation positions in reverse order."
10256 (interactive)
10257 (js2-indent-line t))
10258
10259 (defun js2-1-line-comment-continuation-p ()
10260 "Return t if we're in a 1-line comment continuation.
10261 If so, we don't ever want to use bounce-indent."
10262 (save-excursion
10263 (and (progn
10264 (forward-line 0)
10265 (looking-at "\\s-*//"))
10266 (progn
10267 (forward-line -1)
10268 (forward-line 0)
10269 (when (looking-at "\\s-*$")
10270 (js2-backward-sws)
10271 (forward-line 0))
10272 (looking-at "\\s-*//")))))
10273
10274 (defun js2-indent-line (&optional bounce-backwards)
10275 "Indent the current line as JavaScript source text."
10276 (interactive)
10277 (let (parse-status offset indent-col
10278 ;; Don't whine about errors/warnings when we're indenting.
10279 ;; This has to be set before calling parse-partial-sexp below.
10280 (inhibit-point-motion-hooks t))
10281 (setq parse-status (save-excursion
10282 (syntax-ppss (point-at-bol)))
10283 offset (- (point) (save-excursion
10284 (back-to-indentation)
10285 (point))))
10286 (js2-with-underscore-as-word-syntax
10287 (if (nth 4 parse-status)
10288 (js2-lineup-comment parse-status)
10289 (setq indent-col (js2-proper-indentation parse-status))
10290 ;; See comments below about `js2-mode-last-indented-line'.
10291 (cond
10292 ;; bounce-indenting is disabled during electric-key indent.
10293 ;; It doesn't work well on first line of buffer.
10294 ((and js2-bounce-indent-p
10295 (not (js2-same-line (point-min)))
10296 (not (js2-1-line-comment-continuation-p)))
10297 (js2-bounce-indent indent-col parse-status bounce-backwards))
10298 ;; just indent to the guesser's likely spot
10299 (t (indent-line-to indent-col))))
10300 (when (plusp offset)
10301 (forward-char offset)))))
10302
10303 (defun js2-indent-region (start end)
10304 "Indent the region, but don't use bounce indenting."
10305 (let ((js2-bounce-indent-p nil)
10306 (indent-region-function nil)
10307 (after-change-functions (remq 'js2-mode-edit
10308 after-change-functions)))
10309 (indent-region start end nil) ; nil for byte-compiler
10310 (js2-mode-edit start end (- end start))))
10311
10312 (defvar js2-minor-mode-map
10313 (let ((map (make-sparse-keymap)))
10314 (define-key map (kbd "C-c C-`") #'js2-next-error)
10315 (define-key map [mouse-1] #'js2-mode-show-node)
10316 map)
10317 "Keymap used when `js2-minor-mode' is active.")
10318
10319 ;;;###autoload
10320 (define-minor-mode js2-minor-mode
10321 "Minor mode for running js2 as a background linter.
10322 This allows you to use a different major mode for JavaScript editing,
10323 such as `js-mode', while retaining the asynchronous error/warning
10324 highlighting features of `js2-mode'."
10325 :group 'js2-mode
10326 :lighter " js-lint"
10327 (if js2-minor-mode
10328 (js2-minor-mode-enter)
10329 (js2-minor-mode-exit)))
10330
10331 (defun js2-minor-mode-enter ()
10332 "Initialization for `js2-minor-mode'."
10333 (set (make-local-variable 'max-lisp-eval-depth)
10334 (max max-lisp-eval-depth 3000))
10335 (setq next-error-function #'js2-next-error)
10336 (js2-set-default-externs)
10337 ;; Experiment: make reparse-delay longer for longer files.
10338 (if (plusp js2-dynamic-idle-timer-adjust)
10339 (setq js2-idle-timer-delay
10340 (* js2-idle-timer-delay
10341 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10342 (setq js2-mode-buffer-dirty-p t
10343 js2-mode-parsing nil)
10344 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10345 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10346 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10347 (when js2-include-jslint-globals
10348 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10349 (run-hooks 'js2-init-hook)
10350 (js2-reparse))
10351
10352 (defun js2-minor-mode-exit ()
10353 "Turn off `js2-minor-mode'."
10354 (setq next-error-function nil)
10355 (remove-hook 'after-change-functions #'js2-mode-edit t)
10356 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10357 (when js2-mode-node-overlay
10358 (delete-overlay js2-mode-node-overlay)
10359 (setq js2-mode-node-overlay nil))
10360 (js2-remove-overlays)
10361 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10362 (setq js2-mode-ast nil))
10363
10364 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10365 (make-variable-buffer-local 'js2-source-buffer)
10366
10367 (defun* js2-display-error-list ()
10368 "Display a navigable buffer listing parse errors/warnings."
10369 (interactive)
10370 (unless (js2-have-errors-p)
10371 (message "No errors")
10372 (return-from js2-display-error-list))
10373 (labels ((annotate-list
10374 (lst type)
10375 "Add diagnostic TYPE and line number to errs list"
10376 (mapcar (lambda (err)
10377 (list err type (line-number-at-pos (nth 1 err))))
10378 lst)))
10379 (let* ((srcbuf (current-buffer))
10380 (errbuf (get-buffer-create "*js-lint*"))
10381 (errors (annotate-list
10382 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10383 'js2-error)) ; must be a valid face name
10384 (warnings (annotate-list
10385 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10386 'js2-warning)) ; must be a valid face name
10387 (all-errs (sort (append errors warnings)
10388 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10389 (with-current-buffer errbuf
10390 (let ((inhibit-read-only t))
10391 (erase-buffer)
10392 (dolist (err all-errs)
10393 (destructuring-bind ((msg-key beg _end &rest) type line) err
10394 (insert-text-button
10395 (format "line %d: %s" line (js2-get-msg msg-key))
10396 'face type
10397 'follow-link "\C-m"
10398 'action 'js2-error-buffer-jump
10399 'js2-msg (js2-get-msg msg-key)
10400 'js2-pos beg)
10401 (insert "\n"))))
10402 (js2-error-buffer-mode)
10403 (setq js2-source-buffer srcbuf)
10404 (pop-to-buffer errbuf)
10405 (goto-char (point-min))
10406 (unless (eobp)
10407 (js2-error-buffer-view))))))
10408
10409 (defvar js2-error-buffer-mode-map
10410 (let ((map (make-sparse-keymap)))
10411 (define-key map "n" #'js2-error-buffer-next)
10412 (define-key map "p" #'js2-error-buffer-prev)
10413 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10414 (define-key map "o" #'js2-error-buffer-view)
10415 (define-key map "q" #'js2-error-buffer-quit)
10416 map)
10417 "Keymap used for js2 diagnostics buffers.")
10418
10419 (defun js2-error-buffer-mode ()
10420 "Major mode for js2 diagnostics buffers.
10421 Selecting an error will jump it to the corresponding source-buffer error.
10422 \\{js2-error-buffer-mode-map}"
10423 (interactive)
10424 (setq major-mode 'js2-error-buffer-mode
10425 mode-name "JS Lint Diagnostics")
10426 (use-local-map js2-error-buffer-mode-map)
10427 (setq truncate-lines t)
10428 (set-buffer-modified-p nil)
10429 (setq buffer-read-only t)
10430 (run-hooks 'js2-error-buffer-mode-hook))
10431
10432 (defun js2-error-buffer-next ()
10433 "Move to next error and view it."
10434 (interactive)
10435 (when (zerop (forward-line 1))
10436 (js2-error-buffer-view)))
10437
10438 (defun js2-error-buffer-prev ()
10439 "Move to previous error and view it."
10440 (interactive)
10441 (when (zerop (forward-line -1))
10442 (js2-error-buffer-view)))
10443
10444 (defun js2-error-buffer-quit ()
10445 "Kill the current buffer."
10446 (interactive)
10447 (kill-buffer))
10448
10449 (defun js2-error-buffer-jump (&rest ignored)
10450 "Jump cursor to current error in source buffer."
10451 (interactive)
10452 (when (js2-error-buffer-view)
10453 (pop-to-buffer js2-source-buffer)))
10454
10455 (defun js2-error-buffer-view ()
10456 "Scroll source buffer to show error at current line."
10457 (interactive)
10458 (cond
10459 ((not (eq major-mode 'js2-error-buffer-mode))
10460 (message "Not in a js2 errors buffer"))
10461 ((not (buffer-live-p js2-source-buffer))
10462 (message "Source buffer has been killed"))
10463 ((not (wholenump (get-text-property (point) 'js2-pos)))
10464 (message "There does not seem to be an error here"))
10465 (t
10466 (let ((pos (get-text-property (point) 'js2-pos))
10467 (msg (get-text-property (point) 'js2-msg)))
10468 (save-selected-window
10469 (pop-to-buffer js2-source-buffer)
10470 (goto-char pos)
10471 (message msg))))))
10472
10473 ;;;###autoload
10474 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10475 ;; FIXME: Should derive from js-mode.
10476 "Major mode for editing JavaScript code."
10477 ;; Used by comment-region; don't change it.
10478 (set (make-local-variable 'comment-start) "//")
10479 (set (make-local-variable 'comment-end) "")
10480 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10481 (set (make-local-variable 'max-lisp-eval-depth)
10482 (max max-lisp-eval-depth 3000))
10483 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10484 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10485 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10486 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10487 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10488 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10489 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10490 ;; for characters inside regexp literals.
10491 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10492 ;; this is necessary to make `show-paren-function' work properly
10493 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10494 ;; needed for M-x rgrep, among other things
10495 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10496
10497 (set (make-local-variable 'electric-indent-chars)
10498 (append "{}()[]:;,*." electric-indent-chars))
10499 (set (make-local-variable 'electric-layout-rules)
10500 '((?\; . after) (?\{ . after) (?\} . before)))
10501
10502 ;; some variables needed by cc-engine for paragraph-fill, etc.
10503 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10504 c-comment-start-regexp "/[*/]\\|\\s|"
10505 c-line-comment-starter "//"
10506 c-paragraph-start js2-paragraph-start
10507 c-paragraph-separate "$"
10508 c-syntactic-ws-start js2-syntactic-ws-start
10509 c-syntactic-ws-end js2-syntactic-ws-end
10510 c-syntactic-eol js2-syntactic-eol)
10511
10512 (let ((c-buffer-is-cc-mode t))
10513 ;; Copied from `js-mode'. Also see Bug#6071.
10514 (make-local-variable 'paragraph-start)
10515 (make-local-variable 'paragraph-separate)
10516 (make-local-variable 'paragraph-ignore-fill-prefix)
10517 (make-local-variable 'adaptive-fill-mode)
10518 (make-local-variable 'adaptive-fill-regexp)
10519 (c-setup-paragraph-variables))
10520
10521 (setq font-lock-defaults '(nil t))
10522
10523 ;; Experiment: make reparse-delay longer for longer files.
10524 (when (plusp js2-dynamic-idle-timer-adjust)
10525 (setq js2-idle-timer-delay
10526 (* js2-idle-timer-delay
10527 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10528
10529 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10530 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10531 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10532 (setq next-error-function #'js2-next-error)
10533 (imenu-add-to-menubar (concat "IM-" mode-name))
10534 (add-to-invisibility-spec '(js2-outline . t))
10535 (set (make-local-variable 'line-move-ignore-invisible) t)
10536 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10537
10538 (setq js2-mode-functions-hidden nil
10539 js2-mode-comments-hidden nil
10540 js2-mode-buffer-dirty-p t
10541 js2-mode-parsing nil)
10542
10543 (js2-set-default-externs)
10544
10545 (when js2-include-jslint-globals
10546 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10547
10548 (run-hooks 'js2-init-hook)
10549
10550 (js2-reparse))
10551
10552 (defun js2-mode-exit ()
10553 "Exit `js2-mode' and clean up."
10554 (interactive)
10555 (when js2-mode-node-overlay
10556 (delete-overlay js2-mode-node-overlay)
10557 (setq js2-mode-node-overlay nil))
10558 (js2-remove-overlays)
10559 (setq js2-mode-ast nil)
10560 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10561 (remove-from-invisibility-spec '(js2-outline . t))
10562 (js2-mode-show-all)
10563 (with-silent-modifications
10564 (js2-clear-face (point-min) (point-max))))
10565
10566 (defun js2-mode-reset-timer ()
10567 "Cancel any existing parse timer and schedule a new one."
10568 (if js2-mode-parse-timer
10569 (cancel-timer js2-mode-parse-timer))
10570 (setq js2-mode-parsing nil)
10571 (let ((timer (timer-create)))
10572 (setq js2-mode-parse-timer timer)
10573 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10574 (timer-set-idle-time timer js2-idle-timer-delay)
10575 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10576 (timer-activate-when-idle timer nil)))
10577
10578 (defun js2-mode-idle-reparse (buffer)
10579 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10580 it to be reparsed when the buffer is selected."
10581 (cond ((eq buffer (current-buffer))
10582 (js2-reparse))
10583 ((buffer-live-p buffer)
10584 ;; reparse when the buffer is selected again
10585 (with-current-buffer buffer
10586 (add-hook 'window-configuration-change-hook
10587 #'js2-mode-idle-reparse-inner
10588 nil t)))))
10589
10590 (defun js2-mode-idle-reparse-inner ()
10591 (remove-hook 'window-configuration-change-hook
10592 #'js2-mode-idle-reparse-inner
10593 t)
10594 (js2-reparse))
10595
10596 (defun js2-mode-edit (_beg _end _len)
10597 "Schedule a new parse after buffer is edited.
10598 Buffer edit spans from BEG to END and is of length LEN."
10599 (setq js2-mode-buffer-dirty-p t)
10600 (js2-mode-hide-overlay)
10601 (js2-mode-reset-timer))
10602
10603 (defun js2-minor-mode-edit (_beg _end _len)
10604 "Callback for buffer edits in `js2-mode'.
10605 Schedules a new parse after buffer is edited.
10606 Buffer edit spans from BEG to END and is of length LEN."
10607 (setq js2-mode-buffer-dirty-p t)
10608 (js2-mode-hide-overlay)
10609 (js2-mode-reset-timer))
10610
10611 (defun js2-reparse (&optional force)
10612 "Re-parse current buffer after user finishes some data entry.
10613 If we get any user input while parsing, including cursor motion,
10614 we discard the parse and reschedule it. If FORCE is nil, then the
10615 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10616 (let (time
10617 interrupted-p
10618 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10619 (unless js2-mode-parsing
10620 (setq js2-mode-parsing t)
10621 (unwind-protect
10622 (when (or js2-mode-buffer-dirty-p force)
10623 (js2-remove-overlays)
10624 (with-silent-modifications
10625 (setq js2-mode-buffer-dirty-p nil
10626 js2-mode-fontifications nil
10627 js2-mode-deferred-properties nil)
10628 (if js2-mode-verbose-parse-p
10629 (message "parsing..."))
10630 (setq time
10631 (js2-time
10632 (setq interrupted-p
10633 (catch 'interrupted
10634 (js2-parse)
10635 ;; if parsing is interrupted, comments and regex
10636 ;; literals stay ignored by `parse-partial-sexp'
10637 (remove-text-properties (point-min) (point-max)
10638 '(syntax-table))
10639 (js2-mode-apply-deferred-properties)
10640 (js2-mode-remove-suppressed-warnings)
10641 (js2-mode-show-warnings)
10642 (js2-mode-show-errors)
10643 (if (>= js2-highlight-level 1)
10644 (js2-highlight-jsdoc js2-mode-ast))
10645 nil))))
10646 (if interrupted-p
10647 (progn
10648 ;; unfinished parse => try again
10649 (setq js2-mode-buffer-dirty-p t)
10650 (js2-mode-reset-timer))
10651 (if js2-mode-verbose-parse-p
10652 (message "Parse time: %s" time)))))
10653 (setq js2-mode-parsing nil)
10654 (unless interrupted-p
10655 (setq js2-mode-parse-timer nil))))))
10656
10657 (defun js2-mode-show-node (event)
10658 "Debugging aid: highlight selected AST node on mouse click."
10659 (interactive "e")
10660 (mouse-set-point event)
10661 (setq deactivate-mark t)
10662 (when js2-mode-show-overlay
10663 (let ((node (js2-node-at-point))
10664 beg end)
10665 (if (null node)
10666 (message "No node found at location %s" (point))
10667 (setq beg (js2-node-abs-pos node)
10668 end (+ beg (js2-node-len node)))
10669 (if js2-mode-node-overlay
10670 (move-overlay js2-mode-node-overlay beg end)
10671 (setq js2-mode-node-overlay (make-overlay beg end))
10672 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10673 (with-silent-modifications
10674 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10675 (message "%s, parent: %s"
10676 (js2-node-short-name node)
10677 (if (js2-node-parent node)
10678 (js2-node-short-name (js2-node-parent node))
10679 "nil"))))))
10680
10681 (defun js2-mode-hide-overlay (&optional _p1 p2)
10682 "Remove the debugging overlay when the point moves.
10683 P1 and P2 are the old and new values of point, respectively."
10684 (when js2-mode-node-overlay
10685 (let ((beg (overlay-start js2-mode-node-overlay))
10686 (end (overlay-end js2-mode-node-overlay)))
10687 ;; Sometimes we're called spuriously.
10688 (unless (and p2
10689 (>= p2 beg)
10690 (<= p2 end))
10691 (with-silent-modifications
10692 (remove-text-properties beg end '(point-left nil)))
10693 (delete-overlay js2-mode-node-overlay)
10694 (setq js2-mode-node-overlay nil)))))
10695
10696 (defun js2-mode-reset ()
10697 "Debugging helper: reset everything."
10698 (interactive)
10699 (js2-mode-exit)
10700 (js2-mode))
10701
10702 (defun js2-mode-show-warn-or-err (e face)
10703 "Highlight a warning or error E with FACE.
10704 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10705 The last element is optional. When present, use instead of FACE."
10706 (let* ((key (first e))
10707 (beg (second e))
10708 (end (+ beg (third e)))
10709 ;; Don't inadvertently go out of bounds.
10710 (beg (max (point-min) (min beg (point-max))))
10711 (end (max (point-min) (min end (point-max))))
10712 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10713 (ovl (make-overlay beg end)))
10714 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10715 (overlay-put ovl 'js2-error t)
10716 (put-text-property beg end 'help-echo (js2-get-msg key))
10717 (put-text-property beg end 'point-entered #'js2-echo-error)))
10718
10719 (defun js2-remove-overlays ()
10720 "Remove overlays from buffer that have a `js2-error' property."
10721 (let ((beg (point-min))
10722 (end (point-max)))
10723 (save-excursion
10724 (dolist (o (overlays-in beg end))
10725 (when (overlay-get o 'js2-error)
10726 (delete-overlay o))))))
10727
10728 (defun js2-error-at-point (&optional pos)
10729 "Return non-nil if there's an error overlay at POS.
10730 Defaults to point."
10731 (loop with pos = (or pos (point))
10732 for o in (overlays-at pos)
10733 thereis (overlay-get o 'js2-error)))
10734
10735 (defun js2-mode-apply-deferred-properties ()
10736 "Apply fontifications and other text properties recorded during parsing."
10737 (when (plusp js2-highlight-level)
10738 ;; We defer clearing faces as long as possible to eliminate flashing.
10739 (js2-clear-face (point-min) (point-max))
10740 ;; Have to reverse the recorded fontifications list so that errors
10741 ;; and warnings overwrite the normal fontifications.
10742 (dolist (f (nreverse js2-mode-fontifications))
10743 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10744 (setq js2-mode-fontifications nil))
10745 (dolist (p js2-mode-deferred-properties)
10746 (apply #'put-text-property p))
10747 (setq js2-mode-deferred-properties nil))
10748
10749 (defun js2-mode-show-errors ()
10750 "Highlight syntax errors."
10751 (when js2-mode-show-parse-errors
10752 (dolist (e (js2-ast-root-errors js2-mode-ast))
10753 (js2-mode-show-warn-or-err e 'js2-error))))
10754
10755 (defun js2-mode-remove-suppressed-warnings ()
10756 "Take suppressed warnings out of the AST warnings list.
10757 This ensures that the counts and `next-error' are correct."
10758 (setf (js2-ast-root-warnings js2-mode-ast)
10759 (js2-delete-if
10760 (lambda (e)
10761 (let ((key (caar e)))
10762 (or
10763 (and (not js2-strict-trailing-comma-warning)
10764 (string-match "trailing\\.comma" key))
10765 (and (not js2-strict-cond-assign-warning)
10766 (string= key "msg.equal.as.assign"))
10767 (and js2-missing-semi-one-line-override
10768 (string= key "msg.missing.semi")
10769 (let* ((beg (second e))
10770 (node (js2-node-at-point beg))
10771 (fn (js2-mode-find-parent-fn node))
10772 (body (and fn (js2-function-node-body fn)))
10773 (lc (and body (js2-node-abs-pos body)))
10774 (rc (and lc (+ lc (js2-node-len body)))))
10775 (and fn
10776 (or (null body)
10777 (save-excursion
10778 (goto-char beg)
10779 (and (js2-same-line lc)
10780 (js2-same-line rc))))))))))
10781 (js2-ast-root-warnings js2-mode-ast))))
10782
10783 (defun js2-mode-show-warnings ()
10784 "Highlight strict-mode warnings."
10785 (when js2-mode-show-strict-warnings
10786 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10787 (js2-mode-show-warn-or-err e 'js2-warning))))
10788
10789 (defun js2-echo-error (_old-point new-point)
10790 "Called by point-motion hooks."
10791 (let ((msg (get-text-property new-point 'help-echo)))
10792 (when (and (stringp msg)
10793 (not (active-minibuffer-window))
10794 (not (current-message)))
10795 (message msg))))
10796
10797 (defalias 'js2-echo-help #'js2-echo-error)
10798
10799 (defun js2-line-break (&optional _soft)
10800 "Break line at point and indent, continuing comment if within one.
10801 If inside a string, and `js2-concat-multiline-strings' is not
10802 nil, turn it into concatenation."
10803 (interactive)
10804 (let ((parse-status (syntax-ppss)))
10805 (cond
10806 ;; Check if we're inside a string.
10807 ((nth 3 parse-status)
10808 (if js2-concat-multiline-strings
10809 (js2-mode-split-string parse-status)
10810 (insert "\n")))
10811 ;; Check if inside a block comment.
10812 ((nth 4 parse-status)
10813 (js2-mode-extend-comment (nth 8 parse-status)))
10814 (t
10815 (newline-and-indent)))))
10816
10817 (defun js2-mode-split-string (parse-status)
10818 "Turn a newline in mid-string into a string concatenation.
10819 PARSE-STATUS is as documented in `parse-partial-sexp'."
10820 (let* ((quote-char (nth 3 parse-status))
10821 (at-eol (eq js2-concat-multiline-strings 'eol)))
10822 (insert quote-char)
10823 (insert (if at-eol " +\n" "\n"))
10824 (unless at-eol
10825 (insert "+ "))
10826 (js2-indent-line)
10827 (insert quote-char)
10828 (when (eolp)
10829 (insert quote-char)
10830 (backward-char 1))))
10831
10832 (defun js2-mode-extend-comment (start-pos)
10833 "Indent the line and, when inside a comment block, add comment prefix."
10834 (let (star single col first-line needs-close)
10835 (save-excursion
10836 (back-to-indentation)
10837 (when (< (point) start-pos)
10838 (goto-char start-pos))
10839 (cond
10840 ((looking-at "\\*[^/]")
10841 (setq star t
10842 col (current-column)))
10843 ((looking-at "/\\*")
10844 (setq star t
10845 first-line t
10846 col (1+ (current-column))))
10847 ((looking-at "//")
10848 (setq single t
10849 col (current-column)))))
10850 ;; Heuristic for whether we need to close the comment:
10851 ;; if we've got a parse error here, assume it's an unterminated
10852 ;; comment.
10853 (setq needs-close
10854 (or
10855 (eq (get-text-property (1- (point)) 'point-entered)
10856 'js2-echo-error)
10857 ;; The heuristic above doesn't work well when we're
10858 ;; creating a comment and there's another one downstream,
10859 ;; as our parser thinks this one ends at the end of the
10860 ;; next one. (You can have a /* inside a js block comment.)
10861 ;; So just close it if the next non-ws char isn't a *.
10862 (and first-line
10863 (eolp)
10864 (save-excursion
10865 (skip-chars-forward " \t\r\n")
10866 (not (eq (char-after) ?*))))))
10867 (delete-horizontal-space)
10868 (insert "\n")
10869 (cond
10870 (star
10871 (indent-to col)
10872 (insert "* ")
10873 (if (and first-line needs-close)
10874 (save-excursion
10875 (insert "\n")
10876 (indent-to col)
10877 (insert "*/"))))
10878 ((and single
10879 (save-excursion
10880 (and (zerop (forward-line 1))
10881 (looking-at "\\s-*//"))))
10882 (indent-to col)
10883 (insert "// ")))
10884 ;; Don't need to extend the comment after all.
10885 (js2-indent-line)))
10886
10887 (defun js2-beginning-of-line ()
10888 "Toggle point between bol and first non-whitespace char in line.
10889 Also moves past comment delimiters when inside comments."
10890 (interactive)
10891 (let (node)
10892 (cond
10893 ((bolp)
10894 (back-to-indentation))
10895 ((looking-at "//")
10896 (skip-chars-forward "/ \t"))
10897 ((and (eq (char-after) ?*)
10898 (setq node (js2-comment-at-point))
10899 (memq (js2-comment-node-format node) '(jsdoc block))
10900 (save-excursion
10901 (skip-chars-backward " \t")
10902 (bolp)))
10903 (skip-chars-forward "\* \t"))
10904 (t
10905 (goto-char (point-at-bol))))))
10906
10907 (defun js2-end-of-line ()
10908 "Toggle point between eol and last non-whitespace char in line."
10909 (interactive)
10910 (if (eolp)
10911 (skip-chars-backward " \t")
10912 (goto-char (point-at-eol))))
10913
10914 (defun js2-mode-wait-for-parse (callback)
10915 "Invoke CALLBACK when parsing is finished.
10916 If parsing is already finished, calls CALLBACK immediately."
10917 (if (not js2-mode-buffer-dirty-p)
10918 (funcall callback)
10919 (push callback js2-mode-pending-parse-callbacks)
10920 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10921
10922 (defun js2-mode-parse-finished ()
10923 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10924 ;; We can't let errors propagate up, since it prevents the
10925 ;; `js2-parse' method from completing normally and returning
10926 ;; the ast, which makes things mysteriously not work right.
10927 (unwind-protect
10928 (dolist (cb js2-mode-pending-parse-callbacks)
10929 (condition-case err
10930 (funcall cb)
10931 (error (message "%s" err))))
10932 (setq js2-mode-pending-parse-callbacks nil)))
10933
10934 (defun js2-mode-flag-region (from to flag)
10935 "Hide or show text from FROM to TO, according to FLAG.
10936 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10937 Returns the created overlay if FLAG is non-nil."
10938 (remove-overlays from to 'invisible 'js2-outline)
10939 (when flag
10940 (let ((o (make-overlay from to)))
10941 (overlay-put o 'invisible 'js2-outline)
10942 (overlay-put o 'isearch-open-invisible
10943 'js2-isearch-open-invisible)
10944 o)))
10945
10946 ;; Function to be set as an outline-isearch-open-invisible' property
10947 ;; to the overlay that makes the outline invisible (see
10948 ;; `js2-mode-flag-region').
10949 (defun js2-isearch-open-invisible (_overlay)
10950 ;; We rely on the fact that isearch places point on the matched text.
10951 (js2-mode-show-element))
10952
10953 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10954 "Return cons cell of bounds of folding overlay at POS.
10955 Returns nil if not found."
10956 (let ((overlays (overlays-at (or pos (point))))
10957 o)
10958 (while (and overlays
10959 (not o))
10960 (if (overlay-get (car overlays) 'invisible)
10961 (setq o (car overlays))
10962 (setq overlays (cdr overlays))))
10963 (if o
10964 (cons (overlay-start o) (overlay-end o)))))
10965
10966 (defun js2-mode-function-at-point (&optional pos)
10967 "Return the innermost function node enclosing current point.
10968 Returns nil if point is not in a function."
10969 (let ((node (js2-node-at-point pos)))
10970 (while (and node (not (js2-function-node-p node)))
10971 (setq node (js2-node-parent node)))
10972 (if (js2-function-node-p node)
10973 node)))
10974
10975 (defun js2-mode-toggle-element ()
10976 "Hide or show the foldable element at the point."
10977 (interactive)
10978 (let (comment fn pos)
10979 (save-excursion
10980 (cond
10981 ;; /* ... */ comment?
10982 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10983 (if (js2-mode-invisible-overlay-bounds
10984 (setq pos (+ 3 (js2-node-abs-pos comment))))
10985 (progn
10986 (goto-char pos)
10987 (js2-mode-show-element))
10988 (js2-mode-hide-element)))
10989 ;; //-comment?
10990 ((save-excursion
10991 (back-to-indentation)
10992 (looking-at js2-mode-//-comment-re))
10993 (js2-mode-toggle-//-comment))
10994 ;; function?
10995 ((setq fn (js2-mode-function-at-point))
10996 (setq pos (and (js2-function-node-body fn)
10997 (js2-node-abs-pos (js2-function-node-body fn))))
10998 (goto-char (1+ pos))
10999 (if (js2-mode-invisible-overlay-bounds)
11000 (js2-mode-show-element)
11001 (js2-mode-hide-element)))
11002 (t
11003 (message "Nothing at point to hide or show"))))))
11004
11005 (defun js2-mode-hide-element ()
11006 "Fold/hide contents of a block, showing ellipses.
11007 Show the hidden text with \\[js2-mode-show-element]."
11008 (interactive)
11009 (if js2-mode-buffer-dirty-p
11010 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11011 (let (node body beg end)
11012 (cond
11013 ((js2-mode-invisible-overlay-bounds)
11014 (message "already hidden"))
11015 (t
11016 (setq node (js2-node-at-point))
11017 (cond
11018 ((js2-block-comment-p node)
11019 (js2-mode-hide-comment node))
11020 (t
11021 (while (and node (not (js2-function-node-p node)))
11022 (setq node (js2-node-parent node)))
11023 (if (and node
11024 (setq body (js2-function-node-body node)))
11025 (progn
11026 (setq beg (js2-node-abs-pos body)
11027 end (+ beg (js2-node-len body)))
11028 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11029 (message "No collapsable element found at point"))))))))
11030
11031 (defun js2-mode-show-element ()
11032 "Show the hidden element at current point."
11033 (interactive)
11034 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11035 (if bounds
11036 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11037 (message "Nothing to un-hide"))))
11038
11039 (defun js2-mode-show-all ()
11040 "Show all of the text in the buffer."
11041 (interactive)
11042 (js2-mode-flag-region (point-min) (point-max) nil))
11043
11044 (defun js2-mode-toggle-hide-functions ()
11045 (interactive)
11046 (if js2-mode-functions-hidden
11047 (js2-mode-show-functions)
11048 (js2-mode-hide-functions)))
11049
11050 (defun js2-mode-hide-functions ()
11051 "Hides all non-nested function bodies in the buffer.
11052 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11053 to open an individual entry."
11054 (interactive)
11055 (if js2-mode-buffer-dirty-p
11056 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11057 (if (null js2-mode-ast)
11058 (message "Oops - parsing failed")
11059 (setq js2-mode-functions-hidden t)
11060 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11061
11062 (defun js2-mode-function-hider (n endp)
11063 (when (not endp)
11064 (let ((tt (js2-node-type n))
11065 body beg end)
11066 (cond
11067 ((and (= tt js2-FUNCTION)
11068 (setq body (js2-function-node-body n)))
11069 (setq beg (js2-node-abs-pos body)
11070 end (+ beg (js2-node-len body)))
11071 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11072 nil) ; don't process children of function
11073 (t
11074 t))))) ; keep processing other AST nodes
11075
11076 (defun js2-mode-show-functions ()
11077 "Un-hide any folded function bodies in the buffer."
11078 (interactive)
11079 (setq js2-mode-functions-hidden nil)
11080 (save-excursion
11081 (goto-char (point-min))
11082 (while (/= (goto-char (next-overlay-change (point)))
11083 (point-max))
11084 (dolist (o (overlays-at (point)))
11085 (when (and (overlay-get o 'invisible)
11086 (not (overlay-get o 'comment)))
11087 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11088
11089 (defun js2-mode-hide-comment (n)
11090 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11091 3 ; /**
11092 2)) ; /*
11093 (beg (+ (js2-node-abs-pos n) head))
11094 (end (- (+ beg (js2-node-len n)) head 2))
11095 (o (js2-mode-flag-region beg end 'hide)))
11096 (overlay-put o 'comment t)))
11097
11098 (defun js2-mode-toggle-hide-comments ()
11099 "Folds all block comments in the buffer.
11100 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11101 to open an individual entry."
11102 (interactive)
11103 (if js2-mode-comments-hidden
11104 (js2-mode-show-comments)
11105 (js2-mode-hide-comments)))
11106
11107 (defun js2-mode-hide-comments ()
11108 (interactive)
11109 (if js2-mode-buffer-dirty-p
11110 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11111 (if (null js2-mode-ast)
11112 (message "Oops - parsing failed")
11113 (setq js2-mode-comments-hidden t)
11114 (dolist (n (js2-ast-root-comments js2-mode-ast))
11115 (when (js2-block-comment-p n)
11116 (js2-mode-hide-comment n)))
11117 (js2-mode-hide-//-comments)))
11118
11119 (defun js2-mode-extend-//-comment (direction)
11120 "Find start or end of a block of similar //-comment lines.
11121 DIRECTION is -1 to look back, 1 to look forward.
11122 INDENT is the indentation level to match.
11123 Returns the end-of-line position of the furthest adjacent
11124 //-comment line with the same indentation as the current line.
11125 If there is no such matching line, returns current end of line."
11126 (let ((pos (point-at-eol))
11127 (indent (current-indentation)))
11128 (save-excursion
11129 (while (and (zerop (forward-line direction))
11130 (looking-at js2-mode-//-comment-re)
11131 (eq indent (length (match-string 1))))
11132 (setq pos (point-at-eol)))
11133 pos)))
11134
11135 (defun js2-mode-hide-//-comments ()
11136 "Fold adjacent 1-line comments, showing only snippet of first one."
11137 (let (beg end)
11138 (save-excursion
11139 (goto-char (point-min))
11140 (while (re-search-forward js2-mode-//-comment-re nil t)
11141 (setq beg (point)
11142 end (js2-mode-extend-//-comment 1))
11143 (unless (eq beg end)
11144 (overlay-put (js2-mode-flag-region beg end 'hide)
11145 'comment t))
11146 (goto-char end)
11147 (forward-char 1)))))
11148
11149 (defun js2-mode-toggle-//-comment ()
11150 "Fold or un-fold any multi-line //-comment at point.
11151 Caller should have determined that this line starts with a //-comment."
11152 (let* ((beg (point-at-eol))
11153 (end beg))
11154 (save-excursion
11155 (goto-char end)
11156 (if (js2-mode-invisible-overlay-bounds)
11157 (js2-mode-show-element)
11158 ;; else hide the comment
11159 (setq beg (js2-mode-extend-//-comment -1)
11160 end (js2-mode-extend-//-comment 1))
11161 (unless (eq beg end)
11162 (overlay-put (js2-mode-flag-region beg end 'hide)
11163 'comment t))))))
11164
11165 (defun js2-mode-show-comments ()
11166 "Un-hide any hidden comments, leaving other hidden elements alone."
11167 (interactive)
11168 (setq js2-mode-comments-hidden nil)
11169 (save-excursion
11170 (goto-char (point-min))
11171 (while (/= (goto-char (next-overlay-change (point)))
11172 (point-max))
11173 (dolist (o (overlays-at (point)))
11174 (when (overlay-get o 'comment)
11175 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11176
11177 (defun js2-mode-display-warnings-and-errors ()
11178 "Turn on display of warnings and errors."
11179 (interactive)
11180 (setq js2-mode-show-parse-errors t
11181 js2-mode-show-strict-warnings t)
11182 (js2-reparse 'force))
11183
11184 (defun js2-mode-hide-warnings-and-errors ()
11185 "Turn off display of warnings and errors."
11186 (interactive)
11187 (setq js2-mode-show-parse-errors nil
11188 js2-mode-show-strict-warnings nil)
11189 (js2-reparse 'force))
11190
11191 (defun js2-mode-toggle-warnings-and-errors ()
11192 "Toggle the display of warnings and errors.
11193 Some users don't like having warnings/errors reported while they type."
11194 (interactive)
11195 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11196 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11197 (if (called-interactively-p 'any)
11198 (message "warnings and errors %s"
11199 (if js2-mode-show-parse-errors
11200 "enabled"
11201 "disabled")))
11202 (js2-reparse 'force))
11203
11204 (defun js2-mode-customize ()
11205 (interactive)
11206 (customize-group 'js2-mode))
11207
11208 (defun js2-mode-forward-sexp (&optional arg)
11209 "Move forward across one statement or balanced expression.
11210 With ARG, do it that many times. Negative arg -N means
11211 move backward across N balanced expressions."
11212 (interactive "p")
11213 (setq arg (or arg 1))
11214 (save-restriction
11215 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11216 (js2-reparse)
11217 (let (forward-sexp-function
11218 node (start (point)) pos lp rp child)
11219 (cond
11220 ;; backward-sexp
11221 ;; could probably make this better for some cases:
11222 ;; - if in statement block (e.g. function body), go to parent
11223 ;; - infix exprs like (foo in bar) - maybe go to beginning
11224 ;; of infix expr if in the right-side expression?
11225 ((and arg (minusp arg))
11226 (dotimes (_ (- arg))
11227 (js2-backward-sws)
11228 (forward-char -1) ; Enter the node we backed up to.
11229 (when (setq node (js2-node-at-point (point) t))
11230 (setq pos (js2-node-abs-pos node))
11231 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11232 (setq lp (car parens)
11233 rp (cdr parens)))
11234 (when (and lp (> start lp))
11235 (if (and rp (<= start rp))
11236 ;; Between parens, check if there's a child node we can jump.
11237 (when (setq child (js2-node-closest-child node (point) lp t))
11238 (setq pos (js2-node-abs-pos child)))
11239 ;; Before both parens.
11240 (setq pos lp)))
11241 (let ((state (parse-partial-sexp start pos)))
11242 (goto-char (if (not (zerop (car state)))
11243 ;; Stumble at the unbalanced paren if < 0, or
11244 ;; jump a bit further if > 0.
11245 (scan-sexps start -1)
11246 pos))))
11247 (unless pos (goto-char (point-min)))))
11248 (t
11249 ;; forward-sexp
11250 (dotimes (_ arg)
11251 (js2-forward-sws)
11252 (when (setq node (js2-node-at-point (point) t))
11253 (setq pos (js2-node-abs-pos node))
11254 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11255 (setq lp (car parens)
11256 rp (cdr parens)))
11257 (or
11258 (when (and rp (<= start rp))
11259 (if (> start lp)
11260 (when (setq child (js2-node-closest-child node (point) rp))
11261 (setq pos (js2-node-abs-end child)))
11262 (setq pos (1+ rp))))
11263 ;; No parens or child nodes, looks for the end of the curren node.
11264 (incf pos (js2-node-len
11265 (if (js2-expr-stmt-node-p (js2-node-parent node))
11266 ;; Stop after the semicolon.
11267 (js2-node-parent node)
11268 node))))
11269 (let ((state (save-excursion (parse-partial-sexp start pos))))
11270 (goto-char (if (not (zerop (car state)))
11271 (scan-sexps start 1)
11272 pos))))
11273 (unless pos (goto-char (point-max)))))))))
11274
11275 (defun js2-mode-forward-sexp-parens (node abs-pos)
11276 "Return a cons cell with positions of main parens in NODE."
11277 (cond
11278 ((or (js2-array-node-p node)
11279 (js2-object-node-p node)
11280 (js2-comp-node-p node)
11281 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11282 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11283 ((js2-paren-expr-node-p node)
11284 (let ((lp (js2-node-lp node))
11285 (rp (js2-node-rp node)))
11286 (cons (when lp (+ abs-pos lp))
11287 (when rp (+ abs-pos rp)))))))
11288
11289 (defun js2-node-closest-child (parent point limit &optional before)
11290 (let* ((parent-pos (js2-node-abs-pos parent))
11291 (rpoint (- point parent-pos))
11292 (rlimit (- limit parent-pos))
11293 (min (min rpoint rlimit))
11294 (max (max rpoint rlimit))
11295 found)
11296 (catch 'done
11297 (js2-visit-ast
11298 parent
11299 (lambda (node _end-p)
11300 (if (eq node parent)
11301 t
11302 (let ((pos (js2-node-pos node)) ;; Both relative values.
11303 (end (+ (js2-node-pos node) (js2-node-len node))))
11304 (when (and (>= pos min) (<= end max)
11305 (if before (< pos rpoint) (> end rpoint)))
11306 (setq found node))
11307 (when (> end rpoint)
11308 (throw 'done nil)))
11309 nil))))
11310 found))
11311
11312 (defun js2-errors ()
11313 "Return a list of errors found."
11314 (and js2-mode-ast
11315 (js2-ast-root-errors js2-mode-ast)))
11316
11317 (defun js2-warnings ()
11318 "Return a list of warnings found."
11319 (and js2-mode-ast
11320 (js2-ast-root-warnings js2-mode-ast)))
11321
11322 (defun js2-have-errors-p ()
11323 "Return non-nil if any parse errors or warnings were found."
11324 (or (js2-errors) (js2-warnings)))
11325
11326 (defun js2-errors-and-warnings ()
11327 "Return a copy of the concatenated errors and warnings lists.
11328 They are appended: first the errors, then the warnings.
11329 Entries are of the form (MSG BEG END)."
11330 (when js2-mode-ast
11331 (append (js2-ast-root-errors js2-mode-ast)
11332 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11333
11334 (defun js2-next-error (&optional arg reset)
11335 "Move to next parse error.
11336 Typically invoked via \\[next-error].
11337 ARG is the number of errors, forward or backward, to move.
11338 RESET means start over from the beginning."
11339 (interactive "p")
11340 (if (not (or (js2-errors) (js2-warnings)))
11341 (message "No errors")
11342 (when reset
11343 (goto-char (point-min)))
11344 (let* ((errs (js2-errors-and-warnings))
11345 (continue t)
11346 (start (point))
11347 (count (or arg 1))
11348 (backward (minusp count))
11349 (sorter (if backward '> '<))
11350 (stopper (if backward '< '>))
11351 (count (abs count))
11352 all-errs err)
11353 ;; Sort by start position.
11354 (setq errs (sort errs (lambda (e1 e2)
11355 (funcall sorter (second e1) (second e2))))
11356 all-errs errs)
11357 ;; Find nth error with pos > start.
11358 (while (and errs continue)
11359 (when (funcall stopper (cadar errs) start)
11360 (setq err (car errs))
11361 (if (zerop (decf count))
11362 (setq continue nil)))
11363 (setq errs (cdr errs)))
11364 ;; Clear for `js2-echo-error'.
11365 (message nil)
11366 (if err
11367 (goto-char (second err))
11368 ;; Wrap around to first error.
11369 (goto-char (second (car all-errs)))
11370 ;; If we were already on it, echo msg again.
11371 (if (= (point) start)
11372 (js2-echo-error (point) (point)))))))
11373
11374 (defun js2-down-mouse-3 ()
11375 "Make right-click move the point to the click location.
11376 This makes right-click context menu operations a bit more intuitive.
11377 The point will not move if the region is active, however, to avoid
11378 destroying the region selection."
11379 (interactive)
11380 (when (and js2-move-point-on-right-click
11381 (not mark-active))
11382 (let ((e last-input-event))
11383 (ignore-errors
11384 (goto-char (cadadr e))))))
11385
11386 (defun js2-mode-create-imenu-index ()
11387 "Return an alist for `imenu--index-alist'."
11388 ;; This is built up in `js2-parse-record-imenu' during parsing.
11389 (when js2-mode-ast
11390 ;; if we have an ast but no recorder, they're requesting a rescan
11391 (unless js2-imenu-recorder
11392 (js2-reparse 'force))
11393 (prog1
11394 (js2-build-imenu-index)
11395 (setq js2-imenu-recorder nil
11396 js2-imenu-function-map nil))))
11397
11398 (defun js2-mode-find-tag ()
11399 "Replacement for `find-tag-default'.
11400 `find-tag-default' returns a ridiculous answer inside comments."
11401 (let (beg end)
11402 (js2-with-underscore-as-word-syntax
11403 (save-excursion
11404 (if (and (not (looking-at "[[:alnum:]_$]"))
11405 (looking-back "[[:alnum:]_$]"))
11406 (setq beg (progn (forward-word -1) (point))
11407 end (progn (forward-word 1) (point)))
11408 (setq beg (progn (forward-word 1) (point))
11409 end (progn (forward-word -1) (point))))
11410 (replace-regexp-in-string
11411 "[\"']" ""
11412 (buffer-substring-no-properties beg end))))))
11413
11414 (defun js2-mode-forward-sibling ()
11415 "Move to the end of the sibling following point in parent.
11416 Returns non-nil if successful, or nil if there was no following sibling."
11417 (let* ((node (js2-node-at-point))
11418 (parent (js2-mode-find-enclosing-fn node))
11419 sib)
11420 (when (setq sib (js2-node-find-child-after (point) parent))
11421 (goto-char (+ (js2-node-abs-pos sib)
11422 (js2-node-len sib))))))
11423
11424 (defun js2-mode-backward-sibling ()
11425 "Move to the beginning of the sibling node preceding point in parent.
11426 Parent is defined as the enclosing script or function."
11427 (let* ((node (js2-node-at-point))
11428 (parent (js2-mode-find-enclosing-fn node))
11429 sib)
11430 (when (setq sib (js2-node-find-child-before (point) parent))
11431 (goto-char (js2-node-abs-pos sib)))))
11432
11433 (defun js2-beginning-of-defun (&optional arg)
11434 "Go to line on which current function starts, and return t on success.
11435 If we're not in a function or already at the beginning of one, go
11436 to beginning of previous script-level element.
11437 With ARG N, do that N times. If N is negative, move forward."
11438 (setq arg (or arg 1))
11439 (if (plusp arg)
11440 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11441 (when (cond
11442 ((js2-function-node-p parent)
11443 (goto-char (js2-node-abs-pos parent)))
11444 (t
11445 (js2-mode-backward-sibling)))
11446 (if (> arg 1)
11447 (js2-beginning-of-defun (1- arg))
11448 t)))
11449 (when (js2-end-of-defun)
11450 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11451
11452 (defun js2-end-of-defun ()
11453 "Go to the char after the last position of the current function
11454 or script-level element."
11455 (let* ((node (js2-node-at-point))
11456 (parent (or (and (js2-function-node-p node) node)
11457 (js2-node-parent-script-or-fn node)))
11458 script)
11459 (unless (js2-function-node-p parent)
11460 ;; Use current script-level node, or, if none, the next one.
11461 (setq script (or parent node)
11462 parent (js2-node-find-child-before (point) script))
11463 (when (or (null parent)
11464 (>= (point) (+ (js2-node-abs-pos parent)
11465 (js2-node-len parent))))
11466 (setq parent (js2-node-find-child-after (point) script))))
11467 (when parent
11468 (goto-char (+ (js2-node-abs-pos parent)
11469 (js2-node-len parent))))))
11470
11471 (defun js2-mark-defun (&optional allow-extend)
11472 "Put mark at end of this function, point at beginning.
11473 The function marked is the one that contains point.
11474
11475 Interactively, if this command is repeated,
11476 or (in Transient Mark mode) if the mark is active,
11477 it marks the next defun after the ones already marked."
11478 (interactive "p")
11479 (let (extended)
11480 (when (and allow-extend
11481 (or (and (eq last-command this-command) (mark t))
11482 (and transient-mark-mode mark-active)))
11483 (let ((sib (save-excursion
11484 (goto-char (mark))
11485 (if (js2-mode-forward-sibling)
11486 (point)))))
11487 (if sib
11488 (progn
11489 (set-mark sib)
11490 (setq extended t))
11491 ;; no more siblings - try extending to enclosing node
11492 (goto-char (mark t)))))
11493 (when (not extended)
11494 (let ((node (js2-node-at-point (point) t)) ; skip comments
11495 ast fn stmt parent beg end)
11496 (when (js2-ast-root-p node)
11497 (setq ast node
11498 node (or (js2-node-find-child-after (point) node)
11499 (js2-node-find-child-before (point) node))))
11500 ;; only mark whole buffer if we can't find any children
11501 (if (null node)
11502 (setq node ast))
11503 (if (js2-function-node-p node)
11504 (setq parent node)
11505 (setq fn (js2-mode-find-enclosing-fn node)
11506 stmt (if (or (null fn)
11507 (js2-ast-root-p fn))
11508 (js2-mode-find-first-stmt node))
11509 parent (or stmt fn)))
11510 (setq beg (js2-node-abs-pos parent)
11511 end (+ beg (js2-node-len parent)))
11512 (push-mark beg)
11513 (goto-char end)
11514 (exchange-point-and-mark)))))
11515
11516 (defun js2-narrow-to-defun ()
11517 "Narrow to the function enclosing point."
11518 (interactive)
11519 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11520 (fn (if (js2-script-node-p node)
11521 node
11522 (js2-mode-find-enclosing-fn node)))
11523 (beg (js2-node-abs-pos fn)))
11524 (unless (js2-ast-root-p fn)
11525 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11526
11527 (provide 'js2-mode)
11528
11529 ;;; js2-mode.el ends here